2 * Copyright © 2017 Intel Corporation
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:
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
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
29 #include <util/u_atomic.h>
36 #include <sys/ioctl.h>
39 #include <sys/types.h>
45 #define ETIME ETIMEDOUT
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"
56 #include "iris_bufmgr.h"
57 #include "iris_context.h"
60 #include "drm-uapi/i915_drm.h"
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
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))
80 #define PAGE_SIZE 4096
82 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
85 * Call ioctl, restarting if it is interupted
88 drm_ioctl(int fd
, unsigned long request
, void *arg
)
93 ret
= ioctl(fd
, request
, arg
);
94 } while (ret
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
99 atomic_add_unless(int *v
, int add
, int unless
)
102 c
= p_atomic_read(v
);
103 while (c
!= unless
&& (old
= p_atomic_cmpxchg(v
, c
, c
+ add
)) != c
)
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.
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.
122 * Dynamic array of nodes. (pointer, two ints)
125 struct vma_bucket_node
{
126 uint64_t start_address
;
130 struct bo_cache_bucket
{
131 /** List of cached BOs. */
132 struct list_head head
;
134 /** Size of this bucket, in bytes. */
137 /** List of vma_bucket_nodes */
138 struct util_dynarray vma_list
[IRIS_MEMZONE_COUNT
];
146 /** Array of lists of cached gem objects of power-of-two sizes */
147 struct bo_cache_bucket cache_bucket
[14 * 4];
151 struct hash_table
*name_table
;
152 struct hash_table
*handle_table
;
154 struct util_vma_heap vma_allocator
[IRIS_MEMZONE_COUNT
];
160 static int bo_set_tiling_internal(struct iris_bo
*bo
, uint32_t tiling_mode
,
163 static void bo_free(struct iris_bo
*bo
);
165 static uint64_t vma_alloc(struct iris_bufmgr
*bufmgr
,
166 enum iris_memory_zone memzone
,
167 uint64_t size
, uint64_t alignment
);
170 key_hash_uint(const void *key
)
172 return _mesa_hash_data(key
, 4);
176 key_uint_equal(const void *a
, const void *b
)
178 return *((unsigned *) a
) == *((unsigned *) b
);
181 static struct iris_bo
*
182 hash_find_bo(struct hash_table
*ht
, unsigned int key
)
184 struct hash_entry
*entry
= _mesa_hash_table_search(ht
, &key
);
185 return entry
? (struct iris_bo
*) entry
->data
: NULL
;
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.
193 static struct bo_cache_bucket
*
194 bucket_for_size(struct iris_bufmgr
*bufmgr
, uint64_t size
)
196 /* Calculating the pages and rounding up to the page size. */
197 const unsigned pages
= (size
+ PAGE_SIZE
- 1) / PAGE_SIZE
;
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
206 const unsigned row
= 30 - __builtin_clz((pages
- 1) | 3);
207 const unsigned row_max_pages
= 4 << row
;
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.
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);
218 const unsigned col
= (pages
- prev_row_max_pages
+
219 ((1 << col_size_log2
) - 1)) >> col_size_log2
;
221 /* Calculating the index based on the row and column. */
222 const unsigned index
= (row
* 4) + (col
- 1);
224 return (index
< bufmgr
->num_buckets
) ?
225 &bufmgr
->cache_bucket
[index
] : NULL
;
228 static enum iris_memory_zone
229 memzone_for_address(uint64_t address
)
231 const uint64_t _4GB
= 1ull << 32;
233 if (address
>= 3 * _4GB
)
234 return IRIS_MEMZONE_OTHER
;
236 if (address
>= 2 * _4GB
)
237 return IRIS_MEMZONE_DYNAMIC
;
239 if (address
> 1 * _4GB
)
240 return IRIS_MEMZONE_SURFACE
;
242 /* The binder isn't in any memory zone. */
243 if (address
== 1 * _4GB
)
244 return IRIS_MEMZONE_BINDER
;
246 return IRIS_MEMZONE_SHADER
;
250 bucket_vma_alloc(struct iris_bufmgr
*bufmgr
,
251 struct bo_cache_bucket
*bucket
,
252 enum iris_memory_zone memzone
)
254 struct util_dynarray
*vma_list
= &bucket
->vma_list
[memzone
];
255 struct vma_bucket_node
*node
;
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).
261 * Set the first bit used, and return the start address.
263 node
= util_dynarray_grow(vma_list
, sizeof(struct vma_bucket_node
));
264 node
->start_address
= vma_alloc(bufmgr
, memzone
,
265 64ull * bucket
->size
,
266 64ull * bucket
->size
);
267 node
->bitmap
= ~1ull;
268 return node
->start_address
;
271 /* Pick any bit from any node - they're all the right size and free. */
272 node
= util_dynarray_top_ptr(vma_list
, struct vma_bucket_node
);
273 int bit
= ffsll(node
->bitmap
) - 1;
276 /* Reserve the memory by clearing the bit. */
277 node
->bitmap
&= ~(1ull << bit
);
279 /* If this node is now completely full, remove it from the free list. */
280 if (node
->bitmap
== 0ull) {
281 (void) util_dynarray_pop(vma_list
, struct vma_bucket_node
);
284 return node
->start_address
+ bit
* bucket
->size
;
288 bucket_vma_free(struct bo_cache_bucket
*bucket
,
292 enum iris_memory_zone memzone
= memzone_for_address(address
);
293 struct util_dynarray
*vma_list
= &bucket
->vma_list
[memzone
];
294 const uint64_t node_bytes
= 64ull * bucket
->size
;
295 struct vma_bucket_node
*node
= NULL
;
297 uint64_t start
= (address
/ node_bytes
) * node_bytes
;
298 int bit
= (address
- start
) / bucket
->size
;
300 util_dynarray_foreach(vma_list
, struct vma_bucket_node
, cur
) {
301 if (cur
->start_address
== start
) {
308 node
= util_dynarray_grow(vma_list
, sizeof(struct vma_bucket_node
));
309 node
->start_address
= start
;
313 node
->bitmap
|= 1ull << bit
;
315 /* The block might be entirely free now, and if so, we could return it
316 * to the larger allocator. But we may as well hang on to it, in case
317 * we get more allocations at this block size.
321 static struct bo_cache_bucket
*
322 get_bucket_allocator(struct iris_bufmgr
*bufmgr
, uint64_t size
)
324 /* Skip using the bucket allocator for very large sizes, as it allocates
325 * 64 of them and this can balloon rather quickly.
327 if (size
> 1024 * PAGE_SIZE
)
330 struct bo_cache_bucket
*bucket
= bucket_for_size(bufmgr
, size
);
332 if (bucket
&& bucket
->size
== size
)
339 vma_alloc(struct iris_bufmgr
*bufmgr
,
340 enum iris_memory_zone memzone
,
344 if (memzone
== IRIS_MEMZONE_BINDER
)
347 struct bo_cache_bucket
*bucket
= get_bucket_allocator(bufmgr
, size
);
351 addr
= bucket_vma_alloc(bufmgr
, bucket
, memzone
);
353 addr
= util_vma_heap_alloc(&bufmgr
->vma_allocator
[memzone
], size
,
357 /* Canonicalize the address.
359 * The Broadwell PRM Vol. 2a, MI_LOAD_REGISTER_MEM::MemoryAddress says:
361 * "This field specifies the address of the memory location where the
362 * register value specified in the DWord above will read from. The
363 * address specifies the DWord location of the data. Range =
364 * GraphicsVirtualAddress[63:2] for a DWord register GraphicsAddress
365 * [63:48] are ignored by the HW and assumed to be in correct
366 * canonical form [63:48] == [47]."
368 const int shift
= 63 - 47;
369 addr
= (((int64_t) addr
) << shift
) >> shift
;
375 vma_free(struct iris_bufmgr
*bufmgr
,
379 struct bo_cache_bucket
*bucket
= get_bucket_allocator(bufmgr
, size
);
382 bucket_vma_free(bucket
, address
, size
);
384 enum iris_memory_zone memzone
= memzone_for_address(address
);
385 util_vma_heap_free(&bufmgr
->vma_allocator
[memzone
], address
, size
);
390 iris_bo_busy(struct iris_bo
*bo
)
392 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
393 struct drm_i915_gem_busy busy
= { .handle
= bo
->gem_handle
};
395 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_BUSY
, &busy
);
397 bo
->idle
= !busy
.busy
;
404 iris_bo_madvise(struct iris_bo
*bo
, int state
)
406 struct drm_i915_gem_madvise madv
= {
407 .handle
= bo
->gem_handle
,
412 drm_ioctl(bo
->bufmgr
->fd
, DRM_IOCTL_I915_GEM_MADVISE
, &madv
);
414 return madv
.retained
;
417 /* drop the oldest entries that have been purged by the kernel */
419 iris_bo_cache_purge_bucket(struct iris_bufmgr
*bufmgr
,
420 struct bo_cache_bucket
*bucket
)
422 list_for_each_entry_safe(struct iris_bo
, bo
, &bucket
->head
, head
) {
423 if (iris_bo_madvise(bo
, I915_MADV_DONTNEED
))
431 static struct iris_bo
*
432 bo_alloc_internal(struct iris_bufmgr
*bufmgr
,
435 enum iris_memory_zone memzone
,
437 uint32_t tiling_mode
,
441 unsigned int page_size
= getpagesize();
443 struct bo_cache_bucket
*bucket
;
444 bool alloc_from_cache
;
448 if (flags
& BO_ALLOC_ZEROED
)
451 /* Round the allocated size up to a power of two number of pages. */
452 bucket
= bucket_for_size(bufmgr
, size
);
454 /* If we don't have caching at this size, don't actually round the
457 if (bucket
== NULL
) {
459 if (bo_size
< page_size
)
462 bo_size
= bucket
->size
;
465 mtx_lock(&bufmgr
->lock
);
466 /* Get a buffer out of the cache if available */
468 alloc_from_cache
= false;
469 if (bucket
!= NULL
&& !list_empty(&bucket
->head
)) {
470 /* If the last BO in the cache is idle, then reuse it. Otherwise,
471 * allocate a fresh buffer to avoid stalling.
473 bo
= LIST_ENTRY(struct iris_bo
, bucket
->head
.next
, head
);
474 if (!iris_bo_busy(bo
)) {
475 alloc_from_cache
= true;
479 if (alloc_from_cache
) {
480 if (!iris_bo_madvise(bo
, I915_MADV_WILLNEED
)) {
482 iris_bo_cache_purge_bucket(bufmgr
, bucket
);
486 if (bo_set_tiling_internal(bo
, tiling_mode
, stride
)) {
492 void *map
= iris_bo_map(NULL
, bo
, MAP_WRITE
| MAP_RAW
);
497 memset(map
, 0, bo_size
);
502 if (alloc_from_cache
) {
503 /* If the cached BO isn't in the right memory zone, free the old
504 * memory and assign it a new address.
506 if (memzone
!= memzone_for_address(bo
->gtt_offset
)) {
507 vma_free(bufmgr
, bo
->gtt_offset
, size
);
511 bo
= calloc(1, sizeof(*bo
));
518 struct drm_i915_gem_create create
= { .size
= bo_size
};
520 /* All new BOs we get from the kernel are zeroed, so we don't need to
521 * worry about that here.
523 ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_CREATE
, &create
);
529 bo
->gem_handle
= create
.handle
;
532 bo
->kflags
= EXEC_OBJECT_SUPPORTS_48B_ADDRESS
| EXEC_OBJECT_PINNED
;
534 bo
->tiling_mode
= I915_TILING_NONE
;
535 bo
->swizzle_mode
= I915_BIT_6_SWIZZLE_NONE
;
538 if (bo_set_tiling_internal(bo
, tiling_mode
, stride
))
541 /* Calling set_domain() will allocate pages for the BO outside of the
542 * struct mutex lock in the kernel, which is more efficient than waiting
543 * to create them during the first execbuf that uses the BO.
545 struct drm_i915_gem_set_domain sd
= {
546 .handle
= bo
->gem_handle
,
547 .read_domains
= I915_GEM_DOMAIN_CPU
,
551 if (drm_ioctl(bo
->bufmgr
->fd
, DRM_IOCTL_I915_GEM_SET_DOMAIN
, &sd
) != 0)
555 if (bo
->gtt_offset
== 0ull) {
556 bo
->gtt_offset
= vma_alloc(bufmgr
, memzone
, bo
->size
, 1);
558 if (bo
->gtt_offset
== 0ull)
563 p_atomic_set(&bo
->refcount
, 1);
565 bo
->cache_coherent
= bufmgr
->has_llc
;
568 mtx_unlock(&bufmgr
->lock
);
570 DBG("bo_create: buf %d (%s) %llub\n", bo
->gem_handle
, bo
->name
,
571 (unsigned long long) size
);
578 mtx_unlock(&bufmgr
->lock
);
583 iris_bo_alloc(struct iris_bufmgr
*bufmgr
,
586 enum iris_memory_zone memzone
)
588 return bo_alloc_internal(bufmgr
, name
, size
, memzone
,
589 0, I915_TILING_NONE
, 0);
593 iris_bo_alloc_tiled(struct iris_bufmgr
*bufmgr
, const char *name
,
594 uint64_t size
, enum iris_memory_zone memzone
,
595 uint32_t tiling_mode
, uint32_t pitch
, unsigned flags
)
597 return bo_alloc_internal(bufmgr
, name
, size
, memzone
,
598 flags
, tiling_mode
, pitch
);
602 * Returns a iris_bo wrapping the given buffer object handle.
604 * This can be used when one application needs to pass a buffer object
608 iris_bo_gem_create_from_name(struct iris_bufmgr
*bufmgr
,
609 const char *name
, unsigned int handle
)
613 /* At the moment most applications only have a few named bo.
614 * For instance, in a DRI client only the render buffers passed
615 * between X and the client are named. And since X returns the
616 * alternating names for the front/back buffer a linear search
617 * provides a sufficiently fast match.
619 mtx_lock(&bufmgr
->lock
);
620 bo
= hash_find_bo(bufmgr
->name_table
, handle
);
622 iris_bo_reference(bo
);
626 struct drm_gem_open open_arg
= { .name
= handle
};
627 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_GEM_OPEN
, &open_arg
);
629 DBG("Couldn't reference %s handle 0x%08x: %s\n",
630 name
, handle
, strerror(errno
));
634 /* Now see if someone has used a prime handle to get this
635 * object from the kernel before by looking through the list
636 * again for a matching gem_handle
638 bo
= hash_find_bo(bufmgr
->handle_table
, open_arg
.handle
);
640 iris_bo_reference(bo
);
644 bo
= calloc(1, sizeof(*bo
));
648 p_atomic_set(&bo
->refcount
, 1);
650 bo
->size
= open_arg
.size
;
653 bo
->kflags
= EXEC_OBJECT_SUPPORTS_48B_ADDRESS
| EXEC_OBJECT_PINNED
;
654 bo
->gem_handle
= open_arg
.handle
;
656 bo
->global_name
= handle
;
657 bo
->reusable
= false;
659 bo
->gtt_offset
= vma_alloc(bufmgr
, IRIS_MEMZONE_OTHER
, bo
->size
, 1);
661 _mesa_hash_table_insert(bufmgr
->handle_table
, &bo
->gem_handle
, bo
);
662 _mesa_hash_table_insert(bufmgr
->name_table
, &bo
->global_name
, bo
);
664 struct drm_i915_gem_get_tiling get_tiling
= { .handle
= bo
->gem_handle
};
665 ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_GET_TILING
, &get_tiling
);
669 bo
->tiling_mode
= get_tiling
.tiling_mode
;
670 bo
->swizzle_mode
= get_tiling
.swizzle_mode
;
671 /* XXX stride is unknown */
672 DBG("bo_create_from_handle: %d (%s)\n", handle
, bo
->name
);
675 mtx_unlock(&bufmgr
->lock
);
680 mtx_unlock(&bufmgr
->lock
);
685 bo_free(struct iris_bo
*bo
)
687 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
690 VG_NOACCESS(bo
->map_cpu
, bo
->size
);
691 munmap(bo
->map_cpu
, bo
->size
);
694 VG_NOACCESS(bo
->map_wc
, bo
->size
);
695 munmap(bo
->map_wc
, bo
->size
);
698 VG_NOACCESS(bo
->map_gtt
, bo
->size
);
699 munmap(bo
->map_gtt
, bo
->size
);
703 struct hash_entry
*entry
;
705 if (bo
->global_name
) {
706 entry
= _mesa_hash_table_search(bufmgr
->name_table
, &bo
->global_name
);
707 _mesa_hash_table_remove(bufmgr
->name_table
, entry
);
710 entry
= _mesa_hash_table_search(bufmgr
->handle_table
, &bo
->gem_handle
);
711 _mesa_hash_table_remove(bufmgr
->handle_table
, entry
);
714 vma_free(bo
->bufmgr
, bo
->gtt_offset
, bo
->size
);
716 /* Close this object */
717 struct drm_gem_close close
= { .handle
= bo
->gem_handle
};
718 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_GEM_CLOSE
, &close
);
720 DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
721 bo
->gem_handle
, bo
->name
, strerror(errno
));
726 /** Frees all cached buffers significantly older than @time. */
728 cleanup_bo_cache(struct iris_bufmgr
*bufmgr
, time_t time
)
732 if (bufmgr
->time
== time
)
735 for (i
= 0; i
< bufmgr
->num_buckets
; i
++) {
736 struct bo_cache_bucket
*bucket
= &bufmgr
->cache_bucket
[i
];
738 list_for_each_entry_safe(struct iris_bo
, bo
, &bucket
->head
, head
) {
739 if (time
- bo
->free_time
<= 1)
752 bo_unreference_final(struct iris_bo
*bo
, time_t time
)
754 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
755 struct bo_cache_bucket
*bucket
;
757 DBG("bo_unreference final: %d (%s)\n", bo
->gem_handle
, bo
->name
);
759 bucket
= bucket_for_size(bufmgr
, bo
->size
);
760 /* Put the buffer into our internal cache for reuse if we can. */
761 if (bufmgr
->bo_reuse
&& bo
->reusable
&& bucket
!= NULL
&&
762 iris_bo_madvise(bo
, I915_MADV_DONTNEED
)) {
763 bo
->free_time
= time
;
766 list_addtail(&bo
->head
, &bucket
->head
);
773 iris_bo_unreference(struct iris_bo
*bo
)
778 assert(p_atomic_read(&bo
->refcount
) > 0);
780 if (atomic_add_unless(&bo
->refcount
, -1, 1)) {
781 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
782 struct timespec time
;
784 clock_gettime(CLOCK_MONOTONIC
, &time
);
786 mtx_lock(&bufmgr
->lock
);
788 if (p_atomic_dec_zero(&bo
->refcount
)) {
789 bo_unreference_final(bo
, time
.tv_sec
);
790 cleanup_bo_cache(bufmgr
, time
.tv_sec
);
793 mtx_unlock(&bufmgr
->lock
);
798 bo_wait_with_stall_warning(struct pipe_debug_callback
*dbg
,
802 bool busy
= dbg
&& !bo
->idle
;
803 double elapsed
= unlikely(busy
) ? -get_time() : 0.0;
805 iris_bo_wait_rendering(bo
);
807 if (unlikely(busy
)) {
808 elapsed
+= get_time();
809 if (elapsed
> 1e-5) /* 0.01ms */ {
810 perf_debug(dbg
, "%s a busy \"%s\" BO stalled and took %.03f ms.\n",
811 action
, bo
->name
, elapsed
* 1000);
817 print_flags(unsigned flags
)
819 if (flags
& MAP_READ
)
821 if (flags
& MAP_WRITE
)
823 if (flags
& MAP_ASYNC
)
825 if (flags
& MAP_PERSISTENT
)
827 if (flags
& MAP_COHERENT
)
835 iris_bo_map_cpu(struct pipe_debug_callback
*dbg
,
836 struct iris_bo
*bo
, unsigned flags
)
838 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
840 /* We disallow CPU maps for writing to non-coherent buffers, as the
841 * CPU map can become invalidated when a batch is flushed out, which
842 * can happen at unpredictable times. You should use WC maps instead.
844 assert(bo
->cache_coherent
|| !(flags
& MAP_WRITE
));
847 DBG("iris_bo_map_cpu: %d (%s)\n", bo
->gem_handle
, bo
->name
);
849 struct drm_i915_gem_mmap mmap_arg
= {
850 .handle
= bo
->gem_handle
,
853 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_MMAP
, &mmap_arg
);
856 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
857 __FILE__
, __LINE__
, bo
->gem_handle
, bo
->name
, strerror(errno
));
860 void *map
= (void *) (uintptr_t) mmap_arg
.addr_ptr
;
861 VG_DEFINED(map
, bo
->size
);
863 if (p_atomic_cmpxchg(&bo
->map_cpu
, NULL
, map
)) {
864 VG_NOACCESS(map
, bo
->size
);
865 munmap(map
, bo
->size
);
870 DBG("iris_bo_map_cpu: %d (%s) -> %p, ", bo
->gem_handle
, bo
->name
,
874 if (!(flags
& MAP_ASYNC
)) {
875 bo_wait_with_stall_warning(dbg
, bo
, "CPU mapping");
878 if (!bo
->cache_coherent
&& !bo
->bufmgr
->has_llc
) {
879 /* If we're reusing an existing CPU mapping, the CPU caches may
880 * contain stale data from the last time we read from that mapping.
881 * (With the BO cache, it might even be data from a previous buffer!)
882 * Even if it's a brand new mapping, the kernel may have zeroed the
883 * buffer via CPU writes.
885 * We need to invalidate those cachelines so that we see the latest
886 * contents, and so long as we only read from the CPU mmap we do not
887 * need to write those cachelines back afterwards.
889 * On LLC, the emprical evidence suggests that writes from the GPU
890 * that bypass the LLC (i.e. for scanout) do *invalidate* the CPU
891 * cachelines. (Other reads, such as the display engine, bypass the
892 * LLC entirely requiring us to keep dirty pixels for the scanout
895 gen_invalidate_range(bo
->map_cpu
, bo
->size
);
902 iris_bo_map_wc(struct pipe_debug_callback
*dbg
,
903 struct iris_bo
*bo
, unsigned flags
)
905 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
908 DBG("iris_bo_map_wc: %d (%s)\n", bo
->gem_handle
, bo
->name
);
910 struct drm_i915_gem_mmap mmap_arg
= {
911 .handle
= bo
->gem_handle
,
913 .flags
= I915_MMAP_WC
,
915 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_MMAP
, &mmap_arg
);
918 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
919 __FILE__
, __LINE__
, bo
->gem_handle
, bo
->name
, strerror(errno
));
923 void *map
= (void *) (uintptr_t) mmap_arg
.addr_ptr
;
924 VG_DEFINED(map
, bo
->size
);
926 if (p_atomic_cmpxchg(&bo
->map_wc
, NULL
, map
)) {
927 VG_NOACCESS(map
, bo
->size
);
928 munmap(map
, bo
->size
);
933 DBG("iris_bo_map_wc: %d (%s) -> %p\n", bo
->gem_handle
, bo
->name
, bo
->map_wc
);
936 if (!(flags
& MAP_ASYNC
)) {
937 bo_wait_with_stall_warning(dbg
, bo
, "WC mapping");
944 * Perform an uncached mapping via the GTT.
946 * Write access through the GTT is not quite fully coherent. On low power
947 * systems especially, like modern Atoms, we can observe reads from RAM before
948 * the write via GTT has landed. A write memory barrier that flushes the Write
949 * Combining Buffer (i.e. sfence/mfence) is not sufficient to order the later
950 * read after the write as the GTT write suffers a small delay through the GTT
951 * indirection. The kernel uses an uncached mmio read to ensure the GTT write
952 * is ordered with reads (either by the GPU, WB or WC) and unconditionally
953 * flushes prior to execbuf submission. However, if we are not informing the
954 * kernel about our GTT writes, it will not flush before earlier access, such
955 * as when using the cmdparser. Similarly, we need to be careful if we should
956 * ever issue a CPU read immediately following a GTT write.
958 * Telling the kernel about write access also has one more important
959 * side-effect. Upon receiving notification about the write, it cancels any
960 * scanout buffering for FBC/PSR and friends. Later FBC/PSR is then flushed by
961 * either SW_FINISH or DIRTYFB. The presumption is that we never write to the
962 * actual scanout via a mmaping, only to a backbuffer and so all the FBC/PSR
963 * tracking is handled on the buffer exchange instead.
966 iris_bo_map_gtt(struct pipe_debug_callback
*dbg
,
967 struct iris_bo
*bo
, unsigned flags
)
969 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
971 /* Get a mapping of the buffer if we haven't before. */
972 if (bo
->map_gtt
== NULL
) {
973 DBG("bo_map_gtt: mmap %d (%s)\n", bo
->gem_handle
, bo
->name
);
975 struct drm_i915_gem_mmap_gtt mmap_arg
= { .handle
= bo
->gem_handle
};
977 /* Get the fake offset back... */
978 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_MMAP_GTT
, &mmap_arg
);
980 DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
981 __FILE__
, __LINE__
, bo
->gem_handle
, bo
->name
, strerror(errno
));
986 void *map
= mmap(0, bo
->size
, PROT_READ
| PROT_WRITE
,
987 MAP_SHARED
, bufmgr
->fd
, mmap_arg
.offset
);
988 if (map
== MAP_FAILED
) {
989 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
990 __FILE__
, __LINE__
, bo
->gem_handle
, bo
->name
, strerror(errno
));
994 /* We don't need to use VALGRIND_MALLOCLIKE_BLOCK because Valgrind will
995 * already intercept this mmap call. However, for consistency between
996 * all the mmap paths, we mark the pointer as defined now and mark it
997 * as inaccessible afterwards.
999 VG_DEFINED(map
, bo
->size
);
1001 if (p_atomic_cmpxchg(&bo
->map_gtt
, NULL
, map
)) {
1002 VG_NOACCESS(map
, bo
->size
);
1003 munmap(map
, bo
->size
);
1006 assert(bo
->map_gtt
);
1008 DBG("bo_map_gtt: %d (%s) -> %p, ", bo
->gem_handle
, bo
->name
, bo
->map_gtt
);
1011 if (!(flags
& MAP_ASYNC
)) {
1012 bo_wait_with_stall_warning(dbg
, bo
, "GTT mapping");
1019 can_map_cpu(struct iris_bo
*bo
, unsigned flags
)
1021 if (bo
->cache_coherent
)
1024 /* Even if the buffer itself is not cache-coherent (such as a scanout), on
1025 * an LLC platform reads always are coherent (as they are performed via the
1026 * central system agent). It is just the writes that we need to take special
1027 * care to ensure that land in main memory and not stick in the CPU cache.
1029 if (!(flags
& MAP_WRITE
) && bo
->bufmgr
->has_llc
)
1032 /* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
1033 * across batch flushes where the kernel will change cache domains of the
1034 * bo, invalidating continued access to the CPU mmap on non-LLC device.
1036 * Similarly, ASYNC typically means that the buffer will be accessed via
1037 * both the CPU and the GPU simultaneously. Batches may be executed that
1038 * use the BO even while it is mapped. While OpenGL technically disallows
1039 * most drawing while non-persistent mappings are active, we may still use
1040 * the GPU for blits or other operations, causing batches to happen at
1041 * inconvenient times.
1043 if (flags
& (MAP_PERSISTENT
| MAP_COHERENT
| MAP_ASYNC
))
1046 return !(flags
& MAP_WRITE
);
1050 iris_bo_map(struct pipe_debug_callback
*dbg
,
1051 struct iris_bo
*bo
, unsigned flags
)
1053 if (bo
->tiling_mode
!= I915_TILING_NONE
&& !(flags
& MAP_RAW
))
1054 return iris_bo_map_gtt(dbg
, bo
, flags
);
1058 if (can_map_cpu(bo
, flags
))
1059 map
= iris_bo_map_cpu(dbg
, bo
, flags
);
1061 map
= iris_bo_map_wc(dbg
, bo
, flags
);
1063 /* Allow the attempt to fail by falling back to the GTT where necessary.
1065 * Not every buffer can be mmaped directly using the CPU (or WC), for
1066 * example buffers that wrap stolen memory or are imported from other
1067 * devices. For those, we have little choice but to use a GTT mmapping.
1068 * However, if we use a slow GTT mmapping for reads where we expected fast
1069 * access, that order of magnitude difference in throughput will be clearly
1070 * expressed by angry users.
1072 * We skip MAP_RAW because we want to avoid map_gtt's fence detiling.
1074 if (!map
&& !(flags
& MAP_RAW
)) {
1075 perf_debug(dbg
, "Fallback GTT mapping for %s with access flags %x\n",
1077 map
= iris_bo_map_gtt(dbg
, bo
, flags
);
1084 iris_bo_subdata(struct iris_bo
*bo
, uint64_t offset
,
1085 uint64_t size
, const void *data
)
1087 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
1089 struct drm_i915_gem_pwrite pwrite
= {
1090 .handle
= bo
->gem_handle
,
1093 .data_ptr
= (uint64_t) (uintptr_t) data
,
1096 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_PWRITE
, &pwrite
);
1099 DBG("%s:%d: Error writing data to buffer %d: "
1100 "(%"PRIu64
" %"PRIu64
") %s .\n",
1101 __FILE__
, __LINE__
, bo
->gem_handle
, offset
, size
, strerror(errno
));
1107 /** Waits for all GPU rendering with the object to have completed. */
1109 iris_bo_wait_rendering(struct iris_bo
*bo
)
1111 /* We require a kernel recent enough for WAIT_IOCTL support.
1112 * See intel_init_bufmgr()
1114 iris_bo_wait(bo
, -1);
1118 * Waits on a BO for the given amount of time.
1120 * @bo: buffer object to wait for
1121 * @timeout_ns: amount of time to wait in nanoseconds.
1122 * If value is less than 0, an infinite wait will occur.
1124 * Returns 0 if the wait was successful ie. the last batch referencing the
1125 * object has completed within the allotted time. Otherwise some negative return
1126 * value describes the error. Of particular interest is -ETIME when the wait has
1127 * failed to yield the desired result.
1129 * Similar to iris_bo_wait_rendering except a timeout parameter allows
1130 * the operation to give up after a certain amount of time. Another subtle
1131 * difference is the internal locking semantics are different (this variant does
1132 * not hold the lock for the duration of the wait). This makes the wait subject
1133 * to a larger userspace race window.
1135 * The implementation shall wait until the object is no longer actively
1136 * referenced within a batch buffer at the time of the call. The wait will
1137 * not guarantee that the buffer is re-issued via another thread, or an flinked
1138 * handle. Userspace must make sure this race does not occur if such precision
1141 * Note that some kernels have broken the inifite wait for negative values
1142 * promise, upgrade to latest stable kernels if this is the case.
1145 iris_bo_wait(struct iris_bo
*bo
, int64_t timeout_ns
)
1147 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
1149 /* If we know it's idle, don't bother with the kernel round trip */
1150 if (bo
->idle
&& !bo
->external
)
1153 struct drm_i915_gem_wait wait
= {
1154 .bo_handle
= bo
->gem_handle
,
1155 .timeout_ns
= timeout_ns
,
1157 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_WAIT
, &wait
);
1167 iris_bufmgr_destroy(struct iris_bufmgr
*bufmgr
)
1169 mtx_destroy(&bufmgr
->lock
);
1171 /* Free any cached buffer objects we were going to reuse */
1172 for (int i
= 0; i
< bufmgr
->num_buckets
; i
++) {
1173 struct bo_cache_bucket
*bucket
= &bufmgr
->cache_bucket
[i
];
1175 list_for_each_entry_safe(struct iris_bo
, bo
, &bucket
->head
, head
) {
1176 list_del(&bo
->head
);
1181 for (int i
= 0; i
< IRIS_MEMZONE_COUNT
; i
++)
1182 util_dynarray_fini(&bucket
->vma_list
[i
]);
1185 _mesa_hash_table_destroy(bufmgr
->name_table
, NULL
);
1186 _mesa_hash_table_destroy(bufmgr
->handle_table
, NULL
);
1192 bo_set_tiling_internal(struct iris_bo
*bo
, uint32_t tiling_mode
,
1195 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
1196 struct drm_i915_gem_set_tiling set_tiling
;
1199 if (bo
->global_name
== 0 &&
1200 tiling_mode
== bo
->tiling_mode
&& stride
== bo
->stride
)
1203 memset(&set_tiling
, 0, sizeof(set_tiling
));
1205 /* set_tiling is slightly broken and overwrites the
1206 * input on the error path, so we have to open code
1209 set_tiling
.handle
= bo
->gem_handle
;
1210 set_tiling
.tiling_mode
= tiling_mode
;
1211 set_tiling
.stride
= stride
;
1213 ret
= ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_SET_TILING
, &set_tiling
);
1214 } while (ret
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
1218 bo
->tiling_mode
= set_tiling
.tiling_mode
;
1219 bo
->swizzle_mode
= set_tiling
.swizzle_mode
;
1220 bo
->stride
= set_tiling
.stride
;
1225 iris_bo_get_tiling(struct iris_bo
*bo
, uint32_t *tiling_mode
,
1226 uint32_t *swizzle_mode
)
1228 *tiling_mode
= bo
->tiling_mode
;
1229 *swizzle_mode
= bo
->swizzle_mode
;
1234 iris_bo_import_dmabuf(struct iris_bufmgr
*bufmgr
, int prime_fd
)
1239 mtx_lock(&bufmgr
->lock
);
1240 int ret
= drmPrimeFDToHandle(bufmgr
->fd
, prime_fd
, &handle
);
1242 DBG("import_dmabuf: failed to obtain handle from fd: %s\n",
1244 mtx_unlock(&bufmgr
->lock
);
1249 * See if the kernel has already returned this buffer to us. Just as
1250 * for named buffers, we must not create two bo's pointing at the same
1253 bo
= hash_find_bo(bufmgr
->handle_table
, handle
);
1255 iris_bo_reference(bo
);
1259 bo
= calloc(1, sizeof(*bo
));
1263 p_atomic_set(&bo
->refcount
, 1);
1265 /* Determine size of bo. The fd-to-handle ioctl really should
1266 * return the size, but it doesn't. If we have kernel 3.12 or
1267 * later, we can lseek on the prime fd to get the size. Older
1268 * kernels will just fail, in which case we fall back to the
1269 * provided (estimated or guess size). */
1270 ret
= lseek(prime_fd
, 0, SEEK_END
);
1274 bo
->bufmgr
= bufmgr
;
1275 bo
->kflags
= EXEC_OBJECT_SUPPORTS_48B_ADDRESS
| EXEC_OBJECT_PINNED
;
1277 bo
->gem_handle
= handle
;
1278 _mesa_hash_table_insert(bufmgr
->handle_table
, &bo
->gem_handle
, bo
);
1281 bo
->reusable
= false;
1282 bo
->external
= true;
1283 bo
->gtt_offset
= vma_alloc(bufmgr
, IRIS_MEMZONE_OTHER
, bo
->size
, 1);
1285 struct drm_i915_gem_get_tiling get_tiling
= { .handle
= bo
->gem_handle
};
1286 if (drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_GET_TILING
, &get_tiling
))
1289 bo
->tiling_mode
= get_tiling
.tiling_mode
;
1290 bo
->swizzle_mode
= get_tiling
.swizzle_mode
;
1291 /* XXX stride is unknown */
1294 mtx_unlock(&bufmgr
->lock
);
1299 mtx_unlock(&bufmgr
->lock
);
1304 iris_bo_make_external(struct iris_bo
*bo
)
1306 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
1308 if (!bo
->external
) {
1309 mtx_lock(&bufmgr
->lock
);
1310 if (!bo
->external
) {
1311 _mesa_hash_table_insert(bufmgr
->handle_table
, &bo
->gem_handle
, bo
);
1312 bo
->external
= true;
1314 mtx_unlock(&bufmgr
->lock
);
1319 iris_bo_export_dmabuf(struct iris_bo
*bo
, int *prime_fd
)
1321 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
1323 iris_bo_make_external(bo
);
1325 if (drmPrimeHandleToFD(bufmgr
->fd
, bo
->gem_handle
,
1326 DRM_CLOEXEC
, prime_fd
) != 0)
1329 bo
->reusable
= false;
1335 iris_bo_export_gem_handle(struct iris_bo
*bo
)
1337 iris_bo_make_external(bo
);
1339 return bo
->gem_handle
;
1343 iris_bo_flink(struct iris_bo
*bo
, uint32_t *name
)
1345 struct iris_bufmgr
*bufmgr
= bo
->bufmgr
;
1347 if (!bo
->global_name
) {
1348 struct drm_gem_flink flink
= { .handle
= bo
->gem_handle
};
1350 if (drm_ioctl(bufmgr
->fd
, DRM_IOCTL_GEM_FLINK
, &flink
))
1353 iris_bo_make_external(bo
);
1354 mtx_lock(&bufmgr
->lock
);
1355 if (!bo
->global_name
) {
1356 bo
->global_name
= flink
.name
;
1357 _mesa_hash_table_insert(bufmgr
->name_table
, &bo
->global_name
, bo
);
1359 mtx_unlock(&bufmgr
->lock
);
1361 bo
->reusable
= false;
1364 *name
= bo
->global_name
;
1369 * Enables unlimited caching of buffer objects for reuse.
1371 * This is potentially very memory expensive, as the cache at each bucket
1372 * size is only bounded by how many buffers of that size we've managed to have
1373 * in flight at once.
1376 iris_bufmgr_enable_reuse(struct iris_bufmgr
*bufmgr
)
1378 bufmgr
->bo_reuse
= true;
1382 add_bucket(struct iris_bufmgr
*bufmgr
, int size
)
1384 unsigned int i
= bufmgr
->num_buckets
;
1386 assert(i
< ARRAY_SIZE(bufmgr
->cache_bucket
));
1388 list_inithead(&bufmgr
->cache_bucket
[i
].head
);
1389 for (int z
= 0; z
< IRIS_MEMZONE_COUNT
; z
++)
1390 util_dynarray_init(&bufmgr
->cache_bucket
[i
].vma_list
[z
], NULL
);
1391 bufmgr
->cache_bucket
[i
].size
= size
;
1392 bufmgr
->num_buckets
++;
1394 assert(bucket_for_size(bufmgr
, size
) == &bufmgr
->cache_bucket
[i
]);
1395 assert(bucket_for_size(bufmgr
, size
- 2048) == &bufmgr
->cache_bucket
[i
]);
1396 assert(bucket_for_size(bufmgr
, size
+ 1) != &bufmgr
->cache_bucket
[i
]);
1400 init_cache_buckets(struct iris_bufmgr
*bufmgr
)
1402 uint64_t size
, cache_max_size
= 64 * 1024 * 1024;
1404 /* OK, so power of two buckets was too wasteful of memory.
1405 * Give 3 other sizes between each power of two, to hopefully
1406 * cover things accurately enough. (The alternative is
1407 * probably to just go for exact matching of sizes, and assume
1408 * that for things like composited window resize the tiled
1409 * width/height alignment and rounding of sizes to pages will
1410 * get us useful cache hit rates anyway)
1412 add_bucket(bufmgr
, PAGE_SIZE
);
1413 add_bucket(bufmgr
, PAGE_SIZE
* 2);
1414 add_bucket(bufmgr
, PAGE_SIZE
* 3);
1416 /* Initialize the linked lists for BO reuse cache. */
1417 for (size
= 4 * PAGE_SIZE
; size
<= cache_max_size
; size
*= 2) {
1418 add_bucket(bufmgr
, size
);
1420 add_bucket(bufmgr
, size
+ size
* 1 / 4);
1421 add_bucket(bufmgr
, size
+ size
* 2 / 4);
1422 add_bucket(bufmgr
, size
+ size
* 3 / 4);
1427 iris_create_hw_context(struct iris_bufmgr
*bufmgr
)
1429 struct drm_i915_gem_context_create create
= { };
1430 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_CONTEXT_CREATE
, &create
);
1432 DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno
));
1436 return create
.ctx_id
;
1440 iris_hw_context_set_priority(struct iris_bufmgr
*bufmgr
,
1444 struct drm_i915_gem_context_param p
= {
1446 .param
= I915_CONTEXT_PARAM_PRIORITY
,
1452 if (drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM
, &p
))
1459 iris_destroy_hw_context(struct iris_bufmgr
*bufmgr
, uint32_t ctx_id
)
1461 struct drm_i915_gem_context_destroy d
= { .ctx_id
= ctx_id
};
1464 drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY
, &d
) != 0) {
1465 fprintf(stderr
, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1471 iris_reg_read(struct iris_bufmgr
*bufmgr
, uint32_t offset
, uint64_t *result
)
1473 struct drm_i915_reg_read reg_read
= { .offset
= offset
};
1474 int ret
= drm_ioctl(bufmgr
->fd
, DRM_IOCTL_I915_REG_READ
, ®_read
);
1476 *result
= reg_read
.val
;
1481 * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1482 * and manage map buffer objections.
1484 * \param fd File descriptor of the opened DRM device.
1486 struct iris_bufmgr
*
1487 iris_bufmgr_init(struct gen_device_info
*devinfo
, int fd
)
1489 struct iris_bufmgr
*bufmgr
= calloc(1, sizeof(*bufmgr
));
1493 /* Handles to buffer objects belong to the device fd and are not
1494 * reference counted by the kernel. If the same fd is used by
1495 * multiple parties (threads sharing the same screen bufmgr, or
1496 * even worse the same device fd passed to multiple libraries)
1497 * ownership of those handles is shared by those independent parties.
1499 * Don't do this! Ensure that each library/bufmgr has its own device
1500 * fd so that its namespace does not clash with another.
1504 if (mtx_init(&bufmgr
->lock
, mtx_plain
) != 0) {
1509 bufmgr
->has_llc
= devinfo
->has_llc
;
1511 const uint64_t _4GB
= 1ull << 32;
1513 util_vma_heap_init(&bufmgr
->vma_allocator
[IRIS_MEMZONE_SHADER
],
1515 util_vma_heap_init(&bufmgr
->vma_allocator
[IRIS_MEMZONE_SURFACE
],
1517 util_vma_heap_init(&bufmgr
->vma_allocator
[IRIS_MEMZONE_DYNAMIC
],
1519 util_vma_heap_init(&bufmgr
->vma_allocator
[IRIS_MEMZONE_OTHER
],
1520 3 * _4GB
, (1ull << 48) - 3 * _4GB
);
1522 init_cache_buckets(bufmgr
);
1524 bufmgr
->name_table
=
1525 _mesa_hash_table_create(NULL
, key_hash_uint
, key_uint_equal
);
1526 bufmgr
->handle_table
=
1527 _mesa_hash_table_create(NULL
, key_hash_uint
, key_uint_equal
);