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