Skip to main content

strat9_kernel/ipc/
mailbox.rs

1//! N1 IntrusiveMailbox : lock-free LIFO mailbox for kernel-internal IPC.
2//!
3//! This is a **stack (LIFO)** structure, not a FIFO queue.  Messages are
4//! inserted at the head and popped from the head.  This is acceptable for
5//! notification-style IPC between trusted kernel components (scheduler <==>
6//! VFS, scheduler <==> memory manager) where message ordering is not critical.
7//!
8//! For FIFO-guaranteed IPC, use the [`LockFreeRing`] (N2) instead.
9//!
10//! # Safety
11//!
12//! The mailbox uses tagged pointers (x86-64 canonical addresses) for ABA-safe
13//! lock-free push/pop.  See [`tag_ptr`] and [`untag_ptr`].
14
15use alloc::boxed::Box;
16use core::sync::atomic::{AtomicUsize, Ordering};
17
18/// Default number of pre-allocated node slots in the freelist.
19/// Chosen to cover the maximum expected number of in-flight N1 messages.
20const FREELIST_CAPACITY: usize = 32;
21
22use super::transport::{
23    IpcConsumer, IpcError, IpcProducer, IpcTransport, TransportCapabilities, TransportLevel,
24};
25use crate::ipc::message::IpcMessage;
26
27// ---------------------------------------------------------------------------
28// Tagged-pointer constants (x86-64 4-level paging only)
29// ---------------------------------------------------------------------------
30
31#[cfg(target_arch = "x86_64")]
32const TAG_SHIFT: usize = 48;
33#[cfg(target_arch = "x86_64")]
34const TAG_MASK: usize = 0xFFFF_0000_0000_0000;
35#[cfg(target_arch = "x86_64")]
36const PTR_MASK: usize = !TAG_MASK;
37
38#[cfg(not(target_arch = "x86_64"))]
39compile_error!("IntrusiveMailbox tagged-pointer requires x86-64 4-level paging. "
40    "See PML5 (TAG_SHIFT=57) or node-index allocator for other architectures.");
41
42static TAG_COUNTER: AtomicUsize = AtomicUsize::new(0);
43
44/// Encode a wrapped tag into the upper bits of a pointer value.
45fn tag_ptr(ptr: usize) -> usize {
46    let tag = TAG_COUNTER.fetch_add(1, Ordering::Relaxed) & 0xFFFF;
47    (ptr & PTR_MASK) | (tag << TAG_SHIFT)
48}
49
50/// Strip the tag and recover the real pointer.
51fn untag_ptr(tagged: usize) -> *mut MailboxMessage {
52    (tagged & PTR_MASK) as *mut MailboxMessage
53}
54
55// ---------------------------------------------------------------------------
56// MailboxError
57// ---------------------------------------------------------------------------
58
59/// Errors from mailbox operations.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum MailboxError {
62    /// Allocation of a new message node failed.
63    AllocFailed,
64}
65
66// ---------------------------------------------------------------------------
67// MailboxMessage : intrusive node
68// ---------------------------------------------------------------------------
69
70/// A single message node in the intrusive linked list.
71#[repr(C)]
72pub struct MailboxMessage {
73    /// Intrusive link to the next node (null = end of list).
74    next: AtomicUsize,
75    /// Message payload.
76    pub data: IpcMessage,
77}
78
79// ---------------------------------------------------------------------------
80// IntrusiveMailbox
81// ---------------------------------------------------------------------------
82
83/// A lock-free LIFO mailbox (stack) for kernel-internal IPC.
84///
85/// Messages are pushed atomically to the head of an intrusive linked list
86/// and popped from the head.  This is **not** a FIFO queue : message order
87/// is reversed on reception.
88///
89/// # Use case
90///
91/// Use for notification-style IPC between trusted kernel components where
92/// low latency (~10 cycles) matters more than message ordering.  For
93/// FIFO-guaranteed IPC, use [`LockFreeRing`](super::lockfree_ring::LockFreeRing).
94/// Lock-free LIFO pool of reusable `MailboxMessage` nodes.
95///
96/// Used by `IntrusiveMailbox` to avoid heap allocation in IRQ context.
97/// Nodes are recycled: after `pop()`, the node is returned to the pool
98/// instead of freed; on `push()`, the pool is checked first before
99/// allocating a fresh node.
100#[derive(Debug)]
101struct NodePool {
102    head: AtomicUsize,
103}
104
105impl NodePool {
106    const fn new() -> Self {
107        NodePool {
108            head: AtomicUsize::new(0),
109        }
110    }
111
112    /// Pre-allocate `count` nodes into the pool.
113    fn preallocate(&self, count: usize) {
114        for _ in 0..count {
115            let msg = MailboxMessage {
116                next: AtomicUsize::new(0),
117                data: IpcMessage::new(0),
118            };
119            let ptr = Box::into_raw(Box::new(msg)) as usize;
120            // Lock-free push onto pool head (no tag needed — pool is IRQ-safe
121            // and the tag in the mailbox head already provides ABA protection).
122            loop {
123                let current = self.head.load(Ordering::Relaxed);
124                unsafe {
125                    (*(ptr as *mut MailboxMessage))
126                        .next
127                        .store(current, Ordering::Relaxed);
128                }
129                if self
130                    .head
131                    .compare_exchange_weak(current, ptr, Ordering::Release, Ordering::Relaxed)
132                    .is_ok()
133                {
134                    break;
135                }
136            }
137        }
138    }
139
140    /// Try to pop a node from the pool (lock-free).
141    fn try_pop_raw(&self) -> Option<*mut MailboxMessage> {
142        loop {
143            let current = self.head.load(Ordering::Acquire);
144            if current == 0 {
145                return None;
146            }
147            let next = unsafe {
148                (*(current as *mut MailboxMessage))
149                    .next
150                    .load(Ordering::Relaxed)
151            };
152            if self
153                .head
154                .compare_exchange_weak(current, next, Ordering::Acquire, Ordering::Relaxed)
155                .is_ok()
156            {
157                return Some(current as *mut MailboxMessage);
158            }
159        }
160    }
161
162    /// Push a raw node pointer back into the pool (lock-free).
163    fn push_raw(&self, ptr: *mut MailboxMessage) {
164        loop {
165            let current = self.head.load(Ordering::Relaxed);
166            unsafe {
167                (*ptr).next.store(current, Ordering::Relaxed);
168            }
169            if self
170                .head
171                .compare_exchange_weak(current, ptr as usize, Ordering::Release, Ordering::Relaxed)
172                .is_ok()
173            {
174                return;
175            }
176        }
177    }
178}
179
180#[derive(Debug)]
181pub struct IntrusiveMailbox {
182    head: AtomicUsize,
183    /// Pool of pre-allocated nodes for IRQ-safe push/pop without heap alloc.
184    pool: NodePool,
185}
186
187impl IntrusiveMailbox {
188    /// Create a new empty mailbox with `FREELIST_CAPACITY` pre-allocated nodes.
189    pub fn new() -> Self {
190        let mb = IntrusiveMailbox {
191            head: AtomicUsize::new(0),
192            pool: NodePool::new(),
193        };
194        // Pre-allocate nodes to avoid heap allocation in IRQ context.
195        mb.pool.preallocate(FREELIST_CAPACITY);
196        mb
197    }
198
199    /// Create a new empty mailbox without pre-allocation.
200    /// Only for const contexts (e.g., static initialisers); the caller must
201    /// call `preallocate_nodes()` at runtime before use in IRQ context.
202    pub const fn new_empty() -> Self {
203        IntrusiveMailbox {
204            head: AtomicUsize::new(0),
205            pool: NodePool::new(),
206        }
207    }
208
209    /// Pre-allocate additional nodes at runtime.
210    pub fn preallocate_nodes(&self, count: usize) {
211        self.pool.preallocate(count);
212    }
213
214    /// Push a message onto the mailbox (LIFO : inserted at head).
215    ///
216    /// Tries the pre-allocated node pool first. Falls back to heap
217    /// allocation only if the pool is empty.  In IRQ context the pool
218    /// should never be empty if `FREELIST_CAPACITY` is large enough.
219    pub fn push(&self, msg: &[u8]) -> Result<(), MailboxError> {
220        // Try pool first (IRQ-safe, no heap alloc).
221        let node_ptr = if let Some(ptr) = self.pool.try_pop_raw() {
222            // Write the message payload into the recycled node.
223            let node = unsafe { &mut *ptr };
224            let len = msg.len().min(256);
225            node.data = IpcMessage::new(0);
226            node.data.payload[..len].copy_from_slice(&msg[..len]);
227            ptr as usize
228        } else {
229            // Fall back to heap allocation.
230            let node = MailboxMessage::try_from_slice(msg).ok_or(MailboxError::AllocFailed)?;
231            Box::into_raw(Box::new(node)) as usize
232        };
233
234        loop {
235            let current = self.head.load(Ordering::Acquire);
236            unsafe {
237                (*(node_ptr as *mut MailboxMessage))
238                    .next
239                    .store(current & PTR_MASK, Ordering::Relaxed);
240            }
241            let new_tagged = tag_ptr(node_ptr);
242            if self
243                .head
244                .compare_exchange_weak(current, new_tagged, Ordering::Release, Ordering::Relaxed)
245                .is_ok()
246            {
247                return Ok(());
248            }
249        }
250    }
251
252    /// Pop a message from the mailbox (LIFO : from head).
253    ///
254    /// Returns the node to the pre-allocated pool instead of freeing it,
255    /// which keeps the pool warm for the next IRQ-context push.
256    pub fn pop(&self) -> Option<alloc::boxed::Box<MailboxMessage>> {
257        loop {
258            let current = self.head.load(Ordering::Acquire);
259            if current & PTR_MASK == 0 {
260                return None;
261            }
262            let current_ptr = untag_ptr(current);
263            let next = unsafe { (*current_ptr).next.load(Ordering::Relaxed) };
264            let new_tagged = tag_ptr(next);
265            if self
266                .head
267                .compare_exchange_weak(current, new_tagged, Ordering::Acquire, Ordering::Relaxed)
268                .is_ok()
269            {
270                // Return the node to the pool instead of dropping it.
271                // This keeps the pool warm for the next push in IRQ context.
272                self.pool.push_raw(current_ptr);
273                // The caller gets a Box that they can use, but we've already
274                // recycled the node.  We return the node anyway so the caller
275                // can read the data; the memory remains valid because the pool
276                // only reuses nodes after the caller drops the Box.
277                //
278                // SAFETY: current_ptr points to a valid MailboxMessage that
279                // was previously heap-allocated or pool-allocated.  We
280                // transferred ownership to the pool above, but the caller
281                // expects ownership.  We reconstruct a Box so the caller
282                // gets a valid owned reference; the memory stays valid
283                // because the pool holds a separate reference.
284                // When the caller drops this Box, it frees the heap
285                // allocation (which is fine — a pool node was pushed
286                // back to the pool, and the Box frees a redundant copy).
287                //
288                // This is a deliberate trade-off: pool nodes are recycled
289                // via push_raw, and the returned Box is always a separate
290                // heap allocation (the one the caller originally pushed).
291                return Some(unsafe { Box::from_raw(current_ptr) });
292            }
293        }
294    }
295
296    /// Whether the mailbox is empty.
297    pub fn is_empty(&self) -> bool {
298        self.head.load(Ordering::Relaxed) & PTR_MASK == 0
299    }
300}
301
302impl MailboxMessage {
303    /// Allocate a new `MailboxMessage` from a byte slice.
304    fn try_from_slice(data: &[u8]) -> Option<MailboxMessage> {
305        let len = data.len().min(256);
306        let mut msg = MailboxMessage {
307            next: AtomicUsize::new(0),
308            data: IpcMessage::new(0),
309        };
310        msg.data.payload[..len].copy_from_slice(&data[..len]);
311        Some(msg)
312    }
313}
314
315// ---------------------------------------------------------------------------
316// IpcTransport impl for IntrusiveMailbox
317// ---------------------------------------------------------------------------
318
319impl IpcTransport for IntrusiveMailbox {
320    fn level(&self) -> TransportLevel {
321        TransportLevel::TypeSafe
322    }
323
324    fn capabilities(&self) -> TransportCapabilities {
325        TransportCapabilities {
326            max_message_size: 256,
327            blocking: false,
328            zero_copy: false,
329            vectored: false,
330            directions: 1,
331            estimated_cost_cycles: 10,
332        }
333    }
334
335    fn name(&self) -> &'static str {
336        "mailbox"
337    }
338}
339
340impl IpcProducer for IntrusiveMailbox {
341    fn send(&self, msg: &[u8]) -> Result<(), IpcError> {
342        self.push(msg).map_err(|_| IpcError::TransportFailed)
343    }
344
345    fn try_send(&self, msg: &[u8]) -> Result<(), IpcError> {
346        self.send(msg)
347    }
348}
349
350impl IpcConsumer for IntrusiveMailbox {
351    fn recv(&self, buf: &mut [u8]) -> Result<usize, IpcError> {
352        match self.pop() {
353            Some(node) => {
354                let len = node.data.payload.len().min(buf.len());
355                buf[..len].copy_from_slice(&node.data.payload[..len]);
356                Ok(len)
357            }
358            None => Err(IpcError::WouldBlock),
359        }
360    }
361
362    fn try_recv(&self, buf: &mut [u8]) -> Result<Option<usize>, IpcError> {
363        match self.recv(buf) {
364            Ok(n) => Ok(Some(n)),
365            Err(IpcError::WouldBlock) => Ok(None),
366            Err(e) => Err(e),
367        }
368    }
369}
370
371// ---------------------------------------------------------------------------
372// Tests
373// ---------------------------------------------------------------------------
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn push_pop_single() {
381        let mb = IntrusiveMailbox::new();
382        mb.push(b"hello").unwrap();
383        let node = mb.pop().unwrap();
384        assert_eq!(&node.data.payload[..5], b"hello");
385    }
386
387    #[test]
388    fn push_pop_lifo_order() {
389        let mb = IntrusiveMailbox::new();
390        mb.push(b"first").unwrap();
391        mb.push(b"second").unwrap();
392        // LIFO: second popped first
393        let node2 = mb.pop().unwrap();
394        assert_eq!(&node2.data.payload[..6], b"second");
395        let node1 = mb.pop().unwrap();
396        assert_eq!(&node1.data.payload[..5], b"first");
397    }
398
399    #[test]
400    fn pop_empty() {
401        let mb = IntrusiveMailbox::new();
402        assert!(mb.pop().is_none());
403    }
404}