anv/allocator: Rework chunk return to the state pool.
[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 <stdlib.h>
25 #include <unistd.h>
26 #include <limits.h>
27 #include <assert.h>
28 #include <linux/memfd.h>
29 #include <sys/mman.h>
30
31 #include "anv_private.h"
32
33 #include "util/hash_table.h"
34 #include "util/simple_mtx.h"
35
36 #ifdef HAVE_VALGRIND
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)));\
41 __val; \
42 })
43 #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
44 VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
45 *(__ptr) = (__val); \
46 VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
47 })
48 #else
49 #define VG_NOACCESS_READ(__ptr) (*(__ptr))
50 #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
51 #endif
52
53 /* Design goals:
54 *
55 * - Lock free (except when resizing underlying bos)
56 *
57 * - Constant time allocation with typically only one atomic
58 *
59 * - Multiple allocation sizes without fragmentation
60 *
61 * - Can grow while keeping addresses and offset of contents stable
62 *
63 * - All allocations within one bo so we can point one of the
64 * STATE_BASE_ADDRESS pointers at it.
65 *
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.
80 *
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.
90 *
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
97 * easily freed.
98 */
99
100 /* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
101 * We use it to indicate the free list is empty. */
102 #define EMPTY UINT32_MAX
103
104 #define PAGE_SIZE 4096
105
106 struct anv_mmap_cleanup {
107 void *map;
108 size_t size;
109 uint32_t gem_handle;
110 };
111
112 #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
113
114 #ifndef HAVE_MEMFD_CREATE
115 static inline int
116 memfd_create(const char *name, unsigned int flags)
117 {
118 return syscall(SYS_memfd_create, name, flags);
119 }
120 #endif
121
122 static inline uint32_t
123 ilog2_round_up(uint32_t value)
124 {
125 assert(value != 0);
126 return 32 - __builtin_clz(value - 1);
127 }
128
129 static inline uint32_t
130 round_to_power_of_two(uint32_t value)
131 {
132 return 1 << ilog2_round_up(value);
133 }
134
135 struct anv_state_table_cleanup {
136 void *map;
137 size_t size;
138 };
139
140 #define ANV_STATE_TABLE_CLEANUP_INIT ((struct anv_state_table_cleanup){0})
141 #define ANV_STATE_ENTRY_SIZE (sizeof(struct anv_free_entry))
142
143 static VkResult
144 anv_state_table_expand_range(struct anv_state_table *table, uint32_t size);
145
146 VkResult
147 anv_state_table_init(struct anv_state_table *table,
148 struct anv_device *device,
149 uint32_t initial_entries)
150 {
151 VkResult result;
152
153 table->device = device;
154
155 table->fd = memfd_create("state table", MFD_CLOEXEC);
156 if (table->fd == -1)
157 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
158
159 /* Just make it 2GB up-front. The Linux kernel won't actually back it
160 * with pages until we either map and fault on one of them or we use
161 * userptr and send a chunk of it off to the GPU.
162 */
163 if (ftruncate(table->fd, BLOCK_POOL_MEMFD_SIZE) == -1) {
164 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
165 goto fail_fd;
166 }
167
168 if (!u_vector_init(&table->mmap_cleanups,
169 round_to_power_of_two(sizeof(struct anv_state_table_cleanup)),
170 128)) {
171 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
172 goto fail_fd;
173 }
174
175 table->state.next = 0;
176 table->state.end = 0;
177 table->size = 0;
178
179 uint32_t initial_size = initial_entries * ANV_STATE_ENTRY_SIZE;
180 result = anv_state_table_expand_range(table, initial_size);
181 if (result != VK_SUCCESS)
182 goto fail_mmap_cleanups;
183
184 return VK_SUCCESS;
185
186 fail_mmap_cleanups:
187 u_vector_finish(&table->mmap_cleanups);
188 fail_fd:
189 close(table->fd);
190
191 return result;
192 }
193
194 static VkResult
195 anv_state_table_expand_range(struct anv_state_table *table, uint32_t size)
196 {
197 void *map;
198 struct anv_mmap_cleanup *cleanup;
199
200 /* Assert that we only ever grow the pool */
201 assert(size >= table->state.end);
202
203 /* Make sure that we don't go outside the bounds of the memfd */
204 if (size > BLOCK_POOL_MEMFD_SIZE)
205 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
206
207 cleanup = u_vector_add(&table->mmap_cleanups);
208 if (!cleanup)
209 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
210
211 *cleanup = ANV_MMAP_CLEANUP_INIT;
212
213 /* Just leak the old map until we destroy the pool. We can't munmap it
214 * without races or imposing locking on the block allocate fast path. On
215 * the whole the leaked maps adds up to less than the size of the
216 * current map. MAP_POPULATE seems like the right thing to do, but we
217 * should try to get some numbers.
218 */
219 map = mmap(NULL, size, PROT_READ | PROT_WRITE,
220 MAP_SHARED | MAP_POPULATE, table->fd, 0);
221 if (map == MAP_FAILED) {
222 return vk_errorf(table->device->instance, table->device,
223 VK_ERROR_OUT_OF_HOST_MEMORY, "mmap failed: %m");
224 }
225
226 cleanup->map = map;
227 cleanup->size = size;
228
229 table->map = map;
230 table->size = size;
231
232 return VK_SUCCESS;
233 }
234
235 static VkResult
236 anv_state_table_grow(struct anv_state_table *table)
237 {
238 VkResult result = VK_SUCCESS;
239
240 uint32_t used = align_u32(table->state.next * ANV_STATE_ENTRY_SIZE,
241 PAGE_SIZE);
242 uint32_t old_size = table->size;
243
244 /* The block pool is always initialized to a nonzero size and this function
245 * is always called after initialization.
246 */
247 assert(old_size > 0);
248
249 uint32_t required = MAX2(used, old_size);
250 if (used * 2 <= required) {
251 /* If we're in this case then this isn't the firsta allocation and we
252 * already have enough space on both sides to hold double what we
253 * have allocated. There's nothing for us to do.
254 */
255 goto done;
256 }
257
258 uint32_t size = old_size * 2;
259 while (size < required)
260 size *= 2;
261
262 assert(size > table->size);
263
264 result = anv_state_table_expand_range(table, size);
265
266 done:
267 return result;
268 }
269
270 void
271 anv_state_table_finish(struct anv_state_table *table)
272 {
273 struct anv_state_table_cleanup *cleanup;
274
275 u_vector_foreach(cleanup, &table->mmap_cleanups) {
276 if (cleanup->map)
277 munmap(cleanup->map, cleanup->size);
278 }
279
280 u_vector_finish(&table->mmap_cleanups);
281
282 close(table->fd);
283 }
284
285 VkResult
286 anv_state_table_add(struct anv_state_table *table, uint32_t *idx,
287 uint32_t count)
288 {
289 struct anv_block_state state, old, new;
290 VkResult result;
291
292 assert(idx);
293
294 while(1) {
295 state.u64 = __sync_fetch_and_add(&table->state.u64, count);
296 if (state.next + count <= state.end) {
297 assert(table->map);
298 struct anv_free_entry *entry = &table->map[state.next];
299 for (int i = 0; i < count; i++) {
300 entry[i].state.idx = state.next + i;
301 }
302 *idx = state.next;
303 return VK_SUCCESS;
304 } else if (state.next <= state.end) {
305 /* We allocated the first block outside the pool so we have to grow
306 * the pool. pool_state->next acts a mutex: threads who try to
307 * allocate now will get block indexes above the current limit and
308 * hit futex_wait below.
309 */
310 new.next = state.next + count;
311 do {
312 result = anv_state_table_grow(table);
313 if (result != VK_SUCCESS)
314 return result;
315 new.end = table->size / ANV_STATE_ENTRY_SIZE;
316 } while (new.end < new.next);
317
318 old.u64 = __sync_lock_test_and_set(&table->state.u64, new.u64);
319 if (old.next != state.next)
320 futex_wake(&table->state.end, INT_MAX);
321 } else {
322 futex_wait(&table->state.end, state.end, NULL);
323 continue;
324 }
325 }
326 }
327
328 void
329 anv_free_list_push(union anv_free_list *list,
330 struct anv_state_table *table,
331 uint32_t first, uint32_t count)
332 {
333 union anv_free_list current, old, new;
334 uint32_t last = first;
335
336 for (uint32_t i = 1; i < count; i++, last++)
337 table->map[last].next = last + 1;
338
339 old = *list;
340 do {
341 current = old;
342 table->map[last].next = current.offset;
343 new.offset = first;
344 new.count = current.count + 1;
345 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
346 } while (old.u64 != current.u64);
347 }
348
349 struct anv_state *
350 anv_free_list_pop(union anv_free_list *list,
351 struct anv_state_table *table)
352 {
353 union anv_free_list current, new, old;
354
355 current.u64 = list->u64;
356 while (current.offset != EMPTY) {
357 __sync_synchronize();
358 new.offset = table->map[current.offset].next;
359 new.count = current.count + 1;
360 old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
361 if (old.u64 == current.u64) {
362 struct anv_free_entry *entry = &table->map[current.offset];
363 return &entry->state;
364 }
365 current = old;
366 }
367
368 return NULL;
369 }
370
371 /* All pointers in the ptr_free_list are assumed to be page-aligned. This
372 * means that the bottom 12 bits should all be zero.
373 */
374 #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
375 #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
376 #define PFL_PACK(ptr, count) ({ \
377 (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
378 })
379
380 static bool
381 anv_ptr_free_list_pop(void **list, void **elem)
382 {
383 void *current = *list;
384 while (PFL_PTR(current) != NULL) {
385 void **next_ptr = PFL_PTR(current);
386 void *new_ptr = VG_NOACCESS_READ(next_ptr);
387 unsigned new_count = PFL_COUNT(current) + 1;
388 void *new = PFL_PACK(new_ptr, new_count);
389 void *old = __sync_val_compare_and_swap(list, current, new);
390 if (old == current) {
391 *elem = PFL_PTR(current);
392 return true;
393 }
394 current = old;
395 }
396
397 return false;
398 }
399
400 static void
401 anv_ptr_free_list_push(void **list, void *elem)
402 {
403 void *old, *current;
404 void **next_ptr = elem;
405
406 /* The pointer-based free list requires that the pointer be
407 * page-aligned. This is because we use the bottom 12 bits of the
408 * pointer to store a counter to solve the ABA concurrency problem.
409 */
410 assert(((uintptr_t)elem & 0xfff) == 0);
411
412 old = *list;
413 do {
414 current = old;
415 VG_NOACCESS_WRITE(next_ptr, PFL_PTR(current));
416 unsigned new_count = PFL_COUNT(current) + 1;
417 void *new = PFL_PACK(elem, new_count);
418 old = __sync_val_compare_and_swap(list, current, new);
419 } while (old != current);
420 }
421
422 static VkResult
423 anv_block_pool_expand_range(struct anv_block_pool *pool,
424 uint32_t center_bo_offset, uint32_t size);
425
426 VkResult
427 anv_block_pool_init(struct anv_block_pool *pool,
428 struct anv_device *device,
429 uint64_t start_address,
430 uint32_t initial_size,
431 uint64_t bo_flags)
432 {
433 VkResult result;
434
435 pool->device = device;
436 pool->bo_flags = bo_flags;
437 pool->nbos = 0;
438 pool->size = 0;
439 pool->start_address = gen_canonical_address(start_address);
440
441 /* This pointer will always point to the first BO in the list */
442 pool->bo = &pool->bos[0];
443
444 anv_bo_init(pool->bo, 0, 0);
445
446 pool->fd = memfd_create("block pool", MFD_CLOEXEC);
447 if (pool->fd == -1)
448 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
449
450 /* Just make it 2GB up-front. The Linux kernel won't actually back it
451 * with pages until we either map and fault on one of them or we use
452 * userptr and send a chunk of it off to the GPU.
453 */
454 if (ftruncate(pool->fd, BLOCK_POOL_MEMFD_SIZE) == -1) {
455 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
456 goto fail_fd;
457 }
458
459 if (!u_vector_init(&pool->mmap_cleanups,
460 round_to_power_of_two(sizeof(struct anv_mmap_cleanup)),
461 128)) {
462 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
463 goto fail_fd;
464 }
465
466 pool->state.next = 0;
467 pool->state.end = 0;
468 pool->back_state.next = 0;
469 pool->back_state.end = 0;
470
471 result = anv_block_pool_expand_range(pool, 0, initial_size);
472 if (result != VK_SUCCESS)
473 goto fail_mmap_cleanups;
474
475 return VK_SUCCESS;
476
477 fail_mmap_cleanups:
478 u_vector_finish(&pool->mmap_cleanups);
479 fail_fd:
480 close(pool->fd);
481
482 return result;
483 }
484
485 void
486 anv_block_pool_finish(struct anv_block_pool *pool)
487 {
488 struct anv_mmap_cleanup *cleanup;
489
490 u_vector_foreach(cleanup, &pool->mmap_cleanups) {
491 if (cleanup->map)
492 munmap(cleanup->map, cleanup->size);
493 if (cleanup->gem_handle)
494 anv_gem_close(pool->device, cleanup->gem_handle);
495 }
496
497 u_vector_finish(&pool->mmap_cleanups);
498
499 close(pool->fd);
500 }
501
502 static VkResult
503 anv_block_pool_expand_range(struct anv_block_pool *pool,
504 uint32_t center_bo_offset, uint32_t size)
505 {
506 void *map;
507 uint32_t gem_handle;
508 struct anv_mmap_cleanup *cleanup;
509
510 /* Assert that we only ever grow the pool */
511 assert(center_bo_offset >= pool->back_state.end);
512 assert(size - center_bo_offset >= pool->state.end);
513
514 /* Assert that we don't go outside the bounds of the memfd */
515 assert(center_bo_offset <= BLOCK_POOL_MEMFD_CENTER);
516 assert(size - center_bo_offset <=
517 BLOCK_POOL_MEMFD_SIZE - BLOCK_POOL_MEMFD_CENTER);
518
519 cleanup = u_vector_add(&pool->mmap_cleanups);
520 if (!cleanup)
521 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
522
523 *cleanup = ANV_MMAP_CLEANUP_INIT;
524
525 /* Just leak the old map until we destroy the pool. We can't munmap it
526 * without races or imposing locking on the block allocate fast path. On
527 * the whole the leaked maps adds up to less than the size of the
528 * current map. MAP_POPULATE seems like the right thing to do, but we
529 * should try to get some numbers.
530 */
531 map = mmap(NULL, size, PROT_READ | PROT_WRITE,
532 MAP_SHARED | MAP_POPULATE, pool->fd,
533 BLOCK_POOL_MEMFD_CENTER - center_bo_offset);
534 if (map == MAP_FAILED)
535 return vk_errorf(pool->device->instance, pool->device,
536 VK_ERROR_MEMORY_MAP_FAILED, "mmap failed: %m");
537
538 gem_handle = anv_gem_userptr(pool->device, map, size);
539 if (gem_handle == 0) {
540 munmap(map, size);
541 return vk_errorf(pool->device->instance, pool->device,
542 VK_ERROR_TOO_MANY_OBJECTS, "userptr failed: %m");
543 }
544
545 cleanup->map = map;
546 cleanup->size = size;
547 cleanup->gem_handle = gem_handle;
548
549 #if 0
550 /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
551 * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
552 * always created as I915_CACHING_CACHED, which on non-LLC means
553 * snooped. That can be useful but comes with a bit of overheard. Since
554 * we're eplicitly clflushing and don't want the overhead we need to turn
555 * it off. */
556 if (!pool->device->info.has_llc) {
557 anv_gem_set_caching(pool->device, gem_handle, I915_CACHING_NONE);
558 anv_gem_set_domain(pool->device, gem_handle,
559 I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);
560 }
561 #endif
562
563 /* Now that we successfull allocated everything, we can write the new
564 * center_bo_offset back into pool. */
565 pool->center_bo_offset = center_bo_offset;
566
567 /* For block pool BOs we have to be a bit careful about where we place them
568 * in the GTT. There are two documented workarounds for state base address
569 * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
570 * which state that those two base addresses do not support 48-bit
571 * addresses and need to be placed in the bottom 32-bit range.
572 * Unfortunately, this is not quite accurate.
573 *
574 * The real problem is that we always set the size of our state pools in
575 * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
576 * likely significantly smaller. We do this because we do not no at the
577 * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
578 * the pool during command buffer building so we don't actually have a
579 * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
580 * overflows 48 bits, the GPU appears to treat all accesses to the buffer
581 * as being out of bounds and returns zero. For dynamic state, this
582 * usually just leads to rendering corruptions, but shaders that are all
583 * zero hang the GPU immediately.
584 *
585 * The easiest solution to do is exactly what the bogus workarounds say to
586 * do: restrict these buffers to 32-bit addresses. We could also pin the
587 * BO to some particular location of our choosing, but that's significantly
588 * more work than just not setting a flag. So, we explicitly DO NOT set
589 * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
590 * hard work for us.
591 */
592 struct anv_bo *bo;
593
594 assert(pool->nbos < ANV_MAX_BLOCK_POOL_BOS);
595
596 /* We just need one BO, and we already have a pointer to it. Let's simply
597 * "allocate" it from our array.
598 */
599 if (pool->nbos == 0)
600 pool->nbos++;
601
602 bo = pool->bo;
603
604 anv_bo_init(bo, gem_handle, size);
605 if (pool->bo_flags & EXEC_OBJECT_PINNED) {
606 bo->offset = pool->start_address + BLOCK_POOL_MEMFD_CENTER -
607 center_bo_offset;
608 }
609 bo->flags = pool->bo_flags;
610 bo->map = map;
611 pool->size = size;
612
613 return VK_SUCCESS;
614 }
615
616 static struct anv_bo *
617 anv_block_pool_get_bo(struct anv_block_pool *pool, int32_t *offset)
618 {
619 struct anv_bo *bo, *bo_found = NULL;
620 int32_t cur_offset = 0;
621
622 assert(offset);
623
624 if (!(pool->bo_flags & EXEC_OBJECT_PINNED))
625 return pool->bo;
626
627 anv_block_pool_foreach_bo(bo, pool) {
628 if (*offset < cur_offset + bo->size) {
629 bo_found = bo;
630 break;
631 }
632 cur_offset += bo->size;
633 }
634
635 assert(bo_found != NULL);
636 *offset -= cur_offset;
637
638 return bo_found;
639 }
640
641 /** Returns current memory map of the block pool.
642 *
643 * The returned pointer points to the map for the memory at the specified
644 * offset. The offset parameter is relative to the "center" of the block pool
645 * rather than the start of the block pool BO map.
646 */
647 void*
648 anv_block_pool_map(struct anv_block_pool *pool, int32_t offset)
649 {
650 struct anv_bo *bo = anv_block_pool_get_bo(pool, &offset);
651 return bo->map + pool->center_bo_offset + offset;
652 }
653
654 /** Grows and re-centers the block pool.
655 *
656 * We grow the block pool in one or both directions in such a way that the
657 * following conditions are met:
658 *
659 * 1) The size of the entire pool is always a power of two.
660 *
661 * 2) The pool only grows on both ends. Neither end can get
662 * shortened.
663 *
664 * 3) At the end of the allocation, we have about twice as much space
665 * allocated for each end as we have used. This way the pool doesn't
666 * grow too far in one direction or the other.
667 *
668 * 4) If the _alloc_back() has never been called, then the back portion of
669 * the pool retains a size of zero. (This makes it easier for users of
670 * the block pool that only want a one-sided pool.)
671 *
672 * 5) We have enough space allocated for at least one more block in
673 * whichever side `state` points to.
674 *
675 * 6) The center of the pool is always aligned to both the block_size of
676 * the pool and a 4K CPU page.
677 */
678 static uint32_t
679 anv_block_pool_grow(struct anv_block_pool *pool, struct anv_block_state *state)
680 {
681 VkResult result = VK_SUCCESS;
682
683 pthread_mutex_lock(&pool->device->mutex);
684
685 assert(state == &pool->state || state == &pool->back_state);
686
687 /* Gather a little usage information on the pool. Since we may have
688 * threadsd waiting in queue to get some storage while we resize, it's
689 * actually possible that total_used will be larger than old_size. In
690 * particular, block_pool_alloc() increments state->next prior to
691 * calling block_pool_grow, so this ensures that we get enough space for
692 * which ever side tries to grow the pool.
693 *
694 * We align to a page size because it makes it easier to do our
695 * calculations later in such a way that we state page-aigned.
696 */
697 uint32_t back_used = align_u32(pool->back_state.next, PAGE_SIZE);
698 uint32_t front_used = align_u32(pool->state.next, PAGE_SIZE);
699 uint32_t total_used = front_used + back_used;
700
701 assert(state == &pool->state || back_used > 0);
702
703 uint32_t old_size = pool->size;
704
705 /* The block pool is always initialized to a nonzero size and this function
706 * is always called after initialization.
707 */
708 assert(old_size > 0);
709
710 /* The back_used and front_used may actually be smaller than the actual
711 * requirement because they are based on the next pointers which are
712 * updated prior to calling this function.
713 */
714 uint32_t back_required = MAX2(back_used, pool->center_bo_offset);
715 uint32_t front_required = MAX2(front_used, old_size - pool->center_bo_offset);
716
717 if (back_used * 2 <= back_required && front_used * 2 <= front_required) {
718 /* If we're in this case then this isn't the firsta allocation and we
719 * already have enough space on both sides to hold double what we
720 * have allocated. There's nothing for us to do.
721 */
722 goto done;
723 }
724
725 uint32_t size = old_size * 2;
726 while (size < back_required + front_required)
727 size *= 2;
728
729 assert(size > pool->size);
730
731 /* We compute a new center_bo_offset such that, when we double the size
732 * of the pool, we maintain the ratio of how much is used by each side.
733 * This way things should remain more-or-less balanced.
734 */
735 uint32_t center_bo_offset;
736 if (back_used == 0) {
737 /* If we're in this case then we have never called alloc_back(). In
738 * this case, we want keep the offset at 0 to make things as simple
739 * as possible for users that don't care about back allocations.
740 */
741 center_bo_offset = 0;
742 } else {
743 /* Try to "center" the allocation based on how much is currently in
744 * use on each side of the center line.
745 */
746 center_bo_offset = ((uint64_t)size * back_used) / total_used;
747
748 /* Align down to a multiple of the page size */
749 center_bo_offset &= ~(PAGE_SIZE - 1);
750
751 assert(center_bo_offset >= back_used);
752
753 /* Make sure we don't shrink the back end of the pool */
754 if (center_bo_offset < back_required)
755 center_bo_offset = back_required;
756
757 /* Make sure that we don't shrink the front end of the pool */
758 if (size - center_bo_offset < front_required)
759 center_bo_offset = size - front_required;
760 }
761
762 assert(center_bo_offset % PAGE_SIZE == 0);
763
764 result = anv_block_pool_expand_range(pool, center_bo_offset, size);
765
766 pool->bo->flags = pool->bo_flags;
767
768 done:
769 pthread_mutex_unlock(&pool->device->mutex);
770
771 if (result == VK_SUCCESS) {
772 /* Return the appropriate new size. This function never actually
773 * updates state->next. Instead, we let the caller do that because it
774 * needs to do so in order to maintain its concurrency model.
775 */
776 if (state == &pool->state) {
777 return pool->size - pool->center_bo_offset;
778 } else {
779 assert(pool->center_bo_offset > 0);
780 return pool->center_bo_offset;
781 }
782 } else {
783 return 0;
784 }
785 }
786
787 static uint32_t
788 anv_block_pool_alloc_new(struct anv_block_pool *pool,
789 struct anv_block_state *pool_state,
790 uint32_t block_size)
791 {
792 struct anv_block_state state, old, new;
793
794 while (1) {
795 state.u64 = __sync_fetch_and_add(&pool_state->u64, block_size);
796 if (state.next + block_size <= state.end) {
797 return state.next;
798 } else if (state.next <= state.end) {
799 /* We allocated the first block outside the pool so we have to grow
800 * the pool. pool_state->next acts a mutex: threads who try to
801 * allocate now will get block indexes above the current limit and
802 * hit futex_wait below.
803 */
804 new.next = state.next + block_size;
805 do {
806 new.end = anv_block_pool_grow(pool, pool_state);
807 } while (new.end < new.next);
808
809 old.u64 = __sync_lock_test_and_set(&pool_state->u64, new.u64);
810 if (old.next != state.next)
811 futex_wake(&pool_state->end, INT_MAX);
812 return state.next;
813 } else {
814 futex_wait(&pool_state->end, state.end, NULL);
815 continue;
816 }
817 }
818 }
819
820 int32_t
821 anv_block_pool_alloc(struct anv_block_pool *pool,
822 uint32_t block_size)
823 {
824 return anv_block_pool_alloc_new(pool, &pool->state, block_size);
825 }
826
827 /* Allocates a block out of the back of the block pool.
828 *
829 * This will allocated a block earlier than the "start" of the block pool.
830 * The offsets returned from this function will be negative but will still
831 * be correct relative to the block pool's map pointer.
832 *
833 * If you ever use anv_block_pool_alloc_back, then you will have to do
834 * gymnastics with the block pool's BO when doing relocations.
835 */
836 int32_t
837 anv_block_pool_alloc_back(struct anv_block_pool *pool,
838 uint32_t block_size)
839 {
840 int32_t offset = anv_block_pool_alloc_new(pool, &pool->back_state,
841 block_size);
842
843 /* The offset we get out of anv_block_pool_alloc_new() is actually the
844 * number of bytes downwards from the middle to the end of the block.
845 * We need to turn it into a (negative) offset from the middle to the
846 * start of the block.
847 */
848 assert(offset >= 0);
849 return -(offset + block_size);
850 }
851
852 VkResult
853 anv_state_pool_init(struct anv_state_pool *pool,
854 struct anv_device *device,
855 uint64_t start_address,
856 uint32_t block_size,
857 uint64_t bo_flags)
858 {
859 VkResult result = anv_block_pool_init(&pool->block_pool, device,
860 start_address,
861 block_size * 16,
862 bo_flags);
863 if (result != VK_SUCCESS)
864 return result;
865
866 result = anv_state_table_init(&pool->table, device, 64);
867 if (result != VK_SUCCESS) {
868 anv_block_pool_finish(&pool->block_pool);
869 return result;
870 }
871
872 assert(util_is_power_of_two_or_zero(block_size));
873 pool->block_size = block_size;
874 pool->back_alloc_free_list = ANV_FREE_LIST_EMPTY;
875 for (unsigned i = 0; i < ANV_STATE_BUCKETS; i++) {
876 pool->buckets[i].free_list = ANV_FREE_LIST_EMPTY;
877 pool->buckets[i].block.next = 0;
878 pool->buckets[i].block.end = 0;
879 }
880 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
881
882 return VK_SUCCESS;
883 }
884
885 void
886 anv_state_pool_finish(struct anv_state_pool *pool)
887 {
888 VG(VALGRIND_DESTROY_MEMPOOL(pool));
889 anv_state_table_finish(&pool->table);
890 anv_block_pool_finish(&pool->block_pool);
891 }
892
893 static uint32_t
894 anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool *pool,
895 struct anv_block_pool *block_pool,
896 uint32_t state_size,
897 uint32_t block_size)
898 {
899 struct anv_block_state block, old, new;
900 uint32_t offset;
901
902 /* If our state is large, we don't need any sub-allocation from a block.
903 * Instead, we just grab whole (potentially large) blocks.
904 */
905 if (state_size >= block_size)
906 return anv_block_pool_alloc(block_pool, state_size);
907
908 restart:
909 block.u64 = __sync_fetch_and_add(&pool->block.u64, state_size);
910
911 if (block.next < block.end) {
912 return block.next;
913 } else if (block.next == block.end) {
914 offset = anv_block_pool_alloc(block_pool, block_size);
915 new.next = offset + state_size;
916 new.end = offset + block_size;
917 old.u64 = __sync_lock_test_and_set(&pool->block.u64, new.u64);
918 if (old.next != block.next)
919 futex_wake(&pool->block.end, INT_MAX);
920 return offset;
921 } else {
922 futex_wait(&pool->block.end, block.end, NULL);
923 goto restart;
924 }
925 }
926
927 static uint32_t
928 anv_state_pool_get_bucket(uint32_t size)
929 {
930 unsigned size_log2 = ilog2_round_up(size);
931 assert(size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
932 if (size_log2 < ANV_MIN_STATE_SIZE_LOG2)
933 size_log2 = ANV_MIN_STATE_SIZE_LOG2;
934 return size_log2 - ANV_MIN_STATE_SIZE_LOG2;
935 }
936
937 static uint32_t
938 anv_state_pool_get_bucket_size(uint32_t bucket)
939 {
940 uint32_t size_log2 = bucket + ANV_MIN_STATE_SIZE_LOG2;
941 return 1 << size_log2;
942 }
943
944 /** Helper to push a chunk into the state table.
945 *
946 * It creates 'count' entries into the state table and update their sizes,
947 * offsets and maps, also pushing them as "free" states.
948 */
949 static void
950 anv_state_pool_return_blocks(struct anv_state_pool *pool,
951 uint32_t chunk_offset, uint32_t count,
952 uint32_t block_size)
953 {
954 /* Disallow returning 0 chunks */
955 assert(count != 0);
956
957 /* Make sure we always return chunks aligned to the block_size */
958 assert(chunk_offset % block_size == 0);
959
960 uint32_t st_idx;
961 VkResult result = anv_state_table_add(&pool->table, &st_idx, count);
962 assert(result == VK_SUCCESS);
963 for (int i = 0; i < count; i++) {
964 /* update states that were added back to the state table */
965 struct anv_state *state_i = anv_state_table_get(&pool->table,
966 st_idx + i);
967 state_i->alloc_size = block_size;
968 state_i->offset = chunk_offset + block_size * i;
969 state_i->map = anv_block_pool_map(&pool->block_pool, state_i->offset);
970 }
971
972 uint32_t block_bucket = anv_state_pool_get_bucket(block_size);
973 anv_free_list_push(&pool->buckets[block_bucket].free_list,
974 &pool->table, st_idx, count);
975 }
976
977 /** Returns a chunk of memory back to the state pool.
978 *
979 * Do a two-level split. If chunk_size is bigger than divisor
980 * (pool->block_size), we return as many divisor sized blocks as we can, from
981 * the end of the chunk.
982 *
983 * The remaining is then split into smaller blocks (starting at small_size if
984 * it is non-zero), with larger blocks always being taken from the end of the
985 * chunk.
986 */
987 static void
988 anv_state_pool_return_chunk(struct anv_state_pool *pool,
989 uint32_t chunk_offset, uint32_t chunk_size,
990 uint32_t small_size)
991 {
992 uint32_t divisor = pool->block_size;
993 uint32_t nblocks = chunk_size / divisor;
994 uint32_t rest = chunk_size - nblocks * divisor;
995
996 if (nblocks > 0) {
997 /* First return divisor aligned and sized chunks. We start returning
998 * larger blocks from the end fo the chunk, since they should already be
999 * aligned to divisor. Also anv_state_pool_return_blocks() only accepts
1000 * aligned chunks.
1001 */
1002 uint32_t offset = chunk_offset + rest;
1003 anv_state_pool_return_blocks(pool, offset, nblocks, divisor);
1004 }
1005
1006 chunk_size = rest;
1007 divisor /= 2;
1008
1009 if (small_size > 0 && small_size < divisor)
1010 divisor = small_size;
1011
1012 uint32_t min_size = 1 << ANV_MIN_STATE_SIZE_LOG2;
1013
1014 /* Just as before, return larger divisor aligned blocks from the end of the
1015 * chunk first.
1016 */
1017 while (chunk_size > 0 && divisor >= min_size) {
1018 nblocks = chunk_size / divisor;
1019 rest = chunk_size - nblocks * divisor;
1020 if (nblocks > 0) {
1021 anv_state_pool_return_blocks(pool, chunk_offset + rest,
1022 nblocks, divisor);
1023 chunk_size = rest;
1024 }
1025 divisor /= 2;
1026 }
1027 }
1028
1029 static struct anv_state
1030 anv_state_pool_alloc_no_vg(struct anv_state_pool *pool,
1031 uint32_t size, uint32_t align)
1032 {
1033 uint32_t bucket = anv_state_pool_get_bucket(MAX2(size, align));
1034
1035 struct anv_state *state;
1036 uint32_t alloc_size = anv_state_pool_get_bucket_size(bucket);
1037 int32_t offset;
1038
1039 /* Try free list first. */
1040 state = anv_free_list_pop(&pool->buckets[bucket].free_list,
1041 &pool->table);
1042 if (state) {
1043 assert(state->offset >= 0);
1044 goto done;
1045 }
1046
1047 /* Try to grab a chunk from some larger bucket and split it up */
1048 for (unsigned b = bucket + 1; b < ANV_STATE_BUCKETS; b++) {
1049 state = anv_free_list_pop(&pool->buckets[b].free_list, &pool->table);
1050 if (state) {
1051 unsigned chunk_size = anv_state_pool_get_bucket_size(b);
1052 int32_t chunk_offset = state->offset;
1053
1054 /* First lets update the state we got to its new size. offset and map
1055 * remain the same.
1056 */
1057 state->alloc_size = alloc_size;
1058
1059 /* Now return the unused part of the chunk back to the pool as free
1060 * blocks
1061 *
1062 * There are a couple of options as to what we do with it:
1063 *
1064 * 1) We could fully split the chunk into state.alloc_size sized
1065 * pieces. However, this would mean that allocating a 16B
1066 * state could potentially split a 2MB chunk into 512K smaller
1067 * chunks. This would lead to unnecessary fragmentation.
1068 *
1069 * 2) The classic "buddy allocator" method would have us split the
1070 * chunk in half and return one half. Then we would split the
1071 * remaining half in half and return one half, and repeat as
1072 * needed until we get down to the size we want. However, if
1073 * you are allocating a bunch of the same size state (which is
1074 * the common case), this means that every other allocation has
1075 * to go up a level and every fourth goes up two levels, etc.
1076 * This is not nearly as efficient as it could be if we did a
1077 * little more work up-front.
1078 *
1079 * 3) Split the difference between (1) and (2) by doing a
1080 * two-level split. If it's bigger than some fixed block_size,
1081 * we split it into block_size sized chunks and return all but
1082 * one of them. Then we split what remains into
1083 * state.alloc_size sized chunks and return them.
1084 *
1085 * We choose something close to option (3), which is implemented with
1086 * anv_state_pool_return_chunk(). That is done by returning the
1087 * remaining of the chunk, with alloc_size as a hint of the size that
1088 * we want the smaller chunk split into.
1089 */
1090 anv_state_pool_return_chunk(pool, chunk_offset + alloc_size,
1091 chunk_size - alloc_size, alloc_size);
1092 goto done;
1093 }
1094 }
1095
1096 offset = anv_fixed_size_state_pool_alloc_new(&pool->buckets[bucket],
1097 &pool->block_pool,
1098 alloc_size,
1099 pool->block_size);
1100 /* Everytime we allocate a new state, add it to the state pool */
1101 uint32_t idx;
1102 VkResult result = anv_state_table_add(&pool->table, &idx, 1);
1103 assert(result == VK_SUCCESS);
1104
1105 state = anv_state_table_get(&pool->table, idx);
1106 state->offset = offset;
1107 state->alloc_size = alloc_size;
1108 state->map = anv_block_pool_map(&pool->block_pool, offset);
1109
1110 done:
1111 return *state;
1112 }
1113
1114 struct anv_state
1115 anv_state_pool_alloc(struct anv_state_pool *pool, uint32_t size, uint32_t align)
1116 {
1117 if (size == 0)
1118 return ANV_STATE_NULL;
1119
1120 struct anv_state state = anv_state_pool_alloc_no_vg(pool, size, align);
1121 VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, size));
1122 return state;
1123 }
1124
1125 struct anv_state
1126 anv_state_pool_alloc_back(struct anv_state_pool *pool)
1127 {
1128 struct anv_state *state;
1129 uint32_t alloc_size = pool->block_size;
1130
1131 state = anv_free_list_pop(&pool->back_alloc_free_list, &pool->table);
1132 if (state) {
1133 assert(state->offset < 0);
1134 goto done;
1135 }
1136
1137 int32_t offset;
1138 offset = anv_block_pool_alloc_back(&pool->block_pool,
1139 pool->block_size);
1140 uint32_t idx;
1141 VkResult result = anv_state_table_add(&pool->table, &idx, 1);
1142 assert(result == VK_SUCCESS);
1143
1144 state = anv_state_table_get(&pool->table, idx);
1145 state->offset = offset;
1146 state->alloc_size = alloc_size;
1147 state->map = anv_block_pool_map(&pool->block_pool, state->offset);
1148
1149 done:
1150 VG(VALGRIND_MEMPOOL_ALLOC(pool, state->map, state->alloc_size));
1151 return *state;
1152 }
1153
1154 static void
1155 anv_state_pool_free_no_vg(struct anv_state_pool *pool, struct anv_state state)
1156 {
1157 assert(util_is_power_of_two_or_zero(state.alloc_size));
1158 unsigned bucket = anv_state_pool_get_bucket(state.alloc_size);
1159
1160 if (state.offset < 0) {
1161 assert(state.alloc_size == pool->block_size);
1162 anv_free_list_push(&pool->back_alloc_free_list,
1163 &pool->table, state.idx, 1);
1164 } else {
1165 anv_free_list_push(&pool->buckets[bucket].free_list,
1166 &pool->table, state.idx, 1);
1167 }
1168 }
1169
1170 void
1171 anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state)
1172 {
1173 if (state.alloc_size == 0)
1174 return;
1175
1176 VG(VALGRIND_MEMPOOL_FREE(pool, state.map));
1177 anv_state_pool_free_no_vg(pool, state);
1178 }
1179
1180 struct anv_state_stream_block {
1181 struct anv_state block;
1182
1183 /* The next block */
1184 struct anv_state_stream_block *next;
1185
1186 #ifdef HAVE_VALGRIND
1187 /* A pointer to the first user-allocated thing in this block. This is
1188 * what valgrind sees as the start of the block.
1189 */
1190 void *_vg_ptr;
1191 #endif
1192 };
1193
1194 /* The state stream allocator is a one-shot, single threaded allocator for
1195 * variable sized blocks. We use it for allocating dynamic state.
1196 */
1197 void
1198 anv_state_stream_init(struct anv_state_stream *stream,
1199 struct anv_state_pool *state_pool,
1200 uint32_t block_size)
1201 {
1202 stream->state_pool = state_pool;
1203 stream->block_size = block_size;
1204
1205 stream->block = ANV_STATE_NULL;
1206
1207 stream->block_list = NULL;
1208
1209 /* Ensure that next + whatever > block_size. This way the first call to
1210 * state_stream_alloc fetches a new block.
1211 */
1212 stream->next = block_size;
1213
1214 VG(VALGRIND_CREATE_MEMPOOL(stream, 0, false));
1215 }
1216
1217 void
1218 anv_state_stream_finish(struct anv_state_stream *stream)
1219 {
1220 struct anv_state_stream_block *next = stream->block_list;
1221 while (next != NULL) {
1222 struct anv_state_stream_block sb = VG_NOACCESS_READ(next);
1223 VG(VALGRIND_MEMPOOL_FREE(stream, sb._vg_ptr));
1224 VG(VALGRIND_MAKE_MEM_UNDEFINED(next, stream->block_size));
1225 anv_state_pool_free_no_vg(stream->state_pool, sb.block);
1226 next = sb.next;
1227 }
1228
1229 VG(VALGRIND_DESTROY_MEMPOOL(stream));
1230 }
1231
1232 struct anv_state
1233 anv_state_stream_alloc(struct anv_state_stream *stream,
1234 uint32_t size, uint32_t alignment)
1235 {
1236 if (size == 0)
1237 return ANV_STATE_NULL;
1238
1239 assert(alignment <= PAGE_SIZE);
1240
1241 uint32_t offset = align_u32(stream->next, alignment);
1242 if (offset + size > stream->block.alloc_size) {
1243 uint32_t block_size = stream->block_size;
1244 if (block_size < size)
1245 block_size = round_to_power_of_two(size);
1246
1247 stream->block = anv_state_pool_alloc_no_vg(stream->state_pool,
1248 block_size, PAGE_SIZE);
1249
1250 struct anv_state_stream_block *sb = stream->block.map;
1251 VG_NOACCESS_WRITE(&sb->block, stream->block);
1252 VG_NOACCESS_WRITE(&sb->next, stream->block_list);
1253 stream->block_list = sb;
1254 VG(VG_NOACCESS_WRITE(&sb->_vg_ptr, NULL));
1255
1256 VG(VALGRIND_MAKE_MEM_NOACCESS(stream->block.map, stream->block_size));
1257
1258 /* Reset back to the start plus space for the header */
1259 stream->next = sizeof(*sb);
1260
1261 offset = align_u32(stream->next, alignment);
1262 assert(offset + size <= stream->block.alloc_size);
1263 }
1264
1265 struct anv_state state = stream->block;
1266 state.offset += offset;
1267 state.alloc_size = size;
1268 state.map += offset;
1269
1270 stream->next = offset + size;
1271
1272 #ifdef HAVE_VALGRIND
1273 struct anv_state_stream_block *sb = stream->block_list;
1274 void *vg_ptr = VG_NOACCESS_READ(&sb->_vg_ptr);
1275 if (vg_ptr == NULL) {
1276 vg_ptr = state.map;
1277 VG_NOACCESS_WRITE(&sb->_vg_ptr, vg_ptr);
1278 VALGRIND_MEMPOOL_ALLOC(stream, vg_ptr, size);
1279 } else {
1280 void *state_end = state.map + state.alloc_size;
1281 /* This only updates the mempool. The newly allocated chunk is still
1282 * marked as NOACCESS. */
1283 VALGRIND_MEMPOOL_CHANGE(stream, vg_ptr, vg_ptr, state_end - vg_ptr);
1284 /* Mark the newly allocated chunk as undefined */
1285 VALGRIND_MAKE_MEM_UNDEFINED(state.map, state.alloc_size);
1286 }
1287 #endif
1288
1289 return state;
1290 }
1291
1292 struct bo_pool_bo_link {
1293 struct bo_pool_bo_link *next;
1294 struct anv_bo bo;
1295 };
1296
1297 void
1298 anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device,
1299 uint64_t bo_flags)
1300 {
1301 pool->device = device;
1302 pool->bo_flags = bo_flags;
1303 memset(pool->free_list, 0, sizeof(pool->free_list));
1304
1305 VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
1306 }
1307
1308 void
1309 anv_bo_pool_finish(struct anv_bo_pool *pool)
1310 {
1311 for (unsigned i = 0; i < ARRAY_SIZE(pool->free_list); i++) {
1312 struct bo_pool_bo_link *link = PFL_PTR(pool->free_list[i]);
1313 while (link != NULL) {
1314 struct bo_pool_bo_link link_copy = VG_NOACCESS_READ(link);
1315
1316 anv_gem_munmap(link_copy.bo.map, link_copy.bo.size);
1317 anv_vma_free(pool->device, &link_copy.bo);
1318 anv_gem_close(pool->device, link_copy.bo.gem_handle);
1319 link = link_copy.next;
1320 }
1321 }
1322
1323 VG(VALGRIND_DESTROY_MEMPOOL(pool));
1324 }
1325
1326 VkResult
1327 anv_bo_pool_alloc(struct anv_bo_pool *pool, struct anv_bo *bo, uint32_t size)
1328 {
1329 VkResult result;
1330
1331 const unsigned size_log2 = size < 4096 ? 12 : ilog2_round_up(size);
1332 const unsigned pow2_size = 1 << size_log2;
1333 const unsigned bucket = size_log2 - 12;
1334 assert(bucket < ARRAY_SIZE(pool->free_list));
1335
1336 void *next_free_void;
1337 if (anv_ptr_free_list_pop(&pool->free_list[bucket], &next_free_void)) {
1338 struct bo_pool_bo_link *next_free = next_free_void;
1339 *bo = VG_NOACCESS_READ(&next_free->bo);
1340 assert(bo->gem_handle);
1341 assert(bo->map == next_free);
1342 assert(size <= bo->size);
1343
1344 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
1345
1346 return VK_SUCCESS;
1347 }
1348
1349 struct anv_bo new_bo;
1350
1351 result = anv_bo_init_new(&new_bo, pool->device, pow2_size);
1352 if (result != VK_SUCCESS)
1353 return result;
1354
1355 new_bo.flags = pool->bo_flags;
1356
1357 if (!anv_vma_alloc(pool->device, &new_bo))
1358 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1359
1360 assert(new_bo.size == pow2_size);
1361
1362 new_bo.map = anv_gem_mmap(pool->device, new_bo.gem_handle, 0, pow2_size, 0);
1363 if (new_bo.map == MAP_FAILED) {
1364 anv_gem_close(pool->device, new_bo.gem_handle);
1365 anv_vma_free(pool->device, &new_bo);
1366 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1367 }
1368
1369 *bo = new_bo;
1370
1371 VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
1372
1373 return VK_SUCCESS;
1374 }
1375
1376 void
1377 anv_bo_pool_free(struct anv_bo_pool *pool, const struct anv_bo *bo_in)
1378 {
1379 /* Make a copy in case the anv_bo happens to be storred in the BO */
1380 struct anv_bo bo = *bo_in;
1381
1382 VG(VALGRIND_MEMPOOL_FREE(pool, bo.map));
1383
1384 struct bo_pool_bo_link *link = bo.map;
1385 VG_NOACCESS_WRITE(&link->bo, bo);
1386
1387 assert(util_is_power_of_two_or_zero(bo.size));
1388 const unsigned size_log2 = ilog2_round_up(bo.size);
1389 const unsigned bucket = size_log2 - 12;
1390 assert(bucket < ARRAY_SIZE(pool->free_list));
1391
1392 anv_ptr_free_list_push(&pool->free_list[bucket], link);
1393 }
1394
1395 // Scratch pool
1396
1397 void
1398 anv_scratch_pool_init(struct anv_device *device, struct anv_scratch_pool *pool)
1399 {
1400 memset(pool, 0, sizeof(*pool));
1401 }
1402
1403 void
1404 anv_scratch_pool_finish(struct anv_device *device, struct anv_scratch_pool *pool)
1405 {
1406 for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
1407 for (unsigned i = 0; i < 16; i++) {
1408 struct anv_scratch_bo *bo = &pool->bos[i][s];
1409 if (bo->exists > 0) {
1410 anv_vma_free(device, &bo->bo);
1411 anv_gem_close(device, bo->bo.gem_handle);
1412 }
1413 }
1414 }
1415 }
1416
1417 struct anv_bo *
1418 anv_scratch_pool_alloc(struct anv_device *device, struct anv_scratch_pool *pool,
1419 gl_shader_stage stage, unsigned per_thread_scratch)
1420 {
1421 if (per_thread_scratch == 0)
1422 return NULL;
1423
1424 unsigned scratch_size_log2 = ffs(per_thread_scratch / 2048);
1425 assert(scratch_size_log2 < 16);
1426
1427 struct anv_scratch_bo *bo = &pool->bos[scratch_size_log2][stage];
1428
1429 /* We can use "exists" to shortcut and ignore the critical section */
1430 if (bo->exists)
1431 return &bo->bo;
1432
1433 pthread_mutex_lock(&device->mutex);
1434
1435 __sync_synchronize();
1436 if (bo->exists) {
1437 pthread_mutex_unlock(&device->mutex);
1438 return &bo->bo;
1439 }
1440
1441 const struct anv_physical_device *physical_device =
1442 &device->instance->physicalDevice;
1443 const struct gen_device_info *devinfo = &physical_device->info;
1444
1445 const unsigned subslices = MAX2(physical_device->subslice_total, 1);
1446
1447 unsigned scratch_ids_per_subslice;
1448 if (devinfo->is_haswell) {
1449 /* WaCSScratchSize:hsw
1450 *
1451 * Haswell's scratch space address calculation appears to be sparse
1452 * rather than tightly packed. The Thread ID has bits indicating
1453 * which subslice, EU within a subslice, and thread within an EU it
1454 * is. There's a maximum of two slices and two subslices, so these
1455 * can be stored with a single bit. Even though there are only 10 EUs
1456 * per subslice, this is stored in 4 bits, so there's an effective
1457 * maximum value of 16 EUs. Similarly, although there are only 7
1458 * threads per EU, this is stored in a 3 bit number, giving an
1459 * effective maximum value of 8 threads per EU.
1460 *
1461 * This means that we need to use 16 * 8 instead of 10 * 7 for the
1462 * number of threads per subslice.
1463 */
1464 scratch_ids_per_subslice = 16 * 8;
1465 } else if (devinfo->is_cherryview) {
1466 /* Cherryview devices have either 6 or 8 EUs per subslice, and each EU
1467 * has 7 threads. The 6 EU devices appear to calculate thread IDs as if
1468 * it had 8 EUs.
1469 */
1470 scratch_ids_per_subslice = 8 * 7;
1471 } else {
1472 scratch_ids_per_subslice = devinfo->max_cs_threads;
1473 }
1474
1475 uint32_t max_threads[] = {
1476 [MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
1477 [MESA_SHADER_TESS_CTRL] = devinfo->max_tcs_threads,
1478 [MESA_SHADER_TESS_EVAL] = devinfo->max_tes_threads,
1479 [MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
1480 [MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
1481 [MESA_SHADER_COMPUTE] = scratch_ids_per_subslice * subslices,
1482 };
1483
1484 uint32_t size = per_thread_scratch * max_threads[stage];
1485
1486 anv_bo_init_new(&bo->bo, device, size);
1487
1488 /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1489 * are still relative to the general state base address. When we emit
1490 * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1491 * to the maximum (1 page under 4GB). This allows us to just place the
1492 * scratch buffers anywhere we wish in the bottom 32 bits of address space
1493 * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1494 * However, in order to do so, we need to ensure that the kernel does not
1495 * place the scratch BO above the 32-bit boundary.
1496 *
1497 * NOTE: Technically, it can't go "anywhere" because the top page is off
1498 * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1499 * kernel allocates space using
1500 *
1501 * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1502 *
1503 * so nothing will ever touch the top page.
1504 */
1505 assert(!(bo->bo.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS));
1506
1507 if (device->instance->physicalDevice.has_exec_async)
1508 bo->bo.flags |= EXEC_OBJECT_ASYNC;
1509
1510 if (device->instance->physicalDevice.use_softpin)
1511 bo->bo.flags |= EXEC_OBJECT_PINNED;
1512
1513 anv_vma_alloc(device, &bo->bo);
1514
1515 /* Set the exists last because it may be read by other threads */
1516 __sync_synchronize();
1517 bo->exists = true;
1518
1519 pthread_mutex_unlock(&device->mutex);
1520
1521 return &bo->bo;
1522 }
1523
1524 struct anv_cached_bo {
1525 struct anv_bo bo;
1526
1527 uint32_t refcount;
1528 };
1529
1530 VkResult
1531 anv_bo_cache_init(struct anv_bo_cache *cache)
1532 {
1533 cache->bo_map = _mesa_pointer_hash_table_create(NULL);
1534 if (!cache->bo_map)
1535 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1536
1537 if (pthread_mutex_init(&cache->mutex, NULL)) {
1538 _mesa_hash_table_destroy(cache->bo_map, NULL);
1539 return vk_errorf(NULL, NULL, VK_ERROR_OUT_OF_HOST_MEMORY,
1540 "pthread_mutex_init failed: %m");
1541 }
1542
1543 return VK_SUCCESS;
1544 }
1545
1546 void
1547 anv_bo_cache_finish(struct anv_bo_cache *cache)
1548 {
1549 _mesa_hash_table_destroy(cache->bo_map, NULL);
1550 pthread_mutex_destroy(&cache->mutex);
1551 }
1552
1553 static struct anv_cached_bo *
1554 anv_bo_cache_lookup_locked(struct anv_bo_cache *cache, uint32_t gem_handle)
1555 {
1556 struct hash_entry *entry =
1557 _mesa_hash_table_search(cache->bo_map,
1558 (const void *)(uintptr_t)gem_handle);
1559 if (!entry)
1560 return NULL;
1561
1562 struct anv_cached_bo *bo = (struct anv_cached_bo *)entry->data;
1563 assert(bo->bo.gem_handle == gem_handle);
1564
1565 return bo;
1566 }
1567
1568 UNUSED static struct anv_bo *
1569 anv_bo_cache_lookup(struct anv_bo_cache *cache, uint32_t gem_handle)
1570 {
1571 pthread_mutex_lock(&cache->mutex);
1572
1573 struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
1574
1575 pthread_mutex_unlock(&cache->mutex);
1576
1577 return bo ? &bo->bo : NULL;
1578 }
1579
1580 #define ANV_BO_CACHE_SUPPORTED_FLAGS \
1581 (EXEC_OBJECT_WRITE | \
1582 EXEC_OBJECT_ASYNC | \
1583 EXEC_OBJECT_SUPPORTS_48B_ADDRESS | \
1584 EXEC_OBJECT_PINNED | \
1585 ANV_BO_EXTERNAL)
1586
1587 VkResult
1588 anv_bo_cache_alloc(struct anv_device *device,
1589 struct anv_bo_cache *cache,
1590 uint64_t size, uint64_t bo_flags,
1591 struct anv_bo **bo_out)
1592 {
1593 assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1594
1595 struct anv_cached_bo *bo =
1596 vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
1597 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1598 if (!bo)
1599 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1600
1601 bo->refcount = 1;
1602
1603 /* The kernel is going to give us whole pages anyway */
1604 size = align_u64(size, 4096);
1605
1606 VkResult result = anv_bo_init_new(&bo->bo, device, size);
1607 if (result != VK_SUCCESS) {
1608 vk_free(&device->alloc, bo);
1609 return result;
1610 }
1611
1612 bo->bo.flags = bo_flags;
1613
1614 if (!anv_vma_alloc(device, &bo->bo)) {
1615 anv_gem_close(device, bo->bo.gem_handle);
1616 vk_free(&device->alloc, bo);
1617 return vk_errorf(device->instance, NULL,
1618 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1619 "failed to allocate virtual address for BO");
1620 }
1621
1622 assert(bo->bo.gem_handle);
1623
1624 pthread_mutex_lock(&cache->mutex);
1625
1626 _mesa_hash_table_insert(cache->bo_map,
1627 (void *)(uintptr_t)bo->bo.gem_handle, bo);
1628
1629 pthread_mutex_unlock(&cache->mutex);
1630
1631 *bo_out = &bo->bo;
1632
1633 return VK_SUCCESS;
1634 }
1635
1636 VkResult
1637 anv_bo_cache_import(struct anv_device *device,
1638 struct anv_bo_cache *cache,
1639 int fd, uint64_t bo_flags,
1640 struct anv_bo **bo_out)
1641 {
1642 assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1643 assert(bo_flags & ANV_BO_EXTERNAL);
1644
1645 pthread_mutex_lock(&cache->mutex);
1646
1647 uint32_t gem_handle = anv_gem_fd_to_handle(device, fd);
1648 if (!gem_handle) {
1649 pthread_mutex_unlock(&cache->mutex);
1650 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
1651 }
1652
1653 struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
1654 if (bo) {
1655 /* We have to be careful how we combine flags so that it makes sense.
1656 * Really, though, if we get to this case and it actually matters, the
1657 * client has imported a BO twice in different ways and they get what
1658 * they have coming.
1659 */
1660 uint64_t new_flags = ANV_BO_EXTERNAL;
1661 new_flags |= (bo->bo.flags | bo_flags) & EXEC_OBJECT_WRITE;
1662 new_flags |= (bo->bo.flags & bo_flags) & EXEC_OBJECT_ASYNC;
1663 new_flags |= (bo->bo.flags & bo_flags) & EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1664 new_flags |= (bo->bo.flags | bo_flags) & EXEC_OBJECT_PINNED;
1665
1666 /* It's theoretically possible for a BO to get imported such that it's
1667 * both pinned and not pinned. The only way this can happen is if it
1668 * gets imported as both a semaphore and a memory object and that would
1669 * be an application error. Just fail out in that case.
1670 */
1671 if ((bo->bo.flags & EXEC_OBJECT_PINNED) !=
1672 (bo_flags & EXEC_OBJECT_PINNED)) {
1673 pthread_mutex_unlock(&cache->mutex);
1674 return vk_errorf(device->instance, NULL,
1675 VK_ERROR_INVALID_EXTERNAL_HANDLE,
1676 "The same BO was imported two different ways");
1677 }
1678
1679 /* It's also theoretically possible that someone could export a BO from
1680 * one heap and import it into another or to import the same BO into two
1681 * different heaps. If this happens, we could potentially end up both
1682 * allowing and disallowing 48-bit addresses. There's not much we can
1683 * do about it if we're pinning so we just throw an error and hope no
1684 * app is actually that stupid.
1685 */
1686 if ((new_flags & EXEC_OBJECT_PINNED) &&
1687 (bo->bo.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) !=
1688 (bo_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS)) {
1689 pthread_mutex_unlock(&cache->mutex);
1690 return vk_errorf(device->instance, NULL,
1691 VK_ERROR_INVALID_EXTERNAL_HANDLE,
1692 "The same BO was imported on two different heaps");
1693 }
1694
1695 bo->bo.flags = new_flags;
1696
1697 __sync_fetch_and_add(&bo->refcount, 1);
1698 } else {
1699 off_t size = lseek(fd, 0, SEEK_END);
1700 if (size == (off_t)-1) {
1701 anv_gem_close(device, gem_handle);
1702 pthread_mutex_unlock(&cache->mutex);
1703 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
1704 }
1705
1706 bo = vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
1707 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1708 if (!bo) {
1709 anv_gem_close(device, gem_handle);
1710 pthread_mutex_unlock(&cache->mutex);
1711 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1712 }
1713
1714 bo->refcount = 1;
1715
1716 anv_bo_init(&bo->bo, gem_handle, size);
1717 bo->bo.flags = bo_flags;
1718
1719 if (!anv_vma_alloc(device, &bo->bo)) {
1720 anv_gem_close(device, bo->bo.gem_handle);
1721 pthread_mutex_unlock(&cache->mutex);
1722 vk_free(&device->alloc, bo);
1723 return vk_errorf(device->instance, NULL,
1724 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1725 "failed to allocate virtual address for BO");
1726 }
1727
1728 _mesa_hash_table_insert(cache->bo_map, (void *)(uintptr_t)gem_handle, bo);
1729 }
1730
1731 pthread_mutex_unlock(&cache->mutex);
1732 *bo_out = &bo->bo;
1733
1734 return VK_SUCCESS;
1735 }
1736
1737 VkResult
1738 anv_bo_cache_export(struct anv_device *device,
1739 struct anv_bo_cache *cache,
1740 struct anv_bo *bo_in, int *fd_out)
1741 {
1742 assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
1743 struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
1744
1745 /* This BO must have been flagged external in order for us to be able
1746 * to export it. This is done based on external options passed into
1747 * anv_AllocateMemory.
1748 */
1749 assert(bo->bo.flags & ANV_BO_EXTERNAL);
1750
1751 int fd = anv_gem_handle_to_fd(device, bo->bo.gem_handle);
1752 if (fd < 0)
1753 return vk_error(VK_ERROR_TOO_MANY_OBJECTS);
1754
1755 *fd_out = fd;
1756
1757 return VK_SUCCESS;
1758 }
1759
1760 static bool
1761 atomic_dec_not_one(uint32_t *counter)
1762 {
1763 uint32_t old, val;
1764
1765 val = *counter;
1766 while (1) {
1767 if (val == 1)
1768 return false;
1769
1770 old = __sync_val_compare_and_swap(counter, val, val - 1);
1771 if (old == val)
1772 return true;
1773
1774 val = old;
1775 }
1776 }
1777
1778 void
1779 anv_bo_cache_release(struct anv_device *device,
1780 struct anv_bo_cache *cache,
1781 struct anv_bo *bo_in)
1782 {
1783 assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
1784 struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
1785
1786 /* Try to decrement the counter but don't go below one. If this succeeds
1787 * then the refcount has been decremented and we are not the last
1788 * reference.
1789 */
1790 if (atomic_dec_not_one(&bo->refcount))
1791 return;
1792
1793 pthread_mutex_lock(&cache->mutex);
1794
1795 /* We are probably the last reference since our attempt to decrement above
1796 * failed. However, we can't actually know until we are inside the mutex.
1797 * Otherwise, someone could import the BO between the decrement and our
1798 * taking the mutex.
1799 */
1800 if (unlikely(__sync_sub_and_fetch(&bo->refcount, 1) > 0)) {
1801 /* Turns out we're not the last reference. Unlock and bail. */
1802 pthread_mutex_unlock(&cache->mutex);
1803 return;
1804 }
1805
1806 struct hash_entry *entry =
1807 _mesa_hash_table_search(cache->bo_map,
1808 (const void *)(uintptr_t)bo->bo.gem_handle);
1809 assert(entry);
1810 _mesa_hash_table_remove(cache->bo_map, entry);
1811
1812 if (bo->bo.map)
1813 anv_gem_munmap(bo->bo.map, bo->bo.size);
1814
1815 anv_vma_free(device, &bo->bo);
1816
1817 anv_gem_close(device, bo->bo.gem_handle);
1818
1819 /* Don't unlock until we've actually closed the BO. The whole point of
1820 * the BO cache is to ensure that we correctly handle races with creating
1821 * and releasing GEM handles and we don't want to let someone import the BO
1822 * again between mutex unlock and closing the GEM handle.
1823 */
1824 pthread_mutex_unlock(&cache->mutex);
1825
1826 vk_free(&device->alloc, bo);
1827 }