2 * Copyright © 2015 Intel Corporation
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:
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
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
30 #include "anv_private.h"
32 #include "util/simple_mtx.h"
33 #include "util/anon_file.h"
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)));\
42 #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
43 VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
45 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
48 #define VG_NOACCESS_READ(__ptr) (*(__ptr))
49 #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
53 #define MAP_POPULATE 0
58 * - Lock free (except when resizing underlying bos)
60 * - Constant time allocation with typically only one atomic
62 * - Multiple allocation sizes without fragmentation
64 * - Can grow while keeping addresses and offset of contents stable
66 * - All allocations within one bo so we can point one of the
67 * STATE_BASE_ADDRESS pointers at it.
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.
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.
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
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
107 #define PAGE_SIZE 4096
109 struct anv_mmap_cleanup
{
115 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
117 static inline uint32_t
118 ilog2_round_up(uint32_t value
)
121 return 32 - __builtin_clz(value
- 1);
124 static inline uint32_t
125 round_to_power_of_two(uint32_t value
)
127 return 1 << ilog2_round_up(value
);
130 struct anv_state_table_cleanup
{
135 #define ANV_STATE_TABLE_CLEANUP_INIT ((struct anv_state_table_cleanup){0})
136 #define ANV_STATE_ENTRY_SIZE (sizeof(struct anv_free_entry))
139 anv_state_table_expand_range(struct anv_state_table
*table
, uint32_t size
);
142 anv_state_table_init(struct anv_state_table
*table
,
143 struct anv_device
*device
,
144 uint32_t initial_entries
)
148 table
->device
= device
;
150 /* Just make it 2GB up-front. The Linux kernel won't actually back it
151 * with pages until we either map and fault on one of them or we use
152 * userptr and send a chunk of it off to the GPU.
154 table
->fd
= os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE
, "state table");
155 if (table
->fd
== -1) {
156 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
160 if (!u_vector_init(&table
->cleanups
,
161 round_to_power_of_two(sizeof(struct anv_state_table_cleanup
)),
163 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
167 table
->state
.next
= 0;
168 table
->state
.end
= 0;
171 uint32_t initial_size
= initial_entries
* ANV_STATE_ENTRY_SIZE
;
172 result
= anv_state_table_expand_range(table
, initial_size
);
173 if (result
!= VK_SUCCESS
)
179 u_vector_finish(&table
->cleanups
);
187 anv_state_table_expand_range(struct anv_state_table
*table
, uint32_t size
)
190 struct anv_state_table_cleanup
*cleanup
;
192 /* Assert that we only ever grow the pool */
193 assert(size
>= table
->state
.end
);
195 /* Make sure that we don't go outside the bounds of the memfd */
196 if (size
> BLOCK_POOL_MEMFD_SIZE
)
197 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
199 cleanup
= u_vector_add(&table
->cleanups
);
201 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
203 *cleanup
= ANV_STATE_TABLE_CLEANUP_INIT
;
205 /* Just leak the old map until we destroy the pool. We can't munmap it
206 * without races or imposing locking on the block allocate fast path. On
207 * the whole the leaked maps adds up to less than the size of the
208 * current map. MAP_POPULATE seems like the right thing to do, but we
209 * should try to get some numbers.
211 map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
212 MAP_SHARED
| MAP_POPULATE
, table
->fd
, 0);
213 if (map
== MAP_FAILED
) {
214 return vk_errorf(table
->device
->instance
, table
->device
,
215 VK_ERROR_OUT_OF_HOST_MEMORY
, "mmap failed: %m");
219 cleanup
->size
= size
;
228 anv_state_table_grow(struct anv_state_table
*table
)
230 VkResult result
= VK_SUCCESS
;
232 uint32_t used
= align_u32(table
->state
.next
* ANV_STATE_ENTRY_SIZE
,
234 uint32_t old_size
= table
->size
;
236 /* The block pool is always initialized to a nonzero size and this function
237 * is always called after initialization.
239 assert(old_size
> 0);
241 uint32_t required
= MAX2(used
, old_size
);
242 if (used
* 2 <= required
) {
243 /* If we're in this case then this isn't the firsta allocation and we
244 * already have enough space on both sides to hold double what we
245 * have allocated. There's nothing for us to do.
250 uint32_t size
= old_size
* 2;
251 while (size
< required
)
254 assert(size
> table
->size
);
256 result
= anv_state_table_expand_range(table
, size
);
263 anv_state_table_finish(struct anv_state_table
*table
)
265 struct anv_state_table_cleanup
*cleanup
;
267 u_vector_foreach(cleanup
, &table
->cleanups
) {
269 munmap(cleanup
->map
, cleanup
->size
);
272 u_vector_finish(&table
->cleanups
);
278 anv_state_table_add(struct anv_state_table
*table
, uint32_t *idx
,
281 struct anv_block_state state
, old
, new;
287 state
.u64
= __sync_fetch_and_add(&table
->state
.u64
, count
);
288 if (state
.next
+ count
<= state
.end
) {
290 struct anv_free_entry
*entry
= &table
->map
[state
.next
];
291 for (int i
= 0; i
< count
; i
++) {
292 entry
[i
].state
.idx
= state
.next
+ i
;
296 } else if (state
.next
<= state
.end
) {
297 /* We allocated the first block outside the pool so we have to grow
298 * the pool. pool_state->next acts a mutex: threads who try to
299 * allocate now will get block indexes above the current limit and
300 * hit futex_wait below.
302 new.next
= state
.next
+ count
;
304 result
= anv_state_table_grow(table
);
305 if (result
!= VK_SUCCESS
)
307 new.end
= table
->size
/ ANV_STATE_ENTRY_SIZE
;
308 } while (new.end
< new.next
);
310 old
.u64
= __sync_lock_test_and_set(&table
->state
.u64
, new.u64
);
311 if (old
.next
!= state
.next
)
312 futex_wake(&table
->state
.end
, INT_MAX
);
314 futex_wait(&table
->state
.end
, state
.end
, NULL
);
321 anv_free_list_push(union anv_free_list
*list
,
322 struct anv_state_table
*table
,
323 uint32_t first
, uint32_t count
)
325 union anv_free_list current
, old
, new;
326 uint32_t last
= first
;
328 for (uint32_t i
= 1; i
< count
; i
++, last
++)
329 table
->map
[last
].next
= last
+ 1;
334 table
->map
[last
].next
= current
.offset
;
336 new.count
= current
.count
+ 1;
337 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
338 } while (old
.u64
!= current
.u64
);
342 anv_free_list_pop(union anv_free_list
*list
,
343 struct anv_state_table
*table
)
345 union anv_free_list current
, new, old
;
347 current
.u64
= list
->u64
;
348 while (current
.offset
!= EMPTY
) {
349 __sync_synchronize();
350 new.offset
= table
->map
[current
.offset
].next
;
351 new.count
= current
.count
+ 1;
352 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
353 if (old
.u64
== current
.u64
) {
354 struct anv_free_entry
*entry
= &table
->map
[current
.offset
];
355 return &entry
->state
;
363 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
364 * means that the bottom 12 bits should all be zero.
366 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
367 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
368 #define PFL_PACK(ptr, count) ({ \
369 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
373 anv_ptr_free_list_pop(void **list
, void **elem
)
375 void *current
= *list
;
376 while (PFL_PTR(current
) != NULL
) {
377 void **next_ptr
= PFL_PTR(current
);
378 void *new_ptr
= VG_NOACCESS_READ(next_ptr
);
379 unsigned new_count
= PFL_COUNT(current
) + 1;
380 void *new = PFL_PACK(new_ptr
, new_count
);
381 void *old
= __sync_val_compare_and_swap(list
, current
, new);
382 if (old
== current
) {
383 *elem
= PFL_PTR(current
);
393 anv_ptr_free_list_push(void **list
, void *elem
)
396 void **next_ptr
= elem
;
398 /* The pointer-based free list requires that the pointer be
399 * page-aligned. This is because we use the bottom 12 bits of the
400 * pointer to store a counter to solve the ABA concurrency problem.
402 assert(((uintptr_t)elem
& 0xfff) == 0);
407 VG_NOACCESS_WRITE(next_ptr
, PFL_PTR(current
));
408 unsigned new_count
= PFL_COUNT(current
) + 1;
409 void *new = PFL_PACK(elem
, new_count
);
410 old
= __sync_val_compare_and_swap(list
, current
, new);
411 } while (old
!= current
);
415 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
416 uint32_t center_bo_offset
, uint32_t size
);
419 anv_block_pool_init(struct anv_block_pool
*pool
,
420 struct anv_device
*device
,
421 uint64_t start_address
,
422 uint32_t initial_size
,
427 pool
->device
= device
;
428 pool
->bo_flags
= bo_flags
;
431 pool
->center_bo_offset
= 0;
432 pool
->start_address
= gen_canonical_address(start_address
);
435 if (!(pool
->bo_flags
& EXEC_OBJECT_PINNED
)) {
436 /* Just make it 2GB up-front. The Linux kernel won't actually back it
437 * with pages until we either map and fault on one of them or we use
438 * userptr and send a chunk of it off to the GPU.
440 pool
->fd
= os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE
, "block pool");
442 return vk_error(VK_ERROR_INITIALIZATION_FAILED
);
444 anv_bo_init(&pool
->wrapper_bo
, 0, 0);
445 pool
->wrapper_bo
.is_wrapper
= true;
446 pool
->bo
= &pool
->wrapper_bo
;
448 /* This pointer will always point to the first BO in the list */
449 anv_bo_init(&pool
->bos
[0], 0, 0);
450 pool
->bo
= &pool
->bos
[0];
455 if (!u_vector_init(&pool
->mmap_cleanups
,
456 round_to_power_of_two(sizeof(struct anv_mmap_cleanup
)),
458 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
462 pool
->state
.next
= 0;
464 pool
->back_state
.next
= 0;
465 pool
->back_state
.end
= 0;
467 result
= anv_block_pool_expand_range(pool
, 0, initial_size
);
468 if (result
!= VK_SUCCESS
)
469 goto fail_mmap_cleanups
;
471 /* Make the entire pool available in the front of the pool. If back
472 * allocation needs to use this space, the "ends" will be re-arranged.
474 pool
->state
.end
= pool
->size
;
479 u_vector_finish(&pool
->mmap_cleanups
);
481 if (!(pool
->bo_flags
& EXEC_OBJECT_PINNED
))
488 anv_block_pool_finish(struct anv_block_pool
*pool
)
490 struct anv_mmap_cleanup
*cleanup
;
491 const bool use_softpin
= !!(pool
->bo_flags
& EXEC_OBJECT_PINNED
);
493 u_vector_foreach(cleanup
, &pool
->mmap_cleanups
) {
495 anv_gem_munmap(cleanup
->map
, cleanup
->size
);
497 munmap(cleanup
->map
, cleanup
->size
);
499 if (cleanup
->gem_handle
)
500 anv_gem_close(pool
->device
, cleanup
->gem_handle
);
503 u_vector_finish(&pool
->mmap_cleanups
);
504 if (!(pool
->bo_flags
& EXEC_OBJECT_PINNED
))
509 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
510 uint32_t center_bo_offset
, uint32_t size
)
514 struct anv_mmap_cleanup
*cleanup
;
515 const bool use_softpin
= !!(pool
->bo_flags
& EXEC_OBJECT_PINNED
);
517 /* Assert that we only ever grow the pool */
518 assert(center_bo_offset
>= pool
->back_state
.end
);
519 assert(size
- center_bo_offset
>= pool
->state
.end
);
521 /* Assert that we don't go outside the bounds of the memfd */
522 assert(center_bo_offset
<= BLOCK_POOL_MEMFD_CENTER
);
523 assert(use_softpin
||
524 size
- center_bo_offset
<=
525 BLOCK_POOL_MEMFD_SIZE
- BLOCK_POOL_MEMFD_CENTER
);
527 cleanup
= u_vector_add(&pool
->mmap_cleanups
);
529 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
531 *cleanup
= ANV_MMAP_CLEANUP_INIT
;
533 uint32_t newbo_size
= size
- pool
->size
;
535 gem_handle
= anv_gem_create(pool
->device
, newbo_size
);
536 map
= anv_gem_mmap(pool
->device
, gem_handle
, 0, newbo_size
, 0);
537 if (map
== MAP_FAILED
)
538 return vk_errorf(pool
->device
->instance
, pool
->device
,
539 VK_ERROR_MEMORY_MAP_FAILED
, "gem mmap failed: %m");
540 assert(center_bo_offset
== 0);
542 /* Just leak the old map until we destroy the pool. We can't munmap it
543 * without races or imposing locking on the block allocate fast path. On
544 * the whole the leaked maps adds up to less than the size of the
545 * current map. MAP_POPULATE seems like the right thing to do, but we
546 * should try to get some numbers.
548 map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
549 MAP_SHARED
| MAP_POPULATE
, pool
->fd
,
550 BLOCK_POOL_MEMFD_CENTER
- center_bo_offset
);
551 if (map
== MAP_FAILED
)
552 return vk_errorf(pool
->device
->instance
, pool
->device
,
553 VK_ERROR_MEMORY_MAP_FAILED
, "mmap failed: %m");
555 /* Now that we mapped the new memory, we can write the new
556 * center_bo_offset back into pool and update pool->map. */
557 pool
->center_bo_offset
= center_bo_offset
;
558 pool
->map
= map
+ center_bo_offset
;
559 gem_handle
= anv_gem_userptr(pool
->device
, map
, size
);
560 if (gem_handle
== 0) {
562 return vk_errorf(pool
->device
->instance
, pool
->device
,
563 VK_ERROR_TOO_MANY_OBJECTS
, "userptr failed: %m");
568 cleanup
->size
= use_softpin
? newbo_size
: size
;
569 cleanup
->gem_handle
= gem_handle
;
571 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
572 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
573 * always created as I915_CACHING_CACHED, which on non-LLC means
576 * On platforms that support softpin, we are not going to use userptr
577 * anymore, but we still want to rely on the snooped states. So make sure
578 * everything is set to I915_CACHING_CACHED.
580 if (!pool
->device
->info
.has_llc
)
581 anv_gem_set_caching(pool
->device
, gem_handle
, I915_CACHING_CACHED
);
583 /* For block pool BOs we have to be a bit careful about where we place them
584 * in the GTT. There are two documented workarounds for state base address
585 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
586 * which state that those two base addresses do not support 48-bit
587 * addresses and need to be placed in the bottom 32-bit range.
588 * Unfortunately, this is not quite accurate.
590 * The real problem is that we always set the size of our state pools in
591 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
592 * likely significantly smaller. We do this because we do not no at the
593 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
594 * the pool during command buffer building so we don't actually have a
595 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
596 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
597 * as being out of bounds and returns zero. For dynamic state, this
598 * usually just leads to rendering corruptions, but shaders that are all
599 * zero hang the GPU immediately.
601 * The easiest solution to do is exactly what the bogus workarounds say to
602 * do: restrict these buffers to 32-bit addresses. We could also pin the
603 * BO to some particular location of our choosing, but that's significantly
604 * more work than just not setting a flag. So, we explicitly DO NOT set
605 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
612 assert(pool
->nbos
< ANV_MAX_BLOCK_POOL_BOS
);
615 /* With softpin, we add a new BO to the pool, and set its offset to right
616 * where the previous BO ends (the end of the pool).
618 bo
= &pool
->bos
[pool
->nbos
++];
619 bo_size
= newbo_size
;
620 bo_offset
= pool
->start_address
+ pool
->size
;
622 /* Without softpin, we just need one BO, and we already have a pointer to
623 * it. Simply "allocate" it from our array if we didn't do it before.
624 * The offset doesn't matter since we are not pinning the BO anyway.
626 if (pool
->nbos
== 0) {
627 pool
->wrapper_bo
.map
= &pool
->bos
[0];
630 bo
= pool
->wrapper_bo
.map
;
635 anv_bo_init(bo
, gem_handle
, bo_size
);
636 bo
->offset
= bo_offset
;
637 bo
->flags
= pool
->bo_flags
;
644 /** Returns current memory map of the block pool.
646 * The returned pointer points to the map for the memory at the specified
647 * offset. The offset parameter is relative to the "center" of the block pool
648 * rather than the start of the block pool BO map.
651 anv_block_pool_map(struct anv_block_pool
*pool
, int32_t offset
)
653 if (pool
->bo_flags
& EXEC_OBJECT_PINNED
) {
654 struct anv_bo
*bo
= NULL
;
655 int32_t bo_offset
= 0;
656 anv_block_pool_foreach_bo(iter_bo
, pool
) {
657 if (offset
< bo_offset
+ iter_bo
->size
) {
661 bo_offset
+= iter_bo
->size
;
664 assert(offset
>= bo_offset
);
666 return bo
->map
+ (offset
- bo_offset
);
668 return pool
->map
+ offset
;
672 /** Grows and re-centers the block pool.
674 * We grow the block pool in one or both directions in such a way that the
675 * following conditions are met:
677 * 1) The size of the entire pool is always a power of two.
679 * 2) The pool only grows on both ends. Neither end can get
682 * 3) At the end of the allocation, we have about twice as much space
683 * allocated for each end as we have used. This way the pool doesn't
684 * grow too far in one direction or the other.
686 * 4) If the _alloc_back() has never been called, then the back portion of
687 * the pool retains a size of zero. (This makes it easier for users of
688 * the block pool that only want a one-sided pool.)
690 * 5) We have enough space allocated for at least one more block in
691 * whichever side `state` points to.
693 * 6) The center of the pool is always aligned to both the block_size of
694 * the pool and a 4K CPU page.
697 anv_block_pool_grow(struct anv_block_pool
*pool
, struct anv_block_state
*state
)
699 VkResult result
= VK_SUCCESS
;
701 pthread_mutex_lock(&pool
->device
->mutex
);
703 assert(state
== &pool
->state
|| state
== &pool
->back_state
);
705 /* Gather a little usage information on the pool. Since we may have
706 * threadsd waiting in queue to get some storage while we resize, it's
707 * actually possible that total_used will be larger than old_size. In
708 * particular, block_pool_alloc() increments state->next prior to
709 * calling block_pool_grow, so this ensures that we get enough space for
710 * which ever side tries to grow the pool.
712 * We align to a page size because it makes it easier to do our
713 * calculations later in such a way that we state page-aigned.
715 uint32_t back_used
= align_u32(pool
->back_state
.next
, PAGE_SIZE
);
716 uint32_t front_used
= align_u32(pool
->state
.next
, PAGE_SIZE
);
717 uint32_t total_used
= front_used
+ back_used
;
719 assert(state
== &pool
->state
|| back_used
> 0);
721 uint32_t old_size
= pool
->size
;
723 /* The block pool is always initialized to a nonzero size and this function
724 * is always called after initialization.
726 assert(old_size
> 0);
728 /* The back_used and front_used may actually be smaller than the actual
729 * requirement because they are based on the next pointers which are
730 * updated prior to calling this function.
732 uint32_t back_required
= MAX2(back_used
, pool
->center_bo_offset
);
733 uint32_t front_required
= MAX2(front_used
, old_size
- pool
->center_bo_offset
);
735 if (back_used
* 2 <= back_required
&& front_used
* 2 <= front_required
) {
736 /* If we're in this case then this isn't the firsta allocation and we
737 * already have enough space on both sides to hold double what we
738 * have allocated. There's nothing for us to do.
743 uint32_t size
= old_size
* 2;
744 while (size
< back_required
+ front_required
)
747 assert(size
> pool
->size
);
749 /* We compute a new center_bo_offset such that, when we double the size
750 * of the pool, we maintain the ratio of how much is used by each side.
751 * This way things should remain more-or-less balanced.
753 uint32_t center_bo_offset
;
754 if (back_used
== 0) {
755 /* If we're in this case then we have never called alloc_back(). In
756 * this case, we want keep the offset at 0 to make things as simple
757 * as possible for users that don't care about back allocations.
759 center_bo_offset
= 0;
761 /* Try to "center" the allocation based on how much is currently in
762 * use on each side of the center line.
764 center_bo_offset
= ((uint64_t)size
* back_used
) / total_used
;
766 /* Align down to a multiple of the page size */
767 center_bo_offset
&= ~(PAGE_SIZE
- 1);
769 assert(center_bo_offset
>= back_used
);
771 /* Make sure we don't shrink the back end of the pool */
772 if (center_bo_offset
< back_required
)
773 center_bo_offset
= back_required
;
775 /* Make sure that we don't shrink the front end of the pool */
776 if (size
- center_bo_offset
< front_required
)
777 center_bo_offset
= size
- front_required
;
780 assert(center_bo_offset
% PAGE_SIZE
== 0);
782 result
= anv_block_pool_expand_range(pool
, center_bo_offset
, size
);
785 pthread_mutex_unlock(&pool
->device
->mutex
);
787 if (result
== VK_SUCCESS
) {
788 /* Return the appropriate new size. This function never actually
789 * updates state->next. Instead, we let the caller do that because it
790 * needs to do so in order to maintain its concurrency model.
792 if (state
== &pool
->state
) {
793 return pool
->size
- pool
->center_bo_offset
;
795 assert(pool
->center_bo_offset
> 0);
796 return pool
->center_bo_offset
;
804 anv_block_pool_alloc_new(struct anv_block_pool
*pool
,
805 struct anv_block_state
*pool_state
,
806 uint32_t block_size
, uint32_t *padding
)
808 struct anv_block_state state
, old
, new;
810 /* Most allocations won't generate any padding */
815 state
.u64
= __sync_fetch_and_add(&pool_state
->u64
, block_size
);
816 if (state
.next
+ block_size
<= state
.end
) {
818 } else if (state
.next
<= state
.end
) {
819 if (pool
->bo_flags
& EXEC_OBJECT_PINNED
&& state
.next
< state
.end
) {
820 /* We need to grow the block pool, but still have some leftover
821 * space that can't be used by that particular allocation. So we
822 * add that as a "padding", and return it.
824 uint32_t leftover
= state
.end
- state
.next
;
826 /* If there is some leftover space in the pool, the caller must
829 assert(leftover
== 0 || padding
);
832 state
.next
+= leftover
;
835 /* We allocated the first block outside the pool so we have to grow
836 * the pool. pool_state->next acts a mutex: threads who try to
837 * allocate now will get block indexes above the current limit and
838 * hit futex_wait below.
840 new.next
= state
.next
+ block_size
;
842 new.end
= anv_block_pool_grow(pool
, pool_state
);
843 } while (new.end
< new.next
);
845 old
.u64
= __sync_lock_test_and_set(&pool_state
->u64
, new.u64
);
846 if (old
.next
!= state
.next
)
847 futex_wake(&pool_state
->end
, INT_MAX
);
850 futex_wait(&pool_state
->end
, state
.end
, NULL
);
857 anv_block_pool_alloc(struct anv_block_pool
*pool
,
858 uint32_t block_size
, uint32_t *padding
)
862 offset
= anv_block_pool_alloc_new(pool
, &pool
->state
, block_size
, padding
);
867 /* Allocates a block out of the back of the block pool.
869 * This will allocated a block earlier than the "start" of the block pool.
870 * The offsets returned from this function will be negative but will still
871 * be correct relative to the block pool's map pointer.
873 * If you ever use anv_block_pool_alloc_back, then you will have to do
874 * gymnastics with the block pool's BO when doing relocations.
877 anv_block_pool_alloc_back(struct anv_block_pool
*pool
,
880 int32_t offset
= anv_block_pool_alloc_new(pool
, &pool
->back_state
,
883 /* The offset we get out of anv_block_pool_alloc_new() is actually the
884 * number of bytes downwards from the middle to the end of the block.
885 * We need to turn it into a (negative) offset from the middle to the
886 * start of the block.
889 return -(offset
+ block_size
);
893 anv_state_pool_init(struct anv_state_pool
*pool
,
894 struct anv_device
*device
,
895 uint64_t start_address
,
899 VkResult result
= anv_block_pool_init(&pool
->block_pool
, device
,
903 if (result
!= VK_SUCCESS
)
906 result
= anv_state_table_init(&pool
->table
, device
, 64);
907 if (result
!= VK_SUCCESS
) {
908 anv_block_pool_finish(&pool
->block_pool
);
912 assert(util_is_power_of_two_or_zero(block_size
));
913 pool
->block_size
= block_size
;
914 pool
->back_alloc_free_list
= ANV_FREE_LIST_EMPTY
;
915 for (unsigned i
= 0; i
< ANV_STATE_BUCKETS
; i
++) {
916 pool
->buckets
[i
].free_list
= ANV_FREE_LIST_EMPTY
;
917 pool
->buckets
[i
].block
.next
= 0;
918 pool
->buckets
[i
].block
.end
= 0;
920 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
926 anv_state_pool_finish(struct anv_state_pool
*pool
)
928 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
929 anv_state_table_finish(&pool
->table
);
930 anv_block_pool_finish(&pool
->block_pool
);
934 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool
*pool
,
935 struct anv_block_pool
*block_pool
,
940 struct anv_block_state block
, old
, new;
943 /* We don't always use anv_block_pool_alloc(), which would set *padding to
944 * zero for us. So if we have a pointer to padding, we must zero it out
945 * ourselves here, to make sure we always return some sensible value.
950 /* If our state is large, we don't need any sub-allocation from a block.
951 * Instead, we just grab whole (potentially large) blocks.
953 if (state_size
>= block_size
)
954 return anv_block_pool_alloc(block_pool
, state_size
, padding
);
957 block
.u64
= __sync_fetch_and_add(&pool
->block
.u64
, state_size
);
959 if (block
.next
< block
.end
) {
961 } else if (block
.next
== block
.end
) {
962 offset
= anv_block_pool_alloc(block_pool
, block_size
, padding
);
963 new.next
= offset
+ state_size
;
964 new.end
= offset
+ block_size
;
965 old
.u64
= __sync_lock_test_and_set(&pool
->block
.u64
, new.u64
);
966 if (old
.next
!= block
.next
)
967 futex_wake(&pool
->block
.end
, INT_MAX
);
970 futex_wait(&pool
->block
.end
, block
.end
, NULL
);
976 anv_state_pool_get_bucket(uint32_t size
)
978 unsigned size_log2
= ilog2_round_up(size
);
979 assert(size_log2
<= ANV_MAX_STATE_SIZE_LOG2
);
980 if (size_log2
< ANV_MIN_STATE_SIZE_LOG2
)
981 size_log2
= ANV_MIN_STATE_SIZE_LOG2
;
982 return size_log2
- ANV_MIN_STATE_SIZE_LOG2
;
986 anv_state_pool_get_bucket_size(uint32_t bucket
)
988 uint32_t size_log2
= bucket
+ ANV_MIN_STATE_SIZE_LOG2
;
989 return 1 << size_log2
;
992 /** Helper to push a chunk into the state table.
994 * It creates 'count' entries into the state table and update their sizes,
995 * offsets and maps, also pushing them as "free" states.
998 anv_state_pool_return_blocks(struct anv_state_pool
*pool
,
999 uint32_t chunk_offset
, uint32_t count
,
1000 uint32_t block_size
)
1002 /* Disallow returning 0 chunks */
1005 /* Make sure we always return chunks aligned to the block_size */
1006 assert(chunk_offset
% block_size
== 0);
1009 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &st_idx
, count
);
1010 assert(result
== VK_SUCCESS
);
1011 for (int i
= 0; i
< count
; i
++) {
1012 /* update states that were added back to the state table */
1013 struct anv_state
*state_i
= anv_state_table_get(&pool
->table
,
1015 state_i
->alloc_size
= block_size
;
1016 state_i
->offset
= chunk_offset
+ block_size
* i
;
1017 state_i
->map
= anv_block_pool_map(&pool
->block_pool
, state_i
->offset
);
1020 uint32_t block_bucket
= anv_state_pool_get_bucket(block_size
);
1021 anv_free_list_push(&pool
->buckets
[block_bucket
].free_list
,
1022 &pool
->table
, st_idx
, count
);
1025 /** Returns a chunk of memory back to the state pool.
1027 * Do a two-level split. If chunk_size is bigger than divisor
1028 * (pool->block_size), we return as many divisor sized blocks as we can, from
1029 * the end of the chunk.
1031 * The remaining is then split into smaller blocks (starting at small_size if
1032 * it is non-zero), with larger blocks always being taken from the end of the
1036 anv_state_pool_return_chunk(struct anv_state_pool
*pool
,
1037 uint32_t chunk_offset
, uint32_t chunk_size
,
1038 uint32_t small_size
)
1040 uint32_t divisor
= pool
->block_size
;
1041 uint32_t nblocks
= chunk_size
/ divisor
;
1042 uint32_t rest
= chunk_size
- nblocks
* divisor
;
1045 /* First return divisor aligned and sized chunks. We start returning
1046 * larger blocks from the end fo the chunk, since they should already be
1047 * aligned to divisor. Also anv_state_pool_return_blocks() only accepts
1050 uint32_t offset
= chunk_offset
+ rest
;
1051 anv_state_pool_return_blocks(pool
, offset
, nblocks
, divisor
);
1057 if (small_size
> 0 && small_size
< divisor
)
1058 divisor
= small_size
;
1060 uint32_t min_size
= 1 << ANV_MIN_STATE_SIZE_LOG2
;
1062 /* Just as before, return larger divisor aligned blocks from the end of the
1065 while (chunk_size
> 0 && divisor
>= min_size
) {
1066 nblocks
= chunk_size
/ divisor
;
1067 rest
= chunk_size
- nblocks
* divisor
;
1069 anv_state_pool_return_blocks(pool
, chunk_offset
+ rest
,
1077 static struct anv_state
1078 anv_state_pool_alloc_no_vg(struct anv_state_pool
*pool
,
1079 uint32_t size
, uint32_t align
)
1081 uint32_t bucket
= anv_state_pool_get_bucket(MAX2(size
, align
));
1083 struct anv_state
*state
;
1084 uint32_t alloc_size
= anv_state_pool_get_bucket_size(bucket
);
1087 /* Try free list first. */
1088 state
= anv_free_list_pop(&pool
->buckets
[bucket
].free_list
,
1091 assert(state
->offset
>= 0);
1095 /* Try to grab a chunk from some larger bucket and split it up */
1096 for (unsigned b
= bucket
+ 1; b
< ANV_STATE_BUCKETS
; b
++) {
1097 state
= anv_free_list_pop(&pool
->buckets
[b
].free_list
, &pool
->table
);
1099 unsigned chunk_size
= anv_state_pool_get_bucket_size(b
);
1100 int32_t chunk_offset
= state
->offset
;
1102 /* First lets update the state we got to its new size. offset and map
1105 state
->alloc_size
= alloc_size
;
1107 /* Now return the unused part of the chunk back to the pool as free
1110 * There are a couple of options as to what we do with it:
1112 * 1) We could fully split the chunk into state.alloc_size sized
1113 * pieces. However, this would mean that allocating a 16B
1114 * state could potentially split a 2MB chunk into 512K smaller
1115 * chunks. This would lead to unnecessary fragmentation.
1117 * 2) The classic "buddy allocator" method would have us split the
1118 * chunk in half and return one half. Then we would split the
1119 * remaining half in half and return one half, and repeat as
1120 * needed until we get down to the size we want. However, if
1121 * you are allocating a bunch of the same size state (which is
1122 * the common case), this means that every other allocation has
1123 * to go up a level and every fourth goes up two levels, etc.
1124 * This is not nearly as efficient as it could be if we did a
1125 * little more work up-front.
1127 * 3) Split the difference between (1) and (2) by doing a
1128 * two-level split. If it's bigger than some fixed block_size,
1129 * we split it into block_size sized chunks and return all but
1130 * one of them. Then we split what remains into
1131 * state.alloc_size sized chunks and return them.
1133 * We choose something close to option (3), which is implemented with
1134 * anv_state_pool_return_chunk(). That is done by returning the
1135 * remaining of the chunk, with alloc_size as a hint of the size that
1136 * we want the smaller chunk split into.
1138 anv_state_pool_return_chunk(pool
, chunk_offset
+ alloc_size
,
1139 chunk_size
- alloc_size
, alloc_size
);
1145 offset
= anv_fixed_size_state_pool_alloc_new(&pool
->buckets
[bucket
],
1150 /* Everytime we allocate a new state, add it to the state pool */
1152 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &idx
, 1);
1153 assert(result
== VK_SUCCESS
);
1155 state
= anv_state_table_get(&pool
->table
, idx
);
1156 state
->offset
= offset
;
1157 state
->alloc_size
= alloc_size
;
1158 state
->map
= anv_block_pool_map(&pool
->block_pool
, offset
);
1161 uint32_t return_offset
= offset
- padding
;
1162 anv_state_pool_return_chunk(pool
, return_offset
, padding
, 0);
1170 anv_state_pool_alloc(struct anv_state_pool
*pool
, uint32_t size
, uint32_t align
)
1173 return ANV_STATE_NULL
;
1175 struct anv_state state
= anv_state_pool_alloc_no_vg(pool
, size
, align
);
1176 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
.map
, size
));
1181 anv_state_pool_alloc_back(struct anv_state_pool
*pool
)
1183 struct anv_state
*state
;
1184 uint32_t alloc_size
= pool
->block_size
;
1186 state
= anv_free_list_pop(&pool
->back_alloc_free_list
, &pool
->table
);
1188 assert(state
->offset
< 0);
1193 offset
= anv_block_pool_alloc_back(&pool
->block_pool
,
1196 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &idx
, 1);
1197 assert(result
== VK_SUCCESS
);
1199 state
= anv_state_table_get(&pool
->table
, idx
);
1200 state
->offset
= offset
;
1201 state
->alloc_size
= alloc_size
;
1202 state
->map
= anv_block_pool_map(&pool
->block_pool
, state
->offset
);
1205 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
->map
, state
->alloc_size
));
1210 anv_state_pool_free_no_vg(struct anv_state_pool
*pool
, struct anv_state state
)
1212 assert(util_is_power_of_two_or_zero(state
.alloc_size
));
1213 unsigned bucket
= anv_state_pool_get_bucket(state
.alloc_size
);
1215 if (state
.offset
< 0) {
1216 assert(state
.alloc_size
== pool
->block_size
);
1217 anv_free_list_push(&pool
->back_alloc_free_list
,
1218 &pool
->table
, state
.idx
, 1);
1220 anv_free_list_push(&pool
->buckets
[bucket
].free_list
,
1221 &pool
->table
, state
.idx
, 1);
1226 anv_state_pool_free(struct anv_state_pool
*pool
, struct anv_state state
)
1228 if (state
.alloc_size
== 0)
1231 VG(VALGRIND_MEMPOOL_FREE(pool
, state
.map
));
1232 anv_state_pool_free_no_vg(pool
, state
);
1235 struct anv_state_stream_block
{
1236 struct anv_state block
;
1238 /* The next block */
1239 struct anv_state_stream_block
*next
;
1241 #ifdef HAVE_VALGRIND
1242 /* A pointer to the first user-allocated thing in this block. This is
1243 * what valgrind sees as the start of the block.
1249 /* The state stream allocator is a one-shot, single threaded allocator for
1250 * variable sized blocks. We use it for allocating dynamic state.
1253 anv_state_stream_init(struct anv_state_stream
*stream
,
1254 struct anv_state_pool
*state_pool
,
1255 uint32_t block_size
)
1257 stream
->state_pool
= state_pool
;
1258 stream
->block_size
= block_size
;
1260 stream
->block
= ANV_STATE_NULL
;
1262 stream
->block_list
= NULL
;
1264 /* Ensure that next + whatever > block_size. This way the first call to
1265 * state_stream_alloc fetches a new block.
1267 stream
->next
= block_size
;
1269 VG(VALGRIND_CREATE_MEMPOOL(stream
, 0, false));
1273 anv_state_stream_finish(struct anv_state_stream
*stream
)
1275 struct anv_state_stream_block
*next
= stream
->block_list
;
1276 while (next
!= NULL
) {
1277 struct anv_state_stream_block sb
= VG_NOACCESS_READ(next
);
1278 VG(VALGRIND_MEMPOOL_FREE(stream
, sb
._vg_ptr
));
1279 VG(VALGRIND_MAKE_MEM_UNDEFINED(next
, stream
->block_size
));
1280 anv_state_pool_free_no_vg(stream
->state_pool
, sb
.block
);
1284 VG(VALGRIND_DESTROY_MEMPOOL(stream
));
1288 anv_state_stream_alloc(struct anv_state_stream
*stream
,
1289 uint32_t size
, uint32_t alignment
)
1292 return ANV_STATE_NULL
;
1294 assert(alignment
<= PAGE_SIZE
);
1296 uint32_t offset
= align_u32(stream
->next
, alignment
);
1297 if (offset
+ size
> stream
->block
.alloc_size
) {
1298 uint32_t block_size
= stream
->block_size
;
1299 if (block_size
< size
)
1300 block_size
= round_to_power_of_two(size
);
1302 stream
->block
= anv_state_pool_alloc_no_vg(stream
->state_pool
,
1303 block_size
, PAGE_SIZE
);
1305 struct anv_state_stream_block
*sb
= stream
->block
.map
;
1306 VG_NOACCESS_WRITE(&sb
->block
, stream
->block
);
1307 VG_NOACCESS_WRITE(&sb
->next
, stream
->block_list
);
1308 stream
->block_list
= sb
;
1309 VG(VG_NOACCESS_WRITE(&sb
->_vg_ptr
, NULL
));
1311 VG(VALGRIND_MAKE_MEM_NOACCESS(stream
->block
.map
, stream
->block_size
));
1313 /* Reset back to the start plus space for the header */
1314 stream
->next
= sizeof(*sb
);
1316 offset
= align_u32(stream
->next
, alignment
);
1317 assert(offset
+ size
<= stream
->block
.alloc_size
);
1320 struct anv_state state
= stream
->block
;
1321 state
.offset
+= offset
;
1322 state
.alloc_size
= size
;
1323 state
.map
+= offset
;
1325 stream
->next
= offset
+ size
;
1327 #ifdef HAVE_VALGRIND
1328 struct anv_state_stream_block
*sb
= stream
->block_list
;
1329 void *vg_ptr
= VG_NOACCESS_READ(&sb
->_vg_ptr
);
1330 if (vg_ptr
== NULL
) {
1332 VG_NOACCESS_WRITE(&sb
->_vg_ptr
, vg_ptr
);
1333 VALGRIND_MEMPOOL_ALLOC(stream
, vg_ptr
, size
);
1335 void *state_end
= state
.map
+ state
.alloc_size
;
1336 /* This only updates the mempool. The newly allocated chunk is still
1337 * marked as NOACCESS. */
1338 VALGRIND_MEMPOOL_CHANGE(stream
, vg_ptr
, vg_ptr
, state_end
- vg_ptr
);
1339 /* Mark the newly allocated chunk as undefined */
1340 VALGRIND_MAKE_MEM_UNDEFINED(state
.map
, state
.alloc_size
);
1347 struct bo_pool_bo_link
{
1348 struct bo_pool_bo_link
*next
;
1353 anv_bo_pool_init(struct anv_bo_pool
*pool
, struct anv_device
*device
,
1356 pool
->device
= device
;
1357 pool
->bo_flags
= bo_flags
;
1358 memset(pool
->free_list
, 0, sizeof(pool
->free_list
));
1360 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
1364 anv_bo_pool_finish(struct anv_bo_pool
*pool
)
1366 for (unsigned i
= 0; i
< ARRAY_SIZE(pool
->free_list
); i
++) {
1367 struct bo_pool_bo_link
*link
= PFL_PTR(pool
->free_list
[i
]);
1368 while (link
!= NULL
) {
1369 struct bo_pool_bo_link link_copy
= VG_NOACCESS_READ(link
);
1371 anv_gem_munmap(link_copy
.bo
.map
, link_copy
.bo
.size
);
1372 anv_vma_free(pool
->device
, &link_copy
.bo
);
1373 anv_gem_close(pool
->device
, link_copy
.bo
.gem_handle
);
1374 link
= link_copy
.next
;
1378 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
1382 anv_bo_pool_alloc(struct anv_bo_pool
*pool
, struct anv_bo
*bo
, uint32_t size
)
1386 const unsigned size_log2
= size
< 4096 ? 12 : ilog2_round_up(size
);
1387 const unsigned pow2_size
= 1 << size_log2
;
1388 const unsigned bucket
= size_log2
- 12;
1389 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
1391 void *next_free_void
;
1392 if (anv_ptr_free_list_pop(&pool
->free_list
[bucket
], &next_free_void
)) {
1393 struct bo_pool_bo_link
*next_free
= next_free_void
;
1394 *bo
= VG_NOACCESS_READ(&next_free
->bo
);
1395 assert(bo
->gem_handle
);
1396 assert(bo
->map
== next_free
);
1397 assert(size
<= bo
->size
);
1399 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1404 struct anv_bo new_bo
;
1406 result
= anv_bo_init_new(&new_bo
, pool
->device
, pow2_size
);
1407 if (result
!= VK_SUCCESS
)
1410 new_bo
.flags
= pool
->bo_flags
;
1412 if (!anv_vma_alloc(pool
->device
, &new_bo
))
1413 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY
);
1415 assert(new_bo
.size
== pow2_size
);
1417 new_bo
.map
= anv_gem_mmap(pool
->device
, new_bo
.gem_handle
, 0, pow2_size
, 0);
1418 if (new_bo
.map
== MAP_FAILED
) {
1419 anv_gem_close(pool
->device
, new_bo
.gem_handle
);
1420 anv_vma_free(pool
->device
, &new_bo
);
1421 return vk_error(VK_ERROR_MEMORY_MAP_FAILED
);
1424 /* We are removing the state flushes, so lets make sure that these buffers
1425 * are cached/snooped.
1427 if (!pool
->device
->info
.has_llc
) {
1428 anv_gem_set_caching(pool
->device
, new_bo
.gem_handle
,
1429 I915_CACHING_CACHED
);
1434 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1440 anv_bo_pool_free(struct anv_bo_pool
*pool
, const struct anv_bo
*bo_in
)
1442 /* Make a copy in case the anv_bo happens to be storred in the BO */
1443 struct anv_bo bo
= *bo_in
;
1445 VG(VALGRIND_MEMPOOL_FREE(pool
, bo
.map
));
1447 struct bo_pool_bo_link
*link
= bo
.map
;
1448 VG_NOACCESS_WRITE(&link
->bo
, bo
);
1450 assert(util_is_power_of_two_or_zero(bo
.size
));
1451 const unsigned size_log2
= ilog2_round_up(bo
.size
);
1452 const unsigned bucket
= size_log2
- 12;
1453 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
1455 anv_ptr_free_list_push(&pool
->free_list
[bucket
], link
);
1461 anv_scratch_pool_init(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1463 memset(pool
, 0, sizeof(*pool
));
1467 anv_scratch_pool_finish(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1469 for (unsigned s
= 0; s
< MESA_SHADER_STAGES
; s
++) {
1470 for (unsigned i
= 0; i
< 16; i
++) {
1471 struct anv_scratch_bo
*bo
= &pool
->bos
[i
][s
];
1472 if (bo
->exists
> 0) {
1473 anv_vma_free(device
, &bo
->bo
);
1474 anv_gem_close(device
, bo
->bo
.gem_handle
);
1481 anv_scratch_pool_alloc(struct anv_device
*device
, struct anv_scratch_pool
*pool
,
1482 gl_shader_stage stage
, unsigned per_thread_scratch
)
1484 if (per_thread_scratch
== 0)
1487 unsigned scratch_size_log2
= ffs(per_thread_scratch
/ 2048);
1488 assert(scratch_size_log2
< 16);
1490 struct anv_scratch_bo
*bo
= &pool
->bos
[scratch_size_log2
][stage
];
1492 /* We can use "exists" to shortcut and ignore the critical section */
1496 pthread_mutex_lock(&device
->mutex
);
1498 __sync_synchronize();
1500 pthread_mutex_unlock(&device
->mutex
);
1504 const struct anv_physical_device
*physical_device
=
1505 &device
->instance
->physicalDevice
;
1506 const struct gen_device_info
*devinfo
= &physical_device
->info
;
1508 const unsigned subslices
= MAX2(physical_device
->subslice_total
, 1);
1510 unsigned scratch_ids_per_subslice
;
1511 if (devinfo
->gen
>= 11) {
1512 /* The MEDIA_VFE_STATE docs say:
1514 * "Starting with this configuration, the Maximum Number of
1515 * Threads must be set to (#EU * 8) for GPGPU dispatches.
1517 * Although there are only 7 threads per EU in the configuration,
1518 * the FFTID is calculated as if there are 8 threads per EU,
1519 * which in turn requires a larger amount of Scratch Space to be
1520 * allocated by the driver."
1522 scratch_ids_per_subslice
= 8 * 8;
1523 } else if (devinfo
->is_haswell
) {
1524 /* WaCSScratchSize:hsw
1526 * Haswell's scratch space address calculation appears to be sparse
1527 * rather than tightly packed. The Thread ID has bits indicating
1528 * which subslice, EU within a subslice, and thread within an EU it
1529 * is. There's a maximum of two slices and two subslices, so these
1530 * can be stored with a single bit. Even though there are only 10 EUs
1531 * per subslice, this is stored in 4 bits, so there's an effective
1532 * maximum value of 16 EUs. Similarly, although there are only 7
1533 * threads per EU, this is stored in a 3 bit number, giving an
1534 * effective maximum value of 8 threads per EU.
1536 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1537 * number of threads per subslice.
1539 scratch_ids_per_subslice
= 16 * 8;
1540 } else if (devinfo
->is_cherryview
) {
1541 /* Cherryview devices have either 6 or 8 EUs per subslice, and each EU
1542 * has 7 threads. The 6 EU devices appear to calculate thread IDs as if
1545 scratch_ids_per_subslice
= 8 * 7;
1547 scratch_ids_per_subslice
= devinfo
->max_cs_threads
;
1550 uint32_t max_threads
[] = {
1551 [MESA_SHADER_VERTEX
] = devinfo
->max_vs_threads
,
1552 [MESA_SHADER_TESS_CTRL
] = devinfo
->max_tcs_threads
,
1553 [MESA_SHADER_TESS_EVAL
] = devinfo
->max_tes_threads
,
1554 [MESA_SHADER_GEOMETRY
] = devinfo
->max_gs_threads
,
1555 [MESA_SHADER_FRAGMENT
] = devinfo
->max_wm_threads
,
1556 [MESA_SHADER_COMPUTE
] = scratch_ids_per_subslice
* subslices
,
1559 uint32_t size
= per_thread_scratch
* max_threads
[stage
];
1561 anv_bo_init_new(&bo
->bo
, device
, size
);
1563 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1564 * are still relative to the general state base address. When we emit
1565 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1566 * to the maximum (1 page under 4GB). This allows us to just place the
1567 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1568 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1569 * However, in order to do so, we need to ensure that the kernel does not
1570 * place the scratch BO above the 32-bit boundary.
1572 * NOTE: Technically, it can't go "anywhere" because the top page is off
1573 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1574 * kernel allocates space using
1576 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1578 * so nothing will ever touch the top page.
1580 assert(!(bo
->bo
.flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
));
1582 if (device
->instance
->physicalDevice
.has_exec_async
)
1583 bo
->bo
.flags
|= EXEC_OBJECT_ASYNC
;
1585 if (device
->instance
->physicalDevice
.use_softpin
)
1586 bo
->bo
.flags
|= EXEC_OBJECT_PINNED
;
1588 anv_vma_alloc(device
, &bo
->bo
);
1590 /* Set the exists last because it may be read by other threads */
1591 __sync_synchronize();
1594 pthread_mutex_unlock(&device
->mutex
);
1600 anv_bo_cache_init(struct anv_bo_cache
*cache
)
1602 util_sparse_array_init(&cache
->bo_map
, sizeof(struct anv_bo
), 1024);
1604 if (pthread_mutex_init(&cache
->mutex
, NULL
)) {
1605 util_sparse_array_finish(&cache
->bo_map
);
1606 return vk_errorf(NULL
, NULL
, VK_ERROR_OUT_OF_HOST_MEMORY
,
1607 "pthread_mutex_init failed: %m");
1614 anv_bo_cache_finish(struct anv_bo_cache
*cache
)
1616 util_sparse_array_finish(&cache
->bo_map
);
1617 pthread_mutex_destroy(&cache
->mutex
);
1620 static struct anv_bo
*
1621 anv_bo_cache_lookup(struct anv_bo_cache
*cache
, uint32_t gem_handle
)
1623 return util_sparse_array_get(&cache
->bo_map
, gem_handle
);
1626 #define ANV_BO_CACHE_SUPPORTED_FLAGS \
1627 (EXEC_OBJECT_WRITE | \
1628 EXEC_OBJECT_ASYNC | \
1629 EXEC_OBJECT_SUPPORTS_48B_ADDRESS | \
1633 anv_bo_cache_alloc(struct anv_device
*device
,
1634 struct anv_bo_cache
*cache
,
1635 uint64_t size
, uint64_t bo_flags
,
1637 struct anv_bo
**bo_out
)
1639 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1641 /* The kernel is going to give us whole pages anyway */
1642 size
= align_u64(size
, 4096);
1644 struct anv_bo new_bo
;
1645 VkResult result
= anv_bo_init_new(&new_bo
, device
, size
);
1646 if (result
!= VK_SUCCESS
)
1649 new_bo
.flags
= bo_flags
;
1650 new_bo
.is_external
= is_external
;
1652 if (!anv_vma_alloc(device
, &new_bo
)) {
1653 anv_gem_close(device
, new_bo
.gem_handle
);
1654 return vk_errorf(device
->instance
, NULL
,
1655 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1656 "failed to allocate virtual address for BO");
1659 assert(new_bo
.gem_handle
);
1661 /* If we just got this gem_handle from anv_bo_init_new then we know no one
1662 * else is touching this BO at the moment so we don't need to lock here.
1664 struct anv_bo
*bo
= anv_bo_cache_lookup(cache
, new_bo
.gem_handle
);
1673 anv_bo_cache_import_host_ptr(struct anv_device
*device
,
1674 struct anv_bo_cache
*cache
,
1675 void *host_ptr
, uint32_t size
,
1676 uint64_t bo_flags
, struct anv_bo
**bo_out
)
1678 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1680 uint32_t gem_handle
= anv_gem_userptr(device
, host_ptr
, size
);
1682 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE
);
1684 pthread_mutex_lock(&cache
->mutex
);
1686 struct anv_bo
*bo
= anv_bo_cache_lookup(cache
, gem_handle
);
1687 if (bo
->refcount
> 0) {
1688 /* VK_EXT_external_memory_host doesn't require handling importing the
1689 * same pointer twice at the same time, but we don't get in the way. If
1690 * kernel gives us the same gem_handle, only succeed if the flags match.
1692 assert(bo
->gem_handle
== gem_handle
);
1693 if (bo_flags
!= bo
->flags
) {
1694 pthread_mutex_unlock(&cache
->mutex
);
1695 return vk_errorf(device
->instance
, NULL
,
1696 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1697 "same host pointer imported two different ways");
1699 __sync_fetch_and_add(&bo
->refcount
, 1);
1701 struct anv_bo new_bo
;
1702 anv_bo_init(&new_bo
, gem_handle
, size
);
1703 new_bo
.flags
= bo_flags
;
1704 new_bo
.is_external
= true;
1706 if (!anv_vma_alloc(device
, &new_bo
)) {
1707 anv_gem_close(device
, new_bo
.gem_handle
);
1708 pthread_mutex_unlock(&cache
->mutex
);
1709 return vk_errorf(device
->instance
, NULL
,
1710 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1711 "failed to allocate virtual address for BO");
1717 pthread_mutex_unlock(&cache
->mutex
);
1724 anv_bo_cache_import(struct anv_device
*device
,
1725 struct anv_bo_cache
*cache
,
1726 int fd
, uint64_t bo_flags
,
1727 struct anv_bo
**bo_out
)
1729 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1731 pthread_mutex_lock(&cache
->mutex
);
1733 uint32_t gem_handle
= anv_gem_fd_to_handle(device
, fd
);
1735 pthread_mutex_unlock(&cache
->mutex
);
1736 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE
);
1739 struct anv_bo
*bo
= anv_bo_cache_lookup(cache
, gem_handle
);
1740 if (bo
->refcount
> 0) {
1741 /* We have to be careful how we combine flags so that it makes sense.
1742 * Really, though, if we get to this case and it actually matters, the
1743 * client has imported a BO twice in different ways and they get what
1746 uint64_t new_flags
= 0;
1747 new_flags
|= (bo
->flags
| bo_flags
) & EXEC_OBJECT_WRITE
;
1748 new_flags
|= (bo
->flags
& bo_flags
) & EXEC_OBJECT_ASYNC
;
1749 new_flags
|= (bo
->flags
& bo_flags
) & EXEC_OBJECT_SUPPORTS_48B_ADDRESS
;
1750 new_flags
|= (bo
->flags
| bo_flags
) & EXEC_OBJECT_PINNED
;
1752 /* It's theoretically possible for a BO to get imported such that it's
1753 * both pinned and not pinned. The only way this can happen is if it
1754 * gets imported as both a semaphore and a memory object and that would
1755 * be an application error. Just fail out in that case.
1757 if ((bo
->flags
& EXEC_OBJECT_PINNED
) !=
1758 (bo_flags
& EXEC_OBJECT_PINNED
)) {
1759 pthread_mutex_unlock(&cache
->mutex
);
1760 return vk_errorf(device
->instance
, NULL
,
1761 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1762 "The same BO was imported two different ways");
1765 /* It's also theoretically possible that someone could export a BO from
1766 * one heap and import it into another or to import the same BO into two
1767 * different heaps. If this happens, we could potentially end up both
1768 * allowing and disallowing 48-bit addresses. There's not much we can
1769 * do about it if we're pinning so we just throw an error and hope no
1770 * app is actually that stupid.
1772 if ((new_flags
& EXEC_OBJECT_PINNED
) &&
1773 (bo
->flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
) !=
1774 (bo_flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
)) {
1775 pthread_mutex_unlock(&cache
->mutex
);
1776 return vk_errorf(device
->instance
, NULL
,
1777 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1778 "The same BO was imported on two different heaps");
1781 bo
->flags
= new_flags
;
1783 __sync_fetch_and_add(&bo
->refcount
, 1);
1785 off_t size
= lseek(fd
, 0, SEEK_END
);
1786 if (size
== (off_t
)-1) {
1787 anv_gem_close(device
, gem_handle
);
1788 pthread_mutex_unlock(&cache
->mutex
);
1789 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE
);
1792 struct anv_bo new_bo
;
1793 anv_bo_init(&new_bo
, gem_handle
, size
);
1794 new_bo
.flags
= bo_flags
;
1795 new_bo
.is_external
= true;
1797 if (!anv_vma_alloc(device
, &new_bo
)) {
1798 anv_gem_close(device
, new_bo
.gem_handle
);
1799 pthread_mutex_unlock(&cache
->mutex
);
1800 return vk_errorf(device
->instance
, NULL
,
1801 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1802 "failed to allocate virtual address for BO");
1808 pthread_mutex_unlock(&cache
->mutex
);
1815 anv_bo_cache_export(struct anv_device
*device
,
1816 struct anv_bo_cache
*cache
,
1817 struct anv_bo
*bo
, int *fd_out
)
1819 assert(anv_bo_cache_lookup(cache
, bo
->gem_handle
) == bo
);
1821 /* This BO must have been flagged external in order for us to be able
1822 * to export it. This is done based on external options passed into
1823 * anv_AllocateMemory.
1825 assert(bo
->is_external
);
1827 int fd
= anv_gem_handle_to_fd(device
, bo
->gem_handle
);
1829 return vk_error(VK_ERROR_TOO_MANY_OBJECTS
);
1837 atomic_dec_not_one(uint32_t *counter
)
1846 old
= __sync_val_compare_and_swap(counter
, val
, val
- 1);
1855 anv_bo_cache_release(struct anv_device
*device
,
1856 struct anv_bo_cache
*cache
,
1859 assert(anv_bo_cache_lookup(cache
, bo
->gem_handle
) == bo
);
1861 /* Try to decrement the counter but don't go below one. If this succeeds
1862 * then the refcount has been decremented and we are not the last
1865 if (atomic_dec_not_one(&bo
->refcount
))
1868 pthread_mutex_lock(&cache
->mutex
);
1870 /* We are probably the last reference since our attempt to decrement above
1871 * failed. However, we can't actually know until we are inside the mutex.
1872 * Otherwise, someone could import the BO between the decrement and our
1875 if (unlikely(__sync_sub_and_fetch(&bo
->refcount
, 1) > 0)) {
1876 /* Turns out we're not the last reference. Unlock and bail. */
1877 pthread_mutex_unlock(&cache
->mutex
);
1880 assert(bo
->refcount
== 0);
1883 anv_gem_munmap(bo
->map
, bo
->size
);
1885 anv_vma_free(device
, bo
);
1887 anv_gem_close(device
, bo
->gem_handle
);
1889 /* Don't unlock until we've actually closed the BO. The whole point of
1890 * the BO cache is to ensure that we correctly handle races with creating
1891 * and releasing GEM handles and we don't want to let someone import the BO
1892 * again between mutex unlock and closing the GEM handle.
1894 pthread_mutex_unlock(&cache
->mutex
);