i965: disable shadow batches when batch debugging.
[mesa.git] / src / mesa / drivers / dri / i965 / brw_bufmgr.c
1 /*
2 * Copyright © 2007 Red Hat Inc.
3 * Copyright © 2007-2017 Intel Corporation
4 * Copyright © 2006 VMware, Inc.
5 * All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the next
15 * paragraph) shall be included in all copies or substantial portions of the
16 * Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 * IN THE SOFTWARE.
25 */
26
27 /*
28 * Authors: Thomas Hellström <thellstrom@vmware.com>
29 * Keith Whitwell <keithw@vmware.com>
30 * Eric Anholt <eric@anholt.net>
31 * Dave Airlie <airlied@linux.ie>
32 */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37
38 #include <xf86drm.h>
39 #include <util/u_atomic.h>
40 #include <fcntl.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <assert.h>
46 #include <sys/ioctl.h>
47 #include <sys/stat.h>
48 #include <sys/types.h>
49 #include <stdbool.h>
50
51 #include "errno.h"
52 #include "common/gen_clflush.h"
53 #include "dev/gen_debug.h"
54 #include "common/gen_gem.h"
55 #include "dev/gen_device_info.h"
56 #include "libdrm_macros.h"
57 #include "main/macros.h"
58 #include "util/macros.h"
59 #include "util/hash_table.h"
60 #include "util/list.h"
61 #include "util/u_dynarray.h"
62 #include "util/vma.h"
63 #include "brw_bufmgr.h"
64 #include "brw_context.h"
65 #include "string.h"
66
67 #include "drm-uapi/i915_drm.h"
68
69 #ifdef HAVE_VALGRIND
70 #include <valgrind.h>
71 #include <memcheck.h>
72 #define VG(x) x
73 #else
74 #define VG(x)
75 #endif
76
77 /* VALGRIND_FREELIKE_BLOCK unfortunately does not actually undo the earlier
78 * VALGRIND_MALLOCLIKE_BLOCK but instead leaves vg convinced the memory is
79 * leaked. All because it does not call VG(cli_free) from its
80 * VG_USERREQ__FREELIKE_BLOCK handler. Instead of treating the memory like
81 * and allocation, we mark it available for use upon mmapping and remove
82 * it upon unmapping.
83 */
84 #define VG_DEFINED(ptr, size) VG(VALGRIND_MAKE_MEM_DEFINED(ptr, size))
85 #define VG_NOACCESS(ptr, size) VG(VALGRIND_MAKE_MEM_NOACCESS(ptr, size))
86
87 #define PAGE_SIZE 4096
88
89 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
90
91 static inline int
92 atomic_add_unless(int *v, int add, int unless)
93 {
94 int c, old;
95 c = p_atomic_read(v);
96 while (c != unless && (old = p_atomic_cmpxchg(v, c, c + add)) != c)
97 c = old;
98 return c == unless;
99 }
100
101 /**
102 * i965 fixed-size bucketing VMA allocator.
103 *
104 * The BO cache maintains "cache buckets" for buffers of various sizes.
105 * All buffers in a given bucket are identically sized - when allocating,
106 * we always round up to the bucket size. This means that virtually all
107 * allocations are fixed-size; only buffers which are too large to fit in
108 * a bucket can be variably-sized.
109 *
110 * We create an allocator for each bucket. Each contains a free-list, where
111 * each node contains a <starting address, 64-bit bitmap> pair. Each bit
112 * represents a bucket-sized block of memory. (At the first level, each
113 * bit corresponds to a page. For the second bucket, bits correspond to
114 * two pages, and so on.) 1 means a block is free, and 0 means it's in-use.
115 * The lowest bit in the bitmap is for the first block.
116 *
117 * This makes allocations cheap - any bit of any node will do. We can pick
118 * the head of the list and use ffs() to find a free block. If there are
119 * none, we allocate 64 blocks from a larger allocator - either a bigger
120 * bucketing allocator, or a fallback top-level allocator for large objects.
121 */
122 struct vma_bucket_node {
123 uint64_t start_address;
124 uint64_t bitmap;
125 };
126
127 struct bo_cache_bucket {
128 /** List of cached BOs. */
129 struct list_head head;
130
131 /** Size of this bucket, in bytes. */
132 uint64_t size;
133
134 /** List of vma_bucket_nodes. */
135 struct util_dynarray vma_list[BRW_MEMZONE_COUNT];
136 };
137
138 struct brw_bufmgr {
139 uint32_t refcount;
140
141 struct list_head link;
142
143 int fd;
144
145 mtx_t lock;
146
147 /** Array of lists of cached gem objects of power-of-two sizes */
148 struct bo_cache_bucket cache_bucket[14 * 4];
149 int num_buckets;
150 time_t time;
151
152 struct hash_table *name_table;
153 struct hash_table *handle_table;
154
155 struct util_vma_heap vma_allocator[BRW_MEMZONE_COUNT];
156
157 bool has_llc:1;
158 bool has_mmap_wc:1;
159 bool has_mmap_offset:1;
160 bool bo_reuse:1;
161
162 uint64_t initial_kflags;
163 };
164
165 static mtx_t global_bufmgr_list_mutex = _MTX_INITIALIZER_NP;
166 static struct list_head global_bufmgr_list = {
167 .next = &global_bufmgr_list,
168 .prev = &global_bufmgr_list,
169 };
170
171 static int bo_set_tiling_internal(struct brw_bo *bo, uint32_t tiling_mode,
172 uint32_t stride);
173
174 static void bo_free(struct brw_bo *bo);
175
176 static uint64_t vma_alloc(struct brw_bufmgr *bufmgr,
177 enum brw_memory_zone memzone,
178 uint64_t size, uint64_t alignment);
179
180 static struct brw_bo *
181 hash_find_bo(struct hash_table *ht, unsigned int key)
182 {
183 struct hash_entry *entry = _mesa_hash_table_search(ht, &key);
184 return entry ? (struct brw_bo *) entry->data : NULL;
185 }
186
187 static uint64_t
188 bo_tile_size(struct brw_bufmgr *bufmgr, uint64_t size, uint32_t tiling)
189 {
190 if (tiling == I915_TILING_NONE)
191 return size;
192
193 /* 965+ just need multiples of page size for tiling */
194 return ALIGN(size, PAGE_SIZE);
195 }
196
197 /*
198 * Round a given pitch up to the minimum required for X tiling on a
199 * given chip. We use 512 as the minimum to allow for a later tiling
200 * change.
201 */
202 static uint32_t
203 bo_tile_pitch(struct brw_bufmgr *bufmgr, uint32_t pitch, uint32_t tiling)
204 {
205 unsigned long tile_width;
206
207 /* If untiled, then just align it so that we can do rendering
208 * to it with the 3D engine.
209 */
210 if (tiling == I915_TILING_NONE)
211 return ALIGN(pitch, 64);
212
213 if (tiling == I915_TILING_X)
214 tile_width = 512;
215 else
216 tile_width = 128;
217
218 /* 965 is flexible */
219 return ALIGN(pitch, tile_width);
220 }
221
222 /**
223 * This function finds the correct bucket fit for the input size.
224 * The function works with O(1) complexity when the requested size
225 * was queried instead of iterating the size through all the buckets.
226 */
227 static struct bo_cache_bucket *
228 bucket_for_size(struct brw_bufmgr *bufmgr, uint64_t size)
229 {
230 /* Calculating the pages and rounding up to the page size. */
231 const unsigned pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
232
233 /* Row Bucket sizes clz((x-1) | 3) Row Column
234 * in pages stride size
235 * 0: 1 2 3 4 -> 30 30 30 30 4 1
236 * 1: 5 6 7 8 -> 29 29 29 29 4 1
237 * 2: 10 12 14 16 -> 28 28 28 28 8 2
238 * 3: 20 24 28 32 -> 27 27 27 27 16 4
239 */
240 const unsigned row = 30 - __builtin_clz((pages - 1) | 3);
241 const unsigned row_max_pages = 4 << row;
242
243 /* The '& ~2' is the special case for row 1. In row 1, max pages /
244 * 2 is 2, but the previous row maximum is zero (because there is
245 * no previous row). All row maximum sizes are power of 2, so that
246 * is the only case where that bit will be set.
247 */
248 const unsigned prev_row_max_pages = (row_max_pages / 2) & ~2;
249 int col_size_log2 = row - 1;
250 col_size_log2 += (col_size_log2 < 0);
251
252 const unsigned col = (pages - prev_row_max_pages +
253 ((1 << col_size_log2) - 1)) >> col_size_log2;
254
255 /* Calculating the index based on the row and column. */
256 const unsigned index = (row * 4) + (col - 1);
257
258 return (index < bufmgr->num_buckets) ?
259 &bufmgr->cache_bucket[index] : NULL;
260 }
261
262 static enum brw_memory_zone
263 memzone_for_address(uint64_t address)
264 {
265 const uint64_t _4GB = 1ull << 32;
266
267 if (address >= _4GB)
268 return BRW_MEMZONE_OTHER;
269
270 return BRW_MEMZONE_LOW_4G;
271 }
272
273 static uint64_t
274 bucket_vma_alloc(struct brw_bufmgr *bufmgr,
275 struct bo_cache_bucket *bucket,
276 enum brw_memory_zone memzone)
277 {
278 struct util_dynarray *vma_list = &bucket->vma_list[memzone];
279 struct vma_bucket_node *node;
280
281 if (vma_list->size == 0) {
282 /* This bucket allocator is out of space - allocate a new block of
283 * memory for 64 blocks from a larger allocator (either a larger
284 * bucket or util_vma).
285 *
286 * We align the address to the node size (64 blocks) so that
287 * bucket_vma_free can easily compute the starting address of this
288 * block by rounding any address we return down to the node size.
289 *
290 * Set the first bit used, and return the start address.
291 */
292 uint64_t node_size = 64ull * bucket->size;
293 node = util_dynarray_grow(vma_list, struct vma_bucket_node, 1);
294
295 if (unlikely(!node))
296 return 0ull;
297
298 uint64_t addr = vma_alloc(bufmgr, memzone, node_size, node_size);
299 node->start_address = gen_48b_address(addr);
300 node->bitmap = ~1ull;
301 return node->start_address;
302 }
303
304 /* Pick any bit from any node - they're all the right size and free. */
305 node = util_dynarray_top_ptr(vma_list, struct vma_bucket_node);
306 int bit = ffsll(node->bitmap) - 1;
307 assert(bit >= 0 && bit <= 63);
308
309 /* Reserve the memory by clearing the bit. */
310 assert((node->bitmap & (1ull << bit)) != 0ull);
311 node->bitmap &= ~(1ull << bit);
312
313 uint64_t addr = node->start_address + bit * bucket->size;
314
315 /* If this node is now completely full, remove it from the free list. */
316 if (node->bitmap == 0ull) {
317 (void) util_dynarray_pop(vma_list, struct vma_bucket_node);
318 }
319
320 return addr;
321 }
322
323 static void
324 bucket_vma_free(struct bo_cache_bucket *bucket, uint64_t address)
325 {
326 enum brw_memory_zone memzone = memzone_for_address(address);
327 struct util_dynarray *vma_list = &bucket->vma_list[memzone];
328 const uint64_t node_bytes = 64ull * bucket->size;
329 struct vma_bucket_node *node = NULL;
330
331 /* bucket_vma_alloc allocates 64 blocks at a time, and aligns it to
332 * that 64 block size. So, we can round down to get the starting address.
333 */
334 uint64_t start = (address / node_bytes) * node_bytes;
335
336 /* Dividing the offset from start by bucket size gives us the bit index. */
337 int bit = (address - start) / bucket->size;
338
339 assert(start + bit * bucket->size == address);
340
341 util_dynarray_foreach(vma_list, struct vma_bucket_node, cur) {
342 if (cur->start_address == start) {
343 node = cur;
344 break;
345 }
346 }
347
348 if (!node) {
349 /* No node - the whole group of 64 blocks must have been in-use. */
350 node = util_dynarray_grow(vma_list, struct vma_bucket_node, 1);
351
352 if (unlikely(!node))
353 return; /* bogus, leaks some GPU VMA, but nothing we can do... */
354
355 node->start_address = start;
356 node->bitmap = 0ull;
357 }
358
359 /* Set the bit to return the memory. */
360 assert((node->bitmap & (1ull << bit)) == 0ull);
361 node->bitmap |= 1ull << bit;
362
363 /* The block might be entirely free now, and if so, we could return it
364 * to the larger allocator. But we may as well hang on to it, in case
365 * we get more allocations at this block size.
366 */
367 }
368
369 static struct bo_cache_bucket *
370 get_bucket_allocator(struct brw_bufmgr *bufmgr, uint64_t size)
371 {
372 /* Skip using the bucket allocator for very large sizes, as it allocates
373 * 64 of them and this can balloon rather quickly.
374 */
375 if (size > 1024 * PAGE_SIZE)
376 return NULL;
377
378 struct bo_cache_bucket *bucket = bucket_for_size(bufmgr, size);
379
380 if (bucket && bucket->size == size)
381 return bucket;
382
383 return NULL;
384 }
385
386 /**
387 * Allocate a section of virtual memory for a buffer, assigning an address.
388 *
389 * This uses either the bucket allocator for the given size, or the large
390 * object allocator (util_vma).
391 */
392 static uint64_t
393 vma_alloc(struct brw_bufmgr *bufmgr,
394 enum brw_memory_zone memzone,
395 uint64_t size,
396 uint64_t alignment)
397 {
398 /* Without softpin support, we let the kernel assign addresses. */
399 assert(brw_using_softpin(bufmgr));
400
401 alignment = ALIGN(alignment, PAGE_SIZE);
402
403 struct bo_cache_bucket *bucket = get_bucket_allocator(bufmgr, size);
404 uint64_t addr;
405
406 if (bucket) {
407 addr = bucket_vma_alloc(bufmgr, bucket, memzone);
408 } else {
409 addr = util_vma_heap_alloc(&bufmgr->vma_allocator[memzone], size,
410 alignment);
411 }
412
413 assert((addr >> 48ull) == 0);
414 assert((addr % alignment) == 0);
415
416 return gen_canonical_address(addr);
417 }
418
419 /**
420 * Free a virtual memory area, allowing the address to be reused.
421 */
422 static void
423 vma_free(struct brw_bufmgr *bufmgr,
424 uint64_t address,
425 uint64_t size)
426 {
427 assert(brw_using_softpin(bufmgr));
428
429 /* Un-canonicalize the address. */
430 address = gen_48b_address(address);
431
432 if (address == 0ull)
433 return;
434
435 struct bo_cache_bucket *bucket = get_bucket_allocator(bufmgr, size);
436
437 if (bucket) {
438 bucket_vma_free(bucket, address);
439 } else {
440 enum brw_memory_zone memzone = memzone_for_address(address);
441 util_vma_heap_free(&bufmgr->vma_allocator[memzone], address, size);
442 }
443 }
444
445 int
446 brw_bo_busy(struct brw_bo *bo)
447 {
448 struct brw_bufmgr *bufmgr = bo->bufmgr;
449 struct drm_i915_gem_busy busy = { .handle = bo->gem_handle };
450
451 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_BUSY, &busy);
452 if (ret == 0) {
453 bo->idle = !busy.busy;
454 return busy.busy;
455 }
456 return false;
457 }
458
459 int
460 brw_bo_madvise(struct brw_bo *bo, int state)
461 {
462 struct drm_i915_gem_madvise madv = {
463 .handle = bo->gem_handle,
464 .madv = state,
465 .retained = 1,
466 };
467
468 drmIoctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_MADVISE, &madv);
469
470 return madv.retained;
471 }
472
473 /* drop the oldest entries that have been purged by the kernel */
474 static void
475 brw_bo_cache_purge_bucket(struct brw_bufmgr *bufmgr,
476 struct bo_cache_bucket *bucket)
477 {
478 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
479 if (brw_bo_madvise(bo, I915_MADV_DONTNEED))
480 break;
481
482 list_del(&bo->head);
483 bo_free(bo);
484 }
485 }
486
487 static struct brw_bo *
488 bo_alloc_internal(struct brw_bufmgr *bufmgr,
489 const char *name,
490 uint64_t size,
491 enum brw_memory_zone memzone,
492 unsigned flags,
493 uint32_t tiling_mode,
494 uint32_t stride)
495 {
496 struct brw_bo *bo;
497 int ret;
498 struct bo_cache_bucket *bucket;
499 bool alloc_from_cache;
500 uint64_t bo_size;
501 bool busy = false;
502 bool zeroed = false;
503
504 if (flags & BO_ALLOC_BUSY)
505 busy = true;
506
507 if (flags & BO_ALLOC_ZEROED)
508 zeroed = true;
509
510 /* BUSY does doesn't really jive with ZEROED as we have to wait for it to
511 * be idle before we can memset. Just disallow that combination.
512 */
513 assert(!(busy && zeroed));
514
515 /* Round the allocated size up to a power of two number of pages. */
516 bucket = bucket_for_size(bufmgr, size);
517
518 /* If we don't have caching at this size, don't actually round the
519 * allocation up.
520 */
521 if (bucket == NULL) {
522 unsigned int page_size = getpagesize();
523 bo_size = size == 0 ? page_size : ALIGN(size, page_size);
524 } else {
525 bo_size = bucket->size;
526 }
527 assert(bo_size);
528
529 mtx_lock(&bufmgr->lock);
530 /* Get a buffer out of the cache if available */
531 retry:
532 alloc_from_cache = false;
533 if (bucket != NULL && !list_is_empty(&bucket->head)) {
534 if (busy && !zeroed) {
535 /* Allocate new render-target BOs from the tail (MRU)
536 * of the list, as it will likely be hot in the GPU
537 * cache and in the aperture for us. If the caller
538 * asked us to zero the buffer, we don't want this
539 * because we are going to mmap it.
540 */
541 bo = LIST_ENTRY(struct brw_bo, bucket->head.prev, head);
542 list_del(&bo->head);
543 alloc_from_cache = true;
544 } else {
545 /* For non-render-target BOs (where we're probably
546 * going to map it first thing in order to fill it
547 * with data), check if the last BO in the cache is
548 * unbusy, and only reuse in that case. Otherwise,
549 * allocating a new buffer is probably faster than
550 * waiting for the GPU to finish.
551 */
552 bo = LIST_ENTRY(struct brw_bo, bucket->head.next, head);
553 if (!brw_bo_busy(bo)) {
554 alloc_from_cache = true;
555 list_del(&bo->head);
556 }
557 }
558
559 if (alloc_from_cache) {
560 if (!brw_bo_madvise(bo, I915_MADV_WILLNEED)) {
561 bo_free(bo);
562 brw_bo_cache_purge_bucket(bufmgr, bucket);
563 goto retry;
564 }
565
566 if (bo_set_tiling_internal(bo, tiling_mode, stride)) {
567 bo_free(bo);
568 goto retry;
569 }
570
571 if (zeroed) {
572 void *map = brw_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
573 if (!map) {
574 bo_free(bo);
575 goto retry;
576 }
577 memset(map, 0, bo_size);
578 }
579 }
580 }
581
582 if (alloc_from_cache) {
583 /* If the cache BO isn't in the right memory zone, free the old
584 * memory and assign it a new address.
585 */
586 if ((bo->kflags & EXEC_OBJECT_PINNED) &&
587 memzone != memzone_for_address(bo->gtt_offset)) {
588 vma_free(bufmgr, bo->gtt_offset, bo->size);
589 bo->gtt_offset = 0ull;
590 }
591 } else {
592 bo = calloc(1, sizeof(*bo));
593 if (!bo)
594 goto err;
595
596 bo->size = bo_size;
597 bo->idle = true;
598
599 struct drm_i915_gem_create create = { .size = bo_size };
600
601 /* All new BOs we get from the kernel are zeroed, so we don't need to
602 * worry about that here.
603 */
604 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CREATE, &create);
605 if (ret != 0) {
606 free(bo);
607 goto err;
608 }
609
610 bo->gem_handle = create.handle;
611
612 bo->bufmgr = bufmgr;
613
614 bo->tiling_mode = I915_TILING_NONE;
615 bo->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
616 bo->stride = 0;
617
618 if (bo_set_tiling_internal(bo, tiling_mode, stride))
619 goto err_free;
620
621 /* Calling set_domain() will allocate pages for the BO outside of the
622 * struct mutex lock in the kernel, which is more efficient than waiting
623 * to create them during the first execbuf that uses the BO.
624 */
625 struct drm_i915_gem_set_domain sd = {
626 .handle = bo->gem_handle,
627 .read_domains = I915_GEM_DOMAIN_CPU,
628 .write_domain = 0,
629 };
630
631 if (drmIoctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd) != 0)
632 goto err_free;
633 }
634
635 bo->name = name;
636 p_atomic_set(&bo->refcount, 1);
637 bo->reusable = true;
638 bo->cache_coherent = bufmgr->has_llc;
639 bo->index = -1;
640 bo->kflags = bufmgr->initial_kflags;
641
642 if ((bo->kflags & EXEC_OBJECT_PINNED) && bo->gtt_offset == 0ull) {
643 bo->gtt_offset = vma_alloc(bufmgr, memzone, bo->size, 1);
644
645 if (bo->gtt_offset == 0ull)
646 goto err_free;
647 }
648
649 mtx_unlock(&bufmgr->lock);
650
651 DBG("bo_create: buf %d (%s) %llub\n", bo->gem_handle, bo->name,
652 (unsigned long long) size);
653
654 return bo;
655
656 err_free:
657 bo_free(bo);
658 err:
659 mtx_unlock(&bufmgr->lock);
660 return NULL;
661 }
662
663 struct brw_bo *
664 brw_bo_alloc(struct brw_bufmgr *bufmgr,
665 const char *name, uint64_t size,
666 enum brw_memory_zone memzone)
667 {
668 return bo_alloc_internal(bufmgr, name, size, memzone,
669 0, I915_TILING_NONE, 0);
670 }
671
672 struct brw_bo *
673 brw_bo_alloc_tiled(struct brw_bufmgr *bufmgr, const char *name,
674 uint64_t size, enum brw_memory_zone memzone,
675 uint32_t tiling_mode, uint32_t pitch,
676 unsigned flags)
677 {
678 return bo_alloc_internal(bufmgr, name, size, memzone,
679 flags, tiling_mode, pitch);
680 }
681
682 struct brw_bo *
683 brw_bo_alloc_tiled_2d(struct brw_bufmgr *bufmgr, const char *name,
684 int x, int y, int cpp, enum brw_memory_zone memzone,
685 uint32_t tiling, uint32_t *pitch, unsigned flags)
686 {
687 uint64_t size;
688 uint32_t stride;
689 unsigned long aligned_y, height_alignment;
690
691 /* If we're tiled, our allocations are in 8 or 32-row blocks,
692 * so failure to align our height means that we won't allocate
693 * enough pages.
694 *
695 * If we're untiled, we still have to align to 2 rows high
696 * because the data port accesses 2x2 blocks even if the
697 * bottom row isn't to be rendered, so failure to align means
698 * we could walk off the end of the GTT and fault. This is
699 * documented on 965, and may be the case on older chipsets
700 * too so we try to be careful.
701 */
702 aligned_y = y;
703 height_alignment = 2;
704
705 if (tiling == I915_TILING_X)
706 height_alignment = 8;
707 else if (tiling == I915_TILING_Y)
708 height_alignment = 32;
709 aligned_y = ALIGN(y, height_alignment);
710
711 stride = x * cpp;
712 stride = bo_tile_pitch(bufmgr, stride, tiling);
713 size = stride * aligned_y;
714 size = bo_tile_size(bufmgr, size, tiling);
715 *pitch = stride;
716
717 if (tiling == I915_TILING_NONE)
718 stride = 0;
719
720 return bo_alloc_internal(bufmgr, name, size, memzone,
721 flags, tiling, stride);
722 }
723
724 /**
725 * Returns a brw_bo wrapping the given buffer object handle.
726 *
727 * This can be used when one application needs to pass a buffer object
728 * to another.
729 */
730 struct brw_bo *
731 brw_bo_gem_create_from_name(struct brw_bufmgr *bufmgr,
732 const char *name, unsigned int handle)
733 {
734 struct brw_bo *bo;
735
736 /* At the moment most applications only have a few named bo.
737 * For instance, in a DRI client only the render buffers passed
738 * between X and the client are named. And since X returns the
739 * alternating names for the front/back buffer a linear search
740 * provides a sufficiently fast match.
741 */
742 mtx_lock(&bufmgr->lock);
743 bo = hash_find_bo(bufmgr->name_table, handle);
744 if (bo) {
745 brw_bo_reference(bo);
746 goto out;
747 }
748
749 struct drm_gem_open open_arg = { .name = handle };
750 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
751 if (ret != 0) {
752 DBG("Couldn't reference %s handle 0x%08x: %s\n",
753 name, handle, strerror(errno));
754 bo = NULL;
755 goto out;
756 }
757 /* Now see if someone has used a prime handle to get this
758 * object from the kernel before by looking through the list
759 * again for a matching gem_handle
760 */
761 bo = hash_find_bo(bufmgr->handle_table, open_arg.handle);
762 if (bo) {
763 brw_bo_reference(bo);
764 goto out;
765 }
766
767 bo = calloc(1, sizeof(*bo));
768 if (!bo)
769 goto out;
770
771 p_atomic_set(&bo->refcount, 1);
772
773 bo->size = open_arg.size;
774 bo->gtt_offset = 0;
775 bo->bufmgr = bufmgr;
776 bo->gem_handle = open_arg.handle;
777 bo->name = name;
778 bo->global_name = handle;
779 bo->reusable = false;
780 bo->external = true;
781 bo->kflags = bufmgr->initial_kflags;
782
783 if (bo->kflags & EXEC_OBJECT_PINNED)
784 bo->gtt_offset = vma_alloc(bufmgr, BRW_MEMZONE_OTHER, bo->size, 1);
785
786 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
787 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
788
789 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
790 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling);
791 if (ret != 0)
792 goto err_unref;
793
794 bo->tiling_mode = get_tiling.tiling_mode;
795 bo->swizzle_mode = get_tiling.swizzle_mode;
796 /* XXX stride is unknown */
797 DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
798
799 out:
800 mtx_unlock(&bufmgr->lock);
801 return bo;
802
803 err_unref:
804 bo_free(bo);
805 mtx_unlock(&bufmgr->lock);
806 return NULL;
807 }
808
809 static void
810 bo_free(struct brw_bo *bo)
811 {
812 struct brw_bufmgr *bufmgr = bo->bufmgr;
813
814 if (bo->map_cpu) {
815 VG_NOACCESS(bo->map_cpu, bo->size);
816 drm_munmap(bo->map_cpu, bo->size);
817 }
818 if (bo->map_wc) {
819 VG_NOACCESS(bo->map_wc, bo->size);
820 drm_munmap(bo->map_wc, bo->size);
821 }
822 if (bo->map_gtt) {
823 VG_NOACCESS(bo->map_gtt, bo->size);
824 drm_munmap(bo->map_gtt, bo->size);
825 }
826
827 if (bo->external) {
828 struct hash_entry *entry;
829
830 if (bo->global_name) {
831 entry = _mesa_hash_table_search(bufmgr->name_table, &bo->global_name);
832 _mesa_hash_table_remove(bufmgr->name_table, entry);
833 }
834
835 entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
836 _mesa_hash_table_remove(bufmgr->handle_table, entry);
837 }
838
839 /* Close this object */
840 struct drm_gem_close close = { .handle = bo->gem_handle };
841 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
842 if (ret != 0) {
843 DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
844 bo->gem_handle, bo->name, strerror(errno));
845 }
846
847 if (bo->kflags & EXEC_OBJECT_PINNED)
848 vma_free(bo->bufmgr, bo->gtt_offset, bo->size);
849
850 free(bo);
851 }
852
853 /** Frees all cached buffers significantly older than @time. */
854 static void
855 cleanup_bo_cache(struct brw_bufmgr *bufmgr, time_t time)
856 {
857 int i;
858
859 if (bufmgr->time == time)
860 return;
861
862 for (i = 0; i < bufmgr->num_buckets; i++) {
863 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
864
865 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
866 if (time - bo->free_time <= 1)
867 break;
868
869 list_del(&bo->head);
870
871 bo_free(bo);
872 }
873 }
874
875 bufmgr->time = time;
876 }
877
878 static void
879 bo_unreference_final(struct brw_bo *bo, time_t time)
880 {
881 struct brw_bufmgr *bufmgr = bo->bufmgr;
882 struct bo_cache_bucket *bucket;
883
884 DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
885
886 bucket = bucket_for_size(bufmgr, bo->size);
887 /* Put the buffer into our internal cache for reuse if we can. */
888 if (bufmgr->bo_reuse && bo->reusable && bucket != NULL &&
889 brw_bo_madvise(bo, I915_MADV_DONTNEED)) {
890 bo->free_time = time;
891
892 bo->name = NULL;
893
894 list_addtail(&bo->head, &bucket->head);
895 } else {
896 bo_free(bo);
897 }
898 }
899
900 void
901 brw_bo_unreference(struct brw_bo *bo)
902 {
903 if (bo == NULL)
904 return;
905
906 assert(p_atomic_read(&bo->refcount) > 0);
907
908 if (atomic_add_unless(&bo->refcount, -1, 1)) {
909 struct brw_bufmgr *bufmgr = bo->bufmgr;
910 struct timespec time;
911
912 clock_gettime(CLOCK_MONOTONIC, &time);
913
914 mtx_lock(&bufmgr->lock);
915
916 if (p_atomic_dec_zero(&bo->refcount)) {
917 bo_unreference_final(bo, time.tv_sec);
918 cleanup_bo_cache(bufmgr, time.tv_sec);
919 }
920
921 mtx_unlock(&bufmgr->lock);
922 }
923 }
924
925 static void
926 bo_wait_with_stall_warning(struct brw_context *brw,
927 struct brw_bo *bo,
928 const char *action)
929 {
930 bool busy = brw && brw->perf_debug && !bo->idle;
931 double elapsed = unlikely(busy) ? -get_time() : 0.0;
932
933 brw_bo_wait_rendering(bo);
934
935 if (unlikely(busy)) {
936 elapsed += get_time();
937 if (elapsed > 1e-5) /* 0.01ms */
938 perf_debug("%s a busy \"%s\" BO stalled and took %.03f ms.\n",
939 action, bo->name, elapsed * 1000);
940 }
941 }
942
943 static void
944 print_flags(unsigned flags)
945 {
946 if (flags & MAP_READ)
947 DBG("READ ");
948 if (flags & MAP_WRITE)
949 DBG("WRITE ");
950 if (flags & MAP_ASYNC)
951 DBG("ASYNC ");
952 if (flags & MAP_PERSISTENT)
953 DBG("PERSISTENT ");
954 if (flags & MAP_COHERENT)
955 DBG("COHERENT ");
956 if (flags & MAP_RAW)
957 DBG("RAW ");
958 DBG("\n");
959 }
960
961 static void *
962 brw_bo_gem_mmap_legacy(struct brw_context *brw, struct brw_bo *bo, bool wc)
963 {
964 struct brw_bufmgr *bufmgr = bo->bufmgr;
965
966 struct drm_i915_gem_mmap mmap_arg = {
967 .handle = bo->gem_handle,
968 .size = bo->size,
969 .flags = wc ? I915_MMAP_WC : 0,
970 };
971
972 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
973 if (ret != 0) {
974 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
975 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
976 return NULL;
977 }
978 void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
979
980 return map;
981 }
982
983 static void *
984 brw_bo_gem_mmap_offset(struct brw_context *brw, struct brw_bo *bo, bool wc)
985 {
986 struct brw_bufmgr *bufmgr = bo->bufmgr;
987
988 struct drm_i915_gem_mmap_offset mmap_arg = {
989 .handle = bo->gem_handle,
990 .flags = wc ? I915_MMAP_OFFSET_WC : I915_MMAP_OFFSET_WB,
991 };
992
993 /* Get the fake offset back */
994 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_OFFSET, &mmap_arg);
995 if (ret != 0) {
996 DBG("%s:%d: Error preparing buffer %d (%s): %s .\n",
997 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
998 return NULL;
999 }
1000
1001 /* And map it */
1002 void *map = drm_mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED,
1003 bufmgr->fd, mmap_arg.offset);
1004 if (map == MAP_FAILED) {
1005 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
1006 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
1007 return NULL;
1008 }
1009
1010 return map;
1011 }
1012
1013 static void *
1014 brw_bo_gem_mmap(struct brw_context *brw, struct brw_bo *bo, bool wc)
1015 {
1016 struct brw_bufmgr *bufmgr = bo->bufmgr;
1017
1018 if (bufmgr->has_mmap_offset)
1019 return brw_bo_gem_mmap_offset(brw, bo, wc);
1020 else
1021 return brw_bo_gem_mmap_legacy(brw, bo, wc);
1022 }
1023
1024 static void *
1025 brw_bo_map_cpu(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
1026 {
1027 /* We disallow CPU maps for writing to non-coherent buffers, as the
1028 * CPU map can become invalidated when a batch is flushed out, which
1029 * can happen at unpredictable times. You should use WC maps instead.
1030 */
1031 assert(bo->cache_coherent || !(flags & MAP_WRITE));
1032
1033 if (!bo->map_cpu) {
1034 DBG("brw_bo_map_cpu: %d (%s)\n", bo->gem_handle, bo->name);
1035
1036 void *map = brw_bo_gem_mmap(brw, bo, false);
1037 VG_DEFINED(map, bo->size);
1038
1039 if (p_atomic_cmpxchg(&bo->map_cpu, NULL, map)) {
1040 VG_NOACCESS(map, bo->size);
1041 drm_munmap(map, bo->size);
1042 }
1043 }
1044 assert(bo->map_cpu);
1045
1046 DBG("brw_bo_map_cpu: %d (%s) -> %p, ", bo->gem_handle, bo->name,
1047 bo->map_cpu);
1048 print_flags(flags);
1049
1050 if (!(flags & MAP_ASYNC)) {
1051 bo_wait_with_stall_warning(brw, bo, "CPU mapping");
1052 }
1053
1054 if (!bo->cache_coherent && !bo->bufmgr->has_llc) {
1055 /* If we're reusing an existing CPU mapping, the CPU caches may
1056 * contain stale data from the last time we read from that mapping.
1057 * (With the BO cache, it might even be data from a previous buffer!)
1058 * Even if it's a brand new mapping, the kernel may have zeroed the
1059 * buffer via CPU writes.
1060 *
1061 * We need to invalidate those cachelines so that we see the latest
1062 * contents, and so long as we only read from the CPU mmap we do not
1063 * need to write those cachelines back afterwards.
1064 *
1065 * On LLC, the emprical evidence suggests that writes from the GPU
1066 * that bypass the LLC (i.e. for scanout) do *invalidate* the CPU
1067 * cachelines. (Other reads, such as the display engine, bypass the
1068 * LLC entirely requiring us to keep dirty pixels for the scanout
1069 * out of any cache.)
1070 */
1071 gen_invalidate_range(bo->map_cpu, bo->size);
1072 }
1073
1074 return bo->map_cpu;
1075 }
1076
1077 static void *
1078 brw_bo_map_wc(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
1079 {
1080 struct brw_bufmgr *bufmgr = bo->bufmgr;
1081
1082 if (!bufmgr->has_mmap_wc)
1083 return NULL;
1084
1085 if (!bo->map_wc) {
1086 DBG("brw_bo_map_wc: %d (%s)\n", bo->gem_handle, bo->name);
1087 void *map = brw_bo_gem_mmap(brw, bo, true);
1088 VG_DEFINED(map, bo->size);
1089
1090 if (p_atomic_cmpxchg(&bo->map_wc, NULL, map)) {
1091 VG_NOACCESS(map, bo->size);
1092 drm_munmap(map, bo->size);
1093 }
1094 }
1095 assert(bo->map_wc);
1096
1097 DBG("brw_bo_map_wc: %d (%s) -> %p\n", bo->gem_handle, bo->name, bo->map_wc);
1098 print_flags(flags);
1099
1100 if (!(flags & MAP_ASYNC)) {
1101 bo_wait_with_stall_warning(brw, bo, "WC mapping");
1102 }
1103
1104 return bo->map_wc;
1105 }
1106
1107 /**
1108 * Perform an uncached mapping via the GTT.
1109 *
1110 * Write access through the GTT is not quite fully coherent. On low power
1111 * systems especially, like modern Atoms, we can observe reads from RAM before
1112 * the write via GTT has landed. A write memory barrier that flushes the Write
1113 * Combining Buffer (i.e. sfence/mfence) is not sufficient to order the later
1114 * read after the write as the GTT write suffers a small delay through the GTT
1115 * indirection. The kernel uses an uncached mmio read to ensure the GTT write
1116 * is ordered with reads (either by the GPU, WB or WC) and unconditionally
1117 * flushes prior to execbuf submission. However, if we are not informing the
1118 * kernel about our GTT writes, it will not flush before earlier access, such
1119 * as when using the cmdparser. Similarly, we need to be careful if we should
1120 * ever issue a CPU read immediately following a GTT write.
1121 *
1122 * Telling the kernel about write access also has one more important
1123 * side-effect. Upon receiving notification about the write, it cancels any
1124 * scanout buffering for FBC/PSR and friends. Later FBC/PSR is then flushed by
1125 * either SW_FINISH or DIRTYFB. The presumption is that we never write to the
1126 * actual scanout via a mmaping, only to a backbuffer and so all the FBC/PSR
1127 * tracking is handled on the buffer exchange instead.
1128 */
1129 static void *
1130 brw_bo_map_gtt(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
1131 {
1132 struct brw_bufmgr *bufmgr = bo->bufmgr;
1133
1134 /* Get a mapping of the buffer if we haven't before. */
1135 if (bo->map_gtt == NULL) {
1136 DBG("bo_map_gtt: mmap %d (%s)\n", bo->gem_handle, bo->name);
1137
1138 struct drm_i915_gem_mmap_gtt mmap_arg = { .handle = bo->gem_handle };
1139
1140 /* Get the fake offset back... */
1141 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg);
1142 if (ret != 0) {
1143 DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
1144 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
1145 return NULL;
1146 }
1147
1148 /* and mmap it. */
1149 void *map = drm_mmap(0, bo->size, PROT_READ | PROT_WRITE,
1150 MAP_SHARED, bufmgr->fd, mmap_arg.offset);
1151 if (map == MAP_FAILED) {
1152 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
1153 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
1154 return NULL;
1155 }
1156
1157 /* We don't need to use VALGRIND_MALLOCLIKE_BLOCK because Valgrind will
1158 * already intercept this mmap call. However, for consistency between
1159 * all the mmap paths, we mark the pointer as defined now and mark it
1160 * as inaccessible afterwards.
1161 */
1162 VG_DEFINED(map, bo->size);
1163
1164 if (p_atomic_cmpxchg(&bo->map_gtt, NULL, map)) {
1165 VG_NOACCESS(map, bo->size);
1166 drm_munmap(map, bo->size);
1167 }
1168 }
1169 assert(bo->map_gtt);
1170
1171 DBG("bo_map_gtt: %d (%s) -> %p, ", bo->gem_handle, bo->name, bo->map_gtt);
1172 print_flags(flags);
1173
1174 if (!(flags & MAP_ASYNC)) {
1175 bo_wait_with_stall_warning(brw, bo, "GTT mapping");
1176 }
1177
1178 return bo->map_gtt;
1179 }
1180
1181 static bool
1182 can_map_cpu(struct brw_bo *bo, unsigned flags)
1183 {
1184 if (bo->cache_coherent)
1185 return true;
1186
1187 /* Even if the buffer itself is not cache-coherent (such as a scanout), on
1188 * an LLC platform reads always are coherent (as they are performed via the
1189 * central system agent). It is just the writes that we need to take special
1190 * care to ensure that land in main memory and not stick in the CPU cache.
1191 */
1192 if (!(flags & MAP_WRITE) && bo->bufmgr->has_llc)
1193 return true;
1194
1195 /* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
1196 * across batch flushes where the kernel will change cache domains of the
1197 * bo, invalidating continued access to the CPU mmap on non-LLC device.
1198 *
1199 * Similarly, ASYNC typically means that the buffer will be accessed via
1200 * both the CPU and the GPU simultaneously. Batches may be executed that
1201 * use the BO even while it is mapped. While OpenGL technically disallows
1202 * most drawing while non-persistent mappings are active, we may still use
1203 * the GPU for blits or other operations, causing batches to happen at
1204 * inconvenient times.
1205 */
1206 if (flags & (MAP_PERSISTENT | MAP_COHERENT | MAP_ASYNC))
1207 return false;
1208
1209 return !(flags & MAP_WRITE);
1210 }
1211
1212 void *
1213 brw_bo_map(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
1214 {
1215 if (bo->tiling_mode != I915_TILING_NONE && !(flags & MAP_RAW))
1216 return brw_bo_map_gtt(brw, bo, flags);
1217
1218 void *map;
1219
1220 if (can_map_cpu(bo, flags))
1221 map = brw_bo_map_cpu(brw, bo, flags);
1222 else
1223 map = brw_bo_map_wc(brw, bo, flags);
1224
1225 /* Allow the attempt to fail by falling back to the GTT where necessary.
1226 *
1227 * Not every buffer can be mmaped directly using the CPU (or WC), for
1228 * example buffers that wrap stolen memory or are imported from other
1229 * devices. For those, we have little choice but to use a GTT mmapping.
1230 * However, if we use a slow GTT mmapping for reads where we expected fast
1231 * access, that order of magnitude difference in throughput will be clearly
1232 * expressed by angry users.
1233 *
1234 * We skip MAP_RAW because we want to avoid map_gtt's fence detiling.
1235 */
1236 if (!map && !(flags & MAP_RAW)) {
1237 if (brw) {
1238 perf_debug("Fallback GTT mapping for %s with access flags %x\n",
1239 bo->name, flags);
1240 }
1241 map = brw_bo_map_gtt(brw, bo, flags);
1242 }
1243
1244 return map;
1245 }
1246
1247 int
1248 brw_bo_subdata(struct brw_bo *bo, uint64_t offset,
1249 uint64_t size, const void *data)
1250 {
1251 struct brw_bufmgr *bufmgr = bo->bufmgr;
1252
1253 struct drm_i915_gem_pwrite pwrite = {
1254 .handle = bo->gem_handle,
1255 .offset = offset,
1256 .size = size,
1257 .data_ptr = (uint64_t) (uintptr_t) data,
1258 };
1259
1260 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_PWRITE, &pwrite);
1261 if (ret != 0) {
1262 ret = -errno;
1263 DBG("%s:%d: Error writing data to buffer %d: "
1264 "(%"PRIu64" %"PRIu64") %s .\n",
1265 __FILE__, __LINE__, bo->gem_handle, offset, size, strerror(errno));
1266 }
1267
1268 return ret;
1269 }
1270
1271 /** Waits for all GPU rendering with the object to have completed. */
1272 void
1273 brw_bo_wait_rendering(struct brw_bo *bo)
1274 {
1275 /* We require a kernel recent enough for WAIT_IOCTL support.
1276 * See intel_init_bufmgr()
1277 */
1278 brw_bo_wait(bo, -1);
1279 }
1280
1281 /**
1282 * Waits on a BO for the given amount of time.
1283 *
1284 * @bo: buffer object to wait for
1285 * @timeout_ns: amount of time to wait in nanoseconds.
1286 * If value is less than 0, an infinite wait will occur.
1287 *
1288 * Returns 0 if the wait was successful ie. the last batch referencing the
1289 * object has completed within the allotted time. Otherwise some negative return
1290 * value describes the error. Of particular interest is -ETIME when the wait has
1291 * failed to yield the desired result.
1292 *
1293 * Similar to brw_bo_wait_rendering except a timeout parameter allows
1294 * the operation to give up after a certain amount of time. Another subtle
1295 * difference is the internal locking semantics are different (this variant does
1296 * not hold the lock for the duration of the wait). This makes the wait subject
1297 * to a larger userspace race window.
1298 *
1299 * The implementation shall wait until the object is no longer actively
1300 * referenced within a batch buffer at the time of the call. The wait will
1301 * not guarantee that the buffer is re-issued via another thread, or an flinked
1302 * handle. Userspace must make sure this race does not occur if such precision
1303 * is important.
1304 *
1305 * Note that some kernels have broken the inifite wait for negative values
1306 * promise, upgrade to latest stable kernels if this is the case.
1307 */
1308 int
1309 brw_bo_wait(struct brw_bo *bo, int64_t timeout_ns)
1310 {
1311 struct brw_bufmgr *bufmgr = bo->bufmgr;
1312
1313 /* If we know it's idle, don't bother with the kernel round trip */
1314 if (bo->idle && !bo->external)
1315 return 0;
1316
1317 struct drm_i915_gem_wait wait = {
1318 .bo_handle = bo->gem_handle,
1319 .timeout_ns = timeout_ns,
1320 };
1321 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_WAIT, &wait);
1322 if (ret != 0)
1323 return -errno;
1324
1325 bo->idle = true;
1326
1327 return ret;
1328 }
1329
1330 void
1331 brw_bufmgr_unref(struct brw_bufmgr *bufmgr)
1332 {
1333 mtx_lock(&global_bufmgr_list_mutex);
1334 if (p_atomic_dec_zero(&bufmgr->refcount)) {
1335 list_del(&bufmgr->link);
1336 } else {
1337 bufmgr = NULL;
1338 }
1339 mtx_unlock(&global_bufmgr_list_mutex);
1340
1341 if (!bufmgr)
1342 return;
1343
1344 mtx_destroy(&bufmgr->lock);
1345
1346 /* Free any cached buffer objects we were going to reuse */
1347 for (int i = 0; i < bufmgr->num_buckets; i++) {
1348 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1349
1350 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
1351 list_del(&bo->head);
1352
1353 bo_free(bo);
1354 }
1355
1356 if (brw_using_softpin(bufmgr)) {
1357 for (int z = 0; z < BRW_MEMZONE_COUNT; z++) {
1358 util_dynarray_fini(&bucket->vma_list[z]);
1359 }
1360 }
1361 }
1362
1363 _mesa_hash_table_destroy(bufmgr->name_table, NULL);
1364 _mesa_hash_table_destroy(bufmgr->handle_table, NULL);
1365
1366 if (brw_using_softpin(bufmgr)) {
1367 for (int z = 0; z < BRW_MEMZONE_COUNT; z++) {
1368 util_vma_heap_finish(&bufmgr->vma_allocator[z]);
1369 }
1370 }
1371
1372 close(bufmgr->fd);
1373 bufmgr->fd = -1;
1374
1375 free(bufmgr);
1376 }
1377
1378 static int
1379 bo_set_tiling_internal(struct brw_bo *bo, uint32_t tiling_mode,
1380 uint32_t stride)
1381 {
1382 struct brw_bufmgr *bufmgr = bo->bufmgr;
1383 struct drm_i915_gem_set_tiling set_tiling;
1384 int ret;
1385
1386 if (bo->global_name == 0 &&
1387 tiling_mode == bo->tiling_mode && stride == bo->stride)
1388 return 0;
1389
1390 memset(&set_tiling, 0, sizeof(set_tiling));
1391 do {
1392 /* set_tiling is slightly broken and overwrites the
1393 * input on the error path, so we have to open code
1394 * rmIoctl.
1395 */
1396 set_tiling.handle = bo->gem_handle;
1397 set_tiling.tiling_mode = tiling_mode;
1398 set_tiling.stride = stride;
1399
1400 ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
1401 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
1402 if (ret == -1)
1403 return -errno;
1404
1405 bo->tiling_mode = set_tiling.tiling_mode;
1406 bo->swizzle_mode = set_tiling.swizzle_mode;
1407 bo->stride = set_tiling.stride;
1408 return 0;
1409 }
1410
1411 int
1412 brw_bo_get_tiling(struct brw_bo *bo, uint32_t *tiling_mode,
1413 uint32_t *swizzle_mode)
1414 {
1415 *tiling_mode = bo->tiling_mode;
1416 *swizzle_mode = bo->swizzle_mode;
1417 return 0;
1418 }
1419
1420 static struct brw_bo *
1421 brw_bo_gem_create_from_prime_internal(struct brw_bufmgr *bufmgr, int prime_fd,
1422 int tiling_mode, uint32_t stride)
1423 {
1424 uint32_t handle;
1425 struct brw_bo *bo;
1426
1427 mtx_lock(&bufmgr->lock);
1428 int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1429 if (ret) {
1430 DBG("create_from_prime: failed to obtain handle from fd: %s\n",
1431 strerror(errno));
1432 mtx_unlock(&bufmgr->lock);
1433 return NULL;
1434 }
1435
1436 /*
1437 * See if the kernel has already returned this buffer to us. Just as
1438 * for named buffers, we must not create two bo's pointing at the same
1439 * kernel object
1440 */
1441 bo = hash_find_bo(bufmgr->handle_table, handle);
1442 if (bo) {
1443 brw_bo_reference(bo);
1444 goto out;
1445 }
1446
1447 bo = calloc(1, sizeof(*bo));
1448 if (!bo)
1449 goto out;
1450
1451 p_atomic_set(&bo->refcount, 1);
1452
1453 /* Determine size of bo. The fd-to-handle ioctl really should
1454 * return the size, but it doesn't. If we have kernel 3.12 or
1455 * later, we can lseek on the prime fd to get the size. Older
1456 * kernels will just fail, in which case we fall back to the
1457 * provided (estimated or guess size). */
1458 ret = lseek(prime_fd, 0, SEEK_END);
1459 if (ret != -1)
1460 bo->size = ret;
1461
1462 bo->bufmgr = bufmgr;
1463
1464 bo->gem_handle = handle;
1465 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1466
1467 bo->name = "prime";
1468 bo->reusable = false;
1469 bo->external = true;
1470 bo->kflags = bufmgr->initial_kflags;
1471
1472 if (bo->kflags & EXEC_OBJECT_PINNED) {
1473 assert(bo->size > 0);
1474 bo->gtt_offset = vma_alloc(bufmgr, BRW_MEMZONE_OTHER, bo->size, 1);
1475 }
1476
1477 if (tiling_mode < 0) {
1478 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
1479 if (drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling))
1480 goto err;
1481
1482 bo->tiling_mode = get_tiling.tiling_mode;
1483 bo->swizzle_mode = get_tiling.swizzle_mode;
1484 /* XXX stride is unknown */
1485 } else {
1486 bo_set_tiling_internal(bo, tiling_mode, stride);
1487 }
1488
1489 out:
1490 mtx_unlock(&bufmgr->lock);
1491 return bo;
1492
1493 err:
1494 bo_free(bo);
1495 mtx_unlock(&bufmgr->lock);
1496 return NULL;
1497 }
1498
1499 struct brw_bo *
1500 brw_bo_gem_create_from_prime(struct brw_bufmgr *bufmgr, int prime_fd)
1501 {
1502 return brw_bo_gem_create_from_prime_internal(bufmgr, prime_fd, -1, 0);
1503 }
1504
1505 struct brw_bo *
1506 brw_bo_gem_create_from_prime_tiled(struct brw_bufmgr *bufmgr, int prime_fd,
1507 uint32_t tiling_mode, uint32_t stride)
1508 {
1509 assert(tiling_mode == I915_TILING_NONE ||
1510 tiling_mode == I915_TILING_X ||
1511 tiling_mode == I915_TILING_Y);
1512
1513 return brw_bo_gem_create_from_prime_internal(bufmgr, prime_fd,
1514 tiling_mode, stride);
1515 }
1516
1517 static void
1518 brw_bo_make_external(struct brw_bo *bo)
1519 {
1520 struct brw_bufmgr *bufmgr = bo->bufmgr;
1521
1522 if (!bo->external) {
1523 mtx_lock(&bufmgr->lock);
1524 if (!bo->external) {
1525 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1526 bo->external = true;
1527 }
1528 mtx_unlock(&bufmgr->lock);
1529 }
1530 }
1531
1532 int
1533 brw_bo_gem_export_to_prime(struct brw_bo *bo, int *prime_fd)
1534 {
1535 struct brw_bufmgr *bufmgr = bo->bufmgr;
1536
1537 brw_bo_make_external(bo);
1538
1539 if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1540 DRM_CLOEXEC, prime_fd) != 0)
1541 return -errno;
1542
1543 bo->reusable = false;
1544
1545 return 0;
1546 }
1547
1548 uint32_t
1549 brw_bo_export_gem_handle(struct brw_bo *bo)
1550 {
1551 brw_bo_make_external(bo);
1552
1553 return bo->gem_handle;
1554 }
1555
1556 int
1557 brw_bo_flink(struct brw_bo *bo, uint32_t *name)
1558 {
1559 struct brw_bufmgr *bufmgr = bo->bufmgr;
1560
1561 if (!bo->global_name) {
1562 struct drm_gem_flink flink = { .handle = bo->gem_handle };
1563
1564 if (drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1565 return -errno;
1566
1567 brw_bo_make_external(bo);
1568 mtx_lock(&bufmgr->lock);
1569 if (!bo->global_name) {
1570 bo->global_name = flink.name;
1571 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
1572 }
1573 mtx_unlock(&bufmgr->lock);
1574
1575 bo->reusable = false;
1576 }
1577
1578 *name = bo->global_name;
1579 return 0;
1580 }
1581
1582 static void
1583 add_bucket(struct brw_bufmgr *bufmgr, int size)
1584 {
1585 unsigned int i = bufmgr->num_buckets;
1586
1587 assert(i < ARRAY_SIZE(bufmgr->cache_bucket));
1588
1589 list_inithead(&bufmgr->cache_bucket[i].head);
1590 if (brw_using_softpin(bufmgr)) {
1591 for (int z = 0; z < BRW_MEMZONE_COUNT; z++)
1592 util_dynarray_init(&bufmgr->cache_bucket[i].vma_list[z], NULL);
1593 }
1594 bufmgr->cache_bucket[i].size = size;
1595 bufmgr->num_buckets++;
1596
1597 assert(bucket_for_size(bufmgr, size) == &bufmgr->cache_bucket[i]);
1598 assert(bucket_for_size(bufmgr, size - 2048) == &bufmgr->cache_bucket[i]);
1599 assert(bucket_for_size(bufmgr, size + 1) != &bufmgr->cache_bucket[i]);
1600 }
1601
1602 static void
1603 init_cache_buckets(struct brw_bufmgr *bufmgr)
1604 {
1605 uint64_t size, cache_max_size = 64 * 1024 * 1024;
1606
1607 /* OK, so power of two buckets was too wasteful of memory.
1608 * Give 3 other sizes between each power of two, to hopefully
1609 * cover things accurately enough. (The alternative is
1610 * probably to just go for exact matching of sizes, and assume
1611 * that for things like composited window resize the tiled
1612 * width/height alignment and rounding of sizes to pages will
1613 * get us useful cache hit rates anyway)
1614 */
1615 add_bucket(bufmgr, PAGE_SIZE);
1616 add_bucket(bufmgr, PAGE_SIZE * 2);
1617 add_bucket(bufmgr, PAGE_SIZE * 3);
1618
1619 /* Initialize the linked lists for BO reuse cache. */
1620 for (size = 4 * PAGE_SIZE; size <= cache_max_size; size *= 2) {
1621 add_bucket(bufmgr, size);
1622
1623 add_bucket(bufmgr, size + size * 1 / 4);
1624 add_bucket(bufmgr, size + size * 2 / 4);
1625 add_bucket(bufmgr, size + size * 3 / 4);
1626 }
1627 }
1628
1629 uint32_t
1630 brw_create_hw_context(struct brw_bufmgr *bufmgr)
1631 {
1632 struct drm_i915_gem_context_create create = { };
1633 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create);
1634 if (ret != 0) {
1635 DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno));
1636 return 0;
1637 }
1638
1639 return create.ctx_id;
1640 }
1641
1642 int
1643 brw_hw_context_set_priority(struct brw_bufmgr *bufmgr,
1644 uint32_t ctx_id,
1645 int priority)
1646 {
1647 struct drm_i915_gem_context_param p = {
1648 .ctx_id = ctx_id,
1649 .param = I915_CONTEXT_PARAM_PRIORITY,
1650 .value = priority,
1651 };
1652 int err;
1653
1654 err = 0;
1655 if (drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM, &p))
1656 err = -errno;
1657
1658 return err;
1659 }
1660
1661 void
1662 brw_destroy_hw_context(struct brw_bufmgr *bufmgr, uint32_t ctx_id)
1663 {
1664 struct drm_i915_gem_context_destroy d = { .ctx_id = ctx_id };
1665
1666 if (ctx_id != 0 &&
1667 drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY, &d) != 0) {
1668 fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1669 strerror(errno));
1670 }
1671 }
1672
1673 int
1674 brw_reg_read(struct brw_bufmgr *bufmgr, uint32_t offset, uint64_t *result)
1675 {
1676 struct drm_i915_reg_read reg_read = { .offset = offset };
1677 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_REG_READ, &reg_read);
1678
1679 *result = reg_read.val;
1680 return ret;
1681 }
1682
1683 static int
1684 gem_param(int fd, int name)
1685 {
1686 int v = -1; /* No param uses (yet) the sign bit, reserve it for errors */
1687
1688 struct drm_i915_getparam gp = { .param = name, .value = &v };
1689 if (drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp))
1690 return -1;
1691
1692 return v;
1693 }
1694
1695 static int
1696 gem_context_getparam(int fd, uint32_t context, uint64_t param, uint64_t *value)
1697 {
1698 struct drm_i915_gem_context_param gp = {
1699 .ctx_id = context,
1700 .param = param,
1701 };
1702
1703 if (drmIoctl(fd, DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM, &gp))
1704 return -1;
1705
1706 *value = gp.value;
1707
1708 return 0;
1709 }
1710
1711 bool
1712 brw_using_softpin(struct brw_bufmgr *bufmgr)
1713 {
1714 return bufmgr->initial_kflags & EXEC_OBJECT_PINNED;
1715 }
1716
1717 static struct brw_bufmgr *
1718 brw_bufmgr_ref(struct brw_bufmgr *bufmgr)
1719 {
1720 p_atomic_inc(&bufmgr->refcount);
1721 return bufmgr;
1722 }
1723
1724 /**
1725 * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1726 * and manage map buffer objections.
1727 *
1728 * \param fd File descriptor of the opened DRM device.
1729 */
1730 static struct brw_bufmgr *
1731 brw_bufmgr_create(struct gen_device_info *devinfo, int fd, bool bo_reuse)
1732 {
1733 struct brw_bufmgr *bufmgr;
1734
1735 bufmgr = calloc(1, sizeof(*bufmgr));
1736 if (bufmgr == NULL)
1737 return NULL;
1738
1739 /* Handles to buffer objects belong to the device fd and are not
1740 * reference counted by the kernel. If the same fd is used by
1741 * multiple parties (threads sharing the same screen bufmgr, or
1742 * even worse the same device fd passed to multiple libraries)
1743 * ownership of those handles is shared by those independent parties.
1744 *
1745 * Don't do this! Ensure that each library/bufmgr has its own device
1746 * fd so that its namespace does not clash with another.
1747 */
1748 bufmgr->fd = dup(fd);
1749 if (bufmgr->fd < 0) {
1750 free(bufmgr);
1751 return NULL;
1752 }
1753
1754 p_atomic_set(&bufmgr->refcount, 1);
1755
1756 if (mtx_init(&bufmgr->lock, mtx_plain) != 0) {
1757 close(bufmgr->fd);
1758 free(bufmgr);
1759 return NULL;
1760 }
1761
1762 uint64_t gtt_size;
1763 if (gem_context_getparam(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE, &gtt_size))
1764 gtt_size = 0;
1765
1766 bufmgr->has_llc = devinfo->has_llc;
1767 bufmgr->has_mmap_wc = gem_param(fd, I915_PARAM_MMAP_VERSION) > 0;
1768 bufmgr->bo_reuse = bo_reuse;
1769 bufmgr->has_mmap_offset = gem_param(fd, I915_PARAM_MMAP_GTT_VERSION) >= 4;
1770
1771 const uint64_t _4GB = 4ull << 30;
1772
1773 /* The STATE_BASE_ADDRESS size field can only hold 1 page shy of 4GB */
1774 const uint64_t _4GB_minus_1 = _4GB - PAGE_SIZE;
1775
1776 if (devinfo->gen >= 8 && gtt_size > _4GB) {
1777 bufmgr->initial_kflags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1778
1779 /* Allocate VMA in userspace if we have softpin and full PPGTT. */
1780 if (gem_param(fd, I915_PARAM_HAS_EXEC_SOFTPIN) > 0 &&
1781 gem_param(fd, I915_PARAM_HAS_ALIASING_PPGTT) > 1) {
1782 bufmgr->initial_kflags |= EXEC_OBJECT_PINNED;
1783
1784 util_vma_heap_init(&bufmgr->vma_allocator[BRW_MEMZONE_LOW_4G],
1785 PAGE_SIZE, _4GB_minus_1);
1786
1787 /* Leave the last 4GB out of the high vma range, so that no state
1788 * base address + size can overflow 48 bits.
1789 */
1790 util_vma_heap_init(&bufmgr->vma_allocator[BRW_MEMZONE_OTHER],
1791 1 * _4GB, gtt_size - 2 * _4GB);
1792 } else if (devinfo->gen >= 10) {
1793 /* Softpin landed in 4.5, but GVT used an aliasing PPGTT until
1794 * kernel commit 6b3816d69628becb7ff35978aa0751798b4a940a in
1795 * 4.14. Gen10+ GVT hasn't landed yet, so it's not actually a
1796 * problem - but extending this requirement back to earlier gens
1797 * might actually mean requiring 4.14.
1798 */
1799 fprintf(stderr, "i965 requires softpin (Kernel 4.5) on Gen10+.");
1800 close(bufmgr->fd);
1801 free(bufmgr);
1802 return NULL;
1803 }
1804 }
1805
1806 init_cache_buckets(bufmgr);
1807
1808 bufmgr->name_table =
1809 _mesa_hash_table_create(NULL, _mesa_hash_uint, _mesa_key_uint_equal);
1810 bufmgr->handle_table =
1811 _mesa_hash_table_create(NULL, _mesa_hash_uint, _mesa_key_uint_equal);
1812
1813 return bufmgr;
1814 }
1815
1816 struct brw_bufmgr *
1817 brw_bufmgr_get_for_fd(struct gen_device_info *devinfo, int fd, bool bo_reuse)
1818 {
1819 struct stat st;
1820
1821 if (fstat(fd, &st))
1822 return NULL;
1823
1824 struct brw_bufmgr *bufmgr = NULL;
1825
1826 mtx_lock(&global_bufmgr_list_mutex);
1827 list_for_each_entry(struct brw_bufmgr, iter_bufmgr, &global_bufmgr_list, link) {
1828 struct stat iter_st;
1829 if (fstat(iter_bufmgr->fd, &iter_st))
1830 continue;
1831
1832 if (st.st_rdev == iter_st.st_rdev) {
1833 assert(iter_bufmgr->bo_reuse == bo_reuse);
1834 bufmgr = brw_bufmgr_ref(iter_bufmgr);
1835 goto unlock;
1836 }
1837 }
1838
1839 bufmgr = brw_bufmgr_create(devinfo, fd, bo_reuse);
1840 list_addtail(&bufmgr->link, &global_bufmgr_list);
1841
1842 unlock:
1843 mtx_unlock(&global_bufmgr_list_mutex);
1844
1845 return bufmgr;
1846 }
1847
1848 int
1849 brw_bufmgr_get_fd(struct brw_bufmgr *bufmgr)
1850 {
1851 return bufmgr->fd;
1852 }