strat9_kernel/syscall/time.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//! Time-related syscalls: clock_gettime, nanosleep, clock_nanosleep
24
25use core::sync::atomic::{AtomicI64, AtomicU8, Ordering};
26
27use crate::{
28 memory::userslice::{UserSliceRead, UserSliceReadWrite},
29 process::{block_current_task, current_task_id, yield_task},
30 syscall::error::SyscallError,
31};
32
33pub use strat9_abi::data::TimeSpec;
34
35// SAFETY: TimeSpec is a #[repr(C)] struct with two i64 fields : all bit
36// patterns are valid. Implementing the sealed UserPod trait here allows
37// read_val::<TimeSpec>() / write_val(&TimeSpec) in UserSlice.
38unsafe impl crate::memory::userslice::UserPod for TimeSpec {}
39
40/// Clock IDs for clock_gettime (POSIX-compatible subset)
41pub const CLOCK_MONOTONIC: u32 = 1;
42pub const CLOCK_REALTIME: u32 = 0;
43
44/// Flag for clock_nanosleep: request is an absolute time based on the clock.
45const TIMER_ABSTIME: i32 = 1;
46
47/// Get current monotonic time in nanoseconds since boot.
48///
49/// Uses the scheduler tick counter (100Hz = 10ms per tick).
50#[inline]
51pub fn current_time_ns() -> u64 {
52 crate::process::scheduler::ticks() * 10_000_000 // 10ms = 10,000,000 ns
53}
54
55// ============================================================================
56// Wall clock (CLOCK_REALTIME)
57// ============================================================================
58
59/// `0` = not initialised, `1` = one CPU is reading the RTC, `2` = ready.
60static WALL_STATE: AtomicU8 = AtomicU8::new(0);
61/// `realtime - monotonic`, in nanoseconds (Unix epoch based).
62static WALL_OFFSET_NS: AtomicI64 = AtomicI64::new(0);
63
64/// Whether the CMOS fields describe a believable date. A never-programmed
65/// CMOS reads back as zeroes / 0xFF, which `to_timestamp` happily turns into
66/// an instant that *looks* valid, so the fields must be checked first.
67fn rtc_plausible(dt: &crate::hardware::timer::rtc::RtcDateTime) -> bool {
68 (1..=12).contains(&dt.month)
69 && (1..=31).contains(&dt.day)
70 && dt.hour <= 23
71 && dt.minute <= 59
72 && dt.second <= 60
73 && (2000..=2100).contains(&dt.year)
74}
75
76/// Seed the wall clock from the RTC the first time it is needed.
77fn ensure_wall_clock() {
78 if WALL_STATE.load(Ordering::Acquire) == 2 {
79 return;
80 }
81 if WALL_STATE
82 .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
83 .is_err()
84 {
85 return; // another CPU is initialising; offset 0 until it is done
86 }
87 let mono = current_time_ns() as i64;
88 // The first caller is usually the VFS at early boot, long before
89 // `rtc::init()` runs, so read the CMOS directly rather than waiting for
90 // `is_available()`: the read only needs port I/O. A CMOS that was never
91 // programmed (or a platform with stubbed port I/O) fails the plausibility
92 // check and leaves the clock on uptime.
93 let dt = crate::hardware::timer::rtc::get_datetime();
94 if rtc_plausible(&dt) {
95 let unix_ns = (dt.to_timestamp() as i64).saturating_mul(1_000_000_000);
96 WALL_OFFSET_NS.store(unix_ns - mono, Ordering::Release);
97 }
98 WALL_STATE.store(2, Ordering::Release);
99}
100
101/// Current wall-clock time in nanoseconds since the Unix epoch.
102///
103/// Backed by the RTC (read once, then advanced by the monotonic tick
104/// counter) and adjustable with [`set_realtime_ns`] (e.g. `ntpdate`). With no
105/// usable RTC it degrades to uptime, i.e. the previous behaviour.
106pub fn realtime_ns() -> u64 {
107 ensure_wall_clock();
108 let off = WALL_OFFSET_NS.load(Ordering::Acquire);
109 (current_time_ns() as i64).saturating_add(off).max(0) as u64
110}
111
112/// `realtime - monotonic` offset in nanoseconds.
113fn wall_offset_ns() -> i64 {
114 ensure_wall_clock();
115 WALL_OFFSET_NS.load(Ordering::Acquire)
116}
117
118/// Step the wall clock to `unix_ns` nanoseconds since the Unix epoch.
119pub fn set_realtime_ns(unix_ns: u64) {
120 let mono = current_time_ns() as i64;
121 WALL_OFFSET_NS.store((unix_ns as i64) - mono, Ordering::Release);
122 WALL_STATE.store(2, Ordering::Release);
123}
124
125/// SYS_CLOCK_GETTIME: Get current time for the specified clock.
126///
127/// # Arguments
128/// * `clock_id` - Clock identifier (CLOCK_MONOTONIC or CLOCK_REALTIME)
129/// * `tp_ptr` - Pointer to userspace timespec structure to fill
130///
131/// # Returns
132/// * 0 on success
133/// * -EINVAL if clock_id is invalid
134/// * -EFAULT if tp_ptr is invalid
135///
136/// # POSIX compatibility
137/// This follows the POSIX signature: `int clock_gettime(clockid_t clock_id, struct timespec *tp)`
138pub fn sys_clock_gettime(clock_id: u32, tp_ptr: u64) -> Result<u64, SyscallError> {
139 if tp_ptr == 0 {
140 return Err(SyscallError::Fault);
141 }
142
143 // CLOCK_MONOTONIC counts from boot; CLOCK_REALTIME is the RTC-backed
144 // wall clock (Unix epoch).
145 let now_ns = match clock_id {
146 CLOCK_MONOTONIC => current_time_ns(),
147 CLOCK_REALTIME => realtime_ns(),
148 _ => return Err(SyscallError::InvalidArgument),
149 };
150 let ts = TimeSpec::from_nanos(now_ns);
151
152 let user = UserSliceReadWrite::new(tp_ptr, core::mem::size_of::<TimeSpec>())?;
153 user.write_val(&ts).map_err(|_| SyscallError::Fault)?;
154 Ok(0)
155}
156
157/// SYS_NANOSLEEP: Sleep for a specified duration.
158///
159/// # Arguments
160/// * `req_ptr` - Pointer to timespec structure with requested sleep duration
161/// * `rem_ptr` - Optional pointer to timespec for remaining time (if interrupted)
162///
163/// # Returns
164/// * 0 on success
165/// * -EINTR if interrupted by a signal (remaining time written to rem_ptr)
166/// * -EINVAL if the requested time is invalid
167pub fn sys_nanosleep(req_ptr: u64, rem_ptr: u64) -> Result<u64, SyscallError> {
168 // Read the requested timespec from userspace
169 let req_slice = UserSliceRead::new(req_ptr, core::mem::size_of::<TimeSpec>() as usize)
170 .map_err(|_| SyscallError::Fault)?; // EFAULT
171
172 let req = req_slice
173 .read_val::<TimeSpec>()
174 .map_err(|_| SyscallError::Fault)?;
175
176 // Validate the request
177 if req.tv_sec < 0 || req.tv_nsec < 0 || req.tv_nsec >= 1_000_000_000 {
178 return Err(SyscallError::InvalidArgument); // EINVAL
179 }
180
181 // Handle zero-duration sleep (just yield)
182 if req.tv_sec == 0 && req.tv_nsec == 0 {
183 yield_task();
184 return Ok(0);
185 }
186
187 let sleep_duration_ns = req.to_nanos();
188 let current_ns = current_time_ns();
189 let wake_deadline_ns = current_ns.saturating_add(sleep_duration_ns);
190
191 // Get current task ID
192 let task_id = current_task_id().ok_or_else(|| SyscallError::PermissionDenied)?; // EPERM
193
194 // Set the wake deadline on the task
195 if let Some(task) = crate::process::get_task_by_id(task_id) {
196 task.wake_deadline_ns
197 .store(wake_deadline_ns, Ordering::Relaxed);
198 }
199
200 // Block the current task - it will be woken by:
201 // 1. timer_tick() when the deadline expires (check_wake_deadlines)
202 // 2. A signal (in which case we return EINTR)
203
204 // Check for pending signals before blocking
205 if let Some(task) = crate::process::get_task_by_id(task_id) {
206 let pending = task.pending_signals.get_mask();
207 let blocked = task.blocked_signals.get_mask();
208 let unblocked_pending = pending & !blocked;
209 if unblocked_pending != 0 {
210 // Clear the deadline since we're not sleeping
211 task.wake_deadline_ns.store(0, Ordering::Relaxed);
212 return Err(SyscallError::Interrupted); // EINTR
213 }
214 }
215
216 loop {
217 block_current_task();
218
219 if let Some(task) = crate::process::get_task_by_id(task_id) {
220 let deadline = task.wake_deadline_ns.load(Ordering::Relaxed);
221 let now = current_time_ns();
222
223 if deadline == 0 || now >= deadline {
224 task.wake_deadline_ns.store(0, Ordering::Relaxed);
225 return Ok(0);
226 }
227
228 if crate::process::has_pending_signals() {
229 task.wake_deadline_ns.store(0, Ordering::Relaxed);
230 if rem_ptr != 0 {
231 let remaining_ns = deadline - now;
232 let remaining = TimeSpec::from_nanos(remaining_ns);
233 let rem_slice =
234 UserSliceReadWrite::new(rem_ptr, core::mem::size_of::<TimeSpec>() as usize)
235 .map_err(|_| SyscallError::Fault)?;
236 rem_slice
237 .write_val(&remaining)
238 .map_err(|_| SyscallError::Fault)?;
239 }
240 return Err(SyscallError::Interrupted);
241 }
242 } else {
243 return Err(SyscallError::Fault);
244 }
245 }
246}
247
248/// SYS_CLOCK_NANOSLEEP: Sleep with clock selection and absolute/relative mode.
249///
250/// # Arguments
251/// * `clock_id` - Clock identifier (CLOCK_MONOTONIC or CLOCK_REALTIME)
252/// * `flags` - 0 for relative sleep, TIMER_ABSTIME (1) for absolute wake-up time
253/// * `req_ptr` - Pointer to timespec (absolute time if TIMER_ABSTIME, else duration)
254/// * `rem_ptr` - Optional pointer to timespec for remaining time (relative mode only)
255///
256/// # Returns
257/// * 0 on success
258/// * -EINTR if interrupted by a signal
259/// * -EINVAL if clock_id or timespec is invalid
260/// * -EFAULT if req_ptr is invalid
261///
262/// # POSIX compatibility
263/// POSIX signature: `int clock_nanosleep(clockid_t clock_id, int flags,
264/// const struct timespec *request,
265/// struct timespec *remain)`
266pub fn sys_clock_nanosleep(
267 clock_id: u32,
268 flags: i32,
269 req_ptr: u64,
270 rem_ptr: u64,
271) -> Result<u64, SyscallError> {
272 // Validate clock_id
273 match clock_id {
274 CLOCK_MONOTONIC | CLOCK_REALTIME => {}
275 _ => return Err(SyscallError::InvalidArgument),
276 }
277
278 // Read the request timespec from userspace
279 let req_slice = UserSliceRead::new(req_ptr, core::mem::size_of::<TimeSpec>() as usize)
280 .map_err(|_| SyscallError::Fault)?;
281
282 let req = req_slice
283 .read_val::<TimeSpec>()
284 .map_err(|_| SyscallError::Fault)?;
285
286 // Validate the timespec fields
287 if req.tv_sec < 0 || req.tv_nsec < 0 || req.tv_nsec >= 1_000_000_000 {
288 return Err(SyscallError::InvalidArgument);
289 }
290
291 let current_ns = current_time_ns();
292
293 // Compute the wake deadline
294 let wake_deadline_ns = if (flags & TIMER_ABSTIME) != 0 {
295 // Absolute mode: request value IS the deadline. Wake deadlines run on
296 // the monotonic scheduler clock, so shift a wall-clock request back.
297 let mut deadline = req.to_nanos();
298 if clock_id == CLOCK_REALTIME {
299 let off = wall_offset_ns();
300 deadline = if off >= 0 {
301 deadline.saturating_sub(off as u64)
302 } else {
303 deadline.saturating_add(off.unsigned_abs())
304 };
305 }
306 // If the deadline is in the past, return immediately (success per POSIX)
307 if deadline <= current_ns {
308 return Ok(0);
309 }
310 deadline
311 } else {
312 // Relative mode: deadline = now + request duration
313 let sleep_duration_ns = req.to_nanos();
314
315 // Handle zero-duration sleep (just yield)
316 if sleep_duration_ns == 0 {
317 yield_task();
318 return Ok(0);
319 }
320
321 current_ns.saturating_add(sleep_duration_ns)
322 };
323
324 // Get current task ID
325 let task_id = current_task_id().ok_or_else(|| SyscallError::PermissionDenied)?;
326
327 // Set the wake deadline on the task
328 if let Some(task) = crate::process::get_task_by_id(task_id) {
329 task.wake_deadline_ns
330 .store(wake_deadline_ns, Ordering::Relaxed);
331 }
332
333 // Check for pending signals before blocking
334 if let Some(task) = crate::process::get_task_by_id(task_id) {
335 let pending = task.pending_signals.get_mask();
336 let blocked = task.blocked_signals.get_mask();
337 let unblocked_pending = pending & !blocked;
338 if unblocked_pending != 0 {
339 task.wake_deadline_ns.store(0, Ordering::Relaxed);
340 return Err(SyscallError::Interrupted);
341 }
342 }
343
344 loop {
345 block_current_task();
346
347 if let Some(task) = crate::process::get_task_by_id(task_id) {
348 let deadline = task.wake_deadline_ns.load(Ordering::Relaxed);
349 let now = current_time_ns();
350
351 if deadline == 0 || now >= deadline {
352 task.wake_deadline_ns.store(0, Ordering::Relaxed);
353 return Ok(0);
354 }
355
356 if crate::process::has_pending_signals() {
357 task.wake_deadline_ns.store(0, Ordering::Relaxed);
358
359 // Write remaining time only in relative mode
360 if (flags & TIMER_ABSTIME) == 0 && rem_ptr != 0 {
361 let remaining_ns = deadline - now;
362 let remaining = TimeSpec::from_nanos(remaining_ns);
363 let rem_slice =
364 UserSliceReadWrite::new(rem_ptr, core::mem::size_of::<TimeSpec>() as usize)
365 .map_err(|_| SyscallError::Fault)?;
366 rem_slice
367 .write_val(&remaining)
368 .map_err(|_| SyscallError::Fault)?;
369 }
370 return Err(SyscallError::Interrupted);
371 }
372 } else {
373 return Err(SyscallError::Fault);
374 }
375 }
376}