diff --git a/std/build.rs b/std/build.rs index 98856b5..38dd883 100644 --- a/std/build.rs +++ b/std/build.rs @@ -34,6 +34,7 @@ fn main() { || target_os == "fuchsia" || (target_vendor == "fortanix" && target_env == "sgx") || target_os == "motor" + || target_os == "pinnacle" || target_os == "hermit" || target_os == "trusty" || target_os == "l4re" diff --git a/std/src/os/mod.rs b/std/src/os/mod.rs index f95c6ac..f5a9891 100644 --- a/std/src/os/mod.rs +++ b/std/src/os/mod.rs @@ -143,5 +143,7 @@ pub mod uefi; pub mod vita; #[cfg(target_os = "vxworks")] pub mod vxworks; +#[cfg(target_os = "pinnacle")] +pub mod pinnacle; #[cfg(target_os = "xous")] pub mod xous; diff --git a/std/src/os/pinnacle/mod.rs b/std/src/os/pinnacle/mod.rs new file mode 100644 index 0000000..6e1130b --- /dev/null +++ b/std/src/os/pinnacle/mod.rs @@ -0,0 +1,87 @@ +//! Pinnacle-specific definitions: the system calls, for what std does not +//! wrap, and the kernel handles behind std's sockets and pipes, for event +//! loops that wait on several at once (`wait`). + +#![stable(feature = "rust1", since = "1.0.0")] +#![doc(cfg(target_os = "pinnacle"))] + +use crate::sys::AsInner; +use crate::time::Duration; + +/// What the kernel and its programs agree on: system call numbers and the +/// constants they answer with (Pinnacle's `abi` crate). +#[stable(feature = "rust1", since = "1.0.0")] +pub mod abi { + #[stable(feature = "rust1", since = "1.0.0")] + pub use crate::sys::abi::*; +} + +/// Makes system call `number` with `args` in x0 up; its answer in x0–x2. +#[stable(feature = "rust1", since = "1.0.0")] +pub fn syscall(number: u64, args: [u64; 7]) -> (u64, u64, u64) { + crate::sys::call(number, args) +} + +/// Fills `bytes` from the kernel's randomness, for keys. +#[stable(feature = "rust1", since = "1.0.0")] +pub fn random(bytes: &mut [u8]) { + crate::sys::random::fill_bytes(bytes) +} + +/// A kernel handle: a number in the program's table. +#[stable(feature = "rust1", since = "1.0.0")] +pub type RawHandle = u64; + +/// The channel behind a socket or pipe. +#[stable(feature = "rust1", since = "1.0.0")] +pub trait AsRawHandle { + /// The handle, still owned by `self`. + #[stable(feature = "rust1", since = "1.0.0")] + fn as_raw_handle(&self) -> RawHandle; +} + +macro_rules! raw_handle { + ($($t:ty),*) => {$( + #[stable(feature = "rust1", since = "1.0.0")] + impl AsRawHandle for $t { + fn as_raw_handle(&self) -> RawHandle { + self.as_inner().handle() + } + } + )*}; +} + +raw_handle!( + crate::net::TcpStream, + crate::net::TcpListener, + crate::net::UdpSocket, + crate::process::ChildStdin, + crate::process::ChildStdout, + crate::process::ChildStderr +); + +/// Waits until one of `handles` (channels) has a message, or its peer is +/// gone, or `timeout` passes; takes nothing from them. Returns the index of +/// the first that is ready, or `None` when the timeout passed. What `poll` +/// is elsewhere; `Some(Duration::ZERO)` only looks. +#[stable(feature = "rust1", since = "1.0.0")] +pub fn wait(handles: &[RawHandle], timeout: Option) -> crate::io::Result> { + let deadline = match timeout { + None => 0, + // Already past: answers at once. + Some(t) if t.is_zero() => 1, + Some(t) => { + let ms = u64::try_from(t.as_nanos().div_ceil(1_000_000)).unwrap_or(u64::MAX / 2); + crate::sys::call0(abi::call::TIME).saturating_add(ms).saturating_add(1) + } + }; + let (index, ..) = crate::sys::call( + abi::call::WAIT, + [handles.as_ptr().addr() as u64, handles.len() as u64, deadline, 0, 0, 0, 0], + ); + match index { + abi::ERROR => Err(crate::io::const_error!(crate::io::ErrorKind::InvalidInput, "not a channel")), + abi::TIMEOUT => Ok(None), + i => Ok(Some(i as usize)), + } +} diff --git a/std/src/sys/alloc/mod.rs b/std/src/sys/alloc/mod.rs index 66a2c3b..733df21 100644 --- a/std/src/sys/alloc/mod.rs +++ b/std/src/sys/alloc/mod.rs @@ -100,6 +100,10 @@ cfg_select! { mod wasm; use wasm as imp; } + target_os = "pinnacle" => { + mod pinnacle; + use pinnacle as imp; + } target_os = "xous" => { mod xous; use xous as imp; diff --git a/std/src/sys/alloc/pinnacle.rs b/std/src/sys/alloc/pinnacle.rs new file mode 100644 index 0000000..ba4d518 --- /dev/null +++ b/std/src/sys/alloc/pinnacle.rs @@ -0,0 +1,235 @@ +//! The heap, as Pinnacle's `rt` keeps it, in shards. Requests up to 2 KiB +//! come from power-of-two size classes, free lists of slots carved from +//! 64 KiB arenas: an allocation or a free is a pop or a push. Larger +//! requests take memory from the kernel in whole pages (`map_memory`, +//! zeroed); freed ones are kept, by page count, for reuse up to +//! [`KEPT_BYTES`] a shard, and the rest given back (`unmap_memory`), kept +//! anyway where the kernel cannot take them. +//! +//! A std program's threads share it, so it is [`SHARDS`] heaps, each behind +//! a lock of its own, a thread taking the one its thread pointer picks; a +//! slot freed goes to the freeing thread's, so threads seldom wait on each +//! other. No lock is held over a call to the kernel. + +use super::realloc_fallback; +use crate::alloc::Layout; +use crate::cell::UnsafeCell; +use crate::sync::atomic::{AtomicBool, Ordering}; +use crate::sys::pal::{abi, call1}; + +const PAGE: usize = 4096; +const MIN_CLASS: usize = 16; +const MAX_CLASS: usize = 2048; +const CLASSES: usize = (MAX_CLASS / MIN_CLASS).trailing_zeros() as usize + 1; +const ARENA: usize = 64 * 1024; +/// Freed large blocks, by page count up to this (16 MiB). +const LARGE_KEPT: usize = 4096; +/// The bytes of freed large blocks a shard keeps for reuse; past it, a +/// freed block goes back to the kernel. Given back at once, every growth +/// of a large Vec was a map, a copy and an unmap, and those calls were a +/// quarter of Cartopolis's time. +const KEPT_BYTES: usize = 32 << 20; + +struct State { + classes: [usize; CLASSES], + /// The rest of the current arena. + arena: usize, + arena_end: usize, + large: [usize; LARGE_KEPT + 1], + /// The bytes `large` holds. + kept: usize, +} + +/// The heap's state behind a lock the program's threads share: taking it +/// uncontended is one atomic swap; a thread that finds it taken spins a +/// little, then yields its core. (Not a futex: the futex-based locks may +/// allocate nothing, but a heap must not wait on one that might.) +struct Heap { + locked: AtomicBool, + state: UnsafeCell, +} + +// SAFETY: `state` is touched only with `locked` held. +unsafe impl Sync for Heap {} + +struct Locked<'a>(&'a Heap); + +impl Heap { + fn lock(&self) -> Locked<'_> { + let mut spins = 0; + while self.locked.swap(true, Ordering::Acquire) { + spins += 1; + if spins > 100 { + call1(abi::call::YIELD, 0); + } else { + core::hint::spin_loop(); + } + } + Locked(self) + } +} + +impl Drop for Locked<'_> { + fn drop(&mut self) { + self.0.locked.store(false, Ordering::Release); + } +} + +const SHARDS: usize = 8; + +static HEAP: [Heap; SHARDS] = [const { + Heap { + locked: AtomicBool::new(false), + state: UnsafeCell::new(State { + classes: [0; CLASSES], + arena: 0, + arena_end: 0, + large: [0; LARGE_KEPT + 1], + kept: 0, + }), + } +}; SHARDS]; + +/// The calling thread's shard, from its thread pointer (TPIDR_EL0, each +/// thread's own and readable with no call). +#[inline] +fn shard() -> &'static Heap { + let thread: u64; + // SAFETY: reads a register; no memory. + unsafe { crate::arch::asm!("mrs {}, tpidr_el0", out(reg) thread, options(nomem, nostack, preserves_flags)) }; + &HEAP[(thread.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 61) as usize % SHARDS] +} + +fn from_kernel(size: usize) -> usize { + let address = call1(abi::call::MAP_MEMORY, size as u64); + if address == abi::ERROR { 0 } else { address as usize } +} + +fn class(layout: &Layout) -> Option { + let size = layout.size().max(layout.align()).max(MIN_CLASS).next_power_of_two(); + (size <= MAX_CLASS).then(|| (size / MIN_CLASS).trailing_zeros() as usize) +} + +#[inline] +pub unsafe fn alloc(layout: Layout) -> *mut u8 { + let heap = shard(); + let Some(class) = class(&layout) else { + let pages = layout.size().div_ceil(PAGE); + if layout.align() > PAGE { + return crate::ptr::null_mut(); + } + let kept = if pages <= LARGE_KEPT { + let _locked = heap.lock(); + // SAFETY: the lock is held. + let state = unsafe { &mut *heap.state.get() }; + let block = state.large[pages]; + if block != 0 { + // SAFETY: a kept block's first word links the next. + state.large[pages] = unsafe { *(block as *const usize) }; + state.kept -= pages * PAGE; + } + block + } else { + 0 + }; + if kept != 0 { + // Blocks from the kernel are zeroed; keep it so for a reused one, + // so `alloc_zeroed` can count on it. + // SAFETY: the block is ours again. + unsafe { crate::ptr::write_bytes(kept as *mut u8, 0, pages * PAGE) }; + return kept as *mut u8; + } + return from_kernel(pages * PAGE) as *mut u8; + }; + let _locked = heap.lock(); + // SAFETY: the lock is held. + let state = unsafe { &mut *heap.state.get() }; + if state.classes[class] == 0 { + let size = MIN_CLASS << class; + // A slot is aligned to its size, so its class meets any alignment up + // to it. + state.arena = state.arena.next_multiple_of(size); + if state.arena_end.saturating_sub(state.arena) < size { + state.arena = from_kernel(ARENA); + if state.arena == 0 { + return crate::ptr::null_mut(); + } + state.arena_end = state.arena + ARENA; + } + let slot = state.arena; + state.arena += size; + return slot as *mut u8; + } + let slot = state.classes[class]; + // SAFETY: a free slot's first word links the next. + state.classes[class] = unsafe { *(slot as *const usize) }; + slot as *mut u8 +} + +#[inline] +pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 { + // SAFETY: the caller's layout is valid. + let ptr = unsafe { alloc(layout) }; + // Large blocks come zeroed. + if !ptr.is_null() && class(&layout).is_some() { + // SAFETY: just allocated, `layout.size()` long. + unsafe { ptr.write_bytes(0, layout.size()) }; + } + ptr +} + +#[inline] +pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { + let heap = shard(); + match class(&layout) { + Some(class) => { + let _locked = heap.lock(); + // SAFETY: the lock is held. + let state = unsafe { &mut *heap.state.get() }; + // SAFETY: the slot is ours again; its first word links. + unsafe { *(ptr as *mut usize) = state.classes[class] }; + state.classes[class] = ptr as usize; + } + None => { + let pages = layout.size().div_ceil(PAGE); + // Kept while the shard keeps less than its share; else given + // back, and kept anyway where the kernel cannot take it. + let keep = |always: bool| { + if pages > LARGE_KEPT { + return false; + } + let _locked = heap.lock(); + // SAFETY: the lock is held. + let state = unsafe { &mut *heap.state.get() }; + if !always && state.kept + pages * PAGE > KEPT_BYTES { + return false; + } + // SAFETY: as above. + unsafe { *(ptr as *mut usize) = state.large[pages] }; + state.large[pages] = ptr as usize; + state.kept += pages * PAGE; + true + }; + if !keep(false) && call1(abi::call::UNMAP_MEMORY, ptr as u64) == abi::ERROR { + keep(true); + } + } + } +} + +#[inline] +pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + // SAFETY: the caller's layout is valid, and `new_size` is checked by it. + let new = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; + // A slot of the same class, or a block of as many pages, already fits. + let same = match (class(&layout), class(&new)) { + (Some(a), Some(b)) => a == b, + (None, None) => layout.size().div_ceil(PAGE) == new_size.div_ceil(PAGE), + _ => false, + }; + if same { + return ptr; + } + // SAFETY: as the caller promises for `realloc`. + unsafe { realloc_fallback(ptr, layout, new_size) } +} diff --git a/std/src/sys/args/mod.rs b/std/src/sys/args/mod.rs index c8011a6..3085e23 100644 --- a/std/src/sys/args/mod.rs +++ b/std/src/sys/args/mod.rs @@ -7,6 +7,7 @@ target_family = "windows", target_os = "hermit", target_os = "motor", + target_os = "pinnacle", target_os = "uefi", target_os = "wasi", target_os = "xous", @@ -56,6 +57,10 @@ cfg_select! { mod wali; pub use wali::*; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::*; + } target_os = "xous" => { mod xous; pub use xous::*; diff --git a/std/src/sys/args/pinnacle.rs b/std/src/sys/args/pinnacle.rs new file mode 100644 index 0000000..a66bbd2 --- /dev/null +++ b/std/src/sys/args/pinnacle.rs @@ -0,0 +1,6 @@ +pub use super::common::Args; + +/// The arguments the starter gave (`pal::start`); none when it gave none. +pub fn args() -> Args { + Args::new(crate::sys::pal::start::get().args.clone()) +} diff --git a/std/src/sys/env/mod.rs b/std/src/sys/env/mod.rs index 8985651..5f866ca 100644 --- a/std/src/sys/env/mod.rs +++ b/std/src/sys/env/mod.rs @@ -6,6 +6,7 @@ target_family = "unix", target_os = "hermit", target_os = "motor", + target_os = "pinnacle", all(target_vendor = "fortanix", target_env = "sgx"), target_os = "solid_asp3", target_os = "uefi", @@ -47,6 +48,10 @@ cfg_select! { mod wasi; pub use wasi::*; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::*; + } target_os = "xous" => { mod xous; pub use xous::*; diff --git a/std/src/sys/env/pinnacle.rs b/std/src/sys/env/pinnacle.rs new file mode 100644 index 0000000..de7a217 --- /dev/null +++ b/std/src/sys/env/pinnacle.rs @@ -0,0 +1,34 @@ +//! The environment: what the starter gave (`pal::start`), kept in the +//! program and changed there. + +pub use super::common::Env; +use crate::collections::HashMap; +use crate::ffi::{OsStr, OsString}; +use crate::io; +use crate::sync::{Mutex, OnceLock}; + +type EnvStore = Mutex>; + +fn store() -> &'static EnvStore { + static ENV: OnceLock = OnceLock::new(); + ENV.get_or_init(|| Mutex::new(crate::sys::pal::start::get().env.iter().cloned().collect())) +} + +pub fn env() -> Env { + let env = store().lock().unwrap().iter().map(|(k, v)| (k.clone(), v.clone())).collect(); + Env::new(env) +} + +pub fn getenv(k: &OsStr) -> Option { + store().lock().unwrap().get(k).cloned() +} + +pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { + store().lock().unwrap().insert(k.to_owned(), v.to_owned()); + Ok(()) +} + +pub unsafe fn unsetenv(k: &OsStr) -> io::Result<()> { + store().lock().unwrap().remove(k); + Ok(()) +} diff --git a/std/src/sys/exit.rs b/std/src/sys/exit.rs index 51f8f22..45d94b0 100644 --- a/std/src/sys/exit.rs +++ b/std/src/sys/exit.rs @@ -145,6 +145,7 @@ pub fn exit(code: i32) -> ! { } target_os = "windows" => unsafe { crate::sys::pal::c::ExitProcess(code as u32) }, target_os = "xous" => crate::os::xous::ffi::exit(code as u32), + target_os = "pinnacle" => crate::sys::pal::exit(code), _ => { let _ = code; crate::intrinsics::abort_immediate() diff --git a/std/src/sys/fs/mod.rs b/std/src/sys/fs/mod.rs index e15841b..7b17ec9 100644 --- a/std/src/sys/fs/mod.rs +++ b/std/src/sys/fs/mod.rs @@ -35,6 +35,10 @@ cfg_select! { mod motor; use motor as imp; } + target_os = "pinnacle" => { + mod pinnacle; + use pinnacle as imp; + } target_os = "solid_asp3" => { mod solid; use solid as imp; diff --git a/std/src/sys/fs/pinnacle.rs b/std/src/sys/fs/pinnacle.rs new file mode 100644 index 0000000..944f534 --- /dev/null +++ b/std/src/sys/fs/pinnacle.rs @@ -0,0 +1,581 @@ +//! Files on Pinnacle. The kernel names files by path ("label:/path"; no +//! label is the system disk, `app:` an app's own folder) and has no open +//! files: a `File` here is its path and a position, and each read or write +//! is one call at an offset (`read_at`, `write_at`), which the file system +//! makes a transaction of its own. Directories are listed whole (`list`). +//! +//! What the kernel does not do — renaming, links, permissions, times set by +//! hand — answers "unsupported", but for a file's rename, done as a copy. + +use crate::ffi::OsString; +use crate::fmt; +use crate::fs::TryLockError; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; +use crate::path::{Path, PathBuf}; +use crate::sync::atomic::{AtomicU64, Ordering}; +pub use crate::sys::fs::common::{Dir, ExtraHomeDirs, ExtraMediaDirs}; +use crate::sys::pal::{abi, call}; +use crate::sys::time::{SystemTime, UNIX_EPOCH}; +use crate::sys::unsupported; +use crate::time::Duration; + +/// The most one call copies. +const MAX_COPY: usize = abi::MAX_COPY; + +fn path_bytes(path: &Path) -> io::Result<&[u8]> { + path.to_str() + .map(str::as_bytes) + .ok_or(io::const_error!(io::ErrorKind::InvalidFilename, "a path must be UTF-8")) +} + +fn path_call(number: u64, path: &Path, rest: [u64; 5]) -> io::Result<(u64, u64, u64)> { + let bytes = path_bytes(path)?; + let (a, b, c) = call( + number, + [bytes.as_ptr().addr() as u64, bytes.len() as u64, rest[0], rest[1], rest[2], rest[3], rest[4]], + ); + if a == abi::ERROR { Err(failed()) } else { Ok((a, b, c)) } +} + +/// What a refused call is: the kernel does not say why. +fn failed() -> io::Error { + io::const_error!(io::ErrorKind::Other, "the file system refused it") +} + +fn not_found() -> io::Error { + io::const_error!(io::ErrorKind::NotFound, "no such file or directory") +} + +/// Kinds as `stat` answers them. +const KIND_FILE: u64 = 1; +const KIND_DIR: u64 = 2; + +pub fn stat(path: &Path) -> io::Result { + let (size, kind, modified) = path_call(abi::call::STAT, path, [0; 5]).map_err(|_| not_found())?; + Ok(FileAttr { size, file_type: FileType { dir: kind == KIND_DIR }, modified }) +} + +pub fn lstat(path: &Path) -> io::Result { + stat(path) +} + +fn read_at(path: &Path, offset: u64, buf: &mut [u8]) -> io::Result { + let len = buf.len().min(MAX_COPY); + let (n, ..) = path_call(abi::call::READ_AT, path, [offset, buf.as_mut_ptr().addr() as u64, len as u64, 0, 0])?; + Ok(n as usize) +} + +fn write_at(path: &Path, offset: u64, buf: &[u8]) -> io::Result { + let len = buf.len().min(MAX_COPY); + path_call(abi::call::WRITE_AT, path, [offset, buf.as_ptr().addr() as u64, len as u64, 0, 0])?; + Ok(len) +} + +/// Creates or replaces the file with `data`. +fn write_whole(path: &Path, data: &[u8]) -> io::Result<()> { + path_call(abi::call::WRITE_FILE, path, [data.as_ptr().addr() as u64, data.len() as u64, 0, 0, 0])?; + Ok(()) +} + +pub struct File { + path: PathBuf, + position: AtomicU64, + read: bool, + write: bool, + append: bool, +} + +#[derive(Clone)] +pub struct FileAttr { + size: u64, + file_type: FileType, + /// Seconds since 1970, or 0 without a clock. + modified: u64, +} + +pub struct ReadDir { + dir: PathBuf, + names: crate::vec::IntoIter, +} + +pub struct DirEntry { + dir: PathBuf, + name: String, + file_type: FileType, +} + +#[derive(Clone, Debug)] +pub struct OpenOptions { + read: bool, + write: bool, + append: bool, + truncate: bool, + create: bool, + create_new: bool, +} + +#[derive(Copy, Clone, Debug, Default)] +pub struct FileTimes {} + +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct FilePermissions {} + +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] +pub struct FileType { + dir: bool, +} + +#[derive(Debug)] +pub struct DirBuilder {} + +impl FileAttr { + pub fn size(&self) -> u64 { + self.size + } + + pub fn perm(&self) -> FilePermissions { + FilePermissions {} + } + + pub fn file_type(&self) -> FileType { + self.file_type + } + + pub fn modified(&self) -> io::Result { + if self.modified == 0 { + return unsupported(); + } + UNIX_EPOCH + .checked_add_duration(&Duration::from_secs(self.modified)) + .ok_or(io::const_error!(io::ErrorKind::InvalidData, "a time out of range")) + } + + pub fn accessed(&self) -> io::Result { + unsupported() + } + + pub fn created(&self) -> io::Result { + unsupported() + } +} + +impl FilePermissions { + pub fn readonly(&self) -> bool { + false + } + + pub fn set_readonly(&mut self, _readonly: bool) {} +} + +impl FileTimes { + pub fn set_accessed(&mut self, _t: SystemTime) {} + pub fn set_modified(&mut self, _t: SystemTime) {} +} + +impl FileType { + pub fn is_dir(&self) -> bool { + self.dir + } + + pub fn is_file(&self) -> bool { + !self.dir + } + + pub fn is_symlink(&self) -> bool { + false + } +} + +impl ReadDir { + pub fn dir(&self) -> io::Result { + unsupported() + } +} + +impl fmt::Debug for ReadDir { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("ReadDir").field(&self.dir).finish() + } +} + +impl Iterator for ReadDir { + type Item = io::Result; + + fn next(&mut self) -> Option> { + let mut name = self.names.next()?; + // Directories are listed with a '/' after their name. + let dir = name.ends_with('/'); + if dir { + name.pop(); + } + Some(Ok(DirEntry { dir: self.dir.clone(), name, file_type: FileType { dir } })) + } +} + +impl DirEntry { + pub fn path(&self) -> PathBuf { + self.dir.join(&self.name) + } + + pub fn file_name(&self) -> OsString { + OsString::from(self.name.clone()) + } + + pub fn metadata(&self) -> io::Result { + stat(&self.path()) + } + + pub fn file_type(&self) -> io::Result { + Ok(self.file_type) + } +} + +impl OpenOptions { + pub fn new() -> OpenOptions { + OpenOptions { + read: false, + write: false, + append: false, + truncate: false, + create: false, + create_new: false, + } + } + + pub fn read(&mut self, read: bool) { + self.read = read; + } + pub fn write(&mut self, write: bool) { + self.write = write; + } + pub fn append(&mut self, append: bool) { + self.append = append; + } + pub fn truncate(&mut self, truncate: bool) { + self.truncate = truncate; + } + pub fn create(&mut self, create: bool) { + self.create = create; + } + pub fn create_new(&mut self, create_new: bool) { + self.create_new = create_new; + } +} + +impl File { + pub fn open(path: &Path, opts: &OpenOptions) -> io::Result { + let write = opts.write || opts.append; + if !opts.read && !write { + return Err(io::const_error!(io::ErrorKind::InvalidInput, "opened neither to read nor to write")); + } + if (opts.create || opts.create_new || opts.truncate) && !write { + return Err(io::const_error!(io::ErrorKind::InvalidInput, "creating or truncating needs writing")); + } + match stat(path) { + Ok(attr) if attr.file_type.dir => { + return Err(io::const_error!(io::ErrorKind::IsADirectory, "a directory")); + } + Ok(_) if opts.create_new => { + return Err(io::const_error!(io::ErrorKind::AlreadyExists, "the file exists")); + } + Ok(_) if opts.truncate => write_whole(path, &[])?, + Ok(_) => {} + Err(_) if opts.create || opts.create_new => write_whole(path, &[])?, + Err(e) => return Err(e), + } + Ok(File { + path: path.to_path_buf(), + position: AtomicU64::new(0), + read: opts.read, + write, + append: opts.append, + }) + } + + pub fn file_attr(&self) -> io::Result { + stat(&self.path) + } + + pub fn fsync(&self) -> io::Result<()> { + // Every write is on the disk when its call returns. + Ok(()) + } + + pub fn datasync(&self) -> io::Result<()> { + Ok(()) + } + + pub fn lock(&self) -> io::Result<()> { + unsupported() + } + + pub fn lock_shared(&self) -> io::Result<()> { + unsupported() + } + + pub fn try_lock(&self) -> Result<(), TryLockError> { + Err(TryLockError::Error(io::Error::UNSUPPORTED_PLATFORM)) + } + + pub fn try_lock_shared(&self) -> Result<(), TryLockError> { + Err(TryLockError::Error(io::Error::UNSUPPORTED_PLATFORM)) + } + + pub fn unlock(&self) -> io::Result<()> { + unsupported() + } + + pub fn truncate(&self, size: u64) -> io::Result<()> { + if !self.write { + return Err(io::const_error!(io::ErrorKind::PermissionDenied, "not opened to write")); + } + let now = stat(&self.path)?.size; + if size > now { + // A hole up to the new end, its last byte written. + write_at(&self.path, size - 1, &[0])?; + } else if size < now { + let size = usize::try_from(size) + .ok() + .filter(|&s| s <= MAX_COPY) + .ok_or(io::const_error!(io::ErrorKind::Unsupported, "truncating to more than 16 MiB"))?; + let mut kept = crate::vec![0; size]; + let mut at = 0; + while at < size { + let n = read_at(&self.path, at as u64, &mut kept[at..])?; + if n == 0 { + break; + } + at += n; + } + write_whole(&self.path, &kept[..at])?; + } + Ok(()) + } + + pub fn read(&self, buf: &mut [u8]) -> io::Result { + if !self.read { + return Err(io::const_error!(io::ErrorKind::PermissionDenied, "not opened to read")); + } + let at = self.position.load(Ordering::Relaxed); + let n = read_at(&self.path, at, buf)?; + self.position.store(at + n as u64, Ordering::Relaxed); + Ok(n) + } + + pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { + crate::io::default_read_vectored(|buf| self.read(buf), bufs) + } + + pub fn is_read_vectored(&self) -> bool { + false + } + + pub fn read_buf(&self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> { + crate::io::default_read_buf(|buf| self.read(buf), cursor) + } + + pub fn write(&self, buf: &[u8]) -> io::Result { + if !self.write { + return Err(io::const_error!(io::ErrorKind::PermissionDenied, "not opened to write")); + } + let at = if self.append { stat(&self.path)?.size } else { self.position.load(Ordering::Relaxed) }; + let n = write_at(&self.path, at, buf)?; + self.position.store(at + n as u64, Ordering::Relaxed); + Ok(n) + } + + pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { + crate::io::default_write_vectored(|buf| self.write(buf), bufs) + } + + pub fn is_write_vectored(&self) -> bool { + false + } + + pub fn flush(&self) -> io::Result<()> { + Ok(()) + } + + pub fn seek(&self, pos: SeekFrom) -> io::Result { + let (base, offset) = match pos { + SeekFrom::Start(at) => { + self.position.store(at, Ordering::Relaxed); + return Ok(at); + } + SeekFrom::Current(offset) => (self.position.load(Ordering::Relaxed), offset), + SeekFrom::End(offset) => (stat(&self.path)?.size, offset), + }; + let at = base + .checked_add_signed(offset) + .ok_or(io::const_error!(io::ErrorKind::InvalidInput, "a seek before the start"))?; + self.position.store(at, Ordering::Relaxed); + Ok(at) + } + + pub fn size(&self) -> Option> { + Some(stat(&self.path).map(|a| a.size)) + } + + pub fn tell(&self) -> io::Result { + Ok(self.position.load(Ordering::Relaxed)) + } + + pub fn duplicate(&self) -> io::Result { + Ok(File { + path: self.path.clone(), + position: AtomicU64::new(self.position.load(Ordering::Relaxed)), + read: self.read, + write: self.write, + append: self.append, + }) + } + + pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> { + unsupported() + } + + pub fn set_times(&self, _times: FileTimes) -> io::Result<()> { + unsupported() + } +} + +impl DirBuilder { + pub fn new() -> DirBuilder { + DirBuilder {} + } + + pub fn mkdir(&self, p: &Path) -> io::Result<()> { + // The kernel makes missing parents too; std's `create_dir` must not, + // nor succeed where something is already. + if stat(p).is_ok() { + return Err(io::const_error!(io::ErrorKind::AlreadyExists, "it exists")); + } + if let Some(parent) = p.parent().filter(|p| !p.as_os_str().is_empty()) + && !stat(parent).is_ok_and(|a| a.file_type.dir) + { + return Err(not_found()); + } + path_call(abi::call::CREATE_DIR, p, [0; 5]).map(drop) + } +} + +impl fmt::Debug for File { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("File").field("path", &self.path).finish_non_exhaustive() + } +} + +pub fn readdir(p: &Path) -> io::Result { + if !stat(p)?.file_type.dir { + return Err(io::const_error!(io::ErrorKind::NotADirectory, "not a directory")); + } + // The kernel cuts the list at the buffer's end: grow it until it fits. + let mut size = 4096; + loop { + let mut buf = crate::vec![0u8; size]; + let (n, ..) = path_call(abi::call::LIST, p, [buf.as_mut_ptr().addr() as u64, size as u64, 0, 0, 0])?; + let n = n as usize; + if n < size { + buf.truncate(n); + let text = String::from_utf8(buf) + .map_err(|_| io::const_error!(io::ErrorKind::InvalidData, "a name that is not UTF-8"))?; + let names: Vec = text.lines().map(String::from).collect(); + return Ok(ReadDir { dir: p.to_path_buf(), names: names.into_iter() }); + } + size *= 2; + } +} + +pub fn unlink(p: &Path) -> io::Result<()> { + if stat(p)?.file_type.dir { + return Err(io::const_error!(io::ErrorKind::IsADirectory, "a directory")); + } + path_call(abi::call::REMOVE, p, [0; 5]).map(drop) +} + +pub fn rename(old: &Path, new: &Path) -> io::Result<()> { + if stat(old)?.file_type.dir { + return unsupported(); + } + if stat(new).is_ok_and(|a| a.file_type.dir) { + return Err(io::const_error!(io::ErrorKind::IsADirectory, "the new name is a directory")); + } + // As a copy: the file system cannot move a file yet. + copy(old, new)?; + unlink(old) +} + +pub fn rename_noreplace(old: &Path, new: &Path) -> io::Result<()> { + if stat(new).is_ok() { + return Err(io::const_error!(io::ErrorKind::AlreadyExists, "the new name exists")); + } + rename(old, new) +} + +pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> { + unsupported() +} + +pub fn set_perm_nofollow(_p: &Path, _perm: FilePermissions) -> io::Result<()> { + unsupported() +} + +pub fn set_times(_p: &Path, _times: FileTimes) -> io::Result<()> { + unsupported() +} + +pub fn set_times_nofollow(_p: &Path, _times: FileTimes) -> io::Result<()> { + unsupported() +} + +pub fn rmdir(p: &Path) -> io::Result<()> { + if readdir(p)?.next().is_some() { + return Err(io::const_error!(io::ErrorKind::DirectoryNotEmpty, "the directory is not empty")); + } + path_call(abi::call::REMOVE, p, [0; 5]).map(drop) +} + +pub fn remove_dir_all(path: &Path) -> io::Result<()> { + if !stat(path)?.file_type.dir { + return Err(io::const_error!(io::ErrorKind::NotADirectory, "not a directory")); + } + path_call(abi::call::REMOVE, path, [0; 5]).map(drop) +} + +pub fn exists(path: &Path) -> io::Result { + Ok(stat(path).is_ok()) +} + +pub fn readlink(_p: &Path) -> io::Result { + unsupported() +} + +pub fn symlink(_original: &Path, _link: &Path) -> io::Result<()> { + unsupported() +} + +pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { + unsupported() +} + +pub fn canonicalize(p: &Path) -> io::Result { + stat(p)?; + Ok(p.to_path_buf()) +} + +pub fn copy(from: &Path, to: &Path) -> io::Result { + if stat(from)?.file_type.dir { + return Err(io::const_error!(io::ErrorKind::IsADirectory, "a directory")); + } + write_whole(to, &[])?; + let mut buf = crate::vec![0u8; 1 << 20]; + let mut at = 0u64; + loop { + let n = read_at(from, at, &mut buf)?; + if n == 0 { + return Ok(at); + } + write_at(to, at, &buf[..n])?; + at += n as u64; + } +} diff --git a/std/src/sys/io/error/mod.rs b/std/src/sys/io/error/mod.rs index a56030f..80a074a 100644 --- a/std/src/sys/io/error/mod.rs +++ b/std/src/sys/io/error/mod.rs @@ -31,7 +31,7 @@ cfg_select! { mod xous; pub use xous::*; } - any(target_os = "vexos", target_family = "wasm", target_os = "zkvm", target_os = "trusty") => { + any(target_os = "vexos", target_family = "wasm", target_os = "zkvm", target_os = "trusty", target_os = "pinnacle") => { mod generic; pub use generic::*; } diff --git a/std/src/sys/net/connection/mod.rs b/std/src/sys/net/connection/mod.rs index 49a0f47..6e95969 100644 --- a/std/src/sys/net/connection/mod.rs +++ b/std/src/sys/net/connection/mod.rs @@ -21,6 +21,10 @@ cfg_select! { mod motor; pub use motor::*; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::*; + } target_os = "xous" => { mod xous; pub use xous::*; diff --git a/std/src/sys/net/connection/pinnacle.rs b/std/src/sys/net/connection/pinnacle.rs new file mode 100644 index 0000000..a745457 --- /dev/null +++ b/std/src/sys/net/connection/pinnacle.rs @@ -0,0 +1,744 @@ +//! The network on Pinnacle. The kernel's sockets are channels: a TCP +//! connection's bytes arrive as messages and go out as messages, and it +//! closes when the connection ends; a listener's accepted connections arrive +//! as messages carrying their channel; a UDP socket's datagrams travel as +//! the peer's address, its port, then the payload. TCP connects over IPv4 or +//! IPv6 and names resolve to either; UDP is IPv4 only. +//! +//! What the kernel does not tell (an accepted connection's peer, a +//! connection's own port) is answered as the unspecified address. + +use crate::fmt; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; +use crate::sync::Mutex; +use crate::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use crate::sys::pal::{abi, call, call0, call1}; +use crate::sys::unsupported; +use crate::time::Duration; + +const MAX_MESSAGE: usize = abi::MAX_MESSAGE; + +/// What waiting on a channel gave. +enum Received { + /// A message of this many bytes, carrying this many handles. + Message(usize, usize), + Closed, + TimedOut, +} + +/// Waits on channel `handle` for a message into `buffer` (and handles into +/// `handles`), until `deadline` (ms since boot; 0 for ever). +fn receive(handle: u64, buffer: &mut [u8], handles: &mut [u64], deadline: u64) -> io::Result { + let ends = [handle]; + let (index, len, count) = call( + abi::call::RECEIVE, + [ + ends.as_ptr().addr() as u64, + 1, + buffer.as_mut_ptr().addr() as u64, + buffer.len() as u64, + handles.as_mut_ptr().addr() as u64, + handles.len() as u64, + deadline, + ], + ); + Ok(match (index, len) { + (abi::ERROR, _) => return Err(io::const_error!(io::ErrorKind::Other, "a socket that is gone")), + (abi::TIMEOUT, _) => Received::TimedOut, + (_, abi::CLOSED) => Received::Closed, + (_, len) => Received::Message(len as usize, count as usize), + }) +} + +fn send(handle: u64, bytes: &[u8]) -> io::Result<()> { + let r = call( + abi::call::SEND, + [handle, bytes.as_ptr().addr() as u64, bytes.len() as u64, 0, 0, 0, 0], + ); + if r.0 == abi::ERROR { + Err(io::const_error!(io::ErrorKind::BrokenPipe, "the connection is closed")) + } else { + Ok(()) + } +} + +fn close(handle: u64) { + call1(abi::call::CLOSE, handle); +} + +/// A timeout as the kernel takes one: a deadline in ms since boot, or 0. +#[derive(Default)] +struct Timeout(AtomicU64); + +impl Timeout { + fn set(&self, timeout: Option) -> io::Result<()> { + let ms = match timeout { + None => 0, + Some(d) if d.is_zero() => { + return Err(io::const_error!(io::ErrorKind::InvalidInput, "a zero timeout")); + } + Some(d) => u64::try_from(d.as_nanos().div_ceil(1_000_000)).unwrap_or(u64::MAX), + }; + self.0.store(ms, Ordering::Relaxed); + Ok(()) + } + + fn get(&self) -> Option { + match self.0.load(Ordering::Relaxed) { + 0 => None, + ms => Some(Duration::from_millis(ms)), + } + } + + /// The deadline for a wait starting now; `nonblocking` waits not at all. + fn deadline(&self, nonblocking: bool) -> u64 { + if nonblocking { + // Already past: the call answers at once. + return 1; + } + match self.0.load(Ordering::Relaxed) { + 0 => 0, + // `time` is whole ms, cut down: one more, never short. + ms => call0(abi::call::TIME).saturating_add(ms).saturating_add(1), + } + } +} + +fn timed_out(nonblocking: bool) -> io::Error { + if nonblocking { + io::const_error!(io::ErrorKind::WouldBlock, "nothing yet") + } else { + io::const_error!(io::ErrorKind::TimedOut, "the timeout passed") + } +} + +fn ipv4(addr: &SocketAddr) -> io::Result { + match addr { + SocketAddr::V4(a) => Ok(*a), + SocketAddr::V6(_) => Err(io::const_error!(io::ErrorKind::Unsupported, "IPv4 only")), + } +} + +fn first_ipv4(addr: A) -> io::Result { + let mut last = io::const_error!(io::ErrorKind::InvalidInput, "no address"); + for a in addr.to_socket_addrs()? { + match ipv4(&a) { + Ok(a) => return Ok(a), + Err(e) => last = e, + } + } + Err(last) +} + +/// This device's address, once the network has one. +fn local_ip() -> Ipv4Addr { + let ip = call0(abi::call::NET_INFO); + if ip == abi::ERROR { Ipv4Addr::UNSPECIFIED } else { Ipv4Addr::from_bits(ip as u32) } +} + +const UNSPECIFIED: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)); + +/// What a stream has received and not yet been read. +struct Pending { + bytes: Vec, + at: usize, + closed: bool, +} + +pub struct TcpStream { + handle: u64, + peer: SocketAddr, + pending: Mutex, + read_timeout: Timeout, + nonblocking: AtomicBool, + nodelay: AtomicBool, +} + +impl TcpStream { + pub fn handle(&self) -> u64 { + self.handle + } + + fn from_handle(handle: u64, peer: SocketAddr) -> TcpStream { + TcpStream { + handle, + peer, + pending: Mutex::new(Pending { bytes: Vec::new(), at: 0, closed: false }), + read_timeout: Timeout::default(), + nonblocking: AtomicBool::new(false), + nodelay: AtomicBool::new(false), + } + } + + /// Connects. The kernel opens the connection in the background: one the + /// peer refuses shows as a stream that ends at once. + pub fn connect(addr: A) -> io::Result { + let addr = addr + .to_socket_addrs()? + .next() + .ok_or(io::const_error!(io::ErrorKind::InvalidInput, "no address"))?; + let handle = match addr { + SocketAddr::V4(a) => { + call(abi::call::CONNECT_TCP, [a.ip().to_bits() as u64, a.port() as u64, 0, 0, 0, 0, 0]).0 + } + SocketAddr::V6(a) => { + let bits = a.ip().to_bits(); + let (high, low) = ((bits >> 64) as u64, bits as u64); + call(abi::call::CONNECT_TCP6, [high, low, a.port() as u64, 0, 0, 0, 0]).0 + } + }; + if handle == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::PermissionDenied, "no network for this program")); + } + Ok(TcpStream::from_handle(handle, addr)) + } + + pub fn connect_timeout(addr: &SocketAddr, _: Duration) -> io::Result { + TcpStream::connect(addr) + } + + pub fn set_read_timeout(&self, timeout: Option) -> io::Result<()> { + self.read_timeout.set(timeout) + } + + pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { + // Sending never waits: the kernel queues it. + Ok(()) + } + + pub fn read_timeout(&self) -> io::Result> { + Ok(self.read_timeout.get()) + } + + pub fn write_timeout(&self) -> io::Result> { + Ok(None) + } + + fn read_inner(&self, buf: &mut [u8], peek: bool) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if pending.at < pending.bytes.len() { + let available = &pending.bytes[pending.at..]; + let n = available.len().min(buf.len()); + buf[..n].copy_from_slice(&available[..n]); + if !peek { + pending.at += n; + } + return Ok(n); + } + if pending.closed { + return Ok(0); + } + let nonblocking = self.nonblocking.load(Ordering::Relaxed); + let mut message = crate::vec![0u8; MAX_MESSAGE]; + match receive(self.handle, &mut message, &mut [], self.read_timeout.deadline(nonblocking))? { + Received::Message(len, _) => { + message.truncate(len); + pending.bytes = message; + pending.at = 0; + } + Received::Closed => pending.closed = true, + Received::TimedOut => return Err(timed_out(nonblocking)), + } + } + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + self.read_inner(buf, true) + } + + pub fn read(&self, buf: &mut [u8]) -> io::Result { + self.read_inner(buf, false) + } + + pub fn read_buf(&self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> { + crate::io::default_read_buf(|buf| self.read(buf), cursor) + } + + pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { + crate::io::default_read_vectored(|buf| self.read(buf), bufs) + } + + pub fn is_read_vectored(&self) -> bool { + false + } + + pub fn write(&self, buf: &[u8]) -> io::Result { + let n = buf.len().min(MAX_MESSAGE); + send(self.handle, &buf[..n])?; + Ok(n) + } + + pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { + crate::io::default_write_vectored(|buf| self.write(buf), bufs) + } + + pub fn is_write_vectored(&self) -> bool { + false + } + + pub fn peer_addr(&self) -> io::Result { + Ok(self.peer) + } + + pub fn socket_addr(&self) -> io::Result { + Ok(SocketAddr::V4(SocketAddrV4::new(local_ip(), 0))) + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + match how { + Shutdown::Read => { + self.pending.lock().unwrap_or_else(|e| e.into_inner()).closed = true; + Ok(()) + } + // The kernel closes a connection only whole, as its channel goes. + Shutdown::Write | Shutdown::Both => unsupported(), + } + } + + pub fn duplicate(&self) -> io::Result { + unsupported() + } + + pub fn set_linger(&self, _: Option) -> io::Result<()> { + unsupported() + } + + pub fn linger(&self) -> io::Result> { + Ok(None) + } + + pub fn set_keepalive(&self, _: bool) -> io::Result<()> { + unsupported() + } + + pub fn keepalive(&self) -> io::Result { + Ok(false) + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + // The kernel sends each message as soon as it can: always "no delay". + self.nodelay.store(nodelay, Ordering::Relaxed); + Ok(()) + } + + pub fn nodelay(&self) -> io::Result { + Ok(self.nodelay.load(Ordering::Relaxed)) + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + unsupported() + } + + pub fn ttl(&self) -> io::Result { + unsupported() + } + + pub fn set_hop_limit_v6(&self, _: u8) -> io::Result<()> { + unsupported() + } + + pub fn hop_limit_v6(&self) -> io::Result { + unsupported() + } + + pub fn take_error(&self) -> io::Result> { + Ok(None) + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + self.nonblocking.store(nonblocking, Ordering::Relaxed); + Ok(()) + } +} + +impl Drop for TcpStream { + fn drop(&mut self) { + close(self.handle); + } +} + +impl fmt::Debug for TcpStream { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TcpStream").field("peer", &self.peer).finish_non_exhaustive() + } +} + +pub struct TcpListener { + handle: u64, + port: u16, + nonblocking: AtomicBool, +} + +impl TcpListener { + pub fn handle(&self) -> u64 { + self.handle + } + + pub fn bind(addr: A) -> io::Result { + let addr = first_ipv4(addr)?; + if addr.port() == 0 { + return Err(io::const_error!(io::ErrorKind::Unsupported, "listening needs a port")); + } + let handle = call1(abi::call::LISTEN_TCP, addr.port() as u64); + if handle == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::AddrInUse, "the port is taken, or no network")); + } + Ok(TcpListener { handle, port: addr.port(), nonblocking: AtomicBool::new(false) }) + } + + pub fn socket_addr(&self) -> io::Result { + Ok(SocketAddr::V4(SocketAddrV4::new(local_ip(), self.port))) + } + + pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { + let nonblocking = self.nonblocking.load(Ordering::Relaxed); + loop { + let mut handles = [0u64; abi::MAX_MESSAGE_HANDLES]; + let mut bytes = [0u8; 16]; + let deadline = if nonblocking { 1 } else { 0 }; + match receive(self.handle, &mut bytes, &mut handles, deadline)? { + Received::Message(_, count) if count >= 1 => { + for &extra in &handles[1..count] { + close(extra); + } + return Ok((TcpStream::from_handle(handles[0], UNSPECIFIED), UNSPECIFIED)); + } + Received::Message(..) => {} + Received::Closed => { + return Err(io::const_error!(io::ErrorKind::NotConnected, "the listener is closed")); + } + Received::TimedOut => return Err(timed_out(nonblocking)), + } + } + } + + pub fn duplicate(&self) -> io::Result { + unsupported() + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + unsupported() + } + + pub fn ttl(&self) -> io::Result { + unsupported() + } + + pub fn set_hop_limit_v6(&self, _: u8) -> io::Result<()> { + unsupported() + } + + pub fn hop_limit_v6(&self) -> io::Result { + unsupported() + } + + pub fn set_only_v6(&self, _: bool) -> io::Result<()> { + unsupported() + } + + pub fn only_v6(&self) -> io::Result { + Ok(false) + } + + pub fn take_error(&self) -> io::Result> { + Ok(None) + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + self.nonblocking.store(nonblocking, Ordering::Relaxed); + Ok(()) + } +} + +impl Drop for TcpListener { + fn drop(&mut self) { + close(self.handle); + } +} + +impl fmt::Debug for TcpListener { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TcpListener").field("port", &self.port).finish_non_exhaustive() + } +} + +/// A datagram received and not yet taken (after a peek). +type Datagram = (Vec, SocketAddr); + +pub struct UdpSocket { + handle: u64, + port: u16, + peer: Mutex>, + peeked: Mutex>, + read_timeout: Timeout, + nonblocking: AtomicBool, +} + +impl UdpSocket { + pub fn handle(&self) -> u64 { + self.handle + } + + pub fn bind(addr: A) -> io::Result { + let addr = first_ipv4(addr)?; + let (handle, port, _) = call(abi::call::UDP_BIND, [addr.port() as u64, 0, 0, 0, 0, 0, 0]); + if handle == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::AddrInUse, "the port is taken, or no network")); + } + Ok(UdpSocket { + handle, + port: port as u16, + peer: Mutex::new(None), + peeked: Mutex::new(None), + read_timeout: Timeout::default(), + nonblocking: AtomicBool::new(false), + }) + } + + pub fn peer_addr(&self) -> io::Result { + match *self.peer.lock().unwrap_or_else(|e| e.into_inner()) { + Some(peer) => Ok(SocketAddr::V4(peer)), + None => Err(io::const_error!(io::ErrorKind::NotConnected, "not connected")), + } + } + + pub fn socket_addr(&self) -> io::Result { + Ok(SocketAddr::V4(SocketAddrV4::new(local_ip(), self.port))) + } + + /// The next datagram, from the one peeked if there is one. + fn next(&self, take: bool) -> io::Result { + let mut peeked = self.peeked.lock().unwrap_or_else(|e| e.into_inner()); + if peeked.is_none() { + let nonblocking = self.nonblocking.load(Ordering::Relaxed); + let mut message = crate::vec![0u8; MAX_MESSAGE]; + loop { + match receive(self.handle, &mut message, &mut [], self.read_timeout.deadline(nonblocking))? { + Received::Message(len, _) if len >= 6 => { + let ip = Ipv4Addr::new(message[0], message[1], message[2], message[3]); + let port = u16::from_be_bytes([message[4], message[5]]); + let from = SocketAddrV4::new(ip, port); + let connected = *self.peer.lock().unwrap_or_else(|e| e.into_inner()); + if connected.is_some_and(|p| p != from) { + continue; + } + *peeked = Some((message[6..len].to_vec(), SocketAddr::V4(from))); + break; + } + Received::Message(..) => {} + Received::Closed => { + return Err(io::const_error!(io::ErrorKind::NotConnected, "the socket is closed")); + } + Received::TimedOut => return Err(timed_out(nonblocking)), + } + } + } + let datagram = if take { peeked.take() } else { peeked.clone() }; + Ok(datagram.expect("a datagram was just received")) + } + + fn copy_out(buf: &mut [u8], (bytes, from): Datagram) -> (usize, SocketAddr) { + let n = bytes.len().min(buf.len()); + buf[..n].copy_from_slice(&bytes[..n]); + (n, from) + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + Ok(Self::copy_out(buf, self.next(true)?)) + } + + pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + Ok(Self::copy_out(buf, self.next(false)?)) + } + + pub fn send_to(&self, buf: &[u8], addr: &SocketAddr) -> io::Result { + let to = ipv4(addr)?; + let n = buf.len().min(MAX_MESSAGE - 6); + let mut message = Vec::with_capacity(6 + n); + message.extend_from_slice(&to.ip().octets()); + message.extend_from_slice(&to.port().to_be_bytes()); + message.extend_from_slice(&buf[..n]); + send(self.handle, &message)?; + Ok(n) + } + + pub fn duplicate(&self) -> io::Result { + unsupported() + } + + pub fn set_read_timeout(&self, timeout: Option) -> io::Result<()> { + self.read_timeout.set(timeout) + } + + pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { + Ok(()) + } + + pub fn read_timeout(&self) -> io::Result> { + Ok(self.read_timeout.get()) + } + + pub fn write_timeout(&self) -> io::Result> { + Ok(None) + } + + pub fn set_broadcast(&self, _: bool) -> io::Result<()> { + unsupported() + } + + pub fn broadcast(&self) -> io::Result { + Ok(false) + } + + pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> { + unsupported() + } + + pub fn multicast_loop_v4(&self) -> io::Result { + unsupported() + } + + pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> { + unsupported() + } + + pub fn multicast_ttl_v4(&self) -> io::Result { + unsupported() + } + + pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> { + unsupported() + } + + pub fn multicast_loop_v6(&self) -> io::Result { + unsupported() + } + + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { + unsupported() + } + + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { + unsupported() + } + + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { + unsupported() + } + + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { + unsupported() + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + unsupported() + } + + pub fn ttl(&self) -> io::Result { + unsupported() + } + + pub fn set_hop_limit_v6(&self, _: u8) -> io::Result<()> { + unsupported() + } + + pub fn hop_limit_v6(&self) -> io::Result { + unsupported() + } + + pub fn set_multicast_hop_limit_v6(&self, _: u8) -> io::Result<()> { + unsupported() + } + + pub fn multicast_hop_limit_v6(&self) -> io::Result { + unsupported() + } + + pub fn take_error(&self) -> io::Result> { + Ok(None) + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + self.nonblocking.store(nonblocking, Ordering::Relaxed); + Ok(()) + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result { + self.recv_from(buf).map(|(n, _)| n) + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + self.peek_from(buf).map(|(n, _)| n) + } + + pub fn send(&self, buf: &[u8]) -> io::Result { + let peer = self.peer_addr()?; + self.send_to(buf, &peer) + } + + pub fn connect(&self, addr: A) -> io::Result<()> { + let addr = first_ipv4(addr)?; + *self.peer.lock().unwrap_or_else(|e| e.into_inner()) = Some(addr); + Ok(()) + } +} + +impl Drop for UdpSocket { + fn drop(&mut self) { + close(self.handle); + } +} + +impl fmt::Debug for UdpSocket { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("UdpSocket").field("port", &self.port).finish_non_exhaustive() + } +} + +pub struct LookupHost(crate::option::IntoIter); + +impl Iterator for LookupHost { + type Item = SocketAddr; + fn next(&mut self) -> Option { + self.0.next() + } +} + +/// How long a name is looked up for. +const LOOKUP_MS: u64 = 10_000; + +pub fn lookup_host(host: &str, port: u16) -> io::Result { + let found = |ip: Ipv4Addr| Ok(LookupHost(Some(SocketAddr::V4(SocketAddrV4::new(ip, port))).into_iter())); + if let Ok(ip) = host.parse::() { + return found(ip); + } + if let Ok(ip) = host.parse::() { + return Ok(LookupHost(Some(SocketAddr::V6(SocketAddrV6::new(ip, port, 0, 0))).into_iter())); + } + let handle = call( + abi::call::RESOLVE, + [host.as_ptr().addr() as u64, host.len() as u64, 0, 0, 0, 0, 0], + ) + .0; + if handle == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::PermissionDenied, "no network for this program")); + } + let mut answer = [0u8; 16]; + let deadline = call0(abi::call::TIME).saturating_add(LOOKUP_MS); + let got = receive(handle, &mut answer, &mut [], deadline); + close(handle); + match got? { + Received::Message(4, _) => found(Ipv4Addr::new(answer[0], answer[1], answer[2], answer[3])), + Received::Message(16, _) => { + let ip = Ipv6Addr::from(answer); + Ok(LookupHost(Some(SocketAddr::V6(SocketAddrV6::new(ip, port, 0, 0))).into_iter())) + } + Received::TimedOut => Err(io::const_error!(io::ErrorKind::TimedOut, "the name was not answered")), + _ => Err(io::const_error!(io::ErrorKind::NotFound, "no address for the name")), + } +} diff --git a/std/src/sys/pal/mod.rs b/std/src/sys/pal/mod.rs index 88d9d42..734e2a0 100644 --- a/std/src/sys/pal/mod.rs +++ b/std/src/sys/pal/mod.rs @@ -40,6 +40,10 @@ cfg_select! { mod wasm; pub use self::wasm::*; } + target_os = "pinnacle" => { + mod pinnacle; + pub use self::pinnacle::*; + } target_os = "xous" => { mod xous; pub use self::xous::*; diff --git a/std/src/sys/pal/pinnacle/channel.rs b/std/src/sys/pal/pinnacle/channel.rs new file mode 100644 index 0000000..fff5564 --- /dev/null +++ b/std/src/sys/pal/pinnacle/channel.rs @@ -0,0 +1,95 @@ +//! A channel used as a byte stream: what pipes and standard streams between +//! programs are. Bytes go out as messages of at most `MAX_MESSAGE`; what +//! arrives is read a message at a time, the rest kept for the next read. The +//! stream ends when the other end closes. + +use super::{abi, call, call1}; +use crate::io; +use crate::sync::Mutex; + +/// What has arrived and not yet been read. +struct Pending { + bytes: crate::vec::Vec, + at: usize, + ended: bool, +} + +pub struct Stream { + handle: u64, + pending: Mutex, +} + +impl Stream { + pub fn new(handle: u64) -> Stream { + Stream { handle, pending: Mutex::new(Pending { bytes: crate::vec::Vec::new(), at: 0, ended: false }) } + } + + /// Two ends of a new channel. + pub fn pair() -> io::Result<(Stream, Stream)> { + let (a, b, _) = call(abi::call::CHANNEL, [0; 7]); + if a == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::OutOfMemory, "no channel")); + } + Ok((Stream::new(a), Stream::new(b))) + } + + pub fn handle(&self) -> u64 { + self.handle + } + + /// Gives up the handle without closing it (it was sent away). + pub fn into_handle(self) -> u64 { + let handle = self.handle; + crate::mem::forget(self); + handle + } + + pub fn read(&self, buf: &mut [u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if pending.at < pending.bytes.len() { + let n = (pending.bytes.len() - pending.at).min(buf.len()); + buf[..n].copy_from_slice(&pending.bytes[pending.at..pending.at + n]); + pending.at += n; + return Ok(n); + } + if pending.ended { + return Ok(0); + } + let mut message = crate::vec![0u8; abi::MAX_MESSAGE]; + let ends = [self.handle]; + let (index, len, count) = call( + abi::call::RECEIVE, + [ends.as_ptr().addr() as u64, 1, message.as_mut_ptr().addr() as u64, message.len() as u64, 0, 0, 0], + ); + if index == abi::ERROR || len == abi::CLOSED { + pending.ended = true; + continue; + } + // A message carrying handles is not a stream's: they were not + // taken, so the kernel kept them; nothing to close. + let _ = count; + message.truncate(len as usize); + pending.bytes = message; + pending.at = 0; + } + } + + pub fn write(&self, buf: &[u8]) -> io::Result { + let n = buf.len().min(abi::MAX_MESSAGE); + let (r, ..) = call(abi::call::SEND, [self.handle, buf.as_ptr().addr() as u64, n as u64, 0, 0, 0, 0]); + if r == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::BrokenPipe, "the other end is closed")); + } + Ok(n) + } +} + +impl Drop for Stream { + fn drop(&mut self) { + call1(abi::call::CLOSE, self.handle); + } +} diff --git a/std/src/sys/pal/pinnacle/futex.rs b/std/src/sys/pal/pinnacle/futex.rs new file mode 100644 index 0000000..93b2f07 --- /dev/null +++ b/std/src/sys/pal/pinnacle/futex.rs @@ -0,0 +1,49 @@ +//! Futexes, as the kernel offers them (`futex_wait`, `futex_wake`): what +//! std's `Mutex`, `Condvar`, `RwLock`, `Once` and thread parking stand on. + +use super::{abi, call2, call3}; +use crate::sync::atomic::Atomic; +use crate::time::Duration; + +/// An atomic for use as a futex that is at least 32-bits but may be larger +pub type Futex = Atomic; +/// Must be the underlying type of Futex +pub type Primitive = u32; + +/// An atomic for use as a futex that is at least 8-bits but may be larger. +pub type SmallFutex = Atomic; +/// Must be the underlying type of SmallFutex +pub type SmallPrimitive = u32; + +/// Waits while `futex` holds `expected`, for at most `timeout`. Returns +/// false only when the timeout passed. +pub fn futex_wait(futex: &Atomic, expected: u32, timeout: Option) -> bool { + // The kernel's deadlines are in ms since boot, 0 for none: round a + // timeout up and add one (`time` is whole ms, cut down), never short; + // past the end of time is none. + let deadline = match timeout { + None => 0, + Some(t) => { + let ms = t.as_nanos().div_ceil(1_000_000); + match u64::try_from(ms) { + Ok(ms) => super::call0(abi::call::TIME).checked_add(ms.saturating_add(1)).unwrap_or(0), + Err(_) => 0, + } + } + }; + call3(abi::call::FUTEX_WAIT, futex.as_ptr().addr() as u64, expected as u64, deadline) + != abi::TIMEOUT +} + +/// Wakes one waiter. Returns whether there was one. +#[inline] +pub fn futex_wake(futex: &Atomic) -> bool { + let woken = call2(abi::call::FUTEX_WAKE, futex.as_ptr().addr() as u64, 1); + woken != abi::ERROR && woken > 0 +} + +/// Wakes every waiter. +#[inline] +pub fn futex_wake_all(futex: &Atomic) { + call2(abi::call::FUTEX_WAKE, futex.as_ptr().addr() as u64, u64::MAX); +} diff --git a/std/src/sys/pal/pinnacle/mod.rs b/std/src/sys/pal/pinnacle/mod.rs new file mode 100644 index 0000000..9fa9f38 --- /dev/null +++ b/std/src/sys/pal/pinnacle/mod.rs @@ -0,0 +1,106 @@ +//! Pinnacle: system calls, the program's entry and how it ends. +//! +//! A system call is `svc #0` with its number in x8 and its arguments from x0; +//! results come back in x0 to x2. The numbers and constants are Pinnacle's +//! own `abi` crate, copied in as `abi.rs` when this library is assembled +//! (`cargo xtask std`), so there is one source of them. + +#![forbid(unsafe_op_in_unsafe_fn)] + +#[allow(dead_code, unused_imports, missing_docs)] +pub mod abi; +pub mod channel; +pub mod futex; +pub mod start; + +use crate::io; +use crate::sync::atomic::{AtomicU64, Ordering}; + +pub fn call(number: u64, a: [u64; 7]) -> (u64, u64, u64) { + let (r0, r1, r2); + // SAFETY: a system call; the kernel preserves every register it does not + // answer in, and reads or writes only memory the arguments name. + unsafe { + core::arch::asm!( + "svc #0", + inout("x0") a[0] => r0, + inout("x1") a[1] => r1, + inout("x2") a[2] => r2, + in("x3") a[3], + in("x4") a[4], + in("x5") a[5], + in("x6") a[6], + in("x8") number, + options(nostack), + ); + } + (r0, r1, r2) +} + +pub fn call0(number: u64) -> u64 { + call(number, [0; 7]).0 +} + +pub fn call1(number: u64, a: u64) -> u64 { + call(number, [a, 0, 0, 0, 0, 0, 0]).0 +} + +pub fn call2(number: u64, a: u64, b: u64) -> u64 { + call(number, [a, b, 0, 0, 0, 0, 0]).0 +} + +pub fn call3(number: u64, a: u64, b: u64, c: u64) -> u64 { + call(number, [a, b, c, 0, 0, 0, 0]).0 +} + +/// Ends the program, every thread of it. +pub fn exit(code: i32) -> ! { + call1(abi::call::EXIT_PROCESS, code as u32 as u64); + unreachable!("exit_process returned") +} + +/// Ends the calling thread only. +pub fn exit_thread() -> ! { + call1(abi::call::EXIT, 0); + unreachable!("exit returned") +} + +/// The argument the program was started with (`spawn`'s), in x0 at entry. +static ARGUMENT: AtomicU64 = AtomicU64::new(0); + +pub fn argument() -> u64 { + ARGUMENT.load(Ordering::Relaxed) +} + +/// The kernel starts a program here with its argument in x0 and its stack +/// set up; rustc's `main` runs `lang_start`, which runs the program's own. +#[cfg(not(test))] +#[unsafe(no_mangle)] +pub extern "C" fn _start(argument: u64) -> ! { + unsafe extern "C" { + fn main() -> i32; + } + ARGUMENT.store(argument, Ordering::Relaxed); + start::init(argument); + // SAFETY: rustc's generated entry, called once. + exit(unsafe { main() }) +} + +// SAFETY: must be called only once during runtime initialization. +pub unsafe fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {} + +// SAFETY: must be called only once during runtime cleanup. +pub unsafe fn cleanup() {} + +pub fn unsupported() -> io::Result { + Err(unsupported_err()) +} + +pub fn unsupported_err() -> io::Error { + io::Error::UNSUPPORTED_PLATFORM +} + +/// What a program that aborts ends with: SIGABRT's number, as on Unix. +pub fn abort_internal() -> ! { + exit(134) +} diff --git a/std/src/sys/pal/pinnacle/start.rs b/std/src/sys/pal/pinnacle/start.rs new file mode 100644 index 0000000..7eb3199 --- /dev/null +++ b/std/src/sys/pal/pinnacle/start.rs @@ -0,0 +1,145 @@ +//! What a program's starter gives it beyond the argument: its arguments, +//! environment and standard streams. A std program started with +//! [`abi::STD_START`] finds them in one message on handle 1: +//! +//! - the arguments: a u32 count, then each as a u32 length and its bytes; +//! - the environment: a u32 count, then each as a key and a value, each a +//! u32 length and its bytes; +//! - stdin, stdout, stderr: a byte each, [`CONSOLE`], [`NULL`] or +//! [`CHANNEL`]; the channels among them are the message's handles, in +//! that order. +//! +//! Lengths are little-endian; the message is at most `abi::MAX_MESSAGE`. + +use super::abi; +use crate::ffi::OsString; +use crate::sync::OnceLock; + +pub const CONSOLE: u8 = 0; +pub const NULL: u8 = 1; +pub const CHANNEL: u8 = 2; + +/// Where a standard stream goes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Stream { + Console, + Null, + Channel(u64), +} + +#[derive(Default)] +pub struct Start { + pub args: crate::vec::Vec, + pub env: crate::vec::Vec<(OsString, OsString)>, + pub streams: [Option; 3], +} + +static START: OnceLock = OnceLock::new(); + +/// What the program was started with (nothing, when it was given nothing). +pub fn get() -> &'static Start { + START.get_or_init(Start::default) +} + +/// Stream `n` (0 stdin, 1 stdout, 2 stderr). +pub fn stream(n: usize) -> Stream { + get().streams[n].unwrap_or(Stream::Console) +} + +/// Reads the start message, if `argument` says there is one; at entry, +/// before `main`. +pub fn init(argument: u64) { + if argument != abi::STD_START { + return; + } + let mut message = crate::vec![0u8; abi::MAX_MESSAGE]; + let mut handles = [0u64; abi::MAX_MESSAGE_HANDLES]; + let ends = [1u64]; + let (index, len, count) = super::call( + abi::call::RECEIVE, + [ + ends.as_ptr().addr() as u64, + 1, + message.as_mut_ptr().addr() as u64, + message.len() as u64, + handles.as_mut_ptr().addr() as u64, + handles.len() as u64, + 0, + ], + ); + super::call1(abi::call::CLOSE, 1); + if index != 0 || len == abi::CLOSED { + return; + } + message.truncate(len as usize); + if let Some(start) = parse(&message, &handles[..count as usize]) { + let _ = START.set(start); + } +} + +fn parse(message: &[u8], handles: &[u64]) -> Option { + fn take<'a>(at: &mut &'a [u8], n: usize) -> Option<&'a [u8]> { + let (bytes, rest) = at.split_at_checked(n)?; + *at = rest; + Some(bytes) + } + fn number(at: &mut &[u8]) -> Option { + take(at, 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize) + } + fn string(at: &mut &[u8]) -> Option { + let n = number(at)?; + let bytes = take(at, n)?; + Some(OsString::from(crate::str::from_utf8(bytes).ok()?)) + } + let mut at = message; + let mut start = Start::default(); + for _ in 0..number(&mut at)? { + start.args.push(string(&mut at)?); + } + for _ in 0..number(&mut at)? { + let key = string(&mut at)?; + start.env.push((key, string(&mut at)?)); + } + let modes = take(&mut at, 3)?; + let mut handles = handles.iter(); + for (stream, &mode) in start.streams.iter_mut().zip(modes) { + *stream = Some(match mode { + CONSOLE => Stream::Console, + NULL => Stream::Null, + CHANNEL => Stream::Channel(*handles.next()?), + _ => return None, + }); + } + Some(start) +} + +/// The start message for a program, as [`init`] reads it: the bytes, and +/// the channels to carry with them. +pub fn message(args: &[&[u8]], env: &[(&[u8], &[u8])], streams: [Stream; 3]) -> (crate::vec::Vec, crate::vec::Vec) { + let mut out = crate::vec::Vec::new(); + let string = |out: &mut crate::vec::Vec, b: &[u8]| { + out.extend_from_slice(&(b.len() as u32).to_le_bytes()); + out.extend_from_slice(b); + }; + out.extend_from_slice(&(args.len() as u32).to_le_bytes()); + for arg in args { + string(&mut out, arg); + } + out.extend_from_slice(&(env.len() as u32).to_le_bytes()); + for (key, value) in env { + string(&mut out, key); + string(&mut out, value); + } + let mut handles = crate::vec::Vec::new(); + for stream in streams { + out.push(match stream { + Stream::Console => CONSOLE, + Stream::Null => NULL, + Stream::Channel(h) => { + handles.push(h); + CHANNEL + } + }); + } + (out, handles) +} diff --git a/std/src/sys/pipe/mod.rs b/std/src/sys/pipe/mod.rs index 8522896..053a17b 100644 --- a/std/src/sys/pipe/mod.rs +++ b/std/src/sys/pipe/mod.rs @@ -13,6 +13,10 @@ cfg_select! { mod motor; pub use motor::{Pipe, pipe}; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::{Pipe, pipe}; + } _ => { mod unsupported; pub use unsupported::{Pipe, pipe}; diff --git a/std/src/sys/pipe/pinnacle.rs b/std/src/sys/pipe/pinnacle.rs new file mode 100644 index 0000000..8e622f6 --- /dev/null +++ b/std/src/sys/pipe/pinnacle.rs @@ -0,0 +1,80 @@ +//! Pipes: a channel used as a byte stream (`pal::channel`). + +use crate::fmt; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; +use crate::sys::pal::channel::Stream; + +pub struct Pipe(Stream); + +pub fn pipe() -> io::Result<(Pipe, Pipe)> { + let (a, b) = Stream::pair()?; + Ok((Pipe(a), Pipe(b))) +} + +impl Pipe { + pub(crate) fn from_stream(stream: Stream) -> Pipe { + Pipe(stream) + } + + pub(crate) fn into_stream(self) -> Stream { + self.0 + } + + pub fn handle(&self) -> u64 { + self.0.handle() + } + + pub fn try_clone(&self) -> io::Result { + Err(io::Error::UNSUPPORTED_PLATFORM) + } + + pub fn read(&self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } + + pub fn read_buf(&self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> { + crate::io::default_read_buf(|buf| self.read(buf), cursor) + } + + pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { + crate::io::default_read_vectored(|buf| self.read(buf), bufs) + } + + pub fn is_read_vectored(&self) -> bool { + false + } + + pub fn read_to_end(&self, buf: &mut Vec) -> io::Result { + let start = buf.len(); + let mut chunk = [0u8; 4096]; + loop { + match self.read(&mut chunk)? { + 0 => return Ok(buf.len() - start), + n => buf.extend_from_slice(&chunk[..n]), + } + } + } + + pub fn write(&self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + + pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { + crate::io::default_write_vectored(|buf| self.write(buf), bufs) + } + + pub fn is_write_vectored(&self) -> bool { + false + } + + #[allow(dead_code)] + pub fn diverge(&self) -> ! { + panic!() + } +} + +impl fmt::Debug for Pipe { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Pipe").field(&self.0.handle()).finish() + } +} diff --git a/std/src/sys/process/mod.rs b/std/src/sys/process/mod.rs index 3579a5a..4897fda 100644 --- a/std/src/sys/process/mod.rs +++ b/std/src/sys/process/mod.rs @@ -15,6 +15,10 @@ cfg_select! { mod motor; use motor as imp; } + target_os = "pinnacle" => { + mod pinnacle; + use pinnacle as imp; + } _ => { mod unsupported; use unsupported as imp; diff --git a/std/src/sys/process/pinnacle.rs b/std/src/sys/process/pinnacle.rs new file mode 100644 index 0000000..b840270 --- /dev/null +++ b/std/src/sys/process/pinnacle.rs @@ -0,0 +1,478 @@ +//! Processes on Pinnacle. A program is started by name (`spawn`: built in, +//! or an installed app). When there is more to give it than the kernel's one +//! argument — arguments, an environment, standard streams other than the +//! console — it is started with `STD_START` and a start message on handle 1 +//! (`pal::start`); its streams can be channels, which are its pipes. It is +//! started watched: its exit code arrives on a channel as it ends. + +use super::env::{CommandEnv, CommandEnvs, CommandResolvedEnvs}; +pub use crate::ffi::OsString as EnvKey; +use crate::ffi::{OsStr, OsString}; +use crate::num::NonZero; +use crate::path::Path; +use crate::process::StdioPipes; +use crate::sys::fs::File; +use crate::sys::pal::channel; +use crate::sys::pal::start::{self, Stream}; +use crate::sys::pal::{abi, call, call0, call1}; +use crate::sys::pipe::Pipe; +use crate::{fmt, io}; + +pub struct Command { + program: OsString, + args: Vec, + env: CommandEnv, + + cwd: Option, + stdin: Option, + stdout: Option, + stderr: Option, +} + +#[derive(Debug)] +pub enum Stdio { + Inherit, + Null, + MakePipe, + ParentStdout, + ParentStderr, + /// A pipe end handed to the child. + Pipe(Pipe), + #[allow(dead_code)] // This variant exists only for the Debug impl + InheritFile(File), +} + +impl Command { + pub fn new(program: &OsStr) -> Command { + Command { + program: program.to_owned(), + args: vec![program.to_owned()], + env: Default::default(), + cwd: None, + stdin: None, + stdout: None, + stderr: None, + } + } + + pub fn arg(&mut self, arg: &OsStr) { + self.args.push(arg.to_owned()); + } + + pub fn env_mut(&mut self) -> &mut CommandEnv { + &mut self.env + } + + pub fn cwd(&mut self, dir: &OsStr) { + self.cwd = Some(dir.to_owned()); + } + + pub fn stdin(&mut self, stdin: Stdio) { + self.stdin = Some(stdin); + } + + pub fn stdout(&mut self, stdout: Stdio) { + self.stdout = Some(stdout); + } + + pub fn stderr(&mut self, stderr: Stdio) { + self.stderr = Some(stderr); + } + + pub fn get_program(&self) -> &OsStr { + &self.program + } + + pub fn get_args(&self) -> CommandArgs<'_> { + let mut iter = self.args.iter(); + iter.next(); + CommandArgs { iter } + } + + pub fn get_envs(&self) -> CommandEnvs<'_> { + self.env.iter() + } + + pub fn get_env_clear(&self) -> bool { + self.env.does_clear() + } + + pub fn get_resolved_envs(&self) -> CommandResolvedEnvs { + CommandResolvedEnvs::new(self.env.capture()) + } + + pub fn get_current_dir(&self) -> Option<&Path> { + self.cwd.as_ref().map(|cs| Path::new(cs)) + } + + pub fn spawn(&mut self, default: Stdio, needs_stdin: bool) -> io::Result<(Process, StdioPipes)> { + if self.cwd.is_some() { + return Err(io::const_error!(io::ErrorKind::Unsupported, "programs have no current directory")); + } + let program = self + .program + .to_str() + .ok_or(io::const_error!(io::ErrorKind::InvalidInput, "a program name must be UTF-8"))?; + // Each stream: where the child's goes, and the parent's pipe end. + let mut parent: [Option; 3] = [None, None, None]; + let mut streams = [Stream::Console; 3]; + let chosen = [ + self.stdin.take().or(if needs_stdin { None } else { Some(Stdio::Null) }), + self.stdout.take(), + self.stderr.take(), + ]; + for (n, choice) in chosen.into_iter().enumerate() { + let choice = match choice { + Some(c) => c, + None => match &default { + Stdio::MakePipe => Stdio::MakePipe, + Stdio::Null => Stdio::Null, + _ => Stdio::Inherit, + }, + }; + streams[n] = match choice { + // What this program's own stream is, the child's is too: the + // console, or nothing (a channel cannot be shared). + Stdio::Inherit => match start::stream(n) { + Stream::Channel(_) => Stream::Null, + other => other, + }, + Stdio::ParentStdout | Stdio::ParentStderr => Stream::Console, + Stdio::Null => Stream::Null, + Stdio::MakePipe => { + let (ours, theirs) = channel::Stream::pair()?; + parent[n] = Some(Pipe::from_stream(ours)); + Stream::Channel(theirs.into_handle()) + } + Stdio::Pipe(pipe) => Stream::Channel(pipe.into_stream().into_handle()), + Stdio::InheritFile(_) => { + return Err(io::const_error!(io::ErrorKind::Unsupported, "a file as a program's stream")); + } + }; + } + let args: Vec<&[u8]> = self.args.iter().map(|a| a.as_encoded_bytes()).collect(); + let env = self.env.capture(); + let env: Vec<(&[u8], &[u8])> = + env.iter().map(|(k, v)| (k.as_encoded_bytes(), v.as_encoded_bytes())).collect(); + let (message, mut handles) = start::message(&args, &env, streams); + if message.len() > abi::MAX_MESSAGE { + for h in handles { + call1(abi::call::CLOSE, h); + } + return Err(io::const_error!(io::ErrorKind::ArgumentListTooLong, "more than 4 KiB of arguments")); + } + // The start message waits on a channel the child gets as handle 1. + let (ours, theirs) = channel::Stream::pair()?; + let (r, ..) = call( + abi::call::SEND, + [ours.handle(), message.as_ptr().addr() as u64, message.len() as u64, handles.as_ptr().addr() as u64, handles.len() as u64, 0, 0], + ); + drop(ours); + if r == abi::ERROR { + for h in handles.drain(..) { + call1(abi::call::CLOSE, h); + } + return Err(io::const_error!(io::ErrorKind::Other, "the start message was refused")); + } + let given = [theirs.into_handle()]; + let (id, process, watch) = call( + abi::call::SPAWN, + [ + program.as_ptr().addr() as u64, + program.len() as u64, + abi::STD_START, + given.as_ptr().addr() as u64, + 1, + abi::SPAWN_WATCH, + 0, + ], + ); + if id == abi::ERROR { + call1(abi::call::CLOSE, given[0]); + return Err(io::const_error!(io::ErrorKind::NotFound, "no such program")); + } + let [stdin, stdout, stderr] = parent; + Ok(( + Process { id: id as u32, handle: process, watch: channel::Stream::new(watch), status: None }, + StdioPipes { stdin, stdout, stderr }, + )) + } +} + +pub fn output(cmd: &mut Command) -> io::Result<(ExitStatus, Vec, Vec)> { + let (mut process, mut pipes) = cmd.spawn(Stdio::MakePipe, false)?; + drop(pipes.stdin.take()); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + match (pipes.stdout.take(), pipes.stderr.take()) { + (None, None) => {} + (Some(out), None) => { + out.read_to_end(&mut stdout)?; + } + (None, Some(err)) => { + err.read_to_end(&mut stderr)?; + } + (Some(out), Some(err)) => read_output(out, &mut stdout, err, &mut stderr)?, + } + let status = process.wait()?; + Ok((status, stdout, stderr)) +} + +impl From for Stdio { + fn from(pipe: ChildPipe) -> Stdio { + Stdio::Pipe(pipe) + } +} + +impl From for Stdio { + fn from(_: io::Stdout) -> Stdio { + Stdio::ParentStdout + } +} + +impl From for Stdio { + fn from(_: io::Stderr) -> Stdio { + Stdio::ParentStderr + } +} + +impl From for Stdio { + fn from(file: File) -> Stdio { + Stdio::InheritFile(file) + } +} + + +impl fmt::Debug for Command { + // show all attributes + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if f.alternate() { + let mut debug_command = f.debug_struct("Command"); + debug_command.field("program", &self.program).field("args", &self.args); + if !self.env.is_unchanged() { + debug_command.field("env", &self.env); + } + + if self.cwd.is_some() { + debug_command.field("cwd", &self.cwd); + } + + if self.stdin.is_some() { + debug_command.field("stdin", &self.stdin); + } + if self.stdout.is_some() { + debug_command.field("stdout", &self.stdout); + } + if self.stderr.is_some() { + debug_command.field("stderr", &self.stderr); + } + + debug_command.finish() + } else { + if let Some(ref cwd) = self.cwd { + write!(f, "cd {cwd:?} && ")?; + } + if self.env.does_clear() { + write!(f, "env -i ")?; + // Altered env vars will be printed next, that should exactly work as expected. + } else { + // Removed env vars need the command to be wrapped in `env`. + let mut any_removed = false; + for (key, value_opt) in self.get_envs() { + if value_opt.is_none() { + if !any_removed { + write!(f, "env ")?; + any_removed = true; + } + write!(f, "-u {} ", key.to_string_lossy())?; + } + } + } + // Altered env vars can just be added in front of the program. + for (key, value_opt) in self.get_envs() { + if let Some(value) = value_opt { + write!(f, "{}={value:?} ", key.to_string_lossy())?; + } + } + if self.program != self.args[0] { + write!(f, "[{:?}] ", self.program)?; + } + write!(f, "{:?}", self.args[0])?; + + for arg in &self.args[1..] { + write!(f, " {:?}", arg)?; + } + Ok(()) + } + } +} + +/// A program's exit code, as the kernel gives it: what it passed to +/// `exit_process`, or `KILLED` and the exception class for one ended for a +/// fault, `KILLED` for one ended by a kill. +#[derive(PartialEq, Eq, Clone, Copy, Debug, Default)] +pub struct ExitStatus(i64); + +impl ExitStatus { + pub fn exit_ok(&self) -> Result<(), ExitStatusError> { + if self.0 == 0 { Ok(()) } else { Err(ExitStatusError(*self)) } + } + + pub fn code(&self) -> Option { + i32::try_from(self.0).ok() + } +} + +impl fmt::Display for ExitStatus { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.0 as u64 >= abi::KILLED { + write!(f, "ended by the kernel ({:#x})", self.0) + } else { + write!(f, "exit code: {}", self.0) + } + } +} + +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub struct ExitStatusError(ExitStatus); + +impl Into for ExitStatusError { + fn into(self) -> ExitStatus { + self.0 + } +} + +impl ExitStatusError { + pub fn code(self) -> Option> { + self.0.code().and_then(NonZero::new) + } +} + +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub struct ExitCode(u8); + +impl ExitCode { + pub const SUCCESS: ExitCode = ExitCode(0); + pub const FAILURE: ExitCode = ExitCode(1); + + pub fn as_i32(&self) -> i32 { + self.0 as i32 + } +} + +impl From for ExitCode { + fn from(code: u8) -> Self { + Self(code) + } +} + +pub struct Process { + id: u32, + /// What ends it (`kill`); 0 when it had ended before `spawn` answered. + handle: u64, + /// Where its exit code arrives. + watch: channel::Stream, + status: Option, +} + +impl Process { + pub fn id(&self) -> u32 { + self.id + } + + pub fn kill(&mut self) -> io::Result<()> { + if self.status.is_some() || self.handle == 0 { + return Ok(()); + } + call1(abi::call::KILL, self.handle); + Ok(()) + } + + /// Takes the exit code from the watch channel, waiting until `deadline` + /// (ms since boot; 0 for ever). + fn collect(&mut self, deadline: u64) -> io::Result> { + if let Some(status) = self.status { + return Ok(Some(status)); + } + let mut code = [0u8; 8]; + let ends = [self.watch.handle()]; + let (index, len, _) = call( + abi::call::RECEIVE, + [ends.as_ptr().addr() as u64, 1, code.as_mut_ptr().addr() as u64, 8, 0, 0, deadline], + ); + let status = match (index, len) { + (abi::TIMEOUT, _) => return Ok(None), + (abi::ERROR, _) => return Err(io::const_error!(io::ErrorKind::Other, "the program cannot be waited for")), + (_, 8) => ExitStatus(u64::from_le_bytes(code) as i64), + // Closed with no code: it never ran to its end in this kernel's + // keeping. + _ => ExitStatus(abi::KILLED as i64), + }; + self.status = Some(status); + Ok(Some(status)) + } + + pub fn wait(&mut self) -> io::Result { + self.collect(0).map(|s| s.expect("waiting for ever ends only with a status")) + } + + pub fn try_wait(&mut self) -> io::Result> { + // A deadline already past answers at once. + self.collect(1) + } +} + +impl Drop for Process { + fn drop(&mut self) { + if self.handle != 0 { + call1(abi::call::CLOSE, self.handle); + } + } +} + +pub struct CommandArgs<'a> { + iter: crate::slice::Iter<'a, OsString>, +} + +impl<'a> Iterator for CommandArgs<'a> { + type Item = &'a OsStr; + fn next(&mut self) -> Option<&'a OsStr> { + self.iter.next().map(|os| &**os) + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +impl<'a> ExactSizeIterator for CommandArgs<'a> { + fn len(&self) -> usize { + self.iter.len() + } + fn is_empty(&self) -> bool { + self.iter.is_empty() + } +} + +impl<'a> fmt::Debug for CommandArgs<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter.clone()).finish() + } +} + +pub type ChildPipe = crate::sys::pipe::Pipe; + +/// Both of a child's output pipes, read together so it cannot stall on one +/// while this reads the other. +pub fn read_output(out: ChildPipe, stdout: &mut Vec, err: ChildPipe, stderr: &mut Vec) -> io::Result<()> { + crate::thread::scope(|s| { + let reading_err = s.spawn(move || err.read_to_end(stderr)); + let out = out.read_to_end(stdout); + let err = reading_err.join().expect("the stderr reader panicked"); + out?; + err?; + Ok(()) + }) +} + +pub fn getpid() -> u32 { + call0(abi::call::PID) as u32 +} diff --git a/std/src/sys/random/mod.rs b/std/src/sys/random/mod.rs index 23f6ce8..1a7aa60 100644 --- a/std/src/sys/random/mod.rs +++ b/std/src/sys/random/mod.rs @@ -57,6 +57,10 @@ cfg_select! { mod motor; pub use motor::fill_bytes; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::fill_bytes; + } all(target_vendor = "fortanix", target_env = "sgx") => { mod sgx; pub use sgx::fill_bytes; diff --git a/std/src/sys/random/pinnacle.rs b/std/src/sys/random/pinnacle.rs new file mode 100644 index 0000000..48c8923 --- /dev/null +++ b/std/src/sys/random/pinnacle.rs @@ -0,0 +1,8 @@ +use crate::sys::pal::{abi, call2}; + +/// Random bytes from the kernel, for keys (`random`, 4 KiB a call). +pub fn fill_bytes(bytes: &mut [u8]) { + for chunk in bytes.chunks_mut(4096) { + call2(abi::call::RANDOM, chunk.as_mut_ptr().addr() as u64, chunk.len() as u64); + } +} diff --git a/std/src/sys/stdio/mod.rs b/std/src/sys/stdio/mod.rs index 86d0f3f..633bc37 100644 --- a/std/src/sys/stdio/mod.rs +++ b/std/src/sys/stdio/mod.rs @@ -37,6 +37,10 @@ cfg_select! { mod vexos; pub use vexos::*; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::*; + } target_os = "xous" => { mod xous; pub use xous::*; diff --git a/std/src/sys/stdio/pinnacle.rs b/std/src/sys/stdio/pinnacle.rs new file mode 100644 index 0000000..68c9156 --- /dev/null +++ b/std/src/sys/stdio/pinnacle.rs @@ -0,0 +1,87 @@ +//! The standard streams: what the program's starter gave it +//! (`pal::start`), or the console (`write`) when it gave nothing; stdin is +//! then empty. + +use crate::io; +use crate::sync::OnceLock; +use crate::sys::pal::channel; +use crate::sys::pal::start::{self, Stream}; +use crate::sys::pal::{abi, call2}; + +/// The channel behind stream `n`, made once. +fn channel(n: usize, handle: u64) -> &'static channel::Stream { + static STREAMS: [OnceLock; 3] = [const { OnceLock::new() }; 3]; + STREAMS[n].get_or_init(|| channel::Stream::new(handle)) +} + +fn write(n: usize, buf: &[u8]) -> io::Result { + match start::stream(n) { + Stream::Console => { + call2(abi::call::WRITE, buf.as_ptr().addr() as u64, buf.len() as u64); + Ok(buf.len()) + } + Stream::Null => Ok(buf.len()), + Stream::Channel(handle) => channel(n, handle).write(buf), + } +} + +pub struct Stdin; +pub struct Stdout; +pub struct Stderr; + +impl Stdin { + pub const fn new() -> Stdin { + Stdin + } +} + +impl io::Read for Stdin { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match start::stream(0) { + Stream::Channel(handle) => channel(0, handle).read(buf), + Stream::Console | Stream::Null => Ok(0), + } + } +} + +impl Stdout { + pub const fn new() -> Stdout { + Stdout + } +} + +impl io::Write for Stdout { + fn write(&mut self, buf: &[u8]) -> io::Result { + write(1, buf) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl Stderr { + pub const fn new() -> Stderr { + Stderr + } +} + +impl io::Write for Stderr { + fn write(&mut self, buf: &[u8]) -> io::Result { + write(2, buf) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +pub const STDIN_BUF_SIZE: usize = crate::sys::io::DEFAULT_BUF_SIZE; + +pub fn is_ebadf(_err: &io::Error) -> bool { + true +} + +pub fn panic_output() -> Option { + Some(Stderr) +} diff --git a/std/src/sys/sync/condvar/mod.rs b/std/src/sys/sync/condvar/mod.rs index 615781e..a31602e 100644 --- a/std/src/sys/sync/condvar/mod.rs +++ b/std/src/sys/sync/condvar/mod.rs @@ -7,6 +7,7 @@ cfg_select! { target_os = "openbsd", target_os = "dragonfly", target_os = "motor", + target_os = "pinnacle", target_os = "fuchsia", all(target_family = "wasm", target_feature = "atomics"), target_os = "hermit", diff --git a/std/src/sys/sync/futex/mod.rs b/std/src/sys/sync/futex/mod.rs index 0edb46c..3c4b6ec 100644 --- a/std/src/sys/sync/futex/mod.rs +++ b/std/src/sys/sync/futex/mod.rs @@ -35,5 +35,9 @@ cfg_select! { target_os = "motor" => { pub use moto_rt::futex::*; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::*; + } _ => {} } diff --git a/std/src/sys/sync/futex/pinnacle.rs b/std/src/sys/sync/futex/pinnacle.rs new file mode 100644 index 0000000..7527c6a --- /dev/null +++ b/std/src/sys/sync/futex/pinnacle.rs @@ -0,0 +1 @@ +pub use crate::sys::pal::futex::*; diff --git a/std/src/sys/sync/mutex/mod.rs b/std/src/sys/sync/mutex/mod.rs index 895ab9c..45b2c06 100644 --- a/std/src/sys/sync/mutex/mod.rs +++ b/std/src/sys/sync/mutex/mod.rs @@ -6,6 +6,7 @@ cfg_select! { target_os = "freebsd", target_os = "openbsd", target_os = "motor", + target_os = "pinnacle", target_os = "dragonfly", all(target_family = "wasm", target_feature = "atomics"), target_os = "hermit", diff --git a/std/src/sys/sync/once/mod.rs b/std/src/sys/sync/once/mod.rs index eee7edf..be5beaa 100644 --- a/std/src/sys/sync/once/mod.rs +++ b/std/src/sys/sync/once/mod.rs @@ -15,6 +15,7 @@ cfg_select! { all(target_family = "wasm", target_feature = "atomics"), target_os = "freebsd", target_os = "motor", + target_os = "pinnacle", target_os = "openbsd", target_os = "dragonfly", target_os = "fuchsia", diff --git a/std/src/sys/sync/rwlock/mod.rs b/std/src/sys/sync/rwlock/mod.rs index 9991f29..62c0906 100644 --- a/std/src/sys/sync/rwlock/mod.rs +++ b/std/src/sys/sync/rwlock/mod.rs @@ -10,6 +10,7 @@ cfg_select! { all(target_family = "wasm", target_feature = "atomics"), target_os = "hermit", target_os = "motor", + target_os = "pinnacle", all(target_os = "wasi", target_env = "p3"), ) => { mod futex; diff --git a/std/src/sys/sync/thread_parking/mod.rs b/std/src/sys/sync/thread_parking/mod.rs index dffa0ad..7d39e25 100644 --- a/std/src/sys/sync/thread_parking/mod.rs +++ b/std/src/sys/sync/thread_parking/mod.rs @@ -9,6 +9,7 @@ cfg_select! { target_os = "dragonfly", target_os = "fuchsia", target_os = "motor", + target_os = "pinnacle", target_os = "hermit", all(target_os = "wasi", target_env = "p3"), ) => { diff --git a/std/src/sys/thread/mod.rs b/std/src/sys/thread/mod.rs index dfbfc2b..461c609 100644 --- a/std/src/sys/thread/mod.rs +++ b/std/src/sys/thread/mod.rs @@ -118,6 +118,14 @@ cfg_select! { set_name_wide, sleep, yield_now, }; } + target_os = "pinnacle" => { + mod pinnacle; + pub use pinnacle::{DEFAULT_MIN_STACK_SIZE, Thread, available_parallelism, sleep, yield_now}; + + #[expect(dead_code)] + mod unsupported; + pub use unsupported::{current_os_id, set_name}; + } target_os = "xous" => { mod xous; pub use xous::{DEFAULT_MIN_STACK_SIZE, Thread, available_parallelism, sleep, yield_now}; diff --git a/std/src/sys/thread/pinnacle.rs b/std/src/sys/thread/pinnacle.rs new file mode 100644 index 0000000..ab765c1 --- /dev/null +++ b/std/src/sys/thread/pinnacle.rs @@ -0,0 +1,137 @@ +//! Threads on Pinnacle: tasks of one program sharing its memory and handles +//! (`thread`), on the core with fewest tasks. Joining waits on a futex the +//! thread sets as it ends. + +use crate::io; +use crate::num::NonZero; +use crate::sync::atomic::{AtomicU32, Ordering}; +use crate::sys::pal::futex::{futex_wait, futex_wake_all}; +use crate::sys::pal::{abi, call, call0, call1, exit_thread}; +use crate::thread::ThreadInit; +use crate::time::Duration; + +pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024; +const PAGE: usize = 4096; + +/// What the thread and whoever holds its `Thread` share: whether it has +/// ended, and how many of the two still hold this. The last frees it. +struct Packet { + done: AtomicU32, + holders: AtomicU32, +} + +impl Packet { + /// Lets go of the packet. + /// + /// # Safety + /// Once per holder; `packet` is not used after. + unsafe fn release(packet: *const Packet) { + // SAFETY: the caller still holds it. + if unsafe { (*packet).holders.fetch_sub(1, Ordering::AcqRel) } == 1 { + // SAFETY: the other holder has let go, and it was boxed in `new`. + drop(unsafe { Box::from_raw(packet as *mut Packet) }); + } + } +} + +pub struct Thread { + packet: *const Packet, +} + +unsafe impl Send for Thread {} +unsafe impl Sync for Thread {} + +/// What the new thread starts from: its packet and the work. +struct Start { + packet: *const Packet, + init: Box, +} + +impl Thread { + // unsafe: see thread::Builder::spawn_unchecked for safety requirements + pub unsafe fn new(stack: usize, init: Box) -> io::Result { + let size = stack.max(DEFAULT_MIN_STACK_SIZE).next_multiple_of(PAGE); + // Its stack is private memory, which the kernel takes back only when + // the program ends: a thread's stack outlives the thread. + let base = call1(abi::call::MAP_MEMORY, size as u64); + if base == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::OutOfMemory, "no memory for a thread's stack")); + } + let packet = Box::into_raw(Box::new(Packet { + done: AtomicU32::new(0), + holders: AtomicU32::new(2), + })); + let start = Box::into_raw(Box::new(Start { packet, init })); + let (id, ..) = call( + abi::call::THREAD, + [thread_start as *const () as u64, base + size as u64, start.addr() as u64, 0, 0, 0, 0], + ); + if id == abi::ERROR { + // SAFETY: the thread never started; both are ours again. + unsafe { + drop(Box::from_raw(start)); + drop(Box::from_raw(packet)); + } + return Err(io::const_error!(io::ErrorKind::Other, "no task slot for a thread")); + } + Ok(Thread { packet }) + } + + pub fn join(self) { + // SAFETY: we hold the packet until `drop`. + let done = unsafe { &(*self.packet).done }; + while done.load(Ordering::Acquire) == 0 { + futex_wait(done, 0, None); + } + } +} + +impl Drop for Thread { + fn drop(&mut self) { + // SAFETY: this holder lets go once. + unsafe { Packet::release(self.packet) }; + } +} + +// Kept out of line so nothing of the work is reordered past the TLS +// teardown that follows it. +#[inline(never)] +fn run(init: Box) { + let rust_start = init.init(); + rust_start(); +} + +extern "C" fn thread_start(start: u64) -> ! { + // SAFETY: `new` leaked this box for us to take back. + let Start { packet, init } = *unsafe { Box::from_raw(start as *mut Start) }; + run(init); + // SAFETY: the thread's work is done; its thread-locals go. + unsafe { crate::sys::thread_local::key::destroy_tls() }; + // SAFETY: we hold the packet until `release`. + let done = unsafe { &(*packet).done }; + done.store(1, Ordering::Release); + futex_wake_all(done); + // SAFETY: this holder lets go once, and touches it no more. + unsafe { Packet::release(packet) }; + exit_thread() +} + +pub fn available_parallelism() -> io::Result> { + let cores = call0(abi::call::INFO); + NonZero::new(cores as usize).ok_or(io::Error::UNKNOWN_THREAD_COUNT) +} + +pub fn yield_now() { + call0(abi::call::YIELD); +} + +pub fn sleep(dur: Duration) { + // The kernel sleeps to the millisecond: round up, never short. + let ms = dur.as_nanos().div_ceil(1_000_000).min(u64::MAX as u128 / 2) as u64; + if ms == 0 { + return; + } + // `time` is whole ms, cut down: one more, or the sleep may end short. + let deadline = call0(abi::call::TIME).saturating_add(ms.saturating_add(1)); + call1(abi::call::SLEEP_UNTIL, deadline); +} diff --git a/std/src/sys/thread_local/key/pinnacle.rs b/std/src/sys/thread_local/key/pinnacle.rs new file mode 100644 index 0000000..87c287c --- /dev/null +++ b/std/src/sys/thread_local/key/pinnacle.rs @@ -0,0 +1,145 @@ +//! Thread-local keys on Pinnacle: each thread's table of values, one word a +//! key, is found through its thread pointer (TPIDR_EL0, which the kernel +//! keeps per thread). A thread makes its table at its first use of a key and +//! frees it as it ends, after running the destructors of what it held. + +use crate::alloc::{GlobalAlloc, Layout, System}; +use crate::mem::ManuallyDrop; +use crate::ptr; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{Atomic, AtomicPtr, AtomicUsize}; + +pub type Key = usize; +pub type Dtor = unsafe extern "C" fn(*mut u8); + +/// Keys a table holds; key 0 is never handed out. +const KEYS: usize = 512; +const TABLE: Layout = match Layout::from_size_align(KEYS * size_of::(), 16) { + Ok(layout) => layout, + Err(_) => panic!("a table's layout"), +}; + +static NEXT_KEY: Atomic = AtomicUsize::new(1); +static DTORS: Atomic<*mut Node> = AtomicPtr::new(ptr::null_mut()); + +#[inline] +fn thread_pointer() -> *mut *mut u8 { + let tp: *mut *mut u8; + // SAFETY: reading TPIDR_EL0 has no side effects. + unsafe { core::arch::asm!("mrs {}, tpidr_el0", out(reg) tp, options(nomem, nostack)) }; + tp +} + +#[inline] +fn table() -> *mut *mut u8 { + let tp = thread_pointer(); + if !tp.is_null() { tp } else { new_table() } +} + +#[cold] +fn new_table() -> *mut *mut u8 { + // The System allocator, which keeps nothing per thread. + // SAFETY: a valid layout. + let tp = unsafe { System.alloc_zeroed(TABLE) } as *mut *mut u8; + if tp.is_null() { + rtabort!("no memory for a thread's thread-locals"); + } + // SAFETY: setting TPIDR_EL0, which is this thread's to set. + unsafe { core::arch::asm!("msr tpidr_el0, {}", in(reg) tp, options(nomem, nostack)) }; + tp +} + +#[inline] +pub fn create(dtor: Option) -> Key { + let key = NEXT_KEY.fetch_add(1, Relaxed); + if key >= KEYS { + rtabort!("out of thread-local keys"); + } + if let Some(f) = dtor { + // SAFETY: a key just made. + unsafe { register_dtor(key, f) }; + } + key +} + +#[inline] +pub unsafe fn set(key: Key, value: *mut u8) { + rtassert!(key >= 1 && key < KEYS); + // SAFETY: the key is within this thread's table. + unsafe { *table().add(key) = value }; +} + +#[inline] +pub unsafe fn get(key: Key) -> *mut u8 { + rtassert!(key >= 1 && key < KEYS); + // SAFETY: as in `set`. + unsafe { *table().add(key) } +} + +#[inline] +pub unsafe fn destroy(_key: Key) { + // Keys are not reused: a program makes few. +} + +struct Node { + dtor: Dtor, + key: Key, + next: *mut Node, +} + +unsafe fn register_dtor(key: Key, dtor: Dtor) { + let mut node = ManuallyDrop::new(Box::new_in(Node { key, dtor, next: ptr::null_mut() }, System)); + let mut head = DTORS.load(Acquire); + loop { + node.next = head; + match DTORS.compare_exchange(head, &mut **node, Release, Acquire) { + Ok(_) => return, + Err(current) => head = current, + } + } +} + +/// Runs the ending thread's destructors and frees its table. +pub unsafe fn destroy_tls() { + let tp = thread_pointer(); + if tp.is_null() { + return; + } + // SAFETY: the thread is ending; nothing else reads its values. + unsafe { run_dtors() }; + // SAFETY: the table came from `new_table`, and is cleared before it goes. + unsafe { + core::arch::asm!("msr tpidr_el0, xzr", options(nomem, nostack)); + System.dealloc(tp as *mut u8, TABLE); + } +} + +// Out of line, so no deallocation is reordered past the table's freeing. +#[inline(never)] +unsafe fn run_dtors() { + // Destructors may set other thread-locals: a few rounds, as Windows does. + let mut any_run = true; + for _ in 0..5 { + if !any_run { + break; + } + any_run = false; + let mut cur = DTORS.load(Acquire); + while !cur.is_null() { + // SAFETY: nodes are never freed. + let (key, dtor, next) = unsafe { ((*cur).key, (*cur).dtor, (*cur).next) }; + // SAFETY: a key this program made. + let value = unsafe { get(key) }; + if !value.is_null() { + // SAFETY: as above; the value is handed to its destructor. + unsafe { + set(key, ptr::null_mut()); + dtor(value); + } + any_run = true; + } + cur = next; + } + } + crate::rt::thread_cleanup(); +} diff --git a/std/src/sys/thread_local/mod.rs b/std/src/sys/thread_local/mod.rs index 1c137e5..b798102 100644 --- a/std/src/sys/thread_local/mod.rs +++ b/std/src/sys/thread_local/mod.rs @@ -134,7 +134,7 @@ pub(crate) mod guard { use crate::rt::thread_cleanup; } } - any(target_os = "hermit", target_os = "xous") => { + any(target_os = "hermit", target_os = "xous", target_os = "pinnacle") => { // `std` is the only runtime, so it just calls the destructor functions // itself when the time comes. pub(crate) fn enable() {} @@ -205,6 +205,14 @@ pub(crate) mod key { pub(super) use xous::{Key, get, set}; use xous::{create, destroy}; } + target_os = "pinnacle" => { + mod racy; + mod pinnacle; + pub(super) use racy::LazyKey; + pub(crate) use pinnacle::destroy_tls; + pub(super) use pinnacle::{Key, get, set}; + use pinnacle::{create, destroy}; + } target_os = "motor" => { mod racy; #[cfg(test)] diff --git a/std/src/sys/time/mod.rs b/std/src/sys/time/mod.rs index 179c968..2eba564 100644 --- a/std/src/sys/time/mod.rs +++ b/std/src/sys/time/mod.rs @@ -32,6 +32,10 @@ cfg_select! { mod windows; use windows as imp; } + target_os = "pinnacle" => { + mod pinnacle; + use pinnacle as imp; + } target_os = "xous" => { mod xous; use xous as imp; diff --git a/std/src/sys/time/pinnacle.rs b/std/src/sys/time/pinnacle.rs new file mode 100644 index 0000000..6f6d9bb --- /dev/null +++ b/std/src/sys/time/pinnacle.rs @@ -0,0 +1,90 @@ +//! Time on Pinnacle. `Instant` is the generic timer's virtual counter, which +//! the kernel lets programs read themselves: no system call. `SystemTime` is +//! the board's clock (`clock`, whole seconds since 1970) carried forward by +//! that counter, so it moves smoothly within a second. + +use crate::sync::atomic::{AtomicU64, Ordering}; +use crate::sys::pal::{abi, call0}; +use crate::time::Duration; + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +pub struct Instant(Duration); + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +pub struct SystemTime(Duration); + +pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0)); + +/// The counter since it started. +fn counter() -> Duration { + let (count, frequency): (u64, u64); + // SAFETY: the kernel opens both registers to programs (CNTKCTL_EL1). + unsafe { + core::arch::asm!( + "isb", + "mrs {c}, cntvct_el0", + "mrs {f}, cntfrq_el0", + c = out(reg) count, + f = out(reg) frequency, + options(nomem, nostack), + ); + } + let frequency = frequency.max(1); + let seconds = count / frequency; + let rest = count % frequency; + Duration::new(seconds, ((rest as u128 * 1_000_000_000) / frequency as u128) as u32) +} + +impl Instant { + pub fn now() -> Instant { + Instant(counter()) + } + + pub fn checked_sub_instant(&self, other: &Instant) -> Option { + self.0.checked_sub(other.0) + } + + pub fn checked_add_duration(&self, other: &Duration) -> Option { + self.0.checked_add(*other).map(Instant) + } + + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + self.0.checked_sub(*other).map(Instant) + } +} + +/// The time of day at counter zero, in ns, once read; 0 until then. +static EPOCH_AT_ZERO: AtomicU64 = AtomicU64::new(0); + +impl SystemTime { + pub const MAX: SystemTime = SystemTime(Duration::MAX); + + pub const MIN: SystemTime = SystemTime(Duration::ZERO); + + pub fn now() -> SystemTime { + let mut at_zero = EPOCH_AT_ZERO.load(Ordering::Relaxed); + if at_zero == 0 { + let clock = call0(abi::call::CLOCK); + if clock == 0 { + // No clock on this board: time since it started. + return SystemTime(counter()); + } + let now = Duration::from_secs(clock); + at_zero = now.saturating_sub(counter()).as_nanos() as u64; + EPOCH_AT_ZERO.store(at_zero, Ordering::Relaxed); + } + SystemTime(Duration::from_nanos(at_zero) + counter()) + } + + pub fn sub_time(&self, other: &SystemTime) -> Result { + self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) + } + + pub fn checked_add_duration(&self, other: &Duration) -> Option { + Some(SystemTime(self.0.checked_add(*other)?)) + } + + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(SystemTime(self.0.checked_sub(*other)?)) + } +} diff --git a/std/src/sys/paths/mod.rs b/std/src/sys/paths/mod.rs index 865d06a..1c949ca 100644 --- a/std/src/sys/paths/mod.rs +++ b/std/src/sys/paths/mod.rs @@ -34,6 +34,18 @@ cfg_select! { }; } } + target_os = "pinnacle" => { + mod pinnacle; + #[expect(dead_code)] + mod unsupported; + mod imp { + pub use super::pinnacle::current_exe; + pub use super::unsupported::{ + JoinPathsError, SplitPaths, SplitPathsRef, chdir, getcwd, home_dir, join_paths, + split_paths, split_paths_ref, temp_dir, + }; + } + } target_os = "uefi" => { mod uefi; use uefi as imp; diff --git a/std/src/sys/paths/pinnacle.rs b/std/src/sys/paths/pinnacle.rs new file mode 100644 index 0000000..75673d4 --- /dev/null +++ b/std/src/sys/paths/pinnacle.rs @@ -0,0 +1,16 @@ +//! Paths on Pinnacle: the program's own file, as the kernel names it (an +//! installed app's `system:/apps//program`); the rest unsupported. + +use crate::io; +use crate::path::PathBuf; +use crate::sys::pal::{abi, call}; + +pub fn current_exe() -> io::Result { + let mut buffer = [0u8; 512]; + let (len, _, _) = call(abi::call::PROGRAM, [buffer.as_mut_ptr() as u64, buffer.len() as u64, 0, 0, 0, 0, 0]); + if len == abi::ERROR { + return Err(io::const_error!(io::ErrorKind::Unsupported, "a program built into the system has no file")); + } + let path = crate::str::from_utf8(&buffer[..len as usize]).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; + Ok(PathBuf::from(path)) +}