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 size_t GetStackSizeBytes() const override { return _StackSize * sizeof(Word); }
57 EAccessMode GetAccessMode() const override { return _AccessMode; }
58
59protected:
61
70 {}
71
75 STK_VIRT_DTOR ~Task() = default;
76
77private:
79};
80
95template <Weight _Weight, size_t _StackSize, EAccessMode _AccessMode>
96class TaskW : public ITask
97{
98public:
99 enum { STACK_SIZE = _StackSize };
100
101 const Word *GetStack() const override { return const_cast<Word *>(m_stack); }
102 size_t GetStackSize() const override { return _StackSize; }
103 size_t GetStackSizeBytes() const override { return _StackSize * sizeof(Word); }
104 EAccessMode GetAccessMode() const override { return _AccessMode; }
105 Weight GetWeight() const override { return _Weight; }
106
107protected:
109
117 TaskW() : m_stack() {}
118
123
124private:
126};
127
135template <size_t _StackSize>
137{
138public:
143
149 explicit StackMemoryWrapper(MemoryType *stack) : m_stack(stack)
150 {
151 STK_STATIC_ASSERT(_StackSize >= STACK_SIZE_MIN);
152 }
153
158
161 const Word *GetStack() const override { return (*m_stack); }
162
165 size_t GetStackSize() const override { return _StackSize; }
166
169 size_t GetStackSizeBytes() const override { return (_StackSize * sizeof(Word)); }
170
171private:
173};
174
175// Helper function for Kernel::UpdateTaskState.
176template <bool TicklessMode> inline Timeout GetInitialSleepTicks();
178template <> inline Timeout GetInitialSleepTicks<false>() { return 1; }
179
181inline bool ISyncObject::Tick(Timeout elapsed_ticks)
182{
183 // note: ScopedCriticalSection usage
184 //
185 // Single-core: no critical section needed - Tick() runs inside the
186 // SysTick ISR which already executes with interrupts disabled, making
187 // re-entrancy impossible on the local core.
188 //
189 // Multi-core: critical section is required because the tick handler on
190 // each core may call Tick() concurrently for the same Semaphore instance,
191 // and ISyncObject::Tick() is not re-entrant.
192#if (STK_ARCH_CPU_COUNT > 1)
194#endif
195
197
198 while (itr != nullptr)
199 {
201
202 if (!itr->Tick(elapsed_ticks))
203 {
204 itr->Wake(true);
205 }
206
207 itr = next;
208 }
209
210 return !m_wait_list.IsEmpty();
211}
212
215{
216 Weight max_weight = NO_WEIGHT;
218
219 while (itr != nullptr)
220 {
221 const Weight w = GetUserTaskFromTid(itr->GetTid())->GetWeight();
222 if (w > max_weight)
223 {
224 max_weight = w;
225 }
226
228 }
229
230 return ((max_weight > comp) ? max_weight : NO_WEIGHT);
231}
232
234inline TId ITask::GetId() const
235{
236 return GetTidFromUserTask(this);
237}
238
247
257
264static __stk_forceinline Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
265{
266 return static_cast<Time>((tick_count * static_cast<Time>(resolution)) / 1000LL);
267}
268
275static __stk_forceinline Ticks GetTicksFromMs(Time ms, uint32_t resolution)
276{
277 Ticks tick_count = 0LL;
278
279 if (resolution != 0U)
280 {
281 tick_count = static_cast<Ticks>((ms * 1000LL) / static_cast<Time>(resolution));
282 }
283
284 return tick_count;
285}
286
298
305{
306 const Time time_ms = static_cast<Time>(ms);
307 const Ticks tick_count = GetTicksFromMs(time_ms);
308
309 const Ticks final_ticks = (tick_count < static_cast<Ticks>(WAIT_INFINITE)) ?
310 tick_count : static_cast<Ticks>(WAIT_INFINITE);
311
312 return static_cast<Timeout>(final_ticks);
313}
314
323
331{
332 const IKernelService *const service = IKernelService::GetInstance();
333 const uint32_t resolution = service->GetTickResolution();
334 const Ticks tick_count = service->GetTicks();
335
336 return ((resolution == 1000U) ? tick_count :
337 ((tick_count * static_cast<Ticks>(resolution)) / 1000LL));
338}
339
348
357
364static __stk_forceinline void Sleep(Timeout tick_count)
365{
366 IKernelService::GetInstance()->Sleep(tick_count);
367}
368
381
389static __stk_forceinline bool SleepUntil(Ticks timestamp)
390{
391 return IKernelService::GetInstance()->SleepUntil(timestamp);
392}
393
400{
402}
403
412
419static __stk_forceinline void Delay(Timeout tick_count)
420{
421 IKernelService::GetInstance()->Delay(tick_count);
422}
423
434
435} // namespace stk
436
437#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:115
static Time GetMsFromTicks(Ticks tick_count, uint32_t resolution)
Convert ticks to milliseconds.
Definition stk_helper.h:264
static void Yield()
Notify scheduler to switch to the next runnable task.
Definition stk_helper.h:408
static void Sleep(Timeout tick_count)
Put calling process into a sleep state.
Definition stk_helper.h:364
static void SleepCancel(TId task_id)
Cancel sleep of the task.
Definition stk_helper.h:399
static void SleepMs(Timeout ms)
Put calling process into a sleep state.
Definition stk_helper.h:377
EAccessMode
Hardware access mode by the user task.
Definition stk_common.h:32
static constexpr ITask * GetUserTaskFromTid(TId task_id) noexcept
Get task instance from its identifier.
Definition stk_arch.h:526
static Time GetTimeNowMs()
Get current time in milliseconds since kernel start.
Definition stk_helper.h:330
int64_t Ticks
Ticks value.
Definition stk_common.h:130
static void DelayMs(Timeout ms)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:430
int32_t Timeout
Timeout time (ticks).
Definition stk_common.h:125
static bool SleepUntil(Ticks timestamp)
Put calling process into a sleep state until the specified timestamp.
Definition stk_helper.h:389
int64_t Time
Time value.
Definition stk_common.h:135
static Ticks GetTicksFromMs(Time ms, uint32_t resolution)
Convert milliseconds to ticks.
Definition stk_helper.h:275
static uint32_t GetTickResolution()
Get number of microseconds in one tick.
Definition stk_helper.h:253
static uint32_t GetSysTimerFrequency()
Get system timer frequency.
Definition stk_helper.h:353
static void Delay(Timeout tick_count)
Delay calling process by busy-waiting until the deadline expires.
Definition stk_helper.h:419
constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:194
static Ticks GetTicks()
Get number of ticks elapsed since kernel start.
Definition stk_helper.h:319
@ 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:85
Timeout GetInitialSleepTicks()
constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:183
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:243
Timeout GetInitialSleepTicks< false >()
Definition stk_helper.h:178
static Timeout GetTicksFromMsClampedToTimeout(Timeout ms)
Convert milliseconds to ticks and clamp the result to a Timeout type.
Definition stk_helper.h:304
static constexpr TId GetTidFromUserTask(const ITask *task) noexcept
Get task identifier from ITask instance.
Definition stk_arch.h:520
Timeout GetInitialSleepTicks< true >()
Definition stk_helper.h:177
static Cycles GetSysTimerCount()
Get system timer count value.
Definition stk_helper.h:344
uint64_t Cycles
Cycles value.
Definition stk_common.h:140
Word TId
Task (thread) id.
Definition stk_common.h:120
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:145
RAII guard that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:240
Word Type[TStackSize]
Stack memory type.
Definition stk_common.h:274
Interface for a stack memory region.
Definition stk_common.h:298
Wait object.
Definition stk_common.h:345
virtual TId GetTid() const =0
Get thread Id of this task.
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:534
virtual bool Tick(Timeout elapsed_ticks)
Called by kernel on every system tick to handle timeout logic of waiting tasks.
Definition stk_helper.h:181
Weight FindWeightHigherThan(Weight comp) const
Find higher weight within linked wait objects.
Definition stk_helper.h:214
Interface for a user task.
Definition stk_common.h:599
virtual Weight GetWeight() const
Get static base weight of the task.
Definition stk_common.h:645
TId GetId() const
Get task Id set by application.
Definition stk_helper.h:234
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:69
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
size_t GetStackSizeBytes() const override
Get size of the memory in bytes.
Definition stk_helper.h:56
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:78
EAccessMode GetAccessMode() const override
Get hardware access mode of the user task.
Definition stk_helper.h:57
size_t GetStackSizeBytes() const override
Get size of the memory in bytes.
Definition stk_helper.h:103
Weight GetWeight() const override
Get static base weight of the task.
Definition stk_helper.h:105
TaskW(const TaskW &)=delete
const Word * GetStack() const override
Get pointer to the stack memory.
Definition stk_helper.h:101
~TaskW()=default
Destructor.
EAccessMode GetAccessMode() const override
Get hardware access mode of the user task.
Definition stk_helper.h:104
size_t GetStackSize() const override
Get number of elements of the stack memory array.
Definition stk_helper.h:102
TaskW()
Initializes task instance and zero-initializes its internal stack memory.
Definition stk_helper.h:117
StackMemoryDef< _StackSize >::Type m_stack
Stack memory region, 16-byte aligned.
Definition stk_helper.h:125
size_t GetStackSize() const override
Get number of elements in the wrapped stack array.
Definition stk_helper.h:165
~StackMemoryWrapper()=default
Destructor.
const Word * GetStack() const override
Get pointer to the first element of the wrapped stack array.
Definition stk_helper.h:161
StackMemoryDef< _StackSize >::Type MemoryType
Definition stk_helper.h:142
StackMemoryWrapper(MemoryType *stack)
Construct a wrapper around an existing stack memory array.
Definition stk_helper.h:149
size_t GetStackSizeBytes() const override
Get size of the wrapped stack array in bytes.
Definition stk_helper.h:169
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.