SuperTinyKernel™ RTOS 1.05.3
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
stk::memory Namespace Reference

Memory-related primitives. More...

Classes

struct  MemoryBlock
 Intrusive free-list node overlaid on the first word of every free block. More...

Functions

 BlockMemoryPool (size_t capacity, size_t raw_block_size, uint8_t *storage, size_t storage_size, const char *name=nullptr)
 Construct a pool backed by caller-supplied (external) storage.
 BlockMemoryPool (size_t capacity, size_t raw_block_size, const char *name=nullptr)
 Construct a pool with heap-allocated storage.
 ~BlockMemoryPool ()
 Destructor.
static constexpr size_t AlignBlockSize (size_t raw_size)
 Round a raw block size up to the nearest multiple of BLOCK_ALIGN.
void * TimedAlloc (Timeout timeout=WAIT_INFINITE)
 Allocate one block, blocking until one becomes available or the timeout expires.
template<typename T>
T * TimedAllocT (Timeout timeout=WAIT_INFINITE)
 Allocate one typed block, blocking until one becomes available or the timeout expires.
void * Alloc ()
 Allocate one block, blocking indefinitely until one is available.
template<typename T>
T * AllocT ()
 Allocate one typed block, blocking indefinitely until one is available.
void * TryAlloc ()
 Non-blocking allocation attempt.
template<typename T>
T * TryAllocT ()
 Non-blocking typed allocation attempt.
bool Free (void *ptr)
 Return a previously allocated block to the pool.
bool IsStorageValid () const
 Verify that the backing storage is valid and the pool is ready for use.
size_t GetCapacity () const
 Get the total block capacity of the pool.
size_t GetBlockSize () const
 Get the aligned block size used internally by the allocator.
size_t GetUsedCount () const
 Get the number of currently allocated (outstanding) blocks.
size_t GetFreeCount () const
 Get the number of free (available) blocks.
bool IsFull () const
 Check whether all blocks are currently allocated (pool exhausted).
bool IsEmpty () const
 Check whether all blocks are free (no outstanding allocations).
 STK_NONCOPYABLE_CLASS (BlockMemoryPool)
void BuildFreeList ()
 Initialise the intrusive free-list across m_storage.
void * PopFreeList ()
 Pop the head block from the free-list, increment m_used_count, and return it.

Variables

static const size_t CAPACITY_MAX = 0xFFFEU
static const uint32_t BLOCK_ALIGN = static_cast<uint32_t>(sizeof(MemoryBlock))
 Minimum block alignment in bytes: sizeof(MemoryBlock).
uint8_t * m_storage
 flat byte array holding all N blocks (owned or external)
MemoryBlockm_free_list
 head of the intrusive free-list (nullptr when pool is empty)
sync::ConditionVariable m_cv
 signalled by Free() to wake one task blocked in TimedAlloc()
size_t m_block_size
 aligned block size in bytes (>= BLOCK_ALIGN)
size_t m_capacity
 total number of blocks
uint16_t m_used_count
 number of blocks currently allocated (outstanding)
bool m_storage_owned
 true -> storage is heap-allocated; free in destructor

Detailed Description

Memory-related primitives.

Function Documentation

◆ AlignBlockSize()

constexpr size_t stk::memory::AlignBlockSize ( size_t raw_size)
staticconstexpr

Round a raw block size up to the nearest multiple of BLOCK_ALIGN.

Enforces a minimum of BLOCK_ALIGN so the free-list link always fits inside every free block without extra metadata.

Parameters
[in]raw_sizeRequested block size in bytes.
Returns
Aligned block size in bytes (>= BLOCK_ALIGN).
Note
Use this to compute the required external storage buffer size:
uint8_t buf[N * BlockMemoryPool::AlignBlockSize(sizeof(MyType))];

Definition at line 159 of file stk_memory_blockpool.h.

160 {
161 return Max(BLOCK_ALIGN, (raw_size + (BLOCK_ALIGN - 1U)) & ~(BLOCK_ALIGN - 1U));
162 }
static constexpr T Max(T a, T b)
Compile-time maximum of two values.
Definition stk_defs.h:541
static const uint32_t BLOCK_ALIGN
Minimum block alignment in bytes: sizeof(MemoryBlock).

References BLOCK_ALIGN, and stk::Max().

Here is the call graph for this function:

◆ Alloc()

void * stk::memory::Alloc ( )

Allocate one block, blocking indefinitely until one is available.

Returns
Pointer to an uninitialized block. Never returns nullptr.
Warning
ISR-unsafe.

◆ AllocT()

template<typename T>
T * stk::memory::AllocT ( )

Allocate one typed block, blocking indefinitely until one is available.

Returns
Typed pointer. Never returns nullptr.
Warning
ISR-unsafe.

◆ BlockMemoryPool() [1/2]

stk::memory::BlockMemoryPool ( size_t capacity,
size_t raw_block_size,
const char * name = nullptr )
explicit

Construct a pool with heap-allocated storage.

Allocates a flat byte buffer of capacity * AlignBlockSize(raw_block_size) bytes via operator new (std::nothrow). When exceptions are disabled (embedded default), check IsStorageValid() immediately after construction to detect allocation failure before first use.

Parameters
[in]capacityTotal number of blocks.
[in]raw_block_sizeRequested per-block size in bytes.
[in]nameOptional name forwarded to ITraceable::SetTraceName().
Note
Mirrors the heap-fallback path in osMemoryPoolNew().
ISR-unsafe.

◆ BlockMemoryPool() [2/2]

stk::memory::BlockMemoryPool ( size_t capacity,
size_t raw_block_size,
uint8_t * storage,
size_t storage_size,
const char * name = nullptr )
explicit

Construct a pool backed by caller-supplied (external) storage.

The pool references storage directly without taking ownership. The caller must keep the buffer alive for the entire lifetime of this object. The storage is not freed on destruction.

Parameters
[in]capacityTotal number of blocks the pool can hold.
[in]raw_block_sizeRequested per-block size in bytes. Rounded up internally to AlignBlockSize(raw_block_size).
[in]storagePointer to a caller-owned byte buffer. Must be aligned to at least sizeof(void*) and sized to hold at least capacity * AlignBlockSize(raw_block_size) bytes. Asserted at construction time.
[in]storage_sizeSize of storage in bytes (used for the size assertion).
[in]nameOptional name forwarded to ITraceable::SetTraceName().
Note
Mirrors the mp_mem / mp_size path in osMemoryPoolNew().
ISR-unsafe (must be called from task or init context).

Referenced by stk::test::blockpool::StorageModeTask< _AccessMode >::Run(), RunTest(), and STK_NONCOPYABLE_CLASS().

Here is the caller graph for this function:

◆ BuildFreeList()

void stk::memory::BuildFreeList ( )
private

Initialise the intrusive free-list across m_storage.

Links blocks in reverse order so after the loop m_free_list points to block_0 (lowest address), giving ascending allocation order. Each free block stores a pointer to the next free block in its own first sizeof(MemoryBlock) bytes - zero extra metadata.

◆ Free()

bool stk::memory::Free ( void * ptr)

Return a previously allocated block to the pool.

Pushes the block back onto the free-list head in O(1) and wakes exactly one task blocked inside Alloc() or TimedAlloc(), if any. The woken task is guaranteed to find a free block available.

Parameters
[in]ptrPointer previously returned by Alloc(), TimedAlloc(), or TryAlloc(). Must not be nullptr and must belong to this pool instance. Bounds and alignment are validated; failures trigger an assertion in debug builds and return false in release builds.
Returns
true - block successfully returned. false - ptr is nullptr, out of range, or misaligned; each case indicates a caller logic error.
Note
ISR-safe.
Warning
Double-free is not detected and will silently corrupt the free-list. Null the pointer after Free() to prevent this.

◆ GetBlockSize()

size_t stk::memory::GetBlockSize ( ) const

Get the aligned block size used internally by the allocator.

Equal to AlignBlockSize(raw_block_size) passed at construction. Always >= BLOCK_ALIGN. Matches osMemoryPoolGetBlockSize().

Returns
Aligned block size in bytes.
Note
ISR-safe.

Definition at line 255 of file stk_memory_blockpool.h.

255{ return m_block_size; }
size_t m_block_size
aligned block size in bytes (>= BLOCK_ALIGN)

References m_block_size.

◆ GetCapacity()

size_t stk::memory::GetCapacity ( ) const

Get the total block capacity of the pool.

Returns
Maximum number of blocks that can be simultaneously allocated. Matches osMemoryPoolGetCapacity().
Note
ISR-safe.

Definition at line 247 of file stk_memory_blockpool.h.

247{ return m_capacity; }
size_t m_capacity
total number of blocks

References m_capacity.

◆ GetFreeCount()

size_t stk::memory::GetFreeCount ( ) const

Get the number of free (available) blocks.

Returns
Point-in-time snapshot of GetCapacity() - GetUsedCount(). Matches osMemoryPoolGetSpace().
Note
ISR-safe.

Definition at line 269 of file stk_memory_blockpool.h.

269{ return (m_capacity - m_used_count); }
uint16_t m_used_count
number of blocks currently allocated (outstanding)

References m_capacity, and m_used_count.

Referenced by IsFull().

Here is the caller graph for this function:

◆ GetUsedCount()

size_t stk::memory::GetUsedCount ( ) const

Get the number of currently allocated (outstanding) blocks.

Returns
Point-in-time snapshot. Matches osMemoryPoolGetCount().
Note
May be stale immediately after return in a multi-task environment.
ISR-safe on targets where a 16-bit aligned read is a single instruction.

Definition at line 262 of file stk_memory_blockpool.h.

262{ return m_used_count; }

References m_used_count.

◆ IsEmpty()

bool stk::memory::IsEmpty ( ) const

Check whether all blocks are free (no outstanding allocations).

Returns
true if no blocks are currently allocated.
Note
ISR-safe.

Definition at line 281 of file stk_memory_blockpool.h.

281{ return (m_used_count == 0U); }

References m_used_count.

◆ IsFull()

bool stk::memory::IsFull ( ) const

Check whether all blocks are currently allocated (pool exhausted).

Returns
true if no blocks are available for allocation.
Note
ISR-safe.

Definition at line 275 of file stk_memory_blockpool.h.

275{ return (GetFreeCount() == 0U); }
size_t GetFreeCount() const
Get the number of free (available) blocks.

References GetFreeCount().

Here is the call graph for this function:

◆ IsStorageValid()

bool stk::memory::IsStorageValid ( ) const

Verify that the backing storage is valid and the pool is ready for use.

Always true for pools constructed with external storage. For heap-constructed pools, false if operator new failed. Must be checked after the heap constructor when operating without exceptions (the typical embedded configuration).

Returns
true if the pool is ready for use.
Note
ISR-safe.

Definition at line 240 of file stk_memory_blockpool.h.

240{ return (m_storage != nullptr); }
uint8_t * m_storage
flat byte array holding all N blocks (owned or external)

References m_storage.

◆ PopFreeList()

void * stk::memory::PopFreeList ( )
private

Pop the head block from the free-list, increment m_used_count, and return it.

Note
Caller must hold a critical section and ensure m_free_list != nullptr.

◆ STK_NONCOPYABLE_CLASS()

stk::memory::STK_NONCOPYABLE_CLASS ( BlockMemoryPool )
private

References BlockMemoryPool().

Here is the call graph for this function:

◆ TimedAlloc()

void * stk::memory::TimedAlloc ( Timeout timeout = WAIT_INFINITE)

Allocate one block, blocking until one becomes available or the timeout expires.

If the pool is empty the calling task is suspended via the internal ConditionVariable and woken by the next Free() call. On return the caller owns the block and must eventually return it via Free().

Parameters
[in]timeoutMaximum time to wait (ticks). WAIT_INFINITE - block indefinitely (default). NO_WAIT - return nullptr immediately if pool is empty (identical to TryAlloc(); ISR-safe).
Returns
Pointer to an uninitialized block of at least GetRawBlockSize() bytes, or nullptr if the timeout expired before a block became available.
Warning
ISR-safe only when timeout = NO_WAIT; ISR-unsafe otherwise.

References stk::WAIT_INFINITE.

◆ TimedAllocT()

template<typename T>
T * stk::memory::TimedAllocT ( Timeout timeout = WAIT_INFINITE)

Allocate one typed block, blocking until one becomes available or the timeout expires.

Thin typed wrapper around TimedAlloc(). Asserts that sizeof(T) fits within the aligned block size chosen at construction.

Parameters
[in]timeoutMaximum time to wait (ticks). Same semantics as TimedAlloc().
Returns
Typed pointer, or nullptr if the timeout expired.
Warning
ISR-safe only when timeout = NO_WAIT; ISR-unsafe otherwise.

References stk::WAIT_INFINITE.

◆ TryAlloc()

void * stk::memory::TryAlloc ( )

Non-blocking allocation attempt.

Returns a block immediately if the pool is not empty, or nullptr if all blocks are currently allocated. Never suspends the calling task.

Returns
Pointer to an uninitialized block, or nullptr if the pool is empty.
Note
ISR-safe.

◆ TryAllocT()

template<typename T>
T * stk::memory::TryAllocT ( )

Non-blocking typed allocation attempt.

Returns a typed pointer immediately if the pool is not empty, or nullptr if all blocks are currently allocated. Never suspends the calling task.

Returns
Typed pointer, or nullptr if the pool is empty.
Note
ISR-safe.

◆ ~BlockMemoryPool()

stk::memory::~BlockMemoryPool ( )

Destructor.

Frees heap-allocated storage if m_storage_owned is true. External storage is never touched.

Note
Destroying the pool while tasks are blocked in Alloc() or TimedAlloc() is a logical error (dangling waiters). An assertion is triggered in debug builds inside the ConditionVariable destructor.
MISRA deviation: [STK-DEV-005] Rule 10-3-2.

Variable Documentation

◆ BLOCK_ALIGN

const uint32_t stk::memory::BLOCK_ALIGN = static_cast<uint32_t>(sizeof(MemoryBlock))
staticprivate

Minimum block alignment in bytes: sizeof(MemoryBlock).

Ensures the intrusive free-list pointer stored in the first word of every free block is naturally aligned on all supported STK targets.

Definition at line 300 of file stk_memory_blockpool.h.

Referenced by AlignBlockSize().

◆ CAPACITY_MAX

const size_t stk::memory::CAPACITY_MAX = 0xFFFEU
static

Definition at line 104 of file stk_memory_blockpool.h.

◆ m_block_size

size_t stk::memory::m_block_size
private

aligned block size in bytes (>= BLOCK_ALIGN)

Definition at line 318 of file stk_memory_blockpool.h.

Referenced by GetBlockSize().

◆ m_capacity

size_t stk::memory::m_capacity
private

total number of blocks

Definition at line 319 of file stk_memory_blockpool.h.

Referenced by GetCapacity(), and GetFreeCount().

◆ m_cv

sync::ConditionVariable stk::memory::m_cv
private

signalled by Free() to wake one task blocked in TimedAlloc()

Definition at line 317 of file stk_memory_blockpool.h.

◆ m_free_list

MemoryBlock* stk::memory::m_free_list
private

head of the intrusive free-list (nullptr when pool is empty)

Definition at line 316 of file stk_memory_blockpool.h.

◆ m_storage

uint8_t* stk::memory::m_storage
private

flat byte array holding all N blocks (owned or external)

Definition at line 315 of file stk_memory_blockpool.h.

Referenced by IsStorageValid().

◆ m_storage_owned

bool stk::memory::m_storage_owned
private

true -> storage is heap-allocated; free in destructor

Definition at line 321 of file stk_memory_blockpool.h.

◆ m_used_count

uint16_t stk::memory::m_used_count
private

number of blocks currently allocated (outstanding)

Definition at line 320 of file stk_memory_blockpool.h.

Referenced by GetFreeCount(), GetUsedCount(), and IsEmpty().