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
{
114 static inline uint32_t
115 ilog2_round_up(uint32_t value
)
118 return 32 - __builtin_clz(value
- 1);
121 static inline uint32_t
122 round_to_power_of_two(uint32_t value
)
124 return 1 << ilog2_round_up(value
);
127 struct anv_state_table_cleanup
{
132 #define ANV_STATE_TABLE_CLEANUP_INIT ((struct anv_state_table_cleanup){0})
133 #define ANV_STATE_ENTRY_SIZE (sizeof(struct anv_free_entry))
136 anv_state_table_expand_range(struct anv_state_table
*table
, uint32_t size
);
139 anv_state_table_init(struct anv_state_table
*table
,
140 struct anv_device
*device
,
141 uint32_t initial_entries
)
145 table
->device
= device
;
147 /* Just make it 2GB up-front. The Linux kernel won't actually back it
148 * with pages until we either map and fault on one of them or we use
149 * userptr and send a chunk of it off to the GPU.
151 table
->fd
= os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE
, "state table");
152 if (table
->fd
== -1) {
153 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
157 if (!u_vector_init(&table
->cleanups
,
158 round_to_power_of_two(sizeof(struct anv_state_table_cleanup
)),
160 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
164 table
->state
.next
= 0;
165 table
->state
.end
= 0;
168 uint32_t initial_size
= initial_entries
* ANV_STATE_ENTRY_SIZE
;
169 result
= anv_state_table_expand_range(table
, initial_size
);
170 if (result
!= VK_SUCCESS
)
176 u_vector_finish(&table
->cleanups
);
184 anv_state_table_expand_range(struct anv_state_table
*table
, uint32_t size
)
187 struct anv_state_table_cleanup
*cleanup
;
189 /* Assert that we only ever grow the pool */
190 assert(size
>= table
->state
.end
);
192 /* Make sure that we don't go outside the bounds of the memfd */
193 if (size
> BLOCK_POOL_MEMFD_SIZE
)
194 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
196 cleanup
= u_vector_add(&table
->cleanups
);
198 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
200 *cleanup
= ANV_STATE_TABLE_CLEANUP_INIT
;
202 /* Just leak the old map until we destroy the pool. We can't munmap it
203 * without races or imposing locking on the block allocate fast path. On
204 * the whole the leaked maps adds up to less than the size of the
205 * current map. MAP_POPULATE seems like the right thing to do, but we
206 * should try to get some numbers.
208 map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
209 MAP_SHARED
| MAP_POPULATE
, table
->fd
, 0);
210 if (map
== MAP_FAILED
) {
211 return vk_errorf(table
->device
->instance
, table
->device
,
212 VK_ERROR_OUT_OF_HOST_MEMORY
, "mmap failed: %m");
216 cleanup
->size
= size
;
225 anv_state_table_grow(struct anv_state_table
*table
)
227 VkResult result
= VK_SUCCESS
;
229 uint32_t used
= align_u32(table
->state
.next
* ANV_STATE_ENTRY_SIZE
,
231 uint32_t old_size
= table
->size
;
233 /* The block pool is always initialized to a nonzero size and this function
234 * is always called after initialization.
236 assert(old_size
> 0);
238 uint32_t required
= MAX2(used
, old_size
);
239 if (used
* 2 <= required
) {
240 /* If we're in this case then this isn't the firsta allocation and we
241 * already have enough space on both sides to hold double what we
242 * have allocated. There's nothing for us to do.
247 uint32_t size
= old_size
* 2;
248 while (size
< required
)
251 assert(size
> table
->size
);
253 result
= anv_state_table_expand_range(table
, size
);
260 anv_state_table_finish(struct anv_state_table
*table
)
262 struct anv_state_table_cleanup
*cleanup
;
264 u_vector_foreach(cleanup
, &table
->cleanups
) {
266 munmap(cleanup
->map
, cleanup
->size
);
269 u_vector_finish(&table
->cleanups
);
275 anv_state_table_add(struct anv_state_table
*table
, uint32_t *idx
,
278 struct anv_block_state state
, old
, new;
284 state
.u64
= __sync_fetch_and_add(&table
->state
.u64
, count
);
285 if (state
.next
+ count
<= state
.end
) {
287 struct anv_free_entry
*entry
= &table
->map
[state
.next
];
288 for (int i
= 0; i
< count
; i
++) {
289 entry
[i
].state
.idx
= state
.next
+ i
;
293 } else if (state
.next
<= state
.end
) {
294 /* We allocated the first block outside the pool so we have to grow
295 * the pool. pool_state->next acts a mutex: threads who try to
296 * allocate now will get block indexes above the current limit and
297 * hit futex_wait below.
299 new.next
= state
.next
+ count
;
301 result
= anv_state_table_grow(table
);
302 if (result
!= VK_SUCCESS
)
304 new.end
= table
->size
/ ANV_STATE_ENTRY_SIZE
;
305 } while (new.end
< new.next
);
307 old
.u64
= __sync_lock_test_and_set(&table
->state
.u64
, new.u64
);
308 if (old
.next
!= state
.next
)
309 futex_wake(&table
->state
.end
, INT_MAX
);
311 futex_wait(&table
->state
.end
, state
.end
, NULL
);
318 anv_free_list_push(union anv_free_list
*list
,
319 struct anv_state_table
*table
,
320 uint32_t first
, uint32_t count
)
322 union anv_free_list current
, old
, new;
323 uint32_t last
= first
;
325 for (uint32_t i
= 1; i
< count
; i
++, last
++)
326 table
->map
[last
].next
= last
+ 1;
331 table
->map
[last
].next
= current
.offset
;
333 new.count
= current
.count
+ 1;
334 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
335 } while (old
.u64
!= current
.u64
);
339 anv_free_list_pop(union anv_free_list
*list
,
340 struct anv_state_table
*table
)
342 union anv_free_list current
, new, old
;
344 current
.u64
= list
->u64
;
345 while (current
.offset
!= EMPTY
) {
346 __sync_synchronize();
347 new.offset
= table
->map
[current
.offset
].next
;
348 new.count
= current
.count
+ 1;
349 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
350 if (old
.u64
== current
.u64
) {
351 struct anv_free_entry
*entry
= &table
->map
[current
.offset
];
352 return &entry
->state
;
361 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
362 uint32_t center_bo_offset
, uint32_t size
);
365 anv_block_pool_init(struct anv_block_pool
*pool
,
366 struct anv_device
*device
,
367 uint64_t start_address
,
368 uint32_t initial_size
)
372 pool
->device
= device
;
373 pool
->use_softpin
= device
->instance
->physicalDevice
.use_softpin
;
376 pool
->center_bo_offset
= 0;
377 pool
->start_address
= gen_canonical_address(start_address
);
380 if (pool
->use_softpin
) {
384 /* Just make it 2GB up-front. The Linux kernel won't actually back it
385 * with pages until we either map and fault on one of them or we use
386 * userptr and send a chunk of it off to the GPU.
388 pool
->fd
= os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE
, "block pool");
390 return vk_error(VK_ERROR_INITIALIZATION_FAILED
);
392 pool
->wrapper_bo
= (struct anv_bo
) {
397 pool
->bo
= &pool
->wrapper_bo
;
400 if (!u_vector_init(&pool
->mmap_cleanups
,
401 round_to_power_of_two(sizeof(struct anv_mmap_cleanup
)),
403 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
407 pool
->state
.next
= 0;
409 pool
->back_state
.next
= 0;
410 pool
->back_state
.end
= 0;
412 result
= anv_block_pool_expand_range(pool
, 0, initial_size
);
413 if (result
!= VK_SUCCESS
)
414 goto fail_mmap_cleanups
;
416 /* Make the entire pool available in the front of the pool. If back
417 * allocation needs to use this space, the "ends" will be re-arranged.
419 pool
->state
.end
= pool
->size
;
424 u_vector_finish(&pool
->mmap_cleanups
);
433 anv_block_pool_finish(struct anv_block_pool
*pool
)
435 anv_block_pool_foreach_bo(bo
, pool
) {
437 anv_gem_munmap(bo
->map
, bo
->size
);
438 anv_gem_close(pool
->device
, bo
->gem_handle
);
441 struct anv_mmap_cleanup
*cleanup
;
442 u_vector_foreach(cleanup
, &pool
->mmap_cleanups
)
443 munmap(cleanup
->map
, cleanup
->size
);
444 u_vector_finish(&pool
->mmap_cleanups
);
451 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
452 uint32_t center_bo_offset
, uint32_t size
)
454 /* Assert that we only ever grow the pool */
455 assert(center_bo_offset
>= pool
->back_state
.end
);
456 assert(size
- center_bo_offset
>= pool
->state
.end
);
458 /* Assert that we don't go outside the bounds of the memfd */
459 assert(center_bo_offset
<= BLOCK_POOL_MEMFD_CENTER
);
460 assert(pool
->use_softpin
||
461 size
- center_bo_offset
<=
462 BLOCK_POOL_MEMFD_SIZE
- BLOCK_POOL_MEMFD_CENTER
);
464 /* For state pool BOs we have to be a bit careful about where we place them
465 * in the GTT. There are two documented workarounds for state base address
466 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
467 * which state that those two base addresses do not support 48-bit
468 * addresses and need to be placed in the bottom 32-bit range.
469 * Unfortunately, this is not quite accurate.
471 * The real problem is that we always set the size of our state pools in
472 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
473 * likely significantly smaller. We do this because we do not no at the
474 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
475 * the pool during command buffer building so we don't actually have a
476 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
477 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
478 * as being out of bounds and returns zero. For dynamic state, this
479 * usually just leads to rendering corruptions, but shaders that are all
480 * zero hang the GPU immediately.
482 * The easiest solution to do is exactly what the bogus workarounds say to
483 * do: restrict these buffers to 32-bit addresses. We could also pin the
484 * BO to some particular location of our choosing, but that's significantly
485 * more work than just not setting a flag. So, we explicitly DO NOT set
486 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
487 * hard work for us. When using softpin, we're in control and the fixed
488 * addresses we choose are fine for base addresses.
490 enum anv_bo_alloc_flags bo_alloc_flags
= ANV_BO_ALLOC_CAPTURE
;
491 if (!pool
->use_softpin
)
492 bo_alloc_flags
|= ANV_BO_ALLOC_32BIT_ADDRESS
;
494 if (pool
->use_softpin
) {
495 uint32_t new_bo_size
= size
- pool
->size
;
496 struct anv_bo
*new_bo
;
497 assert(center_bo_offset
== 0);
498 VkResult result
= anv_device_alloc_bo(pool
->device
, new_bo_size
,
500 ANV_BO_ALLOC_FIXED_ADDRESS
|
501 ANV_BO_ALLOC_MAPPED
|
502 ANV_BO_ALLOC_SNOOPED
,
503 pool
->start_address
+ pool
->size
,
505 if (result
!= VK_SUCCESS
)
508 pool
->bos
[pool
->nbos
++] = new_bo
;
510 /* This pointer will always point to the first BO in the list */
511 pool
->bo
= pool
->bos
[0];
513 /* Just leak the old map until we destroy the pool. We can't munmap it
514 * without races or imposing locking on the block allocate fast path. On
515 * the whole the leaked maps adds up to less than the size of the
516 * current map. MAP_POPULATE seems like the right thing to do, but we
517 * should try to get some numbers.
519 void *map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
520 MAP_SHARED
| MAP_POPULATE
, pool
->fd
,
521 BLOCK_POOL_MEMFD_CENTER
- center_bo_offset
);
522 if (map
== MAP_FAILED
)
523 return vk_errorf(pool
->device
->instance
, pool
->device
,
524 VK_ERROR_MEMORY_MAP_FAILED
, "mmap failed: %m");
526 struct anv_bo
*new_bo
;
527 VkResult result
= anv_device_import_bo_from_host_ptr(pool
->device
,
530 0 /* client_address */,
532 if (result
!= VK_SUCCESS
) {
537 struct anv_mmap_cleanup
*cleanup
= u_vector_add(&pool
->mmap_cleanups
);
540 anv_device_release_bo(pool
->device
, new_bo
);
541 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
544 cleanup
->size
= size
;
546 /* Now that we mapped the new memory, we can write the new
547 * center_bo_offset back into pool and update pool->map. */
548 pool
->center_bo_offset
= center_bo_offset
;
549 pool
->map
= map
+ center_bo_offset
;
551 pool
->bos
[pool
->nbos
++] = new_bo
;
552 pool
->wrapper_bo
.map
= new_bo
;
555 assert(pool
->nbos
< ANV_MAX_BLOCK_POOL_BOS
);
561 /** Returns current memory map of the block pool.
563 * The returned pointer points to the map for the memory at the specified
564 * offset. The offset parameter is relative to the "center" of the block pool
565 * rather than the start of the block pool BO map.
568 anv_block_pool_map(struct anv_block_pool
*pool
, int32_t offset
)
570 if (pool
->use_softpin
) {
571 struct anv_bo
*bo
= NULL
;
572 int32_t bo_offset
= 0;
573 anv_block_pool_foreach_bo(iter_bo
, pool
) {
574 if (offset
< bo_offset
+ iter_bo
->size
) {
578 bo_offset
+= iter_bo
->size
;
581 assert(offset
>= bo_offset
);
583 return bo
->map
+ (offset
- bo_offset
);
585 return pool
->map
+ offset
;
589 /** Grows and re-centers the block pool.
591 * We grow the block pool in one or both directions in such a way that the
592 * following conditions are met:
594 * 1) The size of the entire pool is always a power of two.
596 * 2) The pool only grows on both ends. Neither end can get
599 * 3) At the end of the allocation, we have about twice as much space
600 * allocated for each end as we have used. This way the pool doesn't
601 * grow too far in one direction or the other.
603 * 4) If the _alloc_back() has never been called, then the back portion of
604 * the pool retains a size of zero. (This makes it easier for users of
605 * the block pool that only want a one-sided pool.)
607 * 5) We have enough space allocated for at least one more block in
608 * whichever side `state` points to.
610 * 6) The center of the pool is always aligned to both the block_size of
611 * the pool and a 4K CPU page.
614 anv_block_pool_grow(struct anv_block_pool
*pool
, struct anv_block_state
*state
)
616 VkResult result
= VK_SUCCESS
;
618 pthread_mutex_lock(&pool
->device
->mutex
);
620 assert(state
== &pool
->state
|| state
== &pool
->back_state
);
622 /* Gather a little usage information on the pool. Since we may have
623 * threadsd waiting in queue to get some storage while we resize, it's
624 * actually possible that total_used will be larger than old_size. In
625 * particular, block_pool_alloc() increments state->next prior to
626 * calling block_pool_grow, so this ensures that we get enough space for
627 * which ever side tries to grow the pool.
629 * We align to a page size because it makes it easier to do our
630 * calculations later in such a way that we state page-aigned.
632 uint32_t back_used
= align_u32(pool
->back_state
.next
, PAGE_SIZE
);
633 uint32_t front_used
= align_u32(pool
->state
.next
, PAGE_SIZE
);
634 uint32_t total_used
= front_used
+ back_used
;
636 assert(state
== &pool
->state
|| back_used
> 0);
638 uint32_t old_size
= pool
->size
;
640 /* The block pool is always initialized to a nonzero size and this function
641 * is always called after initialization.
643 assert(old_size
> 0);
645 /* The back_used and front_used may actually be smaller than the actual
646 * requirement because they are based on the next pointers which are
647 * updated prior to calling this function.
649 uint32_t back_required
= MAX2(back_used
, pool
->center_bo_offset
);
650 uint32_t front_required
= MAX2(front_used
, old_size
- pool
->center_bo_offset
);
652 if (back_used
* 2 <= back_required
&& front_used
* 2 <= front_required
) {
653 /* If we're in this case then this isn't the firsta allocation and we
654 * already have enough space on both sides to hold double what we
655 * have allocated. There's nothing for us to do.
660 uint32_t size
= old_size
* 2;
661 while (size
< back_required
+ front_required
)
664 assert(size
> pool
->size
);
666 /* We compute a new center_bo_offset such that, when we double the size
667 * of the pool, we maintain the ratio of how much is used by each side.
668 * This way things should remain more-or-less balanced.
670 uint32_t center_bo_offset
;
671 if (back_used
== 0) {
672 /* If we're in this case then we have never called alloc_back(). In
673 * this case, we want keep the offset at 0 to make things as simple
674 * as possible for users that don't care about back allocations.
676 center_bo_offset
= 0;
678 /* Try to "center" the allocation based on how much is currently in
679 * use on each side of the center line.
681 center_bo_offset
= ((uint64_t)size
* back_used
) / total_used
;
683 /* Align down to a multiple of the page size */
684 center_bo_offset
&= ~(PAGE_SIZE
- 1);
686 assert(center_bo_offset
>= back_used
);
688 /* Make sure we don't shrink the back end of the pool */
689 if (center_bo_offset
< back_required
)
690 center_bo_offset
= back_required
;
692 /* Make sure that we don't shrink the front end of the pool */
693 if (size
- center_bo_offset
< front_required
)
694 center_bo_offset
= size
- front_required
;
697 assert(center_bo_offset
% PAGE_SIZE
== 0);
699 result
= anv_block_pool_expand_range(pool
, center_bo_offset
, size
);
702 pthread_mutex_unlock(&pool
->device
->mutex
);
704 if (result
== VK_SUCCESS
) {
705 /* Return the appropriate new size. This function never actually
706 * updates state->next. Instead, we let the caller do that because it
707 * needs to do so in order to maintain its concurrency model.
709 if (state
== &pool
->state
) {
710 return pool
->size
- pool
->center_bo_offset
;
712 assert(pool
->center_bo_offset
> 0);
713 return pool
->center_bo_offset
;
721 anv_block_pool_alloc_new(struct anv_block_pool
*pool
,
722 struct anv_block_state
*pool_state
,
723 uint32_t block_size
, uint32_t *padding
)
725 struct anv_block_state state
, old
, new;
727 /* Most allocations won't generate any padding */
732 state
.u64
= __sync_fetch_and_add(&pool_state
->u64
, block_size
);
733 if (state
.next
+ block_size
<= state
.end
) {
735 } else if (state
.next
<= state
.end
) {
736 if (pool
->use_softpin
&& state
.next
< state
.end
) {
737 /* We need to grow the block pool, but still have some leftover
738 * space that can't be used by that particular allocation. So we
739 * add that as a "padding", and return it.
741 uint32_t leftover
= state
.end
- state
.next
;
743 /* If there is some leftover space in the pool, the caller must
746 assert(leftover
== 0 || padding
);
749 state
.next
+= leftover
;
752 /* We allocated the first block outside the pool so we have to grow
753 * the pool. pool_state->next acts a mutex: threads who try to
754 * allocate now will get block indexes above the current limit and
755 * hit futex_wait below.
757 new.next
= state
.next
+ block_size
;
759 new.end
= anv_block_pool_grow(pool
, pool_state
);
760 } while (new.end
< new.next
);
762 old
.u64
= __sync_lock_test_and_set(&pool_state
->u64
, new.u64
);
763 if (old
.next
!= state
.next
)
764 futex_wake(&pool_state
->end
, INT_MAX
);
767 futex_wait(&pool_state
->end
, state
.end
, NULL
);
774 anv_block_pool_alloc(struct anv_block_pool
*pool
,
775 uint32_t block_size
, uint32_t *padding
)
779 offset
= anv_block_pool_alloc_new(pool
, &pool
->state
, block_size
, padding
);
784 /* Allocates a block out of the back of the block pool.
786 * This will allocated a block earlier than the "start" of the block pool.
787 * The offsets returned from this function will be negative but will still
788 * be correct relative to the block pool's map pointer.
790 * If you ever use anv_block_pool_alloc_back, then you will have to do
791 * gymnastics with the block pool's BO when doing relocations.
794 anv_block_pool_alloc_back(struct anv_block_pool
*pool
,
797 int32_t offset
= anv_block_pool_alloc_new(pool
, &pool
->back_state
,
800 /* The offset we get out of anv_block_pool_alloc_new() is actually the
801 * number of bytes downwards from the middle to the end of the block.
802 * We need to turn it into a (negative) offset from the middle to the
803 * start of the block.
806 return -(offset
+ block_size
);
810 anv_state_pool_init(struct anv_state_pool
*pool
,
811 struct anv_device
*device
,
812 uint64_t start_address
,
815 VkResult result
= anv_block_pool_init(&pool
->block_pool
, device
,
818 if (result
!= VK_SUCCESS
)
821 result
= anv_state_table_init(&pool
->table
, device
, 64);
822 if (result
!= VK_SUCCESS
) {
823 anv_block_pool_finish(&pool
->block_pool
);
827 assert(util_is_power_of_two_or_zero(block_size
));
828 pool
->block_size
= block_size
;
829 pool
->back_alloc_free_list
= ANV_FREE_LIST_EMPTY
;
830 for (unsigned i
= 0; i
< ANV_STATE_BUCKETS
; i
++) {
831 pool
->buckets
[i
].free_list
= ANV_FREE_LIST_EMPTY
;
832 pool
->buckets
[i
].block
.next
= 0;
833 pool
->buckets
[i
].block
.end
= 0;
835 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
841 anv_state_pool_finish(struct anv_state_pool
*pool
)
843 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
844 anv_state_table_finish(&pool
->table
);
845 anv_block_pool_finish(&pool
->block_pool
);
849 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool
*pool
,
850 struct anv_block_pool
*block_pool
,
855 struct anv_block_state block
, old
, new;
858 /* We don't always use anv_block_pool_alloc(), which would set *padding to
859 * zero for us. So if we have a pointer to padding, we must zero it out
860 * ourselves here, to make sure we always return some sensible value.
865 /* If our state is large, we don't need any sub-allocation from a block.
866 * Instead, we just grab whole (potentially large) blocks.
868 if (state_size
>= block_size
)
869 return anv_block_pool_alloc(block_pool
, state_size
, padding
);
872 block
.u64
= __sync_fetch_and_add(&pool
->block
.u64
, state_size
);
874 if (block
.next
< block
.end
) {
876 } else if (block
.next
== block
.end
) {
877 offset
= anv_block_pool_alloc(block_pool
, block_size
, padding
);
878 new.next
= offset
+ state_size
;
879 new.end
= offset
+ block_size
;
880 old
.u64
= __sync_lock_test_and_set(&pool
->block
.u64
, new.u64
);
881 if (old
.next
!= block
.next
)
882 futex_wake(&pool
->block
.end
, INT_MAX
);
885 futex_wait(&pool
->block
.end
, block
.end
, NULL
);
891 anv_state_pool_get_bucket(uint32_t size
)
893 unsigned size_log2
= ilog2_round_up(size
);
894 assert(size_log2
<= ANV_MAX_STATE_SIZE_LOG2
);
895 if (size_log2
< ANV_MIN_STATE_SIZE_LOG2
)
896 size_log2
= ANV_MIN_STATE_SIZE_LOG2
;
897 return size_log2
- ANV_MIN_STATE_SIZE_LOG2
;
901 anv_state_pool_get_bucket_size(uint32_t bucket
)
903 uint32_t size_log2
= bucket
+ ANV_MIN_STATE_SIZE_LOG2
;
904 return 1 << size_log2
;
907 /** Helper to push a chunk into the state table.
909 * It creates 'count' entries into the state table and update their sizes,
910 * offsets and maps, also pushing them as "free" states.
913 anv_state_pool_return_blocks(struct anv_state_pool
*pool
,
914 uint32_t chunk_offset
, uint32_t count
,
917 /* Disallow returning 0 chunks */
920 /* Make sure we always return chunks aligned to the block_size */
921 assert(chunk_offset
% block_size
== 0);
924 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &st_idx
, count
);
925 assert(result
== VK_SUCCESS
);
926 for (int i
= 0; i
< count
; i
++) {
927 /* update states that were added back to the state table */
928 struct anv_state
*state_i
= anv_state_table_get(&pool
->table
,
930 state_i
->alloc_size
= block_size
;
931 state_i
->offset
= chunk_offset
+ block_size
* i
;
932 state_i
->map
= anv_block_pool_map(&pool
->block_pool
, state_i
->offset
);
935 uint32_t block_bucket
= anv_state_pool_get_bucket(block_size
);
936 anv_free_list_push(&pool
->buckets
[block_bucket
].free_list
,
937 &pool
->table
, st_idx
, count
);
940 /** Returns a chunk of memory back to the state pool.
942 * Do a two-level split. If chunk_size is bigger than divisor
943 * (pool->block_size), we return as many divisor sized blocks as we can, from
944 * the end of the chunk.
946 * The remaining is then split into smaller blocks (starting at small_size if
947 * it is non-zero), with larger blocks always being taken from the end of the
951 anv_state_pool_return_chunk(struct anv_state_pool
*pool
,
952 uint32_t chunk_offset
, uint32_t chunk_size
,
955 uint32_t divisor
= pool
->block_size
;
956 uint32_t nblocks
= chunk_size
/ divisor
;
957 uint32_t rest
= chunk_size
- nblocks
* divisor
;
960 /* First return divisor aligned and sized chunks. We start returning
961 * larger blocks from the end fo the chunk, since they should already be
962 * aligned to divisor. Also anv_state_pool_return_blocks() only accepts
965 uint32_t offset
= chunk_offset
+ rest
;
966 anv_state_pool_return_blocks(pool
, offset
, nblocks
, divisor
);
972 if (small_size
> 0 && small_size
< divisor
)
973 divisor
= small_size
;
975 uint32_t min_size
= 1 << ANV_MIN_STATE_SIZE_LOG2
;
977 /* Just as before, return larger divisor aligned blocks from the end of the
980 while (chunk_size
> 0 && divisor
>= min_size
) {
981 nblocks
= chunk_size
/ divisor
;
982 rest
= chunk_size
- nblocks
* divisor
;
984 anv_state_pool_return_blocks(pool
, chunk_offset
+ rest
,
992 static struct anv_state
993 anv_state_pool_alloc_no_vg(struct anv_state_pool
*pool
,
994 uint32_t size
, uint32_t align
)
996 uint32_t bucket
= anv_state_pool_get_bucket(MAX2(size
, align
));
998 struct anv_state
*state
;
999 uint32_t alloc_size
= anv_state_pool_get_bucket_size(bucket
);
1002 /* Try free list first. */
1003 state
= anv_free_list_pop(&pool
->buckets
[bucket
].free_list
,
1006 assert(state
->offset
>= 0);
1010 /* Try to grab a chunk from some larger bucket and split it up */
1011 for (unsigned b
= bucket
+ 1; b
< ANV_STATE_BUCKETS
; b
++) {
1012 state
= anv_free_list_pop(&pool
->buckets
[b
].free_list
, &pool
->table
);
1014 unsigned chunk_size
= anv_state_pool_get_bucket_size(b
);
1015 int32_t chunk_offset
= state
->offset
;
1017 /* First lets update the state we got to its new size. offset and map
1020 state
->alloc_size
= alloc_size
;
1022 /* Now return the unused part of the chunk back to the pool as free
1025 * There are a couple of options as to what we do with it:
1027 * 1) We could fully split the chunk into state.alloc_size sized
1028 * pieces. However, this would mean that allocating a 16B
1029 * state could potentially split a 2MB chunk into 512K smaller
1030 * chunks. This would lead to unnecessary fragmentation.
1032 * 2) The classic "buddy allocator" method would have us split the
1033 * chunk in half and return one half. Then we would split the
1034 * remaining half in half and return one half, and repeat as
1035 * needed until we get down to the size we want. However, if
1036 * you are allocating a bunch of the same size state (which is
1037 * the common case), this means that every other allocation has
1038 * to go up a level and every fourth goes up two levels, etc.
1039 * This is not nearly as efficient as it could be if we did a
1040 * little more work up-front.
1042 * 3) Split the difference between (1) and (2) by doing a
1043 * two-level split. If it's bigger than some fixed block_size,
1044 * we split it into block_size sized chunks and return all but
1045 * one of them. Then we split what remains into
1046 * state.alloc_size sized chunks and return them.
1048 * We choose something close to option (3), which is implemented with
1049 * anv_state_pool_return_chunk(). That is done by returning the
1050 * remaining of the chunk, with alloc_size as a hint of the size that
1051 * we want the smaller chunk split into.
1053 anv_state_pool_return_chunk(pool
, chunk_offset
+ alloc_size
,
1054 chunk_size
- alloc_size
, alloc_size
);
1060 offset
= anv_fixed_size_state_pool_alloc_new(&pool
->buckets
[bucket
],
1065 /* Everytime we allocate a new state, add it to the state pool */
1067 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &idx
, 1);
1068 assert(result
== VK_SUCCESS
);
1070 state
= anv_state_table_get(&pool
->table
, idx
);
1071 state
->offset
= offset
;
1072 state
->alloc_size
= alloc_size
;
1073 state
->map
= anv_block_pool_map(&pool
->block_pool
, offset
);
1076 uint32_t return_offset
= offset
- padding
;
1077 anv_state_pool_return_chunk(pool
, return_offset
, padding
, 0);
1085 anv_state_pool_alloc(struct anv_state_pool
*pool
, uint32_t size
, uint32_t align
)
1088 return ANV_STATE_NULL
;
1090 struct anv_state state
= anv_state_pool_alloc_no_vg(pool
, size
, align
);
1091 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
.map
, size
));
1096 anv_state_pool_alloc_back(struct anv_state_pool
*pool
)
1098 struct anv_state
*state
;
1099 uint32_t alloc_size
= pool
->block_size
;
1101 state
= anv_free_list_pop(&pool
->back_alloc_free_list
, &pool
->table
);
1103 assert(state
->offset
< 0);
1108 offset
= anv_block_pool_alloc_back(&pool
->block_pool
,
1111 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &idx
, 1);
1112 assert(result
== VK_SUCCESS
);
1114 state
= anv_state_table_get(&pool
->table
, idx
);
1115 state
->offset
= offset
;
1116 state
->alloc_size
= alloc_size
;
1117 state
->map
= anv_block_pool_map(&pool
->block_pool
, state
->offset
);
1120 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
->map
, state
->alloc_size
));
1125 anv_state_pool_free_no_vg(struct anv_state_pool
*pool
, struct anv_state state
)
1127 assert(util_is_power_of_two_or_zero(state
.alloc_size
));
1128 unsigned bucket
= anv_state_pool_get_bucket(state
.alloc_size
);
1130 if (state
.offset
< 0) {
1131 assert(state
.alloc_size
== pool
->block_size
);
1132 anv_free_list_push(&pool
->back_alloc_free_list
,
1133 &pool
->table
, state
.idx
, 1);
1135 anv_free_list_push(&pool
->buckets
[bucket
].free_list
,
1136 &pool
->table
, state
.idx
, 1);
1141 anv_state_pool_free(struct anv_state_pool
*pool
, struct anv_state state
)
1143 if (state
.alloc_size
== 0)
1146 VG(VALGRIND_MEMPOOL_FREE(pool
, state
.map
));
1147 anv_state_pool_free_no_vg(pool
, state
);
1150 struct anv_state_stream_block
{
1151 struct anv_state block
;
1153 /* The next block */
1154 struct anv_state_stream_block
*next
;
1156 #ifdef HAVE_VALGRIND
1157 /* A pointer to the first user-allocated thing in this block. This is
1158 * what valgrind sees as the start of the block.
1164 /* The state stream allocator is a one-shot, single threaded allocator for
1165 * variable sized blocks. We use it for allocating dynamic state.
1168 anv_state_stream_init(struct anv_state_stream
*stream
,
1169 struct anv_state_pool
*state_pool
,
1170 uint32_t block_size
)
1172 stream
->state_pool
= state_pool
;
1173 stream
->block_size
= block_size
;
1175 stream
->block
= ANV_STATE_NULL
;
1177 stream
->block_list
= NULL
;
1179 /* Ensure that next + whatever > block_size. This way the first call to
1180 * state_stream_alloc fetches a new block.
1182 stream
->next
= block_size
;
1184 VG(VALGRIND_CREATE_MEMPOOL(stream
, 0, false));
1188 anv_state_stream_finish(struct anv_state_stream
*stream
)
1190 struct anv_state_stream_block
*next
= stream
->block_list
;
1191 while (next
!= NULL
) {
1192 struct anv_state_stream_block sb
= VG_NOACCESS_READ(next
);
1193 VG(VALGRIND_MEMPOOL_FREE(stream
, sb
._vg_ptr
));
1194 VG(VALGRIND_MAKE_MEM_UNDEFINED(next
, stream
->block_size
));
1195 anv_state_pool_free_no_vg(stream
->state_pool
, sb
.block
);
1199 VG(VALGRIND_DESTROY_MEMPOOL(stream
));
1203 anv_state_stream_alloc(struct anv_state_stream
*stream
,
1204 uint32_t size
, uint32_t alignment
)
1207 return ANV_STATE_NULL
;
1209 assert(alignment
<= PAGE_SIZE
);
1211 uint32_t offset
= align_u32(stream
->next
, alignment
);
1212 if (offset
+ size
> stream
->block
.alloc_size
) {
1213 uint32_t block_size
= stream
->block_size
;
1214 if (block_size
< size
)
1215 block_size
= round_to_power_of_two(size
);
1217 stream
->block
= anv_state_pool_alloc_no_vg(stream
->state_pool
,
1218 block_size
, PAGE_SIZE
);
1220 struct anv_state_stream_block
*sb
= stream
->block
.map
;
1221 VG_NOACCESS_WRITE(&sb
->block
, stream
->block
);
1222 VG_NOACCESS_WRITE(&sb
->next
, stream
->block_list
);
1223 stream
->block_list
= sb
;
1224 VG(VG_NOACCESS_WRITE(&sb
->_vg_ptr
, NULL
));
1226 VG(VALGRIND_MAKE_MEM_NOACCESS(stream
->block
.map
, stream
->block_size
));
1228 /* Reset back to the start plus space for the header */
1229 stream
->next
= sizeof(*sb
);
1231 offset
= align_u32(stream
->next
, alignment
);
1232 assert(offset
+ size
<= stream
->block
.alloc_size
);
1235 struct anv_state state
= stream
->block
;
1236 state
.offset
+= offset
;
1237 state
.alloc_size
= size
;
1238 state
.map
+= offset
;
1240 stream
->next
= offset
+ size
;
1242 #ifdef HAVE_VALGRIND
1243 struct anv_state_stream_block
*sb
= stream
->block_list
;
1244 void *vg_ptr
= VG_NOACCESS_READ(&sb
->_vg_ptr
);
1245 if (vg_ptr
== NULL
) {
1247 VG_NOACCESS_WRITE(&sb
->_vg_ptr
, vg_ptr
);
1248 VALGRIND_MEMPOOL_ALLOC(stream
, vg_ptr
, size
);
1250 void *state_end
= state
.map
+ state
.alloc_size
;
1251 /* This only updates the mempool. The newly allocated chunk is still
1252 * marked as NOACCESS. */
1253 VALGRIND_MEMPOOL_CHANGE(stream
, vg_ptr
, vg_ptr
, state_end
- vg_ptr
);
1254 /* Mark the newly allocated chunk as undefined */
1255 VALGRIND_MAKE_MEM_UNDEFINED(state
.map
, state
.alloc_size
);
1263 anv_bo_pool_init(struct anv_bo_pool
*pool
, struct anv_device
*device
)
1265 pool
->device
= device
;
1266 for (unsigned i
= 0; i
< ARRAY_SIZE(pool
->free_list
); i
++) {
1267 util_sparse_array_free_list_init(&pool
->free_list
[i
],
1268 &device
->bo_cache
.bo_map
, 0,
1269 offsetof(struct anv_bo
, free_index
));
1272 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
1276 anv_bo_pool_finish(struct anv_bo_pool
*pool
)
1278 for (unsigned i
= 0; i
< ARRAY_SIZE(pool
->free_list
); i
++) {
1281 util_sparse_array_free_list_pop_elem(&pool
->free_list
[i
]);
1285 /* anv_device_release_bo is going to "free" it */
1286 VG(VALGRIND_MALLOCLIKE_BLOCK(bo
->map
, bo
->size
, 0, 1));
1287 anv_device_release_bo(pool
->device
, bo
);
1291 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
1295 anv_bo_pool_alloc(struct anv_bo_pool
*pool
, uint32_t size
,
1296 struct anv_bo
**bo_out
)
1298 const unsigned size_log2
= size
< 4096 ? 12 : ilog2_round_up(size
);
1299 const unsigned pow2_size
= 1 << size_log2
;
1300 const unsigned bucket
= size_log2
- 12;
1301 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
1304 util_sparse_array_free_list_pop_elem(&pool
->free_list
[bucket
]);
1306 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1311 VkResult result
= anv_device_alloc_bo(pool
->device
,
1313 ANV_BO_ALLOC_MAPPED
|
1314 ANV_BO_ALLOC_SNOOPED
|
1315 ANV_BO_ALLOC_CAPTURE
,
1316 0 /* explicit_address */,
1318 if (result
!= VK_SUCCESS
)
1321 /* We want it to look like it came from this pool */
1322 VG(VALGRIND_FREELIKE_BLOCK(bo
->map
, 0));
1323 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1331 anv_bo_pool_free(struct anv_bo_pool
*pool
, struct anv_bo
*bo
)
1333 VG(VALGRIND_MEMPOOL_FREE(pool
, bo
->map
));
1335 assert(util_is_power_of_two_or_zero(bo
->size
));
1336 const unsigned size_log2
= ilog2_round_up(bo
->size
);
1337 const unsigned bucket
= size_log2
- 12;
1338 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
1340 assert(util_sparse_array_get(&pool
->device
->bo_cache
.bo_map
,
1341 bo
->gem_handle
) == bo
);
1342 util_sparse_array_free_list_push(&pool
->free_list
[bucket
],
1343 &bo
->gem_handle
, 1);
1349 anv_scratch_pool_init(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1351 memset(pool
, 0, sizeof(*pool
));
1355 anv_scratch_pool_finish(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1357 for (unsigned s
= 0; s
< MESA_SHADER_STAGES
; s
++) {
1358 for (unsigned i
= 0; i
< 16; i
++) {
1359 if (pool
->bos
[i
][s
] != NULL
)
1360 anv_device_release_bo(device
, pool
->bos
[i
][s
]);
1366 anv_scratch_pool_alloc(struct anv_device
*device
, struct anv_scratch_pool
*pool
,
1367 gl_shader_stage stage
, unsigned per_thread_scratch
)
1369 if (per_thread_scratch
== 0)
1372 unsigned scratch_size_log2
= ffs(per_thread_scratch
/ 2048);
1373 assert(scratch_size_log2
< 16);
1375 struct anv_bo
*bo
= p_atomic_read(&pool
->bos
[scratch_size_log2
][stage
]);
1380 const struct anv_physical_device
*physical_device
=
1381 &device
->instance
->physicalDevice
;
1382 const struct gen_device_info
*devinfo
= &physical_device
->info
;
1384 const unsigned subslices
= MAX2(physical_device
->subslice_total
, 1);
1386 unsigned scratch_ids_per_subslice
;
1387 if (devinfo
->gen
>= 11) {
1388 /* The MEDIA_VFE_STATE docs say:
1390 * "Starting with this configuration, the Maximum Number of
1391 * Threads must be set to (#EU * 8) for GPGPU dispatches.
1393 * Although there are only 7 threads per EU in the configuration,
1394 * the FFTID is calculated as if there are 8 threads per EU,
1395 * which in turn requires a larger amount of Scratch Space to be
1396 * allocated by the driver."
1398 scratch_ids_per_subslice
= 8 * 8;
1399 } else if (devinfo
->is_haswell
) {
1400 /* WaCSScratchSize:hsw
1402 * Haswell's scratch space address calculation appears to be sparse
1403 * rather than tightly packed. The Thread ID has bits indicating
1404 * which subslice, EU within a subslice, and thread within an EU it
1405 * is. There's a maximum of two slices and two subslices, so these
1406 * can be stored with a single bit. Even though there are only 10 EUs
1407 * per subslice, this is stored in 4 bits, so there's an effective
1408 * maximum value of 16 EUs. Similarly, although there are only 7
1409 * threads per EU, this is stored in a 3 bit number, giving an
1410 * effective maximum value of 8 threads per EU.
1412 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1413 * number of threads per subslice.
1415 scratch_ids_per_subslice
= 16 * 8;
1416 } else if (devinfo
->is_cherryview
) {
1417 /* Cherryview devices have either 6 or 8 EUs per subslice, and each EU
1418 * has 7 threads. The 6 EU devices appear to calculate thread IDs as if
1421 scratch_ids_per_subslice
= 8 * 7;
1423 scratch_ids_per_subslice
= devinfo
->max_cs_threads
;
1426 uint32_t max_threads
[] = {
1427 [MESA_SHADER_VERTEX
] = devinfo
->max_vs_threads
,
1428 [MESA_SHADER_TESS_CTRL
] = devinfo
->max_tcs_threads
,
1429 [MESA_SHADER_TESS_EVAL
] = devinfo
->max_tes_threads
,
1430 [MESA_SHADER_GEOMETRY
] = devinfo
->max_gs_threads
,
1431 [MESA_SHADER_FRAGMENT
] = devinfo
->max_wm_threads
,
1432 [MESA_SHADER_COMPUTE
] = scratch_ids_per_subslice
* subslices
,
1435 uint32_t size
= per_thread_scratch
* max_threads
[stage
];
1437 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1438 * are still relative to the general state base address. When we emit
1439 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1440 * to the maximum (1 page under 4GB). This allows us to just place the
1441 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1442 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1443 * However, in order to do so, we need to ensure that the kernel does not
1444 * place the scratch BO above the 32-bit boundary.
1446 * NOTE: Technically, it can't go "anywhere" because the top page is off
1447 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1448 * kernel allocates space using
1450 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1452 * so nothing will ever touch the top page.
1454 VkResult result
= anv_device_alloc_bo(device
, size
,
1455 ANV_BO_ALLOC_32BIT_ADDRESS
,
1456 0 /* explicit_address */,
1458 if (result
!= VK_SUCCESS
)
1459 return NULL
; /* TODO */
1461 struct anv_bo
*current_bo
=
1462 p_atomic_cmpxchg(&pool
->bos
[scratch_size_log2
][stage
], NULL
, bo
);
1464 anv_device_release_bo(device
, bo
);
1472 anv_bo_cache_init(struct anv_bo_cache
*cache
)
1474 util_sparse_array_init(&cache
->bo_map
, sizeof(struct anv_bo
), 1024);
1476 if (pthread_mutex_init(&cache
->mutex
, NULL
)) {
1477 util_sparse_array_finish(&cache
->bo_map
);
1478 return vk_errorf(NULL
, NULL
, VK_ERROR_OUT_OF_HOST_MEMORY
,
1479 "pthread_mutex_init failed: %m");
1486 anv_bo_cache_finish(struct anv_bo_cache
*cache
)
1488 util_sparse_array_finish(&cache
->bo_map
);
1489 pthread_mutex_destroy(&cache
->mutex
);
1492 #define ANV_BO_CACHE_SUPPORTED_FLAGS \
1493 (EXEC_OBJECT_WRITE | \
1494 EXEC_OBJECT_ASYNC | \
1495 EXEC_OBJECT_SUPPORTS_48B_ADDRESS | \
1496 EXEC_OBJECT_PINNED | \
1497 EXEC_OBJECT_CAPTURE)
1500 anv_bo_alloc_flags_to_bo_flags(struct anv_device
*device
,
1501 enum anv_bo_alloc_flags alloc_flags
)
1503 struct anv_physical_device
*pdevice
= &device
->instance
->physicalDevice
;
1505 uint64_t bo_flags
= 0;
1506 if (!(alloc_flags
& ANV_BO_ALLOC_32BIT_ADDRESS
) &&
1507 pdevice
->supports_48bit_addresses
)
1508 bo_flags
|= EXEC_OBJECT_SUPPORTS_48B_ADDRESS
;
1510 if ((alloc_flags
& ANV_BO_ALLOC_CAPTURE
) && pdevice
->has_exec_capture
)
1511 bo_flags
|= EXEC_OBJECT_CAPTURE
;
1513 if (alloc_flags
& ANV_BO_ALLOC_IMPLICIT_WRITE
) {
1514 assert(alloc_flags
& ANV_BO_ALLOC_IMPLICIT_SYNC
);
1515 bo_flags
|= EXEC_OBJECT_WRITE
;
1518 if (!(alloc_flags
& ANV_BO_ALLOC_IMPLICIT_SYNC
) && pdevice
->has_exec_async
)
1519 bo_flags
|= EXEC_OBJECT_ASYNC
;
1521 if (pdevice
->use_softpin
)
1522 bo_flags
|= EXEC_OBJECT_PINNED
;
1528 anv_device_alloc_bo(struct anv_device
*device
,
1530 enum anv_bo_alloc_flags alloc_flags
,
1531 uint64_t explicit_address
,
1532 struct anv_bo
**bo_out
)
1534 const uint32_t bo_flags
=
1535 anv_bo_alloc_flags_to_bo_flags(device
, alloc_flags
);
1536 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1538 /* The kernel is going to give us whole pages anyway */
1539 size
= align_u64(size
, 4096);
1541 uint32_t gem_handle
= anv_gem_create(device
, size
);
1542 if (gem_handle
== 0)
1543 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY
);
1545 struct anv_bo new_bo
= {
1546 .gem_handle
= gem_handle
,
1551 .is_external
= (alloc_flags
& ANV_BO_ALLOC_EXTERNAL
),
1552 .has_client_visible_address
=
1553 (alloc_flags
& ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS
) != 0,
1556 if (alloc_flags
& ANV_BO_ALLOC_MAPPED
) {
1557 new_bo
.map
= anv_gem_mmap(device
, new_bo
.gem_handle
, 0, size
, 0);
1558 if (new_bo
.map
== MAP_FAILED
) {
1559 anv_gem_close(device
, new_bo
.gem_handle
);
1560 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1564 if (alloc_flags
& ANV_BO_ALLOC_SNOOPED
) {
1565 assert(alloc_flags
& ANV_BO_ALLOC_MAPPED
);
1566 /* We don't want to change these defaults if it's going to be shared
1567 * with another process.
1569 assert(!(alloc_flags
& ANV_BO_ALLOC_EXTERNAL
));
1571 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
1572 * I915_CACHING_NONE on non-LLC platforms. For many internal state
1573 * objects, we'd rather take the snooping overhead than risk forgetting
1574 * a CLFLUSH somewhere. Userptr objects are always created as
1575 * I915_CACHING_CACHED, which on non-LLC means snooped so there's no
1576 * need to do this there.
1578 if (!device
->info
.has_llc
) {
1579 anv_gem_set_caching(device
, new_bo
.gem_handle
,
1580 I915_CACHING_CACHED
);
1584 if (alloc_flags
& ANV_BO_ALLOC_FIXED_ADDRESS
) {
1585 new_bo
.has_fixed_address
= true;
1586 new_bo
.offset
= explicit_address
;
1588 if (!anv_vma_alloc(device
, &new_bo
, explicit_address
)) {
1590 anv_gem_munmap(new_bo
.map
, size
);
1591 anv_gem_close(device
, new_bo
.gem_handle
);
1592 return vk_errorf(device
->instance
, NULL
,
1593 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1594 "failed to allocate virtual address for BO");
1598 assert(new_bo
.gem_handle
);
1600 /* If we just got this gem_handle from anv_bo_init_new then we know no one
1601 * else is touching this BO at the moment so we don't need to lock here.
1603 struct anv_bo
*bo
= anv_device_lookup_bo(device
, new_bo
.gem_handle
);
1612 anv_device_import_bo_from_host_ptr(struct anv_device
*device
,
1613 void *host_ptr
, uint32_t size
,
1614 enum anv_bo_alloc_flags alloc_flags
,
1615 uint64_t client_address
,
1616 struct anv_bo
**bo_out
)
1618 assert(!(alloc_flags
& (ANV_BO_ALLOC_MAPPED
|
1619 ANV_BO_ALLOC_SNOOPED
|
1620 ANV_BO_ALLOC_FIXED_ADDRESS
)));
1622 struct anv_bo_cache
*cache
= &device
->bo_cache
;
1623 const uint32_t bo_flags
=
1624 anv_bo_alloc_flags_to_bo_flags(device
, alloc_flags
);
1625 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1627 uint32_t gem_handle
= anv_gem_userptr(device
, host_ptr
, size
);
1629 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE
);
1631 pthread_mutex_lock(&cache
->mutex
);
1633 struct anv_bo
*bo
= anv_device_lookup_bo(device
, gem_handle
);
1634 if (bo
->refcount
> 0) {
1635 /* VK_EXT_external_memory_host doesn't require handling importing the
1636 * same pointer twice at the same time, but we don't get in the way. If
1637 * kernel gives us the same gem_handle, only succeed if the flags match.
1639 assert(bo
->gem_handle
== gem_handle
);
1640 if (bo_flags
!= bo
->flags
) {
1641 pthread_mutex_unlock(&cache
->mutex
);
1642 return vk_errorf(device
->instance
, NULL
,
1643 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1644 "same host pointer imported two different ways");
1647 if (bo
->has_client_visible_address
!=
1648 ((alloc_flags
& ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS
) != 0)) {
1649 pthread_mutex_unlock(&cache
->mutex
);
1650 return vk_errorf(device
->instance
, NULL
,
1651 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1652 "The same BO was imported with and without buffer "
1656 if (client_address
&& client_address
!= gen_48b_address(bo
->offset
)) {
1657 pthread_mutex_unlock(&cache
->mutex
);
1658 return vk_errorf(device
->instance
, NULL
,
1659 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1660 "The same BO was imported at two different "
1664 __sync_fetch_and_add(&bo
->refcount
, 1);
1666 struct anv_bo new_bo
= {
1667 .gem_handle
= gem_handle
,
1673 .is_external
= true,
1674 .from_host_ptr
= true,
1675 .has_client_visible_address
=
1676 (alloc_flags
& ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS
) != 0,
1679 assert(client_address
== gen_48b_address(client_address
));
1680 if (!anv_vma_alloc(device
, &new_bo
, client_address
)) {
1681 anv_gem_close(device
, new_bo
.gem_handle
);
1682 pthread_mutex_unlock(&cache
->mutex
);
1683 return vk_errorf(device
->instance
, NULL
,
1684 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1685 "failed to allocate virtual address for BO");
1691 pthread_mutex_unlock(&cache
->mutex
);
1698 anv_device_import_bo(struct anv_device
*device
,
1700 enum anv_bo_alloc_flags alloc_flags
,
1701 uint64_t client_address
,
1702 struct anv_bo
**bo_out
)
1704 assert(!(alloc_flags
& (ANV_BO_ALLOC_MAPPED
|
1705 ANV_BO_ALLOC_SNOOPED
|
1706 ANV_BO_ALLOC_FIXED_ADDRESS
)));
1708 struct anv_bo_cache
*cache
= &device
->bo_cache
;
1709 const uint32_t bo_flags
=
1710 anv_bo_alloc_flags_to_bo_flags(device
, alloc_flags
);
1711 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1713 pthread_mutex_lock(&cache
->mutex
);
1715 uint32_t gem_handle
= anv_gem_fd_to_handle(device
, fd
);
1717 pthread_mutex_unlock(&cache
->mutex
);
1718 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE
);
1721 struct anv_bo
*bo
= anv_device_lookup_bo(device
, gem_handle
);
1722 if (bo
->refcount
> 0) {
1723 /* We have to be careful how we combine flags so that it makes sense.
1724 * Really, though, if we get to this case and it actually matters, the
1725 * client has imported a BO twice in different ways and they get what
1728 uint64_t new_flags
= 0;
1729 new_flags
|= (bo
->flags
| bo_flags
) & EXEC_OBJECT_WRITE
;
1730 new_flags
|= (bo
->flags
& bo_flags
) & EXEC_OBJECT_ASYNC
;
1731 new_flags
|= (bo
->flags
& bo_flags
) & EXEC_OBJECT_SUPPORTS_48B_ADDRESS
;
1732 new_flags
|= (bo
->flags
| bo_flags
) & EXEC_OBJECT_PINNED
;
1733 new_flags
|= (bo
->flags
| bo_flags
) & EXEC_OBJECT_CAPTURE
;
1735 /* It's theoretically possible for a BO to get imported such that it's
1736 * both pinned and not pinned. The only way this can happen is if it
1737 * gets imported as both a semaphore and a memory object and that would
1738 * be an application error. Just fail out in that case.
1740 if ((bo
->flags
& EXEC_OBJECT_PINNED
) !=
1741 (bo_flags
& EXEC_OBJECT_PINNED
)) {
1742 pthread_mutex_unlock(&cache
->mutex
);
1743 return vk_errorf(device
->instance
, NULL
,
1744 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1745 "The same BO was imported two different ways");
1748 /* It's also theoretically possible that someone could export a BO from
1749 * one heap and import it into another or to import the same BO into two
1750 * different heaps. If this happens, we could potentially end up both
1751 * allowing and disallowing 48-bit addresses. There's not much we can
1752 * do about it if we're pinning so we just throw an error and hope no
1753 * app is actually that stupid.
1755 if ((new_flags
& EXEC_OBJECT_PINNED
) &&
1756 (bo
->flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
) !=
1757 (bo_flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
)) {
1758 pthread_mutex_unlock(&cache
->mutex
);
1759 return vk_errorf(device
->instance
, NULL
,
1760 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1761 "The same BO was imported on two different heaps");
1764 if (bo
->has_client_visible_address
!=
1765 ((alloc_flags
& ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS
) != 0)) {
1766 pthread_mutex_unlock(&cache
->mutex
);
1767 return vk_errorf(device
->instance
, NULL
,
1768 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1769 "The same BO was imported with and without buffer "
1773 if (client_address
&& client_address
!= gen_48b_address(bo
->offset
)) {
1774 pthread_mutex_unlock(&cache
->mutex
);
1775 return vk_errorf(device
->instance
, NULL
,
1776 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1777 "The same BO was imported at two different "
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 .gem_handle
= gem_handle
,
1798 .is_external
= true,
1799 .has_client_visible_address
=
1800 (alloc_flags
& ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS
) != 0,
1803 assert(client_address
== gen_48b_address(client_address
));
1804 if (!anv_vma_alloc(device
, &new_bo
, client_address
)) {
1805 anv_gem_close(device
, new_bo
.gem_handle
);
1806 pthread_mutex_unlock(&cache
->mutex
);
1807 return vk_errorf(device
->instance
, NULL
,
1808 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1809 "failed to allocate virtual address for BO");
1815 pthread_mutex_unlock(&cache
->mutex
);
1822 anv_device_export_bo(struct anv_device
*device
,
1823 struct anv_bo
*bo
, int *fd_out
)
1825 assert(anv_device_lookup_bo(device
, bo
->gem_handle
) == bo
);
1827 /* This BO must have been flagged external in order for us to be able
1828 * to export it. This is done based on external options passed into
1829 * anv_AllocateMemory.
1831 assert(bo
->is_external
);
1833 int fd
= anv_gem_handle_to_fd(device
, bo
->gem_handle
);
1835 return vk_error(VK_ERROR_TOO_MANY_OBJECTS
);
1843 atomic_dec_not_one(uint32_t *counter
)
1852 old
= __sync_val_compare_and_swap(counter
, val
, val
- 1);
1861 anv_device_release_bo(struct anv_device
*device
,
1864 struct anv_bo_cache
*cache
= &device
->bo_cache
;
1865 assert(anv_device_lookup_bo(device
, bo
->gem_handle
) == bo
);
1867 /* Try to decrement the counter but don't go below one. If this succeeds
1868 * then the refcount has been decremented and we are not the last
1871 if (atomic_dec_not_one(&bo
->refcount
))
1874 pthread_mutex_lock(&cache
->mutex
);
1876 /* We are probably the last reference since our attempt to decrement above
1877 * failed. However, we can't actually know until we are inside the mutex.
1878 * Otherwise, someone could import the BO between the decrement and our
1881 if (unlikely(__sync_sub_and_fetch(&bo
->refcount
, 1) > 0)) {
1882 /* Turns out we're not the last reference. Unlock and bail. */
1883 pthread_mutex_unlock(&cache
->mutex
);
1886 assert(bo
->refcount
== 0);
1888 if (bo
->map
&& !bo
->from_host_ptr
)
1889 anv_gem_munmap(bo
->map
, bo
->size
);
1891 if (!bo
->has_fixed_address
)
1892 anv_vma_free(device
, bo
);
1894 uint32_t gem_handle
= bo
->gem_handle
;
1896 /* Memset the BO just in case. The refcount being zero should be enough to
1897 * prevent someone from assuming the data is valid but it's safer to just
1898 * stomp to zero just in case. We explicitly do this *before* we close the
1899 * GEM handle to ensure that if anyone allocates something and gets the
1900 * same GEM handle, the memset has already happen and won't stomp all over
1901 * any data they may write in this BO.
1903 memset(bo
, 0, sizeof(*bo
));
1905 anv_gem_close(device
, gem_handle
);
1907 /* Don't unlock until we've actually closed the BO. The whole point of
1908 * the BO cache is to ensure that we correctly handle races with creating
1909 * and releasing GEM handles and we don't want to let someone import the BO
1910 * again between mutex unlock and closing the GEM handle.
1912 pthread_mutex_unlock(&cache
->mutex
);