From e0380933e3745214331d358bda8c5e79299c84d2 Mon Sep 17 00:00:00 2001 From: Jim Posen Date: Sun, 6 Jan 2019 10:14:35 -0800 Subject: validation: Refactor file flush logic into FlatFileSeq. --- src/flatfile.cpp | 19 +++++++++++++++++++ src/flatfile.h | 9 +++++++++ src/validation.cpp | 23 +++++------------------ 3 files changed, 33 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/flatfile.cpp b/src/flatfile.cpp index d9fd4041b7..1cdead6bf5 100644 --- a/src/flatfile.cpp +++ b/src/flatfile.cpp @@ -72,3 +72,22 @@ size_t FlatFileSeq::Allocate(const CDiskBlockPos& pos, size_t add_size, bool& ou } return 0; } + +bool FlatFileSeq::Flush(const CDiskBlockPos& pos, bool finalize) +{ + FILE* file = Open(FlatFilePos(pos.nFile, 0)); // Avoid fseek to nPos + if (!file) { + return error("%s: failed to open file %d", __func__, pos.nFile); + } + if (finalize && !TruncateFile(file, pos.nPos)) { + fclose(file); + return error("%s: failed to truncate file %d", __func__, pos.nFile); + } + if (!FileCommit(file)) { + fclose(file); + return error("%s: failed to commit file %d", __func__, pos.nFile); + } + + fclose(file); + return true; +} diff --git a/src/flatfile.h b/src/flatfile.h index 1b5d83e8e6..eea41ddf84 100644 --- a/src/flatfile.h +++ b/src/flatfile.h @@ -45,6 +45,15 @@ public: * @return The number of bytes successfully allocated. */ size_t Allocate(const CDiskBlockPos& pos, size_t add_size, bool& out_of_space); + + /** + * Commit a file to disk, and optionally truncate off extra pre-allocated bytes if final. + * + * @param[in] pos The first unwritten position in the file to be flushed. + * @param[in] finalize True if no more data will be written to this file. + * @return true on success, false on failure. + */ + bool Flush(const CDiskBlockPos& pos, bool finalize = false); }; #endif // BITCOIN_FLATFILE_H diff --git a/src/validation.cpp b/src/validation.cpp index aca555ee0a..98d89599f1 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -1630,25 +1630,12 @@ void static FlushBlockFile(bool fFinalize = false) { LOCK(cs_LastBlockFile); - CDiskBlockPos posOld(nLastBlockFile, 0); - bool status = true; - - FILE *fileOld = OpenBlockFile(posOld); - if (fileOld) { - if (fFinalize) - status &= TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize); - status &= FileCommit(fileOld); - fclose(fileOld); - } - - fileOld = OpenUndoFile(posOld); - if (fileOld) { - if (fFinalize) - status &= TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize); - status &= FileCommit(fileOld); - fclose(fileOld); - } + CDiskBlockPos block_pos_old(nLastBlockFile, vinfoBlockFile[nLastBlockFile].nSize); + CDiskBlockPos undo_pos_old(nLastBlockFile, vinfoBlockFile[nLastBlockFile].nUndoSize); + bool status = true; + status &= BlockFileSeq().Flush(block_pos_old, fFinalize); + status &= UndoFileSeq().Flush(undo_pos_old, fFinalize); if (!status) { AbortNode("Flushing block file to disk failed. This is likely the result of an I/O error."); } -- cgit v1.2.3