garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/selfcheck.rs

raw

//! What every boot proves before it goes on, and what `cargo xtask test`
//! requires of the output: each check prints its line and an "ok", or
//! panics, which powers QEMU off with a failure.

use crate::mm::pages;
use crate::sync::SpinLock;
use crate::{arch, irq, println, sched, smp, timer};
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use pinnacle_abi::{KILLED, arg};

const CHECK_TICKS: u64 = 20;
static SPINS_A: AtomicU64 = AtomicU64::new(0);
static SPINS_B: AtomicU64 = AtomicU64::new(0);
static STOP: AtomicBool = AtomicBool::new(false);

/// One task that never yields, so only preemption can take the core from
/// it, and one that always does, sharing a core: both run within
/// [`CHECK_TICKS`], and both end when told to. A core's idle task never
/// takes a turn from them, so only the slice's end gives the second a turn.
pub fn scheduler() {
    let core = (smp::online().count_ones() > 1).then_some(1);
    let a = sched::spawn_on(core, || {
        while !STOP.load(Ordering::Relaxed) {
            SPINS_A.fetch_add(1, Ordering::Relaxed);
        }
    });
    let b = sched::spawn_on(core, || {
        while !STOP.load(Ordering::Relaxed) {
            SPINS_B.fetch_add(1, Ordering::Relaxed);
            sched::yield_now();
        }
    });
    irq::enable();
    // Counted from here: a PC's boot has ticked already, checking its
    // interrupts.
    let (ticks, switched) = (timer::ticks(), sched::switches());
    while timer::ticks() < ticks + CHECK_TICKS {
        arch::wait_for_interrupt();
    }
    STOP.store(true, Ordering::Relaxed);
    assert_eq!(
        (sched::wait(a), sched::wait(b)),
        (0, 0),
        "a kernel task did not end with 0"
    );

    let (spins_a, spins_b) = (SPINS_A.load(Ordering::Relaxed), SPINS_B.load(Ordering::Relaxed));
    let (switches, yields) = (sched::switches() - switched, sched::yields());
    println!("scheduler: {switches} switches, {yields} yields; task a {spins_a}, task b {spins_b}");
    assert!(spins_a > 0, "the task that never yields never ran");
    assert!(spins_b > 0 && yields > 0, "the yielding task never ran");
    assert!(switches > CHECK_TICKS, "the ticks did not preempt");
    println!("scheduler ok");
}

static SHARED: SpinLock<u64> = SpinLock::new(0);
static CORES_SEEN: AtomicU64 = AtomicU64::new(0);
/// The increments in all, split over the tasks: a fixed amount whatever
/// the cores, or many cores emulated on a few take minutes on one lock.
const INCREMENTS: u64 = 120_000;
static PER_TASK: AtomicU64 = AtomicU64::new(0);

/// Two tasks per running core, spread over the cores, all incrementing one
/// counter under one lock at once: every core runs tasks, and no increment
/// is lost to a race.
pub fn smp() {
    let online = smp::online();
    let count = 2 * online.count_ones() as usize;
    PER_TASK.store(INCREMENTS / count as u64, Ordering::Relaxed);
    let started = timer::now_ms();
    let mut ids = alloc::vec![0; count];
    for id in ids.iter_mut() {
        *id = sched::spawn(|| {
            CORES_SEEN.fetch_or(1 << arch::core_id(), Ordering::Relaxed);
            for _ in 0..PER_TASK.load(Ordering::Relaxed) {
                *SHARED.lock() += 1;
            }
        });
    }
    for &id in &ids {
        // Waited for 20 s at most: a task that does not end says where
        // every task is, instead of the boot stalling silently.
        let code = sched::wait_until(id, timer::now_ms() + 20_000).unwrap_or_else(|| {
            println!("smp: task {id} did not end in 20 s; the tasks:");
            sched::describe();
            // Waits on, so the host sees the hang and asks QEMU where each
            // core is.
            sched::wait(id)
        });
        assert_eq!(code, 0, "a counting task did not end with 0");
    }
    let (total, seen) = (*SHARED.lock(), CORES_SEEN.load(Ordering::Relaxed));
    println!(
        "smp: {count} tasks on cores {seen:#b} of {online:#b}, {total} of {} locked increments in {} ms",
        count as u64 * PER_TASK.load(Ordering::Relaxed),
        timer::now_ms() - started
    );
    assert_eq!(seen, online, "a running core got no task");
    assert_eq!(
        total,
        count as u64 * PER_TASK.load(Ordering::Relaxed),
        "increments were lost"
    );
    println!("smp ok");
}
/// Every device came from the machine's description (the device tree, and
/// PCI), and the drivers found theirs there: one of each `expected` class.
/// What has no driver is listed, as a board brought up would show it.
pub fn devices(expected: &[crate::device::Class]) {
    let all = crate::device::all();
    let mut without: BTreeMap<String, usize> = BTreeMap::new();
    for device in &all {
        match device.driver {
            Some((driver, class)) => println!("devices: {} is {} ({driver})", device.name, class.name()),
            None => *without.entry(device.compatible[0].clone()).or_default() += 1,
        }
    }
    let bound = all.iter().filter(|d| d.driver.is_some()).count();
    let rest: Vec<String> = without
        .iter()
        .map(|(c, n)| {
            if *n > 1 {
                alloc::format!("{c} ({n})")
            } else {
                c.clone()
            }
        })
        .collect();
    println!(
        "devices: {} found, {bound} with a driver; none for {}",
        all.len(),
        rest.join(", ")
    );
    let has = |class: crate::device::Class| all.iter().any(|d| d.driver.is_some_and(|(_, c)| c == class));
    for &class in expected {
        assert!(has(class), "no {} device found", class.name());
    }
    println!("devices ok");
}

/// Two copies of the test program keep a value at the same address and
/// each finds its own after every switch; a third reads the kernel's memory
/// and is killed for it, and the kernel goes on.
pub fn programs() {
    let program = crate::programs::find(b"hello").expect("built without programs: build with `cargo xtask`");
    let start = |argument| {
        sched::spawn_program(program, argument, Vec::new(), false, true, None)
            .expect("could not start a program")
    };
    // A first round grows the kernel heap's size classes the programs use,
    // whose pages the heap keeps: count from after it. The same three at
    // once as the round counted, since three alive together can need a
    // heap page that one alone did not.
    let (first, second, intruder) = (start(arg::ROUNDS), start(arg::ROUNDS), start(arg::TOUCH_KERNEL));
    assert_eq!(sched::wait(first), 0, "a program found its memory changed");
    assert_eq!(sched::wait(second), 0, "a program found its memory changed");
    assert!(
        sched::wait(intruder) >= KILLED,
        "a program read the kernel's memory"
    );
    let free = pages::stats().0;
    let (first, second, intruder) = (start(arg::ROUNDS), start(arg::ROUNDS), start(arg::TOUCH_KERNEL));
    assert_eq!(sched::wait(first), 0, "a program found its memory changed");
    assert_eq!(sched::wait(second), 0, "a program found its memory changed");
    let killed = sched::wait(intruder);
    assert!(killed >= KILLED, "a program read the kernel's memory");
    assert_eq!(
        pages::stats().0,
        free,
        "the programs' pages did not all come back"
    );
    println!("programs: 6 run in user mode, 2 killed (exit code {killed:#x}), every page back");
    println!("programs ok");

    // Channels between programs: a service, messages, shared memory, a
    // timeout (the client checks each and prints what it saw).
    let (server, client) = (start(arg::ECHO_SERVER), start(arg::ECHO_CLIENT));
    assert_eq!(sched::wait(client), 0, "the echo client failed");
    assert_eq!(sched::wait(server), 0, "the echo server failed");
    println!("ipc ok");

    // A service says what it can do, each verb with its effect, and is
    // called by name: what the terminal's commands and the agent use.
    let (server, client) = (start(arg::VERBS_SERVICE), start(arg::VERBS_CLIENT));
    assert_eq!(sched::wait(client), 0, "the verbs client failed");
    assert_eq!(sched::wait(server), 0, "the verbs service failed");
    println!("verbs ok");

    // Threads: a program's pool spreads jobs over the cores; ending the
    // program ends a thread of it that still sleeps.
    let threaded = start(arg::THREADS);
    assert_eq!(sched::wait(threaded), 0, "the thread pool got a wrong sum");
    println!("threads ok");

    // Shared memory goes back when unmapped, while the program runs.
    let unmapping = start(arg::UNMAP);
    assert_eq!(sched::wait(unmapping), 0, "unmapped memory did not come back");
    println!("unmap ok");

    // A program ends another it started, busy threads and all.
    let killer = start(arg::KILL);
    assert_eq!(sched::wait(killer), 0, "a program could not end one it started");
    println!("kill ok");

    // FP/SIMD registers belong to each program: twelve compute at once,
    // two to a core, yielding all along.
    let ids: Vec<usize> = (0..12).map(|_| start(arg::FLOATS)).collect();
    for id in ids {
        assert_eq!(
            sched::wait(id),
            0,
            "a program's FP/SIMD registers changed under it"
        );
    }
    println!("fp: 12 programs computed with FP/SIMD registers while switching, each kept its own");
    println!("fp ok");
}

/// The command `frits`: Frits's compiler and VM in a program, its
/// examples compiled against the terminal's platform and tested, and one
/// run (`abi::FRITS_CHECK`).
pub fn frits() {
    let program = crate::programs::find(b"frits").expect("built without the command frits");
    let id = sched::spawn_program(program, pinnacle_abi::FRITS_CHECK, Vec::new(), false, true, None)
        .expect("could not start frits");
    assert_eq!(sched::wait(id), 0, "frits's examples failed");
    println!("frits ok");
}

/// The app `kees`: a whole account (mail, calendars, contacts, an invite
/// answered) synced against the provider it holds in memory
/// (`abi::KEES_CHECK`), so its engine is known to run here.
pub fn kees() {
    let program = crate::programs::find(b"kees").expect("built without the app kees");
    let id = sched::spawn_program(program, pinnacle_abi::KEES_CHECK, Vec::new(), false, true, None)
        .expect("could not start kees");
    assert_eq!(sched::wait(id), 0, "kees could not sync its demo account");
    println!("kees ok");
}

/// Rust's std: a program built against it (`std/check`) runs its threads,
/// locks, channels and clocks on the futexes, thread pointers and counter
/// the kernel gives it, then std::fs on the system disk and std::net to the
/// package source, and prints what it found. After the disks and the
/// network, which it uses.
pub fn std() {
    let program = crate::programs::find(b"std-check").expect("built without the std programs");
    let id =
        sched::spawn_program(program, 0, Vec::new(), false, true, None).expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the std program failed");
    println!("std ok");
}

/// The crates ported from crates.io (`ports/`): a program on tokio over
/// Pinnacle's mio, which `cargo xtask test` puts on the system disk; not part
/// of the system, so a disk without it skips the check.
pub fn ports() {
    let Some(Ok(elf)) = crate::drivers::block::with_disk("/tests/ports-check", |fs, p| fs.read(p)) else {
        println!("ports: no check on this disk");
        return;
    };
    let id = sched::spawn_program(&elf, 0, Vec::new(), false, true, None).expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the ports' check failed");
    println!("ports ok");
}

/// A screen a loader lit (`drivers::scanout`): what reading an RK3399's
/// display controller makes of the registers U-Boot leaves (a window of
/// 1080 × 1920 in each format it sets, and one switched off), the pixel
/// formats; and, where the boot was given one, that the bands drawn above
/// reached its memory once flushed, in its format and at its stride, and
/// that the page allocator kept off it.
fn lit_screen(bands: &[u32]) {
    use crate::drivers::scanout::{Format, vop_window};
    let act = (1919 << 16) | 1079;
    let argb = vop_window(0, 1, 1080, 0x7f00_0000, act).expect("an RK3399 window on is a screen");
    assert_eq!((argb.width, argb.height, argb.stride), (1080, 1920, 4320));
    assert_eq!((argb.address, argb.format), (0x7f00_0000, Format::Xrgb8888));
    let rgb565 = vop_window(0, 1 | 2 << 1, 540, 0x7f00_0000, act).expect("a 16-bit window is a screen");
    assert_eq!((rgb565.stride, rgb565.format), (2160, Format::Rgb565));
    let swapped = vop_window(0, 1 | 1 << 12, 1080, 0x7f00_0000, act).unwrap();
    assert_eq!(swapped.format, Format::Xbgr8888);
    assert!(
        vop_window(0, 0, 1080, 0x7f00_0000, act).is_none(),
        "a window off is no screen"
    );
    assert!(
        vop_window(1 << 22, 1, 1080, 0x7f00_0000, act).is_none(),
        "a VOP in standby is no screen"
    );
    assert_eq!(Format::Rgb565.encode(0x00ff_8040), 0xfc08);
    assert_eq!(Format::Xbgr8888.encode(0x0011_2233), 0x0033_2211);
    // What the loader reserved stays out of the allocator.
    let mut reserved = 0;
    if let Some(tree) = crate::device::tree() {
        tree.reserved(|address, size| {
            let (start, end) = (address as usize, (address + size) as usize);
            assert!(
                !pages::any_free_in(start, end),
                "the allocator holds reserved memory at {start:#x}"
            );
            reserved += 1;
        });
    }
    if reserved > 0 {
        println!("memory: {reserved} ranges the loader reserved, kept from the allocator");
    }

    let Some(lit) = crate::drivers::scanout::get() else {
        return;
    };
    crate::drivers::display::flush(0, 0, lit.width as i32, lit.height as i32);
    let (start, end) = lit.range();
    for (i, &band) in bands.iter().enumerate() {
        let y = i * lit.height as usize / bands.len();
        let at = crate::mmu::virt(start + y * lit.stride as usize);
        // SAFETY: the first pixel of a row of the lit screen, in RAM.
        let shown = unsafe {
            match lit.format.bytes() {
                4 => (at as *const u32).read_volatile(),
                _ => u32::from((at as *const u16).read_volatile()),
            }
        };
        assert_eq!(
            shown,
            lit.format.encode(band),
            "the lit screen did not get a band"
        );
    }
    assert!(
        !pages::any_free_in(start, end),
        "the page allocator holds pages of the lit screen"
    );
    println!(
        "display: drawn on the screen the loader lit ({}, {:?}, {}x{} at {start:#x}, stride {}), kept from the allocator",
        lit.source, lit.format, lit.width, lit.height, lit.stride
    );
}

/// The display, when there is one: a framebuffer the size of the screen,
/// shown. It draws bands of colour and reads a pixel of each back.
pub fn display() {
    let (width, height) = crate::drivers::display::screen_size();
    if !crate::drivers::display::init(width, height) {
        println!("display: none");
        return;
    }
    let mut guard = crate::drivers::display::DISPLAY.lock();
    let display = guard.as_mut().unwrap();
    let pixels = display.pixels();
    let bands = [0x0020_3a5c, 0x0030_6080, 0x0050_90b0, 0x00e8_d8b0];
    for y in 0..height {
        let band = bands[(y * bands.len() as u32 / height) as usize];
        pixels[(y * width) as usize..((y + 1) * width) as usize].fill(band);
    }
    for (i, &band) in bands.iter().enumerate() {
        let y = i as u32 * height / bands.len() as u32;
        assert_eq!(
            pixels[(y * width) as usize],
            band,
            "the framebuffer did not keep a pixel"
        );
    }
    println!(
        "display: {width}x{height} ({})",
        crate::drivers::display::driver()
    );
    // Let the screen go: the program below writes to the console.
    drop(guard);
    lit_screen(&bands);
    println!("display ok");
    // The 3D virtio-gpu, where QEMU has one (on PCI; `cargo xtask` gives it on
    // a machine with a render node): a Venus context, the first step of a
    // Vulkan run on the host's.
    if crate::drivers::gpu3d::init() {
        match crate::drivers::gpu3d::check() {
            Ok(found) => {
                println!(
                    "gpu3d: capsets {:?}; a Venus context made and destroyed (capset v{}, {} bytes); {} MiB host-visible",
                    found.capsets,
                    found.venus_version,
                    found.venus_bytes,
                    found.host_visible >> 20
                );
                println!("gpu3d ok");
            }
            Err(why) => panic!("gpu3d: {why}"),
        }
        // Venus, from a program: a context of its own (the GPU channel), its
        // command streams' replies read from memory the host shares, an
        // instance made, the host's GPUs named and a buffer filled.
        let program = crate::programs::find(b"hello").expect("built without programs");
        let id = sched::spawn_program(program, arg::GPU, Vec::new(), false, true, None)
            .expect("could not start a program");
        assert_eq!(sched::wait(id), 0, "the Venus check failed");
        println!("venus ok");
    }
}

/// The disks: each with Pinnacle's file system is mounted by its label; on
/// the system disk a file is written, read back and removed.
pub fn files() {
    let labels = crate::drivers::block::init();
    println!("disks: {}", labels.join(", "));
    let checked = crate::drivers::block::with_disk("system:/selfcheck", |fs, path| {
        let data: Vec<u8> = (0..10_000u32).map(|i| i as u8).collect();
        fs.write(path, &data).expect("could not write a file");
        // A range into it, across a block boundary, read back.
        fs.write_at(path, 4_000, &[7; 200])
            .expect("could not write into the file");
        let mut data = data;
        data[4_000..4_200].fill(7);
        let stat = fs.stat(path).expect("the file has no size");
        assert_eq!(stat.size, 10_000, "the file changed size");
        assert_eq!(
            fs.read(path).expect("could not read the file back"),
            data,
            "the file came back changed"
        );
        fs.remove(path).expect("could not remove the file");
        if let Err(problem) = fs.check() {
            panic!("the system disk is not whole after writing: {problem}");
        }
        fs.free()
    });
    match checked {
        Some(free) => {
            println!(
                "files: written, read back and removed; {} MiB free",
                (free as usize * 4096) >> 20
            );
            println!("files ok");
            confinement();
            handles();
            text();
        }
        None => println!("files: no system disk"),
    }
}

/// Text beyond Latin, in a program as an app draws it: `hello` shapes
/// Arabic with the fallback font from the disk, writes in Dutch, and sends
/// a UI tree through its wire format.
fn text() {
    let program = crate::programs::find(b"hello").expect("built without programs: build with `cargo xtask`");
    let id = sched::spawn_program(program, arg::TEXT, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "text was shaped or written wrong");
    println!("text ok");
}

/// An installed app is confined: the test program, run as the app
/// "hello", reaches its own folder and the fonts and nothing else.
fn confinement() {
    for dir in ["/data", "/data/hello"] {
        let _ = crate::drivers::block::with_disk(dir, |fs, p| fs.create_dir(p));
    }
    let program = crate::programs::find(b"hello").expect("built without programs: build with `cargo xtask`");
    let id = sched::spawn_program(
        program,
        arg::CONFINED,
        Vec::new(),
        false,
        true,
        Some("hello".into()),
    )
    .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "a confined app reached past its folder");
    let _ = crate::drivers::block::with_disk("/data/hello", |fs, p| fs.remove_all(p));
    println!("confinement ok");
}

/// File handles: a confined app reads the one file outside its folder it
/// was handed, and nothing else of it; a program keeps an append-only log
/// through a handle that may only add. And the mark on synthesised input
/// survives the wire, where the kernel's own input carries none.
fn handles() {
    use pinnacle_abi::{InputEvent, file};
    let path = "system:/selfcheck-handed";
    let _ = crate::drivers::block::with_disk(path, |fs, p| fs.write(p, b"handed over"));
    let program = crate::programs::find(b"hello").expect("built without programs");
    let handed = crate::object::Object::File(alloc::sync::Arc::new(crate::object::OpenFile {
        path: path.into(),
        rights: file::READ,
    }));
    let id = sched::spawn_program(
        program,
        arg::HANDED_FILE,
        alloc::vec![handed],
        false,
        true,
        Some("hello".into()),
    )
    .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "a handed file was not as handed");
    let _ = crate::drivers::block::with_disk(path, |fs, p| fs.remove(p));
    let id = sched::spawn_program(program, arg::LOG, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the append-only log failed");
    let made = InputEvent {
        kind: InputEvent::PRESS,
        value: 1,
        x: 3,
        y: 4,
        synthetic: true,
        ..InputEvent::default()
    };
    let back = InputEvent::from_bytes(&made.to_bytes()).expect("an event did not decode");
    let physical = InputEvent::from_bytes(
        &InputEvent {
            synthetic: false,
            ..made
        }
        .to_bytes(),
    )
    .unwrap();
    assert!(
        back.synthetic && back.kind == InputEvent::PRESS && !physical.synthetic,
        "the synthetic mark did not survive"
    );
    println!("handles ok");
}

/// Disk requests complete by interrupt while the task that waits for them
/// sleeps: a program writes a 2 MiB file a range at a time, reads it back
/// and checks it, and its waits must have slept, not spun.
/// Every disk nothing is mounted from (an NVMe, a SATA disk, a stick: what
/// the installer may take) is read and, when the self-check is asked for,
/// written: its last block replaced, read back, and put back as it was, so
/// what it holds survives. Each controller's requests and interrupts so
/// proved, on real hardware as in QEMU.
pub fn storage() {
    use crate::drivers::block::{self, BLOCK, Data, Op};
    let writing = crate::args::has("selfcheck");
    let mut checked = 0;
    for disk in block::disks() {
        let Some(c) = block::free_controller(&disk.name) else {
            continue;
        };
        let last = c.blocks() - 1;
        let mut before = alloc::vec![[0u8; BLOCK]; 2];
        if !c.transfer(Op::Read, &[0, last], Data::Into(&mut before)) {
            // A machine's own disk its driver cannot read yet is said,
            // not a reason to stop: only QEMU's must all work.
            assert!(!writing, "storage: {} could not be read", disk.name);
            println!("storage: {} could not be read", disk.name);
            continue;
        }
        if writing {
            let pattern: [[u8; BLOCK]; 1] = [core::array::from_fn(|i| (i as u8) ^ 0xa5)];
            assert!(
                c.transfer(Op::Write, &[last], Data::From(&pattern)),
                "storage: {} refused a write",
                disk.name
            );
            assert!(
                c.transfer(Op::Flush, &[0], Data::None),
                "storage: {} refused a flush",
                disk.name
            );
            let mut back = [[0u8; BLOCK]; 1];
            assert!(
                c.transfer(Op::Read, &[last], Data::Into(&mut back)),
                "storage: {} could not be read",
                disk.name
            );
            assert!(
                back == pattern,
                "storage: {} gave back other bytes than written",
                disk.name
            );
            assert!(
                c.transfer(Op::Write, &[last], Data::From(&before[1..])),
                "storage: {} refused a write",
                disk.name
            );
        }
        println!(
            "storage: {} ({}, {} MiB): {}",
            disk.name,
            disk.model,
            disk.bytes >> 20,
            if writing {
                "a block written, read back and put back"
            } else {
                "read"
            }
        );
        checked += 1;
    }
    if checked > 0 {
        println!("storage ok");
    }
}

/// What USB devices were found, and which driver took each.
pub fn usb() {
    let attached = crate::drivers::usb::hid::ATTACHED.lock().clone();
    if !attached.is_empty() {
        println!("usb: {}", attached.join(", "));
    }
}

pub fn io() {
    use crate::drivers::block;
    if !block::present() {
        println!("io: no disk");
        return;
    }
    let before = block::stats();
    let program = crate::programs::find(b"hello").expect("built without programs");
    let id = sched::spawn_program(program, arg::IO, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the disk check failed");
    let after = block::stats();
    println!(
        "io: {} blocks read ({} from the cache), {} written; {} waits slept, {} waited for the interrupt",
        after.reads - before.reads,
        after.hits - before.hits,
        after.writes - before.writes,
        after.sleeps - before.sleeps,
        after.spins - before.spins,
    );
    assert!(
        after.sleeps > before.sleeps,
        "a program's disk waits did not sleep"
    );
    assert_eq!(after.spins, before.spins, "a program's disk wait spun");
    println!("io ok");
}

/// Sound, when there is a device: a program plays 300 ms of a 440 Hz tone
/// through the kernel's mixer, whose periods complete by interrupt. What
/// came out of the device, `cargo xtask test` hears in QEMU's WAV file.
/// Only when a test asks (`selfcheck` or `tone` on the command line): a
/// laptop starts silent.
pub fn audio() {
    use crate::drivers::sound;
    if !sound::present() {
        println!("audio: no sound device");
        return;
    }
    if !crate::args::has("selfcheck") && !crate::args::has("tone") {
        return;
    }
    let before = sound::stats();
    let program = crate::programs::find(b"hello").expect("built without programs");
    let id = sched::spawn_program(program, arg::AUDIO, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the sound check failed");
    let after = sound::stats();
    println!(
        "audio: {} periods played, {} short of samples, {} frames dropped",
        after.played - before.played,
        after.underruns - before.underruns,
        after.dropped - before.dropped,
    );
    assert!(after.played > before.played, "no period was played");
    assert_eq!(after.dropped, before.dropped, "the player's samples were dropped");
    println!("audio ok");
}

/// Bluetooth, when there is a port to a controller: a program runs the
/// host stack over it, finds the device `cargo xtask` put in the air,
/// connects, discovers its services and reads its name and battery level.
pub fn bluetooth() {
    if !crate::drivers::serial::present(crate::drivers::serial::Port::Bluetooth) {
        println!("bluetooth: no port to a controller");
        return;
    }
    let program = crate::programs::find(b"hello").expect("built without programs");
    let id = sched::spawn_program(program, arg::BLUETOOTH, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the Bluetooth check failed");
    println!("bluetooth ok");
}

/// The modem, when there is a port to one: a program runs the modem driver
/// over it, on the network `cargo xtask` simulates, and calls a number
/// that answers.
pub fn modem() {
    if !crate::drivers::serial::present(crate::drivers::serial::Port::Modem) {
        println!("modem: no port to a modem");
        return;
    }
    let program = crate::programs::find(b"hello").expect("built without programs");
    let id = sched::spawn_program(program, arg::MODEM, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the modem check failed");
    println!("modem ok");
}

/// With a manifest that grants the network, the same confined app has it
/// (run once the network is up: the refusal without the grant is in
/// `confinement`).
pub fn network_grant() {
    if !crate::drivers::net::present() {
        return;
    }
    let program = crate::programs::find(b"hello").expect("built without programs");
    let manifest = b"name=hello\ntitle=Hello\nnetwork=yes\n";
    let _ = crate::drivers::block::with_disk("/apps/hello", |fs, p| fs.create_dir(p));
    let _ = crate::drivers::block::with_disk("/apps/hello/manifest", |fs, p| fs.write(p, manifest));
    let granted = crate::drivers::block::with_disk("/apps/hello/manifest", |fs, p| fs.read(p))
        .and_then(Result::ok)
        .is_some_and(|m| crate::syscall::manifest_grants(&m, "network"));
    assert!(granted, "the manifest's grant was not read");
    let networked = sched::spawn_program_with(
        program,
        arg::CONFINED_NETWORK,
        Vec::new(),
        false,
        true,
        Some("hello".into()),
        granted,
    )
    .expect("could not start a program");
    assert_eq!(
        sched::wait(networked),
        0,
        "an app granted the network did not get it"
    );
    println!("confinement: the network refused without the manifest's grant, had with it");
    let _ = crate::drivers::block::with_disk("/apps/hello", |fs, p| fs.remove_all(p));
}

/// A program listens on a TCP port and the host connects to it through
/// QEMU's forwarded port (`cargo xtask test` sends a line and reads the
/// answer): connections come in as well as go out.
pub fn listen() {
    if !crate::drivers::net::present() {
        println!("listen: no network device");
        return;
    }
    let program = crate::programs::find(b"hello").expect("built without programs");
    let id = sched::spawn_program(program, arg::LISTEN, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the listening check failed");
    println!("listen ok");
}

/// The network, when there is one: a program gets an address by DHCP and
/// fetches the package source's catalog over TCP (HTTP). The model and
/// agent checks need the stand-in provider `cargo xtask` serves beside it;
/// a bundle's `start` serves only files, and they are skipped there
/// (`cargo xtask test` still expects "model ok").
pub fn network() {
    if !crate::drivers::net::present() {
        println!("net: no network device");
        return;
    }
    let program = crate::programs::find(b"hello").expect("built without programs");
    let id = sched::spawn_program(program, arg::NET, Vec::new(), false, true, None)
        .expect("could not start a program");
    match sched::wait(id) {
        0 => {
            println!("net ok");
            model();
        }
        arg::NET_WITHOUT_MODEL => println!("net ok; the model and agent checks skipped"),
        code => panic!("the network check failed ({code})"),
    }
}

/// The `model` service, on the stand-in provider beside the package source:
/// a question and a tool call answered, and both prompts logged.
fn model() {
    let service = crate::programs::find(b"model").expect("built without the model service");
    let client = crate::programs::find(b"hello").expect("built without programs");
    let service = sched::spawn_program(service, arg::MODEL_STANDIN, Vec::new(), false, true, None)
        .expect("could not start the model service");
    let id = sched::spawn_program(client, arg::MODEL_CLIENT, Vec::new(), false, true, None)
        .expect("could not start a program");
    assert_eq!(sched::wait(id), 0, "the model check failed");
    assert_eq!(sched::wait(service), 0, "the model service failed");
    println!("model ok");
    agent();
}

/// The agent's gatekeeper, sealed, against the stand-in model and the
/// self-check's notes service, with `hello` as the terminal and the person.
fn agent() {
    let model = crate::programs::find(b"model").expect("built without the model service");
    let hello = crate::programs::find(b"hello").expect("built without programs");
    let start = |elf, argument| {
        sched::spawn_program(elf, argument, Vec::new(), false, true, None).expect("could not start a program")
    };
    let (notes, model, check) = (
        start(hello, arg::VERBS_SERVICE),
        start(model, arg::MODEL_STANDIN),
        start(hello, arg::AGENT),
    );
    assert_eq!(sched::wait(check), 0, "the agent check failed");
    assert_eq!(sched::wait(model), 0, "the model service failed");
    assert_eq!(sched::wait(notes), 0, "the notes service failed");
    println!("agent ok");
}

/// With nothing to do, the cores sleep: over half a second the cores other
/// than 0 (which runs the check, and so keeps ticking) take next to no timer
/// interrupts, where a periodic tick would wake each 50 times.
pub fn idle() {
    let online = smp::online();
    let others = || {
        (1..smp::MAX_CORES)
            .filter(|&c| online & (1 << c) != 0)
            .map(timer::fired)
            .sum::<u64>()
    };
    let cores = u64::from(online.count_ones()) - 1;
    let before = others();
    let until = timer::now_ms() + 500;
    while timer::now_ms() < until {
        arch::wait_for_interrupt();
    }
    let taken = others() - before;
    println!(
        "idle: {cores} idle cores took {taken} timer interrupts in 500 ms (ticking: {})",
        cores * 500 / timer::SLICE_MS
    );
    assert!(taken <= cores, "idle cores are woken by their timers");
    println!("idle ok");
}

/// A disk in memory, for the vault's check.
struct Ram(Vec<[u8; pinnacle_fs::BLOCK]>);

impl pinnacle_fs::Disk for Ram {
    fn read(&mut self, block: u32, into: &mut [u8; pinnacle_fs::BLOCK]) {
        *into = self.0[block as usize];
    }
    fn write(&mut self, block: u32, from: &[u8; pinnacle_fs::BLOCK]) {
        self.0[block as usize] = *from;
    }
    fn blocks(&self) -> u32 {
        self.0.len() as u32
    }
}

/// The vault on this machine: a file system in one, made, closed, refused
/// a wrong passphrase, opened by the right one, the file back and not to
/// be found on the disk. Few PBKDF2 rounds: the boot need not wait.
pub fn vault() {
    use pinnacle_fs::vault::Vault;
    let disk = Ram(alloc::vec![[0; pinnacle_fs::BLOCK]; 256]);
    let (mut salt, mut key) = ([0u8; 16], [0u8; 32]);
    crate::drivers::random::fill(&mut salt);
    crate::drivers::random::fill(&mut key);
    let vault = Vault::create_with_rounds(disk, "check", 1000, salt, key);
    let mut fs = pinnacle_fs::format(vault, "check");
    fs.write("/secret", b"meet at the lighthouse")
        .expect("could not write in the vault");
    let mut raw = fs.into_disk().into_inner();
    let stored: Vec<u8> = raw.0.iter().flatten().copied().collect();
    assert!(
        !stored.windows(10).any(|w| w == b"lighthouse"),
        "the vault's file is on the disk in the clear"
    );
    raw = match Vault::open(raw, "wrong") {
        Ok(_) => panic!("a wrong passphrase opened the vault"),
        Err((raw, _)) => raw,
    };
    let vault = Vault::open(raw, "check").unwrap_or_else(|_| panic!("the passphrase did not open the vault"));
    let mut fs = pinnacle_fs::Fs::mount(vault).expect("the vault's file system did not mount");
    assert_eq!(fs.read("/secret").as_deref(), Ok(&b"meet at the lighthouse"[..]));
    println!(
        "vault: a file written in a vault, not on its disk in the clear, read back by its passphrase alone"
    );
    println!("vault ok");
}

/// https to a server on the internet, when `/settings/https-test` names one
/// (`cargo xtask https <url>`): TLS 1.3 from a program, its chain checked
/// against Mozilla's roots on the system disk. Not otherwise: the gate
/// must not need the internet.
pub fn https() {
    let asked = crate::drivers::block::with_disk("system:/settings/https-test", |fs, p| fs.stat(p).is_ok());
    if asked != Some(true) || !crate::drivers::net::present() {
        return;
    }
    let program = crate::programs::find(b"hello").expect("built without programs");
    let id = sched::spawn_program(program, arg::HTTPS, Vec::new(), false, true, None)
        .expect("could not start a program");
    if sched::wait(id) == 0 {
        println!("https ok");
    } else {
        println!("https: failed");
    }
}