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
106protected:
108
117 {}
118
122 STK_VIRT_DTOR ~Task() = default;
123
124private:
126};
127
143template <Weight _Weight, size_t _StackSize, EAccessMode _AccessMode>
144class TaskW
145#ifdef _STK_CORTEX_M_TRUSTZONE_NON_SECURE
146 : public tz::nsec::NsTask
147#else
148 : public ITask
149#endif
150{
151public:
152 enum { STACK_SIZE = _StackSize };
153
154 const Word *GetStack() const override { return const_cast<Word *>(m_stack); }
155 size_t GetStackSize() const override { return _StackSize; }
156 EAccessMode GetAccessMode() const override { return _AccessMode; }
157 Weight GetWeight() const override { return _Weight; }
158
159protected:
161
169 TaskW() : m_stack() {}
170
175
176private:
178};
179
187template <size_t _StackSize>
189{
190public:
195
201 explicit StackMemoryWrapper(MemoryType *stack) : m_stack(stack)
202 {
203 STK_STATIC_ASSERT(_StackSize >= STACK_SIZE_MIN);
204 }
205
209
212 const Word *GetStack() const override { return (*m_stack); }
213
216 size_t GetStackSize() const override { return _StackSize; }
217
218private:
220};
221
243#ifdef _STK_CORTEX_M_TRUSTZONE_NON_SECURE
244 : public tz::nsec::NsSyncObject
245#else
246 : public ISyncObject
247#endif
248{
249 friend class IKernelService;
250
251public:
252 void AddWaitObject(IWaitObject *wobj) override
253 {
255 }
256
257 void RemoveWaitObject(IWaitObject *wobj) override
258 {
260 }
261
263 {
264 return m_wait_list;
265 }
266
267protected:
272 {}
273
277 ~SyncObjectBase() = default;
278
279 void WakeOne() override
280 {
281 IKernelService::GetInstance()->Wake(this, false);
282 }
283
284 void WakeAll() override
285 {
286 IKernelService::GetInstance()->Wake(this, true);
287 }
288
290 {
291 return m_wait_list;
292 }
293
295};
296
298inline bool ISyncObject::Tick(Timeout elapsed_ticks)
299{
301
302 // note: ScopedCriticalSection usage
303 //
304 // Single-core: no critical section needed - Tick() runs inside the
305 // SysTick ISR which already executes with interrupts disabled, making
306 // re-entrancy impossible on the local core.
307 //
308 // Multi-core: critical section is required because the tick handler on
309 // each core may call Tick() concurrently for the same Semaphore instance,
310 // and ISyncObject::Tick() is not re-entrant.
311#if (STK_ARCH_CPU_COUNT > 1)
313#endif
314
316
317 while (itr != nullptr)
318 {
320
321 if (!itr->Tick(elapsed_ticks))
322 {
323 itr->Wake(true);
324 }
325
326 itr = next;
327 }
328
329 return !wlist.IsEmpty();
330}
331
334{
335 Weight max_weight = NO_WEIGHT;
337
338 while (itr != nullptr)
339 {
340 const Weight w = GetUserTaskFromTid(itr->GetTid())->GetWeight();
341 if (w > max_weight)
342 {
343 max_weight = w;
344 }
345
347 }
348
349 return ((max_weight > comp) ? max_weight : NO_WEIGHT);
350}
351
362
372
379static __stk_forceinline Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
380{
381 return static_cast<Time>((tick_count * static_cast<Time>(resolution)) / 1000LL);
382}
383
390static __stk_forceinline Ticks GetTicksFromMs(Time ms, uint32_t resolution)
391{
392 Ticks tick_count = 0LL;
393
394 if (resolution != 0U)
395 {
396 tick_count = static_cast<Ticks>((ms * 1000LL) / static_cast<Time>(resolution));
397 }
398
399 return tick_count;
400}
401
413
420{
421 const Time time_ms = static_cast<Time>(ms);
422 const Ticks tick_count = GetTicksFromMs(time_ms);
423
424 const Ticks final_ticks = (tick_count < static_cast<Ticks>(WAIT_INFINITE)) ?
425 tick_count : static_cast<Ticks>(WAIT_INFINITE);
426
427 return static_cast<Timeout>(final_ticks);
428}
429
438
446{
447 const IKernelService *const service = IKernelService::GetInstance();
448 const uint32_t resolution = service->GetTickResolution();
449 const Ticks tick_count = service->GetTicks();
450
451 return ((resolution == 1000U) ? tick_count :
452 ((tick_count * static_cast<Ticks>(resolution)) / 1000LL));
453}
454
463
472
479static __stk_forceinline void Sleep(Timeout tick_count)
480{
481 IKernelService::GetInstance()->Sleep(tick_count);
482}
483
496
504static __stk_forceinline bool SleepUntil(Ticks timestamp)
505{
506 return IKernelService::GetInstance()->SleepUntil(timestamp);
507}
508
515{
517}
518
527
534static __stk_forceinline void Delay(Timeout tick_count)
535{
536 IKernelService::GetInstance()->Delay(tick_count);
537}
538
549
550} // namespace stk
551
552#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:277
#define __stk_aligned(x)
Specifies minimum alignment in bytes for the decorated variable or struct member (data instance prefi...
Definition stk_defs.h:289
#define STK_NONCOPYABLE_CLASS(TYPE)
Disables copy construction and assignment for a class.
Definition stk_defs.h:708
#define STK_STACK_MEMORY_ALIGN
Stack memory alignment.
Definition stk_defs.h:575
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:553
#define STK_VIRT_DTOR
Makes destructors virtual and compliant to strict rules if STK_STRICT_COMPLIANCY=0.
Definition stk_defs.h:261
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:143
static Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
Convert ticks to milliseconds.
Definition stk_helper.h:379
static void Yield()
Notify scheduler to switch to the next runnable task.
Definition stk_helper.h:523
static void Sleep(Timeout tick_count)
Put calling process into a sleep state.
Definition stk_helper.h:479
static void SleepCancel(TId task_id)
Cancel sleep of the task.
Definition stk_helper.h:514
static void SleepMs(Timeout ms)
Put calling process into a sleep state.
Definition stk_helper.h:492
EAccessMode
Hardware access modes by the task.
Definition stk_common.h:36
static constexpr ITask * GetUserTaskFromTid(TId task_id) noexcept
Get task instance from its identifier.
Definition stk_arch.h:725
static Time GetTimeNowMs()
Get current time in milliseconds since kernel start.
Definition stk_helper.h:445
@ 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
int64_t Ticks
Ticks value.
Definition stk_common.h:158
static void DelayMs(Timeout ms)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:545
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:153
static bool SleepUntil(Ticks timestamp)
Put calling process into a sleep state until the specified timestamp.
Definition stk_helper.h:504
int64_t Time
Time value.
Definition stk_common.h:163
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:390
static uint32_t GetTickResolution()
Get number of microseconds in one tick.
Definition stk_helper.h:368
static uint32_t GetSysTimerFrequency()
Get system timer frequency.
Definition stk_helper.h:468
static void Delay(Timeout tick_count)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:534
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:222
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:434
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:211
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:358
static Timeout GetTicksFromMsClampedToTimeout(Timeout ms)
Convert milliseconds to ticks and clamp the result to a Timeout type.
Definition stk_helper.h:419
static Cycles GetSysTimerCount()
Get system timer count value.
Definition stk_helper.h:459
uint64_t Cycles
Cycles value.
Definition stk_common.h:168
Word TId
Task (thread) id.
Definition stk_common.h:148
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:173
RAII instance that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:494
Interface for a stack memory region.
Definition stk_common.h:413
Wait object.
Definition stk_common.h:462
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 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:564
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
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
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
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
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.
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 void Sleep(Timeout ticks)=0
Put calling process into a sleep state.
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.
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:116
Task(const Task &)=delete
~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:125
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:157
TaskW(const TaskW &)=delete
const Word * GetStack() const override
Get pointer to the stack memory.
Definition stk_helper.h:154
~TaskW()=default
Destructor.
EAccessMode GetAccessMode() const override
Get pointer to the stack memory.
Definition stk_helper.h:156
size_t GetStackSize() const override
Get number of elements of the stack memory array.
Definition stk_helper.h:155
TaskW()
Initializes task instance and zero-initializes its internal stack memory.
Definition stk_helper.h:169
StackMemoryDef< _StackSize >::Type m_stack
Stack memory region, 16-byte aligned.
Definition stk_helper.h:177
size_t GetStackSize() const override
Get number of elements in the wrapped stack array.
Definition stk_helper.h:216
~StackMemoryWrapper()=default
Destructor.
const Word * GetStack() const override
Get pointer to the first element of the wrapped stack array.
Definition stk_helper.h:212
StackMemoryDef< _StackSize >::Type MemoryType
Definition stk_helper.h:194
StackMemoryWrapper(MemoryType *stack)
Construct a wrapper around an existing stack memory array.
Definition stk_helper.h:201
~SyncObjectBase()=default
Destructor.
void WakeAll() override
Wake all tasks currently in the wait list.
Definition stk_helper.h:284
SyncObjectBase()
Constructor.
Definition stk_helper.h:271
void RemoveWaitObject(IWaitObject *wobj) override
Called by kernel when a waiting task is being removed (timeout expired, wait aborted,...
Definition stk_helper.h:257
IWaitObject::ListHeadType m_wait_list
Tasks blocked on this object.
Definition stk_helper.h:294
void WakeOne() override
Wake the first task in the wait list (FIFO order).
Definition stk_helper.h:279
const IWaitObject::ListHeadType & GetWaitList() const override
Get list of tasks blocked on this object.
Definition stk_helper.h:262
IWaitObject::ListHeadType & GetWaitList() override
Get list of tasks blocked on this object.
Definition stk_helper.h:289
friend class IKernelService
Definition stk_helper.h:249
void AddWaitObject(IWaitObject *wobj) override
Called by kernel when a new task starts waiting on this event.
Definition stk_helper.h:252
DLEntryType * GetFirst()
Get the first (front) entry without removing it.
bool IsEmpty() const
Check whether the list contains no entries.
DLEntryType * GetNext()
Get the next entry in the list.
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Safely casts an intrusive list entry to its concrete parent container object type.