forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leveled_mutex.go
439 lines (376 loc) · 11.5 KB
/
leveled_mutex.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"sync"
"sync/atomic"
)
// The leveledMutex, leveledRWMutex, and lockState types enables a
// lock hierarchy to be checked. For a program (or subsystem), each
// (rw-)mutex must have a unique associated mutexLevel, which means
// that a (rw-)mutex must not be (r-)locked before another (rw-)mutex
// with a lower mutexLevel in a given execution flow. This is achieved
// by creating a new lockState at the start of an execution flow and
// passing it to the (r-)lock/(r-)unlock methods of each (rw-)mutex.
//
// TODO: Once this becomes a bottleneck, add a +build production
// version that stubs everything out.
// An exclusiveLock is a lock around something that is expected to be
// accessed exclusively. It immediately panics upon any lock
// contention.
type exclusiveLock struct {
v *int32
}
func makeExclusiveLock() exclusiveLock {
return exclusiveLock{
v: new(int32),
}
}
func (l exclusiveLock) lock() {
if !atomic.CompareAndSwapInt32(l.v, 0, 1) {
panic("unexpected concurrent access")
}
}
func (l exclusiveLock) unlock() {
if !atomic.CompareAndSwapInt32(l.v, 1, 0) {
panic("unexpected concurrent access")
}
}
// mutexLevel is the level for a mutex, which must be unique to that
// mutex.
type mutexLevel int
// exclusionType is the type of exclusion of a lock. A regular lock
// always uses write exclusion, where only one thing at a time can
// hold the lock, whereas a reader-writer lock can do either write
// exclusion or read exclusion, where only one writer or any number of
// readers can hold the lock.
type exclusionType int
const (
nonExclusion exclusionType = 0
writeExclusion exclusionType = 1
readExclusion exclusionType = 2
)
func (et exclusionType) prefix() string {
switch et {
case nonExclusion:
return "Un"
case writeExclusion:
return ""
case readExclusion:
return "R"
}
return fmt.Sprintf("exclusionType{%d}", et)
}
// exclusionState holds the state for a held mutex.
type exclusionState struct {
// The level of the held mutex.
level mutexLevel
// The exclusion type of the held mutex.
exclusionType exclusionType
}
// lockState holds the info regarding which level mutexes are held or
// not for a particular execution flow.
type lockState struct {
levelToString func(mutexLevel) string
// Protects exclusionStates.
exclusionStatesLock exclusiveLock
// The stack of held mutexes, ordered by increasing level.
exclusionStates []exclusionState
}
// makeLevelState returns a new lockState. This must be called at the
// start of a new execution flow and passed to any leveledMutex or
// leveledRWMutex operation during that execution flow.
//
// TODO: Consider adding a parameter to set the capacity of
// exclusionStates.
func makeLevelState(levelToString func(mutexLevel) string) *lockState {
return &lockState{
levelToString: levelToString,
exclusionStatesLock: makeExclusiveLock(),
}
}
// currLocked returns the current exclusion state, or nil if there is
// none.
func (state *lockState) currLocked() *exclusionState {
stateCount := len(state.exclusionStates)
if stateCount == 0 {
return nil
}
return &state.exclusionStates[stateCount-1]
}
type levelViolationError struct {
levelToString func(mutexLevel) string
level mutexLevel
exclusionType exclusionType
curr exclusionState
}
func (e levelViolationError) Error() string {
return fmt.Sprintf("level violation: %s %sLocked after %s %sLocked",
e.levelToString(e.level), e.exclusionType.prefix(),
e.levelToString(e.curr.level), e.curr.exclusionType.prefix())
}
func (state *lockState) doLock(
level mutexLevel, exclusionType exclusionType, lock sync.Locker) error {
state.exclusionStatesLock.lock()
defer state.exclusionStatesLock.unlock()
curr := state.currLocked()
if curr != nil && level <= curr.level {
return levelViolationError{
levelToString: state.levelToString,
level: level,
exclusionType: exclusionType,
curr: *curr,
}
}
lock.Lock()
state.exclusionStates = append(state.exclusionStates, exclusionState{
level: level,
exclusionType: exclusionType,
})
return nil
}
type danglingUnlockError struct {
levelToString func(mutexLevel) string
level mutexLevel
exclusionType exclusionType
}
func (e danglingUnlockError) Error() string {
return fmt.Sprintf("%s %sUnlocked while already unlocked",
e.levelToString(e.level), e.exclusionType.prefix())
}
type mismatchedUnlockError struct {
levelToString func(mutexLevel) string
level mutexLevel
exclusionType exclusionType
curr exclusionState
}
func (e mismatchedUnlockError) Error() string {
return fmt.Sprintf(
"%sUnlock call for %s doesn't match %sLock call for %s",
e.exclusionType.prefix(), e.levelToString(e.level),
e.curr.exclusionType.prefix(), e.levelToString(e.curr.level))
}
func (state *lockState) doUnlock(
level mutexLevel, exclusionType exclusionType, lock sync.Locker) error {
state.exclusionStatesLock.lock()
defer state.exclusionStatesLock.unlock()
curr := state.currLocked()
if curr == nil {
return danglingUnlockError{
levelToString: state.levelToString,
level: level,
exclusionType: exclusionType,
}
}
if level != curr.level || curr.exclusionType != exclusionType {
return mismatchedUnlockError{
levelToString: state.levelToString,
level: level,
exclusionType: exclusionType,
curr: *curr,
}
}
lock.Unlock()
state.exclusionStates = state.exclusionStates[:len(state.exclusionStates)-1]
return nil
}
// getExclusionType returns returns the exclusionType for the given
// mutexLevel, or nonExclusion if there is none.
func (state *lockState) getExclusionType(level mutexLevel) exclusionType {
state.exclusionStatesLock.lock()
defer state.exclusionStatesLock.unlock()
// Not worth it to do anything more complicated than a
// brute-force search.
for _, state := range state.exclusionStates {
if state.level > level {
break
}
if state.level == level {
return state.exclusionType
}
}
return nonExclusion
}
// leveledMutex is a mutex with an associated level, which must be
// unique. Note that unlike sync.Mutex, leveledMutex is a reference
// type and not a value type.
type leveledMutex struct {
level mutexLevel
locker sync.Locker
}
func makeLeveledMutex(level mutexLevel, locker sync.Locker) leveledMutex {
return leveledMutex{
level: level,
locker: locker,
}
}
func (m leveledMutex) Lock(lockState *lockState) {
err := lockState.doLock(m.level, writeExclusion, m.locker)
if err != nil {
panic(err)
}
}
func (m leveledMutex) Unlock(lockState *lockState) {
err := lockState.doUnlock(m.level, writeExclusion, m.locker)
if err != nil {
panic(err)
}
}
type unexpectedExclusionError struct {
levelToString func(mutexLevel) string
level mutexLevel
exclusionType exclusionType
}
func (e unexpectedExclusionError) Error() string {
return fmt.Sprintf("%s unexpectedly %sLocked",
e.levelToString(e.level), e.exclusionType.prefix())
}
// AssertUnlocked does nothing if m is unlocked with respect to the
// given lockState. Otherwise, it panics.
func (m leveledMutex) AssertUnlocked(lockState *lockState) {
et := lockState.getExclusionType(m.level)
if et != nonExclusion {
panic(unexpectedExclusionError{
levelToString: lockState.levelToString,
level: m.level,
exclusionType: et,
})
}
}
type unexpectedExclusionTypeError struct {
levelToString func(mutexLevel) string
level mutexLevel
expectedExclusionType exclusionType
exclusionType exclusionType
}
func (e unexpectedExclusionTypeError) Error() string {
return fmt.Sprintf(
"%s unexpectedly not %sLocked; instead it is %sLocked",
e.levelToString(e.level),
e.expectedExclusionType.prefix(),
e.exclusionType.prefix())
}
// AssertLocked does nothing if m is locked with respect to the given
// lockState. Otherwise, it panics.
func (m leveledMutex) AssertLocked(lockState *lockState) {
et := lockState.getExclusionType(m.level)
if et != writeExclusion {
panic(unexpectedExclusionTypeError{
levelToString: lockState.levelToString,
level: m.level,
expectedExclusionType: writeExclusion,
exclusionType: et,
})
}
}
// leveledLocker represents an object that can be locked and unlocked
// with a lockState.
type leveledLocker interface {
Lock(*lockState)
Unlock(*lockState)
}
// leveledMutex is a reader-writer mutex with an associated level,
// which must be unique. Note that unlike sync.RWMutex, leveledRWMutex
// is a reference type and not a value type.
type leveledRWMutex struct {
level mutexLevel
rwLocker rwLocker
}
func makeLeveledRWMutex(level mutexLevel, rwLocker rwLocker) leveledRWMutex {
return leveledRWMutex{
level: level,
rwLocker: rwLocker,
}
}
func (rw leveledRWMutex) Lock(lockState *lockState) {
err := lockState.doLock(rw.level, writeExclusion, rw.rwLocker)
if err != nil {
panic(err)
}
}
func (rw leveledRWMutex) Unlock(lockState *lockState) {
err := lockState.doUnlock(rw.level, writeExclusion, rw.rwLocker)
if err != nil {
panic(err)
}
}
func (rw leveledRWMutex) RLock(lockState *lockState) {
err := lockState.doLock(rw.level, readExclusion, rw.rwLocker.RLocker())
if err != nil {
panic(err)
}
}
func (rw leveledRWMutex) RUnlock(lockState *lockState) {
err := lockState.doUnlock(rw.level, readExclusion, rw.rwLocker.RLocker())
if err != nil {
panic(err)
}
}
// AssertUnlocked does nothing if m is unlocked with respect to the
// given lockState. Otherwise, it panics.
func (rw leveledRWMutex) AssertUnlocked(lockState *lockState) {
et := lockState.getExclusionType(rw.level)
if et != nonExclusion {
panic(unexpectedExclusionError{
levelToString: lockState.levelToString,
level: rw.level,
exclusionType: et,
})
}
}
// AssertLocked does nothing if m is locked with respect to the given
// lockState. Otherwise, it panics.
func (rw leveledRWMutex) AssertLocked(lockState *lockState) {
et := lockState.getExclusionType(rw.level)
if et != writeExclusion {
panic(unexpectedExclusionTypeError{
levelToString: lockState.levelToString,
level: rw.level,
expectedExclusionType: writeExclusion,
exclusionType: et,
})
}
}
// AssertRLocked does nothing if m is r-locked with respect to the
// given lockState. Otherwise, it panics.
func (rw leveledRWMutex) AssertRLocked(lockState *lockState) {
et := lockState.getExclusionType(rw.level)
if et != readExclusion {
panic(unexpectedExclusionTypeError{
levelToString: lockState.levelToString,
level: rw.level,
expectedExclusionType: readExclusion,
exclusionType: et,
})
}
}
type unexpectedNonExclusionError struct {
levelToString func(mutexLevel) string
level mutexLevel
}
func (e unexpectedNonExclusionError) Error() string {
return fmt.Sprintf("%s unexpectedly unlocked", e.levelToString(e.level))
}
// AssertAnyLocked does nothing if m is locked or r-locked with
// respect to the given lockState. Otherwise, it panics.
func (rw leveledRWMutex) AssertAnyLocked(lockState *lockState) {
et := lockState.getExclusionType(rw.level)
if et == nonExclusion {
panic(unexpectedNonExclusionError{
levelToString: lockState.levelToString,
level: rw.level,
})
}
}
func (rw leveledRWMutex) RLocker() leveledLocker {
return (leveledRLocker)(rw)
}
type leveledRLocker leveledRWMutex
func (r leveledRLocker) Lock(lockState *lockState) {
(leveledRWMutex)(r).RLock(lockState)
}
func (r leveledRLocker) Unlock(lockState *lockState) {
(leveledRWMutex)(r).RUnlock(lockState)
}