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_helper.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_HELPER_H_
11#define STK_HELPER_H_
12
13#include "stk_common.h"
14#include "stk_arch.h"
15#ifdef _STK_CORTEX_M_TRUSTZONE_NON_SECURE
16 #include "arch/arm/cortex-m/stk_arch_arm-tz.h"
17#endif
18
22
23namespace stk {
24
35template <size_t TStackSize> struct StackMemoryDef
36{
37 enum EConsts : size_t
38 {
39 SIZE = TStackSize
40 };
41
45#if STK_MPU_STACK_GUARD
46 #if STK_ARCH_ARMV8_M
47 // ARMv8-M alignment is 32 bytes.
48 typedef __stk_aligned(32U) Word Type[SIZE];
49 #else
50 // ARMv7-M alignment is a size of the memory region.
51 typedef __stk_aligned(TStackSize * sizeof(Word)) Word Type[SIZE];
52 #endif
53#else
55#endif
56};
57
91template <size_t _StackSize, EAccessMode _AccessMode>
92class Task
93#ifdef _STK_CORTEX_M_TRUSTZONE_NON_SECURE
94 : public tz::nsec::NsTask
95#else
96 : public ITask
97#endif
98{
99public:
100 enum { STACK_SIZE = _StackSize };
101
102 const Word *GetStack() const override { return const_cast<Word *>(m_stack); }
103 size_t GetStackSize() const override { return _StackSize; }
104 EAccessMode GetAccessMode() const override { return _AccessMode; }
105
106 TId GetTid() const { return GetTidFromUserTask(this); }
107
108protected:
110
119 {}
120
124 STK_VIRT_DTOR ~Task() = default;
125
126private:
128};
129
144template <Weight _Weight, size_t _StackSize, EAccessMode _AccessMode>
145class TaskW
146#ifdef _STK_CORTEX_M_TRUSTZONE_NON_SECURE
147 : public tz::nsec::NsTask
148#else
149 : public ITask
150#endif
151{
152public:
153 enum { STACK_SIZE = _StackSize };
154
155 const Word *GetStack() const override { return const_cast<Word *>(m_stack); }
156 size_t GetStackSize() const override { return _StackSize; }
157 EAccessMode GetAccessMode() const override { return _AccessMode; }
158 Weight GetWeight() const override { return _Weight; }
159
160 TId GetTid() const { return GetTidFromUserTask(this); }
161
162protected:
164
172 TaskW() : m_stack() {}
173
178
179private:
181};
182
190template <size_t _StackSize>
192{
193public:
198
204 explicit StackMemoryWrapper(MemoryType *stack) : m_stack(stack)
205 {
206 STK_STATIC_ASSERT(_StackSize >= STACK_SIZE_MIN);
207 }
208
212
215 const Word *GetStack() const override { return (*m_stack); }
216
219 size_t GetStackSize() const override { return _StackSize; }
220
221private:
223};
224
246#ifdef _STK_CORTEX_M_TRUSTZONE_NON_SECURE
247 : public tz::nsec::NsSyncObject
248#else
249 : public ISyncObject
250#endif
251{
252 friend class IKernelService;
253
254public:
255 void AddWaitObject(IWaitObject *wobj) override
256 {
258 }
259
260 void RemoveWaitObject(IWaitObject *wobj) override
261 {
263 }
264
266 {
267 return m_wait_list;
268 }
269
270protected:
275 {}
276
286 {
288
289 ISyncObject::ListHeadType *const head = GetHead();
290 if (head != nullptr)
291 {
292 head->Unlink(this);
293 }
294 }
295
296 void WakeOne() override
297 {
298 IKernelService::GetInstance()->Wake(this, false);
299 }
300
301 void WakeAll() override
302 {
303 IKernelService::GetInstance()->Wake(this, true);
304 }
305
307 {
308 return m_wait_list;
309 }
310
312};
313
315inline bool ISyncObject::Tick(Timeout elapsed_ticks)
316{
318
319 // note: ScopedCriticalSection usage
320 //
321 // Single-core: no critical section needed - Tick() runs from the tick ISR,
322 // which cannot be re-entered on the local core.
323 //
324 // Multi-core: critical section is required because the tick handler on
325 // each core may call Tick() concurrently for the same sync object,
326 // and ISyncObject::Tick() is not re-entrant.
327#if (STK_ARCH_CPU_COUNT > 1)
329#endif
330
332
333 while (itr != nullptr)
334 {
336
337 if (!itr->Tick(elapsed_ticks))
338 {
339 itr->Wake(true);
340 }
341
342 itr = next;
343 }
344
345 return !wlist.IsEmpty();
346}
347
350{
351 Weight max_weight = NO_WEIGHT;
353
354 while (itr != nullptr)
355 {
356 const Weight w = GetUserTaskFromTid(itr->GetTid())->GetWeight();
357 if (w > max_weight)
358 {
359 max_weight = w;
360 }
361
363 }
364
365 return ((max_weight > comp) ? max_weight : NO_WEIGHT);
366}
367
378
388
395static __stk_forceinline Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
396{
397 return static_cast<Time>((tick_count * static_cast<Time>(resolution)) / 1000LL);
398}
399
406static __stk_forceinline Ticks GetTicksFromMs(Time ms, uint32_t resolution)
407{
408 Ticks tick_count = 0LL;
409
410 if (resolution != 0U)
411 {
412 tick_count = static_cast<Ticks>((ms * 1000LL) / static_cast<Time>(resolution));
413 }
414
415 return tick_count;
416}
417
428
435{
436 const Time time_ms = static_cast<Time>(ms);
437 const Ticks tick_count = GetTicksFromMs(time_ms);
438 const Ticks final_ticks = (tick_count < static_cast<Ticks>(WAIT_INFINITE)) ?
439 tick_count : static_cast<Ticks>(WAIT_INFINITE);
440
441 return static_cast<Timeout>(final_ticks);
442}
443
452
460{
461 const IKernelService *const service = IKernelService::GetInstance();
462 const uint32_t resolution = service->GetTickResolution();
463 const Ticks tick_count = service->GetTicks();
464
465 return ((resolution == 1000U) ? tick_count :
466 ((tick_count * static_cast<Ticks>(resolution)) / 1000LL));
467}
468
477
486
495static __stk_forceinline bool Sleep(Timeout tick_count)
496{
497 return IKernelService::GetInstance()->Sleep(tick_count);
498}
499
510{
512}
513
523static __stk_forceinline bool SleepUntil(Ticks timestamp)
524{
525 return IKernelService::GetInstance()->SleepUntil(timestamp);
526}
527
540{
542}
543
566
582
604
615
628
645
656{
657 return IKernelService::GetInstance()->SetWeight(tid, weight);
658}
659
670{
671 return SetWeight(GetTid(), weight);
672}
673
683{
684 return IKernelService::GetInstance()->SetTimeSlice(tid, ticks);
685}
686
693{
694 return SetTimeSlice(GetTid(), ticks);
695}
696
703static __stk_forceinline void Delay(Timeout tick_count)
704{
705 IKernelService::GetInstance()->Delay(tick_count);
706}
707
718
719} // namespace stk
721#endif /* STK_HELPER_H_ */
Hardware Abstraction Layer (HAL) declarations for the stk::hw namespace.
Contains interface definitions of the library.
#define __stk_forceinline
Forces compiler to always inline the decorated function, regardless of optimisation level.
Definition stk_defs.h:270
#define __stk_aligned(x)
Specifies minimum alignment in bytes for the decorated variable or struct member (data instance prefi...
Definition stk_defs.h:282
#define STK_NONCOPYABLE_CLASS(TYPE)
Deletes (= delete) the copy constructor and copy assignment operator of a class.
Definition stk_defs.h:708
#define STK_STACK_MEMORY_ALIGN
Stack memory alignment.
Definition stk_defs.h:582
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:560
#define STK_VIRT_DTOR
Expands to nothing if STK_STRICT_COMPLIANCY=0 (non-virtual destructors, smaller objects),...
Definition stk_defs.h:254
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:206
static Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
Convert ticks to milliseconds.
Definition stk_helper.h:395
static void Yield()
Notify scheduler to switch to the next runnable task.
Definition stk_helper.h:562
static Timeout SetTimeSlice(TId tid, Timeout ticks)
Change the time-slice quantum of a task at run-time and reload its slice.
Definition stk_helper.h:682
static void SleepCancel(TId task_id)
Cancel sleep of the task.
Definition stk_helper.h:539
EAccessMode
Hardware access modes by the task.
Definition stk_common.h:36
static Time GetTimeNowMs()
Get current time in milliseconds since kernel start.
Definition stk_helper.h:459
ITask * GetUserTaskFromTid(TId task_id) noexcept
Get task instance from its identifier.
Definition stk_arch.h:784
static bool SleepMs(Timeout ms)
Put calling process into a sleep state.
Definition stk_helper.h:509
@ 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
TId GetTidFromUserTask(const ITask *task) noexcept
Get task identifier from ITask instance.
Definition stk_arch.h:775
static void ExitTask()
Terminate the calling task: schedule its removal and switch it out. Does not return.
Definition stk_helper.h:578
int64_t Ticks
Ticks value.
Definition stk_common.h:221
static bool Sleep(Timeout tick_count)
Put calling process into a sleep state.
Definition stk_helper.h:495
static void DelayMs(Timeout ms)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:714
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:216
static ELockResult UnlockScheduler()
Enable task switching (equivalent of CMSIS-RTOS2 osKernelUnlock).
Definition stk_helper.h:611
static bool SleepUntil(Ticks timestamp)
Put calling process into a sleep state until the specified timestamp.
Definition stk_helper.h:523
int64_t Time
Time value.
Definition stk_common.h:226
static ELockResult LockScheduler()
Disable task switching (equivalent of CMSIS-RTOS2 osKernelLock). Ticks, timeouts and ISRs keep runnin...
Definition stk_helper.h:600
ELockResult
Result of IKernel::SetSchedulerLock(), IKernelService::LockScheduler(), UnlockScheduler() and Restore...
Definition stk_common.h:161
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:406
static uint32_t GetTickResolution()
Get number of microseconds in one tick.
Definition stk_helper.h:384
static uint32_t GetSysTimerFrequency()
Get system timer frequency.
Definition stk_helper.h:482
static void Delay(Timeout tick_count)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:703
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:285
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:448
static Weight SetWeight(TId tid, Weight weight)
Change the base scheduling weight of a task at run-time.
Definition stk_helper.h:655
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:374
IKernelService::ScopedSchedulerLock ScopedSchedulerLock
RAII scheduler lock: disables task switching for the lifetime of the object.
Definition stk_helper.h:644
static ELockResult RestoreSchedulerLock(bool locked)
Set the scheduler lock state (equivalent of CMSIS-RTOS2 osKernelRestoreLock).
Definition stk_helper.h:624
static Timeout GetTicksFromMsClampedToTimeout(Timeout ms)
Convert milliseconds to ticks and clamp the result to a Timeout type.
Definition stk_helper.h:434
static Cycles GetSysTimerCount()
Get system timer count value.
Definition stk_helper.h:473
uint64_t Cycles
Cycles value.
Definition stk_common.h:231
Word TId
Task (thread) id.
Definition stk_common.h:211
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:236
RAII instance that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:495
Interface for a stack memory region.
Definition stk_common.h:494
Wait object.
Definition stk_common.h:543
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.
virtual bool Tick(Timeout elapsed_ticks)=0
Update wait object's waiting time.
Synchronization object interface.
Definition stk_common.h:659
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
DLHeadType ListHeadType
List head type for ISyncObject elements.
Definition stk_common.h:667
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.
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
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
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 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.
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 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 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 void Delay(Timeout ticks)=0
Delay calling process.
Disable task switching (equivalent of CMSIS-RTOS2 osKernelLock). Ticks, timeouts and ISRs keep runnin...
Stack memory type definition.
Definition stk_helper.h:36
Word Type[SIZE]
Stack memory type.
Definition stk_helper.h:51
Task()
Initializes task instance and zero-initializes its internal stack memory.
Definition stk_helper.h:118
Task(const Task &)=delete
TId GetTid() const
Definition stk_helper.h:106
~Task()=default
Destructor.
size_t GetStackSize() const override
Get number of elements of the stack memory array.
Definition stk_helper.h:103
const Word * GetStack() const override
Get pointer to the stack memory.
Definition stk_helper.h:102
StackMemoryDef< _StackSize >::Type m_stack
Stack memory region, STK_STACK_MEMORY_ALIGN-byte aligned.
Definition stk_helper.h:127
EAccessMode GetAccessMode() const override
Get pointer to the stack memory.
Definition stk_helper.h:104
Weight GetWeight() const override
Get static base weight of the task.
Definition stk_helper.h:158
TaskW(const TaskW &)=delete
const Word * GetStack() const override
Get pointer to the stack memory.
Definition stk_helper.h:155
~TaskW()=default
Destructor.
EAccessMode GetAccessMode() const override
Get pointer to the stack memory.
Definition stk_helper.h:157
size_t GetStackSize() const override
Get number of elements of the stack memory array.
Definition stk_helper.h:156
TaskW()
Initializes task instance and zero-initializes its internal stack memory.
Definition stk_helper.h:172
TId GetTid() const
Definition stk_helper.h:160
StackMemoryDef< _StackSize >::Type m_stack
Stack memory region, STK_STACK_MEMORY_ALIGN-byte aligned.
Definition stk_helper.h:180
size_t GetStackSize() const override
Get number of elements in the wrapped stack array.
Definition stk_helper.h:219
~StackMemoryWrapper()=default
Destructor.
const Word * GetStack() const override
Get pointer to the first element of the wrapped stack array.
Definition stk_helper.h:215
StackMemoryDef< _StackSize >::Type MemoryType
Definition stk_helper.h:197
StackMemoryWrapper(MemoryType *stack)
Construct a wrapper around an existing stack memory array.
Definition stk_helper.h:204
~SyncObjectBase()
Destructor.
Definition stk_helper.h:285
void WakeAll() override
Wake all tasks currently in the wait list.
Definition stk_helper.h:301
SyncObjectBase()
Constructor.
Definition stk_helper.h:274
void RemoveWaitObject(IWaitObject *wobj) override
Called by kernel when a waiting task is being removed (timeout expired, wait aborted,...
Definition stk_helper.h:260
IWaitObject::ListHeadType & GetMutableWaitList() override
Get list of tasks blocked on this object.
Definition stk_helper.h:306
IWaitObject::ListHeadType m_wait_list
Tasks blocked on this object.
Definition stk_helper.h:311
void WakeOne() override
Wake the first task in the wait list (FIFO order).
Definition stk_helper.h:296
const IWaitObject::ListHeadType & GetWaitList() const override
Get list of tasks blocked on this object.
Definition stk_helper.h:265
friend class IKernelService
Definition stk_helper.h:252
void AddWaitObject(IWaitObject *wobj) override
Called by kernel when a new task starts waiting on this event.
Definition stk_helper.h:255
bool IsEmpty() const
Check whether the list contains no entries.
void Unlink(DLEntryType *entry)
Remove entry from this list.
DLEntryType * GetFirst()
Get the first (front) entry without removing it.
DLEntryType * GetNext()
Get the next entry in the list.
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Casts an intrusive list entry to the concrete type that derives from it.