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