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_newlib.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
23
24#include <new>
25#include <stdint.h>
26
27#include "stk_newlib.h"
28#include "sync/stk_sync_mutex.h"
31
32// ---------------------------------------------------------------------------
33// Lock object
34// ---------------------------------------------------------------------------
35
43struct __lock
44{
45 enum EKind : uint8_t
46 {
50 };
51
53 static const size_t STORAGE_SIZE = (sizeof(stk::sync::FastMutex) > sizeof(stk::sync::Mutex)) ?
54 sizeof(stk::sync::FastMutex) : sizeof(stk::sync::Mutex);
55
57 bool dynamic;
59
61};
62
63namespace stk {
64namespace newlib {
65namespace {
66
67// ---------------------------------------------------------------------------
68// Pool of dynamic lock objects
69// ---------------------------------------------------------------------------
70
71typedef memory::BlockMemoryPool LockPool;
72
74static const size_t LOCK_BLOCK_SIZE = LockPool::AlignBlockSize(sizeof(__lock));
75
76STK_STATIC_ASSERT_DESC(((STK_NEWLIB_MAX_LOCKS > 0U) && (STK_NEWLIB_MAX_LOCKS <= LockPool::CAPACITY_MAX)),
77 "STK_NEWLIB_MAX_LOCKS is out of the pool capacity range");
78STK_STATIC_ASSERT_DESC(((LOCK_BLOCK_SIZE % alignof(__lock)) == 0U),
79 "pool block size must preserve the alignment of the lock object");
80
82alignas(__lock) alignas(void *) uint8_t s_LockPoolStorage[STK_NEWLIB_MAX_LOCKS * LOCK_BLOCK_SIZE];
83
86struct LockPoolBuffer
87{
88 alignas(LockPool) uint8_t data[sizeof(LockPool)];
89};
90LockPoolBuffer s_LockPoolBuffer;
91LockPool *s_LockPool = nullptr;
92
96LockPool *GetLockPool()
97{
99
100 if (s_LockPool == nullptr)
101 {
102 s_LockPool = new (static_cast<void *>(s_LockPoolBuffer.data))
103 LockPool(STK_NEWLIB_MAX_LOCKS, sizeof(__lock), s_LockPoolStorage, sizeof(s_LockPoolStorage));
104 }
105
106 return s_LockPool;
107}
108
114bool IsTaskContext()
115{
116 bool running = false;
117
119
120 if (svc != nullptr)
121 {
122 running = (svc->GetTid() != TID_NONE);
123 }
124
125 return running;
126}
127
138template <typename T, typename Mem, typename... Args>
139static inline T *ConstructIn(Mem &mem, Args &&... args)
140{
141 STK_STATIC_ASSERT_DESC((sizeof(T) <= sizeof(mem.storage)),
142 "storage is too small for the C++ object");
143 STK_STATIC_ASSERT_DESC((alignof(T) <= alignof(Mem)),
144 "storage is not sufficiently aligned for the C++ object");
145
146 return new (static_cast<void *>(mem.storage)) T(static_cast<Args &&>(args)...);
147}
148
153void Construct(_LOCK_T lock, __lock::EKind kind)
154{
156
157 if (lock->kind == __lock::KIND_NONE)
158 {
159 if (kind == __lock::KIND_PLAIN)
160 {
161 lock->mutex = ConstructIn<sync::FastMutex>(*lock);
162 }
163 else
164 {
165 lock->mutex = ConstructIn<sync::Mutex>(*lock);
166 }
167
168 lock->kind = kind;
169 }
170}
171
174stk::IMutex *GetMutex(_LOCK_T lock, __lock::EKind kind)
175{
176 STK_ASSERT(lock != nullptr); // API contract: lock object must be valid
177
178 if (lock->kind == __lock::KIND_NONE)
179 {
180 Construct(lock, kind);
181 }
182
183 STK_ASSERT(lock->kind == kind); // API contract: plain lock must use the non-recursive API
184
185 return lock->mutex;
186}
187
192void Init(_LOCK_T *lock, __lock::EKind kind)
193{
194 STK_ASSERT(lock != nullptr); // API contract: pointer to the lock object must be valid
195
196 _LOCK_T new_lock = GetLockPool()->TryAllocT<__lock>();
197
198 if (new_lock == nullptr)
199 {
200 // Newlib's init callbacks cannot report failure: STK_NEWLIB_MAX_LOCKS is too small
202 }
203 else
204 {
205 new_lock->kind = __lock::KIND_NONE;
206 new_lock->dynamic = true;
207 new_lock->mutex = nullptr;
208
209 Construct(new_lock, kind);
210 }
211
212 *lock = new_lock;
213}
214
217void Close(_LOCK_T lock)
218{
219 if (lock != nullptr)
220 {
221 if (lock->kind == __lock::KIND_PLAIN)
222 {
223 static_cast<sync::FastMutex *>(lock->mutex)->~FastMutex();
224 lock->mutex = nullptr;
225 }
226 else if (lock->kind == __lock::KIND_RECURSIVE)
227 {
228 static_cast<sync::Mutex *>(lock->mutex)->~Mutex();
229 lock->mutex = nullptr;
230 }
231 else
232 {
233 // never constructed, nothing to destroy
234 }
235
236 lock->kind = __lock::KIND_NONE;
237
238 // static locks live in BSS and never go back to the pool
239 if (lock->dynamic)
240 {
241 if (!GetLockPool()->Free(lock))
242 {
243 // the pointer does not belong to the pool memory region: the lock object was corrupted or foreign
245 }
246 }
247 }
248}
249
252void Acquire(_LOCK_T lock, __lock::EKind kind)
253{
254 if (IsTaskContext())
255 {
256 GetMutex(lock, kind)->Lock();
257 }
258}
259
263int TryAcquire(_LOCK_T lock, __lock::EKind kind)
264{
265 int result = 0; // success
266
267 if (IsTaskContext())
268 {
269 if (!GetMutex(lock, kind)->TryLock())
270 {
271 result = 1;
272 }
273 }
274
275 return result;
276}
277
281void Release(_LOCK_T lock, __lock::EKind kind)
282{
283 if (IsTaskContext() && (lock != nullptr) && (lock->kind == kind) && (lock->mutex != nullptr))
284 {
285 lock->mutex->Unlock();
286 }
287}
288
289} // namespace
290} // namespace newlib
291} // namespace stk
292
293// ---------------------------------------------------------------------------
294// Static locks used internally by Newlib
295// ---------------------------------------------------------------------------
296
297#if STK_NEWLIB_STATIC_LOCKS
298
299extern "C" {
300
301// zero-initialized (kind = KIND_NONE), constructed on first use
311
312} // extern "C"
313
314#endif // STK_NEWLIB_STATIC_LOCKS
315
316// ---------------------------------------------------------------------------
317// Newlib retargetable locking API
318// ---------------------------------------------------------------------------
319
320extern "C" {
321
322void __retarget_lock_init(_LOCK_T *lock)
323{
324 stk::newlib::Init(lock, __lock::KIND_PLAIN);
325}
326
328{
329 stk::newlib::Init(lock, __lock::KIND_RECURSIVE);
330}
331
332void __retarget_lock_close(_LOCK_T lock)
333{
334 stk::newlib::Close(lock);
335}
336
338{
339 stk::newlib::Close(lock);
340}
341
342void __retarget_lock_acquire(_LOCK_T lock)
343{
344 stk::newlib::Acquire(lock, __lock::KIND_PLAIN);
345}
346
348{
349 stk::newlib::Acquire(lock, __lock::KIND_RECURSIVE);
350}
351
353{
354 return stk::newlib::TryAcquire(lock, __lock::KIND_PLAIN);
355}
356
358{
359 return stk::newlib::TryAcquire(lock, __lock::KIND_RECURSIVE);
360}
361
362void __retarget_lock_release(_LOCK_T lock)
363{
364 stk::newlib::Release(lock, __lock::KIND_PLAIN);
365}
366
368{
369 stk::newlib::Release(lock, __lock::KIND_RECURSIVE);
370}
371
372} // extern "C"
Implementation of fixed-size block memory pool: stk::memory::BlockMemoryPool.
#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
Implementation of synchronization primitive: stk::sync::FastMutex.
Implementation of synchronization primitive: stk::sync::Mutex.
struct __lock __lock___at_quick_exit_mutex
void __retarget_lock_acquire(_LOCK_T lock)
Acquire lock immediately after the lock object is available.
struct __lock __lock___tz_mutex
struct __lock __lock___arc4random_mutex
int __retarget_lock_try_acquire_recursive(_LOCK_T lock)
Acquire recursive lock if the lock object is available.
struct __lock __lock___dd_hash_mutex
struct __lock __lock___atexit_recursive_mutex
struct __lock __lock___sfp_recursive_mutex
struct __lock __lock___env_recursive_mutex
void __retarget_lock_release_recursive(_LOCK_T lock)
Relinquish the recursive lock ownership.
void __retarget_lock_acquire_recursive(_LOCK_T lock)
Acquire recursive lock immediately after the lock object is available.
struct __lock __lock___malloc_recursive_mutex
void __retarget_lock_init_recursive(_LOCK_T *lock)
Allocate recursive lock related resources.
void __retarget_lock_close(_LOCK_T lock)
Free lock related resources.
void __retarget_lock_init(_LOCK_T *lock)
Allocate lock related resources.
void __retarget_lock_release(_LOCK_T lock)
Relinquish the lock ownership.
struct __lock __lock___sinit_recursive_mutex
int __retarget_lock_try_acquire(_LOCK_T lock)
Acquire lock if the lock object is available.
void __retarget_lock_close_recursive(_LOCK_T lock)
Free recursive lock related resources.
GCC Newlib OS interface: retargetable locking (__retarget_lock_*) on top of STK.
#define STK_NEWLIB_MAX_LOCKS
Capacity of the static pool for dynamic lock objects: the maximum number of locks created by __retarg...
Definition stk_newlib.h:65
Namespace of STK package.
static T * ConstructIn(Mem &mem, Args &&... args)
Construct object T in-place inside a C memory container.
Definition stk_c.h:2970
void STK_KERNEL_PANIC(stk::EKernelPanicId id)
Called when the kernel detects an unrecoverable internal fault.
Definition stk_arch.h:184
@ KERNEL_PANIC_BAD_MEMORY_REGION
Bad memory region (ARM TrustZone: provided memory region overlaps with another one; memory pools: a p...
Definition stk_common.h:73
@ KERNEL_PANIC_NO_MEM
Out of memory: a mandatory allocation (heap or a fixed-size static pool) failed in a context that can...
Definition stk_common.h:75
static constexpr TId TID_NONE
Reserved task/thread id representing zero/none thread id.
Definition stk_common.h:268
Fixed-size block allocator with O(1) alloc/free and proper task-blocking semantics.
RAII instance that enters the critical section on construction and exits it on destruction.
Definition stk_arch.h:495
Interface for mutex synchronization primitive.
Definition stk_common.h:817
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.
static IKernelService * GetInstance()
Get CPU-local instance of the kernel service.
Non-recursive (binary) mutex primitive with ownership tracking.
Recursive mutex primitive that allows the same thread to acquire the lock multiple times.
Lock object behind Newlib's opaque _LOCK_T (struct __lock *).
@ KIND_RECURSIVE
Mutex.
@ KIND_PLAIN
FastMutex.
@ KIND_NONE
not constructed (zero-initialized static lock)
stk::IMutex * mutex
constructed FastMutex (KIND_PLAIN) or Mutex (KIND_RECURSIVE), otherwise nullptr
uint8_t storage[STORAGE_SIZE]
bool dynamic
true if taken from the lock pool by __retarget_lock_init* (and therefore returned by close)
EKind kind
kind of the constructed mutex
static const size_t STORAGE_SIZE
storage large enough for either mutex type