作者: 韩晨旭 10225101440 李畅 10225102463
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

747 řádky
19 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)
před 10 roky
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)
před 10 roky
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)
před 10 roky
  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 <errno.h>
  6. #include <fcntl.h>
  7. #include <pthread.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <sys/mman.h>
  12. #include <sys/resource.h>
  13. #include <sys/stat.h>
  14. #include <sys/time.h>
  15. #include <sys/types.h>
  16. #include <time.h>
  17. #include <unistd.h>
  18. #include <atomic>
  19. #include <deque>
  20. #include <limits>
  21. #include <set>
  22. #include "leveldb/env.h"
  23. #include "leveldb/slice.h"
  24. #include "port/port.h"
  25. #include "port/thread_annotations.h"
  26. #include "util/logging.h"
  27. #include "util/mutexlock.h"
  28. #include "util/posix_logger.h"
  29. #include "util/env_posix_test_helper.h"
  30. // HAVE_FDATASYNC is defined in the auto-generated port_config.h, which is
  31. // included by port_stdcxx.h.
  32. #if !HAVE_FDATASYNC
  33. #define fdatasync fsync
  34. #endif // !HAVE_FDATASYNC
  35. namespace leveldb {
  36. namespace {
  37. static int open_read_only_file_limit = -1;
  38. static int mmap_limit = -1;
  39. static const size_t kBufSize = 65536;
  40. static Status PosixError(const std::string& context, int err_number) {
  41. if (err_number == ENOENT) {
  42. return Status::NotFound(context, strerror(err_number));
  43. } else {
  44. return Status::IOError(context, strerror(err_number));
  45. }
  46. }
  47. // Helper class to limit resource usage to avoid exhaustion.
  48. // Currently used to limit read-only file descriptors and mmap file usage
  49. // so that we do not run out of file descriptors or virtual memory, or run into
  50. // kernel performance problems for very large databases.
  51. class Limiter {
  52. public:
  53. // Limit maximum number of resources to |max_acquires|.
  54. Limiter(int max_acquires) : acquires_allowed_(max_acquires) {}
  55. Limiter(const Limiter&) = delete;
  56. Limiter operator=(const Limiter&) = delete;
  57. // If another resource is available, acquire it and return true.
  58. // Else return false.
  59. bool Acquire() {
  60. int old_acquires_allowed =
  61. acquires_allowed_.fetch_sub(1, std::memory_order_relaxed);
  62. if (old_acquires_allowed > 0)
  63. return true;
  64. acquires_allowed_.fetch_add(1, std::memory_order_relaxed);
  65. return false;
  66. }
  67. // Release a resource acquired by a previous call to Acquire() that returned
  68. // true.
  69. void Release() {
  70. acquires_allowed_.fetch_add(1, std::memory_order_relaxed);
  71. }
  72. private:
  73. // The number of available resources.
  74. //
  75. // This is a counter and is not tied to the invariants of any other class, so
  76. // it can be operated on safely using std::memory_order_relaxed.
  77. std::atomic<int> acquires_allowed_;
  78. };
  79. class PosixSequentialFile: public SequentialFile {
  80. private:
  81. std::string filename_;
  82. int fd_;
  83. public:
  84. PosixSequentialFile(const std::string& fname, int fd)
  85. : filename_(fname), fd_(fd) {}
  86. virtual ~PosixSequentialFile() { close(fd_); }
  87. virtual Status Read(size_t n, Slice* result, char* scratch) {
  88. Status s;
  89. while (true) {
  90. ssize_t r = read(fd_, scratch, n);
  91. if (r < 0) {
  92. if (errno == EINTR) {
  93. continue; // Retry
  94. }
  95. s = PosixError(filename_, errno);
  96. break;
  97. }
  98. *result = Slice(scratch, r);
  99. break;
  100. }
  101. return s;
  102. }
  103. virtual Status Skip(uint64_t n) {
  104. if (lseek(fd_, n, SEEK_CUR) == static_cast<off_t>(-1)) {
  105. return PosixError(filename_, errno);
  106. }
  107. return Status::OK();
  108. }
  109. };
  110. // pread() based random-access
  111. class PosixRandomAccessFile: public RandomAccessFile {
  112. private:
  113. std::string filename_;
  114. bool temporary_fd_; // If true, fd_ is -1 and we open on every read.
  115. int fd_;
  116. Limiter* limiter_;
  117. public:
  118. PosixRandomAccessFile(const std::string& fname, int fd, Limiter* limiter)
  119. : filename_(fname), fd_(fd), limiter_(limiter) {
  120. temporary_fd_ = !limiter->Acquire();
  121. if (temporary_fd_) {
  122. // Open file on every access.
  123. close(fd_);
  124. fd_ = -1;
  125. }
  126. }
  127. virtual ~PosixRandomAccessFile() {
  128. if (!temporary_fd_) {
  129. close(fd_);
  130. limiter_->Release();
  131. }
  132. }
  133. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  134. char* scratch) const {
  135. int fd = fd_;
  136. if (temporary_fd_) {
  137. fd = open(filename_.c_str(), O_RDONLY);
  138. if (fd < 0) {
  139. return PosixError(filename_, errno);
  140. }
  141. }
  142. Status s;
  143. ssize_t r = pread(fd, scratch, n, static_cast<off_t>(offset));
  144. *result = Slice(scratch, (r < 0) ? 0 : r);
  145. if (r < 0) {
  146. // An error: return a non-ok status
  147. s = PosixError(filename_, errno);
  148. }
  149. if (temporary_fd_) {
  150. // Close the temporary file descriptor opened earlier.
  151. close(fd);
  152. }
  153. return s;
  154. }
  155. };
  156. // mmap() based random-access
  157. class PosixMmapReadableFile: public RandomAccessFile {
  158. private:
  159. std::string filename_;
  160. void* mmapped_region_;
  161. size_t length_;
  162. Limiter* limiter_;
  163. public:
  164. // base[0,length-1] contains the mmapped contents of the file.
  165. PosixMmapReadableFile(const std::string& fname, void* base, size_t length,
  166. Limiter* limiter)
  167. : filename_(fname), mmapped_region_(base), length_(length),
  168. limiter_(limiter) {
  169. }
  170. virtual ~PosixMmapReadableFile() {
  171. munmap(mmapped_region_, length_);
  172. limiter_->Release();
  173. }
  174. virtual Status Read(uint64_t offset, size_t n, Slice* result,
  175. char* scratch) const {
  176. Status s;
  177. if (offset + n > length_) {
  178. *result = Slice();
  179. s = PosixError(filename_, EINVAL);
  180. } else {
  181. *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
  182. }
  183. return s;
  184. }
  185. };
  186. class PosixWritableFile : public WritableFile {
  187. private:
  188. // buf_[0, pos_-1] contains data to be written to fd_.
  189. std::string filename_;
  190. int fd_;
  191. char buf_[kBufSize];
  192. size_t pos_;
  193. public:
  194. PosixWritableFile(const std::string& fname, int fd)
  195. : filename_(fname), fd_(fd), pos_(0) { }
  196. ~PosixWritableFile() {
  197. if (fd_ >= 0) {
  198. // Ignoring any potential errors
  199. Close();
  200. }
  201. }
  202. virtual Status Append(const Slice& data) {
  203. size_t n = data.size();
  204. const char* p = data.data();
  205. // Fit as much as possible into buffer.
  206. size_t copy = std::min(n, kBufSize - pos_);
  207. memcpy(buf_ + pos_, p, copy);
  208. p += copy;
  209. n -= copy;
  210. pos_ += copy;
  211. if (n == 0) {
  212. return Status::OK();
  213. }
  214. // Can't fit in buffer, so need to do at least one write.
  215. Status s = FlushBuffered();
  216. if (!s.ok()) {
  217. return s;
  218. }
  219. // Small writes go to buffer, large writes are written directly.
  220. if (n < kBufSize) {
  221. memcpy(buf_, p, n);
  222. pos_ = n;
  223. return Status::OK();
  224. }
  225. return WriteRaw(p, n);
  226. }
  227. virtual Status Close() {
  228. Status result = FlushBuffered();
  229. const int r = close(fd_);
  230. if (r < 0 && result.ok()) {
  231. result = PosixError(filename_, errno);
  232. }
  233. fd_ = -1;
  234. return result;
  235. }
  236. virtual Status Flush() {
  237. return FlushBuffered();
  238. }
  239. Status SyncDirIfManifest() {
  240. const char* f = filename_.c_str();
  241. const char* sep = strrchr(f, '/');
  242. Slice basename;
  243. std::string dir;
  244. if (sep == nullptr) {
  245. dir = ".";
  246. basename = f;
  247. } else {
  248. dir = std::string(f, sep - f);
  249. basename = sep + 1;
  250. }
  251. Status s;
  252. if (basename.starts_with("MANIFEST")) {
  253. int fd = open(dir.c_str(), O_RDONLY);
  254. if (fd < 0) {
  255. s = PosixError(dir, errno);
  256. } else {
  257. if (fsync(fd) < 0) {
  258. s = PosixError(dir, errno);
  259. }
  260. close(fd);
  261. }
  262. }
  263. return s;
  264. }
  265. virtual Status Sync() {
  266. // Ensure new files referred to by the manifest are in the filesystem.
  267. Status s = SyncDirIfManifest();
  268. if (!s.ok()) {
  269. return s;
  270. }
  271. s = FlushBuffered();
  272. if (s.ok()) {
  273. if (fdatasync(fd_) != 0) {
  274. s = PosixError(filename_, errno);
  275. }
  276. }
  277. return s;
  278. }
  279. private:
  280. Status FlushBuffered() {
  281. Status s = WriteRaw(buf_, pos_);
  282. pos_ = 0;
  283. return s;
  284. }
  285. Status WriteRaw(const char* p, size_t n) {
  286. while (n > 0) {
  287. ssize_t r = write(fd_, p, n);
  288. if (r < 0) {
  289. if (errno == EINTR) {
  290. continue; // Retry
  291. }
  292. return PosixError(filename_, errno);
  293. }
  294. p += r;
  295. n -= r;
  296. }
  297. return Status::OK();
  298. }
  299. };
  300. static int LockOrUnlock(int fd, bool lock) {
  301. errno = 0;
  302. struct flock f;
  303. memset(&f, 0, sizeof(f));
  304. f.l_type = (lock ? F_WRLCK : F_UNLCK);
  305. f.l_whence = SEEK_SET;
  306. f.l_start = 0;
  307. f.l_len = 0; // Lock/unlock entire file
  308. return fcntl(fd, F_SETLK, &f);
  309. }
  310. class PosixFileLock : public FileLock {
  311. public:
  312. int fd_;
  313. std::string name_;
  314. };
  315. // Set of locked files. We keep a separate set instead of just
  316. // relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide
  317. // any protection against multiple uses from the same process.
  318. class PosixLockTable {
  319. private:
  320. port::Mutex mu_;
  321. std::set<std::string> locked_files_ GUARDED_BY(mu_);
  322. public:
  323. bool Insert(const std::string& fname) LOCKS_EXCLUDED(mu_) {
  324. MutexLock l(&mu_);
  325. return locked_files_.insert(fname).second;
  326. }
  327. void Remove(const std::string& fname) LOCKS_EXCLUDED(mu_) {
  328. MutexLock l(&mu_);
  329. locked_files_.erase(fname);
  330. }
  331. };
  332. class PosixEnv : public Env {
  333. public:
  334. PosixEnv();
  335. virtual ~PosixEnv() {
  336. char msg[] = "Destroying Env::Default()\n";
  337. fwrite(msg, 1, sizeof(msg), stderr);
  338. abort();
  339. }
  340. virtual Status NewSequentialFile(const std::string& fname,
  341. SequentialFile** result) {
  342. int fd = open(fname.c_str(), O_RDONLY);
  343. if (fd < 0) {
  344. *result = nullptr;
  345. return PosixError(fname, errno);
  346. } else {
  347. *result = new PosixSequentialFile(fname, fd);
  348. return Status::OK();
  349. }
  350. }
  351. virtual Status NewRandomAccessFile(const std::string& fname,
  352. RandomAccessFile** result) {
  353. *result = nullptr;
  354. Status s;
  355. int fd = open(fname.c_str(), O_RDONLY);
  356. if (fd < 0) {
  357. s = PosixError(fname, errno);
  358. } else if (mmap_limit_.Acquire()) {
  359. uint64_t size;
  360. s = GetFileSize(fname, &size);
  361. if (s.ok()) {
  362. void* base = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
  363. if (base != MAP_FAILED) {
  364. *result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_);
  365. } else {
  366. s = PosixError(fname, errno);
  367. }
  368. }
  369. close(fd);
  370. if (!s.ok()) {
  371. mmap_limit_.Release();
  372. }
  373. } else {
  374. *result = new PosixRandomAccessFile(fname, fd, &fd_limit_);
  375. }
  376. return s;
  377. }
  378. virtual Status NewWritableFile(const std::string& fname,
  379. WritableFile** result) {
  380. Status s;
  381. int fd = open(fname.c_str(), O_TRUNC | O_WRONLY | O_CREAT, 0644);
  382. if (fd < 0) {
  383. *result = nullptr;
  384. s = PosixError(fname, errno);
  385. } else {
  386. *result = new PosixWritableFile(fname, fd);
  387. }
  388. return s;
  389. }
  390. virtual Status NewAppendableFile(const std::string& fname,
  391. WritableFile** result) {
  392. Status s;
  393. int fd = open(fname.c_str(), O_APPEND | O_WRONLY | O_CREAT, 0644);
  394. if (fd < 0) {
  395. *result = nullptr;
  396. s = PosixError(fname, errno);
  397. } else {
  398. *result = new PosixWritableFile(fname, fd);
  399. }
  400. return s;
  401. }
  402. virtual bool FileExists(const std::string& fname) {
  403. return access(fname.c_str(), F_OK) == 0;
  404. }
  405. virtual Status GetChildren(const std::string& dir,
  406. std::vector<std::string>* result) {
  407. result->clear();
  408. DIR* d = opendir(dir.c_str());
  409. if (d == nullptr) {
  410. return PosixError(dir, errno);
  411. }
  412. struct dirent* entry;
  413. while ((entry = readdir(d)) != nullptr) {
  414. result->push_back(entry->d_name);
  415. }
  416. closedir(d);
  417. return Status::OK();
  418. }
  419. virtual Status DeleteFile(const std::string& fname) {
  420. Status result;
  421. if (unlink(fname.c_str()) != 0) {
  422. result = PosixError(fname, errno);
  423. }
  424. return result;
  425. }
  426. virtual Status CreateDir(const std::string& name) {
  427. Status result;
  428. if (mkdir(name.c_str(), 0755) != 0) {
  429. result = PosixError(name, errno);
  430. }
  431. return result;
  432. }
  433. virtual Status DeleteDir(const std::string& name) {
  434. Status result;
  435. if (rmdir(name.c_str()) != 0) {
  436. result = PosixError(name, errno);
  437. }
  438. return result;
  439. }
  440. virtual Status GetFileSize(const std::string& fname, uint64_t* size) {
  441. Status s;
  442. struct stat sbuf;
  443. if (stat(fname.c_str(), &sbuf) != 0) {
  444. *size = 0;
  445. s = PosixError(fname, errno);
  446. } else {
  447. *size = sbuf.st_size;
  448. }
  449. return s;
  450. }
  451. virtual Status RenameFile(const std::string& src, const std::string& target) {
  452. Status result;
  453. if (rename(src.c_str(), target.c_str()) != 0) {
  454. result = PosixError(src, errno);
  455. }
  456. return result;
  457. }
  458. virtual Status LockFile(const std::string& fname, FileLock** lock) {
  459. *lock = nullptr;
  460. Status result;
  461. int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
  462. if (fd < 0) {
  463. result = PosixError(fname, errno);
  464. } else if (!locks_.Insert(fname)) {
  465. close(fd);
  466. result = Status::IOError("lock " + fname, "already held by process");
  467. } else if (LockOrUnlock(fd, true) == -1) {
  468. result = PosixError("lock " + fname, errno);
  469. close(fd);
  470. locks_.Remove(fname);
  471. } else {
  472. PosixFileLock* my_lock = new PosixFileLock;
  473. my_lock->fd_ = fd;
  474. my_lock->name_ = fname;
  475. *lock = my_lock;
  476. }
  477. return result;
  478. }
  479. virtual Status UnlockFile(FileLock* lock) {
  480. PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
  481. Status result;
  482. if (LockOrUnlock(my_lock->fd_, false) == -1) {
  483. result = PosixError("unlock", errno);
  484. }
  485. locks_.Remove(my_lock->name_);
  486. close(my_lock->fd_);
  487. delete my_lock;
  488. return result;
  489. }
  490. virtual void Schedule(void (*function)(void*), void* arg);
  491. virtual void StartThread(void (*function)(void* arg), void* arg);
  492. virtual Status GetTestDirectory(std::string* result) {
  493. const char* env = getenv("TEST_TMPDIR");
  494. if (env && env[0] != '\0') {
  495. *result = env;
  496. } else {
  497. char buf[100];
  498. snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
  499. *result = buf;
  500. }
  501. // Directory may already exist
  502. CreateDir(*result);
  503. return Status::OK();
  504. }
  505. static uint64_t gettid() {
  506. pthread_t tid = pthread_self();
  507. uint64_t thread_id = 0;
  508. memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
  509. return thread_id;
  510. }
  511. virtual Status NewLogger(const std::string& fname, Logger** result) {
  512. FILE* f = fopen(fname.c_str(), "w");
  513. if (f == nullptr) {
  514. *result = nullptr;
  515. return PosixError(fname, errno);
  516. } else {
  517. *result = new PosixLogger(f, &PosixEnv::gettid);
  518. return Status::OK();
  519. }
  520. }
  521. virtual uint64_t NowMicros() {
  522. struct timeval tv;
  523. gettimeofday(&tv, nullptr);
  524. return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
  525. }
  526. virtual void SleepForMicroseconds(int micros) {
  527. usleep(micros);
  528. }
  529. private:
  530. void PthreadCall(const char* label, int result) {
  531. if (result != 0) {
  532. fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
  533. abort();
  534. }
  535. }
  536. // BGThread() is the body of the background thread
  537. void BGThread();
  538. static void* BGThreadWrapper(void* arg) {
  539. reinterpret_cast<PosixEnv*>(arg)->BGThread();
  540. return nullptr;
  541. }
  542. pthread_mutex_t mu_;
  543. pthread_cond_t bgsignal_;
  544. pthread_t bgthread_;
  545. bool started_bgthread_;
  546. // Entry per Schedule() call
  547. struct BGItem { void* arg; void (*function)(void*); };
  548. typedef std::deque<BGItem> BGQueue;
  549. BGQueue queue_;
  550. PosixLockTable locks_;
  551. Limiter mmap_limit_;
  552. Limiter fd_limit_;
  553. };
  554. // Return the maximum number of concurrent mmaps.
  555. static int MaxMmaps() {
  556. if (mmap_limit >= 0) {
  557. return mmap_limit;
  558. }
  559. // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
  560. mmap_limit = sizeof(void*) >= 8 ? 1000 : 0;
  561. return mmap_limit;
  562. }
  563. // Return the maximum number of read-only files to keep open.
  564. static intptr_t MaxOpenFiles() {
  565. if (open_read_only_file_limit >= 0) {
  566. return open_read_only_file_limit;
  567. }
  568. struct rlimit rlim;
  569. if (getrlimit(RLIMIT_NOFILE, &rlim)) {
  570. // getrlimit failed, fallback to hard-coded default.
  571. open_read_only_file_limit = 50;
  572. } else if (rlim.rlim_cur == RLIM_INFINITY) {
  573. open_read_only_file_limit = std::numeric_limits<int>::max();
  574. } else {
  575. // Allow use of 20% of available file descriptors for read-only files.
  576. open_read_only_file_limit = rlim.rlim_cur / 5;
  577. }
  578. return open_read_only_file_limit;
  579. }
  580. PosixEnv::PosixEnv()
  581. : started_bgthread_(false),
  582. mmap_limit_(MaxMmaps()),
  583. fd_limit_(MaxOpenFiles()) {
  584. PthreadCall("mutex_init", pthread_mutex_init(&mu_, nullptr));
  585. PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, nullptr));
  586. }
  587. void PosixEnv::Schedule(void (*function)(void*), void* arg) {
  588. PthreadCall("lock", pthread_mutex_lock(&mu_));
  589. // Start background thread if necessary
  590. if (!started_bgthread_) {
  591. started_bgthread_ = true;
  592. PthreadCall(
  593. "create thread",
  594. pthread_create(&bgthread_, nullptr, &PosixEnv::BGThreadWrapper, this));
  595. }
  596. // If the queue is currently empty, the background thread may currently be
  597. // waiting.
  598. if (queue_.empty()) {
  599. PthreadCall("signal", pthread_cond_signal(&bgsignal_));
  600. }
  601. // Add to priority queue
  602. queue_.push_back(BGItem());
  603. queue_.back().function = function;
  604. queue_.back().arg = arg;
  605. PthreadCall("unlock", pthread_mutex_unlock(&mu_));
  606. }
  607. void PosixEnv::BGThread() {
  608. while (true) {
  609. // Wait until there is an item that is ready to run
  610. PthreadCall("lock", pthread_mutex_lock(&mu_));
  611. while (queue_.empty()) {
  612. PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
  613. }
  614. void (*function)(void*) = queue_.front().function;
  615. void* arg = queue_.front().arg;
  616. queue_.pop_front();
  617. PthreadCall("unlock", pthread_mutex_unlock(&mu_));
  618. (*function)(arg);
  619. }
  620. }
  621. namespace {
  622. struct StartThreadState {
  623. void (*user_function)(void*);
  624. void* arg;
  625. };
  626. }
  627. static void* StartThreadWrapper(void* arg) {
  628. StartThreadState* state = reinterpret_cast<StartThreadState*>(arg);
  629. state->user_function(state->arg);
  630. delete state;
  631. return nullptr;
  632. }
  633. void PosixEnv::StartThread(void (*function)(void* arg), void* arg) {
  634. pthread_t t;
  635. StartThreadState* state = new StartThreadState;
  636. state->user_function = function;
  637. state->arg = arg;
  638. PthreadCall("start thread",
  639. pthread_create(&t, nullptr, &StartThreadWrapper, state));
  640. }
  641. } // namespace
  642. static pthread_once_t once = PTHREAD_ONCE_INIT;
  643. static Env* default_env;
  644. static void InitDefaultEnv() { default_env = new PosixEnv; }
  645. void EnvPosixTestHelper::SetReadOnlyFDLimit(int limit) {
  646. assert(default_env == nullptr);
  647. open_read_only_file_limit = limit;
  648. }
  649. void EnvPosixTestHelper::SetReadOnlyMMapLimit(int limit) {
  650. assert(default_env == nullptr);
  651. mmap_limit = limit;
  652. }
  653. Env* Env::Default() {
  654. pthread_once(&once, InitDefaultEnv);
  655. return default_env;
  656. }
  657. } // namespace leveldb