Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mesa
Path: blob/21.2-virgl/src/intel/vulkan/anv_allocator.c
4547 views
1
/*
2
* Copyright © 2015 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 (including the next
12
* paragraph) shall be included in all copies or substantial portions of the
13
* Software.
14
*
15
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21
* IN THE SOFTWARE.
22
*/
23
24
#include <stdlib.h>
25
#include <unistd.h>
26
#include <limits.h>
27
#include <assert.h>
28
#include <sys/mman.h>
29
30
#include "anv_private.h"
31
32
#include "common/intel_aux_map.h"
33
#include "util/anon_file.h"
34
35
#ifdef HAVE_VALGRIND
36
#define VG_NOACCESS_READ(__ptr) ({ \
37
VALGRIND_MAKE_MEM_DEFINED((__ptr), sizeof(*(__ptr))); \
38
__typeof(*(__ptr)) __val = *(__ptr); \
39
VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr)));\
40
__val; \
41
})
42
#define VG_NOACCESS_WRITE(__ptr, __val) ({ \
43
VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
44
*(__ptr) = (__val); \
45
VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
46
})
47
#else
48
#define VG_NOACCESS_READ(__ptr) (*(__ptr))
49
#define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
50
#endif
51
52
#ifndef MAP_POPULATE
53
#define MAP_POPULATE 0
54
#endif
55
56
/* Design goals:
57
*
58
* - Lock free (except when resizing underlying bos)
59
*
60
* - Constant time allocation with typically only one atomic
61
*
62
* - Multiple allocation sizes without fragmentation
63
*
64
* - Can grow while keeping addresses and offset of contents stable
65
*
66
* - All allocations within one bo so we can point one of the
67
* STATE_BASE_ADDRESS pointers at it.
68
*
69
* The overall design is a two-level allocator: top level is a fixed size, big
70
* block (8k) allocator, which operates out of a bo. Allocation is done by
71
* either pulling a block from the free list or growing the used range of the
72
* bo. Growing the range may run out of space in the bo which we then need to
73
* grow. Growing the bo is tricky in a multi-threaded, lockless environment:
74
* we need to keep all pointers and contents in the old map valid. GEM bos in
75
* general can't grow, but we use a trick: we create a memfd and use ftruncate
76
* to grow it as necessary. We mmap the new size and then create a gem bo for
77
* it using the new gem userptr ioctl. Without heavy-handed locking around
78
* our allocation fast-path, there isn't really a way to munmap the old mmap,
79
* so we just keep it around until garbage collection time. While the block
80
* allocator is lockless for normal operations, we block other threads trying
81
* to allocate while we're growing the map. It sholdn't happen often, and
82
* growing is fast anyway.
83
*
84
* At the next level we can use various sub-allocators. The state pool is a
85
* pool of smaller, fixed size objects, which operates much like the block
86
* pool. It uses a free list for freeing objects, but when it runs out of
87
* space it just allocates a new block from the block pool. This allocator is
88
* intended for longer lived state objects such as SURFACE_STATE and most
89
* other persistent state objects in the API. We may need to track more info
90
* with these object and a pointer back to the CPU object (eg VkImage). In
91
* those cases we just allocate a slightly bigger object and put the extra
92
* state after the GPU state object.
93
*
94
* The state stream allocator works similar to how the i965 DRI driver streams
95
* all its state. Even with Vulkan, we need to emit transient state (whether
96
* surface state base or dynamic state base), and for that we can just get a
97
* block and fill it up. These cases are local to a command buffer and the
98
* sub-allocator need not be thread safe. The streaming allocator gets a new
99
* block when it runs out of space and chains them together so they can be
100
* easily freed.
101
*/
102
103
/* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
104
* We use it to indicate the free list is empty. */
105
#define EMPTY UINT32_MAX
106
107
/* On FreeBSD PAGE_SIZE is already defined in
108
* /usr/include/machine/param.h that is indirectly
109
* included here.
110
*/
111
#ifndef PAGE_SIZE
112
#define PAGE_SIZE 4096
113
#endif
114
115
struct anv_mmap_cleanup {
116
void *map;
117
size_t size;
118
};
119
120
static inline uint32_t
121
ilog2_round_up(uint32_t value)
122
{
123
assert(value != 0);
124
return 32 - __builtin_clz(value - 1);
125
}
126
127
static inline uint32_t
128
round_to_power_of_two(uint32_t value)
129
{
130
return 1 << ilog2_round_up(value);
131
}
132
133
struct anv_state_table_cleanup {
134
void *map;
135
size_t size;
136
};
137
138
#define ANV_STATE_TABLE_CLEANUP_INIT ((struct anv_state_table_cleanup){0})
139
#define ANV_STATE_ENTRY_SIZE (sizeof(struct anv_free_entry))
140
141
static VkResult
142
anv_state_table_expand_range(struct anv_state_table *table, uint32_t size);
143
144
VkResult
145
anv_state_table_init(struct anv_state_table *table,
146
struct anv_device *device,
147
uint32_t initial_entries)
148
{
149
VkResult result;
150
151
table->device = device;
152
153
/* Just make it 2GB up-front. The Linux kernel won't actually back it
154
* with pages until we either map and fault on one of them or we use
155
* userptr and send a chunk of it off to the GPU.
156
*/
157
table->fd = os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE, "state table");
158
if (table->fd == -1) {
159
result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
160
goto fail_fd;
161
}
162
163
if (!u_vector_init(&table->cleanups,
164
round_to_power_of_two(sizeof(struct anv_state_table_cleanup)),
165
128)) {
166
result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
167
goto fail_fd;
168
}
169
170
table->state.next = 0;
171
table->state.end = 0;
172
table->size = 0;
173
174
uint32_t initial_size = initial_entries * ANV_STATE_ENTRY_SIZE;
175
result = anv_state_table_expand_range(table, initial_size);
176
if (result != VK_SUCCESS)
177
goto fail_cleanups;
178
179
return VK_SUCCESS;
180
181
fail_cleanups:
182
u_vector_finish(&table->cleanups);
183
fail_fd:
184
close(table->fd);
185
186
return result;
187
}
188
189
static VkResult
190
anv_state_table_expand_range(struct anv_state_table *table, uint32_t size)
191
{
192
void *map;
193
struct anv_state_table_cleanup *cleanup;
194
195
/* Assert that we only ever grow the pool */
196
assert(size >= table->state.end);
197
198
/* Make sure that we don't go outside the bounds of the memfd */
199
if (size > BLOCK_POOL_MEMFD_SIZE)
200
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
201
202
cleanup = u_vector_add(&table->cleanups);
203
if (!cleanup)
204
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
205
206
*cleanup = ANV_STATE_TABLE_CLEANUP_INIT;
207
208
/* Just leak the old map until we destroy the pool. We can't munmap it
209
* without races or imposing locking on the block allocate fast path. On
210
* the whole the leaked maps adds up to less than the size of the
211
* current map. MAP_POPULATE seems like the right thing to do, but we
212
* should try to get some numbers.
213
*/
214
map = mmap(NULL, size, PROT_READ | PROT_WRITE,
215
MAP_SHARED | MAP_POPULATE, table->fd, 0);
216
if (map == MAP_FAILED) {
217
return vk_errorf(table->device, &table->device->vk.base,
218
VK_ERROR_OUT_OF_HOST_MEMORY, "mmap failed: %m");
219
}
220
221
cleanup->map = map;
222
cleanup->size = size;
223
224
table->map = map;
225
table->size = size;
226
227
return VK_SUCCESS;
228
}
229
230
static VkResult
231
anv_state_table_grow(struct anv_state_table *table)
232
{
233
VkResult result = VK_SUCCESS;
234
235
uint32_t used = align_u32(table->state.next * ANV_STATE_ENTRY_SIZE,
236
PAGE_SIZE);
237
uint32_t old_size = table->size;
238
239
/* The block pool is always initialized to a nonzero size and this function
240
* is always called after initialization.
241
*/
242
assert(old_size > 0);
243
244
uint32_t required = MAX2(used, old_size);
245
if (used * 2 <= required) {
246
/* If we're in this case then this isn't the firsta allocation and we
247
* already have enough space on both sides to hold double what we
248
* have allocated. There's nothing for us to do.
249
*/
250
goto done;
251
}
252
253
uint32_t size = old_size * 2;
254
while (size < required)
255
size *= 2;
256
257
assert(size > table->size);
258
259
result = anv_state_table_expand_range(table, size);
260
261
done:
262
return result;
263
}
264
265
void
266
anv_state_table_finish(struct anv_state_table *table)
267
{
268
struct anv_state_table_cleanup *cleanup;
269
270
u_vector_foreach(cleanup, &table->cleanups) {
271
if (cleanup->map)
272
munmap(cleanup->map, cleanup->size);
273
}
274
275
u_vector_finish(&table->cleanups);
276
277
close(table->fd);
278
}
279
280
VkResult
281
anv_state_table_add(struct anv_state_table *table, uint32_t *idx,
282
uint32_t count)
283
{
284
struct anv_block_state state, old, new;
285
VkResult result;
286
287
assert(idx);
288
289
while(1) {
290
state.u64 = __sync_fetch_and_add(&table->state.u64, count);
291
if (state.next + count <= state.end) {
292
assert(table->map);
293
struct anv_free_entry *entry = &table->map[state.next];
294
for (int i = 0; i < count; i++) {
295
entry[i].state.idx = state.next + i;
296
}
297
*idx = state.next;
298
return VK_SUCCESS;
299
} else if (state.next <= state.end) {
300
/* We allocated the first block outside the pool so we have to grow
301
* the pool. pool_state->next acts a mutex: threads who try to
302
* allocate now will get block indexes above the current limit and
303
* hit futex_wait below.
304
*/
305
new.next = state.next + count;
306
do {
307
result = anv_state_table_grow(table);
308
if (result != VK_SUCCESS)
309
return result;
310
new.end = table->size / ANV_STATE_ENTRY_SIZE;
311
} while (new.end < new.next);
312
313
old.u64 = __sync_lock_test_and_set(&table->state.u64, new.u64);
314
if (old.next != state.next)
315
futex_wake(&table->state.end, INT_MAX);
316
} else {
317
futex_wait(&table->state.end, state.end, NULL);
318
continue;
319
}
320
}
321
}
322
323
void
324
anv_free_list_push(union anv_free_list *list,
325
struct anv_state_table *table,
326
uint32_t first, uint32_t count)
327
{
328
union anv_free_list current, old, new;
329
uint32_t last = first;
330
331
for (uint32_t i = 1; i < count; i++, last++)
332
table->map[last].next = last + 1;
333
334
old.u64 = list->u64;
335
do {
336
current = old;
337
table->map[last].next = current.offset;
338
new.offset = first;
339
new.count = current.count + 1;
340
old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
341
} while (old.u64 != current.u64);
342
}
343
344
struct anv_state *
345
anv_free_list_pop(union anv_free_list *list,
346
struct anv_state_table *table)
347
{
348
union anv_free_list current, new, old;
349
350
current.u64 = list->u64;
351
while (current.offset != EMPTY) {
352
__sync_synchronize();
353
new.offset = table->map[current.offset].next;
354
new.count = current.count + 1;
355
old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
356
if (old.u64 == current.u64) {
357
struct anv_free_entry *entry = &table->map[current.offset];
358
return &entry->state;
359
}
360
current = old;
361
}
362
363
return NULL;
364
}
365
366
static VkResult
367
anv_block_pool_expand_range(struct anv_block_pool *pool,
368
uint32_t center_bo_offset, uint32_t size);
369
370
VkResult
371
anv_block_pool_init(struct anv_block_pool *pool,
372
struct anv_device *device,
373
const char *name,
374
uint64_t start_address,
375
uint32_t initial_size)
376
{
377
VkResult result;
378
379
pool->name = name;
380
pool->device = device;
381
pool->use_softpin = device->physical->use_softpin;
382
pool->nbos = 0;
383
pool->size = 0;
384
pool->center_bo_offset = 0;
385
pool->start_address = intel_canonical_address(start_address);
386
pool->map = NULL;
387
388
if (pool->use_softpin) {
389
pool->bo = NULL;
390
pool->fd = -1;
391
} else {
392
/* Just make it 2GB up-front. The Linux kernel won't actually back it
393
* with pages until we either map and fault on one of them or we use
394
* userptr and send a chunk of it off to the GPU.
395
*/
396
pool->fd = os_create_anonymous_file(BLOCK_POOL_MEMFD_SIZE, "block pool");
397
if (pool->fd == -1)
398
return vk_error(VK_ERROR_INITIALIZATION_FAILED);
399
400
pool->wrapper_bo = (struct anv_bo) {
401
.refcount = 1,
402
.offset = -1,
403
.is_wrapper = true,
404
};
405
pool->bo = &pool->wrapper_bo;
406
}
407
408
if (!u_vector_init(&pool->mmap_cleanups,
409
round_to_power_of_two(sizeof(struct anv_mmap_cleanup)),
410
128)) {
411
result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
412
goto fail_fd;
413
}
414
415
pool->state.next = 0;
416
pool->state.end = 0;
417
pool->back_state.next = 0;
418
pool->back_state.end = 0;
419
420
result = anv_block_pool_expand_range(pool, 0, initial_size);
421
if (result != VK_SUCCESS)
422
goto fail_mmap_cleanups;
423
424
/* Make the entire pool available in the front of the pool. If back
425
* allocation needs to use this space, the "ends" will be re-arranged.
426
*/
427
pool->state.end = pool->size;
428
429
return VK_SUCCESS;
430
431
fail_mmap_cleanups:
432
u_vector_finish(&pool->mmap_cleanups);
433
fail_fd:
434
if (pool->fd >= 0)
435
close(pool->fd);
436
437
return result;
438
}
439
440
void
441
anv_block_pool_finish(struct anv_block_pool *pool)
442
{
443
anv_block_pool_foreach_bo(bo, pool) {
444
if (bo->map)
445
anv_gem_munmap(pool->device, bo->map, bo->size);
446
anv_gem_close(pool->device, bo->gem_handle);
447
}
448
449
struct anv_mmap_cleanup *cleanup;
450
u_vector_foreach(cleanup, &pool->mmap_cleanups)
451
munmap(cleanup->map, cleanup->size);
452
u_vector_finish(&pool->mmap_cleanups);
453
454
if (pool->fd >= 0)
455
close(pool->fd);
456
}
457
458
static VkResult
459
anv_block_pool_expand_range(struct anv_block_pool *pool,
460
uint32_t center_bo_offset, uint32_t size)
461
{
462
/* Assert that we only ever grow the pool */
463
assert(center_bo_offset >= pool->back_state.end);
464
assert(size - center_bo_offset >= pool->state.end);
465
466
/* Assert that we don't go outside the bounds of the memfd */
467
assert(center_bo_offset <= BLOCK_POOL_MEMFD_CENTER);
468
assert(pool->use_softpin ||
469
size - center_bo_offset <=
470
BLOCK_POOL_MEMFD_SIZE - BLOCK_POOL_MEMFD_CENTER);
471
472
/* For state pool BOs we have to be a bit careful about where we place them
473
* in the GTT. There are two documented workarounds for state base address
474
* placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
475
* which state that those two base addresses do not support 48-bit
476
* addresses and need to be placed in the bottom 32-bit range.
477
* Unfortunately, this is not quite accurate.
478
*
479
* The real problem is that we always set the size of our state pools in
480
* STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
481
* likely significantly smaller. We do this because we do not no at the
482
* time we emit STATE_BASE_ADDRESS whether or not we will need to expand
483
* the pool during command buffer building so we don't actually have a
484
* valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
485
* overflows 48 bits, the GPU appears to treat all accesses to the buffer
486
* as being out of bounds and returns zero. For dynamic state, this
487
* usually just leads to rendering corruptions, but shaders that are all
488
* zero hang the GPU immediately.
489
*
490
* The easiest solution to do is exactly what the bogus workarounds say to
491
* do: restrict these buffers to 32-bit addresses. We could also pin the
492
* BO to some particular location of our choosing, but that's significantly
493
* more work than just not setting a flag. So, we explicitly DO NOT set
494
* the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
495
* hard work for us. When using softpin, we're in control and the fixed
496
* addresses we choose are fine for base addresses.
497
*/
498
enum anv_bo_alloc_flags bo_alloc_flags = ANV_BO_ALLOC_CAPTURE;
499
if (!pool->use_softpin)
500
bo_alloc_flags |= ANV_BO_ALLOC_32BIT_ADDRESS;
501
502
if (pool->use_softpin) {
503
uint32_t new_bo_size = size - pool->size;
504
struct anv_bo *new_bo;
505
assert(center_bo_offset == 0);
506
VkResult result = anv_device_alloc_bo(pool->device,
507
pool->name,
508
new_bo_size,
509
bo_alloc_flags |
510
ANV_BO_ALLOC_FIXED_ADDRESS |
511
ANV_BO_ALLOC_MAPPED |
512
ANV_BO_ALLOC_SNOOPED,
513
pool->start_address + pool->size,
514
&new_bo);
515
if (result != VK_SUCCESS)
516
return result;
517
518
pool->bos[pool->nbos++] = new_bo;
519
520
/* This pointer will always point to the first BO in the list */
521
pool->bo = pool->bos[0];
522
} else {
523
/* Just leak the old map until we destroy the pool. We can't munmap it
524
* without races or imposing locking on the block allocate fast path. On
525
* the whole the leaked maps adds up to less than the size of the
526
* current map. MAP_POPULATE seems like the right thing to do, but we
527
* should try to get some numbers.
528
*/
529
void *map = mmap(NULL, size, PROT_READ | PROT_WRITE,
530
MAP_SHARED | MAP_POPULATE, pool->fd,
531
BLOCK_POOL_MEMFD_CENTER - center_bo_offset);
532
if (map == MAP_FAILED)
533
return vk_errorf(pool->device, &pool->device->vk.base,
534
VK_ERROR_MEMORY_MAP_FAILED, "mmap failed: %m");
535
536
struct anv_bo *new_bo;
537
VkResult result = anv_device_import_bo_from_host_ptr(pool->device,
538
map, size,
539
bo_alloc_flags,
540
0 /* client_address */,
541
&new_bo);
542
if (result != VK_SUCCESS) {
543
munmap(map, size);
544
return result;
545
}
546
547
struct anv_mmap_cleanup *cleanup = u_vector_add(&pool->mmap_cleanups);
548
if (!cleanup) {
549
munmap(map, size);
550
anv_device_release_bo(pool->device, new_bo);
551
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
552
}
553
cleanup->map = map;
554
cleanup->size = size;
555
556
/* Now that we mapped the new memory, we can write the new
557
* center_bo_offset back into pool and update pool->map. */
558
pool->center_bo_offset = center_bo_offset;
559
pool->map = map + center_bo_offset;
560
561
pool->bos[pool->nbos++] = new_bo;
562
pool->wrapper_bo.map = new_bo;
563
}
564
565
assert(pool->nbos < ANV_MAX_BLOCK_POOL_BOS);
566
pool->size = size;
567
568
return VK_SUCCESS;
569
}
570
571
/** Returns current memory map of the block pool.
572
*
573
* The returned pointer points to the map for the memory at the specified
574
* offset. The offset parameter is relative to the "center" of the block pool
575
* rather than the start of the block pool BO map.
576
*/
577
void*
578
anv_block_pool_map(struct anv_block_pool *pool, int32_t offset, uint32_t size)
579
{
580
if (pool->use_softpin) {
581
struct anv_bo *bo = NULL;
582
int32_t bo_offset = 0;
583
anv_block_pool_foreach_bo(iter_bo, pool) {
584
if (offset < bo_offset + iter_bo->size) {
585
bo = iter_bo;
586
break;
587
}
588
bo_offset += iter_bo->size;
589
}
590
assert(bo != NULL);
591
assert(offset >= bo_offset);
592
assert((offset - bo_offset) + size <= bo->size);
593
594
return bo->map + (offset - bo_offset);
595
} else {
596
return pool->map + offset;
597
}
598
}
599
600
/** Grows and re-centers the block pool.
601
*
602
* We grow the block pool in one or both directions in such a way that the
603
* following conditions are met:
604
*
605
* 1) The size of the entire pool is always a power of two.
606
*
607
* 2) The pool only grows on both ends. Neither end can get
608
* shortened.
609
*
610
* 3) At the end of the allocation, we have about twice as much space
611
* allocated for each end as we have used. This way the pool doesn't
612
* grow too far in one direction or the other.
613
*
614
* 4) If the _alloc_back() has never been called, then the back portion of
615
* the pool retains a size of zero. (This makes it easier for users of
616
* the block pool that only want a one-sided pool.)
617
*
618
* 5) We have enough space allocated for at least one more block in
619
* whichever side `state` points to.
620
*
621
* 6) The center of the pool is always aligned to both the block_size of
622
* the pool and a 4K CPU page.
623
*/
624
static uint32_t
625
anv_block_pool_grow(struct anv_block_pool *pool, struct anv_block_state *state,
626
uint32_t contiguous_size)
627
{
628
VkResult result = VK_SUCCESS;
629
630
pthread_mutex_lock(&pool->device->mutex);
631
632
assert(state == &pool->state || state == &pool->back_state);
633
634
/* Gather a little usage information on the pool. Since we may have
635
* threadsd waiting in queue to get some storage while we resize, it's
636
* actually possible that total_used will be larger than old_size. In
637
* particular, block_pool_alloc() increments state->next prior to
638
* calling block_pool_grow, so this ensures that we get enough space for
639
* which ever side tries to grow the pool.
640
*
641
* We align to a page size because it makes it easier to do our
642
* calculations later in such a way that we state page-aigned.
643
*/
644
uint32_t back_used = align_u32(pool->back_state.next, PAGE_SIZE);
645
uint32_t front_used = align_u32(pool->state.next, PAGE_SIZE);
646
uint32_t total_used = front_used + back_used;
647
648
assert(state == &pool->state || back_used > 0);
649
650
uint32_t old_size = pool->size;
651
652
/* The block pool is always initialized to a nonzero size and this function
653
* is always called after initialization.
654
*/
655
assert(old_size > 0);
656
657
const uint32_t old_back = pool->center_bo_offset;
658
const uint32_t old_front = old_size - pool->center_bo_offset;
659
660
/* The back_used and front_used may actually be smaller than the actual
661
* requirement because they are based on the next pointers which are
662
* updated prior to calling this function.
663
*/
664
uint32_t back_required = MAX2(back_used, old_back);
665
uint32_t front_required = MAX2(front_used, old_front);
666
667
if (pool->use_softpin) {
668
/* With softpin, the pool is made up of a bunch of buffers with separate
669
* maps. Make sure we have enough contiguous space that we can get a
670
* properly contiguous map for the next chunk.
671
*/
672
assert(old_back == 0);
673
front_required = MAX2(front_required, old_front + contiguous_size);
674
}
675
676
if (back_used * 2 <= back_required && front_used * 2 <= front_required) {
677
/* If we're in this case then this isn't the firsta allocation and we
678
* already have enough space on both sides to hold double what we
679
* have allocated. There's nothing for us to do.
680
*/
681
goto done;
682
}
683
684
uint32_t size = old_size * 2;
685
while (size < back_required + front_required)
686
size *= 2;
687
688
assert(size > pool->size);
689
690
/* We compute a new center_bo_offset such that, when we double the size
691
* of the pool, we maintain the ratio of how much is used by each side.
692
* This way things should remain more-or-less balanced.
693
*/
694
uint32_t center_bo_offset;
695
if (back_used == 0) {
696
/* If we're in this case then we have never called alloc_back(). In
697
* this case, we want keep the offset at 0 to make things as simple
698
* as possible for users that don't care about back allocations.
699
*/
700
center_bo_offset = 0;
701
} else {
702
/* Try to "center" the allocation based on how much is currently in
703
* use on each side of the center line.
704
*/
705
center_bo_offset = ((uint64_t)size * back_used) / total_used;
706
707
/* Align down to a multiple of the page size */
708
center_bo_offset &= ~(PAGE_SIZE - 1);
709
710
assert(center_bo_offset >= back_used);
711
712
/* Make sure we don't shrink the back end of the pool */
713
if (center_bo_offset < back_required)
714
center_bo_offset = back_required;
715
716
/* Make sure that we don't shrink the front end of the pool */
717
if (size - center_bo_offset < front_required)
718
center_bo_offset = size - front_required;
719
}
720
721
assert(center_bo_offset % PAGE_SIZE == 0);
722
723
result = anv_block_pool_expand_range(pool, center_bo_offset, size);
724
725
done:
726
pthread_mutex_unlock(&pool->device->mutex);
727
728
if (result == VK_SUCCESS) {
729
/* Return the appropriate new size. This function never actually
730
* updates state->next. Instead, we let the caller do that because it
731
* needs to do so in order to maintain its concurrency model.
732
*/
733
if (state == &pool->state) {
734
return pool->size - pool->center_bo_offset;
735
} else {
736
assert(pool->center_bo_offset > 0);
737
return pool->center_bo_offset;
738
}
739
} else {
740
return 0;
741
}
742
}
743
744
static uint32_t
745
anv_block_pool_alloc_new(struct anv_block_pool *pool,
746
struct anv_block_state *pool_state,
747
uint32_t block_size, uint32_t *padding)
748
{
749
struct anv_block_state state, old, new;
750
751
/* Most allocations won't generate any padding */
752
if (padding)
753
*padding = 0;
754
755
while (1) {
756
state.u64 = __sync_fetch_and_add(&pool_state->u64, block_size);
757
if (state.next + block_size <= state.end) {
758
return state.next;
759
} else if (state.next <= state.end) {
760
if (pool->use_softpin && state.next < state.end) {
761
/* We need to grow the block pool, but still have some leftover
762
* space that can't be used by that particular allocation. So we
763
* add that as a "padding", and return it.
764
*/
765
uint32_t leftover = state.end - state.next;
766
767
/* If there is some leftover space in the pool, the caller must
768
* deal with it.
769
*/
770
assert(leftover == 0 || padding);
771
if (padding)
772
*padding = leftover;
773
state.next += leftover;
774
}
775
776
/* We allocated the first block outside the pool so we have to grow
777
* the pool. pool_state->next acts a mutex: threads who try to
778
* allocate now will get block indexes above the current limit and
779
* hit futex_wait below.
780
*/
781
new.next = state.next + block_size;
782
do {
783
new.end = anv_block_pool_grow(pool, pool_state, block_size);
784
} while (new.end < new.next);
785
786
old.u64 = __sync_lock_test_and_set(&pool_state->u64, new.u64);
787
if (old.next != state.next)
788
futex_wake(&pool_state->end, INT_MAX);
789
return state.next;
790
} else {
791
futex_wait(&pool_state->end, state.end, NULL);
792
continue;
793
}
794
}
795
}
796
797
int32_t
798
anv_block_pool_alloc(struct anv_block_pool *pool,
799
uint32_t block_size, uint32_t *padding)
800
{
801
uint32_t offset;
802
803
offset = anv_block_pool_alloc_new(pool, &pool->state, block_size, padding);
804
805
return offset;
806
}
807
808
/* Allocates a block out of the back of the block pool.
809
*
810
* This will allocated a block earlier than the "start" of the block pool.
811
* The offsets returned from this function will be negative but will still
812
* be correct relative to the block pool's map pointer.
813
*
814
* If you ever use anv_block_pool_alloc_back, then you will have to do
815
* gymnastics with the block pool's BO when doing relocations.
816
*/
817
int32_t
818
anv_block_pool_alloc_back(struct anv_block_pool *pool,
819
uint32_t block_size)
820
{
821
int32_t offset = anv_block_pool_alloc_new(pool, &pool->back_state,
822
block_size, NULL);
823
824
/* The offset we get out of anv_block_pool_alloc_new() is actually the
825
* number of bytes downwards from the middle to the end of the block.
826
* We need to turn it into a (negative) offset from the middle to the
827
* start of the block.
828
*/
829
assert(offset >= 0);
830
return -(offset + block_size);
831
}
832
833
VkResult
834
anv_state_pool_init(struct anv_state_pool *pool,
835
struct anv_device *device,
836
const char *name,
837
uint64_t base_address,
838
int32_t start_offset,
839
uint32_t block_size)
840
{
841
/* We don't want to ever see signed overflow */
842
assert(start_offset < INT32_MAX - (int32_t)BLOCK_POOL_MEMFD_SIZE);
843
844
VkResult result = anv_block_pool_init(&pool->block_pool, device, name,
845
base_address + start_offset,
846
block_size * 16);
847
if (result != VK_SUCCESS)
848
return result;
849
850
pool->start_offset = start_offset;
851
852
result = anv_state_table_init(&pool->table, device, 64);
853
if (result != VK_SUCCESS) {
854
anv_block_pool_finish(&pool->block_pool);
855
return result;
856
}
857
858
assert(util_is_power_of_two_or_zero(block_size));
859
pool->block_size = block_size;
860
pool->back_alloc_free_list = ANV_FREE_LIST_EMPTY;
861
for (unsigned i = 0; i < ANV_STATE_BUCKETS; i++) {
862
pool->buckets[i].free_list = ANV_FREE_LIST_EMPTY;
863
pool->buckets[i].block.next = 0;
864
pool->buckets[i].block.end = 0;
865
}
866
VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
867
868
return VK_SUCCESS;
869
}
870
871
void
872
anv_state_pool_finish(struct anv_state_pool *pool)
873
{
874
VG(VALGRIND_DESTROY_MEMPOOL(pool));
875
anv_state_table_finish(&pool->table);
876
anv_block_pool_finish(&pool->block_pool);
877
}
878
879
static uint32_t
880
anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool *pool,
881
struct anv_block_pool *block_pool,
882
uint32_t state_size,
883
uint32_t block_size,
884
uint32_t *padding)
885
{
886
struct anv_block_state block, old, new;
887
uint32_t offset;
888
889
/* We don't always use anv_block_pool_alloc(), which would set *padding to
890
* zero for us. So if we have a pointer to padding, we must zero it out
891
* ourselves here, to make sure we always return some sensible value.
892
*/
893
if (padding)
894
*padding = 0;
895
896
/* If our state is large, we don't need any sub-allocation from a block.
897
* Instead, we just grab whole (potentially large) blocks.
898
*/
899
if (state_size >= block_size)
900
return anv_block_pool_alloc(block_pool, state_size, padding);
901
902
restart:
903
block.u64 = __sync_fetch_and_add(&pool->block.u64, state_size);
904
905
if (block.next < block.end) {
906
return block.next;
907
} else if (block.next == block.end) {
908
offset = anv_block_pool_alloc(block_pool, block_size, padding);
909
new.next = offset + state_size;
910
new.end = offset + block_size;
911
old.u64 = __sync_lock_test_and_set(&pool->block.u64, new.u64);
912
if (old.next != block.next)
913
futex_wake(&pool->block.end, INT_MAX);
914
return offset;
915
} else {
916
futex_wait(&pool->block.end, block.end, NULL);
917
goto restart;
918
}
919
}
920
921
static uint32_t
922
anv_state_pool_get_bucket(uint32_t size)
923
{
924
unsigned size_log2 = ilog2_round_up(size);
925
assert(size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
926
if (size_log2 < ANV_MIN_STATE_SIZE_LOG2)
927
size_log2 = ANV_MIN_STATE_SIZE_LOG2;
928
return size_log2 - ANV_MIN_STATE_SIZE_LOG2;
929
}
930
931
static uint32_t
932
anv_state_pool_get_bucket_size(uint32_t bucket)
933
{
934
uint32_t size_log2 = bucket + ANV_MIN_STATE_SIZE_LOG2;
935
return 1 << size_log2;
936
}
937
938
/** Helper to push a chunk into the state table.
939
*
940
* It creates 'count' entries into the state table and update their sizes,
941
* offsets and maps, also pushing them as "free" states.
942
*/
943
static void
944
anv_state_pool_return_blocks(struct anv_state_pool *pool,
945
uint32_t chunk_offset, uint32_t count,
946
uint32_t block_size)
947
{
948
/* Disallow returning 0 chunks */
949
assert(count != 0);
950
951
/* Make sure we always return chunks aligned to the block_size */
952
assert(chunk_offset % block_size == 0);
953
954
uint32_t st_idx;
955
UNUSED VkResult result = anv_state_table_add(&pool->table, &st_idx, count);
956
assert(result == VK_SUCCESS);
957
for (int i = 0; i < count; i++) {
958
/* update states that were added back to the state table */
959
struct anv_state *state_i = anv_state_table_get(&pool->table,
960
st_idx + i);
961
state_i->alloc_size = block_size;
962
state_i->offset = pool->start_offset + chunk_offset + block_size * i;
963
state_i->map = anv_block_pool_map(&pool->block_pool,
964
state_i->offset,
965
state_i->alloc_size);
966
}
967
968
uint32_t block_bucket = anv_state_pool_get_bucket(block_size);
969
anv_free_list_push(&pool->buckets[block_bucket].free_list,
970
&pool->table, st_idx, count);
971
}
972
973
/** Returns a chunk of memory back to the state pool.
974
*
975
* Do a two-level split. If chunk_size is bigger than divisor
976
* (pool->block_size), we return as many divisor sized blocks as we can, from
977
* the end of the chunk.
978
*
979
* The remaining is then split into smaller blocks (starting at small_size if
980
* it is non-zero), with larger blocks always being taken from the end of the
981
* chunk.
982
*/
983
static void
984
anv_state_pool_return_chunk(struct anv_state_pool *pool,
985
uint32_t chunk_offset, uint32_t chunk_size,
986
uint32_t small_size)
987
{
988
uint32_t divisor = pool->block_size;
989
uint32_t nblocks = chunk_size / divisor;
990
uint32_t rest = chunk_size - nblocks * divisor;
991
992
if (nblocks > 0) {
993
/* First return divisor aligned and sized chunks. We start returning
994
* larger blocks from the end fo the chunk, since they should already be
995
* aligned to divisor. Also anv_state_pool_return_blocks() only accepts
996
* aligned chunks.
997
*/
998
uint32_t offset = chunk_offset + rest;
999
anv_state_pool_return_blocks(pool, offset, nblocks, divisor);
1000
}
1001
1002
chunk_size = rest;
1003
divisor /= 2;
1004
1005
if (small_size > 0 && small_size < divisor)
1006
divisor = small_size;
1007
1008
uint32_t min_size = 1 << ANV_MIN_STATE_SIZE_LOG2;
1009
1010
/* Just as before, return larger divisor aligned blocks from the end of the
1011
* chunk first.
1012
*/
1013
while (chunk_size > 0 && divisor >= min_size) {
1014
nblocks = chunk_size / divisor;
1015
rest = chunk_size - nblocks * divisor;
1016
if (nblocks > 0) {
1017
anv_state_pool_return_blocks(pool, chunk_offset + rest,
1018
nblocks, divisor);
1019
chunk_size = rest;
1020
}
1021
divisor /= 2;
1022
}
1023
}
1024
1025
static struct anv_state
1026
anv_state_pool_alloc_no_vg(struct anv_state_pool *pool,
1027
uint32_t size, uint32_t align)
1028
{
1029
uint32_t bucket = anv_state_pool_get_bucket(MAX2(size, align));
1030
1031
struct anv_state *state;
1032
uint32_t alloc_size = anv_state_pool_get_bucket_size(bucket);
1033
int32_t offset;
1034
1035
/* Try free list first. */
1036
state = anv_free_list_pop(&pool->buckets[bucket].free_list,
1037
&pool->table);
1038
if (state) {
1039
assert(state->offset >= pool->start_offset);
1040
goto done;
1041
}
1042
1043
/* Try to grab a chunk from some larger bucket and split it up */
1044
for (unsigned b = bucket + 1; b < ANV_STATE_BUCKETS; b++) {
1045
state = anv_free_list_pop(&pool->buckets[b].free_list, &pool->table);
1046
if (state) {
1047
unsigned chunk_size = anv_state_pool_get_bucket_size(b);
1048
int32_t chunk_offset = state->offset;
1049
1050
/* First lets update the state we got to its new size. offset and map
1051
* remain the same.
1052
*/
1053
state->alloc_size = alloc_size;
1054
1055
/* Now return the unused part of the chunk back to the pool as free
1056
* blocks
1057
*
1058
* There are a couple of options as to what we do with it:
1059
*
1060
* 1) We could fully split the chunk into state.alloc_size sized
1061
* pieces. However, this would mean that allocating a 16B
1062
* state could potentially split a 2MB chunk into 512K smaller
1063
* chunks. This would lead to unnecessary fragmentation.
1064
*
1065
* 2) The classic "buddy allocator" method would have us split the
1066
* chunk in half and return one half. Then we would split the
1067
* remaining half in half and return one half, and repeat as
1068
* needed until we get down to the size we want. However, if
1069
* you are allocating a bunch of the same size state (which is
1070
* the common case), this means that every other allocation has
1071
* to go up a level and every fourth goes up two levels, etc.
1072
* This is not nearly as efficient as it could be if we did a
1073
* little more work up-front.
1074
*
1075
* 3) Split the difference between (1) and (2) by doing a
1076
* two-level split. If it's bigger than some fixed block_size,
1077
* we split it into block_size sized chunks and return all but
1078
* one of them. Then we split what remains into
1079
* state.alloc_size sized chunks and return them.
1080
*
1081
* We choose something close to option (3), which is implemented with
1082
* anv_state_pool_return_chunk(). That is done by returning the
1083
* remaining of the chunk, with alloc_size as a hint of the size that
1084
* we want the smaller chunk split into.
1085
*/
1086
anv_state_pool_return_chunk(pool, chunk_offset + alloc_size,
1087
chunk_size - alloc_size, alloc_size);
1088
goto done;
1089
}
1090
}
1091
1092
uint32_t padding;
1093
offset = anv_fixed_size_state_pool_alloc_new(&pool->buckets[bucket],
1094
&pool->block_pool,
1095
alloc_size,
1096
pool->block_size,
1097
&padding);
1098
/* Everytime we allocate a new state, add it to the state pool */
1099
uint32_t idx;
1100
UNUSED VkResult result = anv_state_table_add(&pool->table, &idx, 1);
1101
assert(result == VK_SUCCESS);
1102
1103
state = anv_state_table_get(&pool->table, idx);
1104
state->offset = pool->start_offset + offset;
1105
state->alloc_size = alloc_size;
1106
state->map = anv_block_pool_map(&pool->block_pool, offset, alloc_size);
1107
1108
if (padding > 0) {
1109
uint32_t return_offset = offset - padding;
1110
anv_state_pool_return_chunk(pool, return_offset, padding, 0);
1111
}
1112
1113
done:
1114
return *state;
1115
}
1116
1117
struct anv_state
1118
anv_state_pool_alloc(struct anv_state_pool *pool, uint32_t size, uint32_t align)
1119
{
1120
if (size == 0)
1121
return ANV_STATE_NULL;
1122
1123
struct anv_state state = anv_state_pool_alloc_no_vg(pool, size, align);
1124
VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, size));
1125
return state;
1126
}
1127
1128
struct anv_state
1129
anv_state_pool_alloc_back(struct anv_state_pool *pool)
1130
{
1131
struct anv_state *state;
1132
uint32_t alloc_size = pool->block_size;
1133
1134
/* This function is only used with pools where start_offset == 0 */
1135
assert(pool->start_offset == 0);
1136
1137
state = anv_free_list_pop(&pool->back_alloc_free_list, &pool->table);
1138
if (state) {
1139
assert(state->offset < pool->start_offset);
1140
goto done;
1141
}
1142
1143
int32_t offset;
1144
offset = anv_block_pool_alloc_back(&pool->block_pool,
1145
pool->block_size);
1146
uint32_t idx;
1147
UNUSED VkResult result = anv_state_table_add(&pool->table, &idx, 1);
1148
assert(result == VK_SUCCESS);
1149
1150
state = anv_state_table_get(&pool->table, idx);
1151
state->offset = pool->start_offset + offset;
1152
state->alloc_size = alloc_size;
1153
state->map = anv_block_pool_map(&pool->block_pool, offset, alloc_size);
1154
1155
done:
1156
VG(VALGRIND_MEMPOOL_ALLOC(pool, state->map, state->alloc_size));
1157
return *state;
1158
}
1159
1160
static void
1161
anv_state_pool_free_no_vg(struct anv_state_pool *pool, struct anv_state state)
1162
{
1163
assert(util_is_power_of_two_or_zero(state.alloc_size));
1164
unsigned bucket = anv_state_pool_get_bucket(state.alloc_size);
1165
1166
if (state.offset < pool->start_offset) {
1167
assert(state.alloc_size == pool->block_size);
1168
anv_free_list_push(&pool->back_alloc_free_list,
1169
&pool->table, state.idx, 1);
1170
} else {
1171
anv_free_list_push(&pool->buckets[bucket].free_list,
1172
&pool->table, state.idx, 1);
1173
}
1174
}
1175
1176
void
1177
anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state)
1178
{
1179
if (state.alloc_size == 0)
1180
return;
1181
1182
VG(VALGRIND_MEMPOOL_FREE(pool, state.map));
1183
anv_state_pool_free_no_vg(pool, state);
1184
}
1185
1186
struct anv_state_stream_block {
1187
struct anv_state block;
1188
1189
/* The next block */
1190
struct anv_state_stream_block *next;
1191
1192
#ifdef HAVE_VALGRIND
1193
/* A pointer to the first user-allocated thing in this block. This is
1194
* what valgrind sees as the start of the block.
1195
*/
1196
void *_vg_ptr;
1197
#endif
1198
};
1199
1200
/* The state stream allocator is a one-shot, single threaded allocator for
1201
* variable sized blocks. We use it for allocating dynamic state.
1202
*/
1203
void
1204
anv_state_stream_init(struct anv_state_stream *stream,
1205
struct anv_state_pool *state_pool,
1206
uint32_t block_size)
1207
{
1208
stream->state_pool = state_pool;
1209
stream->block_size = block_size;
1210
1211
stream->block = ANV_STATE_NULL;
1212
1213
/* Ensure that next + whatever > block_size. This way the first call to
1214
* state_stream_alloc fetches a new block.
1215
*/
1216
stream->next = block_size;
1217
1218
util_dynarray_init(&stream->all_blocks, NULL);
1219
1220
VG(VALGRIND_CREATE_MEMPOOL(stream, 0, false));
1221
}
1222
1223
void
1224
anv_state_stream_finish(struct anv_state_stream *stream)
1225
{
1226
util_dynarray_foreach(&stream->all_blocks, struct anv_state, block) {
1227
VG(VALGRIND_MEMPOOL_FREE(stream, block->map));
1228
VG(VALGRIND_MAKE_MEM_NOACCESS(block->map, block->alloc_size));
1229
anv_state_pool_free_no_vg(stream->state_pool, *block);
1230
}
1231
util_dynarray_fini(&stream->all_blocks);
1232
1233
VG(VALGRIND_DESTROY_MEMPOOL(stream));
1234
}
1235
1236
struct anv_state
1237
anv_state_stream_alloc(struct anv_state_stream *stream,
1238
uint32_t size, uint32_t alignment)
1239
{
1240
if (size == 0)
1241
return ANV_STATE_NULL;
1242
1243
assert(alignment <= PAGE_SIZE);
1244
1245
uint32_t offset = align_u32(stream->next, alignment);
1246
if (offset + size > stream->block.alloc_size) {
1247
uint32_t block_size = stream->block_size;
1248
if (block_size < size)
1249
block_size = round_to_power_of_two(size);
1250
1251
stream->block = anv_state_pool_alloc_no_vg(stream->state_pool,
1252
block_size, PAGE_SIZE);
1253
util_dynarray_append(&stream->all_blocks,
1254
struct anv_state, stream->block);
1255
VG(VALGRIND_MAKE_MEM_NOACCESS(stream->block.map, block_size));
1256
1257
/* Reset back to the start */
1258
stream->next = offset = 0;
1259
assert(offset + size <= stream->block.alloc_size);
1260
}
1261
const bool new_block = stream->next == 0;
1262
1263
struct anv_state state = stream->block;
1264
state.offset += offset;
1265
state.alloc_size = size;
1266
state.map += offset;
1267
1268
stream->next = offset + size;
1269
1270
if (new_block) {
1271
assert(state.map == stream->block.map);
1272
VG(VALGRIND_MEMPOOL_ALLOC(stream, state.map, size));
1273
} else {
1274
/* This only updates the mempool. The newly allocated chunk is still
1275
* marked as NOACCESS. */
1276
VG(VALGRIND_MEMPOOL_CHANGE(stream, stream->block.map, stream->block.map,
1277
stream->next));
1278
/* Mark the newly allocated chunk as undefined */
1279
VG(VALGRIND_MAKE_MEM_UNDEFINED(state.map, state.alloc_size));
1280
}
1281
1282
return state;
1283
}
1284
1285
void
1286
anv_state_reserved_pool_init(struct anv_state_reserved_pool *pool,
1287
struct anv_state_pool *parent,
1288
uint32_t count, uint32_t size, uint32_t alignment)
1289
{
1290
pool->pool = parent;
1291
pool->reserved_blocks = ANV_FREE_LIST_EMPTY;
1292
pool->count = count;
1293
1294
for (unsigned i = 0; i < count; i++) {
1295
struct anv_state state = anv_state_pool_alloc(pool->pool, size, alignment);
1296
anv_free_list_push(&pool->reserved_blocks, &pool->pool->table, state.idx, 1);
1297
}
1298
}
1299
1300
void
1301
anv_state_reserved_pool_finish(struct anv_state_reserved_pool *pool)
1302
{
1303
struct anv_state *state;
1304
1305
while ((state = anv_free_list_pop(&pool->reserved_blocks, &pool->pool->table))) {
1306
anv_state_pool_free(pool->pool, *state);
1307
pool->count--;
1308
}
1309
assert(pool->count == 0);
1310
}
1311
1312
struct anv_state
1313
anv_state_reserved_pool_alloc(struct anv_state_reserved_pool *pool)
1314
{
1315
return *anv_free_list_pop(&pool->reserved_blocks, &pool->pool->table);
1316
}
1317
1318
void
1319
anv_state_reserved_pool_free(struct anv_state_reserved_pool *pool,
1320
struct anv_state state)
1321
{
1322
anv_free_list_push(&pool->reserved_blocks, &pool->pool->table, state.idx, 1);
1323
}
1324
1325
void
1326
anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device,
1327
const char *name)
1328
{
1329
pool->name = name;
1330
pool->device = device;
1331
for (unsigned i = 0; i < ARRAY_SIZE(pool->free_list); i++) {
1332
util_sparse_array_free_list_init(&pool->free_list[i],
1333
&device->bo_cache.bo_map, 0,
1334
offsetof(struct anv_bo, free_index));
1335
}
1336
1337
VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
1338
}
1339
1340
void
1341
anv_bo_pool_finish(struct anv_bo_pool *pool)
1342
{
1343
for (unsigned i = 0; i < ARRAY_SIZE(pool->free_list); i++) {
1344
while (1) {
1345
struct anv_bo *bo =
1346
util_sparse_array_free_list_pop_elem(&pool->free_list[i]);
1347
if (bo == NULL)
1348
break;
1349
1350
/* anv_device_release_bo is going to "free" it */
1351
VG(VALGRIND_MALLOCLIKE_BLOCK(bo->map, bo->size, 0, 1));
1352
anv_device_release_bo(pool->device, bo);
1353
}
1354
}
1355
1356
VG(VALGRIND_DESTROY_MEMPOOL(pool));
1357
}
1358
1359
VkResult
1360
anv_bo_pool_alloc(struct anv_bo_pool *pool, uint32_t size,
1361
struct anv_bo **bo_out)
1362
{
1363
const unsigned size_log2 = size < 4096 ? 12 : ilog2_round_up(size);
1364
const unsigned pow2_size = 1 << size_log2;
1365
const unsigned bucket = size_log2 - 12;
1366
assert(bucket < ARRAY_SIZE(pool->free_list));
1367
1368
struct anv_bo *bo =
1369
util_sparse_array_free_list_pop_elem(&pool->free_list[bucket]);
1370
if (bo != NULL) {
1371
VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
1372
*bo_out = bo;
1373
return VK_SUCCESS;
1374
}
1375
1376
VkResult result = anv_device_alloc_bo(pool->device,
1377
pool->name,
1378
pow2_size,
1379
ANV_BO_ALLOC_MAPPED |
1380
ANV_BO_ALLOC_SNOOPED |
1381
ANV_BO_ALLOC_CAPTURE,
1382
0 /* explicit_address */,
1383
&bo);
1384
if (result != VK_SUCCESS)
1385
return result;
1386
1387
/* We want it to look like it came from this pool */
1388
VG(VALGRIND_FREELIKE_BLOCK(bo->map, 0));
1389
VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
1390
1391
*bo_out = bo;
1392
1393
return VK_SUCCESS;
1394
}
1395
1396
void
1397
anv_bo_pool_free(struct anv_bo_pool *pool, struct anv_bo *bo)
1398
{
1399
VG(VALGRIND_MEMPOOL_FREE(pool, bo->map));
1400
1401
assert(util_is_power_of_two_or_zero(bo->size));
1402
const unsigned size_log2 = ilog2_round_up(bo->size);
1403
const unsigned bucket = size_log2 - 12;
1404
assert(bucket < ARRAY_SIZE(pool->free_list));
1405
1406
assert(util_sparse_array_get(&pool->device->bo_cache.bo_map,
1407
bo->gem_handle) == bo);
1408
util_sparse_array_free_list_push(&pool->free_list[bucket],
1409
&bo->gem_handle, 1);
1410
}
1411
1412
// Scratch pool
1413
1414
void
1415
anv_scratch_pool_init(struct anv_device *device, struct anv_scratch_pool *pool)
1416
{
1417
memset(pool, 0, sizeof(*pool));
1418
}
1419
1420
void
1421
anv_scratch_pool_finish(struct anv_device *device, struct anv_scratch_pool *pool)
1422
{
1423
for (unsigned s = 0; s < ARRAY_SIZE(pool->bos[0]); s++) {
1424
for (unsigned i = 0; i < 16; i++) {
1425
if (pool->bos[i][s] != NULL)
1426
anv_device_release_bo(device, pool->bos[i][s]);
1427
}
1428
}
1429
1430
for (unsigned i = 0; i < 16; i++) {
1431
if (pool->surf_states[i].map != NULL) {
1432
anv_state_pool_free(&device->surface_state_pool,
1433
pool->surf_states[i]);
1434
}
1435
}
1436
}
1437
1438
struct anv_bo *
1439
anv_scratch_pool_alloc(struct anv_device *device, struct anv_scratch_pool *pool,
1440
gl_shader_stage stage, unsigned per_thread_scratch)
1441
{
1442
if (per_thread_scratch == 0)
1443
return NULL;
1444
1445
unsigned scratch_size_log2 = ffs(per_thread_scratch / 2048);
1446
assert(scratch_size_log2 < 16);
1447
1448
assert(stage < ARRAY_SIZE(pool->bos));
1449
1450
const struct intel_device_info *devinfo = &device->info;
1451
1452
/* On GFX version 12.5, scratch access changed to a surface-based model.
1453
* Instead of each shader type having its own layout based on IDs passed
1454
* from the relevant fixed-function unit, all scratch access is based on
1455
* thread IDs like it always has been for compute.
1456
*/
1457
if (devinfo->verx10 >= 125)
1458
stage = MESA_SHADER_COMPUTE;
1459
1460
struct anv_bo *bo = p_atomic_read(&pool->bos[scratch_size_log2][stage]);
1461
1462
if (bo != NULL)
1463
return bo;
1464
1465
unsigned subslices = MAX2(device->physical->subslice_total, 1);
1466
1467
/* The documentation for 3DSTATE_PS "Scratch Space Base Pointer" says:
1468
*
1469
* "Scratch Space per slice is computed based on 4 sub-slices. SW
1470
* must allocate scratch space enough so that each slice has 4
1471
* slices allowed."
1472
*
1473
* According to the other driver team, this applies to compute shaders
1474
* as well. This is not currently documented at all.
1475
*
1476
* This hack is no longer necessary on Gfx11+.
1477
*
1478
* For, Gfx11+, scratch space allocation is based on the number of threads
1479
* in the base configuration.
1480
*/
1481
if (devinfo->verx10 == 125)
1482
subslices = 32;
1483
else if (devinfo->ver == 12)
1484
subslices = (devinfo->is_dg1 || devinfo->gt == 2 ? 6 : 2);
1485
else if (devinfo->ver == 11)
1486
subslices = 8;
1487
else if (devinfo->ver >= 9)
1488
subslices = 4 * devinfo->num_slices;
1489
1490
unsigned scratch_ids_per_subslice;
1491
if (devinfo->ver >= 12) {
1492
/* Same as ICL below, but with 16 EUs. */
1493
scratch_ids_per_subslice = 16 * 8;
1494
} else if (devinfo->ver == 11) {
1495
/* The MEDIA_VFE_STATE docs say:
1496
*
1497
* "Starting with this configuration, the Maximum Number of
1498
* Threads must be set to (#EU * 8) for GPGPU dispatches.
1499
*
1500
* Although there are only 7 threads per EU in the configuration,
1501
* the FFTID is calculated as if there are 8 threads per EU,
1502
* which in turn requires a larger amount of Scratch Space to be
1503
* allocated by the driver."
1504
*/
1505
scratch_ids_per_subslice = 8 * 8;
1506
} else if (devinfo->is_haswell) {
1507
/* WaCSScratchSize:hsw
1508
*
1509
* Haswell's scratch space address calculation appears to be sparse
1510
* rather than tightly packed. The Thread ID has bits indicating
1511
* which subslice, EU within a subslice, and thread within an EU it
1512
* is. There's a maximum of two slices and two subslices, so these
1513
* can be stored with a single bit. Even though there are only 10 EUs
1514
* per subslice, this is stored in 4 bits, so there's an effective
1515
* maximum value of 16 EUs. Similarly, although there are only 7
1516
* threads per EU, this is stored in a 3 bit number, giving an
1517
* effective maximum value of 8 threads per EU.
1518
*
1519
* This means that we need to use 16 * 8 instead of 10 * 7 for the
1520
* number of threads per subslice.
1521
*/
1522
scratch_ids_per_subslice = 16 * 8;
1523
} else if (devinfo->is_cherryview) {
1524
/* Cherryview devices have either 6 or 8 EUs per subslice, and each EU
1525
* has 7 threads. The 6 EU devices appear to calculate thread IDs as if
1526
* it had 8 EUs.
1527
*/
1528
scratch_ids_per_subslice = 8 * 7;
1529
} else {
1530
scratch_ids_per_subslice = devinfo->max_cs_threads;
1531
}
1532
1533
uint32_t max_threads[] = {
1534
[MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
1535
[MESA_SHADER_TESS_CTRL] = devinfo->max_tcs_threads,
1536
[MESA_SHADER_TESS_EVAL] = devinfo->max_tes_threads,
1537
[MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
1538
[MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
1539
[MESA_SHADER_COMPUTE] = scratch_ids_per_subslice * subslices,
1540
};
1541
1542
uint32_t size = per_thread_scratch * max_threads[stage];
1543
1544
/* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
1545
* are still relative to the general state base address. When we emit
1546
* STATE_BASE_ADDRESS, we set general state base address to 0 and the size
1547
* to the maximum (1 page under 4GB). This allows us to just place the
1548
* scratch buffers anywhere we wish in the bottom 32 bits of address space
1549
* and just set the scratch base pointer in 3DSTATE_*S using a relocation.
1550
* However, in order to do so, we need to ensure that the kernel does not
1551
* place the scratch BO above the 32-bit boundary.
1552
*
1553
* NOTE: Technically, it can't go "anywhere" because the top page is off
1554
* limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
1555
* kernel allocates space using
1556
*
1557
* end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
1558
*
1559
* so nothing will ever touch the top page.
1560
*/
1561
VkResult result = anv_device_alloc_bo(device, "scratch", size,
1562
ANV_BO_ALLOC_32BIT_ADDRESS |
1563
ANV_BO_ALLOC_LOCAL_MEM,
1564
0 /* explicit_address */,
1565
&bo);
1566
if (result != VK_SUCCESS)
1567
return NULL; /* TODO */
1568
1569
struct anv_bo *current_bo =
1570
p_atomic_cmpxchg(&pool->bos[scratch_size_log2][stage], NULL, bo);
1571
if (current_bo) {
1572
anv_device_release_bo(device, bo);
1573
return current_bo;
1574
} else {
1575
return bo;
1576
}
1577
}
1578
1579
uint32_t
1580
anv_scratch_pool_get_surf(struct anv_device *device,
1581
struct anv_scratch_pool *pool,
1582
unsigned per_thread_scratch)
1583
{
1584
if (per_thread_scratch == 0)
1585
return 0;
1586
1587
unsigned scratch_size_log2 = ffs(per_thread_scratch / 2048);
1588
assert(scratch_size_log2 < 16);
1589
1590
uint32_t surf = p_atomic_read(&pool->surfs[scratch_size_log2]);
1591
if (surf > 0)
1592
return surf;
1593
1594
struct anv_bo *bo =
1595
anv_scratch_pool_alloc(device, pool, MESA_SHADER_COMPUTE,
1596
per_thread_scratch);
1597
struct anv_address addr = { .bo = bo };
1598
1599
struct anv_state state =
1600
anv_state_pool_alloc(&device->surface_state_pool,
1601
device->isl_dev.ss.size, 64);
1602
1603
isl_buffer_fill_state(&device->isl_dev, state.map,
1604
.address = anv_address_physical(addr),
1605
.size_B = bo->size,
1606
.mocs = anv_mocs(device, bo, 0),
1607
.format = ISL_FORMAT_RAW,
1608
.swizzle = ISL_SWIZZLE_IDENTITY,
1609
.stride_B = per_thread_scratch,
1610
.is_scratch = true);
1611
1612
uint32_t current = p_atomic_cmpxchg(&pool->surfs[scratch_size_log2],
1613
0, state.offset);
1614
if (current) {
1615
anv_state_pool_free(&device->surface_state_pool, state);
1616
return current;
1617
} else {
1618
pool->surf_states[scratch_size_log2] = state;
1619
return state.offset;
1620
}
1621
}
1622
1623
VkResult
1624
anv_bo_cache_init(struct anv_bo_cache *cache)
1625
{
1626
util_sparse_array_init(&cache->bo_map, sizeof(struct anv_bo), 1024);
1627
1628
if (pthread_mutex_init(&cache->mutex, NULL)) {
1629
util_sparse_array_finish(&cache->bo_map);
1630
return vk_errorf(NULL, NULL, VK_ERROR_OUT_OF_HOST_MEMORY,
1631
"pthread_mutex_init failed: %m");
1632
}
1633
1634
return VK_SUCCESS;
1635
}
1636
1637
void
1638
anv_bo_cache_finish(struct anv_bo_cache *cache)
1639
{
1640
util_sparse_array_finish(&cache->bo_map);
1641
pthread_mutex_destroy(&cache->mutex);
1642
}
1643
1644
#define ANV_BO_CACHE_SUPPORTED_FLAGS \
1645
(EXEC_OBJECT_WRITE | \
1646
EXEC_OBJECT_ASYNC | \
1647
EXEC_OBJECT_SUPPORTS_48B_ADDRESS | \
1648
EXEC_OBJECT_PINNED | \
1649
EXEC_OBJECT_CAPTURE)
1650
1651
static uint32_t
1652
anv_bo_alloc_flags_to_bo_flags(struct anv_device *device,
1653
enum anv_bo_alloc_flags alloc_flags)
1654
{
1655
struct anv_physical_device *pdevice = device->physical;
1656
1657
uint64_t bo_flags = 0;
1658
if (!(alloc_flags & ANV_BO_ALLOC_32BIT_ADDRESS) &&
1659
pdevice->supports_48bit_addresses)
1660
bo_flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1661
1662
if ((alloc_flags & ANV_BO_ALLOC_CAPTURE) && pdevice->has_exec_capture)
1663
bo_flags |= EXEC_OBJECT_CAPTURE;
1664
1665
if (alloc_flags & ANV_BO_ALLOC_IMPLICIT_WRITE) {
1666
assert(alloc_flags & ANV_BO_ALLOC_IMPLICIT_SYNC);
1667
bo_flags |= EXEC_OBJECT_WRITE;
1668
}
1669
1670
if (!(alloc_flags & ANV_BO_ALLOC_IMPLICIT_SYNC) && pdevice->has_exec_async)
1671
bo_flags |= EXEC_OBJECT_ASYNC;
1672
1673
if (pdevice->use_softpin)
1674
bo_flags |= EXEC_OBJECT_PINNED;
1675
1676
return bo_flags;
1677
}
1678
1679
static uint32_t
1680
anv_device_get_bo_align(struct anv_device *device,
1681
enum anv_bo_alloc_flags alloc_flags)
1682
{
1683
/* Gfx12 CCS surface addresses need to be 64K aligned. */
1684
if (device->info.ver >= 12 && (alloc_flags & ANV_BO_ALLOC_IMPLICIT_CCS))
1685
return 64 * 1024;
1686
1687
return 4096;
1688
}
1689
1690
VkResult
1691
anv_device_alloc_bo(struct anv_device *device,
1692
const char *name,
1693
uint64_t size,
1694
enum anv_bo_alloc_flags alloc_flags,
1695
uint64_t explicit_address,
1696
struct anv_bo **bo_out)
1697
{
1698
if (!device->physical->has_implicit_ccs)
1699
assert(!(alloc_flags & ANV_BO_ALLOC_IMPLICIT_CCS));
1700
1701
const uint32_t bo_flags =
1702
anv_bo_alloc_flags_to_bo_flags(device, alloc_flags);
1703
assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1704
1705
/* The kernel is going to give us whole pages anyway */
1706
size = align_u64(size, 4096);
1707
1708
const uint32_t align = anv_device_get_bo_align(device, alloc_flags);
1709
1710
uint64_t ccs_size = 0;
1711
if (device->info.has_aux_map && (alloc_flags & ANV_BO_ALLOC_IMPLICIT_CCS)) {
1712
/* Align the size up to the next multiple of 64K so we don't have any
1713
* AUX-TT entries pointing from a 64K page to itself.
1714
*/
1715
size = align_u64(size, 64 * 1024);
1716
1717
/* See anv_bo::_ccs_size */
1718
ccs_size = align_u64(DIV_ROUND_UP(size, INTEL_AUX_MAP_GFX12_CCS_SCALE), 4096);
1719
}
1720
1721
uint32_t gem_handle;
1722
1723
/* If we have vram size, we have multiple memory regions and should choose
1724
* one of them.
1725
*/
1726
if (device->physical->vram.size > 0) {
1727
struct drm_i915_gem_memory_class_instance regions[2];
1728
uint32_t nregions = 0;
1729
1730
if (alloc_flags & ANV_BO_ALLOC_LOCAL_MEM) {
1731
/* For vram allocation, still use system memory as a fallback. */
1732
regions[nregions++] = device->physical->vram.region;
1733
regions[nregions++] = device->physical->sys.region;
1734
} else {
1735
regions[nregions++] = device->physical->sys.region;
1736
}
1737
1738
gem_handle = anv_gem_create_regions(device, size + ccs_size,
1739
nregions, regions);
1740
} else {
1741
gem_handle = anv_gem_create(device, size + ccs_size);
1742
}
1743
1744
if (gem_handle == 0)
1745
return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1746
1747
struct anv_bo new_bo = {
1748
.name = name,
1749
.gem_handle = gem_handle,
1750
.refcount = 1,
1751
.offset = -1,
1752
.size = size,
1753
._ccs_size = ccs_size,
1754
.flags = bo_flags,
1755
.is_external = (alloc_flags & ANV_BO_ALLOC_EXTERNAL),
1756
.has_client_visible_address =
1757
(alloc_flags & ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS) != 0,
1758
.has_implicit_ccs = ccs_size > 0,
1759
};
1760
1761
if (alloc_flags & ANV_BO_ALLOC_MAPPED) {
1762
new_bo.map = anv_gem_mmap(device, new_bo.gem_handle, 0, size, 0);
1763
if (new_bo.map == MAP_FAILED) {
1764
anv_gem_close(device, new_bo.gem_handle);
1765
return vk_errorf(device, &device->vk.base,
1766
VK_ERROR_OUT_OF_HOST_MEMORY,
1767
"mmap failed: %m");
1768
}
1769
}
1770
1771
if (alloc_flags & ANV_BO_ALLOC_SNOOPED) {
1772
assert(alloc_flags & ANV_BO_ALLOC_MAPPED);
1773
/* We don't want to change these defaults if it's going to be shared
1774
* with another process.
1775
*/
1776
assert(!(alloc_flags & ANV_BO_ALLOC_EXTERNAL));
1777
1778
/* Regular objects are created I915_CACHING_CACHED on LLC platforms and
1779
* I915_CACHING_NONE on non-LLC platforms. For many internal state
1780
* objects, we'd rather take the snooping overhead than risk forgetting
1781
* a CLFLUSH somewhere. Userptr objects are always created as
1782
* I915_CACHING_CACHED, which on non-LLC means snooped so there's no
1783
* need to do this there.
1784
*/
1785
if (!device->info.has_llc) {
1786
anv_gem_set_caching(device, new_bo.gem_handle,
1787
I915_CACHING_CACHED);
1788
}
1789
}
1790
1791
if (alloc_flags & ANV_BO_ALLOC_FIXED_ADDRESS) {
1792
new_bo.has_fixed_address = true;
1793
new_bo.offset = explicit_address;
1794
} else if (new_bo.flags & EXEC_OBJECT_PINNED) {
1795
new_bo.offset = anv_vma_alloc(device, new_bo.size + new_bo._ccs_size,
1796
align, alloc_flags, explicit_address);
1797
if (new_bo.offset == 0) {
1798
if (new_bo.map)
1799
anv_gem_munmap(device, new_bo.map, size);
1800
anv_gem_close(device, new_bo.gem_handle);
1801
return vk_errorf(device, NULL, VK_ERROR_OUT_OF_DEVICE_MEMORY,
1802
"failed to allocate virtual address for BO");
1803
}
1804
} else {
1805
assert(!new_bo.has_client_visible_address);
1806
}
1807
1808
if (new_bo._ccs_size > 0) {
1809
assert(device->info.has_aux_map);
1810
intel_aux_map_add_mapping(device->aux_map_ctx,
1811
intel_canonical_address(new_bo.offset),
1812
intel_canonical_address(new_bo.offset + new_bo.size),
1813
new_bo.size, 0 /* format_bits */);
1814
}
1815
1816
assert(new_bo.gem_handle);
1817
1818
/* If we just got this gem_handle from anv_bo_init_new then we know no one
1819
* else is touching this BO at the moment so we don't need to lock here.
1820
*/
1821
struct anv_bo *bo = anv_device_lookup_bo(device, new_bo.gem_handle);
1822
*bo = new_bo;
1823
1824
*bo_out = bo;
1825
1826
return VK_SUCCESS;
1827
}
1828
1829
VkResult
1830
anv_device_import_bo_from_host_ptr(struct anv_device *device,
1831
void *host_ptr, uint32_t size,
1832
enum anv_bo_alloc_flags alloc_flags,
1833
uint64_t client_address,
1834
struct anv_bo **bo_out)
1835
{
1836
assert(!(alloc_flags & (ANV_BO_ALLOC_MAPPED |
1837
ANV_BO_ALLOC_SNOOPED |
1838
ANV_BO_ALLOC_FIXED_ADDRESS)));
1839
1840
/* We can't do implicit CCS with an aux table on shared memory */
1841
if (!device->physical->has_implicit_ccs || device->info.has_aux_map)
1842
assert(!(alloc_flags & ANV_BO_ALLOC_IMPLICIT_CCS));
1843
1844
struct anv_bo_cache *cache = &device->bo_cache;
1845
const uint32_t bo_flags =
1846
anv_bo_alloc_flags_to_bo_flags(device, alloc_flags);
1847
assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1848
1849
uint32_t gem_handle = anv_gem_userptr(device, host_ptr, size);
1850
if (!gem_handle)
1851
return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
1852
1853
pthread_mutex_lock(&cache->mutex);
1854
1855
struct anv_bo *bo = anv_device_lookup_bo(device, gem_handle);
1856
if (bo->refcount > 0) {
1857
/* VK_EXT_external_memory_host doesn't require handling importing the
1858
* same pointer twice at the same time, but we don't get in the way. If
1859
* kernel gives us the same gem_handle, only succeed if the flags match.
1860
*/
1861
assert(bo->gem_handle == gem_handle);
1862
if (bo_flags != bo->flags) {
1863
pthread_mutex_unlock(&cache->mutex);
1864
return vk_errorf(device, NULL, VK_ERROR_INVALID_EXTERNAL_HANDLE,
1865
"same host pointer imported two different ways");
1866
}
1867
1868
if (bo->has_client_visible_address !=
1869
((alloc_flags & ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS) != 0)) {
1870
pthread_mutex_unlock(&cache->mutex);
1871
return vk_errorf(device, NULL, VK_ERROR_INVALID_EXTERNAL_HANDLE,
1872
"The same BO was imported with and without buffer "
1873
"device address");
1874
}
1875
1876
if (client_address && client_address != intel_48b_address(bo->offset)) {
1877
pthread_mutex_unlock(&cache->mutex);
1878
return vk_errorf(device, NULL, VK_ERROR_INVALID_EXTERNAL_HANDLE,
1879
"The same BO was imported at two different "
1880
"addresses");
1881
}
1882
1883
__sync_fetch_and_add(&bo->refcount, 1);
1884
} else {
1885
struct anv_bo new_bo = {
1886
.name = "host-ptr",
1887
.gem_handle = gem_handle,
1888
.refcount = 1,
1889
.offset = -1,
1890
.size = size,
1891
.map = host_ptr,
1892
.flags = bo_flags,
1893
.is_external = true,
1894
.from_host_ptr = true,
1895
.has_client_visible_address =
1896
(alloc_flags & ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS) != 0,
1897
};
1898
1899
assert(client_address == intel_48b_address(client_address));
1900
if (new_bo.flags & EXEC_OBJECT_PINNED) {
1901
assert(new_bo._ccs_size == 0);
1902
new_bo.offset = anv_vma_alloc(device, new_bo.size,
1903
anv_device_get_bo_align(device,
1904
alloc_flags),
1905
alloc_flags, client_address);
1906
if (new_bo.offset == 0) {
1907
anv_gem_close(device, new_bo.gem_handle);
1908
pthread_mutex_unlock(&cache->mutex);
1909
return vk_errorf(device, NULL, VK_ERROR_OUT_OF_DEVICE_MEMORY,
1910
"failed to allocate virtual address for BO");
1911
}
1912
} else {
1913
assert(!new_bo.has_client_visible_address);
1914
}
1915
1916
*bo = new_bo;
1917
}
1918
1919
pthread_mutex_unlock(&cache->mutex);
1920
*bo_out = bo;
1921
1922
return VK_SUCCESS;
1923
}
1924
1925
VkResult
1926
anv_device_import_bo(struct anv_device *device,
1927
int fd,
1928
enum anv_bo_alloc_flags alloc_flags,
1929
uint64_t client_address,
1930
struct anv_bo **bo_out)
1931
{
1932
assert(!(alloc_flags & (ANV_BO_ALLOC_MAPPED |
1933
ANV_BO_ALLOC_SNOOPED |
1934
ANV_BO_ALLOC_FIXED_ADDRESS)));
1935
1936
/* We can't do implicit CCS with an aux table on shared memory */
1937
if (!device->physical->has_implicit_ccs || device->info.has_aux_map)
1938
assert(!(alloc_flags & ANV_BO_ALLOC_IMPLICIT_CCS));
1939
1940
struct anv_bo_cache *cache = &device->bo_cache;
1941
const uint32_t bo_flags =
1942
anv_bo_alloc_flags_to_bo_flags(device, alloc_flags);
1943
assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
1944
1945
pthread_mutex_lock(&cache->mutex);
1946
1947
uint32_t gem_handle = anv_gem_fd_to_handle(device, fd);
1948
if (!gem_handle) {
1949
pthread_mutex_unlock(&cache->mutex);
1950
return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
1951
}
1952
1953
struct anv_bo *bo = anv_device_lookup_bo(device, gem_handle);
1954
if (bo->refcount > 0) {
1955
/* We have to be careful how we combine flags so that it makes sense.
1956
* Really, though, if we get to this case and it actually matters, the
1957
* client has imported a BO twice in different ways and they get what
1958
* they have coming.
1959
*/
1960
uint64_t new_flags = 0;
1961
new_flags |= (bo->flags | bo_flags) & EXEC_OBJECT_WRITE;
1962
new_flags |= (bo->flags & bo_flags) & EXEC_OBJECT_ASYNC;
1963
new_flags |= (bo->flags & bo_flags) & EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1964
new_flags |= (bo->flags | bo_flags) & EXEC_OBJECT_PINNED;
1965
new_flags |= (bo->flags | bo_flags) & EXEC_OBJECT_CAPTURE;
1966
1967
/* It's theoretically possible for a BO to get imported such that it's
1968
* both pinned and not pinned. The only way this can happen is if it
1969
* gets imported as both a semaphore and a memory object and that would
1970
* be an application error. Just fail out in that case.
1971
*/
1972
if ((bo->flags & EXEC_OBJECT_PINNED) !=
1973
(bo_flags & EXEC_OBJECT_PINNED)) {
1974
pthread_mutex_unlock(&cache->mutex);
1975
return vk_errorf(device, NULL, VK_ERROR_INVALID_EXTERNAL_HANDLE,
1976
"The same BO was imported two different ways");
1977
}
1978
1979
/* It's also theoretically possible that someone could export a BO from
1980
* one heap and import it into another or to import the same BO into two
1981
* different heaps. If this happens, we could potentially end up both
1982
* allowing and disallowing 48-bit addresses. There's not much we can
1983
* do about it if we're pinning so we just throw an error and hope no
1984
* app is actually that stupid.
1985
*/
1986
if ((new_flags & EXEC_OBJECT_PINNED) &&
1987
(bo->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) !=
1988
(bo_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS)) {
1989
pthread_mutex_unlock(&cache->mutex);
1990
return vk_errorf(device, NULL, VK_ERROR_INVALID_EXTERNAL_HANDLE,
1991
"The same BO was imported on two different heaps");
1992
}
1993
1994
if (bo->has_client_visible_address !=
1995
((alloc_flags & ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS) != 0)) {
1996
pthread_mutex_unlock(&cache->mutex);
1997
return vk_errorf(device, NULL, VK_ERROR_INVALID_EXTERNAL_HANDLE,
1998
"The same BO was imported with and without buffer "
1999
"device address");
2000
}
2001
2002
if (client_address && client_address != intel_48b_address(bo->offset)) {
2003
pthread_mutex_unlock(&cache->mutex);
2004
return vk_errorf(device, NULL, VK_ERROR_INVALID_EXTERNAL_HANDLE,
2005
"The same BO was imported at two different "
2006
"addresses");
2007
}
2008
2009
bo->flags = new_flags;
2010
2011
__sync_fetch_and_add(&bo->refcount, 1);
2012
} else {
2013
off_t size = lseek(fd, 0, SEEK_END);
2014
if (size == (off_t)-1) {
2015
anv_gem_close(device, gem_handle);
2016
pthread_mutex_unlock(&cache->mutex);
2017
return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2018
}
2019
2020
struct anv_bo new_bo = {
2021
.name = "imported",
2022
.gem_handle = gem_handle,
2023
.refcount = 1,
2024
.offset = -1,
2025
.size = size,
2026
.flags = bo_flags,
2027
.is_external = true,
2028
.has_client_visible_address =
2029
(alloc_flags & ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS) != 0,
2030
};
2031
2032
assert(client_address == intel_48b_address(client_address));
2033
if (new_bo.flags & EXEC_OBJECT_PINNED) {
2034
assert(new_bo._ccs_size == 0);
2035
new_bo.offset = anv_vma_alloc(device, new_bo.size,
2036
anv_device_get_bo_align(device,
2037
alloc_flags),
2038
alloc_flags, client_address);
2039
if (new_bo.offset == 0) {
2040
anv_gem_close(device, new_bo.gem_handle);
2041
pthread_mutex_unlock(&cache->mutex);
2042
return vk_errorf(device, NULL, VK_ERROR_OUT_OF_DEVICE_MEMORY,
2043
"failed to allocate virtual address for BO");
2044
}
2045
} else {
2046
assert(!new_bo.has_client_visible_address);
2047
}
2048
2049
*bo = new_bo;
2050
}
2051
2052
pthread_mutex_unlock(&cache->mutex);
2053
*bo_out = bo;
2054
2055
return VK_SUCCESS;
2056
}
2057
2058
VkResult
2059
anv_device_export_bo(struct anv_device *device,
2060
struct anv_bo *bo, int *fd_out)
2061
{
2062
assert(anv_device_lookup_bo(device, bo->gem_handle) == bo);
2063
2064
/* This BO must have been flagged external in order for us to be able
2065
* to export it. This is done based on external options passed into
2066
* anv_AllocateMemory.
2067
*/
2068
assert(bo->is_external);
2069
2070
int fd = anv_gem_handle_to_fd(device, bo->gem_handle);
2071
if (fd < 0)
2072
return vk_error(VK_ERROR_TOO_MANY_OBJECTS);
2073
2074
*fd_out = fd;
2075
2076
return VK_SUCCESS;
2077
}
2078
2079
static bool
2080
atomic_dec_not_one(uint32_t *counter)
2081
{
2082
uint32_t old, val;
2083
2084
val = *counter;
2085
while (1) {
2086
if (val == 1)
2087
return false;
2088
2089
old = __sync_val_compare_and_swap(counter, val, val - 1);
2090
if (old == val)
2091
return true;
2092
2093
val = old;
2094
}
2095
}
2096
2097
void
2098
anv_device_release_bo(struct anv_device *device,
2099
struct anv_bo *bo)
2100
{
2101
struct anv_bo_cache *cache = &device->bo_cache;
2102
assert(anv_device_lookup_bo(device, bo->gem_handle) == bo);
2103
2104
/* Try to decrement the counter but don't go below one. If this succeeds
2105
* then the refcount has been decremented and we are not the last
2106
* reference.
2107
*/
2108
if (atomic_dec_not_one(&bo->refcount))
2109
return;
2110
2111
pthread_mutex_lock(&cache->mutex);
2112
2113
/* We are probably the last reference since our attempt to decrement above
2114
* failed. However, we can't actually know until we are inside the mutex.
2115
* Otherwise, someone could import the BO between the decrement and our
2116
* taking the mutex.
2117
*/
2118
if (unlikely(__sync_sub_and_fetch(&bo->refcount, 1) > 0)) {
2119
/* Turns out we're not the last reference. Unlock and bail. */
2120
pthread_mutex_unlock(&cache->mutex);
2121
return;
2122
}
2123
assert(bo->refcount == 0);
2124
2125
if (bo->map && !bo->from_host_ptr)
2126
anv_gem_munmap(device, bo->map, bo->size);
2127
2128
if (bo->_ccs_size > 0) {
2129
assert(device->physical->has_implicit_ccs);
2130
assert(device->info.has_aux_map);
2131
assert(bo->has_implicit_ccs);
2132
intel_aux_map_unmap_range(device->aux_map_ctx,
2133
intel_canonical_address(bo->offset),
2134
bo->size);
2135
}
2136
2137
if ((bo->flags & EXEC_OBJECT_PINNED) && !bo->has_fixed_address)
2138
anv_vma_free(device, bo->offset, bo->size + bo->_ccs_size);
2139
2140
uint32_t gem_handle = bo->gem_handle;
2141
2142
/* Memset the BO just in case. The refcount being zero should be enough to
2143
* prevent someone from assuming the data is valid but it's safer to just
2144
* stomp to zero just in case. We explicitly do this *before* we close the
2145
* GEM handle to ensure that if anyone allocates something and gets the
2146
* same GEM handle, the memset has already happen and won't stomp all over
2147
* any data they may write in this BO.
2148
*/
2149
memset(bo, 0, sizeof(*bo));
2150
2151
anv_gem_close(device, gem_handle);
2152
2153
/* Don't unlock until we've actually closed the BO. The whole point of
2154
* the BO cache is to ensure that we correctly handle races with creating
2155
* and releasing GEM handles and we don't want to let someone import the BO
2156
* again between mutex unlock and closing the GEM handle.
2157
*/
2158
pthread_mutex_unlock(&cache->mutex);
2159
}
2160
2161