// Does any clean-up for a sync of the given file, given an error
// (which may be nil) that happens during or after StartSync() and
// before FinishSync(). blocksToRemove may be nil.
197582
func (fbo *folderBlockOps) CleanupSyncState(
	ctx context.Context, lState *kbfssync.LockState, md ReadOnlyRootMetadata,
	file data.Path, blocksToRemove []data.BlockPointer,
	result fileSyncState, err error) {
	if jManager, err := GetJournalManager(fbo.config); err == nil {
		defer jManager.dirtyOpEnd(fbo.id())
	}

	if err == nil {
		return
	}

	fbo.blockLock.Lock(lState)
	defer fbo.blockLock.Unlock(lState)

	// Notify error listeners before we reset the dirty blocks and
	// permissions to be granted.
	fbo.notifyErrListenersLocked(lState, file.TailPointer(), err)

	// If there was an error, we need to back out any changes that
	// might have been filled into the sync op, because it could
	// get reused again in a later Sync call.
	if result.si != nil {
		result.si.op.resetUpdateState()

		// Save this MD for later, so we can clean up its
		// newly-referenced block pointers if necessary.
		bpsCopy, err := result.si.bps.deepCopy(ctx)
		if err != nil {
			return
		}
		result.si.toCleanIfUnused = append(result.si.toCleanIfUnused,
			mdToCleanIfUnused{md, bpsCopy})
	}
	if isRecoverableBlockError(err) {
		if result.si != nil {
			fbo.revertSyncInfoAfterRecoverableError(ctx, blocksToRemove, result)
		}
		if result.fblock != nil {
			result.fblock.Set(result.savedFblock)
			fbo.fixChildBlocksAfterRecoverableErrorLocked(
				ctx, lState, file, md,
				result.redirtyOnRecoverableError)
		}
	} else {
		// Since the sync has errored out unrecoverably, the deferred
		// bytes are already accounted for.
		ds := fbo.deferred[file.TailRef()]
		if df := fbo.dirtyFiles[file.TailPointer()]; df != nil {
			df.UpdateNotYetSyncingBytes(-ds.waitBytes)

			// Some blocks that were dirty are now clean under their
			// readied block ID, and now live in the bps rather than
			// the dirty bcache, so we can delete them from the dirty
			// bcache.
			dirtyBcache := fbo.config.DirtyBlockCache()
			for _, ptr := range result.oldFileBlockPtrs {
				if df.IsBlockOrphaned(ptr) {
					fbo.vlog.CLogf(
						ctx, libkb.VLog1, "Deleting dirty orphan: %v", ptr)
					if err := dirtyBcache.Delete(fbo.id(), ptr,
						fbo.branch()); err != nil {
						fbo.vlog.CLogf(
							ctx, libkb.VLog1, "Couldn't delete %v", ptr)
					}
				}
			}
		}

		// On an unrecoverable error, the deferred writes aren't
		// needed anymore since they're already part of the
		// (still-)dirty blocks.
		delete(fbo.deferred, file.TailRef())
	}

	// The sync is over, due to an error, so reset the map so that we
	// don't defer any subsequent writes.
	// Old syncing blocks are now just dirty
	if df := fbo.dirtyFiles[file.TailPointer()]; df != nil {
		df.ResetSyncingBlocksToDirty()
	}
}
360504
func (c *Conf) Cleanup() (err error) {
	err = os.RemoveAll(c.dirPath)
	return
}
1341997
func (s *blockWriteStream) finish() error {
	if s.closed {
		return nil
	}
	s.closed = true

	if err := s.getAckError(); err != nil {
		return err
	}

	err := s.flush(true)
	if err != nil {
		return err
	}

	// The last packet has no data; it's just a marker that the block is finished.
	lastPacket := outboundPacket{
		seqno:     s.seqno,
		offset:    s.offset,
		last:      true,
		checksums: []byte{},
		data:      []byte{},
	}
	s.packets <- lastPacket
	err = s.writePacket(lastPacket)
	if err != nil {
		return err
	}
	close(s.packets)

	// Wait for the ack loop to finish.
	<-s.acksDone

	// Check one more time for any ack errors.
	if err := s.getAckError(); err != nil {
		return err
	}

	return nil
}
589673
func (ss *FileSubStore) Flush() error {
	ss.Lock()
	err := ss.lockFile()
	if err == nil {
		err = ss.flush()
		ss.fm.unlockFile(ss.file)
	}
	ss.Unlock()
	return err
}
1105040
func (df *DirtyFile) SetBlockDirty(ptr BlockPointer) (
	needsCaching bool, isSyncing bool) {
	df.lock.Lock()
	defer df.lock.Unlock()

	state := df.fileBlockStates[ptr]
	needsCaching = state.copy == blockNeedsCopy
	state.copy = blockAlreadyCopied
	isSyncing = state.sync != blockNotSyncing
	df.fileBlockStates[ptr] = state
	return needsCaching, isSyncing
}
1255675
func (writer *baseFileWriter) SetHookAsync(async bool) {
	writer.lock.Lock()
	defer writer.lock.Unlock()
	writer.hookAsync = async
}
100942
func (w *Writer) finishBlock() (blockHandle, error) {
	// Write the restart points to the buffer.
	if w.nEntries == 0 {
		// Every block must have at least one restart point.
		w.restarts = w.restarts[:1]
		w.restarts[0] = 0
	}
	tmp4 := w.tmp[:4]
	for _, x := range w.restarts {
		binary.LittleEndian.PutUint32(tmp4, x)
		w.buf = append(w.buf, tmp4...)
	}
	binary.LittleEndian.PutUint32(tmp4, uint32(len(w.restarts)))
	w.buf = append(w.buf, tmp4...)

	// Compress the buffer, discarding the result if the improvement
	// isn't at least 12.5%.
	b := w.buf
	blockType := byte(noCompressionBlockType)
	if w.compression == db.SnappyCompression {
		compressed := snappy.Encode(w.compressedBuf, b)
		w.compressedBuf = compressed[:cap(compressed)]
		if len(compressed) < len(b)-len(b)/8 {
			blockType = snappyCompressionBlockType
			b = compressed
		}
	}
	bh, err := w.writeRawBlock(b, blockType)

	// Calculate filters.
	if w.filter.policy != nil {
		w.filter.finishBlock(w.offset)
	}

	// Reset the per-block state.
	w.buf = w.buf[:0]
	w.nEntries = 0
	w.restarts = w.restarts[:0]

	return bh, err
}
362720
func (ms *FileMsgStore) Flush() error {
	ms.Lock()
	var err error
	if ms.writeSlice != nil {
		err = ms.lockFiles(ms.writeSlice)
		if err == nil {
			err = ms.flush(ms.writeSlice)
			ms.unlockFiles(ms.writeSlice)
		}
	}
	ms.Unlock()
	return err
}
154482
func (o *copier) Cleanup() {
	for _, path := range o.tmpPaths {
		os.RemoveAll(path)
	}
	o.tmpPaths = []string{}
	if o.activeLayer != nil {
		o.activeLayer.Release()
		o.activeLayer = nil
	}
}
834448
func CleanKeyLocks(lockDir string) error {
	f, err := os.Open(lockDir)
	if err != nil {
		return errwrap.Wrap(errors.New("error opening lockDir"), err)
	}
	defer f.Close()
	files, err := f.Readdir(0)
	if err != nil {
		return errwrap.Wrap(errors.New("error getting lock files list"), err)
	}
	for _, f := range files {
		filename := filepath.Join(lockDir, f.Name())
		keyLock, err := TryExclusiveKeyLock(lockDir, f.Name())
		if err == ErrLocked {
			continue
		}
		if err != nil {
			return err
		}

		err = os.Remove(filename)
		if err != nil {
			keyLock.Close()
			return errwrap.Wrap(errors.New("error removing lock file"), err)
		}
		keyLock.Close()
	}
	return nil
}
92131
func (f *File) Cleanup(ctx context.Context, fi *dokan.FileInfo) {
	var err error
	f.folder.fs.logEnter(ctx, "File Cleanup")
	defer func() { f.folder.reportErr(ctx, libkbfs.WriteMode, err) }()

	f.folder.fs.vlog.CLogf(ctx, libkb.VLog1, "Cleanup %v", *f)
	if fi != nil && fi.IsDeleteOnClose() {
		// renameAndDeletionLock should be the first lock to be grabbed in libdokan.
		f.folder.fs.renameAndDeletionLock.Lock()
		defer f.folder.fs.renameAndDeletionLock.Unlock()
		f.folder.fs.vlog.CLogf(
			ctx, libkb.VLog1, "Removing (Delete) file in cleanup %s", f.name)

		err = f.folder.fs.config.KBFSOps().RemoveEntry(ctx, f.parent, f.name)
	}

	if f.refcount.Decrease() {
		f.folder.fs.vlog.CLogf(ctx, libkb.VLog1, "Forgetting file node")
		f.folder.forgetNode(ctx, f.node)
	}
}
566665
func cleanup(files ...*os.File) {
	for _, file := range files {
		_ = file.Close()
		_ = os.Remove(file.Name())
	}
}
681169
func (f *FileStorage) Flush() error {
	defer f.subscription.NotifyAll(0)
	return f.file.Sync()
}
648297
func (s *nodeStore) Clean() {
	s.mu.Lock()
	for _, rn := range s.nodes {
		rn.Heartbeat.Stop()
	}
	s.nodes = make(map[string]*registeredNode)
	s.mu.Unlock()
}
147227
func (fbo *folderBlockOps) GetDirtyFileBlockRefs(
	lState *kbfssync.LockState) []data.BlockRef {
	fbo.blockLock.RLock(lState)
	defer fbo.blockLock.RUnlock(lState)
	var dirtyRefs []data.BlockRef
	for ref := range fbo.unrefCache {
		dirtyRefs = append(dirtyRefs, ref)
	}
	return dirtyRefs
}
705403
func NewBlockDataToJSONFiles(folder string, fileBase string,
	m ...*sync.Mutex) *BlockDataToJSONFiles {
	if len(m) > 1 {
		panic("Too many inputs.")
	}

	var mtx *sync.Mutex
	if len(m) > 0 {
		mtx = m[0]
	} else {
		mtx = new(sync.Mutex)
	}

	return &BlockDataToJSONFiles{
		fileSaver: fileSaver{
			folder:   folder,
			nameBase: fileBase,
			file:     os.File{},
			mtx:      mtx,
		},
	}
}
18373
func (w *WALSegmentWriter) sync() error {
	if err := w.bw.Flush(); err != nil {
		return err
	}

	if f, ok := w.w.(*os.File); ok {
		return f.Sync()
	}
	return nil
}