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 }
390
391 impl Port for SleepyPort {
392 fn yield_now(&self) {}
393 fn yield_from_isr(&self, _woken: Woken) {}
394 fn enter_critical(&self) {
395 self.nesting.set(self.nesting.get().saturating_add(1));
396 }
397 fn exit_critical(&self) {
398 self.nesting.set(self.nesting.get().saturating_sub(1));
399 }
400 fn set_interrupt_mask_from_isr(&self) -> u32 {
401 0
402 }
403 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
404 fn in_isr(&self) -> bool {
405 false
406 }
407 fn set_in_tick_entry(&self, _yes: bool) {}
408
409 fn suppress_ticks_and_sleep(&self, expected_idle_ticks: u64) -> u64 {
410 self.sleeps.set(self.sleeps.get().saturating_add(1));
411 self.slept
412 .set(self.slept.get().saturating_add(expected_idle_ticks));
413 expected_idle_ticks
414 }
415 }
416
417 /// A port that OVERSLEEPS, to prove the kernel clamps rather than
418 /// trusting it.
419 #[derive(Debug, Default)]
420 pub struct OversleepingPort {
421 nesting: core::cell::Cell<u32>,
422 }
423
424 impl Port for OversleepingPort {
425 fn yield_now(&self) {}
426 fn yield_from_isr(&self, _woken: Woken) {}
427 fn enter_critical(&self) {
428 self.nesting.set(self.nesting.get().saturating_add(1));
429 }
430 fn exit_critical(&self) {
431 self.nesting.set(self.nesting.get().saturating_sub(1));
432 }
433 fn set_interrupt_mask_from_isr(&self) -> u32 {
434 0
435 }
436 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
437 fn in_isr(&self) -> bool {
438 false
439 }
440 fn set_in_tick_entry(&self, _yes: bool) {}
441
442 fn suppress_ticks_and_sleep(&self, expected_idle_ticks: u64) -> u64 {
443 expected_idle_ticks.saturating_mul(4).saturating_add(9)
444 }
445 }
446
447 #[derive(Debug, Default)]
448 pub struct TestPort {
449 nesting: core::cell::Cell<u32>,
450 }
451
452 impl Port for TestPort {
453 fn yield_now(&self) {}
454 fn yield_from_isr(&self, _woken: Woken) {}
455 fn enter_critical(&self) {
456 self.nesting.set(self.nesting.get().saturating_add(1));
457 }
458 fn exit_critical(&self) {
459 self.nesting.set(self.nesting.get().saturating_sub(1));
460 }
461 fn set_interrupt_mask_from_isr(&self) -> u32 {
462 0
463 }
464 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
465 fn in_isr(&self) -> bool {
466 false
467 }
468 fn set_in_tick_entry(&self, _yes: bool) {}
469 }
470
471 /// A [`TestPort`] that COUNTS the switches it was asked for.
472 ///
473 /// `TestPort::yield_now` is empty, which is right for tests about what
474 /// the kernel computes and useless for a test about whether it asked
475 /// for a switch at all. Those are different questions and the second
476 /// one has no other instrument.
477 #[derive(Debug, Default)]
478 pub struct CountingPort {
479 nesting: core::cell::Cell<u32>,
480 yields: core::cell::Cell<u32>,
481 }
482
483 impl Port for CountingPort {
484 /// Count the kernel ASKING for a switch, not one style of taking it.
485 ///
486 /// The first version of this counted `yield_now`, and measured the
487 /// wrong thing: `Port::COMMITS_SWITCH` defaults to `false`, so
488 /// `port_yield` calls `switch_context` itself and never reaches
489 /// `yield_now` at all. The test read zero and looked like a kernel
490 /// defect. `count_yield` is on the unconditional path, so it
491 /// answers "did the kernel decide a switch was needed" whichever
492 /// way the port takes it — which is the question.
493 fn count_yield(&self) {
494 self.yields.set(self.yields.get().saturating_add(1));
495 }
496 fn yield_now(&self) {}
497 fn yield_from_isr(&self, _woken: Woken) {}
498 fn enter_critical(&self) {
499 self.nesting.set(self.nesting.get().saturating_add(1));
500 }
501 fn exit_critical(&self) {
502 self.nesting.set(self.nesting.get().saturating_sub(1));
503 }
504 fn set_interrupt_mask_from_isr(&self) -> u32 {
505 0
506 }
507 fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
508 fn in_isr(&self) -> bool {
509 false
510 }
511 fn set_in_tick_entry(&self, _yes: bool) {}
512 }
513
514 #[derive(Debug, Default)]
515 pub struct NoTrace;
516
517 impl Trace for NoTrace {
518 // Nothing here reads a task name, so the kernel is told not to build one.
519 // Without this the trait default is `true` and every traced event costs a
520 // name lookup plus a UTF-8 validation for a sink that drops it: measured
521 // at 3.86x on one row (2026-09-21).
522 const WANTS_NAMES: bool = false;
523
524 fn event(&mut self, _tick: u64, _event: Event<'_>) {}
525 }
526
527 // The declaration under test: two tasks and two queues of different
528 // types and different lengths, so nothing about the geometry can come
529 // out right by symmetry.
530 crate::system! {
531 mod demo use TestConfig;
532 tasks { consumer: 2, producer: 1 }
533 queues { data: u16; 10, marks: u8; 3 }
534 }
535
536 type K = demo::Kernel<TestPort, NoTrace, NoTickHook>;
537
538 // ---- tickless idle ---------------------------------------------------
539
540 crate::system! {
541 mod sleepy use TicklessConfig;
542 tasks { worker: 1 }
543 queues { mark: u8; 1 }
544 }
545
546 crate::system! {
547 mod awake use TestConfig;
548 tasks { worker: 1 }
549 queues { mark: u8; 1 }
550 }
551
552 /// A sink that keeps the shape of a trace: every event, with the tick it
553 /// carried. Comparing two of these compares two schedules.
554 #[derive(Debug, Default, PartialEq, Eq)]
555 pub struct Recorder {
556 pub lines: std::vec::Vec<(u64, &'static str)>,
557 }
558
559 impl Trace for Recorder {
560 fn event(&mut self, tick: u64, event: Event<'_>) {
561 self.lines.push((tick, event.name()));
562 }
563 }
564
565 /// `worker` delays, leaving only the idle task ready — which is the
566 /// precondition tickless idle exists for.
567 const DELAY: u64 = 10;
568
569 /// Both declarations build what they declare.
570 ///
571 /// The tests that matter below start a scheduler, and `System::build` and
572 /// a started scheduler cannot both have the one queue slot a declaration
573 /// reserves -- `system!` sizes `QUEUES` with "no spare", and the timer
574 /// daemon needs it. So they create the one task they need by hand, and
575 /// this is where the generated builders are exercised.
576 #[test]
577 fn both_tickless_declarations_build_what_they_declare() {
578 let mut asleep = sleepy_kernel();
579 let slept = sleepy::System::build(&mut asleep).expect("the tickless declaration builds");
580
581 let mut ticking =
582 awake::Kernel::<TestPort, NoTrace, NoTickHook>::new(TestPort::default(), NoTrace)
583 .expect("the declared geometry adds up");
584 let ticked = awake::System::build(&mut ticking).expect("the ticking declaration builds");
585
586 // The two declarations are the same text over two configurations, so
587 // they must hand back the same handle for the same task. If they did
588 // not, the arms of the invariance test below would be comparing two
589 // different systems and the comparison would mean nothing.
590 assert_eq!(
591 slept.worker, ticked.worker,
592 "identical declarations gave different task handles"
593 );
594 let _ = (&slept.mark, &ticked.mark);
595 }
596
597 /// A kernel with tickless on and a port that takes every window.
598 fn sleepy_kernel() -> sleepy::Kernel<SleepyPort, Scheduling<Recorder>, NoTickHook> {
599 sleepy::Kernel::new(SleepyPort::default(), Scheduling::new(Recorder::default()))
600 .expect("the declared geometry adds up")
601 }
602
603 /// The port asks for the whole window, and the kernel winds the clock
604 /// over it — all but the last tick, which is left pended so the delayed
605 /// task is woken by the same code that would have woken it.
606 #[test]
607 fn a_sleeping_port_is_asked_for_the_whole_idle_window() {
608 let mut k = sleepy_kernel();
609 k.create_task("worker", 1).expect("worker");
610 let started = k.start_scheduler().expect("start");
611 // The timer daemon is created READY at `TIMER_TASK_PRIORITY`, and
612 // in a running system it blocks on its command queue immediately.
613 // Nothing runs it here, so park it: a task ready above the idle
614 // priority is precisely what `expected_idle_time` refuses to sleep
615 // through, and leaving it ready would test that refusal instead of
616 // the sleep.
617 k.suspend(Some(started.timer))
618 .expect("park the timer daemon");
619 k.delay(DELAY).expect("the worker delays");
620
621 let before = k.tick_count();
622 k.idle_suppress_ticks();
623
624 assert_eq!(k.port().sleeps.get(), 1, "the port was asked once");
625 assert_eq!(
626 k.port().slept.get(),
627 DELAY,
628 "it was offered the whole window"
629 );
630 // Nine ticks were STEPPED and the tenth was left pended, and then
631 // `resume_all` unwound it through `increment_tick` -- which is what
632 // wakes the delayed task, by the same code that would have woken it
633 // had the kernel ticked all ten. So the clock lands on the wake
634 // either way, and that is the whole reason the schedule survives.
635 assert_eq!(
636 k.tick_count(),
637 before.saturating_add(DELAY),
638 "the clock did not land on the worker's wake"
639 );
640 }
641
642 /// The `configUSE_TICKLESS_IDLE` gate: the same port, the same script,
643 /// a configuration with it off, and the port is never asked.
644 #[test]
645 fn tickless_off_never_asks_the_port_to_sleep() {
646 let mut k =
647 awake::Kernel::<SleepyPort, NoTrace, NoTickHook>::new(SleepyPort::default(), NoTrace)
648 .expect("the declared geometry adds up");
649 k.create_task("worker", 1).expect("worker");
650 let started = k.start_scheduler().expect("start");
651 // The timer daemon is created READY at `TIMER_TASK_PRIORITY`, and
652 // in a running system it blocks on its command queue immediately.
653 // Nothing runs it here, so park it: a task ready above the idle
654 // priority is precisely what `expected_idle_time` refuses to sleep
655 // through, and leaving it ready would test that refusal instead of
656 // the sleep.
657 k.suspend(Some(started.timer))
658 .expect("park the timer daemon");
659 k.delay(DELAY).expect("the worker delays");
660
661 let before = k.tick_count();
662 k.idle_suppress_ticks();
663
664 assert_eq!(k.port().sleeps.get(), 0, "the port was asked");
665 assert_eq!(k.tick_count(), before, "the clock moved");
666 }
667
668 /// A port that oversleeps is a port bug, and the kernel refuses to wind
669 /// the clock past the wake it would lose. The C `configASSERT`s this;
670 /// a kernel that forbids panicking has to clamp instead.
671 #[test]
672 fn the_kernel_clamps_a_port_that_oversleeps() {
673 let mut k = sleepy::Kernel::<OversleepingPort, NoTrace, NoTickHook>::new(
674 OversleepingPort::default(),
675 NoTrace,
676 )
677 .expect("the declared geometry adds up");
678 k.create_task("worker", 1).expect("worker");
679 let started = k.start_scheduler().expect("start");
680 // The timer daemon is created READY at `TIMER_TASK_PRIORITY`, and
681 // in a running system it blocks on its command queue immediately.
682 // Nothing runs it here, so park it: a task ready above the idle
683 // priority is precisely what `expected_idle_time` refuses to sleep
684 // through, and leaving it ready would test that refusal instead of
685 // the sleep.
686 k.suspend(Some(started.timer))
687 .expect("park the timer daemon");
688 k.delay(DELAY).expect("the worker delays");
689
690 let before = k.tick_count();
691 k.idle_suppress_ticks();
692
693 // The port claimed `4 * DELAY + 9` = 49 ticks. Unclamped the clock
694 // would be 49 ticks on and the worker's wake would have been stepped
695 // straight past; clamped it lands on the wake exactly, like a port
696 // that behaved.
697 assert_eq!(
698 k.tick_count(),
699 before.saturating_add(DELAY),
700 "a port claiming four times its window moved the clock past the wake"
701 );
702 }
703
704 /// ★ The claim the whole mission rests on.
705 ///
706 /// Two kernels, identical but for `configUSE_TICKLESS_IDLE`, run the
707 /// same script. One sleeps through the idle window; the other ticks
708 /// through it. Their traces differ — that is the point, and it is why a
709 /// byte-diff cannot gate a tickless port. Their SCHEDULES do not.
710 ///
711 /// `Scheduling` is the projection that says so, and this is it applied
712 /// to a kernel that really did suppress its ticks rather than to a trace
713 /// file standing in for one.
714 #[test]
715 fn the_schedule_is_the_same_with_and_without_tickless() {
716 let target = DELAY.saturating_add(2);
717
718 let mut asleep = sleepy_kernel();
719 asleep.create_task("worker", 1).expect("worker");
720 let started = asleep.start_scheduler().expect("start");
721 asleep
722 .suspend(Some(started.timer))
723 .expect("park the timer daemon");
724 asleep.delay(DELAY).expect("the worker delays");
725 asleep.idle_suppress_ticks();
726 while asleep.tick_count() < target {
727 if asleep.increment_tick() {
728 asleep.switch_context();
729 }
730 }
731
732 let mut ticking = awake::Kernel::<TestPort, Scheduling<Recorder>, NoTickHook>::new(
733 TestPort::default(),
734 Scheduling::new(Recorder::default()),
735 )
736 .expect("the declared geometry adds up");
737 ticking.create_task("worker", 1).expect("worker");
738 let started = ticking.start_scheduler().expect("start");
739 ticking
740 .suspend(Some(started.timer))
741 .expect("park the timer daemon");
742 ticking.delay(DELAY).expect("the worker delays");
743 ticking.idle_suppress_ticks();
744 while ticking.tick_count() < target {
745 if ticking.increment_tick() {
746 ticking.switch_context();
747 }
748 }
749
750 assert!(
751 asleep.port().sleeps.get() > 0,
752 "the sleeping arm never slept, so this proves nothing"
753 );
754
755 let slept_schedule = asleep.into_trace().into_inner();
756 let ticked_schedule = ticking.into_trace().into_inner();
757
758 assert_eq!(
759 slept_schedule, ticked_schedule,
760 "sleeping through the idle window moved the schedule"
761 );
762 }
763
764 // ---- a delayed list deeper than the conformance corpus ever builds ---
765
766 // `System` here is never built: the tasks are created directly so the
767 // declared queue slot stays free for `xTimerCreateTimerTask`. The
768 // declaration is still what sizes the kernel.
769 crate::system! {
770 mod deep use TestConfig;
771 tasks {
772 d0: 1, d1: 1, d2: 1, d3: 1, d4: 1,
773 d5: 1, d6: 1, d7: 1, d8: 1, d9: 1
774 }
775 queues { unused: u8; 1 }
776 }
777
778 /// Ten tasks blocked at once, waking in wake-time order.
779 ///
780 /// **This exists because the conformance gate cannot reach here.** That
781 /// gate is the strongest evidence in the project -- 19 scenarios, every
782 /// scheduling decision compared line-for-line against the instrumented C
783 /// kernel -- and its delayed list never gets deeper than FOUR. Measured,
784 /// by replaying each scenario's own trace and tracking membership:
785 ///
786 /// ```text
787 /// BlockQ 4 death 4 dynamic 3 PollQ 3 semtest 3 recmutex 3
788 /// blocktim 3 IntSemTest 3 TimerDemo 3 QPeek 2 GenQTest 2
789 /// MessageBufferAMP 2 countsem 1 QueueOverwrite 1
790 /// QueueSetPolling 1 StreamBufferInterrupt 1 EventGroupsDemo 1
791 /// ```
792 ///
793 /// `vListInsert` is the only operation in the kernel whose cost is its
794 /// depth, and the corpus never tests it past n=4. Anything that goes
795 /// wrong only when the list is deep -- an ordering bug, an off-by-one in
796 /// the walk, a fast path that appends where it should splice -- passes
797 /// that gate green.
798 ///
799 /// The delays are deliberately NOT monotonic: a shortcut that appends
800 /// unconditionally orders them wrongly, and ascending delays would let
801 /// it through. They are distinct, because two tasks sharing a wake time
802 /// wake on the same tick and this probe cannot see which left first.
803 #[test]
804 #[allow(clippy::indexing_slicing)]
805 fn ten_blocked_tasks_wake_in_wake_time_order() {
806 let mut k =
807 deep::Kernel::<TestPort, NoTrace, NoTickHook>::new(TestPort::default(), NoTrace)
808 .expect("the declared geometry adds up");
809 // Created directly rather than through `System::build`. Build would
810 // also create the declared queue, and that slot is the one
811 // `xTimerCreateTimerTask` needs at startup -- the declaration is
812 // here to SIZE the kernel, not to furnish it.
813 let names = ["d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9"];
814 let mut all = [::rusty_rtos_core::handle::TaskHandle::from_raw(0); 10];
815 for (slot, name) in all.iter_mut().zip(names) {
816 *slot = k.create_task(name, 1).expect("task");
817 }
818 let started = k.start_scheduler().expect("start");
819 // Park the timer daemon. It sits at TIMER_TASK_PRIORITY, above these
820 // tasks, so leaving it ready means it is the one that runs and the
821 // ten never get a turn. The tickless tests park it for the same
822 // reason.
823 k.suspend(Some(started.timer)).expect("park the daemon");
824
825 // Out of order on purpose: a shortcut that appends unconditionally
826 // gets these wrong, and ascending delays would let it through.
827 //
828 // DISTINCT, though. Two tasks with the same wake time wake on the
829 // same TICK, and `task_state_get` cannot say which of them left the
830 // delayed list first -- the probe below would record them in index
831 // order whatever the list did. The tie rule is real and it is tested
832 // where it is observable, directly on the list, in
833 // `list::tests::a_value_equal_to_the_tail_goes_after_it`.
834 let delays = [9u64, 3, 14, 7, 1, 11, 5, 8, 2, 13];
835
836 // Block each in turn. `delay` acts on whichever task is RUNNING, so
837 // the schedule picks the order and this records what it picked --
838 // asserting the kernel's own choice rather than assuming one.
839 let mut blocked = [(0u64, 0usize); 10];
840 let mut n = 0usize;
841 for _ in 0..200u32 {
842 if n == all.len() {
843 break;
844 }
845 let running = k.current();
846 if let Some(which) = all.iter().position(|t| *t == running) {
847 if !blocked[..n].iter().any(|(_, w)| *w == which) {
848 k.delay(delays[which]).expect("blocks");
849 blocked[n] = (delays[which], which);
850 n = n.saturating_add(1);
851 }
852 }
853 k.switch_context();
854 }
855 assert_eq!(n, all.len(), "every task should have blocked");
856
857 for (i, task) in all.iter().enumerate() {
858 assert_eq!(
859 k.task_state_get(*task).expect("state"),
860 crate::kernel::TaskState::Blocked,
861 "task {i} should be blocked; all ten are, at once, which is more than twice as deep as any conformance scenario reaches"
862 );
863 }
864
865 // Tick forward and record the order they come back.
866 let mut woke = [0usize; 10];
867 let mut w = 0usize;
868 let mut asleep = [true; 10];
869 for _ in 0..40u32 {
870 k.tick_from_isr();
871 for (i, task) in all.iter().enumerate() {
872 if asleep[i]
873 && k.task_state_get(*task).expect("state") != crate::kernel::TaskState::Blocked
874 {
875 asleep[i] = false;
876 woke[w] = i;
877 w = w.saturating_add(1);
878 }
879 }
880 }
881 assert_eq!(w, all.len(), "every task should have woken");
882
883 // Ascending wake time; ties in the order they blocked. That is what
884 // `vListInsert` promises and the only order the list guarantees.
885 let mut want = blocked;
886 want.sort_by_key(|(ticks, _)| *ticks);
887 let want = want.map(|(_, which)| which);
888 assert_eq!(
889 woke, want,
890 "the delayed list did not wake in wake-time order"
891 );
892 }
893
894 /// Creating a task at a HIGHER priority than the running one must ask
895 /// for a switch; creating one LOWER must not.
896 ///
897 /// **This closes a gap the ledger measured and left open.** `cargo
898 /// mutants` over `kernel.rs`, judged by the conformance corpus, left six
899 /// survivors, and five were this one line in `prvAddNewTaskToReadyList`:
900 ///
901 /// ```text
902 /// if self.running && C::USE_PREEMPTION && self.current_priority() < priority
903 /// ```
904 ///
905 /// `death` was added so the corpus would create tasks after the
906 /// scheduler had started, and it narrowed six survivors to four. It
907 /// could not do better, for a reason visible in its own source:
908 /// `vCreateTasks` creates both suicidal tasks at `uxTaskPriorityGet(
909 /// NULL )` -- its OWN priority -- so the new task never outranks the
910 /// running one. The guard is reached and evaluated on every create and
911 /// is never TRUE. Mutations that make it fire spuriously die at once;
912 /// mutations that suppress a yield which never happens are invisible.
913 /// Reachable is not killed.
914 ///
915 /// No corpus scenario creates a higher-priority task while running, and
916 /// none can be added without a C original to diff against. A unit test
917 /// can do it, and this is it. The four survivors:
918 ///
919 /// | mutation | caught by |
920 /// |---|---|
921 /// | condition → `false` | the HIGHER half |
922 /// | body removed (no yield) | the HIGHER half |
923 /// | `<` → `>` | the HIGHER half |
924 /// | `<` → `!=` | the LOWER half |
925 ///
926 /// Which is why both halves are here. The lower half looks like a
927 /// formality and is the only thing that kills `!=`.
928 #[test]
929 fn creating_a_higher_priority_task_asks_for_a_switch_and_a_lower_one_does_not() {
930 let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
931 .expect("the declared geometry adds up");
932 let mid = k.create_task("mid", 2).expect("task mid");
933 k.start_scheduler().expect("start");
934 assert_eq!(k.current(), mid, "the only app task runs");
935
936 // ---- LOWER: no switch is owed -----------------------------------
937 let before = k.port().yields.get();
938 let _low = k.create_task("low", 1).expect("task low");
939 assert_eq!(
940 k.port().yields.get(),
941 before,
942 "a task created BELOW the running priority cannot preempt it, so the kernel must not ask for a switch"
943 );
944
945 // ---- HIGHER: a switch is owed -----------------------------------
946 let before = k.port().yields.get();
947 let _high = k.create_task("high", 3).expect("task high");
948 assert!(
949 k.port().yields.get() > before,
950 "a task created ABOVE the running priority preempts it, and the kernel must ask for the switch"
951 );
952 }
953
954 /// A kernel with room for a stream buffer, which `system!` never gives
955 /// one: the macro sizes `BUFFERS` and `BYTES` at zero.
956 type BufferKernel = crate::Kernel<
957 TestConfig,
958 TestPort,
959 NoTrace,
960 NoTickHook,
961 4,
962 { crate::list_slots_for(4, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
963 { crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
964 1,
965 1,
966 2,
967 64,
968 0,
969 0,
970 { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
971 >;
972
973 /// `xStreamBufferSetTriggerLevel`'s contract, pinned.
974 ///
975 /// The C coerces a zero trigger to one BEFORE bounds-checking:
976 ///
977 /// ```c
978 /// if( xTriggerLevel == ( size_t ) 0 ) { xTriggerLevel = 1; }
979 /// if( xTriggerLevel < pxStreamBuffer->xLength ) { ...pdPASS }
980 /// else { xReturn = pdFALSE; }
981 /// ```
982 ///
983 /// This kernel had the two the other way round. The orders disagree on
984 /// exactly one input -- a zero trigger against a length of ONE -- and
985 /// that input cannot be built: `length` is `size + 1` (the spare byte a
986 /// ring buffer needs to tell full from empty) and `size == 0` is refused
987 /// at creation. So it was an inconsistency with the C, not a live bug,
988 /// and the order has been matched anyway rather than left resting on an
989 /// arithmetic detail in another function.
990 ///
991 /// What this test pins is the contract at the lengths that exist. There
992 /// is no conformance scenario for this API and no C demo in the vendored
993 /// tree that calls it, so a differential is not available --
994 /// `docs/HOLES.md` H2 -- and this is the only evidence there is.
995 #[test]
996 fn the_trigger_level_contract() {
997 let mut k =
998 BufferKernel::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
999
1000 // `create(1, 1)` is a length of TWO: one byte of payload and the
1001 // spare. The smallest buffer a caller can actually make.
1002 let small = k.stream_buffer_create(1, 1).expect("a one-byte buffer");
1003 assert_eq!(
1004 k.stream_buffer_set_trigger_level(small, 0),
1005 Ok(true),
1006 "zero becomes one, and one IS below a length of two"
1007 );
1008 assert_eq!(
1009 k.stream_buffer_set_trigger_level(small, 2),
1010 Ok(false),
1011 "two is not below a length of two"
1012 );
1013
1014 let wide = k.stream_buffer_create(8, 1).expect("an eight-byte buffer");
1015 assert_eq!(k.stream_buffer_set_trigger_level(wide, 0), Ok(true));
1016 assert_eq!(
1017 k.stream_buffer_set_trigger_level(wide, 8),
1018 Ok(true),
1019 "8 < 9"
1020 );
1021 assert_eq!(
1022 k.stream_buffer_set_trigger_level(wide, 9),
1023 Ok(false),
1024 "nine is not below a length of nine"
1025 );
1026 }
1027
1028 fn kernel() -> K {
1029 K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up")
1030 }
1031
1032 /// `configUSE_TIME_SLICING`: two READY tasks of the same priority
1033 /// must take turns.
1034 ///
1035 /// Fixed priority says what happens between DIFFERENT priorities and
1036 /// nothing at all about two tasks at the same one. The C fills that in
1037 /// twice over: `xTaskIncrementTick` asks for a switch whenever more
1038 /// than one task is ready at the running task's priority, and
1039 /// `taskSELECT_HIGHEST_PRIORITY_TASK` then takes the NEXT entry rather
1040 /// than the head.
1041 ///
1042 /// Without it a task that never blocks starves its equal-priority
1043 /// peers completely — not slowly, completely — and the failure looks
1044 /// like somebody else's demo being broken. `rusty_rtos-capi`'s host
1045 /// cell found it that way: two demo files whose tasks sit at the same
1046 /// priority, one of them getting 13.5 million turns and the other
1047 /// ZERO.
1048 #[derive(Debug, Clone, Copy, Default)]
1049 pub struct SliceConfig;
1050
1051 impl Config for SliceConfig {
1052 type Tick = Bits32;
1053 const TICK_RATE_HZ: u32 = 100;
1054 const MAX_PRIORITIES: u8 = 4;
1055 const MINIMAL_STACK_SIZE: usize = 1;
1056 const MAX_TASK_NAME_LEN: usize = 8;
1057 // The daemon sits BELOW the two tasks under test. Nothing drives
1058 // it here, so at its usual priority it would simply be the current
1059 // task for ever and the test would measure the daemon.
1060 const TIMER_TASK_PRIORITY: u8 = 0;
1061 const TIMER_TASK_STACK_DEPTH: usize = 1;
1062 const TIMER_QUEUE_LENGTH: usize = 1;
1063 const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
1064 // The point of this config: the default, stated out loud.
1065 const USE_TIME_SLICING: bool = true;
1066 const USE_PREEMPTION: bool = true;
1067 }
1068
1069 /// Built from the const generics directly rather than through
1070 /// `system!`, because that macro declares its tasks for you and this
1071 /// test needs to create them itself.
1072 type SliceKernel = crate::Kernel<
1073 SliceConfig,
1074 TestPort,
1075 NoTrace,
1076 NoTickHook,
1077 5,
1078 { crate::list_slots_for(5, 1, crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1)) },
1079 { crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1) },
1080 1,
1081 1,
1082 1,
1083 8,
1084 1,
1085 1,
1086 { <SliceConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1087 >;
1088
1089 /// The same declaration driven by a port that COUNTS switch requests,
1090 /// with room for a queue of our own beside the timer daemon's.
1091 ///
1092 /// `QUEUES` is 2 and `SLOTS` 8 for exactly that reason: the timer queue
1093 /// is created by `Kernel::new` and takes the first of each, so a test
1094 /// that makes its own queue needs the second.
1095 type CountingKernel = crate::Kernel<
1096 SliceConfig,
1097 CountingPort,
1098 NoTrace,
1099 NoTickHook,
1100 5,
1101 { crate::list_slots_for(5, 1, crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1)) },
1102 { crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1) },
1103 2,
1104 8,
1105 1,
1106 8,
1107 1,
1108 1,
1109 { <SliceConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1110 >;
1111
1112 /// Tick a kernel whose two equal-priority tasks never block, and count
1113 /// how many ticks each of them was the current task for.
1114 fn turns_over(ticks: u32) -> (u32, u32) {
1115 let mut k =
1116 SliceKernel::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
1117 let a = k.create_task("a", 2).expect("task a");
1118 let b = k.create_task("b", 2).expect("task b");
1119 k.start_scheduler().expect("start");
1120
1121 let (mut for_a, mut for_b) = (0u32, 0u32);
1122 for _ in 0..ticks {
1123 if k.increment_tick() {
1124 k.switch_context();
1125 }
1126 let now = k.current();
1127 if now == a {
1128 for_a = for_a.saturating_add(1);
1129 } else if now == b {
1130 for_b = for_b.saturating_add(1);
1131 }
1132 }
1133 (for_a, for_b)
1134 }
1135
1136 // A third test belongs here and is not written yet: equal-priority
1137 // rotation with a HIGHER-priority task cutting in between selections,
1138 // which is the shape every real system has. Two attempts at it were
1139 // withdrawn because they measured their own call pattern rather than
1140 // the scheduler -- `delay` yields as part of its contract, so a loop
1141 // that calls `delay` and then `switch_context` makes two selections
1142 // and can only sample after the second.
1143 //
1144 // What is known: driven directly, `switch_context` alternates
1145 // correctly between two equal-priority tasks with a third cutting in
1146 // (observed at the list, cursor 0 -> 1 -> 0). What is not known is why
1147 // `rusty_rtos_port/firmware/host-kernel` sees one of a pair get ZERO
1148 // turns in exactly that shape. That cell fails today and is the live
1149 // reproduction; this is the note that says so rather than a test that
1150 // asserts something unproven.
1151
1152 #[test]
1153 fn two_ready_tasks_of_equal_priority_take_turns() {
1154 let (a, b) = turns_over(200);
1155 assert!(a > 0, "task a never ran: {a} vs {b}");
1156 assert!(b > 0, "task b never ran: {a} vs {b}");
1157 }
1158
1159 /// `queueYIELD_IF_USING_PREEMPTION`: a send that readies a
1160 /// HIGHER-priority receiver must ask for a switch.
1161 ///
1162 /// This is the whole of `TimerDemo.c:469`, with no C anywhere near it.
1163 /// That demo stops a timer and asserts on the next line that the timer
1164 /// is inactive, and its own comment says why it may: "this will appear
1165 /// to happen immediately to this task because this task is running at
1166 /// a priority below the timer service task". `xTimerStop` is a send to
1167 /// the daemon's queue, so the assertion is really this test.
1168 ///
1169 /// It has two halves and the second is the one that bites. A send must
1170 /// ask for a switch when it wakes a higher-priority receiver — AND the
1171 /// receiver has to be WAITING ON THE QUEUE for there to be anything to
1172 /// wake. A daemon that polls its queue with a zero block time is
1173 /// parked nowhere, so the send finds no waiter, asks for nothing, and
1174 /// being higher priority buys it precisely nothing. Both halves are
1175 /// asserted below, because the first one passing is what makes the
1176 /// second one's absence invisible.
1177 #[test]
1178 fn a_send_that_wakes_a_higher_priority_receiver_asks_for_a_switch() {
1179 let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
1180 .expect("the declared geometry adds up");
1181 let hi = k.create_task("hi", 2).expect("task hi");
1182 let lo = k.create_task("lo", 1).expect("task lo");
1183 let q = k.queue_create(4).expect("a queue");
1184 k.start_scheduler().expect("start");
1185
1186 // The high-priority task waits ON the queue, which is what makes
1187 // it a waiter rather than merely a ready task of higher priority.
1188 assert_eq!(k.current(), hi, "the higher priority task runs first");
1189 assert!(
1190 matches!(k.queue_receive(q, 100), Ok(crate::queue::Wait::Blocked)),
1191 "an empty queue with a block time must park the receiver"
1192 );
1193 k.switch_context();
1194 assert_eq!(k.current(), lo, "with hi parked, lo runs");
1195
1196 // Now the send, from the LOWER-priority task.
1197 let before = k.port().yields.get();
1198 assert!(matches!(
1199 k.queue_send(q, 7, 0),
1200 Ok(crate::queue::Wait::Ready(()))
1201 ));
1202 let asked = k.port().yields.get().saturating_sub(before);
1203 assert_eq!(
1204 asked, 1,
1205 "a send that readies a higher-priority receiver must ask for a switch"
1206 );
1207 }
1208
1209 /// The other half: a receiver that did NOT wait cannot be woken, so
1210 /// the send asks for nothing — which is correct, and is exactly the
1211 /// trap a polling daemon falls into.
1212 ///
1213 /// Recorded as an assertion rather than a comment because it is the
1214 /// behaviour a reader will otherwise call a bug in the send path,
1215 /// having found the send not yielding. The send is right; the caller
1216 /// that polls instead of waiting is wrong.
1217 #[test]
1218 fn a_send_asks_for_nothing_when_the_higher_priority_task_never_waited() {
1219 let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
1220 .expect("the declared geometry adds up");
1221 let _hi = k.create_task("hi", 2).expect("task hi");
1222 let _lo = k.create_task("lo", 1).expect("task lo");
1223 let q = k.queue_create(4).expect("a queue");
1224 k.start_scheduler().expect("start");
1225
1226 // `hi` polls. A zero block time on an empty queue is `Empty`, NOT
1227 // `Blocked` — and the difference is the whole point: `Blocked`
1228 // means "I have been parked and will be woken", `Empty` means
1229 // "there was nothing there and I was not parked". A poller gets
1230 // the second, so there is nothing for a later send to wake.
1231 assert!(
1232 matches!(
1233 k.queue_receive(q, 0),
1234 Err(rusty_rtos_core::error::Error::Empty)
1235 ),
1236 "a zero-wait receive on an empty queue reports Empty, not Blocked"
1237 );
1238 k.switch_context();
1239
1240 let before = k.port().yields.get();
1241 assert!(matches!(
1242 k.queue_send(q, 7, 0),
1243 Ok(crate::queue::Wait::Ready(()))
1244 ));
1245 assert_eq!(
1246 k.port().yields.get(),
1247 before,
1248 "there was no waiter to wake, so nothing should have been asked for"
1249 );
1250 }
1251
1252 #[test]
1253 fn neither_equal_priority_task_starves_the_other() {
1254 let (a, b) = turns_over(200);
1255 // A round robin gives them one tick each in turn. Allowing a 4x
1256 // imbalance is generous; a scheduler that never rotates gives one
1257 // of them zero, which is what this is here to catch.
1258 let (lo, hi) = (a.min(b), a.max(b));
1259 assert!(
1260 lo.saturating_mul(4) >= hi,
1261 "one starved the other: {a} against {b}"
1262 );
1263 }
1264
1265 /// **The geometry is the declaration**, arithmetic and all.
1266 ///
1267 /// This is the `.bss` claim as a number rather than a hope: every
1268 /// const is exactly what the two `tasks` and two `queues` lines say,
1269 /// with no spare anywhere.
1270 #[test]
1271 fn the_geometry_is_derived_from_the_declaration() {
1272 assert_eq!(demo::APP_TASKS, 2, "the two declared tasks");
1273 assert_eq!(demo::TASKS, 4, "plus the idle task and the timer daemon");
1274 assert_eq!(demo::QUEUES, 2, "the two declared queues");
1275 assert_eq!(demo::SLOTS, 13, "10 + 3, the declared lengths and no spare");
1276 // `ITEMS` is the SLOT count now, not the item count: two list items
1277 // per task (8), plus one end-marker node per list (14), rounded up
1278 // to a power of two. 22 -> 32.
1279 assert_eq!(
1280 demo::ITEMS,
1281 32,
1282 "8 items + 14 markers, rounded to a power of two"
1283 );
1284 assert_eq!(
1285 demo::ITEMS,
1286 crate::list_slots_for(demo::TASKS, demo::TIMERS, demo::LISTS),
1287 "and it is derived, not written by hand"
1288 );
1289 // The slack is the price of the mask, and it is worth being able to
1290 // see: this configuration carries 10 spare nodes.
1291 assert_eq!(
1292 demo::ITEMS - demo::LISTS,
1293 18,
1294 "item capacity: 8 needed, 18 available"
1295 );
1296 assert_eq!(
1297 demo::LISTS,
1298 crate::lists_for(TestConfig::MAX_PRIORITIES, 2, 0),
1299 "a ready list per priority, the fixed six, and two per queue"
1300 );
1301 }
1302
1303 /// A declared system builds, and `Kernel::new` accepts the geometry —
1304 /// which is the check that `items_for`/`lists_for` were applied to the
1305 /// same numbers the struct was built from.
1306 #[test]
1307 fn a_declared_system_builds_and_the_kernel_accepts_its_geometry() {
1308 let mut k = kernel();
1309 let system = demo::System::build(&mut k).expect("nothing here can fail");
1310 // The handles are the kernel's, in declaration order.
1311 assert!(!system.consumer.is_null());
1312 assert!(!system.producer.is_null());
1313 assert_ne!(system.consumer, system.producer);
1314 assert_eq!(k.task_count(), 2, "no task the declaration did not name");
1315 }
1316
1317 /// The queues come back typed, and carry what they were declared to.
1318 #[test]
1319 fn the_declared_queues_move_their_own_type() {
1320 let mut k = kernel();
1321 let mut system = demo::System::build(&mut k).expect("nothing here can fail");
1322 assert!(matches!(system.data.send(&mut k, 4_242u16, 0), Sent::Ok));
1323 assert!(matches!(system.marks.send(&mut k, 7u8, 0), Sent::Ok));
1324 assert_eq!(system.data.len(&mut k), Ok(1));
1325 assert_eq!(system.marks.len(&mut k), Ok(1));
1326 }
1327
1328 /// **The `.bss` claim, as a number.**
1329 ///
1330 /// The alternative to declaring is what every scenario in this repo
1331 /// does today: pick a geometry by hand that covers the biggest thing
1332 /// you might do. The demo's kernel is sized `TASKS = 24`,
1333 /// `QUEUES = 12`, `SLOTS = 128`, `TIMERS = 32` because it has to hold
1334 /// eighteen scenarios at once. A system that declares two tasks and
1335 /// thirteen slots gets a kernel sized for two tasks and thirteen
1336 /// slots, and the difference is not small.
1337 ///
1338 /// This is a counter, not a benchmark: `size_of` is exact, decided at
1339 /// compile time, and identical on every machine.
1340 #[test]
1341 fn a_declared_kernel_is_sized_for_what_was_declared() {
1342 /// The demo's hand-picked geometry, which is what you use when
1343 /// you cannot declare.
1344 type Blanket = crate::Kernel<
1345 TestConfig,
1346 TestPort,
1347 NoTrace,
1348 NoTickHook,
1349 24,
1350 { crate::list_slots_for(24, 32, crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4)) },
1351 { crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4) },
1352 12,
1353 128,
1354 8,
1355 2048,
1356 32,
1357 4,
1358 { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1359 >;
1360
1361 let declared = core::mem::size_of::<K>();
1362 let blanket = core::mem::size_of::<Blanket>();
1363 // Printed so the footprint row can be read off a test run.
1364 let ratio = blanket as f64 / declared as f64;
1365 std::eprintln!("declared {declared} bytes, hand-sized {blanket} bytes, {ratio:.1}x");
1366 assert!(
1367 declared < blanket,
1368 "a declared kernel ({declared}) should be smaller than one sized for everything ({blanket})"
1369 );
1370 // The declaration is the only input: change the declaration and
1371 // this number changes with it, which is the whole claim.
1372 assert_eq!(
1373 declared,
1374 core::mem::size_of::<demo::Kernel<TestPort, NoTrace, NoTickHook>>()
1375 );
1376 }
1377
1378 /// **The slot count is exact, and the exactness is load-bearing.**
1379 ///
1380 /// `SLOTS` is the sum of the declared lengths, so filling every
1381 /// declared queue to its declared length uses the arena to the last
1382 /// slot and no further. A geometry that was rounded up would pass a
1383 /// weaker version of this; this one would fail if `SLOTS` were 12.
1384 #[test]
1385 fn every_declared_slot_is_usable_and_there_is_not_one_spare() {
1386 let mut k = kernel();
1387 let mut system = demo::System::build(&mut k).expect("nothing here can fail");
1388 for i in 0..10u16 {
1389 assert!(
1390 matches!(system.data.send(&mut k, i, 0), Sent::Ok),
1391 "slot {i} of the declared ten"
1392 );
1393 }
1394 for i in 0..3u8 {
1395 assert!(
1396 matches!(system.marks.send(&mut k, i, 0), Sent::Ok),
1397 "slot {i} of the declared three"
1398 );
1399 }
1400 // Both are now exactly full, which is `SLOTS` exactly consumed.
1401 assert!(matches!(system.data.send(&mut k, 99, 0), Sent::Full(99)));
1402 assert!(matches!(system.marks.send(&mut k, 9, 0), Sent::Full(9)));
1403 assert_eq!(demo::SLOTS, 13);
1404 }
1405}