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::IKernel Class Referenceabstract

Interface for the implementation of the kernel of the scheduler. It supports Soft and Hard Real-Time modes. More...

#include <stk_common.h>

Inheritance diagram for stk::IKernel:
Collaboration diagram for stk::IKernel:

Public Types

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

Public Member Functions

virtual void Initialize (uint32_t resolution_us=PERIODICITY_DEFAULT)=0
 Initialize kernel.
virtual EAddResult AddTask (ITask *user_task)=0
 Add user task.
virtual EAddResult AddTask (ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc)=0
 Add user task.
virtual void RemoveTask (ITask *user_task)=0
 Remove a previously added task from the kernel when it is not started.
virtual void ScheduleTaskRemoval (ITask *user_task)=0
 Schedule task removal from scheduling (exit).
virtual ESuspendResult SuspendTask (ITask *user_task)=0
 Suspend task.
void SuspendTask (ITask *user_task, bool &suspended)
 Suspend task (legacy form).
virtual EResumeResult ResumeTask (ITask *user_task)=0
 Resume task suspended by SuspendTask(), or lift its deferred suspension.
virtual void CancelTaskWait (ITask *user_task)=0
 Cancel a task's in-progress wait or sleep, waking it early.
virtual bool GetTaskState (ITask *user_task, TaskStateInfo &info) const =0
 Get a snapshot of the kernel-side state of a task.
virtual size_t EnumerateKernelTasks (ArrayView< IKernelTask * > tasks)=0
 Enumerate kernel tasks.
virtual size_t EnumerateTasks (ArrayView< ITask * > user_tasks)=0
 Enumerate user tasks.
template<size_t TMaxCount, typename TCallback>
size_t EnumerateTasksT (TCallback &&callback)
 Enumerate tasks, invoking a callback for each active task.
virtual ELockResult SetSchedulerLock (bool lock)=0
 Lock or unlock task switching. Ticks, timeouts and ISRs keep running.
virtual void Start ()=0
 Start kernel scheduling.
virtual EKernelState GetState () const =0
 Get a snapshot of the kernel state.
virtual IPlatform * GetPlatform ()=0
 Get platform driver instance.
virtual ITaskSwitchStrategy * GetSwitchStrategy ()=0
 Get switch strategy instance.

Protected Member Functions

 ~IKernel ()=default
 Destructor.

Detailed Description

Interface for the implementation of the kernel of the scheduler. It supports Soft and Hard Real-Time modes.

Note
Mediator design pattern.

Definition at line 1536 of file stk_common.h.

Member Enumeration Documentation

◆ EKernelState

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().

KSTATE_LOCKED 

Running, but task switching is disabled with IKernelService::LockScheduler(). Ticks, timeouts and ISRs keep running.

Definition at line 1542 of file stk_common.h.

1543 {
1544 KSTATE_INACTIVE = 0,
1545 KSTATE_READY,
1549 };
@ KSTATE_RUNNING
Initialized and running, IKernel::Start() was called successfully.
@ KSTATE_SUSPENDED
Scheduling is suspended with IKernelService::Suspend().
@ KSTATE_LOCKED
Running, but task switching is disabled with IKernelService::LockScheduler(). Ticks,...
@ KSTATE_INACTIVE
Not ready, IKernel::Initialize() must be called.
@ KSTATE_READY
Ready to start, IKernel::Start() must be called.

Constructor & Destructor Documentation

◆ ~IKernel()

stk::IKernel::~IKernel ( )
protecteddefault

Destructor.

Note
Protected by design. Prevents unsafe polymorphic delete.

Member Function Documentation

◆ AddTask() [1/2]

virtual EAddResult stk::IKernel::AddTask ( ITask * user_task)
pure virtual

Add user task.

Note
This function is for Soft Real-Time modes only (i.e. KERNEL_HRT must not be set in the kernel mode flags).
Before Start(): the task is bound and added to the strategy immediately.
After Start() (KERNEL_DYNAMIC only): the task is bound and added immediately, inside a critical section, then scheduled by the next tick. The call does not block, does not yield and is not deferred to the tick handler, so it is also valid while the caller holds a critical section.
ISR-safe in KERNEL_DYNAMIC mode. Restrictions for an ISR caller:
  • the whole operation (stack initialization, MPU setup, ITask::GetStack(), GetAccessMode(), GetMpuRegions(), GetTimeSlice() and GetWeight()) runs with interrupts masked, so keep the stack of such a task modest and call from a low-priority ISR;
  • on Cortex-M the ISR priority must be numerically above (less urgent than) the SVCall priority (STK_CORTEX_M_SVCALL_ISR_PRIORITY), otherwise it is not masked by the critical section of an unprivileged task;
  • with KERNEL_TICKLESS, a task added from an ISR while all other tasks are sleeping is first scheduled when the already armed timer expires (up to the current idle period), not on the next tick; a call from a task is not affected;
  • the kernel is assumed to be per-core: the critical section excludes the tick of the local core only.
Parameters
[in]user_taskPointer to the user task to add.
Returns
See EAddResult. The kernel is not changed if the result is not ADD_OK.
Warning
Error handling depends on the kernel mode:
  • KERNEL_DYNAMIC: any failure is only returned, never asserted. The caller is responsible for checking the result (assert, retry or recover), a task which is not added is silently dropped otherwise (e.g. ADD_FAIL_POOL_FULL, ADD_FAIL_DUPLICATE);
  • other modes: any failure asserts (application design failure), in a release build the failure is not reported and the task is not added.
Note
A task which has been removed (ITask::OnExit() was called) can be added again, the same ITask object and stack are reused. Before the removal is completed the call fails with ADD_FAIL_DUPLICATE.
Warning
The task and stack collision check is always performed, also in a release build.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

Referenced by stk::time::TimerHost::Initialize().

Here is the caller graph for this function:

◆ AddTask() [2/2]

virtual EAddResult stk::IKernel::AddTask ( ITask * user_task,
Timeout periodicity_tc,
Timeout deadline_tc,
Timeout start_delay_tc )
pure virtual

Add user task.

Note
This function is for Hard Real-time mode only, e.g. stk::KERNEL_HRT is used as parameter.
Parameters
[in]user_taskPointer to the user task to add.
[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). 0 means activate immediately.
Note
Periodicity and deadline must be > 0 and < INT32_MAX, start delay must be >= 0.
Returns
See EAddResult. The kernel is not changed if the result is not ADD_OK. ADD_FAIL_INVALID is returned for a null task, an uninitialized or already started kernel, invalid timing parameters, or a call outside KERNEL_HRT mode.
Warning
Tasks must be added before the scheduler is started (before Start()). Adding an HRT task after Start() is not supported, not even from an ISR or in KERNEL_DYNAMIC mode: the HRT schedule (periodicity, deadlines, start delays) is built from the complete task set and is not recomputed at runtime.
Error handling depends on the kernel mode:
  • KERNEL_DYNAMIC: any failure is only returned, never asserted. The caller is responsible for checking the result;
  • KERNEL_STATIC: any failure asserts (application design failure), in a release build the failure is only returned and the task is not added.
The task and stack collision check is always performed, also in a release build.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ CancelTaskWait()

virtual void stk::IKernel::CancelTaskWait ( ITask * user_task)
pure virtual

Cancel a task's in-progress wait or sleep, waking it early.

Parameters
[in]user_taskPointer to the user task whose wait should be cancelled.
Note
Applies to a task blocked in IKernelService::Wait() (KERNEL_SYNC mode) and to a task sleeping via Sleep()/SleepUntil(). No-op if the task is running or suspended.
The cancelled task's IKernelService::Wait() call returns WAIT_RESULT_CANCELED - distinct from WAIT_RESULT_SIGNAL (resource was NOT acquired/signalled) and WAIT_RESULT_TIMEOUT (the timeout, if any, had not yet expired).
Primitives built on top of IKernelService::Wait() surface this in their own terms: the boolean Mutex/FastMutex::TimedLock(), Semaphore::Wait() and Event::Wait() collapse it into their failure result, while the extended variants (FastMutex::TimedLockEx(), Semaphore::WaitEx(), Event::WaitEx()) return WAIT_RESULT_CANCELED as is; EventFlags::Wait() reports it as EventFlags::ERROR_CANCELED, distinct from EventFlags::ERROR_TIMEOUT.
See also
IKernelService::SleepCancel (same effect, addressed by task id and ISR-safe).

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ EnumerateKernelTasks()

virtual size_t stk::IKernel::EnumerateKernelTasks ( ArrayView< IKernelTask * > tasks)
pure virtual

Enumerate kernel tasks.

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

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ EnumerateTasks()

virtual size_t stk::IKernel::EnumerateTasks ( ArrayView< ITask * > user_tasks)
pure virtual

Enumerate user tasks.

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

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

Referenced by EnumerateTasksT().

Here is the caller graph for this function:

◆ EnumerateTasksT()

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

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:886

Definition at line 1744 of file stk_common.h.

1745 {
1746 STK_STATIC_ASSERT(TMaxCount > 0U);
1747
1748 ITask *tasks[TMaxCount] = {};
1749 size_t count = EnumerateTasks(ArrayView<ITask *>(tasks, TMaxCount));
1750 size_t i = 0U;
1751 bool fetch_next = true;
1752
1753 while ((i < count) && fetch_next)
1754 {
1755 fetch_next = callback(tasks[i]);
1756 ++i;
1757 }
1758
1759 return i;
1760 }
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:560
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:

◆ GetPlatform()

virtual IPlatform * stk::IKernel::GetPlatform ( )
pure virtual

Get platform driver instance.

Returns
Pointer to the IPlatform concrete class instance.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ GetState()

virtual EKernelState stk::IKernel::GetState ( ) const
pure virtual

Get a snapshot of the kernel state.

Returns
Kernel state.
See also
EKernelState

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ GetSwitchStrategy()

virtual ITaskSwitchStrategy * stk::IKernel::GetSwitchStrategy ( )
pure virtual

Get switch strategy instance.

Returns
Pointer to the ITaskSwitchStrategy concrete class instance.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ GetTaskState()

virtual bool stk::IKernel::GetTaskState ( ITask * user_task,
TaskStateInfo & info ) const
pure virtual

Get a snapshot of the kernel-side state of a task.

Parameters
[in]user_taskPointer to the user task to query. Must not be nullptr.
[out]infoReceives the snapshot (see TaskStateInfo). Written only if the function returns true, left unchanged otherwise.
Returns
true if the query succeeded and info is valid (TaskStateInfo::state is TASK_STATE_REMOVED if the task is not bound to a kernel slot), false if user_task is nullptr or the kernel is built without KERNEL_TELEMETRY.
Note
The check order resolves overlaps: a task suspended by SuspendTask() or blocked in IKernelService::Wait() is also asleep internally, but is reported as TASK_STATE_SUSPENDED or TASK_STATE_WAITING respectively, never as TASK_STATE_SLEEPING.
The result is a snapshot, the task can change state immediately after the call.
KERNEL_TELEMETRY mode only.
Warning
ISR-safe. Execution time is proportional to the number of task slots.
See also
SuspendTask, CancelTaskWait, ETaskState, TaskStateInfo, KERNEL_TELEMETRY

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ Initialize()

virtual void stk::IKernel::Initialize ( uint32_t resolution_us = PERIODICITY_DEFAULT)
pure virtual

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.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

References stk::PERIODICITY_DEFAULT.

◆ RemoveTask()

virtual void stk::IKernel::RemoveTask ( ITask * user_task)
pure virtual

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
Must only be called when kernel is not running, otherwise call ScheduleTaskRemoval.
KERNEL_DYNAMIC mode only. Asserts if the kernel is not KERNEL_DYNAMIC or if called after Start().
See also
ScheduleTaskRemoval

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ ResumeTask()

virtual EResumeResult stk::IKernel::ResumeTask ( ITask * user_task)
pure virtual

Resume task suspended by SuspendTask(), or lift its deferred suspension.

Parameters
[in]user_taskPointer to the user task to resume.
Returns
See EResumeResult.
Note
ISR-safe.
A task blocked in IKernelService::Wait() is not woken by this call (its wait is not a suspension). Use CancelTaskWait() to interrupt that kind of wait.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ ScheduleTaskRemoval()

virtual void stk::IKernel::ScheduleTaskRemoval ( ITask * user_task)
pure virtual

Schedule task removal from scheduling (exit).

Parameters
[in]user_taskUser task to remove. Must not be nullptr.
Warning
KERNEL_DYNAMIC mode only. Asserts if the kernel is not KERNEL_DYNAMIC or if called before Start() (i.e. while the kernel is not yet running). Use RemoveTask instead to remove a task while the kernel is not running.
See also
RemoveTask

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ SetSchedulerLock()

virtual ELockResult stk::IKernel::SetSchedulerLock ( bool lock)
pure virtual

Lock or unlock task switching. Ticks, timeouts and ISRs keep running.

Parameters
[in]locktrue to lock, false to unlock.
Returns
Previous lock state (LOCK_WAS_UNLOCKED / LOCK_WAS_LOCKED), or LOCK_FAIL / LOCK_FAIL_ISR.
Note
Kernel-level primitive behind IKernelService::LockScheduler(), UnlockScheduler() and RestoreSchedulerLock() (and their stk:: helpers), application code should use those. Always reports the PREVIOUS state.
Not nested. Task context only. Not available in KERNEL_HRT mode (LOCK_FAIL). While locked the kernel state is KSTATE_LOCKED.
See also
IKernelService::LockScheduler for the restrictions that apply to the lock holder.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ Start()

virtual void stk::IKernel::Start ( )
pure virtual

Start kernel scheduling.

Note
Does not return in KERNEL_STATIC mode; in KERNEL_DYNAMIC mode returns after all tasks have exited. Must be called after Initialize() and AddTask().
Kernel must be in KSTATE_READY state.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

◆ SuspendTask() [1/2]

virtual ESuspendResult stk::IKernel::SuspendTask ( ITask * user_task)
pure virtual

Suspend task.

Parameters
[in]user_taskPointer to the user task to suspend.
Returns
See ESuspendResult. A task that is sleeping or blocked on a synchronization object gets a deferred suspension (SUSPEND_DEFERRED): its sleep/wait finishes normally (the wait result is preserved) and the task is then parked until ResumeTask().
Note
ISR-safe. From an ISR the interrupted task is switched out by the next tick, no forced context switch is requested (SVC is illegal in handler mode).
When a task suspends itself (task context) the call returns after it has been resumed.
hw::CriticalSection must not be active otherwise a deadlock will happen if task is suspending self.
Warning
A task which holds the scheduler lock (see IKernelService::LockScheduler) must not suspend itself: asserts in debug builds, in release builds does nothing and returns SUSPEND_FAIL. Suspending another task is allowed.

Implemented in stk::Kernel< TMode, TSize, TStrategy, TPlatform >.

Referenced by SuspendTask().

Here is the caller graph for this function:

◆ SuspendTask() [2/2]

void stk::IKernel::SuspendTask ( ITask * user_task,
bool & suspended )
inline

Suspend task (legacy form).

Parameters
[in]user_taskPointer to the user task to suspend.
[out]suspendedSet to true if the task is suspended immediately (SUSPEND_DONE).
See also
SuspendTask(ITask *)

Definition at line 1661 of file stk_common.h.

1662 {
1663 suspended = (SuspendTask(user_task) == SUSPEND_DONE);
1664 }
@ SUSPEND_DONE
Task was runnable and is suspended now.
Definition stk_common.h:174
virtual ESuspendResult SuspendTask(ITask *user_task)=0
Suspend task.

References stk::SUSPEND_DONE, and SuspendTask().

Here is the call graph for this function:

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