Skip to main content

strat9_kernel/async_io/
dispatch.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//! SQE dispatch : routes submitted SQEs to the appropriate backend.
24//!
25//! Called from `SYS_ASYNC_ENTER` when `to_submit > 0`.  Walks the
26//! submission queue and dispatches each SQE by opcode.
27
28use crate::{
29    ipc::message::{ipc_message_from_raw, ipc_message_to_raw, IpcMessage},
30    memory::{UserSliceRead, UserSliceWrite},
31    vfs::scheme::AsyncSubmitResult,
32};
33
34use super::{
35    complete::{inc_in_flight_for_ring, push_completion_for_ring},
36    ops::AsyncOp,
37    ring::find_ring,
38};
39
40enum DispatchOutcome {
41    CompletedInline,
42    InFlight,
43}
44
45// Errno constants (no libc dependency)
46const EBADF: i32 = -9;
47const EFAULT: i32 = -14;
48const EINVAL: i32 = -22;
49const EIO: i32 = -5;
50const ENOMSG: i32 = -42;
51const IPC_MSG_SIZE: usize = core::mem::size_of::<IpcMessage>();
52
53/// Process up to `count` pending SQEs from the given ring.
54///
55/// Returns the number of SQEs successfully processed.
56pub fn drain_submissions(ring_id: u64, count: u32) -> u32 {
57    let Some(ring) = find_ring(ring_id) else {
58        return 0;
59    };
60
61    let head = ring.sq_head();
62    let tail = ring.sq_tail();
63    let mask = ring
64        .sq_meta()
65        .mask
66        .load(core::sync::atomic::Ordering::Relaxed);
67    let available = tail.wrapping_sub(head).min(count);
68    if available == 0 {
69        return 0;
70    }
71
72    for i in 0..available {
73        let idx = (head.wrapping_add(i)) & mask;
74        let sqe = unsafe { &*ring.sqe_at(idx) };
75        match dispatch_one(sqe, &ring) {
76            Err(e) => {
77                push_completion_for_ring(&ring, sqe.user_data, e, 0);
78            }
79            Ok(DispatchOutcome::CompletedInline) => {}
80            Ok(DispatchOutcome::InFlight) => {
81                inc_in_flight_for_ring(&ring);
82            }
83        }
84    }
85
86    ring.sq_advance_head(available);
87    available
88}
89
90/// Dispatch a single SQE by opcode.
91fn dispatch_one(
92    sqe: &super::ops::AsyncSqe,
93    ring: &super::ring::Ring,
94) -> Result<DispatchOutcome, i32> {
95    let ring_id = ring.id;
96    match sqe.opcode {
97        // Nop : immediate success
98        op if op == AsyncOp::Nop as u8 => {
99            push_completion_for_ring(ring, sqe.user_data, 0, 0);
100            Ok(DispatchOutcome::CompletedInline)
101        }
102
103        // VFS reads : resolve fd and submit through AsyncScheme.
104        op if op == AsyncOp::Read as u8 => {
105            let fd = sqe.fd as u32;
106            let buf_vaddr = sqe.addr;
107            let len = sqe.len as usize;
108
109            // Resolve fd => (scheme, file_id)  (VFS pattern)
110            let task = crate::process::current_task_clone().ok_or(EIO)?;
111            let fd_table = unsafe { &*task.process.fd_table.get() };
112            let file = fd_table.get(fd).map_err(|_| EBADF)?;
113            let file_id = file.file_id();
114            let scheme_ref: &dyn crate::vfs::scheme::Scheme = &**file.scheme();
115
116            match scheme_ref.async_read(file_id, sqe.off, buf_vaddr, len, ring_id, sqe.user_data) {
117                Ok(AsyncSubmitResult::Completed(n)) => {
118                    push_completion_for_ring(ring, sqe.user_data, n, 0);
119                    Ok(DispatchOutcome::CompletedInline)
120                }
121                Ok(AsyncSubmitResult::InFlight) => Ok(DispatchOutcome::InFlight),
122                Err(err) => Err(err as i32),
123            }
124        }
125
126        // VFS writes : resolve fd and submit through AsyncScheme.
127        op if op == AsyncOp::Write as u8 => {
128            let fd = sqe.fd as u32;
129            let buf_vaddr = sqe.addr;
130            let len = sqe.len as usize;
131
132            let task = crate::process::current_task_clone().ok_or(EIO)?;
133            let fd_table = unsafe { &*task.process.fd_table.get() };
134            let file = fd_table.get(fd).map_err(|_| EBADF)?;
135            let file_id = file.file_id();
136            let scheme_ref: &dyn crate::vfs::scheme::Scheme = &**file.scheme();
137
138            match scheme_ref.async_write(file_id, sqe.off, buf_vaddr, len, ring_id, sqe.user_data) {
139                Ok(AsyncSubmitResult::Completed(n)) => {
140                    push_completion_for_ring(ring, sqe.user_data, n, 0);
141                    Ok(DispatchOutcome::CompletedInline)
142                }
143                Ok(AsyncSubmitResult::InFlight) => Ok(DispatchOutcome::InFlight),
144                Err(err) => Err(err as i32),
145            }
146        }
147
148        // IPC send : try_send message to port, push CQE with result
149        op if op == AsyncOp::IpcSend as u8 => {
150            let port_id = crate::ipc::PortId::from_u64(sqe.fd as u64);
151            let Some(port) = crate::ipc::port::get_port(port_id) else {
152                push_completion_for_ring(ring, sqe.user_data, EBADF, 0);
153                return Ok(DispatchOutcome::CompletedInline);
154            };
155            let user_msg = UserSliceRead::new(sqe.addr, core::mem::size_of::<IpcMessage>())
156                .map_err(|_| EFAULT)?;
157            let mut raw = [0u8; IPC_MSG_SIZE];
158            user_msg.copy_to(&mut raw);
159            let msg = ipc_message_from_raw(&raw);
160            let res_code = match port.try_send(msg) {
161                Ok(()) => 0,
162                Err(_) => ENOMSG,
163            };
164            push_completion_for_ring(ring, sqe.user_data, res_code, 0);
165            Ok(DispatchOutcome::CompletedInline)
166        }
167
168        // IPC recv : try_recv message from port, copy to buffer, push CQE
169        op if op == AsyncOp::IpcRecv as u8 => {
170            let port_id = crate::ipc::PortId::from_u64(sqe.fd as u64);
171            let Some(port) = crate::ipc::port::get_port(port_id) else {
172                push_completion_for_ring(ring, sqe.user_data, EBADF, 0);
173                return Ok(DispatchOutcome::CompletedInline);
174            };
175            match port.try_recv() {
176                Ok(Some(msg)) => {
177                    let user_msg =
178                        UserSliceWrite::new(sqe.addr, core::mem::size_of::<IpcMessage>())
179                            .map_err(|_| EFAULT)?;
180                    let mut raw = [0u8; IPC_MSG_SIZE];
181                    ipc_message_to_raw(&msg, &mut raw);
182                    user_msg.copy_from(&raw);
183                    push_completion_for_ring(ring, sqe.user_data, IPC_MSG_SIZE as i32, 0);
184                    Ok(DispatchOutcome::CompletedInline)
185                }
186                Ok(None) => {
187                    push_completion_for_ring(ring, sqe.user_data, ENOMSG, 0);
188                    Ok(DispatchOutcome::CompletedInline)
189                }
190                Err(_) => {
191                    push_completion_for_ring(ring, sqe.user_data, EBADF, 0);
192                    Ok(DispatchOutcome::CompletedInline)
193                }
194            }
195        }
196
197        // IPC call : send message + register async reply via ring CQE.
198        //
199        //   sqe.fd        = port handle (cap id)
200        //   sqe.addr      = pointer to IpcMessage (request in, reply overwrites)
201        //   sqe.user_data = correlation token (echoed in CQE on reply)
202        //
203        op if op == AsyncOp::IpcCall as u8 => {
204            let port_id = crate::ipc::PortId::from_u64(sqe.fd as u64);
205            let Some(port) = crate::ipc::port::get_port(port_id) else {
206                push_completion_for_ring(ring, sqe.user_data, EBADF, 0);
207                return Ok(DispatchOutcome::CompletedInline);
208            };
209
210            // Read the outgoing message from userspace.
211            let user_msg = UserSliceRead::new(sqe.addr, core::mem::size_of::<IpcMessage>())
212                .map_err(|_| EFAULT)?;
213            let mut raw = [0u8; IPC_MSG_SIZE];
214            user_msg.copy_to(&mut raw);
215            let mut msg = ipc_message_from_raw(&raw);
216
217            let task = crate::process::current_task_clone().ok_or(EIO)?;
218            msg.sender = task.id.as_u64();
219
220            port.try_send(msg).map_err(|_| ENOMSG)?;
221
222            crate::ipc::reply::register_ring_call(
223                task.id,
224                port.owner,
225                ring_id,
226                sqe.user_data,
227                sqe.addr,
228            );
229
230            Ok(DispatchOutcome::InFlight)
231        }
232
233        // IPC ABI v2 (13–17): endpoint send/call/recv/reply, notification wait.
234        //   sqe.off  = handle, sqe.addr = MsgBuf / MsgCall / *u64,
235        //   sqe.len  = descriptor size (versions it).
236        // Runs in the ring owner's context (SYS_ASYNC_ENTER is owner-only).
237        op @ 13..=17 => {
238            let task = crate::process::current_task_clone().ok_or(EIO)?;
239            match crate::ipc::v2::async_ops::submit(
240                &task.process,
241                ring_id,
242                op,
243                sqe.off,
244                sqe.addr,
245                sqe.len,
246                sqe.user_data,
247            )? {
248                crate::ipc::v2::async_ops::Submitted::Completed => {
249                    Ok(DispatchOutcome::CompletedInline)
250                }
251                crate::ipc::v2::async_ops::Submitted::InFlight => Ok(DispatchOutcome::InFlight),
252            }
253        }
254
255        // Storage read : submit async AHCI/NVMe read, CQE arrives via the IRQ
256        op if op == AsyncOp::StorageRead as u8 => {
257            let port_idx = sqe.fd as u8;
258            let lba = sqe.off;
259            let byte_count = sqe.len;
260            let user_buf_vaddr = sqe.addr;
261
262            match crate::hardware::storage::ahci::submit_async_storage_op(
263                port_idx,
264                lba,
265                byte_count,
266                user_buf_vaddr,
267                false, // read
268                ring_id,
269                sqe.user_data,
270            ) {
271                Ok(()) => Ok(DispatchOutcome::InFlight), // in-flight; CQE comes from IRQ handler
272                Err(_) => {
273                    push_completion_for_ring(ring, sqe.user_data, EIO, 0);
274                    Ok(DispatchOutcome::CompletedInline)
275                }
276            }
277        }
278
279        // Storage write : submit async AHCI/NVMe write, CQE arrives via IRQ
280        op if op == AsyncOp::StorageWrite as u8 => {
281            let port_idx = sqe.fd as u8;
282            let lba = sqe.off;
283            let byte_count = sqe.len;
284            let user_buf_vaddr = sqe.addr;
285
286            match crate::hardware::storage::ahci::submit_async_storage_op(
287                port_idx,
288                lba,
289                byte_count,
290                user_buf_vaddr,
291                true, // write
292                ring_id,
293                sqe.user_data,
294            ) {
295                Ok(()) => Ok(DispatchOutcome::InFlight), // in-flight; CQE comes from IRQ handler
296                Err(_) => {
297                    push_completion_for_ring(ring, sqe.user_data, EIO, 0);
298                    Ok(DispatchOutcome::CompletedInline)
299                }
300            }
301        }
302
303        // Cancel a parked operation by target token (`addr`), io_uring convention.
304        op if op == AsyncOp::Cancel as u8 => {
305            let res = match crate::ipc::v2::async_ops::cancel(ring_id, sqe.addr) {
306                Ok(()) => 0,
307                Err(error) => error as i64 as i32,
308            };
309            push_completion_for_ring(ring, sqe.user_data, res, 0);
310            Ok(DispatchOutcome::CompletedInline)
311        }
312
313        // Unknown opcode
314        _ => Err(EINVAL),
315    }
316}