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