//! Disks, whatever they are behind: a virtio-blk (QEMU's), an NVMe //! namespace, a SATA disk on an AHCI controller, a USB stick. Each is a //! [`Controller`], asynchronous: its requests complete by interrupt while //! the task that waits for them sleeps, so its core runs others meanwhile //! (the boot task, which has no one to give way to, waits for the interrupt //! instead: [`wait`]). Over each sits a cache of the blocks last read, //! written through. //! //! What is mounted: on a disk with a partition table (`pinnacle_disk::gpt`), //! its Pinnacle partitions, the system's and the data's; on a virtio disk //! without one, the disk as a whole, as QEMU's runs have it. Each file //! system is named by its label ("system", "packages", "data"), behind a //! sleeping [`Mutex`]: a program in a long file operation holds up only //! those after the same disk. A disk of any other kind that holds no //! Pinnacle partition is **free**: listed, untouched, what the installer //! (`install`) may take. When the loader names the system partition it //! started from (`root=` on the command line), that one is the system, and //! a data partition on the same disk is the data, whatever else is plugged //! in. use crate::smp::MAX_CORES; use crate::sync::{Mutex, SpinLock}; use crate::{println, sched}; use alloc::boxed::Box; use alloc::collections::BTreeMap; use alloc::string::String; use alloc::sync::Arc; use alloc::vec; use alloc::vec::Vec; use core::sync::atomic::{AtomicU64, Ordering}; use pinnacle_disk::gpt::{self, Guid}; use pinnacle_fs::vault::Vault; use pinnacle_fs::{Disk, Fs}; pub use pinnacle_fs::BLOCK; /// Blocks the cache keeps per disk: 2 MiB. const CACHE_BLOCKS: usize = 512; /// The core that takes the disks' interrupts when it runs: core 0 has the /// network's and runs the boot. const IRQ_CORE: usize = 1; /// What a request does. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Op { Read, Write, /// Every write before it on the medium, not in a cache on the way. Flush, } /// What a transfer carries: blocks read into, written from, or nothing. pub enum Data<'a> { Into(&'a mut [[u8; BLOCK]]), From(&'a [[u8; BLOCK]]), None, } /// What a disk's blocks travel through. Blocks are Pinnacle's, 4 KiB, /// counted from the device's start; a controller turns them into its own /// sectors. pub trait Controller: Send + Sync { /// Does `op` on each of `blocks` (`data` a block each for a read or a /// write; a flush has one block and no data), in batches it chooses, /// waiting for them. False when the device refused any. fn transfer(&self, op: Op, blocks: &[u64], data: Data) -> bool; /// Its size in blocks. fn blocks(&self) -> u64; /// Its logical sector, in bytes: what a partition table counts in. fn sector(&self) -> u64 { 512 } /// Whether a write may wait in its cache until a flush. fn write_cache(&self) -> bool; /// Its name among the disks (`vda`, `nvme0`, `sda`, `usb0`). fn name(&self) -> &str; /// What it says it is ("QEMU NVMe Ctrl"). fn model(&self) -> &str; /// Whether it may be pulled out (a USB stick). fn removable(&self) -> bool { false } /// Whether a disk without a partition table holds one file system as a /// whole: QEMU's virtio disks do. Others are then free. fn whole_disk_file_system(&self) -> bool { false } /// Stops it, its requests done, as a loader leaves it: what another /// kernel taking over (`chain`) finds. fn reset(&self) {} } static READS: AtomicU64 = AtomicU64::new(0); static HITS: AtomicU64 = AtomicU64::new(0); static WRITES: AtomicU64 = AtomicU64::new(0); static SLEEPS: AtomicU64 = AtomicU64::new(0); static SPINS: AtomicU64 = AtomicU64::new(0); /// How the disks have been used since boot. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Stats { /// Blocks read, and of them answered from the cache. pub reads: u64, pub hits: u64, pub writes: u64, /// Waits for the device that slept (a task gave its core away), and /// that waited for the interrupt with nothing else to do (the boot). pub sleeps: u64, pub spins: u64, } pub fn stats() -> Stats { Stats { reads: READS.load(Ordering::Relaxed), hits: HITS.load(Ordering::Relaxed), writes: WRITES.load(Ordering::Relaxed), sleeps: SLEEPS.load(Ordering::Relaxed), spins: SPINS.load(Ordering::Relaxed), } } /// Waits until `done` holds of what `state` guards, as a controller's user /// waits for its interrupt: a task asleep (its `waiter`, set here, is what /// the interrupt wakes), the boot task (a core's idle task, which cannot /// sleep) in WFI. `done` is asked with the lock held, and may poll the /// device itself: the boot task's interrupt may go to another core, whose /// wake only ends its WFI. pub fn wait( state: &SpinLock, waiter: impl Fn(&mut T) -> &mut Option, mut done: impl FnMut(&mut T) -> bool, ) { let me = sched::current(); loop { { let mut s = state.lock(); if done(&mut s) { *waiter(&mut s) = None; return; } *waiter(&mut s) = Some(me); } if me < MAX_CORES { SPINS.fetch_add(1, Ordering::Relaxed); crate::arch::wait_for_interrupt(); } else { SLEEPS.fetch_add(1, Ordering::Relaxed); sched::sleep(); } } } /// Wakes the task [`wait`] left as a waiter, from an interrupt. pub fn wake(waiter: Option) { match waiter { // The boot task waits in WFI on its own core. Some(task) if task < MAX_CORES => crate::gic::send_sgi(task, sched::RESCHEDULE), Some(task) => sched::wake(task), None => {} } } /// Every interrupt a disk raises, for [`init`]'s second call to send on. static INTERRUPTS: SpinLock> = SpinLock::new(Vec::new()); /// Lets a disk's interrupt through, to the core meant for disks once it /// runs. pub fn route_interrupt(intid: u32) { INTERRUPTS.lock().push(intid); crate::gic::enable_shared_on(intid, irq_core()); } /// The blocks last read or written, by number, each with when it was last /// used; the least recently used goes when the cache is full. struct Cache { blocks: BTreeMap, u64)>, tick: u64, } impl Cache { fn new() -> Cache { Cache { blocks: BTreeMap::new(), tick: 0, } } fn get(&mut self, block: u32, into: &mut [u8; BLOCK]) -> bool { let Some((data, used)) = self.blocks.get_mut(&block) else { return false; }; into.copy_from_slice(&data[..]); self.tick += 1; *used = self.tick; true } fn put(&mut self, block: u32, data: &[u8; BLOCK]) { self.tick += 1; if let Some((held, used)) = self.blocks.get_mut(&block) { held.copy_from_slice(data); *used = self.tick; return; } if self.blocks.len() >= CACHE_BLOCKS && let Some((&oldest, _)) = self.blocks.iter().min_by_key(|(_, (_, used))| *used) { self.blocks.remove(&oldest); } let mut held = block_buffer(); held.copy_from_slice(data); self.blocks.insert(block, (held, self.tick)); } } /// A block's worth of zeros on the heap: kernel tasks' stacks are 16 KiB, /// and a file system below a caller holds blocks of its own there. pub fn block_buffer() -> Box<[u8; BLOCK]> { vec![0u8; BLOCK].into_boxed_slice().try_into().unwrap() } /// A disk as a file system sees it: a run of a controller's blocks (all of /// them, or a partition's), with its cache. pub struct Device { controller: Arc, start: u64, len: u64, cache: Cache, } impl Device { /// The whole of `controller`. pub fn whole(controller: Arc) -> Device { let len = controller.blocks(); Device::part(controller, 0, len) } /// `len` blocks of `controller` from block `start`. pub fn part(controller: Arc, start: u64, len: u64) -> Device { Device { controller, start, len, cache: Cache::new(), } } /// The controller it is on. pub fn controller(&self) -> &Arc { &self.controller } } impl Disk for Device { fn read(&mut self, block: u32, into: &mut [u8; BLOCK]) { self.read_many(&[block], core::slice::from_mut(into)); } fn read_many(&mut self, blocks: &[u32], into: &mut [[u8; BLOCK]]) { READS.fetch_add(blocks.len() as u64, Ordering::Relaxed); let mut missing = Vec::new(); for (i, &block) in blocks.iter().enumerate() { if self.cache.get(block, &mut into[i]) { HITS.fetch_add(1, Ordering::Relaxed); } else { missing.push(i); } } if missing.is_empty() { return; } let numbers: Vec = missing .iter() .map(|&i| self.start + u64::from(blocks[i])) .collect(); let mut data = vec![[0u8; BLOCK]; numbers.len()]; assert!( self.controller .transfer(Op::Read, &numbers, Data::Into(&mut data)), "a disk read failed ({})", self.controller.name() ); for (k, &i) in missing.iter().enumerate() { into[i] = data[k]; self.cache.put(blocks[i], &data[k]); } } fn write(&mut self, block: u32, from: &[u8; BLOCK]) { self.write_many(&[block], core::slice::from_ref(from)); } fn write_many(&mut self, blocks: &[u32], from: &[[u8; BLOCK]]) { WRITES.fetch_add(blocks.len() as u64, Ordering::Relaxed); for (&block, data) in blocks.iter().zip(from) { self.cache.put(block, data); } let numbers: Vec = blocks.iter().map(|&b| self.start + u64::from(b)).collect(); assert!( self.controller.transfer(Op::Write, &numbers, Data::From(from)), "a disk write failed ({})", self.controller.name() ); } fn blocks(&self) -> u32 { // Past 16 TiB a block number no longer fits: the rest goes unused, // where a bare cast would wrap and leave a disk looking tiny. self.len.min(u64::from(u32::MAX)) as u32 } fn flush(&mut self) { if self.controller.write_cache() { assert!( self.controller.transfer(Op::Flush, &[self.start], Data::None), "a disk flush failed ({})", self.controller.name() ); } } } /// The disk as bytes, for its partition table and a boot partition: whole /// blocks read, and the ones a write only partly covers read first. impl pinnacle_disk::Medium for Device { fn read_at(&mut self, offset: u64, into: &mut [u8]) -> bool { if offset + into.len() as u64 > self.size() { return false; } let mut done = 0; while done < into.len() { let at = offset + done as u64; let (block, within) = ((at / BLOCK as u64) as u32, (at % BLOCK as u64) as usize); let mut b = block_buffer(); self.read(block, &mut b); let n = (BLOCK - within).min(into.len() - done); into[done..done + n].copy_from_slice(&b[within..within + n]); done += n; } true } fn write_at(&mut self, offset: u64, from: &[u8]) -> bool { if offset + from.len() as u64 > self.size() { return false; } let mut done = 0; while done < from.len() { let at = offset + done as u64; let (block, within) = ((at / BLOCK as u64) as u32, (at % BLOCK as u64) as usize); let n = (BLOCK - within).min(from.len() - done); let mut b = block_buffer(); if n < BLOCK { self.read(block, &mut b); } b[within..within + n].copy_from_slice(&from[done..done + n]); // Whole blocks in runs, as a file system's batches go. if n == BLOCK { let run = ((from.len() - done) / BLOCK).min(64); let blocks: Vec = (0..run as u32).map(|i| block + i).collect(); let data: Vec<[u8; BLOCK]> = from[done..done + run * BLOCK].as_chunks::().0.to_vec(); self.write_many(&blocks, &data); done += run * BLOCK; continue; } self.write(block, &b); done += n; } true } fn size(&self) -> u64 { self.len * BLOCK as u64 } } /// What a mounted file system is on: a disk as it is, or a vault on one, /// read and written in the clear above it. pub enum Store { Plain(Device), Vault(Vault), } impl Disk for Store { fn read(&mut self, block: u32, into: &mut [u8; BLOCK]) { match self { Store::Plain(d) => d.read(block, into), Store::Vault(v) => v.read(block, into), } } fn write(&mut self, block: u32, from: &[u8; BLOCK]) { match self { Store::Plain(d) => d.write(block, from), Store::Vault(v) => v.write(block, from), } } fn blocks(&self) -> u32 { match self { Store::Plain(d) => d.blocks(), Store::Vault(v) => v.blocks(), } } fn flush(&mut self) { match self { Store::Plain(d) => d.flush(), Store::Vault(v) => v.flush(), } } fn read_many(&mut self, blocks: &[u32], into: &mut [[u8; BLOCK]]) { match self { Store::Plain(d) => d.read_many(blocks, into), Store::Vault(v) => v.read_many(blocks, into), } } fn write_many(&mut self, blocks: &[u32], from: &[[u8; BLOCK]]) { match self { Store::Plain(d) => d.write_many(blocks, from), Store::Vault(v) => v.write_many(blocks, from), } } } /// A mounted disk's file system, held by one task at a time. pub type SharedDisk = Arc>>; /// The mounted disks, by label. pub static DISKS: SpinLock> = SpinLock::new(Vec::new()); /// Disks waiting for a passphrase: a vault to open, or (true) a blank disk /// to make one on. Mounted once opened, under the label inside. static WAITING: SpinLock> = SpinLock::new(Vec::new()); /// What [`vault_state`] answers. pub mod vault_state { pub const NONE: u64 = 0; /// A blank disk, for a new vault and its first passphrase. pub const BLANK: u64 = 1; /// A vault, locked. pub const LOCKED: u64 = 2; } /// Whether a disk waits for a passphrase, and which way. pub fn vault_state() -> u64 { match WAITING.lock().first() { Some((_, true)) => vault_state::BLANK, Some((_, false)) => vault_state::LOCKED, None => vault_state::NONE, } } /// Opens the waiting vault with `passphrase` and mounts it. False when it /// is the wrong one (the vault keeps waiting) or there is none. pub fn open_vault(passphrase: &str) -> bool { let Some(at) = WAITING.lock().iter().position(|(_, blank)| !blank) else { return false; }; let (device, _) = WAITING.lock().remove(at); let on = String::from(device.controller().name()); match Vault::open(device, passphrase) { Ok(vault) => { let mounted = mount(Store::Vault(vault), &on).is_some(); if mounted { move_into_vault(); } mounted } Err((device, _)) => { WAITING.lock().insert(at, (device, false)); false } } } /// Makes the waiting blank disk a vault opened by `passphrase`, with an /// empty file system labelled `data` on it, and mounts it. pub fn create_vault(passphrase: &str) -> bool { let Some(at) = WAITING.lock().iter().position(|(_, blank)| *blank) else { return false; }; let (device, _) = WAITING.lock().remove(at); let on = String::from(device.controller().name()); let (mut salt, mut key) = ([0u8; 16], [0u8; 32]); super::random::fill(&mut salt); super::random::fill(&mut key); let vault = Vault::create(device, passphrase, salt, key); let fs = pinnacle_fs::format(Store::Vault(vault), "data"); println!("disk data: a new vault"); let mounted = mount_fs(fs, &on).is_some(); if mounted { move_into_vault(); } mounted } /// Mounts the file system on `store`, finishing a change a power cut /// interrupted and checking it is whole. Returns its label. `on` is the /// disk it is on. fn mount(store: Store, on: &str) -> Option { mount_fs(Fs::mount(store).ok()?, on) } fn mount_fs(mut fs: Fs, on: &str) -> Option { let label = fs.label.clone(); // The first of a label wins: the system the loader named, then the // disks in the order found. Another (a second system disk plugged in) // is left alone. if mounted(&label) { println!("disk {label} on {on}: another, not mounted"); return None; } IN_USE.lock().push(String::from(on)); fs.set_clock(crate::clock::seconds); if fs.recovered { println!("disk {}: finished a change a power cut interrupted", fs.label); } match fs.check() { Ok(usage) => println!( "disk {}: whole, {} files in {} folders", fs.label, usage.files, usage.directories ), Err(problem) => println!("disk {}: damaged: {problem}", fs.label), } DISKS.lock().push((label.clone(), Arc::new(Mutex::new(fs)))); Some(label) } /// The disks a mounted file system, or a vault waiting to be opened, is on. static IN_USE: SpinLock> = SpinLock::new(Vec::new()); /// Every disk found, whatever it holds, with what that is. static CONTROLLERS: SpinLock, Holds)>> = SpinLock::new(Vec::new()); /// What a disk holds, as [`init`] found it. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Holds { /// Pinnacle: its file system as a whole, or its partitions. Pinnacle, /// A partition table with nothing of Pinnacle's on it: another system's. Other, /// Nothing that says what it is: no partition table, and its first /// block not all zero. Unknown, /// Nothing at all: its first block is all zeros. Empty, } /// A disk, for Settings and the installer. #[derive(Clone, Debug)] pub struct DiskInfo { pub name: String, pub model: String, pub bytes: u64, pub removable: bool, pub holds: Holds, } /// Every disk found, in the order found. pub fn disks() -> Vec { CONTROLLERS .lock() .iter() .map(|(c, holds)| DiskInfo { name: c.name().into(), model: c.model().into(), bytes: c.blocks() * BLOCK as u64, removable: c.removable(), holds: *holds, }) .collect() } /// The disk named `name`, unless it holds a mounted file system. pub fn free_controller(name: &str) -> Option> { let c = CONTROLLERS .lock() .iter() .find(|(c, _)| c.name() == name) .map(|(c, _)| c.clone())?; let busy = IN_USE.lock().iter().any(|n| n == name) || WAITING.lock().iter().any(|(d, _)| d.controller().name() == name); (!busy).then_some(c) } /// Notes that the disk named `name` now holds Pinnacle (the installer put /// it there). pub fn now_holds_pinnacle(name: &str) { for (c, holds) in CONTROLLERS.lock().iter_mut() { if c.name() == name { *holds = Holds::Pinnacle; } } } /// Adds a disk found after [`init`] (a USB stick plugged in): listed, and /// free for the installer; nothing on it is mounted. pub fn add_controller(controller: Arc) { let (_, holds) = candidates(&controller); println!( "disk {}: {} MiB, {}, plugged in", controller.name(), (controller.blocks() * BLOCK as u64) >> 20, controller.model() ); CONTROLLERS.lock().push((controller, holds)); } /// Drops a disk that went away (a USB stick pulled out). What was mounted /// from it stays listed, and fails at its next read. pub fn remove_controller(name: &str) { CONTROLLERS.lock().retain(|(c, _)| c.name() != name); } /// The disk the loader started the system from (`root=`), if it said. static BOOT_DISK: SpinLock>> = SpinLock::new(None); /// The boot partition (FAT, the EFI system partition) of the disk the /// system was started from: where its loader and kernel are. pub fn boot_partition() -> Option { let controller = BOOT_DISK.lock().clone()?; let sector = controller.sector(); let table = gpt::read(&mut Device::whole(controller.clone()), sector)?; let esp = table.partitions.iter().find(|p| p.kind == gpt::EFI_SYSTEM)?; let (start, len) = esp.range(sector); (start % BLOCK as u64 == 0) .then(|| Device::part(controller, start / BLOCK as u64, len.div_ceil(BLOCK as u64))) } /// The labels [`init`] mounted, once it has run. static MOUNTED: SpinLock>> = SpinLock::new(None); /// The core the disks' interrupts go to: [`IRQ_CORE`] once it runs. fn irq_core() -> usize { if crate::smp::online() & (1 << IRQ_CORE) != 0 { IRQ_CORE } else { 0 } } /// Finds every disk and mounts what is Pinnacle's on them, finishing a /// change a power cut interrupted and checking each is whole. Returns their /// labels. Called again (the boot kernel reads the system disk before the /// other cores start, `chain`), it mounts nothing more: it sends the disks' /// interrupts to the core meant for them, now that it may run, and returns /// the same labels. pub fn init() -> Vec { if let Some(labels) = MOUNTED.lock().clone() { for intid in INTERRUPTS.lock().iter() { crate::gic::enable_shared_on(*intid, irq_core()); } return labels; } let found = mount_all(); *MOUNTED.lock() = Some(found.clone()); found } /// Stops every disk, its requests done: what another kernel takes over /// (`chain`) finds them as a loader leaves them. pub fn reset_all() { for (c, _) in CONTROLLERS.lock().iter() { c.reset(); } } /// Every disk on every controller this kernel drives. fn find_all() -> Vec> { let mut all = super::virtio_blk::find(); all.extend(super::nvme::find()); all.extend(super::ahci::find()); all.extend(super::usb::storage::find()); all } /// A file system's place found on a disk, and what kind it may be. struct Candidate { device: Device, /// The partition's own GUID, when it is one. id: Option, /// Only a data partition becomes a vault; only a system one, or a /// whole virtio disk, a plain file system. kind: Kind, } #[derive(Clone, Copy, PartialEq, Eq)] enum Kind { System, Data, /// A whole virtio disk: any of them, as before partitions. Any, } /// The candidates on `controller`, and what it holds. fn candidates(controller: &Arc) -> (Vec, Holds) { let mut whole = Device::whole(controller.clone()); let sector = controller.sector(); if let Some(table) = gpt::read(&mut whole, sector) { let mut found = Vec::new(); for (n, p) in table.partitions.iter().enumerate() { let kind = match p.kind { gpt::PINNACLE_SYSTEM => Kind::System, gpt::PINNACLE_DATA => Kind::Data, _ => continue, }; let (start, len) = p.range(sector); if start % BLOCK as u64 != 0 || len % BLOCK as u64 != 0 { println!( "disk {}p{}: not on 4 KiB blocks, left alone", controller.name(), n + 1 ); continue; } found.push(Candidate { device: Device::part(controller.clone(), start / BLOCK as u64, len / BLOCK as u64), id: Some(p.id), kind, }); } let holds = if found.is_empty() { Holds::Other } else { Holds::Pinnacle }; return (found, holds); } if controller.whole_disk_file_system() { return ( alloc::vec![Candidate { device: whole, id: None, kind: Kind::Any, }], Holds::Pinnacle, ); } let mut first = block_buffer(); whole.read(0, &mut first); let holds = if first.iter().all(|&b| b == 0) { Holds::Empty } else { Holds::Unknown }; (Vec::new(), holds) } fn mount_all() -> Vec { let root = crate::args::value("root").map(|g| g.to_ascii_lowercase()); let mut found = Vec::new(); let mut all: Vec<(Candidate, usize)> = Vec::new(); let mut root_disk = None; for (n, controller) in find_all().into_iter().enumerate() { let (candidates, holds) = candidates(&controller); println!( "disk {}: {} MiB, {}{}", controller.name(), (controller.blocks() * BLOCK as u64) >> 20, controller.model(), match holds { Holds::Pinnacle => "", Holds::Other => ", another system's", Holds::Unknown => ", holding something unknown", Holds::Empty => ", empty", } ); for c in candidates { if c.id.is_some_and(|id| Some(id.text()) == root) { root_disk = Some(n); } all.push((c, n)); } CONTROLLERS.lock().push((controller, holds)); } if root.is_some() && root_disk.is_none() { println!("disk: the system partition the loader named is not here"); } if let Some(n) = root_disk { *BOOT_DISK.lock() = CONTROLLERS.lock().get(n).map(|(c, _)| c.clone()); if let Some(c) = BOOT_DISK.lock().as_ref() { println!("disk: the system is on {}, as the loader said", c.name()); } } // The system the loader named first, then its disk's data; then the // rest as found. all.sort_by_key(|(c, n)| { let named = c.id.is_some_and(|id| Some(id.text()) == root); (!named, Some(*n) != root_disk) }); for (c, _) in all { let mut device = c.device; let mut first = [0u8; BLOCK]; device.read(0, &mut first); let may_be_data = c.kind != Kind::System; if may_be_data && pinnacle_fs::vault::is_vault(&mut device) { println!("disk: a vault, locked"); WAITING.lock().push((device, false)); } else if may_be_data && first.iter().all(|&b| b == 0) { println!("disk: blank"); WAITING.lock().push((device, true)); } else if c.kind != Kind::Data && let Some(label) = { let on = String::from(device.controller().name()); mount(Store::Plain(device), &on) } { found.push(label); } } found } /// A disk's interrupt: its requests completed. False if `intid` is no /// disk's. Every controller on a shared line is asked. pub fn interrupt(intid: u32) -> bool { let virtio = super::virtio_blk::interrupt(intid); let nvme = super::nvme::interrupt(intid); let ahci = super::ahci::interrupt(intid); virtio | nvme | ahci } /// Runs `f` on the disk a path names ("system:/apps" → the disk labelled /// "system", path "/apps"; no label means "system"), holding it for the /// duration: a task in line for it sleeps. pub fn with_disk(path: &str, f: impl FnOnce(&mut Fs, &str) -> R) -> Option { let (label, rest) = path.split_once(':').unwrap_or(("system", path)); let disk = DISKS .lock() .iter() .find(|(l, _)| l == label) .map(|(_, d)| d.clone())?; #[cfg(target_arch = "aarch64")] if crate::profile::on() { let asked = crate::profile::counter(); let mut fs = disk.lock(); let got = crate::profile::counter(); let answer = f(&mut fs, rest); crate::profile::disk(got - asked, crate::profile::counter() - got); return Some(answer); } let mut fs = disk.lock(); Some(f(&mut fs, rest)) } /// Whether any disk was mounted. pub fn present() -> bool { !DISKS.lock().is_empty() } /// Runs `f` on the vault the open `data` disk is in, if it is in one. fn with_data_vault(f: impl FnOnce(&mut Vault) -> R) -> Option { with_disk("data:/", |fs, _| match fs.disk_mut() { Store::Vault(vault) => Some(f(vault)), Store::Plain(_) => None, }) .flatten() } /// Whether `passphrase` opens the open data vault: the lock screen's check. pub fn check_vault(passphrase: &str) -> bool { with_data_vault(|vault| vault.check_passphrase(passphrase)).unwrap_or(false) } /// Seals the open data vault's key under `new`, given `old`. pub fn change_vault_passphrase(old: &str, new: &str) -> bool { let mut salt = [0u8; 16]; super::random::fill(&mut salt); with_data_vault(|vault| vault.change_passphrase(old, new, salt).is_ok()).unwrap_or(false) } /// Whether a disk labelled `label` is mounted. pub fn mounted(label: &str) -> bool { DISKS.lock().iter().any(|(l, _)| l == label) } /// What the system disk kept of the person's own, and where it goes in the /// data vault: the apps' folders, and the p2p service's identity, contacts /// and messages. const INTO_VAULT: [(&str, &str); 4] = [ ("system:/data", "data:/apps"), ("system:/settings/identity", "data:/p2p/identity"), ("system:/contacts", "data:/p2p/contacts"), ("system:/messages", "data:/p2p/messages"), ]; /// Moves what the system disk kept of the person's own into the data vault, /// once it is made or opened: a device that kept it in the clear keeps it /// encrypted from then on. A tree whose place in the vault is taken stays /// where it is; one is removed from the system disk only once all of it /// is in the vault. fn move_into_vault() { for (from, to) in INTO_VAULT { let taken = with_disk(to, |fs, p| fs.stat(p).is_ok()).unwrap_or(true); let there = with_disk(from, |fs, p| fs.stat(p).is_ok()).unwrap_or(false); if taken || !there { continue; } if copy_tree(from, to) { let _ = with_disk(from, |fs, p| fs.remove_all(p)); println!("disk data: moved {from} into the vault"); } else { println!("disk data: could not move {from}; it stays"); } } } /// Copies the file or directory at `from` (a labelled path) to `to`. fn copy_tree(from: &str, to: &str) -> bool { use pinnacle_fs::Kind; let Some(Ok(stat)) = with_disk(from, |fs, p| fs.stat(p)) else { return false; }; match stat.kind { Kind::File => { let Some(Ok(data)) = with_disk(from, |fs, p| fs.read(p)) else { return false; }; if let Some((dir, _)) = to.rsplit_once('/') { let _ = with_disk(dir, |fs, p| fs.create_dir(p)); } matches!(with_disk(to, |fs, p| fs.write(p, &data)), Some(Ok(()))) } Kind::Directory => { let _ = with_disk(to, |fs, p| fs.create_dir(p)); let Some(Ok(names)) = with_disk(from, |fs, p| fs.list(p)) else { return false; }; names.iter().all(|name| { let name = name.trim_end_matches('/'); copy_tree(&alloc::format!("{from}/{name}"), &alloc::format!("{to}/{name}")) }) } } }