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