aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#77 (code only)
Apply it
git checkout -b patch-85026897664322c0 a07d2889149c8fc3788b35c2ebc82344d932717b curl -fsSL https://interplane.io/drakestapleton/aienux/patches/85026897664322c0.patch | git am
Provenance
github-import 1
aien-dev/aienux
77
d3369e9334127d89c01db1749cd5a6fa00b5c15f
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":77,"url":"https://github.com/aien-dev/aienux/pull/77","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:43Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index 379592f3..1fd60880 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -15,6 +15,9 @@ uefi-base = ["dep:uefi"] # UART after boot services exit, so the two features must not be combined. firmware = ["uefi-base", "uefi/panic_handler"] handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc", "uefi/global_allocator"] +# SEED-0A candidate: polled USB keyboard after firmware exit (ADR 0012). +# Only the QEMU keyboard test enables it; hardware staging never does. +usb-keyboard = ["handoff"] [dependencies] uefi = { version = "0.41", default-features = false, optional = true } diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index 68f02dc8..72b08f5e 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -45,6 +45,9 @@ use uefi::runtime::{ResetType, VariableAttributes, VariableVendor}; use uefi::table::cfg::ConfigTableEntry; use uefi::{cstr16, guid, CStr16}; +#[cfg(feature = "usb-keyboard")] +mod usb_keyboard; + /// Commit this image was built from; `scripts/stage_one_time_boot.sh` sets it. const COMMIT: &str = match option_env!("AIENOS_COMMIT") { Some(commit) => commit, @@ -396,6 +399,8 @@ unsafe fn table_at<'a>(addr: usize) -> Option<&'a [u8]> { struct AcpiFacts { cpu: Option<acpi::CpuTopology>, spcr: Option<acpi::SpcrConsole>, + #[cfg(feature = "usb-keyboard")] + mcfg: Option<&'static [u8]>, } fn discover_acpi(boot_mpidr: u64) -> AcpiFacts { @@ -430,6 +435,8 @@ fn discover_acpi(boot_mpidr: u64) -> AcpiFacts { match &table[..4] { b"APIC" => facts.cpu = acpi::madt_cpu_topology_for(table, Some(boot_mpidr)).ok(), b"SPCR" => facts.spcr = acpi::spcr_console(table).ok(), + #[cfg(feature = "usb-keyboard")] + b"MCFG" => facts.mcfg = Some(table), _ => {} } } @@ -706,6 +713,8 @@ fn main() -> Status { stage(FRAMEBUFFER_DISCOVERY); let framebuffer = discover_framebuffer(); *FRAMEBUFFER.lock() = framebuffer; + #[cfg(feature = "usb-keyboard")] + let xhci = usb_keyboard::find_xhci(); let mut pre = Report::new(); header(&mut pre, "pre_exit"); @@ -878,5 +887,7 @@ fn main() -> Status { let _ = writeln!(s, "boot halted: no usable memory region"); } } + #[cfg(feature = "usb-keyboard")] + usb_keyboard::run(xhci, acpi_facts.mcfg, &mut screen); finish(screen) } diff --git a/crates/aienos-boot/src/usb_keyboard.rs b/crates/aienos-boot/src/usb_keyboard.rs new file mode 100644 index 00000000..d5a94870 --- /dev/null +++ b/crates/aienos-boot/src/usb_keyboard.rs @@ -0,0 +1,204 @@ +//! SEED-0A candidate `input.keyboard.usb` (ADR 0012): after firmware exit, +//! drive the xHCI controller with the polled AIENOS driver and echo typed +//! keys on the SPCR console and the screen. +//! +//! Built only with the `usb-keyboard` feature, which the QEMU keyboard test +//! enables and hardware staging does not: the candidate is proven in QEMU +//! and never admitted to Machine 1 before M3 can confine it. + +use aienos_kernel::acpi::{self, EcamWindow}; +use aienos_kernel::arch::aarch64::{counter_frequency_hz, counter_ticks, MmioReg}; +use aienos_kernel::console::EarlyConsole; +use aienos_kernel::display::Screen; +use aienos_kernel::usb::hid::{BootKeyboardDecoder, KeyEvent, TextSink}; +use aienos_kernel::usb::xhci::controller::{DmaMemory, Keyboard}; +use aienos_kernel::usb::xhci::{self, PCI_COMMAND_BUS_MASTER, PCI_COMMAND_MEMORY}; +use core::fmt::Write; +use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; +use uefi::proto::pci::root_bridge::PciRootBridgeIo; +use uefi::proto::pci::PciIoAddress; + +/// Seconds to wait for a line; `AIENOS_KEYBOARD_SECS` at build time. +fn listen_secs() -> u64 { + option_env!("AIENOS_KEYBOARD_SECS") + .and_then(|s| s.parse().ok()) + .unwrap_or(30) +} + +/// DMA memory for the driver, used only after firmware exit. +static mut DMA: DmaMemory = DmaMemory::new(); + +/// Where the first xHCI controller sits, found before firmware exit. +#[derive(Clone, Copy)] +pub struct XhciLocation { + segment: u16, + bus: u8, + device: u8, + function: u8, + mmio: u64, +} + +/// Walk every root bridge for the first xHCI controller (pre-exit only). +pub fn find_xhci() -> Option<XhciLocation> { + for handle in uefi::boot::find_handles::<PciRootBridgeIo>().ok()? { + // Shared open, read-only use, as in GB10 discovery. + let params = OpenProtocolParams { + handle, + agent: uefi::boot::image_handle(), + controller: None, + }; + let Ok(mut root) = (unsafe { + uefi::boot::open_protocol::<PciRootBridgeIo>( + params, + OpenProtocolAttributes::GetProtocol, + ) + }) else { + continue; + }; + let (bus_min, bus_max) = crate::bus_ranges(&mut root).unwrap_or((0, 0)); + for bus in bus_min..=bus_max { + for device in 0..32u8 { + for function in 0..8u8 { + let address = PciIoAddress::new(bus, device, function); + let mut read = |offset| { + root.pci() + .read_one::<u32>(address.with_register(offset)) + .ok() + }; + let Some(_) = read(0).filter(|id| id & 0xffff != 0xffff) else { + if function == 0 { + break; + } + continue; + }; + let bar = (read(0x08), read(0x10), read(0x14)); + if let (Some(class), Some(low), Some(high)) = bar { + if let Some(mmio) = xhci::xhci_mmio_base(class, low, high) { + let segment = root.segment_nr() as u16; + return Some(XhciLocation { + segment, + bus, + device, + function, + mmio, + }); + } + } + let multi = read(0x0c).is_some_and(|v| v & 0x80_0000 != 0); + if function == 0 && !multi { + break; + } + } + } + } + } + None +} + +fn console() -> Option<EarlyConsole> { + crate::CONSOLE + .try_lock() + .and_then(|k| *k) + .and_then(EarlyConsole::from_kind) +} + +/// Write `text` to the SPCR console and the screen. +fn say(screen: &mut Option<Screen>, text: &str) { + if let Some(console) = console() { + console.write_str(text); + } + if let Some(s) = screen.as_mut() { + let _ = s.write_str(text); + } +} + +/// Enable memory decode and bus mastering through ECAM: firmware may have +/// turned them off when it stopped its own USB driver at exit. +fn enable_controller(ecam: &EcamWindow, at: &XhciLocation) -> bool { + let Some(addr) = ecam.config_address(at.bus, at.device, at.function, 0x04) else { + return false; + }; + let command = MmioReg::<u16>::new(addr as usize); + command.write(command.read() | PCI_COMMAND_MEMORY | PCI_COMMAND_BUS_MASTER); + true +} + +/// Post-exit: bring up the keyboard and echo keys until Enter or timeout. +pub fn run(xhci: Option<XhciLocation>, mcfg: Option<&[u8]>, screen: &mut Option<Screen>) { + let mut line = aienos_kernel::report::ReportBuf::<160>::new(); + let Some(at) = xhci else { + say(screen, "\nkeyboard: unavailable (no xHCI controller)\n"); + return; + }; + let _ = writeln!( + line, + "\nkeyboard: xhci {:04x}:{:02x}:{:02x}.{} mmio {:#x}", + at.segment, at.bus, at.device, at.function, at.mmio + ); + say(screen, line.as_str()); + let ecam = mcfg.and_then(|t| acpi::mcfg_window(t, at.segment, at.bus).ok().flatten()); + if !ecam.is_some_and(|w| enable_controller(&w, &at)) { + say( + screen, + "keyboard: unavailable (no ECAM window for the controller)\n", + ); + return; + } + // SAFETY: firmware has exited and released the controller; DMA is used + // by nothing else, is identity-mapped, and lives for the whole boot. + let started = unsafe { Keyboard::start(at.mmio, core::ptr::addr_of_mut!(DMA)) }; + let mut keyboard = match started { + Ok(k) => k, + Err(e) => { + let mut msg = aienos_kernel::report::ReportBuf::<160>::new(); + let _ = writeln!(msg, "keyboard: unavailable ({e})"); + say(screen, msg.as_str()); + return; + } + }; + let (port, slot, endpoint) = keyboard.location(); + let mut msg = aienos_kernel::report::ReportBuf::<200>::new(); + let _ = writeln!( + msg, + "keyboard: ready (port {port}, slot {slot}, endpoint {endpoint:#04x})" + ); + let _ = write!( + msg, + "keyboard: type a line, Enter ends it ({} s)\nkeyboard_echo: ", + listen_secs() + ); + say(screen, msg.as_str()); + + let mut decoder = BootKeyboardDecoder::new(); + let mut text = TextSink::<64>::new(); + let mut entered = false; + let deadline = listen_secs().saturating_mul(counter_frequency_hz()); + let start = counter_ticks(); + while !entered && counter_ticks().wrapping_sub(start) < deadline && !keyboard.is_halted() { + let Some(report) = keyboard.poll() else { + core::hint::spin_loop(); + continue; + }; + decoder.handle_report(&report, |event| { + if event == KeyEvent::Enter { + entered = true; + } else if let KeyEvent::Char(c) = event { + let mut buf = [0u8; 4]; + say(screen, c.encode_utf8(&mut buf)); + text.record(event); + } + }); + } + let mut end = aienos_kernel::report::ReportBuf::<200>::new(); + let reason = match (entered, keyboard.is_halted()) { + (true, _) => "enter", + (false, true) => "endpoint halted", + (false, false) => "timeout", + }; + let _ = writeln!( + end, + "\nkeyboard_line: {}\nkeyboard: done ({reason})", + text.as_str() + ); + say(screen, end.as_str()); +} diff --git a/scripts/qemu_keyboard_test.sh b/scripts/qemu_keyboard_test.sh new file mode 100755 index 00000000..7d776794 --- /dev/null +++ b/scripts/qemu_keyboard_test.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# SEED-0A `input.keyboard.usb` proof in QEMU (ADR 0012): boot the handoff +# image built with the `usb-keyboard` feature on a qemu-xhci controller with +# a usb-kbd, wait until the AIENOS driver reports the keyboard ready after +# ExitBootServices, type keys through the QEMU monitor (`sendkey`), and check +# that the same text comes back on the serial console. Emulator only: it says +# nothing about Machine 1 hardware. +# +# A boot that shows no AIENOS output at all is retried (firmware hang before +# AIENOS runs, issue #61); any failure after AIENOS output fails at once. +# +# Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +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"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; } + +keys=(a b c) +expected="abc" +attempts="${AIENOS_KEYBOARD_ATTEMPTS:-3}" +boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}" + +# Own target directory: a keyboard-enabled image never lands where hardware +# staging or the other tests pick up the handoff image. +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 AIENOS_KEYBOARD_SECS=60 cargo build --quiet --release \ + -p aienos-boot --target aarch64-unknown-uefi --features usb-keyboard --bin aienos-handoff \ + --target-dir target/qemu-keyboard + +work="$(mktemp -d)" +qemu_pid="" +cleanup() { + [[ -n "${qemu_pid}" ]] && kill "${qemu_pid}" 2>/dev/null || true + exec 3>&- 2>/dev/null || true + rm -rf "${work}" +} +trap cleanup EXIT +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp target/qemu-keyboard/aarch64-unknown-uefi/release/aienos-handoff.efi "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + +serial_has() { tr -d '\r' 2>/dev/null <"${work}/serial.log" | grep -q -- "$1"; } +qemu_running() { kill -0 "${qemu_pid}" 2>/dev/null; } + +# Wait until the serial log contains one of the patterns or QEMU exits. +wait_for() { # seconds, pattern... + local deadline=$(( $(date +%s) + $1 )); shift + while (( $(date +%s) < deadline )) && qemu_running; do + for p in "$@"; do serial_has "${p}" && return 0; done + sleep 0.2 + done + for p in "$@"; do serial_has "${p}" && return 0; done + return 1 +} + +stop_qemu() { + if [[ -n "${qemu_pid}" ]]; then + kill "${qemu_pid}" 2>/dev/null || true + wait "${qemu_pid}" 2>/dev/null || true + fi + qemu_pid="" + exec 3>&- 2>/dev/null || true +} + +boot_once() { + cp "${vars_fd}" "${work}/vars.fd" + rm -f "${work}/serial.log" "${work}/mon.in" "${work}/mon.out" + mkfifo "${work}/mon.in" "${work}/mon.out" + qemu-system-aarch64 \ + -M virt,virtualization=on -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -device qemu-xhci,id=xhci -device usb-kbd,bus=xhci.0 \ + -device ramfb -display none -nic none \ + -chardev pipe,id=mon,path="${work}/mon" -mon chardev=mon,mode=readline \ + -serial file:"${work}/serial.log" -no-reboot & + qemu_pid=$! + # Drain monitor output so QEMU never blocks writing it. + cat "${work}/mon.out" >/dev/null & + exec 3>"${work}/mon.in" + + if ! wait_for "${boot_timeout}" "report_kind: pre_exit"; then + echo "attempt ${attempt}: no AIENOS output within ${boot_timeout} s (firmware hang, issue #61)" + stop_qemu + return 2 + fi + if wait_for "${boot_timeout}" "keyboard: ready" "keyboard: unavailable" "report_kind: panic" "report_kind: fault" \ + && serial_has "keyboard: ready"; then + for key in "${keys[@]}" ret; do + echo "sendkey ${key}" >&3 + sleep 0.3 + done + fi + local deadline=$(( $(date +%s) + 90 )) + while qemu_running && (( $(date +%s) < deadline )); do sleep 0.5; done + qemu_running && echo "QEMU still running after the keyboard phase" + stop_qemu + return 0 +} + +started=$(date +%s) +attempt=1 +while :; do + status=0 + boot_once || status=$? + [[ "${status}" != 2 || "${attempt}" -ge "${attempts}" ]] && break + attempt=$(( attempt + 1 )) +done +elapsed=$(( $(date +%s) - started )) + +tr -d '\r' <"${work}/serial.log" >"${work}/serial.txt" 2>/dev/null || true +failed=0 +check() { # description, pattern + if grep -q -- "$2" "${work}/serial.txt"; then + echo "PASS $1" + else + echo "FAIL $1" + failed=1 + fi +} +echo "attempts ${attempt}, ${elapsed} s (commit ${commit:0:12}), sent keys: ${keys[*]} ret" +check "left firmware and entered the kernel" "kernel: alive" +check "xHCI controller found before exit" "keyboard: xhci " +check "keyboard attached by the AIENOS driver" "keyboard: ready" +check "typed text echoed on the serial console" "keyboard_echo: ${expected}" +check "line ended by Enter and reported" "keyboard_line: ${expected}\$" +check "keyboard phase finished on Enter" "keyboard: done (enter)" +if grep -qE "report_kind: (panic|fault)" "${work}/serial.txt"; then + echo "FAIL panic or fault reported" + failed=1 +fi + +if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + echo "---- serial console ----" + cat "${work}/serial.txt" +fi +[[ "${failed}" == 0 ]] && echo "QEMU_KEYBOARD: PASS" || { echo "QEMU_KEYBOARD: FAIL"; exit 1; } diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index 7a48b90c..ee0e7460 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -56,6 +56,15 @@ else echo "SKIPPED: qemu-system-aarch64 or AAVMF firmware not present on host." fi +# Step 6b: SEED-0A USB keyboard candidate, proven in QEMU only (ADR 0012). +echo "" +echo "--- [SEED-0A USB Keyboard in QEMU (input.keyboard.usb)] ---" +if command -v qemu-system-aarch64 >/dev/null && [[ -r "${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" ]]; then + ./scripts/qemu_keyboard_test.sh +else + echo "SKIPPED: qemu-system-aarch64 or AAVMF firmware not present on host." +fi + echo "" echo "============================================================" echo "HOST VERIFICATIONS PASSED."