• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 Collabora Ltd.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * on the rights to use, copy, modify, merge, publish, distribute, sub
8  * license, and/or sell copies of the Software, and to permit persons to whom
9  * the Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
18  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21  * USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23 
24 #include "zink_resource.h"
25 
26 #include "zink_batch.h"
27 #include "zink_context.h"
28 #include "zink_fence.h"
29 #include "zink_program.h"
30 #include "zink_screen.h"
31 
32 #ifdef VK_USE_PLATFORM_METAL_EXT
33 #include "QuartzCore/CAMetalLayer.h"
34 #endif
35 #include "vulkan/wsi/wsi_common.h"
36 
37 #include "util/slab.h"
38 #include "util/u_blitter.h"
39 #include "util/u_debug.h"
40 #include "util/format/u_format.h"
41 #include "util/u_transfer_helper.h"
42 #include "util/u_inlines.h"
43 #include "util/u_memory.h"
44 #include "util/u_upload_mgr.h"
45 #include "util/os_file.h"
46 #include "frontend/sw_winsys.h"
47 
48 #ifndef _WIN32
49 #define ZINK_USE_DMABUF
50 #endif
51 
52 #ifdef ZINK_USE_DMABUF
53 #include <xf86drm.h>
54 #include "drm-uapi/drm_fourcc.h"
55 #else
56 /* these won't actually be used */
57 #define DRM_FORMAT_MOD_INVALID 0
58 #define DRM_FORMAT_MOD_LINEAR 0
59 #endif
60 
61 
62 static bool
equals_ivci(const void * a,const void * b)63 equals_ivci(const void *a, const void *b)
64 {
65    return memcmp(a, b, sizeof(VkImageViewCreateInfo)) == 0;
66 }
67 
68 static bool
equals_bvci(const void * a,const void * b)69 equals_bvci(const void *a, const void *b)
70 {
71    return memcmp(a, b, sizeof(VkBufferViewCreateInfo)) == 0;
72 }
73 
74 static void
75 zink_transfer_flush_region(struct pipe_context *pctx,
76                            struct pipe_transfer *ptrans,
77                            const struct pipe_box *box);
78 
79 void
debug_describe_zink_resource_object(char * buf,const struct zink_resource_object * ptr)80 debug_describe_zink_resource_object(char *buf, const struct zink_resource_object *ptr)
81 {
82    sprintf(buf, "zink_resource_object");
83 }
84 
85 void
zink_destroy_resource_object(struct zink_screen * screen,struct zink_resource_object * obj)86 zink_destroy_resource_object(struct zink_screen *screen, struct zink_resource_object *obj)
87 {
88    if (obj->is_buffer) {
89       util_dynarray_foreach(&obj->tmp, VkBuffer, buffer)
90          VKSCR(DestroyBuffer)(screen->dev, *buffer, NULL);
91       VKSCR(DestroyBuffer)(screen->dev, obj->buffer, NULL);
92    } else {
93       VKSCR(DestroyImage)(screen->dev, obj->image, NULL);
94    }
95 
96    util_dynarray_fini(&obj->tmp);
97    zink_descriptor_set_refs_clear(&obj->desc_set_refs, obj);
98    zink_bo_unref(screen, obj->bo);
99    FREE(obj);
100 }
101 
102 static void
zink_resource_destroy(struct pipe_screen * pscreen,struct pipe_resource * pres)103 zink_resource_destroy(struct pipe_screen *pscreen,
104                       struct pipe_resource *pres)
105 {
106    struct zink_screen *screen = zink_screen(pscreen);
107    struct zink_resource *res = zink_resource(pres);
108    if (pres->target == PIPE_BUFFER) {
109       util_range_destroy(&res->valid_buffer_range);
110       util_idalloc_mt_free(&screen->buffer_ids, res->base.buffer_id_unique);
111       assert(!_mesa_hash_table_num_entries(&res->bufferview_cache));
112       simple_mtx_destroy(&res->bufferview_mtx);
113    } else {
114       assert(!_mesa_hash_table_num_entries(&res->surface_cache));
115       simple_mtx_destroy(&res->surface_mtx);
116    }
117    /* no need to do anything for the caches, these objects own the resource lifetimes */
118 
119    zink_resource_object_reference(screen, &res->obj, NULL);
120    zink_resource_object_reference(screen, &res->scanout_obj, NULL);
121    threaded_resource_deinit(pres);
122    ralloc_free(res);
123 }
124 
125 static VkImageAspectFlags
aspect_from_format(enum pipe_format fmt)126 aspect_from_format(enum pipe_format fmt)
127 {
128    if (util_format_is_depth_or_stencil(fmt)) {
129       VkImageAspectFlags aspect = 0;
130       const struct util_format_description *desc = util_format_description(fmt);
131       if (util_format_has_depth(desc))
132          aspect |= VK_IMAGE_ASPECT_DEPTH_BIT;
133       if (util_format_has_stencil(desc))
134          aspect |= VK_IMAGE_ASPECT_STENCIL_BIT;
135       return aspect;
136    } else
137      return VK_IMAGE_ASPECT_COLOR_BIT;
138 }
139 
140 static VkBufferCreateInfo
create_bci(struct zink_screen * screen,const struct pipe_resource * templ,unsigned bind)141 create_bci(struct zink_screen *screen, const struct pipe_resource *templ, unsigned bind)
142 {
143    VkBufferCreateInfo bci;
144    bci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
145    bci.pNext = NULL;
146    bci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
147    bci.queueFamilyIndexCount = 0;
148    bci.pQueueFamilyIndices = NULL;
149    bci.size = templ->width0;
150    bci.flags = 0;
151    assert(bci.size > 0);
152 
153    bci.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
154                VK_BUFFER_USAGE_TRANSFER_DST_BIT |
155                VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
156 
157    bci.usage |= VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT |
158                 VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT |
159                 VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
160                 VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
161                 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
162                 VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT |
163                 VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT;
164 
165    if (bind & PIPE_BIND_SHADER_IMAGE)
166       bci.usage |= VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
167 
168    if (templ->flags & PIPE_RESOURCE_FLAG_SPARSE)
169       bci.flags |= VK_BUFFER_CREATE_SPARSE_BINDING_BIT;
170    return bci;
171 }
172 
173 static bool
check_ici(struct zink_screen * screen,VkImageCreateInfo * ici,uint64_t modifier)174 check_ici(struct zink_screen *screen, VkImageCreateInfo *ici, uint64_t modifier)
175 {
176    VkImageFormatProperties image_props;
177    VkResult ret;
178    assert(modifier == DRM_FORMAT_MOD_INVALID ||
179           (VKSCR(GetPhysicalDeviceImageFormatProperties2) && screen->info.have_EXT_image_drm_format_modifier));
180    if (VKSCR(GetPhysicalDeviceImageFormatProperties2)) {
181       VkImageFormatProperties2 props2;
182       props2.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
183       props2.pNext = NULL;
184       VkPhysicalDeviceImageFormatInfo2 info;
185       info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
186       info.format = ici->format;
187       info.type = ici->imageType;
188       info.tiling = ici->tiling;
189       info.usage = ici->usage;
190       info.flags = ici->flags;
191 
192       VkPhysicalDeviceImageDrmFormatModifierInfoEXT mod_info;
193       if (modifier != DRM_FORMAT_MOD_INVALID) {
194          mod_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT;
195          mod_info.pNext = NULL;
196          mod_info.drmFormatModifier = modifier;
197          mod_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
198          mod_info.queueFamilyIndexCount = 0;
199          info.pNext = &mod_info;
200       } else
201          info.pNext = NULL;
202 
203       ret = VKSCR(GetPhysicalDeviceImageFormatProperties2)(screen->pdev, &info, &props2);
204       image_props = props2.imageFormatProperties;
205    } else
206       ret = VKSCR(GetPhysicalDeviceImageFormatProperties)(screen->pdev, ici->format, ici->imageType,
207                                                    ici->tiling, ici->usage, ici->flags, &image_props);
208    return ret == VK_SUCCESS;
209 }
210 
211 static VkImageUsageFlags
get_image_usage_for_feats(struct zink_screen * screen,VkFormatFeatureFlags feats,const struct pipe_resource * templ,unsigned bind)212 get_image_usage_for_feats(struct zink_screen *screen, VkFormatFeatureFlags feats, const struct pipe_resource *templ, unsigned bind)
213 {
214    VkImageUsageFlags usage = 0;
215    if (bind & ZINK_BIND_TRANSIENT)
216       usage |= VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
217    else {
218       /* sadly, gallium doesn't let us know if it'll ever need this, so we have to assume */
219       if (feats & VK_FORMAT_FEATURE_TRANSFER_SRC_BIT)
220          usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
221       if (feats & VK_FORMAT_FEATURE_TRANSFER_DST_BIT)
222          usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
223       if (feats & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT && (bind & (PIPE_BIND_LINEAR | PIPE_BIND_SHARED)) != (PIPE_BIND_LINEAR | PIPE_BIND_SHARED))
224          usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
225 
226       if ((feats & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) && (bind & PIPE_BIND_SHADER_IMAGE)) {
227          assert(templ->nr_samples <= 1 || screen->info.feats.features.shaderStorageImageMultisample);
228          usage |= VK_IMAGE_USAGE_STORAGE_BIT;
229       }
230    }
231 
232    if (bind & PIPE_BIND_RENDER_TARGET) {
233       if (feats & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) {
234          usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
235          if ((bind & (PIPE_BIND_LINEAR | PIPE_BIND_SHARED)) != (PIPE_BIND_LINEAR | PIPE_BIND_SHARED))
236             usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
237       } else
238          return 0;
239    }
240 
241    if (bind & PIPE_BIND_DEPTH_STENCIL) {
242       if (feats & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
243          usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
244       else
245          return 0;
246    /* this is unlikely to occur and has been included for completeness */
247    } else if (bind & PIPE_BIND_SAMPLER_VIEW && !(usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) {
248       if (feats & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)
249          usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
250       else
251          return 0;
252    }
253 
254    if (templ->flags & PIPE_RESOURCE_FLAG_SPARSE)
255       usage |= VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT;
256 
257    if (bind & PIPE_BIND_STREAM_OUTPUT)
258       usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
259 
260    return usage;
261 }
262 
263 static VkFormatFeatureFlags
find_modifier_feats(const struct zink_modifier_prop * prop,uint64_t modifier,uint64_t * mod)264 find_modifier_feats(const struct zink_modifier_prop *prop, uint64_t modifier, uint64_t *mod)
265 {
266    for (unsigned j = 0; j < prop->drmFormatModifierCount; j++) {
267       if (prop->pDrmFormatModifierProperties[j].drmFormatModifier == modifier) {
268          *mod = modifier;
269          return prop->pDrmFormatModifierProperties[j].drmFormatModifierTilingFeatures;
270       }
271    }
272    return 0;
273 }
274 
275 static VkImageUsageFlags
get_image_usage(struct zink_screen * screen,VkImageCreateInfo * ici,const struct pipe_resource * templ,unsigned bind,unsigned modifiers_count,const uint64_t * modifiers,uint64_t * mod)276 get_image_usage(struct zink_screen *screen, VkImageCreateInfo *ici, const struct pipe_resource *templ, unsigned bind, unsigned modifiers_count, const uint64_t *modifiers, uint64_t *mod)
277 {
278    VkImageTiling tiling = ici->tiling;
279    *mod = DRM_FORMAT_MOD_INVALID;
280    if (modifiers_count) {
281       bool have_linear = false;
282       const struct zink_modifier_prop *prop = &screen->modifier_props[templ->format];
283       assert(tiling == VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT);
284       for (unsigned i = 0; i < modifiers_count; i++) {
285          if (modifiers[i] == DRM_FORMAT_MOD_LINEAR) {
286             have_linear = true;
287             continue;
288          }
289          VkFormatFeatureFlags feats = find_modifier_feats(prop, modifiers[i], mod);
290          if (feats) {
291             VkImageUsageFlags usage = get_image_usage_for_feats(screen, feats, templ, bind);
292             if (usage) {
293                ici->usage = usage;
294                if (check_ici(screen, ici, *mod))
295                   return usage;
296             }
297          }
298       }
299       /* only try linear if no other options available */
300       if (have_linear) {
301          VkFormatFeatureFlags feats = find_modifier_feats(prop, DRM_FORMAT_MOD_LINEAR, mod);
302          if (feats) {
303             VkImageUsageFlags usage = get_image_usage_for_feats(screen, feats, templ, bind);
304             if (usage) {
305                ici->usage = usage;
306                if (check_ici(screen, ici, *mod))
307                   return usage;
308             }
309          }
310       }
311    } else
312    {
313       VkFormatProperties props = screen->format_props[templ->format];
314       VkFormatFeatureFlags feats = tiling == VK_IMAGE_TILING_LINEAR ? props.linearTilingFeatures : props.optimalTilingFeatures;
315       VkImageUsageFlags usage = get_image_usage_for_feats(screen, feats, templ, bind);
316       if (usage) {
317          ici->usage = usage;
318          if (check_ici(screen, ici, *mod))
319             return usage;
320       }
321    }
322    *mod = DRM_FORMAT_MOD_INVALID;
323    return 0;
324 }
325 
326 static uint64_t
create_ici(struct zink_screen * screen,VkImageCreateInfo * ici,const struct pipe_resource * templ,bool dmabuf,unsigned bind,unsigned modifiers_count,const uint64_t * modifiers,bool * success)327 create_ici(struct zink_screen *screen, VkImageCreateInfo *ici, const struct pipe_resource *templ, bool dmabuf, unsigned bind, unsigned modifiers_count, const uint64_t *modifiers, bool *success)
328 {
329    ici->sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
330    ici->pNext = NULL;
331    ici->flags = modifiers_count || dmabuf || bind & (PIPE_BIND_SCANOUT | PIPE_BIND_DEPTH_STENCIL) ? 0 : VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
332    ici->usage = 0;
333    ici->queueFamilyIndexCount = 0;
334 
335    switch (templ->target) {
336    case PIPE_TEXTURE_1D:
337    case PIPE_TEXTURE_1D_ARRAY:
338       ici->imageType = VK_IMAGE_TYPE_1D;
339       break;
340 
341    case PIPE_TEXTURE_CUBE:
342    case PIPE_TEXTURE_CUBE_ARRAY:
343    case PIPE_TEXTURE_2D:
344    case PIPE_TEXTURE_2D_ARRAY:
345    case PIPE_TEXTURE_RECT:
346       ici->imageType = VK_IMAGE_TYPE_2D;
347       break;
348 
349    case PIPE_TEXTURE_3D:
350       ici->imageType = VK_IMAGE_TYPE_3D;
351       ici->flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
352       break;
353 
354    case PIPE_BUFFER:
355       unreachable("PIPE_BUFFER should already be handled");
356 
357    default:
358       unreachable("Unknown target");
359    }
360 
361    if (screen->info.have_EXT_sample_locations &&
362        bind & PIPE_BIND_DEPTH_STENCIL &&
363        util_format_has_depth(util_format_description(templ->format)))
364       ici->flags |= VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT;
365 
366    ici->format = zink_get_format(screen, templ->format);
367    ici->extent.width = templ->width0;
368    ici->extent.height = templ->height0;
369    ici->extent.depth = templ->depth0;
370    ici->mipLevels = templ->last_level + 1;
371    ici->arrayLayers = MAX2(templ->array_size, 1);
372    ici->samples = templ->nr_samples ? templ->nr_samples : VK_SAMPLE_COUNT_1_BIT;
373    ici->tiling = modifiers_count ? VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT : bind & PIPE_BIND_LINEAR ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
374    ici->sharingMode = VK_SHARING_MODE_EXCLUSIVE;
375    ici->initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
376 
377    /* sampleCounts will be set to VK_SAMPLE_COUNT_1_BIT if at least one of the following conditions is true:
378     * - flags contains VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT
379     *
380     * 44.1.1. Supported Sample Counts
381     */
382    bool want_cube = ici->samples == 1 &&
383                     (templ->target == PIPE_TEXTURE_CUBE ||
384                     templ->target == PIPE_TEXTURE_CUBE_ARRAY ||
385                     (templ->target == PIPE_TEXTURE_2D_ARRAY && ici->extent.width == ici->extent.height && ici->arrayLayers >= 6));
386 
387    if (templ->target == PIPE_TEXTURE_CUBE)
388       ici->arrayLayers *= 6;
389 
390    if (templ->usage == PIPE_USAGE_STAGING &&
391        templ->format != PIPE_FORMAT_B4G4R4A4_UNORM &&
392        templ->format != PIPE_FORMAT_B4G4R4A4_UINT)
393       ici->tiling = VK_IMAGE_TILING_LINEAR;
394 
395    bool first = true;
396    bool tried[2] = {0};
397    uint64_t mod = DRM_FORMAT_MOD_INVALID;
398    while (!ici->usage) {
399       if (!first) {
400          switch (ici->tiling) {
401          case VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT:
402             ici->tiling = VK_IMAGE_TILING_OPTIMAL;
403             modifiers_count = 0;
404             break;
405          case VK_IMAGE_TILING_OPTIMAL:
406             ici->tiling = VK_IMAGE_TILING_LINEAR;
407             break;
408          case VK_IMAGE_TILING_LINEAR:
409             if (bind & PIPE_BIND_LINEAR) {
410                *success = false;
411                return DRM_FORMAT_MOD_INVALID;
412             }
413             ici->tiling = VK_IMAGE_TILING_OPTIMAL;
414             break;
415          default:
416             unreachable("unhandled tiling mode");
417          }
418          if (tried[ici->tiling]) {
419             *success = false;
420                return DRM_FORMAT_MOD_INVALID;
421          }
422       }
423       ici->usage = get_image_usage(screen, ici, templ, bind, modifiers_count, modifiers, &mod);
424       first = false;
425       if (ici->tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT)
426          tried[ici->tiling] = true;
427    }
428    if (want_cube) {
429       ici->flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
430       if (get_image_usage(screen, ici, templ, bind, modifiers_count, modifiers, &mod) != ici->usage)
431          ici->flags &= ~VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
432    }
433 
434    *success = true;
435    return mod;
436 }
437 
438 static struct zink_resource_object *
resource_object_create(struct zink_screen * screen,const struct pipe_resource * templ,struct winsys_handle * whandle,bool * optimal_tiling,const uint64_t * modifiers,int modifiers_count)439 resource_object_create(struct zink_screen *screen, const struct pipe_resource *templ, struct winsys_handle *whandle, bool *optimal_tiling,
440                        const uint64_t *modifiers, int modifiers_count)
441 {
442    struct zink_resource_object *obj = CALLOC_STRUCT(zink_resource_object);
443    if (!obj)
444       return NULL;
445 
446    VkMemoryRequirements reqs;
447    VkMemoryPropertyFlags flags;
448    bool need_dedicated = false;
449    bool shared = templ->bind & PIPE_BIND_SHARED;
450    VkExternalMemoryHandleTypeFlags export_types = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
451 
452    VkExternalMemoryHandleTypeFlags external = 0;
453    if (whandle) {
454       if (whandle->type == WINSYS_HANDLE_TYPE_FD) {
455          external = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
456          export_types |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
457       } else
458          unreachable("unknown handle type");
459    }
460 
461    /* TODO: remove linear for wsi */
462    bool scanout = templ->bind & PIPE_BIND_SCANOUT;
463 
464    pipe_reference_init(&obj->reference, 1);
465    util_dynarray_init(&obj->tmp, NULL);
466    util_dynarray_init(&obj->desc_set_refs.refs, NULL);
467    if (templ->target == PIPE_BUFFER) {
468       VkBufferCreateInfo bci = create_bci(screen, templ, templ->bind);
469 
470       if (VKSCR(CreateBuffer)(screen->dev, &bci, NULL, &obj->buffer) != VK_SUCCESS) {
471          debug_printf("vkCreateBuffer failed\n");
472          goto fail1;
473       }
474 
475       VKSCR(GetBufferMemoryRequirements)(screen->dev, obj->buffer, &reqs);
476       if (templ->usage == PIPE_USAGE_STAGING)
477          flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
478       else if (templ->usage == PIPE_USAGE_STREAM)
479          flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
480       else if (templ->usage == PIPE_USAGE_IMMUTABLE)
481          flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
482       else
483          flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
484       obj->is_buffer = true;
485       obj->transfer_dst = true;
486    } else {
487       bool winsys_modifier = shared && whandle && whandle->modifier != DRM_FORMAT_MOD_INVALID;
488       const uint64_t *ici_modifiers = winsys_modifier ? &whandle->modifier : modifiers;
489       unsigned ici_modifier_count = winsys_modifier ? 1 : modifiers_count;
490       bool success = false;
491       VkImageCreateInfo ici;
492       uint64_t mod = create_ici(screen, &ici, templ, !!external, templ->bind, ici_modifier_count, ici_modifiers, &success);
493       VkExternalMemoryImageCreateInfo emici;
494       VkImageDrmFormatModifierExplicitCreateInfoEXT idfmeci;
495       VkImageDrmFormatModifierListCreateInfoEXT idfmlci;
496       if (!success)
497          goto fail1;
498 
499       if (shared || external) {
500          emici.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
501          emici.pNext = NULL;
502          emici.handleTypes = export_types;
503          ici.pNext = &emici;
504 
505          assert(ici.tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT || mod != DRM_FORMAT_MOD_INVALID);
506          if (winsys_modifier && ici.tiling == VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT) {
507             assert(mod == whandle->modifier);
508             idfmeci.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT;
509             idfmeci.pNext = ici.pNext;
510             idfmeci.drmFormatModifier = mod;
511 
512             /* TODO: store these values from other planes in their
513              * respective zink_resource, and walk the next-pointers to
514              * build up the planar array here instead.
515              */
516             assert(util_format_get_num_planes(templ->format) == 1);
517             idfmeci.drmFormatModifierPlaneCount = 1;
518             VkSubresourceLayout plane_layout = {
519                .offset = whandle->offset,
520                .size = 0,
521                .rowPitch = whandle->stride,
522                .arrayPitch = 0,
523                .depthPitch = 0,
524             };
525             idfmeci.pPlaneLayouts = &plane_layout;
526 
527             ici.pNext = &idfmeci;
528          } else if (ici.tiling == VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT) {
529             idfmlci.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT;
530             idfmlci.pNext = ici.pNext;
531             idfmlci.drmFormatModifierCount = modifiers_count;
532             idfmlci.pDrmFormatModifiers = modifiers;
533             ici.pNext = &idfmlci;
534          } else if (ici.tiling == VK_IMAGE_TILING_OPTIMAL) {
535             // TODO: remove for wsi
536             if (!external)
537                ici.pNext = NULL;
538             scanout = false;
539             shared = false;
540          }
541       }
542 
543       if (optimal_tiling)
544          *optimal_tiling = ici.tiling == VK_IMAGE_TILING_OPTIMAL;
545 
546       if (ici.usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT)
547          obj->transfer_dst = true;
548 
549       if (ici.tiling == VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT)
550          obj->modifier_aspect = VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT;
551 
552       struct wsi_image_create_info image_wsi_info = {
553          VK_STRUCTURE_TYPE_WSI_IMAGE_CREATE_INFO_MESA,
554          NULL,
555          .scanout = true,
556       };
557 
558       if ((screen->needs_mesa_wsi || screen->needs_mesa_flush_wsi) && scanout &&
559           ici.tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT) {
560          image_wsi_info.pNext = ici.pNext;
561          ici.pNext = &image_wsi_info;
562       }
563 
564       VkResult result = VKSCR(CreateImage)(screen->dev, &ici, NULL, &obj->image);
565       if (result != VK_SUCCESS) {
566          debug_printf("vkCreateImage failed\n");
567          goto fail1;
568       }
569 
570       if (VKSCR(GetImageMemoryRequirements2)) {
571          VkMemoryRequirements2 req2;
572          req2.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2;
573          VkImageMemoryRequirementsInfo2 info2;
574          info2.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2;
575          info2.pNext = NULL;
576          info2.image = obj->image;
577          VkMemoryDedicatedRequirements ded;
578          ded.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS;
579          ded.pNext = NULL;
580          req2.pNext = &ded;
581          VKSCR(GetImageMemoryRequirements2)(screen->dev, &info2, &req2);
582          memcpy(&reqs, &req2.memoryRequirements, sizeof(VkMemoryRequirements));
583          need_dedicated = ded.prefersDedicatedAllocation || ded.requiresDedicatedAllocation;
584       } else {
585          VKSCR(GetImageMemoryRequirements)(screen->dev, obj->image, &reqs);
586       }
587       if (templ->usage == PIPE_USAGE_STAGING && ici.tiling == VK_IMAGE_TILING_LINEAR)
588         flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
589       else
590         flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
591 
592       obj->vkflags = ici.flags;
593       obj->vkusage = ici.usage;
594    }
595    obj->alignment = reqs.alignment;
596 
597    if (templ->flags & PIPE_RESOURCE_FLAG_MAP_COHERENT || templ->usage == PIPE_USAGE_DYNAMIC)
598       flags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
599    else if (!(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) &&
600             templ->usage == PIPE_USAGE_STAGING)
601       flags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
602 
603    if (templ->bind & ZINK_BIND_TRANSIENT)
604       flags |= VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT;
605 
606    VkMemoryAllocateInfo mai;
607    enum zink_alloc_flag aflags = templ->flags & PIPE_RESOURCE_FLAG_SPARSE ? ZINK_ALLOC_SPARSE : 0;
608    mai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
609    mai.pNext = NULL;
610    mai.allocationSize = reqs.size;
611    enum zink_heap heap = zink_heap_from_domain_flags(flags, aflags);
612    mai.memoryTypeIndex = screen->heap_map[heap];
613    if (unlikely(!(reqs.memoryTypeBits & BITFIELD_BIT(mai.memoryTypeIndex)))) {
614       /* not valid based on reqs; demote to more compatible type */
615       switch (heap) {
616       case ZINK_HEAP_DEVICE_LOCAL_VISIBLE:
617          heap = ZINK_HEAP_DEVICE_LOCAL;
618          break;
619       case ZINK_HEAP_HOST_VISIBLE_CACHED:
620          heap = ZINK_HEAP_HOST_VISIBLE_COHERENT;
621          break;
622       default:
623          break;
624       }
625       mai.memoryTypeIndex = screen->heap_map[heap];
626       assert(reqs.memoryTypeBits & BITFIELD_BIT(mai.memoryTypeIndex));
627    }
628 
629    VkMemoryType mem_type = screen->info.mem_props.memoryTypes[mai.memoryTypeIndex];
630    obj->coherent = mem_type.propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
631    if (!(templ->flags & PIPE_RESOURCE_FLAG_SPARSE))
632       obj->host_visible = mem_type.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
633 
634    VkMemoryDedicatedAllocateInfo ded_alloc_info = {
635       .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
636       .pNext = mai.pNext,
637       .image = obj->image,
638       .buffer = VK_NULL_HANDLE,
639    };
640 
641    if (screen->info.have_KHR_dedicated_allocation && need_dedicated) {
642       ded_alloc_info.pNext = mai.pNext;
643       mai.pNext = &ded_alloc_info;
644    }
645 
646    VkExportMemoryAllocateInfo emai;
647    if (templ->bind & PIPE_BIND_SHARED && shared) {
648       emai.sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO;
649       emai.handleTypes = export_types;
650 
651       emai.pNext = mai.pNext;
652       mai.pNext = &emai;
653    }
654 
655    VkImportMemoryFdInfoKHR imfi = {
656       VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,
657       NULL,
658    };
659 
660    if (whandle) {
661       imfi.pNext = NULL;
662       imfi.handleType = external;
663       imfi.fd = os_dupfd_cloexec(whandle->handle);
664       if (imfi.fd < 0) {
665          mesa_loge("ZINK: failed to dup dmabuf fd: %s\n", strerror(errno));
666          goto fail1;
667       }
668 
669       imfi.pNext = mai.pNext;
670       mai.pNext = &imfi;
671    }
672 
673    struct wsi_memory_allocate_info memory_wsi_info = {
674       VK_STRUCTURE_TYPE_WSI_MEMORY_ALLOCATE_INFO_MESA,
675       NULL,
676    };
677 
678    if (screen->needs_mesa_wsi && scanout) {
679       memory_wsi_info.implicit_sync = true;
680 
681       memory_wsi_info.pNext = mai.pNext;
682       mai.pNext = &memory_wsi_info;
683    }
684 
685    unsigned alignment = MAX2(reqs.alignment, 256);
686    if (templ->usage == PIPE_USAGE_STAGING && obj->is_buffer)
687       alignment = MAX2(alignment, screen->info.props.limits.minMemoryMapAlignment);
688    obj->alignment = alignment;
689    obj->bo = zink_bo(zink_bo_create(screen, reqs.size, alignment, heap, mai.pNext ? ZINK_ALLOC_NO_SUBALLOC : 0, mai.pNext));
690    if (!obj->bo)
691      goto fail2;
692    if (aflags == ZINK_ALLOC_SPARSE) {
693       obj->size = templ->width0;
694    } else {
695       obj->offset = zink_bo_get_offset(obj->bo);
696       obj->size = zink_bo_get_size(obj->bo);
697    }
698 
699    if (templ->target == PIPE_BUFFER) {
700       if (!(templ->flags & PIPE_RESOURCE_FLAG_SPARSE))
701          if (VKSCR(BindBufferMemory)(screen->dev, obj->buffer, zink_bo_get_mem(obj->bo), obj->offset) != VK_SUCCESS)
702             goto fail3;
703    } else {
704       if (VKSCR(BindImageMemory)(screen->dev, obj->image, zink_bo_get_mem(obj->bo), obj->offset) != VK_SUCCESS)
705          goto fail3;
706    }
707    return obj;
708 
709 fail3:
710    zink_bo_unref(screen, obj->bo);
711 
712 fail2:
713    if (templ->target == PIPE_BUFFER)
714       VKSCR(DestroyBuffer)(screen->dev, obj->buffer, NULL);
715    else
716       VKSCR(DestroyImage)(screen->dev, obj->image, NULL);
717 fail1:
718    FREE(obj);
719    return NULL;
720 }
721 
722 static struct pipe_resource *
resource_create(struct pipe_screen * pscreen,const struct pipe_resource * templ,struct winsys_handle * whandle,unsigned external_usage,const uint64_t * modifiers,int modifiers_count)723 resource_create(struct pipe_screen *pscreen,
724                 const struct pipe_resource *templ,
725                 struct winsys_handle *whandle,
726                 unsigned external_usage,
727                 const uint64_t *modifiers, int modifiers_count)
728 {
729    struct zink_screen *screen = zink_screen(pscreen);
730    struct zink_resource *res = rzalloc(NULL, struct zink_resource);
731 
732    if (modifiers_count > 0) {
733       /* for rebinds */
734       res->modifiers_count = modifiers_count;
735       res->modifiers = mem_dup(modifiers, modifiers_count * sizeof(uint64_t));
736       if (!res->modifiers) {
737          ralloc_free(res);
738          return NULL;
739       }
740       /* TODO: remove this when multi-plane modifiers are supported */
741       const struct zink_modifier_prop *prop = &screen->modifier_props[templ->format];
742       for (unsigned i = 0; i < modifiers_count; i++) {
743          for (unsigned j = 0; j < prop->drmFormatModifierCount; j++) {
744             if (prop->pDrmFormatModifierProperties[j].drmFormatModifier == modifiers[i]) {
745                if (prop->pDrmFormatModifierProperties[j].drmFormatModifierPlaneCount != 1)
746                   res->modifiers[i] = DRM_FORMAT_MOD_INVALID;
747                break;
748             }
749          }
750       }
751    }
752 
753    res->base.b = *templ;
754 
755    threaded_resource_init(&res->base.b);
756    pipe_reference_init(&res->base.b.reference, 1);
757    res->base.b.screen = pscreen;
758 
759    bool optimal_tiling = false;
760    struct pipe_resource templ2 = *templ;
761    unsigned scanout_flags = templ->bind & (PIPE_BIND_SCANOUT | PIPE_BIND_SHARED);
762    if (!(templ->bind & PIPE_BIND_LINEAR))
763       templ2.bind &= ~scanout_flags;
764    res->obj = resource_object_create(screen, &templ2, whandle, &optimal_tiling, NULL, 0);
765    if (!res->obj) {
766       free(res->modifiers);
767       ralloc_free(res);
768       return NULL;
769    }
770 
771    res->internal_format = templ->format;
772    if (templ->target == PIPE_BUFFER) {
773       util_range_init(&res->valid_buffer_range);
774       if (!screen->resizable_bar && templ->width0 >= 8196) {
775          /* We don't want to evict buffers from VRAM by mapping them for CPU access,
776           * because they might never be moved back again. If a buffer is large enough,
777           * upload data by copying from a temporary GTT buffer. 8K might not seem much,
778           * but there can be 100000 buffers.
779           *
780           * This tweak improves performance for viewperf.
781           */
782          res->base.b.flags |= PIPE_RESOURCE_FLAG_DONT_MAP_DIRECTLY;
783       }
784    } else {
785       res->format = zink_get_format(screen, templ->format);
786       res->dmabuf_acquire = whandle && whandle->type == WINSYS_HANDLE_TYPE_FD;
787       res->layout = res->dmabuf_acquire ? VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED;
788       res->optimal_tiling = optimal_tiling;
789       res->aspect = aspect_from_format(templ->format);
790       if (scanout_flags && optimal_tiling) {
791          // TODO: remove for wsi
792          templ2 = res->base.b;
793          templ2.bind = scanout_flags | PIPE_BIND_LINEAR;
794          res->scanout_obj = resource_object_create(screen, &templ2, whandle, &optimal_tiling, res->modifiers, res->modifiers_count);
795          assert(!optimal_tiling);
796       }
797    }
798 
799    if (screen->winsys && (templ->bind & PIPE_BIND_DISPLAY_TARGET)) {
800       struct sw_winsys *winsys = screen->winsys;
801       res->dt = winsys->displaytarget_create(screen->winsys,
802                                              res->base.b.bind,
803                                              res->base.b.format,
804                                              templ->width0,
805                                              templ->height0,
806                                              64, NULL,
807                                              &res->dt_stride);
808    }
809    if (res->obj->is_buffer) {
810       res->base.buffer_id_unique = util_idalloc_mt_alloc(&screen->buffer_ids);
811       _mesa_hash_table_init(&res->bufferview_cache, res, NULL, equals_bvci);
812       simple_mtx_init(&res->bufferview_mtx, mtx_plain);
813    } else {
814       _mesa_hash_table_init(&res->surface_cache, res, NULL, equals_ivci);
815       simple_mtx_init(&res->surface_mtx, mtx_plain);
816    }
817    return &res->base.b;
818 }
819 
820 static struct pipe_resource *
zink_resource_create(struct pipe_screen * pscreen,const struct pipe_resource * templ)821 zink_resource_create(struct pipe_screen *pscreen,
822                      const struct pipe_resource *templ)
823 {
824    return resource_create(pscreen, templ, NULL, 0, NULL, 0);
825 }
826 
827 static struct pipe_resource *
zink_resource_create_with_modifiers(struct pipe_screen * pscreen,const struct pipe_resource * templ,const uint64_t * modifiers,int modifiers_count)828 zink_resource_create_with_modifiers(struct pipe_screen *pscreen, const struct pipe_resource *templ,
829                                     const uint64_t *modifiers, int modifiers_count)
830 {
831    return resource_create(pscreen, templ, NULL, 0, modifiers, modifiers_count);
832 }
833 
834 static bool
zink_resource_get_param(struct pipe_screen * pscreen,struct pipe_context * pctx,struct pipe_resource * pres,unsigned plane,unsigned layer,unsigned level,enum pipe_resource_param param,unsigned handle_usage,uint64_t * value)835 zink_resource_get_param(struct pipe_screen *pscreen, struct pipe_context *pctx,
836                         struct pipe_resource *pres,
837                         unsigned plane,
838                         unsigned layer,
839                         unsigned level,
840                         enum pipe_resource_param param,
841                         unsigned handle_usage,
842                         uint64_t *value)
843 {
844    struct zink_screen *screen = zink_screen(pscreen);
845    struct zink_resource *res = zink_resource(pres);
846    //TODO: remove for wsi
847    struct zink_resource_object *obj = res->scanout_obj ? res->scanout_obj : res->obj;
848    VkImageAspectFlags aspect = obj->modifier_aspect ? obj->modifier_aspect : res->aspect;
849    struct winsys_handle whandle;
850    switch (param) {
851    case PIPE_RESOURCE_PARAM_NPLANES:
852       /* not yet implemented */
853       *value = 1;
854       break;
855 
856    case PIPE_RESOURCE_PARAM_STRIDE: {
857       VkImageSubresource sub_res = {0};
858       VkSubresourceLayout sub_res_layout = {0};
859 
860       sub_res.aspectMask = aspect;
861 
862       VKSCR(GetImageSubresourceLayout)(screen->dev, obj->image, &sub_res, &sub_res_layout);
863 
864       *value = sub_res_layout.rowPitch;
865       break;
866    }
867 
868    case PIPE_RESOURCE_PARAM_OFFSET: {
869          VkImageSubresource isr = {
870             aspect,
871             level,
872             layer
873          };
874          VkSubresourceLayout srl;
875          VKSCR(GetImageSubresourceLayout)(screen->dev, obj->image, &isr, &srl);
876          *value = srl.offset;
877          break;
878    }
879 
880    case PIPE_RESOURCE_PARAM_MODIFIER: {
881       *value = DRM_FORMAT_MOD_INVALID;
882       if (!screen->info.have_EXT_image_drm_format_modifier)
883          return false;
884       if (!res->modifiers)
885          return false;
886       VkImageDrmFormatModifierPropertiesEXT prop;
887       prop.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT;
888       prop.pNext = NULL;
889       if (VKSCR(GetImageDrmFormatModifierPropertiesEXT)(screen->dev, obj->image, &prop) == VK_SUCCESS)
890          *value = prop.drmFormatModifier;
891       break;
892    }
893 
894    case PIPE_RESOURCE_PARAM_LAYER_STRIDE: {
895          VkImageSubresource isr = {
896             aspect,
897             level,
898             layer
899          };
900          VkSubresourceLayout srl;
901          VKSCR(GetImageSubresourceLayout)(screen->dev, obj->image, &isr, &srl);
902          if (res->base.b.target == PIPE_TEXTURE_3D)
903             *value = srl.depthPitch;
904          else
905             *value = srl.arrayPitch;
906          break;
907    }
908 
909    case PIPE_RESOURCE_PARAM_HANDLE_TYPE_SHARED:
910    case PIPE_RESOURCE_PARAM_HANDLE_TYPE_KMS:
911    case PIPE_RESOURCE_PARAM_HANDLE_TYPE_FD: {
912       memset(&whandle, 0, sizeof(whandle));
913       if (param == PIPE_RESOURCE_PARAM_HANDLE_TYPE_SHARED)
914          whandle.type = WINSYS_HANDLE_TYPE_SHARED;
915       else if (param == PIPE_RESOURCE_PARAM_HANDLE_TYPE_KMS)
916          whandle.type = WINSYS_HANDLE_TYPE_KMS;
917       else if (param == PIPE_RESOURCE_PARAM_HANDLE_TYPE_FD)
918          whandle.type = WINSYS_HANDLE_TYPE_FD;
919 
920       if (!pscreen->resource_get_handle(pscreen, pctx, pres, &whandle, handle_usage))
921          return false;
922 
923       *value = whandle.handle;
924       break;
925    }
926    }
927    return true;
928 }
929 
930 static bool
zink_resource_get_handle(struct pipe_screen * pscreen,struct pipe_context * context,struct pipe_resource * tex,struct winsys_handle * whandle,unsigned usage)931 zink_resource_get_handle(struct pipe_screen *pscreen,
932                          struct pipe_context *context,
933                          struct pipe_resource *tex,
934                          struct winsys_handle *whandle,
935                          unsigned usage)
936 {
937    if (whandle->type == WINSYS_HANDLE_TYPE_FD || whandle->type == WINSYS_HANDLE_TYPE_KMS) {
938 #ifdef ZINK_USE_DMABUF
939       struct zink_resource *res = zink_resource(tex);
940       struct zink_screen *screen = zink_screen(pscreen);
941       //TODO: remove for wsi
942       struct zink_resource_object *obj = res->scanout_obj ? res->scanout_obj : res->obj;
943 
944       VkMemoryGetFdInfoKHR fd_info = {0};
945       int fd;
946       fd_info.sType = VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR;
947       //TODO: remove for wsi
948       fd_info.memory = zink_bo_get_mem(obj->bo);
949       if (whandle->type == WINSYS_HANDLE_TYPE_FD)
950          fd_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
951       else
952          fd_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
953       VkResult result = VKSCR(GetMemoryFdKHR)(screen->dev, &fd_info, &fd);
954       if (result != VK_SUCCESS)
955          return false;
956       if (whandle->type == WINSYS_HANDLE_TYPE_KMS) {
957          uint32_t h;
958          bool success = drmPrimeFDToHandle(screen->drm_fd, fd, &h) == 0;
959          close(fd);
960          if (!success)
961             return false;
962          fd = h;
963       }
964       whandle->handle = fd;
965       uint64_t value;
966       zink_resource_get_param(pscreen, context, tex, 0, 0, 0, PIPE_RESOURCE_PARAM_MODIFIER, 0, &value);
967       whandle->modifier = value;
968       zink_resource_get_param(pscreen, context, tex, 0, 0, 0, PIPE_RESOURCE_PARAM_OFFSET, 0, &value);
969       whandle->offset = value;
970       zink_resource_get_param(pscreen, context, tex, 0, 0, 0, PIPE_RESOURCE_PARAM_STRIDE, 0, &value);
971       whandle->stride = value;
972 #else
973       return false;
974 #endif
975    }
976    return true;
977 }
978 
979 static struct pipe_resource *
zink_resource_from_handle(struct pipe_screen * pscreen,const struct pipe_resource * templ,struct winsys_handle * whandle,unsigned usage)980 zink_resource_from_handle(struct pipe_screen *pscreen,
981                  const struct pipe_resource *templ,
982                  struct winsys_handle *whandle,
983                  unsigned usage)
984 {
985 #ifdef ZINK_USE_DMABUF
986    if (whandle->modifier != DRM_FORMAT_MOD_INVALID &&
987        !zink_screen(pscreen)->info.have_EXT_image_drm_format_modifier)
988       return NULL;
989 
990    /* ignore any AUX planes, as well as planar formats */
991    if (templ->format == PIPE_FORMAT_NONE ||
992        util_format_get_num_planes(templ->format) != 1)
993       return NULL;
994 
995    uint64_t modifier = DRM_FORMAT_MOD_INVALID;
996    int modifier_count = 0;
997    if (whandle->modifier != DRM_FORMAT_MOD_INVALID) {
998       modifier = whandle->modifier;
999       modifier_count = 1;
1000    }
1001    return resource_create(pscreen, templ, whandle, usage, &modifier, modifier_count);
1002 #else
1003    return NULL;
1004 #endif
1005 }
1006 
1007 static bool
invalidate_buffer(struct zink_context * ctx,struct zink_resource * res)1008 invalidate_buffer(struct zink_context *ctx, struct zink_resource *res)
1009 {
1010    struct zink_screen *screen = zink_screen(ctx->base.screen);
1011 
1012    assert(res->base.b.target == PIPE_BUFFER);
1013 
1014    if (res->base.b.flags & PIPE_RESOURCE_FLAG_SPARSE)
1015       return false;
1016 
1017    if (res->valid_buffer_range.start > res->valid_buffer_range.end)
1018       return false;
1019 
1020    if (res->so_valid)
1021       ctx->dirty_so_targets = true;
1022    /* force counter buffer reset */
1023    res->so_valid = false;
1024 
1025    util_range_set_empty(&res->valid_buffer_range);
1026    if (!zink_resource_has_usage(res))
1027       return false;
1028 
1029    struct zink_resource_object *old_obj = res->obj;
1030    struct zink_resource_object *new_obj = resource_object_create(screen, &res->base.b, NULL, NULL, NULL, 0);
1031    if (!new_obj) {
1032       debug_printf("new backing resource alloc failed!");
1033       return false;
1034    }
1035    /* this ref must be transferred before rebind or else BOOM */
1036    zink_batch_reference_resource_move(&ctx->batch, res);
1037    res->obj = new_obj;
1038    zink_resource_rebind(ctx, res);
1039    zink_descriptor_set_refs_clear(&old_obj->desc_set_refs, old_obj);
1040    return true;
1041 }
1042 
1043 
1044 static void
zink_resource_invalidate(struct pipe_context * pctx,struct pipe_resource * pres)1045 zink_resource_invalidate(struct pipe_context *pctx, struct pipe_resource *pres)
1046 {
1047    if (pres->target == PIPE_BUFFER)
1048       invalidate_buffer(zink_context(pctx), zink_resource(pres));
1049 }
1050 
1051 static void
zink_transfer_copy_bufimage(struct zink_context * ctx,struct zink_resource * dst,struct zink_resource * src,struct zink_transfer * trans)1052 zink_transfer_copy_bufimage(struct zink_context *ctx,
1053                             struct zink_resource *dst,
1054                             struct zink_resource *src,
1055                             struct zink_transfer *trans)
1056 {
1057    assert((trans->base.b.usage & (PIPE_MAP_DEPTH_ONLY | PIPE_MAP_STENCIL_ONLY)) !=
1058           (PIPE_MAP_DEPTH_ONLY | PIPE_MAP_STENCIL_ONLY));
1059 
1060    bool buf2img = src->base.b.target == PIPE_BUFFER;
1061 
1062    struct pipe_box box = trans->base.b.box;
1063    int x = box.x;
1064    if (buf2img)
1065       box.x = trans->offset;
1066 
1067    if (dst->obj->transfer_dst)
1068       zink_copy_image_buffer(ctx, dst, src, trans->base.b.level, buf2img ? x : 0,
1069                               box.y, box.z, trans->base.b.level, &box, trans->base.b.usage);
1070    else
1071       util_blitter_copy_texture(ctx->blitter, &dst->base.b, trans->base.b.level,
1072                                 x, box.y, box.z, &src->base.b,
1073                                 0, &box);
1074 }
1075 
1076 ALWAYS_INLINE static void
align_offset_size(const VkDeviceSize alignment,VkDeviceSize * offset,VkDeviceSize * size,VkDeviceSize obj_size)1077 align_offset_size(const VkDeviceSize alignment, VkDeviceSize *offset, VkDeviceSize *size, VkDeviceSize obj_size)
1078 {
1079    VkDeviceSize align = *offset % alignment;
1080    if (alignment - 1 > *offset)
1081       *offset = 0;
1082    else
1083       *offset -= align, *size += align;
1084    align = alignment - (*size % alignment);
1085    if (*offset + *size + align > obj_size)
1086       *size = obj_size - *offset;
1087    else
1088       *size += align;
1089 }
1090 
1091 VkMappedMemoryRange
zink_resource_init_mem_range(struct zink_screen * screen,struct zink_resource_object * obj,VkDeviceSize offset,VkDeviceSize size)1092 zink_resource_init_mem_range(struct zink_screen *screen, struct zink_resource_object *obj, VkDeviceSize offset, VkDeviceSize size)
1093 {
1094    assert(obj->size);
1095    align_offset_size(screen->info.props.limits.nonCoherentAtomSize, &offset, &size, obj->size);
1096    VkMappedMemoryRange range = {
1097       VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
1098       NULL,
1099       zink_bo_get_mem(obj->bo),
1100       offset,
1101       size
1102    };
1103    assert(range.size);
1104    return range;
1105 }
1106 
1107 static void *
map_resource(struct zink_screen * screen,struct zink_resource * res)1108 map_resource(struct zink_screen *screen, struct zink_resource *res)
1109 {
1110    assert(res->obj->host_visible);
1111    return zink_bo_map(screen, res->obj->bo);
1112 }
1113 
1114 static void
unmap_resource(struct zink_screen * screen,struct zink_resource * res)1115 unmap_resource(struct zink_screen *screen, struct zink_resource *res)
1116 {
1117    zink_bo_unmap(screen, res->obj->bo);
1118 }
1119 
1120 static struct zink_transfer *
create_transfer(struct zink_context * ctx,struct pipe_resource * pres,unsigned usage,const struct pipe_box * box)1121 create_transfer(struct zink_context *ctx, struct pipe_resource *pres, unsigned usage, const struct pipe_box *box)
1122 {
1123    struct zink_transfer *trans;
1124 
1125    if (usage & PIPE_MAP_THREAD_SAFE)
1126       trans = malloc(sizeof(*trans));
1127    else if (usage & TC_TRANSFER_MAP_THREADED_UNSYNC)
1128       trans = slab_alloc(&ctx->transfer_pool_unsync);
1129    else
1130       trans = slab_alloc(&ctx->transfer_pool);
1131    if (!trans)
1132       return NULL;
1133 
1134    memset(trans, 0, sizeof(*trans));
1135    pipe_resource_reference(&trans->base.b.resource, pres);
1136 
1137    trans->base.b.usage = usage;
1138    trans->base.b.box = *box;
1139    return trans;
1140 }
1141 
1142 static void
destroy_transfer(struct zink_context * ctx,struct zink_transfer * trans)1143 destroy_transfer(struct zink_context *ctx, struct zink_transfer *trans)
1144 {
1145    if (trans->base.b.usage & PIPE_MAP_THREAD_SAFE) {
1146       free(trans);
1147    } else {
1148       /* Don't use pool_transfers_unsync. We are always in the driver
1149        * thread. Freeing an object into a different pool is allowed.
1150        */
1151       slab_free(&ctx->transfer_pool, trans);
1152    }
1153 }
1154 
1155 static void *
zink_buffer_map(struct pipe_context * pctx,struct pipe_resource * pres,unsigned level,unsigned usage,const struct pipe_box * box,struct pipe_transfer ** transfer)1156 zink_buffer_map(struct pipe_context *pctx,
1157                     struct pipe_resource *pres,
1158                     unsigned level,
1159                     unsigned usage,
1160                     const struct pipe_box *box,
1161                     struct pipe_transfer **transfer)
1162 {
1163    struct zink_context *ctx = zink_context(pctx);
1164    struct zink_screen *screen = zink_screen(pctx->screen);
1165    struct zink_resource *res = zink_resource(pres);
1166    struct zink_transfer *trans = create_transfer(ctx, pres, usage, box);
1167    if (!trans)
1168       return NULL;
1169 
1170    void *ptr = NULL;
1171 
1172    if (res->base.is_user_ptr)
1173       usage |= PIPE_MAP_PERSISTENT;
1174 
1175    /* See if the buffer range being mapped has never been initialized,
1176     * in which case it can be mapped unsynchronized. */
1177    if (!(usage & (PIPE_MAP_UNSYNCHRONIZED | TC_TRANSFER_MAP_NO_INFER_UNSYNCHRONIZED)) &&
1178        usage & PIPE_MAP_WRITE && !res->base.is_shared &&
1179        !util_ranges_intersect(&res->valid_buffer_range, box->x, box->x + box->width)) {
1180       usage |= PIPE_MAP_UNSYNCHRONIZED;
1181    }
1182 
1183    /* If discarding the entire range, discard the whole resource instead. */
1184    if (usage & PIPE_MAP_DISCARD_RANGE && box->x == 0 && box->width == res->base.b.width0) {
1185       usage |= PIPE_MAP_DISCARD_WHOLE_RESOURCE;
1186    }
1187 
1188    /* If a buffer in VRAM is too large and the range is discarded, don't
1189     * map it directly. This makes sure that the buffer stays in VRAM.
1190     */
1191    bool force_discard_range = false;
1192    if (usage & (PIPE_MAP_DISCARD_WHOLE_RESOURCE | PIPE_MAP_DISCARD_RANGE) &&
1193        !(usage & PIPE_MAP_PERSISTENT) &&
1194        res->base.b.flags & PIPE_RESOURCE_FLAG_DONT_MAP_DIRECTLY) {
1195       usage &= ~(PIPE_MAP_DISCARD_WHOLE_RESOURCE | PIPE_MAP_UNSYNCHRONIZED);
1196       usage |= PIPE_MAP_DISCARD_RANGE;
1197       force_discard_range = true;
1198    }
1199 
1200    if (usage & PIPE_MAP_DISCARD_WHOLE_RESOURCE &&
1201        !(usage & (PIPE_MAP_UNSYNCHRONIZED | TC_TRANSFER_MAP_NO_INVALIDATE))) {
1202       assert(usage & PIPE_MAP_WRITE);
1203 
1204       if (invalidate_buffer(ctx, res)) {
1205          /* At this point, the buffer is always idle. */
1206          usage |= PIPE_MAP_UNSYNCHRONIZED;
1207       } else {
1208          /* Fall back to a temporary buffer. */
1209          usage |= PIPE_MAP_DISCARD_RANGE;
1210       }
1211    }
1212 
1213    if (usage & PIPE_MAP_DISCARD_RANGE &&
1214         (!res->obj->host_visible ||
1215         !(usage & (PIPE_MAP_UNSYNCHRONIZED | PIPE_MAP_PERSISTENT)))) {
1216 
1217       /* Check if mapping this buffer would cause waiting for the GPU.
1218        */
1219 
1220       if (!res->obj->host_visible || force_discard_range ||
1221           !zink_resource_usage_check_completion(screen, res, ZINK_RESOURCE_ACCESS_RW)) {
1222          /* Do a wait-free write-only transfer using a temporary buffer. */
1223          unsigned offset;
1224 
1225          /* If we are not called from the driver thread, we have
1226           * to use the uploader from u_threaded_context, which is
1227           * local to the calling thread.
1228           */
1229          struct u_upload_mgr *mgr;
1230          if (usage & TC_TRANSFER_MAP_THREADED_UNSYNC)
1231             mgr = ctx->tc->base.stream_uploader;
1232          else
1233             mgr = ctx->base.stream_uploader;
1234          u_upload_alloc(mgr, 0, box->width + box->x,
1235                      screen->info.props.limits.minMemoryMapAlignment, &offset,
1236                      (struct pipe_resource **)&trans->staging_res, (void **)&ptr);
1237          res = zink_resource(trans->staging_res);
1238          trans->offset = offset + box->x;
1239          usage |= PIPE_MAP_UNSYNCHRONIZED;
1240          ptr = ((uint8_t *)ptr) + box->x;
1241       } else {
1242          /* At this point, the buffer is always idle (we checked it above). */
1243          usage |= PIPE_MAP_UNSYNCHRONIZED;
1244       }
1245    } else if (usage & PIPE_MAP_DONTBLOCK) {
1246       /* sparse/device-local will always need to wait since it has to copy */
1247       if (!res->obj->host_visible)
1248          goto success;
1249       if (!zink_resource_usage_check_completion(screen, res, ZINK_RESOURCE_ACCESS_WRITE))
1250          goto success;
1251       usage |= PIPE_MAP_UNSYNCHRONIZED;
1252    } else if (!(usage & PIPE_MAP_UNSYNCHRONIZED) &&
1253               (((usage & PIPE_MAP_READ) && !(usage & PIPE_MAP_PERSISTENT) && res->base.b.usage != PIPE_USAGE_STAGING) || !res->obj->host_visible)) {
1254       assert(!(usage & (TC_TRANSFER_MAP_THREADED_UNSYNC | PIPE_MAP_THREAD_SAFE)));
1255       if (!res->obj->host_visible || !(usage & PIPE_MAP_ONCE)) {
1256          trans->offset = box->x % screen->info.props.limits.minMemoryMapAlignment;
1257          trans->staging_res = pipe_buffer_create(&screen->base, PIPE_BIND_LINEAR, PIPE_USAGE_STAGING, box->width + trans->offset);
1258          if (!trans->staging_res)
1259             goto fail;
1260          struct zink_resource *staging_res = zink_resource(trans->staging_res);
1261          zink_copy_buffer(ctx, staging_res, res, trans->offset, box->x, box->width);
1262          res = staging_res;
1263          usage &= ~PIPE_MAP_UNSYNCHRONIZED;
1264          ptr = map_resource(screen, res);
1265          ptr = ((uint8_t *)ptr) + trans->offset;
1266       }
1267    }
1268 
1269    if (!(usage & PIPE_MAP_UNSYNCHRONIZED)) {
1270       if (usage & PIPE_MAP_WRITE)
1271          zink_resource_usage_wait(ctx, res, ZINK_RESOURCE_ACCESS_RW);
1272       else
1273          zink_resource_usage_wait(ctx, res, ZINK_RESOURCE_ACCESS_WRITE);
1274       res->obj->access = 0;
1275       res->obj->access_stage = 0;
1276    }
1277 
1278    if (!ptr) {
1279       /* if writing to a streamout buffer, ensure synchronization next time it's used */
1280       if (usage & PIPE_MAP_WRITE && res->so_valid) {
1281          ctx->dirty_so_targets = true;
1282          /* force counter buffer reset */
1283          res->so_valid = false;
1284       }
1285       ptr = map_resource(screen, res);
1286       if (!ptr)
1287          goto fail;
1288       ptr = ((uint8_t *)ptr) + box->x;
1289    }
1290 
1291    if (!res->obj->coherent
1292 #if defined(MVK_VERSION)
1293       // Work around for MoltenVk limitation specifically on coherent memory
1294       // MoltenVk returns blank memory ranges when there should be data present
1295       // This is a known limitation of MoltenVK.
1296       // See https://github.com/KhronosGroup/MoltenVK/blob/master/Docs/MoltenVK_Runtime_UserGuide.md#known-moltenvk-limitations
1297 
1298        || screen->instance_info.have_MVK_moltenvk
1299 #endif
1300       ) {
1301       VkDeviceSize size = box->width;
1302       VkDeviceSize offset = res->obj->offset + trans->offset;
1303       VkMappedMemoryRange range = zink_resource_init_mem_range(screen, res->obj, offset, size);
1304       if (VKSCR(InvalidateMappedMemoryRanges)(screen->dev, 1, &range) != VK_SUCCESS) {
1305          zink_bo_unmap(screen, res->obj->bo);
1306          goto fail;
1307       }
1308    }
1309    trans->base.b.usage = usage;
1310    if (usage & PIPE_MAP_WRITE)
1311       util_range_add(&res->base.b, &res->valid_buffer_range, box->x, box->x + box->width);
1312    if ((usage & PIPE_MAP_PERSISTENT) && !(usage & PIPE_MAP_COHERENT))
1313       res->obj->persistent_maps++;
1314 
1315 success:
1316    *transfer = &trans->base.b;
1317    return ptr;
1318 
1319 fail:
1320    destroy_transfer(ctx, trans);
1321    return NULL;
1322 }
1323 
1324 static void *
zink_image_map(struct pipe_context * pctx,struct pipe_resource * pres,unsigned level,unsigned usage,const struct pipe_box * box,struct pipe_transfer ** transfer)1325 zink_image_map(struct pipe_context *pctx,
1326                   struct pipe_resource *pres,
1327                   unsigned level,
1328                   unsigned usage,
1329                   const struct pipe_box *box,
1330                   struct pipe_transfer **transfer)
1331 {
1332    struct zink_context *ctx = zink_context(pctx);
1333    struct zink_screen *screen = zink_screen(pctx->screen);
1334    struct zink_resource *res = zink_resource(pres);
1335    struct zink_transfer *trans = create_transfer(ctx, pres, usage, box);
1336    if (!trans)
1337       return NULL;
1338 
1339    trans->base.b.level = level;
1340 
1341    void *ptr;
1342    if (usage & PIPE_MAP_WRITE && !(usage & PIPE_MAP_READ))
1343       /* this is like a blit, so we can potentially dump some clears or maybe we have to  */
1344       zink_fb_clears_apply_or_discard(ctx, pres, zink_rect_from_box(box), false);
1345    else if (usage & PIPE_MAP_READ)
1346       /* if the map region intersects with any clears then we have to apply them */
1347       zink_fb_clears_apply_region(ctx, pres, zink_rect_from_box(box));
1348    if (res->optimal_tiling || !res->obj->host_visible) {
1349       enum pipe_format format = pres->format;
1350       if (usage & PIPE_MAP_DEPTH_ONLY)
1351          format = util_format_get_depth_only(pres->format);
1352       else if (usage & PIPE_MAP_STENCIL_ONLY)
1353          format = PIPE_FORMAT_S8_UINT;
1354       trans->base.b.stride = util_format_get_stride(format, box->width);
1355       trans->base.b.layer_stride = util_format_get_2d_size(format,
1356                                                          trans->base.b.stride,
1357                                                          box->height);
1358 
1359       struct pipe_resource templ = *pres;
1360       templ.format = format;
1361       templ.usage = usage & PIPE_MAP_READ ? PIPE_USAGE_STAGING : PIPE_USAGE_STREAM;
1362       templ.target = PIPE_BUFFER;
1363       templ.bind = PIPE_BIND_LINEAR;
1364       templ.width0 = trans->base.b.layer_stride * box->depth;
1365       templ.height0 = templ.depth0 = 0;
1366       templ.last_level = 0;
1367       templ.array_size = 1;
1368       templ.flags = 0;
1369 
1370       trans->staging_res = zink_resource_create(pctx->screen, &templ);
1371       if (!trans->staging_res)
1372          goto fail;
1373 
1374       struct zink_resource *staging_res = zink_resource(trans->staging_res);
1375 
1376       if (usage & PIPE_MAP_READ) {
1377          /* force multi-context sync */
1378          if (zink_resource_usage_is_unflushed_write(res))
1379             zink_resource_usage_wait(ctx, res, ZINK_RESOURCE_ACCESS_WRITE);
1380          zink_transfer_copy_bufimage(ctx, staging_res, res, trans);
1381          /* need to wait for rendering to finish */
1382          zink_fence_wait(pctx);
1383       }
1384 
1385       ptr = map_resource(screen, staging_res);
1386    } else {
1387       assert(!res->optimal_tiling);
1388       ptr = map_resource(screen, res);
1389       if (!ptr)
1390          goto fail;
1391       if (zink_resource_has_usage(res)) {
1392          if (usage & PIPE_MAP_WRITE)
1393             zink_fence_wait(pctx);
1394          else
1395             zink_resource_usage_wait(ctx, res, ZINK_RESOURCE_ACCESS_WRITE);
1396       }
1397       VkImageSubresource isr = {
1398          res->obj->modifier_aspect ? res->obj->modifier_aspect : res->aspect,
1399          level,
1400          0
1401       };
1402       VkSubresourceLayout srl;
1403       VKSCR(GetImageSubresourceLayout)(screen->dev, res->obj->image, &isr, &srl);
1404       trans->base.b.stride = srl.rowPitch;
1405       if (res->base.b.target == PIPE_TEXTURE_3D)
1406          trans->base.b.layer_stride = srl.depthPitch;
1407       else
1408          trans->base.b.layer_stride = srl.arrayPitch;
1409       trans->offset = srl.offset;
1410       trans->depthPitch = srl.depthPitch;
1411       const struct util_format_description *desc = util_format_description(res->base.b.format);
1412       unsigned offset = srl.offset +
1413                         box->z * srl.depthPitch +
1414                         (box->y / desc->block.height) * srl.rowPitch +
1415                         (box->x / desc->block.width) * (desc->block.bits / 8);
1416       if (!res->obj->coherent) {
1417          VkDeviceSize size = (VkDeviceSize)box->width * box->height * desc->block.bits / 8;
1418          VkMappedMemoryRange range = zink_resource_init_mem_range(screen, res->obj, res->obj->offset + offset, size);
1419          VKSCR(FlushMappedMemoryRanges)(screen->dev, 1, &range);
1420       }
1421       ptr = ((uint8_t *)ptr) + offset;
1422    }
1423    if (!ptr)
1424       goto fail;
1425 
1426    if (sizeof(void*) == 4)
1427       trans->base.b.usage |= ZINK_MAP_TEMPORARY;
1428    if ((usage & PIPE_MAP_PERSISTENT) && !(usage & PIPE_MAP_COHERENT))
1429       res->obj->persistent_maps++;
1430 
1431    *transfer = &trans->base.b;
1432    return ptr;
1433 
1434 fail:
1435    destroy_transfer(ctx, trans);
1436    return NULL;
1437 }
1438 
1439 static void
zink_transfer_flush_region(struct pipe_context * pctx,struct pipe_transfer * ptrans,const struct pipe_box * box)1440 zink_transfer_flush_region(struct pipe_context *pctx,
1441                            struct pipe_transfer *ptrans,
1442                            const struct pipe_box *box)
1443 {
1444    struct zink_context *ctx = zink_context(pctx);
1445    struct zink_resource *res = zink_resource(ptrans->resource);
1446    struct zink_transfer *trans = (struct zink_transfer *)ptrans;
1447 
1448    if (trans->base.b.usage & PIPE_MAP_WRITE) {
1449       struct zink_screen *screen = zink_screen(pctx->screen);
1450       struct zink_resource *m = trans->staging_res ? zink_resource(trans->staging_res) :
1451                                                      res;
1452       ASSERTED VkDeviceSize size, offset;
1453       if (m->obj->is_buffer) {
1454          size = box->width;
1455          offset = trans->offset;
1456       } else {
1457          size = (VkDeviceSize)box->width * box->height * util_format_get_blocksize(m->base.b.format);
1458          offset = trans->offset +
1459                   box->z * trans->depthPitch +
1460                   util_format_get_2d_size(m->base.b.format, trans->base.b.stride, box->y) +
1461                   util_format_get_stride(m->base.b.format, box->x);
1462          assert(offset + size <= res->obj->size);
1463       }
1464       if (!m->obj->coherent) {
1465          VkMappedMemoryRange range = zink_resource_init_mem_range(screen, m->obj, m->obj->offset, m->obj->size);
1466          VKSCR(FlushMappedMemoryRanges)(screen->dev, 1, &range);
1467       }
1468       if (trans->staging_res) {
1469          struct zink_resource *staging_res = zink_resource(trans->staging_res);
1470 
1471          if (ptrans->resource->target == PIPE_BUFFER)
1472             zink_copy_buffer(ctx, res, staging_res, box->x, offset, box->width);
1473          else
1474             zink_transfer_copy_bufimage(ctx, res, staging_res, trans);
1475       }
1476    }
1477 }
1478 
1479 static void
transfer_unmap(struct pipe_context * pctx,struct pipe_transfer * ptrans)1480 transfer_unmap(struct pipe_context *pctx, struct pipe_transfer *ptrans)
1481 {
1482    struct zink_context *ctx = zink_context(pctx);
1483    struct zink_resource *res = zink_resource(ptrans->resource);
1484    struct zink_transfer *trans = (struct zink_transfer *)ptrans;
1485 
1486    if (!(trans->base.b.usage & (PIPE_MAP_FLUSH_EXPLICIT | PIPE_MAP_COHERENT))) {
1487       zink_transfer_flush_region(pctx, ptrans, &ptrans->box);
1488    }
1489 
1490    if ((trans->base.b.usage & PIPE_MAP_PERSISTENT) && !(trans->base.b.usage & PIPE_MAP_COHERENT))
1491       res->obj->persistent_maps--;
1492 
1493    if (trans->staging_res)
1494       pipe_resource_reference(&trans->staging_res, NULL);
1495    pipe_resource_reference(&trans->base.b.resource, NULL);
1496 
1497    destroy_transfer(ctx, trans);
1498 }
1499 
1500 static void
do_transfer_unmap(struct zink_screen * screen,struct zink_transfer * trans)1501 do_transfer_unmap(struct zink_screen *screen, struct zink_transfer *trans)
1502 {
1503    struct zink_resource *res = zink_resource(trans->staging_res);
1504    if (!res)
1505       res = zink_resource(trans->base.b.resource);
1506    unmap_resource(screen, res);
1507 }
1508 
1509 static void
zink_buffer_unmap(struct pipe_context * pctx,struct pipe_transfer * ptrans)1510 zink_buffer_unmap(struct pipe_context *pctx, struct pipe_transfer *ptrans)
1511 {
1512    struct zink_screen *screen = zink_screen(pctx->screen);
1513    struct zink_transfer *trans = (struct zink_transfer *)ptrans;
1514    if (trans->base.b.usage & PIPE_MAP_ONCE && !trans->staging_res)
1515       do_transfer_unmap(screen, trans);
1516    transfer_unmap(pctx, ptrans);
1517 }
1518 
1519 static void
zink_image_unmap(struct pipe_context * pctx,struct pipe_transfer * ptrans)1520 zink_image_unmap(struct pipe_context *pctx, struct pipe_transfer *ptrans)
1521 {
1522    struct zink_screen *screen = zink_screen(pctx->screen);
1523    struct zink_transfer *trans = (struct zink_transfer *)ptrans;
1524    if (sizeof(void*) == 4)
1525       do_transfer_unmap(screen, trans);
1526    transfer_unmap(pctx, ptrans);
1527 }
1528 
1529 static void
zink_buffer_subdata(struct pipe_context * ctx,struct pipe_resource * buffer,unsigned usage,unsigned offset,unsigned size,const void * data)1530 zink_buffer_subdata(struct pipe_context *ctx, struct pipe_resource *buffer,
1531                     unsigned usage, unsigned offset, unsigned size, const void *data)
1532 {
1533    struct pipe_transfer *transfer = NULL;
1534    struct pipe_box box;
1535    uint8_t *map = NULL;
1536 
1537    usage |= PIPE_MAP_WRITE;
1538 
1539    if (!(usage & PIPE_MAP_DIRECTLY))
1540       usage |= PIPE_MAP_DISCARD_RANGE;
1541 
1542    u_box_1d(offset, size, &box);
1543    map = zink_buffer_map(ctx, buffer, 0, usage, &box, &transfer);
1544    if (!map)
1545       return;
1546 
1547    memcpy(map, data, size);
1548    zink_buffer_unmap(ctx, transfer);
1549 }
1550 
1551 static struct pipe_resource *
zink_resource_get_separate_stencil(struct pipe_resource * pres)1552 zink_resource_get_separate_stencil(struct pipe_resource *pres)
1553 {
1554    /* For packed depth-stencil, we treat depth as the primary resource
1555     * and store S8 as the "second plane" resource.
1556     */
1557    if (pres->next && pres->next->format == PIPE_FORMAT_S8_UINT)
1558       return pres->next;
1559 
1560    return NULL;
1561 
1562 }
1563 
1564 VkBuffer
zink_resource_tmp_buffer(struct zink_screen * screen,struct zink_resource * res,unsigned offset_add,unsigned add_binds,unsigned * offset_out)1565 zink_resource_tmp_buffer(struct zink_screen *screen, struct zink_resource *res, unsigned offset_add, unsigned add_binds, unsigned *offset_out)
1566 {
1567    VkBufferCreateInfo bci = create_bci(screen, &res->base.b, res->base.b.bind | add_binds);
1568    VkDeviceSize size = bci.size - offset_add;
1569    VkDeviceSize offset = offset_add;
1570    if (offset_add) {
1571       assert(bci.size > offset_add);
1572 
1573       align_offset_size(res->obj->alignment, &offset, &size, bci.size);
1574    }
1575    bci.size = size;
1576 
1577    VkBuffer buffer;
1578    if (VKSCR(CreateBuffer)(screen->dev, &bci, NULL, &buffer) != VK_SUCCESS)
1579       return VK_NULL_HANDLE;
1580    VKSCR(BindBufferMemory)(screen->dev, buffer, zink_bo_get_mem(res->obj->bo), res->obj->offset + offset);
1581    if (offset_out)
1582       *offset_out = offset_add - offset;
1583    return buffer;
1584 }
1585 
1586 bool
zink_resource_object_init_storage(struct zink_context * ctx,struct zink_resource * res)1587 zink_resource_object_init_storage(struct zink_context *ctx, struct zink_resource *res)
1588 {
1589    struct zink_screen *screen = zink_screen(ctx->base.screen);
1590    /* base resource already has the cap */
1591    if (res->base.b.bind & PIPE_BIND_SHADER_IMAGE)
1592       return true;
1593    if (res->obj->is_buffer) {
1594       if (res->base.b.bind & PIPE_BIND_SHADER_IMAGE)
1595          return true;
1596 
1597       VkBuffer buffer = zink_resource_tmp_buffer(screen, res, 0, PIPE_BIND_SHADER_IMAGE, NULL);
1598       if (!buffer)
1599          return false;
1600       util_dynarray_append(&res->obj->tmp, VkBuffer, res->obj->buffer);
1601       res->obj->buffer = buffer;
1602       res->base.b.bind |= PIPE_BIND_SHADER_IMAGE;
1603    } else {
1604       zink_fb_clears_apply_region(ctx, &res->base.b, (struct u_rect){0, res->base.b.width0, 0, res->base.b.height0});
1605       zink_resource_image_barrier(ctx, res, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 0, 0);
1606       res->base.b.bind |= PIPE_BIND_SHADER_IMAGE;
1607       struct zink_resource_object *old_obj = res->obj;
1608       struct zink_resource_object *new_obj = resource_object_create(screen, &res->base.b, NULL, &res->optimal_tiling, res->modifiers, res->modifiers_count);
1609       if (!new_obj) {
1610          debug_printf("new backing resource alloc failed!");
1611          res->base.b.bind &= ~PIPE_BIND_SHADER_IMAGE;
1612          return false;
1613       }
1614       struct zink_resource staging = *res;
1615       staging.obj = old_obj;
1616       bool needs_unref = true;
1617       if (zink_resource_has_usage(res)) {
1618          zink_batch_reference_resource_move(&ctx->batch, res);
1619          needs_unref = false;
1620       }
1621       res->obj = new_obj;
1622       zink_descriptor_set_refs_clear(&old_obj->desc_set_refs, old_obj);
1623       for (unsigned i = 0; i <= res->base.b.last_level; i++) {
1624          struct pipe_box box = {0, 0, 0,
1625                                 u_minify(res->base.b.width0, i),
1626                                 u_minify(res->base.b.height0, i), res->base.b.array_size};
1627          box.depth = util_num_layers(&res->base.b, i);
1628          ctx->base.resource_copy_region(&ctx->base, &res->base.b, i, 0, 0, 0, &staging.base.b, i, &box);
1629       }
1630       if (needs_unref)
1631          zink_resource_object_reference(screen, &old_obj, NULL);
1632    }
1633 
1634    zink_resource_rebind(ctx, res);
1635 
1636    return true;
1637 }
1638 
1639 void
zink_resource_setup_transfer_layouts(struct zink_context * ctx,struct zink_resource * src,struct zink_resource * dst)1640 zink_resource_setup_transfer_layouts(struct zink_context *ctx, struct zink_resource *src, struct zink_resource *dst)
1641 {
1642    if (src == dst) {
1643       /* The Vulkan 1.1 specification says the following about valid usage
1644        * of vkCmdBlitImage:
1645        *
1646        * "srcImageLayout must be VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR,
1647        *  VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL or VK_IMAGE_LAYOUT_GENERAL"
1648        *
1649        * and:
1650        *
1651        * "dstImageLayout must be VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR,
1652        *  VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL or VK_IMAGE_LAYOUT_GENERAL"
1653        *
1654        * Since we cant have the same image in two states at the same time,
1655        * we're effectively left with VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR or
1656        * VK_IMAGE_LAYOUT_GENERAL. And since this isn't a present-related
1657        * operation, VK_IMAGE_LAYOUT_GENERAL seems most appropriate.
1658        */
1659       zink_resource_image_barrier(ctx, src,
1660                                   VK_IMAGE_LAYOUT_GENERAL,
1661                                   VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT,
1662                                   VK_PIPELINE_STAGE_TRANSFER_BIT);
1663    } else {
1664       zink_resource_image_barrier(ctx, src,
1665                                   VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1666                                   VK_ACCESS_TRANSFER_READ_BIT,
1667                                   VK_PIPELINE_STAGE_TRANSFER_BIT);
1668 
1669       zink_resource_image_barrier(ctx, dst,
1670                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1671                                   VK_ACCESS_TRANSFER_WRITE_BIT,
1672                                   VK_PIPELINE_STAGE_TRANSFER_BIT);
1673    }
1674 }
1675 
1676 void
zink_get_depth_stencil_resources(struct pipe_resource * res,struct zink_resource ** out_z,struct zink_resource ** out_s)1677 zink_get_depth_stencil_resources(struct pipe_resource *res,
1678                                  struct zink_resource **out_z,
1679                                  struct zink_resource **out_s)
1680 {
1681    if (!res) {
1682       if (out_z) *out_z = NULL;
1683       if (out_s) *out_s = NULL;
1684       return;
1685    }
1686 
1687    if (res->format != PIPE_FORMAT_S8_UINT) {
1688       if (out_z) *out_z = zink_resource(res);
1689       if (out_s) *out_s = zink_resource(zink_resource_get_separate_stencil(res));
1690    } else {
1691       if (out_z) *out_z = NULL;
1692       if (out_s) *out_s = zink_resource(res);
1693    }
1694 }
1695 
1696 static void
zink_resource_set_separate_stencil(struct pipe_resource * pres,struct pipe_resource * stencil)1697 zink_resource_set_separate_stencil(struct pipe_resource *pres,
1698                                    struct pipe_resource *stencil)
1699 {
1700    assert(util_format_has_depth(util_format_description(pres->format)));
1701    pipe_resource_reference(&pres->next, stencil);
1702 }
1703 
1704 static enum pipe_format
zink_resource_get_internal_format(struct pipe_resource * pres)1705 zink_resource_get_internal_format(struct pipe_resource *pres)
1706 {
1707    struct zink_resource *res = zink_resource(pres);
1708    return res->internal_format;
1709 }
1710 
1711 static const struct u_transfer_vtbl transfer_vtbl = {
1712    .resource_create       = zink_resource_create,
1713    .resource_destroy      = zink_resource_destroy,
1714    .transfer_map          = zink_image_map,
1715    .transfer_unmap        = zink_image_unmap,
1716    .transfer_flush_region = zink_transfer_flush_region,
1717    .get_internal_format   = zink_resource_get_internal_format,
1718    .set_stencil           = zink_resource_set_separate_stencil,
1719    .get_stencil           = zink_resource_get_separate_stencil,
1720 };
1721 
1722 bool
zink_screen_resource_init(struct pipe_screen * pscreen)1723 zink_screen_resource_init(struct pipe_screen *pscreen)
1724 {
1725    struct zink_screen *screen = zink_screen(pscreen);
1726    pscreen->resource_create = zink_resource_create;
1727    pscreen->resource_create_with_modifiers = zink_resource_create_with_modifiers;
1728    pscreen->resource_destroy = zink_resource_destroy;
1729    pscreen->transfer_helper = u_transfer_helper_create(&transfer_vtbl, true, true, false, false);
1730 
1731    if (screen->info.have_KHR_external_memory_fd) {
1732       pscreen->resource_get_handle = zink_resource_get_handle;
1733       pscreen->resource_from_handle = zink_resource_from_handle;
1734    }
1735    pscreen->resource_get_param = zink_resource_get_param;
1736    return true;
1737 }
1738 
1739 void
zink_context_resource_init(struct pipe_context * pctx)1740 zink_context_resource_init(struct pipe_context *pctx)
1741 {
1742    pctx->buffer_map = zink_buffer_map;
1743    pctx->buffer_unmap = zink_buffer_unmap;
1744    pctx->texture_map = u_transfer_helper_deinterleave_transfer_map;
1745    pctx->texture_unmap = u_transfer_helper_deinterleave_transfer_unmap;
1746 
1747    pctx->transfer_flush_region = u_transfer_helper_transfer_flush_region;
1748    pctx->buffer_subdata = zink_buffer_subdata;
1749    pctx->texture_subdata = u_default_texture_subdata;
1750    pctx->invalidate_resource = zink_resource_invalidate;
1751 }
1752