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