Skip to main content

strat9_kernel/async_io/
syscall.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//! Asynchronous I/O syscall handlers.
24//!
25//! Dispatches SQEs to VFS backends via `AsyncScheme`,
26//! drains completions, and blocks when `min_complete > 0`.
27
28use alloc::sync::Arc;
29use strat9_abi::data::AsyncRingLayout;
30
31use crate::{memory::UserSliceWrite, syscall::error::SyscallError};
32
33use super::{complete, dispatch, ring::RingError};
34
35#[derive(Debug, Clone, Copy)]
36pub struct AsyncRingMapping {
37    pub sq_base: u64,
38    pub cq_base: u64,
39    pub sq_size: u64,
40    pub cq_size: u64,
41    pub entries: u32,
42}
43
44fn require_owned_ring_by_id(ring_id: u64) -> Result<Arc<super::ring::Ring>, SyscallError> {
45    let task = crate::process::current_task_clone().ok_or(SyscallError::PermissionDenied)?;
46    let ring = super::ring::find_ring(ring_id).ok_or(SyscallError::BadHandle)?;
47
48    if ring.owner_pid != task.pid {
49        return Err(SyscallError::PermissionDenied);
50    }
51
52    Ok(ring)
53}
54
55/// SYS_ASYNC_SETUP(entries: u32, flags: u32) => ring_id: u64
56pub fn sys_async_setup(entries: u64, _flags: u64) -> Result<u64, SyscallError> {
57    let Some(task) = crate::process::current_task_clone() else {
58        return Err(SyscallError::PermissionDenied);
59    };
60    let pid = task.pid;
61    let entries = entries as u32;
62
63    super::ring::Ring::create(pid, entries).map_err(|e| match e {
64        RingError::Alloc => SyscallError::OutOfMemory,
65        RingError::NotFound => SyscallError::BadHandle,
66        RingError::TooManyRings => SyscallError::OutOfMemory,
67    })
68}
69
70/// SYS_ASYNC_MAP(ring_id: u64, out_ptr: *mut AsyncRingLayout) -> total_mapped_bytes: u64
71pub fn sys_async_map(ring_id: u64, out_ptr: u64) -> Result<u64, SyscallError> {
72    if out_ptr == 0 {
73        return Err(SyscallError::Fault);
74    }
75
76    let task = crate::process::current_task_clone().ok_or(SyscallError::PermissionDenied)?;
77    let ring = require_owned_ring_by_id(ring_id)?;
78
79    let mapping = ring
80        .map_into_process(&task.process.address_space_arc())
81        .map_err(|_| SyscallError::OutOfMemory)?;
82
83    let abi = AsyncRingLayout {
84        sq_base: mapping.sq_base,
85        cq_base: mapping.cq_base,
86        sq_size: mapping.sq_size,
87        cq_size: mapping.cq_size,
88        entries: mapping.entries,
89        _reserved: 0,
90    };
91
92    let out = UserSliceWrite::new(out_ptr, core::mem::size_of::<AsyncRingLayout>())?;
93    let bytes = unsafe {
94        core::slice::from_raw_parts(
95            &abi as *const AsyncRingLayout as *const u8,
96            core::mem::size_of::<AsyncRingLayout>(),
97        )
98    };
99    out.copy_from(bytes);
100
101    Ok(mapping.sq_size.saturating_add(mapping.cq_size))
102}
103
104/// SYS_ASYNC_ENTER(ring_id: u64, to_submit: u32, min_complete: u32, flags: u32) => completed: u64
105pub fn sys_async_enter(
106    ring_id: u64,
107    to_submit: u64,
108    min_complete: u64,
109    _flags: u64,
110) -> Result<u64, SyscallError> {
111    let ring = require_owned_ring_by_id(ring_id)?;
112
113    let to_submit = to_submit as u32;
114    let min_complete = min_complete as u32;
115
116    // dispatch submitted SQEs to backends
117    if to_submit > 0 {
118        dispatch::drain_submissions(ring_id, to_submit);
119    }
120
121    crate::hardware::storage::ahci::flush_deferred_async_read_completions(ring_id);
122
123    // Drain up to `min_complete` completions.  The caller wants at least
124    // that many, so if fewer are available we block below.  Passing  `min_complete` as the "max" argument to `drain_completions` is correct.
125    // We never need more than `min_complete` in one round and the blocking path will loop via `wait_until` if needed.
126    // Retry parked IPC v2 operations in this (owner) context; any that
127    // complete post their CQE before the drain below.
128    let task = crate::process::current_task_clone().ok_or(SyscallError::PermissionDenied)?;
129    crate::ipc::v2::async_ops::poll(&task.process, ring_id);
130
131    let mut completed = complete::drain_completions(ring_id, min_complete);
132
133    // If caller asked for more completions than available, block and wait.
134    // An IPC v2 event (`ipc_kick`) ends the wait without a completion so the
135    // parked operations are retried here, outside the wait-queue lock.
136    while completed == 0 && min_complete > 0 {
137        let woke = ring.wq.wait_until(|| {
138            if ring.destroyed.load(core::sync::atomic::Ordering::Acquire) != 0 {
139                return Some(Some(0));
140            }
141
142            crate::hardware::storage::ahci::flush_deferred_async_read_completions(ring_id);
143
144            let ready = complete::drain_completions(ring_id, min_complete);
145            if ready > 0 {
146                return Some(Some(ready));
147            }
148            if ring.ipc_kick.swap(0, core::sync::atomic::Ordering::AcqRel) != 0 {
149                return Some(None);
150            }
151            if crate::process::signal::has_pending_signals() {
152                return Some(Some(0));
153            }
154            None
155        });
156        match woke {
157            Some(n) => {
158                completed = n;
159                break;
160            }
161            None => {
162                crate::ipc::v2::async_ops::poll(&task.process, ring_id);
163                completed = complete::drain_completions(ring_id, min_complete);
164            }
165        }
166    }
167
168    Ok(completed as u64)
169}
170
171/// SYS_ASYNC_CANCEL(ring_id: u64, user_data: u64, flags: u32) => result: u64
172pub fn sys_async_cancel(ring_id: u64, user_data: u64, flags: u64) -> Result<u64, SyscallError> {
173    let _ = require_owned_ring_by_id(ring_id)?;
174
175    if flags != 0 {
176        return Err(SyscallError::InvalidArgument);
177    }
178
179    crate::ipc::v2::async_ops::cancel(ring_id, user_data)?;
180
181    Ok(0)
182}
183
184/// SYS_ASYNC_DESTROY(ring_id: u64, flags: u32) => result: u64
185pub fn sys_async_destroy(ring_id: u64, _flags: u64) -> Result<u64, SyscallError> {
186    let _ = require_owned_ring_by_id(ring_id)?;
187
188    super::ring::destroy_ring(ring_id).map_err(|e| match e {
189        RingError::Alloc => SyscallError::OutOfMemory,
190        RingError::NotFound => SyscallError::BadHandle,
191        RingError::TooManyRings => SyscallError::InvalidArgument,
192    })?;
193
194    Ok(0)
195}