// The file lock must be held before calling this
195742
func (b *Backend) open() error {
	if b.f != nil {
		return nil
	}
	if err := os.MkdirAll(filepath.Dir(b.path), b.mode); err != nil {
		return err
	}

	var err error
	b.f, err = os.OpenFile(b.path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, b.mode)
	if err != nil {
		return err
	}

	// Change the file mode in case the log file already existed. We special
	// case /dev/null since we can't chmod it and bypass if the mode is zero
	switch b.path {
	case "/dev/null":
	default:
		if b.mode != 0 {
			err = os.Chmod(b.path, b.mode)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
538776
func (d *Diskv) createKeyFileWithLock(pathKey *PathKey) (*os.File, error) {
	if d.TempDir != "" {
		if err := os.MkdirAll(d.TempDir, d.PathPerm); err != nil {
			return nil, fmt.Errorf("temp mkdir: %s", err)
		}
		f, err := ioutil.TempFile(d.TempDir, "")
		if err != nil {
			return nil, fmt.Errorf("temp file: %s", err)
		}

		if err := f.Chmod(d.FilePerm); err != nil {
			f.Close()           // error deliberately ignored
			os.Remove(f.Name()) // error deliberately ignored
			return nil, fmt.Errorf("chmod: %s", err)
		}
		return f, nil
	}

	mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // overwrite if exists
	f, err := os.OpenFile(d.completeFilename(pathKey), mode, d.FilePerm)
	if err != nil {
		return nil, fmt.Errorf("open file: %s", err)
	}
	return f, nil
}
1118614
func CreateLockFile(file string) (LockFile, error) {
	fname, err := syscall.UTF16PtrFromString(file)
	if err != nil {
		return nil, err
	}
	f, err := syscall.CreateFile(fname,
		syscall.GENERIC_READ|syscall.GENERIC_WRITE,
		0, // dwShareMode: 0 means "Prevents other processes from opening a file or device if they request delete, read, or write access."
		nil,
		syscall.CREATE_ALWAYS,
		syscall.FILE_ATTRIBUTE_NORMAL,
		0,
	)
	if err != nil {
		// TODO: There HAS to be a better way, but I can't seem to
		// find how to get Windows error codes (also syscall.GetLastError()
		// returns nil here).
		if strings.Contains(err.Error(), "used by another process") {
			err = ErrUnableToLockNow
		}
		syscall.CloseHandle(f)
		return nil, err
	}
	return &lockFile{f: f}, nil
}
478203
func newXtablesFileLock() (*fileLock, error) {
	fd, err := syscall.Open(xtablesLockFilePath, os.O_CREATE, defaultFilePerm)
	if err != nil {
		return nil, err
	}
	return &fileLock{fd: fd}, nil
}
351969
func (ss *FileSubStore) lockFile() error {
	wasOpened, err := ss.fm.lockFile(ss.file)
	if err != nil {
		return err
	}
	// If file was not opened, we need to reset ss.writer
	if !wasOpened {
		if ss.bw != nil {
			ss.writer = ss.bw.createNewWriter(ss.file.handle)
		} else {
			ss.writer = ss.file.handle
		}
	}
	return nil
}
966396
func unlockSandbox(lockFile *os.File) error {
	if lockFile == nil {
		return fmt.Errorf("lockFile cannot be empty")
	}

	err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN)
	if err != nil {
		return err
	}

	lockFile.Close()

	return nil
}
357743
func (fbo *folderBranchOps) setHeadPredecessorLocked(ctx context.Context,
	lState *kbfssync.LockState, md ImmutableRootMetadata) error {
	fbo.mdWriterLock.AssertLocked(lState)
	fbo.headLock.AssertLocked(lState)
	if fbo.head == (ImmutableRootMetadata{}) {
		return errors.New("Unexpected nil head in setHeadPredecessorLocked")
	}
	if fbo.head.Revision() <= kbfsmd.RevisionInitial {
		return errors.Errorf("setHeadPredecessorLocked unexpectedly called with revision %d", fbo.head.Revision())
	}

	if fbo.head.MergedStatus() != kbfsmd.Unmerged {
		return errors.New("Unexpected merged head in setHeadPredecessorLocked")
	}

	err := md.CheckValidSuccessor(md.mdID, fbo.head.ReadOnly())
	if err != nil {
		return err
	}

	oldHandle := fbo.head.GetTlfHandle()
	newHandle := md.GetTlfHandle()

	// The two handles must be the same, since no rekeying is done
	// while unmerged.

	eq, err := oldHandle.Equals(fbo.config.Codec(), *newHandle)
	if err != nil {
		return err
	}
	if !eq {
		return errors.Errorf(
			"head handle %v unexpectedly not equal to new handle = %v",
			oldHandle, newHandle)
	}

	return fbo.setHeadLocked(ctx, lState, md, headTrusted, mdToCommitType(md))
}
300849
func (fbo *folderBlockOps) getFileLocked(ctx context.Context,
	lState *kbfssync.LockState, kmd libkey.KeyMetadata, file data.Path,
	rtype data.BlockReqType) (*data.FileBlock, error) {
	// Callers should have already done this check, but it doesn't
	// hurt to do it again.
	if !file.IsValid() {
		return nil, errors.WithStack(InvalidPathError{file})
	}
	fblock, _, err := fbo.getFileBlockLocked(
		ctx, lState, kmd, file.TailPointer(), file, rtype)
	return fblock, err
}
649459
func (fm *filesManager) closeLockedFile(file *file) error {
	if !atomic.CompareAndSwapInt32(&file.state, fileInUse, fileClosing) {
		panic(fmt.Errorf("file %q is requested to be closed but was not locked by caller", file.name))
	}
	fm.Lock()
	err := fm.doClose(file)
	fm.Unlock()
	return err
}
287231
func (f *FileLock) TryLock() error {
	return f.performLock(syscall.LOCK_EX | syscall.LOCK_NB)
}
136070
func (fm *filesManager) lockFileIfOpened(file *file) bool {
	return atomic.CompareAndSwapInt32(&file.state, fileOpened, fileInUse)
}
1200426
func kbfsLibdokanLockFile(
	fname C.LPCWSTR,
	offset C.LONGLONG,
	length C.LONGLONG,
	pfi C.PDOKAN_FILE_INFO) C.NTSTATUS {
	debugf("LockFile '%v' %v", d16{fname}, *pfi)
	ctx, cancel := getContext(pfi)
	if cancel != nil {
		defer cancel()
	}

	err := getfi(pfi).LockFile(ctx, makeFI(fname, pfi), int64(offset), int64(length))
	return errToNT(err)
}
45655
func (s *Filesystem) Lock(info *LockInfo) (string, error) {
	defer s.mutex()()

	if s.stateFileOut == nil {
		if err := s.createStateFiles(); err != nil {
			return "", err
		}
	}

	if s.lockID != "" {
		return "", fmt.Errorf("state %q already locked", s.stateFileOut.Name())
	}

	if err := s.lock(); err != nil {
		info, infoErr := s.lockInfo()
		if infoErr != nil {
			err = multierror.Append(err, infoErr)
		}

		lockErr := &LockError{
			Info: info,
			Err:  err,
		}

		return "", lockErr
	}

	s.lockID = info.ID
	return s.lockID, s.writeLockInfo(info)
}
1302765
func (l *LockFile) Lock(timeout time.Duration) error {
	end := time.Now().Add(timeout)
	for {
		if l.TryLock() {
			return nil
		}
		if time.Now().Before(end) {
			time.Sleep(l.resolution)
			continue
		}
		return ErrTimeout
	}

	return fmt.Errorf("not reached")
}
1125406
func (file *File) Close() error {
	// Should we cancel all pending requests for the File
	return file.Fid.Clnt.Clunk(file.Fid)
}
932512
func writeLock(chartpath string, lock *chartutil.RequirementsLock) error {
	data, err := yaml.Marshal(lock)
	if err != nil {
		return err
	}
	dest := filepath.Join(chartpath, "requirements.lock")
	return ioutil.WriteFile(dest, data, 0644)
}
676132
func (l *fileLock) Unlock() error {
	defer l.mu.Unlock()
	return syscall.Close(l.fd)
}