LLVM 24.0.0git
MappedFileRegionArena.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file Implements MappedFileRegionArena.
9///
10/// A bump pointer allocator, backed by a memory-mapped file.
11///
12/// The effect we want is:
13///
14/// Step 1. If it doesn't exist, create the file with an initial size.
15/// Step 2. Reserve virtual memory large enough for the max file size.
16/// Step 3. Map the file into memory in the reserved region.
17/// Step 4. Increase the file size and update the mapping when necessary.
18///
19/// However, updating the mapping is challenging when it needs to work portably,
20/// and across multiple processes without locking for every read. Our current
21/// implementation handles the steps above in following ways:
22///
23/// Step 1. Use \ref sys::fs::resize_file_sparse to grow the file to its max
24/// size (typically several GB). If the file system doesn't support
25/// sparse file, this may return a fully allocated file.
26/// Step 2. Call \ref sys::fs::mapped_file_region to map the entire file.
27/// Step 3. [Automatic as part of step 2.]
28/// Step 4. If supported, use \c fallocate or similiar APIs to ensure the file
29/// system storage for the sparse file so we won't end up with partial
30/// file if the disk is out of space.
31///
32/// Additionally, we attempt to resize the file to its actual data size when
33/// closing the mapping, if this is the only concurrent instance. This is done
34/// using file locks. Shrinking the file mitigates problems with having large
35/// files: on filesystems without sparse files it avoids unnecessary space use;
36/// it also avoids allocating the full size if another process copies the file,
37/// which typically loses sparseness. These mitigations only work while the file
38/// is not in use.
39///
40/// The capacity and the header offset is determined by the first user of the
41/// MappedFileRegionArena instance and any future mismatched value from the
42/// original will result in error on creation.
43///
44/// To support resizing, we use two separate file locks:
45/// 1. We use a shared reader lock on a ".shared" file until destruction.
46/// 2. We use a lock on the main file during initialization - shared to check
47/// the status, upgraded to exclusive to resize/initialize the file.
48///
49/// Then during destruction we attempt to get exclusive access on (1), which
50/// requires no concurrent readers. If so, we shrink the file. Using two
51/// separate locks simplifies the implementation and enables it to work on
52/// platforms (e.g. Windows) where a shared/reader lock prevents writing.
53//===----------------------------------------------------------------------===//
54
56#include "OnDiskCommon.h"
59#include "llvm/Support/Errno.h"
60
61#if LLVM_ON_UNIX
62#include <sys/stat.h>
63#if __has_include(<sys/param.h>)
64#include <sys/param.h>
65#endif
66#ifdef DEV_BSIZE
67#define MAPPED_FILE_BSIZE DEV_BSIZE
68#elif __linux__
69#define MAPPED_FILE_BSIZE 512
70#endif
71#endif
72
73using namespace llvm;
74using namespace llvm::cas;
75using namespace llvm::cas::ondisk;
76
77namespace {
78struct FileWithLock {
79 std::string Path;
80 int FD = -1;
81 std::optional<sys::fs::LockKind> Locked;
82
83private:
84 FileWithLock(std::string PathStr, Error &E) : Path(std::move(PathStr)) {
85 ErrorAsOutParameter EOP(&E);
86 if (std::error_code EC = sys::fs::openFileForReadWrite(
88 E = createFileError(Path, EC);
89 }
90
91public:
92 FileWithLock(FileWithLock &) = delete;
93 FileWithLock(FileWithLock &&Other) {
94 Path = std::move(Other.Path);
95 FD = Other.FD;
96 Other.FD = -1;
97 Locked = Other.Locked;
98 Other.Locked = std::nullopt;
99 }
100
101 ~FileWithLock() { consumeError(unlock()); }
102
103 static Expected<FileWithLock> open(StringRef Path) {
105 FileWithLock Result(Path.str(), E);
106 if (E)
107 return std::move(E);
108 return std::move(Result);
109 }
110
111 Error lock(sys::fs::LockKind LK) {
112 assert(!Locked && "already locked");
113 if (std::error_code EC = lockFileThreadSafe(FD, LK))
114 return createFileError(Path, EC);
115 Locked = LK;
116 return Error::success();
117 }
118
119 Error switchLock(sys::fs::LockKind LK) {
120 assert(Locked && "not locked");
121 if (auto E = unlock())
122 return E;
123
124 return lock(LK);
125 }
126
127 Error unlock() {
128 if (Locked) {
129 Locked = std::nullopt;
130 if (std::error_code EC = unlockFileThreadSafe(FD))
131 return createFileError(Path, EC);
132 }
133 return Error::success();
134 }
135
136 // Return true if succeed to lock the file exclusively.
137 bool tryLockExclusive() {
138 assert(!Locked && "can only try to lock if not locked");
139 if (tryLockFileThreadSafe(FD) == std::error_code()) {
140 Locked = sys::fs::LockKind::Exclusive;
141 return true;
142 }
143
144 return false;
145 }
146
147 // Release the lock so it will not be unlocked on destruction.
148 void release() {
149 Locked = std::nullopt;
150 FD = -1;
151 }
152};
153
154struct FileSizeInfo {
155 uint64_t Size;
156 uint64_t AllocatedSize;
157
158 static ErrorOr<FileSizeInfo> get(sys::fs::file_t File);
159};
160} // end anonymous namespace
161
163 const Twine &Path, uint64_t Capacity, uint64_t HeaderOffset,
164 std::shared_ptr<ondisk::OnDiskCASLogger> Logger,
165 function_ref<Error(MappedFileRegionArena &)> NewFileConstructor) {
166 uint64_t MinCapacity = HeaderOffset + sizeof(Header);
167 if (Capacity < MinCapacity)
168 return createStringError(
169 std::make_error_code(std::errc::invalid_argument),
170 "capacity is too small to hold MappedFileRegionArena");
171
173 Result.Path = Path.str();
174 Result.Logger = std::move(Logger);
175
176 // Open the support file. See file comment for details of locking scheme.
177 SmallString<128> SharedFilePath(Result.Path);
178 SharedFilePath.append(".shared");
179
180 auto SharedFileLock = FileWithLock::open(SharedFilePath);
181 if (!SharedFileLock)
182 return SharedFileLock.takeError();
183 Result.SharedLockFD = SharedFileLock->FD;
184
185 // Take shared/reader lock that will be held until destroyImpl if construction
186 // is successful.
187 if (auto E = SharedFileLock->lock(sys::fs::LockKind::Shared))
188 return std::move(E);
189
190 // Take shared/reader lock for initialization.
191 auto MainFile = FileWithLock::open(Result.Path);
192 if (!MainFile)
193 return MainFile.takeError();
194 if (Error E = MainFile->lock(sys::fs::LockKind::Shared))
195 return std::move(E);
196 Result.FD = MainFile->FD;
197
199 auto FileSize = FileSizeInfo::get(File);
200 if (!FileSize)
201 return createFileError(Result.Path, FileSize.getError());
202
203 // If the size is smaller than the capacity, we need to initialize the file.
204 // It maybe empty, or may have been shrunk during a previous close.
205 if (FileSize->Size < Capacity) {
206 // Lock the file exclusively so only one process will do the initialization.
207 if (Error E = MainFile->switchLock(sys::fs::LockKind::Exclusive))
208 return std::move(E);
209 // Retrieve the current size now that we have exclusive access.
210 FileSize = FileSizeInfo::get(File);
211 if (!FileSize)
212 return createFileError(Result.Path, FileSize.getError());
213 }
214
215 if (FileSize->Size >= MinCapacity) {
216 // File is initialized. Read out the header to check for capacity and
217 // offset.
218 SmallVector<char, sizeof(Header)> HeaderContent(sizeof(Header));
219 auto Size = sys::fs::readNativeFileSlice(File, HeaderContent, HeaderOffset);
220 if (!Size)
221 return Size.takeError();
222
223 Header H;
224 memcpy(&H, HeaderContent.data(), sizeof(H));
225 if (H.HeaderOffset != HeaderOffset)
226 return createStringError(
227 std::make_error_code(std::errc::invalid_argument),
228 "specified header offset (" + utostr(HeaderOffset) +
229 ") does not match existing config (" + utostr(H.HeaderOffset) +
230 ")");
231
232 if (H.Capacity < MinCapacity)
233 return createStringError(
234 std::make_error_code(std::errc::bad_file_descriptor),
235 "capacity inside the MappedFileRegionArena is too small");
236
237 // If the capacity doesn't match, use the existing capacity instead.
238 if (H.Capacity != Capacity)
239 Capacity = H.Capacity;
240 }
241
242 // If the size is smaller than capacity, we need to resize the file.
243 if (FileSize->Size < Capacity) {
244 // Acquire the exclusive lock before resizing the file. In the rare case
245 // when opening a large CAS using a small requested size, a shared lock
246 // needs to switch to an exclusive lock here.
247 if (MainFile->Locked != sys::fs::LockKind::Exclusive) {
248 if (Error E = MainFile->switchLock(sys::fs::LockKind::Exclusive))
249 return std::move(E);
250 }
251 if (std::error_code EC =
252 sys::fs::resize_file_sparse(MainFile->FD, Capacity))
253 return createFileError(Result.Path, EC);
254 if (Result.Logger)
255 Result.Logger->logMappedFileRegionArenaResizeFile(
256 Result.Path, FileSize->Size, Capacity);
257 }
258
259 // Create the mapped region.
260 {
261 std::error_code EC;
262 const char *Name = nullptr;
263#ifdef _WIN32
264 // Give the file mapping a name to ensure the same mappings are
265 // shared across processes.
266 std::string MapName = Result.Path;
267 std::replace(MapName.begin(), MapName.end(), '\\', '/');
268 MapName = "Local\\" + MapName;
269 Name = MapName.c_str();
270#endif
272 File, sys::fs::mapped_file_region::readwrite, Capacity, 0, EC, Name);
273 if (EC)
274 return createFileError(Result.Path, EC);
275 Result.Region = std::move(Map);
276 }
277
278 // Initialize the header.
279 if (Error E = Result.initializeHeader(HeaderOffset))
280 return std::move(E);
281
282 if (FileSize->Size < MinCapacity) {
283 assert(MainFile->Locked == sys::fs::LockKind::Exclusive);
284 // If we need to fully initialize the file, call NewFileConstructor.
285 if (Error E = NewFileConstructor(Result))
286 return std::move(E);
287
288 Result.H->HeaderOffset.exchange(HeaderOffset);
289 Result.H->Capacity.exchange(Capacity);
290 }
291
292 if (MainFile->Locked == sys::fs::LockKind::Exclusive) {
293 // If holding an exclusive lock, we might have resized the file and
294 // performed some read/write to the file. Query the file size again to make
295 // sure everything is up-to-date. Otherwise, FileSize info is already
296 // up-to-date.
297 FileSize = FileSizeInfo::get(File);
298 if (!FileSize)
299 return createFileError(Result.Path, FileSize.getError());
300 Result.H->AllocatedSize.exchange(FileSize->AllocatedSize);
301 }
302
303 // Release the shared lock so it can be closed in destoryImpl().
304 SharedFileLock->release();
305 return std::move(Result);
306}
307
308void MappedFileRegionArena::destroyImpl() {
309 if (!FD)
310 return;
311
312 // Drop the shared lock indicating we are no longer accessing the file.
313 if (SharedLockFD)
314 (void)unlockFileThreadSafe(*SharedLockFD);
315
316 // Attempt to truncate the file if we can get exclusive access. Ignore any
317 // errors.
318 if (H) {
319 assert(SharedLockFD && "Must have shared lock file open");
320 if (tryLockFileThreadSafe(*SharedLockFD) == std::error_code()) {
321 size_t Size = size();
322 size_t Capacity = capacity();
323 // sync to file system to make sure all contents are up-to-date.
324 (void)Region.sync();
325 // unmap the file before resizing since that is the requirement for
326 // some platforms.
327 Region.unmap();
328 (void)sys::fs::resize_file(*FD, Size);
329 (void)unlockFileThreadSafe(*SharedLockFD);
330 if (Logger)
331 Logger->logMappedFileRegionArenaResizeFile(Path, Capacity, Size);
332 }
333 }
334
335#ifdef _WIN32
336 // Always unmap to
337 // - avoid address space leak;
338 // - avoid data loss for sparse files.
339 if (Region)
340 Region.unmap();
341#endif
342
343 auto Close = [](std::optional<int> &FD) {
344 if (FD) {
346 sys::fs::closeFile(File);
347 FD = std::nullopt;
348 }
349 };
350
351 // Close the file and shared lock.
352 Close(FD);
353 Close(SharedLockFD);
354
355 if (Logger)
356 Logger->logMappedFileRegionArenaClose(Path);
357}
358
359Error MappedFileRegionArena::initializeHeader(uint64_t HeaderOffset) {
360 if (capacity() >= static_cast<uint64_t>(INT64_MAX))
361 return createStringError(make_error_code(std::errc::protocol_error),
362 "arena capacity does not fit in int64_t");
363 uint64_t HeaderEndOffset = HeaderOffset + sizeof(decltype(*H));
364 if (HeaderEndOffset > capacity())
365 return createStringError(make_error_code(std::errc::protocol_error),
366 "arena header extends past capacity");
367 if (!isAligned(Align::Of<decltype(*H)>(), HeaderOffset))
368 return createStringError(make_error_code(std::errc::protocol_error),
369 "arena header offset is not aligned");
370 H = reinterpret_cast<decltype(H)>(data() + HeaderOffset);
371
372 uint64_t ExistingValue = 0;
373 if (!H->BumpPtr.compare_exchange_strong(ExistingValue, HeaderEndOffset))
374 if (ExistingValue < HeaderEndOffset)
375 return createStringError(
376 make_error_code(std::errc::protocol_error),
377 "arena bump pointer is corrupt: 0x" +
378 utohexstr(ExistingValue, /*LowerCase=*/true));
379 if (Logger)
380 Logger->logMappedFileRegionArenaCreate(Path, *FD, data(), capacity(),
381 size());
382 return Error::success();
383}
384
386 return createStringError(std::make_error_code(std::errc::not_enough_memory),
387 "memory mapped file allocator is out of space");
388}
389
391 AllocSize = alignTo(AllocSize, getAlign());
392 uint64_t OldEnd = H->BumpPtr.fetch_add(AllocSize);
393 uint64_t NewEnd = OldEnd + AllocSize;
394 if (LLVM_UNLIKELY(NewEnd > capacity())) {
395 // Return the allocation. If the start already passed the end, that means
396 // some other concurrent allocations already consumed all the capacity.
397 // There is no need to return the original value. If the start was not
398 // passed the end, current allocation certainly bumped it passed the end.
399 // All other allocation afterwards must have failed and current allocation
400 // is in charge of return the allocation back to a valid value.
401 if (OldEnd <= capacity())
402 (void)H->BumpPtr.exchange(OldEnd);
403
404 if (Logger)
405 Logger->logMappedFileRegionArenaOom(Path, capacity(), OldEnd, AllocSize);
406
408 }
409
410 uint64_t DiskSize = H->AllocatedSize;
411 if (LLVM_UNLIKELY(NewEnd > DiskSize)) {
412 uint64_t NewSize;
413 // The minimum increment is a page, but allocate more to amortize the cost.
414 constexpr uint64_t Increment = 1 * 1024 * 1024; // 1 MB
415 if (Error E = preallocateFileTail(*FD, DiskSize, DiskSize + Increment)
416 .moveInto(NewSize))
417 return std::move(E);
418 assert(NewSize >= DiskSize + Increment);
419 // FIXME: on Darwin this can under-count the size if there is a race to
420 // preallocate disk, because the semantics of F_PREALLOCATE are to add bytes
421 // to the end of the file, not to allocate up to a fixed size.
422 // Any discrepancy will be resolved the next time the file is truncated and
423 // then reopend.
424 while (DiskSize < NewSize)
425 H->AllocatedSize.compare_exchange_strong(DiskSize, NewSize);
426 }
427
428 if (Logger)
429 Logger->logMappedFileRegionArenaAllocate(data(), OldEnd, AllocSize);
430
431 return OldEnd;
432}
433
434ErrorOr<FileSizeInfo> FileSizeInfo::get(sys::fs::file_t File) {
435#if LLVM_ON_UNIX && defined(MAPPED_FILE_BSIZE)
436 struct stat Status;
437 int StatRet = sys::RetryAfterSignal(-1, ::fstat, File.get(), &Status);
438 if (StatRet)
439 return errnoAsErrorCode();
440 uint64_t AllocatedSize = uint64_t(Status.st_blocks) * MAPPED_FILE_BSIZE;
441 return FileSizeInfo{uint64_t(Status.st_size), AllocatedSize};
442#else
443 // Fallback: assume the file is fully allocated. Note: this may result in
444 // data loss on out-of-space.
445 ErrorOr<uint64_t> FileSize = sys::fs::file_size(File);
446 if (!FileSize)
447 return FileSize.getError();
448 return FileSizeInfo{*FileSize, *FileSize};
449#endif
450}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:348
if(!TBB||Cond.size()< 1) return false
#define H(x, y, z)
Definition MD5.cpp:56
static Error createAllocatorOutOfSpaceError()
This file declares interface for MappedFileRegionArena, a bump pointer allocator, backed by a memory-...
This file declares interface for OnDiskCASLogger, an interface that can be used to log CAS events to ...
This file contains some functions that are useful when dealing with strings.
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Logging utility - given an ordered specification of features, and assuming a scalar reward,...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI Expected< MappedFileRegionArena > create(const Twine &Path, uint64_t Capacity, uint64_t HeaderOffset, std::shared_ptr< ondisk::OnDiskCASLogger > Logger, function_ref< Error(MappedFileRegionArena &)> NewFileConstructor)
Create a MappedFileRegionArena.
LLVM_ABI Expected< int64_t > allocateOffset(uint64_t AllocSize)
Allocate, returning the offset from data() instead of a pointer.
static constexpr Align getAlign()
Minimum alignment for allocations, currently hardcoded to 8B.
An efficient, type-erasing, non-owning reference to a callable.
This class represents a memory mapped file.
@ readwrite
May access map via data and modify it. Written to path.
#define INT64_MAX
Definition DataTypes.h:71
LLVM_ABI_FOR_TEST std::error_code lockFileThreadSafe(int FD, llvm::sys::fs::LockKind Kind)
Thread-safe alternative to sys::fs::lockFile.
LLVM_ABI_FOR_TEST std::error_code unlockFileThreadSafe(int FD)
Thread-safe alternative to sys::fs::unlockFile.
std::error_code tryLockFileThreadSafe(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), llvm::sys::fs::LockKind Kind=llvm::sys::fs::LockKind::Exclusive)
Thread-safe alternative to sys::fs::tryLockFile.
Expected< size_t > preallocateFileTail(int FD, size_t CurrentSize, size_t NewSize)
Allocate space for the file FD on disk, if the filesystem supports it.
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
Definition FileSystem.h:780
LLVM_ABI Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
LLVM_ABI std::error_code resize_file_sparse(int FD, uint64_t Size)
Resize path to size with sparse files explicitly enabled.
LockKind
An enumeration for the lock kind.
LLVM_ABI std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
LLVM_ABI file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
Definition FileSystem.h:696
decltype(auto) RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As)
Definition Errno.h:33
This is an optimization pass for GlobalISel generic memory operations.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
std::error_code make_error_code(BitcodeError E)
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
std::string utostr(uint64_t X, bool isNeg=false)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition Error.h:1256
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
static constexpr Align Of()
Allow constructions of constexpr Align from types.
Definition Alignment.h:99
Header for MappedFileRegionArena.
This class wraps the platform specific file handle/descriptor type to provide an unified representati...
Definition File.h:21