i965: Drop alignment parameter from bo_alloc_internal().
[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)
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 = 0;
324 } else {
325 /* For non-render-target BOs (where we're probably
326 * going to map it first thing in order to fill it
327 * with data), check if the last BO in the cache is
328 * unbusy, and only reuse in that case. Otherwise,
329 * allocating a new buffer is probably faster than
330 * waiting for the GPU to finish.
331 */
332 bo = LIST_ENTRY(struct brw_bo, bucket->head.next, head);
333 if (!brw_bo_busy(bo)) {
334 alloc_from_cache = true;
335 list_del(&bo->head);
336 }
337 }
338
339 if (alloc_from_cache) {
340 if (!brw_bo_madvise(bo, I915_MADV_WILLNEED)) {
341 bo_free(bo);
342 brw_bo_cache_purge_bucket(bufmgr, bucket);
343 goto retry;
344 }
345
346 if (bo_set_tiling_internal(bo, tiling_mode, stride)) {
347 bo_free(bo);
348 goto retry;
349 }
350
351 if (zeroed) {
352 void *map = brw_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
353 if (!map) {
354 bo_free(bo);
355 goto retry;
356 }
357 memset(map, 0, bo_size);
358 }
359 }
360 }
361
362 if (!alloc_from_cache) {
363 bo = calloc(1, sizeof(*bo));
364 if (!bo)
365 goto err;
366
367 bo->size = bo_size;
368 bo->idle = true;
369
370 struct drm_i915_gem_create create = { .size = bo_size };
371
372 /* All new BOs we get from the kernel are zeroed, so we don't need to
373 * worry about that here.
374 */
375 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CREATE, &create);
376 if (ret != 0) {
377 free(bo);
378 goto err;
379 }
380
381 bo->gem_handle = create.handle;
382
383 bo->bufmgr = bufmgr;
384 bo->align = 0;
385
386 bo->tiling_mode = I915_TILING_NONE;
387 bo->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
388 bo->stride = 0;
389
390 if (bo_set_tiling_internal(bo, tiling_mode, stride))
391 goto err_free;
392
393 /* Calling set_domain() will allocate pages for the BO outside of the
394 * struct mutex lock in the kernel, which is more efficient than waiting
395 * to create them during the first execbuf that uses the BO.
396 */
397 struct drm_i915_gem_set_domain sd = {
398 .handle = bo->gem_handle,
399 .read_domains = I915_GEM_DOMAIN_CPU,
400 .write_domain = 0,
401 };
402
403 if (drmIoctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd) != 0)
404 goto err_free;
405 }
406
407 bo->name = name;
408 p_atomic_set(&bo->refcount, 1);
409 bo->reusable = true;
410 bo->cache_coherent = bufmgr->has_llc;
411 bo->index = -1;
412 if (bufmgr->supports_48b_addresses)
413 bo->kflags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
414
415 mtx_unlock(&bufmgr->lock);
416
417 DBG("bo_create: buf %d (%s) %llub\n", bo->gem_handle, bo->name,
418 (unsigned long long) size);
419
420 return bo;
421
422 err_free:
423 bo_free(bo);
424 err:
425 mtx_unlock(&bufmgr->lock);
426 return NULL;
427 }
428
429 struct brw_bo *
430 brw_bo_alloc(struct brw_bufmgr *bufmgr,
431 const char *name, uint64_t size, uint64_t alignment)
432 {
433 return bo_alloc_internal(bufmgr, name, size, 0, I915_TILING_NONE, 0);
434 }
435
436 struct brw_bo *
437 brw_bo_alloc_tiled(struct brw_bufmgr *bufmgr, const char *name,
438 uint64_t size, uint32_t tiling_mode, uint32_t pitch,
439 unsigned flags)
440 {
441 return bo_alloc_internal(bufmgr, name, size, flags, tiling_mode, pitch);
442 }
443
444 struct brw_bo *
445 brw_bo_alloc_tiled_2d(struct brw_bufmgr *bufmgr, const char *name,
446 int x, int y, int cpp, uint32_t tiling,
447 uint32_t *pitch, unsigned flags)
448 {
449 uint64_t size;
450 uint32_t stride;
451 unsigned long aligned_y, height_alignment;
452
453 /* If we're tiled, our allocations are in 8 or 32-row blocks,
454 * so failure to align our height means that we won't allocate
455 * enough pages.
456 *
457 * If we're untiled, we still have to align to 2 rows high
458 * because the data port accesses 2x2 blocks even if the
459 * bottom row isn't to be rendered, so failure to align means
460 * we could walk off the end of the GTT and fault. This is
461 * documented on 965, and may be the case on older chipsets
462 * too so we try to be careful.
463 */
464 aligned_y = y;
465 height_alignment = 2;
466
467 if (tiling == I915_TILING_X)
468 height_alignment = 8;
469 else if (tiling == I915_TILING_Y)
470 height_alignment = 32;
471 aligned_y = ALIGN(y, height_alignment);
472
473 stride = x * cpp;
474 stride = bo_tile_pitch(bufmgr, stride, tiling);
475 size = stride * aligned_y;
476 size = bo_tile_size(bufmgr, size, tiling);
477 *pitch = stride;
478
479 if (tiling == I915_TILING_NONE)
480 stride = 0;
481
482 return bo_alloc_internal(bufmgr, name, size, flags, tiling, stride);
483 }
484
485 /**
486 * Returns a brw_bo wrapping the given buffer object handle.
487 *
488 * This can be used when one application needs to pass a buffer object
489 * to another.
490 */
491 struct brw_bo *
492 brw_bo_gem_create_from_name(struct brw_bufmgr *bufmgr,
493 const char *name, unsigned int handle)
494 {
495 struct brw_bo *bo;
496
497 /* At the moment most applications only have a few named bo.
498 * For instance, in a DRI client only the render buffers passed
499 * between X and the client are named. And since X returns the
500 * alternating names for the front/back buffer a linear search
501 * provides a sufficiently fast match.
502 */
503 mtx_lock(&bufmgr->lock);
504 bo = hash_find_bo(bufmgr->name_table, handle);
505 if (bo) {
506 brw_bo_reference(bo);
507 goto out;
508 }
509
510 struct drm_gem_open open_arg = { .name = handle };
511 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
512 if (ret != 0) {
513 DBG("Couldn't reference %s handle 0x%08x: %s\n",
514 name, handle, strerror(errno));
515 bo = NULL;
516 goto out;
517 }
518 /* Now see if someone has used a prime handle to get this
519 * object from the kernel before by looking through the list
520 * again for a matching gem_handle
521 */
522 bo = hash_find_bo(bufmgr->handle_table, open_arg.handle);
523 if (bo) {
524 brw_bo_reference(bo);
525 goto out;
526 }
527
528 bo = calloc(1, sizeof(*bo));
529 if (!bo)
530 goto out;
531
532 p_atomic_set(&bo->refcount, 1);
533
534 bo->size = open_arg.size;
535 bo->gtt_offset = 0;
536 bo->bufmgr = bufmgr;
537 bo->gem_handle = open_arg.handle;
538 bo->name = name;
539 bo->global_name = handle;
540 bo->reusable = false;
541 bo->external = true;
542
543 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
544 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
545
546 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
547 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling);
548 if (ret != 0)
549 goto err_unref;
550
551 bo->tiling_mode = get_tiling.tiling_mode;
552 bo->swizzle_mode = get_tiling.swizzle_mode;
553 /* XXX stride is unknown */
554 DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
555
556 out:
557 mtx_unlock(&bufmgr->lock);
558 return bo;
559
560 err_unref:
561 bo_free(bo);
562 mtx_unlock(&bufmgr->lock);
563 return NULL;
564 }
565
566 static void
567 bo_free(struct brw_bo *bo)
568 {
569 struct brw_bufmgr *bufmgr = bo->bufmgr;
570
571 if (bo->map_cpu) {
572 VG_NOACCESS(bo->map_cpu, bo->size);
573 drm_munmap(bo->map_cpu, bo->size);
574 }
575 if (bo->map_wc) {
576 VG_NOACCESS(bo->map_wc, bo->size);
577 drm_munmap(bo->map_wc, bo->size);
578 }
579 if (bo->map_gtt) {
580 VG_NOACCESS(bo->map_gtt, bo->size);
581 drm_munmap(bo->map_gtt, bo->size);
582 }
583
584 if (bo->external) {
585 struct hash_entry *entry;
586
587 if (bo->global_name) {
588 entry = _mesa_hash_table_search(bufmgr->name_table, &bo->global_name);
589 _mesa_hash_table_remove(bufmgr->name_table, entry);
590 }
591
592 entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
593 _mesa_hash_table_remove(bufmgr->handle_table, entry);
594 }
595
596 /* Close this object */
597 struct drm_gem_close close = { .handle = bo->gem_handle };
598 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
599 if (ret != 0) {
600 DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
601 bo->gem_handle, bo->name, strerror(errno));
602 }
603 free(bo);
604 }
605
606 /** Frees all cached buffers significantly older than @time. */
607 static void
608 cleanup_bo_cache(struct brw_bufmgr *bufmgr, time_t time)
609 {
610 int i;
611
612 if (bufmgr->time == time)
613 return;
614
615 for (i = 0; i < bufmgr->num_buckets; i++) {
616 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
617
618 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
619 if (time - bo->free_time <= 1)
620 break;
621
622 list_del(&bo->head);
623
624 bo_free(bo);
625 }
626 }
627
628 bufmgr->time = time;
629 }
630
631 static void
632 bo_unreference_final(struct brw_bo *bo, time_t time)
633 {
634 struct brw_bufmgr *bufmgr = bo->bufmgr;
635 struct bo_cache_bucket *bucket;
636
637 DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
638
639 bucket = bucket_for_size(bufmgr, bo->size);
640 /* Put the buffer into our internal cache for reuse if we can. */
641 if (bufmgr->bo_reuse && bo->reusable && bucket != NULL &&
642 brw_bo_madvise(bo, I915_MADV_DONTNEED)) {
643 bo->free_time = time;
644
645 bo->name = NULL;
646 bo->kflags = 0;
647
648 list_addtail(&bo->head, &bucket->head);
649 } else {
650 bo_free(bo);
651 }
652 }
653
654 void
655 brw_bo_unreference(struct brw_bo *bo)
656 {
657 if (bo == NULL)
658 return;
659
660 assert(p_atomic_read(&bo->refcount) > 0);
661
662 if (atomic_add_unless(&bo->refcount, -1, 1)) {
663 struct brw_bufmgr *bufmgr = bo->bufmgr;
664 struct timespec time;
665
666 clock_gettime(CLOCK_MONOTONIC, &time);
667
668 mtx_lock(&bufmgr->lock);
669
670 if (p_atomic_dec_zero(&bo->refcount)) {
671 bo_unreference_final(bo, time.tv_sec);
672 cleanup_bo_cache(bufmgr, time.tv_sec);
673 }
674
675 mtx_unlock(&bufmgr->lock);
676 }
677 }
678
679 static void
680 bo_wait_with_stall_warning(struct brw_context *brw,
681 struct brw_bo *bo,
682 const char *action)
683 {
684 bool busy = brw && brw->perf_debug && !bo->idle;
685 double elapsed = unlikely(busy) ? -get_time() : 0.0;
686
687 brw_bo_wait_rendering(bo);
688
689 if (unlikely(busy)) {
690 elapsed += get_time();
691 if (elapsed > 1e-5) /* 0.01ms */
692 perf_debug("%s a busy \"%s\" BO stalled and took %.03f ms.\n",
693 action, bo->name, elapsed * 1000);
694 }
695 }
696
697 static void
698 print_flags(unsigned flags)
699 {
700 if (flags & MAP_READ)
701 DBG("READ ");
702 if (flags & MAP_WRITE)
703 DBG("WRITE ");
704 if (flags & MAP_ASYNC)
705 DBG("ASYNC ");
706 if (flags & MAP_PERSISTENT)
707 DBG("PERSISTENT ");
708 if (flags & MAP_COHERENT)
709 DBG("COHERENT ");
710 if (flags & MAP_RAW)
711 DBG("RAW ");
712 DBG("\n");
713 }
714
715 static void *
716 brw_bo_map_cpu(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
717 {
718 struct brw_bufmgr *bufmgr = bo->bufmgr;
719
720 /* We disallow CPU maps for writing to non-coherent buffers, as the
721 * CPU map can become invalidated when a batch is flushed out, which
722 * can happen at unpredictable times. You should use WC maps instead.
723 */
724 assert(bo->cache_coherent || !(flags & MAP_WRITE));
725
726 if (!bo->map_cpu) {
727 DBG("brw_bo_map_cpu: %d (%s)\n", bo->gem_handle, bo->name);
728
729 struct drm_i915_gem_mmap mmap_arg = {
730 .handle = bo->gem_handle,
731 .size = bo->size,
732 };
733 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
734 if (ret != 0) {
735 ret = -errno;
736 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
737 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
738 return NULL;
739 }
740 void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
741 VG_DEFINED(map, bo->size);
742
743 if (p_atomic_cmpxchg(&bo->map_cpu, NULL, map)) {
744 VG_NOACCESS(map, bo->size);
745 drm_munmap(map, bo->size);
746 }
747 }
748 assert(bo->map_cpu);
749
750 DBG("brw_bo_map_cpu: %d (%s) -> %p, ", bo->gem_handle, bo->name,
751 bo->map_cpu);
752 print_flags(flags);
753
754 if (!(flags & MAP_ASYNC)) {
755 bo_wait_with_stall_warning(brw, bo, "CPU mapping");
756 }
757
758 if (!bo->cache_coherent && !bo->bufmgr->has_llc) {
759 /* If we're reusing an existing CPU mapping, the CPU caches may
760 * contain stale data from the last time we read from that mapping.
761 * (With the BO cache, it might even be data from a previous buffer!)
762 * Even if it's a brand new mapping, the kernel may have zeroed the
763 * buffer via CPU writes.
764 *
765 * We need to invalidate those cachelines so that we see the latest
766 * contents, and so long as we only read from the CPU mmap we do not
767 * need to write those cachelines back afterwards.
768 *
769 * On LLC, the emprical evidence suggests that writes from the GPU
770 * that bypass the LLC (i.e. for scanout) do *invalidate* the CPU
771 * cachelines. (Other reads, such as the display engine, bypass the
772 * LLC entirely requiring us to keep dirty pixels for the scanout
773 * out of any cache.)
774 */
775 gen_invalidate_range(bo->map_cpu, bo->size);
776 }
777
778 return bo->map_cpu;
779 }
780
781 static void *
782 brw_bo_map_wc(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
783 {
784 struct brw_bufmgr *bufmgr = bo->bufmgr;
785
786 if (!bufmgr->has_mmap_wc)
787 return NULL;
788
789 if (!bo->map_wc) {
790 DBG("brw_bo_map_wc: %d (%s)\n", bo->gem_handle, bo->name);
791
792 struct drm_i915_gem_mmap mmap_arg = {
793 .handle = bo->gem_handle,
794 .size = bo->size,
795 .flags = I915_MMAP_WC,
796 };
797 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
798 if (ret != 0) {
799 ret = -errno;
800 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
801 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
802 return NULL;
803 }
804
805 void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
806 VG_DEFINED(map, bo->size);
807
808 if (p_atomic_cmpxchg(&bo->map_wc, NULL, map)) {
809 VG_NOACCESS(map, bo->size);
810 drm_munmap(map, bo->size);
811 }
812 }
813 assert(bo->map_wc);
814
815 DBG("brw_bo_map_wc: %d (%s) -> %p\n", bo->gem_handle, bo->name, bo->map_wc);
816 print_flags(flags);
817
818 if (!(flags & MAP_ASYNC)) {
819 bo_wait_with_stall_warning(brw, bo, "WC mapping");
820 }
821
822 return bo->map_wc;
823 }
824
825 /**
826 * Perform an uncached mapping via the GTT.
827 *
828 * Write access through the GTT is not quite fully coherent. On low power
829 * systems especially, like modern Atoms, we can observe reads from RAM before
830 * the write via GTT has landed. A write memory barrier that flushes the Write
831 * Combining Buffer (i.e. sfence/mfence) is not sufficient to order the later
832 * read after the write as the GTT write suffers a small delay through the GTT
833 * indirection. The kernel uses an uncached mmio read to ensure the GTT write
834 * is ordered with reads (either by the GPU, WB or WC) and unconditionally
835 * flushes prior to execbuf submission. However, if we are not informing the
836 * kernel about our GTT writes, it will not flush before earlier access, such
837 * as when using the cmdparser. Similarly, we need to be careful if we should
838 * ever issue a CPU read immediately following a GTT write.
839 *
840 * Telling the kernel about write access also has one more important
841 * side-effect. Upon receiving notification about the write, it cancels any
842 * scanout buffering for FBC/PSR and friends. Later FBC/PSR is then flushed by
843 * either SW_FINISH or DIRTYFB. The presumption is that we never write to the
844 * actual scanout via a mmaping, only to a backbuffer and so all the FBC/PSR
845 * tracking is handled on the buffer exchange instead.
846 */
847 static void *
848 brw_bo_map_gtt(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
849 {
850 struct brw_bufmgr *bufmgr = bo->bufmgr;
851
852 /* Get a mapping of the buffer if we haven't before. */
853 if (bo->map_gtt == NULL) {
854 DBG("bo_map_gtt: mmap %d (%s)\n", bo->gem_handle, bo->name);
855
856 struct drm_i915_gem_mmap_gtt mmap_arg = { .handle = bo->gem_handle };
857
858 /* Get the fake offset back... */
859 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg);
860 if (ret != 0) {
861 DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
862 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
863 return NULL;
864 }
865
866 /* and mmap it. */
867 void *map = drm_mmap(0, bo->size, PROT_READ | PROT_WRITE,
868 MAP_SHARED, bufmgr->fd, mmap_arg.offset);
869 if (map == MAP_FAILED) {
870 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
871 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
872 return NULL;
873 }
874
875 /* We don't need to use VALGRIND_MALLOCLIKE_BLOCK because Valgrind will
876 * already intercept this mmap call. However, for consistency between
877 * all the mmap paths, we mark the pointer as defined now and mark it
878 * as inaccessible afterwards.
879 */
880 VG_DEFINED(map, bo->size);
881
882 if (p_atomic_cmpxchg(&bo->map_gtt, NULL, map)) {
883 VG_NOACCESS(map, bo->size);
884 drm_munmap(map, bo->size);
885 }
886 }
887 assert(bo->map_gtt);
888
889 DBG("bo_map_gtt: %d (%s) -> %p, ", bo->gem_handle, bo->name, bo->map_gtt);
890 print_flags(flags);
891
892 if (!(flags & MAP_ASYNC)) {
893 bo_wait_with_stall_warning(brw, bo, "GTT mapping");
894 }
895
896 return bo->map_gtt;
897 }
898
899 static bool
900 can_map_cpu(struct brw_bo *bo, unsigned flags)
901 {
902 if (bo->cache_coherent)
903 return true;
904
905 /* Even if the buffer itself is not cache-coherent (such as a scanout), on
906 * an LLC platform reads always are coherent (as they are performed via the
907 * central system agent). It is just the writes that we need to take special
908 * care to ensure that land in main memory and not stick in the CPU cache.
909 */
910 if (!(flags & MAP_WRITE) && bo->bufmgr->has_llc)
911 return true;
912
913 /* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
914 * across batch flushes where the kernel will change cache domains of the
915 * bo, invalidating continued access to the CPU mmap on non-LLC device.
916 *
917 * Similarly, ASYNC typically means that the buffer will be accessed via
918 * both the CPU and the GPU simultaneously. Batches may be executed that
919 * use the BO even while it is mapped. While OpenGL technically disallows
920 * most drawing while non-persistent mappings are active, we may still use
921 * the GPU for blits or other operations, causing batches to happen at
922 * inconvenient times.
923 */
924 if (flags & (MAP_PERSISTENT | MAP_COHERENT | MAP_ASYNC))
925 return false;
926
927 return !(flags & MAP_WRITE);
928 }
929
930 void *
931 brw_bo_map(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
932 {
933 if (bo->tiling_mode != I915_TILING_NONE && !(flags & MAP_RAW))
934 return brw_bo_map_gtt(brw, bo, flags);
935
936 void *map;
937
938 if (can_map_cpu(bo, flags))
939 map = brw_bo_map_cpu(brw, bo, flags);
940 else
941 map = brw_bo_map_wc(brw, bo, flags);
942
943 /* Allow the attempt to fail by falling back to the GTT where necessary.
944 *
945 * Not every buffer can be mmaped directly using the CPU (or WC), for
946 * example buffers that wrap stolen memory or are imported from other
947 * devices. For those, we have little choice but to use a GTT mmapping.
948 * However, if we use a slow GTT mmapping for reads where we expected fast
949 * access, that order of magnitude difference in throughput will be clearly
950 * expressed by angry users.
951 *
952 * We skip MAP_RAW because we want to avoid map_gtt's fence detiling.
953 */
954 if (!map && !(flags & MAP_RAW)) {
955 if (brw) {
956 perf_debug("Fallback GTT mapping for %s with access flags %x\n",
957 bo->name, flags);
958 }
959 map = brw_bo_map_gtt(brw, bo, flags);
960 }
961
962 return map;
963 }
964
965 int
966 brw_bo_subdata(struct brw_bo *bo, uint64_t offset,
967 uint64_t size, const void *data)
968 {
969 struct brw_bufmgr *bufmgr = bo->bufmgr;
970
971 struct drm_i915_gem_pwrite pwrite = {
972 .handle = bo->gem_handle,
973 .offset = offset,
974 .size = size,
975 .data_ptr = (uint64_t) (uintptr_t) data,
976 };
977
978 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_PWRITE, &pwrite);
979 if (ret != 0) {
980 ret = -errno;
981 DBG("%s:%d: Error writing data to buffer %d: "
982 "(%"PRIu64" %"PRIu64") %s .\n",
983 __FILE__, __LINE__, bo->gem_handle, offset, size, strerror(errno));
984 }
985
986 return ret;
987 }
988
989 /** Waits for all GPU rendering with the object to have completed. */
990 void
991 brw_bo_wait_rendering(struct brw_bo *bo)
992 {
993 /* We require a kernel recent enough for WAIT_IOCTL support.
994 * See intel_init_bufmgr()
995 */
996 brw_bo_wait(bo, -1);
997 }
998
999 /**
1000 * Waits on a BO for the given amount of time.
1001 *
1002 * @bo: buffer object to wait for
1003 * @timeout_ns: amount of time to wait in nanoseconds.
1004 * If value is less than 0, an infinite wait will occur.
1005 *
1006 * Returns 0 if the wait was successful ie. the last batch referencing the
1007 * object has completed within the allotted time. Otherwise some negative return
1008 * value describes the error. Of particular interest is -ETIME when the wait has
1009 * failed to yield the desired result.
1010 *
1011 * Similar to brw_bo_wait_rendering except a timeout parameter allows
1012 * the operation to give up after a certain amount of time. Another subtle
1013 * difference is the internal locking semantics are different (this variant does
1014 * not hold the lock for the duration of the wait). This makes the wait subject
1015 * to a larger userspace race window.
1016 *
1017 * The implementation shall wait until the object is no longer actively
1018 * referenced within a batch buffer at the time of the call. The wait will
1019 * not guarantee that the buffer is re-issued via another thread, or an flinked
1020 * handle. Userspace must make sure this race does not occur if such precision
1021 * is important.
1022 *
1023 * Note that some kernels have broken the inifite wait for negative values
1024 * promise, upgrade to latest stable kernels if this is the case.
1025 */
1026 int
1027 brw_bo_wait(struct brw_bo *bo, int64_t timeout_ns)
1028 {
1029 struct brw_bufmgr *bufmgr = bo->bufmgr;
1030
1031 /* If we know it's idle, don't bother with the kernel round trip */
1032 if (bo->idle && !bo->external)
1033 return 0;
1034
1035 struct drm_i915_gem_wait wait = {
1036 .bo_handle = bo->gem_handle,
1037 .timeout_ns = timeout_ns,
1038 };
1039 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_WAIT, &wait);
1040 if (ret != 0)
1041 return -errno;
1042
1043 bo->idle = true;
1044
1045 return ret;
1046 }
1047
1048 void
1049 brw_bufmgr_destroy(struct brw_bufmgr *bufmgr)
1050 {
1051 mtx_destroy(&bufmgr->lock);
1052
1053 /* Free any cached buffer objects we were going to reuse */
1054 for (int i = 0; i < bufmgr->num_buckets; i++) {
1055 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1056
1057 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
1058 list_del(&bo->head);
1059
1060 bo_free(bo);
1061 }
1062 }
1063
1064 _mesa_hash_table_destroy(bufmgr->name_table, NULL);
1065 _mesa_hash_table_destroy(bufmgr->handle_table, NULL);
1066
1067 free(bufmgr);
1068 }
1069
1070 static int
1071 bo_set_tiling_internal(struct brw_bo *bo, uint32_t tiling_mode,
1072 uint32_t stride)
1073 {
1074 struct brw_bufmgr *bufmgr = bo->bufmgr;
1075 struct drm_i915_gem_set_tiling set_tiling;
1076 int ret;
1077
1078 if (bo->global_name == 0 &&
1079 tiling_mode == bo->tiling_mode && stride == bo->stride)
1080 return 0;
1081
1082 memset(&set_tiling, 0, sizeof(set_tiling));
1083 do {
1084 /* set_tiling is slightly broken and overwrites the
1085 * input on the error path, so we have to open code
1086 * rmIoctl.
1087 */
1088 set_tiling.handle = bo->gem_handle;
1089 set_tiling.tiling_mode = tiling_mode;
1090 set_tiling.stride = stride;
1091
1092 ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
1093 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
1094 if (ret == -1)
1095 return -errno;
1096
1097 bo->tiling_mode = set_tiling.tiling_mode;
1098 bo->swizzle_mode = set_tiling.swizzle_mode;
1099 bo->stride = set_tiling.stride;
1100 return 0;
1101 }
1102
1103 int
1104 brw_bo_get_tiling(struct brw_bo *bo, uint32_t *tiling_mode,
1105 uint32_t *swizzle_mode)
1106 {
1107 *tiling_mode = bo->tiling_mode;
1108 *swizzle_mode = bo->swizzle_mode;
1109 return 0;
1110 }
1111
1112 static struct brw_bo *
1113 brw_bo_gem_create_from_prime_internal(struct brw_bufmgr *bufmgr, int prime_fd,
1114 int tiling_mode, uint32_t stride)
1115 {
1116 uint32_t handle;
1117 struct brw_bo *bo;
1118
1119 mtx_lock(&bufmgr->lock);
1120 int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1121 if (ret) {
1122 DBG("create_from_prime: failed to obtain handle from fd: %s\n",
1123 strerror(errno));
1124 mtx_unlock(&bufmgr->lock);
1125 return NULL;
1126 }
1127
1128 /*
1129 * See if the kernel has already returned this buffer to us. Just as
1130 * for named buffers, we must not create two bo's pointing at the same
1131 * kernel object
1132 */
1133 bo = hash_find_bo(bufmgr->handle_table, handle);
1134 if (bo) {
1135 brw_bo_reference(bo);
1136 goto out;
1137 }
1138
1139 bo = calloc(1, sizeof(*bo));
1140 if (!bo)
1141 goto out;
1142
1143 p_atomic_set(&bo->refcount, 1);
1144
1145 /* Determine size of bo. The fd-to-handle ioctl really should
1146 * return the size, but it doesn't. If we have kernel 3.12 or
1147 * later, we can lseek on the prime fd to get the size. Older
1148 * kernels will just fail, in which case we fall back to the
1149 * provided (estimated or guess size). */
1150 ret = lseek(prime_fd, 0, SEEK_END);
1151 if (ret != -1)
1152 bo->size = ret;
1153
1154 bo->bufmgr = bufmgr;
1155
1156 bo->gem_handle = handle;
1157 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1158
1159 bo->name = "prime";
1160 bo->reusable = false;
1161 bo->external = true;
1162
1163 if (tiling_mode < 0) {
1164 struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
1165 if (drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling))
1166 goto err;
1167
1168 bo->tiling_mode = get_tiling.tiling_mode;
1169 bo->swizzle_mode = get_tiling.swizzle_mode;
1170 /* XXX stride is unknown */
1171 } else {
1172 bo_set_tiling_internal(bo, tiling_mode, stride);
1173 }
1174
1175 out:
1176 mtx_unlock(&bufmgr->lock);
1177 return bo;
1178
1179 err:
1180 bo_free(bo);
1181 mtx_unlock(&bufmgr->lock);
1182 return NULL;
1183 }
1184
1185 struct brw_bo *
1186 brw_bo_gem_create_from_prime(struct brw_bufmgr *bufmgr, int prime_fd)
1187 {
1188 return brw_bo_gem_create_from_prime_internal(bufmgr, prime_fd, -1, 0);
1189 }
1190
1191 struct brw_bo *
1192 brw_bo_gem_create_from_prime_tiled(struct brw_bufmgr *bufmgr, int prime_fd,
1193 uint32_t tiling_mode, uint32_t stride)
1194 {
1195 assert(tiling_mode == I915_TILING_NONE ||
1196 tiling_mode == I915_TILING_X ||
1197 tiling_mode == I915_TILING_Y);
1198
1199 return brw_bo_gem_create_from_prime_internal(bufmgr, prime_fd,
1200 tiling_mode, stride);
1201 }
1202
1203 static void
1204 brw_bo_make_external(struct brw_bo *bo)
1205 {
1206 struct brw_bufmgr *bufmgr = bo->bufmgr;
1207
1208 if (!bo->external) {
1209 mtx_lock(&bufmgr->lock);
1210 if (!bo->external) {
1211 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1212 bo->external = true;
1213 }
1214 mtx_unlock(&bufmgr->lock);
1215 }
1216 }
1217
1218 int
1219 brw_bo_gem_export_to_prime(struct brw_bo *bo, int *prime_fd)
1220 {
1221 struct brw_bufmgr *bufmgr = bo->bufmgr;
1222
1223 brw_bo_make_external(bo);
1224
1225 if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1226 DRM_CLOEXEC, prime_fd) != 0)
1227 return -errno;
1228
1229 bo->reusable = false;
1230
1231 return 0;
1232 }
1233
1234 uint32_t
1235 brw_bo_export_gem_handle(struct brw_bo *bo)
1236 {
1237 brw_bo_make_external(bo);
1238
1239 return bo->gem_handle;
1240 }
1241
1242 int
1243 brw_bo_flink(struct brw_bo *bo, uint32_t *name)
1244 {
1245 struct brw_bufmgr *bufmgr = bo->bufmgr;
1246
1247 if (!bo->global_name) {
1248 struct drm_gem_flink flink = { .handle = bo->gem_handle };
1249
1250 if (drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1251 return -errno;
1252
1253 brw_bo_make_external(bo);
1254 mtx_lock(&bufmgr->lock);
1255 if (!bo->global_name) {
1256 bo->global_name = flink.name;
1257 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
1258 }
1259 mtx_unlock(&bufmgr->lock);
1260
1261 bo->reusable = false;
1262 }
1263
1264 *name = bo->global_name;
1265 return 0;
1266 }
1267
1268 /**
1269 * Enables unlimited caching of buffer objects for reuse.
1270 *
1271 * This is potentially very memory expensive, as the cache at each bucket
1272 * size is only bounded by how many buffers of that size we've managed to have
1273 * in flight at once.
1274 */
1275 void
1276 brw_bufmgr_enable_reuse(struct brw_bufmgr *bufmgr)
1277 {
1278 bufmgr->bo_reuse = true;
1279 }
1280
1281 static void
1282 add_bucket(struct brw_bufmgr *bufmgr, int size)
1283 {
1284 unsigned int i = bufmgr->num_buckets;
1285
1286 assert(i < ARRAY_SIZE(bufmgr->cache_bucket));
1287
1288 list_inithead(&bufmgr->cache_bucket[i].head);
1289 bufmgr->cache_bucket[i].size = size;
1290 bufmgr->num_buckets++;
1291
1292 assert(bucket_for_size(bufmgr, size) == &bufmgr->cache_bucket[i]);
1293 assert(bucket_for_size(bufmgr, size - 2048) == &bufmgr->cache_bucket[i]);
1294 assert(bucket_for_size(bufmgr, size + 1) != &bufmgr->cache_bucket[i]);
1295 }
1296
1297 static void
1298 init_cache_buckets(struct brw_bufmgr *bufmgr)
1299 {
1300 uint64_t size, cache_max_size = 64 * 1024 * 1024;
1301
1302 /* OK, so power of two buckets was too wasteful of memory.
1303 * Give 3 other sizes between each power of two, to hopefully
1304 * cover things accurately enough. (The alternative is
1305 * probably to just go for exact matching of sizes, and assume
1306 * that for things like composited window resize the tiled
1307 * width/height alignment and rounding of sizes to pages will
1308 * get us useful cache hit rates anyway)
1309 */
1310 add_bucket(bufmgr, 4096);
1311 add_bucket(bufmgr, 4096 * 2);
1312 add_bucket(bufmgr, 4096 * 3);
1313
1314 /* Initialize the linked lists for BO reuse cache. */
1315 for (size = 4 * 4096; size <= cache_max_size; size *= 2) {
1316 add_bucket(bufmgr, size);
1317
1318 add_bucket(bufmgr, size + size * 1 / 4);
1319 add_bucket(bufmgr, size + size * 2 / 4);
1320 add_bucket(bufmgr, size + size * 3 / 4);
1321 }
1322 }
1323
1324 uint32_t
1325 brw_create_hw_context(struct brw_bufmgr *bufmgr)
1326 {
1327 struct drm_i915_gem_context_create create = { };
1328 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create);
1329 if (ret != 0) {
1330 DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno));
1331 return 0;
1332 }
1333
1334 return create.ctx_id;
1335 }
1336
1337 int
1338 brw_hw_context_set_priority(struct brw_bufmgr *bufmgr,
1339 uint32_t ctx_id,
1340 int priority)
1341 {
1342 struct drm_i915_gem_context_param p = {
1343 .ctx_id = ctx_id,
1344 .param = I915_CONTEXT_PARAM_PRIORITY,
1345 .value = priority,
1346 };
1347 int err;
1348
1349 err = 0;
1350 if (drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM, &p))
1351 err = -errno;
1352
1353 return err;
1354 }
1355
1356 void
1357 brw_destroy_hw_context(struct brw_bufmgr *bufmgr, uint32_t ctx_id)
1358 {
1359 struct drm_i915_gem_context_destroy d = { .ctx_id = ctx_id };
1360
1361 if (ctx_id != 0 &&
1362 drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY, &d) != 0) {
1363 fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1364 strerror(errno));
1365 }
1366 }
1367
1368 int
1369 brw_reg_read(struct brw_bufmgr *bufmgr, uint32_t offset, uint64_t *result)
1370 {
1371 struct drm_i915_reg_read reg_read = { .offset = offset };
1372 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_REG_READ, &reg_read);
1373
1374 *result = reg_read.val;
1375 return ret;
1376 }
1377
1378 static int
1379 gem_param(int fd, int name)
1380 {
1381 int v = -1; /* No param uses (yet) the sign bit, reserve it for errors */
1382
1383 struct drm_i915_getparam gp = { .param = name, .value = &v };
1384 if (drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp))
1385 return -1;
1386
1387 return v;
1388 }
1389
1390 static bool
1391 gem_supports_48b_addresses(int fd)
1392 {
1393 struct drm_i915_gem_exec_object2 obj = {
1394 .flags = EXEC_OBJECT_SUPPORTS_48B_ADDRESS,
1395 };
1396
1397 struct drm_i915_gem_execbuffer2 execbuf = {
1398 .buffers_ptr = (uintptr_t)&obj,
1399 .buffer_count = 1,
1400 .rsvd1 = 0xffffffu,
1401 };
1402
1403 int ret = drmIoctl(fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf);
1404
1405 return ret == -1 && errno == ENOENT;
1406 }
1407
1408 /**
1409 * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1410 * and manage map buffer objections.
1411 *
1412 * \param fd File descriptor of the opened DRM device.
1413 */
1414 struct brw_bufmgr *
1415 brw_bufmgr_init(struct gen_device_info *devinfo, int fd)
1416 {
1417 struct brw_bufmgr *bufmgr;
1418
1419 bufmgr = calloc(1, sizeof(*bufmgr));
1420 if (bufmgr == NULL)
1421 return NULL;
1422
1423 /* Handles to buffer objects belong to the device fd and are not
1424 * reference counted by the kernel. If the same fd is used by
1425 * multiple parties (threads sharing the same screen bufmgr, or
1426 * even worse the same device fd passed to multiple libraries)
1427 * ownership of those handles is shared by those independent parties.
1428 *
1429 * Don't do this! Ensure that each library/bufmgr has its own device
1430 * fd so that its namespace does not clash with another.
1431 */
1432 bufmgr->fd = fd;
1433
1434 if (mtx_init(&bufmgr->lock, mtx_plain) != 0) {
1435 free(bufmgr);
1436 return NULL;
1437 }
1438
1439 bufmgr->has_llc = devinfo->has_llc;
1440 bufmgr->has_mmap_wc = gem_param(fd, I915_PARAM_MMAP_VERSION) > 0;
1441 bufmgr->supports_48b_addresses =
1442 devinfo->gen >= 8 && gem_supports_48b_addresses(fd);
1443
1444 init_cache_buckets(bufmgr);
1445
1446 bufmgr->name_table =
1447 _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1448 bufmgr->handle_table =
1449 _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1450
1451 return bufmgr;
1452 }