// LOCKS_EXCLUDED(fs.mu)
543035
func (fs *statFS) MostRecentWriteSize() int {
	fs.mu.Lock()
	defer fs.mu.Unlock()

	return fs.mostRecentWriteSize
}
796596
func (fs *memFS) StatFS(
	ctx context.Context,
	op *fuseops.StatFSOp) (err error) {
	return
}
136070
func (fm *filesManager) lockFileIfOpened(file *file) bool {
	return atomic.CompareAndSwapInt32(&file.state, fileOpened, fileInUse)
}
444217
func (c *consulClientImpl) LockOpts(opts *api.LockOptions) (*api.Lock, error) {
	return c.conn.client.LockOpts(opts)
}
32221
func (h *overlay) FS() ctxvfs.FileSystem {
	return ctxvfs.Sync(&h.mu, ctxvfs.Map(h.m))
}
43596
func (l *Lock) Lock() (err error) {
	return l.store(func(sem *Semaphore) error {
		return sem.Lock(l.id)
	})
}
138410
func LockUnsafe(path string, configbytes []byte, key []byte) (n int, err error) {
	fmt.Printf("Writing %v bytes to %s\n", len(configbytes), path)
	if configbytes == nil {
		return 0, errors.New("seconf: No bytes to write")
	}

	if path == "" {
		return 0, errors.New("seconf: Path can't be blank")
	}

	key = append(key, pad...)
	naclKey := new([keySize]byte)
	copy(naclKey[:], key[:keySize])
	nonce := new([nonceSize]byte)
	// Read bytes from random and put them in nonce until it is full.
	_, err = io.ReadFull(rand.Reader, nonce[:])
	if err != nil {
		return 0, errors.New("Could not read from random: " + err.Error())
	}
	out := make([]byte, nonceSize)
	copy(out, nonce[:])
	out = secretbox.Seal(out, configbytes, nonce, naclKey)

	err = ioutil.WriteFile(path, out, 0600)
	if err != nil {
		return 0, errors.New("Error while writing config file: " + err.Error())
	}

	return len(out), nil
}
468285
func lockPortable(name string) (io.Closer, error) {
	absName, err := filepath.Abs(name)
	if err != nil {
		return nil, fmt.Errorf("can't Lock file %q: can't find abs path: %v", name, err)
	}
	fi, err := os.Stat(absName)
	if err == nil && fi.Size() > 0 {
		if isStaleLock(absName) {
			os.Remove(absName)
		} else {
			return nil, fmt.Errorf("can't Lock file %q: has non-zero size", name)
		}
	}
	f, err := os.OpenFile(absName, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_EXCL, 0666)
	if err != nil {
		return nil, fmt.Errorf("failed to create lock file %s %v", absName, err)
	}
	if err := json.NewEncoder(f).Encode(&pidLockMeta{OwnerPID: os.Getpid()}); err != nil {
		return nil, err
	}
	return &lockCloser{f: f, abs: absName}, nil
}
253476
func (fm *filesManager) lockFile(file *file) (bool, error) {
	if atomic.CompareAndSwapInt32(&file.state, fileOpened, fileInUse) {
		return true, nil
	}
	return false, fm.openFile(file)
}
289094
func (fs *FileStore) Close() error {
	fs.Lock()
	if fs.closed {
		fs.Unlock()
		return nil
	}
	fs.closed = true

	err := fs.genericStore.close()

	fm := fs.fm
	lockFile := fs.lockFile
	fs.Unlock()

	if fm != nil {
		if fmerr := fm.close(); fmerr != nil && err == nil {
			err = fmerr
		}
	}
	if lockFile != nil {
		err = util.CloseFile(err, lockFile)
	}
	return err
}
1041719
func (fbo *folderBlockOps) GetDirtyDirBlockRefs(
	lState *kbfssync.LockState) []data.BlockRef {
	fbo.blockLock.RLock(lState)
	defer fbo.blockLock.RUnlock(lState)
	var dirtyRefs []data.BlockRef
	for ptr := range fbo.dirtyDirs {
		dirtyRefs = append(dirtyRefs, ptr.Ref())
	}
	return dirtyRefs
}
91450
func (fi *FileNode) Fsync(ctx context.Context, req *fuse.FsyncRequest) error {
	// This needs to perform a *full* flush because, in MFS, a write isn't
	// persisted until the root is updated.
	errs := make(chan error, 1)
	go func() {
		errs <- fi.fi.Flush()
	}()
	select {
	case err := <-errs:
		return err
	case <-ctx.Done():
		return ctx.Err()
	}
}
1005144
func (fbo *folderBlockOps) writeDataLocked(
	ctx context.Context, lState *kbfssync.LockState,
	kmd KeyMetadataWithRootDirEntry, file data.Path, buf []byte, off int64) (
	latestWrite WriteRange, dirtyPtrs []data.BlockPointer,
	newlyDirtiedChildBytes int64, err error) {
	if jManager, err := GetJournalManager(fbo.config); err == nil {
		jManager.dirtyOpStart(fbo.id())
		defer jManager.dirtyOpEnd(fbo.id())
	}

	fbo.blockLock.AssertLocked(lState)
	fbo.vlog.CLogf(ctx, libkb.VLog1, "writeDataLocked on file pointer %v",
		file.TailPointer())
	defer func() {
		fbo.vlog.CLogf(ctx, libkb.VLog1, "writeDataLocked done: %v", err)
	}()

	fblock, err := fbo.writeGetFileLocked(ctx, lState, kmd, file)
	if err != nil {
		return WriteRange{}, nil, 0, err
	}

	chargedTo, err := fbo.getChargedToLocked(ctx, lState, kmd)
	if err != nil {
		return WriteRange{}, nil, 0, err
	}

	fd := fbo.newFileData(lState, file, chargedTo, kmd)

	dirtyBcache := fbo.config.DirtyBlockCache()
	df := fbo.getOrCreateDirtyFileLocked(lState, file)
	defer func() {
		// Always update unsynced bytes and potentially force a sync,
		// even on an error, since the previously-dirty bytes stay in
		// the cache.
		df.UpdateNotYetSyncingBytes(newlyDirtiedChildBytes)
		if dirtyBcache.ShouldForceSync(fbo.id()) {
			select {
			// If we can't send on the channel, that means a sync is
			// already in progress.
			case fbo.forceSyncChan <- struct{}{}:
				fbo.vlog.CLogf(
					ctx, libkb.VLog1, "Forcing a sync due to full buffer")
			default:
			}
		}
	}()

	de, err := fbo.getEntryLocked(ctx, lState, kmd, file, true)
	if err != nil {
		return WriteRange{}, nil, 0, err
	}
	if de.BlockPointer != file.TailPointer() {
		fbo.log.CDebugf(ctx, "DirEntry and file tail pointer don't match: "+
			"%v vs %v", de.BlockPointer, file.TailPointer())
	}

	si, err := fbo.getOrCreateSyncInfoLocked(lState, de)
	if err != nil {
		return WriteRange{}, nil, 0, err
	}

	newDe, dirtyPtrs, unrefs, newlyDirtiedChildBytes, bytesExtended, err :=
		fd.Write(ctx, buf, data.Int64Offset(off), fblock, de, df)
	// Record the unrefs before checking the error so we remember the
	// state of newly dirtied blocks.
	si.unrefs = append(si.unrefs, unrefs...)
	if err != nil {
		return WriteRange{}, nil, newlyDirtiedChildBytes, err
	}

	// Update the file's directory entry.
	now := fbo.nowUnixNano()
	newDe.Mtime = now
	newDe.Ctime = now
	err = fbo.updateEntryLocked(ctx, lState, kmd, file, newDe, true)
	if err != nil {
		return WriteRange{}, nil, newlyDirtiedChildBytes, err
	}

	if fbo.doDeferWrite {
		df.AddDeferredNewBytes(bytesExtended)
	}

	latestWrite = si.op.addWrite(uint64(off), uint64(len(buf)))

	return latestWrite, dirtyPtrs, newlyDirtiedChildBytes, nil
}
319524
func Sync(mu *sync.Mutex, fs FileSystem) FileSystem {
	return &syncFS{mu, fs}
}
309614
func (f *fortress) Lockdown(abort Abort) error {
	return f.allowGuests(false, abort)
}
593194
func (c *Client) SearchLocks(filter map[string]string, limit int, localOnly bool, cached bool) ([]Lock, error) {
	if localOnly {
		return c.searchLocalLocks(filter, limit)
	} else if cached {
		if len(filter) > 0 || limit != 0 {
			return []Lock{}, errors.New("can't search cached locks when filter or limit is set")
		}

		locks := []Lock{}
		err := c.readLocksFromCacheFile("remote", func(decoder *json.Decoder) error {
			return decoder.Decode(&locks)
		})
		return locks, err
	} else {
		locks, err := c.searchRemoteLocks(filter, limit)
		if err != nil {
			return locks, err
		}

		if len(filter) == 0 && limit == 0 {
			err = c.writeLocksToCacheFile("remote", func(writer io.Writer) error {
				return c.EncodeLocks(locks, writer)
			})
		}

		return locks, err
	}
}
347097
func LockFile(filelockpath string) (*os.File, error) {

	if true {
		// take advantage of Open and O_EXCL (man creat for more info)
		// the downside of this approach is that killing the application
		// will prevent file lockfile cleanup even if there is a defer os.Remove(lockfile)
	WAIT_FOR_LOCK:
		for {
			glog.V(2).Infof("locking file: %s", filelockpath)
			fp, err := os.OpenFile(filelockpath, syscall.O_RDWR|syscall.O_CREAT|syscall.O_EXCL, 0600)
			if err != nil {
				if !strings.Contains(err.Error(), syscall.EEXIST.Error()) {
					return nil, err
				}
			} else {
				glog.V(2).Infof("locked file: %s", filelockpath)
				return fp, nil
			}

			glog.Infof("waiting to lock file: %s", filelockpath)
			select {
			case <-time.After(1 * time.Second):
				continue WAIT_FOR_LOCK
			}
		}

		//return nil, fmt.Errorf("timed out waiting to lock file %s", filelockpath)
	} else {

		// other failed attempts to lock file using fcntl/flock/...
		fp, err := os.OpenFile(filelockpath, syscall.O_RDWR|syscall.O_CREAT, 0600)
		if err != nil {
			return nil, err
		}

		glog.V(2).Infof("locking file: %s", filelockpath)
		if false {
			// FIXME: this is not working from GO, but works from C - thread issue even when sync mutex is used
			var flp = C.CString(filelockpath)
			defer C.free(unsafe.Pointer(flp))
			rc := C.fd_lock(C.int(fp.Fd()), flp)
			if 0 != rc {
				return nil, fmt.Errorf("unable to lock file %s", filelockpath)
			}
			/*
				} else if false {
					// BEWARE: flock does not work when two hosts are NFS locking
					// flock tested and works on ubuntu: ext4, btrfs, NFS (same host)
					// flock tested on centos: tmpfs, ext4, btrfs, NFS (same host)
					if err := unix.Flock(int(fp.Fd()), unix.LOCK_EX); err != nil {
						return nil, err
					}
				} else if false {
					// FIXME: unix.FcntlFlock is not working - thread issue and NFS issue
					ft := unix.Flock_t{
						Type:   syscall.F_WRLCK,         //Type of lock: F_RDLCK, F_WRLCK, F_UNLCK
						Whence: int16(os.SEEK_SET),      // How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END
						Start:  0,                       // Starting offset for lock
						Len:    0,                       // Number of bytes to lock
						Pid:    int32(syscall.Getpid()), // PID of process blocking our lock (F_GETLK only)
					}
					glog.V(2).Infof("syscall.Flock_t %#v", ft)

					if err := unix.FcntlFlock(fp.Fd(), syscall.F_SETLKW, &ft); err != nil {
						return nil, err
					}
			*/
		} else if false {
			// FIXME: flock does not work when two hosts are NFS locking
			// flock tested and works on ubuntu: ext4, btrfs, NFS (same host)
			// flock tested on centos: tmpfs, ext4, btrfs, NFS (same host)
			if err := syscall.Flock(int(fp.Fd()), syscall.LOCK_EX); err != nil {
				return nil, err
			}
		} else if false {
			// FIXME: syscall.FcntlFlock is not working - thread issue and syscall issue and NFS issue
			ft := syscall.Flock_t{
				Type:   syscall.F_WRLCK,         //Type of lock: F_RDLCK, F_WRLCK, F_UNLCK
				Whence: int16(os.SEEK_SET),      // How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END
				Start:  0,                       // Starting offset for lock
				Len:    0,                       // Number of bytes to lock
				Pid:    int32(syscall.Getpid()), // PID of process blocking our lock (F_GETLK only)
			}
			glog.V(2).Infof("syscall.Flock_t %#v", ft)

			if err := syscall.FcntlFlock(fp.Fd(), syscall.F_SETLKW /* F_GETLK, F_SETLK, F_SETLKW */, &ft); err != nil {
				return nil, err
			}
		} else if false {
			// FIXME: syscall.FcntlFlock is not working - thread issue and syscall issue and NFS issue
			// This type matches C's "struct flock" defined in /usr/include/x86_64-linux-gnu/bits/fcntl.h
			k := struct {
				Type   uint32
				Whence uint32
				Start  uint64
				Len    uint64
				Pid    uint32
			}{
				Type:   syscall.F_WRLCK,
				Whence: uint32(os.SEEK_SET),
				Start:  0,
				Len:    0, // 0 means to lock the entire file.
				Pid:    uint32(os.Getpid()),
			}

			glog.V(2).Infof("mimic /usr/include/x86_64-linux-gnu/bits/fcntl.h syscall.Flock_t %#v", k)
			_, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fp.Fd(), uintptr(syscall.F_SETLK), uintptr(unsafe.Pointer(&k)))
			if errno != 0 {
				fp.Close()
				return nil, fmt.Errorf("syscall.Syscall error: %s", errno)
			}
		} else {
			return nil, fmt.Errorf("all filelocking implementations fail")
		}

		glog.V(2).Infof("locked  file: %s", filelockpath)
		return fp, nil
	}
}