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