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= 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: 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 +#include +#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= result=PASS|FAIL
;