Skip to main content

strat9_kernel/syscall/
sched.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Scheduling syscalls (`SYS_SCHED_*`, block 345-349).
24//!
25//! Before this module, a userspace task could not change its policy, its
26//! priority or its CPU affinity: all three were fixed at creation from the
27//! silo configuration. The kernel already implements every scheduling class
28//! (`SchedPolicy`), so this is an exposure layer, not a scheduler rewrite.
29//!
30//! Scope is deliberately limited to the calling task. Becoming real-time is
31//! gated on silo-admin capability until a dedicated scheduling capability
32//! resource exists (tracked as security work R11); dropping to Fair/Idle is
33//! always allowed so a task can never trap itself in an unschedulable state.
34
35use super::error::SyscallError;
36use crate::{
37    memory::UserSliceWrite,
38    process::{
39        current_task_clone,
40        sched::{nice::Nice, real_time::RealTimePriority, SchedPolicy},
41        set_task_sched_policy, Task, TaskPriority,
42    },
43};
44
45use strat9_abi::{
46    data::{SchedInfo, SCHED_INFO_FLAG_RT_DEGRADED},
47    syscall::{SCHED_POLICY_FAIR, SCHED_POLICY_FIFO, SCHED_POLICY_IDLE, SCHED_POLICY_RR},
48};
49
50/// Decode an ABI policy/priority pair into a kernel [`SchedPolicy`].
51///
52/// The priority travels in the low 32 bits of the argument and is
53/// interpreted as a signed `i32` so that Nice values below zero survive the
54/// register-width round trip. The upper 32 bits must be a valid sign
55/// extension, otherwise the caller is guessing and gets `EINVAL`.
56fn decode_policy(policy: u32, priority: u64) -> Result<SchedPolicy, SyscallError> {
57    let high = priority >> 32;
58    if high != 0 && high != u32::MAX as u64 {
59        return Err(SyscallError::InvalidArgument);
60    }
61    let priority = priority as u32 as i32;
62
63    match policy {
64        SCHED_POLICY_FAIR => {
65            if !(-20..=19).contains(&priority) {
66                return Err(SyscallError::InvalidArgument);
67            }
68            Ok(SchedPolicy::Fair(Nice::new(priority as i8)))
69        }
70        SCHED_POLICY_RR | SCHED_POLICY_FIFO => {
71            if !(0..=99).contains(&priority) {
72                return Err(SyscallError::InvalidArgument);
73            }
74            let prio = RealTimePriority::new(priority as u8);
75            if policy == SCHED_POLICY_RR {
76                Ok(SchedPolicy::RealTimeRR { prio })
77            } else {
78                Ok(SchedPolicy::RealTimeFifo { prio })
79            }
80        }
81        SCHED_POLICY_IDLE => Ok(SchedPolicy::Idle),
82        _ => Err(SyscallError::InvalidArgument),
83    }
84}
85
86/// Whether `new` gives more CPU entitlement than the task was created with.
87///
88/// The creation [`TaskPriority`] is the delegation ceiling: a task may lower
89/// itself freely (longer Nice, Idle, lower RT priority) but needs an
90/// administrative capability to go above it. This closes the `Nice -20`
91/// starvation hole without trapping a task that temporarily lowered itself:
92/// it can always return to its ceiling.
93fn exceeds_priority_ceiling(base: TaskPriority, new: SchedPolicy) -> bool {
94    use SchedPolicy::*;
95    match (Task::default_sched_policy(base), new) {
96        // Idle is always a downgrade.
97        (_, Idle) => false,
98        // Real-time created tasks may use any Fair value or lower RT prio.
99        (RealTimeRR { .. } | RealTimeFifo { .. }, Fair(_)) => false,
100        (
101            RealTimeRR { prio: b } | RealTimeFifo { prio: b },
102            RealTimeRR { prio: n } | RealTimeFifo { prio: n },
103        ) => n.get() > b.get(),
104        // Fair tasks may move to a greater (lower-priority) Nice value only.
105        (Fair(b), Fair(n)) => n.value().get() < b.value().get(),
106        (Fair(_), RealTimeRR { .. } | RealTimeFifo { .. }) => true,
107        // Idle-created tasks need a capability to become Fair or RT.
108        (Idle, Fair(_) | RealTimeRR { .. } | RealTimeFifo { .. }) => true,
109    }
110}
111
112/// Encode a kernel [`SchedPolicy`] back into the `(policy, priority)` wire
113/// representation used by `SYS_SCHED_GET`.
114fn encode_policy(policy: SchedPolicy) -> (u32, i32) {
115    match policy {
116        SchedPolicy::Fair(nice) => (SCHED_POLICY_FAIR, nice.value().get() as i32),
117        SchedPolicy::RealTimeRR { prio } => (SCHED_POLICY_RR, prio.get() as i32),
118        SchedPolicy::RealTimeFifo { prio } => (SCHED_POLICY_FIFO, prio.get() as i32),
119        SchedPolicy::Idle => (SCHED_POLICY_IDLE, 0),
120    }
121}
122
123/// `SYS_SCHED_SET(345)`: change the calling task's policy and priority.
124pub fn sys_sched_set(policy: u64, priority: u64) -> Result<u64, SyscallError> {
125    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
126    let policy = u32::try_from(policy).map_err(|_| SyscallError::InvalidArgument)?;
127    let new_policy = decode_policy(policy, priority)?;
128
129    // The creation priority is the delegation ceiling. Raising above it —
130    // including any negative Nice value or a higher RT priority — requires
131    // an administrative capability until a dedicated scheduling capability
132    // resource exists.
133    if exceeds_priority_ceiling(task.priority, new_policy) {
134        crate::silo::require_silo_admin()?;
135    }
136
137    if !set_task_sched_policy(task.id, new_policy) {
138        return Err(SyscallError::NoSuchProcess);
139    }
140
141    // Apply the new class immediately instead of waiting for the next tick:
142    // a task switching to RT should not keep running behind Fair work.
143    crate::process::yield_task();
144    Ok(0)
145}
146
147/// `SYS_SCHED_GET(346)`: read the calling task's policy and priority.
148///
149/// Returns `(policy as u32) | (priority_byte << 32)`. For Fair, the byte is
150/// Nice offset by 20 (`0` = -20, `20` = 0, `39` = 19); for RT it is the
151/// priority (`0..=99`); Idle reports `0`. Keeping the sign out of bit 63
152/// means the packed return can never be mistaken for an errno by a generic
153/// syscall wrapper.
154pub fn sys_sched_get() -> Result<u64, SyscallError> {
155    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
156    let (policy, priority) = encode_policy(task.sched_policy());
157    let priority_byte = if policy == SCHED_POLICY_FAIR {
158        (priority + 20) as u8
159    } else {
160        priority as u8
161    };
162    Ok((policy as u64) | ((priority_byte as u64) << 32))
163}
164
165/// The mask of CPUs currently online, as a 64-bit affinity mask.
166fn online_cpu_mask() -> u64 {
167    let mut online = [0usize; crate::arch::percpu::MAX_CPUS];
168    let n = crate::arch::percpu::online_cpu_indices(&mut online);
169    online[..n].iter().fold(0u64, |mask, &cpu| {
170        if cpu < u64::BITS as usize {
171            mask | (1u64 << cpu)
172        } else {
173            mask
174        }
175    })
176}
177
178/// `SYS_SCHED_SETAFFINITY(347)`: replace the calling task's soft CPU mask.
179///
180/// `0` restores the silo default (or "all CPUs" for a task outside a silo).
181///
182/// The request is checked against the online CPU mask and against the silo's
183/// configured partition: a task can narrow its affinity but cannot widen it
184/// beyond what the silo was granted.
185pub fn sys_sched_setaffinity(mask: u64) -> Result<u64, SyscallError> {
186    let online = online_cpu_mask();
187    if mask != 0 && (mask & !online != 0 || mask & online == 0) {
188        return Err(SyscallError::InvalidArgument);
189    }
190
191    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
192    let allowed = crate::silo::allowed_cpu_affinity_for_task(task.id);
193    let effective = if allowed == 0 {
194        mask
195    } else if mask == 0 {
196        // Clearing within a partitioned silo means "silo default", never
197        // "every CPU".
198        allowed
199    } else if mask & !allowed != 0 {
200        return Err(SyscallError::PermissionDenied);
201    } else {
202        mask
203    };
204
205    task.affinity_mask
206        .store(effective, core::sync::atomic::Ordering::Release);
207    Ok(0)
208}
209
210/// `SYS_SCHED_GETAFFINITY(348)`: read the calling task's soft CPU mask.
211pub fn sys_sched_getaffinity() -> Result<u64, SyscallError> {
212    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
213    Ok(task
214        .affinity_mask
215        .load(core::sync::atomic::Ordering::Acquire))
216}
217
218/// `SYS_SCHED_INFO(349)`: fill a [`SchedInfo`] for the calling task.
219pub fn sys_sched_info(out_ptr: u64) -> Result<u64, SyscallError> {
220    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
221    let out = UserSliceWrite::new(out_ptr, core::mem::size_of::<SchedInfo>())?;
222
223    let (policy, priority) = encode_policy(task.sched_policy());
224    let ticks = task.ticks.load(core::sync::atomic::Ordering::Relaxed);
225    let run_time_ns = ticks.saturating_mul(crate::arch::timer::NS_PER_TICK);
226    let blocked_time_ns = task
227        .blocked_ns_total
228        .load(core::sync::atomic::Ordering::Relaxed);
229    let now = crate::sync::scheduler_clock_ns();
230    let ready_time_ns = now
231        .saturating_sub(task.created_ns)
232        .saturating_sub(run_time_ns)
233        .saturating_sub(blocked_time_ns);
234    let mut info = SchedInfo {
235        policy,
236        state: task.state.load(core::sync::atomic::Ordering::Relaxed) as u32,
237        priority,
238        flags: 0,
239        affinity_mask: task
240            .affinity_mask
241            .load(core::sync::atomic::Ordering::Relaxed),
242        run_time_ns,
243        ticks,
244        vruntime: task.vruntime.load(core::sync::atomic::Ordering::Relaxed),
245        rt_budget_remaining: task
246            .rt_budget_remaining
247            .load(core::sync::atomic::Ordering::Relaxed),
248        rt_overruns: task.rt_overruns.load(core::sync::atomic::Ordering::Relaxed),
249        fair_wait_ticks: task
250            .fair_wait_ticks
251            .load(core::sync::atomic::Ordering::Relaxed),
252        wake_deadline_ns: task
253            .wake_deadline_ns
254            .load(core::sync::atomic::Ordering::Relaxed),
255        blocked_time_ns,
256        ready_time_ns,
257    };
258    if task.rt_degraded.load(core::sync::atomic::Ordering::Relaxed) {
259        info.flags |= SCHED_INFO_FLAG_RT_DEGRADED;
260    }
261
262    let raw = unsafe {
263        core::slice::from_raw_parts(
264            &info as *const SchedInfo as *const u8,
265            core::mem::size_of::<SchedInfo>(),
266        )
267    };
268    if out.copy_from(raw) != raw.len() {
269        return Err(SyscallError::Fault);
270    }
271    Ok(0)
272}