1 //===-- tsan_mutex.cc -----------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is a part of ThreadSanitizer (TSan), a race detector.
10 //===----------------------------------------------------------------------===//
11 #include "sanitizer_common/sanitizer_libc.h"
12 #include "tsan_mutex.h"
13 #include "tsan_platform.h"
18 // Simple reader-writer spin-mutex. Optimized for not-so-contended case.
19 // Readers have preference, can possibly starvate writers.
21 // The table fixes what mutexes can be locked under what mutexes.
22 // E.g. if the row for MutexTypeThreads contains MutexTypeReport,
23 // then Report mutex can be locked while under Threads mutex.
24 // The leaf mutexes can be locked under any other mutexes.
25 // Recursive locking is not supported.
26 #if TSAN_DEBUG && !TSAN_GO
27 const MutexType MutexTypeLeaf
= (MutexType
)-1;
28 static MutexType CanLockTab
[MutexTypeCount
][MutexTypeCount
] = {
29 /*0 MutexTypeInvalid*/ {},
30 /*1 MutexTypeTrace*/ {MutexTypeLeaf
},
31 /*2 MutexTypeThreads*/ {MutexTypeReport
},
32 /*3 MutexTypeReport*/ {MutexTypeSyncTab
, MutexTypeSyncVar
,
33 MutexTypeMBlock
, MutexTypeJavaMBlock
},
34 /*4 MutexTypeSyncVar*/ {MutexTypeDDetector
},
35 /*5 MutexTypeSyncTab*/ {MutexTypeSyncVar
},
36 /*6 MutexTypeSlab*/ {MutexTypeLeaf
},
37 /*7 MutexTypeAnnotations*/ {},
38 /*8 MutexTypeAtExit*/ {MutexTypeSyncTab
},
39 /*9 MutexTypeMBlock*/ {MutexTypeSyncVar
},
40 /*10 MutexTypeJavaMBlock*/ {MutexTypeSyncVar
},
41 /*11 MutexTypeDDetector*/ {},
44 static bool CanLockAdj
[MutexTypeCount
][MutexTypeCount
];
47 void InitializeMutex() {
48 #if TSAN_DEBUG && !TSAN_GO
49 // Build the "can lock" adjacency matrix.
50 // If [i][j]==true, then one can lock mutex j while under mutex i.
51 const int N
= MutexTypeCount
;
54 for (int i
= 1; i
< N
; i
++) {
55 for (int j
= 0; j
< N
; j
++) {
56 MutexType z
= CanLockTab
[i
][j
];
57 if (z
== MutexTypeInvalid
)
59 if (z
== MutexTypeLeaf
) {
64 CHECK(!CanLockAdj
[i
][(int)z
]);
65 CanLockAdj
[i
][(int)z
] = true;
69 for (int i
= 0; i
< N
; i
++) {
70 CHECK(!leaf
[i
] || cnt
[i
] == 0);
73 for (int i
= 0; i
< N
; i
++) {
76 for (int j
= 0; j
< N
; j
++) {
77 if (i
== j
|| leaf
[j
] || j
== MutexTypeInvalid
)
79 CHECK(!CanLockAdj
[j
][i
]);
80 CanLockAdj
[j
][i
] = true;
83 // Build the transitive closure.
84 bool CanLockAdj2
[MutexTypeCount
][MutexTypeCount
];
85 for (int i
= 0; i
< N
; i
++) {
86 for (int j
= 0; j
< N
; j
++) {
87 CanLockAdj2
[i
][j
] = CanLockAdj
[i
][j
];
90 for (int k
= 0; k
< N
; k
++) {
91 for (int i
= 0; i
< N
; i
++) {
92 for (int j
= 0; j
< N
; j
++) {
93 if (CanLockAdj2
[i
][k
] && CanLockAdj2
[k
][j
]) {
94 CanLockAdj2
[i
][j
] = true;
100 Printf("Can lock graph:\n");
101 for (int i
= 0; i
< N
; i
++) {
102 for (int j
= 0; j
< N
; j
++) {
103 Printf("%d ", CanLockAdj
[i
][j
]);
107 Printf("Can lock graph closure:\n");
108 for (int i
= 0; i
< N
; i
++) {
109 for (int j
= 0; j
< N
; j
++) {
110 Printf("%d ", CanLockAdj2
[i
][j
]);
115 // Verify that the graph is acyclic.
116 for (int i
= 0; i
< N
; i
++) {
117 if (CanLockAdj2
[i
][i
]) {
118 Printf("Mutex %d participates in a cycle\n", i
);
125 InternalDeadlockDetector::InternalDeadlockDetector() {
126 // Rely on zero initialization because some mutexes can be locked before ctor.
129 #if TSAN_DEBUG && !TSAN_GO
130 void InternalDeadlockDetector::Lock(MutexType t
) {
131 // Printf("LOCK %d @%zu\n", t, seq_ + 1);
132 CHECK_GT(t
, MutexTypeInvalid
);
133 CHECK_LT(t
, MutexTypeCount
);
135 u64 max_idx
= MutexTypeInvalid
;
136 for (int i
= 0; i
!= MutexTypeCount
; i
++) {
139 CHECK_NE(locked_
[i
], max_seq
);
140 if (max_seq
< locked_
[i
]) {
141 max_seq
= locked_
[i
];
146 if (max_idx
== MutexTypeInvalid
)
148 // Printf(" last %d @%zu\n", max_idx, max_seq);
149 if (!CanLockAdj
[max_idx
][t
]) {
150 Printf("ThreadSanitizer: internal deadlock detected\n");
151 Printf("ThreadSanitizer: can't lock %d while under %zu\n",
157 void InternalDeadlockDetector::Unlock(MutexType t
) {
158 // Printf("UNLO %d @%zu #%zu\n", t, seq_, locked_[t]);
164 const uptr kUnlocked
= 0;
165 const uptr kWriteLock
= 1;
166 const uptr kReadLock
= 2;
175 if (iter_
++ < kActiveSpinIters
)
176 proc_yield(kActiveSpinCnt
);
178 internal_sched_yield();
182 u64
Contention() const {
183 u64 active
= iter_
% kActiveSpinIters
;
184 u64 passive
= iter_
- active
;
185 return active
+ 10 * passive
;
190 static const int kActiveSpinIters
= 10;
191 static const int kActiveSpinCnt
= 20;
194 Mutex::Mutex(MutexType type
, StatType stat_type
) {
195 CHECK_GT(type
, MutexTypeInvalid
);
196 CHECK_LT(type
, MutexTypeCount
);
200 #if TSAN_COLLECT_STATS
201 stat_type_
= stat_type
;
203 atomic_store(&state_
, kUnlocked
, memory_order_relaxed
);
207 CHECK_EQ(atomic_load(&state_
, memory_order_relaxed
), kUnlocked
);
211 #if TSAN_DEBUG && !TSAN_GO
212 cur_thread()->internal_deadlock_detector
.Lock(type_
);
214 uptr cmp
= kUnlocked
;
215 if (atomic_compare_exchange_strong(&state_
, &cmp
, kWriteLock
,
216 memory_order_acquire
))
218 for (Backoff backoff
; backoff
.Do();) {
219 if (atomic_load(&state_
, memory_order_relaxed
) == kUnlocked
) {
221 if (atomic_compare_exchange_weak(&state_
, &cmp
, kWriteLock
,
222 memory_order_acquire
)) {
223 #if TSAN_COLLECT_STATS
224 StatInc(cur_thread(), stat_type_
, backoff
.Contention());
232 void Mutex::Unlock() {
233 uptr prev
= atomic_fetch_sub(&state_
, kWriteLock
, memory_order_release
);
235 DCHECK_NE(prev
& kWriteLock
, 0);
236 #if TSAN_DEBUG && !TSAN_GO
237 cur_thread()->internal_deadlock_detector
.Unlock(type_
);
241 void Mutex::ReadLock() {
242 #if TSAN_DEBUG && !TSAN_GO
243 cur_thread()->internal_deadlock_detector
.Lock(type_
);
245 uptr prev
= atomic_fetch_add(&state_
, kReadLock
, memory_order_acquire
);
246 if ((prev
& kWriteLock
) == 0)
248 for (Backoff backoff
; backoff
.Do();) {
249 prev
= atomic_load(&state_
, memory_order_acquire
);
250 if ((prev
& kWriteLock
) == 0) {
251 #if TSAN_COLLECT_STATS
252 StatInc(cur_thread(), stat_type_
, backoff
.Contention());
259 void Mutex::ReadUnlock() {
260 uptr prev
= atomic_fetch_sub(&state_
, kReadLock
, memory_order_release
);
262 DCHECK_EQ(prev
& kWriteLock
, 0);
263 DCHECK_GT(prev
& ~kWriteLock
, 0);
264 #if TSAN_DEBUG && !TSAN_GO
265 cur_thread()->internal_deadlock_detector
.Unlock(type_
);
269 void Mutex::CheckLocked() {
270 CHECK_NE(atomic_load(&state_
, memory_order_relaxed
), 0);
273 } // namespace __tsan