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.
16
#include <sys/types.h>
19
#if defined(LEVELDB_PLATFORM_ANDROID)
22
#include "leveldb/env.h"
23
#include "leveldb/slice.h"
24
#include "port/port.h"
25
#include "util/logging.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
class PosixRandomAccessFile: public RandomAccessFile {
71
std::string filename_;
75
PosixRandomAccessFile(const std::string& fname, int fd)
76
: filename_(fname), fd_(fd) { }
77
virtual ~PosixRandomAccessFile() { close(fd_); }
79
virtual Status Read(uint64_t offset, size_t n, Slice* result,
80
char* scratch) const {
82
ssize_t r = pread(fd_, scratch, n, static_cast<off_t>(offset));
83
*result = Slice(scratch, (r < 0) ? 0 : r);
85
// An error: return a non-ok status
86
s = IOError(filename_, errno);
92
// We preallocate up to an extra megabyte and use memcpy to append new
93
// data to the file. This is safe since we either properly close the
94
// file before reading from it, or for log files, the reading code
95
// knows enough to skip zero suffixes.
96
class PosixMmapFile : public WritableFile {
98
std::string filename_;
101
size_t map_size_; // How much extra memory to map at a time
102
char* base_; // The mapped region
103
char* limit_; // Limit of the mapped region
104
char* dst_; // Where to write next (in range [base_,limit_])
105
char* last_sync_; // Where have we synced up to
106
uint64_t file_offset_; // Offset of base_ in file
108
// Have we done an munmap of unsynced data?
111
// Roundup x to a multiple of y
112
static size_t Roundup(size_t x, size_t y) {
113
return ((x + y - 1) / y) * y;
116
size_t TruncateToPageBoundary(size_t s) {
117
s -= (s & (page_size_ - 1));
118
assert((s % page_size_) == 0);
122
bool UnmapCurrentRegion() {
125
if (last_sync_ < limit_) {
126
// Defer syncing this data until next Sync() call, if any
127
pending_sync_ = true;
129
if (munmap(base_, limit_ - base_) != 0) {
132
file_offset_ += limit_ - base_;
138
// Increase the amount we map the next time, but capped at 1MB
139
if (map_size_ < (1<<20)) {
146
bool MapNewRegion() {
147
assert(base_ == NULL);
148
if (ftruncate(fd_, file_offset_ + map_size_) < 0) {
151
void* ptr = mmap(NULL, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED,
153
if (ptr == MAP_FAILED) {
156
base_ = reinterpret_cast<char*>(ptr);
157
limit_ = base_ + map_size_;
164
PosixMmapFile(const std::string& fname, int fd, size_t page_size)
167
page_size_(page_size),
168
map_size_(Roundup(65536, page_size)),
174
pending_sync_(false) {
175
assert((page_size & (page_size - 1)) == 0);
181
PosixMmapFile::Close();
185
virtual Status Append(const Slice& data) {
186
const char* src = data.data();
187
size_t left = data.size();
189
assert(base_ <= dst_);
190
assert(dst_ <= limit_);
191
size_t avail = limit_ - dst_;
193
if (!UnmapCurrentRegion() ||
195
return IOError(filename_, errno);
199
size_t n = (left <= avail) ? left : avail;
200
memcpy(dst_, src, n);
208
virtual Status Close() {
210
size_t unused = limit_ - dst_;
211
if (!UnmapCurrentRegion()) {
212
s = IOError(filename_, errno);
213
} else if (unused > 0) {
214
// Trim the extra space at the end of the file
215
if (ftruncate(fd_, file_offset_ - unused) < 0) {
216
s = IOError(filename_, errno);
220
if (close(fd_) < 0) {
222
s = IOError(filename_, errno);
232
virtual Status Flush() {
236
virtual Status Sync() {
240
// Some unmapped data was not synced
241
pending_sync_ = false;
242
if (fdatasync(fd_) < 0) {
243
s = IOError(filename_, errno);
247
if (dst_ > last_sync_) {
248
// Find the beginnings of the pages that contain the first and last
249
// bytes to be synced.
250
size_t p1 = TruncateToPageBoundary(last_sync_ - base_);
251
size_t p2 = TruncateToPageBoundary(dst_ - base_ - 1);
253
if (msync(base_ + p1, p2 - p1 + page_size_, MS_SYNC) < 0) {
254
s = IOError(filename_, errno);
262
static int LockOrUnlock(int fd, bool lock) {
265
memset(&f, 0, sizeof(f));
266
f.l_type = (lock ? F_WRLCK : F_UNLCK);
267
f.l_whence = SEEK_SET;
269
f.l_len = 0; // Lock/unlock entire file
270
return fcntl(fd, F_SETLK, &f);
273
class PosixFileLock : public FileLock {
278
class PosixEnv : public Env {
281
virtual ~PosixEnv() {
282
fprintf(stderr, "Destroying Env::Default()\n");
286
virtual Status NewSequentialFile(const std::string& fname,
287
SequentialFile** result) {
288
FILE* f = fopen(fname.c_str(), "r");
291
return IOError(fname, errno);
293
*result = new PosixSequentialFile(fname, f);
298
virtual Status NewRandomAccessFile(const std::string& fname,
299
RandomAccessFile** result) {
300
int fd = open(fname.c_str(), O_RDONLY);
303
return IOError(fname, errno);
305
*result = new PosixRandomAccessFile(fname, fd);
309
virtual Status NewWritableFile(const std::string& fname,
310
WritableFile** result) {
312
const int fd = open(fname.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0644);
315
s = IOError(fname, errno);
317
*result = new PosixMmapFile(fname, fd, page_size_);
322
virtual bool FileExists(const std::string& fname) {
323
return access(fname.c_str(), F_OK) == 0;
326
virtual Status GetChildren(const std::string& dir,
327
std::vector<std::string>* result) {
329
DIR* d = opendir(dir.c_str());
331
return IOError(dir, errno);
333
struct dirent* entry;
334
while ((entry = readdir(d)) != NULL) {
335
result->push_back(entry->d_name);
341
virtual Status DeleteFile(const std::string& fname) {
343
if (unlink(fname.c_str()) != 0) {
344
result = IOError(fname, errno);
349
virtual Status CreateDir(const std::string& name) {
351
if (mkdir(name.c_str(), 0755) != 0) {
352
result = IOError(name, errno);
357
virtual Status DeleteDir(const std::string& name) {
359
if (rmdir(name.c_str()) != 0) {
360
result = IOError(name, errno);
365
virtual Status GetFileSize(const std::string& fname, uint64_t* size) {
368
if (stat(fname.c_str(), &sbuf) != 0) {
370
s = IOError(fname, errno);
372
*size = sbuf.st_size;
377
virtual Status RenameFile(const std::string& src, const std::string& target) {
379
if (rename(src.c_str(), target.c_str()) != 0) {
380
result = IOError(src, errno);
385
virtual Status LockFile(const std::string& fname, FileLock** lock) {
388
int fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
390
result = IOError(fname, errno);
391
} else if (LockOrUnlock(fd, true) == -1) {
392
result = IOError("lock " + fname, errno);
395
PosixFileLock* my_lock = new PosixFileLock;
402
virtual Status UnlockFile(FileLock* lock) {
403
PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
405
if (LockOrUnlock(my_lock->fd_, false) == -1) {
406
result = IOError("unlock", errno);
413
virtual void Schedule(void (*function)(void*), void* arg);
415
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') {
423
snprintf(buf, sizeof(buf), "/tmp/leveldbtest-%d", int(geteuid()));
426
// Directory may already exist
431
static uint64_t gettid() {
432
pthread_t tid = pthread_self();
433
uint64_t thread_id = 0;
434
memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
438
virtual Status NewLogger(const std::string& fname, Logger** result) {
439
FILE* f = fopen(fname.c_str(), "w");
442
return IOError(fname, errno);
444
*result = new PosixLogger(f, &PosixEnv::gettid);
449
virtual uint64_t NowMicros() {
451
gettimeofday(&tv, NULL);
452
return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
455
virtual void SleepForMicroseconds(int micros) {
460
void PthreadCall(const char* label, int result) {
462
fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
467
// BGThread() is the body of the background thread
469
static void* BGThreadWrapper(void* arg) {
470
reinterpret_cast<PosixEnv*>(arg)->BGThread();
476
pthread_cond_t bgsignal_;
478
bool started_bgthread_;
480
// Entry per Schedule() call
481
struct BGItem { void* arg; void (*function)(void*); };
482
typedef std::deque<BGItem> BGQueue;
486
PosixEnv::PosixEnv() : page_size_(getpagesize()),
487
started_bgthread_(false) {
488
PthreadCall("mutex_init", pthread_mutex_init(&mu_, NULL));
489
PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, NULL));
492
void PosixEnv::Schedule(void (*function)(void*), void* arg) {
493
PthreadCall("lock", pthread_mutex_lock(&mu_));
495
// Start background thread if necessary
496
if (!started_bgthread_) {
497
started_bgthread_ = true;
500
pthread_create(&bgthread_, NULL, &PosixEnv::BGThreadWrapper, this));
503
// If the queue is currently empty, the background thread may currently be
505
if (queue_.empty()) {
506
PthreadCall("signal", pthread_cond_signal(&bgsignal_));
509
// Add to priority queue
510
queue_.push_back(BGItem());
511
queue_.back().function = function;
512
queue_.back().arg = arg;
514
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
517
void PosixEnv::BGThread() {
519
// Wait until there is an item that is ready to run
520
PthreadCall("lock", pthread_mutex_lock(&mu_));
521
while (queue_.empty()) {
522
PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
525
void (*function)(void*) = queue_.front().function;
526
void* arg = queue_.front().arg;
529
PthreadCall("unlock", pthread_mutex_unlock(&mu_));
535
struct StartThreadState {
536
void (*user_function)(void*);
540
static void* StartThreadWrapper(void* arg) {
541
StartThreadState* state = reinterpret_cast<StartThreadState*>(arg);
542
state->user_function(state->arg);
547
void PosixEnv::StartThread(void (*function)(void* arg), void* arg) {
549
StartThreadState* state = new StartThreadState;
550
state->user_function = function;
552
PthreadCall("start thread",
553
pthread_create(&t, NULL, &StartThreadWrapper, state));
558
static pthread_once_t once = PTHREAD_ONCE_INIT;
559
static Env* default_env;
560
static void InitDefaultEnv() { default_env = new PosixEnv; }
562
Env* Env::Default() {
563
pthread_once(&once, InitDefaultEnv);
567
} // namespace leveldb