a6eeed79a02e35f3a9281e2de1f9a9503fd58946
[mesa.git] / src / intel / vulkan / anv_allocator.c
1 /*
2 * Copyright © 2015 Intel Corporation
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 <stdlib.h>
25 #include <unistd.h>
26 #include <limits.h>
27 #include <assert.h>
28 #include <sys/mman.h>
29
30 #include "anv_private.h"
31
32 #include "util/hash_table.h"
33 #include "util/simple_mtx.h"
34 #include "util/anon_file.h"
35
36 #ifdef HAVE_VALGRIND
37 #define VG_NOACCESS_READ(__ptr) ({ \
38 VALGRIND_MAKE_MEM_DEFINED((__ptr), sizeof(*(__ptr))); \
39 __typeof(*(__ptr)) __val = *(__ptr); \
40 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr)));\
41 __val; \
42 })
43 #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
44 VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
45 *(__ptr) = (__val); \
46 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
47 })
48 #else
49 #define VG_NOACCESS_READ(__ptr) (*(__ptr))
50 #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
51 #endif
52
53 /* Design goals:
54 *
55 * - Lock free (except when resizing underlying bos)
56 *
57 * - Constant time allocation with typically only one atomic
58 *
59 * - Multiple allocation sizes without fragmentation
60 *
61 * - Can grow while keeping addresses and offset of contents stable
62 *
63 * - All allocations within one bo so we can point one of the
64 * STATE_BASE_ADDRESS pointers at it.
65 *
66 * The overall design is a two-level allocator: top level is a fixed size, big
67 * block (8k) allocator, which operates out of a bo. Allocation is done by
68 * either pulling a block from the free list or growing the used range of the
69 * bo. Growing the range may run out of space in the bo which we then need to
70 * grow. Growing the bo is tricky in a multi-threaded, lockless environment:
71 * we need to keep all pointers and contents in the old map valid. GEM bos in
72 * general can't grow, but we use a trick: we create a memfd and use ftruncate
73 * to grow it as necessary. We mmap the new size and then create a gem bo for
74 * it using the new gem userptr ioctl. Without heavy-handed locking around
75 * our allocation fast-path, there isn't really a way to munmap the old mmap,
76 * so we just keep it around until garbage collection time. While the block
77 * allocator is lockless for normal operations, we block other threads trying
78 * to allocate while we're growing the map. It sholdn't happen often, and
79 * growing is fast anyway.
80 *
81 * At the next level we can use various sub-allocators. The state pool is a
82 * pool of smaller, fixed size objects, which operates much like the block
83 * pool. It uses a free list for freeing objects, but when it runs out of
84 * space it just allocates a new block from the block pool. This allocator is
85 * intended for longer lived state objects such as SURFACE_STATE and most
86 * other persistent state objects in the API. We may need to track more info
87 * with these object and a pointer back to the CPU object (eg VkImage). In
88 * those cases we just allocate a slightly bigger object and put the extra
89 * state after the GPU state object.
90 *
91 * The state stream allocator works similar to how the i965 DRI driver streams
92 * all its state. Even with Vulkan, we need to emit transient state (whether
93 * surface state base or dynamic state base), and for that we can just get a
94 * block and fill it up. These cases are local to a command buffer and the
95 * sub-allocator need not be thread safe. The streaming allocator gets a new
96 * block when it runs out of space and chains them together so they can be
97 * easily freed.
98 */
99
100 /* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
101 * We use it to indicate the free list is empty. */
102 #define EMPTY UINT32_MAX
103
104 #define PAGE_SIZE 4096
105
106 struct anv_mmap_cleanup {
107 void *map;
108 size_t size;
109 uint32_t gem_handle;
110 };
111
112 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
113
114 static inline uint32_t
115 ilog2_round_up(uint32_t value)
116 {
117 assert(value != 0);
118 return 32 - __builtin_clz(value - 1);
119 }
120
121 static inline uint32_t
122 round_to_power_of_two(uint32_t value)
123 {
124 return 1 << ilog2_round_up(value);
125 }
126
127 struct anv_state_table_cleanup {
128 void *map;
129 size_t size;
130 };
131
132 #define ANV_STATE_TABLE_CLEANUP_INIT ((struct anv_state_table_cleanup){0})
133 #define ANV_STATE_ENTRY_SIZE (sizeof(struct anv_free_entry))
134
135 static VkResult
136 anv_state_table_expand_range(struct anv_state_table *table, uint32_t size);
137
138 VkResult
139 anv_state_table_init(struct anv_state_table *table,
140 struct anv_device *device,
141 uint32_t initial_entries)
142 {
143 VkResult result;
144
145 table->device = device;
146
147 /* Just make it 2GB up-front. The Linux kernel won't actually back it
148 * with pages until we either map and fault on one of them or we use
149 * userptr and send a chunk of it off to the GPU.
150 */
151 table->fd = os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE, "state table");
152 if (table->fd == -1) {
153 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
154 goto fail_fd;
155 }
156
157 if (!u_vector_init(&table->cleanups,
158 round_to_power_of_two(sizeof(struct anv_state_table_cleanup)),
159 128)) {
160 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
161 goto fail_fd;
162 }
163
164 table->state.next = 0;
165 table->state.end = 0;
166 table->size = 0;
167
168 uint32_t initial_size = initial_entries * ANV_STATE_ENTRY_SIZE;
169 result = anv_state_table_expand_range(table, initial_size);
170 if (result != VK_SUCCESS)
171 goto fail_cleanups;
172
173 return VK_SUCCESS;
174
175 fail_cleanups:
176 u_vector_finish(&table->cleanups);
177 fail_fd:
178 close(table->fd);
179
180 return result;
181 }
182
183 static VkResult
184 anv_state_table_expand_range(struct anv_state_table *table, uint32_t size)
185 {
186 void *map;
187 struct anv_state_table_cleanup *cleanup;
188
189 /* Assert that we only ever grow the pool */
190 assert(size >= table->state.end);
191
192 /* Make sure that we don't go outside the bounds of the memfd */
193 if (size > BLOCK_POOL_MEMFD_SIZE)
194 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
195
196 cleanup = u_vector_add(&table->cleanups);
197 if (!cleanup)
198 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
199
200 *cleanup = ANV_STATE_TABLE_CLEANUP_INIT;
201
202 /* Just leak the old map until we destroy the pool. We can't munmap it
203 * without races or imposing locking on the block allocate fast path. On
204 * the whole the leaked maps adds up to less than the size of the
205 * current map. MAP_POPULATE seems like the right thing to do, but we
206 * should try to get some numbers.
207 */
208 map = mmap(NULL, size, PROT_READ | PROT_WRITE,
209 MAP_SHARED | MAP_POPULATE, table->fd, 0);
210 if (map == MAP_FAILED) {
211 return vk_errorf(table->device->instance, table->device,
212 VK_ERROR_OUT_OF_HOST_MEMORY, "mmap failed: %m");
213 }
214
215 cleanup->map = map;
216 cleanup->size = size;
217
218 table->map = map;
219 table->size = size;
220
221 return VK_SUCCESS;
222 }
223
224 static VkResult
225 anv_state_table_grow(struct anv_state_table *table)
226 {
227 VkResult result = VK_SUCCESS;
228
229 uint32_t used = align_u32(table->state.next * ANV_STATE_ENTRY_SIZE,
230 PAGE_SIZE);
231 uint32_t old_size = table->size;
232
233 /* The block pool is always initialized to a nonzero size and this function
234 * is always called after initialization.
235 */
236 assert(old_size > 0);
237
238 uint32_t required = MAX2(used, old_size);
239 if (used * 2 <= required) {
240 /* If we're in this case then this isn't the firsta allocation and we
241 * already have enough space on both sides to hold double what we
242 * have allocated. There's nothing for us to do.
243 */
244 goto done;
245 }
246
247 uint32_t size = old_size * 2;
248 while (size < required)
249 size *= 2;
250
251 assert(size > table->size);
252
253 result = anv_state_table_expand_range(table, size);
254
255 done:
256 return result;
257 }
258
259 void
260 anv_state_table_finish(struct anv_state_table *table)
261 {
262 struct anv_state_table_cleanup *cleanup;
263
264 u_vector_foreach(cleanup, &table->cleanups) {
265 if (cleanup->map)
266 munmap(cleanup->map, cleanup->size);
267 }
268
269 u_vector_finish(&table->cleanups);
270
271 close(table->fd);
272 }
273
274 VkResult
275 anv_state_table_add(struct anv_state_table *table, uint32_t *idx,
276 uint32_t count)
277 {
278 struct anv_block_state state, old, new;
279 VkResult result;
280
281 assert(idx);
282
283 while(1) {
284 state.u64 = __sync_fetch_and_add(&table->state.u64, count);
285 if (state.next + count <= state.end) {
286 assert(table->map);
287 struct anv_free_entry *entry = &table->map[state.next];
288 for (int i = 0; i < count; i++) {
289 entry[i].state.idx = state.next + i;
290 }
291 *idx = state.next;
292 return VK_SUCCESS;
293 } else if (state.next <= state.end) {
294 /* We allocated the first block outside the pool so we have to grow
295 * the pool. pool_state->next acts a mutex: threads who try to
296 * allocate now will get block indexes above the current limit and
297 * hit futex_wait below.
298 */
299 new.next = state.next + count;
300 do {
301 result = anv_state_table_grow(table);
302 if (result != VK_SUCCESS)
303 return result;
304 new.end = table->size / ANV_STATE_ENTRY_SIZE;
305 } while (new.end < new.next);
306
307 old.u64 = __sync_lock_test_and_set(&table->state.u64, new.u64);
308 if (old.next != state.next)
309 futex_wake(&table->state.end, INT_MAX);
310 } else {
311 futex_wait(&table->state.end, state.end, NULL);
312 continue;
313 }
314 }
315 }
316
317 void
318 anv_free_list_push(union anv_free_list *list,
319 struct anv_state_table *table,
320 uint32_t first, uint32_t count)
321 {
322 union anv_free_list current, old, new;
323 uint32_t last = first;
324
325 for (uint32_t i = 1; i < count; i++, last++)
326 table->map[last].next = last + 1;
327
328 old = *list;
329 do {
330 current = old;
331 table->map[last].next = current.offset;
332 new.offset = first;
333 new.count = current.count + 1;
334 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
335 } while (old.u64 != current.u64);
336 }
337
338 struct anv_state *
339 anv_free_list_pop(union anv_free_list *list,
340 struct anv_state_table *table)
341 {
342 union anv_free_list current, new, old;
343
344 current.u64 = list->u64;
345 while (current.offset != EMPTY) {
346 __sync_synchronize();
347 new.offset = table->map[current.offset].next;
348 new.count = current.count + 1;
349 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
350 if (old.u64 == current.u64) {
351 struct anv_free_entry *entry = &table->map[current.offset];
352 return &entry->state;
353 }
354 current = old;
355 }
356
357 return NULL;
358 }
359
360 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
361 * means that the bottom 12 bits should all be zero.
362 */
363 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
364 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
365 #define PFL_PACK(ptr, count) ({ \
366 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
367 })
368
369 static bool
370 anv_ptr_free_list_pop(void **list, void **elem)
371 {
372 void *current = *list;
373 while (PFL_PTR(current) != NULL) {
374 void **next_ptr = PFL_PTR(current);
375 void *new_ptr = VG_NOACCESS_READ(next_ptr);
376 unsigned new_count = PFL_COUNT(current) + 1;
377 void *new = PFL_PACK(new_ptr, new_count);
378 void *old = __sync_val_compare_and_swap(list, current, new);
379 if (old == current) {
380 *elem = PFL_PTR(current);
381 return true;
382 }
383 current = old;
384 }
385
386 return false;
387 }
388
389 static void
390 anv_ptr_free_list_push(void **list, void *elem)
391 {
392 void *old, *current;
393 void **next_ptr = elem;
394
395 /* The pointer-based free list requires that the pointer be
396 * page-aligned. This is because we use the bottom 12 bits of the
397 * pointer to store a counter to solve the ABA concurrency problem.
398 */
399 assert(((uintptr_t)elem & 0xfff) == 0);
400
401 old = *list;
402 do {
403 current = old;
404 VG_NOACCESS_WRITE(next_ptr, PFL_PTR(current));
405 unsigned new_count = PFL_COUNT(current) + 1;
406 void *new = PFL_PACK(elem, new_count);
407 old = __sync_val_compare_and_swap(list, current, new);
408 } while (old != current);
409 }
410
411 static VkResult
412 anv_block_pool_expand_range(struct anv_block_pool *pool,
413 uint32_t center_bo_offset, uint32_t size);
414
415 VkResult
416 anv_block_pool_init(struct anv_block_pool *pool,
417 struct anv_device *device,
418 uint64_t start_address,
419 uint32_t initial_size,
420 uint64_t bo_flags)
421 {
422 VkResult result;
423
424 pool->device = device;
425 pool->bo_flags = bo_flags;
426 pool->nbos = 0;
427 pool->size = 0;
428 pool->center_bo_offset = 0;
429 pool->start_address = gen_canonical_address(start_address);
430 pool->map = NULL;
431
432 /* This pointer will always point to the first BO in the list */
433 pool->bo = &pool->bos[0];
434
435 anv_bo_init(pool->bo, 0, 0);
436
437 if (!(pool->bo_flags & EXEC_OBJECT_PINNED)) {
438 /* Just make it 2GB up-front. The Linux kernel won't actually back it
439 * with pages until we either map and fault on one of them or we use
440 * userptr and send a chunk of it off to the GPU.
441 */
442 pool->fd = os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE, "block pool");
443 if (pool->fd == -1)
444 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
445 } else {
446 pool->fd = -1;
447 }
448
449 if (!u_vector_init(&pool->mmap_cleanups,
450 round_to_power_of_two(sizeof(struct anv_mmap_cleanup)),
451 128)) {
452 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
453 goto fail_fd;
454 }
455
456 pool->state.next = 0;
457 pool->state.end = 0;
458 pool->back_state.next = 0;
459 pool->back_state.end = 0;
460
461 result = anv_block_pool_expand_range(pool, 0, initial_size);
462 if (result != VK_SUCCESS)
463 goto fail_mmap_cleanups;
464
465 /* Make the entire pool available in the front of the pool. If back
466 * allocation needs to use this space, the "ends" will be re-arranged.
467 */
468 pool->state.end = pool->size;
469
470 return VK_SUCCESS;
471
472 fail_mmap_cleanups:
473 u_vector_finish(&pool->mmap_cleanups);
474 fail_fd:
475 if (!(pool->bo_flags & EXEC_OBJECT_PINNED))
476 close(pool->fd);
477
478 return result;
479 }
480
481 void
482 anv_block_pool_finish(struct anv_block_pool *pool)
483 {
484 struct anv_mmap_cleanup *cleanup;
485 const bool use_softpin = !!(pool->bo_flags & EXEC_OBJECT_PINNED);
486
487 u_vector_foreach(cleanup, &pool->mmap_cleanups) {
488 if (use_softpin)
489 anv_gem_munmap(cleanup->map, cleanup->size);
490 else
491 munmap(cleanup->map, cleanup->size);
492
493 if (cleanup->gem_handle)
494 anv_gem_close(pool->device, cleanup->gem_handle);
495 }
496
497 u_vector_finish(&pool->mmap_cleanups);
498 if (!(pool->bo_flags & EXEC_OBJECT_PINNED))
499 close(pool->fd);
500 }
501
502 static VkResult
503 anv_block_pool_expand_range(struct anv_block_pool *pool,
504 uint32_t center_bo_offset, uint32_t size)
505 {
506 void *map;
507 uint32_t gem_handle;
508 struct anv_mmap_cleanup *cleanup;
509 const bool use_softpin = !!(pool->bo_flags & EXEC_OBJECT_PINNED);
510
511 /* Assert that we only ever grow the pool */
512 assert(center_bo_offset >= pool->back_state.end);
513 assert(size - center_bo_offset >= pool->state.end);
514
515 /* Assert that we don't go outside the bounds of the memfd */
516 assert(center_bo_offset <= BLOCK_POOL_MEMFD_CENTER);
517 assert(use_softpin ||
518 size - center_bo_offset <=
519 BLOCK_POOL_MEMFD_SIZE - BLOCK_POOL_MEMFD_CENTER);
520
521 cleanup = u_vector_add(&pool->mmap_cleanups);
522 if (!cleanup)
523 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
524
525 *cleanup = ANV_MMAP_CLEANUP_INIT;
526
527 uint32_t newbo_size = size - pool->size;
528 if (use_softpin) {
529 gem_handle = anv_gem_create(pool->device, newbo_size);
530 map = anv_gem_mmap(pool->device, gem_handle, 0, newbo_size, 0);
531 if (map == MAP_FAILED)
532 return vk_errorf(pool->device->instance, pool->device,
533 VK_ERROR_MEMORY_MAP_FAILED, "gem mmap failed: %m");
534 assert(center_bo_offset == 0);
535 } else {
536 /* Just leak the old map until we destroy the pool. We can't munmap it
537 * without races or imposing locking on the block allocate fast path. On
538 * the whole the leaked maps adds up to less than the size of the
539 * current map. MAP_POPULATE seems like the right thing to do, but we
540 * should try to get some numbers.
541 */
542 map = mmap(NULL, size, PROT_READ | PROT_WRITE,
543 MAP_SHARED | MAP_POPULATE, pool->fd,
544 BLOCK_POOL_MEMFD_CENTER - center_bo_offset);
545 if (map == MAP_FAILED)
546 return vk_errorf(pool->device->instance, pool->device,
547 VK_ERROR_MEMORY_MAP_FAILED, "mmap failed: %m");
548
549 /* Now that we mapped the new memory, we can write the new
550 * center_bo_offset back into pool and update pool->map. */
551 pool->center_bo_offset = center_bo_offset;
552 pool->map = map + center_bo_offset;
553 gem_handle = anv_gem_userptr(pool->device, map, size);
554 if (gem_handle == 0) {
555 munmap(map, size);
556 return vk_errorf(pool->device->instance, pool->device,
557 VK_ERROR_TOO_MANY_OBJECTS, "userptr failed: %m");
558 }
559 }
560
561 cleanup->map = map;
562 cleanup->size = use_softpin ? newbo_size : size;
563 cleanup->gem_handle = gem_handle;
564
565 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
566 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
567 * always created as I915_CACHING_CACHED, which on non-LLC means
568 * snooped.
569 *
570 * On platforms that support softpin, we are not going to use userptr
571 * anymore, but we still want to rely on the snooped states. So make sure
572 * everything is set to I915_CACHING_CACHED.
573 */
574 if (!pool->device->info.has_llc)
575 anv_gem_set_caching(pool->device, gem_handle, I915_CACHING_CACHED);
576
577 /* For block pool BOs we have to be a bit careful about where we place them
578 * in the GTT. There are two documented workarounds for state base address
579 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
580 * which state that those two base addresses do not support 48-bit
581 * addresses and need to be placed in the bottom 32-bit range.
582 * Unfortunately, this is not quite accurate.
583 *
584 * The real problem is that we always set the size of our state pools in
585 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
586 * likely significantly smaller. We do this because we do not no at the
587 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
588 * the pool during command buffer building so we don't actually have a
589 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
590 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
591 * as being out of bounds and returns zero. For dynamic state, this
592 * usually just leads to rendering corruptions, but shaders that are all
593 * zero hang the GPU immediately.
594 *
595 * The easiest solution to do is exactly what the bogus workarounds say to
596 * do: restrict these buffers to 32-bit addresses. We could also pin the
597 * BO to some particular location of our choosing, but that's significantly
598 * more work than just not setting a flag. So, we explicitly DO NOT set
599 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
600 * hard work for us.
601 */
602 struct anv_bo *bo;
603 uint32_t bo_size;
604 uint64_t bo_offset;
605
606 assert(pool->nbos < ANV_MAX_BLOCK_POOL_BOS);
607
608 if (use_softpin) {
609 /* With softpin, we add a new BO to the pool, and set its offset to right
610 * where the previous BO ends (the end of the pool).
611 */
612 bo = &pool->bos[pool->nbos++];
613 bo_size = newbo_size;
614 bo_offset = pool->start_address + pool->size;
615 } else {
616 /* Without softpin, we just need one BO, and we already have a pointer to
617 * it. Simply "allocate" it from our array if we didn't do it before.
618 * The offset doesn't matter since we are not pinning the BO anyway.
619 */
620 if (pool->nbos == 0)
621 pool->nbos++;
622 bo = pool->bo;
623 bo_size = size;
624 bo_offset = 0;
625 }
626
627 anv_bo_init(bo, gem_handle, bo_size);
628 bo->offset = bo_offset;
629 bo->flags = pool->bo_flags;
630 bo->map = map;
631 pool->size = size;
632
633 return VK_SUCCESS;
634 }
635
636 static struct anv_bo *
637 anv_block_pool_get_bo(struct anv_block_pool *pool, int32_t *offset)
638 {
639 struct anv_bo *bo, *bo_found = NULL;
640 int32_t cur_offset = 0;
641
642 assert(offset);
643
644 if (!(pool->bo_flags & EXEC_OBJECT_PINNED))
645 return pool->bo;
646
647 anv_block_pool_foreach_bo(bo, pool) {
648 if (*offset < cur_offset + bo->size) {
649 bo_found = bo;
650 break;
651 }
652 cur_offset += bo->size;
653 }
654
655 assert(bo_found != NULL);
656 *offset -= cur_offset;
657
658 return bo_found;
659 }
660
661 /** Returns current memory map of the block pool.
662 *
663 * The returned pointer points to the map for the memory at the specified
664 * offset. The offset parameter is relative to the "center" of the block pool
665 * rather than the start of the block pool BO map.
666 */
667 void*
668 anv_block_pool_map(struct anv_block_pool *pool, int32_t offset)
669 {
670 if (pool->bo_flags & EXEC_OBJECT_PINNED) {
671 struct anv_bo *bo = anv_block_pool_get_bo(pool, &offset);
672 return bo->map + offset;
673 } else {
674 return pool->map + offset;
675 }
676 }
677
678 /** Grows and re-centers the block pool.
679 *
680 * We grow the block pool in one or both directions in such a way that the
681 * following conditions are met:
682 *
683 * 1) The size of the entire pool is always a power of two.
684 *
685 * 2) The pool only grows on both ends. Neither end can get
686 * shortened.
687 *
688 * 3) At the end of the allocation, we have about twice as much space
689 * allocated for each end as we have used. This way the pool doesn't
690 * grow too far in one direction or the other.
691 *
692 * 4) If the _alloc_back() has never been called, then the back portion of
693 * the pool retains a size of zero. (This makes it easier for users of
694 * the block pool that only want a one-sided pool.)
695 *
696 * 5) We have enough space allocated for at least one more block in
697 * whichever side `state` points to.
698 *
699 * 6) The center of the pool is always aligned to both the block_size of
700 * the pool and a 4K CPU page.
701 */
702 static uint32_t
703 anv_block_pool_grow(struct anv_block_pool *pool, struct anv_block_state *state)
704 {
705 VkResult result = VK_SUCCESS;
706
707 pthread_mutex_lock(&pool->device->mutex);
708
709 assert(state == &pool->state || state == &pool->back_state);
710
711 /* Gather a little usage information on the pool. Since we may have
712 * threadsd waiting in queue to get some storage while we resize, it's
713 * actually possible that total_used will be larger than old_size. In
714 * particular, block_pool_alloc() increments state->next prior to
715 * calling block_pool_grow, so this ensures that we get enough space for
716 * which ever side tries to grow the pool.
717 *
718 * We align to a page size because it makes it easier to do our
719 * calculations later in such a way that we state page-aigned.
720 */
721 uint32_t back_used = align_u32(pool->back_state.next, PAGE_SIZE);
722 uint32_t front_used = align_u32(pool->state.next, PAGE_SIZE);
723 uint32_t total_used = front_used + back_used;
724
725 assert(state == &pool->state || back_used > 0);
726
727 uint32_t old_size = pool->size;
728
729 /* The block pool is always initialized to a nonzero size and this function
730 * is always called after initialization.
731 */
732 assert(old_size > 0);
733
734 /* The back_used and front_used may actually be smaller than the actual
735 * requirement because they are based on the next pointers which are
736 * updated prior to calling this function.
737 */
738 uint32_t back_required = MAX2(back_used, pool->center_bo_offset);
739 uint32_t front_required = MAX2(front_used, old_size - pool->center_bo_offset);
740
741 if (back_used * 2 <= back_required && front_used * 2 <= front_required) {
742 /* If we're in this case then this isn't the firsta allocation and we
743 * already have enough space on both sides to hold double what we
744 * have allocated. There's nothing for us to do.
745 */
746 goto done;
747 }
748
749 uint32_t size = old_size * 2;
750 while (size < back_required + front_required)
751 size *= 2;
752
753 assert(size > pool->size);
754
755 /* We compute a new center_bo_offset such that, when we double the size
756 * of the pool, we maintain the ratio of how much is used by each side.
757 * This way things should remain more-or-less balanced.
758 */
759 uint32_t center_bo_offset;
760 if (back_used == 0) {
761 /* If we're in this case then we have never called alloc_back(). In
762 * this case, we want keep the offset at 0 to make things as simple
763 * as possible for users that don't care about back allocations.
764 */
765 center_bo_offset = 0;
766 } else {
767 /* Try to "center" the allocation based on how much is currently in
768 * use on each side of the center line.
769 */
770 center_bo_offset = ((uint64_t)size * back_used) / total_used;
771
772 /* Align down to a multiple of the page size */
773 center_bo_offset &= ~(PAGE_SIZE - 1);
774
775 assert(center_bo_offset >= back_used);
776
777 /* Make sure we don't shrink the back end of the pool */
778 if (center_bo_offset < back_required)
779 center_bo_offset = back_required;
780
781 /* Make sure that we don't shrink the front end of the pool */
782 if (size - center_bo_offset < front_required)
783 center_bo_offset = size - front_required;
784 }
785
786 assert(center_bo_offset % PAGE_SIZE == 0);
787
788 result = anv_block_pool_expand_range(pool, center_bo_offset, size);
789
790 pool->bo->flags = pool->bo_flags;
791
792 done:
793 pthread_mutex_unlock(&pool->device->mutex);
794
795 if (result == VK_SUCCESS) {
796 /* Return the appropriate new size. This function never actually
797 * updates state->next. Instead, we let the caller do that because it
798 * needs to do so in order to maintain its concurrency model.
799 */
800 if (state == &pool->state) {
801 return pool->size - pool->center_bo_offset;
802 } else {
803 assert(pool->center_bo_offset > 0);
804 return pool->center_bo_offset;
805 }
806 } else {
807 return 0;
808 }
809 }
810
811 static uint32_t
812 anv_block_pool_alloc_new(struct anv_block_pool *pool,
813 struct anv_block_state *pool_state,
814 uint32_t block_size, uint32_t *padding)
815 {
816 struct anv_block_state state, old, new;
817
818 /* Most allocations won't generate any padding */
819 if (padding)
820 *padding = 0;
821
822 while (1) {
823 state.u64 = __sync_fetch_and_add(&pool_state->u64, block_size);
824 if (state.next + block_size <= state.end) {
825 return state.next;
826 } else if (state.next <= state.end) {
827 if (pool->bo_flags & EXEC_OBJECT_PINNED && state.next < state.end) {
828 /* We need to grow the block pool, but still have some leftover
829 * space that can't be used by that particular allocation. So we
830 * add that as a "padding", and return it.
831 */
832 uint32_t leftover = state.end - state.next;
833
834 /* If there is some leftover space in the pool, the caller must
835 * deal with it.
836 */
837 assert(leftover == 0 || padding);
838 if (padding)
839 *padding = leftover;
840 state.next += leftover;
841 }
842
843 /* We allocated the first block outside the pool so we have to grow
844 * the pool. pool_state->next acts a mutex: threads who try to
845 * allocate now will get block indexes above the current limit and
846 * hit futex_wait below.
847 */
848 new.next = state.next + block_size;
849 do {
850 new.end = anv_block_pool_grow(pool, pool_state);
851 } while (new.end < new.next);
852
853 old.u64 = __sync_lock_test_and_set(&pool_state->u64, new.u64);
854 if (old.next != state.next)
855 futex_wake(&pool_state->end, INT_MAX);
856 return state.next;
857 } else {
858 futex_wait(&pool_state->end, state.end, NULL);
859 continue;
860 }
861 }
862 }
863
864 int32_t
865 anv_block_pool_alloc(struct anv_block_pool *pool,
866 uint32_t block_size, uint32_t *padding)
867 {
868 uint32_t offset;
869
870 offset = anv_block_pool_alloc_new(pool, &pool->state, block_size, padding);
871
872 return offset;
873 }
874
875 /* Allocates a block out of the back of the block pool.
876 *
877 * This will allocated a block earlier than the "start" of the block pool.
878 * The offsets returned from this function will be negative but will still
879 * be correct relative to the block pool's map pointer.
880 *
881 * If you ever use anv_block_pool_alloc_back, then you will have to do
882 * gymnastics with the block pool's BO when doing relocations.
883 */
884 int32_t
885 anv_block_pool_alloc_back(struct anv_block_pool *pool,
886 uint32_t block_size)
887 {
888 int32_t offset = anv_block_pool_alloc_new(pool, &pool->back_state,
889 block_size, NULL);
890
891 /* The offset we get out of anv_block_pool_alloc_new() is actually the
892 * number of bytes downwards from the middle to the end of the block.
893 * We need to turn it into a (negative) offset from the middle to the
894 * start of the block.
895 */
896 assert(offset >= 0);
897 return -(offset + block_size);
898 }
899
900 VkResult
901 anv_state_pool_init(struct anv_state_pool *pool,
902 struct anv_device *device,
903 uint64_t start_address,
904 uint32_t block_size,
905 uint64_t bo_flags)
906 {
907 VkResult result = anv_block_pool_init(&pool->block_pool, device,
908 start_address,
909 block_size * 16,
910 bo_flags);
911 if (result != VK_SUCCESS)
912 return result;
913
914 result = anv_state_table_init(&pool->table, device, 64);
915 if (result != VK_SUCCESS) {
916 anv_block_pool_finish(&pool->block_pool);
917 return result;
918 }
919
920 assert(util_is_power_of_two_or_zero(block_size));
921 pool->block_size = block_size;
922 pool->back_alloc_free_list = ANV_FREE_LIST_EMPTY;
923 for (unsigned i = 0; i < ANV_STATE_BUCKETS; i++) {
924 pool->buckets[i].free_list = ANV_FREE_LIST_EMPTY;
925 pool->buckets[i].block.next = 0;
926 pool->buckets[i].block.end = 0;
927 }
928 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
929
930 return VK_SUCCESS;
931 }
932
933 void
934 anv_state_pool_finish(struct anv_state_pool *pool)
935 {
936 VG(VALGRIND_DESTROY_MEMPOOL(pool));
937 anv_state_table_finish(&pool->table);
938 anv_block_pool_finish(&pool->block_pool);
939 }
940
941 static uint32_t
942 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool *pool,
943 struct anv_block_pool *block_pool,
944 uint32_t state_size,
945 uint32_t block_size,
946 uint32_t *padding)
947 {
948 struct anv_block_state block, old, new;
949 uint32_t offset;
950
951 /* We don't always use anv_block_pool_alloc(), which would set *padding to
952 * zero for us. So if we have a pointer to padding, we must zero it out
953 * ourselves here, to make sure we always return some sensible value.
954 */
955 if (padding)
956 *padding = 0;
957
958 /* If our state is large, we don't need any sub-allocation from a block.
959 * Instead, we just grab whole (potentially large) blocks.
960 */
961 if (state_size >= block_size)
962 return anv_block_pool_alloc(block_pool, state_size, padding);
963
964 restart:
965 block.u64 = __sync_fetch_and_add(&pool->block.u64, state_size);
966
967 if (block.next < block.end) {
968 return block.next;
969 } else if (block.next == block.end) {
970 offset = anv_block_pool_alloc(block_pool, block_size, padding);
971 new.next = offset + state_size;
972 new.end = offset + block_size;
973 old.u64 = __sync_lock_test_and_set(&pool->block.u64, new.u64);
974 if (old.next != block.next)
975 futex_wake(&pool->block.end, INT_MAX);
976 return offset;
977 } else {
978 futex_wait(&pool->block.end, block.end, NULL);
979 goto restart;
980 }
981 }
982
983 static uint32_t
984 anv_state_pool_get_bucket(uint32_t size)
985 {
986 unsigned size_log2 = ilog2_round_up(size);
987 assert(size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
988 if (size_log2 < ANV_MIN_STATE_SIZE_LOG2)
989 size_log2 = ANV_MIN_STATE_SIZE_LOG2;
990 return size_log2 - ANV_MIN_STATE_SIZE_LOG2;
991 }
992
993 static uint32_t
994 anv_state_pool_get_bucket_size(uint32_t bucket)
995 {
996 uint32_t size_log2 = bucket + ANV_MIN_STATE_SIZE_LOG2;
997 return 1 << size_log2;
998 }
999
1000 /** Helper to push a chunk into the state table.
1001 *
1002 * It creates 'count' entries into the state table and update their sizes,
1003 * offsets and maps, also pushing them as "free" states.
1004 */
1005 static void
1006 anv_state_pool_return_blocks(struct anv_state_pool *pool,
1007 uint32_t chunk_offset, uint32_t count,
1008 uint32_t block_size)
1009 {
1010 /* Disallow returning 0 chunks */
1011 assert(count != 0);
1012
1013 /* Make sure we always return chunks aligned to the block_size */
1014 assert(chunk_offset % block_size == 0);
1015
1016 uint32_t st_idx;
1017 UNUSED VkResult result = anv_state_table_add(&pool->table, &st_idx, count);
1018 assert(result == VK_SUCCESS);
1019 for (int i = 0; i < count; i++) {
1020 /* update states that were added back to the state table */
1021 struct anv_state *state_i = anv_state_table_get(&pool->table,
1022 st_idx + i);
1023 state_i->alloc_size = block_size;
1024 state_i->offset = chunk_offset + block_size * i;
1025 state_i->map = anv_block_pool_map(&pool->block_pool, state_i->offset);
1026 }
1027
1028 uint32_t block_bucket = anv_state_pool_get_bucket(block_size);
1029 anv_free_list_push(&pool->buckets[block_bucket].free_list,
1030 &pool->table, st_idx, count);
1031 }
1032
1033 /** Returns a chunk of memory back to the state pool.
1034 *
1035 * Do a two-level split. If chunk_size is bigger than divisor
1036 * (pool->block_size), we return as many divisor sized blocks as we can, from
1037 * the end of the chunk.
1038 *
1039 * The remaining is then split into smaller blocks (starting at small_size if
1040 * it is non-zero), with larger blocks always being taken from the end of the
1041 * chunk.
1042 */
1043 static void
1044 anv_state_pool_return_chunk(struct anv_state_pool *pool,
1045 uint32_t chunk_offset, uint32_t chunk_size,
1046 uint32_t small_size)
1047 {
1048 uint32_t divisor = pool->block_size;
1049 uint32_t nblocks = chunk_size / divisor;
1050 uint32_t rest = chunk_size - nblocks * divisor;
1051
1052 if (nblocks > 0) {
1053 /* First return divisor aligned and sized chunks. We start returning
1054 * larger blocks from the end fo the chunk, since they should already be
1055 * aligned to divisor. Also anv_state_pool_return_blocks() only accepts
1056 * aligned chunks.
1057 */
1058 uint32_t offset = chunk_offset + rest;
1059 anv_state_pool_return_blocks(pool, offset, nblocks, divisor);
1060 }
1061
1062 chunk_size = rest;
1063 divisor /= 2;
1064
1065 if (small_size > 0 && small_size < divisor)
1066 divisor = small_size;
1067
1068 uint32_t min_size = 1 << ANV_MIN_STATE_SIZE_LOG2;
1069
1070 /* Just as before, return larger divisor aligned blocks from the end of the
1071 * chunk first.
1072 */
1073 while (chunk_size > 0 && divisor >= min_size) {
1074 nblocks = chunk_size / divisor;
1075 rest = chunk_size - nblocks * divisor;
1076 if (nblocks > 0) {
1077 anv_state_pool_return_blocks(pool, chunk_offset + rest,
1078 nblocks, divisor);
1079 chunk_size = rest;
1080 }
1081 divisor /= 2;
1082 }
1083 }
1084
1085 static struct anv_state
1086 anv_state_pool_alloc_no_vg(struct anv_state_pool *pool,
1087 uint32_t size, uint32_t align)
1088 {
1089 uint32_t bucket = anv_state_pool_get_bucket(MAX2(size, align));
1090
1091 struct anv_state *state;
1092 uint32_t alloc_size = anv_state_pool_get_bucket_size(bucket);
1093 int32_t offset;
1094
1095 /* Try free list first. */
1096 state = anv_free_list_pop(&pool->buckets[bucket].free_list,
1097 &pool->table);
1098 if (state) {
1099 assert(state->offset >= 0);
1100 goto done;
1101 }
1102
1103 /* Try to grab a chunk from some larger bucket and split it up */
1104 for (unsigned b = bucket + 1; b < ANV_STATE_BUCKETS; b++) {
1105 state = anv_free_list_pop(&pool->buckets[b].free_list, &pool->table);
1106 if (state) {
1107 unsigned chunk_size = anv_state_pool_get_bucket_size(b);
1108 int32_t chunk_offset = state->offset;
1109
1110 /* First lets update the state we got to its new size. offset and map
1111 * remain the same.
1112 */
1113 state->alloc_size = alloc_size;
1114
1115 /* Now return the unused part of the chunk back to the pool as free
1116 * blocks
1117 *
1118 * There are a couple of options as to what we do with it:
1119 *
1120 * 1) We could fully split the chunk into state.alloc_size sized
1121 * pieces. However, this would mean that allocating a 16B
1122 * state could potentially split a 2MB chunk into 512K smaller
1123 * chunks. This would lead to unnecessary fragmentation.
1124 *
1125 * 2) The classic "buddy allocator" method would have us split the
1126 * chunk in half and return one half. Then we would split the
1127 * remaining half in half and return one half, and repeat as
1128 * needed until we get down to the size we want. However, if
1129 * you are allocating a bunch of the same size state (which is
1130 * the common case), this means that every other allocation has
1131 * to go up a level and every fourth goes up two levels, etc.
1132 * This is not nearly as efficient as it could be if we did a
1133 * little more work up-front.
1134 *
1135 * 3) Split the difference between (1) and (2) by doing a
1136 * two-level split. If it's bigger than some fixed block_size,
1137 * we split it into block_size sized chunks and return all but
1138 * one of them. Then we split what remains into
1139 * state.alloc_size sized chunks and return them.
1140 *
1141 * We choose something close to option (3), which is implemented with
1142 * anv_state_pool_return_chunk(). That is done by returning the
1143 * remaining of the chunk, with alloc_size as a hint of the size that
1144 * we want the smaller chunk split into.
1145 */
1146 anv_state_pool_return_chunk(pool, chunk_offset + alloc_size,
1147 chunk_size - alloc_size, alloc_size);
1148 goto done;
1149 }
1150 }
1151
1152 uint32_t padding;
1153 offset = anv_fixed_size_state_pool_alloc_new(&pool->buckets[bucket],
1154 &pool->block_pool,
1155 alloc_size,
1156 pool->block_size,
1157 &padding);
1158 /* Everytime we allocate a new state, add it to the state pool */
1159 uint32_t idx;
1160 UNUSED VkResult result = anv_state_table_add(&pool->table, &idx, 1);
1161 assert(result == VK_SUCCESS);
1162
1163 state = anv_state_table_get(&pool->table, idx);
1164 state->offset = offset;
1165 state->alloc_size = alloc_size;
1166 state->map = anv_block_pool_map(&pool->block_pool, offset);
1167
1168 if (padding > 0) {
1169 uint32_t return_offset = offset - padding;
1170 anv_state_pool_return_chunk(pool, return_offset, padding, 0);
1171 }
1172
1173 done:
1174 return *state;
1175 }
1176
1177 struct anv_state
1178 anv_state_pool_alloc(struct anv_state_pool *pool, uint32_t size, uint32_t align)
1179 {
1180 if (size == 0)
1181 return ANV_STATE_NULL;
1182
1183 struct anv_state state = anv_state_pool_alloc_no_vg(pool, size, align);
1184 VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, size));
1185 return state;
1186 }
1187
1188 struct anv_state
1189 anv_state_pool_alloc_back(struct anv_state_pool *pool)
1190 {
1191 struct anv_state *state;
1192 uint32_t alloc_size = pool->block_size;
1193
1194 state = anv_free_list_pop(&pool->back_alloc_free_list, &pool->table);
1195 if (state) {
1196 assert(state->offset < 0);
1197 goto done;
1198 }
1199
1200 int32_t offset;
1201 offset = anv_block_pool_alloc_back(&pool->block_pool,
1202 pool->block_size);
1203 uint32_t idx;
1204 UNUSED VkResult result = anv_state_table_add(&pool->table, &idx, 1);
1205 assert(result == VK_SUCCESS);
1206
1207 state = anv_state_table_get(&pool->table, idx);
1208 state->offset = offset;
1209 state->alloc_size = alloc_size;
1210 state->map = anv_block_pool_map(&pool->block_pool, state->offset);
1211
1212 done:
1213 VG(VALGRIND_MEMPOOL_ALLOC(pool, state->map, state->alloc_size));
1214 return *state;
1215 }
1216
1217 static void
1218 anv_state_pool_free_no_vg(struct anv_state_pool *pool, struct anv_state state)
1219 {
1220 assert(util_is_power_of_two_or_zero(state.alloc_size));
1221 unsigned bucket = anv_state_pool_get_bucket(state.alloc_size);
1222
1223 if (state.offset < 0) {
1224 assert(state.alloc_size == pool->block_size);
1225 anv_free_list_push(&pool->back_alloc_free_list,
1226 &pool->table, state.idx, 1);
1227 } else {
1228 anv_free_list_push(&pool->buckets[bucket].free_list,
1229 &pool->table, state.idx, 1);
1230 }
1231 }
1232
1233 void
1234 anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state)
1235 {
1236 if (state.alloc_size == 0)
1237 return;
1238
1239 VG(VALGRIND_MEMPOOL_FREE(pool, state.map));
1240 anv_state_pool_free_no_vg(pool, state);
1241 }
1242
1243 struct anv_state_stream_block {
1244 struct anv_state block;
1245
1246 /* The next block */
1247 struct anv_state_stream_block *next;
1248
1249 #ifdef HAVE_VALGRIND
1250 /* A pointer to the first user-allocated thing in this block. This is
1251 * what valgrind sees as the start of the block.
1252 */
1253 void *_vg_ptr;
1254 #endif
1255 };
1256
1257 /* The state stream allocator is a one-shot, single threaded allocator for
1258 * variable sized blocks. We use it for allocating dynamic state.
1259 */
1260 void
1261 anv_state_stream_init(struct anv_state_stream *stream,
1262 struct anv_state_pool *state_pool,
1263 uint32_t block_size)
1264 {
1265 stream->state_pool = state_pool;
1266 stream->block_size = block_size;
1267
1268 stream->block = ANV_STATE_NULL;
1269
1270 stream->block_list = NULL;
1271
1272 /* Ensure that next + whatever > block_size. This way the first call to
1273 * state_stream_alloc fetches a new block.
1274 */
1275 stream->next = block_size;
1276
1277 VG(VALGRIND_CREATE_MEMPOOL(stream, 0, false));
1278 }
1279
1280 void
1281 anv_state_stream_finish(struct anv_state_stream *stream)
1282 {
1283 struct anv_state_stream_block *next = stream->block_list;
1284 while (next != NULL) {
1285 struct anv_state_stream_block sb = VG_NOACCESS_READ(next);
1286 VG(VALGRIND_MEMPOOL_FREE(stream, sb._vg_ptr));
1287 VG(VALGRIND_MAKE_MEM_UNDEFINED(next, stream->block_size));
1288 anv_state_pool_free_no_vg(stream->state_pool, sb.block);
1289 next = sb.next;
1290 }
1291
1292 VG(VALGRIND_DESTROY_MEMPOOL(stream));
1293 }
1294
1295 struct anv_state
1296 anv_state_stream_alloc(struct anv_state_stream *stream,
1297 uint32_t size, uint32_t alignment)
1298 {
1299 if (size == 0)
1300 return ANV_STATE_NULL;
1301
1302 assert(alignment <= PAGE_SIZE);
1303
1304 uint32_t offset = align_u32(stream->next, alignment);
1305 if (offset + size > stream->block.alloc_size) {
1306 uint32_t block_size = stream->block_size;
1307 if (block_size < size)
1308 block_size = round_to_power_of_two(size);
1309
1310 stream->block = anv_state_pool_alloc_no_vg(stream->state_pool,
1311 block_size, PAGE_SIZE);
1312
1313 struct anv_state_stream_block *sb = stream->block.map;
1314 VG_NOACCESS_WRITE(&sb->block, stream->block);
1315 VG_NOACCESS_WRITE(&sb->next, stream->block_list);
1316 stream->block_list = sb;
1317 VG(VG_NOACCESS_WRITE(&sb->_vg_ptr, NULL));
1318
1319 VG(VALGRIND_MAKE_MEM_NOACCESS(stream->block.map, stream->block_size));
1320
1321 /* Reset back to the start plus space for the header */
1322 stream->next = sizeof(*sb);
1323
1324 offset = align_u32(stream->next, alignment);
1325 assert(offset + size <= stream->block.alloc_size);
1326 }
1327
1328 struct anv_state state = stream->block;
1329 state.offset += offset;
1330 state.alloc_size = size;
1331 state.map += offset;
1332
1333 stream->next = offset + size;
1334
1335 #ifdef HAVE_VALGRIND
1336 struct anv_state_stream_block *sb = stream->block_list;
1337 void *vg_ptr = VG_NOACCESS_READ(&sb->_vg_ptr);
1338 if (vg_ptr == NULL) {
1339 vg_ptr = state.map;
1340 VG_NOACCESS_WRITE(&sb->_vg_ptr, vg_ptr);
1341 VALGRIND_MEMPOOL_ALLOC(stream, vg_ptr, size);
1342 } else {
1343 void *state_end = state.map + state.alloc_size;
1344 /* This only updates the mempool. The newly allocated chunk is still
1345 * marked as NOACCESS. */
1346 VALGRIND_MEMPOOL_CHANGE(stream, vg_ptr, vg_ptr, state_end - vg_ptr);
1347 /* Mark the newly allocated chunk as undefined */
1348 VALGRIND_MAKE_MEM_UNDEFINED(state.map, state.alloc_size);
1349 }
1350 #endif
1351
1352 return state;
1353 }
1354
1355 struct bo_pool_bo_link {
1356 struct bo_pool_bo_link *next;
1357 struct anv_bo bo;
1358 };
1359
1360 void
1361 anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device,
1362 uint64_t bo_flags)
1363 {
1364 pool->device = device;
1365 pool->bo_flags = bo_flags;
1366 memset(pool->free_list, 0, sizeof(pool->free_list));
1367
1368 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
1369 }
1370
1371 void
1372 anv_bo_pool_finish(struct anv_bo_pool *pool)
1373 {
1374 for (unsigned i = 0; i < ARRAY_SIZE(pool->free_list); i++) {
1375 struct bo_pool_bo_link *link = PFL_PTR(pool->free_list[i]);
1376 while (link != NULL) {
1377 struct bo_pool_bo_link link_copy = VG_NOACCESS_READ(link);
1378
1379 anv_gem_munmap(link_copy.bo.map, link_copy.bo.size);
1380 anv_vma_free(pool->device, &link_copy.bo);
1381 anv_gem_close(pool->device, link_copy.bo.gem_handle);
1382 link = link_copy.next;
1383 }
1384 }
1385
1386 VG(VALGRIND_DESTROY_MEMPOOL(pool));
1387 }
1388
1389 VkResult
1390 anv_bo_pool_alloc(struct anv_bo_pool *pool, struct anv_bo *bo, uint32_t size)
1391 {
1392 VkResult result;
1393
1394 const unsigned size_log2 = size < 4096 ? 12 : ilog2_round_up(size);
1395 const unsigned pow2_size = 1 << size_log2;
1396 const unsigned bucket = size_log2 - 12;
1397 assert(bucket < ARRAY_SIZE(pool->free_list));
1398
1399 void *next_free_void;
1400 if (anv_ptr_free_list_pop(&pool->free_list[bucket], &next_free_void)) {
1401 struct bo_pool_bo_link *next_free = next_free_void;
1402 *bo = VG_NOACCESS_READ(&next_free->bo);
1403 assert(bo->gem_handle);
1404 assert(bo->map == next_free);
1405 assert(size <= bo->size);
1406
1407 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
1408
1409 return VK_SUCCESS;
1410 }
1411
1412 struct anv_bo new_bo;
1413
1414 result = anv_bo_init_new(&new_bo, pool->device, pow2_size);
1415 if (result != VK_SUCCESS)
1416 return result;
1417
1418 new_bo.flags = pool->bo_flags;
1419
1420 if (!anv_vma_alloc(pool->device, &new_bo))
1421 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1422
1423 assert(new_bo.size == pow2_size);
1424
1425 new_bo.map = anv_gem_mmap(pool->device, new_bo.gem_handle, 0, pow2_size, 0);
1426 if (new_bo.map == MAP_FAILED) {
1427 anv_gem_close(pool->device, new_bo.gem_handle);
1428 anv_vma_free(pool->device, &new_bo);
1429 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1430 }
1431
1432 /* We are removing the state flushes, so lets make sure that these buffers
1433 * are cached/snooped.
1434 */
1435 if (!pool->device->info.has_llc) {
1436 anv_gem_set_caching(pool->device, new_bo.gem_handle,
1437 I915_CACHING_CACHED);
1438 }
1439
1440 *bo = new_bo;
1441
1442 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
1443
1444 return VK_SUCCESS;
1445 }
1446
1447 void
1448 anv_bo_pool_free(struct anv_bo_pool *pool, const struct anv_bo *bo_in)
1449 {
1450 /* Make a copy in case the anv_bo happens to be storred in the BO */
1451 struct anv_bo bo = *bo_in;
1452
1453 VG(VALGRIND_MEMPOOL_FREE(pool, bo.map));
1454
1455 struct bo_pool_bo_link *link = bo.map;
1456 VG_NOACCESS_WRITE(&link->bo, bo);
1457
1458 assert(util_is_power_of_two_or_zero(bo.size));
1459 const unsigned size_log2 = ilog2_round_up(bo.size);
1460 const unsigned bucket = size_log2 - 12;
1461 assert(bucket < ARRAY_SIZE(pool->free_list));
1462
1463 anv_ptr_free_list_push(&pool->free_list[bucket], link);
1464 }
1465
1466 // Scratch pool
1467
1468 void
1469 anv_scratch_pool_init(struct anv_device *device, struct anv_scratch_pool *pool)
1470 {
1471 memset(pool, 0, sizeof(*pool));
1472 }
1473
1474 void
1475 anv_scratch_pool_finish(struct anv_device *device, struct anv_scratch_pool *pool)
1476 {
1477 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1478 for (unsigned i = 0; i < 16; i++) {
1479 struct anv_scratch_bo *bo = &pool->bos[i][s];
1480 if (bo->exists > 0) {
1481 anv_vma_free(device, &bo->bo);
1482 anv_gem_close(device, bo->bo.gem_handle);
1483 }
1484 }
1485 }
1486 }
1487
1488 struct anv_bo *
1489 anv_scratch_pool_alloc(struct anv_device *device, struct anv_scratch_pool *pool,
1490 gl_shader_stage stage, unsigned per_thread_scratch)
1491 {
1492 if (per_thread_scratch == 0)
1493 return NULL;
1494
1495 unsigned scratch_size_log2 = ffs(per_thread_scratch / 2048);
1496 assert(scratch_size_log2 < 16);
1497
1498 struct anv_scratch_bo *bo = &pool->bos[scratch_size_log2][stage];
1499
1500 /* We can use "exists" to shortcut and ignore the critical section */
1501 if (bo->exists)
1502 return &bo->bo;
1503
1504 pthread_mutex_lock(&device->mutex);
1505
1506 __sync_synchronize();
1507 if (bo->exists) {
1508 pthread_mutex_unlock(&device->mutex);
1509 return &bo->bo;
1510 }
1511
1512 const struct anv_physical_device *physical_device =
1513 &device->instance->physicalDevice;
1514 const struct gen_device_info *devinfo = &physical_device->info;
1515
1516 const unsigned subslices = MAX2(physical_device->subslice_total, 1);
1517
1518 unsigned scratch_ids_per_subslice;
1519 if (devinfo->is_haswell) {
1520 /* WaCSScratchSize:hsw
1521 *
1522 * Haswell's scratch space address calculation appears to be sparse
1523 * rather than tightly packed. The Thread ID has bits indicating
1524 * which subslice, EU within a subslice, and thread within an EU it
1525 * is. There's a maximum of two slices and two subslices, so these
1526 * can be stored with a single bit. Even though there are only 10 EUs
1527 * per subslice, this is stored in 4 bits, so there's an effective
1528 * maximum value of 16 EUs. Similarly, although there are only 7
1529 * threads per EU, this is stored in a 3 bit number, giving an
1530 * effective maximum value of 8 threads per EU.
1531 *
1532 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1533 * number of threads per subslice.
1534 */
1535 scratch_ids_per_subslice = 16 * 8;
1536 } else if (devinfo->is_cherryview) {
1537 /* Cherryview devices have either 6 or 8 EUs per subslice, and each EU
1538 * has 7 threads. The 6 EU devices appear to calculate thread IDs as if
1539 * it had 8 EUs.
1540 */
1541 scratch_ids_per_subslice = 8 * 7;
1542 } else {
1543 scratch_ids_per_subslice = devinfo->max_cs_threads;
1544 }
1545
1546 uint32_t max_threads[] = {
1547 [MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
1548 [MESA_SHADER_TESS_CTRL] = devinfo->max_tcs_threads,
1549 [MESA_SHADER_TESS_EVAL] = devinfo->max_tes_threads,
1550 [MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
1551 [MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
1552 [MESA_SHADER_COMPUTE] = scratch_ids_per_subslice * subslices,
1553 };
1554
1555 uint32_t size = per_thread_scratch * max_threads[stage];
1556
1557 anv_bo_init_new(&bo->bo, device, size);
1558
1559 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1560 * are still relative to the general state base address. When we emit
1561 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1562 * to the maximum (1 page under 4GB). This allows us to just place the
1563 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1564 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1565 * However, in order to do so, we need to ensure that the kernel does not
1566 * place the scratch BO above the 32-bit boundary.
1567 *
1568 * NOTE: Technically, it can't go "anywhere" because the top page is off
1569 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1570 * kernel allocates space using
1571 *
1572 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1573 *
1574 * so nothing will ever touch the top page.
1575 */
1576 assert(!(bo->bo.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS));
1577
1578 if (device->instance->physicalDevice.has_exec_async)
1579 bo->bo.flags |= EXEC_OBJECT_ASYNC;
1580
1581 if (device->instance->physicalDevice.use_softpin)
1582 bo->bo.flags |= EXEC_OBJECT_PINNED;
1583
1584 anv_vma_alloc(device, &bo->bo);
1585
1586 /* Set the exists last because it may be read by other threads */
1587 __sync_synchronize();
1588 bo->exists = true;
1589
1590 pthread_mutex_unlock(&device->mutex);
1591
1592 return &bo->bo;
1593 }
1594
1595 struct anv_cached_bo {
1596 struct anv_bo bo;
1597
1598 uint32_t refcount;
1599 };
1600
1601 VkResult
1602 anv_bo_cache_init(struct anv_bo_cache *cache)
1603 {
1604 cache->bo_map = _mesa_pointer_hash_table_create(NULL);
1605 if (!cache->bo_map)
1606 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1607
1608 if (pthread_mutex_init(&cache->mutex, NULL)) {
1609 _mesa_hash_table_destroy(cache->bo_map, NULL);
1610 return vk_errorf(NULL, NULL, VK_ERROR_OUT_OF_HOST_MEMORY,
1611 "pthread_mutex_init failed: %m");
1612 }
1613
1614 return VK_SUCCESS;
1615 }
1616
1617 void
1618 anv_bo_cache_finish(struct anv_bo_cache *cache)
1619 {
1620 _mesa_hash_table_destroy(cache->bo_map, NULL);
1621 pthread_mutex_destroy(&cache->mutex);
1622 }
1623
1624 static struct anv_cached_bo *
1625 anv_bo_cache_lookup_locked(struct anv_bo_cache *cache, uint32_t gem_handle)
1626 {
1627 struct hash_entry *entry =
1628 _mesa_hash_table_search(cache->bo_map,
1629 (const void *)(uintptr_t)gem_handle);
1630 if (!entry)
1631 return NULL;
1632
1633 struct anv_cached_bo *bo = (struct anv_cached_bo *)entry->data;
1634 assert(bo->bo.gem_handle == gem_handle);
1635
1636 return bo;
1637 }
1638
1639 UNUSED static struct anv_bo *
1640 anv_bo_cache_lookup(struct anv_bo_cache *cache, uint32_t gem_handle)
1641 {
1642 pthread_mutex_lock(&cache->mutex);
1643
1644 struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
1645
1646 pthread_mutex_unlock(&cache->mutex);
1647
1648 return bo ? &bo->bo : NULL;
1649 }
1650
1651 #define ANV_BO_CACHE_SUPPORTED_FLAGS \
1652 (EXEC_OBJECT_WRITE | \
1653 EXEC_OBJECT_ASYNC | \
1654 EXEC_OBJECT_SUPPORTS_48B_ADDRESS | \
1655 EXEC_OBJECT_PINNED | \
1656 ANV_BO_EXTERNAL)
1657
1658 VkResult
1659 anv_bo_cache_alloc(struct anv_device *device,
1660 struct anv_bo_cache *cache,
1661 uint64_t size, uint64_t bo_flags,
1662 struct anv_bo **bo_out)
1663 {
1664 assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1665
1666 struct anv_cached_bo *bo =
1667 vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
1668 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1669 if (!bo)
1670 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1671
1672 bo->refcount = 1;
1673
1674 /* The kernel is going to give us whole pages anyway */
1675 size = align_u64(size, 4096);
1676
1677 VkResult result = anv_bo_init_new(&bo->bo, device, size);
1678 if (result != VK_SUCCESS) {
1679 vk_free(&device->alloc, bo);
1680 return result;
1681 }
1682
1683 bo->bo.flags = bo_flags;
1684
1685 if (!anv_vma_alloc(device, &bo->bo)) {
1686 anv_gem_close(device, bo->bo.gem_handle);
1687 vk_free(&device->alloc, bo);
1688 return vk_errorf(device->instance, NULL,
1689 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1690 "failed to allocate virtual address for BO");
1691 }
1692
1693 assert(bo->bo.gem_handle);
1694
1695 pthread_mutex_lock(&cache->mutex);
1696
1697 _mesa_hash_table_insert(cache->bo_map,
1698 (void *)(uintptr_t)bo->bo.gem_handle, bo);
1699
1700 pthread_mutex_unlock(&cache->mutex);
1701
1702 *bo_out = &bo->bo;
1703
1704 return VK_SUCCESS;
1705 }
1706
1707 VkResult
1708 anv_bo_cache_import_host_ptr(struct anv_device *device,
1709 struct anv_bo_cache *cache,
1710 void *host_ptr, uint32_t size,
1711 uint64_t bo_flags, struct anv_bo **bo_out)
1712 {
1713 assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1714 assert((bo_flags & ANV_BO_EXTERNAL) == 0);
1715
1716 uint32_t gem_handle = anv_gem_userptr(device, host_ptr, size);
1717 if (!gem_handle)
1718 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
1719
1720 pthread_mutex_lock(&cache->mutex);
1721
1722 struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
1723 if (bo) {
1724 /* VK_EXT_external_memory_host doesn't require handling importing the
1725 * same pointer twice at the same time, but we don't get in the way. If
1726 * kernel gives us the same gem_handle, only succeed if the flags match.
1727 */
1728 if (bo_flags != bo->bo.flags) {
1729 pthread_mutex_unlock(&cache->mutex);
1730 return vk_errorf(device->instance, NULL,
1731 VK_ERROR_INVALID_EXTERNAL_HANDLE,
1732 "same host pointer imported two different ways");
1733 }
1734 __sync_fetch_and_add(&bo->refcount, 1);
1735 } else {
1736 bo = vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
1737 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1738 if (!bo) {
1739 anv_gem_close(device, gem_handle);
1740 pthread_mutex_unlock(&cache->mutex);
1741 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1742 }
1743
1744 bo->refcount = 1;
1745
1746 anv_bo_init(&bo->bo, gem_handle, size);
1747 bo->bo.flags = bo_flags;
1748
1749 if (!anv_vma_alloc(device, &bo->bo)) {
1750 anv_gem_close(device, bo->bo.gem_handle);
1751 pthread_mutex_unlock(&cache->mutex);
1752 vk_free(&device->alloc, bo);
1753 return vk_errorf(device->instance, NULL,
1754 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1755 "failed to allocate virtual address for BO");
1756 }
1757
1758 _mesa_hash_table_insert(cache->bo_map, (void *)(uintptr_t)gem_handle, bo);
1759 }
1760
1761 pthread_mutex_unlock(&cache->mutex);
1762 *bo_out = &bo->bo;
1763
1764 return VK_SUCCESS;
1765 }
1766
1767 VkResult
1768 anv_bo_cache_import(struct anv_device *device,
1769 struct anv_bo_cache *cache,
1770 int fd, uint64_t bo_flags,
1771 struct anv_bo **bo_out)
1772 {
1773 assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1774 assert(bo_flags & ANV_BO_EXTERNAL);
1775
1776 pthread_mutex_lock(&cache->mutex);
1777
1778 uint32_t gem_handle = anv_gem_fd_to_handle(device, fd);
1779 if (!gem_handle) {
1780 pthread_mutex_unlock(&cache->mutex);
1781 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
1782 }
1783
1784 struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
1785 if (bo) {
1786 /* We have to be careful how we combine flags so that it makes sense.
1787 * Really, though, if we get to this case and it actually matters, the
1788 * client has imported a BO twice in different ways and they get what
1789 * they have coming.
1790 */
1791 uint64_t new_flags = ANV_BO_EXTERNAL;
1792 new_flags |= (bo->bo.flags | bo_flags) & EXEC_OBJECT_WRITE;
1793 new_flags |= (bo->bo.flags & bo_flags) & EXEC_OBJECT_ASYNC;
1794 new_flags |= (bo->bo.flags & bo_flags) & EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1795 new_flags |= (bo->bo.flags | bo_flags) & EXEC_OBJECT_PINNED;
1796
1797 /* It's theoretically possible for a BO to get imported such that it's
1798 * both pinned and not pinned. The only way this can happen is if it
1799 * gets imported as both a semaphore and a memory object and that would
1800 * be an application error. Just fail out in that case.
1801 */
1802 if ((bo->bo.flags & EXEC_OBJECT_PINNED) !=
1803 (bo_flags & EXEC_OBJECT_PINNED)) {
1804 pthread_mutex_unlock(&cache->mutex);
1805 return vk_errorf(device->instance, NULL,
1806 VK_ERROR_INVALID_EXTERNAL_HANDLE,
1807 "The same BO was imported two different ways");
1808 }
1809
1810 /* It's also theoretically possible that someone could export a BO from
1811 * one heap and import it into another or to import the same BO into two
1812 * different heaps. If this happens, we could potentially end up both
1813 * allowing and disallowing 48-bit addresses. There's not much we can
1814 * do about it if we're pinning so we just throw an error and hope no
1815 * app is actually that stupid.
1816 */
1817 if ((new_flags & EXEC_OBJECT_PINNED) &&
1818 (bo->bo.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) !=
1819 (bo_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS)) {
1820 pthread_mutex_unlock(&cache->mutex);
1821 return vk_errorf(device->instance, NULL,
1822 VK_ERROR_INVALID_EXTERNAL_HANDLE,
1823 "The same BO was imported on two different heaps");
1824 }
1825
1826 bo->bo.flags = new_flags;
1827
1828 __sync_fetch_and_add(&bo->refcount, 1);
1829 } else {
1830 off_t size = lseek(fd, 0, SEEK_END);
1831 if (size == (off_t)-1) {
1832 anv_gem_close(device, gem_handle);
1833 pthread_mutex_unlock(&cache->mutex);
1834 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
1835 }
1836
1837 bo = vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
1838 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1839 if (!bo) {
1840 anv_gem_close(device, gem_handle);
1841 pthread_mutex_unlock(&cache->mutex);
1842 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1843 }
1844
1845 bo->refcount = 1;
1846
1847 anv_bo_init(&bo->bo, gem_handle, size);
1848 bo->bo.flags = bo_flags;
1849
1850 if (!anv_vma_alloc(device, &bo->bo)) {
1851 anv_gem_close(device, bo->bo.gem_handle);
1852 pthread_mutex_unlock(&cache->mutex);
1853 vk_free(&device->alloc, bo);
1854 return vk_errorf(device->instance, NULL,
1855 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1856 "failed to allocate virtual address for BO");
1857 }
1858
1859 _mesa_hash_table_insert(cache->bo_map, (void *)(uintptr_t)gem_handle, bo);
1860 }
1861
1862 pthread_mutex_unlock(&cache->mutex);
1863 *bo_out = &bo->bo;
1864
1865 return VK_SUCCESS;
1866 }
1867
1868 VkResult
1869 anv_bo_cache_export(struct anv_device *device,
1870 struct anv_bo_cache *cache,
1871 struct anv_bo *bo_in, int *fd_out)
1872 {
1873 assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
1874 struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
1875
1876 /* This BO must have been flagged external in order for us to be able
1877 * to export it. This is done based on external options passed into
1878 * anv_AllocateMemory.
1879 */
1880 assert(bo->bo.flags & ANV_BO_EXTERNAL);
1881
1882 int fd = anv_gem_handle_to_fd(device, bo->bo.gem_handle);
1883 if (fd < 0)
1884 return vk_error(VK_ERROR_TOO_MANY_OBJECTS);
1885
1886 *fd_out = fd;
1887
1888 return VK_SUCCESS;
1889 }
1890
1891 static bool
1892 atomic_dec_not_one(uint32_t *counter)
1893 {
1894 uint32_t old, val;
1895
1896 val = *counter;
1897 while (1) {
1898 if (val == 1)
1899 return false;
1900
1901 old = __sync_val_compare_and_swap(counter, val, val - 1);
1902 if (old == val)
1903 return true;
1904
1905 val = old;
1906 }
1907 }
1908
1909 void
1910 anv_bo_cache_release(struct anv_device *device,
1911 struct anv_bo_cache *cache,
1912 struct anv_bo *bo_in)
1913 {
1914 assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
1915 struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
1916
1917 /* Try to decrement the counter but don't go below one. If this succeeds
1918 * then the refcount has been decremented and we are not the last
1919 * reference.
1920 */
1921 if (atomic_dec_not_one(&bo->refcount))
1922 return;
1923
1924 pthread_mutex_lock(&cache->mutex);
1925
1926 /* We are probably the last reference since our attempt to decrement above
1927 * failed. However, we can't actually know until we are inside the mutex.
1928 * Otherwise, someone could import the BO between the decrement and our
1929 * taking the mutex.
1930 */
1931 if (unlikely(__sync_sub_and_fetch(&bo->refcount, 1) > 0)) {
1932 /* Turns out we're not the last reference. Unlock and bail. */
1933 pthread_mutex_unlock(&cache->mutex);
1934 return;
1935 }
1936
1937 struct hash_entry *entry =
1938 _mesa_hash_table_search(cache->bo_map,
1939 (const void *)(uintptr_t)bo->bo.gem_handle);
1940 assert(entry);
1941 _mesa_hash_table_remove(cache->bo_map, entry);
1942
1943 if (bo->bo.map)
1944 anv_gem_munmap(bo->bo.map, bo->bo.size);
1945
1946 anv_vma_free(device, &bo->bo);
1947
1948 anv_gem_close(device, bo->bo.gem_handle);
1949
1950 /* Don't unlock until we've actually closed the BO. The whole point of
1951 * the BO cache is to ensure that we correctly handle races with creating
1952 * and releasing GEM handles and we don't want to let someone import the BO
1953 * again between mutex unlock and closing the GEM handle.
1954 */
1955 pthread_mutex_unlock(&cache->mutex);
1956
1957 vk_free(&device->alloc, bo);
1958 }