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