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