osal_rs/posix/system.rs
1/***************************************************************************
2 *
3 * osal-rs
4 * Copyright (C) 2026 Antonio Salsi <passy.linux@zresa.it>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
18 *
19 ***************************************************************************/
20
21//! System-level control and timing for POSIX.
22//!
23//! [`System`] provides the scheduler-adjacent operations that don't belong
24//! to any single primitive: starting/stopping the "run loop", timing
25//! (`CLOCK_MONOTONIC`-based), and querying/suspending the threads spawned
26//! through this crate's [`crate::os::Thread`] API. Unlike FreeRTOS, POSIX has
27//! no real scheduler to hand control to, so [`System::start`] just spins
28//! until [`System::stop`] is called from another thread.
29//!
30//! # Examples
31//!
32//! ```
33//! use osal_rs::os::*;
34//! use std::sync::Arc;
35//!
36//! // Something else must call `System::stop()` for `start()` to return.
37//! let mut stopper = Thread::new("stopper", 1024, 1);
38//! stopper.spawn_simple(|| {
39//! System::delay(10);
40//! System::stop();
41//! Ok(Arc::new(()))
42//! }).unwrap();
43//!
44//! System::start(); // blocks here until `stop()` runs above
45//! ```
46
47use core::ffi::c_long;
48use core::ops::Deref;
49use core::time::Duration;
50use std::sync::atomic::{AtomicBool, Ordering};
51
52use alloc::vec::Vec;
53
54use crate::os::ThreadFn;
55use crate::posix::ffi::{
56 CLOCK_MONOTONIC, PTHREAD_ONCE_INIT, _SC_AVPHYS_PAGES, _SC_PAGESIZE, clock_gettime, nanosleep, pthread_once, pthread_once_t, pthread_self, sched_yield, sysconf, timespec,
57};
58use crate::posix::thread::{Thread, all_registered_threads, registered_thread_count};
59use crate::posix::types::{BaseType, TickType, UBaseType};
60use crate::traits::{SystemFn, ThreadMetadata, ThreadState, ToTick};
61use crate::utils::OsalRsBool;
62
63static RUN: AtomicBool = AtomicBool::new(true);
64
65/// Snapshot returned by [`System::get_all_thread`]: every thread spawned
66/// through this crate's [`crate::os::Thread`] API (plus the calling thread
67/// itself), and the total elapsed run time at the moment of the snapshot.
68/// Derefs to `&[ThreadMetadata]` for convenient iteration.
69///
70/// # Examples
71///
72/// ```
73/// use osal_rs::os::*;
74///
75/// let state = System::get_all_thread();
76/// // The calling thread is always included.
77/// assert!(!state.is_empty());
78/// ```
79#[derive(Debug, Clone)]
80pub struct SystemState {
81 /// Metadata for every thread spawned through this crate's
82 /// [`crate::os::Thread`] API, plus the calling thread itself.
83 pub tasks: Vec<ThreadMetadata>,
84 /// Total elapsed run time, in milliseconds, at the moment of the
85 /// snapshot (see [`System::get_tick_count`]).
86 pub total_run_time: u32,
87}
88
89impl Deref for SystemState {
90 type Target = [ThreadMetadata];
91
92 fn deref(&self) -> &Self::Target {
93 &self.tasks
94 }
95}
96
97/// Namespace for system-level operations (scheduler control, timing, thread
98/// introspection) - see the [module docs](self) for an overview and a
99/// runnable example. Zero-sized: never instantiated, only used as
100/// `System::function(...)`.
101pub struct System;
102
103impl System {
104 /// Blocks like [`System::delay`], but accepts any [`ToTick`] duration
105 /// (e.g. a [`core::time::Duration`]) instead of a raw tick count.
106 ///
107 /// # Examples
108 ///
109 /// ```
110 /// use osal_rs::os::*;
111 /// use core::time::Duration;
112 ///
113 /// let before = System::get_tick_count();
114 /// System::delay_with_to_tick(Duration::from_millis(10));
115 /// assert!(System::get_tick_count() >= before);
116 /// ```
117 #[inline]
118 pub fn delay_with_to_tick(ticks: impl ToTick) {
119 Self::delay(ticks.to_ticks());
120 }
121
122 /// Blocks like [`System::delay_until`], but accepts any [`ToTick`]
123 /// increment (e.g. a [`core::time::Duration`]) instead of a raw tick
124 /// count.
125 ///
126 /// # Examples
127 ///
128 /// ```
129 /// use osal_rs::os::*;
130 /// use core::time::Duration;
131 ///
132 /// let mut previous = System::get_tick_count();
133 /// System::delay_until_with_to_tick(&mut previous, Duration::from_millis(5));
134 /// ```
135 #[inline]
136 pub fn delay_until_with_to_tick(previous_wake_time: &mut TickType, time_increment: impl ToTick) {
137 Self::delay_until(previous_wake_time, time_increment.to_ticks());
138 }
139
140 fn monotonic_now() -> Duration {
141 let mut ts = timespec::default();
142 unsafe { clock_gettime(CLOCK_MONOTONIC, &mut ts) };
143
144 Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
145 }
146
147 fn start_time() -> Duration {
148 static mut ONCE: pthread_once_t = PTHREAD_ONCE_INIT;
149 static mut START_TIME: Duration = Duration::ZERO;
150
151 extern "C" fn init() {
152 unsafe {
153 START_TIME = System::monotonic_now();
154 }
155 // Without this, a caller landing within nanoseconds of the
156 // epoch capture above would measure 0 elapsed ms (millisecond
157 // resolution) on its very first read, since `pthread_once`
158 // blocks every other racing caller until `init` returns.
159 // Paid once per process, lazily, only if timing is ever used.
160 System::delay(1);
161 }
162
163 unsafe {
164 pthread_once(&raw mut ONCE, Some(init));
165 START_TIME
166 }
167 }
168
169 fn elapsed() -> Duration {
170 Self::monotonic_now().checked_sub(Self::start_time()).unwrap_or_default()
171 }
172}
173
174impl SystemFn for System {
175 /// Spins until [`System::stop`] is called from another thread. There is
176 /// no real scheduler on POSIX to hand control to, so this is just a busy
177 /// loop over an atomic flag - unlike FreeRTOS, where the equivalent call
178 /// never returns.
179 ///
180 /// # Examples
181 ///
182 /// ```
183 /// use osal_rs::os::*;
184 /// use std::sync::Arc;
185 ///
186 /// let mut stopper = Thread::new("stopper", 1024, 1);
187 /// stopper.spawn_simple(|| {
188 /// System::delay(10);
189 /// System::stop();
190 /// Ok(Arc::new(()))
191 /// }).unwrap();
192 ///
193 /// System::start(); // blocks here until `stop()` runs above
194 /// ```
195 fn start() {
196 loop {
197 if !RUN.load(Ordering::Acquire) {
198 break;
199 }
200 }
201 }
202
203 /// Suspends every currently `Ready`/`Running` thread spawned through
204 /// this crate's [`crate::os::Thread`] API (see
205 /// [`crate::os::ThreadFn::suspend`]).
206 ///
207 /// # Examples
208 ///
209 /// ```
210 /// use osal_rs::os::*;
211 /// use std::sync::Arc;
212 ///
213 /// let mut worker = Thread::new("worker", 1024, 1);
214 /// worker.spawn_simple(|| {
215 /// System::delay(200);
216 /// Ok(Arc::new(()))
217 /// }).unwrap();
218 ///
219 /// System::delay(10); // give it a moment to start running
220 /// System::suspend_all();
221 /// assert!(System::resume_all() >= 1);
222 /// ```
223 fn suspend_all() {
224 for tm in all_registered_threads() {
225 if let Ok(t) = Thread::new_with_handle(tm.thread, tm.name.as_str(), tm.stack_depth, tm.current_priority) {
226 if tm.state == ThreadState::Ready || tm.state == ThreadState::Running {
227 t.suspend();
228 }
229 }
230 }
231 }
232
233 /// Resumes every currently `Suspended` thread spawned through this
234 /// crate's [`crate::os::Thread`] API, returning how many were resumed.
235 ///
236 /// See [`System::suspend_all`] for a complete example.
237 fn resume_all() -> BaseType {
238 let mut count = 0;
239
240 for tm in all_registered_threads() {
241 if let Ok(t) = Thread::new_with_handle(tm.thread, tm.name.as_str(), tm.stack_depth, tm.current_priority) {
242 if tm.state == ThreadState::Suspended {
243 t.resume();
244 count += 1;
245 }
246 }
247 }
248
249 count
250 }
251
252 /// Signals [`System::start`]'s spin loop to return. See
253 /// [`System::start`] for a complete example.
254 fn stop() {
255 RUN.store(false, Ordering::Release);
256 }
257
258 /// Returns the number of ticks elapsed since the first time any of
259 /// [`System::get_tick_count`]/[`System::get_current_time_us`] was called
260 /// in this process (that first call defines tick `0`).
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// use osal_rs::os::*;
266 ///
267 /// let before = System::get_tick_count();
268 /// System::delay(5);
269 /// assert!(System::get_tick_count() >= before);
270 /// ```
271 fn get_tick_count() -> TickType {
272 Self::elapsed().as_millis().min(TickType::MAX as u128) as TickType
273 }
274
275 /// Same reference point as [`System::get_tick_count`], but returned as a
276 /// [`Duration`] instead of a raw tick count.
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// use osal_rs::os::*;
282 ///
283 /// let before = System::get_current_time_us();
284 /// System::delay(5);
285 /// assert!(System::get_current_time_us() >= before);
286 /// ```
287 fn get_current_time_us() -> Duration {
288 Self::elapsed()
289 }
290
291 /// Converts a [`Duration`] to POSIX ticks (milliseconds); see
292 /// `crate::posix::duration` for the same conversion via [`ToTick`].
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use osal_rs::os::*;
298 /// use core::time::Duration;
299 ///
300 /// assert_eq!(System::get_ms_from_tick(&Duration::from_millis(250)), 250);
301 /// ```
302 fn get_ms_from_tick(duration: &Duration) -> TickType {
303 duration.as_millis().min(TickType::MAX as u128) as TickType
304 }
305
306 /// Number of threads known to the system: every thread spawned through
307 /// this crate's [`crate::os::Thread`] API, plus the calling thread
308 /// itself.
309 ///
310 /// # Examples
311 ///
312 /// ```
313 /// use osal_rs::os::*;
314 ///
315 /// // Just the calling thread: nothing else has been spawned yet.
316 /// assert_eq!(System::count_threads(), 1);
317 /// ```
318 fn count_threads() -> usize {
319 // +1 for the calling thread itself, which `get_all_thread()` below
320 // always reports even when it wasn't spawned through this crate's API.
321 1 + registered_thread_count()
322 }
323
324 /// Returns a [`SystemState`] snapshot of every thread known to the
325 /// system, mirroring [`System::count_threads`]'s "+1 for the caller"
326 /// accounting.
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// use osal_rs::os::*;
332 ///
333 /// let state = System::get_all_thread();
334 /// assert_eq!(state.len(), System::count_threads());
335 /// ```
336 fn get_all_thread() -> SystemState {
337 let mut tasks = all_registered_threads();
338
339 // Mirror `count_threads()`'s +1: report the calling thread even when
340 // it wasn't spawned through this crate's API. Skip it if the caller
341 // is itself a registered thread (e.g. a spawned worker calling this
342 // from within its own thread function), to avoid double-counting.
343 let caller = unsafe { pthread_self() };
344 if !tasks.iter().any(|metadata| metadata.thread == caller) {
345 tasks.push(Thread::get_metadata_from_handle(caller));
346 }
347
348 SystemState {
349 tasks,
350 total_run_time: Self::get_tick_count().min(TickType::MAX) as u32,
351 }
352 }
353
354 /// Blocks the calling thread for `ticks` (milliseconds on this
355 /// backend), automatically resuming the sleep if interrupted by a
356 /// signal before it elapsed.
357 ///
358 /// # Examples
359 ///
360 /// ```
361 /// use osal_rs::os::*;
362 ///
363 /// let before = System::get_tick_count();
364 /// System::delay(20);
365 /// assert!(System::get_tick_count() - before >= 20);
366 /// ```
367 fn delay(ticks: TickType) {
368 let mut req = timespec {
369 tv_sec: (ticks / 1000) as c_long,
370 tv_nsec: ((ticks % 1000) as c_long) * 1_000_000,
371 };
372
373 loop {
374 let mut rem = timespec::default();
375
376 if unsafe { nanosleep(&req, &mut rem) } == 0 {
377 break;
378 }
379
380 // Interrupted by a signal before `req` elapsed: `rem` holds the
381 // time still left to sleep, so resume with that. If the kernel
382 // left `rem` untouched (a real error, not EINTR), it'll be zero
383 // and the loop exits instead of spinning forever.
384 if rem.tv_sec == 0 && rem.tv_nsec == 0 {
385 break;
386 }
387
388 req = rem;
389 }
390 }
391
392 /// Blocks until `*previous_wake_time + time_increment` (absolute ticks),
393 /// then advances `*previous_wake_time` by `time_increment` - a fixed
394 /// period loop that doesn't drift with the time spent doing work each
395 /// iteration, unlike calling [`System::delay`] with the same increment
396 /// every time.
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// use osal_rs::os::*;
402 ///
403 /// let before = System::get_tick_count();
404 /// let mut previous = before;
405 /// System::delay_until(&mut previous, 20);
406 ///
407 /// assert_eq!(previous, before + 20);
408 /// assert!(System::get_tick_count() >= previous);
409 /// ```
410 fn delay_until(previous_wake_time: &mut TickType, time_increment: TickType) {
411 let next_wake_time = previous_wake_time.saturating_add(time_increment);
412 let now = Self::get_tick_count();
413
414 if next_wake_time > now {
415 Self::delay(next_wake_time - now);
416 }
417
418 *previous_wake_time = next_wake_time;
419 }
420
421 /// Returns [`OsalRsBool::True`] once at least `time` has elapsed since
422 /// `timestamp` (both measured against [`System::get_current_time_us`]'s
423 /// clock).
424 ///
425 /// # Examples
426 ///
427 /// ```
428 /// use osal_rs::os::*;
429 /// use osal_rs::utils::OsalRsBool;
430 /// use core::time::Duration;
431 ///
432 /// let start = System::get_current_time_us();
433 /// assert_eq!(System::check_timer(&start, &Duration::from_millis(500)), OsalRsBool::False);
434 ///
435 /// System::delay(20);
436 /// assert_eq!(System::check_timer(&start, &Duration::from_millis(10)), OsalRsBool::True);
437 /// ```
438 fn check_timer(timestamp: &Duration, time: &Duration) -> OsalRsBool {
439 let elapsed = Self::get_current_time_us().checked_sub(*timestamp).unwrap_or_default();
440
441 if elapsed >= *time {
442 OsalRsBool::True
443 } else {
444 OsalRsBool::False
445 }
446 }
447
448 /// Yields the processor (`sched_yield(2)`) if `higher_priority_task_woken`
449 /// is non-zero, a no-op otherwise. On FreeRTOS this triggers a context
450 /// switch to a just-woken higher-priority task from within an ISR; POSIX
451 /// has no real interrupt context, so this exists purely for API
452 /// compatibility.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// use osal_rs::os::*;
458 ///
459 /// System::yield_from_isr(1); // yields
460 /// System::yield_from_isr(0); // no-op
461 /// ```
462 fn yield_from_isr(higher_priority_task_woken: BaseType) {
463 if higher_priority_task_woken != 0 {
464 unsafe {
465 sched_yield();
466 }
467 }
468 }
469
470 /// Identical to [`System::yield_from_isr`] under a different name,
471 /// matching FreeRTOS's `portEND_SWITCHING_ISR` naming convention.
472 ///
473 /// # Examples
474 ///
475 /// ```
476 /// use osal_rs::os::*;
477 ///
478 /// System::end_switching_isr(1);
479 /// ```
480 fn end_switching_isr(switch_required: BaseType) {
481 if switch_required != 0 {
482 unsafe {
483 sched_yield();
484 }
485 }
486 }
487
488 /// No-op on POSIX: there is no real interrupt/scheduler state to guard,
489 /// unlike FreeRTOS where this disables interrupts/the scheduler.
490 ///
491 /// # Examples
492 ///
493 /// ```
494 /// use osal_rs::os::*;
495 ///
496 /// System::critical_section_enter();
497 /// System::critical_section_exit();
498 /// ```
499 fn critical_section_enter() {}
500
501 /// See [`System::critical_section_enter`].
502 fn critical_section_exit() {}
503
504 /// ISR-context counterpart of [`System::critical_section_enter`]; always
505 /// returns `0` (nothing to restore) since it's a no-op on POSIX.
506 ///
507 /// # Examples
508 ///
509 /// ```
510 /// use osal_rs::os::*;
511 ///
512 /// let saved = System::critical_section_enter_from_isr();
513 /// System::critical_section_exit_from_isr(saved);
514 /// ```
515 fn critical_section_enter_from_isr() -> UBaseType {
516 0
517 }
518
519 /// See [`System::critical_section_enter_from_isr`].
520 fn critical_section_exit_from_isr(_: UBaseType) {}
521
522 /// POSIX processes don't have a fixed heap the way FreeRTOS does (the
523 /// allocator can keep extending it via `mmap`/`brk`), so this reports
524 /// available physical memory as the closest analogue.
525 ///
526 /// # Examples
527 ///
528 /// ```
529 /// use osal_rs::os::*;
530 ///
531 /// assert!(System::get_free_heap_size() > 0);
532 /// ```
533 fn get_free_heap_size() -> usize {
534 // POSIX processes don't have a fixed heap the way FreeRTOS does (the
535 // allocator can keep extending it via mmap/brk), so this reports
536 // available physical memory as the closest analogue.
537 let page_size = unsafe { sysconf(_SC_PAGESIZE) };
538 let avail_pages = unsafe { sysconf(_SC_AVPHYS_PAGES) };
539
540 if page_size <= 0 || avail_pages <= 0 {
541 0
542 } else {
543 (page_size as usize).saturating_mul(avail_pages as usize)
544 }
545 }
546}