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