Skip to main content

strat9_kernel/ipc/
shared_ring.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
23use crate::{
24    capability::CapId,
25    memory::{
26        allocate_mapping_cap_id, ownership_table, release_owned_block, resolve_handle,
27        revoke_mapping_cap_id, unregister_mapping_identity, OwnerError, PhysFrame,
28    },
29    sync::SpinLock,
30};
31use alloc::{collections::BTreeMap, sync::Arc, vec::Vec};
32use core::sync::atomic::{AtomicU64, Ordering};
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct RingId(pub u64);
36
37impl RingId {
38    /// Returns this as u64.
39    pub fn as_u64(self) -> u64 {
40        self.0
41    }
42    /// Builds this from u64.
43    pub fn from_u64(raw: u64) -> Self {
44        Self(raw)
45    }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
49pub enum RingError {
50    #[error("invalid size")]
51    InvalidSize,
52    #[error("allocation failed")]
53    Alloc,
54    #[error("ring not found")]
55    NotFound,
56}
57
58pub struct SharedRing {
59    size: usize,
60    frames: Vec<PhysFrame>,
61    owner_cap_ids: Vec<CapId>,
62    mapping_cap_ids: Vec<CapId>,
63}
64
65impl SharedRing {
66    /// Performs the size operation.
67    pub fn size(&self) -> usize {
68        self.size
69    }
70
71    /// Performs the page count operation.
72    pub fn page_count(&self) -> usize {
73        self.frames.len()
74    }
75
76    /// Performs the frame phys addrs operation.
77    pub fn frame_phys_addrs(&self) -> Vec<u64> {
78        self.frames
79            .iter()
80            .map(|f| f.start_address.as_u64())
81            .collect()
82    }
83
84    /// Returns stable mapping identities for every page in the ring.
85    pub fn mapping_cap_ids(&self) -> &[CapId] {
86        &self.mapping_cap_ids
87    }
88}
89
90impl Drop for SharedRing {
91    /// Performs the drop operation.
92    fn drop(&mut self) {
93        for (frame, owner_cap_id) in self.frames.drain(..).zip(self.owner_cap_ids.drain(..)) {
94            let handle = resolve_handle(frame.start_address);
95            if let Some(block) = unregister_mapping_identity(handle, owner_cap_id) {
96                release_owned_block(block);
97            }
98        }
99    }
100}
101
102fn rollback_ring_frames(frames: Vec<PhysFrame>, owner_cap_ids: &[CapId], registered: usize) {
103    for (frame, owner_cap_id) in frames
104        .iter()
105        .copied()
106        .zip(owner_cap_ids.iter().copied())
107        .take(registered)
108    {
109        let handle = resolve_handle(frame.start_address);
110        if let Some(block) = unregister_mapping_identity(handle, owner_cap_id) {
111            release_owned_block(block);
112        }
113    }
114
115    for frame in frames.into_iter().skip(registered) {
116        crate::sync::with_irqs_disabled(|token| crate::memory::free_frame(token, frame));
117    }
118}
119
120static NEXT_RING_ID: AtomicU64 = AtomicU64::new(1);
121static RINGS: SpinLock<Option<BTreeMap<RingId, Arc<SharedRing>>>> = SpinLock::new(None);
122
123/// Performs the ensure registry operation.
124fn ensure_registry(guard: &mut Option<BTreeMap<RingId, Arc<SharedRing>>>) {
125    if guard.is_none() {
126        *guard = Some(BTreeMap::new());
127    }
128}
129
130/// Creates ring.
131pub fn create_ring(size: usize) -> Result<RingId, RingError> {
132    let ring = Arc::new(allocate_ring(size)?);
133    let id = RingId(NEXT_RING_ID.fetch_add(1, Ordering::Relaxed));
134    let mut reg = RINGS.lock();
135    ensure_registry(&mut *reg);
136    reg.as_mut().unwrap().insert(id, ring);
137    Ok(id)
138}
139
140/// Allocate zeroed, ownership-registered frames without publishing them in
141/// the global ring registry. Used by IPC v2 memory objects, whose lifetime
142/// is held by handles and mappings rather than by a global id.
143///
144/// The frames stay alive while the returned object (its owner references)
145/// or any mapping (its own per-mapping references) exists.
146pub fn allocate_ring(size: usize) -> Result<SharedRing, RingError> {
147    if size == 0 {
148        return Err(RingError::InvalidSize);
149    }
150    let page_count = (size.saturating_add(4095)) / 4096;
151    if page_count == 0 {
152        return Err(RingError::InvalidSize);
153    }
154
155    let mut frames = Vec::with_capacity(page_count);
156    let mut alloc_failed = false;
157    for _ in 0..page_count {
158        let frame =
159            match crate::sync::with_irqs_disabled(|token| crate::memory::allocate_frame(token)) {
160                Ok(f) => f,
161                Err(_) => {
162                    alloc_failed = true;
163                    break;
164                }
165            };
166        let v = crate::memory::phys_to_virt(frame.start_address.as_u64());
167        unsafe { core::ptr::write_bytes(v as *mut u8, 0, 4096) };
168        frames.push(frame);
169    }
170    if alloc_failed {
171        for rollback in frames.drain(..) {
172            crate::sync::with_irqs_disabled(|token| crate::memory::free_frame(token, rollback));
173        }
174        return Err(RingError::Alloc);
175    }
176
177    let owner_cap_ids = (0..page_count)
178        .map(|_| allocate_mapping_cap_id())
179        .collect::<Vec<_>>();
180    let mapping_cap_ids = (0..page_count).map(|_| allocate_mapping_cap_id()).collect();
181
182    let mut registered = 0usize;
183    for (frame, owner_cap_id) in frames.iter().zip(owner_cap_ids.iter().copied()) {
184        let handle = resolve_handle(frame.start_address);
185        match ownership_table().ensure_ref(handle, owner_cap_id) {
186            Ok(_) | Err(OwnerError::CapAlreadyPresent) => {
187                registered += 1;
188            }
189            Err(error) => {
190                log::warn!(
191                    "ipc: failed to register shared ring owner cap={} block={:#x}/{}: {:?}",
192                    owner_cap_id.as_u64(),
193                    handle.base.as_u64(),
194                    handle.order,
195                    error
196                );
197                rollback_ring_frames(frames, &owner_cap_ids, registered);
198                return Err(RingError::Alloc);
199            }
200        }
201    }
202
203    Ok(SharedRing {
204        size,
205        frames,
206        owner_cap_ids,
207        mapping_cap_ids,
208    })
209}
210
211/// Returns ring.
212pub fn get_ring(id: RingId) -> Option<Arc<SharedRing>> {
213    let reg = RINGS.lock();
214    reg.as_ref().and_then(|map| map.get(&id).cloned())
215}
216
217/// Destroys ring.
218pub fn destroy_ring(id: RingId) -> Result<(), RingError> {
219    let mut reg = RINGS.lock();
220    let map = reg.as_mut().ok_or(RingError::NotFound)?;
221
222    // ==========================================================================
223    // CRITICAL: BTreeMap corruption guard
224    //
225    // A corrupted heap can produce a BTreeMap whose internal node pointers are
226    // invalid (e.g. NULL + offset 16 = 0x10), causing remove() to page-fault.
227    // Sanity-check `len()` before mutating: the ring registry never holds more
228    // than a few hundred entries under normal operation.  An absurd value
229    // indicates that the BTreeMap header itself has been overwritten, and
230    // calling remove() would immediately dereference a bad node pointer.
231    //
232    // In that case we bail early rather than crash.  The heap poison detector
233    // in heap.rs will identify the corrupting allocation on the next alloc/free.
234    // ==========================================================================
235    let len = map.len();
236    if len > 10_000 {
237        crate::serial_println!(
238            "\x1b[1;31m[ipc] RINGS BTreeMap corrupted: len={} for id={} \u{2014} aborting remove\x1b[0m",
239            len, id.as_u64()
240        );
241        return Err(RingError::NotFound);
242    }
243    crate::serial_println!("[ipc] destroy_ring(id={}) map.len={}", id.as_u64(), len);
244
245    let ring = map.remove(&id).ok_or(RingError::NotFound)?;
246    drop(reg);
247
248    for &cap_id in ring.mapping_cap_ids() {
249        let _ = revoke_mapping_cap_id(cap_id);
250    }
251    Ok(())
252}