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        // A sink that never reads a name pays for neither the resolve nor
598        // the copy of the whole `Name` that goes with it.
599        let name = if T::WANTS_NAMES {
600            self.timers
601                .resolve(timer)
602                .map(|t| t.name)
603                .unwrap_or_default()
604        } else {
605            Name::default()
606        };
607        self.trace.note_exits(self.port.exits());
608        self.trace.event(
609            tick,
610            Event::TimerCommandSend {
611                timer,
612                name: name.as_str(),
613                command: command.id(),
614                value,
615            },
616        );
617    }
618
619    /// The same line, but owed to `caller` if the send has already handed
620    /// the CPU to the daemon.
621    fn trace_command_send_for(
622        &mut self,
623        caller: TaskHandle,
624        timer: TimerHandle,
625        command: Command,
626        value: u64,
627    ) {
628        // A sink that never reads a name pays for neither the resolve nor
629        // the copy of the whole `Name` that goes with it.
630        let name = if T::WANTS_NAMES {
631            self.timers
632                .resolve(timer)
633                .map(|t| t.name)
634                .unwrap_or_default()
635        } else {
636            Name::default()
637        };
638        self.trace_failure_or_owe(
639            caller,
640            OwedTrace::TimerCommandSend {
641                timer,
642                name,
643                command: command.id(),
644                value,
645            },
646        );
647    }
648
649    /// Put a message in the ring and its index on the queue.
650    fn post_timer_message(&mut self, message: Message, ticks: u64) -> Result<Wait<bool>> {
651        let slot = self.stage_timer_message(message);
652        match self.queue_send_generic(self.timer_queue, slot, ticks, Position::Back)? {
653            Wait::Blocked => Ok(Wait::Blocked),
654            Ready(()) => {
655                self.commit_timer_message();
656                Ok(Ready(true))
657            }
658        }
659    }
660
661    fn post_timer_message_from_isr(&mut self, message: Message) -> Result<(bool, Woken)> {
662        let slot = self.stage_timer_message(message);
663        match self.queue_send_from_isr(self.timer_queue, slot) {
664            Ok(woken) => {
665                self.commit_timer_message();
666                Ok((true, woken))
667            }
668            Err(Error::Full) => Ok((false, Woken::NO)),
669            Err(e) => Err(e),
670        }
671    }
672
673    /// Write the message into the slot the next accepted send will use, and
674    /// answer with that slot — the index the queue will carry.
675    ///
676    /// The C caller holds its `DaemonTaskMessage_t` on its own stack, so a
677    /// send the queue refuses simply loses it and no other message is
678    /// harmed. Here the message lives in a ring the queue carries indices
679    /// into, and the queue's indices are always the run ending just before
680    /// this pointer, so the slot it names is free exactly when the queue
681    /// has room. When it has none the send cannot be accepted either, and
682    /// writing would overwrite a message the daemon has not read yet — the
683    /// oldest one, which is the next it will read.
684    fn stage_timer_message(&mut self, message: Message) -> u64 {
685        let slot = self.timer_message_next;
686        if self.timer_queue_has_room() {
687            if let Some(cell) = self.timer_messages.get_mut(slot) {
688                *cell = message;
689            }
690        }
691        slot as u64
692    }
693
694    /// The queue took the index, so the message it points at belongs to the
695    /// queue until the daemon reads it.
696    fn commit_timer_message(&mut self) {
697        self.timer_message_next = self
698            .timer_message_next
699            .saturating_add(1)
700            .checked_rem(C::TIMER_QUEUE_LENGTH)
701            .unwrap_or(0);
702    }
703
704    /// `uxQueueSpacesAvailable( xTimerQueue ) > 0`, without its critical
705    /// section — this is the kernel reading its own queue, not a task
706    /// asking, so it must cost no sim time.
707    fn timer_queue_has_room(&self) -> bool {
708        self.queues
709            .resolve(self.timer_queue)
710            .is_ok_and(|q| q.waiting < q.length)
711    }
712
713    // ----------------------------------------------------- the daemon task --
714
715    /// `prvGetNextExpireTime`: when the head of the current list is due, and
716    /// whether there is a head at all.
717    pub fn timer_next_expire(&self) -> (u64, bool) {
718        let list = self.timer_list();
719        let empty = self.lists.is_empty(list).unwrap_or(true);
720        if empty {
721            (0, true)
722        } else {
723            (self.lists.head_value(list).unwrap_or(0), false)
724        }
725    }
726
727    /// Whether `pxOverflowTimerList` is empty, which is the second half of
728    /// the daemon's "may I wait for ever?" test.
729    #[must_use]
730    pub fn overflow_timer_list_is_empty(&self) -> bool {
731        self.lists
732            .is_empty(self.overflow_timer_list())
733            .unwrap_or(true)
734    }
735
736    /// `prvSampleTimeNow`: the tick, and whether reading it swapped the two
737    /// timer lists because it wrapped.
738    ///
739    /// # Errors
740    /// As the list operations.
741    pub fn timer_sample_time_now(&mut self) -> Result<(u64, bool)> {
742        let now = self.tick;
743        let switched = now < self.timer_last_time;
744        if switched {
745            self.switch_timer_lists()?;
746        }
747        self.timer_last_time = now;
748        Ok((now, switched))
749    }
750
751    /// `prvSwitchTimerLists`: everything left on the current list has
752    /// expired, so run it, then swap.
753    fn switch_timer_lists(&mut self) -> Result<()> {
754        while self.lists.is_empty(self.timer_list()) == Ok(false) {
755            let next = self.lists.head_value(self.timer_list()).unwrap_or(0);
756            self.process_expired_timer(next, Self::MAX_DELAY)?;
757        }
758        self.timers_swapped = !self.timers_swapped;
759        Ok(())
760    }
761
762    /// `prvProcessExpiredTimer`: take the head off, reload it if it is an
763    /// auto-reload, and run its callback.
764    ///
765    /// # Errors
766    /// As the list operations.
767    pub fn process_expired_timer(&mut self, expire_at: u64, now: u64) -> Result<()> {
768        let list = self.timer_list();
769        let Ok(Some(item)) = self.lists.head(list) else {
770            return Ok(());
771        };
772        // Take it off *first*, whatever it turns out to be. `prvSwitchTimerLists`
773        // loops until this list is empty, so an item this cannot resolve —
774        // a timer deleted while its entry was still queued — would spin
775        // here for ever if the removal came after the lookup.
776        let _ = self.lists.remove(item);
777        let Some(timer) = self.timer_of_item(item) else {
778            return Ok(());
779        };
780        let auto = self
781            .timers
782            .resolve(timer)
783            .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
784            .unwrap_or(false);
785        if auto {
786            self.reload_timer(timer, expire_at, now)?;
787        } else if let Ok(t) = self.timers.resolve_mut(timer) {
788            t.status &= !STATUS_ACTIVE;
789        }
790        self.fire_timer(timer);
791        Ok(())
792    }
793
794    /// `prvReloadTimer`: put it back on the list one period later, and keep
795    /// firing while that period has already gone by.
796    fn reload_timer(&mut self, timer: TimerHandle, expired_at: u64, now: u64) -> Result<()> {
797        let mut expired_at = expired_at;
798        loop {
799            // A period of zero cannot reach here — `timer_create` and
800            // `timer_change_period` both refuse one — but the loop only
801            // terminates because the expiry advances, so it says so.
802            let period = self
803                .timers
804                .resolve(timer)
805                .map(|t| t.period)
806                .unwrap_or(1)
807                .max(1);
808            let next = expired_at.wrapping_add(period) & Self::MAX_DELAY;
809            if !self.insert_timer_in_active_list(timer, next, now, expired_at)? {
810                return Ok(());
811            }
812            expired_at = next;
813            self.fire_timer(timer);
814        }
815    }
816
817    /// The callback itself, through the application's hook.
818    fn fire_timer(&mut self, timer: TimerHandle) {
819        let (name, callback, id) = match self.timers.resolve(timer) {
820            Ok(t) => (t.name, t.callback, t.id),
821            Err(_) => return,
822        };
823        let tick = self.tick;
824        self.trace.note_exits(self.port.exits());
825        self.trace.event(
826            tick,
827            Event::TimerExpired {
828                timer,
829                name: name.as_str(),
830            },
831        );
832        H::timer(self, timer, callback, id);
833    }
834
835    /// `prvInsertTimerInActiveList`: `true` when the timer is already due
836    /// and the daemon should run it now rather than wait for it.
837    ///
838    /// # Errors
839    /// As the list operations.
840    pub fn insert_timer_in_active_list(
841        &mut self,
842        timer: TimerHandle,
843        expiry: u64,
844        now: u64,
845        command_time: u64,
846    ) -> Result<bool> {
847        let item = Self::timer_item(timer);
848        if self.lists.container(item)?.is_some() {
849            let _ = self.lists.remove(item);
850        }
851        self.lists.set_value(item, expiry)?;
852        let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
853        if expiry <= now {
854            if now.wrapping_sub(command_time) & Self::MAX_DELAY >= period {
855                return Ok(true);
856            }
857            let list = self.overflow_timer_list();
858            self.lists.insert(list, item, expiry)?;
859        } else {
860            if now < command_time && expiry >= command_time {
861                return Ok(true);
862            }
863            let list = self.timer_list();
864            self.lists.insert(list, item, expiry)?;
865        }
866        Ok(false)
867    }
868
869    /// `prvProcessReceivedCommands`: drain the queue, one command per call.
870    ///
871    /// The C loops until the queue is empty; a kernel with no stacks does
872    /// one and says whether there is more, because a callback in the middle
873    /// of that loop can block and the daemon has to be able to come back.
874    ///
875    /// # The block time is not a convenience
876    ///
877    /// `ticks` is how long the daemon is willing to WAIT on the queue, and
878    /// passing zero has a consequence beyond promptness: a daemon that
879    /// polls is never on the queue's receive list, so a task posting a
880    /// command finds no waiter to remove and `queue_send_generic` does not
881    /// call `port_yield`. The daemon is higher priority and still does not
882    /// run, because nothing asked for a switch.
883    ///
884    /// That is visible from the C. `TimerDemo.c` stops a timer and asserts
885    /// on the next line that it is inactive, and its comment says it may:
886    /// "this will appear to happen immediately to this task because this
887    /// task is running at a priority below the timer service task". With a
888    /// polling daemon the assertion fails, and nothing else in the corpus
889    /// notices.
890    ///
891    /// So a caller acting as the daemon should pass what
892    /// `prvProcessTimerOrBlockTask` computes — the time to the next expiry,
893    /// or the maximum delay when no timer is active. Zero is correct only
894    /// for a caller that is draining the queue rather than serving it, such
895    /// as a trace-exact state machine that schedules the wait itself.
896    ///
897    /// # Errors
898    /// As the queue receive.
899    pub fn process_one_timer_command(&mut self, ticks: u64) -> Result<Wait<bool>> {
900        let slot = match self.queue_receive(self.timer_queue, ticks) {
901            Ok(Ready(slot)) => slot,
902            Ok(Wait::Blocked) => return Ok(Wait::Blocked),
903            Err(_) => return Ok(Ready(false)),
904        };
905        let message = self
906            .timer_messages
907            .get(slot as usize)
908            .copied()
909            .unwrap_or_default();
910
911        if message.command.id() < 0 {
912            // A pended function call: the daemon just runs it.
913            H::pended(self, message.function, message.param1, message.value);
914            return Ok(Ready(true));
915        }
916
917        let timer = message.timer;
918        if self.timers.resolve(timer).is_err() {
919            return Ok(Ready(true));
920        }
921        let item = Self::timer_item(timer);
922        if self.lists.container(item)?.is_some() {
923            let _ = self.lists.remove(item);
924        }
925        // `traceTIMER_COMMAND_RECEIVED` is not one of the harness's hooks.
926        let (now, _switched) = self.timer_sample_time_now()?;
927
928        if message.command.is_start_or_reset() {
929            if let Ok(t) = self.timers.resolve_mut(timer) {
930                t.status |= STATUS_ACTIVE;
931            }
932            let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
933            let expiry = message.value.wrapping_add(period) & Self::MAX_DELAY;
934            if self.insert_timer_in_active_list(timer, expiry, now, message.value)? {
935                let auto = self
936                    .timers
937                    .resolve(timer)
938                    .map(|t| (t.status & STATUS_AUTORELOAD) != 0)
939                    .unwrap_or(false);
940                if auto {
941                    self.reload_timer(timer, expiry, now)?;
942                } else if let Ok(t) = self.timers.resolve_mut(timer) {
943                    t.status &= !STATUS_ACTIVE;
944                }
945                self.fire_timer(timer);
946            }
947        } else if message.command.is_stop() {
948            if let Ok(t) = self.timers.resolve_mut(timer) {
949                t.status &= !STATUS_ACTIVE;
950            }
951        } else if message.command.is_change_period() {
952            if let Ok(t) = self.timers.resolve_mut(timer) {
953                t.status |= STATUS_ACTIVE;
954                t.period = message.value;
955            }
956            let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
957            let expiry = now.wrapping_add(period) & Self::MAX_DELAY;
958            let _ = self.insert_timer_in_active_list(timer, expiry, now, now)?;
959        } else if message.command == Command::Delete {
960            let _ = self.timers.remove(timer);
961            // `vPortFree( pxTimer )`, which every `heap_N.c` wraps in
962            // `vTaskSuspendAll` / `xTaskResumeAll` exactly as it wraps
963            // malloc -- so a delete costs one outermost critical-section
964            // exit, which under the sim contract is one unit of time,
965            // while emitting no trace line at all (this harness defines no
966            // `traceTIMER_DELETE`).
967            //
968            // `queue_delete` and `event_group_delete` both carry this
969            // note; the timer command was the third object with a free and
970            // the one that had not been told. `TaskNotify` is the scenario
971            // that finds it -- it is the first in the corpus to delete a
972            // timer -- and it showed up exactly as the other two did:
973            // every event agreed and the exit column was one short from
974            // the first delete onwards.
975            self.account_for_allocation();
976        }
977        Ok(Ready(true))
978    }
979
980    /// Which timer a list item belongs to.
981    fn timer_of_item(&self, item: u16) -> Option<TimerHandle> {
982        let base = TASKS.saturating_mul(2) as u16;
983        let index = item.checked_sub(base)?;
984        self.timers.handle_at(index)
985    }
986}
987
988// ================================================================ tests ==
989
990/// `timer.rs` had no unit test at all, and three of its APIs are also ones
991/// no conformance scenario reaches (`docs/HOLES.md`, H2 and H3).
992///
993/// Every test here quotes the `timers.c` line it pins, and pins **the C's
994/// contract** rather than this kernel's behaviour.
995///
996/// The theme is that the timer API is a COMMAND QUEUE. Every mutator
997/// returns "the command was queued", not "the thing happened", and the
998/// queries read state the daemon has not updated yet. That is the single
999/// most surprising thing about this API and no scenario in the corpus
1000/// isolates it, because a scenario always lets the daemon run.
1001#[cfg(test)]
1002#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1003mod tests {
1004    use rusty_rtos_core::config::Config;
1005    use rusty_rtos_core::hooks::NoTickHook;
1006
1007    use crate::queue::Wait;
1008    use crate::system::tests::{NoTrace, TestConfig, TestPort};
1009
1010    /// Three tasks (idle, the timer daemon, one spare), one queue for the
1011    /// timer commands, and room for two timers.
1012    type K = crate::Kernel<
1013        TestConfig,
1014        TestPort,
1015        NoTrace,
1016        NoTickHook,
1017        3,
1018        { crate::list_slots_for(3, 2, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
1019        { crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1020        1,
1021        2,
1022        0,
1023        0,
1024        2,
1025        0,
1026    >;
1027
1028    /// A started kernel with the daemon PARKED, so a queued command stays
1029    /// queued until a test asks for it to be processed.
1030    fn started() -> K {
1031        let mut k = K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up");
1032        let h = k.start_scheduler().expect("start");
1033        k.suspend(Some(h.timer)).expect("park the daemon");
1034        k
1035    }
1036
1037    /// `xTimerStart` queues a command; it does not start a timer.
1038    ///
1039    /// `prvProcessReceivedCommands` is where the flag is actually set:
1040    ///
1041    /// ```c
1042    /// case tmrCOMMAND_START:
1043    ///     ...
1044    ///     pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
1045    /// ```
1046    ///
1047    /// so `pdPASS` from `xTimerStart` means "the daemon has been told", and
1048    /// `xTimerIsTimerActive` keeps saying pdFALSE until the daemon runs. A
1049    /// caller that starts a timer and immediately asks whether it is active
1050    /// gets "no", correctly.
1051    #[test]
1052    fn a_start_only_queues_and_the_timer_is_not_active_until_it_is_processed() {
1053        let mut k = started();
1054        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1055        assert_eq!(k.timer_is_active(t), Ok(false), "created dormant");
1056
1057        assert_eq!(
1058            k.timer_start(t, 0),
1059            Ok(Wait::Ready(true)),
1060            "the COMMAND was accepted"
1061        );
1062        assert_eq!(
1063            k.timer_is_active(t),
1064            Ok(false),
1065            "and the timer is still not running: the daemon has not run"
1066        );
1067
1068        k.process_one_timer_command(0).expect("the daemon runs");
1069        assert_eq!(k.timer_is_active(t), Ok(true), "now it is running");
1070    }
1071
1072    /// `xTimerGetPeriod`:
1073    ///
1074    /// ```c
1075    /// return pxTimer->xTimerPeriodInTicks;
1076    /// ```
1077    ///
1078    /// a plain field read -- and the field is written by the DAEMON:
1079    ///
1080    /// ```c
1081    /// case tmrCOMMAND_CHANGE_PERIOD:
1082    ///     pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
1083    /// ```
1084    ///
1085    /// So between `xTimerChangePeriod` returning pdPASS and the daemon
1086    /// running, `xTimerGetPeriod` answers the OLD period. Two calls that
1087    /// look like a setter and its getter, and they disagree.
1088    #[test]
1089    fn the_period_is_the_old_one_until_a_change_is_processed() {
1090        let mut k = started();
1091        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1092        assert_eq!(k.timer_period(t), Ok(10));
1093
1094        assert_eq!(k.timer_change_period(t, 25, 0), Ok(Wait::Ready(true)));
1095        assert_eq!(
1096            k.timer_period(t),
1097            Ok(10),
1098            "the setter returned pdPASS and the getter still says 10"
1099        );
1100
1101        k.process_one_timer_command(0).expect("the daemon runs");
1102        assert_eq!(k.timer_period(t), Ok(25));
1103        assert_eq!(
1104            k.timer_is_active(t),
1105            Ok(true),
1106            "and a change period STARTS a dormant timer, which is the C's rule"
1107        );
1108    }
1109
1110    /// `xTimerGetExpiryTime`:
1111    ///
1112    /// ```c
1113    /// xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) );
1114    /// return xReturn;
1115    /// ```
1116    ///
1117    /// An unconditional list-item read. **Nothing checks that the timer is
1118    /// active**, so on a dormant one this answers whatever the item was
1119    /// last left holding, and the return type cannot say "not running".
1120    ///
1121    /// The only correct use is gated on `xTimerIsTimerActive`, and that is
1122    /// what this pins -- so that a future caller reads it here rather than
1123    /// discovering it from a wrong wake-up.
1124    #[test]
1125    fn expiry_time_is_an_unguarded_list_read_and_needs_is_active_first() {
1126        let mut k = started();
1127        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1128
1129        // Dormant: the call SUCCEEDS and the answer means nothing.
1130        assert!(
1131            k.timer_expiry_time(t).is_ok(),
1132            "it answers happily for a timer that was never started"
1133        );
1134        assert_eq!(
1135            k.timer_is_active(t),
1136            Ok(false),
1137            "and this is the only call that says the answer is meaningless"
1138        );
1139
1140        k.timer_start(t, 0).expect("queue the start");
1141        k.process_one_timer_command(0).expect("the daemon runs");
1142
1143        assert_eq!(k.timer_is_active(t), Ok(true));
1144        assert_eq!(
1145            k.timer_expiry_time(t),
1146            Ok(k.tick_count().wrapping_add(10)),
1147            "now it is now-plus-the-period, and now it means something"
1148        );
1149    }
1150
1151    /// `vTimerSetReloadMode`:
1152    ///
1153    /// ```c
1154    /// taskENTER_CRITICAL();
1155    /// if( xAutoReload != pdFALSE ) { pxTimer->ucStatus |=  tmrSTATUS_IS_AUTORELOAD; }
1156    /// else                         { pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; }
1157    /// taskEXIT_CRITICAL();
1158    /// ```
1159    ///
1160    /// The odd one out: it is NOT a queued command, it writes the flag
1161    /// directly. So unlike every other mutator in this file it takes effect
1162    /// at once -- and it does not reschedule anything, so a running timer
1163    /// keeps the expiry it already has and the new mode applies from the
1164    /// next expiry on.
1165    #[test]
1166    fn set_auto_reload_is_immediate_and_reschedules_nothing() {
1167        let mut k = started();
1168        let t = k.timer_create("t", 10, false, 0, 0).expect("a one-shot");
1169        assert_eq!(k.timer_auto_reload(t), Ok(false));
1170
1171        k.timer_start(t, 0).expect("queue the start");
1172        k.process_one_timer_command(0).expect("the daemon runs");
1173        let expiry = k.timer_expiry_time(t).expect("an expiry");
1174
1175        // No daemon round trip, unlike start/stop/change-period.
1176        k.timer_set_auto_reload(t, true).expect("set");
1177        assert_eq!(
1178            k.timer_auto_reload(t),
1179            Ok(true),
1180            "immediate: this one is not a queued command"
1181        );
1182        assert_eq!(
1183            k.timer_expiry_time(t),
1184            Ok(expiry),
1185            "and it moved nothing: the pending expiry is untouched"
1186        );
1187        assert_eq!(k.timer_is_active(t), Ok(true));
1188    }
1189
1190    /// The id is the caller's own storage and the kernel never reads it.
1191    /// `TimerDemo` uses it to count callbacks, which is the only reason it
1192    /// has any coverage at all.
1193    #[test]
1194    fn the_id_is_the_callers_and_round_trips() {
1195        let mut k = started();
1196        let t = k.timer_create("t", 10, false, 7, 0).expect("a timer");
1197        assert_eq!(k.timer_id(t), Ok(7), "the creation id");
1198        k.timer_set_id(t, 0xdead_beef).expect("set");
1199        assert_eq!(k.timer_id(t), Ok(0xdead_beef));
1200
1201        // And it survives the daemon, because no command touches it.
1202        k.timer_start(t, 0).expect("queue the start");
1203        k.process_one_timer_command(0).expect("the daemon runs");
1204        assert_eq!(k.timer_id(t), Ok(0xdead_beef));
1205    }
1206
1207    /// The command queue is finite, and a full one is reported as `pdFAIL`
1208    /// from a call whose name suggests it did something.
1209    ///
1210    /// `TestConfig` declares `configTIMER_QUEUE_LENGTH` of one, so the
1211    /// second command with no block time has nowhere to go. It is the same
1212    /// answer a caller gets on a busy system, where it is a race rather
1213    /// than an arithmetic certainty -- which is why it is worth pinning
1214    /// somewhere it is certain.
1215    #[test]
1216    fn a_full_command_queue_refuses_without_erroring() {
1217        let mut k = started();
1218        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1219
1220        assert_eq!(k.timer_start(t, 0), Ok(Wait::Ready(true)), "queued");
1221        assert_eq!(
1222            k.timer_stop(t, 0),
1223            Ok(Wait::Ready(false)),
1224            "refused: the queue is full and the block time is zero"
1225        );
1226        assert_eq!(
1227            k.timer_is_active(t),
1228            Ok(false),
1229            "neither command has run yet"
1230        );
1231
1232        k.process_one_timer_command(0).expect("drain the start");
1233        assert_eq!(k.timer_is_active(t), Ok(true), "the start, not the stop");
1234    }
1235    /// The ISR halves queue exactly like the task halves do, and are just
1236    /// as deferred -- `xTimerStartFromISR` is
1237    /// `xTimerGenericCommandFromISR( ..., tmrCOMMAND_START_FROM_ISR, ... )`
1238    /// and the daemon is still the only thing that sets the flag.
1239    ///
1240    /// What differs is the block time: an ISR cannot wait, so there is no
1241    /// ticks argument and a full queue is reported at once.
1242    #[test]
1243    fn a_start_from_isr_is_queued_and_not_active_until_processed() {
1244        let mut k = started();
1245        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1246
1247        let (queued, _woken) = k.timer_start_from_isr(t).expect("isr");
1248        assert!(queued, "the command was accepted");
1249        assert_eq!(
1250            k.timer_is_active(t),
1251            Ok(false),
1252            "and the timer is not running: the daemon has not run"
1253        );
1254
1255        k.process_one_timer_command(0).expect("the daemon runs");
1256        assert_eq!(k.timer_is_active(t), Ok(true));
1257    }
1258
1259    /// A stop from an interrupt, likewise deferred -- and it takes effect
1260    /// only when the daemon reaches it, so between the two the timer is
1261    /// still running and can still expire.
1262    #[test]
1263    fn a_stop_from_isr_leaves_the_timer_running_until_the_daemon_reaches_it() {
1264        let mut k = started();
1265        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1266        k.timer_start(t, 0).expect("queue the start");
1267        k.process_one_timer_command(0)
1268            .expect("the daemon starts it");
1269        assert_eq!(k.timer_is_active(t), Ok(true));
1270
1271        let (queued, _woken) = k.timer_stop_from_isr(t).expect("isr");
1272        assert!(queued);
1273        assert_eq!(
1274            k.timer_is_active(t),
1275            Ok(true),
1276            "STILL RUNNING: an interrupt asked, and nothing has answered yet"
1277        );
1278
1279        k.process_one_timer_command(0).expect("the daemon stops it");
1280        assert_eq!(k.timer_is_active(t), Ok(false));
1281    }
1282
1283    /// `xTimerChangePeriodFromISR` carries its value the same way, and the
1284    /// period is the daemon's to write.
1285    #[test]
1286    fn a_change_period_from_isr_carries_its_value_through_the_queue() {
1287        let mut k = started();
1288        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1289
1290        let (queued, _woken) = k.timer_change_period_from_isr(t, 40).expect("isr");
1291        assert!(queued);
1292        assert_eq!(k.timer_period(t), Ok(10), "not yet");
1293
1294        k.process_one_timer_command(0).expect("the daemon runs");
1295        assert_eq!(k.timer_period(t), Ok(40));
1296        assert_eq!(
1297            k.timer_is_active(t),
1298            Ok(true),
1299            "and a change period starts a dormant timer, from an ISR too"
1300        );
1301    }
1302
1303    /// `xTimerResetFromISR` restarts the countdown from NOW, which is the
1304    /// whole point of it -- a reset on a running timer must move the
1305    /// expiry, not leave it where it was.
1306    #[test]
1307    fn a_reset_from_isr_moves_the_expiry_forward() {
1308        let mut k = started();
1309        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1310        k.timer_start(t, 0).expect("queue the start");
1311        k.process_one_timer_command(0)
1312            .expect("the daemon starts it");
1313        let first = k.timer_expiry_time(t).expect("an expiry");
1314
1315        for _ in 0..3_u32 {
1316            k.tick_from_isr();
1317        }
1318
1319        let (queued, _woken) = k.timer_reset_from_isr(t).expect("isr");
1320        assert!(queued);
1321        k.process_one_timer_command(0)
1322            .expect("the daemon resets it");
1323
1324        assert_eq!(
1325            k.timer_expiry_time(t),
1326            Ok(first.wrapping_add(3)),
1327            "the countdown restarted from the tick the reset was taken at"
1328        );
1329    }
1330
1331    /// `xTimerPendFunctionCall` rides the same queue as the timer commands
1332    /// -- it is a way to run something in task context that an interrupt
1333    /// asked for, and it competes with real timer work for queue slots.
1334    ///
1335    /// `TestConfig` gives the queue one slot, so this pins the competition
1336    /// rather than assuming it.
1337    #[test]
1338    fn a_pended_function_call_competes_for_the_same_queue() {
1339        let mut k = started();
1340        let t = k.timer_create("t", 10, false, 0, 0).expect("a timer");
1341
1342        assert_eq!(
1343            k.timer_pend_function_call(1, 2, 3, 0),
1344            Ok(Wait::Ready(true)),
1345            "the callback is queued"
1346        );
1347        assert_eq!(
1348            k.timer_start(t, 0),
1349            Ok(Wait::Ready(false)),
1350            "and now a timer start has nowhere to go"
1351        );
1352
1353        k.process_one_timer_command(0).expect("drain the callback");
1354        assert_eq!(
1355            k.timer_start(t, 0),
1356            Ok(Wait::Ready(true)),
1357            "with the slot free again the start is accepted"
1358        );
1359    }
1360
1361    /// The ISR half of the same call, which is how
1362    /// `xEventGroupSetBitsFromISR` reaches the daemon.
1363    #[test]
1364    fn a_pended_function_call_from_isr_queues_without_blocking() {
1365        let mut k = started();
1366        let (queued, _woken) = k.timer_pend_function_call_from_isr(1, 2, 3).expect("isr");
1367        assert!(queued, "queued");
1368
1369        let (queued, _woken) = k.timer_pend_function_call_from_isr(4, 5, 6).expect("isr");
1370        assert!(
1371            !queued,
1372            "and the second is refused at once: an interrupt cannot wait"
1373        );
1374    }
1375}