LLVM 24.0.0git
OnDiskCommon.cpp
Go to the documentation of this file.
1//===- OnDiskCommon.cpp ---------------------------------------------------===//
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
9#include "OnDiskCommon.h"
10#include "llvm/Support/Errno.h"
11#include "llvm/Support/Error.h"
13#include "llvm/Support/Path.h"
15#include <chrono>
16#include <mutex>
17#include <thread>
18
19#if __has_include(<sys/file.h>)
20#include <sys/file.h>
21#ifdef LOCK_SH
22#define HAVE_FLOCK 1
23#else
24#define HAVE_FLOCK 0
25#endif
26#endif
27
28#if __has_include(<fcntl.h>)
29#include <fcntl.h>
30#endif
31
32#if __has_include(<sys/mount.h>)
33#include <sys/mount.h> // statfs
34#endif
35
36#ifdef __APPLE__
37#if __has_include(<sys/sysctl.h>)
38#include <sys/sysctl.h>
39#endif
40#endif
41
42#ifdef _WIN32
44#endif
45
46using namespace llvm;
47
49
51 static std::once_flag Flag;
52 Error Err = Error::success();
53 std::call_once(Flag, [&Err] {
54 ErrorAsOutParameter EAO(&Err);
55 constexpr const char *EnvVar = "LLVM_CAS_MAX_MAPPING_SIZE";
56 auto Value = sys::Process::GetEnv(EnvVar);
57 if (!Value)
58 return;
59
60 uint64_t Size;
61 if (StringRef(*Value).getAsInteger(/*auto*/ 0, Size))
63 "invalid value for %s: expected integer", EnvVar);
65 });
66
67 if (Err)
68 return std::move(Err);
69
71 return std::nullopt;
72
74}
75
79
80std::error_code cas::ondisk::lockFileThreadSafe(int FD,
81 sys::fs::LockKind Kind) {
82#if HAVE_FLOCK
84 -1, flock, FD,
85 Kind == sys::fs::LockKind::Exclusive ? LOCK_EX : LOCK_SH) == 0)
86 return std::error_code();
87 return std::error_code(errno, std::generic_category());
88#elif defined(_WIN32)
89 // On Windows this implementation is thread-safe.
90 return sys::fs::lockFile(FD, Kind);
91#else
92 return make_error_code(std::errc::no_lock_available);
93#endif
94}
95
96std::error_code cas::ondisk::unlockFileThreadSafe(int FD) {
97#if HAVE_FLOCK
98 if (sys::RetryAfterSignal(-1, flock, FD, LOCK_UN) == 0)
99 return std::error_code();
100 return std::error_code(errno, std::generic_category());
101#elif defined(_WIN32)
102 // On Windows this implementation is thread-safe.
103 return sys::fs::unlockFile(FD);
104#else
105 return make_error_code(std::errc::no_lock_available);
106#endif
107}
108
109std::error_code
110cas::ondisk::tryLockFileThreadSafe(int FD, std::chrono::milliseconds Timeout,
111 sys::fs::LockKind Kind) {
112#if HAVE_FLOCK
113 auto Start = std::chrono::steady_clock::now();
114 auto End = Start + Timeout;
115 do {
117 -1, flock, FD,
118 (Kind == sys::fs::LockKind::Exclusive ? LOCK_EX : LOCK_SH) |
119 LOCK_NB) == 0)
120 return std::error_code();
121 int Error = errno;
122 if (Error == EWOULDBLOCK) {
123 if (Timeout.count() == 0)
124 break;
125 // Match sys::fs::tryLockFile, which sleeps for 1 ms per attempt.
126 std::this_thread::sleep_for(std::chrono::milliseconds(1));
127 continue;
128 }
129 return std::error_code(Error, std::generic_category());
130 } while (std::chrono::steady_clock::now() < End);
131 return make_error_code(std::errc::no_lock_available);
132#elif defined(_WIN32)
133 // On Windows this implementation is thread-safe.
134 return sys::fs::tryLockFile(FD, Timeout, Kind);
135#else
136 return make_error_code(std::errc::no_lock_available);
137#endif
138}
139
141 size_t NewSize) {
142 auto CreateError = [&](std::error_code EC) -> Expected<size_t> {
143 if (EC == std::errc::not_supported)
144 // Ignore ENOTSUP in case the filesystem cannot preallocate.
145 return NewSize;
146#if defined(HAVE_POSIX_FALLOCATE)
147 if (EC == std::errc::invalid_argument && CurrentSize < NewSize && // len > 0
148 NewSize < std::numeric_limits<off_t>::max()) // 0 <= offset, len < max
149 // Prior to 2024, POSIX required EINVAL for cases that should be ENOTSUP,
150 // so handle it the same as above if it is not one of the other ways to
151 // get EINVAL.
152 return NewSize;
153#endif
154 return createStringError(EC,
155 "failed to allocate to CAS file: " + EC.message());
156 };
157#if defined(HAVE_POSIX_FALLOCATE)
158 // Note: posix_fallocate returns its error directly, not via errno.
159 int Err;
160 do {
161 Err = posix_fallocate(FD, CurrentSize, NewSize - CurrentSize);
162 } while (Err == EINTR);
163 if (Err)
164 return CreateError(std::error_code(Err, std::generic_category()));
165 return NewSize;
166#elif defined(__APPLE__)
167 fstore_t FAlloc;
168 FAlloc.fst_flags = F_ALLOCATEALL;
169#if defined(F_ALLOCATEPERSIST) && \
170 defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
171 __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 130000
172 // F_ALLOCATEPERSIST is introduced in macOS 13.
173 FAlloc.fst_flags |= F_ALLOCATEPERSIST;
174#endif
175 FAlloc.fst_posmode = F_PEOFPOSMODE;
176 FAlloc.fst_offset = 0;
177 FAlloc.fst_length = NewSize - CurrentSize;
178 FAlloc.fst_bytesalloc = 0;
179 if (sys::RetryAfterSignal(-1, ::fcntl, FD, F_PREALLOCATE, &FAlloc) == -1)
180 return CreateError(errnoAsErrorCode());
181 assert(CurrentSize + FAlloc.fst_bytesalloc >= NewSize);
182 return CurrentSize + FAlloc.fst_bytesalloc;
183#else
184 (void)CreateError; // Silence unused variable.
185 return NewSize; // Pretend it worked.
186#endif
187}
188
190 // Add exceptions to use small database file here.
191#if defined(__APPLE__) && __has_include(<sys/mount.h>)
192 // macOS tmpfs does not support sparse tails.
193 SmallString<128> PathStorage;
194 StringRef Path = P.toNullTerminatedStringRef(PathStorage);
195 struct statfs StatFS;
196 if (statfs(Path.data(), &StatFS) != 0)
197 return false;
198
199 if (strcmp(StatFS.f_fstypename, "tmpfs") == 0)
200 return true;
201#endif
202 // Default to use regular database file.
203 return false;
204}
205
207#ifdef __APPLE__
208#if __has_include(<sys/sysctl.h>) && defined(KERN_BOOTTIME)
209 struct timeval TV;
210 size_t TVLen = sizeof(TV);
211 int KernBoot[2] = {CTL_KERN, KERN_BOOTTIME};
212 if (sysctl(KernBoot, 2, &TV, &TVLen, nullptr, 0) < 0)
214 "failed to get boottime");
215 if (TVLen != sizeof(TV))
216 return createStringError("sysctl kern.boottime unexpected format");
217 return TV.tv_sec;
218#else
219 return 0;
220#endif
221#elif defined(__linux__)
222 // Use the mtime for /proc, which is recreated during system boot.
223 // We could also read /proc/stat and search for 'btime'.
225 if (std::error_code EC = sys::fs::status("/proc", Status))
226 return createFileError("/proc", EC);
227 return Status.getLastModificationTime().time_since_epoch().count();
228#elif defined(_WIN32)
229 // Compute it from the current time and the time since boot, which includes
230 // time spent asleep.
231 auto Uptime = std::chrono::milliseconds(GetTickCount64());
232 auto Boot = std::chrono::system_clock::now() - Uptime;
233 return std::chrono::duration_cast<std::chrono::seconds>(
234 Boot.time_since_epoch())
235 .count();
236#else
237 return 0;
238#endif
239}
240
243 StringRef CopyFromPath) {
244 // \c clonefile requires that the destination path doesn't exist. We create
245 // a "placeholder" temporary file, then modify its path a bit and use that
246 // for \c clonefile to write to.
247 // FIXME: Instead of creating a dummy file, add a new file system API for
248 // copying to a unique path that can loop while checking EEXIST.
249 SmallString<256> UniqueTmpPath;
250 SmallString<256> Model;
251 Model += ParentPath;
252 sys::path::append(Model, "%%%%%%%.tmp");
253 if (std::error_code EC = sys::fs::createUniqueFile(Model, UniqueTmpPath))
254 return createFileError(Model, EC);
255 TmpPath = std::move(UniqueTmpPath);
256 TmpPath += ".tmp"; // modify so that there's no file at that path.
257 // \c copy_file will use \c clonefile when applicable.
258 if (std::error_code EC = sys::fs::copy_file(CopyFromPath, TmpPath))
259 return createFileError(TmpPath, EC);
260
261 return TmpPath;
262}
263
265 if (std::error_code EC = sys::fs::rename(TmpPath, RenameToPath))
266 return createFileError(RenameToPath, EC);
267 TmpPath.clear();
268 return Error::success();
269}
270
272 if (!TmpPath.empty())
273 sys::fs::remove(TmpPath);
274 if (!UniqueTmpPath.empty())
275 sys::fs::remove(UniqueTmpPath);
276}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static uint64_t OnDiskCASMaxMappingSize
#define P(N)
Provides a library for accessing information about this process and other processes on the operating ...
Helper for Errors used as out-parameters.
Definition Error.h:1160
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
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
Error renameTo(StringRef RenameToPath)
Rename the new unique file to RenameToPath.
Expected< StringRef > createAndCopyFrom(StringRef ParentPath, StringRef CopyFromPath)
Create a new unique file path under ParentPath and copy the contents of CopyFromPath into it.
static LLVM_ABI std::optional< std::string > GetEnv(StringRef name)
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:214
LLVM_ABI_FOR_TEST void setMaxMappingSize(uint64_t Size)
Set MaxMappingSize for ondisk CAS.
Expected< std::optional< uint64_t > > getOverriddenMaxMappingSize()
Retrieves an overridden maximum mapping size for CAS files, if any, speicified by LLVM_CAS_MAX_MAPPIN...
std::error_code lockFileThreadSafe(int FD, llvm::sys::fs::LockKind Kind)
Thread-safe alternative to sys::fs::lockFile.
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.
LLVM_ABI_FOR_TEST Expected< uint64_t > getBootTime()
Get boot time for the OS.
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.
bool useSmallMappingSize(const Twine &Path)
Whether to use a small file mapping for ondisk databases created in Path.
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_ABI std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None, unsigned Mode=all_read|all_write)
Create a uniquely named file.
Definition Path.cpp:891
LLVM_ABI std::error_code lockFile(int FD, LockKind Kind=LockKind::Exclusive)
Lock the file.
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1042
LLVM_ABI std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), LockKind Kind=LockKind::Exclusive)
Try to locks the file during the specified time.
LockKind
An enumeration for the lock kind.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code unlockFile(int FD)
Unlock the file.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
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)
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
@ Timeout
Reached timeout while waiting for the owner to release the lock.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition Error.h:1256