i965: Assert that we don't use CPU write maps to non-coherent buffers.
[mesa.git] / src / mesa / drivers / dri / i965 / brw_bufmgr.c
1 /**************************************************************************
2 *
3 * Copyright © 2007 Red Hat Inc.
4 * Copyright © 2007-2012 Intel Corporation
5 * Copyright 2006 Tungsten Graphics, Inc., Bismarck, ND., USA
6 * All Rights Reserved.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the
10 * "Software"), to deal in the Software without restriction, including
11 * without limitation the rights to use, copy, modify, merge, publish,
12 * distribute, sub license, and/or sell copies of the Software, and to
13 * permit persons to whom the Software is furnished to do so, subject to
14 * the following conditions:
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
20 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22 * USE OR OTHER DEALINGS IN THE SOFTWARE.
23 *
24 * The above copyright notice and this permission notice (including the
25 * next paragraph) shall be included in all copies or substantial portions
26 * of the Software.
27 *
28 *
29 **************************************************************************/
30 /*
31 * Authors: Thomas Hellström <thomas-at-tungstengraphics-dot-com>
32 * Keith Whitwell <keithw-at-tungstengraphics-dot-com>
33 * Eric Anholt <eric@anholt.net>
34 * Dave Airlie <airlied@linux.ie>
35 */
36
37 #ifdef HAVE_CONFIG_H
38 #include "config.h"
39 #endif
40
41 #include <xf86drm.h>
42 #include <util/u_atomic.h>
43 #include <fcntl.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <assert.h>
49 #include <pthread.h>
50 #include <sys/ioctl.h>
51 #include <sys/stat.h>
52 #include <sys/types.h>
53 #include <stdbool.h>
54
55 #include "errno.h"
56 #ifndef ETIME
57 #define ETIME ETIMEDOUT
58 #endif
59 #include "common/gen_debug.h"
60 #include "common/gen_device_info.h"
61 #include "libdrm_macros.h"
62 #include "main/macros.h"
63 #include "util/macros.h"
64 #include "util/hash_table.h"
65 #include "util/list.h"
66 #include "brw_bufmgr.h"
67 #include "brw_context.h"
68 #include "string.h"
69
70 #include "i915_drm.h"
71
72 #ifdef HAVE_VALGRIND
73 #include <valgrind.h>
74 #include <memcheck.h>
75 #define VG(x) x
76 #else
77 #define VG(x)
78 #endif
79
80 #define memclear(s) memset(&s, 0, sizeof(s))
81
82 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
83
84 static inline int
85 atomic_add_unless(int *v, int add, int unless)
86 {
87 int c, old;
88 c = p_atomic_read(v);
89 while (c != unless && (old = p_atomic_cmpxchg(v, c, c + add)) != c)
90 c = old;
91 return c == unless;
92 }
93
94 struct bo_cache_bucket {
95 struct list_head head;
96 uint64_t size;
97 };
98
99 struct brw_bufmgr {
100 int fd;
101
102 pthread_mutex_t lock;
103
104 /** Array of lists of cached gem objects of power-of-two sizes */
105 struct bo_cache_bucket cache_bucket[14 * 4];
106 int num_buckets;
107 time_t time;
108
109 struct hash_table *name_table;
110 struct hash_table *handle_table;
111
112 bool has_llc:1;
113 bool bo_reuse:1;
114 };
115
116 static int bo_set_tiling_internal(struct brw_bo *bo, uint32_t tiling_mode,
117 uint32_t stride);
118
119 static void bo_free(struct brw_bo *bo);
120
121 static uint32_t
122 key_hash_uint(const void *key)
123 {
124 return _mesa_hash_data(key, 4);
125 }
126
127 static bool
128 key_uint_equal(const void *a, const void *b)
129 {
130 return *((unsigned *) a) == *((unsigned *) b);
131 }
132
133 static struct brw_bo *
134 hash_find_bo(struct hash_table *ht, unsigned int key)
135 {
136 struct hash_entry *entry = _mesa_hash_table_search(ht, &key);
137 return entry ? (struct brw_bo *) entry->data : NULL;
138 }
139
140 static uint64_t
141 bo_tile_size(struct brw_bufmgr *bufmgr, uint64_t size, uint32_t tiling)
142 {
143 if (tiling == I915_TILING_NONE)
144 return size;
145
146 /* 965+ just need multiples of page size for tiling */
147 return ALIGN(size, 4096);
148 }
149
150 /*
151 * Round a given pitch up to the minimum required for X tiling on a
152 * given chip. We use 512 as the minimum to allow for a later tiling
153 * change.
154 */
155 static uint32_t
156 bo_tile_pitch(struct brw_bufmgr *bufmgr, uint32_t pitch, uint32_t tiling)
157 {
158 unsigned long tile_width;
159
160 /* If untiled, then just align it so that we can do rendering
161 * to it with the 3D engine.
162 */
163 if (tiling == I915_TILING_NONE)
164 return ALIGN(pitch, 64);
165
166 if (tiling == I915_TILING_X)
167 tile_width = 512;
168 else
169 tile_width = 128;
170
171 /* 965 is flexible */
172 return ALIGN(pitch, tile_width);
173 }
174
175 static struct bo_cache_bucket *
176 bucket_for_size(struct brw_bufmgr *bufmgr, uint64_t size)
177 {
178 int i;
179
180 for (i = 0; i < bufmgr->num_buckets; i++) {
181 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
182 if (bucket->size >= size) {
183 return bucket;
184 }
185 }
186
187 return NULL;
188 }
189
190 inline void
191 brw_bo_reference(struct brw_bo *bo)
192 {
193 p_atomic_inc(&bo->refcount);
194 }
195
196 int
197 brw_bo_busy(struct brw_bo *bo)
198 {
199 struct brw_bufmgr *bufmgr = bo->bufmgr;
200 struct drm_i915_gem_busy busy;
201 int ret;
202
203 memclear(busy);
204 busy.handle = bo->gem_handle;
205
206 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_BUSY, &busy);
207 if (ret == 0) {
208 bo->idle = !busy.busy;
209 return busy.busy;
210 }
211 return false;
212 }
213
214 int
215 brw_bo_madvise(struct brw_bo *bo, int state)
216 {
217 struct drm_i915_gem_madvise madv;
218
219 memclear(madv);
220 madv.handle = bo->gem_handle;
221 madv.madv = state;
222 madv.retained = 1;
223 drmIoctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_MADVISE, &madv);
224
225 return madv.retained;
226 }
227
228 /* drop the oldest entries that have been purged by the kernel */
229 static void
230 brw_bo_cache_purge_bucket(struct brw_bufmgr *bufmgr,
231 struct bo_cache_bucket *bucket)
232 {
233 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
234 if (brw_bo_madvise(bo, I915_MADV_DONTNEED))
235 break;
236
237 list_del(&bo->head);
238 bo_free(bo);
239 }
240 }
241
242 static struct brw_bo *
243 bo_alloc_internal(struct brw_bufmgr *bufmgr,
244 const char *name,
245 uint64_t size,
246 unsigned flags,
247 uint32_t tiling_mode,
248 uint32_t stride, uint64_t alignment)
249 {
250 struct brw_bo *bo;
251 unsigned int page_size = getpagesize();
252 int ret;
253 struct bo_cache_bucket *bucket;
254 bool alloc_from_cache;
255 uint64_t bo_size;
256 bool for_render = false;
257
258 if (flags & BO_ALLOC_FOR_RENDER)
259 for_render = true;
260
261 /* Round the allocated size up to a power of two number of pages. */
262 bucket = bucket_for_size(bufmgr, size);
263
264 /* If we don't have caching at this size, don't actually round the
265 * allocation up.
266 */
267 if (bucket == NULL) {
268 bo_size = size;
269 if (bo_size < page_size)
270 bo_size = page_size;
271 } else {
272 bo_size = bucket->size;
273 }
274
275 pthread_mutex_lock(&bufmgr->lock);
276 /* Get a buffer out of the cache if available */
277 retry:
278 alloc_from_cache = false;
279 if (bucket != NULL && !list_empty(&bucket->head)) {
280 if (for_render) {
281 /* Allocate new render-target BOs from the tail (MRU)
282 * of the list, as it will likely be hot in the GPU
283 * cache and in the aperture for us.
284 */
285 bo = LIST_ENTRY(struct brw_bo, bucket->head.prev, head);
286 list_del(&bo->head);
287 alloc_from_cache = true;
288 bo->align = alignment;
289 } else {
290 assert(alignment == 0);
291 /* For non-render-target BOs (where we're probably
292 * going to map it first thing in order to fill it
293 * with data), check if the last BO in the cache is
294 * unbusy, and only reuse in that case. Otherwise,
295 * allocating a new buffer is probably faster than
296 * waiting for the GPU to finish.
297 */
298 bo = LIST_ENTRY(struct brw_bo, bucket->head.next, head);
299 if (!brw_bo_busy(bo)) {
300 alloc_from_cache = true;
301 list_del(&bo->head);
302 }
303 }
304
305 if (alloc_from_cache) {
306 if (!brw_bo_madvise(bo, I915_MADV_WILLNEED)) {
307 bo_free(bo);
308 brw_bo_cache_purge_bucket(bufmgr, bucket);
309 goto retry;
310 }
311
312 if (bo_set_tiling_internal(bo, tiling_mode, stride)) {
313 bo_free(bo);
314 goto retry;
315 }
316 }
317 }
318
319 if (!alloc_from_cache) {
320 struct drm_i915_gem_create create;
321
322 bo = calloc(1, sizeof(*bo));
323 if (!bo)
324 goto err;
325
326 bo->size = bo_size;
327 bo->idle = true;
328
329 memclear(create);
330 create.size = bo_size;
331
332 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CREATE, &create);
333 if (ret != 0) {
334 free(bo);
335 goto err;
336 }
337
338 bo->gem_handle = create.handle;
339 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
340
341 bo->bufmgr = bufmgr;
342 bo->align = alignment;
343
344 bo->tiling_mode = I915_TILING_NONE;
345 bo->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
346 bo->stride = 0;
347
348 if (bo_set_tiling_internal(bo, tiling_mode, stride))
349 goto err_free;
350 }
351
352 bo->name = name;
353 p_atomic_set(&bo->refcount, 1);
354 bo->reusable = true;
355 bo->cache_coherent = bufmgr->has_llc;
356
357 pthread_mutex_unlock(&bufmgr->lock);
358
359 DBG("bo_create: buf %d (%s) %ldb\n", bo->gem_handle, bo->name, size);
360
361 return bo;
362
363 err_free:
364 bo_free(bo);
365 err:
366 pthread_mutex_unlock(&bufmgr->lock);
367 return NULL;
368 }
369
370 struct brw_bo *
371 brw_bo_alloc(struct brw_bufmgr *bufmgr,
372 const char *name, uint64_t size, uint64_t alignment)
373 {
374 return bo_alloc_internal(bufmgr, name, size, 0, I915_TILING_NONE, 0, 0);
375 }
376
377 struct brw_bo *
378 brw_bo_alloc_tiled(struct brw_bufmgr *bufmgr, const char *name,
379 uint64_t size, uint32_t tiling_mode, uint32_t pitch,
380 unsigned flags)
381 {
382 return bo_alloc_internal(bufmgr, name, size, flags, tiling_mode, pitch, 0);
383 }
384
385 struct brw_bo *
386 brw_bo_alloc_tiled_2d(struct brw_bufmgr *bufmgr, const char *name,
387 int x, int y, int cpp, uint32_t tiling,
388 uint32_t *pitch, unsigned flags)
389 {
390 uint64_t size;
391 uint32_t stride;
392 unsigned long aligned_y, height_alignment;
393
394 /* If we're tiled, our allocations are in 8 or 32-row blocks,
395 * so failure to align our height means that we won't allocate
396 * enough pages.
397 *
398 * If we're untiled, we still have to align to 2 rows high
399 * because the data port accesses 2x2 blocks even if the
400 * bottom row isn't to be rendered, so failure to align means
401 * we could walk off the end of the GTT and fault. This is
402 * documented on 965, and may be the case on older chipsets
403 * too so we try to be careful.
404 */
405 aligned_y = y;
406 height_alignment = 2;
407
408 if (tiling == I915_TILING_X)
409 height_alignment = 8;
410 else if (tiling == I915_TILING_Y)
411 height_alignment = 32;
412 aligned_y = ALIGN(y, height_alignment);
413
414 stride = x * cpp;
415 stride = bo_tile_pitch(bufmgr, stride, tiling);
416 size = stride * aligned_y;
417 size = bo_tile_size(bufmgr, size, tiling);
418 *pitch = stride;
419
420 if (tiling == I915_TILING_NONE)
421 stride = 0;
422
423 return bo_alloc_internal(bufmgr, name, size, flags, tiling, stride, 0);
424 }
425
426 /**
427 * Returns a brw_bo wrapping the given buffer object handle.
428 *
429 * This can be used when one application needs to pass a buffer object
430 * to another.
431 */
432 struct brw_bo *
433 brw_bo_gem_create_from_name(struct brw_bufmgr *bufmgr,
434 const char *name, unsigned int handle)
435 {
436 struct brw_bo *bo;
437 int ret;
438 struct drm_gem_open open_arg;
439 struct drm_i915_gem_get_tiling get_tiling;
440
441 /* At the moment most applications only have a few named bo.
442 * For instance, in a DRI client only the render buffers passed
443 * between X and the client are named. And since X returns the
444 * alternating names for the front/back buffer a linear search
445 * provides a sufficiently fast match.
446 */
447 pthread_mutex_lock(&bufmgr->lock);
448 bo = hash_find_bo(bufmgr->name_table, handle);
449 if (bo) {
450 brw_bo_reference(bo);
451 goto out;
452 }
453
454 memclear(open_arg);
455 open_arg.name = handle;
456 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
457 if (ret != 0) {
458 DBG("Couldn't reference %s handle 0x%08x: %s\n",
459 name, handle, strerror(errno));
460 bo = NULL;
461 goto out;
462 }
463 /* Now see if someone has used a prime handle to get this
464 * object from the kernel before by looking through the list
465 * again for a matching gem_handle
466 */
467 bo = hash_find_bo(bufmgr->handle_table, open_arg.handle);
468 if (bo) {
469 brw_bo_reference(bo);
470 goto out;
471 }
472
473 bo = calloc(1, sizeof(*bo));
474 if (!bo)
475 goto out;
476
477 p_atomic_set(&bo->refcount, 1);
478
479 bo->size = open_arg.size;
480 bo->offset64 = 0;
481 bo->bufmgr = bufmgr;
482 bo->gem_handle = open_arg.handle;
483 bo->name = name;
484 bo->global_name = handle;
485 bo->reusable = false;
486 bo->external = true;
487
488 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
489 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
490
491 memclear(get_tiling);
492 get_tiling.handle = bo->gem_handle;
493 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling);
494 if (ret != 0)
495 goto err_unref;
496
497 bo->tiling_mode = get_tiling.tiling_mode;
498 bo->swizzle_mode = get_tiling.swizzle_mode;
499 /* XXX stride is unknown */
500 DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
501
502 out:
503 pthread_mutex_unlock(&bufmgr->lock);
504 return bo;
505
506 err_unref:
507 bo_free(bo);
508 pthread_mutex_unlock(&bufmgr->lock);
509 return NULL;
510 }
511
512 static void
513 bo_free(struct brw_bo *bo)
514 {
515 struct brw_bufmgr *bufmgr = bo->bufmgr;
516 struct drm_gem_close close;
517 struct hash_entry *entry;
518 int ret;
519
520 if (bo->map_cpu) {
521 VG(VALGRIND_FREELIKE_BLOCK(bo->map_cpu, 0));
522 drm_munmap(bo->map_cpu, bo->size);
523 }
524 if (bo->map_wc) {
525 VG(VALGRIND_FREELIKE_BLOCK(bo->map_wc, 0));
526 drm_munmap(bo->map_wc, bo->size);
527 }
528 if (bo->map_gtt) {
529 drm_munmap(bo->map_gtt, bo->size);
530 }
531
532 if (bo->global_name) {
533 entry = _mesa_hash_table_search(bufmgr->name_table, &bo->global_name);
534 _mesa_hash_table_remove(bufmgr->name_table, entry);
535 }
536 entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
537 _mesa_hash_table_remove(bufmgr->handle_table, entry);
538
539 /* Close this object */
540 memclear(close);
541 close.handle = bo->gem_handle;
542 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
543 if (ret != 0) {
544 DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
545 bo->gem_handle, bo->name, strerror(errno));
546 }
547 free(bo);
548 }
549
550 /** Frees all cached buffers significantly older than @time. */
551 static void
552 cleanup_bo_cache(struct brw_bufmgr *bufmgr, time_t time)
553 {
554 int i;
555
556 if (bufmgr->time == time)
557 return;
558
559 for (i = 0; i < bufmgr->num_buckets; i++) {
560 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
561
562 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
563 if (time - bo->free_time <= 1)
564 break;
565
566 list_del(&bo->head);
567
568 bo_free(bo);
569 }
570 }
571
572 bufmgr->time = time;
573 }
574
575 static void
576 bo_unreference_final(struct brw_bo *bo, time_t time)
577 {
578 struct brw_bufmgr *bufmgr = bo->bufmgr;
579 struct bo_cache_bucket *bucket;
580
581 DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
582
583 bucket = bucket_for_size(bufmgr, bo->size);
584 /* Put the buffer into our internal cache for reuse if we can. */
585 if (bufmgr->bo_reuse && bo->reusable && bucket != NULL &&
586 brw_bo_madvise(bo, I915_MADV_DONTNEED)) {
587 bo->free_time = time;
588
589 bo->name = NULL;
590 bo->kflags = 0;
591
592 list_addtail(&bo->head, &bucket->head);
593 } else {
594 bo_free(bo);
595 }
596 }
597
598 void
599 brw_bo_unreference(struct brw_bo *bo)
600 {
601 if (bo == NULL)
602 return;
603
604 assert(p_atomic_read(&bo->refcount) > 0);
605
606 if (atomic_add_unless(&bo->refcount, -1, 1)) {
607 struct brw_bufmgr *bufmgr = bo->bufmgr;
608 struct timespec time;
609
610 clock_gettime(CLOCK_MONOTONIC, &time);
611
612 pthread_mutex_lock(&bufmgr->lock);
613
614 if (p_atomic_dec_zero(&bo->refcount)) {
615 bo_unreference_final(bo, time.tv_sec);
616 cleanup_bo_cache(bufmgr, time.tv_sec);
617 }
618
619 pthread_mutex_unlock(&bufmgr->lock);
620 }
621 }
622
623 static void
624 set_domain(struct brw_context *brw, const char *action,
625 struct brw_bo *bo, uint32_t read_domains, uint32_t write_domain)
626 {
627 struct drm_i915_gem_set_domain sd = {
628 .handle = bo->gem_handle,
629 .read_domains = read_domains,
630 .write_domain = write_domain,
631 };
632
633 double elapsed = unlikely(brw && brw->perf_debug) ? -get_time() : 0.0;
634
635 if (drmIoctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd) != 0) {
636 DBG("%s:%d: Error setting memory domains %d (%08x %08x): %s.\n",
637 __FILE__, __LINE__, bo->gem_handle, read_domains, write_domain,
638 strerror(errno));
639 }
640
641 if (unlikely(brw && brw->perf_debug)) {
642 elapsed += get_time();
643 if (elapsed > 1e-5) /* 0.01ms */
644 perf_debug("%s a busy \"%s\" BO stalled and took %.03f ms.\n",
645 action, bo->name, elapsed * 1000);
646 }
647 }
648
649 static void
650 print_flags(unsigned flags)
651 {
652 if (flags & MAP_READ)
653 DBG("READ ");
654 if (flags & MAP_WRITE)
655 DBG("WRITE ");
656 if (flags & MAP_ASYNC)
657 DBG("ASYNC ");
658 if (flags & MAP_PERSISTENT)
659 DBG("PERSISTENT ");
660 if (flags & MAP_COHERENT)
661 DBG("COHERENT ");
662 if (flags & MAP_RAW)
663 DBG("RAW ");
664 DBG("\n");
665 }
666
667 static void *
668 brw_bo_map_cpu(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
669 {
670 struct brw_bufmgr *bufmgr = bo->bufmgr;
671
672 /* We disallow CPU maps for writing to non-coherent buffers, as the
673 * CPU map can become invalidated when a batch is flushed out, which
674 * can happen at unpredictable times. You should use WC maps instead.
675 */
676 assert(bo->cache_coherent || !(flags & MAP_WRITE));
677
678 if (!bo->map_cpu) {
679 struct drm_i915_gem_mmap mmap_arg;
680 void *map;
681
682 DBG("brw_bo_map_cpu: %d (%s)\n", bo->gem_handle, bo->name);
683
684 memclear(mmap_arg);
685 mmap_arg.handle = bo->gem_handle;
686 mmap_arg.size = bo->size;
687 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
688 if (ret != 0) {
689 ret = -errno;
690 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
691 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
692 return NULL;
693 }
694 VG(VALGRIND_MALLOCLIKE_BLOCK(mmap_arg.addr_ptr, mmap_arg.size, 0, 1));
695 map = (void *) (uintptr_t) mmap_arg.addr_ptr;
696
697 if (p_atomic_cmpxchg(&bo->map_cpu, NULL, map)) {
698 VG(VALGRIND_FREELIKE_BLOCK(map, 0));
699 drm_munmap(map, bo->size);
700 }
701 }
702 DBG("brw_bo_map_cpu: %d (%s) -> %p, ", bo->gem_handle, bo->name,
703 bo->map_cpu);
704 print_flags(flags);
705
706 if (!(flags & MAP_ASYNC) || !bufmgr->has_llc) {
707 set_domain(brw, "CPU mapping", bo, I915_GEM_DOMAIN_CPU,
708 flags & MAP_WRITE ? I915_GEM_DOMAIN_CPU : 0);
709 }
710
711 return bo->map_cpu;
712 }
713
714 static void *
715 brw_bo_map_gtt(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
716 {
717 struct brw_bufmgr *bufmgr = bo->bufmgr;
718
719 /* Get a mapping of the buffer if we haven't before. */
720 if (bo->map_gtt == NULL) {
721 struct drm_i915_gem_mmap_gtt mmap_arg;
722 void *map;
723
724 DBG("bo_map_gtt: mmap %d (%s)\n", bo->gem_handle, bo->name);
725
726 memclear(mmap_arg);
727 mmap_arg.handle = bo->gem_handle;
728
729 /* Get the fake offset back... */
730 int ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg);
731 if (ret != 0) {
732 DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
733 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
734 pthread_mutex_unlock(&bufmgr->lock);
735 return NULL;
736 }
737
738 /* and mmap it. We don't need to use VALGRIND_MALLOCLIKE_BLOCK
739 * because Valgrind will already intercept this mmap call.
740 */
741 map = drm_mmap(0, bo->size, PROT_READ | PROT_WRITE,
742 MAP_SHARED, bufmgr->fd, mmap_arg.offset);
743 if (map == MAP_FAILED) {
744 DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
745 __FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
746 return NULL;
747 }
748
749 if (p_atomic_cmpxchg(&bo->map_gtt, NULL, map)) {
750 drm_munmap(map, bo->size);
751 }
752 }
753
754 DBG("bo_map_gtt: %d (%s) -> %p, ", bo->gem_handle, bo->name, bo->map_gtt);
755 print_flags(flags);
756
757 if (!(flags & MAP_ASYNC) || !bufmgr->has_llc) {
758 set_domain(brw, "GTT mapping", bo,
759 I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);
760 }
761
762 return bo->map_gtt;
763 }
764
765 static bool
766 can_map_cpu(struct brw_bo *bo, unsigned flags)
767 {
768 if (bo->cache_coherent)
769 return true;
770
771 /* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
772 * across batch flushes where the kernel will change cache domains of the
773 * bo, invalidating continued access to the CPU mmap on non-LLC device.
774 *
775 * Similarly, ASYNC typically means that the buffer will be accessed via
776 * both the CPU and the GPU simultaneously. Batches may be executed that
777 * use the BO even while it is mapped. While OpenGL technically disallows
778 * most drawing while non-persistent mappings are active, we may still use
779 * the GPU for blits or other operations, causing batches to happen at
780 * inconvenient times.
781 */
782 if (flags & (MAP_PERSISTENT | MAP_COHERENT | MAP_ASYNC))
783 return false;
784
785 return !(flags & MAP_WRITE);
786 }
787
788 void *
789 brw_bo_map(struct brw_context *brw, struct brw_bo *bo, unsigned flags)
790 {
791 if (bo->tiling_mode != I915_TILING_NONE && !(flags & MAP_RAW))
792 return brw_bo_map_gtt(brw, bo, flags);
793 else if (can_map_cpu(bo, flags))
794 return brw_bo_map_cpu(brw, bo, flags);
795 else
796 return brw_bo_map_gtt(brw, bo, flags);
797 }
798
799 int
800 brw_bo_subdata(struct brw_bo *bo, uint64_t offset,
801 uint64_t size, const void *data)
802 {
803 struct brw_bufmgr *bufmgr = bo->bufmgr;
804 struct drm_i915_gem_pwrite pwrite;
805 int ret;
806
807 memclear(pwrite);
808 pwrite.handle = bo->gem_handle;
809 pwrite.offset = offset;
810 pwrite.size = size;
811 pwrite.data_ptr = (uint64_t) (uintptr_t) data;
812 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_PWRITE, &pwrite);
813 if (ret != 0) {
814 ret = -errno;
815 DBG("%s:%d: Error writing data to buffer %d: "
816 "(%"PRIu64" %"PRIu64") %s .\n",
817 __FILE__, __LINE__, bo->gem_handle, offset, size, strerror(errno));
818 }
819
820 return ret;
821 }
822
823 int
824 brw_bo_get_subdata(struct brw_bo *bo, uint64_t offset,
825 uint64_t size, void *data)
826 {
827 struct brw_bufmgr *bufmgr = bo->bufmgr;
828 struct drm_i915_gem_pread pread;
829 int ret;
830
831 memclear(pread);
832 pread.handle = bo->gem_handle;
833 pread.offset = offset;
834 pread.size = size;
835 pread.data_ptr = (uint64_t) (uintptr_t) data;
836 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_PREAD, &pread);
837 if (ret != 0) {
838 ret = -errno;
839 DBG("%s:%d: Error reading data from buffer %d: "
840 "(%"PRIu64" %"PRIu64") %s .\n",
841 __FILE__, __LINE__, bo->gem_handle, offset, size, strerror(errno));
842 }
843
844 return ret;
845 }
846
847 /** Waits for all GPU rendering with the object to have completed. */
848 void
849 brw_bo_wait_rendering(struct brw_bo *bo)
850 {
851 /* We require a kernel recent enough for WAIT_IOCTL support.
852 * See intel_init_bufmgr()
853 */
854 brw_bo_wait(bo, -1);
855 }
856
857 /**
858 * Waits on a BO for the given amount of time.
859 *
860 * @bo: buffer object to wait for
861 * @timeout_ns: amount of time to wait in nanoseconds.
862 * If value is less than 0, an infinite wait will occur.
863 *
864 * Returns 0 if the wait was successful ie. the last batch referencing the
865 * object has completed within the allotted time. Otherwise some negative return
866 * value describes the error. Of particular interest is -ETIME when the wait has
867 * failed to yield the desired result.
868 *
869 * Similar to brw_bo_wait_rendering except a timeout parameter allows
870 * the operation to give up after a certain amount of time. Another subtle
871 * difference is the internal locking semantics are different (this variant does
872 * not hold the lock for the duration of the wait). This makes the wait subject
873 * to a larger userspace race window.
874 *
875 * The implementation shall wait until the object is no longer actively
876 * referenced within a batch buffer at the time of the call. The wait will
877 * not guarantee that the buffer is re-issued via another thread, or an flinked
878 * handle. Userspace must make sure this race does not occur if such precision
879 * is important.
880 *
881 * Note that some kernels have broken the inifite wait for negative values
882 * promise, upgrade to latest stable kernels if this is the case.
883 */
884 int
885 brw_bo_wait(struct brw_bo *bo, int64_t timeout_ns)
886 {
887 struct brw_bufmgr *bufmgr = bo->bufmgr;
888 struct drm_i915_gem_wait wait;
889 int ret;
890
891 memclear(wait);
892 wait.bo_handle = bo->gem_handle;
893 wait.timeout_ns = timeout_ns;
894 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_WAIT, &wait);
895 if (ret == -1)
896 return -errno;
897
898 return ret;
899 }
900
901 void
902 brw_bufmgr_destroy(struct brw_bufmgr *bufmgr)
903 {
904 pthread_mutex_destroy(&bufmgr->lock);
905
906 /* Free any cached buffer objects we were going to reuse */
907 for (int i = 0; i < bufmgr->num_buckets; i++) {
908 struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
909
910 list_for_each_entry_safe(struct brw_bo, bo, &bucket->head, head) {
911 list_del(&bo->head);
912
913 bo_free(bo);
914 }
915 }
916
917 _mesa_hash_table_destroy(bufmgr->name_table, NULL);
918 _mesa_hash_table_destroy(bufmgr->handle_table, NULL);
919
920 free(bufmgr);
921 }
922
923 static int
924 bo_set_tiling_internal(struct brw_bo *bo, uint32_t tiling_mode,
925 uint32_t stride)
926 {
927 struct brw_bufmgr *bufmgr = bo->bufmgr;
928 struct drm_i915_gem_set_tiling set_tiling;
929 int ret;
930
931 if (bo->global_name == 0 &&
932 tiling_mode == bo->tiling_mode && stride == bo->stride)
933 return 0;
934
935 memset(&set_tiling, 0, sizeof(set_tiling));
936 do {
937 /* set_tiling is slightly broken and overwrites the
938 * input on the error path, so we have to open code
939 * rmIoctl.
940 */
941 set_tiling.handle = bo->gem_handle;
942 set_tiling.tiling_mode = tiling_mode;
943 set_tiling.stride = stride;
944
945 ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
946 } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
947 if (ret == -1)
948 return -errno;
949
950 bo->tiling_mode = set_tiling.tiling_mode;
951 bo->swizzle_mode = set_tiling.swizzle_mode;
952 bo->stride = set_tiling.stride;
953 return 0;
954 }
955
956 int
957 brw_bo_get_tiling(struct brw_bo *bo, uint32_t *tiling_mode,
958 uint32_t *swizzle_mode)
959 {
960 *tiling_mode = bo->tiling_mode;
961 *swizzle_mode = bo->swizzle_mode;
962 return 0;
963 }
964
965 struct brw_bo *
966 brw_bo_gem_create_from_prime(struct brw_bufmgr *bufmgr, int prime_fd)
967 {
968 int ret;
969 uint32_t handle;
970 struct brw_bo *bo;
971 struct drm_i915_gem_get_tiling get_tiling;
972
973 pthread_mutex_lock(&bufmgr->lock);
974 ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
975 if (ret) {
976 DBG("create_from_prime: failed to obtain handle from fd: %s\n",
977 strerror(errno));
978 pthread_mutex_unlock(&bufmgr->lock);
979 return NULL;
980 }
981
982 /*
983 * See if the kernel has already returned this buffer to us. Just as
984 * for named buffers, we must not create two bo's pointing at the same
985 * kernel object
986 */
987 bo = hash_find_bo(bufmgr->handle_table, handle);
988 if (bo) {
989 brw_bo_reference(bo);
990 goto out;
991 }
992
993 bo = calloc(1, sizeof(*bo));
994 if (!bo)
995 goto out;
996
997 p_atomic_set(&bo->refcount, 1);
998
999 /* Determine size of bo. The fd-to-handle ioctl really should
1000 * return the size, but it doesn't. If we have kernel 3.12 or
1001 * later, we can lseek on the prime fd to get the size. Older
1002 * kernels will just fail, in which case we fall back to the
1003 * provided (estimated or guess size). */
1004 ret = lseek(prime_fd, 0, SEEK_END);
1005 if (ret != -1)
1006 bo->size = ret;
1007
1008 bo->bufmgr = bufmgr;
1009
1010 bo->gem_handle = handle;
1011 _mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1012
1013 bo->name = "prime";
1014 bo->reusable = false;
1015 bo->external = true;
1016
1017 memclear(get_tiling);
1018 get_tiling.handle = bo->gem_handle;
1019 if (drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling))
1020 goto err;
1021
1022 bo->tiling_mode = get_tiling.tiling_mode;
1023 bo->swizzle_mode = get_tiling.swizzle_mode;
1024 /* XXX stride is unknown */
1025
1026 out:
1027 pthread_mutex_unlock(&bufmgr->lock);
1028 return bo;
1029
1030 err:
1031 bo_free(bo);
1032 pthread_mutex_unlock(&bufmgr->lock);
1033 return NULL;
1034 }
1035
1036 int
1037 brw_bo_gem_export_to_prime(struct brw_bo *bo, int *prime_fd)
1038 {
1039 struct brw_bufmgr *bufmgr = bo->bufmgr;
1040
1041 if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1042 DRM_CLOEXEC, prime_fd) != 0)
1043 return -errno;
1044
1045 bo->reusable = false;
1046 bo->external = true;
1047
1048 return 0;
1049 }
1050
1051 int
1052 brw_bo_flink(struct brw_bo *bo, uint32_t *name)
1053 {
1054 struct brw_bufmgr *bufmgr = bo->bufmgr;
1055
1056 if (!bo->global_name) {
1057 struct drm_gem_flink flink;
1058
1059 memclear(flink);
1060 flink.handle = bo->gem_handle;
1061 if (drmIoctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1062 return -errno;
1063
1064 pthread_mutex_lock(&bufmgr->lock);
1065 if (!bo->global_name) {
1066 bo->global_name = flink.name;
1067 bo->reusable = false;
1068 bo->external = true;
1069
1070 _mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
1071 }
1072 pthread_mutex_unlock(&bufmgr->lock);
1073 }
1074
1075 *name = bo->global_name;
1076 return 0;
1077 }
1078
1079 /**
1080 * Enables unlimited caching of buffer objects for reuse.
1081 *
1082 * This is potentially very memory expensive, as the cache at each bucket
1083 * size is only bounded by how many buffers of that size we've managed to have
1084 * in flight at once.
1085 */
1086 void
1087 brw_bufmgr_enable_reuse(struct brw_bufmgr *bufmgr)
1088 {
1089 bufmgr->bo_reuse = true;
1090 }
1091
1092 static void
1093 add_bucket(struct brw_bufmgr *bufmgr, int size)
1094 {
1095 unsigned int i = bufmgr->num_buckets;
1096
1097 assert(i < ARRAY_SIZE(bufmgr->cache_bucket));
1098
1099 list_inithead(&bufmgr->cache_bucket[i].head);
1100 bufmgr->cache_bucket[i].size = size;
1101 bufmgr->num_buckets++;
1102 }
1103
1104 static void
1105 init_cache_buckets(struct brw_bufmgr *bufmgr)
1106 {
1107 uint64_t size, cache_max_size = 64 * 1024 * 1024;
1108
1109 /* OK, so power of two buckets was too wasteful of memory.
1110 * Give 3 other sizes between each power of two, to hopefully
1111 * cover things accurately enough. (The alternative is
1112 * probably to just go for exact matching of sizes, and assume
1113 * that for things like composited window resize the tiled
1114 * width/height alignment and rounding of sizes to pages will
1115 * get us useful cache hit rates anyway)
1116 */
1117 add_bucket(bufmgr, 4096);
1118 add_bucket(bufmgr, 4096 * 2);
1119 add_bucket(bufmgr, 4096 * 3);
1120
1121 /* Initialize the linked lists for BO reuse cache. */
1122 for (size = 4 * 4096; size <= cache_max_size; size *= 2) {
1123 add_bucket(bufmgr, size);
1124
1125 add_bucket(bufmgr, size + size * 1 / 4);
1126 add_bucket(bufmgr, size + size * 2 / 4);
1127 add_bucket(bufmgr, size + size * 3 / 4);
1128 }
1129 }
1130
1131 uint32_t
1132 brw_create_hw_context(struct brw_bufmgr *bufmgr)
1133 {
1134 struct drm_i915_gem_context_create create;
1135 int ret;
1136
1137 memclear(create);
1138 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create);
1139 if (ret != 0) {
1140 DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno));
1141 return 0;
1142 }
1143
1144 return create.ctx_id;
1145 }
1146
1147 void
1148 brw_destroy_hw_context(struct brw_bufmgr *bufmgr, uint32_t ctx_id)
1149 {
1150 struct drm_i915_gem_context_destroy d = {.ctx_id = ctx_id };
1151
1152 if (ctx_id != 0 &&
1153 drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY, &d) != 0) {
1154 fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1155 strerror(errno));
1156 }
1157 }
1158
1159 int
1160 brw_reg_read(struct brw_bufmgr *bufmgr, uint32_t offset, uint64_t *result)
1161 {
1162 struct drm_i915_reg_read reg_read;
1163 int ret;
1164
1165 memclear(reg_read);
1166 reg_read.offset = offset;
1167
1168 ret = drmIoctl(bufmgr->fd, DRM_IOCTL_I915_REG_READ, &reg_read);
1169
1170 *result = reg_read.val;
1171 return ret;
1172 }
1173
1174 /**
1175 * Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1176 * and manage map buffer objections.
1177 *
1178 * \param fd File descriptor of the opened DRM device.
1179 */
1180 struct brw_bufmgr *
1181 brw_bufmgr_init(struct gen_device_info *devinfo, int fd, int batch_size)
1182 {
1183 struct brw_bufmgr *bufmgr;
1184
1185 bufmgr = calloc(1, sizeof(*bufmgr));
1186 if (bufmgr == NULL)
1187 return NULL;
1188
1189 /* Handles to buffer objects belong to the device fd and are not
1190 * reference counted by the kernel. If the same fd is used by
1191 * multiple parties (threads sharing the same screen bufmgr, or
1192 * even worse the same device fd passed to multiple libraries)
1193 * ownership of those handles is shared by those independent parties.
1194 *
1195 * Don't do this! Ensure that each library/bufmgr has its own device
1196 * fd so that its namespace does not clash with another.
1197 */
1198 bufmgr->fd = fd;
1199
1200 if (pthread_mutex_init(&bufmgr->lock, NULL) != 0) {
1201 free(bufmgr);
1202 return NULL;
1203 }
1204
1205 bufmgr->has_llc = devinfo->has_llc;
1206
1207 init_cache_buckets(bufmgr);
1208
1209 bufmgr->name_table =
1210 _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1211 bufmgr->handle_table =
1212 _mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1213
1214 return bufmgr;
1215 }