• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Execution scheduling
2 //!
3 //! See Also
4 //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html)
5 use crate::{Errno, Result};
6 
7 #[cfg(linux_android)]
8 pub use self::sched_linux_like::*;
9 
10 #[cfg(linux_android)]
11 mod 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.
clone( mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags, signal: Option<c_int>, ) -> Result<Pid>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                     callback
125                         as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32,
126                 ),
127                 ptr_aligned as *mut c_void,
128                 combined,
129                 &mut cb as *mut _ as *mut c_void,
130             )
131         };
132 
133         Errno::result(res).map(Pid::from_raw)
134     }
135 
136     /// disassociate parts of the process execution context
137     ///
138     /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html)
unshare(flags: CloneFlags) -> Result<()>139     pub fn unshare(flags: CloneFlags) -> Result<()> {
140         let res = unsafe { libc::unshare(flags.bits()) };
141 
142         Errno::result(res).map(drop)
143     }
144 
145     /// reassociate thread with a namespace
146     ///
147     /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html)
setns<Fd: AsFd>(fd: Fd, nstype: CloneFlags) -> Result<()>148     pub fn setns<Fd: AsFd>(fd: Fd, nstype: CloneFlags) -> Result<()> {
149         let res = unsafe { libc::setns(fd.as_fd().as_raw_fd(), nstype.bits()) };
150 
151         Errno::result(res).map(drop)
152     }
153 }
154 
155 #[cfg(any(linux_android, freebsdlike))]
156 pub use self::sched_affinity::*;
157 
158 #[cfg(any(linux_android, freebsdlike))]
159 mod sched_affinity {
160     use crate::errno::Errno;
161     use crate::unistd::Pid;
162     use crate::Result;
163     use std::mem;
164 
165     /// CpuSet represent a bit-mask of CPUs.
166     /// CpuSets are used by sched_setaffinity and
167     /// sched_getaffinity for example.
168     ///
169     /// This is a wrapper around `libc::cpu_set_t`.
170     #[repr(transparent)]
171     #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
172     pub struct CpuSet {
173         #[cfg(not(target_os = "freebsd"))]
174         cpu_set: libc::cpu_set_t,
175         #[cfg(target_os = "freebsd")]
176         cpu_set: libc::cpuset_t,
177     }
178 
179     impl CpuSet {
180         /// Create a new and empty CpuSet.
new() -> CpuSet181         pub fn new() -> CpuSet {
182             CpuSet {
183                 cpu_set: unsafe { mem::zeroed() },
184             }
185         }
186 
187         /// Test to see if a CPU is in the CpuSet.
188         /// `field` is the CPU id to test
is_set(&self, field: usize) -> Result<bool>189         pub fn is_set(&self, field: usize) -> Result<bool> {
190             if field >= CpuSet::count() {
191                 Err(Errno::EINVAL)
192             } else {
193                 Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) })
194             }
195         }
196 
197         /// Add a CPU to CpuSet.
198         /// `field` is the CPU id to add
set(&mut self, field: usize) -> Result<()>199         pub fn set(&mut self, field: usize) -> Result<()> {
200             if field >= CpuSet::count() {
201                 Err(Errno::EINVAL)
202             } else {
203                 unsafe {
204                     libc::CPU_SET(field, &mut self.cpu_set);
205                 }
206                 Ok(())
207             }
208         }
209 
210         /// Remove a CPU from CpuSet.
211         /// `field` is the CPU id to remove
unset(&mut self, field: usize) -> Result<()>212         pub fn unset(&mut self, field: usize) -> Result<()> {
213             if field >= CpuSet::count() {
214                 Err(Errno::EINVAL)
215             } else {
216                 unsafe {
217                     libc::CPU_CLR(field, &mut self.cpu_set);
218                 }
219                 Ok(())
220             }
221         }
222 
223         /// Return the maximum number of CPU in CpuSet
count() -> usize224         pub const fn count() -> usize {
225             #[cfg(not(target_os = "freebsd"))]
226             let bytes = mem::size_of::<libc::cpu_set_t>();
227             #[cfg(target_os = "freebsd")]
228             let bytes = mem::size_of::<libc::cpuset_t>();
229 
230             8 * bytes
231         }
232     }
233 
234     impl Default for CpuSet {
default() -> Self235         fn default() -> Self {
236             Self::new()
237         }
238     }
239 
240     /// `sched_setaffinity` set a thread's CPU affinity mask
241     /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html))
242     ///
243     /// `pid` is the thread ID to update.
244     /// If pid is zero, then the calling thread is updated.
245     ///
246     /// The `cpuset` argument specifies the set of CPUs on which the thread
247     /// will be eligible to run.
248     ///
249     /// # Example
250     ///
251     /// Binding the current thread to CPU 0 can be done as follows:
252     ///
253     /// ```rust,no_run
254     /// use nix::sched::{CpuSet, sched_setaffinity};
255     /// use nix::unistd::Pid;
256     ///
257     /// let mut cpu_set = CpuSet::new();
258     /// cpu_set.set(0).unwrap();
259     /// sched_setaffinity(Pid::from_raw(0), &cpu_set).unwrap();
260     /// ```
sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()>261     pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> {
262         let res = unsafe {
263             libc::sched_setaffinity(
264                 pid.into(),
265                 mem::size_of::<CpuSet>() as libc::size_t,
266                 &cpuset.cpu_set,
267             )
268         };
269 
270         Errno::result(res).map(drop)
271     }
272 
273     /// `sched_getaffinity` get a thread's CPU affinity mask
274     /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html))
275     ///
276     /// `pid` is the thread ID to check.
277     /// If pid is zero, then the calling thread is checked.
278     ///
279     /// Returned `cpuset` is the set of CPUs on which the thread
280     /// is eligible to run.
281     ///
282     /// # Example
283     ///
284     /// Checking if the current thread can run on CPU 0 can be done as follows:
285     ///
286     /// ```rust,no_run
287     /// use nix::sched::sched_getaffinity;
288     /// use nix::unistd::Pid;
289     ///
290     /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap();
291     /// if cpu_set.is_set(0).unwrap() {
292     ///     println!("Current thread can run on CPU 0");
293     /// }
294     /// ```
sched_getaffinity(pid: Pid) -> Result<CpuSet>295     pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> {
296         let mut cpuset = CpuSet::new();
297         let res = unsafe {
298             libc::sched_getaffinity(
299                 pid.into(),
300                 mem::size_of::<CpuSet>() as libc::size_t,
301                 &mut cpuset.cpu_set,
302             )
303         };
304 
305         Errno::result(res).and(Ok(cpuset))
306     }
307 
308     /// Determines the CPU on which the calling thread is running.
sched_getcpu() -> Result<usize>309     pub fn sched_getcpu() -> Result<usize> {
310         let res = unsafe { libc::sched_getcpu() };
311 
312         Errno::result(res).map(|int| int as usize)
313     }
314 }
315 
316 /// Explicitly yield the processor to other threads.
317 ///
318 /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html)
sched_yield() -> Result<()>319 pub fn sched_yield() -> Result<()> {
320     let res = unsafe { libc::sched_yield() };
321 
322     Errno::result(res).map(drop)
323 }
324