nix/
sched.rs

1//! Execution scheduling
2//!
3//! See Also
4//! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html)
5use crate::{Errno, Result};
6
7#[cfg(any(target_os = "android", target_os = "linux"))]
8pub use self::sched_linux_like::*;
9
10#[cfg(any(target_os = "android", target_os = "linux"))]
11mod sched_linux_like {
12    use crate::errno::Errno;
13    use libc::{self, c_int, c_void};
14    use std::mem;
15    use std::option::Option;
16    use std::os::unix::io::RawFd;
17    use crate::unistd::Pid;
18    use crate::Result;
19
20    // For some functions taking with a parameter of type CloneFlags,
21    // only a subset of these flags have an effect.
22    libc_bitflags! {
23        /// Options for use with [`clone`]
24        pub struct CloneFlags: c_int {
25            /// The calling process and the child process run in the same
26            /// memory space.
27            CLONE_VM;
28            /// The caller and the child process share the same  filesystem
29            /// information.
30            CLONE_FS;
31            /// The calling process and the child process share the same file
32            /// descriptor table.
33            CLONE_FILES;
34            /// The calling process and the child process share the same table
35            /// of signal handlers.
36            CLONE_SIGHAND;
37            /// If the calling process is being traced, then trace the child
38            /// also.
39            CLONE_PTRACE;
40            /// The execution of the calling process is suspended until the
41            /// child releases its virtual memory resources via a call to
42            /// execve(2) or _exit(2) (as with vfork(2)).
43            CLONE_VFORK;
44            /// The parent of the new child  (as returned by getppid(2))
45            /// will be the same as that of the calling process.
46            CLONE_PARENT;
47            /// The child is placed in the same thread group as the calling
48            /// process.
49            CLONE_THREAD;
50            /// The cloned child is started in a new mount namespace.
51            CLONE_NEWNS;
52            /// The child and the calling process share a single list of System
53            /// V semaphore adjustment values
54            CLONE_SYSVSEM;
55            // Not supported by Nix due to lack of varargs support in Rust FFI
56            // CLONE_SETTLS;
57            // Not supported by Nix due to lack of varargs support in Rust FFI
58            // CLONE_PARENT_SETTID;
59            // Not supported by Nix due to lack of varargs support in Rust FFI
60            // CLONE_CHILD_CLEARTID;
61            /// Unused since Linux 2.6.2
62            #[deprecated(since = "0.23.0", note = "Deprecated by Linux 2.6.2")]
63            CLONE_DETACHED;
64            /// A tracing process cannot force `CLONE_PTRACE` on this child
65            /// process.
66            CLONE_UNTRACED;
67            // Not supported by Nix due to lack of varargs support in Rust FFI
68            // CLONE_CHILD_SETTID;
69            /// Create the process in a new cgroup namespace.
70            CLONE_NEWCGROUP;
71            /// Create the process in a new UTS namespace.
72            CLONE_NEWUTS;
73            /// Create the process in a new IPC namespace.
74            CLONE_NEWIPC;
75            /// Create the process in a new user namespace.
76            CLONE_NEWUSER;
77            /// Create the process in a new PID namespace.
78            CLONE_NEWPID;
79            /// Create the process in a new network namespace.
80            CLONE_NEWNET;
81            /// The new process shares an I/O context with the calling process.
82            CLONE_IO;
83        }
84    }
85
86    /// Type for the function executed by [`clone`].
87    pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>;
88
89    /// CpuSet represent a bit-mask of CPUs.
90    /// CpuSets are used by sched_setaffinity and
91    /// sched_getaffinity for example.
92    ///
93    /// This is a wrapper around `libc::cpu_set_t`.
94    #[repr(C)]
95    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
96    pub struct CpuSet {
97        cpu_set: libc::cpu_set_t,
98    }
99
100    impl CpuSet {
101        /// Create a new and empty CpuSet.
102        pub fn new() -> CpuSet {
103            CpuSet {
104                cpu_set: unsafe { mem::zeroed() },
105            }
106        }
107
108        /// Test to see if a CPU is in the CpuSet.
109        /// `field` is the CPU id to test
110        pub fn is_set(&self, field: usize) -> Result<bool> {
111            if field >= CpuSet::count() {
112                Err(Errno::EINVAL)
113            } else {
114                Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) })
115            }
116        }
117
118        /// Add a CPU to CpuSet.
119        /// `field` is the CPU id to add
120        pub fn set(&mut self, field: usize) -> Result<()> {
121            if field >= CpuSet::count() {
122                Err(Errno::EINVAL)
123            } else {
124                unsafe { libc::CPU_SET(field, &mut self.cpu_set); }
125                Ok(())
126            }
127        }
128
129        /// Remove a CPU from CpuSet.
130        /// `field` is the CPU id to remove
131        pub fn unset(&mut self, field: usize) -> Result<()> {
132            if field >= CpuSet::count() {
133                Err(Errno::EINVAL)
134            } else {
135                unsafe { libc::CPU_CLR(field, &mut self.cpu_set);}
136                Ok(())
137            }
138        }
139
140        /// Return the maximum number of CPU in CpuSet
141        pub const fn count() -> usize {
142            8 * mem::size_of::<libc::cpu_set_t>()
143        }
144    }
145
146    impl Default for CpuSet {
147        fn default() -> Self {
148            Self::new()
149        }
150    }
151
152    /// `sched_setaffinity` set a thread's CPU affinity mask
153    /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html))
154    ///
155    /// `pid` is the thread ID to update.
156    /// If pid is zero, then the calling thread is updated.
157    ///
158    /// The `cpuset` argument specifies the set of CPUs on which the thread
159    /// will be eligible to run.
160    ///
161    /// # Example
162    ///
163    /// Binding the current thread to CPU 0 can be done as follows:
164    ///
165    /// ```rust,no_run
166    /// use nix::sched::{CpuSet, sched_setaffinity};
167    /// use nix::unistd::Pid;
168    ///
169    /// let mut cpu_set = CpuSet::new();
170    /// cpu_set.set(0);
171    /// sched_setaffinity(Pid::from_raw(0), &cpu_set);
172    /// ```
173    pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> {
174        let res = unsafe {
175            libc::sched_setaffinity(
176                pid.into(),
177                mem::size_of::<CpuSet>() as libc::size_t,
178                &cpuset.cpu_set,
179            )
180        };
181
182        Errno::result(res).map(drop)
183    }
184
185    /// `sched_getaffinity` get a thread's CPU affinity mask
186    /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html))
187    ///
188    /// `pid` is the thread ID to check.
189    /// If pid is zero, then the calling thread is checked.
190    ///
191    /// Returned `cpuset` is the set of CPUs on which the thread
192    /// is eligible to run.
193    ///
194    /// # Example
195    ///
196    /// Checking if the current thread can run on CPU 0 can be done as follows:
197    ///
198    /// ```rust,no_run
199    /// use nix::sched::sched_getaffinity;
200    /// use nix::unistd::Pid;
201    ///
202    /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap();
203    /// if cpu_set.is_set(0).unwrap() {
204    ///     println!("Current thread can run on CPU 0");
205    /// }
206    /// ```
207    pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> {
208        let mut cpuset = CpuSet::new();
209        let res = unsafe {
210            libc::sched_getaffinity(
211                pid.into(),
212                mem::size_of::<CpuSet>() as libc::size_t,
213                &mut cpuset.cpu_set,
214            )
215        };
216
217        Errno::result(res).and(Ok(cpuset))
218    }
219
220    /// `clone` create a child process
221    /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html))
222    ///
223    /// `stack` is a reference to an array which will hold the stack of the new
224    /// process.  Unlike when calling `clone(2)` from C, the provided stack
225    /// address need not be the highest address of the region.  Nix will take
226    /// care of that requirement.  The user only needs to provide a reference to
227    /// a normally allocated buffer.
228    pub fn clone(
229        mut cb: CloneCb,
230        stack: &mut [u8],
231        flags: CloneFlags,
232        signal: Option<c_int>,
233    ) -> Result<Pid> {
234        extern "C" fn callback(data: *mut CloneCb) -> c_int {
235            let cb: &mut CloneCb = unsafe { &mut *data };
236            (*cb)() as c_int
237        }
238
239        let res = unsafe {
240            let combined = flags.bits() | signal.unwrap_or(0);
241            let ptr = stack.as_mut_ptr().add(stack.len());
242            let ptr_aligned = ptr.sub(ptr as usize % 16);
243            libc::clone(
244                mem::transmute(
245                    callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32,
246                ),
247                ptr_aligned as *mut c_void,
248                combined,
249                &mut cb as *mut _ as *mut c_void,
250            )
251        };
252
253        Errno::result(res).map(Pid::from_raw)
254    }
255
256    /// disassociate parts of the process execution context
257    ///
258    /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html)
259    pub fn unshare(flags: CloneFlags) -> Result<()> {
260        let res = unsafe { libc::unshare(flags.bits()) };
261
262        Errno::result(res).map(drop)
263    }
264
265    /// reassociate thread with a namespace
266    ///
267    /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html)
268    pub fn setns(fd: RawFd, nstype: CloneFlags) -> Result<()> {
269        let res = unsafe { libc::setns(fd, nstype.bits()) };
270
271        Errno::result(res).map(drop)
272    }
273}
274
275/// Explicitly yield the processor to other threads.
276///
277/// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html)
278pub fn sched_yield() -> Result<()> {
279    let res = unsafe { libc::sched_yield() };
280
281    Errno::result(res).map(drop)
282}