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
29 #include <linux/futex.h>
30 #include <linux/memfd.h>
33 #include <sys/syscall.h>
35 #include "anv_private.h"
37 #include "util/hash_table.h"
40 #define VG_NOACCESS_READ(__ptr) ({ \
41 VALGRIND_MAKE_MEM_DEFINED((__ptr), sizeof(*(__ptr))); \
42 __typeof(*(__ptr)) __val = *(__ptr); \
43 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr)));\
46 #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
47 VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
49 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
52 #define VG_NOACCESS_READ(__ptr) (*(__ptr))
53 #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
58 * - Lock free (except when resizing underlying bos)
60 * - Constant time allocation with typically only one atomic
62 * - Multiple allocation sizes without fragmentation
64 * - Can grow while keeping addresses and offset of contents stable
66 * - All allocations within one bo so we can point one of the
67 * STATE_BASE_ADDRESS pointers at it.
69 * The overall design is a two-level allocator: top level is a fixed size, big
70 * block (8k) allocator, which operates out of a bo. Allocation is done by
71 * either pulling a block from the free list or growing the used range of the
72 * bo. Growing the range may run out of space in the bo which we then need to
73 * grow. Growing the bo is tricky in a multi-threaded, lockless environment:
74 * we need to keep all pointers and contents in the old map valid. GEM bos in
75 * general can't grow, but we use a trick: we create a memfd and use ftruncate
76 * to grow it as necessary. We mmap the new size and then create a gem bo for
77 * it using the new gem userptr ioctl. Without heavy-handed locking around
78 * our allocation fast-path, there isn't really a way to munmap the old mmap,
79 * so we just keep it around until garbage collection time. While the block
80 * allocator is lockless for normal operations, we block other threads trying
81 * to allocate while we're growing the map. It sholdn't happen often, and
82 * growing is fast anyway.
84 * At the next level we can use various sub-allocators. The state pool is a
85 * pool of smaller, fixed size objects, which operates much like the block
86 * pool. It uses a free list for freeing objects, but when it runs out of
87 * space it just allocates a new block from the block pool. This allocator is
88 * intended for longer lived state objects such as SURFACE_STATE and most
89 * other persistent state objects in the API. We may need to track more info
90 * with these object and a pointer back to the CPU object (eg VkImage). In
91 * those cases we just allocate a slightly bigger object and put the extra
92 * state after the GPU state object.
94 * The state stream allocator works similar to how the i965 DRI driver streams
95 * all its state. Even with Vulkan, we need to emit transient state (whether
96 * surface state base or dynamic state base), and for that we can just get a
97 * block and fill it up. These cases are local to a command buffer and the
98 * sub-allocator need not be thread safe. The streaming allocator gets a new
99 * block when it runs out of space and chains them together so they can be
103 /* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
104 * We use it to indicate the free list is empty. */
107 struct anv_mmap_cleanup
{
113 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
116 sys_futex(void *addr1
, int op
, int val1
,
117 struct timespec
*timeout
, void *addr2
, int val3
)
119 return syscall(SYS_futex
, addr1
, op
, val1
, timeout
, addr2
, val3
);
123 futex_wake(uint32_t *addr
, int count
)
125 return sys_futex(addr
, FUTEX_WAKE
, count
, NULL
, NULL
, 0);
129 futex_wait(uint32_t *addr
, int32_t value
)
131 return sys_futex(addr
, FUTEX_WAIT
, value
, NULL
, NULL
, 0);
135 memfd_create(const char *name
, unsigned int flags
)
137 return syscall(SYS_memfd_create
, name
, flags
);
140 static inline uint32_t
141 ilog2_round_up(uint32_t value
)
144 return 32 - __builtin_clz(value
- 1);
147 static inline uint32_t
148 round_to_power_of_two(uint32_t value
)
150 return 1 << ilog2_round_up(value
);
154 anv_free_list_pop(union anv_free_list
*list
, void **map
, int32_t *offset
)
156 union anv_free_list current
, new, old
;
158 current
.u64
= list
->u64
;
159 while (current
.offset
!= EMPTY
) {
160 /* We have to add a memory barrier here so that the list head (and
161 * offset) gets read before we read the map pointer. This way we
162 * know that the map pointer is valid for the given offset at the
163 * point where we read it.
165 __sync_synchronize();
167 int32_t *next_ptr
= *map
+ current
.offset
;
168 new.offset
= VG_NOACCESS_READ(next_ptr
);
169 new.count
= current
.count
+ 1;
170 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
171 if (old
.u64
== current
.u64
) {
172 *offset
= current
.offset
;
182 anv_free_list_push(union anv_free_list
*list
, void *map
, int32_t offset
)
184 union anv_free_list current
, old
, new;
185 int32_t *next_ptr
= map
+ offset
;
190 VG_NOACCESS_WRITE(next_ptr
, current
.offset
);
192 new.count
= current
.count
+ 1;
193 old
.u64
= __sync_val_compare_and_swap(&list
->u64
, current
.u64
, new.u64
);
194 } while (old
.u64
!= current
.u64
);
197 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
198 * means that the bottom 12 bits should all be zero.
200 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
201 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
202 #define PFL_PACK(ptr, count) ({ \
203 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
207 anv_ptr_free_list_pop(void **list
, void **elem
)
209 void *current
= *list
;
210 while (PFL_PTR(current
) != NULL
) {
211 void **next_ptr
= PFL_PTR(current
);
212 void *new_ptr
= VG_NOACCESS_READ(next_ptr
);
213 unsigned new_count
= PFL_COUNT(current
) + 1;
214 void *new = PFL_PACK(new_ptr
, new_count
);
215 void *old
= __sync_val_compare_and_swap(list
, current
, new);
216 if (old
== current
) {
217 *elem
= PFL_PTR(current
);
227 anv_ptr_free_list_push(void **list
, void *elem
)
230 void **next_ptr
= elem
;
232 /* The pointer-based free list requires that the pointer be
233 * page-aligned. This is because we use the bottom 12 bits of the
234 * pointer to store a counter to solve the ABA concurrency problem.
236 assert(((uintptr_t)elem
& 0xfff) == 0);
241 VG_NOACCESS_WRITE(next_ptr
, PFL_PTR(current
));
242 unsigned new_count
= PFL_COUNT(current
) + 1;
243 void *new = PFL_PACK(elem
, new_count
);
244 old
= __sync_val_compare_and_swap(list
, current
, new);
245 } while (old
!= current
);
249 anv_block_pool_grow(struct anv_block_pool
*pool
, struct anv_block_state
*state
);
252 anv_block_pool_init(struct anv_block_pool
*pool
,
253 struct anv_device
*device
, uint32_t block_size
)
257 assert(util_is_power_of_two(block_size
));
259 pool
->device
= device
;
260 anv_bo_init(&pool
->bo
, 0, 0);
261 pool
->block_size
= block_size
;
262 pool
->free_list
= ANV_FREE_LIST_EMPTY
;
263 pool
->back_free_list
= ANV_FREE_LIST_EMPTY
;
265 pool
->fd
= memfd_create("block pool", MFD_CLOEXEC
);
267 return vk_error(VK_ERROR_INITIALIZATION_FAILED
);
269 /* Just make it 2GB up-front. The Linux kernel won't actually back it
270 * with pages until we either map and fault on one of them or we use
271 * userptr and send a chunk of it off to the GPU.
273 if (ftruncate(pool
->fd
, BLOCK_POOL_MEMFD_SIZE
) == -1) {
274 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
278 if (!u_vector_init(&pool
->mmap_cleanups
,
279 round_to_power_of_two(sizeof(struct anv_mmap_cleanup
)),
281 result
= vk_error(VK_ERROR_INITIALIZATION_FAILED
);
285 pool
->state
.next
= 0;
287 pool
->back_state
.next
= 0;
288 pool
->back_state
.end
= 0;
290 /* Immediately grow the pool so we'll have a backing bo. */
291 pool
->state
.end
= anv_block_pool_grow(pool
, &pool
->state
);
302 anv_block_pool_finish(struct anv_block_pool
*pool
)
304 struct anv_mmap_cleanup
*cleanup
;
306 u_vector_foreach(cleanup
, &pool
->mmap_cleanups
) {
308 munmap(cleanup
->map
, cleanup
->size
);
309 if (cleanup
->gem_handle
)
310 anv_gem_close(pool
->device
, cleanup
->gem_handle
);
313 u_vector_finish(&pool
->mmap_cleanups
);
318 #define PAGE_SIZE 4096
321 anv_block_pool_expand_range(struct anv_block_pool
*pool
,
322 uint32_t center_bo_offset
, uint32_t size
)
326 struct anv_mmap_cleanup
*cleanup
;
328 /* Assert that we only ever grow the pool */
329 assert(center_bo_offset
>= pool
->back_state
.end
);
330 assert(size
- center_bo_offset
>= pool
->state
.end
);
332 cleanup
= u_vector_add(&pool
->mmap_cleanups
);
334 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
336 *cleanup
= ANV_MMAP_CLEANUP_INIT
;
338 /* Just leak the old map until we destroy the pool. We can't munmap it
339 * without races or imposing locking on the block allocate fast path. On
340 * the whole the leaked maps adds up to less than the size of the
341 * current map. MAP_POPULATE seems like the right thing to do, but we
342 * should try to get some numbers.
344 map
= mmap(NULL
, size
, PROT_READ
| PROT_WRITE
,
345 MAP_SHARED
| MAP_POPULATE
, pool
->fd
,
346 BLOCK_POOL_MEMFD_CENTER
- center_bo_offset
);
347 if (map
== MAP_FAILED
)
348 return vk_errorf(VK_ERROR_MEMORY_MAP_FAILED
, "mmap failed: %m");
350 gem_handle
= anv_gem_userptr(pool
->device
, map
, size
);
351 if (gem_handle
== 0) {
353 return vk_errorf(VK_ERROR_TOO_MANY_OBJECTS
, "userptr failed: %m");
357 cleanup
->size
= size
;
358 cleanup
->gem_handle
= gem_handle
;
361 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
362 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
363 * always created as I915_CACHING_CACHED, which on non-LLC means
364 * snooped. That can be useful but comes with a bit of overheard. Since
365 * we're eplicitly clflushing and don't want the overhead we need to turn
367 if (!pool
->device
->info
.has_llc
) {
368 anv_gem_set_caching(pool
->device
, gem_handle
, I915_CACHING_NONE
);
369 anv_gem_set_domain(pool
->device
, gem_handle
,
370 I915_GEM_DOMAIN_GTT
, I915_GEM_DOMAIN_GTT
);
374 /* Now that we successfull allocated everything, we can write the new
375 * values back into pool. */
376 pool
->map
= map
+ center_bo_offset
;
377 pool
->center_bo_offset
= center_bo_offset
;
379 /* For block pool BOs we have to be a bit careful about where we place them
380 * in the GTT. There are two documented workarounds for state base address
381 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
382 * which state that those two base addresses do not support 48-bit
383 * addresses and need to be placed in the bottom 32-bit range.
384 * Unfortunately, this is not quite accurate.
386 * The real problem is that we always set the size of our state pools in
387 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
388 * likely significantly smaller. We do this because we do not no at the
389 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
390 * the pool during command buffer building so we don't actually have a
391 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
392 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
393 * as being out of bounds and returns zero. For dynamic state, this
394 * usually just leads to rendering corruptions, but shaders that are all
395 * zero hang the GPU immediately.
397 * The easiest solution to do is exactly what the bogus workarounds say to
398 * do: restrict these buffers to 32-bit addresses. We could also pin the
399 * BO to some particular location of our choosing, but that's significantly
400 * more work than just not setting a flag. So, we explicitly DO NOT set
401 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
404 anv_bo_init(&pool
->bo
, gem_handle
, size
);
410 /** Grows and re-centers the block pool.
412 * We grow the block pool in one or both directions in such a way that the
413 * following conditions are met:
415 * 1) The size of the entire pool is always a power of two.
417 * 2) The pool only grows on both ends. Neither end can get
420 * 3) At the end of the allocation, we have about twice as much space
421 * allocated for each end as we have used. This way the pool doesn't
422 * grow too far in one direction or the other.
424 * 4) If the _alloc_back() has never been called, then the back portion of
425 * the pool retains a size of zero. (This makes it easier for users of
426 * the block pool that only want a one-sided pool.)
428 * 5) We have enough space allocated for at least one more block in
429 * whichever side `state` points to.
431 * 6) The center of the pool is always aligned to both the block_size of
432 * the pool and a 4K CPU page.
435 anv_block_pool_grow(struct anv_block_pool
*pool
, struct anv_block_state
*state
)
438 VkResult result
= VK_SUCCESS
;
440 pthread_mutex_lock(&pool
->device
->mutex
);
442 assert(state
== &pool
->state
|| state
== &pool
->back_state
);
444 /* Gather a little usage information on the pool. Since we may have
445 * threadsd waiting in queue to get some storage while we resize, it's
446 * actually possible that total_used will be larger than old_size. In
447 * particular, block_pool_alloc() increments state->next prior to
448 * calling block_pool_grow, so this ensures that we get enough space for
449 * which ever side tries to grow the pool.
451 * We align to a page size because it makes it easier to do our
452 * calculations later in such a way that we state page-aigned.
454 uint32_t back_used
= align_u32(pool
->back_state
.next
, PAGE_SIZE
);
455 uint32_t front_used
= align_u32(pool
->state
.next
, PAGE_SIZE
);
456 uint32_t total_used
= front_used
+ back_used
;
458 assert(state
== &pool
->state
|| back_used
> 0);
460 uint32_t old_size
= pool
->bo
.size
;
463 back_used
* 2 <= pool
->center_bo_offset
&&
464 front_used
* 2 <= (old_size
- pool
->center_bo_offset
)) {
465 /* If we're in this case then this isn't the firsta allocation and we
466 * already have enough space on both sides to hold double what we
467 * have allocated. There's nothing for us to do.
473 /* This is the first allocation */
474 size
= MAX2(32 * pool
->block_size
, PAGE_SIZE
);
479 /* We can't have a block pool bigger than 1GB because we use signed
480 * 32-bit offsets in the free list and we don't want overflow. We
481 * should never need a block pool bigger than 1GB anyway.
483 assert(size
<= (1u << 31));
485 /* We compute a new center_bo_offset such that, when we double the size
486 * of the pool, we maintain the ratio of how much is used by each side.
487 * This way things should remain more-or-less balanced.
489 uint32_t center_bo_offset
;
490 if (back_used
== 0) {
491 /* If we're in this case then we have never called alloc_back(). In
492 * this case, we want keep the offset at 0 to make things as simple
493 * as possible for users that don't care about back allocations.
495 center_bo_offset
= 0;
497 /* Try to "center" the allocation based on how much is currently in
498 * use on each side of the center line.
500 center_bo_offset
= ((uint64_t)size
* back_used
) / total_used
;
502 /* Align down to a multiple of both the block size and page size */
503 uint32_t granularity
= MAX2(pool
->block_size
, PAGE_SIZE
);
504 assert(util_is_power_of_two(granularity
));
505 center_bo_offset
&= ~(granularity
- 1);
507 assert(center_bo_offset
>= back_used
);
509 /* Make sure we don't shrink the back end of the pool */
510 if (center_bo_offset
< pool
->back_state
.end
)
511 center_bo_offset
= pool
->back_state
.end
;
513 /* Make sure that we don't shrink the front end of the pool */
514 if (size
- center_bo_offset
< pool
->state
.end
)
515 center_bo_offset
= size
- pool
->state
.end
;
518 assert(center_bo_offset
% pool
->block_size
== 0);
519 assert(center_bo_offset
% PAGE_SIZE
== 0);
521 result
= anv_block_pool_expand_range(pool
, center_bo_offset
, size
);
523 if (pool
->device
->instance
->physicalDevice
.has_exec_async
)
524 pool
->bo
.flags
|= EXEC_OBJECT_ASYNC
;
527 pthread_mutex_unlock(&pool
->device
->mutex
);
529 if (result
== VK_SUCCESS
) {
530 /* Return the appropriate new size. This function never actually
531 * updates state->next. Instead, we let the caller do that because it
532 * needs to do so in order to maintain its concurrency model.
534 if (state
== &pool
->state
) {
535 return pool
->bo
.size
- pool
->center_bo_offset
;
537 assert(pool
->center_bo_offset
> 0);
538 return pool
->center_bo_offset
;
546 anv_block_pool_alloc_new(struct anv_block_pool
*pool
,
547 struct anv_block_state
*pool_state
)
549 struct anv_block_state state
, old
, new;
552 state
.u64
= __sync_fetch_and_add(&pool_state
->u64
, pool
->block_size
);
553 if (state
.next
< state
.end
) {
556 } else if (state
.next
== state
.end
) {
557 /* We allocated the first block outside the pool, we have to grow it.
558 * pool_state->next acts a mutex: threads who try to allocate now will
559 * get block indexes above the current limit and hit futex_wait
561 new.next
= state
.next
+ pool
->block_size
;
562 new.end
= anv_block_pool_grow(pool
, pool_state
);
563 assert(new.end
>= new.next
&& new.end
% pool
->block_size
== 0);
564 old
.u64
= __sync_lock_test_and_set(&pool_state
->u64
, new.u64
);
565 if (old
.next
!= state
.next
)
566 futex_wake(&pool_state
->end
, INT_MAX
);
569 futex_wait(&pool_state
->end
, state
.end
);
576 anv_block_pool_alloc(struct anv_block_pool
*pool
)
580 /* Try free list first. */
581 if (anv_free_list_pop(&pool
->free_list
, &pool
->map
, &offset
)) {
587 return anv_block_pool_alloc_new(pool
, &pool
->state
);
590 /* Allocates a block out of the back of the block pool.
592 * This will allocated a block earlier than the "start" of the block pool.
593 * The offsets returned from this function will be negative but will still
594 * be correct relative to the block pool's map pointer.
596 * If you ever use anv_block_pool_alloc_back, then you will have to do
597 * gymnastics with the block pool's BO when doing relocations.
600 anv_block_pool_alloc_back(struct anv_block_pool
*pool
)
604 /* Try free list first. */
605 if (anv_free_list_pop(&pool
->back_free_list
, &pool
->map
, &offset
)) {
611 offset
= anv_block_pool_alloc_new(pool
, &pool
->back_state
);
613 /* The offset we get out of anv_block_pool_alloc_new() is actually the
614 * number of bytes downwards from the middle to the end of the block.
615 * We need to turn it into a (negative) offset from the middle to the
616 * start of the block.
619 return -(offset
+ pool
->block_size
);
623 anv_block_pool_free(struct anv_block_pool
*pool
, int32_t offset
)
626 anv_free_list_push(&pool
->back_free_list
, pool
->map
, offset
);
628 anv_free_list_push(&pool
->free_list
, pool
->map
, offset
);
633 anv_state_pool_init(struct anv_state_pool
*pool
,
634 struct anv_block_pool
*block_pool
)
636 pool
->block_pool
= block_pool
;
637 for (unsigned i
= 0; i
< ANV_STATE_BUCKETS
; i
++) {
638 pool
->buckets
[i
].free_list
= ANV_FREE_LIST_EMPTY
;
639 pool
->buckets
[i
].block
.next
= 0;
640 pool
->buckets
[i
].block
.end
= 0;
642 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
646 anv_state_pool_finish(struct anv_state_pool
*pool
)
648 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
652 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool
*pool
,
653 struct anv_block_pool
*block_pool
,
656 struct anv_block_state block
, old
, new;
660 block
.u64
= __sync_fetch_and_add(&pool
->block
.u64
, state_size
);
662 if (block
.next
< block
.end
) {
664 } else if (block
.next
== block
.end
) {
665 offset
= anv_block_pool_alloc(block_pool
);
666 new.next
= offset
+ state_size
;
667 new.end
= offset
+ block_pool
->block_size
;
668 old
.u64
= __sync_lock_test_and_set(&pool
->block
.u64
, new.u64
);
669 if (old
.next
!= block
.next
)
670 futex_wake(&pool
->block
.end
, INT_MAX
);
673 futex_wait(&pool
->block
.end
, block
.end
);
678 static struct anv_state
679 anv_state_pool_alloc_no_vg(struct anv_state_pool
*pool
,
680 uint32_t size
, uint32_t align
)
682 unsigned size_log2
= ilog2_round_up(size
< align
? align
: size
);
683 assert(size_log2
<= ANV_MAX_STATE_SIZE_LOG2
);
684 if (size_log2
< ANV_MIN_STATE_SIZE_LOG2
)
685 size_log2
= ANV_MIN_STATE_SIZE_LOG2
;
686 unsigned bucket
= size_log2
- ANV_MIN_STATE_SIZE_LOG2
;
688 struct anv_state state
;
689 state
.alloc_size
= 1 << size_log2
;
691 /* Try free list first. */
692 if (anv_free_list_pop(&pool
->buckets
[bucket
].free_list
,
693 &pool
->block_pool
->map
, &state
.offset
)) {
694 assert(state
.offset
>= 0);
698 state
.offset
= anv_fixed_size_state_pool_alloc_new(&pool
->buckets
[bucket
],
703 state
.map
= pool
->block_pool
->map
+ state
.offset
;
708 anv_state_pool_alloc(struct anv_state_pool
*pool
, uint32_t size
, uint32_t align
)
711 return ANV_STATE_NULL
;
713 struct anv_state state
= anv_state_pool_alloc_no_vg(pool
, size
, align
);
714 VG(VALGRIND_MEMPOOL_ALLOC(pool
, state
.map
, size
));
719 anv_state_pool_free_no_vg(struct anv_state_pool
*pool
, struct anv_state state
)
721 assert(util_is_power_of_two(state
.alloc_size
));
722 unsigned size_log2
= ilog2_round_up(state
.alloc_size
);
723 assert(size_log2
>= ANV_MIN_STATE_SIZE_LOG2
&&
724 size_log2
<= ANV_MAX_STATE_SIZE_LOG2
);
725 unsigned bucket
= size_log2
- ANV_MIN_STATE_SIZE_LOG2
;
727 anv_free_list_push(&pool
->buckets
[bucket
].free_list
,
728 pool
->block_pool
->map
, state
.offset
);
732 anv_state_pool_free(struct anv_state_pool
*pool
, struct anv_state state
)
734 if (state
.alloc_size
== 0)
737 VG(VALGRIND_MEMPOOL_FREE(pool
, state
.map
));
738 anv_state_pool_free_no_vg(pool
, state
);
741 struct anv_state_stream_block
{
742 struct anv_state block
;
745 struct anv_state_stream_block
*next
;
748 /* A pointer to the first user-allocated thing in this block. This is
749 * what valgrind sees as the start of the block.
755 /* The state stream allocator is a one-shot, single threaded allocator for
756 * variable sized blocks. We use it for allocating dynamic state.
759 anv_state_stream_init(struct anv_state_stream
*stream
,
760 struct anv_state_pool
*state_pool
,
763 stream
->state_pool
= state_pool
;
764 stream
->block_size
= block_size
;
766 stream
->block
= ANV_STATE_NULL
;
768 stream
->block_list
= NULL
;
770 /* Ensure that next + whatever > block_size. This way the first call to
771 * state_stream_alloc fetches a new block.
773 stream
->next
= block_size
;
775 VG(VALGRIND_CREATE_MEMPOOL(stream
, 0, false));
779 anv_state_stream_finish(struct anv_state_stream
*stream
)
781 struct anv_state_stream_block
*next
= stream
->block_list
;
782 while (next
!= NULL
) {
783 struct anv_state_stream_block sb
= VG_NOACCESS_READ(next
);
784 VG(VALGRIND_MEMPOOL_FREE(stream
, sb
._vg_ptr
));
785 VG(VALGRIND_MAKE_MEM_UNDEFINED(next
, stream
->block_size
));
786 anv_state_pool_free_no_vg(stream
->state_pool
, sb
.block
);
790 VG(VALGRIND_DESTROY_MEMPOOL(stream
));
794 anv_state_stream_alloc(struct anv_state_stream
*stream
,
795 uint32_t size
, uint32_t alignment
)
798 return ANV_STATE_NULL
;
800 assert(alignment
<= PAGE_SIZE
);
802 uint32_t offset
= align_u32(stream
->next
, alignment
);
803 if (offset
+ size
> stream
->block_size
) {
804 stream
->block
= anv_state_pool_alloc_no_vg(stream
->state_pool
,
808 struct anv_state_stream_block
*sb
= stream
->block
.map
;
809 VG_NOACCESS_WRITE(&sb
->block
, stream
->block
);
810 VG_NOACCESS_WRITE(&sb
->next
, stream
->block_list
);
811 stream
->block_list
= sb
;
812 VG_NOACCESS_WRITE(&sb
->_vg_ptr
, NULL
);
814 VG(VALGRIND_MAKE_MEM_NOACCESS(stream
->block
.map
, stream
->block_size
));
816 /* Reset back to the start plus space for the header */
817 stream
->next
= sizeof(*sb
);
819 offset
= align_u32(stream
->next
, alignment
);
820 assert(offset
+ size
<= stream
->block_size
);
823 struct anv_state state
= stream
->block
;
824 state
.offset
+= offset
;
825 state
.alloc_size
= size
;
828 stream
->next
= offset
+ size
;
831 struct anv_state_stream_block
*sb
= stream
->block_list
;
832 void *vg_ptr
= VG_NOACCESS_READ(&sb
->_vg_ptr
);
833 if (vg_ptr
== NULL
) {
835 VG_NOACCESS_WRITE(&sb
->_vg_ptr
, vg_ptr
);
836 VALGRIND_MEMPOOL_ALLOC(stream
, vg_ptr
, size
);
838 void *state_end
= state
.map
+ state
.alloc_size
;
839 /* This only updates the mempool. The newly allocated chunk is still
840 * marked as NOACCESS. */
841 VALGRIND_MEMPOOL_CHANGE(stream
, vg_ptr
, vg_ptr
, state_end
- vg_ptr
);
842 /* Mark the newly allocated chunk as undefined */
843 VALGRIND_MAKE_MEM_UNDEFINED(state
.map
, state
.alloc_size
);
850 struct bo_pool_bo_link
{
851 struct bo_pool_bo_link
*next
;
856 anv_bo_pool_init(struct anv_bo_pool
*pool
, struct anv_device
*device
)
858 pool
->device
= device
;
859 memset(pool
->free_list
, 0, sizeof(pool
->free_list
));
861 VG(VALGRIND_CREATE_MEMPOOL(pool
, 0, false));
865 anv_bo_pool_finish(struct anv_bo_pool
*pool
)
867 for (unsigned i
= 0; i
< ARRAY_SIZE(pool
->free_list
); i
++) {
868 struct bo_pool_bo_link
*link
= PFL_PTR(pool
->free_list
[i
]);
869 while (link
!= NULL
) {
870 struct bo_pool_bo_link link_copy
= VG_NOACCESS_READ(link
);
872 anv_gem_munmap(link_copy
.bo
.map
, link_copy
.bo
.size
);
873 anv_gem_close(pool
->device
, link_copy
.bo
.gem_handle
);
874 link
= link_copy
.next
;
878 VG(VALGRIND_DESTROY_MEMPOOL(pool
));
882 anv_bo_pool_alloc(struct anv_bo_pool
*pool
, struct anv_bo
*bo
, uint32_t size
)
886 const unsigned size_log2
= size
< 4096 ? 12 : ilog2_round_up(size
);
887 const unsigned pow2_size
= 1 << size_log2
;
888 const unsigned bucket
= size_log2
- 12;
889 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
891 void *next_free_void
;
892 if (anv_ptr_free_list_pop(&pool
->free_list
[bucket
], &next_free_void
)) {
893 struct bo_pool_bo_link
*next_free
= next_free_void
;
894 *bo
= VG_NOACCESS_READ(&next_free
->bo
);
895 assert(bo
->gem_handle
);
896 assert(bo
->map
== next_free
);
897 assert(size
<= bo
->size
);
899 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
904 struct anv_bo new_bo
;
906 result
= anv_bo_init_new(&new_bo
, pool
->device
, pow2_size
);
907 if (result
!= VK_SUCCESS
)
910 assert(new_bo
.size
== pow2_size
);
912 new_bo
.map
= anv_gem_mmap(pool
->device
, new_bo
.gem_handle
, 0, pow2_size
, 0);
913 if (new_bo
.map
== MAP_FAILED
) {
914 anv_gem_close(pool
->device
, new_bo
.gem_handle
);
915 return vk_error(VK_ERROR_MEMORY_MAP_FAILED
);
920 VG(VALGRIND_MEMPOOL_ALLOC(pool
, bo
->map
, size
));
926 anv_bo_pool_free(struct anv_bo_pool
*pool
, const struct anv_bo
*bo_in
)
928 /* Make a copy in case the anv_bo happens to be storred in the BO */
929 struct anv_bo bo
= *bo_in
;
931 VG(VALGRIND_MEMPOOL_FREE(pool
, bo
.map
));
933 struct bo_pool_bo_link
*link
= bo
.map
;
934 VG_NOACCESS_WRITE(&link
->bo
, bo
);
936 assert(util_is_power_of_two(bo
.size
));
937 const unsigned size_log2
= ilog2_round_up(bo
.size
);
938 const unsigned bucket
= size_log2
- 12;
939 assert(bucket
< ARRAY_SIZE(pool
->free_list
));
941 anv_ptr_free_list_push(&pool
->free_list
[bucket
], link
);
947 anv_scratch_pool_init(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
949 memset(pool
, 0, sizeof(*pool
));
953 anv_scratch_pool_finish(struct anv_device
*device
, struct anv_scratch_pool
*pool
)
955 for (unsigned s
= 0; s
< MESA_SHADER_STAGES
; s
++) {
956 for (unsigned i
= 0; i
< 16; i
++) {
957 struct anv_scratch_bo
*bo
= &pool
->bos
[i
][s
];
959 anv_gem_close(device
, bo
->bo
.gem_handle
);
965 anv_scratch_pool_alloc(struct anv_device
*device
, struct anv_scratch_pool
*pool
,
966 gl_shader_stage stage
, unsigned per_thread_scratch
)
968 if (per_thread_scratch
== 0)
971 unsigned scratch_size_log2
= ffs(per_thread_scratch
/ 2048);
972 assert(scratch_size_log2
< 16);
974 struct anv_scratch_bo
*bo
= &pool
->bos
[scratch_size_log2
][stage
];
976 /* We can use "exists" to shortcut and ignore the critical section */
980 pthread_mutex_lock(&device
->mutex
);
982 __sync_synchronize();
986 const struct anv_physical_device
*physical_device
=
987 &device
->instance
->physicalDevice
;
988 const struct gen_device_info
*devinfo
= &physical_device
->info
;
990 /* WaCSScratchSize:hsw
992 * Haswell's scratch space address calculation appears to be sparse
993 * rather than tightly packed. The Thread ID has bits indicating which
994 * subslice, EU within a subslice, and thread within an EU it is.
995 * There's a maximum of two slices and two subslices, so these can be
996 * stored with a single bit. Even though there are only 10 EUs per
997 * subslice, this is stored in 4 bits, so there's an effective maximum
998 * value of 16 EUs. Similarly, although there are only 7 threads per EU,
999 * this is stored in a 3 bit number, giving an effective maximum value
1000 * of 8 threads per EU.
1002 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1003 * number of threads per subslice.
1005 const unsigned subslices
= MAX2(physical_device
->subslice_total
, 1);
1006 const unsigned scratch_ids_per_subslice
=
1007 device
->info
.is_haswell
? 16 * 8 : devinfo
->max_cs_threads
;
1009 uint32_t max_threads
[] = {
1010 [MESA_SHADER_VERTEX
] = devinfo
->max_vs_threads
,
1011 [MESA_SHADER_TESS_CTRL
] = devinfo
->max_tcs_threads
,
1012 [MESA_SHADER_TESS_EVAL
] = devinfo
->max_tes_threads
,
1013 [MESA_SHADER_GEOMETRY
] = devinfo
->max_gs_threads
,
1014 [MESA_SHADER_FRAGMENT
] = devinfo
->max_wm_threads
,
1015 [MESA_SHADER_COMPUTE
] = scratch_ids_per_subslice
* subslices
,
1018 uint32_t size
= per_thread_scratch
* max_threads
[stage
];
1020 anv_bo_init_new(&bo
->bo
, device
, size
);
1022 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1023 * are still relative to the general state base address. When we emit
1024 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1025 * to the maximum (1 page under 4GB). This allows us to just place the
1026 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1027 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1028 * However, in order to do so, we need to ensure that the kernel does not
1029 * place the scratch BO above the 32-bit boundary.
1031 * NOTE: Technically, it can't go "anywhere" because the top page is off
1032 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1033 * kernel allocates space using
1035 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1037 * so nothing will ever touch the top page.
1039 bo
->bo
.flags
&= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS
;
1041 /* Set the exists last because it may be read by other threads */
1042 __sync_synchronize();
1045 pthread_mutex_unlock(&device
->mutex
);
1050 struct anv_cached_bo
{
1057 anv_bo_cache_init(struct anv_bo_cache
*cache
)
1059 cache
->bo_map
= _mesa_hash_table_create(NULL
, _mesa_hash_pointer
,
1060 _mesa_key_pointer_equal
);
1062 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1064 if (pthread_mutex_init(&cache
->mutex
, NULL
)) {
1065 _mesa_hash_table_destroy(cache
->bo_map
, NULL
);
1066 return vk_errorf(VK_ERROR_OUT_OF_HOST_MEMORY
,
1067 "pthread_mutex_init failed: %m");
1074 anv_bo_cache_finish(struct anv_bo_cache
*cache
)
1076 _mesa_hash_table_destroy(cache
->bo_map
, NULL
);
1077 pthread_mutex_destroy(&cache
->mutex
);
1080 static struct anv_cached_bo
*
1081 anv_bo_cache_lookup_locked(struct anv_bo_cache
*cache
, uint32_t gem_handle
)
1083 struct hash_entry
*entry
=
1084 _mesa_hash_table_search(cache
->bo_map
,
1085 (const void *)(uintptr_t)gem_handle
);
1089 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)entry
->data
;
1090 assert(bo
->bo
.gem_handle
== gem_handle
);
1095 static struct anv_bo
*
1096 anv_bo_cache_lookup(struct anv_bo_cache
*cache
, uint32_t gem_handle
)
1098 pthread_mutex_lock(&cache
->mutex
);
1100 struct anv_cached_bo
*bo
= anv_bo_cache_lookup_locked(cache
, gem_handle
);
1102 pthread_mutex_unlock(&cache
->mutex
);
1104 return bo
? &bo
->bo
: NULL
;
1108 anv_bo_cache_alloc(struct anv_device
*device
,
1109 struct anv_bo_cache
*cache
,
1110 uint64_t size
, struct anv_bo
**bo_out
)
1112 struct anv_cached_bo
*bo
=
1113 vk_alloc(&device
->alloc
, sizeof(struct anv_cached_bo
), 8,
1114 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT
);
1116 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1120 /* The kernel is going to give us whole pages anyway */
1121 size
= align_u64(size
, 4096);
1123 VkResult result
= anv_bo_init_new(&bo
->bo
, device
, size
);
1124 if (result
!= VK_SUCCESS
) {
1125 vk_free(&device
->alloc
, bo
);
1129 assert(bo
->bo
.gem_handle
);
1131 pthread_mutex_lock(&cache
->mutex
);
1133 _mesa_hash_table_insert(cache
->bo_map
,
1134 (void *)(uintptr_t)bo
->bo
.gem_handle
, bo
);
1136 pthread_mutex_unlock(&cache
->mutex
);
1144 anv_bo_cache_import(struct anv_device
*device
,
1145 struct anv_bo_cache
*cache
,
1146 int fd
, uint64_t size
, struct anv_bo
**bo_out
)
1148 pthread_mutex_lock(&cache
->mutex
);
1150 /* The kernel is going to give us whole pages anyway */
1151 size
= align_u64(size
, 4096);
1153 uint32_t gem_handle
= anv_gem_fd_to_handle(device
, fd
);
1155 pthread_mutex_unlock(&cache
->mutex
);
1156 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX
);
1159 struct anv_cached_bo
*bo
= anv_bo_cache_lookup_locked(cache
, gem_handle
);
1161 if (bo
->bo
.size
!= size
) {
1162 pthread_mutex_unlock(&cache
->mutex
);
1163 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX
);
1165 __sync_fetch_and_add(&bo
->refcount
, 1);
1167 /* For security purposes, we reject BO imports where the size does not
1168 * match exactly. This prevents a malicious client from passing a
1169 * buffer to a trusted client, lying about the size, and telling the
1170 * trusted client to try and texture from an image that goes
1171 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
1172 * in the trusted client. The trusted client can protect itself against
1173 * this sort of attack but only if it can trust the buffer size.
1175 off_t import_size
= lseek(fd
, 0, SEEK_END
);
1176 if (import_size
== (off_t
)-1 || import_size
!= size
) {
1177 anv_gem_close(device
, gem_handle
);
1178 pthread_mutex_unlock(&cache
->mutex
);
1179 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX
);
1182 bo
= vk_alloc(&device
->alloc
, sizeof(struct anv_cached_bo
), 8,
1183 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT
);
1185 anv_gem_close(device
, gem_handle
);
1186 pthread_mutex_unlock(&cache
->mutex
);
1187 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY
);
1192 anv_bo_init(&bo
->bo
, gem_handle
, size
);
1194 if (device
->instance
->physicalDevice
.supports_48bit_addresses
)
1195 bo
->bo
.flags
|= EXEC_OBJECT_SUPPORTS_48B_ADDRESS
;
1197 if (device
->instance
->physicalDevice
.has_exec_async
)
1198 bo
->bo
.flags
|= EXEC_OBJECT_ASYNC
;
1200 _mesa_hash_table_insert(cache
->bo_map
, (void *)(uintptr_t)gem_handle
, bo
);
1203 pthread_mutex_unlock(&cache
->mutex
);
1205 /* From the Vulkan spec:
1207 * "Importing memory from a file descriptor transfers ownership of
1208 * the file descriptor from the application to the Vulkan
1209 * implementation. The application must not perform any operations on
1210 * the file descriptor after a successful import."
1212 * If the import fails, we leave the file descriptor open.
1222 anv_bo_cache_export(struct anv_device
*device
,
1223 struct anv_bo_cache
*cache
,
1224 struct anv_bo
*bo_in
, int *fd_out
)
1226 assert(anv_bo_cache_lookup(cache
, bo_in
->gem_handle
) == bo_in
);
1227 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)bo_in
;
1229 int fd
= anv_gem_handle_to_fd(device
, bo
->bo
.gem_handle
);
1231 return vk_error(VK_ERROR_TOO_MANY_OBJECTS
);
1239 atomic_dec_not_one(uint32_t *counter
)
1248 old
= __sync_val_compare_and_swap(counter
, val
, val
- 1);
1257 anv_bo_cache_release(struct anv_device
*device
,
1258 struct anv_bo_cache
*cache
,
1259 struct anv_bo
*bo_in
)
1261 assert(anv_bo_cache_lookup(cache
, bo_in
->gem_handle
) == bo_in
);
1262 struct anv_cached_bo
*bo
= (struct anv_cached_bo
*)bo_in
;
1264 /* Try to decrement the counter but don't go below one. If this succeeds
1265 * then the refcount has been decremented and we are not the last
1268 if (atomic_dec_not_one(&bo
->refcount
))
1271 pthread_mutex_lock(&cache
->mutex
);
1273 /* We are probably the last reference since our attempt to decrement above
1274 * failed. However, we can't actually know until we are inside the mutex.
1275 * Otherwise, someone could import the BO between the decrement and our
1278 if (unlikely(__sync_sub_and_fetch(&bo
->refcount
, 1) > 0)) {
1279 /* Turns out we're not the last reference. Unlock and bail. */
1280 pthread_mutex_unlock(&cache
->mutex
);
1284 struct hash_entry
*entry
=
1285 _mesa_hash_table_search(cache
->bo_map
,
1286 (const void *)(uintptr_t)bo
->bo
.gem_handle
);
1288 _mesa_hash_table_remove(cache
->bo_map
, entry
);
1291 anv_gem_munmap(bo
->bo
.map
, bo
->bo
.size
);
1293 anv_gem_close(device
, bo
->bo
.gem_handle
);
1295 /* Don't unlock until we've actually closed the BO. The whole point of
1296 * the BO cache is to ensure that we correctly handle races with creating
1297 * and releasing GEM handles and we don't want to let someone import the BO
1298 * again between mutex unlock and closing the GEM handle.
1300 pthread_mutex_unlock(&cache
->mutex
);
1302 vk_free(&device
->alloc
, bo
);