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