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_c_memory.cpp
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#include <stk.h>
11#include "stk_c.h" // must be included AFTER stk.h
12#include "stk_c_memory.h"
13#include <memory/stk_memory.h>
14
15using namespace stk;
16using namespace stk::memory;
17
18// -----------------------------------------------------------------------------
19// Compile-time consistency checks between the C macros and the C++ classes.
20// If any of them fires, a C++ configuration (STK_MEMORY_*) is seen differently by the C header:
21// set the macros in the build system for every translation unit.
22// -----------------------------------------------------------------------------
23
24// Configuration mirrors.
26 "STK_BLOCKPOOL_ALIGN and BlockMemoryPool::ALIGN_DEFAULT have diverged "
27 "(STK_MEMORY_BLOCKPOOL_ALIGN_DEFAULT). Keep both definitions in sync.");
29 "STK_BYTEPOOL_ALIGN and BytePool::BLOCK_ALIGN have diverged "
30 "(STK_MEMORY_BYTEPOOL_ALIGN_DEFAULT). Keep both definitions in sync.");
32 "STK_MEM_MIN_ALIGNMENT and MemoryAllocator::MIN_ALIGNMENT have diverged. Keep both definitions in sync.");
33
34// Guard against divergence between the C macro STK_BLOCKPOOL_ALIGN_BLOCK_SIZE and
35// the C++ BlockMemoryPool::AlignBlockSize() function, including the optional bitmap.
50 "STK_BLOCKPOOL_* macros and BlockMemoryPool have diverged. Keep both definitions in sync.");
51
52// Same guard for the BytePool C macros: they must match BytePool::AlignSize(),
53// BytePool::RequiredSize() and BytePool::HEADER_SIZE (guard word included).
63 "STK_BYTEPOOL_* macros and BytePool have diverged. Keep both definitions in sync.");
64
65// C wait result enum must stay in sync with its C++ counterpart (values are cast directly).
66STK_STATIC_ASSERT_DESC(static_cast<int32_t>(STK_WAIT_RESULT_FAIL) == static_cast<int32_t>(stk::WAIT_RESULT_FAIL) &&
67 static_cast<int32_t>(STK_WAIT_RESULT_SIGNAL) == static_cast<int32_t>(stk::WAIT_RESULT_SIGNAL) &&
68 static_cast<int32_t>(STK_WAIT_RESULT_TIMEOUT) == static_cast<int32_t>(stk::WAIT_RESULT_TIMEOUT) &&
69 static_cast<int32_t>(STK_WAIT_RESULT_CANCELED) == static_cast<int32_t>(stk::WAIT_RESULT_CANCELED),
70 "stk_wait_result_t mismatch");
71
72// -----------------------------------------------------------------------------
73// stk_blockpool_t — wraps a BlockMemoryPool instance
74//
75// The struct is opaque to C callers. Instances live in s_BlockPools[].
76// -----------------------------------------------------------------------------
77
79{
80 // Constructor forwarded to the external-storage BlockMemoryPool ctor.
81 stk_blockpool_t(size_t capacity, size_t raw_block_size,
82 uint8_t *storage, size_t storage_size, const char *name, size_t alignment)
83 : handle(capacity, raw_block_size, storage, storage_size, name, alignment)
84 {}
85
86#if STK_MEMORY_HAS_HEAP
87 // Constructor forwarded to the heap-storage BlockMemoryPool ctor.
88 stk_blockpool_t(size_t capacity, size_t raw_block_size, const char *name, size_t alignment)
89 : handle(capacity, raw_block_size, name, alignment)
90 {}
91#endif
92
94};
95
96// -----------------------------------------------------------------------------
97// stk_bytepool_t — wraps a BytePool instance
98//
99// The struct is opaque to C callers. Instances live in s_BytePools[].
100// -----------------------------------------------------------------------------
101
103{
104 // Constructor forwarded to the external-storage BytePool ctor.
105 stk_bytepool_t(uint8_t *storage, size_t storage_size, const char *name)
106 : handle(storage, storage_size, name)
107 {}
108
109#if STK_MEMORY_HAS_HEAP
110 // Constructor forwarded to the heap-storage BytePool ctor.
111 stk_bytepool_t(size_t storage_size, const char *name)
112 : handle(storage_size, name)
113 {}
114#endif
115
117};
118
119// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
120// Anonymous namespace to make local functions file-local.
121namespace {
122// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
123
124// Returns a size of memory in stk::Word elements required for object allocation.
125template <typename T> constexpr size_t StkGetWordCountForType()
126{
127 return ((sizeof(T) + sizeof(stk::Word) - 1U) / sizeof(stk::Word));
128}
129
130// Copy stats of the C++ class into the C structure.
131void CopyStats(const MemoryAllocator::Stats &src, stk_mem_stats_t *dst)
132{
133 STK_ASSERT(dst != nullptr);
134
135 if (dst != nullptr)
136 {
137 dst->capacity = src.capacity;
138 dst->allocated = src.allocated;
141 dst->free_count = src.free_count;
143 dst->min_ever_free = src.min_ever_free;
144 }
145}
146
147// -----------------------------------------------------------------------------
148// Static pool of stk_blockpool_t slots
149// -----------------------------------------------------------------------------
150
151// Raw storage for one stk_blockpool_t, sized and aligned for the type.
152struct BlockPoolMem
153{
154 alignas(stk_blockpool_t) Word data[StkGetWordCountForType<stk_blockpool_t>()];
155};
156
157struct BlockPoolSlot
158{
159 BlockPoolSlot() : busy(false)
160 {}
161
162 stk_blockpool_t *pool() { return reinterpret_cast<stk_blockpool_t *>(reinterpret_cast<void *>(mem.data)); }
163 const stk_blockpool_t *pool() const { return reinterpret_cast<const stk_blockpool_t *>(reinterpret_cast<const void *>(mem.data)); }
164
165 BlockPoolMem mem;
166 bool busy;
167}
168s_BlockPools[STK_C_BLOCKPOOL_MAX];
169
170// Raw storage for one stk_bytepool_t, sized and aligned for the type.
171struct BytePoolMem
172{
173 alignas(stk_bytepool_t) Word data[StkGetWordCountForType<stk_bytepool_t>()];
174};
175
176struct BytePoolSlot
177{
178 BytePoolSlot() : busy(false)
179 {}
180
181 stk_bytepool_t *pool() { return reinterpret_cast<stk_bytepool_t *>(reinterpret_cast<void *>(mem.data)); }
182 const stk_bytepool_t *pool() const { return reinterpret_cast<const stk_bytepool_t *>(reinterpret_cast<const void *>(mem.data)); }
183
184 BytePoolMem mem;
185 bool busy;
186}
187s_BytePools[STK_C_BYTEPOOL_MAX];
188
189// -----------------------------------------------------------------------------
190// Internal helpers
191// -----------------------------------------------------------------------------
192
193// Find the slot that owns 'pool'; returns nullptr if not found.
194BlockPoolSlot *FindSlot(const stk_blockpool_t *pool)
195{
196 BlockPoolSlot *result = nullptr;
197
198 for (size_t i = 0U; i < STK_C_BLOCKPOOL_MAX; ++i)
199 {
200 if (s_BlockPools[i].busy)
201 {
202 if (s_BlockPools[i].pool() == pool)
203 {
204 result = &s_BlockPools[i];
205 break;
206 }
207 }
208 }
209
210 return result;
211}
212
213// Acquire a free slot; returns nullptr when the pool is exhausted.
214BlockPoolSlot *AcquireSlot()
215{
216 BlockPoolSlot *result = nullptr;
217
218 for (size_t i = 0U; i < STK_C_BLOCKPOOL_MAX; ++i)
219 {
220 if (!s_BlockPools[i].busy)
221 {
222 s_BlockPools[i].busy = true;
223 result = &s_BlockPools[i];
224 break;
225 }
226 }
227
228 return result;
229}
230
231// Find the byte pool slot that owns 'pool'; returns nullptr if not found.
232BytePoolSlot *FindBytePoolSlot(const stk_bytepool_t *pool)
233{
234 BytePoolSlot *result = nullptr;
235
236 for (size_t i = 0U; i < STK_C_BYTEPOOL_MAX; ++i)
237 {
238 if (s_BytePools[i].busy)
239 {
240 if (s_BytePools[i].pool() == pool)
241 {
242 result = &s_BytePools[i];
243 break;
244 }
245 }
246 }
247
248 return result;
249}
250
251// Acquire a free byte pool slot; returns nullptr when the slot pool is exhausted.
252BytePoolSlot *AcquireBytePoolSlot()
253{
254 BytePoolSlot *result = nullptr;
255
256 for (size_t i = 0U; i < STK_C_BYTEPOOL_MAX; ++i)
257 {
258 if (!s_BytePools[i].busy)
259 {
260 s_BytePools[i].busy = true;
261 result = &s_BytePools[i];
262 break;
263 }
264 }
265
266 return result;
267}
268
269// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
270} // namespace
271// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
272
273// =============================================================================
274// C-interface
275// =============================================================================
276extern "C" {
277
278// -----------------------------------------------------------------------------
279// BlockPool - lifecycle
280// -----------------------------------------------------------------------------
281
283 size_t raw_block_size,
284 const char *name,
285 size_t alignment)
286{
287 STK_ASSERT(capacity > 0U);
288 STK_ASSERT(raw_block_size > 0U);
289
290 stk_blockpool_t *result = nullptr;
291
292#if STK_MEMORY_HAS_HEAP
294
295 BlockPoolSlot *const slot = AcquireSlot();
296
297 // pool exhausted — increase STK_C_BLOCKPOOL_MAX
298 STK_ASSERT(slot != nullptr);
299
300 if (slot != nullptr)
301 {
302 result = ConstructIn<stk_blockpool_t>(slot->mem, capacity, raw_block_size, name, alignment);
303 }
304#else
305 // heap support is compiled out (STK_MEMORY_NO_HEAP): use stk_blockpool_create_static*()
306 STK_UNUSED(name);
307 STK_UNUSED(alignment);
308#endif
309
310 return result;
311}
312
313stk_blockpool_t *stk_blockpool_create(size_t capacity, size_t raw_block_size, const char *name)
314{
315 return stk_blockpool_create_ex(capacity, raw_block_size, name, BlockMemoryPool::ALIGN_DEFAULT);
316}
317
319 size_t raw_block_size,
320 uint8_t *storage_ptr,
321 size_t storage_size,
322 const char *name,
323 size_t alignment)
324{
325 STK_ASSERT(capacity > 0U);
326 STK_ASSERT(raw_block_size > 0U);
327 STK_ASSERT(storage_ptr != nullptr);
328 STK_ASSERT(storage_size >= BlockMemoryPool::RequiredStorageSize(capacity, raw_block_size, alignment));
329
331
332 BlockPoolSlot *const slot = AcquireSlot();
333
334 // pool exhausted — increase STK_C_BLOCKPOOL_MAX
335 STK_ASSERT(slot != nullptr);
336
337 stk_blockpool_t *result = nullptr;
338 if (slot != nullptr)
339 {
340 result = ConstructIn<stk_blockpool_t>(slot->mem, capacity, raw_block_size,
341 storage_ptr, storage_size, name, alignment);
342 }
343
344 return result;
345}
346
348 size_t raw_block_size,
349 uint8_t *storage_ptr,
350 size_t storage_size,
351 const char *name)
352{
353 return stk_blockpool_create_static_ex(capacity, raw_block_size, storage_ptr, storage_size, name,
355}
356
358{
359 STK_ASSERT(pool != nullptr);
360
362
363 BlockPoolSlot *const slot = FindSlot(pool);
364
365 // pool not found: double-destroy or corruption
366 STK_ASSERT(slot != nullptr);
367 if (slot != nullptr)
368 {
369 // Explicitly run the destructor (frees heap storage if owned).
370 pool->~stk_blockpool_t();
371 slot->busy = false;
372 }
373}
374
375// -----------------------------------------------------------------------------
376// BlockPool - allocation
377// -----------------------------------------------------------------------------
378
380{
381 STK_ASSERT(pool != nullptr);
382 // stk_blockpool_alloc() blocks indefinitely and must never be called from an ISR.
383 // Use stk_blockpool_try_alloc() or stk_blockpool_timed_alloc(..., STK_NO_WAIT) instead.
385
386 return pool->handle.Alloc();
387}
388
390{
391 STK_ASSERT(pool != nullptr);
392
393 return pool->handle.TimedAlloc(timeout);
394}
395
397{
398 STK_ASSERT(pool != nullptr);
399 STK_ASSERT(block != nullptr);
400
401 return static_cast<stk_wait_result_t>(pool->handle.TimedAllocEx(block, timeout));
402}
403
405{
406 STK_ASSERT(pool != nullptr);
407
408 return pool->handle.TryAlloc();
409}
410
411// -----------------------------------------------------------------------------
412// BlockPool - deallocation
413// -----------------------------------------------------------------------------
414
416{
417 STK_ASSERT(pool != nullptr);
418
419 return pool->handle.Free(ptr);
420}
421
422// -----------------------------------------------------------------------------
423// BlockPool - query
424// -----------------------------------------------------------------------------
425
427{
428 STK_ASSERT(pool != nullptr);
429
430 return pool->handle.IsStorageValid();
431}
432
434{
435 STK_ASSERT(pool != nullptr);
436
437 return pool->handle.GetCapacity();
438}
439
441{
442 STK_ASSERT(pool != nullptr);
443
444 return pool->handle.GetBlockSize();
445}
446
448{
449 STK_ASSERT(pool != nullptr);
450
451 return pool->handle.GetBlockAlignment();
452}
453
455{
456 STK_ASSERT(pool != nullptr);
457
458 return pool->handle.GetUsedCount();
459}
460
462{
463 STK_ASSERT(pool != nullptr);
464
465 return pool->handle.GetFreeCount();
466}
467
469{
470 STK_ASSERT(pool != nullptr);
471
472 return pool->handle.GetPeakUsedCount();
473}
474
476{
477 STK_ASSERT(pool != nullptr);
478
479 return pool->handle.GetAllocFailCount();
480}
481
483{
484 STK_ASSERT(pool != nullptr);
485
486 CopyStats(pool->handle.GetStats(), stats);
487}
488
490{
491 STK_ASSERT(pool != nullptr);
492
493 return pool->handle.IsFull();
494}
495
497{
498 STK_ASSERT(pool != nullptr);
499
500 return pool->handle.IsEmpty();
501}
502
504{
505 STK_ASSERT(pool != nullptr);
506
507 return &pool->handle;
508}
509
510// =============================================================================
511// BytePool
512// =============================================================================
513
514// -----------------------------------------------------------------------------
515// Lifecycle
516// -----------------------------------------------------------------------------
517
518stk_bytepool_t *stk_bytepool_create(size_t storage_size, const char *name)
519{
521
522 stk_bytepool_t *result = nullptr;
523
524#if STK_MEMORY_HAS_HEAP
526
527 BytePoolSlot *const slot = AcquireBytePoolSlot();
528
529 // pool exhausted — increase STK_C_BYTEPOOL_MAX
530 STK_ASSERT(slot != nullptr);
531
532 if (slot != nullptr)
533 {
534 result = ConstructIn<stk_bytepool_t>(slot->mem, storage_size, name);
535 }
536#else
537 // heap support is compiled out (STK_MEMORY_NO_HEAP): use stk_bytepool_create_static()
538 STK_UNUSED(name);
539#endif
540
541 return result;
542}
543
545 size_t storage_size,
546 const char *name)
547{
548 STK_ASSERT(storage != nullptr);
550
552
553 BytePoolSlot *const slot = AcquireBytePoolSlot();
554
555 // pool exhausted — increase STK_C_BYTEPOOL_MAX
556 STK_ASSERT(slot != nullptr);
557
558 stk_bytepool_t *result = nullptr;
559 if (slot != nullptr)
560 {
561 result = ConstructIn<stk_bytepool_t>(slot->mem, storage, storage_size, name);
562 }
563
564 return result;
565}
566
568{
569 STK_ASSERT(pool != nullptr);
570
572
573 BytePoolSlot *const slot = FindBytePoolSlot(pool);
574
575 // pool not found: double-destroy or corruption
576 STK_ASSERT(slot != nullptr);
577 if (slot != nullptr)
578 {
579 // Explicitly run the destructor (frees heap storage if owned).
580 pool->~stk_bytepool_t();
581 slot->busy = false;
582 }
583}
584
585// -----------------------------------------------------------------------------
586// Allocation
587// -----------------------------------------------------------------------------
588
589void *stk_bytepool_alloc(stk_bytepool_t *pool, size_t size)
590{
591 STK_ASSERT(pool != nullptr);
592 // stk_bytepool_alloc() blocks indefinitely and must never be called from an ISR.
593 // Use stk_bytepool_try_alloc() or stk_bytepool_timed_alloc(..., STK_NO_WAIT) instead.
595
596 return pool->handle.Alloc(size);
597}
598
599void *stk_bytepool_timed_alloc(stk_bytepool_t *pool, size_t size, stk_timeout_t timeout)
600{
601 STK_ASSERT(pool != nullptr);
602
603 return pool->handle.TimedAlloc(size, timeout);
604}
605
607{
608 STK_ASSERT(pool != nullptr);
609 STK_ASSERT(block != nullptr);
610
611 return static_cast<stk_wait_result_t>(pool->handle.TimedAllocEx(block, size, timeout));
612}
613
614void *stk_bytepool_try_alloc(stk_bytepool_t *pool, size_t size)
615{
616 STK_ASSERT(pool != nullptr);
617
618 return pool->handle.TryAlloc(size);
619}
620
621// -----------------------------------------------------------------------------
622// Deallocation
623// -----------------------------------------------------------------------------
624
625bool stk_bytepool_free(stk_bytepool_t *pool, void *ptr)
626{
627 STK_ASSERT(pool != nullptr);
628
629 return pool->handle.Free(ptr);
630}
631
632// -----------------------------------------------------------------------------
633// Query
634// -----------------------------------------------------------------------------
635
637 size_t *available,
638 size_t *largest,
639 size_t *fragments)
640{
641 STK_ASSERT(pool != nullptr);
642
643 size_t avail = 0U;
644 size_t large = 0U;
645 size_t frags = 0U;
646
647 pool->handle.GetInfo(avail, large, frags);
648
649 if (available != nullptr) { *available = avail; }
650 if (largest != nullptr) { *largest = large; }
651 if (fragments != nullptr) { *fragments = frags; }
652}
653
655{
656 STK_ASSERT(pool != nullptr);
657
658 CopyStats(pool->handle.GetStats(), stats);
659}
660
662{
663 STK_ASSERT(pool != nullptr);
664
665 return pool->handle.GetMaxScanLength();
666}
667
669{
670 STK_ASSERT(pool != nullptr);
671
672 return pool->handle.GetAllocFailCount();
673}
674
676{
677 STK_ASSERT(pool != nullptr);
678
679 return pool->handle.GetPeakUsedSize();
680}
681
683{
684 STK_ASSERT(pool != nullptr);
685
686 return pool->handle.IsStorageValid();
687}
688
690{
691 STK_ASSERT(pool != nullptr);
692
693 return pool->handle.GetSize();
694}
695
697{
698 STK_ASSERT(pool != nullptr);
699
700 return pool->handle.GetMaxRequest();
701}
702
704{
705 STK_ASSERT(pool != nullptr);
706
707 return &pool->handle;
708}
709
710// =============================================================================
711// General-purpose allocator
712// =============================================================================
713
715{
716#if STK_MEMORY_NO_HEAP
717 return false;
718#else
720#endif
721}
722
723void *stk_mem_allocate(size_t size)
724{
725 void *result = nullptr;
726
728 {
729 result = MemoryAllocator::Allocate(size);
730 }
731
732 return result;
733}
734
735void stk_mem_free(void *ptr)
736{
737 if ((ptr != nullptr) && stk_mem_is_available())
738 {
740 }
741}
742
743void *stk_mem_allocate_aligned(size_t size, size_t alignment)
744{
745 void *result = nullptr;
746
747#if STK_MEMORY_HAS_HEAP
748 result = MemoryAllocator::AllocateAligned(size, alignment);
749#else
750 STK_UNUSED(size);
751 STK_UNUSED(alignment);
752#endif
753
754 return result;
755}
756
757void stk_mem_free_aligned(void *ptr)
758{
759#if STK_MEMORY_HAS_HEAP
761#else
762 STK_UNUSED(ptr);
763#endif
764}
765
767{
768 STK_ASSERT(stats != nullptr);
769
771 {
772 CopyStats(MemoryAllocator::GetStats(), stats);
773 }
774 else
775 {
776 CopyStats(MemoryAllocator::Stats(), stats);
777 }
778}
779
780// =============================================================================
781} // extern "C"
782// =============================================================================
Collection of memory-related primitives (stk::memory namespace).
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
#define STK_STATIC_ASSERT_DESC(X, DESC)
Compile-time assertion with a custom error description. Produces a compilation error if X is false.
Definition stk_defs.h:548
C language binding/interface for SuperTinyKernel RTOS.
C language bindings for stk::memory::BlockMemoryPool, stk::memory::BytePool and stk::memory::MemoryAl...
stk_wait_result_t
Outcome of a cancellable, timed kernel wait (see stk_cv_wait_ex(), stk_mutex_timed_lock_ex(),...
Definition stk_c.h:210
int32_t stk_timeout_t
Timeout value.
Definition stk_c.h:175
@ STK_WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_c.h:213
@ STK_WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_c.h:212
@ STK_WAIT_RESULT_CANCELED
The wait was cancelled by another task, independent of signal/timeout.
Definition stk_c.h:214
@ STK_WAIT_RESULT_FAIL
The kernel returned an error without actually waiting.
Definition stk_c.h:211
size_t stk_blockpool_get_capacity(const stk_blockpool_t *pool)
Get the total block capacity of the pool.
void * stk_blockpool_timed_alloc(stk_blockpool_t *pool, stk_timeout_t timeout)
Allocate one block, blocking until one becomes available or the timeout expires.
size_t stk_bytepool_get_size(const stk_bytepool_t *pool)
Get the total managed (aligned) area size in bytes, headers included.
#define STK_BLOCKPOOL_STORAGE_SIZE(capacity, raw_block_size)
Same as STK_BLOCKPOOL_STORAGE_SIZE_EX() with the default alignment.
void stk_blockpool_destroy(stk_blockpool_t *pool)
Destroy a pool and return its slot to the static pool.
size_t stk_blockpool_get_alloc_fail_count(const stk_blockpool_t *pool)
Get the number of allocation requests that failed because the pool was exhausted (timeouts and STK_NO...
#define STK_BYTEPOOL_REQUIRED_SIZE(payload_size)
Pool space in bytes consumed by one allocation of payload_size bytes (aligned payload,...
bool stk_blockpool_is_storage_valid(const stk_blockpool_t *pool)
Verify that the backing storage is valid and the pool is ready for use.
bool stk_bytepool_free(stk_bytepool_t *pool, void *ptr)
Return a previously allocated block to the pool.
#define STK_C_BLOCKPOOL_MAX
Maximum number of concurrent stk_blockpool_t instances (default: 8).
size_t stk_blockpool_get_block_alignment(const stk_blockpool_t *pool)
Get the alignment of every block of the pool.
size_t stk_blockpool_get_used_count(const stk_blockpool_t *pool)
Get the number of currently allocated (outstanding) blocks.
#define STK_BLOCKPOOL_ALIGN_BLOCK_SIZE_EX(raw_size, align)
Compute the internally aligned block size for a given raw byte size and alignment.
struct stk_blockpool_t stk_blockpool_t
Opaque handle to a stk::memory::BlockMemoryPool instance.
void * stk_blockpool_alloc(stk_blockpool_t *pool)
Allocate one block, blocking indefinitely until one is available.
void stk_bytepool_destroy(stk_bytepool_t *pool)
Destroy a byte pool and return its slot to the static pool.
size_t stk_bytepool_get_peak_used_size(const stk_bytepool_t *pool)
Get the high watermark of pool consumption in bytes (headers included).
BlockMemoryPool * stk_blockpool_get_instance(stk_blockpool_t *pool)
Get the underlying C++ stk::memory::BlockMemoryPool object wrapped by a stk_blockpool_t handle.
#define STK_BYTEPOOL_ALIGN_SIZE(raw_size)
Round raw_size up to the nearest multiple of STK_BYTEPOOL_ALIGN.
#define STK_C_BYTEPOOL_MAX
Maximum number of concurrent stk_bytepool_t instances (default: 8).
stk_bytepool_t * stk_bytepool_create(size_t storage_size, const char *name)
Create a byte pool backed by heap-allocated storage.
stk_wait_result_t stk_blockpool_timed_alloc_ex(stk_blockpool_t *pool, void **block, stk_timeout_t timeout)
Allocate one block, preserving the full wait outcome.
struct stk_bytepool_t stk_bytepool_t
Opaque handle to a stk::memory::BytePool instance.
void * stk_bytepool_timed_alloc(stk_bytepool_t *pool, size_t size, stk_timeout_t timeout)
Allocate a block, blocking until memory becomes available or the timeout expires.
size_t stk_bytepool_get_max_request(const stk_bytepool_t *pool)
Get the largest request that can ever succeed on this pool.
void * stk_bytepool_alloc(stk_bytepool_t *pool, size_t size)
Allocate a block, blocking indefinitely until enough contiguous memory is available.
stk_wait_result_t stk_bytepool_timed_alloc_ex(stk_bytepool_t *pool, void **block, size_t size, stk_timeout_t timeout)
Allocate a block, preserving the full wait outcome.
#define STK_BLOCKPOOL_BITMAP_BYTES(capacity)
Size in bytes of the "allocated" bitmap of a pool of capacity blocks (0 unless STK_MEMORY_BLOCKPOOL_B...
bool stk_blockpool_free(stk_blockpool_t *pool, void *ptr)
Return a previously allocated block to the pool.
void * stk_blockpool_try_alloc(stk_blockpool_t *pool)
Non-blocking allocation attempt.
size_t stk_bytepool_get_max_scan_length(const stk_bytepool_t *pool)
Get the length of the longest block-list walk (in blocks) of any allocation so far.
stk_blockpool_t * stk_blockpool_create_static(size_t capacity, size_t raw_block_size, uint8_t *storage_ptr, size_t storage_size, const char *name)
Create a block pool backed by caller-supplied (external) storage (default alignment).
#define STK_BYTEPOOL_HEADER_SIZE
Per-block header size in bytes: max(8, STK_BYTEPOOL_ALIGN). Every allocation consumes this many bytes...
stk_blockpool_t * stk_blockpool_create(size_t capacity, size_t raw_block_size, const char *name)
Create a block pool backed by heap-allocated storage (default alignment).
stk_bytepool_t * stk_bytepool_create_static(uint8_t *storage, size_t storage_size, const char *name)
Create a byte pool backed by caller-supplied (external) storage.
void stk_mem_free_aligned(void *ptr)
Free a chunk obtained with stk_mem_allocate_aligned().
#define STK_BLOCKPOOL_STORAGE_SIZE_EX(capacity, raw_block_size, align)
Compute the minimum external storage buffer size in bytes (blocks plus the optional bitmap)....
bool stk_blockpool_is_empty(const stk_blockpool_t *pool)
Check whether all blocks are free (no outstanding allocations).
void stk_mem_get_stats(stk_mem_stats_t *stats)
Get statistics of the general-purpose allocator.
bool stk_bytepool_is_storage_valid(const stk_bytepool_t *pool)
Verify that the backing storage is valid and the pool is ready for use.
bool stk_blockpool_is_full(const stk_blockpool_t *pool)
Check whether all blocks are currently allocated (pool exhausted).
size_t stk_blockpool_get_free_count(const stk_blockpool_t *pool)
Get the number of free (available) blocks.
size_t stk_blockpool_get_peak_used_count(const stk_blockpool_t *pool)
Get the high watermark: the maximum number of blocks allocated at the same time.
void stk_mem_free(void *ptr)
Free a chunk obtained with stk_mem_allocate().
size_t stk_bytepool_get_alloc_fail_count(const stk_bytepool_t *pool)
Get the number of allocation requests that failed because no suitable block was available (timeouts,...
void * stk_bytepool_try_alloc(stk_bytepool_t *pool, size_t size)
Non-blocking allocation attempt.
#define STK_BYTEPOOL_ALIGN
Payload alignment and block size granularity of a byte pool, in bytes (equals STK_MEMORY_BYTEPOOL_ALI...
void stk_bytepool_get_stats(const stk_bytepool_t *pool, stk_mem_stats_t *stats)
Get an O(1) statistics snapshot.
size_t stk_blockpool_get_block_size(const stk_blockpool_t *pool)
Get the aligned block size used internally by the allocator.
#define STK_MEM_MIN_ALIGNMENT
Minimum alignment in bytes guaranteed for pointers returned by stk_mem_allocate() (equals MemoryAlloc...
#define STK_BLOCKPOOL_ALIGN_BLOCK_SIZE(raw_size)
Same as STK_BLOCKPOOL_ALIGN_BLOCK_SIZE_EX() with the default alignment.
void * stk_mem_allocate_aligned(size_t size, size_t alignment)
Allocate a chunk with an alignment stricter than STK_MEM_MIN_ALIGNMENT.
void stk_bytepool_get_info(const stk_bytepool_t *pool, size_t *available, size_t *largest, size_t *fragments)
Collect pool statistics (mutually consistent snapshot).
stk_blockpool_t * stk_blockpool_create_ex(size_t capacity, size_t raw_block_size, const char *name, size_t alignment)
Create a block pool backed by heap-allocated storage with an explicit block alignment.
void stk_blockpool_get_stats(const stk_blockpool_t *pool, stk_mem_stats_t *stats)
Get a consistent statistics snapshot (bytes: blocks * block size).
BytePool * stk_bytepool_get_instance(stk_bytepool_t *pool)
Get the underlying C++ stk::memory::BytePool object wrapped by a stk_bytepool_t handle.
stk_blockpool_t * stk_blockpool_create_static_ex(size_t capacity, size_t raw_block_size, uint8_t *storage_ptr, size_t storage_size, const char *name, size_t alignment)
Create a block pool backed by caller-supplied storage with an explicit block alignment.
#define STK_BLOCKPOOL_ALIGN
Default block alignment in bytes (equals STK_MEMORY_BLOCKPOOL_ALIGN_DEFAULT, i.e. BlockMemoryPool::AL...
bool stk_mem_is_available(void)
Check that the memory allocator implementation is linked in.
void * stk_mem_allocate(size_t size)
Allocate a memory chunk from the general-purpose allocator.
Namespace of STK package.
uintptr_t Word
Native processor word type.
Definition stk_common.h:206
static T * ConstructIn(Mem &mem, Args &&... args)
Construct object T in-place inside a C memory container.
Definition stk_c.h:2970
@ WAIT_RESULT_FAIL
IKernelService::Wait returned with error without waiting.
Definition stk_common.h:139
@ WAIT_RESULT_CANCELED
The wait was cancelled by another task via IKernel::CancelTaskWait(), independent of signal/timeout.
Definition stk_common.h:142
@ WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_common.h:141
@ WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_common.h:140
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
Memory-related primitives: fixed-size block pool, variable-size byte pool, zero-heap pool variants,...
static void * AllocateAligned(size_t size, size_t alignment, size_t offset=0U)
Allocate memory with an alignment stricter than MIN_ALIGNMENT and an optional offset.
static Stats GetStats()
Get stats of memory allocation (checked).
static void Free(void *ptr)
Free the memory chunk (checked).
static constexpr size_t MIN_ALIGNMENT
Minimum alignment (bytes) guaranteed for pointers returned by Allocate().
static bool IsAvailable()
Check that Weak::Allocate() and Weak::Free() were provided by the application.
static void FreeAligned(void *ptr)
Free memory obtained with AllocateAligned().
static void * Allocate(size_t size)
Allocate the memory chunk (checked).
Snapshot of the memory allocator's statistics.
volatile size_t allocated
Number of bytes currently allocated (dynamic value).
volatile size_t allocate_count
Number of successful allocations with Allocate().
size_t capacity
Total capacity of the memory pool in bytes.
volatile size_t free_count
Number of successful frees with Free().
volatile size_t min_ever_free
Minimum free bytes recorded since system start (watermark).
volatile size_t alloc_fail_count
Number of allocation requests that could not be satisfied.
volatile size_t peak_allocated
Maximum number of bytes that were allocated at the same time (high watermark).
Fixed-size block allocator with O(1) alloc/free and proper task-blocking semantics.
size_t GetUsedCount() const
Get the number of currently allocated (outstanding) blocks.
EWaitResult TimedAllocEx(void **block, Timeout timeout_ticks=WAIT_INFINITE)
Allocate one block, preserving the full wait outcome.
static const size_t ALIGN_DEFAULT
Default block alignment in bytes (see STK_MEMORY_BLOCKPOOL_ALIGN_DEFAULT).
static constexpr size_t BitmapBytes(size_t capacity)
Number of bytes of the "allocated" bitmap for capacity blocks.
size_t GetFreeCount() const
Get the number of free (available) blocks.
size_t GetCapacity() const
Get the total block capacity of the pool.
size_t GetBlockAlignment() const
Get the alignment (bytes) of every block.
bool IsFull() const
Check whether all blocks are currently allocated (pool exhausted).
size_t GetAllocFailCount() const
Get the number of allocation requests that failed because the pool was exhausted (timeouts and NO_WAI...
bool IsStorageValid() const
Verify that the backing storage is valid and the pool is ready for use.
MemoryAllocator::Stats GetStats() const
Get a consistent statistics snapshot in the same format as MemoryAllocator::GetStats().
bool Free(void *ptr)
Return a previously allocated block to the pool.
size_t GetPeakUsedCount() const
Get the high watermark: the maximum number of blocks that were allocated at the same time.
void * TryAlloc()
Non-blocking allocation attempt.
void * TimedAlloc(Timeout timeout_ticks=WAIT_INFINITE)
Allocate one block, blocking until one becomes available or the timeout expires.
size_t GetBlockSize() const
Get the aligned block size used internally by the allocator.
void * Alloc()
Allocate one block, blocking indefinitely until one is available.
bool IsEmpty() const
Check whether all blocks are free (no outstanding allocations).
static constexpr size_t RequiredStorageSize(size_t capacity, size_t raw_block_size, size_t alignment=ALIGN_DEFAULT)
Compute the size of the storage buffer required for an external-storage pool.
static constexpr size_t AlignBlockSize(size_t raw_size, size_t alignment=ALIGN_DEFAULT)
Round a raw block size up to the nearest multiple of alignment.
Variable-size (first-fit) allocator with block coalescing and proper task-blocking semantics.
size_t GetMaxScanLength() const
Get the length of the longest block-list walk (in blocks) of any allocation so far.
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 GetMaxRequest() const
Get the largest request that can ever succeed on this pool.
static const size_t HEADER_SIZE
Size of the per-block header in bytes: max(8, BLOCK_ALIGN).
size_t GetPeakUsedSize() const
Get the high watermark of pool consumption in bytes (headers included).
EWaitResult TimedAllocEx(void **block, size_t size, Timeout timeout_ticks=WAIT_INFINITE)
Allocate a block, preserving the full wait outcome.
MemoryAllocator::Stats GetStats() const
Get a consistent O(1) statistics snapshot in the same format as MemoryAllocator::GetStats().
size_t GetSize() const
Get the total size of the managed (aligned) area in bytes, headers included.
void * Alloc(size_t size)
Allocate a block, blocking indefinitely until memory is available.
void GetInfo(size_t &available, size_t &largest, size_t &fragments) const
Collect pool statistics.
static constexpr size_t RequiredSize(size_t payload_size)
Compute the pool space consumed by a single allocation of payload_size bytes.
static constexpr size_t AlignSize(size_t raw_size)
Round a size up to the nearest multiple of the block alignment (BLOCK_ALIGN).
static const size_t BLOCK_ALIGN
Payload alignment and block size granularity in bytes.
size_t GetAllocFailCount() const
Get the number of allocation requests that failed because no suitable block was available (timeouts,...
void * TryAlloc(size_t size)
Non-blocking allocation attempt.
void * TimedAlloc(size_t size, Timeout timeout_ticks=WAIT_INFINITE)
Allocate a block, blocking until memory becomes available or the timeout expires.
RAII-style low-level synchronization primitive for atomic code execution. Used as building brick for ...
Definition stk_sync_cs.h:58
Snapshot of allocator statistics.
size_t peak_allocated
High watermark of allocated bytes.
size_t capacity
Total capacity in bytes.
size_t free_count
Number of successful frees.
size_t min_ever_free
Minimum free bytes recorded since the start (watermark).
size_t allocated
Bytes currently allocated.
size_t allocate_count
Number of successful allocations.
size_t alloc_fail_count
Number of allocation requests that could not be satisfied.
stk_blockpool_t(size_t capacity, size_t raw_block_size, uint8_t *storage, size_t storage_size, const char *name, size_t alignment)
BlockMemoryPool handle
stk_bytepool_t(uint8_t *storage, size_t storage_size, const char *name)