garage44.eu/jeroen/pinnacle

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

.. /kernel/src/sched.rs

raw

//! Tasks, switched round-robin on each core: on every tick (preemption), on
//! a yield, and when a task blocks. A task's whole state is the [`Frame`]
//! its last exception saved on its own kernel stack, so a switch is one
//! pointer swap inside the exception it happens in; there is no separate
//! switch path. A task is a kernel task, or a program in user mode with an
//! [`AddressSpace`] and a handle table of its own; its ASID is its slot, so
//! switching to it writes TTBR0 and flushes nothing.
//!
//! Each task is bound to one core when it starts (the one with fewest
//! tasks), so a core switches only among its own: no task moves between
//! cores, and a program's TLB entries and TTBR0 stay on one. Slot n < cores
//! is core n's idle task: core 0's boot context (kmain), or another core's
//! `smp::secondary_main`. The task table is one [`SpinLock`]; what a core
//! keeps for itself is [`PerCore`]. Waking a task on another core sends
//! that core an interrupt, so it switches at once, not at its next tick.

use crate::exceptions::Frame;
use crate::mm::space::AddressSpace;
use crate::object::Object;
use crate::smp::MAX_CORES;
use crate::sync::{Global, PerCore, SpinLock};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicU64, Ordering};
use pinnacle_abi::call;

/// Task slots: one idle task a core the kernel can run on, then the rest.
const MAX_TASKS: usize = crate::smp::MAX_CORES + 128;
pub const STACK_SIZE: usize = 16 * 1024;
const _: () = assert!(
    STACK_SIZE.is_power_of_two(),
    "boot finds a core's stack by shifting"
);
/// Where a program's mappings (heap, shared memory) start: 64 GiB.
const MAP_BASE: usize = 0x10_0000_0000;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum State {
    Free,
    Ready,
    /// Waiting to be woken, or until this time (ms since boot).
    Blocked(Option<u64>),
    /// Ended, but its core may still be on its stack: it becomes `Exited` at
    /// the core's next switch, from another task's stack.
    Exiting(u64),
    /// Ended with this code, until [`wait`] collects it.
    Exited(u64),
}

/// What a program owns beyond its registers.
pub struct Process {
    pub space: AddressSpace,
    /// Handle n is `handles[n - 1]`.
    pub handles: Vec<Option<Object>>,
    /// Where the next mapping goes, when no address range given back fits.
    pub next_map: usize,
    /// Address ranges given back (start, length, each with its guard page),
    /// by start, none touching another: taken again before `next_map`.
    pub holes: Vec<(usize, usize)>,
    /// The program's own memory `map_memory` gave, by address: its pages.
    pub private: alloc::collections::BTreeMap<usize, usize>,
    /// Shared memory it has mapped, and where: kept alive while mapped
    /// even when its handles are gone, until the program unmaps it.
    pub mapped: Vec<(usize, alloc::sync::Arc<crate::object::Memory>)>,
    /// May take the framebuffer and the input devices.
    pub privileged: bool,
    /// An installed app, by name: confined to its own folder (see the
    /// file calls in `syscall`).
    pub confined: Option<alloc::string::String>,
    /// Started with `SPAWN_SEALED`: it reaches only what its handles
    /// reach (no network, no service by name, no path, no spawning).
    pub sealed: bool,
    /// May use the network: every program the system starts; an app only
    /// when its manifest says so (`syscall::spawn`).
    pub network: bool,
    /// How it ended: the code its last `exit_process` gave, or a kill's.
    pub code: u64,
    /// Who started it and asked to know: as the program goes, its code is
    /// sent here, eight bytes, and the channel closes.
    pub watch: Option<Arc<crate::object::Endpoint>>,
    /// Its number for `ps` and `kill`: never one another program had, as a
    /// task slot is.
    pub id: u64,
    /// The program's name, as it was started (empty for a check's).
    pub name: alloc::string::String,
    /// When it started, ms since boot.
    pub started: u64,
}

/// Numbers the programs started, for [`Process::id`].
static PROCESS_IDS: AtomicU64 = AtomicU64::new(1);

/// What `ps` says of one program ([`processes`]).
pub struct Running {
    pub id: u64,
    pub name: alloc::string::String,
    pub threads: usize,
    /// The memory it asked for and the shared memory it has mapped, in bytes.
    pub memory: usize,
    pub started: u64,
    pub privileged: bool,
    pub app: bool,
    pub sealed: bool,
}

/// Every program that runs, in the order they started.
pub fn processes() -> Vec<Running> {
    let mut found: Vec<(Arc<SpinLock<Process>>, usize)> = Vec::new();
    {
        let tasks = TASKS.lock();
        for task in tasks.tasks.iter().skip(MAX_CORES) {
            let Some(process) = task.process.as_ref() else {
                continue;
            };
            if !matches!(task.state, State::Ready | State::Blocked(_)) {
                continue;
            }
            match found.iter_mut().find(|(p, _)| Arc::ptr_eq(p, process)) {
                Some((_, threads)) => *threads += 1,
                None => found.push((process.clone(), 1)),
            }
        }
    }
    // Each program's lock taken with the task lock let go, as `with_process`
    // does; a hold dropped here may be a program's last, which frees it.
    let mut all: Vec<Running> = found
        .iter()
        .map(|(process, threads)| {
            let p = process.lock();
            let private: usize = p.private.values().sum::<usize>() * crate::mm::PAGE;
            let shared: usize = p.mapped.iter().map(|(_, m)| m.size).sum();
            Running {
                id: p.id,
                name: p.name.clone(),
                threads: *threads,
                memory: private + shared,
                started: p.started,
                privileged: p.privileged,
                app: p.confined.is_some(),
                sealed: p.sealed,
            }
        })
        .collect();
    drop(found);
    all.sort_by_key(|r| r.id);
    all
}

/// The program numbered `id`, while it runs.
pub fn process_by_id(id: u64) -> Option<Arc<SpinLock<Process>>> {
    let candidates: Vec<Arc<SpinLock<Process>>> = {
        let tasks = TASKS.lock();
        tasks.tasks.iter().filter_map(|t| t.process.clone()).collect()
    };
    candidates.into_iter().find(|p| p.lock().id == id)
}

/// Names the program task `id` runs, for `ps`.
pub fn name(id: usize, name: &[u8]) {
    if let Some(process) = process_of(id).and_then(|p| p.upgrade()) {
        process.lock().name = alloc::string::String::from_utf8_lossy(name).into_owned();
    }
}

impl Drop for Process {
    fn drop(&mut self) {
        if let Some(watch) = self.watch.take() {
            watch.send(crate::object::Message {
                bytes: self.code.to_le_bytes().to_vec(),
                handles: Vec::new(),
            });
        }
    }
}

impl Process {
    pub fn add_handle(&mut self, object: Object) -> u64 {
        let slot = match self.handles.iter().position(Option::is_none) {
            Some(i) => i,
            None => {
                self.handles.push(None);
                self.handles.len() - 1
            }
        };
        self.handles[slot] = Some(object);
        slot as u64 + 1
    }

    pub fn handle(&self, handle: u64) -> Option<&Object> {
        self.handles.get((handle as usize).checked_sub(1)?)?.as_ref()
    }

    pub fn take_handle(&mut self, handle: u64) -> Option<Object> {
        self.handles.get_mut((handle as usize).checked_sub(1)?)?.take()
    }

    /// Reserves `size` bytes of the program's address space for a mapping,
    /// and an unmapped guard page after them.
    pub fn reserve(&mut self, size: usize) -> usize {
        let length = size.next_multiple_of(crate::mm::PAGE) + crate::mm::PAGE;
        if let Some(i) = self.holes.iter().position(|&(_, hole)| hole >= length) {
            let (at, hole) = self.holes[i];
            if hole == length {
                self.holes.remove(i);
            } else {
                self.holes[i] = (at + length, hole - length);
            }
            return at;
        }
        let at = self.next_map;
        self.next_map += length;
        at
    }

    /// Gives back what [`reserve`](Self::reserve) answered `at` for `size`,
    /// nothing mapped in it any more.
    pub fn release(&mut self, at: usize, size: usize) {
        let length = size.next_multiple_of(crate::mm::PAGE) + crate::mm::PAGE;
        let i = self.holes.partition_point(|&(start, _)| start < at);
        self.holes.insert(i, (at, length));
        // Joined with the range after it, then with the one before.
        if let Some(&(next, next_length)) = self.holes.get(i + 1)
            && at + length == next
        {
            self.holes[i].1 += next_length;
            self.holes.remove(i + 1);
        }
        if i > 0 && self.holes[i - 1].0 + self.holes[i - 1].1 == at {
            self.holes[i - 1].1 += self.holes[i].1;
            self.holes.remove(i);
        }
    }
}

struct Task {
    state: State,
    core: usize,
    /// Where its context was saved; null while it runs (and for an idle
    /// task, until its first switch away).
    frame: *mut Frame,
    /// The program it is a thread of; every thread of it holds one.
    process: Option<Arc<SpinLock<Process>>>,
    /// That program's TTBR0 value, kept here so a switch takes no lock.
    ttbr: u64,
    /// Someone will `wait` for it; otherwise its slot frees itself when it
    /// ends.
    waited: bool,
    /// Its program ended while it ran on its core: it ends at its next switch.
    doomed: bool,
    /// Woken while not blocked: its next block returns at once.
    woken: bool,
    /// A number no other task started has had: tells a slot's tasks apart.
    serial: u64,
    /// Its FP/SIMD registers while another task's are loaded.
    fp: FpState,
}

// SAFETY: a task's frame pointer is only followed by the core it is bound to.
unsafe impl Send for Task {}

impl Task {
    const FREE: Task = Task {
        state: State::Free,
        core: 0,
        frame: core::ptr::null_mut(),
        process: None,
        ttbr: 0,
        waited: false,
        doomed: false,
        woken: false,
        serial: 0,
        fp: FpState::ZERO,
    };
}

struct Tasks {
    tasks: [Task; MAX_TASKS],
}

static TASKS: SpinLock<Tasks> = SpinLock::new(Tasks {
    tasks: {
        let mut tasks = [Task::FREE; MAX_TASKS];
        // Every core's idle task is ready from the start: it is what the
        // core runs when it starts.
        let mut core = 0;
        while core < MAX_CORES {
            tasks[core].state = State::Ready;
            tasks[core].core = core;
            core += 1;
        }
        tasks
    },
});

#[derive(Clone, Copy)]
struct Core {
    /// The slot it runs; its idle task's until the first switch.
    current: Option<usize>,
    /// What its TTBR0 holds, or 0 while its lower half is closed.
    ttbr0: u64,
    /// A task that exited on this core and is still `Exiting`.
    exiting: Option<usize>,
    /// The task whose FP/SIMD registers are loaded (see `fp_trap`).
    fp_owner: Option<(usize, u64)>,
    /// Whether its idle task has nothing left to do but wait ([`idle`]): it
    /// then runs only when no other task can. Until then (core 0 runs the
    /// boot and the self-check on it) it takes its turn like any task.
    parked: bool,
}

static CORES: PerCore<Core> = PerCore::new(Core {
    current: None,
    ttbr0: 0,
    exiting: None,
    fp_owner: None,
    parked: false,
});

#[repr(C, align(16))]
pub struct Stack([u8; STACK_SIZE]);

/// The top of task `slot`'s kernel stack.
pub fn stack_top(slot: usize) -> u64 {
    // SAFETY: only the address is taken.
    unsafe { STACKS.get()[slot].0.as_ptr_range().end as u64 }
}

/// Every task's kernel stack, by slot: a core other than 0 starts on its
/// idle slot's (`boot::_start_secondary`). Touched only under [`TASKS`]'s
/// lock, for a free slot, or by its own task.
pub static STACKS: Global<[Stack; MAX_TASKS]> = Global::new([const { Stack([0; STACK_SIZE]) }; MAX_TASKS]);

/// Numbers the tasks started, for `Task::serial`.
static SERIAL: AtomicU64 = AtomicU64::new(0);
static SWITCHES: AtomicU64 = AtomicU64::new(0);
static YIELDS: AtomicU64 = AtomicU64::new(0);

/// The interrupt one core sends another to make it switch now.
pub const RESCHEDULE: u32 = 1;

fn this_core() -> &'static mut Core {
    // SAFETY: called with IRQs masked (exception handlers, or under the
    // tasks lock); one reference at a time.
    let core = unsafe { CORES.get() };
    core.current.get_or_insert(crate::arch::core_id());
    core
}

/// What a new task starts with: its first registers, and the program it is
/// a thread of (with that program's TTBR0), if any.
type First = (Frame, Option<(Arc<SpinLock<Process>>, u64)>);

/// Takes a free slot on core `on`, or the online core with fewest tasks, and
/// writes the task's first frame at the top of its kernel stack: a new task
/// starts as if returning from an exception.
fn start(
    tasks: &mut Tasks,
    on: Option<usize>,
    waited: bool,
    first: impl FnOnce(usize) -> Option<First>,
) -> Option<usize> {
    let slot = (MAX_CORES..MAX_TASKS).find(|&i| tasks.tasks[i].state == State::Free)?;
    let online = crate::smp::online();
    let load = |core: usize| {
        tasks
            .tasks
            .iter()
            .filter(|t| t.state != State::Free && t.core == core)
            .count()
    };
    let core = match on {
        Some(core) => Some(core).filter(|&c| online & (1 << c) != 0)?,
        None => (0..MAX_CORES)
            .filter(|&c| online & (1 << c) != 0)
            .min_by_key(|&c| load(c))?,
    };
    let (mut registers, program) = first(slot)?;
    let (process, ttbr) = match program {
        Some((p, ttbr)) => (Some(p), ttbr),
        None => (None, 0),
    };
    // SAFETY: the slot is free, so nothing runs on its stack.
    let stack = unsafe { &mut STACKS.get()[slot] };
    let frame = stack.0.as_mut_ptr_range().end.cast::<Frame>().wrapping_sub(1);
    registers.placed_at(frame as u64);
    // SAFETY: the frame lies at the top of the task's own stack.
    unsafe { frame.write(registers) };
    tasks.tasks[slot] = Task {
        state: State::Ready,
        core,
        frame,
        process,
        ttbr,
        waited,
        doomed: false,
        woken: false,
        serial: SERIAL.fetch_add(1, Ordering::Relaxed) + 1,
        fp: FpState::ZERO,
    };
    // The core may be asleep with its timer off: it switches to it now.
    crate::gic::send_sgi(core, RESCHEDULE);
    Some(slot)
}

/// Starts `entry` as a kernel task; it runs from its core's next switch to
/// it, and returning from it ends the task with code 0.
pub fn spawn(entry: fn()) -> usize {
    spawn_on(None, entry)
}

/// As [`spawn`], on core `core` if it is given.
pub fn spawn_on(core: Option<usize>, entry: fn()) -> usize {
    start(&mut TASKS.lock(), core, true, |_| {
        let ret = kernel_task_return as *const () as u64;
        Some((Frame::kernel_task(entry as *const () as u64, ret), None))
    })
    .expect("no free task slot")
}

/// Where a kernel task's entry returns to.
extern "C" fn kernel_task_return() -> ! {
    crate::arch::kernel_call(call::EXIT, 0);
    unreachable!("EXIT returned")
}

/// Loads `elf` into a new address space and starts it in user mode, with
/// `argument` in x0 and `handles` in its table from 1. Returns its task id.
pub fn spawn_program(
    elf: &[u8],
    argument: u64,
    handles: Vec<Object>,
    privileged: bool,
    waited: bool,
    confined: Option<alloc::string::String>,
) -> Result<usize, crate::process::Error> {
    let network = confined.is_none();
    spawn_program_with(elf, argument, handles, privileged, waited, confined, network)
}

/// As [`spawn_program`], saying whether the program may use the network
/// (an app's manifest may grant it); set before it runs, since it may run
/// on another core at once.
pub fn spawn_program_with(
    elf: &[u8],
    argument: u64,
    handles: Vec<Object>,
    privileged: bool,
    waited: bool,
    confined: Option<alloc::string::String>,
    network: bool,
) -> Result<usize, crate::process::Error> {
    spawn_program_watched(
        &mut { elf },
        argument,
        handles,
        privileged,
        waited,
        confined,
        network,
        false,
        None,
    )
}

/// As [`spawn_program_with`], telling `watch`'s peer the program's exit code
/// as it ends ([`Process::watch`]).
#[allow(clippy::too_many_arguments)]
pub fn spawn_program_watched(
    elf: &mut dyn crate::process::Image,
    argument: u64,
    handles: Vec<Object>,
    privileged: bool,
    waited: bool,
    confined: Option<alloc::string::String>,
    network: bool,
    sealed: bool,
    watch: Option<Arc<crate::object::Endpoint>>,
) -> Result<usize, crate::process::Error> {
    // Loaded before the task lock is taken: an installed program is read
    // from its disk as it loads, and a disk's reads sleep.
    let mut space = AddressSpace::new()?;
    let entry = crate::process::load(elf, &mut space)?;
    start(&mut TASKS.lock(), None, waited, |_| {
        let stack = crate::process::STACK_TOP as u64;
        let handles = handles.into_iter().map(Some).collect();
        let ttbr = space.ttbr();
        let process = Process {
            space,
            handles,
            next_map: MAP_BASE,
            holes: Vec::new(),
            private: alloc::collections::BTreeMap::new(),
            mapped: Vec::new(),
            privileged,
            network: network && !sealed,
            sealed,
            confined,
            code: 0,
            watch,
            id: PROCESS_IDS.fetch_add(1, Ordering::Relaxed),
            name: alloc::string::String::new(),
            started: crate::timer::now_ms(),
        };
        Some((
            Frame::program(entry as u64, stack, argument),
            Some((Arc::new(SpinLock::new(process)), ttbr)),
        ))
    })
    .ok_or(crate::process::Error::OutOfMemory)
}

/// What a core's idle task does once it has nothing else to: it runs only
/// when no other task on the core can, and sleeps until an interrupt, with
/// the core's timer off unless something is due.
pub fn idle() -> ! {
    {
        let _tasks = TASKS.lock();
        this_core().parked = true;
    }
    loop {
        crate::arch::wait_for_interrupt();
    }
}

/// Waits for task `id` to end, frees its slot and returns its exit code.
pub fn wait(id: usize) -> u64 {
    loop {
        {
            let mut tasks = TASKS.lock();
            if let State::Exited(code) = tasks.tasks[id].state {
                tasks.tasks[id] = Task::FREE;
                return code;
            }
        }
        crate::arch::wait_for_interrupt();
    }
}

/// Makes task `id` ready if it is blocked (sending its core an interrupt to
/// switch now), or makes its next block return at once.
pub fn wake(id: usize) {
    let mut tasks = TASKS.lock();
    let task = &mut tasks.tasks[id];
    match task.state {
        State::Blocked(_) => {
            task.state = State::Ready;
            crate::gic::send_sgi(task.core, RESCHEDULE);
        }
        State::Ready => task.woken = true,
        _ => {}
    }
}

/// Blocks the calling task from inside the kernel (a system call waiting
/// for a device, a kernel task) until [`wake`]; a wake that came since the
/// task last ran makes it return at once. It resumes where it was, so the
/// caller may hold a [`crate::sync::Mutex`] across it, but no spin lock. Not
/// for an idle task, which cannot block: it waits for an interrupt instead.
pub fn sleep() {
    crate::arch::kernel_call(call::BLOCK, 0);
}

/// Whether a saved frame is kernel code's: the task was interrupted, or
/// went to [`sleep`], part way through the kernel, perhaps holding a lock
/// or a device request, and must finish that before it can end.
fn in_kernel(frame: *const Frame) -> bool {
    // SAFETY: the saved frame of a task that is off every core.
    unsafe { (*frame).is_kernel() }
}

/// Blocks the calling task until [`wake`] or `deadline` (ms since boot),
/// from inside a system call: the caller rewinds the call first, so that it
/// runs again when the task resumes. Returns the frame to resume.
pub fn block(frame: *mut Frame, deadline: Option<u64>) -> *mut Frame {
    let mut tasks = TASKS.lock();
    let slot = this_core().current.unwrap();
    let task = &mut tasks.tasks[slot];
    if core::mem::take(&mut task.woken) {
        return frame;
    }
    task.state = State::Blocked(deadline);
    let next = next(&mut tasks, frame);
    drop(tasks);
    bury();
    next
}

/// Gives the rest of this time slice to the next ready task (from a kernel
/// task; programs make the same call through the ABI).
pub fn yield_now() {
    crate::arch::kernel_call(call::YIELD, 0);
}

/// A tick, or another core asking this one to switch.
pub fn preempt(frame: *mut Frame) -> *mut Frame {
    let next = next(&mut TASKS.lock(), frame);
    bury();
    next
}

/// A YIELD call.
pub fn switch(frame: *mut Frame) -> *mut Frame {
    YIELDS.fetch_add(1, Ordering::Relaxed);
    let next = next(&mut TASKS.lock(), frame);
    bury();
    next
}

/// An EXIT call, or a program killed for a fault: the task ends, and its
/// handles and address space go.
pub fn exit(frame: *mut Frame, code: u64) -> *mut Frame {
    let mut tasks = TASKS.lock();
    let core = this_core();
    let slot = core.current.unwrap();
    assert!(slot >= MAX_CORES, "an idle task exited");
    let process = end_running(&mut tasks, core, slot, code);
    let next = next(&mut tasks, frame);
    drop(tasks);
    // Its handles may wake others, which takes the lock.
    drop(process);
    bury();
    next
}

/// An EXIT_PROCESS call: the program ends, every thread of it.
pub fn exit_process(frame: *mut Frame, code: u64) -> *mut Frame {
    {
        let mut tasks = TASKS.lock();
        let me = this_core().current.unwrap();
        if let Some(process) = tasks.tasks[me].process.clone() {
            end_threads(&mut tasks, &process, Some(me), code);
        }
    }
    bury();
    exit(frame, code)
}

/// Ends program `process` from outside it (a KILL call): every thread of it,
/// with [`KILLED`](pinnacle_abi::KILLED) for its code.
pub fn kill(process: &Arc<SpinLock<Process>>) {
    end_threads(&mut TASKS.lock(), process, None, pinnacle_abi::KILLED);
    bury();
}

/// The program task `id` runs, to name it by (a handle, as SPAWN gives).
pub fn process_of(id: usize) -> Option<alloc::sync::Weak<SpinLock<Process>>> {
    TASKS.lock().tasks.get(id)?.process.as_ref().map(Arc::downgrade)
}

/// Ends every thread of `process` but `except` (the caller). Threads not
/// running end at once; one running on another core ends at that core's
/// next switch, which an interrupt brings about now.
fn end_threads(tasks: &mut Tasks, process: &Arc<SpinLock<Process>>, except: Option<usize>, code: u64) {
    process.lock().code = code;
    for (i, t) in tasks.tasks.iter_mut().enumerate().skip(MAX_CORES) {
        if Some(i) == except || !t.process.as_ref().is_some_and(|p| Arc::ptr_eq(p, process)) {
            continue;
        }
        match t.state {
            State::Ready | State::Blocked(_) if !t.frame.is_null() && !in_kernel(t.frame) => {
                // Off every core, and out of the kernel: its stack is free.
                // (One asleep inside the kernel is doomed instead: what it
                // waits for wakes it, it finishes, and ends at its next switch.)
                t.state = if t.waited {
                    State::Exited(code)
                } else {
                    State::Free
                };
                GRAVEYARD.lock().extend(t.process.take());
            }
            State::Ready | State::Blocked(_) => {
                t.doomed = true;
                crate::gic::send_sgi(t.core, RESCHEDULE);
            }
            _ => {}
        }
    }
}

/// Ends the task running on this core: it becomes `Exiting` until the core
/// is off its stack. Returns its hold on its program, to drop outside the
/// task lock.
fn end_running(tasks: &mut Tasks, core: &mut Core, slot: usize, code: u64) -> Option<Arc<SpinLock<Process>>> {
    let task = &mut tasks.tasks[slot];
    task.state = State::Exiting(code);
    task.doomed = false;
    let process = task.process.take();
    if process.is_some() && core.ttbr0 == task.ttbr {
        crate::mmu::close_lower_half();
        core.ttbr0 = 0;
    }
    // One task waits per core: settle the one before, whose stack this core
    // has left, before this one takes its place.
    reap(tasks, core, slot);
    core.exiting = Some(slot);
    if core.fp_owner.is_some_and(|(o, _)| o == slot) {
        core.fp_owner = None;
    }
    process
}

/// Holds on programs let go of under the task lock: dropping the last one
/// frees an address space and closes handles, which may wake tasks.
static GRAVEYARD: SpinLock<Vec<Arc<SpinLock<Process>>>> = SpinLock::new(Vec::new());

/// Drops what the graveyard holds; never called with the task lock held.
fn bury() {
    let dead = core::mem::take(&mut *GRAVEYARD.lock());
    drop(dead);
}

/// The running task's id.
pub fn current() -> usize {
    let _masked = crate::irq::Masked::new();
    this_core().current.unwrap()
}

/// Runs `f` on the running task's process, if it is a program. `f` must
/// not send on a channel or wake a task: the program's lock is held.
/// The program the running task belongs to.
pub fn current_process() -> Option<Arc<SpinLock<Process>>> {
    let tasks = TASKS.lock();
    tasks.tasks[this_core().current.unwrap()].process.clone()
}

pub fn with_process<R>(f: impl FnOnce(&mut Process) -> R) -> Option<R> {
    let process = {
        let tasks = TASKS.lock();
        tasks.tasks[this_core().current.unwrap()].process.clone()?
    };
    let mut guard = process.lock();
    Some(f(&mut guard))
}

fn next(tasks: &mut Tasks, frame: *mut Frame) -> *mut Frame {
    let core = this_core();
    let id = crate::arch::core_id();
    let from = core.current.unwrap();
    reap(tasks, core, from);
    tasks.tasks[from].frame = frame;
    if tasks.tasks[from].doomed && from >= MAX_CORES {
        let process = end_running(tasks, core, from, pinnacle_abi::KILLED);
        GRAVEYARD.lock().extend(process);
    }
    // Sleepers whose time has come.
    let now = crate::timer::now_ms();
    for task in tasks.tasks.iter_mut().filter(|t| t.core == id) {
        if let State::Blocked(Some(deadline)) = task.state
            && deadline <= now
        {
            task.state = State::Ready;
        }
    }
    let parked = core.parked;
    let to = (1..=MAX_TASKS)
        .map(|step| (from + step) % MAX_TASKS)
        .find(|&i| tasks.tasks[i].state == State::Ready && tasks.tasks[i].core == id && !(parked && i == id))
        // Only the idle task can run: a core's is always ready.
        .unwrap_or(id);
    // The core's timer: due when the next thing here is. A slice ends while
    // another task waits to run, as an unparked idle task always does; a
    // sleeper wakes at its deadline; core 0 also runs the network's timers.
    let mine = || tasks.tasks.iter().enumerate().filter(|(_, t)| t.core == id);
    let sharing = !parked || mine().any(|(i, t)| i >= MAX_CORES && i != to && t.state == State::Ready);
    let sleepers = mine().filter_map(|(_, t)| match t.state {
        State::Blocked(deadline) => deadline,
        _ => None,
    });
    let network = if id == 0 {
        crate::drivers::net::deadline()
    } else {
        None
    };
    let slice = sharing.then_some(now + crate::timer::SLICE_MS);
    // A task that ended here is settled at the next switch, once the core is
    // off its stack (`reap`): make that at once, or a sleeping core never would.
    let settle = core.exiting.map(|_| now);
    crate::timer::arm(sleepers.chain(network).chain(slice).chain(settle).min());
    if to != from {
        SWITCHES.fetch_add(1, Ordering::Relaxed);
    }
    // A kernel task leaves TTBR0 as it is on ARM: it never uses the lower
    // half. On a PC it closes it (below).
    if tasks.tasks[to].process.is_some() {
        let ttbr = tasks.tasks[to].ttbr;
        if ttbr != core.ttbr0 {
            crate::mmu::switch_lower_half(ttbr);
            if core.ttbr0 == 0 {
                crate::mmu::open_lower_half();
            }
            core.ttbr0 = ttbr;
        }
    } else if crate::mmu::PROGRAM_TABLES_HOLD_THE_KERNEL && core.ttbr0 != 0 {
        // On a PC the program's root is the kernel's tables too: left on it,
        // this core would take its next interrupt on freed tables once the
        // program ends elsewhere (a kill frees it while no core runs it).
        crate::mmu::close_lower_half();
        core.ttbr0 = 0;
    }
    // FP/SIMD stays trapped unless the registers hold this task's.
    set_fp_access(core.fp_owner == Some((to, tasks.tasks[to].serial)));
    crate::arch::entering_task(stack_top(to));
    core.current = Some(to);
    let next = tasks.tasks[to].frame;
    tasks.tasks[to].frame = core::ptr::null_mut();
    next
}

pub fn switches() -> u64 {
    SWITCHES.load(Ordering::Relaxed)
}

pub fn yields() -> u64 {
    YIELDS.load(Ordering::Relaxed)
}

/// Settles the task that exited on this core earlier, now that the core
/// runs on another stack (`on`'s): its slot can be waited for and reused.
fn reap(tasks: &mut Tasks, core: &mut Core, on: usize) {
    if let Some(slot) = core.exiting.filter(|&s| s != on) {
        if let State::Exiting(code) = tasks.tasks[slot].state {
            // Nobody waits for it: its slot is free at once.
            tasks.tasks[slot].state = if tasks.tasks[slot].waited {
                State::Exited(code)
            } else {
                State::Free
            };
        }
        core.exiting = None;
    }
}

/// A program's FP/SIMD registers (q0–q31, FPCR, FPSR), saved while another
/// program's are in the core's registers.
#[repr(C, align(16))]
#[derive(Clone, Copy)]
pub struct FpState([u8; 528]);

impl FpState {
    const ZERO: FpState = FpState([0; 528]);
}

/// Whether a program's FP/SIMD use goes ahead or traps (`fp_trap`).
fn set_fp_access(open: bool) {
    crate::arch::fp_access(open);
}

/// Saves the core's FP/SIMD registers into `state`.
fn save_fp(state: &mut FpState) {
    crate::arch::save_fp(&mut state.0);
}

/// Loads the core's FP/SIMD registers from `state`.
fn load_fp(state: &FpState) {
    crate::arch::load_fp(&state.0);
}

/// A program used FP/SIMD while its registers were not loaded: hand it the
/// core's registers, saving the previous owner's, and let it run the same
/// instruction again. Programs that never use them never come here, and one
/// that is the only user on its core comes here once.
pub fn fp_trap(frame: *mut Frame) -> *mut Frame {
    let mut tasks = TASKS.lock();
    let core = this_core();
    let me = core.current.unwrap();
    let mine = (me, tasks.tasks[me].serial);
    if let Some((owner, serial)) = core.fp_owner.filter(|&o| o != mine) {
        let mut saved = FpState::ZERO;
        set_fp_access(true);
        save_fp(&mut saved);
        // Only if the slot still holds that task: a new one starts clean.
        if tasks.tasks[owner].serial == serial {
            tasks.tasks[owner].fp = saved;
        }
    }
    set_fp_access(true);
    load_fp(&tasks.tasks[me].fp);
    core.fp_owner = Some(mine);
    frame
}

/// Starts a thread of the running program: a task sharing its address space
/// and handles, at `entry` with `stack` and `argument` in x0, on the core
/// with fewest tasks. Returns its task id.
pub fn spawn_thread(entry: u64, stack: u64, argument: u64) -> Option<usize> {
    let mut tasks = TASKS.lock();
    let me = this_core().current.unwrap();
    let process = tasks.tasks[me].process.clone()?;
    let ttbr = tasks.tasks[me].ttbr;
    start(&mut tasks, None, false, |_| {
        Some((Frame::program(entry, stack, argument), Some((process, ttbr))))
    })
}

/// As [`wait`], giving up at `deadline` (ms since boot): `None` then.
pub fn wait_until(id: usize, deadline: u64) -> Option<u64> {
    loop {
        {
            let mut tasks = TASKS.lock();
            if let State::Exited(code) = tasks.tasks[id].state {
                tasks.tasks[id] = Task::FREE;
                return Some(code);
            }
        }
        if crate::timer::now_ms() >= deadline {
            return None;
        }
        crate::arch::wait_for_interrupt();
    }
}

/// Every task in use, for a check that waited too long: its slot, core,
/// state, and whether a core runs it now (no saved frame).
pub fn describe() {
    let tasks = TASKS.lock();
    for (slot, task) in tasks.tasks.iter().enumerate() {
        if task.state == State::Free {
            continue;
        }
        // SAFETY: a task off its core keeps its frame until it runs again;
        // the lock held keeps it so.
        let at = (!task.frame.is_null()).then(|| unsafe { ((*task.frame).pc(), (*task.frame).status()) });
        crate::println!(
            "  task {slot}: core {}, {:?}{}{}{}",
            task.core,
            task.state,
            match at {
                None => alloc::string::String::from(", on its core"),
                Some((pc, spsr)) => alloc::format!(", stopped at {pc:#x}, spsr {spsr:#x}"),
            },
            if task.woken { ", woken" } else { "" },
            if task.doomed { ", doomed" } else { "" },
        );
    }
}