interplane.Get Omega
Read in your language

physics-mv

FORGE: request-bound machine realization, providers and verification for AienOS. Host, simulated and GB10 hardware paths have separate evidence.

Brought by drakestapleton

branch main Branches Tags History

physics-mv / nvrm / nvrm.c

1054 lines · 45585 bytes Raw Blame History
1/*
2 * nvrm.c -- PHYSICS native accelerator substrate (NVRM client), used by M16 qualification,
3 * FORGE realization and the NVRM gates in this tree. M17 (OMEGA_BLACKWELL_VECTOR) was
4 * qualified in aien-spark/omega, not here (aien-architecture doctrine/ROADMAP.md).
5 * See nvrm.h. Sequence follows the NVIDIA open kernel module ABI (580.173.02).
6 */
7
8#include "nvrm.h"
9
10#include <errno.h>
11#include <stddef.h>
12#include <stdatomic.h>
13#include <fcntl.h>
14#include <limits.h>
15#include <stdarg.h>
16#include <stdio.h>
17#include <string.h>
18#include <sys/ioctl.h>
19#include <sys/mman.h>
20#include <time.h>
21#include <unistd.h>
22
23#include "nvos.h"
24#include "nv-ioctl.h"
25#include "nv-ioctl-numbers.h"
26#include "nv_escape.h"
27#include "uvm_linux_ioctl.h"
28#include "uvm_ioctl.h"
29#include "nv-unix-nvos-params-wrappers.h"
30#include "class/clc361.h"
31#include "class/cl0000.h"
32#include "class/cl0080.h"
33#include "class/cl2080.h"
34#include "class/cl0070.h"
35#include "class/cl003e.h"
36#include "class/cl0040.h"
37#include "class/cl90f1.h"
38#include "class/cl9067.h"
39#include "class/cla06c.h"
40#include "class/clc96f.h"
41#include "class/clcec0.h"
42#include "class/clc661.h"
43#include "alloc/alloc_channel.h"
44#include "ctrl/ctrl0000/ctrl0000gpu.h"
45#include "ctrl/ctrl0080/ctrl0080gpu.h"
46#include "ctrl/ctrl2080/ctrl2080gpu.h"
47#include "ctrl/ctrl2080/ctrl2080gr.h"
48#include "ctrl/ctrla06c.h"
49#include "ctrl/ctrlc36f.h"
50
51#define NV_IOWR(nr, sz) _IOC(_IOC_READ | _IOC_WRITE, NV_IOCTL_MAGIC, (nr), (sz))
52
53static int fail(Nvrm *rm, const char *fmt, ...) {
54 va_list ap;
55 va_start(ap, fmt);
56 vsnprintf(rm->err, sizeof rm->err, fmt, ap);
57 va_end(ap);
58 return -1;
59}
60
61/* One /proc/meminfo value in kB, or 0 when it cannot be read. An RM_ALLOC
62 * refused with NV_ERR_NO_MEMORY is only explained next to the size asked for
63 * and the host's memory at that moment (sovereign-core #239). Both numbers
64 * matter: the RM system-memory path failed on low MemFree while MemAvailable
65 * was high (omega#327, two arms), so MemAvailable alone would read as fine. */
66static unsigned long long meminfo_kb(const char *key) {
67 FILE *f = fopen("/proc/meminfo", "r");
68 if (!f) return 0;
69 char line[256];
70 unsigned long long kb = 0;
71 size_t klen = strlen(key);
72 while (fgets(line, sizeof line, f)) {
73 if (strncmp(line, key, klen) != 0 || line[klen] != ':') continue;
74 if (sscanf(line + klen + 1, " %llu kB", &kb) != 1) kb = 0;
75 break;
76 }
77 fclose(f);
78 return kb;
79}
80
81/* Rewrite rm->err after a failed memory RM_ALLOC so it also carries the
82 * requested size, MemFree and MemAvailable. */
83static int fail_alloc_context(Nvrm *rm, uint64_t size) {
84 char prev[sizeof rm->err];
85 memcpy(prev, rm->err, sizeof prev);
86 return fail(rm, "%s for %llu bytes, MemFree %llu kB, MemAvailable %llu kB", prev,
87 (unsigned long long)size, meminfo_kb("MemFree"), meminfo_kb("MemAvailable"));
88}
89
90/* Free physically contiguous blocks of at least `order` pages in the buddy
91 * table at `path` (normally /proc/buddyinfo), counting only the zones named
92 * `zone`, or every zone when `zone` is NULL; ULLONG_MAX when the file cannot
93 * be read. Order 9 is the 2 MiB block the channel's main context buffer needs. */
94unsigned long long nvrm_buddy_free_blocks_ge(const char *path, const char *zone, unsigned order) {
95 FILE *f = fopen(path, "r");
96 if (!f) return ULLONG_MAX;
97 char line[512];
98 unsigned long long total = 0;
99 size_t zlen = zone ? strlen(zone) : 0;
100 while (fgets(line, sizeof line, f)) {
101 const char *p = strstr(line, "zone");
102 if (!p) continue;
103 p += 4;
104 while (*p == ' ') p++;
105 const char *name = p;
106 while (*p && *p != ' ') p++; /* zone name */
107 if (zone && ((size_t)(p - name) != zlen || strncmp(name, zone, zlen) != 0)) continue;
108 unsigned long long n;
109 for (unsigned o = 0; o < 32 && sscanf(p, " %llu", &n) == 1; o++) {
110 if (o >= order) total += n;
111 while (*p == ' ') p++;
112 while (*p && *p != ' ') p++;
113 }
114 }
115 fclose(f);
116 return total;
117}
118
119static void blocks_text(char *out, size_t cap, unsigned long long n) {
120 if (n == ULLONG_MAX) snprintf(out, cap, "UNKNOWN");
121 else snprintf(out, cap, "%llu", n);
122}
123
124/* The 2 MiB-block part of the NV_ERR_NO_MEMORY report, read from the buddy
125 * table at `path`: the Normal-zone count first, then all zones. */
126void nvrm_no_memory_blocks(const char *path, char *out, size_t cap) {
127 char normal[32], all[32];
128 blocks_text(normal, sizeof normal, nvrm_buddy_free_blocks_ge(path, "Normal", 9));
129 blocks_text(all, sizeof all, nvrm_buddy_free_blocks_ge(path, NULL, 9));
130 snprintf(out, cap, "free 2 MiB blocks in the Normal zone %s (all zones %s)", normal, all);
131}
132
133/* Rewrite rm->err after the compute-object RM_ALLOC stayed NV_ERR_NO_MEMORY
134 * through every retry, so the line names the attempts, the wait and the host's
135 * supply of 2 MiB blocks at that moment, in the Normal zone and in all zones.
136 * An all-zone count alone misleads: on the Spark the failure line of the R13
137 * instr4 run read "free 2 MiB blocks 35" (all zones), and the buddy tables
138 * recorded before the DRA-351 runs of 2026-11-16 held 0 to 10 free blocks of
139 * order 9 or more in the Normal zone (351-r13-instr6.buddy-pre: 0;
140 * 351-r13-instr4.buddy-pre: 10). Even the Normal-zone count is an upper bound:
141 * /proc/buddyinfo counts every migratetype (CMA included) and ignores
142 * watermarks, so a nonzero count does not prove the allocation could succeed. */
143static int fail_channel_no_memory(Nvrm *rm, uint32_t attempts, uint32_t delay_ms) {
144 char prev[sizeof rm->err];
145 memcpy(prev, rm->err, sizeof prev);
146 char blocks[128];
147 nvrm_no_memory_blocks("/proc/buddyinfo", blocks, sizeof blocks);
148 return fail(rm, "%s after %u attempts over %u ms; MemFree %llu kB, %s", prev, attempts,
149 (attempts > 1 ? attempts - 1 : 0) * delay_ms, meminfo_kb("MemFree"), blocks);
150}
151
152static int nv_ioctl(int fd, unsigned nr, void *arg, size_t sz) {
153 return ioctl(fd, NV_IOWR(nr, sz), arg);
154}
155
156static int uvm(Nvrm *rm, int fd, unsigned long cmd, void *params, NV_STATUS *st);
157
158static int rm_alloc(Nvrm *rm, uint32_t parent, uint32_t cls, void *params, uint32_t psz, uint32_t *out) {
159 rm->last_rm_status = 0;
160 if (cls == rm->compute_class && rm->inject_rm_alloc_no_memory) {
161 rm->inject_rm_alloc_no_memory--;
162 rm->last_rm_status = NV_ERR_NO_MEMORY;
163 return fail(rm, "RM_ALLOC class 0x%x status 0x%x (NV_ERR_NO_MEMORY) [injected]", cls, NV_ERR_NO_MEMORY);
164 }
165 if (rm->rm_alloc_accepted == UINT64_MAX ||
166 (cls != NV01_ROOT_CLIENT && rm->next_handle == UINT32_MAX))
167 return fail(rm, "RM handle or accounting space exhausted");
168 NVOS21_PARAMETERS p;
169 memset(&p, 0, sizeof p);
170 p.hRoot = rm->root;
171 p.hObjectParent = parent;
172 p.hObjectNew = (cls == NV01_ROOT_CLIENT) ? 0 : rm->next_handle++;
173 p.hClass = cls;
174 p.pAllocParms = NV_PTR_TO_NvP64(params);
175 p.paramsSize = psz;
176 if (nv_ioctl(rm->fd_ctl, NV_ESC_RM_ALLOC, &p, sizeof p) != 0)
177 return fail(rm, "RM_ALLOC class 0x%x ioctl errno %d", cls, errno);
178 rm->last_rm_status = p.status;
179 if (p.status != 0)
180 return fail(rm, "RM_ALLOC class 0x%x status 0x%x%s", cls, p.status,
181 p.status == NV_ERR_NO_MEMORY ? " (NV_ERR_NO_MEMORY)" : "");
182 rm->rm_alloc_accepted++;
183 *out = p.hObjectNew;
184 return 0;
185}
186
187static int rm_free(Nvrm *rm, uint32_t parent, uint32_t obj) {
188 if (!obj) return 0;
189 if (rm->rm_free_accepted == UINT64_MAX) return fail(rm, "RM free accounting exhausted");
190 if (rm->inject_rm_free_failure) {
191 rm->inject_rm_free_failure = 0;
192 return fail(rm, "injected RM_FREE failure for handle 0x%x", obj);
193 }
194 NVOS00_PARAMETERS f;
195 memset(&f, 0, sizeof f);
196 f.hRoot = rm->root;
197 f.hObjectParent = parent;
198 f.hObjectOld = obj;
199 if (nv_ioctl(rm->fd_ctl, NV_ESC_RM_FREE, &f, sizeof f) != 0)
200 return fail(rm, "RM_FREE handle 0x%x errno %d", obj, errno);
201 if (f.status != NV_OK) return fail(rm, "RM_FREE handle 0x%x status 0x%x", obj, f.status);
202 rm->rm_free_accepted++;
203 return 0;
204}
205
206static int uvm_free_checked(Nvrm *rm, uint64_t va, uint64_t size) {
207 if (rm->inject_uvm_free_failure) {
208 rm->inject_uvm_free_failure = 0;
209 return fail(rm, "injected UVM_FREE failure for VA 0x%lx", (unsigned long)va);
210 }
211 UVM_FREE_PARAMS uf;
212 memset(&uf, 0, sizeof uf);
213 uf.base = va;
214 uf.length = size;
215 return uvm(rm, rm->fd_uvm, UVM_FREE, &uf, &uf.rmStatus);
216}
217
218static int dma_unmap_checked(Nvrm *rm, uint32_t hmem, uint64_t va, uint64_t size) {
219 NVOS47_PARAMETERS p;
220 memset(&p, 0, sizeof p);
221 p.hClient = rm->root;
222 p.hDevice = rm->device;
223 p.hDma = rm->virtmem;
224 p.hMemory = hmem;
225 p.dmaOffset = va;
226 p.size = size;
227 if (nv_ioctl(rm->fd_ctl, NV_ESC_RM_UNMAP_MEMORY_DMA, &p, sizeof p) != 0)
228 return fail(rm, "RM_UNMAP_MEMORY_DMA errno %d", errno);
229 if (p.status != NV_OK) return fail(rm, "RM_UNMAP_MEMORY_DMA status 0x%x", p.status);
230 return 0;
231}
232
233static int rm_control(Nvrm *rm, uint32_t obj, uint32_t cmd, void *params, uint32_t psz) {
234 NVOS54_PARAMETERS p;
235 memset(&p, 0, sizeof p);
236 p.hClient = rm->root;
237 p.hObject = obj;
238 p.cmd = cmd;
239 p.params = NV_PTR_TO_NvP64(params);
240 p.paramsSize = psz;
241 if (nv_ioctl(rm->fd_ctl, NV_ESC_RM_CONTROL, &p, sizeof p) != 0)
242 return fail(rm, "RM_CONTROL 0x%x ioctl errno %d", cmd, errno);
243 if (p.status != 0) return fail(rm, "RM_CONTROL 0x%x status 0x%x", cmd, p.status);
244 return 0;
245}
246
247static int uvm(Nvrm *rm, int fd, unsigned long cmd, void *params, NV_STATUS *st) {
248 if (ioctl(fd, cmd, params) != 0) return fail(rm, "UVM 0x%lx errno %d", cmd, errno);
249 if (st && *st != NV_OK) return fail(rm, "UVM 0x%lx status 0x%x", cmd, *st);
250 return 0;
251}
252
253static int open_dev_fd(Nvrm *rm) {
254 char path[32];
255 snprintf(path, sizeof path, "/dev/nvidia%u", rm->minor);
256 int fd = open(path, O_RDWR | O_CLOEXEC);
257 if (fd < 0) return fail(rm, "open %s errno %d", path, errno);
258 nv_ioctl_register_fd_t r = { .ctl_fd = rm->fd_ctl };
259 if (nv_ioctl(fd, NV_ESC_REGISTER_FD, &r, sizeof r) != 0) { close(fd); return fail(rm, "REGISTER_FD errno %d", errno); }
260 return fd;
261}
262
263/* Map an RM memory object into this process at a fixed CPU address. */
264static void *map_to_cpu(Nvrm *rm, uint32_t hmem, uint64_t size, void *target, uint32_t flags, int system) {
265 int fd = system ? open("/dev/nvidiactl", O_RDWR | O_CLOEXEC) : open_dev_fd(rm);
266 if (fd < 0) { fail(rm, "map fd"); return MAP_FAILED; }
267 nv_ioctl_nvos33_parameters_with_fd m;
268 memset(&m, 0, sizeof m);
269 m.fd = fd;
270 m.params.hClient = rm->root;
271 m.params.hDevice = rm->device;
272 m.params.hMemory = hmem;
273 m.params.length = size;
274 m.params.flags = flags;
275 if (nv_ioctl(rm->fd_ctl, NV_ESC_RM_MAP_MEMORY, &m, sizeof m) != 0 || m.params.status != 0) {
276 fail(rm, "RM_MAP_MEMORY errno %d status 0x%x", errno, m.params.status);
277 close(fd);
278 return MAP_FAILED;
279 }
280 void *p = mmap(target, size, PROT_READ | PROT_WRITE, MAP_SHARED | (target ? MAP_FIXED : 0), fd, 0);
281 close(fd);
282 if (p == MAP_FAILED) fail(rm, "mmap errno %d", errno);
283 return p;
284}
285
286static _Atomic uint64_t g_va_counter = 0x1000000000ull;
287static atomic_flag g_va_slots_lock = ATOMIC_FLAG_INIT;
288static uint64_t g_va_recycled[1024];
289static uint32_t g_va_recycled_count;
290
291static uint64_t acquire_va_slot(void) {
292 while (atomic_flag_test_and_set_explicit(&g_va_slots_lock, memory_order_acquire)) { }
293 uint64_t base = g_va_recycled_count ? g_va_recycled[--g_va_recycled_count] : 0;
294 atomic_flag_clear_explicit(&g_va_slots_lock, memory_order_release);
295 if (!base) {
296 uint64_t old = atomic_load_explicit(&g_va_counter, memory_order_relaxed);
297 for (;;) {
298 if (old > UINT64_MAX - 0x100000000ull) return 0;
299 if (atomic_compare_exchange_weak_explicit(&g_va_counter, &old,
300 old + 0x100000000ull, memory_order_relaxed, memory_order_relaxed)) {
301 base = old;
302 break;
303 }
304 }
305 }
306 return base;
307}
308
309static void recycle_va_slot(uint64_t base) {
310 while (atomic_flag_test_and_set_explicit(&g_va_slots_lock, memory_order_acquire)) { }
311 if (g_va_recycled_count < 1024) g_va_recycled[g_va_recycled_count++] = base;
312 atomic_flag_clear_explicit(&g_va_slots_lock, memory_order_release);
313}
314
315int nvrm_open(Nvrm *rm) {
316 memset(rm, 0, sizeof *rm);
317 rm->next_handle = 0xcf000001u;
318 rm->va_next = acquire_va_slot();
319 if (!rm->va_next) return fail(rm, "VA slot space exhausted");
320 rm->va_slot_base = rm->va_next;
321 rm->fd_ctl = open("/dev/nvidiactl", O_RDWR | O_CLOEXEC);
322 rm->fd_uvm = open("/dev/nvidia-uvm", O_RDWR | O_CLOEXEC);
323 rm->fd_uvm2 = open("/dev/nvidia-uvm", O_RDWR | O_CLOEXEC);
324 if (rm->fd_ctl < 0 || rm->fd_uvm < 0 || rm->fd_uvm2 < 0) return fail(rm, "open control nodes errno %d", errno);
325
326 if (rm_alloc(rm, 0, NV01_ROOT_CLIENT, NULL, 0, &rm->root)) return -1;
327
328 UVM_INITIALIZE_PARAMS ui;
329 memset(&ui, 0, sizeof ui);
330 if (uvm(rm, rm->fd_uvm, UVM_INITIALIZE, &ui, &ui.rmStatus)) return -1;
331 UVM_MM_INITIALIZE_PARAMS mi;
332 memset(&mi, 0, sizeof mi);
333 mi.uvmFd = rm->fd_uvm;
334 (void)ioctl(rm->fd_uvm2, UVM_MM_INITIALIZE, &mi); /* libcuda also tolerates failure here */
335
336 nv_ioctl_card_info_t cards[64];
337 memset(cards, 0, sizeof cards);
338 if (nv_ioctl(rm->fd_ctl, NV_ESC_CARD_INFO, cards, sizeof cards) != 0) return fail(rm, "CARD_INFO errno %d", errno);
339 int found = -1;
340 for (int i = 0; i < 64; i++) if (cards[i].valid) { found = i; break; }
341 if (found < 0) return fail(rm, "no GPU");
342 rm->gpu_id = cards[found].gpu_id;
343 rm->minor = cards[found].minor_number;
344
345 rm->fd_dev = open_dev_fd(rm);
346 if (rm->fd_dev < 0) return -1;
347
348 NV0000_CTRL_GPU_GET_ID_INFO_V2_PARAMS idinfo;
349 memset(&idinfo, 0, sizeof idinfo);
350 idinfo.gpuId = rm->gpu_id;
351 if (rm_control(rm, rm->root, NV0000_CTRL_CMD_GPU_GET_ID_INFO_V2, &idinfo, sizeof idinfo)) return -1;
352
353 NV0080_ALLOC_PARAMETERS dp;
354 memset(&dp, 0, sizeof dp);
355 dp.deviceId = idinfo.deviceInstance;
356 dp.hClientShare = rm->root;
357 dp.vaMode = NV_DEVICE_ALLOCATION_VAMODE_OPTIONAL_MULTIPLE_VASPACES;
358 if (rm_alloc(rm, rm->root, NV01_DEVICE_0, &dp, sizeof dp, &rm->device)) return -1;
359 NV2080_ALLOC_PARAMETERS sp;
360 memset(&sp, 0, sizeof sp);
361 if (rm_alloc(rm, rm->device, NV20_SUBDEVICE_0, &sp, sizeof sp, &rm->subdevice)) return -1;
362 NV_MEMORY_VIRTUAL_ALLOCATION_PARAMS vp;
363 memset(&vp, 0, sizeof vp);
364 vp.limit = 0x1ffffffffffffull;
365 if (rm_alloc(rm, rm->device, NV01_MEMORY_VIRTUAL, &vp, sizeof vp, &rm->virtmem)) return -1;
366
367 /* Class list: pick the Blackwell classes that this RM exposes. */
368 NV0080_CTRL_GPU_GET_CLASSLIST_PARAMS cl;
369 memset(&cl, 0, sizeof cl);
370 if (rm_control(rm, rm->device, NV0080_CTRL_CMD_GPU_GET_CLASSLIST, &cl, sizeof cl)) return -1;
371 uint32_t classes[512];
372 if (cl.numClasses > 512) return fail(rm, "too many classes");
373 cl.classList = NV_PTR_TO_NvP64(classes);
374 if (rm_control(rm, rm->device, NV0080_CTRL_CMD_GPU_GET_CLASSLIST, &cl, sizeof cl)) return -1;
375 for (uint32_t i = 0; i < cl.numClasses; i++) {
376 if (classes[i] == BLACKWELL_COMPUTE_B) rm->compute_class = classes[i];
377 if (classes[i] == BLACKWELL_CHANNEL_GPFIFO_A) rm->gpfifo_class = classes[i];
378 if (classes[i] == HOPPER_USERMODE_A) rm->usermode_class = classes[i];
379 }
380 if (!rm->compute_class || !rm->gpfifo_class || !rm->usermode_class)
381 return fail(rm, "missing class: compute 0x%x gpfifo 0x%x usermode 0x%x",
382 rm->compute_class, rm->gpfifo_class, rm->usermode_class);
383
384 if (rm_alloc(rm, rm->subdevice, rm->usermode_class, NULL, 0, &rm->usermode)) return -1;
385 void *mmio = map_to_cpu(rm, rm->usermode, 0x10000, NULL, 0, 0);
386 if (mmio == MAP_FAILED) return -1;
387 rm->usermode_cpu = mmio;
388 rm->doorbell = (volatile uint32_t *)((uint8_t *)mmio + NVC361_NOTIFY_CHANNEL_PENDING);
389
390 NV2080_CTRL_GR_INFO gi = { .index = NV2080_CTRL_GR_INFO_INDEX_SM_VERSION };
391 NV2080_CTRL_GR_GET_INFO_PARAMS gp;
392 memset(&gp, 0, sizeof gp);
393 gp.grInfoListSize = 1;
394 gp.grInfoList = NV_PTR_TO_NvP64(&gi);
395 if (rm_control(rm, rm->subdevice, NV2080_CTRL_CMD_GR_GET_INFO, &gp, sizeof gp)) return -1;
396 rm->sm_version = gi.data;
397
398 NV_VASPACE_ALLOCATION_PARAMETERS vap;
399 memset(&vap, 0, sizeof vap);
400 vap.vaBase = 0x1000;
401 vap.vaSize = 0x1fffffb000000ull;
402 vap.flags = NV_VASPACE_ALLOCATION_FLAGS_ENABLE_PAGE_FAULTING | NV_VASPACE_ALLOCATION_FLAGS_IS_EXTERNALLY_OWNED;
403 if (rm_alloc(rm, rm->device, FERMI_VASPACE_A, &vap, sizeof vap, &rm->vaspace)) return -1;
404
405 NV2080_CTRL_GPU_GET_GID_INFO_PARAMS gid;
406 memset(&gid, 0, sizeof gid);
407 gid.flags = NV2080_GPU_CMD_GPU_GET_GID_FLAGS_FORMAT_BINARY;
408 gid.length = 16;
409 if (rm_control(rm, rm->subdevice, NV2080_CTRL_CMD_GPU_GET_GID_INFO, &gid, sizeof gid)) return -1;
410 memcpy(rm->gpu_uuid, gid.data, 16);
411
412 UVM_REGISTER_GPU_PARAMS rg;
413 memset(&rg, 0, sizeof rg);
414 memcpy(rg.gpu_uuid.uuid, rm->gpu_uuid, 16);
415 rg.rmCtrlFd = -1;
416 if (uvm(rm, rm->fd_uvm, UVM_REGISTER_GPU, &rg, &rg.rmStatus)) return -1;
417 rm->gpu_registered = 1;
418 UVM_REGISTER_GPU_VASPACE_PARAMS rv;
419 memset(&rv, 0, sizeof rv);
420 memcpy(rv.gpuUuid.uuid, rm->gpu_uuid, 16);
421 rv.rmCtrlFd = rm->fd_ctl;
422 rv.hClient = rm->root;
423 rv.hVaSpace = rm->vaspace;
424 if (uvm(rm, rm->fd_uvm, UVM_REGISTER_GPU_VASPACE, &rv, &rv.rmStatus)) return -1;
425 rm->vas_registered = 1;
426 return 0;
427}
428
429/* Return a freed VA range to the sorted, coalesced free list. */
430static int va_release(Nvrm *rm, uint64_t va, uint64_t size) {
431 uint64_t end;
432 if (!size || __builtin_add_overflow(va, size, &end)) {
433 rm->faulted = 1;
434 return fail(rm, "invalid VA release extent");
435 }
436 uint32_t pos = 0;
437 while (pos < rm->free_count && rm->free_list[pos].va < va) pos++;
438 if ((pos && rm->free_list[pos - 1].va + rm->free_list[pos - 1].size > va) ||
439 (pos < rm->free_count && end > rm->free_list[pos].va)) {
440 rm->faulted = 1;
441 return fail(rm, "overlapping VA release extent");
442 }
443
444 if (rm->free_count >= NVRM_MAX_FREE) {
445 /* Free-list table full: leak this VA range (address space only --
446 * no RM object, CPU mapping, or UVM range remains associated with it). */
447 rm->faulted = 1;
448 return fail(rm, "VA free-list full; VA 0x%lx quarantined", (unsigned long)va);
449 }
450 for (uint32_t i = rm->free_count; i > pos; i--) rm->free_list[i] = rm->free_list[i - 1];
451 rm->free_list[pos].va = va;
452 rm->free_list[pos].size = size;
453 rm->free_count++;
454
455 /* Coalesce with the following entry. */
456 if (pos + 1 < rm->free_count && rm->free_list[pos].va + rm->free_list[pos].size == rm->free_list[pos + 1].va) {
457 rm->free_list[pos].size += rm->free_list[pos + 1].size;
458 for (uint32_t i = pos + 1; i + 1 < rm->free_count; i++) rm->free_list[i] = rm->free_list[i + 1];
459 rm->free_count--;
460 }
461 /* Coalesce with the preceding entry. */
462 if (pos > 0 && rm->free_list[pos - 1].va + rm->free_list[pos - 1].size == rm->free_list[pos].va) {
463 rm->free_list[pos - 1].size += rm->free_list[pos].size;
464 for (uint32_t i = pos; i + 1 < rm->free_count; i++) rm->free_list[i] = rm->free_list[i + 1];
465 rm->free_count--;
466 }
467 return 0;
468}
469
470static uint64_t va_take(Nvrm *rm, uint64_t size, uint64_t align) {
471 /* First-fit reuse from the free list (sorted ascending by va), splitting
472 * off any leading alignment pad or trailing remainder as smaller free
473 * entries. Falls back to the bump allocator when nothing fits. */
474 for (uint32_t i = 0; i < rm->free_count; i++) {
475 uint64_t base = rm->free_list[i].va;
476 uint64_t sz = rm->free_list[i].size;
477 uint64_t rounded;
478 uint64_t range_end;
479 if (__builtin_add_overflow(base, align - 1, &rounded) ||
480 __builtin_add_overflow(base, sz, &range_end)) return 0;
481 uint64_t aligned = rounded & ~(align - 1);
482 uint64_t pad = aligned - base;
483 if (pad > sz || size > sz - pad) continue;
484 uint64_t used_end;
485 if (__builtin_add_overflow(aligned, size, &used_end)) return 0;
486
487 if (pad == 0 && used_end == range_end) {
488 /* Exact fit: remove entry i. */
489 for (uint32_t j = i; j + 1 < rm->free_count; j++) rm->free_list[j] = rm->free_list[j + 1];
490 rm->free_count--;
491 } else if (pad == 0) {
492 /* Consume from the front: shrink entry i. */
493 rm->free_list[i].va = used_end;
494 rm->free_list[i].size = range_end - used_end;
495 } else {
496 /* Leading pad remains free at entry i. */
497 rm->free_list[i].size = pad;
498 if (used_end < range_end && rm->free_count < NVRM_MAX_FREE) {
499 for (uint32_t j = rm->free_count; j > i + 1; j--) rm->free_list[j] = rm->free_list[j - 1];
500 rm->free_list[i + 1].va = used_end;
501 rm->free_list[i + 1].size = range_end - used_end;
502 rm->free_count++;
503 }
504 else if (used_end < range_end) {
505 /* Preserve the range intact rather than silently losing VA. */
506 rm->free_list[i].size = sz;
507 continue;
508 }
509 }
510 return aligned;
511 }
512
513 uint64_t rounded;
514 if (__builtin_add_overflow(rm->va_next, align - 1, &rounded)) return 0;
515 uint64_t va = rounded & ~(align - 1);
516 if (__builtin_add_overflow(va, size, &rm->va_next)) return 0;
517 return va;
518}
519
520static int uvm_map(Nvrm *rm, uint64_t va, uint64_t size, uint32_t hmem,
521 uint8_t *uvm_created, uint8_t *dma_mapped) {
522 UVM_CREATE_EXTERNAL_RANGE_PARAMS cr;
523 memset(&cr, 0, sizeof cr);
524 cr.base = va;
525 cr.length = size;
526 if (uvm(rm, rm->fd_uvm, UVM_CREATE_EXTERNAL_RANGE, &cr, &cr.rmStatus)) return -1;
527 *uvm_created = 1;
528
529 NVOS46_PARAMETERS d;
530 memset(&d, 0, sizeof d);
531 d.hClient = rm->root;
532 d.hDevice = rm->device;
533 d.hDma = rm->virtmem;
534 d.hMemory = hmem;
535 d.length = size;
536 d.flags = (NVOS46_FLAGS_PAGE_SIZE_4KB << 8) | (NVOS46_FLAGS_CACHE_SNOOP_ENABLE << 4) | (NVOS46_FLAGS_DMA_OFFSET_FIXED_TRUE << 15);
537 d.dmaOffset = va;
538 if (nv_ioctl(rm->fd_ctl, NV_ESC_RM_MAP_MEMORY_DMA, &d, sizeof d) != 0 || d.status != 0)
539 return fail(rm, "RM_MAP_MEMORY_DMA errno %d status 0x%x", errno, d.status);
540 if (d.dmaOffset != va) return fail(rm, "dmaOffset mismatch");
541 *dma_mapped = 1;
542
543 static UVM_MAP_EXTERNAL_ALLOCATION_PARAMS ma;
544 memset(&ma, 0, sizeof ma);
545 ma.base = va;
546 ma.length = size;
547 ma.rmCtrlFd = rm->fd_ctl;
548 ma.hClient = rm->root;
549 ma.hMemory = hmem;
550 ma.gpuAttributesCount = 1;
551 memcpy(ma.perGpuAttributes[0].gpuUuid.uuid, rm->gpu_uuid, 16);
552 ma.perGpuAttributes[0].gpuMappingType = UvmGpuMappingTypeReadWriteAtomic;
553 return uvm(rm, rm->fd_uvm, UVM_MAP_EXTERNAL_ALLOCATION, &ma, &ma.rmStatus);
554}
555
556static void quarantine_allocation(Nvrm *rm, uint32_t h, uint64_t va, uint64_t size,
557 void *cpu, uint8_t uvm_live, uint8_t dma_live) {
558 NvrmLiveAlloc *e = &rm->live[rm->live_count++];
559 *e = (NvrmLiveAlloc){ .handle = h, .va = va, .size = size, .cpu = cpu,
560 .uvm_live = uvm_live, .dma_live = dma_live,
561 .rm_live = 1, .cpu_live = 1, .quarantined = 1 };
562 rm->faulted = 1;
563}
564
565static int alloc_with_cacheability(Nvrm *rm, uint64_t size, NvrmMem *out, uint32_t gpu_cacheable);
566
567/* Coherent, CPU-mapped, GPU-mapped buffer at one shared virtual address. */
568int nvrm_alloc(Nvrm *rm, uint64_t size, NvrmMem *out) {
569 return alloc_with_cacheability(rm, size, out, NVOS32_ATTR2_GPU_CACHEABLE_YES);
570}
571
572/* Same buffer, but the graphics chip does not keep it in its L2. The CPU
573 * mapping is already uncached, so a CPU store reaches memory; without this a
574 * resident chip program polling the buffer keeps reading its own L2 copy and
575 * never sees the store. For memory both sides poll, not for bulk data. */
576int nvrm_alloc_gpu_uncached(Nvrm *rm, uint64_t size, NvrmMem *out) {
577 return alloc_with_cacheability(rm, size, out, NVOS32_ATTR2_GPU_CACHEABLE_NO);
578}
579
580static int alloc_with_cacheability(Nvrm *rm, uint64_t size, NvrmMem *out, uint32_t gpu_cacheable) {
581 if (!rm || !out || !size || rm->faulted || size > SIZE_MAX - 0xfffULL)
582 return rm ? fail(rm, "invalid or overflowed allocation size") : -1;
583 size = (size + 0xfff) & ~0xfffull;
584 if (rm->live_count >= NVRM_MAX_LIVE) return fail(rm, "live allocation table full (%d)", NVRM_MAX_LIVE);
585 uint64_t va = va_take(rm, size, 0x1000);
586 if (!va) return fail(rm, "GPU VA exhausted or overflowed");
587 /* Reserve the CPU range first so the fixed mapping can never clobber anything. */
588 void *res = mmap((void *)va, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
589 if (res != (void *)va) {
590 if (res != MAP_FAILED) munmap(res, size);
591 rm->faulted = 1;
592 return fail(rm, "VA 0x%lx unavailable", (unsigned long)va);
593 }
594
595 NV_MEMORY_ALLOCATION_PARAMS mp;
596 memset(&mp, 0, sizeof mp);
597 mp.owner = rm->root;
598 mp.type = NVOS32_TYPE_IMAGE;
599 mp.flags = NVOS32_ALLOC_FLAGS_MAP_NOT_REQUIRED | NVOS32_ALLOC_FLAGS_MEMORY_HANDLE_PROVIDED |
600 NVOS32_ALLOC_FLAGS_ALIGNMENT_FORCE | NVOS32_ALLOC_FLAGS_IGNORE_BANK_PLACEMENT;
601 /* GB10 has no local video memory: everything is coherent system memory. */
602 mp.attr = (NVOS32_ATTR_PHYSICALITY_ALLOW_NONCONTIGUOUS << 27) | (NVOS32_ATTR_LOCATION_PCI << 25);
603 mp.attr2 = (gpu_cacheable << 2) | NVOS32_ATTR2_ZBC_PREFER_NO_ZBC;
604 mp.format = 6;
605 mp.size = size;
606 mp.alignment = 0x1000;
607 mp.limit = size - 1;
608 uint32_t h;
609 if (rm_alloc(rm, rm->device, NV01_MEMORY_SYSTEM, &mp, sizeof mp, &h)) {
610 if (munmap(res, size) != 0) rm->faulted = 1;
611 rm->faulted = 1; /* unknown driver state: do not recycle this VA */
612 return fail_alloc_context(rm, size);
613 }
614 void *cpu = map_to_cpu(rm, h, size, (void *)va, 0, 1);
615 if (cpu != (void *)va) {
616 char why[sizeof rm->err];
617 memcpy(why, rm->err, sizeof why);
618 quarantine_allocation(rm, h, va, size, (void *)va, 0, 0);
619 return fail(rm, "cpu map at 0x%lx failed: %s", (unsigned long)va, why);
620 }
621 uint8_t uvm_created = 0, dma_mapped = 0;
622 if (uvm_map(rm, va, size, h, &uvm_created, &dma_mapped)) {
623 quarantine_allocation(rm, h, va, size, cpu, uvm_created, dma_mapped);
624 return -1;
625 }
626 out->handle = h;
627 out->va = va;
628 out->size = size;
629 out->cpu = cpu;
630 memset(cpu, 0, size);
631
632 rm->live[rm->live_count].handle = h;
633 rm->live[rm->live_count].va = va;
634 rm->live[rm->live_count].size = size;
635 rm->live[rm->live_count].cpu = cpu;
636 rm->live[rm->live_count].uvm_live = 1;
637 rm->live[rm->live_count].dma_live = 1;
638 rm->live[rm->live_count].rm_live = 1;
639 rm->live[rm->live_count].cpu_live = 1;
640 rm->live_count++;
641 return 0;
642}
643
644/* Reverse of nvrm_alloc(): drop the UVM external range, free the RM memory
645 * object, unmap the CPU range, and return the VA range to the free list. */
646int nvrm_free(Nvrm *rm, NvrmMem *m) {
647 if (!rm || !m) return -1;
648
649 /* Idempotent: freeing an already-zeroed NvrmMem is a silent no-op. */
650 if (m->handle == 0 && m->va == 0 && m->size == 0 && m->cpu == NULL) return 0;
651
652 /* Reject anything that is not a currently-live allocation (e.g. a stale
653 * copy of an NvrmMem that was already freed elsewhere) without touching
654 * the driver at all. */
655 int idx = -1;
656 for (uint32_t i = 0; i < rm->live_count; i++) {
657 if (rm->live[i].va == m->va && rm->live[i].handle == m->handle && rm->live[i].size == m->size) {
658 if (idx >= 0) { rm->faulted = 1; return fail(rm, "duplicate live allocation table entry"); }
659 idx = (int)i;
660 }
661 }
662 if (idx < 0)
663 return fail(rm, "nvrm_free: va 0x%lx handle 0x%x size 0x%lx is not a live allocation",
664 (unsigned long)m->va, m->handle, (unsigned long)m->size);
665
666 NvrmLiveAlloc *live = &rm->live[idx];
667 if (live->cpu != m->cpu || !m->cpu || !m->size ||
668 (m->va & 0xfff) || (m->size & 0xfff)) {
669 rm->faulted = 1;
670 return fail(rm, "nvrm_free: allocation table identity corrupt");
671 }
672 /* Every completed step is irreversible. Preserve the stage flags if the
673 * next step fails, and quarantine the VA until all releases are proven. */
674 if (live->uvm_live) {
675 if (uvm_free_checked(rm, m->va, m->size) != 0) {
676 live->quarantined = 1;
677 rm->faulted = 1;
678 return -1;
679 }
680 live->uvm_live = 0;
681 }
682 if (live->dma_live) {
683 if (dma_unmap_checked(rm, m->handle, m->va, m->size) != 0) {
684 live->quarantined = 1;
685 rm->faulted = 1;
686 return -1;
687 }
688 live->dma_live = 0;
689 }
690 if (live->rm_live) {
691 if (rm_free(rm, rm->device, m->handle) != 0) {
692 live->quarantined = 1;
693 rm->faulted = 1;
694 return -1;
695 }
696 live->rm_live = 0;
697 }
698 if (live->cpu_live) {
699 if (munmap(m->cpu, m->size) != 0) {
700 live->quarantined = 1;
701 rm->faulted = 1;
702 return fail(rm, "munmap VA 0x%lx errno %d", (unsigned long)m->va, errno);
703 }
704 live->cpu_live = 0;
705 }
706
707 /* Remove from the live table (swap with last). */
708 rm->live[idx] = rm->live[rm->live_count - 1];
709 rm->live_count--;
710
711 if (va_release(rm, m->va, m->size) != 0) return -1;
712
713 memset(m, 0, sizeof *m);
714 return 0;
715}
716
717/* One more GPFIFO channel in rm->chgroup on its own asynchronous subcontext: the same steps as channel 0 below (ring + USERD
718 * GPU-uncached, notifier, GPFIFO, compute object, work-submit token, UVM_REGISTER_CHANNEL). */
719static int chan_extra(Nvrm *rm, NvrmChan *c) {
720 /* NVIDIA nvos.h:3195-3243, FERMI_CONTEXT_SHARE_A represents a subcontext.
721 * Reusing channel 0's context share serialized the C4 event control on GB10;
722 * a separate ASYNC allocation lets the independent queue run before its peer.
723 * n_extra is counted before this call, so partial construction is unwound too. */
724 NV_CTXSHARE_ALLOCATION_PARAMETERS cs;
725 memset(&cs, 0, sizeof cs);
726 cs.hVASpace = rm->vaspace;
727 cs.flags = NV_CTXSHARE_ALLOCATION_FLAGS_SUBCONTEXT_ASYNC;
728 if (rm_alloc(rm, rm->chgroup, FERMI_CONTEXT_SHARE_A, &cs, sizeof cs, &c->ctxshare)) return -1;
729 c->entries = 1024;
730 if (nvrm_alloc_gpu_uncached(rm, 0x10000, &c->fifo)) return -1;
731 if (nvrm_alloc(rm, 0x100000, &c->notifier)) return -1;
732 NV_CHANNEL_ALLOC_PARAMS gp;
733 memset(&gp, 0, sizeof gp);
734 gp.gpFifoOffset = c->fifo.va;
735 gp.gpFifoEntries = c->entries;
736 gp.hObjectError = c->notifier.handle;
737 gp.hObjectBuffer = c->fifo.handle;
738 gp.hUserdMemory[0] = c->fifo.handle;
739 c->userd_off = c->entries * 8;
740 gp.userdOffset[0] = c->userd_off;
741 gp.engineType = 0;
742 gp.hContextShare = c->ctxshare;
743 if (rm_alloc(rm, rm->chgroup, rm->gpfifo_class, &gp, sizeof gp, &c->gpfifo)) return -1;
744 if (rm_alloc(rm, c->gpfifo, rm->compute_class, NULL, 0, &c->compute_obj)) return -1;
745 NVC36F_CTRL_CMD_GPFIFO_GET_WORK_SUBMIT_TOKEN_PARAMS tk = { .workSubmitToken = 0xffffffffu };
746 if (rm_control(rm, c->gpfifo, NVC36F_CTRL_CMD_GPFIFO_GET_WORK_SUBMIT_TOKEN, &tk, sizeof tk)) return -1;
747 c->token = tk.workSubmitToken;
748 UVM_REGISTER_CHANNEL_PARAMS rc;
749 memset(&rc, 0, sizeof rc);
750 memcpy(rc.gpuUuid.uuid, rm->gpu_uuid, 16);
751 rc.rmCtrlFd = rm->fd_ctl;
752 rc.hClient = rm->root;
753 rc.hChannel = c->gpfifo;
754 rc.base = va_take(rm, 0x4000000, 0x1000);
755 if (!rc.base) { rm->faulted = 1; return fail(rm, "channel VA exhausted (extra channel)"); }
756 rc.length = 0x4000000;
757 c->channel_va = rc.base;
758 c->channel_va_size = rc.length;
759 if (uvm(rm, rm->fd_uvm, UVM_REGISTER_CHANNEL, &rc, &rc.rmStatus)) {
760 rm->faulted = 1;
761 return -1;
762 }
763 c->registered = 1;
764 c->put = c->retired = 0;
765 return 0;
766}
767
768static int chan_extra_destroy(Nvrm *rm, NvrmChan *c) {
769 if (c->registered) {
770 UVM_UNREGISTER_CHANNEL_PARAMS p;
771 memset(&p, 0, sizeof p);
772 memcpy(p.gpuUuid.uuid, rm->gpu_uuid, sizeof rm->gpu_uuid);
773 p.hClient = rm->root;
774 p.hChannel = c->gpfifo;
775 if (uvm(rm, rm->fd_uvm, UVM_UNREGISTER_CHANNEL, &p, &p.rmStatus)) return -1;
776 c->registered = 0;
777 }
778 if (c->compute_obj && rm_free(rm, c->gpfifo, c->compute_obj)) return -1;
779 c->compute_obj = 0;
780 if (c->gpfifo && rm_free(rm, rm->chgroup, c->gpfifo)) return -1;
781 c->gpfifo = 0;
782 if (c->ctxshare && rm_free(rm, rm->chgroup, c->ctxshare)) return -1;
783 c->ctxshare = 0;
784 if (c->fifo.handle && nvrm_free(rm, &c->fifo)) return -1;
785 if (c->notifier.handle && nvrm_free(rm, &c->notifier)) return -1;
786 if (c->channel_va_size) {
787 if (va_release(rm, c->channel_va, c->channel_va_size) != 0) return -1;
788 c->channel_va = 0;
789 c->channel_va_size = 0;
790 }
791 c->put = c->retired = 0;
792 return 0;
793}
794
795int nvrm_channel(Nvrm *rm) { return nvrm_channel_n(rm, 0); }
796
797int nvrm_channel_n(Nvrm *rm, uint32_t extra) {
798 if (!rm || rm->faulted || rm->chgroup || rm->channel_registered || rm->n_extra)
799 return rm ? fail(rm, "channel construction requires clean state") : -1;
800 if (extra > NVRM_MAX_EXTRA_CHANNELS) return fail(rm, "extra channels %u > %d", extra, NVRM_MAX_EXTRA_CHANNELS);
801 NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS cg;
802 memset(&cg, 0, sizeof cg);
803 cg.engineType = NV2080_ENGINE_TYPE_GRAPHICS;
804 if (rm_alloc(rm, rm->device, KEPLER_CHANNEL_GROUP_A, &cg, sizeof cg, &rm->chgroup)) return -1;
805 NV_CTXSHARE_ALLOCATION_PARAMETERS cs;
806 memset(&cs, 0, sizeof cs);
807 cs.hVASpace = rm->vaspace;
808 cs.flags = NV_CTXSHARE_ALLOCATION_FLAGS_SUBCONTEXT_ASYNC;
809 if (rm_alloc(rm, rm->chgroup, FERMI_CONTEXT_SHARE_A, &cs, sizeof cs, &rm->ctxshare)) return -1;
810
811 rm->entries = 1024;
812 /* CPU publishes new queue entries and USERD GPPut after each completion.
813 * A GPU-cached allocation can retain their previous contents on GB10;
814 * CPU store barriers alone do not invalidate that cached copy. */
815 if (nvrm_alloc_gpu_uncached(rm, 0x10000, &rm->fifo)) return -1;
816 if (nvrm_alloc(rm, 0x100000, &rm->notifier)) return -1;
817
818 NV_CHANNEL_ALLOC_PARAMS gp;
819 memset(&gp, 0, sizeof gp);
820 gp.gpFifoOffset = rm->fifo.va;
821 gp.gpFifoEntries = rm->entries;
822 gp.hObjectError = rm->notifier.handle;
823 gp.hObjectBuffer = rm->fifo.handle;
824 gp.hUserdMemory[0] = rm->fifo.handle;
825 rm->userd_off = rm->entries * 8; /* USERD follows the ring in the same allocation */
826 gp.userdOffset[0] = rm->userd_off;
827 gp.engineType = 0;
828 gp.hContextShare = rm->ctxshare;
829 if (rm_alloc(rm, rm->chgroup, rm->gpfifo_class, &gp, sizeof gp, &rm->gpfifo)) return -1;
830 /* NV_ERR_NO_MEMORY here is the host lacking one free 2 MiB block for the
831 * channel's main context buffer at this instant (see nvrm.h, omega#523).
832 * Retry that one RM_ALLOC, bounded; any other status is final at once. */
833 uint32_t delay_ms = rm->channel_no_memory_retry_ms ? rm->channel_no_memory_retry_ms
834 : NVRM_CHANNEL_NO_MEMORY_RETRY_MS;
835 const uint32_t budget = NVRM_CHANNEL_NO_MEMORY_RETRIES;
836 rm->channel_no_memory_retries = 0;
837 for (;;) {
838 if (rm_alloc(rm, rm->gpfifo, rm->compute_class, NULL, 0, &rm->compute_obj) == 0) break;
839 if (rm->last_rm_status != NV_ERR_NO_MEMORY) return -1;
840 if (rm->channel_no_memory_retries >= budget)
841 return fail_channel_no_memory(rm, rm->channel_no_memory_retries + 1, delay_ms);
842 rm->channel_no_memory_retries++;
843 usleep((useconds_t)delay_ms * 1000u);
844 }
845
846 NVC36F_CTRL_CMD_GPFIFO_GET_WORK_SUBMIT_TOKEN_PARAMS tk = { .workSubmitToken = 0xffffffffu };
847 if (rm_control(rm, rm->gpfifo, NVC36F_CTRL_CMD_GPFIFO_GET_WORK_SUBMIT_TOKEN, &tk, sizeof tk)) return -1;
848 rm->token = tk.workSubmitToken;
849
850 /* The VA space is UVM-owned: UVM must bind the channel's context buffers before RM will schedule it. */
851 UVM_REGISTER_CHANNEL_PARAMS rc;
852 memset(&rc, 0, sizeof rc);
853 memcpy(rc.gpuUuid.uuid, rm->gpu_uuid, 16);
854 rc.rmCtrlFd = rm->fd_ctl;
855 rc.hClient = rm->root;
856 rc.hChannel = rm->gpfifo;
857 rc.base = va_take(rm, 0x4000000, 0x1000);
858 if (!rc.base) { rm->faulted = 1; return fail(rm, "channel VA exhausted"); }
859 rc.length = 0x4000000;
860 rm->channel_va = rc.base;
861 rm->channel_va_size = rc.length;
862 if (uvm(rm, rm->fd_uvm, UVM_REGISTER_CHANNEL, &rc, &rc.rmStatus)) {
863 rm->faulted = 1;
864 return -1;
865 }
866 rm->channel_registered = 1;
867
868 for (uint32_t i = 0; i < extra; i++) {
869 rm->n_extra = i + 1; /* counted first: destroy undoes a half-built channel */
870 if (chan_extra(rm, &rm->extra[i])) return -1;
871 }
872
873 NVA06C_CTRL_GPFIFO_SCHEDULE_PARAMS sch = { .bEnable = 1 };
874 if (rm_control(rm, rm->chgroup, NVA06C_CTRL_CMD_GPFIFO_SCHEDULE, &sch, sizeof sch)) return -1;
875 rm->put = 0;
876 rm->retired = 0;
877 return 0;
878}
879
880int nvrm_channel_destroy(Nvrm *rm) {
881 if (!rm) return -1;
882 while (rm->n_extra) {
883 if (chan_extra_destroy(rm, &rm->extra[rm->n_extra - 1])) { rm->faulted = 1; return -1; }
884 rm->n_extra--;
885 }
886 if (rm->channel_registered) {
887 UVM_UNREGISTER_CHANNEL_PARAMS p;
888 memset(&p, 0, sizeof p);
889 memcpy(p.gpuUuid.uuid, rm->gpu_uuid, sizeof rm->gpu_uuid);
890 p.hClient = rm->root;
891 p.hChannel = rm->gpfifo;
892 if (uvm(rm, rm->fd_uvm, UVM_UNREGISTER_CHANNEL, &p, &p.rmStatus)) {
893 rm->faulted = 1;
894 return -1;
895 }
896 rm->channel_registered = 0;
897 }
898 if (rm->compute_obj && rm_free(rm, rm->gpfifo, rm->compute_obj)) goto failed;
899 rm->compute_obj = 0;
900 if (rm->gpfifo && rm_free(rm, rm->chgroup, rm->gpfifo)) goto failed;
901 rm->gpfifo = 0;
902 if (rm->ctxshare && rm_free(rm, rm->chgroup, rm->ctxshare)) goto failed;
903 rm->ctxshare = 0;
904 if (rm->chgroup && rm_free(rm, rm->device, rm->chgroup)) goto failed;
905 rm->chgroup = 0;
906 if (rm->fifo.handle && nvrm_free(rm, &rm->fifo)) goto failed;
907 if (rm->notifier.handle && nvrm_free(rm, &rm->notifier)) goto failed;
908 if (rm->channel_va_size) {
909 if (va_release(rm, rm->channel_va, rm->channel_va_size) != 0) goto failed;
910 rm->channel_va = 0;
911 rm->channel_va_size = 0;
912 }
913 rm->put = rm->retired = 0;
914 return 0;
915failed:
916 rm->faulted = 1;
917 return -1;
918}
919
920/* GP entry per clc96f.h: ENTRY0 GET 31:2 (VA low, dword aligned), ENTRY1 GET_HI 7:0,
921 * LEVEL 9:9, LENGTH 30:10 in dwords, SYNC 31:31 = PROCEED. The code below ORs (1ull << 41),
922 * which is ENTRY1 bit 9 = LEVEL, so it sets LEVEL = SUBROUTINE (1), not MAIN (0)
923 * (clc96f.h NVC96F_GP_ENTRY1_LEVEL_MAIN 0x0, _SUBROUTINE 0x1). This encoding is chip-proven
924 * and must not change; whether MAIN was intended is UNKNOWN and needs a chip run to decide. */
925uint64_t nvrm_gp_entry(uint64_t va, uint32_t nwords) {
926 return (va & ~3ull) | ((uint64_t)(nwords & 0x1fffff) << 42) | (1ull << 41);
927}
928
929volatile uint32_t *nvrm_userd_gpput(Nvrm *rm) {
930 return (volatile uint32_t *)((uint8_t *)rm->fifo.cpu + rm->userd_off + offsetof(Nvc96fControl, GPPut));
931}
932
933int nvrm_enqueue(Nvrm *rm, const NvrmMem *pb, uint32_t off, uint32_t nwords) {
934 if (!rm || !pb || rm->faulted || !rm->gpfifo || !rm->fifo.cpu || rm->entries < 2)
935 return rm ? fail(rm, "channel not ready") : -1;
936 if ((off & 3u) || nwords == 0 || nwords > 0x1fffff || (uint64_t)off + (uint64_t)nwords * 4u > pb->size)
937 return fail(rm, "bad pushbuffer span");
938 if (pb->va > UINT64_MAX - off) return fail(rm, "pushbuffer VA overflow");
939 /* Blackwell USERD documents no GPGet (clc96f.h), so consumption is tracked by the
940 * caller via nvrm_retire() after it observes completion. Never overrun unretired entries. */
941 if (rm->put - rm->retired >= rm->entries - 1) return fail(rm, "GPFIFO full: %u entries unretired", rm->put - rm->retired);
942 volatile uint64_t *ring = (volatile uint64_t *)rm->fifo.cpu;
943 ring[rm->put % rm->entries] = nvrm_gp_entry(pb->va + off, nwords);
944 rm->put++;
945 __asm__ volatile("dsb sy" ::: "memory");
946 *nvrm_userd_gpput(rm) = rm->put % rm->entries;
947 __asm__ volatile("dsb sy" ::: "memory");
948 return 0;
949}
950
951void nvrm_retire(Nvrm *rm, uint32_t upto) {
952 if (upto - rm->retired <= rm->put - rm->retired) rm->retired = upto;
953}
954
955void nvrm_ring(Nvrm *rm) {
956 *rm->doorbell = rm->token; /* NVC361_NOTIFY_CHANNEL_PENDING */
957}
958
959int nvrm_submit(Nvrm *rm, const NvrmMem *pb, uint32_t off, uint32_t nwords) {
960 if (nvrm_enqueue(rm, pb, off, nwords)) return -1;
961 nvrm_ring(rm);
962 return 0;
963}
964
965/* nvrm_enqueue + nvrm_ring for an extra channel: the same GP entry, barriers and USERD GPPut, its own ring and token. */
966int nvrm_chan_submit(Nvrm *rm, uint32_t ch, const NvrmMem *pb, uint32_t off, uint32_t nwords) {
967 if (!rm || !pb || rm->faulted || ch == 0 || ch > rm->n_extra) return rm ? fail(rm, "extra channel %u not ready", ch) : -1;
968 NvrmChan *c = &rm->extra[ch - 1];
969 if (!c->gpfifo || !c->fifo.cpu || c->entries < 2) return fail(rm, "extra channel %u not ready", ch);
970 if ((off & 3u) || nwords == 0 || nwords > 0x1fffff || (uint64_t)off + (uint64_t)nwords * 4u > pb->size)
971 return fail(rm, "bad pushbuffer span");
972 if (pb->va > UINT64_MAX - off) return fail(rm, "pushbuffer VA overflow");
973 if (c->put - c->retired >= c->entries - 1) return fail(rm, "GPFIFO full (channel %u): %u entries unretired", ch, c->put - c->retired);
974 volatile uint64_t *ring = (volatile uint64_t *)c->fifo.cpu;
975 ring[c->put % c->entries] = nvrm_gp_entry(pb->va + off, nwords);
976 c->put++;
977 __asm__ volatile("dsb sy" ::: "memory");
978 *(volatile uint32_t *)((uint8_t *)c->fifo.cpu + c->userd_off + offsetof(Nvc96fControl, GPPut)) = c->put % c->entries;
979 __asm__ volatile("dsb sy" ::: "memory");
980 *rm->doorbell = c->token; /* NVC361_NOTIFY_CHANNEL_PENDING: one doorbell page, the token names the channel */
981 return 0;
982}
983
984void nvrm_chan_retire(Nvrm *rm, uint32_t ch, uint32_t upto) {
985 if (!rm || ch == 0 || ch > rm->n_extra) return;
986 NvrmChan *c = &rm->extra[ch - 1];
987 if (upto - c->retired <= c->put - c->retired) c->retired = upto;
988}
989
990uint32_t nvrm_chan_put(const Nvrm *rm, uint32_t ch) {
991 if (!rm) return 0;
992 if (ch == 0) return rm->put;
993 return ch <= rm->n_extra ? rm->extra[ch - 1].put : 0;
994}
995
996int nvrm_close(Nvrm *rm) {
997 if (!rm) return -1;
998 if (rm->root && nvrm_channel_destroy(rm)) rm->faulted = 1;
999 /* Release every remaining allocation, including caller-owned buffers and
1000 * allocations left behind by an interrupted construction path. */
1001 for (uint32_t i = rm->live_count; i > 0;) {
1002 NvrmLiveAlloc e = rm->live[--i];
1003 NvrmMem m = { .handle = e.handle, .va = e.va, .size = e.size, .cpu = e.cpu };
1004 if (nvrm_free(rm, &m) != 0) {
1005 rm->faulted = 1;
1006 /* Closing the client tears down driver state. The CPU mapping is
1007 * process state, so explicitly unmap it even on teardown error. */
1008 if (e.cpu_live && e.cpu) (void)munmap(e.cpu, e.size);
1009 } else if (i < rm->live_count) i++;
1010 }
1011 if (rm->usermode_cpu) {
1012 if (munmap(rm->usermode_cpu, 0x10000) != 0) rm->faulted = 1;
1013 rm->usermode_cpu = NULL;
1014 rm->doorbell = NULL;
1015 }
1016 if (rm->vas_registered) {
1017 UVM_UNREGISTER_GPU_VASPACE_PARAMS p;
1018 memset(&p, 0, sizeof p);
1019 memcpy(p.gpuUuid.uuid, rm->gpu_uuid, sizeof rm->gpu_uuid);
1020 if (uvm(rm, rm->fd_uvm, UVM_UNREGISTER_GPU_VASPACE, &p, &p.rmStatus)) rm->faulted = 1;
1021 rm->vas_registered = 0;
1022 }
1023 if (rm->gpu_registered) {
1024 UVM_UNREGISTER_GPU_PARAMS p;
1025 memset(&p, 0, sizeof p);
1026 memcpy(p.gpu_uuid.uuid, rm->gpu_uuid, sizeof rm->gpu_uuid);
1027 if (uvm(rm, rm->fd_uvm, UVM_UNREGISTER_GPU, &p, &p.rmStatus)) rm->faulted = 1;
1028 rm->gpu_registered = 0;
1029 }
1030 /* Free root children explicitly so a clean close proves every RM object
1031 * was accepted for release; parent teardown alone hides leaked handles. */
1032 if (rm->usermode && rm_free(rm, rm->subdevice, rm->usermode)) rm->faulted = 1;
1033 rm->usermode = 0;
1034 if (rm->vaspace && rm_free(rm, rm->device, rm->vaspace)) rm->faulted = 1;
1035 rm->vaspace = 0;
1036 if (rm->virtmem && rm_free(rm, rm->device, rm->virtmem)) rm->faulted = 1;
1037 rm->virtmem = 0;
1038 if (rm->subdevice && rm_free(rm, rm->device, rm->subdevice)) rm->faulted = 1;
1039 rm->subdevice = 0;
1040 if (rm->device && rm_free(rm, rm->root, rm->device)) rm->faulted = 1;
1041 rm->device = 0;
1042 if (rm->root && rm_free(rm, rm->root, rm->root)) rm->faulted = 1;
1043 rm->root = 0;
1044 if (rm->fd_dev > 0) close(rm->fd_dev);
1045 if (rm->fd_uvm2 > 0) close(rm->fd_uvm2);
1046 if (rm->fd_uvm > 0) close(rm->fd_uvm);
1047 if (rm->fd_ctl > 0) close(rm->fd_ctl);
1048 if (!rm->faulted && rm->live_count == 0 && !rm->channel_registered &&
1049 rm->va_slot_base && rm->va_next >= rm->va_slot_base &&
1050 rm->va_next - rm->va_slot_base <= 0x100000000ull)
1051 recycle_va_slot(rm->va_slot_base);
1052 rm->va_slot_base = 0;
1053 return rm->faulted ? -1 : 0;
1054}