Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions crates/kernel/src/fifo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! Named pipes (FIFOs).
//!
//! `mkfifo`/`mknod(S_IFIFO)` creates a FIFO: a *named* pipe that lives in the
//! filesystem namespace but carries real pipe I/O semantics (blocking reads,
//! EAGAIN when empty-but-open, EOF only after all writers close). Unlike an
//! anonymous `pipe()`, a FIFO is looked up by path when opened, so two
//! independent processes (e.g. a shell's process-substitution reader and
//! writer) can rendezvous through it.
//!
//! Modeling: a FIFO is a kernel [`crate::pipe::PipeBuffer`] (marked
//! `is_fifo`) registered here by canonical path. `open()` connects a read or
//! write end to that shared pipe; `unlink()` removes the registration and
//! frees the pipe. The backing pipe persists across all fds closing (a FIFO
//! keeps existing until unlinked), which is why `PipeBuffer::is_fully_closed`
//! ignores FIFO pipes.
//!
//! Without this, `mknod(S_IFIFO)` fell back to creating a *regular file*
//! (see the old `kernel_mknod` path), so a concurrent reader saw an empty
//! file and got a premature EOF — breaking `read < <(cmd)`.

extern crate alloc;

use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::cell::UnsafeCell;

/// Registry mapping a FIFO's canonical path to its backing pipe index.
pub struct FifoTable {
map: BTreeMap<Vec<u8>, usize>,
}

impl FifoTable {
pub const fn new() -> Self {
FifoTable { map: BTreeMap::new() }
}

/// Register `path` as a FIFO backed by pipe `pipe_idx` (replacing any
/// prior entry — mknod(O_EXCL semantics) is enforced by the caller).
pub fn register(&mut self, path: Vec<u8>, pipe_idx: usize) {
self.map.insert(path, pipe_idx);
}

/// Return the backing pipe index for `path`, if it names a FIFO.
pub fn lookup(&self, path: &[u8]) -> Option<usize> {
self.map.get(path).copied()
}

/// Remove the FIFO named `path`, returning its backing pipe index.
pub fn remove(&mut self, path: &[u8]) -> Option<usize> {
self.map.remove(path)
}
}

pub struct GlobalFifoTable(pub UnsafeCell<FifoTable>);

/// SAFETY: access is serialized — the kernel services one syscall at a time
/// (no concurrent Wasm execution).
unsafe impl Sync for GlobalFifoTable {}

pub static FIFO_TABLE: GlobalFifoTable = GlobalFifoTable(UnsafeCell::new(FifoTable::new()));

/// Get a mutable reference to the global FIFO table.
///
/// # Safety
/// Only safe when access is serialized (single-threaded kernel).
pub unsafe fn global_fifo_table() -> &'static mut FifoTable {
unsafe { &mut *FIFO_TABLE.0.get() }
}
1 change: 1 addition & 0 deletions crates/kernel/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod audio;
pub mod devfs;
pub mod dri;
pub mod fd;
pub mod fifo;
pub mod fork;
pub mod ipc;
pub mod lock;
Expand Down
55 changes: 54 additions & 1 deletion crates/kernel/src/pipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ pub struct PipeBuffer {
write_count: u32,
/// Index of this pipe in the PipeTable (for wakeup events).
pipe_idx: u32,
/// True if this pipe backs a named FIFO (see `crate::fifo`). FIFO pipes
/// persist across all fds closing (freed only on unlink), so
/// `is_fully_closed` never frees them.
is_fifo: bool,
/// True once a writer has ever opened this pipe. A FIFO reader must not
/// treat "no writer" as EOF before the first writer connects — otherwise a
/// reader that opens before the writer's worker starts gets a premature
/// EOF. Anonymous pipes always have a writer at creation, so this stays
/// meaningful only for FIFOs.
writer_ever_opened: bool,
/// Ancillary data queue for SCM_RIGHTS FD passing.
/// Each entry is a batch of FDs sent with one sendmsg call.
ancillary_fds: VecDeque<Vec<InFlightFd>>,
Expand All @@ -80,10 +90,33 @@ impl PipeBuffer {
read_count: 1,
write_count: 1,
pipe_idx: 0,
is_fifo: false,
writer_ever_opened: true,
ancillary_fds: VecDeque::new(),
}
}

/// Create a FIFO backing buffer with no endpoints open yet. Endpoints are
/// attached as processes `open()` the FIFO by path (see `crate::fifo`).
pub fn new_fifo(capacity: usize) -> Self {
let mut pipe = Self::new(capacity);
pipe.read_count = 0;
pipe.write_count = 0;
pipe.is_fifo = true;
pipe.writer_ever_opened = false;
pipe
}

/// True if this pipe backs a named FIFO.
pub fn is_fifo(&self) -> bool {
self.is_fifo
}

/// True once a writer has ever opened this pipe.
pub fn writer_ever_opened(&self) -> bool {
self.writer_ever_opened
}

/// Total capacity of the buffer.
pub fn capacity(&self) -> usize {
self.buf.len()
Expand Down Expand Up @@ -197,6 +230,7 @@ impl PipeBuffer {
/// Add a writer reference (e.g., after fork or dup).
pub fn add_writer(&mut self) {
self.write_count += 1;
self.writer_ever_opened = true;
}

/// Returns true if the read end is still open (any readers remain).
Expand All @@ -210,8 +244,13 @@ impl PipeBuffer {
}

/// Returns true if both endpoints are closed and the pipe can be freed.
///
/// FIFO-backing pipes are exempt: a FIFO persists in the filesystem
/// namespace until unlinked, even when no fds are currently open, so a
/// later `open()` reconnects to the same buffer. FIFO pipes are freed
/// explicitly via [`PipeTable::free_fifo`] on unlink.
pub fn is_fully_closed(&self) -> bool {
self.read_count == 0 && self.write_count == 0
self.read_count == 0 && self.write_count == 0 && !self.is_fifo
}

/// Push ancillary FDs (SCM_RIGHTS) to be delivered with the next recvmsg.
Expand Down Expand Up @@ -317,6 +356,20 @@ impl PipeTable {
}
}

/// Free a FIFO-backing pipe slot on unlink, but only once no endpoints
/// remain open (POSIX: unlinking a FIFO removes the name; open fds keep
/// working until closed). Clears the FIFO exemption so a subsequent close
/// frees it via `free_if_closed`; frees immediately if already idle.
pub fn free_fifo(&mut self, idx: usize) {
if let Some(Some(pipe)) = self.pipes.get_mut(idx) {
pipe.is_fifo = false;
if pipe.is_fully_closed() {
self.pipes[idx] = None;
self.free_list.push(idx);
}
}
}

/// Total number of slots (including freed).
pub fn len(&self) -> usize {
self.pipes.len()
Expand Down
Loading
Loading