rusty_rtos_kernel_core/system.rs
1//! The static face: declare the system, and the geometry is the declaration.
2//!
3//! [`crate::typed`] made one *object* safe to hold — a `Queue<T, N>` that
4//! moves `T`s and cannot be minted from an integer. This makes the whole
5//! *system* safe to declare. You write down the tasks and queues an
6//! application has; the macro writes the kernel's geometry from them and
7//! hands back a struct whose fields are those tasks and queues, by name and
8//! by type.
9//!
10//! ```ignore
11//! rusty_rtos_kernel_core::system! {
12//! mod blinky use PosixDemoConfig;
13//! tasks { consumer: 2, producer: 2 }
14//! queues { data: u16; 10 }
15//! }
16//! ```
17//!
18//! # What that buys, and why each part of it is a compile-time thing
19//!
20//! **Exact `.bss` by construction.** The geometry const generics —
21//! `TASKS`, `ITEMS`, `LISTS`, `QUEUES`, `SLOTS` — are *computed from the
22//! declaration* rather than picked by hand and rounded up. `SLOTS` is the
23//! sum of the declared queue lengths, not a guess; `TASKS` is what you
24//! declared plus the two the kernel makes for itself. A kernel sized this
25//! way holds exactly the system and nothing else, and
26//! `blinky::Kernel::<..>::SIZE` is a number you can put in a footprint
27//! table rather than an allowance you hope covers it.
28//!
29//! **No create-failure path an application can reach.** Every way
30//! `queue_create` and `create_task` can answer `Err` is eliminated *before
31//! the program runs*:
32//!
33//! | how a create fails | why it cannot here |
34//! |---|---|
35//! | the task arena is full | `TASKS` **is** the declared count plus the kernel's two |
36//! | the queue arena is full | `QUEUES` **is** the declared count |
37//! | the item slots are exhausted | `SLOTS` **is** the sum of the declared lengths |
38//! | a list is missing | `LISTS` is `lists_for` over the same numbers |
39//! | the priority is out of range | a `const` assertion per task, so it is a **compile error** |
40//!
41//! [`System::build`] still answers `Result`, because the kernel calls it
42//! makes do and this crate may not panic — but the `Err` arm is now
43//! unreachable by construction rather than merely unlikely, and the table
44//! above says which construction makes each one unreachable. That is the
45//! difference between a runtime check and a proof, and it is the whole
46//! point of the exercise.
47//!
48//! **The handles never enter the application.** `build` is the only place
49//! that touches a create call, and it happens once, at startup. Afterwards
50//! the application holds `system.data` — a `Queue<u16, 10>` — and there is
51//! no constructor anywhere that invents one from an integer. That is what
52//! makes the four Kani harnesses that pass a *symbolic handle* into a
53//! kernel call unwritable against this face: the state they explore has no
54//! way to come into being (`docs/LEDGER.md`, "The topology work,
55//! measured").
56
57/// Declare a system: its tasks, its queues, and the geometry they imply.
58///
59/// See the [module docs](self) for what the expansion contains and why.
60///
61/// The config is named in the header because the number of lists depends
62/// on `Config::MAX_PRIORITIES`, and a `const` may read an associated const
63/// of a *concrete* type — which is why this is a declaration and not a
64/// generic parameter.
65///
66/// # What a declaration refuses, that a hand-sized kernel cannot
67///
68/// Each of these is paired with the working line it is one character
69/// from, so neither can pass for the wrong reason.
70///
71/// **A priority the config has no ready list for.** In C this is a
72/// `configASSERT` on the bench, if `configASSERT` is compiled in, on the
73/// day that task first runs. Here it is a build failure:
74///
75/// ```compile_fail
76/// # use rusty_rtos_core::config::Config;
77/// # use rusty_rtos_core::tick::Bits32;
78/// # #[derive(Debug, Clone, Copy, Default)]
79/// # pub struct Cfg;
80/// # impl Config for Cfg {
81/// # type Tick = Bits32;
82/// # const TICK_RATE_HZ: u32 = 100;
83/// # const MAX_PRIORITIES: u8 = 4;
84/// # const MINIMAL_STACK_SIZE: usize = 1;
85/// # const MAX_TASK_NAME_LEN: usize = 8;
86/// # const TIMER_TASK_PRIORITY: u8 = 3;
87/// # const TIMER_TASK_STACK_DEPTH: usize = 1;
88/// # const TIMER_QUEUE_LENGTH: usize = 1;
89/// # const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
90/// # }
91/// rusty_rtos_kernel_core::system! {
92/// mod bad use Cfg;
93/// tasks { spinner: 4 }
94/// queues { }
95/// }
96/// # fn main() {}
97/// ```
98///
99/// The control arm — the same declaration, one priority lower, which is
100/// the highest `MAX_PRIORITIES = 4` actually has:
101///
102/// ```
103/// # use rusty_rtos_core::config::Config;
104/// # use rusty_rtos_core::tick::Bits32;
105/// # #[derive(Debug, Clone, Copy, Default)]
106/// # pub struct Cfg;
107/// # impl Config for Cfg {
108/// # type Tick = Bits32;
109/// # const TICK_RATE_HZ: u32 = 100;
110/// # const MAX_PRIORITIES: u8 = 4;
111/// # const MINIMAL_STACK_SIZE: usize = 1;
112/// # const MAX_TASK_NAME_LEN: usize = 8;
113/// # const TIMER_TASK_PRIORITY: u8 = 3;
114/// # const TIMER_TASK_STACK_DEPTH: usize = 1;
115/// # const TIMER_QUEUE_LENGTH: usize = 1;
116/// # const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
117/// # }
118/// rusty_rtos_kernel_core::system! {
119/// mod good use Cfg;
120/// tasks { spinner: 3 }
121/// queues { }
122/// }
123/// # fn main() { assert_eq!(good::TASKS, 3); }
124/// ```
125///
126/// **A queue told to carry what it was not declared for.** The
127/// declaration named `data` as a queue of `u16`, so the field is a
128/// `Queue<u16, 4>` and a `u32` is not a `u16`:
129///
130/// ```compile_fail
131/// # use rusty_rtos_core::config::Config;
132/// # use rusty_rtos_core::tick::Bits32;
133/// # #[derive(Debug, Clone, Copy, Default)]
134/// # pub struct Cfg;
135/// # impl Config for Cfg {
136/// # type Tick = Bits32;
137/// # const TICK_RATE_HZ: u32 = 100;
138/// # const MAX_PRIORITIES: u8 = 4;
139/// # const MINIMAL_STACK_SIZE: usize = 1;
140/// # const MAX_TASK_NAME_LEN: usize = 8;
141/// # const TIMER_TASK_PRIORITY: u8 = 3;
142/// # const TIMER_TASK_STACK_DEPTH: usize = 1;
143/// # const TIMER_QUEUE_LENGTH: usize = 1;
144/// # const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
145/// # }
146/// rusty_rtos_kernel_core::system! {
147/// mod app use Cfg;
148/// tasks { worker: 1 }
149/// queues { data: u16; 4 }
150/// }
151/// # fn main() {}
152/// fn wrong<P, T, H>(k: &mut app::Kernel<P, T, H>, s: &mut app::System)
153/// where
154/// P: rusty_rtos_core::port::Port,
155/// T: rusty_rtos_core::trace::Trace,
156/// H: rusty_rtos_kernel_core::TickHook<app::Kernel<P, T, H>>,
157/// {
158/// let _ = s.data.send(k, 70_000u32, 0);
159/// }
160/// ```
161///
162/// The control arm, one type name different:
163///
164/// ```
165/// # use rusty_rtos_core::config::Config;
166/// # use rusty_rtos_core::tick::Bits32;
167/// # #[derive(Debug, Clone, Copy, Default)]
168/// # pub struct Cfg;
169/// # impl Config for Cfg {
170/// # type Tick = Bits32;
171/// # const TICK_RATE_HZ: u32 = 100;
172/// # const MAX_PRIORITIES: u8 = 4;
173/// # const MINIMAL_STACK_SIZE: usize = 1;
174/// # const MAX_TASK_NAME_LEN: usize = 8;
175/// # const TIMER_TASK_PRIORITY: u8 = 3;
176/// # const TIMER_TASK_STACK_DEPTH: usize = 1;
177/// # const TIMER_QUEUE_LENGTH: usize = 1;
178/// # const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
179/// # }
180/// rusty_rtos_kernel_core::system! {
181/// mod app use Cfg;
182/// tasks { worker: 1 }
183/// queues { data: u16; 4 }
184/// }
185/// # fn main() {}
186/// fn right<P, T, H>(k: &mut app::Kernel<P, T, H>, s: &mut app::System)
187/// where
188/// P: rusty_rtos_core::port::Port,
189/// T: rusty_rtos_core::trace::Trace,
190/// H: rusty_rtos_kernel_core::TickHook<app::Kernel<P, T, H>>,
191/// {
192/// let _ = s.data.send(k, 7_000u16, 0);
193/// }
194/// ```
195///
196/// **And there is no third way in.** A `System` has no public
197/// constructor but [`System::build`], and a `Queue<T, N>` has none but
198/// `create`, so no application can hold a handle it invented — which is
199/// what makes the symbolic-handle proofs unwritable against this face
200/// rather than merely slow.
201#[macro_export]
202macro_rules! system {
203 (
204 $(#[$meta:meta])*
205 $vis:vis mod $name:ident use $cfg:ty;
206 tasks { $($task:ident : $prio:expr),* $(,)? }
207 queues { $($queue:ident : $qty:ty ; $qlen:expr),* $(,)? }
208 ) => {
209 $(#[$meta])*
210 $vis mod $name {
211 #![allow(unused_imports, clippy::allow_attributes)]
212 use super::*;
213
214 /// The tasks this system declares. The kernel adds its own two.
215 pub const APP_TASKS: usize = 0usize $(+ { let _ = $prio; 1usize })*;
216 /// Room for every declared task plus the idle task and the
217 /// timer daemon, and for nothing else.
218 pub const TASKS: usize = APP_TASKS + $crate::OVERHEAD_TASKS;
219 /// The declared queues, and no spare.
220 pub const QUEUES: usize = 0usize $(+ { let _ = $qlen; 1usize })*;
221 /// The sum of the declared queue lengths: every slot is spoken
222 /// for and none is spare.
223 pub const SLOTS: usize = 0usize $(+ $qlen)*;
224 /// Software timers. Not declared yet; a system that wants them
225 /// sizes its own kernel.
226 pub const TIMERS: usize = 0;
227 /// Event groups, as `TIMERS`.
228 pub const GROUPS: usize = 0;
229 /// Stream buffers, as `TIMERS`.
230 pub const BUFFERS: usize = 0;
231 /// Stream-buffer bytes, as `TIMERS`.
232 pub const BYTES: usize = 0;
233 /// A ready list per priority, the fixed six, two per queue and
234 /// one per event group.
235 ///
236 /// Declared BEFORE `ITEMS`, which now depends on it: the list
237 /// arena holds one end-marker node per list alongside the items.
238 pub const LISTS: usize = $crate::lists_for(
239 <$cfg as ::rusty_rtos_core::config::Config>::MAX_PRIORITIES,
240 QUEUES,
241 GROUPS,
242 );
243 /// Slots for two list items per task, one per timer, and one
244 /// end marker per list — rounded up to a power of two.
245 pub const ITEMS: usize = $crate::list_slots_for(TASKS, TIMERS, LISTS);
246 /// The timer daemon's mailbox, taken from the config rather than
247 /// from a hardcoded ceiling.
248 ///
249 /// It was `MAX_TIMER_COMMANDS`, a fixed 32, which scaled with
250 /// nothing and so cost the same 768 bytes in a two-task blinker as
251 /// in a twenty-four-task corpus — 39 % of the former's whole
252 /// static footprint. A declared system gets what it declared.
253 pub const TIMER_CMDS: usize =
254 <$cfg as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH;
255
256 // A declared priority the config has no ready list for is a
257 // compile error, not a create that answers `Err` at startup on
258 // the bench. This is the one create-failure path that is an
259 // application mistake rather than a geometry mistake, so it is
260 // the one worth refusing here.
261 $(
262 const _: () = assert!(
263 ($prio as u8) < <$cfg as ::rusty_rtos_core::config::Config>::MAX_PRIORITIES,
264 concat!(
265 "task `", stringify!($task),
266 "` declares a priority its Config has no ready list for"
267 ),
268 );
269 )*
270
271 /// This system's kernel: the geometry above, and nothing to
272 /// choose. `P`, `T` and `H` are still the port, the trace sink
273 /// and the tick hook, which are the platform's business.
274 pub type Kernel<P, T, H> = $crate::Kernel<
275 $cfg, P, T, H,
276 TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS,
277 TIMER_CMDS,
278 >;
279
280 /// The declared system: every task and every queue, by name.
281 ///
282 /// Built once, by [`System::build`]. After that an application
283 /// holds this and never a handle it could have invented.
284 #[derive(Debug)]
285 pub struct System {
286 $(
287 /// A declared task.
288 pub $task: ::rusty_rtos_core::handle::TaskHandle,
289 )*
290 $(
291 /// A declared queue, typed and length-checked.
292 pub $queue: $crate::typed::Queue<$qty, { $qlen }>,
293 )*
294 }
295
296 impl System {
297 /// Create everything the declaration names, in the order it
298 /// names it.
299 ///
300 /// # Errors
301 /// None an application can reach: see the module docs for
302 /// why each create-failure path is closed by construction.
303 /// The `Result` is here because this crate may not panic,
304 /// not because there is a case to handle.
305 pub fn build<P, T, H>(kernel: &mut Kernel<P, T, H>) -> ::rusty_rtos_core::error::Result<Self>
306 where
307 P: ::rusty_rtos_core::port::Port,
308 T: ::rusty_rtos_core::trace::Trace,
309 H: $crate::TickHook<Kernel<P, T, H>>,
310 {
311 $(
312 let $queue = $crate::typed::Queue::<$qty, { $qlen }>::create(kernel)?;
313 )*
314 $(
315 let $task = kernel.create_task(stringify!($task), $prio)?;
316 )*
317 Ok(Self { $($task,)* $($queue,)* })
318 }
319 }
320 }
321 };
322}
323
324#[cfg(test)]
325// `dead_code`: a `system!` declaration generates a `System` and its
326// `build`, and `deep`'s exists to SIZE a kernel rather than to furnish one
327// -- its tasks are created directly so the declared queue slot stays free
328// for the timer daemon.
329#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, dead_code)]
330// `pub(crate)` so `timer.rs`, `stream.rs` and `events.rs` can test against
331// the same config, port and sink rather than declaring three more of each
332// -- three copies of a test harness is three places for it to drift (H3).
333pub(crate) mod tests {
334 use rusty_rtos_core::config::Config;
335 use rusty_rtos_core::hooks::NoTickHook;
336 use rusty_rtos_core::isr::Woken;
337 use rusty_rtos_core::port::Port;
338 use rusty_rtos_core::tick::Bits32;
339 use rusty_rtos_core::trace::{Event, Scheduling, Trace};
340
341 use crate::typed::Sent;
342
343 /// Four priorities, so a declaration can get one wrong.
344 #[derive(Debug, Clone, Copy, Default)]
345 pub struct TestConfig;
346
347 impl Config for TestConfig {
348 type Tick = Bits32;
349 const TICK_RATE_HZ: u32 = 100;
350 const MAX_PRIORITIES: u8 = 4;
351 const MINIMAL_STACK_SIZE: usize = 1;
352 const MAX_TASK_NAME_LEN: usize = 8;
353 const TIMER_TASK_PRIORITY: u8 = 3;
354 const TIMER_TASK_STACK_DEPTH: usize = 1;
355 const TIMER_QUEUE_LENGTH: usize = 1;
356 const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
357 const USE_TIME_SLICING: bool = false;
358 }
359
360 /// [`TestConfig`] with `configUSE_TICKLESS_IDLE` on, and nothing else
361 /// changed — so a difference between the two is the tickless path and
362 /// cannot be anything else.
363 pub struct TicklessConfig;
364
365 impl Config for TicklessConfig {
366 type Tick = Bits32;
367 const TICK_RATE_HZ: u32 = 100;
368 const MAX_PRIORITIES: u8 = 4;
369 const MINIMAL_STACK_SIZE: usize = 1;
370 const MAX_TASK_NAME_LEN: usize = 8;
371 const TIMER_TASK_PRIORITY: u8 = 3;
372 const TIMER_TASK_STACK_DEPTH: usize = 1;
373 const TIMER_QUEUE_LENGTH: usize = 1;
374 const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
375 const USE_TIME_SLICING: bool = false;
376 const USE_TICKLESS_IDLE: bool = true;
377 }
378
379 /// A port that takes every whole window it is offered — the most
380 /// aggressive sleep there is, and so the hardest case for the kernel to
381 /// stay correct across.
382 #[derive(Debug, Default)]
383 pub struct SleepyPort {
384 nesting: core::cell::Cell<u32>,
385 /// Ticks this port has been asked to sleep, in total.
386 pub slept: core::cell::Cell<u64>,
387 /// Times it was asked at all.
388 pub sleeps: core::cell::Cell<u64>,
389 /// Outermost critical-section exits: a refusal to sleep must not
390 /// take a section the C does not.
391 pub exits: core::cell::Cell<u64>,
392 }
393
394 impl Port for SleepyPort {
395 fn yield_now(&self) {}
396 fn yield_from_isr(&self, _woken: Woken) {}
397 fn enter_critical(&self) {
398 self.nesting.set(self.nesting.get().saturating_add(1));
399 }
400 fn exit_critical(&self) {
401 self.nesting.set(self.nesting.get().saturating_sub(1));
402 if self.nesting.get() == 0 {
403 self.exits.set(self.exits.get().saturating_add(1));
404 }
405 }
406 fn set_interrupt_mask_from_isr(&self) -> u32 {
407 0
408 }
409 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
410 fn in_isr(&self) -> bool {
411 false
412 }
413 fn set_in_tick_entry(&self, _yes: bool) {}
414
415 fn suppress_ticks_and_sleep(&self, expected_idle_ticks: u64) -> u64 {
416 self.sleeps.set(self.sleeps.get().saturating_add(1));
417 self.slept
418 .set(self.slept.get().saturating_add(expected_idle_ticks));
419 expected_idle_ticks
420 }
421 }
422
423 /// A port that OVERSLEEPS, to prove the kernel clamps rather than
424 /// trusting it.
425 #[derive(Debug, Default)]
426 pub struct OversleepingPort {
427 nesting: core::cell::Cell<u32>,
428 }
429
430 impl Port for OversleepingPort {
431 fn yield_now(&self) {}
432 fn yield_from_isr(&self, _woken: Woken) {}
433 fn enter_critical(&self) {
434 self.nesting.set(self.nesting.get().saturating_add(1));
435 }
436 fn exit_critical(&self) {
437 self.nesting.set(self.nesting.get().saturating_sub(1));
438 }
439 fn set_interrupt_mask_from_isr(&self) -> u32 {
440 0
441 }
442 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
443 fn in_isr(&self) -> bool {
444 false
445 }
446 fn set_in_tick_entry(&self, _yes: bool) {}
447
448 fn suppress_ticks_and_sleep(&self, expected_idle_ticks: u64) -> u64 {
449 expected_idle_ticks.saturating_mul(4).saturating_add(9)
450 }
451 }
452
453 #[derive(Debug, Default)]
454 pub struct TestPort {
455 nesting: core::cell::Cell<u32>,
456 }
457
458 impl Port for TestPort {
459 fn yield_now(&self) {}
460 fn yield_from_isr(&self, _woken: Woken) {}
461 fn enter_critical(&self) {
462 self.nesting.set(self.nesting.get().saturating_add(1));
463 }
464 fn exit_critical(&self) {
465 self.nesting.set(self.nesting.get().saturating_sub(1));
466 }
467 fn set_interrupt_mask_from_isr(&self) -> u32 {
468 0
469 }
470 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
471 fn in_isr(&self) -> bool {
472 false
473 }
474 fn set_in_tick_entry(&self, _yes: bool) {}
475 }
476
477 /// A [`TestPort`] that COUNTS the switches it was asked for.
478 ///
479 /// `TestPort::yield_now` is empty, which is right for tests about what
480 /// the kernel computes and useless for a test about whether it asked
481 /// for a switch at all. Those are different questions and the second
482 /// one has no other instrument.
483 #[derive(Debug, Default)]
484 pub struct CountingPort {
485 nesting: core::cell::Cell<u32>,
486 yields: core::cell::Cell<u32>,
487 }
488
489 impl Port for CountingPort {
490 /// Count the kernel ASKING for a switch, not one style of taking it.
491 ///
492 /// The first version of this counted `yield_now`, and measured the
493 /// wrong thing: `Port::COMMITS_SWITCH` defaults to `false`, so
494 /// `port_yield` calls `switch_context` itself and never reaches
495 /// `yield_now` at all. The test read zero and looked like a kernel
496 /// defect. `count_yield` is on the unconditional path, so it
497 /// answers "did the kernel decide a switch was needed" whichever
498 /// way the port takes it — which is the question.
499 fn count_yield(&self) {
500 self.yields.set(self.yields.get().saturating_add(1));
501 }
502 fn yield_now(&self) {}
503 fn yield_from_isr(&self, _woken: Woken) {}
504 fn enter_critical(&self) {
505 self.nesting.set(self.nesting.get().saturating_add(1));
506 }
507 fn exit_critical(&self) {
508 self.nesting.set(self.nesting.get().saturating_sub(1));
509 }
510 fn set_interrupt_mask_from_isr(&self) -> u32 {
511 0
512 }
513 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
514 fn in_isr(&self) -> bool {
515 false
516 }
517 fn set_in_tick_entry(&self, _yes: bool) {}
518 }
519
520 #[derive(Debug, Default)]
521 pub struct NoTrace;
522
523 impl Trace for NoTrace {
524 // Nothing here reads a task name, so the kernel is told not to build one.
525 // Without this the trait default is `true` and every traced event costs a
526 // name lookup plus a UTF-8 validation for a sink that drops it: measured
527 // at 3.86x on one row (2026-09-21).
528 const WANTS_NAMES: bool = false;
529
530 fn event(&mut self, _tick: u64, _event: Event<'_>) {}
531 }
532
533 // The declaration under test: two tasks and two queues of different
534 // types and different lengths, so nothing about the geometry can come
535 // out right by symmetry.
536 crate::system! {
537 mod demo use TestConfig;
538 tasks { consumer: 2, producer: 1 }
539 queues { data: u16; 10, marks: u8; 3 }
540 }
541
542 type K = demo::Kernel<TestPort, NoTrace, NoTickHook>;
543
544 // ---- tickless idle ---------------------------------------------------
545
546 crate::system! {
547 mod sleepy use TicklessConfig;
548 tasks { worker: 1 }
549 queues { mark: u8; 1 }
550 }
551
552 crate::system! {
553 mod awake use TestConfig;
554 tasks { worker: 1 }
555 queues { mark: u8; 1 }
556 }
557
558 /// A sink that keeps the shape of a trace: every event, with the tick it
559 /// carried. Comparing two of these compares two schedules.
560 #[derive(Debug, Default, PartialEq, Eq)]
561 pub struct Recorder {
562 pub lines: std::vec::Vec<(u64, &'static str)>,
563 }
564
565 impl Trace for Recorder {
566 fn event(&mut self, tick: u64, event: Event<'_>) {
567 self.lines.push((tick, event.name()));
568 }
569 }
570
571 /// `worker` delays, leaving only the idle task ready — which is the
572 /// precondition tickless idle exists for.
573 const DELAY: u64 = 10;
574
575 /// Both declarations build what they declare.
576 ///
577 /// The tests that matter below start a scheduler, and `System::build` and
578 /// a started scheduler cannot both have the one queue slot a declaration
579 /// reserves -- `system!` sizes `QUEUES` with "no spare", and the timer
580 /// daemon needs it. So they create the one task they need by hand, and
581 /// this is where the generated builders are exercised.
582 #[test]
583 fn both_tickless_declarations_build_what_they_declare() {
584 let mut asleep = sleepy_kernel();
585 let slept = sleepy::System::build(&mut asleep).expect("the tickless declaration builds");
586
587 let mut ticking =
588 awake::Kernel::<TestPort, NoTrace, NoTickHook>::new(TestPort::default(), NoTrace)
589 .expect("the declared geometry adds up");
590 let ticked = awake::System::build(&mut ticking).expect("the ticking declaration builds");
591
592 // The two declarations are the same text over two configurations, so
593 // they must hand back the same handle for the same task. If they did
594 // not, the arms of the invariance test below would be comparing two
595 // different systems and the comparison would mean nothing.
596 assert_eq!(
597 slept.worker, ticked.worker,
598 "identical declarations gave different task handles"
599 );
600 let _ = (&slept.mark, &ticked.mark);
601 }
602
603 /// A kernel with tickless on and a port that takes every window.
604 fn sleepy_kernel() -> sleepy::Kernel<SleepyPort, Scheduling<Recorder>, NoTickHook> {
605 sleepy::Kernel::new(SleepyPort::default(), Scheduling::new(Recorder::default()))
606 .expect("the declared geometry adds up")
607 }
608
609 /// The port asks for the whole window, and the kernel winds the clock
610 /// over it — all but the last tick, which is left pended so the delayed
611 /// task is woken by the same code that would have woken it.
612 #[test]
613 fn a_sleeping_port_is_asked_for_the_whole_idle_window() {
614 let mut k = sleepy_kernel();
615 k.create_task("worker", 1).expect("worker");
616 let started = k.start_scheduler().expect("start");
617 // The timer daemon is created READY at `TIMER_TASK_PRIORITY`, and
618 // in a running system it blocks on its command queue immediately.
619 // Nothing runs it here, so park it: a task ready above the idle
620 // priority is precisely what `expected_idle_time` refuses to sleep
621 // through, and leaving it ready would test that refusal instead of
622 // the sleep.
623 k.suspend(Some(started.timer))
624 .expect("park the timer daemon");
625 k.delay(DELAY).expect("the worker delays");
626
627 let before = k.tick_count();
628 k.idle_suppress_ticks();
629
630 assert_eq!(k.port().sleeps.get(), 1, "the port was asked once");
631 assert_eq!(
632 k.port().slept.get(),
633 DELAY,
634 "it was offered the whole window"
635 );
636 // Nine ticks were STEPPED and the tenth was left pended, and then
637 // `resume_all` unwound it through `increment_tick` -- which is what
638 // wakes the delayed task, by the same code that would have woken it
639 // had the kernel ticked all ten. So the clock lands on the wake
640 // either way, and that is the whole reason the schedule survives.
641 assert_eq!(
642 k.tick_count(),
643 before.saturating_add(DELAY),
644 "the clock did not land on the worker's wake"
645 );
646 }
647
648 /// The `configUSE_TICKLESS_IDLE` gate: the same port, the same script,
649 /// a configuration with it off, and the port is never asked.
650 #[test]
651 fn tickless_off_never_asks_the_port_to_sleep() {
652 let mut k =
653 awake::Kernel::<SleepyPort, NoTrace, NoTickHook>::new(SleepyPort::default(), NoTrace)
654 .expect("the declared geometry adds up");
655 k.create_task("worker", 1).expect("worker");
656 let started = k.start_scheduler().expect("start");
657 // The timer daemon is created READY at `TIMER_TASK_PRIORITY`, and
658 // in a running system it blocks on its command queue immediately.
659 // Nothing runs it here, so park it: a task ready above the idle
660 // priority is precisely what `expected_idle_time` refuses to sleep
661 // through, and leaving it ready would test that refusal instead of
662 // the sleep.
663 k.suspend(Some(started.timer))
664 .expect("park the timer daemon");
665 k.delay(DELAY).expect("the worker delays");
666
667 let before = k.tick_count();
668 k.idle_suppress_ticks();
669
670 assert_eq!(k.port().sleeps.get(), 0, "the port was asked");
671 assert_eq!(k.tick_count(), before, "the clock moved");
672 }
673
674 /// A port that oversleeps is a port bug, and the kernel refuses to wind
675 /// the clock past the wake it would lose. The C `configASSERT`s this;
676 /// a kernel that forbids panicking has to clamp instead.
677 #[test]
678 fn the_kernel_clamps_a_port_that_oversleeps() {
679 let mut k = sleepy::Kernel::<OversleepingPort, NoTrace, NoTickHook>::new(
680 OversleepingPort::default(),
681 NoTrace,
682 )
683 .expect("the declared geometry adds up");
684 k.create_task("worker", 1).expect("worker");
685 let started = k.start_scheduler().expect("start");
686 // The timer daemon is created READY at `TIMER_TASK_PRIORITY`, and
687 // in a running system it blocks on its command queue immediately.
688 // Nothing runs it here, so park it: a task ready above the idle
689 // priority is precisely what `expected_idle_time` refuses to sleep
690 // through, and leaving it ready would test that refusal instead of
691 // the sleep.
692 k.suspend(Some(started.timer))
693 .expect("park the timer daemon");
694 k.delay(DELAY).expect("the worker delays");
695
696 let before = k.tick_count();
697 k.idle_suppress_ticks();
698
699 // The port claimed `4 * DELAY + 9` = 49 ticks. Unclamped the clock
700 // would be 49 ticks on and the worker's wake would have been stepped
701 // straight past; clamped it lands on the wake exactly, like a port
702 // that behaved.
703 assert_eq!(
704 k.tick_count(),
705 before.saturating_add(DELAY),
706 "a port claiming four times its window moved the clock past the wake"
707 );
708 }
709
710 /// ★ The claim the whole mission rests on.
711 ///
712 /// Two kernels, identical but for `configUSE_TICKLESS_IDLE`, run the
713 /// same script. One sleeps through the idle window; the other ticks
714 /// through it. Their traces differ — that is the point, and it is why a
715 /// byte-diff cannot gate a tickless port. Their SCHEDULES do not.
716 ///
717 /// `Scheduling` is the projection that says so, and this is it applied
718 /// to a kernel that really did suppress its ticks rather than to a trace
719 /// file standing in for one.
720 #[test]
721 fn the_schedule_is_the_same_with_and_without_tickless() {
722 let target = DELAY.saturating_add(2);
723
724 let mut asleep = sleepy_kernel();
725 asleep.create_task("worker", 1).expect("worker");
726 let started = asleep.start_scheduler().expect("start");
727 asleep
728 .suspend(Some(started.timer))
729 .expect("park the timer daemon");
730 asleep.delay(DELAY).expect("the worker delays");
731 asleep.idle_suppress_ticks();
732 while asleep.tick_count() < target {
733 if asleep.increment_tick() {
734 asleep.switch_context();
735 }
736 }
737
738 let mut ticking = awake::Kernel::<TestPort, Scheduling<Recorder>, NoTickHook>::new(
739 TestPort::default(),
740 Scheduling::new(Recorder::default()),
741 )
742 .expect("the declared geometry adds up");
743 ticking.create_task("worker", 1).expect("worker");
744 let started = ticking.start_scheduler().expect("start");
745 ticking
746 .suspend(Some(started.timer))
747 .expect("park the timer daemon");
748 ticking.delay(DELAY).expect("the worker delays");
749 ticking.idle_suppress_ticks();
750 while ticking.tick_count() < target {
751 if ticking.increment_tick() {
752 ticking.switch_context();
753 }
754 }
755
756 assert!(
757 asleep.port().sleeps.get() > 0,
758 "the sleeping arm never slept, so this proves nothing"
759 );
760
761 let slept_schedule = asleep.into_trace().into_inner();
762 let ticked_schedule = ticking.into_trace().into_inner();
763
764 assert_eq!(
765 slept_schedule, ticked_schedule,
766 "sleeping through the idle window moved the schedule"
767 );
768 }
769
770 // ---- a delayed list deeper than the conformance corpus ever builds ---
771
772 // `System` here is never built: the tasks are created directly so the
773 // declared queue slot stays free for `xTimerCreateTimerTask`. The
774 // declaration is still what sizes the kernel.
775 crate::system! {
776 mod deep use TestConfig;
777 tasks {
778 d0: 1, d1: 1, d2: 1, d3: 1, d4: 1,
779 d5: 1, d6: 1, d7: 1, d8: 1, d9: 1
780 }
781 queues { unused: u8; 1 }
782 }
783
784 /// Ten tasks blocked at once, waking in wake-time order.
785 ///
786 /// **This exists because the conformance gate cannot reach here.** That
787 /// gate is the strongest evidence in the project -- 19 scenarios, every
788 /// scheduling decision compared line-for-line against the instrumented C
789 /// kernel -- and its delayed list never gets deeper than FOUR. Measured,
790 /// by replaying each scenario's own trace and tracking membership:
791 ///
792 /// ```text
793 /// BlockQ 4 death 4 dynamic 3 PollQ 3 semtest 3 recmutex 3
794 /// blocktim 3 IntSemTest 3 TimerDemo 3 QPeek 2 GenQTest 2
795 /// MessageBufferAMP 2 countsem 1 QueueOverwrite 1
796 /// QueueSetPolling 1 StreamBufferInterrupt 1 EventGroupsDemo 1
797 /// ```
798 ///
799 /// `vListInsert` is the only operation in the kernel whose cost is its
800 /// depth, and the corpus never tests it past n=4. Anything that goes
801 /// wrong only when the list is deep -- an ordering bug, an off-by-one in
802 /// the walk, a fast path that appends where it should splice -- passes
803 /// that gate green.
804 ///
805 /// The delays are deliberately NOT monotonic: a shortcut that appends
806 /// unconditionally orders them wrongly, and ascending delays would let
807 /// it through. They are distinct, because two tasks sharing a wake time
808 /// wake on the same tick and this probe cannot see which left first.
809 #[test]
810 #[allow(clippy::indexing_slicing)]
811 fn ten_blocked_tasks_wake_in_wake_time_order() {
812 let mut k =
813 deep::Kernel::<TestPort, NoTrace, NoTickHook>::new(TestPort::default(), NoTrace)
814 .expect("the declared geometry adds up");
815 // Created directly rather than through `System::build`. Build would
816 // also create the declared queue, and that slot is the one
817 // `xTimerCreateTimerTask` needs at startup -- the declaration is
818 // here to SIZE the kernel, not to furnish it.
819 let names = ["d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9"];
820 let mut all = [::rusty_rtos_core::handle::TaskHandle::from_raw(0); 10];
821 for (slot, name) in all.iter_mut().zip(names) {
822 *slot = k.create_task(name, 1).expect("task");
823 }
824 let started = k.start_scheduler().expect("start");
825 // Park the timer daemon. It sits at TIMER_TASK_PRIORITY, above these
826 // tasks, so leaving it ready means it is the one that runs and the
827 // ten never get a turn. The tickless tests park it for the same
828 // reason.
829 k.suspend(Some(started.timer)).expect("park the daemon");
830
831 // Out of order on purpose: a shortcut that appends unconditionally
832 // gets these wrong, and ascending delays would let it through.
833 //
834 // DISTINCT, though. Two tasks with the same wake time wake on the
835 // same TICK, and `task_state_get` cannot say which of them left the
836 // delayed list first -- the probe below would record them in index
837 // order whatever the list did. The tie rule is real and it is tested
838 // where it is observable, directly on the list, in
839 // `list::tests::a_value_equal_to_the_tail_goes_after_it`.
840 let delays = [9u64, 3, 14, 7, 1, 11, 5, 8, 2, 13];
841
842 // Block each in turn. `delay` acts on whichever task is RUNNING, so
843 // the schedule picks the order and this records what it picked --
844 // asserting the kernel's own choice rather than assuming one.
845 let mut blocked = [(0u64, 0usize); 10];
846 let mut n = 0usize;
847 for _ in 0..200u32 {
848 if n == all.len() {
849 break;
850 }
851 let running = k.current();
852 if let Some(which) = all.iter().position(|t| *t == running) {
853 if !blocked[..n].iter().any(|(_, w)| *w == which) {
854 k.delay(delays[which]).expect("blocks");
855 blocked[n] = (delays[which], which);
856 n = n.saturating_add(1);
857 }
858 }
859 k.switch_context();
860 }
861 assert_eq!(n, all.len(), "every task should have blocked");
862
863 for (i, task) in all.iter().enumerate() {
864 assert_eq!(
865 k.task_state_get(*task).expect("state"),
866 crate::kernel::TaskState::Blocked,
867 "task {i} should be blocked; all ten are, at once, which is more than twice as deep as any conformance scenario reaches"
868 );
869 }
870
871 // Tick forward and record the order they come back.
872 let mut woke = [0usize; 10];
873 let mut w = 0usize;
874 let mut asleep = [true; 10];
875 for _ in 0..40u32 {
876 k.tick_from_isr();
877 for (i, task) in all.iter().enumerate() {
878 if asleep[i]
879 && k.task_state_get(*task).expect("state") != crate::kernel::TaskState::Blocked
880 {
881 asleep[i] = false;
882 woke[w] = i;
883 w = w.saturating_add(1);
884 }
885 }
886 }
887 assert_eq!(w, all.len(), "every task should have woken");
888
889 // Ascending wake time; ties in the order they blocked. That is what
890 // `vListInsert` promises and the only order the list guarantees.
891 let mut want = blocked;
892 want.sort_by_key(|(ticks, _)| *ticks);
893 let want = want.map(|(_, which)| which);
894 assert_eq!(
895 woke, want,
896 "the delayed list did not wake in wake-time order"
897 );
898 }
899
900 /// Creating a task at a HIGHER priority than the running one must ask
901 /// for a switch; creating one LOWER must not.
902 ///
903 /// **This closes a gap the ledger measured and left open.** `cargo
904 /// mutants` over `kernel.rs`, judged by the conformance corpus, left six
905 /// survivors, and five were this one line in `prvAddNewTaskToReadyList`:
906 ///
907 /// ```text
908 /// if self.running && C::USE_PREEMPTION && self.current_priority() < priority
909 /// ```
910 ///
911 /// `death` was added so the corpus would create tasks after the
912 /// scheduler had started, and it narrowed six survivors to four. It
913 /// could not do better, for a reason visible in its own source:
914 /// `vCreateTasks` creates both suicidal tasks at `uxTaskPriorityGet(
915 /// NULL )` -- its OWN priority -- so the new task never outranks the
916 /// running one. The guard is reached and evaluated on every create and
917 /// is never TRUE. Mutations that make it fire spuriously die at once;
918 /// mutations that suppress a yield which never happens are invisible.
919 /// Reachable is not killed.
920 ///
921 /// No corpus scenario creates a higher-priority task while running, and
922 /// none can be added without a C original to diff against. A unit test
923 /// can do it, and this is it. The four survivors:
924 ///
925 /// | mutation | caught by |
926 /// |---|---|
927 /// | condition → `false` | the HIGHER half |
928 /// | body removed (no yield) | the HIGHER half |
929 /// | `<` → `>` | the HIGHER half |
930 /// | `<` → `!=` | the LOWER half |
931 ///
932 /// Which is why both halves are here. The lower half looks like a
933 /// formality and is the only thing that kills `!=`.
934 #[test]
935 fn creating_a_higher_priority_task_asks_for_a_switch_and_a_lower_one_does_not() {
936 let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
937 .expect("the declared geometry adds up");
938 let mid = k.create_task("mid", 2).expect("task mid");
939 k.start_scheduler().expect("start");
940 assert_eq!(k.current(), mid, "the only app task runs");
941
942 // ---- LOWER: no switch is owed -----------------------------------
943 let before = k.port().yields.get();
944 let _low = k.create_task("low", 1).expect("task low");
945 assert_eq!(
946 k.port().yields.get(),
947 before,
948 "a task created BELOW the running priority cannot preempt it, so the kernel must not ask for a switch"
949 );
950
951 // ---- HIGHER: a switch is owed -----------------------------------
952 let before = k.port().yields.get();
953 let _high = k.create_task("high", 3).expect("task high");
954 assert!(
955 k.port().yields.get() > before,
956 "a task created ABOVE the running priority preempts it, and the kernel must ask for the switch"
957 );
958 }
959
960 /// A kernel with room for a stream buffer, which `system!` never gives
961 /// one: the macro sizes `BUFFERS` and `BYTES` at zero.
962 type BufferKernel = crate::Kernel<
963 TestConfig,
964 TestPort,
965 NoTrace,
966 NoTickHook,
967 4,
968 { crate::list_slots_for(4, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
969 { crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
970 1,
971 1,
972 2,
973 64,
974 0,
975 0,
976 { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
977 >;
978
979 /// `xStreamBufferSetTriggerLevel`'s contract, pinned.
980 ///
981 /// The C coerces a zero trigger to one BEFORE bounds-checking:
982 ///
983 /// ```c
984 /// if( xTriggerLevel == ( size_t ) 0 ) { xTriggerLevel = 1; }
985 /// if( xTriggerLevel < pxStreamBuffer->xLength ) { ...pdPASS }
986 /// else { xReturn = pdFALSE; }
987 /// ```
988 ///
989 /// This kernel had the two the other way round. The orders disagree on
990 /// exactly one input -- a zero trigger against a length of ONE -- and
991 /// that input cannot be built: `length` is `size + 1` (the spare byte a
992 /// ring buffer needs to tell full from empty) and `size == 0` is refused
993 /// at creation. So it was an inconsistency with the C, not a live bug,
994 /// and the order has been matched anyway rather than left resting on an
995 /// arithmetic detail in another function.
996 ///
997 /// What this test pins is the contract at the lengths that exist. There
998 /// is no conformance scenario for this API and no C demo in the vendored
999 /// tree that calls it, so a differential is not available --
1000 /// `docs/HOLES.md` H2 -- and this is the only evidence there is.
1001 #[test]
1002 fn the_trigger_level_contract() {
1003 let mut k =
1004 BufferKernel::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
1005
1006 // `create(1, 1)` is a length of TWO: one byte of payload and the
1007 // spare. The smallest buffer a caller can actually make.
1008 let small = k.stream_buffer_create(1, 1).expect("a one-byte buffer");
1009 assert_eq!(
1010 k.stream_buffer_set_trigger_level(small, 0),
1011 Ok(true),
1012 "zero becomes one, and one IS below a length of two"
1013 );
1014 assert_eq!(
1015 k.stream_buffer_set_trigger_level(small, 2),
1016 Ok(false),
1017 "two is not below a length of two"
1018 );
1019
1020 let wide = k.stream_buffer_create(8, 1).expect("an eight-byte buffer");
1021 assert_eq!(k.stream_buffer_set_trigger_level(wide, 0), Ok(true));
1022 assert_eq!(
1023 k.stream_buffer_set_trigger_level(wide, 8),
1024 Ok(true),
1025 "8 < 9"
1026 );
1027 assert_eq!(
1028 k.stream_buffer_set_trigger_level(wide, 9),
1029 Ok(false),
1030 "nine is not below a length of nine"
1031 );
1032 }
1033
1034 fn kernel() -> K {
1035 K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up")
1036 }
1037
1038 /// `configUSE_TIME_SLICING`: two READY tasks of the same priority
1039 /// must take turns.
1040 ///
1041 /// Fixed priority says what happens between DIFFERENT priorities and
1042 /// nothing at all about two tasks at the same one. The C fills that in
1043 /// twice over: `xTaskIncrementTick` asks for a switch whenever more
1044 /// than one task is ready at the running task's priority, and
1045 /// `taskSELECT_HIGHEST_PRIORITY_TASK` then takes the NEXT entry rather
1046 /// than the head.
1047 ///
1048 /// Without it a task that never blocks starves its equal-priority
1049 /// peers completely — not slowly, completely — and the failure looks
1050 /// like somebody else's demo being broken. `rusty_rtos-capi`'s host
1051 /// cell found it that way: two demo files whose tasks sit at the same
1052 /// priority, one of them getting 13.5 million turns and the other
1053 /// ZERO.
1054 #[derive(Debug, Clone, Copy, Default)]
1055 pub struct SliceConfig;
1056
1057 impl Config for SliceConfig {
1058 type Tick = Bits32;
1059 const TICK_RATE_HZ: u32 = 100;
1060 const MAX_PRIORITIES: u8 = 4;
1061 const MINIMAL_STACK_SIZE: usize = 1;
1062 const MAX_TASK_NAME_LEN: usize = 8;
1063 // The daemon sits BELOW the two tasks under test. Nothing drives
1064 // it here, so at its usual priority it would simply be the current
1065 // task for ever and the test would measure the daemon.
1066 const TIMER_TASK_PRIORITY: u8 = 0;
1067 const TIMER_TASK_STACK_DEPTH: usize = 1;
1068 const TIMER_QUEUE_LENGTH: usize = 1;
1069 const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
1070 // The point of this config: the default, stated out loud.
1071 const USE_TIME_SLICING: bool = true;
1072 const USE_PREEMPTION: bool = true;
1073 }
1074
1075 /// Built from the const generics directly rather than through
1076 /// `system!`, because that macro declares its tasks for you and this
1077 /// test needs to create them itself.
1078 type SliceKernel = crate::Kernel<
1079 SliceConfig,
1080 TestPort,
1081 NoTrace,
1082 NoTickHook,
1083 5,
1084 { crate::list_slots_for(5, 1, crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1)) },
1085 { crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1) },
1086 1,
1087 1,
1088 1,
1089 8,
1090 1,
1091 1,
1092 { <SliceConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1093 >;
1094
1095 /// The same declaration driven by a port that COUNTS switch requests,
1096 /// with room for a queue of our own beside the timer daemon's.
1097 ///
1098 /// `QUEUES` is 2 and `SLOTS` 8 for exactly that reason: the timer queue
1099 /// is created by `Kernel::new` and takes the first of each, so a test
1100 /// that makes its own queue needs the second.
1101 type CountingKernel = crate::Kernel<
1102 SliceConfig,
1103 CountingPort,
1104 NoTrace,
1105 NoTickHook,
1106 5,
1107 { crate::list_slots_for(5, 1, crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1)) },
1108 { crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1) },
1109 2,
1110 8,
1111 1,
1112 8,
1113 1,
1114 1,
1115 { <SliceConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1116 >;
1117
1118 /// Tick a kernel whose two equal-priority tasks never block, and count
1119 /// how many ticks each of them was the current task for.
1120 fn turns_over(ticks: u32) -> (u32, u32) {
1121 let mut k =
1122 SliceKernel::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
1123 let a = k.create_task("a", 2).expect("task a");
1124 let b = k.create_task("b", 2).expect("task b");
1125 k.start_scheduler().expect("start");
1126
1127 let (mut for_a, mut for_b) = (0u32, 0u32);
1128 for _ in 0..ticks {
1129 if k.increment_tick() {
1130 k.switch_context();
1131 }
1132 let now = k.current();
1133 if now == a {
1134 for_a = for_a.saturating_add(1);
1135 } else if now == b {
1136 for_b = for_b.saturating_add(1);
1137 }
1138 }
1139 (for_a, for_b)
1140 }
1141
1142 // A third test belongs here and is not written yet: equal-priority
1143 // rotation with a HIGHER-priority task cutting in between selections,
1144 // which is the shape every real system has. Two attempts at it were
1145 // withdrawn because they measured their own call pattern rather than
1146 // the scheduler -- `delay` yields as part of its contract, so a loop
1147 // that calls `delay` and then `switch_context` makes two selections
1148 // and can only sample after the second.
1149 //
1150 // What is known: driven directly, `switch_context` alternates
1151 // correctly between two equal-priority tasks with a third cutting in
1152 // (observed at the list, cursor 0 -> 1 -> 0). What is not known is why
1153 // `rusty_rtos_port/firmware/host-kernel` sees one of a pair get ZERO
1154 // turns in exactly that shape. That cell fails today and is the live
1155 // reproduction; this is the note that says so rather than a test that
1156 // asserts something unproven.
1157
1158 #[test]
1159 fn two_ready_tasks_of_equal_priority_take_turns() {
1160 let (a, b) = turns_over(200);
1161 assert!(a > 0, "task a never ran: {a} vs {b}");
1162 assert!(b > 0, "task b never ran: {a} vs {b}");
1163 }
1164
1165 /// `queueYIELD_IF_USING_PREEMPTION`: a send that readies a
1166 /// HIGHER-priority receiver must ask for a switch.
1167 ///
1168 /// This is the whole of `TimerDemo.c:469`, with no C anywhere near it.
1169 /// That demo stops a timer and asserts on the next line that the timer
1170 /// is inactive, and its own comment says why it may: "this will appear
1171 /// to happen immediately to this task because this task is running at
1172 /// a priority below the timer service task". `xTimerStop` is a send to
1173 /// the daemon's queue, so the assertion is really this test.
1174 ///
1175 /// It has two halves and the second is the one that bites. A send must
1176 /// ask for a switch when it wakes a higher-priority receiver — AND the
1177 /// receiver has to be WAITING ON THE QUEUE for there to be anything to
1178 /// wake. A daemon that polls its queue with a zero block time is
1179 /// parked nowhere, so the send finds no waiter, asks for nothing, and
1180 /// being higher priority buys it precisely nothing. Both halves are
1181 /// asserted below, because the first one passing is what makes the
1182 /// second one's absence invisible.
1183 #[test]
1184 fn a_send_that_wakes_a_higher_priority_receiver_asks_for_a_switch() {
1185 let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
1186 .expect("the declared geometry adds up");
1187 let hi = k.create_task("hi", 2).expect("task hi");
1188 let lo = k.create_task("lo", 1).expect("task lo");
1189 let q = k.queue_create(4).expect("a queue");
1190 k.start_scheduler().expect("start");
1191
1192 // The high-priority task waits ON the queue, which is what makes
1193 // it a waiter rather than merely a ready task of higher priority.
1194 assert_eq!(k.current(), hi, "the higher priority task runs first");
1195 assert!(
1196 matches!(k.queue_receive(q, 100), Ok(crate::queue::Wait::Blocked)),
1197 "an empty queue with a block time must park the receiver"
1198 );
1199 k.switch_context();
1200 assert_eq!(k.current(), lo, "with hi parked, lo runs");
1201
1202 // Now the send, from the LOWER-priority task.
1203 let before = k.port().yields.get();
1204 assert!(matches!(
1205 k.queue_send(q, 7, 0),
1206 Ok(crate::queue::Wait::Ready(()))
1207 ));
1208 let asked = k.port().yields.get().saturating_sub(before);
1209 assert_eq!(
1210 asked, 1,
1211 "a send that readies a higher-priority receiver must ask for a switch"
1212 );
1213 }
1214
1215 /// The other half: a receiver that did NOT wait cannot be woken, so
1216 /// the send asks for nothing — which is correct, and is exactly the
1217 /// trap a polling daemon falls into.
1218 ///
1219 /// Recorded as an assertion rather than a comment because it is the
1220 /// behaviour a reader will otherwise call a bug in the send path,
1221 /// having found the send not yielding. The send is right; the caller
1222 /// that polls instead of waiting is wrong.
1223 #[test]
1224 fn a_send_asks_for_nothing_when_the_higher_priority_task_never_waited() {
1225 let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
1226 .expect("the declared geometry adds up");
1227 let _hi = k.create_task("hi", 2).expect("task hi");
1228 let _lo = k.create_task("lo", 1).expect("task lo");
1229 let q = k.queue_create(4).expect("a queue");
1230 k.start_scheduler().expect("start");
1231
1232 // `hi` polls. A zero block time on an empty queue is `Empty`, NOT
1233 // `Blocked` — and the difference is the whole point: `Blocked`
1234 // means "I have been parked and will be woken", `Empty` means
1235 // "there was nothing there and I was not parked". A poller gets
1236 // the second, so there is nothing for a later send to wake.
1237 assert!(
1238 matches!(
1239 k.queue_receive(q, 0),
1240 Err(rusty_rtos_core::error::Error::Empty)
1241 ),
1242 "a zero-wait receive on an empty queue reports Empty, not Blocked"
1243 );
1244 k.switch_context();
1245
1246 let before = k.port().yields.get();
1247 assert!(matches!(
1248 k.queue_send(q, 7, 0),
1249 Ok(crate::queue::Wait::Ready(()))
1250 ));
1251 assert_eq!(
1252 k.port().yields.get(),
1253 before,
1254 "there was no waiter to wake, so nothing should have been asked for"
1255 );
1256 }
1257
1258 #[test]
1259 fn neither_equal_priority_task_starves_the_other() {
1260 let (a, b) = turns_over(200);
1261 // A round robin gives them one tick each in turn. Allowing a 4x
1262 // imbalance is generous; a scheduler that never rotates gives one
1263 // of them zero, which is what this is here to catch.
1264 let (lo, hi) = (a.min(b), a.max(b));
1265 assert!(
1266 lo.saturating_mul(4) >= hi,
1267 "one starved the other: {a} against {b}"
1268 );
1269 }
1270
1271 /// **The geometry is the declaration**, arithmetic and all.
1272 ///
1273 /// This is the `.bss` claim as a number rather than a hope: every
1274 /// const is exactly what the two `tasks` and two `queues` lines say,
1275 /// with no spare anywhere.
1276 #[test]
1277 fn the_geometry_is_derived_from_the_declaration() {
1278 assert_eq!(demo::APP_TASKS, 2, "the two declared tasks");
1279 assert_eq!(demo::TASKS, 4, "plus the idle task and the timer daemon");
1280 assert_eq!(demo::QUEUES, 2, "the two declared queues");
1281 assert_eq!(demo::SLOTS, 13, "10 + 3, the declared lengths and no spare");
1282 // `ITEMS` is the SLOT count now, not the item count: two list items
1283 // per task (8), plus one end-marker node per list (14), rounded up
1284 // to a power of two. 22 -> 32.
1285 assert_eq!(
1286 demo::ITEMS,
1287 32,
1288 "8 items + 14 markers, rounded to a power of two"
1289 );
1290 assert_eq!(
1291 demo::ITEMS,
1292 crate::list_slots_for(demo::TASKS, demo::TIMERS, demo::LISTS),
1293 "and it is derived, not written by hand"
1294 );
1295 // The slack is the price of the mask, and it is worth being able to
1296 // see: this configuration carries 10 spare nodes.
1297 assert_eq!(
1298 demo::ITEMS - demo::LISTS,
1299 18,
1300 "item capacity: 8 needed, 18 available"
1301 );
1302 assert_eq!(
1303 demo::LISTS,
1304 crate::lists_for(TestConfig::MAX_PRIORITIES, 2, 0),
1305 "a ready list per priority, the fixed six, and two per queue"
1306 );
1307 }
1308
1309 /// A declared system builds, and `Kernel::new` accepts the geometry —
1310 /// which is the check that `items_for`/`lists_for` were applied to the
1311 /// same numbers the struct was built from.
1312 #[test]
1313 fn a_declared_system_builds_and_the_kernel_accepts_its_geometry() {
1314 let mut k = kernel();
1315 let system = demo::System::build(&mut k).expect("nothing here can fail");
1316 // The handles are the kernel's, in declaration order.
1317 assert!(!system.consumer.is_null());
1318 assert!(!system.producer.is_null());
1319 assert_ne!(system.consumer, system.producer);
1320 assert_eq!(k.task_count(), 2, "no task the declaration did not name");
1321 }
1322
1323 /// The queues come back typed, and carry what they were declared to.
1324 #[test]
1325 fn the_declared_queues_move_their_own_type() {
1326 let mut k = kernel();
1327 let mut system = demo::System::build(&mut k).expect("nothing here can fail");
1328 assert!(matches!(system.data.send(&mut k, 4_242u16, 0), Sent::Ok));
1329 assert!(matches!(system.marks.send(&mut k, 7u8, 0), Sent::Ok));
1330 assert_eq!(system.data.len(&mut k), Ok(1));
1331 assert_eq!(system.marks.len(&mut k), Ok(1));
1332 }
1333
1334 /// **The `.bss` claim, as a number.**
1335 ///
1336 /// The alternative to declaring is what every scenario in this repo
1337 /// does today: pick a geometry by hand that covers the biggest thing
1338 /// you might do. The demo's kernel is sized `TASKS = 24`,
1339 /// `QUEUES = 12`, `SLOTS = 128`, `TIMERS = 32` because it has to hold
1340 /// eighteen scenarios at once. A system that declares two tasks and
1341 /// thirteen slots gets a kernel sized for two tasks and thirteen
1342 /// slots, and the difference is not small.
1343 ///
1344 /// This is a counter, not a benchmark: `size_of` is exact, decided at
1345 /// compile time, and identical on every machine.
1346 #[test]
1347 fn a_declared_kernel_is_sized_for_what_was_declared() {
1348 /// The demo's hand-picked geometry, which is what you use when
1349 /// you cannot declare.
1350 type Blanket = crate::Kernel<
1351 TestConfig,
1352 TestPort,
1353 NoTrace,
1354 NoTickHook,
1355 24,
1356 { crate::list_slots_for(24, 32, crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4)) },
1357 { crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4) },
1358 12,
1359 128,
1360 8,
1361 2048,
1362 32,
1363 4,
1364 { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1365 >;
1366
1367 let declared = core::mem::size_of::<K>();
1368 let blanket = core::mem::size_of::<Blanket>();
1369 // Printed so the footprint row can be read off a test run.
1370 let ratio = blanket as f64 / declared as f64;
1371 std::eprintln!("declared {declared} bytes, hand-sized {blanket} bytes, {ratio:.1}x");
1372 assert!(
1373 declared < blanket,
1374 "a declared kernel ({declared}) should be smaller than one sized for everything ({blanket})"
1375 );
1376 // The declaration is the only input: change the declaration and
1377 // this number changes with it, which is the whole claim.
1378 assert_eq!(
1379 declared,
1380 core::mem::size_of::<demo::Kernel<TestPort, NoTrace, NoTickHook>>()
1381 );
1382 }
1383
1384 /// **The slot count is exact, and the exactness is load-bearing.**
1385 ///
1386 /// `SLOTS` is the sum of the declared lengths, so filling every
1387 /// declared queue to its declared length uses the arena to the last
1388 /// slot and no further. A geometry that was rounded up would pass a
1389 /// weaker version of this; this one would fail if `SLOTS` were 12.
1390 #[test]
1391 fn every_declared_slot_is_usable_and_there_is_not_one_spare() {
1392 let mut k = kernel();
1393 let mut system = demo::System::build(&mut k).expect("nothing here can fail");
1394 for i in 0..10u16 {
1395 assert!(
1396 matches!(system.data.send(&mut k, i, 0), Sent::Ok),
1397 "slot {i} of the declared ten"
1398 );
1399 }
1400 for i in 0..3u8 {
1401 assert!(
1402 matches!(system.marks.send(&mut k, i, 0), Sent::Ok),
1403 "slot {i} of the declared three"
1404 );
1405 }
1406 // Both are now exactly full, which is `SLOTS` exactly consumed.
1407 assert!(matches!(system.data.send(&mut k, 99, 0), Sent::Full(99)));
1408 assert!(matches!(system.marks.send(&mut k, 9, 0), Sent::Full(9)));
1409 assert_eq!(demo::SLOTS, 13);
1410 }
1411
1412 // ---- plan P5: the tickless thresholds -----------------------------------
1413 //
1414 // `prvGetExpectedIdleTime`'s three "answer zero" arms and the
1415 // `configEXPECTED_IDLE_TIME_BEFORE_SLEEP` boundary: the survey's mutants
1416 // there lived, because every tickless test above sleeps through a window
1417 // far wider than the threshold with nothing else ready.
1418
1419 /// [`TicklessConfig`] made cooperative: the only build in which a task
1420 /// above the idle priority can be ready while the idle task runs.
1421 pub struct TicklessCooperativeConfig;
1422
1423 impl Config for TicklessCooperativeConfig {
1424 type Tick = Bits32;
1425 const TICK_RATE_HZ: u32 = 100;
1426 const MAX_PRIORITIES: u8 = 4;
1427 const MINIMAL_STACK_SIZE: usize = 1;
1428 const MAX_TASK_NAME_LEN: usize = 8;
1429 const TIMER_TASK_PRIORITY: u8 = 3;
1430 const TIMER_TASK_STACK_DEPTH: usize = 1;
1431 const TIMER_QUEUE_LENGTH: usize = 1;
1432 const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
1433 const USE_TIME_SLICING: bool = false;
1434 const USE_TICKLESS_IDLE: bool = true;
1435 const USE_PREEMPTION: bool = false;
1436 }
1437
1438 /// Room for idle, the daemon and three tasks of our own.
1439 type Tk<Cfg> = crate::Kernel<
1440 Cfg,
1441 SleepyPort,
1442 NoTrace,
1443 NoTickHook,
1444 5,
1445 { crate::list_slots_for(5, 0, crate::lists_for(4, 1, 0)) },
1446 { crate::lists_for(4, 1, 0) },
1447 1,
1448 1,
1449 0,
1450 0,
1451 0,
1452 0,
1453 1,
1454 >;
1455
1456 /// Started, the daemon parked, with the given tasks of our own.
1457 fn tickless<Cfg: Config>(tasks: &[(&str, u8)]) -> Tk<Cfg> {
1458 let mut k = Tk::<Cfg>::new(SleepyPort::default(), NoTrace).expect("geometry");
1459 for &(name, priority) in tasks {
1460 k.create_task(name, priority).expect("a task");
1461 }
1462 let h = k.start_scheduler().expect("start");
1463 k.suspend(Some(h.timer)).expect("park the daemon");
1464 k
1465 }
1466
1467 /// `if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )`:
1468 /// a window of exactly the threshold sleeps.
1469 #[test]
1470 fn an_idle_window_of_exactly_the_threshold_sleeps() {
1471 let mut k = tickless::<TicklessConfig>(&[("worker", 1)]);
1472 k.delay(TicklessConfig::EXPECTED_IDLE_TIME_BEFORE_SLEEP)
1473 .expect("delay");
1474 k.idle_suppress_ticks();
1475 assert_eq!(k.port().sleeps.get(), 1);
1476 }
1477
1478 /// One tick short of it does not -- and the refusal is made before
1479 /// `vTaskSuspendAll`, so it takes no critical section either.
1480 #[test]
1481 fn an_idle_window_below_the_threshold_neither_sleeps_nor_takes_a_section() {
1482 let mut k = tickless::<TicklessConfig>(&[("worker", 1)]);
1483 k.delay(TicklessConfig::EXPECTED_IDLE_TIME_BEFORE_SLEEP - 1)
1484 .expect("delay");
1485 let exits = k.port().exits.get();
1486 k.idle_suppress_ticks();
1487 assert_eq!(k.port().sleeps.get(), 0);
1488 assert_eq!(
1489 k.port().exits.get(),
1490 exits,
1491 "the refusal took a critical section"
1492 );
1493 }
1494
1495 /// Another task at the idle priority is ready, so the next tick must be
1496 /// processed to share the slice: no sleep, however wide the window.
1497 #[test]
1498 fn another_idle_priority_task_ready_means_no_sleep() {
1499 let mut k = tickless::<TicklessConfig>(&[("worker", 1), ("slacker", 0)]);
1500 k.delay(20).expect("the worker delays");
1501 k.idle_suppress_ticks();
1502 assert_eq!(k.port().sleeps.get(), 0);
1503 }
1504
1505 /// Cooperative only: a task above the idle priority was woken but the
1506 /// idle task keeps the CPU, and it must not sleep with that task ready.
1507 #[test]
1508 fn a_ready_task_above_the_idle_priority_means_no_sleep() {
1509 let mut k = tickless::<TicklessCooperativeConfig>(&[("early", 1), ("late", 1)]);
1510 k.delay(50).expect("the first task delays long");
1511 k.delay(3).expect("the second delays short");
1512 for _ in 0..3_u32 {
1513 k.tick_from_isr();
1514 }
1515 assert_eq!(
1516 k.name_of(k.current()).expect("a name").as_str(),
1517 "IDLE",
1518 "cooperative: the woken task does not preempt"
1519 );
1520 k.idle_suppress_ticks();
1521 assert_eq!(k.port().sleeps.get(), 0);
1522 }
1523}