xref: /aosp_15_r20/external/mesa3d/src/broadcom/vulkan/v3dv_query.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2020 Raspberry Pi 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  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * 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 NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include "v3dv_private.h"
25 
26 #include "util/timespec.h"
27 #include "compiler/nir/nir_builder.h"
28 
29 static void
kperfmon_create(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t query)30 kperfmon_create(struct v3dv_device *device,
31                 struct v3dv_query_pool *pool,
32                 uint32_t query)
33 {
34    for (uint32_t i = 0; i < pool->perfmon.nperfmons; i++) {
35       assert(i * DRM_V3D_MAX_PERF_COUNTERS < pool->perfmon.ncounters);
36 
37       struct drm_v3d_perfmon_create req = {
38          .ncounters = MIN2(pool->perfmon.ncounters -
39                            i * DRM_V3D_MAX_PERF_COUNTERS,
40                            DRM_V3D_MAX_PERF_COUNTERS),
41       };
42       memcpy(req.counters,
43              &pool->perfmon.counters[i * DRM_V3D_MAX_PERF_COUNTERS],
44              req.ncounters);
45 
46       int ret = v3dv_ioctl(device->pdevice->render_fd,
47                            DRM_IOCTL_V3D_PERFMON_CREATE,
48                            &req);
49       if (ret)
50          fprintf(stderr, "Failed to create perfmon for query %d: %s\n", query,
51                  strerror(errno));
52 
53       pool->queries[query].perf.kperfmon_ids[i] = req.id;
54    }
55 }
56 
57 static void
kperfmon_destroy(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t query)58 kperfmon_destroy(struct v3dv_device *device,
59                  struct v3dv_query_pool *pool,
60                  uint32_t query)
61 {
62    /* Skip destroying if never created */
63    if (!pool->queries[query].perf.kperfmon_ids[0])
64       return;
65 
66    for (uint32_t i = 0; i < pool->perfmon.nperfmons; i++) {
67       struct drm_v3d_perfmon_destroy req = {
68          .id = pool->queries[query].perf.kperfmon_ids[i]
69       };
70 
71       int ret = v3dv_ioctl(device->pdevice->render_fd,
72                            DRM_IOCTL_V3D_PERFMON_DESTROY,
73                            &req);
74 
75       if (ret) {
76          fprintf(stderr, "Failed to destroy perfmon %u: %s\n",
77                  req.id, strerror(errno));
78       }
79    }
80 }
81 
82 /**
83  * Creates a VkBuffer (and VkDeviceMemory) to access a BO.
84  */
85 static VkResult
create_vk_storage_buffer(struct v3dv_device * device,struct v3dv_bo * bo,VkBuffer * vk_buf,VkDeviceMemory * vk_mem)86 create_vk_storage_buffer(struct v3dv_device *device,
87                          struct v3dv_bo *bo,
88                          VkBuffer *vk_buf,
89                          VkDeviceMemory *vk_mem)
90 {
91    VkDevice vk_device = v3dv_device_to_handle(device);
92 
93    VkBufferCreateInfo buf_info = {
94       .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
95       .size = bo->size,
96       .usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
97    };
98    VkResult result = v3dv_CreateBuffer(vk_device, &buf_info, NULL, vk_buf);
99    if (result != VK_SUCCESS)
100       return result;
101 
102    struct v3dv_device_memory *mem =
103       vk_object_zalloc(&device->vk, NULL, sizeof(*mem),
104                        VK_OBJECT_TYPE_DEVICE_MEMORY);
105    if (!mem)
106       return VK_ERROR_OUT_OF_HOST_MEMORY;
107 
108    mem->bo = bo;
109    mem->type = &device->pdevice->memory.memoryTypes[0];
110 
111    *vk_mem = v3dv_device_memory_to_handle(mem);
112    VkBindBufferMemoryInfo bind_info = {
113       .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
114       .buffer = *vk_buf,
115       .memory = *vk_mem,
116       .memoryOffset = 0,
117    };
118    v3dv_BindBufferMemory2(vk_device, 1, &bind_info);
119 
120    return VK_SUCCESS;
121 }
122 
123 static void
destroy_vk_storage_buffer(struct v3dv_device * device,VkBuffer * vk_buf,VkDeviceMemory * vk_mem)124 destroy_vk_storage_buffer(struct v3dv_device *device,
125                           VkBuffer *vk_buf,
126                           VkDeviceMemory *vk_mem)
127 {
128    if (*vk_mem) {
129       vk_object_free(&device->vk, NULL, v3dv_device_memory_from_handle(*vk_mem));
130       *vk_mem = VK_NULL_HANDLE;
131    }
132 
133    v3dv_DestroyBuffer(v3dv_device_to_handle(device), *vk_buf, NULL);
134    *vk_buf = VK_NULL_HANDLE;
135 }
136 
137 /**
138  * Allocates descriptor sets to access query pool BO (availability and
139  * occlusion query results) from Vulkan pipelines.
140  */
141 static VkResult
create_pool_descriptors(struct v3dv_device * device,struct v3dv_query_pool * pool)142 create_pool_descriptors(struct v3dv_device *device,
143                         struct v3dv_query_pool *pool)
144 {
145    assert(pool->query_type == VK_QUERY_TYPE_OCCLUSION);
146    VkDevice vk_device = v3dv_device_to_handle(device);
147 
148    VkDescriptorPoolSize pool_size = {
149       .type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
150       .descriptorCount = 1,
151    };
152    VkDescriptorPoolCreateInfo pool_info = {
153       .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
154       .flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
155       .maxSets = 1,
156       .poolSizeCount = 1,
157       .pPoolSizes = &pool_size,
158    };
159    VkResult result =
160       v3dv_CreateDescriptorPool(vk_device, &pool_info, NULL,
161                                 &pool->meta.descriptor_pool);
162 
163    if (result != VK_SUCCESS)
164       return result;
165 
166    VkDescriptorSetAllocateInfo alloc_info = {
167       .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
168       .descriptorPool = pool->meta.descriptor_pool,
169       .descriptorSetCount = 1,
170       .pSetLayouts = &device->queries.buf_descriptor_set_layout,
171    };
172    result = v3dv_AllocateDescriptorSets(vk_device, &alloc_info,
173                                         &pool->meta.descriptor_set);
174    if (result != VK_SUCCESS)
175       return result;
176 
177    VkDescriptorBufferInfo desc_buf_info = {
178       .buffer = pool->meta.buf,
179       .offset = 0,
180       .range = VK_WHOLE_SIZE,
181    };
182 
183    VkWriteDescriptorSet write = {
184       .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
185       .dstSet = pool->meta.descriptor_set,
186       .dstBinding = 0,
187       .dstArrayElement = 0,
188       .descriptorCount = 1,
189       .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
190       .pBufferInfo = &desc_buf_info,
191    };
192    v3dv_UpdateDescriptorSets(vk_device, 1, &write, 0, NULL);
193 
194    return VK_SUCCESS;
195 }
196 
197 static void
destroy_pool_descriptors(struct v3dv_device * device,struct v3dv_query_pool * pool)198 destroy_pool_descriptors(struct v3dv_device *device,
199                          struct v3dv_query_pool *pool)
200 {
201    assert(pool->query_type == VK_QUERY_TYPE_OCCLUSION);
202 
203    v3dv_FreeDescriptorSets(v3dv_device_to_handle(device),
204                            pool->meta.descriptor_pool,
205                            1, &pool->meta.descriptor_set);
206    pool->meta.descriptor_set = VK_NULL_HANDLE;
207 
208    v3dv_DestroyDescriptorPool(v3dv_device_to_handle(device),
209                               pool->meta.descriptor_pool, NULL);
210    pool->meta.descriptor_pool = VK_NULL_HANDLE;
211 }
212 
213 static VkResult
pool_create_meta_resources(struct v3dv_device * device,struct v3dv_query_pool * pool)214 pool_create_meta_resources(struct v3dv_device *device,
215                            struct v3dv_query_pool *pool)
216 {
217    VkResult result;
218 
219    if (pool->query_type != VK_QUERY_TYPE_OCCLUSION)
220       return VK_SUCCESS;
221 
222    result = create_vk_storage_buffer(device, pool->occlusion.bo,
223                                      &pool->meta.buf, &pool->meta.mem);
224    if (result != VK_SUCCESS)
225       return result;
226 
227    result = create_pool_descriptors(device, pool);
228    if (result != VK_SUCCESS)
229        return result;
230 
231    return VK_SUCCESS;
232 }
233 
234 static void
pool_destroy_meta_resources(struct v3dv_device * device,struct v3dv_query_pool * pool)235 pool_destroy_meta_resources(struct v3dv_device *device,
236                             struct v3dv_query_pool *pool)
237 {
238    if (pool->query_type != VK_QUERY_TYPE_OCCLUSION)
239       return;
240 
241    destroy_pool_descriptors(device, pool);
242    destroy_vk_storage_buffer(device, &pool->meta.buf, &pool->meta.mem);
243 }
244 
245 VKAPI_ATTR VkResult VKAPI_CALL
v3dv_CreateQueryPool(VkDevice _device,const VkQueryPoolCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkQueryPool * pQueryPool)246 v3dv_CreateQueryPool(VkDevice _device,
247                      const VkQueryPoolCreateInfo *pCreateInfo,
248                      const VkAllocationCallbacks *pAllocator,
249                      VkQueryPool *pQueryPool)
250 {
251    V3DV_FROM_HANDLE(v3dv_device, device, _device);
252 
253    assert(pCreateInfo->queryType == VK_QUERY_TYPE_OCCLUSION ||
254           pCreateInfo->queryType == VK_QUERY_TYPE_TIMESTAMP ||
255           pCreateInfo->queryType == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR);
256    assert(pCreateInfo->queryCount > 0);
257 
258    struct v3dv_query_pool *pool =
259       vk_object_zalloc(&device->vk, pAllocator, sizeof(*pool),
260                        VK_OBJECT_TYPE_QUERY_POOL);
261    if (pool == NULL)
262       return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
263 
264    pool->query_type = pCreateInfo->queryType;
265    pool->query_count = pCreateInfo->queryCount;
266 
267    uint32_t query_idx = 0;
268    VkResult result;
269 
270    const uint32_t pool_bytes = sizeof(struct v3dv_query) * pool->query_count;
271    pool->queries = vk_alloc2(&device->vk.alloc, pAllocator, pool_bytes, 8,
272                              VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
273    if (pool->queries == NULL) {
274       result = vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
275       goto fail;
276    }
277 
278    switch (pool->query_type) {
279    case VK_QUERY_TYPE_OCCLUSION: {
280       /* The hardware allows us to setup groups of 16 queries in consecutive
281        * 4-byte addresses, requiring only that each group of 16 queries is
282        * aligned to a 1024 byte boundary.
283        */
284       const uint32_t query_groups = DIV_ROUND_UP(pool->query_count, 16);
285       uint32_t bo_size = query_groups * 1024;
286       /* After the counters we store avalability data, 1 byte/query */
287       pool->occlusion.avail_offset = bo_size;
288       bo_size += pool->query_count;
289       pool->occlusion.bo = v3dv_bo_alloc(device, bo_size, "query:o", true);
290       if (!pool->occlusion.bo) {
291          result = vk_error(device, VK_ERROR_OUT_OF_DEVICE_MEMORY);
292          goto fail;
293       }
294       if (!v3dv_bo_map(device, pool->occlusion.bo, bo_size)) {
295          result = vk_error(device, VK_ERROR_OUT_OF_DEVICE_MEMORY);
296          goto fail;
297       }
298       break;
299    }
300    case VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR: {
301       const VkQueryPoolPerformanceCreateInfoKHR *pq_info =
302          vk_find_struct_const(pCreateInfo->pNext,
303                               QUERY_POOL_PERFORMANCE_CREATE_INFO_KHR);
304 
305       assert(pq_info);
306 
307       pool->perfmon.ncounters = pq_info->counterIndexCount;
308       for (uint32_t i = 0; i < pq_info->counterIndexCount; i++)
309          pool->perfmon.counters[i] = pq_info->pCounterIndices[i];
310 
311       pool->perfmon.nperfmons = DIV_ROUND_UP(pool->perfmon.ncounters,
312                                              DRM_V3D_MAX_PERF_COUNTERS);
313 
314       assert(pool->perfmon.nperfmons <= V3DV_MAX_PERFMONS);
315       break;
316    }
317    case VK_QUERY_TYPE_TIMESTAMP: {
318       /* 8 bytes per query used for the timestamp value. We have all
319        * timestamps tightly packed first in the buffer.
320        */
321       const uint32_t bo_size = pool->query_count * 8;
322       pool->timestamp.bo = v3dv_bo_alloc(device, bo_size, "query:t", true);
323       if (!pool->timestamp.bo) {
324          result = vk_error(device, VK_ERROR_OUT_OF_DEVICE_MEMORY);
325          goto fail;
326       }
327       if (!v3dv_bo_map(device, pool->timestamp.bo, bo_size)) {
328          result = vk_error(device, VK_ERROR_OUT_OF_DEVICE_MEMORY);
329          goto fail;
330       }
331       break;
332    }
333    default:
334       unreachable("Unsupported query type");
335    }
336 
337    /* Initialize queries in the pool */
338    for (; query_idx < pool->query_count; query_idx++) {
339       pool->queries[query_idx].maybe_available = false;
340       switch (pool->query_type) {
341       case VK_QUERY_TYPE_OCCLUSION: {
342          const uint32_t query_group = query_idx / 16;
343          const uint32_t query_offset = query_group * 1024 + (query_idx % 16) * 4;
344          pool->queries[query_idx].occlusion.offset = query_offset;
345          break;
346          }
347       case VK_QUERY_TYPE_TIMESTAMP:
348          pool->queries[query_idx].timestamp.offset = query_idx * 8;
349          result = vk_sync_create(&device->vk,
350                                  &device->pdevice->drm_syncobj_type, 0, 0,
351                                  &pool->queries[query_idx].timestamp.sync);
352          if (result != VK_SUCCESS)
353             goto fail;
354          break;
355       case VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR: {
356          result = vk_sync_create(&device->vk,
357                                  &device->pdevice->drm_syncobj_type, 0, 0,
358                                  &pool->queries[query_idx].perf.last_job_sync);
359          if (result != VK_SUCCESS)
360             goto fail;
361 
362          kperfmon_create(device, pool, query_idx);
363          break;
364          }
365       default:
366          unreachable("Unsupported query type");
367       }
368    }
369 
370    /* Create meta resources */
371    result = pool_create_meta_resources(device, pool);
372    if (result != VK_SUCCESS)
373       goto fail;
374 
375    *pQueryPool = v3dv_query_pool_to_handle(pool);
376 
377    return VK_SUCCESS;
378 
379 fail:
380    if (pool->query_type == VK_QUERY_TYPE_TIMESTAMP) {
381       for (uint32_t j = 0; j < query_idx; j++)
382          vk_sync_destroy(&device->vk, pool->queries[j].timestamp.sync);
383    }
384 
385    if (pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) {
386       for (uint32_t j = 0; j < query_idx; j++)
387          vk_sync_destroy(&device->vk, pool->queries[j].perf.last_job_sync);
388    }
389 
390    if (pool->occlusion.bo)
391       v3dv_bo_free(device, pool->occlusion.bo);
392    if (pool->timestamp.bo)
393       v3dv_bo_free(device, pool->timestamp.bo);
394    if (pool->queries)
395       vk_free2(&device->vk.alloc, pAllocator, pool->queries);
396    pool_destroy_meta_resources(device, pool);
397    vk_object_free(&device->vk, pAllocator, pool);
398 
399    return result;
400 }
401 
402 VKAPI_ATTR void VKAPI_CALL
v3dv_DestroyQueryPool(VkDevice _device,VkQueryPool queryPool,const VkAllocationCallbacks * pAllocator)403 v3dv_DestroyQueryPool(VkDevice _device,
404                       VkQueryPool queryPool,
405                       const VkAllocationCallbacks *pAllocator)
406 {
407    V3DV_FROM_HANDLE(v3dv_device, device, _device);
408    V3DV_FROM_HANDLE(v3dv_query_pool, pool, queryPool);
409 
410    if (!pool)
411       return;
412 
413    if (pool->occlusion.bo)
414       v3dv_bo_free(device, pool->occlusion.bo);
415 
416    if (pool->timestamp.bo)
417       v3dv_bo_free(device, pool->timestamp.bo);
418 
419    if (pool->query_type == VK_QUERY_TYPE_TIMESTAMP) {
420       for (uint32_t i = 0; i < pool->query_count; i++)
421          vk_sync_destroy(&device->vk, pool->queries[i].timestamp.sync);
422    }
423 
424    if (pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) {
425       for (uint32_t i = 0; i < pool->query_count; i++) {
426          kperfmon_destroy(device, pool, i);
427          vk_sync_destroy(&device->vk, pool->queries[i].perf.last_job_sync);
428       }
429    }
430 
431    if (pool->queries)
432       vk_free2(&device->vk.alloc, pAllocator, pool->queries);
433 
434    pool_destroy_meta_resources(device, pool);
435 
436    vk_object_free(&device->vk, pAllocator, pool);
437 }
438 
439 static void
write_to_buffer(void * dst,uint32_t idx,bool do_64bit,uint64_t value)440 write_to_buffer(void *dst, uint32_t idx, bool do_64bit, uint64_t value)
441 {
442    if (do_64bit) {
443       uint64_t *dst64 = (uint64_t *) dst;
444       dst64[idx] = value;
445    } else {
446       uint32_t *dst32 = (uint32_t *) dst;
447       dst32[idx] = (uint32_t) value;
448    }
449 }
450 
451 static VkResult
query_wait_available(struct v3dv_device * device,struct v3dv_query_pool * pool,struct v3dv_query * q,uint32_t query_idx)452 query_wait_available(struct v3dv_device *device,
453                      struct v3dv_query_pool *pool,
454                      struct v3dv_query *q,
455                      uint32_t query_idx)
456 {
457    /* For occlusion queries we prefer to poll the availability BO in a loop
458     * to waiting on the query results BO, because the latter would
459     * make us wait for any job running queries from the pool, even if those
460     * queries do not involve the one we want to wait on.
461     */
462    if (pool->query_type == VK_QUERY_TYPE_OCCLUSION) {
463       uint8_t *q_addr = ((uint8_t *) pool->occlusion.bo->map) +
464                         pool->occlusion.avail_offset + query_idx;
465       while (*q_addr == 0)
466          usleep(250);
467       return VK_SUCCESS;
468    }
469 
470    if (pool->query_type == VK_QUERY_TYPE_TIMESTAMP) {
471       if (vk_sync_wait(&device->vk, q->timestamp.sync,
472                        0, VK_SYNC_WAIT_COMPLETE, UINT64_MAX) != VK_SUCCESS) {
473          return vk_device_set_lost(&device->vk, "Query job wait failed");
474       }
475       return VK_SUCCESS;
476    }
477 
478    assert(pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR);
479 
480    /* For performance queries we need to wait for the queue to signal that
481     * the query has been submitted for execution before anything else.
482     */
483    VkResult result = VK_SUCCESS;
484    if (!q->maybe_available) {
485       struct timespec timeout;
486       timespec_get(&timeout, TIME_UTC);
487       timespec_add_msec(&timeout, &timeout, 2000);
488 
489       mtx_lock(&device->query_mutex);
490       while (!q->maybe_available) {
491          if (vk_device_is_lost(&device->vk)) {
492             result = VK_ERROR_DEVICE_LOST;
493             break;
494          }
495 
496          int ret = cnd_timedwait(&device->query_ended,
497                                  &device->query_mutex,
498                                  &timeout);
499          if (ret != thrd_success) {
500             mtx_unlock(&device->query_mutex);
501             result = vk_device_set_lost(&device->vk, "Query wait failed");
502             break;
503          }
504       }
505       mtx_unlock(&device->query_mutex);
506 
507       if (result != VK_SUCCESS)
508          return result;
509 
510       /* For performance queries, we also need to wait for the relevant syncobj
511        * to be signaled to ensure completion of the GPU work.
512        */
513       if (pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR &&
514           vk_sync_wait(&device->vk, q->perf.last_job_sync,
515                        0, VK_SYNC_WAIT_COMPLETE, UINT64_MAX) != VK_SUCCESS) {
516         return vk_device_set_lost(&device->vk, "Query job wait failed");
517       }
518    }
519 
520    return result;
521 }
522 
523 static VkResult
query_check_available(struct v3dv_device * device,struct v3dv_query_pool * pool,struct v3dv_query * q,uint32_t query_idx)524 query_check_available(struct v3dv_device *device,
525                       struct v3dv_query_pool *pool,
526                       struct v3dv_query *q,
527                       uint32_t query_idx)
528 {
529    /* For occlusion we check the availability BO */
530    if (pool->query_type == VK_QUERY_TYPE_OCCLUSION) {
531       const uint8_t *q_addr = ((uint8_t *) pool->occlusion.bo->map) +
532                               pool->occlusion.avail_offset + query_idx;
533       return (*q_addr != 0) ? VK_SUCCESS : VK_NOT_READY;
534    }
535 
536    /* For timestamp queries, we need to check if the relevant job
537     * has completed.
538     */
539    if (pool->query_type == VK_QUERY_TYPE_TIMESTAMP) {
540       if (vk_sync_wait(&device->vk, q->timestamp.sync,
541                        0, VK_SYNC_WAIT_COMPLETE, 0) != VK_SUCCESS) {
542          return VK_NOT_READY;
543       }
544       return VK_SUCCESS;
545    }
546 
547    /* For other queries we need to check if the queue has submitted the query
548     * for execution at all.
549     */
550    assert(pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR);
551    if (!q->maybe_available)
552       return VK_NOT_READY;
553 
554    /* For performance queries, we also need to check if the relevant GPU job
555     * has completed.
556     */
557    if (pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR &&
558        vk_sync_wait(&device->vk, q->perf.last_job_sync,
559                     0, VK_SYNC_WAIT_COMPLETE, 0) != VK_SUCCESS) {
560          return VK_NOT_READY;
561    }
562 
563    return VK_SUCCESS;
564 }
565 
566 static VkResult
query_is_available(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t query,bool do_wait,bool * available)567 query_is_available(struct v3dv_device *device,
568                    struct v3dv_query_pool *pool,
569                    uint32_t query,
570                    bool do_wait,
571                    bool *available)
572 {
573    struct v3dv_query *q = &pool->queries[query];
574 
575    if (do_wait) {
576       VkResult result = query_wait_available(device, pool, q, query);
577       if (result != VK_SUCCESS) {
578          *available = false;
579          return result;
580       }
581 
582       *available = true;
583    } else {
584       VkResult result = query_check_available(device, pool, q, query);
585       assert(result == VK_SUCCESS || result == VK_NOT_READY);
586       *available = (result == VK_SUCCESS);
587    }
588 
589    return VK_SUCCESS;
590 }
591 
592 static VkResult
write_occlusion_query_result(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t query,bool do_64bit,void * data,uint32_t slot)593 write_occlusion_query_result(struct v3dv_device *device,
594                              struct v3dv_query_pool *pool,
595                              uint32_t query,
596                              bool do_64bit,
597                              void *data,
598                              uint32_t slot)
599 {
600    assert(pool && pool->query_type == VK_QUERY_TYPE_OCCLUSION);
601 
602    if (vk_device_is_lost(&device->vk))
603       return VK_ERROR_DEVICE_LOST;
604 
605    struct v3dv_query *q = &pool->queries[query];
606    assert(pool->occlusion.bo && pool->occlusion.bo->map);
607 
608    const uint8_t *query_addr =
609       ((uint8_t *) pool->occlusion.bo->map) + q->occlusion.offset;
610    write_to_buffer(data, slot, do_64bit, (uint64_t) *((uint32_t *)query_addr));
611    return VK_SUCCESS;
612 }
613 
614 static VkResult
write_timestamp_query_result(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t query,bool do_64bit,void * data,uint32_t slot)615 write_timestamp_query_result(struct v3dv_device *device,
616                              struct v3dv_query_pool *pool,
617                              uint32_t query,
618                              bool do_64bit,
619                              void *data,
620                              uint32_t slot)
621 {
622    assert(pool && pool->query_type == VK_QUERY_TYPE_TIMESTAMP);
623 
624    struct v3dv_query *q = &pool->queries[query];
625 
626    const uint8_t *query_addr =
627       ((uint8_t *) pool->timestamp.bo->map) + q->timestamp.offset;
628 
629    write_to_buffer(data, slot, do_64bit, *((uint64_t *)query_addr));
630    return VK_SUCCESS;
631 }
632 
633 static VkResult
write_performance_query_result(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t query,bool do_64bit,void * data,uint32_t slot)634 write_performance_query_result(struct v3dv_device *device,
635                                struct v3dv_query_pool *pool,
636                                uint32_t query,
637                                bool do_64bit,
638                                void *data,
639                                uint32_t slot)
640 {
641    assert(pool && pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR);
642 
643    struct v3dv_query *q = &pool->queries[query];
644    uint64_t counter_values[V3D_MAX_PERFCNT];
645 
646    for (uint32_t i = 0; i < pool->perfmon.nperfmons; i++) {
647       struct drm_v3d_perfmon_get_values req = {
648          .id = q->perf.kperfmon_ids[i],
649          .values_ptr = (uintptr_t)(&counter_values[i *
650                                    DRM_V3D_MAX_PERF_COUNTERS])
651       };
652 
653       int ret = v3dv_ioctl(device->pdevice->render_fd,
654                            DRM_IOCTL_V3D_PERFMON_GET_VALUES,
655                            &req);
656 
657       if (ret) {
658          fprintf(stderr, "failed to get perfmon values: %s\n", strerror(errno));
659          return vk_error(device, VK_ERROR_DEVICE_LOST);
660       }
661    }
662 
663    for (uint32_t i = 0; i < pool->perfmon.ncounters; i++)
664       write_to_buffer(data, slot + i, do_64bit, counter_values[i]);
665 
666    return VK_SUCCESS;
667 }
668 
669 static VkResult
write_query_result(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t query,bool do_64bit,void * data,uint32_t slot)670 write_query_result(struct v3dv_device *device,
671                    struct v3dv_query_pool *pool,
672                    uint32_t query,
673                    bool do_64bit,
674                    void *data,
675                    uint32_t slot)
676 {
677    switch (pool->query_type) {
678    case VK_QUERY_TYPE_OCCLUSION:
679       return write_occlusion_query_result(device, pool, query, do_64bit,
680                                           data, slot);
681    case VK_QUERY_TYPE_TIMESTAMP:
682       return write_timestamp_query_result(device, pool, query, do_64bit,
683                                           data, slot);
684    case VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR:
685       return write_performance_query_result(device, pool, query, do_64bit,
686                                             data, slot);
687    default:
688       unreachable("Unsupported query type");
689    }
690 }
691 
692 static uint32_t
get_query_result_count(struct v3dv_query_pool * pool)693 get_query_result_count(struct v3dv_query_pool *pool)
694 {
695    switch (pool->query_type) {
696    case VK_QUERY_TYPE_OCCLUSION:
697    case VK_QUERY_TYPE_TIMESTAMP:
698       return 1;
699    case VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR:
700       return pool->perfmon.ncounters;
701    default:
702       unreachable("Unsupported query type");
703    }
704 }
705 
706 VkResult
v3dv_get_query_pool_results_cpu(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t first,uint32_t count,void * data,VkDeviceSize stride,VkQueryResultFlags flags)707 v3dv_get_query_pool_results_cpu(struct v3dv_device *device,
708                                 struct v3dv_query_pool *pool,
709                                 uint32_t first,
710                                 uint32_t count,
711                                 void *data,
712                                 VkDeviceSize stride,
713                                 VkQueryResultFlags flags)
714 {
715    assert(first < pool->query_count);
716    assert(first + count <= pool->query_count);
717    assert(data);
718 
719    const bool do_64bit = flags & VK_QUERY_RESULT_64_BIT ||
720       pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR;
721    const bool do_wait = flags & VK_QUERY_RESULT_WAIT_BIT;
722    const bool do_partial = flags & VK_QUERY_RESULT_PARTIAL_BIT;
723 
724    uint32_t result_count = get_query_result_count(pool);
725 
726    VkResult result = VK_SUCCESS;
727    for (uint32_t i = first; i < first + count; i++) {
728       bool available = false;
729       VkResult query_result =
730          query_is_available(device, pool, i, do_wait, &available);
731       if (query_result == VK_ERROR_DEVICE_LOST)
732          result = VK_ERROR_DEVICE_LOST;
733 
734       /**
735        * From the Vulkan 1.0 spec:
736        *
737        *    "If VK_QUERY_RESULT_WAIT_BIT and VK_QUERY_RESULT_PARTIAL_BIT are
738        *     both not set then no result values are written to pData for queries
739        *     that are in the unavailable state at the time of the call, and
740        *     vkGetQueryPoolResults returns VK_NOT_READY. However, availability
741        *     state is still written to pData for those queries if
742        *     VK_QUERY_RESULT_WITH_AVAILABILITY_BIT is set."
743        */
744       uint32_t slot = 0;
745 
746       const bool write_result = available || do_partial;
747       if (write_result)
748          write_query_result(device, pool, i, do_64bit, data, slot);
749       slot += result_count;
750 
751       if (flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT)
752          write_to_buffer(data, slot++, do_64bit, available ? 1u : 0u);
753 
754       if (!write_result && result != VK_ERROR_DEVICE_LOST)
755          result = VK_NOT_READY;
756 
757       data += stride;
758    }
759 
760    return result;
761 }
762 
763 VKAPI_ATTR VkResult VKAPI_CALL
v3dv_GetQueryPoolResults(VkDevice _device,VkQueryPool queryPool,uint32_t firstQuery,uint32_t queryCount,size_t dataSize,void * pData,VkDeviceSize stride,VkQueryResultFlags flags)764 v3dv_GetQueryPoolResults(VkDevice _device,
765                          VkQueryPool queryPool,
766                          uint32_t firstQuery,
767                          uint32_t queryCount,
768                          size_t dataSize,
769                          void *pData,
770                          VkDeviceSize stride,
771                          VkQueryResultFlags flags)
772 {
773    V3DV_FROM_HANDLE(v3dv_device, device, _device);
774    V3DV_FROM_HANDLE(v3dv_query_pool, pool, queryPool);
775 
776    if (vk_device_is_lost(&device->vk))
777       return VK_ERROR_DEVICE_LOST;
778 
779    return v3dv_get_query_pool_results_cpu(device, pool, firstQuery, queryCount,
780                                           pData, stride, flags);
781 }
782 
783 /* Emits a series of vkCmdDispatchBase calls to execute all the workgroups
784  * required to handle a number of queries considering per-dispatch limits.
785  */
786 static void
cmd_buffer_emit_dispatch_queries(struct v3dv_cmd_buffer * cmd_buffer,uint32_t query_count)787 cmd_buffer_emit_dispatch_queries(struct v3dv_cmd_buffer *cmd_buffer,
788                                  uint32_t query_count)
789 {
790    VkCommandBuffer vk_cmd_buffer = v3dv_cmd_buffer_to_handle(cmd_buffer);
791 
792    uint32_t dispatched = 0;
793    const uint32_t max_batch_size = 65535;
794    while (dispatched < query_count) {
795       uint32_t batch_size = MIN2(query_count - dispatched, max_batch_size);
796       v3dv_CmdDispatchBase(vk_cmd_buffer, dispatched, 0, 0, batch_size, 1, 1);
797       dispatched += batch_size;
798    }
799 }
800 
801 void
v3dv_cmd_buffer_emit_set_query_availability(struct v3dv_cmd_buffer * cmd_buffer,struct v3dv_query_pool * pool,uint32_t query,uint32_t count,uint8_t availability)802 v3dv_cmd_buffer_emit_set_query_availability(struct v3dv_cmd_buffer *cmd_buffer,
803                                             struct v3dv_query_pool *pool,
804                                             uint32_t query, uint32_t count,
805                                             uint8_t availability)
806 {
807    assert(pool->query_type == VK_QUERY_TYPE_OCCLUSION ||
808           pool->query_type == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR);
809 
810    struct v3dv_device *device = cmd_buffer->device;
811    VkCommandBuffer vk_cmd_buffer = v3dv_cmd_buffer_to_handle(cmd_buffer);
812 
813    /* We are about to emit a compute job to set query availability and we need
814     * to ensure this executes after the graphics work using the queries has
815     * completed.
816     */
817    VkMemoryBarrier2 barrier = {
818       .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
819       .srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
820       .dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
821    };
822    VkDependencyInfo barrier_info = {
823       .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
824       .memoryBarrierCount = 1,
825       .pMemoryBarriers = &barrier,
826    };
827    v3dv_cmd_buffer_emit_pipeline_barrier(cmd_buffer, &barrier_info);
828 
829    /* Dispatch queries */
830    v3dv_cmd_buffer_meta_state_push(cmd_buffer, true);
831 
832    v3dv_CmdBindPipeline(vk_cmd_buffer,
833                         VK_PIPELINE_BIND_POINT_COMPUTE,
834                         device->queries.avail_pipeline);
835 
836    v3dv_CmdBindDescriptorSets(vk_cmd_buffer,
837                               VK_PIPELINE_BIND_POINT_COMPUTE,
838                               device->queries.avail_pipeline_layout,
839                               0, 1, &pool->meta.descriptor_set,
840                               0, NULL);
841 
842    struct {
843       uint32_t offset;
844       uint32_t query;
845       uint8_t availability;
846    } push_data = { pool->occlusion.avail_offset, query, availability };
847    v3dv_CmdPushConstants(vk_cmd_buffer,
848                          device->queries.avail_pipeline_layout,
849                          VK_SHADER_STAGE_COMPUTE_BIT,
850                          0, sizeof(push_data), &push_data);
851    cmd_buffer_emit_dispatch_queries(cmd_buffer, count);
852 
853    v3dv_cmd_buffer_meta_state_pop(cmd_buffer, false);
854 }
855 
856 static void
cmd_buffer_emit_reset_occlusion_query_pool(struct v3dv_cmd_buffer * cmd_buffer,struct v3dv_query_pool * pool,uint32_t query,uint32_t count)857 cmd_buffer_emit_reset_occlusion_query_pool(struct v3dv_cmd_buffer *cmd_buffer,
858                                            struct v3dv_query_pool *pool,
859                                            uint32_t query, uint32_t count)
860 {
861    struct v3dv_device *device = cmd_buffer->device;
862    VkCommandBuffer vk_cmd_buffer = v3dv_cmd_buffer_to_handle(cmd_buffer);
863 
864    /* Ensure the GPU is done with the queries in the graphics queue before
865     * we reset in the compute queue.
866     */
867    VkMemoryBarrier2 barrier = {
868       .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
869       .srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
870       .dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
871    };
872    VkDependencyInfo barrier_info = {
873       .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
874       .memoryBarrierCount = 1,
875       .pMemoryBarriers = &barrier,
876    };
877    v3dv_cmd_buffer_emit_pipeline_barrier(cmd_buffer, &barrier_info);
878 
879    /* Emit compute reset */
880    v3dv_cmd_buffer_meta_state_push(cmd_buffer, true);
881 
882    v3dv_CmdBindPipeline(vk_cmd_buffer,
883                         VK_PIPELINE_BIND_POINT_COMPUTE,
884                         device->queries.reset_occlusion_pipeline);
885 
886    v3dv_CmdBindDescriptorSets(vk_cmd_buffer,
887                               VK_PIPELINE_BIND_POINT_COMPUTE,
888                               device->queries.reset_occlusion_pipeline_layout,
889                               0, 1, &pool->meta.descriptor_set,
890                               0, NULL);
891    struct {
892       uint32_t offset;
893       uint32_t query;
894    } push_data = { pool->occlusion.avail_offset, query };
895    v3dv_CmdPushConstants(vk_cmd_buffer,
896                          device->queries.reset_occlusion_pipeline_layout,
897                          VK_SHADER_STAGE_COMPUTE_BIT,
898                          0, sizeof(push_data), &push_data);
899 
900    cmd_buffer_emit_dispatch_queries(cmd_buffer, count);
901 
902    v3dv_cmd_buffer_meta_state_pop(cmd_buffer, false);
903 
904    /* Ensure future work in the graphics queue using the queries doesn't start
905     * before the reset completed.
906     */
907    barrier = (VkMemoryBarrier2) {
908       .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
909       .srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
910       .dstStageMask = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT,
911    };
912    barrier_info = (VkDependencyInfo) {
913       .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
914       .memoryBarrierCount = 1,
915       .pMemoryBarriers = &barrier,
916    };
917    v3dv_cmd_buffer_emit_pipeline_barrier(cmd_buffer, &barrier_info);
918 }
919 
920 static void
cmd_buffer_emit_reset_query_pool(struct v3dv_cmd_buffer * cmd_buffer,struct v3dv_query_pool * pool,uint32_t first,uint32_t count)921 cmd_buffer_emit_reset_query_pool(struct v3dv_cmd_buffer *cmd_buffer,
922                                  struct v3dv_query_pool *pool,
923                                  uint32_t first, uint32_t count)
924 {
925    assert(pool->query_type == VK_QUERY_TYPE_OCCLUSION);
926    cmd_buffer_emit_reset_occlusion_query_pool(cmd_buffer, pool, first, count);
927 }
928 
929 static void
cmd_buffer_emit_reset_query_pool_cpu(struct v3dv_cmd_buffer * cmd_buffer,struct v3dv_query_pool * pool,uint32_t first,uint32_t count)930 cmd_buffer_emit_reset_query_pool_cpu(struct v3dv_cmd_buffer *cmd_buffer,
931                                      struct v3dv_query_pool *pool,
932                                      uint32_t first, uint32_t count)
933 {
934    assert(pool->query_type != VK_QUERY_TYPE_OCCLUSION);
935 
936    struct v3dv_job *job =
937       v3dv_cmd_buffer_create_cpu_job(cmd_buffer->device,
938                                      V3DV_JOB_TYPE_CPU_RESET_QUERIES,
939                                      cmd_buffer, -1);
940    v3dv_return_if_oom(cmd_buffer, NULL);
941    job->cpu.query_reset.pool = pool;
942    job->cpu.query_reset.first = first;
943    job->cpu.query_reset.count = count;
944    list_addtail(&job->list_link, &cmd_buffer->jobs);
945 }
946 
947 VKAPI_ATTR void VKAPI_CALL
v3dv_CmdResetQueryPool(VkCommandBuffer commandBuffer,VkQueryPool queryPool,uint32_t firstQuery,uint32_t queryCount)948 v3dv_CmdResetQueryPool(VkCommandBuffer commandBuffer,
949                        VkQueryPool queryPool,
950                        uint32_t firstQuery,
951                        uint32_t queryCount)
952 {
953    V3DV_FROM_HANDLE(v3dv_cmd_buffer, cmd_buffer, commandBuffer);
954    V3DV_FROM_HANDLE(v3dv_query_pool, pool, queryPool);
955 
956    /* Resets can only happen outside a render pass instance so we should not
957     * be in the middle of job recording.
958     */
959    assert(cmd_buffer->state.pass == NULL);
960    assert(cmd_buffer->state.job == NULL);
961 
962    assert(firstQuery < pool->query_count);
963    assert(firstQuery + queryCount <= pool->query_count);
964 
965    /* We can reset occlusion queries in the GPU, but for other query types
966     * we emit a CPU job that will call v3dv_reset_query_pool_cpu when executed
967     * in the queue.
968     */
969    if (pool->query_type == VK_QUERY_TYPE_OCCLUSION) {
970       cmd_buffer_emit_reset_query_pool(cmd_buffer, pool, firstQuery, queryCount);
971    } else {
972       cmd_buffer_emit_reset_query_pool_cpu(cmd_buffer, pool,
973                                            firstQuery, queryCount);
974    }
975 }
976 
977 /**
978  * Creates a descriptor pool so we can create a descriptors for the destination
979  * buffers of vkCmdCopyQueryResults for queries where this is implemented in
980  * the GPU.
981  */
982 static VkResult
create_storage_buffer_descriptor_pool(struct v3dv_cmd_buffer * cmd_buffer)983 create_storage_buffer_descriptor_pool(struct v3dv_cmd_buffer *cmd_buffer)
984 {
985    /* If this is not the first pool we create one for this command buffer
986     * size it based on the size of the currently exhausted pool.
987     */
988    uint32_t descriptor_count = 32;
989    if (cmd_buffer->meta.query.dspool != VK_NULL_HANDLE) {
990       struct v3dv_descriptor_pool *exhausted_pool =
991          v3dv_descriptor_pool_from_handle(cmd_buffer->meta.query.dspool);
992       descriptor_count = MIN2(exhausted_pool->max_entry_count * 2, 1024);
993    }
994 
995    /* Create the descriptor pool */
996    cmd_buffer->meta.query.dspool = VK_NULL_HANDLE;
997    VkDescriptorPoolSize pool_size = {
998       .type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
999       .descriptorCount = descriptor_count,
1000    };
1001    VkDescriptorPoolCreateInfo info = {
1002       .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
1003       .maxSets = descriptor_count,
1004       .poolSizeCount = 1,
1005       .pPoolSizes = &pool_size,
1006       .flags = 0,
1007    };
1008    VkResult result =
1009       v3dv_CreateDescriptorPool(v3dv_device_to_handle(cmd_buffer->device),
1010                                 &info,
1011                                 &cmd_buffer->device->vk.alloc,
1012                                 &cmd_buffer->meta.query.dspool);
1013 
1014    if (result == VK_SUCCESS) {
1015       assert(cmd_buffer->meta.query.dspool != VK_NULL_HANDLE);
1016       const VkDescriptorPool vk_pool = cmd_buffer->meta.query.dspool;
1017 
1018       v3dv_cmd_buffer_add_private_obj(
1019          cmd_buffer, (uintptr_t) vk_pool,
1020          (v3dv_cmd_buffer_private_obj_destroy_cb)v3dv_DestroyDescriptorPool);
1021 
1022       struct v3dv_descriptor_pool *pool =
1023          v3dv_descriptor_pool_from_handle(vk_pool);
1024       pool->is_driver_internal = true;
1025    }
1026 
1027    return result;
1028 }
1029 
1030 static VkResult
allocate_storage_buffer_descriptor_set(struct v3dv_cmd_buffer * cmd_buffer,VkDescriptorSet * set)1031 allocate_storage_buffer_descriptor_set(struct v3dv_cmd_buffer *cmd_buffer,
1032                                        VkDescriptorSet *set)
1033 {
1034    /* Make sure we have a descriptor pool */
1035    VkResult result;
1036    if (cmd_buffer->meta.query.dspool == VK_NULL_HANDLE) {
1037       result = create_storage_buffer_descriptor_pool(cmd_buffer);
1038       if (result != VK_SUCCESS)
1039          return result;
1040    }
1041    assert(cmd_buffer->meta.query.dspool != VK_NULL_HANDLE);
1042 
1043    /* Allocate descriptor set */
1044    struct v3dv_device *device = cmd_buffer->device;
1045    VkDevice vk_device = v3dv_device_to_handle(device);
1046    VkDescriptorSetAllocateInfo info = {
1047       .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
1048       .descriptorPool = cmd_buffer->meta.query.dspool,
1049       .descriptorSetCount = 1,
1050       .pSetLayouts = &device->queries.buf_descriptor_set_layout,
1051    };
1052    result = v3dv_AllocateDescriptorSets(vk_device, &info, set);
1053 
1054    /* If we ran out of pool space, grow the pool and try again */
1055    if (result == VK_ERROR_OUT_OF_POOL_MEMORY) {
1056       result = create_storage_buffer_descriptor_pool(cmd_buffer);
1057       if (result == VK_SUCCESS) {
1058          info.descriptorPool = cmd_buffer->meta.query.dspool;
1059          result = v3dv_AllocateDescriptorSets(vk_device, &info, set);
1060       }
1061    }
1062 
1063    return result;
1064 }
1065 
1066 static uint32_t
copy_pipeline_index_from_flags(VkQueryResultFlags flags)1067 copy_pipeline_index_from_flags(VkQueryResultFlags flags)
1068 {
1069    uint32_t index = 0;
1070    if (flags & VK_QUERY_RESULT_64_BIT)
1071       index |= 1;
1072    if (flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT)
1073       index |= 2;
1074    if (flags & VK_QUERY_RESULT_PARTIAL_BIT)
1075       index |= 4;
1076    assert(index < 8);
1077    return index;
1078 }
1079 
1080 static nir_shader *
1081 get_copy_query_results_cs(const nir_shader_compiler_options *compiler_options,
1082                           VkQueryResultFlags flags);
1083 
1084 static void
cmd_buffer_emit_copy_query_pool_results(struct v3dv_cmd_buffer * cmd_buffer,struct v3dv_query_pool * pool,uint32_t first,uint32_t count,struct v3dv_buffer * buf,uint32_t offset,uint32_t stride,VkQueryResultFlags flags)1085 cmd_buffer_emit_copy_query_pool_results(struct v3dv_cmd_buffer *cmd_buffer,
1086                                         struct v3dv_query_pool *pool,
1087                                         uint32_t first, uint32_t count,
1088                                         struct v3dv_buffer *buf,
1089                                         uint32_t offset, uint32_t stride,
1090                                         VkQueryResultFlags flags)
1091 {
1092    struct v3dv_device *device = cmd_buffer->device;
1093    VkDevice vk_device = v3dv_device_to_handle(device);
1094    VkCommandBuffer vk_cmd_buffer = v3dv_cmd_buffer_to_handle(cmd_buffer);
1095 
1096    /* Create the required copy pipeline if not yet created */
1097    uint32_t pipeline_idx = copy_pipeline_index_from_flags(flags);
1098    if (!device->queries.copy_pipeline[pipeline_idx]) {
1099       const nir_shader_compiler_options *compiler_options =
1100          v3dv_pipeline_get_nir_options(&device->devinfo);
1101       nir_shader *copy_query_results_cs_nir =
1102          get_copy_query_results_cs(compiler_options, flags);
1103       VkResult result =
1104          v3dv_create_compute_pipeline_from_nir(
1105                device, copy_query_results_cs_nir,
1106                device->queries.copy_pipeline_layout,
1107                &device->queries.copy_pipeline[pipeline_idx]);
1108       ralloc_free(copy_query_results_cs_nir);
1109       if (result != VK_SUCCESS) {
1110          fprintf(stderr, "Failed to create copy query results pipeline\n");
1111          return;
1112       }
1113    }
1114 
1115    /* FIXME: do we need this barrier? Since vkCmdEndQuery should've been called
1116     * and that already waits maybe we don't (since this is serialized
1117     * in the compute queue with EndQuery anyway).
1118     */
1119    if (flags & VK_QUERY_RESULT_WAIT_BIT) {
1120       VkMemoryBarrier2 barrier = {
1121          .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
1122          .srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
1123          .dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
1124       };
1125       VkDependencyInfo barrier_info = {
1126          .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
1127          .memoryBarrierCount = 1,
1128          .pMemoryBarriers = &barrier,
1129       };
1130       v3dv_cmd_buffer_emit_pipeline_barrier(cmd_buffer, &barrier_info);
1131    }
1132 
1133    /* Allocate and setup descriptor set for output buffer */
1134    VkDescriptorSet out_buf_descriptor_set;
1135    VkResult result =
1136       allocate_storage_buffer_descriptor_set(cmd_buffer,
1137                                              &out_buf_descriptor_set);
1138    if (result != VK_SUCCESS) {
1139       fprintf(stderr, "vkCmdCopyQueryPoolResults failed: "
1140               "could not allocate descriptor.\n");
1141       return;
1142    }
1143 
1144    VkDescriptorBufferInfo desc_buf_info = {
1145       .buffer = v3dv_buffer_to_handle(buf),
1146       .offset = 0,
1147       .range = VK_WHOLE_SIZE,
1148    };
1149    VkWriteDescriptorSet write = {
1150       .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
1151       .dstSet = out_buf_descriptor_set,
1152       .dstBinding = 0,
1153       .dstArrayElement = 0,
1154       .descriptorCount = 1,
1155       .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
1156       .pBufferInfo = &desc_buf_info,
1157    };
1158    v3dv_UpdateDescriptorSets(vk_device, 1, &write, 0, NULL);
1159 
1160    /* Dispatch copy */
1161    v3dv_cmd_buffer_meta_state_push(cmd_buffer, true);
1162 
1163    assert(device->queries.copy_pipeline[pipeline_idx]);
1164    v3dv_CmdBindPipeline(vk_cmd_buffer,
1165                         VK_PIPELINE_BIND_POINT_COMPUTE,
1166                         device->queries.copy_pipeline[pipeline_idx]);
1167 
1168    VkDescriptorSet sets[2] = {
1169       pool->meta.descriptor_set,
1170       out_buf_descriptor_set,
1171    };
1172    v3dv_CmdBindDescriptorSets(vk_cmd_buffer,
1173                               VK_PIPELINE_BIND_POINT_COMPUTE,
1174                               device->queries.copy_pipeline_layout,
1175                               0, 2, sets, 0, NULL);
1176 
1177    struct {
1178       uint32_t avail_offset, first, offset, stride, flags;
1179    } push_data = { pool->occlusion.avail_offset, first, offset, stride, flags };
1180    v3dv_CmdPushConstants(vk_cmd_buffer,
1181                          device->queries.copy_pipeline_layout,
1182                          VK_SHADER_STAGE_COMPUTE_BIT,
1183                          0, sizeof(push_data), &push_data);
1184 
1185    cmd_buffer_emit_dispatch_queries(cmd_buffer, count);
1186 
1187    v3dv_cmd_buffer_meta_state_pop(cmd_buffer, false);
1188 }
1189 
1190 static void
cmd_buffer_emit_copy_query_pool_results_cpu(struct v3dv_cmd_buffer * cmd_buffer,struct v3dv_query_pool * pool,uint32_t first,uint32_t count,struct v3dv_buffer * dst,uint32_t offset,uint32_t stride,VkQueryResultFlags flags)1191 cmd_buffer_emit_copy_query_pool_results_cpu(struct v3dv_cmd_buffer *cmd_buffer,
1192                                             struct v3dv_query_pool *pool,
1193                                             uint32_t first,
1194                                             uint32_t count,
1195                                             struct v3dv_buffer *dst,
1196                                             uint32_t offset,
1197                                             uint32_t stride,
1198                                             VkQueryResultFlags flags)
1199 {
1200    struct v3dv_job *job =
1201       v3dv_cmd_buffer_create_cpu_job(cmd_buffer->device,
1202                                      V3DV_JOB_TYPE_CPU_COPY_QUERY_RESULTS,
1203                                      cmd_buffer, -1);
1204    v3dv_return_if_oom(cmd_buffer, NULL);
1205 
1206    job->cpu.query_copy_results.pool = pool;
1207    job->cpu.query_copy_results.first = first;
1208    job->cpu.query_copy_results.count = count;
1209    job->cpu.query_copy_results.dst = dst;
1210    job->cpu.query_copy_results.offset = offset;
1211    job->cpu.query_copy_results.stride = stride;
1212    job->cpu.query_copy_results.flags = flags;
1213 
1214    list_addtail(&job->list_link, &cmd_buffer->jobs);
1215 }
1216 
1217 VKAPI_ATTR void VKAPI_CALL
v3dv_CmdCopyQueryPoolResults(VkCommandBuffer commandBuffer,VkQueryPool queryPool,uint32_t firstQuery,uint32_t queryCount,VkBuffer dstBuffer,VkDeviceSize dstOffset,VkDeviceSize stride,VkQueryResultFlags flags)1218 v3dv_CmdCopyQueryPoolResults(VkCommandBuffer commandBuffer,
1219                              VkQueryPool queryPool,
1220                              uint32_t firstQuery,
1221                              uint32_t queryCount,
1222                              VkBuffer dstBuffer,
1223                              VkDeviceSize dstOffset,
1224                              VkDeviceSize stride,
1225                              VkQueryResultFlags flags)
1226 {
1227    V3DV_FROM_HANDLE(v3dv_cmd_buffer, cmd_buffer, commandBuffer);
1228    V3DV_FROM_HANDLE(v3dv_query_pool, pool, queryPool);
1229    V3DV_FROM_HANDLE(v3dv_buffer, dst, dstBuffer);
1230 
1231    /* Copies can only happen outside a render pass instance so we should not
1232     * be in the middle of job recording.
1233     */
1234    assert(cmd_buffer->state.pass == NULL);
1235    assert(cmd_buffer->state.job == NULL);
1236 
1237    assert(firstQuery < pool->query_count);
1238    assert(firstQuery + queryCount <= pool->query_count);
1239 
1240    /* For occlusion queries we implement the copy in the GPU but for other
1241     * queries we emit a CPU job that will call v3dv_get_query_pool_results_cpu
1242     * when executed in the queue.
1243     */
1244    if (pool->query_type == VK_QUERY_TYPE_OCCLUSION) {
1245       cmd_buffer_emit_copy_query_pool_results(cmd_buffer, pool,
1246                                               firstQuery, queryCount,
1247                                               dst, (uint32_t) dstOffset,
1248                                               (uint32_t) stride, flags);
1249    } else {
1250       cmd_buffer_emit_copy_query_pool_results_cpu(cmd_buffer, pool,
1251                                                   firstQuery, queryCount,
1252                                                   dst, (uint32_t)dstOffset,
1253                                                   (uint32_t) stride, flags);
1254    }
1255 }
1256 
1257 VKAPI_ATTR void VKAPI_CALL
v3dv_CmdBeginQuery(VkCommandBuffer commandBuffer,VkQueryPool queryPool,uint32_t query,VkQueryControlFlags flags)1258 v3dv_CmdBeginQuery(VkCommandBuffer commandBuffer,
1259                    VkQueryPool queryPool,
1260                    uint32_t query,
1261                    VkQueryControlFlags flags)
1262 {
1263    V3DV_FROM_HANDLE(v3dv_cmd_buffer, cmd_buffer, commandBuffer);
1264    V3DV_FROM_HANDLE(v3dv_query_pool, pool, queryPool);
1265 
1266    v3dv_cmd_buffer_begin_query(cmd_buffer, pool, query, flags);
1267 }
1268 
1269 VKAPI_ATTR void VKAPI_CALL
v3dv_CmdEndQuery(VkCommandBuffer commandBuffer,VkQueryPool queryPool,uint32_t query)1270 v3dv_CmdEndQuery(VkCommandBuffer commandBuffer,
1271                  VkQueryPool queryPool,
1272                  uint32_t query)
1273 {
1274    V3DV_FROM_HANDLE(v3dv_cmd_buffer, cmd_buffer, commandBuffer);
1275    V3DV_FROM_HANDLE(v3dv_query_pool, pool, queryPool);
1276 
1277    v3dv_cmd_buffer_end_query(cmd_buffer, pool, query);
1278 }
1279 
1280 void
v3dv_reset_query_pool_cpu(struct v3dv_device * device,struct v3dv_query_pool * pool,uint32_t first,uint32_t count)1281 v3dv_reset_query_pool_cpu(struct v3dv_device *device,
1282                           struct v3dv_query_pool *pool,
1283                           uint32_t first,
1284                           uint32_t count)
1285 {
1286    mtx_lock(&device->query_mutex);
1287 
1288    if (pool->query_type == VK_QUERY_TYPE_TIMESTAMP) {
1289       assert(first + count <= pool->query_count);
1290 
1291       /* Reset timestamp */
1292       uint8_t *base_addr;
1293       base_addr  = ((uint8_t *) pool->timestamp.bo->map) +
1294                     pool->queries[first].timestamp.offset;
1295       memset(base_addr, 0, 8 * count);
1296 
1297       for (uint32_t i = first; i < first + count; i++) {
1298          if (vk_sync_reset(&device->vk, pool->queries[i].timestamp.sync) != VK_SUCCESS)
1299             fprintf(stderr, "Failed to reset sync");
1300       }
1301 
1302       mtx_unlock(&device->query_mutex);
1303       return;
1304    }
1305 
1306    for (uint32_t i = first; i < first + count; i++) {
1307       assert(i < pool->query_count);
1308       struct v3dv_query *q = &pool->queries[i];
1309       q->maybe_available = false;
1310       switch (pool->query_type) {
1311       case VK_QUERY_TYPE_OCCLUSION: {
1312          /* Reset availability */
1313          uint8_t *base_addr = ((uint8_t *) pool->occlusion.bo->map) +
1314                               pool->occlusion.avail_offset + first;
1315          memset(base_addr, 0, count);
1316 
1317          /* Reset occlusion counter */
1318          const uint8_t *q_addr =
1319             ((uint8_t *) pool->occlusion.bo->map) + q->occlusion.offset;
1320          uint32_t *counter = (uint32_t *) q_addr;
1321          *counter = 0;
1322          break;
1323       }
1324       case VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR:
1325          kperfmon_destroy(device, pool, i);
1326          kperfmon_create(device, pool, i);
1327          if (vk_sync_reset(&device->vk, q->perf.last_job_sync) != VK_SUCCESS)
1328             fprintf(stderr, "Failed to reset sync");
1329          break;
1330       default:
1331          unreachable("Unsupported query type");
1332       }
1333    }
1334 
1335    mtx_unlock(&device->query_mutex);
1336 }
1337 
1338 VKAPI_ATTR void VKAPI_CALL
v3dv_ResetQueryPool(VkDevice _device,VkQueryPool queryPool,uint32_t firstQuery,uint32_t queryCount)1339 v3dv_ResetQueryPool(VkDevice _device,
1340                     VkQueryPool queryPool,
1341                     uint32_t firstQuery,
1342                     uint32_t queryCount)
1343 {
1344    V3DV_FROM_HANDLE(v3dv_device, device, _device);
1345    V3DV_FROM_HANDLE(v3dv_query_pool, pool, queryPool);
1346 
1347    v3dv_reset_query_pool_cpu(device, pool, firstQuery, queryCount);
1348 }
1349 
1350 VKAPI_ATTR VkResult VKAPI_CALL
v3dv_EnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(VkPhysicalDevice physicalDevice,uint32_t queueFamilyIndex,uint32_t * pCounterCount,VkPerformanceCounterKHR * pCounters,VkPerformanceCounterDescriptionKHR * pCounterDescriptions)1351 v3dv_EnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR(
1352    VkPhysicalDevice physicalDevice,
1353    uint32_t queueFamilyIndex,
1354    uint32_t *pCounterCount,
1355    VkPerformanceCounterKHR *pCounters,
1356    VkPerformanceCounterDescriptionKHR *pCounterDescriptions)
1357 {
1358    V3DV_FROM_HANDLE(v3dv_physical_device, pDevice, physicalDevice);
1359 
1360    return v3dv_X(pDevice, enumerate_performance_query_counters)(pDevice,
1361                                                                 pCounterCount,
1362                                                                 pCounters,
1363                                                                 pCounterDescriptions);
1364 }
1365 
1366 VKAPI_ATTR void VKAPI_CALL
v3dv_GetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR(VkPhysicalDevice physicalDevice,const VkQueryPoolPerformanceCreateInfoKHR * pPerformanceQueryCreateInfo,uint32_t * pNumPasses)1367 v3dv_GetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR(
1368    VkPhysicalDevice physicalDevice,
1369    const VkQueryPoolPerformanceCreateInfoKHR *pPerformanceQueryCreateInfo,
1370    uint32_t *pNumPasses)
1371 {
1372    *pNumPasses = DIV_ROUND_UP(pPerformanceQueryCreateInfo->counterIndexCount,
1373                               DRM_V3D_MAX_PERF_COUNTERS);
1374 }
1375 
1376 VKAPI_ATTR VkResult VKAPI_CALL
v3dv_AcquireProfilingLockKHR(VkDevice _device,const VkAcquireProfilingLockInfoKHR * pInfo)1377 v3dv_AcquireProfilingLockKHR(
1378    VkDevice _device,
1379    const VkAcquireProfilingLockInfoKHR *pInfo)
1380 {
1381    return VK_SUCCESS;
1382 }
1383 
1384 VKAPI_ATTR void VKAPI_CALL
v3dv_ReleaseProfilingLockKHR(VkDevice device)1385 v3dv_ReleaseProfilingLockKHR(VkDevice device)
1386 {
1387 }
1388 
1389 static inline void
nir_set_query_availability(nir_builder * b,nir_def * buf,nir_def * offset,nir_def * query_idx,nir_def * avail)1390 nir_set_query_availability(nir_builder *b,
1391                            nir_def *buf,
1392                            nir_def *offset,
1393                            nir_def *query_idx,
1394                            nir_def *avail)
1395 {
1396    offset = nir_iadd(b, offset, query_idx); /* we use 1B per query */
1397    nir_store_ssbo(b, avail, buf, offset, .write_mask = 0x1, .align_mul = 1);
1398 }
1399 
1400 static inline nir_def *
nir_get_query_availability(nir_builder * b,nir_def * buf,nir_def * offset,nir_def * query_idx)1401 nir_get_query_availability(nir_builder *b,
1402                            nir_def *buf,
1403                            nir_def *offset,
1404                            nir_def *query_idx)
1405 {
1406    offset = nir_iadd(b, offset, query_idx); /* we use 1B per query */
1407    nir_def *avail = nir_load_ssbo(b, 1, 8, buf, offset, .align_mul = 1);
1408    return nir_i2i32(b, avail);
1409 }
1410 
1411 static nir_shader *
get_set_query_availability_cs(const nir_shader_compiler_options * options)1412 get_set_query_availability_cs(const nir_shader_compiler_options *options)
1413 {
1414    nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, options,
1415                                                   "set query availability cs");
1416 
1417    nir_def *buf =
1418       nir_vulkan_resource_index(&b, 2, 32, nir_imm_int(&b, 0),
1419                                 .desc_set = 0,
1420                                 .binding = 0,
1421                                 .desc_type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1422 
1423    /* This assumes a local size of 1 and a horizontal-only dispatch. If we
1424     * ever change any of these parameters we need to update how we compute the
1425     * query index here.
1426     */
1427    nir_def *wg_id = nir_channel(&b, nir_load_workgroup_id(&b), 0);
1428 
1429    nir_def *offset =
1430       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 0, .range = 4);
1431 
1432    nir_def *query_idx =
1433       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 4, .range = 4);
1434 
1435    nir_def *avail =
1436       nir_load_push_constant(&b, 1, 8, nir_imm_int(&b, 0), .base = 8, .range = 1);
1437 
1438    query_idx = nir_iadd(&b, query_idx, wg_id);
1439    nir_set_query_availability(&b, buf, offset, query_idx, avail);
1440 
1441    return b.shader;
1442 }
1443 
1444 static inline nir_def *
nir_get_occlusion_counter_offset(nir_builder * b,nir_def * query_idx)1445 nir_get_occlusion_counter_offset(nir_builder *b, nir_def *query_idx)
1446 {
1447    nir_def *query_group = nir_udiv_imm(b, query_idx, 16);
1448    nir_def *query_group_offset = nir_umod_imm(b, query_idx, 16);
1449    nir_def *offset =
1450       nir_iadd(b, nir_imul_imm(b, query_group, 1024),
1451                   nir_imul_imm(b, query_group_offset, 4));
1452    return offset;
1453 }
1454 
1455 static inline void
nir_reset_occlusion_counter(nir_builder * b,nir_def * buf,nir_def * query_idx)1456 nir_reset_occlusion_counter(nir_builder *b,
1457                             nir_def *buf,
1458                             nir_def *query_idx)
1459 {
1460    nir_def *offset = nir_get_occlusion_counter_offset(b, query_idx);
1461    nir_def *zero = nir_imm_int(b, 0);
1462    nir_store_ssbo(b, zero, buf, offset, .write_mask = 0x1, .align_mul = 4);
1463 }
1464 
1465 static inline nir_def *
nir_read_occlusion_counter(nir_builder * b,nir_def * buf,nir_def * query_idx)1466 nir_read_occlusion_counter(nir_builder *b,
1467                            nir_def *buf,
1468                            nir_def *query_idx)
1469 {
1470    nir_def *offset = nir_get_occlusion_counter_offset(b, query_idx);
1471    return nir_load_ssbo(b, 1, 32, buf, offset, .access = 0, .align_mul = 4);
1472 }
1473 
1474 static nir_shader *
get_reset_occlusion_query_cs(const nir_shader_compiler_options * options)1475 get_reset_occlusion_query_cs(const nir_shader_compiler_options *options)
1476 {
1477    nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, options,
1478                                                   "reset occlusion query cs");
1479 
1480    nir_def *buf =
1481       nir_vulkan_resource_index(&b, 2, 32, nir_imm_int(&b, 0),
1482                                 .desc_set = 0,
1483                                 .binding = 0,
1484                                 .desc_type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1485 
1486    /* This assumes a local size of 1 and a horizontal-only dispatch. If we
1487     * ever change any of these parameters we need to update how we compute the
1488     * query index here.
1489     */
1490    nir_def *wg_id = nir_channel(&b, nir_load_workgroup_id(&b), 0);
1491 
1492    nir_def *avail_offset =
1493       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 0, .range = 4);
1494 
1495    nir_def *base_query_idx =
1496       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 4, .range = 4);
1497 
1498    nir_def *query_idx = nir_iadd(&b, base_query_idx, wg_id);
1499 
1500    nir_set_query_availability(&b, buf, avail_offset, query_idx,
1501                               nir_imm_intN_t(&b, 0, 8));
1502    nir_reset_occlusion_counter(&b, buf, query_idx);
1503 
1504    return b.shader;
1505 }
1506 
1507 static void
write_query_buffer(nir_builder * b,nir_def * buf,nir_def ** offset,nir_def * value,bool flag_64bit)1508 write_query_buffer(nir_builder *b,
1509                    nir_def *buf,
1510                    nir_def **offset,
1511                    nir_def *value,
1512                    bool flag_64bit)
1513 {
1514    if (flag_64bit) {
1515       /* Create a 64-bit value using a vec2 with the .Y component set to 0
1516        * so we can write a 64-bit value in a single store.
1517        */
1518       nir_def *value64 = nir_vec2(b, value, nir_imm_int(b, 0));
1519       nir_store_ssbo(b, value64, buf, *offset, .write_mask = 0x3, .align_mul = 8);
1520       *offset = nir_iadd_imm(b, *offset, 8);
1521    } else {
1522       nir_store_ssbo(b, value, buf, *offset, .write_mask = 0x1, .align_mul = 4);
1523       *offset = nir_iadd_imm(b, *offset, 4);
1524    }
1525 }
1526 
1527 static nir_shader *
get_copy_query_results_cs(const nir_shader_compiler_options * options,VkQueryResultFlags flags)1528 get_copy_query_results_cs(const nir_shader_compiler_options *options,
1529                           VkQueryResultFlags flags)
1530 {
1531    bool flag_64bit = flags & VK_QUERY_RESULT_64_BIT;
1532    bool flag_avail = flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT;
1533    bool flag_partial = flags & VK_QUERY_RESULT_PARTIAL_BIT;
1534 
1535    nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, options,
1536                                                   "copy query results cs");
1537 
1538    nir_def *buf =
1539       nir_vulkan_resource_index(&b, 2, 32, nir_imm_int(&b, 0),
1540                                 .desc_set = 0,
1541                                 .binding = 0,
1542                                 .desc_type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1543 
1544    nir_def *buf_out =
1545       nir_vulkan_resource_index(&b, 2, 32, nir_imm_int(&b, 0),
1546                                 .desc_set = 1,
1547                                 .binding = 0,
1548                                 .desc_type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1549 
1550    /* Read push constants */
1551    nir_def *avail_offset =
1552       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 0, .range = 4);
1553 
1554    nir_def *base_query_idx =
1555       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 4, .range = 4);
1556 
1557    nir_def *base_offset_out =
1558       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 8, .range = 4);
1559 
1560    nir_def *stride =
1561       nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 12, .range = 4);
1562 
1563    /* This assumes a local size of 1 and a horizontal-only dispatch. If we
1564     * ever change any of these parameters we need to update how we compute the
1565     * query index here.
1566     */
1567    nir_def *wg_id = nir_channel(&b, nir_load_workgroup_id(&b), 0);
1568    nir_def *query_idx = nir_iadd(&b, base_query_idx, wg_id);
1569 
1570    /* Read query availability if needed */
1571    nir_def *avail = NULL;
1572    if (flag_avail || !flag_partial)
1573       avail = nir_get_query_availability(&b, buf, avail_offset, query_idx);
1574 
1575    /* Write occusion query result... */
1576    nir_def *offset =
1577       nir_iadd(&b, base_offset_out, nir_imul(&b, wg_id, stride));
1578 
1579    /* ...if partial is requested, we always write */
1580    if(flag_partial) {
1581       nir_def *query_res = nir_read_occlusion_counter(&b, buf, query_idx);
1582       write_query_buffer(&b, buf_out, &offset, query_res, flag_64bit);
1583    } else {
1584       /*...otherwise, we only write if the query is available */
1585       nir_if *if_stmt = nir_push_if(&b, nir_ine_imm(&b, avail, 0));
1586          nir_def *query_res = nir_read_occlusion_counter(&b, buf, query_idx);
1587          write_query_buffer(&b, buf_out, &offset, query_res, flag_64bit);
1588       nir_pop_if(&b, if_stmt);
1589    }
1590 
1591    /* Write query availability */
1592    if (flag_avail)
1593       write_query_buffer(&b, buf_out, &offset, avail, flag_64bit);
1594 
1595    return b.shader;
1596 }
1597 
1598 static bool
create_query_pipelines(struct v3dv_device * device)1599 create_query_pipelines(struct v3dv_device *device)
1600 {
1601    VkResult result;
1602    VkPipeline pipeline;
1603 
1604    /* Set layout: single storage buffer */
1605    if (!device->queries.buf_descriptor_set_layout) {
1606       VkDescriptorSetLayoutBinding descriptor_set_layout_binding = {
1607          .binding = 0,
1608          .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
1609          .descriptorCount = 1,
1610          .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT,
1611       };
1612       VkDescriptorSetLayoutCreateInfo descriptor_set_layout_info = {
1613          .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
1614          .bindingCount = 1,
1615          .pBindings = &descriptor_set_layout_binding,
1616       };
1617       result =
1618          v3dv_CreateDescriptorSetLayout(v3dv_device_to_handle(device),
1619                                         &descriptor_set_layout_info,
1620                                         &device->vk.alloc,
1621                                         &device->queries.buf_descriptor_set_layout);
1622       if (result != VK_SUCCESS)
1623          return false;
1624    }
1625 
1626    /* Set availability pipeline.
1627     *
1628     * Pipeline layout:
1629     *  - 1 storage buffer for the BO with the query availability.
1630     *  - 2 push constants:
1631     *    0B: offset of the availability info in the buffer (4 bytes)
1632     *    4B: base query index (4 bytes).
1633     *    8B: availability (1 byte).
1634     */
1635    if (!device->queries.avail_pipeline_layout) {
1636       VkPipelineLayoutCreateInfo pipeline_layout_info = {
1637          .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1638          .setLayoutCount = 1,
1639          .pSetLayouts = &device->queries.buf_descriptor_set_layout,
1640          .pushConstantRangeCount = 1,
1641          .pPushConstantRanges =
1642              &(VkPushConstantRange) { VK_SHADER_STAGE_COMPUTE_BIT, 0, 9 },
1643       };
1644 
1645       result =
1646          v3dv_CreatePipelineLayout(v3dv_device_to_handle(device),
1647                                    &pipeline_layout_info,
1648                                    &device->vk.alloc,
1649                                    &device->queries.avail_pipeline_layout);
1650 
1651       if (result != VK_SUCCESS)
1652          return false;
1653    }
1654 
1655    const nir_shader_compiler_options *compiler_options =
1656       v3dv_pipeline_get_nir_options(&device->devinfo);
1657 
1658    if (!device->queries.avail_pipeline) {
1659       nir_shader *set_query_availability_cs_nir =
1660          get_set_query_availability_cs(compiler_options);
1661       result = v3dv_create_compute_pipeline_from_nir(device,
1662                                                      set_query_availability_cs_nir,
1663                                                      device->queries.avail_pipeline_layout,
1664                                                      &pipeline);
1665       ralloc_free(set_query_availability_cs_nir);
1666       if (result != VK_SUCCESS)
1667          return false;
1668 
1669       device->queries.avail_pipeline = pipeline;
1670    }
1671 
1672    /* Reset occlusion query pipeline.
1673     *
1674     * Pipeline layout:
1675     *  - 1 storage buffer for the BO with the occlusion and availability data.
1676     *  - Push constants:
1677     *    0B: offset of the availability info in the buffer (4B)
1678     *    4B: base query index (4B)
1679     */
1680    if (!device->queries.reset_occlusion_pipeline_layout) {
1681       VkPipelineLayoutCreateInfo pipeline_layout_info = {
1682          .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1683          .setLayoutCount = 1,
1684          .pSetLayouts = &device->queries.buf_descriptor_set_layout,
1685          .pushConstantRangeCount = 1,
1686          .pPushConstantRanges =
1687              &(VkPushConstantRange) { VK_SHADER_STAGE_COMPUTE_BIT, 0, 8 },
1688       };
1689 
1690       result =
1691          v3dv_CreatePipelineLayout(v3dv_device_to_handle(device),
1692                                    &pipeline_layout_info,
1693                                    &device->vk.alloc,
1694                                    &device->queries.reset_occlusion_pipeline_layout);
1695 
1696       if (result != VK_SUCCESS)
1697          return false;
1698    }
1699 
1700    if (!device->queries.reset_occlusion_pipeline) {
1701       nir_shader *reset_occlusion_query_cs_nir =
1702          get_reset_occlusion_query_cs(compiler_options);
1703       result = v3dv_create_compute_pipeline_from_nir(
1704                   device,
1705                   reset_occlusion_query_cs_nir,
1706                   device->queries.reset_occlusion_pipeline_layout,
1707                   &pipeline);
1708       ralloc_free(reset_occlusion_query_cs_nir);
1709       if (result != VK_SUCCESS)
1710          return false;
1711 
1712       device->queries.reset_occlusion_pipeline = pipeline;
1713    }
1714 
1715    /* Copy query results pipelines.
1716     *
1717     * Pipeline layout:
1718     *  - 1 storage buffer for the BO with the query availability and occlusion.
1719     *  - 1 storage buffer for the output.
1720     *  - Push constants:
1721     *    0B: offset of the availability info in the buffer (4B)
1722     *    4B: base query index (4B)
1723     *    8B: offset into output buffer (4B)
1724     *    12B: stride (4B)
1725     *
1726     * We create multiple specialized pipelines depending on the copy flags
1727     * to remove conditionals from the copy shader and get more optimized
1728     * pipelines.
1729     */
1730    if (!device->queries.copy_pipeline_layout) {
1731       VkDescriptorSetLayout set_layouts[2] = {
1732          device->queries.buf_descriptor_set_layout,
1733          device->queries.buf_descriptor_set_layout
1734       };
1735       VkPipelineLayoutCreateInfo pipeline_layout_info = {
1736          .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1737          .setLayoutCount = 2,
1738          .pSetLayouts = set_layouts,
1739          .pushConstantRangeCount = 1,
1740          .pPushConstantRanges =
1741              &(VkPushConstantRange) { VK_SHADER_STAGE_COMPUTE_BIT, 0, 16 },
1742       };
1743 
1744       result =
1745          v3dv_CreatePipelineLayout(v3dv_device_to_handle(device),
1746                                    &pipeline_layout_info,
1747                                    &device->vk.alloc,
1748                                    &device->queries.copy_pipeline_layout);
1749 
1750       if (result != VK_SUCCESS)
1751          return false;
1752    }
1753 
1754    /* Actual copy pipelines are created lazily on demand since there can be up
1755     * to 8 depending on the flags used, however it is likely that applications
1756     * will use the same flags every time and only one pipeline is required.
1757     */
1758 
1759    return true;
1760 }
1761 
1762 static void
destroy_query_pipelines(struct v3dv_device * device)1763 destroy_query_pipelines(struct v3dv_device *device)
1764 {
1765    VkDevice _device = v3dv_device_to_handle(device);
1766 
1767    /* Availability pipeline */
1768    v3dv_DestroyPipeline(_device, device->queries.avail_pipeline,
1769                          &device->vk.alloc);
1770    device->queries.avail_pipeline = VK_NULL_HANDLE;
1771    v3dv_DestroyPipelineLayout(_device, device->queries.avail_pipeline_layout,
1772                               &device->vk.alloc);
1773    device->queries.avail_pipeline_layout = VK_NULL_HANDLE;
1774 
1775    /* Reset occlusion pipeline */
1776    v3dv_DestroyPipeline(_device, device->queries.reset_occlusion_pipeline,
1777                          &device->vk.alloc);
1778    device->queries.reset_occlusion_pipeline = VK_NULL_HANDLE;
1779    v3dv_DestroyPipelineLayout(_device,
1780                               device->queries.reset_occlusion_pipeline_layout,
1781                               &device->vk.alloc);
1782    device->queries.reset_occlusion_pipeline_layout = VK_NULL_HANDLE;
1783 
1784    /* Copy pipelines */
1785    for (int i = 0; i < 8; i++) {
1786       v3dv_DestroyPipeline(_device, device->queries.copy_pipeline[i],
1787                             &device->vk.alloc);
1788       device->queries.copy_pipeline[i] = VK_NULL_HANDLE;
1789    }
1790    v3dv_DestroyPipelineLayout(_device, device->queries.copy_pipeline_layout,
1791                               &device->vk.alloc);
1792    device->queries.copy_pipeline_layout = VK_NULL_HANDLE;
1793 
1794    v3dv_DestroyDescriptorSetLayout(_device,
1795                                    device->queries.buf_descriptor_set_layout,
1796                                    &device->vk.alloc);
1797    device->queries.buf_descriptor_set_layout = VK_NULL_HANDLE;
1798 }
1799 
1800 /**
1801  * Allocates device resources for implementing certain types of queries.
1802  */
1803 VkResult
v3dv_query_allocate_resources(struct v3dv_device * device)1804 v3dv_query_allocate_resources(struct v3dv_device *device)
1805 {
1806    if (!create_query_pipelines(device))
1807       return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
1808 
1809    return VK_SUCCESS;
1810 }
1811 
1812 void
v3dv_query_free_resources(struct v3dv_device * device)1813 v3dv_query_free_resources(struct v3dv_device *device)
1814 {
1815    destroy_query_pipelines(device);
1816 }
1817