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