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 #if !defined(LEVELDB_PLATFORM_WINDOWS)
18 #include <sys/types.h>
21 #if defined(LEVELDB_PLATFORM_ANDROID)
24 #include "leveldb/env.h"
25 #include "leveldb/slice.h"
26 #include "port/port.h"
27 #include "util/logging.h"
28 #include "util/mutexlock.h"
29 #include "util/posix_logger.h"
35 static Status IOError(const std::string& context, int err_number) {
36 return Status::IOError(context, strerror(err_number));
39 class PosixSequentialFile: public SequentialFile {
41 std::string filename_;
45 PosixSequentialFile(const std::string& fname, FILE* f)
46 : filename_(fname), file_(f) { }
47 virtual ~PosixSequentialFile() { fclose(file_); }
49 virtual Status Read(size_t n, Slice* result, char* scratch) {
51 size_t r = fread_unlocked(scratch, 1, n, file_);
52 *result = Slice(scratch, r);
55 // We leave status as ok if we hit the end of the file
57 // A partial read with an error: return a non-ok status
58 s = IOError(filename_, errno);
64 virtual Status Skip(uint64_t n) {
65 if (fseek(file_, n, SEEK_CUR)) {
66 return IOError(filename_, errno);
72 // pread() based random-access
73 class PosixRandomAccessFile: public RandomAccessFile {
75 std::string filename_;
79 PosixRandomAccessFile(const std::string& fname, int fd)
80 : filename_(fname), fd_(fd) { }
81 virtual ~PosixRandomAccessFile() { close(fd_); }
83 virtual Status Read(uint64_t offset, size_t n, Slice* result,
84 char* scratch) const {
86 ssize_t r = pread(fd_, scratch, n, static_cast<off_t>(offset));
87 *result = Slice(scratch, (r < 0) ? 0 : r);
89 // An error: return a non-ok status
90 s = IOError(filename_, errno);
96 // Helper class to limit mmap file usage so that we do not end up
97 // running out virtual memory or running into kernel performance
98 // problems for very large databases.
101 // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
103 SetAllowed(sizeof(void*) >= 8 ? 1000 : 0);
106 // If another mmap slot is available, acquire it and return true.
107 // Else return false.
109 if (GetAllowed() <= 0) {
113 intptr_t x = GetAllowed();
122 // Release a slot acquired by a previous call to Acquire() that returned true.
125 SetAllowed(GetAllowed() + 1);
130 port::AtomicPointer allowed_;
132 intptr_t GetAllowed() const {
133 return reinterpret_cast<intptr_t>(allowed_.Acquire_Load());
136 // REQUIRES: mu_ must be held
137 void SetAllowed(intptr_t v) {
138 allowed_.Release_Store(reinterpret_cast<void*>(v));
141 MmapLimiter(const MmapLimiter&);
142 void operator=(const MmapLimiter&);
145 // mmap() based random-access
146 class PosixMmapReadableFile: public RandomAccessFile {
148 std::string filename_;
149 void* mmapped_region_;
151 MmapLimiter* limiter_;
154 // base[0,length-1] contains the mmapped contents of the file.
155 PosixMmapReadableFile(const std::string& fname, void* base, size_t length,
156 MmapLimiter* limiter)
157 : filename_(fname), mmapped_region_(base), length_(length),
161 virtual ~PosixMmapReadableFile() {
162 munmap(mmapped_region_, length_);
166 virtual Status Read(uint64_t offset, size_t n, Slice* result,
167 char* scratch) const {
169 if (offset + n > length_) {
171 s = IOError(filename_, EINVAL);
173 *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
179 // We preallocate up to an extra megabyte and use memcpy to append new
180 // data to the file. This is safe since we either properly close the
181 // file before reading from it, or for log files, the reading code
182 // knows enough to skip zero suffixes.
183 class PosixMmapFile : public WritableFile {
185 std::string filename_;
188 size_t map_size_; // How much extra memory to map at a time
189 char* base_; // The mapped region
190 char* limit_; // Limit of the mapped region
191 char* dst_; // Where to write next (in range [base_,limit_])
192 char* last_sync_; // Where have we synced up to
193 uint64_t file_offset_; // Offset of base_ in file
195 // Have we done an munmap of unsynced data?
198 // Roundup x to a multiple of y
199 static size_t Roundup(size_t x, size_t y) {
200 return ((x + y - 1) / y) * y;
203 size_t TruncateToPageBoundary(size_t s) {
204 s -= (s & (page_size_ - 1));
205 assert((s % page_size_) == 0);
209 bool UnmapCurrentRegion() {
212 if (last_sync_ < limit_) {
213 // Defer syncing this data until next Sync() call, if any
214 pending_sync_ = true;
216 if (munmap(base_, limit_ - base_) != 0) {
219 file_offset_ += limit_ - base_;
225 // Increase the amount we map the next time, but capped at 1MB
226 if (map_size_ < (1<<20)) {
233 bool MapNewRegion() {
234 assert(base_ == NULL);
235 if (ftruncate(fd_, file_offset_ + map_size_) < 0) {
238 void* ptr = mmap(NULL, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED,
240 if (ptr == MAP_FAILED) {
243 base_ = reinterpret_cast<char*>(ptr);
244 limit_ = base_ + map_size_;
251 PosixMmapFile(const std::string& fname, int fd, size_t page_size)
254 page_size_(page_size),
255 map_size_(Roundup(65536, page_size)),
261 pending_sync_(false) {
262 assert((page_size & (page_size - 1)) == 0);
268 PosixMmapFile::Close();
272 virtual Status Append(const Slice& data) {
273 const char* src = data.data();
274 size_t left = data.size();
276 assert(base_ <= dst_);
277 assert(dst_ <= limit_);
278 size_t avail = limit_ - dst_;
280 if (!UnmapCurrentRegion() ||
282 return IOError(filename_, errno);
286 size_t n = (left <= avail) ? left : avail;
287 memcpy(dst_, src, n);
295 virtual Status Close() {
297 size_t unused = limit_ - dst_;
298 if (!UnmapCurrentRegion()) {
299 s = IOError(filename_, errno);
300 } else if (unused > 0) {
301 // Trim the extra space at the end of the file
302 if (ftruncate(fd_, file_offset_ - unused) < 0) {
303 s = IOError(filename_, errno);
307 if (close(fd_) < 0) {
309 s = IOError(filename_, errno);
319 virtual Status Flush() {
323 virtual Status Sync() {
327 // Some unmapped data was not synced
328 pending_sync_ = false;
329 if (fdatasync(fd_) < 0) {
330 s = IOError(filename_, errno);
334 if (dst_ > last_sync_) {
335 // Find the beginnings of the pages that contain the first and last
336 // bytes to be synced.
337 size_t p1 = TruncateToPageBoundary(last_sync_ - base_);
338 size_t p2 = TruncateToPageBoundary(dst_ - base_ - 1);
340 if (msync(base_ + p1, p2 - p1 + page_size_, MS_SYNC) < 0) {
341 s = IOError(filename_, errno);
349 static int LockOrUnlock(int fd, bool lock) {
352 memset(&f, 0, sizeof(f));
353 f.l_type = (lock ? F_WRLCK : F_UNLCK);
354 f.l_whence = SEEK_SET;
356 f.l_len = 0; // Lock/unlock entire file
357 return fcntl(fd, F_SETLK, &f);
360 class PosixFileLock : public FileLock {
366 // Set of locked files. We keep a separate set instead of just
367 // relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide
368 // any protection against multiple uses from the same process.
369 class PosixLockTable {
372 std::set<std::string> locked_files_;
374 bool Insert(const std::string& fname) {
376 return locked_files_.insert(fname).second;
378 void Remove(const std::string& fname) {
380 locked_files_.erase(fname);
384 class PosixEnv : public Env {
387 virtual ~PosixEnv() {
388 fprintf(stderr, "Destroying Env::Default()\n");
392 virtual Status NewSequentialFile(const std::string& fname,
393 SequentialFile** result) {
394 FILE* f = fopen(fname.c_str(), "r");
397 return IOError(fname, errno);
399 *result = new PosixSequentialFile(fname, f);
404 virtual Status NewRandomAccessFile(const std::string& fname,
405 RandomAccessFile** result) {
408 int fd = open(fname.c_str(), O_RDONLY);
410 s = IOError(fname, errno);
411 } else if (mmap_limit_.Acquire()) {
413 s = GetFileSize(fname, &size);
415 void* base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
416 if (base != MAP_FAILED) {
417 *result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_);
419 s = IOError(fname, errno);
424 mmap_limit_.Release();
427 *result = new PosixRandomAccessFile(fname, fd);
432 virtual Status NewWritableFile(const std::string& fname,
433 WritableFile** result) {
435 const int fd = open(fname.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0644);
438 s = IOError(fname, errno);
440 *result = new PosixMmapFile(fname, fd, page_size_);
445 virtual bool FileExists(const std::string& fname) {
446 return access(fname.c_str(), F_OK) == 0;
449 virtual Status GetChildren(const std::string& dir,
450 std::vector<std::string>* result) {
452 DIR* d = opendir(dir.c_str());
454 return IOError(dir, errno);
456 struct dirent* entry;
457 while ((entry = readdir(d)) != NULL) {
458 result->push_back(entry->d_name);
464 virtual Status DeleteFile(const std::string& fname) {
466 if (unlink(fname.c_str()) != 0) {
467 result = IOError(fname, errno);
472 virtual Status CreateDir(const std::string& name) {
474 if (mkdir(name.c_str(), 0755) != 0) {
475 result = IOError(name, errno);
480 virtual Status DeleteDir(const std::string& name) {
482 if (rmdir(name.c_str()) != 0) {
483 result = IOError(name, errno);
488 virtual Status GetFileSize(const std::string& fname, uint64_t* size) {
491 if (stat(fname.c_str(), &sbuf) != 0) {
493 s = IOError(fname, errno);
495 *size = sbuf.st_size;
500 virtual Status RenameFile(const std::string& src, const std::string& target) {
502 if (rename(src.c_str(), target.c_str()) != 0) {
503 result = IOError(src, errno);
508 virtual Status LockFile(const std::string& fname, FileLock** lock) {
511 int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
513 result = IOError(fname, errno);
514 } else if (!locks_.Insert(fname)) {
516 result = Status::IOError("lock " + fname, "already held by process");
517 } else if (LockOrUnlock(fd, true) == -1) {
518 result = IOError("lock " + fname, errno);
520 locks_.Remove(fname);
522 PosixFileLock* my_lock = new PosixFileLock;
524 my_lock->name_ = fname;
530 virtual Status UnlockFile(FileLock* lock) {
531 PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
533 if (LockOrUnlock(my_lock->fd_, false) == -1) {
534 result = IOError("unlock", errno);
536 locks_.Remove(my_lock->name_);
542 virtual void Schedule(void (*function)(void*), void* arg);
544 virtual void StartThread(void (*function)(void* arg), void* arg);
546 virtual Status GetTestDirectory(std::string* result) {
547 const char* env = getenv("TEST_TMPDIR");
548 if (env && env[0] != '\0') {
552 snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
555 // Directory may already exist
560 static uint64_t gettid() {
561 pthread_t tid = pthread_self();
562 uint64_t thread_id = 0;
563 memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
567 virtual Status NewLogger(const std::string& fname, Logger** result) {
568 FILE* f = fopen(fname.c_str(), "w");
571 return IOError(fname, errno);
573 *result = new PosixLogger(f, &PosixEnv::gettid);
578 virtual uint64_t NowMicros() {
580 gettimeofday(&tv, NULL);
581 return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
584 virtual void SleepForMicroseconds(int micros) {
589 void PthreadCall(const char* label, int result) {
591 fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
596 // BGThread() is the body of the background thread
598 static void* BGThreadWrapper(void* arg) {
599 reinterpret_cast<PosixEnv*>(arg)->BGThread();
605 pthread_cond_t bgsignal_;
607 bool started_bgthread_;
609 // Entry per Schedule() call
610 struct BGItem { void* arg; void (*function)(void*); };
611 typedef std::deque<BGItem> BGQueue;
614 PosixLockTable locks_;
615 MmapLimiter mmap_limit_;
618 PosixEnv::PosixEnv() : page_size_(getpagesize()),
619 started_bgthread_(false) {
620 PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL));
621 PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL));
624 void PosixEnv::Schedule(void (*function)(void*), void* arg) {
625 PthreadCall("lock", pthread_mutex_lock(&mu_));
627 // Start background thread if necessary
628 if (!started_bgthread_) {
629 started_bgthread_ = true;
632 pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this));
635 // If the queue is currently empty, the background thread may currently be
637 if (queue_.empty()) {
638 PthreadCall("signal", pthread_cond_signal(&bgsignal_));
641 // Add to priority queue
642 queue_.push_back(BGItem());
643 queue_.back().function = function;
644 queue_.back().arg = arg;
646 PthreadCall("unlock", pthread_mutex_unlock(&mu_));
649 void PosixEnv::BGThread() {
651 // Wait until there is an item that is ready to run
652 PthreadCall("lock", pthread_mutex_lock(&mu_));
653 while (queue_.empty()) {
654 PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
657 void (*function)(void*) = queue_.front().function;
658 void* arg = queue_.front().arg;
661 PthreadCall("unlock", pthread_mutex_unlock(&mu_));
667 struct StartThreadState {
668 void (*user_function)(void*);
672 static void* StartThreadWrapper(void* arg) {
673 StartThreadState* state = reinterpret_cast<StartThreadState*>(arg);
674 state->user_function(state->arg);
679 void PosixEnv::StartThread(void (*function)(void* arg), void* arg) {
681 StartThreadState* state = new StartThreadState;
682 state->user_function = function;
684 PthreadCall("start thread",
685 pthread_create(&t, NULL, &StartThreadWrapper, state));
690 static pthread_once_t once = PTHREAD_ONCE_INIT;
691 static Env* default_env;
692 static void InitDefaultEnv() { default_env = new PosixEnv; }
694 Env* Env::Default() {
695 pthread_once(&once, InitDefaultEnv);
699 } // namespace leveldb