7e4db1aeb65ec6e5dc192b534409387855c60c77
[mesa.git] / src / intel / vulkan / anv_allocator.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
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:
10 *
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
13 * Software.
14 *
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
21 * IN THE SOFTWARE.
22 */
23
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <limits.h>
28 #include <assert.h>
29 #include <linux/futex.h>
30 #include <linux/memfd.h>
31 #include <sys/time.h>
32 #include <sys/mman.h>
33 #include <sys/syscall.h>
34
35 #include "anv_private.h"
36
37 #ifdef HAVE_VALGRIND
38 #define VG_NOACCESS_READ(__ptr) ({ \
39 VALGRIND_MAKE_MEM_DEFINED((__ptr), sizeof(*(__ptr))); \
40 __typeof(*(__ptr)) __val = *(__ptr); \
41 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr)));\
42 __val; \
43 })
44 #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
45 VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
46 *(__ptr) = (__val); \
47 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
48 })
49 #else
50 #define VG_NOACCESS_READ(__ptr) (*(__ptr))
51 #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
52 #endif
53
54 /* Design goals:
55 *
56 * - Lock free (except when resizing underlying bos)
57 *
58 * - Constant time allocation with typically only one atomic
59 *
60 * - Multiple allocation sizes without fragmentation
61 *
62 * - Can grow while keeping addresses and offset of contents stable
63 *
64 * - All allocations within one bo so we can point one of the
65 * STATE_BASE_ADDRESS pointers at it.
66 *
67 * The overall design is a two-level allocator: top level is a fixed size, big
68 * block (8k) allocator, which operates out of a bo. Allocation is done by
69 * either pulling a block from the free list or growing the used range of the
70 * bo. Growing the range may run out of space in the bo which we then need to
71 * grow. Growing the bo is tricky in a multi-threaded, lockless environment:
72 * we need to keep all pointers and contents in the old map valid. GEM bos in
73 * general can't grow, but we use a trick: we create a memfd and use ftruncate
74 * to grow it as necessary. We mmap the new size and then create a gem bo for
75 * it using the new gem userptr ioctl. Without heavy-handed locking around
76 * our allocation fast-path, there isn't really a way to munmap the old mmap,
77 * so we just keep it around until garbage collection time. While the block
78 * allocator is lockless for normal operations, we block other threads trying
79 * to allocate while we're growing the map. It sholdn't happen often, and
80 * growing is fast anyway.
81 *
82 * At the next level we can use various sub-allocators. The state pool is a
83 * pool of smaller, fixed size objects, which operates much like the block
84 * pool. It uses a free list for freeing objects, but when it runs out of
85 * space it just allocates a new block from the block pool. This allocator is
86 * intended for longer lived state objects such as SURFACE_STATE and most
87 * other persistent state objects in the API. We may need to track more info
88 * with these object and a pointer back to the CPU object (eg VkImage). In
89 * those cases we just allocate a slightly bigger object and put the extra
90 * state after the GPU state object.
91 *
92 * The state stream allocator works similar to how the i965 DRI driver streams
93 * all its state. Even with Vulkan, we need to emit transient state (whether
94 * surface state base or dynamic state base), and for that we can just get a
95 * block and fill it up. These cases are local to a command buffer and the
96 * sub-allocator need not be thread safe. The streaming allocator gets a new
97 * block when it runs out of space and chains them together so they can be
98 * easily freed.
99 */
100
101 /* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
102 * We use it to indicate the free list is empty. */
103 #define EMPTY 1
104
105 struct anv_mmap_cleanup {
106 void *map;
107 size_t size;
108 uint32_t gem_handle;
109 };
110
111 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
112
113 static inline long
114 sys_futex(void *addr1, int op, int val1,
115 struct timespec *timeout, void *addr2, int val3)
116 {
117 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
118 }
119
120 static inline int
121 futex_wake(uint32_t *addr, int count)
122 {
123 return sys_futex(addr, FUTEX_WAKE, count, NULL, NULL, 0);
124 }
125
126 static inline int
127 futex_wait(uint32_t *addr, int32_t value)
128 {
129 return sys_futex(addr, FUTEX_WAIT, value, NULL, NULL, 0);
130 }
131
132 static inline int
133 memfd_create(const char *name, unsigned int flags)
134 {
135 return syscall(SYS_memfd_create, name, flags);
136 }
137
138 static inline uint32_t
139 ilog2_round_up(uint32_t value)
140 {
141 assert(value != 0);
142 return 32 - __builtin_clz(value - 1);
143 }
144
145 static inline uint32_t
146 round_to_power_of_two(uint32_t value)
147 {
148 return 1 << ilog2_round_up(value);
149 }
150
151 static bool
152 anv_free_list_pop(union anv_free_list *list, void **map, int32_t *offset)
153 {
154 union anv_free_list current, new, old;
155
156 current.u64 = list->u64;
157 while (current.offset != EMPTY) {
158 /* We have to add a memory barrier here so that the list head (and
159 * offset) gets read before we read the map pointer. This way we
160 * know that the map pointer is valid for the given offset at the
161 * point where we read it.
162 */
163 __sync_synchronize();
164
165 int32_t *next_ptr = *map + current.offset;
166 new.offset = VG_NOACCESS_READ(next_ptr);
167 new.count = current.count + 1;
168 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
169 if (old.u64 == current.u64) {
170 *offset = current.offset;
171 return true;
172 }
173 current = old;
174 }
175
176 return false;
177 }
178
179 static void
180 anv_free_list_push(union anv_free_list *list, void *map, int32_t offset)
181 {
182 union anv_free_list current, old, new;
183 int32_t *next_ptr = map + offset;
184
185 old = *list;
186 do {
187 current = old;
188 VG_NOACCESS_WRITE(next_ptr, current.offset);
189 new.offset = offset;
190 new.count = current.count + 1;
191 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
192 } while (old.u64 != current.u64);
193 }
194
195 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
196 * means that the bottom 12 bits should all be zero.
197 */
198 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
199 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
200 #define PFL_PACK(ptr, count) ({ \
201 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
202 })
203
204 static bool
205 anv_ptr_free_list_pop(void **list, void **elem)
206 {
207 void *current = *list;
208 while (PFL_PTR(current) != NULL) {
209 void **next_ptr = PFL_PTR(current);
210 void *new_ptr = VG_NOACCESS_READ(next_ptr);
211 unsigned new_count = PFL_COUNT(current) + 1;
212 void *new = PFL_PACK(new_ptr, new_count);
213 void *old = __sync_val_compare_and_swap(list, current, new);
214 if (old == current) {
215 *elem = PFL_PTR(current);
216 return true;
217 }
218 current = old;
219 }
220
221 return false;
222 }
223
224 static void
225 anv_ptr_free_list_push(void **list, void *elem)
226 {
227 void *old, *current;
228 void **next_ptr = elem;
229
230 /* The pointer-based free list requires that the pointer be
231 * page-aligned. This is because we use the bottom 12 bits of the
232 * pointer to store a counter to solve the ABA concurrency problem.
233 */
234 assert(((uintptr_t)elem & 0xfff) == 0);
235
236 old = *list;
237 do {
238 current = old;
239 VG_NOACCESS_WRITE(next_ptr, PFL_PTR(current));
240 unsigned new_count = PFL_COUNT(current) + 1;
241 void *new = PFL_PACK(elem, new_count);
242 old = __sync_val_compare_and_swap(list, current, new);
243 } while (old != current);
244 }
245
246 static uint32_t
247 anv_block_pool_grow(struct anv_block_pool *pool, struct anv_block_state *state);
248
249 VkResult
250 anv_block_pool_init(struct anv_block_pool *pool,
251 struct anv_device *device, uint32_t block_size)
252 {
253 VkResult result;
254
255 assert(util_is_power_of_two(block_size));
256
257 pool->device = device;
258 anv_bo_init(&pool->bo, 0, 0);
259 pool->block_size = block_size;
260 pool->free_list = ANV_FREE_LIST_EMPTY;
261 pool->back_free_list = ANV_FREE_LIST_EMPTY;
262
263 pool->fd = memfd_create("block pool", MFD_CLOEXEC);
264 if (pool->fd == -1)
265 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
266
267 /* Just make it 2GB up-front. The Linux kernel won't actually back it
268 * with pages until we either map and fault on one of them or we use
269 * userptr and send a chunk of it off to the GPU.
270 */
271 if (ftruncate(pool->fd, BLOCK_POOL_MEMFD_SIZE) == -1) {
272 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
273 goto fail_fd;
274 }
275
276 if (!u_vector_init(&pool->mmap_cleanups,
277 round_to_power_of_two(sizeof(struct anv_mmap_cleanup)),
278 128)) {
279 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
280 goto fail_fd;
281 }
282
283 pool->state.next = 0;
284 pool->state.end = 0;
285 pool->back_state.next = 0;
286 pool->back_state.end = 0;
287
288 /* Immediately grow the pool so we'll have a backing bo. */
289 pool->state.end = anv_block_pool_grow(pool, &pool->state);
290
291 return VK_SUCCESS;
292
293 fail_fd:
294 close(pool->fd);
295
296 return result;
297 }
298
299 void
300 anv_block_pool_finish(struct anv_block_pool *pool)
301 {
302 struct anv_mmap_cleanup *cleanup;
303
304 u_vector_foreach(cleanup, &pool->mmap_cleanups) {
305 if (cleanup->map)
306 munmap(cleanup->map, cleanup->size);
307 if (cleanup->gem_handle)
308 anv_gem_close(pool->device, cleanup->gem_handle);
309 }
310
311 u_vector_finish(&pool->mmap_cleanups);
312
313 close(pool->fd);
314 }
315
316 #define PAGE_SIZE 4096
317
318 /** Grows and re-centers the block pool.
319 *
320 * We grow the block pool in one or both directions in such a way that the
321 * following conditions are met:
322 *
323 * 1) The size of the entire pool is always a power of two.
324 *
325 * 2) The pool only grows on both ends. Neither end can get
326 * shortened.
327 *
328 * 3) At the end of the allocation, we have about twice as much space
329 * allocated for each end as we have used. This way the pool doesn't
330 * grow too far in one direction or the other.
331 *
332 * 4) If the _alloc_back() has never been called, then the back portion of
333 * the pool retains a size of zero. (This makes it easier for users of
334 * the block pool that only want a one-sided pool.)
335 *
336 * 5) We have enough space allocated for at least one more block in
337 * whichever side `state` points to.
338 *
339 * 6) The center of the pool is always aligned to both the block_size of
340 * the pool and a 4K CPU page.
341 */
342 static uint32_t
343 anv_block_pool_grow(struct anv_block_pool *pool, struct anv_block_state *state)
344 {
345 size_t size;
346 void *map;
347 uint32_t gem_handle;
348 struct anv_mmap_cleanup *cleanup;
349
350 pthread_mutex_lock(&pool->device->mutex);
351
352 assert(state == &pool->state || state == &pool->back_state);
353
354 /* Gather a little usage information on the pool. Since we may have
355 * threadsd waiting in queue to get some storage while we resize, it's
356 * actually possible that total_used will be larger than old_size. In
357 * particular, block_pool_alloc() increments state->next prior to
358 * calling block_pool_grow, so this ensures that we get enough space for
359 * which ever side tries to grow the pool.
360 *
361 * We align to a page size because it makes it easier to do our
362 * calculations later in such a way that we state page-aigned.
363 */
364 uint32_t back_used = align_u32(pool->back_state.next, PAGE_SIZE);
365 uint32_t front_used = align_u32(pool->state.next, PAGE_SIZE);
366 uint32_t total_used = front_used + back_used;
367
368 assert(state == &pool->state || back_used > 0);
369
370 size_t old_size = pool->bo.size;
371
372 if (old_size != 0 &&
373 back_used * 2 <= pool->center_bo_offset &&
374 front_used * 2 <= (old_size - pool->center_bo_offset)) {
375 /* If we're in this case then this isn't the firsta allocation and we
376 * already have enough space on both sides to hold double what we
377 * have allocated. There's nothing for us to do.
378 */
379 goto done;
380 }
381
382 if (old_size == 0) {
383 /* This is the first allocation */
384 size = MAX2(32 * pool->block_size, PAGE_SIZE);
385 } else {
386 size = old_size * 2;
387 }
388
389 /* We can't have a block pool bigger than 1GB because we use signed
390 * 32-bit offsets in the free list and we don't want overflow. We
391 * should never need a block pool bigger than 1GB anyway.
392 */
393 assert(size <= (1u << 31));
394
395 /* We compute a new center_bo_offset such that, when we double the size
396 * of the pool, we maintain the ratio of how much is used by each side.
397 * This way things should remain more-or-less balanced.
398 */
399 uint32_t center_bo_offset;
400 if (back_used == 0) {
401 /* If we're in this case then we have never called alloc_back(). In
402 * this case, we want keep the offset at 0 to make things as simple
403 * as possible for users that don't care about back allocations.
404 */
405 center_bo_offset = 0;
406 } else {
407 /* Try to "center" the allocation based on how much is currently in
408 * use on each side of the center line.
409 */
410 center_bo_offset = ((uint64_t)size * back_used) / total_used;
411
412 /* Align down to a multiple of both the block size and page size */
413 uint32_t granularity = MAX2(pool->block_size, PAGE_SIZE);
414 assert(util_is_power_of_two(granularity));
415 center_bo_offset &= ~(granularity - 1);
416
417 assert(center_bo_offset >= back_used);
418
419 /* Make sure we don't shrink the back end of the pool */
420 if (center_bo_offset < pool->back_state.end)
421 center_bo_offset = pool->back_state.end;
422
423 /* Make sure that we don't shrink the front end of the pool */
424 if (size - center_bo_offset < pool->state.end)
425 center_bo_offset = size - pool->state.end;
426 }
427
428 assert(center_bo_offset % pool->block_size == 0);
429 assert(center_bo_offset % PAGE_SIZE == 0);
430
431 /* Assert that we only ever grow the pool */
432 assert(center_bo_offset >= pool->back_state.end);
433 assert(size - center_bo_offset >= pool->state.end);
434
435 cleanup = u_vector_add(&pool->mmap_cleanups);
436 if (!cleanup)
437 goto fail;
438 *cleanup = ANV_MMAP_CLEANUP_INIT;
439
440 /* Just leak the old map until we destroy the pool. We can't munmap it
441 * without races or imposing locking on the block allocate fast path. On
442 * the whole the leaked maps adds up to less than the size of the
443 * current map. MAP_POPULATE seems like the right thing to do, but we
444 * should try to get some numbers.
445 */
446 map = mmap(NULL, size, PROT_READ | PROT_WRITE,
447 MAP_SHARED | MAP_POPULATE, pool->fd,
448 BLOCK_POOL_MEMFD_CENTER - center_bo_offset);
449 cleanup->map = map;
450 cleanup->size = size;
451
452 if (map == MAP_FAILED)
453 goto fail;
454
455 gem_handle = anv_gem_userptr(pool->device, map, size);
456 if (gem_handle == 0)
457 goto fail;
458 cleanup->gem_handle = gem_handle;
459
460 #if 0
461 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
462 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
463 * always created as I915_CACHING_CACHED, which on non-LLC means
464 * snooped. That can be useful but comes with a bit of overheard. Since
465 * we're eplicitly clflushing and don't want the overhead we need to turn
466 * it off. */
467 if (!pool->device->info.has_llc) {
468 anv_gem_set_caching(pool->device, gem_handle, I915_CACHING_NONE);
469 anv_gem_set_domain(pool->device, gem_handle,
470 I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);
471 }
472 #endif
473
474 /* Now that we successfull allocated everything, we can write the new
475 * values back into pool. */
476 pool->map = map + center_bo_offset;
477 pool->center_bo_offset = center_bo_offset;
478
479 /* For block pool BOs we have to be a bit careful about where we place them
480 * in the GTT. There are two documented workarounds for state base address
481 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
482 * which state that those two base addresses do not support 48-bit
483 * addresses and need to be placed in the bottom 32-bit range.
484 * Unfortunately, this is not quite accurate.
485 *
486 * The real problem is that we always set the size of our state pools in
487 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
488 * likely significantly smaller. We do this because we do not no at the
489 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
490 * the pool during command buffer building so we don't actually have a
491 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
492 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
493 * as being out of bounds and returns zero. For dynamic state, this
494 * usually just leads to rendering corruptions, but shaders that are all
495 * zero hang the GPU immediately.
496 *
497 * The easiest solution to do is exactly what the bogus workarounds say to
498 * do: restrict these buffers to 32-bit addresses. We could also pin the
499 * BO to some particular location of our choosing, but that's significantly
500 * more work than just not setting a flag. So, we explicitly DO NOT set
501 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
502 * hard work for us.
503 */
504 anv_bo_init(&pool->bo, gem_handle, size);
505 pool->bo.map = map;
506
507 if (pool->device->instance->physicalDevice.has_exec_async)
508 pool->bo.flags |= EXEC_OBJECT_ASYNC;
509
510 done:
511 pthread_mutex_unlock(&pool->device->mutex);
512
513 /* Return the appropreate new size. This function never actually
514 * updates state->next. Instead, we let the caller do that because it
515 * needs to do so in order to maintain its concurrency model.
516 */
517 if (state == &pool->state) {
518 return pool->bo.size - pool->center_bo_offset;
519 } else {
520 assert(pool->center_bo_offset > 0);
521 return pool->center_bo_offset;
522 }
523
524 fail:
525 pthread_mutex_unlock(&pool->device->mutex);
526
527 return 0;
528 }
529
530 static uint32_t
531 anv_block_pool_alloc_new(struct anv_block_pool *pool,
532 struct anv_block_state *pool_state)
533 {
534 struct anv_block_state state, old, new;
535
536 while (1) {
537 state.u64 = __sync_fetch_and_add(&pool_state->u64, pool->block_size);
538 if (state.next < state.end) {
539 assert(pool->map);
540 return state.next;
541 } else if (state.next == state.end) {
542 /* We allocated the first block outside the pool, we have to grow it.
543 * pool_state->next acts a mutex: threads who try to allocate now will
544 * get block indexes above the current limit and hit futex_wait
545 * below. */
546 new.next = state.next + pool->block_size;
547 new.end = anv_block_pool_grow(pool, pool_state);
548 assert(new.end >= new.next && new.end % pool->block_size == 0);
549 old.u64 = __sync_lock_test_and_set(&pool_state->u64, new.u64);
550 if (old.next != state.next)
551 futex_wake(&pool_state->end, INT_MAX);
552 return state.next;
553 } else {
554 futex_wait(&pool_state->end, state.end);
555 continue;
556 }
557 }
558 }
559
560 int32_t
561 anv_block_pool_alloc(struct anv_block_pool *pool)
562 {
563 int32_t offset;
564
565 /* Try free list first. */
566 if (anv_free_list_pop(&pool->free_list, &pool->map, &offset)) {
567 assert(offset >= 0);
568 assert(pool->map);
569 return offset;
570 }
571
572 return anv_block_pool_alloc_new(pool, &pool->state);
573 }
574
575 /* Allocates a block out of the back of the block pool.
576 *
577 * This will allocated a block earlier than the "start" of the block pool.
578 * The offsets returned from this function will be negative but will still
579 * be correct relative to the block pool's map pointer.
580 *
581 * If you ever use anv_block_pool_alloc_back, then you will have to do
582 * gymnastics with the block pool's BO when doing relocations.
583 */
584 int32_t
585 anv_block_pool_alloc_back(struct anv_block_pool *pool)
586 {
587 int32_t offset;
588
589 /* Try free list first. */
590 if (anv_free_list_pop(&pool->back_free_list, &pool->map, &offset)) {
591 assert(offset < 0);
592 assert(pool->map);
593 return offset;
594 }
595
596 offset = anv_block_pool_alloc_new(pool, &pool->back_state);
597
598 /* The offset we get out of anv_block_pool_alloc_new() is actually the
599 * number of bytes downwards from the middle to the end of the block.
600 * We need to turn it into a (negative) offset from the middle to the
601 * start of the block.
602 */
603 assert(offset >= 0);
604 return -(offset + pool->block_size);
605 }
606
607 void
608 anv_block_pool_free(struct anv_block_pool *pool, int32_t offset)
609 {
610 if (offset < 0) {
611 anv_free_list_push(&pool->back_free_list, pool->map, offset);
612 } else {
613 anv_free_list_push(&pool->free_list, pool->map, offset);
614 }
615 }
616
617 static void
618 anv_fixed_size_state_pool_init(struct anv_fixed_size_state_pool *pool,
619 size_t state_size)
620 {
621 /* At least a cache line and must divide the block size. */
622 assert(state_size >= 64 && util_is_power_of_two(state_size));
623
624 pool->state_size = state_size;
625 pool->free_list = ANV_FREE_LIST_EMPTY;
626 pool->block.next = 0;
627 pool->block.end = 0;
628 }
629
630 static uint32_t
631 anv_fixed_size_state_pool_alloc(struct anv_fixed_size_state_pool *pool,
632 struct anv_block_pool *block_pool)
633 {
634 int32_t offset;
635 struct anv_block_state block, old, new;
636
637 /* Try free list first. */
638 if (anv_free_list_pop(&pool->free_list, &block_pool->map, &offset)) {
639 assert(offset >= 0);
640 return offset;
641 }
642
643 /* If free list was empty (or somebody raced us and took the items) we
644 * allocate a new item from the end of the block */
645 restart:
646 block.u64 = __sync_fetch_and_add(&pool->block.u64, pool->state_size);
647
648 if (block.next < block.end) {
649 return block.next;
650 } else if (block.next == block.end) {
651 offset = anv_block_pool_alloc(block_pool);
652 new.next = offset + pool->state_size;
653 new.end = offset + block_pool->block_size;
654 old.u64 = __sync_lock_test_and_set(&pool->block.u64, new.u64);
655 if (old.next != block.next)
656 futex_wake(&pool->block.end, INT_MAX);
657 return offset;
658 } else {
659 futex_wait(&pool->block.end, block.end);
660 goto restart;
661 }
662 }
663
664 static void
665 anv_fixed_size_state_pool_free(struct anv_fixed_size_state_pool *pool,
666 struct anv_block_pool *block_pool,
667 uint32_t offset)
668 {
669 anv_free_list_push(&pool->free_list, block_pool->map, offset);
670 }
671
672 void
673 anv_state_pool_init(struct anv_state_pool *pool,
674 struct anv_block_pool *block_pool)
675 {
676 pool->block_pool = block_pool;
677 for (unsigned i = 0; i < ANV_STATE_BUCKETS; i++) {
678 size_t size = 1 << (ANV_MIN_STATE_SIZE_LOG2 + i);
679 anv_fixed_size_state_pool_init(&pool->buckets[i], size);
680 }
681 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
682 }
683
684 void
685 anv_state_pool_finish(struct anv_state_pool *pool)
686 {
687 VG(VALGRIND_DESTROY_MEMPOOL(pool));
688 }
689
690 struct anv_state
691 anv_state_pool_alloc(struct anv_state_pool *pool, size_t size, size_t align)
692 {
693 unsigned size_log2 = ilog2_round_up(size < align ? align : size);
694 assert(size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
695 if (size_log2 < ANV_MIN_STATE_SIZE_LOG2)
696 size_log2 = ANV_MIN_STATE_SIZE_LOG2;
697 unsigned bucket = size_log2 - ANV_MIN_STATE_SIZE_LOG2;
698
699 struct anv_state state;
700 state.alloc_size = 1 << size_log2;
701 state.offset = anv_fixed_size_state_pool_alloc(&pool->buckets[bucket],
702 pool->block_pool);
703 state.map = pool->block_pool->map + state.offset;
704 VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, size));
705 return state;
706 }
707
708 void
709 anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state)
710 {
711 assert(util_is_power_of_two(state.alloc_size));
712 unsigned size_log2 = ilog2_round_up(state.alloc_size);
713 assert(size_log2 >= ANV_MIN_STATE_SIZE_LOG2 &&
714 size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
715 unsigned bucket = size_log2 - ANV_MIN_STATE_SIZE_LOG2;
716
717 VG(VALGRIND_MEMPOOL_FREE(pool, state.map));
718 anv_fixed_size_state_pool_free(&pool->buckets[bucket],
719 pool->block_pool, state.offset);
720 }
721
722 #define NULL_BLOCK 1
723 struct anv_state_stream_block {
724 /* The next block */
725 struct anv_state_stream_block *next;
726
727 /* The offset into the block pool at which this block starts */
728 uint32_t offset;
729
730 #ifdef HAVE_VALGRIND
731 /* A pointer to the first user-allocated thing in this block. This is
732 * what valgrind sees as the start of the block.
733 */
734 void *_vg_ptr;
735 #endif
736 };
737
738 /* The state stream allocator is a one-shot, single threaded allocator for
739 * variable sized blocks. We use it for allocating dynamic state.
740 */
741 void
742 anv_state_stream_init(struct anv_state_stream *stream,
743 struct anv_block_pool *block_pool)
744 {
745 stream->block_pool = block_pool;
746 stream->block = NULL;
747
748 /* Ensure that next + whatever > end. This way the first call to
749 * state_stream_alloc fetches a new block.
750 */
751 stream->next = 1;
752 stream->end = 0;
753
754 VG(VALGRIND_CREATE_MEMPOOL(stream, 0, false));
755 }
756
757 void
758 anv_state_stream_finish(struct anv_state_stream *stream)
759 {
760 VG(const uint32_t block_size = stream->block_pool->block_size);
761
762 struct anv_state_stream_block *next = stream->block;
763 while (next != NULL) {
764 struct anv_state_stream_block sb = VG_NOACCESS_READ(next);
765 VG(VALGRIND_MEMPOOL_FREE(stream, sb._vg_ptr));
766 VG(VALGRIND_MAKE_MEM_UNDEFINED(next, block_size));
767 anv_block_pool_free(stream->block_pool, sb.offset);
768 next = sb.next;
769 }
770
771 VG(VALGRIND_DESTROY_MEMPOOL(stream));
772 }
773
774 struct anv_state
775 anv_state_stream_alloc(struct anv_state_stream *stream,
776 uint32_t size, uint32_t alignment)
777 {
778 struct anv_state_stream_block *sb = stream->block;
779
780 struct anv_state state;
781
782 state.offset = align_u32(stream->next, alignment);
783 if (state.offset + size > stream->end) {
784 uint32_t block = anv_block_pool_alloc(stream->block_pool);
785 sb = stream->block_pool->map + block;
786
787 VG(VALGRIND_MAKE_MEM_UNDEFINED(sb, sizeof(*sb)));
788 sb->next = stream->block;
789 sb->offset = block;
790 VG(sb->_vg_ptr = NULL);
791 VG(VALGRIND_MAKE_MEM_NOACCESS(sb, stream->block_pool->block_size));
792
793 stream->block = sb;
794 stream->start = block;
795 stream->next = block + sizeof(*sb);
796 stream->end = block + stream->block_pool->block_size;
797
798 state.offset = align_u32(stream->next, alignment);
799 assert(state.offset + size <= stream->end);
800 }
801
802 assert(state.offset > stream->start);
803 state.map = (void *)sb + (state.offset - stream->start);
804 state.alloc_size = size;
805
806 #ifdef HAVE_VALGRIND
807 void *vg_ptr = VG_NOACCESS_READ(&sb->_vg_ptr);
808 if (vg_ptr == NULL) {
809 vg_ptr = state.map;
810 VG_NOACCESS_WRITE(&sb->_vg_ptr, vg_ptr);
811 VALGRIND_MEMPOOL_ALLOC(stream, vg_ptr, size);
812 } else {
813 void *state_end = state.map + state.alloc_size;
814 /* This only updates the mempool. The newly allocated chunk is still
815 * marked as NOACCESS. */
816 VALGRIND_MEMPOOL_CHANGE(stream, vg_ptr, vg_ptr, state_end - vg_ptr);
817 /* Mark the newly allocated chunk as undefined */
818 VALGRIND_MAKE_MEM_UNDEFINED(state.map, state.alloc_size);
819 }
820 #endif
821
822 stream->next = state.offset + size;
823
824 return state;
825 }
826
827 struct bo_pool_bo_link {
828 struct bo_pool_bo_link *next;
829 struct anv_bo bo;
830 };
831
832 void
833 anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device)
834 {
835 pool->device = device;
836 memset(pool->free_list, 0, sizeof(pool->free_list));
837
838 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
839 }
840
841 void
842 anv_bo_pool_finish(struct anv_bo_pool *pool)
843 {
844 for (unsigned i = 0; i < ARRAY_SIZE(pool->free_list); i++) {
845 struct bo_pool_bo_link *link = PFL_PTR(pool->free_list[i]);
846 while (link != NULL) {
847 struct bo_pool_bo_link link_copy = VG_NOACCESS_READ(link);
848
849 anv_gem_munmap(link_copy.bo.map, link_copy.bo.size);
850 anv_gem_close(pool->device, link_copy.bo.gem_handle);
851 link = link_copy.next;
852 }
853 }
854
855 VG(VALGRIND_DESTROY_MEMPOOL(pool));
856 }
857
858 VkResult
859 anv_bo_pool_alloc(struct anv_bo_pool *pool, struct anv_bo *bo, uint32_t size)
860 {
861 VkResult result;
862
863 const unsigned size_log2 = size < 4096 ? 12 : ilog2_round_up(size);
864 const unsigned pow2_size = 1 << size_log2;
865 const unsigned bucket = size_log2 - 12;
866 assert(bucket < ARRAY_SIZE(pool->free_list));
867
868 void *next_free_void;
869 if (anv_ptr_free_list_pop(&pool->free_list[bucket], &next_free_void)) {
870 struct bo_pool_bo_link *next_free = next_free_void;
871 *bo = VG_NOACCESS_READ(&next_free->bo);
872 assert(bo->gem_handle);
873 assert(bo->map == next_free);
874 assert(size <= bo->size);
875
876 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
877
878 return VK_SUCCESS;
879 }
880
881 struct anv_bo new_bo;
882
883 result = anv_bo_init_new(&new_bo, pool->device, pow2_size);
884 if (result != VK_SUCCESS)
885 return result;
886
887 assert(new_bo.size == pow2_size);
888
889 new_bo.map = anv_gem_mmap(pool->device, new_bo.gem_handle, 0, pow2_size, 0);
890 if (new_bo.map == NULL) {
891 anv_gem_close(pool->device, new_bo.gem_handle);
892 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
893 }
894
895 *bo = new_bo;
896
897 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
898
899 return VK_SUCCESS;
900 }
901
902 void
903 anv_bo_pool_free(struct anv_bo_pool *pool, const struct anv_bo *bo_in)
904 {
905 /* Make a copy in case the anv_bo happens to be storred in the BO */
906 struct anv_bo bo = *bo_in;
907
908 VG(VALGRIND_MEMPOOL_FREE(pool, bo.map));
909
910 struct bo_pool_bo_link *link = bo.map;
911 VG_NOACCESS_WRITE(&link->bo, bo);
912
913 assert(util_is_power_of_two(bo.size));
914 const unsigned size_log2 = ilog2_round_up(bo.size);
915 const unsigned bucket = size_log2 - 12;
916 assert(bucket < ARRAY_SIZE(pool->free_list));
917
918 anv_ptr_free_list_push(&pool->free_list[bucket], link);
919 }
920
921 // Scratch pool
922
923 void
924 anv_scratch_pool_init(struct anv_device *device, struct anv_scratch_pool *pool)
925 {
926 memset(pool, 0, sizeof(*pool));
927 }
928
929 void
930 anv_scratch_pool_finish(struct anv_device *device, struct anv_scratch_pool *pool)
931 {
932 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
933 for (unsigned i = 0; i < 16; i++) {
934 struct anv_scratch_bo *bo = &pool->bos[i][s];
935 if (bo->exists > 0)
936 anv_gem_close(device, bo->bo.gem_handle);
937 }
938 }
939 }
940
941 struct anv_bo *
942 anv_scratch_pool_alloc(struct anv_device *device, struct anv_scratch_pool *pool,
943 gl_shader_stage stage, unsigned per_thread_scratch)
944 {
945 if (per_thread_scratch == 0)
946 return NULL;
947
948 unsigned scratch_size_log2 = ffs(per_thread_scratch / 2048);
949 assert(scratch_size_log2 < 16);
950
951 struct anv_scratch_bo *bo = &pool->bos[scratch_size_log2][stage];
952
953 /* We can use "exists" to shortcut and ignore the critical section */
954 if (bo->exists)
955 return &bo->bo;
956
957 pthread_mutex_lock(&device->mutex);
958
959 __sync_synchronize();
960 if (bo->exists)
961 return &bo->bo;
962
963 const struct anv_physical_device *physical_device =
964 &device->instance->physicalDevice;
965 const struct gen_device_info *devinfo = &physical_device->info;
966
967 /* WaCSScratchSize:hsw
968 *
969 * Haswell's scratch space address calculation appears to be sparse
970 * rather than tightly packed. The Thread ID has bits indicating which
971 * subslice, EU within a subslice, and thread within an EU it is.
972 * There's a maximum of two slices and two subslices, so these can be
973 * stored with a single bit. Even though there are only 10 EUs per
974 * subslice, this is stored in 4 bits, so there's an effective maximum
975 * value of 16 EUs. Similarly, although there are only 7 threads per EU,
976 * this is stored in a 3 bit number, giving an effective maximum value
977 * of 8 threads per EU.
978 *
979 * This means that we need to use 16 * 8 instead of 10 * 7 for the
980 * number of threads per subslice.
981 */
982 const unsigned subslices = MAX2(physical_device->subslice_total, 1);
983 const unsigned scratch_ids_per_subslice =
984 device->info.is_haswell ? 16 * 8 : devinfo->max_cs_threads;
985
986 uint32_t max_threads[] = {
987 [MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
988 [MESA_SHADER_TESS_CTRL] = devinfo->max_tcs_threads,
989 [MESA_SHADER_TESS_EVAL] = devinfo->max_tes_threads,
990 [MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
991 [MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
992 [MESA_SHADER_COMPUTE] = scratch_ids_per_subslice * subslices,
993 };
994
995 uint32_t size = per_thread_scratch * max_threads[stage];
996
997 anv_bo_init_new(&bo->bo, device, size);
998
999 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1000 * are still relative to the general state base address. When we emit
1001 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1002 * to the maximum (1 page under 4GB). This allows us to just place the
1003 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1004 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1005 * However, in order to do so, we need to ensure that the kernel does not
1006 * place the scratch BO above the 32-bit boundary.
1007 *
1008 * NOTE: Technically, it can't go "anywhere" because the top page is off
1009 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1010 * kernel allocates space using
1011 *
1012 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1013 *
1014 * so nothing will ever touch the top page.
1015 */
1016 bo->bo.flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1017
1018 /* Set the exists last because it may be read by other threads */
1019 __sync_synchronize();
1020 bo->exists = true;
1021
1022 pthread_mutex_unlock(&device->mutex);
1023
1024 return &bo->bo;
1025 }