iris: Make use of devinfo has_aux_map field
[mesa.git] / src / gallium / drivers / iris / iris_bufmgr.c
1 /*
2 * Copyright © 2017 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 shall be included
12 * in all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 */
22
23 /**
24 * @file iris_bufmgr.c
25 *
26 * The Iris buffer manager.
27 *
28 * XXX: write better comments
29 * - BOs
30 * - Explain BO cache
31 * - main interface to GEM in the kernel
32 */
33
34 #include <xf86drm.h>
35 #include <util/u_atomic.h>
36 #include <fcntl.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <assert.h>
42 #include <sys/ioctl.h>
43 #include <sys/mman.h>
44 #include <sys/stat.h>
45 #include <sys/types.h>
46 #include <stdbool.h>
47 #include <time.h>
48 #include <unistd.h>
49
50 #include "errno.h"
51 #include "common/gen_aux_map.h"
52 #include "common/gen_clflush.h"
53 #include "dev/gen_debug.h"
54 #include "common/gen_gem.h"
55 #include "dev/gen_device_info.h"
56 #include "main/macros.h"
57 #include "os/os_mman.h"
58 #include "util/debug.h"
59 #include "util/macros.h"
60 #include "util/hash_table.h"
61 #include "util/list.h"
62 #include "util/os_file.h"
63 #include "util/u_dynarray.h"
64 #include "util/vma.h"
65 #include "iris_bufmgr.h"
66 #include "iris_context.h"
67 #include "string.h"
68
69 #include "drm-uapi/i915_drm.h"
70
71 #ifdef HAVE_VALGRIND
72 #include <valgrind.h>
73 #include <memcheck.h>
74 #define VG(x) x
75 #else
76 #define VG(x)
77 #endif
78
79 /* VALGRIND_FREELIKE_BLOCK unfortunately does not actually undo the earlier
80 * VALGRIND_MALLOCLIKE_BLOCK but instead leaves vg convinced the memory is
81 * leaked. All because it does not call VG(cli_free) from its
82 * VG_USERREQ__FREELIKE_BLOCK handler. Instead of treating the memory like
83 * and allocation, we mark it available for use upon mmapping and remove
84 * it upon unmapping.
85 */
86 #define VG_DEFINED(ptr, size) VG(VALGRIND_MAKE_MEM_DEFINED(ptr, size))
87 #define VG_NOACCESS(ptr, size) VG(VALGRIND_MAKE_MEM_NOACCESS(ptr, size))
88
89 #define PAGE_SIZE 4096
90
91 #define WARN_ONCE(cond, fmt...) do { \
92 if (unlikely(cond)) { \
93 static bool _warned = false; \
94 if (!_warned) { \
95 fprintf(stderr, "WARNING: "); \
96 fprintf(stderr, fmt); \
97 _warned = true; \
98 } \
99 } \
100 } while (0)
101
102 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
103
104 static inline int
105 atomic_add_unless(int *v, int add, int unless)
106 {
107 int c, old;
108 c = p_atomic_read(v);
109 while (c != unless && (old = p_atomic_cmpxchg(v, c, c + add)) != c)
110 c = old;
111 return c == unless;
112 }
113
114 static const char *
115 memzone_name(enum iris_memory_zone memzone)
116 {
117 const char *names[] = {
118 [IRIS_MEMZONE_SHADER] = "shader",
119 [IRIS_MEMZONE_BINDER] = "binder",
120 [IRIS_MEMZONE_SURFACE] = "surface",
121 [IRIS_MEMZONE_DYNAMIC] = "dynamic",
122 [IRIS_MEMZONE_OTHER] = "other",
123 [IRIS_MEMZONE_BORDER_COLOR_POOL] = "bordercolor",
124 };
125 assert(memzone < ARRAY_SIZE(names));
126 return names[memzone];
127 }
128
129 struct bo_cache_bucket {
130 /** List of cached BOs. */
131 struct list_head head;
132
133 /** Size of this bucket, in bytes. */
134 uint64_t size;
135 };
136
137 struct bo_export {
138 /** File descriptor associated with a handle export. */
139 int drm_fd;
140
141 /** GEM handle in drm_fd */
142 uint32_t gem_handle;
143
144 struct list_head link;
145 };
146
147 struct iris_bufmgr {
148 /**
149 * List into the list of bufmgr.
150 */
151 struct list_head link;
152
153 uint32_t refcount;
154
155 int fd;
156
157 mtx_t lock;
158
159 /** Array of lists of cached gem objects of power-of-two sizes */
160 struct bo_cache_bucket cache_bucket[14 * 4];
161 int num_buckets;
162 time_t time;
163
164 struct hash_table *name_table;
165 struct hash_table *handle_table;
166
167 /**
168 * List of BOs which we've effectively freed, but are hanging on to
169 * until they're idle before closing and returning the VMA.
170 */
171 struct list_head zombie_list;
172
173 struct util_vma_heap vma_allocator[IRIS_MEMZONE_COUNT];
174
175 bool has_llc:1;
176 bool has_mmap_offset:1;
177 bool has_tiling_uapi:1;
178 bool bo_reuse:1;
179
180 struct gen_aux_map_context *aux_map_ctx;
181 };
182
183 static mtx_t global_bufmgr_list_mutex = _MTX_INITIALIZER_NP;
184 static struct list_head global_bufmgr_list = {
185 .next = &global_bufmgr_list,
186 .prev = &global_bufmgr_list,
187 };
188
189 static int bo_set_tiling_internal(struct iris_bo *bo, uint32_t tiling_mode,
190 uint32_t stride);
191
192 static void bo_free(struct iris_bo *bo);
193
194 static struct iris_bo *
195 find_and_ref_external_bo(struct hash_table *ht, unsigned int key)
196 {
197 struct hash_entry *entry = _mesa_hash_table_search(ht, &key);
198 struct iris_bo *bo = entry ? entry->data : NULL;
199
200 if (bo) {
201 assert(bo->external);
202 assert(!bo->reusable);
203
204 /* Being non-reusable, the BO cannot be in the cache lists, but it
205 * may be in the zombie list if it had reached zero references, but
206 * we hadn't yet closed it...and then reimported the same BO. If it
207 * is, then remove it since it's now been resurrected.
208 */
209 if (bo->head.prev || bo->head.next)
210 list_del(&bo->head);
211
212 iris_bo_reference(bo);
213 }
214
215 return bo;
216 }
217
218 /**
219 * This function finds the correct bucket fit for the input size.
220 * The function works with O(1) complexity when the requested size
221 * was queried instead of iterating the size through all the buckets.
222 */
223 static struct bo_cache_bucket *
224 bucket_for_size(struct iris_bufmgr *bufmgr, uint64_t size)
225 {
226 /* Calculating the pages and rounding up to the page size. */
227 const unsigned pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
228
229 /* Row Bucket sizes clz((x-1) | 3) Row Column
230 * in pages stride size
231 * 0: 1 2 3 4 -> 30 30 30 30 4 1
232 * 1: 5 6 7 8 -> 29 29 29 29 4 1
233 * 2: 10 12 14 16 -> 28 28 28 28 8 2
234 * 3: 20 24 28 32 -> 27 27 27 27 16 4
235 */
236 const unsigned row = 30 - __builtin_clz((pages - 1) | 3);
237 const unsigned row_max_pages = 4 << row;
238
239 /* The '& ~2' is the special case for row 1. In row 1, max pages /
240 * 2 is 2, but the previous row maximum is zero (because there is
241 * no previous row). All row maximum sizes are power of 2, so that
242 * is the only case where that bit will be set.
243 */
244 const unsigned prev_row_max_pages = (row_max_pages / 2) & ~2;
245 int col_size_log2 = row - 1;
246 col_size_log2 += (col_size_log2 < 0);
247
248 const unsigned col = (pages - prev_row_max_pages +
249 ((1 << col_size_log2) - 1)) >> col_size_log2;
250
251 /* Calculating the index based on the row and column. */
252 const unsigned index = (row * 4) + (col - 1);
253
254 return (index < bufmgr->num_buckets) ?
255 &bufmgr->cache_bucket[index] : NULL;
256 }
257
258 enum iris_memory_zone
259 iris_memzone_for_address(uint64_t address)
260 {
261 STATIC_ASSERT(IRIS_MEMZONE_OTHER_START > IRIS_MEMZONE_DYNAMIC_START);
262 STATIC_ASSERT(IRIS_MEMZONE_DYNAMIC_START > IRIS_MEMZONE_SURFACE_START);
263 STATIC_ASSERT(IRIS_MEMZONE_SURFACE_START > IRIS_MEMZONE_BINDER_START);
264 STATIC_ASSERT(IRIS_MEMZONE_BINDER_START > IRIS_MEMZONE_SHADER_START);
265 STATIC_ASSERT(IRIS_BORDER_COLOR_POOL_ADDRESS == IRIS_MEMZONE_DYNAMIC_START);
266
267 if (address >= IRIS_MEMZONE_OTHER_START)
268 return IRIS_MEMZONE_OTHER;
269
270 if (address == IRIS_BORDER_COLOR_POOL_ADDRESS)
271 return IRIS_MEMZONE_BORDER_COLOR_POOL;
272
273 if (address > IRIS_MEMZONE_DYNAMIC_START)
274 return IRIS_MEMZONE_DYNAMIC;
275
276 if (address >= IRIS_MEMZONE_SURFACE_START)
277 return IRIS_MEMZONE_SURFACE;
278
279 if (address >= IRIS_MEMZONE_BINDER_START)
280 return IRIS_MEMZONE_BINDER;
281
282 return IRIS_MEMZONE_SHADER;
283 }
284
285 /**
286 * Allocate a section of virtual memory for a buffer, assigning an address.
287 *
288 * This uses either the bucket allocator for the given size, or the large
289 * object allocator (util_vma).
290 */
291 static uint64_t
292 vma_alloc(struct iris_bufmgr *bufmgr,
293 enum iris_memory_zone memzone,
294 uint64_t size,
295 uint64_t alignment)
296 {
297 /* Force alignment to be some number of pages */
298 alignment = ALIGN(alignment, PAGE_SIZE);
299
300 if (memzone == IRIS_MEMZONE_BORDER_COLOR_POOL)
301 return IRIS_BORDER_COLOR_POOL_ADDRESS;
302
303 /* The binder handles its own allocations. Return non-zero here. */
304 if (memzone == IRIS_MEMZONE_BINDER)
305 return IRIS_MEMZONE_BINDER_START;
306
307 uint64_t addr =
308 util_vma_heap_alloc(&bufmgr->vma_allocator[memzone], size, alignment);
309
310 assert((addr >> 48ull) == 0);
311 assert((addr % alignment) == 0);
312
313 return gen_canonical_address(addr);
314 }
315
316 static void
317 vma_free(struct iris_bufmgr *bufmgr,
318 uint64_t address,
319 uint64_t size)
320 {
321 if (address == IRIS_BORDER_COLOR_POOL_ADDRESS)
322 return;
323
324 /* Un-canonicalize the address. */
325 address = gen_48b_address(address);
326
327 if (address == 0ull)
328 return;
329
330 enum iris_memory_zone memzone = iris_memzone_for_address(address);
331
332 /* The binder handles its own allocations. */
333 if (memzone == IRIS_MEMZONE_BINDER)
334 return;
335
336 util_vma_heap_free(&bufmgr->vma_allocator[memzone], address, size);
337 }
338
339 int
340 iris_bo_busy(struct iris_bo *bo)
341 {
342 struct iris_bufmgr *bufmgr = bo->bufmgr;
343 struct drm_i915_gem_busy busy = { .handle = bo->gem_handle };
344
345 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_BUSY, &busy);
346 if (ret == 0) {
347 bo->idle = !busy.busy;
348 return busy.busy;
349 }
350 return false;
351 }
352
353 int
354 iris_bo_madvise(struct iris_bo *bo, int state)
355 {
356 struct drm_i915_gem_madvise madv = {
357 .handle = bo->gem_handle,
358 .madv = state,
359 .retained = 1,
360 };
361
362 gen_ioctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_MADVISE, &madv);
363
364 return madv.retained;
365 }
366
367 static struct iris_bo *
368 bo_calloc(void)
369 {
370 struct iris_bo *bo = calloc(1, sizeof(*bo));
371 if (!bo)
372 return NULL;
373
374 list_inithead(&bo->exports);
375
376 bo->hash = _mesa_hash_pointer(bo);
377
378 return bo;
379 }
380
381 static struct iris_bo *
382 alloc_bo_from_cache(struct iris_bufmgr *bufmgr,
383 struct bo_cache_bucket *bucket,
384 uint32_t alignment,
385 enum iris_memory_zone memzone,
386 unsigned flags,
387 bool match_zone)
388 {
389 if (!bucket)
390 return NULL;
391
392 struct iris_bo *bo = NULL;
393
394 list_for_each_entry_safe(struct iris_bo, cur, &bucket->head, head) {
395 /* Try a little harder to find one that's already in the right memzone */
396 if (match_zone && memzone != iris_memzone_for_address(cur->gtt_offset))
397 continue;
398
399 /* If the last BO in the cache is busy, there are no idle BOs. Bail,
400 * either falling back to a non-matching memzone, or if that fails,
401 * allocating a fresh buffer.
402 */
403 if (iris_bo_busy(cur))
404 return NULL;
405
406 list_del(&cur->head);
407
408 /* Tell the kernel we need this BO. If it still exists, we're done! */
409 if (iris_bo_madvise(cur, I915_MADV_WILLNEED)) {
410 bo = cur;
411 break;
412 }
413
414 /* This BO was purged, throw it out and keep looking. */
415 bo_free(cur);
416 }
417
418 if (!bo)
419 return NULL;
420
421 if (bo->aux_map_address) {
422 /* This buffer was associated with an aux-buffer range. We make sure
423 * that buffers are not reused from the cache while the buffer is (busy)
424 * being used by an executing batch. Since we are here, the buffer is no
425 * longer being used by a batch and the buffer was deleted (in order to
426 * end up in the cache). Therefore its old aux-buffer range can be
427 * removed from the aux-map.
428 */
429 if (bo->bufmgr->aux_map_ctx)
430 gen_aux_map_unmap_range(bo->bufmgr->aux_map_ctx, bo->gtt_offset,
431 bo->size);
432 bo->aux_map_address = 0;
433 }
434
435 /* If the cached BO isn't in the right memory zone, or the alignment
436 * isn't sufficient, free the old memory and assign it a new address.
437 */
438 if (memzone != iris_memzone_for_address(bo->gtt_offset) ||
439 bo->gtt_offset % alignment != 0) {
440 vma_free(bufmgr, bo->gtt_offset, bo->size);
441 bo->gtt_offset = 0ull;
442 }
443
444 /* Zero the contents if necessary. If this fails, fall back to
445 * allocating a fresh BO, which will always be zeroed by the kernel.
446 */
447 if (flags & BO_ALLOC_ZEROED) {
448 void *map = iris_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
449 if (map) {
450 memset(map, 0, bo->size);
451 } else {
452 bo_free(bo);
453 return NULL;
454 }
455 }
456
457 return bo;
458 }
459
460 static struct iris_bo *
461 alloc_fresh_bo(struct iris_bufmgr *bufmgr, uint64_t bo_size)
462 {
463 struct iris_bo *bo = bo_calloc();
464 if (!bo)
465 return NULL;
466
467 struct drm_i915_gem_create create = { .size = bo_size };
468
469 /* All new BOs we get from the kernel are zeroed, so we don't need to
470 * worry about that here.
471 */
472 if (gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CREATE, &create) != 0) {
473 free(bo);
474 return NULL;
475 }
476
477 bo->gem_handle = create.handle;
478 bo->bufmgr = bufmgr;
479 bo->size = bo_size;
480 bo->idle = true;
481 bo->tiling_mode = I915_TILING_NONE;
482 bo->stride = 0;
483
484 /* Calling set_domain() will allocate pages for the BO outside of the
485 * struct mutex lock in the kernel, which is more efficient than waiting
486 * to create them during the first execbuf that uses the BO.
487 */
488 struct drm_i915_gem_set_domain sd = {
489 .handle = bo->gem_handle,
490 .read_domains = I915_GEM_DOMAIN_CPU,
491 .write_domain = 0,
492 };
493
494 if (gen_ioctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd) != 0) {
495 bo_free(bo);
496 return NULL;
497 }
498
499 return bo;
500 }
501
502 static struct iris_bo *
503 bo_alloc_internal(struct iris_bufmgr *bufmgr,
504 const char *name,
505 uint64_t size,
506 uint32_t alignment,
507 enum iris_memory_zone memzone,
508 unsigned flags,
509 uint32_t tiling_mode,
510 uint32_t stride)
511 {
512 struct iris_bo *bo;
513 unsigned int page_size = getpagesize();
514 struct bo_cache_bucket *bucket = bucket_for_size(bufmgr, size);
515
516 /* Round the size up to the bucket size, or if we don't have caching
517 * at this size, a multiple of the page size.
518 */
519 uint64_t bo_size =
520 bucket ? bucket->size : MAX2(ALIGN(size, page_size), page_size);
521
522 mtx_lock(&bufmgr->lock);
523
524 /* Get a buffer out of the cache if available. First, we try to find
525 * one with a matching memory zone so we can avoid reallocating VMA.
526 */
527 bo = alloc_bo_from_cache(bufmgr, bucket, alignment, memzone, flags, true);
528
529 /* If that fails, we try for any cached BO, without matching memzone. */
530 if (!bo) {
531 bo = alloc_bo_from_cache(bufmgr, bucket, alignment, memzone, flags,
532 false);
533 }
534
535 mtx_unlock(&bufmgr->lock);
536
537 if (!bo) {
538 bo = alloc_fresh_bo(bufmgr, bo_size);
539 if (!bo)
540 return NULL;
541 }
542
543 if (bo->gtt_offset == 0ull) {
544 mtx_lock(&bufmgr->lock);
545 bo->gtt_offset = vma_alloc(bufmgr, memzone, bo->size, alignment);
546 mtx_unlock(&bufmgr->lock);
547
548 if (bo->gtt_offset == 0ull)
549 goto err_free;
550 }
551
552 if (bo_set_tiling_internal(bo, tiling_mode, stride))
553 goto err_free;
554
555 bo->name = name;
556 p_atomic_set(&bo->refcount, 1);
557 bo->reusable = bucket && bufmgr->bo_reuse;
558 bo->cache_coherent = bufmgr->has_llc;
559 bo->index = -1;
560 bo->kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
561
562 /* By default, capture all driver-internal buffers like shader kernels,
563 * surface states, dynamic states, border colors, and so on.
564 */
565 if (memzone < IRIS_MEMZONE_OTHER)
566 bo->kflags |= EXEC_OBJECT_CAPTURE;
567
568 if ((flags & BO_ALLOC_COHERENT) && !bo->cache_coherent) {
569 struct drm_i915_gem_caching arg = {
570 .handle = bo->gem_handle,
571 .caching = 1,
572 };
573 if (gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_CACHING, &arg) == 0) {
574 bo->cache_coherent = true;
575 bo->reusable = false;
576 }
577 }
578
579 DBG("bo_create: buf %d (%s) (%s memzone) %llub\n", bo->gem_handle,
580 bo->name, memzone_name(memzone), (unsigned long long) size);
581
582 return bo;
583
584 err_free:
585 bo_free(bo);
586 return NULL;
587 }
588
589 struct iris_bo *
590 iris_bo_alloc(struct iris_bufmgr *bufmgr,
591 const char *name,
592 uint64_t size,
593 enum iris_memory_zone memzone)
594 {
595 return bo_alloc_internal(bufmgr, name, size, 1, memzone,
596 0, I915_TILING_NONE, 0);
597 }
598
599 struct iris_bo *
600 iris_bo_alloc_tiled(struct iris_bufmgr *bufmgr, const char *name,
601 uint64_t size, uint32_t alignment,
602 enum iris_memory_zone memzone,
603 uint32_t tiling_mode, uint32_t pitch, unsigned flags)
604 {
605 return bo_alloc_internal(bufmgr, name, size, alignment, memzone,
606 flags, tiling_mode, pitch);
607 }
608
609 struct iris_bo *
610 iris_bo_create_userptr(struct iris_bufmgr *bufmgr, const char *name,
611 void *ptr, size_t size,
612 enum iris_memory_zone memzone)
613 {
614 struct drm_gem_close close = { 0, };
615 struct iris_bo *bo;
616
617 bo = bo_calloc();
618 if (!bo)
619 return NULL;
620
621 struct drm_i915_gem_userptr arg = {
622 .user_ptr = (uintptr_t)ptr,
623 .user_size = size,
624 };
625 if (gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_USERPTR, &arg))
626 goto err_free;
627 bo->gem_handle = arg.handle;
628
629 /* Check the buffer for validity before we try and use it in a batch */
630 struct drm_i915_gem_set_domain sd = {
631 .handle = bo->gem_handle,
632 .read_domains = I915_GEM_DOMAIN_CPU,
633 };
634 if (gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd))
635 goto err_close;
636
637 bo->name = name;
638 bo->size = size;
639 bo->map_cpu = ptr;
640
641 bo->bufmgr = bufmgr;
642 bo->kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
643
644 mtx_lock(&bufmgr->lock);
645 bo->gtt_offset = vma_alloc(bufmgr, memzone, size, 1);
646 mtx_unlock(&bufmgr->lock);
647
648 if (bo->gtt_offset == 0ull)
649 goto err_close;
650
651 p_atomic_set(&bo->refcount, 1);
652 bo->userptr = true;
653 bo->cache_coherent = true;
654 bo->index = -1;
655 bo->idle = true;
656
657 return bo;
658
659 err_close:
660 close.handle = bo->gem_handle;
661 gen_ioctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
662 err_free:
663 free(bo);
664 return NULL;
665 }
666
667 /**
668 * Returns a iris_bo wrapping the given buffer object handle.
669 *
670 * This can be used when one application needs to pass a buffer object
671 * to another.
672 */
673 struct iris_bo *
674 iris_bo_gem_create_from_name(struct iris_bufmgr *bufmgr,
675 const char *name, unsigned int handle)
676 {
677 struct iris_bo *bo;
678
679 /* At the moment most applications only have a few named bo.
680 * For instance, in a DRI client only the render buffers passed
681 * between X and the client are named. And since X returns the
682 * alternating names for the front/back buffer a linear search
683 * provides a sufficiently fast match.
684 */
685 mtx_lock(&bufmgr->lock);
686 bo = find_and_ref_external_bo(bufmgr->name_table, handle);
687 if (bo)
688 goto out;
689
690 struct drm_gem_open open_arg = { .name = handle };
691 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
692 if (ret != 0) {
693 DBG("Couldn't reference %s handle 0x%08x: %s\n",
694 name, handle, strerror(errno));
695 bo = NULL;
696 goto out;
697 }
698 /* Now see if someone has used a prime handle to get this
699 * object from the kernel before by looking through the list
700 * again for a matching gem_handle
701 */
702 bo = find_and_ref_external_bo(bufmgr->handle_table, open_arg.handle);
703 if (bo)
704 goto out;
705
706 bo = bo_calloc();
707 if (!bo)
708 goto out;
709
710 p_atomic_set(&bo->refcount, 1);
711
712 bo->size = open_arg.size;
713 bo->bufmgr = bufmgr;
714 bo->gem_handle = open_arg.handle;
715 bo->name = name;
716 bo->global_name = handle;
717 bo->reusable = false;
718 bo->external = true;
719 bo->kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
720 bo->gtt_offset = vma_alloc(bufmgr, IRIS_MEMZONE_OTHER, bo->size, 1);
721
722 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
723 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
724
725 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
726 ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling);
727 if (ret != 0)
728 goto err_unref;
729
730 bo->tiling_mode = get_tiling.tiling_mode;
731
732 /* XXX stride is unknown */
733 DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
734
735 out:
736 mtx_unlock(&bufmgr->lock);
737 return bo;
738
739 err_unref:
740 bo_free(bo);
741 mtx_unlock(&bufmgr->lock);
742 return NULL;
743 }
744
745 static void
746 bo_close(struct iris_bo *bo)
747 {
748 struct iris_bufmgr *bufmgr = bo->bufmgr;
749
750 if (bo->external) {
751 struct hash_entry *entry;
752
753 if (bo->global_name) {
754 entry = _mesa_hash_table_search(bufmgr->name_table, &bo->global_name);
755 _mesa_hash_table_remove(bufmgr->name_table, entry);
756 }
757
758 entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
759 _mesa_hash_table_remove(bufmgr->handle_table, entry);
760
761 list_for_each_entry_safe(struct bo_export, export, &bo->exports, link) {
762 struct drm_gem_close close = { .handle = export->gem_handle };
763 gen_ioctl(export->drm_fd, DRM_IOCTL_GEM_CLOSE, &close);
764
765 list_del(&export->link);
766 free(export);
767 }
768 } else {
769 assert(list_is_empty(&bo->exports));
770 }
771
772 /* Close this object */
773 struct drm_gem_close close = { .handle = bo->gem_handle };
774 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
775 if (ret != 0) {
776 DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
777 bo->gem_handle, bo->name, strerror(errno));
778 }
779
780 if (bo->aux_map_address && bo->bufmgr->aux_map_ctx) {
781 gen_aux_map_unmap_range(bo->bufmgr->aux_map_ctx, bo->gtt_offset,
782 bo->size);
783 }
784
785 /* Return the VMA for reuse */
786 vma_free(bo->bufmgr, bo->gtt_offset, bo->size);
787
788 free(bo);
789 }
790
791 static void
792 bo_free(struct iris_bo *bo)
793 {
794 struct iris_bufmgr *bufmgr = bo->bufmgr;
795
796 if (bo->map_cpu && !bo->userptr) {
797 VG_NOACCESS(bo->map_cpu, bo->size);
798 os_munmap(bo->map_cpu, bo->size);
799 }
800 if (bo->map_wc) {
801 VG_NOACCESS(bo->map_wc, bo->size);
802 os_munmap(bo->map_wc, bo->size);
803 }
804 if (bo->map_gtt) {
805 VG_NOACCESS(bo->map_gtt, bo->size);
806 os_munmap(bo->map_gtt, bo->size);
807 }
808
809 if (bo->idle) {
810 bo_close(bo);
811 } else {
812 /* Defer closing the GEM BO and returning the VMA for reuse until the
813 * BO is idle. Just move it to the dead list for now.
814 */
815 list_addtail(&bo->head, &bufmgr->zombie_list);
816 }
817 }
818
819 /** Frees all cached buffers significantly older than @time. */
820 static void
821 cleanup_bo_cache(struct iris_bufmgr *bufmgr, time_t time)
822 {
823 int i;
824
825 if (bufmgr->time == time)
826 return;
827
828 for (i = 0; i < bufmgr->num_buckets; i++) {
829 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
830
831 list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
832 if (time - bo->free_time <= 1)
833 break;
834
835 list_del(&bo->head);
836
837 bo_free(bo);
838 }
839 }
840
841 list_for_each_entry_safe(struct iris_bo, bo, &bufmgr->zombie_list, head) {
842 /* Stop once we reach a busy BO - all others past this point were
843 * freed more recently so are likely also busy.
844 */
845 if (!bo->idle && iris_bo_busy(bo))
846 break;
847
848 list_del(&bo->head);
849 bo_close(bo);
850 }
851
852 bufmgr->time = time;
853 }
854
855 static void
856 bo_unreference_final(struct iris_bo *bo, time_t time)
857 {
858 struct iris_bufmgr *bufmgr = bo->bufmgr;
859 struct bo_cache_bucket *bucket;
860
861 DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
862
863 bucket = NULL;
864 if (bo->reusable)
865 bucket = bucket_for_size(bufmgr, bo->size);
866 /* Put the buffer into our internal cache for reuse if we can. */
867 if (bucket && iris_bo_madvise(bo, I915_MADV_DONTNEED)) {
868 bo->free_time = time;
869 bo->name = NULL;
870
871 list_addtail(&bo->head, &bucket->head);
872 } else {
873 bo_free(bo);
874 }
875 }
876
877 void
878 iris_bo_unreference(struct iris_bo *bo)
879 {
880 if (bo == NULL)
881 return;
882
883 assert(p_atomic_read(&bo->refcount) > 0);
884
885 if (atomic_add_unless(&bo->refcount, -1, 1)) {
886 struct iris_bufmgr *bufmgr = bo->bufmgr;
887 struct timespec time;
888
889 clock_gettime(CLOCK_MONOTONIC, &time);
890
891 mtx_lock(&bufmgr->lock);
892
893 if (p_atomic_dec_zero(&bo->refcount)) {
894 bo_unreference_final(bo, time.tv_sec);
895 cleanup_bo_cache(bufmgr, time.tv_sec);
896 }
897
898 mtx_unlock(&bufmgr->lock);
899 }
900 }
901
902 static void
903 bo_wait_with_stall_warning(struct pipe_debug_callback *dbg,
904 struct iris_bo *bo,
905 const char *action)
906 {
907 bool busy = dbg && !bo->idle;
908 double elapsed = unlikely(busy) ? -get_time() : 0.0;
909
910 iris_bo_wait_rendering(bo);
911
912 if (unlikely(busy)) {
913 elapsed += get_time();
914 if (elapsed > 1e-5) /* 0.01ms */ {
915 perf_debug(dbg, "%s a busy \"%s\" BO stalled and took %.03f ms.\n",
916 action, bo->name, elapsed * 1000);
917 }
918 }
919 }
920
921 static void
922 print_flags(unsigned flags)
923 {
924 if (flags & MAP_READ)
925 DBG("READ ");
926 if (flags & MAP_WRITE)
927 DBG("WRITE ");
928 if (flags & MAP_ASYNC)
929 DBG("ASYNC ");
930 if (flags & MAP_PERSISTENT)
931 DBG("PERSISTENT ");
932 if (flags & MAP_COHERENT)
933 DBG("COHERENT ");
934 if (flags & MAP_RAW)
935 DBG("RAW ");
936 DBG("\n");
937 }
938
939 static void *
940 iris_bo_gem_mmap_legacy(struct pipe_debug_callback *dbg,
941 struct iris_bo *bo, bool wc)
942 {
943 struct iris_bufmgr *bufmgr = bo->bufmgr;
944
945 struct drm_i915_gem_mmap mmap_arg = {
946 .handle = bo->gem_handle,
947 .size = bo->size,
948 .flags = wc ? I915_MMAP_WC : 0,
949 };
950
951 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
952 if (ret != 0) {
953 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
954 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
955 return NULL;
956 }
957 void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
958
959 return map;
960 }
961
962 static void *
963 iris_bo_gem_mmap_offset(struct pipe_debug_callback *dbg, struct iris_bo *bo,
964 bool wc)
965 {
966 struct iris_bufmgr *bufmgr = bo->bufmgr;
967
968 struct drm_i915_gem_mmap_offset mmap_arg = {
969 .handle = bo->gem_handle,
970 .flags = wc ? I915_MMAP_OFFSET_WC : I915_MMAP_OFFSET_WB,
971 };
972
973 /* Get the fake offset back */
974 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_OFFSET, &mmap_arg);
975 if (ret != 0) {
976 DBG("%s:%d: Error preparing buffer %d (%s): %s .\n",
977 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
978 return NULL;
979 }
980
981 /* And map it */
982 void *map = mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED,
983 bufmgr->fd, mmap_arg.offset);
984 if (map == MAP_FAILED) {
985 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
986 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
987 return NULL;
988 }
989
990 return map;
991 }
992
993 static void *
994 iris_bo_gem_mmap(struct pipe_debug_callback *dbg, struct iris_bo *bo, bool wc)
995 {
996 struct iris_bufmgr *bufmgr = bo->bufmgr;
997
998 if (bufmgr->has_mmap_offset)
999 return iris_bo_gem_mmap_offset(dbg, bo, wc);
1000 else
1001 return iris_bo_gem_mmap_legacy(dbg, bo, wc);
1002 }
1003
1004 static void *
1005 iris_bo_map_cpu(struct pipe_debug_callback *dbg,
1006 struct iris_bo *bo, unsigned flags)
1007 {
1008 /* We disallow CPU maps for writing to non-coherent buffers, as the
1009 * CPU map can become invalidated when a batch is flushed out, which
1010 * can happen at unpredictable times. You should use WC maps instead.
1011 */
1012 assert(bo->cache_coherent || !(flags & MAP_WRITE));
1013
1014 if (!bo->map_cpu) {
1015 DBG("iris_bo_map_cpu: %d (%s)\n", bo->gem_handle, bo->name);
1016 void *map = iris_bo_gem_mmap(dbg, bo, false);
1017 if (!map) {
1018 return NULL;
1019 }
1020
1021 VG_DEFINED(map, bo->size);
1022
1023 if (p_atomic_cmpxchg(&bo->map_cpu, NULL, map)) {
1024 VG_NOACCESS(map, bo->size);
1025 os_munmap(map, bo->size);
1026 }
1027 }
1028 assert(bo->map_cpu);
1029
1030 DBG("iris_bo_map_cpu: %d (%s) -> %p, ", bo->gem_handle, bo->name,
1031 bo->map_cpu);
1032 print_flags(flags);
1033
1034 if (!(flags & MAP_ASYNC)) {
1035 bo_wait_with_stall_warning(dbg, bo, "CPU mapping");
1036 }
1037
1038 if (!bo->cache_coherent && !bo->bufmgr->has_llc) {
1039 /* If we're reusing an existing CPU mapping, the CPU caches may
1040 * contain stale data from the last time we read from that mapping.
1041 * (With the BO cache, it might even be data from a previous buffer!)
1042 * Even if it's a brand new mapping, the kernel may have zeroed the
1043 * buffer via CPU writes.
1044 *
1045 * We need to invalidate those cachelines so that we see the latest
1046 * contents, and so long as we only read from the CPU mmap we do not
1047 * need to write those cachelines back afterwards.
1048 *
1049 * On LLC, the emprical evidence suggests that writes from the GPU
1050 * that bypass the LLC (i.e. for scanout) do *invalidate* the CPU
1051 * cachelines. (Other reads, such as the display engine, bypass the
1052 * LLC entirely requiring us to keep dirty pixels for the scanout
1053 * out of any cache.)
1054 */
1055 gen_invalidate_range(bo->map_cpu, bo->size);
1056 }
1057
1058 return bo->map_cpu;
1059 }
1060
1061 static void *
1062 iris_bo_map_wc(struct pipe_debug_callback *dbg,
1063 struct iris_bo *bo, unsigned flags)
1064 {
1065 if (!bo->map_wc) {
1066 DBG("iris_bo_map_wc: %d (%s)\n", bo->gem_handle, bo->name);
1067 void *map = iris_bo_gem_mmap(dbg, bo, true);
1068 if (!map) {
1069 return NULL;
1070 }
1071
1072 VG_DEFINED(map, bo->size);
1073
1074 if (p_atomic_cmpxchg(&bo->map_wc, NULL, map)) {
1075 VG_NOACCESS(map, bo->size);
1076 os_munmap(map, bo->size);
1077 }
1078 }
1079 assert(bo->map_wc);
1080
1081 DBG("iris_bo_map_wc: %d (%s) -> %p\n", bo->gem_handle, bo->name, bo->map_wc);
1082 print_flags(flags);
1083
1084 if (!(flags & MAP_ASYNC)) {
1085 bo_wait_with_stall_warning(dbg, bo, "WC mapping");
1086 }
1087
1088 return bo->map_wc;
1089 }
1090
1091 /**
1092 * Perform an uncached mapping via the GTT.
1093 *
1094 * Write access through the GTT is not quite fully coherent. On low power
1095 * systems especially, like modern Atoms, we can observe reads from RAM before
1096 * the write via GTT has landed. A write memory barrier that flushes the Write
1097 * Combining Buffer (i.e. sfence/mfence) is not sufficient to order the later
1098 * read after the write as the GTT write suffers a small delay through the GTT
1099 * indirection. The kernel uses an uncached mmio read to ensure the GTT write
1100 * is ordered with reads (either by the GPU, WB or WC) and unconditionally
1101 * flushes prior to execbuf submission. However, if we are not informing the
1102 * kernel about our GTT writes, it will not flush before earlier access, such
1103 * as when using the cmdparser. Similarly, we need to be careful if we should
1104 * ever issue a CPU read immediately following a GTT write.
1105 *
1106 * Telling the kernel about write access also has one more important
1107 * side-effect. Upon receiving notification about the write, it cancels any
1108 * scanout buffering for FBC/PSR and friends. Later FBC/PSR is then flushed by
1109 * either SW_FINISH or DIRTYFB. The presumption is that we never write to the
1110 * actual scanout via a mmaping, only to a backbuffer and so all the FBC/PSR
1111 * tracking is handled on the buffer exchange instead.
1112 */
1113 static void *
1114 iris_bo_map_gtt(struct pipe_debug_callback *dbg,
1115 struct iris_bo *bo, unsigned flags)
1116 {
1117 struct iris_bufmgr *bufmgr = bo->bufmgr;
1118
1119 /* If we don't support get/set_tiling, there's no support for GTT mapping
1120 * either (it won't do any de-tiling for us).
1121 */
1122 assert(bufmgr->has_tiling_uapi);
1123
1124 /* Get a mapping of the buffer if we haven't before. */
1125 if (bo->map_gtt == NULL) {
1126 DBG("bo_map_gtt: mmap %d (%s)\n", bo->gem_handle, bo->name);
1127
1128 struct drm_i915_gem_mmap_gtt mmap_arg = { .handle = bo->gem_handle };
1129
1130 /* Get the fake offset back... */
1131 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg);
1132 if (ret != 0) {
1133 DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
1134 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
1135 return NULL;
1136 }
1137
1138 /* and mmap it. */
1139 void *map = os_mmap(0, bo->size, PROT_READ | PROT_WRITE,
1140 MAP_SHARED, bufmgr->fd, mmap_arg.offset);
1141 if (map == MAP_FAILED) {
1142 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
1143 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
1144 return NULL;
1145 }
1146
1147 /* We don't need to use VALGRIND_MALLOCLIKE_BLOCK because Valgrind will
1148 * already intercept this mmap call. However, for consistency between
1149 * all the mmap paths, we mark the pointer as defined now and mark it
1150 * as inaccessible afterwards.
1151 */
1152 VG_DEFINED(map, bo->size);
1153
1154 if (p_atomic_cmpxchg(&bo->map_gtt, NULL, map)) {
1155 VG_NOACCESS(map, bo->size);
1156 os_munmap(map, bo->size);
1157 }
1158 }
1159 assert(bo->map_gtt);
1160
1161 DBG("bo_map_gtt: %d (%s) -> %p, ", bo->gem_handle, bo->name, bo->map_gtt);
1162 print_flags(flags);
1163
1164 if (!(flags & MAP_ASYNC)) {
1165 bo_wait_with_stall_warning(dbg, bo, "GTT mapping");
1166 }
1167
1168 return bo->map_gtt;
1169 }
1170
1171 static bool
1172 can_map_cpu(struct iris_bo *bo, unsigned flags)
1173 {
1174 if (bo->cache_coherent)
1175 return true;
1176
1177 /* Even if the buffer itself is not cache-coherent (such as a scanout), on
1178 * an LLC platform reads always are coherent (as they are performed via the
1179 * central system agent). It is just the writes that we need to take special
1180 * care to ensure that land in main memory and not stick in the CPU cache.
1181 */
1182 if (!(flags & MAP_WRITE) && bo->bufmgr->has_llc)
1183 return true;
1184
1185 /* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
1186 * across batch flushes where the kernel will change cache domains of the
1187 * bo, invalidating continued access to the CPU mmap on non-LLC device.
1188 *
1189 * Similarly, ASYNC typically means that the buffer will be accessed via
1190 * both the CPU and the GPU simultaneously. Batches may be executed that
1191 * use the BO even while it is mapped. While OpenGL technically disallows
1192 * most drawing while non-persistent mappings are active, we may still use
1193 * the GPU for blits or other operations, causing batches to happen at
1194 * inconvenient times.
1195 *
1196 * If RAW is set, we expect the caller to be able to handle a WC buffer
1197 * more efficiently than the involuntary clflushes.
1198 */
1199 if (flags & (MAP_PERSISTENT | MAP_COHERENT | MAP_ASYNC | MAP_RAW))
1200 return false;
1201
1202 return !(flags & MAP_WRITE);
1203 }
1204
1205 void *
1206 iris_bo_map(struct pipe_debug_callback *dbg,
1207 struct iris_bo *bo, unsigned flags)
1208 {
1209 if (bo->tiling_mode != I915_TILING_NONE && !(flags & MAP_RAW))
1210 return iris_bo_map_gtt(dbg, bo, flags);
1211
1212 void *map;
1213
1214 if (can_map_cpu(bo, flags))
1215 map = iris_bo_map_cpu(dbg, bo, flags);
1216 else
1217 map = iris_bo_map_wc(dbg, bo, flags);
1218
1219 /* Allow the attempt to fail by falling back to the GTT where necessary.
1220 *
1221 * Not every buffer can be mmaped directly using the CPU (or WC), for
1222 * example buffers that wrap stolen memory or are imported from other
1223 * devices. For those, we have little choice but to use a GTT mmapping.
1224 * However, if we use a slow GTT mmapping for reads where we expected fast
1225 * access, that order of magnitude difference in throughput will be clearly
1226 * expressed by angry users.
1227 *
1228 * We skip MAP_RAW because we want to avoid map_gtt's fence detiling.
1229 */
1230 if (!map && !(flags & MAP_RAW)) {
1231 perf_debug(dbg, "Fallback GTT mapping for %s with access flags %x\n",
1232 bo->name, flags);
1233 map = iris_bo_map_gtt(dbg, bo, flags);
1234 }
1235
1236 return map;
1237 }
1238
1239 /** Waits for all GPU rendering with the object to have completed. */
1240 void
1241 iris_bo_wait_rendering(struct iris_bo *bo)
1242 {
1243 /* We require a kernel recent enough for WAIT_IOCTL support.
1244 * See intel_init_bufmgr()
1245 */
1246 iris_bo_wait(bo, -1);
1247 }
1248
1249 /**
1250 * Waits on a BO for the given amount of time.
1251 *
1252 * @bo: buffer object to wait for
1253 * @timeout_ns: amount of time to wait in nanoseconds.
1254 * If value is less than 0, an infinite wait will occur.
1255 *
1256 * Returns 0 if the wait was successful ie. the last batch referencing the
1257 * object has completed within the allotted time. Otherwise some negative return
1258 * value describes the error. Of particular interest is -ETIME when the wait has
1259 * failed to yield the desired result.
1260 *
1261 * Similar to iris_bo_wait_rendering except a timeout parameter allows
1262 * the operation to give up after a certain amount of time. Another subtle
1263 * difference is the internal locking semantics are different (this variant does
1264 * not hold the lock for the duration of the wait). This makes the wait subject
1265 * to a larger userspace race window.
1266 *
1267 * The implementation shall wait until the object is no longer actively
1268 * referenced within a batch buffer at the time of the call. The wait will
1269 * not guarantee that the buffer is re-issued via another thread, or an flinked
1270 * handle. Userspace must make sure this race does not occur if such precision
1271 * is important.
1272 *
1273 * Note that some kernels have broken the inifite wait for negative values
1274 * promise, upgrade to latest stable kernels if this is the case.
1275 */
1276 int
1277 iris_bo_wait(struct iris_bo *bo, int64_t timeout_ns)
1278 {
1279 struct iris_bufmgr *bufmgr = bo->bufmgr;
1280
1281 /* If we know it's idle, don't bother with the kernel round trip */
1282 if (bo->idle && !bo->external)
1283 return 0;
1284
1285 struct drm_i915_gem_wait wait = {
1286 .bo_handle = bo->gem_handle,
1287 .timeout_ns = timeout_ns,
1288 };
1289 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_WAIT, &wait);
1290 if (ret != 0)
1291 return -errno;
1292
1293 bo->idle = true;
1294
1295 return ret;
1296 }
1297
1298 static void
1299 iris_bufmgr_destroy(struct iris_bufmgr *bufmgr)
1300 {
1301 /* Free aux-map buffers */
1302 gen_aux_map_finish(bufmgr->aux_map_ctx);
1303
1304 /* bufmgr will no longer try to free VMA entries in the aux-map */
1305 bufmgr->aux_map_ctx = NULL;
1306
1307 mtx_destroy(&bufmgr->lock);
1308
1309 /* Free any cached buffer objects we were going to reuse */
1310 for (int i = 0; i < bufmgr->num_buckets; i++) {
1311 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1312
1313 list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
1314 list_del(&bo->head);
1315
1316 bo_free(bo);
1317 }
1318 }
1319
1320 /* Close any buffer objects on the dead list. */
1321 list_for_each_entry_safe(struct iris_bo, bo, &bufmgr->zombie_list, head) {
1322 list_del(&bo->head);
1323 bo_close(bo);
1324 }
1325
1326 _mesa_hash_table_destroy(bufmgr->name_table, NULL);
1327 _mesa_hash_table_destroy(bufmgr->handle_table, NULL);
1328
1329 for (int z = 0; z < IRIS_MEMZONE_COUNT; z++) {
1330 if (z != IRIS_MEMZONE_BINDER)
1331 util_vma_heap_finish(&bufmgr->vma_allocator[z]);
1332 }
1333
1334 close(bufmgr->fd);
1335
1336 free(bufmgr);
1337 }
1338
1339 static int
1340 bo_set_tiling_internal(struct iris_bo *bo, uint32_t tiling_mode,
1341 uint32_t stride)
1342 {
1343 struct iris_bufmgr *bufmgr = bo->bufmgr;
1344 struct drm_i915_gem_set_tiling set_tiling;
1345 int ret;
1346
1347 if (bo->global_name == 0 &&
1348 tiling_mode == bo->tiling_mode && stride == bo->stride)
1349 return 0;
1350
1351 /* If we can't do map_gtt, the set/get_tiling API isn't useful. And it's
1352 * actually not supported by the kernel in those cases.
1353 */
1354 if (!bufmgr->has_tiling_uapi) {
1355 bo->tiling_mode = tiling_mode;
1356 bo->stride = stride;
1357 return 0;
1358 }
1359
1360 memset(&set_tiling, 0, sizeof(set_tiling));
1361 do {
1362 /* set_tiling is slightly broken and overwrites the
1363 * input on the error path, so we have to open code
1364 * drm_ioctl.
1365 */
1366 set_tiling.handle = bo->gem_handle;
1367 set_tiling.tiling_mode = tiling_mode;
1368 set_tiling.stride = stride;
1369
1370 ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
1371 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
1372 if (ret == -1)
1373 return -errno;
1374
1375 bo->tiling_mode = set_tiling.tiling_mode;
1376 bo->stride = set_tiling.stride;
1377 return 0;
1378 }
1379
1380 struct iris_bo *
1381 iris_bo_import_dmabuf(struct iris_bufmgr *bufmgr, int prime_fd,
1382 int tiling, uint32_t stride)
1383 {
1384 uint32_t handle;
1385 struct iris_bo *bo;
1386
1387 mtx_lock(&bufmgr->lock);
1388 int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1389 if (ret) {
1390 DBG("import_dmabuf: failed to obtain handle from fd: %s\n",
1391 strerror(errno));
1392 mtx_unlock(&bufmgr->lock);
1393 return NULL;
1394 }
1395
1396 /*
1397 * See if the kernel has already returned this buffer to us. Just as
1398 * for named buffers, we must not create two bo's pointing at the same
1399 * kernel object
1400 */
1401 bo = find_and_ref_external_bo(bufmgr->handle_table, handle);
1402 if (bo)
1403 goto out;
1404
1405 bo = bo_calloc();
1406 if (!bo)
1407 goto out;
1408
1409 p_atomic_set(&bo->refcount, 1);
1410
1411 /* Determine size of bo. The fd-to-handle ioctl really should
1412 * return the size, but it doesn't. If we have kernel 3.12 or
1413 * later, we can lseek on the prime fd to get the size. Older
1414 * kernels will just fail, in which case we fall back to the
1415 * provided (estimated or guess size). */
1416 ret = lseek(prime_fd, 0, SEEK_END);
1417 if (ret != -1)
1418 bo->size = ret;
1419
1420 bo->bufmgr = bufmgr;
1421 bo->name = "prime";
1422 bo->reusable = false;
1423 bo->external = true;
1424 bo->kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
1425
1426 /* From the Bspec, Memory Compression - Gen12:
1427 *
1428 * The base address for the surface has to be 64K page aligned and the
1429 * surface is expected to be padded in the virtual domain to be 4 4K
1430 * pages.
1431 *
1432 * The dmabuf may contain a compressed surface. Align the BO to 64KB just
1433 * in case. We always align to 64KB even on platforms where we don't need
1434 * to, because it's a fairly reasonable thing to do anyway.
1435 */
1436 bo->gtt_offset =
1437 vma_alloc(bufmgr, IRIS_MEMZONE_OTHER, bo->size, 64 * 1024);
1438
1439 bo->gem_handle = handle;
1440 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1441
1442 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
1443 if (!bufmgr->has_tiling_uapi)
1444 get_tiling.tiling_mode = I915_TILING_NONE;
1445 else if (gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling))
1446 goto err;
1447
1448 if (tiling == -1) {
1449 bo->tiling_mode = get_tiling.tiling_mode;
1450 /* XXX stride is unknown */
1451 } else {
1452 /* Modifiers path */
1453 if (get_tiling.tiling_mode == tiling || !bufmgr->has_tiling_uapi) {
1454 bo->tiling_mode = tiling;
1455 bo->stride = stride;
1456 } else if (bo_set_tiling_internal(bo, tiling, stride)) {
1457 goto err;
1458 }
1459 }
1460
1461 out:
1462 mtx_unlock(&bufmgr->lock);
1463 return bo;
1464
1465 err:
1466 bo_free(bo);
1467 mtx_unlock(&bufmgr->lock);
1468 return NULL;
1469 }
1470
1471 static void
1472 iris_bo_make_external_locked(struct iris_bo *bo)
1473 {
1474 if (!bo->external) {
1475 _mesa_hash_table_insert(bo->bufmgr->handle_table, &bo->gem_handle, bo);
1476 /* If a BO is going to be used externally, it could be sent to the
1477 * display HW. So make sure our CPU mappings don't assume cache
1478 * coherency since display is outside that cache.
1479 */
1480 bo->cache_coherent = false;
1481 bo->external = true;
1482 bo->reusable = false;
1483 }
1484 }
1485
1486 void
1487 iris_bo_make_external(struct iris_bo *bo)
1488 {
1489 struct iris_bufmgr *bufmgr = bo->bufmgr;
1490
1491 if (bo->external) {
1492 assert(!bo->reusable);
1493 return;
1494 }
1495
1496 mtx_lock(&bufmgr->lock);
1497 iris_bo_make_external_locked(bo);
1498 mtx_unlock(&bufmgr->lock);
1499 }
1500
1501 int
1502 iris_bo_export_dmabuf(struct iris_bo *bo, int *prime_fd)
1503 {
1504 struct iris_bufmgr *bufmgr = bo->bufmgr;
1505
1506 iris_bo_make_external(bo);
1507
1508 if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1509 DRM_CLOEXEC, prime_fd) != 0)
1510 return -errno;
1511
1512 return 0;
1513 }
1514
1515 uint32_t
1516 iris_bo_export_gem_handle(struct iris_bo *bo)
1517 {
1518 iris_bo_make_external(bo);
1519
1520 return bo->gem_handle;
1521 }
1522
1523 int
1524 iris_bo_flink(struct iris_bo *bo, uint32_t *name)
1525 {
1526 struct iris_bufmgr *bufmgr = bo->bufmgr;
1527
1528 if (!bo->global_name) {
1529 struct drm_gem_flink flink = { .handle = bo->gem_handle };
1530
1531 if (gen_ioctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1532 return -errno;
1533
1534 mtx_lock(&bufmgr->lock);
1535 if (!bo->global_name) {
1536 iris_bo_make_external_locked(bo);
1537 bo->global_name = flink.name;
1538 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
1539 }
1540 mtx_unlock(&bufmgr->lock);
1541 }
1542
1543 *name = bo->global_name;
1544 return 0;
1545 }
1546
1547 int
1548 iris_bo_export_gem_handle_for_device(struct iris_bo *bo, int drm_fd,
1549 uint32_t *out_handle)
1550 {
1551 /* Only add the new GEM handle to the list of export if it belongs to a
1552 * different GEM device. Otherwise we might close the same buffer multiple
1553 * times.
1554 */
1555 struct iris_bufmgr *bufmgr = bo->bufmgr;
1556 int ret = os_same_file_description(drm_fd, bufmgr->fd);
1557 WARN_ONCE(ret < 0,
1558 "Kernel has no file descriptor comparison support: %s\n",
1559 strerror(errno));
1560 if (ret == 0) {
1561 *out_handle = iris_bo_export_gem_handle(bo);
1562 return 0;
1563 }
1564
1565 struct bo_export *export = calloc(1, sizeof(*export));
1566 if (!export)
1567 return -ENOMEM;
1568
1569 export->drm_fd = drm_fd;
1570
1571 int dmabuf_fd = -1;
1572 int err = iris_bo_export_dmabuf(bo, &dmabuf_fd);
1573 if (err) {
1574 free(export);
1575 return err;
1576 }
1577
1578 mtx_lock(&bufmgr->lock);
1579 err = drmPrimeFDToHandle(drm_fd, dmabuf_fd, &export->gem_handle);
1580 close(dmabuf_fd);
1581 if (err) {
1582 mtx_unlock(&bufmgr->lock);
1583 free(export);
1584 return err;
1585 }
1586
1587 bool found = false;
1588 list_for_each_entry(struct bo_export, iter, &bo->exports, link) {
1589 if (iter->drm_fd != drm_fd)
1590 continue;
1591 /* Here we assume that for a given DRM fd, we'll always get back the
1592 * same GEM handle for a given buffer.
1593 */
1594 assert(iter->gem_handle == export->gem_handle);
1595 free(export);
1596 export = iter;
1597 found = true;
1598 break;
1599 }
1600 if (!found)
1601 list_addtail(&export->link, &bo->exports);
1602
1603 mtx_unlock(&bufmgr->lock);
1604
1605 *out_handle = export->gem_handle;
1606
1607 return 0;
1608 }
1609
1610 static void
1611 add_bucket(struct iris_bufmgr *bufmgr, int size)
1612 {
1613 unsigned int i = bufmgr->num_buckets;
1614
1615 assert(i < ARRAY_SIZE(bufmgr->cache_bucket));
1616
1617 list_inithead(&bufmgr->cache_bucket[i].head);
1618 bufmgr->cache_bucket[i].size = size;
1619 bufmgr->num_buckets++;
1620
1621 assert(bucket_for_size(bufmgr, size) == &bufmgr->cache_bucket[i]);
1622 assert(bucket_for_size(bufmgr, size - 2048) == &bufmgr->cache_bucket[i]);
1623 assert(bucket_for_size(bufmgr, size + 1) != &bufmgr->cache_bucket[i]);
1624 }
1625
1626 static void
1627 init_cache_buckets(struct iris_bufmgr *bufmgr)
1628 {
1629 uint64_t size, cache_max_size = 64 * 1024 * 1024;
1630
1631 /* OK, so power of two buckets was too wasteful of memory.
1632 * Give 3 other sizes between each power of two, to hopefully
1633 * cover things accurately enough. (The alternative is
1634 * probably to just go for exact matching of sizes, and assume
1635 * that for things like composited window resize the tiled
1636 * width/height alignment and rounding of sizes to pages will
1637 * get us useful cache hit rates anyway)
1638 */
1639 add_bucket(bufmgr, PAGE_SIZE);
1640 add_bucket(bufmgr, PAGE_SIZE * 2);
1641 add_bucket(bufmgr, PAGE_SIZE * 3);
1642
1643 /* Initialize the linked lists for BO reuse cache. */
1644 for (size = 4 * PAGE_SIZE; size <= cache_max_size; size *= 2) {
1645 add_bucket(bufmgr, size);
1646
1647 add_bucket(bufmgr, size + size * 1 / 4);
1648 add_bucket(bufmgr, size + size * 2 / 4);
1649 add_bucket(bufmgr, size + size * 3 / 4);
1650 }
1651 }
1652
1653 uint32_t
1654 iris_create_hw_context(struct iris_bufmgr *bufmgr)
1655 {
1656 struct drm_i915_gem_context_create create = { };
1657 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create);
1658 if (ret != 0) {
1659 DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno));
1660 return 0;
1661 }
1662
1663 /* Upon declaring a GPU hang, the kernel will zap the guilty context
1664 * back to the default logical HW state and attempt to continue on to
1665 * our next submitted batchbuffer. However, our render batches assume
1666 * the previous GPU state is preserved, and only emit commands needed
1667 * to incrementally change that state. In particular, we inherit the
1668 * STATE_BASE_ADDRESS and PIPELINE_SELECT settings, which are critical.
1669 * With default base addresses, our next batches will almost certainly
1670 * cause more GPU hangs, leading to repeated hangs until we're banned
1671 * or the machine is dead.
1672 *
1673 * Here we tell the kernel not to attempt to recover our context but
1674 * immediately (on the next batchbuffer submission) report that the
1675 * context is lost, and we will do the recovery ourselves. Ideally,
1676 * we'll have two lost batches instead of a continual stream of hangs.
1677 */
1678 struct drm_i915_gem_context_param p = {
1679 .ctx_id = create.ctx_id,
1680 .param = I915_CONTEXT_PARAM_RECOVERABLE,
1681 .value = false,
1682 };
1683 drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM, &p);
1684
1685 return create.ctx_id;
1686 }
1687
1688 static int
1689 iris_hw_context_get_priority(struct iris_bufmgr *bufmgr, uint32_t ctx_id)
1690 {
1691 struct drm_i915_gem_context_param p = {
1692 .ctx_id = ctx_id,
1693 .param = I915_CONTEXT_PARAM_PRIORITY,
1694 };
1695 drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM, &p);
1696 return p.value; /* on error, return 0 i.e. default priority */
1697 }
1698
1699 int
1700 iris_hw_context_set_priority(struct iris_bufmgr *bufmgr,
1701 uint32_t ctx_id,
1702 int priority)
1703 {
1704 struct drm_i915_gem_context_param p = {
1705 .ctx_id = ctx_id,
1706 .param = I915_CONTEXT_PARAM_PRIORITY,
1707 .value = priority,
1708 };
1709 int err;
1710
1711 err = 0;
1712 if (gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM, &p))
1713 err = -errno;
1714
1715 return err;
1716 }
1717
1718 uint32_t
1719 iris_clone_hw_context(struct iris_bufmgr *bufmgr, uint32_t ctx_id)
1720 {
1721 uint32_t new_ctx = iris_create_hw_context(bufmgr);
1722
1723 if (new_ctx) {
1724 int priority = iris_hw_context_get_priority(bufmgr, ctx_id);
1725 iris_hw_context_set_priority(bufmgr, new_ctx, priority);
1726 }
1727
1728 return new_ctx;
1729 }
1730
1731 void
1732 iris_destroy_hw_context(struct iris_bufmgr *bufmgr, uint32_t ctx_id)
1733 {
1734 struct drm_i915_gem_context_destroy d = { .ctx_id = ctx_id };
1735
1736 if (ctx_id != 0 &&
1737 gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY, &d) != 0) {
1738 fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1739 strerror(errno));
1740 }
1741 }
1742
1743 int
1744 iris_reg_read(struct iris_bufmgr *bufmgr, uint32_t offset, uint64_t *result)
1745 {
1746 struct drm_i915_reg_read reg_read = { .offset = offset };
1747 int ret = gen_ioctl(bufmgr->fd, DRM_IOCTL_I915_REG_READ, &reg_read);
1748
1749 *result = reg_read.val;
1750 return ret;
1751 }
1752
1753 static uint64_t
1754 iris_gtt_size(int fd)
1755 {
1756 /* We use the default (already allocated) context to determine
1757 * the default configuration of the virtual address space.
1758 */
1759 struct drm_i915_gem_context_param p = {
1760 .param = I915_CONTEXT_PARAM_GTT_SIZE,
1761 };
1762 if (!gen_ioctl(fd, DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM, &p))
1763 return p.value;
1764
1765 return 0;
1766 }
1767
1768 static struct gen_buffer *
1769 gen_aux_map_buffer_alloc(void *driver_ctx, uint32_t size)
1770 {
1771 struct gen_buffer *buf = malloc(sizeof(struct gen_buffer));
1772 if (!buf)
1773 return NULL;
1774
1775 struct iris_bufmgr *bufmgr = (struct iris_bufmgr *)driver_ctx;
1776
1777 struct iris_bo *bo =
1778 iris_bo_alloc_tiled(bufmgr, "aux-map", size, 64 * 1024,
1779 IRIS_MEMZONE_OTHER, I915_TILING_NONE, 0, 0);
1780
1781 buf->driver_bo = bo;
1782 buf->gpu = bo->gtt_offset;
1783 buf->gpu_end = buf->gpu + bo->size;
1784 buf->map = iris_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
1785 return buf;
1786 }
1787
1788 static void
1789 gen_aux_map_buffer_free(void *driver_ctx, struct gen_buffer *buffer)
1790 {
1791 iris_bo_unreference((struct iris_bo*)buffer->driver_bo);
1792 free(buffer);
1793 }
1794
1795 static struct gen_mapped_pinned_buffer_alloc aux_map_allocator = {
1796 .alloc = gen_aux_map_buffer_alloc,
1797 .free = gen_aux_map_buffer_free,
1798 };
1799
1800 static int
1801 gem_param(int fd, int name)
1802 {
1803 int v = -1; /* No param uses (yet) the sign bit, reserve it for errors */
1804
1805 struct drm_i915_getparam gp = { .param = name, .value = &v };
1806 if (gen_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp))
1807 return -1;
1808
1809 return v;
1810 }
1811
1812 /**
1813 * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1814 * and manage map buffer objections.
1815 *
1816 * \param fd File descriptor of the opened DRM device.
1817 */
1818 static struct iris_bufmgr *
1819 iris_bufmgr_create(struct gen_device_info *devinfo, int fd, bool bo_reuse)
1820 {
1821 uint64_t gtt_size = iris_gtt_size(fd);
1822 if (gtt_size <= IRIS_MEMZONE_OTHER_START)
1823 return NULL;
1824
1825 struct iris_bufmgr *bufmgr = calloc(1, sizeof(*bufmgr));
1826 if (bufmgr == NULL)
1827 return NULL;
1828
1829 /* Handles to buffer objects belong to the device fd and are not
1830 * reference counted by the kernel. If the same fd is used by
1831 * multiple parties (threads sharing the same screen bufmgr, or
1832 * even worse the same device fd passed to multiple libraries)
1833 * ownership of those handles is shared by those independent parties.
1834 *
1835 * Don't do this! Ensure that each library/bufmgr has its own device
1836 * fd so that its namespace does not clash with another.
1837 */
1838 bufmgr->fd = os_dupfd_cloexec(fd);
1839
1840 p_atomic_set(&bufmgr->refcount, 1);
1841
1842 if (mtx_init(&bufmgr->lock, mtx_plain) != 0) {
1843 close(bufmgr->fd);
1844 free(bufmgr);
1845 return NULL;
1846 }
1847
1848 list_inithead(&bufmgr->zombie_list);
1849
1850 bufmgr->has_llc = devinfo->has_llc;
1851 bufmgr->has_tiling_uapi = devinfo->has_tiling_uapi;
1852 bufmgr->bo_reuse = bo_reuse;
1853 bufmgr->has_mmap_offset = gem_param(fd, I915_PARAM_MMAP_GTT_VERSION) >= 4;
1854
1855 STATIC_ASSERT(IRIS_MEMZONE_SHADER_START == 0ull);
1856 const uint64_t _4GB = 1ull << 32;
1857 const uint64_t _2GB = 1ul << 31;
1858
1859 /* The STATE_BASE_ADDRESS size field can only hold 1 page shy of 4GB */
1860 const uint64_t _4GB_minus_1 = _4GB - PAGE_SIZE;
1861
1862 util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_SHADER],
1863 PAGE_SIZE, _4GB_minus_1 - PAGE_SIZE);
1864 util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_SURFACE],
1865 IRIS_MEMZONE_SURFACE_START,
1866 _4GB_minus_1 - IRIS_MAX_BINDERS * IRIS_BINDER_SIZE);
1867 /* TODO: Why does limiting to 2GB help some state items on gen12?
1868 * - CC Viewport Pointer
1869 * - Blend State Pointer
1870 * - Color Calc State Pointer
1871 */
1872 const uint64_t dynamic_pool_size =
1873 (devinfo->gen >= 12 ? _2GB : _4GB_minus_1) - IRIS_BORDER_COLOR_POOL_SIZE;
1874 util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_DYNAMIC],
1875 IRIS_MEMZONE_DYNAMIC_START + IRIS_BORDER_COLOR_POOL_SIZE,
1876 dynamic_pool_size);
1877
1878 /* Leave the last 4GB out of the high vma range, so that no state
1879 * base address + size can overflow 48 bits.
1880 */
1881 util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_OTHER],
1882 IRIS_MEMZONE_OTHER_START,
1883 (gtt_size - _4GB) - IRIS_MEMZONE_OTHER_START);
1884
1885 init_cache_buckets(bufmgr);
1886
1887 bufmgr->name_table =
1888 _mesa_hash_table_create(NULL, _mesa_hash_uint, _mesa_key_uint_equal);
1889 bufmgr->handle_table =
1890 _mesa_hash_table_create(NULL, _mesa_hash_uint, _mesa_key_uint_equal);
1891
1892 if (devinfo->has_aux_map) {
1893 bufmgr->aux_map_ctx = gen_aux_map_init(bufmgr, &aux_map_allocator,
1894 devinfo);
1895 assert(bufmgr->aux_map_ctx);
1896 }
1897
1898 return bufmgr;
1899 }
1900
1901 static struct iris_bufmgr *
1902 iris_bufmgr_ref(struct iris_bufmgr *bufmgr)
1903 {
1904 p_atomic_inc(&bufmgr->refcount);
1905 return bufmgr;
1906 }
1907
1908 void
1909 iris_bufmgr_unref(struct iris_bufmgr *bufmgr)
1910 {
1911 mtx_lock(&global_bufmgr_list_mutex);
1912 if (p_atomic_dec_zero(&bufmgr->refcount)) {
1913 list_del(&bufmgr->link);
1914 iris_bufmgr_destroy(bufmgr);
1915 }
1916 mtx_unlock(&global_bufmgr_list_mutex);
1917 }
1918
1919 /**
1920 * Gets an already existing GEM buffer manager or create a new one.
1921 *
1922 * \param fd File descriptor of the opened DRM device.
1923 */
1924 struct iris_bufmgr *
1925 iris_bufmgr_get_for_fd(struct gen_device_info *devinfo, int fd, bool bo_reuse)
1926 {
1927 struct stat st;
1928
1929 if (fstat(fd, &st))
1930 return NULL;
1931
1932 struct iris_bufmgr *bufmgr = NULL;
1933
1934 mtx_lock(&global_bufmgr_list_mutex);
1935 list_for_each_entry(struct iris_bufmgr, iter_bufmgr, &global_bufmgr_list, link) {
1936 struct stat iter_st;
1937 if (fstat(iter_bufmgr->fd, &iter_st))
1938 continue;
1939
1940 if (st.st_rdev == iter_st.st_rdev) {
1941 assert(iter_bufmgr->bo_reuse == bo_reuse);
1942 bufmgr = iris_bufmgr_ref(iter_bufmgr);
1943 goto unlock;
1944 }
1945 }
1946
1947 bufmgr = iris_bufmgr_create(devinfo, fd, bo_reuse);
1948 list_addtail(&bufmgr->link, &global_bufmgr_list);
1949
1950 unlock:
1951 mtx_unlock(&global_bufmgr_list_mutex);
1952
1953 return bufmgr;
1954 }
1955
1956 int
1957 iris_bufmgr_get_fd(struct iris_bufmgr *bufmgr)
1958 {
1959 return bufmgr->fd;
1960 }
1961
1962 void*
1963 iris_bufmgr_get_aux_map_context(struct iris_bufmgr *bufmgr)
1964 {
1965 return bufmgr->aux_map_ctx;
1966 }