Skip to main content

rusty_rtos_kernel_core/
timer.rs

1//! `timers.c`: software timers and the daemon task that runs them.
2//!
3//! A software timer is not an interrupt and not a thread. It is an entry on
4//! one of two sorted lists, and a task — the daemon, `Tmr Svc` — that
5//! blocks on a queue until either a command arrives or the head of the list
6//! is due. Everything a caller does to a timer is a *message*: start, stop,
7//! reset, change period, delete. Nothing touches the lists but the daemon.
8//!
9//! That indirection is the whole design, and it is why the trace has a
10//! `TIMER_COMMAND_SEND` line for every call and a `TIMER_EXPIRED` line only
11//! when the daemon gets round to it.
12//!
13//! Two things this kernel spells differently from the C, both because it
14//! has no pointers:
15//!
16//! * the command queue carries an *index* into a ring of commands rather
17//!   than a struct, so the queue keeps the length, the blocking and the
18//!   full behaviour the trace depends on while the payload lives beside it;
19//! * a callback is a small number the application's hook switches on,
20//!   rather than a function pointer. `pvTimerID` rides along with it.
21
22use rusty_rtos_core::config::Config;
23use rusty_rtos_core::error::{Error, Result};
24use rusty_rtos_core::handle::{TaskHandle, TimerHandle};
25use rusty_rtos_core::hooks::TickHook;
26use rusty_rtos_core::isr::Woken;
27use rusty_rtos_core::list::ListId;
28use rusty_rtos_core::port::Port;
29use rusty_rtos_core::trace::{Event, Trace};
30
31use crate::kernel::{Kernel, OwedTrace};
32use crate::name::Name;
33use crate::queue::{Position, Ready, Wait};
34
35/// How many `DaemonTaskMessage_t`s the ring beside the timer queue holds.
36///
37/// The C's queue carries the structs themselves; this one carries indices
38/// into here, so the queue keeps the length, the blocking and the
39/// full behaviour a trace depends on while the payload lives beside it.
40/// [`Config::validate`] refuses a `TIMER_QUEUE_LENGTH` larger than this,
41/// for the same reason it bounds the notification arrays.
42pub const MAX_TIMER_COMMANDS: usize = 32;
43
44/// `tmrSTATUS_IS_ACTIVE`.
45pub(crate) const STATUS_ACTIVE: u8 = 0x01;
46/// `tmrSTATUS_IS_AUTORELOAD`.
47pub(crate) const STATUS_AUTORELOAD: u8 = 0x04;
48
49/// The command ids, exactly as `timers.h` numbers them — the numbering is
50/// load-bearing, because `xTimerGenericCommandFromTask` refuses anything at
51/// or above [`Command::FIRST_FROM_ISR`] and the from-ISR half refuses
52/// anything below it.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Command {
55    /// `tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR`.
56    ExecuteCallbackFromIsr,
57    /// `tmrCOMMAND_EXECUTE_CALLBACK`.
58    ExecuteCallback,
59    /// `tmrCOMMAND_START`.
60    Start,
61    /// `tmrCOMMAND_RESET`.
62    Reset,
63    /// `tmrCOMMAND_STOP`.
64    Stop,
65    /// `tmrCOMMAND_CHANGE_PERIOD`.
66    ChangePeriod,
67    /// `tmrCOMMAND_DELETE`.
68    Delete,
69    /// `tmrCOMMAND_START_FROM_ISR`.
70    StartFromIsr,
71    /// `tmrCOMMAND_RESET_FROM_ISR`.
72    ResetFromIsr,
73    /// `tmrCOMMAND_STOP_FROM_ISR`.
74    StopFromIsr,
75    /// `tmrCOMMAND_CHANGE_PERIOD_FROM_ISR`.
76    ChangePeriodFromIsr,
77}
78
79impl Command {
80    /// `tmrFIRST_FROM_ISR_COMMAND`.
81    pub const FIRST_FROM_ISR: i32 = 6;
82
83    /// The number `timers.h` gives it, which is what the trace prints.
84    #[must_use]
85    pub const fn id(self) -> i32 {
86        match self {
87            Self::ExecuteCallbackFromIsr => -2,
88            Self::ExecuteCallback => -1,
89            Self::Start => 1,
90            Self::Reset => 2,
91            Self::Stop => 3,
92            Self::ChangePeriod => 4,
93            Self::Delete => 5,
94            Self::StartFromIsr => 6,
95            Self::ResetFromIsr => 7,
96            Self::StopFromIsr => 8,
97            Self::ChangePeriodFromIsr => 9,
98        }
99    }
100
101    #[inline]
102    const fn is_from_isr(self) -> bool {
103        self.id() >= Self::FIRST_FROM_ISR
104    }
105
106    const fn is_start_or_reset(self) -> bool {
107        matches!(
108            self,
109            Self::Start | Self::StartFromIsr | Self::Reset | Self::ResetFromIsr
110        )
111    }
112
113    const fn is_stop(self) -> bool {
114        matches!(self, Self::Stop | Self::StopFromIsr)
115    }
116
117    const fn is_change_period(self) -> bool {
118        matches!(self, Self::ChangePeriod | Self::ChangePeriodFromIsr)
119    }
120}
121
122/// One `DaemonTaskMessage_t`, kept beside the queue rather than in it.
123#[derive(Debug, Clone, Copy)]
124pub struct Message {
125    /// Which command this is.
126    pub command: Command,
127    /// `xMessageValue` for a timer command; `ulParameter2` for a pended
128    /// function call.
129    pub(crate) value: u64,
130    /// The timer the command is for, if it is a timer command.
131    pub(crate) timer: TimerHandle,
132    /// `pvParameter1` of a pended function call.
133    pub(crate) param1: u64,
134    /// Which pended function, for the hook to switch on.
135    pub(crate) function: u16,
136}
137
138impl Default for Message {
139    fn default() -> Self {
140        Self {
141            command: Command::Stop,
142            value: 0,
143            timer: TimerHandle::NULL,
144            param1: 0,
145            function: 0,
146        }
147    }
148}
149
150/// A `u64` held as two `u32`s, so it does not force eight-byte alignment.
151///
152/// `Timer` lives in an arena, and an arena slot pays its value's ALIGNMENT as
153/// padding around the generation beside it. `Timer`'s fields sum to 36 bytes,
154/// but two `u64`s aligned the struct to 8 and rounded the slot to 48. Aligned
155/// to 4 it is 40 -- the same as the `Timer_t` the C allocates.
156///
157/// The public API still takes and answers `u64`; only the storage is split.
158#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
159#[cfg(target_pointer_width = "32")]
160pub(crate) struct Split64 {
161    lo: u32,
162    hi: u32,
163}
164
165/// On a 64-bit host a `u64` IS one register, so splitting it is pure cost:
166/// every read pays a shift and an or to put back something the machine was
167/// holding whole. Measured on `bench/sb-ir`, `StreamBufferDemo` **149,452,276
168/// against 139,479,427** -- 7.2 % of the oracle, for a representation that
169/// exists to help a machine the oracle is not.
170///
171/// This is STORAGE, not arithmetic: `new` and `get` are lossless and every
172/// value computed from them is identical on both widths, so the conformance
173/// corpus proves the same behaviour either way. The layout already differs by
174/// pointer width (`usize` is four bytes on the targets and eight here), so
175/// this adds no new axis of divergence.
176#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
177#[cfg(not(target_pointer_width = "32"))]
178pub(crate) struct Split64 {
179    whole: u64,
180}
181
182#[cfg(target_pointer_width = "32")]
183impl Split64 {
184    /// Split a `u64`.
185    pub(crate) const fn new(value: u64) -> Self {
186        Self {
187            lo: (value & 0xFFFF_FFFF) as u32,
188            hi: (value >> 32) as u32,
189        }
190    }
191
192    /// Put it back together.
193    pub(crate) const fn get(self) -> u64 {
194        (self.hi as u64) << 32 | self.lo as u64
195    }
196}
197
198#[cfg(not(target_pointer_width = "32"))]
199impl Split64 {
200    /// Keep it whole.
201    pub(crate) const fn new(value: u64) -> Self {
202        Self { whole: value }
203    }
204
205    /// Hand it back.
206    pub(crate) const fn get(self) -> u64 {
207        self.whole
208    }
209}
210
211/// One software timer: a `Timer_t` without the pointers.
212#[derive(Debug, Clone, Copy, Default)]
213pub struct Timer {
214    pub(crate) name: Name,
215    /// `xTimerPeriodInTicks`.
216    pub(crate) period: Split64,
217    /// `pvTimerID`.
218    pub(crate) id: Split64,
219    /// Which callback the application's hook should run.
220    pub(crate) callback: u16,
221    /// `ucStatus`.
222    pub(crate) status: u8,
223}
224
225impl<
226    C: Config,
227    P: Port,
228    T: Trace,
229    H,
230    const TASKS: usize,
231    const ITEMS: usize,
232    const LISTS: usize,
233    const QUEUES: usize,
234    const SLOTS: usize,
235    const BUFFERS: usize,
236    const BYTES: usize,
237    const TIMERS: usize,
238    const GROUPS: usize,
239    const TIMER_CMDS: usize,
240> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS, TIMER_CMDS>
241where
242    H: TickHook<Self>,
243{
244    /// `pxCurrentTimerList` and `pxOverflowTimerList`, as list ids. They sit
245    /// after the ready lists and the four task lists, before the queues'.
246    pub(crate) fn timer_list(&self) -> ListId {
247        let base = C::MAX_PRIORITIES.saturating_add(4);
248        base.saturating_add(u8::from(self.timers_swapped))
249    }
250
251    pub(crate) fn overflow_timer_list(&self) -> ListId {
252        let base = C::MAX_PRIORITIES.saturating_add(4);
253        base.saturating_add(u8::from(!self.timers_swapped))
254    }
255
256    /// The list item a timer sorts by. Task items come first, then one per
257    /// timer.
258    pub(crate) fn timer_item(timer: TimerHandle) -> u16 {
259        (TASKS.saturating_mul(2) as u16).saturating_add(timer.index() as u16)
260    }
261
262    // ---------------------------------------------------------- creating --
263
264    /// `xTimerCreate`.
265    ///
266    /// `callback` names which of the application's timer callbacks this
267    /// timer runs; `id` is `pvTimerID`.
268    ///
269    /// # Errors
270    /// [`Error::Full`] when the timer arena is full;
271    /// [`Error::InvalidArgument`] for a zero period, which the C asserts on.
272    pub fn timer_create(
273        &mut self,
274        name: &str,
275        period: u64,
276        auto_reload: bool,
277        id: u64,
278        callback: u16,
279    ) -> Result<TimerHandle> {
280        if period == 0 {
281            return Err(Error::InvalidArgument);
282        }
283        // `pvPortMalloc( sizeof( Timer_t ) )` comes first.
284        self.account_for_allocation();
285        let status = if auto_reload { STATUS_AUTORELOAD } else { 0 };
286        let handle = self
287            .timers
288            .try_insert(Timer {
289                // A timer keeps the *pointer* to its name in the C, so it
290                // is never truncated the way a task's is. `Oneshot Timer`
291                // is thirteen characters and `configMAX_TASK_NAME_LEN` is
292                // twelve.
293                name: Name::new(name, crate::NAME_CAPACITY),
294                period: Split64::new(period),
295                id: Split64::new(id),
296                callback,
297                status,
298            })
299            .map_err(|_| Error::Full)?;
300        // `prvInitialiseNewTimer` opens with `prvCheckForValidListAndQueue`.
301        self.check_for_valid_list_and_queue()?;
302        let tick = self.tick;
303        // Gated, as its sibling `trace_command_send` already was: a sink that
304        // never reads a name pays for neither the resolve nor the copy of the
305        // whole `Name`. And the `as_str` is gated TOO, not just the resolve --
306        // turning even a default `Name` into a `&str` calls
307        // `core::str::from_utf8`, which is 534 bytes of validation this
308        // kernel links for no other reason.
309        let name = if T::WANTS_NAMES {
310            self.timers
311                .resolve(handle)
312                .map(|t| t.name)
313                .unwrap_or_default()
314        } else {
315            Name::default()
316        };
317        self.note_exits();
318        self.trace.event(
319            tick,
320            Event::TimerCreate {
321                timer: handle,
322                name: if T::WANTS_NAMES { name.as_str() } else { "" },
323            },
324        );
325        Ok(handle)
326    }
327
328    /// `prvCheckForValidListAndQueue`: make the command queue if no timer
329    /// has made it yet, inside one critical section either way.
330    ///
331    /// The C makes it lazily, on the first `xTimerCreate` — which for
332    /// `TimerDemo` is *before the scheduler starts*, so the queue is the
333    /// first object in the trace and not the third. Everything the create
334    /// does happens inside the outer section, so the whole thing is one
335    /// outermost exit whether or not it built anything.
336    ///
337    /// # Errors
338    /// As [`Kernel::queue_create`].
339    // Out of line at BOTH callers: win 29, -8 B of flash and 2 fewer rv32
340    // instructions, against `andi` +1.
341    //
342    // This said "A3: ONE caller in the linked kernel, so this pays a prologue
343    // and epilogue for a single call" and carried `#[inline(always)]`. The
344    // caller count was wrong -- `timer.rs` and `kernel.rs` both call it -- so
345    // A3 never applied, and at two callers `always` DUPLICATES an 86-byte body
346    // rather than moving it. Found by auditing every inline rationale in the
347    // kernel against the actual census, which is the third wrong or
348    // contradictory inline rationale found on 2026-09-25.
349    #[inline(never)]
350    pub(crate) fn check_for_valid_list_and_queue(&mut self) -> Result<()> {
351        self.enter_critical();
352        let result = if self.timer_queue.is_null() {
353            match self.queue_create(C::TIMER_QUEUE_LENGTH) {
354                Ok(queue) => {
355                    self.timer_queue = queue;
356                    Ok(())
357                }
358                Err(e) => Err(e),
359            }
360        } else {
361            Ok(())
362        };
363        self.exit_critical();
364        result
365    }
366
367    /// `pvTimerGetTimerID`.
368    ///
369    /// # Errors
370    /// [`Error::Gone`] for a stale handle.
371    pub fn timer_id(&mut self, timer: TimerHandle) -> Result<u64> {
372        // The C wraps this in a critical section.
373        self.enter_critical();
374        let id = self.timers.resolve(timer).map(|t| t.id.get());
375        self.exit_critical();
376        id
377    }
378
379    /// `vTimerSetTimerID`.
380    ///
381    /// # Errors
382    /// [`Error::Gone`] for a stale handle.
383    pub fn timer_set_id(&mut self, timer: TimerHandle, id: u64) -> Result<()> {
384        self.enter_critical();
385        let result = self.timers.resolve_mut(timer).map(|t| {
386            t.id = Split64::new(id);
387        });
388        self.exit_critical();
389        result
390    }
391
392    /// `xTimerGetPeriod`.
393    ///
394    /// # Errors
395    /// [`Error::Gone`] for a stale handle.
396    pub fn timer_period(&self, timer: TimerHandle) -> Result<u64> {
397        self.timers.resolve(timer).map(|t| t.period.get())
398    }
399
400    /// `xTimerIsTimerActive`.
401    ///
402    /// # Errors
403    /// [`Error::Gone`] for a stale handle.
404    pub fn timer_is_active(&mut self, timer: TimerHandle) -> Result<bool> {
405        self.enter_critical();
406        let active = self
407            .timers
408            .resolve(timer)
409            .map(|t| (t.status & STATUS_ACTIVE) != 0);
410        self.exit_critical();
411        active
412    }
413
414    /// `xTimerGetExpiryTime`.
415    ///
416    /// # Errors
417    /// [`Error::Gone`] for a stale handle.
418    pub fn timer_expiry_time(&self, timer: TimerHandle) -> Result<u64> {
419        self.timers.resolve(timer)?;
420        self.lists.value(Self::timer_item(timer))
421    }
422
423    /// `xTimerGetReloadMode`.
424    ///
425    /// # Errors
426    /// [`Error::Gone`] for a stale handle.
427    pub fn timer_auto_reload(&mut self, timer: TimerHandle) -> Result<bool> {
428        self.enter_critical();
429        let auto = self
430            .timers
431            .resolve(timer)
432            .map(|t| (t.status & STATUS_AUTORELOAD) != 0);
433        self.exit_critical();
434        auto
435    }
436
437    /// `vTimerSetReloadMode`.
438    ///
439    /// # Errors
440    /// [`Error::Gone`] for a stale handle.
441    pub fn timer_set_auto_reload(&mut self, timer: TimerHandle, auto: bool) -> Result<()> {
442        self.enter_critical();
443        let result = self.timers.resolve_mut(timer).map(|t| {
444            if auto {
445                t.status |= STATUS_AUTORELOAD;
446            } else {
447                t.status &= !STATUS_AUTORELOAD;
448            }
449        });
450        self.exit_critical();
451        result
452    }
453
454    // --------------------------------------------------- sending commands --
455
456    /// `xTimerGenericCommandFromTask`.
457    ///
458    /// # Errors
459    /// [`Error::Gone`] for a stale handle.
460    pub fn timer_command(
461        &mut self,
462        timer: TimerHandle,
463        command: Command,
464        value: u64,
465        ticks: u64,
466    ) -> Result<Wait<bool>> {
467        // The retry of a command that blocked on a full queue sends what its
468        // first pass built. `xTimerStart` and `xTimerReset` read the tick
469        // count ONCE, before the send, and the C carries that sample in the
470        // message through the block; reading the clock again here made the
471        // command time late by however long the task waited, and the timer
472        // expire that much late. The API differential found it with the
473        // daemon below a task (two cores, step 4015: blocked, a tick, then
474        // the retry). The first pass's frame on the command queue is what
475        // says this is a retry.
476        let caller = self.cur();
477        let retry = self.waiting_on(caller, self.timer_queue);
478        let value = if retry { self.held(caller) } else { value };
479        let message = Message {
480            command,
481            value,
482            timer,
483            ..Message::default()
484        };
485        // The C refuses a from-ISR command here and still traces the send.
486        if command.is_from_isr() {
487            self.trace_command_send(timer, command, value);
488            return Ok(Ready(false));
489        }
490        // `if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )` — before
491        // the scheduler runs, a command may not block.
492        let ticks = if self.is_running() { ticks } else { 0 };
493        // `caller` is also who to trace against. The C runs
494        // `traceTIMER_COMMAND_SEND` on the line after `xQueueSendToBack`, so a
495        // send that made the daemon ready switches away first and the line
496        // runs when this task has the CPU back — after the `TASK_SWITCHED_IN`
497        // that returns it.
498        // `traceTIMER_COMMAND_SEND` fires whatever the send returned — and
499        // a full queue is the *point* of TimerDemo's first test, which
500        // starts exactly as many timers as the queue holds and then
501        // requires the next one to fail.
502        match self.post_timer_message(message, ticks) {
503            Ok(Wait::Blocked) => {
504                self.hold(caller, value);
505                Ok(Wait::Blocked)
506            }
507            Ok(Ready(ok)) => {
508                self.trace_command_send_for(caller, timer, command, value);
509                Ok(Ready(ok))
510            }
511            Err(Error::Full) => {
512                self.trace_command_send_for(caller, timer, command, value);
513                Ok(Ready(false))
514            }
515            Err(e) => Err(e),
516        }
517    }
518
519    /// `xTimerStart`.
520    ///
521    /// # Errors
522    /// As [`Kernel::timer_command`].
523    pub fn timer_start(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
524        let now = self.tick;
525        self.timer_command(timer, Command::Start, now, ticks)
526    }
527
528    /// `xTimerStop`.
529    ///
530    /// # Errors
531    /// As [`Kernel::timer_command`].
532    pub fn timer_stop(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
533        self.timer_command(timer, Command::Stop, 0, ticks)
534    }
535
536    /// `xTimerReset`.
537    ///
538    /// # Errors
539    /// As [`Kernel::timer_command`].
540    pub fn timer_reset(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
541        let now = self.tick;
542        self.timer_command(timer, Command::Reset, now, ticks)
543    }
544
545    /// `xTimerChangePeriod`.
546    ///
547    /// A period of zero is refused. The C asserts against one, which on this
548    /// harness ends the run; refusing is the same answer without ending it,
549    /// and it matters because a zero-period auto-reload timer would reload
550    /// for ever without the clock moving.
551    ///
552    /// # Errors
553    /// [`Error::InvalidArgument`] for a zero period; otherwise as
554    /// [`Kernel::timer_command`].
555    pub fn timer_change_period(
556        &mut self,
557        timer: TimerHandle,
558        period: u64,
559        ticks: u64,
560    ) -> Result<Wait<bool>> {
561        if period == 0 {
562            return Err(Error::InvalidArgument);
563        }
564        self.timer_command(timer, Command::ChangePeriod, period, ticks)
565    }
566
567    /// `xTimerDelete`.
568    ///
569    /// # Errors
570    /// As [`Kernel::timer_command`].
571    pub fn timer_delete(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
572        self.timer_command(timer, Command::Delete, 0, ticks)
573    }
574
575    /// `xTimerStartFromISR`.
576    ///
577    /// # Errors
578    /// As [`Kernel::timer_command_from_isr`].
579    pub fn timer_start_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
580        let now = self.tick_count_from_isr();
581        self.timer_command_from_isr(timer, Command::StartFromIsr, now)
582    }
583
584    /// `xTimerStopFromISR`.
585    ///
586    /// # Errors
587    /// As [`Kernel::timer_command_from_isr`].
588    pub fn timer_stop_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
589        self.timer_command_from_isr(timer, Command::StopFromIsr, 0)
590    }
591
592    /// `xTimerResetFromISR`.
593    ///
594    /// # Errors
595    /// As [`Kernel::timer_command_from_isr`].
596    pub fn timer_reset_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
597        let now = self.tick_count_from_isr();
598        self.timer_command_from_isr(timer, Command::ResetFromIsr, now)
599    }
600
601    /// `xTimerChangePeriodFromISR`.
602    ///
603    /// # Errors
604    /// As [`Kernel::timer_command_from_isr`].
605    pub fn timer_change_period_from_isr(
606        &mut self,
607        timer: TimerHandle,
608        period: u64,
609    ) -> Result<(bool, Woken)> {
610        self.timer_command_from_isr(timer, Command::ChangePeriodFromIsr, period)
611    }
612
613    /// `xTimerGenericCommandFromISR`: the raw command, value and all.
614    ///
615    /// Prefer the four wrappers above. They exist because the C's public
616    /// from-ISR API does not let a caller choose the value: a start or a
617    /// reset always carries `xTaskGetTickCountFromISR()`. A value from
618    /// somewhere else is a *command time* the daemon will believe, and a
619    /// command time far enough in the future makes `prvReloadTimer` reload
620    /// without ever landing in the future — a loop the C has too, and
621    /// reaches the same way.
622    ///
623    /// # Errors
624    /// [`Error::Gone`] for a stale handle.
625    pub fn timer_command_from_isr(
626        &mut self,
627        timer: TimerHandle,
628        command: Command,
629        value: u64,
630    ) -> Result<(bool, Woken)> {
631        if !command.is_from_isr() || (command.is_change_period() && value == 0) {
632            self.trace_command_send(timer, command, value);
633            return Ok((false, Woken::NO));
634        }
635        let message = Message {
636            command,
637            value,
638            timer,
639            ..Message::default()
640        };
641        let (ok, woken) = self.post_timer_message_from_isr(message)?;
642        self.trace_command_send(timer, command, value);
643        Ok((ok, woken))
644    }
645
646    /// `xTimerPendFunctionCall`: run `function` on the daemon task.
647    ///
648    /// # Errors
649    /// As the queue send.
650    pub fn timer_pend_function_call(
651        &mut self,
652        function: u16,
653        param1: u64,
654        param2: u64,
655        ticks: u64,
656    ) -> Result<Wait<bool>> {
657        let message = Message {
658            command: Command::ExecuteCallback,
659            value: param2,
660            timer: TimerHandle::NULL,
661            param1,
662            function,
663        };
664        // `tracePEND_FUNC_CALL` is not one of the harness's hooks, so this
665        // says nothing on either side.
666        self.post_timer_message(message, ticks)
667    }
668
669    /// `xTimerPendFunctionCallFromISR`.
670    ///
671    /// This is how `xEventGroupSetBitsFromISR` does its work: an interrupt
672    /// cannot walk an event group's waiting list, so it hands the job to
673    /// the daemon.
674    ///
675    /// # Errors
676    /// As the queue send.
677    pub fn timer_pend_function_call_from_isr(
678        &mut self,
679        function: u16,
680        param1: u64,
681        param2: u64,
682    ) -> Result<(bool, Woken)> {
683        let message = Message {
684            command: Command::ExecuteCallbackFromIsr,
685            value: param2,
686            timer: TimerHandle::NULL,
687            param1,
688            function,
689        };
690        self.post_timer_message_from_isr(message)
691    }
692
693    fn trace_command_send(&mut self, timer: TimerHandle, command: Command, value: u64) {
694        // Nothing to say, so nothing to build. `trace_failure_or_owe` returns
695        // at once for a sink that emits nothing, but the forty-byte
696        // `OwedTrace::TimerCommandSend` is assembled at THIS call site before
697        // the call, and a `Name` copy with it.
698        if !T::EMITS {
699            return;
700        }
701        let tick = self.tick;
702        // A sink that never reads a name pays for neither the resolve nor
703        // the copy of the whole `Name` that goes with it.
704        let name = if T::WANTS_NAMES {
705            self.timers
706                .resolve(timer)
707                .map(|t| t.name)
708                .unwrap_or_default()
709        } else {
710            Name::default()
711        };
712        self.note_exits();
713        self.trace.event(
714            tick,
715            Event::TimerCommandSend {
716                timer,
717                // Gated for the same reason the resolve above is: `as_str` on
718                // even a default `Name` reaches `core::str::from_utf8`.
719                name: if T::WANTS_NAMES { name.as_str() } else { "" },
720                command: command.id(),
721                value,
722            },
723        );
724    }
725
726    /// The same line, but owed to `caller` if the send has already handed
727    /// the CPU to the daemon.
728    fn trace_command_send_for(
729        &mut self,
730        caller: TaskHandle,
731        timer: TimerHandle,
732        command: Command,
733        value: u64,
734    ) {
735        // Nothing to say, so nothing to build. `trace_failure_or_owe` returns
736        // at once for a sink that emits nothing, but the forty-byte
737        // `OwedTrace::TimerCommandSend` is assembled at THIS call site before
738        // the call, and a `Name` copy with it.
739        if !T::EMITS {
740            return;
741        }
742        // A sink that never reads a name pays for neither the resolve nor
743        // the copy of the whole `Name` that goes with it.
744        let name = if T::WANTS_NAMES {
745            self.timers
746                .resolve(timer)
747                .map(|t| t.name)
748                .unwrap_or_default()
749        } else {
750            Name::default()
751        };
752        self.trace_failure_or_owe(
753            caller,
754            OwedTrace::TimerCommandSend {
755                timer,
756                name,
757                command: command.id(),
758                value,
759            },
760        );
761    }
762
763    /// Put a message in the ring and its index on the queue.
764    fn post_timer_message(&mut self, message: Message, ticks: u64) -> Result<Wait<bool>> {
765        let slot = self.stage_timer_message(message);
766        match self.send_generic_outlined(self.timer_queue, slot, ticks, Position::Back)? {
767            Wait::Blocked => Ok(Wait::Blocked),
768            Ready(()) => {
769                self.commit_timer_message();
770                Ok(Ready(true))
771            }
772        }
773    }
774
775    fn post_timer_message_from_isr(&mut self, message: Message) -> Result<(bool, Woken)> {
776        let slot = self.stage_timer_message(message);
777        match self.queue_send_from_isr(self.timer_queue, slot) {
778            Ok(woken) => {
779                self.commit_timer_message();
780                Ok((true, woken))
781            }
782            Err(Error::Full) => Ok((false, Woken::NO)),
783            Err(e) => Err(e),
784        }
785    }
786
787    /// Write the message into the slot the next accepted send will use, and
788    /// answer with that slot — the index the queue will carry.
789    ///
790    /// The C caller holds its `DaemonTaskMessage_t` on its own stack, so a
791    /// send the queue refuses simply loses it and no other message is
792    /// harmed. Here the message lives in a ring the queue carries indices
793    /// into, and the queue's indices are always the run ending just before
794    /// this pointer, so the slot it names is free exactly when the queue
795    /// has room. When it has none the send cannot be accepted either, and
796    /// writing would overwrite a message the daemon has not read yet — the
797    /// oldest one, which is the next it will read.
798    fn stage_timer_message(&mut self, message: Message) -> u64 {
799        let slot = self.timer_message_next;
800        if self.timer_queue_has_room() {
801            if let Some(cell) = self.timer_messages.get_mut(slot) {
802                *cell = message;
803            }
804        }
805        slot as u64
806    }
807
808    /// The queue took the index, so the message it points at belongs to the
809    /// queue until the daemon reads it.
810    fn commit_timer_message(&mut self) {
811        self.timer_message_next = self
812            .timer_message_next
813            .saturating_add(1)
814            .checked_rem(C::TIMER_QUEUE_LENGTH)
815            .unwrap_or(0);
816    }
817
818    /// `uxQueueSpacesAvailable( xTimerQueue ) > 0`, without its critical
819    /// section — this is the kernel reading its own queue, not a task
820    /// asking, so it must cost no sim time.
821    fn timer_queue_has_room(&self) -> bool {
822        self.queues
823            .resolve(self.timer_queue)
824            .is_ok_and(|q| q.waiting < q.length)
825    }
826
827    // ----------------------------------------------------- the daemon task --
828
829    /// `prvGetNextExpireTime`: when the head of the current list is due, and
830    /// whether there is a head at all.
831    pub fn timer_next_expire(&self) -> (u64, bool) {
832        let list = self.timer_list();
833        let empty = self.lists.is_empty(list).unwrap_or(true);
834        if empty {
835            (0, true)
836        } else {
837            (self.lists.head_value(list).unwrap_or(0), false)
838        }
839    }
840
841    /// Whether `pxOverflowTimerList` is empty, which is the second half of
842    /// the daemon's "may I wait for ever?" test.
843    #[must_use]
844    pub fn overflow_timer_list_is_empty(&self) -> bool {
845        self.lists
846            .is_empty(self.overflow_timer_list())
847            .unwrap_or(true)
848    }
849
850    /// `prvSampleTimeNow`: the tick, and whether reading it swapped the two
851    /// timer lists because it wrapped.
852    ///
853    /// # Errors
854    /// As the list operations.
855    pub fn timer_sample_time_now(&mut self) -> Result<(u64, bool)> {
856        let now = self.tick;
857        let switched = now < self.timer_last_time;
858        if switched {
859            self.switch_timer_lists()?;
860        }
861        self.timer_last_time = now;
862        Ok((now, switched))
863    }
864
865    /// `prvSwitchTimerLists`: everything left on the current list has
866    /// expired, so run it, then swap.
867    fn switch_timer_lists(&mut self) -> Result<()> {
868        while !self.lists.is_empty_of(self.timer_list()) {
869            let next = self.lists.head_value(self.timer_list()).unwrap_or(0);
870            self.process_expired_timer(next, Self::MAX_DELAY)?;
871        }
872        self.timers_swapped = !self.timers_swapped;
873        Ok(())
874    }
875
876    /// `prvProcessExpiredTimer`: take the head off, reload it if it is an
877    /// auto-reload, and run its callback.
878    ///
879    /// # Errors
880    /// As the list operations.
881    pub fn process_expired_timer(&mut self, expire_at: u64, now: u64) -> Result<()> {
882        let list = self.timer_list();
883        let Ok(Some(item)) = self.lists.head(list) else {
884            return Ok(());
885        };
886        // Take it off *first*, whatever it turns out to be. `prvSwitchTimerLists`
887        // loops until this list is empty, so an item this cannot resolve —
888        // a timer deleted while its entry was still queued — would spin
889        // here for ever if the removal came after the lookup.
890        let _ = self.lists.unlink(item);
891        let Some(timer) = self.timer_of_item(item) else {
892            return Ok(());
893        };
894        let auto = self
895            .timers
896            .resolve(timer)
897            .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
898            .unwrap_or(false);
899        if auto {
900            self.reload_timer(timer, expire_at, now)?;
901        } else if let Ok(t) = self.timers.resolve_mut(timer) {
902            t.status &= !STATUS_ACTIVE;
903        }
904        self.fire_timer(timer);
905        Ok(())
906    }
907
908    /// `prvReloadTimer`: put it back on the list one period later, and keep
909    /// firing while that period has already gone by.
910    fn reload_timer(&mut self, timer: TimerHandle, expired_at: u64, now: u64) -> Result<()> {
911        let mut expired_at = expired_at;
912        loop {
913            // A period of zero cannot reach here — `timer_create` and
914            // `timer_change_period` both refuse one — but the loop only
915            // terminates because the expiry advances, so it says so.
916            let period = self
917                .timers
918                .resolve(timer)
919                .map(|t| t.period.get())
920                .unwrap_or(1)
921                .max(1);
922            let next = expired_at.wrapping_add(period) & Self::MAX_DELAY;
923            if !self.insert_timer_in_active_list(timer, next, now, expired_at)? {
924                return Ok(());
925            }
926            expired_at = next;
927            self.fire_timer(timer);
928        }
929    }
930
931    /// The callback itself, through the application's hook.
932    fn fire_timer(&mut self, timer: TimerHandle) {
933        let (name, callback, id) = match self.timers.resolve(timer) {
934            Ok(t) => (t.name, t.callback, t.id.get()),
935            Err(_) => return,
936        };
937        let tick = self.tick;
938        self.note_exits();
939        self.trace.event(
940            tick,
941            Event::TimerExpired {
942                timer,
943                name: name.as_str(),
944            },
945        );
946        H::timer(self, timer, callback, id);
947    }
948
949    /// `prvInsertTimerInActiveList`: `true` when the timer is already due
950    /// and the daemon should run it now rather than wait for it.
951    ///
952    /// # Errors
953    /// As the list operations.
954    pub fn insert_timer_in_active_list(
955        &mut self,
956        timer: TimerHandle,
957        expiry: u64,
958        now: u64,
959        command_time: u64,
960    ) -> Result<bool> {
961        let item = Self::timer_item(timer);
962        // `remove` is its own guard: it answers `NotActive` for an item
963        // in no list, and the container test read the same node to learn
964        // what `remove` was about to say. Same fold as `suspend` and
965        // `add_current_task_to_delayed_list`.
966        let _ = self.lists.unlink(item);
967        self.lists.set_value(item, expiry)?;
968        let period = self
969            .timers
970            .resolve(timer)
971            .map(|t| t.period.get())
972            .unwrap_or(1);
973        if expiry <= now {
974            if now.wrapping_sub(command_time) & Self::MAX_DELAY >= period {
975                return Ok(true);
976            }
977            let list = self.overflow_timer_list();
978            self.lists.insert(list, item, expiry)?;
979        } else {
980            if now < command_time && expiry >= command_time {
981                return Ok(true);
982            }
983            let list = self.timer_list();
984            self.lists.insert(list, item, expiry)?;
985        }
986        Ok(false)
987    }
988
989    /// `prvProcessReceivedCommands`: drain the queue, one command per call.
990    ///
991    /// The C loops until the queue is empty; a kernel with no stacks does
992    /// one and says whether there is more, because a callback in the middle
993    /// of that loop can block and the daemon has to be able to come back.
994    ///
995    /// # The block time is not a convenience
996    ///
997    /// `ticks` is how long the daemon is willing to WAIT on the queue, and
998    /// passing zero has a consequence beyond promptness: a daemon that
999    /// polls is never on the queue's receive list, so a task posting a
1000    /// command finds no waiter to remove and `queue_send_generic` does not
1001    /// call `port_yield`. The daemon is higher priority and still does not
1002    /// run, because nothing asked for a switch.
1003    ///
1004    /// That is visible from the C. `TimerDemo.c` stops a timer and asserts
1005    /// on the next line that it is inactive, and its comment says it may:
1006    /// "this will appear to happen immediately to this task because this
1007    /// task is running at a priority below the timer service task". With a
1008    /// polling daemon the assertion fails, and nothing else in the corpus
1009    /// notices.
1010    ///
1011    /// So a caller acting as the daemon should pass what
1012    /// `prvProcessTimerOrBlockTask` computes — the time to the next expiry,
1013    /// or the maximum delay when no timer is active. Zero is correct only
1014    /// for a caller that is draining the queue rather than serving it, such
1015    /// as a trace-exact state machine that schedules the wait itself.
1016    ///
1017    /// # Errors
1018    /// As the queue receive.
1019    pub fn process_one_timer_command(&mut self, ticks: u64) -> Result<Wait<bool>> {
1020        match self.timer_receive_command(ticks)? {
1021            Wait::Blocked => Ok(Wait::Blocked),
1022            Ready(None) => Ok(Ready(false)),
1023            Ready(Some(message)) => {
1024                self.timer_execute_command(message)?;
1025                Ok(Ready(true))
1026            }
1027        }
1028    }
1029
1030    /// The first half of [`Kernel::process_one_timer_command`]: the
1031    /// `xQueueReceive` of `prvProcessReceivedCommands`'s loop: the message,
1032    /// for [`Kernel::timer_execute_command`], or `None` for an empty queue.
1033    ///
1034    /// A COPY of the message, as the C copies it into the daemon's local
1035    /// `xMessage`: the receive frees the ring slot it sat in, and a post
1036    /// between the two halves -- the tick hook's, say -- can reuse it.
1037    ///
1038    /// The halves are separate for a daemon that has to stop BETWEEN them.
1039    /// On two cores the receive is a top-level call that leaves a critical
1040    /// section, so it ends the daemon's turn (the two-core contract), and
1041    /// what the command then does -- a callback, the `vPortFree` a delete
1042    /// costs -- happens in the turns after. One call for both put the
1043    /// daemon a turn ahead of the C (two-core `TaskNotify`, a delete).
1044    ///
1045    /// # Errors
1046    /// As the queue receive.
1047    pub fn timer_receive_command(&mut self, ticks: u64) -> Result<Wait<Option<Message>>> {
1048        match self.queue_receive(self.timer_queue, ticks) {
1049            Ok(Ready(slot)) => Ok(Ready(Some(
1050                self.timer_messages
1051                    .get(slot as usize)
1052                    .copied()
1053                    .unwrap_or_default(),
1054            ))),
1055            Ok(Wait::Blocked) => Ok(Wait::Blocked),
1056            Err(_) => Ok(Ready(None)),
1057        }
1058    }
1059
1060    /// The second half of [`Kernel::process_one_timer_command`]: carry out
1061    /// the command [`Kernel::timer_receive_command`] took.
1062    ///
1063    /// # Errors
1064    /// As the list operations.
1065    pub fn timer_execute_command(&mut self, message: Message) -> Result<()> {
1066        if message.command.id() < 0 {
1067            // A pended function call: the daemon just runs it.
1068            H::pended(self, message.function, message.param1, message.value);
1069            return Ok(());
1070        }
1071
1072        let timer = message.timer;
1073        if self.timers.resolve(timer).is_err() {
1074            return Ok(());
1075        }
1076        let item = Self::timer_item(timer);
1077        // `remove` is its own guard: it answers `NotActive` for an item
1078        // in no list, and the container test read the same node to learn
1079        // what `remove` was about to say. Same fold as `suspend` and
1080        // `add_current_task_to_delayed_list`.
1081        let _ = self.lists.unlink(item);
1082        // `traceTIMER_COMMAND_RECEIVED` is not one of the harness's hooks.
1083        let (now, _switched) = self.timer_sample_time_now()?;
1084
1085        if message.command.is_start_or_reset() {
1086            if let Ok(t) = self.timers.resolve_mut(timer) {
1087                t.status |= STATUS_ACTIVE;
1088            }
1089            let period = self
1090                .timers
1091                .resolve(timer)
1092                .map(|t| t.period.get())
1093                .unwrap_or(1);
1094            let expiry = message.value.wrapping_add(period) & Self::MAX_DELAY;
1095            if self.insert_timer_in_active_list(timer, expiry, now, message.value)? {
1096                let auto = self
1097                    .timers
1098                    .resolve(timer)
1099                    .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
1100                    .unwrap_or(false);
1101                if auto {
1102                    self.reload_timer(timer, expiry, now)?;
1103                } else if let Ok(t) = self.timers.resolve_mut(timer) {
1104                    t.status &= !STATUS_ACTIVE;
1105                }
1106                self.fire_timer(timer);
1107            }
1108        } else if message.command.is_stop() {
1109            if let Ok(t) = self.timers.resolve_mut(timer) {
1110                t.status &= !STATUS_ACTIVE;
1111            }
1112        } else if message.command.is_change_period() {
1113            if let Ok(t) = self.timers.resolve_mut(timer) {
1114                t.status |= STATUS_ACTIVE;
1115                t.period = Split64::new(message.value);
1116            }
1117            let period = self
1118                .timers
1119                .resolve(timer)
1120                .map(|t| t.period.get())
1121                .unwrap_or(1);
1122            let expiry = now.wrapping_add(period) & Self::MAX_DELAY;
1123            let _ = self.insert_timer_in_active_list(timer, expiry, now, now)?;
1124        } else if message.command == Command::Delete {
1125            let _ = self.timers.discard(timer);
1126            // `vPortFree( pxTimer )`, which every `heap_N.c` wraps in
1127            // `vTaskSuspendAll` / `xTaskResumeAll` exactly as it wraps
1128            // malloc -- so a delete costs one outermost critical-section
1129            // exit, which under the sim contract is one unit of time,
1130            // while emitting no trace line at all (this harness defines no
1131            // `traceTIMER_DELETE`).
1132            //
1133            // `queue_delete` and `event_group_delete` both carry this
1134            // note; the timer command was the third object with a free and
1135            // the one that had not been told. `TaskNotify` is the scenario
1136            // that finds it -- it is the first in the corpus to delete a
1137            // timer -- and it showed up exactly as the other two did:
1138            // every event agreed and the exit column was one short from
1139            // the first delete onwards.
1140            self.account_for_allocation();
1141        }
1142        Ok(())
1143    }
1144
1145    /// Which timer a list item belongs to.
1146    fn timer_of_item(&self, item: u16) -> Option<TimerHandle> {
1147        let base = TASKS.saturating_mul(2) as u16;
1148        let index = item.checked_sub(base)?;
1149        self.timers.handle_at(index)
1150    }
1151}
1152
1153// ================================================================ tests ==
1154
1155/// `timer.rs` had no unit test at all, and three of its APIs are also ones
1156/// no conformance scenario reaches (`docs/HOLES.md`, H2 and H3).
1157///
1158/// Every test here quotes the `timers.c` line it pins, and pins **the C's
1159/// contract** rather than this kernel's behaviour.
1160///
1161/// The theme is that the timer API is a COMMAND QUEUE. Every mutator
1162/// returns "the command was queued", not "the thing happened", and the
1163/// queries read state the daemon has not updated yet. That is the single
1164/// most surprising thing about this API and no scenario in the corpus
1165/// isolates it, because a scenario always lets the daemon run.
1166#[cfg(test)]
1167#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1168mod tests {
1169    use rusty_rtos_core::config::Config;
1170    use rusty_rtos_core::hooks::NoTickHook;
1171
1172    use crate::queue::Wait;
1173    use crate::system::tests::{NoTrace, TestConfig, TestPort};
1174
1175    /// Three tasks (idle, the timer daemon, one spare), one queue for the
1176    /// timer commands, and room for two timers.
1177    type K = crate::Kernel<
1178        TestConfig,
1179        TestPort,
1180        NoTrace,
1181        NoTickHook,
1182        3,
1183        { crate::list_slots_for(3, 2, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
1184        { crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1185        1,
1186        2,
1187        0,
1188        0,
1189        2,
1190        0,
1191        { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1192    >;
1193
1194    /// A started kernel with the daemon PARKED, so a queued command stays
1195    /// queued until a test asks for it to be processed.
1196    fn started() -> K {
1197        let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
1198        let h = k.start_scheduler().expect("start");
1199        k.suspend(Some(h.timer)).expect("park the daemon");
1200        k
1201    }
1202
1203    /// `xTimerStart` queues a command; it does not start a timer.
1204    ///
1205    /// `prvProcessReceivedCommands` is where the flag is actually set:
1206    ///
1207    /// ```c
1208    /// case tmrCOMMAND_START:
1209    ///     ...
1210    ///     pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
1211    /// ```
1212    ///
1213    /// so `pdPASS` from `xTimerStart` means "the daemon has been told", and
1214    /// `xTimerIsTimerActive` keeps saying pdFALSE until the daemon runs. A
1215    /// caller that starts a timer and immediately asks whether it is active
1216    /// gets "no", correctly.
1217    #[test]
1218    fn a_start_only_queues_and_the_timer_is_not_active_until_it_is_processed() {
1219        let mut k = started();
1220        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1221        assert_eq!(k.timer_is_active(t), Ok(false), "created dormant");
1222
1223        assert_eq!(
1224            k.timer_start(t, 0),
1225            Ok(Wait::Ready(true)),
1226            "the COMMAND was accepted"
1227        );
1228        assert_eq!(
1229            k.timer_is_active(t),
1230            Ok(false),
1231            "and the timer is still not running: the daemon has not run"
1232        );
1233
1234        k.process_one_timer_command(0).expect("the daemon runs");
1235        assert_eq!(k.timer_is_active(t), Ok(true), "now it is running");
1236    }
1237
1238    /// `xTimerGetPeriod`:
1239    ///
1240    /// ```c
1241    /// return pxTimer->xTimerPeriodInTicks;
1242    /// ```
1243    ///
1244    /// a plain field read -- and the field is written by the DAEMON:
1245    ///
1246    /// ```c
1247    /// case tmrCOMMAND_CHANGE_PERIOD:
1248    ///     pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
1249    /// ```
1250    ///
1251    /// So between `xTimerChangePeriod` returning pdPASS and the daemon
1252    /// running, `xTimerGetPeriod` answers the OLD period. Two calls that
1253    /// look like a setter and its getter, and they disagree.
1254    #[test]
1255    fn the_period_is_the_old_one_until_a_change_is_processed() {
1256        let mut k = started();
1257        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1258        assert_eq!(k.timer_period(t), Ok(10));
1259
1260        assert_eq!(k.timer_change_period(t, 25, 0), Ok(Wait::Ready(true)));
1261        assert_eq!(
1262            k.timer_period(t),
1263            Ok(10),
1264            "the setter returned pdPASS and the getter still says 10"
1265        );
1266
1267        k.process_one_timer_command(0).expect("the daemon runs");
1268        assert_eq!(k.timer_period(t), Ok(25));
1269        assert_eq!(
1270            k.timer_is_active(t),
1271            Ok(true),
1272            "and a change period STARTS a dormant timer, which is the C's rule"
1273        );
1274    }
1275
1276    /// `xTimerGetExpiryTime`:
1277    ///
1278    /// ```c
1279    /// xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) );
1280    /// return xReturn;
1281    /// ```
1282    ///
1283    /// An unconditional list-item read. **Nothing checks that the timer is
1284    /// active**, so on a dormant one this answers whatever the item was
1285    /// last left holding, and the return type cannot say "not running".
1286    ///
1287    /// The only correct use is gated on `xTimerIsTimerActive`, and that is
1288    /// what this pins -- so that a future caller reads it here rather than
1289    /// discovering it from a wrong wake-up.
1290    #[test]
1291    fn expiry_time_is_an_unguarded_list_read_and_needs_is_active_first() {
1292        let mut k = started();
1293        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1294
1295        // Dormant: the call SUCCEEDS and the answer means nothing.
1296        assert!(
1297            k.timer_expiry_time(t).is_ok(),
1298            "it answers happily for a timer that was never started"
1299        );
1300        assert_eq!(
1301            k.timer_is_active(t),
1302            Ok(false),
1303            "and this is the only call that says the answer is meaningless"
1304        );
1305
1306        k.timer_start(t, 0).expect("queue the start");
1307        k.process_one_timer_command(0).expect("the daemon runs");
1308
1309        assert_eq!(k.timer_is_active(t), Ok(true));
1310        assert_eq!(
1311            k.timer_expiry_time(t),
1312            Ok(k.tick_count().wrapping_add(10)),
1313            "now it is now-plus-the-period, and now it means something"
1314        );
1315    }
1316
1317    /// `vTimerSetReloadMode`:
1318    ///
1319    /// ```c
1320    /// taskENTER_CRITICAL();
1321    /// if( xAutoReload != pdFALSE ) { pxTimer->ucStatus |=  tmrSTATUS_IS_AUTORELOAD; }
1322    /// else                         { pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; }
1323    /// taskEXIT_CRITICAL();
1324    /// ```
1325    ///
1326    /// The odd one out: it is NOT a queued command, it writes the flag
1327    /// directly. So unlike every other mutator in this file it takes effect
1328    /// at once -- and it does not reschedule anything, so a running timer
1329    /// keeps the expiry it already has and the new mode applies from the
1330    /// next expiry on.
1331    #[test]
1332    fn set_auto_reload_is_immediate_and_reschedules_nothing() {
1333        let mut k = started();
1334        let t = k.timer_create("t", 10, false, 0, 0).expect("a one-shot");
1335        assert_eq!(k.timer_auto_reload(t), Ok(false));
1336
1337        k.timer_start(t, 0).expect("queue the start");
1338        k.process_one_timer_command(0).expect("the daemon runs");
1339        let expiry = k.timer_expiry_time(t).expect("an expiry");
1340
1341        // No daemon round trip, unlike start/stop/change-period.
1342        k.timer_set_auto_reload(t, true).expect("set");
1343        assert_eq!(
1344            k.timer_auto_reload(t),
1345            Ok(true),
1346            "immediate: this one is not a queued command"
1347        );
1348        assert_eq!(
1349            k.timer_expiry_time(t),
1350            Ok(expiry),
1351            "and it moved nothing: the pending expiry is untouched"
1352        );
1353        assert_eq!(k.timer_is_active(t), Ok(true));
1354    }
1355
1356    /// The id is the caller's own storage and the kernel never reads it.
1357    /// `TimerDemo` uses it to count callbacks, which is the only reason it
1358    /// has any coverage at all.
1359    #[test]
1360    fn the_id_is_the_callers_and_round_trips() {
1361        let mut k = started();
1362        let t = k.timer_create("t", 10, false, 7, 0).expect("a timer");
1363        assert_eq!(k.timer_id(t), Ok(7), "the creation id");
1364        k.timer_set_id(t, 0xdead_beef).expect("set");
1365        assert_eq!(k.timer_id(t), Ok(0xdead_beef));
1366
1367        // And it survives the daemon, because no command touches it.
1368        k.timer_start(t, 0).expect("queue the start");
1369        k.process_one_timer_command(0).expect("the daemon runs");
1370        assert_eq!(k.timer_id(t), Ok(0xdead_beef));
1371    }
1372
1373    /// The command queue is finite, and a full one is reported as `pdFAIL`
1374    /// from a call whose name suggests it did something.
1375    ///
1376    /// `TestConfig` declares `configTIMER_QUEUE_LENGTH` of one, so the
1377    /// second command with no block time has nowhere to go. It is the same
1378    /// answer a caller gets on a busy system, where it is a race rather
1379    /// than an arithmetic certainty -- which is why it is worth pinning
1380    /// somewhere it is certain.
1381    #[test]
1382    fn a_full_command_queue_refuses_without_erroring() {
1383        let mut k = started();
1384        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1385
1386        assert_eq!(k.timer_start(t, 0), Ok(Wait::Ready(true)), "queued");
1387        assert_eq!(
1388            k.timer_stop(t, 0),
1389            Ok(Wait::Ready(false)),
1390            "refused: the queue is full and the block time is zero"
1391        );
1392        assert_eq!(
1393            k.timer_is_active(t),
1394            Ok(false),
1395            "neither command has run yet"
1396        );
1397
1398        k.process_one_timer_command(0).expect("drain the start");
1399        assert_eq!(k.timer_is_active(t), Ok(true), "the start, not the stop");
1400    }
1401    /// The ISR halves queue exactly like the task halves do, and are just
1402    /// as deferred -- `xTimerStartFromISR` is
1403    /// `xTimerGenericCommandFromISR( ..., tmrCOMMAND_START_FROM_ISR, ... )`
1404    /// and the daemon is still the only thing that sets the flag.
1405    ///
1406    /// What differs is the block time: an ISR cannot wait, so there is no
1407    /// ticks argument and a full queue is reported at once.
1408    #[test]
1409    fn a_start_from_isr_is_queued_and_not_active_until_processed() {
1410        let mut k = started();
1411        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1412
1413        let (queued, _woken) = k.timer_start_from_isr(t).expect("isr");
1414        assert!(queued, "the command was accepted");
1415        assert_eq!(
1416            k.timer_is_active(t),
1417            Ok(false),
1418            "and the timer is not running: the daemon has not run"
1419        );
1420
1421        k.process_one_timer_command(0).expect("the daemon runs");
1422        assert_eq!(k.timer_is_active(t), Ok(true));
1423    }
1424
1425    /// A stop from an interrupt, likewise deferred -- and it takes effect
1426    /// only when the daemon reaches it, so between the two the timer is
1427    /// still running and can still expire.
1428    #[test]
1429    fn a_stop_from_isr_leaves_the_timer_running_until_the_daemon_reaches_it() {
1430        let mut k = started();
1431        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1432        k.timer_start(t, 0).expect("queue the start");
1433        k.process_one_timer_command(0)
1434            .expect("the daemon starts it");
1435        assert_eq!(k.timer_is_active(t), Ok(true));
1436
1437        let (queued, _woken) = k.timer_stop_from_isr(t).expect("isr");
1438        assert!(queued);
1439        assert_eq!(
1440            k.timer_is_active(t),
1441            Ok(true),
1442            "STILL RUNNING: an interrupt asked, and nothing has answered yet"
1443        );
1444
1445        k.process_one_timer_command(0).expect("the daemon stops it");
1446        assert_eq!(k.timer_is_active(t), Ok(false));
1447    }
1448
1449    /// `xTimerChangePeriodFromISR` carries its value the same way, and the
1450    /// period is the daemon's to write.
1451    #[test]
1452    fn a_change_period_from_isr_carries_its_value_through_the_queue() {
1453        let mut k = started();
1454        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1455
1456        let (queued, _woken) = k.timer_change_period_from_isr(t, 40).expect("isr");
1457        assert!(queued);
1458        assert_eq!(k.timer_period(t), Ok(10), "not yet");
1459
1460        k.process_one_timer_command(0).expect("the daemon runs");
1461        assert_eq!(k.timer_period(t), Ok(40));
1462        assert_eq!(
1463            k.timer_is_active(t),
1464            Ok(true),
1465            "and a change period starts a dormant timer, from an ISR too"
1466        );
1467    }
1468
1469    /// `xTimerResetFromISR` restarts the countdown from NOW, which is the
1470    /// whole point of it -- a reset on a running timer must move the
1471    /// expiry, not leave it where it was.
1472    #[test]
1473    fn a_reset_from_isr_moves_the_expiry_forward() {
1474        let mut k = started();
1475        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1476        k.timer_start(t, 0).expect("queue the start");
1477        k.process_one_timer_command(0)
1478            .expect("the daemon starts it");
1479        let first = k.timer_expiry_time(t).expect("an expiry");
1480
1481        for _ in 0..3_u32 {
1482            k.tick_from_isr();
1483        }
1484
1485        let (queued, _woken) = k.timer_reset_from_isr(t).expect("isr");
1486        assert!(queued);
1487        k.process_one_timer_command(0)
1488            .expect("the daemon resets it");
1489
1490        assert_eq!(
1491            k.timer_expiry_time(t),
1492            Ok(first.wrapping_add(3)),
1493            "the countdown restarted from the tick the reset was taken at"
1494        );
1495    }
1496
1497    /// `xTimerPendFunctionCall` rides the same queue as the timer commands
1498    /// -- it is a way to run something in task context that an interrupt
1499    /// asked for, and it competes with real timer work for queue slots.
1500    ///
1501    /// `TestConfig` gives the queue one slot, so this pins the competition
1502    /// rather than assuming it.
1503    #[test]
1504    fn a_pended_function_call_competes_for_the_same_queue() {
1505        let mut k = started();
1506        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1507
1508        assert_eq!(
1509            k.timer_pend_function_call(1, 2, 3, 0),
1510            Ok(Wait::Ready(true)),
1511            "the callback is queued"
1512        );
1513        assert_eq!(
1514            k.timer_start(t, 0),
1515            Ok(Wait::Ready(false)),
1516            "and now a timer start has nowhere to go"
1517        );
1518
1519        k.process_one_timer_command(0).expect("drain the callback");
1520        assert_eq!(
1521            k.timer_start(t, 0),
1522            Ok(Wait::Ready(true)),
1523            "with the slot free again the start is accepted"
1524        );
1525    }
1526
1527    /// The ISR half of the same call, which is how
1528    /// `xEventGroupSetBitsFromISR` reaches the daemon.
1529    #[test]
1530    fn a_pended_function_call_from_isr_queues_without_blocking() {
1531        let mut k = started();
1532        let (queued, _woken) = k.timer_pend_function_call_from_isr(1, 2, 3).expect("isr");
1533        assert!(queued, "queued");
1534
1535        let (queued, _woken) = k.timer_pend_function_call_from_isr(4, 5, 6).expect("isr");
1536        assert!(
1537            !queued,
1538            "and the second is refused at once: an interrupt cannot wait"
1539        );
1540    }
1541
1542    /// The from-ISR entry refuses what the C `configASSERT`s
1543    /// (`xTimerGenericCommandFromISR`): a task-level command, and a change
1544    /// of period to zero. Refused means traced, answered false, and nothing
1545    /// queued for the daemon (plan P5: `||` -> `&&` survived every oracle,
1546    /// which never makes the call the C cannot answer).
1547    #[test]
1548    fn the_isr_entry_refuses_a_task_command_and_a_zero_period() {
1549        use rusty_rtos_core::isr::Woken;
1550        let mut k = started();
1551        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1552        for (command, value) in [
1553            (super::Command::Start, 0),
1554            (super::Command::ChangePeriodFromIsr, 0),
1555        ] {
1556            assert_eq!(
1557                k.timer_command_from_isr(t, command, value),
1558                Ok((false, Woken::NO)),
1559                "{command:?} {value} must be refused"
1560            );
1561            assert_eq!(
1562                k.process_one_timer_command(0),
1563                Ok(Wait::Ready(false)),
1564                "{command:?} {value} reached the daemon's queue"
1565            );
1566        }
1567        // And a good one still goes through.
1568        assert_eq!(
1569            k.timer_command_from_isr(t, super::Command::ChangePeriodFromIsr, 5),
1570            Ok((true, Woken::NO))
1571        );
1572    }
1573
1574    /// `Split64` is storage: `new` then `get` is the identity, a high word
1575    /// included. On a 64-bit host it is one `u64` and this is trivial; at
1576    /// the targets' width (`--target i686-pc-windows-msvc`) it is two words,
1577    /// and a value past 2^32 is the only thing that tells the halves apart
1578    /// (plan P5: `<<` -> `>>` lived, because every stored tick fits 32 bits).
1579    #[test]
1580    fn a_split_value_comes_back_whole() {
1581        for value in [
1582            0,
1583            1,
1584            0xFFFF_FFFF,
1585            0x1_0000_0000,
1586            0x0123_4567_89AB_CDEF,
1587            u64::MAX,
1588        ] {
1589            assert_eq!(super::Split64::new(value).get(), value, "{value:#x}");
1590        }
1591    }
1592}