Debian Codegraph @

src/asahi/lib/agx_device.c

raw
1 /*
2 * Copyright 2021 Alyssa Rosenzweig
3 * Copyright 2019 Collabora, Ltd.
4 * Copyright 2020 Igalia S.L.
5 * SPDX-License-Identifier: MIT
6 */
7
8 #include "agx_device.h"
9 #include <inttypes.h>
10 #include "clc/asahi_clc.h"
11 #include "drm-uapi/asahi_drm.h"
12 #include "util/bitscan.h"
13 #include "util/macros.h"
14 #include "util/ralloc.h"
15 #include "util/timespec.h"
16 #include "agx_abi.h"
17 #include "agx_bo.h"
18 #include "agx_compile.h"
19 #include "agx_device_virtio.h"
20 #include "agx_scratch.h"
21 #include "decode.h"
22 #include "glsl_types.h"
23 #include "layout.h"
24 #include "libagx_dgc.h"
25 #include "libagx_shaders.h"
26
27 #include <fcntl.h>
28 #include <xf86drm.h>
29 #include "drm-uapi/dma-buf.h"
30 #include "util/blob.h"
31 #include "util/log.h"
32 #include "util/mesa-blake3.h"
33 #include "util/os_file.h"
34 #include "util/os_mman.h"
35 #include "util/os_time.h"
36 #include "util/simple_mtx.h"
37 #include "util/u_math.h"
38 #include "util/u_printf.h"
39 #include "git_sha1.h"
40 #include "nir_serialize.h"
41 #include "vdrm.h"
42
43 static inline int
44 asahi_simple_ioctl(struct agx_device *dev, unsigned cmd, void *req)
45 {
46 if (dev->is_virtio) {
47 return agx_virtio_simple_ioctl(dev, cmd, req);
48 } else {
49 return drmIoctl(dev->fd, cmd, req);
50 }
51 }
52
53 /* clang-format off */
54 static const struct debug_named_value agx_debug_options[] = {
55 {"trace", AGX_DBG_TRACE, "Trace the command stream"},
56 {"bodump", AGX_DBG_BODUMP, "Periodically dump live BOs"},
57 {"no16", AGX_DBG_NO16, "Disable 16-bit support"},
58 {"perf", AGX_DBG_PERF, "Print performance warnings"},
59 #ifndef NDEBUG
60 {"dirty", AGX_DBG_DIRTY, "Disable dirty tracking"},
61 #endif
62 {"precompile",AGX_DBG_PRECOMPILE,"Precompile shaders for shader-db"},
63 {"nocompress",AGX_DBG_NOCOMPRESS,"Disable lossless compression"},
64 {"nocluster", AGX_DBG_NOCLUSTER,"Disable vertex clustering"},
65 {"sync", AGX_DBG_SYNC, "Synchronously wait for all submissions"},
66 {"stats", AGX_DBG_STATS, "Show command execution statistics"},
67 {"resource", AGX_DBG_RESOURCE, "Log resource operations"},
68 {"batch", AGX_DBG_BATCH, "Log batches"},
69 {"nowc", AGX_DBG_NOWC, "Disable write-combining"},
70 {"synctvb", AGX_DBG_SYNCTVB, "Synchronous TVB growth"},
71 {"smalltile", AGX_DBG_SMALLTILE,"Force 16x16 tiles"},
72 {"feedback", AGX_DBG_FEEDBACK, "Debug feedback loops"},
73 {"nomsaa", AGX_DBG_NOMSAA, "Force disable MSAA"},
74 {"noshadow", AGX_DBG_NOSHADOW, "Force disable resource shadowing"},
75 {"scratch", AGX_DBG_SCRATCH, "Debug scratch memory usage"},
76 {"1queue", AGX_DBG_1QUEUE, "Force usage of a single queue for multiple contexts"},
77 {"nosoft", AGX_DBG_NOSOFT, "Disable soft fault optimizations"},
78 {"nomerge", AGX_DBG_NOMERGE, "Disable control stream merging"},
79 {"bodumpverbose", AGX_DBG_BODUMPVERBOSE, "Include extra info with dumps"},
80 DEBUG_NAMED_VALUE_END
81 };
82 /* clang-format on */
83
84 void
85 agx_bo_free(struct agx_device *dev, struct agx_bo *bo)
86 {
87 const uint64_t handle = bo->handle;
88
89 if (bo->_map)
90 munmap(bo->_map, bo->size);
91
92 /* Free the VA. No need to unmap the BO or unbind the VA, as the kernel will
93 * take care of that when we close it.
94 */
95 agx_va_free(dev, bo->va, false);
96
97 if (bo->prime_fd != -1)
98 close(bo->prime_fd);
99
100 /* Reset the handle. This has to happen before the GEM close to avoid a race.
101 */
102 memset(bo, 0, sizeof(*bo));
103 __sync_synchronize();
104
105 struct drm_gem_close args = {.handle = handle};
106 drmIoctl(dev->fd, DRM_IOCTL_GEM_CLOSE, &args);
107 }
108
109 static int
110 agx_drm_bo_bind(struct agx_device *dev, struct drm_asahi_gem_bind_op *ops,
111 uint32_t count)
112 {
113 struct drm_asahi_vm_bind vm_bind = {
114 .num_binds = count,
115 .vm_id = dev->vm_id,
116 .userptr = (uintptr_t)ops,
117 .stride = sizeof(*ops),
118 };
119
120 int ret = drmIoctl(dev->fd, DRM_IOCTL_ASAHI_VM_BIND, &vm_bind);
121 if (ret) {
122 fprintf(stderr, "DRM_IOCTL_ASAHI_VM_BIND failed\n");
123 }
124
125 return ret;
126 }
127
128 /*
129 * Convenience helper to bind a single BO regardless of kernel module.
130 */
131 int
132 agx_bo_bind(struct agx_device *dev, struct agx_bo *bo, uint64_t addr,
133 size_t size_B, uint64_t offset_B, uint32_t flags)
134 {
135 assert((size_B % 16384) == 0 && "alignment required");
136 assert((offset_B % 16384) == 0 && "alignment required");
137 assert((addr % 16384) == 0 && "alignment required");
138
139 struct drm_asahi_gem_bind_op op = {
140 .flags = flags,
141 .handle = bo ? bo->uapi_handle : 0,
142 .offset = offset_B,
143 .range = size_B,
144 .addr = addr,
145 };
146
147 return dev->ops.bo_bind(dev, &op, 1);
148 }
149
150 int
151 agx_bind_timestamps(struct agx_device *dev, struct agx_bo *bo, uint32_t *handle)
152 {
153 struct drm_asahi_gem_bind_object bind = {
154 .op = DRM_ASAHI_BIND_OBJECT_OP_BIND,
155 .flags = DRM_ASAHI_BIND_OBJECT_USAGE_TIMESTAMPS,
156 .handle = bo->uapi_handle,
157 .range = bo->size,
158 };
159
160 int ret = dev->ops.bo_bind_object(dev, &bind);
161 *handle = bind.object_handle;
162 return ret;
163 }
164
165 static struct agx_bo *
166 agx_bo_alloc(struct agx_device *dev, size_t size, size_t align,
167 enum agx_bo_flags flags)
168 {
169 struct agx_bo *bo;
170 unsigned handle = 0;
171
172 /* executable implies low va */
173 assert(!(flags & AGX_BO_EXEC) || (flags & AGX_BO_LOW_VA));
174
175 struct drm_asahi_gem_create gem_create = {.size = size};
176
177 if (flags & AGX_BO_WRITEBACK)
178 gem_create.flags |= DRM_ASAHI_GEM_WRITEBACK;
179
180 if (!(flags & (AGX_BO_SHARED | AGX_BO_SHAREABLE))) {
181 gem_create.flags |= DRM_ASAHI_GEM_VM_PRIVATE;
182 gem_create.vm_id = dev->vm_id;
183 }
184
185 int ret = drmIoctl(dev->fd, DRM_IOCTL_ASAHI_GEM_CREATE, &gem_create);
186 if (ret) {
187 fprintf(stderr, "DRM_IOCTL_ASAHI_GEM_CREATE failed: %m\n");
188 return NULL;
189 }
190
191 handle = gem_create.handle;
192
193 pthread_mutex_lock(&dev->bo_map_lock);
194 bo = agx_lookup_bo(dev, handle);
195 dev->max_handle = MAX2(dev->max_handle, handle);
196 pthread_mutex_unlock(&dev->bo_map_lock);
197
198 /* Fresh handle */
199 assert(!memcmp(bo, &((struct agx_bo){}), sizeof(*bo)));
200
201 bo->dev = dev;
202 bo->size = gem_create.size;
203 bo->align = align;
204 bo->flags = flags;
205 bo->handle = bo->uapi_handle = handle;
206 bo->prime_fd = -1;
207
208 enum agx_va_flags va_flags = flags & AGX_BO_LOW_VA ? AGX_VA_USC : 0;
209 bo->va = agx_va_alloc(dev, size, bo->align, va_flags, 0);
210 if (!bo->va) {
211 fprintf(stderr, "Failed to allocate BO VMA\n");
212 agx_bo_free(dev, bo);
213 return NULL;
214 }
215
216 uint32_t bind = DRM_ASAHI_BIND_READ;
217 if (!(flags & AGX_BO_READONLY)) {
218 bind |= DRM_ASAHI_BIND_WRITE;
219 }
220
221 ret = agx_bo_bind(dev, bo, bo->va->addr, bo->size, 0, bind);
222 if (ret) {
223 agx_bo_free(dev, bo);
224 return NULL;
225 }
226
227 return bo;
228 }
229
230 static void
231 agx_bo_mmap(struct agx_device *dev, struct agx_bo *bo, void *fixed_addr)
232 {
233 assert(bo->_map == NULL && "not double mapped");
234
235 struct drm_asahi_gem_mmap_offset gem_mmap_offset = {.handle =
236 bo->uapi_handle};
237 int ret, flags;
238
239 ret = drmIoctl(dev->fd, DRM_IOCTL_ASAHI_GEM_MMAP_OFFSET, &gem_mmap_offset);
240 if (ret) {
241 fprintf(stderr, "DRM_IOCTL_ASAHI_MMAP_BO failed: %m\n");
242 assert(0);
243 }
244
245 flags = MAP_SHARED | (fixed_addr ? MAP_FIXED : 0);
246 bo->_map = os_mmap(fixed_addr, bo->size, PROT_READ | PROT_WRITE, flags,
247 dev->fd, gem_mmap_offset.offset);
248 if (bo->_map == MAP_FAILED) {
249 bo->_map = NULL;
250 fprintf(stderr,
251 "mmap failed: result=%p size=0x%llx fd=%i offset=0x%llx %m\n",
252 bo->_map, (long long)bo->size, dev->fd,
253 (long long)gem_mmap_offset.offset);
254 }
255 }
256
257 struct agx_bo *
258 agx_bo_import(struct agx_device *dev, int fd)
259 {
260 struct agx_bo *bo;
261 ASSERTED int ret;
262 unsigned gem_handle;
263
264 pthread_mutex_lock(&dev->bo_map_lock);
265
266 ret = drmPrimeFDToHandle(dev->fd, fd, &gem_handle);
267 if (ret) {
268 fprintf(stderr, "import failed: Could not map fd %d to handle\n", fd);
269 pthread_mutex_unlock(&dev->bo_map_lock);
270 return NULL;
271 }
272
273 bo = agx_lookup_bo(dev, gem_handle);
274 dev->max_handle = MAX2(dev->max_handle, gem_handle);
275
276 if (!bo->size) {
277 bo->dev = dev;
278 bo->size = lseek(fd, 0, SEEK_END);
279 bo->align = AIL_PAGESIZE;
280
281 /* Sometimes this can fail and return -1. size of -1 is not
282 * a nice thing for mmap to try mmap. Be more robust also
283 * for zero sized maps and fail nicely too
284 */
285 if ((bo->size == 0) || (bo->size == (size_t)-1)) {
286 goto error;
287 }
288 if (bo->size & (AIL_PAGESIZE - 1)) {
289 fprintf(
290 stderr,
291 "import failed: BO is not a multiple of the page size (0x%llx bytes)\n",
292 (long long)bo->size);
293 goto error;
294 }
295
296 bo->flags = AGX_BO_SHARED | AGX_BO_SHAREABLE;
297 bo->handle = gem_handle;
298 bo->prime_fd = os_dupfd_cloexec(fd);
299 bo->label = "Imported BO";
300 assert(bo->prime_fd >= 0);
301
302 p_atomic_set(&bo->refcnt, 1);
303 bo->va = agx_va_alloc(dev, bo->size, bo->align, 0, 0);
304
305 if (!bo->va) {
306 fprintf(
307 stderr,
308 "import failed: Could not allocate from VMA heap (0x%llx bytes)\n",
309 (long long)bo->size);
310 abort();
311 }
312
313 if (dev->is_virtio) {
314 bo->uapi_handle = vdrm_handle_to_res_id(dev->vdrm, bo->handle);
315 } else {
316 bo->uapi_handle = bo->handle;
317 }
318
319 ret = agx_bo_bind(dev, bo, bo->va->addr, bo->size, 0,
320 DRM_ASAHI_BIND_READ | DRM_ASAHI_BIND_WRITE);
321 if (ret) {
322 fprintf(stderr, "import failed: Could not bind BO at 0x%llx\n",
323 (long long)bo->va->addr);
324 abort();
325 }
326 } else {
327 /* bo->refcnt == 0 can happen if the BO
328 * was being released but agx_bo_import() acquired the
329 * lock before agx_bo_unreference(). In that case, refcnt
330 * is 0 and we can't use agx_bo_reference() directly, we
331 * have to re-initialize the refcnt().
332 * Note that agx_bo_unreference() checks
333 * refcnt value just after acquiring the lock to
334 * make sure the object is not freed if agx_bo_import()
335 * acquired it in the meantime.
336 */
337 if (p_atomic_read(&bo->refcnt) == 0)
338 p_atomic_set(&bo->refcnt, 1);
339 else
340 agx_bo_reference(bo);
341
342 /* If this bo came back to us via import, it had better
343 * been marked shared to begin with.
344 */
345 assert(bo->flags & AGX_BO_SHAREABLE);
346 assert(bo->flags & AGX_BO_SHARED);
347 assert(bo->prime_fd != -1);
348 }
349 pthread_mutex_unlock(&dev->bo_map_lock);
350
351 assert(bo->dev != NULL && "post-condition");
352
353 if (dev->debug & AGX_DBG_TRACE) {
354 agx_bo_map(bo);
355 agxdecode_track_alloc(dev->agxdecode, bo);
356 }
357
358 return bo;
359
360 error:
361 memset(bo, 0, sizeof(*bo));
362 pthread_mutex_unlock(&dev->bo_map_lock);
363 return NULL;
364 }
365
366 void
367 agx_bo_make_shared(struct agx_device *dev, struct agx_bo *bo)
368 {
369 assert(bo->flags & AGX_BO_SHAREABLE);
370 if (bo->flags & AGX_BO_SHARED) {
371 assert(bo->prime_fd >= 0);
372 return;
373 }
374
375 bo->flags |= AGX_BO_SHARED;
376 assert(bo->prime_fd == -1);
377
378 int ret = drmPrimeHandleToFD(dev->fd, bo->handle, DRM_CLOEXEC | DRM_RDWR,
379 &bo->prime_fd);
380 assert(ret == 0);
381 assert(bo->prime_fd >= 0);
382
383 /* If there is a pending writer to this BO, import it into the buffer
384 * for implicit sync.
385 */
386 uint64_t writer = p_atomic_read_relaxed(&bo->writer);
387 if (writer) {
388 int out_sync_fd = -1;
389 int ret = drmSyncobjExportSyncFile(dev->fd, agx_bo_writer_syncobj(writer),
390 &out_sync_fd);
391 assert(ret >= 0);
392 assert(out_sync_fd >= 0);
393
394 ret = agx_import_sync_file(dev, bo, out_sync_fd);
395 assert(ret >= 0);
396 close(out_sync_fd);
397 }
398 }
399
400 int
401 agx_bo_export(struct agx_device *dev, struct agx_bo *bo)
402 {
403 agx_bo_make_shared(dev, bo);
404
405 assert(bo->prime_fd >= 0);
406 return os_dupfd_cloexec(bo->prime_fd);
407 }
408
409 static int
410 agx_bo_bind_object(struct agx_device *dev,
411 struct drm_asahi_gem_bind_object *bind)
412 {
413 int ret = drmIoctl(dev->fd, DRM_IOCTL_ASAHI_GEM_BIND_OBJECT, bind);
414 if (ret) {
415 fprintf(stderr,
416 "DRM_IOCTL_ASAHI_GEM_BIND_OBJECT failed: %m (handle=%d)\n",
417 bind->handle);
418 }
419
420 return ret;
421 }
422
423 static int
424 agx_bo_unbind_object(struct agx_device *dev, uint32_t object_handle)
425 {
426 struct drm_asahi_gem_bind_object gem_bind = {
427 .op = DRM_ASAHI_BIND_OBJECT_OP_UNBIND,
428 .object_handle = object_handle,
429 };
430
431 int ret = drmIoctl(dev->fd, DRM_IOCTL_ASAHI_GEM_BIND_OBJECT, &gem_bind);
432 if (ret) {
433 fprintf(stderr,
434 "DRM_IOCTL_ASAHI_GEM_BIND_OBJECT failed: %m (object_handle=%d)\n",
435 object_handle);
436 }
437
438 return ret;
439 }
440
441 static ssize_t
442 agx_get_params(struct agx_device *dev, void *buf, size_t size)
443 {
444 struct drm_asahi_get_params get_param = {
445 .param_group = 0,
446 .pointer = (uint64_t)(uintptr_t)buf,
447 .size = size,
448 };
449
450 memset(buf, 0, size);
451
452 int ret = drmIoctl(dev->fd, DRM_IOCTL_ASAHI_GET_PARAMS, &get_param);
453 if (ret) {
454 fprintf(stderr, "DRM_IOCTL_ASAHI_GET_PARAMS failed: %m\n");
455 return -EINVAL;
456 }
457
458 return get_param.size;
459 }
460
461 static int
462 agx_submit(struct agx_device *dev, struct drm_asahi_submit *submit,
463 struct agx_submit_virt *virt)
464 {
465 return drmIoctl(dev->fd, DRM_IOCTL_ASAHI_SUBMIT, submit);
466 }
467
468 const agx_device_ops_t agx_device_drm_ops = {
469 .bo_alloc = agx_bo_alloc,
470 .bo_bind = agx_drm_bo_bind,
471 .bo_mmap = agx_bo_mmap,
472 .get_params = agx_get_params,
473 .submit = agx_submit,
474 .bo_bind_object = agx_bo_bind_object,
475 .bo_unbind_object = agx_bo_unbind_object,
476 };
477
478 static uint64_t
479 gcd(uint64_t n, uint64_t m)
480 {
481 while (n != 0) {
482 uint64_t remainder = m % n;
483 m = n;
484 n = remainder;
485 }
486
487 return m;
488 }
489
490 static void
491 agx_init_timestamps(struct agx_device *dev)
492 {
493 uint64_t user_ts_gcd =
494 gcd(dev->params.command_timestamp_frequency_hz, NSEC_PER_SEC);
495
496 dev->user_timestamp_to_ns.num = NSEC_PER_SEC / user_ts_gcd;
497 dev->user_timestamp_to_ns.den =
498 dev->params.command_timestamp_frequency_hz / user_ts_gcd;
499 }
500
501 bool
502 agx_open_device(void *memctx, struct agx_device *dev)
503 {
504 dev->debug =
505 debug_get_flags_option("ASAHI_MESA_DEBUG", agx_debug_options, 0);
506
507 dev->ops = agx_device_drm_ops;
508
509 ssize_t params_size = -1;
510
511 /* DRM version check */
512 {
513 drmVersionPtr version = drmGetVersion(dev->fd);
514 if (!version) {
515 fprintf(stderr, "cannot get version: %s", strerror(errno));
516 return NULL;
517 }
518
519 if (!strcmp(version->name, "asahi")) {
520 dev->is_virtio = false;
521 dev->ops = agx_device_drm_ops;
522 } else if (!strcmp(version->name, "virtio_gpu")) {
523 dev->is_virtio = true;
524 if (!agx_virtio_open_device(dev)) {
525 fprintf(
526 stderr,
527 "Error opening virtio-gpu device for Asahi native context\n");
528 return false;
529 }
530 } else {
531 return false;
532 }
533
534 drmFreeVersion(version);
535 }
536
537 params_size = dev->ops.get_params(dev, &dev->params, sizeof(dev->params));
538 if (params_size <= 0) {
539 assert(0);
540 return false;
541 }
542 assert(params_size >= sizeof(dev->params));
543
544 assert(dev->params.gpu_generation >= 13);
545 const char *variant = " Unknown";
546 switch (dev->params.gpu_variant) {
547 case 'G':
548 variant = "";
549 break;
550 case 'S':
551 variant = " Pro";
552 break;
553 case 'C':
554 variant = " Max";
555 break;
556 case 'D':
557 variant = " Ultra";
558 break;
559 }
560 snprintf(dev->name, sizeof(dev->name), "Apple M%d%s (G%d%c %02X)",
561 dev->params.gpu_generation - 12, variant,
562 dev->params.gpu_generation, dev->params.gpu_variant,
563 dev->params.gpu_revision + 0xA0);
564
565 /* We need a large chunk of VA space carved out for robustness. Hardware
566 * loads can shift an i32 by up to 2, for a total shift of 4. If the base
567 * address is zero, 36-bits is therefore enough to trap any zero-extended
568 * 32-bit index. For more generality we would need a larger carveout, but
569 * this is already optimal for VBOs.
570 *
571 * TODO: Maybe this should be on top instead? Might be ok.
572 */
573 uint64_t reservation = (1ull << 36);
574
575 /* Also reserve VA space for the printf buffer at a stable address, avoiding
576 * the need for relocs in precompiled shaders.
577 */
578 assert(reservation == LIBAGX_PRINTF_BUFFER_ADDRESS);
579 reservation += LIBAGX_PRINTF_BUFFER_SIZE;
580
581 dev->guard_size = AIL_PAGESIZE;
582 // Put the USC heap at the bottom of the user address space, 4GiB aligned
583 dev->shader_base =
584 ALIGN_POT(MAX2(dev->params.vm_start, reservation), 0x100000000ull);
585
586 if (dev->shader_base < reservation) {
587 /* Our robustness implementation requires the bottom unmapped */
588 fprintf(stderr, "Unexpected address layout, can't cope\n");
589 assert(0);
590 return false;
591 }
592
593 uint64_t shader_size = 0x100000000ull;
594 // Put the user heap after the USC heap
595 uint64_t user_start = dev->shader_base + shader_size;
596
597 assert(dev->shader_base >= dev->params.vm_start);
598 assert(user_start < dev->params.vm_end);
599
600 dev->agxdecode = agxdecode_new_context(dev->shader_base);
601
602 agx_init_timestamps(dev);
603
604 util_sparse_array_init(&dev->bo_map, sizeof(struct agx_bo), 512);
605 pthread_mutex_init(&dev->bo_map_lock, NULL);
606
607 simple_mtx_init(&dev->bo_cache.lock, mtx_plain);
608 list_inithead(&dev->bo_cache.lru);
609
610 for (unsigned i = 0; i < ARRAY_SIZE(dev->bo_cache.buckets); ++i)
611 list_inithead(&dev->bo_cache.buckets[i]);
612
613 // Put the kernel heap at the top of the address space.
614 // Give it 32GB of address space, should be more than enough for any
615 // reasonable use case.
616 uint64_t kernel_size = MAX2(dev->params.vm_kernel_min_size, 32ull << 30);
617 struct drm_asahi_vm_create vm_create = {
618 .kernel_start = dev->params.vm_end - kernel_size,
619 .kernel_end = dev->params.vm_end,
620 };
621
622 uint64_t user_size = vm_create.kernel_start - user_start;
623
624 int ret = asahi_simple_ioctl(dev, DRM_IOCTL_ASAHI_VM_CREATE, &vm_create);
625 if (ret) {
626 fprintf(stderr, "DRM_IOCTL_ASAHI_VM_CREATE failed: %m\n");
627 assert(0);
628 return false;
629 }
630
631 /* Round the user VA window to powers-of-two... */
632 user_start = util_next_power_of_two64(user_start);
633 user_size = util_next_power_of_two64(user_size + 1) >> 1;
634
635 /* ...so when we cut user size in half to emulate sparse buffers... */
636 user_size /= 2;
637
638 /* ...or maybe in quarters if necessary to disambiguate */
639 if (user_size == user_start) {
640 user_size /= 2;
641 }
642
643 /* ...we can distinguish the top/bottom half by an address bit */
644 dev->sparse_ro_offset = user_size;
645 assert((user_start & dev->sparse_ro_offset) == 0);
646 assert(((user_start + (user_size - 1)) & dev->sparse_ro_offset) == 0);
647
648 simple_mtx_init(&dev->vma_lock, mtx_plain);
649 util_vma_heap_init(&dev->main_heap, user_start, user_size);
650 util_vma_heap_init(&dev->usc_heap, dev->shader_base, shader_size);
651
652 dev->vm_id = vm_create.vm_id;
653
654 glsl_type_singleton_init_or_ref();
655
656 if (agx_gather_device_key(dev).needs_g13x_coherency == U_TRISTATE_YES) {
657 dev->libagx_programs = libagx_g13x;
658 } else {
659 dev->libagx_programs = libagx_g13g;
660 }
661
662 if (dev->params.gpu_generation >= 14 && dev->params.num_clusters_total > 1) {
663 dev->chip = AGX_CHIP_G14X;
664 } else if (dev->params.gpu_generation >= 14) {
665 dev->chip = AGX_CHIP_G14G;
666 } else if (dev->params.gpu_generation >= 13 &&
667 dev->params.num_clusters_total > 1) {
668 dev->chip = AGX_CHIP_G13X;
669 } else {
670 dev->chip = AGX_CHIP_G13G;
671 }
672
673 /* Bind read-only zero page at 2^32. This is in our reservation, and can be
674 * addressed with only small integers in the low/high. That lets us do some
675 * robustness optimization even without soft fault.
676 */
677 {
678 void *bo = agx_bo_create(dev, 16384, 0, 0, "Zero page");
679 int ret = agx_bo_bind(dev, bo, AGX_ZERO_PAGE_ADDRESS, 16384, 0,
680 DRM_ASAHI_BIND_READ);
681 if (ret) {
682 fprintf(stderr, "Failed to bind zero page");
683 return false;
684 }
685
686 dev->zero_bo = bo;
687 }
688
689 {
690 void *bo = agx_bo_create(dev, AIL_PAGESIZE, 0, 0, "Scratch page");
691 int ret = agx_bo_bind(dev, bo, AGX_SCRATCH_PAGE_ADDRESS, AIL_PAGESIZE, 0,
692 DRM_ASAHI_BIND_READ | DRM_ASAHI_BIND_WRITE);
693 if (ret) {
694 fprintf(stderr, "Failed to bind zero page");
695 return false;
696 }
697
698 dev->scratch_bo = bo;
699
700 /* The contents of the scratch page are undefined, but making them nonzero
701 * helps fuzz for bugs where we incorrectly read from the write section.
702 */
703 memset(agx_bo_map(dev->scratch_bo), 0xCA, AIL_PAGESIZE);
704 }
705
706 void *bo = agx_bo_create(dev, LIBAGX_PRINTF_BUFFER_SIZE, 0, AGX_BO_WRITEBACK,
707 "Printf/abort");
708
709 ret = agx_bo_bind(dev, bo, LIBAGX_PRINTF_BUFFER_ADDRESS,
710 LIBAGX_PRINTF_BUFFER_SIZE, 0,
711 DRM_ASAHI_BIND_READ | DRM_ASAHI_BIND_WRITE);
712 if (ret) {
713 fprintf(stderr, "Failed to bind printf buffer");
714 return false;
715 }
716
717 u_printf_init(&dev->printf, bo, agx_bo_map(bo));
718 return true;
719 }
720
721 void
722 agx_close_device(struct agx_device *dev)
723 {
724 agx_bo_unreference(dev, dev->printf.bo);
725 agx_bo_unreference(dev, dev->zero_bo);
726 agx_bo_unreference(dev, dev->scratch_bo);
727 u_printf_destroy(&dev->printf);
728 agx_bo_cache_evict_all(dev);
729 util_sparse_array_finish(&dev->bo_map);
730 agxdecode_destroy_context(dev->agxdecode);
731
732 util_vma_heap_finish(&dev->main_heap);
733 util_vma_heap_finish(&dev->usc_heap);
734 glsl_type_singleton_decref();
735
736 close(dev->fd);
737 }
738
739 uint32_t
740 agx_create_command_queue(struct agx_device *dev,
741 enum drm_asahi_priority priority)
742 {
743
744 if (dev->debug & AGX_DBG_1QUEUE) {
745 // Abuse this lock for this, it's debug only anyway
746 simple_mtx_lock(&dev->vma_lock);
747 if (dev->queue_id) {
748 simple_mtx_unlock(&dev->vma_lock);
749 return dev->queue_id;
750 }
751 }
752
753 struct drm_asahi_queue_create queue_create = {
754 .vm_id = dev->vm_id,
755 .priority = priority,
756 .usc_exec_base = dev->shader_base,
757 };
758
759 int ret =
760 asahi_simple_ioctl(dev, DRM_IOCTL_ASAHI_QUEUE_CREATE, &queue_create);
761 if (ret) {
762 fprintf(stderr, "DRM_IOCTL_ASAHI_QUEUE_CREATE failed: %m\n");
763 assert(0);
764 }
765
766 if (dev->debug & AGX_DBG_1QUEUE) {
767 dev->queue_id = queue_create.queue_id;
768 simple_mtx_unlock(&dev->vma_lock);
769 }
770
771 return queue_create.queue_id;
772 }
773
774 int
775 agx_destroy_command_queue(struct agx_device *dev, uint32_t queue_id)
776 {
777 if (dev->debug & AGX_DBG_1QUEUE)
778 return 0;
779
780 struct drm_asahi_queue_destroy queue_destroy = {
781 .queue_id = queue_id,
782 };
783
784 return asahi_simple_ioctl(dev, DRM_IOCTL_ASAHI_QUEUE_DESTROY,
785 &queue_destroy);
786 }
787
788 int
789 agx_import_sync_file(struct agx_device *dev, struct agx_bo *bo, int fd)
790 {
791 struct dma_buf_import_sync_file import_sync_file_ioctl = {
792 .flags = DMA_BUF_SYNC_WRITE,
793 .fd = fd,
794 };
795
796 assert(fd >= 0);
797 assert(bo->prime_fd != -1);
798
799 int ret = drmIoctl(bo->prime_fd, DMA_BUF_IOCTL_IMPORT_SYNC_FILE,
800 &import_sync_file_ioctl);
801 assert(ret >= 0);
802
803 return ret;
804 }
805
806 int
807 agx_export_sync_file(struct agx_device *dev, struct agx_bo *bo)
808 {
809 struct dma_buf_export_sync_file export_sync_file_ioctl = {
810 .flags = DMA_BUF_SYNC_RW,
811 .fd = -1,
812 };
813
814 assert(bo->prime_fd != -1);
815
816 int ret = drmIoctl(bo->prime_fd, DMA_BUF_IOCTL_EXPORT_SYNC_FILE,
817 &export_sync_file_ioctl);
818 assert(ret >= 0);
819 assert(export_sync_file_ioctl.fd >= 0);
820
821 return ret >= 0 ? export_sync_file_ioctl.fd : ret;
822 }
823
824 void
825 agx_debug_fault(struct agx_device *dev, uint64_t addr)
826 {
827 pthread_mutex_lock(&dev->bo_map_lock);
828
829 struct agx_bo *best = NULL;
830
831 for (uint32_t handle = 0; handle < dev->max_handle; handle++) {
832 struct agx_bo *bo = agx_lookup_bo(dev, handle);
833 if (!bo->va)
834 continue;
835
836 uint64_t bo_addr = bo->va->addr;
837 if (bo->flags & AGX_BO_LOW_VA)
838 bo_addr += dev->shader_base;
839
840 if (!bo->size || bo_addr > addr)
841 continue;
842
843 if (!best || bo_addr > best->va->addr)
844 best = bo;
845 }
846
847 if (!best) {
848 mesa_logw("Address 0x%" PRIx64 " is unknown\n", addr);
849 } else {
850 uint64_t start = best->va->addr;
851 uint64_t end = best->va->addr + best->size;
852 if (addr > (end + 1024 * 1024 * 1024)) {
853 /* 1GiB max as a sanity check */
854 mesa_logw("Address 0x%" PRIx64 " is unknown\n", addr);
855 } else if (addr > end) {
856 mesa_logw("Address 0x%" PRIx64 " is 0x%" PRIx64
857 " bytes beyond an object at 0x%" PRIx64 "..0x%" PRIx64
858 " (%s)\n",
859 addr, addr - end, start, end - 1, best->label);
860 } else {
861 mesa_logw("Address 0x%" PRIx64 " is 0x%" PRIx64
862 " bytes into an object at 0x%" PRIx64 "..0x%" PRIx64
863 " (%s)\n",
864 addr, addr - start, start, end - 1, best->label);
865 }
866 }
867
868 pthread_mutex_unlock(&dev->bo_map_lock);
869 }
870
871 uint64_t
872 agx_get_gpu_timestamp(struct agx_device *dev)
873 {
874 struct drm_asahi_get_time get_time = {.flags = 0};
875
876 int ret = asahi_simple_ioctl(dev, DRM_IOCTL_ASAHI_GET_TIME, &get_time);
877 if (ret) {
878 fprintf(stderr, "DRM_IOCTL_ASAHI_GET_TIME failed: %m\n");
879 }
880
881 return get_time.gpu_timestamp;
882 }
883
884 /* (Re)define UUID_SIZE to avoid including vulkan.h (or p_defines.h) here. */
885 #define UUID_SIZE 16
886
887 void
888 agx_get_device_uuid(const struct agx_device *dev, void *uuid)
889 {
890 blake3_hasher blake3_ctx;
891 _mesa_blake3_init(&blake3_ctx);
892
893 /* The device UUID uniquely identifies the given device within the machine.
894 * Since we never have more than one device, this doesn't need to be a real
895 * UUID, so we use BLAKE3("agx" + gpu_generation + gpu_variant + gpu_revision).
896 */
897 static const char *device_name = "agx";
898 _mesa_blake3_update(&blake3_ctx, device_name, strlen(device_name));
899
900 _mesa_blake3_update(&blake3_ctx, &dev->params.gpu_generation,
901 sizeof(dev->params.gpu_generation));
902 _mesa_blake3_update(&blake3_ctx, &dev->params.gpu_variant,
903 sizeof(dev->params.gpu_variant));
904 _mesa_blake3_update(&blake3_ctx, &dev->params.gpu_revision,
905 sizeof(dev->params.gpu_revision));
906
907 uint8_t blake3[BLAKE3_KEY_LEN];
908 _mesa_blake3_final(&blake3_ctx, blake3);
909
910 assert(BLAKE3_KEY_LEN >= UUID_SIZE);
911 memcpy(uuid, blake3, UUID_SIZE);
912 }
913
914 void
915 agx_get_driver_uuid(void *uuid)
916 {
917 const char *driver_id = PACKAGE_VERSION MESA_GIT_SHA1;
918
919 /* The driver UUID is used for determining sharability of images and memory
920 * between two Vulkan instances in separate processes, but also to
921 * determining memory objects and sharability between Vulkan and OpenGL
922 * driver. People who want to share memory need to also check the device
923 * UUID.
924 */
925 blake3_hasher blake3_ctx;
926 _mesa_blake3_init(&blake3_ctx);
927
928 _mesa_blake3_update(&blake3_ctx, driver_id, strlen(driver_id));
929
930 uint8_t blake3[BLAKE3_KEY_LEN];
931 _mesa_blake3_final(&blake3_ctx, blake3);
932
933 assert(BLAKE3_KEY_LEN >= UUID_SIZE);
934 memcpy(uuid, blake3, UUID_SIZE);
935 }
936
937 unsigned
938 agx_get_num_cores(const struct agx_device *dev)
939 {
940 unsigned n = 0;
941
942 for (unsigned cl = 0; cl < dev->params.num_clusters_total; cl++) {
943 n += util_bitcount(dev->params.core_masks[cl]);
944 }
945
946 return n;
947 }
948
949 struct agx_device_key
950 agx_gather_device_key(struct agx_device *dev)
951 {
952 bool g13x_coh = (dev->params.gpu_generation == 13 &&
953 dev->params.num_clusters_total > 1) ||
954 dev->params.num_dies > 1;
955
956 return (struct agx_device_key){
957 .needs_g13x_coherency = u_tristate_make(g13x_coh),
958 .soft_fault = agx_has_soft_fault(dev),
959 };
960 }