1use std::{
2 os::fd::{AsFd, BorrowedFd, OwnedFd},
3 ptr,
4};
5
6use dope_sys::{
7 Cloexec, Nonblock,
8 engine::{life, life::Error, ring::Backend as _},
9 io::{
10 fd::{self, Fd},
11 socket::{Setup, Socket as _, addr, option::tuning::Quiesce as _},
12 },
13 probe::Stopped,
14 ring::ready::Ready as _,
15 thread::{self, Thread},
16};
17use o3::depot;
18
19use crate::{
20 Accepted, Borrowed, Canary, Closing, Context, Control, Cpus, Encoded, Engine, Enter, Errno,
21 Fault, Fifo, Infallible, MAX, Observe, Outcome, Payload, Poll, Primary, Producer, Range, Ready,
22 Recover, Released, Resources, Ring, Selected, Session, Table, Timer, Waiting, accept, admit,
23 affinity, bounded, buffer, buffers, complete, cq, create,
24 driver::{Quiesced, tuning::Progress},
25 engine, enter, errno, error, fast, file, gso, host, kernel, mem, memory, num, op, option,
26 permit, pipe, probe, provided, record, ring, socket, sq, submit,
27 system::signal,
28 token, tuning, types,
29};
30
31#[derive(Debug)]
32pub struct Uring;
33
34impl Uring {
35 fn open_with(flags: libc::c_int) -> Result<(OwnedFd, OwnedFd), pipe::Error> {
36 let mut fds = [0; 2];
37 let result = unsafe { libc::pipe2(fds.as_mut_ptr(), flags) };
39 unsafe { fd::raw::Pair::new(fds).try_adopt::<Self, Errno>(result) }
41 .map_err(pipe::Error::Open)
42 }
43
44 pub(crate) unsafe fn status(raw: libc::c_long) -> kernel::raw::Status<-1, { i32::MAX }> {
47 const { assert!(mem::size_of::<libc::c_long>() == mem::size_of::<libc::ssize_t>()) };
48 unsafe { kernel::raw::Status::from_count(raw as libc::ssize_t) }
51 }
52
53 pub(crate) fn try_map<const FLAGS: libc::c_int>(
55 bytes: num::NonZero<usize>,
56 ) -> Result<*mut libc::c_void, Errno> {
57 const { assert!(FLAGS & !libc::MAP_NORESERVE == 0) };
58 let address = unsafe {
60 libc::mmap(
61 ptr::null_mut(),
62 bytes.get(),
63 libc::PROT_READ | libc::PROT_WRITE,
64 libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | FLAGS,
65 -1,
66 0,
67 )
68 };
69 if address == libc::MAP_FAILED {
70 Err(unsafe { kernel::raw::Code::last::<Self>().into() })
72 } else {
73 Ok(address)
74 }
75 }
76
77 pub(crate) unsafe fn try_unmap<E: From<Errno>>(
81 address: *mut libc::c_void,
82 bytes: num::NonZero<usize>,
83 ) -> Result<(), E> {
84 let result = unsafe { libc::munmap(address, bytes.get()) };
86 unsafe { kernel::raw::Status::new(result).try_zero::<Self, E>() }
88 }
89}
90
91impl accept::Source for Uring {
92 type Failure<F: From<Errno>> = Errno;
93
94 const MAX_IN_FLIGHT: num::NonZero<usize> = num::NonZero::<usize>::MAX;
95
96 fn is_retryable(error: Errno) -> bool {
97 error.is_block()
98 || matches!(
99 error.code().get(),
100 libc::EINTR
101 | libc::ECONNABORTED
102 | libc::ENETDOWN
103 | libc::EPROTO
104 | libc::ENOPROTOOPT
105 | libc::EHOSTDOWN
106 | libc::ENONET
107 | libc::EHOSTUNREACH
108 | libc::EOPNOTSUPP
109 | libc::ENETUNREACH
110 )
111 }
112
113 fn can_defer(error: Errno) -> bool {
114 error.code().get() == libc::ENFILE
115 }
116}
117
118impl<L: Copy + Eq> buffer::Selection<L> for Uring {
119 type Error = (<Self as provided::Source>::Index, L);
120}
121
122impl<C: Context> engine::Source<C> for Uring {
123 type Backend = Engine<C>;
124 type Closing = Closing<C>;
125}
126
127impl<C, P, R> engine::Storage<C, P, R> for Uring
128where
129 C: Context<Layout: memory::raw::Canary>,
130 P: Copy + From<Primary> + From<memory::Error>,
131 R: Copy,
132{
133 type Cleanup = <Self as create::Source>::Resources<C::Token, C::Layout, P>;
134 type Release = <Self as probe::Source>::Release<C::Token, C::Layout, R>;
135}
136
137impl engine::Removal for Uring {
138 type Slot = <Self as submit::Control>::Target;
139}
140
141impl gso::Source for Uring {
142 type Mode = Control;
143
144 const LIMITS: Option<(
145 bounded::U32<1, { MAX as u32 }>,
146 bounded::U32<2, { u16::MAX as u32 }>,
147 )> = Some((bounded::U32::exact::<65_535>(), bounded::U32::exact::<64>()));
148}
149
150impl kernel::Source for Uring {
151 type Code = op::Code;
152 type Failure<S: Copy + Eq> = error::Failure<S>;
153 type Returned = error::Returned;
154}
155
156#[inline]
157pub fn try_crc32() -> Result<bool, Errno> {
158 if let Some(enabled) = thread::raw::crc32() {
159 return Ok(enabled);
160 }
161 Ok(unsafe { libc::getauxval(libc::AT_HWCAP) } & (1 << 7) != 0)
163}
164
165impl Thread for Uring {
166 type Timer = Timer;
167 type Receiver = signal::raw::Receiver;
168 type Cpus = Cpus;
169
170 fn is_main() -> bool {
171 unsafe { libc::syscall(libc::SYS_gettid) == libc::getpid() as libc::c_long }
174 }
175
176 fn current() -> Result<Self::Cpus, affinity::Error> {
177 let mut mask: libc::cpu_set_t = unsafe { mem::zeroed() };
180 let result =
182 unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut mask) };
183 unsafe { kernel::raw::Status::new(result).try_zero::<Uring, Errno>() }
185 .map_err(affinity::Error::Current)?;
186 Ok(Cpus::new(&mask))
187 }
188
189 fn bind(cpu: affinity::raw::Cpu) -> Result<(), affinity::Error> {
190 const MAX: u32 = Cpus::LIMIT as u32 - 1;
191 let index = bounded::U32::<0, MAX>::new(u32::from(cpu.raw())).ok_or(
192 affinity::Error::BindingRange {
193 cpu,
194 maximum: MAX as u16,
195 },
196 )?;
197 let mut mask: libc::cpu_set_t = unsafe { mem::zeroed() };
199 unsafe { libc::CPU_SET(index.into_usize(), &mut mask) };
201 let result =
203 unsafe { libc::sched_setaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mask) };
204 unsafe { kernel::raw::Status::new(result).try_zero::<Uring, Errno>() }
206 .map_err(|fault| affinity::Error::Bind { cpu, fault })?;
207 Ok(())
208 }
209}
210
211impl errno::Source for Uring {
212 fn clear() {
213 unsafe { libc::__errno_location().write(0) };
215 }
216}
217
218impl pipe::Pipe for Uring {
219 fn open() -> Result<(OwnedFd, OwnedFd), pipe::Error> {
220 Self::open_with(libc::O_CLOEXEC)
221 }
222
223 fn nonblocking() -> Result<(OwnedFd, OwnedFd), pipe::Error> {
224 Self::open_with(libc::O_CLOEXEC | libc::O_NONBLOCK)
225 }
226}
227
228impl permit::Source for Uring {
229 type Queue<K: permit::raw::Key, I: depot::raw::Compact> = Fifo<K, I>;
230}
231
232impl provided::Source for Uring {
233 const PROVIDED: u16 = 1;
234 const CANARY: u16 = 2;
235 type Index = cq::Buffer;
236 type Context<L: memory::raw::Receive> = buffers::raw::Context<L>;
237 type Canary<L: memory::raw::Canary> = Canary<L>;
238 type Producer<L: memory::raw::Receive> = Producer<L>;
239 type Pending<E: memory::raw::Extent> = Selected<E, E::Capacity>;
240 type Complete<E: memory::raw::Extent> = Selected<E, E::Length>;
241}
242
243impl file::File for Uring {
244 type Options = types::OpenHow;
245 type Metadata = crate::raw::Metadata;
246 type Request<'a> = Borrowed<'a>;
247}
248
249impl socket::Socket for Uring {
250 const MAX_IOVECS: usize = libc::UIO_MAXIOV as usize;
251 type Error = Errno;
252
253 fn socket(domain: libc::c_int, kind: libc::c_int) -> Result<OwnedFd, Self::Error> {
254 Self::try_open(domain, kind | libc::SOCK_CLOEXEC, 0)
255 }
256
257 fn pair() -> Result<(OwnedFd, OwnedFd), record::Error> {
258 Self::try_pair::<Errno>(libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC)
259 .map_err(record::Error::Open)
260 }
261}
262
263impl addr::Source for Uring {
264 const UNIX_TERMINATED: bool = false;
265 const UNIX_ABSTRACT: bool = true;
266
267 fn header(domain: socket::Domain, _: addr::Socklen) -> [u8; 2] {
268 (domain.raw() as u16).to_ne_bytes()
269 }
270}
271
272impl option::Source for Uring {
273 const KEEP_IDLE: libc::c_int = libc::TCP_KEEPIDLE;
274}
275
276impl socket::Prepare for Uring {
277 type Handle = OwnedFd;
278 type Fast = num::NonZero<i32>;
279
280 fn fast_open(depth: Option<num::NonZero<i32>>) -> Result<Option<Self::Fast>, fast::Error> {
281 Ok(depth)
282 }
283
284 fn open(domain: socket::Domain, kind: socket::Kind) -> Result<Self::Handle, socket::Create> {
285 Self::socket(domain.raw(), kind.raw()).map_err(socket::Create::socket)
286 }
287
288 fn listener(domain: socket::Domain) -> Result<Self::Handle, socket::Create> {
289 Self::open(domain, socket::Kind::Stream)
290 }
291
292 fn adopt(file: OwnedFd) -> Result<Self::Handle, socket::Setup> {
293 <Self as Fd>::update::<Cloexec>(file.as_fd()).map_err(Setup::cloexec)?;
294 <Self as Fd>::remove::<Nonblock>(file.as_fd()).map_err(Setup::nonblock)?;
295 Ok(file)
296 }
297
298 fn into_fd(handle: Self::Handle) -> OwnedFd {
299 handle
300 }
301
302 fn set_fast(file: BorrowedFd<'_>, fast: Self::Fast) -> Result<(), Errno> {
303 Self::set_option(file, libc::IPPROTO_TCP, libc::TCP_FASTOPEN, &fast.get())
304 }
305}
306impl<T: Copy + Eq, S: Copy + Eq, F: Copy + Eq> Observe<T, S, F> for Uring {
307 type Observation = crate::Observed<T>;
308}
309impl tuning::Source for Uring {
310 type State<E: Copy, const N: usize> = crate::State<E, N>;
311 type Table<E: Copy, const N: usize> = Table<E, N>;
312}
313
314impl ring::Source for Uring {
315 type Ready<T: complete::raw::Token, L: memory::raw::Receive> = Ready<T, L>;
316 type Poll = enter::Poll<kernel::Errno<error::Enter>, kernel::Errno<error::Register<24>>>;
317 type Enter<'a, T: 'a> = Enter<'a, T>;
318 type Entry<T> = cq::Entry<T>;
319 type Message<'a, const NAME: usize, const CONTROL: usize> = cq::Output<'a, NAME, CONTROL>;
320 type Ring<T: complete::raw::Token> = Ring<T>;
321}
322
323impl submit::Control for Uring {
324 type Target = sq::Fixed;
325 type Owned<T: complete::raw::Token> = sq::Owned<T>;
326 type Poll<'a, T: complete::raw::Token> = Poll<'a, T>;
327
328 fn nop<T: complete::raw::Token>(complete: T) -> Self::Owned<T> {
329 sq::Entry::new(sq::Entry::NOP, sq::Descriptor::File(-1)).user_data(complete)
330 }
331
332 fn close<T: complete::raw::Token>(slot: Self::Target, complete: T) -> Self::Owned<T> {
333 use crate::reactor::op::files;
334
335 let mut entry = sq::Entry::new(files::CLOSE, sq::Descriptor::File(0));
336 entry.fields().index = slot.encode();
337 entry.user_data(complete)
338 }
339
340 fn shutdown<T: complete::raw::Token>(slot: Self::Target, complete: T) -> Self::Owned<T> {
341 use crate::reactor::op::sockets;
342
343 sockets::shutdown(slot, socket::How::BOTH)
344 .flags(sq::Flags::HARD_LINK | sq::Flags::SKIP_SUCCESS)
345 .user_data(complete)
346 }
347}
348
349impl probe::Source for Uring {
350 type Range = Range;
351 type Release<T: token::Codec, L: memory::raw::Canary, P: Copy> = Released<T, L, P>;
352 type Cleanup<T: token::Codec, L: memory::raw::Canary, P: Copy> = Recover<T, L, P>;
353 type Payload = Payload;
354 type Accept<T: token::Codec> = Accepted<T>;
355
356 type Session<T: token::Codec, L: memory::raw::Canary> = Session<T, L>;
357
358 type Outcome<T: complete::raw::Token, P: Copy> = Outcome<T, P>;
359 type Waiting<T: token::Codec, S> = Waiting<S, T>;
360}
361
362impl create::Source for Uring {
363 type Primary = Primary;
364 type Failure<T: token::Codec> = Fault<T>;
365 type Resources<
366 T: token::Codec,
367 L: memory::raw::Canary,
368 P: Copy + From<Self::Primary> + From<memory::Error>,
369 > = Resources<T, L, P>;
370}
371
372impl token::Source for Uring {
373 type Token<C: host::Context> = Encoded<C>;
374}
375
376impl admit::Native for Uring {
377 type Error<F> = Infallible;
378}
379
380impl<'a, C, R> life::Finish<'a, R> for Uring
381where
382 C: Context + 'a,
383 C::Tuning: Progress<C::Token>,
384 R: life::Reclaim<Backend = Engine<C>> + 'a,
385{
386 type Quiesced = Quiesced<R>;
387
388 fn try_finish(
389 resolver: R,
390 ) -> Result<Self::Quiesced, Stopped<R, Error<<Self as ring::Source>::Poll, R::Fault>>> {
391 Engine::try_finish(resolver)
392 }
393}
394
395impl<'a, C, R> life::Quiesce<'a, R> for Uring
396where
397 C: Context + 'a,
398 C::Tuning: Progress<C::Token>,
399 R: life::Cancel<Backend = Engine<C>> + 'a,
400 R::Cancelling: 'a,
401 R::Closing: 'a,
402{
403 type Quiesced = Quiesced<R::Closing>;
404
405 fn try_quiesce(
406 resolver: R,
407 ) -> Result<Self::Quiesced, Stopped<R::Closing, Error<<Self as ring::Source>::Poll, R::Fault>>>
408 {
409 use life::{Close as _, Finish as _, Resolver as _};
410
411 let mut resolver = resolver.cancel();
412 resolver.backend().tuning().cancel_all();
413 let result = resolver.backend().ring().submit().map_err(Error::File);
414 (resolver, ()) = Stopped::attach(resolver, result)
415 .map_err(|stopped| stopped.map(life::Close::into_closing))?;
416 let result = resolver.backend().ring().cancel_all().map_err(Error::File);
417 (resolver, ()) = Stopped::attach(resolver, result)
418 .map_err(|stopped| stopped.map(life::Close::into_closing))?;
419 resolver =
420 Engine::drain(resolver).map_err(|stopped| stopped.map(life::Close::into_closing))?;
421 if !resolver.backend().tuning().is_quiescent() {
422 return Err(Stopped {
423 state: resolver.into_closing(),
424 cause: Error::Tuning,
425 });
426 }
427 Self::try_finish(resolver.into_closing())
428 }
429}