interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / src / omega_gpu_session.h

303 lines · 18704 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef OMEGA_GPU_SESSION_H
18#define OMEGA_GPU_SESSION_H
19/*
20 * omega_gpu_session: the ONE persistent device for the native GPU APIs
21 * (FB-1 cut 4b, 2026-10-04). Shared by omega_gpu_matmul_api,
22 * omega_gpu_elementwise_api and omega_gpu_attention_api.
23 *
24 * Before this cut the matmul API kept its own device open for the process while
25 * the elementwise and attention APIs opened a client, device, VA space and
26 * channel for EVERY call and closed them again (~40 ms per call against ~0.1 ms
27 * of chip time; TinyLlama decode makes ~3500 elementwise calls per 32 tokens,
28 * sovereign-core cut 3c: 0.207 tok/s). Now:
29 * - one RM client / device / channel per process, opened on the first launch of
30 * any API and kept until omega_gpu_session_close();
31 * - one pushbuffer, constant bank, marker page and QMD page, reused per launch;
32 * - staging buffers owned by the callers grow to a high-water mark and are reused
33 * (omega_gpu_session_scratch);
34 * - every buffer is GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE, read
35 * 2026-10-04: "For system memory this will not be coherent with direct CPU
36 * mappings"; the default for system memory is uncached), because the host
37 * writes inputs the chip then reads, and polls the markers the chip writes;
38 * - every launch keeps the chip-proven sequence: shader-cache invalidate
39 * (clcec0.h NVCEC0_INVALIDATE_SHADER_CACHES, cut 1b finding), constant bank
40 * upload, QMD0 / QMD1, first marker, L2_FLUSH_DIRTY, second marker on the
41 * uncached page (C3 tail, omega#225/#230), GPFIFO retire after completion.
42 * - an uncertain completion (marker wait timed out) latches the process: nothing
43 * is freed or closed (the chip may still be running) and every later launch
44 * of every API is refused, as the engine does (omega_gpu_engine.h).
45 *
46 * Threading: one process-wide mutex. A caller takes omega_gpu_session_lock(),
47 * does its whole call (kernel lookup, staging, launches, readback) and unlocks.
48 * Calls from several threads therefore serialise on the device; that is the
49 * documented model (one channel, one GPFIFO).
50 *
51 * Diagnostics (cut 4b flake investigation): every failure names its stage
52 * (omega_gpu_session_last_error) and an open failure carries the driver text
53 * (Nvrm.err: RM class, ioctl errno, RM status) so a first-call failure is never
54 * reported as a bare CHIP_FAIL again.
55 *
56 * Portability (native v1 P07 cut C, session part; aienos#286, docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md):
57 * this file and omega_gpu_session.c no longer name a Linux driver type or call one. Everything the session
58 * needs from the machine goes through the installed OmegaGpuPlatform (src/omega_gpu_platform.h, ABI 1.1,
59 * service set OMEGA_GPU_SVC_REQUIRED_SESSION): device open/close, typed DMA buffers with explicit rights,
60 * kind and GPU-uncached policy, the submission queue, POLLING completion (poll_word; the session never
61 * claims or waits on an interrupt), explicit CPU<->GPU sync, the nanosecond clock, the session lock and
62 * CPU-only host memory. omega_gpu_session_set_platform installs one; the hosted build installs the Linux
63 * reference (src/omega_gpu_platform_linux.c, reference only) on first use when none was installed; the
64 * freestanding build (OMEGA_GPU_NO_POSIX) has no default and refuses until a platform is installed.
65 * Buffers are OmegaGpuMem: a typed handle (index + generation) plus the CPU view and the GPU VA as two
66 * distinct fields; no bus or physical address reaches the APIs. A handle from a closed device is stale and
67 * every use of it is refused.
68 *
69 * Uncertain completion parks, it never releases: after a marker poll timed out or a launch was cancelled
70 * after submit, the device may still be reading or writing any session buffer, so every buffer the session
71 * or an API frees from then on is PARKED (kept allocated, counted in omega_gpu_session_parked) and never
72 * returned to the platform; close and reopen are refused; the latch holds for the life of the process.
73 */
74#include <stdbool.h>
75#include <stddef.h>
76#include <stdint.h>
77#include "omega_gpu_platform.h"
78
79#ifdef __cplusplus
80extern "C" {
81#endif
82
83/* A device buffer: typed handle, kind, CPU view (cpu, size bytes) and GPU VA (va). cpu NULL = none. */
84typedef struct {
85 OmegaGpuBufferHandle handle;
86 uint32_t kind; /* OMEGA_GPU_HANDLE_BUF_DATA, _BUF_CODE or _BUF_QUEUE */
87 void *cpu; /* CPU view (OmegaCpuView.ptr) */
88 uint64_t va; /* GPU virtual address (OmegaGpuVa.va) */
89 uint64_t size; /* bytes of both views */
90} OmegaGpuMem;
91
92typedef struct {
93 OmegaGpuDeviceHandle dev;
94 OmegaGpuQueueHandle queue;
95 OmegaGpuMem pb, cbank, marker, qmd; /* per-launch scratch, owned by the session (pb is the queue ring) */
96 uint32_t opens; /* device opens in this process */
97 uint64_t last_open_ns; /* wall time of the last successful open */
98} OmegaGpuSession;
99
100/* A caller-owned staging buffer that grows to its high-water mark. */
101typedef struct {
102 OmegaGpuMem mem;
103 size_t cap; /* usable bytes */
104 size_t high_water; /* largest request so far */
105 bool reserved; /* serving reservation active: a request past cap is refused, never allocated (omega_gpu_session_scratch_reserve) */
106} OmegaGpuScratch;
107
108/* One launch: a kernel already resident at code_va, the argument words for
109 * constant bank 0 at 0x380 (buffer addresses then parameters), the grid. */
110typedef struct {
111 uint64_t code_va;
112 uint32_t gpr_count; /* registers the QMD declares (multiple of 8, >= 64 in practice) */
113 uint32_t threads_x, threads_y;
114 uint32_t grid_x, grid_y;
115 size_t num_elements; /* QMD config num_elements (kept per API for identical words) */
116 const uint32_t *args; /* n_args words written at cbank + 0x380 */
117 uint32_t n_args; /* <= OMEGA_GPU_SESSION_MAX_ARGS */
118 uint64_t timeout_ms; /* marker poll; past it the completion is uncertain and the process latches */
119 uint32_t shared_bytes; /* shared memory per CTA; 0 = the QMD default (1024) */
120 uint32_t spin_us; /* poll the marker without sleeping for up to this long, then the platform's
121 poll_word (Linux reference: 50 us sleep-poll) until timeout_ms; 0 = the process-wide setting
122 (omega_gpu_session_set_spin_us) */
123} OmegaGpuLaunch;
124#define OMEGA_GPU_SESSION_MAX_SPIN_US 1000000u
125#define OMEGA_GPU_SESSION_MAX_ARGS 32u
126/* poll_word is called in slices of at most this many ms so a cancel request is seen within one slice */
127#define OMEGA_GPU_SESSION_POLL_SLICE_MS 1u
128
129/* ---- platform (ABI 1.2) ---- */
130
131/* Installs the platform the session runs on. Negotiates caps against OMEGA_GPU_SVC_REQUIRED_SESSION and checks the
132 * table (omega_gpu_platform_check_for). OMEGA_GPU_PLAT_OK, or the refusal; REFUSED_BUSY while the device is open,
133 * the lock is held or the process is latched. NULL p uninstalls (refused the same way). Install once, at start. */
134int omega_gpu_session_set_platform(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps);
135/* The installed platform (the hosted build installs the Linux reference here when none was installed); NULL in the
136 * freestanding build until omega_gpu_session_set_platform. */
137const OmegaGpuPlatform *omega_gpu_session_platform(void);
138/* The installed platform's caps.submit_prefix_words: words queue_submit may put ahead of the caller's in the ring, so a
139 * caller that fills the ring budgets ring words minus this (omega #457 L2 invalidate prefix). 0 with no platform. */
140uint32_t omega_gpu_session_submit_prefix_words(void);
141
142/* Completion is observed by polling a GPU-uncached word; the session never claims interrupt support. */
143typedef enum { OMEGA_GPU_COMPLETION_POLLING = 1 } OmegaGpuCompletionMode;
144OmegaGpuCompletionMode omega_gpu_session_completion_mode(void);
145
146/* Platform clock in ns (CLOCK_NS); 0 without a platform. */
147uint64_t omega_gpu_session_now_ns(void);
148
149/* CPU-only memory for API tables and staging, from the platform HOST_MEM service (Linux reference: malloc/free).
150 * NULL without a platform or on refusal; 0 bytes gives a unique 1-byte block (malloc(0) behaviour); calloc also
151 * refuses n * size overflow. free(NULL) is a no-op. */
152void *omega_gpu_host_alloc(size_t bytes);
153void *omega_gpu_host_calloc(size_t n, size_t size);
154void omega_gpu_host_free(void *p);
155
156/* ---- lock, open, state ---- */
157
158/* Take the session lock (platform LOCK service, lock id OMEGA_GPU_SESSION_LOCK_ID). Does not touch the device.
159 * Without a platform it is a no-op and the open that follows refuses. */
160#define OMEGA_GPU_SESSION_LOCK_ID 0u
161void omega_gpu_session_lock(void);
162void omega_gpu_session_unlock(void);
163
164/* Caller holds the lock. Opens the device on first use. NULL when the process is
165 * latched, no platform is installed or the open failed (stage in omega_gpu_session_last_error). */
166OmegaGpuSession *omega_gpu_session_open(void);
167bool omega_gpu_session_is_open(void);
168
169/* 1 once an uncertain completion has latched this process. */
170int omega_gpu_session_is_blocked(void);
171
172/* Process-wide marker-poll spin window, used by every launch whose own spin_us is 0
173 * (the matmul, elementwise and attention APIs leave it 0). 0 (the default) keeps the
174 * poll_word sleep-poll (Linux reference: 50 us, which Linux timer slack rounds to about 102 us
175 * per launch on GB10, omega#328). 0 on success, -1 above OMEGA_GPU_SESSION_MAX_SPIN_US (setting unchanged). */
176int omega_gpu_session_set_spin_us(uint32_t us);
177uint32_t omega_gpu_session_spin_us(void);
178
179/* ---- buffers ---- */
180
181/* Caller holds the lock, device open. GPU-uncached DATA buffer (CPU and GPU read/write), page rounded. */
182int omega_gpu_session_alloc(size_t bytes, OmegaGpuMem *out);
183/* Caller holds the lock, device open. A CODE buffer (CPU writes, GPU executes, GPU never writes) for code_size
184 * bytes with the 2 KB instruction prefetch tail (omega_gpu_code_alloc.h), the tail zero-filled; the caller writes
185 * the code to out->cpu. */
186int omega_gpu_session_alloc_code(size_t code_size, OmegaGpuMem *out);
187/* Releases m to the platform and zeroes *m. Latched: m is PARKED instead (never released). A handle from a closed
188 * device (stale) or a closed session is refused: nothing is released, the refusal is counted
189 * (OmegaGpuAllocStats.stale_refusals) and *m is zeroed. */
190void omega_gpu_session_free(OmegaGpuMem *m);
191
192/* Explicit visibility of a whole buffer (platform SYNC): CPU writes before the device reads them, device writes
193 * before the CPU reads them (Linux reference: dsb sy, the barrier the APIs issued themselves before cut C).
194 * 0 also for a buffer with no CPU view (nothing to sync); -1 with the stage named when refused or no device. */
195int omega_gpu_session_sync_to_gpu(const OmegaGpuMem *m);
196int omega_gpu_session_sync_to_cpu(const OmegaGpuMem *m);
197
198/* Caller holds the lock, device open. Makes s->mem at least `bytes` long
199 * (reallocated when it grows; contents are not kept). */
200int omega_gpu_session_scratch(OmegaGpuScratch *s, size_t bytes);
201/* Caller holds the lock, device open. Allocates s->mem for `bytes` now and marks it reserved: from then on
202 * omega_gpu_session_scratch(s, n) with n <= the reserved capacity never touches the driver, and with n past it
203 * returns OMEGA_GPU_SESSION_SCRATCH_RESERVED (-2) with a clear error and no allocation. 0 on success, -1 on
204 * allocation failure (not reserved then). Cleared by omega_gpu_session_scratch_free (device close) or _unreserve. */
205#define OMEGA_GPU_SESSION_SCRATCH_RESERVED (-2)
206int omega_gpu_session_scratch_reserve(OmegaGpuScratch *s, size_t bytes);
207void omega_gpu_session_scratch_unreserve(OmegaGpuScratch *s);
208void omega_gpu_session_scratch_free(OmegaGpuScratch *s);
209
210/* ---- launch, cancel ---- */
211
212/* Caller holds the lock, device open, not latched. Submits one launch and polls
213 * for both markers. 0 on success; -1 with the stage named on failure. A marker
214 * timeout latches the process (uncertain completion). elapsed_ns (submit to second
215 * marker) and the observed first marker word are added / stored when the pointers are given.
216 * OMEGA_GPU_SESSION_CANCELLED: a cancel request was seen. Before submit nothing was submitted and the
217 * session stays usable; after submit the completion is uncertain and the process latches. */
218#define OMEGA_GPU_SESSION_CANCELLED (-3)
219int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out);
220
221/* Asks the launch in progress (or the next one) to stop. Any thread, no lock. Polling cannot stop the device: a
222 * launch already submitted is not cancelled on the chip, its completion becomes uncertain (latch + park). The
223 * request is consumed by the launch that sees it. */
224void omega_gpu_session_cancel(void);
225
226/* Stage of the most recent failure ("" if none). Shared by every API. */
227const char *omega_gpu_session_last_error(void);
228/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10): library code names its failure stage. */
229void omega_gpu_session_set_error(const char *stage);
230
231/* L136 (roadblock R3): caller holds the lock, device open. Queue i (1..3) past the session's own queue, with its own
232 * 64 KB ring, opened on first use (in order: 1, then 2, ...) and kept until close. The Linux reference grants it only
233 * when the device was opened with AIEN_OMEGA_GPU_CHANNELS > i (a second GPFIFO channel in the same channel group and
234 * VA space); otherwise the platform refuses and this returns -1 with the stage named. Work on different queues is not
235 * ordered against each other. 0 ok. */
236int omega_gpu_session_extra_queue(uint32_t i, OmegaGpuQueueHandle *out);
237/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10).
238 * L136: latch the process now (uncertain completion seen by a caller that cannot prove it with a queue-0 launch, e.g. a
239 * list on an extra queue timed out). Parks every session buffer; every later launch of every API is refused. */
240void omega_gpu_session_latch_uncertain(const char *why);
241
242/* C5: after a latch (a timeout or a cancel after submit), throw the device away and lift the latch, in the same process.
243 * Takes the lock itself. Runs the on-close hooks (still latched), closes the device through the platform, and only
244 * then clears the latch and the parked list. The Linux reference's RM client close is meant to destroy this process's
245 * channels, and so any grid still running on them, and to release the driver objects; that has no chip run yet
246 * (evidence/C5-ISOLATION), and buffers the caller did not free are not unmapped by it (omega_gpu_platform_linux.c,
247 * ref_device_close). Every handle and command list of the old device is stale; the next open starts a new device.
248 * A latch noted by a module (omega_gpu_session_note_module_latch) counts as latched. 0 ok; -1 with the reason: not
249 * latched, latched but no device open, or the close was refused or reported a driver teardown fault (then it stays
250 * latched for good: the old grid may still run, the process must exit). */
251int omega_gpu_session_recover(void);
252/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10).
253 * A module that latched itself (the command lists after a timeout whose check launch completed) tells the session, so
254 * omega_gpu_session_recover accepts it as latched. Launches of other APIs are not refused by it. */
255void omega_gpu_session_note_module_latch(void);
256/* Recoveries so far in this process (a command list latched before the latest recovery no longer blocks). */
257uint32_t omega_gpu_session_recoveries(void);
258
259/* INTERNAL (not part of the Runtime API; docs/runtime/API.md section 10).
260 * Caller holds the lock. Register a function the session calls (lock held, device
261 * still open) right before it closes, so an API can drop its resident kernels and
262 * scratch. Up to 8; the same function is registered once. (Taking the lock inside
263 * deadlocked the first call of every API on 2026-10-04: the APIs register from
264 * their open path, which already holds it.) */
265int omega_gpu_session_on_close(void (*hook)(void));
266
267/* Close the device and free every session buffer. Takes the lock itself.
268 * Refused (no-op) after an uncertain completion. The next open reopens; every handle of the
269 * closed device is stale from then on. */
270void omega_gpu_session_close(void);
271
272/* Device opens so far in this process (diagnostics; a persistent session shows 1). */
273uint32_t omega_gpu_session_open_count(void);
274
275/* Driver allocations made through omega_gpu_session_alloc (every GPU API buffer, tensor, scratch growth and kernel
276 * code buffer) since the process started, for measurement: a serving daemon reads it after warm-up and per request
277 * to show that serving asks the driver for nothing. Covers this session layer only, not other engines. */
278typedef struct {
279 uint64_t allocs; /* successful driver allocations */
280 uint64_t alloc_bytes; /* their page-rounded bytes */
281 uint64_t alloc_failures; /* driver refusals (e.g. NV_ERR_NO_MEMORY) */
282 uint64_t frees; /* driver frees */
283 uint64_t stale_refusals; /* frees refused because the handle was stale (closed device or double free) */
284} OmegaGpuAllocStats;
285void omega_gpu_session_alloc_stats(OmegaGpuAllocStats *out);
286
287/* Buffers parked after an uncertain completion: kept allocated, never returned to the platform. The session's own
288 * launch buffers (ring, constant bank, marker, QMD page) are parked at the latch; every later free parks too.
289 * The first OMEGA_GPU_SESSION_PARK_MAX are listed by handle; past that they are still kept, counted in untracked. */
290#define OMEGA_GPU_SESSION_PARK_MAX 512u
291typedef struct {
292 uint32_t buffers; /* parked buffers (listed + untracked) */
293 uint32_t untracked; /* parked past the list (still never released) */
294 uint64_t bytes; /* their bytes */
295} OmegaGpuParkStats;
296void omega_gpu_session_parked(OmegaGpuParkStats *out);
297/* 1 if this handle is parked (listed). */
298int omega_gpu_session_is_parked(OmegaGpuBufferHandle h);
299
300#ifdef __cplusplus
301}
302#endif
303#endif