//! System updates, the kernel's part (`pinnacle_pkg::system` has the rest): //! which system runs, and handing the machine to a kernel kept on the system //! disk. //! //! The kernel the boot medium holds is the boot kernel. Before the other //! cores start it reads the boot record (`system:/system/boot`): when it //! names a slot whose system is newer than its own, it reads that slot's //! kernel into memory, checks it against the slot's package (signed by a //! key in `system:/settings/system-keys`, the kernel listed with its //! SHA-256), and hands over to it: disks stopped, interrupts and the timer //! off, the caches cleaned and turned off with the MMU, then a jump to the //! image's first byte with the device tree in x0, as a loader starts a //! kernel. The image moves itself to its load address (`boot`), over the //! boot kernel. It is told in x1–x3 that it was handed over to (and from //! which EL the boot kernel was entered, and which slot it is), so it reads //! no record and hands over to nothing. //! //! A slot whose system is not newer, a package that does not open or a //! kernel that does not match leaves the boot kernel running its own; the //! record is told so when it was a try. use alloc::string::String; use alloc::vec::Vec; use core::sync::atomic::{AtomicU64, Ordering}; use pinnacle_pkg::system::{RECORD, Record, Slot, newer}; use crate::println; /// The system's version: the number of commits on main it was built from, /// as `cargo xtask` says; 0 for a build it did not number. pub const VERSION: &str = match option_env!("PINNACLE_VERSION") { Some(v) => v, None => "0", }; /// What a boot kernel puts in x1 when it hands over: "PINNCHAN". pub const HANDED_OVER: u64 = u64::from_be_bytes(*b"PINNCHAN"); /// The slot this kernel runs from (`Slot::number`), 0 for the boot kernel. static SLOT: AtomicU64 = AtomicU64::new(0); /// What the system call `system` op 0 answers. pub fn describe() -> String { let slot = Slot::from_number(SLOT.load(Ordering::Relaxed)).map_or("boot", Slot::name); alloc::format!("version={VERSION}\nboard={}\nslot={slot}\n", crate::board::NAME) } /// Notes that this kernel was handed over to, as slot `slot`. pub fn handed_over(slot: u64) { SLOT.store(slot, Ordering::Relaxed); let name = Slot::from_number(slot).map_or("?", Slot::name); println!("system: version {VERSION}, handed over to from slot {name}"); } fn read(path: &str) -> Option> { crate::drivers::block::with_disk(path, |fs, p| fs.read(p).ok()).flatten() } fn write_record(record: &Record) { let text = record.text(); let written = crate::drivers::block::with_disk(&alloc::format!("system:{RECORD}"), |fs, p| { fs.write(p, text.as_bytes()).is_ok() }); if written != Some(true) { println!("system: could not write the boot record"); } } /// What a slot holds, checked: its version and its kernel's size and /// SHA-256, from its package. None when it holds nothing this kernel may /// run. fn slot_package(slot: Slot) -> Option<(String, u64, [u8; 32])> { let package = read(&alloc::format!("system:{}/package", slot.folder()))?; let keys = read("system:/settings/system-keys").unwrap_or_default(); let trusted = pinnacle_pkg::parse_keys(core::str::from_utf8(&keys).unwrap_or("")); let entries = match pinnacle_pkg::open(&package, &trusted) { Ok(entries) => entries, Err(e) => { println!("system: slot {}'s package: {}", slot.name(), e.describe()); return None; } }; let entry = |want: &str| { entries .iter() .find(|(n, _)| *n == want) .and_then(|(_, data)| core::str::from_utf8(data).ok()) }; let manifest = entry("manifest")?; let field = |key: &str| { manifest .lines() .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) .map(str::trim) }; if field("board") != Some(crate::board::NAME) { println!("system: slot {} is for another board", slot.name()); return None; } let version = field("version")?; let files = pinnacle_pkg::files(entry("files")?)?; let kernel = files.iter().find(|f| f.path == "kernel")?; Some((version.into(), kernel.size, kernel.sha256)) } /// At a start of the boot kernel, before the other cores: hands over to /// the system the boot record names, if it may; returns when this kernel's /// own system runs. pub fn boot(device_tree: usize, entered_at: usize) { crate::drivers::block::init(); let Some(text) = read(&alloc::format!("system:{RECORD}")) else { return; }; let record = Record::parse(core::str::from_utf8(&text).unwrap_or("")); let (slot, write) = record.at_start(); if let Some(failed) = write.and_then(|w| w.failed).filter(|_| record.tried) { println!( "system: slot {}'s system did not start: back to the one before", failed.name() ); } let Some(slot) = slot else { if let Some(write) = write { write_record(&write); } return; }; let refuse = |why: &str| { println!("system: slot {}: {why}; the boot kernel's own runs", slot.name()); // A try that cannot be made has failed. if record.next == Some(slot) { write_record(&Record { next: None, tried: false, failed: Some(slot), ..record }); } }; let Some((version, size, sha256)) = slot_package(slot) else { return refuse("no system this kernel may run"); }; if !newer(&version, VERSION) { // The boot medium's own is as new (a development build, or a boot // medium written since): it runs, the record as it was. println!( "system: slot {} has version {version}, the boot kernel {VERSION}: the boot kernel's runs", slot.name() ); // Not a failure, and not tried again at every start. if record.next == Some(slot) { write_record(&Record { next: None, tried: false, ..record }); } return; } let path = alloc::format!("system:{}/kernel", slot.folder()); let Some(image) = Image::read(&path, size, clear_of(&path)) else { return refuse("its kernel could not be read"); }; if image.sha256() != sha256 { image.free(); return refuse("its kernel is not what its package says"); } if let Some(write) = write { write_record(&write); } println!( "system: handing over to version {version} in slot {}", slot.name() ); image.hand_over(device_tree, entered_at, slot.number()) } /// Restarts the device: what `system` op 1 asks. pub fn restart() -> ! { println!("system: restarting"); crate::board::restart() } /// Turns the device off: what its power button asks (ACPI's, on a PC). #[cfg(target_arch = "x86_64")] pub fn power_off() -> ! { println!("system: turning off"); crate::board::power_off(0) } /// A kernel read into contiguous memory, aligned to 2 MiB as a loader would /// place it. struct Image { /// Its first byte, kernel virtual. at: usize, size: usize, /// The blocks it was read into, to give back if it is not used. blocks: Vec, } impl Image { /// Into blocks at physical `above` and higher: clear of where a PC's /// kernel is copied to (`hand_over`). fn read(path: &str, size: u64, above: usize) -> Option { use crate::mm::pages::{self, MAX_ORDER}; const BLOCK: usize = crate::mm::PAGE << MAX_ORDER; let size = usize::try_from(size).ok()?; let need = size.div_ceil(BLOCK).max(1); // Blocks until `need` of them lie one after another: a fresh // allocator hands them out in order, so that is soon. Those below // `above` are held meanwhile, so as not to be handed out again. let mut blocks: Vec = Vec::new(); let mut below: Vec = Vec::new(); let run = loop { let Some(block) = pages::alloc(MAX_ORDER) else { break None; }; if crate::mmu::physical(block) < above { below.push(block); if below.len() > 256 { break None; } continue; } blocks.push(block); blocks.sort_unstable(); let mut start = 0; let mut found = None; for i in 1..=blocks.len() { if i == blocks.len() || blocks[i] != blocks[i - 1] + BLOCK { if i - start >= need { found = Some(blocks[start]); break; } start = i; } } if found.is_some() { break found; } if blocks.len() > 64 { break None; } }; for b in below { pages::free(b, MAX_ORDER); } let Some(run) = run else { for &b in &blocks { pages::free(b, MAX_ORDER); } return None; }; // The ones outside the run go back now. let (used, spare): (Vec, Vec) = blocks .into_iter() .partition(|&b| b >= run && b < run + need * BLOCK); for b in spare { pages::free(b, MAX_ORDER); } let image = Image { at: run, size, blocks: used, }; const CHUNK: usize = 1 << 20; let mut done = 0; while done < size { let len = CHUNK.min(size - done); let piece = crate::drivers::block::with_disk(path, |fs, p| fs.read_at(p, done as u64, len as u64).ok()) .flatten(); match piece { Some(bytes) if bytes.len() == len => { // SAFETY: the run is ours, `size` bytes long and more. unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), (run + done) as *mut u8, len) }; } _ => { image.free(); return None; } } done += len; } Some(image) } fn bytes(&self) -> &[u8] { // SAFETY: read in full by `read`. unsafe { core::slice::from_raw_parts(self.at as *const u8, self.size) } } fn sha256(&self) -> [u8; 32] { let mut hash = pinnacle_pkg::Sha256::new(); hash.update(self.bytes()); hash.finish() } fn free(self) { for b in self.blocks { crate::mm::pages::free(b, crate::mm::pages::MAX_ORDER); } } /// Hands the machine to it: see the module's text. #[cfg(target_arch = "aarch64")] fn hand_over(self, device_tree: usize, entered_at: usize, slot: u64) -> ! { // An ARM64 boot image: "ARM\x64" at 56. if self.bytes().get(56..60) != Some(b"ARM\x64") { panic!("a slot's kernel is not an ARM64 boot image"); } // SAFETY: masks every exception on this core, the only one running. unsafe { core::arch::asm!("msr daifset, #0xf", options(nostack)) }; crate::timer::arm(None); crate::drivers::block::reset_all(); let (ram_start, ram_end) = crate::mm::ram_range(); let entry = crate::mmu::physical(self.at); let trampoline = crate::mmu::physical(trampoline as *const () as usize); let tables = crate::mmu::physical(&raw const crate::mmu::TABLES as usize); // SAFETY: the lower half maps RAM as it is again (boot's tables), // and the trampoline runs from there with the MMU off: it does not // return. unsafe { core::arch::asm!( "msr ttbr0_el1, {tables}", "isb", tables = in(reg) tables, options(nostack), ); crate::mmu::open_lower_half(); core::arch::asm!( "dsb ish", "tlbi vmalle1", "dsb ish", "isb", "br {trampoline}", trampoline = in(reg) trampoline, in("x0") entry, in("x1") device_tree, in("x2") entered_at, in("x3") slot, in("x4") ram_start, in("x5") ram_end, options(noreturn, nostack), ); } } /// Hands the machine to it, as GRUB would start it: a PC's kernel is /// an ELF, its segments copied to the physical addresses it names (the /// boot kernel's own, from 2 MiB), then entered at its entry in 32-bit /// protected mode, paging off, with Multiboot2's magic in EAX and boot /// information in EBX: the loader's, the slot added to the command /// line ([`crate::loader::SLOT_ARGUMENT`]). The copy runs from a page of /// its own (`trampoline`), above everything it copies to, as the image /// is. #[cfg(target_arch = "x86_64")] fn hand_over(self, _device_tree: usize, _entered_at: usize, slot: u64) -> ! { let Some((entry, loads)) = elf_loads(self.bytes()) else { panic!("a slot's kernel is not an x86-64 ELF"); }; let top = loads.iter().map(|l| l.physical + l.memory).max().unwrap_or(0); let image = crate::mmu::physical(self.at); assert!( image >= top, "a slot's kernel was read where it is to be copied to" ); assert!( image + self.size <= 1 << 32, "a slot's kernel was read above 4 GiB" ); let boot = crate::loader::kept().expect("nothing from the loader"); // A page for the trampoline, its plan and its stack; one for the // boot information: above what is copied to, below 4 GiB. let page = || loop { let p = crate::mm::pages::alloc(0).expect("no page for a handover"); let physical = crate::mmu::physical(p); if physical >= top && physical + crate::mm::PAGE <= 1 << 32 { break p; } }; let (code, info) = (page(), page()); // Page tables of its own for the copy: the boot kernel's lie in what // is copied over. The first 4 GiB as they are, in 1 GiB pages. let (root, directory) = (page(), page()); // SAFETY: two pages of our own, as tables: a root, and the // directory of its first entry. unsafe { let (root, directory) = (root as *mut u64, directory as *mut u64); for i in 0..512 { root.add(i).write(0); directory .add(i) .write(if i < 4 { (i as u64) << 30 | 0x83 } else { 0 }); } root.write(crate::mmu::physical(directory as usize) as u64 | 0x3); } let blob = trampoline_code(); // SAFETY: two pages of our own, written before the jump. let (code_page, info_page) = unsafe { ( core::slice::from_raw_parts_mut(code as *mut u8, crate::mm::PAGE), core::slice::from_raw_parts_mut(info as *mut u8, crate::mm::PAGE), ) }; code_page[..blob.len()].copy_from_slice(blob); // The plan after the code: (to, from, length) a step, from 0 for // memory to clear. let plan_at = blob.len().next_multiple_of(8); let mut steps = 0; for l in &loads { for (to, from, len) in [ (l.physical, image + l.offset, l.file), (l.physical + l.file, 0, l.memory - l.file), ] { if len == 0 { continue; } let at = plan_at + 24 * steps; for (i, word) in [to, from, len].into_iter().enumerate() { code_page[at + 8 * i..at + 8 * i + 8].copy_from_slice(&(word as u64).to_le_bytes()); } steps += 1; } } assert!( plan_at + 24 * steps + 256 <= crate::mm::PAGE, "a handover plan too long" ); let extra = alloc::format!("{}{slot}", crate::loader::SLOT_ARGUMENT); boot.multiboot2(&extra, info_page) .expect("the boot information does not fit a page"); println!( "system: {} segments to {:#x}..{top:#x}, entered at {entry:#x}", loads.len(), loads.iter().map(|l| l.physical).min().unwrap_or(0) ); let code = crate::mmu::physical(code); crate::timer::arm(None); crate::drivers::block::reset_all(); // SAFETY: interrupts off; the trampoline runs from the identity map // (the first 4 GiB, still open: no other core runs), copies over // this kernel and does not return. unsafe { core::arch::asm!( "cli", "jmp {code}", code = in(reg) code, in("rdi") code + plan_at, in("rsi") steps, in("rdx") entry, in("rcx") crate::mmu::physical(info), in("r8") code + crate::mm::PAGE, in("r9") crate::mmu::physical(root), options(noreturn), ) } } #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] fn hand_over(self, _device_tree: usize, _entered_at: usize, _slot: u64) -> ! { panic!("handing over to another kernel is not built for this processor") } } /// Where a slot's kernel may be read to so that handing over does not /// overwrite it: on a PC above every address its ELF is copied to (from /// its first page's headers); an ARM image moves itself, anywhere will do. fn clear_of(path: &str) -> usize { #[cfg(target_arch = "x86_64")] { let head = crate::drivers::block::with_disk(path, |fs, p| fs.read_at(p, 0, 4096).ok()).flatten(); head.as_deref().and_then(elf_loads).map_or(0, |(_, loads)| { loads.iter().map(|l| l.physical + l.memory).max().unwrap_or(0) }) } #[cfg(not(target_arch = "x86_64"))] { let _ = path; 0 } } /// One of an ELF's loadable segments: where it goes, where it is in the /// file, its bytes there and in memory. #[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))] struct Load { physical: usize, offset: usize, file: usize, memory: usize, } /// An x86-64 ELF's entry and loadable segments, from its headers (which /// lie in its first page). The entry is below 4 GiB, where 32-bit code can /// reach it. #[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))] fn elf_loads(elf: &[u8]) -> Option<(usize, Vec)> { let at = |offset: usize, len: usize| -> Option { let bytes = elf.get(offset..offset + len)?; Some(bytes.iter().rev().fold(0, |n, &b| n << 8 | usize::from(b))) }; // "\x7fELF", 64-bit, little-endian; x86-64 (62). if elf.get(..6)? != b"\x7fELF\x02\x01" || at(18, 2)? != 62 { return None; } let entry = at(24, 8)?; let (phoff, phentsize, phnum) = (at(32, 8)?, at(54, 2)?, at(56, 2)?); let mut loads = Vec::new(); for i in 0..phnum { let h = phoff + i * phentsize; const PT_LOAD: usize = 1; if at(h, 4)? != PT_LOAD || at(h + 40, 8)? == 0 { continue; } let load = Load { offset: at(h + 8, 8)?, physical: at(h + 24, 8)?, file: at(h + 32, 8)?, memory: at(h + 40, 8)?, }; if load.file > load.memory { return None; } loads.push(load); } (entry < 1 << 32 && !loads.is_empty()).then_some((entry, loads)) } /// The trampoline's bytes, copied to a page of their own. #[cfg(target_arch = "x86_64")] fn trampoline_code() -> &'static [u8] { unsafe extern "C" { static chain_trampoline: u8; static chain_trampoline_end: u8; } // SAFETY: two labels around the code below, in the image. unsafe { let start = &raw const chain_trampoline; let end = &raw const chain_trampoline_end; core::slice::from_raw_parts(start, end as usize - start as usize) } } // From its page in the identity map, interrupts off: each step of the plan // (rdi, rsi steps of to, from, length; from 0 clears), then down to 32-bit // protected mode, paging and long mode off, and into the kernel (rdx) as // Multiboot2 enters one: its magic in EAX, the information (rcx) in EBX. // r8 is the top of its stack, r9 its page tables (the boot kernel's are // copied over). Position-independent: it runs from a copy. #[cfg(target_arch = "x86_64")] core::arch::global_asm!( ".pushsection .text.chain_trampoline, \"ax\"", ".code64", ".global chain_trampoline", ".global chain_trampoline_end", "chain_trampoline:", // No task's FPU state left pending (CR0.TS): the next kernel's first // SSE instruction runs before it has an IDT. "clts", "mov cr3, r9", "mov rsp, r8", "mov ebx, ecx", "mov ebp, edx", "cld", "2:", "test rsi, rsi", "jz 4f", "mov rcx, [rdi + 16]", "mov rax, [rdi + 8]", "push rdi", "push rsi", "mov rdi, [rdi]", "test rax, rax", "jz 3f", "mov rsi, rax", "rep movsb", "jmp 5f", "3:", "xor eax, eax", "rep stosb", "5:", "pop rsi", "pop rdi", "add rdi, 24", "dec rsi", "jmp 2b", "4:", // Its own GDT, by its address in this copy. "lea rax, [rip + 7f]", "mov [rip + 8f + 2], rax", "lgdt [rip + 8f]", "lea rax, [rip + 6f]", "push 0x08", "push rax", "retfq", ".code32", "6:", "mov ax, 0x10", "mov ds, ax", "mov es, ax", "mov ss, ax", "mov fs, ax", "mov gs, ax", "mov eax, cr0", "and eax, 0x7fffffff", "mov cr0, eax", "mov ecx, 0xc0000080", "rdmsr", "and eax, 0xfffffeff", "wrmsr", "mov eax, 0x36d76289", "jmp ebp", ".code64", ".balign 8", "7:", ".quad 0", ".quad 0x00cf9a000000ffff", // 0x08: 32-bit code ".quad 0x00cf92000000ffff", // 0x10: data "8:", ".word 23", ".quad 0", "chain_trampoline_end:", ".popsection", ); /// From the lower half, at its physical address: the MMU and caches off, /// every line of RAM cleaned to memory and dropped (the boot kernel's /// stack and data among them, which the next kernel moves over), then the /// jump. x0 the image, x1 the device tree, x2 the EL entered at, x3 the /// slot, x4–x5 RAM. #[cfg(target_arch = "aarch64")] #[unsafe(naked)] unsafe extern "C" fn trampoline() -> ! { core::arch::naked_asm!( "mrs x6, sctlr_el1", "bic x6, x6, #1", // M: the MMU "bic x6, x6, #(1 << 2)", // C: the data cache "bic x6, x6, #(1 << 12)", // I: the instruction cache "msr sctlr_el1, x6", "isb", // The cache's line, from CTR_EL0.DminLine (words, log 2). "mrs x6, ctr_el0", "ubfx x6, x6, #16, #4", "mov x7, #4", "lsl x7, x7, x6", "mov x6, x4", "1:", "dc civac, x6", "add x6, x6, x7", "cmp x6, x5", "b.lo 1b", "dsb sy", "ic iallu", "tlbi vmalle1", "dsb sy", "isb", "mov x6, x0", "mov x0, x1", "ldr x1, ={handed}", "br x6", handed = const HANDED_OVER, ) }