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