ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
mutex.c File Reference

Per-thread mutex lock stack for deadlock detection. More...

Go to the source code of this file.

Data Structures

struct  thread_lock_stack_t
struct  thread_registry_entry_t
 thread lock stack keeps the values that move through the subsystem: depth, guard, telemetry. Some members are pointers into caller- or subsystem-owned memory, so lifetime follows the API that populated them rather than the struct copy itself. More...
struct  deadlock_state_t
struct  cond_deadlock_snapshot_t
 deadlock state is intentionally a small, concrete record. Fields such as count give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystem—not independently managed. More...
struct  cond_deadlock_entry_t
struct  cond_deadlock_batch_t
 When code needs to work with cond deadlock entry, it keeps state here instead of scattering it across globals. Initialization establishes the handles and sizes; teardown must release any allocation, lock, thread, or callback context recorded in those fields. More...

Macros

#define DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE   4096
#define DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE   256
#define DEBUG_MUTEX_MUTEX_NAME_BUFFER_SIZE   256
#define DEBUG_MUTEX_HELD_BY_NAME_BUFFER_SIZE   256
#define DEBUG_MUTEX_STUCK_BUFFER_SIZE   64
#define DEBUG_MUTEX_COND_BUFFER_SIZE   1024
#define DEBUG_MUTEX_NAME_BUFFER_SIZE   256
#define MUTEX_STACK_MAX_DEPTH   64
#define MAX_THREADS   256
#define MAX_CYCLE_MUTEXES   16
#define MAX_CYCLE_LEN   64
 DFS-based cycle detection in the waits-for graph Returns cycle start index if found, -1 otherwise Fills cycle_path with indices of threads in the cycle (if found).
#define COND_DEADLOCK_THRESHOLD_NS   (5ULL * 1000000000ULL)

Functions

void mutex_stack_push_pending (uintptr_t mutex_key, const char *mutex_name)
 Push a mutex onto the current thread's lock stack (PENDING state).
void mutex_stack_push_locked (uintptr_t mutex_key, const char *mutex_name)
void mutex_stack_mark_locked (uintptr_t mutex_key)
 Mark the top of the current thread's lock stack as LOCKED (transitions PENDING -> LOCKED).
void mutex_stack_pop (uintptr_t mutex_key)
 Pop the top mutex from the current thread's lock stack (unlock).
int mutex_stack_get_current (mutex_stack_entry_t *out_entries, int max_entries)
 Get the current thread's lock stack.
int mutex_stack_get_all_threads (mutex_stack_entry_t ***out_stacks, int **out_stack_counts, int *out_thread_count)
 Get all threads' lock stacks for deadlock analysis.
void mutex_stack_free_all_threads (mutex_stack_entry_t **stacks, int *stack_counts, int thread_count)
 Free memory allocated by mutex_stack_get_all_threads().
bool mutex_stack_try_snapshot (mutex_wait_snapshot_t *waits, size_t capacity, size_t *count, bool *limited)
void mutex_stack_detect_deadlocks (void)
 Detect circular wait deadlocks using DFS-based cycle detection.
bool debug_sync_is_cleanup_in_progress (void)
void debug_sync_check_cond_deadlocks (void)
 The useful part of cond deadlock batch is in entries, count: together they describe what is pending, who owns it, and how much data is valid. Keep the object with its parent operation and use the parent cleanup path.
int mutex_stack_init (void)
 Initialize mutex stack system.
void mutex_stack_cleanup_current_thread (void)
 Cleanup TLS stack for current thread Explicitly frees the thread-local mutex stack. Used to prevent leaks when TLS destructors might not run reliably (e.g., before TLS key deletion).
void mutex_stack_cleanup (void)
 Cleanup mutex stack system.

Detailed Description

Per-thread mutex lock stack for deadlock detection.

Date
February 2026

Tracks which mutexes are held and pending per thread. Detects circular wait patterns (classic deadlock condition).

Definition in file mutex.c.

Macro Definition Documentation

◆ COND_DEADLOCK_THRESHOLD_NS

#define COND_DEADLOCK_THRESHOLD_NS   (5ULL * 1000000000ULL)

Definition at line 811 of file mutex.c.

Referenced by debug_sync_check_cond_deadlocks().

◆ DEBUG_MUTEX_COND_BUFFER_SIZE

#define DEBUG_MUTEX_COND_BUFFER_SIZE   1024

Definition at line 8 of file mutex.c.

◆ DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE

#define DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE   4096

Definition at line 3 of file mutex.c.

Referenced by mutex_stack_detect_deadlocks().

◆ DEBUG_MUTEX_HELD_BY_NAME_BUFFER_SIZE

#define DEBUG_MUTEX_HELD_BY_NAME_BUFFER_SIZE   256

Definition at line 6 of file mutex.c.

Referenced by mutex_stack_detect_deadlocks().

◆ DEBUG_MUTEX_MUTEX_NAME_BUFFER_SIZE

#define DEBUG_MUTEX_MUTEX_NAME_BUFFER_SIZE   256

Definition at line 5 of file mutex.c.

Referenced by mutex_stack_detect_deadlocks().

◆ DEBUG_MUTEX_NAME_BUFFER_SIZE

#define DEBUG_MUTEX_NAME_BUFFER_SIZE   256

Definition at line 9 of file mutex.c.

◆ DEBUG_MUTEX_STUCK_BUFFER_SIZE

#define DEBUG_MUTEX_STUCK_BUFFER_SIZE   64

Definition at line 7 of file mutex.c.

◆ DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE

#define DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE   256

Definition at line 4 of file mutex.c.

Referenced by mutex_stack_detect_deadlocks().

◆ MAX_CYCLE_LEN

#define MAX_CYCLE_LEN   64

DFS-based cycle detection in the waits-for graph Returns cycle start index if found, -1 otherwise Fills cycle_path with indices of threads in the cycle (if found).

Definition at line 477 of file mutex.c.

Referenced by mutex_stack_detect_deadlocks(), and mutex_stack_try_snapshot().

◆ MAX_CYCLE_MUTEXES

#define MAX_CYCLE_MUTEXES   16

Definition at line 98 of file mutex.c.

Referenced by mutex_stack_detect_deadlocks().

◆ MAX_THREADS

#define MAX_THREADS   256

Definition at line 62 of file mutex.c.

Referenced by mutex_stack_detect_deadlocks(), and mutex_stack_try_snapshot().

◆ MUTEX_STACK_MAX_DEPTH

#define MUTEX_STACK_MAX_DEPTH   64

Definition at line 40 of file mutex.c.

Referenced by mutex_stack_get_all_threads(), and mutex_stack_try_snapshot().

Function Documentation

◆ debug_sync_is_cleanup_in_progress()

bool debug_sync_is_cleanup_in_progress ( void )
extern

◆ mutex_stack_cleanup()

void mutex_stack_cleanup ( void )

Cleanup mutex stack system.

Definition at line 1064 of file mutex.c.

1064 {
1065 // Signal shutdown to prevent new allocations from threads still running
1066 atomic_store_bool(&g_shutting_down, true);
1067
1068 // Call only after tracked workers stop. Windows FLS key deletion invokes
1069 // destructors; POSIX key deletion does not. Delete first so those callbacks
1070 // retire their entries before we free any remaining allocations.
1071 if (atomic_load_bool(&g_tls_initialized)) {
1072 platform_tls_key_delete(g_tls_mutex_stack);
1073 atomic_store_bool(&g_tls_initialized, false);
1074 }
1075 registry_lock();
1076 int count = atomic_load_int(&g_thread_registry_count);
1077 for (int i = 0; i < count; ++i) {
1078 free(g_thread_registry[i].stack);
1079 g_thread_registry[i].stack = NULL;
1080 }
1081 registry_unlock();
1082
1083 // Clear registry on cleanup using atomic operations
1084 atomic_store_int(&g_thread_registry_count, 0);
1085}
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_int(atomic_t *a, int value)
Atomically store an int value.
int atomic_load_int(atomic_t *a)
Atomically load an int value.

References atomic_load_bool(), atomic_load_int(), atomic_store_bool(), and atomic_store_int().

Referenced by asciichat_shared_destroy().

◆ mutex_stack_cleanup_current_thread()

void mutex_stack_cleanup_current_thread ( void )

Cleanup TLS stack for current thread Explicitly frees the thread-local mutex stack. Used to prevent leaks when TLS destructors might not run reliably (e.g., before TLS key deletion).

Definition at line 1028 of file mutex.c.

1028 {
1029 // Explicitly free the current thread's TLS stack
1030 // This is used to prevent leaks when TLS destructors might not run reliably
1031 // (e.g., debug threads exiting before mutex_stack_cleanup() deletes the TLS
1032 // key)
1033
1034 if (!atomic_load_bool(&g_tls_initialized)) {
1035 return; // TLS not initialized, nothing to clean up
1036 }
1037
1038 thread_lock_stack_t *stack =
1039 (thread_lock_stack_t *)platform_tls_get(g_tls_mutex_stack);
1040 if (!stack) {
1041 return; // No stack allocated for this thread
1042 }
1043
1044 // Clear from TLS
1045 platform_tls_set(g_tls_mutex_stack, NULL);
1046
1047 // Update registry if this thread is registered
1048 thread_id_t current_thread = thread_self();
1049 registry_lock();
1050 int count = atomic_load_int(&g_thread_registry_count);
1051 for (int i = 0; i < count; i++) {
1052 if (thread_equal(g_thread_registry[i].thread_id, current_thread) &&
1053 g_thread_registry[i].stack == stack) {
1054 g_thread_registry[i].stack = NULL; // Mark as freed in registry
1055 break;
1056 }
1057 }
1058
1059 // Free the stack (raw free to match raw malloc above)
1060 free(stack);
1061 registry_unlock();
1062}

References atomic_load_bool(), and atomic_load_int().

◆ mutex_stack_detect_deadlocks()

void mutex_stack_detect_deadlocks ( void )

Detect circular wait deadlocks using DFS-based cycle detection.

Detect and log circular wait deadlocks.

Detects both same-thread and multi-thread deadlock patterns of any length:

Same-thread deadlock:

  • Thread tries to acquire a mutex it already holds (recursive lock on non-recursive mutex)

Multi-thread circular wait (2-way, 3-way, N-way):

  • Uses DFS to detect cycles in the "waits-for" graph
  • Reports all threads involved in the cycle

Definition at line 656 of file mutex.c.

656 {
657 // Fixed scratch avoids allocating one list per thread on every 100 ms scan.
658 // Skip a busy snapshot rather than interfering with the threads being
659 // observed.
660 static thread_lock_stack_t snapshots[MAX_THREADS];
661 static thread_id_t ids[MAX_THREADS];
662 static atomic_flag sampling = ATOMIC_FLAG_INIT;
663 if (atomic_flag_test_and_set(&sampling))
664 return;
665 uint64_t expected = 0;
666 if (!atomic_compare_exchange_strong(&g_registry_guard.impl, &expected, 1)) {
667 atomic_flag_clear(&sampling);
668 return;
669 }
670 int thread_count = atomic_load_int_impl(&g_thread_registry_count);
671 bool complete = true;
672 for (int i = 0; i < thread_count; ++i) {
673 thread_lock_stack_t *src = g_thread_registry[i].stack;
674 ids[i] = g_thread_registry[i].thread_id;
675 snapshots[i].depth = 0;
676 if (!src)
677 continue;
678 expected = 0;
679 if (!atomic_compare_exchange_strong(&src->guard.impl, &expected, 1)) {
680 complete = false;
681 break;
682 }
683 snapshots[i].depth = src->depth;
684 memcpy(snapshots[i].stack, src->stack,
685 (size_t)src->depth * sizeof(mutex_stack_entry_t));
686 atomic_store(&src->guard.impl, 0);
687 }
688 atomic_store(&g_registry_guard.impl, 0);
689 if (!complete) {
690 atomic_flag_clear(&sampling);
691 return;
692 }
693
694 // Check each thread for deadlock conditions
695 for (int i = 0; i < thread_count; i++) {
696 thread_lock_stack_t *stack_a = &snapshots[i];
697 uintptr_t waiting_for = thread_waiting_for_mutex(stack_a);
698
699 if (waiting_for == 0)
700 continue; // Thread not waiting
701
702 // Same-thread deadlock: thread trying to acquire a mutex it already holds
703 if (thread_holds_mutex(stack_a, waiting_for)) {
704 log_error(
705 "%s",
708 "╔═══════════════════════════════════════════════════════════╗"));
709 log_error(
710 "%s",
713 "║ ⚠️ DEADLOCK DETECTED: Same-thread Recursive Lock ⚠️ ║"));
714 log_error(
715 "%s",
718 "╚═══════════════════════════════════════════════════════════╝"));
719 log_error(" Thread Address: 0x%lx", (unsigned long)ids[i]);
720 log_error(" Mutex: 0x%lx", waiting_for);
721 log_error(" Issue: Thread attempts recursive lock on "
722 "non-recursive mutex");
723 continue;
724 }
725
726 // Multi-thread circular wait: use DFS to detect cycles
727 int cycle_path[MAX_CYCLE_LEN];
728 int cycle_len = 0;
729 int cycle_start =
730 detect_cycle_dfs(snapshots, thread_count, i, cycle_path, &cycle_len);
731
732 if (cycle_start >= 0 && cycle_len > 1) {
733 // Collect mutexes involved in this deadlock
734 uintptr_t cycle_mutexes[MAX_CYCLE_MUTEXES];
735 int mutex_count = 0;
736 for (int k = 0; k < cycle_len && mutex_count < MAX_CYCLE_MUTEXES; k++) {
737 int thread_idx = cycle_path[k];
738 thread_lock_stack_t *stack = &snapshots[thread_idx];
739 uintptr_t waiting_for = thread_waiting_for_mutex(stack);
740 if (waiting_for != 0) {
741 cycle_mutexes[mutex_count++] = waiting_for;
742 }
743 }
744
745 // Check if mutexes are different from last deadlock
746 bool is_new_deadlock =
747 deadlock_mutexes_changed(cycle_mutexes, mutex_count);
748 if (is_new_deadlock) {
749 update_deadlock_state(cycle_mutexes, mutex_count);
750 }
751
752 // Cycle detected! Build complete message in one string
753 char cycle_msg[DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE];
754 int msg_len = 0;
755
756 // Leading newline and header box
757 msg_len +=
758 snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len, "\n%s\n",
760 "╔═════════════════════════════════╗"));
761 msg_len +=
762 snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len, "%s\n",
764 "║ DEADLOCK: Circular Wait Cycle ║"));
765 msg_len +=
766 snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len, "%s\n",
768 "╚═════════════════════════════════╝"));
769
770 // Print each thread in the cycle
771 for (int k = 0; k < cycle_len; k++) {
772 int thread_idx = cycle_path[k];
773 int next_thread_idx = cycle_path[(k + 1) % cycle_len];
774
775 thread_lock_stack_t *current_stack = &snapshots[thread_idx];
776 uintptr_t current_waiting = thread_waiting_for_mutex(current_stack);
777
778 char thread_name[DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE],
781 NAMED_GET_BY_PTR((uintptr_t)ids[thread_idx], thread_name,
782 sizeof(thread_name));
783 NAMED_GET_BY_PTR((uintptr_t)current_waiting, mutex_name,
784 sizeof(mutex_name));
785 NAMED_GET_BY_PTR((uintptr_t)ids[next_thread_idx], held_by_name,
786 sizeof(held_by_name));
787
788 msg_len += snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len,
789 " T%d: %s waits for %s (held by %s)%s", k + 1,
790 thread_name, mutex_name, held_by_name,
791 k < cycle_len - 1 ? "\n" : "");
792 }
793
794 // Log repeated deadlock detections (skip first call, throttle subsequent
795 // ones)
796 if (!is_new_deadlock) {
797 log_error_every(1000000, "%s", cycle_msg); // 1000000 µs = 1 second
798 }
799 }
800 }
801
802 atomic_flag_clear(&sampling);
803}
int atomic_load_int_impl(const atomic_t *a)
@ LOG_COLOR_ERROR
Definition color.h:11
unsigned long long uint64_t
#define NAMED_GET_BY_PTR(key, buffer, size)
Get name of a pointer/key or format as address fallback.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
const char * colored_string(log_color_t color, const char *text)
Build a colored string for terminal output.
#define log_error_every(interval_us, fmt,...)
Rate-limited ERROR logging.
Definition log/log.h:728
#define MAX_CYCLE_MUTEXES
Definition mutex.c:98
#define DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE
Definition mutex.c:4
#define DEBUG_MUTEX_MUTEX_NAME_BUFFER_SIZE
Definition mutex.c:5
#define MAX_CYCLE_LEN
DFS-based cycle detection in the waits-for graph Returns cycle start index if found,...
Definition mutex.c:477
#define MAX_THREADS
Definition mutex.c:62
#define DEBUG_MUTEX_HELD_BY_NAME_BUFFER_SIZE
Definition mutex.c:6
#define DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE
Definition mutex.c:3
Definition mutex.h:44
mutex_stack_entry_t stack[64]
Definition mutex.c:43
atomic_t guard
Definition mutex.c:45

References atomic_load_int_impl(), colored_string(), DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE, DEBUG_MUTEX_HELD_BY_NAME_BUFFER_SIZE, DEBUG_MUTEX_MUTEX_NAME_BUFFER_SIZE, DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE, thread_lock_stack_t::depth, thread_lock_stack_t::guard, LOG_COLOR_ERROR, log_error, log_error_every, MAX_CYCLE_LEN, MAX_CYCLE_MUTEXES, MAX_THREADS, NAMED_GET_BY_PTR, and thread_lock_stack_t::stack.

◆ mutex_stack_free_all_threads()

void mutex_stack_free_all_threads ( mutex_stack_entry_t ** stacks,
int * stack_counts,
int thread_count )

Free memory allocated by mutex_stack_get_all_threads().

Definition at line 407 of file mutex.c.

408 {
409
410 if (!stacks || !stack_counts)
411 return;
412
413 for (int i = 0; i < thread_count; i++) {
414 SAFE_FREE(stacks[i]);
415 }
416
417 SAFE_FREE(stacks);
418 SAFE_FREE(stack_counts);
419}
#define SAFE_FREE(ptr)

References SAFE_FREE.

◆ mutex_stack_get_all_threads()

int mutex_stack_get_all_threads ( mutex_stack_entry_t *** out_stacks,
int ** out_stack_counts,
int * out_thread_count )

Get all threads' lock stacks for deadlock analysis.

Allocates memory for all thread stacks. Caller must free with mutex_stack_free_all_threads().

Parameters
out_stacksPointer to array of stacks (one per thread)
out_stack_countsArray of stack sizes corresponding to out_stacks
out_thread_countNumber of threads with lock stacks
Returns
0 on success, -1 on error

Definition at line 351 of file mutex.c.

352 {
353
354 if (!out_stacks || !out_stack_counts || !out_thread_count) {
355 return -1;
356 }
357
358 // Read the thread count with acquire semantics (lock-free, no mutex needed)
359 // Use memory_order_seq_cst to ensure we get a consistent snapshot
360 int thread_count = atomic_load_int(&g_thread_registry_count);
361
362 // Allocate arrays for threads in the registry
363 // Note: SAFE_MALLOC takes bytes as first parameter, not count
364 *out_stacks = SAFE_CALLOC(thread_count, sizeof(mutex_stack_entry_t *),
366 *out_stack_counts = SAFE_CALLOC(thread_count, sizeof(int), int *);
367
368 if (!*out_stacks || !*out_stack_counts) {
369 SAFE_FREE(*out_stacks);
370 SAFE_FREE(*out_stack_counts);
371 return -1;
372 }
373
374 // Copy each thread's stack from the registry
375 // Note: the thread count can change concurrently, so we re-read it in the
376 // loop to avoid accessing out-of-bounds memory if threads exit during
377 // iteration
378 for (int i = 0; i < thread_count; i++) {
379 // Re-check thread count in case registry shrank
380 int current_registry_count = atomic_load_int(&g_thread_registry_count);
381 if (i >= current_registry_count) {
382 break;
383 }
384
385 // Allocate before locking because tracked allocation updates the lock
386 // stack.
387 (*out_stacks)[i] =
390 (*out_stack_counts)[i] = 0;
391 registry_lock();
392 thread_lock_stack_t *src = g_thread_registry[i].stack;
393 if (src) {
394 stack_lock(src);
395 int depth = src->depth;
396 (*out_stack_counts)[i] = depth;
397 memcpy((*out_stacks)[i], src->stack, depth * sizeof(mutex_stack_entry_t));
398 stack_unlock(src);
399 }
400 registry_unlock();
401 }
402
403 *out_thread_count = thread_count;
404 return 0;
405}
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
#define MUTEX_STACK_MAX_DEPTH
Definition mutex.c:40

References atomic_load_int(), thread_lock_stack_t::depth, MUTEX_STACK_MAX_DEPTH, SAFE_CALLOC, SAFE_FREE, SAFE_MALLOC, and thread_lock_stack_t::stack.

◆ mutex_stack_get_current()

int mutex_stack_get_current ( mutex_stack_entry_t * out_entries,
int max_entries )

Get the current thread's lock stack.

Parameters
out_entriesPointer to array where entries will be stored
max_entriesMaximum number of entries to return
Returns
Number of entries in the stack (may be > max_entries if truncated)

Definition at line 333 of file mutex.c.

333 {
334 thread_lock_stack_t *stack = get_thread_local_stack();
335 if (!stack || !out_entries) {
336 return 0;
337 }
338
339 stack_lock(stack);
340 int depth = stack->depth;
341 int count = (depth < max_entries) ? depth : max_entries;
342 memcpy(out_entries, stack->stack, count * sizeof(mutex_stack_entry_t));
343 stack_unlock(stack);
344 return depth; // Return actual depth even if truncated
345}

References thread_lock_stack_t::depth, and thread_lock_stack_t::stack.

◆ mutex_stack_init()

int mutex_stack_init ( void )

Initialize mutex stack system.

Returns
0 on success, -1 on error

Definition at line 1020 of file mutex.c.

1020 {
1021#ifndef NDEBUG
1022 atomic_store(&g_next_cond_check_ns, 0);
1023#endif
1024 // No initialization needed - registry uses lock-free atomic operations
1025 return 0;
1026}

◆ mutex_stack_mark_locked()

void mutex_stack_mark_locked ( uintptr_t mutex_key)

Mark the top of the current thread's lock stack as LOCKED (transitions PENDING -> LOCKED).

Parameters
mutex_keyPointer to mutex (must match most recent pending push)

Definition at line 280 of file mutex.c.

280 {
281 thread_lock_stack_t *stack = get_thread_local_stack();
282 if (!stack) {
283 return;
284 }
285
286 // Mark the top of the stack as locked
287 stack_lock(stack);
288 if (stack->depth == 0) {
289 stack_unlock(stack);
290 return;
291 }
292 int top = stack->depth - 1;
293 if (stack->stack[top].mutex_key == mutex_key) {
295 stack->stack[top].timestamp_ns = time_get_ns();
296 }
297 stack_unlock(stack);
298
299 // Thread-local only. Registry is populated on-demand by
300 // mutex_stack_get_all_threads()
301}
@ MUTEX_STACK_STATE_LOCKED
Definition mutex.h:38
mutex_stack_state_t state
Definition mutex.h:47
uint64_t timestamp_ns
Definition mutex.h:48
uintptr_t mutex_key
Definition mutex.h:45

References thread_lock_stack_t::depth, mutex_stack_entry_t::mutex_key, MUTEX_STACK_STATE_LOCKED, thread_lock_stack_t::stack, mutex_stack_entry_t::state, and mutex_stack_entry_t::timestamp_ns.

◆ mutex_stack_pop()

void mutex_stack_pop ( uintptr_t mutex_key)

Pop the top mutex from the current thread's lock stack (unlock).

Parameters
mutex_keyPointer to mutex (used for validation)

Definition at line 303 of file mutex.c.

303 {
304 thread_lock_stack_t *stack = get_thread_local_stack();
305 if (!stack) {
306 return;
307 }
308
309 // Validate top matches
310 stack_lock(stack);
311 if (stack->depth == 0) {
312 stack_unlock(stack);
313 return;
314 }
315 // Locks may be released out of acquisition order. Remove the most recent
316 // matching acquisition, preserving any recursive acquisitions below it.
317 for (int i = stack->depth - 1; i >= 0; --i) {
318 if (stack->stack[i].mutex_key == mutex_key) {
319 memmove(&stack->stack[i], &stack->stack[i + 1],
320 (size_t)(stack->depth - i - 1) * sizeof(stack->stack[0]));
321 --stack->depth;
322 break;
323 }
324 }
325 stack_unlock(stack);
326
327 // Thread-local only. Registry is populated on-demand by
328 // mutex_stack_get_all_threads()
329}

References thread_lock_stack_t::depth, mutex_stack_entry_t::mutex_key, and thread_lock_stack_t::stack.

◆ mutex_stack_push_locked()

void mutex_stack_push_locked ( uintptr_t mutex_key,
const char * mutex_name )

Record an already acquired lock without publishing a transient pending wait.

Definition at line 276 of file mutex.c.

276 {
277 mutex_stack_push(mutex_key, mutex_name, MUTEX_STACK_STATE_LOCKED);
278}

References MUTEX_STACK_STATE_LOCKED.

◆ mutex_stack_push_pending()

void mutex_stack_push_pending ( uintptr_t mutex_key,
const char * mutex_name )

Push a mutex onto the current thread's lock stack (PENDING state).

Parameters
mutex_keyPointer to mutex (used as unique ID)
mutex_nameHuman-readable name of mutex

Definition at line 272 of file mutex.c.

272 {
273 mutex_stack_push(mutex_key, mutex_name, MUTEX_STACK_STATE_PENDING);
274}
@ MUTEX_STACK_STATE_PENDING
Definition mutex.h:37

References MUTEX_STACK_STATE_PENDING.

◆ mutex_stack_try_snapshot()

bool mutex_stack_try_snapshot ( mutex_wait_snapshot_t * waits,
size_t capacity,
size_t * count,
bool * limited )

Definition at line 529 of file mutex.c.

530 {
531 // A single collector owns this scratch space. Never dereference names from
532 // copied stacks: their registry entries may have been removed meanwhile.
533 static thread_lock_stack_t snapshots[MAX_THREADS];
534 static thread_id_t ids[MAX_THREADS];
535 static atomic_flag sampling = ATOMIC_FLAG_INIT;
536 if (atomic_flag_test_and_set(&sampling))
537 return false;
538 uint64_t expected = 0;
539 if (!atomic_compare_exchange_strong(&g_registry_guard.impl, &expected, 1)) {
540 atomic_flag_clear(&sampling);
541 return false;
542 }
543 int threads = atomic_load_int_impl(&g_thread_registry_count);
544 bool complete = true;
545 for (int i = 0; i < threads; ++i) {
546 thread_lock_stack_t *stack = g_thread_registry[i].stack;
547 ids[i] = g_thread_registry[i].thread_id;
548 snapshots[i].depth = 0;
549 if (!stack)
550 continue;
551 expected = 0;
552 if (!atomic_compare_exchange_strong(&stack->guard.impl, &expected, 1)) {
553 complete = false;
554 break;
555 }
556 snapshots[i].depth = stack->depth;
557 memcpy(snapshots[i].stack, stack->stack, sizeof(stack->stack));
558 snapshots[i].telemetry = stack->telemetry;
559 atomic_store(&stack->guard.impl, 0);
560 }
561 atomic_store(&g_registry_guard.impl, 0);
562 if (complete) {
563 *count = 0;
564 *limited = threads >= MAX_CYCLE_LEN;
565 for (int i = 0; i < threads; ++i) {
566 uintptr_t key = thread_waiting_for_mutex(&snapshots[i]);
567 *limited |= snapshots[i].depth == MUTEX_STACK_MAX_DEPTH;
568 if (!key)
569 continue;
570 if (*count == capacity) {
571 *limited = true;
572 continue;
573 }
574 int path[MAX_CYCLE_LEN], length = 0;
575 bool cycle = thread_holds_mutex(&snapshots[i], key);
576 if (detect_cycle_dfs(snapshots, threads, i, path, &length) >= 0)
577 for (int j = 0; j < length; ++j)
578 cycle |= path[j] == i;
579 mutex_wait_snapshot_t *wait = &waits[(*count)++];
580 *wait = snapshots[i].telemetry;
581 wait->mutex_key = key;
582 wait->thread_key = (uintptr_t)ids[i];
583 wait->since_ns = snapshots[i].stack[snapshots[i].depth - 1].timestamp_ns;
584 wait->cycle = cycle;
585 }
586 }
587 atomic_flag_clear(&sampling);
588 return complete;
589}
For mutex wait snapshot, this is the live record that ties mutex_key, thread_key, since_ns,...
Definition mutex.h:122
uint64_t since_ns
Definition mutex.h:125
uintptr_t thread_key
Definition mutex.h:124
uintptr_t mutex_key
Definition mutex.h:123
mutex_wait_snapshot_t telemetry
Definition mutex.c:46

References atomic_load_int_impl(), mutex_wait_snapshot_t::cycle, thread_lock_stack_t::depth, thread_lock_stack_t::guard, MAX_CYCLE_LEN, MAX_THREADS, mutex_wait_snapshot_t::mutex_key, MUTEX_STACK_MAX_DEPTH, mutex_wait_snapshot_t::since_ns, thread_lock_stack_t::stack, thread_lock_stack_t::telemetry, mutex_wait_snapshot_t::thread_key, and mutex_stack_entry_t::timestamp_ns.