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