Skip to main content

osal_rs/
lib.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//! # OSAL-RS - Operating System Abstraction Layer for Rust
22//!
23//! A cross-platform abstraction layer for embedded and real-time operating systems.
24//!
25//! ## Overview
26//!
27//! OSAL-RS provides a unified, safe Rust API for working with different real-time
28//! operating systems. Currently supports FreeRTOS with planned support for POSIX
29//! and other RTOSes.
30//!
31//! ## Features
32//!
33//! - **Thread Management**: Create and control threads with priorities
34//! - **Synchronization**: Mutexes, semaphores, and event groups
35//! - **Communication**: Queues for inter-thread message passing
36//! - **Timers**: Software timers for periodic and one-shot operations
37//! - **Time Management**: Duration-based timing with tick conversion
38//! - **No-std Support**: Works in bare-metal embedded environments
39//! - **Type Safety**: Leverages Rust's type system for correctness
40//!
41//! ## Quick Start
42//!
43//! ### Basic Thread Example
44//!
45//! ```ignore
46//! use osal_rs::os::*;
47//! use core::time::Duration;
48//!
49//! fn main() {
50//!     // Create a thread
51//!     let thread = Thread::new(
52//!         "worker",
53//!         4096,  // stack size
54//!         5,     // priority
55//!         || {
56//!             loop {
57//!                 println!("Working...");
58//!                 Duration::from_secs(1).sleep();
59//!             }
60//!         }
61//!     ).unwrap();
62//!
63//!     thread.start().unwrap();
64//!     
65//!     // Start the scheduler
66//!     System::start();
67//! }
68//! ```
69//!
70//! ### Mutex Example
71//!
72//! ```ignore
73//! use osal_rs::os::*;
74//! use alloc::sync::Arc;
75//!
76//! let counter = Arc::new(Mutex::new(0));
77//! let counter_clone = counter.clone();
78//!
79//! let thread = Thread::new("incrementer", 2048, 5, move || {
80//!     let mut guard = counter_clone.lock().unwrap();
81//!     *guard += 1;
82//! }).unwrap();
83//! ```
84//!
85//! ### Queue Example
86//!
87//! ```ignore
88//! use osal_rs::os::*;
89//! use core::time::Duration;
90//!
91//! let queue = Queue::new(10, 4).unwrap();
92//!
93//! // Send data
94//! let data = [1u8, 2, 3, 4];
95//! queue.post(&data, 100).unwrap();
96//!
97//! // Receive data
98//! let mut buffer = [0u8; 4];
99//! queue.fetch(&mut buffer, 100).unwrap();
100//! ```
101//!
102//! ### Semaphore Example
103//!
104//! ```ignore
105//! use osal_rs::os::*;
106//! use core::time::Duration;
107//!
108//! let sem = Semaphore::new(1, 1).unwrap();
109//!
110//! if sem.wait(Duration::from_millis(100)).into() {
111//!     // Critical section
112//!     sem.signal();
113//! }
114//! ```
115//!
116//! ### Timer Example
117//!
118//! ```ignore
119//! use osal_rs::os::*;
120//! use core::time::Duration;
121//!
122//! let timer = Timer::new_with_to_tick(
123//!     "periodic",
124//!     Duration::from_millis(500),
125//!     true,  // auto-reload
126//!     None,
127//!     |_, _| {
128//!         println!("Timer tick");
129//!         Ok(None)
130//!     }
131//! ).unwrap();
132//!
133//! timer.start_with_to_tick(Duration::from_millis(10));
134//! ```
135//!
136//! ## Module Organization
137//!
138//! - [`os`] - Main module containing all OS abstractions
139//!   - Threads, mutexes, semaphores, queues, event groups, timers
140//!   - System-level functions
141//!   - Type definitions
142//! - [`utils`] - Utility types and error definitions
143//! - [`log`] - Logging macros
144//! - `traits` - Private module defining the trait abstractions
145//! - `freertos` - Private FreeRTOS implementation (enabled with `freertos` feature)
146//! - `posix` - Private POSIX implementation (enabled with `posix` feature, planned)
147//!
148//! ## Features
149//!
150//! - `freertos` - Enable FreeRTOS support (default)
151//! - `posix` - Enable POSIX support (planned)
152//! - `posix` - Enable host/POSIX support (uses standard library)
153//!
154//! ## Requirements
155//!
156//! When using with FreeRTOS:
157//! - FreeRTOS kernel must be properly configured
158//! - Link the C porting layer from `osal-rs-porting/freertos/`
159//! - Set appropriate `FreeRTOSConfig.h` options:
160//!   - `configTICK_RATE_HZ` - Defines the tick frequency
161//!   - `configUSE_MUTEXES` - Must be 1 for mutex support
162//!   - `configUSE_COUNTING_SEMAPHORES` - Must be 1 for semaphore support
163//!   - `configUSE_TIMERS` - Must be 1 for timer support
164//!   - `configSUPPORT_DYNAMIC_ALLOCATION` - Must be 1 for dynamic allocation
165//!
166//! ## Platform Support
167//!
168//! Currently tested on:
169//! - ARM Cortex-M (Raspberry Pi Pico/RP2040, RP2350)
170//! - ARM Cortex-M4F (STM32F4 series)
171//! - ARM Cortex-M7 (STM32H7 series)
172//! - RISC-V (RP2350 RISC-V cores)
173//!
174//! ## Thread Safety
175//!
176//! All types are designed with thread safety in mind:
177//! - Most operations are thread-safe and can be called from multiple threads
178//! - Methods with `_from_isr` suffix are ISR-safe (callable from interrupt context)
179//! - Regular methods (without `_from_isr`) must not be called from ISR context
180//! - Mutexes use priority inheritance to prevent priority inversion
181//!
182//! ## ISR Context
183//!
184//! Operations in ISR context have restrictions:
185//! - Cannot block or use timeouts (must use zero timeout or `_from_isr` variants)
186//! - Must be extremely fast to avoid blocking other interrupts
187//! - Use semaphores or queues to defer work to task context
188//! - Event groups and notifications are ISR-safe for signaling
189//!
190//! ## Safety
191//!
192//! This library uses `unsafe` internally to interface with C APIs but provides
193//! safe Rust abstractions. All public APIs are designed to be memory-safe when
194//! used correctly:
195//! - Type safety through generic parameters
196//! - RAII patterns for automatic resource management
197//! - Rust's ownership system prevents data races
198//! - FFI boundaries are carefully validated
199//!
200//! ## Performance Considerations
201//!
202//! - Allocations happen on the FreeRTOS heap, not the system heap
203//! - Stack sizes must be carefully tuned for each thread
204//! - Priority inversion is mitigated through priority inheritance
205//! - Context switches are triggered by blocking operations
206//!
207//! ## Best Practices
208//!
209//! 1. **Thread Creation**: Always specify appropriate stack sizes based on usage
210//! 2. **Mutexes**: Prefer scoped locking with guards to prevent deadlocks
211//! 3. **Queues**: Use type-safe `QueueStreamed` when possible
212//! 4. **Semaphores**: Use binary semaphores for signaling, counting for resources
213//! 5. **ISR Handlers**: Keep ISR code minimal, defer work to tasks
214//! 6. **Error Handling**: Always check `Result` return values
215//!
216//! ## License
217//!
218//! LGPL-2.1-or-later - See LICENSE file for details
219
220#![cfg_attr(not(feature = "posix"), no_std)]
221
222extern crate alloc;
223
224#[cfg(not(any(feature = "freertos", feature = "posix")))]
225compile_error!("Enable either the `freertos` backend or the `posix` host backend.");
226
227/// FreeRTOS implementation of OSAL traits.
228///
229/// This module contains the concrete implementation of all OSAL abstractions
230/// for FreeRTOS, including threads, mutexes, queues, timers, etc.
231///
232/// Enabled with the `freertos` feature flag (on by default).
233#[cfg(feature = "freertos")]
234mod freertos;
235
236/// POSIX implementation of OSAL traits (planned).
237///
238/// This module will contain the implementation for POSIX-compliant systems.
239/// Currently under development.
240///
241/// Enabled with the `posix` feature flag.
242#[cfg(all(feature = "posix", not(feature = "freertos")))]
243mod posix;
244
245pub mod log;
246
247/// Trait definitions for OSAL abstractions.
248///
249/// This private module defines all the trait interfaces that concrete
250/// implementations must satisfy. Traits are re-exported through the `os` module.
251mod traits;
252
253pub mod utils;
254
255/// Select FreeRTOS as the active OSAL backend.
256#[cfg(feature = "freertos")]
257use crate::freertos as osal;
258
259/// Select POSIX as the active OSAL backend.
260#[cfg(all(feature = "posix", not(feature = "freertos")))]
261use crate::posix as osal;
262
263/// Main OSAL module re-exporting all OS abstractions and traits.
264///
265/// This module provides a unified interface to all OSAL functionality through `osal_rs::os::*`.
266/// It re-exports:
267/// - Thread management types (`Thread`, `ThreadNotification`)
268/// - Synchronization primitives (`Mutex`, `Semaphore`, `EventGroup`)
269/// - Communication types (`Queue`, `QueueStreamed`)
270/// - Timer types (`Timer`)
271/// - System functions (`System`)
272/// - All trait definitions from the `traits` module
273/// - Type definitions and configuration from the active backend
274///
275/// The actual implementation (FreeRTOS or POSIX) is selected at compile time via features.
276///
277/// # Examples
278///
279/// ```ignore
280/// use osal_rs::os::*;
281///
282/// fn main() {
283///     // Create and start a thread
284///     let thread = Thread::new("worker", 4096, 5, || {
285///         println!("Worker thread running");
286///     }).unwrap();
287///     
288///     thread.start().unwrap();
289///     System::start();
290/// }
291/// ```
292pub mod os {
293
294    #[cfg(feature = "freertos")]
295    use crate::osal::allocator::Allocator;
296
297    /// Global allocator using the underlying RTOS heap.
298    ///
299    /// This static variable configures Rust's global allocator to use the
300    /// RTOS heap (e.g., FreeRTOS heap) instead of the system heap.
301    ///
302    /// # Behavior
303    ///
304    /// - All allocations via `alloc::vec::Vec`, `alloc::boxed::Box`, `alloc::string::String`, etc.
305    ///   will use the RTOS heap
306    /// - Memory is managed by the underlying RTOS (e.g., `pvPortMalloc`/`vPortFree` in FreeRTOS)
307    /// - Thread-safe: can be used from multiple tasks safely
308    ///
309    /// # Feature Flag
310    ///
311    /// Active when using the `freertos` backend.
312    ///
313    /// # FreeRTOS Configuration
314    ///
315    /// Ensure your `FreeRTOSConfig.h` has:
316    /// - `configSUPPORT_DYNAMIC_ALLOCATION` set to 1
317    /// - `configTOTAL_HEAP_SIZE` configured appropriately for your application
318    ///
319    /// # Example
320    ///
321    /// ```ignore
322    /// use alloc::vec::Vec;
323    ///
324    /// // This allocation uses the FreeRTOS heap via ALLOCATOR
325    /// let mut v = Vec::new();
326    /// v.push(42);
327    /// ```
328    #[cfg(feature = "freertos")]
329    #[global_allocator]
330    pub static ALLOCATOR: Allocator = Allocator;
331
332    /// Event group synchronization primitives.
333    #[allow(unused_imports)]
334    pub use crate::osal::event_group::*;
335    
336    /// Mutex types and guards for mutual exclusion.
337    #[allow(unused_imports)]
338    pub use crate::osal::mutex::*;
339    
340    /// Queue types for inter-task communication.
341    #[allow(unused_imports)]
342    pub use crate::osal::queue::*;
343    
344    /// Semaphore types for signaling and resource management.
345    #[allow(unused_imports)]
346    pub use crate::osal::semaphore::*;
347    
348    /// System-level functions (scheduler, timing, critical sections).
349    pub use crate::osal::system::*;
350    
351    /// Thread/task management and notification types.
352    pub use crate::osal::thread::*;
353    
354    /// Software timer types for periodic and one-shot callbacks.
355    #[allow(unused_imports)]
356    pub use crate::osal::timer::*;
357    
358    /// All OSAL trait definitions for advanced usage.
359    pub use crate::traits::*;
360    
361    /// RTOS configuration constants and types.
362    pub use crate::osal::config as config;
363    
364    /// Type aliases and common types used throughout OSAL.
365    pub use crate::osal::types as types;
366    
367}
368
369/// Default panic handler for `no_std` environments.
370///
371/// This panic handler is active for the `freertos` backend.
372/// It prints panic information and enters an infinite loop to halt execution.
373///
374/// # Behavior
375///
376/// 1. Attempts to print panic information using the `println!` macro
377/// 2. Enters an infinite empty loop, halting the program
378///
379/// # Feature Flag
380///
381/// - Enabled for `freertos`
382/// - Automatically disabled when using `posix`
383///
384/// # Safety
385///
386/// This handler is intentionally simple and does not attempt cleanup or recovery.
387/// In production embedded systems, consider:
388/// - Logging panic info to persistent storage
389/// - Performing safe shutdown procedures
390/// - Resetting the system via watchdog
391///
392#[cfg(feature = "freertos")]
393#[panic_handler]
394fn panic(info: &core::panic::PanicInfo) -> ! {
395    println!("Panic occurred: {}", info);
396    #[allow(clippy::empty_loop)]
397    loop {}
398}
399