f698123db4c47f3e99ea17077c01a3f1bddd37d5
[mesa.git] / src / mesa / drivers / dri / i965 / brw_bufmgr.c
1 /*
2 * Copyright © 2007 Red Hat Inc.
3 * Copyright © 2007-2017 Intel Corporation
4 * Copyright © 2006 VMware, Inc.
5 * All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the next
15 * paragraph) shall be included in all copies or substantial portions of the
16 * Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 * IN THE SOFTWARE.
25 */
26
27 /*
28 * Authors: Thomas Hellström <thellstrom@vmware.com>
29 * Keith Whitwell <keithw@vmware.com>
30 * Eric Anholt <eric@anholt.net>
31 * Dave Airlie <airlied@linux.ie>
32 */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37
38 #include <xf86drm.h>
39 #include <util/u_atomic.h>
40 #include <fcntl.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <assert.h>
46 #include <sys/ioctl.h>
47 #include <sys/stat.h>
48 #include <sys/types.h>
49 #include <stdbool.h>
50
51 #include "errno.h"
52 #ifndef ETIME
53 #define ETIME ETIMEDOUT
54 #endif
55 #include "common/gen_clflush.h"
56 #include "common/gen_debug.h"
57 #include "dev/gen_device_info.h"
58 #include "libdrm_macros.h"
59 #include "main/macros.h"
60 #include "util/macros.h"
61 #include "util/hash_table.h"
62 #include "util/list.h"
63 #include "brw_bufmgr.h"
64 #include "brw_context.h"
65 #include "string.h"
66
67 #include "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 struct bo_cache_bucket {
102 struct list_head head;
103 uint64_t size;
104 };
105
106 struct brw_bufmgr {
107 int fd;
108
109 mtx_t lock;
110
111 /** Array of lists of cached gem objects of power-of-two sizes */
112 struct bo_cache_bucket cache_bucket[14 * 4];
113 int num_buckets;
114 time_t time;
115
116 struct hash_table *name_table;
117 struct hash_table *handle_table;
118
119 bool has_llc:1;
120 bool has_mmap_wc:1;
121 bool bo_reuse:1;
122 bool supports_48b_addresses:1;
123 };
124
125 static int bo_set_tiling_internal(struct brw_bo *bo, uint32_t tiling_mode,
126 uint32_t stride);
127
128 static void bo_free(struct brw_bo *bo);
129
130 static uint32_t
131 key_hash_uint(const void *key)
132 {
133 return _mesa_hash_data(key, 4);
134 }
135
136 static bool
137 key_uint_equal(const void *a, const void *b)
138 {
139 return *((unsigned *) a) == *((unsigned *) b);
140 }
141
142 static struct brw_bo *
143 hash_find_bo(struct hash_table *ht, unsigned int key)
144 {
145 struct hash_entry *entry = _mesa_hash_table_search(ht, &key);
146 return entry ? (struct brw_bo *) entry->data : NULL;
147 }
148
149 static uint64_t
150 bo_tile_size(struct brw_bufmgr *bufmgr, uint64_t size, uint32_t tiling)
151 {
152 if (tiling == I915_TILING_NONE)
153 return size;
154
155 /* 965+ just need multiples of page size for tiling */
156 return ALIGN(size, 4096);
157 }
158
159 /*
160 * Round a given pitch up to the minimum required for X tiling on a
161 * given chip. We use 512 as the minimum to allow for a later tiling
162 * change.
163 */
164 static uint32_t
165 bo_tile_pitch(struct brw_bufmgr *bufmgr, uint32_t pitch, uint32_t tiling)
166 {
167 unsigned long tile_width;
168
169 /* If untiled, then just align it so that we can do rendering
170 * to it with the 3D engine.
171 */
172 if (tiling == I915_TILING_NONE)
173 return ALIGN(pitch, 64);
174
175 if (tiling == I915_TILING_X)
176 tile_width = 512;
177 else
178 tile_width = 128;
179
180 /* 965 is flexible */
181 return ALIGN(pitch, tile_width);
182 }
183
184 /**
185 * This function finds the correct bucket fit for the input size.
186 * The function works with O(1) complexity when the requested size
187 * was queried instead of iterating the size through all the buckets.
188 */
189 static struct bo_cache_bucket *
190 bucket_for_size(struct brw_bufmgr *bufmgr, uint64_t size)
191 {
192 /* Calculating the pages and rounding up to the page size. */
193 const unsigned pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
194
195 /* Row Bucket sizes clz((x-1) | 3) Row Column
196 * in pages stride size
197 * 0: 1 2 3 4 -> 30 30 30 30 4 1
198 * 1: 5 6 7 8 -> 29 29 29 29 4 1
199 * 2: 10 12 14 16 -> 28 28 28 28 8 2
200 * 3: 20 24 28 32 -> 27 27 27 27 16 4
201 */
202 const unsigned row = 30 - __builtin_clz((pages - 1) | 3);
203 const unsigned row_max_pages = 4 << row;
204
205 /* The '& ~2' is the special case for row 1. In row 1, max pages /
206 * 2 is 2, but the previous row maximum is zero (because there is
207 * no previous row). All row maximum sizes are power of 2, so that
208 * is the only case where that bit will be set.
209 */
210 const unsigned prev_row_max_pages = (row_max_pages / 2) & ~2;
211 int col_size_log2 = row - 1;
212 col_size_log2 += (col_size_log2 < 0);
213
214 const unsigned col = (pages - prev_row_max_pages +
215 ((1 << col_size_log2) - 1)) >> col_size_log2;
216
217 /* Calculating the index based on the row and column. */
218 const unsigned index = (row * 4) + (col - 1);
219
220 return (index < bufmgr->num_buckets) ?
221 &bufmgr->cache_bucket[index] : NULL;
222 }
223
224 int
225 brw_bo_busy(struct brw_bo *bo)
226 {
227 struct brw_bufmgr *bufmgr = bo->bufmgr;
228 struct drm_i915_gem_busy busy = { .handle = bo->gem_handle };
229
230 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_BUSY, &busy);
231 if (ret == 0) {
232 bo->idle = !busy.busy;
233 return busy.busy;
234 }
235 return false;
236 }
237
238 int
239 brw_bo_madvise(struct brw_bo *bo, int state)
240 {
241 struct drm_i915_gem_madvise madv = {
242 .handle = bo->gem_handle,
243 .madv = state,
244 .retained = 1,
245 };
246
247 drmIoctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_MADVISE, &madv);
248
249 return madv.retained;
250 }
251
252 /* drop the oldest entries that have been purged by the kernel */
253 static void
254 brw_bo_cache_purge_bucket(struct brw_bufmgr *bufmgr,
255 struct bo_cache_bucket *bucket)
256 {
257 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
258 if (brw_bo_madvise(bo, I915_MADV_DONTNEED))
259 break;
260
261 list_del(&bo->head);
262 bo_free(bo);
263 }
264 }
265
266 static struct brw_bo *
267 bo_alloc_internal(struct brw_bufmgr *bufmgr,
268 const char *name,
269 uint64_t size,
270 unsigned flags,
271 uint32_t tiling_mode,
272 uint32_t stride, uint64_t alignment)
273 {
274 struct brw_bo *bo;
275 unsigned int page_size = getpagesize();
276 int ret;
277 struct bo_cache_bucket *bucket;
278 bool alloc_from_cache;
279 uint64_t bo_size;
280 bool busy = false;
281 bool zeroed = false;
282
283 if (flags & BO_ALLOC_BUSY)
284 busy = true;
285
286 if (flags & BO_ALLOC_ZEROED)
287 zeroed = true;
288
289 /* BUSY does doesn't really jive with ZEROED as we have to wait for it to
290 * be idle before we can memset. Just disallow that combination.
291 */
292 assert(!(busy && zeroed));
293
294 /* Round the allocated size up to a power of two number of pages. */
295 bucket = bucket_for_size(bufmgr, size);
296
297 /* If we don't have caching at this size, don't actually round the
298 * allocation up.
299 */
300 if (bucket == NULL) {
301 bo_size = size;
302 if (bo_size < page_size)
303 bo_size = page_size;
304 } else {
305 bo_size = bucket->size;
306 }
307
308 mtx_lock(&bufmgr->lock);
309 /* Get a buffer out of the cache if available */
310 retry:
311 alloc_from_cache = false;
312 if (bucket != NULL && !list_empty(&bucket->head)) {
313 if (busy && !zeroed) {
314 /* Allocate new render-target BOs from the tail (MRU)
315 * of the list, as it will likely be hot in the GPU
316 * cache and in the aperture for us. If the caller
317 * asked us to zero the buffer, we don't want this
318 * because we are going to mmap it.
319 */
320 bo = LIST_ENTRY(struct brw_bo, bucket->head.prev, head);
321 list_del(&bo->head);
322 alloc_from_cache = true;
323 bo->align = alignment;
324 } else {
325 assert(alignment == 0);
326 /* For non-render-target BOs (where we're probably
327 * going to map it first thing in order to fill it
328 * with data), check if the last BO in the cache is
329 * unbusy, and only reuse in that case. Otherwise,
330 * allocating a new buffer is probably faster than
331 * waiting for the GPU to finish.
332 */
333 bo = LIST_ENTRY(struct brw_bo, bucket->head.next, head);
334 if (!brw_bo_busy(bo)) {
335 alloc_from_cache = true;
336 list_del(&bo->head);
337 }
338 }
339
340 if (alloc_from_cache) {
341 if (!brw_bo_madvise(bo, I915_MADV_WILLNEED)) {
342 bo_free(bo);
343 brw_bo_cache_purge_bucket(bufmgr, bucket);
344 goto retry;
345 }
346
347 if (bo_set_tiling_internal(bo, tiling_mode, stride)) {
348 bo_free(bo);
349 goto retry;
350 }
351
352 if (zeroed) {
353 void *map = brw_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
354 if (!map) {
355 bo_free(bo);
356 goto retry;
357 }
358 memset(map, 0, bo_size);
359 }
360 }
361 }
362
363 if (!alloc_from_cache) {
364 bo = calloc(1, sizeof(*bo));
365 if (!bo)
366 goto err;
367
368 bo->size = bo_size;
369 bo->idle = true;
370
371 struct drm_i915_gem_create create = { .size = bo_size };
372
373 /* All new BOs we get from the kernel are zeroed, so we don't need to
374 * worry about that here.
375 */
376 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CREATE, &create);
377 if (ret != 0) {
378 free(bo);
379 goto err;
380 }
381
382 bo->gem_handle = create.handle;
383
384 bo->bufmgr = bufmgr;
385 bo->align = alignment;
386
387 bo->tiling_mode = I915_TILING_NONE;
388 bo->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
389 bo->stride = 0;
390
391 if (bo_set_tiling_internal(bo, tiling_mode, stride))
392 goto err_free;
393
394 /* Calling set_domain() will allocate pages for the BO outside of the
395 * struct mutex lock in the kernel, which is more efficient than waiting
396 * to create them during the first execbuf that uses the BO.
397 */
398 struct drm_i915_gem_set_domain sd = {
399 .handle = bo->gem_handle,
400 .read_domains = I915_GEM_DOMAIN_CPU,
401 .write_domain = 0,
402 };
403
404 if (drmIoctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd) != 0)
405 goto err_free;
406 }
407
408 bo->name = name;
409 p_atomic_set(&bo->refcount, 1);
410 bo->reusable = true;
411 bo->cache_coherent = bufmgr->has_llc;
412 bo->index = -1;
413 if (bufmgr->supports_48b_addresses)
414 bo->kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
415
416 mtx_unlock(&bufmgr->lock);
417
418 DBG("bo_create: buf %d (%s) %llub\n", bo->gem_handle, bo->name,
419 (unsigned long long) size);
420
421 return bo;
422
423 err_free:
424 bo_free(bo);
425 err:
426 mtx_unlock(&bufmgr->lock);
427 return NULL;
428 }
429
430 struct brw_bo *
431 brw_bo_alloc(struct brw_bufmgr *bufmgr,
432 const char *name, uint64_t size, uint64_t alignment)
433 {
434 return bo_alloc_internal(bufmgr, name, size, 0, I915_TILING_NONE, 0, 0);
435 }
436
437 struct brw_bo *
438 brw_bo_alloc_tiled(struct brw_bufmgr *bufmgr, const char *name,
439 uint64_t size, uint32_t tiling_mode, uint32_t pitch,
440 unsigned flags)
441 {
442 return bo_alloc_internal(bufmgr, name, size, flags, tiling_mode, pitch, 0);
443 }
444
445 struct brw_bo *
446 brw_bo_alloc_tiled_2d(struct brw_bufmgr *bufmgr, const char *name,
447 int x, int y, int cpp, uint32_t tiling,
448 uint32_t *pitch, unsigned flags)
449 {
450 uint64_t size;
451 uint32_t stride;
452 unsigned long aligned_y, height_alignment;
453
454 /* If we're tiled, our allocations are in 8 or 32-row blocks,
455 * so failure to align our height means that we won't allocate
456 * enough pages.
457 *
458 * If we're untiled, we still have to align to 2 rows high
459 * because the data port accesses 2x2 blocks even if the
460 * bottom row isn't to be rendered, so failure to align means
461 * we could walk off the end of the GTT and fault. This is
462 * documented on 965, and may be the case on older chipsets
463 * too so we try to be careful.
464 */
465 aligned_y = y;
466 height_alignment = 2;
467
468 if (tiling == I915_TILING_X)
469 height_alignment = 8;
470 else if (tiling == I915_TILING_Y)
471 height_alignment = 32;
472 aligned_y = ALIGN(y, height_alignment);
473
474 stride = x * cpp;
475 stride = bo_tile_pitch(bufmgr, stride, tiling);
476 size = stride * aligned_y;
477 size = bo_tile_size(bufmgr, size, tiling);
478 *pitch = stride;
479
480 if (tiling == I915_TILING_NONE)
481 stride = 0;
482
483 return bo_alloc_internal(bufmgr, name, size, flags, tiling, stride, 0);
484 }
485
486 /**
487 * Returns a brw_bo wrapping the given buffer object handle.
488 *
489 * This can be used when one application needs to pass a buffer object
490 * to another.
491 */
492 struct brw_bo *
493 brw_bo_gem_create_from_name(struct brw_bufmgr *bufmgr,
494 const char *name, unsigned int handle)
495 {
496 struct brw_bo *bo;
497
498 /* At the moment most applications only have a few named bo.
499 * For instance, in a DRI client only the render buffers passed
500 * between X and the client are named. And since X returns the
501 * alternating names for the front/back buffer a linear search
502 * provides a sufficiently fast match.
503 */
504 mtx_lock(&bufmgr->lock);
505 bo = hash_find_bo(bufmgr->name_table, handle);
506 if (bo) {
507 brw_bo_reference(bo);
508 goto out;
509 }
510
511 struct drm_gem_open open_arg = { .name = handle };
512 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
513 if (ret != 0) {
514 DBG("Couldn't reference %s handle 0x%08x: %s\n",
515 name, handle, strerror(errno));
516 bo = NULL;
517 goto out;
518 }
519 /* Now see if someone has used a prime handle to get this
520 * object from the kernel before by looking through the list
521 * again for a matching gem_handle
522 */
523 bo = hash_find_bo(bufmgr->handle_table, open_arg.handle);
524 if (bo) {
525 brw_bo_reference(bo);
526 goto out;
527 }
528
529 bo = calloc(1, sizeof(*bo));
530 if (!bo)
531 goto out;
532
533 p_atomic_set(&bo->refcount, 1);
534
535 bo->size = open_arg.size;
536 bo->gtt_offset = 0;
537 bo->bufmgr = bufmgr;
538 bo->gem_handle = open_arg.handle;
539 bo->name = name;
540 bo->global_name = handle;
541 bo->reusable = false;
542 bo->external = true;
543
544 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
545 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
546
547 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
548 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling);
549 if (ret != 0)
550 goto err_unref;
551
552 bo->tiling_mode = get_tiling.tiling_mode;
553 bo->swizzle_mode = get_tiling.swizzle_mode;
554 /* XXX stride is unknown */
555 DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
556
557 out:
558 mtx_unlock(&bufmgr->lock);
559 return bo;
560
561 err_unref:
562 bo_free(bo);
563 mtx_unlock(&bufmgr->lock);
564 return NULL;
565 }
566
567 static void
568 bo_free(struct brw_bo *bo)
569 {
570 struct brw_bufmgr *bufmgr = bo->bufmgr;
571
572 if (bo->map_cpu) {
573 VG_NOACCESS(bo->map_cpu, bo->size);
574 drm_munmap(bo->map_cpu, bo->size);
575 }
576 if (bo->map_wc) {
577 VG_NOACCESS(bo->map_wc, bo->size);
578 drm_munmap(bo->map_wc, bo->size);
579 }
580 if (bo->map_gtt) {
581 VG_NOACCESS(bo->map_gtt, bo->size);
582 drm_munmap(bo->map_gtt, bo->size);
583 }
584
585 if (bo->external) {
586 struct hash_entry *entry;
587
588 if (bo->global_name) {
589 entry = _mesa_hash_table_search(bufmgr->name_table, &bo->global_name);
590 _mesa_hash_table_remove(bufmgr->name_table, entry);
591 }
592
593 entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
594 _mesa_hash_table_remove(bufmgr->handle_table, entry);
595 }
596
597 /* Close this object */
598 struct drm_gem_close close = { .handle = bo->gem_handle };
599 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
600 if (ret != 0) {
601 DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
602 bo->gem_handle, bo->name, strerror(errno));
603 }
604 free(bo);
605 }
606
607 /** Frees all cached buffers significantly older than @time. */
608 static void
609 cleanup_bo_cache(struct brw_bufmgr *bufmgr, time_t time)
610 {
611 int i;
612
613 if (bufmgr->time == time)
614 return;
615
616 for (i = 0; i < bufmgr->num_buckets; i++) {
617 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
618
619 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
620 if (time - bo->free_time <= 1)
621 break;
622
623 list_del(&bo->head);
624
625 bo_free(bo);
626 }
627 }
628
629 bufmgr->time = time;
630 }
631
632 static void
633 bo_unreference_final(struct brw_bo *bo, time_t time)
634 {
635 struct brw_bufmgr *bufmgr = bo->bufmgr;
636 struct bo_cache_bucket *bucket;
637
638 DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
639
640 bucket = bucket_for_size(bufmgr, bo->size);
641 /* Put the buffer into our internal cache for reuse if we can. */
642 if (bufmgr->bo_reuse && bo->reusable && bucket != NULL &&
643 brw_bo_madvise(bo, I915_MADV_DONTNEED)) {
644 bo->free_time = time;
645
646 bo->name = NULL;
647 bo->kflags = 0;
648
649 list_addtail(&bo->head, &bucket->head);
650 } else {
651 bo_free(bo);
652 }
653 }
654
655 void
656 brw_bo_unreference(struct brw_bo *bo)
657 {
658 if (bo == NULL)
659 return;
660
661 assert(p_atomic_read(&bo->refcount) > 0);
662
663 if (atomic_add_unless(&bo->refcount, -1, 1)) {
664 struct brw_bufmgr *bufmgr = bo->bufmgr;
665 struct timespec time;
666
667 clock_gettime(CLOCK_MONOTONIC, &time);
668
669 mtx_lock(&bufmgr->lock);
670
671 if (p_atomic_dec_zero(&bo->refcount)) {
672 bo_unreference_final(bo, time.tv_sec);
673 cleanup_bo_cache(bufmgr, time.tv_sec);
674 }
675
676 mtx_unlock(&bufmgr->lock);
677 }
678 }
679
680 static void
681 bo_wait_with_stall_warning(struct brw_context *brw,
682 struct brw_bo *bo,
683 const char *action)
684 {
685 bool busy = brw && brw->perf_debug && !bo->idle;
686 double elapsed = unlikely(busy) ? -get_time() : 0.0;
687
688 brw_bo_wait_rendering(bo);
689
690 if (unlikely(busy)) {
691 elapsed += get_time();
692 if (elapsed > 1e-5) /* 0.01ms */
693 perf_debug("%s a busy \"%s\" BO stalled and took %.03f ms.\n",
694 action, bo->name, elapsed * 1000);
695 }
696 }
697
698 static void
699 print_flags(unsigned flags)
700 {
701 if (flags & MAP_READ)
702 DBG("READ ");
703 if (flags & MAP_WRITE)
704 DBG("WRITE ");
705 if (flags & MAP_ASYNC)
706 DBG("ASYNC ");
707 if (flags & MAP_PERSISTENT)
708 DBG("PERSISTENT ");
709 if (flags & MAP_COHERENT)
710 DBG("COHERENT ");
711 if (flags & MAP_RAW)
712 DBG("RAW ");
713 DBG("\n");
714 }
715
716 static void *
717 brw_bo_map_cpu(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
718 {
719 struct brw_bufmgr *bufmgr = bo->bufmgr;
720
721 /* We disallow CPU maps for writing to non-coherent buffers, as the
722 * CPU map can become invalidated when a batch is flushed out, which
723 * can happen at unpredictable times. You should use WC maps instead.
724 */
725 assert(bo->cache_coherent || !(flags & MAP_WRITE));
726
727 if (!bo->map_cpu) {
728 DBG("brw_bo_map_cpu: %d (%s)\n", bo->gem_handle, bo->name);
729
730 struct drm_i915_gem_mmap mmap_arg = {
731 .handle = bo->gem_handle,
732 .size = bo->size,
733 };
734 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
735 if (ret != 0) {
736 ret = -errno;
737 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
738 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
739 return NULL;
740 }
741 void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
742 VG_DEFINED(map, bo->size);
743
744 if (p_atomic_cmpxchg(&bo->map_cpu, NULL, map)) {
745 VG_NOACCESS(map, bo->size);
746 drm_munmap(map, bo->size);
747 }
748 }
749 assert(bo->map_cpu);
750
751 DBG("brw_bo_map_cpu: %d (%s) -> %p, ", bo->gem_handle, bo->name,
752 bo->map_cpu);
753 print_flags(flags);
754
755 if (!(flags & MAP_ASYNC)) {
756 bo_wait_with_stall_warning(brw, bo, "CPU mapping");
757 }
758
759 if (!bo->cache_coherent && !bo->bufmgr->has_llc) {
760 /* If we're reusing an existing CPU mapping, the CPU caches may
761 * contain stale data from the last time we read from that mapping.
762 * (With the BO cache, it might even be data from a previous buffer!)
763 * Even if it's a brand new mapping, the kernel may have zeroed the
764 * buffer via CPU writes.
765 *
766 * We need to invalidate those cachelines so that we see the latest
767 * contents, and so long as we only read from the CPU mmap we do not
768 * need to write those cachelines back afterwards.
769 *
770 * On LLC, the emprical evidence suggests that writes from the GPU
771 * that bypass the LLC (i.e. for scanout) do *invalidate* the CPU
772 * cachelines. (Other reads, such as the display engine, bypass the
773 * LLC entirely requiring us to keep dirty pixels for the scanout
774 * out of any cache.)
775 */
776 gen_invalidate_range(bo->map_cpu, bo->size);
777 }
778
779 return bo->map_cpu;
780 }
781
782 static void *
783 brw_bo_map_wc(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
784 {
785 struct brw_bufmgr *bufmgr = bo->bufmgr;
786
787 if (!bufmgr->has_mmap_wc)
788 return NULL;
789
790 if (!bo->map_wc) {
791 DBG("brw_bo_map_wc: %d (%s)\n", bo->gem_handle, bo->name);
792
793 struct drm_i915_gem_mmap mmap_arg = {
794 .handle = bo->gem_handle,
795 .size = bo->size,
796 .flags = I915_MMAP_WC,
797 };
798 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
799 if (ret != 0) {
800 ret = -errno;
801 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
802 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
803 return NULL;
804 }
805
806 void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
807 VG_DEFINED(map, bo->size);
808
809 if (p_atomic_cmpxchg(&bo->map_wc, NULL, map)) {
810 VG_NOACCESS(map, bo->size);
811 drm_munmap(map, bo->size);
812 }
813 }
814 assert(bo->map_wc);
815
816 DBG("brw_bo_map_wc: %d (%s) -> %p\n", bo->gem_handle, bo->name, bo->map_wc);
817 print_flags(flags);
818
819 if (!(flags & MAP_ASYNC)) {
820 bo_wait_with_stall_warning(brw, bo, "WC mapping");
821 }
822
823 return bo->map_wc;
824 }
825
826 /**
827 * Perform an uncached mapping via the GTT.
828 *
829 * Write access through the GTT is not quite fully coherent. On low power
830 * systems especially, like modern Atoms, we can observe reads from RAM before
831 * the write via GTT has landed. A write memory barrier that flushes the Write
832 * Combining Buffer (i.e. sfence/mfence) is not sufficient to order the later
833 * read after the write as the GTT write suffers a small delay through the GTT
834 * indirection. The kernel uses an uncached mmio read to ensure the GTT write
835 * is ordered with reads (either by the GPU, WB or WC) and unconditionally
836 * flushes prior to execbuf submission. However, if we are not informing the
837 * kernel about our GTT writes, it will not flush before earlier access, such
838 * as when using the cmdparser. Similarly, we need to be careful if we should
839 * ever issue a CPU read immediately following a GTT write.
840 *
841 * Telling the kernel about write access also has one more important
842 * side-effect. Upon receiving notification about the write, it cancels any
843 * scanout buffering for FBC/PSR and friends. Later FBC/PSR is then flushed by
844 * either SW_FINISH or DIRTYFB. The presumption is that we never write to the
845 * actual scanout via a mmaping, only to a backbuffer and so all the FBC/PSR
846 * tracking is handled on the buffer exchange instead.
847 */
848 static void *
849 brw_bo_map_gtt(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
850 {
851 struct brw_bufmgr *bufmgr = bo->bufmgr;
852
853 /* Get a mapping of the buffer if we haven't before. */
854 if (bo->map_gtt == NULL) {
855 DBG("bo_map_gtt: mmap %d (%s)\n", bo->gem_handle, bo->name);
856
857 struct drm_i915_gem_mmap_gtt mmap_arg = { .handle = bo->gem_handle };
858
859 /* Get the fake offset back... */
860 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg);
861 if (ret != 0) {
862 DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
863 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
864 return NULL;
865 }
866
867 /* and mmap it. */
868 void *map = drm_mmap(0, bo->size, PROT_READ | PROT_WRITE,
869 MAP_SHARED, bufmgr->fd, mmap_arg.offset);
870 if (map == MAP_FAILED) {
871 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
872 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
873 return NULL;
874 }
875
876 /* We don't need to use VALGRIND_MALLOCLIKE_BLOCK because Valgrind will
877 * already intercept this mmap call. However, for consistency between
878 * all the mmap paths, we mark the pointer as defined now and mark it
879 * as inaccessible afterwards.
880 */
881 VG_DEFINED(map, bo->size);
882
883 if (p_atomic_cmpxchg(&bo->map_gtt, NULL, map)) {
884 VG_NOACCESS(map, bo->size);
885 drm_munmap(map, bo->size);
886 }
887 }
888 assert(bo->map_gtt);
889
890 DBG("bo_map_gtt: %d (%s) -> %p, ", bo->gem_handle, bo->name, bo->map_gtt);
891 print_flags(flags);
892
893 if (!(flags & MAP_ASYNC)) {
894 bo_wait_with_stall_warning(brw, bo, "GTT mapping");
895 }
896
897 return bo->map_gtt;
898 }
899
900 static bool
901 can_map_cpu(struct brw_bo *bo, unsigned flags)
902 {
903 if (bo->cache_coherent)
904 return true;
905
906 /* Even if the buffer itself is not cache-coherent (such as a scanout), on
907 * an LLC platform reads always are coherent (as they are performed via the
908 * central system agent). It is just the writes that we need to take special
909 * care to ensure that land in main memory and not stick in the CPU cache.
910 */
911 if (!(flags & MAP_WRITE) && bo->bufmgr->has_llc)
912 return true;
913
914 /* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
915 * across batch flushes where the kernel will change cache domains of the
916 * bo, invalidating continued access to the CPU mmap on non-LLC device.
917 *
918 * Similarly, ASYNC typically means that the buffer will be accessed via
919 * both the CPU and the GPU simultaneously. Batches may be executed that
920 * use the BO even while it is mapped. While OpenGL technically disallows
921 * most drawing while non-persistent mappings are active, we may still use
922 * the GPU for blits or other operations, causing batches to happen at
923 * inconvenient times.
924 */
925 if (flags & (MAP_PERSISTENT | MAP_COHERENT | MAP_ASYNC))
926 return false;
927
928 return !(flags & MAP_WRITE);
929 }
930
931 void *
932 brw_bo_map(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
933 {
934 if (bo->tiling_mode != I915_TILING_NONE && !(flags & MAP_RAW))
935 return brw_bo_map_gtt(brw, bo, flags);
936
937 void *map;
938
939 if (can_map_cpu(bo, flags))
940 map = brw_bo_map_cpu(brw, bo, flags);
941 else
942 map = brw_bo_map_wc(brw, bo, flags);
943
944 /* Allow the attempt to fail by falling back to the GTT where necessary.
945 *
946 * Not every buffer can be mmaped directly using the CPU (or WC), for
947 * example buffers that wrap stolen memory or are imported from other
948 * devices. For those, we have little choice but to use a GTT mmapping.
949 * However, if we use a slow GTT mmapping for reads where we expected fast
950 * access, that order of magnitude difference in throughput will be clearly
951 * expressed by angry users.
952 *
953 * We skip MAP_RAW because we want to avoid map_gtt's fence detiling.
954 */
955 if (!map && !(flags & MAP_RAW)) {
956 if (brw) {
957 perf_debug("Fallback GTT mapping for %s with access flags %x\n",
958 bo->name, flags);
959 }
960 map = brw_bo_map_gtt(brw, bo, flags);
961 }
962
963 return map;
964 }
965
966 int
967 brw_bo_subdata(struct brw_bo *bo, uint64_t offset,
968 uint64_t size, const void *data)
969 {
970 struct brw_bufmgr *bufmgr = bo->bufmgr;
971
972 struct drm_i915_gem_pwrite pwrite = {
973 .handle = bo->gem_handle,
974 .offset = offset,
975 .size = size,
976 .data_ptr = (uint64_t) (uintptr_t) data,
977 };
978
979 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_PWRITE, &pwrite);
980 if (ret != 0) {
981 ret = -errno;
982 DBG("%s:%d: Error writing data to buffer %d: "
983 "(%"PRIu64" %"PRIu64") %s .\n",
984 __FILE__, __LINE__, bo->gem_handle, offset, size, strerror(errno));
985 }
986
987 return ret;
988 }
989
990 /** Waits for all GPU rendering with the object to have completed. */
991 void
992 brw_bo_wait_rendering(struct brw_bo *bo)
993 {
994 /* We require a kernel recent enough for WAIT_IOCTL support.
995 * See intel_init_bufmgr()
996 */
997 brw_bo_wait(bo, -1);
998 }
999
1000 /**
1001 * Waits on a BO for the given amount of time.
1002 *
1003 * @bo: buffer object to wait for
1004 * @timeout_ns: amount of time to wait in nanoseconds.
1005 * If value is less than 0, an infinite wait will occur.
1006 *
1007 * Returns 0 if the wait was successful ie. the last batch referencing the
1008 * object has completed within the allotted time. Otherwise some negative return
1009 * value describes the error. Of particular interest is -ETIME when the wait has
1010 * failed to yield the desired result.
1011 *
1012 * Similar to brw_bo_wait_rendering except a timeout parameter allows
1013 * the operation to give up after a certain amount of time. Another subtle
1014 * difference is the internal locking semantics are different (this variant does
1015 * not hold the lock for the duration of the wait). This makes the wait subject
1016 * to a larger userspace race window.
1017 *
1018 * The implementation shall wait until the object is no longer actively
1019 * referenced within a batch buffer at the time of the call. The wait will
1020 * not guarantee that the buffer is re-issued via another thread, or an flinked
1021 * handle. Userspace must make sure this race does not occur if such precision
1022 * is important.
1023 *
1024 * Note that some kernels have broken the inifite wait for negative values
1025 * promise, upgrade to latest stable kernels if this is the case.
1026 */
1027 int
1028 brw_bo_wait(struct brw_bo *bo, int64_t timeout_ns)
1029 {
1030 struct brw_bufmgr *bufmgr = bo->bufmgr;
1031
1032 /* If we know it's idle, don't bother with the kernel round trip */
1033 if (bo->idle && !bo->external)
1034 return 0;
1035
1036 struct drm_i915_gem_wait wait = {
1037 .bo_handle = bo->gem_handle,
1038 .timeout_ns = timeout_ns,
1039 };
1040 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_WAIT, &wait);
1041 if (ret != 0)
1042 return -errno;
1043
1044 bo->idle = true;
1045
1046 return ret;
1047 }
1048
1049 void
1050 brw_bufmgr_destroy(struct brw_bufmgr *bufmgr)
1051 {
1052 mtx_destroy(&bufmgr->lock);
1053
1054 /* Free any cached buffer objects we were going to reuse */
1055 for (int i = 0; i < bufmgr->num_buckets; i++) {
1056 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1057
1058 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
1059 list_del(&bo->head);
1060
1061 bo_free(bo);
1062 }
1063 }
1064
1065 _mesa_hash_table_destroy(bufmgr->name_table, NULL);
1066 _mesa_hash_table_destroy(bufmgr->handle_table, NULL);
1067
1068 free(bufmgr);
1069 }
1070
1071 static int
1072 bo_set_tiling_internal(struct brw_bo *bo, uint32_t tiling_mode,
1073 uint32_t stride)
1074 {
1075 struct brw_bufmgr *bufmgr = bo->bufmgr;
1076 struct drm_i915_gem_set_tiling set_tiling;
1077 int ret;
1078
1079 if (bo->global_name == 0 &&
1080 tiling_mode == bo->tiling_mode && stride == bo->stride)
1081 return 0;
1082
1083 memset(&set_tiling, 0, sizeof(set_tiling));
1084 do {
1085 /* set_tiling is slightly broken and overwrites the
1086 * input on the error path, so we have to open code
1087 * rmIoctl.
1088 */
1089 set_tiling.handle = bo->gem_handle;
1090 set_tiling.tiling_mode = tiling_mode;
1091 set_tiling.stride = stride;
1092
1093 ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
1094 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
1095 if (ret == -1)
1096 return -errno;
1097
1098 bo->tiling_mode = set_tiling.tiling_mode;
1099 bo->swizzle_mode = set_tiling.swizzle_mode;
1100 bo->stride = set_tiling.stride;
1101 return 0;
1102 }
1103
1104 int
1105 brw_bo_get_tiling(struct brw_bo *bo, uint32_t *tiling_mode,
1106 uint32_t *swizzle_mode)
1107 {
1108 *tiling_mode = bo->tiling_mode;
1109 *swizzle_mode = bo->swizzle_mode;
1110 return 0;
1111 }
1112
1113 static struct brw_bo *
1114 brw_bo_gem_create_from_prime_internal(struct brw_bufmgr *bufmgr, int prime_fd,
1115 int tiling_mode, uint32_t stride)
1116 {
1117 uint32_t handle;
1118 struct brw_bo *bo;
1119
1120 mtx_lock(&bufmgr->lock);
1121 int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1122 if (ret) {
1123 DBG("create_from_prime: failed to obtain handle from fd: %s\n",
1124 strerror(errno));
1125 mtx_unlock(&bufmgr->lock);
1126 return NULL;
1127 }
1128
1129 /*
1130 * See if the kernel has already returned this buffer to us. Just as
1131 * for named buffers, we must not create two bo's pointing at the same
1132 * kernel object
1133 */
1134 bo = hash_find_bo(bufmgr->handle_table, handle);
1135 if (bo) {
1136 brw_bo_reference(bo);
1137 goto out;
1138 }
1139
1140 bo = calloc(1, sizeof(*bo));
1141 if (!bo)
1142 goto out;
1143
1144 p_atomic_set(&bo->refcount, 1);
1145
1146 /* Determine size of bo. The fd-to-handle ioctl really should
1147 * return the size, but it doesn't. If we have kernel 3.12 or
1148 * later, we can lseek on the prime fd to get the size. Older
1149 * kernels will just fail, in which case we fall back to the
1150 * provided (estimated or guess size). */
1151 ret = lseek(prime_fd, 0, SEEK_END);
1152 if (ret != -1)
1153 bo->size = ret;
1154
1155 bo->bufmgr = bufmgr;
1156
1157 bo->gem_handle = handle;
1158 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1159
1160 bo->name = "prime";
1161 bo->reusable = false;
1162 bo->external = true;
1163
1164 if (tiling_mode < 0) {
1165 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
1166 if (drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling))
1167 goto err;
1168
1169 bo->tiling_mode = get_tiling.tiling_mode;
1170 bo->swizzle_mode = get_tiling.swizzle_mode;
1171 /* XXX stride is unknown */
1172 } else {
1173 bo_set_tiling_internal(bo, tiling_mode, stride);
1174 }
1175
1176 out:
1177 mtx_unlock(&bufmgr->lock);
1178 return bo;
1179
1180 err:
1181 bo_free(bo);
1182 mtx_unlock(&bufmgr->lock);
1183 return NULL;
1184 }
1185
1186 struct brw_bo *
1187 brw_bo_gem_create_from_prime(struct brw_bufmgr *bufmgr, int prime_fd)
1188 {
1189 return brw_bo_gem_create_from_prime_internal(bufmgr, prime_fd, -1, 0);
1190 }
1191
1192 struct brw_bo *
1193 brw_bo_gem_create_from_prime_tiled(struct brw_bufmgr *bufmgr, int prime_fd,
1194 uint32_t tiling_mode, uint32_t stride)
1195 {
1196 assert(tiling_mode == I915_TILING_NONE ||
1197 tiling_mode == I915_TILING_X ||
1198 tiling_mode == I915_TILING_Y);
1199
1200 return brw_bo_gem_create_from_prime_internal(bufmgr, prime_fd,
1201 tiling_mode, stride);
1202 }
1203
1204 static void
1205 brw_bo_make_external(struct brw_bo *bo)
1206 {
1207 struct brw_bufmgr *bufmgr = bo->bufmgr;
1208
1209 if (!bo->external) {
1210 mtx_lock(&bufmgr->lock);
1211 if (!bo->external) {
1212 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1213 bo->external = true;
1214 }
1215 mtx_unlock(&bufmgr->lock);
1216 }
1217 }
1218
1219 int
1220 brw_bo_gem_export_to_prime(struct brw_bo *bo, int *prime_fd)
1221 {
1222 struct brw_bufmgr *bufmgr = bo->bufmgr;
1223
1224 brw_bo_make_external(bo);
1225
1226 if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1227 DRM_CLOEXEC, prime_fd) != 0)
1228 return -errno;
1229
1230 bo->reusable = false;
1231
1232 return 0;
1233 }
1234
1235 uint32_t
1236 brw_bo_export_gem_handle(struct brw_bo *bo)
1237 {
1238 brw_bo_make_external(bo);
1239
1240 return bo->gem_handle;
1241 }
1242
1243 int
1244 brw_bo_flink(struct brw_bo *bo, uint32_t *name)
1245 {
1246 struct brw_bufmgr *bufmgr = bo->bufmgr;
1247
1248 if (!bo->global_name) {
1249 struct drm_gem_flink flink = { .handle = bo->gem_handle };
1250
1251 if (drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1252 return -errno;
1253
1254 brw_bo_make_external(bo);
1255 mtx_lock(&bufmgr->lock);
1256 if (!bo->global_name) {
1257 bo->global_name = flink.name;
1258 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
1259 }
1260 mtx_unlock(&bufmgr->lock);
1261
1262 bo->reusable = false;
1263 }
1264
1265 *name = bo->global_name;
1266 return 0;
1267 }
1268
1269 /**
1270 * Enables unlimited caching of buffer objects for reuse.
1271 *
1272 * This is potentially very memory expensive, as the cache at each bucket
1273 * size is only bounded by how many buffers of that size we've managed to have
1274 * in flight at once.
1275 */
1276 void
1277 brw_bufmgr_enable_reuse(struct brw_bufmgr *bufmgr)
1278 {
1279 bufmgr->bo_reuse = true;
1280 }
1281
1282 static void
1283 add_bucket(struct brw_bufmgr *bufmgr, int size)
1284 {
1285 unsigned int i = bufmgr->num_buckets;
1286
1287 assert(i < ARRAY_SIZE(bufmgr->cache_bucket));
1288
1289 list_inithead(&bufmgr->cache_bucket[i].head);
1290 bufmgr->cache_bucket[i].size = size;
1291 bufmgr->num_buckets++;
1292
1293 assert(bucket_for_size(bufmgr, size) == &bufmgr->cache_bucket[i]);
1294 assert(bucket_for_size(bufmgr, size - 2048) == &bufmgr->cache_bucket[i]);
1295 assert(bucket_for_size(bufmgr, size + 1) != &bufmgr->cache_bucket[i]);
1296 }
1297
1298 static void
1299 init_cache_buckets(struct brw_bufmgr *bufmgr)
1300 {
1301 uint64_t size, cache_max_size = 64 * 1024 * 1024;
1302
1303 /* OK, so power of two buckets was too wasteful of memory.
1304 * Give 3 other sizes between each power of two, to hopefully
1305 * cover things accurately enough. (The alternative is
1306 * probably to just go for exact matching of sizes, and assume
1307 * that for things like composited window resize the tiled
1308 * width/height alignment and rounding of sizes to pages will
1309 * get us useful cache hit rates anyway)
1310 */
1311 add_bucket(bufmgr, 4096);
1312 add_bucket(bufmgr, 4096 * 2);
1313 add_bucket(bufmgr, 4096 * 3);
1314
1315 /* Initialize the linked lists for BO reuse cache. */
1316 for (size = 4 * 4096; size <= cache_max_size; size *= 2) {
1317 add_bucket(bufmgr, size);
1318
1319 add_bucket(bufmgr, size + size * 1 / 4);
1320 add_bucket(bufmgr, size + size * 2 / 4);
1321 add_bucket(bufmgr, size + size * 3 / 4);
1322 }
1323 }
1324
1325 uint32_t
1326 brw_create_hw_context(struct brw_bufmgr *bufmgr)
1327 {
1328 struct drm_i915_gem_context_create create = { };
1329 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create);
1330 if (ret != 0) {
1331 DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno));
1332 return 0;
1333 }
1334
1335 return create.ctx_id;
1336 }
1337
1338 int
1339 brw_hw_context_set_priority(struct brw_bufmgr *bufmgr,
1340 uint32_t ctx_id,
1341 int priority)
1342 {
1343 struct drm_i915_gem_context_param p = {
1344 .ctx_id = ctx_id,
1345 .param = I915_CONTEXT_PARAM_PRIORITY,
1346 .value = priority,
1347 };
1348 int err;
1349
1350 err = 0;
1351 if (drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM, &p))
1352 err = -errno;
1353
1354 return err;
1355 }
1356
1357 void
1358 brw_destroy_hw_context(struct brw_bufmgr *bufmgr, uint32_t ctx_id)
1359 {
1360 struct drm_i915_gem_context_destroy d = { .ctx_id = ctx_id };
1361
1362 if (ctx_id != 0 &&
1363 drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY, &d) != 0) {
1364 fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1365 strerror(errno));
1366 }
1367 }
1368
1369 int
1370 brw_reg_read(struct brw_bufmgr *bufmgr, uint32_t offset, uint64_t *result)
1371 {
1372 struct drm_i915_reg_read reg_read = { .offset = offset };
1373 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_REG_READ, &reg_read);
1374
1375 *result = reg_read.val;
1376 return ret;
1377 }
1378
1379 static int
1380 gem_param(int fd, int name)
1381 {
1382 int v = -1; /* No param uses (yet) the sign bit, reserve it for errors */
1383
1384 struct drm_i915_getparam gp = { .param = name, .value = &v };
1385 if (drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp))
1386 return -1;
1387
1388 return v;
1389 }
1390
1391 static bool
1392 gem_supports_48b_addresses(int fd)
1393 {
1394 struct drm_i915_gem_exec_object2 obj = {
1395 .flags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS,
1396 };
1397
1398 struct drm_i915_gem_execbuffer2 execbuf = {
1399 .buffers_ptr = (uintptr_t)&obj,
1400 .buffer_count = 1,
1401 .rsvd1 = 0xffffffu,
1402 };
1403
1404 int ret = drmIoctl(fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf);
1405
1406 return ret == -1 && errno == ENOENT;
1407 }
1408
1409 /**
1410 * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1411 * and manage map buffer objections.
1412 *
1413 * \param fd File descriptor of the opened DRM device.
1414 */
1415 struct brw_bufmgr *
1416 brw_bufmgr_init(struct gen_device_info *devinfo, int fd)
1417 {
1418 struct brw_bufmgr *bufmgr;
1419
1420 bufmgr = calloc(1, sizeof(*bufmgr));
1421 if (bufmgr == NULL)
1422 return NULL;
1423
1424 /* Handles to buffer objects belong to the device fd and are not
1425 * reference counted by the kernel. If the same fd is used by
1426 * multiple parties (threads sharing the same screen bufmgr, or
1427 * even worse the same device fd passed to multiple libraries)
1428 * ownership of those handles is shared by those independent parties.
1429 *
1430 * Don't do this! Ensure that each library/bufmgr has its own device
1431 * fd so that its namespace does not clash with another.
1432 */
1433 bufmgr->fd = fd;
1434
1435 if (mtx_init(&bufmgr->lock, mtx_plain) != 0) {
1436 free(bufmgr);
1437 return NULL;
1438 }
1439
1440 bufmgr->has_llc = devinfo->has_llc;
1441 bufmgr->has_mmap_wc = gem_param(fd, I915_PARAM_MMAP_VERSION) > 0;
1442 bufmgr->supports_48b_addresses =
1443 devinfo->gen >= 8 && gem_supports_48b_addresses(fd);
1444
1445 init_cache_buckets(bufmgr);
1446
1447 bufmgr->name_table =
1448 _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1449 bufmgr->handle_table =
1450 _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1451
1452 return bufmgr;
1453 }