iris: Allow shared scanout buffer to be placed in smem as well
[platform/upstream/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/intel_aux_map.h"
52 #include "common/intel_clflush.h"
53 #include "dev/intel_debug.h"
54 #include "common/intel_gem.h"
55 #include "dev/intel_device_info.h"
56 #include "isl/isl.h"
57 #include "util/os_mman.h"
58 #include "util/u_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 #include "iris_kmd_backend.h"
69 #include "i915/iris_bufmgr.h"
70 #include "xe/iris_bufmgr.h"
71
72 #include "drm-uapi/i915_drm.h"
73
74 #ifdef HAVE_VALGRIND
75 #include <valgrind.h>
76 #include <memcheck.h>
77 #define VG(x) x
78 #else
79 #define VG(x)
80 #endif
81
82 /* VALGRIND_FREELIKE_BLOCK unfortunately does not actually undo the earlier
83  * VALGRIND_MALLOCLIKE_BLOCK but instead leaves vg convinced the memory is
84  * leaked. All because it does not call VG(cli_free) from its
85  * VG_USERREQ__FREELIKE_BLOCK handler. Instead of treating the memory like
86  * and allocation, we mark it available for use upon mmapping and remove
87  * it upon unmapping.
88  */
89 #define VG_DEFINED(ptr, size) VG(VALGRIND_MAKE_MEM_DEFINED(ptr, size))
90 #define VG_NOACCESS(ptr, size) VG(VALGRIND_MAKE_MEM_NOACCESS(ptr, size))
91
92 /* On FreeBSD PAGE_SIZE is already defined in
93  * /usr/include/machine/param.h that is indirectly
94  * included here.
95  */
96 #ifndef PAGE_SIZE
97 #define PAGE_SIZE 4096
98 #endif
99
100 #define WARN_ONCE(cond, fmt...) do {                            \
101    if (unlikely(cond)) {                                        \
102       static bool _warned = false;                              \
103       if (!_warned) {                                           \
104          fprintf(stderr, "WARNING: ");                          \
105          fprintf(stderr, fmt);                                  \
106          _warned = true;                                        \
107       }                                                         \
108    }                                                            \
109 } while (0)
110
111 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
112
113 /**
114  * For debugging purposes, this returns a time in seconds.
115  */
116 static double
117 get_time(void)
118 {
119    struct timespec tp;
120
121    clock_gettime(CLOCK_MONOTONIC, &tp);
122
123    return tp.tv_sec + tp.tv_nsec / 1000000000.0;
124 }
125
126 static inline int
127 atomic_add_unless(int *v, int add, int unless)
128 {
129    int c, old;
130    c = p_atomic_read(v);
131    while (c != unless && (old = p_atomic_cmpxchg(v, c, c + add)) != c)
132       c = old;
133    return c == unless;
134 }
135
136 static const char *
137 memzone_name(enum iris_memory_zone memzone)
138 {
139    const char *names[] = {
140       [IRIS_MEMZONE_SHADER]   = "shader",
141       [IRIS_MEMZONE_BINDER]   = "binder",
142       [IRIS_MEMZONE_SCRATCH]  = "scratchsurf",
143       [IRIS_MEMZONE_SURFACE]  = "surface",
144       [IRIS_MEMZONE_DYNAMIC]  = "dynamic",
145       [IRIS_MEMZONE_OTHER]    = "other",
146       [IRIS_MEMZONE_BORDER_COLOR_POOL] = "bordercolor",
147    };
148    assert(memzone < ARRAY_SIZE(names));
149    return names[memzone];
150 }
151
152 struct bo_cache_bucket {
153    /** List of cached BOs. */
154    struct list_head head;
155
156    /** Size of this bucket, in bytes. */
157    uint64_t size;
158 };
159
160 struct bo_export {
161    /** File descriptor associated with a handle export. */
162    int drm_fd;
163
164    /** GEM handle in drm_fd */
165    uint32_t gem_handle;
166
167    struct list_head link;
168 };
169
170 struct iris_memregion {
171    struct intel_memory_class_instance *region;
172    uint64_t size;
173 };
174
175 #define NUM_SLAB_ALLOCATORS 3
176
177 struct iris_slab {
178    struct pb_slab base;
179
180    unsigned entry_size;
181
182    /** The BO representing the entire slab */
183    struct iris_bo *bo;
184
185    /** Array of iris_bo structs representing BOs allocated out of this slab */
186    struct iris_bo *entries;
187 };
188
189 #define BUCKET_ARRAY_SIZE (14 * 4)
190
191 struct iris_bufmgr {
192    /**
193     * List into the list of bufmgr.
194     */
195    struct list_head link;
196
197    uint32_t refcount;
198
199    int fd;
200
201    simple_mtx_t lock;
202    simple_mtx_t bo_deps_lock;
203
204    /** Array of lists of cached gem objects of power-of-two sizes */
205    struct bo_cache_bucket cache_bucket[BUCKET_ARRAY_SIZE];
206    int num_buckets;
207
208    /** Same as cache_bucket, but for local memory gem objects */
209    struct bo_cache_bucket local_cache_bucket[BUCKET_ARRAY_SIZE];
210    int num_local_buckets;
211
212    /** Same as cache_bucket, but for local-preferred memory gem objects */
213    struct bo_cache_bucket local_preferred_cache_bucket[BUCKET_ARRAY_SIZE];
214    int num_local_preferred_buckets;
215
216    time_t time;
217
218    struct hash_table *name_table;
219    struct hash_table *handle_table;
220
221    /**
222     * List of BOs which we've effectively freed, but are hanging on to
223     * until they're idle before closing and returning the VMA.
224     */
225    struct list_head zombie_list;
226
227    struct util_vma_heap vma_allocator[IRIS_MEMZONE_COUNT];
228
229    struct iris_memregion vram, sys;
230
231    /* Used only when use_global_vm is true. */
232    uint32_t global_vm_id;
233
234    int next_screen_id;
235
236    struct intel_device_info devinfo;
237    const struct iris_kmd_backend *kmd_backend;
238    bool bo_reuse:1;
239    bool use_global_vm:1;
240
241    struct intel_aux_map_context *aux_map_ctx;
242
243    struct pb_slabs bo_slabs[NUM_SLAB_ALLOCATORS];
244
245    struct iris_border_color_pool border_color_pool;
246 };
247
248 static simple_mtx_t global_bufmgr_list_mutex = SIMPLE_MTX_INITIALIZER;
249 static struct list_head global_bufmgr_list = {
250    .next = &global_bufmgr_list,
251    .prev = &global_bufmgr_list,
252 };
253
254 static void bo_free(struct iris_bo *bo);
255
256 static struct iris_bo *
257 find_and_ref_external_bo(struct hash_table *ht, unsigned int key)
258 {
259    struct hash_entry *entry = _mesa_hash_table_search(ht, &key);
260    struct iris_bo *bo = entry ? entry->data : NULL;
261
262    if (bo) {
263       assert(iris_bo_is_external(bo));
264       assert(iris_bo_is_real(bo));
265       assert(!bo->real.reusable);
266
267       /* Being non-reusable, the BO cannot be in the cache lists, but it
268        * may be in the zombie list if it had reached zero references, but
269        * we hadn't yet closed it...and then reimported the same BO.  If it
270        * is, then remove it since it's now been resurrected.
271        */
272       if (list_is_linked(&bo->head))
273          list_del(&bo->head);
274
275       iris_bo_reference(bo);
276    }
277
278    return bo;
279 }
280
281 static void
282 bucket_info_for_heap(struct iris_bufmgr *bufmgr, enum iris_heap heap,
283                      struct bo_cache_bucket **cache_bucket, int **num_buckets)
284 {
285    switch (heap) {
286    case IRIS_HEAP_SYSTEM_MEMORY:
287       *cache_bucket = bufmgr->cache_bucket;
288       *num_buckets = &bufmgr->num_buckets;
289       break;
290    case IRIS_HEAP_DEVICE_LOCAL:
291       *cache_bucket = bufmgr->local_cache_bucket;
292       *num_buckets = &bufmgr->num_local_buckets;
293       break;
294    case IRIS_HEAP_DEVICE_LOCAL_PREFERRED:
295       *cache_bucket = bufmgr->local_preferred_cache_bucket;
296       *num_buckets = &bufmgr->num_local_preferred_buckets;
297       break;
298    case IRIS_HEAP_MAX:
299    default:
300       *cache_bucket = NULL;
301       *num_buckets = NULL;
302       unreachable("invalid heap");
303    }
304
305    assert(**num_buckets < BUCKET_ARRAY_SIZE);
306 }
307 /**
308  * This function finds the correct bucket fit for the input size.
309  * The function works with O(1) complexity when the requested size
310  * was queried instead of iterating the size through all the buckets.
311  */
312 static struct bo_cache_bucket *
313 bucket_for_size(struct iris_bufmgr *bufmgr, uint64_t size,
314                 enum iris_heap heap, unsigned flags)
315 {
316
317    /* Protected bo needs special handling during allocation.
318     * Exported and scanout bos also need special handling during allocation
319     * in Xe KMD.
320     */
321    if ((flags & BO_ALLOC_PROTECTED) ||
322        ((flags & (BO_ALLOC_SHARED | BO_ALLOC_SCANOUT)) &&
323         bufmgr->devinfo.kmd_type == INTEL_KMD_TYPE_XE))
324       return NULL;
325
326    /* Calculating the pages and rounding up to the page size. */
327    const unsigned pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
328
329    /* Row  Bucket sizes    clz((x-1) | 3)   Row    Column
330     *        in pages                      stride   size
331     *   0:   1  2  3  4 -> 30 30 30 30        4       1
332     *   1:   5  6  7  8 -> 29 29 29 29        4       1
333     *   2:  10 12 14 16 -> 28 28 28 28        8       2
334     *   3:  20 24 28 32 -> 27 27 27 27       16       4
335     */
336    const unsigned row = 30 - __builtin_clz((pages - 1) | 3);
337    const unsigned row_max_pages = 4 << row;
338
339    /* The '& ~2' is the special case for row 1. In row 1, max pages /
340     * 2 is 2, but the previous row maximum is zero (because there is
341     * no previous row). All row maximum sizes are power of 2, so that
342     * is the only case where that bit will be set.
343     */
344    const unsigned prev_row_max_pages = (row_max_pages / 2) & ~2;
345    int col_size_log2 = row - 1;
346    col_size_log2 += (col_size_log2 < 0);
347
348    const unsigned col = (pages - prev_row_max_pages +
349                         ((1 << col_size_log2) - 1)) >> col_size_log2;
350
351    /* Calculating the index based on the row and column. */
352    const unsigned index = (row * 4) + (col - 1);
353
354    int *num_buckets;
355    struct bo_cache_bucket *buckets;
356    bucket_info_for_heap(bufmgr, heap, &buckets, &num_buckets);
357
358    return (index < *num_buckets) ? &buckets[index] : NULL;
359 }
360
361 enum iris_memory_zone
362 iris_memzone_for_address(uint64_t address)
363 {
364    STATIC_ASSERT(IRIS_MEMZONE_OTHER_START    > IRIS_MEMZONE_DYNAMIC_START);
365    STATIC_ASSERT(IRIS_MEMZONE_SURFACE_START  > IRIS_MEMZONE_SCRATCH_START);
366    STATIC_ASSERT(IRIS_MEMZONE_SCRATCH_START == IRIS_MEMZONE_BINDER_START);
367    STATIC_ASSERT(IRIS_MEMZONE_BINDER_START   > IRIS_MEMZONE_SHADER_START);
368    STATIC_ASSERT(IRIS_MEMZONE_DYNAMIC_START  > IRIS_MEMZONE_SURFACE_START);
369    STATIC_ASSERT(IRIS_BORDER_COLOR_POOL_ADDRESS == IRIS_MEMZONE_DYNAMIC_START);
370
371    if (address >= IRIS_MEMZONE_OTHER_START)
372       return IRIS_MEMZONE_OTHER;
373
374    if (address == IRIS_BORDER_COLOR_POOL_ADDRESS)
375       return IRIS_MEMZONE_BORDER_COLOR_POOL;
376
377    if (address > IRIS_MEMZONE_DYNAMIC_START)
378       return IRIS_MEMZONE_DYNAMIC;
379
380    if (address >= IRIS_MEMZONE_SURFACE_START)
381       return IRIS_MEMZONE_SURFACE;
382
383    if (address >= (IRIS_MEMZONE_BINDER_START + IRIS_SCRATCH_ZONE_SIZE))
384       return IRIS_MEMZONE_BINDER;
385
386    if (address >= IRIS_MEMZONE_SCRATCH_START)
387       return IRIS_MEMZONE_SCRATCH;
388
389    return IRIS_MEMZONE_SHADER;
390 }
391
392 /**
393  * Allocate a section of virtual memory for a buffer, assigning an address.
394  *
395  * This uses either the bucket allocator for the given size, or the large
396  * object allocator (util_vma).
397  */
398 static uint64_t
399 vma_alloc(struct iris_bufmgr *bufmgr,
400           enum iris_memory_zone memzone,
401           uint64_t size,
402           uint64_t alignment)
403 {
404    simple_mtx_assert_locked(&bufmgr->lock);
405
406    /* Force minimum alignment based on device requirements */
407    assert((alignment & (alignment - 1)) == 0);
408    alignment = MAX2(alignment, bufmgr->devinfo.mem_alignment);
409
410    if (memzone == IRIS_MEMZONE_BORDER_COLOR_POOL)
411       return IRIS_BORDER_COLOR_POOL_ADDRESS;
412
413    uint64_t addr =
414       util_vma_heap_alloc(&bufmgr->vma_allocator[memzone], size, alignment);
415
416    assert((addr >> 48ull) == 0);
417    assert((addr % alignment) == 0);
418
419    return intel_canonical_address(addr);
420 }
421
422 static void
423 vma_free(struct iris_bufmgr *bufmgr,
424          uint64_t address,
425          uint64_t size)
426 {
427    simple_mtx_assert_locked(&bufmgr->lock);
428
429    if (address == IRIS_BORDER_COLOR_POOL_ADDRESS)
430       return;
431
432    /* Un-canonicalize the address. */
433    address = intel_48b_address(address);
434
435    if (address == 0ull)
436       return;
437
438    enum iris_memory_zone memzone = iris_memzone_for_address(address);
439
440    assert(memzone < ARRAY_SIZE(bufmgr->vma_allocator));
441
442    util_vma_heap_free(&bufmgr->vma_allocator[memzone], address, size);
443 }
444
445 /* A timeout of 0 just checks for busyness. */
446 static int
447 iris_bo_wait_syncobj(struct iris_bo *bo, int64_t timeout_ns)
448 {
449    int ret = 0;
450    struct iris_bufmgr *bufmgr = bo->bufmgr;
451
452    /* If we know it's idle, don't bother with the kernel round trip */
453    if (bo->idle)
454       return 0;
455
456    simple_mtx_lock(&bufmgr->bo_deps_lock);
457
458    uint32_t handles[bo->deps_size * IRIS_BATCH_COUNT * 2];
459    int handle_count = 0;
460
461    for (int d = 0; d < bo->deps_size; d++) {
462       for (int b = 0; b < IRIS_BATCH_COUNT; b++) {
463          struct iris_syncobj *r = bo->deps[d].read_syncobjs[b];
464          struct iris_syncobj *w = bo->deps[d].write_syncobjs[b];
465          if (r)
466             handles[handle_count++] = r->handle;
467          if (w)
468             handles[handle_count++] = w->handle;
469       }
470    }
471
472    if (handle_count == 0)
473       goto out;
474
475    /* Unlike the gem wait, negative values are not infinite here. */
476    int64_t timeout_abs = os_time_get_absolute_timeout(timeout_ns);
477    if (timeout_abs < 0)
478       timeout_abs = INT64_MAX;
479
480    struct drm_syncobj_wait args = {
481       .handles = (uintptr_t) handles,
482       .timeout_nsec = timeout_abs,
483       .count_handles = handle_count,
484       .flags = DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL,
485    };
486
487    ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_SYNCOBJ_WAIT, &args);
488    if (ret != 0) {
489       ret = -errno;
490       goto out;
491    }
492
493    /* We just waited everything, so clean all the deps. */
494    for (int d = 0; d < bo->deps_size; d++) {
495       for (int b = 0; b < IRIS_BATCH_COUNT; b++) {
496          iris_syncobj_reference(bufmgr, &bo->deps[d].write_syncobjs[b], NULL);
497          iris_syncobj_reference(bufmgr, &bo->deps[d].read_syncobjs[b], NULL);
498       }
499    }
500
501 out:
502    simple_mtx_unlock(&bufmgr->bo_deps_lock);
503    return ret;
504 }
505
506 static bool
507 iris_bo_busy_syncobj(struct iris_bo *bo)
508 {
509    return iris_bo_wait_syncobj(bo, 0) == -ETIME;
510 }
511
512 bool
513 iris_bo_busy(struct iris_bo *bo)
514 {
515    bool busy;
516
517    switch (iris_bufmgr_get_device_info(bo->bufmgr)->kmd_type) {
518    case INTEL_KMD_TYPE_I915:
519       if (iris_bo_is_external(bo))
520          busy = iris_i915_bo_busy_gem(bo);
521       else
522          busy = iris_bo_busy_syncobj(bo);
523       break;
524    case INTEL_KMD_TYPE_XE:
525       busy = iris_bo_busy_syncobj(bo);
526       break;
527    default:
528       unreachable("missing");
529       busy = true;
530    }
531
532    bo->idle = !busy;
533
534    return busy;
535 }
536
537 /**
538  * Specify the volatility of the buffer.
539  * \param bo Buffer to create a name for
540  * \param state The purgeable status
541  *
542  * Use IRIS_MADVICE_DONT_NEED to mark the buffer as purgeable, and it will be
543  * reclaimed under memory pressure. If you subsequently require the buffer,
544  * then you must pass IRIS_MADVICE_WILL_NEED to mark the buffer as required.
545  *
546  * Returns true if the buffer was retained, or false if it was discarded
547  * whilst marked as IRIS_MADVICE_DONT_NEED.
548  */
549 static inline bool
550 iris_bo_madvise(struct iris_bo *bo, enum iris_madvice state)
551 {
552    /* We can't madvise suballocated BOs. */
553    assert(iris_bo_is_real(bo));
554
555    return bo->bufmgr->kmd_backend->bo_madvise(bo, state);
556 }
557
558 static struct iris_bo *
559 bo_calloc(void)
560 {
561    struct iris_bo *bo = calloc(1, sizeof(*bo));
562    if (!bo)
563       return NULL;
564
565    list_inithead(&bo->real.exports);
566
567    bo->hash = _mesa_hash_pointer(bo);
568
569    return bo;
570 }
571
572 static void
573 bo_unmap(struct iris_bo *bo)
574 {
575    assert(iris_bo_is_real(bo));
576
577    VG_NOACCESS(bo->real.map, bo->size);
578    os_munmap(bo->real.map, bo->size);
579    bo->real.map = NULL;
580 }
581
582 static struct pb_slabs *
583 get_slabs(struct iris_bufmgr *bufmgr, uint64_t size)
584 {
585    for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
586       struct pb_slabs *slabs = &bufmgr->bo_slabs[i];
587
588       if (size <= 1ull << (slabs->min_order + slabs->num_orders - 1))
589          return slabs;
590    }
591
592    unreachable("should have found a valid slab for this size");
593 }
594
595 /* Return the power of two size of a slab entry matching the input size. */
596 static unsigned
597 get_slab_pot_entry_size(struct iris_bufmgr *bufmgr, unsigned size)
598 {
599    unsigned entry_size = util_next_power_of_two(size);
600    unsigned min_entry_size = 1 << bufmgr->bo_slabs[0].min_order;
601
602    return MAX2(entry_size, min_entry_size);
603 }
604
605 /* Return the slab entry alignment. */
606 static unsigned
607 get_slab_entry_alignment(struct iris_bufmgr *bufmgr, unsigned size)
608 {
609    unsigned entry_size = get_slab_pot_entry_size(bufmgr, size);
610
611    if (size <= entry_size * 3 / 4)
612       return entry_size / 4;
613
614    return entry_size;
615 }
616
617 static bool
618 iris_can_reclaim_slab(void *priv, struct pb_slab_entry *entry)
619 {
620    struct iris_bo *bo = container_of(entry, struct iris_bo, slab.entry);
621
622    return !iris_bo_busy(bo);
623 }
624
625 static void
626 iris_slab_free(void *priv, struct pb_slab *pslab)
627 {
628    struct iris_bufmgr *bufmgr = priv;
629    struct iris_slab *slab = (void *) pslab;
630    struct intel_aux_map_context *aux_map_ctx = bufmgr->aux_map_ctx;
631
632    assert(!slab->bo->aux_map_address);
633
634    /* Since we're freeing the whole slab, all buffers allocated out of it
635     * must be reclaimable.  We require buffers to be idle to be reclaimed
636     * (see iris_can_reclaim_slab()), so we know all entries must be idle.
637     * Therefore, we can safely unmap their aux table entries.
638     */
639    for (unsigned i = 0; i < pslab->num_entries; i++) {
640       struct iris_bo *bo = &slab->entries[i];
641       if (aux_map_ctx && bo->aux_map_address) {
642          intel_aux_map_unmap_range(aux_map_ctx, bo->address, bo->size);
643          bo->aux_map_address = 0;
644       }
645
646       /* Unref read/write dependency syncobjs and free the array. */
647       for (int d = 0; d < bo->deps_size; d++) {
648          for (int b = 0; b < IRIS_BATCH_COUNT; b++) {
649             iris_syncobj_reference(bufmgr, &bo->deps[d].write_syncobjs[b], NULL);
650             iris_syncobj_reference(bufmgr, &bo->deps[d].read_syncobjs[b], NULL);
651          }
652       }
653       free(bo->deps);
654    }
655
656    iris_bo_unreference(slab->bo);
657
658    free(slab->entries);
659    free(slab);
660 }
661
662 static struct pb_slab *
663 iris_slab_alloc(void *priv,
664                 unsigned heap,
665                 unsigned entry_size,
666                 unsigned group_index)
667 {
668    struct iris_bufmgr *bufmgr = priv;
669    struct iris_slab *slab = calloc(1, sizeof(struct iris_slab));
670    uint32_t flags;
671    unsigned slab_size = 0;
672    /* We only support slab allocation for IRIS_MEMZONE_OTHER */
673    enum iris_memory_zone memzone = IRIS_MEMZONE_OTHER;
674
675    if (!slab)
676       return NULL;
677
678    struct pb_slabs *slabs = bufmgr->bo_slabs;
679
680    /* Determine the slab buffer size. */
681    for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
682       unsigned max_entry_size =
683          1 << (slabs[i].min_order + slabs[i].num_orders - 1);
684
685       if (entry_size <= max_entry_size) {
686          /* The slab size is twice the size of the largest possible entry. */
687          slab_size = max_entry_size * 2;
688
689          if (!util_is_power_of_two_nonzero(entry_size)) {
690             assert(util_is_power_of_two_nonzero(entry_size * 4 / 3));
691
692             /* If the entry size is 3/4 of a power of two, we would waste
693              * space and not gain anything if we allocated only twice the
694              * power of two for the backing buffer:
695              *
696              *    2 * 3/4 = 1.5 usable with buffer size 2
697              *
698              * Allocating 5 times the entry size leads us to the next power
699              * of two and results in a much better memory utilization:
700              *
701              *    5 * 3/4 = 3.75 usable with buffer size 4
702              */
703             if (entry_size * 5 > slab_size)
704                slab_size = util_next_power_of_two(entry_size * 5);
705          }
706
707          /* The largest slab should have the same size as the PTE fragment
708           * size to get faster address translation.
709           *
710           * TODO: move this to intel_device_info?
711           */
712          const unsigned pte_size = 2 * 1024 * 1024;
713
714          if (i == NUM_SLAB_ALLOCATORS - 1 && slab_size < pte_size)
715             slab_size = pte_size;
716
717          break;
718       }
719    }
720    assert(slab_size != 0);
721
722    if (heap == IRIS_HEAP_SYSTEM_MEMORY)
723       flags = BO_ALLOC_SMEM;
724    else if (heap == IRIS_HEAP_DEVICE_LOCAL)
725       flags = BO_ALLOC_LMEM;
726    else
727       flags = BO_ALLOC_PLAIN;
728
729    slab->bo =
730       iris_bo_alloc(bufmgr, "slab", slab_size, slab_size, memzone, flags);
731    if (!slab->bo)
732       goto fail;
733
734    slab_size = slab->bo->size;
735
736    slab->base.num_entries = slab_size / entry_size;
737    slab->base.num_free = slab->base.num_entries;
738    slab->entry_size = entry_size;
739    slab->entries = calloc(slab->base.num_entries, sizeof(*slab->entries));
740    if (!slab->entries)
741       goto fail_bo;
742
743    list_inithead(&slab->base.free);
744
745    for (unsigned i = 0; i < slab->base.num_entries; i++) {
746       struct iris_bo *bo = &slab->entries[i];
747
748       bo->size = entry_size;
749       bo->bufmgr = bufmgr;
750       bo->hash = _mesa_hash_pointer(bo);
751       bo->gem_handle = 0;
752       bo->address = slab->bo->address + i * entry_size;
753       bo->aux_map_address = 0;
754       bo->index = -1;
755       bo->refcount = 0;
756       bo->idle = true;
757
758       bo->slab.entry.slab = &slab->base;
759       bo->slab.entry.group_index = group_index;
760       bo->slab.entry.entry_size = entry_size;
761
762       bo->slab.real = iris_get_backing_bo(slab->bo);
763
764       list_addtail(&bo->slab.entry.head, &slab->base.free);
765    }
766
767    return &slab->base;
768
769 fail_bo:
770    iris_bo_unreference(slab->bo);
771 fail:
772    free(slab);
773    return NULL;
774 }
775
776 static enum iris_heap
777 flags_to_heap(struct iris_bufmgr *bufmgr, unsigned flags)
778 {
779    if (bufmgr->vram.size > 0) {
780       if ((flags & BO_ALLOC_SMEM) || (flags & BO_ALLOC_COHERENT))
781          return IRIS_HEAP_SYSTEM_MEMORY;
782       if ((flags & BO_ALLOC_LMEM) ||
783           ((flags & BO_ALLOC_SCANOUT) && !(flags & BO_ALLOC_SHARED)))
784          return IRIS_HEAP_DEVICE_LOCAL;
785       return IRIS_HEAP_DEVICE_LOCAL_PREFERRED;
786    } else {
787       assert(!(flags & BO_ALLOC_LMEM));
788       return IRIS_HEAP_SYSTEM_MEMORY;
789    }
790 }
791
792 static bool
793 zero_bo(struct iris_bufmgr *bufmgr,
794         unsigned flags,
795         struct iris_bo *bo)
796 {
797    assert(flags & BO_ALLOC_ZEROED);
798
799    if (bufmgr->devinfo.has_flat_ccs && (flags & BO_ALLOC_LMEM)) {
800       /* With flat CCS, all allocations in LMEM have memory ranges with
801        * corresponding CCS elements. These elements are only accessible
802        * through GPU commands, but we don't issue GPU commands here.
803        */
804       return false;
805    }
806
807    void *map = iris_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
808    if (!map)
809       return false;
810
811    memset(map, 0, bo->size);
812    return true;
813 }
814
815 static struct iris_bo *
816 alloc_bo_from_slabs(struct iris_bufmgr *bufmgr,
817                     const char *name,
818                     uint64_t size,
819                     uint32_t alignment,
820                     unsigned flags)
821 {
822    if (flags & BO_ALLOC_NO_SUBALLOC)
823       return NULL;
824
825    struct pb_slabs *last_slab = &bufmgr->bo_slabs[NUM_SLAB_ALLOCATORS - 1];
826    unsigned max_slab_entry_size =
827       1 << (last_slab->min_order + last_slab->num_orders - 1);
828
829    if (size > max_slab_entry_size)
830       return NULL;
831
832    struct pb_slab_entry *entry;
833
834    enum iris_heap heap = flags_to_heap(bufmgr, flags);
835
836    unsigned alloc_size = size;
837
838    /* Always use slabs for sizes less than 4 KB because the kernel aligns
839     * everything to 4 KB.
840     */
841    if (size < alignment && alignment <= 4 * 1024)
842       alloc_size = alignment;
843
844    if (alignment > get_slab_entry_alignment(bufmgr, alloc_size)) {
845       /* 3/4 allocations can return too small alignment.
846        * Try again with a power of two allocation size.
847        */
848       unsigned pot_size = get_slab_pot_entry_size(bufmgr, alloc_size);
849
850       if (alignment <= pot_size) {
851          /* This size works but wastes some memory to fulfill the alignment. */
852          alloc_size = pot_size;
853       } else {
854          /* can't fulfill alignment requirements */
855          return NULL;
856       }
857    }
858
859    struct pb_slabs *slabs = get_slabs(bufmgr, alloc_size);
860    entry = pb_slab_alloc(slabs, alloc_size, heap);
861    if (!entry) {
862       /* Clean up and try again... */
863       pb_slabs_reclaim(slabs);
864
865       entry = pb_slab_alloc(slabs, alloc_size, heap);
866    }
867    if (!entry)
868       return NULL;
869
870    struct iris_bo *bo = container_of(entry, struct iris_bo, slab.entry);
871
872    if (bo->aux_map_address && bo->bufmgr->aux_map_ctx) {
873       /* This buffer was associated with an aux-buffer range.  We only allow
874        * slab allocated buffers to be reclaimed when idle (not in use by an
875        * executing batch).  (See iris_can_reclaim_slab().)  So we know that
876        * our previous aux mapping is no longer in use, and we can safely
877        * remove it.
878        */
879       intel_aux_map_unmap_range(bo->bufmgr->aux_map_ctx, bo->address,
880                                 bo->size);
881       bo->aux_map_address = 0;
882    }
883
884    p_atomic_set(&bo->refcount, 1);
885    bo->name = name;
886    bo->size = size;
887
888    /* Zero the contents if necessary.  If this fails, fall back to
889     * allocating a fresh BO, which will always be zeroed by the kernel.
890     */
891    if ((flags & BO_ALLOC_ZEROED) && !zero_bo(bufmgr, flags, bo)) {
892       pb_slab_free(slabs, &bo->slab.entry);
893       return NULL;
894    }
895
896    return bo;
897 }
898
899 static struct iris_bo *
900 alloc_bo_from_cache(struct iris_bufmgr *bufmgr,
901                     struct bo_cache_bucket *bucket,
902                     uint32_t alignment,
903                     enum iris_memory_zone memzone,
904                     enum iris_mmap_mode mmap_mode,
905                     unsigned flags,
906                     bool match_zone)
907 {
908    if (!bucket)
909       return NULL;
910
911    struct iris_bo *bo = NULL;
912
913    simple_mtx_assert_locked(&bufmgr->lock);
914
915    list_for_each_entry_safe(struct iris_bo, cur, &bucket->head, head) {
916       assert(iris_bo_is_real(cur));
917
918       /* Find one that's got the right mapping type.  We used to swap maps
919        * around but the kernel doesn't allow this on discrete GPUs.
920        */
921       if (mmap_mode != cur->real.mmap_mode)
922          continue;
923
924       /* Try a little harder to find one that's already in the right memzone */
925       if (match_zone && memzone != iris_memzone_for_address(cur->address))
926          continue;
927
928       /* If the last BO in the cache is busy, there are no idle BOs.  Bail,
929        * either falling back to a non-matching memzone, or if that fails,
930        * allocating a fresh buffer.
931        */
932       if (iris_bo_busy(cur))
933          return NULL;
934
935       list_del(&cur->head);
936
937       /* Tell the kernel we need this BO and check if it still exist */
938       if (!iris_bo_madvise(cur, IRIS_MADVICE_WILL_NEED)) {
939          /* This BO was purged, throw it out and keep looking. */
940          bo_free(cur);
941          continue;
942       }
943
944       if (cur->aux_map_address) {
945          /* This buffer was associated with an aux-buffer range. We make sure
946           * that buffers are not reused from the cache while the buffer is (busy)
947           * being used by an executing batch. Since we are here, the buffer is no
948           * longer being used by a batch and the buffer was deleted (in order to
949           * end up in the cache). Therefore its old aux-buffer range can be
950           * removed from the aux-map.
951           */
952          if (cur->bufmgr->aux_map_ctx)
953             intel_aux_map_unmap_range(cur->bufmgr->aux_map_ctx, cur->address,
954                                       cur->size);
955          cur->aux_map_address = 0;
956       }
957
958       /* If the cached BO isn't in the right memory zone, or the alignment
959        * isn't sufficient, free the old memory and assign it a new address.
960        */
961       if (memzone != iris_memzone_for_address(cur->address) ||
962           cur->address % alignment != 0) {
963          if (!bufmgr->kmd_backend->gem_vm_unbind(cur)) {
964             DBG("Unable to unbind vm of buf %u\n", cur->gem_handle);
965             bo_free(cur);
966             continue;
967          }
968
969          vma_free(bufmgr, cur->address, cur->size);
970          cur->address = 0ull;
971       }
972
973       bo = cur;
974       break;
975    }
976
977    if (!bo)
978       return NULL;
979
980    /* Zero the contents if necessary.  If this fails, fall back to
981     * allocating a fresh BO, which will always be zeroed by the kernel.
982     */
983    if ((flags & BO_ALLOC_ZEROED) && !zero_bo(bufmgr, flags, bo)) {
984       bo_free(bo);
985       return NULL;
986    }
987
988    return bo;
989 }
990
991 static int
992 i915_gem_set_domain(struct iris_bufmgr *bufmgr, uint32_t handle,
993                     uint32_t read_domains, uint32_t write_domains)
994 {
995    struct drm_i915_gem_set_domain sd = {
996       .handle = handle,
997       .read_domains = read_domains,
998       .write_domain = write_domains,
999    };
1000    return intel_ioctl(iris_bufmgr_get_fd(bufmgr),
1001                       DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd);
1002 }
1003
1004 static struct iris_bo *
1005 alloc_fresh_bo(struct iris_bufmgr *bufmgr, uint64_t bo_size, unsigned flags)
1006 {
1007    struct iris_bo *bo = bo_calloc();
1008    if (!bo)
1009       return NULL;
1010
1011    bo->real.heap = flags_to_heap(bufmgr, flags);
1012
1013    const struct intel_memory_class_instance *regions[2];
1014    uint16_t num_regions = 0;
1015
1016    if (bufmgr->vram.size > 0) {
1017       switch (bo->real.heap) {
1018       case IRIS_HEAP_DEVICE_LOCAL_PREFERRED:
1019          /* For vram allocations, still use system memory as a fallback. */
1020          regions[num_regions++] = bufmgr->vram.region;
1021          regions[num_regions++] = bufmgr->sys.region;
1022          break;
1023       case IRIS_HEAP_DEVICE_LOCAL:
1024          regions[num_regions++] = bufmgr->vram.region;
1025          break;
1026       case IRIS_HEAP_SYSTEM_MEMORY:
1027          regions[num_regions++] = bufmgr->sys.region;
1028          break;
1029       case IRIS_HEAP_MAX:
1030          unreachable("invalid heap for BO");
1031       }
1032    } else {
1033       regions[num_regions++] = bufmgr->sys.region;
1034    }
1035
1036    bo->gem_handle = bufmgr->kmd_backend->gem_create(bufmgr, regions,
1037                                                     num_regions, bo_size,
1038                                                     bo->real.heap, flags);
1039    if (bo->gem_handle == 0) {
1040       free(bo);
1041       return NULL;
1042    }
1043    bo->bufmgr = bufmgr;
1044    bo->size = bo_size;
1045    bo->idle = true;
1046
1047    if (bufmgr->vram.size == 0)
1048       /* Calling set_domain() will allocate pages for the BO outside of the
1049        * struct mutex lock in the kernel, which is more efficient than waiting
1050        * to create them during the first execbuf that uses the BO.
1051        */
1052       i915_gem_set_domain(bufmgr, bo->gem_handle, I915_GEM_DOMAIN_CPU, 0);
1053
1054    return bo;
1055 }
1056
1057 const char *
1058 iris_heap_to_string[IRIS_HEAP_MAX] = {
1059    [IRIS_HEAP_SYSTEM_MEMORY] = "system",
1060    [IRIS_HEAP_DEVICE_LOCAL] = "local",
1061    [IRIS_HEAP_DEVICE_LOCAL_PREFERRED] = "local-preferred",
1062 };
1063
1064 struct iris_bo *
1065 iris_bo_alloc(struct iris_bufmgr *bufmgr,
1066               const char *name,
1067               uint64_t size,
1068               uint32_t alignment,
1069               enum iris_memory_zone memzone,
1070               unsigned flags)
1071 {
1072    struct iris_bo *bo;
1073    unsigned int page_size = getpagesize();
1074    enum iris_heap heap = flags_to_heap(bufmgr, flags);
1075    bool local = heap != IRIS_HEAP_SYSTEM_MEMORY;
1076    struct bo_cache_bucket *bucket = bucket_for_size(bufmgr, size, heap, flags);
1077
1078    if (memzone != IRIS_MEMZONE_OTHER || (flags & BO_ALLOC_COHERENT))
1079       flags |= BO_ALLOC_NO_SUBALLOC;
1080
1081    bo = alloc_bo_from_slabs(bufmgr, name, size, alignment, flags);
1082
1083    if (bo)
1084       return bo;
1085
1086    /* Round the size up to the bucket size, or if we don't have caching
1087     * at this size, a multiple of the page size.
1088     */
1089    uint64_t bo_size =
1090       bucket ? bucket->size : MAX2(ALIGN(size, page_size), page_size);
1091
1092    bool is_coherent = bufmgr->devinfo.has_llc ||
1093                       (bufmgr->vram.size > 0 && !local) ||
1094                       (flags & BO_ALLOC_COHERENT);
1095    bool is_scanout = (flags & BO_ALLOC_SCANOUT) != 0;
1096
1097    enum iris_mmap_mode mmap_mode;
1098    if (!intel_vram_all_mappable(&bufmgr->devinfo) && heap == IRIS_HEAP_DEVICE_LOCAL)
1099       mmap_mode = IRIS_MMAP_NONE;
1100    else if (!local && is_coherent && !is_scanout)
1101       mmap_mode = IRIS_MMAP_WB;
1102    else
1103       mmap_mode = IRIS_MMAP_WC;
1104
1105    simple_mtx_lock(&bufmgr->lock);
1106
1107    /* Get a buffer out of the cache if available.  First, we try to find
1108     * one with a matching memory zone so we can avoid reallocating VMA.
1109     */
1110    bo = alloc_bo_from_cache(bufmgr, bucket, alignment, memzone, mmap_mode,
1111                             flags, true);
1112
1113    /* If that fails, we try for any cached BO, without matching memzone. */
1114    if (!bo) {
1115       bo = alloc_bo_from_cache(bufmgr, bucket, alignment, memzone, mmap_mode,
1116                                flags, false);
1117    }
1118
1119    simple_mtx_unlock(&bufmgr->lock);
1120
1121    if (!bo) {
1122       bo = alloc_fresh_bo(bufmgr, bo_size, flags);
1123       if (!bo)
1124          return NULL;
1125    }
1126
1127    if (bo->address == 0ull) {
1128       simple_mtx_lock(&bufmgr->lock);
1129       bo->address = vma_alloc(bufmgr, memzone, bo->size, alignment);
1130       simple_mtx_unlock(&bufmgr->lock);
1131
1132       if (bo->address == 0ull)
1133          goto err_free;
1134
1135       if (!bufmgr->kmd_backend->gem_vm_bind(bo))
1136          goto err_vm_alloc;
1137    }
1138
1139    bo->name = name;
1140    p_atomic_set(&bo->refcount, 1);
1141    bo->real.reusable = bucket && bufmgr->bo_reuse;
1142    bo->real.protected = flags & BO_ALLOC_PROTECTED;
1143    bo->index = -1;
1144    bo->real.kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
1145
1146    /* By default, capture all driver-internal buffers like shader kernels,
1147     * surface states, dynamic states, border colors, and so on.
1148     */
1149    if (memzone < IRIS_MEMZONE_OTHER || INTEL_DEBUG(DEBUG_CAPTURE_ALL))
1150       bo->real.kflags |= EXEC_OBJECT_CAPTURE;
1151
1152    assert(bo->real.map == NULL || bo->real.mmap_mode == mmap_mode);
1153    bo->real.mmap_mode = mmap_mode;
1154
1155    /* On integrated GPUs, enable snooping to ensure coherency if needed.
1156     * For discrete, we instead use SMEM and avoid WB maps for coherency.
1157     */
1158    if ((flags & BO_ALLOC_COHERENT) &&
1159        !bufmgr->devinfo.has_llc && bufmgr->devinfo.has_caching_uapi) {
1160       if (bufmgr->kmd_backend->bo_set_caching(bo, true) != 0)
1161          goto err_free;
1162
1163       bo->real.reusable = false;
1164    }
1165
1166    DBG("bo_create: buf %d (%s) (%s memzone) (%s) %llub\n", bo->gem_handle,
1167        bo->name, memzone_name(memzone), iris_heap_to_string[bo->real.heap],
1168        (unsigned long long) size);
1169
1170    return bo;
1171
1172 err_vm_alloc:
1173    vma_free(bufmgr, bo->address, bo->size);
1174 err_free:
1175    simple_mtx_lock(&bufmgr->lock);
1176    bo_free(bo);
1177    simple_mtx_unlock(&bufmgr->lock);
1178    return NULL;
1179 }
1180
1181 static int
1182 iris_bo_close(int fd, uint32_t gem_handle)
1183 {
1184    struct drm_gem_close close = {
1185       .handle = gem_handle,
1186    };
1187    return intel_ioctl(fd, DRM_IOCTL_GEM_CLOSE, &close);
1188 }
1189
1190 static int
1191 iris_bufmgr_bo_close(struct iris_bufmgr *bufmgr, uint32_t gem_handle)
1192 {
1193    return iris_bo_close(bufmgr->fd, gem_handle);
1194 }
1195
1196 struct iris_bo *
1197 iris_bo_create_userptr(struct iris_bufmgr *bufmgr, const char *name,
1198                        void *ptr, size_t size,
1199                        enum iris_memory_zone memzone)
1200 {
1201    struct iris_bo *bo;
1202
1203    bo = bo_calloc();
1204    if (!bo)
1205       return NULL;
1206
1207    struct drm_i915_gem_userptr arg = {
1208       .user_ptr = (uintptr_t)ptr,
1209       .user_size = size,
1210       .flags = bufmgr->devinfo.has_userptr_probe ? I915_USERPTR_PROBE : 0,
1211    };
1212    if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_USERPTR, &arg))
1213       goto err_free;
1214    bo->gem_handle = arg.handle;
1215
1216    if (!bufmgr->devinfo.has_userptr_probe) {
1217       /* Check the buffer for validity before we try and use it in a batch */
1218       if (i915_gem_set_domain(bufmgr, bo->gem_handle, I915_GEM_DOMAIN_CPU, 0))
1219          goto err_close;
1220    }
1221
1222    bo->name = name;
1223    bo->size = size;
1224    bo->real.map = ptr;
1225
1226    bo->bufmgr = bufmgr;
1227    bo->real.kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
1228
1229    if (INTEL_DEBUG(DEBUG_CAPTURE_ALL))
1230       bo->real.kflags |= EXEC_OBJECT_CAPTURE;
1231
1232    simple_mtx_lock(&bufmgr->lock);
1233    bo->address = vma_alloc(bufmgr, memzone, size, 1);
1234    simple_mtx_unlock(&bufmgr->lock);
1235
1236    if (bo->address == 0ull)
1237       goto err_close;
1238
1239    p_atomic_set(&bo->refcount, 1);
1240    bo->real.userptr = true;
1241    bo->index = -1;
1242    bo->idle = true;
1243    bo->real.mmap_mode = IRIS_MMAP_WB;
1244
1245    return bo;
1246
1247 err_close:
1248    iris_bufmgr_bo_close(bufmgr, bo->gem_handle);
1249 err_free:
1250    free(bo);
1251    return NULL;
1252 }
1253
1254 /**
1255  * Returns a iris_bo wrapping the given buffer object handle.
1256  *
1257  * This can be used when one application needs to pass a buffer object
1258  * to another.
1259  */
1260 struct iris_bo *
1261 iris_bo_gem_create_from_name(struct iris_bufmgr *bufmgr,
1262                              const char *name, unsigned int handle)
1263 {
1264    struct iris_bo *bo;
1265
1266    /* At the moment most applications only have a few named bo.
1267     * For instance, in a DRI client only the render buffers passed
1268     * between X and the client are named. And since X returns the
1269     * alternating names for the front/back buffer a linear search
1270     * provides a sufficiently fast match.
1271     */
1272    simple_mtx_lock(&bufmgr->lock);
1273    bo = find_and_ref_external_bo(bufmgr->name_table, handle);
1274    if (bo)
1275       goto out;
1276
1277    struct drm_gem_open open_arg = { .name = handle };
1278    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
1279    if (ret != 0) {
1280       DBG("Couldn't reference %s handle 0x%08x: %s\n",
1281           name, handle, strerror(errno));
1282       bo = NULL;
1283       goto out;
1284    }
1285    /* Now see if someone has used a prime handle to get this
1286     * object from the kernel before by looking through the list
1287     * again for a matching gem_handle
1288     */
1289    bo = find_and_ref_external_bo(bufmgr->handle_table, open_arg.handle);
1290    if (bo)
1291       goto out;
1292
1293    bo = bo_calloc();
1294    if (!bo) {
1295       iris_bufmgr_bo_close(bufmgr, open_arg.handle);
1296       goto out;
1297    }
1298
1299    p_atomic_set(&bo->refcount, 1);
1300
1301    bo->size = open_arg.size;
1302    bo->bufmgr = bufmgr;
1303    bo->gem_handle = open_arg.handle;
1304    bo->name = name;
1305    bo->real.global_name = handle;
1306    bo->real.reusable = false;
1307    bo->real.imported = true;
1308    bo->real.mmap_mode = IRIS_MMAP_NONE;
1309    bo->real.kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
1310    if (INTEL_DEBUG(DEBUG_CAPTURE_ALL))
1311       bo->real.kflags |= EXEC_OBJECT_CAPTURE;
1312    bo->address = vma_alloc(bufmgr, IRIS_MEMZONE_OTHER, bo->size, 1);
1313    if (bo->address == 0ull)
1314       goto err_free;
1315
1316    if (!bufmgr->kmd_backend->gem_vm_bind(bo))
1317       goto err_vm_alloc;
1318
1319    _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1320    _mesa_hash_table_insert(bufmgr->name_table, &bo->real.global_name, bo);
1321
1322    DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
1323
1324 out:
1325    simple_mtx_unlock(&bufmgr->lock);
1326    return bo;
1327
1328 err_vm_alloc:
1329    vma_free(bufmgr, bo->address, bo->size);
1330 err_free:
1331    bo_free(bo);
1332    simple_mtx_unlock(&bufmgr->lock);
1333    return NULL;
1334 }
1335
1336 static void
1337 bo_close(struct iris_bo *bo)
1338 {
1339    struct iris_bufmgr *bufmgr = bo->bufmgr;
1340
1341    simple_mtx_assert_locked(&bufmgr->lock);
1342    assert(iris_bo_is_real(bo));
1343
1344    if (iris_bo_is_external(bo)) {
1345       struct hash_entry *entry;
1346
1347       if (bo->real.global_name) {
1348          entry = _mesa_hash_table_search(bufmgr->name_table,
1349                                          &bo->real.global_name);
1350          _mesa_hash_table_remove(bufmgr->name_table, entry);
1351       }
1352
1353       entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
1354       _mesa_hash_table_remove(bufmgr->handle_table, entry);
1355
1356       list_for_each_entry_safe(struct bo_export, export, &bo->real.exports, link) {
1357          iris_bo_close(export->drm_fd, export->gem_handle);
1358
1359          list_del(&export->link);
1360          free(export);
1361       }
1362    } else {
1363       assert(list_is_empty(&bo->real.exports));
1364    }
1365
1366    /* Unbind and return the VMA for reuse */
1367    if (bufmgr->kmd_backend->gem_vm_unbind(bo))
1368       vma_free(bo->bufmgr, bo->address, bo->size);
1369    else
1370       DBG("Unable to unbind vm of buf %u\n", bo->gem_handle);
1371
1372    /* Close this object */
1373    if (iris_bufmgr_bo_close(bufmgr, bo->gem_handle) != 0) {
1374       DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
1375           bo->gem_handle, bo->name, strerror(errno));
1376    }
1377
1378    if (bo->aux_map_address && bo->bufmgr->aux_map_ctx) {
1379       intel_aux_map_unmap_range(bo->bufmgr->aux_map_ctx, bo->address,
1380                                 bo->size);
1381    }
1382
1383    for (int d = 0; d < bo->deps_size; d++) {
1384       for (int b = 0; b < IRIS_BATCH_COUNT; b++) {
1385          iris_syncobj_reference(bufmgr, &bo->deps[d].write_syncobjs[b], NULL);
1386          iris_syncobj_reference(bufmgr, &bo->deps[d].read_syncobjs[b], NULL);
1387       }
1388    }
1389    free(bo->deps);
1390
1391    free(bo);
1392 }
1393
1394 static void
1395 bo_free(struct iris_bo *bo)
1396 {
1397    struct iris_bufmgr *bufmgr = bo->bufmgr;
1398
1399    simple_mtx_assert_locked(&bufmgr->lock);
1400    assert(iris_bo_is_real(bo));
1401
1402    if (!bo->real.userptr && bo->real.map)
1403       bo_unmap(bo);
1404
1405    if (bo->idle || !iris_bo_busy(bo)) {
1406       bo_close(bo);
1407    } else {
1408       /* Defer closing the GEM BO and returning the VMA for reuse until the
1409        * BO is idle.  Just move it to the dead list for now.
1410        */
1411       list_addtail(&bo->head, &bufmgr->zombie_list);
1412    }
1413 }
1414
1415 /** Frees all cached buffers significantly older than @time. */
1416 static void
1417 cleanup_bo_cache(struct iris_bufmgr *bufmgr, time_t time)
1418 {
1419    int i;
1420
1421    simple_mtx_assert_locked(&bufmgr->lock);
1422
1423    if (bufmgr->time == time)
1424       return;
1425
1426    for (i = 0; i < bufmgr->num_buckets; i++) {
1427       struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1428
1429       list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
1430          if (time - bo->real.free_time <= 1)
1431             break;
1432
1433          list_del(&bo->head);
1434
1435          bo_free(bo);
1436       }
1437    }
1438
1439    for (i = 0; i < bufmgr->num_local_buckets; i++) {
1440       struct bo_cache_bucket *bucket = &bufmgr->local_cache_bucket[i];
1441
1442       list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
1443          if (time - bo->real.free_time <= 1)
1444             break;
1445
1446          list_del(&bo->head);
1447
1448          bo_free(bo);
1449       }
1450    }
1451
1452    for (i = 0; i < bufmgr->num_local_preferred_buckets; i++) {
1453       struct bo_cache_bucket *bucket = &bufmgr->local_preferred_cache_bucket[i];
1454
1455       list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
1456          if (time - bo->real.free_time <= 1)
1457             break;
1458
1459          list_del(&bo->head);
1460
1461          bo_free(bo);
1462       }
1463    }
1464
1465    list_for_each_entry_safe(struct iris_bo, bo, &bufmgr->zombie_list, head) {
1466       /* Stop once we reach a busy BO - all others past this point were
1467        * freed more recently so are likely also busy.
1468        */
1469       if (!bo->idle && iris_bo_busy(bo))
1470          break;
1471
1472       list_del(&bo->head);
1473       bo_close(bo);
1474    }
1475
1476    bufmgr->time = time;
1477 }
1478
1479 static void
1480 bo_unreference_final(struct iris_bo *bo, time_t time)
1481 {
1482    struct iris_bufmgr *bufmgr = bo->bufmgr;
1483    struct bo_cache_bucket *bucket;
1484
1485    DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
1486
1487    assert(iris_bo_is_real(bo));
1488
1489    bucket = NULL;
1490    if (bo->real.reusable)
1491       bucket = bucket_for_size(bufmgr, bo->size, bo->real.heap, 0);
1492    /* Put the buffer into our internal cache for reuse if we can. */
1493    if (bucket && iris_bo_madvise(bo, IRIS_MADVICE_DONT_NEED)) {
1494       bo->real.free_time = time;
1495       bo->name = NULL;
1496
1497       list_addtail(&bo->head, &bucket->head);
1498    } else {
1499       bo_free(bo);
1500    }
1501 }
1502
1503 void
1504 iris_bo_unreference(struct iris_bo *bo)
1505 {
1506    if (bo == NULL)
1507       return;
1508
1509    assert(p_atomic_read(&bo->refcount) > 0);
1510
1511    if (atomic_add_unless(&bo->refcount, -1, 1)) {
1512       struct iris_bufmgr *bufmgr = bo->bufmgr;
1513       struct timespec time;
1514
1515       clock_gettime(CLOCK_MONOTONIC, &time);
1516
1517       if (bo->gem_handle == 0) {
1518          pb_slab_free(get_slabs(bufmgr, bo->size), &bo->slab.entry);
1519       } else {
1520          simple_mtx_lock(&bufmgr->lock);
1521
1522          if (p_atomic_dec_zero(&bo->refcount)) {
1523             bo_unreference_final(bo, time.tv_sec);
1524             cleanup_bo_cache(bufmgr, time.tv_sec);
1525          }
1526
1527          simple_mtx_unlock(&bufmgr->lock);
1528       }
1529    }
1530 }
1531
1532 static void
1533 bo_wait_with_stall_warning(struct util_debug_callback *dbg,
1534                            struct iris_bo *bo,
1535                            const char *action)
1536 {
1537    bool busy = dbg && !bo->idle;
1538    double elapsed = unlikely(busy) ? -get_time() : 0.0;
1539
1540    iris_bo_wait_rendering(bo);
1541
1542    if (unlikely(busy)) {
1543       elapsed += get_time();
1544       if (elapsed > 1e-5) /* 0.01ms */ {
1545          perf_debug(dbg, "%s a busy \"%s\" BO stalled and took %.03f ms.\n",
1546                     action, bo->name, elapsed * 1000);
1547       }
1548    }
1549 }
1550
1551 static void
1552 print_flags(unsigned flags)
1553 {
1554    if (flags & MAP_READ)
1555       DBG("READ ");
1556    if (flags & MAP_WRITE)
1557       DBG("WRITE ");
1558    if (flags & MAP_ASYNC)
1559       DBG("ASYNC ");
1560    if (flags & MAP_PERSISTENT)
1561       DBG("PERSISTENT ");
1562    if (flags & MAP_COHERENT)
1563       DBG("COHERENT ");
1564    if (flags & MAP_RAW)
1565       DBG("RAW ");
1566    DBG("\n");
1567 }
1568
1569 void *
1570 iris_bo_map(struct util_debug_callback *dbg,
1571             struct iris_bo *bo, unsigned flags)
1572 {
1573    struct iris_bufmgr *bufmgr = bo->bufmgr;
1574    void *map = NULL;
1575
1576    if (bo->gem_handle == 0) {
1577       struct iris_bo *real = iris_get_backing_bo(bo);
1578       uint64_t offset = bo->address - real->address;
1579       map = iris_bo_map(dbg, real, flags | MAP_ASYNC) + offset;
1580    } else {
1581       assert(bo->real.mmap_mode != IRIS_MMAP_NONE);
1582       if (bo->real.mmap_mode == IRIS_MMAP_NONE)
1583          return NULL;
1584
1585       if (!bo->real.map) {
1586          DBG("iris_bo_map: %d (%s)\n", bo->gem_handle, bo->name);
1587          map = bufmgr->kmd_backend->gem_mmap(bufmgr, bo);
1588          if (!map) {
1589             return NULL;
1590          }
1591
1592          VG_DEFINED(map, bo->size);
1593
1594          if (p_atomic_cmpxchg(&bo->real.map, NULL, map)) {
1595             VG_NOACCESS(map, bo->size);
1596             os_munmap(map, bo->size);
1597          }
1598       }
1599       assert(bo->real.map);
1600       map = bo->real.map;
1601    }
1602
1603    DBG("iris_bo_map: %d (%s) -> %p\n",
1604        bo->gem_handle, bo->name, bo->real.map);
1605    print_flags(flags);
1606
1607    if (!(flags & MAP_ASYNC)) {
1608       bo_wait_with_stall_warning(dbg, bo, "memory mapping");
1609    }
1610
1611    return map;
1612 }
1613
1614 /**
1615  * Waits on a BO for the given amount of time.
1616  *
1617  * @bo: buffer object to wait for
1618  * @timeout_ns: amount of time to wait in nanoseconds.
1619  *   If value is less than 0, an infinite wait will occur.
1620  *
1621  * Returns 0 if the wait was successful ie. the last batch referencing the
1622  * object has completed within the allotted time. Otherwise some negative return
1623  * value describes the error. Of particular interest is -ETIME when the wait has
1624  * failed to yield the desired result.
1625  *
1626  * Similar to iris_bo_wait_rendering except a timeout parameter allows
1627  * the operation to give up after a certain amount of time. Another subtle
1628  * difference is the internal locking semantics are different (this variant does
1629  * not hold the lock for the duration of the wait). This makes the wait subject
1630  * to a larger userspace race window.
1631  *
1632  * The implementation shall wait until the object is no longer actively
1633  * referenced within a batch buffer at the time of the call. The wait will
1634  * not guarantee that the buffer is re-issued via another thread, or an flinked
1635  * handle. Userspace must make sure this race does not occur if such precision
1636  * is important.
1637  *
1638  * Note that some kernels have broken the infinite wait for negative values
1639  * promise, upgrade to latest stable kernels if this is the case.
1640  */
1641 static inline int
1642 iris_bo_wait(struct iris_bo *bo, int64_t timeout_ns)
1643 {
1644    int ret;
1645
1646    switch (iris_bufmgr_get_device_info(bo->bufmgr)->kmd_type) {
1647    case INTEL_KMD_TYPE_I915:
1648       if (iris_bo_is_external(bo))
1649          ret = iris_i915_bo_wait_gem(bo, timeout_ns);
1650       else
1651          ret = iris_bo_wait_syncobj(bo, timeout_ns);
1652       break;
1653    case INTEL_KMD_TYPE_XE:
1654       ret = iris_bo_wait_syncobj(bo, timeout_ns);
1655       break;
1656    default:
1657       unreachable("missing");
1658       ret = -1;
1659    }
1660
1661    bo->idle = ret == 0;
1662
1663    return ret;
1664 }
1665
1666 /** Waits for all GPU rendering with the object to have completed. */
1667 void
1668 iris_bo_wait_rendering(struct iris_bo *bo)
1669 {
1670    /* We require a kernel recent enough for WAIT_IOCTL support.
1671     * See intel_init_bufmgr()
1672     */
1673    iris_bo_wait(bo, -1);
1674 }
1675
1676 static void
1677 iris_bufmgr_destroy_global_vm(struct iris_bufmgr *bufmgr)
1678 {
1679    switch (bufmgr->devinfo.kmd_type) {
1680    case INTEL_KMD_TYPE_I915:
1681       /* Nothing to do in i915 */
1682       break;
1683    case INTEL_KMD_TYPE_XE:
1684       iris_xe_destroy_global_vm(bufmgr);
1685       break;
1686    default:
1687       unreachable("missing");
1688    }
1689 }
1690
1691 static void
1692 iris_bufmgr_destroy(struct iris_bufmgr *bufmgr)
1693 {
1694    iris_destroy_border_color_pool(&bufmgr->border_color_pool);
1695
1696    /* Free aux-map buffers */
1697    intel_aux_map_finish(bufmgr->aux_map_ctx);
1698
1699    /* bufmgr will no longer try to free VMA entries in the aux-map */
1700    bufmgr->aux_map_ctx = NULL;
1701
1702    for (int i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
1703       if (bufmgr->bo_slabs[i].groups)
1704          pb_slabs_deinit(&bufmgr->bo_slabs[i]);
1705    }
1706
1707    simple_mtx_lock(&bufmgr->lock);
1708    /* Free any cached buffer objects we were going to reuse */
1709    for (int i = 0; i < bufmgr->num_buckets; i++) {
1710       struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1711
1712       list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
1713          list_del(&bo->head);
1714
1715          bo_free(bo);
1716       }
1717    }
1718
1719    for (int i = 0; i < bufmgr->num_local_buckets; i++) {
1720       struct bo_cache_bucket *bucket = &bufmgr->local_cache_bucket[i];
1721
1722       list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
1723          list_del(&bo->head);
1724
1725          bo_free(bo);
1726       }
1727    }
1728
1729    for (int i = 0; i < bufmgr->num_local_preferred_buckets; i++) {
1730       struct bo_cache_bucket *bucket = &bufmgr->local_preferred_cache_bucket[i];
1731
1732       list_for_each_entry_safe(struct iris_bo, bo, &bucket->head, head) {
1733          list_del(&bo->head);
1734
1735          bo_free(bo);
1736       }
1737    }
1738
1739    /* Close any buffer objects on the dead list. */
1740    list_for_each_entry_safe(struct iris_bo, bo, &bufmgr->zombie_list, head) {
1741       list_del(&bo->head);
1742       bo_close(bo);
1743    }
1744
1745    _mesa_hash_table_destroy(bufmgr->name_table, NULL);
1746    _mesa_hash_table_destroy(bufmgr->handle_table, NULL);
1747
1748    for (int z = 0; z < IRIS_MEMZONE_COUNT; z++)
1749          util_vma_heap_finish(&bufmgr->vma_allocator[z]);
1750
1751    iris_bufmgr_destroy_global_vm(bufmgr);
1752
1753    close(bufmgr->fd);
1754
1755    simple_mtx_unlock(&bufmgr->lock);
1756
1757    simple_mtx_destroy(&bufmgr->lock);
1758    simple_mtx_destroy(&bufmgr->bo_deps_lock);
1759
1760    free(bufmgr);
1761 }
1762
1763 int
1764 iris_gem_get_tiling(struct iris_bo *bo, uint32_t *tiling)
1765 {
1766    struct iris_bufmgr *bufmgr = bo->bufmgr;
1767
1768    if (!bufmgr->devinfo.has_tiling_uapi) {
1769       *tiling = I915_TILING_NONE;
1770       return 0;
1771    }
1772
1773    struct drm_i915_gem_get_tiling ti = { .handle = bo->gem_handle };
1774    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &ti);
1775
1776    if (ret) {
1777       DBG("gem_get_tiling failed for BO %u: %s\n",
1778           bo->gem_handle, strerror(errno));
1779    }
1780
1781    *tiling = ti.tiling_mode;
1782
1783    return ret;
1784 }
1785
1786 int
1787 iris_gem_set_tiling(struct iris_bo *bo, const struct isl_surf *surf)
1788 {
1789    struct iris_bufmgr *bufmgr = bo->bufmgr;
1790    uint32_t tiling_mode = isl_tiling_to_i915_tiling(surf->tiling);
1791    int ret;
1792
1793    /* If we can't do map_gtt, the set/get_tiling API isn't useful. And it's
1794     * actually not supported by the kernel in those cases.
1795     */
1796    if (!bufmgr->devinfo.has_tiling_uapi)
1797       return 0;
1798
1799    /* GEM_SET_TILING is slightly broken and overwrites the input on the
1800     * error path, so we have to open code intel_ioctl().
1801     */
1802    do {
1803       struct drm_i915_gem_set_tiling set_tiling = {
1804          .handle = bo->gem_handle,
1805          .tiling_mode = tiling_mode,
1806          .stride = surf->row_pitch_B,
1807       };
1808       ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
1809    } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
1810
1811    if (ret) {
1812       DBG("gem_set_tiling failed for BO %u: %s\n",
1813           bo->gem_handle, strerror(errno));
1814    }
1815
1816    return ret;
1817 }
1818
1819 struct iris_bo *
1820 iris_bo_import_dmabuf(struct iris_bufmgr *bufmgr, int prime_fd)
1821 {
1822    uint32_t handle;
1823    struct iris_bo *bo;
1824
1825    simple_mtx_lock(&bufmgr->lock);
1826    int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1827    if (ret) {
1828       DBG("import_dmabuf: failed to obtain handle from fd: %s\n",
1829           strerror(errno));
1830       simple_mtx_unlock(&bufmgr->lock);
1831       return NULL;
1832    }
1833
1834    /*
1835     * See if the kernel has already returned this buffer to us. Just as
1836     * for named buffers, we must not create two bo's pointing at the same
1837     * kernel object
1838     */
1839    bo = find_and_ref_external_bo(bufmgr->handle_table, handle);
1840    if (bo)
1841       goto out;
1842
1843    bo = bo_calloc();
1844    if (!bo)
1845       goto out;
1846
1847    p_atomic_set(&bo->refcount, 1);
1848
1849    /* Determine size of bo.  The fd-to-handle ioctl really should
1850     * return the size, but it doesn't.  If we have kernel 3.12 or
1851     * later, we can lseek on the prime fd to get the size.  Older
1852     * kernels will just fail, in which case we fall back to the
1853     * provided (estimated or guess size). */
1854    ret = lseek(prime_fd, 0, SEEK_END);
1855    if (ret != -1)
1856       bo->size = ret;
1857
1858    bo->bufmgr = bufmgr;
1859    bo->name = "prime";
1860    bo->real.reusable = false;
1861    bo->real.imported = true;
1862    bo->real.mmap_mode = IRIS_MMAP_NONE;
1863    bo->real.kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED;
1864    if (INTEL_DEBUG(DEBUG_CAPTURE_ALL))
1865       bo->real.kflags |= EXEC_OBJECT_CAPTURE;
1866    bo->gem_handle = handle;
1867
1868    /* From the Bspec, Memory Compression - Gfx12:
1869     *
1870     *    The base address for the surface has to be 64K page aligned and the
1871     *    surface is expected to be padded in the virtual domain to be 4 4K
1872     *    pages.
1873     *
1874     * The dmabuf may contain a compressed surface. Align the BO to 64KB just
1875     * in case. We always align to 64KB even on platforms where we don't need
1876     * to, because it's a fairly reasonable thing to do anyway.
1877     */
1878    bo->address = vma_alloc(bufmgr, IRIS_MEMZONE_OTHER, bo->size, 64 * 1024);
1879    if (bo->address == 0ull)
1880       goto err_free;
1881
1882    if (!bufmgr->kmd_backend->gem_vm_bind(bo))
1883       goto err_vm_alloc;
1884
1885    _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1886
1887 out:
1888    simple_mtx_unlock(&bufmgr->lock);
1889    return bo;
1890
1891 err_vm_alloc:
1892    vma_free(bufmgr, bo->address, bo->size);
1893 err_free:
1894    bo_free(bo);
1895    simple_mtx_unlock(&bufmgr->lock);
1896    return NULL;
1897 }
1898
1899 static void
1900 iris_bo_mark_exported_locked(struct iris_bo *bo)
1901 {
1902    struct iris_bufmgr *bufmgr = bo->bufmgr;
1903
1904    /* We cannot export suballocated BOs. */
1905    assert(iris_bo_is_real(bo));
1906    simple_mtx_assert_locked(&bufmgr->lock);
1907
1908    if (!iris_bo_is_external(bo))
1909       _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1910
1911    if (!bo->real.exported) {
1912       /* If a BO is going to be used externally, it could be sent to the
1913        * display HW. So make sure our CPU mappings don't assume cache
1914        * coherency since display is outside that cache.
1915        */
1916       bo->real.exported = true;
1917       bo->real.reusable = false;
1918    }
1919 }
1920
1921 void
1922 iris_bo_mark_exported(struct iris_bo *bo)
1923 {
1924    struct iris_bufmgr *bufmgr = bo->bufmgr;
1925
1926    /* We cannot export suballocated BOs. */
1927    assert(iris_bo_is_real(bo));
1928
1929    if (bo->real.exported) {
1930       assert(!bo->real.reusable);
1931       return;
1932    }
1933
1934    simple_mtx_lock(&bufmgr->lock);
1935    iris_bo_mark_exported_locked(bo);
1936    simple_mtx_unlock(&bufmgr->lock);
1937 }
1938
1939 int
1940 iris_bo_export_dmabuf(struct iris_bo *bo, int *prime_fd)
1941 {
1942    struct iris_bufmgr *bufmgr = bo->bufmgr;
1943
1944    /* We cannot export suballocated BOs. */
1945    assert(iris_bo_is_real(bo));
1946
1947    if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1948                           DRM_CLOEXEC | DRM_RDWR, prime_fd) != 0)
1949       return -errno;
1950
1951    iris_bo_mark_exported(bo);
1952
1953    return 0;
1954 }
1955
1956 static uint32_t
1957 iris_bo_export_gem_handle(struct iris_bo *bo)
1958 {
1959    /* We cannot export suballocated BOs. */
1960    assert(iris_bo_is_real(bo));
1961
1962    iris_bo_mark_exported(bo);
1963
1964    return bo->gem_handle;
1965 }
1966
1967 int
1968 iris_bo_flink(struct iris_bo *bo, uint32_t *name)
1969 {
1970    struct iris_bufmgr *bufmgr = bo->bufmgr;
1971
1972    /* We cannot export suballocated BOs. */
1973    assert(iris_bo_is_real(bo));
1974
1975    if (!bo->real.global_name) {
1976       struct drm_gem_flink flink = { .handle = bo->gem_handle };
1977
1978       if (intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1979          return -errno;
1980
1981       simple_mtx_lock(&bufmgr->lock);
1982       if (!bo->real.global_name) {
1983          iris_bo_mark_exported_locked(bo);
1984          bo->real.global_name = flink.name;
1985          _mesa_hash_table_insert(bufmgr->name_table, &bo->real.global_name, bo);
1986       }
1987       simple_mtx_unlock(&bufmgr->lock);
1988    }
1989
1990    *name = bo->real.global_name;
1991    return 0;
1992 }
1993
1994 int
1995 iris_bo_export_gem_handle_for_device(struct iris_bo *bo, int drm_fd,
1996                                      uint32_t *out_handle)
1997 {
1998    /* We cannot export suballocated BOs. */
1999    assert(iris_bo_is_real(bo));
2000
2001    /* Only add the new GEM handle to the list of export if it belongs to a
2002     * different GEM device. Otherwise we might close the same buffer multiple
2003     * times.
2004     */
2005    struct iris_bufmgr *bufmgr = bo->bufmgr;
2006    int ret = os_same_file_description(drm_fd, bufmgr->fd);
2007    WARN_ONCE(ret < 0,
2008              "Kernel has no file descriptor comparison support: %s\n",
2009              strerror(errno));
2010    if (ret == 0) {
2011       *out_handle = iris_bo_export_gem_handle(bo);
2012       return 0;
2013    }
2014
2015    struct bo_export *export = calloc(1, sizeof(*export));
2016    if (!export)
2017       return -ENOMEM;
2018
2019    export->drm_fd = drm_fd;
2020
2021    int dmabuf_fd = -1;
2022    int err = iris_bo_export_dmabuf(bo, &dmabuf_fd);
2023    if (err) {
2024       free(export);
2025       return err;
2026    }
2027
2028    simple_mtx_lock(&bufmgr->lock);
2029    err = drmPrimeFDToHandle(drm_fd, dmabuf_fd, &export->gem_handle);
2030    close(dmabuf_fd);
2031    if (err) {
2032       simple_mtx_unlock(&bufmgr->lock);
2033       free(export);
2034       return err;
2035    }
2036
2037    bool found = false;
2038    list_for_each_entry(struct bo_export, iter, &bo->real.exports, link) {
2039       if (iter->drm_fd != drm_fd)
2040          continue;
2041       /* Here we assume that for a given DRM fd, we'll always get back the
2042        * same GEM handle for a given buffer.
2043        */
2044       assert(iter->gem_handle == export->gem_handle);
2045       free(export);
2046       export = iter;
2047       found = true;
2048       break;
2049    }
2050    if (!found)
2051       list_addtail(&export->link, &bo->real.exports);
2052
2053    simple_mtx_unlock(&bufmgr->lock);
2054
2055    *out_handle = export->gem_handle;
2056
2057    return 0;
2058 }
2059
2060 static void
2061 add_bucket(struct iris_bufmgr *bufmgr, int size, enum iris_heap heap)
2062 {
2063    int *num_buckets;
2064    struct bo_cache_bucket *buckets;
2065    bucket_info_for_heap(bufmgr, heap, &buckets, &num_buckets);
2066
2067    unsigned int i = (*num_buckets)++;
2068
2069    list_inithead(&buckets[i].head);
2070    buckets[i].size = size;
2071
2072    assert(bucket_for_size(bufmgr, size, heap, 0) == &buckets[i]);
2073    assert(bucket_for_size(bufmgr, size - 2048, heap, 0) == &buckets[i]);
2074    assert(bucket_for_size(bufmgr, size + 1, heap, 0) != &buckets[i]);
2075 }
2076
2077 static void
2078 init_cache_buckets(struct iris_bufmgr *bufmgr, enum iris_heap heap)
2079 {
2080    uint64_t size, cache_max_size = 64 * 1024 * 1024;
2081
2082    /* OK, so power of two buckets was too wasteful of memory.
2083     * Give 3 other sizes between each power of two, to hopefully
2084     * cover things accurately enough.  (The alternative is
2085     * probably to just go for exact matching of sizes, and assume
2086     * that for things like composited window resize the tiled
2087     * width/height alignment and rounding of sizes to pages will
2088     * get us useful cache hit rates anyway)
2089     */
2090    add_bucket(bufmgr, PAGE_SIZE, heap);
2091    add_bucket(bufmgr, PAGE_SIZE * 2, heap);
2092    add_bucket(bufmgr, PAGE_SIZE * 3, heap);
2093
2094    /* Initialize the linked lists for BO reuse cache. */
2095    for (size = 4 * PAGE_SIZE; size <= cache_max_size; size *= 2) {
2096       add_bucket(bufmgr, size, heap);
2097
2098       add_bucket(bufmgr, size + size * 1 / 4, heap);
2099       add_bucket(bufmgr, size + size * 2 / 4, heap);
2100       add_bucket(bufmgr, size + size * 3 / 4, heap);
2101    }
2102 }
2103
2104 static struct intel_buffer *
2105 intel_aux_map_buffer_alloc(void *driver_ctx, uint32_t size)
2106 {
2107    struct intel_buffer *buf = malloc(sizeof(struct intel_buffer));
2108    if (!buf)
2109       return NULL;
2110
2111    struct iris_bufmgr *bufmgr = (struct iris_bufmgr *)driver_ctx;
2112
2113    unsigned int page_size = getpagesize();
2114    size = MAX2(ALIGN(size, page_size), page_size);
2115
2116    struct iris_bo *bo = alloc_fresh_bo(bufmgr, size, 0);
2117    if (!bo) {
2118       free(buf);
2119       return NULL;
2120    }
2121
2122    simple_mtx_lock(&bufmgr->lock);
2123
2124    bo->address = vma_alloc(bufmgr, IRIS_MEMZONE_OTHER, bo->size, 64 * 1024);
2125    if (bo->address == 0ull)
2126       goto err_free;
2127
2128    if (!bufmgr->kmd_backend->gem_vm_bind(bo))
2129       goto err_vm_alloc;
2130
2131    simple_mtx_unlock(&bufmgr->lock);
2132
2133    bo->name = "aux-map";
2134    p_atomic_set(&bo->refcount, 1);
2135    bo->index = -1;
2136    bo->real.kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS | EXEC_OBJECT_PINNED |
2137                      EXEC_OBJECT_CAPTURE;
2138    bo->real.mmap_mode =
2139       bo->real.heap != IRIS_HEAP_SYSTEM_MEMORY ? IRIS_MMAP_WC : IRIS_MMAP_WB;
2140
2141    buf->driver_bo = bo;
2142    buf->gpu = bo->address;
2143    buf->gpu_end = buf->gpu + bo->size;
2144    buf->map = iris_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
2145    return buf;
2146
2147 err_vm_alloc:
2148    vma_free(bufmgr, bo->address, bo->size);
2149 err_free:
2150    free(buf);
2151    bo_free(bo);
2152    simple_mtx_unlock(&bufmgr->lock);
2153    return NULL;
2154 }
2155
2156 static void
2157 intel_aux_map_buffer_free(void *driver_ctx, struct intel_buffer *buffer)
2158 {
2159    iris_bo_unreference((struct iris_bo*)buffer->driver_bo);
2160    free(buffer);
2161 }
2162
2163 static struct intel_mapped_pinned_buffer_alloc aux_map_allocator = {
2164    .alloc = intel_aux_map_buffer_alloc,
2165    .free = intel_aux_map_buffer_free,
2166 };
2167
2168 static bool
2169 iris_bufmgr_get_meminfo(struct iris_bufmgr *bufmgr,
2170                         struct intel_device_info *devinfo)
2171 {
2172    bufmgr->sys.region = &devinfo->mem.sram.mem;
2173    bufmgr->sys.size = devinfo->mem.sram.mappable.size;
2174
2175    bufmgr->vram.region = &devinfo->mem.vram.mem;
2176    bufmgr->vram.size = devinfo->mem.vram.mappable.size;
2177
2178    return true;
2179 }
2180
2181 static bool
2182 iris_bufmgr_init_global_vm(struct iris_bufmgr *bufmgr)
2183 {
2184    switch (bufmgr->devinfo.kmd_type) {
2185    case INTEL_KMD_TYPE_I915:
2186       bufmgr->use_global_vm = iris_i915_init_global_vm(bufmgr, &bufmgr->global_vm_id);
2187       /* i915 don't require VM, so returning true even if use_global_vm is false */
2188       return true;
2189    case INTEL_KMD_TYPE_XE:
2190       bufmgr->use_global_vm = iris_xe_init_global_vm(bufmgr, &bufmgr->global_vm_id);
2191       /* Xe requires VM */
2192       return bufmgr->use_global_vm;
2193    default:
2194       unreachable("missing");
2195       return false;
2196    }
2197 }
2198
2199 /**
2200  * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
2201  * and manage map buffer objections.
2202  *
2203  * \param fd File descriptor of the opened DRM device.
2204  */
2205 static struct iris_bufmgr *
2206 iris_bufmgr_create(struct intel_device_info *devinfo, int fd, bool bo_reuse)
2207 {
2208    if (devinfo->gtt_size <= IRIS_MEMZONE_OTHER_START)
2209       return NULL;
2210
2211    struct iris_bufmgr *bufmgr = calloc(1, sizeof(*bufmgr));
2212    if (bufmgr == NULL)
2213       return NULL;
2214
2215    /* Handles to buffer objects belong to the device fd and are not
2216     * reference counted by the kernel.  If the same fd is used by
2217     * multiple parties (threads sharing the same screen bufmgr, or
2218     * even worse the same device fd passed to multiple libraries)
2219     * ownership of those handles is shared by those independent parties.
2220     *
2221     * Don't do this! Ensure that each library/bufmgr has its own device
2222     * fd so that its namespace does not clash with another.
2223     */
2224    bufmgr->fd = os_dupfd_cloexec(fd);
2225    if (bufmgr->fd == -1)
2226       goto error_dup;
2227
2228    p_atomic_set(&bufmgr->refcount, 1);
2229
2230    simple_mtx_init(&bufmgr->lock, mtx_plain);
2231    simple_mtx_init(&bufmgr->bo_deps_lock, mtx_plain);
2232
2233    list_inithead(&bufmgr->zombie_list);
2234
2235    bufmgr->devinfo = *devinfo;
2236    devinfo = &bufmgr->devinfo;
2237    bufmgr->bo_reuse = bo_reuse;
2238    iris_bufmgr_get_meminfo(bufmgr, devinfo);
2239    bufmgr->kmd_backend = iris_kmd_backend_get(devinfo->kmd_type);
2240
2241    struct intel_query_engine_info *engine_info;
2242    engine_info = intel_engine_get_info(bufmgr->fd, bufmgr->devinfo.kmd_type);
2243    if (!engine_info)
2244       goto error_engine_info;
2245    bufmgr->devinfo.has_compute_engine = intel_engines_count(engine_info,
2246                                                             INTEL_ENGINE_CLASS_COMPUTE);
2247    free(engine_info);
2248
2249    if (!iris_bufmgr_init_global_vm(bufmgr))
2250       goto error_init_vm;
2251
2252    STATIC_ASSERT(IRIS_MEMZONE_SHADER_START == 0ull);
2253    const uint64_t _4GB = 1ull << 32;
2254    const uint64_t _2GB = 1ul << 31;
2255
2256    /* The STATE_BASE_ADDRESS size field can only hold 1 page shy of 4GB */
2257    const uint64_t _4GB_minus_1 = _4GB - PAGE_SIZE;
2258
2259    util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_SHADER],
2260                       PAGE_SIZE, _4GB_minus_1 - PAGE_SIZE);
2261    util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_BINDER],
2262                       IRIS_MEMZONE_BINDER_START + IRIS_SCRATCH_ZONE_SIZE,
2263                       IRIS_BINDER_ZONE_SIZE - IRIS_SCRATCH_ZONE_SIZE);
2264    util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_SCRATCH],
2265                       IRIS_MEMZONE_SCRATCH_START, IRIS_SCRATCH_ZONE_SIZE);
2266    util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_SURFACE],
2267                       IRIS_MEMZONE_SURFACE_START, _4GB_minus_1 -
2268                       IRIS_BINDER_ZONE_SIZE - IRIS_SCRATCH_ZONE_SIZE);
2269
2270    /* Wa_2209859288: the Tigerlake PRM's workarounds volume says:
2271     *
2272     *    "PSDunit is dropping MSB of the blend state pointer from SD FIFO"
2273     *    "Limit the Blend State Pointer to < 2G"
2274     *
2275     * We restrict the dynamic state pool to 2GB so that we don't ever get a
2276     * BLEND_STATE pointer with the MSB set.  We aren't likely to need the
2277     * full 4GB for dynamic state anyway.
2278     */
2279    const uint64_t dynamic_pool_size =
2280       (devinfo->ver >= 12 ? _2GB : _4GB_minus_1) - IRIS_BORDER_COLOR_POOL_SIZE;
2281    util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_DYNAMIC],
2282                       IRIS_MEMZONE_DYNAMIC_START + IRIS_BORDER_COLOR_POOL_SIZE,
2283                       dynamic_pool_size);
2284
2285    /* Leave the last 4GB out of the high vma range, so that no state
2286     * base address + size can overflow 48 bits.
2287     */
2288    util_vma_heap_init(&bufmgr->vma_allocator[IRIS_MEMZONE_OTHER],
2289                       IRIS_MEMZONE_OTHER_START,
2290                       (devinfo->gtt_size - _4GB) - IRIS_MEMZONE_OTHER_START);
2291
2292    init_cache_buckets(bufmgr, IRIS_HEAP_SYSTEM_MEMORY);
2293    init_cache_buckets(bufmgr, IRIS_HEAP_DEVICE_LOCAL);
2294    init_cache_buckets(bufmgr, IRIS_HEAP_DEVICE_LOCAL_PREFERRED);
2295
2296    unsigned min_slab_order = 8;  /* 256 bytes */
2297    unsigned max_slab_order = 20; /* 1 MB (slab size = 2 MB) */
2298    unsigned num_slab_orders_per_allocator =
2299       (max_slab_order - min_slab_order) / NUM_SLAB_ALLOCATORS;
2300
2301    /* Divide the size order range among slab managers. */
2302    for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
2303       unsigned min_order = min_slab_order;
2304       unsigned max_order =
2305          MIN2(min_order + num_slab_orders_per_allocator, max_slab_order);
2306
2307       if (!pb_slabs_init(&bufmgr->bo_slabs[i], min_order, max_order,
2308                          IRIS_HEAP_MAX, true, bufmgr,
2309                          iris_can_reclaim_slab,
2310                          iris_slab_alloc,
2311                          (void *) iris_slab_free)) {
2312          goto error_slabs_init;
2313       }
2314       min_slab_order = max_order + 1;
2315    }
2316
2317    bufmgr->name_table =
2318       _mesa_hash_table_create(NULL, _mesa_hash_uint, _mesa_key_uint_equal);
2319    bufmgr->handle_table =
2320       _mesa_hash_table_create(NULL, _mesa_hash_uint, _mesa_key_uint_equal);
2321
2322    if (devinfo->has_aux_map) {
2323       bufmgr->aux_map_ctx = intel_aux_map_init(bufmgr, &aux_map_allocator,
2324                                                devinfo);
2325       assert(bufmgr->aux_map_ctx);
2326    }
2327
2328    iris_init_border_color_pool(bufmgr, &bufmgr->border_color_pool);
2329
2330    return bufmgr;
2331
2332 error_slabs_init:
2333    for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
2334       if (!bufmgr->bo_slabs[i].groups)
2335          break;
2336
2337       pb_slabs_deinit(&bufmgr->bo_slabs[i]);
2338    }
2339    iris_bufmgr_destroy_global_vm(bufmgr);
2340 error_init_vm:
2341 error_engine_info:
2342    close(bufmgr->fd);
2343 error_dup:
2344    free(bufmgr);
2345    return NULL;
2346 }
2347
2348 static struct iris_bufmgr *
2349 iris_bufmgr_ref(struct iris_bufmgr *bufmgr)
2350 {
2351    p_atomic_inc(&bufmgr->refcount);
2352    return bufmgr;
2353 }
2354
2355 void
2356 iris_bufmgr_unref(struct iris_bufmgr *bufmgr)
2357 {
2358    simple_mtx_lock(&global_bufmgr_list_mutex);
2359    if (p_atomic_dec_zero(&bufmgr->refcount)) {
2360       list_del(&bufmgr->link);
2361       iris_bufmgr_destroy(bufmgr);
2362    }
2363    simple_mtx_unlock(&global_bufmgr_list_mutex);
2364 }
2365
2366 /** Returns a new unique id, to be used by screens. */
2367 int
2368 iris_bufmgr_create_screen_id(struct iris_bufmgr *bufmgr)
2369 {
2370    return p_atomic_inc_return(&bufmgr->next_screen_id) - 1;
2371 }
2372
2373 /**
2374  * Gets an already existing GEM buffer manager or create a new one.
2375  *
2376  * \param fd File descriptor of the opened DRM device.
2377  */
2378 struct iris_bufmgr *
2379 iris_bufmgr_get_for_fd(int fd, bool bo_reuse)
2380 {
2381    struct intel_device_info devinfo;
2382    struct stat st;
2383
2384    if (fstat(fd, &st))
2385       return NULL;
2386
2387    struct iris_bufmgr *bufmgr = NULL;
2388
2389    simple_mtx_lock(&global_bufmgr_list_mutex);
2390    list_for_each_entry(struct iris_bufmgr, iter_bufmgr, &global_bufmgr_list, link) {
2391       struct stat iter_st;
2392       if (fstat(iter_bufmgr->fd, &iter_st))
2393          continue;
2394
2395       if (st.st_rdev == iter_st.st_rdev) {
2396          assert(iter_bufmgr->bo_reuse == bo_reuse);
2397          bufmgr = iris_bufmgr_ref(iter_bufmgr);
2398          goto unlock;
2399       }
2400    }
2401
2402    if (!intel_get_device_info_from_fd(fd, &devinfo))
2403       return NULL;
2404
2405    if (devinfo.ver < 8 || devinfo.platform == INTEL_PLATFORM_CHV)
2406       return NULL;
2407
2408    bufmgr = iris_bufmgr_create(&devinfo, fd, bo_reuse);
2409    if (bufmgr)
2410       list_addtail(&bufmgr->link, &global_bufmgr_list);
2411
2412  unlock:
2413    simple_mtx_unlock(&global_bufmgr_list_mutex);
2414
2415    return bufmgr;
2416 }
2417
2418 int
2419 iris_bufmgr_get_fd(struct iris_bufmgr *bufmgr)
2420 {
2421    return bufmgr->fd;
2422 }
2423
2424 void*
2425 iris_bufmgr_get_aux_map_context(struct iris_bufmgr *bufmgr)
2426 {
2427    return bufmgr->aux_map_ctx;
2428 }
2429
2430 simple_mtx_t *
2431 iris_bufmgr_get_bo_deps_lock(struct iris_bufmgr *bufmgr)
2432 {
2433    return &bufmgr->bo_deps_lock;
2434 }
2435
2436 struct iris_border_color_pool *
2437 iris_bufmgr_get_border_color_pool(struct iris_bufmgr *bufmgr)
2438 {
2439    return &bufmgr->border_color_pool;
2440 }
2441
2442 uint64_t
2443 iris_bufmgr_vram_size(struct iris_bufmgr *bufmgr)
2444 {
2445    return bufmgr->vram.size;
2446 }
2447
2448 uint64_t
2449 iris_bufmgr_sram_size(struct iris_bufmgr *bufmgr)
2450 {
2451    return bufmgr->sys.size;
2452 }
2453
2454 const struct intel_device_info *
2455 iris_bufmgr_get_device_info(struct iris_bufmgr *bufmgr)
2456 {
2457    return &bufmgr->devinfo;
2458 }
2459
2460 const struct iris_kmd_backend *
2461 iris_bufmgr_get_kernel_driver_backend(struct iris_bufmgr *bufmgr)
2462 {
2463    return bufmgr->kmd_backend;
2464 }
2465
2466 uint32_t
2467 iris_bufmgr_get_global_vm_id(struct iris_bufmgr *bufmgr)
2468 {
2469    return bufmgr->global_vm_id;
2470 }
2471
2472 bool
2473 iris_bufmgr_use_global_vm_id(struct iris_bufmgr *bufmgr)
2474 {
2475    return bufmgr->use_global_vm;
2476 }