#[macro_export]
macro_rules! system {
(
$(#[$meta:meta])*
$vis:vis mod $name:ident use $cfg:ty;
tasks { $($task:ident : $prio:expr),* $(,)? }
queues { $($queue:ident : $qty:ty ; $qlen:expr),* $(,)? }
) => {
$(#[$meta])*
$vis mod $name {
#![allow(unused_imports, clippy::allow_attributes)]
use super::*;
pub const APP_TASKS: usize = 0usize $(+ { let _ = $prio; 1usize })*;
pub const TASKS: usize = APP_TASKS + $crate::OVERHEAD_TASKS;
pub const QUEUES: usize = 0usize $(+ { let _ = $qlen; 1usize })*;
pub const SLOTS: usize = 0usize $(+ $qlen)*;
pub const TIMERS: usize = 0;
pub const GROUPS: usize = 0;
pub const BUFFERS: usize = 0;
pub const BYTES: usize = 0;
pub const ITEMS: usize = $crate::items_for(TASKS, TIMERS);
pub const LISTS: usize = $crate::lists_for(
<$cfg as ::rusty_rtos_core::config::Config>::MAX_PRIORITIES,
QUEUES,
GROUPS,
);
$(
const _: () = assert!(
($prio as u8) < <$cfg as ::rusty_rtos_core::config::Config>::MAX_PRIORITIES,
concat!(
"task `", stringify!($task),
"` declares a priority its Config has no ready list for"
),
);
)*
pub type Kernel<P, T, H> = $crate::Kernel<
$cfg, P, T, H,
TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS,
>;
#[derive(Debug)]
pub struct System {
$(
pub $task: ::rusty_rtos_core::handle::TaskHandle,
)*
$(
pub $queue: $crate::typed::Queue<$qty, { $qlen }>,
)*
}
impl System {
pub fn build<P, T, H>(kernel: &mut Kernel<P, T, H>) -> ::rusty_rtos_core::error::Result<Self>
where
P: ::rusty_rtos_core::port::Port,
T: ::rusty_rtos_core::trace::Trace,
H: $crate::TickHook<Kernel<P, T, H>>,
{
$(
let $queue = $crate::typed::Queue::<$qty, { $qlen }>::create(kernel)?;
)*
$(
let $task = kernel.create_task(stringify!($task), $prio)?;
)*
Ok(Self { $($task,)* $($queue,)* })
}
}
}
};
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use rusty_rtos_core::config::Config;
use rusty_rtos_core::hooks::NoTickHook;
use rusty_rtos_core::isr::Woken;
use rusty_rtos_core::port::Port;
use rusty_rtos_core::tick::Bits32;
use rusty_rtos_core::trace::{Event, Trace};
use crate::typed::Sent;
#[derive(Debug, Clone, Copy, Default)]
pub struct TestConfig;
impl Config for TestConfig {
type Tick = Bits32;
const TICK_RATE_HZ: u32 = 100;
const MAX_PRIORITIES: u8 = 4;
const MINIMAL_STACK_SIZE: usize = 1;
const MAX_TASK_NAME_LEN: usize = 8;
const TIMER_TASK_PRIORITY: u8 = 3;
const TIMER_TASK_STACK_DEPTH: usize = 1;
const TIMER_QUEUE_LENGTH: usize = 1;
const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
const USE_TIME_SLICING: bool = false;
}
#[derive(Debug, Default)]
pub struct TestPort {
nesting: core::cell::Cell<u32>,
}
impl Port for TestPort {
fn yield_now(&self) {}
fn yield_from_isr(&self, _woken: Woken) {}
fn enter_critical(&self) {
self.nesting.set(self.nesting.get().saturating_add(1));
}
fn exit_critical(&self) {
self.nesting.set(self.nesting.get().saturating_sub(1));
}
fn set_interrupt_mask_from_isr(&self) -> u32 {
0
}
fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
fn in_isr(&self) -> bool {
false
}
fn set_in_tick_entry(&self, _yes: bool) {}
}
#[derive(Debug, Default)]
pub struct CountingPort {
nesting: core::cell::Cell<u32>,
yields: core::cell::Cell<u32>,
}
impl Port for CountingPort {
fn count_yield(&self) {
self.yields.set(self.yields.get().saturating_add(1));
}
fn yield_now(&self) {}
fn yield_from_isr(&self, _woken: Woken) {}
fn enter_critical(&self) {
self.nesting.set(self.nesting.get().saturating_add(1));
}
fn exit_critical(&self) {
self.nesting.set(self.nesting.get().saturating_sub(1));
}
fn set_interrupt_mask_from_isr(&self) -> u32 {
0
}
fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
fn in_isr(&self) -> bool {
false
}
fn set_in_tick_entry(&self, _yes: bool) {}
}
#[derive(Debug, Default)]
pub struct NoTrace;
impl Trace for NoTrace {
fn event(&mut self, _tick: u64, _event: Event<'_>) {}
}
crate::system! {
mod demo use TestConfig;
tasks { consumer: 2, producer: 1 }
queues { data: u16; 10, marks: u8; 3 }
}
type K = demo::Kernel<TestPort, NoTrace, NoTickHook>;
fn kernel() -> K {
K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up")
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SliceConfig;
impl Config for SliceConfig {
type Tick = Bits32;
const TICK_RATE_HZ: u32 = 100;
const MAX_PRIORITIES: u8 = 4;
const MINIMAL_STACK_SIZE: usize = 1;
const MAX_TASK_NAME_LEN: usize = 8;
const TIMER_TASK_PRIORITY: u8 = 0;
const TIMER_TASK_STACK_DEPTH: usize = 1;
const TIMER_QUEUE_LENGTH: usize = 1;
const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
const USE_TIME_SLICING: bool = true;
const USE_PREEMPTION: bool = true;
}
type SliceKernel = crate::Kernel<
SliceConfig,
TestPort,
NoTrace,
NoTickHook,
5,
{ crate::items_for(5, 1) },
{ crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1) },
1,
1,
1,
8,
1,
1,
>;
type CountingKernel = crate::Kernel<
SliceConfig,
CountingPort,
NoTrace,
NoTickHook,
5,
{ crate::items_for(5, 1) },
{ crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1) },
2,
8,
1,
8,
1,
1,
>;
fn turns_over(ticks: u32) -> (u32, u32) {
let mut k =
SliceKernel::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
let a = k.create_task("a", 2).expect("task a");
let b = k.create_task("b", 2).expect("task b");
k.start_scheduler().expect("start");
let (mut for_a, mut for_b) = (0u32, 0u32);
for _ in 0..ticks {
if k.increment_tick() {
k.switch_context();
}
let now = k.current();
if now == a {
for_a = for_a.saturating_add(1);
} else if now == b {
for_b = for_b.saturating_add(1);
}
}
(for_a, for_b)
}
#[test]
fn two_ready_tasks_of_equal_priority_take_turns() {
let (a, b) = turns_over(200);
assert!(a > 0, "task a never ran: {a} vs {b}");
assert!(b > 0, "task b never ran: {a} vs {b}");
}
#[test]
fn a_send_that_wakes_a_higher_priority_receiver_asks_for_a_switch() {
let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
.expect("the declared geometry adds up");
let hi = k.create_task("hi", 2).expect("task hi");
let lo = k.create_task("lo", 1).expect("task lo");
let q = k.queue_create(4).expect("a queue");
k.start_scheduler().expect("start");
assert_eq!(k.current(), hi, "the higher priority task runs first");
assert!(
matches!(k.queue_receive(q, 100), Ok(crate::queue::Wait::Blocked)),
"an empty queue with a block time must park the receiver"
);
k.switch_context();
assert_eq!(k.current(), lo, "with hi parked, lo runs");
let before = k.port().yields.get();
assert!(matches!(
k.queue_send(q, 7, 0),
Ok(crate::queue::Wait::Ready(()))
));
let asked = k.port().yields.get().saturating_sub(before);
assert_eq!(
asked, 1,
"a send that readies a higher-priority receiver must ask for a switch"
);
}
#[test]
fn a_send_asks_for_nothing_when_the_higher_priority_task_never_waited() {
let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
.expect("the declared geometry adds up");
let _hi = k.create_task("hi", 2).expect("task hi");
let _lo = k.create_task("lo", 1).expect("task lo");
let q = k.queue_create(4).expect("a queue");
k.start_scheduler().expect("start");
assert!(
matches!(
k.queue_receive(q, 0),
Err(rusty_rtos_core::error::Error::Empty)
),
"a zero-wait receive on an empty queue reports Empty, not Blocked"
);
k.switch_context();
let before = k.port().yields.get();
assert!(matches!(
k.queue_send(q, 7, 0),
Ok(crate::queue::Wait::Ready(()))
));
assert_eq!(
k.port().yields.get(),
before,
"there was no waiter to wake, so nothing should have been asked for"
);
}
#[test]
fn neither_equal_priority_task_starves_the_other() {
let (a, b) = turns_over(200);
let (lo, hi) = (a.min(b), a.max(b));
assert!(
lo.saturating_mul(4) >= hi,
"one starved the other: {a} against {b}"
);
}
#[test]
fn the_geometry_is_derived_from_the_declaration() {
assert_eq!(demo::APP_TASKS, 2, "the two declared tasks");
assert_eq!(demo::TASKS, 4, "plus the idle task and the timer daemon");
assert_eq!(demo::QUEUES, 2, "the two declared queues");
assert_eq!(demo::SLOTS, 13, "10 + 3, the declared lengths and no spare");
assert_eq!(demo::ITEMS, 8, "two list items per task, no timers");
assert_eq!(
demo::LISTS,
crate::lists_for(TestConfig::MAX_PRIORITIES, 2, 0),
"a ready list per priority, the fixed six, and two per queue"
);
}
#[test]
fn a_declared_system_builds_and_the_kernel_accepts_its_geometry() {
let mut k = kernel();
let system = demo::System::build(&mut k).expect("nothing here can fail");
assert!(!system.consumer.is_null());
assert!(!system.producer.is_null());
assert_ne!(system.consumer, system.producer);
assert_eq!(k.task_count(), 2, "no task the declaration did not name");
}
#[test]
fn the_declared_queues_move_their_own_type() {
let mut k = kernel();
let mut system = demo::System::build(&mut k).expect("nothing here can fail");
assert!(matches!(system.data.send(&mut k, 4_242u16, 0), Sent::Ok));
assert!(matches!(system.marks.send(&mut k, 7u8, 0), Sent::Ok));
assert_eq!(system.data.len(&mut k), Ok(1));
assert_eq!(system.marks.len(&mut k), Ok(1));
}
#[test]
fn a_declared_kernel_is_sized_for_what_was_declared() {
type Blanket = crate::Kernel<
TestConfig,
TestPort,
NoTrace,
NoTickHook,
24,
{ crate::items_for(24, 32) },
{ crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4) },
12,
128,
8,
2048,
32,
4,
>;
let declared = core::mem::size_of::<K>();
let blanket = core::mem::size_of::<Blanket>();
let ratio = blanket as f64 / declared as f64;
std::eprintln!("declared {declared} bytes, hand-sized {blanket} bytes, {ratio:.1}x");
assert!(
declared < blanket,
"a declared kernel ({declared}) should be smaller than one sized for everything ({blanket})"
);
assert_eq!(
declared,
core::mem::size_of::<demo::Kernel<TestPort, NoTrace, NoTickHook>>()
);
}
#[test]
fn every_declared_slot_is_usable_and_there_is_not_one_spare() {
let mut k = kernel();
let mut system = demo::System::build(&mut k).expect("nothing here can fail");
for i in 0..10u16 {
assert!(
matches!(system.data.send(&mut k, i, 0), Sent::Ok),
"slot {i} of the declared ten"
);
}
for i in 0..3u8 {
assert!(
matches!(system.marks.send(&mut k, i, 0), Sent::Ok),
"slot {i} of the declared three"
);
}
assert!(matches!(system.data.send(&mut k, 99, 0), Sent::Full(99)));
assert!(matches!(system.marks.send(&mut k, 9, 0), Sent::Full(9)));
assert_eq!(demo::SLOTS, 13);
}
}