diff --git a/docs/TRUST-1-M5-GATE-MATRIX.md b/docs/TRUST-1-M5-GATE-MATRIX.md index ab95b21a..117fe2e8 100644 --- a/docs/TRUST-1-M5-GATE-MATRIX.md +++ b/docs/TRUST-1-M5-GATE-MATRIX.md @@ -32,7 +32,7 @@ Implementation language at the base snapshot: Rust (`crates/aienos-crypto`, `crates/aienos-kernel/src/crypto/envelope.rs`, `crates/aienos-kernel/src/security.rs`). Under the no-Rust rule these are the reference to port, not the target. C ports landed 2026-10-01: `native/crypto` (#183) and `native/m5` (#186), host-tested only. -The C sealed Store (`native/store/store_sealed.c`, lane 11) wires `native/m5` into the C twin of the Store engine over `native/disk`, host file-backed only (receipt `evidence/trust1_m5_qualification_6fd36c3012ad792862e6098492ae78d7b091c5fada8af73c7c60e6a8f544a650.json`, gates `store_native_c`, `store_rust_crosscheck` and `m5_store_encrypted_objects`). The `m5_store_encrypted_objects` PASS is a host software gate only; it is not the production Store row, which stays MISSING_IMPLEMENTATION. The sealed C Store is QEMU-tested in the C kernel: `native/kernel/svc/store_boot.c` opens it (TEST keys, keyed M5 + anchor) in the C kernel boot path on QEMU virtual NVMe, 512 B and 4096 B namespaces, through the QEMU-only unsafe DMA bypass build (receipt `evidence/trust1_m5_qualification_3358bc2585f0982e1dfbcd0f5ed2fe077847332591782edff8974f0da9caeded.json`, gates `ck_m1_boot_qemu`, `ck_store_kernel_qemu`, `ck_argus1_revoke_qemu`; also `evidence/ck_gates_7a8b4dac2f2ff3ab37154fdd94e2f4894425090bdf95728f4e546aad14866548.json`). Physical: NOT_RUN. The SMMU-confined NVMe mode is NOT_RUN. Gate `m5_store_kernel_binding` stays MISSING_IMPLEMENTATION: it asks for the binding on a real device, which QEMU cannot show. The Rust kernel Store has no M5 wiring. Summary: `TRUST1_M5_QUALIFICATION: NOT_QUALIFIED (pass=20 fail=0 not_run=1 blocked=11 missing=5)` with QEMU suites on (`store_rust_crosscheck` NOT_RUN: Rust store tool not built in that worktree). +The C sealed Store (`native/store/store_sealed.c`, lane 11) wires `native/m5` into the C twin of the Store engine over `native/disk`, host file-backed only (receipt `evidence/trust1_m5_qualification_6fd36c3012ad792862e6098492ae78d7b091c5fada8af73c7c60e6a8f544a650.json`, gates `store_native_c`, `store_rust_crosscheck` and `m5_store_encrypted_objects`). The `m5_store_encrypted_objects` PASS is a host software gate only; it is not the production Store row, which stays MISSING_IMPLEMENTATION. The sealed C Store is QEMU-tested in the C kernel: `native/kernel/svc/store_boot.c` opens it (TEST keys, keyed M5 + anchor) in the C kernel boot path on QEMU virtual NVMe, 512 B and 4096 B namespaces, through the QEMU-only unsafe DMA bypass build (receipt `evidence/trust1_m5_qualification_3358bc2585f0982e1dfbcd0f5ed2fe077847332591782edff8974f0da9caeded.json`, gates `ck_m1_boot_qemu`, `ck_store_kernel_qemu`, `ck_argus1_revoke_qemu`; also `evidence/ck_gates_7a8b4dac2f2ff3ab37154fdd94e2f4894425090bdf95728f4e546aad14866548.json`). Physical: NOT_RUN. The SMMU-confined NVMe mode has since passed in QEMU only (`evidence/ck_gates_23482745517ec1967d2667b24d2a1cd9eafb27cdd91bdb91be7712a3a2968812.json`, gates `SMMU`, `M4_NVME`, `M4_STORE`); physical NOT_RUN. Gate `m5_store_kernel_binding` stays MISSING_IMPLEMENTATION: it asks for the binding on a real device, which QEMU cannot show. The Rust kernel Store has no M5 wiring. Summary: `TRUST1_M5_QUALIFICATION: NOT_QUALIFIED (pass=20 fail=0 not_run=1 blocked=11 missing=5)` with QEMU suites on (`store_rust_crosscheck` NOT_RUN: Rust store tool not built in that worktree). | Requirement | Implementation on main | Evidence on main | Hardware / operator | Verdict | Remaining blocker | |---|---|---|---|---|---| diff --git a/evidence/ck_gates_d414b074fc687e1dd90229653d1b681d60b6ea7f94aca75caa0f8cfc27fc53e0.json b/evidence/ck_gates_d414b074fc687e1dd90229653d1b681d60b6ea7f94aca75caa0f8cfc27fc53e0.json new file mode 100644 index 00000000..616b853d --- /dev/null +++ b/evidence/ck_gates_d414b074fc687e1dd90229653d1b681d60b6ea7f94aca75caa0f8cfc27fc53e0.json @@ -0,0 +1,39 @@ +{ + "schema": "aienos.ck_gates.v1", + "started_utc": "2026-10-01T09:51:18Z", + "finished_utc": "2026-10-01T09:52:50Z", + "commit": "5b88e78c8c2afed444c65381da9d41100cce0b81", + "commit_subject": "ck m3: review fixes (stack guard floor on cooperative switch, contain only the expected EL0 fault)", + "tree_clean_before": true, + "tree_clean_after": true, + "quiet_flag": "/tmp/lane25.quiet", + "quiet_flag_present_at_start": false, + "host": {"hostname": "spark-b87b", "arch": "aarch64", "kernel": "7.0.0-1019-nvidia", "cpu_model": "Cortex-A725;Cortex-X925"}, + "qemu": {"binary": "/usr/bin/qemu-system-aarch64", "version": "QEMU emulator version 8.2.2 (Debian 1:8.2.2+ds-0ubuntu1.18)"}, + "firmware": {"aavmf_code": "/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd", "aavmf_code_sha256": "4a4cb7f6d8106bb2a7dd8c763fab14b1810152136fc4304e5b728f0043e84f12", "aavmf_vars": "/usr/share/AAVMF/AAVMF_VARS.fd", "aavmf_vars_sha256": "b3b855c5a80310168051164986855692d1bdb06e67619856177965cd87c6774f"}, + "nvme_dma_mode": "Confined (QEMU SMMUv3 stage 1, out-of-window DMA faulted); no-SMMU boot denied (NoSmmu); TEST-ONLY bypass image checked separately", + "children": [ + {"name": "boot", "script": "scripts/qemu_ck_boot_test.sh", "present": true, "script_sha256": "64bcb2d1285485b989dc8309ce0b024ea799d3bce13cff22f62924d3ae4b7cce", "exit": "0", "seconds": 6, "log_sha256": "3a8a357354209af1f8e8309ecde4fda88ac778f65bdfedf83de2c15bfbce235f", "log_lines": 22}, + {"name": "store", "script": "scripts/qemu_ck_store_test.sh", "present": true, "script_sha256": "b005ed29619d1113536a0686cedafe84fcea95fa30321307ec1d1335ea231925", "exit": "0", "seconds": 85, "log_sha256": "de460b35155097c442599e7cd62cc66e74dabfc4c14403d56819ea5c46c3f71a", "log_lines": 533} + ], + "gates": [ + {"id": "M1", "marker": "AIENOS_CK_M1", "source": "boot", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M3", "marker": "AIENOS_CK_M3", "source": "boot", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "SMMU", "marker": "AIENOS_CK_SMMU", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "NVME_SHUTDOWN", "marker": "AIENOS_CK_NVME_SHUTDOWN", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "P2_ARTIFACT", "marker": "AIENOS_CK_P2_ARTIFACT", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no signed artifact loader (EL0, W^X, admission receipts) in the C kernel"}, + {"id": "M0_ROLLBACK", "marker": "AIENOS_CK_M0_ROLLBACK", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: C loader signatures, A/B, BootNext and rollback are parked (native/boot/README.md)"}, + {"id": "M4_NVME", "marker": "AIENOS_CK_M4_NVME", "source": "store", "verdict": "PASS", "reason": "SMMU-confined NVMe DMA in QEMU (iommu=smmuv3, default build); TEST-ONLY bypass build boot-checked separately"}, + {"id": "M4_STORE", "marker": "AIENOS_CK_M4_STORE", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M4_STORE_CRASH", "marker": "AIENOS_CK_M4_STORE_CRASH", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no C Store crash/kill campaign (4 KiB or 512 B) and no slot reuse (C Store is append-only)"}, + {"id": "M4_CONTINUITY", "marker": "AIENOS_CK_M4_CONTINUITY", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no continuity core (ADR 0016 agent identity and memory) in the C kernel"}, + {"id": "M4_RECOVERY", "marker": "AIENOS_CK_M4_RECOVERY", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no Recovery Core (ADR 0006) in the C kernel"}, + {"id": "ARGUS1_REVOKE", "marker": "AIENOS_CK_ARGUS1_REVOKE", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "KEYBOARD", "marker": "AIENOS_CK_KEYBOARD", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no xHCI/USB HID keyboard driver in the C kernel"} + ], + "counts": {"total": 13, "pass": 7, "fail": 0, "not_run": 6}, + "verdict": "NOT_ALL_GATES_PASS", + "parity": "native/kernel/GATES.md", + "physical": "NOT_RUN", + "physical_statement": "QEMU emulator runs only. Nothing here was run on Machine 1 or any GB10; no physical qualification is claimed." +} diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 9a49808b..3e40e909 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -17,11 +17,11 @@ Status vocabulary: - **NOT_RUN**: no C implementation exists (MISSING_IMPLEMENTATION, reason given). `ck_gates.sh` prints NOT_RUN for these; never PASS. -C gates (one line each from `ck_gates.sh`): `M1` (from +C gates (one line each from `ck_gates.sh`): `M1` and `M3` (from `scripts/qemu_ck_boot_test.sh`), `M4_NVME`, `M4_STORE`, `ARGUS1_REVOKE` `SMMU`, `NVME_SHUTDOWN` (from `scripts/qemu_ck_store_test.sh`; rows 21-24b, 47-72, 76 and 96-101 were checked against its exact grep patterns), and the NOT_RUN gates -`M3`, `P2_ARTIFACT`, `M0_ROLLBACK`, `M4_STORE_CRASH`, +`P2_ARTIFACT`, `M0_ROLLBACK`, `M4_STORE_CRASH`, `M4_CONTINUITY`, `M4_RECOVERY`, `KEYBOARD`. `M4_NVME` and `SMMU` PASS in the SMMU-confined mode (default `make full` @@ -53,18 +53,37 @@ builds with make instead of cargo and takes the machine quiet flag itself. | 14 | (none in Rust) guard pages fault and are contained (`guard_page: ok fault=contained`) | M1 | DIFFERS (added check, C only; stricter) | | 15 | final verdict line `QEMU_BOOT: PASS` | M1 | DIFFERS (`AIENOS_CK_M1: PASS`; quiet flag held -> `AIENOS_CK_M1: NOT_RUN`, exit 3) | -## M3: scripts/qemu_boot_test.sh M3 lines -> CK `M3` +## M3: scripts/qemu_boot_test.sh M3 lines -> CK `M3` (scripts/qemu_ck_boot_test.sh) | # | Rust check (pattern) | CK gate | Status | | --- | --- | --- | --- | -| 16 | cooperative threads (`threads: ok`) | M3 | NOT_RUN (MISSING_IMPLEMENTATION: no threads/scheduler in the C kernel) | -| 17 | EL0 isolation (`el0: ok write=granted forged=denied fault=contained exit=0`) | M3 | NOT_RUN (MISSING_IMPLEMENTATION: no EL0 tasks) | -| 18 | timer preemption (`preempt: ok`) | M3 | NOT_RUN (MISSING_IMPLEMENTATION: no preemptive scheduler) | -| 19 | MADT placement (`placement: worker0=class0/core0 worker1=class0/core1`) | M3 | NOT_RUN (MISSING_IMPLEMENTATION: only the boot CPU is brought up) | -| 20 | typed IPC (`ipc: ok message=delivered cap=delegated rights=attenuated forged=denied revoked=denied`) | M3 | NOT_RUN (MISSING_IMPLEMENTATION: no IPC; the stage `caps:` line mirrors the capability semantics in-kernel but is not IPC) | - -`qemu_ck_boot_test.sh` prints these five as `NOT_RUN` and they do not count -toward `AIENOS_CK_M1`. +| 16 | cooperative threads (`threads: ok`) | M3 | IDENTICAL | +| 17 | EL0 isolation (`el0: ok write=granted forged=denied fault=contained exit=0`) | M3 | IDENTICAL | +| 18 | timer preemption (`preempt: ok`) | M3 | IDENTICAL | +| 19 | MADT placement (`placement: worker0=class0/core0 worker1=class0/core1`) | M3 | IDENTICAL (same pattern; like the Rust kernel this is computed from the MADT GICC entries and no secondary core is started) | +| 20 | typed IPC (`ipc: ok message=delivered cap=delegated rights=attenuated forged=denied revoked=denied`) | M3 | IDENTICAL | + +`scripts/lib_ck_m1_checks.sh` (`ck_m3_checks`) greps the same five patterns +as `qemu_boot_test.sh` lines 63-67 on the same boot. `AIENOS_CK_M3` is PASS +only if all five pass and every M1 check of that boot passes (no fault or +panic, QEMU exit 0); the quiet flag held prints `AIENOS_CK_M3: NOT_RUN`. +The C code is `native/kernel/core/m3.c`, `core/sched.c`, `core/ipc.c`, +`arch/m3.S` (ports of the Rust thread.rs, scheduler.rs, ipc.rs, caps.rs, +user.rs and acpi.rs placement). How the C kernel does the work differs, not +the observable: + +- one extra line `ipc_detail: exit_a=.. exit_b0=.. exit_b1=.. child=.. revoke=..` + that no check reads; +- the return from EL0 to the kernel uses SPSR 0x3c5 (EL1h, DAIF masked; Rust 0x5) + and every EL0 entry zeroes x0-x30, TPIDR_EL0 and TPIDRRO_EL0 (the Rust + kernel enters EL0 with kernel register values); every exception return + zeroes TPIDRRO_EL0; +- the EL0 window uses ASID 0 and a full `tlbi vmalle1` on each TTBR0 swap + (Rust: ASID 1); the code page is EL0 read-only and PXN, the stack page EL0 + read-write, PXN and UXN; +- threads and preempt workers save x19-x30 and sp only (the kernel is built + without FP/SIMD); EL0 runs with CPACR FPEN=01 so EL0 FP/SIMD traps to the + kernel and is contained, never saved. ## SMMU: scripts/qemu_smmu_test.sh (= keyboard test, SMMU on, bypass forced off) -> CK `SMMU` @@ -105,7 +124,7 @@ per-stream page tables, `ck_dma_confine` / `ck_dma_unconfine` / | # | Rust check (pattern) | CK gate | Status | | --- | --- | --- | --- | -| 33 | common: kernel alive + M3 threads/el0/ipc proofs unchanged | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION: no artifact loader; M3 also missing) | +| 33 | common: kernel alive + M3 threads/el0/ipc proofs unchanged | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION: no artifact loader) | | 34 | firmware read all candidates (`^artifact_candidates: N$`), report not truncated, final report | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | | 35 | frames reclaimed (`artifact_frames_free_before` == `_after`) | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | | 36 | qualification build labelled TEST ONLY, receipt tier line | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | @@ -244,7 +263,7 @@ complete. ## Summary counts -Rows 1-101: IDENTICAL 15, DIFFERS 25, NOT_RUN 61 (rows 92-95 have no CK gate at all; rows 96-101 are C-only). Rows 13, 24, 47-72, 76 and 96-101 were re-verified against scripts/qemu_ck_store_test.sh and scripts/lib_ck_m1_checks.sh at the commit that adds this line. +Rows 1-101: IDENTICAL 20, DIFFERS 25, NOT_RUN 56 (rows 92-95 have no CK gate at all; rows 96-101 are C-only). Rows 13, 24, 47-72, 76 and 96-101 were re-verified against scripts/qemu_ck_store_test.sh and scripts/lib_ck_m1_checks.sh at the commit that adds this line. `scripts/trust1_m5_qualify.sh --with-qemu` also runs three of these gates as qemu rows: `ck_m1_boot_qemu` (M1), `ck_store_kernel_qemu` (M4_STORE) and diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 5b3fc75b..5a38765c 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -75,9 +75,10 @@ CORE_C := $(BOOT)/efi_main.c \ $(KDIR)/arch/exception.c $(KDIR)/arch/gic.c $(KDIR)/arch/timer.c \ $(KDIR)/core/acpi.c $(KDIR)/core/console.c $(KDIR)/core/fmt.c \ $(KDIR)/core/kmain.c $(KDIR)/core/libc_min.c $(KDIR)/core/report.c \ - $(KDIR)/core/smmu.c $(KDIR)/core/smmu_svc.c \ + $(KDIR)/core/smmu.c $(KDIR)/core/smmu_svc.c $(KDIR)/core/sched.c $(KDIR)/core/ipc.c \ + $(KDIR)/core/m3.c \ $(KDIR)/mm/frames.c $(KDIR)/mm/heap.c $(KDIR)/mm/mmu.c $(KDIR)/mm/pt.c -CORE_S := $(BOOT)/efi_entry.S $(KDIR)/arch/vectors.S +CORE_S := $(BOOT)/efi_entry.S $(KDIR)/arch/vectors.S $(KDIR)/arch/m3.S HDRS := $(wildcard $(KDIR)/include/*.h $(KDIR)/*/*.h $(BOOT)/*.h) KOBJ := $(OUT)/obj @@ -175,8 +176,8 @@ $(FULL_EFI): $(FULL_ELF) # ---- host unit tests ---- HOST_SRCS := $(KDIR)/core/fmt.c $(KDIR)/core/acpi.c $(KDIR)/core/smmu.c $(KDIR)/mm/frames.c \ - $(KDIR)/mm/pt.c $(KDIR)/mm/heap.c -TESTS := test_fmt test_frames test_pt test_acpi test_heap test_smmu + $(KDIR)/mm/pt.c $(KDIR)/mm/heap.c $(KDIR)/core/sched.c $(KDIR)/core/ipc.c +TESTS := test_fmt test_frames test_pt test_acpi test_heap test_smmu test_sched test_ipc HCFLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -I$(KDIR)/core -I$(KDIR)/mm -I$(KDIR)/tests SANFLAGS := -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer diff --git a/native/kernel/README.md b/native/kernel/README.md index c069f91d..c6690391 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -11,7 +11,7 @@ QEMU qualifies nothing physical: a PASS here says nothing about real hardware. | `include/ck.h` | Frozen contract for stage code (devices, security, store). Lane 18 core added only `ck_irq_register`, `ck_irq_enable`, `ck_irq_cpu_enable`. | | `arch/` | Vectors, EL2 -> EL1h entry (ADR 0009), recoverable probe, exception and IRQ dispatch, GICv3, EL1 physical timer. | | `mm/` | Frame allocator (UEFI map), 4 KiB-granule page-table builder, heap, the kernel address space (`mmu.c`). | -| `core/` | Console, printf, ACPI, reports/panic/PSCI reset, `kmain.c`. | +| `core/` | Console, printf, ACPI, reports/panic/PSCI reset, M3 (threads, scheduler, EL0, capabilities, IPC), `kmain.c`. | | `tests/` | Host unit tests. | | `../boot/` | Minimal UEFI entry stub (one image with the kernel). | @@ -108,6 +108,13 @@ low-water free bytes. - `guard_page: ok fault=contained` is an addition: the C kernel proves its guard pages fault and that the fault is handled. The Rust kernel has no such test. -- M3 features (threads, EL0, preemption, placement, IPC) are not implemented - yet; the QEMU script reports them as NOT_RUN. +- M3 (threads, EL0, preemption, placement, IPC) runs in the core before the + stages (`core/m3.c`, `core/sched.c`, `core/ipc.c`, `arch/m3.S`; host tests + `tests/test_sched.c`, `tests/test_ipc.c`) and prints the same five lines as + the Rust kernel, plus an extra `ipc_detail:` line. Differences in how: + the EL0 return uses SPSR 0x3c5 (Rust 0x5); EL0 entry zeroes all general + registers and TPIDR_EL0/TPIDRRO_EL0; the EL0 window uses ASID 0 with a + full TLB flush (Rust ASID 1); context switches save x19-x30 and sp only + (no FP/SIMD; EL0 FP/SIMD traps). Placement is computed from the MADT; no + secondary core is started (same as Rust). See GATES.md rows 16-20. - MAIR adds a Normal Non-cacheable attribute (index 2) for the DMA pool. diff --git a/native/kernel/arch/exception.c b/native/kernel/arch/exception.c index eb3c89cd..6a562f51 100644 --- a/native/kernel/arch/exception.c +++ b/native/kernel/arch/exception.c @@ -1,5 +1,6 @@ /* exception.c -- synchronous exceptions, FIQ/SError, and the IRQ dispatcher. - * Any exception other than an armed probe or an IRQ is fatal: it prints + * Any exception other than an armed probe, an IRQ or an M3 EL0 task's + * syscall/contained fault (core/m3.c) is fatal: it prints * "report_kind: fault" with ESR/FAR/ELR and resets. */ #include "arch.h" #include "ck_internal.h" @@ -7,7 +8,13 @@ struct ck_probe ck_probe_state; void ck_exception(struct ck_frame *f, uint64_t vector); -void ck_irq_dispatch(struct ck_frame *f); +struct ck_frame *ck_irq_dispatch(struct ck_frame *f); + +/* M3 hooks (core/m3.c), set only while its checks run. ck_tick_switch may + * return another frame to resume (timer preemption); ck_lower_sync handles + * a synchronous exception from an M3 EL0 task (0) or declines it (-1). */ +struct ck_frame *(*ck_tick_switch)(struct ck_frame *f); +int (*ck_lower_sync)(struct ck_frame *f, uint64_t esr); void ck_el2_fatal(uint64_t vector); static const char *const vec_names[16] = { @@ -23,6 +30,9 @@ void ck_exception(struct ck_frame *f, uint64_t vector) unsigned el = ck_current_el(); uint64_t esr = ck_rd(esr_el1), far = ck_rd(far_el1), elr = f->elr; uint64_t ec = (esr >> 26) & 0x3f; + /* sync_lower64: an EL0 task of the M3 checks (syscall or contained fault). */ + if (vector == 8 && ck_lower_sync && ck_lower_sync(f, esr) == 0) + return; /* Armed probe: a data abort at the probing load on the current EL. */ if (el == 1 && vector == 4 && ec == 0x25 && ck_probe_state.fixup && elr == ck_probe_state.insn) { @@ -62,13 +72,12 @@ int ck_irq_register(uint32_t intid, void (*fn)(void *arg), void *arg) static uint64_t spurious, unhandled; -void ck_irq_dispatch(struct ck_frame *f) +struct ck_frame *ck_irq_dispatch(struct ck_frame *f) { - (void)f; uint32_t id = (uint32_t)ck_rd_s(ICC_IAR1_EL1) & 0xffffff; if (id >= 1020) { spurious++; - return; + return f; } if (id == 30) ck_timer_tick(); /* re-arms before EOI */ @@ -78,6 +87,9 @@ void ck_irq_dispatch(struct ck_frame *f) unhandled++; ck_wr_s(ICC_EOIR1_EL1, id); ck_isb(); + if (id == 30 && ck_tick_switch) + return ck_tick_switch(f); + return f; } void ck_irq_cpu_enable(int on) diff --git a/native/kernel/arch/m3.S b/native/kernel/arch/m3.S new file mode 100644 index 00000000..8d0c15b8 --- /dev/null +++ b/native/kernel/arch/m3.S @@ -0,0 +1,239 @@ +/* m3.S -- M3 isolation primitives for core/m3.c (port of the global_asm in + * crates/aienos-kernel/src/thread.rs and user.rs): + * ck_ctx_switch cooperative switch of x19-x30 and sp + * ck_thread_start first frame of a cooperative thread + * ck_el0_enter eret to EL0 with every general register chosen + * ck_el0_resume kernel landing point after an EL0 task exits + * ck_el0_demo_* position-independent EL0 program of the el0 check + * ck_ipc_prog_* position-independent EL0 program of the ipc check + * The kernel is built -mgeneral-regs-only, so no kernel code keeps live state + * in FP/SIMD registers and the context holds no d8-d15 (the Rust context + * does). EL0 FP/SIMD use traps (CPACR_EL1.FPEN = 01 while EL0 runs). */ + + .text + +/* void ck_ctx_switch(struct ck_ctx *from x0, const struct ck_ctx *to x1) + * struct ck_ctx { uint64_t x19_x30[12]; uint64_t sp; } */ + .global ck_ctx_switch + .type ck_ctx_switch, %function +ck_ctx_switch: + stp x19, x20, [x0, #0] + stp x21, x22, [x0, #16] + stp x23, x24, [x0, #32] + stp x25, x26, [x0, #48] + stp x27, x28, [x0, #64] + stp x29, x30, [x0, #80] + mov x9, sp + str x9, [x0, #96] + ldp x19, x20, [x1, #0] + ldp x21, x22, [x1, #16] + ldp x23, x24, [x1, #32] + ldp x25, x26, [x1, #48] + ldp x27, x28, [x1, #64] + ldp x29, x30, [x1, #80] + ldr x9, [x1, #96] + mov sp, x9 + ret + .size ck_ctx_switch, . - ck_ctx_switch + +/* Entered by the first ck_ctx_switch into a prepared context: x19 = arg, + * x20 = entry. Never returns: ck_thread_exit parks the thread. */ + .global ck_thread_start + .type ck_thread_start, %function +ck_thread_start: + mov x0, x19 + blr x20 + bl ck_thread_exit +1: b 1b + .size ck_thread_start, . - ck_thread_start + +/* void ck_el0_enter(uint64_t entry x0, uint64_t user_sp x1, const uint64_t regs[31] x2) + * Saves the kernel callee-saved registers on SP_EL1, records SP_EL1 in + * ck_el0_kernel_sp, loads x0-x30 from regs (no kernel value reaches EL0) and + * erets to EL0t with interrupts unmasked. Returns when the EL0 task exits + * (the syscall handler redirects to ck_el0_resume). */ + .global ck_el0_enter + .type ck_el0_enter, %function +ck_el0_enter: + sub sp, sp, #96 + stp x19, x20, [sp, #0] + stp x21, x22, [sp, #16] + stp x23, x24, [sp, #32] + stp x25, x26, [sp, #48] + stp x27, x28, [sp, #64] + stp x29, x30, [sp, #80] + adrp x9, ck_el0_kernel_sp + mov x10, sp + str x10, [x9, :lo12:ck_el0_kernel_sp] + msr sp_el0, x1 + msr elr_el1, x0 + msr spsr_el1, xzr /* EL0t, DAIF clear */ + msr tpidrro_el0, xzr /* vectors.S scratch: never visible to EL0 */ + msr tpidr_el0, xzr + mov x30, x2 + ldp x0, x1, [x30, #0] + ldp x2, x3, [x30, #16] + ldp x4, x5, [x30, #32] + ldp x6, x7, [x30, #48] + ldp x8, x9, [x30, #64] + ldp x10, x11, [x30, #80] + ldp x12, x13, [x30, #96] + ldp x14, x15, [x30, #112] + ldp x16, x17, [x30, #128] + ldp x18, x19, [x30, #144] + ldp x20, x21, [x30, #160] + ldp x22, x23, [x30, #176] + ldp x24, x25, [x30, #192] + ldp x26, x27, [x30, #208] + ldp x28, x29, [x30, #224] + ldr x30, [x30, #240] + isb + eret + .size ck_el0_enter, . - ck_el0_enter + +/* Reached by eret (SPSR = EL1h, DAIF masked) after the EL0 task exits. */ + .global ck_el0_resume + .type ck_el0_resume, %function +ck_el0_resume: + adrp x9, ck_el0_kernel_sp + ldr x9, [x9, :lo12:ck_el0_kernel_sp] + mov sp, x9 + ldp x19, x20, [sp, #0] + ldp x21, x22, [sp, #16] + ldp x23, x24, [sp, #32] + ldp x25, x26, [sp, #48] + ldp x27, x28, [sp, #64] + ldp x29, x30, [sp, #80] + add sp, sp, #96 + ret + .size ck_el0_resume, . - ck_el0_resume + +/* ---- EL0 programs: copied into a user code page, never run in place ---- */ + .section .rodata.ck_el0, "a" + .balign 4 +/* el0 check (user.rs aienos_user_code): x0 = console handle, x3 = a kernel + * address. write granted, write with a forged handle, read the kernel + * address (must fault and be contained), exit 0. */ + .global ck_el0_demo_start, ck_el0_demo_end +ck_el0_demo_start: + mov x19, x0 + mov x0, x19 + adr x1, 2f + mov x2, #16 + mov x8, #1 + svc #0 + mov x0, xzr + adr x1, 2f + mov x2, #16 + mov x8, #1 + svc #0 + ldr x21, [x3] + mov x0, xzr + mov x8, #2 + svc #0 +1: b 1b + .balign 4 +2: .ascii "el0 user: hello\n" +ck_el0_demo_end: + +/* ipc check (user.rs aienos_ipc_code): x20 = handle0, x21 = handle1, + * x22 = role (1 = A, 2 = B phase 0, bit 8 = B phase 1). Exit code is a + * bitmask of failed expectations (0 = all as expected). */ + .balign 4 + .global ck_ipc_prog_start, ck_ipc_prog_end +ck_ipc_prog_start: + mov x23, xzr + cmp x22, #1 + b.eq 10f + tbnz x22, #8, 50f + b 20f +10: mov x0, x20 /* A: send kind 7 on the channel */ + mov x1, #7 + mov x2, #0x1111 + mov x3, #0x2222 + mov x4, #0x3333 + mov x5, #0xa + mov x6, #0x1000 + mov x7, #2 + mov x8, #3 + svc #0 + cmp x0, #0 + b.eq 15f + orr x23, x23, #32 +15: mov x0, x21 /* A: delegate READ on the object to B */ + mov x1, #1 + mov x2, #1 + mov x8, #5 + svc #0 + cmp x0, #0 + b.eq 16f + orr x23, x23, #64 +16: mov x0, x23 + mov x8, #2 + svc #0 +70: b 70b +20: mov x0, x20 /* B0: receive */ + mov x8, #4 + svc #0 + cmp x0, #0 + b.eq 21f + orr x23, x23, #1 +21: cmp x1, #7 + b.eq 22f + orr x23, x23, #1 +22: movz x5, #0x1111 + cmp x2, x5 + b.eq 23f + orr x23, x23, #1 +23: movz x5, #0x2222 + cmp x3, x5 + b.eq 24f + orr x23, x23, #1 +24: mov x0, x21 /* B0: read object word 0 */ + mov x1, #0 + mov x8, #6 + svc #0 + movz x5, #0xee01 + movk x5, #0xc0ff, lsl #16 + cmp x0, x5 + b.eq 25f + orr x23, x23, #2 +25: mov x0, x21 /* B0: write must be refused (READ only) */ + mov x1, #0 + mov x2, #0xbad + mov x8, #7 + svc #0 + cmp x0, #0 + b.ne 26f + orr x23, x23, #4 +26: mov x6, #1 /* B0: forged handle must be refused */ + lsl x6, x6, #32 + eor x0, x21, x6 + mov x1, #0 + mov x8, #6 + svc #0 + cmp x0, #0 + b.ne 27f + orr x23, x23, #8 +27: mov x0, x23 + mov x8, #2 + svc #0 +71: b 71b +50: mov x0, x21 /* B1: revoked handle must be refused */ + mov x1, #0 + mov x8, #6 + svc #0 + cmp x0, #0 + b.ne 51f + orr x23, x23, #16 +51: mov x0, x23 + mov x8, #2 + svc #0 +72: b 72b +ck_ipc_prog_end: + + .bss + .balign 8 + .global ck_el0_kernel_sp +ck_el0_kernel_sp: + .space 8 diff --git a/native/kernel/arch/vectors.S b/native/kernel/arch/vectors.S index 4216eb54..bf2f8617 100644 --- a/native/kernel/arch/vectors.S +++ b/native/kernel/arch/vectors.S @@ -1,8 +1,9 @@ /* vectors.S -- exception vectors, EL2 -> EL1h entry, recoverable probe. * ck_vectors serves VBAR_EL1 only; ck_vectors_el2 (fatal-only) serves VBAR_EL2 * before the drop to EL1. - * TPIDR_EL1 and TPIDRRO_EL0 are scratch registers in the entry path (no EL0 - * runs in this core yet). Frame layout: struct ck_frame in arch.h. */ + * TPIDR_EL1 and TPIDRRO_EL0 are scratch registers in the entry path; every + * exit clears TPIDRRO_EL0 so no kernel value is readable from EL0 (the M3 + * EL0 tasks, core/m3.c). Frame layout: struct ck_frame in arch.h. */ #define FRAME 272 .text @@ -71,11 +72,18 @@ ck_vec_common: stp x2, x1, [sp, #256] mov x0, sp cmp x1, #5 - b.ne 2f - bl ck_irq_dispatch + b.eq 4f + cmp x1, #9 + b.eq 4f + bl ck_exception b 3f -2: bl ck_exception -3: ldp x30, x2, [sp, #240] + /* IRQ: the dispatcher returns the frame to resume. It is the same frame + * unless the M3 preemption check switches to another task's frame, which + * sits at the top of that task's stack, so SP moves with it. */ +4: bl ck_irq_dispatch + mov sp, x0 +3: msr tpidrro_el0, xzr /* scratch never leaks to EL0 */ + ldp x30, x2, [sp, #240] msr elr_el1, x2 ldr x2, [sp, #256] msr spsr_el1, x2 diff --git a/native/kernel/core/acpi.c b/native/kernel/core/acpi.c index 71b106d9..0e9838e0 100644 --- a/native/kernel/core/acpi.c +++ b/native/kernel/core/acpi.c @@ -146,6 +146,84 @@ int ck_madt_parse(const void *madt, struct ck_madt_gic *out) return 0; } + +static void topo_add(struct ck_cpu_topology *t, uint8_t cls) +{ + for (unsigned i = 0; i < t->distinct_classes; i++) + if (t->class_id[i] == cls) { + t->class_count[i]++; + return; + } + if (t->distinct_classes >= CK_MAX_CLASSES) { + t->unknown_class++; + return; + } + /* Insert keeping the classes sorted. */ + unsigned at = t->distinct_classes; + while (at > 0 && t->class_id[at - 1] > cls) { + t->class_id[at] = t->class_id[at - 1]; + t->class_count[at] = t->class_count[at - 1]; + at--; + } + t->class_id[at] = cls; + t->class_count[at] = 1; + t->distinct_classes++; +} + +int ck_madt_cpu_topology(const void *madt, struct ck_cpu_topology *out) +{ + const uint8_t *m = madt; + struct ck_cpu_topology t = { 0 }; + uint32_t len = rd32(m + 4); + if (!sig_eq(m, "APIC", 4) || len < 44) + return -1; + for (uint32_t at = 44; at < len;) { + if (at + 2 > len) + return -1; + uint8_t type = m[at], elen = m[at + 1]; + if (elen < 2 || at + elen > len) + return -1; + const uint8_t *e = m + at; + if (type == 0x0b) { /* GICC */ + if (elen < 16) + return -1; + if (rd32(e + 12) & (1u | 8u)) { + t.cores++; + if (!t.has_first_mpidr && elen >= 76) { + t.has_first_mpidr = 1; + t.first_mpidr = rd64(e + 68); + } + if (elen >= 77) + topo_add(&t, e[76]); + else + t.unknown_class++; + } + } + at += elen; + } + *out = t; + return 0; +} + +int ck_place_task(const struct ck_cpu_topology *t, uint32_t task_index, uint8_t *class_id, + uint32_t *core) +{ + uint32_t capacity = 0; + for (unsigned i = 0; i < t->distinct_classes; i++) + capacity += t->class_count[i]; + if (capacity == 0) + return -1; + uint32_t idx = task_index % capacity; + for (unsigned i = 0; i < t->distinct_classes; i++) { + if (idx < t->class_count[i]) { + *class_id = t->class_id[i]; + *core = idx; + return 0; + } + idx -= t->class_count[i]; + } + return -1; +} int ck_spcr_parse(const void *spcr, struct ck_spcr *out) { const uint8_t *s = spcr; diff --git a/native/kernel/core/acpi.h b/native/kernel/core/acpi.h index 980e1c0e..04817114 100644 --- a/native/kernel/core/acpi.h +++ b/native/kernel/core/acpi.h @@ -45,6 +45,26 @@ struct ck_madt_gic { /* 0 on success, -1 on a malformed table (bad entry length, truncation). */ int ck_madt_parse(const void *madt, struct ck_madt_gic *out); +/* CPU topology from the MADT GICC entries (acpi.rs madt_cpu_topology): enabled + * or online-capable cores, (efficiency class, count) pairs sorted by class, + * cores whose entry is too short (< 77 bytes) to carry a class. Pure parse; + * nothing here starts a core. 0 ok, -1 malformed. */ +#define CK_MAX_CLASSES 8 +struct ck_cpu_topology { + uint32_t cores; + uint8_t class_id[CK_MAX_CLASSES]; + uint32_t class_count[CK_MAX_CLASSES]; + unsigned distinct_classes; + uint32_t unknown_class; + int has_first_mpidr; + uint64_t first_mpidr; +}; +int ck_madt_cpu_topology(const void *madt, struct ck_cpu_topology *out); +/* thread.rs place_task: task_index modulo the classified cores, walked class + * by class. 0 and (class, index within class), or -1 if no core is classified. */ +int ck_place_task(const struct ck_cpu_topology *t, uint32_t task_index, uint8_t *class_id, + uint32_t *core); + struct ck_spcr { uint8_t interface_type; /* 0x03 PL011, 0x0d/0x0e SBSA, 0x00/0x12 16550 */ uint8_t space; /* GAS address space: 0 = system memory */ diff --git a/native/kernel/core/ck_internal.h b/native/kernel/core/ck_internal.h index 043ea936..b1f26abc 100644 --- a/native/kernel/core/ck_internal.h +++ b/native/kernel/core/ck_internal.h @@ -73,5 +73,7 @@ struct ck_timer_window { int ck_timer_window(uint32_t ms, struct ck_timer_window *out); uint64_t ck_counter_to_us(uint64_t counter, uint64_t freq); void ck_timer_tick(void); /* IRQ dispatcher: INTID 30 */ +/* M3 isolation checks: threads, el0, preempt, placement, ipc (core/m3.c). */ +void ck_m3_run(void); #endif diff --git a/native/kernel/core/ipc.c b/native/kernel/core/ipc.c new file mode 100644 index 00000000..a47f4313 --- /dev/null +++ b/native/kernel/core/ipc.c @@ -0,0 +1,336 @@ +/* ipc.c -- see ipc.h. caps.rs and ipc.rs logic, step for step. */ +#include "ipc.h" + +void ck_cap_init(struct ck_cap_table *t, uint32_t id, unsigned n) +{ + t->id = id; + t->n = n == 0 ? 1 : (n > CK_CAP_SLOTS ? CK_CAP_SLOTS : n); + for (unsigned i = 0; i < CK_CAP_SLOTS; i++) { + t->slots[i] = (struct ck_cap_slot){ 0 }; + t->generations[i] = 0; + } +} + +static int allocate(struct ck_cap_table *t, uint32_t resource, unsigned rights, int has_parent, + uint32_t parent_table, struct ck_handle parent, struct ck_handle *out) +{ + for (unsigned i = 0; i < t->n; i++) { + /* A slot whose generation reached the maximum is retired for good, so + * no old handle can ever match again. */ + if (t->slots[i].live || t->generations[i] == 0xffffffffu) + continue; + uint32_t gen = t->generations[i] + 1; + t->generations[i] = gen; + t->slots[i] = (struct ck_cap_slot){ .live = 1, .rights = (uint8_t)rights, + .has_parent = (uint8_t)has_parent, + .generation = gen, .resource = resource, + .parent_table = parent_table, .parent = parent }; + out->index = i; + out->generation = gen; + return CK_CAP_OK; + } + return CK_CAP_FULL; +} + +int ck_cap_insert(struct ck_cap_table *t, uint32_t resource, unsigned rights, struct ck_handle *out) +{ + if (rights & ~CK_R_ALL) + return CK_CAP_ESCALATION; + return allocate(t, resource, rights, 0, 0, (struct ck_handle){ 0, 0 }, out); +} + +/* Live slot for the handle, tombstones included (revocation walks them). */ +static const struct ck_cap_slot *slot_any(const struct ck_cap_table *t, struct ck_handle h) +{ + if (h.index >= t->n) + return 0; + const struct ck_cap_slot *s = &t->slots[h.index]; + return s->live && s->generation == h.generation ? s : 0; +} + +static const struct ck_cap_slot *slot_ok(const struct ck_cap_table *t, struct ck_handle h) +{ + const struct ck_cap_slot *s = slot_any(t, h); + return s && !s->tombstone ? s : 0; +} + +int ck_cap_lookup(const struct ck_cap_table *t, struct ck_handle h, unsigned required, + uint32_t *resource) +{ + const struct ck_cap_slot *s = slot_ok(t, h); + if (!s) + return CK_CAP_INVALID; + if ((s->rights & required) != required) + return CK_CAP_MISSING_RIGHTS; + if (resource) + *resource = s->resource; + return CK_CAP_OK; +} + +int ck_cap_rights(const struct ck_cap_table *t, struct ck_handle h, unsigned *rights) +{ + const struct ck_cap_slot *s = slot_ok(t, h); + if (!s) + return CK_CAP_INVALID; + *rights = s->rights; + return CK_CAP_OK; +} + +int ck_cap_remove(struct ck_cap_table *t, struct ck_handle h) +{ + const struct ck_cap_slot *s = slot_ok(t, h); + if (!s) + return CK_CAP_INVALID; + if (s->derived) + t->slots[h.index].tombstone = 1; + else + t->slots[h.index] = (struct ck_cap_slot){ 0 }; + return CK_CAP_OK; +} + +int ck_cap_derive_into(struct ck_cap_table *from, struct ck_handle h, struct ck_cap_table *to, + unsigned rights, struct ck_handle *out) +{ + const struct ck_cap_slot *s = slot_ok(from, h); + if (!s) + return CK_CAP_INVALID; + if (!(s->rights & CK_R_DERIVE)) + return CK_CAP_MISSING_RIGHTS; + if (rights & ~(unsigned)s->rights) + return CK_CAP_ESCALATION; + int r = allocate(to, s->resource, rights, 1, from->id, h, out); + if (r) + return r; + from->slots[h.index].derived = 1; + return CK_CAP_OK; +} + +int ck_cap_derive(struct ck_cap_table *t, struct ck_handle h, unsigned rights, struct ck_handle *out) +{ + return ck_cap_derive_into(t, h, t, rights, out); +} + +int ck_cap_transfer(struct ck_cap_table *from, struct ck_handle h, struct ck_cap_table *to, + struct ck_handle *out) +{ + const struct ck_cap_slot *s = slot_ok(from, h); + if (!s) + return CK_CAP_INVALID; + if (!(s->rights & CK_R_GRANT)) + return CK_CAP_MISSING_RIGHTS; + return allocate(to, s->resource, s->rights, 0, 0, (struct ck_handle){ 0, 0 }, out); +} + +static struct ck_cap_table *table_by_id(struct ck_cap_table *const *tables, unsigned n, uint32_t id) +{ + for (unsigned i = 0; i < n; i++) + if (tables[i]->id == id) + return tables[i]; + return 0; +} + +/* Depth of (table, h) below the root along parent links: >= 0, -1 if not a + * descendant, DEPTH_CYCLE if the chain is longer than every slot (a cycle). */ +#define DEPTH_CYCLE (-1000) +static int revocation_depth(uint32_t table, struct ck_handle h, uint32_t root_table, + struct ck_handle root, struct ck_cap_table *const *tables, unsigned n, + unsigned capacity) +{ + for (unsigned depth = 0; depth <= capacity; depth++) { + if (table == root_table && h.index == root.index && h.generation == root.generation) + return (int)depth; + const struct ck_cap_table *t = table_by_id(tables, n, table); + if (!t) + return -1; + const struct ck_cap_slot *s = slot_any(t, h); + if (!s || !s->has_parent) + return -1; + table = s->parent_table; + h = s->parent; + } + return DEPTH_CYCLE; +} + +int ck_cap_revoke(uint32_t table_id, struct ck_handle h, struct ck_cap_table *const *tables, + unsigned ntables) +{ + unsigned matches = 0; + for (unsigned i = 0; i < ntables; i++) + matches += tables[i]->id == table_id; + if (matches != 1) + return CK_CAP_DUPLICATE_TABLE; + const struct ck_cap_slot *rs = slot_ok(table_by_id(tables, ntables, table_id), h); + if (!rs) + return CK_CAP_INVALID; + if (!(rs->rights & CK_R_REVOKE)) + return CK_CAP_MISSING_RIGHTS; + unsigned capacity = 0; + for (unsigned i = 0; i < ntables; i++) + capacity += tables[i]->n; + /* Validate every chain first: a cycle fails before anything is removed. */ + for (unsigned i = 0; i < ntables; i++) + for (unsigned s = 0; s < tables[i]->n; s++) + if (tables[i]->slots[s].live && + revocation_depth(tables[i]->id, + (struct ck_handle){ s, tables[i]->slots[s].generation }, table_id, + h, tables, ntables, capacity) == DEPTH_CYCLE) + return CK_CAP_FULL; + for (unsigned round = 0; round < capacity; round++) { + int best = -1; + struct ck_cap_table *bt = 0; + unsigned bs = 0; + for (unsigned i = 0; i < ntables; i++) + for (unsigned s = 0; s < tables[i]->n; s++) { + if (!tables[i]->slots[s].live) + continue; + int d = revocation_depth(tables[i]->id, + (struct ck_handle){ s, tables[i]->slots[s].generation }, + table_id, h, tables, ntables, capacity); + if (d > best) { + best = d; + bt = tables[i]; + bs = s; + } + } + if (best < 0) + break; + bt->slots[bs] = (struct ck_cap_slot){ 0 }; + } + return CK_CAP_OK; +} + +/* ---- channel ---- */ +void ck_chan_init(struct ck_channel *c, unsigned cap) +{ + c->head = c->len = 0; + c->cap = cap == 0 ? 1 : (cap > CK_CHAN_CAP ? CK_CHAN_CAP : cap); +} + +int ck_chan_send(struct ck_channel *c, const struct ck_msg *m) +{ + if (c->len == c->cap) + return -1; + c->ring[(c->head + c->len) % c->cap] = *m; + c->len++; + return 0; +} + +int ck_chan_recv(struct ck_channel *c, struct ck_msg *m) +{ + if (c->len == 0) + return -1; + *m = c->ring[c->head]; + c->head = (c->head + 1) % c->cap; + c->len--; + return 0; +} + +/* ---- ipc ---- */ +void ck_ipc_reset(struct ck_ipc *ipc, struct ck_handle *a_send, struct ck_handle *a_object, + struct ck_handle *b_recv) +{ + ck_chan_init(&ipc->chan, CK_CHAN_CAP); + ipc->object[0] = 0xc0ffee01; + ipc->object[1] = 0x0badc0de; + ipc->object[2] = 0x12345678; + ipc->object[3] = 0x9abcdef0; + ck_cap_init(&ipc->tables[0], CK_IPC_PRINCIPAL_A, CK_CAP_SLOTS); + ck_cap_init(&ipc->tables[1], CK_IPC_PRINCIPAL_B, CK_CAP_SLOTS); + ipc->active = 0; + ck_cap_insert(&ipc->tables[0], CK_IPC_CHANNEL_RESOURCE, CK_R_WRITE, a_send); + ck_cap_insert(&ipc->tables[0], CK_IPC_OBJECT_RESOURCE, + CK_R_READ | CK_R_WRITE | CK_R_DERIVE | CK_R_REVOKE, a_object); + ck_cap_insert(&ipc->tables[1], CK_IPC_CHANNEL_RESOURCE, CK_R_READ, b_recv); +} + +static int gated(const struct ck_cap_table *t, struct ck_handle h, unsigned right, uint32_t resource) +{ + uint32_t found; + int r = ck_cap_lookup(t, h, right, &found); + if (r == CK_CAP_OK) + return found == resource ? CK_IPC_OK : CK_IPC_WRONG_RESOURCE; + return r == CK_CAP_MISSING_RIGHTS ? CK_IPC_MISSING_RIGHTS : CK_IPC_INVALID_HANDLE; +} + +int ck_ipc_send(struct ck_ipc *ipc, unsigned p, struct ck_handle h, const struct ck_msg *m) +{ + if (p > 1) + return CK_IPC_INVALID_HANDLE; + int r = gated(&ipc->tables[p], h, CK_R_WRITE, CK_IPC_CHANNEL_RESOURCE); + if (r) + return r; + return ck_chan_send(&ipc->chan, m) ? CK_IPC_CHANNEL_FULL : CK_IPC_OK; +} + +int ck_ipc_recv(struct ck_ipc *ipc, unsigned p, struct ck_handle h, struct ck_msg *m) +{ + if (p > 1) + return CK_IPC_INVALID_HANDLE; + int r = gated(&ipc->tables[p], h, CK_R_READ, CK_IPC_CHANNEL_RESOURCE); + if (r) + return r; + return ck_chan_recv(&ipc->chan, m) ? CK_IPC_CHANNEL_EMPTY : CK_IPC_OK; +} + +int ck_ipc_delegate(struct ck_ipc *ipc, unsigned from, struct ck_handle h, unsigned to, + unsigned rights, struct ck_handle *child) +{ + if (from > 1 || to > 1 || from == to) + return CK_IPC_INVALID_HANDLE; + int r = gated(&ipc->tables[from], h, CK_R_READ, CK_IPC_OBJECT_RESOURCE); + if (r) + return r; + if (rights & ~(CK_R_READ | CK_R_WRITE)) + return CK_IPC_MISSING_RIGHTS; + r = ck_cap_derive_into(&ipc->tables[from], h, &ipc->tables[to], rights, child); + switch (r) { + case CK_CAP_OK: return CK_IPC_OK; + case CK_CAP_FULL: return CK_IPC_DELEGATION_FAILED; + case CK_CAP_MISSING_RIGHTS: + case CK_CAP_ESCALATION: return CK_IPC_MISSING_RIGHTS; + default: return CK_IPC_INVALID_HANDLE; + } +} + +int ck_ipc_object_read(struct ck_ipc *ipc, unsigned p, struct ck_handle h, uint64_t offset, + uint64_t *value) +{ + if (p > 1) + return CK_IPC_INVALID_HANDLE; + int r = gated(&ipc->tables[p], h, CK_R_READ, CK_IPC_OBJECT_RESOURCE); + if (r) + return r; + if (offset >= CK_IPC_OBJECT_SLOTS) + return CK_IPC_WRONG_RESOURCE; + *value = ipc->object[offset]; + return CK_IPC_OK; +} + +int ck_ipc_object_write(struct ck_ipc *ipc, unsigned p, struct ck_handle h, uint64_t offset, + uint64_t value) +{ + if (p > 1) + return CK_IPC_INVALID_HANDLE; + int r = gated(&ipc->tables[p], h, CK_R_WRITE, CK_IPC_OBJECT_RESOURCE); + if (r) + return r; + if (offset >= CK_IPC_OBJECT_SLOTS) + return CK_IPC_WRONG_RESOURCE; + ipc->object[offset] = value; + return CK_IPC_OK; +} + +int ck_ipc_revoke(struct ck_ipc *ipc, unsigned owner, struct ck_handle h) +{ + if (owner > 1) + return CK_IPC_INVALID_HANDLE; + struct ck_cap_table *const tables[2] = { &ipc->tables[0], &ipc->tables[1] }; + int r = ck_cap_revoke(ipc->tables[owner].id, h, tables, 2); + switch (r) { + case CK_CAP_OK: return CK_IPC_OK; + case CK_CAP_FULL: return CK_IPC_DELEGATION_FAILED; + case CK_CAP_MISSING_RIGHTS: + case CK_CAP_ESCALATION: return CK_IPC_MISSING_RIGHTS; + default: return CK_IPC_INVALID_HANDLE; + } +} diff --git a/native/kernel/core/ipc.h b/native/kernel/core/ipc.h new file mode 100644 index 00000000..d0a5505d --- /dev/null +++ b/native/kernel/core/ipc.h @@ -0,0 +1,143 @@ +/* ipc.h -- capability tables and typed bounded IPC for the C kernel core. + * Port of crates/aienos-kernel/src/caps.rs (CapTable: generation-checked + * handles, attenuating derive, cross-table derive, tombstones, cascading + * revoke) and crates/aienos-kernel/src/ipc.rs (bounded FIFO channel of fixed + * 56-byte messages, two principals, a four-word object reachable only through + * capabilities). Pure logic, no hardware: host-tested in tests/test_ipc.c; + * the EL0 IPC demo (core/m3.c) drives it from SVC calls. */ +#ifndef AIENOS_CK_IPC_H +#define AIENOS_CK_IPC_H + +#include + +/* Rights (caps.rs Rights; the same bits are the syscall wire form). */ +#define CK_R_READ 0x01u +#define CK_R_WRITE 0x02u +#define CK_R_MAP 0x04u +#define CK_R_GRANT 0x08u +#define CK_R_DERIVE 0x10u +#define CK_R_REVOKE 0x20u +#define CK_R_ALL 0x3fu + +enum { + CK_CAP_OK = 0, + CK_CAP_FULL = -1, + CK_CAP_INVALID = -2, + CK_CAP_MISSING_RIGHTS = -3, + CK_CAP_ESCALATION = -4, + CK_CAP_DUPLICATE_TABLE = -5, +}; + +struct ck_handle { + uint32_t index, generation; +}; +/* Register form: generation << 32 | index (abi.rs Handle::to_raw). */ +static inline uint64_t ck_handle_raw(struct ck_handle h) +{ + return ((uint64_t)h.generation << 32) | h.index; +} +/* Fails closed (-1) on generation 0. */ +static inline int ck_handle_from_raw(uint64_t raw, struct ck_handle *h) +{ + if ((raw >> 32) == 0) + return -1; + h->index = (uint32_t)raw; + h->generation = (uint32_t)(raw >> 32); + return 0; +} + +#define CK_CAP_SLOTS 8 +struct ck_cap_slot { + uint8_t live, rights, derived, tombstone, has_parent; + uint32_t generation, resource; + uint32_t parent_table; + struct ck_handle parent; +}; +struct ck_cap_table { + uint32_t id; + unsigned n; /* usable slots, 1..CK_CAP_SLOTS */ + struct ck_cap_slot slots[CK_CAP_SLOTS]; + uint32_t generations[CK_CAP_SLOTS]; +}; + +void ck_cap_init(struct ck_cap_table *t, uint32_t id, unsigned n); +int ck_cap_insert(struct ck_cap_table *t, uint32_t resource, unsigned rights, struct ck_handle *out); +/* 0 and *resource if the handle is live and holds every required right. */ +int ck_cap_lookup(const struct ck_cap_table *t, struct ck_handle h, unsigned required, + uint32_t *resource); +int ck_cap_rights(const struct ck_cap_table *t, struct ck_handle h, unsigned *rights); +/* A derived-from capability becomes a tombstone so revoke still reaches its + * children; others free their slot. */ +int ck_cap_remove(struct ck_cap_table *t, struct ck_handle h); +int ck_cap_derive(struct ck_cap_table *t, struct ck_handle h, unsigned rights, struct ck_handle *out); +int ck_cap_derive_into(struct ck_cap_table *from, struct ck_handle h, struct ck_cap_table *to, + unsigned rights, struct ck_handle *out); +int ck_cap_transfer(struct ck_cap_table *from, struct ck_handle h, struct ck_cap_table *to, + struct ck_handle *out); +/* Needs REVOKE on (table_id, h); removes it and every descendant in tables, + * deepest first. Table ids must be unique among tables. */ +int ck_cap_revoke(uint32_t table_id, struct ck_handle h, struct ck_cap_table *const *tables, + unsigned ntables); + +/* ---- typed messages and the bounded channel (ipc.rs) ---- */ +struct ck_msg { + uint32_t kind; + uint32_t reserved; + uint64_t payload[3]; + uint64_t region_base; + uint32_t region_pages; + uint32_t reserved2; + uint64_t object; +}; +_Static_assert(sizeof(struct ck_msg) == 56, "message is 56 bytes like abi.rs Message"); + +#define CK_CHAN_CAP 8 +struct ck_channel { + struct ck_msg ring[CK_CHAN_CAP]; + unsigned head, len, cap; /* cap: 1..CK_CHAN_CAP */ +}; +void ck_chan_init(struct ck_channel *c, unsigned cap); +int ck_chan_send(struct ck_channel *c, const struct ck_msg *m); /* -1 full */ +int ck_chan_recv(struct ck_channel *c, struct ck_msg *m); /* -1 empty */ + +enum { + CK_IPC_OK = 0, + CK_IPC_CHANNEL_FULL = -1, + CK_IPC_CHANNEL_EMPTY = -2, + CK_IPC_MISSING_RIGHTS = -3, + CK_IPC_INVALID_HANDLE = -4, + CK_IPC_WRONG_RESOURCE = -5, + CK_IPC_DELEGATION_FAILED = -6, +}; + +#define CK_IPC_CHANNEL_RESOURCE 0x49504348u /* "IPCH" */ +#define CK_IPC_OBJECT_RESOURCE 0x49504f42u /* "IPOB" */ +#define CK_IPC_PRINCIPAL_A 0x45000041u +#define CK_IPC_PRINCIPAL_B 0x45000042u +#define CK_IPC_OBJECT_SLOTS 4 + +struct ck_ipc { + struct ck_channel chan; + uint64_t object[CK_IPC_OBJECT_SLOTS]; + struct ck_cap_table tables[2]; /* principal A, principal B */ + unsigned active; /* index of the running principal */ +}; + +/* Fresh state: A holds send (WRITE on the channel) and the object (READ, + * WRITE, DERIVE, REVOKE); B holds receive (READ on the channel). A active. */ +void ck_ipc_reset(struct ck_ipc *ipc, struct ck_handle *a_send, struct ck_handle *a_object, + struct ck_handle *b_recv); +int ck_ipc_send(struct ck_ipc *ipc, unsigned principal, struct ck_handle h, const struct ck_msg *m); +int ck_ipc_recv(struct ck_ipc *ipc, unsigned principal, struct ck_handle h, struct ck_msg *m); +/* Delegates the object from principal `from` to `to` with rights that must + * be a subset of READ|WRITE (and of the source rights). */ +int ck_ipc_delegate(struct ck_ipc *ipc, unsigned from, struct ck_handle h, unsigned to, + unsigned rights, struct ck_handle *child); +int ck_ipc_object_read(struct ck_ipc *ipc, unsigned principal, struct ck_handle h, + uint64_t offset, uint64_t *value); +int ck_ipc_object_write(struct ck_ipc *ipc, unsigned principal, struct ck_handle h, + uint64_t offset, uint64_t value); +/* Revokes (owner principal index, h) across both tables. */ +int ck_ipc_revoke(struct ck_ipc *ipc, unsigned owner, struct ck_handle h); + +#endif diff --git a/native/kernel/core/kmain.c b/native/kernel/core/kmain.c index 0015a1a0..1c253656 100644 --- a/native/kernel/core/kmain.c +++ b/native/kernel/core/kmain.c @@ -4,8 +4,9 @@ * vectors, PSCI conduit, own address space, then EL2 -> EL1h (ADR 0009) with * the MMU on our tables. ck_el1_main then reports the MMU switch from live * registers, proves the guard pages, brings up GICv3 and the EL1 physical - * timer, runs the linked boot stages and ends with the final report and a - * PSCI reset. QEMU runs of this path qualify nothing physical. */ + * timer, runs the M3 isolation checks (core/m3.c) and the linked boot stages, + * and ends with the final report and a PSCI reset. QEMU runs of this path + * qualify nothing physical. */ #include "arch.h" #include "ck_internal.h" @@ -114,6 +115,9 @@ static __attribute__((noreturn)) void ck_el1_main(void *arg) ck_puts("kernel: alive\n"); ck_printf("kernel_el: EL%u%s\n", el, (spsel & 1) ? "h" : "t"); + /* M3 isolation checks (core/m3.c), before any stage registers an IRQ. */ + ck_m3_run(); + run_stage("devices", ck_stage_devices); run_stage("security", ck_stage_security); run_stage("store", ck_stage_store); @@ -127,7 +131,6 @@ static __attribute__((noreturn)) void ck_el1_main(void *arg) ck_set_stage("final"); ck_puts("\n"); ck_report_header("final"); - ck_puts("M3 features (threads, el0, preempt, placement, ipc): not implemented in the C kernel yet\n"); ck_puts("note: QEMU qualifies nothing physical\n"); ck_reset(); } diff --git a/native/kernel/core/m3.c b/native/kernel/core/m3.c new file mode 100644 index 00000000..5990e623 --- /dev/null +++ b/native/kernel/core/m3.c @@ -0,0 +1,633 @@ +/* m3.c -- M3 isolation checks in the C kernel core (port of the Rust kernel's + * thread.rs, user.rs and ipc.rs demos as driven by aienos-boot handoff.rs). + * Prints, in the Rust order: + * threads: two cooperative EL1 threads on the core/sched.c run queue + * el0: an EL0 task in its own address space: capability-checked write, + * forged handle refused, kernel-address read faults and is contained + * preempt: two spinning EL1 workers switched only by the timer IRQ + * placement: workers placed on cores from the MADT efficiency classes + * (pure computation: neither kernel starts a secondary core) + * ipc: two EL0 principals, typed message, attenuated delegation, + * forged handle refused, revoked handle refused + * Single core, EL1h; runs with IRQs masked except inside the preempt check + * and while EL0 runs. */ +#include "acpi.h" +#include "arch.h" +#include "ck_internal.h" +#include "ipc.h" +#include "pt.h" +#include "sched.h" + +#define DENIED 0xffffffffffffffffull + +/* ---- vector hooks (arch/exception.c) ---- */ +extern struct ck_frame *(*ck_tick_switch)(struct ck_frame *f); +extern int (*ck_lower_sync)(struct ck_frame *f, uint64_t esr); + +/* ---- asm (arch/m3.S) ---- */ +struct ck_ctx { + uint64_t x19_x30[12]; + uint64_t sp; +}; +void ck_ctx_switch(struct ck_ctx *from, const struct ck_ctx *to); +void ck_thread_start(void); +void ck_thread_exit(void); +void ck_el0_enter(uint64_t entry, uint64_t user_sp, const uint64_t regs[31]); +void ck_el0_resume(void); +extern const char ck_el0_demo_start[], ck_el0_demo_end[]; +extern const char ck_ipc_prog_start[], ck_ipc_prog_end[]; + +/* ===================== cooperative threads (thread.rs) ===================== */ +#define TMAX 4 +static struct ck_ctx contexts[TMAX], main_ctx; +static int runnable[TMAX]; +static unsigned current = TMAX; +static struct ck_sched sched; +static uint8_t thread_stack[2][8192] __attribute__((aligned(16))); +static char trace[10]; +static unsigned trace_len; +static uint64_t thread_floor[TMAX]; /* stack base per thread, for the vector stack guard */ +static uint64_t kernel_floor; + +static void yield_now(void) +{ + unsigned from = current, target = TMAX; + for (unsigned i = 0; i < TMAX; i++) { + uint32_t id; + if (ck_sched_tick(&sched, 0, &id) == 1 && id < TMAX && runnable[id] && id != from) { + target = id; + break; + } + } + if (target == from) + return; + current = target; + /* keep the vector stack guard on the stack that will run */ + ck_stack_floor = target == TMAX ? kernel_floor : thread_floor[target]; + ck_ctx_switch(from == TMAX ? &main_ctx : &contexts[from], + target == TMAX ? &main_ctx : &contexts[target]); +} + +void ck_thread_exit(void) +{ + runnable[current] = 0; + ck_sched_remove(&sched, current); + for (;;) + yield_now(); +} + +static int spawn(uint8_t *stack, size_t len, void (*entry)(uint64_t), uint64_t arg) +{ + for (unsigned slot = 0; slot < TMAX; slot++) { + if (runnable[slot] || ck_sched_task(&sched, slot)) + continue; + uint64_t sp = (((uint64_t)(uintptr_t)stack + len) & ~15ull) - 16; + contexts[slot] = (struct ck_ctx){ .sp = sp }; + thread_floor[slot] = (uint64_t)(uintptr_t)stack; + contexts[slot].x19_x30[0] = arg; + contexts[slot].x19_x30[1] = (uint64_t)(uintptr_t)entry; + contexts[slot].x19_x30[11] = (uint64_t)(uintptr_t)ck_thread_start; + if (ck_sched_enqueue(&sched, slot, CK_PRIO_NORMAL) < 0) + return -1; + runnable[slot] = 1; + return (int)slot; + } + return -1; +} + +static void thread_worker(uint64_t tag) +{ + for (int i = 0; i < 5; i++) { + if (trace_len < sizeof trace) + trace[trace_len++] = tag == 0 ? 'A' : 'B'; + yield_now(); + } +} + +static void check_threads(void) +{ + static const uint8_t one_class[1] = { 0 }; + ck_sched_init(&sched, 1, one_class, TMAX, 8); + trace_len = 0; + current = TMAX; + int ok = spawn(thread_stack[0], sizeof thread_stack[0], thread_worker, 0) >= 0 && + spawn(thread_stack[1], sizeof thread_stack[1], thread_worker, 1) >= 0; + while (ok && (runnable[0] || runnable[1] || runnable[2] || runnable[3])) + yield_now(); + char seen[sizeof trace + 1]; + memcpy(seen, trace, trace_len); + seen[trace_len] = 0; + ck_printf("threads: %s interleave=%s\n", + trace_len == 10 && !memcmp(seen, "ABABABABAB", 10) ? "ok" : "unexpected", seen); +} + +/* ======================= timer preemption (thread.rs) ====================== */ +static uint8_t preempt_stack[2][16384] __attribute__((aligned(16))); +static volatile uint64_t counter_a, counter_b; +static volatile int preempt_active, preempt_done; +static uint64_t preempt_switches; +static struct ck_frame *worker_frame[2], *main_frame; +static unsigned preempt_cur; + +static void preempt_worker(uint64_t which) +{ + for (;;) { + if (which) + counter_b = counter_b + 1; + else + counter_a = counter_a + 1; + } +} + +/* A worker function never returns; if one did, its x30 lands here. */ +static void preempt_worker_exit(void) +{ + ck_panic("preempt: worker returned"); +} + +static struct ck_frame *prepare_frame(uint8_t *stack, size_t len, void (*entry)(uint64_t), + uint64_t arg) +{ + uint64_t top = ((uint64_t)(uintptr_t)stack + len) & ~15ull; + struct ck_frame *f = (struct ck_frame *)(uintptr_t)(top - sizeof(struct ck_frame)); + memset(f, 0, sizeof *f); + f->x[0] = arg; + f->x[30] = (uint64_t)(uintptr_t)preempt_worker_exit; + f->elr = (uint64_t)(uintptr_t)entry; + f->spsr = 0x5; /* EL1h, DAIF clear: the next tick preempts it */ + f->vector = 5; + return f; +} + +/* Called by ck_irq_dispatch after the timer tick was re-armed and EOId. + * Returns the frame the vector exit restores (SP moves onto that stack). */ +static struct ck_frame *preempt_tick(struct ck_frame *f) +{ + if (!preempt_active) + return f; + if (!main_frame) { + main_frame = f; + preempt_cur = 0; + ck_stack_floor = (uint64_t)(uintptr_t)preempt_stack[0]; + return worker_frame[0]; + } + worker_frame[preempt_cur] = f; + if (preempt_switches >= 4 && counter_a > 0 && counter_b > 0) { + preempt_active = 0; + preempt_done = 1; + struct ck_frame *t = main_frame; + main_frame = 0; + ck_stack_floor = kernel_floor; + return t; + } + preempt_cur ^= 1; + preempt_switches++; + ck_stack_floor = (uint64_t)(uintptr_t)preempt_stack[preempt_cur]; + return worker_frame[preempt_cur]; +} + +static void check_preempt(void) +{ + counter_a = counter_b = 0; + preempt_switches = 0; + main_frame = 0; + preempt_done = 0; + worker_frame[0] = prepare_frame(preempt_stack[0], sizeof preempt_stack[0], preempt_worker, 0); + worker_frame[1] = prepare_frame(preempt_stack[1], sizeof preempt_stack[1], preempt_worker, 1); + uint64_t hz = ck_rd(cntfrq_el0); + int timed_out = 0; + if (hz) { + preempt_active = 1; + ck_tick_switch = preempt_tick; + uint64_t start = ck_rd(cntpct_el0); + ck_wr(cntp_cval_el0, start + hz / 100); + ck_wr(cntp_ctl_el0, 1); + ck_isb(); + ck_irq_on(); + ck_isb(); + /* Main resumes only when the dispatcher hands its frame back. The + * timeout covers a timer that never fires (main never left). */ + while (!preempt_done) { + if (ck_rd(cntpct_el0) - start > hz * 2) { + timed_out = 1; + break; + } + } + ck_irq_off(); + ck_isb(); + preempt_active = 0; + ck_tick_switch = 0; + ck_wr(cntp_ctl_el0, 0); + ck_isb(); + ck_stack_floor = kernel_floor; + } + uint64_t a = counter_a, b = counter_b; + int ok = !timed_out && a > 0 && b > 0 && preempt_switches >= 4; + ck_printf("preempt: %s a=%llu b=%llu switches=%llu\n", ok ? "ok" : "failed", + (unsigned long long)a, (unsigned long long)b, (unsigned long long)preempt_switches); +} + +/* ============================ placement (MADT) ============================= */ +static void check_placement(void) +{ + const void *madt = ck_acpi_find("APIC"); + struct ck_cpu_topology topo; + if (!madt || ck_madt_cpu_topology(madt, &topo)) { + ck_puts("placement: unavailable\n"); + return; + } + char line[128]; + size_t n = 0; + static const char *const names[2] = { "worker0", "worker1" }; + n += (size_t)ck_snprintf(line, sizeof line, "placement:"); + for (uint32_t i = 0; i < 2; i++) { + uint8_t cls; + uint32_t core; + if (ck_place_task(&topo, i, &cls, &core) == 0) + n += (size_t)ck_snprintf(line + n, sizeof line - n, " %s=class%u/core%u", names[i], + (unsigned)cls, (unsigned)core); + else + n += (size_t)ck_snprintf(line + n, sizeof line - n, " %s=unplaced", names[i]); + } + ck_printf("%s\n", line); +} + +/* ===================== EL0 address spaces (user.rs) ======================== */ +struct el0_window { + uint64_t l0[512], l1[512], l2[512], l3[512]; + uint8_t code[4096]; + uint8_t stack[4096]; +} __attribute__((aligned(4096))); +static struct el0_window demo_window, ipc_window[2]; + +#define PTE_TABLE 3ull +#define PTE_PAGE 3ull +#define PTE_AP_EL0_RW (1ull << 6) +#define PTE_AP_EL0_RO (3ull << 6) +#define PTE_NG (1ull << 11) + +static void clean_range(const void *p, size_t len, int icache) +{ + uint64_t ctr = ck_rd(ctr_el0); + uint64_t dline = 4ull << ((ctr >> 16) & 0xf), iline = 4ull << (ctr & 0xf); + uint64_t a = (uint64_t)(uintptr_t)p, end = a + len; + for (uint64_t x = a & ~(dline - 1); x < end; x += dline) + __asm__ volatile("dc civac, %0" ::"r"(x) : "memory"); + ck_dsb_ish(); + if (icache) { + for (uint64_t x = a & ~(iline - 1); x < end; x += iline) + __asm__ volatile("ic ivau, %0" ::"r"(x) : "memory"); + ck_dsb_ish(); + } + ck_isb(); +} + +/* Kernel L0 copied (kernel mappings stay EL1-only: AP[1] = 0), one free + * L0 slot in the lower half chained to: page 0 = code (EL0 read-only, + * executable at EL0, never at EL1), page 1 = stack (EL0 read-write, never + * executable). nG: the user pages are not global. Returns the user base, 0 if + * no L0 slot is free or the image does not fit. */ +static uint64_t build_window(struct el0_window *w, const char *img, size_t len, uint64_t kroot) +{ + if (len > sizeof w->code) + return 0; + memcpy(w->l0, (const void *)(uintptr_t)kroot, sizeof w->l0); + unsigned idx = 0; + for (unsigned i = 1; i < 256 && !idx; i++) + if (!w->l0[i]) + idx = i; + if (!idx) + return 0; + memset(w->l1, 0, sizeof w->l1); + memset(w->l2, 0, sizeof w->l2); + memset(w->l3, 0, sizeof w->l3); + w->l0[idx] = (uint64_t)(uintptr_t)w->l1 | PTE_TABLE; + w->l1[0] = (uint64_t)(uintptr_t)w->l2 | PTE_TABLE; + w->l2[0] = (uint64_t)(uintptr_t)w->l3 | PTE_TABLE; + uint64_t common = CK_PTE_ATTRIDX(CK_MAIR_IDX_NORMAL) | CK_PTE_SH_INNER | CK_PTE_AF | PTE_NG | + CK_PTE_PXN; + w->l3[0] = (uint64_t)(uintptr_t)w->code | PTE_PAGE | PTE_AP_EL0_RO | common; + w->l3[1] = (uint64_t)(uintptr_t)w->stack | PTE_PAGE | PTE_AP_EL0_RW | common | CK_PTE_UXN; + memset(w->code, 0, sizeof w->code); + memcpy(w->code, img, len); + memset(w->stack, 0, sizeof w->stack); + clean_range(w->l0, 4 * 4096, 0); + clean_range(w->code, sizeof w->code, 1); + clean_range(w->stack, sizeof w->stack, 0); + return (uint64_t)idx << 39; +} + +static void swap_ttbr0(uint64_t ttbr0) +{ + ck_dsb_ish(); + ck_wr(ttbr0_el1, ttbr0); + ck_isb(); + __asm__ volatile("tlbi vmalle1" ::: "memory"); + ck_dsb_ish(); + ck_isb(); +} + +enum { EL0_NONE, EL0_DEMO, EL0_IPC }; +static int el0_mode; +static uint64_t el0_exit; +static uint64_t el0_code_base; /* user VA of the running task's code page */ +static const uint8_t *el0_code; /* kernel view of that page */ + +static void el0_to_kernel(struct ck_frame *f, uint64_t code) +{ + el0_exit = code; + f->elr = (uint64_t)(uintptr_t)ck_el0_resume; + f->spsr = 0x3c5; /* EL1h, DAIF masked (the Rust kernel resumes with 0x5) */ +} + +/* Runs one EL0 task to its exit on the given address space. */ +static uint64_t run_el0(uint64_t root, uint64_t base, const struct el0_window *w, int mode, + const uint64_t regs[31]) +{ + uint64_t kttbr = ck_rd(ttbr0_el1), cpacr = ck_rd(cpacr_el1); + el0_mode = mode; + el0_exit = DENIED; + el0_code_base = base; + el0_code = w->code; + ck_wr(cpacr_el1, (cpacr & ~(3ull << 20)) | (1ull << 20)); /* FP/SIMD traps at EL0 */ + swap_ttbr0(root); + ck_el0_enter(base, base + 0x2000, regs); + swap_ttbr0(kttbr); + ck_wr(cpacr_el1, cpacr); + ck_isb(); + el0_mode = EL0_NONE; + return el0_exit; +} + +/* ---- el0 check (user.rs run_demo) ---- */ +#define CONSOLE_RESOURCE 1u +static struct ck_cap_table user_caps; +static uint64_t authorized_raw; +static int write_granted, forged_denied, fault_contained; +static uint64_t el0_probe_addr; /* the one kernel address the demo task is expected to fault on */ +#define EL0_FAULT_KILLED 0xfa17ull /* exit code of a task killed by an unexpected fault */ + +static int user_bytes(uint64_t addr, uint64_t len, const uint8_t **out) +{ + if (addr < el0_code_base || len > 4096 || addr - el0_code_base > 4096 - len) + return -1; + *out = el0_code + (addr - el0_code_base); + return 0; +} + +static void demo_write(struct ck_frame *f) +{ + uint64_t raw = f->x[0]; + struct ck_handle h; + if (ck_handle_from_raw(raw, &h)) { + forged_denied = 1; + f->x[0] = DENIED; + return; + } + uint32_t res = 0; + int allowed = ck_cap_lookup(&user_caps, h, CK_R_WRITE, &res) == 0 && res == CONSOLE_RESOURCE; + const uint8_t *bytes; + if (allowed && user_bytes(f->x[1], f->x[2], &bytes) == 0) { + char chunk[65]; + for (uint64_t at = 0; at < f->x[2]; at += 64) { + uint64_t n = f->x[2] - at < 64 ? f->x[2] - at : 64; + memcpy(chunk, bytes + at, n); + chunk[n] = 0; + ck_puts(chunk); + } + write_granted = 1; + f->x[0] = 0; + return; + } + if (raw != authorized_raw) + forged_denied = 1; + f->x[0] = DENIED; +} + +static void check_el0(uint64_t kroot) +{ + write_granted = forged_denied = fault_contained = 0; + ck_cap_init(&user_caps, 0x454c3001u, 4); + struct ck_handle h; + uint64_t base = build_window(&demo_window, ck_el0_demo_start, + (size_t)(ck_el0_demo_end - ck_el0_demo_start), kroot); + if (ck_cap_insert(&user_caps, CONSOLE_RESOURCE, CK_R_WRITE, &h) || !base) { + ck_puts("el0: failed setup\n"); + return; + } + authorized_raw = ck_handle_raw(h); + uint64_t regs[31] = { 0 }; + regs[0] = authorized_raw; + regs[3] = (uint64_t)(uintptr_t)ck_el0_enter; /* kernel text: EL1-only */ + el0_probe_addr = regs[3]; + uint64_t code = run_el0((uint64_t)(uintptr_t)demo_window.l0, base, &demo_window, EL0_DEMO, regs); + int ok = write_granted && forged_denied && fault_contained && code == 0; + ck_printf("el0: %s write=%s forged=%s fault=%s exit=%llu\n", ok ? "ok" : "failed", + write_granted ? "granted" : "denied", forged_denied ? "denied" : "accepted", + fault_contained ? "contained" : "uncontained", (unsigned long long)code); +} + +/* ---- ipc check (user.rs run_ipc_demo) ---- */ +static struct ck_ipc ipc; +static unsigned ipc_principal, ipc_phase; +static int msg_delivered, cap_delegated, rights_attenuated, ipc_forged, ipc_revoked; +static uint64_t sent_kind, sent_p0, sent_p1, sent_obj, child_raw; + +static void ipc_handle_refused(void) +{ + if (ipc_phase) + ipc_revoked = 1; + else + ipc_forged = 1; +} + +static void dispatch_ipc(struct ck_frame *f) +{ + struct ck_handle h; + uint64_t nr = f->x[8]; + if (nr == 2) { /* exit */ + el0_to_kernel(f, f->x[0]); + return; + } + if (nr < 3 || nr > 7) { + f->x[0] = DENIED; + return; + } + if (ck_handle_from_raw(f->x[0], &h)) { + if (nr == 6) + ipc_handle_refused(); + f->x[0] = DENIED; + return; + } + switch (nr) { + case 3: { /* channel send */ + struct ck_msg m = { 0 }; + m.kind = (uint32_t)f->x[1]; + m.payload[0] = f->x[2]; + m.payload[1] = f->x[3]; + m.payload[2] = f->x[4]; + m.region_base = f->x[5]; + m.region_pages = (uint32_t)f->x[6]; + m.object = f->x[7]; + if (ck_ipc_send(&ipc, ipc_principal, h, &m) == 0) { + sent_kind = f->x[1]; + sent_p0 = f->x[2]; + sent_p1 = f->x[3]; + sent_obj = f->x[7]; + f->x[0] = 0; + } else { + f->x[0] = DENIED; + } + break; + } + case 4: { /* channel receive */ + struct ck_msg m; + if (ck_ipc_recv(&ipc, ipc_principal, h, &m)) { + f->x[0] = DENIED; + break; + } + if (m.kind == sent_kind && m.payload[0] == sent_p0 && m.payload[1] == sent_p1 && + m.object == sent_obj) + msg_delivered = 1; + f->x[0] = 0; + f->x[1] = m.kind; + f->x[2] = m.payload[0]; + f->x[3] = m.payload[1]; + f->x[4] = m.payload[2]; + f->x[5] = m.object; + break; + } + case 5: { /* delegate: x1 = target principal index, x2 = wire rights */ + struct ck_handle child; + if ((f->x[2] & ~(uint64_t)CK_R_ALL) || f->x[1] > 1 || + ck_ipc_delegate(&ipc, ipc_principal, h, (unsigned)f->x[1], (unsigned)f->x[2], &child)) { + f->x[0] = DENIED; + break; + } + cap_delegated = 1; + child_raw = ck_handle_raw(child); + f->x[0] = 0; + break; + } + case 6: { /* object read */ + uint64_t v; + int r = ck_ipc_object_read(&ipc, ipc_principal, h, f->x[1], &v); + if (r == 0) { + f->x[0] = v; + } else { + if (r == CK_IPC_INVALID_HANDLE) + ipc_handle_refused(); + f->x[0] = DENIED; + } + break; + } + case 7: { /* object write */ + int r = ck_ipc_object_write(&ipc, ipc_principal, h, f->x[1], f->x[2]); + if (r == CK_IPC_MISSING_RIGHTS) + rights_attenuated = 1; + f->x[0] = r ? DENIED : 0; + break; + } + } +} + +static int lower_sync(struct ck_frame *f, uint64_t esr) +{ + if (el0_mode == EL0_NONE || (f->spsr & 0xf) != 0) + return -1; /* not from an M3 EL0 task: fatal path */ + uint64_t ec = (esr >> 26) & 0x3f; + if (ec == 0x15 && (esr & 0xffff) == 0) { + if (el0_mode == EL0_IPC) + dispatch_ipc(f); + else if (f->x[8] == 1) + demo_write(f); + else if (f->x[8] == 2) + el0_to_kernel(f, f->x[0]); + else + f->x[0] = DENIED; + } else if (ec == 0x24) { /* data abort from EL0 */ + uint64_t far; + __asm__ volatile("mrs %0, far_el1" : "=r"(far)); + if (el0_mode == EL0_DEMO && !fault_contained && far == el0_probe_addr) { + /* the demo's one expected probe of kernel memory: contained, + * the load is skipped and the task continues to its exit */ + fault_contained = 1; + f->elr += 4; + } else { + /* any other EL0 fault kills the task; the kernel keeps running */ + el0_to_kernel(f, EL0_FAULT_KILLED); + } + } else { + el0_to_kernel(f, DENIED); + } + return 0; +} + +static void check_ipc(uint64_t kroot) +{ + msg_delivered = cap_delegated = rights_attenuated = ipc_forged = ipc_revoked = 0; + child_raw = 0; + struct ck_handle a_send, a_obj, b_recv; + ck_ipc_reset(&ipc, &a_send, &a_obj, &b_recv); + size_t len = (size_t)(ck_ipc_prog_end - ck_ipc_prog_start); + uint64_t base_a = build_window(&ipc_window[0], ck_ipc_prog_start, len, kroot); + uint64_t base_b = build_window(&ipc_window[1], ck_ipc_prog_start, len, kroot); + if (!base_a || !base_b) { + ck_puts("ipc: failed setup\n"); + return; + } + uint64_t root_a = (uint64_t)(uintptr_t)ipc_window[0].l0; + uint64_t root_b = (uint64_t)(uintptr_t)ipc_window[1].l0; + uint64_t regs[31] = { 0 }; + + /* principal A: send the typed message, delegate an attenuated copy */ + ipc_principal = 0; + ipc_phase = 0; + regs[0] = regs[22] = 1; + regs[20] = ck_handle_raw(a_send); + regs[21] = ck_handle_raw(a_obj); + uint64_t exit_a = run_el0(root_a, base_a, &ipc_window[0], EL0_IPC, regs); + + /* principal B, phase 0: receive, read, attempt write, forge */ + ipc_principal = 1; + regs[0] = regs[22] = 2; + regs[20] = ck_handle_raw(b_recv); + regs[21] = child_raw; + uint64_t exit_b0 = run_el0(root_b, base_b, &ipc_window[1], EL0_IPC, regs); + + /* the kernel revokes A's ancestor; B's derived handle must die */ + int revoke = ck_ipc_revoke(&ipc, 0, a_obj); + + /* principal B, phase 1: the derived handle no longer resolves */ + ipc_phase = 1; + regs[0] = regs[22] = 0x102; + uint64_t exit_b1 = run_el0(root_b, base_b, &ipc_window[1], EL0_IPC, regs); + + int ok = msg_delivered && cap_delegated && rights_attenuated && ipc_forged && ipc_revoked && + revoke == 0 && exit_a == 0 && exit_b0 == 0 && exit_b1 == 0; + ck_printf("ipc: %s message=%s cap=%s rights=%s forged=%s revoked=%s\n", ok ? "ok" : "failed", + msg_delivered ? "delivered" : "missed", cap_delegated ? "delegated" : "failed", + rights_attenuated ? "attenuated" : "escalated", ipc_forged ? "denied" : "accepted", + ipc_revoked ? "denied" : "accepted"); + ck_printf("ipc_detail: exit_a=0x%llx exit_b0=0x%llx exit_b1=0x%llx child=0x%llx revoke=%d\n", + (unsigned long long)exit_a, (unsigned long long)exit_b0, + (unsigned long long)exit_b1, (unsigned long long)child_raw, revoke); +} + +void ck_m3_run(void) +{ + kernel_floor = ck_stack_floor; + uint64_t kroot = ck_mm_report()->root; + ck_lower_sync = lower_sync; + ck_set_stage("m3_threads"); + check_threads(); + ck_set_stage("m3_el0"); + check_el0(kroot); + ck_set_stage("m3_preempt"); + check_preempt(); + ck_set_stage("m3_placement"); + check_placement(); + ck_set_stage("m3_ipc"); + check_ipc(kroot); + ck_lower_sync = 0; +} diff --git a/native/kernel/core/sched.c b/native/kernel/core/sched.c new file mode 100644 index 00000000..d1026839 --- /dev/null +++ b/native/kernel/core/sched.c @@ -0,0 +1,191 @@ +/* sched.c -- see sched.h. Same decisions as scheduler.rs, step for step. */ +#include "sched.h" + +int ck_sched_init(struct ck_sched *s, unsigned cpus, const uint8_t *classes, unsigned tasks, + unsigned bg_interval) +{ + if (cpus > CK_SCHED_MAX_CPUS || tasks > CK_SCHED_MAX_TASKS) + return -1; + s->cpus = cpus; + s->ntasks = tasks; + for (unsigned c = 0; c < CK_SCHED_MAX_CPUS; c++) { + s->classes[c] = c < cpus ? classes[c] : 0; + s->queue_len[c] = 0; + s->bg_wait[c] = 0; + for (unsigned t = 0; t < CK_SCHED_MAX_TASKS; t++) + s->queues[c][t] = -1; + } + for (unsigned t = 0; t < CK_SCHED_MAX_TASKS; t++) { + s->used[t] = 0; + s->tasks[t] = (struct ck_task){ 0 }; + } + s->bg_interval = bg_interval ? bg_interval : 1; + s->cursor = 0; + return 0; +} + +int ck_sched_place(const struct ck_sched *s, enum ck_prio prio) +{ + if (s->cpus == 0) + return CK_SCHED_NO_CPUS; + unsigned start = s->cursor % s->cpus; + if (prio == CK_PRIO_NORMAL) { + unsigned best = start; + for (unsigned off = 1; off < s->cpus; off++) { + unsigned cpu = (start + off) % s->cpus; + if (s->queue_len[cpu] < s->queue_len[best]) + best = cpu; + } + return (int)best; + } + uint8_t want = s->classes[0]; + for (unsigned c = 1; c < s->cpus; c++) { + if (prio == CK_PRIO_LATENCY ? s->classes[c] > want : s->classes[c] < want) + want = s->classes[c]; + } + for (unsigned off = 0; off < s->cpus; off++) { + unsigned cpu = (start + off) % s->cpus; + if (s->classes[cpu] == want) + return (int)cpu; + } + return CK_SCHED_NO_CPUS; /* unreachable */ +} + +static int slot_of(const struct ck_sched *s, uint32_t id) +{ + for (unsigned t = 0; t < s->ntasks; t++) + if (s->used[t] && s->tasks[t].id == id) + return (int)t; + return -1; +} + +int ck_sched_enqueue(struct ck_sched *s, uint32_t id, enum ck_prio prio) +{ + if (slot_of(s, id) >= 0) + return CK_SCHED_DUPLICATE; + int slot = -1; + for (unsigned t = 0; t < s->ntasks; t++) + if (!s->used[t]) { + slot = (int)t; + break; + } + if (slot < 0) + return CK_SCHED_FULL; + int cpu = ck_sched_place(s, prio); + if (cpu < 0) + return cpu; + s->cursor = ((unsigned)cpu + 1) % s->cpus; + s->queues[cpu][s->queue_len[cpu]++] = slot; + s->used[slot] = 1; + s->tasks[slot] = (struct ck_task){ .id = id, .prio = prio, .cpu = (unsigned)cpu, .ticks = 0 }; + return cpu; +} + +static void queue_drop(struct ck_sched *s, unsigned cpu, unsigned at) +{ + unsigned len = s->queue_len[cpu]; + for (unsigned i = at; i + 1 < len; i++) + s->queues[cpu][i] = s->queues[cpu][i + 1]; + s->queues[cpu][len - 1] = -1; + s->queue_len[cpu] = len - 1; +} + +int ck_sched_remove(struct ck_sched *s, uint32_t id) +{ + int slot = slot_of(s, id); + if (slot < 0) + return CK_SCHED_UNKNOWN; + for (unsigned cpu = 0; cpu < s->cpus; cpu++) { + for (unsigned i = 0; i < s->queue_len[cpu]; i++) { + if (s->queues[cpu][i] == slot) { + queue_drop(s, cpu, i); + goto done; + } + } + } +done: + s->used[slot] = 0; + return CK_SCHED_OK; +} + +int ck_sched_steal(struct ck_sched *s, unsigned idle) +{ + if (idle >= s->cpus) + return CK_SCHED_INVALID_CPU; + if (s->queue_len[idle] != 0) + return 0; + int donor = -1; + for (unsigned cpu = 0; cpu < s->cpus; cpu++) + if (cpu != idle && s->queue_len[cpu] > 1 && + (donor < 0 || s->queue_len[cpu] > s->queue_len[donor])) + donor = (int)cpu; + if (donor < 0) + return 0; + /* Candidate: lowest priority, then most ticks (first wins ties). */ + unsigned pick = 0; + for (unsigned i = 1; i < s->queue_len[donor]; i++) { + const struct ck_task *t = &s->tasks[s->queues[donor][i]]; + const struct ck_task *p = &s->tasks[s->queues[donor][pick]]; + if (t->prio < p->prio || (t->prio == p->prio && t->ticks > p->ticks)) + pick = i; + } + int slot = s->queues[donor][pick]; + queue_drop(s, (unsigned)donor, pick); + s->queues[idle][0] = slot; + s->queue_len[idle] = 1; + s->tasks[slot].cpu = idle; + return 1; +} + +int ck_sched_tick(struct ck_sched *s, unsigned cpu, uint32_t *id) +{ + if (cpu >= s->cpus) + return CK_SCHED_INVALID_CPU; + if (s->queue_len[cpu] == 0) { + int st = ck_sched_steal(s, cpu); + if (st < 0) + return st; + if (!st) + return 0; + } + unsigned len = s->queue_len[cpu]; + int has_bg = 0, has_higher = 0; + for (unsigned i = 0; i < len; i++) { + enum ck_prio p = s->tasks[s->queues[cpu][i]].prio; + if (p == CK_PRIO_BACKGROUND) + has_bg = 1; + else + has_higher = 1; + } + int force_bg = 0; + if (has_bg && has_higher) { + s->bg_wait[cpu]++; + force_bg = s->bg_wait[cpu] >= s->bg_interval; + } else { + s->bg_wait[cpu] = 0; + } + int sel = s->queues[cpu][0]; + for (unsigned i = 1; i < len; i++) { + int slot = s->queues[cpu][i]; + const struct ck_task *t = &s->tasks[slot], *p = &s->tasks[sel]; + int wins; + if (force_bg) + wins = (t->prio == CK_PRIO_BACKGROUND && p->prio != CK_PRIO_BACKGROUND) || + (t->prio == p->prio && t->ticks < p->ticks); + else + wins = t->prio > p->prio || (t->prio == p->prio && t->ticks < p->ticks); + if (wins) + sel = slot; + } + if (s->tasks[sel].prio == CK_PRIO_BACKGROUND) + s->bg_wait[cpu] = 0; + s->tasks[sel].ticks++; + *id = s->tasks[sel].id; + return 1; +} + +const struct ck_task *ck_sched_task(const struct ck_sched *s, uint32_t id) +{ + int slot = slot_of(s, id); + return slot < 0 ? 0 : &s->tasks[slot]; +} diff --git a/native/kernel/core/sched.h b/native/kernel/core/sched.h new file mode 100644 index 00000000..52baa5ac --- /dev/null +++ b/native/kernel/core/sched.h @@ -0,0 +1,61 @@ +/* sched.h -- run-queue scheduler, port of crates/aienos-kernel/src/scheduler.rs. + * Pure logic (no hardware): per-CPU queues, three priorities, fair ticks + * among equal priorities, a background budget under higher-priority load, + * placement by CPU efficiency class and work stealing. Host-tested in + * tests/test_sched.c; the M3 threads use it with one CPU. */ +#ifndef AIENOS_CK_SCHED_H +#define AIENOS_CK_SCHED_H + +#include + +#define CK_SCHED_MAX_CPUS 8 +#define CK_SCHED_MAX_TASKS 16 + +enum ck_prio { CK_PRIO_BACKGROUND = 0, CK_PRIO_NORMAL = 1, CK_PRIO_LATENCY = 2 }; + +enum ck_sched_err { + CK_SCHED_OK = 0, + CK_SCHED_NO_CPUS = -1, + CK_SCHED_FULL = -2, + CK_SCHED_DUPLICATE = -3, + CK_SCHED_INVALID_CPU = -4, + CK_SCHED_UNKNOWN = -5, +}; + +struct ck_task { + uint32_t id; + enum ck_prio prio; + unsigned cpu; + uint64_t ticks; +}; + +struct ck_sched { + unsigned cpus, ntasks; + uint8_t classes[CK_SCHED_MAX_CPUS]; + uint8_t used[CK_SCHED_MAX_TASKS]; + struct ck_task tasks[CK_SCHED_MAX_TASKS]; + int queues[CK_SCHED_MAX_CPUS][CK_SCHED_MAX_TASKS]; /* task slots, -1 empty */ + unsigned queue_len[CK_SCHED_MAX_CPUS]; + unsigned bg_wait[CK_SCHED_MAX_CPUS]; + unsigned bg_interval; + unsigned cursor; +}; + +/* cpus 0 is allowed (every placement then fails with CK_SCHED_NO_CPUS). + * Returns -1 if cpus or tasks exceed the maximums. Interval 0 means 1. */ +int ck_sched_init(struct ck_sched *s, unsigned cpus, const uint8_t *classes, unsigned tasks, + unsigned bg_interval); +/* CPU for a new task: Latency -> highest class, Background -> lowest class, + * Normal -> shortest queue; ties from the round-robin cursor. */ +int ck_sched_place(const struct ck_sched *s, enum ck_prio prio); +/* Returns the CPU it was queued on, or an error. */ +int ck_sched_enqueue(struct ck_sched *s, uint32_t id, enum ck_prio prio); +int ck_sched_remove(struct ck_sched *s, uint32_t id); +/* Picks the next task on cpu (stealing if idle): 1 and *id set, 0 if none, + * or an error. The picked task's tick count increases. */ +int ck_sched_tick(struct ck_sched *s, unsigned cpu, uint32_t *id); +/* 1 if a task moved to idle_cpu, 0 if not, or an error. */ +int ck_sched_steal(struct ck_sched *s, unsigned idle_cpu); +const struct ck_task *ck_sched_task(const struct ck_sched *s, uint32_t id); + +#endif diff --git a/native/kernel/tests/test_acpi.c b/native/kernel/tests/test_acpi.c index 29a80ee8..fe8fe7e9 100644 --- a/native/kernel/tests/test_acpi.c +++ b/native/kernel/tests/test_acpi.c @@ -180,6 +180,32 @@ int main(void) sum_fix(rsdp, 20, 8); CHECK(ck_acpi_root(r, &x) == 0x1234 && x == 0); CHECK(ck_acpi_root(0, &x) == 0); + /* CPU topology (acpi.rs madt_cpu_topology) and placement (thread.rs). */ + struct ck_cpu_topology tp; + uint8_t pc; + uint32_t pn; + CHECK(ck_madt_cpu_topology(madt, &tp) == 0); + CHECK(tp.cores == 1 && tp.distinct_classes == 1 && tp.class_id[0] == 0 && + tp.class_count[0] == 1 && tp.unknown_class == 0 && tp.has_first_mpidr && + tp.first_mpidr == 0); + CHECK(ck_place_task(&tp, 1, &pc, &pn) == 0 && pc == 0 && pn == 0); + memcpy(m2, madt, sizeof m2); + w32(m2 + 44 + 80 + 12, 8); /* second GICC online-capable, class 1 */ + m2[44 + 80 + 76] = 1; + m2[44 + 76] = 2; /* first GICC class 2: sorted after class 1 */ + CHECK(ck_madt_cpu_topology(m2, &tp) == 0); + CHECK(tp.cores == 2 && tp.distinct_classes == 2 && tp.class_id[0] == 1 && tp.class_id[1] == 2); + m2[44 + 1] = 0; + CHECK(ck_madt_cpu_topology(m2, &tp) == -1); + memset(&tp, 0, sizeof tp); + CHECK(ck_place_task(&tp, 0, &pc, &pn) == -1); /* empty topology is unplaced */ + tp.distinct_classes = 2; + tp.class_id[0] = 0; tp.class_count[0] = 2; + tp.class_id[1] = 1; tp.class_count[1] = 2; + static const uint8_t wc[8] = { 0, 0, 1, 1, 0, 0, 1, 1 }; + static const uint32_t wn[8] = { 0, 1, 0, 1, 0, 1, 0, 1 }; + for (uint32_t i = 0; i < 8; i++) + CHECK(ck_place_task(&tp, i, &pc, &pn) == 0 && pc == wc[i] && pn == wn[i]); test_spans(); return ck_t_verdict("CK_ACPI"); } diff --git a/native/kernel/tests/test_ipc.c b/native/kernel/tests/test_ipc.c new file mode 100644 index 00000000..a5ea8a1e --- /dev/null +++ b/native/kernel/tests/test_ipc.c @@ -0,0 +1,195 @@ +/* test_ipc.c -- host tests for core/ipc.c: the caps.rs and ipc.rs test lists + * (generation checks, attenuation, cross-table revoke, tombstones, bounded + * FIFO channel, gated IPC calls) plus the exact sequence the EL0 IPC demo runs. */ +#include "ck_test.h" +#include "ipc.h" + +#define H(i, g) ((struct ck_handle){ (i), (g) }) + +static struct ck_msg msg(uint32_t kind) +{ + struct ck_msg m = { 0 }; + m.kind = kind; + m.payload[0] = kind * 3u; + m.object = kind; + return m; +} + +static int msg_eq(const struct ck_msg *a, const struct ck_msg *b) +{ + return a->kind == b->kind && a->payload[0] == b->payload[0] && + a->payload[1] == b->payload[1] && a->payload[2] == b->payload[2] && + a->region_base == b->region_base && a->region_pages == b->region_pages && + a->object == b->object; +} + +int main(void) +{ + struct ck_cap_table t, u, v; + struct ck_handle h, h2, c, gc; + uint32_t res = 0; + + /* raw handles: round trip, generation 0 is forged */ + struct ck_handle r; + CHECK(ck_handle_raw(H(3, 7)) == ((7ull << 32) | 3)); + CHECK(ck_handle_from_raw((7ull << 32) | 3, &r) == 0 && r.index == 3 && r.generation == 7); + CHECK(ck_handle_from_raw(5, &r) == -1); + + /* stale handle after slot reuse */ + ck_cap_init(&t, 1, 2); + CHECK(ck_cap_insert(&t, 10, CK_R_READ, &h) == 0); + CHECK(ck_cap_remove(&t, h) == 0); + CHECK(ck_cap_insert(&t, 11, CK_R_READ, &h2) == 0); + CHECK(h2.index == h.index && h2.generation != h.generation); + CHECK(ck_cap_lookup(&t, h, CK_R_READ, &res) == CK_CAP_INVALID); + CHECK(ck_cap_lookup(&t, h2, CK_R_READ, &res) == 0 && res == 11); + CHECK(ck_cap_lookup(&t, h2, CK_R_WRITE, &res) == CK_CAP_MISSING_RIGHTS); + CHECK(ck_cap_lookup(&t, H(9, 1), CK_R_READ, &res) == CK_CAP_INVALID); + + /* generation exhaustion retires the slot */ + ck_cap_init(&t, 1, 1); + t.generations[0] = 0xfffffffeu; + CHECK(ck_cap_insert(&t, 1, CK_R_READ, &h) == 0 && h.generation == 0xffffffffu); + CHECK(ck_cap_remove(&t, h) == 0); + CHECK(ck_cap_insert(&t, 1, CK_R_READ, &h2) == CK_CAP_FULL); + + /* derive cannot add rights; needs DERIVE */ + ck_cap_init(&t, 1, 8); + ck_cap_insert(&t, 5, CK_R_READ | CK_R_DERIVE, &h); + CHECK(ck_cap_derive(&t, h, CK_R_READ | CK_R_WRITE, &c) == CK_CAP_ESCALATION); + CHECK(ck_cap_derive(&t, h, CK_R_READ, &c) == 0); + CHECK(ck_cap_derive(&t, c, CK_R_READ, &gc) == CK_CAP_MISSING_RIGHTS); + CHECK(ck_cap_insert(&t, 5, 0x40, &h2) == CK_CAP_ESCALATION); + + /* revoke cascades two levels across tables */ + ck_cap_init(&t, 1, 8); + ck_cap_init(&u, 2, 8); + ck_cap_init(&v, 3, 8); + ck_cap_insert(&t, 5, CK_R_ALL, &h); + CHECK(ck_cap_derive_into(&t, h, &u, CK_R_READ | CK_R_DERIVE, &c) == 0); + CHECK(ck_cap_derive_into(&u, c, &v, CK_R_READ, &gc) == 0); + ck_cap_insert(&u, 6, CK_R_READ, &h2); /* unrelated survivor */ + struct ck_cap_table *const three[3] = { &t, &u, &v }; + CHECK(ck_cap_revoke(2, c, three, 3) == CK_CAP_MISSING_RIGHTS); + CHECK(ck_cap_revoke(1, h, three, 3) == 0); + CHECK(ck_cap_lookup(&t, h, 0, 0) == CK_CAP_INVALID); + CHECK(ck_cap_lookup(&u, c, 0, 0) == CK_CAP_INVALID); + CHECK(ck_cap_lookup(&v, gc, 0, 0) == CK_CAP_INVALID); + CHECK(ck_cap_lookup(&u, h2, CK_R_READ, &res) == 0 && res == 6); + struct ck_cap_table *const dup[2] = { &t, &t }; + CHECK(ck_cap_revoke(1, h, dup, 2) == CK_CAP_DUPLICATE_TABLE); + + /* revoke with single-slot tables */ + ck_cap_init(&t, 1, 1); + ck_cap_init(&u, 2, 1); + ck_cap_insert(&t, 5, CK_R_ALL, &h); + CHECK(ck_cap_derive_into(&t, h, &u, CK_R_READ, &c) == 0); + struct ck_cap_table *const two[2] = { &t, &u }; + CHECK(ck_cap_revoke(1, h, two, 2) == 0); + CHECK(ck_cap_insert(&t, 5, CK_R_READ, &h2) == 0 && ck_cap_insert(&u, 5, CK_R_READ, &h2) == 0); + + /* cyclic parent metadata fails closed before removing anything */ + ck_cap_init(&t, 1, 2); + ck_cap_init(&u, 2, 2); + ck_cap_insert(&t, 5, CK_R_ALL, &h); + ck_cap_insert(&u, 5, CK_R_ALL, &c); + ck_cap_insert(&u, 5, CK_R_ALL, &gc); + u.slots[c.index].has_parent = 1; + u.slots[c.index].parent_table = 2; + u.slots[c.index].parent = gc; + u.slots[gc.index].has_parent = 1; + u.slots[gc.index].parent_table = 2; + u.slots[gc.index].parent = c; + CHECK(ck_cap_revoke(1, h, two, 2) == CK_CAP_FULL); + CHECK(ck_cap_lookup(&t, h, 0, 0) == 0); + + /* transfer needs GRANT; full table reported */ + ck_cap_init(&t, 1, 8); + ck_cap_init(&u, 2, 1); + ck_cap_insert(&t, 5, CK_R_READ, &h); + CHECK(ck_cap_transfer(&t, h, &u, &c) == CK_CAP_MISSING_RIGHTS); + ck_cap_insert(&t, 5, CK_R_READ | CK_R_GRANT, &h2); + CHECK(ck_cap_transfer(&t, h2, &u, &c) == 0); + CHECK(ck_cap_transfer(&t, h2, &u, &gc) == CK_CAP_FULL); + + /* removing a derived parent tombstones it; subtree stays revocable */ + ck_cap_init(&t, 1, 8); + ck_cap_init(&u, 2, 8); + ck_cap_insert(&t, 5, CK_R_ALL, &h); + ck_cap_derive_into(&t, h, &u, CK_R_READ | CK_R_DERIVE | CK_R_REVOKE, &c); + ck_cap_derive_into(&u, c, &t, CK_R_READ, &gc); + CHECK(ck_cap_remove(&u, c) == 0); + CHECK(ck_cap_lookup(&u, c, 0, 0) == CK_CAP_INVALID); + CHECK(u.slots[c.index].tombstone == 1); + CHECK(ck_cap_lookup(&t, gc, CK_R_READ, 0) == 0); + CHECK(ck_cap_revoke(1, h, two, 2) == 0); + CHECK(ck_cap_lookup(&t, gc, 0, 0) == CK_CAP_INVALID); + CHECK(u.slots[c.index].live == 0); + /* removing a never-derived capability frees its slot */ + ck_cap_init(&t, 1, 1); + ck_cap_insert(&t, 5, CK_R_READ, &h); + CHECK(ck_cap_remove(&t, h) == 0 && t.slots[0].live == 0); + CHECK(ck_cap_remove(&t, h) == CK_CAP_INVALID); + + /* channel is FIFO and bounded */ + struct ck_channel ch; + struct ck_msg m1 = msg(1), m2 = msg(2), out; + ck_chan_init(&ch, 2); + CHECK(ck_chan_send(&ch, &m1) == 0 && ck_chan_send(&ch, &m2) == 0); + struct ck_msg m3 = msg(3); + CHECK(ck_chan_send(&ch, &m3) == -1); + CHECK(ck_chan_recv(&ch, &out) == 0 && msg_eq(&out, &m1)); + CHECK(ck_chan_send(&ch, &m3) == 0); + CHECK(ck_chan_recv(&ch, &out) == 0 && msg_eq(&out, &m2)); + CHECK(ck_chan_recv(&ch, &out) == 0 && msg_eq(&out, &m3)); + CHECK(ck_chan_recv(&ch, &out) == -1); + + /* gated IPC */ + static struct ck_ipc ipc; + struct ck_handle a_send, a_obj, b_recv, child; + uint64_t val = 0; + ck_ipc_reset(&ipc, &a_send, &a_obj, &b_recv); + struct ck_msg m7 = msg(7); + CHECK(ck_ipc_recv(&ipc, 0, a_send, &out) == CK_IPC_MISSING_RIGHTS); + CHECK(ck_ipc_send(&ipc, 1, b_recv, &m7) == CK_IPC_MISSING_RIGHTS); + CHECK(ck_ipc_send(&ipc, 0, a_obj, &m7) == CK_IPC_WRONG_RESOURCE); + CHECK(ck_ipc_send(&ipc, 0, H(a_send.index, a_send.generation + 1), &m7) == + CK_IPC_INVALID_HANDLE); + CHECK(ck_ipc_recv(&ipc, 1, b_recv, &out) == CK_IPC_CHANNEL_EMPTY); + /* delegation without DERIVE, and escalation, are MissingRights */ + struct ck_handle plain; + ck_cap_insert(&ipc.tables[0], CK_IPC_OBJECT_RESOURCE, CK_R_READ, &plain); + CHECK(ck_ipc_delegate(&ipc, 0, plain, 1, CK_R_READ, &child) == CK_IPC_MISSING_RIGHTS); + CHECK(ck_ipc_delegate(&ipc, 0, a_obj, 1, CK_R_READ | CK_R_MAP, &child) == + CK_IPC_MISSING_RIGHTS); + CHECK(ck_ipc_delegate(&ipc, 0, a_obj, 1, CK_R_READ | CK_R_WRITE, &child) == 0); + CHECK(ck_ipc_object_write(&ipc, 1, child, 3, 77) == 0 && ipc.object[3] == 77); + CHECK(ck_ipc_object_read(&ipc, 1, child, 4, &val) == CK_IPC_WRONG_RESOURCE); + + /* end to end: the exact EL0 demo sequence */ + ck_ipc_reset(&ipc, &a_send, &a_obj, &b_recv); + struct ck_msg sent = { .kind = 7, .payload = { 0x1111, 0x2222, 0x3333 }, + .region_base = 0xa000, .region_pages = 2, .object = 0 }; + CHECK(ck_ipc_send(&ipc, 0, a_send, &sent) == 0); + CHECK(ck_ipc_delegate(&ipc, 0, a_obj, 1, CK_R_READ, &child) == 0); + CHECK(ck_ipc_recv(&ipc, 1, b_recv, &out) == 0 && msg_eq(&out, &sent)); + CHECK(ck_ipc_object_read(&ipc, 1, child, 0, &val) == 0 && val == 0xc0ffee01); + CHECK(ck_ipc_object_write(&ipc, 1, child, 0, 0xbad) == CK_IPC_MISSING_RIGHTS); + struct ck_handle forged; + CHECK(ck_handle_from_raw(ck_handle_raw(child) ^ (1ull << 32), &forged) == -1); + forged = H(child.index, child.generation + 1); + CHECK(ck_ipc_object_read(&ipc, 1, forged, 0, &val) == CK_IPC_INVALID_HANDLE); + CHECK(ck_ipc_revoke(&ipc, 1, child) == CK_IPC_MISSING_RIGHTS); + CHECK(ck_ipc_revoke(&ipc, 0, a_obj) == 0); + CHECK(ck_ipc_object_read(&ipc, 1, child, 1, &val) == CK_IPC_INVALID_HANDLE); + CHECK(ck_ipc_object_read(&ipc, 0, a_obj, 1, &val) == CK_IPC_INVALID_HANDLE); + CHECK(ck_ipc_send(&ipc, 0, a_send, &sent) == 0); /* unrelated caps survive */ + + /* receiver table full: source untouched */ + ck_ipc_reset(&ipc, &a_send, &a_obj, &b_recv); + for (int i = 0; i < CK_CAP_SLOTS - 1; i++) + ck_cap_insert(&ipc.tables[1], 1, CK_R_READ, &h); + CHECK(ck_ipc_delegate(&ipc, 0, a_obj, 1, CK_R_READ, &child) == CK_IPC_DELEGATION_FAILED); + CHECK(ipc.tables[0].slots[a_obj.index].derived == 0); + return ck_t_verdict("test_ipc"); +} diff --git a/native/kernel/tests/test_sched.c b/native/kernel/tests/test_sched.c new file mode 100644 index 00000000..3f603884 --- /dev/null +++ b/native/kernel/tests/test_sched.c @@ -0,0 +1,107 @@ +/* test_sched.c -- host tests for core/sched.c (the scheduler.rs test list, + * plus the cooperative-thread order the M3 boot check expects). */ +#include "ck_test.h" +#include "sched.h" + +static uint32_t tick(struct ck_sched *s, unsigned cpu) +{ + uint32_t id = 0; + int r = ck_sched_tick(s, cpu, &id); + return r == 1 ? id : (r == 0 ? 0 : 0xffffffffu); +} + +int main(void) +{ + struct ck_sched s; + uint8_t c0011[4] = { 0, 0, 1, 1 }, c0[1] = { 0 }, c01[2] = { 0, 1 }, c00[2] = { 0, 0 }; + + /* placement: latency on fast cores, background on efficient ones */ + ck_sched_init(&s, 4, c0011, 8, 8); + int cpu = ck_sched_enqueue(&s, 1, CK_PRIO_LATENCY); + CHECK(cpu == 2 || cpu == 3); + cpu = ck_sched_enqueue(&s, 2, CK_PRIO_BACKGROUND); + CHECK(cpu == 0 || cpu == 1); + + /* equal priority tasks share ticks fairly */ + ck_sched_init(&s, 1, c0, 4, 8); + ck_sched_enqueue(&s, 1, CK_PRIO_NORMAL); + ck_sched_enqueue(&s, 2, CK_PRIO_NORMAL); + for (int i = 0; i < 20; i++) + tick(&s, 0); + CHECK(ck_sched_task(&s, 1)->ticks == 10); + CHECK(ck_sched_task(&s, 2)->ticks == 10); + + /* fair order alternates (the threads demo relies on it) */ + ck_sched_init(&s, 1, c0, 4, 8); + ck_sched_enqueue(&s, 0, CK_PRIO_NORMAL); + ck_sched_enqueue(&s, 1, CK_PRIO_NORMAL); + char order[9] = { 0 }; + for (int i = 0; i < 8; i++) + order[i] = (char)('A' + tick(&s, 0)); + CHECK(order[0] == 'A' && order[1] == 'B' && order[6] == 'A' && order[7] == 'B'); + + /* priority prevents basic inversion */ + ck_sched_init(&s, 1, c0, 4, 8); + ck_sched_enqueue(&s, 1, CK_PRIO_BACKGROUND); + ck_sched_enqueue(&s, 2, CK_PRIO_LATENCY); + CHECK(tick(&s, 0) == 2); + + /* background runs within the configured interval under latency load */ + ck_sched_init(&s, 1, c0, 2, 7); + ck_sched_enqueue(&s, 1, CK_PRIO_BACKGROUND); + ck_sched_enqueue(&s, 2, CK_PRIO_LATENCY); + int bg = 0; + for (int i = 0; i < 7; i++) + bg |= tick(&s, 0) == 1; + CHECK(bg); + + /* latency keeps a large majority with a background budget */ + ck_sched_init(&s, 1, c0, 2, 8); + ck_sched_enqueue(&s, 1, CK_PRIO_BACKGROUND); + ck_sched_enqueue(&s, 2, CK_PRIO_LATENCY); + for (int i = 0; i < 80; i++) + tick(&s, 0); + CHECK(ck_sched_task(&s, 2)->ticks > 80 * 3 / 4); + CHECK(ck_sched_task(&s, 2)->ticks > ck_sched_task(&s, 1)->ticks); + + /* idle cpu steals and runs work */ + ck_sched_init(&s, 2, c01, 4, 8); + ck_sched_enqueue(&s, 1, CK_PRIO_BACKGROUND); + ck_sched_enqueue(&s, 2, CK_PRIO_BACKGROUND); + CHECK(ck_sched_steal(&s, 1) == 1); + CHECK(ck_sched_task(&s, 1)->cpu == 1 || ck_sched_task(&s, 2)->cpu == 1); + uint32_t id; + CHECK(ck_sched_tick(&s, 1, &id) == 1); + + /* empty queues and invalid cpu */ + ck_sched_init(&s, 2, c01, 2, 8); + CHECK(ck_sched_tick(&s, 0, &id) == 0); + CHECK(ck_sched_steal(&s, 1) == 0); + CHECK(ck_sched_tick(&s, 2, &id) == CK_SCHED_INVALID_CPU); + + /* round-robin placement and duplicate rejection */ + ck_sched_init(&s, 2, c00, 4, 8); + CHECK(ck_sched_enqueue(&s, 1, CK_PRIO_NORMAL) == 0); + CHECK(ck_sched_enqueue(&s, 2, CK_PRIO_NORMAL) == 1); + CHECK(ck_sched_enqueue(&s, 1, CK_PRIO_NORMAL) == CK_SCHED_DUPLICATE); + + /* removed tasks free their slot and leave the queue */ + ck_sched_init(&s, 1, c0, 2, 8); + ck_sched_enqueue(&s, 1, CK_PRIO_NORMAL); + ck_sched_enqueue(&s, 2, CK_PRIO_NORMAL); + CHECK(ck_sched_enqueue(&s, 3, CK_PRIO_NORMAL) == CK_SCHED_FULL); + CHECK(ck_sched_remove(&s, 1) == 0); + CHECK(s.queue_len[0] == 1); + CHECK(ck_sched_task(&s, 1) == 0); + CHECK(ck_sched_enqueue(&s, 3, CK_PRIO_NORMAL) == 0); + for (int i = 0; i < 4; i++) + CHECK(tick(&s, 0) != 1); + CHECK(ck_sched_remove(&s, 1) == CK_SCHED_UNKNOWN); + + /* no cpus, oversize */ + CHECK(ck_sched_init(&s, 0, c0, 2, 8) == 0); + CHECK(ck_sched_enqueue(&s, 1, CK_PRIO_NORMAL) == CK_SCHED_NO_CPUS); + CHECK(ck_sched_init(&s, CK_SCHED_MAX_CPUS + 1, c0, 2, 8) == -1); + CHECK(ck_sched_init(&s, 1, c0, CK_SCHED_MAX_TASKS + 1, 8) == -1); + return ck_t_verdict("test_sched"); +} diff --git a/scripts/ck_gates.sh b/scripts/ck_gates.sh index ab5787e7..d980232a 100755 --- a/scripts/ck_gates.sh +++ b/scripts/ck_gates.sh @@ -41,7 +41,7 @@ set -uo pipefail # =========================================================================== CK_GATE_TABLE=' M1|boot|- -M3|missing|no threads, EL0 tasks, preemption, MADT placement or typed IPC in the C kernel +M3|boot|- SMMU|store|- NVME_SHUTDOWN|store|- P2_ARTIFACT|missing|no signed artifact loader (EL0, W^X, admission receipts) in the C kernel @@ -318,7 +318,7 @@ self_test() { } expect_missing_all() { local g - for g in M3 P2_ARTIFACT M0_ROLLBACK M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY KEYBOARD; do expect "${g}" NOT_RUN; done + for g in P2_ARTIFACT M0_ROLLBACK M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY KEYBOARD; do expect "${g}" NOT_RUN; done } scenario() { # NAME BOOT_SCRIPT STORE_SCRIPT scen="$1" @@ -329,36 +329,36 @@ self_test() { # A: all present gates PASS; the store child also claims PASS for gates # with no C implementation, which must stay NOT_RUN. - scenario A "$(fake bootA 0 'PASS x' 'AIENOS_CK_M1: PASS')" \ + scenario A "$(fake bootA 0 'PASS x' 'AIENOS_CK_M3: PASS' 'AIENOS_CK_M1: PASS')" \ "$(fake storeA 0 'AIENOS_CK_M4_NVME: PASS' 'AIENOS_CK_M4_STORE: PASS' 'AIENOS_CK_ARGUS1_REVOKE: PASS (narrow)' \ - 'AIENOS_CK_SMMU: PASS' 'AIENOS_CK_NVME_SHUTDOWN: PASS' 'AIENOS_CK_M3: PASS' 'AIENOS_CK_KEYBOARD: PASS' 'PASS NVMe DMA granted confined' \ + 'AIENOS_CK_SMMU: PASS' 'AIENOS_CK_NVME_SHUTDOWN: PASS' 'AIENOS_CK_KEYBOARD: PASS' 'PASS NVMe DMA granted confined' \ 'PASS DMA outside the window faulted, page intact, controller still usable (differs)' 'PASS NVMe DMA denied without an SMMU' \ 'PASS NVMe DMA granted through the TEST-ONLY bypass')" - expect M1 PASS; expect M4_NVME PASS; expect M4_STORE PASS; expect ARGUS1_REVOKE PASS; expect SMMU PASS; expect NVME_SHUTDOWN PASS; expect_missing_all + expect M1 PASS; expect M3 PASS; expect M4_NVME PASS; expect M4_STORE PASS; expect ARGUS1_REVOKE PASS; expect SMMU PASS; expect NVME_SHUTDOWN PASS; expect_missing_all count_rows - [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "6/0/7/13" && ${overall} == NOT_ALL_GATES_PASS ]] \ - && ok "A: counts 6/0/7 of 13, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" + [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "7/0/6/13" && ${overall} == NOT_ALL_GATES_PASS ]] \ + && ok "A: counts 7/0/6 of 13, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" [[ "$(nvme_dma_mode)" == "Confined (QEMU SMMUv3 stage 1, out-of-window DMA faulted); no-SMMU boot denied (NoSmmu); TEST-ONLY bypass image checked separately" ]] && ok "A: confined DMA mode recorded from the store PASS lines" || bad "A: dma mode '$(nvme_dma_mode)'" grep -qxF "AIENOS_CK_M4_NVME: PASS (${M4_NVME_PASS_NOTE})" "${tmp}/A.out" \ && ok "A: M4_NVME PASS line carries the confined-mode note" || bad "A: M4_NVME PASS line lacks the note" - grep -qx 'AIENOS_CK_M3: NOT_RUN (MISSING_IMPLEMENTATION: no threads, EL0 tasks, preemption, MADT placement or typed IPC in the C kernel)' "${tmp}/A.out" \ - && ok "A: missing gate prints NOT_RUN (MISSING_IMPLEMENTATION: reason)" || bad "A: M3 line wrong" + grep -qx 'AIENOS_CK_KEYBOARD: NOT_RUN (MISSING_IMPLEMENTATION: no xHCI/USB HID keyboard driver in the C kernel)' "${tmp}/A.out" \ + && ok "A: missing gate prints NOT_RUN (MISSING_IMPLEMENTATION: reason)" || bad "A: KEYBOARD line wrong" [[ "$(grep -c '^AIENOS_CK_[A-Z0-9_]*: ' "${tmp}/A.out")" == 13 ]] && ok "A: exactly 13 verdict lines" || bad "A: verdict line count" # B: boot FAIL; store script missing -> its three gates NOT_RUN, never PASS. - scenario B "$(fake bootB 1 'FAIL kernel: alive' 'AIENOS_CK_M1: FAIL')" "${tmp}/kids/does_not_exist.sh" - expect M1 FAIL; expect M4_NVME NOT_RUN; expect M4_STORE NOT_RUN; expect ARGUS1_REVOKE NOT_RUN; expect SMMU NOT_RUN; expect NVME_SHUTDOWN NOT_RUN; expect_missing_all + scenario B "$(fake bootB 1 'FAIL kernel: alive' 'AIENOS_CK_M3: FAIL' 'AIENOS_CK_M1: FAIL')" "${tmp}/kids/does_not_exist.sh" + expect M1 FAIL; expect M3 FAIL; expect M4_NVME NOT_RUN; expect M4_STORE NOT_RUN; expect ARGUS1_REVOKE NOT_RUN; expect SMMU NOT_RUN; expect NVME_SHUTDOWN NOT_RUN; expect_missing_all [[ "$(nvme_dma_mode)" == "not run" ]] && ok "B: dma mode 'not run' when the store script is missing" || bad "B: dma mode" # C: boot NOT_RUN (quiet flag held, exit 3); store mixed with exit 1. - scenario C "$(fake bootC 3 'NOT_RUN quiet flag held' 'AIENOS_CK_M1: NOT_RUN')" \ + scenario C "$(fake bootC 3 'NOT_RUN quiet flag held' 'AIENOS_CK_M3: NOT_RUN' 'AIENOS_CK_M1: NOT_RUN')" \ "$(fake storeC 1 'AIENOS_CK_M4_NVME: PASS' 'AIENOS_CK_M4_STORE: FAIL' 'AIENOS_CK_ARGUS1_REVOKE: PASS')" - expect M1 NOT_RUN; expect M4_NVME PASS; expect M4_STORE FAIL; expect ARGUS1_REVOKE PASS + expect M1 NOT_RUN; expect M3 NOT_RUN; expect M4_NVME PASS; expect M4_STORE FAIL; expect ARGUS1_REVOKE PASS # D: no marker at all (exit 0); PASS lines with an unexplained exit 2. scenario D "$(fake bootD 0 'all good, honest')" \ "$(fake storeD 2 'AIENOS_CK_M4_NVME: PASS' 'AIENOS_CK_M4_STORE: PASS' 'AIENOS_CK_ARGUS1_REVOKE: PASS')" - expect M1 FAIL; expect M4_NVME FAIL; expect M4_STORE FAIL; expect ARGUS1_REVOKE FAIL + expect M1 FAIL; expect M3 FAIL; expect M4_NVME FAIL; expect M4_STORE FAIL; expect ARGUS1_REVOKE FAIL # E: contradictory lines; a marker inside a line (echoed serial) does not # count; NOT_RUN with exit 3. @@ -370,6 +370,12 @@ self_test() { scenario F "$(fake bootF 3 'AIENOS_CK_M1: PASS')" "$(fake storeF 0 'AIENOS_CK_M4_NVME: PASSED' 'AIENOS_CK_M4_STORE: PASS')" expect M1 FAIL; expect M4_NVME FAIL; expect M4_STORE PASS; expect ARGUS1_REVOKE FAIL + # G: M3 FAIL with M1 PASS in one boot (exit 1 explained by the M3 FAIL + # line); an M3 PASS claimed by the store child is ignored (M3 is a boot gate). + scenario G "$(fake bootG 1 'FAIL typed IPC' 'AIENOS_CK_M3: FAIL' 'AIENOS_CK_M1: PASS')" \ + "$(fake storeG 0 'AIENOS_CK_M3: PASS' 'AIENOS_CK_M4_NVME: PASS')" + expect M1 PASS; expect M3 FAIL; expect M4_NVME PASS + # Receipt: named by its content hash, valid JSON, physical NOT_RUN, never overwritten. scenario R "$(fake bootR 0 'AIENOS_CK_M1: PASS')" "$(fake storeR 0 'AIENOS_CK_M4_NVME: PASS')" count_rows diff --git a/scripts/lib_ck_m1_checks.sh b/scripts/lib_ck_m1_checks.sh index 02a95e23..d61e34da 100644 --- a/scripts/lib_ck_m1_checks.sh +++ b/scripts/lib_ck_m1_checks.sh @@ -4,7 +4,9 @@ # where qemu_ck_boot_test.sh's header lists a deliberate difference. # Not executable on its own. Callers set: work (serial text in # ${work}/serial.txt), commit, qemu_status; ck_m1_checks sets failed=1 on any -# failure and never resets it. +# failure and never resets it. ck_m3_checks (Lane 25) runs the five M3 checks +# of qemu_boot_test.sh with the same patterns and sets m3_failed=1 on any +# failure; it does not touch failed, so the M1 verdict is unchanged. check() { # description, pattern if grep -q -- "$2" "${work}/serial.txt"; then @@ -22,20 +24,12 @@ check_absent() { # description, pattern echo "PASS $1" fi } -not_run() { # description: M3 feature the C kernel does not have yet - echo "NOT_RUN $1 (not implemented in the C kernel yet)" -} ck_m1_checks() { check "pre-exit report printed" "report_kind: pre_exit" check "image is this commit" "aienos_commit: ${commit}" check "left firmware and entered the kernel" "kernel: alive" check "kernel entered EL1h" "kernel_el: EL1h" - not_run "cooperative threads interleaved" - not_run "EL0 capability and fault isolation" - not_run "timer-driven preemption across runnable tasks" - not_run "deterministic MADT placement of preempt workers" - not_run "typed IPC with attenuated revocable delegation" check "EL1 page tables and caches enabled" "mmu: enabled" check "GICv3 enabled" "gic: v3" if grep -qE 'timer_irq: ([0-9]+) ticks' "${work}/serial.txt"; then @@ -100,3 +94,20 @@ ck_m1_checks() { failed=1 fi } + +ck_m3_checks() { + # Same five patterns as qemu_boot_test.sh lines 63-67 (the Rust M3 rows). + m3_check() { # description, pattern + if grep -q -- "$2" "${work}/serial.txt"; then + echo "PASS $1" + else + echo "FAIL $1" + m3_failed=1 + fi + } + m3_check "cooperative threads interleaved" "threads: ok" + m3_check "EL0 capability and fault isolation" "el0: ok write=granted forged=denied fault=contained exit=0" + m3_check "timer-driven preemption across runnable tasks" "preempt: ok" + m3_check "deterministic MADT placement of preempt workers" "placement: worker0=class0/core0 worker1=class0/core1" + m3_check "typed IPC with attenuated revocable delegation" "ipc: ok message=delivered cap=delegated rights=attenuated forged=denied revoked=denied" +} diff --git a/scripts/qemu_ck_boot_test.sh b/scripts/qemu_ck_boot_test.sh index 92cccdfb..88b85cb9 100755 --- a/scripts/qemu_ck_boot_test.sh +++ b/scripts/qemu_ck_boot_test.sh @@ -12,13 +12,17 @@ # another run holds it; AIENOS_QUIET_FLAG overrides the flag path and # AIENOS_QUIET_TAG the text written into it (the flag is removed only if # it still holds exactly that text, and at most once per run); -# - the M3 checks (threads, el0, preempt, placement, ipc) print NOT_RUN: the -# C kernel does not implement them yet, so they do not count; +# - the five M3 checks (threads, el0, preempt, placement, ipc) use the same +# patterns and give their own verdict AIENOS_CK_M3, which is PASS only if +# all five pass AND every M1 check of the same boot passes (no fault, no +# panic, QEMU exit 0); the C kernel prints one extra line, ipc_detail, +# which no check reads (native/kernel/GATES.md rows 16-20 list the +# differences in how the C kernel does the work); # - one added check: guard_page (the C kernel's guard-page fault self test); # - stricter: any QEMU exit status other than 0 fails (the Rust script fails # only on the timeout status 124); PSCI reset with -no-reboot exits 0; # - the checks live in scripts/lib_ck_m1_checks.sh (shared with the Store gate); -# - final line is AIENOS_CK_M1: PASS|FAIL|NOT_RUN. +# - last two lines are AIENOS_CK_M3: and AIENOS_CK_M1: PASS|FAIL|NOT_RUN. # Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). set -euo pipefail @@ -27,8 +31,8 @@ cd "${repo_root}" 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 "AIENOS_CK_M1: NOT_RUN"; exit 2; } -[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "AIENOS_CK_M1: NOT_RUN"; exit 2; } +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; echo "AIENOS_CK_M3: NOT_RUN"; echo "AIENOS_CK_M1: NOT_RUN"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "AIENOS_CK_M3: NOT_RUN"; echo "AIENOS_CK_M1: NOT_RUN"; exit 2; } cross="" if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi @@ -41,6 +45,7 @@ quiet_flag="${AIENOS_QUIET_FLAG:-${HOME}/workspace/.spark-quiet}" quiet_tag="${AIENOS_QUIET_TAG:-qemu_ck_boot_test $$}" if ! ( set -C; echo "${quiet_tag}" > "${quiet_flag}" ) 2>/dev/null; then echo "NOT_RUN quiet flag ${quiet_flag} is held: $(head -c 200 "${quiet_flag}" 2>/dev/null || true)" + echo "AIENOS_CK_M3: NOT_RUN" echo "AIENOS_CK_M1: NOT_RUN" exit 3 fi @@ -92,9 +97,15 @@ failed=0 source "${repo_root}/scripts/lib_ck_m1_checks.sh" echo "qemu exit ${qemu_status} after ${elapsed} s (commit ${commit:0:12})" ck_m1_checks +m3_failed=0 +ck_m3_checks -if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then +if [[ "${failed}" != 0 || "${m3_failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then echo "---- serial console ----" cat "${work}/serial.txt" fi -[[ "${failed}" == 0 ]] && echo "AIENOS_CK_M1: PASS" || { echo "AIENOS_CK_M1: FAIL"; exit 1; } +m3_verdict=PASS +[[ "${m3_failed}" == 0 && "${failed}" == 0 ]] || m3_verdict=FAIL +echo "AIENOS_CK_M3: ${m3_verdict}" +[[ "${failed}" == 0 ]] && echo "AIENOS_CK_M1: PASS" || echo "AIENOS_CK_M1: FAIL" +[[ "${failed}" == 0 && "${m3_verdict}" == PASS ]] || exit 1