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 detail {
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
77
90
101
111
115enum ESystemTaskId : uint32_t
116{
117 SYS_TASK_ID_SLEEP = 0xFFFFFFFF,
118 SYS_TASK_ID_EXIT = 0xFFFFFFFE
119};
120
125enum ETraceEventId : uint32_t
126{
129 TRACE_EVENT_SLEEP = 1000 + 1,
130 TRACE_EVENT_WAIT = 1000 + 2,
132};
133
144
155
167
178
189
198
206typedef uintptr_t Word;
207
211typedef Word TId;
212
216typedef int32_t Timeout;
217
221typedef int64_t Ticks;
222
226typedef int64_t Time;
227
231typedef uint64_t Cycles;
232
236typedef int32_t Weight;
237
263static constexpr TId TID_ISR_N = static_cast<TId>(0xFFFFF000U);
264
268static constexpr TId TID_NONE = static_cast<TId>(0U);
269
274static constexpr Timeout WAIT_INFINITE = INT32_MAX;
275
280static constexpr Timeout NO_WAIT = 0;
281
285static constexpr Weight NO_WEIGHT = -1;
286
290static constexpr Weight DEFAULT_WEIGHT = 1;
291
296static constexpr Timeout NO_TIME_SLICE = 0;
297
309static constexpr bool IsIsrTid(TId id) { return ((id & TID_ISR_N) == TID_ISR_N); }
310
322template <typename T> class ArrayView
323{
324public:
325 typedef T value_type;
326
329 ArrayView() : m_ptr(nullptr), m_size(0U)
330 {}
331
336 ArrayView(T *ptr, size_t size) : m_ptr(ptr), m_size(size)
337 {}
338
344 T &operator[](size_t index) const
345 {
346 STK_ASSERT(index < m_size); // enforces MISRA Rule 5-0-16
347 return UncheckedAt(index); // MISRA Rule 5-0-15 deviation centralized
348 }
349
353 T *GetPtr() { return m_ptr; }
354
358 const T *GetPtr() const { return m_ptr; }
359
363 size_t GetSize() const { return m_size; }
364
365private:
371 __stk_forceinline T &UncheckedAt(size_t index) const
372 {
373 return m_ptr[index]; // deviation: indexing non-array pointer
374 }
375
376 T *m_ptr;
377 size_t m_size;
378};
379
391
396#if STK_MPU
397struct MpuRegion
398{
399 Word addr;
400 Word attr;
401};
402#endif
403
408#if STK_MPU && STK_MPU_STACK_GUARD
409template <uint8_t REGIONS_COUNT>
410struct TaskMpuT
411{
419 static constexpr uint8_t NUM_REGIONS = REGIONS_COUNT;
420
421 MpuRegion region[NUM_REGIONS];
422};
424typedef TaskMpuT<STK_MPU_TASK_REGIONS> TaskMpu;
426typedef TaskMpuT<STK_MPU_TASK_REGIONS_NS> TaskMpuNs;
427#endif // STK_MPU && STK_MPU_STACK_GUARD
428
433#if STK_MPU
434typedef ArrayView<const struct MpuRegionConfig> MpuRegionList;
435#endif
436
443#if STK_MPU
444struct MpuConfig
445{
449 static constexpr uint32_t MPU_OFF = 0U;
450
453 MpuConfig() : regions(), mode(MPU_OFF)
454 {}
455
460 MpuConfig(const MpuRegionList &regions_, uint32_t mode_) : regions(regions_), mode(mode_)
461 {}
462
463 MpuRegionList regions;
464 uint32_t mode;
465};
466#endif
467
472struct Stack
473{
475 uint32_t access_mode;
476#if STK_MPU && STK_MPU_STACK_GUARD
477 TaskMpu mpu;
478 #ifdef _STK_CORTEX_M_TRUSTZONE
479 TaskMpuNs mpu_ns;
480 #endif
481#endif
482#if STK_TLS && !STK_TLS_PREFER_REGISTER
483 Word tls;
484#endif
485#if STK_STACK_NEEDS_TASK_ID
487#endif
488};
489
494{
495public:
498 virtual const Word *GetStack() const = 0;
499
502 virtual size_t GetStackSize() const = 0;
503
511 virtual size_t GetStackSpace() const
512 {
514 const size_t total_size = stack.GetSize();
515 size_t space = 0U;
516
517 for (size_t i = 0U; i < total_size; ++i)
518 {
519 if (stack[i] == STK_STACK_MEMORY_FILLER)
520 {
521 space = i + 1U;
522 }
523 else
524 {
525 break; // terminate loop as soon as watermark ends
526 }
527 }
528
529 return space;
530 }
531
532protected:
536 ~IStackMemory() = default;
537};
538
542class IWaitObject : public detail::DListEntry<IWaitObject, false>
543{
544public:
549
554
566
570 virtual TId GetTid() const = 0;
571
578 virtual void Wake(bool timeout) = 0;
579
584 virtual EState GetState() const = 0;
585
592 virtual bool Tick(Timeout elapsed_ticks) = 0;
593
594protected:
598 ~IWaitObject() = default;
599};
600
606{
607public:
608#if STK_SYNC_DEBUG_NAMES
609 ITraceable() : m_trace_name(nullptr)
610 {}
611#endif
612
617 void SetTraceName(const char *name)
618 {
619 #if STK_SYNC_DEBUG_NAMES
620 m_trace_name = name;
621 #else
622 STK_UNUSED(name);
623 #endif
624 }
625
629 const char *GetTraceName() const
630 {
631 #if STK_SYNC_DEBUG_NAMES
632 return m_trace_name;
633 #else
634 return nullptr;
635 #endif
636 }
637
638protected:
642 ~ITraceable() = default;
643
644#if STK_SYNC_DEBUG_NAMES
645 const char *m_trace_name;
646#endif
647};
648
658class ISyncObject : public detail::DListEntry<ISyncObject, false>
659{
660 friend class IKernelService;
662
663public:
668
673
679 static inline void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
680 {
681 STK_ASSERT(wobj->GetHead() == nullptr);
682 wlist.LinkBack(wobj);
683 }
684
689 virtual void AddWaitObject(IWaitObject *wobj) = 0;
690
697 {
698 STK_ASSERT(wobj->GetHead() == &wlist);
699 wlist.Unlink(wobj);
700 }
701
706 virtual void RemoveWaitObject(IWaitObject *wobj) = 0;
707
720 virtual bool Tick(Timeout elapsed_ticks);
721
728
736 static inline void WakeOne(IWaitObject::ListHeadType &wlist)
737 {
739 if (obj != nullptr)
740 {
741 obj->Wake(false);
742 }
743 }
744
752 static inline void WakeAll(IWaitObject::ListHeadType &wlist)
753 {
755 obj != nullptr;
757 {
758 obj->Wake(false);
759 }
760 }
761
767 virtual const IWaitObject::ListHeadType &GetWaitList() const = 0;
768
778 {
780 GetWaitList().GetFirst());
781
782 return ((obj != nullptr) ? obj->GetTid() : TID_NONE);
783 }
784
785protected:
789 ~ISyncObject() = default;
790
797 virtual void WakeOne() = 0;
798
805 virtual void WakeAll() = 0;
806
810};
811
817{
818public:
825 {
826 public:
827 explicit ScopedLock(IMutex &mutex) : m_mutex(mutex)
828 {
829 m_mutex.Lock();
830 }
832 {
833 m_mutex.Unlock();
834 }
835
836 private:
838
840 };
841
844 virtual void Lock() = 0;
845
848 virtual void Unlock() = 0;
849
853 virtual bool TryLock() = 0;
854
855protected:
859 ~IMutex() = default;
860};
861
885class ITask : public IStackMemory
886{
887public:
902 virtual void Run() = 0;
903
908#if STK_TZ_SECURE
909 virtual IStackMemory *GetSecureStackMemory() { return nullptr; }
910#endif
911
955#if STK_MPU
956 virtual const MpuRegionList *GetMpuRegions() const
957 {
958 return nullptr;
959 }
960#endif
961
964 virtual EAccessMode GetAccessMode() const = 0;
965
973 virtual void OnDeadlineMissed(uint32_t duration) { STK_UNUSED(duration); }
974
990 virtual void OnExit() {}
991
997 virtual Weight GetWeight() const { return DEFAULT_WEIGHT; }
998
1006 virtual Timeout GetTimeSlice() const { return NO_TIME_SLICE; }
1007
1013 virtual const char *GetTraceName() const { return nullptr; }
1014
1015protected:
1019 ~ITask() = default;
1020};
1021
1031class IKernelTask : public detail::DListEntry<IKernelTask, true>
1032{
1033public:
1038
1043
1046 virtual ITask *GetUserTask() = 0;
1047
1051 virtual Stack GetUserStack() const = 0;
1052
1059 virtual Weight GetWeight() const = 0;
1060
1067 virtual Weight GetBaseWeight() const = 0;
1068
1074 virtual void SetCurrentWeight(Weight weight) = 0;
1075
1082 virtual Weight GetCurrentWeight() const = 0;
1083
1087 virtual Timeout GetHrtPeriodicity() const = 0;
1088
1092 virtual Timeout GetHrtDeadline() const = 0;
1093
1100 virtual Timeout GetHrtRelativeDeadline() const = 0;
1101
1105 virtual bool IsSleeping() const = 0;
1106
1112 virtual void Wake() = 0;
1113
1114protected:
1118 ~IKernelTask() = default;
1119};
1120
1134{
1135public:
1142 {
1143 public:
1148 virtual void OnStart(Stack *&active) = 0;
1149
1154 virtual void OnStop() = 0;
1155
1171 virtual bool OnTick(Stack *&idle, Stack *&active
1172 #if STK_TICKLESS_IDLE
1173 , Timeout &ticks
1174 #endif
1175 ) = 0;
1176
1180 virtual void OnTaskExit(const Stack *stack) = 0;
1181
1186 virtual TId OnGetTid(Word caller_SP) = 0;
1187
1191 virtual void OnSuspend(bool suspended) = 0;
1192
1199 virtual bool OnForceContextSwitch(TId id, Stack *&idle, Stack *&active) = 0;
1200 };
1201
1207 {
1208 public:
1213 virtual bool OnSleep(Timeout sleep_ticks)
1214 {
1215 STK_UNUSED(sleep_ticks);
1216 return false;
1217 }
1218
1223 virtual bool OnHardFault()
1224 {
1225 return false;
1226 }
1227
1239 #if STK_MPU
1240 virtual const MpuConfig *OnConfigureMpu() const
1241 {
1242 return nullptr;
1243 }
1244 #endif
1245
1255 virtual bool OnException(EHwException exc_id, TId tid, const struct FaultContext *const ctx)
1256 {
1257 STK_UNUSED(exc_id);
1258 STK_UNUSED(tid);
1259 STK_UNUSED(ctx);
1260 return false;
1261 }
1262 };
1263
1271 virtual void Initialize(IEventHandler *event_handler, IKernelService *service, uint32_t resolution_us, Stack *exit_trap) = 0;
1272
1277 virtual void Start() = 0;
1278
1281 virtual void Stop() = 0;
1282
1289 virtual void InitStack(EStackType stack_type, Stack *stack, IStackMemory *stack_memory, ITask *user_task) = 0;
1290
1295 virtual uint32_t GetTickResolution() const = 0;
1296
1301 virtual Cycles GetSysTimerCount() const = 0;
1302
1307 virtual uint32_t GetSysTimerFrequency() const = 0;
1308
1311 virtual void ForceContextSwitch(TId id) = 0;
1312
1322 virtual void ProcessTick() = 0;
1323
1327 virtual void ProcessHardFault() = 0;
1328
1334 virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure = false) = 0;
1335
1340 virtual Word GetCallerSP() const = 0;
1341
1347 virtual TId GetTid() const = 0;
1348
1355 virtual Timeout Suspend() = 0;
1356
1362 virtual void Resume(Timeout elapsed_ticks) = 0;
1363
1371 virtual void SetCpuFrequency(uint8_t core_id, uint32_t frequency) = 0;
1372
1373protected:
1377 ~IPlatform() = default;
1378};
1379
1406{
1407public:
1412 virtual void AddTask(IKernelTask *task) = 0;
1413
1418 virtual void RemoveTask(IKernelTask *task) = 0;
1419
1423 virtual IKernelTask *GetFirst() = 0;
1424
1431 virtual IKernelTask *GetNext() = 0;
1432
1436 virtual size_t GetSize() const = 0;
1437
1442 virtual void OnTaskSleep(IKernelTask *task) = 0;
1443
1448 virtual void OnTaskWake(IKernelTask *task) = 0;
1449
1460 virtual bool OnTaskYield(IKernelTask *task)
1461 {
1462 STK_UNUSED(task);
1463 return false;
1464 }
1465
1475 virtual bool OnTaskTimeSlice(IKernelTask *task)
1476 {
1477 STK_UNUSED(task);
1478 return false;
1479 }
1480
1502 {
1503 STK_UNUSED(task);
1504 return false;
1505 }
1506
1518 virtual void OnTaskWeightChange(IKernelTask *task, Weight old_weight)
1519 {
1520 STK_UNUSED(task);
1521 STK_UNUSED(old_weight);
1522 }
1523
1524protected:
1529};
1530
1537{
1538public:
1550
1561 virtual void Initialize(uint32_t resolution_us = PERIODICITY_DEFAULT) = 0;
1562
1596 virtual EAddResult AddTask(ITask *user_task) = 0;
1597
1619 virtual EAddResult AddTask(ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc) = 0;
1620
1630 virtual void RemoveTask(ITask *user_task) = 0;
1631
1639 virtual void ScheduleTaskRemoval(ITask *user_task) = 0;
1640
1654 virtual ESuspendResult SuspendTask(ITask *user_task) = 0;
1655
1661 void SuspendTask(ITask *user_task, bool &suspended)
1662 {
1663 suspended = (SuspendTask(user_task) == SUSPEND_DONE);
1664 }
1665
1673 virtual EResumeResult ResumeTask(ITask *user_task) = 0;
1674
1690 virtual void CancelTaskWait(ITask *user_task) = 0;
1691
1707 virtual bool GetTaskState(ITask *user_task, TaskStateInfo &info) const = 0;
1708
1715
1721 virtual size_t EnumerateTasks(ArrayView<ITask *> user_tasks) = 0;
1722
1743 template <size_t TMaxCount, typename TCallback>
1744 size_t EnumerateTasksT(TCallback &&callback)
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 }
1761
1772 virtual ELockResult SetSchedulerLock(bool lock) = 0;
1773
1779 virtual void Start() = 0;
1780
1785 virtual EKernelState GetState() const = 0;
1786
1790 virtual IPlatform *GetPlatform() = 0;
1791
1796
1797protected:
1801 ~IKernel() = default;
1802};
1803
1813{
1814public:
1818
1824 virtual TId GetTid() const = 0;
1825
1830 virtual Ticks GetTicks() const = 0;
1831
1837 virtual uint32_t GetTickResolution() const = 0;
1838
1843 virtual Cycles GetSysTimerCount() const = 0;
1844
1849 virtual uint32_t GetSysTimerFrequency() const = 0;
1850
1857 virtual void Delay(Timeout ticks) = 0;
1858
1868 virtual bool Sleep(Timeout ticks) = 0;
1869
1879 virtual bool SleepUntil(Ticks timestamp) = 0;
1880
1892 virtual void SleepCancel(TId task_id) = 0;
1893
1902 virtual void SwitchToNext() = 0;
1903
1916 virtual void ExitTask() = 0;
1917
1933 virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout) = 0;
1934
1942 virtual void Wake(ISyncObject *sobj, bool all) = 0;
1943
1954 virtual Timeout Suspend() = 0;
1955
1967 virtual void Resume(Timeout elapsed_ticks) = 0;
1968
1974 virtual void InheritWeight(TId tid, Weight weight) = 0;
1975
1982 virtual void RestoreWeight(TId tid, ISyncObject *sobj = nullptr) = 0;
1983
1996 virtual Weight SetWeight(TId tid, Weight weight) = 0;
1997
2006 virtual Timeout SetTimeSlice(TId tid, Timeout ticks) = 0;
2007
2035
2043
2052 virtual ELockResult RestoreSchedulerLock(bool locked) = 0;
2053
2067 {
2068 public:
2072 {
2073 // restore the state which was before construction: keeps an outer lock held (nesting)
2075 }
2076
2077 private:
2079
2081 };
2082
2083protected:
2087 ~IKernelService() = default;
2088
2095};
2096
2097} // namespace stk
2098
2099#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:270
#define STK_NONCOPYABLE_CLASS(TYPE)
Deletes (= delete) the copy constructor and copy assignment operator of 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:532
#define STK_STACK_SIZE_MIN
Minimum stack size in elements of Word, shared by all stack allocation lower-bound checks.
Definition stk_defs.h:646
#define STK_STACK_MEMORY_FILLER
Sentinel value written to the entire stack region at initialization (stack watermark pattern).
Definition stk_defs.h:570
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:560
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:206
static constexpr TId TID_ISR_N
Bitmask sentinel for ISR-context task identifiers.
Definition stk_common.h:263
ESuspendResult
Result of IKernel::SuspendTask().
Definition stk_common.h:172
@ SUSPEND_DONE
Task was runnable and is suspended now.
Definition stk_common.h:174
@ SUSPEND_DEFERRED
Task is sleeping/waiting: it will be suspended when the sleep/wait ends (wait result is preserved).
Definition stk_common.h:175
@ SUSPEND_ALREADY
Task is already suspended or already has a deferred suspension pending.
Definition stk_common.h:176
@ SUSPEND_FAIL
Task is not bound to the kernel, or is exiting.
Definition stk_common.h:173
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:280
EAddResult
Result of IKernel::AddTask() (both the Soft Real-Time and the Hard Real-Time overloads).
Definition stk_common.h:149
@ ADD_FAIL_POOL_FULL
No free kernel slot left (TASKS_MAX reached). In KERNEL_DYNAMIC mode retry later, once a task has exi...
Definition stk_common.h:152
@ ADD_FAIL_INVALID
Invalid call: task is nullptr, kernel is not initialized, or adding is not allowed in the current ker...
Definition stk_common.h:150
@ ADD_OK
Task was added.
Definition stk_common.h:153
@ ADD_FAIL_DUPLICATE
The task (or its stack) is already added to the kernel. Application design failure.
Definition stk_common.h:151
EWaitResult
Wait result (see IKernelService::Wait).
Definition stk_common.h:138
@ WAIT_RESULT_FAIL
IKernelService::Wait returned with error without waiting.
Definition stk_common.h:139
@ WAIT_RESULT_CANCELED
The wait was cancelled by another task via IKernel::CancelTaskWait(), independent of signal/timeout.
Definition stk_common.h:142
@ WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_common.h:141
@ WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_common.h:140
EConsts
Constants.
Definition stk_common.h:106
@ PERIODICITY_DEFAULT
Default periodicity (microseconds), 1 millisecond.
Definition stk_common.h:108
@ 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:109
@ PERIODICITY_MAX
Maximum periodicity (microseconds), 99 milliseconds (note: this value is the highest working on a rea...
Definition stk_common.h:107
int64_t Ticks
Ticks value.
Definition stk_common.h:221
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; memory pools: a p...
Definition stk_common.h:73
@ KERNEL_PANIC_CPU_EXCEPTION
CPU reported an exception and halted execution.
Definition stk_common.h:66
@ KERNEL_PANIC_NO_MEM
Out of memory: a mandatory allocation (heap or a fixed-size static pool) failed in a context that can...
Definition stk_common.h:75
@ 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:82
@ TASK_STATE_EXITING
Run() has returned, the slot is released on the next tick (KERNEL_DYNAMIC mode only).
Definition stk_common.h:88
@ TASK_STATE_SLEEPING
Sleeping via Sleep()/SleepUntil(), with a finite or an infinite timeout.
Definition stk_common.h:85
@ TASK_STATE_SUSPENDED
Suspended by IKernel::SuspendTask().
Definition stk_common.h:87
@ TASK_STATE_REMOVED
The task is not bound to a kernel slot (never added, or already removed).
Definition stk_common.h:83
@ TASK_STATE_WAITING
Blocked on a synchronization object (IKernelService::Wait). KERNEL_SYNC mode only.
Definition stk_common.h:86
@ TASK_STATE_READY
Runnable: running, or waiting for the CPU.
Definition stk_common.h:84
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:216
int64_t Time
Time value.
Definition stk_common.h:226
ELockResult
Result of IKernel::SetSchedulerLock(), IKernelService::LockScheduler(), UnlockScheduler() and Restore...
Definition stk_common.h:161
@ LOCK_WAS_UNLOCKED
LockScheduler/UnlockScheduler: previous state was unlocked. RestoreSchedulerLock: now unlocked.
Definition stk_common.h:164
@ LOCK_FAIL
Kernel is not running, is suspended, or is in KERNEL_HRT mode.
Definition stk_common.h:163
@ LOCK_FAIL_ISR
Called from an ISR.
Definition stk_common.h:162
@ LOCK_WAS_LOCKED
LockScheduler/UnlockScheduler: previous state was locked. RestoreSchedulerLock: now locked.
Definition stk_common.h:165
ESystemTaskId
System task id.
Definition stk_common.h:116
@ SYS_TASK_ID_EXIT
Exit trap.
Definition stk_common.h:118
@ SYS_TASK_ID_SLEEP
Sleep trap.
Definition stk_common.h:117
static constexpr Weight DEFAULT_WEIGHT
Weight value: default weight of value (1) (see SwitchStrategySmoothWeightedRoundRobin).
Definition stk_common.h:290
static constexpr bool IsIsrTid(TId id)
Test whether a task identifier represents an ISR context.
Definition stk_common.h:309
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:296
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:285
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274
static constexpr TId TID_NONE
Reserved task/thread id representing zero/none thread id.
Definition stk_common.h:268
ETraceEventId
Trace event identifiers for tracing task suspension and resume with debugging tools (e....
Definition stk_common.h:126
@ TRACE_EVENT_UNKNOWN
Unknown / uninitialized trace event.
Definition stk_common.h:127
@ TRACE_EVENT_SLEEP
Task entered a sleep state.
Definition stk_common.h:129
@ TRACE_EVENT_SUSPEND
Task suspended via Suspend.
Definition stk_common.h:131
@ TRACE_EVENT_SWITCH
Task blocked by the context switch.
Definition stk_common.h:128
@ TRACE_EVENT_WAIT
Task suspended on a sync object.
Definition stk_common.h:130
EStackType
Stack type.
Definition stk_common.h:96
@ STACK_SLEEP_TRAP
Stack of the Sleep trap.
Definition stk_common.h:98
@ STACK_USER_TASK
Stack of the user task.
Definition stk_common.h:97
@ STACK_EXIT_TRAP
Stack of the Exit trap.
Definition stk_common.h:99
EResumeResult
Result of IKernel::ResumeTask().
Definition stk_common.h:183
@ RESUME_FAIL
Task is not bound to the kernel, or is exiting.
Definition stk_common.h:184
@ RESUME_LIFTED
Deferred suspension was cancelled before it took effect.
Definition stk_common.h:187
@ RESUME_NOT_SUSPENDED
Task was not suspended by SuspendTask() (no-op).
Definition stk_common.h:185
@ RESUME_DONE
Suspended task has been resumed.
Definition stk_common.h:186
uint64_t Cycles
Cycles value.
Definition stk_common.h:231
EHwException
Hardware exception id (see IPlatform::IEventOverrider::OnException).
Definition stk_common.h:194
@ HW_EXCEPT_MEMACCESS
MemManage on ARM / Page Fault or PMP violation on RISC-V.
Definition stk_common.h:196
@ HW_EXCEPT_FATAL
HardFault on ARM / Unhandled Fatal Trap on RISC-V.
Definition stk_common.h:195
Word TId
Task (thread) id.
Definition stk_common.h:211
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:236
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 ...
Definition stk.h:39
ARMv7-M/ARMv8-M system fault exception context state capture.
Lightweight, non-owning view over a contiguous sequence of elements.
Definition stk_common.h:323
ArrayView()
Construct an empty ArrayView with a null pointer and zero size.
Definition stk_common.h:329
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:371
T * GetPtr()
Get pointer to the beginning of elements in the view.
Definition stk_common.h:353
ArrayView(T *ptr, size_t size)
Construct an ArrayView from a raw pointer and size.
Definition stk_common.h:336
size_t GetSize() const
Get number of elements in the view.
Definition stk_common.h:363
const T * GetPtr() const
Get constant pointer to the beginning of elements in the view.
Definition stk_common.h:358
T & operator[](size_t index) const
Subscript operator for element access.
Definition stk_common.h:344
T * m_ptr
Pointer to the underlying memory block.
Definition stk_common.h:376
size_t m_size
Total number of elements in the view.
Definition stk_common.h:377
Snapshot of the kernel-side state of a task, filled in by IKernel::GetTaskState().
Definition stk_common.h:384
ETaskState state
Task state.
Definition stk_common.h:385
ISyncObject * wait_obj
Definition stk_common.h:386
Stack descriptor.
Definition stk_common.h:473
uint32_t access_mode
Bitfield with hardware access mode of the task (see EAccessMode).
Definition stk_common.h:475
TId tid
Task id (see STK_SEGGER_SYSVIEW, STK_MPU_STACK_GUARD).
Definition stk_common.h:486
Word SP
Offset 0: Stack Pointer (SP) register (note: must always be at offset 0).
Definition stk_common.h:474
Interface for a stack memory region.
Definition stk_common.h:494
~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:511
virtual const Word * GetStack() const =0
Get pointer to the stack memory.
Wait object.
Definition stk_common.h:543
EState
State of the WaitObject.
Definition stk_common.h:559
@ STATE_CANCELLED
Wait was cancelled via Cancel() rather than Wake()/timeout.
Definition stk_common.h:564
@ STATE_TIMEOUT
Wait expired due to timeout rather than a Wake() signal.
Definition stk_common.h:563
@ STATE_SIGNALED
Wake signaled.
Definition stk_common.h:562
@ STATE_NONE
Not waiting, no result pending.
Definition stk_common.h:560
@ STATE_WAIT
Wait is active.
Definition stk_common.h:561
DLEntryType ListEntryType
List entry type of IWaitObject elements.
Definition stk_common.h:553
DLHeadType ListHeadType
List head type for IWaitObject elements.
Definition stk_common.h:548
virtual TId GetTid() const =0
Get thread Id of the task that owns this wait object.
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:606
const char * GetTraceName() const
Get name.
Definition stk_common.h:629
void SetTraceName(const char *name)
Set name.
Definition stk_common.h:617
~ITraceable()=default
Destructor.
Synchronization object interface.
Definition stk_common.h:659
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:315
DLEntryType ListEntryType
List entry type of ISyncObject elements.
Definition stk_common.h:672
~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:777
DLHeadType ListHeadType
List head type for ISyncObject elements.
Definition stk_common.h:667
friend class tz::nsec::detail::CmseISyncObjectWrapper
Definition stk_common.h:661
static void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
Called by kernel when a new task starts waiting on this event.
Definition stk_common.h:679
virtual IWaitObject::ListHeadType & GetMutableWaitList()=0
Get list of tasks blocked on this object.
friend class IKernelService
Definition stk_common.h:660
static void WakeAll(IWaitObject::ListHeadType &wlist)
Wake all tasks currently in the wait list.
Definition stk_common.h:752
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:696
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:349
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:736
Interface for mutex synchronization primitive.
Definition stk_common.h:817
~IMutex()=default
Destructor.
virtual bool TryLock()=0
Try locking the mutex in a single non-blocking attempt.
virtual void Unlock()=0
Unlock the mutex.
virtual void Lock()=0
Lock the mutex.
ScopedLock(IMutex &mutex)
Definition stk_common.h:827
Interface for a user task.
Definition stk_common.h:886
virtual Weight GetWeight() const
Get static base weight of the task.
Definition stk_common.h:997
virtual EAccessMode GetAccessMode() const =0
Get pointer to the stack memory.
virtual const char * GetTraceName() const
Get task trace name set by application.
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:990
virtual Timeout GetTimeSlice() const
Get time-slice quantum of the task (ticks). KERNEL_TIMESLICE only.
~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:973
Scheduling-strategy-facing interface for a kernel task slot.
virtual void Wake()=0
Wake a sleeping task on the next scheduling tick.
DLEntryType ListEntryType
List entry type of IKernelTask elements.
virtual Weight GetCurrentWeight() const =0
Get the current dynamic weight value of this task.
virtual Weight GetWeight() const =0
Get the effective weight of the task.
virtual Timeout GetHrtRelativeDeadline() const =0
Get HRT task's remaining 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.
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 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 ForceContextSwitch(TId id)=0
Force context switch.
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.
Interface for a back-end event handler.
virtual void OnTaskExit(const 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 *&active)=0
Called by ISR handler to notify that scheduling is about to start.
virtual bool OnForceContextSwitch(TId id, Stack *&idle, Stack *&active)=0
Called when a task state change forces a context switch (sleep, wait, suspend, yield,...
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 OnSuspend(bool suspended)=0
Called by the driver when scheduling is suspended or resumed (tickless suspend, see IPlatform::Suspen...
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_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.
virtual EAddResult AddTask(ITask *user_task)=0
Add user task.
void SuspendTask(ITask *user_task, bool &suspended)
Suspend task (legacy form).
virtual ELockResult SetSchedulerLock(bool lock)=0
Lock or unlock task switching. Ticks, timeouts and ISRs keep running.
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 ESuspendResult SuspendTask(ITask *user_task)=0
Suspend task.
virtual bool GetTaskState(ITask *user_task, TaskStateInfo &info) const =0
Get a snapshot of the kernel-side state of a task.
size_t EnumerateTasksT(TCallback &&callback)
Enumerate tasks, invoking a callback for each active task.
virtual EAddResult AddTask(ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc)=0
Add user task.
virtual size_t EnumerateKernelTasks(ArrayView< IKernelTask * > tasks)=0
Enumerate kernel tasks.
virtual EResumeResult ResumeTask(ITask *user_task)=0
Resume task suspended by SuspendTask(), or lift its deferred suspension.
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 or sleep, waking it early.
virtual void Start()=0
Start kernel scheduling.
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 ELockResult UnlockScheduler()=0
Enable task switching (equivalent of CMSIS-RTOS2 osKernelUnlock).
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.
virtual bool Sleep(Timeout ticks)=0
Put calling process into a sleep state.
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 Weight SetWeight(TId tid, Weight weight)=0
Change the base weight of the task at run-time (replaces ITask::GetWeight() value).
virtual void ExitTask()=0
Terminate the calling task: schedule its removal and switch it out. Does not return.
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 ELockResult LockScheduler()=0
Disable task switching (equivalent of CMSIS-RTOS2 osKernelLock). Ticks, timeouts and ISRs keep runnin...
virtual ELockResult RestoreSchedulerLock(bool locked)=0
Set the lock state (equivalent of CMSIS-RTOS2 osKernelRestoreLock).
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)
Casts an intrusive list entry to the concrete type that derives from it.
MPU region descriptor (raw hardware register values).
MPU descriptor of the task (a set of NUM_REGIONS regions), see TaskMpu / TaskMpuNs.
Aggregated hardware MPU setup configuration and state descriptor.