10#ifndef STK_TIME_TIMER_H_
11#define STK_TIME_TIMER_H_
27#ifndef STK_TIMER_THREADS_COUNT
28 #define STK_TIMER_THREADS_COUNT 1U
34#ifndef STK_TIMER_HANDLER_STACK_SIZE
35 #define STK_TIMER_HANDLER_STACK_SIZE 256U
41#ifndef STK_TIMER_COUNT_MAX
42 #define STK_TIMER_COUNT_MAX 32U
237 bool Start(
Timer &tmr, uint32_t delay, uint32_t period = 0);
262 bool Restart(
Timer &tmr, uint32_t delay, uint32_t period = 0);
480 uint32_t remaining_ticks = 0U;
491 remaining_ticks =
static_cast<uint32_t
>(remaining);
495 return remaining_ticks;
703 while (tmr !=
nullptr)
712 bool one_shot =
false;
741 __stk_full_memfence();
753 if ((next_deadline > 0) && (next_deadline < next_sleep))
755 next_sleep = next_deadline;
783 Timer *tmr =
nullptr;
784 bool keep_running =
true;
796 keep_running =
false;
1002 bool success =
true;
1003 bool proceed_to_write =
true;
1009 if (is_rearm && (cmd.
timer !=
nullptr))
1014 proceed_to_write =
false;
1021 __stk_full_memfence();
1026 if (proceed_to_write)
1031 if (is_rearm && (cmd.
timer !=
nullptr))
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
#define STK_STACK_SIZE_MIN
Minimum stack size in elements of Word, shared by all stack allocation lower-bound checks.
#define STK_VIRT_DTOR
Makes destructors virtual and compliant to strict rules if STK_STRICT_COMPLIANCY=0.
Implementation of synchronization primitive: stk::sync::Event.
Implementation of synchronization primitives: stk::sync::Pipe - runtime-sized byte-stream pipe over a...
#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).
Namespace of STK package.
uintptr_t Word
Native processor word type.
EAccessMode
Hardware access mode by the user task.
@ ACCESS_USER
Unprivileged access mode (access to some hardware is restricted, see CPU manual for details).
constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
int64_t Ticks
Ticks value.
int32_t Timeout
Timeout time (ticks).
static constexpr T Max(T a, T b)
Compile-time maximum of two values.
constexpr Weight DEFAULT_WEIGHT
Weight value: default weight of value (1) (see SwitchStrategySmoothWeightedRoundRobin).
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
static __stk_forceinline void WriteVolatile64(volatile T *addr, T value)
Atomically write a 64-bit volatile value.
static __stk_forceinline T ReadVolatile64(volatile const T *addr)
Atomically read a 64-bit volatile value.
Word Type[TStackSize]
Stack memory type.
Interface for a user task.
Interface for the implementation of the kernel of the scheduler. It supports Soft and Hard Real-Time ...
virtual void AddTask(ITask *user_task)=0
Add user task.
Intrusive doubly-linked list container. Manages a collection of DListEntry nodes embedded in host obj...
Intrusive doubly-linked list node. Embed this as a base class in any object (T) that needs to partici...
DListEntry< Timer, TClosedLoop > DLEntryType
DLEntryType * GetNext()
Get the next entry in the list.
DLHeadType * GetHead()
Get the list head this entry currently belongs to.
bool IsLinked() const
Check whether this entry is currently a member of any list.
Helper for casting list entries to concrete (parent) types.
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Safely casts an intrusive list entry to its concrete parent container object type.
Thread-safe, type-safe FIFO communication pipe with internal storage.
TimerWorkerTask m_task_process[1U]
handler tasks
TimerHostMemory m_task_handler_memory[1U]
handler task memory
bool SetPeriod(Timer &tmr, uint32_t period)
Change the period of a running periodic timer without affecting its current deadline.
Ticks m_now
last known current time (ticks)
util::DListHead< Timer, false > m_active
active timers (tick task only)
sync::PipeT< TimerCommand, 32U > CommandQueue
Lock-free pipe used to send TimerCommand records from API callers to the tick task.
void Initialize(IKernel *kernel, EAccessMode mode)
Initialize timer host instance.
bool IsEmpty() const
Return true if no timers are currently active.
sync::PipeT< Timer *, 32U > ReadyQueue
Lock-free pipe used to transfer expired timer pointers from the tick task to handler tasks.
bool Stop(Timer &tmr)
Stop running timer.
Ticks GetTimeNow() const
Get current time.
TimerWorkerTask m_task_tick
timer task
size_t GetSize() const
Return number of currently active timers.
STK_NONCOPYABLE_CLASS(TimerHost)
TaskTickMemory m_task_tick_memory
tick task memory
@ TASK_TICK_MEMORY_SIZE
stack memory size of the timer handler task
@ TASK_HANDLER_STACK_SIZE
@ TASK_COUNT
total number of tasks serving this instance
void(* TimerFuncType)(TimerHost *host)
Timer task function prototype.
ReadyQueue m_queue
queue of timers ready for handling
bool Shutdown()
Shutdown host instance. All timers are stopped and removed from the host.
bool Restart(Timer &tmr, uint32_t delay, uint32_t period=0)
Atomically stop and re-start timer.
void UpdateTime()
Tick task body: drives the timer list and dispatches expired timers.
StackMemoryDef< TASK_TICK_MEMORY_SIZE >::Type TaskTickMemory
Stack memory type for the single tick task.
bool StartOrReset(Timer &tmr, uint32_t delay, uint32_t period=0)
Start timer if inactive, or reset its deadline if already active and periodic.
TimerHost()
Default constructor. Zero-initializes all internal state.
bool ProcessCommands(Timeout next_sleep)
Drain the command queue and execute each pending command.
bool PushCommand(TimerCommand cmd)
Enqueue a command for the tick task.
bool Reset(Timer &tmr)
Reset periodic timer's deadline.
void ProcessTimers()
Handler task body: dequeues expired timers and invokes their OnExpired() callbacks.
~TimerHost()=default
Destructor.
CommandQueue m_commands
command queue
StackMemoryDef< TASK_HANDLER_STACK_SIZE >::Type TimerHostMemory
Stack memory type for each handler task.
bool Start(Timer &tmr, uint32_t delay, uint32_t period=0)
Start timer.
Abstract base class for a timer managed by TimerHost.
volatile bool m_active
true if active
Ticks m_deadline
absolute expiration time (ticks)
Ticks GetDeadline() const
Get the absolute time in ticks at which the timer will expire.
volatile bool m_rearming
true while a CMD_RESTART / CMD_START_OR_RESET is already in the command queue
uint32_t GetRemainingTicks() const
Get remaining ticks until the timer next expires.
Ticks m_timestamp
absolute time at which timer expired (ticks), updated by TimerHost
uint32_t m_period
reload period in ticks (0 = one-shot)
STK_VIRT_DTOR ~Timer()=default
Destructor.
bool IsActive() const
Check whether the timer is currently active.
STK_NONCOPYABLE_CLASS(Timer)
Timer()
Default constructor.
uint32_t GetPeriod() const
Get the reload period of the timer.
volatile bool m_pending
true if pending to be handled
Ticks GetTimestamp() const
Get the tick count at which the timer last expired.
virtual void OnExpired(TimerHost *host)=0
Callback invoked by the handler task when this timer expires.
Internal kernel task used by TimerHost for both the tick task and handler tasks.
EAccessMode GetAccessMode() const override
Get hardware access mode of the user task.
int32_t GetWeight() const override
Get static base weight of the task.
size_t GetStackSizeBytes() const override
Get size of the memory in bytes.
size_t GetStackSize() const override
Get number of elements of the stack memory array.
const char * GetTraceName() const override
Get task trace name set by application.
TimerFuncType m_func
entry function (tick loop or handler loop)
const Word * GetStack() const override
Get pointer to the stack memory.
void SetWeight(int32_t weight)
Override the scheduling weight assigned by Initialize().
TimerWorkerTask()
Default constructor. All members are zero/null-initialized.
size_t m_stack_size
stack size in words
void Initialize(TimerHost *host, Word *stack, size_t stack_size, EAccessMode mode, TimerFuncType const func)
Bind this task to a host, stack buffer, access mode, and entry function.
void Run() override
Timer task entry point.
TimerHost * m_host
owning TimerHost instance
void OnExit() override
Called by the kernel before removal from the scheduling (see stk::KERNEL_DYNAMIC).
Word * m_stack
pointer to stack buffer
int32_t m_weight
scheduling weight
void OnDeadlineMissed(uint32_t) override
Called by the scheduler if deadline of the task is missed when Kernel is operating in Hard Real-Time ...
EAccessMode m_mode
kernel access mode
POD command record passed from the public API methods to the tick task via the command queue.
EId
Identifies the operation to perform on the target timer.
@ CMD_SHUTDOWN
shutdown timer host
@ 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
uint32_t period
reload period ticks (CMD_START / CMD_RESTART / CMD_START_OR_RESET / CMD_SET_PERIOD)
Timer * timer
timer instance
Ticks timestamp
hw tick count captured at call site
uint32_t delay
initial delay ticks (CMD_START / CMD_RESTART / CMD_START_OR_RESET)