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