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