xref: /aosp_15_r20/external/mesa3d/src/gallium/drivers/crocus/crocus_bufmgr.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
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 crocus_bufmgr.c
25  *
26  * The crocus 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 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37 
38 #include <xf86drm.h>
39 #include <util/u_atomic.h>
40 #include <fcntl.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <assert.h>
46 #include <sys/ioctl.h>
47 #include <sys/mman.h>
48 #include <sys/stat.h>
49 #include <sys/types.h>
50 #include <stdbool.h>
51 #include <time.h>
52 
53 #include "errno.h"
54 #include "common/intel_mem.h"
55 #include "dev/intel_debug.h"
56 #include "common/intel_gem.h"
57 #include "dev/intel_device_info.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 "crocus_bufmgr.h"
66 #include "crocus_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 /**
80  * For debugging purposes, this returns a time in seconds.
81  */
82 static double
get_time(void)83 get_time(void)
84 {
85    struct timespec tp;
86 
87    clock_gettime(CLOCK_MONOTONIC, &tp);
88 
89    return tp.tv_sec + tp.tv_nsec / 1000000000.0;
90 }
91 
92 /* VALGRIND_FREELIKE_BLOCK unfortunately does not actually undo the earlier
93  * VALGRIND_MALLOCLIKE_BLOCK but instead leaves vg convinced the memory is
94  * leaked. All because it does not call VG(cli_free) from its
95  * VG_USERREQ__FREELIKE_BLOCK handler. Instead of treating the memory like
96  * and allocation, we mark it available for use upon mmapping and remove
97  * it upon unmapping.
98  */
99 #define VG_DEFINED(ptr, size) VG(VALGRIND_MAKE_MEM_DEFINED(ptr, size))
100 #define VG_NOACCESS(ptr, size) VG(VALGRIND_MAKE_MEM_NOACCESS(ptr, size))
101 
102 #ifndef PAGE_SIZE
103 #define PAGE_SIZE 4096
104 #endif
105 
106 #define WARN_ONCE(cond, fmt...) do {                            \
107    if (unlikely(cond)) {                                        \
108       static bool _warned = false;                              \
109       if (!_warned) {                                           \
110          fprintf(stderr, "WARNING: ");                          \
111          fprintf(stderr, fmt);                                  \
112          _warned = true;                                        \
113       }                                                         \
114    }                                                            \
115 } while (0)
116 
117 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
118 
119 struct bo_cache_bucket {
120    /** List of cached BOs. */
121    struct list_head head;
122 
123    /** Size of this bucket, in bytes. */
124    uint64_t size;
125 };
126 
127 struct bo_export {
128    /** File descriptor associated with a handle export. */
129    int drm_fd;
130 
131    /** GEM handle in drm_fd */
132    uint32_t gem_handle;
133 
134    struct list_head link;
135 };
136 
137 struct crocus_bufmgr {
138    /**
139     * List into the list of bufmgr.
140     */
141    struct list_head link;
142 
143    uint32_t refcount;
144 
145    int fd;
146 
147    simple_mtx_t lock;
148 
149    /** Array of lists of cached gem objects of power-of-two sizes */
150    struct bo_cache_bucket cache_bucket[14 * 4];
151    int num_buckets;
152    time_t time;
153 
154    struct hash_table *name_table;
155    struct hash_table *handle_table;
156 
157    /**
158     * List of BOs which we've effectively freed, but are hanging on to
159     * until they're idle before closing and returning the VMA.
160     */
161    struct list_head zombie_list;
162 
163    bool has_llc:1;
164    bool has_mmap_offset:1;
165    bool has_tiling_uapi:1;
166    bool bo_reuse:1;
167 };
168 
169 static simple_mtx_t global_bufmgr_list_mutex = SIMPLE_MTX_INITIALIZER;
170 static struct list_head global_bufmgr_list = {
171    .next = &global_bufmgr_list,
172    .prev = &global_bufmgr_list,
173 };
174 
175 static int bo_set_tiling_internal(struct crocus_bo *bo, uint32_t tiling_mode,
176                                   uint32_t stride);
177 
178 static void bo_free(struct crocus_bo *bo);
179 
180 static uint32_t
key_hash_uint(const void * key)181 key_hash_uint(const void *key)
182 {
183    return _mesa_hash_data(key, 4);
184 }
185 
186 static bool
key_uint_equal(const void * a,const void * b)187 key_uint_equal(const void *a, const void *b)
188 {
189    return *((unsigned *) a) == *((unsigned *) b);
190 }
191 
192 static struct crocus_bo *
find_and_ref_external_bo(struct hash_table * ht,unsigned int key)193 find_and_ref_external_bo(struct hash_table *ht, unsigned int key)
194 {
195    struct hash_entry *entry = _mesa_hash_table_search(ht, &key);
196    struct crocus_bo *bo = entry ? entry->data : NULL;
197 
198    if (bo) {
199       assert(bo->external);
200       assert(!bo->reusable);
201 
202       /* Being non-reusable, the BO cannot be in the cache lists, but it
203        * may be in the zombie list if it had reached zero references, but
204        * we hadn't yet closed it...and then reimported the same BO.  If it
205        * is, then remove it since it's now been resurrected.
206        */
207       if (bo->head.prev || bo->head.next)
208          list_del(&bo->head);
209 
210       crocus_bo_reference(bo);
211    }
212 
213    return bo;
214 }
215 
216 /**
217  * This function finds the correct bucket fit for the input size.
218  * The function works with O(1) complexity when the requested size
219  * was queried instead of iterating the size through all the buckets.
220  */
221 static struct bo_cache_bucket *
bucket_for_size(struct crocus_bufmgr * bufmgr,uint64_t size)222 bucket_for_size(struct crocus_bufmgr *bufmgr, uint64_t size)
223 {
224    /* Calculating the pages and rounding up to the page size. */
225    const unsigned pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
226 
227    /* Row  Bucket sizes    clz((x-1) | 3)   Row    Column
228     *        in pages                      stride   size
229     *   0:   1  2  3  4 -> 30 30 30 30        4       1
230     *   1:   5  6  7  8 -> 29 29 29 29        4       1
231     *   2:  10 12 14 16 -> 28 28 28 28        8       2
232     *   3:  20 24 28 32 -> 27 27 27 27       16       4
233     */
234    const unsigned row = 30 - __builtin_clz((pages - 1) | 3);
235    const unsigned row_max_pages = 4 << row;
236 
237    /* The '& ~2' is the special case for row 1. In row 1, max pages /
238     * 2 is 2, but the previous row maximum is zero (because there is
239     * no previous row). All row maximum sizes are power of 2, so that
240     * is the only case where that bit will be set.
241     */
242    const unsigned prev_row_max_pages = (row_max_pages / 2) & ~2;
243    int col_size_log2 = row - 1;
244    col_size_log2 += (col_size_log2 < 0);
245 
246    const unsigned col = (pages - prev_row_max_pages +
247                          ((1 << col_size_log2) - 1)) >> col_size_log2;
248 
249    /* Calculating the index based on the row and column. */
250    const unsigned index = (row * 4) + (col - 1);
251 
252    return (index < bufmgr->num_buckets) ?
253           &bufmgr->cache_bucket[index] : NULL;
254 }
255 
256 
257 int
crocus_bo_busy(struct crocus_bo * bo)258 crocus_bo_busy(struct crocus_bo *bo)
259 {
260    struct crocus_bufmgr *bufmgr = bo->bufmgr;
261    struct drm_i915_gem_busy busy = { .handle = bo->gem_handle };
262 
263    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_BUSY, &busy);
264    if (ret == 0) {
265       bo->idle = !busy.busy;
266       return busy.busy;
267    }
268    return false;
269 }
270 
271 int
crocus_bo_madvise(struct crocus_bo * bo,int state)272 crocus_bo_madvise(struct crocus_bo *bo, int state)
273 {
274    struct drm_i915_gem_madvise madv = {
275       .handle = bo->gem_handle,
276       .madv = state,
277       .retained = 1,
278    };
279 
280    intel_ioctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_MADVISE, &madv);
281 
282    return madv.retained;
283 }
284 
285 static struct crocus_bo *
bo_calloc(void)286 bo_calloc(void)
287 {
288    struct crocus_bo *bo = calloc(1, sizeof(*bo));
289    if (!bo)
290       return NULL;
291 
292    list_inithead(&bo->exports);
293    bo->hash = _mesa_hash_pointer(bo);
294    return bo;
295 }
296 
297 static struct crocus_bo *
alloc_bo_from_cache(struct crocus_bufmgr * bufmgr,struct bo_cache_bucket * bucket,uint32_t alignment,unsigned flags)298 alloc_bo_from_cache(struct crocus_bufmgr *bufmgr,
299                     struct bo_cache_bucket *bucket,
300                     uint32_t alignment,
301                     unsigned flags)
302 {
303    if (!bucket)
304       return NULL;
305 
306    struct crocus_bo *bo = NULL;
307 
308    list_for_each_entry_safe(struct crocus_bo, cur, &bucket->head, head) {
309       /* If the last BO in the cache is busy, there are no idle BOs.  Bail,
310        * either falling back to a non-matching memzone, or if that fails,
311        * allocating a fresh buffer.
312        */
313       if (crocus_bo_busy(cur))
314          return NULL;
315 
316       list_del(&cur->head);
317 
318       /* Tell the kernel we need this BO.  If it still exists, we're done! */
319       if (crocus_bo_madvise(cur, I915_MADV_WILLNEED)) {
320          bo = cur;
321          break;
322       }
323 
324       /* This BO was purged, throw it out and keep looking. */
325       bo_free(cur);
326    }
327 
328    if (!bo)
329       return NULL;
330 
331    /* Zero the contents if necessary.  If this fails, fall back to
332     * allocating a fresh BO, which will always be zeroed by the kernel.
333     */
334    if (flags & BO_ALLOC_ZEROED) {
335       void *map = crocus_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
336       if (map) {
337          memset(map, 0, bo->size);
338       } else {
339          bo_free(bo);
340          return NULL;
341       }
342    }
343 
344    return bo;
345 }
346 
347 static struct crocus_bo *
alloc_fresh_bo(struct crocus_bufmgr * bufmgr,uint64_t bo_size)348 alloc_fresh_bo(struct crocus_bufmgr *bufmgr, uint64_t bo_size)
349 {
350    struct crocus_bo *bo = bo_calloc();
351    if (!bo)
352       return NULL;
353 
354    struct drm_i915_gem_create create = { .size = bo_size };
355 
356    /* All new BOs we get from the kernel are zeroed, so we don't need to
357     * worry about that here.
358     */
359    if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CREATE, &create) != 0) {
360       free(bo);
361       return NULL;
362    }
363 
364    bo->gem_handle = create.handle;
365    bo->bufmgr = bufmgr;
366    bo->size = bo_size;
367    bo->idle = true;
368    bo->tiling_mode = I915_TILING_NONE;
369    bo->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
370    bo->stride = 0;
371 
372    /* Calling set_domain() will allocate pages for the BO outside of the
373     * struct mutex lock in the kernel, which is more efficient than waiting
374     * to create them during the first execbuf that uses the BO.
375     */
376    struct drm_i915_gem_set_domain sd = {
377       .handle = bo->gem_handle,
378       .read_domains = I915_GEM_DOMAIN_CPU,
379       .write_domain = 0,
380    };
381 
382    if (intel_ioctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd) != 0) {
383       bo_free(bo);
384       return NULL;
385    }
386 
387    return bo;
388 }
389 
390 static struct crocus_bo *
bo_alloc_internal(struct crocus_bufmgr * bufmgr,const char * name,uint64_t size,uint32_t alignment,unsigned flags,uint32_t tiling_mode,uint32_t stride)391 bo_alloc_internal(struct crocus_bufmgr *bufmgr,
392                   const char *name,
393                   uint64_t size,
394                   uint32_t alignment,
395                   unsigned flags,
396                   uint32_t tiling_mode,
397                   uint32_t stride)
398 {
399    struct crocus_bo *bo;
400    unsigned int page_size = getpagesize();
401    struct bo_cache_bucket *bucket = bucket_for_size(bufmgr, size);
402 
403    /* Round the size up to the bucket size, or if we don't have caching
404     * at this size, a multiple of the page size.
405     */
406    uint64_t bo_size =
407       bucket ? bucket->size : MAX2(align64(size, page_size), page_size);
408 
409    simple_mtx_lock(&bufmgr->lock);
410 
411    /* Get a buffer out of the cache if available.  First, we try to find
412     * one with a matching memory zone so we can avoid reallocating VMA.
413     */
414    bo = alloc_bo_from_cache(bufmgr, bucket, alignment, flags);
415 
416    simple_mtx_unlock(&bufmgr->lock);
417 
418    if (!bo) {
419       bo = alloc_fresh_bo(bufmgr, bo_size);
420       if (!bo)
421          return NULL;
422    }
423 
424    if (bo_set_tiling_internal(bo, tiling_mode, stride))
425       goto err_free;
426 
427    bo->name = name;
428    p_atomic_set(&bo->refcount, 1);
429    bo->reusable = bucket && bufmgr->bo_reuse;
430    bo->cache_coherent = bufmgr->has_llc;
431    bo->index = -1;
432    bo->kflags = 0;
433 
434    if (flags & BO_ALLOC_SCANOUT)
435       bo->scanout = 1;
436 
437    if ((flags & BO_ALLOC_COHERENT) && !bo->cache_coherent) {
438       struct drm_i915_gem_caching arg = {
439          .handle = bo->gem_handle,
440          .caching = 1,
441       };
442       if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_CACHING, &arg) == 0) {
443          bo->cache_coherent = true;
444          bo->reusable = false;
445       }
446    }
447 
448    DBG("bo_create: buf %d (%s) %llub\n", bo->gem_handle,
449        bo->name, (unsigned long long) size);
450 
451    return bo;
452 
453 err_free:
454    bo_free(bo);
455    return NULL;
456 }
457 
458 struct crocus_bo *
crocus_bo_alloc(struct crocus_bufmgr * bufmgr,const char * name,uint64_t size)459 crocus_bo_alloc(struct crocus_bufmgr *bufmgr,
460                 const char *name,
461                 uint64_t size)
462 {
463    return bo_alloc_internal(bufmgr, name, size, 1,
464                             0, I915_TILING_NONE, 0);
465 }
466 
467 struct crocus_bo *
crocus_bo_alloc_tiled(struct crocus_bufmgr * bufmgr,const char * name,uint64_t size,uint32_t alignment,uint32_t tiling_mode,uint32_t pitch,unsigned flags)468 crocus_bo_alloc_tiled(struct crocus_bufmgr *bufmgr, const char *name,
469                       uint64_t size, uint32_t alignment,
470                       uint32_t tiling_mode, uint32_t pitch, unsigned flags)
471 {
472    return bo_alloc_internal(bufmgr, name, size, alignment,
473                             flags, tiling_mode, pitch);
474 }
475 
476 struct crocus_bo *
crocus_bo_create_userptr(struct crocus_bufmgr * bufmgr,const char * name,void * ptr,size_t size)477 crocus_bo_create_userptr(struct crocus_bufmgr *bufmgr, const char *name,
478                          void *ptr, size_t size)
479 {
480    struct crocus_bo *bo;
481 
482    bo = bo_calloc();
483    if (!bo)
484       return NULL;
485 
486    struct drm_i915_gem_userptr arg = {
487       .user_ptr = (uintptr_t)ptr,
488       .user_size = size,
489    };
490    if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_USERPTR, &arg))
491       goto err_free;
492    bo->gem_handle = arg.handle;
493 
494    /* Check the buffer for validity before we try and use it in a batch */
495    struct drm_i915_gem_set_domain sd = {
496       .handle = bo->gem_handle,
497       .read_domains = I915_GEM_DOMAIN_CPU,
498    };
499    if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd))
500       goto err_close;
501 
502    bo->name = name;
503    bo->size = size;
504    bo->map_cpu = ptr;
505 
506    bo->bufmgr = bufmgr;
507    bo->kflags = 0;
508 
509    p_atomic_set(&bo->refcount, 1);
510    bo->userptr = true;
511    bo->cache_coherent = true;
512    bo->index = -1;
513    bo->idle = true;
514 
515    return bo;
516 
517 err_close:
518    intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &bo->gem_handle);
519 err_free:
520    free(bo);
521    return NULL;
522 }
523 
524 /**
525  * Returns a crocus_bo wrapping the given buffer object handle.
526  *
527  * This can be used when one application needs to pass a buffer object
528  * to another.
529  */
530 struct crocus_bo *
crocus_bo_gem_create_from_name(struct crocus_bufmgr * bufmgr,const char * name,unsigned int handle)531 crocus_bo_gem_create_from_name(struct crocus_bufmgr *bufmgr,
532                                const char *name, unsigned int handle)
533 {
534    struct crocus_bo *bo;
535 
536    /* At the moment most applications only have a few named bo.
537     * For instance, in a DRI client only the render buffers passed
538     * between X and the client are named. And since X returns the
539     * alternating names for the front/back buffer a linear search
540     * provides a sufficiently fast match.
541     */
542    simple_mtx_lock(&bufmgr->lock);
543    bo = find_and_ref_external_bo(bufmgr->name_table, handle);
544    if (bo)
545       goto out;
546 
547    struct drm_gem_open open_arg = { .name = handle };
548    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
549    if (ret != 0) {
550       DBG("Couldn't reference %s handle 0x%08x: %s\n",
551           name, handle, strerror(errno));
552       bo = NULL;
553       goto out;
554    }
555    /* Now see if someone has used a prime handle to get this
556     * object from the kernel before by looking through the list
557     * again for a matching gem_handle
558     */
559    bo = find_and_ref_external_bo(bufmgr->handle_table, open_arg.handle);
560    if (bo)
561       goto out;
562 
563    bo = bo_calloc();
564    if (!bo)
565       goto out;
566 
567    p_atomic_set(&bo->refcount, 1);
568 
569    bo->size = open_arg.size;
570    bo->gtt_offset = 0;
571    bo->bufmgr = bufmgr;
572    bo->gem_handle = open_arg.handle;
573    bo->name = name;
574    bo->global_name = handle;
575    bo->reusable = false;
576    bo->external = true;
577    bo->kflags = 0;
578 
579    _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
580    _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
581 
582    struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
583    ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling);
584    if (ret != 0)
585       goto err_unref;
586 
587    bo->tiling_mode = get_tiling.tiling_mode;
588    bo->swizzle_mode = get_tiling.swizzle_mode;
589    /* XXX stride is unknown */
590    DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
591 
592 out:
593    simple_mtx_unlock(&bufmgr->lock);
594    return bo;
595 
596 err_unref:
597    bo_free(bo);
598    simple_mtx_unlock(&bufmgr->lock);
599    return NULL;
600 }
601 
602 static void
bo_close(struct crocus_bo * bo)603 bo_close(struct crocus_bo *bo)
604 {
605    struct crocus_bufmgr *bufmgr = bo->bufmgr;
606 
607    if (bo->external) {
608       struct hash_entry *entry;
609 
610       if (bo->global_name) {
611          entry = _mesa_hash_table_search(bufmgr->name_table, &bo->global_name);
612          _mesa_hash_table_remove(bufmgr->name_table, entry);
613       }
614 
615       entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
616       _mesa_hash_table_remove(bufmgr->handle_table, entry);
617 
618       list_for_each_entry_safe(struct bo_export, export, &bo->exports, link) {
619          struct drm_gem_close close = { .handle = export->gem_handle };
620          intel_ioctl(export->drm_fd, DRM_IOCTL_GEM_CLOSE, &close);
621 
622          list_del(&export->link);
623          free(export);
624       }
625    } else {
626       assert(list_is_empty(&bo->exports));
627    }
628 
629    /* Close this object */
630    struct drm_gem_close close = { .handle = bo->gem_handle };
631    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
632    if (ret != 0) {
633       DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
634           bo->gem_handle, bo->name, strerror(errno));
635    }
636 
637    free(bo);
638 }
639 
640 static void
bo_free(struct crocus_bo * bo)641 bo_free(struct crocus_bo *bo)
642 {
643    struct crocus_bufmgr *bufmgr = bo->bufmgr;
644 
645    if (bo->map_cpu && !bo->userptr) {
646       VG_NOACCESS(bo->map_cpu, bo->size);
647       munmap(bo->map_cpu, bo->size);
648    }
649    if (bo->map_wc) {
650       VG_NOACCESS(bo->map_wc, bo->size);
651       munmap(bo->map_wc, bo->size);
652    }
653    if (bo->map_gtt) {
654       VG_NOACCESS(bo->map_gtt, bo->size);
655       munmap(bo->map_gtt, bo->size);
656    }
657 
658    if (bo->idle) {
659       bo_close(bo);
660    } else {
661       /* Defer closing the GEM BO and returning the VMA for reuse until the
662        * BO is idle.  Just move it to the dead list for now.
663        */
664       list_addtail(&bo->head, &bufmgr->zombie_list);
665    }
666 }
667 
668 /** Frees all cached buffers significantly older than @time. */
669 static void
cleanup_bo_cache(struct crocus_bufmgr * bufmgr,time_t time)670 cleanup_bo_cache(struct crocus_bufmgr *bufmgr, time_t time)
671 {
672    int i;
673 
674    if (bufmgr->time == time)
675       return;
676 
677    for (i = 0; i < bufmgr->num_buckets; i++) {
678       struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
679 
680       list_for_each_entry_safe(struct crocus_bo, bo, &bucket->head, head) {
681          if (time - bo->free_time <= 1)
682             break;
683 
684          list_del(&bo->head);
685 
686          bo_free(bo);
687       }
688    }
689 
690    list_for_each_entry_safe(struct crocus_bo, bo, &bufmgr->zombie_list, head) {
691       /* Stop once we reach a busy BO - all others past this point were
692        * freed more recently so are likely also busy.
693        */
694       if (!bo->idle && crocus_bo_busy(bo))
695          break;
696 
697       list_del(&bo->head);
698       bo_close(bo);
699    }
700 
701    bufmgr->time = time;
702 }
703 
704 static void
bo_unreference_final(struct crocus_bo * bo,time_t time)705 bo_unreference_final(struct crocus_bo *bo, time_t time)
706 {
707    struct crocus_bufmgr *bufmgr = bo->bufmgr;
708    struct bo_cache_bucket *bucket;
709 
710    DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
711 
712    bucket = NULL;
713    if (bo->reusable)
714       bucket = bucket_for_size(bufmgr, bo->size);
715    /* Put the buffer into our internal cache for reuse if we can. */
716    if (bucket && crocus_bo_madvise(bo, I915_MADV_DONTNEED)) {
717       bo->free_time = time;
718       bo->name = NULL;
719 
720       list_addtail(&bo->head, &bucket->head);
721    } else {
722       bo_free(bo);
723    }
724 }
725 
726 void
__crocus_bo_unreference(struct crocus_bo * bo)727 __crocus_bo_unreference(struct crocus_bo *bo)
728 {
729    struct crocus_bufmgr *bufmgr = bo->bufmgr;
730    struct timespec time;
731 
732    clock_gettime(CLOCK_MONOTONIC, &time);
733 
734    simple_mtx_lock(&bufmgr->lock);
735 
736    if (p_atomic_dec_zero(&bo->refcount)) {
737       bo_unreference_final(bo, time.tv_sec);
738       cleanup_bo_cache(bufmgr, time.tv_sec);
739    }
740 
741    simple_mtx_unlock(&bufmgr->lock);
742 }
743 
744 static void
bo_wait_with_stall_warning(struct util_debug_callback * dbg,struct crocus_bo * bo,const char * action)745 bo_wait_with_stall_warning(struct util_debug_callback *dbg,
746                            struct crocus_bo *bo,
747                            const char *action)
748 {
749    bool busy = dbg && !bo->idle;
750    double elapsed = unlikely(busy) ? -get_time() : 0.0;
751 
752    crocus_bo_wait_rendering(bo);
753 
754    if (unlikely(busy)) {
755       elapsed += get_time();
756       if (elapsed > 1e-5) /* 0.01ms */ {
757          perf_debug(dbg, "%s a busy \"%s\" BO stalled and took %.03f ms.\n",
758                     action, bo->name, elapsed * 1000);
759       }
760    }
761 }
762 
763 static void
print_flags(unsigned flags)764 print_flags(unsigned flags)
765 {
766    if (flags & MAP_READ)
767       DBG("READ ");
768    if (flags & MAP_WRITE)
769       DBG("WRITE ");
770    if (flags & MAP_ASYNC)
771       DBG("ASYNC ");
772    if (flags & MAP_PERSISTENT)
773       DBG("PERSISTENT ");
774    if (flags & MAP_COHERENT)
775       DBG("COHERENT ");
776    if (flags & MAP_RAW)
777       DBG("RAW ");
778    DBG("\n");
779 }
780 
781 static void *
crocus_bo_gem_mmap_legacy(struct util_debug_callback * dbg,struct crocus_bo * bo,bool wc)782 crocus_bo_gem_mmap_legacy(struct util_debug_callback *dbg,
783                           struct crocus_bo *bo, bool wc)
784 {
785    struct crocus_bufmgr *bufmgr = bo->bufmgr;
786 
787    struct drm_i915_gem_mmap mmap_arg = {
788       .handle = bo->gem_handle,
789       .size = bo->size,
790       .flags = wc ? I915_MMAP_WC : 0,
791    };
792 
793    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
794    if (ret != 0) {
795       DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
796           __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
797       return NULL;
798    }
799    void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
800 
801    return map;
802 }
803 
804 static void *
crocus_bo_gem_mmap_offset(struct util_debug_callback * dbg,struct crocus_bo * bo,bool wc)805 crocus_bo_gem_mmap_offset(struct util_debug_callback *dbg, struct crocus_bo *bo,
806                           bool wc)
807 {
808    struct crocus_bufmgr *bufmgr = bo->bufmgr;
809 
810    struct drm_i915_gem_mmap_offset mmap_arg = {
811       .handle = bo->gem_handle,
812       .flags = wc ? I915_MMAP_OFFSET_WC : I915_MMAP_OFFSET_WB,
813    };
814 
815    /* Get the fake offset back */
816    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_OFFSET, &mmap_arg);
817    if (ret != 0) {
818       DBG("%s:%d: Error preparing buffer %d (%s): %s .\n",
819           __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
820       return NULL;
821    }
822 
823    /* And map it */
824    void *map = mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED,
825                     bufmgr->fd, mmap_arg.offset);
826    if (map == MAP_FAILED) {
827       DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
828           __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
829       return NULL;
830    }
831 
832    return map;
833 }
834 
835 static void *
crocus_bo_gem_mmap(struct util_debug_callback * dbg,struct crocus_bo * bo,bool wc)836 crocus_bo_gem_mmap(struct util_debug_callback *dbg, struct crocus_bo *bo, bool wc)
837 {
838    struct crocus_bufmgr *bufmgr = bo->bufmgr;
839 
840    if (bufmgr->has_mmap_offset)
841       return crocus_bo_gem_mmap_offset(dbg, bo, wc);
842    else
843       return crocus_bo_gem_mmap_legacy(dbg, bo, wc);
844 }
845 
846 static void *
crocus_bo_map_cpu(struct util_debug_callback * dbg,struct crocus_bo * bo,unsigned flags)847 crocus_bo_map_cpu(struct util_debug_callback *dbg,
848                   struct crocus_bo *bo, unsigned flags)
849 {
850    /* We disallow CPU maps for writing to non-coherent buffers, as the
851     * CPU map can become invalidated when a batch is flushed out, which
852     * can happen at unpredictable times.  You should use WC maps instead.
853     */
854    assert(bo->cache_coherent || !(flags & MAP_WRITE));
855 
856    if (!bo->map_cpu) {
857       DBG("crocus_bo_map_cpu: %d (%s)\n", bo->gem_handle, bo->name);
858 
859       void *map = crocus_bo_gem_mmap(dbg, bo, false);
860       if (!map) {
861          return NULL;
862       }
863 
864       VG_DEFINED(map, bo->size);
865 
866       if (p_atomic_cmpxchg(&bo->map_cpu, NULL, map)) {
867          VG_NOACCESS(map, bo->size);
868          munmap(map, bo->size);
869       }
870    }
871    assert(bo->map_cpu);
872 
873    DBG("crocus_bo_map_cpu: %d (%s) -> %p, ", bo->gem_handle, bo->name,
874        bo->map_cpu);
875    print_flags(flags);
876 
877    if (!(flags & MAP_ASYNC)) {
878       bo_wait_with_stall_warning(dbg, bo, "CPU mapping");
879    }
880 
881    if (!bo->cache_coherent && !bo->bufmgr->has_llc) {
882       /* If we're reusing an existing CPU mapping, the CPU caches may
883        * contain stale data from the last time we read from that mapping.
884        * (With the BO cache, it might even be data from a previous buffer!)
885        * Even if it's a brand new mapping, the kernel may have zeroed the
886        * buffer via CPU writes.
887        *
888        * We need to invalidate those cachelines so that we see the latest
889        * contents, and so long as we only read from the CPU mmap we do not
890        * need to write those cachelines back afterwards.
891        *
892        * On LLC, the emprical evidence suggests that writes from the GPU
893        * that bypass the LLC (i.e. for scanout) do *invalidate* the CPU
894        * cachelines. (Other reads, such as the display engine, bypass the
895        * LLC entirely requiring us to keep dirty pixels for the scanout
896        * out of any cache.)
897        */
898 #ifdef SUPPORT_INTEL_INTEGRATED_GPUS
899       intel_invalidate_range(bo->map_cpu, bo->size);
900 #endif
901    }
902 
903    return bo->map_cpu;
904 }
905 
906 static void *
crocus_bo_map_wc(struct util_debug_callback * dbg,struct crocus_bo * bo,unsigned flags)907 crocus_bo_map_wc(struct util_debug_callback *dbg,
908                  struct crocus_bo *bo, unsigned flags)
909 {
910    if (!bo->map_wc) {
911       DBG("crocus_bo_map_wc: %d (%s)\n", bo->gem_handle, bo->name);
912 
913       void *map = crocus_bo_gem_mmap(dbg, bo, true);
914       if (!map) {
915          return NULL;
916       }
917 
918       VG_DEFINED(map, bo->size);
919 
920       if (p_atomic_cmpxchg(&bo->map_wc, NULL, map)) {
921          VG_NOACCESS(map, bo->size);
922          munmap(map, bo->size);
923       }
924    }
925    assert(bo->map_wc);
926 
927    DBG("crocus_bo_map_wc: %d (%s) -> %p\n", bo->gem_handle, bo->name, bo->map_wc);
928    print_flags(flags);
929 
930    if (!(flags & MAP_ASYNC)) {
931       bo_wait_with_stall_warning(dbg, bo, "WC mapping");
932    }
933 
934    return bo->map_wc;
935 }
936 
937 /**
938  * Perform an uncached mapping via the GTT.
939  *
940  * Write access through the GTT is not quite fully coherent. On low power
941  * systems especially, like modern Atoms, we can observe reads from RAM before
942  * the write via GTT has landed. A write memory barrier that flushes the Write
943  * Combining Buffer (i.e. sfence/mfence) is not sufficient to order the later
944  * read after the write as the GTT write suffers a small delay through the GTT
945  * indirection. The kernel uses an uncached mmio read to ensure the GTT write
946  * is ordered with reads (either by the GPU, WB or WC) and unconditionally
947  * flushes prior to execbuf submission. However, if we are not informing the
948  * kernel about our GTT writes, it will not flush before earlier access, such
949  * as when using the cmdparser. Similarly, we need to be careful if we should
950  * ever issue a CPU read immediately following a GTT write.
951  *
952  * Telling the kernel about write access also has one more important
953  * side-effect. Upon receiving notification about the write, it cancels any
954  * scanout buffering for FBC/PSR and friends. Later FBC/PSR is then flushed by
955  * either SW_FINISH or DIRTYFB. The presumption is that we never write to the
956  * actual scanout via a mmaping, only to a backbuffer and so all the FBC/PSR
957  * tracking is handled on the buffer exchange instead.
958  */
959 static void *
crocus_bo_map_gtt(struct util_debug_callback * dbg,struct crocus_bo * bo,unsigned flags)960 crocus_bo_map_gtt(struct util_debug_callback *dbg,
961                   struct crocus_bo *bo, unsigned flags)
962 {
963    struct crocus_bufmgr *bufmgr = bo->bufmgr;
964 
965    /* If we don't support get/set_tiling, there's no support for GTT mapping
966     * either (it won't do any de-tiling for us).
967     */
968    assert(bufmgr->has_tiling_uapi);
969 
970    /* Get a mapping of the buffer if we haven't before. */
971    if (bo->map_gtt == NULL) {
972       DBG("bo_map_gtt: mmap %d (%s)\n", bo->gem_handle, bo->name);
973 
974       struct drm_i915_gem_mmap_gtt mmap_arg = { .handle = bo->gem_handle };
975 
976       /* Get the fake offset back... */
977       int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg);
978       if (ret != 0) {
979          DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
980              __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
981          return NULL;
982       }
983 
984       /* and mmap it. */
985       void *map = mmap(0, bo->size, PROT_READ | PROT_WRITE,
986                        MAP_SHARED, bufmgr->fd, mmap_arg.offset);
987       if (map == MAP_FAILED) {
988          DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
989              __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
990          return NULL;
991       }
992 
993       /* We don't need to use VALGRIND_MALLOCLIKE_BLOCK because Valgrind will
994        * already intercept this mmap call. However, for consistency between
995        * all the mmap paths, we mark the pointer as defined now and mark it
996        * as inaccessible afterwards.
997        */
998       VG_DEFINED(map, bo->size);
999 
1000       if (p_atomic_cmpxchg(&bo->map_gtt, NULL, map)) {
1001          VG_NOACCESS(map, bo->size);
1002          munmap(map, bo->size);
1003       }
1004    }
1005    assert(bo->map_gtt);
1006 
1007    DBG("bo_map_gtt: %d (%s) -> %p, ", bo->gem_handle, bo->name, bo->map_gtt);
1008    print_flags(flags);
1009 
1010    if (!(flags & MAP_ASYNC)) {
1011       bo_wait_with_stall_warning(dbg, bo, "GTT mapping");
1012    }
1013 
1014    return bo->map_gtt;
1015 }
1016 
1017 static bool
can_map_cpu(struct crocus_bo * bo,unsigned flags)1018 can_map_cpu(struct crocus_bo *bo, unsigned flags)
1019 {
1020    if (bo->scanout)
1021       return false;
1022 
1023    if (bo->cache_coherent)
1024       return true;
1025 
1026    /* Even if the buffer itself is not cache-coherent (such as a scanout), on
1027     * an LLC platform reads always are coherent (as they are performed via the
1028     * central system agent). It is just the writes that we need to take special
1029     * care to ensure that land in main memory and not stick in the CPU cache.
1030     */
1031    if (!(flags & MAP_WRITE) && bo->bufmgr->has_llc)
1032       return true;
1033 
1034    /* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
1035     * across batch flushes where the kernel will change cache domains of the
1036     * bo, invalidating continued access to the CPU mmap on non-LLC device.
1037     *
1038     * Similarly, ASYNC typically means that the buffer will be accessed via
1039     * both the CPU and the GPU simultaneously.  Batches may be executed that
1040     * use the BO even while it is mapped.  While OpenGL technically disallows
1041     * most drawing while non-persistent mappings are active, we may still use
1042     * the GPU for blits or other operations, causing batches to happen at
1043     * inconvenient times.
1044     *
1045     * If RAW is set, we expect the caller to be able to handle a WC buffer
1046     * more efficiently than the involuntary clflushes.
1047     */
1048    if (flags & (MAP_PERSISTENT | MAP_COHERENT | MAP_ASYNC | MAP_RAW))
1049       return false;
1050 
1051    return !(flags & MAP_WRITE);
1052 }
1053 
1054 void *
crocus_bo_map(struct util_debug_callback * dbg,struct crocus_bo * bo,unsigned flags)1055 crocus_bo_map(struct util_debug_callback *dbg,
1056               struct crocus_bo *bo, unsigned flags)
1057 {
1058    if (bo->tiling_mode != I915_TILING_NONE && !(flags & MAP_RAW))
1059       return crocus_bo_map_gtt(dbg, bo, flags);
1060 
1061    void *map;
1062 
1063    if (can_map_cpu(bo, flags))
1064       map = crocus_bo_map_cpu(dbg, bo, flags);
1065    else
1066       map = crocus_bo_map_wc(dbg, bo, flags);
1067 
1068    /* Allow the attempt to fail by falling back to the GTT where necessary.
1069     *
1070     * Not every buffer can be mmaped directly using the CPU (or WC), for
1071     * example buffers that wrap stolen memory or are imported from other
1072     * devices. For those, we have little choice but to use a GTT mmapping.
1073     * However, if we use a slow GTT mmapping for reads where we expected fast
1074     * access, that order of magnitude difference in throughput will be clearly
1075     * expressed by angry users.
1076     *
1077     * We skip MAP_RAW because we want to avoid map_gtt's fence detiling.
1078     */
1079    if (!map && !(flags & MAP_RAW)) {
1080       perf_debug(dbg, "Fallback GTT mapping for %s with access flags %x\n",
1081                  bo->name, flags);
1082       map = crocus_bo_map_gtt(dbg, bo, flags);
1083    }
1084 
1085    return map;
1086 }
1087 
1088 /** Waits for all GPU rendering with the object to have completed. */
1089 void
crocus_bo_wait_rendering(struct crocus_bo * bo)1090 crocus_bo_wait_rendering(struct crocus_bo *bo)
1091 {
1092    /* We require a kernel recent enough for WAIT_IOCTL support.
1093     * See intel_init_bufmgr()
1094     */
1095    crocus_bo_wait(bo, -1);
1096 }
1097 
1098 /**
1099  * Waits on a BO for the given amount of time.
1100  *
1101  * @bo: buffer object to wait for
1102  * @timeout_ns: amount of time to wait in nanoseconds.
1103  *   If value is less than 0, an infinite wait will occur.
1104  *
1105  * Returns 0 if the wait was successful ie. the last batch referencing the
1106  * object has completed within the allotted time. Otherwise some negative return
1107  * value describes the error. Of particular interest is -ETIME when the wait has
1108  * failed to yield the desired result.
1109  *
1110  * Similar to crocus_bo_wait_rendering except a timeout parameter allows
1111  * the operation to give up after a certain amount of time. Another subtle
1112  * difference is the internal locking semantics are different (this variant does
1113  * not hold the lock for the duration of the wait). This makes the wait subject
1114  * to a larger userspace race window.
1115  *
1116  * The implementation shall wait until the object is no longer actively
1117  * referenced within a batch buffer at the time of the call. The wait will
1118  * not guarantee that the buffer is re-issued via another thread, or an flinked
1119  * handle. Userspace must make sure this race does not occur if such precision
1120  * is important.
1121  *
1122  * Note that some kernels have broken the inifite wait for negative values
1123  * promise, upgrade to latest stable kernels if this is the case.
1124  */
1125 int
crocus_bo_wait(struct crocus_bo * bo,int64_t timeout_ns)1126 crocus_bo_wait(struct crocus_bo *bo, int64_t timeout_ns)
1127 {
1128    struct crocus_bufmgr *bufmgr = bo->bufmgr;
1129 
1130    /* If we know it's idle, don't bother with the kernel round trip */
1131    if (bo->idle && !bo->external)
1132       return 0;
1133 
1134    struct drm_i915_gem_wait wait = {
1135       .bo_handle = bo->gem_handle,
1136       .timeout_ns = timeout_ns,
1137    };
1138    int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_WAIT, &wait);
1139    if (ret != 0)
1140       return -errno;
1141 
1142    bo->idle = true;
1143 
1144    return ret;
1145 }
1146 
1147 static void
crocus_bufmgr_destroy(struct crocus_bufmgr * bufmgr)1148 crocus_bufmgr_destroy(struct crocus_bufmgr *bufmgr)
1149 {
1150    simple_mtx_destroy(&bufmgr->lock);
1151 
1152    /* Free any cached buffer objects we were going to reuse */
1153    for (int i = 0; i < bufmgr->num_buckets; i++) {
1154       struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1155 
1156       list_for_each_entry_safe(struct crocus_bo, bo, &bucket->head, head) {
1157          list_del(&bo->head);
1158 
1159          bo_free(bo);
1160       }
1161    }
1162 
1163    /* Close any buffer objects on the dead list. */
1164    list_for_each_entry_safe(struct crocus_bo, bo, &bufmgr->zombie_list, head) {
1165       list_del(&bo->head);
1166       bo_close(bo);
1167    }
1168 
1169    _mesa_hash_table_destroy(bufmgr->name_table, NULL);
1170    _mesa_hash_table_destroy(bufmgr->handle_table, NULL);
1171 
1172    close(bufmgr->fd);
1173 
1174    free(bufmgr);
1175 }
1176 
1177 static int
bo_set_tiling_internal(struct crocus_bo * bo,uint32_t tiling_mode,uint32_t stride)1178 bo_set_tiling_internal(struct crocus_bo *bo, uint32_t tiling_mode,
1179                        uint32_t stride)
1180 {
1181    struct crocus_bufmgr *bufmgr = bo->bufmgr;
1182    struct drm_i915_gem_set_tiling set_tiling;
1183    int ret;
1184 
1185    if (bo->global_name == 0 &&
1186        tiling_mode == bo->tiling_mode && stride == bo->stride)
1187       return 0;
1188 
1189    memset(&set_tiling, 0, sizeof(set_tiling));
1190    do {
1191       /* set_tiling is slightly broken and overwrites the
1192        * input on the error path, so we have to open code
1193        * drm_ioctl.
1194        */
1195       set_tiling.handle = bo->gem_handle;
1196       set_tiling.tiling_mode = tiling_mode;
1197       set_tiling.stride = stride;
1198 
1199       ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
1200    } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
1201    if (ret == -1)
1202       return -errno;
1203 
1204    bo->tiling_mode = set_tiling.tiling_mode;
1205    bo->swizzle_mode = set_tiling.swizzle_mode;
1206    bo->stride = set_tiling.stride;
1207    return 0;
1208 }
1209 
1210 int
crocus_bo_get_tiling(struct crocus_bo * bo,uint32_t * tiling_mode,uint32_t * swizzle_mode)1211 crocus_bo_get_tiling(struct crocus_bo *bo, uint32_t *tiling_mode,
1212                      uint32_t *swizzle_mode)
1213 {
1214    *tiling_mode = bo->tiling_mode;
1215    *swizzle_mode = bo->swizzle_mode;
1216    return 0;
1217 }
1218 
1219 struct crocus_bo *
crocus_bo_import_dmabuf(struct crocus_bufmgr * bufmgr,int prime_fd,uint64_t modifier)1220 crocus_bo_import_dmabuf(struct crocus_bufmgr *bufmgr, int prime_fd,
1221                         uint64_t modifier)
1222 {
1223    uint32_t handle;
1224    struct crocus_bo *bo;
1225 
1226    simple_mtx_lock(&bufmgr->lock);
1227    int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1228    if (ret) {
1229       DBG("import_dmabuf: failed to obtain handle from fd: %s\n",
1230           strerror(errno));
1231       simple_mtx_unlock(&bufmgr->lock);
1232       return NULL;
1233    }
1234 
1235    /*
1236     * See if the kernel has already returned this buffer to us. Just as
1237     * for named buffers, we must not create two bo's pointing at the same
1238     * kernel object
1239     */
1240    bo = find_and_ref_external_bo(bufmgr->handle_table, handle);
1241    if (bo)
1242       goto out;
1243 
1244    bo = bo_calloc();
1245    if (!bo)
1246       goto out;
1247 
1248    p_atomic_set(&bo->refcount, 1);
1249 
1250    /* Determine size of bo.  The fd-to-handle ioctl really should
1251     * return the size, but it doesn't.  If we have kernel 3.12 or
1252     * later, we can lseek on the prime fd to get the size.  Older
1253     * kernels will just fail, in which case we fall back to the
1254     * provided (estimated or guess size). */
1255    ret = lseek(prime_fd, 0, SEEK_END);
1256    if (ret != -1)
1257       bo->size = ret;
1258 
1259    bo->bufmgr = bufmgr;
1260    bo->name = "prime";
1261    bo->reusable = false;
1262    bo->external = true;
1263    bo->kflags = 0;
1264    bo->gem_handle = handle;
1265    _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1266 
1267    const struct isl_drm_modifier_info *mod_info =
1268       isl_drm_modifier_get_info(modifier);
1269    if (mod_info) {
1270       bo->tiling_mode = isl_tiling_to_i915_tiling(mod_info->tiling);
1271    } else if (bufmgr->has_tiling_uapi) {
1272       struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
1273       if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling))
1274          goto err;
1275 
1276       bo->tiling_mode = get_tiling.tiling_mode;
1277    } else {
1278       bo->tiling_mode = I915_TILING_NONE;
1279    }
1280 
1281 out:
1282    simple_mtx_unlock(&bufmgr->lock);
1283    return bo;
1284 
1285 err:
1286    bo_free(bo);
1287    simple_mtx_unlock(&bufmgr->lock);
1288    return NULL;
1289 }
1290 
1291 struct crocus_bo *
crocus_bo_import_dmabuf_no_mods(struct crocus_bufmgr * bufmgr,int prime_fd)1292 crocus_bo_import_dmabuf_no_mods(struct crocus_bufmgr *bufmgr,
1293                                 int prime_fd)
1294 {
1295    uint32_t handle;
1296    struct crocus_bo *bo;
1297 
1298    simple_mtx_lock(&bufmgr->lock);
1299    int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1300    if (ret) {
1301       DBG("import_dmabuf: failed to obtain handle from fd: %s\n",
1302           strerror(errno));
1303       simple_mtx_unlock(&bufmgr->lock);
1304       return NULL;
1305    }
1306 
1307    /*
1308     * See if the kernel has already returned this buffer to us. Just as
1309     * for named buffers, we must not create two bo's pointing at the same
1310     * kernel object
1311     */
1312    bo = find_and_ref_external_bo(bufmgr->handle_table, handle);
1313    if (bo)
1314       goto out;
1315 
1316    bo = bo_calloc();
1317    if (!bo)
1318       goto out;
1319 
1320    p_atomic_set(&bo->refcount, 1);
1321 
1322    /* Determine size of bo.  The fd-to-handle ioctl really should
1323     * return the size, but it doesn't.  If we have kernel 3.12 or
1324     * later, we can lseek on the prime fd to get the size.  Older
1325     * kernels will just fail, in which case we fall back to the
1326     * provided (estimated or guess size). */
1327    ret = lseek(prime_fd, 0, SEEK_END);
1328    if (ret != -1)
1329       bo->size = ret;
1330 
1331    bo->bufmgr = bufmgr;
1332    bo->name = "prime";
1333    bo->reusable = false;
1334    bo->external = true;
1335    bo->kflags = 0;
1336    bo->gem_handle = handle;
1337    _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1338 
1339 out:
1340    simple_mtx_unlock(&bufmgr->lock);
1341    return bo;
1342 }
1343 
1344 static void
crocus_bo_make_external_locked(struct crocus_bo * bo)1345 crocus_bo_make_external_locked(struct crocus_bo *bo)
1346 {
1347    if (!bo->external) {
1348       _mesa_hash_table_insert(bo->bufmgr->handle_table, &bo->gem_handle, bo);
1349       bo->external = true;
1350       bo->reusable = false;
1351    }
1352 }
1353 
1354 static void
crocus_bo_make_external(struct crocus_bo * bo)1355 crocus_bo_make_external(struct crocus_bo *bo)
1356 {
1357    struct crocus_bufmgr *bufmgr = bo->bufmgr;
1358 
1359    if (bo->external) {
1360       assert(!bo->reusable);
1361       return;
1362    }
1363 
1364    simple_mtx_lock(&bufmgr->lock);
1365    crocus_bo_make_external_locked(bo);
1366    simple_mtx_unlock(&bufmgr->lock);
1367 }
1368 
1369 int
crocus_bo_export_dmabuf(struct crocus_bo * bo,int * prime_fd)1370 crocus_bo_export_dmabuf(struct crocus_bo *bo, int *prime_fd)
1371 {
1372    struct crocus_bufmgr *bufmgr = bo->bufmgr;
1373 
1374    crocus_bo_make_external(bo);
1375 
1376    if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1377                           DRM_CLOEXEC | DRM_RDWR, prime_fd) != 0)
1378       return -errno;
1379 
1380    return 0;
1381 }
1382 
1383 uint32_t
crocus_bo_export_gem_handle(struct crocus_bo * bo)1384 crocus_bo_export_gem_handle(struct crocus_bo *bo)
1385 {
1386    crocus_bo_make_external(bo);
1387 
1388    return bo->gem_handle;
1389 }
1390 
1391 int
crocus_bo_flink(struct crocus_bo * bo,uint32_t * name)1392 crocus_bo_flink(struct crocus_bo *bo, uint32_t *name)
1393 {
1394    struct crocus_bufmgr *bufmgr = bo->bufmgr;
1395 
1396    if (!bo->global_name) {
1397       struct drm_gem_flink flink = { .handle = bo->gem_handle };
1398 
1399       if (intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1400          return -errno;
1401 
1402       simple_mtx_lock(&bufmgr->lock);
1403       if (!bo->global_name) {
1404          crocus_bo_make_external_locked(bo);
1405          bo->global_name = flink.name;
1406          _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
1407       }
1408       simple_mtx_unlock(&bufmgr->lock);
1409    }
1410 
1411    *name = bo->global_name;
1412    return 0;
1413 }
1414 
1415 int
crocus_bo_export_gem_handle_for_device(struct crocus_bo * bo,int drm_fd,uint32_t * out_handle)1416 crocus_bo_export_gem_handle_for_device(struct crocus_bo *bo, int drm_fd,
1417                                        uint32_t *out_handle)
1418 {
1419    /* Only add the new GEM handle to the list of export if it belongs to a
1420     * different GEM device. Otherwise we might close the same buffer multiple
1421     * times.
1422     */
1423    struct crocus_bufmgr *bufmgr = bo->bufmgr;
1424    int ret = os_same_file_description(drm_fd, bufmgr->fd);
1425    WARN_ONCE(ret < 0,
1426              "Kernel has no file descriptor comparison support: %s\n",
1427              strerror(errno));
1428    if (ret == 0) {
1429       *out_handle = crocus_bo_export_gem_handle(bo);
1430       return 0;
1431    }
1432 
1433    struct bo_export *export = calloc(1, sizeof(*export));
1434    if (!export)
1435       return -ENOMEM;
1436 
1437    export->drm_fd = drm_fd;
1438 
1439    int dmabuf_fd = -1;
1440    int err = crocus_bo_export_dmabuf(bo, &dmabuf_fd);
1441    if (err) {
1442       free(export);
1443       return err;
1444    }
1445 
1446    simple_mtx_lock(&bufmgr->lock);
1447    err = drmPrimeFDToHandle(drm_fd, dmabuf_fd, &export->gem_handle);
1448    close(dmabuf_fd);
1449    if (err) {
1450       simple_mtx_unlock(&bufmgr->lock);
1451       free(export);
1452       return err;
1453    }
1454 
1455    bool found = false;
1456    list_for_each_entry(struct bo_export, iter, &bo->exports, link) {
1457       if (iter->drm_fd != drm_fd)
1458          continue;
1459       /* Here we assume that for a given DRM fd, we'll always get back the
1460        * same GEM handle for a given buffer.
1461        */
1462       assert(iter->gem_handle == export->gem_handle);
1463       free(export);
1464       export = iter;
1465       found = true;
1466       break;
1467    }
1468    if (!found)
1469       list_addtail(&export->link, &bo->exports);
1470 
1471    simple_mtx_unlock(&bufmgr->lock);
1472 
1473    *out_handle = export->gem_handle;
1474 
1475    return 0;
1476 }
1477 
1478 static void
add_bucket(struct crocus_bufmgr * bufmgr,int size)1479 add_bucket(struct crocus_bufmgr *bufmgr, int size)
1480 {
1481    unsigned int i = bufmgr->num_buckets;
1482 
1483    assert(i < ARRAY_SIZE(bufmgr->cache_bucket));
1484 
1485    list_inithead(&bufmgr->cache_bucket[i].head);
1486    bufmgr->cache_bucket[i].size = size;
1487    bufmgr->num_buckets++;
1488 
1489    assert(bucket_for_size(bufmgr, size) == &bufmgr->cache_bucket[i]);
1490    assert(bucket_for_size(bufmgr, size - 2048) == &bufmgr->cache_bucket[i]);
1491    assert(bucket_for_size(bufmgr, size + 1) != &bufmgr->cache_bucket[i]);
1492 }
1493 
1494 static void
init_cache_buckets(struct crocus_bufmgr * bufmgr)1495 init_cache_buckets(struct crocus_bufmgr *bufmgr)
1496 {
1497    uint64_t size, cache_max_size = 64 * 1024 * 1024;
1498 
1499    /* OK, so power of two buckets was too wasteful of memory.
1500     * Give 3 other sizes between each power of two, to hopefully
1501     * cover things accurately enough.  (The alternative is
1502     * probably to just go for exact matching of sizes, and assume
1503     * that for things like composited window resize the tiled
1504     * width/height alignment and rounding of sizes to pages will
1505     * get us useful cache hit rates anyway)
1506     */
1507    add_bucket(bufmgr, PAGE_SIZE);
1508    add_bucket(bufmgr, PAGE_SIZE * 2);
1509    add_bucket(bufmgr, PAGE_SIZE * 3);
1510 
1511    /* Initialize the linked lists for BO reuse cache. */
1512    for (size = 4 * PAGE_SIZE; size <= cache_max_size; size *= 2) {
1513       add_bucket(bufmgr, size);
1514 
1515       add_bucket(bufmgr, size + size * 1 / 4);
1516       add_bucket(bufmgr, size + size * 2 / 4);
1517       add_bucket(bufmgr, size + size * 3 / 4);
1518    }
1519 }
1520 
1521 uint32_t
crocus_create_hw_context(struct crocus_bufmgr * bufmgr)1522 crocus_create_hw_context(struct crocus_bufmgr *bufmgr)
1523 {
1524    uint32_t ctx_id;
1525    if (!intel_gem_create_context(bufmgr->fd, &ctx_id)) {
1526       DBG("intel_gem_create_context failed: %s\n", strerror(errno));
1527       return 0;
1528    }
1529 
1530    /* Upon declaring a GPU hang, the kernel will zap the guilty context
1531     * back to the default logical HW state and attempt to continue on to
1532     * our next submitted batchbuffer.  However, our render batches assume
1533     * the previous GPU state is preserved, and only emit commands needed
1534     * to incrementally change that state.  In particular, we inherit the
1535     * STATE_BASE_ADDRESS and PIPELINE_SELECT settings, which are critical.
1536     * With default base addresses, our next batches will almost certainly
1537     * cause more GPU hangs, leading to repeated hangs until we're banned
1538     * or the machine is dead.
1539     *
1540     * Here we tell the kernel not to attempt to recover our context but
1541     * immediately (on the next batchbuffer submission) report that the
1542     * context is lost, and we will do the recovery ourselves.  Ideally,
1543     * we'll have two lost batches instead of a continual stream of hangs.
1544     */
1545    intel_gem_set_context_param(bufmgr->fd, ctx_id,
1546                                I915_CONTEXT_PARAM_RECOVERABLE, false);
1547 
1548    return ctx_id;
1549 }
1550 
1551 static int
crocus_hw_context_get_priority(struct crocus_bufmgr * bufmgr,uint32_t ctx_id)1552 crocus_hw_context_get_priority(struct crocus_bufmgr *bufmgr, uint32_t ctx_id)
1553 {
1554    uint64_t priority = 0;
1555    intel_gem_get_context_param(bufmgr->fd, ctx_id,
1556                                I915_CONTEXT_PARAM_PRIORITY, &priority);
1557    return priority; /* on error, return 0 i.e. default priority */
1558 }
1559 
1560 int
crocus_hw_context_set_priority(struct crocus_bufmgr * bufmgr,uint32_t ctx_id,int priority)1561 crocus_hw_context_set_priority(struct crocus_bufmgr *bufmgr,
1562                                uint32_t ctx_id,
1563                                int priority)
1564 {
1565    int err = 0;
1566    if (!intel_gem_set_context_param(bufmgr->fd, ctx_id,
1567                                     I915_CONTEXT_PARAM_PRIORITY, priority))
1568       err = -errno;
1569 
1570    return err;
1571 }
1572 
1573 uint32_t
crocus_clone_hw_context(struct crocus_bufmgr * bufmgr,uint32_t ctx_id)1574 crocus_clone_hw_context(struct crocus_bufmgr *bufmgr, uint32_t ctx_id)
1575 {
1576    uint32_t new_ctx = crocus_create_hw_context(bufmgr);
1577 
1578    if (new_ctx) {
1579       int priority = crocus_hw_context_get_priority(bufmgr, ctx_id);
1580       crocus_hw_context_set_priority(bufmgr, new_ctx, priority);
1581    }
1582 
1583    return new_ctx;
1584 }
1585 
1586 void
crocus_destroy_hw_context(struct crocus_bufmgr * bufmgr,uint32_t ctx_id)1587 crocus_destroy_hw_context(struct crocus_bufmgr *bufmgr, uint32_t ctx_id)
1588 {
1589    if (ctx_id != 0 &&
1590        !intel_gem_destroy_context(bufmgr->fd, ctx_id)) {
1591       fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1592               strerror(errno));
1593    }
1594 }
1595 
1596 /**
1597  * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1598  * and manage map buffer objections.
1599  *
1600  * \param fd File descriptor of the opened DRM device.
1601  */
1602 static struct crocus_bufmgr *
crocus_bufmgr_create(struct intel_device_info * devinfo,int fd,bool bo_reuse)1603 crocus_bufmgr_create(struct intel_device_info *devinfo, int fd, bool bo_reuse)
1604 {
1605    struct crocus_bufmgr *bufmgr = calloc(1, sizeof(*bufmgr));
1606    if (bufmgr == NULL)
1607       return NULL;
1608 
1609    /* Handles to buffer objects belong to the device fd and are not
1610     * reference counted by the kernel.  If the same fd is used by
1611     * multiple parties (threads sharing the same screen bufmgr, or
1612     * even worse the same device fd passed to multiple libraries)
1613     * ownership of those handles is shared by those independent parties.
1614     *
1615     * Don't do this! Ensure that each library/bufmgr has its own device
1616     * fd so that its namespace does not clash with another.
1617     */
1618    bufmgr->fd = os_dupfd_cloexec(fd);
1619 
1620    p_atomic_set(&bufmgr->refcount, 1);
1621 
1622    simple_mtx_init(&bufmgr->lock, mtx_plain);
1623 
1624    list_inithead(&bufmgr->zombie_list);
1625 
1626    bufmgr->has_llc = devinfo->has_llc;
1627    bufmgr->has_tiling_uapi = devinfo->has_tiling_uapi;
1628    bufmgr->bo_reuse = bo_reuse;
1629    bufmgr->has_mmap_offset = devinfo->has_mmap_offset;
1630 
1631    init_cache_buckets(bufmgr);
1632 
1633    bufmgr->name_table =
1634       _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1635    bufmgr->handle_table =
1636       _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1637 
1638    return bufmgr;
1639 }
1640 
1641 static struct crocus_bufmgr *
crocus_bufmgr_ref(struct crocus_bufmgr * bufmgr)1642 crocus_bufmgr_ref(struct crocus_bufmgr *bufmgr)
1643 {
1644    p_atomic_inc(&bufmgr->refcount);
1645    return bufmgr;
1646 }
1647 
1648 void
crocus_bufmgr_unref(struct crocus_bufmgr * bufmgr)1649 crocus_bufmgr_unref(struct crocus_bufmgr *bufmgr)
1650 {
1651    simple_mtx_lock(&global_bufmgr_list_mutex);
1652    if (p_atomic_dec_zero(&bufmgr->refcount)) {
1653       list_del(&bufmgr->link);
1654       crocus_bufmgr_destroy(bufmgr);
1655    }
1656    simple_mtx_unlock(&global_bufmgr_list_mutex);
1657 }
1658 
1659 /**
1660  * Gets an already existing GEM buffer manager or create a new one.
1661  *
1662  * \param fd File descriptor of the opened DRM device.
1663  */
1664 struct crocus_bufmgr *
crocus_bufmgr_get_for_fd(struct intel_device_info * devinfo,int fd,bool bo_reuse)1665 crocus_bufmgr_get_for_fd(struct intel_device_info *devinfo, int fd, bool bo_reuse)
1666 {
1667    struct stat st;
1668 
1669    if (fstat(fd, &st))
1670       return NULL;
1671 
1672    struct crocus_bufmgr *bufmgr = NULL;
1673 
1674    simple_mtx_lock(&global_bufmgr_list_mutex);
1675    list_for_each_entry(struct crocus_bufmgr, iter_bufmgr, &global_bufmgr_list, link) {
1676       struct stat iter_st;
1677       if (fstat(iter_bufmgr->fd, &iter_st))
1678          continue;
1679 
1680       if (st.st_rdev == iter_st.st_rdev) {
1681          assert(iter_bufmgr->bo_reuse == bo_reuse);
1682          bufmgr = crocus_bufmgr_ref(iter_bufmgr);
1683          goto unlock;
1684       }
1685    }
1686 
1687    bufmgr = crocus_bufmgr_create(devinfo, fd, bo_reuse);
1688    if (bufmgr)
1689       list_addtail(&bufmgr->link, &global_bufmgr_list);
1690 
1691  unlock:
1692    simple_mtx_unlock(&global_bufmgr_list_mutex);
1693 
1694    return bufmgr;
1695 }
1696 
1697 int
crocus_bufmgr_get_fd(struct crocus_bufmgr * bufmgr)1698 crocus_bufmgr_get_fd(struct crocus_bufmgr *bufmgr)
1699 {
1700    return bufmgr->fd;
1701 }
1702