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