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