anv/allocator: Rework a comment
[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 <stdint.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <limits.h>
28 #include <assert.h>
29 #include <linux/futex.h>
30 #include <linux/memfd.h>
31 #include <sys/time.h>
32 #include <sys/mman.h>
33 #include <sys/syscall.h>
34
35 #include "anv_private.h"
36
37 #include "util/hash_table.h"
38
39 #ifdef HAVE_VALGRIND
40 #define VG_NOACCESS_READ(__ptr) ({ \
41 VALGRIND_MAKE_MEM_DEFINED((__ptr), sizeof(*(__ptr))); \
42 __typeof(*(__ptr)) __val = *(__ptr); \
43 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr)));\
44 __val; \
45 })
46 #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
47 VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
48 *(__ptr) = (__val); \
49 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
50 })
51 #else
52 #define VG_NOACCESS_READ(__ptr) (*(__ptr))
53 #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
54 #endif
55
56 /* Design goals:
57 *
58 * - Lock free (except when resizing underlying bos)
59 *
60 * - Constant time allocation with typically only one atomic
61 *
62 * - Multiple allocation sizes without fragmentation
63 *
64 * - Can grow while keeping addresses and offset of contents stable
65 *
66 * - All allocations within one bo so we can point one of the
67 * STATE_BASE_ADDRESS pointers at it.
68 *
69 * The overall design is a two-level allocator: top level is a fixed size, big
70 * block (8k) allocator, which operates out of a bo. Allocation is done by
71 * either pulling a block from the free list or growing the used range of the
72 * bo. Growing the range may run out of space in the bo which we then need to
73 * grow. Growing the bo is tricky in a multi-threaded, lockless environment:
74 * we need to keep all pointers and contents in the old map valid. GEM bos in
75 * general can't grow, but we use a trick: we create a memfd and use ftruncate
76 * to grow it as necessary. We mmap the new size and then create a gem bo for
77 * it using the new gem userptr ioctl. Without heavy-handed locking around
78 * our allocation fast-path, there isn't really a way to munmap the old mmap,
79 * so we just keep it around until garbage collection time. While the block
80 * allocator is lockless for normal operations, we block other threads trying
81 * to allocate while we're growing the map. It sholdn't happen often, and
82 * growing is fast anyway.
83 *
84 * At the next level we can use various sub-allocators. The state pool is a
85 * pool of smaller, fixed size objects, which operates much like the block
86 * pool. It uses a free list for freeing objects, but when it runs out of
87 * space it just allocates a new block from the block pool. This allocator is
88 * intended for longer lived state objects such as SURFACE_STATE and most
89 * other persistent state objects in the API. We may need to track more info
90 * with these object and a pointer back to the CPU object (eg VkImage). In
91 * those cases we just allocate a slightly bigger object and put the extra
92 * state after the GPU state object.
93 *
94 * The state stream allocator works similar to how the i965 DRI driver streams
95 * all its state. Even with Vulkan, we need to emit transient state (whether
96 * surface state base or dynamic state base), and for that we can just get a
97 * block and fill it up. These cases are local to a command buffer and the
98 * sub-allocator need not be thread safe. The streaming allocator gets a new
99 * block when it runs out of space and chains them together so they can be
100 * easily freed.
101 */
102
103 /* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
104 * We use it to indicate the free list is empty. */
105 #define EMPTY 1
106
107 struct anv_mmap_cleanup {
108 void *map;
109 size_t size;
110 uint32_t gem_handle;
111 };
112
113 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
114
115 static inline long
116 sys_futex(void *addr1, int op, int val1,
117 struct timespec *timeout, void *addr2, int val3)
118 {
119 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
120 }
121
122 static inline int
123 futex_wake(uint32_t *addr, int count)
124 {
125 return sys_futex(addr, FUTEX_WAKE, count, NULL, NULL, 0);
126 }
127
128 static inline int
129 futex_wait(uint32_t *addr, int32_t value)
130 {
131 return sys_futex(addr, FUTEX_WAIT, value, NULL, NULL, 0);
132 }
133
134 static inline int
135 memfd_create(const char *name, unsigned int flags)
136 {
137 return syscall(SYS_memfd_create, name, flags);
138 }
139
140 static inline uint32_t
141 ilog2_round_up(uint32_t value)
142 {
143 assert(value != 0);
144 return 32 - __builtin_clz(value - 1);
145 }
146
147 static inline uint32_t
148 round_to_power_of_two(uint32_t value)
149 {
150 return 1 << ilog2_round_up(value);
151 }
152
153 static bool
154 anv_free_list_pop(union anv_free_list *list, void **map, int32_t *offset)
155 {
156 union anv_free_list current, new, old;
157
158 current.u64 = list->u64;
159 while (current.offset != EMPTY) {
160 /* We have to add a memory barrier here so that the list head (and
161 * offset) gets read before we read the map pointer. This way we
162 * know that the map pointer is valid for the given offset at the
163 * point where we read it.
164 */
165 __sync_synchronize();
166
167 int32_t *next_ptr = *map + current.offset;
168 new.offset = VG_NOACCESS_READ(next_ptr);
169 new.count = current.count + 1;
170 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
171 if (old.u64 == current.u64) {
172 *offset = current.offset;
173 return true;
174 }
175 current = old;
176 }
177
178 return false;
179 }
180
181 static void
182 anv_free_list_push(union anv_free_list *list, void *map, int32_t offset)
183 {
184 union anv_free_list current, old, new;
185 int32_t *next_ptr = map + offset;
186
187 old = *list;
188 do {
189 current = old;
190 VG_NOACCESS_WRITE(next_ptr, current.offset);
191 new.offset = offset;
192 new.count = current.count + 1;
193 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
194 } while (old.u64 != current.u64);
195 }
196
197 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
198 * means that the bottom 12 bits should all be zero.
199 */
200 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
201 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
202 #define PFL_PACK(ptr, count) ({ \
203 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
204 })
205
206 static bool
207 anv_ptr_free_list_pop(void **list, void **elem)
208 {
209 void *current = *list;
210 while (PFL_PTR(current) != NULL) {
211 void **next_ptr = PFL_PTR(current);
212 void *new_ptr = VG_NOACCESS_READ(next_ptr);
213 unsigned new_count = PFL_COUNT(current) + 1;
214 void *new = PFL_PACK(new_ptr, new_count);
215 void *old = __sync_val_compare_and_swap(list, current, new);
216 if (old == current) {
217 *elem = PFL_PTR(current);
218 return true;
219 }
220 current = old;
221 }
222
223 return false;
224 }
225
226 static void
227 anv_ptr_free_list_push(void **list, void *elem)
228 {
229 void *old, *current;
230 void **next_ptr = elem;
231
232 /* The pointer-based free list requires that the pointer be
233 * page-aligned. This is because we use the bottom 12 bits of the
234 * pointer to store a counter to solve the ABA concurrency problem.
235 */
236 assert(((uintptr_t)elem & 0xfff) == 0);
237
238 old = *list;
239 do {
240 current = old;
241 VG_NOACCESS_WRITE(next_ptr, PFL_PTR(current));
242 unsigned new_count = PFL_COUNT(current) + 1;
243 void *new = PFL_PACK(elem, new_count);
244 old = __sync_val_compare_and_swap(list, current, new);
245 } while (old != current);
246 }
247
248 static VkResult
249 anv_block_pool_expand_range(struct anv_block_pool *pool,
250 uint32_t center_bo_offset, uint32_t size);
251
252 VkResult
253 anv_block_pool_init(struct anv_block_pool *pool,
254 struct anv_device *device,
255 uint32_t initial_size)
256 {
257 VkResult result;
258
259 pool->device = device;
260 anv_bo_init(&pool->bo, 0, 0);
261
262 pool->fd = memfd_create("block pool", MFD_CLOEXEC);
263 if (pool->fd == -1)
264 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
265
266 /* Just make it 2GB up-front. The Linux kernel won't actually back it
267 * with pages until we either map and fault on one of them or we use
268 * userptr and send a chunk of it off to the GPU.
269 */
270 if (ftruncate(pool->fd, BLOCK_POOL_MEMFD_SIZE) == -1) {
271 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
272 goto fail_fd;
273 }
274
275 if (!u_vector_init(&pool->mmap_cleanups,
276 round_to_power_of_two(sizeof(struct anv_mmap_cleanup)),
277 128)) {
278 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
279 goto fail_fd;
280 }
281
282 pool->state.next = 0;
283 pool->state.end = 0;
284 pool->back_state.next = 0;
285 pool->back_state.end = 0;
286
287 result = anv_block_pool_expand_range(pool, 0, initial_size);
288 if (result != VK_SUCCESS)
289 goto fail_mmap_cleanups;
290
291 return VK_SUCCESS;
292
293 fail_mmap_cleanups:
294 u_vector_finish(&pool->mmap_cleanups);
295 fail_fd:
296 close(pool->fd);
297
298 return result;
299 }
300
301 void
302 anv_block_pool_finish(struct anv_block_pool *pool)
303 {
304 struct anv_mmap_cleanup *cleanup;
305
306 u_vector_foreach(cleanup, &pool->mmap_cleanups) {
307 if (cleanup->map)
308 munmap(cleanup->map, cleanup->size);
309 if (cleanup->gem_handle)
310 anv_gem_close(pool->device, cleanup->gem_handle);
311 }
312
313 u_vector_finish(&pool->mmap_cleanups);
314
315 close(pool->fd);
316 }
317
318 #define PAGE_SIZE 4096
319
320 static VkResult
321 anv_block_pool_expand_range(struct anv_block_pool *pool,
322 uint32_t center_bo_offset, uint32_t size)
323 {
324 void *map;
325 uint32_t gem_handle;
326 struct anv_mmap_cleanup *cleanup;
327
328 /* Assert that we only ever grow the pool */
329 assert(center_bo_offset >= pool->back_state.end);
330 assert(size - center_bo_offset >= pool->state.end);
331
332 cleanup = u_vector_add(&pool->mmap_cleanups);
333 if (!cleanup)
334 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
335
336 *cleanup = ANV_MMAP_CLEANUP_INIT;
337
338 /* Just leak the old map until we destroy the pool. We can't munmap it
339 * without races or imposing locking on the block allocate fast path. On
340 * the whole the leaked maps adds up to less than the size of the
341 * current map. MAP_POPULATE seems like the right thing to do, but we
342 * should try to get some numbers.
343 */
344 map = mmap(NULL, size, PROT_READ | PROT_WRITE,
345 MAP_SHARED | MAP_POPULATE, pool->fd,
346 BLOCK_POOL_MEMFD_CENTER - center_bo_offset);
347 if (map == MAP_FAILED)
348 return vk_errorf(VK_ERROR_MEMORY_MAP_FAILED, "mmap failed: %m");
349
350 gem_handle = anv_gem_userptr(pool->device, map, size);
351 if (gem_handle == 0) {
352 munmap(map, size);
353 return vk_errorf(VK_ERROR_TOO_MANY_OBJECTS, "userptr failed: %m");
354 }
355
356 cleanup->map = map;
357 cleanup->size = size;
358 cleanup->gem_handle = gem_handle;
359
360 #if 0
361 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
362 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
363 * always created as I915_CACHING_CACHED, which on non-LLC means
364 * snooped. That can be useful but comes with a bit of overheard. Since
365 * we're eplicitly clflushing and don't want the overhead we need to turn
366 * it off. */
367 if (!pool->device->info.has_llc) {
368 anv_gem_set_caching(pool->device, gem_handle, I915_CACHING_NONE);
369 anv_gem_set_domain(pool->device, gem_handle,
370 I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);
371 }
372 #endif
373
374 /* Now that we successfull allocated everything, we can write the new
375 * values back into pool. */
376 pool->map = map + center_bo_offset;
377 pool->center_bo_offset = center_bo_offset;
378
379 /* For block pool BOs we have to be a bit careful about where we place them
380 * in the GTT. There are two documented workarounds for state base address
381 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
382 * which state that those two base addresses do not support 48-bit
383 * addresses and need to be placed in the bottom 32-bit range.
384 * Unfortunately, this is not quite accurate.
385 *
386 * The real problem is that we always set the size of our state pools in
387 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
388 * likely significantly smaller. We do this because we do not no at the
389 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
390 * the pool during command buffer building so we don't actually have a
391 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
392 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
393 * as being out of bounds and returns zero. For dynamic state, this
394 * usually just leads to rendering corruptions, but shaders that are all
395 * zero hang the GPU immediately.
396 *
397 * The easiest solution to do is exactly what the bogus workarounds say to
398 * do: restrict these buffers to 32-bit addresses. We could also pin the
399 * BO to some particular location of our choosing, but that's significantly
400 * more work than just not setting a flag. So, we explicitly DO NOT set
401 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
402 * hard work for us.
403 */
404 anv_bo_init(&pool->bo, gem_handle, size);
405 pool->bo.map = map;
406
407 return VK_SUCCESS;
408 }
409
410 /** Grows and re-centers the block pool.
411 *
412 * We grow the block pool in one or both directions in such a way that the
413 * following conditions are met:
414 *
415 * 1) The size of the entire pool is always a power of two.
416 *
417 * 2) The pool only grows on both ends. Neither end can get
418 * shortened.
419 *
420 * 3) At the end of the allocation, we have about twice as much space
421 * allocated for each end as we have used. This way the pool doesn't
422 * grow too far in one direction or the other.
423 *
424 * 4) If the _alloc_back() has never been called, then the back portion of
425 * the pool retains a size of zero. (This makes it easier for users of
426 * the block pool that only want a one-sided pool.)
427 *
428 * 5) We have enough space allocated for at least one more block in
429 * whichever side `state` points to.
430 *
431 * 6) The center of the pool is always aligned to both the block_size of
432 * the pool and a 4K CPU page.
433 */
434 static uint32_t
435 anv_block_pool_grow(struct anv_block_pool *pool, struct anv_block_state *state,
436 uint32_t block_size)
437 {
438 VkResult result = VK_SUCCESS;
439
440 pthread_mutex_lock(&pool->device->mutex);
441
442 assert(state == &pool->state || state == &pool->back_state);
443
444 /* Gather a little usage information on the pool. Since we may have
445 * threadsd waiting in queue to get some storage while we resize, it's
446 * actually possible that total_used will be larger than old_size. In
447 * particular, block_pool_alloc() increments state->next prior to
448 * calling block_pool_grow, so this ensures that we get enough space for
449 * which ever side tries to grow the pool.
450 *
451 * We align to a page size because it makes it easier to do our
452 * calculations later in such a way that we state page-aigned.
453 */
454 uint32_t back_used = align_u32(pool->back_state.next, PAGE_SIZE);
455 uint32_t front_used = align_u32(pool->state.next, PAGE_SIZE);
456 uint32_t total_used = front_used + back_used;
457
458 assert(state == &pool->state || back_used > 0);
459
460 uint32_t old_size = pool->bo.size;
461
462 /* The block pool is always initialized to a nonzero size and this function
463 * is always called after initialization.
464 */
465 assert(old_size > 0);
466
467 /* The back_used and front_used may actually be smaller than the actual
468 * requirement because they are based on the next pointers which are
469 * updated prior to calling this function.
470 */
471 uint32_t back_required = MAX2(back_used, pool->center_bo_offset);
472 uint32_t front_required = MAX2(front_used, old_size - pool->center_bo_offset);
473
474 if (back_used * 2 <= back_required && front_used * 2 <= front_required) {
475 /* If we're in this case then this isn't the firsta allocation and we
476 * already have enough space on both sides to hold double what we
477 * have allocated. There's nothing for us to do.
478 */
479 goto done;
480 }
481
482 uint32_t size = old_size * 2;
483 while (size < back_required + front_required)
484 size *= 2;
485
486 assert(size > pool->bo.size);
487
488 /* We can't have a block pool bigger than 1GB because we use signed
489 * 32-bit offsets in the free list and we don't want overflow. We
490 * should never need a block pool bigger than 1GB anyway.
491 */
492 assert(size <= (1u << 31));
493
494 /* We compute a new center_bo_offset such that, when we double the size
495 * of the pool, we maintain the ratio of how much is used by each side.
496 * This way things should remain more-or-less balanced.
497 */
498 uint32_t center_bo_offset;
499 if (back_used == 0) {
500 /* If we're in this case then we have never called alloc_back(). In
501 * this case, we want keep the offset at 0 to make things as simple
502 * as possible for users that don't care about back allocations.
503 */
504 center_bo_offset = 0;
505 } else {
506 /* Try to "center" the allocation based on how much is currently in
507 * use on each side of the center line.
508 */
509 center_bo_offset = ((uint64_t)size * back_used) / total_used;
510
511 /* Align down to a multiple of both the block size and page size */
512 uint32_t granularity = MAX2(block_size, PAGE_SIZE);
513 assert(util_is_power_of_two(granularity));
514 center_bo_offset &= ~(granularity - 1);
515
516 assert(center_bo_offset >= back_used);
517
518 /* Make sure we don't shrink the back end of the pool */
519 if (center_bo_offset < pool->back_state.end)
520 center_bo_offset = pool->back_state.end;
521
522 /* Make sure that we don't shrink the front end of the pool */
523 if (size - center_bo_offset < pool->state.end)
524 center_bo_offset = size - pool->state.end;
525 }
526
527 assert(center_bo_offset % block_size == 0);
528 assert(center_bo_offset % PAGE_SIZE == 0);
529
530 result = anv_block_pool_expand_range(pool, center_bo_offset, size);
531
532 if (pool->device->instance->physicalDevice.has_exec_async)
533 pool->bo.flags |= EXEC_OBJECT_ASYNC;
534
535 done:
536 pthread_mutex_unlock(&pool->device->mutex);
537
538 if (result == VK_SUCCESS) {
539 /* Return the appropriate new size. This function never actually
540 * updates state->next. Instead, we let the caller do that because it
541 * needs to do so in order to maintain its concurrency model.
542 */
543 if (state == &pool->state) {
544 return pool->bo.size - pool->center_bo_offset;
545 } else {
546 assert(pool->center_bo_offset > 0);
547 return pool->center_bo_offset;
548 }
549 } else {
550 return 0;
551 }
552 }
553
554 static uint32_t
555 anv_block_pool_alloc_new(struct anv_block_pool *pool,
556 struct anv_block_state *pool_state,
557 uint32_t block_size)
558 {
559 struct anv_block_state state, old, new;
560
561 assert(util_is_power_of_two(block_size));
562
563 while (1) {
564 state.u64 = __sync_fetch_and_add(&pool_state->u64, block_size);
565 if (state.next < state.end) {
566 assert(pool->map);
567 return state.next;
568 } else if (state.next == state.end) {
569 /* We allocated the first block outside the pool so we have to grow
570 * the pool. pool_state->next acts a mutex: threads who try to
571 * allocate now will get block indexes above the current limit and
572 * hit futex_wait below.
573 */
574 new.next = state.next + block_size;
575 new.end = anv_block_pool_grow(pool, pool_state, block_size);
576 old.u64 = __sync_lock_test_and_set(&pool_state->u64, new.u64);
577 if (old.next != state.next)
578 futex_wake(&pool_state->end, INT_MAX);
579 return state.next;
580 } else {
581 futex_wait(&pool_state->end, state.end);
582 continue;
583 }
584 }
585 }
586
587 int32_t
588 anv_block_pool_alloc(struct anv_block_pool *pool,
589 uint32_t block_size)
590 {
591 return anv_block_pool_alloc_new(pool, &pool->state, block_size);
592 }
593
594 /* Allocates a block out of the back of the block pool.
595 *
596 * This will allocated a block earlier than the "start" of the block pool.
597 * The offsets returned from this function will be negative but will still
598 * be correct relative to the block pool's map pointer.
599 *
600 * If you ever use anv_block_pool_alloc_back, then you will have to do
601 * gymnastics with the block pool's BO when doing relocations.
602 */
603 int32_t
604 anv_block_pool_alloc_back(struct anv_block_pool *pool,
605 uint32_t block_size)
606 {
607 int32_t offset = anv_block_pool_alloc_new(pool, &pool->back_state,
608 block_size);
609
610 /* The offset we get out of anv_block_pool_alloc_new() is actually the
611 * number of bytes downwards from the middle to the end of the block.
612 * We need to turn it into a (negative) offset from the middle to the
613 * start of the block.
614 */
615 assert(offset >= 0);
616 return -(offset + block_size);
617 }
618
619 VkResult
620 anv_state_pool_init(struct anv_state_pool *pool,
621 struct anv_device *device,
622 uint32_t block_size)
623 {
624 VkResult result = anv_block_pool_init(&pool->block_pool, device,
625 block_size * 16);
626 if (result != VK_SUCCESS)
627 return result;
628
629 assert(util_is_power_of_two(block_size));
630 pool->block_size = block_size;
631 pool->back_alloc_free_list = ANV_FREE_LIST_EMPTY;
632 for (unsigned i = 0; i < ANV_STATE_BUCKETS; i++) {
633 pool->buckets[i].free_list = ANV_FREE_LIST_EMPTY;
634 pool->buckets[i].block.next = 0;
635 pool->buckets[i].block.end = 0;
636 }
637 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
638
639 return VK_SUCCESS;
640 }
641
642 void
643 anv_state_pool_finish(struct anv_state_pool *pool)
644 {
645 VG(VALGRIND_DESTROY_MEMPOOL(pool));
646 anv_block_pool_finish(&pool->block_pool);
647 }
648
649 static uint32_t
650 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool *pool,
651 struct anv_block_pool *block_pool,
652 uint32_t state_size,
653 uint32_t block_size)
654 {
655 struct anv_block_state block, old, new;
656 uint32_t offset;
657
658 restart:
659 block.u64 = __sync_fetch_and_add(&pool->block.u64, state_size);
660
661 if (block.next < block.end) {
662 return block.next;
663 } else if (block.next == block.end) {
664 offset = anv_block_pool_alloc(block_pool, block_size);
665 new.next = offset + state_size;
666 new.end = offset + block_size;
667 old.u64 = __sync_lock_test_and_set(&pool->block.u64, new.u64);
668 if (old.next != block.next)
669 futex_wake(&pool->block.end, INT_MAX);
670 return offset;
671 } else {
672 futex_wait(&pool->block.end, block.end);
673 goto restart;
674 }
675 }
676
677 static struct anv_state
678 anv_state_pool_alloc_no_vg(struct anv_state_pool *pool,
679 uint32_t size, uint32_t align)
680 {
681 unsigned size_log2 = ilog2_round_up(size < align ? align : size);
682 assert(size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
683 if (size_log2 < ANV_MIN_STATE_SIZE_LOG2)
684 size_log2 = ANV_MIN_STATE_SIZE_LOG2;
685 unsigned bucket = size_log2 - ANV_MIN_STATE_SIZE_LOG2;
686
687 struct anv_state state;
688 state.alloc_size = 1 << size_log2;
689
690 /* Try free list first. */
691 if (anv_free_list_pop(&pool->buckets[bucket].free_list,
692 &pool->block_pool.map, &state.offset)) {
693 assert(state.offset >= 0);
694 goto done;
695 }
696
697 state.offset = anv_fixed_size_state_pool_alloc_new(&pool->buckets[bucket],
698 &pool->block_pool,
699 state.alloc_size,
700 pool->block_size);
701
702 done:
703 state.map = pool->block_pool.map + state.offset;
704 return state;
705 }
706
707 struct anv_state
708 anv_state_pool_alloc(struct anv_state_pool *pool, uint32_t size, uint32_t align)
709 {
710 if (size == 0)
711 return ANV_STATE_NULL;
712
713 struct anv_state state = anv_state_pool_alloc_no_vg(pool, size, align);
714 VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, size));
715 return state;
716 }
717
718 struct anv_state
719 anv_state_pool_alloc_back(struct anv_state_pool *pool)
720 {
721 struct anv_state state;
722 state.alloc_size = pool->block_size;
723
724 if (anv_free_list_pop(&pool->back_alloc_free_list,
725 &pool->block_pool.map, &state.offset)) {
726 assert(state.offset < 0);
727 goto done;
728 }
729
730 state.offset = anv_block_pool_alloc_back(&pool->block_pool,
731 pool->block_size);
732
733 done:
734 state.map = pool->block_pool.map + state.offset;
735 VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, state.alloc_size));
736 return state;
737 }
738
739 static void
740 anv_state_pool_free_no_vg(struct anv_state_pool *pool, struct anv_state state)
741 {
742 assert(util_is_power_of_two(state.alloc_size));
743 unsigned size_log2 = ilog2_round_up(state.alloc_size);
744 assert(size_log2 >= ANV_MIN_STATE_SIZE_LOG2 &&
745 size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
746 unsigned bucket = size_log2 - ANV_MIN_STATE_SIZE_LOG2;
747
748 if (state.offset < 0) {
749 assert(state.alloc_size == pool->block_size);
750 anv_free_list_push(&pool->back_alloc_free_list,
751 pool->block_pool.map, state.offset);
752 } else {
753 anv_free_list_push(&pool->buckets[bucket].free_list,
754 pool->block_pool.map, state.offset);
755 }
756 }
757
758 void
759 anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state)
760 {
761 if (state.alloc_size == 0)
762 return;
763
764 VG(VALGRIND_MEMPOOL_FREE(pool, state.map));
765 anv_state_pool_free_no_vg(pool, state);
766 }
767
768 struct anv_state_stream_block {
769 struct anv_state block;
770
771 /* The next block */
772 struct anv_state_stream_block *next;
773
774 #ifdef HAVE_VALGRIND
775 /* A pointer to the first user-allocated thing in this block. This is
776 * what valgrind sees as the start of the block.
777 */
778 void *_vg_ptr;
779 #endif
780 };
781
782 /* The state stream allocator is a one-shot, single threaded allocator for
783 * variable sized blocks. We use it for allocating dynamic state.
784 */
785 void
786 anv_state_stream_init(struct anv_state_stream *stream,
787 struct anv_state_pool *state_pool,
788 uint32_t block_size)
789 {
790 stream->state_pool = state_pool;
791 stream->block_size = block_size;
792
793 stream->block = ANV_STATE_NULL;
794
795 stream->block_list = NULL;
796
797 /* Ensure that next + whatever > block_size. This way the first call to
798 * state_stream_alloc fetches a new block.
799 */
800 stream->next = block_size;
801
802 VG(VALGRIND_CREATE_MEMPOOL(stream, 0, false));
803 }
804
805 void
806 anv_state_stream_finish(struct anv_state_stream *stream)
807 {
808 struct anv_state_stream_block *next = stream->block_list;
809 while (next != NULL) {
810 struct anv_state_stream_block sb = VG_NOACCESS_READ(next);
811 VG(VALGRIND_MEMPOOL_FREE(stream, sb._vg_ptr));
812 VG(VALGRIND_MAKE_MEM_UNDEFINED(next, stream->block_size));
813 anv_state_pool_free_no_vg(stream->state_pool, sb.block);
814 next = sb.next;
815 }
816
817 VG(VALGRIND_DESTROY_MEMPOOL(stream));
818 }
819
820 struct anv_state
821 anv_state_stream_alloc(struct anv_state_stream *stream,
822 uint32_t size, uint32_t alignment)
823 {
824 if (size == 0)
825 return ANV_STATE_NULL;
826
827 assert(alignment <= PAGE_SIZE);
828
829 uint32_t offset = align_u32(stream->next, alignment);
830 if (offset + size > stream->block_size) {
831 stream->block = anv_state_pool_alloc_no_vg(stream->state_pool,
832 stream->block_size,
833 PAGE_SIZE);
834
835 struct anv_state_stream_block *sb = stream->block.map;
836 VG_NOACCESS_WRITE(&sb->block, stream->block);
837 VG_NOACCESS_WRITE(&sb->next, stream->block_list);
838 stream->block_list = sb;
839 VG_NOACCESS_WRITE(&sb->_vg_ptr, NULL);
840
841 VG(VALGRIND_MAKE_MEM_NOACCESS(stream->block.map, stream->block_size));
842
843 /* Reset back to the start plus space for the header */
844 stream->next = sizeof(*sb);
845
846 offset = align_u32(stream->next, alignment);
847 assert(offset + size <= stream->block_size);
848 }
849
850 struct anv_state state = stream->block;
851 state.offset += offset;
852 state.alloc_size = size;
853 state.map += offset;
854
855 stream->next = offset + size;
856
857 #ifdef HAVE_VALGRIND
858 struct anv_state_stream_block *sb = stream->block_list;
859 void *vg_ptr = VG_NOACCESS_READ(&sb->_vg_ptr);
860 if (vg_ptr == NULL) {
861 vg_ptr = state.map;
862 VG_NOACCESS_WRITE(&sb->_vg_ptr, vg_ptr);
863 VALGRIND_MEMPOOL_ALLOC(stream, vg_ptr, size);
864 } else {
865 void *state_end = state.map + state.alloc_size;
866 /* This only updates the mempool. The newly allocated chunk is still
867 * marked as NOACCESS. */
868 VALGRIND_MEMPOOL_CHANGE(stream, vg_ptr, vg_ptr, state_end - vg_ptr);
869 /* Mark the newly allocated chunk as undefined */
870 VALGRIND_MAKE_MEM_UNDEFINED(state.map, state.alloc_size);
871 }
872 #endif
873
874 return state;
875 }
876
877 struct bo_pool_bo_link {
878 struct bo_pool_bo_link *next;
879 struct anv_bo bo;
880 };
881
882 void
883 anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device)
884 {
885 pool->device = device;
886 memset(pool->free_list, 0, sizeof(pool->free_list));
887
888 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
889 }
890
891 void
892 anv_bo_pool_finish(struct anv_bo_pool *pool)
893 {
894 for (unsigned i = 0; i < ARRAY_SIZE(pool->free_list); i++) {
895 struct bo_pool_bo_link *link = PFL_PTR(pool->free_list[i]);
896 while (link != NULL) {
897 struct bo_pool_bo_link link_copy = VG_NOACCESS_READ(link);
898
899 anv_gem_munmap(link_copy.bo.map, link_copy.bo.size);
900 anv_gem_close(pool->device, link_copy.bo.gem_handle);
901 link = link_copy.next;
902 }
903 }
904
905 VG(VALGRIND_DESTROY_MEMPOOL(pool));
906 }
907
908 VkResult
909 anv_bo_pool_alloc(struct anv_bo_pool *pool, struct anv_bo *bo, uint32_t size)
910 {
911 VkResult result;
912
913 const unsigned size_log2 = size < 4096 ? 12 : ilog2_round_up(size);
914 const unsigned pow2_size = 1 << size_log2;
915 const unsigned bucket = size_log2 - 12;
916 assert(bucket < ARRAY_SIZE(pool->free_list));
917
918 void *next_free_void;
919 if (anv_ptr_free_list_pop(&pool->free_list[bucket], &next_free_void)) {
920 struct bo_pool_bo_link *next_free = next_free_void;
921 *bo = VG_NOACCESS_READ(&next_free->bo);
922 assert(bo->gem_handle);
923 assert(bo->map == next_free);
924 assert(size <= bo->size);
925
926 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
927
928 return VK_SUCCESS;
929 }
930
931 struct anv_bo new_bo;
932
933 result = anv_bo_init_new(&new_bo, pool->device, pow2_size);
934 if (result != VK_SUCCESS)
935 return result;
936
937 assert(new_bo.size == pow2_size);
938
939 new_bo.map = anv_gem_mmap(pool->device, new_bo.gem_handle, 0, pow2_size, 0);
940 if (new_bo.map == MAP_FAILED) {
941 anv_gem_close(pool->device, new_bo.gem_handle);
942 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
943 }
944
945 *bo = new_bo;
946
947 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
948
949 return VK_SUCCESS;
950 }
951
952 void
953 anv_bo_pool_free(struct anv_bo_pool *pool, const struct anv_bo *bo_in)
954 {
955 /* Make a copy in case the anv_bo happens to be storred in the BO */
956 struct anv_bo bo = *bo_in;
957
958 VG(VALGRIND_MEMPOOL_FREE(pool, bo.map));
959
960 struct bo_pool_bo_link *link = bo.map;
961 VG_NOACCESS_WRITE(&link->bo, bo);
962
963 assert(util_is_power_of_two(bo.size));
964 const unsigned size_log2 = ilog2_round_up(bo.size);
965 const unsigned bucket = size_log2 - 12;
966 assert(bucket < ARRAY_SIZE(pool->free_list));
967
968 anv_ptr_free_list_push(&pool->free_list[bucket], link);
969 }
970
971 // Scratch pool
972
973 void
974 anv_scratch_pool_init(struct anv_device *device, struct anv_scratch_pool *pool)
975 {
976 memset(pool, 0, sizeof(*pool));
977 }
978
979 void
980 anv_scratch_pool_finish(struct anv_device *device, struct anv_scratch_pool *pool)
981 {
982 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
983 for (unsigned i = 0; i < 16; i++) {
984 struct anv_scratch_bo *bo = &pool->bos[i][s];
985 if (bo->exists > 0)
986 anv_gem_close(device, bo->bo.gem_handle);
987 }
988 }
989 }
990
991 struct anv_bo *
992 anv_scratch_pool_alloc(struct anv_device *device, struct anv_scratch_pool *pool,
993 gl_shader_stage stage, unsigned per_thread_scratch)
994 {
995 if (per_thread_scratch == 0)
996 return NULL;
997
998 unsigned scratch_size_log2 = ffs(per_thread_scratch / 2048);
999 assert(scratch_size_log2 < 16);
1000
1001 struct anv_scratch_bo *bo = &pool->bos[scratch_size_log2][stage];
1002
1003 /* We can use "exists" to shortcut and ignore the critical section */
1004 if (bo->exists)
1005 return &bo->bo;
1006
1007 pthread_mutex_lock(&device->mutex);
1008
1009 __sync_synchronize();
1010 if (bo->exists)
1011 return &bo->bo;
1012
1013 const struct anv_physical_device *physical_device =
1014 &device->instance->physicalDevice;
1015 const struct gen_device_info *devinfo = &physical_device->info;
1016
1017 /* WaCSScratchSize:hsw
1018 *
1019 * Haswell's scratch space address calculation appears to be sparse
1020 * rather than tightly packed. The Thread ID has bits indicating which
1021 * subslice, EU within a subslice, and thread within an EU it is.
1022 * There's a maximum of two slices and two subslices, so these can be
1023 * stored with a single bit. Even though there are only 10 EUs per
1024 * subslice, this is stored in 4 bits, so there's an effective maximum
1025 * value of 16 EUs. Similarly, although there are only 7 threads per EU,
1026 * this is stored in a 3 bit number, giving an effective maximum value
1027 * of 8 threads per EU.
1028 *
1029 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1030 * number of threads per subslice.
1031 */
1032 const unsigned subslices = MAX2(physical_device->subslice_total, 1);
1033 const unsigned scratch_ids_per_subslice =
1034 device->info.is_haswell ? 16 * 8 : devinfo->max_cs_threads;
1035
1036 uint32_t max_threads[] = {
1037 [MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
1038 [MESA_SHADER_TESS_CTRL] = devinfo->max_tcs_threads,
1039 [MESA_SHADER_TESS_EVAL] = devinfo->max_tes_threads,
1040 [MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
1041 [MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
1042 [MESA_SHADER_COMPUTE] = scratch_ids_per_subslice * subslices,
1043 };
1044
1045 uint32_t size = per_thread_scratch * max_threads[stage];
1046
1047 anv_bo_init_new(&bo->bo, device, size);
1048
1049 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1050 * are still relative to the general state base address. When we emit
1051 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1052 * to the maximum (1 page under 4GB). This allows us to just place the
1053 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1054 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1055 * However, in order to do so, we need to ensure that the kernel does not
1056 * place the scratch BO above the 32-bit boundary.
1057 *
1058 * NOTE: Technically, it can't go "anywhere" because the top page is off
1059 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1060 * kernel allocates space using
1061 *
1062 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1063 *
1064 * so nothing will ever touch the top page.
1065 */
1066 bo->bo.flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1067
1068 /* Set the exists last because it may be read by other threads */
1069 __sync_synchronize();
1070 bo->exists = true;
1071
1072 pthread_mutex_unlock(&device->mutex);
1073
1074 return &bo->bo;
1075 }
1076
1077 struct anv_cached_bo {
1078 struct anv_bo bo;
1079
1080 uint32_t refcount;
1081 };
1082
1083 VkResult
1084 anv_bo_cache_init(struct anv_bo_cache *cache)
1085 {
1086 cache->bo_map = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
1087 _mesa_key_pointer_equal);
1088 if (!cache->bo_map)
1089 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1090
1091 if (pthread_mutex_init(&cache->mutex, NULL)) {
1092 _mesa_hash_table_destroy(cache->bo_map, NULL);
1093 return vk_errorf(VK_ERROR_OUT_OF_HOST_MEMORY,
1094 "pthread_mutex_init failed: %m");
1095 }
1096
1097 return VK_SUCCESS;
1098 }
1099
1100 void
1101 anv_bo_cache_finish(struct anv_bo_cache *cache)
1102 {
1103 _mesa_hash_table_destroy(cache->bo_map, NULL);
1104 pthread_mutex_destroy(&cache->mutex);
1105 }
1106
1107 static struct anv_cached_bo *
1108 anv_bo_cache_lookup_locked(struct anv_bo_cache *cache, uint32_t gem_handle)
1109 {
1110 struct hash_entry *entry =
1111 _mesa_hash_table_search(cache->bo_map,
1112 (const void *)(uintptr_t)gem_handle);
1113 if (!entry)
1114 return NULL;
1115
1116 struct anv_cached_bo *bo = (struct anv_cached_bo *)entry->data;
1117 assert(bo->bo.gem_handle == gem_handle);
1118
1119 return bo;
1120 }
1121
1122 static struct anv_bo *
1123 anv_bo_cache_lookup(struct anv_bo_cache *cache, uint32_t gem_handle)
1124 {
1125 pthread_mutex_lock(&cache->mutex);
1126
1127 struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
1128
1129 pthread_mutex_unlock(&cache->mutex);
1130
1131 return bo ? &bo->bo : NULL;
1132 }
1133
1134 VkResult
1135 anv_bo_cache_alloc(struct anv_device *device,
1136 struct anv_bo_cache *cache,
1137 uint64_t size, struct anv_bo **bo_out)
1138 {
1139 struct anv_cached_bo *bo =
1140 vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
1141 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1142 if (!bo)
1143 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1144
1145 bo->refcount = 1;
1146
1147 /* The kernel is going to give us whole pages anyway */
1148 size = align_u64(size, 4096);
1149
1150 VkResult result = anv_bo_init_new(&bo->bo, device, size);
1151 if (result != VK_SUCCESS) {
1152 vk_free(&device->alloc, bo);
1153 return result;
1154 }
1155
1156 assert(bo->bo.gem_handle);
1157
1158 pthread_mutex_lock(&cache->mutex);
1159
1160 _mesa_hash_table_insert(cache->bo_map,
1161 (void *)(uintptr_t)bo->bo.gem_handle, bo);
1162
1163 pthread_mutex_unlock(&cache->mutex);
1164
1165 *bo_out = &bo->bo;
1166
1167 return VK_SUCCESS;
1168 }
1169
1170 VkResult
1171 anv_bo_cache_import(struct anv_device *device,
1172 struct anv_bo_cache *cache,
1173 int fd, uint64_t size, struct anv_bo **bo_out)
1174 {
1175 pthread_mutex_lock(&cache->mutex);
1176
1177 /* The kernel is going to give us whole pages anyway */
1178 size = align_u64(size, 4096);
1179
1180 uint32_t gem_handle = anv_gem_fd_to_handle(device, fd);
1181 if (!gem_handle) {
1182 pthread_mutex_unlock(&cache->mutex);
1183 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX);
1184 }
1185
1186 struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
1187 if (bo) {
1188 if (bo->bo.size != size) {
1189 pthread_mutex_unlock(&cache->mutex);
1190 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX);
1191 }
1192 __sync_fetch_and_add(&bo->refcount, 1);
1193 } else {
1194 /* For security purposes, we reject BO imports where the size does not
1195 * match exactly. This prevents a malicious client from passing a
1196 * buffer to a trusted client, lying about the size, and telling the
1197 * trusted client to try and texture from an image that goes
1198 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
1199 * in the trusted client. The trusted client can protect itself against
1200 * this sort of attack but only if it can trust the buffer size.
1201 */
1202 off_t import_size = lseek(fd, 0, SEEK_END);
1203 if (import_size == (off_t)-1 || import_size != size) {
1204 anv_gem_close(device, gem_handle);
1205 pthread_mutex_unlock(&cache->mutex);
1206 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX);
1207 }
1208
1209 bo = vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
1210 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1211 if (!bo) {
1212 anv_gem_close(device, gem_handle);
1213 pthread_mutex_unlock(&cache->mutex);
1214 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1215 }
1216
1217 bo->refcount = 1;
1218
1219 anv_bo_init(&bo->bo, gem_handle, size);
1220
1221 if (device->instance->physicalDevice.supports_48bit_addresses)
1222 bo->bo.flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1223
1224 if (device->instance->physicalDevice.has_exec_async)
1225 bo->bo.flags |= EXEC_OBJECT_ASYNC;
1226
1227 _mesa_hash_table_insert(cache->bo_map, (void *)(uintptr_t)gem_handle, bo);
1228 }
1229
1230 pthread_mutex_unlock(&cache->mutex);
1231
1232 /* From the Vulkan spec:
1233 *
1234 * "Importing memory from a file descriptor transfers ownership of
1235 * the file descriptor from the application to the Vulkan
1236 * implementation. The application must not perform any operations on
1237 * the file descriptor after a successful import."
1238 *
1239 * If the import fails, we leave the file descriptor open.
1240 */
1241 close(fd);
1242
1243 *bo_out = &bo->bo;
1244
1245 return VK_SUCCESS;
1246 }
1247
1248 VkResult
1249 anv_bo_cache_export(struct anv_device *device,
1250 struct anv_bo_cache *cache,
1251 struct anv_bo *bo_in, int *fd_out)
1252 {
1253 assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
1254 struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
1255
1256 int fd = anv_gem_handle_to_fd(device, bo->bo.gem_handle);
1257 if (fd < 0)
1258 return vk_error(VK_ERROR_TOO_MANY_OBJECTS);
1259
1260 *fd_out = fd;
1261
1262 return VK_SUCCESS;
1263 }
1264
1265 static bool
1266 atomic_dec_not_one(uint32_t *counter)
1267 {
1268 uint32_t old, val;
1269
1270 val = *counter;
1271 while (1) {
1272 if (val == 1)
1273 return false;
1274
1275 old = __sync_val_compare_and_swap(counter, val, val - 1);
1276 if (old == val)
1277 return true;
1278
1279 val = old;
1280 }
1281 }
1282
1283 void
1284 anv_bo_cache_release(struct anv_device *device,
1285 struct anv_bo_cache *cache,
1286 struct anv_bo *bo_in)
1287 {
1288 assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
1289 struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
1290
1291 /* Try to decrement the counter but don't go below one. If this succeeds
1292 * then the refcount has been decremented and we are not the last
1293 * reference.
1294 */
1295 if (atomic_dec_not_one(&bo->refcount))
1296 return;
1297
1298 pthread_mutex_lock(&cache->mutex);
1299
1300 /* We are probably the last reference since our attempt to decrement above
1301 * failed. However, we can't actually know until we are inside the mutex.
1302 * Otherwise, someone could import the BO between the decrement and our
1303 * taking the mutex.
1304 */
1305 if (unlikely(__sync_sub_and_fetch(&bo->refcount, 1) > 0)) {
1306 /* Turns out we're not the last reference. Unlock and bail. */
1307 pthread_mutex_unlock(&cache->mutex);
1308 return;
1309 }
1310
1311 struct hash_entry *entry =
1312 _mesa_hash_table_search(cache->bo_map,
1313 (const void *)(uintptr_t)bo->bo.gem_handle);
1314 assert(entry);
1315 _mesa_hash_table_remove(cache->bo_map, entry);
1316
1317 if (bo->bo.map)
1318 anv_gem_munmap(bo->bo.map, bo->bo.size);
1319
1320 anv_gem_close(device, bo->bo.gem_handle);
1321
1322 /* Don't unlock until we've actually closed the BO. The whole point of
1323 * the BO cache is to ensure that we correctly handle races with creating
1324 * and releasing GEM handles and we don't want to let someone import the BO
1325 * again between mutex unlock and closing the GEM handle.
1326 */
1327 pthread_mutex_unlock(&cache->mutex);
1328
1329 vk_free(&device->alloc, bo);
1330 }