小组成员: 曹可心-10223903406 朴祉燕-10224602413
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.

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