Skip to main content

strat9_kernel/syscall/
chan.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//! Typed MPMC sync-channel syscall handlers.
24//!
25//! Provides bounded multi-producer, multi-consumer channels for
26//! inter-process message passing (IPC-02).
27
28use super::error::SyscallError;
29use crate::{
30    capability::{CapId, ResourceType},
31    ipc::{
32        channel::{self, ChanId},
33        message::IpcMessage,
34    },
35    memory::{UserSliceRead, UserSliceWrite},
36    process::current_task_clone,
37};
38
39const MSG_SIZE: usize = core::mem::size_of::<IpcMessage>();
40
41// ABI contract: userspace uses `strat9_abi::data::IPC_MESSAGE_SIZE`.
42// If IpcMessage's size changes, this assertion forces a deliberate review of
43// the userspace ABI in lock-step with the ABI constant.
44const _: () = assert!(
45    MSG_SIZE == strat9_abi::data::IPC_MESSAGE_SIZE,
46    "IpcMessage size changed : update userspace ABI"
47);
48
49/// SYS_CHAN_CREATE (220): create a bounded sync-channel.
50pub fn sys_chan_create(capacity: u64) -> Result<u64, SyscallError> {
51    let cap = capacity.clamp(1, 1024) as usize;
52
53    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
54
55    // Reserve quota before creating the channel.
56    task.process
57        .ipc_quota
58        .try_reserve(cap)
59        .map_err(|_| SyscallError::OutOfMemory)?;
60
61    let chan_id = match channel::create_channel(cap) {
62        id => id,
63    };
64
65    let caps = unsafe { &*task.process.capabilities.get() };
66    let cap_id = crate::capability::CapId::new();
67    let chan_cap = crate::capability::Capability {
68        id: cap_id,
69        permissions: crate::capability::CapPermissions {
70            read: true,
71            write: true,
72            execute: false,
73            grant: true,
74            revoke: false,
75        },
76        resource_type: ResourceType::Channel,
77        resource: chan_id.as_u64() as usize,
78        // Badge defaults to capability ID; receivers see this in msg.sender.
79        // When this capability is granted/delegated, the granter can supply
80        // a custom badge so the receiver can distinguish individual clients.
81        badge: cap_id.as_u64(),
82        dma: crate::capability::DmaRights::none(),
83    };
84    let handle = caps.insert(chan_cap);
85
86    log::debug!(
87        "syscall: CHAN_CREATE(cap={}) => chan={} handle={}",
88        cap,
89        chan_id,
90        handle.as_u64()
91    );
92    Ok(handle.as_u64())
93}
94
95/// SYS_CHAN_SEND (221): send one `IpcMessage` to a channel, blocking if full.
96///
97/// **P1 fix**: The kernel now injects `cap.badge` into `msg.sender` instead
98/// of the raw task ID.  This follows the capability-endpoint model (seL4):
99/// the receiver sees only the badge of the delegation chain, never the
100/// sender's global identity.  A sender cannot forge the badge because the
101/// kernel overwrites `msg.sender` after reading the message from user-space.
102pub fn sys_chan_send(handle: u64, msg_ptr: u64) -> Result<u64, SyscallError> {
103    sys_chan_send_timeout(handle, msg_ptr, 0)
104}
105
106/// SYS_CHAN_SEND_TIMEOUT (225): send with a bounded wait for space.
107pub fn sys_chan_send_timeout(
108    handle: u64,
109    msg_ptr: u64,
110    timeout_ns: u64,
111) -> Result<u64, SyscallError> {
112    crate::silo::enforce_cap_for_current_task(handle)?;
113
114    let user_slice = UserSliceRead::new(msg_ptr, MSG_SIZE).map_err(SyscallError::from)?;
115    let mut msg = IpcMessage::new(0);
116    let n = user_slice.copy_to(unsafe {
117        core::slice::from_raw_parts_mut(&mut msg as *mut IpcMessage as *mut u8, MSG_SIZE)
118    });
119    if n != MSG_SIZE {
120        return Err(SyscallError::Fault);
121    }
122
123    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
124    let caps = unsafe { &*task.process.capabilities.get() };
125    let cap = caps
126        .get(CapId::from_raw(handle))
127        .ok_or(SyscallError::BadHandle)?;
128    if cap.resource_type != ResourceType::Channel || !cap.permissions.write {
129        return Err(SyscallError::PermissionDenied);
130    }
131    let chan_id = ChanId::from_u64(cap.resource as u64);
132
133    // Inject the capability badge : the receiver sees this in msg.sender,
134    // not the sender's global task ID.  The badge is set at capability
135    // creation time (defaults to cap_id) and can be overridden via grant.
136    msg.sender = cap.badge;
137
138    let chan = channel::get_channel(chan_id).ok_or(SyscallError::BadHandle)?;
139    chan.send_deadline(msg, crate::sync::deadline_after_ns(timeout_ns))
140        .map_err(SyscallError::from)?;
141
142    Ok(0)
143}
144
145/// SYS_CHAN_RECV (222): receive one `IpcMessage`, blocking if empty.
146
147pub fn sys_chan_recv(handle: u64, msg_ptr: u64) -> Result<u64, SyscallError> {
148    sys_chan_recv_timeout(handle, msg_ptr, 0)
149}
150
151/// SYS_CHAN_RECV_TIMEOUT (226): receive with a bounded wait.
152pub fn sys_chan_recv_timeout(
153    handle: u64,
154    msg_ptr: u64,
155    timeout_ns: u64,
156) -> Result<u64, SyscallError> {
157    crate::silo::enforce_cap_for_current_task(handle)?;
158
159    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
160    let caps = unsafe { &*task.process.capabilities.get() };
161    let cap = caps
162        .get(CapId::from_raw(handle))
163        .ok_or(SyscallError::BadHandle)?;
164    if cap.resource_type != ResourceType::Channel || !cap.permissions.read {
165        return Err(SyscallError::PermissionDenied);
166    }
167    let chan_id = ChanId::from_u64(cap.resource as u64);
168
169    // Validate the destination buffer BEFORE consuming the message.
170    // If the pointer is invalid, we return EFAULT without touching the queue.
171    let user_slice = UserSliceWrite::new(msg_ptr, MSG_SIZE).map_err(SyscallError::from)?;
172
173    let chan = channel::get_channel(chan_id).ok_or(SyscallError::BadHandle)?;
174    let msg = chan
175        .recv_deadline(crate::sync::deadline_after_ns(timeout_ns))
176        .map_err(SyscallError::from)?;
177
178    let n = user_slice.copy_from(unsafe {
179        core::slice::from_raw_parts(&msg as *const IpcMessage as *const u8, MSG_SIZE)
180    });
181    if n != MSG_SIZE {
182        // Defensive: should not happen after buffer validation, but the
183        // message has already been consumed
184        return Err(SyscallError::Fault);
185    }
186
187    Ok(0)
188}
189
190/// SYS_CHAN_TRY_RECV (223): non-blocking receive.
191///
192/// **P0 fix**: Same as `sys_chan_recv` : validate the user destination buffer
193/// before consuming the message from the queue.
194pub fn sys_chan_try_recv(handle: u64, msg_ptr: u64) -> Result<u64, SyscallError> {
195    crate::silo::enforce_cap_for_current_task(handle)?;
196
197    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
198    let caps = unsafe { &*task.process.capabilities.get() };
199    let cap = caps
200        .get(CapId::from_raw(handle))
201        .ok_or(SyscallError::BadHandle)?;
202    if cap.resource_type != ResourceType::Channel || !cap.permissions.read {
203        return Err(SyscallError::PermissionDenied);
204    }
205    let chan_id = ChanId::from_u64(cap.resource as u64);
206
207    let user_slice = UserSliceWrite::new(msg_ptr, MSG_SIZE).map_err(SyscallError::from)?;
208
209    let chan = channel::get_channel(chan_id).ok_or(SyscallError::BadHandle)?;
210    match chan.try_recv() {
211        Ok(msg) => {
212            let n = user_slice.copy_from(unsafe {
213                core::slice::from_raw_parts(&msg as *const IpcMessage as *const u8, MSG_SIZE)
214            });
215            if n != MSG_SIZE {
216                return Err(SyscallError::Fault);
217            }
218            Ok(0)
219        }
220        Err(e) => Err(SyscallError::from(e)),
221    }
222}
223
224/// SYS_CHAN_CLOSE (224): close a channel handle.
225
226pub fn sys_chan_close(handle: u64) -> Result<u64, SyscallError> {
227    crate::silo::enforce_cap_for_current_task(handle)?;
228
229    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
230    let caps = unsafe { &*task.process.capabilities.get() };
231    let cap = caps
232        .get(CapId::from_raw(handle))
233        .ok_or(SyscallError::BadHandle)?;
234    if cap.resource_type != ResourceType::Channel {
235        return Err(SyscallError::BadHandle);
236    }
237    let chan_id = ChanId::from_u64(cap.resource as u64);
238    let has_revoke = cap.permissions.revoke;
239
240    // Look up the channel to get its capacity for quota release.
241    let capacity = channel::get_channel(chan_id)
242        .map(|c| c.capacity())
243        .unwrap_or(0);
244
245    let cap = caps
246        .remove(CapId::from_raw(handle))
247        .ok_or(SyscallError::BadHandle)?;
248    debug_assert_eq!(cap.resource_type, ResourceType::Channel);
249
250    // Release per-process IPC quota for this handle.
251    task.process.ipc_quota.release(capacity);
252
253    if has_revoke {
254        // Full release: decrement global refcount and destroy channel if
255        // this was the last capability referencing it.
256        crate::capability::release_capability(&cap, Some(task.id));
257    } else {
258        // Local-only close: decrement the global refcount without triggering
259        // channel destruction.  The channel stays alive until all other
260        // capabilities (held by other processes) are also dropped.
261        crate::capability::get_capability_manager().revoke_capability(cap.id);
262    }
263
264    log::debug!("syscall: CHAN_CLOSE(handle={}) => chan={}", handle, chan_id);
265    Ok(0)
266}