Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
About Files History Releases Proposed changes Issues For developers
feat(kernel): native bounded byte pipe primitive (AIENOS-NATIVE-PIPE-1, #428)
merged 1f9cf4e790b6e08a #433 · opened 2026-10-18 22:30 UTC · closed 2026-10-31 02:21 UTC · merged 2026-10-31 02:21 UTC
Imported from GitHub aien-dev/aienux#433, by drakestapleton
Base 4c25c6ce4f179915aa2aba1670bbcc08c5b88a19 · Head ed6fcb3c7fafa8793d34946fac3408846e3d8356
Merged on GitHub as 8b664a57ff8f3a6882854415059c398dd1954792 ; reachable from main d01b2f19cccf3e173a6bdb3541813d467f537a76 (observed 2026-11-18T16:35:39Z)
drakestapleton wrote on 2026-10-18 22:30 UTC
Summary
Implements aienos-mv#428 (AIENOS-NATIVE-PIPE-1): a capability-controlled bounded native byte pipe in the C kernel core, distinct from the 56-byte typed message ring in ipc.h.
Contract read: aien-protocols-mv specs/osh-platform/OSH_PLATFORM_ABI.md at commit fb5fca98e667 (v1 DRAFT, unfrozen), sections 3, 4.4, 8.1, 8.5, 8.6, 9, 12. Choices the draft does not pin are marked UNVERIFIED in pipe.h.
What is in it
core/osh_err.h: one shared copy of the section 8.6 error codes (osh_op.h now includes it; same numbers and strings).
core/pipe.h, core/pipe.c: fixed pool of 4 pipes, 64 KiB each, all static. Read end and write end are separate capabilities (CK_R_READ vs CK_R_WRITE) in the caller's ck_cap_table; every op does ck_cap_lookup at the moment of the effect. Epoch per slot so a capability that outlived its pipe fails STALE. Ops: PIPE_CREATE, STREAM_READ, STREAM_WRITE, STREAM_CLOSE, STREAM_DUP, plus revoke and cancel, behind a versioned frame dispatch (CK_PIPE_ABI_VERSION, unknown op or version refused with NOT_SUPPORTED before any effect). FIFO bytes, partial I/O, WOULD_BLOCK or blocking through a wait/wake hook, last writer closed gives EOF after drain, no reader gives BROKEN_PIPE, revoke scrubs the buffer and wakes both ends, no byte is delivered after it. Stats: max resident bytes, waits, wakeups, cancellations.
tests/test_pipe.c + tests/fixtures/pipe/p001..p020.vec: 20 machine-readable cases (NUL payload, capacity and partial I/O, zero length, broken pipe, EOF, rights, handle reuse, revoke during blocked read and write, close races, both closed, cancel, stalled consumer, malformed frames, limits, dup, transfer). A producer and consumer are interleaved through ck_sched. Tables asserted empty after every case. pipe-mutant rule proves the test fails when the write right check is removed.
core/pipe_test.c + scripts/qemu_ck_pipe_test.sh: TEST-ONLY QEMU driver behind CK_PIPE_TEST, refused with CK_HARDWARE_STAGING and CK_SERVICE; default images are checked not to contain the self-test string.
README and GATES.md notes. Crumbs recompiled with the pinned tool (aien-architecture @ d0f0b95d ).
Verification run on the Spark (host aarch64, gcc 13.3.0, GNU Make 4.3, QEMU 8.2.2)
make -C native/kernel test: PASS (test_pipe 1239 checks, mutants fail as required)
make -C native/kernel sanitize: PASS
make -C native/kernel: default core image builds, no test string inside
scripts/qemu_ck_pipe_test.sh: 22/22 PASS, AIENOS_CK_PIPE: PASS
Host and QEMU evidence only. Nothing physical is qualified. Task lifecycle and shell dispatch over pipes are the separate child issues.
Handoff: Spark ~/handoffs/2026-10-18-aienos-428-pipe.md.
Closes #428
Summary
Implements aienos-mv#428 (AIENOS-NATIVE-PIPE-1): a capability-controlled bounded native byte pipe in the C kernel core, distinct from the 56-byte typed message ring in ipc.h.
Contract read: aien-protocols-mv specs/osh-platform/OSH_PLATFORM_ABI.md at commit fb5fca98e667 (v1 DRAFT, unfrozen), sections 3, 4.4, 8.1, 8.5, 8.6, 9, 12. Choices the draft does not pin are marked UNVERIFIED in pipe.h.
What is in it
core/osh_err.h: one shared copy of the section 8.6 error codes (osh_op.h now includes it; same numbers and strings).
core/pipe.h, core/pipe.c: fixed pool of 4 pipes, 64 KiB each, all static. Read end and write end are separate capabilities (CK_R_READ vs CK_R_WRITE) in the caller's ck_cap_table; every op does ck_cap_lookup at the moment of the effect. Epoch per slot so a capability that outlived its pipe fails STALE. Ops: PIPE_CREATE, STREAM_READ, STREAM_WRITE, STREAM_CLOSE, STREAM_DUP, plus revoke and cancel, behind a versioned frame dispatch (CK_PIPE_ABI_VERSION, unknown op or version refused with NOT_SUPPORTED before any effect). FIFO bytes, partial I/O, WOULD_BLOCK or blocking through a wait/wake hook, last writer closed gives EOF after drain, no reader gives BROKEN_PIPE, revoke scrubs the buffer and wakes both ends, no byte is delivered after it. Stats: max resident bytes, waits, wakeups, cancellations.
tests/test_pipe.c + tests/fixtures/pipe/p001..p020.vec: 20 machine-readable cases (NUL payload, capacity and partial I/O, zero length, broken pipe, EOF, rights, handle reuse, revoke during blocked read and write, close races, both closed, cancel, stalled consumer, malformed frames, limits, dup, transfer). A producer and consumer are interleaved through ck_sched. Tables asserted empty after every case. pipe-mutant proves the test fails when the write right check is removed. pipe-slice-mutant proves it fails when the user-window check is removed.
core/pipe_test.c + scripts/qemu_ck_pipe_test.sh: TEST-ONLY QEMU driver behind CK_PIPE_TEST, refused with CK_HARDWARE_STAGING and CK_SERVICE; default images are checked not to contain the self-test string.
README and GATES.md notes. Crumbs recompiled with the pinned tool (aien-architecture @ d0f0b95d344b4c6628c3d868346932fd247ce168 ). crumb verify: 96 crumbs current.
Review 5711477325
Locking
One ticket lock per pool (lock_ticket / lock_serving), using the same __atomic_* orders as core/smp.c. There is no spinlock type in this kernel. The lock covers every pipe field, refcount, ring, stat, and the live count. Pipe ops are not called from interrupt handlers. If a wake or a cancel is ever called from an IRQ, the lock must mask IRQs, or that CPU deadlocks against itself. It is never held across wait or wake: those hooks re-enter (the scheduler hook runs pipe ops; the cooperative driver runs the peer inside the wait). A waiter increments waiting[end] under the lock before the drop. The wake hook runs only after unlock, and only if a waiter was already published. The wake hook must be sticky: pd_wait does not clear woken[] on entry, so a wake that lands in that window is still observed. before_wait is optional and NULL in the kernel; the host tests use it to force that window. Pool init stores both lock words to 0 before the pool is shared. The capability table is covered only by this pool lock.
Findings
SMP races on the pool, rings, refcounts, and close/teardown: fixed by the ticket lock above. Lost wakeups are closed by publishing waiting[] before the unlock and by the sticky wake flag. The lock is not held across the hooks, so a hook that re-enters does not deadlock.
slice / slice_len in ck_pipe_dispatch: the range check is review 5719220696 (d), below. The earlier note that the syscall must validate the range is now the check at this entry, plus the two duties filed as #494.
A blocking write used to re-read the caller buffer after parking. On the first WOULD_BLOCK of a blocking write, the call copies at most CK_PIPE_WRITE_SNAP (1024) bytes into a kernel stack buffer while the lock is still held, parks, and commits only from that snapshot. The caller buffer is not read again after the park in that call. A write that finds room does not snapshot; it copies straight into the ring, up to the free space. The snapshot is wiped with volatile stores before return.
ck_pipe_release_table counted a handle as closed even when close failed. It now counts a slot only when close returns OSH_E_OK. A forged epoch comes back STALE and is not counted. An index past the pool (>= CK_PIPE_POOL_PIPES) returns DENIED before the capability is removed, and is not counted.
Rebase onto main: not done. The branch contains a true merge of origin/main at 4c25c6ce (#441). No rebase and no force-push. Main has not moved past that commit.
Review 5719220696 (d)
ck_pipe_dispatch takes user_lo and user_hi (hi exclusive). On STREAM_READ and STREAM_WRITE, before the slice is read or written:
len == 0 passes.
Otherwise the base must lie in [user_lo, user_hi) and len <= user_hi - base.
There is no base + len add. A length that would wrap fails the subtraction form.
Anything else returns INVALID_ARG and does not touch the slice.
Kernel callers pass the bounds of their own buffer. A length of 0 does not consult the window. pipe.h requires the syscall layer to assert that user_hi is below the user-VA top on each arch (below TTBR1 / 0xFFFF000000000000 on ARM64, below the canonical upper half on x86) and to copy through a kernel bounce buffer outside the pool lock. Those two duties are #494. pipe.h also requires the sticky woken[] wake hook, and IRQ masking if a wake or cancel path ever runs from an IRQ.
CK_PIPE_MUTANT_SKIP_SLICE (make pipe-slice-mutant) compiles the check out. test_pipe then fails.
AIEN Checks does not run a kernel make target. Its portable smoke set is the gates whose requires is only portable (AIENOS-ZERO-DISK-SECRETS). test_pipe is already on make -C native/kernel test, and pipe-slice-mutant is on that target too. Running it from AIEN Checks would mean teaching .github/workflows/aien-verification.yml to run that make target, or marking aienos-ck-host-tests.gate (requires: host) as portable. No workflow file was edited.
Verification
Earlier Spark run (2026-10-18, recorded in the handoff, not re-run for this review): make -C native/kernel test PASS (test_pipe 1239 checks), sanitize PASS, default image builds with no test string, scripts/qemu_ck_pipe_test.sh 22/22 PASS. Handoff: Spark ~/handoffs/2026-10-18-aienos-428-pipe.md.
This review, on the VM, hardware-unverified. Nothing here ran on a Spark or on real hardware.
Host test_pipe: PASS, 1382 checks (clang 18). The new checks are the user-window cases.
HOSTCC=gcc ASan+UBSan: PASS, 1382 checks.
make pipe-mutant: fails 6 of 1382, as required.
make pipe-slice-mutant: fails 13 of 1262, as required. The mapped out-of-window slices are accepted and move bytes; the wrapping address faults and the test stops, because the copy would run with the ticket lock held.
One-off gcc -fsanitize=thread of test_pipe: PASS, 1382 checks, no race report. Not a Makefile target.
scripts/qemu_ck_pipe_test.sh on this tree: AIENOS_CK_PIPE: PASS (QEMU 8.2.2, aarch64 virt, -smp 4). The pipe self-test is one kernel thread. The -smp 4 boot is not a multi-core pipe result. Concurrent read/write, close-while-parked, and the shared-pool create/close stress ran on host pthreads only.
Closes #428
— Grokbot
<div><a href="https://cursor.com/agents/bc-32327ffa -31b9-524f-bf28-a31c751ca4e3 ?cursor_ref=pr_footer&cursor_cta=open_in_web"> <picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"> <source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"> <img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"> </picture></a> <a href="https://cursor.com/background-agent?bcId=bc-32327ffa -31b9-524f-bf28-a31c751ca4e3 &cursor_ref=pr_footer&cursor_cta=open_in_cursor"> <picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"> <source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"> <img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"> </picture></a> </div>
drakestapleton reviewed (COMMENTED) on 2026-10-30 11:18 UTC
Triage: needs-changes (capability / IPC trust boundary)
The rights handling looks right: attenuation-only dup, authority re-checked when the effect happens, and epoch/generation STALE checks. Findings:
Locking/SMP , native/kernel/core/pipe.c (whole file): the pool is global, and read/write/close/dup/revoke and the ref counts take no lock. Other PRs (#424) run four cores, so this needs a lock or a documented single-core invariant.
User pointer handling , pipe.c ~L396–465 (ck_pipe_dispatch): slice/slice_len go straight to read/write, and nothing in this file checks that they lie in the caller's address space. The syscall layer must validate the range or copy in/out; please document or assert this.
TOCTOU , pipe.c ~L223 (park) with the write loop ~L260–275: a blocking write re-reads the caller's buffer after waking. If that buffer is user memory, its contents can change between retries; copy into the kernel first.
ck_pipe_release_table, pipe.c ~L377–389: counts a handle as closed even when ck_stream_close fails, so the return value can overstate cleanup.
Also: merge conflicts with main, so a rebase is needed. To be merge-ready: rebase, fix 1–3 (and 4), and add a test for concurrent close/park.
drakestapleton reviewed (COMMENTED) on 2026-10-30 22:10 UTC
Re-review at 9869cbdb , following review 5711477325 . Verdict: needs-changes. There is one must-fix item, (d). The rest is met.
Drake's asks in 5711477325 :
Lock the shared pool, or document a single-core invariant. Met , with one ticket lock per pool (see (a)).
Have the syscall layer validate slice/slice_len, or document/assert that it must. Met as written : this is documented in pipe.h L56/L195 and pipe.c L595. The range check itself still doesn't exist, which is (d).
Copy a blocking write into the kernel before parking. Met (see (b)).
release_table must count only successful closes. Met (see (c)).
Rebase. This was replaced by a true merge of main 4c25c6ce , and the conflict is resolved. The head is mergeable and clean.
Add a test for concurrent close and park. Met : test_close_park in test_pipe.c uses pthreads, plus the threaded xfer and pair cases.
(a) Ticket lock. OK, no must-fix.
Every pipe field is read and written only under pool_lock: ring head and len, refcounts, waiting[], flags, stats and live. That covers create, read, write, close, dup, revoke, cancel, release_table and pool_empty.
park() (L294-317) increments waiting[end] under the lock before pool_unlock. It then calls wait without the lock and re-locks afterwards. It decrements waiting[] only when the epoch is unchanged.
Wakes are recorded under the lock (note_wake only fires when a waiter is published) and fired after the unlock. The wake note has room for CK_CAP_SLOTS entries, and each close notes at most one wake, so release_table cannot overflow it.
No wakeup is lost between the drop and the park, because the wake is sticky: pd_wait does not clear woken[] on entry (pipe_drive.h L89-99). That is a contract on any future kernel wait/wake hook : a wake that arrives before wait must stay pending. Please state it in pipe.h's hooks comment.
IRQ masking. Nothing takes the lock from IRQ or timer context today. The only kernel caller is the CK_PIPE_TEST self-test thread (kmain.c). pipe.c is built into the image only under CK_PIPE_TEST. fire_wakes runs in the calling thread, not in an IRQ. So not masking is correct today. If a wake or cancel path is ever called from an IRQ, the lock must mask IRQs, or that CPU deadlocks against itself.
Lock ordering. Each op takes exactly one pool lock, and there is no nesting across pools. The ck_cap_* table calls run inside it, so the order is pool, then cap table. Nothing in ipc.c calls back into pipe.c. Note that the cap table is protected only by this pool lock. Any non-pipe user of the same ck_cap_table on another core would race. That isn't introduced here, but it is worth one line in pipe.h.
Ticket correctness.
Lock: fetch_add RELAXED on the ticket, spinning with an ACQUIRE load of serving.
Unlock: only the holder writes serving, using a RELAXED load and a RELEASE store.
This is correct on ARM64 and x86, it is FIFO-fair, and u32 wrap is harmless.
(b) 1 KiB snapshot. OK.
On the fast path, write_once reads the caller buffer once, straight into the ring.
On the first WOULD_BLOCK of a blocking write, up to CK_PIPE_WRITE_SNAP (1024) bytes are copied into snap[] while the lock is held (L367-374). Every retry then uses src = snap.
Nothing reads the caller buffer after a wake. A blocked write larger than 1 KiB returns a partial count of at most 1024 bytes from the snapshot. Partial I/O is allowed by the op contract, and the caller loops.
snap is wiped with volatile stores on both exit paths.
(c) release_table. OK. It counts only when close_locked(...) == OSH_E_OK (L537). A forged epoch gives STALE, and an index past the pool gives DENIED before the capability is removed (L402-403). Neither is counted.
(d) slice/slice_len. MUST-FIX.
This tree has no syscall path to the pipe. The only callers are the host test and the CK_PIPE_TEST self-test, which use kernel buffers. Nothing validates the range.
ck_pipe_dispatch passes the pointer straight through (L595-598):
/* slice/slice_len are not proved to lie in the caller's address space. ... */
e = op == CK_PIPE_OP_READ ? ck_stream_read(p, caller, h, slice, slice_len, ...)
: ck_stream_write(p, caller, h, slice, slice_len, ...);
ck_stream_read/ck_stream_write check only len && !buf. Nothing checks the user range, slice + len overflow, or kernel addresses.
The first syscall that wires ck_pipe_dispatch to a user frame would hand the kernel an arbitrary read/write primitive. The ring copy loops dereference buf directly, under a spinning lock.
Exact fix. Put the check at the pipe entry so no future caller can skip it.
Add the caller's user window to ck_pipe_dispatch: uintptr_t user_lo, uintptr_t user_hi (hi exclusive). Kernel self-test callers pass the bounds of their kernel buffer.
Add to pipe.c:
static int slice_ok(const void *s, size_t len, uintptr_t lo, uintptr_t hi)
{
uintptr_t b = (uintptr_t)s;
if (len == 0) return 1;
if (lo >= hi || b < lo || b >= hi) return 0;
return len <= hi - b; /* no b + len overflow */
}
In the READ/WRITE case, before the call:
if (!slice_ok(slice, slice_len, user_lo, user_hi)) { e = OSH_E_INVALID_ARG; break; }
Wherever the syscall layer derives user_hi from the task's mapping, assert that it never exceeds the user-VA top: below TTBR1 / 0xFFFF000000000000 on ARM64, and below the canonical upper half on x86.
When the syscall exists, copy in and out through a kernel bounce buffer outside the pool lock, so a user fault never happens with the ticket lock held.
Add test cases for: len == 0; slice + len wrapping (slice = UINTPTR_MAX - 3, len = 8); a slice that starts in range and ends past user_hi; and a kernel-half address. Each must return INVALID_ARG with no effect.
(e) Scope and state. OK.
The chain is 3fc0c3f9 → 404a27a2 (the fix) → aa5c7243 (a true merge with parents 404a27a2 and 4c25c6ce ) → 9869cbdb (crumbs).
4c25c6ce ...9869cbdb touches only PR files, so every main-side file matches its 4c25c6ce blob. Those PR files are:
core/pipe.c, pipe.h, pipe_drive.h, pipe_test.c, osh_err.h and osh_op.{c,h}
kmain.c: the CK_PIPE_TEST hook only
the Makefile pipe rules, test_pipe.c, and fixtures p001-p020
scripts/qemu_ck_pipe_test.sh, the README and GATES.md notes, and crumbs
The AIEN Checks log reads crumb verify: OK: 96 crumbs current. Every check passes; AIEN Alpha was skipped.
The PR is mergeable and clean. The PR's three commit messages are pure ASCII.
Verification limits. The fix is host-tested only, using pthreads under ASan/UBSan plus a one-off TSan run, according to the PR body. I found no test_pipe run in the AIEN Checks log. The QEMU self-test is a single kernel thread, so the -smp 4 boot is not a multi-core result. Multi-core behaviour is hardware-unverified.
— Grokbot
Fetch it
A git bundle of the pull request's head, 89571 bytes.
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/1f9cf4e790b6e08a .bundle -o 1f9cf4e790b6e08a .bundle
git fetch 1f9cf4e790b6e08a .bundle refs/pull/433/head
Raw bundle · 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/aienux
433
ed6fcb3c7fafa8793d34946fac3408846e3d8356
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":433,"url":"https://github.com/aien-dev/aienux/pull/433","export_sha256":"222ed873664c8b6770fec92487a3521a4b5f81629ee6399038e519facf854bee ","imported_utc":"2026-11-18T16:35:39Z"}
Changes
diff --git a/.crumb b/.crumb
index 8a900f40 ..a714ebcd 100644
--- a/.crumb
+++ b/.crumb
@@ -28,19 +28,19 @@
},
{
"digest": "74bb22d6e439ad7405487d6846114229171cd42746cd2c3e7b2c2d41276008c4 ",
- "last_commit": "7ded42c1 ",
+ "last_commit": "4c25c6ce ",
"name": "docs",
"purpose": "Directory docs. Purpose not yet described by a human."
},
{
- "digest": "3a926ce10dde2c007298b9044481d1750b46e912d73d39ead2b4bd78de5696aa ",
- "last_commit": "1a71c956 ",
+ "digest": "296167be2131bbca5563d7d63a5b97326a6bb05619fc57b38a3ce1aa05f15de6 ",
+ "last_commit": "2c149f76 ",
"name": "native",
"purpose": "Directory native. Purpose not yet described by a human."
},
{
- "digest": "2dffaed43899cb00c03694e7e840f7fd844898f3a155797eee43a17f397c8af5 ",
- "last_commit": "9e0e6179 ",
+ "digest": "da2a96be8a25fde997c2d63599b68c250193223946f25c812a27c6794890f83a ",
+ "last_commit": "aa5c7243 ",
"name": "scripts",
"purpose": "Directory scripts. Purpose not yet described by a human."
},
@@ -51,15 +51,15 @@
"purpose": "First-party host artifact preparation tools"
}
],
- "children_root": "sha256:a1d8cf5c29a4e14b678605134b0f741e1b4caa55e889609cd3cc3fcfc262ae42 ",
- "compiled_at": "2026-10-30T21:47:57Z",
+ "children_root": "sha256:f674262b8048a97e759bb44bd65dc123f1e6a4f14e161792318f7e246b805207 ",
+ "compiled_at": "2026-10-30T22:19:45Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:d1303645b17e65fbf189a6d2d4d1580528ae3b4e8bd59c0f0d278384a22e4b52 ",
+ "digest": "sha256:efa02f271a711d3327a1ac10da1780922fed18d4678e850cb230a5121cb161d5 ",
"evidence_files": 274,
"evidence_root": "sha256:af014a4ed8f6fe759fc5809807fb47578d3410811b522d9f65d749382b029802 ",
- "files": 3661,
- "generated_at_commit": "1a71c956cbcae1cca7e88563d50973ea48107961 ",
- "source_tree": "sha256:5de2a534e35595d8cb5d72ab9a62ec19ab98b182b46a33ffe1e7b02f6dc2ddb7 "
+ "files": 3689,
+ "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e ",
+ "source_tree": "sha256:27b32e27060e6ec14a7d8ba81548fc2492cf1e5801ead3a5b2766a32054f2364 "
},
"owner_lane": "",
"provenance": {
diff --git a/native/.crumb b/native/.crumb
index 1ad96d33 ..33a630d1 100644
--- a/native/.crumb
+++ b/native/.crumb
@@ -79,8 +79,8 @@
"purpose": "Directory native/disk. Purpose not yet described by a human."
},
{
- "digest": "503362c5f3ee164bb02c3b3d322e243d9b43036a6821c78db650b6d6e70ec6a9 ",
- "last_commit": "1a71c956 ",
+ "digest": "dff38314f5a4663218092ed0e56904bcbb57f5cdec4e1b7d4cdcdc4845dc2fe0 ",
+ "last_commit": "2c149f76 ",
"name": "kernel",
"purpose": "Directory native/kernel. Purpose not yet described by a human."
},
@@ -115,15 +115,15 @@
"purpose": "Directory native/store. Purpose not yet described by a human."
}
],
- "children_root": "sha256:480627fea04d74898a16d5002a6eb123cf1e83c3f6639eb882b113d401ba728c ",
- "compiled_at": "2026-10-30T21:47:57Z",
+ "children_root": "sha256:5b227b35bd1a67e65dce28d5be0308c90452bb36cae33ad98f6efe7313cc1f68 ",
+ "compiled_at": "2026-10-30T22:19:45Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:3a926ce10dde2c007298b9044481d1750b46e912d73d39ead2b4bd78de5696aa ",
+ "digest": "sha256:296167be2131bbca5563d7d63a5b97326a6bb05619fc57b38a3ce1aa05f15de6 ",
"evidence_files": 24,
"evidence_root": "sha256:ecc7ccf2e924c221a5bac1d91e23b13d8f3c8d78c2a893a882ed7ca5e88d855d ",
- "files": 714,
- "generated_at_commit": "1a71c956cbcae1cca7e88563d50973ea48107961 ",
- "source_tree": "sha256:691f51fd6b78ba6bbe89987b7ea5f284b11f31c61f7801fbe0f5cb8b3ae544d5 "
+ "files": 741,
+ "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e ",
+ "source_tree": "sha256:dfda991de2f45b21220a58ecf0111d034daf175ea3ae07eb5e6e1779f87a18c1 "
},
"owner_lane": "",
"provenance": {
diff --git a/native/kernel/.crumb b/native/kernel/.crumb
index 74b37b0b ..f7a60903 100644
--- a/native/kernel/.crumb
+++ b/native/kernel/.crumb
@@ -57,14 +57,14 @@
"purpose": "Directory native/kernel/artifact. Purpose not yet described by a human."
},
{
- "digest": "d4196275e1dc11d6b92d0fe9b90bbd9b7bbef17cd4ec63bc2fb09acfa7bd7b90 ",
- "last_commit": "a1fc1f34 ",
+ "digest": "3448d48e8498c2a3409e69923020b57bf1146bd1d5913e70f7559cefd9d005bd ",
+ "last_commit": "2c149f76 ",
"name": "core",
"purpose": "Directory native/kernel/core. Purpose not yet described by a human."
},
{
"digest": "bef70d40dabe6ab1d9c94b1ca2134346bd79827441a451fc387b79d00a23caec ",
- "last_commit": "7ded42c1 ",
+ "last_commit": "4c25c6ce ",
"name": "dev",
"purpose": "Directory native/kernel/dev. Purpose not yet described by a human."
},
@@ -87,27 +87,27 @@
"purpose": "Directory native/kernel/svc. Purpose not yet described by a human."
},
{
- "digest": "d532b7b49cd10c87e7e1528820c7d870b1eccd049ffe66cc4162bc01ae71c4a9 ",
- "last_commit": "1a71c956 ",
+ "digest": "59c0ca771d489fe85c31391d5c8c2b70da110f5f13f4c15b9ba126a41ed3e5fa ",
+ "last_commit": "2c149f76 ",
"name": "tests",
"purpose": "Directory native/kernel/tests. Purpose not yet described by a human."
},
{
"digest": "e2b20996fe1250a8288abeb0e61cd9635e6da541384c5b5ba564c5f528e2a5f8 ",
- "last_commit": "9f50e634 ",
+ "last_commit": "4c25c6ce ",
"name": "tools",
"purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin"
}
],
- "children_root": "sha256:d5a0b0a6469bf409c7ae4219c42df2be6e09e89780d8181cae1b24d45b2ac393 ",
- "compiled_at": "2026-10-30T21:47:57Z",
+ "children_root": "sha256:1633084cdb6ab386a5783ff4b09e6f9b4fe268e30108f619dff7d835a10f49b8 ",
+ "compiled_at": "2026-10-30T22:19:45Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:503362c5f3ee164bb02c3b3d322e243d9b43036a6821c78db650b6d6e70ec6a9 ",
+ "digest": "sha256:dff38314f5a4663218092ed0e56904bcbb57f5cdec4e1b7d4cdcdc4845dc2fe0 ",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "files": 459,
- "generated_at_commit": "1a71c956cbcae1cca7e88563d50973ea48107961 ",
- "source_tree": "sha256:a0ea32bfbdd582370681c8a094a8c67a6be0866817556a31523e83cfd7a222e4 "
+ "files": 486,
+ "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e ",
+ "source_tree": "sha256:86cbe2a637b3f6d8e0dbfce7b904824c250a8dacd8eb62d4b3b487ad5093a216 "
},
"owner_lane": "",
"provenance": {
diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md
index e1791cf8 ..f89baa63 100644
--- a/native/kernel/GATES.md
+++ b/native/kernel/GATES.md
@@ -868,6 +868,36 @@ real asynchronous events. (4) Numeric resource-class and operation ids, the REVO
are this adapter's choices (UNVERIFIED against a frozen contract). (5) The request digest covers the request cells and the OUT
bytes; the contract's exact digest input is not defined (UNVERIFIED). (6) The "task" is the adapter's session; the EL0 shell units
hold no capability (caps=0) and the check is made by the kernel-side adapter.
+## PIPE: the native bounded byte pipe (AIENOS-NATIVE-PIPE-1, aienos-mv#428) -> CK `PIPE` (scripts/qemu_ck_pipe_test.sh)
+
+Label: **QEMU (aarch64 virt), TEST build, not physical.** Host and QEMU evidence qualify nothing physical; nothing here ran on
+a Spark, a Pi or the iMac. Contract: OSH_PLATFORM_ABI sections 4.4, 8.1, 8.5, 8.6, 9 read at aien-protocols-mv `fb5fca98e667 `
+(v1 DRAFT, unfrozen). The image is `make CK_PIPE_TEST=1` (own OUT `target/native-kernel-test-pipe`, refused with
+`CK_HARDWARE_STAGING` and `CK_SERVICE`; default images are checked to carry no trace of it). After `kernel: alive` it runs
+`core/pipe_test.c`: a producer and a consumer task, step functions interleaved by `core/sched.c`, each holding one end of a
+`core/pipe.c` pipe in its own capability table (`core/ipc.c`), through the same driver as the host test (`core/pipe_drive.h`);
+then the boot goes on to its report and PSCI reset. Checks, one boot, every one with both tables and the pool empty afterwards:
+160 KiB payload with every fifth byte NUL byte for byte; a slow consumer fills the 64 KiB pipe and the producer sees WOULD_BLOCK;
+EOF after the last writer closes; never more than the capacity buffered; the blocking variant parks and wakes through the
+scheduler; BROKEN_PIPE with no reader; a write after revoke refused with 0 bytes delivered after it; a revoke mid-transfer with no
+read succeeding afterwards; a closed handle STALE after its slot is reused; an unknown op and another ABI version NOT_SUPPORTED;
+cancel INTERRUPTED once with no byte moved. Host test `test_pipe` (the 20-case corpus in `tests/fixtures/pipe/` plus the
+scheduler transfers, also under ASan+UBSan); a mutant that skips the write-right check must fail it (`make pipe-mutant`).
+Limits: (1) the kernel's wait hook yields cooperatively to the scheduler inside one kernel thread; the QEMU image does not
+context-switch a blocked pipe op onto another core. Host `test_pipe` does, with pthreads: concurrent read/write, close while
+the peer is parked (including the window after the waiter is published and before `wait` runs), and create/close on a shared
+pool. That is host-only. It is not a QEMU multi-core result and it qualifies nothing physical. (2) In the QEMU driver, revoke,
+close and cancel "while waiting" are still the peer task's step. The host threaded cases close from a second thread; they are
+not asynchronous interrupts. (3) The op ids, the call frame cell layout, the second return value of
+PIPE_CREATE, the capability resource layout, the pool size (4 pipes) and STREAM_DUP's capability form (rights and a target table
+instead of a descriptor number) are this kernel's choices, UNVERIFIED against a frozen contract. (4) A ck_cap_table has 8 slots,
+below the draft's "3 standard streams plus 16 open streams" per session; a session with more streams needs a larger table.
+(5) No QEMU negative control mutates the kernel image; the red-before-green control is the host mutant.
+
+| # | Check | CK gate | Status |
+|---|---|---|---|
+| 221 | `CK_PIPE_TEST=1` image: 11 `pipe_check` lines PASS with `tables_empty=1`, `pipe_test: done checks=11 failed=0 capacity=65536 pool_pipes=4`, payload detail `bytes=163840 ... mismatches=0 would_block>0`, revoked write `n=0 ... bytes_delivered=0`, boot report reached, no panic, QEMU exit 0 | PIPE | QEMU PASS (2026-10-18, base ee34c7d plus this change, QEMU 8.2.2, AIENOS_CK_PIPE PASS; hardware NOT_RUN) |
+
## LIFECYCLE: resident production lifecycle (native v1 plan P03, P04 cuts 1-2b, P05 cut 1, P06 cuts 2-4; C-only) -> CK `LIFECYCLE` (scripts/qemu_ck_lifecycle_test.sh)
diff --git a/native/kernel/Makefile b/native/kernel/Makefile
index 4602be5f ..89488222 100644
--- a/native/kernel/Makefile
+++ b/native/kernel/Makefile
@@ -505,6 +505,21 @@ endif
OUT ?= $(REPO)/target/native-kernel-test-rollback-$(strip $(CK_TEST_ROLLBACK))
SMP_TEST_FLAGS += -DCK_TEST_ROLLBACK_$(subst -,_,$(shell echo '$(strip $(CK_TEST_ROLLBACK))' | tr a-z A-Z))=1
endif
+# AIENOS-NATIVE-PIPE-1 (aienos-mv#428): CK_PIPE_TEST=1 adds the TEST-ONLY pipe self-test (core/pipe_test.c, gate
+# scripts/qemu_ck_pipe_test.sh): after "kernel: alive" it drives the pipe primitive (core/pipe.c) with a producer and a
+# consumer task through the scheduler and prints pipe_check lines. Own OUT; announces itself; refused with
+# CK_HARDWARE_STAGING and CK_SERVICE. Default images are checked to carry no trace of it (pipe_check).
+CK_PIPE_TEST ?=
+ifneq ($(strip $(CK_PIPE_TEST)),)
+ifneq ($(strip $(CK_PIPE_TEST)),1)
+$(error CK_PIPE_TEST must be empty or 1)
+endif
+ifneq ($(strip $(CK_HARDWARE_STAGING)),)
+$(error CK_PIPE_TEST (TEST-only pipe self-test) cannot be combined with CK_HARDWARE_STAGING)
+endif
+OUT ?= $(REPO)/target/native-kernel-test-pipe
+SMP_TEST_FLAGS += -DCK_PIPE_TEST=1
+endif
# SLOTLDR.EFI trusted keys (native v1 plan P11 cut 2a; native/boot/slot_loader.c,
# make slot-loader):
# CK_SLOT_KEYS=<file> owner public keys, "owner_root_ed25519 <64 hex>" lines
@@ -685,7 +700,7 @@ endif
ifneq ($(strip $(CK_CONSOLE_SESSION)),)
$(error CK_SERVICE cannot be combined with CK_CONSOLE_SESSION)
endif
-ifneq ($(strip $(CK_TEST_XHCI_MUTATION)$(CK_TEST_STORE_CRASH)$(CK_TEST_CONTINUITY)$(CK_TEST_FWCFG_ARTIFACTS)$(CK_TEST_SMP_SKIP_CPU)$(CK_TEST_ROLLBACK)$(CK_TEST_STALE_HANDOFF)$(CK_TEST_DISK_XLATE_BYPASS)),)
+ifneq ($(strip $(CK_TEST_XHCI_MUTATION)$(CK_TEST_STORE_CRASH)$(CK_TEST_CONTINUITY)$(CK_TEST_FWCFG_ARTIFACTS)$(CK_TEST_SMP_SKIP_CPU)$(CK_TEST_ROLLBACK)$(CK_TEST_STALE_HANDOFF)$(CK_TEST_DISK_XLATE_BYPASS)$(CK_PIPE_TEST)),)
$(error CK_SERVICE cannot be combined with a CK_TEST_* flag)
endif
endif
@@ -977,6 +992,9 @@ ART_C += $(KDIR)/core/artifact_card.c $(KDIR)/core/artifact_card_stage.c
CORE_C += $(BOOT)/efi_artifact.c
endif
CORE_C += $(ART_C)
+ifeq ($(strip $(CK_PIPE_TEST)),1)
+CORE_C += $(KDIR)/core/pipe.c $(KDIR)/core/pipe_test.c
+endif
CORE_S := $(BOOT)/efi_entry.S $(KDIR)/arch/vectors.S $(KDIR)/arch/m3.S $(KDIR)/arch/smp_entry.S
HDRS := $(wildcard $(KDIR)/include/*.h $(KDIR)/*/*.h $(BOOT)/*.h)
@@ -1278,6 +1296,15 @@ define rollback_check
fi
endef
+# pipe_check(elf): only a CK_PIPE_TEST image may carry the TEST-only pipe self-test, and it must announce itself.
+define pipe_check
+ @if [ "$(strip $(CK_PIPE_TEST))" = 1 ]; then \
+ grep -aqF "TEST-ONLY pipe self-test" $(1) || { echo "pipe test image lacks its TEST-ONLY announcement"; rm -f $(1); exit 1; }; \
+ else \
+ if grep -aqF "TEST-ONLY pipe self-test" $(1); then echo "default image carries the TEST-ONLY pipe self-test"; rm -f $(1); exit 1; fi; \
+ fi
+endef
+
# smp_check(elf): only a CK_TEST_SMP_SKIP_CPU image may carry the SMP mutation
# announcement, and such an image must carry it.
define smp_check
@@ -1389,6 +1416,7 @@ $(ELF): $(CORE_OBJS) $(BOOT)/image.ld
@if [ -z "$(strip $(CK_TEST_STALE_HANDOFF))" ] && grep -aqF "TEST-ONLY stale handoff" $@; then \
echo "default image carries the TEST-only stale handoff"; rm -f $@; exit 1; fi
$(call rollback_check,$@)
+ $(call pipe_check,$@)
@s=$$($(KNM) $@ | grep -E ' [TtDdBbWwVv] ck_stage_(devices|security|store|quiesce)$$' || true); \
if [ -n "$$s" ]; then echo "core image defines stage symbols: $$s"; rm -f $@; exit 1; fi
$(call fwcfg_check,$@)
@@ -1399,6 +1427,7 @@ $(ELF): $(CORE_OBJS) $(BOOT)/image.ld
$(FULL_ELF): $(CORE_OBJS) $(STAGE_BUILT) $(BOOT)/image.ld
$(call link_image,$@,$(CORE_OBJS) $(STAGE_LINK) $(CK_RUST_LIBS) $(CK_INFER_LIB))
$(call rollback_check,$@)
+ $(call pipe_check,$@)
@for s in $(FULL_STAGE_SYMS); do \
$(KNM) $@ | grep -qE " [TW] $$s$$" || { echo "full image lacks $$s"; rm -f $@; exit 1; }; done
$(call fwcfg_check,$@)
@@ -1425,7 +1454,7 @@ HOST_SRCS := $(KDIR)/core/fmt.c $(KDIR)/core/acpi.c $(KDIR)/core/smmu.c $(KDIR)/
$(KDIR)/core/line_rx.c $(KDIR)/core/klog.c $(KDIR)/core/klog_slot.c $(KDIR)/core/cpufeat.c $(KDIR)/core/unlock_req.c $(KDIR)/core/agent_cmd.c $(KDIR)/core/artifact_card.c
TESTS := test_fmt test_frames test_pt test_acpi test_acpi_dev test_heap test_smmu test_sched test_ipc test_artifact test_osc_unit test_osc_launch test_osc_admit test_osc_receipt test_entropy test_handoff test_fbcon test_osh_op \
test_continuity_codec test_continuity_resolve test_continuity_commit test_continuity_recovery test_continuity_geometry \
- test_continuity_subject test_continuity_subject_provision test_lifecycle test_console_rx test_klog test_klog_slot test_pi5 test_pi5_marker test_pi5_rng test_cpufeat test_dma_window test_pi5_pcie test_pi5_net test_pi5_gem test_unlock_req test_context test_agent_cmd test_artifact_card \
+ test_continuity_subject test_continuity_subject_provision test_lifecycle test_console_rx test_klog test_klog_slot test_pi5 test_pi5_marker test_pi5_rng test_cpufeat test_dma_window test_pi5_pcie test_pi5_net test_pi5_gem test_unlock_req test_context test_agent_cmd test_artifact_card test_pipe \
test_netboot_text test_gb10_gsp_boot
TESTS += test_gpu_sim test_gsp_mmio
HCFLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -I$(KDIR)/core -I$(KDIR)/mm -I$(KDIR)/tests -I$(BOOT)
@@ -1460,6 +1489,42 @@ osh-op-mutant: $(OUT)/host/test_osh_op_mutant
@if $< > $<.log 2>&1; then cat $<.log; echo "test_osh_op mutant (permission check always OK): PASSED, test does not catch it"; exit 1; \
else grep -F "test_osh_op: FAIL" $<.log && echo "test_osh_op mutant (permission check always OK): FAILS as required"; fi
+# Native pipe primitive (core/pipe.c, aienos-mv#428): pure logic over ipc.c capability tables, driven through sched.c by
+# core/pipe_drive.h. Own rule: the test reads the fixture corpus in tests/fixtures/pipe/.
+PIPE_SRCS := $(KDIR)/core/pipe.c $(KDIR)/core/ipc.c $(KDIR)/core/sched.c
+PIPE_DEPS := $(KDIR)/tests/test_pipe.c $(PIPE_SRCS) $(KDIR)/tests/ck_test.h $(HDRS) $(wildcard $(KDIR)/tests/fixtures/pipe/*)
+PIPE_DEF := -DPIPE_FIXTURE_DIR='"$(abspath $(KDIR)/tests/fixtures/pipe)"'
+# core/ is not a -I ahead of the system headers: <sched.h> must stay POSIX for the
+# pthread host test. Quoted includes still find core/ headers (the sources live there,
+# and -idirafter covers the test file).
+PIPE_HCFLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -I$(KDIR)/mm -I$(KDIR)/tests -I$(BOOT) -idirafter $(KDIR)/core -pthread
+$(OUT)/host/test_pipe: $(PIPE_DEPS)
+ @mkdir -p $(dir $@)
+ $(HOSTCC) $(PIPE_HCFLAGS) $(PIPE_DEF) -o $@ $< $(PIPE_SRCS)
+
+$(OUT)/host-san/test_pipe: $(PIPE_DEPS)
+ @mkdir -p $(dir $@)
+ $(HOSTCC) $(PIPE_HCFLAGS) $(SANFLAGS) $(PIPE_DEF) -o $@ $< $(PIPE_SRCS)
+
+# TEST-ONLY mutant of core/pipe.c: a write does not check the WRITE right or the end. test_pipe must FAIL against it
+# (red before green); "make test" fails if the test stops catching it. Host only.
+$(OUT)/host/test_pipe_mutant: $(PIPE_DEPS)
+ @mkdir -p $(dir $@)
+ $(HOSTCC) $(PIPE_HCFLAGS) $(PIPE_DEF) -DCK_PIPE_MUTANT_SKIP_RIGHTS -o $@ $< $(PIPE_SRCS)
+
+pipe-mutant: $(OUT)/host/test_pipe_mutant
+ @if $< > $<.log 2>&1; then cat $<.log; echo "test_pipe mutant (write right not checked): PASSED, test does not catch it"; exit 1; \
+ else grep -F "test_pipe: FAIL" $<.log && echo "test_pipe mutant (write right not checked): FAILS as required"; fi
+
+# TEST-ONLY mutant: ck_pipe_dispatch does not reject a slice outside [user_lo, user_hi). test_pipe must FAIL.
+$(OUT)/host/test_pipe_slice_mutant: $(PIPE_DEPS)
+ @mkdir -p $(dir $@)
+ $(HOSTCC) $(PIPE_HCFLAGS) $(PIPE_DEF) -DCK_PIPE_MUTANT_SKIP_SLICE -o $@ $< $(PIPE_SRCS)
+
+pipe-slice-mutant: $(OUT)/host/test_pipe_slice_mutant
+ @if $< > $<.log 2>&1; then cat $<.log; echo "test_pipe mutant (user slice not checked): PASSED, test does not catch it"; exit 1; \
+ else grep -F "test_pipe: FAIL" $<.log && echo "test_pipe mutant (user slice not checked): FAILS as required"; fi
+
# N3 context assembly + approval binding (core/context.c, core/context_proposal.c, aienos#329): pure logic over
# the argus SHA-256. Own rule (needs sha256.c). The mutant skips the foreign-binding check: test_context must
# FAIL against it (red before green); "make test" fails if the test stops catching it. Host only (context.c
@@ -1580,8 +1645,8 @@ smmu-l2-mutants: $(OUT)/host/test_smmu
else echo "mutant flag refused under CK_HARDWARE_STAGING"; fi; \
if [ $$fail = 0 ]; then echo "CK_SMMU_L2_MUTANTS: PASS"; else echo "CK_SMMU_L2_MUTANTS: FAIL"; exit 1; fi
-test: $(addprefix $(OUT)/host/,$(TESTS)) osc-receipt-mutants osc-receipt-release osc-code-flip-guard handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test gb10-gsp-free gb10-gsp-nvhdr-check gb10-gsp-mutants slot-test slot-free package-test slot-loader-check
- @fail=0; for t in $(filter-out osc-receipt-mutants osc-receipt-release osc-code-flip-guard handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test gb10-gsp-free gb10-gsp-nvhdr-check gb10-gsp-mutants slot-test slot-free package-test slot-loader-check,$^); do $$t || fail=1; done; \
+test: $(addprefix $(OUT)/host/,$(TESTS)) osc-receipt-mutants osc-receipt-release osc-code-flip-guard handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant pipe-mutant pipe-slice-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test gb10-gsp-free gb10-gsp-nvhdr-check gb10-gsp-mutants slot-test slot-free package-test slot-loader-check
+ @fail=0; for t in $(filter-out osc-receipt-mutants osc-receipt-release osc-code-flip-guard handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant pipe-mutant pipe-slice-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test gb10-gsp-free gb10-gsp-nvhdr-check gb10-gsp-mutants slot-test slot-free package-test slot-loader-check,$^); do $$t || fail=1; done; \
if [ $$fail = 0 ]; then echo "CK_CORE_HOST: PASS"; else echo "CK_CORE_HOST: FAIL"; exit 1; fi
sanitize: $(addprefix $(OUT)/host-san/,$(TESTS))
diff --git a/native/kernel/README.md b/native/kernel/README.md
index ce1c04eb ..352295e4 100644
--- a/native/kernel/README.md
+++ b/native/kernel/README.md
@@ -633,6 +633,36 @@ low-water free bytes.
lists (whole pages). Tables, stack, heap and pool come from it and are never
handed out again.
+## Native pipes (AIENOS-NATIVE-PIPE-1, aienos-mv#428)
+
+`core/pipe.c` / `core/pipe.h` make a pipe a kernel primitive: two independently scheduled operations exchange ordered
+bytes through a bounded buffer, with no intermediate file. It is a byte stream, separate from the 56-byte typed
+message ring of `core/ipc.h`; it reuses only the ipc.h capability tables.
+
+- **Contract.** OSH_PLATFORM_ABI (aien-protocols-mv `specs/osh-platform/`, read at `fb5fca98e667 `, v1 DRAFT, unfrozen):
+ PIPE_CREATE, STREAM_READ / WRITE / CLOSE / DUP (section 8.1), at least 64 KiB per pipe (8.5), the error codes of 8.6
+ (one shared copy in `core/osh_err.h`, also used by `core/osh_op.h`), epoch staleness (4.4) and authority at the
+ moment of the effect (9.2). Choices the draft does not pin are marked UNVERIFIED in `pipe.h`.
+- **Ends are capabilities.** The read end holds `CK_R_READ`, the write end `CK_R_WRITE`, never both; optional
+ `CK_R_DERIVE` (dup in the same table), `CK_R_GRANT` (dup into another principal's table) and `CK_R_REVOKE`. Every
+ operation calls `ck_cap_lookup` when it acts, so a handle that was closed, reused or revoked is refused even if it
+ was valid a moment earlier (STALE, DENIED, REVOKED).
+- **Bounded.** A static pool of `CK_PIPE_POOL_PIPES` (4) pipes of `CK_PIPE_CAPACITY` (65536) bytes; nothing is allocated.
+ A write past the free space is partial, a write on a full pipe returns WOULD_BLOCK (or parks with `CK_PIPE_F_BLOCK`
+ through the pool's wait / wake hook, which the kernel points at the scheduler). Last writer closed: reads return 0
+ bytes once drained (EOF). No reader: BROKEN_PIPE. Revoke scrubs the buffer and no byte is delivered after it; cancel
+ makes the next or the blocked call on that end return INTERRUPTED with no byte moved. Counters (bytes, max resident,
+ WOULD_BLOCK, waits, wakeups, cancellations, revocations, refusals) are in `struct ck_pipe_stats`.
+- **Versioned op table.** `ck_pipe_dispatch` takes a platform call frame (magic `OSHF`, `CK_PIPE_ABI_VERSION` 1, op id,
+ reserved, arguments) and refuses malformed frames and unknown ops or versions (INVALID_ARG, NOT_SUPPORTED) before any
+ effect.
+- **Tests.** `make test` runs `test_pipe` (the 20-case corpus in `tests/fixtures/pipe/`, format in its README, plus
+ producer / consumer transfers through `core/sched.c`) and `pipe-mutant` (the write-right check removed: the test must
+ fail); `make sanitize` runs it under ASan+UBSan. `scripts/qemu_ck_pipe_test.sh` builds the TEST-ONLY `CK_PIPE_TEST=1`
+ image and checks the in-kernel run (GATES.md, PIPE). Host and QEMU evidence qualify nothing physical.
+- **Not yet.** Task execution and shell dispatch over pipes are separate issues; the kernel's blocking hook yields
+ cooperatively inside one kernel thread, it does not switch M3 threads.
+
## Notes for stage code
- `ck_puts` prints the string as given; it does not add a newline.
diff --git a/native/kernel/core/.crumb b/native/kernel/core/.crumb
index cbe66c3e ..974f039d 100644
--- a/native/kernel/core/.crumb
+++ b/native/kernel/core/.crumb
@@ -7,14 +7,14 @@
"generated": {
"children": [],
"children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "compiled_at": "2026-10-30T12:19:24Z",
+ "compiled_at": "2026-10-30T22:19:45Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:d4196275e1dc11d6b92d0fe9b90bbd9b7bbef17cd4ec63bc2fb09acfa7bd7b90 ",
+ "digest": "sha256:3448d48e8498c2a3409e69923020b57bf1146bd1d5913e70f7559cefd9d005bd ",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "files": 69,
- "generated_at_commit": "84ee2a02f78229167998d21a8ff03fe65bedb821 ",
- "source_tree": "sha256:bbed7cef6c96eb3a715ddd76d2f893cdf2a86fea642a5d360f6f474aeb5ff49f "
+ "files": 74,
+ "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e ",
+ "source_tree": "sha256:970cbbf3037456d4d1dfe0a1694124c8889b8c19a83c4bd75286ccd98e3f559f "
},
"owner_lane": "",
"provenance": {
diff --git a/native/kernel/core/kmain.c b/native/kernel/core/kmain.c
index 8b9b01eb ..16a39236 100644
--- a/native/kernel/core/kmain.c
+++ b/native/kernel/core/kmain.c
@@ -138,6 +138,10 @@ static __attribute__((noreturn)) void rollback_test_end(void)
}
#endif
+#ifdef CK_PIPE_TEST
+void ck_pipe_selftest(void);
+#endif
+
static __attribute__((noreturn)) void ck_el1_main(void *arg)
{
struct ck_handoff *h = arg;
@@ -228,6 +232,10 @@ static __attribute__((noreturn)) void ck_el1_main(void *arg)
#if defined(CK_TEST_ROLLBACK_CPU_FAULT) || defined(CK_TEST_ROLLBACK_HANG)
rollback_test_end();
#endif
+#ifdef CK_PIPE_TEST
+ /* TEST-ONLY pipe self-test (core/pipe_test.c, scripts/qemu_ck_pipe_test.sh); never in a production image. */
+ ck_pipe_selftest();
+#endif
{
struct ck_cpu_features cf;
diff --git a/native/kernel/core/osh_err.h b/native/kernel/core/osh_err.h
new file mode 100644
index 00000000 ..b4754102
--- /dev/null
+++ b/native/kernel/core/osh_err.h
@@ -0,0 +1,25 @@
+/* osh_err.h -- OSH platform error codes (OSH_PLATFORM_ABI.md section 8.6, v1 DRAFT, unfrozen; read at aien-protocols-mv
+ * fb5fca98e667 ). One copy of the numbering, shared by the test-only shell adapter (osh_op.h) and the kernel pipe primitive
+ * (pipe.h), so the two can never disagree. Pure definitions, no test-only guard: the pipe primitive is not test-only. */
+#ifndef AIENOS_CK_OSH_ERR_H
+#define AIENOS_CK_OSH_ERR_H
+
+enum osh_err {
+ OSH_E_OK = 0, OSH_E_DENIED = 1, OSH_E_REVOKED = 2, OSH_E_STALE = 3, OSH_E_NOT_FOUND = 4, OSH_E_UNAVAILABLE = 5,
+ OSH_E_INVALID_ARG = 6, OSH_E_LIMIT = 7, OSH_E_INTERRUPTED = 8, OSH_E_BROKEN_PIPE = 9, OSH_E_IO = 10,
+ OSH_E_OUTCOME_UNKNOWN = 11, OSH_E_CAP_DOMAIN_MISMATCH = 12, OSH_E_CAP_GEN_NARROW = 13, OSH_E_NOT_SUPPORTED = 14,
+ OSH_E_WOULD_BLOCK = 15, OSH_E_PARTIAL_LAUNCH = 16
+};
+#define OSH_E_COUNT 17u
+
+/* Name of a code; section 8.6: an unknown code is IO, never OK. */
+static inline const char *osh_err_label(unsigned e)
+{
+ static const char *const n[OSH_E_COUNT] = { "OK", "DENIED", "REVOKED", "STALE", "NOT_FOUND", "UNAVAILABLE",
+ "INVALID_ARG", "LIMIT", "INTERRUPTED", "BROKEN_PIPE", "IO",
+ "OUTCOME_UNKNOWN", "CAP_DOMAIN_MISMATCH", "CAP_GEN_NARROW",
+ "NOT_SUPPORTED", "WOULD_BLOCK", "PARTIAL_LAUNCH" };
+ return e < OSH_E_COUNT ? n[e] : "IO";
+}
+
+#endif
diff --git a/native/kernel/core/osh_op.c b/native/kernel/core/osh_op.c
index f178d805 ..7c33f682 100644
--- a/native/kernel/core/osh_op.c
+++ b/native/kernel/core/osh_op.c
@@ -54,10 +54,7 @@ __attribute__((unused)) static int same(const void *a, const void *b, size_t n)
const char *osh_err_name(unsigned e)
{
- static const char *const n[] = { "OK", "DENIED", "REVOKED", "STALE", "NOT_FOUND", "UNAVAILABLE", "INVALID_ARG", "LIMIT",
- "INTERRUPTED", "BROKEN_PIPE", "IO", "OUTCOME_UNKNOWN", "CAP_DOMAIN_MISMATCH",
- "CAP_GEN_NARROW", "NOT_SUPPORTED", "WOULD_BLOCK", "PARTIAL_LAUNCH" };
- return e < sizeof n / sizeof n[0] ? n[e] : "IO"; /* section 8.6: an unknown code is IO, never OK */
+ return osh_err_label(e); /* osh_err.h; section 8.6: an unknown code is IO, never OK */
}
const char *osh_outcome_name(unsigned o)
diff --git a/native/kernel/core/osh_op.h b/native/kernel/core/osh_op.h
index 3065fc83 ..230615d2 100644
--- a/native/kernel/core/osh_op.h
+++ b/native/kernel/core/osh_op.h
@@ -41,13 +41,8 @@
#error "CK_OSH_OP_TEST cannot be combined with CK_HARDWARE_STAGING"
#endif
-/* section 8.6 platform error codes (numbers as in the draft) */
-enum osh_err {
- OSH_E_OK = 0, OSH_E_DENIED = 1, OSH_E_REVOKED = 2, OSH_E_STALE = 3, OSH_E_NOT_FOUND = 4, OSH_E_UNAVAILABLE = 5,
- OSH_E_INVALID_ARG = 6, OSH_E_LIMIT = 7, OSH_E_INTERRUPTED = 8, OSH_E_BROKEN_PIPE = 9, OSH_E_IO = 10,
- OSH_E_OUTCOME_UNKNOWN = 11, OSH_E_CAP_DOMAIN_MISMATCH = 12, OSH_E_CAP_GEN_NARROW = 13, OSH_E_NOT_SUPPORTED = 14,
- OSH_E_WOULD_BLOCK = 15, OSH_E_PARTIAL_LAUNCH = 16
-};
+/* section 8.6 platform error codes: one shared numbering (osh_err.h), also used by the kernel pipe primitive (pipe.h) */
+#include "osh_err.h"
/* section 10 outcomes */
enum osh_outcome { OSH_O_NOT_STARTED = 0, OSH_O_COMPLETED, OSH_O_FAILED_NO_EFFECT, OSH_O_CANCELLED, OSH_O_OUTCOME_UNKNOWN };
diff --git a/native/kernel/core/pipe.c b/native/kernel/core/pipe.c
new file mode 100644
index 00000000 ..c8919d9d
--- /dev/null
+++ b/native/kernel/core/pipe.c
@@ -0,0 +1,642 @@
+/* pipe.c -- see pipe.h. Bounded byte pipes over ipc.h capability tables; no allocation, no libc.
+ *
+ * The pool lock is a ticket lock on lock_ticket / lock_serving. core/smp.c publishes cross-core state with
+ * __atomic_*; this file uses the same builtins (there is no spinlock type in the kernel). Every pipe field,
+ * refcount, stat and the live count is touched only while the lock is held. wait and wake run after it is
+ * dropped, so a hook can re-enter. Pipe ops are not called from interrupt handlers; the lock does not mask IRQs.
+ */
+#include "pipe.h"
+
+static void bytes_zero(uint8_t *d, size_t n)
+{
+ for (size_t i = 0; i < n; i++)
+ d[i] = 0;
+}
+
+/* The snapshot sits on the stack and is dead after the call. A plain store can be deleted; a volatile store cannot. */
+static void snap_zero(uint8_t *d, size_t n)
+{
+ volatile uint8_t *p = d;
+ for (size_t i = 0; i < n; i++)
+ p[i] = 0;
+}
+
+static void stats_zero(struct ck_pipe_stats *s)
+{
+ *s = (struct ck_pipe_stats){ 0 };
+}
+
+static void cpu_relax(void)
+{
+#if defined(__aarch64__)
+ __asm__ volatile("yield" ::: "memory");
+#elif defined(__x86_64__) || defined(__i386__)
+ __asm__ volatile("pause" ::: "memory");
+#else
+ __asm__ volatile("" ::: "memory");
+#endif
+}
+
+static void pool_lock(struct ck_pipe_pool *p)
+{
+ uint32_t me = __atomic_fetch_add(&p->lock_ticket, 1u, __ATOMIC_RELAXED);
+ while (__atomic_load_n(&p->lock_serving, __ATOMIC_ACQUIRE) != me)
+ cpu_relax();
+}
+
+static void pool_unlock(struct ck_pipe_pool *p)
+{
+ uint32_t next = __atomic_load_n(&p->lock_serving, __ATOMIC_RELAXED) + 1u;
+ __atomic_store_n(&p->lock_serving, next, __ATOMIC_RELEASE);
+}
+
+void ck_pipe_pool_init(struct ck_pipe_pool *p, const struct ck_pipe_hooks *hooks)
+{
+ for (unsigned i = 0; i < CK_PIPE_POOL_PIPES; i++) {
+ struct ck_pipe *q = &p->pipes[i];
+ bytes_zero(q->buf, CK_PIPE_CAPACITY);
+ q->head = q->len = q->epoch = 0;
+ q->reader_refs = q->writer_refs = 0;
+ q->flags = 0;
+ q->waiting[0] = q->waiting[1] = 0;
+ stats_zero(&q->stats);
+ }
+ p->hooks = hooks;
+ stats_zero(&p->total);
+ p->live = 0;
+ /* Unlocked (ticket == serving). Init is single-threaded, before the pool is shared. */
+ __atomic_store_n(&p->lock_ticket, 0u, __ATOMIC_RELAXED);
+ __atomic_store_n(&p->lock_serving, 0u, __ATOMIC_RELAXED);
+}
+
+int ck_pipe_pool_empty(struct ck_pipe_pool *p)
+{
+ pool_lock(p);
+ int empty = p->live == 0;
+ for (unsigned i = 0; i < CK_PIPE_POOL_PIPES; i++)
+ if (p->pipes[i].flags & CK_PIPE_LIVE)
+ empty = 0;
+ pool_unlock(p);
+ return empty;
+}
+
+/* Every counter is kept twice: this incarnation and the pool total. */
+#define BUMP(p, q, field, by) \
+ do { \
+ (q)->stats.field += (by); \
+ (p)->total.field += (by); \
+ } while (0)
+
+/* Wakes recorded under the lock and fired after it is dropped. One close wakes one end; a table has CK_CAP_SLOTS. */
+#define CK_PIPE_WAKE_NOTE CK_CAP_SLOTS
+struct ck_wake_note {
+ unsigned n;
+ unsigned idx[CK_PIPE_WAKE_NOTE];
+ unsigned end[CK_PIPE_WAKE_NOTE];
+};
+
+static void note_wake(struct ck_wake_note *note, struct ck_pipe_pool *p, unsigned idx, unsigned end)
+{
+ struct ck_pipe *q = &p->pipes[idx];
+ if (!q->waiting[end] || !p->hooks || !p->hooks->wake)
+ return;
+ BUMP(p, q, wakeups, 1);
+ if (note->n < CK_PIPE_WAKE_NOTE) {
+ note->idx[note->n] = idx;
+ note->end[note->n] = end;
+ note->n++;
+ }
+}
+
+static void fire_wakes(struct ck_pipe_pool *p, const struct ck_wake_note *note)
+{
+ if (!note->n || !p->hooks || !p->hooks->wake)
+ return;
+ for (unsigned i = 0; i < note->n; i++)
+ p->hooks->wake(p->hooks->ctx, note->idx[i], note->end[i]);
+}
+
+static unsigned data_right(unsigned end)
+{
+ return end == CK_PIPE_END_READ ? CK_R_READ : CK_R_WRITE;
+}
+
+/* The effect-boundary check, run inside every operation at the moment of its effect. Lock is held.
+ * need: rights the capability must hold. want_end: the end the operation needs, or -1 for either.
+ * OK with *idx and *end set; otherwise the refusal. A REVOKED pipe is reported only when live_ok is 0. */
+static unsigned resolve(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h, unsigned need,
+ int want_end, int live_ok, unsigned *idx, unsigned *end)
+{
+ if (!t || h.generation == 0 || h.index >= t->n)
+ return OSH_E_INVALID_ARG;
+ uint32_t res = 0;
+ int r = ck_cap_lookup(t, h, need, &res);
+ if (r == CK_CAP_INVALID)
+ return OSH_E_STALE; /* slot closed, or reused under a newer generation */
+ if (r != CK_CAP_OK)
+ return OSH_E_DENIED; /* the capability lacks a right this effect needs */
+ if ((res >> 24) != CK_PIPE_RES_TAG)
+ return OSH_E_DENIED; /* not a stream capability */
+ unsigned i = (res >> 20) & 7u, e = (res >> 23) & 1u;
+ uint32_t epoch = res & CK_PIPE_EPOCH_MAX;
+ if (i >= CK_PIPE_POOL_PIPES)
+ return OSH_E_DENIED;
+ if (want_end >= 0 && e != (unsigned)want_end)
+ return OSH_E_DENIED; /* a read end cannot write, a write end cannot read */
+ const struct ck_pipe *q = &p->pipes[i];
+ if (!(q->flags & CK_PIPE_LIVE) || q->epoch != epoch)
+ return OSH_E_STALE; /* section 4.4: an id from an earlier incarnation */
+ if (!live_ok && (q->flags & CK_PIPE_REVOKED))
+ return OSH_E_REVOKED;
+ *idx = i;
+ *end = e;
+ return OSH_E_OK;
+}
+
+static unsigned refuse(struct ck_pipe_pool *p, unsigned e)
+{
+ if (e == OSH_E_DENIED || e == OSH_E_STALE || e == OSH_E_REVOKED)
+ p->total.refused++;
+ return e;
+}
+
+unsigned ck_pipe_create(struct ck_pipe_pool *p, struct ck_cap_table *t, struct ck_handle *rd, struct ck_handle *wr)
+{
+ if (!t || !rd || !wr)
+ return OSH_E_INVALID_ARG;
+ pool_lock(p);
+ unsigned idx = CK_PIPE_POOL_PIPES;
+ for (unsigned i = 0; i < CK_PIPE_POOL_PIPES; i++)
+ if (!(p->pipes[i].flags & CK_PIPE_LIVE) && p->pipes[i].epoch < CK_PIPE_EPOCH_MAX) {
+ idx = i;
+ break;
+ }
+ if (idx == CK_PIPE_POOL_PIPES) {
+ pool_unlock(p);
+ return OSH_E_LIMIT;
+ }
+ struct ck_pipe *q = &p->pipes[idx];
+ uint32_t epoch = q->epoch + 1;
+ struct ck_handle r, w;
+ if (ck_cap_insert(t, ck_pipe_resource(idx, CK_PIPE_END_READ, epoch), CK_R_READ | CK_PIPE_CTL_RIGHTS, &r) !=
+ CK_CAP_OK) {
+ pool_unlock(p);
+ return OSH_E_LIMIT;
+ }
+ if (ck_cap_insert(t, ck_pipe_resource(idx, CK_PIPE_END_WRITE, epoch), CK_R_WRITE | CK_PIPE_CTL_RIGHTS, &w) !=
+ CK_CAP_OK) {
+ ck_cap_remove(t, r); /* nothing stays allocated on failure */
+ pool_unlock(p);
+ return OSH_E_LIMIT;
+ }
+ q->epoch = epoch;
+ q->head = q->len = 0;
+ q->reader_refs = q->writer_refs = 1;
+ q->flags = CK_PIPE_LIVE;
+ q->waiting[0] = q->waiting[1] = 0;
+ stats_zero(&q->stats);
+ p->live++;
+ *rd = r;
+ *wr = w;
+ pool_unlock(p);
+ return OSH_E_OK;
+}
+
+static unsigned read_once(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h, uint8_t *buf,
+ size_t max, size_t *n, unsigned *idx_out, struct ck_wake_note *note)
+{
+ unsigned idx, end;
+ unsigned e = resolve(p, t, h, CK_R_READ, CK_PIPE_END_READ, 0, &idx, &end);
+ if (e != OSH_E_OK)
+ return refuse(p, e);
+ struct ck_pipe *q = &p->pipes[idx];
+ *idx_out = idx;
+ if (q->flags & CK_PIPE_CANCEL_READ) {
+ q->flags &= ~CK_PIPE_CANCEL_READ;
+ BUMP(p, q, cancellations, 1);
+ return OSH_E_INTERRUPTED;
+ }
+ if (max == 0)
+ return OSH_E_OK;
+ if (q->len == 0) {
+ if (q->writer_refs == 0) {
+ BUMP(p, q, eof, 1);
+ return OSH_E_OK; /* every writer closed and the buffer is drained: EOF */
+ }
+ BUMP(p, q, would_block, 1);
+ return OSH_E_WOULD_BLOCK;
+ }
+ size_t take = max < q->len ? max : q->len;
+ for (size_t i = 0; i < take; i++) {
+ buf[i] = q->buf[q->head];
+ q->buf[q->head] = 0; /* consumed bytes do not stay resident */
+ q->head = (q->head + 1) % CK_PIPE_CAPACITY;
+ }
+ q->len -= (uint32_t)take;
+ if (q->len == 0)
+ q->head = 0;
+ *n = take;
+ BUMP(p, q, bytes_read, take);
+ BUMP(p, q, reads, 1);
+ note_wake(note, p, idx, CK_PIPE_END_WRITE);
+ return OSH_E_OK;
+}
+
+static unsigned write_once(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h,
+ const uint8_t *buf, size_t len, size_t *n, unsigned *idx_out, struct ck_wake_note *note)
+{
+ unsigned idx, end;
+#ifdef CK_PIPE_MUTANT_SKIP_RIGHTS
+ /* TEST-ONLY mutant (make pipe-mutant): the write right and the end are not checked. test_pipe must fail. */
+ unsigned e = resolve(p, t, h, 0, -1, 0, &idx, &end);
+#else
+ unsigned e = resolve(p, t, h, CK_R_WRITE, CK_PIPE_END_WRITE, 0, &idx, &end);
+#endif
+ if (e != OSH_E_OK)
+ return refuse(p, e);
+ struct ck_pipe *q = &p->pipes[idx];
+ *idx_out = idx;
+ if (q->flags & CK_PIPE_CANCEL_WRITE) {
+ q->flags &= ~CK_PIPE_CANCEL_WRITE;
+ BUMP(p, q, cancellations, 1);
+ return OSH_E_INTERRUPTED;
+ }
+ if (q->reader_refs == 0) {
+ BUMP(p, q, broken_pipe, 1);
+ return OSH_E_BROKEN_PIPE;
+ }
+ if (len == 0)
+ return OSH_E_OK;
+ size_t room = CK_PIPE_CAPACITY - q->len;
+ if (room == 0) {
+ BUMP(p, q, would_block, 1);
+ return OSH_E_WOULD_BLOCK;
+ }
+ size_t put = len < room ? len : room;
+ uint32_t at = (q->head + q->len) % CK_PIPE_CAPACITY;
+ for (size_t i = 0; i < put; i++) {
+ q->buf[at] = buf[i];
+ at = (at + 1) % CK_PIPE_CAPACITY;
+ }
+ q->len += (uint32_t)put;
+ *n = put;
+ BUMP(p, q, bytes_written, put);
+ BUMP(p, q, writes, 1);
+ if (q->len > q->stats.max_resident)
+ q->stats.max_resident = q->len;
+ if (q->len > p->total.max_resident)
+ p->total.max_resident = q->len;
+ note_wake(note, p, idx, CK_PIPE_END_READ);
+ return OSH_E_OK;
+}
+
+/* Park on (idx, end). Lock is held on entry and on return. The hook runs without the lock. */
+static unsigned park(struct ck_pipe_pool *p, unsigned idx, unsigned end)
+{
+ if (!p->hooks || !p->hooks->wait)
+ return OSH_E_WOULD_BLOCK;
+ struct ck_pipe *q = &p->pipes[idx];
+ uint32_t epoch = q->epoch;
+ q->waiting[end]++;
+ BUMP(p, q, waits, 1);
+ pool_unlock(p);
+ if (p->hooks->before_wait)
+ p->hooks->before_wait(p->hooks->ctx);
+ unsigned w = p->hooks->wait(p->hooks->ctx, idx, end);
+ pool_lock(p);
+ q = &p->pipes[idx];
+ /* Freed and recreated while we were out: that incarnation's waiting[] is not ours to decrement. */
+ if (q->epoch == epoch && q->waiting[end])
+ q->waiting[end]--;
+ if (w != OSH_E_OK) {
+ if (w == OSH_E_INTERRUPTED && q->epoch == epoch)
+ BUMP(p, q, cancellations, 1);
+ return w >= OSH_E_COUNT ? OSH_E_IO : w; /* section 8.6: an unknown code is IO, never OK */
+ }
+ return OSH_E_OK;
+}
+
+unsigned ck_stream_read(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h, uint8_t *buf,
+ size_t max, unsigned flags, size_t *n)
+{
+ if (!n || (max && !buf) || (flags & ~CK_PIPE_F_BLOCK))
+ return OSH_E_INVALID_ARG;
+ pool_lock(p);
+ for (;;) {
+ struct ck_wake_note note = { 0 };
+ unsigned idx = 0;
+ *n = 0;
+ unsigned e = read_once(p, t, h, buf, max, n, &idx, ¬e);
+ if (e != OSH_E_WOULD_BLOCK || !(flags & CK_PIPE_F_BLOCK)) {
+ pool_unlock(p);
+ fire_wakes(p, ¬e);
+ return e;
+ }
+ e = park(p, idx, CK_PIPE_END_READ);
+ if (e != OSH_E_OK) {
+ pool_unlock(p);
+ return e;
+ }
+ }
+}
+
+unsigned ck_stream_write(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h, const uint8_t *buf,
+ size_t len, unsigned flags, size_t *n)
+{
+ if (!n || (len && !buf) || (flags & ~CK_PIPE_F_BLOCK))
+ return OSH_E_INVALID_ARG;
+ /* Snapshot only on the path that parks. The copy happens before park, while the lock is still held,
+ * so the retry cannot observe a caller buffer that changed during the wait. */
+ uint8_t snap[CK_PIPE_WRITE_SNAP];
+ const uint8_t *src = buf;
+ size_t src_len = len;
+ int snapped = 0;
+ pool_lock(p);
+ for (;;) {
+ struct ck_wake_note note = { 0 };
+ unsigned idx = 0;
+ *n = 0;
+ unsigned e = write_once(p, t, h, src, src_len, n, &idx, ¬e);
+ if (e != OSH_E_WOULD_BLOCK || !(flags & CK_PIPE_F_BLOCK)) {
+ pool_unlock(p);
+ fire_wakes(p, ¬e);
+ if (snapped)
+ snap_zero(snap, CK_PIPE_WRITE_SNAP);
+ return e;
+ }
+ if (!snapped && len > 0) {
+ size_t take = len < CK_PIPE_WRITE_SNAP ? len : CK_PIPE_WRITE_SNAP;
+ for (size_t i = 0; i < take; i++)
+ snap[i] = buf[i];
+ src = snap;
+ src_len = take;
+ snapped = 1;
+ }
+ e = park(p, idx, CK_PIPE_END_WRITE);
+ if (e != OSH_E_OK) {
+ pool_unlock(p);
+ if (snapped)
+ snap_zero(snap, CK_PIPE_WRITE_SNAP);
+ return e;
+ }
+ }
+}
+
+static void pipe_free(struct ck_pipe_pool *p, struct ck_pipe *q)
+{
+ bytes_zero(q->buf, CK_PIPE_CAPACITY);
+ q->head = q->len = 0;
+ q->flags = 0;
+ q->waiting[0] = q->waiting[1] = 0;
+ p->live--;
+}
+
+static unsigned close_locked(struct ck_pipe_pool *p, struct ck_cap_table *t, struct ck_handle h,
+ struct ck_wake_note *note)
+{
+ if (!t || h.generation == 0 || h.index >= t->n)
+ return OSH_E_INVALID_ARG;
+ uint32_t res = 0;
+ if (ck_cap_lookup(t, h, 0, &res) != CK_CAP_OK)
+ return refuse(p, OSH_E_STALE); /* already closed, or the slot belongs to someone newer */
+ if ((res >> 24) != CK_PIPE_RES_TAG || ((res >> 20) & 7u) >= CK_PIPE_POOL_PIPES)
+ return refuse(p, OSH_E_DENIED); /* not ours to close here */
+ unsigned idx, end;
+ unsigned e = resolve(p, t, h, 0, -1, 1, &idx, &end);
+ ck_cap_remove(t, h); /* the handle is released whatever the pipe's state */
+ if (e != OSH_E_OK)
+ return refuse(p, e);
+ struct ck_pipe *q = &p->pipes[idx];
+ if (end == CK_PIPE_END_READ) {
+ if (q->reader_refs)
+ q->reader_refs--;
+ if (q->reader_refs == 0)
+ note_wake(note, p, idx, CK_PIPE_END_WRITE); /* a blocked writer now sees BROKEN_PIPE */
+ } else {
+ if (q->writer_refs)
+ q->writer_refs--;
+ if (q->writer_refs == 0)
+ note_wake(note, p, idx, CK_PIPE_END_READ); /* a blocked reader now sees EOF once drained */
+ }
+ if (q->reader_refs == 0 && q->writer_refs == 0)
+ pipe_free(p, q);
+ return OSH_E_OK;
+}
+
+unsigned ck_stream_close(struct ck_pipe_pool *p, struct ck_cap_table *t, struct ck_handle h)
+{
+ if (!t || h.generation == 0 || h.index >= t->n)
+ return OSH_E_INVALID_ARG;
+ struct ck_wake_note note = { 0 };
+ pool_lock(p);
+ unsigned e = close_locked(p, t, h, ¬e);
+ pool_unlock(p);
+ fire_wakes(p, ¬e);
+ return e;
+}
+
+unsigned ck_stream_dup(struct ck_pipe_pool *p, struct ck_cap_table *from, struct ck_handle h, struct ck_cap_table *to,
+ unsigned rights, struct ck_handle *out)
+{
+ if (!to || !out)
+ return OSH_E_INVALID_ARG;
+ pool_lock(p);
+ unsigned need = to == from ? CK_R_DERIVE : CK_R_GRANT;
+ unsigned idx, end;
+ unsigned e = resolve(p, from, h, need, -1, 0, &idx, &end);
+ if (e != OSH_E_OK) {
+ e = refuse(p, e);
+ pool_unlock(p);
+ return e;
+ }
+ unsigned have = 0;
+ ck_cap_rights(from, h, &have);
+ unsigned dr = data_right(end);
+ if (!(rights & dr) || (rights & ~(dr | CK_PIPE_CTL_RIGHTS))) {
+ pool_unlock(p);
+ return OSH_E_INVALID_ARG; /* a dup carries its end's data right and nothing of the other end */
+ }
+ if (rights & ~have) {
+ e = refuse(p, OSH_E_DENIED); /* attenuation only: never more than the source holds */
+ pool_unlock(p);
+ return e;
+ }
+ struct ck_pipe *q = &p->pipes[idx];
+ struct ck_handle c;
+ if (ck_cap_insert(to, ck_pipe_resource(idx, end, q->epoch), rights, &c) != CK_CAP_OK) {
+ pool_unlock(p);
+ return OSH_E_LIMIT;
+ }
+ if (end == CK_PIPE_END_READ)
+ q->reader_refs++;
+ else
+ q->writer_refs++;
+ *out = c;
+ pool_unlock(p);
+ return OSH_E_OK;
+}
+
+unsigned ck_pipe_revoke(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h)
+{
+ struct ck_wake_note note = { 0 };
+ pool_lock(p);
+ unsigned idx, end;
+ unsigned e = resolve(p, t, h, CK_R_REVOKE, -1, 0, &idx, &end);
+ if (e != OSH_E_OK) {
+ e = refuse(p, e);
+ pool_unlock(p);
+ return e;
+ }
+ struct ck_pipe *q = &p->pipes[idx];
+ q->flags |= CK_PIPE_REVOKED;
+ q->flags &= ~(CK_PIPE_CANCEL_READ | CK_PIPE_CANCEL_WRITE);
+ bytes_zero(q->buf, CK_PIPE_CAPACITY); /* buffered bytes are never delivered after a revoke */
+ q->head = q->len = 0;
+ BUMP(p, q, revocations, 1);
+ note_wake(¬e, p, idx, CK_PIPE_END_READ);
+ note_wake(¬e, p, idx, CK_PIPE_END_WRITE);
+ pool_unlock(p);
+ fire_wakes(p, ¬e);
+ return OSH_E_OK;
+}
+
+unsigned ck_pipe_cancel(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h)
+{
+ struct ck_wake_note note = { 0 };
+ pool_lock(p);
+ unsigned idx, end, rights = 0;
+ unsigned e = resolve(p, t, h, 0, -1, 0, &idx, &end);
+ if (e != OSH_E_OK) {
+ e = refuse(p, e);
+ pool_unlock(p);
+ return e;
+ }
+ ck_cap_rights(t, h, &rights);
+ if (!(rights & data_right(end))) { /* the end's own data right: READ to interrupt reads, WRITE to interrupt writes */
+ e = refuse(p, OSH_E_DENIED);
+ pool_unlock(p);
+ return e;
+ }
+ p->pipes[idx].flags |= end == CK_PIPE_END_READ ? CK_PIPE_CANCEL_READ : CK_PIPE_CANCEL_WRITE;
+ note_wake(¬e, p, idx, end);
+ pool_unlock(p);
+ fire_wakes(p, ¬e);
+ return OSH_E_OK;
+}
+
+unsigned ck_pipe_release_table(struct ck_pipe_pool *p, struct ck_cap_table *t)
+{
+ struct ck_wake_note note = { 0 };
+ unsigned closed = 0;
+ pool_lock(p);
+ for (unsigned i = 0; i < t->n; i++) {
+ const struct ck_cap_slot *s = &t->slots[i];
+ if (!s->live || s->tombstone || (s->resource >> 24) != CK_PIPE_RES_TAG)
+ continue;
+ struct ck_handle h = { i, s->generation };
+ if (close_locked(p, t, h, ¬e) == OSH_E_OK)
+ closed++;
+ }
+ pool_unlock(p);
+ fire_wakes(p, ¬e);
+ return closed;
+}
+
+/* ---- versioned op table ---- */
+static const uint8_t op_args[] = { [CK_PIPE_OP_CREATE] = 0, [CK_PIPE_OP_READ] = 2, [CK_PIPE_OP_WRITE] = 2,
+ [CK_PIPE_OP_CLOSE] = 1, [CK_PIPE_OP_DUP] = 3 };
+#define OP_MAX CK_PIPE_OP_DUP
+
+#ifndef CK_PIPE_MUTANT_SKIP_SLICE
+/* 1 when [s, s+len) lies in [lo, hi). len 0 passes. Otherwise no s+len add: a wrapping length fails. */
+static int slice_ok(const void *s, size_t len, uintptr_t lo, uintptr_t hi)
+{
+ uintptr_t b = (uintptr_t)s;
+ if (len == 0)
+ return 1;
+ if (lo >= hi || b < lo || b >= hi)
+ return 0;
+ return len <= hi - b;
+}
+#endif
+
+unsigned ck_pipe_dispatch(struct ck_pipe_pool *p, struct ck_cap_table *caller, struct ck_cap_table *peer,
+ const uint64_t *frame, size_t ncells, uint8_t *slice, size_t slice_len,
+ uintptr_t user_lo, uintptr_t user_hi, struct ck_pipe_ret *ret)
+{
+ struct ck_pipe_ret r = { 0 };
+ unsigned e;
+ struct ck_handle h = { 0, 0 };
+ if (!frame || ncells < 4 || frame[0] != CK_PIPE_FRAME_MAGIC) {
+ e = OSH_E_INVALID_ARG;
+ goto done;
+ }
+ if (frame[1] != CK_PIPE_ABI_VERSION) {
+ e = OSH_E_NOT_SUPPORTED; /* section 3: never guess at another version */
+ goto done;
+ }
+ if (frame[3] != 0) {
+ e = OSH_E_INVALID_ARG;
+ goto done;
+ }
+ if (frame[2] == 0 || frame[2] > OP_MAX) {
+ e = OSH_E_NOT_SUPPORTED; /* unknown op: refused before any effect */
+ goto done;
+ }
+ unsigned op = (unsigned)frame[2];
+ if (ncells != 4u + op_args[op] || (op != CK_PIPE_OP_CREATE && ck_handle_from_raw(frame[4], &h) != 0)) {
+ e = OSH_E_INVALID_ARG;
+ goto done;
+ }
+ size_t n = 0;
+ switch (op) {
+ case CK_PIPE_OP_CREATE: {
+ struct ck_handle rd, wr;
+ e = ck_pipe_create(p, caller, &rd, &wr);
+ if (e == OSH_E_OK) {
+ r.value = ck_handle_raw(rd);
+ r.value2 = ck_handle_raw(wr);
+ }
+ break;
+ }
+ case CK_PIPE_OP_READ:
+ case CK_PIPE_OP_WRITE:
+ if (frame[5] & ~(uint64_t)CK_PIPE_F_BLOCK) {
+ e = OSH_E_INVALID_ARG;
+ break;
+ }
+#ifdef CK_PIPE_MUTANT_SKIP_SLICE
+ /* TEST-ONLY (make pipe-slice-mutant): the user window is not checked. test_pipe must fail. */
+ (void)user_lo;
+ (void)user_hi;
+#else
+ if (!slice_ok(slice, slice_len, user_lo, user_hi)) {
+ e = OSH_E_INVALID_ARG;
+ break;
+ }
+#endif
+ e = op == CK_PIPE_OP_READ ? ck_stream_read(p, caller, h, slice, slice_len, (unsigned)frame[5], &n)
+ : ck_stream_write(p, caller, h, slice, slice_len, (unsigned)frame[5], &n);
+ r.value = n;
+ break;
+ case CK_PIPE_OP_CLOSE:
+ e = ck_stream_close(p, caller, h);
+ break;
+ default: { /* CK_PIPE_OP_DUP */
+ struct ck_handle c;
+ if (frame[5] & ~(uint64_t)CK_R_ALL || frame[6] > 1 || (frame[6] == 1 && !peer)) {
+ e = OSH_E_INVALID_ARG;
+ break;
+ }
+ e = ck_stream_dup(p, caller, h, frame[6] ? peer : caller, (unsigned)frame[5], &c);
+ if (e == OSH_E_OK)
+ r.value = ck_handle_raw(c);
+ break;
+ }
+ }
+done:
+ r.error = e;
+ if (ret)
+ *ret = r;
+ return e;
+}
diff --git a/native/kernel/core/pipe.h b/native/kernel/core/pipe.h
new file mode 100644
index 00000000 ..633fefec
--- /dev/null
+++ b/native/kernel/core/pipe.h
@@ -0,0 +1,216 @@
+/* pipe.h -- bounded byte-stream pipes, a native AIENOS execution primitive (aienos-mv#428, AIENOS-NATIVE-PIPE-1).
+ *
+ * Contract: aien-protocols-mv specs/osh-platform/OSH_PLATFORM_ABI.md read at commit fb5fca98e667 (v1 DRAFT, unfrozen):
+ * section 8.1 (PIPE_CREATE, STREAM_READ / WRITE / CLOSE / DUP; bounded pipes with backpressure, WOULD_BLOCK or block,
+ * BROKEN_PIPE when the reader closed), 8.5 (64 KiB per pipe minimum, LIMIT instead of truncation), 8.6 (error codes,
+ * shared with osh_op.h through osh_err.h), 4.4 (epoch: an id from another epoch fails STALE) and 9.2 (authority is
+ * checked at the moment of the effect). Anything below marked UNVERIFIED is this kernel's own choice where the draft
+ * names a thing but does not pin it.
+ *
+ * This is a byte pipe, separate from the 56-byte typed message ring in ipc.h. It reuses only the capability tables of
+ * ipc.h: every stream end is a capability in the caller's ck_cap_table, and every operation looks the handle up with
+ * ck_cap_lookup (live slot, matching generation, required right) when the effect happens, not before.
+ *
+ * read end capability with CK_R_READ (never CK_R_WRITE)
+ * write end capability with CK_R_WRITE (never CK_R_READ)
+ * optional CK_R_DERIVE (dup into the same table), CK_R_GRANT (dup into another table), CK_R_REVOKE (revoke the pipe)
+ *
+ * Lifetimes. A pipe lives while at least one end capability is open. reader_refs / writer_refs count the open end
+ * capabilities (create gives one of each, every dup adds one, every close removes one). Last writer closed: once the
+ * buffer is drained a read returns OK with 0 bytes (EOF). No reader: a write returns BROKEN_PIPE. Both counts zero: the
+ * pipe slot is scrubbed and freed. Capabilities are independent slots (no derive parent link), so a closed end frees
+ * its slot at once and a table can always be emptied; ipc.h cascading revoke is therefore not used for pipes.
+ * Every pipe capability must be released through ck_stream_close or ck_pipe_release_table: removing one with
+ * ck_cap_remove directly would leave its count held.
+ *
+ * Epoch. Each pool slot has an epoch, incremented every time the slot is (re)created. The capability resource carries
+ * it, so a capability that outlived its pipe never reaches the next pipe in that slot: STALE. A handle whose capability
+ * slot was closed (and maybe reused with a new generation) also fails STALE, by the ck_cap generation check.
+ *
+ * Revocation and cancellation. ck_pipe_revoke (CK_R_REVOKE on either end) kills the whole pipe: the buffered bytes are
+ * scrubbed, both ends are woken, and every later read, write, dup or cancel on any end returns REVOKED; no byte is
+ * delivered after a revoke. Only close still works, to release the handles. ck_pipe_cancel (the data right of that
+ * end) interrupts the end: the next or currently blocked read (or write) on that end returns INTERRUPTED with no
+ * bytes moved, once; a later call runs normally (section 10: an interrupted wait is retried without re-running an
+ * effect, and an interrupted call here never moved a byte).
+ *
+ * Blocking. With CK_PIPE_F_BLOCK a read on an empty pipe or a write on a full one parks the caller through the
+ * pool's wait hook instead of returning WOULD_BLOCK, and retries (re-checking authority) after the hook returns OK.
+ * A blocking call returns as soon as it moved at least one byte (partial I/O; the caller loops). The kernel's hook
+ * yields to the scheduler; the host test simulates it. Without a wait hook a blocking call returns WOULD_BLOCK.
+ * A blocking write copies the bytes it may commit into a kernel buffer before it parks (at most CK_PIPE_WRITE_SNAP
+ * of them) and the retry reads that buffer, not the caller memory. A write that does not park copies once, under
+ * the pool lock, straight into the ring.
+ *
+ * Locking. One ticket lock covers the pool (every pipe, the ref counts, the ring, the stats, the live count).
+ * core/smp.c is the kernel's SMP primitive and it synchronises with __atomic_*; there is no separate spinlock
+ * type, so the ticket lock uses those same orders. create, read, write, close, dup, revoke, cancel, release and
+ * ck_pipe_pool_empty all take it. It is not IRQ-safe: pipe ops are not called from interrupt handlers. If a wake
+ * or a cancel is ever called from an IRQ, this lock must mask IRQs, or that CPU deadlocks against itself. It is
+ * never held across wait or wake, so a hook may call back into the pipe. The waiter increments waiting[end] under
+ * the lock before dropping it; a waker calls the wake hook after dropping the lock, and only when that count was
+ * non-zero. The wake hook must be sticky (woken[] stays set until wait has observed it). before_wait, if set,
+ * runs in that window; production leaves it NULL. The capability table is covered only by this pool lock. Another
+ * core using the same ck_cap_table for a non-pipe operation would race.
+ * ck_pipe_pool_init is single-threaded, before the pool is shared.
+ *
+ * User window. ck_pipe_dispatch rejects a read or a write whose slice lies outside [user_lo, user_hi) with
+ * INVALID_ARG, before anything reads or writes the slice. A length of 0 passes. Otherwise the base must sit in
+ * [user_lo, user_hi) and the length must be <= user_hi - base. The check never adds base and length, so a length
+ * that would wrap the address space fails. ck_stream_read and ck_stream_write do not repeat it; a direct caller
+ * passes a kernel buffer it already owns.
+ * The syscall layer still has two duties. It must assert, on each architecture, that user_hi is below the user-VA
+ * top: below TTBR1 (0xFFFF000000000000) on ARM64, and below the canonical upper half on x86. It must copy the
+ * slice in and out through a kernel bounce buffer outside the pool lock, so a user fault never runs while the
+ * ticket lock is held.
+ *
+ * Memory: a fixed pool of CK_PIPE_POOL_PIPES pipes with CK_PIPE_CAPACITY bytes each, all static; nothing grows.
+ * Pure logic, no hardware: host-tested in tests/test_pipe.c (fixtures in tests/fixtures/pipe/, plus host threads
+ * for concurrent read, write and close), driven in QEMU by core/pipe_test.c (CK_PIPE_TEST). The QEMU driver is
+ * one kernel thread. Host and QEMU evidence qualify nothing physical. */
+#ifndef AIENOS_CK_PIPE_H
+#define AIENOS_CK_PIPE_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include "ipc.h"
+#include "osh_err.h"
+
+#define CK_PIPE_ABI_VERSION 1u /* section 3: abi_version of the platform frame */
+#define CK_PIPE_FRAME_MAGIC 0x4F534846u /* section 3: "OSHF", platform frame magic */
+#define CK_PIPE_CAPACITY 65536u /* bytes per pipe; section 8.5 minimum 64 KiB (LIMITS_GET max_pipe_bytes) */
+#define CK_PIPE_POOL_PIPES 4u /* pipes per pool; UNVERIFIED: the draft sets no pipe count */
+_Static_assert(CK_PIPE_CAPACITY >= 65536u, "section 8.5: at least 64 KiB per pipe");
+_Static_assert(CK_PIPE_POOL_PIPES >= 1u && CK_PIPE_POOL_PIPES <= 8u, "the pipe index has three bits in the resource");
+
+/* Capability resource of a stream end: tag 0x50 ("P") in bits 31..24, end in bit 23, pipe index in bits 22..20,
+ * epoch in bits 19..0. A slot whose epoch reached CK_PIPE_EPOCH_MAX is retired for good. Layout UNVERIFIED (own). */
+#define CK_PIPE_RES_TAG 0x50u
+#define CK_PIPE_EPOCH_MAX 0xFFFFFu
+static inline uint32_t ck_pipe_resource(unsigned idx, unsigned end, uint32_t epoch)
+{
+ return (CK_PIPE_RES_TAG << 24) | ((uint32_t)(end & 1u) << 23) | ((uint32_t)(idx & 7u) << 20) |
+ (epoch & CK_PIPE_EPOCH_MAX);
+}
+
+enum ck_pipe_end { CK_PIPE_END_READ = 0, CK_PIPE_END_WRITE = 1 };
+
+/* Platform op ids of the versioned op table. The draft names the operations; the numbers are UNVERIFIED (own). */
+enum ck_pipe_op {
+ CK_PIPE_OP_CREATE = 1, /* PIPE_CREATE() -> (read_stream, write_stream) */
+ CK_PIPE_OP_READ = 2, /* STREAM_READ(stream, out_slice) -> n, 0 = EOF */
+ CK_PIPE_OP_WRITE = 3, /* STREAM_WRITE(stream, in_slice) -> n, partial writes allowed */
+ CK_PIPE_OP_CLOSE = 4, /* STREAM_CLOSE(stream) */
+ CK_PIPE_OP_DUP = 5, /* STREAM_DUP(src_stream, rights, target table) -> stream; capability form, UNVERIFIED */
+};
+
+#define CK_PIPE_F_BLOCK 0x1u /* read / write flag: park through the wait hook instead of WOULD_BLOCK */
+/* Bytes a blocking write snapshots before it parks. Kept under 4 KiB so a nested park still fits a 16 KiB
+ * secondary-core stack (core/smp.c). A longer blocking write returns a partial count and the caller loops. */
+#define CK_PIPE_WRITE_SNAP 1024u
+_Static_assert(CK_PIPE_WRITE_SNAP >= 1u && CK_PIPE_WRITE_SNAP <= 4096u, "snapshot must fit a secondary stack");
+
+/* Rights a create gives each end beyond its data right, and the only rights a dup may carry. */
+#define CK_PIPE_CTL_RIGHTS (CK_R_DERIVE | CK_R_GRANT | CK_R_REVOKE)
+
+struct ck_pipe_stats {
+ uint64_t bytes_written, bytes_read; /* bytes that moved */
+ uint64_t writes, reads; /* calls that moved at least one byte */
+ uint64_t max_resident; /* most bytes ever buffered at once (never above CK_PIPE_CAPACITY) */
+ uint64_t would_block; /* WOULD_BLOCK results seen, returned or waited on (backpressure) */
+ uint64_t waits; /* calls into the wait hook */
+ uint64_t wakeups; /* calls into the wake hook (an end had a waiter) */
+ uint64_t cancellations; /* INTERRUPTED results */
+ uint64_t revocations; /* pipes revoked */
+ uint64_t broken_pipe; /* BROKEN_PIPE results */
+ uint64_t eof; /* reads that returned EOF */
+ uint64_t refused; /* DENIED, STALE and REVOKED results at the effect boundary (pool total only) */
+};
+
+#define CK_PIPE_LIVE 0x1u
+#define CK_PIPE_REVOKED 0x2u
+#define CK_PIPE_CANCEL_READ 0x4u
+#define CK_PIPE_CANCEL_WRITE 0x8u
+
+struct ck_pipe {
+ uint8_t buf[CK_PIPE_CAPACITY]; /* ring: bytes head..head+len-1 (mod capacity) are buffered */
+ uint32_t head, len;
+ uint32_t epoch; /* 0 = never created */
+ uint32_t reader_refs, writer_refs;
+ uint32_t flags;
+ uint32_t waiting[2]; /* callers parked in the wait hook, per end; only touched under the pool lock */
+ struct ck_pipe_stats stats; /* this incarnation; reset at create */
+};
+
+/* Wait / wake hook. wait: the caller would block on (pipe, end); return OSH_E_OK to retry the operation (it re-checks
+ * authority) or an error (normally OSH_E_INTERRUPTED) to give up; the operation then returns it with no byte moved.
+ * Called without the pool lock. The wake flag must be sticky. A wake may already have run after the waiter was
+ * published and before wait is called; wait must observe it and must not clear it before that observation
+ * (pd_wait leaves woken[] set until it has seen it). A hook that clears the flag on entry loses that wake.
+ * wake: (pipe, end) may proceed (bytes, space, close, revoke or cancel); called only when that end has a waiter,
+ * and only after the pool lock is dropped. before_wait: optional, same window, NULL in production. */
+struct ck_pipe_hooks {
+ void *ctx;
+ unsigned (*wait)(void *ctx, unsigned pipe, unsigned end);
+ void (*wake)(void *ctx, unsigned pipe, unsigned end);
+ void (*before_wait)(void *ctx);
+};
+
+struct ck_pipe_pool {
+ struct ck_pipe pipes[CK_PIPE_POOL_PIPES];
+ const struct ck_pipe_hooks *hooks; /* may be 0 */
+ struct ck_pipe_stats total; /* every incarnation since init */
+ unsigned live; /* pipes currently live */
+ /* Ticket lock. ticket is the next number handed out; serving is the number now inside.
+ * Both 0 is unlocked. Only __atomic_* touches them. */
+ uint32_t lock_ticket, lock_serving;
+};
+
+void ck_pipe_pool_init(struct ck_pipe_pool *p, const struct ck_pipe_hooks *hooks);
+/* 1 if no pipe is live (every end of every pipe was closed). Takes the pool lock. */
+int ck_pipe_pool_empty(struct ck_pipe_pool *p);
+
+/* PIPE_CREATE: a new pipe, both ends inserted into t. LIMIT if the pool or the table is full (nothing is left
+ * allocated). The draft's PIPE_CREATE takes no binding, so no prior capability is required (UNVERIFIED). */
+unsigned ck_pipe_create(struct ck_pipe_pool *p, struct ck_cap_table *t, struct ck_handle *rd, struct ck_handle *wr);
+/* STREAM_READ / STREAM_WRITE: *n = bytes moved (0 with OK on a read = EOF, or max == 0). */
+unsigned ck_stream_read(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h, uint8_t *buf,
+ size_t max, unsigned flags, size_t *n);
+unsigned ck_stream_write(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h, const uint8_t *buf,
+ size_t len, unsigned flags, size_t *n);
+/* STREAM_CLOSE: releases the capability. Works on a revoked pipe. STALE (after releasing the capability) if it named
+ * an earlier incarnation of the slot. */
+unsigned ck_stream_close(struct ck_pipe_pool *p, struct ck_cap_table *t, struct ck_handle h);
+/* STREAM_DUP: a new capability on the same end in `to` with `rights`, which must hold the end's data right, be a
+ * subset of the source rights and of data right | CK_PIPE_CTL_RIGHTS. Needs CK_R_DERIVE (to == from) or
+ * CK_R_GRANT (another table) on the source. */
+unsigned ck_stream_dup(struct ck_pipe_pool *p, struct ck_cap_table *from, struct ck_handle h, struct ck_cap_table *to,
+ unsigned rights, struct ck_handle *out);
+/* Revoke the whole pipe (CK_R_REVOKE on either end). */
+unsigned ck_pipe_revoke(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h);
+/* Interrupt the end h names (its data right needed). */
+unsigned ck_pipe_cancel(struct ck_pipe_pool *p, const struct ck_cap_table *t, struct ck_handle h);
+/* Section 12 cleanup: closes every pipe capability in t. Returns how many STREAM_CLOSE calls returned OK.
+ * A failure is not counted. STALE (the capability was released, but it named a dead incarnation) is a failure. */
+unsigned ck_pipe_release_table(struct ck_pipe_pool *p, struct ck_cap_table *t);
+
+/* ---- versioned op table ----
+ * A platform call frame is cells (u64): 0 magic CK_PIPE_FRAME_MAGIC, 1 abi_version, 2 op, 3 reserved (0), then the
+ * op's arguments; the frame must be exactly 4 + nargs cells. Arguments: READ / WRITE: handle (ck_handle_raw form),
+ * flags; CLOSE: handle; DUP: handle, rights, target (0 caller table, 1 peer table); CREATE: none. The byte slice is
+ * the read destination or the write source. Check order, first failure wins, all before any effect: frame shorter
+ * than 4 cells, bad magic or nonzero reserved -> INVALID_ARG; abi_version not CK_PIPE_ABI_VERSION or an unknown op
+ * -> NOT_SUPPORTED; wrong cell count, a generation-0 handle or unknown flag bits -> INVALID_ARG.
+ * Result: {error, value} as in section 8; PIPE_CREATE also fills value2 (the write end). value2 is UNVERIFIED.
+ * READ and WRITE then require slice[0, slice_len) inside [user_lo, user_hi), user_hi exclusive. A length of 0
+ * passes. Any other slice is INVALID_ARG before the buffer is touched (see the user-window note above).
+ * user_lo and user_hi are the caller's window; kernel self-tests pass the bounds of their own buffer. */
+struct ck_pipe_ret {
+ uint32_t error;
+ uint64_t value, value2;
+};
+unsigned ck_pipe_dispatch(struct ck_pipe_pool *p, struct ck_cap_table *caller, struct ck_cap_table *peer,
+ const uint64_t *frame, size_t ncells, uint8_t *slice, size_t slice_len,
+ uintptr_t user_lo, uintptr_t user_hi, struct ck_pipe_ret *ret);
+
+#endif
diff --git a/native/kernel/core/pipe_drive.h b/native/kernel/core/pipe_drive.h
new file mode 100644
index 00000000 ..f248467b
--- /dev/null
+++ b/native/kernel/core/pipe_drive.h
@@ -0,0 +1,227 @@
+/* pipe_drive.h -- TEST driver for the pipe primitive (pipe.h): a producer and a consumer task, each a step function,
+ * interleaved by the run-queue scheduler (sched.h), exchanging a binary payload (every fifth byte NUL) through one pipe.
+ * Shared by the host test (tests/test_pipe.c) and the QEMU self-test (core/pipe_test.c, CK_PIPE_TEST) so both run
+ * the same scenario. No libc, no allocation: the caller owns the world, the pool, both tables and the sink buffer.
+ *
+ * The producer owns the write end; the read end is handed to the consumer's own table with STREAM_DUP (READ, plus
+ * REVOKE for the revocation scenario) and the producer's copy is closed, so each task holds one end. Non-blocking mode:
+ * a WOULD_BLOCK ends the step with no progress and the scheduler runs the other task. Blocking mode: the wait hook
+ * marks the caller blocked and keeps ticking the scheduler, running the other task's steps, until the wake hook fires
+ * for that end (OK, the call retries) or the spin bound runs out (INTERRUPTED: a stalled peer). A wake posted
+ * before wait runs is kept: woken[] is not cleared on entry. Static functions only. One kernel thread. */
+#ifndef AIENOS_CK_PIPE_DRIVE_H
+#define AIENOS_CK_PIPE_DRIVE_H
+
+#include "pipe.h"
+#include "sched.h"
+
+#define PD_CHUNK_MAX 8192u
+#define PD_SPIN_MAX 64u
+#define PD_TICK_MAX 2000000u
+
+struct pd_world;
+struct pd_task {
+ uint32_t id;
+ int done, blocked;
+ void (*step)(struct pd_world *w, struct pd_task *t);
+};
+
+struct pd_world {
+ struct ck_pipe_pool *pool;
+ struct ck_cap_table *prod_t, *cons_t;
+ struct ck_pipe_hooks hooks;
+ struct ck_sched sched;
+ struct pd_task tasks[2]; /* 0 producer, 1 consumer */
+ struct pd_task *current;
+ struct ck_handle w, r;
+ uint8_t woken[CK_PIPE_POOL_PIPES][2];
+ unsigned flags; /* CK_PIPE_F_BLOCK or 0 */
+ size_t total; /* payload bytes to send */
+ size_t chunk_w, chunk_r; /* bytes per producer write / consumer read */
+ unsigned prod_every, cons_every; /* a task moves bytes on one step in this many (a slow side), 0 or 1 = every step */
+ size_t revoke_at; /* consumer revokes the pipe once it has this many bytes (0 = never) */
+ uint8_t *sink; /* total bytes */
+ uint8_t wbuf[PD_CHUNK_MAX], rbuf[PD_CHUNK_MAX];
+ /* results */
+ size_t sent, recvd, reads_after_revoke;
+ unsigned setup_err, prod_err, cons_err; /* OSH_E_OK, or the error the task ended on */
+ int eof_seen, revoked;
+ uint64_t ticks, wait_spins, prod_steps, cons_steps;
+};
+
+static inline uint8_t pd_byte(size_t i)
+{
+ return i % 5 == 0 ? 0 : (uint8_t)(((uint32_t)i * 2654435761u) >> 13);
+}
+
+static inline struct pd_task *pd_find(struct pd_world *w, uint32_t id)
+{
+ return w->tasks[0].id == id ? &w->tasks[0] : w->tasks[1].id == id ? &w->tasks[1] : 0;
+}
+
+/* One scheduler tick: run the picked task's step unless it is blocked (parked on the stack) or done. */
+static inline int pd_tick(struct pd_world *w)
+{
+ uint32_t id = 0;
+ if (ck_sched_tick(&w->sched, 0, &id) != 1)
+ return 0;
+ w->ticks++;
+ struct pd_task *t = pd_find(w, id);
+ if (!t || t->blocked || t->done)
+ return 1;
+ struct pd_task *prev = w->current;
+ w->current = t;
+ t->step(w, t);
+ w->current = prev;
+ if (t->done)
+ ck_sched_remove(&w->sched, t->id);
+ return 1;
+}
+
+static inline unsigned pd_wait(void *ctx, unsigned pipe, unsigned end)
+{
+ struct pd_world *w = ctx;
+ struct pd_task *me = w->current;
+ if (!me)
+ return OSH_E_INTERRUPTED;
+ me->blocked = 1;
+ /* Do not clear woken[] here. The pipe publishes the waiter, drops its lock, then calls wait. A peer can
+ * wake in that window. Clearing first would drop that wake and the task would sleep with data already queued. */
+ for (unsigned s = 0; s < PD_SPIN_MAX; s++) {
+ if (__atomic_load_n(&w->woken[pipe][end], __ATOMIC_ACQUIRE))
+ break;
+ w->wait_spins++;
+ if (!pd_tick(w))
+ break;
+ }
+ me->blocked = 0;
+ unsigned got = __atomic_exchange_n(&w->woken[pipe][end], 0, __ATOMIC_ACQ_REL);
+ return got ? OSH_E_OK : OSH_E_INTERRUPTED;
+}
+
+static inline void pd_wake(void *ctx, unsigned pipe, unsigned end)
+{
+ struct pd_world *w = ctx;
+ __atomic_store_n(&w->woken[pipe][end], 1, __ATOMIC_RELEASE);
+}
+
+static inline void pd_producer(struct pd_world *w, struct pd_task *t)
+{
+ w->prod_steps++;
+ if (w->prod_every > 1 && w->prod_steps % w->prod_every)
+ return; /* thinking: no I/O this step */
+ if (w->sent == w->total) {
+ ck_stream_close(w->pool, w->prod_t, w->w); /* last writer: the consumer sees EOF once drained */
+ t->done = 1;
+ return;
+ }
+ size_t want = w->total - w->sent;
+ if (want > w->chunk_w)
+ want = w->chunk_w;
+ for (size_t i = 0; i < want; i++)
+ w->wbuf[i] = pd_byte(w->sent + i);
+ size_t n = 0;
+ unsigned e = ck_stream_write(w->pool, w->prod_t, w->w, w->wbuf, want, w->flags, &n);
+ if (e == OSH_E_OK) {
+ w->sent += n;
+ } else if (e != OSH_E_WOULD_BLOCK) {
+ w->prod_err = e;
+ ck_stream_close(w->pool, w->prod_t, w->w);
+ t->done = 1;
+ }
+}
+
+static inline void pd_consumer(struct pd_world *w, struct pd_task *t)
+{
+ w->cons_steps++;
+ if (w->cons_every > 1 && w->cons_steps % w->cons_every)
+ return;
+ size_t n = 0;
+ unsigned e = ck_stream_read(w->pool, w->cons_t, w->r, w->rbuf, w->chunk_r, w->flags, &n);
+ if (e == OSH_E_OK && n > 0) {
+ if (w->revoked)
+ w->reads_after_revoke++;
+ for (size_t i = 0; i < n && w->recvd + i < w->total; i++)
+ w->sink[w->recvd + i] = w->rbuf[i];
+ w->recvd += n;
+ if (w->revoke_at && !w->revoked && w->recvd >= w->revoke_at) {
+ w->revoked = ck_pipe_revoke(w->pool, w->cons_t, w->r) == OSH_E_OK;
+ if (!w->revoked)
+ w->cons_err = OSH_E_IO;
+ }
+ } else if (e == OSH_E_OK) {
+ w->eof_seen = 1;
+ ck_stream_close(w->pool, w->cons_t, w->r);
+ t->done = 1;
+ } else if (e != OSH_E_WOULD_BLOCK) {
+ w->cons_err = e;
+ ck_stream_close(w->pool, w->cons_t, w->r);
+ t->done = 1;
+ }
+}
+
+/* Run one transfer. pool and both tables must be fresh (the pool initialised with &w->hooks by this call). */
+static inline void pd_run(struct pd_world *w, struct ck_pipe_pool *pool, struct ck_cap_table *prod_t,
+ struct ck_cap_table *cons_t, uint8_t *sink, size_t total, size_t chunk_w, size_t chunk_r,
+ unsigned flags, unsigned prod_every, unsigned cons_every, size_t revoke_at)
+{
+ *w = (struct pd_world){ .pool = pool, .prod_t = prod_t, .cons_t = cons_t, .sink = sink, .total = total,
+ .chunk_w = chunk_w > PD_CHUNK_MAX ? PD_CHUNK_MAX : chunk_w,
+ .chunk_r = chunk_r > PD_CHUNK_MAX ? PD_CHUNK_MAX : chunk_r, .flags = flags,
+ .prod_every = prod_every, .cons_every = cons_every, .revoke_at = revoke_at };
+ w->hooks = (struct ck_pipe_hooks){ w, pd_wait, pd_wake, 0 };
+ ck_pipe_pool_init(pool, &w->hooks);
+ struct ck_handle r0;
+ w->setup_err = ck_pipe_create(pool, prod_t, &r0, &w->w);
+ if (w->setup_err != OSH_E_OK)
+ return;
+ w->setup_err = ck_stream_dup(pool, prod_t, r0, cons_t, CK_R_READ | (revoke_at ? CK_R_REVOKE : 0), &w->r);
+ unsigned c = ck_stream_close(pool, prod_t, r0); /* the producer keeps only the write end */
+ if (w->setup_err == OSH_E_OK)
+ w->setup_err = c;
+ if (w->setup_err != OSH_E_OK) {
+ ck_pipe_release_table(pool, prod_t);
+ ck_pipe_release_table(pool, cons_t);
+ return;
+ }
+ static const uint8_t classes[1] = { 0 };
+ ck_sched_init(&w->sched, 1, classes, CK_SCHED_MAX_TASKS, 1);
+ w->tasks[0] = (struct pd_task){ .id = 0x50524f44u, .step = pd_producer }; /* "PROD" */
+ w->tasks[1] = (struct pd_task){ .id = 0x434f4e53u, .step = pd_consumer }; /* "CONS" */
+ ck_sched_enqueue(&w->sched, w->tasks[0].id, CK_PRIO_NORMAL);
+ ck_sched_enqueue(&w->sched, w->tasks[1].id, CK_PRIO_NORMAL);
+ while ((!w->tasks[0].done || !w->tasks[1].done) && w->ticks < PD_TICK_MAX)
+ if (!pd_tick(w))
+ break;
+ /* section 12: whatever happened, no end stays open */
+ ck_pipe_release_table(pool, prod_t);
+ ck_pipe_release_table(pool, cons_t);
+}
+
+/* Bytes of the sink that differ from the payload, over what was received. */
+static inline size_t pd_mismatches(const struct pd_world *w)
+{
+ size_t bad = 0, n = w->recvd < w->total ? w->recvd : w->total;
+ for (size_t i = 0; i < n; i++)
+ bad += w->sink[i] != pd_byte(i);
+ return bad;
+}
+
+static inline size_t pd_nul_count(const struct pd_world *w)
+{
+ size_t z = 0, n = w->recvd < w->total ? w->recvd : w->total;
+ for (size_t i = 0; i < n; i++)
+ z += w->sink[i] == 0;
+ return z;
+}
+
+/* 1 if the table holds no live slot at all (tombstones included). */
+static inline int pd_table_empty(const struct ck_cap_table *t)
+{
+ for (unsigned i = 0; i < CK_CAP_SLOTS; i++)
+ if (t->slots[i].live)
+ return 0;
+ return 1;
+}
+
+#endif
diff --git a/native/kernel/core/pipe_test.c b/native/kernel/core/pipe_test.c
new file mode 100644
index 00000000 ..8d789951
--- /dev/null
+++ b/native/kernel/core/pipe_test.c
@@ -0,0 +1,173 @@
+/* pipe_test.c -- AIENOS_CK_PIPE kernel self-test (TEST ONLY, CK_PIPE_TEST=1; gate scripts/qemu_ck_pipe_test.sh).
+ *
+ * Drives the pipe primitive (core/pipe.c, aienos-mv#428) inside the kernel: a producer and a consumer task, step
+ * functions interleaved by the run-queue scheduler (core/sched.c), each holding one end in its own capability table,
+ * through the same driver the host test uses (core/pipe_drive.h). The kernel's wait hook yields to the scheduler
+ * (it keeps ticking it, running the other task) until the wake hook fires; this is cooperative scheduling inside one
+ * kernel thread, not a context switch between M3 threads. Lines on the serial console:
+ * pipe_check: name=<check> result=PASS|FAIL <details>; <label>
+ * pipe_test: done checks=<n> failed=<n> capacity=<bytes> pool_pipes=<n>; <label>
+ * QEMU (aarch64 virt), TEST build, not physical: qualifies nothing physical. */
+#ifndef CK_PIPE_TEST
+#error "pipe_test is test-only: build with make CK_PIPE_TEST=1"
+#endif
+#ifdef CK_HARDWARE_STAGING
+#error "CK_PIPE_TEST cannot be combined with CK_HARDWARE_STAGING"
+#endif
+#include "ck_internal.h"
+#include "pipe.h"
+#include "pipe_drive.h"
+
+#define LABEL "QEMU (aarch64 virt), TEST build, not physical"
+#define PAYLOAD (160u * 1024u) /* 2.5 pipe capacities */
+
+static struct ck_pipe_pool pool;
+static struct ck_cap_table ta, tb;
+static struct pd_world world;
+static uint8_t sink[PAYLOAD];
+static unsigned checks, failed;
+
+static void fresh(void)
+{
+ ck_cap_init(&ta, 0x41, CK_CAP_SLOTS);
+ ck_cap_init(&tb, 0x42, CK_CAP_SLOTS);
+}
+
+static int empty(void)
+{
+ return pd_table_empty(&ta) && pd_table_empty(&tb) && ck_pipe_pool_empty(&pool);
+}
+
+static void verdict(const char *name, int ok)
+{
+ checks++;
+ failed += !ok;
+ ck_printf("pipe_check: name=%s result=%s tables_empty=%d; %s\n", name, ok ? "PASS" : "FAIL", empty(), LABEL);
+}
+
+static size_t expected_nuls(size_t n)
+{
+ size_t z = 0;
+ for (size_t i = 0; i < n; i++)
+ z += pd_byte(i) == 0;
+ return z;
+}
+
+static void transfer(const char *name, unsigned flags)
+{
+ fresh();
+ pd_run(&world, &pool, &ta, &tb, sink, PAYLOAD, 8192, 1000, flags, 1, 4, 0);
+ const struct ck_pipe_stats *s = &pool.total;
+ size_t bad = pd_mismatches(&world), nul = pd_nul_count(&world);
+ ck_printf("pipe_detail: %s bytes=%lu sent=%lu nul=%lu expected_nul=%lu mismatches=%lu would_block=%llu waits=%llu "
+ "wakeups=%llu max_resident=%llu capacity=%u eof=%d prod_steps=%llu cons_steps=%llu ticks=%llu\n",
+ name, (unsigned long)world.recvd, (unsigned long)world.sent, (unsigned long)nul,
+ (unsigned long)expected_nuls(PAYLOAD), (unsigned long)bad, (unsigned long long)s->would_block,
+ (unsigned long long)s->waits, (unsigned long long)s->wakeups, (unsigned long long)s->max_resident,
+ CK_PIPE_CAPACITY, world.eof_seen, (unsigned long long)world.prod_steps,
+ (unsigned long long)world.cons_steps, (unsigned long long)world.ticks);
+ int moved = world.setup_err == OSH_E_OK && world.prod_err == OSH_E_OK && world.cons_err == OSH_E_OK &&
+ world.recvd == PAYLOAD && world.sent == PAYLOAD && bad == 0 && nul == expected_nuls(PAYLOAD) &&
+ nul > 0 && s->bytes_read == PAYLOAD;
+ if (!flags) {
+ verdict("payload_nul_byte_for_byte", moved);
+ verdict("backpressure_would_block", moved && s->would_block > 0 && s->max_resident == CK_PIPE_CAPACITY &&
+ world.prod_steps > 1 && world.cons_steps > 1);
+ verdict("eof_after_last_writer", moved && world.eof_seen && s->eof == 1);
+ verdict("bounded_memory", s->max_resident <= CK_PIPE_CAPACITY && empty());
+ } else {
+ verdict("blocking_wait_wake_through_scheduler", moved && s->waits > 0 && s->wakeups > 0 &&
+ s->cancellations == 0 && world.eof_seen && empty());
+ }
+}
+
+static void broken_pipe(void)
+{
+ fresh();
+ ck_pipe_pool_init(&pool, 0);
+ struct ck_handle r, w;
+ size_t n = 1;
+ static const uint8_t b[3] = { 'a', 0, 'b' };
+ int ok = ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK;
+ ok = ok && ck_stream_close(&pool, &ta, r) == OSH_E_OK;
+ unsigned e = ck_stream_write(&pool, &ta, w, b, 3, 0, &n);
+ ok = ok && e == OSH_E_BROKEN_PIPE && n == 0 && pool.total.broken_pipe == 1;
+ ok = ok && ck_stream_close(&pool, &ta, w) == OSH_E_OK;
+ ck_printf("pipe_detail: broken_pipe write_after_reader_close=%s n=%lu\n", osh_err_label(e), (unsigned long)n);
+ verdict("broken_pipe_no_reader", ok && empty());
+}
+
+static void revoked_write(void)
+{
+ fresh();
+ ck_pipe_pool_init(&pool, 0);
+ struct ck_handle r, w;
+ size_t n = 0, m = 9;
+ uint8_t got[4];
+ static const uint8_t b1[2] = { 'o', 'k' }, b2[2] = { 0, 'x' };
+ int ok = ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK;
+ ok = ok && ck_stream_write(&pool, &ta, w, b1, 2, 0, &n) == OSH_E_OK && n == 2;
+ ok = ok && ck_pipe_revoke(&pool, &ta, w) == OSH_E_OK;
+ unsigned ew = ck_stream_write(&pool, &ta, w, b2, 2, 0, &n);
+ unsigned er = ck_stream_read(&pool, &ta, r, got, 4, 0, &m);
+ ok = ok && ew == OSH_E_REVOKED && n == 0 && er == OSH_E_REVOKED && m == 0 && pool.total.bytes_read == 0;
+ ok = ok && ck_stream_close(&pool, &ta, r) == OSH_E_OK && ck_stream_close(&pool, &ta, w) == OSH_E_OK;
+ ck_printf("pipe_detail: revoked write=%s n=%lu read=%s n=%lu bytes_delivered=%llu\n", osh_err_label(ew),
+ (unsigned long)n, osh_err_label(er), (unsigned long)m, (unsigned long long)pool.total.bytes_read);
+ verdict("revoked_write_refused_no_bytes_after", ok && empty());
+
+ /* revoked mid-stream by the consumer through the scheduler: nothing is read after the revoke */
+ fresh();
+ pd_run(&world, &pool, &ta, &tb, sink, PAYLOAD, 8192, 1000, CK_PIPE_F_BLOCK, 1, 4, 50000);
+ ck_printf("pipe_detail: revoke_midstream recvd=%lu reads_after_revoke=%lu prod=%s cons=%s bytes_read=%llu\n",
+ (unsigned long)world.recvd, (unsigned long)world.reads_after_revoke, osh_err_label(world.prod_err),
+ osh_err_label(world.cons_err), (unsigned long long)pool.total.bytes_read);
+ verdict("revoke_midstream_no_data_after", world.revoked && world.reads_after_revoke == 0 &&
+ world.prod_err == OSH_E_REVOKED && world.cons_err == OSH_E_REVOKED &&
+ pool.total.bytes_read == world.recvd && pd_mismatches(&world) == 0 &&
+ empty());
+}
+
+static void stale_and_ops(void)
+{
+ fresh();
+ ck_pipe_pool_init(&pool, 0);
+ struct ck_handle r, w, r2, w2;
+ size_t n = 0;
+ uint8_t b[2] = { 0, 0 };
+ int ok = ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK;
+ ok = ok && ck_stream_close(&pool, &ta, r) == OSH_E_OK && ck_stream_close(&pool, &ta, w) == OSH_E_OK;
+ ok = ok && ck_pipe_create(&pool, &ta, &r2, &w2) == OSH_E_OK && r2.index == r.index;
+ unsigned es = ck_stream_read(&pool, &ta, r, b, 2, 0, &n);
+ ok = ok && es == OSH_E_STALE && ck_pipe_release_table(&pool, &ta) == 2;
+ verdict("stale_handle_after_close", ok && empty());
+
+ struct ck_pipe_ret ret;
+ uint64_t unknown[4] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, 9, 0 };
+ uint64_t v2[4] = { CK_PIPE_FRAME_MAGIC, 2, CK_PIPE_OP_CREATE, 0 };
+ /* No slice. A length of 0 does not consult the window. */
+ unsigned eu = ck_pipe_dispatch(&pool, &ta, &tb, unknown, 4, 0, 0, 0, 0, &ret);
+ unsigned ev = ck_pipe_dispatch(&pool, &ta, &tb, v2, 4, 0, 0, 0, 0, &ret);
+ ck_printf("pipe_detail: op_table abi_version=%u unknown_op=%s version_2=%s\n", CK_PIPE_ABI_VERSION,
+ osh_err_label(eu), osh_err_label(ev));
+ verdict("unknown_op_not_supported", eu == OSH_E_NOT_SUPPORTED && ev == OSH_E_NOT_SUPPORTED && empty());
+
+ ok = ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK && ck_pipe_cancel(&pool, &ta, w) == OSH_E_OK;
+ unsigned ei = ck_stream_write(&pool, &ta, w, b, 2, 0, &n);
+ ok = ok && ei == OSH_E_INTERRUPTED && n == 0 && ck_stream_write(&pool, &ta, w, b, 2, 0, &n) == OSH_E_OK && n == 2;
+ ok = ok && ck_pipe_release_table(&pool, &ta) == 2;
+ verdict("cancel_interrupts_once", ok && empty());
+}
+
+void ck_pipe_selftest(void)
+{
+ ck_printf("pipe_test: TEST-ONLY pipe self-test begin abi_version=%u capacity=%u pool_pipes=%u payload=%u; %s\n",
+ CK_PIPE_ABI_VERSION, CK_PIPE_CAPACITY, CK_PIPE_POOL_PIPES, PAYLOAD, LABEL);
+ transfer("nonblocking", 0);
+ transfer("blocking", CK_PIPE_F_BLOCK);
+ broken_pipe();
+ revoked_write();
+ stale_and_ops();
+ ck_printf("pipe_test: done checks=%u failed=%u capacity=%u pool_pipes=%u; %s\n", checks, failed, CK_PIPE_CAPACITY,
+ CK_PIPE_POOL_PIPES, LABEL);
+}
diff --git a/native/kernel/tests/.crumb b/native/kernel/tests/.crumb
index 50f62260 ..e84d6fd9 100644
--- a/native/kernel/tests/.crumb
+++ b/native/kernel/tests/.crumb
@@ -7,14 +7,14 @@
"generated": {
"children": [],
"children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "compiled_at": "2026-10-30T21:47:57Z",
+ "compiled_at": "2026-10-30T22:19:45Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:d532b7b49cd10c87e7e1528820c7d870b1eccd049ffe66cc4162bc01ae71c4a9 ",
+ "digest": "sha256:59c0ca771d489fe85c31391d5c8c2b70da110f5f13f4c15b9ba126a41ed3e5fa ",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "files": 197,
- "generated_at_commit": "1a71c956cbcae1cca7e88563d50973ea48107961 ",
- "source_tree": "sha256:1a92d182d4a413b551322a9e1b870d633a6ee472172a14357b7626df935717be "
+ "files": 219,
+ "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e ",
+ "source_tree": "sha256:1123f9c5096d098afcd490f67bc36f4f83ba5f9ecdfd6ffbee3ffec1e56dfec5 "
},
"owner_lane": "",
"provenance": {
diff --git a/native/kernel/tests/fixtures/pipe/README.md b/native/kernel/tests/fixtures/pipe/README.md
new file mode 100644
index 00000000 ..447ea5dc
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/README.md
@@ -0,0 +1,34 @@
+# Pipe primitive vectors (aienos-mv#428)
+
+Machine-checkable cases for the native pipe primitive (`native/kernel/core/pipe.c`), one file per case, read by
+`native/kernel/tests/test_pipe.c`. Contract: OSH_PLATFORM_ABI v1 DRAFT (aien-protocols-mv `specs/osh-platform/`,
+read at `fb5fca98e667 `), sections 4.4, 8.1, 8.5, 8.6 and 9. Authored from that text and this kernel's choices; the
+choices the draft leaves open are marked UNVERIFIED in `core/pipe.h`. Plain text so the corpus can later move to
+`specs/osh-platform/vectors/` next to the shell-core vectors (same quoted-byte escapes as their `expected.txt`).
+
+## File `pNNN_<name>.vec`
+
+- `case <name>` and `kind positive|negative` are required.
+- `#` starts a comment. Tokens are separated by spaces.
+- `<q>` is a double-quoted byte string: `\xHH` any byte, `\"` and `\\` themselves. NUL and bytes >= 0x80 are allowed.
+- Two capability tables exist, `A` and `B` (two principals), both empty at the start; the pool has 4 pipes of 65536 bytes.
+- Every step line is `<command> => <ERROR> [n=<N>] [data=<q>]`. `<ERROR>` is a section 8.6 name (`OK`, `DENIED`,
+ `REVOKED`, `STALE`, `INVALID_ARG`, `LIMIT`, `INTERRUPTED`, `BROKEN_PIPE`, `NOT_SUPPORTED`, `WOULD_BLOCK`, ...).
+ `n=` is the byte count moved (or, for `release`, the capabilities closed); `data=` the exact bytes read.
+
+| command | meaning |
+|---|---|
+| `create <R> <W> <T>` | PIPE_CREATE in table T; names the read and write end |
+| `write <H> <q>` | non-blocking STREAM_WRITE |
+| `fill <H> <count> <hex byte>` | non-blocking STREAM_WRITE of `count` copies of one byte |
+| `read <H> <max>` | non-blocking STREAM_READ |
+| `bread <H> <max> <action>` / `bwrite <H> <q> <action>` | blocking read / write; the first time it parks, the peer runs `<action>` (`none`, or one `write`, `read`, `close`, `revoke`, `cancel` command, which must return OK); a second park gives up INTERRUPTED (a stalled peer) |
+| `close <H>` | STREAM_CLOSE |
+| `dup <H> <NEW> <T> <rights>` | STREAM_DUP into table T; rights letters `r` READ, `w` WRITE, `m` MAP, `g` GRANT, `d` DERIVE, `v` REVOKE |
+| `revoke <H>` / `cancel <H>` | revoke the pipe / interrupt that end |
+| `release <T>` | close every pipe capability in table T (section 12 cleanup) |
+| `frame <T> <slice> <cell>...` | raw platform call through the versioned op table; `<slice>` is `-` or `<q>`; cells are hex, or `$<H>` for a handle in register form; the peer table is the other one |
+| `check <item>...` | `empty` (both tables and the pool hold nothing), or `<counter>=<N>` over the pool totals: `bytes_written bytes_read writes reads max_resident would_block waits wakeups cancellations revocations broken_pipe eof refused`, and `pipes` (live pipes) |
+
+A handle name keeps its value after `close`, so a later use of it tests a stale handle. Each case must end with every
+capability released: the runner fails a case whose tables or pool are not empty at the end of the file.
diff --git a/native/kernel/tests/fixtures/pipe/p001_nul_payload.vec b/native/kernel/tests/fixtures/pipe/p001_nul_payload.vec
new file mode 100644
index 00000000 ..e084ca5b
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p001_nul_payload.vec
@@ -0,0 +1,11 @@
+case nul_payload
+kind positive
+# bytes including NUL and 0xFF pass byte for byte; last writer closed -> EOF once drained
+create R W A => OK
+write W "a\x00b\x00\xff\x00" => OK n=6
+read R 16 => OK n=6 data="a\x00b\x00\xff\x00"
+close W => OK
+read R 16 => OK n=0
+check eof=1 bytes_written=6 bytes_read=6
+close R => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p002_capacity_partial.vec b/native/kernel/tests/fixtures/pipe/p002_capacity_partial.vec
new file mode 100644
index 00000000 ..38467866
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p002_capacity_partial.vec
@@ -0,0 +1,15 @@
+case capacity_partial
+kind negative
+# a finite buffer: a write past capacity is partial, a write on a full pipe is WOULD_BLOCK, never unbounded
+create R W A => OK
+fill W 65000 41 => OK n=65000
+fill W 1000 42 => OK n=536
+write W "x" => WOULD_BLOCK
+check max_resident=65536 would_block=1
+read R 100 => OK n=100
+fill W 200 43 => OK n=100
+write W "x" => WOULD_BLOCK
+check max_resident=65536 would_block=2
+close W => OK
+close R => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p003_zero_length.vec b/native/kernel/tests/fixtures/pipe/p003_zero_length.vec
new file mode 100644
index 00000000 ..f25f11b3
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p003_zero_length.vec
@@ -0,0 +1,12 @@
+case zero_length
+kind negative
+# zero-length read and write move nothing; authority and state are still checked
+create R W A => OK
+write W "" => OK n=0
+read R 0 => OK n=0
+read R 4 => WOULD_BLOCK
+write R "" => DENIED
+close R => OK
+write W "" => BROKEN_PIPE
+close W => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p004_broken_pipe.vec b/native/kernel/tests/fixtures/pipe/p004_broken_pipe.vec
new file mode 100644
index 00000000 ..95f01b7b
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p004_broken_pipe.vec
@@ -0,0 +1,9 @@
+case broken_pipe
+kind negative
+create R W A => OK
+write W "kept" => OK n=4
+close R => OK
+write W "x" => BROKEN_PIPE
+check broken_pipe=1 bytes_written=4 bytes_read=0
+close W => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p005_eof_after_drain.vec b/native/kernel/tests/fixtures/pipe/p005_eof_after_drain.vec
new file mode 100644
index 00000000 ..ef9ff074
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p005_eof_after_drain.vec
@@ -0,0 +1,12 @@
+case eof_after_drain
+kind positive
+create R W A => OK
+write W "abc" => OK n=3
+close W => OK
+read R 2 => OK n=2 data="ab"
+read R 2 => OK n=1 data="c"
+read R 2 => OK n=0
+read R 2 => OK n=0
+check eof=2
+close R => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p006_rights.vec b/native/kernel/tests/fixtures/pipe/p006_rights.vec
new file mode 100644
index 00000000 ..f3f92cc5
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p006_rights.vec
@@ -0,0 +1,23 @@
+case rights
+kind negative
+# a read end cannot write and a write end cannot read; dup attenuates and never widens
+create R W A => OK
+write R "x" => DENIED
+read W 1 => DENIED
+dup R X A w => INVALID_ARG
+dup R X A rm => INVALID_ARG
+dup R RB B r => OK
+dup RB RC B r => DENIED
+dup RB RC A r => DENIED
+revoke RB => DENIED
+cancel W => OK
+dup W WB B wg => OK
+dup WB WC B wd => DENIED
+write WB "q" => INTERRUPTED
+write WB "q" => OK n=1
+read RB 4 => OK n=1 data="q"
+close RB => OK
+close WB => OK
+close R => OK
+close W => OK
+check empty refused=6
diff --git a/native/kernel/tests/fixtures/pipe/p007_handle_reuse.vec b/native/kernel/tests/fixtures/pipe/p007_handle_reuse.vec
new file mode 100644
index 00000000 ..02e46de7
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p007_handle_reuse.vec
@@ -0,0 +1,17 @@
+case handle_reuse
+kind negative
+# a closed handle is stale even after its slot is reused by a new pipe (generation check)
+create R W A => OK
+close R => OK
+close W => OK
+create R2 W2 A => OK
+read R 1 => STALE
+write W "x" => STALE
+close R => STALE
+cancel W => STALE
+revoke W => STALE
+write W2 "ok" => OK n=2
+read R2 8 => OK n=2 data="ok"
+close R2 => OK
+close W2 => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p008_revoke_blocked_read.vec b/native/kernel/tests/fixtures/pipe/p008_revoke_blocked_read.vec
new file mode 100644
index 00000000 ..9021f8fa
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p008_revoke_blocked_read.vec
@@ -0,0 +1,13 @@
+case revoke_blocked_read
+kind negative
+# a reader parked on an empty pipe wakes on revoke and gets REVOKED; nothing flows afterwards
+create R W A => OK
+bread R 4 revoke W => REVOKED
+check revocations=1 waits=1 wakeups=1
+write W "x" => REVOKED
+read R 1 => REVOKED
+dup R X A r => REVOKED
+cancel R => REVOKED
+close R => OK
+close W => OK
+check empty bytes_read=0
diff --git a/native/kernel/tests/fixtures/pipe/p009_revoke_blocked_write.vec b/native/kernel/tests/fixtures/pipe/p009_revoke_blocked_write.vec
new file mode 100644
index 00000000 ..6c580b01
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p009_revoke_blocked_write.vec
@@ -0,0 +1,11 @@
+case revoke_blocked_write
+kind negative
+# a writer parked on a full pipe wakes on revoke; the 64 KiB already buffered is scrubbed, never delivered
+create R W A => OK
+fill W 65536 61 => OK n=65536
+bwrite W "z" revoke R => REVOKED
+check revocations=1 waits=1 wakeups=1 bytes_written=65536
+read R 1 => REVOKED
+close W => OK
+close R => OK
+check empty bytes_read=0
diff --git a/native/kernel/tests/fixtures/pipe/p010_close_reader_race.vec b/native/kernel/tests/fixtures/pipe/p010_close_reader_race.vec
new file mode 100644
index 00000000 ..04e8c68d
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p010_close_reader_race.vec
@@ -0,0 +1,9 @@
+case close_reader_race
+kind negative
+# a writer parked at capacity when the last reader closes wakes to BROKEN_PIPE
+create R W A => OK
+fill W 65536 62 => OK n=65536
+bwrite W "z" close R => BROKEN_PIPE
+check broken_pipe=1 waits=1 wakeups=1
+close W => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p011_close_writer_race.vec b/native/kernel/tests/fixtures/pipe/p011_close_writer_race.vec
new file mode 100644
index 00000000 ..0911f4f6
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p011_close_writer_race.vec
@@ -0,0 +1,8 @@
+case close_writer_race
+kind positive
+# a reader parked on an empty pipe when the last writer closes wakes to EOF (0 bytes, OK)
+create R W A => OK
+bread R 4 close W => OK n=0
+check eof=1 waits=1 wakeups=1
+close R => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p012_both_closed.vec b/native/kernel/tests/fixtures/pipe/p012_both_closed.vec
new file mode 100644
index 00000000 ..775de480
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p012_both_closed.vec
@@ -0,0 +1,11 @@
+case both_closed
+kind negative
+create R W A => OK
+write W "lost" => OK n=4
+close W => OK
+close R => OK
+check empty
+close R => STALE
+close W => STALE
+read R 1 => STALE
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p013_cancel_blocked_read.vec b/native/kernel/tests/fixtures/pipe/p013_cancel_blocked_read.vec
new file mode 100644
index 00000000 ..f6e08cc3
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p013_cancel_blocked_read.vec
@@ -0,0 +1,12 @@
+case cancel_blocked_read
+kind negative
+# cancel interrupts a parked reader once, no byte moved; the next call runs normally
+create R W A => OK
+bread R 4 cancel R => INTERRUPTED
+check cancellations=1 waits=1 wakeups=1
+read R 4 => WOULD_BLOCK
+write W "ok" => OK n=2
+read R 4 => OK n=2 data="ok"
+close W => OK
+close R => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p014_cancel_pending_write.vec b/native/kernel/tests/fixtures/pipe/p014_cancel_pending_write.vec
new file mode 100644
index 00000000 ..533904e3
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p014_cancel_pending_write.vec
@@ -0,0 +1,15 @@
+case cancel_pending_write
+kind negative
+# a cancel with no waiter interrupts the next call on that end only
+create R W A => OK
+cancel W => OK
+read R 1 => WOULD_BLOCK
+write W "x" => INTERRUPTED
+write W "x" => OK n=1
+cancel R => OK
+read R 1 => INTERRUPTED
+read R 1 => OK n=1 data="x"
+check cancellations=2 bytes_read=1
+close R => OK
+close W => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p015_stalled_consumer.vec b/native/kernel/tests/fixtures/pipe/p015_stalled_consumer.vec
new file mode 100644
index 00000000 ..7cb7417d
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p015_stalled_consumer.vec
@@ -0,0 +1,11 @@
+case stalled_consumer
+kind negative
+# a writer parked behind a consumer that never reads gives up INTERRUPTED at the wait bound, no byte moved
+create R W A => OK
+fill W 65536 63 => OK n=65536
+bwrite W "z" none => INTERRUPTED
+check waits=2 would_block=2 cancellations=1 bytes_written=65536
+read R 3 => OK n=3 data="ccc"
+close R => OK
+close W => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p016_blocked_read_progress.vec b/native/kernel/tests/fixtures/pipe/p016_blocked_read_progress.vec
new file mode 100644
index 00000000 ..bef5c901
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p016_blocked_read_progress.vec
@@ -0,0 +1,11 @@
+case blocked_read_progress
+kind positive
+# a parked reader wakes when bytes arrive and returns them (partial: what is there)
+create R W B => OK
+bread R 8 write W "hi\x00" => OK n=3 data="hi\x00"
+check waits=1 wakeups=1
+bwrite W "yo" none => OK n=2
+read R 8 => OK n=2 data="yo"
+close R => OK
+close W => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p017_malformed_frames.vec b/native/kernel/tests/fixtures/pipe/p017_malformed_frames.vec
new file mode 100644
index 00000000 ..6de5e746
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p017_malformed_frames.vec
@@ -0,0 +1,27 @@
+case malformed_frames
+kind negative
+# platform call frames: every malformed header is refused before any effect
+frame A - 4F534846 1 => INVALID_ARG
+frame A - 12345678 1 1 0 => INVALID_ARG
+frame A - 4F534846 2 1 0 => NOT_SUPPORTED
+frame A - 4F534846 0 1 0 => NOT_SUPPORTED
+frame A - 4F534846 1 1 1 => INVALID_ARG
+frame A - 4F534846 1 0 0 => NOT_SUPPORTED
+frame A - 4F534846 1 6 0 => NOT_SUPPORTED
+frame A - 4F534846 1 FFFFFFFF00000001 0 => NOT_SUPPORTED
+frame A - 4F534846 1 1 0 0 => INVALID_ARG
+frame A - 4F534846 1 4 0 0 => INVALID_ARG
+check empty
+create R W A => OK
+frame A - 4F534846 1 3 0 $W => INVALID_ARG
+frame A "abc" 4F534846 1 3 0 $W 2 => INVALID_ARG
+frame A "abc" 4F534846 1 3 0 $W 0 => OK n=3
+frame A - 4F534846 1 5 0 $R 1 2 => INVALID_ARG
+frame A - 4F534846 1 5 0 $R 1 1 => OK
+frame A - 4F534846 1 7 0 $R => NOT_SUPPORTED
+check bytes_written=3 bytes_read=0
+release B => OK n=1
+frame A - 4F534846 1 4 0 $R => OK
+frame A - 4F534846 1 4 0 $R => STALE
+close W => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p018_limits.vec b/native/kernel/tests/fixtures/pipe/p018_limits.vec
new file mode 100644
index 00000000 ..8f328f1d
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p018_limits.vec
@@ -0,0 +1,19 @@
+case limits
+kind negative
+# a full pool or a full capability table returns LIMIT and leaves nothing allocated
+create R1 W1 A => OK
+create R2 W2 A => OK
+create R3 W3 A => OK
+create R4 W4 A => OK
+create X Y B => LIMIT
+check pipes=4
+close R1 => OK
+close W1 => OK
+check pipes=3
+dup R2 D1 A r => OK
+dup R2 D2 A r => OK
+create X Y A => LIMIT
+dup R2 D3 A r => LIMIT
+check pipes=3
+release A => OK n=8
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p019_dup_refs.vec b/native/kernel/tests/fixtures/pipe/p019_dup_refs.vec
new file mode 100644
index 00000000 ..fda38b90
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p019_dup_refs.vec
@@ -0,0 +1,13 @@
+case dup_refs
+kind positive
+# every dup is a reference: EOF only after the last write end closes
+create R W A => OK
+dup W W2 A w => OK
+close W => OK
+write W2 "x" => OK n=1
+read R 4 => OK n=1 data="x"
+read R 4 => WOULD_BLOCK
+close W2 => OK
+read R 4 => OK n=0
+close R => OK
+check empty
diff --git a/native/kernel/tests/fixtures/pipe/p020_transfer.vec b/native/kernel/tests/fixtures/pipe/p020_transfer.vec
new file mode 100644
index 00000000 ..796f2a13
--- /dev/null
+++ b/native/kernel/tests/fixtures/pipe/p020_transfer.vec
@@ -0,0 +1,13 @@
+case transfer
+kind positive
+# an end handed to another principal's table (GRANT) works there; the giver closes its copy
+create R W A => OK
+dup R RB B rv => OK
+close R => OK
+write W "\x00\x01\x02" => OK n=3
+read RB 3 => OK n=3 data="\x00\x01\x02"
+revoke RB => OK
+write W "x" => REVOKED
+close RB => OK
+close W => OK
+check empty revocations=1
diff --git a/native/kernel/tests/test_pipe.c b/native/kernel/tests/test_pipe.c
new file mode 100644
index 00000000 ..3edeabb0
--- /dev/null
+++ b/native/kernel/tests/test_pipe.c
@@ -0,0 +1,1196 @@
+/* test_pipe.c -- host tests for core/pipe.c (aienos-mv#428): the fixture corpus in tests/fixtures/pipe/ (format in its
+ * README.md), then producer / consumer transfers through the scheduler (core/pipe_drive.h), revocation mid-stream,
+ * epoch staleness and the versioned op table, then pthreads (concurrent read/write, close while parked, shared-pool
+ * create/close). Every case ends with both capability tables and the pipe pool empty. */
+#define _GNU_SOURCE
+#include <dirent.h>
+#include <errno.h>
+#include <pthread.h>
+#include <sched.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include "ck_test.h"
+#include "pipe.h"
+#include "pipe_drive.h"
+
+#ifndef PIPE_FIXTURE_DIR
+#define PIPE_FIXTURE_DIR "native/kernel/tests/fixtures/pipe"
+#endif
+
+static struct ck_pipe_pool pool;
+static struct ck_cap_table ta, tb;
+
+static int expect(int ok, const char *file, int line, const char *what)
+{
+ ck_t_run++;
+ if (!ok) {
+ ck_t_fail++;
+ printf(" FAIL %s:%d: %s\n", file, line, what);
+ }
+ return ok;
+}
+
+/* ---- fixture runner ---- */
+#define TOK_MAX 24
+#define BYTES_MAX 256
+struct tok {
+ char s[64];
+ int quoted;
+ uint8_t b[BYTES_MAX];
+ size_t n;
+};
+struct name {
+ char s[16];
+ struct ck_cap_table *t;
+ struct ck_handle h;
+};
+static struct name names[32];
+static unsigned nnames;
+static const char *cur_file;
+static int cur_line;
+
+/* the wait hook's scripted peer: first wait runs the action, every later wait gives up (a stalled peer) */
+static struct tok *act;
+static int nact, wait_calls;
+static unsigned act_err;
+
+static int hexval(int c)
+{
+ return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
+}
+
+static int tokenize(const char *line, struct tok *t, int max)
+{
+ int n = 0;
+ const char *p = line;
+ while (*p) {
+ while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
+ p++;
+ if (!*p || *p == '#')
+ break;
+ if (n == max)
+ return -1;
+ struct tok *k = &t[n++];
+ memset(k, 0, sizeof *k);
+ if (*p == '"') {
+ k->quoted = 1;
+ p++;
+ while (*p && *p != '"') {
+ int c = (unsigned char)*p++;
+ if (c == '\\') {
+ if (*p == 'x' && hexval(p[1]) >= 0 && hexval(p[2]) >= 0) {
+ c = hexval(p[1]) * 16 + hexval(p[2]);
+ p += 3;
+ } else if (*p == '"' || *p == '\\') {
+ c = (unsigned char)*p++;
+ } else {
+ return -1;
+ }
+ }
+ if (k->n == BYTES_MAX)
+ return -1;
+ k->b[k->n++] = (uint8_t)c;
+ }
+ if (*p != '"')
+ return -1;
+ p++;
+ strcpy(k->s, "\"\"");
+ } else {
+ size_t l = 0;
+ while (*p && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r' && *p != '"') {
+ if (l + 1 >= sizeof k->s)
+ return -1;
+ k->s[l++] = *p++;
+ }
+ }
+ }
+ return n;
+}
+
+static struct ck_cap_table *table_of(const char *s)
+{
+ return !strcmp(s, "A") ? &ta : !strcmp(s, "B") ? &tb : 0;
+}
+
+static struct name *find(const char *s)
+{
+ for (unsigned i = 0; i < nnames; i++)
+ if (!strcmp(names[i].s, s))
+ return &names[i];
+ return 0;
+}
+
+static void bind(const char *s, struct ck_cap_table *t, struct ck_handle h)
+{
+ struct name *n = find(s);
+ if (!n && nnames < 32)
+ n = &names[nnames++];
+ if (!n)
+ return;
+ snprintf(n->s, sizeof n->s, "%s", s);
+ n->t = t;
+ n->h = h;
+}
+
+static int parse_err(const char *s)
+{
+ for (unsigned i = 0; i < OSH_E_COUNT; i++)
+ if (!strcmp(s, osh_err_label(i)))
+ return (int)i;
+ return -1;
+}
+
+static int parse_rights(const char *s, unsigned *r)
+{
+ *r = 0;
+ for (; *s; s++) {
+ switch (*s) {
+ case 'r': *r |= CK_R_READ; break;
+ case 'w': *r |= CK_R_WRITE; break;
+ case 'm': *r |= CK_R_MAP; break;
+ case 'g': *r |= CK_R_GRANT; break;
+ case 'd': *r |= CK_R_DERIVE; break;
+ case 'v': *r |= CK_R_REVOKE; break;
+ default: return -1;
+ }
+ }
+ return 0;
+}
+
+static uint8_t big[70000], rbig[70000];
+
+/* Runs one data or control command (also used for the wait hook's action). *n and the read bytes are returned. */
+static int run_cmd(struct tok *c, int nc, unsigned *err, size_t *n, const uint8_t **data, int *handled_bind)
+{
+ *n = 0;
+ *data = 0;
+ *handled_bind = 0;
+ struct name *h = nc > 1 ? find(c[1].s) : 0;
+ if (!strcmp(c[0].s, "write") && nc == 3 && h && c[2].quoted) {
+ *err = ck_stream_write(&pool, h->t, h->h, c[2].b, c[2].n, 0, n);
+ } else if (!strcmp(c[0].s, "fill") && nc == 4 && h) {
+ size_t cnt = strtoul(c[2].s, 0, 10);
+ if (cnt > sizeof big)
+ return -1;
+ memset(big, (int)strtoul(c[3].s, 0, 16), cnt);
+ *err = ck_stream_write(&pool, h->t, h->h, big, cnt, 0, n);
+ } else if (!strcmp(c[0].s, "read") && nc == 3 && h) {
+ size_t max = strtoul(c[2].s, 0, 10);
+ if (max > sizeof rbig)
+ return -1;
+ *err = ck_stream_read(&pool, h->t, h->h, rbig, max, 0, n);
+ *data = rbig;
+ } else if (!strcmp(c[0].s, "close") && nc == 2 && h) {
+ *err = ck_stream_close(&pool, h->t, h->h);
+ } else if (!strcmp(c[0].s, "revoke") && nc == 2 && h) {
+ *err = ck_pipe_revoke(&pool, h->t, h->h);
+ } else if (!strcmp(c[0].s, "cancel") && nc == 2 && h) {
+ *err = ck_pipe_cancel(&pool, h->t, h->h);
+ } else {
+ return -1;
+ }
+ return 0;
+}
+
+static unsigned vec_wait(void *ctx, unsigned pipe, unsigned end)
+{
+ (void)ctx;
+ (void)pipe;
+ (void)end;
+ if (wait_calls++ > 0 || !act)
+ return OSH_E_INTERRUPTED;
+ if (nact == 1 && !strcmp(act[0].s, "none"))
+ return OSH_E_OK;
+ size_t n;
+ const uint8_t *d;
+ int hb;
+ if (run_cmd(act, nact, &act_err, &n, &d, &hb) != 0)
+ act_err = 0xff;
+ return OSH_E_OK;
+}
+static void vec_wake(void *ctx, unsigned pipe, unsigned end)
+{
+ (void)ctx;
+ (void)pipe;
+ (void)end;
+}
+static const struct ck_pipe_hooks vec_hooks = { 0, vec_wait, vec_wake, 0 };
+
+static uint64_t stat_of(const char *k, int *ok)
+{
+ const struct ck_pipe_stats *s = &pool.total;
+ *ok = 1;
+#define S(f) if (!strcmp(k, #f)) return s->f;
+ S(bytes_written) S(bytes_read) S(writes) S(reads) S(max_resident) S(would_block) S(waits) S(wakeups)
+ S(cancellations) S(revocations) S(broken_pipe) S(eof) S(refused)
+#undef S
+ if (!strcmp(k, "pipes"))
+ return pool.live;
+ *ok = 0;
+ return 0;
+}
+
+static int all_empty(void)
+{
+ return pd_table_empty(&ta) && pd_table_empty(&tb) && ck_pipe_pool_empty(&pool);
+}
+
+static void run_line(struct tok *t, int nt)
+{
+ char what[160];
+ if (!strcmp(t[0].s, "case") || !strcmp(t[0].s, "kind"))
+ return;
+ if (!strcmp(t[0].s, "check")) {
+ for (int i = 1; i < nt; i++) {
+ if (!strcmp(t[i].s, "empty")) {
+ expect(all_empty(), cur_file, cur_line, "check empty: tables and pool hold nothing");
+ continue;
+ }
+ char key[64];
+ snprintf(key, sizeof key, "%s", t[i].s);
+ char *eq = strchr(key, '=');
+ int ok = 0;
+ if (eq) {
+ *eq = 0;
+ uint64_t want = strtoull(eq + 1, 0, 10), got = stat_of(key, &ok);
+ snprintf(what, sizeof what, "check %s: want %llu got %llu", key, (unsigned long long)want,
+ (unsigned long long)got);
+ ok = ok && got == want;
+ } else {
+ snprintf(what, sizeof what, "check: bad item %s", t[i].s);
+ }
+ expect(ok, cur_file, cur_line, what);
+ }
+ return;
+ }
+ int arrow = -1;
+ for (int i = 0; i < nt; i++)
+ if (!t[i].quoted && !strcmp(t[i].s, "=>"))
+ arrow = i;
+ if (!expect(arrow > 0 && arrow + 1 < nt, cur_file, cur_line, "line has '<command> => <ERR>'"))
+ return;
+ int want = parse_err(t[arrow + 1].s);
+ if (!expect(want >= 0, cur_file, cur_line, "known error name"))
+ return;
+ long want_n = -1;
+ struct tok *want_data = 0;
+ for (int i = arrow + 2; i < nt; i++) {
+ if (!strncmp(t[i].s, "n=", 2))
+ want_n = strtol(t[i].s + 2, 0, 10);
+ else if (!strcmp(t[i].s, "data=") && i + 1 < nt && t[i + 1].quoted)
+ want_data = &t[++i];
+ else
+ expect(0, cur_file, cur_line, "unknown expectation item");
+ }
+ struct tok *c = t;
+ int nc = arrow;
+ unsigned err = 0xff;
+ size_t n = 0;
+ const uint8_t *data = 0;
+ struct name *h = nc > 1 ? find(c[1].s) : 0;
+ act = 0;
+ nact = 0;
+ wait_calls = 0;
+ act_err = 0;
+ if (!strcmp(c[0].s, "create") && nc == 4 && table_of(c[3].s)) {
+ struct ck_handle r, w;
+ err = ck_pipe_create(&pool, table_of(c[3].s), &r, &w);
+ if (err == OSH_E_OK) {
+ bind(c[1].s, table_of(c[3].s), r);
+ bind(c[2].s, table_of(c[3].s), w);
+ }
+ } else if (!strcmp(c[0].s, "dup") && nc == 5 && h && table_of(c[3].s)) {
+ unsigned rights;
+ struct ck_handle o;
+ if (!expect(parse_rights(c[4].s, &rights) == 0, cur_file, cur_line, "rights letters"))
+ return;
+ err = ck_stream_dup(&pool, h->t, h->h, table_of(c[3].s), rights, &o);
+ if (err == OSH_E_OK)
+ bind(c[2].s, table_of(c[3].s), o);
+ } else if (!strcmp(c[0].s, "release") && nc == 2 && table_of(c[1].s)) {
+ n = ck_pipe_release_table(&pool, table_of(c[1].s));
+ err = OSH_E_OK;
+ } else if ((!strcmp(c[0].s, "bread") || !strcmp(c[0].s, "bwrite")) && nc >= 4 && h) {
+ act = &c[3];
+ nact = nc - 3;
+ if (c[0].s[1] == 'r') {
+ size_t max = strtoul(c[2].s, 0, 10);
+ if (!expect(max <= sizeof rbig, cur_file, cur_line, "read size"))
+ return;
+ err = ck_stream_read(&pool, h->t, h->h, rbig, max, CK_PIPE_F_BLOCK, &n);
+ data = rbig;
+ } else {
+ err = ck_stream_write(&pool, h->t, h->h, c[2].b, c[2].n, CK_PIPE_F_BLOCK, &n);
+ }
+ expect(act_err == OSH_E_OK, cur_file, cur_line, "the wait hook's action succeeded");
+ } else if (!strcmp(c[0].s, "frame") && nc >= 3 && table_of(c[1].s)) {
+ uint64_t cells[16];
+ size_t ncell = 0;
+ for (int i = 3; i < nc && ncell < 16; i++) {
+ if (c[i].s[0] == '$') {
+ struct name *x = find(c[i].s + 1);
+ if (!expect(x != 0, cur_file, cur_line, "frame names a known handle"))
+ return;
+ cells[ncell++] = ck_handle_raw(x->h);
+ } else {
+ cells[ncell++] = strtoull(c[i].s, 0, 16);
+ }
+ }
+ struct ck_pipe_ret ret;
+ struct ck_cap_table *me = table_of(c[1].s);
+ uint8_t slice[BYTES_MAX];
+ size_t sl = 0;
+ if (c[2].quoted) {
+ memcpy(slice, c[2].b, c[2].n);
+ sl = c[2].n;
+ }
+ err = ck_pipe_dispatch(&pool, me, me == &ta ? &tb : &ta, cells, ncell, sl ? slice : 0, sl,
+ (uintptr_t)slice, (uintptr_t)slice + sizeof slice, &ret);
+ expect(ret.error == err, cur_file, cur_line, "frame result carries the error");
+ n = (size_t)ret.value;
+ if (want_n < 0)
+ n = 0;
+ } else {
+ int hb;
+ if (!expect(run_cmd(c, nc, &err, &n, &data, &hb) == 0, cur_file, cur_line, "known command"))
+ return;
+ }
+ snprintf(what, sizeof what, "%s: want %s got %s", c[0].s, osh_err_label((unsigned)want), osh_err_label(err));
+ expect(err == (unsigned)want, cur_file, cur_line, what);
+ if (want_n >= 0) {
+ snprintf(what, sizeof what, "%s: want n=%ld got n=%zu", c[0].s, want_n, n);
+ expect(n == (size_t)want_n, cur_file, cur_line, what);
+ }
+ if (want_data)
+ expect(data && n == want_data->n && !memcmp(data, want_data->b, n), cur_file, cur_line, "data byte for byte");
+}
+
+static int run_file(const char *dir, const char *fname)
+{
+ char path[512], line[1024];
+ snprintf(path, sizeof path, "%s/%s", dir, fname);
+ FILE *f = fopen(path, "r");
+ if (!expect(f != 0, fname, 0, "fixture opens"))
+ return 0;
+ ck_cap_init(&ta, 0x41, CK_CAP_SLOTS);
+ ck_cap_init(&tb, 0x42, CK_CAP_SLOTS);
+ ck_pipe_pool_init(&pool, &vec_hooks);
+ nnames = 0;
+ cur_file = fname;
+ cur_line = 0;
+ int has_case = 0, has_kind = 0, fail_before = ck_t_fail;
+ struct tok t[TOK_MAX];
+ while (fgets(line, sizeof line, f)) {
+ cur_line++;
+ int nt = tokenize(line, t, TOK_MAX);
+ if (!expect(nt >= 0, fname, cur_line, "line tokenizes"))
+ continue;
+ if (nt == 0)
+ continue;
+ has_case |= !strcmp(t[0].s, "case") && nt == 2;
+ has_kind |= !strcmp(t[0].s, "kind") && nt == 2 && (!strcmp(t[1].s, "positive") || !strcmp(t[1].s, "negative"));
+ run_line(t, nt);
+ }
+ fclose(f);
+ expect(has_case && has_kind, fname, cur_line, "fixture names its case and kind");
+ expect(all_empty(), fname, cur_line, "end of case: both tables and the pool are empty");
+ printf(" pipe fixture %s: %s\n", fname, ck_t_fail == fail_before ? "ok" : "FAILED");
+ return 1;
+}
+
+static int cmp_str(const void *a, const void *b)
+{
+ return strcmp(*(char *const *)a, *(char *const *)b);
+}
+
+static void run_fixtures(const char *dir)
+{
+ DIR *d = opendir(dir);
+ if (!expect(d != 0, dir, 0, "fixture directory opens"))
+ return;
+ char *list[128];
+ int n = 0;
+ struct dirent *e;
+ while ((e = readdir(d)) && n < 128) {
+ size_t l = strlen(e->d_name);
+ if (l > 4 && !strcmp(e->d_name + l - 4, ".vec"))
+ list[n++] = strdup(e->d_name);
+ }
+ closedir(d);
+ qsort(list, (size_t)n, sizeof list[0], cmp_str);
+ int ran = 0;
+ for (int i = 0; i < n; i++) {
+ ran += run_file(dir, list[i]);
+ free(list[i]);
+ }
+ CHECK(ran >= 20);
+}
+
+/* ---- transfers through the scheduler ---- */
+static struct pd_world world;
+static uint8_t sink[200000];
+
+static size_t expected_nuls(size_t n)
+{
+ size_t z = 0;
+ for (size_t i = 0; i < n; i++)
+ z += pd_byte(i) == 0;
+ return z;
+}
+
+static void fresh_tables(void)
+{
+ ck_cap_init(&ta, 0x41, CK_CAP_SLOTS);
+ ck_cap_init(&tb, 0x42, CK_CAP_SLOTS);
+}
+
+static void check_full_transfer(const char *label, unsigned flags, size_t cw, size_t cr, unsigned pe, unsigned ce)
+{
+ fresh_tables();
+ memset(sink, 0xaa, sizeof sink);
+ pd_run(&world, &pool, &ta, &tb, sink, sizeof sink, cw, cr, flags, pe, ce, 0);
+ const struct ck_pipe_stats *s = &pool.total;
+ printf(" transfer %s: sent=%zu recvd=%zu nul=%zu would_block=%llu waits=%llu wakeups=%llu max_resident=%llu "
+ "prod_steps=%llu cons_steps=%llu ticks=%llu\n",
+ label, world.sent, world.recvd, pd_nul_count(&world), (unsigned long long)s->would_block,
+ (unsigned long long)s->waits, (unsigned long long)s->wakeups, (unsigned long long)s->max_resident,
+ (unsigned long long)world.prod_steps, (unsigned long long)world.cons_steps,
+ (unsigned long long)world.ticks);
+ CHECK(world.setup_err == OSH_E_OK);
+ CHECK(world.prod_err == OSH_E_OK && world.cons_err == OSH_E_OK);
+ CHECK(world.tasks[0].done && world.tasks[1].done);
+ CHECK(world.sent == sizeof sink && world.recvd == sizeof sink);
+ CHECK(pd_mismatches(&world) == 0); /* byte for byte */
+ CHECK(pd_nul_count(&world) == expected_nuls(sizeof sink)); /* NUL bytes included */
+ CHECK(pd_nul_count(&world) >= sizeof sink / 5);
+ CHECK(world.eof_seen && s->eof == 1); /* last writer closed -> EOF */
+ CHECK(s->bytes_written == sizeof sink && s->bytes_read == sizeof sink);
+ CHECK(s->max_resident <= CK_PIPE_CAPACITY); /* bounded memory */
+ CHECK(s->cancellations == 0 && s->broken_pipe == 0 && s->revocations == 0);
+ CHECK(world.prod_steps > 1 && world.cons_steps > 1); /* real interleaving */
+ CHECK(all_empty());
+}
+
+static void test_transfers(void)
+{
+ /* slow consumer, non-blocking: the producer sees WOULD_BLOCK and the buffer reaches capacity */
+ check_full_transfer("slow-consumer-nonblocking", 0, 8192, 1000, 1, 4);
+ CHECK(pool.total.would_block > 0);
+ CHECK(pool.total.max_resident == CK_PIPE_CAPACITY);
+ CHECK(pool.total.waits == 0);
+ /* slow consumer, blocking: the producer parks and the consumer's reads wake it */
+ check_full_transfer("slow-consumer-blocking", CK_PIPE_F_BLOCK, 8192, 1000, 1, 4);
+ CHECK(pool.total.waits > 0 && pool.total.wakeups > 0);
+ CHECK(pool.total.max_resident == CK_PIPE_CAPACITY);
+ /* slow producer, blocking: the consumer parks on an empty pipe and the producer's writes wake it */
+ check_full_transfer("slow-producer-blocking", CK_PIPE_F_BLOCK, 1000, 8192, 4, 1);
+ CHECK(pool.total.waits > 0 && pool.total.wakeups > 0);
+ CHECK(pool.total.max_resident < CK_PIPE_CAPACITY);
+}
+
+static void test_revoke_midstream(unsigned flags)
+{
+ fresh_tables();
+ memset(sink, 0xaa, sizeof sink);
+ pd_run(&world, &pool, &ta, &tb, sink, sizeof sink, 8192, 1000, flags, 1, 4, 50000);
+ const struct ck_pipe_stats *s = &pool.total;
+ printf(" revoke mid-stream (%s): recvd=%zu sent=%zu reads_after_revoke=%zu prod_err=%s cons_err=%s\n",
+ flags ? "blocking" : "nonblocking", world.recvd, world.sent, world.reads_after_revoke,
+ osh_err_label(world.prod_err), osh_err_label(world.cons_err));
+ CHECK(world.setup_err == OSH_E_OK);
+ CHECK(world.revoked);
+ CHECK(world.reads_after_revoke == 0); /* no data emitted after revocation */
+ CHECK(world.recvd >= 50000 && world.recvd < 50000 + 1000);
+ CHECK(s->bytes_read == world.recvd);
+ CHECK(world.cons_err == OSH_E_REVOKED && world.prod_err == OSH_E_REVOKED);
+ CHECK(world.sent < sizeof sink);
+ CHECK(pd_mismatches(&world) == 0);
+ CHECK(s->revocations == 1 && s->eof == 0);
+ CHECK(world.tasks[0].done && world.tasks[1].done);
+ CHECK(all_empty());
+}
+
+static void test_epoch_and_forgery(void)
+{
+ fresh_tables();
+ ck_pipe_pool_init(&pool, 0);
+ struct ck_handle r, w, f, g;
+ size_t n = 0;
+ uint8_t b[4] = { 1, 2, 3, 4 };
+ CHECK(ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK);
+ uint32_t epoch = pool.pipes[0].epoch;
+ CHECK(epoch == 1);
+ /* a capability naming another incarnation of the same slot is STALE (section 4.4), and close still releases it */
+ CHECK(ck_cap_insert(&ta, ck_pipe_resource(0, CK_PIPE_END_WRITE, epoch + 1), CK_R_WRITE, &f) == CK_CAP_OK);
+ CHECK(ck_stream_write(&pool, &ta, f, b, 4, 0, &n) == OSH_E_STALE && n == 0);
+ CHECK(ck_stream_close(&pool, &ta, f) == OSH_E_STALE);
+ CHECK(ck_cap_lookup(&ta, f, 0, 0) == CK_CAP_INVALID);
+ CHECK(pool.pipes[0].writer_refs == 1); /* the live pipe's count is untouched */
+ /* a capability on something that is not a stream is DENIED and not closed here */
+ CHECK(ck_cap_insert(&ta, CK_IPC_OBJECT_RESOURCE, CK_R_WRITE, &g) == CK_CAP_OK);
+ CHECK(ck_stream_write(&pool, &ta, g, b, 4, 0, &n) == OSH_E_DENIED);
+ CHECK(ck_stream_close(&pool, &ta, g) == OSH_E_DENIED);
+ CHECK(ck_cap_remove(&ta, g) == CK_CAP_OK);
+ /* no wait hook: a blocking read on an empty pipe returns WOULD_BLOCK */
+ CHECK(ck_stream_read(&pool, &ta, r, b, 4, CK_PIPE_F_BLOCK, &n) == OSH_E_WOULD_BLOCK);
+ CHECK(ck_stream_read(&pool, &ta, r, b, 4, 0x80, &n) == OSH_E_INVALID_ARG);
+ CHECK(ck_stream_close(&pool, &ta, r) == OSH_E_OK && ck_stream_close(&pool, &ta, w) == OSH_E_OK);
+ CHECK(all_empty());
+ /* a slot whose epoch reached the maximum is retired; with every slot retired create is LIMIT */
+ for (unsigned i = 0; i < CK_PIPE_POOL_PIPES; i++)
+ pool.pipes[i].epoch = CK_PIPE_EPOCH_MAX - 1;
+ CHECK(ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK && pool.pipes[0].epoch == CK_PIPE_EPOCH_MAX);
+ CHECK(ck_pipe_release_table(&pool, &ta) == 2);
+ for (unsigned i = 1; i < CK_PIPE_POOL_PIPES; i++)
+ pool.pipes[i].epoch = CK_PIPE_EPOCH_MAX;
+ CHECK(ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_LIMIT);
+ CHECK(all_empty());
+}
+
+/* The slice is the whole window, so a length that fits the buffer passes the range check. A length of 0 does not
+ * consult the window. */
+static unsigned dispatch_owned(struct ck_cap_table *caller, struct ck_cap_table *peer, const uint64_t *frame,
+ size_t ncells, uint8_t *slice, size_t slice_len, struct ck_pipe_ret *ret)
+{
+ uintptr_t lo = (uintptr_t)slice;
+ uintptr_t hi = lo + slice_len;
+ return ck_pipe_dispatch(&pool, caller, peer, frame, ncells, slice_len ? slice : 0, slice_len, lo, hi, ret);
+}
+
+static void test_dispatch(void)
+{
+ fresh_tables();
+ ck_pipe_pool_init(&pool, 0);
+ struct ck_pipe_ret ret;
+ uint64_t create[4] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_CREATE, 0 };
+ CHECK(dispatch_owned(&ta, &tb, create, 4, 0, 0, &ret) == OSH_E_OK && ret.error == OSH_E_OK);
+ uint64_t rd = ret.value, wr = ret.value2;
+ CHECK(rd != 0 && wr != 0 && rd != wr);
+ uint8_t msg[5] = { 'p', 0, 'i', 0, 'p' }, got[8];
+ uint64_t wf[6] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_WRITE, 0, wr, 0 };
+ CHECK(dispatch_owned(&ta, &tb, wf, 6, msg, 5, &ret) == OSH_E_OK && ret.value == 5);
+ uint64_t dup[7] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_DUP, 0, rd, CK_R_READ, 1 };
+ CHECK(dispatch_owned(&ta, &tb, dup, 7, 0, 0, &ret) == OSH_E_OK);
+ uint64_t rb = ret.value;
+ uint64_t rf[6] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_READ, 0, rb, 0 };
+ /* the dup lives in the peer table: from the caller's table the same raw handle is not ours */
+ CHECK(dispatch_owned(&tb, &ta, rf, 6, got, 8, &ret) == OSH_E_OK && ret.value == 5 && !memcmp(got, msg, 5));
+ /* the read end in the peer table cannot write */
+ uint64_t wb[6] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_WRITE, 0, rb, 0 };
+ CHECK(dispatch_owned(&tb, &ta, wb, 6, msg, 5, &ret) == OSH_E_DENIED && ret.value == 0);
+ uint64_t cl[5] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_CLOSE, 0, 0 };
+ cl[4] = rd;
+ CHECK(dispatch_owned(&ta, &tb, cl, 5, 0, 0, &ret) == OSH_E_OK);
+ cl[4] = wr;
+ CHECK(dispatch_owned(&ta, &tb, cl, 5, 0, 0, &ret) == OSH_E_OK);
+ cl[4] = rb;
+ CHECK(dispatch_owned(&tb, &ta, cl, 5, 0, 0, &ret) == OSH_E_OK);
+ CHECK(all_empty());
+ CHECK(dispatch_owned(&ta, &tb, 0, 0, 0, 0, &ret) == OSH_E_INVALID_ARG);
+}
+
+/* A close that fails must not add to the release count. The forged cap is removed (STALE) and still not counted.
+ * A pipe-tagged index outside the pool is DENIED, left in the table, and not counted. */
+static void test_release_count(void)
+{
+ fresh_tables();
+ ck_pipe_pool_init(&pool, 0);
+ struct ck_handle r, w, forged, outside;
+ CHECK(ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK);
+ uint32_t epoch = pool.pipes[0].epoch;
+ CHECK(ck_cap_insert(&ta, ck_pipe_resource(0, CK_PIPE_END_READ, epoch + 1), CK_R_READ, &forged) == CK_CAP_OK);
+ CHECK(ck_cap_insert(&ta, ck_pipe_resource(7, CK_PIPE_END_WRITE, 1), CK_R_WRITE, &outside) == CK_CAP_OK);
+ CHECK(ck_pipe_release_table(&pool, &ta) == 2);
+ CHECK(ck_cap_lookup(&ta, forged, 0, 0) == CK_CAP_INVALID);
+ CHECK(ck_cap_lookup(&ta, outside, 0, 0) == CK_CAP_OK);
+ CHECK(ck_cap_remove(&ta, outside) == CK_CAP_OK);
+ CHECK(all_empty());
+}
+
+/* Blocking write must commit the bytes it snapshotted, not a buffer the peer rewrote while the writer was parked. */
+static uint8_t toctou_src[4] = { 1, 2, 3, 4 };
+static struct ck_handle toctou_src_rd;
+
+static unsigned toctou_wait(void *ctx, unsigned pipe, unsigned end)
+{
+ (void)ctx;
+ (void)pipe;
+ (void)end;
+ memset(toctou_src, 0xA5, sizeof toctou_src);
+ uint8_t dump[4];
+ size_t n = 0;
+ unsigned e = ck_stream_read(&pool, &ta, toctou_src_rd, dump, 4, 0, &n);
+ if (e != OSH_E_OK || n != 4)
+ return OSH_E_IO;
+ return OSH_E_OK;
+}
+
+static void toctou_wake(void *ctx, unsigned pipe, unsigned end)
+{
+ (void)ctx;
+ (void)pipe;
+ (void)end;
+}
+
+static void test_toctou_snapshot(void)
+{
+ fresh_tables();
+ static const struct ck_pipe_hooks hooks = { 0, toctou_wait, toctou_wake, 0 };
+ ck_pipe_pool_init(&pool, &hooks);
+ struct ck_handle r, w;
+ size_t n = 0;
+ CHECK(ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK);
+ toctou_src_rd = r;
+ memset(big, 0x11, CK_PIPE_CAPACITY);
+ CHECK(ck_stream_write(&pool, &ta, w, big, CK_PIPE_CAPACITY, 0, &n) == OSH_E_OK && n == CK_PIPE_CAPACITY);
+ toctou_src[0] = 1;
+ toctou_src[1] = 2;
+ toctou_src[2] = 3;
+ toctou_src[3] = 4;
+ CHECK(ck_stream_write(&pool, &ta, w, toctou_src, 4, CK_PIPE_F_BLOCK, &n) == OSH_E_OK && n == 4);
+ CHECK(toctou_src[0] == 0xA5 && toctou_src[3] == 0xA5);
+ int bad = 0;
+ for (size_t got = 0; got < CK_PIPE_CAPACITY;) {
+ uint8_t b[64];
+ size_t want = CK_PIPE_CAPACITY - got;
+ if (want > sizeof b)
+ want = sizeof b;
+ size_t rn = 0;
+ if (ck_stream_read(&pool, &ta, r, b, want, 0, &rn) != OSH_E_OK || rn != want) {
+ bad = 1;
+ break;
+ }
+ for (size_t i = 0; i < rn; i++) {
+ uint8_t expect = (got + i) < CK_PIPE_CAPACITY - 4 ? 0x11 : (uint8_t)(got + i - (CK_PIPE_CAPACITY - 4) + 1);
+ if (b[i] != expect)
+ bad = 1;
+ }
+ got += rn;
+ }
+ CHECK(!bad);
+ CHECK(ck_stream_close(&pool, &ta, r) == OSH_E_OK && ck_stream_close(&pool, &ta, w) == OSH_E_OK);
+ CHECK(all_empty());
+}
+
+/* Host threads. The wait hook is a counting semaphore: a wake that lands before wait runs is still observed. */
+struct host_sync {
+ pthread_mutex_t mu;
+ pthread_cond_t cv;
+ unsigned pending[CK_PIPE_POOL_PIPES][2];
+ int in_window, peer_done, use_window, timed_out;
+};
+
+static struct host_sync host;
+
+static void on_alarm(int sig)
+{
+ (void)sig;
+ const char msg[] = "test_pipe: timeout (lock or wakeup)\n";
+ ssize_t wr = write(STDERR_FILENO, msg, sizeof msg - 1);
+ (void)wr;
+ _Exit(1);
+}
+
+static void host_lock(void)
+{
+ pthread_mutex_lock(&host.mu);
+}
+
+static void host_unlock(void)
+{
+ pthread_mutex_unlock(&host.mu);
+}
+
+static int wait_pred(int *pred)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_REALTIME, &ts);
+ ts.tv_sec += 3;
+ while (!*pred) {
+ if (pthread_cond_timedwait(&host.cv, &host.mu, &ts) == ETIMEDOUT)
+ return -1;
+ }
+ return 0;
+}
+
+static void host_before(void *ctx)
+{
+ struct host_sync *s = ctx;
+ if (!s->use_window)
+ return;
+ host_lock();
+ s->in_window = 1;
+ pthread_cond_broadcast(&s->cv);
+ int bad = wait_pred(&s->peer_done);
+ if (bad)
+ s->timed_out = 1;
+ host_unlock();
+}
+
+static unsigned host_wait(void *ctx, unsigned pipe, unsigned end)
+{
+ struct host_sync *s = ctx;
+ host_lock();
+ if (!s->use_window) {
+ s->in_window = 1;
+ pthread_cond_broadcast(&s->cv);
+ }
+ struct timespec ts;
+ clock_gettime(CLOCK_REALTIME, &ts);
+ ts.tv_sec += 3;
+ while (s->pending[pipe][end] == 0) {
+ if (pthread_cond_timedwait(&s->cv, &s->mu, &ts) == ETIMEDOUT) {
+ s->timed_out = 1;
+ host_unlock();
+ return OSH_E_INTERRUPTED;
+ }
+ }
+ s->pending[pipe][end]--;
+ host_unlock();
+ return OSH_E_OK;
+}
+
+static void host_wake(void *ctx, unsigned pipe, unsigned end)
+{
+ struct host_sync *s = ctx;
+ host_lock();
+ s->pending[pipe][end]++;
+ pthread_cond_broadcast(&s->cv);
+ host_unlock();
+}
+
+static void host_reset(int window)
+{
+ host_lock();
+ memset(host.pending, 0, sizeof host.pending);
+ host.in_window = host.peer_done = host.timed_out = 0;
+ host.use_window = window;
+ host_unlock();
+}
+
+static int wait_window(void)
+{
+ host_lock();
+ int bad = wait_pred(&host.in_window);
+ host_unlock();
+ return bad;
+}
+
+static void mark_peer(void)
+{
+ host_lock();
+ host.peer_done = 1;
+ pthread_cond_broadcast(&host.cv);
+ host_unlock();
+}
+
+struct xfer {
+ struct ck_cap_table *table;
+ struct ck_handle h;
+ size_t total, chunk, moved, bad;
+ unsigned err;
+ int reader;
+};
+
+static void *xfer_thread(void *arg)
+{
+ struct xfer *x = arg;
+ size_t off = 0;
+ while (off < x->total) {
+ size_t want = x->total - off;
+ if (want > x->chunk)
+ want = x->chunk;
+ uint8_t tmp[1024];
+ size_t n = 0;
+ unsigned e;
+ if (x->reader) {
+ e = ck_stream_read(&pool, x->table, x->h, tmp, want, CK_PIPE_F_BLOCK, &n);
+ if (e != OSH_E_OK || n == 0) {
+ x->err = e == OSH_E_OK ? 0xffu : e;
+ return 0;
+ }
+ for (size_t i = 0; i < n; i++)
+ x->bad += tmp[i] != pd_byte(off + i);
+ } else {
+ for (size_t i = 0; i < want; i++)
+ tmp[i] = pd_byte(off + i);
+ e = ck_stream_write(&pool, x->table, x->h, tmp, want, CK_PIPE_F_BLOCK, &n);
+ if (e != OSH_E_OK || n == 0) {
+ x->err = e == OSH_E_OK ? 0xffu : e;
+ return 0;
+ }
+ }
+ off += n;
+ }
+ x->moved = off;
+ if (x->reader) {
+ size_t n = 0;
+ uint8_t b;
+ unsigned e = ck_stream_read(&pool, x->table, x->h, &b, 1, CK_PIPE_F_BLOCK, &n);
+ if (e != OSH_E_OK || n != 0)
+ x->err = e == OSH_E_OK ? 0xffu : e;
+ ck_stream_close(&pool, x->table, x->h);
+ } else {
+ unsigned e = ck_stream_close(&pool, x->table, x->h);
+ if (e != OSH_E_OK)
+ x->err = e;
+ }
+ return 0;
+}
+
+static void *nb_thread(void *arg)
+{
+ struct xfer *x = arg;
+ size_t off = 0;
+ while (off < x->total) {
+ size_t want = x->total - off;
+ if (want > x->chunk)
+ want = x->chunk;
+ uint8_t tmp[256];
+ size_t n = 0;
+ unsigned e;
+ if (x->reader) {
+ e = ck_stream_read(&pool, x->table, x->h, tmp, want, 0, &n);
+ if (e == OSH_E_WOULD_BLOCK) {
+ sched_yield();
+ continue;
+ }
+ if (e != OSH_E_OK || n == 0) {
+ x->err = e == OSH_E_OK ? 0xffu : e;
+ return 0;
+ }
+ for (size_t i = 0; i < n; i++)
+ x->bad += tmp[i] != pd_byte(off + i);
+ } else {
+ for (size_t i = 0; i < want; i++)
+ tmp[i] = pd_byte(off + i);
+ e = ck_stream_write(&pool, x->table, x->h, tmp, want, 0, &n);
+ if (e == OSH_E_WOULD_BLOCK) {
+ sched_yield();
+ continue;
+ }
+ if (e != OSH_E_OK || n == 0) {
+ x->err = e == OSH_E_OK ? 0xffu : e;
+ return 0;
+ }
+ }
+ off += n;
+ }
+ x->moved = off;
+ if (!x->reader) {
+ unsigned e = ck_stream_close(&pool, x->table, x->h);
+ if (e != OSH_E_OK)
+ x->err = e;
+ } else {
+ for (;;) {
+ uint8_t b;
+ size_t n = 0;
+ unsigned e = ck_stream_read(&pool, x->table, x->h, &b, 1, 0, &n);
+ if (e == OSH_E_WOULD_BLOCK) {
+ sched_yield();
+ continue;
+ }
+ if (e != OSH_E_OK || n != 0)
+ x->err = e == OSH_E_OK ? 0xffu : e;
+ break;
+ }
+ ck_stream_close(&pool, x->table, x->h);
+ }
+ return 0;
+}
+
+struct pair_job {
+ struct ck_cap_table *table;
+ unsigned err;
+ int n;
+};
+
+static void *pair_thread(void *arg)
+{
+ struct pair_job *j = arg;
+ for (int i = 0; i < j->n; i++) {
+ struct ck_handle r, w;
+ unsigned e = ck_pipe_create(&pool, j->table, &r, &w);
+ if (e != OSH_E_OK) {
+ j->err = e;
+ return 0;
+ }
+ uint8_t b[8], out[8];
+ for (int k = 0; k < 8; k++)
+ b[k] = (uint8_t)(i + k);
+ size_t n = 0;
+ e = ck_stream_write(&pool, j->table, w, b, 8, 0, &n);
+ if (e != OSH_E_OK || n != 8) {
+ j->err = e == OSH_E_OK ? 0xffu : e;
+ return 0;
+ }
+ e = ck_stream_read(&pool, j->table, r, out, 8, 0, &n);
+ if (e != OSH_E_OK || n != 8 || memcmp(out, b, 8) != 0) {
+ j->err = e == OSH_E_OK ? 0xffu : e;
+ return 0;
+ }
+ if (ck_stream_close(&pool, j->table, r) != OSH_E_OK || ck_stream_close(&pool, j->table, w) != OSH_E_OK) {
+ j->err = OSH_E_IO;
+ return 0;
+ }
+ }
+ return 0;
+}
+
+struct one_call {
+ struct ck_cap_table *table;
+ struct ck_handle h;
+ int is_write;
+ unsigned err;
+ size_t n;
+ uint8_t buf[4];
+};
+
+static void *one_call_thread(void *arg)
+{
+ struct one_call *c = arg;
+ if (c->is_write)
+ c->err = ck_stream_write(&pool, c->table, c->h, c->buf, 4, CK_PIPE_F_BLOCK, &c->n);
+ else
+ c->err = ck_stream_read(&pool, c->table, c->h, c->buf, 4, CK_PIPE_F_BLOCK, &c->n);
+ return 0;
+}
+
+static void join_one(pthread_t th, struct one_call *c, unsigned want, size_t want_n)
+{
+ pthread_join(th, 0);
+ CHECK(c->err == want);
+ CHECK(c->n == want_n);
+ CHECK(!host.timed_out);
+}
+
+static void test_close_park(int window, int break_writer)
+{
+ fresh_tables();
+ host_reset(window);
+ struct ck_pipe_hooks hooks = { &host, host_wait, host_wake, host_before };
+ ck_pipe_pool_init(&pool, &hooks);
+ struct ck_handle r, w;
+ CHECK(ck_pipe_create(&pool, &ta, &r, &w) == OSH_E_OK);
+ struct one_call call;
+ memset(&call, 0, sizeof call);
+ pthread_t th;
+ if (break_writer) {
+ size_t n = 0;
+ memset(big, 0x22, CK_PIPE_CAPACITY);
+ CHECK(ck_stream_write(&pool, &ta, w, big, CK_PIPE_CAPACITY, 0, &n) == OSH_E_OK && n == CK_PIPE_CAPACITY);
+ call.table = &ta;
+ call.h = w;
+ call.is_write = 1;
+ call.buf[0] = call.buf[1] = call.buf[2] = call.buf[3] = 9;
+ CHECK(pthread_create(&th, 0, one_call_thread, &call) == 0);
+ CHECK(wait_window() == 0);
+ CHECK(ck_stream_close(&pool, &ta, r) == OSH_E_OK);
+ if (window)
+ mark_peer();
+ join_one(th, &call, OSH_E_BROKEN_PIPE, 0);
+ CHECK(pool.total.bytes_written == CK_PIPE_CAPACITY);
+ CHECK(ck_stream_close(&pool, &ta, w) == OSH_E_OK);
+ } else {
+ call.table = &ta;
+ call.h = r;
+ CHECK(pthread_create(&th, 0, one_call_thread, &call) == 0);
+ CHECK(wait_window() == 0);
+ CHECK(ck_stream_close(&pool, &ta, w) == OSH_E_OK);
+ if (window)
+ mark_peer();
+ join_one(th, &call, OSH_E_OK, 0);
+ CHECK(pool.total.eof == 1);
+ CHECK(ck_stream_close(&pool, &ta, r) == OSH_E_OK);
+ }
+ CHECK(all_empty());
+}
+
+static void test_concurrent(void)
+{
+ signal(SIGALRM, on_alarm);
+ alarm(60);
+ static const struct ck_pipe_hooks hooks = { &host, host_wait, host_wake, host_before };
+ const size_t total = 128u * 1024u;
+ for (int iter = 0; iter < 4; iter++) {
+ fresh_tables();
+ host_reset(0);
+ ck_pipe_pool_init(&pool, &hooks);
+ struct ck_handle r0, w, r;
+ CHECK(ck_pipe_create(&pool, &ta, &r0, &w) == OSH_E_OK);
+ CHECK(ck_stream_dup(&pool, &ta, r0, &tb, CK_R_READ, &r) == OSH_E_OK);
+ CHECK(ck_stream_close(&pool, &ta, r0) == OSH_E_OK);
+ struct xfer wr = { .table = &ta, .h = w, .total = total, .chunk = 1000 };
+ struct xfer rd = { .table = &tb, .h = r, .total = total, .chunk = 700, .reader = 1 };
+ pthread_t tw, tr;
+ CHECK(pthread_create(&tw, 0, xfer_thread, &wr) == 0);
+ CHECK(pthread_create(&tr, 0, xfer_thread, &rd) == 0);
+ pthread_join(tw, 0);
+ pthread_join(tr, 0);
+ CHECK(wr.err == 0 && rd.err == 0);
+ CHECK(wr.moved == total && rd.moved == total && rd.bad == 0);
+ CHECK(!host.timed_out);
+ CHECK(all_empty());
+ }
+ fresh_tables();
+ ck_pipe_pool_init(&pool, 0);
+ struct ck_handle r0, w, r;
+ CHECK(ck_pipe_create(&pool, &ta, &r0, &w) == OSH_E_OK);
+ CHECK(ck_stream_dup(&pool, &ta, r0, &tb, CK_R_READ, &r) == OSH_E_OK);
+ CHECK(ck_stream_close(&pool, &ta, r0) == OSH_E_OK);
+ struct xfer wr = { .table = &ta, .h = w, .total = total, .chunk = 256 };
+ struct xfer rd = { .table = &tb, .h = r, .total = total, .chunk = 128, .reader = 1 };
+ pthread_t tw, tr;
+ CHECK(pthread_create(&tw, 0, nb_thread, &wr) == 0);
+ CHECK(pthread_create(&tr, 0, nb_thread, &rd) == 0);
+ pthread_join(tw, 0);
+ pthread_join(tr, 0);
+ CHECK(wr.err == 0 && rd.err == 0);
+ CHECK(wr.moved == total && rd.moved == total && rd.bad == 0);
+ CHECK(all_empty());
+
+ test_close_park(1, 0);
+ test_close_park(1, 1);
+ test_close_park(0, 0);
+ test_close_park(0, 1);
+
+ fresh_tables();
+ ck_pipe_pool_init(&pool, 0);
+ struct pair_job ja = { .table = &ta, .n = 80 };
+ struct pair_job jb = { .table = &tb, .n = 80 };
+ CHECK(pthread_create(&tw, 0, pair_thread, &ja) == 0);
+ CHECK(pthread_create(&tr, 0, pair_thread, &jb) == 0);
+ pthread_join(tw, 0);
+ pthread_join(tr, 0);
+ CHECK(ja.err == 0 && jb.err == 0);
+ CHECK(all_empty());
+ alarm(0);
+}
+
+/* Above the user-VA top named in pipe.h: ARM64 TTBR1 is 0xFFFF000000000000, and this is the x86 canonical high half. */
+#define SLICE_KERNEL_HALF ((uintptr_t)0xFFFF800000000000ULL)
+
+static sigjmp_buf slice_jmp;
+
+static void slice_fault(int sig)
+{
+ (void)sig;
+ siglongjmp(slice_jmp, 1);
+}
+
+static unsigned frame_rw(int is_write, uint64_t raw, uint8_t *slice, size_t len, uintptr_t lo, uintptr_t hi,
+ struct ck_pipe_ret *ret)
+{
+ uint64_t fr[6] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, is_write ? CK_PIPE_OP_WRITE : CK_PIPE_OP_READ, 0, raw,
+ 0 };
+ return ck_pipe_dispatch(&pool, &ta, &tb, fr, 6, slice, len, lo, hi, ret);
+}
+
+/* A rejected slice must not move a byte. A fault means the check did not run before the copy; the ticket lock
+ * would still be held, so stop rather than deadlock the next op. */
+static void slice_reject(int is_write, uint64_t raw, void *slice, size_t len, uintptr_t lo, uintptr_t hi,
+ uint32_t plen, uint64_t bw, uint64_t br)
+{
+ struct ck_pipe_ret ret;
+ if (sigsetjmp(slice_jmp, 1) != 0) {
+ CHECK(0 && "slice faulted; the range check did not reject it");
+ ck_t_verdict("test_pipe");
+ fflush(stdout);
+ _Exit(1);
+ }
+ unsigned err = frame_rw(is_write, raw, slice, len, lo, hi, &ret);
+ CHECK(err == OSH_E_INVALID_ARG && ret.error == OSH_E_INVALID_ARG && ret.value == 0);
+ CHECK(pool.pipes[0].len == plen && pool.total.bytes_written == bw && pool.total.bytes_read == br);
+}
+
+static void test_slice_window(void)
+{
+ fresh_tables();
+ ck_pipe_pool_init(&pool, 0);
+ struct sigaction sa, old_segv, old_bus;
+ memset(&sa, 0, sizeof sa);
+ sa.sa_handler = slice_fault;
+ sigemptyset(&sa.sa_mask);
+ CHECK(sigaction(SIGSEGV, &sa, &old_segv) == 0);
+ CHECK(sigaction(SIGBUS, &sa, &old_bus) == 0);
+
+ struct ck_pipe_ret ret;
+ uint64_t create[4] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_CREATE, 0 };
+ CHECK(ck_pipe_dispatch(&pool, &ta, &tb, create, 4, 0, 0, 0, 0, &ret) == OSH_E_OK);
+ uint64_t rd = ret.value, wr = ret.value2;
+ CHECK(pool.pipes[0].flags & CK_PIPE_LIVE);
+
+ /* The declared window is mem[16, 32). The allocation is larger, so a slice past hi is still mapped. */
+ uint8_t mem[64];
+ memset(mem, 0x5A, sizeof mem);
+ uintptr_t lo = (uintptr_t)(mem + 16);
+ uintptr_t hi = lo + 16;
+ memcpy(mem + 16, "abcd", 4);
+ CHECK(frame_rw(1, wr, mem + 16, 4, lo, hi, &ret) == OSH_E_OK && ret.value == 4);
+ uint32_t plen = pool.pipes[0].len;
+ uint64_t bw = pool.total.bytes_written, br = pool.total.bytes_read;
+ CHECK(plen == 4 && bw == 4 && br == 0);
+
+ /* len 0 passes, including a pointer that must not be dereferenced. */
+ CHECK(frame_rw(0, rd, 0, 0, lo, hi, &ret) == OSH_E_OK && ret.value == 0);
+ CHECK(frame_rw(0, rd, (uint8_t *)(UINTPTR_MAX - 3), 0, lo, hi, &ret) == OSH_E_OK && ret.value == 0);
+ CHECK(frame_rw(1, wr, (uint8_t *)SLICE_KERNEL_HALF, 0, lo, hi, &ret) == OSH_E_OK && ret.value == 0);
+ CHECK(pool.pipes[0].len == plen && pool.total.bytes_written == bw && pool.total.bytes_read == br);
+
+ /* Outside the window, still inside the allocation. */
+ slice_reject(1, wr, mem, 4, lo, hi, plen, bw, br);
+ slice_reject(1, wr, mem + 40, 4, lo, hi, plen, bw, br);
+ /* One byte before lo, and the exclusive end. */
+ slice_reject(1, wr, (void *)(lo - 1), 1, lo, hi, plen, bw, br);
+ slice_reject(1, wr, (void *)hi, 1, lo, hi, plen, bw, br);
+ /* Starts on the last byte of the window and runs past hi. */
+ slice_reject(1, wr, (void *)(hi - 1), 2, lo, hi, plen, bw, br);
+ /* base == lo and len == hi - lo + 1. */
+ slice_reject(1, wr, (void *)lo, 17, lo, hi, plen, bw, br);
+ /* slice + len wraps the address space. */
+ slice_reject(1, wr, (void *)(UINTPTR_MAX - 3), 8, lo, hi, plen, bw, br);
+ /* Kernel half. */
+ slice_reject(1, wr, (void *)SLICE_KERNEL_HALF, 4, lo, hi, plen, bw, br);
+
+ /* Boundaries that are inside: lo, the last byte, and a length that lands exactly on hi. */
+ uint8_t got[4];
+ CHECK(frame_rw(0, rd, got, 4, (uintptr_t)got, (uintptr_t)got + sizeof got, &ret) == OSH_E_OK && ret.value == 4);
+ CHECK(!memcmp(got, "abcd", 4));
+ mem[31] = 'Z';
+ CHECK(frame_rw(1, wr, (uint8_t *)(hi - 1), 1, lo, hi, &ret) == OSH_E_OK && ret.value == 1);
+ CHECK(frame_rw(1, wr, (uint8_t *)lo, 16, lo, hi, &ret) == OSH_E_OK && ret.value == 16);
+ CHECK(pool.pipes[0].len == 1 + 16);
+
+ uint64_t cl[5] = { CK_PIPE_FRAME_MAGIC, CK_PIPE_ABI_VERSION, CK_PIPE_OP_CLOSE, 0, rd };
+ CHECK(ck_pipe_dispatch(&pool, &ta, &tb, cl, 5, 0, 0, 0, 0, &ret) == OSH_E_OK);
+ cl[4] = wr;
+ CHECK(ck_pipe_dispatch(&pool, &ta, &tb, cl, 5, 0, 0, 0, 0, &ret) == OSH_E_OK);
+ CHECK(all_empty());
+ CHECK(sigaction(SIGSEGV, &old_segv, 0) == 0);
+ CHECK(sigaction(SIGBUS, &old_bus, 0) == 0);
+}
+
+int main(int argc, char **argv)
+{
+ _Static_assert(CK_PIPE_CAPACITY >= 65536u, "section 8.5 minimum");
+ CHECK(osh_err_label(OSH_E_WOULD_BLOCK)[0] == 'W' && !strcmp(osh_err_label(99), "IO"));
+ run_fixtures(argc > 1 ? argv[1] : PIPE_FIXTURE_DIR);
+ test_transfers();
+ test_revoke_midstream(0);
+ test_revoke_midstream(CK_PIPE_F_BLOCK);
+ test_epoch_and_forgery();
+ test_dispatch();
+ test_slice_window();
+ test_release_count();
+ test_toctou_snapshot();
+ CHECK(pthread_mutex_init(&host.mu, 0) == 0);
+ CHECK(pthread_cond_init(&host.cv, 0) == 0);
+ test_concurrent();
+ pthread_cond_destroy(&host.cv);
+ pthread_mutex_destroy(&host.mu);
+ return ck_t_verdict("test_pipe");
+}
diff --git a/scripts/.crumb b/scripts/.crumb
index 49ecf9f6 ..cda77dcf 100644
--- a/scripts/.crumb
+++ b/scripts/.crumb
@@ -7,14 +7,14 @@
"generated": {
"children": [],
"children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "compiled_at": "2026-10-30T13:17:50Z",
+ "compiled_at": "2026-10-30T22:01:00Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:2dffaed43899cb00c03694e7e840f7fd844898f3a155797eee43a17f397c8af5 ",
+ "digest": "sha256:da2a96be8a25fde997c2d63599b68c250193223946f25c812a27c6794890f83a ",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "files": 125,
- "generated_at_commit": "3e157636411b2e360023ed02fe8b00f3fb1eb3ab ",
- "source_tree": "sha256:23bdd38fdff4372416b91a9231898663760450e57d193eb13aeb3fac2abcd620 "
+ "files": 126,
+ "generated_at_commit": "aa5c72433acdaf6ab773fa698b1840dce2aa6159 ",
+ "source_tree": "sha256:7a5241f248371b770ad3236d66db360a80bfac983e488c35a6e98063b31b1e3f "
},
"owner_lane": "",
"provenance": {
diff --git a/scripts/qemu_ck_pipe_test.sh b/scripts/qemu_ck_pipe_test.sh
new file mode 100755
index 00000000 ..17f3cb1e
--- /dev/null
+++ b/scripts/qemu_ck_pipe_test.sh
@@ -0,0 +1,108 @@
+#!/usr/bin/env bash
+# AIENOS_CK_PIPE gate (AIENOS-NATIVE-PIPE-1, aienos-mv#428): the native pipe primitive (native/kernel/core/pipe.c) driven
+# from inside the C kernel. A TEST-ONLY image (make CK_PIPE_TEST=1, refused with CK_HARDWARE_STAGING) runs
+# core/pipe_test.c after "kernel: alive": a producer and a consumer task, step functions interleaved by the kernel's
+# run-queue scheduler, each holding one pipe end in its own capability table, then the negative cases. The boot then
+# goes on as usual to its report and PSCI reset.
+#
+# Label: QEMU (aarch64 virt), TEST build, not physical. Nothing here ran on a Spark or any real machine; a PASS
+# qualifies nothing physical.
+# Checks (one boot):
+# payload_nul_byte_for_byte 160 KiB with every fifth byte NUL arrives byte for byte, no temporary file
+# backpressure_would_block a slow consumer fills the 64 KiB pipe; the producer sees WOULD_BLOCK
+# eof_after_last_writer the consumer reads EOF (0 bytes, OK) after the producer closes
+# bounded_memory never more than the pipe capacity buffered
+# blocking_wait_wake_through_scheduler the blocking variant parks and is woken through the scheduler
+# broken_pipe_no_reader write with no reader -> BROKEN_PIPE, no bytes
+# revoked_write_refused_no_bytes_after write after revoke -> REVOKED, nothing delivered after it
+# revoke_midstream_no_data_after the consumer revokes mid-transfer; no read succeeds afterwards
+# stale_handle_after_close a closed handle stays STALE after its slot is reused
+# unknown_op_not_supported unknown op / other ABI version -> NOT_SUPPORTED before any effect
+# cancel_interrupts_once cancel -> INTERRUPTED once with no byte moved
+# every check: both capability tables and the pipe pool empty afterwards (tables_empty=1).
+# Last line: AIENOS_CK_PIPE: PASS|FAIL|NOT_RUN.
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "${repo_root}"
+verdict=AIENOS_CK_PIPE
+code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}"
+vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}"
+command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; echo "${verdict}: NOT_RUN"; exit 2; }
+[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "${verdict}: NOT_RUN"; exit 2; }
+
+cross=""
+if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi
+commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
+out="${AIENOS_CK_OUT_PIPE:-${repo_root}/target/native-kernel-test-pipe}"
+make -s -C native/kernel CROSS="${cross}" OUT="${out}" AIENOS_COMMIT="${commit}" CK_PIPE_TEST=1 >/dev/null
+
+# Machine quiet flag (read only) and the QEMU gate lock (one gate at a time):
+# scripts/lib_gate_hold.sh (aienos#278).
+. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib_gate_hold.sh"
+if ! gh_quiet_check || ! gh_lock_take qemu_ck_pipe_test "${AIENOS_GATE_MINUTES:-60}"; then
+ echo "NOT_RUN ${gh_why}"
+ echo "${verdict}: NOT_RUN"
+ exit 3
+fi
+# Release only this run's own gate lock record, at most once.
+release_flag() { gh_lock_release; }
+work="$(mktemp -d)"
+cleanup() { rm -rf "${work}"; release_flag; }
+trap cleanup EXIT
+mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS"
+touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT"
+cp "${out}/BOOTAA64.EFI" "${work}/esp/EFI/BOOT/BOOTAA64.EFI"
+cp "${vars_fd}" "${work}/vars.fd"
+log="${work}/serial.log"
+
+started=$(date +%s)
+set +e
+timeout "${AIENOS_QEMU_TIMEOUT:-300}" qemu-system-aarch64 \
+ -M virt,virtualization=on,gic-version=3 -accel tcg,thread=single -cpu max -smp 4 -m 2048 \
+ -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \
+ -drive if=pflash,format=raw,file="${work}/vars.fd" \
+ -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \
+ -device virtio-blk-pci,drive=esp \
+ -device ramfb -display none -nic none \
+ -serial file:"${log}" -no-reboot
+qemu_status=$?
+set -e
+elapsed=$(( $(date +%s) - started ))
+release_flag
+
+serial="${work}/serial.txt"
+tr -d '\r' <"${log}" >"${serial}"
+[[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${serial}" "${AIENOS_LOG_DIR}/qemu_ck_pipe_serial.log"
+failed=0
+pass() { echo "PASS $1"; }
+fail() { echo "FAIL $1"; failed=1; }
+has() { grep -qE -- "$2" "$1"; }
+check() { if has "${serial}" "$2"; then pass "$1"; else fail "$1"; fi; }
+echo "qemu exit ${qemu_status} after ${elapsed} s (commit ${commit:0:12})"
+[[ "${qemu_status}" == 0 ]] && pass "QEMU exit status 0 (PSCI reset)" || fail "QEMU exit status ${qemu_status} (124 = timeout)"
+
+label='QEMU \(aarch64 virt\), TEST build, not physical'
+check "left firmware and entered the kernel" "kernel: alive"
+check "the image announces the TEST-ONLY pipe self-test" "^pipe_test: TEST-ONLY pipe self-test begin abi_version=1 capacity=65536 pool_pipes=4 payload=163840; ${label}\$"
+for c in payload_nul_byte_for_byte backpressure_would_block eof_after_last_writer bounded_memory \
+ blocking_wait_wake_through_scheduler broken_pipe_no_reader revoked_write_refused_no_bytes_after \
+ revoke_midstream_no_data_after stale_handle_after_close unknown_op_not_supported cancel_interrupts_once; do
+ check "${c}" "^pipe_check: name=${c} result=PASS tables_empty=1; ${label}\$"
+done
+check "payload detail: all 163840 bytes, NUL bytes counted, zero mismatches" "^pipe_detail: nonblocking bytes=163840 sent=163840 nul=[1-9][0-9]* expected_nul=[1-9][0-9]* mismatches=0 would_block=[1-9]"
+check "blocking detail: waits and wakeups observed" "^pipe_detail: blocking bytes=163840 .* waits=[1-9][0-9]* wakeups=[1-9]"
+check "revoked write refused, zero bytes delivered" "^pipe_detail: revoked write=REVOKED n=0 read=REVOKED n=0 bytes_delivered=0\$"
+check "broken pipe detail" "^pipe_detail: broken_pipe write_after_reader_close=BROKEN_PIPE n=0\$"
+check "self-test summary: 11 checks, 0 failed" "^pipe_test: done checks=11 failed=0 capacity=65536 pool_pipes=4; ${label}\$"
+if has "${serial}" "^pipe_check: .* result=FAIL"; then fail "no pipe check failed"; else pass "no pipe check failed"; fi
+check "the boot went on to its report" "report_kind: final"
+if has "${serial}" "report_kind: (panic|fault)"; then fail "panic or fault reported"; else pass "no kernel panic or fault report"; fi
+
+if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then
+ echo "---- serial console (pipe lines) ----"
+ grep -E "^(pipe_|kernel: alive|report_kind|panic)" "${serial}" || true
+fi
+[[ "${failed}" == 0 ]] && { echo "${verdict}: PASS"; exit 0; }
+echo "${verdict}: FAIL"
+exit 1