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_common.h
Go to the documentation of this file.
1/*
2 * SuperTinyKernel(TM) RTOS: Lightweight High-Performance Deterministic C++ RTOS for Embedded Systems.
3 *
4 * Source: https://github.com/SuperTinyKernel-RTOS
5 *
6 * Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com>. All Rights Reserved.
7 * License: MIT License, see LICENSE for a full text.
8 */
9
10#ifndef STK_COMMON_H_
11#define STK_COMMON_H_
12
13#include "stk_defs.h"
14#include "stk_linked_list.h"
15
19
20namespace stk {
21
22// Forward declarations:
23class IKernelService;
24class IKernelTask;
25class ITask;
26class ISyncObject;
27namespace tz { namespace nsec { namespace util {
28 class CmseISyncObjectWrapper;
29}}}
30
35enum EAccessMode : uint32_t
36{
38 ACCESS_PRIVILEGED = (1 << 0),
39 ACCESS_SECURE = (1 << 1)
40};
41
45enum EKernelMode : uint8_t
46{
47 KERNEL_STATIC = (1 << 0),
48 KERNEL_DYNAMIC = (1 << 1),
49 KERNEL_HRT = (1 << 2),
50 KERNEL_SYNC = (1 << 3),
51 KERNEL_TICKLESS = (1 << 4),
52 KERNEL_TIMESLICE = (1 << 5),
53 KERNEL_TELEMETRY = (1 << 6)
54};
55
76
89
100
110
114enum ESystemTaskId : uint32_t
115{
116 SYS_TASK_ID_SLEEP = 0xFFFFFFFF,
117 SYS_TASK_ID_EXIT = 0xFFFFFFFE
118};
119
124enum ETraceEventId : uint32_t
125{
128 TRACE_EVENT_SLEEP = 1000 + 1,
129 TRACE_EVENT_WAIT = 1000 + 2,
131};
132
143
152
160typedef uintptr_t Word;
161
165typedef Word TId;
166
170typedef int32_t Timeout;
171
175typedef int64_t Ticks;
176
180typedef int64_t Time;
181
185typedef uint64_t Cycles;
186
190typedef int32_t Weight;
191
217static constexpr TId TID_ISR_N = static_cast<TId>(0xFFFFF000U);
218
222static constexpr TId TID_NONE = static_cast<TId>(0U);
223
228static constexpr Timeout WAIT_INFINITE = INT32_MAX;
229
234static constexpr Timeout NO_WAIT = 0;
235
239static constexpr Weight NO_WEIGHT = -1;
240
244static constexpr Weight DEFAULT_WEIGHT = 1;
245
250static constexpr Timeout NO_TIME_SLICE = 0;
251
263static constexpr bool IsIsrTid(TId id) { return ((id & TID_ISR_N) == TID_ISR_N); }
264
276template <typename T> class ArrayView
277{
278public:
279 typedef T value_type;
280
283 ArrayView() : m_ptr(nullptr), m_size(0U)
284 {}
285
290 ArrayView(T *ptr, size_t size) : m_ptr(ptr), m_size(size)
291 {}
292
298 T &operator[](size_t index) const
299 {
300 STK_ASSERT(index < m_size); // enforces MISRA Rule 5-0-16
301 return UncheckedAt(index); // MISRA Rule 5-0-15 deviation centralized
302 }
303
307 T *GetPtr() { return m_ptr; }
308
312 const T *GetPtr() const { return m_ptr; }
313
317 size_t GetSize() const { return m_size; }
318
319private:
325 __stk_forceinline T &UncheckedAt(size_t index) const
326 {
327 return m_ptr[index]; // deviation: indexing non-array pointer
328 }
329
330 T *m_ptr;
331 size_t m_size;
332};
333
345
350#if STK_MPU
351struct MpuRegion
352{
353 Word addr;
354 Word attr;
355};
356#endif
357
362#if STK_MPU && STK_MPU_STACK_GUARD
363template <uint8_t REGIONS_COUNT>
364struct TaskMpuT
365{
373 static constexpr uint8_t NUM_REGIONS = REGIONS_COUNT;
374
375 MpuRegion region[NUM_REGIONS];
376};
378typedef TaskMpuT<STK_MPU_TASK_REGIONS> TaskMpu;
380typedef TaskMpuT<STK_MPU_TASK_REGIONS_NS> TaskMpuNs;
381#endif // STK_MPU && STK_MPU_STACK_GUARD
382
387#if STK_MPU
388typedef ArrayView<const struct MpuRegionConfig> MpuRegionList;
389#endif
390
397#if STK_MPU
398struct MpuConfig
399{
403 static constexpr uint32_t MPU_OFF = 0U;
404
407 MpuConfig() : regions(), mode(MPU_OFF)
408 {}
409
414 MpuConfig(const MpuRegionList &regions_, uint32_t mode_) : regions(regions_), mode(mode_)
415 {}
416
417 MpuRegionList regions;
418 uint32_t mode;
419};
420#endif
421
426struct Stack
427{
429 uint32_t access_mode;
430#if STK_MPU && STK_MPU_STACK_GUARD
431 TaskMpu mpu;
432 #ifdef _STK_CORTEX_M_TRUSTZONE
433 TaskMpuNs mpu_ns;
434 #endif
435#endif
436#if STK_TLS && !STK_TLS_PREFER_REGISTER
437 Word tls;
438#endif
439#if STK_STACK_NEEDS_TASK_ID
441#endif
442};
443
448{
449public:
452 virtual const Word *GetStack() const = 0;
453
456 virtual size_t GetStackSize() const = 0;
457
465 virtual size_t GetStackSpace() const
466 {
468 const size_t total_size = stack.GetSize();
469 size_t space = 0U;
470
471 for (size_t i = 0U; i < total_size; ++i)
472 {
473 if (stack[i] == STK_STACK_MEMORY_FILLER)
474 {
475 space = i + 1U;
476 }
477 else
478 {
479 break; // terminate loop as soon as watermark ends
480 }
481 }
482
483 return space;
484 }
485
486protected:
490 ~IStackMemory() = default;
491};
492
496class IWaitObject : public util::DListEntry<IWaitObject, false>
497{
498public:
503
508
520
524 virtual TId GetTid() const = 0;
525
532 virtual void Wake(bool timeout) = 0;
533
538 virtual EState GetState() const = 0;
539
545 virtual bool Tick(Timeout elapsed_ticks) = 0;
546
547protected:
551 ~IWaitObject() = default;
552};
553
559{
560public:
561#if STK_SYNC_DEBUG_NAMES
562 ITraceable() : m_trace_name(nullptr)
563 {}
564#endif
565
570 void SetTraceName(const char *name)
571 {
572 #if STK_SYNC_DEBUG_NAMES
573 m_trace_name = name;
574 #else
575 STK_UNUSED(name);
576 #endif
577 }
578
582 const char *GetTraceName() const
583 {
584 #if STK_SYNC_DEBUG_NAMES
585 return m_trace_name;
586 #else
587 return nullptr;
588 #endif
589 }
590
591protected:
595 ~ITraceable() = default;
596
597#if STK_SYNC_DEBUG_NAMES
598 const char *m_trace_name;
599#endif
600};
601
611class ISyncObject : public util::DListEntry<ISyncObject, false>
612{
613 friend class IKernelService;
615
616public:
621
626
631 static inline void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
632 {
633 STK_ASSERT(wobj->GetHead() == nullptr);
634 wlist.LinkBack(wobj);
635 }
636
641 virtual void AddWaitObject(IWaitObject *wobj) = 0;
642
648 {
649 STK_ASSERT(wobj->GetHead() == &wlist);
650 wlist.Unlink(wobj);
651 }
652
657 virtual void RemoveWaitObject(IWaitObject *wobj) = 0;
658
671 virtual bool Tick(Timeout elapsed_ticks);
672
679
686 static inline void WakeOne(IWaitObject::ListHeadType &wlist)
687 {
689 if (obj != nullptr)
690 {
691 obj->Wake(false);
692 }
693 }
694
701 static inline void WakeAll(IWaitObject::ListHeadType &wlist)
702 {
704 obj != nullptr;
706 {
707 obj->Wake(false);
708 }
709 }
710
716 virtual const IWaitObject::ListHeadType &GetWaitList() const = 0;
717
727 {
729 GetWaitList().GetFirst());
730
731 return ((obj != nullptr) ? obj->GetTid() : TID_NONE);
732 }
733
734protected:
738 ~ISyncObject() = default;
739
746 virtual void WakeOne() = 0;
747
754 virtual void WakeAll() = 0;
755
759};
760
766{
767public:
774 {
775 public:
776 explicit ScopedLock(IMutex &mutex) : m_mutex(mutex) { m_mutex.Lock(); }
777 ~ScopedLock() { m_mutex.Unlock(); }
778
779 private:
781
783 };
784
787 virtual void Lock() = 0;
788
791 virtual void Unlock() = 0;
792
793protected:
797 ~IMutex() = default;
798};
799
823class ITask : public IStackMemory
824{
825public:
840 virtual void Run() = 0;
841
846#if STK_TZ_SECURE
847 virtual IStackMemory *GetSecureStackMemory() { return nullptr; }
848#endif
849
893#if STK_MPU
894 virtual const MpuRegionList *GetMpuRegions() const
895 {
896 return nullptr;
897 }
898#endif
899
902 virtual EAccessMode GetAccessMode() const = 0;
903
911 virtual void OnDeadlineMissed(uint32_t duration) { STK_UNUSED(duration); }
912
921 virtual void OnExit() {}
922
928 virtual Weight GetWeight() const { return DEFAULT_WEIGHT; }
929
937 virtual Timeout GetTimeSlice() const { return NO_TIME_SLICE; }
938
944 virtual const char *GetTraceName() const { return nullptr; }
945
946protected:
950 ~ITask() = default;
951};
952
962class IKernelTask : public util::DListEntry<IKernelTask, true>
963{
964public:
969
974
977 virtual ITask *GetUserTask() = 0;
978
982 virtual Stack GetUserStack() const = 0;
983
989 virtual Weight GetWeight() const = 0;
990
997 virtual Weight GetBaseWeight() const = 0;
998
1004 virtual void SetCurrentWeight(Weight weight) = 0;
1005
1011 virtual Weight GetCurrentWeight() const = 0;
1012
1016 virtual Timeout GetHrtPeriodicity() const = 0;
1017
1021 virtual Timeout GetHrtDeadline() const = 0;
1022
1030 virtual Timeout GetHrtRelativeDeadline() const = 0;
1031
1035 virtual bool IsSleeping() const = 0;
1036
1042 virtual void Wake() = 0;
1043
1044protected:
1048 ~IKernelTask() = default;
1049};
1050
1064{
1065public:
1072 {
1073 public:
1078 virtual void OnStart(Stack *&enable) = 0;
1079
1084 virtual void OnStop() = 0;
1085
1101 virtual bool OnTick(Stack *&idle, Stack *&active
1102 #if STK_TICKLESS_IDLE
1103 , Timeout &ticks
1104 #endif
1105 ) = 0;
1106
1110 virtual void OnTaskSwitch(Word caller_SP) = 0;
1111
1116 virtual void OnTaskSleep(Word caller_SP, Timeout ticks) = 0;
1117
1123 virtual bool OnTaskSleepUntil(Word caller_SP, Ticks timestamp) = 0;
1124
1128 virtual void OnTaskExit(Stack *stack) = 0;
1129
1136 virtual EWaitResult OnTaskWait(Word caller_SP, ISyncObject *sync_obj, IMutex *mutex, Timeout timeout) = 0;
1137
1142 virtual TId OnGetTid(Word caller_SP) = 0;
1143
1147 virtual void OnSuspend(bool suspended) = 0;
1148
1155 virtual bool OnForceContextSwitch(TId id, Stack *&idle, Stack *&active) = 0;
1156 };
1157
1163 {
1164 public:
1168 virtual bool OnSleep(Timeout sleep_ticks)
1169 {
1170 STK_UNUSED(sleep_ticks);
1171 return false;
1172 }
1173
1178 virtual bool OnHardFault()
1179 {
1180 return false;
1181 }
1182
1194 #if STK_MPU
1195 virtual const MpuConfig *OnConfigureMpu() const
1196 {
1197 return nullptr;
1198 }
1199 #endif
1200
1210 virtual bool OnException(EHwException exc_id, TId tid, const struct FaultContext *const ctx)
1211 {
1212 STK_UNUSED(exc_id);
1213 STK_UNUSED(tid);
1214 STK_UNUSED(ctx);
1215 return false;
1216 }
1217 };
1218
1226 virtual void Initialize(IEventHandler *event_handler, IKernelService *service, uint32_t resolution_us, Stack *exit_trap) = 0;
1227
1232 virtual void Start() = 0;
1233
1236 virtual void Stop() = 0;
1237
1244 virtual void InitStack(EStackType stack_type, Stack *stack, IStackMemory *stack_memory, ITask *user_task) = 0;
1245
1250 virtual uint32_t GetTickResolution() const = 0;
1251
1256 virtual Cycles GetSysTimerCount() const = 0;
1257
1262 virtual uint32_t GetSysTimerFrequency() const = 0;
1263
1266 virtual void SwitchToNext() = 0;
1267
1270 virtual void ForceContextSwitch(TId id) = 0;
1271
1276 virtual void Sleep(Timeout ticks) = 0;
1277
1285 virtual bool SleepUntil(Ticks timestamp) = 0;
1286
1297 virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout) = 0;
1298
1308 virtual void ProcessTick() = 0;
1309
1313 virtual void ProcessHardFault() = 0;
1314
1320 virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure = false) = 0;
1321
1326 virtual Word GetCallerSP() const = 0;
1327
1333 virtual TId GetTid() const = 0;
1334
1341 virtual Timeout Suspend() = 0;
1342
1348 virtual void Resume(Timeout elapsed_ticks) = 0;
1349
1357 virtual void SetCpuFrequency(uint8_t core_id, uint32_t frequency) = 0;
1358
1359protected:
1363 ~IPlatform() = default;
1364};
1365
1392{
1393public:
1398 virtual void AddTask(IKernelTask *task) = 0;
1399
1404 virtual void RemoveTask(IKernelTask *task) = 0;
1405
1409 virtual IKernelTask *GetFirst() = 0;
1410
1417 virtual IKernelTask *GetNext() = 0;
1418
1422 virtual size_t GetSize() const = 0;
1423
1428 virtual void OnTaskSleep(IKernelTask *task) = 0;
1429
1434 virtual void OnTaskWake(IKernelTask *task) = 0;
1435
1446 virtual bool OnTaskYield(IKernelTask *task)
1447 {
1448 STK_UNUSED(task);
1449 return false;
1450 }
1451
1461 virtual bool OnTaskTimeSlice(IKernelTask *task)
1462 {
1463 STK_UNUSED(task);
1464 return false;
1465 }
1466
1488 {
1489 STK_UNUSED(task);
1490 return false;
1491 }
1492
1505 virtual void OnTaskWeightChange(IKernelTask *task, Weight old_weight)
1506 {
1507 STK_UNUSED(task);
1508 STK_UNUSED(old_weight);
1509 }
1510
1511protected:
1516};
1517
1524{
1525public:
1536
1547 virtual void Initialize(uint32_t resolution_us = PERIODICITY_DEFAULT) = 0;
1548
1554 virtual void AddTask(ITask *user_task) = 0;
1555
1563 virtual void AddTask(ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc) = 0;
1564
1575 virtual void RemoveTask(ITask *user_task) = 0;
1576
1584 virtual void ScheduleTaskRemoval(ITask *user_task) = 0;
1585
1592 virtual void SuspendTask(ITask *user_task, bool &suspended) = 0;
1593
1600 virtual void ResumeTask(ITask *user_task) = 0;
1601
1620 virtual void CancelTaskWait(ITask *user_task) = 0;
1621
1637 virtual bool GetTaskState(ITask *user_task, TaskStateInfo &info) const = 0;
1638
1645
1651 virtual size_t EnumerateTasks(ArrayView<ITask *> user_tasks) = 0;
1652
1673 template <size_t TMaxCount, typename TCallback>
1674 size_t EnumerateTasksT(TCallback &&callback)
1675 {
1676 STK_STATIC_ASSERT(TMaxCount > 0U);
1677
1678 ITask *tasks[TMaxCount] = {};
1679 size_t count = EnumerateTasks(ArrayView<ITask *>(tasks, TMaxCount));
1680 size_t i = 0U;
1681 bool fetch_next = true;
1682
1683 while ((i < count) && fetch_next)
1684 {
1685 fetch_next = callback(tasks[i]);
1686 ++i;
1687 }
1688
1689 return i;
1690 }
1691
1696 virtual void Start() = 0;
1697
1702 virtual EKernelState GetState() const = 0;
1703
1707 virtual IPlatform *GetPlatform() = 0;
1708
1713
1714protected:
1718 ~IKernel() = default;
1719};
1720
1730{
1731public:
1735
1741 virtual TId GetTid() const = 0;
1742
1747 virtual Ticks GetTicks() const = 0;
1748
1754 virtual uint32_t GetTickResolution() const = 0;
1755
1760 virtual Cycles GetSysTimerCount() const = 0;
1761
1766 virtual uint32_t GetSysTimerFrequency() const = 0;
1767
1775 virtual void Delay(Timeout ticks) = 0;
1776
1783 virtual void Sleep(Timeout ticks) = 0;
1784
1792 virtual bool SleepUntil(Ticks timestamp) = 0;
1793
1805 virtual void SleepCancel(TId task_id) = 0;
1806
1811 virtual void SwitchToNext() = 0;
1812
1826 virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout) = 0;
1827
1835 virtual void Wake(ISyncObject *sobj, bool all) = 0;
1836
1847 virtual Timeout Suspend() = 0;
1848
1860 virtual void Resume(Timeout elapsed_ticks) = 0;
1861
1867 virtual void InheritWeight(TId tid, Weight weight) = 0;
1868
1875 virtual void RestoreWeight(TId tid, ISyncObject *sobj = nullptr) = 0;
1876
1889 virtual Weight SetWeight(TId tid, Weight weight) = 0;
1890
1899 virtual Timeout SetTimeSlice(TId tid, Timeout ticks) = 0;
1900
1901protected:
1905 ~IKernelService() = default;
1906
1913};
1914
1915} // namespace stk
1916
1917#endif /* STK_COMMON_H_ */
Compiler and platform low-level definitions for STK.
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
#define __stk_forceinline
Forces compiler to always inline the decorated function, regardless of optimisation level.
Definition stk_defs.h:277
#define STK_NONCOPYABLE_CLASS(TYPE)
Disables copy construction and assignment for a class.
Definition stk_defs.h:708
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:516
#define STK_STACK_SIZE_MIN
Minimum stack size in elements of Word, shared by all stack allocation lower-bound checks.
Definition stk_defs.h:640
#define STK_STACK_MEMORY_FILLER
Sentinel value written to the entire stack region at initialization (stack watermark pattern).
Definition stk_defs.h:563
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:553
Intrusive doubly-linked list implementation used internally by the kernel.
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:160
static constexpr TId TID_ISR_N
Bitmask sentinel for ISR-context task identifiers.
Definition stk_common.h:217
EAccessMode
Hardware access modes by the task.
Definition stk_common.h:36
@ ACCESS_USER
Unprivileged access mode (access to some hardware is restricted, see CPU manual for details)....
Definition stk_common.h:37
@ ACCESS_PRIVILEGED
Privileged access mode (access to hardware is fully unrestricted).
Definition stk_common.h:38
@ ACCESS_SECURE
Secure access mode (ARM TrustZone, Secure binary).
Definition stk_common.h:39
static constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
Definition stk_common.h:234
EWaitResult
Wait result (see IKernelService::Wait).
Definition stk_common.h:137
@ WAIT_RESULT_FAIL
IKernelService::Wait returned with error without waiting.
Definition stk_common.h:138
@ WAIT_RESULT_CANCELED
The wait was cancelled by another task via IKernel::CancelTaskWait(), independent of signal/timeout.
Definition stk_common.h:141
@ WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_common.h:140
@ WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_common.h:139
EConsts
Constants.
Definition stk_common.h:105
@ PERIODICITY_DEFAULT
Default periodicity (microseconds), 1 millisecond.
Definition stk_common.h:107
@ STACK_SIZE_MIN
Minimum stack size in elements of Word. Used as a lower bound for all stack allocations (user task,...
Definition stk_common.h:108
@ PERIODICITY_MAX
Maximum periodicity (microseconds), 99 milliseconds (note: this value is the highest working on a rea...
Definition stk_common.h:106
int64_t Ticks
Ticks value.
Definition stk_common.h:175
EKernelPanicId
Identifies the source of a kernel panic.
Definition stk_common.h:60
@ KERNEL_PANIC_UNKNOWN_SVC
Unknown service command received by SVC handler.
Definition stk_common.h:68
@ KERNEL_PANIC_BAD_STACK_TYPE
Stack type is unknown.
Definition stk_common.h:71
@ KERNEL_PANIC_NS_ACCESS
Non-secure access to protected resource.
Definition stk_common.h:72
@ KERNEL_PANIC_BAD_MODE
Kernel is in bad/unsupported mode for the current operation.
Definition stk_common.h:70
@ KERNEL_PANIC_HRT_HARD_FAULT
Kernel running in KERNEL_HRT mode reported deadline failure of the task.
Definition stk_common.h:65
@ KERNEL_PANIC_CS_NESTING_OVERFLOW
Critical section nesting limit exceeded: violation of STK_CS_NESTINGS_MAX.
Definition stk_common.h:67
@ KERNEL_PANIC_NONE
Panic is absent (no fault).
Definition stk_common.h:61
@ KERNEL_PANIC_BAD_MEMORY_REGION
Bad memory region (ARM TrustZone: provided memory region overlaps with another one).
Definition stk_common.h:73
@ KERNEL_PANIC_CPU_EXCEPTION
CPU reported an exception and halted execution.
Definition stk_common.h:66
@ KERNEL_PANIC_SYNC_DEADLOCK
Deadlock caused by a synchronization primitive: a task tried to acquire a non-recursive primitive (e....
Definition stk_common.h:74
@ KERNEL_PANIC_STACK_CORRUPT
Stack integrity check failed.
Definition stk_common.h:63
@ KERNEL_PANIC_SPINLOCK_DEADLOCK
Spin-lock timeout expired: lock owner never released.
Definition stk_common.h:62
@ KERNEL_PANIC_BAD_STATE
Kernel entered unexpected (bad) state.
Definition stk_common.h:69
@ KERNEL_PANIC_ASSERT
Internal assertion failed (maps from STK_ASSERT).
Definition stk_common.h:64
ETaskState
Kernel-side state of a task, see IKernel::GetTaskState().
Definition stk_common.h:81
@ TASK_STATE_EXITING
Run() has returned, the slot is released on the next tick (KERNEL_DYNAMIC mode only).
Definition stk_common.h:87
@ TASK_STATE_SLEEPING
Sleeping via Sleep()/SleepUntil(), with a finite or an infinite timeout.
Definition stk_common.h:84
@ TASK_STATE_SUSPENDED
Suspended by IKernel::SuspendTask().
Definition stk_common.h:86
@ TASK_STATE_REMOVED
The task is not bound to a kernel slot (never added, or already removed).
Definition stk_common.h:82
@ TASK_STATE_WAITING
Blocked on a synchronization object (IKernelService::Wait). KERNEL_SYNC mode only.
Definition stk_common.h:85
@ TASK_STATE_READY
Runnable: running, or waiting for the CPU.
Definition stk_common.h:83
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:170
int64_t Time
Time value.
Definition stk_common.h:180
ESystemTaskId
System task id.
Definition stk_common.h:115
@ SYS_TASK_ID_EXIT
Exit trap.
Definition stk_common.h:117
@ SYS_TASK_ID_SLEEP
Sleep trap.
Definition stk_common.h:116
static constexpr Weight DEFAULT_WEIGHT
Weight value: default weight of value (1) (see SwitchStrategySmoothWeightedRoundRobin).
Definition stk_common.h:244
static constexpr bool IsIsrTid(TId id)
Test whether a task identifier represents an ISR context.
Definition stk_common.h:263
static constexpr Timeout NO_TIME_SLICE
Time-slice quantum value: no time-slicing for the task (it runs until it blocks, yields or is preempt...
Definition stk_common.h:250
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:239
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:228
static constexpr TId TID_NONE
Reserved task/thread id representing zero/none thread id.
Definition stk_common.h:222
ETraceEventId
Trace event identifiers for tracing task suspension and resume with debugging tools (e....
Definition stk_common.h:125
@ TRACE_EVENT_UNKNOWN
Unknown / uninitialized trace event.
Definition stk_common.h:126
@ TRACE_EVENT_SLEEP
Task entered a sleep state.
Definition stk_common.h:128
@ TRACE_EVENT_SUSPEND
Task suspended via Suspend.
Definition stk_common.h:130
@ TRACE_EVENT_SWITCH
Task blocked by the context switch.
Definition stk_common.h:127
@ TRACE_EVENT_WAIT
Task suspended on a sync object.
Definition stk_common.h:129
EStackType
Stack type.
Definition stk_common.h:95
@ STACK_SLEEP_TRAP
Stack of the Sleep trap.
Definition stk_common.h:97
@ STACK_USER_TASK
Stack of the user task.
Definition stk_common.h:96
@ STACK_EXIT_TRAP
Stack of the Exit trap.
Definition stk_common.h:98
uint64_t Cycles
Cycles value.
Definition stk_common.h:185
EHwException
Hardware exception id (see IPlatform::IEventOverrider::OnException).
Definition stk_common.h:148
@ HW_EXCEPT_MEMACCESS
MemManage on ARM / Page Fault or PMP violation on RISC-V.
Definition stk_common.h:150
@ HW_EXCEPT_FATAL
HardFault on ARM / Unhandled Fatal Trap on RISC-V.
Definition stk_common.h:149
Word TId
Task (thread) id.
Definition stk_common.h:165
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:190
EKernelMode
Kernel operating mode.
Definition stk_common.h:46
@ KERNEL_TELEMETRY
Enable introspection functions for diagnostics / telemetry (see IKernel::GetTaskState).
Definition stk_common.h:53
@ KERNEL_TIMESLICE
Time-slicing: running task is rotated behind its same-priority peers when its quantum (see ITask::Get...
Definition stk_common.h:52
@ KERNEL_TICKLESS
Tickless mode. To use this mode STK_TICKLESS_IDLE must be defined to 1 in stk_config....
Definition stk_common.h:51
@ KERNEL_SYNC
Synchronization support (see Event).
Definition stk_common.h:50
@ KERNEL_HRT
Hard Real-Time (HRT) behavior (tasks are scheduled periodically and have an execution deadline,...
Definition stk_common.h:49
@ KERNEL_STATIC
All tasks are static and can not exit.
Definition stk_common.h:47
@ KERNEL_DYNAMIC
Tasks can be added or removed and therefore exit when done.
Definition stk_common.h:48
Internal utility namespace containing data structure helpers (linked lists, etc.) used by the kernel ...
ARMv7-M/ARMv8-M system fault exception context state capture.
Lightweight, non-owning view over a contiguous sequence of elements.
Definition stk_common.h:277
ArrayView()
Construct an empty ArrayView with a null pointer and zero size.
Definition stk_common.h:283
T & UncheckedAt(size_t index) const
Deviation MISRA-CPP-2008-5-0-15 \reason Array indexing on a base pointer is required for a dynamic-si...
Definition stk_common.h:325
T * GetPtr()
Get pointer to the beginning of elements in the view.
Definition stk_common.h:307
ArrayView(T *ptr, size_t size)
Construct an ArrayView from a raw pointer and size.
Definition stk_common.h:290
size_t GetSize() const
Get number of elements in the view.
Definition stk_common.h:317
const T * GetPtr() const
Get constant pointer to the beginning of elements in the view.
Definition stk_common.h:312
T & operator[](size_t index) const
Subscript operator for element access.
Definition stk_common.h:298
T * m_ptr
Pointer to the underlying memory block.
Definition stk_common.h:330
size_t m_size
Total number of elements in the view.
Definition stk_common.h:331
Snapshot of the kernel-side state of a task, filled in by IKernel::GetTaskState().
Definition stk_common.h:338
ETaskState state
Task state.
Definition stk_common.h:339
ISyncObject * wait_obj
Definition stk_common.h:340
Stack descriptor.
Definition stk_common.h:427
uint32_t access_mode
Bitfield with hardware access mode of the task (see EAccessMode).
Definition stk_common.h:429
TId tid
Task id (see STK_SEGGER_SYSVIEW, STK_MPU_STACK_GUARD).
Definition stk_common.h:440
Word SP
Offset 0: Stack Pointer (SP) register (note: must always be at offset 0).
Definition stk_common.h:428
Interface for a stack memory region.
Definition stk_common.h:448
~IStackMemory()=default
Destructor.
virtual size_t GetStackSize() const =0
Get number of elements of the stack memory array.
virtual size_t GetStackSpace() const
Get available stack space.
Definition stk_common.h:465
virtual const Word * GetStack() const =0
Get pointer to the stack memory.
Wait object.
Definition stk_common.h:497
EState
State of the WaitObject.
Definition stk_common.h:513
@ STATE_CANCELLED
Wait was cancelled via Cancel() rather than Wake()/timeout.
Definition stk_common.h:518
@ STATE_TIMEOUT
Wait expired due to timeout rather than a Wake() signal.
Definition stk_common.h:517
@ STATE_SIGNALED
Wake signaled.
Definition stk_common.h:516
@ STATE_WAIT
Wait is active.
Definition stk_common.h:515
DLEntryType ListEntryType
List entry type of IWaitObject elements.
Definition stk_common.h:507
DLHeadType ListHeadType
List head type for IWaitObject elements.
Definition stk_common.h:502
virtual TId GetTid() const =0
Get thread Id of the task owning .
virtual void Wake(bool timeout)=0
Wake task.
~IWaitObject()=default
Destructor.
virtual EState GetState() const =0
Get current state.
virtual bool Tick(Timeout elapsed_ticks)=0
Update wait object's waiting time.
Traceable object.
Definition stk_common.h:559
const char * GetTraceName() const
Get name.
Definition stk_common.h:582
void SetTraceName(const char *name)
Set name.
Definition stk_common.h:570
~ITraceable()=default
Destructor.
Synchronization object interface.
Definition stk_common.h:612
virtual void WakeAll()=0
Wake all tasks currently in the wait list.
virtual bool Tick(Timeout elapsed_ticks)
Called by kernel on every system tick to handle timeout logic of waiting tasks.
Definition stk_helper.h:316
DLEntryType ListEntryType
List entry type of ISyncObject elements.
Definition stk_common.h:625
~ISyncObject()=default
Destructor.
virtual void WakeOne()=0
Wake the first task in the wait list (FIFO order).
TId GetFirstWaiterTid() const
Get id of the task which is first in the wait list (FIFO order), i.e. the one that WakeOne() would wa...
Definition stk_common.h:726
friend class tz::nsec::util::CmseISyncObjectWrapper
Definition stk_common.h:614
DLHeadType ListHeadType
List head type for ISyncObject elements.
Definition stk_common.h:620
static void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
Called by kernel when a new task starts waiting on this event.
Definition stk_common.h:631
virtual IWaitObject::ListHeadType & GetMutableWaitList()=0
Get list of tasks blocked on this object.
friend class IKernelService
Definition stk_common.h:613
static void WakeAll(IWaitObject::ListHeadType &wlist)
Wake all tasks currently in the wait list.
Definition stk_common.h:701
static void RemoveWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
Called by kernel when a waiting task is being removed (timeout expired, wait aborted,...
Definition stk_common.h:647
virtual const IWaitObject::ListHeadType & GetWaitList() const =0
Get list of tasks blocked on this object.
Weight FindWeightHigherThan(Weight comp) const
Find higher weight within linked wait objects.
Definition stk_helper.h:351
virtual void RemoveWaitObject(IWaitObject *wobj)=0
Called by kernel when a waiting task is being removed (timeout expired, wait aborted,...
virtual void AddWaitObject(IWaitObject *wobj)=0
Called by kernel when a new task starts waiting on this event.
static void WakeOne(IWaitObject::ListHeadType &wlist)
Wake the first task in the wait list (FIFO order).
Definition stk_common.h:686
Interface for mutex synchronization primitive.
Definition stk_common.h:766
~IMutex()=default
Destructor.
virtual void Unlock()=0
Unlock the mutex.
virtual void Lock()=0
Lock the mutex.
ScopedLock(IMutex &mutex)
Definition stk_common.h:776
Interface for a user task.
Definition stk_common.h:824
virtual Weight GetWeight() const
Get static base weight of the task.
Definition stk_common.h:928
virtual EAccessMode GetAccessMode() const =0
Get pointer to the stack memory.
virtual const char * GetTraceName() const
Get task trace name set by application.
Definition stk_common.h:944
virtual void Run()=0
Entry point of the user task.
virtual void OnExit()
Called by the kernel before removal from the scheduling (see stk::KERNEL_DYNAMIC).
Definition stk_common.h:921
virtual Timeout GetTimeSlice() const
Get time-slice quantum of the task (ticks). KERNEL_TIMESLICE only.
Definition stk_common.h:937
~ITask()=default
Destructor.
virtual void OnDeadlineMissed(uint32_t duration)
Called by the scheduler if deadline of the task is missed when Kernel is operating in Hard Real-Time ...
Definition stk_common.h:911
Scheduling-strategy-facing interface for a kernel task slot.
Definition stk_common.h:963
virtual void Wake()=0
Wake a sleeping task on the next scheduling tick.
DLEntryType ListEntryType
List entry type of IKernelTask elements.
Definition stk_common.h:973
virtual Weight GetCurrentWeight() const =0
Get the current dynamic weight value of this task.
virtual Weight GetWeight() const =0
Get static base weight assigned to the task.
virtual Timeout GetHrtRelativeDeadline() const =0
Get HRT task's relative deadline.
virtual Weight GetBaseWeight() const =0
Get the base (configured) weight of the task, ignoring any priority-inheritance boost.
virtual Timeout GetHrtDeadline() const =0
Get HRT task deadline (max allowed task execution time).
DLHeadType ListHeadType
List head type for IKernelTask elements.
Definition stk_common.h:968
virtual bool IsSleeping() const =0
Check whether the task is currently sleeping.
virtual Timeout GetHrtPeriodicity() const =0
Get HRT task execution periodicity.
virtual ITask * GetUserTask()=0
Get user task.
virtual void SetCurrentWeight(Weight weight)=0
Set the current dynamic weight value used by the scheduling strategy.
virtual Stack GetUserStack() const =0
Get user task's Stack info.
~IKernelTask()=default
Destructor.
Interface for a platform driver.
virtual void ProcessTick()=0
Process one tick.
virtual Word GetCallerSP() const =0
Get caller's Stack Pointer (SP).
virtual TId GetTid() const =0
Get thread Id.
~IPlatform()=default
Destructor.
virtual void Initialize(IEventHandler *event_handler, IKernelService *service, uint32_t resolution_us, Stack *exit_trap)=0
Initialize scheduler's context.
virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout)=0
Put calling process into a waiting state until synchronization object is signaled or timeout occurs.
virtual Timeout Suspend()=0
Suspend scheduling.
virtual Cycles GetSysTimerCount() const =0
Get system timer count value.
virtual void Start()=0
Start scheduling.
virtual void Stop()=0
Stop scheduling.
virtual uint32_t GetSysTimerFrequency() const =0
Get system timer frequency.
virtual void Resume(Timeout elapsed_ticks)=0
Resume scheduling after a prior Suspend() call.
virtual void SwitchToNext()=0
Switch to a next task.
virtual void ForceContextSwitch(TId id)=0
Force context switch.
virtual void Sleep(Timeout ticks)=0
Put calling process into a sleep state.
virtual uint32_t GetTickResolution() const =0
Get resolution of the system tick timer in microseconds. Resolution means a number of microseconds be...
virtual void InitStack(EStackType stack_type, Stack *stack, IStackMemory *stack_memory, ITask *user_task)=0
Initialize stack memory of the user task.
virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure=false)=0
Set platform event overrider.
virtual void ProcessHardFault()=0
Cause a hard fault of the system.
virtual void SetCpuFrequency(uint8_t core_id, uint32_t frequency)=0
Notify the scheduler of a CPU core's operating frequency.
virtual bool SleepUntil(Ticks timestamp)=0
Put calling process into a sleep state until the specified timestamp.
Interface for a back-end event handler.
virtual void OnTaskExit(Stack *stack)=0
Called from the Thread process when task finished (its Run function exited by return).
virtual bool OnTick(Stack *&idle, Stack *&active, Timeout &ticks)=0
Called by ISR handler to notify about the next system tick.
virtual void OnStart(Stack *&enable)=0
Called by ISR handler to notify that scheduling is about to start.
virtual EWaitResult OnTaskWait(Word caller_SP, ISyncObject *sync_obj, IMutex *mutex, Timeout timeout)=0
Called from the Thread process when task needs to wait.
virtual bool OnForceContextSwitch(TId id, Stack *&idle, Stack *&active)=0
Called when task state change forces a context switch (Sleep, SleepUntil, Wait).
virtual TId OnGetTid(Word caller_SP)=0
Called from the Thread process when for getting task/thread id of the process.
virtual void OnStop()=0
Called by driver to notify that scheduling is stopped.
virtual void OnTaskSleep(Word caller_SP, Timeout ticks)=0
Called by Thread process (via IKernelService::Sleep) for exclusion of the calling process from schedu...
virtual void OnSuspend(bool suspended)=0
Called from the Thread process to suspend scheduling.
virtual void OnTaskSwitch(Word caller_SP)=0
Called by Thread process (via IKernelService::SwitchToNext) to switch to a next task.
virtual bool OnTaskSleepUntil(Word caller_SP, Ticks timestamp)=0
Called by Thread process (via IKernelService::SleepUntil) for exclusion of the calling process from s...
Interface for a platform event overrider.
virtual bool OnSleep(Timeout sleep_ticks)
Called by the Kernel when it is entering a sleep mode.
virtual bool OnHardFault()
Called by Kernel when hard fault happens.
virtual bool OnException(EHwException exc_id, TId tid, const struct FaultContext *const ctx)
Called by the platform driver during initialization to obtain global, application-defined MPU configu...
Interface for a task switching strategy implementation.
virtual void RemoveTask(IKernelTask *task)=0
Remove task.
virtual void OnTaskSleep(IKernelTask *task)=0
Notification that a task has entered sleep/blocked state.
virtual void OnTaskWake(IKernelTask *task)=0
Notification that a task is becoming runnable again.
~ITaskSwitchStrategy()=default
Destructor.
virtual bool OnTaskTimeSlice(IKernelTask *task)
Notification that the running task's time slice expired (KERNEL_TIMESLICE only).
virtual bool OnTaskDeadlineMissed(IKernelTask *task)
Notification that a task has exceeded its HRT deadline; returns whether the strategy can recover with...
virtual IKernelTask * GetFirst()=0
Get first task.
virtual void OnTaskWeightChange(IKernelTask *task, Weight old_weight)
Notification that a runnable task's scheduling weight has changed.
virtual bool OnTaskYield(IKernelTask *task)
Notification that the running task called Yield() (non-HRT kernel modes only).
virtual size_t GetSize() const =0
Get number of tasks currently managed by this strategy.
virtual IKernelTask * GetNext()=0
Advance the internal iterator and return the next runnable task.
virtual void AddTask(IKernelTask *task)=0
Add task.
Interface for the implementation of the kernel of the scheduler. It supports Soft and Hard Real-Time ...
EKernelState
Kernel state.
@ 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.
virtual void ResumeTask(ITask *user_task)=0
Resume task.
virtual void SuspendTask(ITask *user_task, bool &suspended)=0
Suspend task.
virtual IPlatform * GetPlatform()=0
Get platform driver instance.
virtual size_t EnumerateTasks(ArrayView< ITask * > user_tasks)=0
Enumerate user tasks.
virtual EKernelState GetState() const =0
Get a snapshot of the kernel state.
~IKernel()=default
Destructor.
virtual void RemoveTask(ITask *user_task)=0
Remove a previously added task from the kernel when it is not started.
virtual bool GetTaskState(ITask *user_task, TaskStateInfo &info) const =0
Get a snapshot of the kernel-side state of a task.
virtual void AddTask(ITask *user_task)=0
Add user task.
size_t EnumerateTasksT(TCallback &&callback)
Enumerate tasks, invoking a callback for each active task.
virtual size_t EnumerateKernelTasks(ArrayView< IKernelTask * > tasks)=0
Enumerate kernel tasks.
virtual void ScheduleTaskRemoval(ITask *user_task)=0
Schedule task removal from scheduling (exit).
virtual void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT)=0
Initialize kernel.
virtual ITaskSwitchStrategy * GetSwitchStrategy()=0
Get switch strategy instance.
virtual void CancelTaskWait(ITask *user_task)=0
Cancel a task's in-progress wait on a synchronization object, waking it early.
virtual void Start()=0
Start kernel scheduling.
virtual void AddTask(ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc)=0
Add user task.
Interface for the kernel services exposed to the user processes during run-time when Kernel started s...
virtual TId GetTid() const =0
Get thread Id of the currently running task.
virtual Timeout SetTimeSlice(TId tid, Timeout ticks)=0
Change the time-slice quantum of the task at run-time and reload its slice.
virtual void Wake(ISyncObject *sobj, bool all)=0
Wake one or all tasks currently waiting on a synchronization object.
virtual void SleepCancel(TId task_id)=0
Cancel sleep of the task.
virtual void InheritWeight(TId tid, Weight weight)=0
Inherit weight for the task.
static IKernelService * GetInstance()
Get CPU-local instance of the kernel service.
virtual uint32_t GetTickResolution() const =0
Get number of microseconds in one tick.
~IKernelService()=default
Destructor.
virtual bool SleepUntil(Ticks timestamp)=0
Put calling process into a sleep state until the specified timestamp.
virtual Ticks GetTicks() const =0
Get number of ticks elapsed since kernel start.
virtual void SwitchToNext()=0
Notify scheduler to switch to the next task (yield).
virtual void Resume(Timeout elapsed_ticks)=0
Resume scheduling after a prior Suspend() call.
virtual void Sleep(Timeout ticks)=0
Put calling process into a sleep state.
virtual Weight SetWeight(TId tid, Weight weight)=0
Change the base weight of the task at run-time (replaces ITask::GetWeight() value).
virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout)=0
Put calling process into a waiting state until synchronization object is signaled or timeout occurs.
virtual Cycles GetSysTimerCount() const =0
Get system timer count value.
virtual uint32_t GetSysTimerFrequency() const =0
Get system timer frequency.
virtual Timeout Suspend()=0
Suspend scheduling.
virtual void RestoreWeight(TId tid, ISyncObject *sobj=nullptr)=0
Restore weight of the task to the original value.
static IWaitObject::ListHeadType & GetMutableWaitList(ISyncObject *sobj)
Access helper to the mutable IWaitObject::GetWaitList().
virtual void Delay(Timeout ticks)=0
Delay calling process.
void LinkBack(DLEntryType *entry)
Append entry to the back of the list (pointer overload).
void Unlink(DLEntryType *entry)
Remove entry from this list.
DLEntryType * GetFirst()
Get the first (front) entry without removing it.
Intrusive doubly-linked list node. Embed this as a base class in any object (T) that needs to partici...
DListEntry< IWaitObject, TClosedLoop > DLEntryType
DLHeadType * GetHead()
Get the list head this entry currently belongs to.
DListHead< IWaitObject, TClosedLoop > DLHeadType
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Safely casts an intrusive list entry to its concrete parent container object type.
MPU region descriptor.
MPU descriptor of the task.
Aggregated hardware MPU setup configuration and state descriptor.