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};
53
73
84
94
98enum ESystemTaskId : uint32_t
99{
100 SYS_TASK_ID_SLEEP = 0xFFFFFFFF,
101 SYS_TASK_ID_EXIT = 0xFFFFFFFE
102};
103
108enum ETraceEventId : uint32_t
109{
112 TRACE_EVENT_SLEEP = 1000 + 1,
113 TRACE_EVENT_WAIT = 1000 + 2,
115};
116
126
135
143typedef uintptr_t Word;
144
148typedef Word TId;
149
153typedef int32_t Timeout;
154
158typedef int64_t Ticks;
159
163typedef int64_t Time;
164
168typedef uint64_t Cycles;
169
173typedef int32_t Weight;
174
200static constexpr TId TID_ISR_N = static_cast<TId>(0xFFFFF000U);
201
205static constexpr TId TID_NONE = static_cast<TId>(0U);
206
211static constexpr Timeout WAIT_INFINITE = INT32_MAX;
212
217static constexpr Timeout NO_WAIT = 0;
218
222static constexpr Weight NO_WEIGHT = -1;
223
227static constexpr Weight DEFAULT_WEIGHT = 1;
228
240static __stk_forceinline bool IsIsrTid(TId id) { return ((id & TID_ISR_N) == TID_ISR_N); }
241
253template <typename T> class ArrayView
254{
255public:
256 typedef T value_type;
257
260 ArrayView() : m_ptr(nullptr), m_size(0U)
261 {}
262
267 ArrayView(T *ptr, size_t size) : m_ptr(ptr), m_size(size)
268 {}
269
275 T &operator[](size_t index) const
276 {
277 STK_ASSERT(index < m_size); // enforces MISRA Rule 5-0-16
278 return UncheckedAt(index); // MISRA Rule 5-0-15 deviation centralized
279 }
280
284 T *GetPtr() { return m_ptr; }
285
289 const T *GetPtr() const { return m_ptr; }
290
294 size_t GetSize() const { return m_size; }
295
296private:
302 __stk_forceinline T &UncheckedAt(size_t index) const
303 {
304 return m_ptr[index]; // deviation: indexing non-array pointer
305 }
306
307 T *m_ptr;
308 size_t m_size;
309};
310
315#if STK_MPU
316struct MpuRegion
317{
318 Word addr;
319 Word attr;
320};
321#endif
322
327#if STK_MPU && STK_MPU_STACK_GUARD
328template <uint8_t REGIONS_COUNT>
329struct TaskMpuT
330{
338 static constexpr uint8_t NUM_REGIONS = REGIONS_COUNT;
339
340 MpuRegion region[NUM_REGIONS];
341};
343typedef TaskMpuT<STK_MPU_TASK_REGIONS> TaskMpu;
345typedef TaskMpuT<STK_MPU_TASK_REGIONS_NS> TaskMpuNs;
346#endif // STK_MPU && STK_MPU_STACK_GUARD
347
352#if STK_MPU
353typedef ArrayView<const struct MpuRegionConfig> MpuRegionList;
354#endif
355
362#if STK_MPU
363struct MpuConfig
364{
368 static constexpr uint32_t MPU_OFF = 0U;
369
372 MpuConfig() : regions(), mode(MPU_OFF)
373 {}
374
379 MpuConfig(const MpuRegionList &regions_, uint32_t mode_) : regions(regions_), mode(mode_)
380 {}
381
382 MpuRegionList regions;
383 uint32_t mode;
384};
385#endif
386
391struct Stack
392{
394 uint32_t access_mode;
395#if STK_MPU && STK_MPU_STACK_GUARD
396 TaskMpu mpu;
397 #ifdef _STK_CORTEX_M_TRUSTZONE
398 TaskMpuNs mpu_ns;
399 #endif
400#endif
401#if STK_TLS && !STK_TLS_PREFER_REGISTER
402 Word tls;
403#endif
404#if STK_STACK_NEEDS_TASK_ID
406#endif
407};
408
413{
414public:
417 virtual const Word *GetStack() const = 0;
418
421 virtual size_t GetStackSize() const = 0;
422
430 virtual size_t GetStackSpace() const
431 {
433 const size_t total_size = stack.GetSize();
434 size_t space = 0U;
435
436 for (size_t i = 0U; i < total_size; ++i)
437 {
438 if (stack[i] == STK_STACK_MEMORY_FILLER)
439 {
440 space = i + 1U;
441 }
442 else
443 {
444 break; // terminate loop as soon as watermark ends
445 }
446 }
447
448 return space;
449 }
450
451protected:
455 ~IStackMemory() = default;
456};
457
461class IWaitObject : public util::DListEntry<IWaitObject, false>
462{
463public:
468
473
477 virtual TId GetTid() const = 0;
478
485 virtual void Wake(bool timeout) = 0;
486
490 virtual bool IsTimeout() const = 0;
491
497 virtual bool Tick(Timeout elapsed_ticks) = 0;
498
499protected:
503 ~IWaitObject() = default;
504};
505
511{
512public:
513#if STK_SYNC_DEBUG_NAMES
514 ITraceable() : m_trace_name(nullptr)
515 {}
516#endif
517
522 void SetTraceName(const char *name)
523 {
524 #if STK_SYNC_DEBUG_NAMES
525 m_trace_name = name;
526 #else
527 STK_UNUSED(name);
528 #endif
529 }
530
534 const char *GetTraceName() const
535 {
536 #if STK_SYNC_DEBUG_NAMES
537 return m_trace_name;
538 #else
539 return nullptr;
540 #endif
541 }
542
543protected:
547 ~ITraceable() = default;
548
549#if STK_SYNC_DEBUG_NAMES
550 const char *m_trace_name;
551#endif
552};
553
563class ISyncObject : public util::DListEntry<ISyncObject, false>
564{
565 friend class IKernelService;
567
568public:
573
578
583 static inline void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
584 {
585 STK_ASSERT(wobj->GetHead() == nullptr);
586 wlist.LinkBack(wobj);
587 }
588
593 virtual void AddWaitObject(IWaitObject *wobj) = 0;
594
600 {
601 STK_ASSERT(wobj->GetHead() == &wlist);
602 wlist.Unlink(wobj);
603 }
604
609 virtual void RemoveWaitObject(IWaitObject *wobj) = 0;
610
623 virtual bool Tick(Timeout elapsed_ticks);
624
631
638 static inline void WakeOne(IWaitObject::ListHeadType &wlist)
639 {
641 {
642 obj->Wake(false);
643 }
644 }
645
652 static inline void WakeAll(IWaitObject::ListHeadType &wlist)
653 {
655 {
656 obj->Wake(false);
657 }
658 }
659
663 virtual const IWaitObject::ListHeadType &GetWaitList() const = 0;
664
665protected:
669 ~ISyncObject() = default;
670
677 virtual void WakeOne() = 0;
678
685 virtual void WakeAll() = 0;
686
690};
691
697{
698public:
705 {
706 public:
707 explicit ScopedLock(IMutex &mutex) : m_mutex(mutex) { m_mutex.Lock(); }
708 ~ScopedLock() { m_mutex.Unlock(); }
709
710 private:
712
714 };
715
718 virtual void Lock() = 0;
719
722 virtual void Unlock() = 0;
723
724protected:
728 ~IMutex() = default;
729};
730
754class ITask : public IStackMemory
755{
756public:
771 virtual void Run() = 0;
772
777#if STK_TZ_SECURE
778 virtual IStackMemory *GetSecureStackMemory() { return nullptr; }
779#endif
780
824#if STK_MPU
825 virtual const MpuRegionList *GetMpuRegions() const
826 {
827 return nullptr;
828 }
829#endif
830
833 virtual EAccessMode GetAccessMode() const = 0;
834
842 virtual void OnDeadlineMissed(uint32_t duration) { STK_UNUSED(duration); }
843
852 virtual void OnExit() {}
853
859 virtual Weight GetWeight() const { return DEFAULT_WEIGHT; }
860
866 virtual const char *GetTraceName() const { return nullptr; }
867
868protected:
872 ~ITask() = default;
873};
874
884class IKernelTask : public util::DListEntry<IKernelTask, true>
885{
886public:
891
896
899 virtual ITask *GetUserTask() = 0;
900
904 virtual Stack GetUserStack() const = 0;
905
911 virtual Weight GetWeight() const = 0;
912
918 virtual void SetCurrentWeight(Weight weight) = 0;
919
925 virtual Weight GetCurrentWeight() const = 0;
926
930 virtual Timeout GetHrtPeriodicity() const = 0;
931
935 virtual Timeout GetHrtDeadline() const = 0;
936
944 virtual Timeout GetHrtRelativeDeadline() const = 0;
945
949 virtual bool IsSleeping() const = 0;
950
956 virtual void Wake() = 0;
957
958protected:
962 ~IKernelTask() = default;
963};
964
978{
979public:
986 {
987 public:
992 virtual void OnStart(Stack *&enable) = 0;
993
998 virtual void OnStop() = 0;
999
1015 virtual bool OnTick(Stack *&idle, Stack *&active
1016 #if STK_TICKLESS_IDLE
1017 , Timeout &ticks
1018 #endif
1019 ) = 0;
1020
1024 virtual void OnTaskSwitch(Word caller_SP) = 0;
1025
1030 virtual void OnTaskSleep(Word caller_SP, Timeout ticks) = 0;
1031
1037 virtual bool OnTaskSleepUntil(Word caller_SP, Ticks timestamp) = 0;
1038
1042 virtual void OnTaskExit(Stack *stack) = 0;
1043
1050 virtual EWaitResult OnTaskWait(Word caller_SP, ISyncObject *sync_obj, IMutex *mutex, Timeout timeout) = 0;
1051
1056 virtual TId OnGetTid(Word caller_SP) = 0;
1057
1061 virtual void OnSuspend(bool suspended) = 0;
1062
1069 virtual bool OnForceContextSwitch(TId id, Stack *&idle, Stack *&active) = 0;
1070 };
1071
1077 {
1078 public:
1082 virtual bool OnSleep(Timeout sleep_ticks)
1083 {
1084 STK_UNUSED(sleep_ticks);
1085 return false;
1086 }
1087
1092 virtual bool OnHardFault()
1093 {
1094 return false;
1095 }
1096
1108 #if STK_MPU
1109 virtual const MpuConfig *OnConfigureMpu() const
1110 {
1111 return nullptr;
1112 }
1113 #endif
1114
1124 virtual bool OnException(EHwException exc_id, TId tid, const struct FaultContext *const ctx)
1125 {
1126 STK_UNUSED(exc_id);
1127 STK_UNUSED(tid);
1128 STK_UNUSED(ctx);
1129 return false;
1130 }
1131 };
1132
1140 virtual void Initialize(IEventHandler *event_handler, IKernelService *service, uint32_t resolution_us, Stack *exit_trap) = 0;
1141
1146 virtual void Start() = 0;
1147
1150 virtual void Stop() = 0;
1151
1158 virtual void InitStack(EStackType stack_type, Stack *stack, IStackMemory *stack_memory, ITask *user_task) = 0;
1159
1164 virtual uint32_t GetTickResolution() const = 0;
1165
1170 virtual Cycles GetSysTimerCount() const = 0;
1171
1176 virtual uint32_t GetSysTimerFrequency() const = 0;
1177
1180 virtual void SwitchToNext() = 0;
1181
1184 virtual void ForceContextSwitch(TId id) = 0;
1185
1190 virtual void Sleep(Timeout ticks) = 0;
1191
1199 virtual bool SleepUntil(Ticks timestamp) = 0;
1200
1214 virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout) = 0;
1215
1225 virtual void ProcessTick() = 0;
1226
1230 virtual void ProcessHardFault() = 0;
1231
1237 virtual void SetEventOverrider(IEventOverrider *overrider, bool non_secure = false) = 0;
1238
1243 virtual Word GetCallerSP() const = 0;
1244
1250 virtual TId GetTid() const = 0;
1251
1258 virtual Timeout Suspend() = 0;
1259
1265 virtual void Resume(Timeout elapsed_ticks) = 0;
1266
1274 virtual void SetCpuFrequency(uint8_t core_id, uint32_t frequency) = 0;
1275
1276protected:
1280 ~IPlatform() = default;
1281};
1282
1307{
1308public:
1313 virtual void AddTask(IKernelTask *task) = 0;
1314
1319 virtual void RemoveTask(IKernelTask *task) = 0;
1320
1324 virtual IKernelTask *GetFirst() = 0;
1325
1332 virtual IKernelTask *GetNext() = 0;
1333
1337 virtual size_t GetSize() const = 0;
1338
1343 virtual void OnTaskSleep(IKernelTask *task) = 0;
1344
1349 virtual void OnTaskWake(IKernelTask *task) = 0;
1350
1372 {
1373 STK_UNUSED(task);
1374 return false;
1375 }
1376
1389 virtual void OnTaskWeightChange(IKernelTask *task, Weight old_weight)
1390 {
1391 STK_UNUSED(task);
1392 STK_UNUSED(old_weight);
1393 }
1394
1395protected:
1400};
1401
1408{
1409public:
1420
1431 virtual void Initialize(uint32_t resolution_us = PERIODICITY_DEFAULT) = 0;
1432
1438 virtual void AddTask(ITask *user_task) = 0;
1439
1447 virtual void AddTask(ITask *user_task, Timeout periodicity_tc, Timeout deadline_tc, Timeout start_delay_tc) = 0;
1448
1459 virtual void RemoveTask(ITask *user_task) = 0;
1460
1468 virtual void ScheduleTaskRemoval(ITask *user_task) = 0;
1469
1476 virtual void SuspendTask(ITask *user_task, bool &suspended) = 0;
1477
1481 virtual void ResumeTask(ITask *user_task) = 0;
1482
1489
1495 virtual size_t EnumerateTasks(ArrayView<ITask *> user_tasks) = 0;
1496
1517 template <size_t TMaxCount, typename TCallback>
1518 size_t EnumerateTasksT(TCallback &&callback)
1519 {
1520 STK_STATIC_ASSERT(TMaxCount > 0U);
1521
1522 ITask *tasks[TMaxCount] = {};
1523 size_t count = EnumerateTasks(ArrayView<ITask *>(tasks, TMaxCount));
1524 size_t i = 0U;
1525 bool fetch_next = true;
1526
1527 while ((i < count) && fetch_next)
1528 {
1529 fetch_next = callback(tasks[i]);
1530 ++i;
1531 }
1532
1533 return i;
1534 }
1535
1540 virtual void Start() = 0;
1541
1546 virtual EKernelState GetState() const = 0;
1547
1551 virtual IPlatform *GetPlatform() = 0;
1552
1557
1558protected:
1562 ~IKernel() = default;
1563};
1564
1574{
1575public:
1579
1585 virtual TId GetTid() const = 0;
1586
1591 virtual Ticks GetTicks() const = 0;
1592
1598 virtual uint32_t GetTickResolution() const = 0;
1599
1604 virtual Cycles GetSysTimerCount() const = 0;
1605
1610 virtual uint32_t GetSysTimerFrequency() const = 0;
1611
1619 virtual void Delay(Timeout ticks) = 0;
1620
1627 virtual void Sleep(Timeout ticks) = 0;
1628
1636 virtual bool SleepUntil(Ticks timestamp) = 0;
1637
1643 virtual void SleepCancel(TId task_id) = 0;
1644
1649 virtual void SwitchToNext() = 0;
1650
1664 virtual EWaitResult Wait(ISyncObject *sobj, IMutex *mutex, Timeout timeout) = 0;
1665
1673 virtual void Wake(ISyncObject *sobj, bool all) = 0;
1674
1685 virtual Timeout Suspend() = 0;
1686
1698 virtual void Resume(Timeout elapsed_ticks) = 0;
1699
1705 virtual void InheritWeight(TId tid, Weight weight) = 0;
1706
1713 virtual void RestoreWeight(TId tid, ISyncObject *sobj = nullptr) = 0;
1714
1715protected:
1719 ~IKernelService() = default;
1720
1724 {
1725 return sobj->GetWaitList();
1726 }
1727};
1728
1729} // namespace stk
1730
1731#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:143
static constexpr TId TID_ISR_N
Bitmask sentinel for ISR-context task identifiers.
Definition stk_common.h:200
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:217
EWaitResult
Wait result (see IKernelService::Wait).
Definition stk_common.h:121
@ WAIT_RESULT_FAIL
IKernelService::Wait returned with error without waiting.
Definition stk_common.h:122
@ WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_common.h:124
@ WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_common.h:123
EConsts
Constants.
Definition stk_common.h:89
@ PERIODICITY_DEFAULT
Default periodicity (microseconds), 1 millisecond.
Definition stk_common.h:91
@ 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:92
@ PERIODICITY_MAX
Maximum periodicity (microseconds), 99 milliseconds (note: this value is the highest working on a rea...
Definition stk_common.h:90
int64_t Ticks
Ticks value.
Definition stk_common.h:158
EKernelPanicId
Identifies the source of a kernel panic.
Definition stk_common.h:58
@ KERNEL_PANIC_UNKNOWN_SVC
Unknown service command received by SVC handler.
Definition stk_common.h:66
@ KERNEL_PANIC_BAD_STACK_TYPE
Stack type is unknown.
Definition stk_common.h:69
@ KERNEL_PANIC_NS_ACCESS
Non-secure access to protected resource.
Definition stk_common.h:70
@ KERNEL_PANIC_BAD_MODE
Kernel is in bad/unsupported mode for the current operation.
Definition stk_common.h:68
@ KERNEL_PANIC_HRT_HARD_FAULT
Kernel running in KERNEL_HRT mode reported deadline failure of the task.
Definition stk_common.h:63
@ KERNEL_PANIC_CS_NESTING_OVERFLOW
Critical section nesting limit exceeded: violation of STK_CS_NESTINGS_MAX.
Definition stk_common.h:65
@ KERNEL_PANIC_NONE
Panic is absent (no fault).
Definition stk_common.h:59
@ KERNEL_PANIC_BAD_MEMORY_REGION
Bad memory region (ARM TrustZone: provided memory region overlaps with another one).
Definition stk_common.h:71
@ KERNEL_PANIC_CPU_EXCEPTION
CPU reported an exception and halted execution.
Definition stk_common.h:64
@ KERNEL_PANIC_STACK_CORRUPT
Stack integrity check failed.
Definition stk_common.h:61
@ KERNEL_PANIC_SPINLOCK_DEADLOCK
Spin-lock timeout expired: lock owner never released.
Definition stk_common.h:60
@ KERNEL_PANIC_BAD_STATE
Kernel entered unexpected (bad) state.
Definition stk_common.h:67
@ KERNEL_PANIC_ASSERT
Internal assertion failed (maps from STK_ASSERT).
Definition stk_common.h:62
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:153
static bool IsIsrTid(TId id)
Test whether a task identifier represents an ISR context.
Definition stk_common.h:240
int64_t Time
Time value.
Definition stk_common.h:163
ESystemTaskId
System task id.
Definition stk_common.h:99
@ SYS_TASK_ID_EXIT
Exit trap.
Definition stk_common.h:101
@ SYS_TASK_ID_SLEEP
Sleep trap.
Definition stk_common.h:100
static constexpr Weight DEFAULT_WEIGHT
Weight value: default weight of value (1) (see SwitchStrategySmoothWeightedRoundRobin).
Definition stk_common.h:227
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:222
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:211
static constexpr TId TID_NONE
Reserved task/thread id representing zero/none thread id.
Definition stk_common.h:205
ETraceEventId
Trace event identifiers for tracing task suspension and resume with debugging tools (e....
Definition stk_common.h:109
@ TRACE_EVENT_UNKNOWN
Unknown / uninitialized trace event.
Definition stk_common.h:110
@ TRACE_EVENT_SLEEP
Task entered a sleep state.
Definition stk_common.h:112
@ TRACE_EVENT_SUSPEND
Task suspended via Suspend.
Definition stk_common.h:114
@ TRACE_EVENT_SWITCH
Task blocked by the context switch.
Definition stk_common.h:111
@ TRACE_EVENT_WAIT
Task suspended on a sync object.
Definition stk_common.h:113
EStackType
Stack type.
Definition stk_common.h:79
@ STACK_SLEEP_TRAP
Stack of the Sleep trap.
Definition stk_common.h:81
@ STACK_USER_TASK
Stack of the user task.
Definition stk_common.h:80
@ STACK_EXIT_TRAP
Stack of the Exit trap.
Definition stk_common.h:82
uint64_t Cycles
Cycles value.
Definition stk_common.h:168
EHwException
Hardware exception id (see IPlatform::IEventOverrider::OnException).
Definition stk_common.h:131
@ HW_EXCEPT_MEMACCESS
MemManage on ARM / Page Fault or PMP violation on RISC-V.
Definition stk_common.h:133
@ HW_EXCEPT_FATAL
HardFault on ARM / Unhandled Fatal Trap on RISC-V.
Definition stk_common.h:132
Word TId
Task (thread) id.
Definition stk_common.h:148
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:173
EKernelMode
Kernel operating mode.
Definition stk_common.h:46
@ 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:254
ArrayView()
Construct an empty ArrayView with a null pointer and zero size.
Definition stk_common.h:260
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:302
T * GetPtr()
Get pointer to the beginning of elements in the view.
Definition stk_common.h:284
ArrayView(T *ptr, size_t size)
Construct an ArrayView from a raw pointer and size.
Definition stk_common.h:267
size_t GetSize() const
Get number of elements in the view.
Definition stk_common.h:294
const T * GetPtr() const
Get constant pointer to the beginning of elements in the view.
Definition stk_common.h:289
T & operator[](size_t index) const
Subscript operator for element access.
Definition stk_common.h:275
T * m_ptr
Pointer to the underlying memory block.
Definition stk_common.h:307
size_t m_size
Total number of elements in the view.
Definition stk_common.h:308
Stack descriptor.
Definition stk_common.h:392
uint32_t access_mode
Bitfield with hardware access mode of the task (see EAccessMode).
Definition stk_common.h:394
TId tid
Task id (see STK_SEGGER_SYSVIEW, STK_MPU_STACK_GUARD).
Definition stk_common.h:405
Word SP
Offset 0: Stack Pointer (SP) register (note: must always be at offset 0).
Definition stk_common.h:393
Interface for a stack memory region.
Definition stk_common.h:413
~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:430
virtual const Word * GetStack() const =0
Get pointer to the stack memory.
Wait object.
Definition stk_common.h:462
DLEntryType ListEntryType
List entry type of IWaitObject elements.
Definition stk_common.h:472
DLHeadType ListHeadType
List head type for IWaitObject elements.
Definition stk_common.h:467
virtual TId GetTid() const =0
Get thread Id of the task owning .
virtual bool IsTimeout() const =0
Check if task woke up due to a timeout.
virtual void Wake(bool timeout)=0
Wake task.
~IWaitObject()=default
Destructor.
virtual bool Tick(Timeout elapsed_ticks)=0
Update wait object's waiting time.
Traceable object.
Definition stk_common.h:511
const char * GetTraceName() const
Get name.
Definition stk_common.h:534
void SetTraceName(const char *name)
Set name.
Definition stk_common.h:522
~ITraceable()=default
Destructor.
Synchronization object interface.
Definition stk_common.h:564
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:298
DLEntryType ListEntryType
List entry type of ISyncObject elements.
Definition stk_common.h:577
~ISyncObject()=default
Destructor.
virtual void WakeOne()=0
Wake the first task in the wait list (FIFO order).
virtual IWaitObject::ListHeadType & GetWaitList()=0
Get list of tasks blocked on this object.
friend class tz::nsec::util::CmseISyncObjectWrapper
Definition stk_common.h:566
DLHeadType ListHeadType
List head type for ISyncObject elements.
Definition stk_common.h:572
static void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
Called by kernel when a new task starts waiting on this event.
Definition stk_common.h:583
friend class IKernelService
Definition stk_common.h:565
static void WakeAll(IWaitObject::ListHeadType &wlist)
Wake all tasks currently in the wait list.
Definition stk_common.h:652
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:599
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:333
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:638
Interface for mutex synchronization primitive.
Definition stk_common.h:697
~IMutex()=default
Destructor.
virtual void Unlock()=0
Unlock the mutex.
virtual void Lock()=0
Lock the mutex.
ScopedLock(IMutex &mutex)
Definition stk_common.h:707
Interface for a user task.
Definition stk_common.h:755
virtual Weight GetWeight() const
Get static base weight of the task.
Definition stk_common.h:859
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:866
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:852
~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:842
Scheduling-strategy-facing interface for a kernel task slot.
Definition stk_common.h:885
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:895
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 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:890
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.
Definition stk_common.h:978
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.
Definition stk_common.h:986
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 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 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 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 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 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.
static IWaitObject::ListHeadType & GetWaitList(ISyncObject *sobj)
IWaitObject::GetWaitList() access helper.
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.
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.