Skip to main content

strat9_kernel/ipc/v2/
handle.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//! Per-process generation-tagged handle table (IPC ABI v2, §3.1).
24
25use super::{
26    endpoint,
27    endpoint::{CallSlot, Endpoint},
28    notif::Notification,
29};
30use alloc::{sync::Arc, vec::Vec};
31use strat9_abi::ipc_v2::{Handle, EP_RECV, GENERIC_RIGHTS_MASK, RIGHTS_SAME, RIGHT_DUPLICATE};
32
33/// Hard limit on live entries in one process handle table.
34pub const MAX_HANDLES: usize = 256;
35
36/// The object a handle resolves to.
37#[derive(Clone)]
38pub enum ObjRef {
39    /// Endpoint object.
40    Endpoint(Arc<Endpoint>),
41    /// Single-use reply target for an in-flight call.
42    Reply(Arc<CallSlot>),
43    /// Notification object.
44    Notif(Arc<Notification>),
45    /// Memory object.
46    Mem(Arc<super::memobj::MemObject>),
47}
48
49impl ObjRef {
50    /// `ObjType` written into a received `CapXfer::mode` (§4.2).
51    pub fn obj_type(&self) -> u32 {
52        use strat9_abi::ipc_v2::{OBJ_ENDPOINT, OBJ_MEMOBJ, OBJ_NOTIFICATION, OBJ_REPLY};
53        match self {
54            ObjRef::Endpoint(_) => OBJ_ENDPOINT,
55            ObjRef::Reply(_) => OBJ_REPLY,
56            ObjRef::Notif(_) => OBJ_NOTIFICATION,
57            ObjRef::Mem(_) => OBJ_MEMOBJ,
58        }
59    }
60}
61
62/// One table entry: rights, object and immutable badge.
63#[derive(Clone)]
64pub struct Entry {
65    /// Rights bitmask (§3.2).
66    pub rights: u32,
67    /// Referenced object.
68    pub obj: ObjRef,
69    /// Endpoint sender badge / notification bit mask / Reply generation.
70    pub badge: u64,
71}
72
73#[derive(Clone)]
74struct Slot {
75    gen: u32,
76    entry: Option<Entry>,
77}
78
79/// The process handle table.
80///
81/// Index 0 is permanently reserved and never handed out: this makes handle
82/// value `0` (structure `(index=0, gen=0)/2`) impossible without needing a
83/// non-zero starting generation. A new slot starts at generation 1 and every
84/// reuse increments the generation before the entry becomes visible.
85pub struct HandleTable {
86    slots: Vec<Slot>,
87    free: Vec<u32>,
88    len: usize,
89    /// Slots promised to an in-progress receive (§4.5 step 3). Counted against
90    /// [`HandleTable::free_slots`] but not yet occupied; [`HandleTable::insert`]
91    /// consumes one unit per successful insert.
92    reserved: usize,
93}
94
95impl Default for HandleTable {
96    fn default() -> Self {
97        Self::new()
98    }
99}
100
101impl HandleTable {
102    /// Create an empty table with the reserved index-0 slot.
103    pub fn new() -> Self {
104        HandleTable {
105            slots: alloc::vec![Slot {
106                gen: 0,
107                entry: None,
108            }],
109            free: Vec::new(),
110            len: 0,
111            reserved: 0,
112        }
113    }
114
115    /// Number of live entries.
116    pub fn table_len(&self) -> usize {
117        self.len
118    }
119
120    /// Number of slots currently promised by [`HandleTable::reserve`].
121    pub fn reserved(&self) -> usize {
122        self.reserved
123    }
124
125    /// Slots that may still be handed out, honouring outstanding reservations.
126    pub fn free_slots(&self) -> usize {
127        MAX_HANDLES.saturating_sub(self.len + self.reserved)
128    }
129
130    /// Reserve `n` slots for an in-progress receive (§4.5 step 3).
131    ///
132    /// Invariant: after a successful `reserve(n)` the next `n` successful
133    /// [`HandleTable::insert`] calls cannot fail for capacity reasons; each one
134    /// consumes one reserved unit. The caller must release any unused units
135    /// with [`HandleTable::release_reservation`].
136    pub fn reserve(&mut self, n: usize) -> Result<(), crate::syscall::error::SyscallError> {
137        if n > self.free_slots() {
138            return Err(crate::syscall::error::SyscallError::NoSpace);
139        }
140        self.reserved += n;
141        Ok(())
142    }
143
144    /// Return `n` unused reserved slots (saturating).
145    pub fn release_reservation(&mut self, n: usize) {
146        self.reserved = self.reserved.saturating_sub(n);
147    }
148
149    /// Insert an entry, reusing a free slot if possible.
150    ///
151    /// Returns `None` when the table already holds [`MAX_HANDLES`] entries and
152    /// no reservation covers this insert. A successful insert consumes one
153    /// unit of an outstanding reservation, guaranteeing it cannot fail.
154    pub fn insert(&mut self, rights: u32, obj: ObjRef, badge: u64) -> Option<Handle> {
155        if self.reserved > 0 {
156            self.reserved -= 1;
157        } else if self.len >= MAX_HANDLES {
158            return None;
159        }
160        let entry = Entry { rights, obj, badge };
161        if let Some(index) = self.free.pop() {
162            let slot = &mut self.slots[index as usize];
163            // A reused slot must never resolve the previous generation.
164            slot.gen = slot.gen.wrapping_add(1).max(1);
165            slot.entry = Some(entry);
166            self.len += 1;
167            Some(Handle::new(index, slot.gen))
168        } else {
169            let index = self.slots.len() as u32;
170            self.slots.push(Slot {
171                gen: 1,
172                entry: Some(entry),
173            });
174            self.len += 1;
175            Some(Handle::new(index, 1))
176        }
177    }
178
179    /// Resolve a handle and check that `required` rights are present.
180    pub fn resolve(
181        &self,
182        h: Handle,
183        required: u32,
184    ) -> Result<Entry, crate::syscall::error::SyscallError> {
185        let entry = self.validate(h)?;
186        if entry.rights & required != required {
187            return Err(crate::syscall::error::SyscallError::PermissionDenied);
188        }
189        Ok(entry)
190    }
191
192    /// Take an entry out of the table and **apply its object side effects**
193    /// (endpoint reference release, Reply-handle cancellation).
194    pub fn remove(&mut self, h: Handle) -> Result<Entry, crate::syscall::error::SyscallError> {
195        let entry = self.remove_raw(h)?;
196        endpoint::release_handle(&entry);
197        Ok(entry)
198    }
199
200    /// Take an entry out of the table without object side effects.
201    ///
202    /// For consumption paths that take over the object's obligations, e.g.
203    /// `sys_ep_reply`, which delivers the reply immediately afterwards and must
204    /// not cancel the call it is completing.
205    pub fn remove_raw(&mut self, h: Handle) -> Result<Entry, crate::syscall::error::SyscallError> {
206        let entry = self.validate(h)?;
207        let slot = &mut self.slots[h.index() as usize];
208        slot.entry = None;
209        self.free.push(h.index());
210        self.len -= 1;
211        Ok(entry)
212    }
213
214    /// Drain every entry, applying the object-side effects of dropping each
215    /// handle (in particular closing the last `EP_RECV` endpoint reference).
216    pub fn remove_all(&mut self) {
217        for slot in self.slots.iter_mut() {
218            if let Some(entry) = slot.entry.take() {
219                endpoint::release_handle(&entry);
220            }
221        }
222        self.slots.truncate(1);
223        self.free.clear();
224        self.len = 0;
225        self.reserved = 0;
226    }
227
228    /// Duplicate a handle with an equal or smaller rights mask.
229    pub fn duplicate(
230        &mut self,
231        h: Handle,
232        requested_rights: u32,
233    ) -> Result<Handle, crate::syscall::error::SyscallError> {
234        let entry = self.validate(h)?;
235        if entry.rights & RIGHT_DUPLICATE == 0 {
236            return Err(crate::syscall::error::SyscallError::PermissionDenied);
237        }
238        let rights = if requested_rights == RIGHTS_SAME {
239            entry.rights
240        } else {
241            requested_rights & entry.rights
242        };
243        let new = self
244            .insert(rights, entry.obj.clone(), entry.badge)
245            .ok_or(crate::syscall::error::SyscallError::NoSpace)?;
246        if rights & EP_RECV != 0 {
247            endpoint::retain_handle(&entry);
248        }
249        Ok(new)
250    }
251
252    /// Clone this table for `fork`: same objects, rights and generations.
253    /// Every copied `EP_RECV` endpoint entry takes an extra reference.
254    pub fn fork_clone(&self) -> Self {
255        let out = HandleTable {
256            slots: self.slots.clone(),
257            free: self.free.clone(),
258            len: self.len,
259            reserved: 0,
260        };
261        for slot in out.slots.iter() {
262            if let Some(entry) = slot.entry.as_ref() {
263                if entry.rights & EP_RECV != 0 {
264                    endpoint::retain_handle(entry);
265                }
266            }
267        }
268        out
269    }
270
271    /// Mask of rights that may be requested through `ipc_mint`/`duplicate`.
272    pub const fn generic_rights() -> u32 {
273        GENERIC_RIGHTS_MASK
274    }
275
276    fn validate(&self, h: Handle) -> Result<Entry, crate::syscall::error::SyscallError> {
277        use crate::syscall::error::SyscallError;
278        if !h.is_valid() {
279            return Err(SyscallError::BadHandle);
280        }
281        let slot = self
282            .slots
283            .get(h.index() as usize)
284            .ok_or(SyscallError::BadHandle)?;
285        if slot.gen != h.generation() {
286            return Err(SyscallError::BadHandle);
287        }
288        slot.entry.clone().ok_or(SyscallError::BadHandle)
289    }
290}