solana_perf/
thread.rs

1use std::fmt::Display;
2
3/// Wrapper for `nice(3)`.
4#[cfg(target_os = "linux")]
5fn nice(adjustment: i8) -> Result<i8, nix::errno::Errno> {
6    unsafe {
7        *libc::__errno_location() = 0;
8        let niceness = libc::nice(libc::c_int::from(adjustment));
9        let errno = *libc::__errno_location();
10        if (niceness == -1) && (errno != 0) {
11            Err(errno)
12        } else {
13            Ok(niceness)
14        }
15    }
16    .map(|niceness| i8::try_from(niceness).expect("Unexpected niceness value"))
17    .map_err(nix::errno::Errno::from_raw)
18}
19
20/// Adds `adjustment` to the nice value of calling thread. Negative `adjustment` increases priority,
21/// positive `adjustment` decreases priority. New thread inherits nice value from current thread
22/// when created.
23///
24/// Fails on non-Linux systems for all `adjustment` values except of zero.
25#[cfg(target_os = "linux")]
26pub fn renice_this_thread(adjustment: i8) -> Result<(), String> {
27    // On Linux, the nice value is a per-thread attribute. See `man 7 sched` for details.
28    // Other systems probably should use pthread_setschedprio(), but, on Linux, thread priority
29    // is fixed to zero for SCHED_OTHER threads (which is the default).
30    nice(adjustment)
31        .map(|_| ())
32        .map_err(|err| format!("Failed to change thread's nice value: {err}"))
33}
34
35/// Adds `adjustment` to the nice value of calling thread. Negative `adjustment` increases priority,
36/// positive `adjustment` decreases priority. New thread inherits nice value from current thread
37/// when created.
38///
39/// Fails on non-Linux systems for all `adjustment` values except of zero.
40#[cfg(not(target_os = "linux"))]
41pub fn renice_this_thread(adjustment: i8) -> Result<(), String> {
42    if adjustment == 0 {
43        Ok(())
44    } else {
45        Err(String::from(
46            "Failed to change thread's nice value: only supported on Linux",
47        ))
48    }
49}
50
51/// Check whether the nice value can be changed by `adjustment`.
52#[cfg(target_os = "linux")]
53pub fn is_renice_allowed(adjustment: i8) -> bool {
54    use caps::{CapSet, Capability};
55
56    if adjustment >= 0 {
57        true
58    } else {
59        nix::unistd::geteuid().is_root()
60            || caps::has_cap(None, CapSet::Effective, Capability::CAP_SYS_NICE)
61                .map_err(|err| warn!("Failed to get thread's capabilities: {err}"))
62                .unwrap_or(false)
63    }
64}
65
66/// Check whether the nice value can be changed by `adjustment`.
67#[cfg(not(target_os = "linux"))]
68pub fn is_renice_allowed(adjustment: i8) -> bool {
69    adjustment == 0
70}
71
72pub fn is_niceness_adjustment_valid<T>(value: T) -> Result<(), String>
73where
74    T: AsRef<str> + Display,
75{
76    let adjustment = value
77        .as_ref()
78        .parse::<i8>()
79        .map_err(|err| format!("error parsing niceness adjustment value '{value}': {err}"))?;
80    if is_renice_allowed(adjustment) {
81        Ok(())
82    } else {
83        Err(String::from(
84            "niceness adjustment supported only on Linux; negative adjustment (priority increase) \
85             requires root or CAP_SYS_NICE (see `man 7 capabilities` for details)",
86        ))
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    #[cfg(target_os = "linux")]
93    use super::*;
94
95    #[cfg(target_os = "linux")]
96    #[test]
97    fn test_nice() {
98        // No change / get current niceness
99        let niceness = nice(0).unwrap();
100
101        // Decrease priority (allowed for unprivileged processes)
102        let result = std::thread::spawn(|| nice(1)).join().unwrap();
103        assert_eq!(result, Ok(niceness + 1));
104
105        // Sanity check: ensure that current thread's nice value not changed after previous call
106        // from different thread
107        assert_eq!(nice(0), Ok(niceness));
108
109        // Sanity check: ensure that new thread inherits nice value from current thread
110        let inherited_niceness = std::thread::spawn(|| {
111            nice(1).unwrap();
112            std::thread::spawn(|| nice(0).unwrap()).join().unwrap()
113        })
114        .join()
115        .unwrap();
116        assert_eq!(inherited_niceness, niceness + 1);
117
118        if !is_renice_allowed(-1) {
119            // Increase priority (not allowed for unprivileged processes)
120            let result = std::thread::spawn(|| nice(-1)).join().unwrap();
121            assert!(result.is_err());
122        }
123    }
124
125    #[test]
126    fn test_is_niceness_adjustment_valid() {
127        use super::is_niceness_adjustment_valid;
128        assert_eq!(is_niceness_adjustment_valid("0"), Ok(()));
129        assert!(is_niceness_adjustment_valid("128").is_err());
130        assert!(is_niceness_adjustment_valid("-129").is_err());
131    }
132}