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::sync::Mutex Class Referencefinal

Recursive mutex primitive that allows the same thread to acquire the lock multiple times. More...

#include <stk_sync_mutex.h>

Inheritance diagram for stk::sync::Mutex:
Collaboration diagram for stk::sync::Mutex:

Public Types

typedef DLHeadType ListHeadType
 List head type for ISyncObject elements.
typedef DLEntryType ListEntryType
 List entry type of ISyncObject elements.
enum  
 A tag for type-safe casts done by CastListEntryToParent. More...
typedef DListEntry< ISyncObject, TClosedLoop > DLEntryType
 Convenience alias for this entry type. Used to avoid repeating the full template spelling.
typedef DListHead< ISyncObject, TClosedLoop > DLHeadType
 Convenience alias for the corresponding list head type.

Public Member Functions

 Mutex ()
 Constructor.
 ~Mutex ()
 Destructor.
EWaitResult TimedLockEx (Timeout timeout_ticks)
 Acquire lock, preserving the full wait outcome.
bool TimedLock (Timeout timeout_ticks)
 Acquire lock.
void Lock () override
 Acquire lock.
bool TryLock ()
 Try to acquire the lock without blocking.
void Unlock () override
 Release lock.
TId GetOwner () const
 Get owner of the mutex.
bool IsLocked () const
 Check if the mutex is currently locked.
uint16_t GetRecursionCount () const
 Get current recursion depth.
void AddWaitObject (IWaitObject *wobj) override
 Called by kernel when a new task starts waiting on this event.
void RemoveWaitObject (IWaitObject *wobj) override
 Called by kernel when a waiting task is being removed (timeout expired, wait aborted, task terminated etc.).
const IWaitObject::ListHeadType & GetWaitList () const override
 Get list of tasks blocked on this object.
virtual bool Tick (Timeout elapsed_ticks)
 Called by kernel on every system tick to handle timeout logic of waiting tasks.
Weight FindWeightHigherThan (Weight comp) const
 Find higher weight within linked wait objects.
TId GetFirstWaiterTid () const
 Get id of the task which is first in the wait list (FIFO order), i.e. the one that WakeOne() would wake next.
DLHeadType * GetHead ()
 Get the list head this entry currently belongs to.
DLEntryType * GetNext ()
 Get the next entry in the list.
DLEntryType * GetPrev ()
 Get the previous entry in the list.
bool IsLinked () const
 Check whether this entry is currently a member of any list.
 operator ISyncObject * ()
 Implicit conversion to a mutable pointer to the host object (T).
 operator const ISyncObject * () const
 Implicit conversion to a const pointer to the host object (T).
void SetTraceName (const char *name)
 Set name.
const char * GetTraceName () const
 Get name.

Static Public Member Functions

static void AddWaitObject (IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
 Called by kernel when a new task starts waiting on this event.
static void RemoveWaitObject (IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
 Called by kernel when a waiting task is being removed (timeout expired, wait aborted, task terminated etc.).
static void WakeOne (IWaitObject::ListHeadType &wlist)
 Wake the first task in the wait list (FIFO order).
static void WakeAll (IWaitObject::ListHeadType &wlist)
 Wake all tasks currently in the wait list.

Static Public Attributes

static const uint16_t RECURSION_MAX = 0xFFFEU
 maximum nesting depth

Protected Member Functions

void WakeOne () override
 Wake the first task in the wait list (FIFO order).
void WakeAll () override
 Wake all tasks currently in the wait list.
IWaitObject::ListHeadType & GetMutableWaitList () override
 Get list of tasks blocked on this object.

Protected Attributes

IWaitObject::ListHeadType m_wait_list
 Tasks blocked on this object.

Private Member Functions

 Mutex (const Mutex &)=delete
Mutex & operator= (const Mutex &)=delete
void Link (DLHeadType *head, DLEntryType *next, DLEntryType *prev)
 Wire this entry into a list between prev and next.
void Unlink ()
 Remove this entry from its current list.

Private Attributes

TId m_owner_tid
 thread id of the current owner
uint16_t m_recursion_count
 recursion depth
DLHeadType * m_head
 Owning list head, or NULL when the entry is not linked.
DLEntryType * m_next
 Next entry in the list, or NULL (open list boundary) / first entry (closed loop).
DLEntryType * m_prev
 Previous entry in the list, or NULL (open list boundary) / last entry (closed loop).

Detailed Description

Recursive mutex primitive that allows the same thread to acquire the lock multiple times.

Recursive mutex tracks ownership and a recursion count. If the owning thread calls Lock() again, the count is incremented and the call returns immediately without blocking. The lock is only fully released when Unlock() has been called an equal number of times.

// Example: Recursive locking in nested methods
stk::sync::Mutex g_ResourceMtx;
void Method_Internal() {
// second acquisition (recursion count = 2)
g_ResourceMtx.Lock();
// ... perform internal logic ...
g_ResourceMtx.Unlock();
}
void Method_Public() {
// first acquisition (recursion count = 1)
if (g_ResourceMtx.TimedLock(100)) {
// safe to call: same thread already owns the lock
Method_Internal();
g_ResourceMtx.Unlock();
}
}
Recursive mutex primitive that allows the same thread to acquire the lock multiple times.
bool TimedLock(Timeout timeout_ticks)
Acquire lock.
void Unlock() override
Release lock.
void Lock() override
Acquire lock.
Note
Only available when kernel is compiled with KERNEL_SYNC mode enabled.
See also
ISyncObject, IWaitObject, IKernelService::Wait
Examples
secure_task/example.cpp, and sync/example.cpp.

Definition at line 54 of file stk_sync_mutex.h.

Member Typedef Documentation

◆ DLEntryType

typedef DListEntry<ISyncObject, TClosedLoop> stk::detail::DListEntry< ISyncObject, TClosedLoop >::DLEntryType
inherited

Convenience alias for this entry type. Used to avoid repeating the full template spelling.

Definition at line 75 of file stk_linked_list.h.

◆ DLHeadType

typedef DListHead<ISyncObject, TClosedLoop> stk::detail::DListEntry< ISyncObject, TClosedLoop >::DLHeadType
inherited

Convenience alias for the corresponding list head type.

Definition at line 80 of file stk_linked_list.h.

◆ ListEntryType

List entry type of ISyncObject elements.

Definition at line 672 of file stk_common.h.

◆ ListHeadType

List head type for ISyncObject elements.

Definition at line 667 of file stk_common.h.

Member Enumeration Documentation

◆ anonymous enum

anonymous enum
inherited

A tag for type-safe casts done by CastListEntryToParent.

See also
CastListEntryToParent.

Definition at line 70 of file stk_linked_list.h.

70{ DLEntryTag = 1 };
Intrusive doubly-linked list node. Embed this as a base class in any object (T) that needs to partici...

Constructor & Destructor Documentation

◆ Mutex() [1/2]

stk::sync::Mutex::Mutex ( )
inlineexplicit

Constructor.

Definition at line 61 of file stk_sync_mutex.h.

62 {}
static constexpr TId TID_NONE
Reserved task/thread id representing zero/none thread id.
Definition stk_common.h:268
TId m_owner_tid
thread id of the current owner
uint16_t m_recursion_count
recursion depth

References m_owner_tid, m_recursion_count, and stk::TID_NONE.

Referenced by Mutex().

Here is the caller graph for this function:

◆ ~Mutex()

stk::sync::Mutex::~Mutex ( )
inline

Destructor.

Note
If tasks are still waiting at destruction time it is considered a logical error (dangling waiters). An assertion is triggered in debug builds.
MISRA deviation: [STK-DEV-005] Rule 10-3-2.

Definition at line 69 of file stk_sync_mutex.h.

70 {
71 STK_ASSERT(m_wait_list.IsEmpty()); // API contract: must not be destroyed with waiting tasks
72 }
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
IWaitObject::ListHeadType m_wait_list
Tasks blocked on this object.
Definition stk_helper.h:311

References stk::SyncObjectBase::m_wait_list, STK_ASSERT, and STK_VIRT_DTOR.

Referenced by pthread_mutex_destroy().

Here is the caller graph for this function:

◆ Mutex() [2/2]

stk::sync::Mutex::Mutex ( const Mutex & )
privatedelete

References Mutex().

Here is the call graph for this function:

Member Function Documentation

◆ AddWaitObject() [1/2]

void stk::ISyncObject::AddWaitObject ( IWaitObject::ListHeadType & wlist,
IWaitObject * wobj )
inlinestaticinherited

Called by kernel when a new task starts waiting on this event.

Parameters
[in]wlistWait list.
[in]wobjWait object representing blocked task.
Note
Utility for AddWaitObject and ARM TrustZone support.

Definition at line 679 of file stk_common.h.

680 {
681 STK_ASSERT(wobj->GetHead() == nullptr);
682 wlist.LinkBack(wobj);
683 }

References stk::detail::DListEntry< T, TClosedLoop >::GetHead(), stk::detail::DListHead< T, TClosedLoop >::LinkBack(), and STK_ASSERT.

Referenced by stk::SyncObjectBase::AddWaitObject(), and stk::Kernel< TMode, TSize, TStrategy, TPlatform >::KernelTask::WaitObject::SetupWait().

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

◆ AddWaitObject() [2/2]

void stk::SyncObjectBase::AddWaitObject ( IWaitObject * wobj)
inlineoverridevirtualinherited

Called by kernel when a new task starts waiting on this event.

Parameters
[in]wobjWait object representing blocked task.
Note
Must be called inside the critical section (see hw::CriticalSection, sync::ScopedCrticalSection).

Implements stk::ISyncObject.

Definition at line 255 of file stk_helper.h.

256 {
258 }
static void AddWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
Called by kernel when a new task starts waiting on this event.
Definition stk_common.h:679

References stk::ISyncObject::AddWaitObject(), and m_wait_list.

Here is the call graph for this function:

◆ FindWeightHigherThan()

Weight stk::ISyncObject::FindWeightHigherThan ( Weight comp) const
inlineinherited

Find higher weight within linked wait objects.

Implementation of ISyncObject::FindWeightHigherThan, see ISyncObject. Placed here as it depends on GetUserTaskFromTid.

Parameters
[in]compWeight to compare with.
Returns
Higher weight value than comp, or NO_WEIGHT if there is no object with a higher weight.
Note
Must be called inside the critical section (see hw::CriticalSection, sync::ScopedCrticalSection).

Definition at line 349 of file stk_helper.h.

350{
351 Weight max_weight = NO_WEIGHT;
352 const IWaitObject *itr = detail::DListCast::ListEntryToParent<const IWaitObject>(GetWaitList().GetFirst());
353
354 while (itr != nullptr)
355 {
356 const Weight w = GetUserTaskFromTid(itr->GetTid())->GetWeight();
357 if (w > max_weight)
358 {
359 max_weight = w;
360 }
361
363 }
364
365 return ((max_weight > comp) ? max_weight : NO_WEIGHT);
366}
ITask * GetUserTaskFromTid(TId task_id) noexcept
Get task instance from its identifier.
Definition stk_arch.h:784
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:285
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:236
virtual const IWaitObject::ListHeadType & GetWaitList() const =0
Get list of tasks blocked on this object.
virtual Weight GetWeight() const
Get static base weight of the task.
Definition stk_common.h:997
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Casts an intrusive list entry to the concrete type that derives from it.

References stk::detail::DListEntry< T, TClosedLoop >::GetNext(), stk::IWaitObject::GetTid(), stk::GetUserTaskFromTid(), GetWaitList(), stk::ITask::GetWeight(), stk::detail::DListCast::ListEntryToParent(), and stk::NO_WEIGHT.

Referenced by stk::Kernel< TMode, TSize, TStrategy, TPlatform >::OnRestoreWeight(), stk::sync::FastMutex::Unlock(), and stk::sync::Mutex::Unlock().

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

◆ GetFirstWaiterTid()

TId stk::ISyncObject::GetFirstWaiterTid ( ) const
inlineinherited

Get id of the task which is first in the wait list (FIFO order), i.e. the one that WakeOne() would wake next.

Returns
TId of the first waiter, or TID_NONE if no tasks are currently waiting.
Note
Read-only introspection for diagnostics / telemetry.
The result is a snapshot: call inside the critical section (see hw::CriticalSection, sync::ScopedCrticalSection) if the list may change concurrently.
See also
GetWaitList

Definition at line 777 of file stk_common.h.

778 {
779 const IWaitObject *const obj = detail::DListCast::ListEntryToParent<const IWaitObject>(
780 GetWaitList().GetFirst());
781
782 return ((obj != nullptr) ? obj->GetTid() : TID_NONE);
783 }

References stk::IWaitObject::GetTid(), GetWaitList(), stk::detail::DListCast::ListEntryToParent(), and stk::TID_NONE.

Here is the call graph for this function:

◆ GetHead()

DLHeadType * stk::detail::DListEntry< ISyncObject, TClosedLoop >::GetHead ( )
inlineinherited

Get the list head this entry currently belongs to.

Returns
Pointer to the owning DListHead, or NULL if the entry is not linked.

Definition at line 85 of file stk_linked_list.h.

85{ return m_head; }

Referenced by stk::SyncObjectBase::~SyncObjectBase().

Here is the caller graph for this function:

◆ GetMutableWaitList()

IWaitObject::ListHeadType & stk::SyncObjectBase::GetMutableWaitList ( )
inlineoverrideprotectedvirtualinherited

Get list of tasks blocked on this object.

Implements stk::ISyncObject.

Definition at line 306 of file stk_helper.h.

307 {
308 return m_wait_list;
309 }

References m_wait_list.

◆ GetNext()

DLEntryType * stk::detail::DListEntry< ISyncObject, TClosedLoop >::GetNext ( )
inlineinherited

Get the next entry in the list.

Returns
Next entry. In an open list NULL for the last entry; in a closed loop the last entry wraps to the first one, so the result is never NULL for a linked entry.

Definition at line 96 of file stk_linked_list.h.

96{ return m_next; }

◆ GetOwner()

TId stk::sync::Mutex::GetOwner ( ) const
inline

Get owner of the mutex.

Warning
ISR-safe.
Returns
Thread id of the owner, or TID_NONE if the mutex is free.

Definition at line 123 of file stk_sync_mutex.h.

123{ return m_owner_tid; }

References m_owner_tid.

Referenced by stk::pthread::IsMutexOwner(), and tx_mutex_info_get().

Here is the caller graph for this function:

◆ GetPrev()

DLEntryType * stk::detail::DListEntry< ISyncObject, TClosedLoop >::GetPrev ( )
inlineinherited

Get the previous entry in the list.

Returns
Previous entry. In an open list NULL for the first entry; in a closed loop the first entry wraps to the last one, so the result is never NULL for a linked entry.

Definition at line 106 of file stk_linked_list.h.

106{ return m_prev; }

◆ GetRecursionCount()

uint16_t stk::sync::Mutex::GetRecursionCount ( ) const
inline

Get current recursion depth.

Note
Reads the counter without a critical section. The value is only stable for the caller if the caller is the owner (nobody else modifies the counter while the lock is held); for a non-owner it is a snapshot that may be stale immediately.
Warning
ISR-safe.
Returns
0 if the mutex is free, otherwise the number of nested Lock() calls made by the owner (1..RECURSION_MAX).

Definition at line 140 of file stk_sync_mutex.h.

140{ return m_recursion_count; }

References m_recursion_count.

Referenced by stk::pthread::PreLockCheck(), and tx_mutex_info_get().

Here is the caller graph for this function:

◆ GetTraceName()

const char * stk::ITraceable::GetTraceName ( ) const
inlineinherited

Get name.

Returns
Name string, or NULL if not set or if STK_SYNC_DEBUG_NAMES is 0.

Definition at line 629 of file stk_common.h.

630 {
631 #if STK_SYNC_DEBUG_NAMES
632 return m_trace_name;
633 #else
634 return nullptr;
635 #endif
636 }

◆ GetWaitList()

const IWaitObject::ListHeadType & stk::SyncObjectBase::GetWaitList ( ) const
inlineoverridevirtualinherited

Get list of tasks blocked on this object.

Note
Read-only access for diagnostics / telemetry.
The result is a snapshot: call inside the critical section (see hw::CriticalSection, sync::ScopedCrticalSection) if the list may change concurrently.

Implements stk::ISyncObject.

Definition at line 265 of file stk_helper.h.

266 {
267 return m_wait_list;
268 }

References m_wait_list.

◆ IsLinked()

bool stk::detail::DListEntry< ISyncObject, TClosedLoop >::IsLinked ( ) const
inlineinherited

Check whether this entry is currently a member of any list.

Returns
true if linked (m_head != NULL); false otherwise.

Definition at line 115 of file stk_linked_list.h.

115{ return (GetHead() != nullptr); }

◆ IsLocked()

bool stk::sync::Mutex::IsLocked ( ) const
inline

Check if the mutex is currently locked.

Note
Snapshot only, may be stale immediately for a non-owner.
Warning
ISR-safe.

Definition at line 129 of file stk_sync_mutex.h.

129{ return (m_owner_tid != TID_NONE); }

References m_owner_tid, and stk::TID_NONE.

◆ Link()

void stk::detail::DListEntry< ISyncObject, TClosedLoop >::Link ( DLHeadType * head,
DLEntryType * next,
DLEntryType * prev )
inlineprivateinherited

Wire this entry into a list between prev and next.

Parameters
[in]headThe owning DListHead. Stored as a back-pointer for IsLinked() and ownership checks.
[in]nextThe entry that will follow this one, or NULL if this becomes the last entry.
[in]prevThe entry that will precede this one, or NULL if this becomes the first entry.
Note
Called exclusively by DListHead::Link(). Assumes the entry is not currently linked. Updates the neighbours' forward/back pointers to splice this entry in.

Definition at line 150 of file stk_linked_list.h.

151 {
152 m_head = head;
153 m_next = next;
154 m_prev = prev;
155
156 if (m_prev != nullptr)
157 {
158 m_prev->m_next = this;
159 }
160
161 if (m_next != nullptr)
162 {
163 m_next->m_prev = this;
164 }
165 }
DLEntryType * m_next
Next entry in the list, or NULL (open list boundary) / first entry (closed loop).
DLEntryType * m_prev
Previous entry in the list, or NULL (open list boundary) / last entry (closed loop).

◆ Lock()

void stk::sync::Mutex::Lock ( )
inlineoverridevirtual

Acquire lock.

Note
Not cancelable: a void Lock() cannot report failure and must return with the lock held, so a cancellation (IKernel::CancelTaskWait()) is absorbed and the wait is retried. This also keeps the mutex re-acquisition at the end of ConditionVariable::Wait() reliable (the kernel re-locks via this method). Use TimedLockEx() if cancellation must be observed. Panics (KERNEL_PANIC_ASSERT) on any other failure.
Warning
ISR-unsafe.

Implements stk::IMutex.

Definition at line 239 of file stk_sync_mutex.h.

240{
241 EWaitResult result;
242
243 do
244 {
245 result = TimedLockEx(WAIT_INFINITE);
246 }
247 while (result == WAIT_RESULT_CANCELED);
248
249 if (result != WAIT_RESULT_SIGNAL)
250 {
252 }
253}
void STK_KERNEL_PANIC(stk::EKernelPanicId id)
Called when the kernel detects an unrecoverable internal fault.
Definition stk_arch.h:184
EWaitResult
Wait result (see IKernelService::Wait).
Definition stk_common.h:138
@ WAIT_RESULT_CANCELED
The wait was cancelled by another task via IKernel::CancelTaskWait(), independent of signal/timeout.
Definition stk_common.h:142
@ WAIT_RESULT_SIGNAL
The wake was caused by a signal.
Definition stk_common.h:140
@ KERNEL_PANIC_ASSERT
Internal assertion failed (maps from STK_ASSERT).
Definition stk_common.h:64
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274
EWaitResult TimedLockEx(Timeout timeout_ticks)
Acquire lock, preserving the full wait outcome.

References stk::KERNEL_PANIC_ASSERT, stk::STK_KERNEL_PANIC(), TimedLockEx(), stk::WAIT_INFINITE, stk::WAIT_RESULT_CANCELED, and stk::WAIT_RESULT_SIGNAL.

Referenced by MqReceiveImpl(), MqSendImpl(), pthread_mutex_lock(), pthread_once(), pthread_spin_lock(), and stk_mutex_lock().

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

◆ operator const ISyncObject *()

stk::detail::DListEntry< ISyncObject, TClosedLoop >::operator const ISyncObject * ( ) const
inlineinherited

Implicit conversion to a const pointer to the host object (T).

Note
Safe because T must derive from DListEntry<T, TClosedLoop>. Eliminates the need for explicit static_cast at call sites.
MISRA deviation: [STK-DEV-004] Rule 5-2-x.

Definition at line 129 of file stk_linked_list.h.

129{ return static_cast<const T *>(this); }

◆ operator ISyncObject *()

stk::detail::DListEntry< ISyncObject, TClosedLoop >::operator ISyncObject* ( )
inlineinherited

Implicit conversion to a mutable pointer to the host object (T).

Note
Safe because T must derive from DListEntry<T, TClosedLoop>. Eliminates the need for explicit static_cast at call sites.
MISRA deviation: [STK-DEV-004] Rule 5-2-x.

Definition at line 122 of file stk_linked_list.h.

122{ return static_cast<T *>(this); }

◆ operator=()

Mutex & stk::sync::Mutex::operator= ( const Mutex & )
privatedelete

◆ RemoveWaitObject() [1/2]

void stk::ISyncObject::RemoveWaitObject ( IWaitObject::ListHeadType & wlist,
IWaitObject * wobj )
inlinestaticinherited

Called by kernel when a waiting task is being removed (timeout expired, wait aborted, task terminated etc.).

Parameters
[in]wlistWait list.
[in]wobjWait object to remove from the wait list.
Note
Utility for RemoveWaitObject and ARM TrustZone support.

Definition at line 696 of file stk_common.h.

697 {
698 STK_ASSERT(wobj->GetHead() == &wlist);
699 wlist.Unlink(wobj);
700 }

References stk::detail::DListEntry< T, TClosedLoop >::GetHead(), STK_ASSERT, and stk::detail::DListHead< T, TClosedLoop >::Unlink().

Referenced by stk::SyncObjectBase::RemoveWaitObject().

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

◆ RemoveWaitObject() [2/2]

void stk::SyncObjectBase::RemoveWaitObject ( IWaitObject * wobj)
inlineoverridevirtualinherited

Called by kernel when a waiting task is being removed (timeout expired, wait aborted, task terminated etc.).

Parameters
[in]wobjWait object to remove from the wait list.
Note
Must be called inside the critical section (see hw::CriticalSection, sync::ScopedCrticalSection).

Implements stk::ISyncObject.

Definition at line 260 of file stk_helper.h.

261 {
263 }
static void RemoveWaitObject(IWaitObject::ListHeadType &wlist, IWaitObject *wobj)
Called by kernel when a waiting task is being removed (timeout expired, wait aborted,...
Definition stk_common.h:696

References m_wait_list, and stk::ISyncObject::RemoveWaitObject().

Referenced by stk::sync::Event::RemoveWaitObject().

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

◆ SetTraceName()

void stk::ITraceable::SetTraceName ( const char * name)
inlineinherited

Set name.

Parameters
[in]nameNull-terminated string or NULL.
Note
If STK_SYNC_DEBUG_NAMES is 0 then calling this function has no effect.
Examples
sync/example.cpp.

Definition at line 617 of file stk_common.h.

618 {
619 #if STK_SYNC_DEBUG_NAMES
620 m_trace_name = name;
621 #else
622 STK_UNUSED(name);
623 #endif
624 }
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715

References STK_UNUSED.

Referenced by stk::memory::BlockMemoryPool::BlockMemoryPool(), stk::memory::BlockMemoryPool::BlockMemoryPool(), stk::memory::BytePool::BytePool(), stk::memory::BytePool::BytePool(), RunExample(), tx_block_pool_create(), tx_mutex_create(), and tx_queue_create().

Here is the caller graph for this function:

◆ Tick()

bool stk::ISyncObject::Tick ( Timeout elapsed_ticks)
inlinevirtualinherited

Called by kernel on every system tick to handle timeout logic of waiting tasks.

Implementation of ISyncObject::Tick, see ISyncObject. Placed here as it depends on hw namespace.

Parameters
[in]elapsed_ticksNumber of ticks elapsed between this and previous calls, in case of KERNEL_TICKLESS mode this value can be >1, for non-tickless mode it is always 1.
Returns
true if this synchronization object still has waiters with a finite timeout and requires further tick calls. false if the wait list is empty or all remaining waiters have infinite timeouts, signaling to the kernel that it may stop calling Tick() for this object until a new waiter is added.
Note
When this method returns false, the kernel unlinks this object from its active sync list. It will be re-linked automatically when the next waiter is added via AddWaitObject().
Does not need to be called inside critical section.

Definition at line 315 of file stk_helper.h.

316{
318
319 // note: ScopedCriticalSection usage
320 //
321 // Single-core: no critical section needed - Tick() runs from the tick ISR,
322 // which cannot be re-entered on the local core.
323 //
324 // Multi-core: critical section is required because the tick handler on
325 // each core may call Tick() concurrently for the same sync object,
326 // and ISyncObject::Tick() is not re-entrant.
327#if (STK_ARCH_CPU_COUNT > 1)
328 const hw::CriticalSection::ScopedLock cs_;
329#endif
330
331 IWaitObject *itr = detail::DListCast::ListEntryToParent<IWaitObject>(wlist.GetFirst());
332
333 while (itr != nullptr)
334 {
335 IWaitObject *const next = detail::DListCast::ListEntryToParent<IWaitObject>(itr->GetNext());
336
337 if (!itr->Tick(elapsed_ticks))
338 {
339 itr->Wake(true);
340 }
341
342 itr = next;
343 }
344
345 return !wlist.IsEmpty();
346}
DLHeadType ListHeadType
List head type for IWaitObject elements.
Definition stk_common.h:548
virtual IWaitObject::ListHeadType & GetMutableWaitList()=0
Get list of tasks blocked on this object.

References stk::detail::DListHead< T, TClosedLoop >::GetFirst(), GetMutableWaitList(), stk::detail::DListEntry< T, TClosedLoop >::GetNext(), stk::detail::DListHead< T, TClosedLoop >::IsEmpty(), stk::detail::DListCast::ListEntryToParent(), stk::IWaitObject::Tick(), and stk::IWaitObject::Wake().

Here is the call graph for this function:

◆ TimedLock()

bool stk::sync::Mutex::TimedLock ( Timeout timeout_ticks)
inline

Acquire lock.

Parameters
[in]timeout_ticksMaximum time to wait (ticks).
Note
Maximum number of recursive locks must not exceed 0xFFFEU.
Warning
ISR-safe only with timeout_ticks = NO_WAIT, ISR-unsafe otherwise.
Returns
True if lock acquired, false otherwise (timeout, cancellation or NO_WAIT on a busy mutex). Use TimedLockEx() to tell these apart.

Definition at line 94 of file stk_sync_mutex.h.

94{ return (TimedLockEx(timeout_ticks) == WAIT_RESULT_SIGNAL); }

References TimedLockEx(), and stk::WAIT_RESULT_SIGNAL.

Referenced by stk_mutex_timed_lock(), and TryLock().

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

◆ TimedLockEx()

EWaitResult stk::sync::Mutex::TimedLockEx ( Timeout timeout_ticks)
inline

Acquire lock, preserving the full wait outcome.

Parameters
[in]timeout_ticksMaximum time to wait (ticks).
Note
Maximum number of recursive locks must not exceed 0xFFFEU.
Warning
ISR-safe only with timeout_ticks = NO_WAIT, ISR-unsafe otherwise.
Returns
WAIT_RESULT_SIGNAL if the lock was acquired (note: here "signal" means "lock acquired", including the immediate and recursive paths where no notification was involved), WAIT_RESULT_TIMEOUT if the lock was busy and the timeout expired (or NO_WAIT was passed), WAIT_RESULT_CANCELED if the wait was cancelled via IKernel::CancelTaskWait(), WAIT_RESULT_FAIL if the kernel rejected the wait.

Definition at line 153 of file stk_sync_mutex.h.

154{
156 const TId current_tid = svc->GetTid();
157
158 ScopedCriticalSection cs_;
159
160 const TId owner_tid = m_owner_tid;
161
162 // NO_WAIT on a busy mutex is reported as an immediately-expired timeout
164
165 STK_ASSERT(current_tid != TID_NONE); // API contract: must be called inside STK task
166
167 // recursive path: already owned by the calling thread
168 if ((m_recursion_count != 0U) && (owner_tid == current_tid))
169 {
170 STK_ASSERT(m_recursion_count < RECURSION_MAX); // API contract: caller must not exceed max recursion depth
171
172 m_recursion_count = static_cast<uint16_t>(m_recursion_count + 1U);
173 result = WAIT_RESULT_SIGNAL;
174 }
175 // fast path: mutex is free
176 else if (m_recursion_count == 0U)
177 {
178 // kernel invariant: counter is zero so owner must be TID_NONE
179 if (owner_tid != TID_NONE)
180 {
182 }
183
185 m_owner_tid = current_tid;
186 __stk_full_memfence();
187
188 result = WAIT_RESULT_SIGNAL;
189 }
190 // slow path: block until available or timeout expires
191 else if (timeout_ticks != NO_WAIT)
192 {
193 STK_ASSERT(!hw::IsInsideISR()); // API contract: caller must not be in ISR for a blocking call
194
195 // boost priority of the owner to avoid priority inversion (in case of sched::SwitchStrategyFixedPriority,
196 // otherwise ignored by the kernel), noop if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
197 svc->InheritWeight(owner_tid, GetUserTaskFromTid(current_tid)->GetWeight());
198
199 // mutex owned by another thread (slow path/blocking)
200 result = svc->Wait(this, &cs_, timeout_ticks);
201
202 if (result != WAIT_RESULT_SIGNAL)
203 {
204 // kernel invariant: a wait that did not end in a signal must not leave this thread as the
205 // owner (Unlock() hands over ownership only together with a signal), otherwise the caller
206 // would be told it failed while owning a lock nobody will release
207 STK_ASSERT(m_owner_tid != current_tid);
208
209 // if owner did not change, undo priority boost to avoid stuck elevated priority: lookup for a
210 // higher weight within existing wait objects, noop if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
211 if (owner_tid == m_owner_tid)
212 {
213 svc->RestoreWeight(owner_tid, this);
214 }
215 }
216 else
217 {
218 // kernel invariant: if either condition is false, the low-level lock and the
219 // recursion counter are out of sync, this is an internal defect, not a caller error
220 if ((m_owner_tid != current_tid) || (m_recursion_count != 1U))
221 {
223 }
224 }
225 }
226 // try-lock variant: owned by someone else, but no-wait requested
227 else
228 {
229 // result is WAIT_RESULT_TIMEOUT already, noop
230 }
231
232 return result;
233}
static constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
Definition stk_common.h:280
@ WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_common.h:141
Word TId
Task (thread) id.
Definition stk_common.h:211
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
friend class IKernelService
Definition stk_common.h:660
static IKernelService * GetInstance()
Get CPU-local instance of the kernel service.
static const uint16_t RECURSION_MAX
maximum nesting depth

References stk::IKernelService::GetInstance(), stk::IKernelService::GetTid(), stk::GetUserTaskFromTid(), stk::SyncObjectBase::IKernelService, stk::IKernelService::InheritWeight(), stk::hw::IsInsideISR(), stk::KERNEL_PANIC_ASSERT, m_owner_tid, m_recursion_count, stk::NO_WAIT, RECURSION_MAX, stk::IKernelService::RestoreWeight(), STK_ASSERT, stk::STK_KERNEL_PANIC(), stk::TID_NONE, stk::IKernelService::Wait(), stk::WAIT_RESULT_SIGNAL, and stk::WAIT_RESULT_TIMEOUT.

Referenced by Lock(), pthread_mutex_timedlock(), stk_mutex_timed_lock_ex(), and TimedLock().

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

◆ TryLock()

bool stk::sync::Mutex::TryLock ( )
inlinevirtual

Try to acquire the lock without blocking.

Warning
ISR-safe.
Returns
True if lock acquired (including a recursive acquisition by the owner), false if the lock is owned by another thread.

Implements stk::IMutex.

Definition at line 112 of file stk_sync_mutex.h.

112{ return TimedLock(NO_WAIT); }

References stk::NO_WAIT, and TimedLock().

Referenced by pthread_mutex_trylock(), pthread_spin_trylock(), and stk_mutex_trylock().

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

◆ Unlink()

void stk::detail::DListEntry< ISyncObject, TClosedLoop >::Unlink ( )
inlineprivateinherited

Remove this entry from its current list.

Note
Called exclusively by DListHead::Unlink(). Patches the neighbours' pointers to bridge over this entry, then clears m_head, m_next, and m_prev to NULL so the entry is in a clean unlinked state.
Does not update DListHead::m_count or m_first / m_last — those are the responsibility of the calling DListHead::Unlink().

Definition at line 174 of file stk_linked_list.h.

175 {
176 if (m_prev != nullptr)
177 {
179 }
180
181 if (m_next != nullptr)
182 {
184 }
185
186 m_head = nullptr;
187 m_next = nullptr;
188 m_prev = nullptr;
189 }

◆ Unlock()

void stk::sync::Mutex::Unlock ( )
inlineoverridevirtual

Release lock.

Warning
ISR-safe.

Implements stk::IMutex.

Definition at line 259 of file stk_sync_mutex.h.

260{
261 const ScopedCriticalSection cs_;
262
264 (m_owner_tid != TID_NONE)); // API contract: caller must own the lock
265 STK_ASSERT(m_recursion_count != 0U); // API contract: must have matching Lock()
266
267 m_recursion_count = static_cast<uint16_t>(m_recursion_count - 1U);
268
269 if (m_recursion_count == 0U)
270 {
272
273 // restore priority of the owner, noop if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
274 if (m_owner_tid != TID_NONE)
275 {
276 svc->RestoreWeight(m_owner_tid);
277 }
278
279 if (!m_wait_list.IsEmpty())
280 {
281 // pass ownership directly to the first waiter (FIFO order)
282 IWaitObject *const waiter = detail::DListCast::ListEntryToParent<IWaitObject>(m_wait_list.GetFirst());
283
284 // transfer ownership to the waiter
286 m_owner_tid = waiter->GetTid();
287 __stk_full_memfence();
288
289 // wake up
290 waiter->Wake(false);
291
292 // boost priority from the highest-priority task still in wait list, skip the lookup if none left,
293 // noop if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
294 if (!m_wait_list.IsEmpty())
295 {
296 svc->InheritWeight(m_owner_tid,
298 }
299 }
300 else
301 {
302 // free completely if there are no waiters
304 __stk_full_memfence();
305 }
306 }
307}
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:374
Weight FindWeightHigherThan(Weight comp) const
Find higher weight within linked wait objects.
Definition stk_helper.h:349

References stk::ISyncObject::FindWeightHigherThan(), stk::IKernelService::GetInstance(), stk::GetTid(), stk::IWaitObject::GetTid(), stk::GetUserTaskFromTid(), stk::SyncObjectBase::IKernelService, stk::IKernelService::InheritWeight(), stk::detail::DListCast::ListEntryToParent(), m_owner_tid, m_recursion_count, stk::SyncObjectBase::m_wait_list, stk::IKernelService::RestoreWeight(), STK_ASSERT, stk::TID_NONE, and stk::IWaitObject::Wake().

Referenced by MqReceiveImpl(), MqSendImpl(), pthread_mutex_unlock(), pthread_once(), pthread_rwlock_unlock(), pthread_spin_unlock(), and stk_mutex_unlock().

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

◆ WakeAll() [1/2]

void stk::ISyncObject::WakeAll ( IWaitObject::ListHeadType & wlist)
inlinestaticinherited

Wake all tasks currently in the wait list.

Parameters
[in]wlistWait list.
Note
Each woken task is notified with timeout=false, indicating a successful signal (not a timeout expiry).
Does nothing if no tasks are currently waiting.
Utility for WakeAll and ARM TrustZone support.

Definition at line 752 of file stk_common.h.

753 {
754 for (IWaitObject *obj = detail::DListCast::ListEntryToParent<IWaitObject>(wlist.GetFirst());
755 obj != nullptr;
757 {
758 obj->Wake(false);
759 }
760 }

References stk::detail::DListHead< T, TClosedLoop >::GetFirst(), and stk::detail::DListCast::ListEntryToParent().

Here is the call graph for this function:

◆ WakeAll() [2/2]

void stk::SyncObjectBase::WakeAll ( )
inlineoverrideprotectedvirtualinherited

Wake all tasks currently in the wait list.

Note
Each woken task is notified with timeout=false, indicating a successful signal (not a timeout expiry).
Does nothing if no tasks are currently waiting.
Must be called inside the critical section (see hw::CriticalSection, sync::ScopedCrticalSection).

Implements stk::ISyncObject.

Definition at line 301 of file stk_helper.h.

302 {
303 IKernelService::GetInstance()->Wake(this, true);
304 }
virtual void Wake(ISyncObject *sobj, bool all)=0
Wake one or all tasks currently waiting on a synchronization object.

References stk::IKernelService::GetInstance(), and stk::IKernelService::Wake().

Referenced by stk::sync::ConditionVariable::NotifyAll_CS(), stk::sync::Event::Pulse(), and stk::sync::Event::Set().

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

◆ WakeOne() [1/2]

void stk::ISyncObject::WakeOne ( IWaitObject::ListHeadType & wlist)
inlinestaticinherited

Wake the first task in the wait list (FIFO order).

Parameters
[in]wlistWait list.
Note
The woken task is notified with timeout=false, indicating a successful signal (not a timeout expiry).
Does nothing if no tasks are currently waiting.
Utility for WakeOne and ARM TrustZone support.

Definition at line 736 of file stk_common.h.

737 {
738 IWaitObject *const obj = detail::DListCast::ListEntryToParent<IWaitObject>(wlist.GetFirst());
739 if (obj != nullptr)
740 {
741 obj->Wake(false);
742 }
743 }

References stk::detail::DListHead< T, TClosedLoop >::GetFirst(), stk::detail::DListCast::ListEntryToParent(), and stk::IWaitObject::Wake().

Here is the call graph for this function:

◆ WakeOne() [2/2]

void stk::SyncObjectBase::WakeOne ( )
inlineoverrideprotectedvirtualinherited

Wake the first task in the wait list (FIFO order).

Note
The woken task is notified with timeout=false, indicating a successful signal (not a timeout expiry).
Does nothing if no tasks are currently waiting.
Must be called inside the critical section (see hw::CriticalSection, sync::ScopedCrticalSection).

Implements stk::ISyncObject.

Definition at line 296 of file stk_helper.h.

297 {
298 IKernelService::GetInstance()->Wake(this, false);
299 }

References stk::IKernelService::GetInstance(), and stk::IKernelService::Wake().

Referenced by stk::sync::ConditionVariable::NotifyOne_CS(), stk::sync::Event::Pulse(), stk::sync::Event::Set(), and stk::sync::SemaphoreT< T >::TrySignalLimited().

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

Member Data Documentation

◆ m_head

DLHeadType* stk::detail::DListEntry< ISyncObject, TClosedLoop >::m_head
privateinherited

Owning list head, or NULL when the entry is not linked.

Definition at line 191 of file stk_linked_list.h.

◆ m_next

DLEntryType* stk::detail::DListEntry< ISyncObject, TClosedLoop >::m_next
privateinherited

Next entry in the list, or NULL (open list boundary) / first entry (closed loop).

Definition at line 192 of file stk_linked_list.h.

◆ m_owner_tid

TId stk::sync::Mutex::m_owner_tid
private

thread id of the current owner

Definition at line 145 of file stk_sync_mutex.h.

Referenced by GetOwner(), IsLocked(), Mutex(), TimedLockEx(), and Unlock().

◆ m_prev

DLEntryType* stk::detail::DListEntry< ISyncObject, TClosedLoop >::m_prev
privateinherited

Previous entry in the list, or NULL (open list boundary) / last entry (closed loop).

Definition at line 193 of file stk_linked_list.h.

◆ m_recursion_count

uint16_t stk::sync::Mutex::m_recursion_count
private

recursion depth

Definition at line 146 of file stk_sync_mutex.h.

Referenced by GetRecursionCount(), Mutex(), TimedLockEx(), and Unlock().

◆ m_wait_list

◆ RECURSION_MAX

const uint16_t stk::sync::Mutex::RECURSION_MAX = 0xFFFEU
static

maximum nesting depth

Definition at line 57 of file stk_sync_mutex.h.

Referenced by stk::pthread::PreLockCheck(), and TimedLockEx().


The documentation for this class was generated from the following file: