Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mesa
Path: blob/21.2-virgl/src/gallium/drivers/crocus/crocus_bufmgr.c
4570 views
1
/*
2
* Copyright © 2017 Intel Corporation
3
*
4
* Permission is hereby granted, free of charge, to any person obtaining a
5
* copy of this software and associated documentation files (the "Software"),
6
* to deal in the Software without restriction, including without limitation
7
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
8
* and/or sell copies of the Software, and to permit persons to whom the
9
* Software is furnished to do so, subject to the following conditions:
10
*
11
* The above copyright notice and this permission notice shall be included
12
* in all copies or substantial portions of the Software.
13
*
14
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
* DEALINGS IN THE SOFTWARE.
21
*/
22
23
/**
24
* @file crocus_bufmgr.c
25
*
26
* The crocus buffer manager.
27
*
28
* XXX: write better comments
29
* - BOs
30
* - Explain BO cache
31
* - main interface to GEM in the kernel
32
*/
33
34
#ifdef HAVE_CONFIG_H
35
#include "config.h"
36
#endif
37
38
#include <xf86drm.h>
39
#include <util/u_atomic.h>
40
#include <fcntl.h>
41
#include <stdio.h>
42
#include <stdlib.h>
43
#include <string.h>
44
#include <unistd.h>
45
#include <assert.h>
46
#include <sys/ioctl.h>
47
#include <sys/mman.h>
48
#include <sys/stat.h>
49
#include <sys/types.h>
50
#include <stdbool.h>
51
#include <time.h>
52
53
#include "errno.h"
54
#include "common/intel_clflush.h"
55
#include "dev/intel_debug.h"
56
#include "common/intel_gem.h"
57
#include "dev/intel_device_info.h"
58
#include "main/macros.h"
59
#include "util/debug.h"
60
#include "util/macros.h"
61
#include "util/hash_table.h"
62
#include "util/list.h"
63
#include "util/os_file.h"
64
#include "util/u_dynarray.h"
65
#include "util/vma.h"
66
#include "crocus_bufmgr.h"
67
#include "crocus_context.h"
68
#include "string.h"
69
70
#include "drm-uapi/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
/**
81
* For debugging purposes, this returns a time in seconds.
82
*/
83
static double
84
get_time(void)
85
{
86
struct timespec tp;
87
88
clock_gettime(CLOCK_MONOTONIC, &tp);
89
90
return tp.tv_sec + tp.tv_nsec / 1000000000.0;
91
}
92
93
/* VALGRIND_FREELIKE_BLOCK unfortunately does not actually undo the earlier
94
* VALGRIND_MALLOCLIKE_BLOCK but instead leaves vg convinced the memory is
95
* leaked. All because it does not call VG(cli_free) from its
96
* VG_USERREQ__FREELIKE_BLOCK handler. Instead of treating the memory like
97
* and allocation, we mark it available for use upon mmapping and remove
98
* it upon unmapping.
99
*/
100
#define VG_DEFINED(ptr, size) VG(VALGRIND_MAKE_MEM_DEFINED(ptr, size))
101
#define VG_NOACCESS(ptr, size) VG(VALGRIND_MAKE_MEM_NOACCESS(ptr, size))
102
103
#define PAGE_SIZE 4096
104
105
#define WARN_ONCE(cond, fmt...) do { \
106
if (unlikely(cond)) { \
107
static bool _warned = false; \
108
if (!_warned) { \
109
fprintf(stderr, "WARNING: "); \
110
fprintf(stderr, fmt); \
111
_warned = true; \
112
} \
113
} \
114
} while (0)
115
116
#define FILE_DEBUG_FLAG DEBUG_BUFMGR
117
118
struct bo_cache_bucket {
119
/** List of cached BOs. */
120
struct list_head head;
121
122
/** Size of this bucket, in bytes. */
123
uint64_t size;
124
};
125
126
struct bo_export {
127
/** File descriptor associated with a handle export. */
128
int drm_fd;
129
130
/** GEM handle in drm_fd */
131
uint32_t gem_handle;
132
133
struct list_head link;
134
};
135
136
struct crocus_bufmgr {
137
/**
138
* List into the list of bufmgr.
139
*/
140
struct list_head link;
141
142
uint32_t refcount;
143
144
int fd;
145
146
simple_mtx_t lock;
147
148
/** Array of lists of cached gem objects of power-of-two sizes */
149
struct bo_cache_bucket cache_bucket[14 * 4];
150
int num_buckets;
151
time_t time;
152
153
struct hash_table *name_table;
154
struct hash_table *handle_table;
155
156
/**
157
* List of BOs which we've effectively freed, but are hanging on to
158
* until they're idle before closing and returning the VMA.
159
*/
160
struct list_head zombie_list;
161
162
bool has_llc:1;
163
bool has_mmap_offset:1;
164
bool has_tiling_uapi:1;
165
bool bo_reuse:1;
166
};
167
168
static simple_mtx_t global_bufmgr_list_mutex = _SIMPLE_MTX_INITIALIZER_NP;
169
static struct list_head global_bufmgr_list = {
170
.next = &global_bufmgr_list,
171
.prev = &global_bufmgr_list,
172
};
173
174
static int bo_set_tiling_internal(struct crocus_bo *bo, uint32_t tiling_mode,
175
uint32_t stride);
176
177
static void bo_free(struct crocus_bo *bo);
178
179
static uint32_t
180
key_hash_uint(const void *key)
181
{
182
return _mesa_hash_data(key, 4);
183
}
184
185
static bool
186
key_uint_equal(const void *a, const void *b)
187
{
188
return *((unsigned *) a) == *((unsigned *) b);
189
}
190
191
static struct crocus_bo *
192
find_and_ref_external_bo(struct hash_table *ht, unsigned int key)
193
{
194
struct hash_entry *entry = _mesa_hash_table_search(ht, &key);
195
struct crocus_bo *bo = entry ? entry->data : NULL;
196
197
if (bo) {
198
assert(bo->external);
199
assert(!bo->reusable);
200
201
/* Being non-reusable, the BO cannot be in the cache lists, but it
202
* may be in the zombie list if it had reached zero references, but
203
* we hadn't yet closed it...and then reimported the same BO. If it
204
* is, then remove it since it's now been resurrected.
205
*/
206
if (bo->head.prev || bo->head.next)
207
list_del(&bo->head);
208
209
crocus_bo_reference(bo);
210
}
211
212
return bo;
213
}
214
215
/**
216
* This function finds the correct bucket fit for the input size.
217
* The function works with O(1) complexity when the requested size
218
* was queried instead of iterating the size through all the buckets.
219
*/
220
static struct bo_cache_bucket *
221
bucket_for_size(struct crocus_bufmgr *bufmgr, uint64_t size)
222
{
223
/* Calculating the pages and rounding up to the page size. */
224
const unsigned pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
225
226
/* Row Bucket sizes clz((x-1) | 3) Row Column
227
* in pages stride size
228
* 0: 1 2 3 4 -> 30 30 30 30 4 1
229
* 1: 5 6 7 8 -> 29 29 29 29 4 1
230
* 2: 10 12 14 16 -> 28 28 28 28 8 2
231
* 3: 20 24 28 32 -> 27 27 27 27 16 4
232
*/
233
const unsigned row = 30 - __builtin_clz((pages - 1) | 3);
234
const unsigned row_max_pages = 4 << row;
235
236
/* The '& ~2' is the special case for row 1. In row 1, max pages /
237
* 2 is 2, but the previous row maximum is zero (because there is
238
* no previous row). All row maximum sizes are power of 2, so that
239
* is the only case where that bit will be set.
240
*/
241
const unsigned prev_row_max_pages = (row_max_pages / 2) & ~2;
242
int col_size_log2 = row - 1;
243
col_size_log2 += (col_size_log2 < 0);
244
245
const unsigned col = (pages - prev_row_max_pages +
246
((1 << col_size_log2) - 1)) >> col_size_log2;
247
248
/* Calculating the index based on the row and column. */
249
const unsigned index = (row * 4) + (col - 1);
250
251
return (index < bufmgr->num_buckets) ?
252
&bufmgr->cache_bucket[index] : NULL;
253
}
254
255
256
int
257
crocus_bo_busy(struct crocus_bo *bo)
258
{
259
struct crocus_bufmgr *bufmgr = bo->bufmgr;
260
struct drm_i915_gem_busy busy = { .handle = bo->gem_handle };
261
262
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_BUSY, &busy);
263
if (ret == 0) {
264
bo->idle = !busy.busy;
265
return busy.busy;
266
}
267
return false;
268
}
269
270
int
271
crocus_bo_madvise(struct crocus_bo *bo, int state)
272
{
273
struct drm_i915_gem_madvise madv = {
274
.handle = bo->gem_handle,
275
.madv = state,
276
.retained = 1,
277
};
278
279
intel_ioctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_MADVISE, &madv);
280
281
return madv.retained;
282
}
283
284
static struct crocus_bo *
285
bo_calloc(void)
286
{
287
struct crocus_bo *bo = calloc(1, sizeof(*bo));
288
if (!bo)
289
return NULL;
290
291
list_inithead(&bo->exports);
292
bo->hash = _mesa_hash_pointer(bo);
293
return bo;
294
}
295
296
static struct crocus_bo *
297
alloc_bo_from_cache(struct crocus_bufmgr *bufmgr,
298
struct bo_cache_bucket *bucket,
299
uint32_t alignment,
300
unsigned flags)
301
{
302
if (!bucket)
303
return NULL;
304
305
struct crocus_bo *bo = NULL;
306
307
list_for_each_entry_safe(struct crocus_bo, cur, &bucket->head, head) {
308
/* If the last BO in the cache is busy, there are no idle BOs. Bail,
309
* either falling back to a non-matching memzone, or if that fails,
310
* allocating a fresh buffer.
311
*/
312
if (crocus_bo_busy(cur))
313
return NULL;
314
315
list_del(&cur->head);
316
317
/* Tell the kernel we need this BO. If it still exists, we're done! */
318
if (crocus_bo_madvise(cur, I915_MADV_WILLNEED)) {
319
bo = cur;
320
break;
321
}
322
323
/* This BO was purged, throw it out and keep looking. */
324
bo_free(cur);
325
}
326
327
if (!bo)
328
return NULL;
329
330
/* Zero the contents if necessary. If this fails, fall back to
331
* allocating a fresh BO, which will always be zeroed by the kernel.
332
*/
333
if (flags & BO_ALLOC_ZEROED) {
334
void *map = crocus_bo_map(NULL, bo, MAP_WRITE | MAP_RAW);
335
if (map) {
336
memset(map, 0, bo->size);
337
} else {
338
bo_free(bo);
339
return NULL;
340
}
341
}
342
343
return bo;
344
}
345
346
static struct crocus_bo *
347
alloc_fresh_bo(struct crocus_bufmgr *bufmgr, uint64_t bo_size)
348
{
349
struct crocus_bo *bo = bo_calloc();
350
if (!bo)
351
return NULL;
352
353
struct drm_i915_gem_create create = { .size = bo_size };
354
355
/* All new BOs we get from the kernel are zeroed, so we don't need to
356
* worry about that here.
357
*/
358
if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CREATE, &create) != 0) {
359
free(bo);
360
return NULL;
361
}
362
363
bo->gem_handle = create.handle;
364
bo->bufmgr = bufmgr;
365
bo->size = bo_size;
366
bo->idle = true;
367
bo->tiling_mode = I915_TILING_NONE;
368
bo->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
369
bo->stride = 0;
370
371
/* Calling set_domain() will allocate pages for the BO outside of the
372
* struct mutex lock in the kernel, which is more efficient than waiting
373
* to create them during the first execbuf that uses the BO.
374
*/
375
struct drm_i915_gem_set_domain sd = {
376
.handle = bo->gem_handle,
377
.read_domains = I915_GEM_DOMAIN_CPU,
378
.write_domain = 0,
379
};
380
381
if (intel_ioctl(bo->bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd) != 0) {
382
bo_free(bo);
383
return NULL;
384
}
385
386
return bo;
387
}
388
389
static struct crocus_bo *
390
bo_alloc_internal(struct crocus_bufmgr *bufmgr,
391
const char *name,
392
uint64_t size,
393
uint32_t alignment,
394
unsigned flags,
395
uint32_t tiling_mode,
396
uint32_t stride)
397
{
398
struct crocus_bo *bo;
399
unsigned int page_size = getpagesize();
400
struct bo_cache_bucket *bucket = bucket_for_size(bufmgr, size);
401
402
/* Round the size up to the bucket size, or if we don't have caching
403
* at this size, a multiple of the page size.
404
*/
405
uint64_t bo_size =
406
bucket ? bucket->size : MAX2(ALIGN(size, page_size), page_size);
407
408
simple_mtx_lock(&bufmgr->lock);
409
410
/* Get a buffer out of the cache if available. First, we try to find
411
* one with a matching memory zone so we can avoid reallocating VMA.
412
*/
413
bo = alloc_bo_from_cache(bufmgr, bucket, alignment, flags);
414
415
simple_mtx_unlock(&bufmgr->lock);
416
417
if (!bo) {
418
bo = alloc_fresh_bo(bufmgr, bo_size);
419
if (!bo)
420
return NULL;
421
}
422
423
if (bo_set_tiling_internal(bo, tiling_mode, stride))
424
goto err_free;
425
426
bo->name = name;
427
p_atomic_set(&bo->refcount, 1);
428
bo->reusable = bucket && bufmgr->bo_reuse;
429
bo->cache_coherent = bufmgr->has_llc;
430
bo->index = -1;
431
bo->kflags = 0;
432
433
if ((flags & BO_ALLOC_COHERENT) && !bo->cache_coherent) {
434
struct drm_i915_gem_caching arg = {
435
.handle = bo->gem_handle,
436
.caching = 1,
437
};
438
if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_CACHING, &arg) == 0) {
439
bo->cache_coherent = true;
440
bo->reusable = false;
441
}
442
}
443
444
DBG("bo_create: buf %d (%s) %llub\n", bo->gem_handle,
445
bo->name, (unsigned long long) size);
446
447
return bo;
448
449
err_free:
450
bo_free(bo);
451
return NULL;
452
}
453
454
struct crocus_bo *
455
crocus_bo_alloc(struct crocus_bufmgr *bufmgr,
456
const char *name,
457
uint64_t size)
458
{
459
return bo_alloc_internal(bufmgr, name, size, 1,
460
0, I915_TILING_NONE, 0);
461
}
462
463
struct crocus_bo *
464
crocus_bo_alloc_tiled(struct crocus_bufmgr *bufmgr, const char *name,
465
uint64_t size, uint32_t alignment,
466
uint32_t tiling_mode, uint32_t pitch, unsigned flags)
467
{
468
return bo_alloc_internal(bufmgr, name, size, alignment,
469
flags, tiling_mode, pitch);
470
}
471
472
struct crocus_bo *
473
crocus_bo_create_userptr(struct crocus_bufmgr *bufmgr, const char *name,
474
void *ptr, size_t size)
475
{
476
struct crocus_bo *bo;
477
478
bo = bo_calloc();
479
if (!bo)
480
return NULL;
481
482
struct drm_i915_gem_userptr arg = {
483
.user_ptr = (uintptr_t)ptr,
484
.user_size = size,
485
};
486
if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_USERPTR, &arg))
487
goto err_free;
488
bo->gem_handle = arg.handle;
489
490
/* Check the buffer for validity before we try and use it in a batch */
491
struct drm_i915_gem_set_domain sd = {
492
.handle = bo->gem_handle,
493
.read_domains = I915_GEM_DOMAIN_CPU,
494
};
495
if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &sd))
496
goto err_close;
497
498
bo->name = name;
499
bo->size = size;
500
bo->map_cpu = ptr;
501
502
bo->bufmgr = bufmgr;
503
bo->kflags = 0;
504
505
p_atomic_set(&bo->refcount, 1);
506
bo->userptr = true;
507
bo->cache_coherent = true;
508
bo->index = -1;
509
bo->idle = true;
510
511
return bo;
512
513
err_close:
514
intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &bo->gem_handle);
515
err_free:
516
free(bo);
517
return NULL;
518
}
519
520
/**
521
* Returns a crocus_bo wrapping the given buffer object handle.
522
*
523
* This can be used when one application needs to pass a buffer object
524
* to another.
525
*/
526
struct crocus_bo *
527
crocus_bo_gem_create_from_name(struct crocus_bufmgr *bufmgr,
528
const char *name, unsigned int handle)
529
{
530
struct crocus_bo *bo;
531
532
/* At the moment most applications only have a few named bo.
533
* For instance, in a DRI client only the render buffers passed
534
* between X and the client are named. And since X returns the
535
* alternating names for the front/back buffer a linear search
536
* provides a sufficiently fast match.
537
*/
538
simple_mtx_lock(&bufmgr->lock);
539
bo = find_and_ref_external_bo(bufmgr->name_table, handle);
540
if (bo)
541
goto out;
542
543
struct drm_gem_open open_arg = { .name = handle };
544
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_OPEN, &open_arg);
545
if (ret != 0) {
546
DBG("Couldn't reference %s handle 0x%08x: %s\n",
547
name, handle, strerror(errno));
548
bo = NULL;
549
goto out;
550
}
551
/* Now see if someone has used a prime handle to get this
552
* object from the kernel before by looking through the list
553
* again for a matching gem_handle
554
*/
555
bo = find_and_ref_external_bo(bufmgr->handle_table, open_arg.handle);
556
if (bo)
557
goto out;
558
559
bo = bo_calloc();
560
if (!bo)
561
goto out;
562
563
p_atomic_set(&bo->refcount, 1);
564
565
bo->size = open_arg.size;
566
bo->gtt_offset = 0;
567
bo->bufmgr = bufmgr;
568
bo->gem_handle = open_arg.handle;
569
bo->name = name;
570
bo->global_name = handle;
571
bo->reusable = false;
572
bo->external = true;
573
bo->kflags = 0;
574
575
_mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
576
_mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
577
578
struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
579
ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling);
580
if (ret != 0)
581
goto err_unref;
582
583
bo->tiling_mode = get_tiling.tiling_mode;
584
bo->swizzle_mode = get_tiling.swizzle_mode;
585
/* XXX stride is unknown */
586
DBG("bo_create_from_handle: %d (%s)\n", handle, bo->name);
587
588
out:
589
simple_mtx_unlock(&bufmgr->lock);
590
return bo;
591
592
err_unref:
593
bo_free(bo);
594
simple_mtx_unlock(&bufmgr->lock);
595
return NULL;
596
}
597
598
static void
599
bo_close(struct crocus_bo *bo)
600
{
601
struct crocus_bufmgr *bufmgr = bo->bufmgr;
602
603
if (bo->external) {
604
struct hash_entry *entry;
605
606
if (bo->global_name) {
607
entry = _mesa_hash_table_search(bufmgr->name_table, &bo->global_name);
608
_mesa_hash_table_remove(bufmgr->name_table, entry);
609
}
610
611
entry = _mesa_hash_table_search(bufmgr->handle_table, &bo->gem_handle);
612
_mesa_hash_table_remove(bufmgr->handle_table, entry);
613
}
614
615
/* Close this object */
616
struct drm_gem_close close = { .handle = bo->gem_handle };
617
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_CLOSE, &close);
618
if (ret != 0) {
619
DBG("DRM_IOCTL_GEM_CLOSE %d failed (%s): %s\n",
620
bo->gem_handle, bo->name, strerror(errno));
621
}
622
623
free(bo);
624
}
625
626
static void
627
bo_free(struct crocus_bo *bo)
628
{
629
struct crocus_bufmgr *bufmgr = bo->bufmgr;
630
631
if (bo->map_cpu && !bo->userptr) {
632
VG_NOACCESS(bo->map_cpu, bo->size);
633
munmap(bo->map_cpu, bo->size);
634
}
635
if (bo->map_wc) {
636
VG_NOACCESS(bo->map_wc, bo->size);
637
munmap(bo->map_wc, bo->size);
638
}
639
if (bo->map_gtt) {
640
VG_NOACCESS(bo->map_gtt, bo->size);
641
munmap(bo->map_gtt, bo->size);
642
}
643
644
if (bo->idle) {
645
bo_close(bo);
646
} else {
647
/* Defer closing the GEM BO and returning the VMA for reuse until the
648
* BO is idle. Just move it to the dead list for now.
649
*/
650
list_addtail(&bo->head, &bufmgr->zombie_list);
651
}
652
}
653
654
/** Frees all cached buffers significantly older than @time. */
655
static void
656
cleanup_bo_cache(struct crocus_bufmgr *bufmgr, time_t time)
657
{
658
int i;
659
660
if (bufmgr->time == time)
661
return;
662
663
for (i = 0; i < bufmgr->num_buckets; i++) {
664
struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
665
666
list_for_each_entry_safe(struct crocus_bo, bo, &bucket->head, head) {
667
if (time - bo->free_time <= 1)
668
break;
669
670
list_del(&bo->head);
671
672
bo_free(bo);
673
}
674
}
675
676
list_for_each_entry_safe(struct crocus_bo, bo, &bufmgr->zombie_list, head) {
677
/* Stop once we reach a busy BO - all others past this point were
678
* freed more recently so are likely also busy.
679
*/
680
if (!bo->idle && crocus_bo_busy(bo))
681
break;
682
683
list_del(&bo->head);
684
bo_close(bo);
685
}
686
687
bufmgr->time = time;
688
}
689
690
static void
691
bo_unreference_final(struct crocus_bo *bo, time_t time)
692
{
693
struct crocus_bufmgr *bufmgr = bo->bufmgr;
694
struct bo_cache_bucket *bucket;
695
696
DBG("bo_unreference final: %d (%s)\n", bo->gem_handle, bo->name);
697
698
bucket = NULL;
699
if (bo->reusable)
700
bucket = bucket_for_size(bufmgr, bo->size);
701
/* Put the buffer into our internal cache for reuse if we can. */
702
if (bucket && crocus_bo_madvise(bo, I915_MADV_DONTNEED)) {
703
bo->free_time = time;
704
bo->name = NULL;
705
706
list_addtail(&bo->head, &bucket->head);
707
} else {
708
bo_free(bo);
709
}
710
}
711
712
void
713
__crocus_bo_unreference(struct crocus_bo *bo)
714
{
715
struct crocus_bufmgr *bufmgr = bo->bufmgr;
716
struct timespec time;
717
718
clock_gettime(CLOCK_MONOTONIC, &time);
719
720
simple_mtx_lock(&bufmgr->lock);
721
722
if (p_atomic_dec_zero(&bo->refcount)) {
723
bo_unreference_final(bo, time.tv_sec);
724
cleanup_bo_cache(bufmgr, time.tv_sec);
725
}
726
727
simple_mtx_unlock(&bufmgr->lock);
728
}
729
730
static void
731
bo_wait_with_stall_warning(struct pipe_debug_callback *dbg,
732
struct crocus_bo *bo,
733
const char *action)
734
{
735
bool busy = dbg && !bo->idle;
736
double elapsed = unlikely(busy) ? -get_time() : 0.0;
737
738
crocus_bo_wait_rendering(bo);
739
740
if (unlikely(busy)) {
741
elapsed += get_time();
742
if (elapsed > 1e-5) /* 0.01ms */ {
743
perf_debug(dbg, "%s a busy \"%s\" BO stalled and took %.03f ms.\n",
744
action, bo->name, elapsed * 1000);
745
}
746
}
747
}
748
749
static void
750
print_flags(unsigned flags)
751
{
752
if (flags & MAP_READ)
753
DBG("READ ");
754
if (flags & MAP_WRITE)
755
DBG("WRITE ");
756
if (flags & MAP_ASYNC)
757
DBG("ASYNC ");
758
if (flags & MAP_PERSISTENT)
759
DBG("PERSISTENT ");
760
if (flags & MAP_COHERENT)
761
DBG("COHERENT ");
762
if (flags & MAP_RAW)
763
DBG("RAW ");
764
DBG("\n");
765
}
766
767
static void *
768
crocus_bo_gem_mmap_legacy(struct pipe_debug_callback *dbg,
769
struct crocus_bo *bo, bool wc)
770
{
771
struct crocus_bufmgr *bufmgr = bo->bufmgr;
772
773
struct drm_i915_gem_mmap mmap_arg = {
774
.handle = bo->gem_handle,
775
.size = bo->size,
776
.flags = wc ? I915_MMAP_WC : 0,
777
};
778
779
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg);
780
if (ret != 0) {
781
DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
782
__FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
783
return NULL;
784
}
785
void *map = (void *) (uintptr_t) mmap_arg.addr_ptr;
786
787
return map;
788
}
789
790
static void *
791
crocus_bo_gem_mmap_offset(struct pipe_debug_callback *dbg, struct crocus_bo *bo,
792
bool wc)
793
{
794
struct crocus_bufmgr *bufmgr = bo->bufmgr;
795
796
struct drm_i915_gem_mmap_offset mmap_arg = {
797
.handle = bo->gem_handle,
798
.flags = wc ? I915_MMAP_OFFSET_WC : I915_MMAP_OFFSET_WB,
799
};
800
801
/* Get the fake offset back */
802
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_OFFSET, &mmap_arg);
803
if (ret != 0) {
804
DBG("%s:%d: Error preparing buffer %d (%s): %s .\n",
805
__FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
806
return NULL;
807
}
808
809
/* And map it */
810
void *map = mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED,
811
bufmgr->fd, mmap_arg.offset);
812
if (map == MAP_FAILED) {
813
DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
814
__FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
815
return NULL;
816
}
817
818
return map;
819
}
820
821
static void *
822
crocus_bo_gem_mmap(struct pipe_debug_callback *dbg, struct crocus_bo *bo, bool wc)
823
{
824
struct crocus_bufmgr *bufmgr = bo->bufmgr;
825
826
if (bufmgr->has_mmap_offset)
827
return crocus_bo_gem_mmap_offset(dbg, bo, wc);
828
else
829
return crocus_bo_gem_mmap_legacy(dbg, bo, wc);
830
}
831
832
static void *
833
crocus_bo_map_cpu(struct pipe_debug_callback *dbg,
834
struct crocus_bo *bo, unsigned flags)
835
{
836
/* We disallow CPU maps for writing to non-coherent buffers, as the
837
* CPU map can become invalidated when a batch is flushed out, which
838
* can happen at unpredictable times. You should use WC maps instead.
839
*/
840
assert(bo->cache_coherent || !(flags & MAP_WRITE));
841
842
if (!bo->map_cpu) {
843
DBG("crocus_bo_map_cpu: %d (%s)\n", bo->gem_handle, bo->name);
844
845
void *map = crocus_bo_gem_mmap(dbg, bo, false);
846
if (!map) {
847
return NULL;
848
}
849
850
VG_DEFINED(map, bo->size);
851
852
if (p_atomic_cmpxchg(&bo->map_cpu, NULL, map)) {
853
VG_NOACCESS(map, bo->size);
854
munmap(map, bo->size);
855
}
856
}
857
assert(bo->map_cpu);
858
859
DBG("crocus_bo_map_cpu: %d (%s) -> %p, ", bo->gem_handle, bo->name,
860
bo->map_cpu);
861
print_flags(flags);
862
863
if (!(flags & MAP_ASYNC)) {
864
bo_wait_with_stall_warning(dbg, bo, "CPU mapping");
865
}
866
867
if (!bo->cache_coherent && !bo->bufmgr->has_llc) {
868
/* If we're reusing an existing CPU mapping, the CPU caches may
869
* contain stale data from the last time we read from that mapping.
870
* (With the BO cache, it might even be data from a previous buffer!)
871
* Even if it's a brand new mapping, the kernel may have zeroed the
872
* buffer via CPU writes.
873
*
874
* We need to invalidate those cachelines so that we see the latest
875
* contents, and so long as we only read from the CPU mmap we do not
876
* need to write those cachelines back afterwards.
877
*
878
* On LLC, the emprical evidence suggests that writes from the GPU
879
* that bypass the LLC (i.e. for scanout) do *invalidate* the CPU
880
* cachelines. (Other reads, such as the display engine, bypass the
881
* LLC entirely requiring us to keep dirty pixels for the scanout
882
* out of any cache.)
883
*/
884
intel_invalidate_range(bo->map_cpu, bo->size);
885
}
886
887
return bo->map_cpu;
888
}
889
890
static void *
891
crocus_bo_map_wc(struct pipe_debug_callback *dbg,
892
struct crocus_bo *bo, unsigned flags)
893
{
894
if (!bo->map_wc) {
895
DBG("crocus_bo_map_wc: %d (%s)\n", bo->gem_handle, bo->name);
896
897
void *map = crocus_bo_gem_mmap(dbg, bo, true);
898
if (!map) {
899
return NULL;
900
}
901
902
VG_DEFINED(map, bo->size);
903
904
if (p_atomic_cmpxchg(&bo->map_wc, NULL, map)) {
905
VG_NOACCESS(map, bo->size);
906
munmap(map, bo->size);
907
}
908
}
909
assert(bo->map_wc);
910
911
DBG("crocus_bo_map_wc: %d (%s) -> %p\n", bo->gem_handle, bo->name, bo->map_wc);
912
print_flags(flags);
913
914
if (!(flags & MAP_ASYNC)) {
915
bo_wait_with_stall_warning(dbg, bo, "WC mapping");
916
}
917
918
return bo->map_wc;
919
}
920
921
/**
922
* Perform an uncached mapping via the GTT.
923
*
924
* Write access through the GTT is not quite fully coherent. On low power
925
* systems especially, like modern Atoms, we can observe reads from RAM before
926
* the write via GTT has landed. A write memory barrier that flushes the Write
927
* Combining Buffer (i.e. sfence/mfence) is not sufficient to order the later
928
* read after the write as the GTT write suffers a small delay through the GTT
929
* indirection. The kernel uses an uncached mmio read to ensure the GTT write
930
* is ordered with reads (either by the GPU, WB or WC) and unconditionally
931
* flushes prior to execbuf submission. However, if we are not informing the
932
* kernel about our GTT writes, it will not flush before earlier access, such
933
* as when using the cmdparser. Similarly, we need to be careful if we should
934
* ever issue a CPU read immediately following a GTT write.
935
*
936
* Telling the kernel about write access also has one more important
937
* side-effect. Upon receiving notification about the write, it cancels any
938
* scanout buffering for FBC/PSR and friends. Later FBC/PSR is then flushed by
939
* either SW_FINISH or DIRTYFB. The presumption is that we never write to the
940
* actual scanout via a mmaping, only to a backbuffer and so all the FBC/PSR
941
* tracking is handled on the buffer exchange instead.
942
*/
943
static void *
944
crocus_bo_map_gtt(struct pipe_debug_callback *dbg,
945
struct crocus_bo *bo, unsigned flags)
946
{
947
struct crocus_bufmgr *bufmgr = bo->bufmgr;
948
949
/* If we don't support get/set_tiling, there's no support for GTT mapping
950
* either (it won't do any de-tiling for us).
951
*/
952
assert(bufmgr->has_tiling_uapi);
953
954
/* Get a mapping of the buffer if we haven't before. */
955
if (bo->map_gtt == NULL) {
956
DBG("bo_map_gtt: mmap %d (%s)\n", bo->gem_handle, bo->name);
957
958
struct drm_i915_gem_mmap_gtt mmap_arg = { .handle = bo->gem_handle };
959
960
/* Get the fake offset back... */
961
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg);
962
if (ret != 0) {
963
DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n",
964
__FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
965
return NULL;
966
}
967
968
/* and mmap it. */
969
void *map = mmap(0, bo->size, PROT_READ | PROT_WRITE,
970
MAP_SHARED, bufmgr->fd, mmap_arg.offset);
971
if (map == MAP_FAILED) {
972
DBG("%s:%d: Error mapping buffer %d (%s): %s .\n",
973
__FILE__, __LINE__, bo->gem_handle, bo->name, strerror(errno));
974
return NULL;
975
}
976
977
/* We don't need to use VALGRIND_MALLOCLIKE_BLOCK because Valgrind will
978
* already intercept this mmap call. However, for consistency between
979
* all the mmap paths, we mark the pointer as defined now and mark it
980
* as inaccessible afterwards.
981
*/
982
VG_DEFINED(map, bo->size);
983
984
if (p_atomic_cmpxchg(&bo->map_gtt, NULL, map)) {
985
VG_NOACCESS(map, bo->size);
986
munmap(map, bo->size);
987
}
988
}
989
assert(bo->map_gtt);
990
991
DBG("bo_map_gtt: %d (%s) -> %p, ", bo->gem_handle, bo->name, bo->map_gtt);
992
print_flags(flags);
993
994
if (!(flags & MAP_ASYNC)) {
995
bo_wait_with_stall_warning(dbg, bo, "GTT mapping");
996
}
997
998
return bo->map_gtt;
999
}
1000
1001
static bool
1002
can_map_cpu(struct crocus_bo *bo, unsigned flags)
1003
{
1004
if (bo->cache_coherent)
1005
return true;
1006
1007
/* Even if the buffer itself is not cache-coherent (such as a scanout), on
1008
* an LLC platform reads always are coherent (as they are performed via the
1009
* central system agent). It is just the writes that we need to take special
1010
* care to ensure that land in main memory and not stick in the CPU cache.
1011
*/
1012
if (!(flags & MAP_WRITE) && bo->bufmgr->has_llc)
1013
return true;
1014
1015
/* If PERSISTENT or COHERENT are set, the mmapping needs to remain valid
1016
* across batch flushes where the kernel will change cache domains of the
1017
* bo, invalidating continued access to the CPU mmap on non-LLC device.
1018
*
1019
* Similarly, ASYNC typically means that the buffer will be accessed via
1020
* both the CPU and the GPU simultaneously. Batches may be executed that
1021
* use the BO even while it is mapped. While OpenGL technically disallows
1022
* most drawing while non-persistent mappings are active, we may still use
1023
* the GPU for blits or other operations, causing batches to happen at
1024
* inconvenient times.
1025
*
1026
* If RAW is set, we expect the caller to be able to handle a WC buffer
1027
* more efficiently than the involuntary clflushes.
1028
*/
1029
if (flags & (MAP_PERSISTENT | MAP_COHERENT | MAP_ASYNC | MAP_RAW))
1030
return false;
1031
1032
return !(flags & MAP_WRITE);
1033
}
1034
1035
void *
1036
crocus_bo_map(struct pipe_debug_callback *dbg,
1037
struct crocus_bo *bo, unsigned flags)
1038
{
1039
if (bo->tiling_mode != I915_TILING_NONE && !(flags & MAP_RAW))
1040
return crocus_bo_map_gtt(dbg, bo, flags);
1041
1042
void *map;
1043
1044
if (can_map_cpu(bo, flags))
1045
map = crocus_bo_map_cpu(dbg, bo, flags);
1046
else
1047
map = crocus_bo_map_wc(dbg, bo, flags);
1048
1049
/* Allow the attempt to fail by falling back to the GTT where necessary.
1050
*
1051
* Not every buffer can be mmaped directly using the CPU (or WC), for
1052
* example buffers that wrap stolen memory or are imported from other
1053
* devices. For those, we have little choice but to use a GTT mmapping.
1054
* However, if we use a slow GTT mmapping for reads where we expected fast
1055
* access, that order of magnitude difference in throughput will be clearly
1056
* expressed by angry users.
1057
*
1058
* We skip MAP_RAW because we want to avoid map_gtt's fence detiling.
1059
*/
1060
if (!map && !(flags & MAP_RAW)) {
1061
perf_debug(dbg, "Fallback GTT mapping for %s with access flags %x\n",
1062
bo->name, flags);
1063
map = crocus_bo_map_gtt(dbg, bo, flags);
1064
}
1065
1066
return map;
1067
}
1068
1069
/** Waits for all GPU rendering with the object to have completed. */
1070
void
1071
crocus_bo_wait_rendering(struct crocus_bo *bo)
1072
{
1073
/* We require a kernel recent enough for WAIT_IOCTL support.
1074
* See intel_init_bufmgr()
1075
*/
1076
crocus_bo_wait(bo, -1);
1077
}
1078
1079
/**
1080
* Waits on a BO for the given amount of time.
1081
*
1082
* @bo: buffer object to wait for
1083
* @timeout_ns: amount of time to wait in nanoseconds.
1084
* If value is less than 0, an infinite wait will occur.
1085
*
1086
* Returns 0 if the wait was successful ie. the last batch referencing the
1087
* object has completed within the allotted time. Otherwise some negative return
1088
* value describes the error. Of particular interest is -ETIME when the wait has
1089
* failed to yield the desired result.
1090
*
1091
* Similar to crocus_bo_wait_rendering except a timeout parameter allows
1092
* the operation to give up after a certain amount of time. Another subtle
1093
* difference is the internal locking semantics are different (this variant does
1094
* not hold the lock for the duration of the wait). This makes the wait subject
1095
* to a larger userspace race window.
1096
*
1097
* The implementation shall wait until the object is no longer actively
1098
* referenced within a batch buffer at the time of the call. The wait will
1099
* not guarantee that the buffer is re-issued via another thread, or an flinked
1100
* handle. Userspace must make sure this race does not occur if such precision
1101
* is important.
1102
*
1103
* Note that some kernels have broken the inifite wait for negative values
1104
* promise, upgrade to latest stable kernels if this is the case.
1105
*/
1106
int
1107
crocus_bo_wait(struct crocus_bo *bo, int64_t timeout_ns)
1108
{
1109
struct crocus_bufmgr *bufmgr = bo->bufmgr;
1110
1111
/* If we know it's idle, don't bother with the kernel round trip */
1112
if (bo->idle && !bo->external)
1113
return 0;
1114
1115
struct drm_i915_gem_wait wait = {
1116
.bo_handle = bo->gem_handle,
1117
.timeout_ns = timeout_ns,
1118
};
1119
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_WAIT, &wait);
1120
if (ret != 0)
1121
return -errno;
1122
1123
bo->idle = true;
1124
1125
return ret;
1126
}
1127
1128
static void
1129
crocus_bufmgr_destroy(struct crocus_bufmgr *bufmgr)
1130
{
1131
simple_mtx_destroy(&bufmgr->lock);
1132
1133
/* Free any cached buffer objects we were going to reuse */
1134
for (int i = 0; i < bufmgr->num_buckets; i++) {
1135
struct bo_cache_bucket *bucket = &bufmgr->cache_bucket[i];
1136
1137
list_for_each_entry_safe(struct crocus_bo, bo, &bucket->head, head) {
1138
list_del(&bo->head);
1139
1140
bo_free(bo);
1141
}
1142
}
1143
1144
/* Close any buffer objects on the dead list. */
1145
list_for_each_entry_safe(struct crocus_bo, bo, &bufmgr->zombie_list, head) {
1146
list_del(&bo->head);
1147
bo_close(bo);
1148
}
1149
1150
_mesa_hash_table_destroy(bufmgr->name_table, NULL);
1151
_mesa_hash_table_destroy(bufmgr->handle_table, NULL);
1152
1153
close(bufmgr->fd);
1154
1155
free(bufmgr);
1156
}
1157
1158
static int
1159
bo_set_tiling_internal(struct crocus_bo *bo, uint32_t tiling_mode,
1160
uint32_t stride)
1161
{
1162
struct crocus_bufmgr *bufmgr = bo->bufmgr;
1163
struct drm_i915_gem_set_tiling set_tiling;
1164
int ret;
1165
1166
if (bo->global_name == 0 &&
1167
tiling_mode == bo->tiling_mode && stride == bo->stride)
1168
return 0;
1169
1170
memset(&set_tiling, 0, sizeof(set_tiling));
1171
do {
1172
/* set_tiling is slightly broken and overwrites the
1173
* input on the error path, so we have to open code
1174
* drm_ioctl.
1175
*/
1176
set_tiling.handle = bo->gem_handle;
1177
set_tiling.tiling_mode = tiling_mode;
1178
set_tiling.stride = stride;
1179
1180
ret = ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling);
1181
} while (ret == -1 && (errno == EINTR || errno == EAGAIN));
1182
if (ret == -1)
1183
return -errno;
1184
1185
bo->tiling_mode = set_tiling.tiling_mode;
1186
bo->swizzle_mode = set_tiling.swizzle_mode;
1187
bo->stride = set_tiling.stride;
1188
return 0;
1189
}
1190
1191
int
1192
crocus_bo_get_tiling(struct crocus_bo *bo, uint32_t *tiling_mode,
1193
uint32_t *swizzle_mode)
1194
{
1195
*tiling_mode = bo->tiling_mode;
1196
*swizzle_mode = bo->swizzle_mode;
1197
return 0;
1198
}
1199
1200
struct crocus_bo *
1201
crocus_bo_import_dmabuf(struct crocus_bufmgr *bufmgr, int prime_fd,
1202
uint64_t modifier)
1203
{
1204
uint32_t handle;
1205
struct crocus_bo *bo;
1206
1207
simple_mtx_lock(&bufmgr->lock);
1208
int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1209
if (ret) {
1210
DBG("import_dmabuf: failed to obtain handle from fd: %s\n",
1211
strerror(errno));
1212
simple_mtx_unlock(&bufmgr->lock);
1213
return NULL;
1214
}
1215
1216
/*
1217
* See if the kernel has already returned this buffer to us. Just as
1218
* for named buffers, we must not create two bo's pointing at the same
1219
* kernel object
1220
*/
1221
bo = find_and_ref_external_bo(bufmgr->handle_table, handle);
1222
if (bo)
1223
goto out;
1224
1225
bo = bo_calloc();
1226
if (!bo)
1227
goto out;
1228
1229
p_atomic_set(&bo->refcount, 1);
1230
1231
/* Determine size of bo. The fd-to-handle ioctl really should
1232
* return the size, but it doesn't. If we have kernel 3.12 or
1233
* later, we can lseek on the prime fd to get the size. Older
1234
* kernels will just fail, in which case we fall back to the
1235
* provided (estimated or guess size). */
1236
ret = lseek(prime_fd, 0, SEEK_END);
1237
if (ret != -1)
1238
bo->size = ret;
1239
1240
bo->bufmgr = bufmgr;
1241
bo->name = "prime";
1242
bo->reusable = false;
1243
bo->external = true;
1244
bo->kflags = 0;
1245
bo->gem_handle = handle;
1246
_mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1247
1248
const struct isl_drm_modifier_info *mod_info =
1249
isl_drm_modifier_get_info(modifier);
1250
if (mod_info) {
1251
bo->tiling_mode = isl_tiling_to_i915_tiling(mod_info->tiling);
1252
} else if (bufmgr->has_tiling_uapi) {
1253
struct drm_i915_gem_get_tiling get_tiling = { .handle = bo->gem_handle };
1254
if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling))
1255
goto err;
1256
1257
bo->tiling_mode = get_tiling.tiling_mode;
1258
} else {
1259
bo->tiling_mode = I915_TILING_NONE;
1260
}
1261
1262
out:
1263
simple_mtx_unlock(&bufmgr->lock);
1264
return bo;
1265
1266
err:
1267
bo_free(bo);
1268
simple_mtx_unlock(&bufmgr->lock);
1269
return NULL;
1270
}
1271
1272
struct crocus_bo *
1273
crocus_bo_import_dmabuf_no_mods(struct crocus_bufmgr *bufmgr,
1274
int prime_fd)
1275
{
1276
uint32_t handle;
1277
struct crocus_bo *bo;
1278
1279
simple_mtx_lock(&bufmgr->lock);
1280
int ret = drmPrimeFDToHandle(bufmgr->fd, prime_fd, &handle);
1281
if (ret) {
1282
DBG("import_dmabuf: failed to obtain handle from fd: %s\n",
1283
strerror(errno));
1284
simple_mtx_unlock(&bufmgr->lock);
1285
return NULL;
1286
}
1287
1288
/*
1289
* See if the kernel has already returned this buffer to us. Just as
1290
* for named buffers, we must not create two bo's pointing at the same
1291
* kernel object
1292
*/
1293
bo = find_and_ref_external_bo(bufmgr->handle_table, handle);
1294
if (bo)
1295
goto out;
1296
1297
bo = bo_calloc();
1298
if (!bo)
1299
goto out;
1300
1301
p_atomic_set(&bo->refcount, 1);
1302
1303
/* Determine size of bo. The fd-to-handle ioctl really should
1304
* return the size, but it doesn't. If we have kernel 3.12 or
1305
* later, we can lseek on the prime fd to get the size. Older
1306
* kernels will just fail, in which case we fall back to the
1307
* provided (estimated or guess size). */
1308
ret = lseek(prime_fd, 0, SEEK_END);
1309
if (ret != -1)
1310
bo->size = ret;
1311
1312
bo->bufmgr = bufmgr;
1313
bo->name = "prime";
1314
bo->reusable = false;
1315
bo->external = true;
1316
bo->kflags = 0;
1317
bo->gem_handle = handle;
1318
_mesa_hash_table_insert(bufmgr->handle_table, &bo->gem_handle, bo);
1319
1320
out:
1321
simple_mtx_unlock(&bufmgr->lock);
1322
return bo;
1323
}
1324
1325
static void
1326
crocus_bo_make_external_locked(struct crocus_bo *bo)
1327
{
1328
if (!bo->external) {
1329
_mesa_hash_table_insert(bo->bufmgr->handle_table, &bo->gem_handle, bo);
1330
bo->external = true;
1331
bo->reusable = false;
1332
}
1333
}
1334
1335
static void
1336
crocus_bo_make_external(struct crocus_bo *bo)
1337
{
1338
struct crocus_bufmgr *bufmgr = bo->bufmgr;
1339
1340
if (bo->external) {
1341
assert(!bo->reusable);
1342
return;
1343
}
1344
1345
simple_mtx_lock(&bufmgr->lock);
1346
crocus_bo_make_external_locked(bo);
1347
simple_mtx_unlock(&bufmgr->lock);
1348
}
1349
1350
int
1351
crocus_bo_export_dmabuf(struct crocus_bo *bo, int *prime_fd)
1352
{
1353
struct crocus_bufmgr *bufmgr = bo->bufmgr;
1354
1355
crocus_bo_make_external(bo);
1356
1357
if (drmPrimeHandleToFD(bufmgr->fd, bo->gem_handle,
1358
DRM_CLOEXEC, prime_fd) != 0)
1359
return -errno;
1360
1361
return 0;
1362
}
1363
1364
uint32_t
1365
crocus_bo_export_gem_handle(struct crocus_bo *bo)
1366
{
1367
crocus_bo_make_external(bo);
1368
1369
return bo->gem_handle;
1370
}
1371
1372
int
1373
crocus_bo_flink(struct crocus_bo *bo, uint32_t *name)
1374
{
1375
struct crocus_bufmgr *bufmgr = bo->bufmgr;
1376
1377
if (!bo->global_name) {
1378
struct drm_gem_flink flink = { .handle = bo->gem_handle };
1379
1380
if (intel_ioctl(bufmgr->fd, DRM_IOCTL_GEM_FLINK, &flink))
1381
return -errno;
1382
1383
simple_mtx_lock(&bufmgr->lock);
1384
if (!bo->global_name) {
1385
crocus_bo_make_external_locked(bo);
1386
bo->global_name = flink.name;
1387
_mesa_hash_table_insert(bufmgr->name_table, &bo->global_name, bo);
1388
}
1389
simple_mtx_unlock(&bufmgr->lock);
1390
}
1391
1392
*name = bo->global_name;
1393
return 0;
1394
}
1395
1396
int
1397
crocus_bo_export_gem_handle_for_device(struct crocus_bo *bo, int drm_fd,
1398
uint32_t *out_handle)
1399
{
1400
/* Only add the new GEM handle to the list of export if it belongs to a
1401
* different GEM device. Otherwise we might close the same buffer multiple
1402
* times.
1403
*/
1404
struct crocus_bufmgr *bufmgr = bo->bufmgr;
1405
int ret = os_same_file_description(drm_fd, bufmgr->fd);
1406
WARN_ONCE(ret < 0,
1407
"Kernel has no file descriptor comparison support: %s\n",
1408
strerror(errno));
1409
if (ret == 0) {
1410
*out_handle = crocus_bo_export_gem_handle(bo);
1411
return 0;
1412
}
1413
1414
struct bo_export *export = calloc(1, sizeof(*export));
1415
if (!export)
1416
return -ENOMEM;
1417
1418
export->drm_fd = drm_fd;
1419
1420
int dmabuf_fd = -1;
1421
int err = crocus_bo_export_dmabuf(bo, &dmabuf_fd);
1422
if (err) {
1423
free(export);
1424
return err;
1425
}
1426
1427
simple_mtx_lock(&bufmgr->lock);
1428
err = drmPrimeFDToHandle(drm_fd, dmabuf_fd, &export->gem_handle);
1429
close(dmabuf_fd);
1430
if (err) {
1431
simple_mtx_unlock(&bufmgr->lock);
1432
free(export);
1433
return err;
1434
}
1435
1436
bool found = false;
1437
list_for_each_entry(struct bo_export, iter, &bo->exports, link) {
1438
if (iter->drm_fd != drm_fd)
1439
continue;
1440
/* Here we assume that for a given DRM fd, we'll always get back the
1441
* same GEM handle for a given buffer.
1442
*/
1443
assert(iter->gem_handle == export->gem_handle);
1444
free(export);
1445
export = iter;
1446
found = true;
1447
break;
1448
}
1449
if (!found)
1450
list_addtail(&export->link, &bo->exports);
1451
1452
simple_mtx_unlock(&bufmgr->lock);
1453
1454
*out_handle = export->gem_handle;
1455
1456
return 0;
1457
}
1458
1459
static void
1460
add_bucket(struct crocus_bufmgr *bufmgr, int size)
1461
{
1462
unsigned int i = bufmgr->num_buckets;
1463
1464
assert(i < ARRAY_SIZE(bufmgr->cache_bucket));
1465
1466
list_inithead(&bufmgr->cache_bucket[i].head);
1467
bufmgr->cache_bucket[i].size = size;
1468
bufmgr->num_buckets++;
1469
1470
assert(bucket_for_size(bufmgr, size) == &bufmgr->cache_bucket[i]);
1471
assert(bucket_for_size(bufmgr, size - 2048) == &bufmgr->cache_bucket[i]);
1472
assert(bucket_for_size(bufmgr, size + 1) != &bufmgr->cache_bucket[i]);
1473
}
1474
1475
static void
1476
init_cache_buckets(struct crocus_bufmgr *bufmgr)
1477
{
1478
uint64_t size, cache_max_size = 64 * 1024 * 1024;
1479
1480
/* OK, so power of two buckets was too wasteful of memory.
1481
* Give 3 other sizes between each power of two, to hopefully
1482
* cover things accurately enough. (The alternative is
1483
* probably to just go for exact matching of sizes, and assume
1484
* that for things like composited window resize the tiled
1485
* width/height alignment and rounding of sizes to pages will
1486
* get us useful cache hit rates anyway)
1487
*/
1488
add_bucket(bufmgr, PAGE_SIZE);
1489
add_bucket(bufmgr, PAGE_SIZE * 2);
1490
add_bucket(bufmgr, PAGE_SIZE * 3);
1491
1492
/* Initialize the linked lists for BO reuse cache. */
1493
for (size = 4 * PAGE_SIZE; size <= cache_max_size; size *= 2) {
1494
add_bucket(bufmgr, size);
1495
1496
add_bucket(bufmgr, size + size * 1 / 4);
1497
add_bucket(bufmgr, size + size * 2 / 4);
1498
add_bucket(bufmgr, size + size * 3 / 4);
1499
}
1500
}
1501
1502
uint32_t
1503
crocus_create_hw_context(struct crocus_bufmgr *bufmgr)
1504
{
1505
struct drm_i915_gem_context_create create = { };
1506
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create);
1507
if (ret != 0) {
1508
DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno));
1509
return 0;
1510
}
1511
1512
/* Upon declaring a GPU hang, the kernel will zap the guilty context
1513
* back to the default logical HW state and attempt to continue on to
1514
* our next submitted batchbuffer. However, our render batches assume
1515
* the previous GPU state is preserved, and only emit commands needed
1516
* to incrementally change that state. In particular, we inherit the
1517
* STATE_BASE_ADDRESS and PIPELINE_SELECT settings, which are critical.
1518
* With default base addresses, our next batches will almost certainly
1519
* cause more GPU hangs, leading to repeated hangs until we're banned
1520
* or the machine is dead.
1521
*
1522
* Here we tell the kernel not to attempt to recover our context but
1523
* immediately (on the next batchbuffer submission) report that the
1524
* context is lost, and we will do the recovery ourselves. Ideally,
1525
* we'll have two lost batches instead of a continual stream of hangs.
1526
*/
1527
struct drm_i915_gem_context_param p = {
1528
.ctx_id = create.ctx_id,
1529
.param = I915_CONTEXT_PARAM_RECOVERABLE,
1530
.value = false,
1531
};
1532
drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM, &p);
1533
1534
return create.ctx_id;
1535
}
1536
1537
static int
1538
crocus_hw_context_get_priority(struct crocus_bufmgr *bufmgr, uint32_t ctx_id)
1539
{
1540
struct drm_i915_gem_context_param p = {
1541
.ctx_id = ctx_id,
1542
.param = I915_CONTEXT_PARAM_PRIORITY,
1543
};
1544
drmIoctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM, &p);
1545
return p.value; /* on error, return 0 i.e. default priority */
1546
}
1547
1548
int
1549
crocus_hw_context_set_priority(struct crocus_bufmgr *bufmgr,
1550
uint32_t ctx_id,
1551
int priority)
1552
{
1553
struct drm_i915_gem_context_param p = {
1554
.ctx_id = ctx_id,
1555
.param = I915_CONTEXT_PARAM_PRIORITY,
1556
.value = priority,
1557
};
1558
int err;
1559
1560
err = 0;
1561
if (intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM, &p))
1562
err = -errno;
1563
1564
return err;
1565
}
1566
1567
uint32_t
1568
crocus_clone_hw_context(struct crocus_bufmgr *bufmgr, uint32_t ctx_id)
1569
{
1570
uint32_t new_ctx = crocus_create_hw_context(bufmgr);
1571
1572
if (new_ctx) {
1573
int priority = crocus_hw_context_get_priority(bufmgr, ctx_id);
1574
crocus_hw_context_set_priority(bufmgr, new_ctx, priority);
1575
}
1576
1577
return new_ctx;
1578
}
1579
1580
void
1581
crocus_destroy_hw_context(struct crocus_bufmgr *bufmgr, uint32_t ctx_id)
1582
{
1583
struct drm_i915_gem_context_destroy d = { .ctx_id = ctx_id };
1584
1585
if (ctx_id != 0 &&
1586
intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY, &d) != 0) {
1587
fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n",
1588
strerror(errno));
1589
}
1590
}
1591
1592
int
1593
crocus_reg_read(struct crocus_bufmgr *bufmgr, uint32_t offset, uint64_t *result)
1594
{
1595
struct drm_i915_reg_read reg_read = { .offset = offset };
1596
int ret = intel_ioctl(bufmgr->fd, DRM_IOCTL_I915_REG_READ, &reg_read);
1597
1598
*result = reg_read.val;
1599
return ret;
1600
}
1601
1602
static int
1603
gem_param(int fd, int name)
1604
{
1605
int v = -1; /* No param uses (yet) the sign bit, reserve it for errors */
1606
1607
struct drm_i915_getparam gp = { .param = name, .value = &v };
1608
if (intel_ioctl(fd, DRM_IOCTL_I915_GETPARAM, &gp))
1609
return -1;
1610
1611
return v;
1612
}
1613
1614
/**
1615
* Initializes the GEM buffer manager, which uses the kernel to allocate, map,
1616
* and manage map buffer objections.
1617
*
1618
* \param fd File descriptor of the opened DRM device.
1619
*/
1620
static struct crocus_bufmgr *
1621
crocus_bufmgr_create(struct intel_device_info *devinfo, int fd, bool bo_reuse)
1622
{
1623
struct crocus_bufmgr *bufmgr = calloc(1, sizeof(*bufmgr));
1624
if (bufmgr == NULL)
1625
return NULL;
1626
1627
/* Handles to buffer objects belong to the device fd and are not
1628
* reference counted by the kernel. If the same fd is used by
1629
* multiple parties (threads sharing the same screen bufmgr, or
1630
* even worse the same device fd passed to multiple libraries)
1631
* ownership of those handles is shared by those independent parties.
1632
*
1633
* Don't do this! Ensure that each library/bufmgr has its own device
1634
* fd so that its namespace does not clash with another.
1635
*/
1636
bufmgr->fd = os_dupfd_cloexec(fd);
1637
1638
p_atomic_set(&bufmgr->refcount, 1);
1639
1640
simple_mtx_init(&bufmgr->lock, mtx_plain);
1641
1642
list_inithead(&bufmgr->zombie_list);
1643
1644
bufmgr->has_llc = devinfo->has_llc;
1645
bufmgr->has_tiling_uapi = devinfo->has_tiling_uapi;
1646
bufmgr->bo_reuse = bo_reuse;
1647
bufmgr->has_mmap_offset = gem_param(fd, I915_PARAM_MMAP_GTT_VERSION) >= 4;
1648
1649
init_cache_buckets(bufmgr);
1650
1651
bufmgr->name_table =
1652
_mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1653
bufmgr->handle_table =
1654
_mesa_hash_table_create(NULL, key_hash_uint, key_uint_equal);
1655
1656
return bufmgr;
1657
}
1658
1659
static struct crocus_bufmgr *
1660
crocus_bufmgr_ref(struct crocus_bufmgr *bufmgr)
1661
{
1662
p_atomic_inc(&bufmgr->refcount);
1663
return bufmgr;
1664
}
1665
1666
void
1667
crocus_bufmgr_unref(struct crocus_bufmgr *bufmgr)
1668
{
1669
simple_mtx_lock(&global_bufmgr_list_mutex);
1670
if (p_atomic_dec_zero(&bufmgr->refcount)) {
1671
list_del(&bufmgr->link);
1672
crocus_bufmgr_destroy(bufmgr);
1673
}
1674
simple_mtx_unlock(&global_bufmgr_list_mutex);
1675
}
1676
1677
/**
1678
* Gets an already existing GEM buffer manager or create a new one.
1679
*
1680
* \param fd File descriptor of the opened DRM device.
1681
*/
1682
struct crocus_bufmgr *
1683
crocus_bufmgr_get_for_fd(struct intel_device_info *devinfo, int fd, bool bo_reuse)
1684
{
1685
struct stat st;
1686
1687
if (fstat(fd, &st))
1688
return NULL;
1689
1690
struct crocus_bufmgr *bufmgr = NULL;
1691
1692
simple_mtx_lock(&global_bufmgr_list_mutex);
1693
list_for_each_entry(struct crocus_bufmgr, iter_bufmgr, &global_bufmgr_list, link) {
1694
struct stat iter_st;
1695
if (fstat(iter_bufmgr->fd, &iter_st))
1696
continue;
1697
1698
if (st.st_rdev == iter_st.st_rdev) {
1699
assert(iter_bufmgr->bo_reuse == bo_reuse);
1700
bufmgr = crocus_bufmgr_ref(iter_bufmgr);
1701
goto unlock;
1702
}
1703
}
1704
1705
bufmgr = crocus_bufmgr_create(devinfo, fd, bo_reuse);
1706
if (bufmgr)
1707
list_addtail(&bufmgr->link, &global_bufmgr_list);
1708
1709
unlock:
1710
simple_mtx_unlock(&global_bufmgr_list_mutex);
1711
1712
return bufmgr;
1713
}
1714
1715
int
1716
crocus_bufmgr_get_fd(struct crocus_bufmgr *bufmgr)
1717
{
1718
return bufmgr->fd;
1719
}
1720
1721