oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! What macOS alone has: POSIX asynchronous I/O, which is for files.
//!
//! `aio_read`, `aio_write` and `aio_fsync` hand an operation to the kernel,
//! which runs it on a thread of its own while the caller goes on. It is a
//! small thing next to io_uring (`io::linux`) and to completion ports
//! (`io::windows`), and this module is all of it:
//!
//! - **An [`Operation`]** (with the `alloc` feature): the memory the kernel
//!   refers to while an operation runs — the control block and the buffer —
//!   owned by one object, which starts a read, a write or a flush, tells
//!   its outcome, cancels it and hands the buffer back.
//! - **[`wait`]**: waiting until one of several operations is over, or a
//!   timeout passes (`aio_suspend`).
//! - **A [`Batch`]**: several reads and writes started with one call
//!   (`lio_listio`).
//! - **A notice by signal** (`Operation::set_notice`), which is what an
//!   [`event::Poller`](crate::event::Poller) can wait for: see
//!   [below](self#being-told-by-a-signal).
//! - **[`limits`]**: how few operations the system takes.
//!
//! ```no_run
//! # #[cfg(feature = "alloc")]
//! # fn main() -> oscall::Result<()> {
//! use oscall::fs::{self, OpenOptions};
//! use oscall::io::macos::{self, Operation};
//!
//! let file = fs::open("data", &OpenOptions::new().read(true))?;
//! let mut reads = [Operation::new(), Operation::new()];
//! reads[0].read(&file, Vec::with_capacity(4096), 0)?;
//! reads[1].read(&file, Vec::with_capacity(4096), 1 << 20)?;
//!
//! // ... the thread does something else, then wants one of them.
//! let over = macos::wait(&[&reads[0], &reads[1]], None)?.expect("no timeout");
//! let count = reads[over].result().expect("it is over")?;
//! let data = reads[over].take_buffer().expect("it was a read");
//! assert_eq!(data.len(), count);
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "alloc"))]
//! # fn main() {}
//! ```
//!
//! # What it does, and what it does not
//!
//! Everything here was measured on macOS 15 (x86_64) and macOS 26
//! (aarch64), which differ where it is said.
//!
//! - **Files, not pipes or sockets.** An operation is taken on what has
//!   positions: a file, and also a device or a FIFO, which are files to the
//!   kernel. On a pipe or a socket it is refused
//!   ([`NotSeekable`](crate::ErrorKind::NotSeekable)). Waiting until those
//!   can be read or written is what [`event`](crate::event) is for.
//! - **Few at a time.** A process has 16 operations at once, and the whole
//!   system 90 ([`limits`]): one more is refused with
//!   [`WouldBlock`](crate::ErrorKind::WouldBlock). The 16 are those of
//!   everything in the process that uses asynchronous I/O, and an
//!   operation counts from its start until its outcome is *taken*, not
//!   until it is over: see `Operation::result`.
//! - **Before macOS 26, every refusal is `WouldBlock`.** Whatever keeps an
//!   operation from being started — a handle that is closed, or not open
//!   for the operation, a pipe, too many operations — the kernel of macOS
//!   15 answers `EAGAIN`. macOS 26 tells them apart:
//!   [`BadHandle`](crate::ErrorKind::BadHandle),
//!   [`NotSeekable`](crate::ErrorKind::NotSeekable),
//!   [`InvalidInput`](crate::ErrorKind::InvalidInput).
//! - **A few threads of the kernel do the work**, and an operation that
//!   waits holds one. On macOS 15 they are four (`kern.aiothreads`), for
//!   all the processes of the system: with four reads waiting on a FIFO
//!   that nobody writes to, a read of a file was not started in two
//!   seconds, in that process or in another one. macOS 26 ran the sixteen
//!   reads of a process at once, and another process was not kept
//!   waiting. Keep this for files, which do not wait.
//! - **Nothing queues completions.** `kevent` refuses the filter made for
//!   it (`EVFILT_AIO`: `ENOTSUP` on macOS 15, `EPERM` on macOS 26). The
//!   program asks (`Operation::result`) or waits ([`wait`]), for the
//!   operations it names. The only notice the kernel gives is a signal,
//!   which says that *something* is over: see
//!   [below](self#being-told-by-a-signal).
//! - **Only what has not begun is cancelled.** `Operation::cancel` takes
//!   an operation no thread has started on out of the queue; one that runs,
//!   runs to its end. A read that waits on a FIFO cannot be stopped.
//! - **An operation that runs keeps its handle, and on macOS 15 its
//!   process.** Closing a handle cancels the operations still queued on
//!   it, and then *waits* for those that run: with a read of a FIFO in
//!   flight, `close` returned when the FIFO was written to, three seconds
//!   later. A process that exits waits for them too on macOS 15 (it was
//!   still there four seconds after it called `exit`), and not on macOS
//!   26. With files neither lasts.
//!
//! # Being told by a signal
//!
//! An operation can have the kernel send a signal to the process when it
//! is over (`Operation::set_notice`, and the notice of a [`Batch`]). With
//! the signals of [`process`](crate::process) that makes asynchronous I/O
//! one more thing an [`event::Poller`](crate::event::Poller) waits for:
//!
//! ```no_run
//! # #[cfg(feature = "alloc")]
//! # fn main() -> oscall::Result<()> {
//! use oscall::event::{Event, Poller};
//! use oscall::fs::{self, OpenOptions};
//! use oscall::io::macos::{self, Operation};
//! use oscall::process::unix::SignalExt;
//! use oscall::process::{Signal, Signals};
//!
//! let notice = Signal::from_raw(macos::SIGIO);
//! let signals = Signals::new(&[notice])?;
//! let poller = Poller::new()?;
//! poller.register_signals(&signals, 1)?;
//!
//! let file = fs::open("data", &OpenOptions::new().read(true))?;
//! let mut reads = [Operation::new(), Operation::new()];
//! for (i, read) in reads.iter_mut().enumerate() {
//!     read.set_notice(Some(notice));
//!     read.read(&file, Vec::with_capacity(4096), i as u64 * 4096)?;
//! }
//!
//! let mut events = [Event::EMPTY; 8];
//! let mut left = reads.len();
//! while left > 0 {
//!     let count = poller.wait(&mut events, None)?;
//!     for event in &events[..count] {
//!         if event.token() == 1 {
//!             while signals.try_next().is_some() {}
//!             // Something is over: every operation is asked.
//!             for read in &mut reads {
//!                 if let Some(buf) = read.take_buffer() {
//!                     left -= 1;
//!                     // ...
//! #                   drop(buf);
//!                 }
//!             }
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "alloc"))]
//! # fn main() {}
//! ```
//!
//! What that is, and what it is not:
//!
//! - **A signal carries no operation.** It says that an operation that
//!   asked for it is over, not which: the program asks each of those it
//!   has in flight. And signals merge: several operations that end
//!   before the program looks are told by one signal, or by several, as
//!   it falls. So one event of the poller stands for any number of
//!   completions, and now and then for none (an operation that was asked
//!   about before its signal was looked at).
//! - **The signal is the process's**, and a
//!   [`Signals`](crate::process::Signals) has it for the whole process:
//!   two parts of a program cannot each have their notices by the same
//!   signal, and a library that takes one takes it from its program.
//! - **A signal nobody listens to does what it does by default**, also
//!   when it comes from an operation: most end the process. [`SIGIO`] is
//!   the one to take: the system discards it when it has no handler, so
//!   that an operation that ends after its `Signals` is gone is harmless,
//!   and it is the signal made to say that I/O is possible. The kernel
//!   refuses `SIGKILL` for a notice.
//! - **The signal comes after the outcome is there**: when the program
//!   was told, [`result`](Operation::result) of the operation that ended
//!   was not `None`, each time it was tried.
//! - **A wait is interrupted by it.** The signal is delivered to a thread
//!   of the process, whichever the kernel picks; [`wait`] ends with
//!   [`Interrupted`](crate::ErrorKind::Interrupted) in that thread, as do
//!   the calls of other modules that say so.
//! - **A batch is told of once**, when the last of its operations is over.
//!
//! # Whose memory it is
//!
//! The kernel knows an operation by the address of its control block, and
//! writes what it reads to the buffer when the operation runs, wherever the
//! program has gone by then. An [`Operation`] makes that sound without
//! `unsafe`:
//!
//! - it owns the control block and the buffer, on the heap: moving the
//!   `Operation`, or forgetting it, moves or frees neither;
//! - while its operation is in flight it lends nothing out
//!   (`take_buffer` returns `None`) and starts nothing else
//!   ([`ResourceBusy`](crate::ErrorKind::ResourceBusy));
//! - **dropped in flight, it cancels the operation and waits for it to be
//!   over** (`aio_cancel`, `aio_suspend`) before the memory is freed, and
//!   takes its outcome so that the place it held is free again. An
//!   operation on a file that has begun is over in the time the file
//!   takes; one that waits (a FIFO) may never be: after a few seconds the
//!   memory is leaked instead, never freed under the kernel, and the place
//!   is lost to the process. Its handle is still not one to close: see
//!   above.
//!
//! An operation can also read into, or write from, memory the caller
//! keeps (`Operation::read_kept`, `Operation::write_kept`): for a buffer
//! that is part of something larger, or that is not a `Vec`. Those are
//! `unsafe`: the caller then answers for the memory until the operation
//! is over, and the control block is still the `Operation`'s.

#[cfg(feature = "alloc")]
use crate::ErrorKind;
use crate::Result;
use crate::sys::aio as sys;

/// How much asynchronous I/O the system takes: see [`limits`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Limits {
    /// How many operations the whole system has at a time, all processes
    /// together (`kern.aiomax`): 90 unless the administrator changed it.
    pub system: u32,
    /// How many operations one process has at a time (`kern.aioprocmax`):
    /// 16 unless the administrator changed it. An operation counts from
    /// its start until its outcome is taken.
    pub process: u32,
    /// The value of `kern.aiothreads`, 4 by default: on macOS 15, how many
    /// threads of the kernel run the operations of all the processes.
    /// macOS 26 has the value, and runs more operations at once than it
    /// says.
    pub threads: u32,
}

/// Reads the limits of asynchronous I/O.
///
/// `sysctlbyname`, three times. The values are the system's as a whole;
/// how many operations other parts of the process, or other processes,
/// have in flight is not told.
pub fn limits() -> Result<Limits> {
    let (system, process, threads) = sys::limits()?;
    Ok(Limits {
        system,
        process,
        threads,
    })
}

/// The number of `SIGIO`, the signal to have for the notice of an
/// operation (`Operation::set_notice`): one that is discarded when nobody
/// listens to it, where most end the process. See the
/// [module documentation](self#being-told-by-a-signal).
pub const SIGIO: i32 = 23;

/// How many operations a `Batch` takes: the `AIO_LISTIO_MAX` of the
/// kernel, 16, which is also how many a process has at a time unless the
/// administrator raised that ([`limits`]).
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;

    /// How long a dropped operation is waited for, once cancelled, before
    /// its memory is given up for lost.
    const DROP_PATIENCE: Duration = Duration::from_secs(5);

    /// How many operations [`wait`] lists without allocating: twice what a
    /// process may have in flight by default.
    const INLINE: usize = 32;

    #[derive(Clone, Copy, PartialEq, Eq)]
    enum State {
        /// Nothing was started, or the start was refused.
        Idle,
        /// The kernel has the operation, which holds a place.
        InFlight,
        /// The outcome was taken from the kernel, which has forgotten the
        /// operation.
        Done,
    }

    /// What the kernel refers to while an operation runs. It lives on the
    /// heap, at an address that does not change, until no operation is in
    /// flight.
    struct Inner {
        /// The kernel knows the operation by this address.
        cb: UnsafeCell<Aiocb>,
        state: Cell<State>,
        /// What the operation came to, once `state` is `Done`.
        outcome: Cell<Option<Result<usize>>>,
        /// The descriptor the operation was started on, which `aio_cancel`
        /// wants.
        fd: i32,
        request: Request,
        buf: Vec<u8>,
        /// Whether `buf` is a buffer the caller gave and has not taken
        /// back.
        has_buf: bool,
        /// The signal that tells of a completion, if one was asked for.
        notice: Option<i32>,
    }

    /// The memory an operation reads into or writes from.
    enum Memory {
        /// None: a flush.
        None,
        /// A buffer the operation owns until it is taken back.
        Owned(Vec<u8>),
        /// Memory the caller keeps, by the contract of an `unsafe`
        /// function.
        Kept(*mut u8, usize),
    }

    /// The memory of one asynchronous operation at a time, and the means
    /// to start it, to know its outcome and to cancel it. See the
    /// [module documentation](super#whose-memory-it-is).
    ///
    /// An `Operation` is made once and used again and again: starting an
    /// operation takes `&mut self` and fails with
    /// [`ResourceBusy`](ErrorKind::ResourceBusy) while the previous one is
    /// in flight. It holds one allocation for its lifetime.
    ///
    /// The handle an operation is started on is not borrowed. Closing it
    /// while the operation is in flight is not unsound, and waits: see the
    /// [module documentation](super#what-it-does-and-what-it-does-not).
    ///
    /// It is `Send` and not `Sync`: an operation does not belong to the
    /// thread that started it, and goes on when that thread ends, but its
    /// outcome is taken from the kernel once, by whoever asks first.
    pub struct Operation(NonNull<Inner>);

    // SAFETY: the memory is owned, and the kernel does not care which
    // thread started an operation or asks about it.
    unsafe impl Send for Operation {}

    impl Operation {
        /// Makes an operation that has not started anything. This
        /// allocates, and asks nothing of the system.
        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)))
        }

        /// Asks for `signal` to be sent to the process each time an
        /// operation this one starts from now on is over, or with `None`
        /// for nothing to be sent, which is how an `Operation` is made.
        ///
        /// This is the one notice the kernel gives, and what lets a
        /// program wait for operations along with everything else: a
        /// [`Signals`](crate::process::Signals) that listens to the
        /// signal is told of it, and an
        /// [`event::Poller`](crate::event::Poller) waits for a `Signals`
        /// ([`register_signals`](crate::event::Poller::register_signals)).
        /// See the [module documentation](super#being-told-by-a-signal)
        /// for what the signal says and what it does not, and for which
        /// signal to take.
        ///
        /// A signal the kernel does not take for a notice (a number that
        /// is no signal, `SIGKILL`) is refused when an operation is
        /// started
        /// ([`InvalidInput`](ErrorKind::InvalidInput);
        /// [`WouldBlock`](ErrorKind::WouldBlock) before macOS 26). The
        /// operations of a [`Batch`] are not told of one by one: the
        /// batch has a notice of its own.
        ///
        /// `SIGEV_SIGNAL` in the `aio_sigevent` of the control block.
        pub fn set_notice(&mut self, signal: Option<Signal>) {
            let signal = signal.map(|signal| signal.0);
            // SAFETY: only this member is touched, which the kernel knows
            // nothing of: the block of an operation in flight is left
            // alone.
            unsafe { (*self.0.as_ptr()).notice = signal };
        }

        fn inner(&self) -> &Inner {
            // SAFETY: the allocation lives as long as `self`. The block
            // the kernel is given is in an `UnsafeCell`, and what `&self`
            // changes is in `Cell`s: an `Operation` is not `Sync`.
            unsafe { self.0.as_ref() }
        }

        /// Whether the kernel still has an operation whose outcome was
        /// not taken.
        fn in_flight(&self) -> bool {
            self.inner().state.get() == State::InFlight
        }

        /// Whether an operation was started and is not over yet: the
        /// kernel may still read or write the buffer.
        ///
        /// This asks the kernel, as [`result`](Self::result) does.
        pub fn is_pending(&self) -> bool {
            self.result().is_none() && self.in_flight()
        }

        /// What the kernel does not touch, for an operation that is not
        /// in flight.
        fn idle(&mut self) -> Result<&mut Inner> {
            if self.is_pending() {
                return Err(ErrorKind::ResourceBusy.into());
            }
            // SAFETY: nothing is in flight: the kernel has no use of the
            // allocation, and `self` is borrowed mutably.
            Ok(unsafe { self.0.as_mut() })
        }

        /// Describes an operation in the control block, and takes its
        /// memory, without starting it: the operation has started nothing,
        /// and an owned buffer can be taken back.
        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)?;
            // SAFETY: the block and an owned buffer belong to the
            // allocation, which lives until the outcome of the operation
            // was taken: `Drop` sees to it. Memory the caller keeps is
            // the caller's to keep, by the contract of the function that
            // took it.
            unsafe { sys::submit(inner.cb.get_mut(), request) }?;
            inner.state.set(State::InFlight);
            Ok(())
        }

        /// Starts reading from `handle` into `buf`, at `offset` bytes from
        /// the start of the file: up to the capacity of `buf`, replacing
        /// what it holds.
        ///
        /// Once the operation is over, [`result`](Self::result) has the
        /// count and [`take_buffer`](Self::take_buffer) the buffer, whose
        /// length is that count. At or after the end of the file the
        /// count is 0, which is not an error.
        ///
        /// The position of the handle is neither used nor moved. On what
        /// has none to speak of (a device, a FIFO), `offset` is ignored.
        /// At most `i32::MAX` bytes are read at once.
        ///
        /// On an error nothing was started and the buffer can be taken
        /// back. What is wrong with the handle is told here, when the
        /// operation is started (see the
        /// [module documentation](super#what-it-does-and-what-it-does-not)
        /// for the errors, and for macOS 15); what goes wrong with the
        /// reading itself is the outcome of the operation (a directory:
        /// [`IsADirectory`](ErrorKind::IsADirectory)). Fails with
        /// [`ResourceBusy`](ErrorKind::ResourceBusy) if the previous
        /// operation is still in flight, and then leaves `buf` to be
        /// dropped.
        ///
        /// `aio_read`.
        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)
        }

        /// [`read`](Self::read) into memory the caller keeps: up to `len`
        /// bytes at `ptr`. There is no buffer to take back; the outcome is
        /// the count of bytes the kernel wrote there. A null pointer is
        /// refused whatever the length
        /// ([`InvalidInput`](ErrorKind::InvalidInput)).
        ///
        /// # Safety
        ///
        /// The `len` bytes at `ptr` must be writable, and nothing else may
        /// read or write them, from this call until the operation is
        /// over: until [`result`](Self::result) is not `None`, or
        /// [`is_pending`](Self::is_pending) is false, or this returned an
        /// error. Dropping the `Operation` does not end that: dropped in
        /// flight it waits for its operation, but for a few seconds only
        /// (see the [module documentation](super#whose-memory-it-is)),
        /// after which the kernel may still write. Memory that can go
        /// away is waited for with [`wait`] first.
        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)
        }

        /// Starts writing `buf` to `handle`, at `offset` bytes from the
        /// start of the file; at its end, whatever `offset` is, on a
        /// handle opened for appending.
        ///
        /// The outcome is the count of bytes written. Writing past the end
        /// extends the file, and the gap reads as zeroes. Errors are as
        /// for [`read`](Self::read).
        ///
        /// `aio_write`.
        pub fn write(&mut self, handle: impl AsHandle, buf: Vec<u8>, offset: u64) -> Result<()> {
            self.start(handle, Request::Write, Memory::Owned(buf), offset)
        }

        /// [`write`](Self::write) from memory the caller keeps: the `len`
        /// bytes at `ptr`.
        ///
        /// # Safety
        ///
        /// The `len` bytes at `ptr` must be readable, and nothing may
        /// write them, from this call until the operation is over, as for
        /// [`read_kept`](Self::read_kept).
        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)
        }

        /// Starts writing what the system holds of the file to its
        /// storage: all of it, or with `data_only` what is needed to read
        /// the data back. The outcome is 0.
        ///
        /// **The handle must be open for writing**
        /// ([`BadHandle`](ErrorKind::BadHandle) otherwise), which
        /// [`fs::sync_all`](crate::fs::sync_all) does not ask. And this is
        /// the system's `fsync`, which hands the data to the drive without
        /// asking the drive to write its cache: `fs::sync_all` does ask
        /// (`F_FULLFSYNC`), and there is no asynchronous form of that.
        ///
        /// `aio_fsync`, with `O_SYNC` or `O_DSYNC`.
        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)
        }

        /// The outcome of the operation: `None` while it is in flight, or
        /// if none was started; then the count of bytes transferred, or
        /// the error. An operation that was cancelled fails with
        /// [`Canceled`](ErrorKind::Canceled).
        ///
        /// The first call that finds the operation over takes its outcome
        /// from the kernel, which **frees the place the operation held**
        /// among the few a process has ([`limits`](super::limits)): an
        /// operation that is over and was not asked about still counts.
        /// The outcome is kept, and told again until another operation is
        /// started. [`is_pending`](Self::is_pending),
        /// [`take_buffer`](Self::take_buffer), [`wait`] and dropping the
        /// `Operation` take it as well.
        ///
        /// `aio_error`, then `aio_return` the first time the operation is
        /// over.
        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 => {
                    // SAFETY: the block is the one the operation in flight
                    // was started with, and its outcome was not taken: the
                    // state says both.
                    let outcome = unsafe { sys::take(inner.cb.get()) }?;
                    inner.outcome.set(Some(outcome));
                    inner.state.set(State::Done);
                    Some(outcome)
                }
            }
        }

        /// Asks the kernel to give up the operation in flight. `Ok(true)`
        /// if it did: the operation is over, and its outcome is
        /// [`Canceled`](ErrorKind::Canceled). `Ok(false)` if there is
        /// nothing to cancel (no operation, or one that is over), or if a
        /// thread of the kernel has started on the operation: it then
        /// runs to its end, and has its own outcome.
        ///
        /// `aio_cancel`.
        pub fn cancel(&self) -> Result<bool> {
            if !self.is_pending() {
                return Ok(false);
            }
            let inner = self.inner();
            // SAFETY: the block is allocated, and is the one of an
            // operation in flight.
            unsafe { sys::cancel(inner.fd, inner.cb.get()) }
        }

        /// The buffer of the operation, once it is not in flight: `None`
        /// until then, for a [`sync`](Self::sync), and once taken.
        ///
        /// After a read its length is the count of bytes read (0 if the
        /// operation failed); after a write it is as it was given.
        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 {
                // SAFETY: the kernel wrote that many bytes at the start of
                // the buffer, and never more than its capacity.
                unsafe { buf.set_len(count.min(buf.capacity())) };
            }
            Some(buf)
        }
    }

    /// Several reads and writes to start with one call: `lio_listio`.
    ///
    /// Each is described as it would be started, with the [`Operation`]
    /// that is to hold it, which the batch borrows; nothing is asked of
    /// the system until [`submit`](Self::submit) or
    /// [`submit_and_wait`](Self::submit_and_wait). A batch that is
    /// dropped instead has started nothing, and the buffers can be taken
    /// back from the operations.
    ///
    /// ```no_run
    /// # fn main() -> oscall::Result<()> {
    /// use oscall::fs::{self, OpenOptions};
    /// use oscall::io::macos::{Batch, Operation};
    ///
    /// let file = fs::open("data", &OpenOptions::new().read(true))?;
    /// let mut reads = [Operation::new(), Operation::new()];
    /// let mut batch = Batch::new();
    /// for (i, read) in reads.iter_mut().enumerate() {
    ///     batch.read(read, &file, Vec::with_capacity(4096), i as u64 * 4096)?;
    /// }
    /// batch.submit_and_wait()?;
    /// for read in &mut reads {
    ///     let count = read.result().expect("it is over")?;
    ///     assert_eq!(read.take_buffer().expect("it was a read").len(), count);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// What a batch saves is system calls: its operations are queued one
    /// by one all the same, each holds a place of the process
    /// ([`limits`](super::limits)), and each has its own outcome. A flush
    /// cannot be part of one.
    pub struct Batch<'a> {
        operations: [Option<&'a mut Operation>; BATCH_MAX],
        count: usize,
    }

    impl<'a> Batch<'a> {
        /// A batch of nothing.
        pub fn new() -> Self {
            Self {
                operations: [const { None }; BATCH_MAX],
                count: 0,
            }
        }

        /// How many operations the batch has.
        #[inline]
        pub fn len(&self) -> usize {
            self.count
        }

        /// Whether the batch has no operation.
        #[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)?;
            // The notice of a list is the list's: none of its
            // operations is told of by itself.
            inner.cb.get_mut().set_notice(None);
            self.operations[self.count] = Some(operation);
            self.count += 1;
            Ok(())
        }

        /// Adds a read, as [`Operation::read`] would start it, which
        /// `operation` is to hold.
        ///
        /// Fails with [`InvalidInput`](ErrorKind::InvalidInput) when the
        /// batch is full ([`BATCH_MAX`]) or for an offset the system
        /// cannot hold, and with
        /// [`ResourceBusy`](ErrorKind::ResourceBusy) if `operation` is in
        /// flight. Nothing is asked of the system: what is wrong with
        /// the handle is told when the batch is submitted.
        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)
        }

        /// Adds a write, as [`Operation::write`] would start it. Errors
        /// are as for [`read`](Self::read).
        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,
            )
        }

        /// Adds a read into memory the caller keeps, as
        /// [`Operation::read_kept`] would start it.
        ///
        /// # Safety
        ///
        /// As [`Operation::read_kept`], from the moment the batch is
        /// submitted, whatever the submission returns.
        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)
        }

        /// Adds a write from memory the caller keeps, as
        /// [`Operation::write_kept`] would start it.
        ///
        /// # Safety
        ///
        /// As [`Operation::write_kept`], from the moment the batch is
        /// submitted, whatever the submission returns.
        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);
            // SAFETY: each block is the one of an `Operation`, prepared
            // by `add`, which nothing else can have started: the batch
            // borrows it. The blocks and the buffers live until the
            // outcomes were taken, as for one operation.
            let submitted = unsafe { sys::submit_list(&list[..self.count], wait, notice) };
            // Whatever the call said, the kernel has what it has.
            for operation in self.operations.iter().flatten() {
                let inner = operation.inner();
                // SAFETY: the block is allocated.
                if unsafe { sys::submitted(inner.cb.get()) } {
                    inner.state.set(State::InFlight);
                }
            }
            submitted
        }

        /// Starts the operations of the batch, and returns once the
        /// kernel has them. With `notice`, that signal is sent to the
        /// process **once, when the last of them is over**, in the place
        /// of whatever notice each [`Operation`] was
        /// [set](Operation::set_notice) to give; with `None` nothing is
        /// sent.
        ///
        /// **An error does not always mean that nothing was started**,
        /// and each `Operation` says what became of it: one that was
        /// started is in flight or over, as ever; one that was not has
        /// no [`result`](Operation::result), is not
        /// [pending](Operation::is_pending), and its buffer can be taken
        /// back. As measured on macOS 15 and 26:
        ///
        /// - the kernel looks at every operation before it starts any.
        ///   If it refuses one for what it is (the refusals of
        ///   [`Operation::read`]: a handle that is not open for it, a
        ///   pipe), **none is started**, and that refusal is the error;
        /// - if the process has too few places left for all of them
        ///   ([`WouldBlock`](ErrorKind::WouldBlock)), **the first ones
        ///   of the batch are started**, as many as there were places.
        ///
        /// An empty batch fails with
        /// [`InvalidInput`](ErrorKind::InvalidInput).
        ///
        /// `lio_listio` with `LIO_NOWAIT`.
        pub fn submit(self, notice: Option<Signal>) -> Result<()> {
            self.submit_list(false, notice)
        }

        /// Starts the operations of the batch and waits until they are
        /// all over: when this returns `Ok`, every
        /// [`result`](Operation::result) is there. No signal is sent.
        ///
        /// The outcome of an operation is its own: that one failed is
        /// not an error here. An error is a refusal, as for
        /// [`submit`](Self::submit), and then the operations that were
        /// started, if any were, may still be in flight: so too when a
        /// signal that is handled ends the wait
        /// ([`Interrupted`](ErrorKind::Interrupted)).
        ///
        /// `lio_listio` with `LIO_WAIT`.
        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() {
                // Whatever this says, the operation has to be over before
                // the memory goes.
                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 {
                        // The kernel still refers to the buffer: it is
                        // its own from now on.
                        return;
                    };
                    // SAFETY: the operation of the block is in flight. A
                    // wait that a signal interrupted is started again.
                    let _ = unsafe { sys::suspend(&list, Some(left)) };
                }
            }
            // SAFETY: the allocation was made by `Box` in `new`, nothing
            // is in flight, and nothing else refers to it.
            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()
        }
    }

    /// Waits until one of `operations` is over, or `timeout` passes, and
    /// returns its place in the slice: `None` means the timeout passed.
    ///
    /// The first operation of the slice that is over is told, **and is
    /// told again by the next call** for as long as it is listed: an
    /// outcome stays until its `Operation` starts something else. Leave
    /// out those that were seen. An operation that has started nothing is
    /// passed over; if none of them is in flight or over, there is
    /// nothing to wait for and this fails with
    /// [`InvalidInput`](ErrorKind::InvalidInput).
    ///
    /// The outcome of the operation that is told has been taken from the
    /// kernel: [`Operation::result`] has it. Only the operations listed
    /// end the wait; there is no waiting for whichever operation of the
    /// process comes first.
    ///
    /// `timeout` never ends early; `None` waits for as long as it takes,
    /// zero only looks. A signal that is handled ends the wait with
    /// [`Interrupted`](ErrorKind::Interrupted).
    ///
    /// `aio_suspend`, once, unless an operation is over already.
    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 {
                // More than a process has by default: the limit was
                // raised.
                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[..]
        };
        // SAFETY: every block of the list is the one of an operation in
        // flight, whose outcome was not taken.
        if !unsafe { sys::suspend(list, timeout) }? {
            return Ok(None);
        }
        Ok(operations
            .iter()
            .position(|operation| operation.result().is_some()))
    }
}