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
28 #include <linux/memfd.h>
31 #include "anv_private.h"
33 #include "util/hash_table.h"
34 #include "util/simple_mtx.h"
37 #define VG_NOACCESS_READ(__ptr) ({ \
38 VALGRIND_MAKE_MEM_DEFINED((__ptr), sizeof(*(__ptr))); \
39 __typeof(*(__ptr)) __val = *(__ptr); \
40 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr)));\
43 #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
44 VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
46 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
49 #define VG_NOACCESS_READ(__ptr) (*(__ptr))
50 #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
55 * - Lock free (except when resizing underlying bos)
57 * - Constant time allocation with typically only one atomic
59 * - Multiple allocation sizes without fragmentation
61 * - Can grow while keeping addresses and offset of contents stable
63 * - All allocations within one bo so we can point one of the
64 * STATE_BASE_ADDRESS pointers at it.
66 * The overall design is a two-level allocator: top level is a fixed size, big
67 * block (8k) allocator, which operates out of a bo. Allocation is done by
68 * either pulling a block from the free list or growing the used range of the
69 * bo. Growing the range may run out of space in the bo which we then need to
70 * grow. Growing the bo is tricky in a multi-threaded, lockless environment:
71 * we need to keep all pointers and contents in the old map valid. GEM bos in
72 * general can't grow, but we use a trick: we create a memfd and use ftruncate
73 * to grow it as necessary. We mmap the new size and then create a gem bo for
74 * it using the new gem userptr ioctl. Without heavy-handed locking around
75 * our allocation fast-path, there isn't really a way to munmap the old mmap,
76 * so we just keep it around until garbage collection time. While the block
77 * allocator is lockless for normal operations, we block other threads trying
78 * to allocate while we're growing the map. It sholdn't happen often, and
79 * growing is fast anyway.
81 * At the next level we can use various sub-allocators. The state pool is a
82 * pool of smaller, fixed size objects, which operates much like the block
83 * pool. It uses a free list for freeing objects, but when it runs out of
84 * space it just allocates a new block from the block pool. This allocator is
85 * intended for longer lived state objects such as SURFACE_STATE and most
86 * other persistent state objects in the API. We may need to track more info
87 * with these object and a pointer back to the CPU object (eg VkImage). In
88 * those cases we just allocate a slightly bigger object and put the extra
89 * state after the GPU state object.
91 * The state stream allocator works similar to how the i965 DRI driver streams
92 * all its state. Even with Vulkan, we need to emit transient state (whether
93 * surface state base or dynamic state base), and for that we can just get a
94 * block and fill it up. These cases are local to a command buffer and the
95 * sub-allocator need not be thread safe. The streaming allocator gets a new
96 * block when it runs out of space and chains them together so they can be
100 /* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
101 * We use it to indicate the free list is empty. */
102 #define EMPTY UINT32_MAX
104 #define PAGE_SIZE 4096
106 struct anv_mmap_cleanup
{
112 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
114 #ifndef HAVE_MEMFD_CREATE
116 memfd_create(const char *name
, unsigned int flags
)
118 return syscall(SYS_memfd_create
, name
, flags
);
122 static inline uint32_t
123 ilog2_round_up(uint32_t value
)
126 return 32 - __builtin_clz(value
- 1);
129 static inline uint32_t
130 round_to_power_of_two(uint32_t value
)
132 return 1 << ilog2_round_up(value
);
135 struct anv_state_table_cleanup
{
140 #define ANV_STATE_TABLE_CLEANUP_INIT ((struct anv_state_table_cleanup){0})
141 #define ANV_STATE_ENTRY_SIZE (sizeof(struct anv_free_entry))
144 anv_state_table_expand_range(struct anv_state_table
*table
, uint32_t size
);
147 anv_state_table_init(struct anv_state_table
*table
,
148 struct anv_device
*device
,
149 uint32_t initial_entries
)
153 table
->device
= device
;
155 table
->fd
= memfd_create("state table", MFD_CLOEXEC
);
157 return vk_error(VK_ERROR_INITIALIZATION_FAILED
);
159 /* Just make it 2GB up-front. The Linux kernel won't actually back it
160 * with pages until we either map and fault on one of them or we use
161 * userptr and send a chunk of it off to the GPU.
163 if (ftruncate(table
->fd
, BLOCK_POOL_MEMFD_SIZE
) == -1) {
164 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
168 if (!u_vector_init(&table
->mmap_cleanups
,
169 round_to_power_of_two(sizeof(struct anv_state_table_cleanup
)),
171 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
175 table
->state
.next
= 0;
176 table
->state
.end
= 0;
179 uint32_t initial_size
= initial_entries
* ANV_STATE_ENTRY_SIZE
;
180 result
= anv_state_table_expand_range(table
, initial_size
);
181 if (result
!= VK_SUCCESS
)
182 goto fail_mmap_cleanups
;
187 u_vector_finish(&table
->mmap_cleanups
);
195 anv_state_table_expand_range(struct anv_state_table
*table
, uint32_t size
)
198 struct anv_mmap_cleanup
*cleanup
;
200 /* Assert that we only ever grow the pool */
201 assert(size
>= table
->state
.end
);
203 /* Make sure that we don't go outside the bounds of the memfd */
204 if (size
> BLOCK_POOL_MEMFD_SIZE
)
205 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
207 cleanup
= u_vector_add(&table
->mmap_cleanups
);
209 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
211 *cleanup
= ANV_MMAP_CLEANUP_INIT
;
213 /* Just leak the old map until we destroy the pool. We can't munmap it
214 * without races or imposing locking on the block allocate fast path. On
215 * the whole the leaked maps adds up to less than the size of the
216 * current map. MAP_POPULATE seems like the right thing to do, but we
217 * should try to get some numbers.
219 map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
220 MAP_SHARED
| MAP_POPULATE
, table
->fd
, 0);
221 if (map
== MAP_FAILED
) {
222 return vk_errorf(table
->device
->instance
, table
->device
,
223 VK_ERROR_OUT_OF_HOST_MEMORY
, "mmap failed: %m");
227 cleanup
->size
= size
;
236 anv_state_table_grow(struct anv_state_table
*table
)
238 VkResult result
= VK_SUCCESS
;
240 uint32_t used
= align_u32(table
->state
.next
* ANV_STATE_ENTRY_SIZE
,
242 uint32_t old_size
= table
->size
;
244 /* The block pool is always initialized to a nonzero size and this function
245 * is always called after initialization.
247 assert(old_size
> 0);
249 uint32_t required
= MAX2(used
, old_size
);
250 if (used
* 2 <= required
) {
251 /* If we're in this case then this isn't the firsta allocation and we
252 * already have enough space on both sides to hold double what we
253 * have allocated. There's nothing for us to do.
258 uint32_t size
= old_size
* 2;
259 while (size
< required
)
262 assert(size
> table
->size
);
264 result
= anv_state_table_expand_range(table
, size
);
271 anv_state_table_finish(struct anv_state_table
*table
)
273 struct anv_state_table_cleanup
*cleanup
;
275 u_vector_foreach(cleanup
, &table
->mmap_cleanups
) {
277 munmap(cleanup
->map
, cleanup
->size
);
280 u_vector_finish(&table
->mmap_cleanups
);
286 anv_state_table_add(struct anv_state_table
*table
, uint32_t *idx
,
289 struct anv_block_state state
, old
, new;
295 state
.u64
= __sync_fetch_and_add(&table
->state
.u64
, count
);
296 if (state
.next
+ count
<= state
.end
) {
298 struct anv_free_entry
*entry
= &table
->map
[state
.next
];
299 for (int i
= 0; i
< count
; i
++) {
300 entry
[i
].state
.idx
= state
.next
+ i
;
304 } else if (state
.next
<= state
.end
) {
305 /* We allocated the first block outside the pool so we have to grow
306 * the pool. pool_state->next acts a mutex: threads who try to
307 * allocate now will get block indexes above the current limit and
308 * hit futex_wait below.
310 new.next
= state
.next
+ count
;
312 result
= anv_state_table_grow(table
);
313 if (result
!= VK_SUCCESS
)
315 new.end
= table
->size
/ ANV_STATE_ENTRY_SIZE
;
316 } while (new.end
< new.next
);
318 old
.u64
= __sync_lock_test_and_set(&table
->state
.u64
, new.u64
);
319 if (old
.next
!= state
.next
)
320 futex_wake(&table
->state
.end
, INT_MAX
);
322 futex_wait(&table
->state
.end
, state
.end
, NULL
);
329 anv_free_list_push(union anv_free_list
*list
,
330 struct anv_state_table
*table
,
331 uint32_t first
, uint32_t count
)
333 union anv_free_list current
, old
, new;
334 uint32_t last
= first
;
336 for (uint32_t i
= 1; i
< count
; i
++, last
++)
337 table
->map
[last
].next
= last
+ 1;
342 table
->map
[last
].next
= current
.offset
;
344 new.count
= current
.count
+ 1;
345 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
346 } while (old
.u64
!= current
.u64
);
350 anv_free_list_pop(union anv_free_list
*list
,
351 struct anv_state_table
*table
)
353 union anv_free_list current
, new, old
;
355 current
.u64
= list
->u64
;
356 while (current
.offset
!= EMPTY
) {
357 __sync_synchronize();
358 new.offset
= table
->map
[current
.offset
].next
;
359 new.count
= current
.count
+ 1;
360 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
361 if (old
.u64
== current
.u64
) {
362 struct anv_free_entry
*entry
= &table
->map
[current
.offset
];
363 return &entry
->state
;
371 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
372 * means that the bottom 12 bits should all be zero.
374 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
375 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
376 #define PFL_PACK(ptr, count) ({ \
377 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
381 anv_ptr_free_list_pop(void **list
, void **elem
)
383 void *current
= *list
;
384 while (PFL_PTR(current
) != NULL
) {
385 void **next_ptr
= PFL_PTR(current
);
386 void *new_ptr
= VG_NOACCESS_READ(next_ptr
);
387 unsigned new_count
= PFL_COUNT(current
) + 1;
388 void *new = PFL_PACK(new_ptr
, new_count
);
389 void *old
= __sync_val_compare_and_swap(list
, current
, new);
390 if (old
== current
) {
391 *elem
= PFL_PTR(current
);
401 anv_ptr_free_list_push(void **list
, void *elem
)
404 void **next_ptr
= elem
;
406 /* The pointer-based free list requires that the pointer be
407 * page-aligned. This is because we use the bottom 12 bits of the
408 * pointer to store a counter to solve the ABA concurrency problem.
410 assert(((uintptr_t)elem
& 0xfff) == 0);
415 VG_NOACCESS_WRITE(next_ptr
, PFL_PTR(current
));
416 unsigned new_count
= PFL_COUNT(current
) + 1;
417 void *new = PFL_PACK(elem
, new_count
);
418 old
= __sync_val_compare_and_swap(list
, current
, new);
419 } while (old
!= current
);
423 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
424 uint32_t center_bo_offset
, uint32_t size
);
427 anv_block_pool_init(struct anv_block_pool
*pool
,
428 struct anv_device
*device
,
429 uint64_t start_address
,
430 uint32_t initial_size
,
435 pool
->device
= device
;
436 pool
->bo_flags
= bo_flags
;
439 pool
->center_bo_offset
= 0;
440 pool
->start_address
= gen_canonical_address(start_address
);
443 /* This pointer will always point to the first BO in the list */
444 pool
->bo
= &pool
->bos
[0];
446 anv_bo_init(pool
->bo
, 0, 0);
448 if (!(pool
->bo_flags
& EXEC_OBJECT_PINNED
)) {
449 pool
->fd
= memfd_create("block pool", MFD_CLOEXEC
);
451 return vk_error(VK_ERROR_INITIALIZATION_FAILED
);
453 /* Just make it 2GB up-front. The Linux kernel won't actually back it
454 * with pages until we either map and fault on one of them or we use
455 * userptr and send a chunk of it off to the GPU.
457 if (ftruncate(pool
->fd
, BLOCK_POOL_MEMFD_SIZE
) == -1) {
458 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
465 if (!u_vector_init(&pool
->mmap_cleanups
,
466 round_to_power_of_two(sizeof(struct anv_mmap_cleanup
)),
468 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
472 pool
->state
.next
= 0;
474 pool
->back_state
.next
= 0;
475 pool
->back_state
.end
= 0;
477 result
= anv_block_pool_expand_range(pool
, 0, initial_size
);
478 if (result
!= VK_SUCCESS
)
479 goto fail_mmap_cleanups
;
484 u_vector_finish(&pool
->mmap_cleanups
);
486 if (!(pool
->bo_flags
& EXEC_OBJECT_PINNED
))
493 anv_block_pool_finish(struct anv_block_pool
*pool
)
495 struct anv_mmap_cleanup
*cleanup
;
497 u_vector_foreach(cleanup
, &pool
->mmap_cleanups
) {
499 munmap(cleanup
->map
, cleanup
->size
);
500 if (cleanup
->gem_handle
)
501 anv_gem_close(pool
->device
, cleanup
->gem_handle
);
504 u_vector_finish(&pool
->mmap_cleanups
);
505 if (!(pool
->bo_flags
& EXEC_OBJECT_PINNED
))
510 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
511 uint32_t center_bo_offset
, uint32_t size
)
515 struct anv_mmap_cleanup
*cleanup
;
516 const bool use_softpin
= !!(pool
->bo_flags
& EXEC_OBJECT_PINNED
);
518 /* Assert that we only ever grow the pool */
519 assert(center_bo_offset
>= pool
->back_state
.end
);
520 assert(size
- center_bo_offset
>= pool
->state
.end
);
522 /* Assert that we don't go outside the bounds of the memfd */
523 assert(center_bo_offset
<= BLOCK_POOL_MEMFD_CENTER
);
524 assert(use_softpin
||
525 size
- center_bo_offset
<=
526 BLOCK_POOL_MEMFD_SIZE
- BLOCK_POOL_MEMFD_CENTER
);
528 cleanup
= u_vector_add(&pool
->mmap_cleanups
);
530 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
532 *cleanup
= ANV_MMAP_CLEANUP_INIT
;
534 uint32_t newbo_size
= size
- pool
->size
;
536 gem_handle
= anv_gem_create(pool
->device
, newbo_size
);
537 map
= anv_gem_mmap(pool
->device
, gem_handle
, 0, newbo_size
, 0);
538 if (map
== MAP_FAILED
)
539 return vk_errorf(pool
->device
->instance
, pool
->device
,
540 VK_ERROR_MEMORY_MAP_FAILED
, "gem mmap failed: %m");
541 assert(center_bo_offset
== 0);
543 /* Just leak the old map until we destroy the pool. We can't munmap it
544 * without races or imposing locking on the block allocate fast path. On
545 * the whole the leaked maps adds up to less than the size of the
546 * current map. MAP_POPULATE seems like the right thing to do, but we
547 * should try to get some numbers.
549 map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
550 MAP_SHARED
| MAP_POPULATE
, pool
->fd
,
551 BLOCK_POOL_MEMFD_CENTER
- center_bo_offset
);
552 if (map
== MAP_FAILED
)
553 return vk_errorf(pool
->device
->instance
, pool
->device
,
554 VK_ERROR_MEMORY_MAP_FAILED
, "mmap failed: %m");
556 /* Now that we mapped the new memory, we can write the new
557 * center_bo_offset back into pool and update pool->map. */
558 pool
->center_bo_offset
= center_bo_offset
;
559 pool
->map
= map
+ center_bo_offset
;
560 gem_handle
= anv_gem_userptr(pool
->device
, map
, size
);
561 if (gem_handle
== 0) {
563 return vk_errorf(pool
->device
->instance
, pool
->device
,
564 VK_ERROR_TOO_MANY_OBJECTS
, "userptr failed: %m");
569 cleanup
->size
= use_softpin
? newbo_size
: size
;
570 cleanup
->gem_handle
= gem_handle
;
572 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
573 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
574 * always created as I915_CACHING_CACHED, which on non-LLC means
577 * On platforms that support softpin, we are not going to use userptr
578 * anymore, but we still want to rely on the snooped states. So make sure
579 * everything is set to I915_CACHING_CACHED.
581 if (!pool
->device
->info
.has_llc
)
582 anv_gem_set_caching(pool
->device
, gem_handle
, I915_CACHING_CACHED
);
584 /* For block pool BOs we have to be a bit careful about where we place them
585 * in the GTT. There are two documented workarounds for state base address
586 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
587 * which state that those two base addresses do not support 48-bit
588 * addresses and need to be placed in the bottom 32-bit range.
589 * Unfortunately, this is not quite accurate.
591 * The real problem is that we always set the size of our state pools in
592 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
593 * likely significantly smaller. We do this because we do not no at the
594 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
595 * the pool during command buffer building so we don't actually have a
596 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
597 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
598 * as being out of bounds and returns zero. For dynamic state, this
599 * usually just leads to rendering corruptions, but shaders that are all
600 * zero hang the GPU immediately.
602 * The easiest solution to do is exactly what the bogus workarounds say to
603 * do: restrict these buffers to 32-bit addresses. We could also pin the
604 * BO to some particular location of our choosing, but that's significantly
605 * more work than just not setting a flag. So, we explicitly DO NOT set
606 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
613 assert(pool
->nbos
< ANV_MAX_BLOCK_POOL_BOS
);
616 /* With softpin, we add a new BO to the pool, and set its offset to right
617 * where the previous BO ends (the end of the pool).
619 bo
= &pool
->bos
[pool
->nbos
++];
620 bo_size
= newbo_size
;
621 bo_offset
= pool
->start_address
+ pool
->size
;
623 /* Without softpin, we just need one BO, and we already have a pointer to
624 * it. Simply "allocate" it from our array if we didn't do it before.
625 * The offset doesn't matter since we are not pinning the BO anyway.
634 anv_bo_init(bo
, gem_handle
, bo_size
);
635 bo
->offset
= bo_offset
;
636 bo
->flags
= pool
->bo_flags
;
643 static struct anv_bo
*
644 anv_block_pool_get_bo(struct anv_block_pool
*pool
, int32_t *offset
)
646 struct anv_bo
*bo
, *bo_found
= NULL
;
647 int32_t cur_offset
= 0;
651 if (!(pool
->bo_flags
& EXEC_OBJECT_PINNED
))
654 anv_block_pool_foreach_bo(bo
, pool
) {
655 if (*offset
< cur_offset
+ bo
->size
) {
659 cur_offset
+= bo
->size
;
662 assert(bo_found
!= NULL
);
663 *offset
-= cur_offset
;
668 /** Returns current memory map of the block pool.
670 * The returned pointer points to the map for the memory at the specified
671 * offset. The offset parameter is relative to the "center" of the block pool
672 * rather than the start of the block pool BO map.
675 anv_block_pool_map(struct anv_block_pool
*pool
, int32_t offset
)
677 if (pool
->bo_flags
& EXEC_OBJECT_PINNED
) {
678 struct anv_bo
*bo
= anv_block_pool_get_bo(pool
, &offset
);
679 return bo
->map
+ offset
;
681 return pool
->map
+ offset
;
685 /** Grows and re-centers the block pool.
687 * We grow the block pool in one or both directions in such a way that the
688 * following conditions are met:
690 * 1) The size of the entire pool is always a power of two.
692 * 2) The pool only grows on both ends. Neither end can get
695 * 3) At the end of the allocation, we have about twice as much space
696 * allocated for each end as we have used. This way the pool doesn't
697 * grow too far in one direction or the other.
699 * 4) If the _alloc_back() has never been called, then the back portion of
700 * the pool retains a size of zero. (This makes it easier for users of
701 * the block pool that only want a one-sided pool.)
703 * 5) We have enough space allocated for at least one more block in
704 * whichever side `state` points to.
706 * 6) The center of the pool is always aligned to both the block_size of
707 * the pool and a 4K CPU page.
710 anv_block_pool_grow(struct anv_block_pool
*pool
, struct anv_block_state
*state
)
712 VkResult result
= VK_SUCCESS
;
714 pthread_mutex_lock(&pool
->device
->mutex
);
716 assert(state
== &pool
->state
|| state
== &pool
->back_state
);
718 /* Gather a little usage information on the pool. Since we may have
719 * threadsd waiting in queue to get some storage while we resize, it's
720 * actually possible that total_used will be larger than old_size. In
721 * particular, block_pool_alloc() increments state->next prior to
722 * calling block_pool_grow, so this ensures that we get enough space for
723 * which ever side tries to grow the pool.
725 * We align to a page size because it makes it easier to do our
726 * calculations later in such a way that we state page-aigned.
728 uint32_t back_used
= align_u32(pool
->back_state
.next
, PAGE_SIZE
);
729 uint32_t front_used
= align_u32(pool
->state
.next
, PAGE_SIZE
);
730 uint32_t total_used
= front_used
+ back_used
;
732 assert(state
== &pool
->state
|| back_used
> 0);
734 uint32_t old_size
= pool
->size
;
736 /* The block pool is always initialized to a nonzero size and this function
737 * is always called after initialization.
739 assert(old_size
> 0);
741 /* The back_used and front_used may actually be smaller than the actual
742 * requirement because they are based on the next pointers which are
743 * updated prior to calling this function.
745 uint32_t back_required
= MAX2(back_used
, pool
->center_bo_offset
);
746 uint32_t front_required
= MAX2(front_used
, old_size
- pool
->center_bo_offset
);
748 if (back_used
* 2 <= back_required
&& front_used
* 2 <= front_required
) {
749 /* If we're in this case then this isn't the firsta allocation and we
750 * already have enough space on both sides to hold double what we
751 * have allocated. There's nothing for us to do.
756 uint32_t size
= old_size
* 2;
757 while (size
< back_required
+ front_required
)
760 assert(size
> pool
->size
);
762 /* We compute a new center_bo_offset such that, when we double the size
763 * of the pool, we maintain the ratio of how much is used by each side.
764 * This way things should remain more-or-less balanced.
766 uint32_t center_bo_offset
;
767 if (back_used
== 0) {
768 /* If we're in this case then we have never called alloc_back(). In
769 * this case, we want keep the offset at 0 to make things as simple
770 * as possible for users that don't care about back allocations.
772 center_bo_offset
= 0;
774 /* Try to "center" the allocation based on how much is currently in
775 * use on each side of the center line.
777 center_bo_offset
= ((uint64_t)size
* back_used
) / total_used
;
779 /* Align down to a multiple of the page size */
780 center_bo_offset
&= ~(PAGE_SIZE
- 1);
782 assert(center_bo_offset
>= back_used
);
784 /* Make sure we don't shrink the back end of the pool */
785 if (center_bo_offset
< back_required
)
786 center_bo_offset
= back_required
;
788 /* Make sure that we don't shrink the front end of the pool */
789 if (size
- center_bo_offset
< front_required
)
790 center_bo_offset
= size
- front_required
;
793 assert(center_bo_offset
% PAGE_SIZE
== 0);
795 result
= anv_block_pool_expand_range(pool
, center_bo_offset
, size
);
797 pool
->bo
->flags
= pool
->bo_flags
;
800 pthread_mutex_unlock(&pool
->device
->mutex
);
802 if (result
== VK_SUCCESS
) {
803 /* Return the appropriate new size. This function never actually
804 * updates state->next. Instead, we let the caller do that because it
805 * needs to do so in order to maintain its concurrency model.
807 if (state
== &pool
->state
) {
808 return pool
->size
- pool
->center_bo_offset
;
810 assert(pool
->center_bo_offset
> 0);
811 return pool
->center_bo_offset
;
819 anv_block_pool_alloc_new(struct anv_block_pool
*pool
,
820 struct anv_block_state
*pool_state
,
821 uint32_t block_size
, uint32_t *padding
)
823 struct anv_block_state state
, old
, new;
825 /* Most allocations won't generate any padding */
830 state
.u64
= __sync_fetch_and_add(&pool_state
->u64
, block_size
);
831 if (state
.next
+ block_size
<= state
.end
) {
833 } else if (state
.next
<= state
.end
) {
834 if (pool
->bo_flags
& EXEC_OBJECT_PINNED
&& state
.next
< state
.end
) {
835 /* We need to grow the block pool, but still have some leftover
836 * space that can't be used by that particular allocation. So we
837 * add that as a "padding", and return it.
839 uint32_t leftover
= state
.end
- state
.next
;
841 /* If there is some leftover space in the pool, the caller must
844 assert(leftover
== 0 || padding
);
847 state
.next
+= leftover
;
850 /* We allocated the first block outside the pool so we have to grow
851 * the pool. pool_state->next acts a mutex: threads who try to
852 * allocate now will get block indexes above the current limit and
853 * hit futex_wait below.
855 new.next
= state
.next
+ block_size
;
857 new.end
= anv_block_pool_grow(pool
, pool_state
);
858 } while (new.end
< new.next
);
860 old
.u64
= __sync_lock_test_and_set(&pool_state
->u64
, new.u64
);
861 if (old
.next
!= state
.next
)
862 futex_wake(&pool_state
->end
, INT_MAX
);
865 futex_wait(&pool_state
->end
, state
.end
, NULL
);
872 anv_block_pool_alloc(struct anv_block_pool
*pool
,
873 uint32_t block_size
, uint32_t *padding
)
877 offset
= anv_block_pool_alloc_new(pool
, &pool
->state
, block_size
, padding
);
882 /* Allocates a block out of the back of the block pool.
884 * This will allocated a block earlier than the "start" of the block pool.
885 * The offsets returned from this function will be negative but will still
886 * be correct relative to the block pool's map pointer.
888 * If you ever use anv_block_pool_alloc_back, then you will have to do
889 * gymnastics with the block pool's BO when doing relocations.
892 anv_block_pool_alloc_back(struct anv_block_pool
*pool
,
895 int32_t offset
= anv_block_pool_alloc_new(pool
, &pool
->back_state
,
898 /* The offset we get out of anv_block_pool_alloc_new() is actually the
899 * number of bytes downwards from the middle to the end of the block.
900 * We need to turn it into a (negative) offset from the middle to the
901 * start of the block.
904 return -(offset
+ block_size
);
908 anv_state_pool_init(struct anv_state_pool
*pool
,
909 struct anv_device
*device
,
910 uint64_t start_address
,
914 VkResult result
= anv_block_pool_init(&pool
->block_pool
, device
,
918 if (result
!= VK_SUCCESS
)
921 result
= anv_state_table_init(&pool
->table
, device
, 64);
922 if (result
!= VK_SUCCESS
) {
923 anv_block_pool_finish(&pool
->block_pool
);
927 assert(util_is_power_of_two_or_zero(block_size
));
928 pool
->block_size
= block_size
;
929 pool
->back_alloc_free_list
= ANV_FREE_LIST_EMPTY
;
930 for (unsigned i
= 0; i
< ANV_STATE_BUCKETS
; i
++) {
931 pool
->buckets
[i
].free_list
= ANV_FREE_LIST_EMPTY
;
932 pool
->buckets
[i
].block
.next
= 0;
933 pool
->buckets
[i
].block
.end
= 0;
935 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
941 anv_state_pool_finish(struct anv_state_pool
*pool
)
943 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
944 anv_state_table_finish(&pool
->table
);
945 anv_block_pool_finish(&pool
->block_pool
);
949 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool
*pool
,
950 struct anv_block_pool
*block_pool
,
955 struct anv_block_state block
, old
, new;
958 /* We don't always use anv_block_pool_alloc(), which would set *padding to
959 * zero for us. So if we have a pointer to padding, we must zero it out
960 * ourselves here, to make sure we always return some sensible value.
965 /* If our state is large, we don't need any sub-allocation from a block.
966 * Instead, we just grab whole (potentially large) blocks.
968 if (state_size
>= block_size
)
969 return anv_block_pool_alloc(block_pool
, state_size
, padding
);
972 block
.u64
= __sync_fetch_and_add(&pool
->block
.u64
, state_size
);
974 if (block
.next
< block
.end
) {
976 } else if (block
.next
== block
.end
) {
977 offset
= anv_block_pool_alloc(block_pool
, block_size
, padding
);
978 new.next
= offset
+ state_size
;
979 new.end
= offset
+ block_size
;
980 old
.u64
= __sync_lock_test_and_set(&pool
->block
.u64
, new.u64
);
981 if (old
.next
!= block
.next
)
982 futex_wake(&pool
->block
.end
, INT_MAX
);
985 futex_wait(&pool
->block
.end
, block
.end
, NULL
);
991 anv_state_pool_get_bucket(uint32_t size
)
993 unsigned size_log2
= ilog2_round_up(size
);
994 assert(size_log2
<= ANV_MAX_STATE_SIZE_LOG2
);
995 if (size_log2
< ANV_MIN_STATE_SIZE_LOG2
)
996 size_log2
= ANV_MIN_STATE_SIZE_LOG2
;
997 return size_log2
- ANV_MIN_STATE_SIZE_LOG2
;
1001 anv_state_pool_get_bucket_size(uint32_t bucket
)
1003 uint32_t size_log2
= bucket
+ ANV_MIN_STATE_SIZE_LOG2
;
1004 return 1 << size_log2
;
1007 /** Helper to push a chunk into the state table.
1009 * It creates 'count' entries into the state table and update their sizes,
1010 * offsets and maps, also pushing them as "free" states.
1013 anv_state_pool_return_blocks(struct anv_state_pool
*pool
,
1014 uint32_t chunk_offset
, uint32_t count
,
1015 uint32_t block_size
)
1017 /* Disallow returning 0 chunks */
1020 /* Make sure we always return chunks aligned to the block_size */
1021 assert(chunk_offset
% block_size
== 0);
1024 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &st_idx
, count
);
1025 assert(result
== VK_SUCCESS
);
1026 for (int i
= 0; i
< count
; i
++) {
1027 /* update states that were added back to the state table */
1028 struct anv_state
*state_i
= anv_state_table_get(&pool
->table
,
1030 state_i
->alloc_size
= block_size
;
1031 state_i
->offset
= chunk_offset
+ block_size
* i
;
1032 state_i
->map
= anv_block_pool_map(&pool
->block_pool
, state_i
->offset
);
1035 uint32_t block_bucket
= anv_state_pool_get_bucket(block_size
);
1036 anv_free_list_push(&pool
->buckets
[block_bucket
].free_list
,
1037 &pool
->table
, st_idx
, count
);
1040 /** Returns a chunk of memory back to the state pool.
1042 * Do a two-level split. If chunk_size is bigger than divisor
1043 * (pool->block_size), we return as many divisor sized blocks as we can, from
1044 * the end of the chunk.
1046 * The remaining is then split into smaller blocks (starting at small_size if
1047 * it is non-zero), with larger blocks always being taken from the end of the
1051 anv_state_pool_return_chunk(struct anv_state_pool
*pool
,
1052 uint32_t chunk_offset
, uint32_t chunk_size
,
1053 uint32_t small_size
)
1055 uint32_t divisor
= pool
->block_size
;
1056 uint32_t nblocks
= chunk_size
/ divisor
;
1057 uint32_t rest
= chunk_size
- nblocks
* divisor
;
1060 /* First return divisor aligned and sized chunks. We start returning
1061 * larger blocks from the end fo the chunk, since they should already be
1062 * aligned to divisor. Also anv_state_pool_return_blocks() only accepts
1065 uint32_t offset
= chunk_offset
+ rest
;
1066 anv_state_pool_return_blocks(pool
, offset
, nblocks
, divisor
);
1072 if (small_size
> 0 && small_size
< divisor
)
1073 divisor
= small_size
;
1075 uint32_t min_size
= 1 << ANV_MIN_STATE_SIZE_LOG2
;
1077 /* Just as before, return larger divisor aligned blocks from the end of the
1080 while (chunk_size
> 0 && divisor
>= min_size
) {
1081 nblocks
= chunk_size
/ divisor
;
1082 rest
= chunk_size
- nblocks
* divisor
;
1084 anv_state_pool_return_blocks(pool
, chunk_offset
+ rest
,
1092 static struct anv_state
1093 anv_state_pool_alloc_no_vg(struct anv_state_pool
*pool
,
1094 uint32_t size
, uint32_t align
)
1096 uint32_t bucket
= anv_state_pool_get_bucket(MAX2(size
, align
));
1098 struct anv_state
*state
;
1099 uint32_t alloc_size
= anv_state_pool_get_bucket_size(bucket
);
1102 /* Try free list first. */
1103 state
= anv_free_list_pop(&pool
->buckets
[bucket
].free_list
,
1106 assert(state
->offset
>= 0);
1110 /* Try to grab a chunk from some larger bucket and split it up */
1111 for (unsigned b
= bucket
+ 1; b
< ANV_STATE_BUCKETS
; b
++) {
1112 state
= anv_free_list_pop(&pool
->buckets
[b
].free_list
, &pool
->table
);
1114 unsigned chunk_size
= anv_state_pool_get_bucket_size(b
);
1115 int32_t chunk_offset
= state
->offset
;
1117 /* First lets update the state we got to its new size. offset and map
1120 state
->alloc_size
= alloc_size
;
1122 /* Now return the unused part of the chunk back to the pool as free
1125 * There are a couple of options as to what we do with it:
1127 * 1) We could fully split the chunk into state.alloc_size sized
1128 * pieces. However, this would mean that allocating a 16B
1129 * state could potentially split a 2MB chunk into 512K smaller
1130 * chunks. This would lead to unnecessary fragmentation.
1132 * 2) The classic "buddy allocator" method would have us split the
1133 * chunk in half and return one half. Then we would split the
1134 * remaining half in half and return one half, and repeat as
1135 * needed until we get down to the size we want. However, if
1136 * you are allocating a bunch of the same size state (which is
1137 * the common case), this means that every other allocation has
1138 * to go up a level and every fourth goes up two levels, etc.
1139 * This is not nearly as efficient as it could be if we did a
1140 * little more work up-front.
1142 * 3) Split the difference between (1) and (2) by doing a
1143 * two-level split. If it's bigger than some fixed block_size,
1144 * we split it into block_size sized chunks and return all but
1145 * one of them. Then we split what remains into
1146 * state.alloc_size sized chunks and return them.
1148 * We choose something close to option (3), which is implemented with
1149 * anv_state_pool_return_chunk(). That is done by returning the
1150 * remaining of the chunk, with alloc_size as a hint of the size that
1151 * we want the smaller chunk split into.
1153 anv_state_pool_return_chunk(pool
, chunk_offset
+ alloc_size
,
1154 chunk_size
- alloc_size
, alloc_size
);
1160 offset
= anv_fixed_size_state_pool_alloc_new(&pool
->buckets
[bucket
],
1165 /* Everytime we allocate a new state, add it to the state pool */
1167 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &idx
, 1);
1168 assert(result
== VK_SUCCESS
);
1170 state
= anv_state_table_get(&pool
->table
, idx
);
1171 state
->offset
= offset
;
1172 state
->alloc_size
= alloc_size
;
1173 state
->map
= anv_block_pool_map(&pool
->block_pool
, offset
);
1176 uint32_t return_offset
= offset
- padding
;
1177 anv_state_pool_return_chunk(pool
, return_offset
, padding
, 0);
1185 anv_state_pool_alloc(struct anv_state_pool
*pool
, uint32_t size
, uint32_t align
)
1188 return ANV_STATE_NULL
;
1190 struct anv_state state
= anv_state_pool_alloc_no_vg(pool
, size
, align
);
1191 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
.map
, size
));
1196 anv_state_pool_alloc_back(struct anv_state_pool
*pool
)
1198 struct anv_state
*state
;
1199 uint32_t alloc_size
= pool
->block_size
;
1201 state
= anv_free_list_pop(&pool
->back_alloc_free_list
, &pool
->table
);
1203 assert(state
->offset
< 0);
1208 offset
= anv_block_pool_alloc_back(&pool
->block_pool
,
1211 UNUSED VkResult result
= anv_state_table_add(&pool
->table
, &idx
, 1);
1212 assert(result
== VK_SUCCESS
);
1214 state
= anv_state_table_get(&pool
->table
, idx
);
1215 state
->offset
= offset
;
1216 state
->alloc_size
= alloc_size
;
1217 state
->map
= anv_block_pool_map(&pool
->block_pool
, state
->offset
);
1220 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
->map
, state
->alloc_size
));
1225 anv_state_pool_free_no_vg(struct anv_state_pool
*pool
, struct anv_state state
)
1227 assert(util_is_power_of_two_or_zero(state
.alloc_size
));
1228 unsigned bucket
= anv_state_pool_get_bucket(state
.alloc_size
);
1230 if (state
.offset
< 0) {
1231 assert(state
.alloc_size
== pool
->block_size
);
1232 anv_free_list_push(&pool
->back_alloc_free_list
,
1233 &pool
->table
, state
.idx
, 1);
1235 anv_free_list_push(&pool
->buckets
[bucket
].free_list
,
1236 &pool
->table
, state
.idx
, 1);
1241 anv_state_pool_free(struct anv_state_pool
*pool
, struct anv_state state
)
1243 if (state
.alloc_size
== 0)
1246 VG(VALGRIND_MEMPOOL_FREE(pool
, state
.map
));
1247 anv_state_pool_free_no_vg(pool
, state
);
1250 struct anv_state_stream_block
{
1251 struct anv_state block
;
1253 /* The next block */
1254 struct anv_state_stream_block
*next
;
1256 #ifdef HAVE_VALGRIND
1257 /* A pointer to the first user-allocated thing in this block. This is
1258 * what valgrind sees as the start of the block.
1264 /* The state stream allocator is a one-shot, single threaded allocator for
1265 * variable sized blocks. We use it for allocating dynamic state.
1268 anv_state_stream_init(struct anv_state_stream
*stream
,
1269 struct anv_state_pool
*state_pool
,
1270 uint32_t block_size
)
1272 stream
->state_pool
= state_pool
;
1273 stream
->block_size
= block_size
;
1275 stream
->block
= ANV_STATE_NULL
;
1277 stream
->block_list
= NULL
;
1279 /* Ensure that next + whatever > block_size. This way the first call to
1280 * state_stream_alloc fetches a new block.
1282 stream
->next
= block_size
;
1284 VG(VALGRIND_CREATE_MEMPOOL(stream
, 0, false));
1288 anv_state_stream_finish(struct anv_state_stream
*stream
)
1290 struct anv_state_stream_block
*next
= stream
->block_list
;
1291 while (next
!= NULL
) {
1292 struct anv_state_stream_block sb
= VG_NOACCESS_READ(next
);
1293 VG(VALGRIND_MEMPOOL_FREE(stream
, sb
._vg_ptr
));
1294 VG(VALGRIND_MAKE_MEM_UNDEFINED(next
, stream
->block_size
));
1295 anv_state_pool_free_no_vg(stream
->state_pool
, sb
.block
);
1299 VG(VALGRIND_DESTROY_MEMPOOL(stream
));
1303 anv_state_stream_alloc(struct anv_state_stream
*stream
,
1304 uint32_t size
, uint32_t alignment
)
1307 return ANV_STATE_NULL
;
1309 assert(alignment
<= PAGE_SIZE
);
1311 uint32_t offset
= align_u32(stream
->next
, alignment
);
1312 if (offset
+ size
> stream
->block
.alloc_size
) {
1313 uint32_t block_size
= stream
->block_size
;
1314 if (block_size
< size
)
1315 block_size
= round_to_power_of_two(size
);
1317 stream
->block
= anv_state_pool_alloc_no_vg(stream
->state_pool
,
1318 block_size
, PAGE_SIZE
);
1320 struct anv_state_stream_block
*sb
= stream
->block
.map
;
1321 VG_NOACCESS_WRITE(&sb
->block
, stream
->block
);
1322 VG_NOACCESS_WRITE(&sb
->next
, stream
->block_list
);
1323 stream
->block_list
= sb
;
1324 VG(VG_NOACCESS_WRITE(&sb
->_vg_ptr
, NULL
));
1326 VG(VALGRIND_MAKE_MEM_NOACCESS(stream
->block
.map
, stream
->block_size
));
1328 /* Reset back to the start plus space for the header */
1329 stream
->next
= sizeof(*sb
);
1331 offset
= align_u32(stream
->next
, alignment
);
1332 assert(offset
+ size
<= stream
->block
.alloc_size
);
1335 struct anv_state state
= stream
->block
;
1336 state
.offset
+= offset
;
1337 state
.alloc_size
= size
;
1338 state
.map
+= offset
;
1340 stream
->next
= offset
+ size
;
1342 #ifdef HAVE_VALGRIND
1343 struct anv_state_stream_block
*sb
= stream
->block_list
;
1344 void *vg_ptr
= VG_NOACCESS_READ(&sb
->_vg_ptr
);
1345 if (vg_ptr
== NULL
) {
1347 VG_NOACCESS_WRITE(&sb
->_vg_ptr
, vg_ptr
);
1348 VALGRIND_MEMPOOL_ALLOC(stream
, vg_ptr
, size
);
1350 void *state_end
= state
.map
+ state
.alloc_size
;
1351 /* This only updates the mempool. The newly allocated chunk is still
1352 * marked as NOACCESS. */
1353 VALGRIND_MEMPOOL_CHANGE(stream
, vg_ptr
, vg_ptr
, state_end
- vg_ptr
);
1354 /* Mark the newly allocated chunk as undefined */
1355 VALGRIND_MAKE_MEM_UNDEFINED(state
.map
, state
.alloc_size
);
1362 struct bo_pool_bo_link
{
1363 struct bo_pool_bo_link
*next
;
1368 anv_bo_pool_init(struct anv_bo_pool
*pool
, struct anv_device
*device
,
1371 pool
->device
= device
;
1372 pool
->bo_flags
= bo_flags
;
1373 memset(pool
->free_list
, 0, sizeof(pool
->free_list
));
1375 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
1379 anv_bo_pool_finish(struct anv_bo_pool
*pool
)
1381 for (unsigned i
= 0; i
< ARRAY_SIZE(pool
->free_list
); i
++) {
1382 struct bo_pool_bo_link
*link
= PFL_PTR(pool
->free_list
[i
]);
1383 while (link
!= NULL
) {
1384 struct bo_pool_bo_link link_copy
= VG_NOACCESS_READ(link
);
1386 anv_gem_munmap(link_copy
.bo
.map
, link_copy
.bo
.size
);
1387 anv_vma_free(pool
->device
, &link_copy
.bo
);
1388 anv_gem_close(pool
->device
, link_copy
.bo
.gem_handle
);
1389 link
= link_copy
.next
;
1393 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
1397 anv_bo_pool_alloc(struct anv_bo_pool
*pool
, struct anv_bo
*bo
, uint32_t size
)
1401 const unsigned size_log2
= size
< 4096 ? 12 : ilog2_round_up(size
);
1402 const unsigned pow2_size
= 1 << size_log2
;
1403 const unsigned bucket
= size_log2
- 12;
1404 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
1406 void *next_free_void
;
1407 if (anv_ptr_free_list_pop(&pool
->free_list
[bucket
], &next_free_void
)) {
1408 struct bo_pool_bo_link
*next_free
= next_free_void
;
1409 *bo
= VG_NOACCESS_READ(&next_free
->bo
);
1410 assert(bo
->gem_handle
);
1411 assert(bo
->map
== next_free
);
1412 assert(size
<= bo
->size
);
1414 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1419 struct anv_bo new_bo
;
1421 result
= anv_bo_init_new(&new_bo
, pool
->device
, pow2_size
);
1422 if (result
!= VK_SUCCESS
)
1425 new_bo
.flags
= pool
->bo_flags
;
1427 if (!anv_vma_alloc(pool
->device
, &new_bo
))
1428 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY
);
1430 assert(new_bo
.size
== pow2_size
);
1432 new_bo
.map
= anv_gem_mmap(pool
->device
, new_bo
.gem_handle
, 0, pow2_size
, 0);
1433 if (new_bo
.map
== MAP_FAILED
) {
1434 anv_gem_close(pool
->device
, new_bo
.gem_handle
);
1435 anv_vma_free(pool
->device
, &new_bo
);
1436 return vk_error(VK_ERROR_MEMORY_MAP_FAILED
);
1439 /* We are removing the state flushes, so lets make sure that these buffers
1440 * are cached/snooped.
1442 if (!pool
->device
->info
.has_llc
) {
1443 anv_gem_set_caching(pool
->device
, new_bo
.gem_handle
,
1444 I915_CACHING_CACHED
);
1449 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1455 anv_bo_pool_free(struct anv_bo_pool
*pool
, const struct anv_bo
*bo_in
)
1457 /* Make a copy in case the anv_bo happens to be storred in the BO */
1458 struct anv_bo bo
= *bo_in
;
1460 VG(VALGRIND_MEMPOOL_FREE(pool
, bo
.map
));
1462 struct bo_pool_bo_link
*link
= bo
.map
;
1463 VG_NOACCESS_WRITE(&link
->bo
, bo
);
1465 assert(util_is_power_of_two_or_zero(bo
.size
));
1466 const unsigned size_log2
= ilog2_round_up(bo
.size
);
1467 const unsigned bucket
= size_log2
- 12;
1468 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
1470 anv_ptr_free_list_push(&pool
->free_list
[bucket
], link
);
1476 anv_scratch_pool_init(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1478 memset(pool
, 0, sizeof(*pool
));
1482 anv_scratch_pool_finish(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1484 for (unsigned s
= 0; s
< MESA_SHADER_STAGES
; s
++) {
1485 for (unsigned i
= 0; i
< 16; i
++) {
1486 struct anv_scratch_bo
*bo
= &pool
->bos
[i
][s
];
1487 if (bo
->exists
> 0) {
1488 anv_vma_free(device
, &bo
->bo
);
1489 anv_gem_close(device
, bo
->bo
.gem_handle
);
1496 anv_scratch_pool_alloc(struct anv_device
*device
, struct anv_scratch_pool
*pool
,
1497 gl_shader_stage stage
, unsigned per_thread_scratch
)
1499 if (per_thread_scratch
== 0)
1502 unsigned scratch_size_log2
= ffs(per_thread_scratch
/ 2048);
1503 assert(scratch_size_log2
< 16);
1505 struct anv_scratch_bo
*bo
= &pool
->bos
[scratch_size_log2
][stage
];
1507 /* We can use "exists" to shortcut and ignore the critical section */
1511 pthread_mutex_lock(&device
->mutex
);
1513 __sync_synchronize();
1515 pthread_mutex_unlock(&device
->mutex
);
1519 const struct anv_physical_device
*physical_device
=
1520 &device
->instance
->physicalDevice
;
1521 const struct gen_device_info
*devinfo
= &physical_device
->info
;
1523 const unsigned subslices
= MAX2(physical_device
->subslice_total
, 1);
1525 unsigned scratch_ids_per_subslice
;
1526 if (devinfo
->is_haswell
) {
1527 /* WaCSScratchSize:hsw
1529 * Haswell's scratch space address calculation appears to be sparse
1530 * rather than tightly packed. The Thread ID has bits indicating
1531 * which subslice, EU within a subslice, and thread within an EU it
1532 * is. There's a maximum of two slices and two subslices, so these
1533 * can be stored with a single bit. Even though there are only 10 EUs
1534 * per subslice, this is stored in 4 bits, so there's an effective
1535 * maximum value of 16 EUs. Similarly, although there are only 7
1536 * threads per EU, this is stored in a 3 bit number, giving an
1537 * effective maximum value of 8 threads per EU.
1539 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1540 * number of threads per subslice.
1542 scratch_ids_per_subslice
= 16 * 8;
1543 } else if (devinfo
->is_cherryview
) {
1544 /* Cherryview devices have either 6 or 8 EUs per subslice, and each EU
1545 * has 7 threads. The 6 EU devices appear to calculate thread IDs as if
1548 scratch_ids_per_subslice
= 8 * 7;
1550 scratch_ids_per_subslice
= devinfo
->max_cs_threads
;
1553 uint32_t max_threads
[] = {
1554 [MESA_SHADER_VERTEX
] = devinfo
->max_vs_threads
,
1555 [MESA_SHADER_TESS_CTRL
] = devinfo
->max_tcs_threads
,
1556 [MESA_SHADER_TESS_EVAL
] = devinfo
->max_tes_threads
,
1557 [MESA_SHADER_GEOMETRY
] = devinfo
->max_gs_threads
,
1558 [MESA_SHADER_FRAGMENT
] = devinfo
->max_wm_threads
,
1559 [MESA_SHADER_COMPUTE
] = scratch_ids_per_subslice
* subslices
,
1562 uint32_t size
= per_thread_scratch
* max_threads
[stage
];
1564 anv_bo_init_new(&bo
->bo
, device
, size
);
1566 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1567 * are still relative to the general state base address. When we emit
1568 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1569 * to the maximum (1 page under 4GB). This allows us to just place the
1570 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1571 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1572 * However, in order to do so, we need to ensure that the kernel does not
1573 * place the scratch BO above the 32-bit boundary.
1575 * NOTE: Technically, it can't go "anywhere" because the top page is off
1576 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1577 * kernel allocates space using
1579 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1581 * so nothing will ever touch the top page.
1583 assert(!(bo
->bo
.flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
));
1585 if (device
->instance
->physicalDevice
.has_exec_async
)
1586 bo
->bo
.flags
|= EXEC_OBJECT_ASYNC
;
1588 if (device
->instance
->physicalDevice
.use_softpin
)
1589 bo
->bo
.flags
|= EXEC_OBJECT_PINNED
;
1591 anv_vma_alloc(device
, &bo
->bo
);
1593 /* Set the exists last because it may be read by other threads */
1594 __sync_synchronize();
1597 pthread_mutex_unlock(&device
->mutex
);
1602 struct anv_cached_bo
{
1609 anv_bo_cache_init(struct anv_bo_cache
*cache
)
1611 cache
->bo_map
= _mesa_pointer_hash_table_create(NULL
);
1613 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1615 if (pthread_mutex_init(&cache
->mutex
, NULL
)) {
1616 _mesa_hash_table_destroy(cache
->bo_map
, NULL
);
1617 return vk_errorf(NULL
, NULL
, VK_ERROR_OUT_OF_HOST_MEMORY
,
1618 "pthread_mutex_init failed: %m");
1625 anv_bo_cache_finish(struct anv_bo_cache
*cache
)
1627 _mesa_hash_table_destroy(cache
->bo_map
, NULL
);
1628 pthread_mutex_destroy(&cache
->mutex
);
1631 static struct anv_cached_bo
*
1632 anv_bo_cache_lookup_locked(struct anv_bo_cache
*cache
, uint32_t gem_handle
)
1634 struct hash_entry
*entry
=
1635 _mesa_hash_table_search(cache
->bo_map
,
1636 (const void *)(uintptr_t)gem_handle
);
1640 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)entry
->data
;
1641 assert(bo
->bo
.gem_handle
== gem_handle
);
1646 UNUSED
static struct anv_bo
*
1647 anv_bo_cache_lookup(struct anv_bo_cache
*cache
, uint32_t gem_handle
)
1649 pthread_mutex_lock(&cache
->mutex
);
1651 struct anv_cached_bo
*bo
= anv_bo_cache_lookup_locked(cache
, gem_handle
);
1653 pthread_mutex_unlock(&cache
->mutex
);
1655 return bo
? &bo
->bo
: NULL
;
1658 #define ANV_BO_CACHE_SUPPORTED_FLAGS \
1659 (EXEC_OBJECT_WRITE | \
1660 EXEC_OBJECT_ASYNC | \
1661 EXEC_OBJECT_SUPPORTS_48B_ADDRESS | \
1662 EXEC_OBJECT_PINNED | \
1666 anv_bo_cache_alloc(struct anv_device
*device
,
1667 struct anv_bo_cache
*cache
,
1668 uint64_t size
, uint64_t bo_flags
,
1669 struct anv_bo
**bo_out
)
1671 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1673 struct anv_cached_bo
*bo
=
1674 vk_alloc(&device
->alloc
, sizeof(struct anv_cached_bo
), 8,
1675 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT
);
1677 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1681 /* The kernel is going to give us whole pages anyway */
1682 size
= align_u64(size
, 4096);
1684 VkResult result
= anv_bo_init_new(&bo
->bo
, device
, size
);
1685 if (result
!= VK_SUCCESS
) {
1686 vk_free(&device
->alloc
, bo
);
1690 bo
->bo
.flags
= bo_flags
;
1692 if (!anv_vma_alloc(device
, &bo
->bo
)) {
1693 anv_gem_close(device
, bo
->bo
.gem_handle
);
1694 vk_free(&device
->alloc
, bo
);
1695 return vk_errorf(device
->instance
, NULL
,
1696 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1697 "failed to allocate virtual address for BO");
1700 assert(bo
->bo
.gem_handle
);
1702 pthread_mutex_lock(&cache
->mutex
);
1704 _mesa_hash_table_insert(cache
->bo_map
,
1705 (void *)(uintptr_t)bo
->bo
.gem_handle
, bo
);
1707 pthread_mutex_unlock(&cache
->mutex
);
1715 anv_bo_cache_import(struct anv_device
*device
,
1716 struct anv_bo_cache
*cache
,
1717 int fd
, uint64_t bo_flags
,
1718 struct anv_bo
**bo_out
)
1720 assert(bo_flags
== (bo_flags
& ANV_BO_CACHE_SUPPORTED_FLAGS
));
1721 assert(bo_flags
& ANV_BO_EXTERNAL
);
1723 pthread_mutex_lock(&cache
->mutex
);
1725 uint32_t gem_handle
= anv_gem_fd_to_handle(device
, fd
);
1727 pthread_mutex_unlock(&cache
->mutex
);
1728 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE
);
1731 struct anv_cached_bo
*bo
= anv_bo_cache_lookup_locked(cache
, gem_handle
);
1733 /* We have to be careful how we combine flags so that it makes sense.
1734 * Really, though, if we get to this case and it actually matters, the
1735 * client has imported a BO twice in different ways and they get what
1738 uint64_t new_flags
= ANV_BO_EXTERNAL
;
1739 new_flags
|= (bo
->bo
.flags
| bo_flags
) & EXEC_OBJECT_WRITE
;
1740 new_flags
|= (bo
->bo
.flags
& bo_flags
) & EXEC_OBJECT_ASYNC
;
1741 new_flags
|= (bo
->bo
.flags
& bo_flags
) & EXEC_OBJECT_SUPPORTS_48B_ADDRESS
;
1742 new_flags
|= (bo
->bo
.flags
| bo_flags
) & EXEC_OBJECT_PINNED
;
1744 /* It's theoretically possible for a BO to get imported such that it's
1745 * both pinned and not pinned. The only way this can happen is if it
1746 * gets imported as both a semaphore and a memory object and that would
1747 * be an application error. Just fail out in that case.
1749 if ((bo
->bo
.flags
& EXEC_OBJECT_PINNED
) !=
1750 (bo_flags
& EXEC_OBJECT_PINNED
)) {
1751 pthread_mutex_unlock(&cache
->mutex
);
1752 return vk_errorf(device
->instance
, NULL
,
1753 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1754 "The same BO was imported two different ways");
1757 /* It's also theoretically possible that someone could export a BO from
1758 * one heap and import it into another or to import the same BO into two
1759 * different heaps. If this happens, we could potentially end up both
1760 * allowing and disallowing 48-bit addresses. There's not much we can
1761 * do about it if we're pinning so we just throw an error and hope no
1762 * app is actually that stupid.
1764 if ((new_flags
& EXEC_OBJECT_PINNED
) &&
1765 (bo
->bo
.flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
) !=
1766 (bo_flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
)) {
1767 pthread_mutex_unlock(&cache
->mutex
);
1768 return vk_errorf(device
->instance
, NULL
,
1769 VK_ERROR_INVALID_EXTERNAL_HANDLE
,
1770 "The same BO was imported on two different heaps");
1773 bo
->bo
.flags
= new_flags
;
1775 __sync_fetch_and_add(&bo
->refcount
, 1);
1777 off_t size
= lseek(fd
, 0, SEEK_END
);
1778 if (size
== (off_t
)-1) {
1779 anv_gem_close(device
, gem_handle
);
1780 pthread_mutex_unlock(&cache
->mutex
);
1781 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE
);
1784 bo
= vk_alloc(&device
->alloc
, sizeof(struct anv_cached_bo
), 8,
1785 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT
);
1787 anv_gem_close(device
, gem_handle
);
1788 pthread_mutex_unlock(&cache
->mutex
);
1789 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1794 anv_bo_init(&bo
->bo
, gem_handle
, size
);
1795 bo
->bo
.flags
= bo_flags
;
1797 if (!anv_vma_alloc(device
, &bo
->bo
)) {
1798 anv_gem_close(device
, bo
->bo
.gem_handle
);
1799 pthread_mutex_unlock(&cache
->mutex
);
1800 vk_free(&device
->alloc
, bo
);
1801 return vk_errorf(device
->instance
, NULL
,
1802 VK_ERROR_OUT_OF_DEVICE_MEMORY
,
1803 "failed to allocate virtual address for BO");
1806 _mesa_hash_table_insert(cache
->bo_map
, (void *)(uintptr_t)gem_handle
, bo
);
1809 pthread_mutex_unlock(&cache
->mutex
);
1816 anv_bo_cache_export(struct anv_device
*device
,
1817 struct anv_bo_cache
*cache
,
1818 struct anv_bo
*bo_in
, int *fd_out
)
1820 assert(anv_bo_cache_lookup(cache
, bo_in
->gem_handle
) == bo_in
);
1821 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)bo_in
;
1823 /* This BO must have been flagged external in order for us to be able
1824 * to export it. This is done based on external options passed into
1825 * anv_AllocateMemory.
1827 assert(bo
->bo
.flags
& ANV_BO_EXTERNAL
);
1829 int fd
= anv_gem_handle_to_fd(device
, bo
->bo
.gem_handle
);
1831 return vk_error(VK_ERROR_TOO_MANY_OBJECTS
);
1839 atomic_dec_not_one(uint32_t *counter
)
1848 old
= __sync_val_compare_and_swap(counter
, val
, val
- 1);
1857 anv_bo_cache_release(struct anv_device
*device
,
1858 struct anv_bo_cache
*cache
,
1859 struct anv_bo
*bo_in
)
1861 assert(anv_bo_cache_lookup(cache
, bo_in
->gem_handle
) == bo_in
);
1862 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)bo_in
;
1864 /* Try to decrement the counter but don't go below one. If this succeeds
1865 * then the refcount has been decremented and we are not the last
1868 if (atomic_dec_not_one(&bo
->refcount
))
1871 pthread_mutex_lock(&cache
->mutex
);
1873 /* We are probably the last reference since our attempt to decrement above
1874 * failed. However, we can't actually know until we are inside the mutex.
1875 * Otherwise, someone could import the BO between the decrement and our
1878 if (unlikely(__sync_sub_and_fetch(&bo
->refcount
, 1) > 0)) {
1879 /* Turns out we're not the last reference. Unlock and bail. */
1880 pthread_mutex_unlock(&cache
->mutex
);
1884 struct hash_entry
*entry
=
1885 _mesa_hash_table_search(cache
->bo_map
,
1886 (const void *)(uintptr_t)bo
->bo
.gem_handle
);
1888 _mesa_hash_table_remove(cache
->bo_map
, entry
);
1891 anv_gem_munmap(bo
->bo
.map
, bo
->bo
.size
);
1893 anv_vma_free(device
, &bo
->bo
);
1895 anv_gem_close(device
, bo
->bo
.gem_handle
);
1897 /* Don't unlock until we've actually closed the BO. The whole point of
1898 * the BO cache is to ensure that we correctly handle races with creating
1899 * and releasing GEM handles and we don't want to let someone import the BO
1900 * again between mutex unlock and closing the GEM handle.
1902 pthread_mutex_unlock(&cache
->mutex
);
1904 vk_free(&device
->alloc
, bo
);