作者: 韩晨旭 10225101440 李畅 10225102463
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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