25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

893 satır
26 KiB

Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 yıl önce
leveldb: Fix PosixWritableFile::Sync() on Apple systems. Apple doesn't follow POSIX specifications for fsync(). Instead, fsync() guarantees to flush the buffer cache to the device, which means the data will survive kernel panics, but may not survive power outages. Applications that need stronger guarantees (like databases) need to use fcntl(F_FULLFSYNC). This CL switches PosixWritableFile::Sync() to get the stronger guarantees on Apple systems. The improved implementation follows the same principles as SQLite [1] and node.js [2]. Research for the fcntl() to fsync() fallback strategy: Apple's released source code at https://opensource.apple.com/ shows at least three different error codes being returned when a filesystem does not support F_FULLFSYNC. fcntl() is implemented in xnu-4903.221.2 in bsd/kern/kern_descrip.c, where it delegates to fcntl_nocancel(). The documentation for fcntl_nocancel() mentions error codes for some operations, but does not include F_FULLFSYNC. The F_FULLSYNC branch in fcntl_nocancel() calls VNOP_IOCTL(_, F_FULLSYNC, NULL, 0, _), whose return value sets the error code. VNOP_IOCTL() is implemented in bsd/vfs/kpi_vfs.c and calls the ioctl function in the vnode's operation vector. The per-filesystem function names follow the pattern _vnop_ioctl() for all the instances in opensource code: {hfs,msdosfs,nfs,ntfs,smbfs,webdav,zfs}_vnop_ioctl(). hfs-407.30.1, msdosfs-229.200.3, and nfs in xnu-4903.221.2 handle F_FULLFSYNC. ntfs-94.200.1 and smb-759.40.1 do not handle F_FULLFSYNC, and the default branch returns ENOSUP. webdav-380.200.1 also does not handle F_FULLFSYNC, but the default branch returns EINVAL. zfs-59 also does not handle F_FULLSYNC, and its default branch returns ENOTTY. From a different angle, Apple's ntfs-94.200.1 includes utility code that uses fcntl(F_FULLFSYNC) and falls back to fsync() just like we do, supporting the hypothesis that there is no good way to detect lack of F_FULLFSYNC support. Also, Apple's fcntl() man page [3] does not mention a way to detect lack of F_FULLFSYNC support. [1] https://www.sqlite.org/src/doc/trunk/src/os_unix.c [2] https://github.com/libuv/libuv/blob/master/src/unix/fs.c [3] https://developer.apple.com/library/archive/documentatiVon/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html Tested: https://travis-ci.org/pwnall/leveldb/builds/477318498 TAP global presubmit ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=228593729
6 yıl önce
leveldb: Fix PosixWritableFile::Sync() on Apple systems. Apple doesn't follow POSIX specifications for fsync(). Instead, fsync() guarantees to flush the buffer cache to the device, which means the data will survive kernel panics, but may not survive power outages. Applications that need stronger guarantees (like databases) need to use fcntl(F_FULLFSYNC). This CL switches PosixWritableFile::Sync() to get the stronger guarantees on Apple systems. The improved implementation follows the same principles as SQLite [1] and node.js [2]. Research for the fcntl() to fsync() fallback strategy: Apple's released source code at https://opensource.apple.com/ shows at least three different error codes being returned when a filesystem does not support F_FULLFSYNC. fcntl() is implemented in xnu-4903.221.2 in bsd/kern/kern_descrip.c, where it delegates to fcntl_nocancel(). The documentation for fcntl_nocancel() mentions error codes for some operations, but does not include F_FULLFSYNC. The F_FULLSYNC branch in fcntl_nocancel() calls VNOP_IOCTL(_, F_FULLSYNC, NULL, 0, _), whose return value sets the error code. VNOP_IOCTL() is implemented in bsd/vfs/kpi_vfs.c and calls the ioctl function in the vnode's operation vector. The per-filesystem function names follow the pattern _vnop_ioctl() for all the instances in opensource code: {hfs,msdosfs,nfs,ntfs,smbfs,webdav,zfs}_vnop_ioctl(). hfs-407.30.1, msdosfs-229.200.3, and nfs in xnu-4903.221.2 handle F_FULLFSYNC. ntfs-94.200.1 and smb-759.40.1 do not handle F_FULLFSYNC, and the default branch returns ENOSUP. webdav-380.200.1 also does not handle F_FULLFSYNC, but the default branch returns EINVAL. zfs-59 also does not handle F_FULLSYNC, and its default branch returns ENOTTY. From a different angle, Apple's ntfs-94.200.1 includes utility code that uses fcntl(F_FULLFSYNC) and falls back to fsync() just like we do, supporting the hypothesis that there is no good way to detect lack of F_FULLFSYNC support. Also, Apple's fcntl() man page [3] does not mention a way to detect lack of F_FULLFSYNC support. [1] https://www.sqlite.org/src/doc/trunk/src/os_unix.c [2] https://github.com/libuv/libuv/blob/master/src/unix/fs.c [3] https://developer.apple.com/library/archive/documentatiVon/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html Tested: https://travis-ci.org/pwnall/leveldb/builds/477318498 TAP global presubmit ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=228593729
6 yıl önce
leveldb: Fix PosixWritableFile::Sync() on Apple systems. Apple doesn't follow POSIX specifications for fsync(). Instead, fsync() guarantees to flush the buffer cache to the device, which means the data will survive kernel panics, but may not survive power outages. Applications that need stronger guarantees (like databases) need to use fcntl(F_FULLFSYNC). This CL switches PosixWritableFile::Sync() to get the stronger guarantees on Apple systems. The improved implementation follows the same principles as SQLite [1] and node.js [2]. Research for the fcntl() to fsync() fallback strategy: Apple's released source code at https://opensource.apple.com/ shows at least three different error codes being returned when a filesystem does not support F_FULLFSYNC. fcntl() is implemented in xnu-4903.221.2 in bsd/kern/kern_descrip.c, where it delegates to fcntl_nocancel(). The documentation for fcntl_nocancel() mentions error codes for some operations, but does not include F_FULLFSYNC. The F_FULLSYNC branch in fcntl_nocancel() calls VNOP_IOCTL(_, F_FULLSYNC, NULL, 0, _), whose return value sets the error code. VNOP_IOCTL() is implemented in bsd/vfs/kpi_vfs.c and calls the ioctl function in the vnode's operation vector. The per-filesystem function names follow the pattern _vnop_ioctl() for all the instances in opensource code: {hfs,msdosfs,nfs,ntfs,smbfs,webdav,zfs}_vnop_ioctl(). hfs-407.30.1, msdosfs-229.200.3, and nfs in xnu-4903.221.2 handle F_FULLFSYNC. ntfs-94.200.1 and smb-759.40.1 do not handle F_FULLFSYNC, and the default branch returns ENOSUP. webdav-380.200.1 also does not handle F_FULLFSYNC, but the default branch returns EINVAL. zfs-59 also does not handle F_FULLSYNC, and its default branch returns ENOTTY. From a different angle, Apple's ntfs-94.200.1 includes utility code that uses fcntl(F_FULLFSYNC) and falls back to fsync() just like we do, supporting the hypothesis that there is no good way to detect lack of F_FULLFSYNC support. Also, Apple's fcntl() man page [3] does not mention a way to detect lack of F_FULLFSYNC support. [1] https://www.sqlite.org/src/doc/trunk/src/os_unix.c [2] https://github.com/libuv/libuv/blob/master/src/unix/fs.c [3] https://developer.apple.com/library/archive/documentatiVon/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html Tested: https://travis-ci.org/pwnall/leveldb/builds/477318498 TAP global presubmit ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=228593729
6 yıl önce
leveldb: Fix PosixWritableFile::Sync() on Apple systems. Apple doesn't follow POSIX specifications for fsync(). Instead, fsync() guarantees to flush the buffer cache to the device, which means the data will survive kernel panics, but may not survive power outages. Applications that need stronger guarantees (like databases) need to use fcntl(F_FULLFSYNC). This CL switches PosixWritableFile::Sync() to get the stronger guarantees on Apple systems. The improved implementation follows the same principles as SQLite [1] and node.js [2]. Research for the fcntl() to fsync() fallback strategy: Apple's released source code at https://opensource.apple.com/ shows at least three different error codes being returned when a filesystem does not support F_FULLFSYNC. fcntl() is implemented in xnu-4903.221.2 in bsd/kern/kern_descrip.c, where it delegates to fcntl_nocancel(). The documentation for fcntl_nocancel() mentions error codes for some operations, but does not include F_FULLFSYNC. The F_FULLSYNC branch in fcntl_nocancel() calls VNOP_IOCTL(_, F_FULLSYNC, NULL, 0, _), whose return value sets the error code. VNOP_IOCTL() is implemented in bsd/vfs/kpi_vfs.c and calls the ioctl function in the vnode's operation vector. The per-filesystem function names follow the pattern _vnop_ioctl() for all the instances in opensource code: {hfs,msdosfs,nfs,ntfs,smbfs,webdav,zfs}_vnop_ioctl(). hfs-407.30.1, msdosfs-229.200.3, and nfs in xnu-4903.221.2 handle F_FULLFSYNC. ntfs-94.200.1 and smb-759.40.1 do not handle F_FULLFSYNC, and the default branch returns ENOSUP. webdav-380.200.1 also does not handle F_FULLFSYNC, but the default branch returns EINVAL. zfs-59 also does not handle F_FULLSYNC, and its default branch returns ENOTTY. From a different angle, Apple's ntfs-94.200.1 includes utility code that uses fcntl(F_FULLFSYNC) and falls back to fsync() just like we do, supporting the hypothesis that there is no good way to detect lack of F_FULLFSYNC support. Also, Apple's fcntl() man page [3] does not mention a way to detect lack of F_FULLFSYNC support. [1] https://www.sqlite.org/src/doc/trunk/src/os_unix.c [2] https://github.com/libuv/libuv/blob/master/src/unix/fs.c [3] https://developer.apple.com/library/archive/documentatiVon/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html Tested: https://travis-ci.org/pwnall/leveldb/builds/477318498 TAP global presubmit ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=228593729
6 yıl önce
leveldb: Fix PosixWritableFile::Sync() on Apple systems. Apple doesn't follow POSIX specifications for fsync(). Instead, fsync() guarantees to flush the buffer cache to the device, which means the data will survive kernel panics, but may not survive power outages. Applications that need stronger guarantees (like databases) need to use fcntl(F_FULLFSYNC). This CL switches PosixWritableFile::Sync() to get the stronger guarantees on Apple systems. The improved implementation follows the same principles as SQLite [1] and node.js [2]. Research for the fcntl() to fsync() fallback strategy: Apple's released source code at https://opensource.apple.com/ shows at least three different error codes being returned when a filesystem does not support F_FULLFSYNC. fcntl() is implemented in xnu-4903.221.2 in bsd/kern/kern_descrip.c, where it delegates to fcntl_nocancel(). The documentation for fcntl_nocancel() mentions error codes for some operations, but does not include F_FULLFSYNC. The F_FULLSYNC branch in fcntl_nocancel() calls VNOP_IOCTL(_, F_FULLSYNC, NULL, 0, _), whose return value sets the error code. VNOP_IOCTL() is implemented in bsd/vfs/kpi_vfs.c and calls the ioctl function in the vnode's operation vector. The per-filesystem function names follow the pattern _vnop_ioctl() for all the instances in opensource code: {hfs,msdosfs,nfs,ntfs,smbfs,webdav,zfs}_vnop_ioctl(). hfs-407.30.1, msdosfs-229.200.3, and nfs in xnu-4903.221.2 handle F_FULLFSYNC. ntfs-94.200.1 and smb-759.40.1 do not handle F_FULLFSYNC, and the default branch returns ENOSUP. webdav-380.200.1 also does not handle F_FULLFSYNC, but the default branch returns EINVAL. zfs-59 also does not handle F_FULLSYNC, and its default branch returns ENOTTY. From a different angle, Apple's ntfs-94.200.1 includes utility code that uses fcntl(F_FULLFSYNC) and falls back to fsync() just like we do, supporting the hypothesis that there is no good way to detect lack of F_FULLFSYNC support. Also, Apple's fcntl() man page [3] does not mention a way to detect lack of F_FULLFSYNC support. [1] https://www.sqlite.org/src/doc/trunk/src/os_unix.c [2] https://github.com/libuv/libuv/blob/master/src/unix/fs.c [3] https://developer.apple.com/library/archive/documentatiVon/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html Tested: https://travis-ci.org/pwnall/leveldb/builds/477318498 TAP global presubmit ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=228593729
6 yıl önce
leveldb: Fix PosixWritableFile::Sync() on Apple systems. Apple doesn't follow POSIX specifications for fsync(). Instead, fsync() guarantees to flush the buffer cache to the device, which means the data will survive kernel panics, but may not survive power outages. Applications that need stronger guarantees (like databases) need to use fcntl(F_FULLFSYNC). This CL switches PosixWritableFile::Sync() to get the stronger guarantees on Apple systems. The improved implementation follows the same principles as SQLite [1] and node.js [2]. Research for the fcntl() to fsync() fallback strategy: Apple's released source code at https://opensource.apple.com/ shows at least three different error codes being returned when a filesystem does not support F_FULLFSYNC. fcntl() is implemented in xnu-4903.221.2 in bsd/kern/kern_descrip.c, where it delegates to fcntl_nocancel(). The documentation for fcntl_nocancel() mentions error codes for some operations, but does not include F_FULLFSYNC. The F_FULLSYNC branch in fcntl_nocancel() calls VNOP_IOCTL(_, F_FULLSYNC, NULL, 0, _), whose return value sets the error code. VNOP_IOCTL() is implemented in bsd/vfs/kpi_vfs.c and calls the ioctl function in the vnode's operation vector. The per-filesystem function names follow the pattern _vnop_ioctl() for all the instances in opensource code: {hfs,msdosfs,nfs,ntfs,smbfs,webdav,zfs}_vnop_ioctl(). hfs-407.30.1, msdosfs-229.200.3, and nfs in xnu-4903.221.2 handle F_FULLFSYNC. ntfs-94.200.1 and smb-759.40.1 do not handle F_FULLFSYNC, and the default branch returns ENOSUP. webdav-380.200.1 also does not handle F_FULLFSYNC, but the default branch returns EINVAL. zfs-59 also does not handle F_FULLSYNC, and its default branch returns ENOTTY. From a different angle, Apple's ntfs-94.200.1 includes utility code that uses fcntl(F_FULLFSYNC) and falls back to fsync() just like we do, supporting the hypothesis that there is no good way to detect lack of F_FULLFSYNC support. Also, Apple's fcntl() man page [3] does not mention a way to detect lack of F_FULLFSYNC support. [1] https://www.sqlite.org/src/doc/trunk/src/os_unix.c [2] https://github.com/libuv/libuv/blob/master/src/unix/fs.c [3] https://developer.apple.com/library/archive/documentatiVon/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html Tested: https://travis-ci.org/pwnall/leveldb/builds/477318498 TAP global presubmit ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=228593729
6 yıl önce
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include <dirent.h>
  5. #include <fcntl.h>
  6. #include <pthread.h>
  7. #include <sys/mman.h>
  8. #include <sys/resource.h>
  9. #include <sys/stat.h>
  10. #include <sys/time.h>
  11. #include <sys/types.h>
  12. #include <unistd.h>
  13. #include <atomic>
  14. #include <cerrno>
  15. #include <cstddef>
  16. #include <cstdint>
  17. #include <cstdio>
  18. #include <cstdlib>
  19. #include <cstring>
  20. #include <limits>
  21. #include <queue>
  22. #include <set>
  23. #include <string>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <utility>
  27. #include "leveldb/env.h"
  28. #include "leveldb/slice.h"
  29. #include "leveldb/status.h"
  30. #include "port/port.h"
  31. #include "port/thread_annotations.h"
  32. #include "util/env_posix_test_helper.h"
  33. #include "util/posix_logger.h"
  34. namespace leveldb {
  35. namespace {
  36. // Set by EnvPosixTestHelper::SetReadOnlyMMapLimit() and MaxOpenFiles().
  37. int g_open_read_only_file_limit = -1;
  38. // Up to 1000 mmap regions for 64-bit binaries; none for 32-bit.
  39. constexpr const int kDefaultMmapLimit = (sizeof(void*) >= 8) ? 1000 : 0;
  40. // Can be set using EnvPosixTestHelper::SetReadOnlyMMapLimit.
  41. int g_mmap_limit = kDefaultMmapLimit;
  42. // Common flags defined for all posix open operations
  43. #if defined(HAVE_O_CLOEXEC)
  44. constexpr const int kOpenBaseFlags = O_CLOEXEC;
  45. #else
  46. constexpr const int kOpenBaseFlags = 0;
  47. #endif // defined(HAVE_O_CLOEXEC)
  48. constexpr const size_t kWritableFileBufferSize = 65536;
  49. Status PosixError(const std::string& context, int error_number) {
  50. if (error_number == ENOENT) {
  51. return Status::NotFound(context, std::strerror(error_number));
  52. } else {
  53. return Status::IOError(context, std::strerror(error_number));
  54. }
  55. }
  56. // Helper class to limit resource usage to avoid exhaustion.
  57. // Currently used to limit read-only file descriptors and mmap file usage
  58. // so that we do not run out of file descriptors or virtual memory, or run into
  59. // kernel performance problems for very large databases.
  60. class Limiter {
  61. public:
  62. // Limit maximum number of resources to |max_acquires|.
  63. Limiter(int max_acquires) : acquires_allowed_(max_acquires) {}
  64. Limiter(const Limiter&) = delete;
  65. Limiter operator=(const Limiter&) = delete;
  66. // If another resource is available, acquire it and return true.
  67. // Else return false.
  68. bool Acquire() {
  69. int old_acquires_allowed =
  70. acquires_allowed_.fetch_sub(1, std::memory_order_relaxed);
  71. if (old_acquires_allowed > 0) return true;
  72. acquires_allowed_.fetch_add(1, std::memory_order_relaxed);
  73. return false;
  74. }
  75. // Release a resource acquired by a previous call to Acquire() that returned
  76. // true.
  77. void Release() { acquires_allowed_.fetch_add(1, std::memory_order_relaxed); }
  78. private:
  79. // The number of available resources.
  80. //
  81. // This is a counter and is not tied to the invariants of any other class, so
  82. // it can be operated on safely using std::memory_order_relaxed.
  83. std::atomic<int> acquires_allowed_;
  84. };
  85. // Implements sequential read access in a file using read().
  86. //
  87. // Instances of this class are thread-friendly but not thread-safe, as required
  88. // by the SequentialFile API.
  89. class PosixSequentialFile final : public SequentialFile {
  90. public:
  91. PosixSequentialFile(std::string filename, int fd)
  92. : fd_(fd), filename_(filename) {}
  93. ~PosixSequentialFile() override { close(fd_); }
  94. Status Read(size_t n, Slice* result, char* scratch) override {
  95. Status status;
  96. while (true) {
  97. ::ssize_t read_size = ::read(fd_, scratch, n);
  98. if (read_size < 0) { // Read error.
  99. if (errno == EINTR) {
  100. continue; // Retry
  101. }
  102. status = PosixError(filename_, errno);
  103. break;
  104. }
  105. *result = Slice(scratch, read_size);
  106. break;
  107. }
  108. return status;
  109. }
  110. Status Skip(uint64_t n) override {
  111. if (::lseek(fd_, n, SEEK_CUR) == static_cast<off_t>(-1)) {
  112. return PosixError(filename_, errno);
  113. }
  114. return Status::OK();
  115. }
  116. private:
  117. const int fd_;
  118. const std::string filename_;
  119. };
  120. // Implements random read access in a file using pread().
  121. //
  122. // Instances of this class are thread-safe, as required by the RandomAccessFile
  123. // API. Instances are immutable and Read() only calls thread-safe library
  124. // functions.
  125. class PosixRandomAccessFile final : public RandomAccessFile {
  126. public:
  127. // The new instance takes ownership of |fd|. |fd_limiter| must outlive this
  128. // instance, and will be used to determine if .
  129. PosixRandomAccessFile(std::string filename, int fd, Limiter* fd_limiter)
  130. : has_permanent_fd_(fd_limiter->Acquire()),
  131. fd_(has_permanent_fd_ ? fd : -1),
  132. fd_limiter_(fd_limiter),
  133. filename_(std::move(filename)) {
  134. if (!has_permanent_fd_) {
  135. assert(fd_ == -1);
  136. ::close(fd); // The file will be opened on every read.
  137. }
  138. }
  139. ~PosixRandomAccessFile() override {
  140. if (has_permanent_fd_) {
  141. assert(fd_ != -1);
  142. ::close(fd_);
  143. fd_limiter_->Release();
  144. }
  145. }
  146. Status Read(uint64_t offset, size_t n, Slice* result,
  147. char* scratch) const override {
  148. int fd = fd_;
  149. if (!has_permanent_fd_) {
  150. fd = ::open(filename_.c_str(), O_RDONLY | kOpenBaseFlags);
  151. if (fd < 0) {
  152. return PosixError(filename_, errno);
  153. }
  154. }
  155. assert(fd != -1);
  156. Status status;
  157. ssize_t read_size = ::pread(fd, scratch, n, static_cast<off_t>(offset));
  158. *result = Slice(scratch, (read_size < 0) ? 0 : read_size);
  159. if (read_size < 0) {
  160. // An error: return a non-ok status.
  161. status = PosixError(filename_, errno);
  162. }
  163. if (!has_permanent_fd_) {
  164. // Close the temporary file descriptor opened earlier.
  165. assert(fd != fd_);
  166. ::close(fd);
  167. }
  168. return status;
  169. }
  170. private:
  171. const bool has_permanent_fd_; // If false, the file is opened on every read.
  172. const int fd_; // -1 if has_permanent_fd_ is false.
  173. Limiter* const fd_limiter_;
  174. const std::string filename_;
  175. };
  176. // Implements random read access in a file using mmap().
  177. //
  178. // Instances of this class are thread-safe, as required by the RandomAccessFile
  179. // API. Instances are immutable and Read() only calls thread-safe library
  180. // functions.
  181. class PosixMmapReadableFile final : public RandomAccessFile {
  182. public:
  183. // mmap_base[0, length-1] points to the memory-mapped contents of the file. It
  184. // must be the result of a successful call to mmap(). This instances takes
  185. // over the ownership of the region.
  186. //
  187. // |mmap_limiter| must outlive this instance. The caller must have already
  188. // aquired the right to use one mmap region, which will be released when this
  189. // instance is destroyed.
  190. PosixMmapReadableFile(std::string filename, char* mmap_base, size_t length,
  191. Limiter* mmap_limiter)
  192. : mmap_base_(mmap_base),
  193. length_(length),
  194. mmap_limiter_(mmap_limiter),
  195. filename_(std::move(filename)) {}
  196. ~PosixMmapReadableFile() override {
  197. ::munmap(static_cast<void*>(mmap_base_), length_);
  198. mmap_limiter_->Release();
  199. }
  200. Status Read(uint64_t offset, size_t n, Slice* result,
  201. char* scratch) const override {
  202. if (offset + n > length_) {
  203. *result = Slice();
  204. return PosixError(filename_, EINVAL);
  205. }
  206. *result = Slice(mmap_base_ + offset, n);
  207. return Status::OK();
  208. }
  209. private:
  210. char* const mmap_base_;
  211. const size_t length_;
  212. Limiter* const mmap_limiter_;
  213. const std::string filename_;
  214. };
  215. class PosixWritableFile final : public WritableFile {
  216. public:
  217. PosixWritableFile(std::string filename, int fd)
  218. : pos_(0),
  219. fd_(fd),
  220. is_manifest_(IsManifest(filename)),
  221. filename_(std::move(filename)),
  222. dirname_(Dirname(filename_)) {}
  223. ~PosixWritableFile() override {
  224. if (fd_ >= 0) {
  225. // Ignoring any potential errors
  226. Close();
  227. }
  228. }
  229. Status Append(const Slice& data) override {
  230. size_t write_size = data.size();
  231. const char* write_data = data.data();
  232. // Fit as much as possible into buffer.
  233. size_t copy_size = std::min(write_size, kWritableFileBufferSize - pos_);
  234. std::memcpy(buf_ + pos_, write_data, copy_size);
  235. write_data += copy_size;
  236. write_size -= copy_size;
  237. pos_ += copy_size;
  238. if (write_size == 0) {
  239. return Status::OK();
  240. }
  241. // Can't fit in buffer, so need to do at least one write.
  242. Status status = FlushBuffer();
  243. if (!status.ok()) {
  244. return status;
  245. }
  246. // Small writes go to buffer, large writes are written directly.
  247. if (write_size < kWritableFileBufferSize) {
  248. std::memcpy(buf_, write_data, write_size);
  249. pos_ = write_size;
  250. return Status::OK();
  251. }
  252. return WriteUnbuffered(write_data, write_size);
  253. }
  254. Status Close() override {
  255. Status status = FlushBuffer();
  256. const int close_result = ::close(fd_);
  257. if (close_result < 0 && status.ok()) {
  258. status = PosixError(filename_, errno);
  259. }
  260. fd_ = -1;
  261. return status;
  262. }
  263. Status Flush() override { return FlushBuffer(); }
  264. Status Sync() override {
  265. // Ensure new files referred to by the manifest are in the filesystem.
  266. //
  267. // This needs to happen before the manifest file is flushed to disk, to
  268. // avoid crashing in a state where the manifest refers to files that are not
  269. // yet on disk.
  270. Status status = SyncDirIfManifest();
  271. if (!status.ok()) {
  272. return status;
  273. }
  274. status = FlushBuffer();
  275. if (!status.ok()) {
  276. return status;
  277. }
  278. return SyncFd(fd_, filename_);
  279. }
  280. private:
  281. Status FlushBuffer() {
  282. Status status = WriteUnbuffered(buf_, pos_);
  283. pos_ = 0;
  284. return status;
  285. }
  286. Status WriteUnbuffered(const char* data, size_t size) {
  287. while (size > 0) {
  288. ssize_t write_result = ::write(fd_, data, size);
  289. if (write_result < 0) {
  290. if (errno == EINTR) {
  291. continue; // Retry
  292. }
  293. return PosixError(filename_, errno);
  294. }
  295. data += write_result;
  296. size -= write_result;
  297. }
  298. return Status::OK();
  299. }
  300. Status SyncDirIfManifest() {
  301. Status status;
  302. if (!is_manifest_) {
  303. return status;
  304. }
  305. int fd = ::open(dirname_.c_str(), O_RDONLY | kOpenBaseFlags);
  306. if (fd < 0) {
  307. status = PosixError(dirname_, errno);
  308. } else {
  309. status = SyncFd(fd, dirname_);
  310. ::close(fd);
  311. }
  312. return status;
  313. }
  314. // Ensures that all the caches associated with the given file descriptor's
  315. // data are flushed all the way to durable media, and can withstand power
  316. // failures.
  317. //
  318. // The path argument is only used to populate the description string in the
  319. // returned Status if an error occurs.
  320. static Status SyncFd(int fd, const std::string& fd_path) {
  321. #if HAVE_FULLFSYNC
  322. // On macOS and iOS, fsync() doesn't guarantee durability past power
  323. // failures. fcntl(F_FULLFSYNC) is required for that purpose. Some
  324. // filesystems don't support fcntl(F_FULLFSYNC), and require a fallback to
  325. // fsync().
  326. if (::fcntl(fd, F_FULLFSYNC) == 0) {
  327. return Status::OK();
  328. }
  329. #endif // HAVE_FULLFSYNC
  330. #if HAVE_FDATASYNC
  331. bool sync_success = ::fdatasync(fd) == 0;
  332. #else
  333. bool sync_success = ::fsync(fd) == 0;
  334. #endif // HAVE_FDATASYNC
  335. if (sync_success) {
  336. return Status::OK();
  337. }
  338. return PosixError(fd_path, errno);
  339. }
  340. // Returns the directory name in a path pointing to a file.
  341. //
  342. // Returns "." if the path does not contain any directory separator.
  343. static std::string Dirname(const std::string& filename) {
  344. std::string::size_type separator_pos = filename.rfind('/');
  345. if (separator_pos == std::string::npos) {
  346. return std::string(".");
  347. }
  348. // The filename component should not contain a path separator. If it does,
  349. // the splitting was done incorrectly.
  350. assert(filename.find('/', separator_pos + 1) == std::string::npos);
  351. return filename.substr(0, separator_pos);
  352. }
  353. // Extracts the file name from a path pointing to a file.
  354. //
  355. // The returned Slice points to |filename|'s data buffer, so it is only valid
  356. // while |filename| is alive and unchanged.
  357. static Slice Basename(const std::string& filename) {
  358. std::string::size_type separator_pos = filename.rfind('/');
  359. if (separator_pos == std::string::npos) {
  360. return Slice(filename);
  361. }
  362. // The filename component should not contain a path separator. If it does,
  363. // the splitting was done incorrectly.
  364. assert(filename.find('/', separator_pos + 1) == std::string::npos);
  365. return Slice(filename.data() + separator_pos + 1,
  366. filename.length() - separator_pos - 1);
  367. }
  368. // True if the given file is a manifest file.
  369. static bool IsManifest(const std::string& filename) {
  370. return Basename(filename).starts_with("MANIFEST");
  371. }
  372. // buf_[0, pos_ - 1] contains data to be written to fd_.
  373. char buf_[kWritableFileBufferSize];
  374. size_t pos_;
  375. int fd_;
  376. const bool is_manifest_; // True if the file's name starts with MANIFEST.
  377. const std::string filename_;
  378. const std::string dirname_; // The directory of filename_.
  379. };
  380. int LockOrUnlock(int fd, bool lock) {
  381. errno = 0;
  382. struct ::flock file_lock_info;
  383. std::memset(&file_lock_info, 0, sizeof(file_lock_info));
  384. file_lock_info.l_type = (lock ? F_WRLCK : F_UNLCK);
  385. file_lock_info.l_whence = SEEK_SET;
  386. file_lock_info.l_start = 0;
  387. file_lock_info.l_len = 0; // Lock/unlock entire file.
  388. return ::fcntl(fd, F_SETLK, &file_lock_info);
  389. }
  390. // Instances are thread-safe because they are immutable.
  391. class PosixFileLock : public FileLock {
  392. public:
  393. PosixFileLock(int fd, std::string filename)
  394. : fd_(fd), filename_(std::move(filename)) {}
  395. int fd() const { return fd_; }
  396. const std::string& filename() const { return filename_; }
  397. private:
  398. const int fd_;
  399. const std::string filename_;
  400. };
  401. // Tracks the files locked by PosixEnv::LockFile().
  402. //
  403. // We maintain a separate set instead of relying on fcntl(F_SETLK) because
  404. // fcntl(F_SETLK) does not provide any protection against multiple uses from the
  405. // same process.
  406. //
  407. // Instances are thread-safe because all member data is guarded by a mutex.
  408. class PosixLockTable {
  409. public:
  410. bool Insert(const std::string& fname) LOCKS_EXCLUDED(mu_) {
  411. mu_.Lock();
  412. bool succeeded = locked_files_.insert(fname).second;
  413. mu_.Unlock();
  414. return succeeded;
  415. }
  416. void Remove(const std::string& fname) LOCKS_EXCLUDED(mu_) {
  417. mu_.Lock();
  418. locked_files_.erase(fname);
  419. mu_.Unlock();
  420. }
  421. private:
  422. port::Mutex mu_;
  423. std::set<std::string> locked_files_ GUARDED_BY(mu_);
  424. };
  425. class PosixEnv : public Env {
  426. public:
  427. PosixEnv();
  428. ~PosixEnv() override {
  429. static char msg[] = "PosixEnv singleton destroyed. Unsupported behavior!\n";
  430. std::fwrite(msg, 1, sizeof(msg), stderr);
  431. std::abort();
  432. }
  433. Status NewSequentialFile(const std::string& filename,
  434. SequentialFile** result) override {
  435. int fd = ::open(filename.c_str(), O_RDONLY | kOpenBaseFlags);
  436. if (fd < 0) {
  437. *result = nullptr;
  438. return PosixError(filename, errno);
  439. }
  440. *result = new PosixSequentialFile(filename, fd);
  441. return Status::OK();
  442. }
  443. Status NewRandomAccessFile(const std::string& filename,
  444. RandomAccessFile** result) override {
  445. *result = nullptr;
  446. int fd = ::open(filename.c_str(), O_RDONLY | kOpenBaseFlags);
  447. if (fd < 0) {
  448. return PosixError(filename, errno);
  449. }
  450. if (!mmap_limiter_.Acquire()) {
  451. *result = new PosixRandomAccessFile(filename, fd, &fd_limiter_);
  452. return Status::OK();
  453. }
  454. uint64_t file_size;
  455. Status status = GetFileSize(filename, &file_size);
  456. if (status.ok()) {
  457. void* mmap_base =
  458. ::mmap(/*addr=*/nullptr, file_size, PROT_READ, MAP_SHARED, fd, 0);
  459. if (mmap_base != MAP_FAILED) {
  460. *result = new PosixMmapReadableFile(filename,
  461. reinterpret_cast<char*>(mmap_base),
  462. file_size, &mmap_limiter_);
  463. } else {
  464. status = PosixError(filename, errno);
  465. }
  466. }
  467. ::close(fd);
  468. if (!status.ok()) {
  469. mmap_limiter_.Release();
  470. }
  471. return status;
  472. }
  473. Status NewWritableFile(const std::string& filename,
  474. WritableFile** result) override {
  475. int fd = ::open(filename.c_str(),
  476. O_TRUNC | O_WRONLY | O_CREAT | kOpenBaseFlags, 0644);
  477. if (fd < 0) {
  478. *result = nullptr;
  479. return PosixError(filename, errno);
  480. }
  481. *result = new PosixWritableFile(filename, fd);
  482. return Status::OK();
  483. }
  484. Status NewAppendableFile(const std::string& filename,
  485. WritableFile** result) override {
  486. int fd = ::open(filename.c_str(),
  487. O_APPEND | O_WRONLY | O_CREAT | kOpenBaseFlags, 0644);
  488. if (fd < 0) {
  489. *result = nullptr;
  490. return PosixError(filename, errno);
  491. }
  492. *result = new PosixWritableFile(filename, fd);
  493. return Status::OK();
  494. }
  495. bool FileExists(const std::string& filename) override {
  496. return ::access(filename.c_str(), F_OK) == 0;
  497. }
  498. Status GetChildren(const std::string& directory_path,
  499. std::vector<std::string>* result) override {
  500. result->clear();
  501. ::DIR* dir = ::opendir(directory_path.c_str());
  502. if (dir == nullptr) {
  503. return PosixError(directory_path, errno);
  504. }
  505. struct ::dirent* entry;
  506. while ((entry = ::readdir(dir)) != nullptr) {
  507. result->emplace_back(entry->d_name);
  508. }
  509. ::closedir(dir);
  510. return Status::OK();
  511. }
  512. Status DeleteFile(const std::string& filename) override {
  513. if (::unlink(filename.c_str()) != 0) {
  514. return PosixError(filename, errno);
  515. }
  516. return Status::OK();
  517. }
  518. Status CreateDir(const std::string& dirname) override {
  519. if (::mkdir(dirname.c_str(), 0755) != 0) {
  520. return PosixError(dirname, errno);
  521. }
  522. return Status::OK();
  523. }
  524. Status DeleteDir(const std::string& dirname) override {
  525. if (::rmdir(dirname.c_str()) != 0) {
  526. return PosixError(dirname, errno);
  527. }
  528. return Status::OK();
  529. }
  530. Status GetFileSize(const std::string& filename, uint64_t* size) override {
  531. struct ::stat file_stat;
  532. if (::stat(filename.c_str(), &file_stat) != 0) {
  533. *size = 0;
  534. return PosixError(filename, errno);
  535. }
  536. *size = file_stat.st_size;
  537. return Status::OK();
  538. }
  539. Status RenameFile(const std::string& from, const std::string& to) override {
  540. if (std::rename(from.c_str(), to.c_str()) != 0) {
  541. return PosixError(from, errno);
  542. }
  543. return Status::OK();
  544. }
  545. Status LockFile(const std::string& filename, FileLock** lock) override {
  546. *lock = nullptr;
  547. int fd = ::open(filename.c_str(), O_RDWR | O_CREAT | kOpenBaseFlags, 0644);
  548. if (fd < 0) {
  549. return PosixError(filename, errno);
  550. }
  551. if (!locks_.Insert(filename)) {
  552. ::close(fd);
  553. return Status::IOError("lock " + filename, "already held by process");
  554. }
  555. if (LockOrUnlock(fd, true) == -1) {
  556. int lock_errno = errno;
  557. ::close(fd);
  558. locks_.Remove(filename);
  559. return PosixError("lock " + filename, lock_errno);
  560. }
  561. *lock = new PosixFileLock(fd, filename);
  562. return Status::OK();
  563. }
  564. Status UnlockFile(FileLock* lock) override {
  565. PosixFileLock* posix_file_lock = static_cast<PosixFileLock*>(lock);
  566. if (LockOrUnlock(posix_file_lock->fd(), false) == -1) {
  567. return PosixError("unlock " + posix_file_lock->filename(), errno);
  568. }
  569. locks_.Remove(posix_file_lock->filename());
  570. ::close(posix_file_lock->fd());
  571. delete posix_file_lock;
  572. return Status::OK();
  573. }
  574. void Schedule(void (*background_work_function)(void* background_work_arg),
  575. void* background_work_arg) override;
  576. void StartThread(void (*thread_main)(void* thread_main_arg),
  577. void* thread_main_arg) override;
  578. Status GetTestDirectory(std::string* result) override {
  579. const char* env = std::getenv("TEST_TMPDIR");
  580. if (env && env[0] != '\0') {
  581. *result = env;
  582. } else {
  583. char buf[100];
  584. std::snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d",
  585. static_cast<int>(::geteuid()));
  586. *result = buf;
  587. }
  588. // The CreateDir status is ignored because the directory may already exist.
  589. CreateDir(*result);
  590. return Status::OK();
  591. }
  592. Status NewLogger(const std::string& filename, Logger** result) override {
  593. int fd = ::open(filename.c_str(),
  594. O_APPEND | O_WRONLY | O_CREAT | kOpenBaseFlags, 0644);
  595. if (fd < 0) {
  596. *result = nullptr;
  597. return PosixError(filename, errno);
  598. }
  599. std::FILE* fp = ::fdopen(fd, "w");
  600. if (fp == nullptr) {
  601. ::close(fd);
  602. *result = nullptr;
  603. return PosixError(filename, errno);
  604. } else {
  605. *result = new PosixLogger(fp);
  606. return Status::OK();
  607. }
  608. }
  609. uint64_t NowMicros() override {
  610. static constexpr uint64_t kUsecondsPerSecond = 1000000;
  611. struct ::timeval tv;
  612. ::gettimeofday(&tv, nullptr);
  613. return static_cast<uint64_t>(tv.tv_sec) * kUsecondsPerSecond + tv.tv_usec;
  614. }
  615. void SleepForMicroseconds(int micros) override { ::usleep(micros); }
  616. private:
  617. void BackgroundThreadMain();
  618. static void BackgroundThreadEntryPoint(PosixEnv* env) {
  619. env->BackgroundThreadMain();
  620. }
  621. // Stores the work item data in a Schedule() call.
  622. //
  623. // Instances are constructed on the thread calling Schedule() and used on the
  624. // background thread.
  625. //
  626. // This structure is thread-safe beacuse it is immutable.
  627. struct BackgroundWorkItem {
  628. explicit BackgroundWorkItem(void (*function)(void* arg), void* arg)
  629. : function(function), arg(arg) {}
  630. void (*const function)(void*);
  631. void* const arg;
  632. };
  633. port::Mutex background_work_mutex_;
  634. port::CondVar background_work_cv_ GUARDED_BY(background_work_mutex_);
  635. bool started_background_thread_ GUARDED_BY(background_work_mutex_);
  636. std::queue<BackgroundWorkItem> background_work_queue_
  637. GUARDED_BY(background_work_mutex_);
  638. PosixLockTable locks_; // Thread-safe.
  639. Limiter mmap_limiter_; // Thread-safe.
  640. Limiter fd_limiter_; // Thread-safe.
  641. };
  642. // Return the maximum number of concurrent mmaps.
  643. int MaxMmaps() { return g_mmap_limit; }
  644. // Return the maximum number of read-only files to keep open.
  645. int MaxOpenFiles() {
  646. if (g_open_read_only_file_limit >= 0) {
  647. return g_open_read_only_file_limit;
  648. }
  649. struct ::rlimit rlim;
  650. if (::getrlimit(RLIMIT_NOFILE, &rlim)) {
  651. // getrlimit failed, fallback to hard-coded default.
  652. g_open_read_only_file_limit = 50;
  653. } else if (rlim.rlim_cur == RLIM_INFINITY) {
  654. g_open_read_only_file_limit = std::numeric_limits<int>::max();
  655. } else {
  656. // Allow use of 20% of available file descriptors for read-only files.
  657. g_open_read_only_file_limit = rlim.rlim_cur / 5;
  658. }
  659. return g_open_read_only_file_limit;
  660. }
  661. } // namespace
  662. PosixEnv::PosixEnv()
  663. : background_work_cv_(&background_work_mutex_),
  664. started_background_thread_(false),
  665. mmap_limiter_(MaxMmaps()),
  666. fd_limiter_(MaxOpenFiles()) {}
  667. void PosixEnv::Schedule(
  668. void (*background_work_function)(void* background_work_arg),
  669. void* background_work_arg) {
  670. background_work_mutex_.Lock();
  671. // Start the background thread, if we haven't done so already.
  672. if (!started_background_thread_) {
  673. started_background_thread_ = true;
  674. std::thread background_thread(PosixEnv::BackgroundThreadEntryPoint, this);
  675. background_thread.detach();
  676. }
  677. // If the queue is empty, the background thread may be waiting for work.
  678. if (background_work_queue_.empty()) {
  679. background_work_cv_.Signal();
  680. }
  681. background_work_queue_.emplace(background_work_function, background_work_arg);
  682. background_work_mutex_.Unlock();
  683. }
  684. void PosixEnv::BackgroundThreadMain() {
  685. while (true) {
  686. background_work_mutex_.Lock();
  687. // Wait until there is work to be done.
  688. while (background_work_queue_.empty()) {
  689. background_work_cv_.Wait();
  690. }
  691. assert(!background_work_queue_.empty());
  692. auto background_work_function = background_work_queue_.front().function;
  693. void* background_work_arg = background_work_queue_.front().arg;
  694. background_work_queue_.pop();
  695. background_work_mutex_.Unlock();
  696. background_work_function(background_work_arg);
  697. }
  698. }
  699. namespace {
  700. // Wraps an Env instance whose destructor is never created.
  701. //
  702. // Intended usage:
  703. // using PlatformSingletonEnv = SingletonEnv<PlatformEnv>;
  704. // void ConfigurePosixEnv(int param) {
  705. // PlatformSingletonEnv::AssertEnvNotInitialized();
  706. // // set global configuration flags.
  707. // }
  708. // Env* Env::Default() {
  709. // static PlatformSingletonEnv default_env;
  710. // return default_env.env();
  711. // }
  712. template <typename EnvType>
  713. class SingletonEnv {
  714. public:
  715. SingletonEnv() {
  716. #if !defined(NDEBUG)
  717. env_initialized_.store(true, std::memory_order::memory_order_relaxed);
  718. #endif // !defined(NDEBUG)
  719. static_assert(sizeof(env_storage_) >= sizeof(EnvType),
  720. "env_storage_ will not fit the Env");
  721. static_assert(alignof(decltype(env_storage_)) >= alignof(EnvType),
  722. "env_storage_ does not meet the Env's alignment needs");
  723. new (&env_storage_) EnvType();
  724. }
  725. ~SingletonEnv() = default;
  726. SingletonEnv(const SingletonEnv&) = delete;
  727. SingletonEnv& operator=(const SingletonEnv&) = delete;
  728. Env* env() { return reinterpret_cast<Env*>(&env_storage_); }
  729. static void AssertEnvNotInitialized() {
  730. #if !defined(NDEBUG)
  731. assert(!env_initialized_.load(std::memory_order::memory_order_relaxed));
  732. #endif // !defined(NDEBUG)
  733. }
  734. private:
  735. typename std::aligned_storage<sizeof(EnvType), alignof(EnvType)>::type
  736. env_storage_;
  737. #if !defined(NDEBUG)
  738. static std::atomic<bool> env_initialized_;
  739. #endif // !defined(NDEBUG)
  740. };
  741. #if !defined(NDEBUG)
  742. template <typename EnvType>
  743. std::atomic<bool> SingletonEnv<EnvType>::env_initialized_;
  744. #endif // !defined(NDEBUG)
  745. using PosixDefaultEnv = SingletonEnv<PosixEnv>;
  746. } // namespace
  747. void PosixEnv::StartThread(void (*thread_main)(void* thread_main_arg),
  748. void* thread_main_arg) {
  749. std::thread new_thread(thread_main, thread_main_arg);
  750. new_thread.detach();
  751. }
  752. void EnvPosixTestHelper::SetReadOnlyFDLimit(int limit) {
  753. PosixDefaultEnv::AssertEnvNotInitialized();
  754. g_open_read_only_file_limit = limit;
  755. }
  756. void EnvPosixTestHelper::SetReadOnlyMMapLimit(int limit) {
  757. PosixDefaultEnv::AssertEnvNotInitialized();
  758. g_mmap_limit = limit;
  759. }
  760. Env* Env::Default() {
  761. static PosixDefaultEnv env_container;
  762. return env_container.env();
  763. }
  764. } // namespace leveldb