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