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::hw Namespace Reference

Hardware Abstraction Layer (HAL) for architecture-specific operations. More...

Namespaces

namespace  detail

Classes

struct  ExceptionFrame
 ARMv7-M/ARMv8-M hardware exception frame (8 words, highest address on the stack). More...
class  CriticalSection
 Nestable, SMP-safe critical section that combines local interrupt masking with a global cross-core spinlock. More...
class  SpinLock
 Atomic busy-wait lock used as the global cross-core synchronisation primitive inside CriticalSection. More...
class  HiResClock
 High-resolution clock for high-precision measurements. More...

Functions

template<typename T>
static Word PtrToWord (T *const ptr) noexcept
 Cast a pointer to a CPU register-width integer.
template<typename T>
static T * WordToPtr (Word value) noexcept
 Cast a CPU register-width integer back to a pointer.
bool IsInsideISR ()
 Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
bool IsPrivilegedContext ()
 Check if caller context is Privileged.
template<typename T>
T ReadVolatile64 (volatile const T *addr)
 Atomically read a 64-bit volatile value.
template<typename T>
void WriteVolatile64 (volatile T *addr, T value)
 Atomically write a 64-bit volatile value.

Detailed Description

Hardware Abstraction Layer (HAL) for architecture-specific operations.

This namespace contains low-level functions that interface directly with the CPU registers and hardware state. Implementations live in the architecture back-end headers included above and are typically written in assembly or using compiler intrinsics for maximum performance and minimum latency.

See also
IsInsideISR, GetTlsPtr, SetTlsPtr, CriticalSection, SpinLock, ReadVolatile64, WriteVolatile64, HiResClock

Function Documentation

◆ IsInsideISR()

bool stk::hw::IsInsideISR ( )

Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).

Returns
true if called from an ISR context; false if called from a normal task/thread context.
Note
Used as a guard in all ISR-unsafe kernel functions (Sleep, Delay, Yield, GetTid, etc.) to catch accidental calls from interrupt context that would deadlock the scheduler.
ISR-safe itself: may be called from any context.

Referenced by stk::time::TimerHost::CanWait(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::Delay(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::ExitTask(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::SetSchedulerLock(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::Sleep(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::SleepUntil(), stk_blockpool_alloc(), stk_bytepool_alloc(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::SuspendTask(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::SwitchToNext(), stk::sync::EventFlagsT< T >::Sync(), stk::memory::BlockMemoryPool::TimedAllocEx(), stk::memory::BytePool::TimedAllocEx(), stk::sync::FastMutex::TimedLockEx(), stk::sync::Mutex::TimedLockEx(), stk::sync::SpinLock::Unlock(), stk::sync::EventFlagsT< T >::Wait(), stk::sync::Barrier::WaitEx(), stk::sync::ConditionVariable::WaitEx(), stk::sync::Event::WaitEx(), stk::sync::EventFlagsT< T >::WaitEx(), and stk::sync::SemaphoreT< T >::WaitEx().

Here is the caller graph for this function:

◆ IsPrivilegedContext()

bool stk::hw::IsPrivilegedContext ( )

Check if caller context is Privileged.

Returns
true if Privileged; false otherwise.
Note
ISR-safe itself: may be called from any context.
Examples
blinky-trustzone-sc/example.cpp, and blinky_mpu-trustzone-sc/example.cpp.

References __stk_forceinline.

Referenced by NSC_bsp_Led_SwitchOnExclusive(), and stk_critical_section_enter().

Here is the caller graph for this function:

◆ PtrToWord()

template<typename T>
Word stk::hw::PtrToWord ( T *const ptr)
inlinestaticnoexcept

Cast a pointer to a CPU register-width integer.

Template Parameters
TThe type of the object pointed to.
Parameters
[in]ptrThe pointer to be converted.
Returns
The numeric value of the pointer as a Word.
Note
This operation is used to store pointers within task context structures or stack frames where raw register values are required.
MISRA deviation: [STK-DEV-001] Rule 5-2-7 (reinterpret_cast). This is a mechanical necessity for low-level kernel operations where the hardware requires integral values for address registers.
See also
WordToPtr
Examples
blinky_mpu-hard/example.cpp, blinky_mpu-trustzone-ns/example.cpp, and blinky_mpu/example.cpp.

Definition at line 215 of file stk_arch.h.

216{
217 STK_STATIC_ASSERT(sizeof(Word) == sizeof(T *));
218 return reinterpret_cast<Word>(ptr);
219}
#define STK_STATIC_ASSERT(X)
Compile-time assertion. Produces a compilation error if X is false.
Definition stk_defs.h:560
uintptr_t Word
Native processor word type.
Definition stk_common.h:206

References __stk_forceinline, and STK_STATIC_ASSERT.

Referenced by stk::memory::MemoryAllocator::AllocateAligned(), stk::memory::BlockMemoryPool::BuildFreeList(), stk::memory::BlockMemoryPool::Free(), stk::memory::BytePool::Free(), stk::memory::MemoryAllocator::FreeAligned(), GetGlobalMpuRegions(), NonSecureLedTask< _AccessMode >::GetMpuRegions(), stk::memory::MemoryAllocator::GetStats(), stk::GetTidFromUserTask(), stk::memory::BytePool::Init(), stk::PlatformContext::InitStackMemory(), stk::memory::MemoryAllocator::IsAvailable(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::IsMemoryOfSP(), MyTask< _AccessMode >::MyTask(), PlatformEventHandler::OnConfigureMpu(), stk::memory::BlockMemoryPool::PopFreeList(), ReadVolatile64(), SecureHwCommandQueueTask< _AccessMode >::SecureHwCommandQueueTask(), stk::memory::BlockMemoryPool::Setup(), stk::STK_MEMCPY(), stk::STK_MEMSET(), and WriteVolatile64().

Here is the caller graph for this function:

◆ ReadVolatile64()

template<typename T>
T stk::hw::ReadVolatile64 ( volatile const T * addr)
inline

Atomically read a 64-bit volatile value.

Template Parameters
TMust be exactly 8 bytes wide and at least 4-byte aligned (enforced by static assertions).
Parameters
[in]addrPointer to the volatile 64-bit memory location.
Returns
Consistent 64-bit snapshot of the value at addr.
Note
On 64-bit architectures a single aligned load is inherently atomic, the value is read directly with no additional protocol.
On 32-bit architectures uses a lock-free hi-lo retry protocol compatible with WriteVolatile64: reads the high half, then the low half, then re-reads the high half. If the high half changed between the first and second read, a tick occurred between the two 32-bit loads and the pair is retried until a consistent snapshot is obtained. Requires that WriteVolatile64 writes hi before lo (which it does).
Requires a single writer that uses WriteVolatile64. Safe with multiple concurrent readers. Not C++ memory-model compliant, intended for bare-metal embedded use only.
MISRA deviation: [STK-DEV-002] Rule 5-2-7, 5-0-15. Required for lock-free 64-bit I/O on 32-bit architectures using a Hi-Lo retry protocol.
Warning
Not safe for read-modify-write operations. Use only for polling a value written atomically by a single producer.
See also
WriteVolatile64

Definition at line 332 of file stk_arch.h.

333{
334 STK_STATIC_ASSERT_N(sz, sizeof(T) == 8U); // only 64-bit types permitted
335 STK_STATIC_ASSERT_N(al, alignof(T) >= 4U); // type must be at least 4-byte aligned
338
339 if __stk_constexpr_cpp17 (sizeof(void *) == 8U) // 64-bit arch: aligned 64-bit load is inherently atomic
340 {
341 return (*addr);
342 }
343 else
344 {
345 // 32-bit arch: split the 64-bit address into two 32-bit halves;
346 // writer always updates hi before lo (see WriteVolatile64), so if hi is
347 // the same before and after reading lo, no write straddled the two reads.
348 #if STK_STRICT_COMPLIANCY
349 const Word p_base = hw::PtrToWord(addr);
350 volatile const uint32_t *const plo = hw::WordToPtr<uint32_t>(p_base + (STK_ENDIAN_IDX_LO * sizeof(uint32_t)));
351 volatile const uint32_t *const phi = hw::WordToPtr<uint32_t>(p_base + (STK_ENDIAN_IDX_HI * sizeof(uint32_t)));
352 #else
353 volatile const uint32_t *const p_base = reinterpret_cast<volatile const uint32_t *>(addr);
354 volatile const uint32_t *const plo = &p_base[STK_ENDIAN_IDX_LO];
355 volatile const uint32_t *const phi = &p_base[STK_ENDIAN_IDX_HI];
356 #endif
357
358 uint32_t hi, lo;
359 do
360 {
361 hi = (*phi);
362 __stk_full_memfence();
363
364 lo = (*plo);
365 __stk_full_memfence();
366 }
367 while (hi != (*phi)); // hi changed: a write occurred during the read; retry
368
369 const uint64_t result = (static_cast<uint64_t>(hi) << 32U) | static_cast<uint64_t>(lo);
370
371 return static_cast<T>(result);
372 }
373}
#define STK_STATIC_ASSERT_N(NAME, X)
Compile-time assertion with a name tag (documentation only, see STK_STATIC_ASSERT_DESC_N).
Definition stk_defs.h:555
#define STK_ENDIAN_IDX_LO
Array index of the low 32-bit word when a 64-bit value is viewed as uint32_t[2].
Definition stk_defs.h:700
#define STK_ENDIAN_IDX_HI
Array index of the high 32-bit word when a 64-bit value is viewed as uint32_t[2].
Definition stk_defs.h:699
#define __stk_constexpr_cpp17
constexpr definition for C++17 and above.
Definition stk_defs.h:505
static T * WordToPtr(Word value) noexcept
Cast a CPU register-width integer back to a pointer.
Definition stk_arch.h:232
static Word PtrToWord(T *const ptr) noexcept
Cast a pointer to a CPU register-width integer.
Definition stk_arch.h:215

References __stk_constexpr_cpp17, __stk_forceinline, PtrToWord(), STK_ENDIAN_IDX_HI, STK_ENDIAN_IDX_LO, STK_STATIC_ASSERT_N, and WordToPtr().

Referenced by stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::GetTicks(), and stk::time::TimerHost::GetTimeNow().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ WordToPtr()

template<typename T>
T * stk::hw::WordToPtr ( Word value)
inlinestaticnoexcept

Cast a CPU register-width integer back to a pointer.

Template Parameters
TThe type of the object the resulting pointer will address.
Parameters
[in]valueThe register-width integer (Word) to be converted.
Returns
A pointer of type T* addressing the memory location specified by the value.
Note
This is the inverse of PtrToWord and is primarily used when restoring a task's context from a saved stack frame.
MISRA deviation: [STK-DEV-001] Rule 5-2-7 (reinterpret_cast). Required for restoring pointer types from numeric CPU context structures.
See also
PtrToWord

Definition at line 232 of file stk_arch.h.

233{
234 STK_STATIC_ASSERT(sizeof(Word) == sizeof(T *));
235 return reinterpret_cast<T *>(value);
236}

References __stk_forceinline, and STK_STATIC_ASSERT.

Referenced by stk::memory::MemoryAllocator::AllocateAligned(), stk::memory::BlockMemoryPool::BuildFreeList(), stk::memory::MemoryAllocator::FreeAligned(), stk::GetUserTaskFromTid(), stk::memory::BytePool::Init(), ReadVolatile64(), and WriteVolatile64().

Here is the caller graph for this function:

◆ WriteVolatile64()

template<typename T>
void stk::hw::WriteVolatile64 ( volatile T * addr,
T value )
inline

Atomically write a 64-bit volatile value.

Template Parameters
TMust be exactly 8 bytes wide and at least 4-byte aligned (enforced by static assertions).
Parameters
[in]addrPointer to the volatile 64-bit memory location.
[in]valueValue to write.
Note
On 64-bit architectures a single aligned store is inherently atomic.
On 32-bit architectures the value is split into two 32-bit half-writes. The high half is always written before the low half. This ordering is the contractual invariant that ReadVolatile64 depends on to detect a mid-write tear: if a reader observes a changed high half, it knows a write occurred and retries. Breaking this order (writing lo before hi) will corrupt concurrent reads.
A full memory fence is emitted between the two half-writes to prevent the CPU from reordering the stores.
ISR-safe: does not use a critical section.
MISRA deviation: [STK-DEV-002] Rule 5-2-7, 5-0-15. Required for lock-free 64-bit I/O on 32-bit architectures using a Hi-Lo retry protocol.
Warning
Supports only a single writer at a time. Concurrent writers on the same address will corrupt the value. Not safe for read-modify-write operations (e.g. increment); the caller must ensure exclusive write access by other means.
Not C++ memory-model compliant; intended for bare-metal embedded use only.
See also
ReadVolatile64

Definition at line 397 of file stk_arch.h.

398{
399 STK_STATIC_ASSERT_N(sz, sizeof(T) == 8U); // only 64-bit types permitted
400 STK_STATIC_ASSERT_N(al, alignof(T) >= 4U); // type must be at least 4-byte aligned
403
404 if __stk_constexpr_cpp17 (sizeof(void *) == 8U) // 64-bit arch: aligned 64-bit store is inherently atomic
405 {
406 (*addr) = value;
407 }
408 else
409 {
410 #if STK_STRICT_COMPLIANCY
411 const Word p_base = hw::PtrToWord(addr);
412 volatile uint32_t *const plo = hw::WordToPtr<uint32_t>(p_base + (STK_ENDIAN_IDX_LO * sizeof(uint32_t)));
413 volatile uint32_t *const phi = hw::WordToPtr<uint32_t>(p_base + (STK_ENDIAN_IDX_HI * sizeof(uint32_t)));
414 #else
415 volatile uint32_t *const p_base = reinterpret_cast<volatile uint32_t *>(addr);
416 volatile uint32_t *const plo = &p_base[STK_ENDIAN_IDX_LO];
417 volatile uint32_t *const phi = &p_base[STK_ENDIAN_IDX_HI];
418 #endif
419
420 // write hi first: ReadVolatile64 reads hi twice and retries if it changed,
421 // so writing hi before lo ensures readers can detect a torn write.
422 (*phi) = static_cast<uint32_t>(static_cast<uint64_t>(value) >> 32U);
423 __stk_full_memfence();
424
425 (*plo) = static_cast<uint32_t>(value);
426 }
427}

References __stk_constexpr_cpp17, __stk_forceinline, PtrToWord(), STK_ENDIAN_IDX_HI, STK_ENDIAN_IDX_LO, STK_STATIC_ASSERT_N, and WordToPtr().

Referenced by stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelService::IncrementTicks(), and stk::time::TimerHost::ScanTimers().

Here is the call graph for this function:
Here is the caller graph for this function: