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