garage44.eu/jeroen/pinnacle

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

.. /kernel/src/install.rs

raw

//! Installing Pinnacle on one of the device's own disks, from the medium
//! it was started from (a USB stick): what makes the device boot without
//! the stick.
//!
//! The disk gets a partition table (`pinnacle_disk::gpt`) with three
//! partitions, each starting on a whole MiB:
//!
//! 1. **boot**, the EFI system partition (FAT32): the loader where a UEFI
//!    firmware looks for one on a disk it has no entry for
//!    (`EFI/BOOT/BOOTAA64.EFI` or `BOOTX64.EFI`, U-Boot's UEFI as well),
//!    the kernel (`PINNACLE/KERNEL`) and its command line
//!    (`PINNACLE/CMDLINE`), which names the system partition (`root=`):
//!    the very files the medium's own boot partition holds.
//! 2. **system**, Pinnacle's file system labelled `system`, with every file
//!    of the running system copied into it: apps, fonts, settings, the
//!    system slots (`docs/updates.md`).
//! 3. **data**, the rest, left blank: at the first start from the disk the
//!    person chooses the passphrase that makes it their vault.
//!
//! The firmware's own boot entries (UEFI's `Boot####` variables) are not
//! written: the kernel does not call UEFI's runtime services. A firmware
//! that boots only from its entries needs one made in its setup screen.
//!
//! It runs as a kernel task of its own, started by the system call
//! `install` (Settings → Storage), which asks how it goes meanwhile; or at
//! boot, from `install-to=<disk>` on the command line (`cargo xtask
//! install-test`), after which the machine is turned off.

use crate::drivers::block::{self, BLOCK, Device, Store};
use crate::println;
use crate::sync::SpinLock;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_disk::gpt::{self, Guid, Partition, Table};
use pinnacle_disk::{Medium, fat};
use pinnacle_fs::{Disk, Fs, Kind};

/// The boot partition's size: room for a FAT32 and two kernels.
const BOOT_MIB: u64 = 300;
/// The least room the data partition gets.
const DATA_MIN_MIB: u64 = 64;

/// The loader's place on the boot partition, for this architecture.
#[cfg(target_arch = "aarch64")]
const LOADER: &str = "EFI/BOOT/BOOTAA64.EFI";
#[cfg(target_arch = "x86_64")]
const LOADER: &str = "EFI/BOOT/BOOTX64.EFI";
const KERNEL: &str = "PINNACLE/KERNEL";
const CMDLINE: &str = "PINNACLE/CMDLINE";

/// How an installation goes, for the system call to answer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum State {
    Idle,
    Running(String),
    Done(String),
    Failed(String),
}

static STATE: SpinLock<State> = SpinLock::new(State::Idle);
/// The disk the task was started for.
static TARGET: SpinLock<Option<String>> = SpinLock::new(None);

fn report(what: String) {
    println!("install: {what}");
    *STATE.lock() = State::Running(what);
}

pub fn state() -> State {
    STATE.lock().clone()
}

/// Whether there is a boot partition to install from: the system was
/// started from a disk by its loader, not by QEMU's `-kernel`.
pub fn possible() -> bool {
    block::boot_partition().is_some()
}

/// The least a disk must hold for Pinnacle, the running system's files
/// with room to spare.
pub fn min_bytes() -> u64 {
    ((BOOT_MIB + DATA_MIN_MIB) << 20) + system_bytes()
}

/// What the system partition gets: twice what the running system's files
/// take, at least 512 MiB.
fn system_bytes() -> u64 {
    let used = block::with_disk("system:/", |fs, _| {
        u64::from(fs.capacity() - fs.free()) * BLOCK as u64
    })
    .unwrap_or(0);
    (2 * used).max(512 << 20).next_multiple_of(1 << 20)
}

/// Starts installing on `disk` in a task of its own. False when one is
/// running already, or the disk is not free.
pub fn start(disk: &str) -> bool {
    {
        let mut state = STATE.lock();
        if matches!(*state, State::Running(_)) || block::free_controller(disk).is_none() {
            return false;
        }
        *state = State::Running(String::from("starting"));
    }
    *TARGET.lock() = Some(String::from(disk));
    crate::sched::spawn(task);
    true
}

fn task() {
    let Some(disk) = TARGET.lock().take() else { return };
    let words = extra_words();
    let state = match install(&disk, &words) {
        Ok(summary) => State::Done(summary),
        Err(why) => State::Failed(String::from(why)),
    };
    println!("install: {state:?}");
    *STATE.lock() = state;
}

/// The words of this command line the installed system keeps: all but
/// which partition is the system and what to install.
fn extra_words() -> String {
    crate::args::line()
        .split(' ')
        .filter(|w| !w.is_empty() && !w.starts_with("root=") && !w.starts_with("install-to="))
        .collect::<Vec<_>>()
        .join(" ")
}

/// `install-to=<disk>` on the command line: installs there at once, says
/// how it went and turns the machine off.
pub fn from_command_line() {
    let Some(disk) = crate::args::value("install-to") else {
        return;
    };
    match install(&disk, &extra_words()) {
        Ok(summary) => {
            println!("install: {summary}");
            println!("install ok");
            crate::board::power_off(0)
        }
        Err(why) => {
            println!("install: failed: {why}");
            crate::board::power_off(1)
        }
    }
}

/// 16 random bytes, as a GUID.
fn random_guid() -> Guid {
    let mut bytes = [0u8; 16];
    crate::drivers::random::fill(&mut bytes);
    Guid::random(bytes)
}

/// Installs on `disk`, the installed system's command line ending in
/// `words`. What was done, or why not.
pub fn install(disk: &str, words: &str) -> Result<String, &'static str> {
    let controller = block::free_controller(disk).ok_or("that disk is in use, or not there")?;
    let mut boot = block::boot_partition()
        .ok_or("this system was not started from a disk: it has no boot partition to install from")?;
    // Read as they are written: a kernel is larger than the largest block
    // the kernel's memory hands out (16 MiB).
    let mut loader = fat::Reader::open(&mut boot, 0, LOADER).ok_or("the boot partition has no loader")?;
    let mut kernel = fat::Reader::open(&mut boot, 0, KERNEL).ok_or("the boot partition has no kernel")?;

    let sector = controller.sector();
    let bytes = controller.blocks() * BLOCK as u64;
    let sectors = bytes / sector;
    let (first, last) = gpt::usable(sector, sectors);
    let mib = (1 << 20) / sector;
    let boot_first = gpt::align(sector, first);
    let system_first = boot_first + BOOT_MIB * mib;
    let data_first = system_first + system_bytes() / sector;
    // The data partition ends on a whole MiB too, below the table's copy.
    let data_last = ((last + 1) / mib) * mib - 1;
    if data_last < data_first + DATA_MIN_MIB * mib {
        return Err("the disk is too small for Pinnacle");
    }
    let system_id = random_guid();
    let table = Table {
        sector,
        disk: random_guid(),
        partitions: alloc::vec![
            Partition {
                kind: gpt::EFI_SYSTEM,
                id: random_guid(),
                first: boot_first,
                last: system_first - 1,
                name: String::from("boot"),
            },
            Partition {
                kind: gpt::PINNACLE_SYSTEM,
                id: system_id,
                first: system_first,
                last: data_first - 1,
                name: String::from("Pinnacle system"),
            },
            Partition {
                kind: gpt::PINNACLE_DATA,
                id: random_guid(),
                first: data_first,
                last: data_last,
                name: String::from("Pinnacle data"),
            },
        ],
    };
    report(alloc::format!("partitioning {disk}"));
    let mut whole = Device::whole(controller.clone());
    // Each partition's start blank first: nothing a system before left
    // there is taken for a file system or a vault.
    let zero = block::block_buffer();
    for p in &table.partitions {
        if !whole.write_at(p.first * sector, &zero[..]) {
            return Err("the disk refused a write");
        }
    }
    if !gpt::write(&mut whole, &table) {
        return Err("the partition table could not be written");
    }

    report(String::from("writing the boot partition"));
    let line = if words.is_empty() {
        alloc::format!("root={}", system_id.text())
    } else {
        alloc::format!("root={} {words}", system_id.text())
    };
    let (boot_at, boot_len) = table.partitions[0].range(sector);
    let mut line_at = 0;
    fat::format_from(
        &mut whole,
        boot_at,
        boot_len,
        "PINNACLE",
        u32::from_le_bytes(system_id.0[..4].try_into().unwrap()),
        &[
            (LOADER, loader.size),
            (KERNEL, kernel.size),
            (CMDLINE, line.len() as u64),
        ],
        &mut |file, into| match file {
            0 => loader.read(&mut boot, into),
            1 => kernel.read(&mut boot, into),
            _ => {
                let Some(part) = line.as_bytes().get(line_at..line_at + into.len()) else {
                    return false;
                };
                into.copy_from_slice(part);
                line_at += into.len();
                true
            }
        },
    )?;
    drop(boot);
    whole.flush();
    drop(whole);

    report(String::from("making the system's file system"));
    let (system_at, system_len) = table.partitions[1].range(sector);
    let part = Device::part(
        controller.clone(),
        system_at / BLOCK as u64,
        system_len / BLOCK as u64,
    );
    let mut target = pinnacle_fs::format(Store::Plain(part), "system");
    target.set_clock(crate::board::clock);
    let mut copied = Copied::default();
    copy_tree("/", &mut target, &mut copied)?;
    target.disk_mut().flush();
    if let Err(problem) = target.check() {
        println!("install: the copy is not whole: {problem}");
        return Err("the system copied is not whole");
    }
    drop(target);
    block::now_holds_pinnacle(disk);
    Ok(alloc::format!(
        "Pinnacle on {disk}: {} files, {} MiB",
        copied.files,
        copied.bytes >> 20
    ))
}

#[derive(Default)]
struct Copied {
    files: usize,
    folders: usize,
    bytes: u64,
}

/// What a file is read and written in: 1 MiB at a time.
const CHUNK: u64 = 1 << 20;

/// Copies `path` of the running system, and all under it, to the same
/// path on `target`.
fn copy_tree(path: &str, target: &mut Fs<Store>, copied: &mut Copied) -> Result<(), &'static str> {
    let source = alloc::format!("system:{path}");
    let stat = block::with_disk(&source, |fs, p| fs.stat(p))
        .and_then(Result::ok)
        .ok_or("a file of the system could not be read")?;
    match stat.kind {
        Kind::Directory => {
            if path != "/" {
                target
                    .create_dir(path)
                    .map_err(|_| "a folder could not be made")?;
            }
            copied.folders += 1;
            if copied.folders.is_multiple_of(50) {
                report(alloc::format!(
                    "copying the system: {} files, {} MiB",
                    copied.files,
                    copied.bytes >> 20
                ));
            }
            let names = block::with_disk(&source, |fs, p| fs.list(p))
                .and_then(Result::ok)
                .ok_or("a folder of the system could not be read")?;
            for name in names {
                let name = name.trim_end_matches('/');
                let child = if path == "/" {
                    alloc::format!("/{name}")
                } else {
                    alloc::format!("{path}/{name}")
                };
                copy_tree(&child, target, copied)?;
            }
        }
        Kind::File => {
            let mut at = 0;
            if stat.size == 0 {
                target
                    .write(path, &[])
                    .map_err(|_| "a file could not be written")?;
            }
            while at < stat.size {
                let len = CHUNK.min(stat.size - at);
                let data = block::with_disk(&source, |fs, p| fs.read_at(p, at, len))
                    .and_then(Result::ok)
                    .ok_or("a file of the system could not be read")?;
                target
                    .write_at(path, at, &data)
                    .map_err(|_| "a file could not be written (is the disk full?)")?;
                at += len;
            }
            copied.files += 1;
            copied.bytes += stat.size;
        }
    }
    Ok(())
}