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 Member Functions

 Mutex ()
 Constructor.
 ~Mutex ()
 Destructor.
bool TimedLock (Timeout timeout_ticks)
 Acquire lock.
void Lock () override
 Acquire lock.
bool TryLock ()
 Acquire the lock.
void Unlock () override
 Release lock.
TId GetOwner () const
 Get owner of the mutex.
void SetTraceName (const char *name)
 Set name.
const char * GetTraceName () const
 Get name.

Private 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.

Private Member Functions

 Mutex (const Mutex &)=delete
Mutexoperator= (const Mutex &)=delete
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::ListHeadTypeGetWaitList () const override
 Get list of tasks blocked on this object.
IWaitObject::ListHeadTypeGetWaitList () override
 Get list of tasks blocked on this object.
void WakeOne () override
 Wake the first task in the wait list (FIFO order).
void WakeAll () override
 Wake all tasks currently in the wait list.
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.
DLHeadTypeGetHead ()
 Get the list head this entry currently belongs to.
DLEntryTypeGetNext ()
 Get the next entry in the list.
DLEntryTypeGetPrev ()
 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 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.

Static Private 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.

Private Attributes

TId m_owner_tid
 thread id of the current owner
uint16_t m_recursion_count
 recursion depth
IWaitObject::ListHeadType m_wait_list
 Tasks blocked on this object.
DLHeadTypem_head
 Owning list head, or NULL when the entry is not linked.
DLEntryTypem_next
 Next entry in the list, or NULL (open list boundary) / first entry (closed loop).
DLEntryTypem_prev
 Previous entry in the list, or NULL (open list boundary) / last entry (closed loop).

Static Private Attributes

static const uint16_t RECURSION_MAX = 0xFFFEU
 maximum nesting depth

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

Definition at line 54 of file stk_sync_mutex.h.

Member Typedef Documentation

◆ DLEntryType

typedef DListEntry<ISyncObject, TClosedLoop> stk::util::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::util::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 557 of file stk_common.h.

◆ ListHeadType

List head type for ISyncObject elements.

Definition at line 552 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 59 of file stk_sync_mutex.h.

60 {}
static constexpr TId TID_NONE
Reserved task/thread id representing zero/none thread id.
Definition stk_common.h:202
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 67 of file stk_sync_mutex.h.

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

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

◆ 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]wobjWait object representing blocked task.
Note
Utility for AddWaitObject and ARM TrustZone support.

Definition at line 563 of file stk_common.h.

564 {
565 STK_ASSERT(wobj->GetHead() == nullptr);
566 wlist.LinkBack(wobj);
567 }

References stk::util::DListEntry< T, TClosedLoop >::GetHead(), stk::util::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 253 of file stk_helper.h.

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

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::Tick, 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 334 of file stk_helper.h.

335{
336 Weight max_weight = NO_WEIGHT;
337 const IWaitObject *itr = util::DListCast::ListEntryToParent<const IWaitObject>(GetWaitList().GetFirst());
338
339 while (itr != nullptr)
340 {
341 const Weight w = GetUserTaskFromTid(itr->GetTid())->GetWeight();
342 if (w > max_weight)
343 {
344 max_weight = w;
345 }
346
348 }
349
350 return ((max_weight > comp) ? max_weight : NO_WEIGHT);
351}
static constexpr ITask * GetUserTaskFromTid(TId task_id) noexcept
Get task instance from its identifier.
Definition stk_arch.h:617
static constexpr Weight NO_WEIGHT
Weight value: weight is not set.
Definition stk_common.h:219
int32_t Weight
Weight value (aka priority).
Definition stk_common.h:170
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:834
static __stk_forceinline TTargetType * ListEntryToParent(TSourceType *const lentry)
Safely casts an intrusive list entry to its concrete parent container object type.

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

Referenced by stk::Kernel< stk::KERNEL_DYNAMIC|stk::KERNEL_SYNC|stk::KERNEL_TICKLESS,(16U), stk::SwitchStrategyFP32, stk::PlatformDefault >::OnRestoreWeight(), and stk::sync::Mutex::Unlock().

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

◆ GetHead()

DLHeadType * stk::util::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; }

◆ GetNext()

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

Get the next entry in the list.

Returns
Pointer to the next DListEntry, or NULL if this is the last entry (open list) or the first entry (closed loop, where next wraps to first).
Note
In a closed loop (TClosedLoop == true) this pointer is never NULL when the entry is linked.

Definition at line 98 of file stk_linked_list.h.

98{ return m_next; }

◆ GetOwner()

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

Get owner of the mutex.

Warning
ISR-safe.

Definition at line 99 of file stk_sync_mutex.h.

99{ return m_owner_tid; }

References m_owner_tid.

Referenced by uxSemaphoreGetCount(), xSemaphoreGetMutexHolder(), and xSemaphoreGetMutexHolderFromISR().

Here is the caller graph for this function:

◆ GetPrev()

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

Get the previous entry in the list.

Returns
Pointer to the previous DListEntry, or NULL if this is the first entry (open list) or the last entry (closed loop, where prev wraps to last).
Note
In a closed loop (TClosedLoop == true) this pointer is never NULL when the entry is linked.

Definition at line 114 of file stk_linked_list.h.

114{ return m_prev; }

◆ 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 515 of file stk_common.h.

516 {
517 #if STK_SYNC_DEBUG_NAMES
518 return m_trace_name;
519 #else
520 return nullptr;
521 #endif
522 }

◆ GetWaitList() [1/2]

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

Get list of tasks blocked on this object.

Note
Read-only access for diagnostics / telemetry.

Implements stk::ISyncObject.

Definition at line 263 of file stk_helper.h.

264 {
265 return m_wait_list;
266 }

References m_wait_list.

◆ GetWaitList() [2/2]

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

Get list of tasks blocked on this object.

Implements stk::ISyncObject.

Definition at line 290 of file stk_helper.h.

291 {
292 return m_wait_list;
293 }

References m_wait_list.

◆ IsLinked()

bool stk::util::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 127 of file stk_linked_list.h.

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

◆ Link()

void stk::util::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 162 of file stk_linked_list.h.

163 {
164 m_head = head;
165 m_next = next;
166 m_prev = prev;
167
168 if (m_prev != nullptr)
169 {
170 m_prev->m_next = this;
171 }
172
173 if (m_next != nullptr)
174 {
175 m_next->m_prev = this;
176 }
177 }
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.

Warning
ISR-unsafe.

Implements stk::IMutex.

Definition at line 83 of file stk_sync_mutex.h.

#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:654
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:208

References STK_UNUSED, TimedLock(), and stk::WAIT_INFINITE.

Referenced by stk_mutex_lock().

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

◆ operator const ISyncObject *()

stk::util::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 141 of file stk_linked_list.h.

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

◆ operator ISyncObject *()

stk::util::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 134 of file stk_linked_list.h.

134{ 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]wobjWait object to remove from the wait list.
Note
Utility for AddWaitObject and ARM TrustZone support.

Definition at line 579 of file stk_common.h.

580 {
581 STK_ASSERT(wobj->GetHead() == &wlist);
582 wlist.Unlink(wobj);
583 }

References stk::util::DListEntry< T, TClosedLoop >::GetHead(), STK_ASSERT, and stk::util::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 258 of file stk_helper.h.

259 {
261 }
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:579

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.

Definition at line 503 of file stk_common.h.

504 {
505 #if STK_SYNC_DEBUG_NAMES
506 m_trace_name = name;
507 #else
508 STK_UNUSED(name);
509 #endif
510 }

References STK_UNUSED.

Referenced by stk::memory::BlockMemoryPool::BlockMemoryPool(), and stk::memory::BlockMemoryPool::BlockMemoryPool().

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 299 of file stk_helper.h.

300{
302
303 // note: ScopedCriticalSection usage
304 //
305 // Single-core: no critical section needed - Tick() runs inside the
306 // SysTick ISR which already executes with interrupts disabled, making
307 // re-entrancy impossible on the local core.
308 //
309 // Multi-core: critical section is required because the tick handler on
310 // each core may call Tick() concurrently for the same Semaphore instance,
311 // and ISyncObject::Tick() is not re-entrant.
312#if (STK_ARCH_CPU_COUNT > 1)
313 const hw::CriticalSection::ScopedLock cs_;
314#endif
315
316 IWaitObject *itr = util::DListCast::ListEntryToParent<IWaitObject>(wlist.GetFirst());
317
318 while (itr != nullptr)
319 {
320 IWaitObject *const next = util::DListCast::ListEntryToParent<IWaitObject>(itr->GetNext());
321
322 if (!itr->Tick(elapsed_ticks))
323 {
324 itr->Wake(true);
325 }
326
327 itr = next;
328 }
329
330 return !wlist.IsEmpty();
331}
DLHeadType ListHeadType
List head type for IWaitObject elements.
Definition stk_common.h:449

References stk::util::DListHead< T, TClosedLoop >::GetFirst(), stk::util::DListEntry< T, TClosedLoop >::GetNext(), GetWaitList(), stk::util::DListHead< T, TClosedLoop >::IsEmpty(), stk::util::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 if timeout occurred.

Definition at line 114 of file stk_sync_mutex.h.

115{
117 const TId current_tid = svc->GetTid();
118
119 ScopedCriticalSection cs_;
120
121 const TId owner_tid = m_owner_tid;
122 bool success = false;
123
124 // recursive path: already owned by the calling thread
125 if ((m_recursion_count != 0U) && (owner_tid == current_tid))
126 {
127 STK_ASSERT(m_recursion_count < RECURSION_MAX); // API contract: caller must not exceed max recursion depth
128
129 m_recursion_count = static_cast<uint16_t>(m_recursion_count + 1U);
130 success = true;
131 }
132 // fast path: mutex is free
133 else if (m_recursion_count == 0U)
134 {
135 // kernel invariant: counter is zero so owner must be TID_NONE
136 if (owner_tid != TID_NONE)
137 {
139 }
140
142 m_owner_tid = current_tid;
143 __stk_full_memfence();
144
145 success = true;
146 }
147 // slow path: block until available or timeout expires
148 else if (timeout_ticks != NO_WAIT)
149 {
150 STK_ASSERT(!hw::IsInsideISR()); // API contract: caller must not be in ISR for a blocking call
151
152 // boost priority of the owner to avoid priority inversion (in case of SwitchStrategyFixedPriority,
153 // otherwise ignored by the kernel), noop if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
154 svc->InheritWeight(owner_tid, GetUserTaskFromTid(current_tid)->GetWeight());
155
156 // mutex owned by another thread (slow path/blocking)
157 if (svc->Wait(this, &cs_, timeout_ticks) == WAIT_RESULT_TIMEOUT)
158 {
159 // if owner did not change, undo priority boost to avoid stuck elevated priority: lookup for a
160 // higher weight within existing wait objects, noop if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
161 if (owner_tid == m_owner_tid)
162 {
163 svc->RestoreWeight(owner_tid, this);
164 }
165
166 success = false;
167 }
168 else
169 {
170 // kernel invariant: if either condition is false, the low-level lock and the
171 // recursion counter are out of sync, this is an internal defect, not a caller error
172 if ((m_owner_tid != current_tid) || (m_recursion_count != 1U))
173 {
175 }
176
177 success = true;
178 }
179 }
180 // try-lock variant: owned by someone else, but no-wait requested
181 else
182 {
183 // success is false already, noop
184 }
185
186 return success;
187}
static constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
Definition stk_common.h:214
@ WAIT_RESULT_TIMEOUT
The wake was caused by a timeout expiry.
Definition stk_common.h:121
static __stk_forceinline void STK_KERNEL_PANIC(stk::EKernelPanicId id)
Called when the kernel detects an unrecoverable internal fault.
Definition stk_arch.h:75
Word TId
Task (thread) id.
Definition stk_common.h:145
@ KERNEL_PANIC_ASSERT
Internal assertion failed (maps from STK_ASSERT).
Definition stk_common.h:62
bool IsInsideISR()
Check whether the CPU is currently executing inside a hardware interrupt service routine (ISR).
friend class IKernelService
Definition stk_common.h:545
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(), and stk::WAIT_RESULT_TIMEOUT.

Referenced by Lock(), osMutexAcquire(), stk_mutex_timed_lock(), TryLock(), and xSemaphoreTake().

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

◆ TryLock()

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

Acquire the lock.

Warning
ISR-safe.
Returns
True if lock acquired, false if lock is already acquired by another task.

Definition at line 89 of file stk_sync_mutex.h.

89{ return TimedLock(NO_WAIT); }

References stk::NO_WAIT, and TimedLock().

Referenced by stk_mutex_trylock().

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

◆ Unlink()

void stk::util::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 186 of file stk_linked_list.h.

187 {
188 if (m_prev != nullptr)
189 {
191 }
192
193 if (m_next != nullptr)
194 {
196 }
197
198 m_head = nullptr;
199 m_next = nullptr;
200 m_prev = nullptr;
201 }

◆ Unlock()

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

Release lock.

Warning
ISR-safe.

Implements stk::IMutex.

Definition at line 193 of file stk_sync_mutex.h.

194{
195 const ScopedCriticalSection cs_;
196
197 STK_ASSERT(m_owner_tid == GetTid()); // API contract: caller must own the lock
198 STK_ASSERT(m_recursion_count != 0U); // API contract: must have matching Lock()
199
200 m_recursion_count = static_cast<uint16_t>(m_recursion_count - 1U);
201
202 if (m_recursion_count == 0U)
203 {
205
206 // restore priority of the owner, noop if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
207 svc->RestoreWeight(m_owner_tid);
208
209 if (!m_wait_list.IsEmpty())
210 {
211 // pass ownership directly to the first waiter (FIFO order)
212 IWaitObject *const waiter = util::DListCast::ListEntryToParent<IWaitObject>(m_wait_list.GetFirst());
213
214 // transfer ownership to the waiter
216 m_owner_tid = waiter->GetTid();
217 __stk_full_memfence();
218
219 // wake up
220 waiter->Wake(false);
221
222 // boost priority from the highest-priority task currently in wait list,
223 // noop if the list is empty or if ISwitchStrategy::PRIORITY_INHERITANCE_API = 0
224 svc->InheritWeight(m_owner_tid,
226 }
227 else
228 {
229 // free completely if there are no waiters
231 __stk_full_memfence();
232 }
233 }
234}
static TId GetTid()
Get task/thread Id of the calling task.
Definition stk_helper.h:359
Weight FindWeightHigherThan(Weight comp) const
Find higher weight within linked wait objects.
Definition stk_helper.h:334

References stk::ISyncObject::FindWeightHigherThan(), stk::IKernelService::GetInstance(), stk::GetTid(), stk::IWaitObject::GetTid(), stk::GetUserTaskFromTid(), stk::SyncObjectBase::IKernelService, stk::IKernelService::InheritWeight(), stk::util::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 stk_mutex_unlock(), and xSemaphoreGive().

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.

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 AddWaitObject and ARM TrustZone support.

Definition at line 632 of file stk_common.h.

633 {
634 while (IWaitObject *const obj = util::DListCast::ListEntryToParent<IWaitObject>(wlist.GetFirst()))
635 {
636 obj->Wake(false);
637 }
638 }

References stk::util::DListHead< T, TClosedLoop >::GetFirst(), and stk::util::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 285 of file stk_helper.h.

286 {
287 IKernelService::GetInstance()->Wake(this, true);
288 }
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).

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 AddWaitObject and ARM TrustZone support.

Definition at line 618 of file stk_common.h.

619 {
620 if (IWaitObject *const obj = util::DListCast::ListEntryToParent<IWaitObject>(wlist.GetFirst()))
621 {
622 obj->Wake(false);
623 }
624 }

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

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 280 of file stk_helper.h.

281 {
282 IKernelService::GetInstance()->Wake(this, false);
283 }

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::Semaphore::Signal().

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

Member Data Documentation

◆ m_head

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

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

Definition at line 203 of file stk_linked_list.h.

◆ m_next

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

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

Definition at line 204 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 106 of file stk_sync_mutex.h.

Referenced by GetOwner(), Mutex(), TimedLock(), and Unlock().

◆ m_prev

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

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

Definition at line 205 of file stk_linked_list.h.

◆ m_recursion_count

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

recursion depth

Definition at line 107 of file stk_sync_mutex.h.

Referenced by Mutex(), TimedLock(), and Unlock().

◆ m_wait_list

◆ RECURSION_MAX

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

maximum nesting depth

Definition at line 104 of file stk_sync_mutex.h.

Referenced by TimedLock().


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