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