master
h 58 lines 1.89 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #ifndef NETDATA_SPINLOCK_H
4 #define NETDATA_SPINLOCK_H
5
6 #include "libnetdata/common.h"
7
8 #ifdef SPINLOCK_IMPL_WITH_MUTEX
9 typedef struct netdata_spinlock
10 {
11 netdata_mutex_t inner;
12 } SPINLOCK;
13 #else
14 typedef struct netdata_spinlock
15 {
16 bool locked;
17 #ifdef NETDATA_INTERNAL_CHECKS
18 pid_t locker_pid;
19 size_t spins;
20 #endif
21 } SPINLOCK;
22 #endif
23
24 #ifdef SPINLOCK_IMPL_WITH_MUTEX
25 #define SPINLOCK_INITIALIZER { .inner = PTHREAD_MUTEX_INITIALIZER }
26
27 #define spinlock_lock(spinlock) netdata_mutex_lock(&((spinlock)->inner))
28 #define spinlock_unlock(spinlock) netdata_mutex_unlock(&((spinlock)->inner))
29 #define spinlock_trylock(spinlock) (netdata_mutex_trylock(&((spinlock)->inner)) == 0)
30 #define spinlock_init(spinlock) netdata_mutex_init(&((spinlock)->inner)
31 #else
32 #ifdef NETDATA_INTERNAL_CHECKS
33 #define SPINLOCK_INITIALIZER { .locked = false, .locker_pid = 0, .spins = 0 }
34 #else
35 #define SPINLOCK_INITIALIZER { .locked = false }
36 #endif
37
38 #define SPINLOCK_DEADLOCK_TIMEOUT_SEC 3600 // Number of seconds to wait before declaring a deadlock
39 #define SPINS_BEFORE_DEADLOCK_CHECK 100000
40
41 // Helper function to detect deadlocks
42 void spinlock_deadlock_detect(usec_t *timestamp, const char *type, const char *func);
43
44 void spinlock_init_with_trace(SPINLOCK *spinlock, const char *func);
45 #define spinlock_init(spinlock) spinlock_init_with_trace(spinlock, __FUNCTION__)
46
47 void spinlock_lock_with_trace(SPINLOCK *spinlock, const char *func);
48 #define spinlock_lock(spinlock) spinlock_lock_with_trace(spinlock, __FUNCTION__)
49
50 void spinlock_unlock_with_trace(SPINLOCK *spinlock, const char *func __maybe_unused);
51 #define spinlock_unlock(spinlock) spinlock_unlock_with_trace(spinlock, __FUNCTION__)
52
53 bool spinlock_trylock_with_trace(SPINLOCK *spinlock, const char *func __maybe_unused);
54 #define spinlock_trylock(spinlock) spinlock_trylock_with_trace(spinlock, __FUNCTION__)
55
56 #endif
57
58 #endif //NETDATA_SPINLOCK_H