Skip to main content

strat9_kernel/ipc/v2/
async_ops.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 v2 operations on async rings: `AsyncOp` 13–17 (spec §11).
24//!
25//! # Execution model
26//!
27//! Every operation, at submission and at every retry, runs in the **ring
28//! owner's** context: `SYS_ASYNC_ENTER` is only accepted from the owning
29//! process, and both [`submit`] and [`poll`] are called from it. All user
30//! copies therefore target the owner's address space, outside any IPC lock;
31//! nothing is ever written from a peer's context (the defect of the v1
32//! `AsyncRing` reply path).
33//!
34//! An operation that cannot complete without blocking is *parked*. IPC events
35//! (enqueue, dequeue, reply, cancellation, signal, close) call
36//! [`notify_event`], which kicks every ring that has parked operations; the
37//! owner's `SYS_ASYNC_ENTER` then calls [`poll`], which retries them
38//! non-blockingly and posts a CQE for each one that completes.
39
40use super::endpoint::{self, CallSlot, CallState};
41use crate::{
42    async_io::{complete::push_completion, ring::find_ring},
43    process::process::Process,
44    sync::SpinLock,
45    syscall::{
46        error::SyscallError,
47        ipc_v2::{self as sys, WaitSpec},
48    },
49};
50use alloc::{sync::Arc, vec::Vec};
51use core::{
52    mem::size_of,
53    sync::atomic::{AtomicUsize, Ordering},
54};
55use strat9_abi::ipc_v2::{MsgBuf, MsgCall, IPC_NONBLOCK};
56
57/// `AsyncOp` opcodes owned by this module.
58pub const OP_EP_SEND: u8 = 13;
59pub const OP_EP_CALL: u8 = 14;
60pub const OP_EP_RECV: u8 = 15;
61pub const OP_EP_REPLY: u8 = 16;
62pub const OP_NOTIF_WAIT: u8 = 17;
63
64/// What a parked operation is waiting for.
65enum Kind {
66    /// `EpSend`: queue full or quota exhausted.
67    Send,
68    /// `EpRecv`: queue empty.
69    Recv,
70    /// `NotifWait`: word is zero.
71    NotifWait,
72    /// `EpCall`: the enqueue itself would block (full queue or exhausted
73    /// quota). Holds the `*MsgBuf` request and response descriptors until
74    /// `call_submit` commits, then becomes `Call`.
75    CallSubmit { req: u64, resp: u64 },
76    /// `EpCall`: committed, waiting for the reply.
77    Call { slot: Arc<CallSlot>, resp: MsgBuf },
78}
79
80struct Parked {
81    ring_id: u64,
82    user_data: u64,
83    handle: u64,
84    addr: u64,
85    kind: Kind,
86}
87
88static PARKED: SpinLock<Vec<Parked>> = SpinLock::new(Vec::new());
89/// Fast path for [`notify_event`]: no lock when nothing is parked.
90static PARKED_COUNT: AtomicUsize = AtomicUsize::new(0);
91
92/// Result of one non-blocking attempt.
93enum Attempt {
94    /// Completed: CQE `res` value (`>= 0` or `-errno`).
95    Done(i32),
96    /// Would block: keep parked.
97    Pending,
98}
99
100fn errno(error: SyscallError) -> i32 {
101    error as i64 as i32
102}
103
104fn finished(result: Result<u64, SyscallError>) -> Attempt {
105    match result {
106        Ok(value) => Attempt::Done(value as i32),
107        Err(SyscallError::Again) => Attempt::Pending,
108        Err(error) => Attempt::Done(errno(error)),
109    }
110}
111
112const NONBLOCK: u64 = IPC_NONBLOCK as u64;
113
114fn attempt(process: &Process, op: &mut Parked) -> Attempt {
115    if let Kind::CallSubmit { req, resp } = &op.kind {
116        let (req, resp) = (*req, *resp);
117        match sys::call_submit(process, op.handle, req, resp, WaitSpec::NONBLOCK) {
118            Ok((slot, resp)) => op.kind = Kind::Call { slot, resp },
119            Err(SyscallError::Again) => return Attempt::Pending,
120            Err(error) => return Attempt::Done(errno(error)),
121        }
122    }
123    match &op.kind {
124        Kind::Send => finished(sys::sys_ep_send(process, op.handle, op.addr, NONBLOCK, 0)),
125        Kind::Recv => finished(sys::sys_ep_recv(process, op.handle, op.addr, NONBLOCK, 0)),
126        Kind::NotifWait => finished(sys::sys_notif_wait(
127            process, op.handle, op.addr, NONBLOCK, 0,
128        )),
129        Kind::CallSubmit { .. } => unreachable!("converted to Kind::Call above"),
130        Kind::Call { slot, resp } => {
131            let state = *slot.state.lock();
132            match state {
133                CallState::Done | CallState::Cancelled => {
134                    match sys::call_finish(process, slot, resp) {
135                        Ok(_) => Attempt::Done(0),
136                        Err(error) => Attempt::Done(errno(error)),
137                    }
138                }
139                _ => Attempt::Pending,
140            }
141        }
142    }
143}
144
145/// Submission outcome reported to the async dispatcher.
146pub enum Submitted {
147    /// A CQE was already posted.
148    Completed,
149    /// Parked; a CQE will follow from [`poll`].
150    InFlight,
151}
152
153/// Submit one IPC v2 SQE (`AsyncOp` 13–17) for `ring_id`.
154///
155/// `handle` = SQE `off`, `addr` = SQE `addr`, `len` = SQE `len` (must equal
156/// the descriptor size, which versions it). Errors are returned as `-errno`
157/// for the dispatcher to post.
158pub fn submit(
159    process: &Process,
160    ring_id: u64,
161    opcode: u8,
162    handle: u64,
163    addr: u64,
164    len: u32,
165    user_data: u64,
166) -> Result<Submitted, i32> {
167    let expected = match opcode {
168        OP_EP_SEND | OP_EP_RECV | OP_EP_REPLY => size_of::<MsgBuf>(),
169        OP_EP_CALL => size_of::<MsgCall>(),
170        OP_NOTIF_WAIT => size_of::<u64>(),
171        _ => return Err(errno(SyscallError::InvalidArgument)),
172    };
173    if len as usize != expected {
174        return Err(errno(SyscallError::InvalidArgument));
175    }
176
177    let mut op = Parked {
178        ring_id,
179        user_data,
180        handle,
181        addr,
182        kind: Kind::Send,
183    };
184    let first = match opcode {
185        OP_EP_SEND => attempt(process, &mut op),
186        OP_EP_RECV => {
187            op.kind = Kind::Recv;
188            attempt(process, &mut op)
189        }
190        OP_NOTIF_WAIT => {
191            op.kind = Kind::NotifWait;
192            attempt(process, &mut op)
193        }
194        // A reply never blocks (§6.2 rule 5).
195        OP_EP_REPLY => Attempt::Done(match sys::sys_ep_reply(process, handle, addr) {
196            Ok(_) => 0,
197            Err(error) => errno(error),
198        }),
199        OP_EP_CALL => {
200            // `MsgCall { req, resp }`: req at `addr`, resp right after it.
201            op.kind = Kind::CallSubmit {
202                req: addr,
203                resp: addr + size_of::<MsgBuf>() as u64,
204            };
205            attempt(process, &mut op)
206        }
207        _ => unreachable!("opcode validated above"),
208    };
209
210    match first {
211        Attempt::Done(res) => {
212            push_completion(ring_id, user_data, res, 0);
213            Ok(Submitted::Completed)
214        }
215        Attempt::Pending => {
216            PARKED.lock().push(op);
217            PARKED_COUNT.fetch_add(1, Ordering::AcqRel);
218            Ok(Submitted::InFlight)
219        }
220    }
221}
222
223/// Retry the parked operations of `ring_id`. Must run in the ring owner's
224/// context (called from `SYS_ASYNC_ENTER`). Returns how many completed.
225pub fn poll(process: &Process, ring_id: u64) -> u32 {
226    if PARKED_COUNT.load(Ordering::Acquire) == 0 {
227        return 0;
228    }
229    // Take this ring's operations out; attempts run with no lock held.
230    let mine: Vec<Parked> = {
231        let mut parked = PARKED.lock();
232        let (mine, rest): (Vec<Parked>, Vec<Parked>) =
233            parked.drain(..).partition(|op| op.ring_id == ring_id);
234        *parked = rest;
235        mine
236    };
237    PARKED_COUNT.fetch_sub(mine.len(), Ordering::AcqRel);
238
239    let mut completed = 0;
240    let mut still = Vec::new();
241    for mut op in mine {
242        match attempt(process, &mut op) {
243            Attempt::Done(res) => {
244                push_completion(op.ring_id, op.user_data, res, 0);
245                completed += 1;
246            }
247            Attempt::Pending => still.push(op),
248        }
249    }
250    if !still.is_empty() {
251        PARKED_COUNT.fetch_add(still.len(), Ordering::AcqRel);
252        PARKED.lock().extend(still);
253    }
254    completed
255}
256
257/// An IPC v2 event happened: kick every ring that has parked operations.
258///
259/// Called after the event, outside IPC locks. Cheap when nothing is parked.
260pub fn notify_event() {
261    if PARKED_COUNT.load(Ordering::Acquire) == 0 {
262        return;
263    }
264    let mut rings: Vec<u64> = Vec::new();
265    {
266        let parked = PARKED.lock();
267        for op in parked.iter() {
268            if !rings.contains(&op.ring_id) {
269                rings.push(op.ring_id);
270            }
271        }
272    }
273    for id in rings {
274        if let Some(ring) = find_ring(id) {
275            ring.ipc_kick.store(1, Ordering::Release);
276            ring.wq.wake_all();
277        }
278    }
279}
280
281/// Cancel the parked operation of `ring_id` whose `user_data == target`.
282///
283/// The cancelled operation's CQE reports `-ECANCELED`; a `Kind::Call` that was
284/// already committed is abandoned exactly like a signal on the sync path
285/// (`abandon_call`, §6.2), so a late reply releases its capabilities instead
286/// of leaking them. `Kind::CallSubmit` holds no resources yet.
287///
288/// Returns `Err(NotFound)` when no such parked operation exists (including the
289/// benign race where `poll` already took it).
290pub fn cancel(ring_id: u64, target: u64) -> Result<(), SyscallError> {
291    let op = {
292        let mut parked = PARKED.lock();
293        match parked
294            .iter()
295            .position(|op| op.ring_id == ring_id && op.user_data == target)
296        {
297            Some(index) => parked.remove(index),
298            None => return Err(SyscallError::NotFound),
299        }
300    };
301    PARKED_COUNT.fetch_sub(1, Ordering::AcqRel);
302    // No lock held across `abandon_call` or the completion push.
303    if let Kind::Call { slot, .. } = op.kind {
304        endpoint::abandon_call(&slot);
305    }
306    push_completion(ring_id, target, errno(SyscallError::Canceled), 0);
307    Ok(())
308}
309
310/// Drop every parked operation of a destroyed ring. Pending calls are
311/// abandoned so a late reply's capabilities are released (§6.2).
312pub fn drop_ring(ring_id: u64) {
313    let dropped: Vec<Parked> = {
314        let mut parked = PARKED.lock();
315        let (dropped, rest): (Vec<Parked>, Vec<Parked>) =
316            parked.drain(..).partition(|op| op.ring_id == ring_id);
317        *parked = rest;
318        dropped
319    };
320    PARKED_COUNT.fetch_sub(dropped.len(), Ordering::AcqRel);
321    for op in dropped {
322        if let Kind::Call { slot, .. } = op.kind {
323            endpoint::abandon_call(&slot);
324        }
325    }
326}