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