gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/sync/locking/generic_mutex.go (about) 1 // Copyright 2022 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package locking 16 17 import ( 18 "reflect" 19 20 "gvisor.dev/gvisor/pkg/sync" 21 "gvisor.dev/gvisor/pkg/sync/locking" 22 ) 23 24 // Mutex is sync.Mutex with the correctness validator. 25 type Mutex struct { 26 mu sync.Mutex 27 } 28 29 var genericMarkIndex *locking.MutexClass 30 31 // lockNames is a list of user-friendly lock names. 32 // Populated in init. 33 var lockNames []string 34 35 // lockNameIndex is used as an index passed to NestedLock and NestedUnlock, 36 // referring to an index within lockNames. 37 // Values are specified using the "consts" field of go_template_instance. 38 type lockNameIndex int 39 40 // DO NOT REMOVE: The following function automatically replaced with lock index constants. 41 // LOCK_NAME_INDEX_CONSTANTS 42 const () 43 44 // Lock locks m. 45 // +checklocksignore 46 func (m *Mutex) Lock() { 47 locking.AddGLock(genericMarkIndex, -1) 48 m.mu.Lock() 49 } 50 51 // NestedLock locks m knowing that another lock of the same type is held. 52 // +checklocksignore 53 func (m *Mutex) NestedLock(i lockNameIndex) { 54 locking.AddGLock(genericMarkIndex, int(i)) 55 m.mu.Lock() 56 } 57 58 // Unlock unlocks m. 59 // +checklocksignore 60 func (m *Mutex) Unlock() { 61 locking.DelGLock(genericMarkIndex, -1) 62 m.mu.Unlock() 63 } 64 65 // NestedUnlock unlocks m knowing that another lock of the same type is held. 66 // +checklocksignore 67 func (m *Mutex) NestedUnlock(i lockNameIndex) { 68 locking.DelGLock(genericMarkIndex, int(i)) 69 m.mu.Unlock() 70 } 71 72 // DO NOT REMOVE: The following function is automatically replaced. 73 func initLockNames() {} 74 75 func init() { 76 initLockNames() 77 genericMarkIndex = locking.NewMutexClass(reflect.TypeOf(Mutex{}), lockNames) 78 }