SuperTinyKernel™ RTOS 1.06.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
19
20namespace stk {
21
48template <size_t _StackSize, EAccessMode _AccessMode>
49class Task : public ITask
50{
51public:
52 enum { STACK_SIZE = _StackSize };
53
54 const Word *GetStack() const override { return const_cast<Word *>(m_stack); }
55 size_t GetStackSize() const override { return _StackSize; }
56 EAccessMode GetAccessMode() const override { return _AccessMode; }
57
58protected:
60
69 {}
70
74 STK_VIRT_DTOR ~Task() = default;
75
76private:
78};
79
94template <Weight _Weight, size_t _StackSize, EAccessMode _AccessMode>
95class TaskW : public ITask
96{
97public:
98 enum { STACK_SIZE = _StackSize };
99
100 const Word *GetStack() const override { return const_cast<Word *>(m_stack); }
101 size_t GetStackSize() const override { return _StackSize; }
102 EAccessMode GetAccessMode() const override { return _AccessMode; }
103 Weight GetWeight() const override { return _Weight; }
104
105protected:
107
115 TaskW() : m_stack() {}
116
121
122private:
124};
125
133template <size_t _StackSize>
135{
136public:
141
147 explicit StackMemoryWrapper(MemoryType *stack) : m_stack(stack)
148 {
149 STK_STATIC_ASSERT(_StackSize >= STACK_SIZE_MIN);
150 }
151
156
159 const Word *GetStack() const override { return (*m_stack); }
160
163 size_t GetStackSize() const override { return _StackSize; }
164
165private:
167};
168
169// Helper function for Kernel::UpdateTaskState.
170template <bool TicklessMode> inline Timeout GetInitialSleepTicks();
172template <> inline Timeout GetInitialSleepTicks<false>() { return 1; }
173
175inline bool ISyncObject::Tick(Timeout elapsed_ticks)
176{
177 // note: ScopedCriticalSection usage
178 //
179 // Single-core: no critical section needed - Tick() runs inside the
180 // SysTick ISR which already executes with interrupts disabled, making
181 // re-entrancy impossible on the local core.
182 //
183 // Multi-core: critical section is required because the tick handler on
184 // each core may call Tick() concurrently for the same Semaphore instance,
185 // and ISyncObject::Tick() is not re-entrant.
186#if (STK_ARCH_CPU_COUNT > 1)
188#endif
189
191
192 while (itr != nullptr)
193 {
195
196 if (!itr->Tick(elapsed_ticks))
197 {
198 itr->Wake(true);
199 }
200
201 itr = next;
202 }
203
204 return !m_wait_list.IsEmpty();
205}
206
209{
210 Weight max_weight = NO_WEIGHT;
212
213 while (itr != nullptr)
214 {
215 const Weight w = GetUserTaskFromTid(itr->GetTid())->GetWeight();
216 if (w > max_weight)
217 {
218 max_weight = w;
219 }
220
222 }
223
224 return ((max_weight > comp) ? max_weight : NO_WEIGHT);
225}
226
228inline TId ITask::GetId() const
229{
230 return GetTidFromUserTask(this);
231}
232
241
251
258static __stk_forceinline Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
259{
260 return static_cast<Time>((tick_count * static_cast<Time>(resolution)) / 1000LL);
261}
262
269static __stk_forceinline Ticks GetTicksFromMs(Time ms, uint32_t resolution)
270{
271 Ticks tick_count = 0LL;
272
273 if (resolution != 0U)
274 {
275 tick_count = static_cast<Ticks>((ms * 1000LL) / static_cast<Time>(resolution));
276 }
277
278 return tick_count;
279}
280
292
299{
300 const Time time_ms = static_cast<Time>(ms);
301 const Ticks tick_count = GetTicksFromMs(time_ms);
302
303 const Ticks final_ticks = (tick_count < static_cast<Ticks>(WAIT_INFINITE)) ?
304 tick_count : static_cast<Ticks>(WAIT_INFINITE);
305
306 return static_cast<Timeout>(final_ticks);
307}
308
317
325{
326 const IKernelService *const service = IKernelService::GetInstance();
327 const uint32_t resolution = service->GetTickResolution();
328 const Ticks tick_count = service->GetTicks();
329
330 return ((resolution == 1000U) ? tick_count :
331 ((tick_count * static_cast<Ticks>(resolution)) / 1000LL));
332}
333
342
351
358static __stk_forceinline void Sleep(Timeout tick_count)
359{
360 IKernelService::GetInstance()->Sleep(tick_count);
361}
362
375
383static __stk_forceinline bool SleepUntil(Ticks timestamp)
384{
385 return IKernelService::GetInstance()->SleepUntil(timestamp);
386}
387
394{
396}
397
406
413static __stk_forceinline void Delay(Timeout tick_count)
414{
415 IKernelService::GetInstance()->Delay(tick_count);
416}
417
428
429} // namespace stk
430
431#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:175
#define STK_NONCOPYABLE_CLASS(TYPE)
Disables copy construction and assignment for a class.
Definition stk_defs.h:601
#define STK_TICKLESS_TICKS_MAX
Maximum number of kernel ticks the hardware timer may be suppressed in one tickless idle interval whe...
Definition stk_defs.h:77
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:446
#define STK_VIRT_DTOR
Makes destructors virtual and compliant to strict rules if STK_STRICT_COMPLIANCY=0.
Definition stk_defs.h:159
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:136
static Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
Convert ticks to milliseconds.
Definition stk_helper.h:258
static void Yield()
Notify scheduler to switch to the next runnable task.
Definition stk_helper.h:402
static void Sleep(Timeout tick_count)
Put calling process into a sleep state.
Definition stk_helper.h:358
static void SleepCancel(TId task_id)
Cancel sleep of the task.
Definition stk_helper.h:393
static void SleepMs(Timeout ms)
Put calling process into a sleep state.
Definition stk_helper.h:371
EAccessMode
Hardware access modes by the task.
Definition stk_common.h:42
static constexpr ITask * GetUserTaskFromTid(TId task_id) noexcept
Get task instance from its identifier.
Definition stk_arch.h:532
static Time GetTimeNowMs()
Get current time in milliseconds since kernel start.
Definition stk_helper.h:324
int64_t Ticks
Ticks value.
Definition stk_common.h:151
static void DelayMs(Timeout ms)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:424
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:146
static bool SleepUntil(Ticks timestamp)
Put calling process into a sleep state until the specified timestamp.
Definition stk_helper.h:383
int64_t Time
Time value.
Definition stk_common.h:156
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:269
static uint32_t GetTickResolution()
Get number of microseconds in one tick.
Definition stk_helper.h:247
static uint32_t GetSysTimerFrequency()
Get system timer frequency.
Definition stk_helper.h:347
static void Delay(Timeout tick_count)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:413
constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:215
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:313
@ 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:96
Timeout GetInitialSleepTicks()
constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:204
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:237
Timeout GetInitialSleepTicks< false >()
Definition stk_helper.h:172
static Timeout GetTicksFromMsClampedToTimeout(Timeout ms)
Convert milliseconds to ticks and clamp the result to a Timeout type.
Definition stk_helper.h:298
static constexpr TId GetTidFromUserTask(const ITask *task) noexcept
Get task identifier from ITask instance.
Definition stk_arch.h:526
Timeout GetInitialSleepTicks< true >()
Definition stk_helper.h:171
static Cycles GetSysTimerCount()
Get system timer count value.
Definition stk_helper.h:338
uint64_t Cycles
Cycles value.
Definition stk_common.h:161
Word TId
Task (thread) id.
Definition stk_common.h:141
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:166
RAII guard that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:363
Word Type[TStackSize]
Stack memory type.
Definition stk_common.h:295
Interface for a stack memory region.
Definition stk_common.h:319
Wait object.
Definition stk_common.h:362
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.
IWaitObject::ListHeadType m_wait_list
tasks blocked on this object
Definition stk_common.h:605
virtual bool Tick(Timeout elapsed_ticks)
Called by kernel on every system tick to handle timeout logic of waiting tasks.
Definition stk_helper.h:175
Weight FindWeightHigherThan(Weight comp) const
Find higher weight within linked wait objects.
Definition stk_helper.h:208
Interface for a user task.
Definition stk_common.h:670
virtual Weight GetWeight() const
Get static base weight of the task.
Definition stk_common.h:722
TId GetId() const
Get task Id set by application.
Definition stk_helper.h:228
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 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.
Task()
Initializes task instance and zero-initializes its internal stack memory.
Definition stk_helper.h:68
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:55
const Word * GetStack() const override
Get pointer to the stack memory.
Definition stk_helper.h:54
StackMemoryDef< _StackSize >::Type m_stack
Stack memory region, 16-byte aligned.
Definition stk_helper.h:77
EAccessMode GetAccessMode() const override
Get hardware access mode of the user task.
Definition stk_helper.h:56
Weight GetWeight() const override
Get static base weight of the task.
Definition stk_helper.h:103
TaskW(const TaskW &)=delete
const Word * GetStack() const override
Get pointer to the stack memory.
Definition stk_helper.h:100
~TaskW()=default
Destructor.
EAccessMode GetAccessMode() const override
Get hardware access mode of the user task.
Definition stk_helper.h:102
size_t GetStackSize() const override
Get number of elements of the stack memory array.
Definition stk_helper.h:101
TaskW()
Initializes task instance and zero-initializes its internal stack memory.
Definition stk_helper.h:115
StackMemoryDef< _StackSize >::Type m_stack
Stack memory region, 16-byte aligned.
Definition stk_helper.h:123
size_t GetStackSize() const override
Get number of elements in the wrapped stack array.
Definition stk_helper.h:163
~StackMemoryWrapper()=default
Destructor.
const Word * GetStack() const override
Get pointer to the first element of the wrapped stack array.
Definition stk_helper.h:159
StackMemoryDef< _StackSize >::Type MemoryType
Definition stk_helper.h:140
StackMemoryWrapper(MemoryType *stack)
Construct a wrapper around an existing stack memory array.
Definition stk_helper.h:147
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.