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