#[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 LISTS: usize = $crate::lists_for(
<$cfg as ::rusty_rtos_core::config::Config>::MAX_PRIORITIES,
QUEUES,
GROUPS,
);
pub const ITEMS: usize = $crate::list_slots_for(TASKS, TIMERS, LISTS);
pub const TIMER_CMDS: usize =
<$cfg as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH;
$(
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,
TIMER_CMDS,
>;
#[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, dead_code)]
pub(crate) 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, Scheduling, 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;
}
pub struct TicklessConfig;
impl Config for TicklessConfig {
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;
const USE_TICKLESS_IDLE: bool = true;
}
#[derive(Debug, Default)]
pub struct SleepyPort {
nesting: core::cell::Cell<u32>,
pub slept: core::cell::Cell<u64>,
pub sleeps: core::cell::Cell<u64>,
pub exits: core::cell::Cell<u64>,
}
impl Port for SleepyPort {
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));
if self.nesting.get() == 0 {
self.exits.set(self.exits.get().saturating_add(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) {}
fn suppress_ticks_and_sleep(&self, expected_idle_ticks: u64) -> u64 {
self.sleeps.set(self.sleeps.get().saturating_add(1));
self.slept
.set(self.slept.get().saturating_add(expected_idle_ticks));
expected_idle_ticks
}
}
#[derive(Debug, Default)]
pub struct OversleepingPort {
nesting: core::cell::Cell<u32>,
}
impl Port for OversleepingPort {
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) {}
fn suppress_ticks_and_sleep(&self, expected_idle_ticks: u64) -> u64 {
expected_idle_ticks.saturating_mul(4).saturating_add(9)
}
}
#[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 {
const WANTS_NAMES: bool = false;
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>;
crate::system! {
mod sleepy use TicklessConfig;
tasks { worker: 1 }
queues { mark: u8; 1 }
}
crate::system! {
mod awake use TestConfig;
tasks { worker: 1 }
queues { mark: u8; 1 }
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Recorder {
pub lines: std::vec::Vec<(u64, &'static str)>,
}
impl Trace for Recorder {
fn event(&mut self, tick: u64, event: Event<'_>) {
self.lines.push((tick, event.name()));
}
}
const DELAY: u64 = 10;
#[test]
fn both_tickless_declarations_build_what_they_declare() {
let mut asleep = sleepy_kernel();
let slept = sleepy::System::build(&mut asleep).expect("the tickless declaration builds");
let mut ticking =
awake::Kernel::<TestPort, NoTrace, NoTickHook>::new(TestPort::default(), NoTrace)
.expect("the declared geometry adds up");
let ticked = awake::System::build(&mut ticking).expect("the ticking declaration builds");
assert_eq!(
slept.worker, ticked.worker,
"identical declarations gave different task handles"
);
let _ = (&slept.mark, &ticked.mark);
}
fn sleepy_kernel() -> sleepy::Kernel<SleepyPort, Scheduling<Recorder>, NoTickHook> {
sleepy::Kernel::new(SleepyPort::default(), Scheduling::new(Recorder::default()))
.expect("the declared geometry adds up")
}
#[test]
fn a_sleeping_port_is_asked_for_the_whole_idle_window() {
let mut k = sleepy_kernel();
k.create_task("worker", 1).expect("worker");
let started = k.start_scheduler().expect("start");
k.suspend(Some(started.timer))
.expect("park the timer daemon");
k.delay(DELAY).expect("the worker delays");
let before = k.tick_count();
k.idle_suppress_ticks();
assert_eq!(k.port().sleeps.get(), 1, "the port was asked once");
assert_eq!(
k.port().slept.get(),
DELAY,
"it was offered the whole window"
);
assert_eq!(
k.tick_count(),
before.saturating_add(DELAY),
"the clock did not land on the worker's wake"
);
}
#[test]
fn tickless_off_never_asks_the_port_to_sleep() {
let mut k =
awake::Kernel::<SleepyPort, NoTrace, NoTickHook>::new(SleepyPort::default(), NoTrace)
.expect("the declared geometry adds up");
k.create_task("worker", 1).expect("worker");
let started = k.start_scheduler().expect("start");
k.suspend(Some(started.timer))
.expect("park the timer daemon");
k.delay(DELAY).expect("the worker delays");
let before = k.tick_count();
k.idle_suppress_ticks();
assert_eq!(k.port().sleeps.get(), 0, "the port was asked");
assert_eq!(k.tick_count(), before, "the clock moved");
}
#[test]
fn the_kernel_clamps_a_port_that_oversleeps() {
let mut k = sleepy::Kernel::<OversleepingPort, NoTrace, NoTickHook>::new(
OversleepingPort::default(),
NoTrace,
)
.expect("the declared geometry adds up");
k.create_task("worker", 1).expect("worker");
let started = k.start_scheduler().expect("start");
k.suspend(Some(started.timer))
.expect("park the timer daemon");
k.delay(DELAY).expect("the worker delays");
let before = k.tick_count();
k.idle_suppress_ticks();
assert_eq!(
k.tick_count(),
before.saturating_add(DELAY),
"a port claiming four times its window moved the clock past the wake"
);
}
#[test]
fn the_schedule_is_the_same_with_and_without_tickless() {
let target = DELAY.saturating_add(2);
let mut asleep = sleepy_kernel();
asleep.create_task("worker", 1).expect("worker");
let started = asleep.start_scheduler().expect("start");
asleep
.suspend(Some(started.timer))
.expect("park the timer daemon");
asleep.delay(DELAY).expect("the worker delays");
asleep.idle_suppress_ticks();
while asleep.tick_count() < target {
if asleep.increment_tick() {
asleep.switch_context();
}
}
let mut ticking = awake::Kernel::<TestPort, Scheduling<Recorder>, NoTickHook>::new(
TestPort::default(),
Scheduling::new(Recorder::default()),
)
.expect("the declared geometry adds up");
ticking.create_task("worker", 1).expect("worker");
let started = ticking.start_scheduler().expect("start");
ticking
.suspend(Some(started.timer))
.expect("park the timer daemon");
ticking.delay(DELAY).expect("the worker delays");
ticking.idle_suppress_ticks();
while ticking.tick_count() < target {
if ticking.increment_tick() {
ticking.switch_context();
}
}
assert!(
asleep.port().sleeps.get() > 0,
"the sleeping arm never slept, so this proves nothing"
);
let slept_schedule = asleep.into_trace().into_inner();
let ticked_schedule = ticking.into_trace().into_inner();
assert_eq!(
slept_schedule, ticked_schedule,
"sleeping through the idle window moved the schedule"
);
}
crate::system! {
mod deep use TestConfig;
tasks {
d0: 1, d1: 1, d2: 1, d3: 1, d4: 1,
d5: 1, d6: 1, d7: 1, d8: 1, d9: 1
}
queues { unused: u8; 1 }
}
#[test]
#[allow(clippy::indexing_slicing)]
fn ten_blocked_tasks_wake_in_wake_time_order() {
let mut k =
deep::Kernel::<TestPort, NoTrace, NoTickHook>::new(TestPort::default(), NoTrace)
.expect("the declared geometry adds up");
let names = ["d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9"];
let mut all = [::rusty_rtos_core::handle::TaskHandle::from_raw(0); 10];
for (slot, name) in all.iter_mut().zip(names) {
*slot = k.create_task(name, 1).expect("task");
}
let started = k.start_scheduler().expect("start");
k.suspend(Some(started.timer)).expect("park the daemon");
let delays = [9u64, 3, 14, 7, 1, 11, 5, 8, 2, 13];
let mut blocked = [(0u64, 0usize); 10];
let mut n = 0usize;
for _ in 0..200u32 {
if n == all.len() {
break;
}
let running = k.current();
if let Some(which) = all.iter().position(|t| *t == running) {
if !blocked[..n].iter().any(|(_, w)| *w == which) {
k.delay(delays[which]).expect("blocks");
blocked[n] = (delays[which], which);
n = n.saturating_add(1);
}
}
k.switch_context();
}
assert_eq!(n, all.len(), "every task should have blocked");
for (i, task) in all.iter().enumerate() {
assert_eq!(
k.task_state_get(*task).expect("state"),
crate::kernel::TaskState::Blocked,
"task {i} should be blocked; all ten are, at once, which is more than twice as deep as any conformance scenario reaches"
);
}
let mut woke = [0usize; 10];
let mut w = 0usize;
let mut asleep = [true; 10];
for _ in 0..40u32 {
k.tick_from_isr();
for (i, task) in all.iter().enumerate() {
if asleep[i]
&& k.task_state_get(*task).expect("state") != crate::kernel::TaskState::Blocked
{
asleep[i] = false;
woke[w] = i;
w = w.saturating_add(1);
}
}
}
assert_eq!(w, all.len(), "every task should have woken");
let mut want = blocked;
want.sort_by_key(|(ticks, _)| *ticks);
let want = want.map(|(_, which)| which);
assert_eq!(
woke, want,
"the delayed list did not wake in wake-time order"
);
}
#[test]
fn creating_a_higher_priority_task_asks_for_a_switch_and_a_lower_one_does_not() {
let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
.expect("the declared geometry adds up");
let mid = k.create_task("mid", 2).expect("task mid");
k.start_scheduler().expect("start");
assert_eq!(k.current(), mid, "the only app task runs");
let before = k.port().yields.get();
let _low = k.create_task("low", 1).expect("task low");
assert_eq!(
k.port().yields.get(),
before,
"a task created BELOW the running priority cannot preempt it, so the kernel must not ask for a switch"
);
let before = k.port().yields.get();
let _high = k.create_task("high", 3).expect("task high");
assert!(
k.port().yields.get() > before,
"a task created ABOVE the running priority preempts it, and the kernel must ask for the switch"
);
}
type BufferKernel = crate::Kernel<
TestConfig,
TestPort,
NoTrace,
NoTickHook,
4,
{ crate::list_slots_for(4, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
{ crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1,
1,
2,
64,
0,
0,
{ <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
>;
#[test]
fn the_trigger_level_contract() {
let mut k =
BufferKernel::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
let small = k.stream_buffer_create(1, 1).expect("a one-byte buffer");
assert_eq!(
k.stream_buffer_set_trigger_level(small, 0),
Ok(true),
"zero becomes one, and one IS below a length of two"
);
assert_eq!(
k.stream_buffer_set_trigger_level(small, 2),
Ok(false),
"two is not below a length of two"
);
let wide = k.stream_buffer_create(8, 1).expect("an eight-byte buffer");
assert_eq!(k.stream_buffer_set_trigger_level(wide, 0), Ok(true));
assert_eq!(
k.stream_buffer_set_trigger_level(wide, 8),
Ok(true),
"8 < 9"
);
assert_eq!(
k.stream_buffer_set_trigger_level(wide, 9),
Ok(false),
"nine is not below a length of nine"
);
}
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::list_slots_for(5, 1, crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1)) },
{ crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1) },
1,
1,
1,
8,
1,
1,
{ <SliceConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
>;
type CountingKernel = crate::Kernel<
SliceConfig,
CountingPort,
NoTrace,
NoTickHook,
5,
{ crate::list_slots_for(5, 1, crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1)) },
{ crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1) },
2,
8,
1,
8,
1,
1,
{ <SliceConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
>;
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,
32,
"8 items + 14 markers, rounded to a power of two"
);
assert_eq!(
demo::ITEMS,
crate::list_slots_for(demo::TASKS, demo::TIMERS, demo::LISTS),
"and it is derived, not written by hand"
);
assert_eq!(
demo::ITEMS - demo::LISTS,
18,
"item capacity: 8 needed, 18 available"
);
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::list_slots_for(24, 32, crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4)) },
{ crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4) },
12,
128,
8,
2048,
32,
4,
{ <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
>;
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);
}
pub struct TicklessCooperativeConfig;
impl Config for TicklessCooperativeConfig {
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;
const USE_TICKLESS_IDLE: bool = true;
const USE_PREEMPTION: bool = false;
}
type Tk<Cfg> = crate::Kernel<
Cfg,
SleepyPort,
NoTrace,
NoTickHook,
5,
{ crate::list_slots_for(5, 0, crate::lists_for(4, 1, 0)) },
{ crate::lists_for(4, 1, 0) },
1,
1,
0,
0,
0,
0,
1,
>;
fn tickless<Cfg: Config>(tasks: &[(&str, u8)]) -> Tk<Cfg> {
let mut k = Tk::<Cfg>::new(SleepyPort::default(), NoTrace).expect("geometry");
for &(name, priority) in tasks {
k.create_task(name, priority).expect("a task");
}
let h = k.start_scheduler().expect("start");
k.suspend(Some(h.timer)).expect("park the daemon");
k
}
#[test]
fn an_idle_window_of_exactly_the_threshold_sleeps() {
let mut k = tickless::<TicklessConfig>(&[("worker", 1)]);
k.delay(TicklessConfig::EXPECTED_IDLE_TIME_BEFORE_SLEEP)
.expect("delay");
k.idle_suppress_ticks();
assert_eq!(k.port().sleeps.get(), 1);
}
#[test]
fn an_idle_window_below_the_threshold_neither_sleeps_nor_takes_a_section() {
let mut k = tickless::<TicklessConfig>(&[("worker", 1)]);
k.delay(TicklessConfig::EXPECTED_IDLE_TIME_BEFORE_SLEEP - 1)
.expect("delay");
let exits = k.port().exits.get();
k.idle_suppress_ticks();
assert_eq!(k.port().sleeps.get(), 0);
assert_eq!(
k.port().exits.get(),
exits,
"the refusal took a critical section"
);
}
#[test]
fn another_idle_priority_task_ready_means_no_sleep() {
let mut k = tickless::<TicklessConfig>(&[("worker", 1), ("slacker", 0)]);
k.delay(20).expect("the worker delays");
k.idle_suppress_ticks();
assert_eq!(k.port().sleeps.get(), 0);
}
#[test]
fn a_ready_task_above_the_idle_priority_means_no_sleep() {
let mut k = tickless::<TicklessCooperativeConfig>(&[("early", 1), ("late", 1)]);
k.delay(50).expect("the first task delays long");
k.delay(3).expect("the second delays short");
for _ in 0..3_u32 {
k.tick_from_isr();
}
assert_eq!(
k.name_of(k.current()).expect("a name").as_str(),
"IDLE",
"cooperative: the woken task does not preempt"
);
k.idle_suppress_ticks();
assert_eq!(k.port().sleeps.get(), 0);
}
}