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.

698 rivejä
18 KiB

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