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