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