Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/patches/21900a29379fa428 # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-mv#422 (code only) closed derived `21900a29379fa428` #422 Imported from GitHub aien-dev/omega-mv#422 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `d2e0b556b9c6a203f185a70cdff54269633054d4` · Head `cef5d51571f167fa10409d7fbeb773d413c3f489` ### Apply it ``` git checkout -b patch-21900a29379fa428 d2e0b556b9c6a203f185a70cdff54269633054d4 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/21900a29379fa428.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-mv 422 cef5d51571f167fa10409d7fbeb773d413c3f489 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":422,"url":"https://github.com/aien-dev/omega-mv/pull/422","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:50Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 9a237882d..dc51ac574 100644 --- a/.crumb +++ b/.crumb @@ -51,8 +51,8 @@ "purpose": "Directory calibration. Purpose not yet described by a human." }, { - "digest": "9140b57d45416f04c6fb5c625e57ae0d64b05f40e2fccb7aba5b189c39230158", - "last_commit": "15c7666", + "digest": "0790547d35025c5b3000f1fbb6da5f46eac7177f936af129ef1f54fd417aabab", + "last_commit": "a073db7", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -63,8 +63,8 @@ "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "d17193f5ff654d28d5077cbae323ae0c5e8a01a12c42b1ba1cfc4fe06968e597", - "last_commit": "15c7666", + "digest": "bb7a612a73a0204d9c380ebc40c84bb2695823835c9e5c9f7afbd1610de13f73", + "last_commit": "a073db7", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -87,33 +87,33 @@ "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "9a14a6455d68afb539c466dd4ee8a11cbbeb75c160381564c59c69e09b05b620", - "last_commit": "15c7666", + "digest": "ca23df0b2067634f96a724c504f83505411a7a191ed771bfdc1470e64182d448", + "last_commit": "a073db7", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "2345fa6923ad5f3cc3886b5c19e6345a728ddb8c810d07e00d754e2ffefa1646", - "last_commit": "15c7666", + "digest": "788442ab21c299f10bd79e6b00bcc478840dc7fe0992e8bc3ae84ce604341085", + "last_commit": "a073db7", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { - "digest": "285407d8f7949613c6b57b225fa50b2bb076aaa874fded0895d82fbf285fb832", - "last_commit": "d708443", + "digest": "d7ca15ce0b953f4434663ff5e9ae64e669d30051a6c37b72805d11aec7648af3", + "last_commit": "a073db7", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:82e335b4499771cad1eae3e885c28f2d6e82b2ed2cd6bec637d23c69faa690fe", - "compiled_at": "2026-10-12T16:18:14Z", + "children_root": "sha256:ef0a9b5420375d41f97193458db0275e4e756ca08b88ddd85e5dcda3757f2007", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:fcebac156df4ad862917aa8660f3232d7ffb31d0ba72b34f7555fa5bc6f01424", + "digest": "sha256:873c03b40f2ffbff4e07d631de2bc9a1576f9d7391fb283041526ec93cd3a8cc", "evidence_files": 7245, "evidence_root": "sha256:035beef5cdb99afaefd1743640f5e7eeaaed13c4a5ec6c8b4b6a4cb0c528407a", - "files": 9739, - "generated_at_commit": "15c7666a3d3183750adc61edb60b7a84141c104a", - "source_tree": "sha256:28588f78533401ca69cb8b7fcb0e75f5affa51a284f193439f69c1588fd12b0b" + "files": 9745, + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:ccefbc5a7da33efdffc06b140457412d38896692629234b36409c3a862b88e5c" }, "owner_lane": "", "provenance": { diff --git a/.github/workflows/host-suites-2.yml b/.github/workflows/host-suites-2.yml index 53f4b881a..68aec4451 100644 --- a/.github/workflows/host-suites-2.yml +++ b/.github/workflows/host-suites-2.yml @@ -155,7 +155,7 @@ jobs: sel argus "^src/runtime/|^tests/runtime/|^tests/bench_rx_argus\.c$|^mk/machine-identity\.mk$|^src/(sha256|omega_evidence)\.|^(physics|aienos|argus)\.lock$" sel numeric2 "^tests/(test_omega_reduce|test_omega_divsqrt_gb10)\.c$|^tests/numeric_oracle\.h$|^src/(omega_numeric|omega_blackwell_(encoder|codegen|matmul|qmd)|sha256)" sel tensor "^tools/m20_receipt(_mutations)?\.sh$|^tests/test_m20_receipt\.sh$|^tests/fixtures/m20_receipt/|^src/tensor/|^tests/test_omega_tensor(_store)?\.c$|^tools/tensor_mutations\.sh$|^mk/tensor\.mk$|^src/(omega_numeric|omega_blackwell_(encoder|codegen|matmul|qmd)|sha256)" - sel gpuengine "^src/omega_gpu_(engine|platform)\.|^src/omega_blackwell_(encoder|qmd|realize|codegen|matmul)\.|^src/sha256\.|^tests/test_omega_(gpu_engine|gpu_engine_compile|gpu_platform|codegen_freestanding)\.c$|^tools/gpu_engine_mutations\.sh$|^mk/omega-gpu-engine\.mk$" + sel gpuengine "^src/omega_gpu_(engine|platform)\.|^src/omega_blackwell_(encoder|qmd|realize|codegen|matmul)\.|^src/omega_gpu_(session|serving|matmul_api|attention_api|wait|fmt|platform_linux)\.|^src/sha256\.|^tests/test_omega_(gpu_engine|gpu_engine_compile|gpu_platform|codegen_freestanding|gpu_session_platform|gpu_platform_linux)\.c$|^tests/fake_m16_native\.c$|^physics\.lock$|^tools/gpu_engine_mutations\.sh$|^mk/omega-gpu-engine\.mk$" visor: needs: changes @@ -436,6 +436,24 @@ jobs: run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-codegen-freestanding - name: Engine mutants (each protection removed once must be caught) run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-gpu-engine-mutants + - name: Portable GPU session over OmegaGpuPlatform, freestanding closure (native v1 P07 cut C session part) + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 build/test_omega_gpu_session_platform test-gpu-session-mutants && ./build/test_omega_gpu_session_platform + - name: Read pinned Physics commit + id: pins + run: | + p=$(tr -d '[:space:]' < physics.lock) + test -n "$p" + echo "physics=$p" >> "$GITHUB_OUTPUT" + - name: Checkout pinned Physics headers (Linux reference platform only) + uses: actions/checkout@v4 + with: + repository: aien-dev/physics + ref: ${{ steps.pins.outputs.physics }} + path: physics-src + - name: Keep the Physics checkout out of Omega tree status + run: printf 'physics-src/\n' >> .git/info/exclude + - name: Linux reference platform (reference only, hosted, fake driver) and full session suite + run: make PHYSICS_DIR=$GITHUB_WORKSPACE/physics-src test-gpu-session-platform tensor: needs: changes diff --git a/Makefile b/Makefile index 5663c5db2..edc489561 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ SRCS = src/sha256.c src/omega_canonical.c src/omega_validate.c src/omega_core.c src/omega_library.c src/omega_discovery.c src/omega_machine.c src/omega_realize_synth.c \ src/omega_matvec.c src/omega_accelerator.c src/omega_accelerator_world.c \ src/omega_vector.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_session.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_attention_api.c src/omega_gpu_serving.c src/omega_world_gates.c src/omega_gpu_wait.c \ + src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c src/omega_gpu_fmt.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_attention_api.c src/omega_gpu_serving.c src/omega_world_gates.c src/omega_gpu_wait.c \ src/omega_evidence.c \ $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c \ tools/omegatool.c diff --git a/bench/prime_race/.crumb b/bench/prime_race/.crumb index 7f2f6bcbd..98f65a875 100644 --- a/bench/prime_race/.crumb +++ b/bench/prime_race/.crumb @@ -3,14 +3,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-05T23:21:14Z", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:2ff0bcbc1cfcfd4b5c4572225f063ff0f542447b9cc85b413a183eebc6d26cf0", + "digest": "sha256:106590f7de0ce420a9124def908e436ce0334521416343705fb543fe27b400b7", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 10, - "generated_at_commit": "2f8b6f85971afc782d986abb888e55fa200ca3d0", - "source_tree": "sha256:eb185f001ff6c322c33228fe0021cf8bd22ebf3183d990ca54a48ad3cceba033" + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:952bd31a0df4183e99f2a481fd89b0370e69221849c87ae66683ab738e5af956" } }, "invariants": [ diff --git a/bench/prime_race/gb10_native.c b/bench/prime_race/gb10_native.c index 5772600d9..a4d04fc25 100644 --- a/bench/prime_race/gb10_native.c +++ b/bench/prime_race/gb10_native.c @@ -105,7 +105,7 @@ typedef struct { uint32_t entries; /* table entries for this limit, sentinel included (fixed by the limit) */ uint32_t shared_bytes; /* 0: global-table kernel; else the staged kernel's shared memory per CTA */ OmegaBlackwellKernel k; - NvrmMem code, out, table; + OmegaGpuMem code, out, table; uint64_t diag_ns, launches; int locked, opened; } gb_state; diff --git a/bench/prime_race/tests/gb10_launch_cost.c b/bench/prime_race/tests/gb10_launch_cost.c index 75a28af64..6b637f161 100644 --- a/bench/prime_race/tests/gb10_launch_cost.c +++ b/bench/prime_race/tests/gb10_launch_cost.c @@ -79,7 +79,7 @@ int main(int argc, char **argv) { omega_gpu_session_lock(); if (!omega_gpu_session_open()) { fprintf(stderr, "open failed: %s\n", omega_gpu_session_last_error()); return 2; } - NvrmMem code, out, tab; + OmegaGpuMem code, out, tab; if (omega_gpu_session_alloc(k.code_size, &code) || omega_gpu_session_alloc((size_t)(nwords ? nwords : 1) * 4, &out) || omega_gpu_session_alloc(((size_t)root / 2 + 2) * 12, &tab)) { fprintf(stderr, "alloc failed\n"); return 2; } memcpy(code.cpu, k.code, k.code_size); diff --git a/docs/.crumb b/docs/.crumb index a233e63dc..85eb88df8 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -81,8 +81,8 @@ "purpose": "Directory docs/estimation. Purpose not yet described by a human." }, { - "digest": "4814693fa8bfdb9b4c6a1270714aea1625edb47eb360b95dd57509ccb9fa507e", - "last_commit": "15c7666", + "digest": "82617b47b6fee43e883fa67d97ecf12e15b112dfce8c5729a8ff77c1ef48bcba", + "last_commit": "a073db7", "name": "numeric", "purpose": "Directory docs/numeric. Purpose not yet described by a human." }, @@ -117,15 +117,15 @@ "purpose": "Directory docs/turing. Purpose not yet described by a human." } ], - "children_root": "sha256:58266768b4537aa7e4a3706895d03421952f342a27e67e1a84d53a1d48f9d1e8", - "compiled_at": "2026-10-12T16:18:14Z", + "children_root": "sha256:9352f505ab6ddff156505d8092d938451e40a2d1f40e86df9abe0e10e327c0ee", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:9140b57d45416f04c6fb5c625e57ae0d64b05f40e2fccb7aba5b189c39230158", + "digest": "sha256:0790547d35025c5b3000f1fbb6da5f46eac7177f936af129ef1f54fd417aabab", "evidence_files": 34, "evidence_root": "sha256:589d8b3706e6d7a202ab20b278dac5fc5bafc973f1c2a867b2668aa7210b65cc", "files": 119, - "generated_at_commit": "15c7666a3d3183750adc61edb60b7a84141c104a", - "source_tree": "sha256:30350b853fc40afad9169bd8e543adcd422d0366516028f0d7e529689fc3c8ad" + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:7275e5a9943a6e9572ac4295a7b0ffb4f0bf754cd42277bb148862c67bfe0327" }, "owner_lane": "", "provenance": { diff --git a/docs/numeric/.crumb b/docs/numeric/.crumb index 57980a14f..d26213db2 100644 --- a/docs/numeric/.crumb +++ b/docs/numeric/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T16:18:14Z", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:4814693fa8bfdb9b4c6a1270714aea1625edb47eb360b95dd57509ccb9fa507e", + "digest": "sha256:82617b47b6fee43e883fa67d97ecf12e15b112dfce8c5729a8ff77c1ef48bcba", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 11, - "generated_at_commit": "15c7666a3d3183750adc61edb60b7a84141c104a", - "source_tree": "sha256:b85bf1bcb0362ad7c4cef16554ca55d8179b6d0858d2fbd6400584f996c4e82d" + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:556ea8188eb5b58ec322a565225ab7612de218570fe17a1d3df387a7b8be3b29" }, "owner_lane": "", "provenance": { diff --git a/docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md b/docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md index e73b99158..d7089ecae 100644 --- a/docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md +++ b/docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md @@ -1,6 +1,7 @@ # Omega GPU native boundary: dependency map and freestanding link target -Native v1 P07 cut A and A.2. Tracks aienos#286 (cut A) and aien-architecture#190. +Native v1 P07 cut A, A.2 and the session part of cut C (omega#419 for A.2, +omega#421 for cut C session part). Tracks aienos#286 and aien-architecture#190. Companion of `docs/numeric/OMEGA_GPU_ENGINE.md` (the engine contract) and `src/omega_gpu_platform.h` (the platform contract this cut adds). @@ -26,7 +27,7 @@ Claimed (host evidence, `make test-gpu-engine-freestanding`): platform clock installed, every job is refused at `STEP_CLOCK_CHECK` before any backend call. - The platform contract (`src/omega_gpu_platform.h`) has a test - (`tests/test_omega_gpu_platform.c`, 6 cases) reaching every refusal name. + (`tests/test_omega_gpu_platform.c`, 7 cases in ABI 1.1) reaching every refusal name. - The engine mutation sweep still kills all 49 mutants (`make test-gpu-engine-mutants`). - Cut A.2 (`make test-codegen-freestanding`): code generation runs without an allocator. The caller supplies the code buffer and its capacity @@ -42,6 +43,49 @@ Claimed (host evidence, `make test-gpu-engine-freestanding`): `__truncsfbf2`) and equals the hosted cast on all 2^32 inputs. A control links a `malloc` caller into the freestanding object and requires the `nm -u` check to refuse it. +- Cut C, session part (`make test-gpu-session-platform`): the persistent GPU + session, the serving allocator and the matmul and attention tensor APIs run + over `OmegaGpuPlatform` (ABI 1.1) instead of calling `physics/nvrm` and + `physics/m16` directly. The freestanding closure grows from 8 to 14 files: + `src/omega_gpu_session.c`, `src/omega_gpu_serving.c`, + `src/omega_gpu_matmul_api.c`, `src/omega_gpu_attention_api.c`, + `src/omega_gpu_wait.c` and the new bounded formatter `src/omega_gpu_fmt.c` + (the session's only text path; it replaces `snprintf`/`strncpy` and a test + compares it to `snprintf` on every format the session uses). The partial link + still leaves only `memcpy`, `memset`, `strcmp` and `strlen` undefined. + - Typed resources: every session buffer is an `OmegaGpuMem` carrying an + `OmegaGpuBufferHandle` (index + generation), its kind (DATA, CODE, QUEUE), + CPU view, GPU VA and size. `omega_gpu_session.h` no longer names `NvrmMem`. + - Same allocations as before, in the same order and sizes (ring, marker, + method block, scratch), all GPU-uncached; the marker is `HOST_POLLED`. The + GB10 completion-flag rule (section 2) is enforced by the platform check, + not by convention. + - Completion is polling and says so: `OmegaGpuPlatform.poll_word` (renamed + from `wait_word`), `omega_gpu_session_completion_mode()` returns + `OMEGA_GPU_COMPLETION_POLLING`, and neither the session nor the Linux + reference claims `OMEGA_GPU_SVC_IRQ`. + - Cancel, timeout and uncertain completion: a cancel before submit refuses + with nothing in flight and no latch; a cancel or timeout after the doorbell + latches the session as uncertain and parks (never frees) every buffer the + device may still touch; a free of a latched buffer parks it; close, reopen + and platform install are refused while latched. Parked bytes and counts are + reported. + - Stale handles: after close and reopen, a handle from the earlier + incarnation is refused and counted (`stale_refusals`), never reused. + - Explicit visibility: the old `dsb` barriers become + `omega_gpu_session_sync_to_gpu` / `sync_to_cpu` calls on named buffers. + - The Linux driver path is a separate reference implementation, + `src/omega_gpu_platform_linux.c` (reference only, hosted only, excluded from + the freestanding closure, with its own test + `tests/test_omega_gpu_platform_linux.c`, 6 cases including "same driver + calls in the same order as before"). Hosted builds install it by default; + the freestanding build has no default platform and refuses until one is + installed. + - Tests: session platform 13 of 13 cases (fork-isolated), Linux reference 6 + of 6, six session mutants all killed (`make test-gpu-session-mutants`), + serving-alloc output byte-identical to main in all six modes apart from + test line numbers, matmul-api host-only 171/0, attention host-only 107/0 + and simulator 219/0, engine 50/0, platform 7/0. Not claimed: @@ -52,6 +96,11 @@ Not claimed: GPU. Device discovery, bounded MMIO/DMA/IRQ ownership and the SMMU path are cut B, and their evidence is NOT_RUN until an attended hardware window (native v1 gate N4; the B7b one-page SMMU probe is not GPU compute). +- No native GPU backend yet. Cut C's session part moves the dependency onto + `OmegaGpuPlatform`; the only platform that drives a real GB10 today is the + Linux reference. Native GB10 execution through any of this is NOT_RUN. +- The elementwise API, the numeric launchers, the vector executor and the + resident runtime still depend on Linux (section 3). - No production use of the test-only hooks. `omega_gpu_engine_test_set_clock` remains test-only; the production time service is `omega_gpu_engine_set_clock`, which the native platform calls once at init. @@ -72,7 +121,7 @@ files in section 3. | Bus addresses / SMMU translation | kernel DMA API inside RM | AIENOS SMMU, `OmegaGpuBusAddr` (no raw physical address type exists) | B | NOT_RUN | | Channel / queue creation (GPFIFO, USERD) | `m16_native_create_channel`, `nvrm_channel` | native queue behind `OmegaGpuQueueHandle`, ring is a `BUF_QUEUE` buffer | B/C | NOT_RUN | | Submit token / doorbell | `m16_native_submit_methods`, `nvrm_enqueue`, `nvrm_ring` | `OmegaGpuPlatform.mmio_write32` on the doorbell region | C | NOT_RUN | -| Completion (marker words, semaphores) | `m16_native_wait_marker*`, host polling | `OmegaGpuPlatform.wait_word` on a HOST_POLLED, GPU-uncached buffer | C | contract DONE, device NOT_RUN | +| Completion (marker words, semaphores) | `m16_native_wait_marker*`, host polling | `OmegaGpuPlatform.poll_word` (polling, ABI 1.1) on a HOST_POLLED, GPU-uncached buffer | C | contract and session DONE (cut C), device NOT_RUN | | Interrupts | RM interrupt handling (not used by our launchers: they poll) | `OMEGA_GPU_SVC_IRQ` only when a real interrupt wait exists; polling never claims it | B | NOT_RUN | | Visibility / cache maintenance | L2 flush mem-op + uncached marker (C3 block) | `OmegaGpuPlatform.sync_*` plus the same mem-op sequence in the encoder | C | NOT_RUN | | Time, waiting, locking | `clock_gettime`, `usleep`, pthread | `OmegaGpuPlatform.time_now_ms`, `wait_ms`, `lock`/`unlock` | A (contract) | DONE | @@ -105,11 +154,14 @@ development-host measurement or gating and is not part of the native product | `src/sha256.c` | 0 | 0 | none | A | DONE | | `src/omega_blackwell_codegen.c` | 0 | 0 | none in the freestanding build (stdio, stdlib only in the hosted build) | A.2 | DONE: caller-provided code buffer (`omega_blackwell_kernel_encode_into`); allocating generators, diagnostics and the printing variation self-test are hosted only | | `src/omega_blackwell_matmul.c` | 0 | 0 | none in the freestanding build (stdlib only in the hosted build) | A.2 | DONE: `omega_blackwell_kernel_free` and the dispatcher hosted only; integer bf16 rounding in the freestanding build | -| `src/omega_gpu_wait.c` | 0 | 0 | time.h | C | clock from the platform time service | -| `src/omega_gpu_serving.c` | 0 | 0 | none | C | moves with the session | -| `src/omega_gpu_matmul_api.c` | 0 | 0 | stdlib, stdio, time | C | moves with the session | -| `src/omega_gpu_attention_api.c` | 0 | 0 | stdio, stdlib, time | C | moves with the session | -| `src/omega_gpu_session.c` (+ `.h` leaks `NvrmMem`) | 19 | 7 | pthread, stdio, time | C | `NvrmMem` in the session header becomes `OmegaGpuBufferHandle`; lock from the platform | +| `src/omega_gpu_wait.c` | 0 | 0 | none in the freestanding build (time only in the hosted build) | C | DONE (session part): freestanding has no default clock and refuses without `cfg->now_ns` | +| `src/omega_gpu_serving.c` | 0 | 0 | none | C | DONE (session part): in the freestanding closure | +| `src/omega_gpu_matmul_api.c` | 0 | 0 | none (string.h only for mem*/str*) | C | DONE (session part): host memory and clock from the session, code encoded in place into a CODE buffer, explicit sync calls | +| `src/omega_gpu_attention_api.c` | 0 | 0 | none (stdio only under `OMEGA_ATTN_DEBUG`) | C | DONE (session part): same as matmul API | +| `src/omega_gpu_session.c` | 0 | 0 | none in the freestanding build (pthread only for the hosted default install) | C | DONE (session part): every device call through `OmegaGpuPlatform` ABI 1.1; header names `OmegaGpuMem`, not `NvrmMem` | +| `src/omega_gpu_fmt.c` | 0 | 0 | none (stdarg) | C | new: bounded formatter for session and API text | +| `src/omega_gpu_platform_linux.c` | 13 | 15 | pthread, stdio, stdlib, time | reference only | new: the Linux RM/UVM implementation of `OmegaGpuPlatform`, hosted only, never in the freestanding closure; its own test | +| `src/omega_gpu_elementwise_api.c` | 0 | 0 | stdio, stdlib, time | C (later part) | uses `OmegaGpuMem` from the session; still hosted | | `src/omega_blackwell_engine.c` | 19 | 13 | errno, stdio, time | stays Linux-private | the Linux backend of `OmegaGpuBackend`; a sibling native backend over `OmegaGpuPlatform` arrives in B/C | | `src/omega_numeric_gb10.c` | 21 | 2 | stdio, stdlib, errno, time | C/D | numeric launchers follow the engine Phase B order | | `src/omega_numeric_divsqrt_gb10.c` | 20 | 2 | stdio, stdlib, errno, time | C/D | same | @@ -122,10 +174,9 @@ development-host measurement or gating and is not part of the native product | `src/omega_blackwell_gates.c` | 0 | 1 | stdio, stdlib, time | host tooling | stays on Linux | Headers that still expose a Linux driver type and must lose it before the cut -that migrates their users: `src/omega_gpu_session.h` (`NvrmMem`, cut C), -`src/omega_numeric_native.h` (C/D), `src/forge_realization.h`, +that migrates their users: `src/omega_numeric_native.h` (C/D), `src/forge_realization.h`, `src/omega_evidence.h`, `src/omega_accelerator_world.h`, -`src/omega_physics_dir.h` (host tooling; they keep it). +`src/omega_physics_dir.h` (host tooling; they keep it). `src/omega_gpu_session.h` lost `NvrmMem` in cut C (session part). Distinct driver entry points in use (count of call sites, same snapshot): `nvrm_mthd` 188, `m16_native_close` 46, `nvrm_alloc` 33, @@ -146,8 +197,10 @@ an RM method table. `.github/workflows/host-suites-2.yml`. - Flags: `-std=gnu11 -O2 -Wall -Wextra -Werror -ffreestanding -fno-builtin - -fno-stack-protector -DOMEGA_GPU_NO_POSIX -DOMEGA_NUMERIC_CPU_ONLY`. -- The eight objects are partially linked (`gcc -r -nostdlib`); `nm -u` on the + -fno-stack-protector -U_FORTIFY_SOURCE -DOMEGA_GPU_NO_POSIX -DOMEGA_NUMERIC_CPU_ONLY`. + `-U_FORTIFY_SOURCE` (cut C) keeps glibc from redirecting `memcpy` to + `__memcpy_chk` when a distribution compiler enables fortify by default. +- The fourteen objects (eight from A and A.2, six from cut C) are partially linked (`gcc -r -nostdlib`); `nm -u` on the result may show only `memcpy|memmove|memset|memcmp|strlen|strcmp` (and the GOT symbol). Anything else fails the build with the symbol named. - `OMEGA_GPU_NO_POSIX` in `src/omega_gpu_engine.c`: `err_no` is recorded as 0 @@ -161,7 +214,7 @@ an RM method table. ## 5. The platform contract in one page -`src/omega_gpu_platform.h`, ABI 1.0. +`src/omega_gpu_platform.h`, ABI 1.1 (1.0 in cut A; 1.1 adds the session services in cut C). - Handles: `OmegaGpuDeviceHandle`, `OmegaGpuBufferHandle`, `OmegaGpuQueueHandle`, each `index + generation`; generation 0 is never issued; a closed handle is @@ -177,6 +230,16 @@ an RM method table. `omega_gpu_platform_check` refuses a claimed service without a function and refuses a function that no claimed service declares (a hidden path is a silent fallback). +- ABI 1.1 (cut C, session part): services DEVICE (open, close, driver text of + the last failure), QUEUE (open, submit, retire, close over a `BUF_QUEUE` + ring), CLOCK_NS and HOST_MEM, required together as + `OMEGA_GPU_SVC_REQUIRED_SESSION` (no MMIO, no IRQ) and checked by + `omega_gpu_platform_check_for`. COMPLETION is `poll_word` (renamed from + `wait_word`): reached in serial-number order, `OMEGA_GPU_POLL_TIMED_OUT` when + not, and a timeout says nothing about the device. New refusal + `OMEGA_GPU_PLAT_REFUSED_DEVICE`. Handle slots raised from 64 to 1024 (a + serving session holds one buffer per weight tensor). A refused + `queue_submit` rang no doorbell, so nothing of it is in flight. - Limits and concurrency: `OmegaGpuPlatformCaps` carries device, buffer, queue, in-flight, per-buffer and total byte limits; `omega_gpu_platform_negotiate` refuses a required set the platform does not @@ -190,15 +253,21 @@ an RM method table. `omega_blackwell_codegen.c` and `omega_blackwell_matmul.c`, both in the freestanding target. The kernels each API builds for itself (`omega_gpu_attention_api.c`, `omega_gpu_elementwise_api.c`) still malloc - their code and move with the session in cut C. + their code and move with the session in cut C (the attention API moved in + cut C session part; the elementwise API has not). - B (needs an attended window, native v1 gate order N1 then N4): AIENOS-side discovery and bounded device ownership through the platform services; a discovery-only run makes zero configuration writes; SMMU/DMA resolved; polling does not claim IRQ. Implement aienos#285 before any domain-1 resource number is reused or persisted. The arch#163 native-order conflict is resolved explicitly in that cut, not implied here. -- C: native backend of `OmegaGpuBackend` over `OmegaGpuPlatform`; the - session, serving and API files drop `NvrmMem` and libc time/lock calls. +- C, session part: DONE (see section 1): session, serving, matmul and + attention APIs and the bounded wait run over `OmegaGpuPlatform` ABI 1.1 and + are in the freestanding closure; the Linux driver path is the separate + reference `src/omega_gpu_platform_linux.c`. +- C, remaining: a native implementation of `OmegaGpuPlatform` and a native + backend of `OmegaGpuBackend` (both need cut B device ownership first); the + elementwise API (`omega_gpu_elementwise_api.c`) joins the closure. - D: vector executor (sha256 pin re-sealed on chip), numeric launchers, resident runtime. @@ -206,3 +275,7 @@ Pre-existing, unrelated to this cut: `make test-gpu-serving-alloc` fails its `bounds` mode on omega main 536870f1 ("in-bounds paged calls touched the driver (1 allocs)"), reproduced on an untouched checkout on 2026-10-12. It belongs to the matmul serving lane (cut I, omega#414), and is reported there. +On main 4d0bb36 its `sweep` mode fails 130 checks as well; cut C leaves both +failures unchanged (the output of all six modes is identical to main apart +from test line numbers). `gpu_attention_test --hd 128 --host-only` fails 16 +of 107 on main 4d0bb36 and on this branch with the same list. diff --git a/mk/.crumb b/mk/.crumb index 2a3f06782..534b33d69 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T16:18:14Z", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:d17193f5ff654d28d5077cbae323ae0c5e8a01a12c42b1ba1cfc4fe06968e597", + "digest": "sha256:bb7a612a73a0204d9c380ebc40c84bb2695823835c9e5c9f7afbd1610de13f73", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 67, - "generated_at_commit": "15c7666a3d3183750adc61edb60b7a84141c104a", - "source_tree": "sha256:2f16ba91decd1db32bafc5552006255692bd76882e9d211fd3720ef1da818252" + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:99298a209933d9311ece77629b6d00f2e022985259a641142229aa65578b8b80" }, "owner_lane": "", "provenance": { diff --git a/mk/omega-gpu-engine.mk b/mk/omega-gpu-engine.mk index a7fecc268..0f044a9d6 100644 --- a/mk/omega-gpu-engine.mk +++ b/mk/omega-gpu-engine.mk @@ -79,7 +79,7 @@ test-gpu-engine-gb10-compile: build/test_omega_gpu_engine_gb10.o # Measurement (sc#277): driver allocations and frees made by the REAL session + matmul + attention # APIs while serving a Qwen3-4B-shaped sequence, against the simulated driver. Host only, no device. # Prints MEASURE lines; asserts only bookkeeping. Links no physics C sources, only its headers. -GPU_SERVE_ALLOC_SRCS = src/omega_gpu_session.c src/omega_gpu_matmul_api.c src/omega_gpu_attention_api.c src/omega_gpu_serving.c \ +GPU_SERVE_ALLOC_SRCS = src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c src/omega_gpu_fmt.c src/omega_gpu_matmul_api.c src/omega_gpu_attention_api.c src/omega_gpu_serving.c \ src/omega_gpu_wait.c src/omega_blackwell_codegen.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ src/omega_blackwell_matmul.c src/sha256.c build/gpu_serving_alloc_count_test: tests/gpu_serving_alloc_count_test.c tests/fake_m16_native.c tests/fake_m16_native.h $(GPU_SERVE_ALLOC_SRCS) @@ -111,14 +111,23 @@ test-gpu-serving-alloc: build/gpu_serving_alloc_count_test # runtime symbols; it proves nothing about device ownership (NOT_RUN until cut B runs on the Spark). GPU_FS_DIR = build/gpu_fs GPU_FS_CFLAGS = -std=gnu11 -O2 -Wall -Wextra -Werror -ffreestanding -fno-builtin -fno-stack-protector \ - -DOMEGA_GPU_NO_POSIX -DOMEGA_NUMERIC_CPU_ONLY -Isrc + -U_FORTIFY_SOURCE -DOMEGA_GPU_NO_POSIX -DOMEGA_NUMERIC_CPU_ONLY -Isrc +# P07 cut C (session part): the persistent session, the matmul and attention APIs, the serving reservation and the +# bounded wait join the link. Their machine comes from an installed OmegaGpuPlatform; the Linux reference +# (src/omega_gpu_platform_linux.c) is deliberately NOT in this list. Still outside it: the elementwise API, the +# numeric launchers, the vector executor, the resident runtime (docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md). GPU_FS_SRCS = src/omega_gpu_engine.c src/omega_gpu_platform.c src/omega_blackwell_encoder.c src/omega_blackwell_codegen.c \ - src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_blackwell_realize.c src/sha256.c + src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/omega_blackwell_realize.c src/sha256.c \ + src/omega_gpu_session.c src/omega_gpu_fmt.c src/omega_gpu_matmul_api.c src/omega_gpu_attention_api.c \ + src/omega_gpu_serving.c src/omega_gpu_wait.c +GPU_FS_HDRS = src/omega_gpu_engine.h src/omega_gpu_platform.h src/omega_blackwell_codegen.h src/omega_blackwell_matmul.h \ + src/omega_gpu_session.h src/omega_gpu_fmt.h src/omega_gpu_matmul_api.h src/omega_gpu_attention_api.h \ + src/omega_gpu_serving.h src/omega_gpu_wait.h GPU_FS_OBJS = $(patsubst src/%.c,$(GPU_FS_DIR)/%.o,$(GPU_FS_SRCS)) GPU_FS_LINK = $(GPU_FS_DIR)/omega_gpu_freestanding.o GPU_FS_ALLOWED = memcpy|memmove|memset|memcmp|strlen|strcmp -$(GPU_FS_DIR)/%.o: src/%.c src/omega_gpu_engine.h src/omega_gpu_platform.h src/omega_blackwell_codegen.h src/omega_blackwell_matmul.h +$(GPU_FS_DIR)/%.o: src/%.c $(GPU_FS_HDRS) @mkdir -p $(GPU_FS_DIR) gcc $(GPU_FS_CFLAGS) -c -o $@ $< @@ -172,3 +181,45 @@ test-gpu-fs-allowlist-control: $(GPU_FS_LINK) @bad=$$(nm -u $(GPU_FS_DIR)/control/with_canary.o | awk '{print $$NF}' | grep -Ev '^(_GLOBAL_OFFSET_TABLE_|($(GPU_FS_ALLOWED)))$$' || true); \ if [ "$$bad" != "malloc" ]; then echo "allowlist control: expected exactly malloc refused, got '$$bad'"; exit 1; fi; \ echo "allowlist control: a malloc caller is refused by the nm -u check (as required)" + +# native v1 P07 cut C, session part (aienos#286): the portable session over OmegaGpuPlatform. +# - test_omega_gpu_session_platform links the FREESTANDING partial-link object and drives it through a fake +# platform: install refusals, no default platform, typed GPU-uncached buffers, polling only, cancel before and +# after submit, timeout (latch + park, nothing released), stale handle after close/reopen, reservation refusal. +# - test_omega_gpu_platform_linux drives the Linux REFERENCE platform (reference only) on the simulated driver: +# same driver calls in the same order as before cut C, its refusals, and a marker that never lands. +# - the mutants prove the session test can fail: each one breaks one rule in a copy of the session and the test +# must report FAIL for it. +.PHONY: test-gpu-session-platform test-gpu-session-mutants +build/test_omega_gpu_session_platform: tests/test_omega_gpu_session_platform.c $(GPU_FS_LINK) + @mkdir -p build + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_GPU_NO_POSIX -o $@ tests/test_omega_gpu_session_platform.c $(GPU_FS_LINK) +GPU_LINUX_REF_SRCS = src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c src/omega_gpu_fmt.c src/omega_blackwell_qmd.c +build/test_omega_gpu_platform_linux: tests/test_omega_gpu_platform_linux.c tests/fake_m16_native.c tests/fake_m16_native.h $(GPU_LINUX_REF_SRCS) $(GPU_FS_HDRS) src/omega_gpu_platform_linux.h + @mkdir -p build + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE -pthread -Isrc -Itests $(GPU_ENGINE_PHYS_INC) \ + -o $@ tests/test_omega_gpu_platform_linux.c tests/fake_m16_native.c $(GPU_LINUX_REF_SRCS) +test-gpu-session-platform: build/test_omega_gpu_session_platform build/test_omega_gpu_platform_linux test-gpu-session-mutants + ./build/test_omega_gpu_session_platform + ./build/test_omega_gpu_platform_linux + +GPU_SESSION_MUT_DIR = build/gpu_session_mut +test-gpu-session-mutants: $(GPU_FS_LINK) + @mkdir -p $(GPU_SESSION_MUT_DIR) + @set -e; killed=0; \ + smut() { name=$$1; script=$$2; \ + sed -e "$$script" src/omega_gpu_session.c > $(GPU_SESSION_MUT_DIR)/$$name.c; \ + if cmp -s src/omega_gpu_session.c $(GPU_SESSION_MUT_DIR)/$$name.c; then echo "mutant $$name: pattern not found"; exit 1; fi; \ + gcc $(GPU_FS_CFLAGS) -c -o $(GPU_SESSION_MUT_DIR)/$$name.o $(GPU_SESSION_MUT_DIR)/$$name.c; \ + objs=$$(echo $(GPU_FS_OBJS) | tr ' ' '\n' | grep -v '/omega_gpu_session.o$$' | tr '\n' ' '); \ + gcc -std=gnu11 -O2 -Wall -Wextra -Werror -Isrc -DOMEGA_GPU_NO_POSIX -o $(GPU_SESSION_MUT_DIR)/$$name \ + tests/test_omega_gpu_session_platform.c $$objs $(GPU_SESSION_MUT_DIR)/$$name.o; \ + if ./$(GPU_SESSION_MUT_DIR)/$$name > $(GPU_SESSION_MUT_DIR)/$$name.log 2>&1; then echo "mutant $$name SURVIVED"; exit 1; fi; \ + echo "mutant $$name killed: $$(grep -c '^FAIL' $(GPU_SESSION_MUT_DIR)/$$name.log) case(s) failed"; killed=$$((killed+1)); }; \ + smut release-when-latched 's|if (LOAD(g_blocked)) {$$|if (0) {|'; \ + smut ignore-cancel 's|if (LOAD(g_cancel)) return WAIT_CANCELLED;|;|g'; \ + smut no-latch-on-timeout 's|latch(w == WAIT_TIMED_OUT|omega_gpu_session_set_error(w == WAIT_TIMED_OUT|'; \ + smut stale-not-counted 's|else { BUMP(g_stats.stale_refusals, 1u); fail_plat("dma_free", rc); }|else {}|'; \ + smut marker-not-polled 's|RIGHTS_MARKER, PAGE|RIGHTS_DATA, PAGE|'; \ + smut close-while-latched 's|if (g_open \&\& !LOAD(g_blocked) \&\& p) {|if (g_open \&\& p) {|; s|if (!LOAD(g_blocked)) { /\* a hook|if (1) { /* a hook|'; \ + echo "test-gpu-session-mutants: $$killed of 6 mutants killed" diff --git a/src/.crumb b/src/.crumb index 3596bd85e..53cbe5315 100644 --- a/src/.crumb +++ b/src/.crumb @@ -176,14 +176,14 @@ } ], "children_root": "sha256:2f64d32b2351272f4de10e1143efdb74dbc3cae56b1f0a3039ca9edcfebf6e8c", - "compiled_at": "2026-10-12T16:18:14Z", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:9a14a6455d68afb539c466dd4ee8a11cbbeb75c160381564c59c69e09b05b620", + "digest": "sha256:ca23df0b2067634f96a724c504f83505411a7a191ed771bfdc1470e64182d448", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 453, - "generated_at_commit": "15c7666a3d3183750adc61edb60b7a84141c104a", - "source_tree": "sha256:96aad6f3b79b63757302dec42d016e695ceca5937a7d60a97586510bca6c7f38" + "files": 457, + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:3051eb94eb85f9c1749d656f78c433fa6730da9ae5e153c8bd47f0e168acd369" }, "owner_lane": "", "provenance": { diff --git a/src/omega_gpu_attention_api.c b/src/omega_gpu_attention_api.c index 52a26dc28..d9d56b121 100644 --- a/src/omega_gpu_attention_api.c +++ b/src/omega_gpu_attention_api.c @@ -30,12 +30,12 @@ #include "omega_blackwell_qmd.h" #include "omega_blackwell_submit.h" #include "omega_gpu_session.h" +#include "omega_gpu_fmt.h" #include "sha256.h" -#include -#include -#include +#ifdef OMEGA_ATTN_DEBUG +#include /* the debug trace only; never in the freestanding build */ +#endif #include -#include /* ------------------------------------------------------------------ codegen */ @@ -695,7 +695,7 @@ static void gen_attention(Em *e, const KSpec *k) { #define AT_GPR_BUDGET 96u /* cut K: the GQA-group hd 128 kernel carries four heads of running state (the matmul blocked kernels launch at 108) */ static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) { - BlackwellIRProgram *prog = calloc(1, sizeof *prog); + BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL; omega_bw_ir_init(prog); Em e; memset(&e, 0, sizeof e); e.p = prog; @@ -713,7 +713,7 @@ static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellI if (e.err == 0 && ra_rc == 0 && loop_rc == 0 && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) { size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16; memset(kernel, 0, sizeof *kernel); - kernel->code = malloc(max_bytes); + kernel->code = omega_gpu_host_alloc(max_bytes); size_t emitted = 0; if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) { kernel->code_size = emitted; @@ -723,10 +723,10 @@ static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellI sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); rc = OMEGA_GPU_ATTN_OK; } else { - free(kernel->code); kernel->code = NULL; + omega_gpu_host_free(kernel->code); kernel->code = NULL; } } - if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else free(prog); + if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else omega_gpu_host_free(prog); return rc; } @@ -737,12 +737,12 @@ static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellI static int g_mutant; static int g_divergent; /* omega #308 R2 test hook: see KSpec.divergent */ static bool g_dedupe = true; /* shared-prefix staging dedupe; false = legacy per-sequence staging (test hook) */ -typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; NvrmMem code; } Slot; +typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; OmegaGpuMem code; } Slot; static OmegaGpuAttnSim g_sim; static Slot g_cache[16]; /* split variants (cut F) multiply the shapes in flight */ static int g_split = -1; /* test hook: forced log2split (0..OMEGA_GPU_ATTN_MAX_LOG2SPLIT), -1 = chosen per launch from the context */ static OmegaGpuScratch g_q, g_pool, g_tab, g_out; /* staging, grown to the high-water mark, reused per call */ -static NvrmMem g_resident; /* the resident KV pool (omega_gpu_attention_pool_alloc); cpu NULL = none */ +static OmegaGpuMem g_resident; /* the resident KV pool (omega_gpu_attention_pool_alloc); cpu NULL = none */ static bool g_hooked; #define LOCK() omega_gpu_session_lock() #define UNLOCK() omega_gpu_session_unlock() @@ -774,7 +774,7 @@ int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu) { LOCK(); if (g_resident.cpu) { omega_gpu_session_set_error("attention pool: already allocated"); UNLOCK(); return OMEGA_GPU_ATTN_BAD_ARGS; } if (g_sim) { - g_resident.cpu = calloc(1, bytes); + g_resident.cpu = omega_gpu_host_calloc(1, bytes); if (!g_resident.cpu) { UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } g_resident.va = (uintptr_t)g_resident.cpu; g_resident.size = bytes; } else { @@ -789,14 +789,14 @@ int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu) { void omega_gpu_attention_pool_free(void) { LOCK(); - if (g_resident.cpu) { if (g_sim) free(g_resident.cpu); else omega_gpu_session_free(&g_resident); } + if (g_resident.cpu) { if (g_sim) omega_gpu_host_free(g_resident.cpu); else omega_gpu_session_free(&g_resident); } memset(&g_resident, 0, sizeof g_resident); UNLOCK(); } static void cache_clear_locked(void) { for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used) { free(g_cache[i].kernel.code); free(g_cache[i].prog); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } + if (g_cache[i].used) { omega_gpu_host_free(g_cache[i].kernel.code); omega_gpu_host_free(g_cache[i].prog); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } } void omega_gpu_attention_cache_clear(void) { @@ -836,7 +836,7 @@ static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, size_t slot = 0; for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; } s = &g_cache[slot]; - if (s->used) { free(s->kernel.code); free(s->prog); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ + if (s->used) { omega_gpu_host_free(s->kernel.code); omega_gpu_host_free(s->prog); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ memset(s, 0, sizeof *s); s->used = 1; s->k = k; s->kernel = kern; s->prog = kp; *hit = false; @@ -844,7 +844,7 @@ static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, if (upload && !s->code.cpu) { if (omega_gpu_session_alloc_code(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size); - __asm__ volatile("dsb sy" ::: "memory"); + if (omega_gpu_session_sync_to_gpu(&s->code) != 0) { omega_gpu_session_free(&s->code); return OMEGA_GPU_ATTN_CHIP_FAIL; } } *out = s; return OMEGA_GPU_ATTN_OK; @@ -870,10 +870,7 @@ const char *omega_gpu_attention_last_error(void) { return omega_gpu_session_last #define AT_POISON 0xffbadbadu #define AT_WAIT_MS 600000ull -static uint64_t now_ns(void) { - struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); - return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; -} +static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } /* the platform clock (CLOCK_NS) */ typedef OmegaGpuAttnLaunch Launch; @@ -889,7 +886,7 @@ static int dev_open_locked(void) { static void *stage_target(size_t bytes, void **host_tmp, int *fail_rc) { *host_tmp = NULL; *fail_rc = OMEGA_GPU_ATTN_CHIP_FAIL; - if (g_sim) { *host_tmp = malloc(bytes ? bytes : 1); return *host_tmp; } + if (g_sim) { *host_tmp = omega_gpu_host_alloc(bytes ? bytes : 1); return *host_tmp; } int r = omega_gpu_session_scratch(&g_pool, bytes); if (r != 0) { if (r == OMEGA_GPU_SESSION_SCRATCH_RESERVED) *fail_rc = OMEGA_GPU_ATTN_TOO_LARGE; return NULL; } /* reserved bound exceeded: loud, no allocation */ return g_pool.mem.cpu; @@ -911,7 +908,10 @@ static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { size_t out_words = L->out_bytes / 4; uint32_t *out_dev = (uint32_t *)g_out.mem.cpu; for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON; - __asm__ volatile("dsb sy" ::: "memory"); + /* the KV this launch reads: the staged pool, or the resident pool the caller wrote in place */ + if (omega_gpu_session_sync_to_gpu(&g_q.mem) != 0 || omega_gpu_session_sync_to_gpu(&g_tab.mem) != 0 || + omega_gpu_session_sync_to_gpu(&g_out.mem) != 0 || omega_gpu_session_sync_to_gpu(L->pool_va ? &g_resident : &g_pool.mem) != 0) + return OMEGA_GPU_ATTN_CHIP_FAIL; uint32_t args[ARG_WORDS]; args[0] = (uint32_t)g_q.mem.va; args[1] = (uint32_t)(g_q.mem.va >> 32); @@ -926,6 +926,7 @@ static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { }; uint64_t elapsed = 0; uint32_t marker = 0; if (omega_gpu_session_launch(&GL, &elapsed, &marker) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; + if (omega_gpu_session_sync_to_cpu(&g_out.mem) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; memcpy(L->out, g_out.mem.cpu, L->out_bytes); uint32_t unwritten = 0; @@ -1032,7 +1033,7 @@ static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bo info->kernel_cache_hit = hit; info->gpr_count = k->gpr_count; info->insn_count = (uint32_t)k->insn_count; - snprintf(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)"); + omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)"); info->sm_architecture = 121; } static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } @@ -1095,7 +1096,7 @@ int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const floa .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 } }; rc = launch(ks, &L, info); - free(host_tmp); + omega_gpu_host_free(host_tmp); UNLOCK(); if (info) info->call_ns = now_ns() - t0; return rc; @@ -1139,8 +1140,8 @@ int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const if (info) { info->kv_bytes_staged += 2 * plane; info->kv_bytes_naive += (uint64_t)num_rows * 2 * plane; info->kv_blocks_logical += num_rows; info->kv_blocks_unique += 1; } const uint32_t per = rows_per_launch(num_rows, num_q_heads, row * 4); /* table of one launch: per block ids (all 0: the one staged block), then per context lengths */ - uint32_t *tab = calloc(2 * (size_t)per, sizeof *tab); - if (!tab) { free(host_tmp); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } + uint32_t *tab = omega_gpu_host_calloc(2 * (size_t)per, sizeof *tab); + if (!tab) { omega_gpu_host_free(host_tmp); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } for (uint32_t r0 = 0; r0 < num_rows && rc == OMEGA_GPU_ATTN_OK; r0 += per) { const uint32_t nr = num_rows - r0 < per ? num_rows - r0 : per; for (uint32_t i = 0; i < nr; i++) { tab[i] = 0; tab[nr + i] = base_len + r0 + i + 1; } @@ -1152,8 +1153,8 @@ int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const }; rc = launch(ks, &L, info); } - free(tab); - free(host_tmp); + omega_gpu_host_free(tab); + omega_gpu_host_free(host_tmp); UNLOCK(); if (info) info->call_ns = now_ns() - t0; return rc; @@ -1198,9 +1199,9 @@ static void combine_splits(const float *part, float *out, size_t rows, uint32_t for (size_t r = 0; r < rows; r++) { const float *p = part + r * S * pw; float *o = out + r * HD; - float mx = -INFINITY; + float mx = -__builtin_inff(); for (uint32_t s = 0; s < S; s++) if (p[s * pw + HD] > mx) mx = p[s * pw + HD]; - if (!(mx > -INFINITY)) { memset(o, 0, (size_t)HD * 4); continue; } + if (!(mx > -__builtin_inff())) { memset(o, 0, (size_t)HD * 4); continue; } float w[1u << OMEGA_GPU_ATTN_MAX_LOG2SPLIT], lsum = 0.0f; for (uint32_t s = 0; s < S; s++) { w[s] = host_exp2(p[s * pw + HD] - mx); lsum += w[s] * p[s * pw + HD + 1]; } const float inv = 1.0f / lsum; @@ -1229,14 +1230,14 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou return OMEGA_GPU_ATTN_BAD_ARGS; size_t row = (size_t)num_q_heads * HD; /* effective context per sequence and block id range check */ - uint32_t *eff = calloc(num_seqs ? num_seqs : 1, sizeof *eff); + uint32_t *eff = omega_gpu_host_calloc(num_seqs ? num_seqs : 1, sizeof *eff); if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL; for (uint32_t s = 0; s < num_seqs; s++) { uint64_t cap = (uint64_t)n_blocks[s] * ly->block_size; eff[s] = (uint32_t)(ctx[s] < cap ? ctx[s] : cap); for (uint32_t b = 0; b < n_blocks[s]; b++) { uint64_t id = tables[s][b]; - if (id >= ly->num_blocks || id * ly->block_stride_bytes + (uint64_t)(layer_idx + 1) * ly->layer_stride_bytes > ly->pool_bytes) { free(eff); return OMEGA_GPU_ATTN_BAD_ARGS; } + if (id >= ly->num_blocks || id * ly->block_stride_bytes + (uint64_t)(layer_idx + 1) * ly->layer_stride_bytes > ly->pool_bytes) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_BAD_ARGS; } } } uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads; @@ -1248,11 +1249,11 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou else for (uint32_t s = 0; s < num_seqs; s++) { uint32_t l = own_log2split(eff[s], HD); if (l > log2split) log2split = l; } while (log2split && ((uint64_t)num_q_heads * seqs_per_launch << log2split) > OMEGA_GPU_ATTN_SPLIT_MAX_CTAS) log2split--; const uint32_t S = 1u << log2split; - float *part = malloc((size_t)seqs_per_launch * num_q_heads * S * (HD + 2) * 4); /* the partials of one launch */ - if (!part) { free(eff); return OMEGA_GPU_ATTN_CHIP_FAIL; } + float *part = omega_gpu_host_alloc((size_t)seqs_per_launch * num_q_heads * S * (HD + 2) * 4); /* the partials of one launch */ + if (!part) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_CHIP_FAIL; } Slot *ks = NULL; rc = begin(false, log2bs, log2gqa, HD, (int)log2split, &ks, info); - if (rc != OMEGA_GPU_ATTN_OK) { free(eff); free(part); return rc; } + if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_host_free(eff); omega_gpu_host_free(part); return rc; } uint32_t maxb = 1; for (uint32_t s = 0; s < num_seqs; s++) if (n_blocks[s] > maxb) maxb = n_blocks[s]; /* Resident pool (2026-10-12): the caller's pool IS omega's allocation. Read it in place when the @@ -1267,9 +1268,9 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou int32_t *slot_of = NULL; uint32_t *touched = NULL; if (g_dedupe && !resident) { size_t nb = ly->num_blocks ? ly->num_blocks : 1; - slot_of = malloc(nb * sizeof *slot_of); - touched = malloc(nb * sizeof *touched); - if (!slot_of || !touched) { free(slot_of); free(touched); free(eff); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } + slot_of = omega_gpu_host_alloc(nb * sizeof *slot_of); + touched = omega_gpu_host_alloc(nb * sizeof *touched); + if (!slot_of || !touched) { omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(eff); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } memset(slot_of, 0xff, nb * sizeof *slot_of); /* every entry -1 */ } for (uint32_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) { @@ -1277,7 +1278,7 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou /* logical references: every sequence's blocks up to its (truncated) context */ uint32_t total = 0; for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; - uint32_t *tab = calloc((size_t)ns * maxb + ns, sizeof *tab); + uint32_t *tab = omega_gpu_host_calloc((size_t)ns * maxb + ns, sizeof *tab); if (!tab) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } if (resident) { /* the table carries the physical ids; the kernel's block stride is the pool's; the layer @@ -1300,7 +1301,7 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou }; rc = launch(ks, &L, info); if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD); - free(tab); + omega_gpu_host_free(tab); continue; } /* pass 1: assign staged slots. Dedupe keys on the PHYSICAL block id (not the table @@ -1321,11 +1322,11 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou tab[(size_t)ns * maxb + s] = eff[s0 + s]; } uint64_t staged_bytes = (uint64_t)(g ? g : 1) * ly->layer_stride_bytes; - if (staged_bytes > 0xffffffffull) { free(tab); rc = OMEGA_GPU_ATTN_TOO_LARGE; break; } + if (staged_bytes > 0xffffffffull) { omega_gpu_host_free(tab); rc = OMEGA_GPU_ATTN_TOO_LARGE; break; } void *host_tmp = NULL; int stage_rc; uint8_t *staged = stage_target((size_t)staged_bytes, &host_tmp, &stage_rc); - if (!staged) { free(tab); rc = stage_rc; break; } + if (!staged) { omega_gpu_host_free(tab); rc = stage_rc; break; } /* pass 2: copy each staged slot's (physical block, layer) slice exactly once */ if (g_dedupe) { for (uint32_t u = 0; u < g; u++) { @@ -1358,10 +1359,10 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou }; rc = launch(ks, &L, info); if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD); - free(host_tmp); free(tab); + omega_gpu_host_free(host_tmp); omega_gpu_host_free(tab); } UNLOCK(); - free(eff); free(slot_of); free(touched); free(part); + omega_gpu_host_free(eff); omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(part); if (info) info->call_ns = now_ns() - t0; return rc; } @@ -1384,13 +1385,13 @@ int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const float *out, OmegaGpuAttnInfo *info) { if (!q || !pool || !layout || !out || !block_tables || !context_lens || num_seqs == 0) return OMEGA_GPU_ATTN_BAD_ARGS; /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */ - uint32_t **tables = calloc(num_seqs, sizeof *tables); - uint32_t *nb = calloc(num_seqs, sizeof *nb), *cx = calloc(num_seqs, sizeof *cx); - if (!tables || !nb || !cx) { free(tables); free(nb); free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; } + uint32_t **tables = omega_gpu_host_calloc(num_seqs, sizeof *tables); + uint32_t *nb = omega_gpu_host_calloc(num_seqs, sizeof *nb), *cx = omega_gpu_host_calloc(num_seqs, sizeof *cx); + if (!tables || !nb || !cx) { omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; } int rc = OMEGA_GPU_ATTN_OK; for (uint32_t s = 0; s < num_seqs; s++) { cx[s] = context_lens[s] > 0 ? (uint32_t)context_lens[s] : 0; - tables[s] = calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables); + tables[s] = omega_gpu_host_calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables); if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } for (uint32_t b = 0; b < max_blocks_per_seq; b++) { int32_t v = block_tables[(size_t)s * max_blocks_per_seq + b]; @@ -1399,8 +1400,8 @@ int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const } if (rc == OMEGA_GPU_ATTN_OK) rc = paged_core(q, pool, layout, (const uint32_t *const *)tables, nb, cx, num_seqs, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info); - for (uint32_t s = 0; s < num_seqs; s++) free(tables[s]); - free(tables); free(nb); free(cx); + for (uint32_t s = 0; s < num_seqs; s++) omega_gpu_host_free(tables[s]); + omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx); return rc; } diff --git a/src/omega_gpu_elementwise_api.c b/src/omega_gpu_elementwise_api.c index 6002d3ed8..fb821e4f3 100644 --- a/src/omega_gpu_elementwise_api.c +++ b/src/omega_gpu_elementwise_api.c @@ -868,7 +868,7 @@ static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kerne /* One kernel per (op, mutant); the device copy is uploaded once and stays * resident for the process (cut 4b: no per-call code page). */ -typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; NvrmMem code; } Slot; +typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; OmegaGpuMem code; } Slot; static int g_mutant_op; /* 0 = none */ static int g_mutant_level = 1; /* the mutant number built for g_mutant_op (1 math, 2 join dropped, 3 join corrupted) */ static Slot g_cache[8]; diff --git a/src/omega_gpu_fmt.c b/src/omega_gpu_fmt.c new file mode 100644 index 000000000..2652cc1a2 --- /dev/null +++ b/src/omega_gpu_fmt.c @@ -0,0 +1,65 @@ +/* omega_gpu_fmt.c -- see omega_gpu_fmt.h. Freestanding: stdarg only. */ +#include "omega_gpu_fmt.h" +#include +#include + +typedef struct { char *out; size_t cap, n; } Sink; + +static void put(Sink *s, char c) { + if (s->n + 1 < s->cap) s->out[s->n++] = c; +} +static void put_str(Sink *s, const char *p) { + if (!p) p = "(null)"; + while (*p) put(s, *p++); +} +static void put_u(Sink *s, unsigned long long v, unsigned base) { + char tmp[24]; + int i = 0; + do { unsigned d = (unsigned)(v % base); tmp[i++] = (char)(d < 10 ? '0' + d : 'a' + d - 10); v /= base; } while (v); + while (i) put(s, tmp[--i]); +} +static void put_d(Sink *s, long long v) { + if (v < 0) { put(s, '-'); put_u(s, (unsigned long long)(-(v + 1)) + 1ull, 10); } + else put_u(s, (unsigned long long)v, 10); +} + +int omega_gpu_fmt(char *out, size_t cap, const char *fmt, ...) { + Sink s = { out, cap, 0 }; + va_list ap; + if (!out || cap == 0) return 0; + if (!fmt) fmt = ""; + va_start(ap, fmt); + for (const char *p = fmt; *p; p++) { + if (*p != '%') { put(&s, *p); continue; } + const char *start = p++; + int l = 0, z = 0; + if (*p == 'z') { z = 1; p++; } + else while (*p == 'l' && l < 2) { l++; p++; } + switch (*p) { + case 's': put_str(&s, va_arg(ap, const char *)); break; + case 'c': put(&s, (char)va_arg(ap, int)); break; + case 'd': + if (z) put_d(&s, (long long)va_arg(ap, ptrdiff_t)); + else if (l == 2) put_d(&s, va_arg(ap, long long)); + else if (l == 1) put_d(&s, va_arg(ap, long)); + else put_d(&s, va_arg(ap, int)); + break; + case 'u': case 'x': { + unsigned base = *p == 'x' ? 16u : 10u; + if (z) put_u(&s, va_arg(ap, size_t), base); + else if (l == 2) put_u(&s, va_arg(ap, unsigned long long), base); + else if (l == 1) put_u(&s, va_arg(ap, unsigned long), base); + else put_u(&s, va_arg(ap, unsigned int), base); + break; + } + case '%': put(&s, '%'); break; + default: /* unsupported conversion: copy it literally, consume nothing */ + for (const char *q = start; q <= p && *q; q++) put(&s, *q); + if (!*p) p--; + break; + } + } + va_end(ap); + s.out[s.n] = '\0'; + return (int)s.n; +} diff --git a/src/omega_gpu_fmt.h b/src/omega_gpu_fmt.h new file mode 100644 index 000000000..99c903d49 --- /dev/null +++ b/src/omega_gpu_fmt.h @@ -0,0 +1,10 @@ +/* omega_gpu_fmt.h -- bounded message formatting for the freestanding GPU code (native v1 P07 cut C session + * part, aienos#286). The session and the tensor APIs format their error stages with it in both builds, so a + * stage reads the same with or without libc. Conversions: %s %c %d %u %x %ld %lu %lld %llu %zu %%; anything + * else is copied literally. Always NUL-terminates inside cap (cap > 0); truncates, never overflows. Returns + * the number of characters written (without the NUL). */ +#ifndef OMEGA_GPU_FMT_H +#define OMEGA_GPU_FMT_H +#include +int omega_gpu_fmt(char *out, size_t cap, const char *fmt, ...) __attribute__((format(printf, 3, 4))); +#endif diff --git a/src/omega_gpu_matmul_api.c b/src/omega_gpu_matmul_api.c index b9f4944c3..0575bc9c5 100644 --- a/src/omega_gpu_matmul_api.c +++ b/src/omega_gpu_matmul_api.c @@ -15,16 +15,12 @@ */ #include "omega_gpu_matmul_api.h" #include "omega_gpu_session.h" +#include "omega_gpu_fmt.h" #include "omega_blackwell_codegen.h" #include "omega_blackwell_matmul.h" #include "omega_blackwell_qmd.h" #include "omega_blackwell_submit.h" -#include "nvrm.h" -#include -#include -#include #include -#include #define CACHE_SLOTS 8 /* default kernel cache slots; raised only by omega_gpu_matmul_reserve */ #define CACHE_SLOTS_MAX 128 /* storage for the opt-in larger cache (a code buffer is a few KB); Qwen3-4B serving needs 95 */ @@ -35,7 +31,7 @@ struct OmegaGpuTensor { uint32_t k, n, kp, np; - NvrmMem mem; /* kp x np bf16 in fragment order (omega_matmul_frag_pack_b) */ + OmegaGpuMem mem; /* kp x np bf16 in fragment order (omega_matmul_frag_pack_b) */ }; typedef struct { @@ -46,7 +42,7 @@ typedef struct { int mutant; OmegaMatMulSpec spec; OmegaBlackwellKernel kernel; - NvrmMem code; /* resident copy of kernel.code */ + OmegaGpuMem code; /* resident copy of kernel.code */ } CacheSlot; static struct { @@ -69,11 +65,8 @@ static struct { #define FAILAT(s) (omega_gpu_session_set_error(s), 1) const char *omega_gpu_matmul_last_error(void) { return omega_gpu_session_last_error(); } -static uint64_t now_ns(void) { - struct timespec t; - clock_gettime(CLOCK_MONOTONIC, &t); - return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; -} +static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } /* the platform clock (CLOCK_NS) */ +static inline double abs_d(double x) { return x < 0.0 ? -x : x; } static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } @@ -97,8 +90,7 @@ static void cache_clear_locked(void) { for (unsigned i = 0; i < CACHE_SLOTS_MAX; i++) { CacheSlot *s = &g.cache[i]; if (!s->valid) continue; - omega_blackwell_kernel_free(&s->kernel); - omega_gpu_session_free(&s->code); + omega_gpu_session_free(&s->code); /* kernel.code points into it */ memset(s, 0, sizeof *s); } g.cache_next = 0; @@ -254,7 +246,7 @@ static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, uint32_t rt, ui } if (g.sealed) { char e[160]; - snprintf(e, sizeof e, "serving reservation exceeded: matmul kernel kp=%u np=%u grid_x=%u rt=%u ct=%u was not prepared", kp, np, grid_x, rt, ct); + omega_gpu_fmt(e, sizeof e, "serving reservation exceeded: matmul kernel kp=%u np=%u grid_x=%u rt=%u ct=%u was not prepared", kp, np, grid_x, rt, ct); omega_gpu_session_set_error(e); return OMEGA_GPU_MATMUL_TOO_LARGE; } @@ -278,14 +270,22 @@ static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, uint32_t rt, ui uint32_t unroll = blocked ? omega_matmul_frag_block_unroll(kp, rt, ct) : g.unroll ? g.unroll : omega_matmul_frag_unroll(kp); /* the mutant drops the last pass, so it needs two: halve the unroll of a one-pass shape */ if (g.mutant && (blocked || !g.unroll)) while (unroll > 1 && kp / 16u / unroll < 2) unroll /= 2; - int cg = blocked ? omega_blackwell_codegen_matmul_frag_block(&spec, grid_x, unroll, rt, ct, g.mutant, &kernel) - : omega_blackwell_codegen_matmul_frag(&spec, grid_x, unroll, g.mutant, &kernel); - if (cg != 0 || !kernel.code || kernel.code_size == 0) - return OMEGA_GPU_MATMUL_CODEGEN_FAIL; - NvrmMem code; - if (omega_gpu_session_alloc_code(kernel.code_size, &code) != 0) { omega_blackwell_kernel_free(&kernel); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - memcpy(code.cpu, kernel.code, kernel.code_size); - if (s->valid) { omega_blackwell_kernel_free(&s->kernel); omega_gpu_session_free(&s->code); } + /* P07 cut C: the program is built in host memory and encoded straight into the device code buffer, sized + * exactly (omega_bw_program_code_bytes: the bytes the allocating generators produce, cut A.2 proves them + * identical). kernel.code then points into that buffer and owns nothing. */ + BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); + if (!prog) { omega_gpu_session_set_error("matmul codegen: host memory"); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } + int cg = blocked ? omega_blackwell_codegen_matmul_frag_block_prog(&spec, grid_x, unroll, rt, ct, g.mutant, prog) + : omega_blackwell_codegen_matmul_frag_prog(&spec, grid_x, unroll, g.mutant, prog); + const size_t need = cg == 0 ? omega_bw_program_code_bytes(prog) : 0; + if (cg != 0 || need == 0) { omega_gpu_host_free(prog); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } + OmegaGpuMem code; + if (omega_gpu_session_alloc_code(need, &code) != 0) { omega_gpu_host_free(prog); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + cg = omega_blackwell_kernel_encode_into(prog, code.cpu, need, &kernel); + omega_gpu_host_free(prog); + if (cg != 0 || !kernel.code || kernel.code_size != need) { omega_gpu_session_free(&code); return OMEGA_GPU_MATMUL_CODEGEN_FAIL; } + if (omega_gpu_session_sync_to_gpu(&code) != 0) { omega_gpu_session_free(&code); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + if (s->valid) omega_gpu_session_free(&s->code); s->valid = true; s->pinned = false; s->kp = kp; s->np = np; s->grid_x = grid_x; s->rt = rt; s->ct = ct; s->mutant = g.mutant; s->spec = spec; s->kernel = kernel; s->code = code; *out = s; *hit = false; @@ -318,27 +318,27 @@ int omega_gpu_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, Omeg if (out) *out = NULL; if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; - OmegaGpuTensor *t = calloc(1, sizeof *t); + OmegaGpuTensor *t = omega_gpu_host_calloc(1, sizeof *t); if (!t) return OMEGA_GPU_MATMUL_BAD_ARGS; t->k = k; t->n = n; t->kp = round_up(k, OMEGA_GPU_MATMUL_TILE_K); t->np = round_up(n, OMEGA_GPU_MATMUL_TILE_N); /* fragment order (omega_matmul_frag_pack_b), packed on the host FRAG_PACK_TILES column * tiles at a time and copied in order into the uncached device buffer */ const uint32_t nt = t->np / 8u; - uint16_t *h = malloc((size_t)FRAG_PACK_TILES * t->kp * 8u * sizeof *h); - if (!h) { free(t); return OMEGA_GPU_MATMUL_BAD_ARGS; } + uint16_t *h = omega_gpu_host_alloc((size_t)FRAG_PACK_TILES * t->kp * 8u * sizeof *h); + if (!h) { omega_gpu_host_free(t); return OMEGA_GPU_MATMUL_BAD_ARGS; } int rc = OMEGA_GPU_MATMUL_OK; omega_gpu_session_lock(); if (!dev_open_locked() || omega_gpu_session_alloc((size_t)t->kp * t->np * 2u, &t->mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; omega_gpu_session_unlock(); - if (rc != OMEGA_GPU_MATMUL_OK) { free(h); free(t); return rc; } + if (rc != OMEGA_GPU_MATMUL_OK) { omega_gpu_host_free(h); omega_gpu_host_free(t); return rc; } uint16_t *d = t->mem.cpu; for (uint32_t nt0 = 0; nt0 < nt; nt0 += FRAG_PACK_TILES) { const uint32_t nt1 = nt - nt0 < FRAG_PACK_TILES ? nt : nt0 + FRAG_PACK_TILES; omega_matmul_frag_pack_b(b, k, n, t->kp, nt0, nt1, h); memcpy(&d[(size_t)nt0 * t->kp * 8u], h, (size_t)(nt1 - nt0) * t->kp * 8u * sizeof *h); } - free(h); - __asm__ volatile("dsb sy" ::: "memory"); + omega_gpu_host_free(h); + if (omega_gpu_session_sync_to_gpu(&t->mem) != 0) { omega_gpu_tensor_free(t); return OMEGA_GPU_MATMUL_CHIP_FAIL; } *out = t; return OMEGA_GPU_MATMUL_OK; } @@ -348,11 +348,11 @@ int omega_gpu_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpu if (!b || !out || k == 0 || n == 0) return OMEGA_GPU_MATMUL_BAD_ARGS; if (k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; size_t cnt = (size_t)k * n; - uint16_t *h = malloc(cnt * sizeof *h); + uint16_t *h = omega_gpu_host_alloc(cnt * sizeof *h); if (!h) return OMEGA_GPU_MATMUL_BAD_ARGS; for (size_t i = 0; i < cnt; i++) h[i] = omega_fp32_to_bf16(b[i]); int rc = omega_gpu_tensor_upload_bf16(k, n, h, out); - free(h); + omega_gpu_host_free(h); return rc; } @@ -361,7 +361,7 @@ void omega_gpu_tensor_free(OmegaGpuTensor *t) { omega_gpu_session_lock(); omega_gpu_session_free(&t->mem); omega_gpu_session_unlock(); - free(t); + omega_gpu_host_free(t); } /* ---- the matmul ---- */ @@ -381,7 +381,7 @@ static int matmul_core(uint32_t m, const uint16_t *a16, const float *a32, const info->m = m; info->k = k; info->n = n; info->padded_m = mp; info->padded_n = np; info->padded_k = kp; info->k_slices = 1; info->rows_per_call = rows_per_launch; info->grid_x = grid_x; info->grid_y = grid_y_full; info->resident = true; info->kernel_cache_hit = true; - strncpy(info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)", sizeof info->target_chip - 1); + (void)omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "%s", "NVIDIA DGX Spark (Grace Blackwell GB10)"); info->sm_architecture = 121; } if (g.sealed && !(g.a_buf.reserved && g.c_buf.reserved)) { @@ -421,7 +421,7 @@ static int matmul_core(uint32_t m, const uint16_t *a16, const float *a32, const * word was three passes over m x np (12.6 MB at m = 128, n = 24576: about 2 ms per prefill call, 2026-10-12). */ float *cd = g.c_buf.mem.cpu; omega_matmul_result_sentinels(cd, m, n, np, POISON_F32, 1); - __asm__ volatile("dsb sy" ::: "memory"); + if (omega_gpu_session_sync_to_gpu(&g.a_buf.mem) != 0 || omega_gpu_session_sync_to_gpu(&g.c_buf.mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; for (uint32_t r0 = 0; r0 < mp && rc == OMEGA_GPU_MATMUL_OK; r0 += rows_per_launch) { uint32_t rows = mp - r0 < rows_per_launch ? mp - r0 : rows_per_launch; @@ -434,6 +434,7 @@ static int matmul_core(uint32_t m, const uint16_t *a16, const float *a32, const grid_x, grid_y, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL); if (info) info->chip_calls++; } + if (rc == OMEGA_GPU_MATMUL_OK && omega_gpu_session_sync_to_cpu(&g.c_buf.mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; if (rc == OMEGA_GPU_MATMUL_OK) { /* the chip must have stored every fragment tile with a real output word (sentinel check) */ size_t unchanged = omega_matmul_result_sentinels(cd, m, n, np, POISON_F32, 0); @@ -480,9 +481,9 @@ static void oracle(uint32_t m, uint32_t k, uint32_t n, const uint16_t *a, const double acc = 0.0, scale = 0.0; for (uint32_t t = 0; t < k; t++) { double p = (double)omega_bf16_to_fp32(a[(size_t)i * k + t]) * (double)omega_bf16_to_fp32(b[(size_t)t * n + j]); - acc += p; scale += fabs(p); + acc += p; scale += abs_d(p); } - double d = fabs(acc - (double)c[(size_t)i * n + j]); + double d = abs_d(acc - (double)c[(size_t)i * n + j]); double rel = d / (scale > 1e-6 ? scale : 1e-6); if ((float)d > max_abs) max_abs = (float)d; if ((float)rel > max_rel) max_rel = (float)rel; @@ -525,13 +526,13 @@ int omega_gpu_matmul_f32(uint32_t m, uint32_t k, uint32_t n, if (m > OMEGA_BW_MATMUL_MAX_M || k > OMEGA_BW_MATMUL_MAX_K || n > OMEGA_BW_MATMUL_MAX_N) return OMEGA_GPU_MATMUL_TOO_LARGE; size_t na = (size_t)m * k, nb = (size_t)k * n; - uint16_t *ab = malloc(na * sizeof *ab); - uint16_t *bb = malloc(nb * sizeof *bb); - if (!ab || !bb) { free(ab); free(bb); return OMEGA_GPU_MATMUL_BAD_ARGS; } + uint16_t *ab = omega_gpu_host_alloc(na * sizeof *ab); + uint16_t *bb = omega_gpu_host_alloc(nb * sizeof *bb); + if (!ab || !bb) { omega_gpu_host_free(ab); omega_gpu_host_free(bb); return OMEGA_GPU_MATMUL_BAD_ARGS; } for (size_t i = 0; i < na; i++) ab[i] = omega_fp32_to_bf16(a[i]); for (size_t i = 0; i < nb; i++) bb[i] = omega_fp32_to_bf16(b[i]); int rc = omega_gpu_matmul_bf16(m, k, n, ab, bb, c, info); - free(ab); - free(bb); + omega_gpu_host_free(ab); + omega_gpu_host_free(bb); return rc; } diff --git a/src/omega_gpu_platform.c b/src/omega_gpu_platform.c index a795e0c13..79f43c94a 100644 --- a/src/omega_gpu_platform.c +++ b/src/omega_gpu_platform.c @@ -18,6 +18,7 @@ static const char *const REFUSAL_NAMES[OMEGA_GPU_PLAT_REFUSAL_COUNT] = { "REFUSED_CACHE_POLICY", "REFUSED_LIMIT", "REFUSED_BUSY", + "REFUSED_DEVICE", }; const char *omega_gpu_platform_refusal_name(int refusal) @@ -51,13 +52,19 @@ static int svc(uint32_t services, uint32_t bit, int present_all, int present_any } int omega_gpu_platform_check(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps) +{ + return omega_gpu_platform_check_for(p, caps, OMEGA_GPU_SVC_REQUIRED_V1); +} + +int omega_gpu_platform_check_for(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps, uint32_t required) { int rc; uint32_t s; if (!p || !caps) return OMEGA_GPU_PLAT_REFUSED_ARGS; s = caps->services; if (s & ~OMEGA_GPU_SVC_ALL) return OMEGA_GPU_PLAT_REFUSED_ARGS; - if ((s & OMEGA_GPU_SVC_REQUIRED_V1) != OMEGA_GPU_SVC_REQUIRED_V1) return OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE; + if (required & ~OMEGA_GPU_SVC_ALL) return OMEGA_GPU_PLAT_REFUSED_ARGS; + if ((s & required) != required) return OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE; if ((rc = svc(s, OMEGA_GPU_SVC_TIME, p->time_now_ms != 0, p->time_now_ms != 0)) != 0) return rc; if ((rc = svc(s, OMEGA_GPU_SVC_WAIT, p->wait_ms != 0, p->wait_ms != 0)) != 0) return rc; if ((rc = svc(s, OMEGA_GPU_SVC_LOCK, p->lock != 0 && p->unlock != 0, p->lock != 0 || p->unlock != 0)) != 0) @@ -71,8 +78,19 @@ int omega_gpu_platform_check(const OmegaGpuPlatform *p, const OmegaGpuPlatformCa if ((rc = svc(s, OMEGA_GPU_SVC_SYNC, p->sync_cpu_to_gpu != 0 && p->sync_gpu_to_cpu != 0, p->sync_cpu_to_gpu != 0 || p->sync_gpu_to_cpu != 0)) != 0) return rc; - if ((rc = svc(s, OMEGA_GPU_SVC_COMPLETION, p->wait_word != 0, p->wait_word != 0)) != 0) return rc; + if ((rc = svc(s, OMEGA_GPU_SVC_COMPLETION, p->poll_word != 0, p->poll_word != 0)) != 0) return rc; if ((rc = svc(s, OMEGA_GPU_SVC_IRQ, p->irq_wait != 0, p->irq_wait != 0)) != 0) return rc; + if ((rc = svc(s, OMEGA_GPU_SVC_DEVICE, p->device_open != 0 && p->device_close != 0 && p->diag_text != 0, + p->device_open != 0 || p->device_close != 0 || p->diag_text != 0)) != 0) + return rc; + if ((rc = svc(s, OMEGA_GPU_SVC_QUEUE, + p->queue_open != 0 && p->queue_close != 0 && p->queue_submit != 0 && p->queue_retire != 0, + p->queue_open != 0 || p->queue_close != 0 || p->queue_submit != 0 || p->queue_retire != 0)) != 0) + return rc; + if ((rc = svc(s, OMEGA_GPU_SVC_CLOCK_NS, p->time_now_ns != 0, p->time_now_ns != 0)) != 0) return rc; + if ((rc = svc(s, OMEGA_GPU_SVC_HOST_MEM, p->host_alloc != 0 && p->host_free != 0, + p->host_alloc != 0 || p->host_free != 0)) != 0) + return rc; return OMEGA_GPU_PLAT_OK; } diff --git a/src/omega_gpu_platform.h b/src/omega_gpu_platform.h index daca3c4cf..dedc4c669 100644 --- a/src/omega_gpu_platform.h +++ b/src/omega_gpu_platform.h @@ -39,7 +39,7 @@ #include #define OMEGA_GPU_PLATFORM_ABI_MAJOR 1u -#define OMEGA_GPU_PLATFORM_ABI_MINOR 0u +#define OMEGA_GPU_PLATFORM_ABI_MINOR 1u /* 1.1 (P07 cut C session part): DEVICE, QUEUE, CLOCK_NS, HOST_MEM; COMPLETION is poll_word */ /* ---- typed handles ------------------------------------------------------ */ @@ -95,12 +95,21 @@ enum { OMEGA_GPU_SVC_MMIO = 1u << 3, /* bounded register access by device handle and region */ OMEGA_GPU_SVC_DMA = 1u << 4, /* device-visible memory with CPU view, GPU VA and bus address */ OMEGA_GPU_SVC_SYNC = 1u << 5, /* explicit CPU<->GPU visibility (cache maintenance, flush) */ - OMEGA_GPU_SVC_COMPLETION = 1u << 6, /* wait on an uncached word (polling) */ + OMEGA_GPU_SVC_COMPLETION = 1u << 6, /* POLL an uncached word (poll_word); polling is never an interrupt */ OMEGA_GPU_SVC_IRQ = 1u << 7, /* real device interrupt wait; polling never counts */ OMEGA_GPU_SVC_REQUIRED_V1 = OMEGA_GPU_SVC_TIME | OMEGA_GPU_SVC_WAIT | OMEGA_GPU_SVC_LOCK | OMEGA_GPU_SVC_MMIO | OMEGA_GPU_SVC_DMA | OMEGA_GPU_SVC_SYNC | OMEGA_GPU_SVC_COMPLETION, - OMEGA_GPU_SVC_ALL = (1u << 8) - 1u + /* ABI 1.1: what the persistent GPU session (src/omega_gpu_session.c) needs on top of v1 */ + OMEGA_GPU_SVC_DEVICE = 1u << 8, /* open / close one device context, driver text of the last failure */ + OMEGA_GPU_SVC_QUEUE = 1u << 9, /* submission queue over a BUF_QUEUE ring: open, submit, retire, close */ + OMEGA_GPU_SVC_CLOCK_NS = 1u << 10, /* monotonic nanosecond clock (launch timing) */ + OMEGA_GPU_SVC_HOST_MEM = 1u << 11, /* CPU-only memory for tables and staging (never device-visible) */ + OMEGA_GPU_SVC_REQUIRED_SESSION = OMEGA_GPU_SVC_TIME | OMEGA_GPU_SVC_WAIT | OMEGA_GPU_SVC_LOCK | + OMEGA_GPU_SVC_DMA | OMEGA_GPU_SVC_SYNC | OMEGA_GPU_SVC_COMPLETION | + OMEGA_GPU_SVC_DEVICE | OMEGA_GPU_SVC_QUEUE | OMEGA_GPU_SVC_CLOCK_NS | + OMEGA_GPU_SVC_HOST_MEM, + OMEGA_GPU_SVC_ALL = (1u << 12) - 1u }; typedef struct { @@ -131,11 +140,15 @@ typedef enum { OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY, /* host-polled buffer asked to be GPU-cached */ OMEGA_GPU_PLAT_REFUSED_LIMIT, /* a capability limit would be exceeded */ OMEGA_GPU_PLAT_REFUSED_BUSY, /* concurrency limit reached */ + OMEGA_GPU_PLAT_REFUSED_DEVICE, /* 1.1: the device or its driver refused (diag_text says why) */ OMEGA_GPU_PLAT_REFUSAL_COUNT } OmegaGpuPlatformRefusal; const char *omega_gpu_platform_refusal_name(int refusal); /* static strings, never NULL */ +/* poll_word result when the word did not reach the value in time (not a refusal: nothing was wrong with the call). */ +#define OMEGA_GPU_POLL_TIMED_OUT 100 + /* ---- the platform service table ----------------------------------------- */ typedef struct { @@ -155,11 +168,33 @@ typedef struct { /* SYNC: explicit visibility over a byte range of one buffer. */ int (*sync_cpu_to_gpu)(void *ctx, OmegaGpuBufferHandle buf, uint64_t offset, uint64_t len); int (*sync_gpu_to_cpu)(void *ctx, OmegaGpuBufferHandle buf, uint64_t offset, uint64_t len); - /* COMPLETION: poll one uncached 32-bit word until it equals expected or timeout_ms passes. */ - int (*wait_word)(void *ctx, OmegaGpuBufferHandle buf, uint64_t offset, uint32_t expected, + /* COMPLETION, by POLLING (never an interrupt): read one GPU-uncached 32-bit word of a HOST_POLLED buffer until + * it has reached expected in serial-number order, (int32_t)(word - expected) >= 0 (the m16_native_wait_marker + * rule), or timeout_ms passes. 0 reached, OMEGA_GPU_POLL_TIMED_OUT not reached, else a refusal. *observed is + * the last value read. A timeout says nothing about the device: the work may still be running. */ + int (*poll_word)(void *ctx, OmegaGpuBufferHandle buf, uint64_t offset, uint32_t expected, uint64_t timeout_ms, uint32_t *observed); /* IRQ: NULL unless OMEGA_GPU_SVC_IRQ is claimed. */ int (*irq_wait)(void *ctx, OmegaGpuDeviceHandle dev, uint64_t timeout_ms); + /* ---- ABI 1.1 ---- */ + /* DEVICE: open the device context with this ordinal (0 = the one GB10), close it. Closing makes every buffer and + * queue handle of the device stale. diag_text: driver text of the most recent failure, "" if none, never NULL. */ + int (*device_open)(void *ctx, uint32_t ordinal, OmegaGpuDeviceHandle *out); + int (*device_close)(void *ctx, OmegaGpuDeviceHandle dev); + const char *(*diag_text)(void *ctx); + /* QUEUE: a submission queue whose ring is a BUF_QUEUE buffer of the same device. queue_submit copies nwords method + * words into the ring and rings the doorbell (one GPFIFO entry); queue_retire marks every submitted entry consumed + * and is called only after the caller saw that work complete. A refused queue_submit rang no doorbell: nothing of it is in + * flight (m16_native_submit_methods fails before nvrm_ring). */ + int (*queue_open)(void *ctx, OmegaGpuDeviceHandle dev, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *out); + int (*queue_close)(void *ctx, OmegaGpuQueueHandle q); + int (*queue_submit)(void *ctx, OmegaGpuQueueHandle q, const uint32_t *words, uint32_t nwords); + int (*queue_retire)(void *ctx, OmegaGpuQueueHandle q); + /* CLOCK_NS */ + uint64_t (*time_now_ns)(void *ctx); + /* HOST_MEM: NULL on refusal; host_free(NULL) is a no-op. */ + void *(*host_alloc)(void *ctx, size_t bytes); + void (*host_free)(void *ctx, void *p); } OmegaGpuPlatform; /* ---- contract checks (pure, freestanding) -------------------------------- */ @@ -172,6 +207,9 @@ int omega_gpu_platform_negotiate(const OmegaGpuPlatformCaps *provided, const Ome * outside caps->services is NULL (no undeclared service, no fallback); the * v1 required set is present. */ int omega_gpu_platform_check(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps); +/* The same, requiring the service set `required` (for example OMEGA_GPU_SVC_REQUIRED_SESSION) instead of the v1 set. + * omega_gpu_platform_check(p, caps) is omega_gpu_platform_check_for(p, caps, OMEGA_GPU_SVC_REQUIRED_V1). */ +int omega_gpu_platform_check_for(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps, uint32_t required); /* Buffer descriptor rules: kind known, length non-zero and within caps, * rights non-empty and consistent with the kind, host-polled means @@ -180,7 +218,7 @@ int omega_gpu_platform_check_buffer(const OmegaGpuBufferDesc *d, const OmegaGpuP /* ---- handle table (index + generation) ----------------------------------- */ -#define OMEGA_GPU_HANDLE_SLOTS 64u +#define OMEGA_GPU_HANDLE_SLOTS 1024u /* 1.1: a serving session holds one buffer per weight tensor (Qwen3-8B: ~260) */ typedef struct { uint32_t generation[OMEGA_GPU_HANDLE_SLOTS]; /* next generation to issue for the slot; starts at 1 */ diff --git a/src/omega_gpu_platform_linux.c b/src/omega_gpu_platform_linux.c new file mode 100644 index 000000000..0aaae7386 --- /dev/null +++ b/src/omega_gpu_platform_linux.c @@ -0,0 +1,343 @@ +/* omega_gpu_platform_linux.c -- Linux REFERENCE implementation of OmegaGpuPlatform 1.1. REFERENCE ONLY: see the + * header. Every driver call here is the one src/omega_gpu_session.c made directly before P07 cut C, in the same + * order, so the launch path on GB10 under Linux is unchanged: + * device_open = nvrm_open + m16_native_create_channel (session open, before the four session buffers) + * dma_alloc = nvrm_alloc_gpu_uncached (every session / API buffer) + * dma_free = nvrm_free + * queue_open = ctx.pb_mem = the ring buffer (m16_native_enqueue_methods copies methods there) + * queue_submit = m16_native_submit_methods + * queue_retire = nvrm_retire(&rm, rm.put) (after both markers landed) + * poll_word = m16_native_wait_marker (>= serial compare, 50 us sleep-poll) + * sync_* = dsb sy (the barrier the session issued itself) + * device_close = m16_native_close (nvrm_close) + */ +#include "omega_gpu_platform_linux.h" + +#include "m16_native.h" +#include "nvrm.h" + +#include +#include +#include +#include +#include + +#define LINUX_REF_BUFFERS (OMEGA_GPU_HANDLE_SLOTS - 2u) /* one slot each for the device and the queue */ + +typedef struct { + pthread_mutex_t mu; /* table, device and diagnostics */ + pthread_mutex_t locks[OMEGA_GPU_PLATFORM_LINUX_LOCKS]; + int ready; + OmegaGpuHandleTable t; + NvrmMem mem[OMEGA_GPU_HANDLE_SLOTS]; + uint32_t rights[OMEGA_GPU_HANDLE_SLOTS]; + M16NativeContext m16; + OmegaGpuDeviceHandle dev; /* generation 0 = closed */ + OmegaGpuQueueHandle queue; + char diag[320]; +} LinuxRef; + +static LinuxRef g_ref = { + .mu = PTHREAD_MUTEX_INITIALIZER, + .locks = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER}, +}; + +static const OmegaGpuPlatformCaps g_caps = { + .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, + .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, + .services = OMEGA_GPU_SVC_REQUIRED_SESSION, /* no MMIO (RM owns the registers), no IRQ (polling only) */ + .max_devices = 1, + .max_buffers = LINUX_REF_BUFFERS, + .max_queues = 1, + .max_inflight = 1, + .max_buffer_bytes = 1ull << 37, /* 128 GiB: the whole unified pool */ + .max_total_bytes = 1ull << 37, +}; + +static void ref_lock(LinuxRef *r) { + pthread_mutex_lock(&r->mu); + if (!r->ready) { omega_gpu_handles_init(&r->t); r->ready = 1; } +} +static void ref_unlock(LinuxRef *r) { pthread_mutex_unlock(&r->mu); } + +/* Records why the call failed; REFUSED_DEVICE carries the driver text (Nvrm.err). Called with r->mu held. */ +static int refuse(LinuxRef *r, int rc, const char *stage) { + if (rc == OMEGA_GPU_PLAT_REFUSED_DEVICE) + snprintf(r->diag, sizeof r->diag, "%s: %s", stage, r->m16.rm.err[0] ? r->m16.rm.err : "(no driver text)"); + else + snprintf(r->diag, sizeof r->diag, "%s: %s", stage, omega_gpu_platform_refusal_name(rc)); + return rc; +} + +static int dev_ok(LinuxRef *r, OmegaGpuDeviceHandle d) { + return omega_gpu_handles_check(&r->t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); +} + +/* A live buffer handle of any buffer kind; *kind gets it. */ +static int buf_ok(LinuxRef *r, OmegaGpuBufferHandle b, uint32_t *kind) { + if (b.index >= OMEGA_GPU_HANDLE_SLOTS || b.generation == 0u) return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; + if (!r->t.live[b.index] || r->t.generation[b.index] != b.generation) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; + const uint32_t k = r->t.kind[b.index]; + if (k != OMEGA_GPU_HANDLE_BUF_DATA && k != OMEGA_GPU_HANDLE_BUF_CODE && k != OMEGA_GPU_HANDLE_BUF_QUEUE) + return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; + if (kind) *kind = k; + return OMEGA_GPU_PLAT_OK; +} + +static int range_ok(LinuxRef *r, OmegaGpuBufferHandle b, uint64_t off, uint64_t len) { + const uint64_t size = r->mem[b.index].size; + return (len == 0u || off > size || len > size - off) ? OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH : OMEGA_GPU_PLAT_OK; +} + +static uint64_t ref_now_ns(void *ctx) { + (void)ctx; + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; +} +static uint64_t ref_now_ms(void *ctx) { return ref_now_ns(ctx) / 1000000ull; } + +static int ref_wait_ms(void *ctx, uint64_t ms) { + (void)ctx; + struct timespec t = {.tv_sec = (time_t)(ms / 1000u), .tv_nsec = (long)(ms % 1000u) * 1000000L}; + while (nanosleep(&t, &t) != 0) {} + return OMEGA_GPU_PLAT_OK; +} + +static int ref_lock_id(void *ctx, uint32_t id) { + LinuxRef *r = ctx; + if (id >= OMEGA_GPU_PLATFORM_LINUX_LOCKS) return OMEGA_GPU_PLAT_REFUSED_ARGS; + return pthread_mutex_lock(&r->locks[id]) == 0 ? OMEGA_GPU_PLAT_OK : OMEGA_GPU_PLAT_REFUSED_BUSY; +} +static int ref_unlock_id(void *ctx, uint32_t id) { + LinuxRef *r = ctx; + if (id >= OMEGA_GPU_PLATFORM_LINUX_LOCKS) return OMEGA_GPU_PLAT_REFUSED_ARGS; + return pthread_mutex_unlock(&r->locks[id]) == 0 ? OMEGA_GPU_PLAT_OK : OMEGA_GPU_PLAT_REFUSED_ARGS; +} + +static int ref_device_open(void *ctx, uint32_t ordinal, OmegaGpuDeviceHandle *out) { + LinuxRef *r = ctx; + int rc; + if (!out) return OMEGA_GPU_PLAT_REFUSED_ARGS; + memset(out, 0, sizeof *out); + ref_lock(r); + if (ordinal != 0u) { rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_ARGS, "device_open"); goto out; } + if (r->dev.generation != 0u) { rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_LIMIT, "device_open (already open)"); goto out; } + memset(&r->m16, 0, sizeof r->m16); + /* nvrm_open directly (m16_native_open is memset + nvrm_open + nvrm_close on failure) so the driver's own + * failure text survives into the stage name, as the session did before cut C. */ + if (nvrm_open(&r->m16.rm) != 0) { + rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, "nvrm_open"); + (void)nvrm_close(&r->m16.rm); + goto out; + } + if (m16_native_create_channel(&r->m16) != 0) { + rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, "m16_native_create_channel"); + (void)m16_native_close(&r->m16); + goto out; + } + rc = omega_gpu_handles_open(&r->t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); + if (rc != OMEGA_GPU_PLAT_OK) { (void)m16_native_close(&r->m16); rc = refuse(r, rc, "device_open"); goto out; } + r->dev = *out; + r->diag[0] = '\0'; +out: + ref_unlock(r); + return rc; +} + +static int ref_device_close(void *ctx, OmegaGpuDeviceHandle dev) { + LinuxRef *r = ctx; + ref_lock(r); + int rc = dev_ok(r, dev); + if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "device_close"); ref_unlock(r); return rc; } + /* Every handle of the device goes stale. The RM client close below releases the driver objects; buffers the + * caller did not free are not unmapped here, exactly as before cut C. */ + for (uint32_t i = 0; i < OMEGA_GPU_HANDLE_SLOTS; i++) { + if (!r->t.live[i] || i == dev.index) continue; + (void)omega_gpu_handles_close(&r->t, i, r->t.generation[i], r->t.kind[i]); + memset(&r->mem[i], 0, sizeof r->mem[i]); + r->rights[i] = 0; + } + (void)omega_gpu_handles_close(&r->t, dev.index, dev.generation, OMEGA_GPU_HANDLE_DEVICE); + memset(&r->dev, 0, sizeof r->dev); + memset(&r->queue, 0, sizeof r->queue); + (void)m16_native_close(&r->m16); + ref_unlock(r); + return OMEGA_GPU_PLAT_OK; +} + +static const char *ref_diag_text(void *ctx) { return ((LinuxRef *)ctx)->diag; } + +static int ref_dma_alloc(void *ctx, OmegaGpuDeviceHandle dev, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *out, + OmegaCpuView *cpu, OmegaGpuVa *gpu, OmegaGpuBusAddr *bus) { + LinuxRef *r = ctx; + if (!desc || !out || !cpu || !gpu) return OMEGA_GPU_PLAT_REFUSED_ARGS; + memset(out, 0, sizeof *out); memset(cpu, 0, sizeof *cpu); memset(gpu, 0, sizeof *gpu); + if (bus) memset(bus, 0, sizeof *bus); + ref_lock(r); + int rc = dev_ok(r, dev); + if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_platform_check_buffer(desc, &g_caps); + /* everything here is GPU-uncached; a cached buffer would need flushes nobody issues */ + if (rc == OMEGA_GPU_PLAT_OK && desc->gpu_cache != OMEGA_GPU_CACHE_GPU_UNCACHED) rc = OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY; + if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "dma_alloc"); ref_unlock(r); return rc; } + uint32_t idx = 0, gen = 0; + rc = omega_gpu_handles_open(&r->t, desc->kind, desc->bytes, LINUX_REF_BUFFERS, g_caps.max_total_bytes, &idx, &gen); + if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "dma_alloc"); ref_unlock(r); return rc; } + NvrmMem m; + if (nvrm_alloc_gpu_uncached(&r->m16.rm, desc->bytes, &m) != 0) { + (void)omega_gpu_handles_close(&r->t, idx, gen, desc->kind); /* this slot never got memory: its generation moves on */ + rc = refuse(r, OMEGA_GPU_PLAT_REFUSED_DEVICE, "nvrm_alloc_gpu_uncached"); + ref_unlock(r); + return rc; + } + r->mem[idx] = m; + r->rights[idx] = desc->rights; + out->index = idx; out->generation = gen; + cpu->ptr = m.cpu; cpu->len = (size_t)m.size; + gpu->va = m.va; + ref_unlock(r); + return OMEGA_GPU_PLAT_OK; +} + +static int ref_dma_free(void *ctx, OmegaGpuBufferHandle b) { + LinuxRef *r = ctx; + uint32_t kind = 0; + ref_lock(r); + int rc = buf_ok(r, b, &kind); + if (rc == OMEGA_GPU_PLAT_OK && r->queue.generation != 0u && r->m16.pb_mem.handle == r->mem[b.index].handle && + r->m16.pb_mem.cpu == r->mem[b.index].cpu) + rc = OMEGA_GPU_PLAT_REFUSED_BUSY; /* the open queue still uses it as its ring */ + if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "dma_free"); ref_unlock(r); return rc; } + (void)nvrm_free(&r->m16.rm, &r->mem[b.index]); + (void)omega_gpu_handles_close(&r->t, b.index, b.generation, kind); + memset(&r->mem[b.index], 0, sizeof r->mem[b.index]); + r->rights[b.index] = 0; + ref_unlock(r); + return OMEGA_GPU_PLAT_OK; +} + +static void barrier(void) { +#if defined(__aarch64__) + __asm__ volatile("dsb sy" ::: "memory"); +#else + __sync_synchronize(); +#endif +} + +static int ref_sync(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint64_t len, const char *stage) { + LinuxRef *r = ctx; + ref_lock(r); + int rc = buf_ok(r, b, NULL); + if (rc == OMEGA_GPU_PLAT_OK) rc = range_ok(r, b, off, len); + if (rc != OMEGA_GPU_PLAT_OK) rc = refuse(r, rc, stage); + ref_unlock(r); + if (rc == OMEGA_GPU_PLAT_OK) barrier(); /* uncached system memory: a full barrier is the whole sync */ + return rc; +} +static int ref_sync_to_gpu(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint64_t len) { return ref_sync(ctx, b, off, len, "sync_cpu_to_gpu"); } +static int ref_sync_to_cpu(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint64_t len) { return ref_sync(ctx, b, off, len, "sync_gpu_to_cpu"); } + +static int ref_poll_word(void *ctx, OmegaGpuBufferHandle b, uint64_t off, uint32_t expected, uint64_t timeout_ms, uint32_t *observed) { + LinuxRef *r = ctx; + ref_lock(r); + int rc = buf_ok(r, b, NULL); + if (rc == OMEGA_GPU_PLAT_OK && !(r->rights[b.index] & OMEGA_GPU_RIGHT_HOST_POLLED)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; + if (rc == OMEGA_GPU_PLAT_OK && (off & 3u)) rc = OMEGA_GPU_PLAT_REFUSED_ARGS; + if (rc == OMEGA_GPU_PLAT_OK) rc = range_ok(r, b, off, 4u); + if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "poll_word"); ref_unlock(r); return rc; } + volatile uint32_t *w = (volatile uint32_t *)((uint8_t *)r->mem[b.index].cpu + off); + ref_unlock(r); /* never hold the table lock while polling */ + rc = m16_native_wait_marker(w, expected, timeout_ms) == 0 ? OMEGA_GPU_PLAT_OK : OMEGA_GPU_POLL_TIMED_OUT; + if (observed) *observed = *w; + return rc; +} + +static int queue_ok(LinuxRef *r, OmegaGpuQueueHandle q) { + return omega_gpu_handles_check(&r->t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); +} + +static int ref_queue_open(void *ctx, OmegaGpuDeviceHandle dev, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *out) { + LinuxRef *r = ctx; + uint32_t kind = 0; + if (!out) return OMEGA_GPU_PLAT_REFUSED_ARGS; + memset(out, 0, sizeof *out); + ref_lock(r); + int rc = dev_ok(r, dev); + if (rc == OMEGA_GPU_PLAT_OK) rc = buf_ok(r, ring, &kind); + if (rc == OMEGA_GPU_PLAT_OK && kind != OMEGA_GPU_HANDLE_BUF_QUEUE) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; + if (rc == OMEGA_GPU_PLAT_OK && r->queue.generation != 0u) rc = OMEGA_GPU_PLAT_REFUSED_LIMIT; + if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_handles_open(&r->t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &out->index, &out->generation); + if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "queue_open"); ref_unlock(r); return rc; } + r->m16.pb_mem = r->mem[ring.index]; /* m16_native_enqueue_methods copies the method stream here */ + r->queue = *out; + ref_unlock(r); + return OMEGA_GPU_PLAT_OK; +} + +static int ref_queue_close(void *ctx, OmegaGpuQueueHandle q) { + LinuxRef *r = ctx; + ref_lock(r); + int rc = queue_ok(r, q); + if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_handles_close(&r->t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); + if (rc != OMEGA_GPU_PLAT_OK) { rc = refuse(r, rc, "queue_close"); ref_unlock(r); return rc; } + memset(&r->queue, 0, sizeof r->queue); + memset(&r->m16.pb_mem, 0, sizeof r->m16.pb_mem); + ref_unlock(r); + return OMEGA_GPU_PLAT_OK; +} + +static int ref_queue_submit(void *ctx, OmegaGpuQueueHandle q, const uint32_t *words, uint32_t nwords) { + LinuxRef *r = ctx; + ref_lock(r); + int rc = queue_ok(r, q); + if (rc == OMEGA_GPU_PLAT_OK && (!words || nwords == 0u)) rc = OMEGA_GPU_PLAT_REFUSED_ARGS; + if (rc == OMEGA_GPU_PLAT_OK && (uint64_t)nwords * 4u > r->m16.pb_mem.size) rc = OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; + if (rc == OMEGA_GPU_PLAT_OK && m16_native_submit_methods(&r->m16, words, nwords) != 0) rc = OMEGA_GPU_PLAT_REFUSED_DEVICE; + if (rc != OMEGA_GPU_PLAT_OK) rc = refuse(r, rc, "submit_methods"); + ref_unlock(r); + return rc; +} + +static int ref_queue_retire(void *ctx, OmegaGpuQueueHandle q) { + LinuxRef *r = ctx; + ref_lock(r); + int rc = queue_ok(r, q); + if (rc == OMEGA_GPU_PLAT_OK) nvrm_retire(&r->m16.rm, r->m16.rm.put); /* both releases landed: the entry is consumed */ + else rc = refuse(r, rc, "queue_retire"); + ref_unlock(r); + return rc; +} + +static void *ref_host_alloc(void *ctx, size_t bytes) { (void)ctx; return bytes ? malloc(bytes) : NULL; } +static void ref_host_free(void *ctx, void *p) { (void)ctx; free(p); } + +static const OmegaGpuPlatform g_platform = { + .ctx = &g_ref, + .time_now_ms = ref_now_ms, + .wait_ms = ref_wait_ms, + .lock = ref_lock_id, + .unlock = ref_unlock_id, + .mmio_read32 = NULL, /* not provided: the RM driver owns the registers */ + .mmio_write32 = NULL, + .dma_alloc = ref_dma_alloc, + .dma_free = ref_dma_free, + .sync_cpu_to_gpu = ref_sync_to_gpu, + .sync_gpu_to_cpu = ref_sync_to_cpu, + .poll_word = ref_poll_word, + .irq_wait = NULL, /* polling is not interrupt support */ + .device_open = ref_device_open, + .device_close = ref_device_close, + .diag_text = ref_diag_text, + .queue_open = ref_queue_open, + .queue_close = ref_queue_close, + .queue_submit = ref_queue_submit, + .queue_retire = ref_queue_retire, + .time_now_ns = ref_now_ns, + .host_alloc = ref_host_alloc, + .host_free = ref_host_free, +}; + +const OmegaGpuPlatform *omega_gpu_platform_linux(OmegaGpuPlatformCaps *caps) { + if (caps) *caps = g_caps; + return &g_platform; +} diff --git a/src/omega_gpu_platform_linux.h b/src/omega_gpu_platform_linux.h new file mode 100644 index 000000000..076922b31 --- /dev/null +++ b/src/omega_gpu_platform_linux.h @@ -0,0 +1,40 @@ +/* omega_gpu_platform_linux.h -- the Linux REFERENCE implementation of OmegaGpuPlatform (ABI 1.1). + * + * REFERENCE ONLY (native v1 P07 cut C, session part; aienos#286). This is today's GB10 path under Linux + * (physics nvrm + m16_native, the open NVIDIA kernel driver), wrapped in the platform contract so the + * portable session (src/omega_gpu_session.c) runs the same launch words it always ran. It is NOT the + * native platform and is not part of the freestanding closure: it includes Linux headers, takes pthread + * mutexes, reads CLOCK_MONOTONIC and calls malloc. The AIENOS platform implements the same table over its + * own device ownership (cut B); nothing in the session may depend on anything this file does beyond the + * contract in src/omega_gpu_platform.h. + * + * What it provides: TIME, WAIT, LOCK, DMA, SYNC, COMPLETION (polling: m16_native_wait_marker, a 50 us + * sleep-poll), DEVICE, QUEUE, CLOCK_NS, HOST_MEM. Not MMIO (the RM driver owns the registers) and not IRQ + * (polling is never claimed as interrupt support). One device (ordinal 0), one queue (the m16 channel, + * GPFIFO entries carrying the method words copied into the BUF_QUEUE ring), every buffer GPU-uncached + * (nvrm_alloc_gpu_uncached; a GPU_CACHED request is refused with REFUSED_CACHE_POLICY because nothing here + * would flush it). The bus address is reported as 0: the RM driver owns the IOMMU mapping and does not + * expose it. Closing the device makes every buffer and queue handle of it stale (generation bump); the RM + * client close releases the driver objects, as the session always did. + * + * Tested by tests/test_omega_gpu_platform_linux.c on the simulated driver (tests/fake_m16_native.c); + * GB10 execution through it is the same driver calls as before this cut and is NOT re-run here. + */ +#ifndef OMEGA_GPU_PLATFORM_LINUX_H +#define OMEGA_GPU_PLATFORM_LINUX_H + +#include "omega_gpu_platform.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define OMEGA_GPU_PLATFORM_LINUX_LOCKS 4u /* lock ids 0..3 */ + +/* The process-wide Linux reference platform and its caps (written to *caps when caps is not NULL). */ +const OmegaGpuPlatform *omega_gpu_platform_linux(OmegaGpuPlatformCaps *caps); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/omega_gpu_session.c b/src/omega_gpu_session.c index 28fd4eb73..1e7c63722 100644 --- a/src/omega_gpu_session.c +++ b/src/omega_gpu_session.c @@ -1,23 +1,35 @@ /* - * omega_gpu_session.c: FB-1 cut 4b. See the header for the contract. + * omega_gpu_session.c: FB-1 cut 4b, made portable in native v1 P07 cut C (session part). See the header. * - * The launch words are the ones omega_gpu_matmul_api.c (cut 1b, chip PASS - * FB1-CUT1B-4345406) and omega_gpu_elementwise_api.c (cut 4, FB1-CUT4-0d0241a) - * both emitted; the two were identical except for the argument word count, which - * is now a parameter. Nothing about the sequence changed in this cut. + * The launch words are the ones omega_gpu_matmul_api.c (cut 1b, chip PASS FB1-CUT1B-4345406) and + * omega_gpu_elementwise_api.c (cut 4, FB1-CUT4-0d0241a) both emitted; cut C did not change one of them. What + * changed is where the machine comes from: every device, buffer, queue, clock, lock and host-memory call goes + * through the installed OmegaGpuPlatform (ABI 1.1), so this file builds freestanding (OMEGA_GPU_NO_POSIX) with no + * Linux header and no libc call. The hosted build installs the Linux reference (src/omega_gpu_platform_linux.c) + * on first use; it makes the same driver calls in the same order as this file did before. + * + * No read-modify-write atomics: the freestanding target must not pull libgcc outline atomics, so shared words are + * plain atomic loads and stores, and counters are only written with the session lock held. */ #include "omega_gpu_session.h" #include "omega_gpu_code_alloc.h" +#include "omega_gpu_fmt.h" #include "omega_blackwell_qmd.h" -#include "omega_blackwell_submit.h" -#include "nvrm.h" -#include -#include +#include "omega_blackwell_submit.h" /* launch constants only (macros); the vector executor itself stays Linux-private */ #include -#include + +#ifndef OMEGA_GPU_NO_POSIX +#include "omega_gpu_platform_linux.h" +#include +#endif #define PAGE 0x1000ull +/* Push-buffer method header (the nvrm_mthd encoding, physics nvrm.h): increasing, count words, subchannel. */ +static inline uint32_t bw_mthd(uint32_t subc, uint32_t mthd, uint32_t count) { + return (2u << 28) | (count << 16) | (subc << 13) | (mthd >> 2); +} + /* Same words as src/omega_blackwell_submit.c SETUP_WORDS (compute class setup). */ static const uint32_t SETUP_WORDS[18] = { 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, @@ -25,99 +37,258 @@ static const uint32_t SETUP_WORDS[18] = { 0x20012559, 0x00000000, }; -static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; +static const OmegaGpuPlatform *g_p; /* installed platform (atomic load / store) */ +static OmegaGpuPlatformCaps g_caps; static OmegaGpuSession g_s; -static bool g_open, g_blocked; -static uint32_t g_spin_us; /* omega_gpu_session_set_spin_us; 0 = sleep-poll only */ +static bool g_open; +static uint32_t g_blocked; /* latched (atomic) */ +static uint32_t g_locked; /* session lock held (atomic) */ +static uint32_t g_cancel; /* cancel requested (atomic) */ +static uint32_t g_spin_us; /* omega_gpu_session_set_spin_us; 0 = poll_word only */ static char g_err[320] = ""; static void (*g_hooks[8])(void); static unsigned g_nhooks; +static OmegaGpuAllocStats g_stats; /* written with the lock held, read with atomic loads */ +static OmegaGpuBufferHandle g_parked[OMEGA_GPU_SESSION_PARK_MAX]; +static OmegaGpuParkStats g_park; + +#define LOAD(x) __atomic_load_n(&(x), __ATOMIC_ACQUIRE) +#define STORE(x, v) __atomic_store_n(&(x), (v), __ATOMIC_RELEASE) +#define BUMP(x, by) STORE((x), LOAD(x) + (by)) /* lock held: one writer */ -static uint64_t now_ns(void) { - struct timespec t; - clock_gettime(CLOCK_MONOTONIC, &t); - return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; +/* ---- platform ---- */ + +static int install(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps) { + if (!p || !caps) return OMEGA_GPU_PLAT_REFUSED_ARGS; + OmegaGpuPlatformCaps req = { + .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, + .services = OMEGA_GPU_SVC_REQUIRED_SESSION, + .max_devices = 1, .max_buffers = 8, .max_queues = 1, .max_inflight = 1, + .max_buffer_bytes = 0x10000, .max_total_bytes = 0x10000 + 3 * 0x10000, + }; + int rc = omega_gpu_platform_negotiate(caps, &req); + if (rc == OMEGA_GPU_PLAT_OK) rc = omega_gpu_platform_check_for(p, caps, OMEGA_GPU_SVC_REQUIRED_SESSION); + if (rc != OMEGA_GPU_PLAT_OK) return rc; + g_caps = *caps; + STORE(g_p, p); + return OMEGA_GPU_PLAT_OK; } -/* Marker wait. With spin_us, the host first re-reads the uncached marker word back to back (with - * the ARM yield hint) so a launch that finishes inside the window is seen within about one read, - * instead of after a 50 us sleep that Linux timer slack stretches further. Past the window it is - * the same m16 sleep-poll as before, with the full timeout, so a stuck launch still latches. */ -static int session_wait(volatile uint32_t *m, uint32_t want, uint64_t timeout_ms, uint32_t spin_us) { - if (spin_us) { - const uint64_t end = now_ns() + (uint64_t)spin_us * 1000u; - do { - if ((int32_t)(*m - want) >= 0) return 0; - __asm__ volatile("yield" ::: "memory"); - } while (now_ns() < end); - } - return m16_native_wait_marker(m, want, timeout_ms); +int omega_gpu_session_set_platform(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps) { + if (g_open || LOAD(g_locked) || LOAD(g_blocked)) return OMEGA_GPU_PLAT_REFUSED_BUSY; + if (!p) { STORE(g_p, (const OmegaGpuPlatform *)0); return OMEGA_GPU_PLAT_OK; } + return install(p, caps); } -static size_t page_up(size_t b) { b = (b + PAGE - 1) & ~(PAGE - 1); return b < PAGE ? PAGE : b; } -const char *omega_gpu_session_last_error(void) { return g_err; } -void omega_gpu_session_set_error(const char *stage) { - snprintf(g_err, sizeof g_err, "%s", stage ? stage : ""); +#ifndef OMEGA_GPU_NO_POSIX +static pthread_once_t g_default_once = PTHREAD_ONCE_INIT; +static void install_default(void) { + if (LOAD(g_p)) return; /* one was installed explicitly */ + OmegaGpuPlatformCaps c; + const OmegaGpuPlatform *p = omega_gpu_platform_linux(&c); + (void)install(p, &c); } -static void fail_rm(const char *stage, const Nvrm *rm) { - /* the driver text (RM class / ioctl errno / RM status, nvrm.c fail()) travels with the stage */ - snprintf(g_err, sizeof g_err, "%s: %s", stage, rm && rm->err[0] ? rm->err : "(no driver text)"); +#endif + +static const OmegaGpuPlatform *platform(void) { + const OmegaGpuPlatform *p = LOAD(g_p); +#ifndef OMEGA_GPU_NO_POSIX + if (!p) { pthread_once(&g_default_once, install_default); p = LOAD(g_p); } +#endif + return p; } -void omega_gpu_session_lock(void) { pthread_mutex_lock(&g_mu); } -void omega_gpu_session_unlock(void) { pthread_mutex_unlock(&g_mu); } +const OmegaGpuPlatform *omega_gpu_session_platform(void) { return platform(); } +OmegaGpuCompletionMode omega_gpu_session_completion_mode(void) { return OMEGA_GPU_COMPLETION_POLLING; } + +uint64_t omega_gpu_session_now_ns(void) { + const OmegaGpuPlatform *p = platform(); + return p ? p->time_now_ns(p->ctx) : 0u; +} + +void *omega_gpu_host_alloc(size_t bytes) { + const OmegaGpuPlatform *p = platform(); + return p ? p->host_alloc(p->ctx, bytes ? bytes : 1) : (void *)0; /* 0 bytes: a unique 1-byte block, as malloc(0) gives */ +} +void *omega_gpu_host_calloc(size_t n, size_t size) { + size_t bytes; + if (__builtin_mul_overflow(n, size, &bytes)) return (void *)0; + void *q = omega_gpu_host_alloc(bytes); + if (q) memset(q, 0, bytes); + return q; +} +void omega_gpu_host_free(void *q) { + const OmegaGpuPlatform *p = platform(); + if (p && q) p->host_free(p->ctx, q); +} + +/* ---- errors ---- */ + +const char *omega_gpu_session_last_error(void) { return g_err; } +void omega_gpu_session_set_error(const char *stage) { omega_gpu_fmt(g_err, sizeof g_err, "%s", stage ? stage : ""); } + +/* A platform refusal: the driver text when the device refused (the Linux reference writes ": ", + * the stage names the session ever reported), else the stage and the refusal name. */ +static void fail_plat(const char *stage, int rc) { + const OmegaGpuPlatform *p = LOAD(g_p); + const char *diag = p ? p->diag_text(p->ctx) : ""; + if (rc == OMEGA_GPU_PLAT_REFUSED_DEVICE && diag && diag[0]) + omega_gpu_fmt(g_err, sizeof g_err, "%s", diag); + else + omega_gpu_fmt(g_err, sizeof g_err, "%s: %s", stage, omega_gpu_platform_refusal_name(rc)); +} + +/* ---- lock, state ---- */ + +void omega_gpu_session_lock(void) { + const OmegaGpuPlatform *p = platform(); + if (!p) return; + (void)p->lock(p->ctx, OMEGA_GPU_SESSION_LOCK_ID); + STORE(g_locked, 1u); +} +void omega_gpu_session_unlock(void) { + const OmegaGpuPlatform *p = LOAD(g_p); + if (!p) return; + STORE(g_locked, 0u); + (void)p->unlock(p->ctx, OMEGA_GPU_SESSION_LOCK_ID); +} bool omega_gpu_session_is_open(void) { return g_open; } -int omega_gpu_session_is_blocked(void) { return g_blocked ? 1 : 0; } +int omega_gpu_session_is_blocked(void) { return LOAD(g_blocked) ? 1 : 0; } int omega_gpu_session_set_spin_us(uint32_t us) { if (us > OMEGA_GPU_SESSION_MAX_SPIN_US) return -1; - __atomic_store_n(&g_spin_us, us, __ATOMIC_RELAXED); + STORE(g_spin_us, us); return 0; } -uint32_t omega_gpu_session_spin_us(void) { return __atomic_load_n(&g_spin_us, __ATOMIC_RELAXED); } +uint32_t omega_gpu_session_spin_us(void) { return LOAD(g_spin_us); } +void omega_gpu_session_cancel(void) { STORE(g_cancel, 1u); } -/* driver allocations made through this session (omega_gpu_session_alloc_stats) */ -static OmegaGpuAllocStats g_stats; +/* Consumes a pending cancel request. */ +static bool take_cancel(void) { + if (!LOAD(g_cancel)) return false; + STORE(g_cancel, 0u); + return true; +} void omega_gpu_session_alloc_stats(OmegaGpuAllocStats *out) { if (!out) return; - out->allocs = __atomic_load_n(&g_stats.allocs, __ATOMIC_RELAXED); - out->alloc_bytes = __atomic_load_n(&g_stats.alloc_bytes, __ATOMIC_RELAXED); - out->alloc_failures = __atomic_load_n(&g_stats.alloc_failures, __ATOMIC_RELAXED); - out->frees = __atomic_load_n(&g_stats.frees, __ATOMIC_RELAXED); + out->allocs = LOAD(g_stats.allocs); + out->alloc_bytes = LOAD(g_stats.alloc_bytes); + out->alloc_failures = LOAD(g_stats.alloc_failures); + out->frees = LOAD(g_stats.frees); + out->stale_refusals = LOAD(g_stats.stale_refusals); +} + +/* ---- parking ---- */ + +static void park(const OmegaGpuMem *m) { + uint32_t n = LOAD(g_park.buffers) - LOAD(g_park.untracked); + for (uint32_t i = 0; i < n; i++) + if (g_parked[i].index == m->handle.index && g_parked[i].generation == m->handle.generation) return; + if (n < OMEGA_GPU_SESSION_PARK_MAX) g_parked[n] = m->handle; + else BUMP(g_park.untracked, 1u); + BUMP(g_park.bytes, m->size); + BUMP(g_park.buffers, 1u); +} + +void omega_gpu_session_parked(OmegaGpuParkStats *out) { + if (!out) return; + out->buffers = LOAD(g_park.buffers); + out->untracked = LOAD(g_park.untracked); + out->bytes = LOAD(g_park.bytes); } -int omega_gpu_session_alloc(size_t bytes, NvrmMem *out) { - if (!g_open || g_blocked) { omega_gpu_session_set_error("alloc without open device"); return -1; } - if (nvrm_alloc_gpu_uncached(&g_s.ctx.rm, page_up(bytes), out) != 0) { - __atomic_add_fetch(&g_stats.alloc_failures, 1, __ATOMIC_RELAXED); - fail_rm("nvrm_alloc_gpu_uncached", &g_s.ctx.rm); memset(out, 0, sizeof *out); return -1; +int omega_gpu_session_is_parked(OmegaGpuBufferHandle h) { + uint32_t n = LOAD(g_park.buffers) - LOAD(g_park.untracked); + if (h.generation == 0u) return 0; + for (uint32_t i = 0; i < n && i < OMEGA_GPU_SESSION_PARK_MAX; i++) + if (g_parked[i].index == h.index && g_parked[i].generation == h.generation) return 1; + return 0; +} + +/* Uncertain completion: the device may still touch any session buffer. Keep everything, refuse everything. */ +static void latch(const char *why) { + STORE(g_blocked, 1u); + if (g_s.pb.cpu) park(&g_s.pb); + if (g_s.cbank.cpu) park(&g_s.cbank); + if (g_s.marker.cpu) park(&g_s.marker); + if (g_s.qmd.cpu) park(&g_s.qmd); + omega_gpu_session_set_error(why); +} + +/* ---- buffers ---- */ + +static size_t page_up(size_t b) { b = (b + PAGE - 1) & ~(PAGE - 1); return b < PAGE ? PAGE : b; } + +static int mem_alloc(uint32_t kind, uint32_t rights, size_t bytes, OmegaGpuMem *out) { + const OmegaGpuPlatform *p = LOAD(g_p); + memset(out, 0, sizeof *out); + if (!g_open || LOAD(g_blocked) || !p) { omega_gpu_session_set_error("alloc without open device"); return -1; } + const size_t want = page_up(bytes); + OmegaGpuBufferDesc d = {.kind = kind, .rights = rights, .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .align = (uint32_t)PAGE, .bytes = want}; + OmegaCpuView cpu; OmegaGpuVa va; OmegaGpuBusAddr bus; /* the bus address never leaves this function */ + int rc = p->dma_alloc(p->ctx, g_s.dev, &d, &out->handle, &cpu, &va, &bus); + if (rc != OMEGA_GPU_PLAT_OK || !cpu.ptr || cpu.len < want) { + if (rc == OMEGA_GPU_PLAT_OK) { (void)p->dma_free(p->ctx, out->handle); rc = OMEGA_GPU_PLAT_REFUSED_LIMIT; } + BUMP(g_stats.alloc_failures, 1u); + fail_plat("dma_alloc", rc); + memset(out, 0, sizeof *out); + return -1; } - __atomic_add_fetch(&g_stats.allocs, 1, __ATOMIC_RELAXED); - __atomic_add_fetch(&g_stats.alloc_bytes, (uint64_t)page_up(bytes), __ATOMIC_RELAXED); + out->kind = kind; out->cpu = cpu.ptr; out->va = va.va; out->size = cpu.len; + BUMP(g_stats.allocs, 1u); + BUMP(g_stats.alloc_bytes, (uint64_t)want); return 0; } -int omega_gpu_session_alloc_code(size_t code_size, NvrmMem *out) { +#define RIGHTS_DATA (OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE) +#define RIGHTS_CODE (OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ | OMEGA_GPU_RIGHT_GPU_EXEC) +#define RIGHTS_RING (OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ) +#define RIGHTS_MARKER (OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_WRITE | OMEGA_GPU_RIGHT_HOST_POLLED) +#define RIGHTS_CBANK (OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ) + +int omega_gpu_session_alloc(size_t bytes, OmegaGpuMem *out) { + return mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_DATA, bytes, out); +} + +int omega_gpu_session_alloc_code(size_t code_size, OmegaGpuMem *out) { size_t bytes = omega_gpu_code_alloc_bytes(code_size); if (bytes == 0) { omega_gpu_session_set_error("code size overflow"); memset(out, 0, sizeof *out); return -1; } - if (omega_gpu_session_alloc(bytes, out) != 0) return -1; + if (mem_alloc(OMEGA_GPU_HANDLE_BUF_CODE, RIGHTS_CODE, bytes, out) != 0) return -1; memset((uint8_t *)out->cpu + code_size, 0, bytes - code_size); return 0; } -void omega_gpu_session_free(NvrmMem *m) { - if (m->cpu && g_open && !g_blocked) { - (void)nvrm_free(&g_s.ctx.rm, m); - __atomic_add_fetch(&g_stats.frees, 1, __ATOMIC_RELAXED); +void omega_gpu_session_free(OmegaGpuMem *m) { + if (!m) return; + if (m->cpu) { + const OmegaGpuPlatform *p = LOAD(g_p); + if (LOAD(g_blocked)) { + park(m); /* the device may still use it */ + } else if (!g_open || !p) { + BUMP(g_stats.stale_refusals, 1u); /* its device is closed: the handle is stale, nothing to release */ + } else { + int rc = p->dma_free(p->ctx, m->handle); + if (rc == OMEGA_GPU_PLAT_OK) BUMP(g_stats.frees, 1u); + else { BUMP(g_stats.stale_refusals, 1u); fail_plat("dma_free", rc); } + } } memset(m, 0, sizeof *m); } +static int sync_mem(const OmegaGpuMem *m, int to_gpu) { + const OmegaGpuPlatform *p = LOAD(g_p); + if (!m || !m->cpu) return 0; + if (!p || !g_open) { omega_gpu_session_set_error("sync without open device"); return -1; } + int rc = to_gpu ? p->sync_cpu_to_gpu(p->ctx, m->handle, 0, m->size) : p->sync_gpu_to_cpu(p->ctx, m->handle, 0, m->size); + if (rc != OMEGA_GPU_PLAT_OK) { fail_plat(to_gpu ? "sync_cpu_to_gpu" : "sync_gpu_to_cpu", rc); return -1; } + return 0; +} +int omega_gpu_session_sync_to_gpu(const OmegaGpuMem *m) { return sync_mem(m, 1); } +int omega_gpu_session_sync_to_cpu(const OmegaGpuMem *m) { return sync_mem(m, 0); } + int omega_gpu_session_scratch(OmegaGpuScratch *s, size_t bytes) { if (s->reserved && (bytes > s->cap || !s->mem.cpu)) { - char msg[128]; - snprintf(msg, sizeof msg, "serving reservation exceeded: need %zu bytes, reserved %zu", bytes, s->cap); - omega_gpu_session_set_error(msg); + omega_gpu_fmt(g_err, sizeof g_err, "serving reservation exceeded: need %zu bytes, reserved %zu", bytes, s->cap); return OMEGA_GPU_SESSION_SCRATCH_RESERVED; } if (bytes > s->high_water) s->high_water = bytes; @@ -149,28 +320,38 @@ static void free_session_buffers(void) { omega_gpu_session_free(&g_s.cbank); omega_gpu_session_free(&g_s.pb); } +/* ---- open, close ---- */ + OmegaGpuSession *omega_gpu_session_open(void) { - if (g_blocked) { omega_gpu_session_set_error("process latched"); return NULL; } + if (LOAD(g_blocked)) { omega_gpu_session_set_error("process latched"); return NULL; } if (g_open) return &g_s; - uint64_t t0 = now_ns(); - memset(&g_s.ctx, 0, sizeof g_s.ctx); - /* nvrm_open directly (m16_native_open is memset + nvrm_open + nvrm_close on - * failure) so the driver's own failure text survives into the stage name. */ - if (nvrm_open(&g_s.ctx.rm) != 0) { fail_rm("nvrm_open", &g_s.ctx.rm); (void)nvrm_close(&g_s.ctx.rm); return NULL; } - if (m16_native_create_channel(&g_s.ctx) != 0) { fail_rm("m16_native_create_channel", &g_s.ctx.rm); (void)m16_native_close(&g_s.ctx); return NULL; } + const OmegaGpuPlatform *p = platform(); + if (!p) { omega_gpu_session_set_error("no GPU platform installed (omega_gpu_session_set_platform)"); return NULL; } + uint64_t t0 = p->time_now_ns(p->ctx); + const uint32_t opens = g_s.opens; + memset(&g_s, 0, sizeof g_s); + g_s.opens = opens; + int rc = p->device_open(p->ctx, 0, &g_s.dev); + if (rc != OMEGA_GPU_PLAT_OK) { fail_plat("device_open", rc); memset(&g_s.dev, 0, sizeof g_s.dev); return NULL; } g_open = true; /* so alloc / free work during the rest of the open */ - if (omega_gpu_session_alloc(0x10000, &g_s.pb) || omega_gpu_session_alloc(PAGE, &g_s.cbank) || - omega_gpu_session_alloc(PAGE, &g_s.marker) || omega_gpu_session_alloc(0x10000, &g_s.qmd)) { - char keep[sizeof g_err]; memcpy(keep, g_err, sizeof keep); + /* same four buffers, same sizes, same order as before cut C; every one GPU-uncached */ + if (mem_alloc(OMEGA_GPU_HANDLE_BUF_QUEUE, RIGHTS_RING, 0x10000, &g_s.pb) || + mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_CBANK, PAGE, &g_s.cbank) || + mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_MARKER, PAGE, &g_s.marker) || + mem_alloc(OMEGA_GPU_HANDLE_BUF_DATA, RIGHTS_DATA, 0x10000, &g_s.qmd) || + (rc = p->queue_open(p->ctx, g_s.dev, g_s.pb.handle, &g_s.queue)) != OMEGA_GPU_PLAT_OK) { + char keep[sizeof g_err]; + if (rc != OMEGA_GPU_PLAT_OK) fail_plat("queue_open", rc); + memcpy(keep, g_err, sizeof keep); free_session_buffers(); g_open = false; - (void)m16_native_close(&g_s.ctx); - snprintf(g_err, sizeof g_err, "session scratch alloc (%s)", keep); + (void)p->device_close(p->ctx, g_s.dev); + memset(&g_s.dev, 0, sizeof g_s.dev); + omega_gpu_fmt(g_err, sizeof g_err, "session scratch alloc (%s)", keep); return NULL; } - g_s.ctx.pb_mem = g_s.pb; /* m16_native_enqueue_methods copies the method stream here */ g_s.opens++; - g_s.last_open_ns = now_ns() - t0; + g_s.last_open_ns = p->time_now_ns(p->ctx) - t0; return &g_s; } @@ -184,24 +365,76 @@ int omega_gpu_session_on_close(void (*hook)(void)) { /* caller holds the lock (t } void omega_gpu_session_close(void) { - pthread_mutex_lock(&g_mu); - if (g_open && !g_blocked) { + omega_gpu_session_lock(); + const OmegaGpuPlatform *p = LOAD(g_p); + if (g_open && !LOAD(g_blocked) && p) { for (unsigned i = 0; i < g_nhooks; i++) g_hooks[i](); - free_session_buffers(); - (void)m16_native_close(&g_s.ctx); - g_open = false; + if (!LOAD(g_blocked)) { /* a hook's launch may have latched: then nothing below runs */ + (void)p->queue_close(p->ctx, g_s.queue); + memset(&g_s.queue, 0, sizeof g_s.queue); + free_session_buffers(); + (void)p->device_close(p->ctx, g_s.dev); /* every handle of this device is stale from here */ + memset(&g_s.dev, 0, sizeof g_s.dev); + g_open = false; + } } - pthread_mutex_unlock(&g_mu); + omega_gpu_session_unlock(); } +/* ---- launch ---- */ + static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } +static inline void cpu_relax(void) { +#if defined(__aarch64__) + __asm__ volatile("yield" ::: "memory"); +#else + __asm__ volatile("" ::: "memory"); +#endif +} + +#define WAIT_CANCELLED 1 +#define WAIT_TIMED_OUT 2 +#define WAIT_REFUSED 3 + +/* Marker wait by POLLING. With spin_us, the host first re-reads the uncached marker word back to back (with the + * ARM yield hint) so a launch that finishes inside the window is seen within about one read. Then the platform's + * poll_word in slices of OMEGA_GPU_SESSION_POLL_SLICE_MS (Linux reference: the m16 50 us sleep-poll) until + * timeout_ms, checking for a cancel request between slices. */ +static int session_wait(const OmegaGpuPlatform *p, uint64_t off, uint32_t want, uint64_t timeout_ms, uint32_t spin_us) { + volatile uint32_t *m = (volatile uint32_t *)((uint8_t *)g_s.marker.cpu + off); + if (spin_us) { + const uint64_t end = p->time_now_ns(p->ctx) + (uint64_t)spin_us * 1000u; + do { + if ((int32_t)(*m - want) >= 0) return 0; + if (LOAD(g_cancel)) return WAIT_CANCELLED; + cpu_relax(); + } while (p->time_now_ns(p->ctx) < end); + } + uint64_t waited = 0; + for (;;) { + if (LOAD(g_cancel)) return WAIT_CANCELLED; + const uint64_t left = timeout_ms - waited; + const uint64_t slice = left < OMEGA_GPU_SESSION_POLL_SLICE_MS ? left : OMEGA_GPU_SESSION_POLL_SLICE_MS; + uint32_t seen = 0; + int rc = p->poll_word(p->ctx, g_s.marker.handle, off, want, slice, &seen); + if (rc == OMEGA_GPU_PLAT_OK) return 0; + if (rc != OMEGA_GPU_POLL_TIMED_OUT) return WAIT_REFUSED; + waited += slice; + if (waited >= timeout_ms) return WAIT_TIMED_OUT; + } +} + int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out) { - if (!g_open || g_blocked) { omega_gpu_session_set_error(g_blocked ? "process latched" : "launch without open device"); return -1; } + const OmegaGpuPlatform *p = LOAD(g_p); + if (!g_open || LOAD(g_blocked) || !p) { + omega_gpu_session_set_error(LOAD(g_blocked) ? "process latched" : "launch without open device"); return -1; + } if (!L || !L->args || L->n_args == 0 || L->n_args > OMEGA_GPU_SESSION_MAX_ARGS || L->threads_x == 0 || L->grid_x == 0 || L->grid_y == 0 || L->spin_us > OMEGA_GPU_SESSION_MAX_SPIN_US) { omega_gpu_session_set_error("launch arguments"); return -1; } + if (take_cancel()) { omega_gpu_session_set_error("launch cancelled before submit"); return OMEGA_GPU_SESSION_CANCELLED; } const uint32_t threads_y = L->threads_y ? L->threads_y : 1; uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; omega_blackwell_build_cbank_driver_2d(cbank_data, g_s.cbank.va, L->threads_x, threads_y, L->grid_x, L->grid_y); @@ -228,7 +461,11 @@ int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint volatile uint32_t *hmarker = (volatile uint32_t *)g_s.marker.cpu; volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)g_s.marker.cpu + 0x10); *hsem = 0; *hmarker = 0; *hmarker2 = 0; - __asm__ volatile("dsb sy" ::: "memory"); + /* explicit visibility of everything the CPU just wrote (Linux reference: dsb sy, the barrier issued here before) */ + int rc = p->sync_cpu_to_gpu(p->ctx, g_s.cbank.handle, 0, PAGE); + if (rc == OMEGA_GPU_PLAT_OK) rc = p->sync_cpu_to_gpu(p->ctx, g_s.qmd.handle, 0, 0x3000); + if (rc == OMEGA_GPU_PLAT_OK) rc = p->sync_cpu_to_gpu(p->ctx, g_s.marker.handle, 0, 0x20); + if (rc != OMEGA_GPU_PLAT_OK) { fail_plat("sync_cpu_to_gpu", rc); return -1; } uint32_t pb[1024]; size_t n = 0; @@ -236,16 +473,16 @@ int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint /* Invalidate the SM instruction, constant and data caches before this launch * (cut 1b finding: a reused code address served stale instructions; clcec0.h * NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, bits INSTRUCTION 0, DATA 4, CONSTANT 12). */ - pb[n++] = nvrm_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; + pb[n++] = bw_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; /* constant bank 0: driver words, then our arguments at 0x380 (inline upload) */ - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(g_s.cbank.va >> 32); pb[n++] = (uint32_t)g_s.cbank.va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = bw_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(g_s.cbank.va >> 32); pb[n++] = (uint32_t)g_s.cbank.va; + pb[n++] = bw_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; + pb[n++] = bw_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; pb[n++] = (224u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); memcpy(&pb[n], cbank_data, 224 * 4); n += 224; - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((g_s.cbank.va + 0x380) >> 32); pb[n++] = (uint32_t)(g_s.cbank.va + 0x380); - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = L->n_args * 4u; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = bw_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((g_s.cbank.va + 0x380) >> 32); pb[n++] = (uint32_t)(g_s.cbank.va + 0x380); + pb[n++] = bw_mthd(1, 0x0180, 2); pb[n++] = L->n_args * 4u; pb[n++] = 0x00000001; + pb[n++] = bw_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; pb[n++] = (L->n_args << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); memcpy(&pb[n], L->args, (size_t)L->n_args * 4u); n += L->n_args; /* QMD0 (null grid, dependence 2) */ @@ -253,9 +490,9 @@ int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; /* intermediate semaphore init */ - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = bw_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; + pb[n++] = bw_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; + pb[n++] = bw_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; pb[n++] = (1u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; /* QMD1 (the kernel) */ @@ -263,30 +500,42 @@ int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; /* first marker */ - pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = bw_mthd(0, 0x005c, 5); pb[n++] = (uint32_t)g_s.marker.va; pb[n++] = (uint32_t)(g_s.marker.va >> 32); pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); /* C3 tail: L2_FLUSH_DIRTY, then the second release on the uncached marker page */ - pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); - pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = bw_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); + pb[n++] = bw_mthd(0, 0x005c, 5); pb[n++] = (uint32_t)(g_s.marker.va + 0x10); pb[n++] = (uint32_t)((g_s.marker.va + 0x10) >> 32); pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); const uint32_t spin_us = L->spin_us ? L->spin_us : omega_gpu_session_spin_us(); - uint64_t t0 = now_ns(); - if (m16_native_submit_methods(&g_s.ctx, pb, n) != 0) { fail_rm("submit_methods", &g_s.ctx.rm); return -1; } - if (session_wait(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, L->timeout_ms, spin_us) != 0 || - session_wait(hmarker2, OMEGA_BW_MARKER2_PAYLOAD, L->timeout_ms, spin_us) != 0) { - g_blocked = true; /* uncertain completion: keep everything, refuse every later call */ - omega_gpu_session_set_error("marker wait timed out (latched)"); + uint64_t t0 = p->time_now_ns(p->ctx); + rc = p->queue_submit(p->ctx, g_s.queue, pb, (uint32_t)n); + if (rc != OMEGA_GPU_PLAT_OK) { + fail_plat("submit_methods", rc); /* contract: a refused submit rang no doorbell, nothing is in flight */ + return -1; + } + int w = session_wait(p, 0, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, L->timeout_ms, spin_us); + if (w == 0) w = session_wait(p, 0x10, OMEGA_BW_MARKER2_PAYLOAD, L->timeout_ms, spin_us); + if (w != 0) { + /* uncertain completion: keep everything (parked), refuse every later call */ + if (w == WAIT_CANCELLED) { + (void)take_cancel(); + latch("launch cancelled after submit (completion uncertain, latched)"); + return OMEGA_GPU_SESSION_CANCELLED; + } + latch(w == WAIT_TIMED_OUT ? "marker wait timed out (latched)" : "marker poll refused (latched)"); return -1; } - __asm__ volatile("dsb sy" ::: "memory"); - uint64_t t1 = now_ns(); - nvrm_retire(&g_s.ctx.rm, g_s.ctx.rm.put); /* both releases landed: the GPFIFO entry is consumed */ + (void)p->sync_gpu_to_cpu(p->ctx, g_s.marker.handle, 0, 0x20); + (void)p->sync_gpu_to_cpu(p->ctx, g_s.qmd.handle, 0x2000, 4); + uint64_t t1 = p->time_now_ns(p->ctx); + (void)p->queue_retire(p->ctx, g_s.queue); /* both releases landed: the GPFIFO entry is consumed */ if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { omega_gpu_session_set_error("intermediate semaphore not DONE"); return -1; } if (elapsed_ns) *elapsed_ns += t1 - t0; if (marker_out) *marker_out = *hmarker; + (void)hmarker2; return 0; } diff --git a/src/omega_gpu_session.h b/src/omega_gpu_session.h index d00da8e41..cd454d49a 100644 --- a/src/omega_gpu_session.h +++ b/src/omega_gpu_session.h @@ -36,26 +36,54 @@ * (omega_gpu_session_last_error) and an open failure carries the driver text * (Nvrm.err: RM class, ioctl errno, RM status) so a first-call failure is never * reported as a bare CHIP_FAIL again. + * + * Portability (native v1 P07 cut C, session part; aienos#286, docs/numeric/OMEGA_GPU_NATIVE_BOUNDARY.md): + * this file and omega_gpu_session.c no longer name a Linux driver type or call one. Everything the session + * needs from the machine goes through the installed OmegaGpuPlatform (src/omega_gpu_platform.h, ABI 1.1, + * service set OMEGA_GPU_SVC_REQUIRED_SESSION): device open/close, typed DMA buffers with explicit rights, + * kind and GPU-uncached policy, the submission queue, POLLING completion (poll_word; the session never + * claims or waits on an interrupt), explicit CPU<->GPU sync, the nanosecond clock, the session lock and + * CPU-only host memory. omega_gpu_session_set_platform installs one; the hosted build installs the Linux + * reference (src/omega_gpu_platform_linux.c, reference only) on first use when none was installed; the + * freestanding build (OMEGA_GPU_NO_POSIX) has no default and refuses until a platform is installed. + * Buffers are OmegaGpuMem: a typed handle (index + generation) plus the CPU view and the GPU VA as two + * distinct fields; no bus or physical address reaches the APIs. A handle from a closed device is stale and + * every use of it is refused. + * + * Uncertain completion parks, it never releases: after a marker poll timed out or a launch was cancelled + * after submit, the device may still be reading or writing any session buffer, so every buffer the session + * or an API frees from then on is PARKED (kept allocated, counted in omega_gpu_session_parked) and never + * returned to the platform; close and reopen are refused; the latch holds for the life of the process. */ #include #include #include -#include "m16_native.h" +#include "omega_gpu_platform.h" #ifdef __cplusplus extern "C" { #endif +/* A device buffer: typed handle, kind, CPU view (cpu, size bytes) and GPU VA (va). cpu NULL = none. */ typedef struct { - M16NativeContext ctx; - NvrmMem pb, cbank, marker, qmd; /* per-launch scratch, owned by the session */ - uint32_t opens; /* device opens in this process */ - uint64_t last_open_ns; /* wall time of the last successful open */ + OmegaGpuBufferHandle handle; + uint32_t kind; /* OMEGA_GPU_HANDLE_BUF_DATA, _BUF_CODE or _BUF_QUEUE */ + void *cpu; /* CPU view (OmegaCpuView.ptr) */ + uint64_t va; /* GPU virtual address (OmegaGpuVa.va) */ + uint64_t size; /* bytes of both views */ +} OmegaGpuMem; + +typedef struct { + OmegaGpuDeviceHandle dev; + OmegaGpuQueueHandle queue; + OmegaGpuMem pb, cbank, marker, qmd; /* per-launch scratch, owned by the session (pb is the queue ring) */ + uint32_t opens; /* device opens in this process */ + uint64_t last_open_ns; /* wall time of the last successful open */ } OmegaGpuSession; /* A caller-owned staging buffer that grows to its high-water mark. */ typedef struct { - NvrmMem mem; + OmegaGpuMem mem; size_t cap; /* usable bytes */ size_t high_water; /* largest request so far */ bool reserved; /* serving reservation active: a request past cap is refused, never allocated (omega_gpu_session_scratch_reserve) */ @@ -71,39 +99,81 @@ typedef struct { size_t num_elements; /* QMD config num_elements (kept per API for identical words) */ const uint32_t *args; /* n_args words written at cbank + 0x380 */ uint32_t n_args; /* <= OMEGA_GPU_SESSION_MAX_ARGS */ - uint64_t timeout_ms; /* marker wait; past it the process latches */ + uint64_t timeout_ms; /* marker poll; past it the completion is uncertain and the process latches */ uint32_t shared_bytes; /* shared memory per CTA; 0 = the QMD default (1024) */ - uint32_t spin_us; /* poll the marker without sleeping for up to this long, then the usual - 50 us sleep-poll until timeout_ms; 0 = sleep-poll only (old behavior) */ + uint32_t spin_us; /* poll the marker without sleeping for up to this long, then the platform's + poll_word (Linux reference: 50 us sleep-poll) until timeout_ms; 0 = poll_word only */ } OmegaGpuLaunch; #define OMEGA_GPU_SESSION_MAX_SPIN_US 1000000u #define OMEGA_GPU_SESSION_MAX_ARGS 32u - -/* Take the session lock. Never fails; does not touch the device. */ +/* poll_word is called in slices of at most this many ms so a cancel request is seen within one slice */ +#define OMEGA_GPU_SESSION_POLL_SLICE_MS 1u + +/* ---- platform (ABI 1.1) ---- */ + +/* Installs the platform the session runs on. Negotiates caps against OMEGA_GPU_SVC_REQUIRED_SESSION and checks the + * table (omega_gpu_platform_check_for). OMEGA_GPU_PLAT_OK, or the refusal; REFUSED_BUSY while the device is open, + * the lock is held or the process is latched. NULL p uninstalls (refused the same way). Install once, at start. */ +int omega_gpu_session_set_platform(const OmegaGpuPlatform *p, const OmegaGpuPlatformCaps *caps); +/* The installed platform (the hosted build installs the Linux reference here when none was installed); NULL in the + * freestanding build until omega_gpu_session_set_platform. */ +const OmegaGpuPlatform *omega_gpu_session_platform(void); + +/* Completion is observed by polling a GPU-uncached word; the session never claims interrupt support. */ +typedef enum { OMEGA_GPU_COMPLETION_POLLING = 1 } OmegaGpuCompletionMode; +OmegaGpuCompletionMode omega_gpu_session_completion_mode(void); + +/* Platform clock in ns (CLOCK_NS); 0 without a platform. */ +uint64_t omega_gpu_session_now_ns(void); + +/* CPU-only memory for API tables and staging, from the platform HOST_MEM service (Linux reference: malloc/free). + * NULL without a platform or on refusal; 0 bytes gives a unique 1-byte block (malloc(0) behaviour); calloc also + * refuses n * size overflow. free(NULL) is a no-op. */ +void *omega_gpu_host_alloc(size_t bytes); +void *omega_gpu_host_calloc(size_t n, size_t size); +void omega_gpu_host_free(void *p); + +/* ---- lock, open, state ---- */ + +/* Take the session lock (platform LOCK service, lock id OMEGA_GPU_SESSION_LOCK_ID). Does not touch the device. + * Without a platform it is a no-op and the open that follows refuses. */ +#define OMEGA_GPU_SESSION_LOCK_ID 0u void omega_gpu_session_lock(void); void omega_gpu_session_unlock(void); /* Caller holds the lock. Opens the device on first use. NULL when the process is - * latched or the open failed (stage in omega_gpu_session_last_error). */ + * latched, no platform is installed or the open failed (stage in omega_gpu_session_last_error). */ OmegaGpuSession *omega_gpu_session_open(void); bool omega_gpu_session_is_open(void); /* 1 once an uncertain completion has latched this process. */ int omega_gpu_session_is_blocked(void); -/* Process-wide marker-wait spin window, used by every launch whose own spin_us is 0 +/* Process-wide marker-poll spin window, used by every launch whose own spin_us is 0 * (the matmul, elementwise and attention APIs leave it 0). 0 (the default) keeps the - * 50 us sleep-poll, which Linux timer slack rounds to about 102 us per launch on GB10 - * (omega#328). 0 on success, -1 above OMEGA_GPU_SESSION_MAX_SPIN_US (setting unchanged). */ + * poll_word sleep-poll (Linux reference: 50 us, which Linux timer slack rounds to about 102 us + * per launch on GB10, omega#328). 0 on success, -1 above OMEGA_GPU_SESSION_MAX_SPIN_US (setting unchanged). */ int omega_gpu_session_set_spin_us(uint32_t us); uint32_t omega_gpu_session_spin_us(void); -/* Caller holds the lock, device open. GPU-uncached allocation, page rounded. */ -int omega_gpu_session_alloc(size_t bytes, NvrmMem *out); -/* Caller holds the lock, device open. A GPU code buffer for code_size bytes with the 2 KB instruction - * prefetch tail (omega_gpu_code_alloc.h), the tail zero-filled; the caller copies the code to out->cpu. */ -int omega_gpu_session_alloc_code(size_t code_size, NvrmMem *out); -void omega_gpu_session_free(NvrmMem *m); /* no-op when latched or closed; zeroes *m */ +/* ---- buffers ---- */ + +/* Caller holds the lock, device open. GPU-uncached DATA buffer (CPU and GPU read/write), page rounded. */ +int omega_gpu_session_alloc(size_t bytes, OmegaGpuMem *out); +/* Caller holds the lock, device open. A CODE buffer (CPU writes, GPU executes, GPU never writes) for code_size + * bytes with the 2 KB instruction prefetch tail (omega_gpu_code_alloc.h), the tail zero-filled; the caller writes + * the code to out->cpu. */ +int omega_gpu_session_alloc_code(size_t code_size, OmegaGpuMem *out); +/* Releases m to the platform and zeroes *m. Latched: m is PARKED instead (never released). A handle from a closed + * device (stale) or a closed session is refused: nothing is released, the refusal is counted + * (OmegaGpuAllocStats.stale_refusals) and *m is zeroed. */ +void omega_gpu_session_free(OmegaGpuMem *m); + +/* Explicit visibility of a whole buffer (platform SYNC): CPU writes before the device reads them, device writes + * before the CPU reads them (Linux reference: dsb sy, the barrier the APIs issued themselves before cut C). + * 0 also for a buffer with no CPU view (nothing to sync); -1 with the stage named when refused or no device. */ +int omega_gpu_session_sync_to_gpu(const OmegaGpuMem *m); +int omega_gpu_session_sync_to_cpu(const OmegaGpuMem *m); /* Caller holds the lock, device open. Makes s->mem at least `bytes` long * (reallocated when it grows; contents are not kept). */ @@ -117,12 +187,22 @@ int omega_gpu_session_scratch_reserve(OmegaGpuScratch *s, size_t bytes); void omega_gpu_session_scratch_unreserve(OmegaGpuScratch *s); void omega_gpu_session_scratch_free(OmegaGpuScratch *s); -/* Caller holds the lock, device open, not latched. Submits one launch and waits +/* ---- launch, cancel ---- */ + +/* Caller holds the lock, device open, not latched. Submits one launch and polls * for both markers. 0 on success; -1 with the stage named on failure. A marker - * timeout latches the process. elapsed_ns (submit to second marker) and the - * observed first marker word are added / stored when the pointers are given. */ + * timeout latches the process (uncertain completion). elapsed_ns (submit to second + * marker) and the observed first marker word are added / stored when the pointers are given. + * OMEGA_GPU_SESSION_CANCELLED: a cancel request was seen. Before submit nothing was submitted and the + * session stays usable; after submit the completion is uncertain and the process latches. */ +#define OMEGA_GPU_SESSION_CANCELLED (-3) int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out); +/* Asks the launch in progress (or the next one) to stop. Any thread, no lock. Polling cannot stop the device: a + * launch already submitted is not cancelled on the chip, its completion becomes uncertain (latch + park). The + * request is consumed by the launch that sees it. */ +void omega_gpu_session_cancel(void); + /* Stage of the most recent failure ("" if none). Shared by every API. */ const char *omega_gpu_session_last_error(void); void omega_gpu_session_set_error(const char *stage); @@ -135,7 +215,8 @@ void omega_gpu_session_set_error(const char *stage); int omega_gpu_session_on_close(void (*hook)(void)); /* Close the device and free every session buffer. Takes the lock itself. - * Refused (no-op) after an uncertain completion. The next open reopens. */ + * Refused (no-op) after an uncertain completion. The next open reopens; every handle of the + * closed device is stale from then on. */ void omega_gpu_session_close(void); /* Device opens so far in this process (diagnostics; a persistent session shows 1). */ @@ -149,9 +230,23 @@ typedef struct { uint64_t alloc_bytes; /* their page-rounded bytes */ uint64_t alloc_failures; /* driver refusals (e.g. NV_ERR_NO_MEMORY) */ uint64_t frees; /* driver frees */ + uint64_t stale_refusals; /* frees refused because the handle was stale (closed device or double free) */ } OmegaGpuAllocStats; void omega_gpu_session_alloc_stats(OmegaGpuAllocStats *out); +/* Buffers parked after an uncertain completion: kept allocated, never returned to the platform. The session's own + * launch buffers (ring, constant bank, marker, QMD page) are parked at the latch; every later free parks too. + * The first OMEGA_GPU_SESSION_PARK_MAX are listed by handle; past that they are still kept, counted in untracked. */ +#define OMEGA_GPU_SESSION_PARK_MAX 512u +typedef struct { + uint32_t buffers; /* parked buffers (listed + untracked) */ + uint32_t untracked; /* parked past the list (still never released) */ + uint64_t bytes; /* their bytes */ +} OmegaGpuParkStats; +void omega_gpu_session_parked(OmegaGpuParkStats *out); +/* 1 if this handle is parked (listed). */ +int omega_gpu_session_is_parked(OmegaGpuBufferHandle h); + #ifdef __cplusplus } #endif diff --git a/src/omega_gpu_wait.c b/src/omega_gpu_wait.c index ad5169497..8a4342586 100644 --- a/src/omega_gpu_wait.c +++ b/src/omega_gpu_wait.c @@ -1,14 +1,21 @@ #include "omega_gpu_wait.h" #include -#include +#ifndef OMEGA_GPU_NO_POSIX +#include static uint64_t real_now_ns(void *ctx) { (void)ctx; struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; } +#define DEFAULT_NOW_NS real_now_ns +#else +/* P07 cut C: the freestanding build has no clock of its own; the caller passes the platform clock + * (cfg->now_ns, e.g. OmegaGpuPlatform.time_now_ns) and a wait without one is refused (INVALID_STATE). */ +#define DEFAULT_NOW_NS NULL +#endif static void real_barrier(void *ctx) { (void)ctx; @@ -56,7 +63,11 @@ static bool wait_core(omega_gpu_wait_kind_t kind, volatile uint32_t *word, uint3 cfg = &zero; } - uint64_t (*now_ns)(void *) = cfg->now_ns ? cfg->now_ns : real_now_ns; + uint64_t (*now_ns)(void *) = cfg->now_ns ? cfg->now_ns : DEFAULT_NOW_NS; + if (!now_ns) { + rpt->result = OMEGA_GPU_WAIT_INVALID_STATE; /* no clock: a bounded wait cannot be bounded */ + return false; + } void (*barrier)(void *) = cfg->barrier ? cfg->barrier : real_barrier; void (*relax)(void *) = cfg->relax ? cfg->relax : real_relax; uint64_t total_ns = 1000000ull * (cfg->total_timeout_ms ? cfg->total_timeout_ms : OMEGA_GPU_WAIT_DEFAULT_TOTAL_MS); diff --git a/src/omega_gpu_wait.h b/src/omega_gpu_wait.h index 466881766..27e2c3613 100644 --- a/src/omega_gpu_wait.h +++ b/src/omega_gpu_wait.h @@ -77,7 +77,8 @@ typedef struct { /* Optional: return true to stop the wait (ABORTED). */ bool (*abort)(void *ctx); /* Test hooks. NULL means the real ones (CLOCK_MONOTONIC, dsb, yield). - * hook_ctx is passed to now_ns, barrier, relax, valid and abort. */ + * hook_ctx is passed to now_ns, barrier, relax, valid and abort. The freestanding build (OMEGA_GPU_NO_POSIX) + * has no default clock: now_ns is required there (the platform clock) and a wait without it is INVALID_STATE. */ uint64_t (*now_ns)(void *ctx); void (*barrier)(void *ctx); void (*relax)(void *ctx); diff --git a/tests/.crumb b/tests/.crumb index ea6d09478..3728092e2 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -290,14 +290,14 @@ } ], "children_root": "sha256:9597c068d5bf4eb27f1d91842813a2b10269c2ccae421dceefb4308030ec0fc2", - "compiled_at": "2026-10-12T16:18:14Z", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:2345fa6923ad5f3cc3886b5c19e6345a728ddb8c810d07e00d754e2ffefa1646", + "digest": "sha256:788442ab21c299f10bd79e6b00bcc478840dc7fe0992e8bc3ae84ce604341085", "evidence_files": 16, "evidence_root": "sha256:96d08097822ad95f4e562c19e0ba5df5a035774c48632f1832912c40a27bd27a", - "files": 1026, - "generated_at_commit": "15c7666a3d3183750adc61edb60b7a84141c104a", - "source_tree": "sha256:56a0fb6880a1ad68c6f0e039a4cc22281da7633e0d2873302539b493083d5c9e" + "files": 1028, + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:57c17899f9cd6b68a9a1a50998040533fe0ec85d61518cef3b56c4643d9a7f40" }, "owner_lane": "", "provenance": { diff --git a/tests/gpu_serving_alloc_count_test.c b/tests/gpu_serving_alloc_count_test.c index cfb62168c..6acd075fb 100644 --- a/tests/gpu_serving_alloc_count_test.c +++ b/tests/gpu_serving_alloc_count_test.c @@ -34,6 +34,7 @@ #include #include "fake_m16_native.h" +#include "nvrm.h" /* the session reaches the fake driver through the Linux reference platform (P07 cut C) */ #include "omega_gpu_attention_api.h" #include "omega_gpu_matmul_api.h" #include "omega_gpu_serving.h" diff --git a/tests/test_omega_gpu_platform.c b/tests/test_omega_gpu_platform.c index ceeba2f54..73e81f635 100644 --- a/tests/test_omega_gpu_platform.c +++ b/tests/test_omega_gpu_platform.c @@ -35,7 +35,7 @@ static void full_platform(OmegaGpuPlatform *p) memset(p, 0, sizeof *p); p->time_now_ms = f_now; p->wait_ms = f_wait; p->lock = f_lock; p->unlock = f_lock; p->mmio_read32 = f_rd; p->mmio_write32 = f_wr; p->dma_alloc = f_alloc; p->dma_free = f_free; - p->sync_cpu_to_gpu = f_sync; p->sync_gpu_to_cpu = f_sync; p->wait_word = f_word; + p->sync_cpu_to_gpu = f_sync; p->sync_gpu_to_cpu = f_sync; p->poll_word = f_word; } static void caps_v1(OmegaGpuPlatformCaps *c) @@ -82,7 +82,7 @@ static void case_negotiate(void) p.services |= OMEGA_GPU_SVC_IRQ; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_OK); /* unknown service bits are malformed */ - p.services |= 1u << 9; + p.services |= 1u << 12; /* the first bit past ABI 1.1 */ EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_ARGS); /* every limit */ caps_v1(&p); caps_v1(&r); r.max_devices = 2; EXPECT(omega_gpu_platform_negotiate(&p, &r) == OMEGA_GPU_PLAT_REFUSED_LIMIT); @@ -117,7 +117,7 @@ static void case_check_table(void) full_platform(&p); p.mmio_write32 = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); full_platform(&p); p.dma_free = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); full_platform(&p); p.sync_gpu_to_cpu = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); - full_platform(&p); p.wait_word = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); + full_platform(&p); p.poll_word = NULL; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); /* IRQ: claimed needs irq_wait; polling-only platforms do not claim it and must not carry one */ full_platform(&p); c.services |= OMEGA_GPU_SVC_IRQ; EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); @@ -128,6 +128,58 @@ static void case_check_table(void) case_end("SERVICE_TABLE_MATCHES_CLAIMS_NO_HIDDEN_FALLBACK"); } + +/* ABI 1.1: the services the persistent GPU session requires (OMEGA_GPU_SVC_REQUIRED_SESSION). */ +static int f_dopen(void *c, uint32_t o, OmegaGpuDeviceHandle *d) { (void)c; (void)o; d->index = 0; d->generation = 1; return 0; } +static int f_dclose(void *c, OmegaGpuDeviceHandle d) { (void)c; (void)d; return 0; } +static const char *f_diag(void *c) { (void)c; return ""; } +static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle r, OmegaGpuQueueHandle *q) { (void)c; (void)d; (void)r; q->index = 0; q->generation = 1; return 0; } +static int f_qclose(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } +static int f_qsubmit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { (void)c; (void)q; (void)w; (void)n; return 0; } +static int f_qretire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; return 0; } +static uint64_t f_ns(void *c) { (void)c; return 1u; } +static void *f_halloc(void *c, size_t b) { (void)c; (void)b; return NULL; } +static void f_hfree(void *c, void *p) { (void)c; (void)p; } +static void session_platform(OmegaGpuPlatform *p, OmegaGpuPlatformCaps *c) +{ + full_platform(p); + p->mmio_read32 = NULL; p->mmio_write32 = NULL; /* the session needs no MMIO: a platform without it is fine */ + p->device_open = f_dopen; p->device_close = f_dclose; p->diag_text = f_diag; + p->queue_open = f_qopen; p->queue_close = f_qclose; p->queue_submit = f_qsubmit; p->queue_retire = f_qretire; + p->time_now_ns = f_ns; p->host_alloc = f_halloc; p->host_free = f_hfree; + caps_v1(c); + c->services = OMEGA_GPU_SVC_REQUIRED_SESSION; +} + +static void case_session_services(void) +{ + OmegaGpuPlatform p; + OmegaGpuPlatformCaps c; + case_begin(); + EXPECT(OMEGA_GPU_PLATFORM_ABI_MINOR == 1u); + EXPECT(!(OMEGA_GPU_SVC_REQUIRED_SESSION & (OMEGA_GPU_SVC_IRQ | OMEGA_GPU_SVC_MMIO))); + session_platform(&p, &c); + EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_OK); + /* the v1 check still demands MMIO, so a session-only platform is not a v1 device-owner platform */ + EXPECT(omega_gpu_platform_check(&p, &c) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); + EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_ALL + 1u) == OMEGA_GPU_PLAT_REFUSED_ARGS); + /* each new service: a missing function is refused */ + session_platform(&p, &c); p.device_close = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); + session_platform(&p, &c); p.diag_text = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); + session_platform(&p, &c); p.queue_retire = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); + session_platform(&p, &c); p.time_now_ns = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); + session_platform(&p, &c); p.host_free = NULL; EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_NULL_SERVICE); + /* a required service not claimed is missing; a function of an unclaimed service is a hidden path */ + session_platform(&p, &c); c.services &= ~OMEGA_GPU_SVC_QUEUE; + EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); + EXPECT(omega_gpu_platform_check_for(&p, &c, c.services) == OMEGA_GPU_PLAT_REFUSED_ARGS); + /* polling never claims IRQ: a session platform with an irq_wait it does not claim is refused */ + session_platform(&p, &c); p.irq_wait = f_irq; + EXPECT(omega_gpu_platform_check_for(&p, &c, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_REFUSED_ARGS); + EXPECT(omega_gpu_platform_negotiate(&c, &c) == OMEGA_GPU_PLAT_OK); + EXPECT(OMEGA_GPU_POLL_TIMED_OUT >= (int)OMEGA_GPU_PLAT_REFUSAL_COUNT); + case_end("SESSION_SERVICES_ABI_1_1_POLLING_NOT_IRQ"); +} static void case_buffers(void) { OmegaGpuBufferDesc d; @@ -223,8 +275,8 @@ static void case_handles(void) /* table capacity */ omega_gpu_handles_init(&t); for (n = 0; n < OMEGA_GPU_HANDLE_SLOTS; n++) - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, 1000, 1000, &i, &g) == OMEGA_GPU_PLAT_OK); - EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, 1000, 1000, &i, &g) == OMEGA_GPU_PLAT_REFUSED_LIMIT); + EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, OMEGA_GPU_HANDLE_SLOTS + 1u, OMEGA_GPU_HANDLE_SLOTS + 1u, &i, &g) == OMEGA_GPU_PLAT_OK); + EXPECT(omega_gpu_handles_open(&t, OMEGA_GPU_HANDLE_BUF_DATA, 1, OMEGA_GPU_HANDLE_SLOTS + 1u, OMEGA_GPU_HANDLE_SLOTS + 1u, &i, &g) == OMEGA_GPU_PLAT_REFUSED_LIMIT); /* a wrapped generation retires the slot instead of reissuing generation 0 */ omega_gpu_handles_init(&t); t.generation[0] = 0xFFFFFFFFu; @@ -247,7 +299,7 @@ static void case_sizes(void) EXPECT(sizeof(OmegaGpuQueueHandle) == 8u); EXPECT(sizeof(OmegaGpuVa) == 8u && sizeof(OmegaGpuBusAddr) == 8u); EXPECT(sizeof(OmegaCpuView) == sizeof(void *) + sizeof(size_t)); - EXPECT(OMEGA_GPU_SVC_REQUIRED_V1 == (OMEGA_GPU_SVC_ALL & ~OMEGA_GPU_SVC_IRQ)); + EXPECT((OMEGA_GPU_SVC_REQUIRED_V1 | OMEGA_GPU_SVC_IRQ) == 0xFFu); /* the v1 bits; 1.1 adds 8..11 */ case_end("HANDLE_AND_ADDRESS_SHAPES"); } @@ -256,6 +308,7 @@ int main(void) case_names(); case_negotiate(); case_check_table(); + case_session_services(); case_buffers(); case_handles(); case_sizes(); diff --git a/tests/test_omega_gpu_platform_linux.c b/tests/test_omega_gpu_platform_linux.c new file mode 100644 index 000000000..0fae39ab1 --- /dev/null +++ b/tests/test_omega_gpu_platform_linux.c @@ -0,0 +1,188 @@ +/* test_omega_gpu_platform_linux: the Linux REFERENCE platform (src/omega_gpu_platform_linux.c, reference only) on the + * simulated driver (tests/fake_m16_native.c). Host program, hosted build, opens no device. + * + * What it checks: the reference claims exactly the session service set (no MMIO, no IRQ: polling is never claimed as + * an interrupt) and passes the contract check; the hosted session installs it by default; the session makes the same + * driver calls in the same order as before P07 cut C (channel, then the four session buffers through + * nvrm_alloc_gpu_uncached, one submit with the C3 tail, both marker waits, close); the reference refuses a GPU-cached + * buffer, a poll of a buffer that is not HOST_POLLED, freeing the live queue ring, an oversize submit and every handle + * of a closed device; the driver's own failure text survives an open failure; a marker that never lands latches the + * session, which then frees nothing and closes nothing. Each case runs in its own child process. + */ +#include "fake_m16_native.h" +#include "nvrm.h" +#include "omega_blackwell_submit.h" +#include "omega_gpu_platform_linux.h" +#include "omega_gpu_session.h" + +#include +#include +#include +#include +#include + +/* The three driver symbols the session path needs that the fake (written for the vector engine) lacks. */ +static int g_open_fail; +int nvrm_open(Nvrm *rm) { + if (g_open_fail) { snprintf(rm->err, sizeof rm->err, "fake RM: open refused"); return -1; } + fk.device_open = 1; return 0; +} +int nvrm_close(Nvrm *rm) { (void)rm; return 0; } +static int g_retires; +void nvrm_retire(Nvrm *rm, uint32_t upto) { (void)rm; (void)upto; g_retires++; } + +static int case_ok; +#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) + +static const uint32_t ARGS[4] = {1, 2, 3, 4}; +static OmegaGpuLaunch launch_desc(uint64_t timeout_ms) { + OmegaGpuLaunch L = { .code_va = 0x200000000ull, .gpr_count = 64, .threads_x = 32, .grid_x = 1, .grid_y = 1, + .num_elements = 32, .args = ARGS, .n_args = 4, .timeout_ms = timeout_ms }; + return L; +} + +static void c_caps(void) { + OmegaGpuPlatformCaps caps; + const OmegaGpuPlatform *p = omega_gpu_platform_linux(&caps); + EXPECT(p != NULL); + EXPECT(caps.services == OMEGA_GPU_SVC_REQUIRED_SESSION); + EXPECT(!(caps.services & OMEGA_GPU_SVC_IRQ) && !(caps.services & OMEGA_GPU_SVC_MMIO)); + EXPECT(p->irq_wait == NULL && p->mmio_read32 == NULL && p->mmio_write32 == NULL); + EXPECT(omega_gpu_platform_check_for(p, &caps, OMEGA_GPU_SVC_REQUIRED_SESSION) == OMEGA_GPU_PLAT_OK); + EXPECT(caps.abi_major == 1 && caps.abi_minor == 1); +} + +static void c_default_install(void) { + fake_reset(); + EXPECT(omega_gpu_session_platform() == omega_gpu_platform_linux(NULL)); /* hosted: the reference by default */ + EXPECT(omega_gpu_session_completion_mode() == OMEGA_GPU_COMPLETION_POLLING); +} + +static void c_same_driver_calls(void) { + fake_reset(); + fk.kernel_mode = FK_KERNEL_SKIP; + omega_gpu_session_lock(); + OmegaGpuSession *s = omega_gpu_session_open(); + EXPECT(s != NULL); + if (!s) { printf(" %s\n", omega_gpu_session_last_error()); omega_gpu_session_unlock(); return; } + EXPECT(fk.channel_calls == 1 && fk.uncached_calls == 4 && fk.alloc_calls == 4 && fk.live == 4); + const int ch = fake_nth(FK_EV_CHANNEL, 1), a1 = fake_nth(FK_EV_ALLOC, 1); + EXPECT(ch >= 0 && a1 > ch); /* channel first, then the session buffers */ + EXPECT(fk.ev[fake_nth(FK_EV_ALLOC, 1)].a == 0x10000 && fk.ev[fake_nth(FK_EV_ALLOC, 2)].a == 0x1000 && + fk.ev[fake_nth(FK_EV_ALLOC, 3)].a == 0x1000 && fk.ev[fake_nth(FK_EV_ALLOC, 4)].a == 0x10000); + OmegaGpuLaunch L = launch_desc(1000); + uint32_t mk = 0; + EXPECT(omega_gpu_session_launch(&L, NULL, &mk) == 0); + EXPECT(fk.submit_calls == 1 && fk.pb_mem_size == 0x10000); + EXPECT(fake_count(FK_EV_PB_RELEASE) == 2 && fake_count(FK_EV_PB_FLUSH) == 1); /* the C3 tail */ + EXPECT(fk.marker1_va == s->marker.va && fk.marker2_va == s->marker.va + 0x10); + EXPECT(fk.sem_va == s->qmd.va + 0x2000 && fk.sem_init_value == OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT); + EXPECT(mk == OMEGA_BW_MARKER_COMPLETION_PAYLOAD && g_retires == 1); + omega_gpu_session_unlock(); + omega_gpu_session_close(); + EXPECT(fk.free_calls == 4 && fk.close_calls == 1 && fk.live_at_close == 0 && fk.double_free == 0); +} + +static void c_reference_refusals(void) { + fake_reset(); + OmegaGpuPlatformCaps caps; + const OmegaGpuPlatform *p = omega_gpu_platform_linux(&caps); + OmegaGpuDeviceHandle d; + EXPECT(p->device_open(p->ctx, 0, &d) == OMEGA_GPU_PLAT_OK); + OmegaGpuDeviceHandle d2; + EXPECT(p->device_open(p->ctx, 0, &d2) == OMEGA_GPU_PLAT_REFUSED_LIMIT); /* one device context */ + OmegaGpuBufferDesc cached = {.kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE, + .gpu_cache = OMEGA_GPU_CACHE_GPU_CACHED, .bytes = 4096}; + OmegaGpuBufferHandle h; OmegaCpuView cpu; OmegaGpuVa va; OmegaGpuBusAddr bus; + const int allocs0 = fk.alloc_calls; + EXPECT(p->dma_alloc(p->ctx, d, &cached, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); + cached.rights |= OMEGA_GPU_RIGHT_HOST_POLLED; /* polled and cached: the contract refuses it too */ + EXPECT(p->dma_alloc(p->ctx, d, &cached, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_CACHE_POLICY); + EXPECT(fk.alloc_calls == allocs0); /* refused before the driver */ + OmegaGpuBufferDesc data = {.kind = OMEGA_GPU_HANDLE_BUF_DATA, .rights = OMEGA_GPU_RIGHT_CPU_READ | OMEGA_GPU_RIGHT_GPU_WRITE, + .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .bytes = 4096}; + EXPECT(p->dma_alloc(p->ctx, d, &data, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_OK); + EXPECT(cpu.ptr != NULL && cpu.len >= 4096 && bus.iova == 0); + uint32_t seen = 0; + EXPECT(p->poll_word(p->ctx, h, 0, 1, 1, &seen) == OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS); /* not HOST_POLLED */ + OmegaGpuBufferDesc ring = {.kind = OMEGA_GPU_HANDLE_BUF_QUEUE, .rights = OMEGA_GPU_RIGHT_CPU_WRITE | OMEGA_GPU_RIGHT_GPU_READ, + .gpu_cache = OMEGA_GPU_CACHE_GPU_UNCACHED, .bytes = 4096}; + OmegaGpuBufferHandle rh; OmegaGpuQueueHandle q; + EXPECT(p->dma_alloc(p->ctx, d, &ring, &rh, &cpu, &va, &bus) == OMEGA_GPU_PLAT_OK); + EXPECT(p->queue_open(p->ctx, d, h, &q) == OMEGA_GPU_PLAT_REFUSED_BAD_KIND); /* a DATA buffer is not a ring */ + EXPECT(p->queue_open(p->ctx, d, rh, &q) == OMEGA_GPU_PLAT_OK); + EXPECT(p->dma_free(p->ctx, rh) == OMEGA_GPU_PLAT_REFUSED_BUSY); /* the open queue still uses it */ + static uint32_t big[2048]; + EXPECT(p->queue_submit(p->ctx, q, big, 2048) == OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH); /* 8 KiB into a 4 KiB ring */ + EXPECT(fk.submit_calls == 0); + const int frees0 = fk.free_calls; + EXPECT(p->device_close(p->ctx, d) == OMEGA_GPU_PLAT_OK); + /* every handle of the closed device is stale */ + EXPECT(p->dma_free(p->ctx, h) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); + EXPECT(p->sync_cpu_to_gpu(p->ctx, h, 0, 4) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); + EXPECT(p->queue_submit(p->ctx, q, big, 4) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); + EXPECT(p->dma_alloc(p->ctx, d, &data, &h, &cpu, &va, &bus) == OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE); + EXPECT(fk.free_calls == frees0); + EXPECT(strstr(p->diag_text(p->ctx), "STALE") != NULL); +} + +static void c_open_failure_text(void) { + fake_reset(); + fk.channel_fail = 1; + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() == NULL); + EXPECT(strncmp(omega_gpu_session_last_error(), "m16_native_create_channel: ", 27) == 0); + EXPECT(strstr(omega_gpu_session_last_error(), FK_TEXT) != NULL); /* the driver's own text survives */ + fk.channel_fail = 0; + g_open_fail = 1; + EXPECT(omega_gpu_session_open() == NULL); + EXPECT(strcmp(omega_gpu_session_last_error(), "nvrm_open: fake RM: open refused") == 0); + g_open_fail = 0; + EXPECT(omega_gpu_session_open() != NULL && !omega_gpu_session_is_blocked()); + omega_gpu_session_unlock(); + omega_gpu_session_close(); +} + +static void c_marker_never_latches(void) { + fake_reset(); + fk.kernel_mode = FK_KERNEL_SKIP; + fk.marker_mode = FK_SYNC_NEVER; + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() != NULL); + OmegaGpuLaunch L = launch_desc(5); + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); + EXPECT(omega_gpu_session_is_blocked()); + EXPECT(fk.wait_calls == 5 && fk.clock_ms == 5); /* five 1 ms poll slices, then uncertain */ + EXPECT(g_retires == 0); + omega_gpu_session_unlock(); + omega_gpu_session_close(); + EXPECT(fk.free_calls == 0 && fk.close_calls == 0 && fk.live == 4); /* parked: nothing released, nothing closed */ + OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); + EXPECT(ps.buffers == 4); +} + +typedef struct { const char *id; void (*fn)(void); } Case; +static const Case CASES[] = { + {"LINUX_REF_CAPS_NO_MMIO_NO_IRQ", c_caps}, + {"HOSTED_DEFAULT_IS_LINUX_REFERENCE", c_default_install}, + {"SAME_DRIVER_CALLS_AND_ORDER_AS_BEFORE", c_same_driver_calls}, + {"REFERENCE_REFUSALS_CACHED_POLLED_RING_STALE", c_reference_refusals}, + {"OPEN_FAILURE_KEEPS_DRIVER_TEXT", c_open_failure_text}, + {"MARKER_NEVER_LATCHES_AND_PARKS", c_marker_never_latches}, +}; + +int main(void) { + int pass = 0, fail = 0; + for (size_t i = 0; i < sizeof CASES / sizeof CASES[0]; i++) { + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } + int st = 0; + waitpid(pid, &st, 0); + const int ok = WIFEXITED(st) && WEXITSTATUS(st) == 0; + printf("%s %s\n", ok ? "PASS" : "FAIL", CASES[i].id); + if (ok) pass++; else fail++; + } + printf("test_omega_gpu_platform_linux (reference only, simulated driver): %d passed, %d failed\n", pass, fail); + return fail ? 1 : 0; +} diff --git a/tests/test_omega_gpu_session_platform.c b/tests/test_omega_gpu_session_platform.c new file mode 100644 index 000000000..32317fcfe --- /dev/null +++ b/tests/test_omega_gpu_session_platform.c @@ -0,0 +1,517 @@ +/* test_omega_gpu_session_platform: the portable GPU session (native v1 P07 cut C, session part; aienos#286) on a + * FAKE OmegaGpuPlatform. Host program; links the FREESTANDING partial-link object (build/gpu_fs/ + * omega_gpu_freestanding.o: session, matmul and attention APIs, serving, wait, codegen, platform contract), so what + * runs here is the code the native build would run. Opens no device, touches no GPU. + * + * The fake device "completes" a launch at submit time by writing the intermediate semaphore DONE and both marker + * payloads, or (hang mode) writes nothing. Its clock advances only when asked (plus 1 us per read), so timeouts are + * exact and instant. Each case runs in its own child process because an uncertain completion latches the process + * for good (that is the rule under test). + * + * Cases: platform install refusals; freestanding build has no default platform; open/launch/close with typed + * buffers, explicit rights and GPU-uncached policy (host-polled marker); polling only (irq never called, mode is + * POLLING); cancel before submit (nothing submitted, not latched); cancel after submit (latched, parked); timeout + * (latched, session buffers parked, later frees park, close/reopen/install refused, nothing released); stale handle + * refusal after close and reopen; close/reopen (new device generation, opens 2); serving reservation refusal (no + * platform allocation); matmul API code buffer is a CODE buffer encoded in place; wait helper refuses without a clock; + * the bounded formatter matches snprintf and never writes past its cap. + */ +#include "omega_gpu_session.h" +#include "omega_gpu_matmul_api.h" +#include "omega_gpu_wait.h" +#include "omega_gpu_fmt.h" +#include "omega_blackwell_submit.h" + +#include +#include +#include +#include +#include + +static int case_ok; +#define EXPECT(c) do { if (!(c)) { case_ok = 0; printf(" expect failed at line %d: %s\n", __LINE__, #c); } } while (0) + +/* ---- the fake platform ---- */ +#define NB OMEGA_GPU_HANDLE_SLOTS +enum { MODE_COMPLETE = 0, MODE_HANG = 1 }; +static struct { + OmegaGpuHandleTable t; + void *mem[NB]; + OmegaGpuBufferDesc desc[NB]; + uint32_t dev_of[NB]; /* device generation a buffer belongs to */ + OmegaGpuDeviceHandle dev; + OmegaGpuQueueHandle q; + OmegaGpuBufferHandle ring; + int mode; + int cancel_on_poll; /* poll_word calls omega_gpu_session_cancel() on its first call */ + uint64_t ns; + unsigned allocs, frees, free_refusals, submits, polls, retires, syncs, irq_calls, dev_opens, dev_closes; + unsigned locks_held; + unsigned cached_requests; /* buffers asked GPU-cached (must stay 0) */ + unsigned allocs_unlocked; /* allocations without the session lock (must stay 0) */ + int fail_open; +} fk; + +static uint64_t f_now_ns(void *c) { (void)c; fk.ns += 1000u; return fk.ns; } +static uint64_t f_now_ms(void *c) { return f_now_ns(c) / 1000000u; } +static int f_wait(void *c, uint64_t ms) { (void)c; fk.ns += ms * 1000000u; return 0; } +static int f_lock(void *c, uint32_t id) { (void)c; if (id != OMEGA_GPU_SESSION_LOCK_ID) return OMEGA_GPU_PLAT_REFUSED_ARGS; fk.locks_held++; return 0; } +static int f_unlock(void *c, uint32_t id) { (void)c; if (id != OMEGA_GPU_SESSION_LOCK_ID || !fk.locks_held) return OMEGA_GPU_PLAT_REFUSED_ARGS; fk.locks_held--; return 0; } +static const char *f_diag(void *c) { (void)c; return fk.fail_open ? "fake device: no GB10 here" : ""; } + +static int f_dev_open(void *c, uint32_t ord, OmegaGpuDeviceHandle *out) { + (void)c; + if (fk.fail_open) return OMEGA_GPU_PLAT_REFUSED_DEVICE; + if (ord != 0 || fk.dev.generation) return OMEGA_GPU_PLAT_REFUSED_LIMIT; + int rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_DEVICE, 0, 1, 0, &out->index, &out->generation); + if (rc == 0) { fk.dev = *out; fk.dev_opens++; } + return rc; +} +static int f_dev_close(void *c, OmegaGpuDeviceHandle d) { + (void)c; + int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); + if (rc) return rc; + for (uint32_t i = 0; i < NB; i++) /* every handle of the device goes stale */ + if (fk.t.live[i] && i != d.index) { (void)omega_gpu_handles_close(&fk.t, i, fk.t.generation[i], fk.t.kind[i]); free(fk.mem[i]); fk.mem[i] = NULL; } + (void)omega_gpu_handles_close(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); + memset(&fk.dev, 0, sizeof fk.dev); memset(&fk.q, 0, sizeof fk.q); + fk.dev_closes++; + return 0; +} + +static OmegaGpuPlatformCaps g_caps = { + .abi_major = OMEGA_GPU_PLATFORM_ABI_MAJOR, .abi_minor = OMEGA_GPU_PLATFORM_ABI_MINOR, + .services = OMEGA_GPU_SVC_REQUIRED_SESSION, .max_devices = 1, .max_buffers = 1000, .max_queues = 1, .max_inflight = 1, + .max_buffer_bytes = 1ull << 30, .max_total_bytes = 1ull << 32, +}; + +static int f_alloc(void *c, OmegaGpuDeviceHandle d, const OmegaGpuBufferDesc *desc, OmegaGpuBufferHandle *o, + OmegaCpuView *cpu, OmegaGpuVa *g, OmegaGpuBusAddr *b) { + (void)c; + int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); + if (!rc) rc = omega_gpu_platform_check_buffer(desc, &g_caps); + if (rc) return rc; + if (desc->gpu_cache != OMEGA_GPU_CACHE_GPU_UNCACHED) fk.cached_requests++; + if (!fk.locks_held) fk.allocs_unlocked++; + rc = omega_gpu_handles_open(&fk.t, desc->kind, desc->bytes, 1000, 1ull << 32, &o->index, &o->generation); + if (rc) return rc; + void *m = calloc(1, desc->bytes); + fk.mem[o->index] = m; fk.desc[o->index] = *desc; fk.dev_of[o->index] = d.generation; + cpu->ptr = m; cpu->len = desc->bytes; g->va = 0x100000000ull + (uint64_t)o->index * 0x1000000ull; b->iova = 0; + fk.allocs++; + return 0; +} +static int f_free(void *c, OmegaGpuBufferHandle h) { + (void)c; + if (h.index >= NB) { fk.free_refusals++; return OMEGA_GPU_PLAT_REFUSED_BAD_HANDLE; } + int rc = omega_gpu_handles_close(&fk.t, h.index, h.generation, fk.t.kind[h.index]); + if (rc) { fk.free_refusals++; return rc; } + free(fk.mem[h.index]); fk.mem[h.index] = NULL; + fk.frees++; + return 0; +} +static int buf_live(OmegaGpuBufferHandle h) { + return h.index < NB && fk.t.live[h.index] && fk.t.generation[h.index] == h.generation; +} +static int f_sync(void *c, OmegaGpuBufferHandle h, uint64_t off, uint64_t len) { + (void)c; + if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; + if (len == 0 || off > fk.desc[h.index].bytes || len > fk.desc[h.index].bytes - off) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; + fk.syncs++; + return 0; +} +static int f_poll(void *c, OmegaGpuBufferHandle h, uint64_t off, uint32_t want, uint64_t ms, uint32_t *seen) { + (void)c; + if (!buf_live(h)) return OMEGA_GPU_PLAT_REFUSED_STALE_HANDLE; + if (!(fk.desc[h.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)) return OMEGA_GPU_PLAT_REFUSED_BAD_RIGHTS; + fk.polls++; + if (fk.cancel_on_poll) { fk.cancel_on_poll = 0; omega_gpu_session_cancel(); } + volatile uint32_t *w = (volatile uint32_t *)((uint8_t *)fk.mem[h.index] + off); + *seen = *w; + if ((int32_t)(*w - want) >= 0) return 0; + fk.ns += ms * 1000000u; + return OMEGA_GPU_POLL_TIMED_OUT; +} +static int f_irq(void *c, OmegaGpuDeviceHandle d, uint64_t t) { (void)c; (void)d; (void)t; fk.irq_calls++; return 0; } +static int f_qopen(void *c, OmegaGpuDeviceHandle d, OmegaGpuBufferHandle ring, OmegaGpuQueueHandle *o) { + (void)c; + int rc = omega_gpu_handles_check(&fk.t, d.index, d.generation, OMEGA_GPU_HANDLE_DEVICE); + if (!rc && (!buf_live(ring) || fk.t.kind[ring.index] != OMEGA_GPU_HANDLE_BUF_QUEUE)) rc = OMEGA_GPU_PLAT_REFUSED_BAD_KIND; + if (!rc) rc = omega_gpu_handles_open(&fk.t, OMEGA_GPU_HANDLE_QUEUE, 0, 1, 0, &o->index, &o->generation); + if (!rc) { fk.q = *o; fk.ring = ring; } + return rc; +} +static int f_qclose(void *c, OmegaGpuQueueHandle q) { + (void)c; + int rc = omega_gpu_handles_close(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); + if (!rc) memset(&fk.q, 0, sizeof fk.q); + return rc; +} +/* The fake device: the launch completes at submit (both markers and the semaphore), or never (hang). The marker and + * semaphore addresses are read back from the method words: the QMD page is the buffer whose VA the QMD0 header + * names, the marker page the one whose VA the first release names. */ +static void *va_to_cpu(uint64_t va) { + for (uint32_t i = 0; i < NB; i++) { + if (!fk.mem[i] || !fk.t.live[i]) continue; + uint64_t base = 0x100000000ull + (uint64_t)i * 0x1000000ull; + if (va >= base && va < base + fk.desc[i].bytes) return (uint8_t *)fk.mem[i] + (va - base); + } + return NULL; +} +static int f_submit(void *c, OmegaGpuQueueHandle q, const uint32_t *w, uint32_t n) { + (void)c; + int rc = omega_gpu_handles_check(&fk.t, q.index, q.generation, OMEGA_GPU_HANDLE_QUEUE); + if (rc) return rc; + if ((uint64_t)n * 4u > fk.desc[fk.ring.index].bytes) return OMEGA_GPU_PLAT_REFUSED_BAD_LENGTH; + memcpy(fk.mem[fk.ring.index], w, (size_t)n * 4u); + fk.submits++; + if (fk.mode != MODE_COMPLETE) return 0; + for (uint32_t i = 0; i + 5 < n; i++) { + if (w[i] == ((2u << 28) | (5u << 16) | (0u << 13) | (0x005cu >> 2))) { /* release: va lo, va hi, payload */ + uint64_t va = (uint64_t)w[i + 1] | ((uint64_t)w[i + 2] << 32); + uint32_t *m = va_to_cpu(va); + if (m) *m = w[i + 3]; + } + if (w[i] == ((2u << 28) | (2u << 16) | (1u << 13) | (0x0188u >> 2)) && w[i + 3] == ((2u << 28) | (2u << 16) | (1u << 13) | (0x0180u >> 2)) && + w[i + 4] == 4u) { /* the semaphore init upload: the kernel ran, the semaphore says DONE */ + uint32_t *s = va_to_cpu(((uint64_t)w[i + 1] << 32) | w[i + 2]); + if (s) *s = OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE; + } + } + return 0; +} +static int f_retire(void *c, OmegaGpuQueueHandle q) { (void)c; (void)q; fk.retires++; return 0; } +static void *f_halloc(void *c, size_t b) { (void)c; return malloc(b); } +static void f_hfree(void *c, void *p) { (void)c; free(p); } + +static OmegaGpuPlatform g_plat = { + .ctx = &fk, .time_now_ms = f_now_ms, .wait_ms = f_wait, .lock = f_lock, .unlock = f_unlock, + .dma_alloc = f_alloc, .dma_free = f_free, .sync_cpu_to_gpu = f_sync, .sync_gpu_to_cpu = f_sync, .poll_word = f_poll, + .device_open = f_dev_open, .device_close = f_dev_close, .diag_text = f_diag, + .queue_open = f_qopen, .queue_close = f_qclose, .queue_submit = f_submit, .queue_retire = f_retire, + .time_now_ns = f_now_ns, .host_alloc = f_halloc, .host_free = f_hfree, +}; + +static void fk_reset(void) { memset(&fk, 0, sizeof fk); omega_gpu_handles_init(&fk.t); } + +static int install(void) { return omega_gpu_session_set_platform(&g_plat, &g_caps); } + +static const uint32_t ARGS[4] = {1, 2, 3, 4}; +static OmegaGpuLaunch launch_desc(uint64_t timeout_ms) { + OmegaGpuLaunch L = { .code_va = 0x200000000ull, .gpr_count = 64, .threads_x = 32, .grid_x = 1, .grid_y = 1, + .num_elements = 32, .args = ARGS, .n_args = 4, .timeout_ms = timeout_ms }; + return L; +} + +/* ---- cases ---- */ + +static void c_install_refusals(void) { + fk_reset(); + OmegaGpuPlatform p = g_plat; + OmegaGpuPlatformCaps caps = g_caps; + caps.services &= ~OMEGA_GPU_SVC_CLOCK_NS; p.time_now_ns = NULL; + EXPECT(omega_gpu_session_set_platform(&p, &caps) == OMEGA_GPU_PLAT_REFUSED_MISSING_SERVICE); + p = g_plat; caps = g_caps; + p.irq_wait = f_irq; /* a function for a service it does not claim: refused, never used */ + const int rc_irq = omega_gpu_session_set_platform(&p, &caps); + EXPECT(rc_irq != OMEGA_GPU_PLAT_OK && omega_gpu_session_platform() == NULL); + caps = g_caps; caps.abi_minor = 0; + EXPECT(omega_gpu_session_set_platform(&g_plat, &caps) == OMEGA_GPU_PLAT_REFUSED_ABI); + EXPECT(omega_gpu_session_platform() == NULL); /* nothing was installed */ + EXPECT(install() == OMEGA_GPU_PLAT_OK); + EXPECT(omega_gpu_session_platform() == &g_plat); + EXPECT(omega_gpu_session_completion_mode() == OMEGA_GPU_COMPLETION_POLLING); +} + +static void c_no_default_platform(void) { + fk_reset(); + /* the freestanding build has no Linux fallback: nothing installed means refused, not emulated */ + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() == NULL); + EXPECT(strstr(omega_gpu_session_last_error(), "no GPU platform installed") != NULL); + omega_gpu_session_unlock(); + EXPECT(omega_gpu_host_alloc(16) == NULL); + EXPECT(omega_gpu_session_now_ns() == 0); +} + +static void c_open_launch_close(void) { + fk_reset(); + EXPECT(install() == 0); + omega_gpu_session_lock(); + EXPECT(fk.locks_held == 1); + OmegaGpuSession *s = omega_gpu_session_open(); + EXPECT(s != NULL); + if (!s) { omega_gpu_session_unlock(); return; } + EXPECT(fk.allocs == 4 && fk.dev_opens == 1); + /* typed buffers, explicit rights, all GPU-uncached; the polled marker is HOST_POLLED */ + EXPECT(fk.t.kind[s->pb.handle.index] == OMEGA_GPU_HANDLE_BUF_QUEUE); + EXPECT(fk.desc[s->marker.handle.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED); + EXPECT(!(fk.desc[s->cbank.handle.index].rights & OMEGA_GPU_RIGHT_HOST_POLLED)); + EXPECT(fk.cached_requests == 0 && fk.allocs_unlocked == 0); + EXPECT(s->pb.va != s->cbank.va && s->marker.size >= 0x1000 && s->qmd.size >= 0x10000); + OmegaGpuLaunch L = launch_desc(100); + uint64_t el = 0; uint32_t mk = 0; + EXPECT(omega_gpu_session_launch(&L, &el, &mk) == 0); + EXPECT(mk == OMEGA_BW_MARKER_COMPLETION_PAYLOAD && fk.submits == 1 && fk.retires == 1 && el > 0); + EXPECT(fk.syncs >= 3); /* explicit CPU->GPU and GPU->CPU visibility, never implicit */ + EXPECT(fk.irq_calls == 0); /* polling only */ + EXPECT(!omega_gpu_session_is_blocked()); + /* a CODE buffer: CPU writes, GPU executes, never GPU-written, prefetch tail zeroed */ + OmegaGpuMem code; + EXPECT(omega_gpu_session_alloc_code(100, &code) == 0); + EXPECT(fk.t.kind[code.handle.index] == OMEGA_GPU_HANDLE_BUF_CODE); + EXPECT((fk.desc[code.handle.index].rights & OMEGA_GPU_RIGHT_GPU_EXEC) && !(fk.desc[code.handle.index].rights & OMEGA_GPU_RIGHT_GPU_WRITE)); + omega_gpu_session_free(&code); + EXPECT(code.cpu == NULL && fk.frees == 1); + omega_gpu_session_unlock(); + EXPECT(fk.locks_held == 0); + omega_gpu_session_close(); + EXPECT(fk.dev_closes == 1 && fk.frees == 5 && fk.t.nlive == 0); + EXPECT(!omega_gpu_session_is_open()); +} + +static void c_cancel_before_submit(void) { + fk_reset(); + EXPECT(install() == 0); + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() != NULL); + omega_gpu_session_cancel(); + OmegaGpuLaunch L = launch_desc(100); + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == OMEGA_GPU_SESSION_CANCELLED); + EXPECT(fk.submits == 0); /* nothing went to the device */ + EXPECT(!omega_gpu_session_is_blocked()); /* so nothing is uncertain */ + OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); + EXPECT(ps.buffers == 0); + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); /* the request was consumed; the session still works */ + omega_gpu_session_unlock(); + omega_gpu_session_close(); + EXPECT(fk.dev_closes == 1); +} + +static void check_latched(unsigned frees_before) { + EXPECT(omega_gpu_session_is_blocked()); + OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); + EXPECT(ps.buffers == 4 && ps.untracked == 0 && ps.bytes >= 0x10000 + 0x1000 + 0x1000 + 0x10000); + /* a buffer the caller frees now is parked too, never released: the device may still be using it */ + OmegaGpuMem m = {0}; + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_alloc(64, &m) != 0); /* no new allocation after a latch */ + omega_gpu_session_unlock(); + EXPECT(fk.frees == frees_before); + omega_gpu_session_close(); + EXPECT(fk.dev_closes == 0 && fk.frees == frees_before); /* close refused: nothing released */ + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() == NULL && strstr(omega_gpu_session_last_error(), "latched") != NULL); + OmegaGpuLaunch L = launch_desc(10); + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); + EXPECT(strstr(omega_gpu_session_last_error(), "process latched") != NULL); + omega_gpu_session_unlock(); + EXPECT(omega_gpu_session_set_platform(&g_plat, &g_caps) == OMEGA_GPU_PLAT_REFUSED_BUSY); + EXPECT(fk.irq_calls == 0); +} + +static void c_timeout_parks(void) { + fk_reset(); + EXPECT(install() == 0); + omega_gpu_session_lock(); + OmegaGpuSession *s = omega_gpu_session_open(); + EXPECT(s != NULL); + OmegaGpuMem user; + EXPECT(omega_gpu_session_alloc(4096, &user) == 0); + fk.mode = MODE_HANG; + OmegaGpuLaunch L = launch_desc(25); + const uint64_t t0 = fk.ns; + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); + EXPECT(strstr(omega_gpu_session_last_error(), "timed out") != NULL); + EXPECT(fk.polls >= 25 && fk.ns - t0 >= 25ull * 1000000u); /* polled in 1 ms slices for the whole timeout */ + EXPECT(fk.retires == 0); /* never retired: the entry may still be in flight */ + OmegaGpuBufferHandle uh = user.handle; + omega_gpu_session_free(&user); + EXPECT(user.cpu == NULL && omega_gpu_session_is_parked(uh)); + EXPECT(omega_gpu_session_is_parked(s->marker.handle) && omega_gpu_session_is_parked(s->pb.handle)); + omega_gpu_session_unlock(); + OmegaGpuParkStats ps; omega_gpu_session_parked(&ps); + EXPECT(ps.buffers == 5); + EXPECT(fk.frees == 0 && fk.t.nlive == 1 + 1 + 5); /* device, queue, 5 buffers: all still allocated */ + /* the generic latch checks expect the four session buffers; the user buffer made it five */ + EXPECT(omega_gpu_session_is_blocked()); + omega_gpu_session_close(); + EXPECT(fk.dev_closes == 0 && fk.frees == 0); +} + +static void c_cancel_after_submit(void) { + fk_reset(); + EXPECT(install() == 0); + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() != NULL); + fk.mode = MODE_HANG; + fk.cancel_on_poll = 1; /* the cancel arrives while the host is polling */ + OmegaGpuLaunch L = launch_desc(60000); + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == OMEGA_GPU_SESSION_CANCELLED); + EXPECT(fk.submits == 1 && fk.polls <= 2); /* seen within one poll slice, not after the 60 s timeout */ + EXPECT(strstr(omega_gpu_session_last_error(), "cancelled after submit") != NULL); + omega_gpu_session_unlock(); + check_latched(0); +} + +static void c_timeout_latch_rules(void) { + fk_reset(); + EXPECT(install() == 0); + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() != NULL); + fk.mode = MODE_HANG; + OmegaGpuLaunch L = launch_desc(3); + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == -1); + omega_gpu_session_unlock(); + check_latched(0); +} + +static void c_stale_after_reopen(void) { + fk_reset(); + EXPECT(install() == 0); + omega_gpu_session_lock(); + OmegaGpuSession *s = omega_gpu_session_open(); + EXPECT(s != NULL); + const OmegaGpuDeviceHandle d1 = s->dev; + OmegaGpuMem old; + EXPECT(omega_gpu_session_alloc(8192, &old) == 0); + omega_gpu_session_unlock(); + omega_gpu_session_close(); /* the caller kept `old` past the close */ + EXPECT(fk.dev_closes == 1); + omega_gpu_session_lock(); + s = omega_gpu_session_open(); + EXPECT(s != NULL && omega_gpu_session_open_count() == 2); + EXPECT(s->dev.index != d1.index || s->dev.generation != d1.generation); /* a new device generation */ + const unsigned frees = fk.frees; + OmegaGpuAllocStats st0, st1; + omega_gpu_session_alloc_stats(&st0); + omega_gpu_session_free(&old); /* a handle of the closed device: refused, nothing released */ + omega_gpu_session_alloc_stats(&st1); + EXPECT(st1.stale_refusals == st0.stale_refusals + 1 && st1.frees == st0.frees); + EXPECT(fk.frees == frees && fk.free_refusals == 1); + EXPECT(strstr(omega_gpu_session_last_error(), "STALE") != NULL || strstr(omega_gpu_session_last_error(), "stale") != NULL); + EXPECT(old.cpu == NULL); + OmegaGpuLaunch L = launch_desc(100); + EXPECT(omega_gpu_session_launch(&L, NULL, NULL) == 0); /* the reopened session works */ + omega_gpu_session_unlock(); + omega_gpu_session_close(); + EXPECT(fk.dev_closes == 2 && fk.t.nlive == 0); +} + +static void c_open_failure_text(void) { + fk_reset(); + EXPECT(install() == 0); + fk.fail_open = 1; + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() == NULL); + EXPECT(strstr(omega_gpu_session_last_error(), "fake device: no GB10 here") != NULL); /* the driver text survives */ + EXPECT(!omega_gpu_session_is_blocked() && fk.allocs == 0); + fk.fail_open = 0; + EXPECT(omega_gpu_session_open() != NULL); /* a failed open is not a latch */ + omega_gpu_session_unlock(); + omega_gpu_session_close(); +} + +static void c_reservation_refusal(void) { + fk_reset(); + EXPECT(install() == 0); + omega_gpu_session_lock(); + EXPECT(omega_gpu_session_open() != NULL); + OmegaGpuScratch sc; memset(&sc, 0, sizeof sc); + EXPECT(omega_gpu_session_scratch_reserve(&sc, 10000) == 0); + const unsigned allocs = fk.allocs; + EXPECT(omega_gpu_session_scratch(&sc, 9000) == 0); + EXPECT(omega_gpu_session_scratch(&sc, sc.cap + 1) == OMEGA_GPU_SESSION_SCRATCH_RESERVED); + EXPECT(fk.allocs == allocs); /* refused loudly, nothing allocated */ + EXPECT(strstr(omega_gpu_session_last_error(), "serving reservation exceeded") != NULL); + omega_gpu_session_scratch_free(&sc); + omega_gpu_session_unlock(); + omega_gpu_session_close(); + EXPECT(fk.t.nlive == 0); +} + +static void c_matmul_code_buffer(void) { + fk_reset(); + EXPECT(install() == 0); + uint16_t b[32 * 16]; + memset(b, 0, sizeof b); + OmegaGpuTensor *t = NULL; + EXPECT(omega_gpu_tensor_upload_bf16(32, 16, b, &t) == OMEGA_GPU_MATMUL_OK); + uint16_t a[32]; memset(a, 0, sizeof a); + float c[16]; + OmegaGpuMatmulInfo info; + /* the fake device runs no kernel, so the result sentinels survive: CHIP_FAIL is the expected verdict here */ + int rc = omega_gpu_matmul_resident_bf16(1, a, t, c, &info); + EXPECT(rc == OMEGA_GPU_MATMUL_CHIP_FAIL && fk.submits >= 1); + unsigned code_bufs = 0; + for (uint32_t i = 0; i < NB; i++) + if (fk.t.live[i] && fk.t.kind[i] == OMEGA_GPU_HANDLE_BUF_CODE) { + code_bufs++; + const uint8_t *p = fk.mem[i]; + unsigned nz = 0; + for (uint32_t j = 0; j < 64; j++) nz += p[j] != 0; + EXPECT(nz > 0); /* the kernel was encoded in place into the device code buffer */ + EXPECT((fk.desc[i].rights & OMEGA_GPU_RIGHT_GPU_EXEC) && !(fk.desc[i].rights & OMEGA_GPU_RIGHT_GPU_WRITE)); + } + EXPECT(code_bufs == 1); + EXPECT(fk.cached_requests == 0 && fk.allocs_unlocked == 0 && fk.irq_calls == 0); + omega_gpu_tensor_free(t); + omega_gpu_session_close(); + EXPECT(fk.t.nlive == 0); +} + +static void c_wait_needs_clock(void) { + volatile uint32_t word = 0; + omega_gpu_wait_report_t r; + EXPECT(!omega_gpu_wait_fixed(&word, 1, &r, NULL)); + EXPECT(r.result == OMEGA_GPU_WAIT_INVALID_STATE); /* no clock in the freestanding build: refused, not unbounded */ +} + +static void c_fmt_matches_snprintf(void) { + char a[96], b[96]; + const long long big = -9223372036854775807LL - 1; + omega_gpu_fmt(a, sizeof a, "%s:%c:%d:%u:%x:%ld:%lu:%lld:%llu:%zu:%%", "stage", 'x', -42, 4000000000u, 0xbeefu, + -7L, 9UL, big, 18446744073709551615ULL, (size_t)12345); + snprintf(b, sizeof b, "%s:%c:%d:%u:%x:%ld:%lu:%lld:%llu:%zu:%%", "stage", 'x', -42, 4000000000u, 0xbeefu, + -7L, 9UL, big, 18446744073709551615ULL, (size_t)12345); + EXPECT(strcmp(a, b) == 0); + char s[8]; + memset(s, 'Z', sizeof s); + omega_gpu_fmt(s, 6, "%s", "truncate me"); + EXPECT(strcmp(s, "trunc") == 0 && s[6] == 'Z' && s[7] == 'Z'); /* bounded: NUL inside cap, nothing past it */ + omega_gpu_fmt(s, 1, "%d", 123); + EXPECT(s[0] == '\0'); +} + +typedef struct { const char *id; void (*fn)(void); } Case; +static const Case CASES[] = { + {"INSTALL_REFUSALS_ABI_1_1", c_install_refusals}, + {"FREESTANDING_NO_DEFAULT_PLATFORM", c_no_default_platform}, + {"OPEN_LAUNCH_CLOSE_TYPED_UNCACHED_POLLING", c_open_launch_close}, + {"OPEN_FAILURE_KEEPS_DRIVER_TEXT", c_open_failure_text}, + {"CANCEL_BEFORE_SUBMIT_NOT_LATCHED", c_cancel_before_submit}, + {"CANCEL_AFTER_SUBMIT_LATCHES_AND_PARKS", c_cancel_after_submit}, + {"TIMEOUT_PARKS_NEVER_RELEASES", c_timeout_parks}, + {"TIMEOUT_LATCH_REFUSES_CLOSE_REOPEN_INSTALL", c_timeout_latch_rules}, + {"STALE_HANDLE_REFUSED_AFTER_CLOSE_REOPEN", c_stale_after_reopen}, + {"SERVING_RESERVATION_REFUSES_WITHOUT_ALLOC", c_reservation_refusal}, + {"MATMUL_CODE_BUFFER_ENCODED_IN_PLACE", c_matmul_code_buffer}, + {"WAIT_REFUSES_WITHOUT_CLOCK", c_wait_needs_clock}, + {"FMT_BOUNDED_MATCHES_SNPRINTF", c_fmt_matches_snprintf}, +}; + +int main(void) { + int pass = 0, fail = 0; + for (size_t i = 0; i < sizeof CASES / sizeof CASES[0]; i++) { + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { case_ok = 1; CASES[i].fn(); fflush(stdout); _exit(case_ok ? 0 : 1); } + int st = 0; + waitpid(pid, &st, 0); + const int ok = WIFEXITED(st) && WEXITSTATUS(st) == 0; + printf("%s %s\n", ok ? "PASS" : "FAIL", CASES[i].id); + if (ok) pass++; else fail++; + } + printf("test_omega_gpu_session_platform: %d passed, %d failed\n", pass, fail); + return fail ? 1 : 0; +} diff --git a/tools/.crumb b/tools/.crumb index 20936ec8c..e8d4c6a12 100644 --- a/tools/.crumb +++ b/tools/.crumb @@ -26,44 +26,44 @@ "children": [ { "digest": "9cd3943087595dd868914a23a9fef7bebda3d78b773762c287ac4b7a6c2e2f40", - "last_commit": "05ed1a10", + "last_commit": "05ed1a1", "name": "argus", "purpose": "Directory tools/argus. Purpose not yet described by a human." }, { "digest": "870928d3974d2e90f8bd2999a69a0e81e8d6026feecc2bd133988da61d8b4bba", - "last_commit": "7683eaaa", + "last_commit": "7683eaa", "name": "brownian", "purpose": "Directory tools/brownian. Purpose not yet described by a human." }, { "digest": "64fe22fe57fab7e61e65cb7652e73dbde613c260cb8677b05d8b98a067231e83", - "last_commit": "00f54b6b", + "last_commit": "00f54b6", "name": "dual_experiment", "purpose": "Runner for the DUAL applicability experiment: runs the pre-registered campaign and writes result" }, { "digest": "11eb4960ad04fe5bd01ee9d2bbb6900712176c0991ecc0b02b3204ac60248eeb", - "last_commit": "38a6a569", + "last_commit": "38a6a56", "name": "estimation", "purpose": "Directory tools/estimation. Purpose not yet described by a human." }, { "digest": "98d1f4d802b90006977d73b14acb92971927f2cf5bdf05d8dc5653a1b10fcf1b", - "last_commit": "ae1dd00a", + "last_commit": "ae1dd00", "name": "turing_verify_indep", "purpose": "Directory tools/turing_verify_indep. Purpose not yet described by a human." } ], "children_root": "sha256:3051f793dc23155cfff1c4a549e97d3bfe74b3e094d3bd812985bba517919051", - "compiled_at": "2026-10-12T10:51:44Z", + "compiled_at": "2026-10-12T16:47:44Z", "compiler": "crumb-compile/1", - "digest": "sha256:285407d8f7949613c6b57b225fa50b2bb076aaa874fded0895d82fbf285fb832", + "digest": "sha256:d7ca15ce0b953f4434663ff5e9ae64e669d30051a6c37b72805d11aec7648af3", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 139, - "generated_at_commit": "e04bd5021b2a4f311fb9838887c170c4bf3164b6", - "source_tree": "sha256:5a8bc055de0e0c544201ed70b9e091c93298f8cce9ef8ff967cade1712e69975" + "generated_at_commit": "a073db70e22eec13128c00554683dd8c59b6f456", + "source_tree": "sha256:a0bff3dd2bd84fc5ec0cc7120c6f0503ddaf18eac6a2ec1c3fc26f1d509a982c" }, "owner_lane": "", "provenance": { diff --git a/tools/probe_gpu_open.sh b/tools/probe_gpu_open.sh index 30d061389..3581b84a3 100755 --- a/tools/probe_gpu_open.sh +++ b/tools/probe_gpu_open.sh @@ -43,7 +43,7 @@ run_variant overlap grep -c 'rc=OK' "$LOG" > "$OUT/ok_count.txt" grep 'rc=' "$LOG" | grep -v 'rc=OK' | grep -v negative_control > "$OUT/failures.txt" echo "end $(date -u +%FT%TZ)" >> "$OUT/device.txt" -cp tests/gpu_session_probe.c src/omega_gpu_session.c tools/probe_gpu_open.sh "$OUT/" +cp tests/gpu_session_probe.c src/omega_gpu_session.c src/omega_gpu_platform.c src/omega_gpu_platform_linux.c tools/probe_gpu_open.sh "$OUT/" (cd "$OUT" && sha256sum -- * > SHA256SUMS) echo "PROBE_GPU_OPEN: negative_control_exit=$neg_rc first_call_failures=$fails/$total (details $OUT/failures.txt)" [ "$neg_rc" != 0 ] || { echo "PROBE_GPU_OPEN: INSTRUMENT FAIL (negative control passed)"; exit 3; } diff --git a/tools/run_gpu_cut4b_chip.sh b/tools/run_gpu_cut4b_chip.sh index 528e2825b..3647b2f73 100755 --- a/tools/run_gpu_cut4b_chip.sh +++ b/tools/run_gpu_cut4b_chip.sh @@ -47,7 +47,7 @@ step matmul_timing ./build/gpu_matmul_api_test --timing --out "$OUT/matmul_ ./tools/probe_gpu_open.sh "$OUT/probe" "$PROBE_N" > "$OUT/probe.log" 2>&1; prc=$? tail -1 "$OUT/probe.log" echo "end $(date -u +%FT%TZ)" >> "$OUT/device.txt" -cp src/omega_gpu_session.c src/omega_gpu_session.h src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h \ +cp src/omega_gpu_session.c src/omega_gpu_session.h src/omega_gpu_platform.c src/omega_gpu_platform_linux.c src/omega_gpu_fmt.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h \ src/omega_gpu_attention_api.c src/omega_gpu_attention_api.h tests/gpu_elementwise_test.c tests/gpu_attention_test.c tests/gpu_matmul_api_test.c "$OUT/" (cd "$OUT" && sha256sum -- * probe/* 2>/dev/null > SHA256SUMS) echo "FB1-CUT4B chip gate failed_steps=$fail probe_rc=$prc receipt=$OUT" ```