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(linux_android)]
8pub use self::sched_linux_like::*;
9
10#[cfg(linux_android)]
11mod sched_linux_like {
12 use crate::errno::Errno;
13 use crate::unistd::Pid;
14 use crate::Result;
15 use libc::{self, c_int, c_void};
16 use std::mem;
17 use std::option::Option;
18 use std::os::unix::io::{AsFd, AsRawFd};
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 /// `clone` create a child process
90 /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html))
91 ///
92 /// `stack` is a reference to an array which will hold the stack of the new
93 /// process. Unlike when calling `clone(2)` from C, the provided stack
94 /// address need not be the highest address of the region. Nix will take
95 /// care of that requirement. The user only needs to provide a reference to
96 /// a normally allocated buffer.
97 ///
98 /// # Safety
99 ///
100 /// Because `clone` creates a child process with its stack located in
101 /// `stack` without specifying the size of the stack, special care must be
102 /// taken to ensure that the child process does not overflow the provided
103 /// stack space.
104 ///
105 /// See [`fork`](crate::unistd::fork) for additional safety concerns related
106 /// to executing child processes.
107 pub unsafe fn clone(
108 mut cb: CloneCb,
109 stack: &mut [u8],
110 flags: CloneFlags,
111 signal: Option<c_int>,
112 ) -> Result<Pid> {
113 extern "C" fn callback(data: *mut CloneCb) -> c_int {
114 let cb: &mut CloneCb = unsafe { &mut *data };
115 (*cb)() as c_int
116 }
117
118 let combined = flags.bits() | signal.unwrap_or(0);
119 let res = unsafe {
120 let ptr = stack.as_mut_ptr().add(stack.len());
121 let ptr_aligned = ptr.sub(ptr as usize % 16);
122 libc::clone(
123 mem::transmute::<
124 extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32,
125 extern "C" fn(*mut libc::c_void) -> i32,
126 >(
127 callback
128 as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32,
129 ),
130 ptr_aligned as *mut c_void,
131 combined,
132 &mut cb as *mut _ as *mut c_void,
133 )
134 };
135
136 Errno::result(res).map(Pid::from_raw)
137 }
138
139 /// disassociate parts of the process execution context
140 ///
141 /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html)
142 pub fn unshare(flags: CloneFlags) -> Result<()> {
143 let res = unsafe { libc::unshare(flags.bits()) };
144
145 Errno::result(res).map(drop)
146 }
147
148 /// reassociate thread with a namespace
149 ///
150 /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html)
151 pub fn setns<Fd: AsFd>(fd: Fd, nstype: CloneFlags) -> Result<()> {
152 let res = unsafe { libc::setns(fd.as_fd().as_raw_fd(), nstype.bits()) };
153
154 Errno::result(res).map(drop)
155 }
156}
157
158#[cfg(any(linux_android, freebsdlike))]
159pub use self::sched_affinity::*;
160
161#[cfg(any(linux_android, freebsdlike))]
162mod sched_affinity {
163 use crate::errno::Errno;
164 use crate::unistd::Pid;
165 use crate::Result;
166 use std::mem;
167
168 /// CpuSet represent a bit-mask of CPUs.
169 /// CpuSets are used by sched_setaffinity and
170 /// sched_getaffinity for example.
171 ///
172 /// This is a wrapper around `libc::cpu_set_t`.
173 #[repr(transparent)]
174 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
175 pub struct CpuSet {
176 #[cfg(not(target_os = "freebsd"))]
177 cpu_set: libc::cpu_set_t,
178 #[cfg(target_os = "freebsd")]
179 cpu_set: libc::cpuset_t,
180 }
181
182 impl CpuSet {
183 /// Create a new and empty CpuSet.
184 pub fn new() -> CpuSet {
185 CpuSet {
186 cpu_set: unsafe { mem::zeroed() },
187 }
188 }
189
190 /// Test to see if a CPU is in the CpuSet.
191 /// `field` is the CPU id to test
192 pub fn is_set(&self, field: usize) -> Result<bool> {
193 if field >= CpuSet::count() {
194 Err(Errno::EINVAL)
195 } else {
196 Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) })
197 }
198 }
199
200 /// Add a CPU to CpuSet.
201 /// `field` is the CPU id to add
202 pub fn set(&mut self, field: usize) -> Result<()> {
203 if field >= CpuSet::count() {
204 Err(Errno::EINVAL)
205 } else {
206 unsafe {
207 libc::CPU_SET(field, &mut self.cpu_set);
208 }
209 Ok(())
210 }
211 }
212
213 /// Remove a CPU from CpuSet.
214 /// `field` is the CPU id to remove
215 pub fn unset(&mut self, field: usize) -> Result<()> {
216 if field >= CpuSet::count() {
217 Err(Errno::EINVAL)
218 } else {
219 unsafe {
220 libc::CPU_CLR(field, &mut self.cpu_set);
221 }
222 Ok(())
223 }
224 }
225
226 /// Return the maximum number of CPU in CpuSet
227 pub const fn count() -> usize {
228 #[cfg(not(target_os = "freebsd"))]
229 let bytes = mem::size_of::<libc::cpu_set_t>();
230 #[cfg(target_os = "freebsd")]
231 let bytes = mem::size_of::<libc::cpuset_t>();
232
233 8 * bytes
234 }
235 }
236
237 impl Default for CpuSet {
238 fn default() -> Self {
239 Self::new()
240 }
241 }
242
243 /// `sched_setaffinity` set a thread's CPU affinity mask
244 /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html))
245 ///
246 /// `pid` is the thread ID to update.
247 /// If pid is zero, then the calling thread is updated.
248 ///
249 /// The `cpuset` argument specifies the set of CPUs on which the thread
250 /// will be eligible to run.
251 ///
252 /// # Example
253 ///
254 /// Binding the current thread to CPU 0 can be done as follows:
255 ///
256 /// ```rust,no_run
257 /// use nix::sched::{CpuSet, sched_setaffinity};
258 /// use nix::unistd::Pid;
259 ///
260 /// let mut cpu_set = CpuSet::new();
261 /// cpu_set.set(0).unwrap();
262 /// sched_setaffinity(Pid::from_raw(0), &cpu_set).unwrap();
263 /// ```
264 pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> {
265 let res = unsafe {
266 libc::sched_setaffinity(
267 pid.into(),
268 mem::size_of::<CpuSet>() as libc::size_t,
269 &cpuset.cpu_set,
270 )
271 };
272
273 Errno::result(res).map(drop)
274 }
275
276 /// `sched_getaffinity` get a thread's CPU affinity mask
277 /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html))
278 ///
279 /// `pid` is the thread ID to check.
280 /// If pid is zero, then the calling thread is checked.
281 ///
282 /// Returned `cpuset` is the set of CPUs on which the thread
283 /// is eligible to run.
284 ///
285 /// # Example
286 ///
287 /// Checking if the current thread can run on CPU 0 can be done as follows:
288 ///
289 /// ```rust,no_run
290 /// use nix::sched::sched_getaffinity;
291 /// use nix::unistd::Pid;
292 ///
293 /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap();
294 /// if cpu_set.is_set(0).unwrap() {
295 /// println!("Current thread can run on CPU 0");
296 /// }
297 /// ```
298 pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> {
299 let mut cpuset = CpuSet::new();
300 let res = unsafe {
301 libc::sched_getaffinity(
302 pid.into(),
303 mem::size_of::<CpuSet>() as libc::size_t,
304 &mut cpuset.cpu_set,
305 )
306 };
307
308 Errno::result(res).and(Ok(cpuset))
309 }
310
311 /// Determines the CPU on which the calling thread is running.
312 pub fn sched_getcpu() -> Result<usize> {
313 let res = unsafe { libc::sched_getcpu() };
314
315 Errno::result(res).map(|int| int as usize)
316 }
317}
318
319/// Explicitly yield the processor to other threads.
320///
321/// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html)
322pub fn sched_yield() -> Result<()> {
323 let res = unsafe { libc::sched_yield() };
324
325 Errno::result(res).map(drop)
326}