// Lock implements the MDServer interface for MDServerMemory.
978534
func (md *MDServerMemory) Lock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error {
	// An RPC-based client would receive a throttle message from the
	// server and retry with backoff, but here we need to implement
	// the retry logic explicitly.
	for {
		ch := md.doLock(ctx, tlfID, lockID)
		if ch == nil {
			return nil
		}
		select {
		// TODO: wait for the clock to pass the expired time.  We'd
		// need a new method in the `Clock` interface to support this.
		case <-ch:
			continue
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}
854023
func (rw LeveledRWMutex) Lock(lockState *LockState) {
	err := lockState.doLock(rw.level, writeExclusion, rw.rwLocker)
	if err != nil {
		panic(err)
	}
}
380829
func NewMDServerMemory(config mdServerLocalConfig) (*MDServerMemory, error) {
	handleDb := make(map[mdHandleKey]tlf.ID)
	latestHandleDb := make(map[tlf.ID]tlf.Handle)
	mdDb := make(map[mdBlockKey]mdBlockMemList)
	branchDb := make(map[mdBranchKey]kbfsmd.BranchID)
	writerKeyBundleDb := make(map[mdExtraWriterKey]kbfsmd.TLFWriterKeyBundleV3)
	readerKeyBundleDb := make(map[mdExtraReaderKey]kbfsmd.TLFReaderKeyBundleV3)
	log := config.MakeLogger("MDSM")
	truncateLockManager := newMDServerLocalTruncatedLockManager()
	shared := mdServerMemShared{
		handleDb:            handleDb,
		latestHandleDb:      latestHandleDb,
		mdDb:                mdDb,
		branchDb:            branchDb,
		writerKeyBundleDb:   writerKeyBundleDb,
		readerKeyBundleDb:   readerKeyBundleDb,
		truncateLockManager: &truncateLockManager,
		lockIDs:             make(map[mdLockMemKey]mdLockMemVal),
		iTeamMigrationLocks: make(map[tlf.ID]bool),
		updateManager:       newMDServerLocalUpdateManager(),
		merkleRoots:         make(map[keybase1.MerkleTreeID]*kbfsmd.MerkleRoot),
	}
	mdserv := &MDServerMemory{config, log, &shared}
	return mdserv, nil
}
1082258
func (l *lockfile) Lock() {
	if l.ro {
		l.RLock()
	} else {
		l.lock(unix.F_WRLCK)
	}
}
1051745
func (n *nsLockMap) lock(volume, path string, lockSource, opsID string, readLock bool, timeout time.Duration) (locked bool) {
	var nsLk *nsLock

	n.lockMapMutex.Lock()
	param := nsParam{volume, path}
	nsLk, found := n.lockMap[param]
	if !found {
		n.lockMap[param] = &nsLock{
			LRWMutex: &lsync.LRWMutex{},
			ref:      1,
		}
		nsLk = n.lockMap[param]
	} else {
		// Update ref count here to avoid multiple races.
		nsLk.ref++
	}
	n.lockMapMutex.Unlock()

	// Locking here will block (until timeout).
	if readLock {
		locked = nsLk.GetRLock(opsID, lockSource, timeout)
	} else {
		locked = nsLk.GetLock(opsID, lockSource, timeout)
	}

	if !locked { // We failed to get the lock

		// Decrement ref count since we failed to get the lock
		n.lockMapMutex.Lock()
		nsLk.ref--
		if nsLk.ref == 0 {
			// Remove from the map if there are no more references.
			delete(n.lockMap, param)
		}
		n.lockMapMutex.Unlock()
	}
	return
}
869215
func (m *Mutex) Lock(ctx context.Context) error {
	lockCtx, cancel := context.WithTimeout(ctx, m.timeout)
	defer cancel()
	return m.mutex.Lock(lockCtx)
}
1063521
func (s *State) Lock(info *state.LockInfo) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	if s.disableLocks {
		return "", nil
	}

	if c, ok := s.Client.(ClientLocker); ok {
		return c.Lock(info)
	}
	return "", nil
}
980452
func (r *keyring) Lock(passphrase []byte) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.locked {
		return errLocked
	}

	r.locked = true
	r.passphrase = passphrase
	return nil
}
1332132
func (c *TeeConn) Lock(ctx context.Context, dirPath, contents string) (topo.LockDescriptor, error) {
	// Lock lockFirst.
	fLD, err := c.lockFirst.Lock(ctx, dirPath, contents)
	if err != nil {
		return nil, err
	}

	// Lock lockSecond.
	sLD, err := c.lockSecond.Lock(ctx, dirPath, contents)
	if err != nil {
		if err := fLD.Unlock(ctx); err != nil {
			log.Warningf("Failed to unlock lockFirst after failed lockSecond lock for %v: %v", dirPath, err)
		}
		return nil, err
	}

	// Remember both locks in teeTopoLockDescriptor.
	return &teeTopoLockDescriptor{
		c:                    c,
		dirPath:              dirPath,
		firstLockDescriptor:  fLD,
		secondLockDescriptor: sLD,
	}, nil
}
281076
func (s *Filesystem) lock() error {
	log.Printf("[TRACE] statemgr.Filesystem: locking %s using fcntl flock", s.path)
	flock := &syscall.Flock_t{
		Type:   syscall.F_RDLCK | syscall.F_WRLCK,
		Whence: int16(os.SEEK_SET),
		Start:  0,
		Len:    0,
	}

	fd := s.stateFileOut.Fd()
	return syscall.FcntlFlock(fd, syscall.F_SETLK, flock)
}
292792
func (r *Registry) WithLock(obj mo.Reference, f func()) {
	if enableLocker {
		mu := r.locker(obj)
		mu.Lock()
		defer mu.Unlock()
	}
	f()
}
225199
func (c *Mutex) Lock(id uint64) {
	c.mapMtx.Lock()
	mtx, ok := c.mutexes[id]
	if ok {
		// If the mutex already existed in the map, we
		// increment its counter, to indicate that there
		// now is one more goroutine waiting for it.
		mtx.cnt++
	} else {
		// If it was not in the map, it means no other
		// goroutine has locked the mutex for this ID,
		// and we can create a new mutex with count 1
		// and add it to the map.
		mtx = &cntMutex{
			cnt: 1,
		}
		c.mutexes[id] = mtx
	}
	c.mapMtx.Unlock()

	// Acquire the mutex for this ID.
	mtx.Lock()
}
412194
func (st *StatsConn) Lock(ctx context.Context, dirPath, contents string) (LockDescriptor, error) {
	startTime := time.Now()
	statsKey := []string{"Lock", st.cell}
	defer topoStatsConnTimings.Record(statsKey, startTime)
	res, err := st.conn.Lock(ctx, dirPath, contents)
	if err != nil {
		topoStatsConnErrors.Add(statsKey, int64(1))
		return res, err
	}
	return res, err
}
493355
func (dm *DRWMutex) lockBlocking(timeout time.Duration, id, source string, isReadLock bool) (locked bool) {
	doneCh, start := make(chan struct{}), time.Now().UTC()
	defer close(doneCh)

	// Use incremental back-off algorithm for repeated attempts to acquire the lock
	for range newRetryTimerSimple(doneCh) {
		// Create temp array on stack.
		locks := make([]string, dm.clnt.dNodeCount)

		// Try to acquire the lock.
		success := lock(dm.clnt, &locks, dm.Name, id, source, isReadLock)
		if success {
			dm.m.Lock()
			defer dm.m.Unlock()

			// If success, copy array to object
			if isReadLock {
				// Append new array of strings at the end
				dm.readersLocks = append(dm.readersLocks, make([]string, dm.clnt.dNodeCount))
				// and copy stack array into last spot
				copy(dm.readersLocks[len(dm.readersLocks)-1], locks[:])
			} else {
				copy(dm.writeLocks, locks[:])
			}

			return true
		}
		if time.Now().UTC().Sub(start) >= timeout { // Are we past the timeout?
			break
		}
		// Failed to acquire the lock on this attempt, incrementally wait
		// for a longer back-off time and try again afterwards.
	}
	return false
}
828538
func (m *Mutex) Lock() {
	spin := NewSpinner(m.priority)
	for !m.TryLock() {
		spin.Yield()
	}
}
94085
func (scheduler *LatchesScheduler) Lock(startTS uint64, keys [][]byte) *Lock {
	lock := scheduler.latches.genLock(startTS, keys)
	lock.wg.Add(1)
	if scheduler.latches.acquire(lock) == acquireLocked {
		lock.wg.Wait()
	}
	if lock.isLocked() {
		panic("should never run here")
	}
	return lock
}
733616
func (c *Conn) Lock(ctx context.Context, dirPath, contents string) (topo.LockDescriptor, error) {
	for {
		c.factory.mu.Lock()

		if c.factory.err != nil {
			c.factory.mu.Unlock()
			return nil, c.factory.err
		}

		n := c.factory.nodeByPath(c.cell, dirPath)
		if n == nil {
			c.factory.mu.Unlock()
			return nil, topo.NewError(topo.NoNode, dirPath)
		}

		if l := n.lock; l != nil {
			// Someone else has the lock. Just wait for it.
			c.factory.mu.Unlock()
			select {
			case <-l:
				// Node was unlocked, try again to grab it.
				continue
			case <-ctx.Done():
				// Done waiting
				return nil, convertError(ctx.Err(), dirPath)
			}
		}

		// Noone has the lock, grab it.
		n.lock = make(chan struct{})
		n.lockContents = contents
		c.factory.mu.Unlock()
		return &memoryTopoLockDescriptor{
			c:       c,
			dirPath: dirPath,
		}, nil
	}
}