Skip to main content

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            /// Two list items per task plus one per timer, exactly the
234            /// `ListItem_t`s a C `TCB_t` carries.
235            pub const ITEMS: usize = $crate::items_for(TASKS, TIMERS);
236            /// A ready list per priority, the fixed six, two per queue and
237            /// one per event group.
238            pub const LISTS: usize = $crate::lists_for(
239                <$cfg as ::rusty_rtos_core::config::Config>::MAX_PRIORITIES,
240                QUEUES,
241                GROUPS,
242            );
243
244            // A declared priority the config has no ready list for is a
245            // compile error, not a create that answers `Err` at startup on
246            // the bench. This is the one create-failure path that is an
247            // application mistake rather than a geometry mistake, so it is
248            // the one worth refusing here.
249            $(
250                const _: () = assert!(
251                    ($prio as u8) < <$cfg as ::rusty_rtos_core::config::Config>::MAX_PRIORITIES,
252                    concat!(
253                        "task `", stringify!($task),
254                        "` declares a priority its Config has no ready list for"
255                    ),
256                );
257            )*
258
259            /// This system's kernel: the geometry above, and nothing to
260            /// choose. `P`, `T` and `H` are still the port, the trace sink
261            /// and the tick hook, which are the platform's business.
262            pub type Kernel<P, T, H> = $crate::Kernel<
263                $cfg, P, T, H,
264                TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS,
265            >;
266
267            /// The declared system: every task and every queue, by name.
268            ///
269            /// Built once, by [`System::build`]. After that an application
270            /// holds this and never a handle it could have invented.
271            #[derive(Debug)]
272            pub struct System {
273                $(
274                    /// A declared task.
275                    pub $task: ::rusty_rtos_core::handle::TaskHandle,
276                )*
277                $(
278                    /// A declared queue, typed and length-checked.
279                    pub $queue: $crate::typed::Queue<$qty, { $qlen }>,
280                )*
281            }
282
283            impl System {
284                /// Create everything the declaration names, in the order it
285                /// names it.
286                ///
287                /// # Errors
288                /// None an application can reach: see the module docs for
289                /// why each create-failure path is closed by construction.
290                /// The `Result` is here because this crate may not panic,
291                /// not because there is a case to handle.
292                pub fn build<P, T, H>(kernel: &mut Kernel<P, T, H>) -> ::rusty_rtos_core::error::Result<Self>
293                where
294                    P: ::rusty_rtos_core::port::Port,
295                    T: ::rusty_rtos_core::trace::Trace,
296                    H: $crate::TickHook<Kernel<P, T, H>>,
297                {
298                    $(
299                        let $queue = $crate::typed::Queue::<$qty, { $qlen }>::create(kernel)?;
300                    )*
301                    $(
302                        let $task = kernel.create_task(stringify!($task), $prio)?;
303                    )*
304                    Ok(Self { $($task,)* $($queue,)* })
305                }
306            }
307        }
308    };
309}
310
311#[cfg(test)]
312#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
313mod tests {
314    use rusty_rtos_core::config::Config;
315    use rusty_rtos_core::hooks::NoTickHook;
316    use rusty_rtos_core::isr::Woken;
317    use rusty_rtos_core::port::Port;
318    use rusty_rtos_core::tick::Bits32;
319    use rusty_rtos_core::trace::{Event, Trace};
320
321    use crate::typed::Sent;
322
323    /// Four priorities, so a declaration can get one wrong.
324    #[derive(Debug, Clone, Copy, Default)]
325    pub struct TestConfig;
326
327    impl Config for TestConfig {
328        type Tick = Bits32;
329        const TICK_RATE_HZ: u32 = 100;
330        const MAX_PRIORITIES: u8 = 4;
331        const MINIMAL_STACK_SIZE: usize = 1;
332        const MAX_TASK_NAME_LEN: usize = 8;
333        const TIMER_TASK_PRIORITY: u8 = 3;
334        const TIMER_TASK_STACK_DEPTH: usize = 1;
335        const TIMER_QUEUE_LENGTH: usize = 1;
336        const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
337        const USE_TIME_SLICING: bool = false;
338    }
339
340    #[derive(Debug, Default)]
341    pub struct TestPort {
342        nesting: core::cell::Cell<u32>,
343    }
344
345    impl Port for TestPort {
346        fn yield_now(&self) {}
347        fn yield_from_isr(&self, _woken: Woken) {}
348        fn enter_critical(&self) {
349            self.nesting.set(self.nesting.get().saturating_add(1));
350        }
351        fn exit_critical(&self) {
352            self.nesting.set(self.nesting.get().saturating_sub(1));
353        }
354        fn set_interrupt_mask_from_isr(&self) -> u32 {
355            0
356        }
357        fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
358        fn in_isr(&self) -> bool {
359            false
360        }
361        fn set_in_tick_entry(&self, _yes: bool) {}
362    }
363
364    /// A [`TestPort`] that COUNTS the switches it was asked for.
365    ///
366    /// `TestPort::yield_now` is empty, which is right for tests about what
367    /// the kernel computes and useless for a test about whether it asked
368    /// for a switch at all. Those are different questions and the second
369    /// one has no other instrument.
370    #[derive(Debug, Default)]
371    pub struct CountingPort {
372        nesting: core::cell::Cell<u32>,
373        yields: core::cell::Cell<u32>,
374    }
375
376    impl Port for CountingPort {
377        /// Count the kernel ASKING for a switch, not one style of taking it.
378        ///
379        /// The first version of this counted `yield_now`, and measured the
380        /// wrong thing: `Port::COMMITS_SWITCH` defaults to `false`, so
381        /// `port_yield` calls `switch_context` itself and never reaches
382        /// `yield_now` at all. The test read zero and looked like a kernel
383        /// defect. `count_yield` is on the unconditional path, so it
384        /// answers "did the kernel decide a switch was needed" whichever
385        /// way the port takes it — which is the question.
386        fn count_yield(&self) {
387            self.yields.set(self.yields.get().saturating_add(1));
388        }
389        fn yield_now(&self) {}
390        fn yield_from_isr(&self, _woken: Woken) {}
391        fn enter_critical(&self) {
392            self.nesting.set(self.nesting.get().saturating_add(1));
393        }
394        fn exit_critical(&self) {
395            self.nesting.set(self.nesting.get().saturating_sub(1));
396        }
397        fn set_interrupt_mask_from_isr(&self) -> u32 {
398            0
399        }
400        fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
401        fn in_isr(&self) -> bool {
402            false
403        }
404        fn set_in_tick_entry(&self, _yes: bool) {}
405    }
406
407    #[derive(Debug, Default)]
408    pub struct NoTrace;
409
410    impl Trace for NoTrace {
411        fn event(&mut self, _tick: u64, _event: Event<'_>) {}
412    }
413
414    // The declaration under test: two tasks and two queues of different
415    // types and different lengths, so nothing about the geometry can come
416    // out right by symmetry.
417    crate::system! {
418        mod demo use TestConfig;
419        tasks { consumer: 2, producer: 1 }
420        queues { data: u16; 10, marks: u8; 3 }
421    }
422
423    type K = demo::Kernel<TestPort, NoTrace, NoTickHook>;
424
425    fn kernel() -> K {
426        K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up")
427    }
428
429    /// `configUSE_TIME_SLICING`: two READY tasks of the same priority
430    /// must take turns.
431    ///
432    /// Fixed priority says what happens between DIFFERENT priorities and
433    /// nothing at all about two tasks at the same one. The C fills that in
434    /// twice over: `xTaskIncrementTick` asks for a switch whenever more
435    /// than one task is ready at the running task's priority, and
436    /// `taskSELECT_HIGHEST_PRIORITY_TASK` then takes the NEXT entry rather
437    /// than the head.
438    ///
439    /// Without it a task that never blocks starves its equal-priority
440    /// peers completely — not slowly, completely — and the failure looks
441    /// like somebody else's demo being broken. `rusty_rtos-capi`'s host
442    /// cell found it that way: two demo files whose tasks sit at the same
443    /// priority, one of them getting 13.5 million turns and the other
444    /// ZERO.
445    #[derive(Debug, Clone, Copy, Default)]
446    pub struct SliceConfig;
447
448    impl Config for SliceConfig {
449        type Tick = Bits32;
450        const TICK_RATE_HZ: u32 = 100;
451        const MAX_PRIORITIES: u8 = 4;
452        const MINIMAL_STACK_SIZE: usize = 1;
453        const MAX_TASK_NAME_LEN: usize = 8;
454        // The daemon sits BELOW the two tasks under test. Nothing drives
455        // it here, so at its usual priority it would simply be the current
456        // task for ever and the test would measure the daemon.
457        const TIMER_TASK_PRIORITY: u8 = 0;
458        const TIMER_TASK_STACK_DEPTH: usize = 1;
459        const TIMER_QUEUE_LENGTH: usize = 1;
460        const NOTIFICATION_ARRAY_ENTRIES: usize = 1;
461        // The point of this config: the default, stated out loud.
462        const USE_TIME_SLICING: bool = true;
463        const USE_PREEMPTION: bool = true;
464    }
465
466    /// Built from the const generics directly rather than through
467    /// `system!`, because that macro declares its tasks for you and this
468    /// test needs to create them itself.
469    type SliceKernel = crate::Kernel<
470        SliceConfig,
471        TestPort,
472        NoTrace,
473        NoTickHook,
474        5,
475        { crate::items_for(5, 1) },
476        { crate::lists_for(SliceConfig::MAX_PRIORITIES, 1, 1) },
477        1,
478        1,
479        1,
480        8,
481        1,
482        1,
483    >;
484
485    /// The same declaration driven by a port that COUNTS switch requests,
486    /// with room for a queue of our own beside the timer daemon's.
487    ///
488    /// `QUEUES` is 2 and `SLOTS` 8 for exactly that reason: the timer queue
489    /// is created by `Kernel::new` and takes the first of each, so a test
490    /// that makes its own queue needs the second.
491    type CountingKernel = crate::Kernel<
492        SliceConfig,
493        CountingPort,
494        NoTrace,
495        NoTickHook,
496        5,
497        { crate::items_for(5, 1) },
498        { crate::lists_for(SliceConfig::MAX_PRIORITIES, 2, 1) },
499        2,
500        8,
501        1,
502        8,
503        1,
504        1,
505    >;
506
507    /// Tick a kernel whose two equal-priority tasks never block, and count
508    /// how many ticks each of them was the current task for.
509    fn turns_over(ticks: u32) -> (u32, u32) {
510        let mut k =
511            SliceKernel::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
512        let a = k.create_task("a", 2).expect("task a");
513        let b = k.create_task("b", 2).expect("task b");
514        k.start_scheduler().expect("start");
515
516        let (mut for_a, mut for_b) = (0u32, 0u32);
517        for _ in 0..ticks {
518            if k.increment_tick() {
519                k.switch_context();
520            }
521            let now = k.current();
522            if now == a {
523                for_a = for_a.saturating_add(1);
524            } else if now == b {
525                for_b = for_b.saturating_add(1);
526            }
527        }
528        (for_a, for_b)
529    }
530
531    // A third test belongs here and is not written yet: equal-priority
532    // rotation with a HIGHER-priority task cutting in between selections,
533    // which is the shape every real system has. Two attempts at it were
534    // withdrawn because they measured their own call pattern rather than
535    // the scheduler -- `delay` yields as part of its contract, so a loop
536    // that calls `delay` and then `switch_context` makes two selections
537    // and can only sample after the second.
538    //
539    // What is known: driven directly, `switch_context` alternates
540    // correctly between two equal-priority tasks with a third cutting in
541    // (observed at the list, cursor 0 -> 1 -> 0). What is not known is why
542    // `rusty_rtos_port/firmware/host-kernel` sees one of a pair get ZERO
543    // turns in exactly that shape. That cell fails today and is the live
544    // reproduction; this is the note that says so rather than a test that
545    // asserts something unproven.
546
547    #[test]
548    fn two_ready_tasks_of_equal_priority_take_turns() {
549        let (a, b) = turns_over(200);
550        assert!(a > 0, "task a never ran: {a} vs {b}");
551        assert!(b > 0, "task b never ran: {a} vs {b}");
552    }
553
554    /// `queueYIELD_IF_USING_PREEMPTION`: a send that readies a
555    /// HIGHER-priority receiver must ask for a switch.
556    ///
557    /// This is the whole of `TimerDemo.c:469`, with no C anywhere near it.
558    /// That demo stops a timer and asserts on the next line that the timer
559    /// is inactive, and its own comment says why it may: "this will appear
560    /// to happen immediately to this task because this task is running at
561    /// a priority below the timer service task". `xTimerStop` is a send to
562    /// the daemon's queue, so the assertion is really this test.
563    ///
564    /// It has two halves and the second is the one that bites. A send must
565    /// ask for a switch when it wakes a higher-priority receiver — AND the
566    /// receiver has to be WAITING ON THE QUEUE for there to be anything to
567    /// wake. A daemon that polls its queue with a zero block time is
568    /// parked nowhere, so the send finds no waiter, asks for nothing, and
569    /// being higher priority buys it precisely nothing. Both halves are
570    /// asserted below, because the first one passing is what makes the
571    /// second one's absence invisible.
572    #[test]
573    fn a_send_that_wakes_a_higher_priority_receiver_asks_for_a_switch() {
574        let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
575            .expect("the declared geometry adds up");
576        let hi = k.create_task("hi", 2).expect("task hi");
577        let lo = k.create_task("lo", 1).expect("task lo");
578        let q = k.queue_create(4).expect("a queue");
579        k.start_scheduler().expect("start");
580
581        // The high-priority task waits ON the queue, which is what makes
582        // it a waiter rather than merely a ready task of higher priority.
583        assert_eq!(k.current(), hi, "the higher priority task runs first");
584        assert!(
585            matches!(k.queue_receive(q, 100), Ok(crate::queue::Wait::Blocked)),
586            "an empty queue with a block time must park the receiver"
587        );
588        k.switch_context();
589        assert_eq!(k.current(), lo, "with hi parked, lo runs");
590
591        // Now the send, from the LOWER-priority task.
592        let before = k.port().yields.get();
593        assert!(matches!(
594            k.queue_send(q, 7, 0),
595            Ok(crate::queue::Wait::Ready(()))
596        ));
597        let asked = k.port().yields.get().saturating_sub(before);
598        assert_eq!(
599            asked, 1,
600            "a send that readies a higher-priority receiver must ask for a switch"
601        );
602    }
603
604    /// The other half: a receiver that did NOT wait cannot be woken, so
605    /// the send asks for nothing — which is correct, and is exactly the
606    /// trap a polling daemon falls into.
607    ///
608    /// Recorded as an assertion rather than a comment because it is the
609    /// behaviour a reader will otherwise call a bug in the send path,
610    /// having found the send not yielding. The send is right; the caller
611    /// that polls instead of waiting is wrong.
612    #[test]
613    fn a_send_asks_for_nothing_when_the_higher_priority_task_never_waited() {
614        let mut k = CountingKernel::new(CountingPort::default(), NoTrace)
615            .expect("the declared geometry adds up");
616        let _hi = k.create_task("hi", 2).expect("task hi");
617        let _lo = k.create_task("lo", 1).expect("task lo");
618        let q = k.queue_create(4).expect("a queue");
619        k.start_scheduler().expect("start");
620
621        // `hi` polls. A zero block time on an empty queue is `Empty`, NOT
622        // `Blocked` — and the difference is the whole point: `Blocked`
623        // means "I have been parked and will be woken", `Empty` means
624        // "there was nothing there and I was not parked". A poller gets
625        // the second, so there is nothing for a later send to wake.
626        assert!(
627            matches!(
628                k.queue_receive(q, 0),
629                Err(rusty_rtos_core::error::Error::Empty)
630            ),
631            "a zero-wait receive on an empty queue reports Empty, not Blocked"
632        );
633        k.switch_context();
634
635        let before = k.port().yields.get();
636        assert!(matches!(
637            k.queue_send(q, 7, 0),
638            Ok(crate::queue::Wait::Ready(()))
639        ));
640        assert_eq!(
641            k.port().yields.get(),
642            before,
643            "there was no waiter to wake, so nothing should have been asked for"
644        );
645    }
646
647    #[test]
648    fn neither_equal_priority_task_starves_the_other() {
649        let (a, b) = turns_over(200);
650        // A round robin gives them one tick each in turn. Allowing a 4x
651        // imbalance is generous; a scheduler that never rotates gives one
652        // of them zero, which is what this is here to catch.
653        let (lo, hi) = (a.min(b), a.max(b));
654        assert!(
655            lo.saturating_mul(4) >= hi,
656            "one starved the other: {a} against {b}"
657        );
658    }
659
660    /// **The geometry is the declaration**, arithmetic and all.
661    ///
662    /// This is the `.bss` claim as a number rather than a hope: every
663    /// const is exactly what the two `tasks` and two `queues` lines say,
664    /// with no spare anywhere.
665    #[test]
666    fn the_geometry_is_derived_from_the_declaration() {
667        assert_eq!(demo::APP_TASKS, 2, "the two declared tasks");
668        assert_eq!(demo::TASKS, 4, "plus the idle task and the timer daemon");
669        assert_eq!(demo::QUEUES, 2, "the two declared queues");
670        assert_eq!(demo::SLOTS, 13, "10 + 3, the declared lengths and no spare");
671        assert_eq!(demo::ITEMS, 8, "two list items per task, no timers");
672        assert_eq!(
673            demo::LISTS,
674            crate::lists_for(TestConfig::MAX_PRIORITIES, 2, 0),
675            "a ready list per priority, the fixed six, and two per queue"
676        );
677    }
678
679    /// A declared system builds, and `Kernel::new` accepts the geometry —
680    /// which is the check that `items_for`/`lists_for` were applied to the
681    /// same numbers the struct was built from.
682    #[test]
683    fn a_declared_system_builds_and_the_kernel_accepts_its_geometry() {
684        let mut k = kernel();
685        let system = demo::System::build(&mut k).expect("nothing here can fail");
686        // The handles are the kernel's, in declaration order.
687        assert!(!system.consumer.is_null());
688        assert!(!system.producer.is_null());
689        assert_ne!(system.consumer, system.producer);
690        assert_eq!(k.task_count(), 2, "no task the declaration did not name");
691    }
692
693    /// The queues come back typed, and carry what they were declared to.
694    #[test]
695    fn the_declared_queues_move_their_own_type() {
696        let mut k = kernel();
697        let mut system = demo::System::build(&mut k).expect("nothing here can fail");
698        assert!(matches!(system.data.send(&mut k, 4_242u16, 0), Sent::Ok));
699        assert!(matches!(system.marks.send(&mut k, 7u8, 0), Sent::Ok));
700        assert_eq!(system.data.len(&mut k), Ok(1));
701        assert_eq!(system.marks.len(&mut k), Ok(1));
702    }
703
704    /// **The `.bss` claim, as a number.**
705    ///
706    /// The alternative to declaring is what every scenario in this repo
707    /// does today: pick a geometry by hand that covers the biggest thing
708    /// you might do. The demo's kernel is sized `TASKS = 24`,
709    /// `QUEUES = 12`, `SLOTS = 128`, `TIMERS = 32` because it has to hold
710    /// eighteen scenarios at once. A system that declares two tasks and
711    /// thirteen slots gets a kernel sized for two tasks and thirteen
712    /// slots, and the difference is not small.
713    ///
714    /// This is a counter, not a benchmark: `size_of` is exact, decided at
715    /// compile time, and identical on every machine.
716    #[test]
717    fn a_declared_kernel_is_sized_for_what_was_declared() {
718        /// The demo's hand-picked geometry, which is what you use when
719        /// you cannot declare.
720        type Blanket = crate::Kernel<
721            TestConfig,
722            TestPort,
723            NoTrace,
724            NoTickHook,
725            24,
726            { crate::items_for(24, 32) },
727            { crate::lists_for(TestConfig::MAX_PRIORITIES, 12, 4) },
728            12,
729            128,
730            8,
731            2048,
732            32,
733            4,
734        >;
735
736        let declared = core::mem::size_of::<K>();
737        let blanket = core::mem::size_of::<Blanket>();
738        // Printed so the footprint row can be read off a test run.
739        let ratio = blanket as f64 / declared as f64;
740        std::eprintln!("declared {declared} bytes, hand-sized {blanket} bytes, {ratio:.1}x");
741        assert!(
742            declared < blanket,
743            "a declared kernel ({declared}) should be smaller than one              sized for everything ({blanket})"
744        );
745        // The declaration is the only input: change the declaration and
746        // this number changes with it, which is the whole claim.
747        assert_eq!(
748            declared,
749            core::mem::size_of::<demo::Kernel<TestPort, NoTrace, NoTickHook>>()
750        );
751    }
752
753    /// **The slot count is exact, and the exactness is load-bearing.**
754    ///
755    /// `SLOTS` is the sum of the declared lengths, so filling every
756    /// declared queue to its declared length uses the arena to the last
757    /// slot and no further. A geometry that was rounded up would pass a
758    /// weaker version of this; this one would fail if `SLOTS` were 12.
759    #[test]
760    fn every_declared_slot_is_usable_and_there_is_not_one_spare() {
761        let mut k = kernel();
762        let mut system = demo::System::build(&mut k).expect("nothing here can fail");
763        for i in 0..10u16 {
764            assert!(
765                matches!(system.data.send(&mut k, i, 0), Sent::Ok),
766                "slot {i} of the declared ten"
767            );
768        }
769        for i in 0..3u8 {
770            assert!(
771                matches!(system.marks.send(&mut k, i, 0), Sent::Ok),
772                "slot {i} of the declared three"
773            );
774        }
775        // Both are now exactly full, which is `SLOTS` exactly consumed.
776        assert!(matches!(system.data.send(&mut k, 99, 0), Sent::Full(99)));
777        assert!(matches!(system.marks.send(&mut k, 9, 0), Sent::Full(9)));
778        assert_eq!(demo::SLOTS, 13);
779    }
780}