-
Notifications
You must be signed in to change notification settings - Fork 54
/
lock_tracker.go
314 lines (267 loc) · 6.29 KB
/
lock_tracker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"math"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"golang.org/x/exp/slices"
)
const lockTrackerMaxStackDepth = 16
var lockTrackerEnabled = false
var enableLockTrackerOnce sync.Once
var lowResTime uint32 = uint32(time.Now().Unix())
var enableLockTrackerStackTrace uint32
// EnableLockTracker enable lock tracking background worker. This should be
// called during init
func EnableLockTracker() {
enableLockTrackerOnce.Do(func() {
lockTrackerEnabled = true
go updateLowResTime()
})
}
func ToggleLockTrackerStackTraces(enable bool) {
var v uint32
if enable {
v = 1
}
atomic.StoreUint32(&enableLockTrackerStackTrace, v)
}
func updateLowResTime() {
ticker := time.NewTicker(time.Second)
for t := range ticker.C {
atomic.StoreUint32(&lowResTime, uint32(t.Unix()))
}
}
var weakRefs []uintptr
var weakRefFree []int
var weakRefLock sync.Mutex
func NumMutexes() int {
weakRefLock.Lock()
defer weakRefLock.Unlock()
return len(weakRefs) - len(weakRefFree)
}
// ScanTrackedLocks check all lock trackers
func ScanTrackedLocks(threshold time.Duration) []*StuckLock {
minTS := uint32(time.Now().Add(-threshold).Unix())
weakRefLock.Lock()
defer weakRefLock.Unlock()
return scanTrackedLocks(weakRefs, minTS)
}
var nextScanMin int
// ScanTrackedLocksI check lock trackers incrementally n at a time
func ScanTrackedLocksI(threshold time.Duration, n int) []*StuckLock {
minTS := uint32(time.Now().Add(-threshold).Unix())
if n <= 0 {
n = 10000
}
weakRefLock.Lock()
defer weakRefLock.Unlock()
min := nextScanMin
max := nextScanMin + n
if rl := len(weakRefs); rl <= max {
max = rl
nextScanMin = 0
} else {
nextScanMin = max
}
return scanTrackedLocks(weakRefs[min:max], minTS)
}
//go:norace
//go:nosplit
func scanTrackedLocks(refs []uintptr, minTS uint32) []*StuckLock {
var stuck []*StuckLock
for _, ref := range refs {
if ref != 0 {
t := (*lockTracker)(unsafe.Pointer(ref))
ts := atomic.LoadUint32(&t.ts)
waiting := atomic.LoadInt32(&t.waiting)
if ts <= minTS && waiting > 0 {
stuck = append(stuck, &StuckLock{
stack: slices.Clone(t.stack),
ts: ts,
waiting: waiting,
held: atomic.LoadInt32(&t.held),
})
}
}
}
return stuck
}
type StuckLock struct {
stack []uintptr
ts uint32
waiting int32
held int32
}
func (d *StuckLock) FirstLockedAtStack() string {
fs := runtime.CallersFrames(d.stack)
var b strings.Builder
for {
f, ok := fs.Next()
if !ok {
break
}
if f.Function != "" {
b.WriteString(f.Function)
b.WriteByte('\n')
}
if f.File != "" {
b.WriteByte('\t')
b.WriteString(f.File)
b.WriteByte(':')
b.WriteString(strconv.Itoa(f.Line))
b.WriteByte('\n')
}
}
return b.String()
}
func (d *StuckLock) HeldSince() time.Time {
return time.Unix(int64(d.ts), 0)
}
func (d *StuckLock) NumGoroutineHeld() int {
return int(d.held)
}
func (d *StuckLock) NumGoroutineWaiting() int {
return int(d.waiting)
}
type lockTracker struct {
stack []uintptr
ts uint32
waiting int32
held int32
ref int
}
func (t *lockTracker) trackWait() {
if t != nil {
atomic.AddInt32(&t.waiting, 1)
}
}
func (t *lockTracker) trackLock() {
if t != nil {
atomic.AddInt32(&t.waiting, -1)
if atomic.AddInt32(&t.held, 1) == 1 {
atomic.StoreUint32(&t.ts, atomic.LoadUint32(&lowResTime))
if atomic.LoadUint32(&enableLockTrackerStackTrace) == 1 {
n := runtime.Callers(2, t.stack[:lockTrackerMaxStackDepth])
t.stack = t.stack[:n]
}
}
}
}
func (t *lockTracker) trackUnlock() {
if t != nil {
if atomic.AddInt32(&t.held, -1) == 0 {
atomic.StoreUint32(&t.ts, math.MaxUint32)
}
}
}
func newLockTracker() *lockTracker {
t := &lockTracker{
stack: make([]uintptr, lockTrackerMaxStackDepth),
ts: math.MaxUint32,
}
runtime.SetFinalizer(t, finalizeLockTracker)
weakRefLock.Lock()
defer weakRefLock.Unlock()
if fi := len(weakRefFree) - 1; fi >= 0 {
t.ref = weakRefFree[fi]
weakRefs[t.ref] = uintptr((unsafe.Pointer)(t))
weakRefFree = weakRefFree[:fi]
} else {
t.ref = len(weakRefs)
weakRefs = append(weakRefs, uintptr((unsafe.Pointer)(t)))
}
return t
}
func finalizeLockTracker(t *lockTracker) {
weakRefLock.Lock()
defer weakRefLock.Unlock()
weakRefs[t.ref] = 0
weakRefFree = append(weakRefFree, t.ref)
}
var waiting lockTracker
//go:linkname sync_runtime_canSpin sync.runtime_canSpin
func sync_runtime_canSpin(int) bool
//go:linkname sync_runtime_doSpin sync.runtime_doSpin
func sync_runtime_doSpin()
func lazyInitLockTracker(p **lockTracker) *lockTracker {
if !lockTrackerEnabled {
return nil
}
up := (*unsafe.Pointer)(unsafe.Pointer(p))
iter := 0
for {
if t := atomic.LoadPointer(up); t == nil {
if atomic.CompareAndSwapPointer(up, nil, (unsafe.Pointer)(&waiting)) {
atomic.StorePointer(up, (unsafe.Pointer)(newLockTracker()))
}
} else if t == (unsafe.Pointer)(&waiting) {
if sync_runtime_canSpin(iter) {
sync_runtime_doSpin()
iter++
} else {
runtime.Gosched()
}
} else {
return (*lockTracker)(t)
}
}
}
type Mutex struct {
sync.Mutex
t *lockTracker
}
func (m *Mutex) Lock() {
t := lazyInitLockTracker(&m.t)
t.trackWait()
m.Mutex.Lock()
t.trackLock()
}
func (m *Mutex) Unlock() {
t := lazyInitLockTracker(&m.t)
t.trackUnlock()
m.Mutex.Unlock()
}
type RWMutex struct {
sync.RWMutex
t *lockTracker
}
func (m *RWMutex) Lock() {
t := lazyInitLockTracker(&m.t)
t.trackWait()
m.RWMutex.Lock()
t.trackLock()
}
func (m *RWMutex) Unlock() {
t := lazyInitLockTracker(&m.t)
t.trackUnlock()
m.RWMutex.Unlock()
}
func (m *RWMutex) RLock() {
t := lazyInitLockTracker(&m.t)
t.trackWait()
m.RWMutex.RLock()
t.trackLock()
}
func (m *RWMutex) RUnlock() {
t := lazyInitLockTracker(&m.t)
t.trackUnlock()
m.RWMutex.RUnlock()
}