SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
stk::time::TimerHost Class Reference

Software timer multiplexer that manages multiple Timer instances on top of a small fixed set of kernel tasks. More...

#include <stk_time_timer.h>

Collaboration diagram for stk::time::TimerHost:

Classes

struct  TimerInfo
 Consistent snapshot of a timer, see QuerySync(). More...
struct  Config
 Optional configuration of the timer tasks, see Initialize(). More...
class  TimerWorkerTask
 Internal kernel task used by TimerHost for both the tick task and handler tasks. More...
struct  Completion
 Completion point of a synchronous command, lives on the stack of the waiting caller. More...
struct  TimerCommand
 POD command record passed from the public API methods to the tick task via the command queue. More...

Public Types

enum  EConsts : size_t {
  TASK_COUNT = (1U + 1U ) ,
  TASK_TICK_MEMORY_SIZE = Max<size_t>(256U, STK_STACK_SIZE_MIN) ,
  TASK_HANDLER_STACK_SIZE = Max<size_t>( 256U , STK_STACK_SIZE_MIN)
}
enum  EResult : int8_t {
  RES_CANCELLED = -5 ,
  RES_INVALID_PARAM = -4 ,
  RES_QUEUE_FULL = -3 ,
  RES_NOT_READY = -2 ,
  RES_FAIL = -1 ,
  RES_OK = 0 ,
  RES_ACTIVE = 1 ,
  RES_INACTIVE = 2 ,
  RES_NOT_PERIODIC = 3 ,
  RES_QUEUED = 4
}
 Outcome of a command: returned by the asynchronous API (Start(), Stop(), ...) and by the synchronous API (StartSync() and the other *Sync() functions), see "Result codes" in TimerHost. More...
typedef ::stk::time::Timer Timer
 Alias of stk::time::Timer, keeps the former nested name TimerHost::Timer valid.

Public Member Functions

 TimerHost ()
 Default constructor. Zero-initializes all internal state.
 ~TimerHost ()=default
 Destructor.
EAddResult Initialize (IKernel *kernel, EAccessMode mode, const Config &cfg=Config())
 Initialize timer host instance.
void InitializePolled ()
 Initialize timer host instance in polled mode (no kernel tasks are created).
Timeout Process ()
 Run the host once (polled mode only): execute pending commands, evaluate deadlines and invoke OnExpired() of every expired timer inline.
EResult Start (Timer &tmr, uint32_t delay, uint32_t period=0)
 Start timer.
EResult Stop (Timer &tmr)
 Stop running timer.
EResult Reset (Timer &tmr)
 Reset periodic timer's deadline.
EResult Restart (Timer &tmr, uint32_t delay, uint32_t period=0)
 Atomically stop and re-start timer.
EResult StartOrReset (Timer &tmr, uint32_t delay, uint32_t period=0)
 Start timer if inactive, or reset its deadline if already active and periodic.
EResult SetPeriod (Timer &tmr, uint32_t period)
 Change the period of a running periodic timer without affecting its current deadline.
EResult StartSync (Timer &tmr, uint32_t delay, uint32_t period=0)
 Start timer and wait for the result (see "Synchronous API" in TimerHost).
EResult ActivateSync (Timer &tmr)
 Start timer with the delay and period stored in it and wait for the result.
EResult StopSync (Timer &tmr)
 Stop timer and wait for the result.
EResult RestartSync (Timer &tmr, uint32_t delay, uint32_t period=0)
 Atomically stop and re-start timer and wait for the result.
EResult ResetSync (Timer &tmr)
 Reset periodic timer's deadline and wait for the result.
EResult SetPeriodSync (Timer &tmr, uint32_t period)
 Change the period of a running periodic timer without affecting its current deadline and wait for the result.
EResult ChangeSync (Timer &tmr, uint32_t delay, uint32_t period)
 Change the delay and period of an inactive timer and wait for the result.
EResult QuerySync (Timer &tmr, TimerInfo &info)
 Get a consistent snapshot of the timer (evaluated by the tick task).
bool IsHostTid (TId tid)
 Check whether a task id belongs to a task of this host (tick or handler task).
bool IsEmpty () const
 Return true if no timers are currently active.
size_t GetSize () const
 Return number of currently active timers.
EResult Shutdown ()
 Shutdown host instance. All timers are stopped and removed from the host.
Ticks GetTimeNow () const
 Get current time.

Private Types

typedef void(* TimerFuncType) (TimerHost *host)
 Timer task function prototype.
typedef StackMemoryDef< TASK_TICK_MEMORY_SIZE >::Type TaskTickMemory
 Stack memory type for the single tick task.
typedef StackMemoryDef< TASK_HANDLER_STACK_SIZE >::Type TimerHostMemory
 Stack memory type for each handler task.
typedef detail::DListHead< Timer::ReadyNode, false > ReadyList
 Intrusive list of the expired timers (via Timer::m_ready_node) handed over from the tick task to the handler tasks. Protected by a critical section.
typedef sync::PipeT< TimerCommand, 32U > CommandQueue
 Lock-free pipe used to send TimerCommand records from API callers to the tick task.

Private Member Functions

 STK_NONCOPYABLE_CLASS (TimerHost)
void UpdateTime ()
 Tick task body: drives the timer list and dispatches expired timers.
Timeout ScanTimers (Ticks now)
 Evaluate all active timers against the given time.
void ProcessTimers ()
 Handler task body: dequeues expired timers from the ready list and invokes their OnExpired() callbacks.
bool ProcessCommands (Timeout next_sleep)
 Drain the command queue and execute each pending command.
EResult PushCommand (TimerCommand cmd, Timeout wait=NO_WAIT)
 Enqueue a command for the tick task.
bool CanWait () const
 Check whether the calling context can wait for the completion of a command.
void CancelPending (Timer &tmr)
 Cancel a pending (expired, not yet handled) expiration of the timer.
void WaitCallbackDone (Timer &tmr)
 Wait until no handler task is executing the callback of the timer.
EResult Execute (TimerCommand::EId id, Timer &tmr, uint32_t delay, uint32_t period, TimerInfo *info)
 Execute a command synchronously, or queue it if the caller can not wait.

Private Attributes

TaskTickMemory m_task_tick_memory
 tick task memory
TimerHostMemory m_task_handler_memory [1U]
 handler task memory
TimerWorkerTask m_task_tick
 timer task
TimerWorkerTask m_task_process [1U]
 handler tasks
detail::DListHead< Timer, false > m_active
 active timers (tick task only)
ReadyList m_ready_list
 expired timers waiting for a handler task (access only inside a critical section)
sync::Event m_ready_event
 auto-reset event which wakes a handler task when m_ready_list gets an entry or on shutdown
CommandQueue m_commands
 command queue
Ticks m_now
 last known current time (ticks)
bool m_polled
 true in polled mode (InitializePolled()), no tasks, callbacks run inline from Process()
volatile bool m_ready
 true while the host has a consumer of the command queue (initialized and not shut down)
volatile bool m_shutdown
 true once CMD_SHUTDOWN was received (task mode): handlers exit after draining m_ready_list
Timer *volatile m_running [1U]
 timers whose callback is being executed by a handler task (one slot per handler: set inside the claim critical section, cleared and polled lock-free), see WaitCallbackDone()
IKernel * m_kernel
 kernel of the task mode (nullptr in polled mode)
volatile TId m_tick_tid
 id of the tick task (TID_NONE until it runs), commands must not be waited for from it

Detailed Description

Software timer multiplexer that manages multiple Timer instances on top of a small fixed set of kernel tasks.

TimerHost has two operating modes:

In task mode TimerHost internally runs two categories of tasks:

  • One tick task that maintains the active timer list, evaluates deadlines every wake cycle, and queues expired timers for dispatch.
  • One or more handler tasks (see STK_TIMER_THREADS_COUNT) that dequeue expired timers and invoke their OnExpired() callbacks.

All timers share the same tick and handler tasks, so the total kernel task overhead is constant regardless of how many timers are active.

Two timer modes are supported:

  • One-shot: fires once after delay ticks and becomes inactive automatically.
  • Periodic: fires every period ticks until explicitly stopped.
Note
TimerHost must be initialized before use by calling Initialize() (task mode) or InitializePolled() (polled mode). The number of timers is not limited by TimerHost (STK_TIMER_COMMAND_QUEUE_SIZE is the capacity of the command queue). The maximum timer period is bounded by uint32_t (~49 days at 1 ms resolution).
Requires a kernel built with stk::KERNEL_SYNC: the command queue is stk::sync::Pipe based, the handler tasks are woken by a stk::sync::Event. The list of expired timers is intrusive (no capacity limit of its own, a Timer is queued at most once) and is protected by a critical section.
In task mode TimerHost occupies TASK_COUNT (1 + STK_TIMER_THREADS_COUNT) kernel task slots, make sure the kernel's task budget (e.g. Kernel::TASKS_MAX) accounts for them. Initialize() reports a failure to add a task (e.g. ADD_FAIL_POOL_FULL), in KERNEL_DYNAMIC mode such a failure is never asserted. Polled mode occupies no task slots.
Task mode is a soft real-time component: its tasks block on internal queues and are registered with IKernel::AddTask(ITask *). It cannot be used with a kernel running in stk::KERNEL_HRT mode (the kernel rejects the task with ADD_FAIL_INVALID and asserts), use polled mode there.
Scheduling weights
The tick task and the handler tasks are registered with the weights supplied via Config (see Initialize()), by default DEFAULT_WEIGHT is used for all of them. A weight is strategy-specific and is passed to the kernel unchanged, TimerHost does not interpret it:

It is recommended that the tick task is at least as urgent as the handler tasks, otherwise a long OnExpired() callback delays evaluation of all other deadlines.

Configuration examples (pick the one matching the strategy the kernel is built with, a kernel using sched::SwitchStrategyRoundRobin, sched::SwitchStrategyEDF or sched::SwitchStrategyMonotonic needs no Config):

// sched::SwitchStrategyFP32: real preemption priority
// sched::SwitchStrategyPT32: keep threshold == priority (no hold)
// sched::SwitchStrategySWRR: no preemption, only a larger share. Tick latency is bounded by rotation, not priority.
cfg.tick_weight = 4;
g_TimerHost.Initialize(kernel, stk::ACCESS_USER, cfg);
@ ACCESS_USER
Unprivileged access mode (access to some hardware is restricted, see CPU manual for details)....
Definition stk_common.h:37
static constexpr Weight MakeWeight(uint16_t priority, uint16_t threshold)
Optional configuration of the timer tasks, see Initialize().
Weight handler_weight
Weight of every handler task (default: DEFAULT_WEIGHT).
Weight tick_weight
Weight of the tick task (default: DEFAULT_WEIGHT).
Polled mode and HRT kernels
In polled mode TimerHost creates no kernel tasks, therefore the weights and stack buffers of Config do not apply. The application calls Process() periodically from a single context of its own and the OnExpired() callbacks of expired timers run inline from Process(). This is the way to use TimerHost with stk::KERNEL_HRT, where tasks are periodic jobs (IKernel::AddTask() with periodicity and deadline) and blocking on queues is not a job. Things to keep in mind:
  • the period of the driving job is the timer resolution: a timer fires on the first Process() call at or after its deadline, i.e. it may be late by up to one period;
  • callbacks run in the driving job, so the worst-case execution time of all callbacks which can expire in the same call is part of that job's WCET and of the schedulability analysis;
  • Start(), Stop() and the other commands may be issued from any task (callbacks included), they take effect at the next Process() call;
  • Process() never blocks, it uses non-blocking queue operations only.
// HRT kernel: a periodic job drives the timers
class TimerJob : public stk::Task<256, stk::ACCESS_USER>
{
public:
void Run()
{
for (;;)
{
g_TimerHost.Process(); // runs expired callbacks inline
stk::Yield(); // job completed, sleep until the next period
}
}
};
TimerJob g_TimerJob;
void SetupTimers(stk::IKernel *kernel)
{
g_TimerHost.InitializePolled();
// 5 ms timer resolution, 2 ms budget (callbacks included) per job
}
static void Yield()
Notify scheduler to switch to the next runnable task.
Definition stk_helper.h:562
static Timeout GetTicksFromMsClampedToTimeout(Timeout ms)
Convert milliseconds to ticks and clamp the result to a Timeout type.
Definition stk_helper.h:434
virtual void Run()=0
Entry point of the user task.
Interface for the implementation of the kernel of the scheduler. It supports Soft and Hard Real-Time ...
virtual EAddResult AddTask(ITask *user_task)=0
Add user task.
Partial implementation of the user task.
Definition stk_helper.h:98

Process() returns the number of ticks until the earliest deadline, a non-HRT application can use it to sleep only as long as needed (commands issued meanwhile are picked up when the sleep ends, hence the cap):

for (;;)
{
const stk::Timeout next = g_TimerHost.Process();
if (next != stk::NO_WAIT)
{
stk::Sleep((next < 100) ? next : 100);
}
}
static constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
Definition stk_common.h:280
static bool Sleep(Timeout tick_count)
Put calling process into a sleep state.
Definition stk_helper.h:495
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:216
// define a concrete timer by overriding OnExpired
class HeartbeatTimer : public stk::time::Timer
{
public:
{
// called every 500 ms
ToggleLed();
}
};
// declare host and timer instances (static storage, no heap)
HeartbeatTimer g_Heartbeat;
// one-shot example: send a delayed notification
class NotifyTimer : public stk::time::Timer
{
public:
{
g_Event.Signal();
}
};
NotifyTimer g_Notify;
void SetupTimers(stk::IKernel *kernel)
{
// initialize the host, must be called before Start() (default weights and internal stacks)
if (g_TimerHost.Initialize(kernel, stk::ACCESS_USER) != stk::ADD_OK)
{
// e.g. no free task slots in the kernel
return;
}
// start 500 ms periodic heartbeat
uint32_t period = static_cast<uint32_t>(stk::GetTicksFromMs(500));
if (g_TimerHost.Start(g_Heartbeat, period, period) != stk::time::TimerHost::RES_OK)
{
// e.g. RES_QUEUE_FULL (called from an ISR / before the kernel started), RES_ACTIVE, RES_NOT_READY
}
// start a one-shot notification after 1 second
uint32_t delay = static_cast<uint32_t>(stk::GetTicksFromMs(1000));
g_TimerHost.Start(g_Notify, delay);
}
@ ADD_OK
Task was added.
Definition stk_common.h:153
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:406
Abstract base class for a timer managed by TimerHost.
virtual void OnExpired(TimerHost *host)=0
Callback invoked when this timer expires.
Software timer multiplexer that manages multiple Timer instances on top of a small fixed set of kerne...
EResult Start(Timer &tmr, uint32_t delay, uint32_t period=0)
Start timer.
EAddResult Initialize(IKernel *kernel, EAccessMode mode, const Config &cfg=Config())
Initialize timer host instance.
@ RES_OK
Sync: the command was executed. Async: the command was accepted into the command queue.
Command queue
Commands of both APIs reach the tick task through a queue of STK_TIMER_COMMAND_QUEUE_SIZE entries (default 32). The macro is the capacity of this queue only, it does not limit the number of timers, which are intrusive and owned by the application: size it for the burst of commands which can be issued before the tick task runs, not for the number of timers. (STK_TIMER_COUNT_MAX is the deprecated name of this macro.) When the queue is full:
  • a caller which can wait (task context, task mode, kernel running, not the tick task) blocks until the tick task has drained a slot, no command is lost and nothing is asserted. An asynchronous call is therefore non-blocking only while the queue has room;
  • a caller which can not wait (ISR, kernel not started, polled mode, the tick task) gets RES_QUEUE_FULL, nothing is queued. A blocking call must not be made from a critical section or with interrupts disabled. The wait ends when a slot is free, or fails with RES_CANCELLED only if it is cancelled (IKernel::CancelTaskWait()).
Result codes
Every command (asynchronous and synchronous) returns an EResult. Negative values are errors: the command was not queued and not executed. Positive values report the state of the timer (the command was refused because its precondition does not hold) or that the outcome is unknown:
  • RES_OK: synchronous API - the command was executed. Asynchronous API - the command was accepted into the command queue (or coalesced with an identical one already waiting, see Restart()); it is executed later by the tick task and its outcome is not reported;
  • RES_ACTIVE, RES_INACTIVE, RES_NOT_PERIODIC: the timer is not in the state the command requires. The asynchronous API evaluates this from the unsynchronized state of the timer, so it is advisory: nothing is queued when it reports a mismatch, but a command which was accepted can still be dropped by the tick task if the state has changed meanwhile. Use the synchronous API for an exact outcome;
  • RES_QUEUED: synchronous API only, the calling context can not wait, the command was queued asynchronously;
  • RES_QUEUE_FULL, RES_CANCELLED: the command queue is full and the caller can not wait, or the wait was cancelled;
  • RES_NOT_READY: the host is not initialized, its initialization failed, or it has been shut down;
  • RES_INVALID_PARAM: an argument is out of range (e.g. a zero or too large period of SetPeriod());
  • RES_FAIL: unspecified failure.
Warning
RES_OK is 0. A check like if(host.Start(...)) which was written for the former bool return value means "failed" now, compare with RES_OK explicitly.
Synchronous API
The asynchronous commands (Start(), Stop(), ...) only queue a request: the result is evaluated later by the tick task, the caller gets RES_OK ("queued") or an error code (e.g. RES_QUEUE_FULL if it can not wait for a free slot), see "Result codes". The synchronous variants (StartSync(), StopSync(), RestartSync(), ResetSync(), SetPeriodSync(), ActivateSync(), ChangeSync(), QuerySync()) queue the same command together with a completion point and block the caller until the tick task has executed it, so the returned EResult is the exact outcome of the command (e.g. EResult::RES_ACTIVE for a timer which was already active). They also block while the command queue is full instead of failing, so the number of concurrent callers is not limited by STK_TIMER_COMMAND_QUEUE_SIZE (see "Command queue"). If the host is not initialized, every call returns RES_NOT_READY.
  • A sync call waits only where waiting is possible: task context, kernel running, task mode. From an ISR, before the kernel is started, while the scheduler is locked (IKernelService::LockScheduler(): the tick task can not run, and a StopSync() issued then does not wait for a running callback, so its "Timer may be released" guarantee does not apply), or in polled mode, the command is queued asynchronously and RES_QUEUED is returned (RES_QUEUE_FULL if the queue is full), QuerySync() returns an advisory snapshot instead. Callbacks may use the sync API in task mode (they run in handler tasks, the tick task never waits for them), in polled mode they get RES_QUEUED.
  • The tick task must be at least as urgent as every task which uses the sync API, otherwise a more urgent caller is blocked by a less urgent tick task (priority inversion). Configure the weights via Config.
  • A command with a completion is never coalesced (see Restart()), every caller gets its own result.
  • The wait is not abortable: if it is cancelled (IKernel::CancelTaskWait()) the call keeps waiting, the completion lives on the caller's stack and must outlive the tick task's access to it.
  • StopSync() (and every other command which cancels or re-arms a timer) removes an expiration which was already handed over to the handlers: expired timers wait in an intrusive ready list, one node per Timer, and the command unlinks the node before it completes. When StopSync() returns the host holds no queued reference to the Timer and no callback of that expiration will start. A callback which a handler task has already dequeued is not interrupted, StopSync() waits for it (polling every tick) before it returns, so after StopSync() the Timer is neither queued nor in use by the host and its storage can be released.
  • The wait for a running callback is skipped when StopSync() is called from a callback (a handler task): a callback which stops its own timer would wait for itself, and two callbacks stopping each other's timers would wait for each other. From a callback StopSync() guarantees only that no further callback of the timer starts. The asynchronous Stop() and the ISR / not-started / polled paths (RES_QUEUED) never wait either.
  • For ThreadX-like ordering of callbacks keep STK_TIMER_THREADS_COUNT at 1 (a single handler task runs the callbacks in expiration order, as the ThreadX timer thread does).
See also
Timer, TimerHost::Config, TimerHost::Process, TimerHost::InitializePolled, TimerHost::StartSync, STK_TIMER_THREADS_COUNT, STK_TIMER_HANDLER_STACK_SIZE, STK_TIMER_COMMAND_QUEUE_SIZE
Examples
debounce/example.cpp, httpd/example.cpp, httpd_tls/example.cpp, low_power/example.cpp, and timer/example.cpp.

Definition at line 433 of file stk_time_timer.h.

Member Typedef Documentation

◆ CommandQueue

Lock-free pipe used to send TimerCommand records from API callers to the tick task.

Definition at line 992 of file stk_time_timer.h.

◆ ReadyList

Intrusive list of the expired timers (via Timer::m_ready_node) handed over from the tick task to the handler tasks. Protected by a critical section.

Definition at line 987 of file stk_time_timer.h.

◆ TaskTickMemory

Stack memory type for the single tick task.

Definition at line 976 of file stk_time_timer.h.

◆ Timer

Alias of stk::time::Timer, keeps the former nested name TimerHost::Timer valid.

Note
Qualified on purpose and declared before any other use of the name Timer in this class: an unqualified "typedef Timer Timer;" changes the meaning of Timer inside the class (ill-formed, rejected by GCC).
Examples
timer/example.cpp.

Definition at line 485 of file stk_time_timer.h.

◆ TimerFuncType

typedef void(* stk::time::TimerHost::TimerFuncType) (TimerHost *host)
private

Timer task function prototype.

Definition at line 775 of file stk_time_timer.h.

◆ TimerHostMemory

Stack memory type for each handler task.

Definition at line 981 of file stk_time_timer.h.

Member Enumeration Documentation

◆ EConsts

Enumerator
TASK_COUNT 

total number of tasks serving this instance

stack memory size of the tick task

TASK_TICK_MEMORY_SIZE 

stack memory size of the timer handler task

TASK_HANDLER_STACK_SIZE 

Definition at line 436 of file stk_time_timer.h.

437 {
440
443
446 };
#define STK_STACK_SIZE_MIN
Minimum stack size in elements of Word, shared by all stack allocation lower-bound checks.
Definition stk_defs.h:646
#define STK_TIMER_THREADS_COUNT
Number of threads handling timers in TimerHost (default: 1).
#define STK_TIMER_HANDLER_STACK_SIZE
Stack size of the timer handler, increase if your timers consume more (default: 256).
constexpr T Max(T a, T b) noexcept
Compile-time maximum of two values.
Definition stk_defs.h:758
@ TASK_TICK_MEMORY_SIZE
stack memory size of the timer handler task
@ TASK_COUNT
total number of tasks serving this instance

◆ EResult

Outcome of a command: returned by the asynchronous API (Start(), Stop(), ...) and by the synchronous API (StartSync() and the other *Sync() functions), see "Result codes" in TimerHost.

Note
Negative values are errors (nothing was queued or executed), positive values report the state of the timer or an unknown outcome. The values of the existing codes are stable.
Enumerator
RES_CANCELLED 

The wait for a free command queue slot was cancelled (IKernel::CancelTaskWait()), nothing is queued.

RES_INVALID_PARAM 

An argument is out of range (e.g. zero period for SetPeriod()), nothing is queued.

RES_QUEUE_FULL 

The command queue is full and the caller can not wait (ISR, kernel not started, polled mode, tick task), nothing is queued.

RES_NOT_READY 

Host is not initialized (or its initialization failed), or it has been shut down.

RES_FAIL 

Unspecified failure.

RES_OK 

Sync: the command was executed. Async: the command was accepted into the command queue.

RES_ACTIVE 

The timer is active, but the command requires it to be inactive (start, activate, change).

RES_INACTIVE 

The timer is not active, but the command requires it to be active (stop, reset).

RES_NOT_PERIODIC 

The timer is not periodic, but the command requires it to be.

RES_QUEUED 

The calling context can not wait: the command was queued asynchronously, its outcome is unknown.

Definition at line 454 of file stk_time_timer.h.

455 {
456 RES_CANCELLED = -5,
457 RES_INVALID_PARAM = -4,
458 RES_QUEUE_FULL = -3,
459 RES_NOT_READY = -2,
460 RES_FAIL = -1,
461 RES_OK = 0,
462 RES_ACTIVE = 1,
463 RES_INACTIVE = 2,
464 RES_NOT_PERIODIC = 3,
465 RES_QUEUED = 4
466 };
@ RES_CANCELLED
The wait for a free command queue slot was cancelled (IKernel::CancelTaskWait()), nothing is queued.
@ RES_QUEUE_FULL
The command queue is full and the caller can not wait (ISR, kernel not started, polled mode,...
@ RES_NOT_PERIODIC
The timer is not periodic, but the command requires it to be.
@ RES_QUEUED
The calling context can not wait: the command was queued asynchronously, its outcome is unknown.
@ RES_INACTIVE
The timer is not active, but the command requires it to be active (stop, reset).
@ RES_INVALID_PARAM
An argument is out of range (e.g. zero period for SetPeriod()), nothing is queued.
@ RES_FAIL
Unspecified failure.
@ RES_NOT_READY
Host is not initialized (or its initialization failed), or it has been shut down.
@ RES_ACTIVE
The timer is active, but the command requires it to be inactive (start, activate, change).

Constructor & Destructor Documentation

◆ TimerHost()

stk::time::TimerHost::TimerHost ( )
inlineexplicit

Default constructor. Zero-initializes all internal state.

Note
Call Initialize() before using any other member function.

Definition at line 522 of file stk_time_timer.h.

524 m_active(), m_ready_list(), m_ready_event(false, false), m_now(0), m_polled(false), m_ready(false),
525 m_shutdown(false), m_running(), m_kernel(nullptr), m_tick_tid(TID_NONE)
526 {}
static constexpr TId TID_NONE
Reserved task/thread id representing zero/none thread id.
Definition stk_common.h:268
TimerWorkerTask m_task_process[1U]
handler tasks
TimerHostMemory m_task_handler_memory[1U]
handler task memory
sync::Event m_ready_event
auto-reset event which wakes a handler task when m_ready_list gets an entry or on shutdown
Ticks m_now
last known current time (ticks)
IKernel * m_kernel
kernel of the task mode (nullptr in polled mode)
TimerWorkerTask m_task_tick
timer task
TaskTickMemory m_task_tick_memory
tick task memory
ReadyList m_ready_list
expired timers waiting for a handler task (access only inside a critical section)
volatile TId m_tick_tid
id of the tick task (TID_NONE until it runs), commands must not be waited for from it
volatile bool m_shutdown
true once CMD_SHUTDOWN was received (task mode): handlers exit after draining m_ready_list
Timer *volatile m_running[1U]
timers whose callback is being executed by a handler task (one slot per handler: set inside the claim...
volatile bool m_ready
true while the host has a consumer of the command queue (initialized and not shut down)
detail::DListHead< Timer, false > m_active
active timers (tick task only)
bool m_polled
true in polled mode (InitializePolled()), no tasks, callbacks run inline from Process()

References m_active, m_kernel, m_now, m_polled, m_ready, m_ready_event, m_ready_list, m_running, m_shutdown, m_task_handler_memory, m_task_process, m_task_tick, m_task_tick_memory, m_tick_tid, and stk::TID_NONE.

Referenced by Initialize(), stk::time::TimerHost::TimerWorkerTask::Initialize(), and STK_NONCOPYABLE_CLASS().

Here is the caller graph for this function:

◆ ~TimerHost()

stk::time::TimerHost::~TimerHost ( )
default

Destructor.

Note
MISRA deviation: [STK-DEV-005] Rule 10-3-2.

Member Function Documentation

◆ ActivateSync()

TimerHost::EResult stk::time::TimerHost::ActivateSync ( Timer & tmr)
inline

Start timer with the delay and period stored in it and wait for the result.

Parameters
[in]tmrTimer instance. Must not be active.
Returns
RES_OK, RES_ACTIVE if the timer is already active, RES_QUEUED, or an error code (RES_NOT_READY, RES_QUEUE_FULL, RES_CANCELLED).
Note
The parameters are those of the last StartSync(), Start(), Restart() or ChangeSync() (the expiration is relative to the moment of the call).

Definition at line 2080 of file stk_time_timer.h.

2081{
2082 return Execute(TimerCommand::CMD_ACTIVATE, tmr, 0U, 0U, nullptr);
2083}
EResult Execute(TimerCommand::EId id, Timer &tmr, uint32_t delay, uint32_t period, TimerInfo *info)
Execute a command synchronously, or queue it if the caller can not wait.
@ CMD_ACTIVATE
start with the delay and period stored in the timer

References stk::time::TimerHost::TimerCommand::CMD_ACTIVATE, and Execute().

Referenced by stk_timer_activate_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CancelPending()

void stk::time::TimerHost::CancelPending ( Timer & tmr)
inlineprivate

Cancel a pending (expired, not yet handled) expiration of the timer.

Parameters
[in]tmrTimer instance.

Clears Timer::m_pending and, in task mode, unlinks the timer's node from the ready list, so no handler task can dequeue it afterwards and the host holds no queued reference to tmr. Atomic with the dequeue done by a handler task: if the handler got there first, the callback is already claimed and runs (it is not interrupted).

Note
Tick task only (commands) and in polled mode. Takes a critical section in task mode.

Definition at line 1928 of file stk_time_timer.h.

1929{
1930 if (m_polled)
1931 {
1932 // callbacks run inline from Process(), nothing is ever queued
1933 tmr.m_pending = false;
1934 }
1935 else
1936 {
1937 // atomic with the claim done by a handler task (ProcessTimers): either the handler has dequeued the
1938 // timer already (it runs the callback, too late to cancel) or it finds nothing and never sees the timer
1939 hw::CriticalSection::ScopedLock cs;
1940
1941 if (tmr.m_ready_node.IsLinked())
1942 {
1943 m_ready_list.Unlink(&tmr.m_ready_node);
1944 }
1945
1946 tmr.m_pending = false;
1947 }
1948}

References stk::detail::DListEntry< T, TClosedLoop >::IsLinked(), stk::time::Timer::m_pending, m_polled, m_ready_list, and stk::time::Timer::m_ready_node.

Referenced by ProcessCommands().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CanWait()

bool stk::time::TimerHost::CanWait ( ) const
inlineprivate

Check whether the calling context can wait for the completion of a command.

Returns
True in task mode, from a task (not ISR, not the tick task), with the kernel running (not locked: KSTATE_LOCKED reads as "can not wait") and the host initialized.

Definition at line 1919 of file stk_time_timer.h.

1920{
1921 // Task mode only (polled mode has no tick task to complete the command), from a task which is not the tick
1922 // task (the tick task completes the commands), not from an ISR, with the kernel scheduling (otherwise
1923 // nobody runs the tick task).
1924 return (m_ready && !m_polled && (m_kernel != nullptr) && !hw::IsInsideISR() &&
1925 (m_kernel->GetState() == IKernel::KSTATE_RUNNING) && (GetTid() != m_tick_tid));
1926}
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:374
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
@ KSTATE_RUNNING
Initialized and running, IKernel::Start() was called successfully.

References stk::GetTid(), stk::hw::IsInsideISR(), stk::IKernel::KSTATE_RUNNING, m_kernel, m_polled, m_ready, and m_tick_tid.

Referenced by Execute(), and PushCommand().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ChangeSync()

TimerHost::EResult stk::time::TimerHost::ChangeSync ( Timer & tmr,
uint32_t delay,
uint32_t period )
inline

Change the delay and period of an inactive timer and wait for the result.

Parameters
[in]tmrTimer instance. Must not be active.
[in]delayNew initial delay in ticks.
[in]periodNew reload period in ticks (0 is one-shot timer).
Returns
RES_OK, RES_ACTIVE if the timer is active (nothing is changed), RES_QUEUED, or an error code (RES_NOT_READY, RES_QUEUE_FULL, RES_CANCELLED).
Note
The timer is not started, the values are used by the next ActivateSync().

Definition at line 2112 of file stk_time_timer.h.

2113{
2114 return Execute(TimerCommand::CMD_CHANGE, tmr, delay, period, nullptr);
2115}
@ CMD_CHANGE
store delay and period of an inactive timer (does not start it)

References stk::time::TimerHost::TimerCommand::CMD_CHANGE, and Execute().

Referenced by stk_timer_change_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Execute()

TimerHost::EResult stk::time::TimerHost::Execute ( TimerCommand::EId id,
Timer & tmr,
uint32_t delay,
uint32_t period,
TimerInfo * info )
inlineprivate

Execute a command synchronously, or queue it if the caller can not wait.

Parameters
[in]idCommand id.
[in]tmrTarget timer.
[in]delayDelay argument of the command.
[in]periodPeriod argument of the command.
[out]infoSnapshot for CMD_QUERY, otherwise nullptr.
Returns
Outcome of the command, RES_QUEUED or an error code.

Definition at line 1982 of file stk_time_timer.h.

1984{
1985 STK_ASSERT(delay <= static_cast<uint32_t>(WAIT_INFINITE));
1986 STK_ASSERT((period == 0U) || (period <= static_cast<uint32_t>(WAIT_INFINITE)));
1987
1988 EResult result = RES_NOT_READY;
1989
1990 if (!m_ready)
1991 {
1992 // not initialized, initialization failed or shut down: nobody consumes the command queue
1993 }
1994 else if (CanWait())
1995 {
1996 // the completion is owned by this frame: the tick task makes its last access with Set()
1997 Completion completion;
1998
1999 const EResult queued = PushCommand({
2000 .cmd = id,
2001 .timer = &tmr,
2002 .timestamp = GetTicks(),
2003 .delay = delay,
2004 .period = period,
2005 .completion = &completion
2006 }, WAIT_INFINITE);
2007
2008 if (queued == RES_OK)
2009 {
2010 // keep waiting if the wait is cancelled (IKernel::CancelTaskWait()): returning would leave
2011 // the tick task with a pointer to a dead stack frame
2012 EWaitResult wr;
2013 do
2014 {
2015 wr = completion.done.WaitEx(WAIT_INFINITE);
2016
2017 if (wr == WAIT_RESULT_FAIL)
2018 {
2019 Sleep(1); // not expected, do not spin
2020 }
2021 }
2022 while (wr != WAIT_RESULT_SIGNAL);
2023
2024 result = completion.result;
2025
2026 if (info != nullptr)
2027 {
2028 *info = completion.info;
2029 }
2030
2031 // a stop completes only when the callback which a handler already started (if any) has returned,
2032 // the timer was unlinked from the ready list by the tick task so no other callback can start
2033 if ((id == TimerCommand::CMD_STOP) && ((result == RES_OK) || (result == RES_INACTIVE)))
2034 {
2035 WaitCallbackDone(tmr);
2036 }
2037 }
2038 else
2039 {
2040 // nothing was queued (e.g. the wait for a free slot was cancelled)
2041 result = queued;
2042 }
2043 }
2044 else if (id == TimerCommand::CMD_QUERY)
2045 {
2046 // can not wait (ISR, kernel not started, polled mode, ...): advisory snapshot
2047 if (info != nullptr)
2048 {
2049 info->active = tmr.m_active;
2050 info->delay = tmr.m_delay;
2051 info->period = tmr.m_period;
2052 info->remaining = tmr.GetRemainingTicks();
2053 }
2054
2055 result = RES_OK;
2056 }
2057 else
2058 {
2059 // can not wait: queue it asynchronously, the outcome is unknown to the caller
2060 const EResult queued = PushCommand({
2061 .cmd = id,
2062 .timer = &tmr,
2063 .timestamp = GetTicks(),
2064 .delay = delay,
2065 .period = period,
2066 .completion = nullptr
2067 });
2068
2069 result = ((queued == RES_OK) ? RES_QUEUED : queued);
2070 }
2071
2072 return result;
2073}
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
EWaitResult
Wait result (see IKernelService::Wait).
Definition stk_common.h:138
@ WAIT_RESULT_FAIL
IKernelService::Wait returned with error without waiting.
Definition stk_common.h:139
@ WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_common.h:140
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:448
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274
bool CanWait() const
Check whether the calling context can wait for the completion of a command.
EResult PushCommand(TimerCommand cmd, Timeout wait=NO_WAIT)
Enqueue a command for the tick task.
EResult
Outcome of a command: returned by the asynchronous API (Start(), Stop(), ...) and by the synchronous ...
void WaitCallbackDone(Timer &tmr)
Wait until no handler task is executing the callback of the timer.
Completion point of a synchronous command, lives on the stack of the waiting caller.
@ CMD_QUERY
fill TimerInfo of the timer (synchronous only)

References stk::time::TimerHost::TimerInfo::active, CanWait(), stk::time::TimerHost::TimerCommand::CMD_QUERY, stk::time::TimerHost::TimerCommand::CMD_STOP, stk::time::TimerHost::TimerInfo::delay, stk::time::TimerHost::Completion::done, stk::time::Timer::GetRemainingTicks(), stk::GetTicks(), stk::time::TimerHost::Completion::info, stk::time::Timer::m_active, stk::time::Timer::m_delay, stk::time::Timer::m_period, m_ready, stk::time::TimerHost::TimerInfo::period, PushCommand(), stk::time::TimerHost::TimerInfo::remaining, RES_INACTIVE, RES_NOT_READY, RES_OK, RES_QUEUED, stk::time::TimerHost::Completion::result, stk::Sleep(), STK_ASSERT, stk::WAIT_INFINITE, stk::WAIT_RESULT_FAIL, stk::WAIT_RESULT_SIGNAL, WaitCallbackDone(), and stk::sync::Event::WaitEx().

Referenced by ActivateSync(), ChangeSync(), QuerySync(), ResetSync(), RestartSync(), SetPeriodSync(), StartSync(), and StopSync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetSize()

size_t stk::time::TimerHost::GetSize ( ) const
inline

Return number of currently active timers.

Returns
Active timer count.
Note
The value is advisory and may change immediately after the call.

Definition at line 755 of file stk_time_timer.h.

755{ return m_active.GetSize(); }

References m_active.

Referenced by stk_timerhost_get_size().

Here is the caller graph for this function:

◆ GetTimeNow()

Ticks stk::time::TimerHost::GetTimeNow ( ) const
inline

Get current time.

Returns
Current time (ticks).

Definition at line 767 of file stk_time_timer.h.

767{ return hw::ReadVolatile64(&m_now); }
T ReadVolatile64(volatile const T *addr)
Atomically read a 64-bit volatile value.
Definition stk_arch.h:332

References m_now, and stk::hw::ReadVolatile64().

Referenced by stk_timerhost_get_time_now().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Initialize()

EAddResult stk::time::TimerHost::Initialize ( IKernel * kernel,
EAccessMode mode,
const Config & cfg = Config() )
inline

Initialize timer host instance.

Parameters
[in]kernelKernel to which instance will be bound.
[in]modeAccess mode for the timer handling tasks which call expired timers. The access mode of the tick task is Config::tick_mode (ACCESS_USER by default).
[in]cfgWeights, access mode of the tick task and (optionally) stack buffers of the tick and handler tasks, by default DEFAULT_WEIGHT, ACCESS_USER and the internal stacks are used (see Config).
Returns
ADD_OK on success, otherwise the first failure reported by IKernel::AddTask(ITask *), e.g. ADD_FAIL_POOL_FULL if the kernel has no free task slots, ADD_FAIL_DUPLICATE if a stack is shared, or ADD_FAIL_INVALID (e.g. KERNEL_HRT kernel or kernel not initialized).
Note
Must be called before Start() of a KERNEL_STATIC kernel and after the kernel was initialized.
On failure the host is unusable. Tasks added before the failure remain registered with the kernel (blocked on the empty ready list), in KERNEL_DYNAMIC mode they can be released with IKernel::ScheduleTaskRemoval().
Warning
With sched::SwitchStrategyPreemptionThreshold the weights in cfg must be set explicitly, the default weight is not neutral for this strategy (see "Scheduling weights" in TimerHost).
Examples
httpd/example.cpp, httpd_tls/example.cpp, and low_power/example.cpp.

Definition at line 1039 of file stk_time_timer.h.

1040{
1041 STK_ASSERT(kernel != nullptr);
1042 STK_ASSERT(cfg.tick_weight != NO_WEIGHT);
1043 STK_ASSERT(cfg.handler_weight != NO_WEIGHT);
1044
1045 m_polled = false; // task mode (selects the mode again if the host was used in polled mode before)
1046 m_ready = false; // accepts commands only once both tasks have been added
1047 m_shutdown = false; // handlers keep running (a re-initialization after Shutdown())
1048 m_kernel = kernel;
1049
1050 EAddResult result = ADD_OK;
1051
1052 // handler tasks first: they only wait on the (empty) ready list until the tick task is added
1053 for (size_t i = 0U; (i < STK_TIMER_THREADS_COUNT) && (result == ADD_OK); ++i)
1054 {
1055 Word *stack = m_task_handler_memory[i];
1056 size_t size = TASK_HANDLER_STACK_SIZE;
1057
1058 if (cfg.handler_stack[i] != nullptr)
1059 {
1060 stack = cfg.handler_stack[i];
1061 size = cfg.handler_stack_size;
1062 }
1063
1065
1066 m_task_process[i].Initialize(this, stack, size, mode, cfg.handler_weight, [](TimerHost *host)
1067 {
1068 host->ProcessTimers();
1069 });
1070 result = kernel->AddTask(&m_task_process[i]);
1071 }
1072
1073 if (result == ADD_OK)
1074 {
1075 Word *stack = m_task_tick_memory;
1076 size_t size = TASK_TICK_MEMORY_SIZE;
1077
1078 if (cfg.tick_stack != nullptr)
1079 {
1080 stack = cfg.tick_stack;
1081 size = cfg.tick_stack_size;
1082 }
1083
1085
1086 m_task_tick.Initialize(this, stack, size, cfg.tick_mode, cfg.tick_weight, [](TimerHost *host)
1087 {
1088 host->UpdateTime();
1089 });
1090 result = kernel->AddTask(&m_task_tick);
1091 }
1092
1093 // commands are accepted from now on (the tick task is added, it drains the queue once it is scheduled)
1094 m_ready = (result == ADD_OK);
1095
1096 return result;
1097}
uintptr_t Word
Native processor word type.
Definition stk_common.h:206
EAddResult
Result of IKernel::AddTask() (both the Soft Real-Time and the Hard Real-Time overloads).
Definition stk_common.h:149
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:285
TimerHost()
Default constructor. Zero-initializes all internal state.

References stk::ADD_OK, stk::IKernel::AddTask(), stk::time::TimerHost::Config::handler_stack, stk::time::TimerHost::Config::handler_stack_size, stk::time::TimerHost::Config::handler_weight, m_kernel, m_polled, m_ready, m_shutdown, m_task_handler_memory, m_task_process, m_task_tick, m_task_tick_memory, stk::NO_WEIGHT, STK_ASSERT, STK_STACK_SIZE_MIN, STK_TIMER_THREADS_COUNT, TASK_HANDLER_STACK_SIZE, TASK_TICK_MEMORY_SIZE, stk::time::TimerHost::Config::tick_mode, stk::time::TimerHost::Config::tick_stack, stk::time::TimerHost::Config::tick_stack_size, stk::time::TimerHost::Config::tick_weight, and TimerHost().

Referenced by cy_rtos_stk_kernel_init(), stk::interop_c_helper::InitializeTimerHost(), stk::interop_c_helper::InitializeTimerHostEx(), and RunExample().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializePolled()

void stk::time::TimerHost::InitializePolled ( )
inline

Initialize timer host instance in polled mode (no kernel tasks are created).

The application drives the host by calling Process() periodically. Expired timers are handled inline, from the context which calls Process(), see "Polled mode and HRT kernels" in TimerHost. This is the mode to use with a stk::KERNEL_HRT kernel.

Note
Mutually exclusive with Initialize(), call one of them before any other member function. After Shutdown() the host can be initialized again in either mode. No kernel is involved, therefore it can not fail and does not depend on kernel mode, task slots, weights or stack buffers (see Config).

Definition at line 1420 of file stk_time_timer.h.

1421{
1422 m_polled = true;
1423 m_kernel = nullptr;
1424 m_ready = true;
1425}

References m_kernel, m_polled, and m_ready.

Referenced by stk_timerhost_init_polled().

Here is the caller graph for this function:

◆ IsEmpty()

bool stk::time::TimerHost::IsEmpty ( ) const
inline

Return true if no timers are currently active.

Returns
True if active timer count is zero.
Note
The value is advisory and may change immediately after the call.

Definition at line 749 of file stk_time_timer.h.

749{ return m_active.IsEmpty(); }

References m_active.

Referenced by stk_timerhost_is_empty().

Here is the caller graph for this function:

◆ IsHostTid()

bool stk::time::TimerHost::IsHostTid ( TId tid)
inline

Check whether a task id belongs to a task of this host (tick or handler task).

Parameters
[in]tidTask id, e.g. from GetTid().
Returns
True in task mode if tid is the tick task or one of the handler tasks, i.e. the caller is running TimerHost code or an OnExpired() callback. Always false in polled mode.
Note
Lets an application layer tell its own tasks from the host's tasks, e.g. to map GetTid() to its own thread object.

Definition at line 728 of file stk_time_timer.h.

729 {
730 bool result = false;
731
732 if (!m_polled && (tid != TID_NONE))
733 {
734 result = (tid == GetTidFromUserTask(&m_task_tick));
735
736 for (size_t i = 0U; (i < STK_TIMER_THREADS_COUNT) && !result; ++i)
737 {
738 result = (tid == GetTidFromUserTask(&m_task_process[i]));
739 }
740 }
741
742 return result;
743 }
TId GetTidFromUserTask(const ITask *task) noexcept
Get task identifier from ITask instance.
Definition stk_arch.h:775

References stk::GetTidFromUserTask(), m_polled, m_task_process, m_task_tick, STK_TIMER_THREADS_COUNT, and stk::TID_NONE.

Referenced by WaitCallbackDone().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Process()

Timeout stk::time::TimerHost::Process ( )
inline

Run the host once (polled mode only): execute pending commands, evaluate deadlines and invoke OnExpired() of every expired timer inline.

Returns
Ticks until the earliest active deadline: NO_WAIT if a timer is already overdue (call again without delay), WAIT_INFINITE if no timer is active.
Note
Never blocks. Call it periodically from one context only, not concurrently and not from OnExpired(). Start(), Stop() and the other commands remain callable from any task.
Resolution: a timer fires on the first call at or after its deadline. A periodic timer which is overdue by more than its period fires once per call until its schedule has caught up (no drift is accumulated).
Callbacks run one after another with the time sampled at the start of the call, a slow callback delays the following ones. Commands issued by a callback take effect at the next call.
Shutdown() stops and removes all timers, the host stays usable afterwards (there are no tasks to exit).
Warning
Only valid after InitializePolled().

Definition at line 1431 of file stk_time_timer.h.

1432{
1434
1435 // execute pending commands, never blocks in polled mode
1437
1438 return ScanTimers(GetTicks());
1439}
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
Timeout ScanTimers(Ticks now)
Evaluate all active timers against the given time.
bool ProcessCommands(Timeout next_sleep)
Drain the command queue and execute each pending command.

References stk::GetTicks(), m_polled, stk::NO_WAIT, ProcessCommands(), ScanTimers(), STK_ASSERT, and STK_UNUSED.

Referenced by stk_timerhost_process().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProcessCommands()

bool stk::time::TimerHost::ProcessCommands ( Timeout next_sleep)
inlineprivate

Drain the command queue and execute each pending command.

Parameters
[in]next_sleepMaximum ticks to block waiting for the first command when the active list is non-empty. Overridden to WAIT_INFINITE when empty (task mode only, polled mode never blocks).
Returns
True to continue the tick loop; false when CMD_SHUTDOWN is processed.
Note
Called exclusively from the tick task (UpdateTime()).

Definition at line 1540 of file stk_time_timer.h.

1541{
1542 TimerCommand cmd = {};
1543 bool working = true;
1544
1545 // if nothing is active, sleep indefinitely until a command arrives (task mode only,
1546 // polled mode never blocks)
1547 if (m_active.IsEmpty() && !m_polled)
1548 {
1549 next_sleep = WAIT_INFINITE;
1550 }
1551
1552 while (working)
1553 {
1554 if (!m_commands.Read(cmd, next_sleep))
1555 {
1556 break;
1557 }
1558
1559 // outcome reported to a synchronous caller (ignored for an asynchronous command)
1560 EResult res = RES_OK;
1561 TimerInfo info = {};
1562
1563 switch (cmd.cmd)
1564 {
1566 {
1567 Timer *const tmr = cmd.timer;
1568 STK_ASSERT(tmr != nullptr);
1569
1570 // reject if already active or linked (double-start)
1571 if (!tmr->m_active)
1572 {
1573 STK_ASSERT(!tmr->IsLinked());
1574
1575 tmr->m_deadline = cmd.timestamp + static_cast<Ticks>(cmd.delay);
1576 tmr->m_delay = cmd.delay;
1577 tmr->m_period = cmd.period;
1578 tmr->m_active = true;
1579 CancelPending(*tmr); // drops an expiration of a previous run which was not handled yet
1580
1581 m_active.LinkBack(tmr);
1582 next_sleep = NO_WAIT;
1583 }
1584 else
1585 {
1586 res = RES_ACTIVE;
1587 }
1588
1589 break; }
1590
1592 {
1593 Timer *const tmr = cmd.timer;
1594 STK_ASSERT(tmr != nullptr);
1595
1596 // start with the delay and period stored in the timer
1597 if (!tmr->m_active)
1598 {
1599 STK_ASSERT(!tmr->IsLinked());
1600
1601 tmr->m_deadline = cmd.timestamp + static_cast<Ticks>(tmr->m_delay);
1602 tmr->m_active = true;
1603 CancelPending(*tmr);
1604
1605 m_active.LinkBack(tmr);
1606 next_sleep = NO_WAIT;
1607 }
1608 else
1609 {
1610 res = RES_ACTIVE;
1611 }
1612
1613 break; }
1614
1616 {
1617 Timer *const tmr = cmd.timer;
1618 STK_ASSERT(tmr != nullptr);
1619
1620 res = (tmr->m_active ? RES_OK : RES_INACTIVE);
1621
1622 tmr->m_active = false;
1623
1624 // unlinks an expiration which is queued for a handler but was not started yet: once this command
1625 // completed no queued reference to the timer is left (a callback already running is not affected)
1626 CancelPending(*tmr);
1627
1628 // allow possibly duplicate CMD_STOP as it is harmless for the logic
1629 if (tmr->IsLinked())
1630 {
1631 m_active.Unlink(tmr);
1632 }
1633
1634 break; }
1635
1637 {
1638 Timer *const tmr = cmd.timer;
1639 STK_ASSERT(tmr != nullptr);
1640
1641 // only reset if still active and periodic
1642 if (tmr->m_active && (tmr->m_period != 0U))
1643 {
1644 STK_ASSERT(tmr->GetHead() == &m_active);
1645
1646 tmr->m_deadline = cmd.timestamp + static_cast<Ticks>(tmr->m_period);
1647 CancelPending(*tmr);
1648
1649 next_sleep = NO_WAIT;
1650 }
1651 else
1652 {
1653 res = (tmr->m_active ? RES_NOT_PERIODIC : RES_INACTIVE);
1654 }
1655
1656 break; }
1657
1659 {
1660 // atomic stop + re-start: no precondition on current timer state
1661 Timer *const tmr = cmd.timer;
1662 STK_ASSERT(tmr != nullptr);
1663
1664 // unlink if currently in the active list
1665 if (tmr->IsLinked())
1666 {
1667 m_active.Unlink(tmr);
1668 }
1669
1670 // re-arm with fresh parameters
1671 tmr->m_deadline = cmd.timestamp + static_cast<Ticks>(cmd.delay);
1672 tmr->m_delay = cmd.delay;
1673 tmr->m_period = cmd.period;
1674 tmr->m_active = true;
1675 tmr->m_rearming = false;
1676 CancelPending(*tmr);
1677
1678 // re-link to the back of the list
1679 m_active.LinkBack(tmr);
1680 next_sleep = NO_WAIT;
1681
1682 break; }
1683
1685 {
1686 Timer *const tmr = cmd.timer;
1687 STK_ASSERT(tmr != nullptr);
1688
1689 // not currently active: start with supplied parameters
1690 if (!tmr->m_active)
1691 {
1692 STK_ASSERT(!tmr->IsLinked());
1693
1694 tmr->m_deadline = cmd.timestamp + static_cast<Ticks>(cmd.delay);
1695 tmr->m_delay = cmd.delay;
1696 tmr->m_period = cmd.period;
1697 tmr->m_active = true;
1698 tmr->m_rearming = false;
1699 CancelPending(*tmr);
1700
1701 m_active.LinkBack(tmr);
1702 }
1703 // active and periodic: reset deadline anchored to call-site timestamp
1704 else if (tmr->m_period != 0U)
1705 {
1706 STK_ASSERT(tmr->GetHead() == &m_active);
1707
1708 tmr->m_deadline = cmd.timestamp + static_cast<Ticks>(tmr->m_period);
1709 CancelPending(*tmr);
1710 }
1711 else
1712 {
1713 res = RES_NOT_PERIODIC;
1714 }
1715
1716 // active one-shot: no action - cannot reset a one-shot mid-flight,
1717 // caller should use Restart() if unconditional re-arm is needed
1718
1719 next_sleep = NO_WAIT;
1720
1721 break; }
1722
1724 {
1725 Timer *const tmr = cmd.timer;
1726 STK_ASSERT(tmr != nullptr);
1727 STK_ASSERT(cmd.period != 0U);
1728
1729 // guard: only apply if still active and periodic
1730 if (tmr->m_active && (tmr->m_period != 0U))
1731 {
1732 STK_ASSERT(tmr->GetHead() == &m_active);
1733
1734 // new period takes effect on the next reload, current deadline is
1735 // intentionally left unchanged so the in-flight interval is not
1736 // truncated or extended, caller can follow up with Reset() if
1737 // immediate application is required
1738 tmr->m_period = cmd.period;
1739 }
1740 else
1741 {
1742 res = (tmr->m_active ? RES_NOT_PERIODIC : RES_INACTIVE);
1743 }
1744
1745 break; }
1746
1748 {
1749 Timer *const tmr = cmd.timer;
1750 STK_ASSERT(tmr != nullptr);
1751
1752 // parameters of an active timer can not be changed (stop it first), the timer is not started here
1753 if (!tmr->m_active)
1754 {
1755 tmr->m_delay = cmd.delay;
1756 tmr->m_period = cmd.period;
1757 }
1758 else
1759 {
1760 res = RES_ACTIVE;
1761 }
1762
1763 break; }
1764
1766 {
1767 Timer *const tmr = cmd.timer;
1768 STK_ASSERT(tmr != nullptr);
1769
1770 // evaluated by the tick task, so all fields belong to the same moment
1771 info.active = tmr->m_active;
1772 info.delay = tmr->m_delay;
1773 info.period = tmr->m_period;
1774 info.remaining = 0U;
1775
1776 if (tmr->m_active)
1777 {
1778 const Ticks left = tmr->m_deadline - GetTicks();
1779
1780 if (left > 0)
1781 {
1782 info.remaining = static_cast<uint32_t>(left);
1783 }
1784 }
1785
1786 break; }
1787
1789 {
1790 if (m_polled)
1791 {
1792 // no tasks to stop: stop and release all timers, the host stays usable
1794 while (tmr != nullptr)
1795 {
1796 m_active.Unlink(tmr);
1797
1798 tmr->m_active = false;
1799 tmr->m_pending = false;
1800 tmr->m_rearming = false;
1801
1803 }
1804 }
1805 else
1806 {
1807 // handler tasks drain the ready list and exit: the flag is published before the wake-up,
1808 // every exiting handler wakes the next one (the event is auto-reset)
1809 m_shutdown = true;
1810 __stk_full_memfence();
1811
1813
1814 // signal UpdateTime() to exit its loop
1815 working = false;
1816 }
1817
1818 break; }
1819
1820 default:
1821 {
1822 STK_ASSERT(false);
1823 res = RES_FAIL;
1824
1825 break; }
1826 }
1827
1828 // complete a synchronous command: the result is published first, Set() is the last access to the
1829 // completion because the waiting caller owns it (stack) and may return right after it is woken
1830 if (cmd.completion != nullptr)
1831 {
1832 Completion *const completion = cmd.completion;
1833
1834 completion->info = info;
1835 completion->result = res;
1836 __stk_full_memfence();
1837
1838 STK_UNUSED(completion->done.Set());
1839 }
1840 }
1841
1842 return working;
1843}
int64_t Ticks
Ticks value.
Definition stk_common.h:221
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Casts an intrusive list entry to the concrete type that derives from it.
void CancelPending(Timer &tmr)
Cancel a pending (expired, not yet handled) expiration of the timer.
::stk::time::Timer Timer
Alias of stk::time::Timer, keeps the former nested name TimerHost::Timer valid.
CommandQueue m_commands
command queue
Consistent snapshot of a timer, see QuerySync().
TimerInfo info
snapshot (CMD_QUERY only)
POD command record passed from the public API methods to the tick task via the command queue.
@ CMD_SET_PERIOD
change period of a running periodic timer
@ CMD_START_OR_RESET
start if inactive, reset deadline if active and periodic
@ CMD_RESTART
atomic stop + re-start

References stk::time::TimerHost::TimerInfo::active, CancelPending(), stk::time::TimerHost::TimerCommand::cmd, stk::time::TimerHost::TimerCommand::CMD_ACTIVATE, stk::time::TimerHost::TimerCommand::CMD_CHANGE, stk::time::TimerHost::TimerCommand::CMD_QUERY, stk::time::TimerHost::TimerCommand::CMD_RESET, stk::time::TimerHost::TimerCommand::CMD_RESTART, stk::time::TimerHost::TimerCommand::CMD_SET_PERIOD, stk::time::TimerHost::TimerCommand::CMD_SHUTDOWN, stk::time::TimerHost::TimerCommand::CMD_START, stk::time::TimerHost::TimerCommand::CMD_START_OR_RESET, stk::time::TimerHost::TimerCommand::CMD_STOP, stk::time::TimerHost::TimerCommand::completion, stk::time::TimerHost::TimerCommand::delay, stk::time::TimerHost::TimerInfo::delay, stk::time::TimerHost::Completion::done, stk::detail::DListEntry< T, TClosedLoop >::GetHead(), stk::GetTicks(), stk::time::TimerHost::Completion::info, stk::detail::DListEntry< T, TClosedLoop >::IsLinked(), stk::detail::DListCast::ListEntryToParent(), stk::time::Timer::m_active, m_active, m_commands, stk::time::Timer::m_deadline, stk::time::Timer::m_delay, stk::time::Timer::m_pending, stk::time::Timer::m_period, m_polled, m_ready_event, stk::time::Timer::m_rearming, m_shutdown, stk::NO_WAIT, stk::time::TimerHost::TimerCommand::period, stk::time::TimerHost::TimerInfo::period, stk::time::TimerHost::TimerInfo::remaining, RES_ACTIVE, RES_FAIL, RES_INACTIVE, RES_NOT_PERIODIC, RES_OK, stk::time::TimerHost::Completion::result, stk::sync::Event::Set(), STK_ASSERT, STK_UNUSED, stk::time::TimerHost::TimerCommand::timer, stk::time::TimerHost::TimerCommand::timestamp, and stk::WAIT_INFINITE.

Referenced by Process(), and UpdateTime().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProcessTimers()

void stk::time::TimerHost::ProcessTimers ( )
inlineprivate

Handler task body: dequeues expired timers from the ready list and invokes their OnExpired() callbacks.

Note
Runs in each handler task context. Blocks on the ready event while the list is empty and exits once the list is drained after CMD_SHUTDOWN (m_shutdown).

Definition at line 1445 of file stk_time_timer.h.

1446{
1447 bool keep_running = true;
1448
1449 while (keep_running)
1450 {
1451 Timer *tmr = nullptr;
1452 bool wait = false;
1453 size_t slot = STK_TIMER_THREADS_COUNT; // running slot of the claimed timer
1454
1455 // dequeue and claim the expiration in one critical section: a command which cancels it
1456 // (CancelPending) either runs before (nothing to dequeue) or after (too late, the callback runs)
1457 {
1458 hw::CriticalSection::ScopedLock cs;
1459
1460 if (!m_ready_list.IsEmpty())
1461 {
1463
1464 // the node is linked only while pending, kept as a guard for the invariant
1465 if (queued->m_pending)
1466 {
1467 queued->m_pending = false;
1468 tmr = queued;
1469
1470 // publish "callback running" in the same critical section as the claim: a stop executed
1471 // afterwards (CancelPending) is guaranteed to see it in WaitCallbackDone(). Each handler
1472 // owns at most one slot, so a free one always exists.
1473 for (size_t i = 0U; (i < STK_TIMER_THREADS_COUNT) && (slot == STK_TIMER_THREADS_COUNT); ++i)
1474 {
1475 if (m_running[i] == nullptr)
1476 {
1477 slot = i;
1478 }
1479 }
1480
1482
1483 if (slot < STK_TIMER_THREADS_COUNT)
1484 {
1485 m_running[slot] = tmr;
1486 }
1487 }
1488 }
1489 else if (m_shutdown)
1490 {
1491 keep_running = false;
1492 }
1493 else
1494 {
1495 wait = true;
1496 }
1497 }
1498
1499 if (tmr != nullptr)
1500 {
1501 // the timer must not be touched after the callback: it may be stopped and released by it
1502 // (or by a task waiting in StopSync() which is released by the slot cleared below)
1503 tmr->OnExpired(this);
1504
1505 if (slot < STK_TIMER_THREADS_COUNT)
1506 {
1507 // no critical section: an aligned pointer store is atomic, the slot is owned by this handler
1508 // (a concurrent free-slot search skips it or finds it free, either is correct)
1509 __stk_full_memfence();
1510 m_running[slot] = nullptr;
1511 __stk_full_memfence();
1512 }
1513 }
1514 else if (!keep_running)
1515 {
1516 // shutdown: wake the next handler (the event is auto-reset), it drains the list and exits too
1518 }
1519 else if (wait)
1520 {
1521 // nothing to handle: sleep until the tick task hands over an expiration or shuts down. The event
1522 // keeps its signaled state if Set() happened before this call, so no wake-up is lost. A spurious
1523 // wake-up only repeats the loop.
1525 {
1526 Sleep(1); // not expected, do not spin
1527 }
1528 }
1529 else
1530 {
1531 // dequeued a cancelled entry, look at the list again
1532 }
1533 }
1534}

References stk::detail::DListCast::ListEntryToParent(), stk::time::Timer::m_pending, m_ready_event, m_ready_list, m_running, m_shutdown, stk::time::Timer::OnExpired(), stk::Sleep(), STK_ASSERT, STK_TIMER_THREADS_COUNT, STK_UNUSED, stk::WAIT_INFINITE, and stk::WAIT_RESULT_FAIL.

Here is the call graph for this function:

◆ PushCommand()

TimerHost::EResult stk::time::TimerHost::PushCommand ( TimerCommand cmd,
Timeout wait = NO_WAIT )
inlineprivate

Enqueue a command for the tick task.

Parameters
[in]cmdFully initialized TimerCommand to push.
[in]waitMaximum ticks to wait for a free queue slot: NO_WAIT (default) does not wait unless the queue is full and the caller can wait (see CanWait()), WAIT_INFINITE blocks until the tick task has drained at least one command.
Returns
RES_OK if the command was queued (or coalesced), RES_NOT_READY if the host has no consumer of the queue, RES_QUEUE_FULL if the queue is full and the caller can not wait, RES_CANCELLED if the wait for a free slot was cancelled.
Note
May be called from any context. When the queue is full a caller which can wait blocks until a slot is free (see "Command queue" in TimerHost), otherwise it receives RES_QUEUE_FULL.
Warning
A blocking push must not be issued from the context which drains the queue (the tick task, Process() and callbacks run by it), see CanWait().

Definition at line 1849 of file stk_time_timer.h.

1850{
1851 EResult result = RES_OK;
1852
1853 if (!m_ready)
1854 {
1855 // not initialized, initialization failed or shut down: nobody consumes the command queue
1856 result = RES_NOT_READY;
1857 }
1858 else
1859 {
1860 bool proceed_to_write = true;
1861
1862 const bool is_rearm = (cmd.cmd == TimerCommand::CMD_RESTART) ||
1864
1865 // rearm coalescing (CMD_RESTART and CMD_START_OR_RESET of asynchronous callers only: a synchronous
1866 // caller needs its own result, its command is never merged into another one)
1867 if (is_rearm && (cmd.timer != nullptr) && (cmd.completion == nullptr))
1868 {
1869 if (cmd.timer->m_rearming)
1870 {
1871 // already rearming - successfully coalesced, no need to write to queue
1872 proceed_to_write = false;
1873 }
1874 else
1875 {
1876 cmd.timer->m_rearming = true;
1877
1878 // prevent compiler from sinking the flag write past Write()
1879 __stk_full_memfence();
1880 }
1881 }
1882
1883 // write to command queue
1884 if (proceed_to_write)
1885 {
1886 bool blocking = (wait == WAIT_INFINITE);
1887 bool written = m_commands.Write(cmd, wait);
1888
1889 // queue full: a caller which can wait blocks until the tick task has drained a slot instead of failing,
1890 // the tick task never waits for a caller, so the wait ends. Checked only now to keep the fast path short.
1891 if (!written && (wait == NO_WAIT) && CanWait())
1892 {
1893 blocking = true;
1894 written = m_commands.Write(cmd, WAIT_INFINITE);
1895 }
1896
1897 if (!written)
1898 {
1899 // revert the flag if this was a failed rearm attempt
1900 if (is_rearm && (cmd.timer != nullptr) && (cmd.completion == nullptr))
1901 {
1902 cmd.timer->m_rearming = false;
1903 }
1904
1905 // an unbounded wait fails only if it was cancelled, otherwise the queue is full and the caller
1906 // can not wait (ISR, kernel not running, polled mode, tick task): it may retry or escalate
1907 result = (blocking ? RES_CANCELLED : RES_QUEUE_FULL);
1908 }
1909 }
1910 }
1911
1912 return result;
1913}

References CanWait(), stk::time::TimerHost::TimerCommand::cmd, stk::time::TimerHost::TimerCommand::CMD_RESTART, stk::time::TimerHost::TimerCommand::CMD_START_OR_RESET, stk::time::TimerHost::TimerCommand::completion, m_commands, m_ready, stk::time::Timer::m_rearming, stk::NO_WAIT, RES_CANCELLED, RES_NOT_READY, RES_OK, RES_QUEUE_FULL, stk::time::TimerHost::TimerCommand::timer, and stk::WAIT_INFINITE.

Referenced by Execute(), Reset(), Restart(), SetPeriod(), Shutdown(), Start(), StartOrReset(), and Stop().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ QuerySync()

TimerHost::EResult stk::time::TimerHost::QuerySync ( Timer & tmr,
TimerInfo & info )
inline

Get a consistent snapshot of the timer (evaluated by the tick task).

Parameters
[in]tmrTimer instance.
[out]infoSnapshot, valid if the result is RES_OK.
Returns
RES_OK, RES_NOT_READY if the host is not initialized or has been shut down.
Note
From a context which can not wait (see "Synchronous API" in TimerHost) the snapshot is read without synchronization and is advisory (RES_OK is returned).

Definition at line 2117 of file stk_time_timer.h.

2118{
2119 return Execute(TimerCommand::CMD_QUERY, tmr, 0U, 0U, &info);
2120}

References stk::time::TimerHost::TimerCommand::CMD_QUERY, and Execute().

Referenced by cy_rtos_timer_is_running(), and stk_timer_query_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Reset()

TimerHost::EResult stk::time::TimerHost::Reset ( Timer & tmr)
inline

Reset periodic timer's deadline.

Parameters
[in]tmrTimer instance. Must be active and periodic.
Returns
RES_OK if the command was queued, RES_INACTIVE if the timer is not active, RES_NOT_PERIODIC if it is a one-shot timer (nothing is queued in both cases), RES_QUEUE_FULL, RES_CANCELLED, RES_NOT_READY.

Definition at line 1162 of file stk_time_timer.h.

1163{
1164 EResult result;
1165
1166 // timer must be active and periodic
1167 if (!tmr.m_active)
1168 {
1169 result = RES_INACTIVE;
1170 }
1171 else if (tmr.m_period == 0U)
1172 {
1173 result = RES_NOT_PERIODIC;
1174 }
1175 else
1176 {
1177 result = PushCommand({
1179 .timer = &tmr,
1180 .timestamp = GetTicks(),
1181 .delay = 0U,
1182 .period = 0U,
1183 .completion = nullptr
1184 });
1185 }
1186
1187 return result;
1188}

References stk::time::TimerHost::TimerCommand::CMD_RESET, stk::GetTicks(), stk::time::Timer::m_active, stk::time::Timer::m_period, PushCommand(), RES_INACTIVE, and RES_NOT_PERIODIC.

Referenced by stk_timer_reset().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ResetSync()

TimerHost::EResult stk::time::TimerHost::ResetSync ( Timer & tmr)
inline

Reset periodic timer's deadline and wait for the result.

Parameters
[in]tmrTimer instance. Must be active and periodic.
Returns
RES_OK, RES_INACTIVE, RES_NOT_PERIODIC, RES_QUEUED, or an error code (RES_NOT_READY, RES_QUEUE_FULL, RES_CANCELLED).

Definition at line 2095 of file stk_time_timer.h.

2096{
2097 return Execute(TimerCommand::CMD_RESET, tmr, 0U, 0U, nullptr);
2098}

References stk::time::TimerHost::TimerCommand::CMD_RESET, and Execute().

Referenced by stk_timer_reset_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Restart()

TimerHost::EResult stk::time::TimerHost::Restart ( Timer & tmr,
uint32_t delay,
uint32_t period = 0 )
inline

Atomically stop and re-start timer.

Parameters
[in]tmrTimer instance (active or inactive).
[in]delayInitial delay in ticks before first expiration.
[in]periodReload period in ticks (0 is one-shot timer).
Returns
RES_OK if the command was queued (or coalesced with one already waiting), RES_QUEUE_FULL, RES_CANCELLED, RES_NOT_READY.
Note
Unlike calling Stop() followed by Start(), this operation is atomic with respect to the tick task: the timer cannot fire between the implicit stop and re-start, and only one command queue slot is consumed. Useful for watchdog refresh and debounce reset patterns. Safe to call regardless of whether the timer is currently active.

Definition at line 1194 of file stk_time_timer.h.

1195{
1196 STK_ASSERT(delay <= static_cast<uint32_t>(WAIT_INFINITE));
1197 STK_ASSERT((period == 0U) || (period <= static_cast<uint32_t>(WAIT_INFINITE)));
1198
1199 return PushCommand({
1201 .timer = &tmr,
1202 .timestamp = GetTicks(),
1203 .delay = delay,
1204 .period = period,
1205 .completion = nullptr
1206 });
1207}

References stk::time::TimerHost::TimerCommand::CMD_RESTART, stk::GetTicks(), PushCommand(), STK_ASSERT, and stk::WAIT_INFINITE.

Referenced by stk_timer_restart().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ RestartSync()

TimerHost::EResult stk::time::TimerHost::RestartSync ( Timer & tmr,
uint32_t delay,
uint32_t period = 0 )
inline

Atomically stop and re-start timer and wait for the result.

Parameters
[in]tmrTimer instance (active or inactive).
[in]delayInitial delay in ticks before first expiration, stored in the timer.
[in]periodReload period in ticks (0 is one-shot timer), stored in the timer.
Returns
RES_OK, RES_QUEUED, or an error code (RES_NOT_READY, RES_QUEUE_FULL, RES_CANCELLED).

Definition at line 2090 of file stk_time_timer.h.

2091{
2092 return Execute(TimerCommand::CMD_RESTART, tmr, delay, period, nullptr);
2093}

References stk::time::TimerHost::TimerCommand::CMD_RESTART, and Execute().

Referenced by cy_rtos_timer_start(), osThreadFeedWatchdog(), osTimerStart(), and stk_timer_restart_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ScanTimers()

Timeout stk::time::TimerHost::ScanTimers ( Ticks now)
inlineprivate

Evaluate all active timers against the given time.

Parameters
[in]nowCurrent time (ticks).
Returns
Ticks until the earliest active deadline (NO_WAIT if a timer is overdue, WAIT_INFINITE if none).
Note
Task mode: queues expired timers for the handler tasks. Polled mode: invokes OnExpired() of expired timers inline. Runs exclusively in the tick task (task mode) or in Process() (polled mode).

Definition at line 1311 of file stk_time_timer.h.

1312{
1313 Timeout next_sleep = WAIT_INFINITE;
1314
1315 // using WriteVolatile64() to guarantee correct lockless reading order by ReadVolatile64
1317
1319 while (tmr != nullptr)
1320 {
1321 Timer *const next = detail::DListCast::ListEntryToParent<Timer>(tmr->GetNext());
1322
1323 if (tmr->m_active)
1324 {
1325 // check if still pending to be handled
1326 if (!tmr->m_pending)
1327 {
1328 bool one_shot = false;
1329 const Ticks diff = now - tmr->m_deadline;
1330
1331 if (diff >= 0)
1332 {
1333 // set timestamp at which timer expired
1334 tmr->m_timestamp = now;
1335
1336 // avoid updating timer again before it was handled
1337 tmr->m_pending = true;
1338
1339 // periodic
1340 if (tmr->m_period != 0U)
1341 {
1342 // reload (use now to avoid drift accumulation)
1343 tmr->m_deadline = now + static_cast<Ticks>(tmr->m_period) - diff;
1344 }
1345 // one-shot
1346 else
1347 {
1348 one_shot = true;
1349
1350 // remove from active timers
1351 m_active.Unlink(tmr);
1352
1353 // mark as inactive (must follow Unlink)
1354 tmr->m_active = false;
1355 }
1356
1357 __stk_full_memfence();
1358
1359 if (m_polled)
1360 {
1361 // polled mode: no handler tasks, handle inline (the timer is already
1362 // re-armed or unlinked, commands issued by the callback are deferred)
1363 tmr->m_pending = false;
1364 tmr->OnExpired(this);
1365 }
1366 // hand over to a handler task, must never block: a blocked tick task would stop completing
1367 // commands, while a handler (callback) may itself be waiting for a synchronous command.
1368 // The timer owns its node, so this can not fail (no queue to overflow): m_pending was false,
1369 // therefore the node is not linked (see Timer::ReadyNode)
1370 else
1371 {
1372 {
1373 hw::CriticalSection::ScopedLock cs;
1374
1375 STK_ASSERT(!tmr->m_ready_node.IsLinked());
1376 m_ready_list.LinkBack(&tmr->m_ready_node);
1377 }
1378
1380 }
1381 }
1382
1383 // one-shot timer does not affect next_sleep
1384 if (!one_shot)
1385 {
1386 Timeout next_deadline = static_cast<Timeout>(tmr->m_deadline - now);
1387
1388 // task mode: a (re)loaded deadline always lies in the future, polled mode: the caller
1389 // may poll slower than the period, an overdue timer is served by the next call
1390 STK_ASSERT(m_polled || (next_deadline > 0));
1391
1392 if (next_deadline <= 0)
1393 {
1394 next_deadline = NO_WAIT;
1395 }
1396
1397 if (next_deadline < next_sleep)
1398 {
1399 next_sleep = next_deadline;
1400 }
1401 }
1402 }
1403 }
1404 else
1405 {
1406 // could be stopped externally, remove from active timers
1407 m_active.Unlink(tmr);
1408 }
1409
1410 tmr = next;
1411 }
1412
1413 return next_sleep;
1414}
void WriteVolatile64(volatile T *addr, T value)
Atomically write a 64-bit volatile value.
Definition stk_arch.h:397

References stk::detail::DListEntry< T, TClosedLoop >::GetNext(), stk::detail::DListEntry< T, TClosedLoop >::IsLinked(), stk::detail::DListCast::ListEntryToParent(), stk::time::Timer::m_active, m_active, stk::time::Timer::m_deadline, m_now, stk::time::Timer::m_pending, stk::time::Timer::m_period, m_polled, m_ready_event, m_ready_list, stk::time::Timer::m_ready_node, stk::time::Timer::m_timestamp, stk::NO_WAIT, stk::time::Timer::OnExpired(), STK_ASSERT, STK_UNUSED, stk::WAIT_INFINITE, and stk::hw::WriteVolatile64().

Referenced by Process(), and UpdateTime().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetPeriod()

TimerHost::EResult stk::time::TimerHost::SetPeriod ( Timer & tmr,
uint32_t period )
inline

Change the period of a running periodic timer without affecting its current deadline.

Parameters
[in]tmrTimer instance. Must be active and periodic.
[in]periodNew reload period in ticks. Must be non-zero.
Returns
RES_OK if the command was queued, RES_INVALID_PARAM if period is zero or larger than WAIT_INFINITE, RES_INACTIVE if the timer is not active, RES_NOT_PERIODIC if it is a one-shot timer (nothing is queued in these cases), RES_QUEUE_FULL, RES_CANCELLED, RES_NOT_READY.
Note
The new period takes effect on the next reload after the current deadline fires. To apply the new period immediately (restart from now), call Reset() after SetPeriod().

Definition at line 1232 of file stk_time_timer.h.

1233{
1234 EResult result;
1235
1236 // period == 0 is rejected: it would silently convert a periodic timer
1237 // to one-shot semantics, which is better expressed via Stop() + Start()
1238 if ((period == 0U) || (period > static_cast<uint32_t>(WAIT_INFINITE)))
1239 {
1240 result = RES_INVALID_PARAM;
1241 }
1242 else if (!tmr.m_active)
1243 {
1244 result = RES_INACTIVE;
1245 }
1246 else if (tmr.m_period == 0U)
1247 {
1248 result = RES_NOT_PERIODIC;
1249 }
1250 else
1251 {
1252 result = PushCommand({
1254 .timer = &tmr,
1255 .timestamp = 0LL,
1256 .delay = 0U,
1257 .period = period,
1258 .completion = nullptr
1259 });
1260 }
1261
1262 return result;
1263}

References stk::time::TimerHost::TimerCommand::CMD_SET_PERIOD, stk::time::Timer::m_active, stk::time::Timer::m_period, PushCommand(), RES_INACTIVE, RES_INVALID_PARAM, RES_NOT_PERIODIC, and stk::WAIT_INFINITE.

Referenced by stk_timer_set_period().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetPeriodSync()

TimerHost::EResult stk::time::TimerHost::SetPeriodSync ( Timer & tmr,
uint32_t period )
inline

Change the period of a running periodic timer without affecting its current deadline and wait for the result.

Parameters
[in]tmrTimer instance. Must be active and periodic.
[in]periodNew reload period in ticks. Must be non-zero.
Returns
RES_OK, RES_INACTIVE if the timer is not active, RES_NOT_PERIODIC if it is a one-shot timer (nothing is changed in both cases), RES_QUEUED, RES_INVALID_PARAM if period is zero or larger than WAIT_INFINITE (nothing is queued), or an error code (RES_NOT_READY, RES_QUEUE_FULL, RES_CANCELLED).
Note
The new period takes effect on the next reload after the current deadline fires. To apply it immediately (restart from now), call ResetSync() after SetPeriodSync().
Unlike SetPeriod(), the state of the timer is evaluated by the tick task, so the outcome is exact and a timer which is stopped or re-armed by a command queued earlier is judged correctly.

Definition at line 2100 of file stk_time_timer.h.

2101{
2102 // period == 0 is rejected as in SetPeriod(): it would silently convert a periodic timer to one-shot
2103 // semantics (and CMD_SET_PERIOD asserts on it), the activity of the timer is judged by the tick task
2104 if ((period == 0U) || (period > static_cast<uint32_t>(WAIT_INFINITE)))
2105 {
2106 return RES_INVALID_PARAM;
2107 }
2108
2109 return Execute(TimerCommand::CMD_SET_PERIOD, tmr, 0U, period, nullptr);
2110}

References stk::time::TimerHost::TimerCommand::CMD_SET_PERIOD, Execute(), RES_INVALID_PARAM, and stk::WAIT_INFINITE.

Referenced by stk_timer_set_period_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Shutdown()

TimerHost::EResult stk::time::TimerHost::Shutdown ( )
inline

Shutdown host instance. All timers are stopped and removed from the host.

Returns
RES_OK if the command was queued, RES_QUEUE_FULL, RES_CANCELLED, RES_NOT_READY (already shut down or not initialized).
Note
Task mode: the tick and handler tasks exit. Polled mode: the host stays usable.
Examples
timer/example.cpp.

Definition at line 1269 of file stk_time_timer.h.

1270{
1271 return PushCommand({
1273 .timer = nullptr,
1274 .timestamp = 0LL,
1275 .delay = 0U,
1276 .period = 0U,
1277 .completion = nullptr
1278 });
1279}

References stk::time::TimerHost::TimerCommand::CMD_SHUTDOWN, and PushCommand().

Referenced by ShutdownTimer::OnExpired(), and stk_timerhost_shutdown().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Start()

TimerHost::EResult stk::time::TimerHost::Start ( Timer & tmr,
uint32_t delay,
uint32_t period = 0 )
inline

Start timer.

Parameters
[in]tmrTimer instance. Must not already be active.
[in]delayInitial delay in ticks before first expiration.
[in]periodReload period in ticks (0 is one-shot timer).
Returns
RES_OK if the command was queued, RES_ACTIVE if the timer is already active (nothing is queued), RES_QUEUE_FULL, RES_CANCELLED, RES_NOT_READY (see "Result codes" in TimerHost).
Examples
low_power/example.cpp.

Definition at line 1103 of file stk_time_timer.h.

1104{
1105 STK_ASSERT(delay <= static_cast<uint32_t>(WAIT_INFINITE));
1106 STK_ASSERT((period == 0U) || (period <= static_cast<uint32_t>(WAIT_INFINITE)));
1107
1108 EResult result;
1109
1110 // timer must not already be active (advisory check, the tick task evaluates the exact state)
1111 if (!tmr.m_active)
1112 {
1113 result = PushCommand({
1115 .timer = &tmr,
1116 .timestamp = GetTicks(),
1117 .delay = delay,
1118 .period = period,
1119 .completion = nullptr
1120 });
1121 }
1122 else
1123 {
1124 result = RES_ACTIVE;
1125 }
1126
1127 return result;
1128}

References stk::time::TimerHost::TimerCommand::CMD_START, stk::GetTicks(), stk::time::Timer::m_active, PushCommand(), RES_ACTIVE, STK_ASSERT, and stk::WAIT_INFINITE.

Referenced by RunExample(), and stk_timer_start().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ StartOrReset()

TimerHost::EResult stk::time::TimerHost::StartOrReset ( Timer & tmr,
uint32_t delay,
uint32_t period = 0 )
inline

Start timer if inactive, or reset its deadline if already active and periodic.

Parameters
[in]tmrTimer instance (active or inactive).
[in]delayInitial delay in ticks (used only when starting).
[in]periodReload period in ticks (used only when starting, 0 is one-shot).
Returns
RES_OK if the command was queued (or coalesced with one already waiting), RES_QUEUE_FULL, RES_CANCELLED, RES_NOT_READY.
Note
Collapses the common pattern: if (timer.IsActive()) host.Reset(timer); else host.Start(timer, delay, period); into a single atomic operation, eliminating the TOCTOU race between the IsActive() check and the subsequent call. If the timer is active but one-shot, no action is taken (a one-shot timer mid-flight cannot be reset; use Restart() instead).

Definition at line 1213 of file stk_time_timer.h.

1214{
1215 STK_ASSERT(delay <= static_cast<uint32_t>(WAIT_INFINITE));
1216 STK_ASSERT((period == 0U) || (period <= static_cast<uint32_t>(WAIT_INFINITE)));
1217
1218 return PushCommand({
1220 .timer = &tmr,
1221 .timestamp = GetTicks(),
1222 .delay = delay,
1223 .period = period,
1224 .completion = nullptr
1225 });
1226}

References stk::time::TimerHost::TimerCommand::CMD_START_OR_RESET, stk::GetTicks(), PushCommand(), STK_ASSERT, and stk::WAIT_INFINITE.

Referenced by stk_timer_start_or_reset().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ StartSync()

TimerHost::EResult stk::time::TimerHost::StartSync ( Timer & tmr,
uint32_t delay,
uint32_t period = 0 )
inline

Start timer and wait for the result (see "Synchronous API" in TimerHost).

Parameters
[in]tmrTimer instance. Must not be active.
[in]delayInitial delay in ticks before first expiration, stored in the timer.
[in]periodReload period in ticks (0 is one-shot timer), stored in the timer.
Returns
RES_OK, RES_ACTIVE if the timer is already active (nothing is changed), RES_QUEUED, or an error code (RES_NOT_READY, RES_QUEUE_FULL, RES_CANCELLED).

Definition at line 2075 of file stk_time_timer.h.

2076{
2077 return Execute(TimerCommand::CMD_START, tmr, delay, period, nullptr);
2078}

References stk::time::TimerHost::TimerCommand::CMD_START, and Execute().

Referenced by stk_timer_start_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ STK_NONCOPYABLE_CLASS()

stk::time::TimerHost::STK_NONCOPYABLE_CLASS ( TimerHost )
private

References TimerHost().

Here is the call graph for this function:

◆ Stop()

TimerHost::EResult stk::time::TimerHost::Stop ( Timer & tmr)
inline

Stop running timer.

Parameters
[in]tmrTimer instance. Must be active.
Returns
RES_OK if the command was queued, RES_INACTIVE if the timer is not active (nothing is queued), RES_QUEUE_FULL, RES_CANCELLED, RES_NOT_READY.

Definition at line 1134 of file stk_time_timer.h.

1135{
1136 EResult result;
1137
1138 // timer must be active (advisory check, the tick task evaluates the exact state)
1139 if (tmr.m_active)
1140 {
1141 result = PushCommand({
1143 .timer = &tmr,
1144 .timestamp = 0LL,
1145 .delay = 0U,
1146 .period = 0U,
1147 .completion = nullptr
1148 });
1149 }
1150 else
1151 {
1152 result = RES_INACTIVE;
1153 }
1154
1155 return result;
1156}

References stk::time::TimerHost::TimerCommand::CMD_STOP, stk::time::Timer::m_active, PushCommand(), and RES_INACTIVE.

Referenced by stk_timer_stop().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ StopSync()

TimerHost::EResult stk::time::TimerHost::StopSync ( Timer & tmr)
inline

Stop timer and wait for the result.

Parameters
[in]tmrTimer instance.
Returns
RES_OK if it was active, RES_INACTIVE if it was not active (a one-shot which already expired, its queued callback is cancelled if it has not started yet), RES_QUEUED, or an error code (RES_NOT_READY, RES_QUEUE_FULL, RES_CANCELLED).
Note
Also waits until a callback of this timer which a handler task has already started has returned, after RES_OK / RES_INACTIVE the Timer storage may be released.
Warning
Called from an OnExpired() callback it does not wait for running callbacks (deadlock guard), see "Synchronous API" in TimerHost. Do not release the Timer from a callback of another timer.

Definition at line 2085 of file stk_time_timer.h.

2086{
2087 return Execute(TimerCommand::CMD_STOP, tmr, 0U, 0U, nullptr);
2088}

References stk::time::TimerHost::TimerCommand::CMD_STOP, and Execute().

Referenced by cy_rtos_timer_deinit(), cy_rtos_timer_stop(), osThreadFeedWatchdog(), osTimerDelete(), osTimerStop(), and stk_timer_stop_sync().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateTime()

void stk::time::TimerHost::UpdateTime ( )
inlineprivate

Tick task body: drives the timer list and dispatches expired timers.

Note
Runs exclusively in the tick task context. Loops until CMD_SHUTDOWN is received.

Definition at line 1285 of file stk_time_timer.h.

1286{
1287 Timeout next_sleep = NO_WAIT;
1288
1289 // synchronous callers must never wait from this task (it is the one which completes their commands)
1290 m_tick_tid = GetTid();
1291
1292 while (ProcessCommands(next_sleep))
1293 {
1294 next_sleep = ScanTimers(GetTicks());
1295 }
1296
1297 // no consumer of the command queue any more: synchronous calls fail instead of waiting forever
1298 m_ready = false;
1299
1300 // unlink all timers on shutdown
1301 while (Timer::DLEntryType *const tmr = m_active.GetFirst())
1302 {
1303 m_active.Unlink(tmr);
1304 }
1305}
DListEntry< Timer, TClosedLoop > DLEntryType

References stk::GetTicks(), stk::GetTid(), m_active, m_ready, m_tick_tid, stk::NO_WAIT, ProcessCommands(), and ScanTimers().

Here is the call graph for this function:

◆ WaitCallbackDone()

void stk::time::TimerHost::WaitCallbackDone ( Timer & tmr)
inlineprivate

Wait until no handler task is executing the callback of the timer.

Parameters
[in]tmrTimer instance, already stopped (CancelPending() done by the tick task), so no new callback of it can start and the wait is bounded by the callback which is running now.

Polls the running slots every tick (Sleep(1)), lock-free: it takes no critical section.

Note
Does nothing when called from a handler task of this host (an OnExpired() callback): a callback which stops its own timer would wait for itself, and two callbacks stopping each other's timers would wait for each other. The guarantee therefore does not apply to a stop issued from a callback.
Warning
Task context with the kernel running only (see CanWait()).

Definition at line 1950 of file stk_time_timer.h.

1951{
1952 // a callback must not wait (self-stop and mutual-stop deadlock), the caller of a stop from a callback
1953 // gets the "no new callback starts" guarantee only
1954 if (!IsHostTid(GetTid()))
1955 {
1956 bool running = true;
1957
1958 while (running)
1959 {
1960 running = false;
1961
1962 // no critical section: the slots are aligned volatile pointers (atomic reads), the claim which
1963 // set a slot happened before the stop completed, and the timer can not be claimed again
1964 __stk_full_memfence();
1965
1966 for (size_t i = 0U; i < STK_TIMER_THREADS_COUNT; ++i)
1967 {
1968 if (m_running[i] == &tmr)
1969 {
1970 running = true;
1971 }
1972 }
1973
1974 if (running)
1975 {
1976 Sleep(1);
1977 }
1978 }
1979 }
1980}
bool IsHostTid(TId tid)
Check whether a task id belongs to a task of this host (tick or handler task).

References stk::GetTid(), IsHostTid(), m_running, stk::Sleep(), and STK_TIMER_THREADS_COUNT.

Referenced by Execute().

Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ m_active

detail::DListHead<Timer, false> stk::time::TimerHost::m_active
private

active timers (tick task only)

Definition at line 998 of file stk_time_timer.h.

Referenced by GetSize(), IsEmpty(), ProcessCommands(), ScanTimers(), TimerHost(), and UpdateTime().

◆ m_commands

CommandQueue stk::time::TimerHost::m_commands
private

command queue

Definition at line 1001 of file stk_time_timer.h.

Referenced by ProcessCommands(), and PushCommand().

◆ m_kernel

IKernel* stk::time::TimerHost::m_kernel
private

kernel of the task mode (nullptr in polled mode)

Definition at line 1007 of file stk_time_timer.h.

Referenced by CanWait(), Initialize(), InitializePolled(), and TimerHost().

◆ m_now

Ticks stk::time::TimerHost::m_now
private

last known current time (ticks)

Definition at line 1002 of file stk_time_timer.h.

Referenced by GetTimeNow(), ScanTimers(), and TimerHost().

◆ m_polled

bool stk::time::TimerHost::m_polled
private

true in polled mode (InitializePolled()), no tasks, callbacks run inline from Process()

Definition at line 1003 of file stk_time_timer.h.

Referenced by CancelPending(), CanWait(), Initialize(), InitializePolled(), IsHostTid(), Process(), ProcessCommands(), ScanTimers(), and TimerHost().

◆ m_ready

volatile bool stk::time::TimerHost::m_ready
private

true while the host has a consumer of the command queue (initialized and not shut down)

Definition at line 1004 of file stk_time_timer.h.

Referenced by CanWait(), Execute(), Initialize(), InitializePolled(), PushCommand(), TimerHost(), and UpdateTime().

◆ m_ready_event

sync::Event stk::time::TimerHost::m_ready_event
private

auto-reset event which wakes a handler task when m_ready_list gets an entry or on shutdown

Definition at line 1000 of file stk_time_timer.h.

Referenced by ProcessCommands(), ProcessTimers(), ScanTimers(), and TimerHost().

◆ m_ready_list

ReadyList stk::time::TimerHost::m_ready_list
private

expired timers waiting for a handler task (access only inside a critical section)

Definition at line 999 of file stk_time_timer.h.

Referenced by CancelPending(), ProcessTimers(), ScanTimers(), and TimerHost().

◆ m_running

Timer* volatile stk::time::TimerHost::m_running[1U]
private

timers whose callback is being executed by a handler task (one slot per handler: set inside the claim critical section, cleared and polled lock-free), see WaitCallbackDone()

Definition at line 1006 of file stk_time_timer.h.

Referenced by ProcessTimers(), TimerHost(), and WaitCallbackDone().

◆ m_shutdown

volatile bool stk::time::TimerHost::m_shutdown
private

true once CMD_SHUTDOWN was received (task mode): handlers exit after draining m_ready_list

Definition at line 1005 of file stk_time_timer.h.

Referenced by Initialize(), ProcessCommands(), ProcessTimers(), and TimerHost().

◆ m_task_handler_memory

TimerHostMemory stk::time::TimerHost::m_task_handler_memory[1U]
private

handler task memory

Definition at line 995 of file stk_time_timer.h.

Referenced by Initialize(), and TimerHost().

◆ m_task_process

TimerWorkerTask stk::time::TimerHost::m_task_process[1U]
private

handler tasks

Definition at line 997 of file stk_time_timer.h.

Referenced by Initialize(), IsHostTid(), and TimerHost().

◆ m_task_tick

TimerWorkerTask stk::time::TimerHost::m_task_tick
private

timer task

Definition at line 996 of file stk_time_timer.h.

Referenced by Initialize(), IsHostTid(), and TimerHost().

◆ m_task_tick_memory

TaskTickMemory stk::time::TimerHost::m_task_tick_memory
private

tick task memory

Definition at line 994 of file stk_time_timer.h.

Referenced by Initialize(), and TimerHost().

◆ m_tick_tid

volatile TId stk::time::TimerHost::m_tick_tid
private

id of the tick task (TID_NONE until it runs), commands must not be waited for from it

Definition at line 1008 of file stk_time_timer.h.

Referenced by CanWait(), TimerHost(), and UpdateTime().


The documentation for this class was generated from the following file: