#[cfg(feature = "alloc")]
use crate::ErrorKind;
use crate::Result;
use crate::sys::aio as sys;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Limits {
pub system: u32,
pub process: u32,
pub threads: u32,
}
pub fn limits() -> Result<Limits> {
let (system, process, threads) = sys::limits()?;
Ok(Limits {
system,
process,
threads,
})
}
pub const SIGIO: i32 = 23;
pub const BATCH_MAX: usize = sys::LISTIO_MAX;
#[cfg(feature = "alloc")]
pub use operation::{Batch, Operation, wait};
#[cfg(feature = "alloc")]
mod operation {
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::cell::{Cell, UnsafeCell};
use core::fmt;
use core::ptr::NonNull;
use core::time::Duration;
use super::{BATCH_MAX, ErrorKind, Result, sys};
use crate::AsHandle;
use crate::process::Signal;
use crate::sys::aio::{Aiocb, Request};
use crate::time::Clock;
const DROP_PATIENCE: Duration = Duration::from_secs(5);
const INLINE: usize = 32;
#[derive(Clone, Copy, PartialEq, Eq)]
enum State {
Idle,
InFlight,
Done,
}
struct Inner {
cb: UnsafeCell<Aiocb>,
state: Cell<State>,
outcome: Cell<Option<Result<usize>>>,
fd: i32,
request: Request,
buf: Vec<u8>,
has_buf: bool,
notice: Option<i32>,
}
enum Memory {
None,
Owned(Vec<u8>),
Kept(*mut u8, usize),
}
pub struct Operation(NonNull<Inner>);
unsafe impl Send for Operation {}
impl Operation {
pub fn new() -> Self {
let inner = Box::new(Inner {
cb: UnsafeCell::new(Aiocb::new()),
state: Cell::new(State::Idle),
outcome: Cell::new(None),
fd: -1,
request: Request::Read,
buf: Vec::new(),
has_buf: false,
notice: None,
});
Self(NonNull::from(Box::leak(inner)))
}
pub fn set_notice(&mut self, signal: Option<Signal>) {
let signal = signal.map(|signal| signal.0);
unsafe { (*self.0.as_ptr()).notice = signal };
}
fn inner(&self) -> &Inner {
unsafe { self.0.as_ref() }
}
fn in_flight(&self) -> bool {
self.inner().state.get() == State::InFlight
}
pub fn is_pending(&self) -> bool {
self.result().is_none() && self.in_flight()
}
fn idle(&mut self) -> Result<&mut Inner> {
if self.is_pending() {
return Err(ErrorKind::ResourceBusy.into());
}
Ok(unsafe { self.0.as_mut() })
}
fn prepare(
&mut self,
handle: impl AsHandle,
request: Request,
memory: Memory,
offset: u64,
) -> Result<&mut Inner> {
let fd = handle.as_handle().as_raw();
let offset = i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput)?;
let inner = self.idle()?;
inner.state.set(State::Idle);
inner.outcome.set(None);
inner.fd = fd;
inner.request = request;
inner.has_buf = matches!(memory, Memory::Owned(_));
let (ptr, len) = match memory {
Memory::None => {
inner.buf = Vec::new();
(core::ptr::null_mut(), 0)
}
Memory::Owned(buf) => {
inner.buf = buf;
let len = match request {
Request::Read => inner.buf.capacity(),
_ => inner.buf.len(),
};
(inner.buf.as_mut_ptr(), len)
}
Memory::Kept(ptr, len) => {
inner.buf = Vec::new();
(ptr, len)
}
};
let notice = inner.notice;
let cb = inner.cb.get_mut();
cb.set(fd, ptr, len, offset);
cb.set_notice(notice);
cb.set_listed(request);
Ok(inner)
}
fn start(
&mut self,
handle: impl AsHandle,
request: Request,
memory: Memory,
offset: u64,
) -> Result<()> {
let inner = self.prepare(handle, request, memory, offset)?;
unsafe { sys::submit(inner.cb.get_mut(), request) }?;
inner.state.set(State::InFlight);
Ok(())
}
pub fn read(&mut self, handle: impl AsHandle, mut buf: Vec<u8>, offset: u64) -> Result<()> {
buf.clear();
self.start(handle, Request::Read, Memory::Owned(buf), offset)
}
pub unsafe fn read_kept(
&mut self,
handle: impl AsHandle,
ptr: *mut u8,
len: usize,
offset: u64,
) -> Result<()> {
self.start(handle, Request::Read, Memory::Kept(ptr, len), offset)
}
pub fn write(&mut self, handle: impl AsHandle, buf: Vec<u8>, offset: u64) -> Result<()> {
self.start(handle, Request::Write, Memory::Owned(buf), offset)
}
pub unsafe fn write_kept(
&mut self,
handle: impl AsHandle,
ptr: *const u8,
len: usize,
offset: u64,
) -> Result<()> {
let memory = Memory::Kept(ptr.cast_mut(), len);
self.start(handle, Request::Write, memory, offset)
}
pub fn sync(&mut self, handle: impl AsHandle, data_only: bool) -> Result<()> {
let request = if data_only {
Request::SyncData
} else {
Request::Sync
};
self.start(handle, request, Memory::None, 0)
}
pub fn result(&self) -> Option<Result<usize>> {
let inner = self.inner();
match inner.state.get() {
State::Idle => None,
State::Done => inner.outcome.get(),
State::InFlight => {
let outcome = unsafe { sys::take(inner.cb.get()) }?;
inner.outcome.set(Some(outcome));
inner.state.set(State::Done);
Some(outcome)
}
}
}
pub fn cancel(&self) -> Result<bool> {
if !self.is_pending() {
return Ok(false);
}
let inner = self.inner();
unsafe { sys::cancel(inner.fd, inner.cb.get()) }
}
pub fn take_buffer(&mut self) -> Option<Vec<u8>> {
let count = self.result().and_then(Result::ok).unwrap_or(0);
let inner = self.idle().ok()?;
if !inner.has_buf {
return None;
}
inner.has_buf = false;
let mut buf = core::mem::take(&mut inner.buf);
if inner.request == Request::Read {
unsafe { buf.set_len(count.min(buf.capacity())) };
}
Some(buf)
}
}
pub struct Batch<'a> {
operations: [Option<&'a mut Operation>; BATCH_MAX],
count: usize,
}
impl<'a> Batch<'a> {
pub fn new() -> Self {
Self {
operations: [const { None }; BATCH_MAX],
count: 0,
}
}
#[inline]
pub fn len(&self) -> usize {
self.count
}
#[inline]
pub fn is_empty(&self) -> bool {
self.count == 0
}
fn add(
&mut self,
operation: &'a mut Operation,
handle: impl AsHandle,
request: Request,
memory: Memory,
offset: u64,
) -> Result<()> {
if self.count == BATCH_MAX {
return Err(ErrorKind::InvalidInput.into());
}
let inner = operation.prepare(handle, request, memory, offset)?;
inner.cb.get_mut().set_notice(None);
self.operations[self.count] = Some(operation);
self.count += 1;
Ok(())
}
pub fn read(
&mut self,
operation: &'a mut Operation,
handle: impl AsHandle,
mut buf: Vec<u8>,
offset: u64,
) -> Result<()> {
buf.clear();
self.add(operation, handle, Request::Read, Memory::Owned(buf), offset)
}
pub fn write(
&mut self,
operation: &'a mut Operation,
handle: impl AsHandle,
buf: Vec<u8>,
offset: u64,
) -> Result<()> {
self.add(
operation,
handle,
Request::Write,
Memory::Owned(buf),
offset,
)
}
pub unsafe fn read_kept(
&mut self,
operation: &'a mut Operation,
handle: impl AsHandle,
ptr: *mut u8,
len: usize,
offset: u64,
) -> Result<()> {
let memory = Memory::Kept(ptr, len);
self.add(operation, handle, Request::Read, memory, offset)
}
pub unsafe fn write_kept(
&mut self,
operation: &'a mut Operation,
handle: impl AsHandle,
ptr: *const u8,
len: usize,
offset: u64,
) -> Result<()> {
let memory = Memory::Kept(ptr.cast_mut(), len);
self.add(operation, handle, Request::Write, memory, offset)
}
fn submit_list(self, wait: bool, notice: Option<Signal>) -> Result<()> {
if self.count == 0 {
return Err(ErrorKind::InvalidInput.into());
}
let mut list = [core::ptr::null_mut::<Aiocb>(); BATCH_MAX];
for (place, operation) in list.iter_mut().zip(self.operations.iter().flatten()) {
*place = operation.inner().cb.get();
}
let notice = notice.map(|signal| signal.0);
let submitted = unsafe { sys::submit_list(&list[..self.count], wait, notice) };
for operation in self.operations.iter().flatten() {
let inner = operation.inner();
if unsafe { sys::submitted(inner.cb.get()) } {
inner.state.set(State::InFlight);
}
}
submitted
}
pub fn submit(self, notice: Option<Signal>) -> Result<()> {
self.submit_list(false, notice)
}
pub fn submit_and_wait(self) -> Result<()> {
self.submit_list(true, None)
}
}
impl Default for Batch<'_> {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Batch<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Batch")
.field("len", &self.count)
.finish_non_exhaustive()
}
}
impl Default for Operation {
fn default() -> Self {
Self::new()
}
}
impl Drop for Operation {
fn drop(&mut self) {
if self.is_pending() {
let _ = self.cancel();
let list = [self.inner().cb.get().cast_const()];
let start = Clock::Monotonic.now();
while self.result().is_none() {
let left = match (start, Clock::Monotonic.now()) {
(Ok(start), Ok(now)) => {
DROP_PATIENCE.checked_sub(now.saturating_sub(start))
}
_ => None,
};
let Some(left) = left.filter(|left| !left.is_zero()) else {
return;
};
let _ = unsafe { sys::suspend(&list, Some(left)) };
}
}
drop(unsafe { Box::from_raw(self.0.as_ptr()) });
}
}
impl fmt::Debug for Operation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Operation")
.field("result", &self.result())
.finish_non_exhaustive()
}
}
pub fn wait(operations: &[&Operation], timeout: Option<Duration>) -> Result<Option<usize>> {
let mut inline = [core::ptr::null::<Aiocb>(); INLINE];
let mut spilled = Vec::new();
let mut count = 0;
for (index, operation) in operations.iter().enumerate() {
if operation.result().is_some() {
return Ok(Some(index));
}
if !operation.in_flight() {
continue;
}
let cb = operation.inner().cb.get().cast_const();
if count < INLINE {
inline[count] = cb;
} else {
if spilled.is_empty() {
spilled.extend_from_slice(&inline);
}
spilled.push(cb);
}
count += 1;
}
if count == 0 {
return Err(ErrorKind::InvalidInput.into());
}
let list = if count <= INLINE {
&inline[..count]
} else {
&spilled[..]
};
if !unsafe { sys::suspend(list, timeout) }? {
return Ok(None);
}
Ok(operations
.iter()
.position(|operation| operation.result().is_some()))
}
}