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)
16 #include <sys/types.h>
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"
32 static Status IOError(const std::string& context, int err_number) {
33 return Status::IOError(context, strerror(err_number));
36 class PosixSequentialFile: public SequentialFile {
38 std::string filename_;
42 PosixSequentialFile(const std::string& fname, FILE* f)
43 : filename_(fname), file_(f) { }
44 virtual ~PosixSequentialFile() { fclose(file_); }
46 virtual Status Read(size_t n, Slice* result, char* scratch) {
48 size_t r = fread_unlocked(scratch, 1, n, file_);
49 *result = Slice(scratch, r);
52 // We leave status as ok if we hit the end of the file
54 // A partial read with an error: return a non-ok status
55 s = IOError(filename_, errno);
61 virtual Status Skip(uint64_t n) {
62 if (fseek(file_, n, SEEK_CUR)) {
63 return IOError(filename_, errno);
69 // pread() based random-access
70 class PosixRandomAccessFile: public RandomAccessFile {
72 std::string filename_;
76 PosixRandomAccessFile(const std::string& fname, int fd)
77 : filename_(fname), fd_(fd) { }
78 virtual ~PosixRandomAccessFile() { close(fd_); }
80 virtual Status Read(uint64_t offset, size_t n, Slice* result,
81 char* scratch) const {
83 ssize_t r = pread(fd_, scratch, n, static_cast<off_t>(offset));
84 *result = Slice(scratch, (r < 0) ? 0 : r);
86 // An error: return a non-ok status
87 s = IOError(filename_, errno);
93 // Helper class to limit mmap file usage so that we do not end up
94 // running out virtual memory or running into kernel performance
95 // problems for very large databases.
98 // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
100 SetAllowed(sizeof(void*) >= 8 ? 1000 : 0);
103 // If another mmap slot is available, acquire it and return true.
104 // Else return false.
106 if (GetAllowed() <= 0) {
110 intptr_t x = GetAllowed();
119 // Release a slot acquired by a previous call to Acquire() that returned true.
122 SetAllowed(GetAllowed() + 1);
127 port::AtomicPointer allowed_;
129 intptr_t GetAllowed() const {
130 return reinterpret_cast<intptr_t>(allowed_.Acquire_Load());
133 // REQUIRES: mu_ must be held
134 void SetAllowed(intptr_t v) {
135 allowed_.Release_Store(reinterpret_cast<void*>(v));
138 MmapLimiter(const MmapLimiter&);
139 void operator=(const MmapLimiter&);
142 // mmap() based random-access
143 class PosixMmapReadableFile: public RandomAccessFile {
145 std::string filename_;
146 void* mmapped_region_;
148 MmapLimiter* limiter_;
151 // base[0,length-1] contains the mmapped contents of the file.
152 PosixMmapReadableFile(const std::string& fname, void* base, size_t length,
153 MmapLimiter* limiter)
154 : filename_(fname), mmapped_region_(base), length_(length),
158 virtual ~PosixMmapReadableFile() {
159 munmap(mmapped_region_, length_);
163 virtual Status Read(uint64_t offset, size_t n, Slice* result,
164 char* scratch) const {
166 if (offset + n > length_) {
168 s = IOError(filename_, EINVAL);
170 *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
176 class PosixWritableFile : public WritableFile {
178 std::string filename_;
182 PosixWritableFile(const std::string& fname, FILE* f)
183 : filename_(fname), file_(f) { }
185 ~PosixWritableFile() {
187 // Ignoring any potential errors
192 virtual Status Append(const Slice& data) {
193 size_t r = fwrite_unlocked(data.data(), 1, data.size(), file_);
194 if (r != data.size()) {
195 return IOError(filename_, errno);
200 virtual Status Close() {
202 if (fclose(file_) != 0) {
203 result = IOError(filename_, errno);
209 virtual Status Flush() {
210 if (fflush_unlocked(file_) != 0) {
211 return IOError(filename_, errno);
216 Status SyncDirIfManifest() {
217 const char* f = filename_.c_str();
218 const char* sep = strrchr(f, '/');
225 dir = std::string(f, sep - f);
229 if (basename.starts_with("MANIFEST")) {
230 int fd = open(dir.c_str(), O_RDONLY);
232 s = IOError(dir, errno);
235 s = IOError(dir, errno);
243 virtual Status Sync() {
244 // Ensure new files referred to by the manifest are in the filesystem.
245 Status s = SyncDirIfManifest();
249 if (fflush_unlocked(file_) != 0 ||
250 fdatasync(fileno(file_)) != 0) {
251 s = Status::IOError(filename_, strerror(errno));
257 static int LockOrUnlock(int fd, bool lock) {
260 memset(&f, 0, sizeof(f));
261 f.l_type = (lock ? F_WRLCK : F_UNLCK);
262 f.l_whence = SEEK_SET;
264 f.l_len = 0; // Lock/unlock entire file
265 return fcntl(fd, F_SETLK, &f);
268 class PosixFileLock : public FileLock {
274 // Set of locked files. We keep a separate set instead of just
275 // relying on fcntrl(F_SETLK) since fcntl(F_SETLK) does not provide
276 // any protection against multiple uses from the same process.
277 class PosixLockTable {
280 std::set<std::string> locked_files_;
282 bool Insert(const std::string& fname) {
284 return locked_files_.insert(fname).second;
286 void Remove(const std::string& fname) {
288 locked_files_.erase(fname);
292 class PosixEnv : public Env {
295 virtual ~PosixEnv() {
296 char msg[] = "Destroying Env::Default()\n";
297 fwrite(msg, 1, sizeof(msg), stderr);
301 virtual Status NewSequentialFile(const std::string& fname,
302 SequentialFile** result) {
303 FILE* f = fopen(fname.c_str(), "r");
306 return IOError(fname, errno);
308 *result = new PosixSequentialFile(fname, f);
313 virtual Status NewRandomAccessFile(const std::string& fname,
314 RandomAccessFile** result) {
317 int fd = open(fname.c_str(), O_RDONLY);
319 s = IOError(fname, errno);
320 } else if (mmap_limit_.Acquire()) {
322 s = GetFileSize(fname, &size);
324 void* base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
325 if (base != MAP_FAILED) {
326 *result = new PosixMmapReadableFile(fname, base, size, &mmap_limit_);
328 s = IOError(fname, errno);
333 mmap_limit_.Release();
336 *result = new PosixRandomAccessFile(fname, fd);
341 virtual Status NewWritableFile(const std::string& fname,
342 WritableFile** result) {
344 FILE* f = fopen(fname.c_str(), "w");
347 s = IOError(fname, errno);
349 *result = new PosixWritableFile(fname, f);
354 virtual bool FileExists(const std::string& fname) {
355 return access(fname.c_str(), F_OK) == 0;
358 virtual Status GetChildren(const std::string& dir,
359 std::vector<std::string>* result) {
361 DIR* d = opendir(dir.c_str());
363 return IOError(dir, errno);
365 struct dirent* entry;
366 while ((entry = readdir(d)) != NULL) {
367 result->push_back(entry->d_name);
373 virtual Status DeleteFile(const std::string& fname) {
375 if (unlink(fname.c_str()) != 0) {
376 result = IOError(fname, errno);
381 virtual Status CreateDir(const std::string& name) {
383 if (mkdir(name.c_str(), 0755) != 0) {
384 result = IOError(name, errno);
389 virtual Status DeleteDir(const std::string& name) {
391 if (rmdir(name.c_str()) != 0) {
392 result = IOError(name, errno);
397 virtual Status GetFileSize(const std::string& fname, uint64_t* size) {
400 if (stat(fname.c_str(), &sbuf) != 0) {
402 s = IOError(fname, errno);
404 *size = sbuf.st_size;
409 virtual Status RenameFile(const std::string& src, const std::string& target) {
411 if (rename(src.c_str(), target.c_str()) != 0) {
412 result = IOError(src, errno);
417 virtual Status LockFile(const std::string& fname, FileLock** lock) {
420 int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
422 result = IOError(fname, errno);
423 } else if (!locks_.Insert(fname)) {
425 result = Status::IOError("lock " + fname, "already held by process");
426 } else if (LockOrUnlock(fd, true) == -1) {
427 result = IOError("lock " + fname, errno);
429 locks_.Remove(fname);
431 PosixFileLock* my_lock = new PosixFileLock;
433 my_lock->name_ = fname;
439 virtual Status UnlockFile(FileLock* lock) {
440 PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
442 if (LockOrUnlock(my_lock->fd_, false) == -1) {
443 result = IOError("unlock", errno);
445 locks_.Remove(my_lock->name_);
451 virtual void Schedule(void (*function)(void*), void* arg);
453 virtual void StartThread(void (*function)(void* arg), void* arg);
455 virtual Status GetTestDirectory(std::string* result) {
456 const char* env = getenv("TEST_TMPDIR");
457 if (env && env[0] != '\0') {
461 snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
464 // Directory may already exist
469 static uint64_t gettid() {
470 pthread_t tid = pthread_self();
471 uint64_t thread_id = 0;
472 memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
476 virtual Status NewLogger(const std::string& fname, Logger** result) {
477 FILE* f = fopen(fname.c_str(), "w");
480 return IOError(fname, errno);
482 *result = new PosixLogger(f, &PosixEnv::gettid);
487 virtual uint64_t NowMicros() {
489 gettimeofday(&tv, NULL);
490 return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
493 virtual void SleepForMicroseconds(int micros) {
498 void PthreadCall(const char* label, int result) {
500 fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
505 // BGThread() is the body of the background thread
507 static void* BGThreadWrapper(void* arg) {
508 reinterpret_cast<PosixEnv*>(arg)->BGThread();
513 pthread_cond_t bgsignal_;
515 bool started_bgthread_;
517 // Entry per Schedule() call
518 struct BGItem { void* arg; void (*function)(void*); };
519 typedef std::deque<BGItem> BGQueue;
522 PosixLockTable locks_;
523 MmapLimiter mmap_limit_;
526 PosixEnv::PosixEnv() : started_bgthread_(false) {
527 PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL));
528 PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL));
531 void PosixEnv::Schedule(void (*function)(void*), void* arg) {
532 PthreadCall("lock", pthread_mutex_lock(&mu_));
534 // Start background thread if necessary
535 if (!started_bgthread_) {
536 started_bgthread_ = true;
539 pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this));
542 // If the queue is currently empty, the background thread may currently be
544 if (queue_.empty()) {
545 PthreadCall("signal", pthread_cond_signal(&bgsignal_));
548 // Add to priority queue
549 queue_.push_back(BGItem());
550 queue_.back().function = function;
551 queue_.back().arg = arg;
553 PthreadCall("unlock", pthread_mutex_unlock(&mu_));
556 void PosixEnv::BGThread() {
558 // Wait until there is an item that is ready to run
559 PthreadCall("lock", pthread_mutex_lock(&mu_));
560 while (queue_.empty()) {
561 PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
564 void (*function)(void*) = queue_.front().function;
565 void* arg = queue_.front().arg;
568 PthreadCall("unlock", pthread_mutex_unlock(&mu_));
574 struct StartThreadState {
575 void (*user_function)(void*);
579 static void* StartThreadWrapper(void* arg) {
580 StartThreadState* state = reinterpret_cast<StartThreadState*>(arg);
581 state->user_function(state->arg);
586 void PosixEnv::StartThread(void (*function)(void* arg), void* arg) {
588 StartThreadState* state = new StartThreadState;
589 state->user_function = function;
591 PthreadCall("start thread",
592 pthread_create(&t, NULL, &StartThreadWrapper, state));
597 static pthread_once_t once = PTHREAD_ONCE_INIT;
598 static Env* default_env;
599 static void InitDefaultEnv() { default_env = new PosixEnv; }
601 Env* Env::Default() {
602 pthread_once(&once, InitDefaultEnv);
606 } // namespace leveldb