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