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