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. */
104 struct anv_mmap_cleanup
{
110 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
113 memfd_create(const char *name
, unsigned int flags
)
115 return syscall(SYS_memfd_create
, name
, flags
);
118 static inline uint32_t
119 ilog2_round_up(uint32_t value
)
122 return 32 - __builtin_clz(value
- 1);
125 static inline uint32_t
126 round_to_power_of_two(uint32_t value
)
128 return 1 << ilog2_round_up(value
);
132 anv_free_list_pop(union anv_free_list
*list
, void **map
, int32_t *offset
)
134 union anv_free_list current
, new, old
;
136 current
.u64
= list
->u64
;
137 while (current
.offset
!= EMPTY
) {
138 /* We have to add a memory barrier here so that the list head (and
139 * offset) gets read before we read the map pointer. This way we
140 * know that the map pointer is valid for the given offset at the
141 * point where we read it.
143 __sync_synchronize();
145 int32_t *next_ptr
= *map
+ current
.offset
;
146 new.offset
= VG_NOACCESS_READ(next_ptr
);
147 new.count
= current
.count
+ 1;
148 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
149 if (old
.u64
== current
.u64
) {
150 *offset
= current
.offset
;
160 anv_free_list_push(union anv_free_list
*list
, void *map
, int32_t offset
,
161 uint32_t size
, uint32_t count
)
163 union anv_free_list current
, old
, new;
164 int32_t *next_ptr
= map
+ offset
;
166 /* If we're returning more than one chunk, we need to build a chain to add
167 * to the list. Fortunately, we can do this without any atomics since we
168 * own everything in the chain right now. `offset` is left pointing to the
169 * head of our chain list while `next_ptr` points to the tail.
171 for (uint32_t i
= 1; i
< count
; i
++) {
172 VG_NOACCESS_WRITE(next_ptr
, offset
+ i
* size
);
173 next_ptr
= map
+ offset
+ i
* size
;
179 VG_NOACCESS_WRITE(next_ptr
, current
.offset
);
181 new.count
= current
.count
+ 1;
182 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
183 } while (old
.u64
!= current
.u64
);
186 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
187 * means that the bottom 12 bits should all be zero.
189 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
190 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
191 #define PFL_PACK(ptr, count) ({ \
192 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
196 anv_ptr_free_list_pop(void **list
, void **elem
)
198 void *current
= *list
;
199 while (PFL_PTR(current
) != NULL
) {
200 void **next_ptr
= PFL_PTR(current
);
201 void *new_ptr
= VG_NOACCESS_READ(next_ptr
);
202 unsigned new_count
= PFL_COUNT(current
) + 1;
203 void *new = PFL_PACK(new_ptr
, new_count
);
204 void *old
= __sync_val_compare_and_swap(list
, current
, new);
205 if (old
== current
) {
206 *elem
= PFL_PTR(current
);
216 anv_ptr_free_list_push(void **list
, void *elem
)
219 void **next_ptr
= elem
;
221 /* The pointer-based free list requires that the pointer be
222 * page-aligned. This is because we use the bottom 12 bits of the
223 * pointer to store a counter to solve the ABA concurrency problem.
225 assert(((uintptr_t)elem
& 0xfff) == 0);
230 VG_NOACCESS_WRITE(next_ptr
, PFL_PTR(current
));
231 unsigned new_count
= PFL_COUNT(current
) + 1;
232 void *new = PFL_PACK(elem
, new_count
);
233 old
= __sync_val_compare_and_swap(list
, current
, new);
234 } while (old
!= current
);
238 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
239 uint32_t center_bo_offset
, uint32_t size
);
242 anv_block_pool_init(struct anv_block_pool
*pool
,
243 struct anv_device
*device
,
244 uint32_t initial_size
)
248 pool
->device
= device
;
249 anv_bo_init(&pool
->bo
, 0, 0);
251 pool
->fd
= memfd_create("block pool", MFD_CLOEXEC
);
253 return vk_error(VK_ERROR_INITIALIZATION_FAILED
);
255 /* Just make it 2GB up-front. The Linux kernel won't actually back it
256 * with pages until we either map and fault on one of them or we use
257 * userptr and send a chunk of it off to the GPU.
259 if (ftruncate(pool
->fd
, BLOCK_POOL_MEMFD_SIZE
) == -1) {
260 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
264 if (!u_vector_init(&pool
->mmap_cleanups
,
265 round_to_power_of_two(sizeof(struct anv_mmap_cleanup
)),
267 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
271 pool
->state
.next
= 0;
273 pool
->back_state
.next
= 0;
274 pool
->back_state
.end
= 0;
276 result
= anv_block_pool_expand_range(pool
, 0, initial_size
);
277 if (result
!= VK_SUCCESS
)
278 goto fail_mmap_cleanups
;
283 u_vector_finish(&pool
->mmap_cleanups
);
291 anv_block_pool_finish(struct anv_block_pool
*pool
)
293 struct anv_mmap_cleanup
*cleanup
;
295 u_vector_foreach(cleanup
, &pool
->mmap_cleanups
) {
297 munmap(cleanup
->map
, cleanup
->size
);
298 if (cleanup
->gem_handle
)
299 anv_gem_close(pool
->device
, cleanup
->gem_handle
);
302 u_vector_finish(&pool
->mmap_cleanups
);
307 #define PAGE_SIZE 4096
310 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
311 uint32_t center_bo_offset
, uint32_t size
)
315 struct anv_mmap_cleanup
*cleanup
;
317 /* Assert that we only ever grow the pool */
318 assert(center_bo_offset
>= pool
->back_state
.end
);
319 assert(size
- center_bo_offset
>= pool
->state
.end
);
321 /* Assert that we don't go outside the bounds of the memfd */
322 assert(center_bo_offset
<= BLOCK_POOL_MEMFD_CENTER
);
323 assert(size
- center_bo_offset
<=
324 BLOCK_POOL_MEMFD_SIZE
- BLOCK_POOL_MEMFD_CENTER
);
326 cleanup
= u_vector_add(&pool
->mmap_cleanups
);
328 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
330 *cleanup
= ANV_MMAP_CLEANUP_INIT
;
332 /* Just leak the old map until we destroy the pool. We can't munmap it
333 * without races or imposing locking on the block allocate fast path. On
334 * the whole the leaked maps adds up to less than the size of the
335 * current map. MAP_POPULATE seems like the right thing to do, but we
336 * should try to get some numbers.
338 map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
339 MAP_SHARED
| MAP_POPULATE
, pool
->fd
,
340 BLOCK_POOL_MEMFD_CENTER
- center_bo_offset
);
341 if (map
== MAP_FAILED
)
342 return vk_errorf(pool
->device
->instance
, pool
->device
,
343 VK_ERROR_MEMORY_MAP_FAILED
, "mmap failed: %m");
345 gem_handle
= anv_gem_userptr(pool
->device
, map
, size
);
346 if (gem_handle
== 0) {
348 return vk_errorf(pool
->device
->instance
, pool
->device
,
349 VK_ERROR_TOO_MANY_OBJECTS
, "userptr failed: %m");
353 cleanup
->size
= size
;
354 cleanup
->gem_handle
= gem_handle
;
357 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
358 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
359 * always created as I915_CACHING_CACHED, which on non-LLC means
360 * snooped. That can be useful but comes with a bit of overheard. Since
361 * we're eplicitly clflushing and don't want the overhead we need to turn
363 if (!pool
->device
->info
.has_llc
) {
364 anv_gem_set_caching(pool
->device
, gem_handle
, I915_CACHING_NONE
);
365 anv_gem_set_domain(pool
->device
, gem_handle
,
366 I915_GEM_DOMAIN_GTT
, I915_GEM_DOMAIN_GTT
);
370 /* Now that we successfull allocated everything, we can write the new
371 * values back into pool. */
372 pool
->map
= map
+ center_bo_offset
;
373 pool
->center_bo_offset
= center_bo_offset
;
375 /* For block pool BOs we have to be a bit careful about where we place them
376 * in the GTT. There are two documented workarounds for state base address
377 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
378 * which state that those two base addresses do not support 48-bit
379 * addresses and need to be placed in the bottom 32-bit range.
380 * Unfortunately, this is not quite accurate.
382 * The real problem is that we always set the size of our state pools in
383 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
384 * likely significantly smaller. We do this because we do not no at the
385 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
386 * the pool during command buffer building so we don't actually have a
387 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
388 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
389 * as being out of bounds and returns zero. For dynamic state, this
390 * usually just leads to rendering corruptions, but shaders that are all
391 * zero hang the GPU immediately.
393 * The easiest solution to do is exactly what the bogus workarounds say to
394 * do: restrict these buffers to 32-bit addresses. We could also pin the
395 * BO to some particular location of our choosing, but that's significantly
396 * more work than just not setting a flag. So, we explicitly DO NOT set
397 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
400 anv_bo_init(&pool
->bo
, gem_handle
, size
);
406 /** Grows and re-centers the block pool.
408 * We grow the block pool in one or both directions in such a way that the
409 * following conditions are met:
411 * 1) The size of the entire pool is always a power of two.
413 * 2) The pool only grows on both ends. Neither end can get
416 * 3) At the end of the allocation, we have about twice as much space
417 * allocated for each end as we have used. This way the pool doesn't
418 * grow too far in one direction or the other.
420 * 4) If the _alloc_back() has never been called, then the back portion of
421 * the pool retains a size of zero. (This makes it easier for users of
422 * the block pool that only want a one-sided pool.)
424 * 5) We have enough space allocated for at least one more block in
425 * whichever side `state` points to.
427 * 6) The center of the pool is always aligned to both the block_size of
428 * the pool and a 4K CPU page.
431 anv_block_pool_grow(struct anv_block_pool
*pool
, struct anv_block_state
*state
)
433 VkResult result
= VK_SUCCESS
;
435 pthread_mutex_lock(&pool
->device
->mutex
);
437 assert(state
== &pool
->state
|| state
== &pool
->back_state
);
439 /* Gather a little usage information on the pool. Since we may have
440 * threadsd waiting in queue to get some storage while we resize, it's
441 * actually possible that total_used will be larger than old_size. In
442 * particular, block_pool_alloc() increments state->next prior to
443 * calling block_pool_grow, so this ensures that we get enough space for
444 * which ever side tries to grow the pool.
446 * We align to a page size because it makes it easier to do our
447 * calculations later in such a way that we state page-aigned.
449 uint32_t back_used
= align_u32(pool
->back_state
.next
, PAGE_SIZE
);
450 uint32_t front_used
= align_u32(pool
->state
.next
, PAGE_SIZE
);
451 uint32_t total_used
= front_used
+ back_used
;
453 assert(state
== &pool
->state
|| back_used
> 0);
455 uint32_t old_size
= pool
->bo
.size
;
457 /* The block pool is always initialized to a nonzero size and this function
458 * is always called after initialization.
460 assert(old_size
> 0);
462 /* The back_used and front_used may actually be smaller than the actual
463 * requirement because they are based on the next pointers which are
464 * updated prior to calling this function.
466 uint32_t back_required
= MAX2(back_used
, pool
->center_bo_offset
);
467 uint32_t front_required
= MAX2(front_used
, old_size
- pool
->center_bo_offset
);
469 if (back_used
* 2 <= back_required
&& front_used
* 2 <= front_required
) {
470 /* If we're in this case then this isn't the firsta allocation and we
471 * already have enough space on both sides to hold double what we
472 * have allocated. There's nothing for us to do.
477 uint32_t size
= old_size
* 2;
478 while (size
< back_required
+ front_required
)
481 assert(size
> pool
->bo
.size
);
483 /* We compute a new center_bo_offset such that, when we double the size
484 * of the pool, we maintain the ratio of how much is used by each side.
485 * This way things should remain more-or-less balanced.
487 uint32_t center_bo_offset
;
488 if (back_used
== 0) {
489 /* If we're in this case then we have never called alloc_back(). In
490 * this case, we want keep the offset at 0 to make things as simple
491 * as possible for users that don't care about back allocations.
493 center_bo_offset
= 0;
495 /* Try to "center" the allocation based on how much is currently in
496 * use on each side of the center line.
498 center_bo_offset
= ((uint64_t)size
* back_used
) / total_used
;
500 /* Align down to a multiple of the page size */
501 center_bo_offset
&= ~(PAGE_SIZE
- 1);
503 assert(center_bo_offset
>= back_used
);
505 /* Make sure we don't shrink the back end of the pool */
506 if (center_bo_offset
< pool
->back_state
.end
)
507 center_bo_offset
= pool
->back_state
.end
;
509 /* Make sure that we don't shrink the front end of the pool */
510 if (size
- center_bo_offset
< pool
->state
.end
)
511 center_bo_offset
= size
- pool
->state
.end
;
514 assert(center_bo_offset
% PAGE_SIZE
== 0);
516 result
= anv_block_pool_expand_range(pool
, center_bo_offset
, size
);
518 if (pool
->device
->instance
->physicalDevice
.has_exec_async
)
519 pool
->bo
.flags
|= EXEC_OBJECT_ASYNC
;
522 pthread_mutex_unlock(&pool
->device
->mutex
);
524 if (result
== VK_SUCCESS
) {
525 /* Return the appropriate new size. This function never actually
526 * updates state->next. Instead, we let the caller do that because it
527 * needs to do so in order to maintain its concurrency model.
529 if (state
== &pool
->state
) {
530 return pool
->bo
.size
- pool
->center_bo_offset
;
532 assert(pool
->center_bo_offset
> 0);
533 return pool
->center_bo_offset
;
541 anv_block_pool_alloc_new(struct anv_block_pool
*pool
,
542 struct anv_block_state
*pool_state
,
545 struct anv_block_state state
, old
, new;
548 state
.u64
= __sync_fetch_and_add(&pool_state
->u64
, block_size
);
549 if (state
.next
+ block_size
<= state
.end
) {
552 } else if (state
.next
<= state
.end
) {
553 /* We allocated the first block outside the pool so we have to grow
554 * the pool. pool_state->next acts a mutex: threads who try to
555 * allocate now will get block indexes above the current limit and
556 * hit futex_wait below.
558 new.next
= state
.next
+ block_size
;
560 new.end
= anv_block_pool_grow(pool
, pool_state
);
561 } while (new.end
< new.next
);
563 old
.u64
= __sync_lock_test_and_set(&pool_state
->u64
, new.u64
);
564 if (old
.next
!= state
.next
)
565 futex_wake(&pool_state
->end
, INT_MAX
);
568 futex_wait(&pool_state
->end
, state
.end
);
575 anv_block_pool_alloc(struct anv_block_pool
*pool
,
578 return anv_block_pool_alloc_new(pool
, &pool
->state
, block_size
);
581 /* Allocates a block out of the back of the block pool.
583 * This will allocated a block earlier than the "start" of the block pool.
584 * The offsets returned from this function will be negative but will still
585 * be correct relative to the block pool's map pointer.
587 * If you ever use anv_block_pool_alloc_back, then you will have to do
588 * gymnastics with the block pool's BO when doing relocations.
591 anv_block_pool_alloc_back(struct anv_block_pool
*pool
,
594 int32_t offset
= anv_block_pool_alloc_new(pool
, &pool
->back_state
,
597 /* The offset we get out of anv_block_pool_alloc_new() is actually the
598 * number of bytes downwards from the middle to the end of the block.
599 * We need to turn it into a (negative) offset from the middle to the
600 * start of the block.
603 return -(offset
+ block_size
);
607 anv_state_pool_init(struct anv_state_pool
*pool
,
608 struct anv_device
*device
,
611 VkResult result
= anv_block_pool_init(&pool
->block_pool
, device
,
613 if (result
!= VK_SUCCESS
)
616 assert(util_is_power_of_two(block_size
));
617 pool
->block_size
= block_size
;
618 pool
->back_alloc_free_list
= ANV_FREE_LIST_EMPTY
;
619 for (unsigned i
= 0; i
< ANV_STATE_BUCKETS
; i
++) {
620 pool
->buckets
[i
].free_list
= ANV_FREE_LIST_EMPTY
;
621 pool
->buckets
[i
].block
.next
= 0;
622 pool
->buckets
[i
].block
.end
= 0;
624 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
630 anv_state_pool_finish(struct anv_state_pool
*pool
)
632 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
633 anv_block_pool_finish(&pool
->block_pool
);
637 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool
*pool
,
638 struct anv_block_pool
*block_pool
,
642 struct anv_block_state block
, old
, new;
645 /* If our state is large, we don't need any sub-allocation from a block.
646 * Instead, we just grab whole (potentially large) blocks.
648 if (state_size
>= block_size
)
649 return anv_block_pool_alloc(block_pool
, state_size
);
652 block
.u64
= __sync_fetch_and_add(&pool
->block
.u64
, state_size
);
654 if (block
.next
< block
.end
) {
656 } else if (block
.next
== block
.end
) {
657 offset
= anv_block_pool_alloc(block_pool
, block_size
);
658 new.next
= offset
+ state_size
;
659 new.end
= offset
+ block_size
;
660 old
.u64
= __sync_lock_test_and_set(&pool
->block
.u64
, new.u64
);
661 if (old
.next
!= block
.next
)
662 futex_wake(&pool
->block
.end
, INT_MAX
);
665 futex_wait(&pool
->block
.end
, block
.end
);
671 anv_state_pool_get_bucket(uint32_t size
)
673 unsigned size_log2
= ilog2_round_up(size
);
674 assert(size_log2
<= ANV_MAX_STATE_SIZE_LOG2
);
675 if (size_log2
< ANV_MIN_STATE_SIZE_LOG2
)
676 size_log2
= ANV_MIN_STATE_SIZE_LOG2
;
677 return size_log2
- ANV_MIN_STATE_SIZE_LOG2
;
681 anv_state_pool_get_bucket_size(uint32_t bucket
)
683 uint32_t size_log2
= bucket
+ ANV_MIN_STATE_SIZE_LOG2
;
684 return 1 << size_log2
;
687 static struct anv_state
688 anv_state_pool_alloc_no_vg(struct anv_state_pool
*pool
,
689 uint32_t size
, uint32_t align
)
691 uint32_t bucket
= anv_state_pool_get_bucket(MAX2(size
, align
));
693 struct anv_state state
;
694 state
.alloc_size
= anv_state_pool_get_bucket_size(bucket
);
696 /* Try free list first. */
697 if (anv_free_list_pop(&pool
->buckets
[bucket
].free_list
,
698 &pool
->block_pool
.map
, &state
.offset
)) {
699 assert(state
.offset
>= 0);
703 /* Try to grab a chunk from some larger bucket and split it up */
704 for (unsigned b
= bucket
+ 1; b
< ANV_STATE_BUCKETS
; b
++) {
705 int32_t chunk_offset
;
706 if (anv_free_list_pop(&pool
->buckets
[b
].free_list
,
707 &pool
->block_pool
.map
, &chunk_offset
)) {
708 unsigned chunk_size
= anv_state_pool_get_bucket_size(b
);
710 /* We've found a chunk that's larger than the requested state size.
711 * There are a couple of options as to what we do with it:
713 * 1) We could fully split the chunk into state.alloc_size sized
714 * pieces. However, this would mean that allocating a 16B
715 * state could potentially split a 2MB chunk into 512K smaller
716 * chunks. This would lead to unnecessary fragmentation.
718 * 2) The classic "buddy allocator" method would have us split the
719 * chunk in half and return one half. Then we would split the
720 * remaining half in half and return one half, and repeat as
721 * needed until we get down to the size we want. However, if
722 * you are allocating a bunch of the same size state (which is
723 * the common case), this means that every other allocation has
724 * to go up a level and every fourth goes up two levels, etc.
725 * This is not nearly as efficient as it could be if we did a
726 * little more work up-front.
728 * 3) Split the difference between (1) and (2) by doing a
729 * two-level split. If it's bigger than some fixed block_size,
730 * we split it into block_size sized chunks and return all but
731 * one of them. Then we split what remains into
732 * state.alloc_size sized chunks and return all but one.
734 * We choose option (3).
736 if (chunk_size
> pool
->block_size
&&
737 state
.alloc_size
< pool
->block_size
) {
738 assert(chunk_size
% pool
->block_size
== 0);
739 /* We don't want to split giant chunks into tiny chunks. Instead,
740 * break anything bigger than a block into block-sized chunks and
741 * then break it down into bucket-sized chunks from there. Return
742 * all but the first block of the chunk to the block bucket.
744 const uint32_t block_bucket
=
745 anv_state_pool_get_bucket(pool
->block_size
);
746 anv_free_list_push(&pool
->buckets
[block_bucket
].free_list
,
747 pool
->block_pool
.map
,
748 chunk_offset
+ pool
->block_size
,
750 (chunk_size
/ pool
->block_size
) - 1);
751 chunk_size
= pool
->block_size
;
754 assert(chunk_size
% state
.alloc_size
== 0);
755 anv_free_list_push(&pool
->buckets
[bucket
].free_list
,
756 pool
->block_pool
.map
,
757 chunk_offset
+ state
.alloc_size
,
759 (chunk_size
/ state
.alloc_size
) - 1);
761 state
.offset
= chunk_offset
;
766 state
.offset
= anv_fixed_size_state_pool_alloc_new(&pool
->buckets
[bucket
],
772 state
.map
= pool
->block_pool
.map
+ state
.offset
;
777 anv_state_pool_alloc(struct anv_state_pool
*pool
, uint32_t size
, uint32_t align
)
780 return ANV_STATE_NULL
;
782 struct anv_state state
= anv_state_pool_alloc_no_vg(pool
, size
, align
);
783 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
.map
, size
));
788 anv_state_pool_alloc_back(struct anv_state_pool
*pool
)
790 struct anv_state state
;
791 state
.alloc_size
= pool
->block_size
;
793 if (anv_free_list_pop(&pool
->back_alloc_free_list
,
794 &pool
->block_pool
.map
, &state
.offset
)) {
795 assert(state
.offset
< 0);
799 state
.offset
= anv_block_pool_alloc_back(&pool
->block_pool
,
803 state
.map
= pool
->block_pool
.map
+ state
.offset
;
804 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
.map
, state
.alloc_size
));
809 anv_state_pool_free_no_vg(struct anv_state_pool
*pool
, struct anv_state state
)
811 assert(util_is_power_of_two(state
.alloc_size
));
812 unsigned bucket
= anv_state_pool_get_bucket(state
.alloc_size
);
814 if (state
.offset
< 0) {
815 assert(state
.alloc_size
== pool
->block_size
);
816 anv_free_list_push(&pool
->back_alloc_free_list
,
817 pool
->block_pool
.map
, state
.offset
,
818 state
.alloc_size
, 1);
820 anv_free_list_push(&pool
->buckets
[bucket
].free_list
,
821 pool
->block_pool
.map
, state
.offset
,
822 state
.alloc_size
, 1);
827 anv_state_pool_free(struct anv_state_pool
*pool
, struct anv_state state
)
829 if (state
.alloc_size
== 0)
832 VG(VALGRIND_MEMPOOL_FREE(pool
, state
.map
));
833 anv_state_pool_free_no_vg(pool
, state
);
836 struct anv_state_stream_block
{
837 struct anv_state block
;
840 struct anv_state_stream_block
*next
;
843 /* A pointer to the first user-allocated thing in this block. This is
844 * what valgrind sees as the start of the block.
850 /* The state stream allocator is a one-shot, single threaded allocator for
851 * variable sized blocks. We use it for allocating dynamic state.
854 anv_state_stream_init(struct anv_state_stream
*stream
,
855 struct anv_state_pool
*state_pool
,
858 stream
->state_pool
= state_pool
;
859 stream
->block_size
= block_size
;
861 stream
->block
= ANV_STATE_NULL
;
863 stream
->block_list
= NULL
;
865 /* Ensure that next + whatever > block_size. This way the first call to
866 * state_stream_alloc fetches a new block.
868 stream
->next
= block_size
;
870 VG(VALGRIND_CREATE_MEMPOOL(stream
, 0, false));
874 anv_state_stream_finish(struct anv_state_stream
*stream
)
876 struct anv_state_stream_block
*next
= stream
->block_list
;
877 while (next
!= NULL
) {
878 struct anv_state_stream_block sb
= VG_NOACCESS_READ(next
);
879 VG(VALGRIND_MEMPOOL_FREE(stream
, sb
._vg_ptr
));
880 VG(VALGRIND_MAKE_MEM_UNDEFINED(next
, stream
->block_size
));
881 anv_state_pool_free_no_vg(stream
->state_pool
, sb
.block
);
885 VG(VALGRIND_DESTROY_MEMPOOL(stream
));
889 anv_state_stream_alloc(struct anv_state_stream
*stream
,
890 uint32_t size
, uint32_t alignment
)
893 return ANV_STATE_NULL
;
895 assert(alignment
<= PAGE_SIZE
);
897 uint32_t offset
= align_u32(stream
->next
, alignment
);
898 if (offset
+ size
> stream
->block
.alloc_size
) {
899 uint32_t block_size
= stream
->block_size
;
900 if (block_size
< size
)
901 block_size
= round_to_power_of_two(size
);
903 stream
->block
= anv_state_pool_alloc_no_vg(stream
->state_pool
,
904 block_size
, PAGE_SIZE
);
906 struct anv_state_stream_block
*sb
= stream
->block
.map
;
907 VG_NOACCESS_WRITE(&sb
->block
, stream
->block
);
908 VG_NOACCESS_WRITE(&sb
->next
, stream
->block_list
);
909 stream
->block_list
= sb
;
910 VG(VG_NOACCESS_WRITE(&sb
->_vg_ptr
, NULL
));
912 VG(VALGRIND_MAKE_MEM_NOACCESS(stream
->block
.map
, stream
->block_size
));
914 /* Reset back to the start plus space for the header */
915 stream
->next
= sizeof(*sb
);
917 offset
= align_u32(stream
->next
, alignment
);
918 assert(offset
+ size
<= stream
->block
.alloc_size
);
921 struct anv_state state
= stream
->block
;
922 state
.offset
+= offset
;
923 state
.alloc_size
= size
;
926 stream
->next
= offset
+ size
;
929 struct anv_state_stream_block
*sb
= stream
->block_list
;
930 void *vg_ptr
= VG_NOACCESS_READ(&sb
->_vg_ptr
);
931 if (vg_ptr
== NULL
) {
933 VG_NOACCESS_WRITE(&sb
->_vg_ptr
, vg_ptr
);
934 VALGRIND_MEMPOOL_ALLOC(stream
, vg_ptr
, size
);
936 void *state_end
= state
.map
+ state
.alloc_size
;
937 /* This only updates the mempool. The newly allocated chunk is still
938 * marked as NOACCESS. */
939 VALGRIND_MEMPOOL_CHANGE(stream
, vg_ptr
, vg_ptr
, state_end
- vg_ptr
);
940 /* Mark the newly allocated chunk as undefined */
941 VALGRIND_MAKE_MEM_UNDEFINED(state
.map
, state
.alloc_size
);
948 struct bo_pool_bo_link
{
949 struct bo_pool_bo_link
*next
;
954 anv_bo_pool_init(struct anv_bo_pool
*pool
, struct anv_device
*device
)
956 pool
->device
= device
;
957 memset(pool
->free_list
, 0, sizeof(pool
->free_list
));
959 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
963 anv_bo_pool_finish(struct anv_bo_pool
*pool
)
965 for (unsigned i
= 0; i
< ARRAY_SIZE(pool
->free_list
); i
++) {
966 struct bo_pool_bo_link
*link
= PFL_PTR(pool
->free_list
[i
]);
967 while (link
!= NULL
) {
968 struct bo_pool_bo_link link_copy
= VG_NOACCESS_READ(link
);
970 anv_gem_munmap(link_copy
.bo
.map
, link_copy
.bo
.size
);
971 anv_gem_close(pool
->device
, link_copy
.bo
.gem_handle
);
972 link
= link_copy
.next
;
976 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
980 anv_bo_pool_alloc(struct anv_bo_pool
*pool
, struct anv_bo
*bo
, uint32_t size
)
984 const unsigned size_log2
= size
< 4096 ? 12 : ilog2_round_up(size
);
985 const unsigned pow2_size
= 1 << size_log2
;
986 const unsigned bucket
= size_log2
- 12;
987 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
989 void *next_free_void
;
990 if (anv_ptr_free_list_pop(&pool
->free_list
[bucket
], &next_free_void
)) {
991 struct bo_pool_bo_link
*next_free
= next_free_void
;
992 *bo
= VG_NOACCESS_READ(&next_free
->bo
);
993 assert(bo
->gem_handle
);
994 assert(bo
->map
== next_free
);
995 assert(size
<= bo
->size
);
997 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1002 struct anv_bo new_bo
;
1004 result
= anv_bo_init_new(&new_bo
, pool
->device
, pow2_size
);
1005 if (result
!= VK_SUCCESS
)
1008 if (pool
->device
->instance
->physicalDevice
.supports_48bit_addresses
)
1009 new_bo
.flags
|= EXEC_OBJECT_SUPPORTS_48B_ADDRESS
;
1011 if (pool
->device
->instance
->physicalDevice
.has_exec_async
)
1012 new_bo
.flags
|= EXEC_OBJECT_ASYNC
;
1014 assert(new_bo
.size
== pow2_size
);
1016 new_bo
.map
= anv_gem_mmap(pool
->device
, new_bo
.gem_handle
, 0, pow2_size
, 0);
1017 if (new_bo
.map
== MAP_FAILED
) {
1018 anv_gem_close(pool
->device
, new_bo
.gem_handle
);
1019 return vk_error(VK_ERROR_MEMORY_MAP_FAILED
);
1024 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
1030 anv_bo_pool_free(struct anv_bo_pool
*pool
, const struct anv_bo
*bo_in
)
1032 /* Make a copy in case the anv_bo happens to be storred in the BO */
1033 struct anv_bo bo
= *bo_in
;
1035 VG(VALGRIND_MEMPOOL_FREE(pool
, bo
.map
));
1037 struct bo_pool_bo_link
*link
= bo
.map
;
1038 VG_NOACCESS_WRITE(&link
->bo
, bo
);
1040 assert(util_is_power_of_two(bo
.size
));
1041 const unsigned size_log2
= ilog2_round_up(bo
.size
);
1042 const unsigned bucket
= size_log2
- 12;
1043 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
1045 anv_ptr_free_list_push(&pool
->free_list
[bucket
], link
);
1051 anv_scratch_pool_init(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1053 memset(pool
, 0, sizeof(*pool
));
1057 anv_scratch_pool_finish(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
1059 for (unsigned s
= 0; s
< MESA_SHADER_STAGES
; s
++) {
1060 for (unsigned i
= 0; i
< 16; i
++) {
1061 struct anv_scratch_bo
*bo
= &pool
->bos
[i
][s
];
1063 anv_gem_close(device
, bo
->bo
.gem_handle
);
1069 anv_scratch_pool_alloc(struct anv_device
*device
, struct anv_scratch_pool
*pool
,
1070 gl_shader_stage stage
, unsigned per_thread_scratch
)
1072 if (per_thread_scratch
== 0)
1075 unsigned scratch_size_log2
= ffs(per_thread_scratch
/ 2048);
1076 assert(scratch_size_log2
< 16);
1078 struct anv_scratch_bo
*bo
= &pool
->bos
[scratch_size_log2
][stage
];
1080 /* We can use "exists" to shortcut and ignore the critical section */
1084 pthread_mutex_lock(&device
->mutex
);
1086 __sync_synchronize();
1090 const struct anv_physical_device
*physical_device
=
1091 &device
->instance
->physicalDevice
;
1092 const struct gen_device_info
*devinfo
= &physical_device
->info
;
1094 /* WaCSScratchSize:hsw
1096 * Haswell's scratch space address calculation appears to be sparse
1097 * rather than tightly packed. The Thread ID has bits indicating which
1098 * subslice, EU within a subslice, and thread within an EU it is.
1099 * There's a maximum of two slices and two subslices, so these can be
1100 * stored with a single bit. Even though there are only 10 EUs per
1101 * subslice, this is stored in 4 bits, so there's an effective maximum
1102 * value of 16 EUs. Similarly, although there are only 7 threads per EU,
1103 * this is stored in a 3 bit number, giving an effective maximum value
1104 * of 8 threads per EU.
1106 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1107 * number of threads per subslice.
1109 const unsigned subslices
= MAX2(physical_device
->subslice_total
, 1);
1110 const unsigned scratch_ids_per_subslice
=
1111 device
->info
.is_haswell
? 16 * 8 : devinfo
->max_cs_threads
;
1113 uint32_t max_threads
[] = {
1114 [MESA_SHADER_VERTEX
] = devinfo
->max_vs_threads
,
1115 [MESA_SHADER_TESS_CTRL
] = devinfo
->max_tcs_threads
,
1116 [MESA_SHADER_TESS_EVAL
] = devinfo
->max_tes_threads
,
1117 [MESA_SHADER_GEOMETRY
] = devinfo
->max_gs_threads
,
1118 [MESA_SHADER_FRAGMENT
] = devinfo
->max_wm_threads
,
1119 [MESA_SHADER_COMPUTE
] = scratch_ids_per_subslice
* subslices
,
1122 uint32_t size
= per_thread_scratch
* max_threads
[stage
];
1124 anv_bo_init_new(&bo
->bo
, device
, size
);
1126 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1127 * are still relative to the general state base address. When we emit
1128 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1129 * to the maximum (1 page under 4GB). This allows us to just place the
1130 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1131 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1132 * However, in order to do so, we need to ensure that the kernel does not
1133 * place the scratch BO above the 32-bit boundary.
1135 * NOTE: Technically, it can't go "anywhere" because the top page is off
1136 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1137 * kernel allocates space using
1139 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1141 * so nothing will ever touch the top page.
1143 assert(!(bo
->bo
.flags
& EXEC_OBJECT_SUPPORTS_48B_ADDRESS
));
1145 if (device
->instance
->physicalDevice
.has_exec_async
)
1146 bo
->bo
.flags
|= EXEC_OBJECT_ASYNC
;
1148 /* Set the exists last because it may be read by other threads */
1149 __sync_synchronize();
1152 pthread_mutex_unlock(&device
->mutex
);
1157 struct anv_cached_bo
{
1164 anv_bo_cache_init(struct anv_bo_cache
*cache
)
1166 cache
->bo_map
= _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1167 _mesa_key_pointer_equal
);
1169 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1171 if (pthread_mutex_init(&cache
->mutex
, NULL
)) {
1172 _mesa_hash_table_destroy(cache
->bo_map
, NULL
);
1173 return vk_errorf(NULL
, NULL
, VK_ERROR_OUT_OF_HOST_MEMORY
,
1174 "pthread_mutex_init failed: %m");
1181 anv_bo_cache_finish(struct anv_bo_cache
*cache
)
1183 _mesa_hash_table_destroy(cache
->bo_map
, NULL
);
1184 pthread_mutex_destroy(&cache
->mutex
);
1187 static struct anv_cached_bo
*
1188 anv_bo_cache_lookup_locked(struct anv_bo_cache
*cache
, uint32_t gem_handle
)
1190 struct hash_entry
*entry
=
1191 _mesa_hash_table_search(cache
->bo_map
,
1192 (const void *)(uintptr_t)gem_handle
);
1196 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)entry
->data
;
1197 assert(bo
->bo
.gem_handle
== gem_handle
);
1202 UNUSED
static struct anv_bo
*
1203 anv_bo_cache_lookup(struct anv_bo_cache
*cache
, uint32_t gem_handle
)
1205 pthread_mutex_lock(&cache
->mutex
);
1207 struct anv_cached_bo
*bo
= anv_bo_cache_lookup_locked(cache
, gem_handle
);
1209 pthread_mutex_unlock(&cache
->mutex
);
1211 return bo
? &bo
->bo
: NULL
;
1215 anv_bo_cache_alloc(struct anv_device
*device
,
1216 struct anv_bo_cache
*cache
,
1217 uint64_t size
, struct anv_bo
**bo_out
)
1219 struct anv_cached_bo
*bo
=
1220 vk_alloc(&device
->alloc
, sizeof(struct anv_cached_bo
), 8,
1221 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT
);
1223 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1227 /* The kernel is going to give us whole pages anyway */
1228 size
= align_u64(size
, 4096);
1230 VkResult result
= anv_bo_init_new(&bo
->bo
, device
, size
);
1231 if (result
!= VK_SUCCESS
) {
1232 vk_free(&device
->alloc
, bo
);
1236 assert(bo
->bo
.gem_handle
);
1238 pthread_mutex_lock(&cache
->mutex
);
1240 _mesa_hash_table_insert(cache
->bo_map
,
1241 (void *)(uintptr_t)bo
->bo
.gem_handle
, bo
);
1243 pthread_mutex_unlock(&cache
->mutex
);
1251 anv_bo_cache_import(struct anv_device
*device
,
1252 struct anv_bo_cache
*cache
,
1253 int fd
, struct anv_bo
**bo_out
)
1255 pthread_mutex_lock(&cache
->mutex
);
1257 uint32_t gem_handle
= anv_gem_fd_to_handle(device
, fd
);
1259 pthread_mutex_unlock(&cache
->mutex
);
1260 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR
);
1263 struct anv_cached_bo
*bo
= anv_bo_cache_lookup_locked(cache
, gem_handle
);
1265 __sync_fetch_and_add(&bo
->refcount
, 1);
1267 off_t size
= lseek(fd
, 0, SEEK_END
);
1268 if (size
== (off_t
)-1) {
1269 anv_gem_close(device
, gem_handle
);
1270 pthread_mutex_unlock(&cache
->mutex
);
1271 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR
);
1274 bo
= vk_alloc(&device
->alloc
, sizeof(struct anv_cached_bo
), 8,
1275 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT
);
1277 anv_gem_close(device
, gem_handle
);
1278 pthread_mutex_unlock(&cache
->mutex
);
1279 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1284 anv_bo_init(&bo
->bo
, gem_handle
, size
);
1286 _mesa_hash_table_insert(cache
->bo_map
, (void *)(uintptr_t)gem_handle
, bo
);
1289 pthread_mutex_unlock(&cache
->mutex
);
1296 anv_bo_cache_export(struct anv_device
*device
,
1297 struct anv_bo_cache
*cache
,
1298 struct anv_bo
*bo_in
, int *fd_out
)
1300 assert(anv_bo_cache_lookup(cache
, bo_in
->gem_handle
) == bo_in
);
1301 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)bo_in
;
1303 int fd
= anv_gem_handle_to_fd(device
, bo
->bo
.gem_handle
);
1305 return vk_error(VK_ERROR_TOO_MANY_OBJECTS
);
1313 atomic_dec_not_one(uint32_t *counter
)
1322 old
= __sync_val_compare_and_swap(counter
, val
, val
- 1);
1331 anv_bo_cache_release(struct anv_device
*device
,
1332 struct anv_bo_cache
*cache
,
1333 struct anv_bo
*bo_in
)
1335 assert(anv_bo_cache_lookup(cache
, bo_in
->gem_handle
) == bo_in
);
1336 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)bo_in
;
1338 /* Try to decrement the counter but don't go below one. If this succeeds
1339 * then the refcount has been decremented and we are not the last
1342 if (atomic_dec_not_one(&bo
->refcount
))
1345 pthread_mutex_lock(&cache
->mutex
);
1347 /* We are probably the last reference since our attempt to decrement above
1348 * failed. However, we can't actually know until we are inside the mutex.
1349 * Otherwise, someone could import the BO between the decrement and our
1352 if (unlikely(__sync_sub_and_fetch(&bo
->refcount
, 1) > 0)) {
1353 /* Turns out we're not the last reference. Unlock and bail. */
1354 pthread_mutex_unlock(&cache
->mutex
);
1358 struct hash_entry
*entry
=
1359 _mesa_hash_table_search(cache
->bo_map
,
1360 (const void *)(uintptr_t)bo
->bo
.gem_handle
);
1362 _mesa_hash_table_remove(cache
->bo_map
, entry
);
1365 anv_gem_munmap(bo
->bo
.map
, bo
->bo
.size
);
1367 anv_gem_close(device
, bo
->bo
.gem_handle
);
1369 /* Don't unlock until we've actually closed the BO. The whole point of
1370 * the BO cache is to ensure that we correctly handle races with creating
1371 * and releasing GEM handles and we don't want to let someone import the BO
1372 * again between mutex unlock and closing the GEM handle.
1374 pthread_mutex_unlock(&cache
->mutex
);
1376 vk_free(&device
->alloc
, bo
);