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