Skip to main content

strat9_kernel/ipc/
port.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! IPC Port : a kernel-managed message queue with blocking send/recv.
24//!
25//! Each port has a bounded FIFO queue of `IpcMessage`s. Senders block if
26//! the queue is full; receivers block if it's empty. The scheduler's
27//! block/wake API (via `WaitQueue`) provides the blocking mechanism.
28
29use super::message::IpcMessage;
30use crate::{
31    process::TaskId,
32    sync::{SpinLock, WaitQueue},
33};
34use alloc::{collections::BTreeMap, sync::Arc};
35use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
36use crossbeam_queue::ArrayQueue;
37
38/// Maximum number of messages buffered in a single port.
39const PORT_QUEUE_CAPACITY: usize = 16;
40
41/// Unique identifier for an IPC port.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
43pub struct PortId(pub u64);
44
45impl PortId {
46    /// Get the raw u64 value.
47    pub fn as_u64(self) -> u64 {
48        self.0
49    }
50
51    /// Create a PortId from a raw u64.
52    pub fn from_u64(raw: u64) -> Self {
53        PortId(raw)
54    }
55}
56
57impl core::fmt::Display for PortId {
58    /// Performs the fmt operation.
59    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
60        write!(f, "{}", self.0)
61    }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
65pub enum IpcError {
66    #[error("port not found")]
67    PortNotFound,
68    #[error("not owner of port")]
69    NotOwner,
70    #[error("port destroyed")]
71    PortDestroyed,
72    #[error("port queue full")]
73    WouldBlock,
74    #[error("operation timed out")]
75    TimedOut,
76    #[error("interrupted by signal")]
77    Interrupted,
78}
79
80/// An IPC port: a bounded message queue with blocking semantics.
81pub struct Port {
82    /// Unique port identifier.
83    pub id: PortId,
84    /// TaskId of the port's creator/owner.
85    pub owner: TaskId,
86    /// The message queue (bounded to `PORT_QUEUE_CAPACITY`).
87    queue: ArrayQueue<IpcMessage>,
88    /// Set to true when the port is destroyed; blocked tasks wake with error.
89    destroyed: AtomicBool,
90    /// Tasks blocked because the queue is full (waiting to send).
91    send_waitq: WaitQueue,
92    /// Tasks blocked because the queue is empty (waiting to receive).
93    recv_waitq: WaitQueue,
94}
95
96impl Port {
97    /// Create a new port owned by the given task.
98    fn new(id: PortId, owner: TaskId) -> Self {
99        Port {
100            id,
101            owner,
102            queue: ArrayQueue::new(PORT_QUEUE_CAPACITY),
103            destroyed: AtomicBool::new(false),
104            send_waitq: WaitQueue::new(),
105            recv_waitq: WaitQueue::new(),
106        }
107    }
108
109    /// Send a message to this port.
110    ///
111    /// If the queue is full, the calling task blocks until space is available.
112    /// Returns `Err(IpcError::PortDestroyed)` if the port is destroyed while
113    /// the sender is blocked.
114    pub fn send(&self, msg: IpcMessage) -> Result<(), IpcError> {
115        self.send_deadline(msg, None)
116    }
117
118    /// Send a message, giving up at `deadline_ns` on the scheduler clock.
119    ///
120    /// `None` waits forever. On expiry the caller is removed from the wait
121    /// queue (the deadline mechanism wakes it, then `wait_until_deadline`
122    /// unregisters it) and [`IpcError::TimedOut`] is returned, so a missing
123    /// receiver cannot block a sender forever.
124    pub fn send_deadline(&self, msg: IpcMessage, deadline_ns: Option<u64>) -> Result<(), IpcError> {
125        let result = self.send_waitq.wait_until_deadline(deadline_ns, || {
126            // P2 fix: check for pending signals to avoid livelock.
127            if crate::process::signal::has_pending_signals() {
128                return Some(Err(IpcError::Interrupted));
129            }
130            if self.destroyed.load(Ordering::Acquire) {
131                return Some(Err(IpcError::PortDestroyed));
132            }
133            match self.queue.push(msg) {
134                Ok(()) => Some(Ok(())),
135                Err(_) => None,
136            }
137        });
138        let result = result.unwrap_or(Err(IpcError::TimedOut));
139        if result.is_ok() {
140            self.recv_waitq.wake_one();
141        }
142        result
143    }
144
145    /// Receive a message from this port.
146    ///
147    /// If the queue is empty, the calling task blocks until a message arrives.
148    /// Returns `Err(IpcError::PortDestroyed)` if the port is destroyed while
149    /// the receiver is blocked.
150    pub fn recv(&self) -> Result<IpcMessage, IpcError> {
151        self.recv_deadline(None)
152    }
153
154    /// Receive a message, giving up at `deadline_ns` on the scheduler clock.
155    ///
156    /// `None` waits forever. On expiry the caller is unregistered and
157    /// [`IpcError::TimedOut`] is returned; a message that arrived at the
158    /// same instant is still preferred (the condition is re-checked once
159    /// after the deadline).
160    pub fn recv_deadline(&self, deadline_ns: Option<u64>) -> Result<IpcMessage, IpcError> {
161        let result = self.recv_waitq.wait_until_deadline(deadline_ns, || {
162            if let Some(msg) = self.queue.pop() {
163                return Some(Ok(msg));
164            }
165            // P2 fix: check for pending signals to avoid livelock.
166            if crate::process::signal::has_pending_signals() {
167                return Some(Err(IpcError::Interrupted));
168            }
169            if self.destroyed.load(Ordering::Acquire) {
170                return Some(Err(IpcError::PortDestroyed));
171            }
172            None
173        });
174        let result = result.unwrap_or(Err(IpcError::TimedOut));
175        if result.is_ok() {
176            self.send_waitq.wake_one();
177        }
178        result
179    }
180
181    /// Try to send a message to this port without blocking.
182    ///
183    /// Returns `Ok(())` if the message was queued,
184    /// or `Err(WouldBlock)` if the queue is full.
185    pub fn try_send(&self, msg: IpcMessage) -> Result<(), IpcError> {
186        match self.queue.push(msg) {
187            Ok(()) => {
188                self.recv_waitq.wake_one();
189                Ok(())
190            }
191            Err(_) => Err(IpcError::WouldBlock),
192        }
193    }
194
195    /// Try to receive a message from this port without blocking.
196    ///
197    /// Returns `Ok(Some(msg))` if a message was available, `Ok(None)` if empty,
198    /// or `Err(IpcError::PortDestroyed)` if the port is destroyed.
199    pub fn try_recv(&self) -> Result<Option<IpcMessage>, IpcError> {
200        if let Some(msg) = self.queue.pop() {
201            self.send_waitq.wake_one();
202            return Ok(Some(msg));
203        }
204        if self.destroyed.load(Ordering::Acquire) {
205            return Err(IpcError::PortDestroyed);
206        }
207        Ok(None)
208    }
209
210    /// Mark the port as destroyed and wake all blocked tasks.
211    fn destroy(&self) {
212        self.destroyed.store(true, Ordering::Release);
213        self.send_waitq.wake_all();
214        self.recv_waitq.wake_all();
215    }
216
217    /// Returns whether messages is available.
218    pub fn has_messages(&self) -> bool {
219        !self.queue.is_empty()
220    }
221
222    /// Returns whether this can send.
223    pub fn can_send(&self) -> bool {
224        !self.destroyed.load(Ordering::Acquire) && !self.queue.is_full()
225    }
226
227    /// Returns whether destroyed.
228    pub fn is_destroyed(&self) -> bool {
229        self.destroyed.load(Ordering::Acquire)
230    }
231}
232
233// ===========================================================================
234// Global port registry
235// ===========================================================================
236
237/// Next port ID to assign.
238static NEXT_PORT_ID: AtomicU64 = AtomicU64::new(1);
239
240/// Global registry of all live ports.
241static PORTS: SpinLock<Option<BTreeMap<PortId, Arc<Port>>>> = SpinLock::new(None);
242
243/// Ensure the registry is initialized (called lazily).
244fn ensure_registry(guard: &mut Option<BTreeMap<PortId, Arc<Port>>>) {
245    if guard.is_none() {
246        *guard = Some(BTreeMap::new());
247    }
248}
249
250/// Create a new port owned by `owner`. Returns the new port's ID.
251pub fn create_port(owner: TaskId) -> PortId {
252    let id = PortId(NEXT_PORT_ID.fetch_add(1, Ordering::Relaxed));
253    let port = Arc::new(Port::new(id, owner));
254
255    let mut registry = PORTS.lock();
256    ensure_registry(&mut *registry);
257    registry.as_mut().unwrap().insert(id, port);
258
259    log::debug!("IPC: created port {} (owner={})", id, owner);
260    id
261}
262
263/// Look up a port by ID. Returns a cloned `Arc<Port>` if found.
264pub fn get_port(id: PortId) -> Option<Arc<Port>> {
265    let registry = PORTS.lock();
266    registry.as_ref().and_then(|map| map.get(&id).cloned())
267}
268
269/// Destroy a port, removing it from the registry and waking all waiters.
270///
271/// Returns `Ok(())` if destroyed, `Err` if not found or not owned by caller.
272pub fn destroy_port(id: PortId, caller: TaskId) -> Result<(), IpcError> {
273    let port = {
274        let mut registry = PORTS.lock();
275        let map = registry.as_mut().ok_or(IpcError::PortNotFound)?;
276        let port = map.get(&id).ok_or(IpcError::PortNotFound)?;
277        if port.owner != caller {
278            return Err(IpcError::NotOwner);
279        }
280        let port = port.clone();
281        map.remove(&id);
282        port
283    };
284
285    port.destroy();
286    log::debug!("IPC: destroyed port {} (by task {})", id, caller);
287    Ok(())
288}
289
290/// Clean up all ports owned by a dying task.
291///
292/// For each port: drain queued messages and deliver error replies to any
293/// callers blocked in `wait_for_reply`, then destroy the port.
294///
295/// NOTE: Only covers messages still in the queue. If the owner already
296/// recv'd a message but died before calling reply(), the caller task
297/// remains stuck. Servers should handle their own graceful shutdown.
298pub fn cleanup_ports_for_task(owner: TaskId) {
299    super::reply::cancel_replies_waiting_on(owner);
300
301    let owned: alloc::vec::Vec<Arc<Port>> = {
302        let mut registry = PORTS.lock();
303        let Some(map) = registry.as_mut() else { return };
304        let ids: alloc::vec::Vec<PortId> = map
305            .iter()
306            .filter(|(_, p)| p.owner == owner)
307            .map(|(id, _)| *id)
308            .collect();
309        let mut ports = alloc::vec::Vec::with_capacity(ids.len());
310        for id in ids {
311            if let Some(p) = map.remove(&id) {
312                ports.push(p);
313            }
314        }
315        ports
316    };
317
318    for port in owned {
319        port.destroy();
320        while let Some(msg) = port.queue.pop() {
321            let sender = TaskId::from_u64(msg.sender);
322            if sender == owner {
323                continue;
324            }
325            let mut err_reply = IpcMessage::new(0x80);
326            let epipe: u32 = 32;
327            err_reply.payload[0..4].copy_from_slice(&epipe.to_le_bytes());
328            // The dead owner is the awaited responder: authorization passes.
329            let _ = super::reply::deliver_reply(owner, sender, err_reply);
330        }
331    }
332}