From deca81fa7e5a2b6040325c87959df6630d50b791 Mon Sep 17 00:00:00 2001 From: Steven Wu Date: Tue, 6 May 2025 13:49:11 -0700 Subject: [PATCH] [CAS] sync memory mapped file when closing CAS To avoid unnecessary data lost due to power lost immediately after the build, make sure the mapped files in the CAS are sync'ed back to the file system when the last user of the CAS closed the file. rdar://150379440 --- llvm/lib/CAS/MappedFileRegionBumpPtr.cpp | 3 ++- llvm/lib/Support/Unix/Path.inc | 6 ++++++ llvm/lib/Support/Windows/Path.inc | 6 ++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/llvm/lib/CAS/MappedFileRegionBumpPtr.cpp b/llvm/lib/CAS/MappedFileRegionBumpPtr.cpp index 3c01331c61b81..e1f73dd9fc048 100644 --- a/llvm/lib/CAS/MappedFileRegionBumpPtr.cpp +++ b/llvm/lib/CAS/MappedFileRegionBumpPtr.cpp @@ -53,7 +53,6 @@ #include "llvm/CAS/MappedFileRegionBumpPtr.h" #include "OnDiskCommon.h" -#include "llvm/ADT/StringMap.h" #include "llvm/CAS/OnDiskCASLogger.h" using namespace llvm; @@ -196,6 +195,8 @@ void MappedFileRegionBumpPtr::destroyImpl() { size_t Size = size(); size_t Capacity = capacity(); assert(Size < Capacity); + // sync to file system to make sure all contents are up-to-date. + (void)Region.sync(); (void)sys::fs::resize_file(*FD, size()); (void)unlockFileThreadSafe(*SharedLockFD); diff --git a/llvm/lib/Support/Unix/Path.inc b/llvm/lib/Support/Unix/Path.inc index 891aba31d3451..50ef812b60397 100644 --- a/llvm/lib/Support/Unix/Path.inc +++ b/llvm/lib/Support/Unix/Path.inc @@ -876,6 +876,12 @@ void mapped_file_region::unmapImpl() { ::munmap(Mapping, Size); } +std::error_code mapped_file_region::sync() const { + if (int Res = ::msync(Mapping, Size, MS_SYNC)) + return std::error_code(Res, std::generic_category()); + return std::error_code(); +} + void mapped_file_region::dontNeedImpl() { assert(Mode == mapped_file_region::readonly); if (!Mapping) diff --git a/llvm/lib/Support/Windows/Path.inc b/llvm/lib/Support/Windows/Path.inc index 39f8c6925a502..736fd1f58b709 100644 --- a/llvm/lib/Support/Windows/Path.inc +++ b/llvm/lib/Support/Windows/Path.inc @@ -1011,6 +1011,12 @@ void mapped_file_region::unmapImpl() { void mapped_file_region::dontNeedImpl() {} +std::error_code mapped_file_region::sync() const { + if (::FlushViewOfFile(Mapping, 0)) + return std::error_code(); + return mapWindowsError(::GetLastError()); +} + int mapped_file_region::alignment() { SYSTEM_INFO SysInfo; ::GetSystemInfo(&SysInfo);