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::Kernel< TMode, TSize, TStrategy, TPlatform > Class Template Referencefinal

Concrete implementation of IKernel. More...

#include <stk.h>

Inheritance diagram for stk::Kernel< TMode, TSize, TStrategy, TPlatform >:
Collaboration diagram for stk::Kernel< TMode, TSize, TStrategy, TPlatform >:

Classes

class  KernelTask
 Internal per-slot kernel descriptor that wraps a user ITask instance. More...
class  KernelService
 Concrete implementation of IKernelService exposed to running tasks. More...
class  SleepTrapStack
 Storage bundle for the sleep trap: a Stack descriptor paired with its backing memory. More...
class  ExitTrapStack
 Storage bundle for the exit trap: a Stack descriptor paired with its backing memory. More...

Public Types

enum  EKernelState : uint8_t {
  KSTATE_INACTIVE = 0 ,
  KSTATE_READY ,
  KSTATE_RUNNING ,
  KSTATE_SUSPENDED
}
 Kernel state. More...

Public Member Functions

 Kernel ()
 Construct the kernel with all storage zero-initialized, m_request cleared to REQ_NONE, and m_kstate set to KSTATE_INACTIVE (indicating uninitialized state; advanced to KSTATE_READY by Initialize()).
 ~Kernel ()=default
 Destructor.
void Initialize (uint32_t resolution_us=PERIODICITY_DEFAULT) override
 Initialize kernel.
void AddTask (ITask *user_task) override
 Register task for a soft real-time (SRT) scheduling.
void AddTask (ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc) override
 Register a task for hard real-time (HRT) scheduling.
void RemoveTask (ITask *user_task) override
 Remove a previously added task from the kernel when it is not started.
void ScheduleTaskRemoval (ITask *user_task) override
 Schedule task removal from scheduling (exit).
void SuspendTask (ITask *user_task, bool &suspended) override
 Suspend task.
void ResumeTask (ITask *user_task) override
 Resume task.
void CancelTaskWait (ITask *user_task) override
 Cancel task's in-progress wait on a synchronization object.
size_t EnumerateKernelTasks (ArrayView< IKernelTask * > tasks) override
 Enumerate kernel tasks.
size_t EnumerateTasks (ArrayView< ITask * > user_tasks) override
 Enumerate user tasks.
void Start () override
 Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or indefinitely (KERNEL_STATIC mode).
bool IsStarted () const
 Check whether scheduler is currently running.
IPlatform * GetPlatform () override
 Get platform driver instance owned by this kernel.
ITaskSwitchStrategy * GetSwitchStrategy () override
 Get task-switching strategy instance owned by this kernel.
EKernelState GetState () const override
 Get kernel state.
template<size_t TMaxCount, typename TCallback>
size_t EnumerateTasksT (TCallback &&callback)
 Enumerate tasks, invoking a callback for each active task.

Static Public Attributes

static constexpr size_t TASKS_MAX = TSize
 Maximum number of concurrently registered tasks. Fixed at compile time. Exceeding this limit in AddTask() triggers a compile-time assert (TASKS_MAX > 0) and a runtime STK_ASSERT.

Protected Types

enum  ERequest : uint8_t {
  REQ_NONE = 0 ,
  REQ_ADD_TASK = (1 << 0)
}
 Bitmask flags for pending inter-task requests that must be processed by the kernel on the next tick (in UpdateTaskRequest()). More...
enum  EFsmState : int8_t {
  FSM_STATE_NONE = -1 ,
  FSM_STATE_SWITCHING ,
  FSM_STATE_SLEEPING ,
  FSM_STATE_WAKING ,
  FSM_STATE_EXITING ,
  FSM_STATE_MAX
}
 Finite-state machine (FSM) state. Encodes what the kernel is currently doing between two consecutive tick events. More...
enum  EFsmEvent : int8_t {
  FSM_EVENT_SWITCH = 0 ,
  FSM_EVENT_SLEEP ,
  FSM_EVENT_WAKE ,
  FSM_EVENT_EXIT ,
  FSM_EVENT_MAX
}
 Finite-state machine (FSM) event. Computed by FetchNextEvent() each tick based on strategy output and current kernel state. More...
typedef StackMemoryWrapper<((32U))> SleepTrapStackMemory
 Stack memory wrapper type for the sleep trap.
typedef StackMemoryWrapper< STACK_SIZE_MIN > ExitTrapStackMemory
 Stack memory wrapper type for the exit trap.
typedef KernelTask TaskStorageType[TASKS_MAX]
 KernelTask array type used as a storage for the KernelTask instances.
typedef ISyncObject::ListHeadType SyncObjectList
 Intrusive list of active ISyncObject instances registered with this kernel. Each sync object in this list receives a Tick() call every kernel tick for timeout tracking. Allocated only when KERNEL_SYNC is set (zero-size otherwise).

Protected Member Functions

void InitTraps ()
 Initialize stack of the traps.
KernelTask * AllocateNewTask (ITask *user_task)
 Allocate new instance of KernelTask.
void AddKernelTask (KernelTask *task)
 Add kernel task to the scheduling strategy.
void AllocateAndAddNewTask (ITask *user_task)
 Allocate new instance of KernelTask and add it into the scheduling process.
void HrtAllocateAndAddNewTask (ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc)
 Allocate new instance of KernelTask and add it into the HRT scheduling process.
void RequestAddTask (ITask *const user_task)
 Request to add new task.
KernelTask * FindTaskByUserTask (const ITask *user_task)
 Find kernel task by the bound ITask instance.
KernelTask * FindTaskByStack (const Stack *stack)
 Find kernel task by the bound Stack instance.
KernelTask * FindTaskBySP (Word SP)
 Find kernel task for a Stack Pointer (SP).
void RemoveTask (KernelTask *task)
 Remove kernel task.
void OnStart (Stack *&active) override
 Called by platform driver immediately after a scheduler start (first tick).
void OnStop () override
 Called by the platform driver after a scheduler stop (all tasks have exited).
bool OnTick (Stack *&idle, Stack *&active, Timeout &ticks) override
 Process one scheduler tick. Called from the platform timer/tick ISR.
bool OnForceContextSwitch (TId id, Stack *&idle, Stack *&active)
 Called when task state change forces a context switch (Sleep, SleepUntil, Wait).
void OnTaskSwitch (Word caller_SP) override
 Called by Thread process (via IKernelService::SwitchToNext) to switch to a next task.
void OnTaskSleep (Word caller_SP, Timeout ticks) override
 Called by Thread process (via IKernelService::Sleep) for exclusion of the calling process from scheduling (sleeping).
bool OnTaskSleepUntil (Word caller_SP, Ticks timestamp) override
 Called by Thread process (via IKernelService::SleepUntil) for exclusion of the calling process from scheduling (sleeping).
void OnTaskSleepCancel (TId task_id)
void OnTaskExit (Stack *stack) override
 Called from the Thread process when task finished (its Run function exited by return).
EWaitResult OnTaskWait (Word caller_SP, ISyncObject *sync_obj, IMutex *mutex, Timeout timeout) override
 Called from the Thread process when task needs to wait.
TId OnGetTid (Word caller_SP) override
 Called from the Thread process when for getting task/thread id of the process.
void OnSuspend (bool suspended) override
 Called from the Thread process to suspend scheduling.
void OnInheritWeight (TId tid, Weight weight)
Weight OnSetWeight (TId tid, Weight weight)
void OnRestoreWeight (TId tid, ISyncObject *sobj)
Timeout UpdateTasks (const Timeout elapsed_ticks)
 Update tasks (sleep, requests).
void ProcessTaskPendingSleep (KernelTask *const task)
void ProcessTaskPendingYield (KernelTask *const task)
Timeout UpdateTaskState (const Timeout elapsed_ticks)
 Update task state: process removals, deliver sleep/wake notifications, advance sleep timers, and track HRT durations.
void UpdateSyncObjects (const Timeout elapsed_ticks)
 Update synchronization objects.
void UpdateTaskRequest ()
 Update pending task requests.
EFsmEvent FetchNextEvent (KernelTask *&next)
 Fetch next event for the FSM.
EFsmState GetNewFsmState (KernelTask *&next)
 Get new FSM state.
bool UpdateFsmState (Stack *&idle, Stack *&active)
 Update FSM state.
bool StateSwitch (KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
 Switches contexts.
bool StateWake (KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
 Wakes up after sleeping.
bool StateSleep (KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
 Enters into a sleeping mode.
bool StateExit (KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
 Exits from scheduling.
bool IsInitialized () const
 Check whether Initialize() has been called and completed successfully.
void ScheduleAddTask ()
 Signal the kernel to process a pending AddTask request on the next tick.

Static Protected Member Functions

static bool IsValidFsmState (EFsmState state)
 Check if FSM state is valid.
static constexpr bool IsStaticMode ()
static constexpr bool IsDynamicMode ()
static constexpr bool IsHrtMode ()
static constexpr bool IsSyncMode ()
static constexpr bool IsTicklessMode ()

Protected Attributes

KernelService m_service
 Kernel service singleton exposed to running tasks via IKernelService::GetInstance().
TPlatform m_platform
 Platform driver (SysTick, PendSV, context switch implementation).
TStrategy m_strategy
 Task-switching strategy (determines which task runs next).
KernelTask * m_task_now
 Currently executing task, or nullptr before Start() or after all tasks exit.
TaskStorageType m_task_storage
 Static pool of TSize KernelTask slots (free slots have m_user == nullptr).
SleepTrapStack m_sleep_trap [1]
 Sleep trap (always present): executed when all tasks are sleeping.
ExitTrapStack m_exit_trap [STK_ALLOCATE_COUNT< TMode, KERNEL_DYNAMIC, 1U, 0U >::Value]
 Exit trap: zero-size in KERNEL_STATIC mode; one entry in KERNEL_DYNAMIC mode.
EFsmState m_fsm_state
 Current FSM state. Drives context-switch decision on every tick.
volatile uint8_t m_request
 Bitmask of pending ERequest flags from running tasks. Written by tasks, read/cleared by UpdateTaskRequest() in tick context.
volatile EKernelState m_kstate
 Current kernel state.
SyncObjectList m_sync_list [STK_ALLOCATE_COUNT< TMode, KERNEL_SYNC, 1U, 0U >::Value]
 List of active sync objects. Zero-size (no memory) if KERNEL_SYNC is not set.
const EFsmState m_fsm [FSM_STATE_MAX][FSM_EVENT_MAX]

Static Protected Attributes

static constexpr Timeout YIELD_TICKS = 1
 Ticks to yield.

Detailed Description

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
class stk::Kernel< TMode, TSize, TStrategy, TPlatform >

Concrete implementation of IKernel.

All configuration is expressed as template parameters. No virtual dispatch, no heap allocation - the entire kernel, tasks, and traps live in statically reserved storage.

Template Parameters
TModeBitmask of EKernelMode flags that configures kernel features:
  • KERNEL_STATIC - fixed task list, no add/remove after Start().
  • KERNEL_DYNAMIC - tasks may be added or removed at runtime.
  • KERNEL_HRT - Hard Real-Time mode (must combine with STATIC or DYNAMIC).
  • KERNEL_SYNC - enables synchronization primitives (Mutex, Event, etc.).
  • KERNEL_TICKLESS - enables tickless low-power operation. Requires STK_TICKLESS_IDLE=1 in stk_config.h. Incompatible with KERNEL_HRT (tickless suppresses the timer, which destroys the precise periodicity HRT depends on - enforced by the compile-time assertion TICKLESS_HRT_CONFLICT). KERNEL_STATIC and KERNEL_DYNAMIC are mutually exclusive.
TSizeMaximum number of concurrent tasks. Must be > 0.
TStrategyTask-switching strategy type (e.g. SwitchStrategyRoundRobin). Must inherit ITaskSwitchStrategy.
TPlatformPlatform driver type (e.g. PlatformArmCortexM, or PlatformDefault). Must inherit IPlatform.
Note
At least 1 task is required: TSize must be > 0 (enforced by compile-time assertion).
KERNEL_HRT is incompatible with weighted scheduling strategies (WEIGHT_API == true), also enforced by a compile-time assertion.
KERNEL_TICKLESS is incompatible with KERNEL_HRT, also enforced by a compile-time assertion (TICKLESS_HRT_CONFLICT).

Usage example:

static MyTask1<256, ACCESS_PRIVILEGED> task1;
static MyTask2<512, ACCESS_USER> task2;
static MyTask3<512, ACCESS_USER> task3;
kernel.Initialize();
kernel.AddTask(&task1);
kernel.AddTask(&task2);
kernel.AddTask(&task3);
kernel.Start();
Concrete implementation of IKernel.
Definition stk.h:92
void AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1231
void Start() override
Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or i...
Definition stk.h:1510
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1194

Definition at line 87 of file stk.h.

Member Typedef Documentation

◆ ExitTrapStackMemory

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
typedef StackMemoryWrapper<STACK_SIZE_MIN> stk::Kernel< TMode, TSize, TStrategy, TPlatform >::ExitTrapStackMemory
protected

Stack memory wrapper type for the exit trap.

See also
ExitTrapStack, STACK_SIZE_MIN

Definition at line 104 of file stk.h.

◆ SleepTrapStackMemory

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
typedef StackMemoryWrapper< ( (32U) )> stk::Kernel< TMode, TSize, TStrategy, TPlatform >::SleepTrapStackMemory
protected

Stack memory wrapper type for the sleep trap.

See also
SleepTrapStack, STK_SLEEP_TRAP_STACK_SIZE

Definition at line 98 of file stk.h.

◆ SyncObjectList

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
typedef ISyncObject::ListHeadType stk::Kernel< TMode, TSize, TStrategy, TPlatform >::SyncObjectList
protected

Intrusive list of active ISyncObject instances registered with this kernel. Each sync object in this list receives a Tick() call every kernel tick for timeout tracking. Allocated only when KERNEL_SYNC is set (zero-size otherwise).

Definition at line 2899 of file stk.h.

◆ TaskStorageType

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
typedef KernelTask stk::Kernel< TMode, TSize, TStrategy, TPlatform >::TaskStorageType[TASKS_MAX]
protected

KernelTask array type used as a storage for the KernelTask instances.

Definition at line 2861 of file stk.h.

Member Enumeration Documentation

◆ EFsmEvent

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
enum stk::Kernel::EFsmEvent : int8_t
protected

Finite-state machine (FSM) event. Computed by FetchNextEvent() each tick based on strategy output and current kernel state.

Enumerator
FSM_EVENT_SWITCH 

Strategy returned a runnable task, perform a context switch.

FSM_EVENT_SLEEP 

No runnable tasks, enter sleep trap.

FSM_EVENT_WAKE 

A task became runnable while the kernel was sleeping, wake from sleep trap.

FSM_EVENT_EXIT 

No tasks remain (KERNEL_DYNAMIC), exit scheduling and return from Start().

FSM_EVENT_MAX 

Sentinel: number of valid events (used to size the FSM table).

Definition at line 1583 of file stk.h.

1584 {
1585 FSM_EVENT_SWITCH = 0,
1590 };
@ FSM_EVENT_EXIT
No tasks remain (KERNEL_DYNAMIC), exit scheduling and return from Start().
Definition stk.h:1588
@ FSM_EVENT_WAKE
A task became runnable while the kernel was sleeping, wake from sleep trap.
Definition stk.h:1587
@ FSM_EVENT_SLEEP
No runnable tasks, enter sleep trap.
Definition stk.h:1586
@ FSM_EVENT_SWITCH
Strategy returned a runnable task, perform a context switch.
Definition stk.h:1585
@ FSM_EVENT_MAX
Sentinel: number of valid events (used to size the FSM table).
Definition stk.h:1589

◆ EFsmState

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
enum stk::Kernel::EFsmState : int8_t
protected

Finite-state machine (FSM) state. Encodes what the kernel is currently doing between two consecutive tick events.

Enumerator
FSM_STATE_NONE 

Sentinel / uninitialized value. Set by the constructor, replaced by FSM_STATE_SWITCHING on the first tick.

FSM_STATE_SWITCHING 

Normal operation: switching between runnable tasks each tick.

FSM_STATE_SLEEPING 

All tasks are sleeping, the sleep trap is executing (CPU in low-power state).

FSM_STATE_WAKING 

At least one task woke up, transitioning from sleep trap back to a user task.

FSM_STATE_EXITING 

All tasks exited (KERNEL_DYNAMIC only), executing the exit trap to return from Start().

FSM_STATE_MAX 

Sentinel: number of valid states (used to size the FSM table), denotes uninitialized state.

Definition at line 1569 of file stk.h.

1570 {
1571 FSM_STATE_NONE = -1,
1577 };
@ FSM_STATE_EXITING
All tasks exited (KERNEL_DYNAMIC only), executing the exit trap to return from Start().
Definition stk.h:1575
@ FSM_STATE_SLEEPING
All tasks are sleeping, the sleep trap is executing (CPU in low-power state).
Definition stk.h:1573
@ FSM_STATE_SWITCHING
Normal operation: switching between runnable tasks each tick.
Definition stk.h:1572
@ FSM_STATE_NONE
Sentinel / uninitialized value. Set by the constructor, replaced by FSM_STATE_SWITCHING on the first ...
Definition stk.h:1571
@ FSM_STATE_MAX
Sentinel: number of valid states (used to size the FSM table), denotes uninitialized state.
Definition stk.h:1576
@ FSM_STATE_WAKING
At least one task woke up, transitioning from sleep trap back to a user task.
Definition stk.h:1574

◆ EKernelState

enum stk::IKernel::EKernelState : uint8_t
inherited

Kernel state.

Enumerator
KSTATE_INACTIVE 

Not ready, IKernel::Initialize() must be called.

KSTATE_READY 

Ready to start, IKernel::Start() must be called.

KSTATE_RUNNING 

Initialized and running, IKernel::Start() was called successfully.

KSTATE_SUSPENDED 

Scheduling is suspended with IKernelService::Suspend().

Definition at line 1455 of file stk_common.h.

1456 {
1457 KSTATE_INACTIVE = 0,
1458 KSTATE_READY,
1461 };
@ KSTATE_RUNNING
Initialized and running, IKernel::Start() was called successfully.
@ KSTATE_SUSPENDED
Scheduling is suspended with IKernelService::Suspend().
@ KSTATE_INACTIVE
Not ready, IKernel::Initialize() must be called.
@ KSTATE_READY
Ready to start, IKernel::Start() must be called.

◆ ERequest

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
enum stk::Kernel::ERequest : uint8_t
protected

Bitmask flags for pending inter-task requests that must be processed by the kernel on the next tick (in UpdateTaskRequest()).

Enumerator
REQ_NONE 

No pending requests.

REQ_ADD_TASK 

An AddTask() request is pending from a running task (KERNEL_DYNAMIC only).

Definition at line 110 of file stk.h.

111 {
112 REQ_NONE = 0,
113 REQ_ADD_TASK = (1 << 0)
114 };
@ REQ_ADD_TASK
An AddTask() request is pending from a running task (KERNEL_DYNAMIC only).
Definition stk.h:113
@ REQ_NONE
No pending requests.
Definition stk.h:112

Constructor & Destructor Documentation

◆ Kernel()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
stk::Kernel< TMode, TSize, TStrategy, TPlatform >::Kernel ( )
inlineexplicit

Construct the kernel with all storage zero-initialized, m_request cleared to REQ_NONE, and m_kstate set to KSTATE_INACTIVE (indicating uninitialized state; advanced to KSTATE_READY by Initialize()).

Note
In debug builds also verifies that TPlatform derives from IPlatform and TStrategy from ITaskSwitchStrategy.
If TMode includes KERNEL_TICKLESS, a compile-time assertion fires unless STK_TICKLESS_IDLE is defined to 1 in stk_config.h.

Definition at line 1161 of file stk.h.

1163 {
1164 #ifdef _DEBUG
1165 // TPlatform must inherit IPlatform
1168
1169 // TStrategy must inherit ITaskSwitchStrategy
1172 #endif
1173
1174 #if !STK_TICKLESS_IDLE
1176 "STK_TICKLESS_IDLE must be defined to 1 for KERNEL_TICKLESS");
1177 #endif
1178 }
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
#define STK_STATIC_ASSERT_DESC(X, DESC)
Compile-time assertion with a custom error description. Produces a compilation error if X is false.
Definition stk_defs.h:536
volatile uint8_t m_request
Bitmask of pending ERequest flags from running tasks. Written by tasks, read/cleared by UpdateTaskReq...
Definition stk.h:2909
TStrategy m_strategy
Task-switching strategy (determines which task runs next).
Definition stk.h:2903
SleepTrapStack m_sleep_trap[1]
Sleep trap (always present): executed when all tasks are sleeping.
Definition stk.h:2906
volatile EKernelState m_kstate
Current kernel state.
Definition stk.h:2910
ExitTrapStack m_exit_trap[STK_ALLOCATE_COUNT< TMode, KERNEL_DYNAMIC, 1U, 0U >::Value]
Exit trap: zero-size in KERNEL_STATIC mode; one entry in KERNEL_DYNAMIC mode.
Definition stk.h:2907
TaskStorageType m_task_storage
Static pool of TSize KernelTask slots (free slots have m_user == nullptr).
Definition stk.h:2905
KernelTask * m_task_now
Currently executing task, or nullptr before Start() or after all tasks exit.
Definition stk.h:2904
TPlatform m_platform
Platform driver (SysTick, PendSV, context switch implementation).
Definition stk.h:2902
EFsmState m_fsm_state
Current FSM state. Drives context-switch decision on every tick.
Definition stk.h:2908

◆ ~Kernel()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
stk::Kernel< TMode, TSize, TStrategy, TPlatform >::~Kernel ( )
default

Destructor.

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

Member Function Documentation

◆ AddKernelTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::AddKernelTask ( KernelTask * task)
inlineprotected

Add kernel task to the scheduling strategy.

Parameters
[in]taskPointer to the kernel task.

Definition at line 1683 of file stk.h.

1684 {
1685 #if STK_SEGGER_SYSVIEW
1686 // start tracing new task
1687 SEGGER_SYSVIEW_OnTaskCreate(task->GetUserStackPtr()->tid);
1688 if (IsStarted())
1689 {
1691 }
1692 #endif
1693
1694 m_strategy.AddTask(task);
1695 }
bool IsStarted() const
Check whether scheduler is currently running.
Definition stk.h:1537

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AllocateAndAddNewTask(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::HrtAllocateAndAddNewTask().

Here is the caller graph for this function:

◆ AddTask() [1/2]

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::AddTask ( ITask * user_task)
inlineoverridevirtual

Register task for a soft real-time (SRT) scheduling.

Parameters
[in]user_taskUser task to add. Must not already be registered. Must not be nullptr.
Note
Before Start(): allocates a free KernelTask slot and adds it to the strategy immediately.
After Start() (KERNEL_DYNAMIC only): serialises the request via RequestAddTask() - the calling task yields and the kernel processes the request on the next tick.
Warning
Asserts if called in KERNEL_HRT mode (use the HRT overload instead), if called after Start() without KERNEL_DYNAMIC, or if TASKS_MAX is exceeded.

Implements stk::IKernel.

Definition at line 1231 of file stk.h.

1232 {
1234 {
1235 STK_ASSERT(user_task != nullptr);
1237
1238 // when started the operation must be serialized by switching out from processing until
1239 // kernel processes this request
1240 if (IsStarted())
1241 {
1243 {
1245 }
1246 else
1247 {
1248 STK_ASSERT(false);
1249 }
1250 }
1251 else
1252 {
1254 }
1255 }
1256 else
1257 {
1258 STK_ASSERT(false);
1259 }
1260 }
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:516
#define __stk_constexpr_cpp17
constexpr definition for C++17 and above.
Definition stk_defs.h:489
void RequestAddTask(ITask *const user_task)
Request to add new task.
Definition stk.h:1729
static constexpr bool IsHrtMode()
Definition stk.h:2831
void AllocateAndAddNewTask(ITask *user_task)
Allocate new instance of KernelTask and add it into the scheduling process.
Definition stk.h:1700
bool IsInitialized() const
Check whether Initialize() has been called and completed successfully.
Definition stk.h:2795
static constexpr bool IsDynamicMode()
Definition stk.h:2830

◆ AddTask() [2/2]

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::AddTask ( ITask * user_task,
Timeout periodicity_tc,
Timeout deadline_tc,
Timeout start_delay_tc )
inlineoverridevirtual

Register a task for hard real-time (HRT) scheduling.

Parameters
[in]user_taskUser task to add. Must not already be registered. Must not be nullptr.
[in]periodicity_tcActivation period in ticks. Must be > 0 and < INT32_MAX.
[in]deadline_tcMaximum allowed active duration in ticks. Must be > 0 and < INT32_MAX.
[in]start_delay_tcInitial sleep delay in ticks before the first activation. 0 means activate immediately.
Note
Must be called before Start(). Dynamic (post-Start) HRT task addition is not supported.
Warning
Asserts if called outside KERNEL_HRT mode (use the SRT overload instead) or after Start().

Implements stk::IKernel.

Definition at line 1270 of file stk.h.

1272 {
1274 {
1275 STK_ASSERT(user_task != nullptr);
1278
1280 }
1281 else
1282 {
1283 STK_ASSERT(false);
1284 }
1285 }
void HrtAllocateAndAddNewTask(ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc)
Allocate new instance of KernelTask and add it into the HRT scheduling process.
Definition stk.h:1715

◆ AllocateAndAddNewTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::AllocateAndAddNewTask ( ITask * user_task)
inlineprotected

Allocate new instance of KernelTask and add it into the scheduling process.

Parameters
[in]user_taskUser task for which kernel task object is allocated.

Definition at line 1700 of file stk.h.

1701 {
1703 STK_ASSERT(task != nullptr);
1704
1706 }
KernelTask * AllocateNewTask(ITask *user_task)
Allocate new instance of KernelTask.
Definition stk.h:1643
void AddKernelTask(KernelTask *task)
Add kernel task to the scheduling strategy.
Definition stk.h:1683
Internal per-slot kernel descriptor that wraps a user ITask instance.
Definition stk.h:128

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AddTask(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTaskRequest().

Here is the caller graph for this function:

◆ AllocateNewTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
KernelTask * stk::Kernel< TMode, TSize, TStrategy, TPlatform >::AllocateNewTask ( ITask * user_task)
inlineprotected

Allocate new instance of KernelTask.

Parameters
[in]user_taskUser task for which kernel task object is allocated.
Returns
Kernel task.

Definition at line 1643 of file stk.h.

1644 {
1645 // look for a free kernel task
1646 KernelTask *new_task = nullptr;
1647 for (size_t i = 0U; i < TASKS_MAX; ++i)
1648 {
1649 KernelTask *const task = &m_task_storage[i];
1650 if (task->IsBusy())
1651 {
1652 // avoid task collision
1653 STK_ASSERT(task->m_user != user_task);
1654
1655 // avoid stack collision
1656 STK_ASSERT(task->m_user->GetStack() != user_task->GetStack());
1657 }
1658 else
1659 if (new_task == nullptr)
1660 {
1661 new_task = task;
1662 #if defined(NDEBUG) && !defined(_STK_ASSERT_REDIRECT)
1663 break; // break if assertions are inactive and do not try to validate collision with existing tasks
1664 #endif
1665 }
1666 else
1667 {
1668 // noop, continue to the next slot
1669 }
1670 }
1671
1672 // if nullptr - exceeded max supported kernel task count, application design failure
1673 STK_ASSERT(new_task != nullptr);
1674
1675 new_task->Bind(&m_platform, user_task);
1676
1677 return new_task;
1678 }
static constexpr size_t TASKS_MAX
Maximum number of concurrently registered tasks. Fixed at compile time. Exceeding this limit in AddTa...
Definition stk.h:1151

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AllocateAndAddNewTask(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::HrtAllocateAndAddNewTask().

Here is the caller graph for this function:

◆ CancelTaskWait()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::CancelTaskWait ( ITask * user_task)
inlineoverridevirtual

Cancel task's in-progress wait on a synchronization object.

Parameters
[in]user_taskPointer to the user task whose wait should be cancelled.

Implements stk::IKernel.

Definition at line 1428 of file stk.h.

1429 {
1430 STK_ASSERT(user_task != nullptr);
1431
1433 {
1434 // avoid race with OnTick
1436
1438 STK_ASSERT(task != nullptr);
1439
1440 // only cancel if actually blocked in OnTaskWait() on a sync object; no-op otherwise
1441 // (e.g. task is running, suspended via SuspendTask(), or plainly sleeping)
1442 if (task->m_wait_obj->IsWaiting())
1443 {
1444 task->m_wait_obj->Cancel();
1445 }
1446 }
1447 else
1448 {
1449 // kernel operating mode must include KERNEL_SYNC for tasks to be able to wait
1450 STK_ASSERT(false);
1451 }
1452 }
static constexpr bool IsSyncMode()
Definition stk.h:2832
KernelTask * FindTaskByUserTask(const ITask *user_task)
Find kernel task by the bound ITask instance.
Definition stk.h:1762

◆ EnumerateKernelTasks()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
size_t stk::Kernel< TMode, TSize, TStrategy, TPlatform >::EnumerateKernelTasks ( ArrayView< IKernelTask * > tasks)
inlineoverridevirtual

Enumerate kernel tasks.

Parameters
[in]tasksReference to the ArrayView of IKernelTask pointers.
Returns
Number of tasks in the array.

Implements stk::IKernel.

Definition at line 1458 of file stk.h.

1459 {
1460 size_t count = 0U;
1461 const size_t limit = Min(tasks.GetSize(), TASKS_MAX);
1462
1463 // avoid race with OnTick
1465
1466 for (size_t i = 0U; i < limit; ++i)
1467 {
1468 KernelTask *const task = &m_task_storage[i];
1469 if (task->IsBusy())
1470 {
1471 tasks[count++] = task;
1472 }
1473 }
1474
1475 return count;
1476 }
static constexpr T Min(T a, T b) noexcept
Compile-time minimum of two values.
Definition stk_defs.h:753

◆ EnumerateTasks()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
size_t stk::Kernel< TMode, TSize, TStrategy, TPlatform >::EnumerateTasks ( ArrayView< ITask * > user_tasks)
inlineoverridevirtual

Enumerate user tasks.

Parameters
[in]user_tasksReference to the ArrayView of ITask pointers.
Returns
Number of tasks in the array.

Implements stk::IKernel.

Definition at line 1482 of file stk.h.

1483 {
1484 size_t count = 0U;
1485 const size_t limit = Min(user_tasks.GetSize(), TASKS_MAX);
1486
1487 // avoid race with OnTick
1489
1490 for (size_t i = 0U; i < limit; ++i)
1491 {
1492 KernelTask *const task = &m_task_storage[i];
1493 if (task->IsBusy())
1494 {
1495 user_tasks[count++] = task->GetUserTask();
1496 }
1497 }
1498
1499 return count;
1500 }

◆ EnumerateTasksT()

template<size_t TMaxCount, typename TCallback>
size_t stk::IKernel::EnumerateTasksT ( TCallback && callback)
inlineinherited

Enumerate tasks, invoking a callback for each active task.

Template Parameters
TMaxCountMaximum number of tasks to enumerate. Should match or exceed the kernel's task capacity. Determines the size of the internal stack-allocated buffer (TMaxCount * sizeof(ITask*) bytes on the stack).
TCallbackCallable type, deduced automatically. Must satisfy: bool(ITask*)
Parameters
[in]callbackCallable invoked for each active task. Return true to continue, false to stop early.
Returns
Number of tasks visited (up to TMaxCount).
Warning
ISR-safe.

Example:

kernel.EnumerateTasks<_STK_KERNEL_TASKS_COUNT>([](ITask *t) {
Log(t->GetTraceName());
return true; // continue
});
Interface for a user task.
Definition stk_common.h:772

Definition at line 1579 of file stk_common.h.

1580 {
1581 STK_STATIC_ASSERT(TMaxCount > 0U);
1582
1583 ITask *tasks[TMaxCount] = {};
1584 size_t count = EnumerateTasks(ArrayView<ITask *>(tasks, TMaxCount));
1585 size_t i = 0U;
1586 bool fetch_next = true;
1587
1588 while ((i < count) && fetch_next)
1589 {
1590 fetch_next = callback(tasks[i]);
1591 ++i;
1592 }
1593
1594 return i;
1595 }
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:553
virtual size_t EnumerateTasks(ArrayView< ITask * > user_tasks)=0
Enumerate user tasks.

References EnumerateTasks(), and STK_STATIC_ASSERT.

Here is the call graph for this function:

◆ FetchNextEvent()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
EFsmEvent stk::Kernel< TMode, TSize, TStrategy, TPlatform >::FetchNextEvent ( KernelTask *& next)
inlineprotected

Fetch next event for the FSM.

Parameters
[out]nextNext kernel task to which Kernel can switch.
Returns
FSM event.

Definition at line 2561 of file stk.h.

2562 {
2564
2565 // try getting next task for scheduling
2567
2568 // sleep-aware strategy returns nullptr if no active tasks available
2569 if (next != nullptr)
2570 {
2571 // strategy must provide active-only task
2572 STK_ASSERT(!next->IsSleeping());
2573
2574 // if was sleeping, process wake event first
2576 }
2577 // start sleeping
2578 else
2579 {
2581 {
2582 // if nullptr is returned then either strategy has all tasks sleeping or none left,
2583 // if KERNEL_DYNAMIC mode and no tasks left then exit from scheduling
2584 if (m_strategy.GetSize() == 0U)
2585 {
2586 next = nullptr;
2588 }
2589 }
2590 }
2591
2592 return type;
2593 }
EFsmEvent
Finite-state machine (FSM) event. Computed by FetchNextEvent() each tick based on strategy output and...
Definition stk.h:1584
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Safely casts an intrusive list entry to its concrete parent container object type.

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::GetNewFsmState().

Here is the caller graph for this function:

◆ FindTaskBySP()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
KernelTask * stk::Kernel< TMode, TSize, TStrategy, TPlatform >::FindTaskBySP ( Word SP)
inlineprotected

Find kernel task for a Stack Pointer (SP).

Parameters
[in]SPStack pointer.
Returns
Kernel task.

Definition at line 1804 of file stk.h.

1805 {
1806 STK_ASSERT(m_task_now != nullptr);
1807
1808 KernelTask *found_task = nullptr;
1809
1810 if (m_task_now->IsMemoryOfSP(SP))
1811 {
1813 }
1814 else
1815 {
1816 for (size_t i = 0U; i < TASKS_MAX; ++i)
1817 {
1818 KernelTask *const task = &m_task_storage[i];
1819
1820 // skip finished tasks (applicable only for KERNEL_DYNAMIC mode)
1822 {
1823 if (!task->IsBusy())
1824 {
1825 continue;
1826 }
1827 }
1828
1829 if (task->IsMemoryOfSP(SP))
1830 {
1831 found_task = task;
1832 break;
1833 }
1834 }
1835 }
1836
1837 return found_task;
1838 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnGetTid(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskSleep(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskSleepUntil(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskSwitch(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskWait(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::RequestAddTask().

Here is the caller graph for this function:

◆ FindTaskByStack()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
KernelTask * stk::Kernel< TMode, TSize, TStrategy, TPlatform >::FindTaskByStack ( const Stack * stack)
inlineprotected

Find kernel task by the bound Stack instance.

Parameters
[in]stackStack.
Returns
Kernel task.

Definition at line 1783 of file stk.h.

1784 {
1785 KernelTask *found_task = nullptr;
1786
1787 for (size_t i = 0U; i < TASKS_MAX; ++i)
1788 {
1789 KernelTask *const task = &m_task_storage[i];
1790 if (task->GetUserStackPtr() == stack)
1791 {
1792 found_task = task;
1793 break;
1794 }
1795 }
1796
1797 return found_task;
1798 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskExit().

Here is the caller graph for this function:

◆ FindTaskByUserTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
KernelTask * stk::Kernel< TMode, TSize, TStrategy, TPlatform >::FindTaskByUserTask ( const ITask * user_task)
inlineprotected

Find kernel task by the bound ITask instance.

Parameters
[in]user_taskUser task.
Returns
Kernel task.

Definition at line 1762 of file stk.h.

1763 {
1764 KernelTask *found_task = nullptr;
1765
1766 for (size_t i = 0U; i < TASKS_MAX; ++i)
1767 {
1768 KernelTask *const task = &m_task_storage[i];
1769 if (task->GetUserTask() == user_task)
1770 {
1771 found_task = task;
1772 break;
1773 }
1774 }
1775
1776 return found_task;
1777 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::CancelTaskWait(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnInheritWeight(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnRestoreWeight(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnSetWeight(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskSleepCancel(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::RemoveTask(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::ResumeTask(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::ScheduleTaskRemoval(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::SuspendTask().

Here is the caller graph for this function:

◆ GetNewFsmState()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
EFsmState stk::Kernel< TMode, TSize, TStrategy, TPlatform >::GetNewFsmState ( KernelTask *& next)
inlineprotected

Get new FSM state.

Parameters
[out]nextNext kernel task to which Kernel can switch.
Returns
FSM state.

Definition at line 2602 of file stk.h.

2603 {
2606 }
static bool IsValidFsmState(EFsmState state)
Check if FSM state is valid.
Definition stk.h:1602
const EFsmState m_fsm[FSM_STATE_MAX][FSM_EVENT_MAX]
Definition stk.h:2913
EFsmEvent FetchNextEvent(KernelTask *&next)
Fetch next event for the FSM.
Definition stk.h:2561

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnStart(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateFsmState().

Here is the caller graph for this function:

◆ GetPlatform()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
IPlatform * stk::Kernel< TMode, TSize, TStrategy, TPlatform >::GetPlatform ( )
inlineoverridevirtual

Get platform driver instance owned by this kernel.

Returns
Pointer to the internal TPlatform cast to IPlatform*.

Implements stk::IKernel.

Definition at line 1545 of file stk.h.

1545{ return &m_platform; }

◆ GetState()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
EKernelState stk::Kernel< TMode, TSize, TStrategy, TPlatform >::GetState ( ) const
inlineoverridevirtual

Get kernel state.

Implements stk::IKernel.

Definition at line 1554 of file stk.h.

1554{ return m_kstate; }

◆ GetSwitchStrategy()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
ITaskSwitchStrategy * stk::Kernel< TMode, TSize, TStrategy, TPlatform >::GetSwitchStrategy ( )
inlineoverridevirtual

Get task-switching strategy instance owned by this kernel.

Returns
Pointer to the internal TStrategy cast to ITaskSwitchStrategy*.

Implements stk::IKernel.

Definition at line 1550 of file stk.h.

1550{ return &m_strategy; }

◆ HrtAllocateAndAddNewTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::HrtAllocateAndAddNewTask ( ITask * user_task,
Timeout periodicity_tc,
Timeout deadline_tc,
Timeout start_delay_tc )
inlineprotected

Allocate new instance of KernelTask and add it into the HRT scheduling process.

Note
Related to stk::KERNEL_HRT mode only.
Parameters
[in]user_taskUser task for which kernel task object is allocated.
[in]periodicity_tcPeriodicity time at which task is scheduled (ticks).
[in]deadline_tcDeadline time within which a task must complete its work (ticks).
[in]start_delay_tcInitial start delay for the task (ticks).

Definition at line 1715 of file stk.h.

1716 {
1718 STK_ASSERT(task != nullptr);
1719
1721
1723 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AddTask().

Here is the caller graph for this function:

◆ Initialize()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::Initialize ( uint32_t resolution_us = PERIODICITY_DEFAULT)
inlineoverridevirtual

Initialize kernel.

Parameters
[in]resolution_usResolution of the system tick (SysTick) timer in microseconds. Defaults to PERIODICITY_DEFAULT (1000 µs = 1 ms).
Note
Must be called before AddTask() and Start().
If running on an STM32 device with HAL driver or on QEMU, do not change the default resolution (PERIODICITY_DEFAULT). STM32's HAL expects 1 millisecond resolution and QEMU does not have enough resolution on Windows to operate correctly at sub-millisecond resolution.
Kernel must be in KSTATE_INACTIVE state.

Implements stk::IKernel.

Definition at line 1194 of file stk.h.

1195 {
1199
1200 // reinitialize key state variables
1201 m_task_now = nullptr;
1204
1205 // exit trap is required only for KERNEL_DYNAMIC mode
1208 {
1209 exit_trap = &m_exit_trap[0].stack;
1210 }
1211 else
1212 {
1213 exit_trap = nullptr;
1214 }
1215
1216 m_service.Initialize(this);
1217 m_platform.Initialize(this, &m_service, resolution_us, exit_trap);
1218
1219 // now ready to Start()
1221 }
KernelService m_service
Kernel service singleton exposed to running tasks via IKernelService::GetInstance().
Definition stk.h:2901

◆ InitTraps()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::InitTraps ( )
inlineprotected

Initialize stack of the traps.

Definition at line 1609 of file stk.h.

1610 {
1611 // init stack for a Sleep trap
1612 {
1614
1616 sleep.stack.access_mode = ACCESS_PRIVILEGED;
1617 #if STK_STACK_NEEDS_TASK_ID
1618 sleep.stack.tid = SYS_TASK_ID_SLEEP;
1619 #endif
1620
1621 STK_UNUSED(m_platform.InitStack(STACK_SLEEP_TRAP, &sleep.stack, &wrapper, nullptr));
1622 }
1623
1624 // init stack for an Exit trap
1626 {
1628
1630 exit.stack.access_mode = ACCESS_PRIVILEGED;
1631 #if STK_STACK_NEEDS_TASK_ID
1632 exit.stack.tid = SYS_TASK_ID_EXIT;
1633 #endif
1634
1635 STK_UNUSED(m_platform.InitStack(STACK_EXIT_TRAP, &exit.stack, &wrapper, nullptr));
1636 }
1637 }
StackMemoryWrapper< STACK_SIZE_MIN > ExitTrapStackMemory
Stack memory wrapper type for the exit trap.
Definition stk.h:104
StackMemoryWrapper<((32U))> SleepTrapStackMemory
Stack memory wrapper type for the sleep trap.
Definition stk.h:98
Storage bundle for the sleep trap: a Stack descriptor paired with its backing memory.
Definition stk.h:2871
Storage bundle for the exit trap: a Stack descriptor paired with its backing memory.
Definition stk.h:2887

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::Start().

Here is the caller graph for this function:

◆ IsDynamicMode()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
constexpr bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::IsDynamicMode ( )
inlinestaticconstexprprotected

Definition at line 2830 of file stk.h.

2830{ return ((TMode & KERNEL_DYNAMIC) != 0U); }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AddTask(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::FetchNextEvent(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::FindTaskBySP(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::Initialize(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::InitTraps(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnStop(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskExit(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::RemoveTask(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::ScheduleTaskRemoval(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::StateExit(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTaskRequest(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTaskState().

Here is the caller graph for this function:

◆ IsHrtMode()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
constexpr bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::IsHrtMode ( )
inlinestaticconstexprprotected

Definition at line 2831 of file stk.h.

2831{ return ((TMode & KERNEL_HRT) != 0U); }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AddTask(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AddTask(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::GetHrtDeadline(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::GetHrtPeriodicity(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::GetHrtRelativeDeadline(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnStart(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskSleep(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskSwitch(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::ScheduleRemoval(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::Sleep(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::SleepCancel(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::SleepUntil(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::StateSleep(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::StateSwitch(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::StateWake(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::Unbind(), stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTaskRequest(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTaskState().

Here is the caller graph for this function:

◆ IsInitialized()

◆ IsStarted()

◆ IsStaticMode()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
constexpr bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::IsStaticMode ( )
inlinestaticconstexprprotected

Definition at line 2829 of file stk.h.

2829{ return ((TMode & KERNEL_STATIC) != 0U); }

◆ IsSyncMode()

◆ IsTicklessMode()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
constexpr bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::IsTicklessMode ( )
inlinestaticconstexprprotected

◆ IsValidFsmState()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::IsValidFsmState ( EFsmState state)
inlinestaticprotected

Check if FSM state is valid.

Definition at line 1602 of file stk.h.

1603 {
1604 return ((state > FSM_STATE_NONE) && (state < FSM_STATE_MAX));
1605 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::GetNewFsmState().

Here is the caller graph for this function:

◆ OnForceContextSwitch()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnForceContextSwitch ( TId id,
Stack *& idle,
Stack *& active )
inlineprotectedvirtual

Called when task state change forces a context switch (Sleep, SleepUntil, Wait).

Parameters
[in]idTask id causing this forced context switch.
[out]idleStack of the task which must enter Idle state.
[out]activeStack of the task which must enter Active state (to which context will switch).
Returns
True if context switch is required, False otherwise.

Implements stk::IPlatform::IEventHandler.

Definition at line 1988 of file stk.h.

1989 {
1990 bool switch_context = false;
1991 KernelTask *const task = m_task_now;
1992
1993 STK_ASSERT(task != nullptr);
1994
1995 // note: called from inside ISR, therefore protection by critical section is not needed
1996
1997 if (task->GetTid() == id)
1998 {
1999 // current task is busy-waiting to be de-scheduled
2000 if (task->IsSleeping())
2001 {
2002 if ((task->m_state & KernelTask::STATE_SLEEP_PENDING) != 0U)
2003 {
2005
2007 }
2008 }
2009 else
2010 {
2012 {
2013 // current task yielded and stays runnable: let the strategy pick the next task
2014 if ((task->m_state & KernelTask::STATE_YIELD_PENDING) != 0U)
2015 {
2017
2019 }
2020 }
2021 }
2022 }
2023
2024 return switch_context;
2025 }
bool UpdateFsmState(Stack *&idle, Stack *&active)
Update FSM state.
Definition stk.h:2613
void ProcessTaskPendingSleep(KernelTask *const task)
Definition stk.h:2349
void ProcessTaskPendingYield(KernelTask *const task)
Definition stk.h:2360
@ STATE_YIELD_PENDING
Task called Yield() and the strategy handled it via OnTaskYield() (task stays runnable); cleared by t...
Definition stk.h:142
@ STATE_SLEEP_PENDING
Task called Sleep/SleepUntil/Yield; strategy's OnTaskSleep() will be invoked on the next tick (sleep-...
Definition stk.h:139

◆ OnGetTid()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
TId stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnGetTid ( Word caller_SP)
inlineoverrideprotectedvirtual

Called from the Thread process when for getting task/thread id of the process.

Parameters
[in]caller_SPValue of Stack Pointer (SP) register (for locating the calling process inside the kernel).
Returns
Task/thread id of the process (returns always valid TId belonging to a task).

Implements stk::IPlatform::IEventHandler.

Definition at line 2235 of file stk.h.

2236 {
2238 STK_ASSERT(task != nullptr);
2239
2240 return task->GetTid();
2241 }
KernelTask * FindTaskBySP(Word SP)
Find kernel task for a Stack Pointer (SP).
Definition stk.h:1804

◆ OnInheritWeight()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnInheritWeight ( TId tid,
Weight weight )
inlineprotected

Definition at line 2268 of file stk.h.

2269 {
2272
2273 if (weight != NO_WEIGHT)
2274 {
2276 STK_ASSERT(task != nullptr);
2277
2278 const Weight prev_weight = task->GetWeight();
2279
2280 if (prev_weight < weight)
2281 {
2282 task->SetCurrentWeight(weight);
2283 m_strategy.OnTaskWeightChange(task, prev_weight);
2284 }
2285 }
2286 }
static constexpr ITask * GetUserTaskFromTid(TId task_id) noexcept
Get task instance from its identifier.
Definition stk_arch.h:725

◆ OnRestoreWeight()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnRestoreWeight ( TId tid,
ISyncObject * sobj )
inlineprotected

Definition at line 2315 of file stk.h.

2316 {
2319
2321 STK_ASSERT(task != nullptr);
2322
2323 const Weight prev_weight = task->GetWeight();
2324
2325 // restore to original or boost from wait objects
2326 task->SetCurrentWeight(sobj != nullptr ? sobj->FindWeightHigherThan(task->GetWeight()) : NO_WEIGHT);
2327
2328 m_strategy.OnTaskWeightChange(task, prev_weight);
2329 }

◆ OnSetWeight()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
Weight stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnSetWeight ( TId tid,
Weight weight )
inlineprotected

Definition at line 2288 of file stk.h.

2289 {
2293
2295 STK_ASSERT(task != nullptr);
2296
2297 const Weight prev_weight = task->GetWeight(); // effective weight (base or inherited)
2298 const Weight prev_base = task->GetBaseWeight();
2299
2300 task->SetBaseWeight(weight);
2301
2302 // an inherited weight that does not exceed the new base weight is no longer a boost
2303 if ((task->GetCurrentWeight() != NO_WEIGHT) && (task->GetCurrentWeight() <= weight))
2304 {
2305 task->SetCurrentWeight(NO_WEIGHT);
2306 }
2307
2308 // always notify: the strategy may depend on parts of the weight that do not change
2309 // the effective weight while a boost is active (e.g. preemption-threshold)
2310 m_strategy.OnTaskWeightChange(task, prev_weight);
2311
2312 return prev_base;
2313 }

◆ OnStart()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnStart ( Stack *& active)
inlineoverrideprotectedvirtual

Called by platform driver immediately after a scheduler start (first tick).

Parameters
[out]activeSet to the stack of the first task to run, or to the sleep-trap stack if all tasks are initially sleeping.
Note
Delivers initial OnTaskSleep notifications to sleep-aware strategies for any tasks that were added in a sleeping state before Start() was called.
Selects the first runnable task via GetNewFsmState() and transitions the kernel to KSTATE_RUNNING.
If STK_SEGGER_SYSVIEW is enabled, emits a task-start trace event for the first task.
Warning
At least one task must have been added via AddTask(); asserts if the strategy pool is empty.

Implements stk::IPlatform::IEventHandler.

Definition at line 1869 of file stk.h.

1870 {
1871 STK_ASSERT(m_strategy.GetSize() != 0);
1872
1873 // iterate tasks and generate OnTaskSleep for a strategy for all initially sleeping tasks
1874 for (size_t i = 0U; i < TASKS_MAX; ++i)
1875 {
1876 KernelTask *const task = &m_task_storage[i];
1877
1878 if ((task->m_state & KernelTask::STATE_SLEEP_PENDING) != 0U)
1879 {
1880 STK_ASSERT(task->IsSleeping());
1881
1883
1884 // notify strategy that task is sleeping
1886 {
1887 m_strategy.OnTaskSleep(task);
1888 }
1889 }
1890 }
1891
1892 // get initial state and first task
1893 {
1895
1896 KernelTask *next = nullptr;
1898
1899 // expecting only SLEEPING or SWITCHING states
1901
1903 {
1904 m_task_now = next;
1905 active = next->GetUserStackPtr();
1906
1908 {
1909 next->HrtOnSwitchedIn();
1910 }
1911 }
1912 else
1914 {
1916 active = &m_sleep_trap[0].stack;
1917 }
1918 else
1919 {
1920 // unexpected state
1922 }
1923 }
1924
1925 // is in running state
1927 }
static void STK_KERNEL_PANIC(stk::EKernelPanicId id)
Called when the kernel detects an unrecoverable internal fault.
Definition stk_arch.h:183
EFsmState GetNewFsmState(KernelTask *&next)
Get new FSM state.
Definition stk.h:2602

◆ OnStop()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnStop ( )
inlineoverrideprotectedvirtual

Called by the platform driver after a scheduler stop (all tasks have exited).

Note
KERNEL_DYNAMIC mode only: resets FSM to FSM_STATE_NONE and transitions kernel back to KSTATE_READY so Start() may be called again.
Has no effect in KERNEL_STATIC mode (static kernels never stop).

Implements stk::IPlatform::IEventHandler.

Definition at line 1934 of file stk.h.

1935 {
1937 {
1939
1940 // is in stopped state, i.e. is ready to Start() again
1942 }
1943 }

◆ OnSuspend()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnSuspend ( bool suspended)
inlineoverrideprotectedvirtual

Called from the Thread process to suspend scheduling.

Parameters
[in]suspendedtrue if scheduling was successfully suspended, false otherwise.

Implements stk::IPlatform::IEventHandler.

Definition at line 2243 of file stk.h.

2244 {
2245 // toggle kernel state
2246 if (suspended)
2247 {
2248 if (m_kstate == KSTATE_RUNNING)
2249 {
2251 }
2252 }
2253 else
2254 {
2255 if (m_kstate == KSTATE_SUSPENDED)
2256 {
2258 }
2259 }
2260
2261 // force yield for a currently active task
2262 if (!m_task_now->IsSleeping())
2263 {
2264 m_task_now->ScheduleSleep(YIELD_TICKS);
2265 }
2266 }
static constexpr Timeout YIELD_TICKS
Ticks to yield.
Definition stk.h:1598

◆ OnTaskExit()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnTaskExit ( Stack * stack)
inlineoverrideprotectedvirtual

Called from the Thread process when task finished (its Run function exited by return).

Parameters
[out]stackStack of the exited task.

Implements stk::IPlatform::IEventHandler.

Definition at line 2155 of file stk.h.

2156 {
2158 {
2160 STK_ASSERT(task != nullptr);
2161
2162 // task is being stopped and will terminate
2163 #if STK_SEGGER_SYSVIEW
2165 #endif
2166
2167 // notify kernel to execute removal
2168 {
2169 // make change to HRT/sleep/removal state atomic (same as OnTaskSleep/OnTaskSleepUntil)
2171
2172 task->ScheduleRemoval();
2173 }
2174 }
2175 else
2176 {
2177 // kernel operating mode must be KERNEL_DYNAMIC for tasks to be able to exit
2179 }
2180 }
KernelTask * FindTaskByStack(const Stack *stack)
Find kernel task by the bound Stack instance.
Definition stk.h:1783

◆ OnTaskSleep()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnTaskSleep ( Word caller_SP,
Timeout ticks )
inlineoverrideprotectedvirtual

Called by Thread process (via IKernelService::Sleep) for exclusion of the calling process from scheduling (sleeping).

Parameters
[in]caller_SPValue of Stack Pointer (SP) register (for locating the calling process inside the kernel).
[in]ticksTime to sleep (ticks).

Implements stk::IPlatform::IEventHandler.

Definition at line 2073 of file stk.h.

2074 {
2076 STK_ASSERT(task != nullptr);
2077
2078 // make change to HRT state and sleep time atomic
2079 {
2081
2083 {
2084 task->HrtOnWorkCompleted();
2085 }
2086
2087 if (ticks > 0)
2088 {
2089 task->ScheduleSleep(ticks);
2090
2091 // trace blocked on Sleep
2092 #if STK_SEGGER_SYSVIEW
2093 SEGGER_SYSVIEW_OnTaskStopReady(task->GetUserStackPtr()->tid, TRACE_EVENT_SLEEP);
2094 #endif
2095 }
2096 }
2097
2098 // note: we do not spin long here, kernel will switch this task out from scheduling on the next tick
2099 task->BusyWaitWhileSleeping(this);
2100 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTaskSwitch().

Here is the caller graph for this function:

◆ OnTaskSleepCancel()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnTaskSleepCancel ( TId task_id)
inlineprotected

Definition at line 2141 of file stk.h.

2142 {
2144 if (task != nullptr)
2145 {
2147
2148 if (task->IsSleeping())
2149 {
2150 task->Wake();
2151 }
2152 }
2153 }

◆ OnTaskSleepUntil()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnTaskSleepUntil ( Word caller_SP,
Ticks timestamp )
inlineoverrideprotectedvirtual

Called by Thread process (via IKernelService::SleepUntil) for exclusion of the calling process from scheduling (sleeping).

Parameters
[in]caller_SPValue of Stack Pointer (SP) register (for locating the calling process inside the kernel).
[in]timestampAbsolute timestamp (ticks).
Returns
True if sleep succeeded, false otherwise.

Implements stk::IPlatform::IEventHandler.

Definition at line 2102 of file stk.h.

2103 {
2105 STK_ASSERT(task != nullptr);
2106
2107 bool result = true;
2108
2109 // make change to HRT state and sleep time atomic
2110 {
2112
2113 // calculate signed delta (handles wrap-around correctly)
2114 const Ticks delta = timestamp - m_service.m_ticks;
2115
2116 if (delta > 0)
2117 {
2119 task->ScheduleSleep(static_cast<Timeout>(Min(delta, infinite_ticks)));
2120
2121 // trace blocked on on SleepUntil
2122 #if STK_SEGGER_SYSVIEW
2123 SEGGER_SYSVIEW_OnTaskStopReady(task->GetUserStackPtr()->tid, TRACE_EVENT_SLEEP);
2124 #endif
2125 }
2126 else
2127 {
2128 result = false; // deadline already hit or passed
2129 }
2130 }
2131
2132 // note: we do not spin long here, kernel will switch this task out from scheduling on the next tick
2133 if (result)
2134 {
2135 task->BusyWaitWhileSleeping(this);
2136 }
2137
2138 return result;
2139 }

◆ OnTaskSwitch()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnTaskSwitch ( Word caller_SP)
inlineoverrideprotectedvirtual

Called by Thread process (via IKernelService::SwitchToNext) to switch to a next task.

Parameters
[in]caller_SPValue of Stack Pointer (SP) register (for locating the calling process inside the kernel).

Implements stk::IPlatform::IEventHandler.

Definition at line 2027 of file stk.h.

2028 {
2029 // let the strategy handle the yield without putting the task to sleep (e.g. to hand
2030 // the CPU to same-priority peers only), not applicable in HRT mode where Yield()
2031 // means work completion
2033 {
2035 STK_ASSERT(task != nullptr);
2036
2037 if (task != nullptr)
2038 {
2039 bool handled = false;
2040 {
2042
2043 if (!task->IsSleeping())
2044 {
2045 if (m_strategy.OnTaskYield(task))
2046 {
2047 task->ScheduleYield();
2048 handled = true;
2049 }
2050 }
2051 }
2052
2053 if (handled)
2054 {
2055 task->BusyWaitWhileYielding(this);
2056 }
2057 else
2058 {
2060 }
2061 }
2062 else
2063 {
2064 // defensive: do nothing on null task
2065 }
2066 }
2067 else
2068 {
2070 }
2071 }
void OnTaskSleep(Word caller_SP, Timeout ticks) override
Called by Thread process (via IKernelService::Sleep) for exclusion of the calling process from schedu...
Definition stk.h:2073

◆ OnTaskWait()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
EWaitResult stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnTaskWait ( Word caller_SP,
ISyncObject * sync_obj,
IMutex * mutex,
Timeout timeout )
inlineoverrideprotectedvirtual

Called from the Thread process when task needs to wait.

Parameters
[in]caller_SPValue of Stack Pointer (SP) register (for locating the calling process inside the kernel).
[in]sync_objISyncObject instance (passed by Wait).
[in]mutexIMutex instance (passed by Wait).
[in]timeoutTime to sleep (ticks).

Implements stk::IPlatform::IEventHandler.

Definition at line 2182 of file stk.h.

2183 {
2185 {
2186 STK_ASSERT(timeout != 0); // API contract: caller must not be in ISR
2187 STK_ASSERT(sync_obj != nullptr); // API contract: ISyncObject instance must be provided
2188 STK_ASSERT(mutex != nullptr); // API contract: IMutex instance must be provided
2189 STK_ASSERT((sync_obj->GetHead() == nullptr) || (sync_obj->GetHead() == &m_sync_list[0]));
2190
2192 STK_ASSERT(task != nullptr);
2193
2194 // configure waiting
2195 task->m_wait_obj->SetupWait(sync_obj, timeout);
2196
2197 // register ISyncObject if not yet
2198 if (sync_obj->GetHead() == nullptr)
2199 {
2200 m_sync_list->LinkBack(sync_obj);
2201 }
2202
2203 // start sleeping infinitely, we rely on a Wake call via WaitObject
2204 task->ScheduleSleep(WAIT_INFINITE);
2205
2206 // trace blocked on sync object's Wait
2207 #if STK_SEGGER_SYSVIEW
2208 SEGGER_SYSVIEW_OnTaskStopReady(task->GetUserStackPtr()->tid, TRACE_EVENT_WAIT);
2209 #endif
2210
2211 // unlock mutex locked externally, so that we could wait in a busy-waiting loop
2212 mutex->Unlock();
2213
2214 // note: we do not spin long here, kernel will switch this task out from scheduling on the next tick
2215 task->BusyWaitWhileSleeping(this);
2216
2217 // extract & clear this wait's result BEFORE mutex->Lock(): a contended Lock() recurses
2218 // into OnTaskWait() and reuses this same per-task WaitObject, which would otherwise
2219 // silently overwrite/clear our still-unread result
2220 const EWaitResult result = task->m_wait_obj->GetWaitResult();
2221 task->m_wait_obj->ClearState();
2222
2223 // re-lock mutex when returning to the task's execution space
2224 mutex->Lock();
2225
2226 return result;
2227 }
2228 else
2229 {
2230 STK_ASSERT(false);
2231 return WAIT_RESULT_FAIL;
2232 }
2233 }
SyncObjectList m_sync_list[STK_ALLOCATE_COUNT< TMode, KERNEL_SYNC, 1U, 0U >::Value]
List of active sync objects. Zero-size (no memory) if KERNEL_SYNC is not set.
Definition stk.h:2911

◆ OnTick()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnTick ( Stack *& idle,
Stack *& active,
Timeout & ticks )
inlineoverrideprotectedvirtual

Process one scheduler tick. Called from the platform timer/tick ISR.

Parameters
[out]idleStack descriptor to context-switch out (nullptr if no switch needed).
[out]activeStack descriptor to context-switch in (nullptr if no switch needed).
[in,out]ticks(KERNEL_TICKLESS builds only) On entry: actual number of ticks elapsed since the last call, as measured by the platform driver. On return: the number of ticks the hardware timer may suppress before the next required wakeup, computed as the minimum remaining sleep across all active tasks, clamped to [1, STK_TICKLESS_TICKS_MAX]. The platform driver programs this value into the timer to avoid unnecessary wakeups. This parameter is absent in non-tickless builds.
Returns
true if a context switch is required (idle and active are valid); false if the current task continues running.
Note
In non-tickless mode the internal tick counter always advances by exactly 1 per call.
In tickless mode (KERNEL_TICKLESS) the counter advances by the ticks value supplied by the platform driver, which may be greater than 1 after a suppressed interval.

Implements stk::IPlatform::IEventHandler.

Definition at line 1961 of file stk.h.

1966 {
1967 #if !STK_TICKLESS_IDLE
1968 // in non-tickless mode kernel is advancing strictly by 1 tick on every OnTick call
1969 enum { ticks = 1 };
1970 #endif
1971
1972 // advance internal timestamp
1973 m_service.IncrementTicks(ticks);
1974
1975 // consume elapsed and update to ticks to sleep
1976 #if STK_TICKLESS_IDLE
1977 ticks = (
1978 #else
1979 // notify compiler that we ignore a return value of UpdateTasks
1980 STK_UNUSED(
1981 #endif
1983
1984 // decide on a context switch
1985 return UpdateFsmState(idle, active);
1986 }
Timeout UpdateTasks(const Timeout elapsed_ticks)
Update tasks (sleep, requests).
Definition stk.h:2333

◆ ProcessTaskPendingSleep()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::ProcessTaskPendingSleep ( KernelTask *const task)
inlineprotected

◆ ProcessTaskPendingYield()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::ProcessTaskPendingYield ( KernelTask *const task)
inlineprotected

◆ RemoveTask() [1/2]

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::RemoveTask ( ITask * user_task)
inlineoverridevirtual

Remove a previously added task from the kernel when it is not started.

Parameters
[in]user_taskUser task to remove. Must not be nullptr.
Note
Only valid before Start() (i.e. while the kernel is not running). To remove tasks after Start() the task should return from its Run function (in KERNEL_DYNAMIC mode the slot is freed automatically on the next tick).
Warning
KERNEL_DYNAMIC mode only. Asserts if called in KERNEL_STATIC or KERNEL_HRT mode, or if called after Start().

Implements stk::IKernel.

Definition at line 1295 of file stk.h.

1296 {
1298 {
1299 STK_ASSERT(user_task != nullptr);
1301
1303 if (task != nullptr)
1304 {
1306 }
1307 }
1308 else
1309 {
1310 // kernel operating mode must be KERNEL_DYNAMIC for tasks to be able to be removed
1311 STK_ASSERT(false);
1312 }
1313 }
void RemoveTask(ITask *user_task) override
Remove a previously added task from the kernel when it is not started.
Definition stk.h:1295

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::RemoveTask(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTaskState().

Here is the caller graph for this function:

◆ RemoveTask() [2/2]

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::RemoveTask ( KernelTask * task)
inlineprotected

Remove kernel task.

Note
Removal of the kernel task means releasing it from the user task details.
Parameters
[in]taskKernel task.

Definition at line 1844 of file stk.h.

1845 {
1846 STK_ASSERT(task != nullptr);
1847
1848 #if STK_SEGGER_SYSVIEW
1849 SEGGER_SYSVIEW_OnTaskTerminate(task->GetUserStackPtr()->tid);
1850 #endif
1851
1852 // notify task about pending exit
1853 task->GetUserTask()->OnExit();
1854
1855 m_strategy.RemoveTask(task);
1856 task->Unbind();
1857 }

◆ RequestAddTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::RequestAddTask ( ITask *const user_task)
inlineprotected

Request to add new task.

Note
Must be called by the task process only!
Parameters
[in]user_taskUser task to add.

Definition at line 1729 of file stk.h.

1730 {
1731 KernelTask *const caller = FindTaskBySP(m_platform.GetCallerSP());
1732 STK_ASSERT(caller != nullptr);
1733
1734 typename KernelTask::AddTaskRequest req = { .user_task = user_task };
1735 caller->m_srt[0].add_task_req = &req;
1736
1737 // notify kernel
1739
1740 // switch out and wait for completion (due to context switch request could be processed here)
1741 if (caller->m_srt[0].add_task_req != nullptr)
1742 {
1743 m_service.SwitchToNext();
1744 }
1745
1746 // wait until request is consumed
1748 {
1749 while (caller->m_srt[0].add_task_req != nullptr)
1750 {
1752 }
1753 }
1754
1755 STK_ASSERT(caller->m_srt[0].add_task_req == nullptr);
1756 }
void ScheduleAddTask()
Signal the kernel to process a pending AddTask request on the next tick.
Definition stk.h:2801
Payload for an in-flight AddTask() request issued by a running task.
Definition stk.h:154

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::AddTask().

Here is the caller graph for this function:

◆ ResumeTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::ResumeTask ( ITask * user_task)
inlineoverridevirtual

Resume task.

Parameters
[in]user_taskPointer to the user task to resume.
Warning
Must not be called on a task blocked in OnTaskWait() on a sync object - asserts. Use CancelTaskWait() instead.

Implements stk::IKernel.

Definition at line 1401 of file stk.h.

1402 {
1403 STK_ASSERT(user_task != nullptr);
1404
1405 // avoid race with OnTick
1407
1409 STK_ASSERT(task != nullptr);
1410
1411 // must be suspended by SuspendTask, otherwise noop
1412 if ((task->m_state & KernelTask::STATE_SUSPENDED) != 0U)
1413 {
1414 // clear state
1416
1417 // wake up
1418 if (task->IsSleeping())
1419 {
1420 task->Wake();
1421 }
1422 }
1423 }
@ STATE_SUSPENDED
Task is suspended by SuspendTask.
Definition stk.h:141

◆ ScheduleAddTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::ScheduleAddTask ( )
inlineprotected

Signal the kernel to process a pending AddTask request on the next tick.

Note
Sets the REQ_ADD_TASK bit in m_request under a hw::CriticalSection::ScopedLock, so the ISR-side tick handler observes the flag safely without a data race.

Definition at line 2801 of file stk.h.

2802 {
2805 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::RequestAddTask().

Here is the caller graph for this function:

◆ ScheduleTaskRemoval()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::ScheduleTaskRemoval ( ITask * user_task)
inlineoverridevirtual

Schedule task removal from scheduling (exit).

Parameters
[in]user_taskUser task to remove. Must not be nullptr.
Warning
KERNEL_DYNAMIC mode only. Asserts if called in KERNEL_STATIC or KERNEL_HRT mode, or if called after Start().

Implements stk::IKernel.

Definition at line 1320 of file stk.h.

1321 {
1323 {
1324 STK_ASSERT(user_task != nullptr);
1326
1328
1330 if (task != nullptr)
1331 {
1332 task->ScheduleRemoval();
1333 }
1334 }
1335 else
1336 {
1337 // kernel operating mode must be KERNEL_DYNAMIC for tasks to be able to be removed
1338 STK_ASSERT(false);
1339 }
1340 }

◆ Start()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::Start ( )
inlineoverridevirtual

Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or indefinitely (KERNEL_STATIC mode).

Note
Re-initializes trap stacks on every call so Start() can be called again after a previous scheduling session ended.
If STK_SEGGER_SYSVIEW is enabled, starts tracing and registers all pre-added tasks.
Warning
At least one task must have been added via AddTask() before calling Start(). Asserts if called before Initialize().

Implements stk::IKernel.

Definition at line 1510 of file stk.h.

1511 {
1513
1514 // stacks of the traps must be re-initilized on every subsequent Start
1515 InitTraps();
1516
1517 // start tracing
1518 #if STK_SEGGER_SYSVIEW
1520 for (size_t i = 0U; i < TASKS_MAX; ++i)
1521 {
1523 if (task->IsBusy())
1524 {
1526 }
1527 }
1528 #endif
1529
1530 m_platform.Start();
1531 }
void InitTraps()
Initialize stack of the traps.
Definition stk.h:1609

◆ StateExit()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::StateExit ( KernelTask * now,
KernelTask * next,
Stack *& idle,
Stack *& active )
inlineprotected

Exits from scheduling.

Note
FSM state: stk::FSM_STATE_EXITING.
Exits only if stk::KERNEL_DYNAMIC mode is specified, otherwise ignored.
Parameters
[in]nowCurrently active kernel task (ignored).
[in]nextNext kernel task (ignored).
[out]idleStack of the task which must enter Idle state.
[out]activeStack of the task which must enter Active state (to which context will switch).

Definition at line 2766 of file stk.h.

2767 {
2768 STK_UNUSED(now);
2770
2772 {
2773 // dynamic tasks are not supported if main processes's stack memory is not provided in Start()
2774 STK_ASSERT(m_exit_trap[0].stack.SP != 0);
2775
2776 idle = nullptr;
2777 active = &m_exit_trap[0].stack;
2778
2779 m_task_now = nullptr;
2780
2781 m_platform.Stop();
2782 }
2783 else
2784 {
2787 }
2788
2789 return false;
2790 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateFsmState().

Here is the caller graph for this function:

◆ StateSleep()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::StateSleep ( KernelTask * now,
KernelTask * next,
Stack *& idle,
Stack *& active )
inlineprotected

Enters into a sleeping mode.

Note
FSM state: stk::FSM_STATE_SLEEPING.
Parameters
[in]nowCurrently active kernel task.
[in]nextNext kernel task (ignored).
[out]idleStack of the task which must enter Idle state.
[out]activeStack of the task which must enter Active state (to which context will switch).

Definition at line 2735 of file stk.h.

2736 {
2738
2739 STK_ASSERT(now != nullptr);
2740 STK_ASSERT(m_sleep_trap[0].stack.SP != 0);
2741
2742 idle = now->GetUserStackPtr();
2743 active = &m_sleep_trap[0].stack;
2744
2746
2748 {
2749 if (!now->IsPendingRemoval())
2750 {
2751 now->HrtOnSwitchedOut();
2752 }
2753 }
2754
2755 return true; // switch context
2756 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateFsmState().

Here is the caller graph for this function:

◆ StateSwitch()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::StateSwitch ( KernelTask * now,
KernelTask * next,
Stack *& idle,
Stack *& active )
inlineprotected

Switches contexts.

Note
FSM state: stk::FSM_STATE_SWITCHING.
Parameters
[in]nowCurrently active kernel task.
[in]nextNext kernel task.
[out]idleStack of the task which must enter Idle state.
[out]activeStack of the task which must enter Active state (to which context will switch).

Definition at line 2656 of file stk.h.

2657 {
2658 STK_ASSERT(now != nullptr);
2659 STK_ASSERT(next != nullptr);
2660
2661 bool switch_context = false;
2662
2663 // if equal: do not switch context because task did not change
2664 if (next != now)
2665 {
2666 idle = now->GetUserStackPtr();
2667 active = next->GetUserStackPtr();
2668
2669 // if stack memory is exceeded these assertions will be hit
2670 #if STK_STACK_GUARD
2671 if (now->IsBusy())
2672 {
2673 // current task could exit, thus we check it with IsBusy to avoid referencing nullptr returned by GetUserTask()
2674 STK_ASSERT(now->GetUserTask()->GetStack()[0] == STK_STACK_MEMORY_FILLER);
2675 }
2676 STK_ASSERT(next->GetUserTask()->GetStack()[0] == STK_STACK_MEMORY_FILLER);
2677 #endif
2678
2679 m_task_now = next;
2680
2682 {
2683 if (now->m_hrt[0].done)
2684 {
2685 now->HrtOnSwitchedOut();
2686 next->HrtOnSwitchedIn();
2687 }
2688 }
2689
2690 switch_context = true;
2691 }
2692
2693 return switch_context;
2694 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateFsmState().

Here is the caller graph for this function:

◆ StateWake()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::StateWake ( KernelTask * now,
KernelTask * next,
Stack *& idle,
Stack *& active )
inlineprotected

Wakes up after sleeping.

Note
FSM state: stk::FSM_STATE_WAKING.
Parameters
[in]nowCurrently active kernel task (ignored).
[in]nextNext kernel task.
[out]idleStack of the task which must enter Idle state.
[out]activeStack of the task which must enter Active state (to which context will switch).

Definition at line 2703 of file stk.h.

2704 {
2705 STK_UNUSED(now);
2706
2707 STK_ASSERT(next != nullptr);
2708
2709 idle = &m_sleep_trap[0].stack;
2710 active = next->GetUserStackPtr();
2711
2712 // if stack memory is exceeded these assertions will be hit
2714 #if STK_STACK_GUARD
2715 STK_ASSERT(next->GetUserTask()->GetStack()[0] == STK_STACK_MEMORY_FILLER);
2716 #endif
2717
2718 m_task_now = next;
2719
2721 {
2722 next->HrtOnSwitchedIn();
2723 }
2724
2725 return true; // switch context
2726 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateFsmState().

Here is the caller graph for this function:

◆ SuspendTask()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::SuspendTask ( ITask * user_task,
bool & suspended )
inlineoverridevirtual

Suspend task.

Parameters
[in]user_taskPointer to the user task to suspend.
[out]suspendedSet to true if task is suspended.
Note
hw::CriticalSection must not be active otherwise a deadlock will happen if task is suspending self.

Implements stk::IKernel.

Definition at line 1348 of file stk.h.

1349 {
1350 STK_ASSERT(user_task != nullptr);
1351
1352 bool self = false;
1353
1354 // avoid race with OnTick
1355 {
1357
1359 STK_ASSERT(task != nullptr);
1360
1361 // nesting not supported, must not be suspended by SuspendTask
1362 STK_ASSERT((task->m_state & KernelTask::STATE_SUSPENDED) == 0U);
1363
1364 // only suspend if the task is currently awake: if it is already sleeping
1365 // (e.g. blocked on a mutex or timed Sleep), do not overwrite m_time_sleep,
1366 // that would corrupt the original sleep state and, for sync-object waits,
1367 // would interfere with WaitObject::Tick()
1368 suspended = !task->IsSleeping();
1369 if (suspended == true)
1370 {
1371 task->ScheduleSleep(WAIT_INFINITE);
1372
1373 // check if suspending self
1374 self = (task == m_task_now);
1375
1376 // trace blocked via Suspend
1377 if (self)
1378 {
1379 #if STK_SEGGER_SYSVIEW
1381 #endif
1382 }
1383
1384 // set state
1386 }
1387 }
1388
1389 // note: we do not spin long here, kernel will switch this task out from scheduling on the next tick
1390 if (self)
1391 {
1392 m_task_now->BusyWaitWhileSleeping(this);
1393 }
1394 }

◆ UpdateFsmState()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
bool stk::Kernel< TMode, TSize, TStrategy, TPlatform >::UpdateFsmState ( Stack *& idle,
Stack *& active )
inlineprotected

Update FSM state.

Parameters
[out]idleStack of the task which must enter Idle state.
[out]activeStack of the task which must enter Active state (to which context will switch).
Returns
FSM state.

Definition at line 2613 of file stk.h.

2614 {
2615 KernelTask *const now = m_task_now, *next = nullptr;
2616 bool switch_context = false;
2617
2619
2620 switch (new_state)
2621 {
2625 break;
2626 case FSM_STATE_SLEEPING:
2629 break;
2630 case FSM_STATE_WAKING:
2633 break;
2634 case FSM_STATE_EXITING:
2637 break;
2638 case FSM_STATE_NONE:
2639 break; // valid intermittent non-persisting state: no-transition
2640 case FSM_STATE_MAX:
2641 default: // invalid state value
2643 break;
2644 }
2645
2646 return switch_context;
2647 }
EFsmState
Finite-state machine (FSM) state. Encodes what the kernel is currently doing between two consecutive ...
Definition stk.h:1570
bool StateWake(KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
Wakes up after sleeping.
Definition stk.h:2703
bool StateExit(KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
Exits from scheduling.
Definition stk.h:2766
bool StateSwitch(KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
Switches contexts.
Definition stk.h:2656
bool StateSleep(KernelTask *now, KernelTask *next, Stack *&idle, Stack *&active)
Enters into a sleeping mode.
Definition stk.h:2735

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnForceContextSwitch(), and stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTick().

Here is the caller graph for this function:

◆ UpdateSyncObjects()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::UpdateSyncObjects ( const Timeout elapsed_ticks)
inlineprotected

Update synchronization objects.

Definition at line 2510 of file stk.h.

2511 {
2513
2514 while (itr != nullptr)
2515 {
2516 ISyncObject::ListEntryType *const next = itr->GetNext();
2517
2519 {
2520 m_sync_list->Unlink(itr);
2521 }
2522
2523 itr = next;
2524 }
2525 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTasks().

Here is the caller graph for this function:

◆ UpdateTaskRequest()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
void stk::Kernel< TMode, TSize, TStrategy, TPlatform >::UpdateTaskRequest ( )
inlineprotected

Update pending task requests.

Definition at line 2529 of file stk.h.

2530 {
2531 // process AddTask requests coming from tasks (KERNEL_DYNAMIC mode only, KERNEL_HRT is
2532 // excluded as we assume that HRT tasks must be known to the kernel before a Start())
2534 {
2535 // process serialized AddTask request made from another active task, requesting process
2536 // is currently waiting due to SwitchToNext()
2537 if ((m_request & REQ_ADD_TASK) != 0U)
2538 {
2540
2541 for (size_t i = 0U; i < TASKS_MAX; ++i)
2542 {
2543 KernelTask *const task = &m_task_storage[i];
2544
2545 if (task->m_srt[0].add_task_req != nullptr)
2546 {
2547 AllocateAndAddNewTask(task->m_srt[0].add_task_req->user_task);
2548
2549 task->m_srt[0].add_task_req = nullptr;
2551 }
2552 }
2553 }
2554 }
2555 }

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTasks().

Here is the caller graph for this function:

◆ UpdateTasks()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
Timeout stk::Kernel< TMode, TSize, TStrategy, TPlatform >::UpdateTasks ( const Timeout elapsed_ticks)
inlineprotected

Update tasks (sleep, requests).

Definition at line 2333 of file stk.h.

2334 {
2335 // sync objects are updated before UpdateTaskRequest which may add a new object (newly added object must become 1 tick older)
2337 {
2339 }
2340
2341 if (m_request != REQ_NONE)
2342 {
2344 }
2345
2347 }
void UpdateTaskRequest()
Update pending task requests.
Definition stk.h:2529
Timeout UpdateTaskState(const Timeout elapsed_ticks)
Update task state: process removals, deliver sleep/wake notifications, advance sleep timers,...
Definition stk.h:2396
void UpdateSyncObjects(const Timeout elapsed_ticks)
Update synchronization objects.
Definition stk.h:2510

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnTick().

Here is the caller graph for this function:

◆ UpdateTaskState()

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
Timeout stk::Kernel< TMode, TSize, TStrategy, TPlatform >::UpdateTaskState ( const Timeout elapsed_ticks)
inlineprotected

Update task state: process removals, deliver sleep/wake notifications, advance sleep timers, and track HRT durations.

Parameters
[in]elapsed_ticksNumber of ticks elapsed since the previous call. Always 1 in non-tickless mode, may be >1 in tickless mode.
Returns
In non-tickless mode: always 1. In tickless mode (KERNEL_TICKLESS): the minimum remaining sleep ticks across all active tasks, clamped to [1, STK_TICKLESS_TICKS_MAX]. The platform driver uses this value to program the next timer wakeup interval, suppressing timer/tick ISR for that many ticks when the system would otherwise be idle.
Note
Sleep entry/exit protocol: ScheduleSleep() sets STATE_SLEEP_PENDING and stores m_time_sleep = -ticks. This function's first pass over a newly-sleeping task (the "entry tick") consumes STATE_SLEEP_PENDING and delivers OnTaskSleep() to the strategy, but does NOT also advance m_time_sleep on that same pass - doing both in one call would let a 1-tick sleep collapse to zero elapsed time (OnTaskSleep and OnTaskWake firing back-to-back before the task was ever excluded from scheduling). The entry tick is therefore required to be a single, uncoalesced tick (asserted below); this holds because a task can only enter STATE_SLEEP_PENDING by putting itself to sleep, which means it was actively running (not idle) up to that point, so tickless coalescing, which only suppresses ticks while the CPU is idle, cannot have applied yet. If Wake()/SleepCancel() races in before the entry tick runs, STATE_WAKE_PENDING is set alongside STATE_SLEEP_PENDING. The entry tick then delivers OnTaskSleep() followed immediately by the normal advance (and OnTaskWake(), since m_time_sleep was already primed to -1 by Wake()) in the same pass, so the task still resumes on the next tick as promised, with the two notifications correctly paired instead of an orphaned OnTaskWake(). Tasks sleeping via WAIT_INFINITE (IsSleepInfinite()) are excluded from the per-tick advance entirely so they never spuriously time out; only an explicit Wake() (which directly sets m_time_sleep = -1) ends an infinite sleep.

Definition at line 2396 of file stk.h.

2397 {
2399
2400 for (size_t i = 0U; i < TASKS_MAX; ++i)
2401 {
2402 KernelTask *const task = &m_task_storage[i];
2403
2405 {
2406 // a pending yield is consumed by this tick (the strategy already moved its cursor)
2407 if ((task->m_state & KernelTask::STATE_YIELD_PENDING) != 0U)
2408 {
2410 }
2411 }
2412
2413 if (task->IsSleeping())
2414 {
2416 {
2417 // task is pending removal, wait until it is switched out
2418 if (task->IsPendingRemoval())
2419 {
2420 const size_t tasks_left = m_strategy.GetSize();
2421
2422 if ((task != m_task_now) ||
2423 ((tasks_left == 1U) && (m_fsm_state == FSM_STATE_SLEEPING)))
2424 {
2426 continue;
2427 }
2428 }
2429 }
2430
2431 bool just_entered_sleep = false;
2432
2433 // note: only currently scheduled task can be pending to sleep
2434 if ((task->m_state & KernelTask::STATE_SLEEP_PENDING) != 0U)
2435 {
2436 STK_ASSERT(elapsed_ticks == 1); // entry tick must be a single, uncoalesced tick
2437
2438 // if Wake() raced in before this entry tick ran, STATE_WAKE_PENDING is set:
2439 // deliver OnTaskSleep() below as usual, then fall through to the advance block
2440 // in this same pass instead of waiting an extra tick, so the paired OnTaskWake()
2441 // still fires on schedule.
2442 const bool wake_pending = ((task->m_state & KernelTask::STATE_WAKE_PENDING) != 0U);
2443
2445
2447 }
2448
2449 if (!just_entered_sleep && !task->IsSleepInfinite())
2450 {
2451 // advance sleep time by number of elapsed ticks (always 1 if non-Tickless)
2452 task->m_time_sleep += elapsed_ticks;
2453
2454 // deliver sleep event to the strategy
2456 {
2457 // notify strategy that the task woke up
2458 if (!task->IsSleeping())
2459 {
2460 m_strategy.OnTaskWake(task);
2461 }
2462 }
2463 }
2464 }
2465 else
2466 {
2468 {
2469 // in HRT mode we trace how long task spent in active state (doing some work)
2470 if (task->IsBusy())
2471 {
2472 task->m_hrt[0].duration += elapsed_ticks;
2473
2474 // check if deadline is missed (HRT failure)
2475 if (task->HrtIsDeadlineMissed(task->m_hrt[0].duration))
2476 {
2477 // report deadline overrun to the strategy which supports overrun recovery
2479 {
2480 if (!m_strategy.OnTaskDeadlineMissed(task))
2481 {
2482 // report failure if it could not be recovered by the scheduling strategy
2483 task->HrtHardFailDeadline(&m_platform);
2484 }
2485 }
2486 else
2487 {
2488 task->HrtHardFailDeadline(&m_platform);
2489 }
2490 }
2491 }
2492 }
2493 }
2494
2495 // get the number of ticks the driver has to keep CPU in Idle
2497 {
2498 if ((sleep_ticks > 1) && task->IsBusy())
2499 {
2500 sleep_ticks = task->GetSleepTicks(sleep_ticks);
2501 }
2502 }
2503 }
2504
2505 return sleep_ticks;
2506 }
Timeout GetInitialSleepTicks()
static constexpr bool IsTicklessMode()
Definition stk.h:2833

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::UpdateTasks().

Here is the caller graph for this function:

Member Data Documentation

◆ m_exit_trap

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
ExitTrapStack stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_exit_trap[STK_ALLOCATE_COUNT< TMode, KERNEL_DYNAMIC, 1U, 0U >::Value]
protected

Exit trap: zero-size in KERNEL_STATIC mode; one entry in KERNEL_DYNAMIC mode.

Definition at line 2907 of file stk.h.

◆ m_fsm

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
const EFsmState stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_fsm[FSM_STATE_MAX][FSM_EVENT_MAX]
protected
Initial value:

Compile-time FSM transition table. Indexed as m_fsm[current_state][event] -> next_state. FSM_STATE_NONE as a next-state means "no transition": the FSM stays in the current state. Updated by UpdateFsmState() each tick via GetNewFsmState() -> FetchNextEvent().

Definition at line 2913 of file stk.h.

2913 {
2914 // FSM_EVENT_SWITCH FSM_EVENT_SLEEP FSM_EVENT_WAKE FSM_EVENT_EXIT
2919 };

◆ m_fsm_state

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
EFsmState stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_fsm_state
protected

Current FSM state. Drives context-switch decision on every tick.

Definition at line 2908 of file stk.h.

◆ m_kstate

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
volatile EKernelState stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_kstate
protected

Current kernel state.

Definition at line 2910 of file stk.h.

◆ m_platform

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
TPlatform stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_platform
protected

◆ m_request

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
volatile uint8_t stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_request
protected

Bitmask of pending ERequest flags from running tasks. Written by tasks, read/cleared by UpdateTaskRequest() in tick context.

Definition at line 2909 of file stk.h.

◆ m_service

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
KernelService stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_service
protected

Kernel service singleton exposed to running tasks via IKernelService::GetInstance().

Definition at line 2901 of file stk.h.

◆ m_sleep_trap

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
SleepTrapStack stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_sleep_trap[1]
protected

Sleep trap (always present): executed when all tasks are sleeping.

Definition at line 2906 of file stk.h.

◆ m_strategy

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
TStrategy stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_strategy
protected

Task-switching strategy (determines which task runs next).

Definition at line 2903 of file stk.h.

◆ m_sync_list

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
SyncObjectList stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_sync_list[STK_ALLOCATE_COUNT< TMode, KERNEL_SYNC, 1U, 0U >::Value]
protected

List of active sync objects. Zero-size (no memory) if KERNEL_SYNC is not set.

Definition at line 2911 of file stk.h.

◆ m_task_now

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
KernelTask* stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_task_now
protected

Currently executing task, or nullptr before Start() or after all tasks exit.

Definition at line 2904 of file stk.h.

◆ m_task_storage

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
TaskStorageType stk::Kernel< TMode, TSize, TStrategy, TPlatform >::m_task_storage
protected

Static pool of TSize KernelTask slots (free slots have m_user == nullptr).

Definition at line 2905 of file stk.h.

◆ TASKS_MAX

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
size_t stk::Kernel< TMode, TSize, TStrategy, TPlatform >::TASKS_MAX = TSize
staticconstexpr

Maximum number of concurrently registered tasks. Fixed at compile time. Exceeding this limit in AddTask() triggers a compile-time assert (TASKS_MAX > 0) and a runtime STK_ASSERT.

Definition at line 1151 of file stk.h.

◆ YIELD_TICKS

template<uint8_t TMode, uint32_t TSize, class TStrategy, class TPlatform>
Timeout stk::Kernel< TMode, TSize, TStrategy, TPlatform >::YIELD_TICKS = 1
staticconstexprprotected

Ticks to yield.

Yield with 2 ticks: 1 will be incremented on the next OnTick call by UpdateTasks and remaining 1 will cause a context switch by UpdateFsmState when strategy detects it as a sleeping test.

Definition at line 1598 of file stk.h.


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