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