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