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
|
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build ts_mutex_debug
package syncs
import (
"bytes"
"fmt"
"log"
"runtime"
"sync"
"unsafe"
"go4.org/mem"
)
// MutexDebugging indicates whether the "ts_mutex_debug" build tag is set
// and mutex debugging is enabled.
const MutexDebugging = true
type Mutex struct {
sync.Mutex
}
type RWMutex struct {
sync.RWMutex
}
func RequiresMutex(mu *Mutex) {
// TODO: check
}
// TODO(bradfitz): actually track stuff when in debug mode.
var bufPool = &sync.Pool{
New: func() any {
b := make([]byte, 16<<10)
return &b
},
}
func (m *Mutex) Lock() {
defer m.Mutex.Lock()
gid := curGoroutineID()
up := uintptr((unsafe.Pointer)(m))
bufp := bufPool.Get().(*[]byte)
defer bufPool.Put(bufp)
stack := (*bufp)[:runtime.Stack(*bufp, false)]
trackMu.Lock()
defer trackMu.Unlock()
gid = walkToParent(gid)
name, ok := mutexName[up]
if !ok {
name = "unnamed"
log.Printf("XXX unregistered Mutex.Lock %p called from:\n%s", m, stack)
}
switch name {
case "ipnlocal.LocalBackend.mu", "wgengine.userspaceEngine.wgLock", "ipnlocal.nodeBackend.mu":
if bytes.Contains(stack, []byte("wireguard-go/device.(*Device).RoutineReceiveIncoming")) {
log.Printf("XXX mutex Lock from wireguard land: %s, %s", name, stack)
}
}
gi, ok := goroutines[gid]
if !ok {
gi = &goroutineInfo{}
goroutines[gid] = gi
}
gi.holding = append(gi.holding, &heldLock{
mutexAddr: up,
name: name,
})
if len(gi.holding) > 1 {
names := make([]string, 0, len(gi.holding))
for i, hl := range gi.holding {
names = append(names, hl.name)
if i == 0 {
continue
}
lo := lockOrder{
first: gi.holding[i-1].name,
second: hl.name,
}
if lockOrders[lo.reverse()] {
log.Printf("mutex: potential deadlock detected: lock order violation: %q then %q (saw reverse order before); goroutine %d stack:\n%s", lo.first, lo.second, gid, stack)
} else {
if _, ok := lockOrders[lo]; !ok {
log.Printf("XXX learned new lock order: %q then %q", lo.first, lo.second)
lockOrders[lo] = true
}
}
}
log.Printf("XXX goroutine %v holding %q", gid, names)
}
}
func (m *Mutex) Unlock() {
defer m.Mutex.Unlock()
up := uintptr((unsafe.Pointer)(m))
gid := curGoroutineID()
trackMu.Lock()
defer trackMu.Unlock()
gid = walkToParent(gid)
name, ok := mutexName[up]
if !ok {
name = "unnamed"
}
gi, ok := goroutines[gid]
if !ok || len(gi.holding) == 0 {
log.Printf("mutex: unlock of %p (%s) by goroutine %d with no held locks", m, name, gid)
return
}
last := gi.holding[len(gi.holding)-1]
if last.mutexAddr != up {
log.Printf("mutex: unlock of %p (%s) by goroutine %d, but last held lock is %p (%s)", m, name, gid, last.mutexAddr, last.name)
return
}
gi.holding[len(gi.holding)-1] = nil
gi.holding = gi.holding[:len(gi.holding)-1]
if len(gi.holding) == 0 {
delete(goroutines, gid)
}
}
var (
trackMu sync.Mutex
mutexName = make(map[uintptr]string)
goroutines = make(map[uint64]*goroutineInfo)
parentGID = make(map[uint64]uint64) // child goroutine ID -> parent (for ForkJoinGo)
lockOrders = make(map[lockOrder]bool) // observed lock orderings
)
type lockOrder struct {
first string
second string
}
func (lo lockOrder) reverse() lockOrder {
return lockOrder{first: lo.second, second: lo.first}
}
type goroutineInfo struct {
holding []*heldLock
}
type heldLock struct {
mutexAddr uintptr
name string
// TODO: stack? [16]uintptr?
}
// RegisterMutex registers the given mutex with the given name for
// debugging purposes.
func RegisterMutex(mu *Mutex, name string) {
trackMu.Lock()
defer trackMu.Unlock()
up := uintptr((unsafe.Pointer)(mu))
mutexName[up] = name
runtime.AddCleanup(mu, func(up uintptr) {
trackMu.Lock()
defer trackMu.Unlock()
delete(mutexName, up)
}, up)
}
var littleBuf = sync.Pool{
New: func() interface{} {
buf := make([]byte, 64)
return &buf
},
}
var goroutineSpace = []byte("goroutine ")
func curGoroutineID() uint64 {
bp := littleBuf.Get().(*[]byte)
defer littleBuf.Put(bp)
b := *bp
b = b[:runtime.Stack(b, false)]
// Parse the 4707 out of "goroutine 4707 ["
b = bytes.TrimPrefix(b, goroutineSpace)
i := bytes.IndexByte(b, ' ')
if i < 0 {
panic(fmt.Sprintf("No space found in %q", b))
}
b = b[:i]
n, err := mem.ParseUint(mem.B(b), 10, 64)
if err != nil {
panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
}
return n
}
func trackForkJoinPair(parent, child uint64, add bool) {
trackMu.Lock()
defer trackMu.Unlock()
if add {
parentGID[child] = parent
} else {
delete(parentGID, child)
}
}
func walkToParent(gid uint64) uint64 {
for {
p, ok := parentGID[gid]
if !ok {
return gid
}
gid = p
}
}
// ForkJoinGo is like go fn() but indicates that the goroutine
// is part of a fork-join parallelism pattern.
//
// This compiles to just "go fn()" in non-debug builds.
func ForkJoinGo(fn func()) {
parentGID := curGoroutineID()
go func() {
childGID := curGoroutineID()
trackForkJoinPair(parentGID, childGID, true)
defer trackForkJoinPair(parentGID, childGID, false)
fn()
}()
}
|