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