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