env_posix.cc 15 KB

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