1use crate::sched::PreemptRtError::{PriorityAboveMax, PriorityBelowMin};
2use libc::{c_int, pid_t};
3use std::fmt;
4use thiserror::Error;
5
6pub type RtResult<T> = Result<T, PreemptRtError>;
8
9#[derive(Debug, Error)]
10pub enum PreemptRtError {
12 #[error("c function returned errno: {0}")]
13 Errno(c_int),
14 #[error("unknown scheduler for value {0}")]
15 UnknownScheduler(c_int),
16 #[error("priority {0} is higher than max priority {1}")]
17 PriorityAboveMax(c_int, c_int),
18 #[error("priority {0} is lower than min priority {1}")]
19 PriorityBelowMin(c_int, c_int),
20 #[error("current platform {0} does not support preempt-rt")]
21 NonLinuxPlatform(&'static str),
22}
23
24#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
25pub struct Pid(pid_t);
27
28impl Pid {
29 pub const fn current_thread() -> Self {
33 Pid(0)
34 }
35}
36
37impl From<Pid> for pid_t {
38 fn from(pid: Pid) -> Self {
39 pid.0
40 }
41}
42
43impl fmt::Display for Pid {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 fmt::Display::fmt(&self.0, f)
46 }
47}
48
49#[repr(i32)]
50#[allow(non_camel_case_types)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
52pub enum Scheduler {
59 #[cfg(target_os = "linux")]
61 SCHED_NORMAL = libc::SCHED_NORMAL,
62 #[cfg(target_os = "macos")]
64 SCHED_NORMAL = libc::SCHED_OTHER,
65 SCHED_FIFO = libc::SCHED_FIFO,
69 SCHED_RR = libc::SCHED_RR,
71 #[cfg(target_os = "linux")]
75 SCHED_BATCH = libc::SCHED_BATCH,
76 #[cfg(target_os = "linux")]
79 SCHED_IDLE = libc::SCHED_IDLE,
80 #[cfg(target_os = "linux")]
84 SCHED_DEADLINE = libc::SCHED_DEADLINE,
85}
86
87impl TryFrom<c_int> for Scheduler {
88 type Error = PreemptRtError;
89
90 fn try_from(value: c_int) -> RtResult<Self> {
91 match value {
92 #[cfg(target_os = "linux")]
93 libc::SCHED_NORMAL => Ok(Scheduler::SCHED_NORMAL),
94 #[cfg(target_os = "macos")]
95 libc::SCHED_OTHER => Ok(Scheduler::SCHED_NORMAL),
96 libc::SCHED_FIFO => Ok(Scheduler::SCHED_FIFO),
97 libc::SCHED_RR => Ok(Scheduler::SCHED_RR),
98 #[cfg(target_os = "linux")]
99 libc::SCHED_BATCH => Ok(Scheduler::SCHED_BATCH),
100 #[cfg(target_os = "linux")]
101 libc::SCHED_IDLE => Ok(Scheduler::SCHED_IDLE),
102 #[cfg(target_os = "linux")]
103 libc::SCHED_DEADLINE => Ok(Scheduler::SCHED_DEADLINE),
104 _ => Err(PreemptRtError::UnknownScheduler(value)),
105 }
106 }
107}
108
109fn handle_errno(result: c_int) -> RtResult<c_int> {
110 if result == -1 {
111 #[cfg(target_os = "linux")]
112 return Err(PreemptRtError::Errno(unsafe { *libc::__errno_location() }));
113 #[cfg(target_os = "macos")]
114 return Err(PreemptRtError::Errno(unsafe { *libc::__error() }));
115 } else {
116 Ok(result)
117 }
118}
119
120impl Scheduler {
121 pub fn priority_max(&self) -> RtResult<c_int> {
123 let res = unsafe { libc::sched_get_priority_max(*self as c_int) };
124 handle_errno(res)
125 }
126
127 pub fn priority_min(&self) -> RtResult<c_int> {
129 let res = unsafe { libc::sched_get_priority_min(*self as c_int) };
130 handle_errno(res)
131 }
132
133 pub fn with_params(self, params: SchedulerParams) -> ParameterizedScheduler {
135 ParameterizedScheduler {
136 scheduler: self,
137 params,
138 }
139 }
140}
141
142#[repr(C)]
143#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
144pub struct SchedulerParams {
147 pub priority: c_int,
149}
150
151#[cfg(target_os = "linux")]
152impl From<SchedulerParams> for libc::sched_param {
153 #[cfg(not(any(target_env = "musl", target_env = "ohos")))]
154 fn from(param: SchedulerParams) -> Self {
155 libc::sched_param {
156 sched_priority: param.priority,
157 }
158 }
159
160 #[cfg(any(target_env = "musl", target_env = "ohos"))]
161 fn from(param: SchedulerParams) -> Self {
162 let ts_zero = libc::timespec {
163 tv_sec: 0,
164 tv_nsec: 0,
165 };
166 libc::sched_param {
169 sched_priority: param.priority,
170 sched_ss_init_budget: ts_zero.clone(),
171 sched_ss_low_priority: 0,
172 sched_ss_repl_period: ts_zero.clone(),
173 sched_ss_max_repl: 0,
174 }
175 }
176}
177
178impl From<libc::sched_param> for SchedulerParams {
179 fn from(param: libc::sched_param) -> Self {
180 SchedulerParams {
181 priority: param.sched_priority,
182 }
183 }
184}
185
186pub trait IntoSchedParams {
187 fn into_sched_params(self) -> SchedulerParams;
188}
189
190impl IntoSchedParams for SchedulerParams {
191 fn into_sched_params(self) -> SchedulerParams {
192 self
193 }
194}
195
196impl IntoSchedParams for i32 {
197 fn into_sched_params(self) -> SchedulerParams {
198 SchedulerParams {
199 priority: self as c_int,
200 }
201 }
202}
203
204impl<T: IntoSchedParams> IntoSchedParams for Option<T> {
205 fn into_sched_params(self) -> SchedulerParams {
206 match self {
207 None => SchedulerParams { priority: 0 },
208 Some(param) => param.into_sched_params(),
209 }
210 }
211}
212
213#[cfg_attr(target_os = "macos", allow(unused))]
214#[derive(Debug, Clone)]
215pub struct ParameterizedScheduler {
216 scheduler: Scheduler,
217 params: SchedulerParams,
218}
219
220impl ParameterizedScheduler {
221 #[cfg_attr(target_os = "macos", allow(unused_variables))]
224 pub fn set_on(self, pid: Pid) -> RtResult<()> {
225 let priority = self.params.priority;
226 let max = self.scheduler.priority_max()?;
227 let min = self.scheduler.priority_min()?;
228 if priority > max {
229 Err(PriorityAboveMax(priority, max))
230 } else if priority < min {
231 Err(PriorityBelowMin(priority, min))
232 } else {
233 #[cfg(target_os = "linux")]
234 return set_scheduler(pid, self.scheduler, self.params);
235 #[cfg(target_os = "macos")]
236 return Err(PreemptRtError::NonLinuxPlatform("macos"));
237 }
238 }
239
240 pub fn set_current(self) -> RtResult<()> {
241 self.set_on(Pid::current_thread())
242 }
243}
244
245#[cfg(target_os = "linux")]
246mod linux {
247 use super::*;
248 use std::mem::MaybeUninit;
249
250 pub fn get_scheduler(pid: Pid) -> RtResult<Scheduler> {
253 let res = unsafe { libc::sched_getscheduler(pid.into()) };
254 handle_errno(res).and_then(Scheduler::try_from)
255 }
256
257 pub fn set_scheduler(pid: Pid, scheduler: Scheduler, param: SchedulerParams) -> RtResult<()> {
267 let param: libc::sched_param = param.into();
268 let res = unsafe { libc::sched_setscheduler(pid.into(), scheduler as c_int, ¶m) };
269
270 handle_errno(res).map(drop)
271 }
272
273 pub fn get_scheduler_params(pid: Pid) -> RtResult<SchedulerParams> {
276 let mut param: MaybeUninit<libc::sched_param> = MaybeUninit::uninit();
277 let res = unsafe { libc::sched_getparam(pid.into(), param.as_mut_ptr()) };
278
279 handle_errno(res).map(|_| unsafe { param.assume_init() }.into())
280 }
281 pub fn set_scheduler_params(pid: Pid, param: SchedulerParams) -> RtResult<()> {
287 let param: libc::sched_param = param.into();
288 let res = unsafe { libc::sched_setparam(pid.into(), ¶m) };
289 handle_errno(res).map(drop)
290 }
291}
292
293#[cfg(target_os = "linux")]
294pub use linux::*;