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