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::{QueueHandle, 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    const fn is_from_isr(self) -> bool {
102        self.id() >= Self::FIRST_FROM_ISR
103    }
104
105    const fn is_start_or_reset(self) -> bool {
106        matches!(
107            self,
108            Self::Start | Self::StartFromIsr | Self::Reset | Self::ResetFromIsr
109        )
110    }
111
112    const fn is_stop(self) -> bool {
113        matches!(self, Self::Stop | Self::StopFromIsr)
114    }
115
116    const fn is_change_period(self) -> bool {
117        matches!(self, Self::ChangePeriod | Self::ChangePeriodFromIsr)
118    }
119}
120
121/// One `DaemonTaskMessage_t`, kept beside the queue rather than in it.
122#[derive(Debug, Clone, Copy)]
123pub struct Message {
124    /// Which command this is.
125    pub command: Command,
126    /// `xMessageValue` for a timer command; `ulParameter2` for a pended
127    /// function call.
128    pub(crate) value: u64,
129    /// The timer the command is for, if it is a timer command.
130    pub(crate) timer: TimerHandle,
131    /// `pvParameter1` of a pended function call.
132    pub(crate) param1: u64,
133    /// Which pended function, for the hook to switch on.
134    pub(crate) function: u16,
135}
136
137impl Default for Message {
138    fn default() -> Self {
139        Self {
140            command: Command::Stop,
141            value: 0,
142            timer: TimerHandle::NULL,
143            param1: 0,
144            function: 0,
145        }
146    }
147}
148
149/// One software timer: a `Timer_t` without the pointers.
150#[derive(Debug, Clone, Copy, Default)]
151pub struct Timer {
152    pub(crate) name: Name,
153    /// `xTimerPeriodInTicks`.
154    pub(crate) period: u64,
155    /// `pvTimerID`.
156    pub(crate) id: u64,
157    /// Which callback the application's hook should run.
158    pub(crate) callback: u16,
159    /// `ucStatus`.
160    pub(crate) status: u8,
161}
162
163impl<
164    C: Config,
165    P: Port,
166    T: Trace,
167    H,
168    const TASKS: usize,
169    const ITEMS: usize,
170    const LISTS: usize,
171    const QUEUES: usize,
172    const SLOTS: usize,
173    const BUFFERS: usize,
174    const BYTES: usize,
175    const TIMERS: usize,
176    const GROUPS: usize,
177> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS>
178where
179    H: TickHook<Self>,
180{
181    /// `pxCurrentTimerList` and `pxOverflowTimerList`, as list ids. They sit
182    /// after the ready lists and the four task lists, before the queues'.
183    pub(crate) fn timer_list(&self) -> ListId {
184        let base = C::MAX_PRIORITIES.saturating_add(4);
185        base.saturating_add(u8::from(self.timers_swapped))
186    }
187
188    pub(crate) fn overflow_timer_list(&self) -> ListId {
189        let base = C::MAX_PRIORITIES.saturating_add(4);
190        base.saturating_add(u8::from(!self.timers_swapped))
191    }
192
193    /// The list item a timer sorts by. Task items come first, then one per
194    /// timer.
195    pub(crate) fn timer_item(timer: TimerHandle) -> u16 {
196        (TASKS.saturating_mul(2) as u16).saturating_add(timer.index())
197    }
198
199    // ---------------------------------------------------------- creating --
200
201    /// `xTimerCreate`.
202    ///
203    /// `callback` names which of the application's timer callbacks this
204    /// timer runs; `id` is `pvTimerID`.
205    ///
206    /// # Errors
207    /// [`Error::Full`] when the timer arena is full;
208    /// [`Error::InvalidArgument`] for a zero period, which the C asserts on.
209    pub fn timer_create(
210        &mut self,
211        name: &str,
212        period: u64,
213        auto_reload: bool,
214        id: u64,
215        callback: u16,
216    ) -> Result<TimerHandle> {
217        if period == 0 {
218            return Err(Error::InvalidArgument);
219        }
220        // `pvPortMalloc( sizeof( Timer_t ) )` comes first.
221        self.account_for_allocation();
222        let status = if auto_reload { STATUS_AUTORELOAD } else { 0 };
223        let handle = self
224            .timers
225            .try_insert(Timer {
226                // A timer keeps the *pointer* to its name in the C, so it
227                // is never truncated the way a task's is. `Oneshot Timer`
228                // is thirteen characters and `configMAX_TASK_NAME_LEN` is
229                // twelve.
230                name: Name::new(name, crate::NAME_CAPACITY),
231                period,
232                id,
233                callback,
234                status,
235            })
236            .map_err(|_| Error::Full)?;
237        // `prvInitialiseNewTimer` opens with `prvCheckForValidListAndQueue`.
238        self.check_for_valid_list_and_queue()?;
239        let tick = self.tick;
240        let name = self
241            .timers
242            .resolve(handle)
243            .map(|t| t.name)
244            .unwrap_or_default();
245        self.trace.note_exits(self.port.exits());
246        self.trace.event(
247            tick,
248            Event::TimerCreate {
249                timer: handle,
250                name: name.as_str(),
251            },
252        );
253        Ok(handle)
254    }
255
256    /// `prvCheckForValidListAndQueue`: make the command queue if no timer
257    /// has made it yet, inside one critical section either way.
258    ///
259    /// The C makes it lazily, on the first `xTimerCreate` — which for
260    /// `TimerDemo` is *before the scheduler starts*, so the queue is the
261    /// first object in the trace and not the third. Everything the create
262    /// does happens inside the outer section, so the whole thing is one
263    /// outermost exit whether or not it built anything.
264    ///
265    /// # Errors
266    /// As [`Kernel::queue_create`].
267    pub(crate) fn check_for_valid_list_and_queue(&mut self) -> Result<()> {
268        self.enter_critical();
269        let result = if self.timer_queue == QueueHandle::NULL {
270            match self.queue_create(C::TIMER_QUEUE_LENGTH) {
271                Ok(queue) => {
272                    self.timer_queue = queue;
273                    Ok(())
274                }
275                Err(e) => Err(e),
276            }
277        } else {
278            Ok(())
279        };
280        self.exit_critical();
281        result
282    }
283
284    /// `pvTimerGetTimerID`.
285    ///
286    /// # Errors
287    /// [`Error::Gone`] for a stale handle.
288    pub fn timer_id(&mut self, timer: TimerHandle) -> Result<u64> {
289        // The C wraps this in a critical section.
290        self.enter_critical();
291        let id = self.timers.resolve(timer).map(|t| t.id);
292        self.exit_critical();
293        id
294    }
295
296    /// `vTimerSetTimerID`.
297    ///
298    /// # Errors
299    /// [`Error::Gone`] for a stale handle.
300    pub fn timer_set_id(&mut self, timer: TimerHandle, id: u64) -> Result<()> {
301        self.enter_critical();
302        let result = self.timers.resolve_mut(timer).map(|t| {
303            t.id = id;
304        });
305        self.exit_critical();
306        result
307    }
308
309    /// `xTimerGetPeriod`.
310    ///
311    /// # Errors
312    /// [`Error::Gone`] for a stale handle.
313    pub fn timer_period(&self, timer: TimerHandle) -> Result<u64> {
314        self.timers.resolve(timer).map(|t| t.period)
315    }
316
317    /// `xTimerIsTimerActive`.
318    ///
319    /// # Errors
320    /// [`Error::Gone`] for a stale handle.
321    pub fn timer_is_active(&mut self, timer: TimerHandle) -> Result<bool> {
322        self.enter_critical();
323        let active = self
324            .timers
325            .resolve(timer)
326            .map(|t| (t.status & STATUS_ACTIVE) != 0);
327        self.exit_critical();
328        active
329    }
330
331    /// `xTimerGetExpiryTime`.
332    ///
333    /// # Errors
334    /// [`Error::Gone`] for a stale handle.
335    pub fn timer_expiry_time(&self, timer: TimerHandle) -> Result<u64> {
336        self.timers.resolve(timer)?;
337        self.lists.value(Self::timer_item(timer))
338    }
339
340    /// `xTimerGetReloadMode`.
341    ///
342    /// # Errors
343    /// [`Error::Gone`] for a stale handle.
344    pub fn timer_auto_reload(&mut self, timer: TimerHandle) -> Result<bool> {
345        self.enter_critical();
346        let auto = self
347            .timers
348            .resolve(timer)
349            .map(|t| (t.status & STATUS_AUTORELOAD) != 0);
350        self.exit_critical();
351        auto
352    }
353
354    /// `vTimerSetReloadMode`.
355    ///
356    /// # Errors
357    /// [`Error::Gone`] for a stale handle.
358    pub fn timer_set_auto_reload(&mut self, timer: TimerHandle, auto: bool) -> Result<()> {
359        self.enter_critical();
360        let result = self.timers.resolve_mut(timer).map(|t| {
361            if auto {
362                t.status |= STATUS_AUTORELOAD;
363            } else {
364                t.status &= !STATUS_AUTORELOAD;
365            }
366        });
367        self.exit_critical();
368        result
369    }
370
371    // --------------------------------------------------- sending commands --
372
373    /// `xTimerGenericCommandFromTask`.
374    ///
375    /// # Errors
376    /// [`Error::Gone`] for a stale handle.
377    pub fn timer_command(
378        &mut self,
379        timer: TimerHandle,
380        command: Command,
381        value: u64,
382        ticks: u64,
383    ) -> Result<Wait<bool>> {
384        let message = Message {
385            command,
386            value,
387            timer,
388            ..Message::default()
389        };
390        // The C refuses a from-ISR command here and still traces the send.
391        if command.is_from_isr() {
392            self.trace_command_send(timer, command, value);
393            return Ok(Ready(false));
394        }
395        // `if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )` — before
396        // the scheduler runs, a command may not block.
397        let ticks = if self.is_running() { ticks } else { 0 };
398        // Who to trace against. The C runs `traceTIMER_COMMAND_SEND` on the
399        // line after `xQueueSendToBack`, so a send that made the daemon
400        // ready switches away first and the line runs when this task has
401        // the CPU back — after the `TASK_SWITCHED_IN` that returns it.
402        let caller = self.current();
403        // `traceTIMER_COMMAND_SEND` fires whatever the send returned — and
404        // a full queue is the *point* of TimerDemo's first test, which
405        // starts exactly as many timers as the queue holds and then
406        // requires the next one to fail.
407        match self.post_timer_message(message, ticks) {
408            Ok(Wait::Blocked) => Ok(Wait::Blocked),
409            Ok(Ready(ok)) => {
410                self.trace_command_send_for(caller, timer, command, value);
411                Ok(Ready(ok))
412            }
413            Err(Error::Full) => {
414                self.trace_command_send_for(caller, timer, command, value);
415                Ok(Ready(false))
416            }
417            Err(e) => Err(e),
418        }
419    }
420
421    /// `xTimerStart`.
422    ///
423    /// # Errors
424    /// As [`Kernel::timer_command`].
425    pub fn timer_start(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
426        let now = self.tick;
427        self.timer_command(timer, Command::Start, now, ticks)
428    }
429
430    /// `xTimerStop`.
431    ///
432    /// # Errors
433    /// As [`Kernel::timer_command`].
434    pub fn timer_stop(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
435        self.timer_command(timer, Command::Stop, 0, ticks)
436    }
437
438    /// `xTimerReset`.
439    ///
440    /// # Errors
441    /// As [`Kernel::timer_command`].
442    pub fn timer_reset(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
443        let now = self.tick;
444        self.timer_command(timer, Command::Reset, now, ticks)
445    }
446
447    /// `xTimerChangePeriod`.
448    ///
449    /// A period of zero is refused. The C asserts against one, which on this
450    /// harness ends the run; refusing is the same answer without ending it,
451    /// and it matters because a zero-period auto-reload timer would reload
452    /// for ever without the clock moving.
453    ///
454    /// # Errors
455    /// [`Error::InvalidArgument`] for a zero period; otherwise as
456    /// [`Kernel::timer_command`].
457    pub fn timer_change_period(
458        &mut self,
459        timer: TimerHandle,
460        period: u64,
461        ticks: u64,
462    ) -> Result<Wait<bool>> {
463        if period == 0 {
464            return Err(Error::InvalidArgument);
465        }
466        self.timer_command(timer, Command::ChangePeriod, period, ticks)
467    }
468
469    /// `xTimerDelete`.
470    ///
471    /// # Errors
472    /// As [`Kernel::timer_command`].
473    pub fn timer_delete(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
474        self.timer_command(timer, Command::Delete, 0, ticks)
475    }
476
477    /// `xTimerStartFromISR`.
478    ///
479    /// # Errors
480    /// As [`Kernel::timer_command_from_isr`].
481    pub fn timer_start_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
482        let now = self.tick_count_from_isr();
483        self.timer_command_from_isr(timer, Command::StartFromIsr, now)
484    }
485
486    /// `xTimerStopFromISR`.
487    ///
488    /// # Errors
489    /// As [`Kernel::timer_command_from_isr`].
490    pub fn timer_stop_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
491        self.timer_command_from_isr(timer, Command::StopFromIsr, 0)
492    }
493
494    /// `xTimerResetFromISR`.
495    ///
496    /// # Errors
497    /// As [`Kernel::timer_command_from_isr`].
498    pub fn timer_reset_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
499        let now = self.tick_count_from_isr();
500        self.timer_command_from_isr(timer, Command::ResetFromIsr, now)
501    }
502
503    /// `xTimerChangePeriodFromISR`.
504    ///
505    /// # Errors
506    /// As [`Kernel::timer_command_from_isr`].
507    pub fn timer_change_period_from_isr(
508        &mut self,
509        timer: TimerHandle,
510        period: u64,
511    ) -> Result<(bool, Woken)> {
512        self.timer_command_from_isr(timer, Command::ChangePeriodFromIsr, period)
513    }
514
515    /// `xTimerGenericCommandFromISR`: the raw command, value and all.
516    ///
517    /// Prefer the four wrappers above. They exist because the C's public
518    /// from-ISR API does not let a caller choose the value: a start or a
519    /// reset always carries `xTaskGetTickCountFromISR()`. A value from
520    /// somewhere else is a *command time* the daemon will believe, and a
521    /// command time far enough in the future makes `prvReloadTimer` reload
522    /// without ever landing in the future — a loop the C has too, and
523    /// reaches the same way.
524    ///
525    /// # Errors
526    /// [`Error::Gone`] for a stale handle.
527    pub fn timer_command_from_isr(
528        &mut self,
529        timer: TimerHandle,
530        command: Command,
531        value: u64,
532    ) -> Result<(bool, Woken)> {
533        if !command.is_from_isr() || (command.is_change_period() && value == 0) {
534            self.trace_command_send(timer, command, value);
535            return Ok((false, Woken::NO));
536        }
537        let message = Message {
538            command,
539            value,
540            timer,
541            ..Message::default()
542        };
543        let (ok, woken) = self.post_timer_message_from_isr(message)?;
544        self.trace_command_send(timer, command, value);
545        Ok((ok, woken))
546    }
547
548    /// `xTimerPendFunctionCall`: run `function` on the daemon task.
549    ///
550    /// # Errors
551    /// As the queue send.
552    pub fn timer_pend_function_call(
553        &mut self,
554        function: u16,
555        param1: u64,
556        param2: u64,
557        ticks: u64,
558    ) -> Result<Wait<bool>> {
559        let message = Message {
560            command: Command::ExecuteCallback,
561            value: param2,
562            timer: TimerHandle::NULL,
563            param1,
564            function,
565        };
566        // `tracePEND_FUNC_CALL` is not one of the harness's hooks, so this
567        // says nothing on either side.
568        self.post_timer_message(message, ticks)
569    }
570
571    /// `xTimerPendFunctionCallFromISR`.
572    ///
573    /// This is how `xEventGroupSetBitsFromISR` does its work: an interrupt
574    /// cannot walk an event group's waiting list, so it hands the job to
575    /// the daemon.
576    ///
577    /// # Errors
578    /// As the queue send.
579    pub fn timer_pend_function_call_from_isr(
580        &mut self,
581        function: u16,
582        param1: u64,
583        param2: u64,
584    ) -> Result<(bool, Woken)> {
585        let message = Message {
586            command: Command::ExecuteCallbackFromIsr,
587            value: param2,
588            timer: TimerHandle::NULL,
589            param1,
590            function,
591        };
592        self.post_timer_message_from_isr(message)
593    }
594
595    fn trace_command_send(&mut self, timer: TimerHandle, command: Command, value: u64) {
596        let tick = self.tick;
597        let name = self
598            .timers
599            .resolve(timer)
600            .map(|t| t.name)
601            .unwrap_or_default();
602        self.trace.note_exits(self.port.exits());
603        self.trace.event(
604            tick,
605            Event::TimerCommandSend {
606                timer,
607                name: name.as_str(),
608                command: command.id(),
609                value,
610            },
611        );
612    }
613
614    /// The same line, but owed to `caller` if the send has already handed
615    /// the CPU to the daemon.
616    fn trace_command_send_for(
617        &mut self,
618        caller: TaskHandle,
619        timer: TimerHandle,
620        command: Command,
621        value: u64,
622    ) {
623        let name = self
624            .timers
625            .resolve(timer)
626            .map(|t| t.name)
627            .unwrap_or_default();
628        self.trace_failure_or_owe(
629            caller,
630            OwedTrace::TimerCommandSend {
631                timer,
632                name,
633                command: command.id(),
634                value,
635            },
636        );
637    }
638
639    /// Put a message in the ring and its index on the queue.
640    fn post_timer_message(&mut self, message: Message, ticks: u64) -> Result<Wait<bool>> {
641        let slot = self.stage_timer_message(message);
642        match self.queue_send_generic(self.timer_queue, slot, ticks, Position::Back)? {
643            Wait::Blocked => Ok(Wait::Blocked),
644            Ready(()) => {
645                self.commit_timer_message();
646                Ok(Ready(true))
647            }
648        }
649    }
650
651    fn post_timer_message_from_isr(&mut self, message: Message) -> Result<(bool, Woken)> {
652        let slot = self.stage_timer_message(message);
653        match self.queue_send_from_isr(self.timer_queue, slot) {
654            Ok(woken) => {
655                self.commit_timer_message();
656                Ok((true, woken))
657            }
658            Err(Error::Full) => Ok((false, Woken::NO)),
659            Err(e) => Err(e),
660        }
661    }
662
663    /// Write the message into the slot the next accepted send will use, and
664    /// answer with that slot — the index the queue will carry.
665    ///
666    /// The C caller holds its `DaemonTaskMessage_t` on its own stack, so a
667    /// send the queue refuses simply loses it and no other message is
668    /// harmed. Here the message lives in a ring the queue carries indices
669    /// into, and the queue's indices are always the run ending just before
670    /// this pointer, so the slot it names is free exactly when the queue
671    /// has room. When it has none the send cannot be accepted either, and
672    /// writing would overwrite a message the daemon has not read yet — the
673    /// oldest one, which is the next it will read.
674    fn stage_timer_message(&mut self, message: Message) -> u64 {
675        let slot = self.timer_message_next;
676        if self.timer_queue_has_room() {
677            if let Some(cell) = self.timer_messages.get_mut(slot) {
678                *cell = message;
679            }
680        }
681        slot as u64
682    }
683
684    /// The queue took the index, so the message it points at belongs to the
685    /// queue until the daemon reads it.
686    fn commit_timer_message(&mut self) {
687        self.timer_message_next = self
688            .timer_message_next
689            .saturating_add(1)
690            .checked_rem(C::TIMER_QUEUE_LENGTH)
691            .unwrap_or(0);
692    }
693
694    /// `uxQueueSpacesAvailable( xTimerQueue ) > 0`, without its critical
695    /// section — this is the kernel reading its own queue, not a task
696    /// asking, so it must cost no sim time.
697    fn timer_queue_has_room(&self) -> bool {
698        self.queues
699            .resolve(self.timer_queue)
700            .is_ok_and(|q| q.waiting < q.length)
701    }
702
703    // ----------------------------------------------------- the daemon task --
704
705    /// `prvGetNextExpireTime`: when the head of the current list is due, and
706    /// whether there is a head at all.
707    pub fn timer_next_expire(&self) -> (u64, bool) {
708        let list = self.timer_list();
709        let empty = self.lists.is_empty(list).unwrap_or(true);
710        if empty {
711            (0, true)
712        } else {
713            (self.lists.head_value(list).unwrap_or(0), false)
714        }
715    }
716
717    /// Whether `pxOverflowTimerList` is empty, which is the second half of
718    /// the daemon's "may I wait for ever?" test.
719    #[must_use]
720    pub fn overflow_timer_list_is_empty(&self) -> bool {
721        self.lists
722            .is_empty(self.overflow_timer_list())
723            .unwrap_or(true)
724    }
725
726    /// `prvSampleTimeNow`: the tick, and whether reading it swapped the two
727    /// timer lists because it wrapped.
728    ///
729    /// # Errors
730    /// As the list operations.
731    pub fn timer_sample_time_now(&mut self) -> Result<(u64, bool)> {
732        let now = self.tick;
733        let switched = now < self.timer_last_time;
734        if switched {
735            self.switch_timer_lists()?;
736        }
737        self.timer_last_time = now;
738        Ok((now, switched))
739    }
740
741    /// `prvSwitchTimerLists`: everything left on the current list has
742    /// expired, so run it, then swap.
743    fn switch_timer_lists(&mut self) -> Result<()> {
744        while self.lists.is_empty(self.timer_list()) == Ok(false) {
745            let next = self.lists.head_value(self.timer_list()).unwrap_or(0);
746            self.process_expired_timer(next, Self::MAX_DELAY)?;
747        }
748        self.timers_swapped = !self.timers_swapped;
749        Ok(())
750    }
751
752    /// `prvProcessExpiredTimer`: take the head off, reload it if it is an
753    /// auto-reload, and run its callback.
754    ///
755    /// # Errors
756    /// As the list operations.
757    pub fn process_expired_timer(&mut self, expire_at: u64, now: u64) -> Result<()> {
758        let list = self.timer_list();
759        let Ok(Some(item)) = self.lists.head(list) else {
760            return Ok(());
761        };
762        // Take it off *first*, whatever it turns out to be. `prvSwitchTimerLists`
763        // loops until this list is empty, so an item this cannot resolve —
764        // a timer deleted while its entry was still queued — would spin
765        // here for ever if the removal came after the lookup.
766        let _ = self.lists.remove(item);
767        let Some(timer) = self.timer_of_item(item) else {
768            return Ok(());
769        };
770        let auto = self
771            .timers
772            .resolve(timer)
773            .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
774            .unwrap_or(false);
775        if auto {
776            self.reload_timer(timer, expire_at, now)?;
777        } else if let Ok(t) = self.timers.resolve_mut(timer) {
778            t.status &= !STATUS_ACTIVE;
779        }
780        self.fire_timer(timer);
781        Ok(())
782    }
783
784    /// `prvReloadTimer`: put it back on the list one period later, and keep
785    /// firing while that period has already gone by.
786    fn reload_timer(&mut self, timer: TimerHandle, expired_at: u64, now: u64) -> Result<()> {
787        let mut expired_at = expired_at;
788        loop {
789            // A period of zero cannot reach here — `timer_create` and
790            // `timer_change_period` both refuse one — but the loop only
791            // terminates because the expiry advances, so it says so.
792            let period = self
793                .timers
794                .resolve(timer)
795                .map(|t| t.period)
796                .unwrap_or(1)
797                .max(1);
798            let next = expired_at.wrapping_add(period) & Self::MAX_DELAY;
799            if !self.insert_timer_in_active_list(timer, next, now, expired_at)? {
800                return Ok(());
801            }
802            expired_at = next;
803            self.fire_timer(timer);
804        }
805    }
806
807    /// The callback itself, through the application's hook.
808    fn fire_timer(&mut self, timer: TimerHandle) {
809        let (name, callback, id) = match self.timers.resolve(timer) {
810            Ok(t) => (t.name, t.callback, t.id),
811            Err(_) => return,
812        };
813        let tick = self.tick;
814        self.trace.note_exits(self.port.exits());
815        self.trace.event(
816            tick,
817            Event::TimerExpired {
818                timer,
819                name: name.as_str(),
820            },
821        );
822        H::timer(self, timer, callback, id);
823    }
824
825    /// `prvInsertTimerInActiveList`: `true` when the timer is already due
826    /// and the daemon should run it now rather than wait for it.
827    ///
828    /// # Errors
829    /// As the list operations.
830    pub fn insert_timer_in_active_list(
831        &mut self,
832        timer: TimerHandle,
833        expiry: u64,
834        now: u64,
835        command_time: u64,
836    ) -> Result<bool> {
837        let item = Self::timer_item(timer);
838        if self.lists.container(item)?.is_some() {
839            let _ = self.lists.remove(item);
840        }
841        self.lists.set_value(item, expiry)?;
842        let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
843        if expiry <= now {
844            if now.wrapping_sub(command_time) & Self::MAX_DELAY >= period {
845                return Ok(true);
846            }
847            let list = self.overflow_timer_list();
848            self.lists.insert(list, item, expiry)?;
849        } else {
850            if now < command_time && expiry >= command_time {
851                return Ok(true);
852            }
853            let list = self.timer_list();
854            self.lists.insert(list, item, expiry)?;
855        }
856        Ok(false)
857    }
858
859    /// `prvProcessReceivedCommands`: drain the queue, one command per call.
860    ///
861    /// The C loops until the queue is empty; a kernel with no stacks does
862    /// one and says whether there is more, because a callback in the middle
863    /// of that loop can block and the daemon has to be able to come back.
864    ///
865    /// # The block time is not a convenience
866    ///
867    /// `ticks` is how long the daemon is willing to WAIT on the queue, and
868    /// passing zero has a consequence beyond promptness: a daemon that
869    /// polls is never on the queue's receive list, so a task posting a
870    /// command finds no waiter to remove and `queue_send_generic` does not
871    /// call `port_yield`. The daemon is higher priority and still does not
872    /// run, because nothing asked for a switch.
873    ///
874    /// That is visible from the C. `TimerDemo.c` stops a timer and asserts
875    /// on the next line that it is inactive, and its comment says it may:
876    /// "this will appear to happen immediately to this task because this
877    /// task is running at a priority below the timer service task". With a
878    /// polling daemon the assertion fails, and nothing else in the corpus
879    /// notices.
880    ///
881    /// So a caller acting as the daemon should pass what
882    /// `prvProcessTimerOrBlockTask` computes — the time to the next expiry,
883    /// or the maximum delay when no timer is active. Zero is correct only
884    /// for a caller that is draining the queue rather than serving it, such
885    /// as a trace-exact state machine that schedules the wait itself.
886    ///
887    /// # Errors
888    /// As the queue receive.
889    pub fn process_one_timer_command(&mut self, ticks: u64) -> Result<Wait<bool>> {
890        let slot = match self.queue_receive(self.timer_queue, ticks) {
891            Ok(Ready(slot)) => slot,
892            Ok(Wait::Blocked) => return Ok(Wait::Blocked),
893            Err(_) => return Ok(Ready(false)),
894        };
895        let message = self
896            .timer_messages
897            .get(slot as usize)
898            .copied()
899            .unwrap_or_default();
900
901        if message.command.id() < 0 {
902            // A pended function call: the daemon just runs it.
903            H::pended(self, message.function, message.param1, message.value);
904            return Ok(Ready(true));
905        }
906
907        let timer = message.timer;
908        if self.timers.resolve(timer).is_err() {
909            return Ok(Ready(true));
910        }
911        let item = Self::timer_item(timer);
912        if self.lists.container(item)?.is_some() {
913            let _ = self.lists.remove(item);
914        }
915        // `traceTIMER_COMMAND_RECEIVED` is not one of the harness's hooks.
916        let (now, _switched) = self.timer_sample_time_now()?;
917
918        if message.command.is_start_or_reset() {
919            if let Ok(t) = self.timers.resolve_mut(timer) {
920                t.status |= STATUS_ACTIVE;
921            }
922            let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
923            let expiry = message.value.wrapping_add(period) & Self::MAX_DELAY;
924            if self.insert_timer_in_active_list(timer, expiry, now, message.value)? {
925                let auto = self
926                    .timers
927                    .resolve(timer)
928                    .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
929                    .unwrap_or(false);
930                if auto {
931                    self.reload_timer(timer, expiry, now)?;
932                } else if let Ok(t) = self.timers.resolve_mut(timer) {
933                    t.status &= !STATUS_ACTIVE;
934                }
935                self.fire_timer(timer);
936            }
937        } else if message.command.is_stop() {
938            if let Ok(t) = self.timers.resolve_mut(timer) {
939                t.status &= !STATUS_ACTIVE;
940            }
941        } else if message.command.is_change_period() {
942            if let Ok(t) = self.timers.resolve_mut(timer) {
943                t.status |= STATUS_ACTIVE;
944                t.period = message.value;
945            }
946            let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
947            let expiry = now.wrapping_add(period) & Self::MAX_DELAY;
948            let _ = self.insert_timer_in_active_list(timer, expiry, now, now)?;
949        } else if message.command == Command::Delete {
950            let _ = self.timers.remove(timer);
951        }
952        Ok(Ready(true))
953    }
954
955    /// Which timer a list item belongs to.
956    fn timer_of_item(&self, item: u16) -> Option<TimerHandle> {
957        let base = TASKS.saturating_mul(2) as u16;
958        let index = item.checked_sub(base)?;
959        self.timers.handle_at(index)
960    }
961}