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
210
213 const Word *GetStack() const override { return (*m_stack); }
214
217 size_t GetStackSize() const override { return _StackSize; }
218
219private:
221};
222
244#ifdef _STK_CORTEX_M_TRUSTZONE_NON_SECURE
245 : public tz::nsec::NsSyncObject
246#else
247 : public ISyncObject
248#endif
249{
250 friend class IKernelService;
251
252public:
253 void AddWaitObject(IWaitObject *wobj) override
254 {
256 }
257
258 void RemoveWaitObject(IWaitObject *wobj) override
259 {
261 }
262
264 {
265 return m_wait_list;
266 }
267
268protected:
273 {}
274
278 ~SyncObjectBase() = default;
279
280 void WakeOne() override
281 {
282 IKernelService::GetInstance()->Wake(this, false);
283 }
284
285 void WakeAll() override
286 {
287 IKernelService::GetInstance()->Wake(this, true);
288 }
289
291 {
292 return m_wait_list;
293 }
294
296};
297
299inline bool ISyncObject::Tick(Timeout elapsed_ticks)
300{
302
303 // note: ScopedCriticalSection usage
304 //
305 // Single-core: no critical section needed - Tick() runs inside the
306 // SysTick ISR which already executes with interrupts disabled, making
307 // re-entrancy impossible on the local core.
308 //
309 // Multi-core: critical section is required because the tick handler on
310 // each core may call Tick() concurrently for the same Semaphore instance,
311 // and ISyncObject::Tick() is not re-entrant.
312#if (STK_ARCH_CPU_COUNT > 1)
314#endif
315
317
318 while (itr != nullptr)
319 {
321
322 if (!itr->Tick(elapsed_ticks))
323 {
324 itr->Wake(true);
325 }
326
327 itr = next;
328 }
329
330 return !wlist.IsEmpty();
331}
332
335{
336 Weight max_weight = NO_WEIGHT;
338
339 while (itr != nullptr)
340 {
341 const Weight w = GetUserTaskFromTid(itr->GetTid())->GetWeight();
342 if (w > max_weight)
343 {
344 max_weight = w;
345 }
346
348 }
349
350 return ((max_weight > comp) ? max_weight : NO_WEIGHT);
351}
352
363
373
380static __stk_forceinline Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
381{
382 return static_cast<Time>((tick_count * static_cast<Time>(resolution)) / 1000LL);
383}
384
391static __stk_forceinline Ticks GetTicksFromMs(Time ms, uint32_t resolution)
392{
393 Ticks tick_count = 0LL;
394
395 if (resolution != 0U)
396 {
397 tick_count = static_cast<Ticks>((ms * 1000LL) / static_cast<Time>(resolution));
398 }
399
400 return tick_count;
401}
402
414
421{
422 const Time time_ms = static_cast<Time>(ms);
423 const Ticks tick_count = GetTicksFromMs(time_ms);
424
425 const Ticks final_ticks = (tick_count < static_cast<Ticks>(WAIT_INFINITE)) ?
426 tick_count : static_cast<Ticks>(WAIT_INFINITE);
427
428 return static_cast<Timeout>(final_ticks);
429}
430
439
447{
448 const IKernelService *const service = IKernelService::GetInstance();
449 const uint32_t resolution = service->GetTickResolution();
450 const Ticks tick_count = service->GetTicks();
451
452 return ((resolution == 1000U) ? tick_count :
453 ((tick_count * static_cast<Ticks>(resolution)) / 1000LL));
454}
455
464
473
480static __stk_forceinline void Sleep(Timeout tick_count)
481{
482 IKernelService::GetInstance()->Sleep(tick_count);
483}
484
497
505static __stk_forceinline bool SleepUntil(Ticks timestamp)
506{
507 return IKernelService::GetInstance()->SleepUntil(timestamp);
508}
509
516{
518}
519
528
535static __stk_forceinline void Delay(Timeout tick_count)
536{
537 IKernelService::GetInstance()->Delay(tick_count);
538}
539
550
551} // namespace stk
552
553#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:218
#define __stk_aligned(x)
Specifies minimum alignment in bytes for the decorated variable or struct member (data instance prefi...
Definition stk_defs.h:230
#define STK_NONCOPYABLE_CLASS(TYPE)
Disables copy construction and assignment for a class.
Definition stk_defs.h:647
#define STK_STACK_MEMORY_ALIGN
Stack memory alignment.
Definition stk_defs.h:514
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:492
#define STK_VIRT_DTOR
Makes destructors virtual and compliant to strict rules if STK_STRICT_COMPLIANCY=0.
Definition stk_defs.h:202
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:140
static Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
Convert ticks to milliseconds.
Definition stk_helper.h:380
static void Yield()
Notify scheduler to switch to the next runnable task.
Definition stk_helper.h:524
static void Sleep(Timeout tick_count)
Put calling process into a sleep state.
Definition stk_helper.h:480
static void SleepCancel(TId task_id)
Cancel sleep of the task.
Definition stk_helper.h:515
static void SleepMs(Timeout ms)
Put calling process into a sleep state.
Definition stk_helper.h:493
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:617
static Time GetTimeNowMs()
Get current time in milliseconds since kernel start.
Definition stk_helper.h:446
@ 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:91
int64_t Ticks
Ticks value.
Definition stk_common.h:155
static void DelayMs(Timeout ms)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:546
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:150
static bool SleepUntil(Ticks timestamp)
Put calling process into a sleep state until the specified timestamp.
Definition stk_helper.h:505
int64_t Time
Time value.
Definition stk_common.h:160
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:391
static uint32_t GetTickResolution()
Get number of microseconds in one tick.
Definition stk_helper.h:369
static uint32_t GetSysTimerFrequency()
Get system timer frequency.
Definition stk_helper.h:469
static void Delay(Timeout tick_count)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:535
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:219
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:435
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:208
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:359
static Timeout GetTicksFromMsClampedToTimeout(Timeout ms)
Convert milliseconds to ticks and clamp the result to a Timeout type.
Definition stk_helper.h:420
static Cycles GetSysTimerCount()
Get system timer count value.
Definition stk_helper.h:460
uint64_t Cycles
Cycles value.
Definition stk_common.h:165
Word TId
Task (thread) id.
Definition stk_common.h:145
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:170
RAII instance that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:386
Interface for a stack memory region.
Definition stk_common.h:401
Wait object.
Definition stk_common.h:444
DLHeadType ListHeadType
List head type for IWaitObject elements.
Definition stk_common.h:449
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:544
virtual bool Tick(Timeout elapsed_ticks)
Called by kernel on every system tick to handle timeout logic of waiting tasks.
Definition stk_helper.h:299
static void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
Called by kernel when a new task starts waiting on this event.
Definition stk_common.h:563
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:579
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:334
Interface for a user task.
Definition stk_common.h:734
virtual Weight GetWeight() const
Get static base weight of the task.
Definition stk_common.h:834
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 hardware access mode of the user task.
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 hardware access mode of the user task.
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:217
~StackMemoryWrapper()=default
Destructor.
const Word * GetStack() const override
Get pointer to the first element of the wrapped stack array.
Definition stk_helper.h:213
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:285
SyncObjectBase()
Constructor.
Definition stk_helper.h:272
void RemoveWaitObject(IWaitObject *wobj) override
Called by kernel when a waiting task is being removed (timeout expired, wait aborted,...
Definition stk_helper.h:258
IWaitObject::ListHeadType m_wait_list
Tasks blocked on this object.
Definition stk_helper.h:295
void WakeOne() override
Wake the first task in the wait list (FIFO order).
Definition stk_helper.h:280
const IWaitObject::ListHeadType & GetWaitList() const override
Get list of tasks blocked on this object.
Definition stk_helper.h:263
IWaitObject::ListHeadType & GetWaitList() override
Get list of tasks blocked on this object.
Definition stk_helper.h:290
friend class IKernelService
Definition stk_helper.h:250
void AddWaitObject(IWaitObject *wobj) override
Called by kernel when a new task starts waiting on this event.
Definition stk_helper.h:253
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.