作者: 韩晨旭 10225101440 李畅 10225102463
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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