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