Skip to main content

dope_uring/system/ffi/
thread.rs

1use std::mem;
2
3use dope_sys::{
4    Errno, kernel,
5    thread::{Thread, affinity},
6};
7use o3::base::num::bounded;
8
9use crate::{Backend, system};
10
11impl Thread for Backend {
12    type Timer = system::Timer;
13    type Receiver = system::ffi::Receiver;
14    type Cpus = system::ffi::Cpus;
15
16    fn current() -> Result<Self::Cpus, affinity::Error> {
17        // SAFETY: zero gives the kernel initialized storage even when the CPU
18        // set representation contains padding.
19        let mut mask: libc::cpu_set_t = unsafe { mem::zeroed() };
20        // SAFETY: mask points to writable storage of the exact size supplied.
21        let result =
22            unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut mask) };
23        // SAFETY: sched_getaffinity returns zero or -1 with errno.
24        unsafe { kernel::raw::Status::new(result).try_zero::<Backend, Errno>() }
25            .map_err(affinity::Error::Current)?;
26        // SAFETY: the mask was initialized and its native population fits system::ffi::Cpus::LIMIT.
27        let count = unsafe { libc::CPU_COUNT(&mask) } as u16;
28        Ok(system::ffi::Cpus {
29            mask,
30            indices: 0..system::ffi::Cpus::LIMIT,
31            remaining: count,
32        })
33    }
34
35    fn bind(cpu: affinity::raw::Cpu) -> Result<(), affinity::Error> {
36        const MAX: u32 = system::ffi::Cpus::LIMIT as u32 - 1;
37        let index = bounded::raw::U32::<0, MAX>::new(u32::from(cpu.raw())).ok_or(
38            affinity::Error::BindingRange {
39                cpu,
40                maximum: MAX as u16,
41            },
42        )?;
43        // SAFETY: zero is the empty set.
44        let mut mask: libc::cpu_set_t = unsafe { mem::zeroed() };
45        // SAFETY: index retains this native mask's admitted bound and mask is initialized.
46        unsafe { libc::CPU_SET(index.into_usize(), &mut mask) };
47        // SAFETY: mask is an initialized cpu_set_t of the exact ABI size.
48        let result =
49            unsafe { libc::sched_setaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mask) };
50        // SAFETY: sched_setaffinity returns zero or -1 with errno.
51        unsafe { kernel::raw::Status::new(result).try_zero::<Backend, Errno>() }
52            .map_err(|fault| affinity::Error::Bind { cpu, fault })
53    }
54}