env_posix.cc 56.2 KB
Newer Older
1 2 3 4 5
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
J
jorlow@chromium.org 已提交
6 7 8 9 10
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include <deque>
11
#include <set>
J
jorlow@chromium.org 已提交
12 13 14 15 16 17 18
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
19
#include <sys/ioctl.h>
J
jorlow@chromium.org 已提交
20 21
#include <sys/mman.h>
#include <sys/stat.h>
K
kailiu 已提交
22
#ifdef OS_LINUX
A
Abhishek Kona 已提交
23
#include <sys/statfs.h>
24
#include <sys/syscall.h>
K
kailiu 已提交
25
#endif
J
jorlow@chromium.org 已提交
26 27 28 29
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
30 31
#if defined(OS_LINUX)
#include <linux/fs.h>
J
jorlow@chromium.org 已提交
32
#endif
L
Lei Jin 已提交
33 34
#include <signal.h>
#include <algorithm>
35 36
#include "rocksdb/env.h"
#include "rocksdb/slice.h"
J
jorlow@chromium.org 已提交
37
#include "port/port.h"
38
#include "util/coding.h"
J
jorlow@chromium.org 已提交
39
#include "util/logging.h"
40
#include "util/posix_logger.h"
41
#include "util/random.h"
42
#include "util/iostats_context_imp.h"
L
Lei Jin 已提交
43
#include "util/rate_limiter.h"
44
#include "util/sync_point.h"
45 46
#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"
J
jorlow@chromium.org 已提交
47

I
Islam AbdelRahman 已提交
48 49 50
// Get nano time includes
#if defined(OS_LINUX) || defined(OS_FREEBSD)
#elif defined(__MACH__)
K
kailiu 已提交
51 52
#include <mach/clock.h>
#include <mach/mach.h>
I
Islam AbdelRahman 已提交
53 54
#else
#include <chrono>
K
kailiu 已提交
55 56
#endif

A
Abhishek Kona 已提交
57 58 59 60 61 62 63 64 65 66
#if !defined(TMPFS_MAGIC)
#define TMPFS_MAGIC 0x01021994
#endif
#if !defined(XFS_SUPER_MAGIC)
#define XFS_SUPER_MAGIC 0x58465342
#endif
#if !defined(EXT4_SUPER_MAGIC)
#define EXT4_SUPER_MAGIC 0xEF53
#endif

K
kailiu 已提交
67 68
// For non linux platform, the following macros are used only as place
// holder.
S
sdong 已提交
69
#if !(defined OS_LINUX) && !(defined CYGWIN)
K
kailiu 已提交
70 71 72 73 74 75 76
#define POSIX_FADV_NORMAL 0 /* [MC1] no further special treatment */
#define POSIX_FADV_RANDOM 1 /* [MC1] expect random page refs */
#define POSIX_FADV_SEQUENTIAL 2 /* [MC1] expect sequential page refs */
#define POSIX_FADV_WILLNEED 3 /* [MC1] will need these pages */
#define POSIX_FADV_DONTNEED 4 /* [MC1] dont need these pages */
#endif

77 78
// This is only set from db_stress.cc and for testing only.
// If non-zero, kill at various points in source code with probability 1/this
79
int rocksdb_kill_odds = 0;
80

81
namespace rocksdb {
J
jorlow@chromium.org 已提交
82 83 84

namespace {

K
kailiu 已提交
85 86 87 88 89 90 91 92 93 94
// A wrapper for fadvise, if the platform doesn't support fadvise,
// it will simply return Status::NotSupport.
int Fadvise(int fd, off_t offset, size_t len, int advice) {
#ifdef OS_LINUX
  return posix_fadvise(fd, offset, len, advice);
#else
  return 0;  // simply do nothing.
#endif
}

95 96 97 98
ThreadStatusUpdater* CreateThreadStatusUpdater() {
  return new ThreadStatusUpdater();
}

99 100 101 102
// list of pathnames that are locked
static std::set<std::string> lockedFiles;
static port::Mutex mutex_lockedFiles;

103 104 105 106
static Status IOError(const std::string& context, int err_number) {
  return Status::IOError(context, strerror(err_number));
}

107 108
#ifdef NDEBUG
// empty in release build
109
#define TEST_KILL_RANDOM(rocksdb_kill_odds)
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
#else

// Kill the process with probablity 1/odds for testing.
static void TestKillRandom(int odds, const std::string& srcfile,
                           int srcline) {
  time_t curtime = time(nullptr);
  Random r((uint32_t)curtime);

  assert(odds > 0);
  bool crash = r.OneIn(odds);
  if (crash) {
    fprintf(stdout, "Crashing at %s:%d\n", srcfile.c_str(), srcline);
    fflush(stdout);
    kill(getpid(), SIGTERM);
  }
}

// To avoid crashing always at some frequently executed codepaths (during
// kill random test), use this factor to reduce odds
#define REDUCE_ODDS 2
#define REDUCE_ODDS2 4

132 133 134
#define TEST_KILL_RANDOM(rocksdb_kill_odds) {   \
  if (rocksdb_kill_odds > 0) { \
    TestKillRandom(rocksdb_kill_odds, __FILE__, __LINE__);     \
135 136 137 138 139
  } \
}

#endif

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
#if defined(OS_LINUX)
namespace {
  static size_t GetUniqueIdFromFile(int fd, char* id, size_t max_size) {
    if (max_size < kMaxVarint64Length*3) {
      return 0;
    }

    struct stat buf;
    int result = fstat(fd, &buf);
    if (result == -1) {
      return 0;
    }

    long version = 0;
    result = ioctl(fd, FS_IOC_GETVERSION, &version);
    if (result == -1) {
      return 0;
    }
    uint64_t uversion = (uint64_t)version;

    char* rid = id;
    rid = EncodeVarint64(rid, buf.st_dev);
    rid = EncodeVarint64(rid, buf.st_ino);
    rid = EncodeVarint64(rid, uversion);
    assert(rid >= id);
    return static_cast<size_t>(rid-id);
  }
}
#endif

J
jorlow@chromium.org 已提交
170 171 172 173
class PosixSequentialFile: public SequentialFile {
 private:
  std::string filename_;
  FILE* file_;
174
  int fd_;
175
  bool use_os_buffer_;
J
jorlow@chromium.org 已提交
176 177

 public:
178 179
  PosixSequentialFile(const std::string& fname, FILE* f,
      const EnvOptions& options)
180
      : filename_(fname), file_(f), fd_(fileno(f)),
H
Haobo Xu 已提交
181
        use_os_buffer_(options.use_os_buffer) {
182
  }
J
jorlow@chromium.org 已提交
183 184
  virtual ~PosixSequentialFile() { fclose(file_); }

I
Igor Sugak 已提交
185
  virtual Status Read(size_t n, Slice* result, char* scratch) override {
J
jorlow@chromium.org 已提交
186
    Status s;
187
    size_t r = 0;
I
Igor Canadi 已提交
188
    do {
S
sdong 已提交
189
#ifndef CYGWIN
I
Igor Canadi 已提交
190
      r = fread_unlocked(scratch, 1, n, file_);
S
sdong 已提交
191 192 193
#else
      r = fread(scratch, 1, n, file_);
#endif
194
    } while (r == 0 && ferror(file_) && errno == EINTR);
195
    IOSTATS_ADD(bytes_read, r);
J
jorlow@chromium.org 已提交
196 197 198 199
    *result = Slice(scratch, r);
    if (r < n) {
      if (feof(file_)) {
        // We leave status as ok if we hit the end of the file
200 201 202
        // We also clear the error so that the reads can continue
        // if a new data is written to the file
        clearerr(file_);
J
jorlow@chromium.org 已提交
203 204
      } else {
        // A partial read with an error: return a non-ok status
205
        s = IOError(filename_, errno);
J
jorlow@chromium.org 已提交
206 207
      }
    }
208
    if (!use_os_buffer_) {
209 210
      // we need to fadvise away the entire range of pages because
      // we do not want readahead pages to be cached.
K
kailiu 已提交
211
      Fadvise(fd_, 0, 0, POSIX_FADV_DONTNEED); // free OS pages
212
    }
J
jorlow@chromium.org 已提交
213 214
    return s;
  }
215

I
Igor Sugak 已提交
216
  virtual Status Skip(uint64_t n) override {
217
    if (fseek(file_, static_cast<long int>(n), SEEK_CUR)) {
218
      return IOError(filename_, errno);
219 220 221
    }
    return Status::OK();
  }
222

I
Igor Sugak 已提交
223
  virtual Status InvalidateCache(size_t offset, size_t length) override {
K
kailiu 已提交
224 225 226
#ifndef OS_LINUX
    return Status::OK();
#else
227
    // free OS pages
K
kailiu 已提交
228
    int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
229 230 231 232
    if (ret == 0) {
      return Status::OK();
    }
    return IOError(filename_, errno);
K
kailiu 已提交
233
#endif
234
  }
J
jorlow@chromium.org 已提交
235 236
};

237
// pread() based random-access
J
jorlow@chromium.org 已提交
238 239 240 241
class PosixRandomAccessFile: public RandomAccessFile {
 private:
  std::string filename_;
  int fd_;
242
  bool use_os_buffer_;
J
jorlow@chromium.org 已提交
243 244

 public:
245 246
  PosixRandomAccessFile(const std::string& fname, int fd,
                        const EnvOptions& options)
H
Haobo Xu 已提交
247
      : filename_(fname), fd_(fd), use_os_buffer_(options.use_os_buffer) {
248
    assert(!options.use_mmap_reads || sizeof(void*) < 8);
249
  }
J
jorlow@chromium.org 已提交
250 251 252
  virtual ~PosixRandomAccessFile() { close(fd_); }

  virtual Status Read(uint64_t offset, size_t n, Slice* result,
I
Igor Sugak 已提交
253
                      char* scratch) const override {
J
jorlow@chromium.org 已提交
254
    Status s;
I
Igor Canadi 已提交
255
    ssize_t r = -1;
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    size_t left = n;
    char* ptr = scratch;
    while (left > 0) {
      r = pread(fd_, ptr, left, static_cast<off_t>(offset));
      if (r <= 0) {
        if (errno == EINTR) {
          continue;
        }
        break;
      }
      ptr += r;
      offset += r;
      left -= r;
    }

    IOSTATS_ADD_IF_POSITIVE(bytes_read, n - left);
    *result = Slice(scratch, (r < 0) ? 0 : n - left);
J
jorlow@chromium.org 已提交
273 274
    if (r < 0) {
      // An error: return a non-ok status
275
      s = IOError(filename_, errno);
J
jorlow@chromium.org 已提交
276
    }
277
    if (!use_os_buffer_) {
278 279
      // we need to fadvise away the entire range of pages because
      // we do not want readahead pages to be cached.
K
kailiu 已提交
280
      Fadvise(fd_, 0, 0, POSIX_FADV_DONTNEED); // free OS pages
281
    }
J
jorlow@chromium.org 已提交
282 283
    return s;
  }
284

K
kailiu 已提交
285
#ifdef OS_LINUX
I
Igor Sugak 已提交
286
  virtual size_t GetUniqueId(char* id, size_t max_size) const override {
287
    return GetUniqueIdFromFile(fd_, id, max_size);
288 289
  }
#endif
290

I
Igor Sugak 已提交
291
  virtual void Hint(AccessPattern pattern) override {
292 293
    switch(pattern) {
      case NORMAL:
K
kailiu 已提交
294
        Fadvise(fd_, 0, 0, POSIX_FADV_NORMAL);
295 296
        break;
      case RANDOM:
K
kailiu 已提交
297
        Fadvise(fd_, 0, 0, POSIX_FADV_RANDOM);
298 299
        break;
      case SEQUENTIAL:
K
kailiu 已提交
300
        Fadvise(fd_, 0, 0, POSIX_FADV_SEQUENTIAL);
301 302
        break;
      case WILLNEED:
K
kailiu 已提交
303
        Fadvise(fd_, 0, 0, POSIX_FADV_WILLNEED);
304 305
        break;
      case DONTNEED:
K
kailiu 已提交
306
        Fadvise(fd_, 0, 0, POSIX_FADV_DONTNEED);
307 308 309 310 311 312 313
        break;
      default:
        assert(false);
        break;
    }
  }

I
Igor Sugak 已提交
314
  virtual Status InvalidateCache(size_t offset, size_t length) override {
K
kailiu 已提交
315 316 317
#ifndef OS_LINUX
    return Status::OK();
#else
318
    // free OS pages
K
kailiu 已提交
319
    int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
320 321 322 323
    if (ret == 0) {
      return Status::OK();
    }
    return IOError(filename_, errno);
K
kailiu 已提交
324
#endif
325
  }
J
jorlow@chromium.org 已提交
326 327
};

328 329 330
// mmap() based random-access
class PosixMmapReadableFile: public RandomAccessFile {
 private:
331
  int fd_;
332 333 334 335 336 337
  std::string filename_;
  void* mmapped_region_;
  size_t length_;

 public:
  // base[0,length-1] contains the mmapped contents of the file.
338 339
  PosixMmapReadableFile(const int fd, const std::string& fname,
                        void* base, size_t length,
340
                        const EnvOptions& options)
341
      : fd_(fd), filename_(fname), mmapped_region_(base), length_(length) {
K
kailiu 已提交
342
    fd_ = fd_ + 0;  // suppress the warning for used variables
H
Haobo Xu 已提交
343 344
    assert(options.use_mmap_reads);
    assert(options.use_os_buffer);
345
  }
S
Siying Dong 已提交
346
  virtual ~PosixMmapReadableFile() {
347 348 349 350 351
    int ret = munmap(mmapped_region_, length_);
    if (ret != 0) {
      fprintf(stdout, "failed to munmap %p length %zu \n",
              mmapped_region_, length_);
    }
S
Siying Dong 已提交
352
  }
353 354

  virtual Status Read(uint64_t offset, size_t n, Slice* result,
I
Igor Sugak 已提交
355
                      char* scratch) const override {
356 357 358 359 360 361 362 363 364
    Status s;
    if (offset + n > length_) {
      *result = Slice();
      s = IOError(filename_, EINVAL);
    } else {
      *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
    }
    return s;
  }
I
Igor Sugak 已提交
365
  virtual Status InvalidateCache(size_t offset, size_t length) override {
K
kailiu 已提交
366 367 368
#ifndef OS_LINUX
    return Status::OK();
#else
369
    // free OS pages
K
kailiu 已提交
370
    int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
371 372 373 374
    if (ret == 0) {
      return Status::OK();
    }
    return IOError(filename_, errno);
K
kailiu 已提交
375
#endif
376
  }
377 378
};

J
jorlow@chromium.org 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
// We preallocate up to an extra megabyte and use memcpy to append new
// data to the file.  This is safe since we either properly close the
// file before reading from it, or for log files, the reading code
// knows enough to skip zero suffixes.
class PosixMmapFile : public WritableFile {
 private:
  std::string filename_;
  int fd_;
  size_t page_size_;
  size_t map_size_;       // How much extra memory to map at a time
  char* base_;            // The mapped region
  char* limit_;           // Limit of the mapped region
  char* dst_;             // Where to write next  (in range [base_,limit_])
  char* last_sync_;       // Where have we synced up to
  uint64_t file_offset_;  // Offset of base_ in file
  // Have we done an munmap of unsynced data?
  bool pending_sync_;
I
Igor Canadi 已提交
396
#ifdef ROCKSDB_FALLOCATE_PRESENT
I
Igor Canadi 已提交
397
  bool fallocate_with_keep_size_;
I
Igor Canadi 已提交
398
#endif
J
jorlow@chromium.org 已提交
399 400 401 402 403 404 405 406 407 408 409 410

  // Roundup x to a multiple of y
  static size_t Roundup(size_t x, size_t y) {
    return ((x + y - 1) / y) * y;
  }

  size_t TruncateToPageBoundary(size_t s) {
    s -= (s & (page_size_ - 1));
    assert((s % page_size_) == 0);
    return s;
  }

411
  Status UnmapCurrentRegion() {
412
    TEST_KILL_RANDOM(rocksdb_kill_odds);
A
Abhishek Kona 已提交
413
    if (base_ != nullptr) {
J
jorlow@chromium.org 已提交
414 415 416 417
      if (last_sync_ < limit_) {
        // Defer syncing this data until next Sync() call, if any
        pending_sync_ = true;
      }
418 419 420
      int munmap_status = munmap(base_, limit_ - base_);
      if (munmap_status != 0) {
        return IOError(filename_, munmap_status);
421
      }
J
jorlow@chromium.org 已提交
422
      file_offset_ += limit_ - base_;
A
Abhishek Kona 已提交
423 424 425 426
      base_ = nullptr;
      limit_ = nullptr;
      last_sync_ = nullptr;
      dst_ = nullptr;
J
jorlow@chromium.org 已提交
427 428 429 430 431 432

      // Increase the amount we map the next time, but capped at 1MB
      if (map_size_ < (1<<20)) {
        map_size_ *= 2;
      }
    }
433
    return Status::OK();
J
jorlow@chromium.org 已提交
434 435
  }

A
Abhishek Kona 已提交
436
  Status MapNewRegion() {
437
#ifdef ROCKSDB_FALLOCATE_PRESENT
A
Abhishek Kona 已提交
438
    assert(base_ == nullptr);
A
Abhishek Kona 已提交
439

440
    TEST_KILL_RANDOM(rocksdb_kill_odds);
I
Igor Canadi 已提交
441
    // we can't fallocate with FALLOC_FL_KEEP_SIZE here
442 443 444 445 446 447 448 449 450 451 452
    {
      IOSTATS_TIMER_GUARD(allocate_nanos);
      int alloc_status = fallocate(fd_, 0, file_offset_, map_size_);
      if (alloc_status != 0) {
        // fallback to posix_fallocate
        alloc_status = posix_fallocate(fd_, file_offset_, map_size_);
      }
      if (alloc_status != 0) {
        return Status::IOError("Error allocating space to file : " + filename_ +
          "Error : " + strerror(alloc_status));
      }
J
jorlow@chromium.org 已提交
453
    }
A
Abhishek Kona 已提交
454

455
    TEST_KILL_RANDOM(rocksdb_kill_odds);
A
Abhishek Kona 已提交
456
    void* ptr = mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED,
J
jorlow@chromium.org 已提交
457 458
                     fd_, file_offset_);
    if (ptr == MAP_FAILED) {
A
Abhishek Kona 已提交
459
      return Status::IOError("MMap failed on " + filename_);
J
jorlow@chromium.org 已提交
460
    }
461

462
    TEST_KILL_RANDOM(rocksdb_kill_odds);
463

J
jorlow@chromium.org 已提交
464 465 466 467
    base_ = reinterpret_cast<char*>(ptr);
    limit_ = base_ + map_size_;
    dst_ = base_;
    last_sync_ = base_;
A
Abhishek Kona 已提交
468
    return Status::OK();
K
kailiu 已提交
469 470 471
#else
    return Status::NotSupported("This platform doesn't support fallocate()");
#endif
J
jorlow@chromium.org 已提交
472 473 474
  }

 public:
475 476
  PosixMmapFile(const std::string& fname, int fd, size_t page_size,
                const EnvOptions& options)
J
jorlow@chromium.org 已提交
477 478 479 480
      : filename_(fname),
        fd_(fd),
        page_size_(page_size),
        map_size_(Roundup(65536, page_size)),
A
Abhishek Kona 已提交
481 482 483 484
        base_(nullptr),
        limit_(nullptr),
        dst_(nullptr),
        last_sync_(nullptr),
J
jorlow@chromium.org 已提交
485
        file_offset_(0),
I
Igor Canadi 已提交
486 487 488 489
        pending_sync_(false) {
#ifdef ROCKSDB_FALLOCATE_PRESENT
    fallocate_with_keep_size_ = options.fallocate_with_keep_size;
#endif
J
jorlow@chromium.org 已提交
490
    assert((page_size & (page_size - 1)) == 0);
H
Haobo Xu 已提交
491
    assert(options.use_mmap_writes);
J
jorlow@chromium.org 已提交
492 493 494 495 496 497 498 499 500
  }


  ~PosixMmapFile() {
    if (fd_ >= 0) {
      PosixMmapFile::Close();
    }
  }

I
Igor Sugak 已提交
501
  virtual Status Append(const Slice& data) override {
J
jorlow@chromium.org 已提交
502 503
    const char* src = data.data();
    size_t left = data.size();
504
    TEST_KILL_RANDOM(rocksdb_kill_odds * REDUCE_ODDS);
505
    PrepareWrite(static_cast<size_t>(GetFileSize()), left);
J
jorlow@chromium.org 已提交
506 507 508 509 510
    while (left > 0) {
      assert(base_ <= dst_);
      assert(dst_ <= limit_);
      size_t avail = limit_ - dst_;
      if (avail == 0) {
511 512 513 514 515 516 517
        Status s = UnmapCurrentRegion();
        if (!s.ok()) {
          return s;
        }
        s = MapNewRegion();
        if (!s.ok()) {
          return s;
518
        }
519
        TEST_KILL_RANDOM(rocksdb_kill_odds);
J
jorlow@chromium.org 已提交
520 521 522 523
      }

      size_t n = (left <= avail) ? left : avail;
      memcpy(dst_, src, n);
524
      IOSTATS_ADD(bytes_written, n);
J
jorlow@chromium.org 已提交
525 526 527 528
      dst_ += n;
      src += n;
      left -= n;
    }
529
    TEST_KILL_RANDOM(rocksdb_kill_odds);
J
jorlow@chromium.org 已提交
530 531 532
    return Status::OK();
  }

I
Igor Sugak 已提交
533
  virtual Status Close() override {
J
jorlow@chromium.org 已提交
534 535
    Status s;
    size_t unused = limit_ - dst_;
536

537
    TEST_KILL_RANDOM(rocksdb_kill_odds);
538

539 540
    s = UnmapCurrentRegion();
    if (!s.ok()) {
541 542
      s = IOError(filename_, errno);
    } else if (unused > 0) {
J
jorlow@chromium.org 已提交
543 544
      // Trim the extra space at the end of the file
      if (ftruncate(fd_, file_offset_ - unused) < 0) {
545
        s = IOError(filename_, errno);
J
jorlow@chromium.org 已提交
546 547 548
      }
    }

549
    TEST_KILL_RANDOM(rocksdb_kill_odds);
550

J
jorlow@chromium.org 已提交
551 552
    if (close(fd_) < 0) {
      if (s.ok()) {
553
        s = IOError(filename_, errno);
J
jorlow@chromium.org 已提交
554 555 556 557
      }
    }

    fd_ = -1;
A
Abhishek Kona 已提交
558 559
    base_ = nullptr;
    limit_ = nullptr;
J
jorlow@chromium.org 已提交
560 561 562
    return s;
  }

I
Igor Sugak 已提交
563
  virtual Status Flush() override {
564
    TEST_KILL_RANDOM(rocksdb_kill_odds);
J
jorlow@chromium.org 已提交
565 566 567
    return Status::OK();
  }

I
Igor Sugak 已提交
568
  virtual Status Sync() override {
J
jorlow@chromium.org 已提交
569 570 571 572
    Status s;

    if (pending_sync_) {
      // Some unmapped data was not synced
573
      TEST_KILL_RANDOM(rocksdb_kill_odds);
J
jorlow@chromium.org 已提交
574 575
      pending_sync_ = false;
      if (fdatasync(fd_) < 0) {
576
        s = IOError(filename_, errno);
J
jorlow@chromium.org 已提交
577
      }
578
      TEST_KILL_RANDOM(rocksdb_kill_odds * REDUCE_ODDS);
J
jorlow@chromium.org 已提交
579 580 581 582 583 584 585 586
    }

    if (dst_ > last_sync_) {
      // Find the beginnings of the pages that contain the first and last
      // bytes to be synced.
      size_t p1 = TruncateToPageBoundary(last_sync_ - base_);
      size_t p2 = TruncateToPageBoundary(dst_ - base_ - 1);
      last_sync_ = dst_;
587
      TEST_KILL_RANDOM(rocksdb_kill_odds);
J
jorlow@chromium.org 已提交
588
      if (msync(base_ + p1, p2 - p1 + page_size_, MS_SYNC) < 0) {
589
        s = IOError(filename_, errno);
J
jorlow@chromium.org 已提交
590
      }
591
      TEST_KILL_RANDOM(rocksdb_kill_odds);
J
jorlow@chromium.org 已提交
592 593 594 595
    }

    return s;
  }
596 597 598 599

  /**
   * Flush data as well as metadata to stable storage.
   */
I
Igor Sugak 已提交
600
  virtual Status Fsync() override {
601 602
    if (pending_sync_) {
      // Some unmapped data was not synced
603
      TEST_KILL_RANDOM(rocksdb_kill_odds);
604 605 606 607
      pending_sync_ = false;
      if (fsync(fd_) < 0) {
        return IOError(filename_, errno);
      }
608
      TEST_KILL_RANDOM(rocksdb_kill_odds);
609 610 611 612 613
    }
    // This invocation to Sync will not issue the call to
    // fdatasync because pending_sync_ has already been cleared.
    return Sync();
  }
614 615 616 617 618 619

  /**
   * Get the size of valid data in the file. This will not match the
   * size that is returned from the filesystem because we use mmap
   * to extend file by map_size every time.
   */
I
Igor Sugak 已提交
620
  virtual uint64_t GetFileSize() override {
621 622 623
    size_t used = dst_ - base_;
    return file_offset_ + used;
  }
624

I
Igor Sugak 已提交
625
  virtual Status InvalidateCache(size_t offset, size_t length) override {
K
kailiu 已提交
626 627 628
#ifndef OS_LINUX
    return Status::OK();
#else
629
    // free OS pages
K
kailiu 已提交
630
    int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
631 632 633 634
    if (ret == 0) {
      return Status::OK();
    }
    return IOError(filename_, errno);
K
kailiu 已提交
635
#endif
636 637
  }

638
#ifdef ROCKSDB_FALLOCATE_PRESENT
I
Igor Sugak 已提交
639
  virtual Status Allocate(off_t offset, off_t len) override {
640
    TEST_KILL_RANDOM(rocksdb_kill_odds);
641
    IOSTATS_TIMER_GUARD(allocate_nanos);
I
Igor Canadi 已提交
642 643 644
    int alloc_status = fallocate(
        fd_, fallocate_with_keep_size_ ? FALLOC_FL_KEEP_SIZE : 0, offset, len);
    if (alloc_status == 0) {
645 646 647 648 649
      return Status::OK();
    } else {
      return IOError(filename_, errno);
    }
  }
650
#endif
J
jorlow@chromium.org 已提交
651 652
};

653 654 655 656 657 658 659
// Use posix write to write data to a file.
class PosixWritableFile : public WritableFile {
 private:
  const std::string filename_;
  int fd_;
  size_t cursize_;      // current size of cached data in buf_
  size_t capacity_;     // max size of buf_
M
Mayank Agarwal 已提交
660
  unique_ptr<char[]> buf_;           // a buffer to cache writes
661 662 663
  uint64_t filesize_;
  bool pending_sync_;
  bool pending_fsync_;
664
  uint64_t last_sync_size_;
H
Haobo Xu 已提交
665
  uint64_t bytes_per_sync_;
I
Igor Canadi 已提交
666
#ifdef ROCKSDB_FALLOCATE_PRESENT
I
Igor Canadi 已提交
667
  bool fallocate_with_keep_size_;
I
Igor Canadi 已提交
668
#endif
L
Lei Jin 已提交
669
  RateLimiter* rate_limiter_;
670 671

 public:
672
  PosixWritableFile(const std::string& fname, int fd, size_t capacity,
I
Igor Canadi 已提交
673 674 675 676 677 678 679 680 681 682
                    const EnvOptions& options)
      : filename_(fname),
        fd_(fd),
        cursize_(0),
        capacity_(capacity),
        buf_(new char[capacity]),
        filesize_(0),
        pending_sync_(false),
        pending_fsync_(false),
        last_sync_size_(0),
L
Lei Jin 已提交
683 684
        bytes_per_sync_(options.bytes_per_sync),
        rate_limiter_(options.rate_limiter) {
I
Igor Canadi 已提交
685 686 687
#ifdef ROCKSDB_FALLOCATE_PRESENT
    fallocate_with_keep_size_ = options.fallocate_with_keep_size;
#endif
H
Haobo Xu 已提交
688
    assert(!options.use_mmap_writes);
689 690 691 692 693 694 695 696
  }

  ~PosixWritableFile() {
    if (fd_ >= 0) {
      PosixWritableFile::Close();
    }
  }

I
Igor Sugak 已提交
697
  virtual Status Append(const Slice& data) override {
698
    const char* src = data.data();
699 700 701 702 703
    size_t left = data.size();
    Status s;
    pending_sync_ = true;
    pending_fsync_ = true;

704
    TEST_KILL_RANDOM(rocksdb_kill_odds * REDUCE_ODDS2);
705

706
    PrepareWrite(static_cast<size_t>(GetFileSize()), left);
707 708 709 710 711 712 713 714 715
    // if there is no space in the cache, then flush
    if (cursize_ + left > capacity_) {
      s = Flush();
      if (!s.ok()) {
        return s;
      }
      // Increase the buffer size, but capped at 1MB
      if (capacity_ < (1<<20)) {
        capacity_ *= 2;
M
Mayank Agarwal 已提交
716
        buf_.reset(new char[capacity_]);
717 718 719 720 721 722 723
      }
      assert(cursize_ == 0);
    }

    // if the write fits into the cache, then write to cache
    // otherwise do a write() syscall to write to OS buffers.
    if (cursize_ + left <= capacity_) {
M
Mayank Agarwal 已提交
724
      memcpy(buf_.get()+cursize_, src, left);
725 726 727
      cursize_ += left;
    } else {
      while (left != 0) {
728 729 730 731 732 733
        ssize_t done;
        size_t size = RequestToken(left);
        {
          IOSTATS_TIMER_GUARD(write_nanos);
          done = write(fd_, src, size);
        }
734
        if (done < 0) {
I
Igor Canadi 已提交
735 736 737
          if (errno == EINTR) {
            continue;
          }
738 739
          return IOError(filename_, errno);
        }
740
        IOSTATS_ADD(bytes_written, done);
741
        TEST_KILL_RANDOM(rocksdb_kill_odds);
742

743 744 745 746 747 748 749 750
        left -= done;
        src += done;
      }
    }
    filesize_ += data.size();
    return Status::OK();
  }

I
Igor Sugak 已提交
751
  virtual Status Close() override {
752 753 754
    Status s;
    s = Flush(); // flush cache to OS
    if (!s.ok()) {
755
      return s;
756
    }
757

758
    TEST_KILL_RANDOM(rocksdb_kill_odds);
759

760 761 762 763 764
    size_t block_size;
    size_t last_allocated_block;
    GetPreallocationStatus(&block_size, &last_allocated_block);
    if (last_allocated_block > 0) {
      // trim the extra space preallocated at the end of the file
765 766
      // NOTE(ljin): we probably don't want to surface failure as an IOError,
      // but it will be nice to log these errors.
767 768
      int dummy __attribute__((unused));
      dummy = ftruncate(fd_, filesize_);
769 770 771 772 773 774 775 776 777 778 779 780
#ifdef ROCKSDB_FALLOCATE_PRESENT
      // in some file systems, ftruncate only trims trailing space if the
      // new file size is smaller than the current size. Calling fallocate
      // with FALLOC_FL_PUNCH_HOLE flag to explicitly release these unused
      // blocks. FALLOC_FL_PUNCH_HOLE is supported on at least the following
      // filesystems:
      //   XFS (since Linux 2.6.38)
      //   ext4 (since Linux 3.0)
      //   Btrfs (since Linux 3.7)
      //   tmpfs (since Linux 3.5)
      // We ignore error since failure of this operation does not affect
      // correctness.
781
      IOSTATS_TIMER_GUARD(allocate_nanos);
782 783 784
      fallocate(fd_, FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE,
                filesize_, block_size * last_allocated_block - filesize_);
#endif
785 786
    }

787
    if (close(fd_) < 0) {
788
      s = IOError(filename_, errno);
789 790 791 792 793 794
    }
    fd_ = -1;
    return s;
  }

  // write out the cached data to the OS cache
I
Igor Sugak 已提交
795
  virtual Status Flush() override {
796
    TEST_KILL_RANDOM(rocksdb_kill_odds * REDUCE_ODDS2);
797
    size_t left = cursize_;
M
Mayank Agarwal 已提交
798
    char* src = buf_.get();
799
    while (left != 0) {
800 801 802 803 804 805
      ssize_t done;
      size_t size = RequestToken(left);
      {
        IOSTATS_TIMER_GUARD(write_nanos);
        done = write(fd_, src, size);
      }
806
      if (done < 0) {
I
Igor Canadi 已提交
807 808 809
        if (errno == EINTR) {
          continue;
        }
810 811
        return IOError(filename_, errno);
      }
812
      IOSTATS_ADD(bytes_written, done);
813
      TEST_KILL_RANDOM(rocksdb_kill_odds * REDUCE_ODDS2);
814 815 816 817
      left -= done;
      src += done;
    }
    cursize_ = 0;
818

H
Haobo Xu 已提交
819 820 821 822 823 824
    // sync OS cache to disk for every bytes_per_sync_
    // TODO: give log file and sst file different options (log
    // files could be potentially cached in OS for their whole
    // life time, thus we might not want to flush at all).
    if (bytes_per_sync_ &&
        filesize_ - last_sync_size_ >= bytes_per_sync_) {
825 826 827 828
      RangeSync(last_sync_size_, filesize_ - last_sync_size_);
      last_sync_size_ = filesize_;
    }

829 830 831
    return Status::OK();
  }

I
Igor Sugak 已提交
832
  virtual Status Sync() override {
I
Igor Canadi 已提交
833 834 835 836
    Status s = Flush();
    if (!s.ok()) {
      return s;
    }
837
    TEST_KILL_RANDOM(rocksdb_kill_odds);
838 839 840
    if (pending_sync_ && fdatasync(fd_) < 0) {
      return IOError(filename_, errno);
    }
841
    TEST_KILL_RANDOM(rocksdb_kill_odds);
842 843 844 845
    pending_sync_ = false;
    return Status::OK();
  }

I
Igor Sugak 已提交
846
  virtual Status Fsync() override {
I
Igor Canadi 已提交
847 848 849 850
    Status s = Flush();
    if (!s.ok()) {
      return s;
    }
851
    TEST_KILL_RANDOM(rocksdb_kill_odds);
852 853 854
    if (pending_fsync_ && fsync(fd_) < 0) {
      return IOError(filename_, errno);
    }
855
    TEST_KILL_RANDOM(rocksdb_kill_odds);
856 857 858 859 860
    pending_fsync_ = false;
    pending_sync_ = false;
    return Status::OK();
  }

I
Igor Sugak 已提交
861
  virtual uint64_t GetFileSize() override { return filesize_; }
862

I
Igor Sugak 已提交
863
  virtual Status InvalidateCache(size_t offset, size_t length) override {
K
kailiu 已提交
864 865 866
#ifndef OS_LINUX
    return Status::OK();
#else
867
    // free OS pages
K
kailiu 已提交
868
    int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
869 870 871 872
    if (ret == 0) {
      return Status::OK();
    }
    return IOError(filename_, errno);
K
kailiu 已提交
873
#endif
874 875
  }

876
#ifdef ROCKSDB_FALLOCATE_PRESENT
I
Igor Sugak 已提交
877
  virtual Status Allocate(off_t offset, off_t len) override {
878
    TEST_KILL_RANDOM(rocksdb_kill_odds);
879 880 881
    int alloc_status;
    IOSTATS_TIMER_GUARD(allocate_nanos);
    alloc_status = fallocate(
I
Igor Canadi 已提交
882 883
        fd_, fallocate_with_keep_size_ ? FALLOC_FL_KEEP_SIZE : 0, offset, len);
    if (alloc_status == 0) {
884 885 886 887 888
      return Status::OK();
    } else {
      return IOError(filename_, errno);
    }
  }
889

I
Igor Sugak 已提交
890
  virtual Status RangeSync(off_t offset, off_t nbytes) override {
891
    IOSTATS_TIMER_GUARD(range_sync_nanos);
892 893 894 895 896 897
    if (sync_file_range(fd_, offset, nbytes, SYNC_FILE_RANGE_WRITE) == 0) {
      return Status::OK();
    } else {
      return IOError(filename_, errno);
    }
  }
I
Igor Sugak 已提交
898
  virtual size_t GetUniqueId(char* id, size_t max_size) const override {
899 900
    return GetUniqueIdFromFile(fd_, id, max_size);
  }
901
#endif
L
Lei Jin 已提交
902 903 904 905 906 907 908 909 910 911

 private:
  inline size_t RequestToken(size_t bytes) {
    if (rate_limiter_ && io_priority_ < Env::IO_TOTAL) {
      bytes = std::min(bytes,
          static_cast<size_t>(rate_limiter_->GetSingleBurstBytes()));
      rate_limiter_->Request(bytes, io_priority_);
    }
    return bytes;
  }
912 913
};

914 915 916 917 918 919
class PosixRandomRWFile : public RandomRWFile {
 private:
  const std::string filename_;
  int fd_;
  bool pending_sync_;
  bool pending_fsync_;
I
Igor Canadi 已提交
920
#ifdef ROCKSDB_FALLOCATE_PRESENT
I
Igor Canadi 已提交
921
  bool fallocate_with_keep_size_;
I
Igor Canadi 已提交
922
#endif
923 924

 public:
I
Igor Canadi 已提交
925 926 927 928
  PosixRandomRWFile(const std::string& fname, int fd, const EnvOptions& options)
      : filename_(fname),
        fd_(fd),
        pending_sync_(false),
I
Igor Canadi 已提交
929 930 931 932
        pending_fsync_(false) {
#ifdef ROCKSDB_FALLOCATE_PRESENT
    fallocate_with_keep_size_ = options.fallocate_with_keep_size;
#endif
933 934 935 936 937 938 939 940 941
    assert(!options.use_mmap_writes && !options.use_mmap_reads);
  }

  ~PosixRandomRWFile() {
    if (fd_ >= 0) {
      Close();
    }
  }

I
Igor Sugak 已提交
942
  virtual Status Write(uint64_t offset, const Slice& data) override {
943 944 945 946 947 948 949
    const char* src = data.data();
    size_t left = data.size();
    Status s;
    pending_sync_ = true;
    pending_fsync_ = true;

    while (left != 0) {
950 951 952 953 954
      ssize_t done;
      {
        IOSTATS_TIMER_GUARD(write_nanos);
        done = pwrite(fd_, src, left, offset);
      }
955
      if (done < 0) {
I
Igor Canadi 已提交
956 957 958
        if (errno == EINTR) {
          continue;
        }
959 960
        return IOError(filename_, errno);
      }
961
      IOSTATS_ADD(bytes_written, done);
962 963 964 965 966 967 968 969 970 971

      left -= done;
      src += done;
      offset += done;
    }

    return Status::OK();
  }

  virtual Status Read(uint64_t offset, size_t n, Slice* result,
I
Igor Sugak 已提交
972
                      char* scratch) const override {
973
    Status s;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
    ssize_t r = -1;
    size_t left = n;
    char* ptr = scratch;
    while (left > 0) {
      r = pread(fd_, ptr, left, static_cast<off_t>(offset));
      if (r <= 0) {
        if (errno == EINTR) {
          continue;
        }
        break;
      }
      ptr += r;
      offset += r;
      left -= r;
    }
    IOSTATS_ADD_IF_POSITIVE(bytes_read, n - left);
    *result = Slice(scratch, (r < 0) ? 0 : n - left);
991 992 993 994 995 996
    if (r < 0) {
      s = IOError(filename_, errno);
    }
    return s;
  }

I
Igor Sugak 已提交
997
  virtual Status Close() override {
998 999 1000 1001 1002 1003 1004 1005
    Status s = Status::OK();
    if (fd_ >= 0 && close(fd_) < 0) {
      s = IOError(filename_, errno);
    }
    fd_ = -1;
    return s;
  }

I
Igor Sugak 已提交
1006
  virtual Status Sync() override {
1007 1008 1009 1010 1011 1012 1013
    if (pending_sync_ && fdatasync(fd_) < 0) {
      return IOError(filename_, errno);
    }
    pending_sync_ = false;
    return Status::OK();
  }

I
Igor Sugak 已提交
1014
  virtual Status Fsync() override {
1015 1016 1017 1018 1019 1020 1021 1022
    if (pending_fsync_ && fsync(fd_) < 0) {
      return IOError(filename_, errno);
    }
    pending_fsync_ = false;
    pending_sync_ = false;
    return Status::OK();
  }

1023
#ifdef ROCKSDB_FALLOCATE_PRESENT
I
Igor Sugak 已提交
1024
  virtual Status Allocate(off_t offset, off_t len) override {
I
Igor Canadi 已提交
1025
    TEST_KILL_RANDOM(rocksdb_kill_odds);
1026
    IOSTATS_TIMER_GUARD(allocate_nanos);
I
Igor Canadi 已提交
1027 1028 1029
    int alloc_status = fallocate(
        fd_, fallocate_with_keep_size_ ? FALLOC_FL_KEEP_SIZE : 0, offset, len);
    if (alloc_status == 0) {
1030 1031 1032 1033 1034 1035 1036 1037
      return Status::OK();
    } else {
      return IOError(filename_, errno);
    }
  }
#endif
};

1038 1039 1040 1041 1042 1043 1044
class PosixDirectory : public Directory {
 public:
  explicit PosixDirectory(int fd) : fd_(fd) {}
  ~PosixDirectory() {
    close(fd_);
  }

I
Igor Sugak 已提交
1045
  virtual Status Fsync() override {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    if (fsync(fd_) == -1) {
      return IOError("directory", errno);
    }
    return Status::OK();
  }

 private:
  int fd_;
};

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
static int LockOrUnlock(const std::string& fname, int fd, bool lock) {
  mutex_lockedFiles.Lock();
  if (lock) {
    // If it already exists in the lockedFiles set, then it is already locked,
    // and fail this lock attempt. Otherwise, insert it into lockedFiles.
    // This check is needed because fcntl() does not detect lock conflict
    // if the fcntl is issued by the same thread that earlier acquired
    // this lock.
    if (lockedFiles.insert(fname).second == false) {
      mutex_lockedFiles.Unlock();
      errno = ENOLCK;
      return -1;
    }
  } else {
    // If we are unlocking, then verify that we had locked it earlier,
    // it should already exist in lockedFiles. Remove it from lockedFiles.
    if (lockedFiles.erase(fname) != 1) {
      mutex_lockedFiles.Unlock();
      errno = ENOLCK;
      return -1;
    }
  }
J
jorlow@chromium.org 已提交
1078 1079 1080 1081 1082 1083 1084
  errno = 0;
  struct flock f;
  memset(&f, 0, sizeof(f));
  f.l_type = (lock ? F_WRLCK : F_UNLCK);
  f.l_whence = SEEK_SET;
  f.l_start = 0;
  f.l_len = 0;        // Lock/unlock entire file
1085 1086 1087 1088 1089 1090 1091
  int value = fcntl(fd, F_SETLK, &f);
  if (value == -1 && lock) {
    // if there is an error in locking, then remove the pathname from lockedfiles
    lockedFiles.erase(fname);
  }
  mutex_lockedFiles.Unlock();
  return value;
J
jorlow@chromium.org 已提交
1092 1093 1094 1095 1096
}

class PosixFileLock : public FileLock {
 public:
  int fd_;
1097
  std::string filename;
J
jorlow@chromium.org 已提交
1098 1099
};

1100 1101 1102
void PthreadCall(const char* label, int result) {
  if (result != 0) {
    fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
1103
    abort();
1104 1105 1106
  }
}

J
jorlow@chromium.org 已提交
1107 1108 1109
class PosixEnv : public Env {
 public:
  PosixEnv();
1110

1111
  virtual ~PosixEnv() {
1112 1113 1114
    for (const auto tid : threads_to_join_) {
      pthread_join(tid, nullptr);
    }
1115 1116 1117 1118 1119 1120
    for (int pool_id = 0; pool_id < Env::Priority::TOTAL; ++pool_id) {
      thread_pools_[pool_id].JoinAllThreads();
    }
    // All threads must be joined before the deletion of
    // thread_status_updater_.
    delete thread_status_updater_;
J
jorlow@chromium.org 已提交
1121 1122
  }

1123
  void SetFD_CLOEXEC(int fd, const EnvOptions* options) {
H
Haobo Xu 已提交
1124
    if ((options == nullptr || options->set_fd_cloexec) && fd > 0) {
1125 1126 1127 1128
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
    }
  }

J
jorlow@chromium.org 已提交
1129
  virtual Status NewSequentialFile(const std::string& fname,
1130
                                   unique_ptr<SequentialFile>* result,
I
Igor Sugak 已提交
1131
                                   const EnvOptions& options) override {
1132
    result->reset();
I
Igor Canadi 已提交
1133 1134
    FILE* f = nullptr;
    do {
1135
      IOSTATS_TIMER_GUARD(open_nanos);
I
Igor Canadi 已提交
1136 1137
      f = fopen(fname.c_str(), "r");
    } while (f == nullptr && errno == EINTR);
A
Abhishek Kona 已提交
1138 1139
    if (f == nullptr) {
      *result = nullptr;
1140
      return IOError(fname, errno);
J
jorlow@chromium.org 已提交
1141
    } else {
1142 1143
      int fd = fileno(f);
      SetFD_CLOEXEC(fd, &options);
1144
      result->reset(new PosixSequentialFile(fname, f, options));
J
jorlow@chromium.org 已提交
1145 1146 1147 1148 1149
      return Status::OK();
    }
  }

  virtual Status NewRandomAccessFile(const std::string& fname,
1150
                                     unique_ptr<RandomAccessFile>* result,
I
Igor Sugak 已提交
1151
                                     const EnvOptions& options) override {
1152
    result->reset();
1153
    Status s;
1154 1155 1156 1157 1158
    int fd;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), O_RDONLY);
    }
1159
    SetFD_CLOEXEC(fd, &options);
J
jorlow@chromium.org 已提交
1160
    if (fd < 0) {
1161
      s = IOError(fname, errno);
H
Haobo Xu 已提交
1162
    } else if (options.use_mmap_reads && sizeof(void*) >= 8) {
1163 1164 1165 1166 1167 1168
      // Use of mmap for random reads has been removed because it
      // kills performance when storage is fast.
      // Use mmap when virtual address-space is plentiful.
      uint64_t size;
      s = GetFileSize(fname, &size);
      if (s.ok()) {
A
Abhishek Kona 已提交
1169
        void* base = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
1170
        if (base != MAP_FAILED) {
1171 1172
          result->reset(new PosixMmapReadableFile(fd, fname, base,
                                                  size, options));
1173 1174 1175 1176 1177
        } else {
          s = IOError(fname, errno);
        }
      }
      close(fd);
1178
    } else {
1179
      result->reset(new PosixRandomAccessFile(fname, fd, options));
J
jorlow@chromium.org 已提交
1180
    }
1181
    return s;
J
jorlow@chromium.org 已提交
1182 1183 1184
  }

  virtual Status NewWritableFile(const std::string& fname,
1185
                                 unique_ptr<WritableFile>* result,
I
Igor Sugak 已提交
1186
                                 const EnvOptions& options) override {
1187
    result->reset();
J
jorlow@chromium.org 已提交
1188
    Status s;
I
Igor Canadi 已提交
1189 1190
    int fd = -1;
    do {
1191
      IOSTATS_TIMER_GUARD(open_nanos);
I
Igor Canadi 已提交
1192 1193
      fd = open(fname.c_str(), O_CREAT | O_RDWR | O_TRUNC, 0644);
    } while (fd < 0 && errno == EINTR);
J
jorlow@chromium.org 已提交
1194
    if (fd < 0) {
1195
      s = IOError(fname, errno);
J
jorlow@chromium.org 已提交
1196
    } else {
1197
      SetFD_CLOEXEC(fd, &options);
H
Haobo Xu 已提交
1198
      if (options.use_mmap_writes) {
1199 1200
        if (!checkedDiskForMmap_) {
          // this will be executed once in the program's lifetime.
A
Abhishek Kona 已提交
1201
          // do not use mmapWrite on non ext-3/xfs/tmpfs systems.
1202 1203 1204 1205
          if (!SupportsFastAllocate(fname)) {
            forceMmapOff = true;
          }
          checkedDiskForMmap_ = true;
A
Abhishek Kona 已提交
1206 1207
        }
      }
H
Haobo Xu 已提交
1208
      if (options.use_mmap_writes && !forceMmapOff) {
1209
        result->reset(new PosixMmapFile(fname, fd, page_size_, options));
1210
      } else {
K
kailiu 已提交
1211 1212 1213 1214 1215 1216 1217
        // disable mmap writes
        EnvOptions no_mmap_writes_options = options;
        no_mmap_writes_options.use_mmap_writes = false;

        result->reset(
            new PosixWritableFile(fname, fd, 65536, no_mmap_writes_options)
        );
1218
      }
J
jorlow@chromium.org 已提交
1219 1220 1221 1222
    }
    return s;
  }

1223 1224
  virtual Status NewRandomRWFile(const std::string& fname,
                                 unique_ptr<RandomRWFile>* result,
I
Igor Sugak 已提交
1225
                                 const EnvOptions& options) override {
1226
    result->reset();
1227 1228 1229 1230
    // no support for mmap yet
    if (options.use_mmap_writes || options.use_mmap_reads) {
      return Status::NotSupported("No support for mmap read/write yet");
    }
1231
    Status s;
1232 1233 1234 1235 1236
    int fd;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), O_CREAT | O_RDWR, 0644);
    }
1237 1238 1239 1240 1241 1242 1243 1244 1245
    if (fd < 0) {
      s = IOError(fname, errno);
    } else {
      SetFD_CLOEXEC(fd, &options);
      result->reset(new PosixRandomRWFile(fname, fd, options));
    }
    return s;
  }

1246
  virtual Status NewDirectory(const std::string& name,
I
Igor Sugak 已提交
1247
                              unique_ptr<Directory>* result) override {
1248
    result->reset();
1249 1250 1251 1252 1253
    int fd;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(name.c_str(), 0);
    }
1254 1255 1256 1257 1258 1259 1260 1261
    if (fd < 0) {
      return IOError(name, errno);
    } else {
      result->reset(new PosixDirectory(fd));
    }
    return Status::OK();
  }

I
Igor Sugak 已提交
1262
  virtual bool FileExists(const std::string& fname) override {
J
jorlow@chromium.org 已提交
1263 1264 1265 1266
    return access(fname.c_str(), F_OK) == 0;
  }

  virtual Status GetChildren(const std::string& dir,
I
Igor Sugak 已提交
1267
                             std::vector<std::string>* result) override {
J
jorlow@chromium.org 已提交
1268 1269
    result->clear();
    DIR* d = opendir(dir.c_str());
A
Abhishek Kona 已提交
1270
    if (d == nullptr) {
1271
      return IOError(dir, errno);
J
jorlow@chromium.org 已提交
1272 1273
    }
    struct dirent* entry;
A
Abhishek Kona 已提交
1274
    while ((entry = readdir(d)) != nullptr) {
J
jorlow@chromium.org 已提交
1275 1276 1277 1278 1279 1280
      result->push_back(entry->d_name);
    }
    closedir(d);
    return Status::OK();
  }

I
Igor Sugak 已提交
1281
  virtual Status DeleteFile(const std::string& fname) override {
J
jorlow@chromium.org 已提交
1282 1283
    Status result;
    if (unlink(fname.c_str()) != 0) {
1284
      result = IOError(fname, errno);
J
jorlow@chromium.org 已提交
1285 1286 1287 1288
    }
    return result;
  };

I
Igor Sugak 已提交
1289
  virtual Status CreateDir(const std::string& name) override {
J
jorlow@chromium.org 已提交
1290 1291
    Status result;
    if (mkdir(name.c_str(), 0755) != 0) {
1292
      result = IOError(name, errno);
J
jorlow@chromium.org 已提交
1293 1294 1295 1296
    }
    return result;
  };

I
Igor Sugak 已提交
1297
  virtual Status CreateDirIfMissing(const std::string& name) override {
1298 1299 1300 1301
    Status result;
    if (mkdir(name.c_str(), 0755) != 0) {
      if (errno != EEXIST) {
        result = IOError(name, errno);
1302 1303 1304 1305
      } else if (!DirExists(name)) { // Check that name is actually a
                                     // directory.
        // Message is taken from mkdir
        result = Status::IOError("`"+name+"' exists but is not a directory");
1306 1307 1308 1309 1310
      }
    }
    return result;
  };

I
Igor Sugak 已提交
1311
  virtual Status DeleteDir(const std::string& name) override {
J
jorlow@chromium.org 已提交
1312 1313
    Status result;
    if (rmdir(name.c_str()) != 0) {
1314
      result = IOError(name, errno);
J
jorlow@chromium.org 已提交
1315 1316 1317 1318
    }
    return result;
  };

I
Igor Sugak 已提交
1319 1320
  virtual Status GetFileSize(const std::string& fname,
                             uint64_t* size) override {
J
jorlow@chromium.org 已提交
1321 1322 1323 1324
    Status s;
    struct stat sbuf;
    if (stat(fname.c_str(), &sbuf) != 0) {
      *size = 0;
1325
      s = IOError(fname, errno);
J
jorlow@chromium.org 已提交
1326 1327 1328 1329 1330 1331
    } else {
      *size = sbuf.st_size;
    }
    return s;
  }

1332
  virtual Status GetFileModificationTime(const std::string& fname,
I
Igor Sugak 已提交
1333
                                         uint64_t* file_mtime) override {
1334 1335 1336 1337 1338 1339 1340
    struct stat s;
    if (stat(fname.c_str(), &s) !=0) {
      return IOError(fname, errno);
    }
    *file_mtime = static_cast<uint64_t>(s.st_mtime);
    return Status::OK();
  }
I
Igor Sugak 已提交
1341 1342
  virtual Status RenameFile(const std::string& src,
                            const std::string& target) override {
J
jorlow@chromium.org 已提交
1343 1344
    Status result;
    if (rename(src.c_str(), target.c_str()) != 0) {
1345
      result = IOError(src, errno);
J
jorlow@chromium.org 已提交
1346 1347 1348 1349
    }
    return result;
  }

I
Igor Sugak 已提交
1350 1351
  virtual Status LinkFile(const std::string& src,
                          const std::string& target) override {
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    Status result;
    if (link(src.c_str(), target.c_str()) != 0) {
      if (errno == EXDEV) {
        return Status::NotSupported("No cross FS links allowed");
      }
      result = IOError(src, errno);
    }
    return result;
  }

I
Igor Sugak 已提交
1362
  virtual Status LockFile(const std::string& fname, FileLock** lock) override {
A
Abhishek Kona 已提交
1363
    *lock = nullptr;
J
jorlow@chromium.org 已提交
1364
    Status result;
1365 1366 1367 1368 1369
    int fd;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), O_RDWR | O_CREAT, 0644);
    }
J
jorlow@chromium.org 已提交
1370
    if (fd < 0) {
1371
      result = IOError(fname, errno);
1372
    } else if (LockOrUnlock(fname, fd, true) == -1) {
1373
      result = IOError("lock " + fname, errno);
J
jorlow@chromium.org 已提交
1374 1375
      close(fd);
    } else {
1376
      SetFD_CLOEXEC(fd, nullptr);
J
jorlow@chromium.org 已提交
1377 1378
      PosixFileLock* my_lock = new PosixFileLock;
      my_lock->fd_ = fd;
1379
      my_lock->filename = fname;
J
jorlow@chromium.org 已提交
1380 1381 1382 1383 1384
      *lock = my_lock;
    }
    return result;
  }

I
Igor Sugak 已提交
1385
  virtual Status UnlockFile(FileLock* lock) override {
J
jorlow@chromium.org 已提交
1386 1387
    PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
    Status result;
1388
    if (LockOrUnlock(my_lock->filename, my_lock->fd_, false) == -1) {
1389
      result = IOError("unlock", errno);
J
jorlow@chromium.org 已提交
1390 1391 1392 1393 1394 1395
    }
    close(my_lock->fd_);
    delete my_lock;
    return result;
  }

1396 1397 1398 1399
  virtual void Schedule(void (*function)(void* arg1), void* arg,
                        Priority pri = LOW, void* tag = nullptr) override;

  virtual int UnSchedule(void* arg, Priority pri) override;
1400

I
Igor Sugak 已提交
1401
  virtual void StartThread(void (*function)(void* arg), void* arg) override;
J
jorlow@chromium.org 已提交
1402

I
Igor Sugak 已提交
1403
  virtual void WaitForJoin() override;
L
Lei Jin 已提交
1404

1405 1406
  virtual unsigned int GetThreadPoolQueueLen(Priority pri = LOW) const override;

I
Igor Sugak 已提交
1407
  virtual Status GetTestDirectory(std::string* result) override {
J
jorlow@chromium.org 已提交
1408 1409 1410 1411 1412
    const char* env = getenv("TEST_TMPDIR");
    if (env && env[0] != '\0') {
      *result = env;
    } else {
      char buf[100];
1413
      snprintf(buf, sizeof(buf), "/tmp/rocksdbtest-%d", int(geteuid()));
J
jorlow@chromium.org 已提交
1414 1415 1416 1417 1418 1419 1420
      *result = buf;
    }
    // Directory may already exist
    CreateDir(*result);
    return Status::OK();
  }

1421 1422 1423 1424 1425 1426
  virtual Status GetThreadList(
      std::vector<ThreadStatus>* thread_list) override {
    assert(thread_status_updater_);
    return thread_status_updater_->GetThreadList(thread_list);
  }

1427
  static uint64_t gettid(pthread_t tid) {
J
jorlow@chromium.org 已提交
1428
    uint64_t thread_id = 0;
J
jorlow@chromium.org 已提交
1429
    memcpy(&thread_id, &tid, std::min(sizeof(thread_id), sizeof(tid)));
1430 1431
    return thread_id;
  }
J
jorlow@chromium.org 已提交
1432

1433 1434 1435 1436 1437
  static uint64_t gettid() {
    pthread_t tid = pthread_self();
    return gettid(tid);
  }

I
Islam AbdelRahman 已提交
1438
  virtual uint64_t GetThreadID() const override {
1439 1440 1441
    return gettid(pthread_self());
  }

1442
  virtual Status NewLogger(const std::string& fname,
I
Igor Sugak 已提交
1443
                           shared_ptr<Logger>* result) override {
1444 1445 1446 1447 1448
    FILE* f;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
      f = fopen(fname.c_str(), "w");
    }
A
Abhishek Kona 已提交
1449
    if (f == nullptr) {
1450
      result->reset();
1451 1452
      return IOError(fname, errno);
    } else {
1453 1454
      int fd = fileno(f);
      SetFD_CLOEXEC(fd, nullptr);
I
Igor Canadi 已提交
1455
      result->reset(new PosixLogger(f, &PosixEnv::gettid, this));
1456
      return Status::OK();
J
jorlow@chromium.org 已提交
1457 1458 1459
    }
  }

I
Igor Sugak 已提交
1460
  virtual uint64_t NowMicros() override {
I
Igor Canadi 已提交
1461 1462 1463
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
J
jorlow@chromium.org 已提交
1464 1465
  }

I
Igor Sugak 已提交
1466
  virtual uint64_t NowNanos() override {
I
Islam AbdelRahman 已提交
1467
#if defined(OS_LINUX) || defined(OS_FREEBSD)
I
Igor Canadi 已提交
1468 1469 1470
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return static_cast<uint64_t>(ts.tv_sec) * 1000000000 + ts.tv_nsec;
1471
#elif defined(__MACH__)
I
Igor Canadi 已提交
1472 1473 1474 1475 1476 1477
    clock_serv_t cclock;
    mach_timespec_t ts;
    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
    clock_get_time(cclock, &ts);
    mach_port_deallocate(mach_task_self(), cclock);
    return static_cast<uint64_t>(ts.tv_sec) * 1000000000 + ts.tv_nsec;
I
Islam AbdelRahman 已提交
1478 1479 1480 1481
#else
    return std::chrono::duration_cast<std::chrono::nanoseconds>(
       std::chrono::steady_clock::now().time_since_epoch()).count();
#endif
1482 1483
  }

I
Igor Sugak 已提交
1484
  virtual void SleepForMicroseconds(int micros) override { usleep(micros); }
J
jorlow@chromium.org 已提交
1485

I
Igor Sugak 已提交
1486
  virtual Status GetHostName(char* name, uint64_t len) override {
1487
    int ret = gethostname(name, static_cast<size_t>(len));
1488 1489 1490 1491 1492 1493 1494 1495 1496
    if (ret < 0) {
      if (errno == EFAULT || errno == EINVAL)
        return Status::InvalidArgument(strerror(errno));
      else
        return IOError("GetHostName", errno);
    }
    return Status::OK();
  }

I
Igor Sugak 已提交
1497
  virtual Status GetCurrentTime(int64_t* unix_time) override {
A
Abhishek Kona 已提交
1498
    time_t ret = time(nullptr);
1499 1500 1501 1502 1503 1504 1505 1506
    if (ret == (time_t) -1) {
      return IOError("GetCurrentTime", errno);
    }
    *unix_time = (int64_t) ret;
    return Status::OK();
  }

  virtual Status GetAbsolutePath(const std::string& db_path,
I
Igor Sugak 已提交
1507
                                 std::string* output_path) override {
1508 1509 1510 1511 1512 1513 1514
    if (db_path.find('/') == 0) {
      *output_path = db_path;
      return Status::OK();
    }

    char the_path[256];
    char* ret = getcwd(the_path, 256);
A
Abhishek Kona 已提交
1515
    if (ret == nullptr) {
1516 1517 1518 1519 1520 1521 1522
      return Status::IOError(strerror(errno));
    }

    *output_path = ret;
    return Status::OK();
  }

A
Abhishek Kona 已提交
1523
  // Allow increasing the number of worker threads.
I
Igor Sugak 已提交
1524
  virtual void SetBackgroundThreads(int num, Priority pri) override {
1525 1526
    assert(pri >= Priority::LOW && pri <= Priority::HIGH);
    thread_pools_[pri].SetBackgroundThreads(num);
1527 1528
  }

1529
  // Allow increasing the number of worker threads.
I
Igor Sugak 已提交
1530
  virtual void IncBackgroundThreadsIfNeeded(int num, Priority pri) override {
1531 1532 1533 1534
    assert(pri >= Priority::LOW && pri <= Priority::HIGH);
    thread_pools_[pri].IncBackgroundThreadsIfNeeded(num);
  }

1535 1536 1537 1538 1539 1540 1541
  virtual void LowerThreadPoolIOPriority(Priority pool = LOW) override {
    assert(pool >= Priority::LOW && pool <= Priority::HIGH);
#ifdef OS_LINUX
    thread_pools_[pool].LowerIOPriority();
#endif
  }

I
Igor Sugak 已提交
1542
  virtual std::string TimeToString(uint64_t secondsSince1970) override {
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
    const time_t seconds = (time_t)secondsSince1970;
    struct tm t;
    int maxsize = 64;
    std::string dummy;
    dummy.reserve(maxsize);
    dummy.resize(maxsize);
    char* p = &dummy[0];
    localtime_r(&seconds, &t);
    snprintf(p, maxsize,
             "%04d/%02d/%02d-%02d:%02d:%02d ",
             t.tm_year + 1900,
             t.tm_mon + 1,
             t.tm_mday,
             t.tm_hour,
             t.tm_min,
             t.tm_sec);
    return dummy;
  }

1562 1563
  EnvOptions OptimizeForLogWrite(const EnvOptions& env_options,
                                 const DBOptions& db_options) const override {
I
Igor Canadi 已提交
1564 1565
    EnvOptions optimized = env_options;
    optimized.use_mmap_writes = false;
1566
    optimized.bytes_per_sync = db_options.wal_bytes_per_sync;
I
Igor Canadi 已提交
1567 1568 1569 1570
    // TODO(icanadi) it's faster if fallocate_with_keep_size is false, but it
    // breaks TransactionLogIteratorStallAtLastRecord unit test. Fix the unit
    // test and make this false
    optimized.fallocate_with_keep_size = true;
I
Igor Canadi 已提交
1571 1572 1573
    return optimized;
  }

I
Igor Sugak 已提交
1574 1575
  EnvOptions OptimizeForManifestWrite(
      const EnvOptions& env_options) const override {
I
Igor Canadi 已提交
1576 1577 1578 1579 1580 1581
    EnvOptions optimized = env_options;
    optimized.use_mmap_writes = false;
    optimized.fallocate_with_keep_size = true;
    return optimized;
  }

J
jorlow@chromium.org 已提交
1582
 private:
1583 1584
  bool checkedDiskForMmap_;
  bool forceMmapOff; // do we override Env options?
A
Abhishek Kona 已提交
1585

J
jorlow@chromium.org 已提交
1586

1587 1588 1589 1590 1591 1592 1593 1594 1595
  // Returns true iff the named directory exists and is a directory.
  virtual bool DirExists(const std::string& dname) {
    struct stat statbuf;
    if (stat(dname.c_str(), &statbuf) == 0) {
      return S_ISDIR(statbuf.st_mode);
    }
    return false; // stat() failed return false
  }

A
Abhishek Kona 已提交
1596
  bool SupportsFastAllocate(const std::string& path) {
J
James Golick 已提交
1597
#ifdef ROCKSDB_FALLOCATE_PRESENT
A
Abhishek Kona 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    struct statfs s;
    if (statfs(path.c_str(), &s)){
      return false;
    }
    switch (s.f_type) {
      case EXT4_SUPER_MAGIC:
        return true;
      case XFS_SUPER_MAGIC:
        return true;
      case TMPFS_MAGIC:
        return true;
      default:
        return false;
    }
K
kailiu 已提交
1612 1613 1614
#else
    return false;
#endif
A
Abhishek Kona 已提交
1615 1616
  }

J
jorlow@chromium.org 已提交
1617 1618 1619
  size_t page_size_;


1620 1621
  class ThreadPool {
   public:
1622 1623 1624 1625 1626
    ThreadPool()
        : total_threads_limit_(1),
          bgthreads_(0),
          queue_(),
          queue_len_(0),
1627
          exit_all_threads_(false),
1628 1629
          low_io_priority_(false),
          env_(nullptr) {
1630 1631 1632
      PthreadCall("mutex_init", pthread_mutex_init(&mu_, nullptr));
      PthreadCall("cvar_init", pthread_cond_init(&bgsignal_, nullptr));
    }
J
jorlow@chromium.org 已提交
1633

1634
    ~ThreadPool() {
1635 1636 1637 1638
      assert(bgthreads_.size() == 0U);
    }

    void JoinAllThreads() {
1639 1640 1641 1642 1643 1644 1645 1646
      PthreadCall("lock", pthread_mutex_lock(&mu_));
      assert(!exit_all_threads_);
      exit_all_threads_ = true;
      PthreadCall("signalall", pthread_cond_broadcast(&bgsignal_));
      PthreadCall("unlock", pthread_mutex_unlock(&mu_));
      for (const auto tid : bgthreads_) {
        pthread_join(tid, nullptr);
      }
1647 1648 1649 1650 1651
      bgthreads_.clear();
    }

    void SetHostEnv(Env* env) {
      env_ = env;
1652
    }
J
jorlow@chromium.org 已提交
1653

1654 1655 1656 1657 1658 1659 1660 1661
    void LowerIOPriority() {
#ifdef OS_LINUX
      PthreadCall("lock", pthread_mutex_lock(&mu_));
      low_io_priority_ = true;
      PthreadCall("unlock", pthread_mutex_unlock(&mu_));
#endif
    }

1662 1663 1664 1665 1666 1667 1668 1669 1670
    // Return true if there is at least one thread needs to terminate.
    bool HasExcessiveThread() {
      return static_cast<int>(bgthreads_.size()) > total_threads_limit_;
    }

    // Return true iff the current thread is the excessive thread to terminate.
    // Always terminate the running thread that is added last, even if there are
    // more than one thread to terminate.
    bool IsLastExcessiveThread(size_t thread_id) {
1671
      return HasExcessiveThread() && thread_id == bgthreads_.size() - 1;
1672 1673 1674 1675 1676 1677 1678
    }

    // Is one of the threads to terminate.
    bool IsExcessiveThread(size_t thread_id) {
      return static_cast<int>(thread_id) >= total_threads_limit_;
    }

Y
Yueh-Hsuan Chiang 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
    // Return the thread priority.
    // This would allow its member-thread to know its priority.
    Env::Priority GetThreadPriority() {
      return priority_;
    }

    // Set the thread priority.
    void SetThreadPriority(Env::Priority priority) {
      priority_ = priority;
    }

1690
    void BGThread(size_t thread_id) {
1691
      bool low_io_priority = false;
1692 1693 1694
      while (true) {
        // Wait until there is an item that is ready to run
        PthreadCall("lock", pthread_mutex_lock(&mu_));
1695 1696 1697
        // Stop waiting if the thread needs to do work or needs to terminate.
        while (!exit_all_threads_ && !IsLastExcessiveThread(thread_id) &&
               (queue_.empty() || IsExcessiveThread(thread_id))) {
1698 1699 1700 1701 1702 1703
          PthreadCall("wait", pthread_cond_wait(&bgsignal_, &mu_));
        }
        if (exit_all_threads_) { // mechanism to let BG threads exit safely
          PthreadCall("unlock", pthread_mutex_unlock(&mu_));
          break;
        }
1704 1705 1706 1707
        if (IsLastExcessiveThread(thread_id)) {
          // Current thread is the last generated one and is excessive.
          // We always terminate excessive thread in the reverse order of
          // generation time.
1708 1709
          auto terminating_thread = bgthreads_.back();
          pthread_detach(terminating_thread);
1710 1711 1712 1713 1714 1715 1716 1717
          bgthreads_.pop_back();
          if (HasExcessiveThread()) {
            // There is still at least more excessive thread to terminate.
            WakeUpAllThreads();
          }
          PthreadCall("unlock", pthread_mutex_unlock(&mu_));
          break;
        }
1718 1719 1720
        void (*function)(void*) = queue_.front().function;
        void* arg = queue_.front().arg;
        queue_.pop_front();
1721 1722
        queue_len_.store(static_cast<unsigned int>(queue_.size()),
                         std::memory_order_relaxed);
H
Haobo Xu 已提交
1723

1724
        bool decrease_io_priority = (low_io_priority != low_io_priority_);
1725
        PthreadCall("unlock", pthread_mutex_unlock(&mu_));
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747

#ifdef OS_LINUX
        if (decrease_io_priority) {
          #define IOPRIO_CLASS_SHIFT               (13)
          #define IOPRIO_PRIO_VALUE(class, data)   \
              (((class) << IOPRIO_CLASS_SHIFT) | data)
          // Put schedule into IOPRIO_CLASS_IDLE class (lowest)
          // These system calls only have an effect when used in conjunction
          // with an I/O scheduler that supports I/O priorities. As at
          // kernel 2.6.17 the only such scheduler is the Completely
          // Fair Queuing (CFQ) I/O scheduler.
          // To change scheduler:
          //  echo cfq > /sys/block/<device_name>/queue/schedule
          // Tunables to consider:
          //  /sys/block/<device_name>/queue/slice_idle
          //  /sys/block/<device_name>/queue/slice_sync
          syscall(SYS_ioprio_set,
                  1,  // IOPRIO_WHO_PROCESS
                  0,  // current thread
                  IOPRIO_PRIO_VALUE(3, 0));
          low_io_priority = true;
        }
Z
ZHANG Biao 已提交
1748 1749
#else
        (void)decrease_io_priority; // avoid 'unused variable' error
1750
#endif
1751 1752 1753
        (*function)(arg);
      }
    }
J
jorlow@chromium.org 已提交
1754

1755 1756 1757 1758 1759 1760 1761 1762
    // Helper struct for passing arguments when creating threads.
    struct BGThreadMetadata {
      ThreadPool* thread_pool_;
      size_t thread_id_;  // Thread count in the thread.
      explicit BGThreadMetadata(ThreadPool* thread_pool, size_t thread_id)
          : thread_pool_(thread_pool), thread_id_(thread_id) {}
    };

1763
    static void* BGThreadWrapper(void* arg) {
1764 1765 1766
      BGThreadMetadata* meta = reinterpret_cast<BGThreadMetadata*>(arg);
      size_t thread_id = meta->thread_id_;
      ThreadPool* tp = meta->thread_pool_;
1767
#if ROCKSDB_USING_THREAD_STATUS
Y
Yueh-Hsuan Chiang 已提交
1768
      // for thread-status
1769
      ThreadStatusUtil::SetThreadType(tp->env_,
Y
Yueh-Hsuan Chiang 已提交
1770
          (tp->GetThreadPriority() == Env::Priority::HIGH ?
1771 1772
              ThreadStatus::HIGH_PRIORITY :
              ThreadStatus::LOW_PRIORITY));
1773
#endif
1774 1775
      delete meta;
      tp->BGThread(thread_id);
1776
#if ROCKSDB_USING_THREAD_STATUS
1777
      ThreadStatusUtil::UnregisterThread();
1778
#endif
1779 1780
      return nullptr;
    }
J
jorlow@chromium.org 已提交
1781

1782 1783 1784 1785
    void WakeUpAllThreads() {
      PthreadCall("signalall", pthread_cond_broadcast(&bgsignal_));
    }

1786
    void SetBackgroundThreadsInternal(int num, bool allow_reduce) {
1787
      PthreadCall("lock", pthread_mutex_lock(&mu_));
1788 1789 1790 1791
      if (exit_all_threads_) {
        PthreadCall("unlock", pthread_mutex_unlock(&mu_));
        return;
      }
1792 1793
      if (num > total_threads_limit_ ||
          (num < total_threads_limit_ && allow_reduce)) {
I
Igor Canadi 已提交
1794
        total_threads_limit_ = std::max(1, num);
1795 1796
        WakeUpAllThreads();
        StartBGThreads();
1797 1798
      }
      PthreadCall("unlock", pthread_mutex_unlock(&mu_));
J
jorlow@chromium.org 已提交
1799
    }
1800

1801 1802 1803 1804 1805 1806 1807 1808
    void IncBackgroundThreadsIfNeeded(int num) {
      SetBackgroundThreadsInternal(num, false);
    }

    void SetBackgroundThreads(int num) {
      SetBackgroundThreadsInternal(num, true);
    }

1809
    void StartBGThreads() {
1810 1811 1812 1813
      // Start background thread if necessary
      while ((int)bgthreads_.size() < total_threads_limit_) {
        pthread_t t;
        PthreadCall(
1814 1815 1816
            "create thread",
            pthread_create(&t, nullptr, &ThreadPool::BGThreadWrapper,
                           new BGThreadMetadata(this, bgthreads_.size())));
1817 1818

        // Set the thread name to aid debugging
1819 1820
#if defined(_GNU_SOURCE) && defined(__GLIBC_PREREQ)
#if __GLIBC_PREREQ(2, 12)
1821 1822 1823 1824
        char name_buf[16];
        snprintf(name_buf, sizeof name_buf, "rocksdb:bg%zu", bgthreads_.size());
        name_buf[sizeof name_buf - 1] = '\0';
        pthread_setname_np(t, name_buf);
1825
#endif
1826 1827
#endif

1828 1829
        bgthreads_.push_back(t);
      }
1830 1831
    }

1832
    void Schedule(void (*function)(void* arg1), void* arg, void* tag) {
1833 1834 1835 1836 1837 1838 1839 1840
      PthreadCall("lock", pthread_mutex_lock(&mu_));

      if (exit_all_threads_) {
        PthreadCall("unlock", pthread_mutex_unlock(&mu_));
        return;
      }

      StartBGThreads();
1841 1842 1843 1844 1845

      // Add to priority queue
      queue_.push_back(BGItem());
      queue_.back().function = function;
      queue_.back().arg = arg;
1846
      queue_.back().tag = tag;
1847 1848
      queue_len_.store(static_cast<unsigned int>(queue_.size()),
                       std::memory_order_relaxed);
1849

1850 1851 1852 1853 1854 1855 1856 1857
      if (!HasExcessiveThread()) {
        // Wake up at least one waiting thread.
        PthreadCall("signal", pthread_cond_signal(&bgsignal_));
      } else {
        // Need to wake up all threads to make sure the one woken
        // up is not the one to terminate.
        WakeUpAllThreads();
      }
1858

1859 1860
      PthreadCall("unlock", pthread_mutex_unlock(&mu_));
    }
J
jorlow@chromium.org 已提交
1861

1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
    int UnSchedule(void* arg) {
      int count = 0;
      PthreadCall("lock", pthread_mutex_lock(&mu_));

      // Remove from priority queue
      BGQueue::iterator it = queue_.begin();
      while (it != queue_.end()) {
        if (arg == (*it).tag) {
          it = queue_.erase(it);
          count++;
        } else {
          it++;
        }
      }
      queue_len_.store(static_cast<unsigned int>(queue_.size()),
                       std::memory_order_relaxed);
      PthreadCall("unlock", pthread_mutex_unlock(&mu_));
      return count;
    }

1882 1883 1884 1885
    unsigned int GetQueueLen() const {
      return queue_len_.load(std::memory_order_relaxed);
    }

1886 1887
   private:
    // Entry per Schedule() call
1888 1889 1890 1891 1892
    struct BGItem {
      void* arg;
      void (*function)(void*);
      void* tag;
    };
1893 1894 1895 1896 1897 1898 1899
    typedef std::deque<BGItem> BGQueue;

    pthread_mutex_t mu_;
    pthread_cond_t bgsignal_;
    int total_threads_limit_;
    std::vector<pthread_t> bgthreads_;
    BGQueue queue_;
1900
    std::atomic_uint queue_len_;  // Queue length. Used for stats reporting
1901
    bool exit_all_threads_;
1902
    bool low_io_priority_;
Y
Yueh-Hsuan Chiang 已提交
1903
    Env::Priority priority_;
1904
    Env* env_;
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
  };

  std::vector<ThreadPool> thread_pools_;

  pthread_mutex_t mu_;
  std::vector<pthread_t> threads_to_join_;

};

PosixEnv::PosixEnv() : checkedDiskForMmap_(false),
                       forceMmapOff(false),
                       page_size_(getpagesize()),
                       thread_pools_(Priority::TOTAL) {
  PthreadCall("mutex_init", pthread_mutex_init(&mu_, nullptr));
Y
Yueh-Hsuan Chiang 已提交
1919 1920 1921
  for (int pool_id = 0; pool_id < Env::Priority::TOTAL; ++pool_id) {
    thread_pools_[pool_id].SetThreadPriority(
        static_cast<Env::Priority>(pool_id));
1922 1923
    // This allows later initializing the thread-local-env of each thread.
    thread_pools_[pool_id].SetHostEnv(this);
Y
Yueh-Hsuan Chiang 已提交
1924
  }
1925
  thread_status_updater_ = CreateThreadStatusUpdater();
1926 1927
}

1928 1929
void PosixEnv::Schedule(void (*function)(void* arg1), void* arg, Priority pri,
                        void* tag) {
1930
  assert(pri >= Priority::LOW && pri <= Priority::HIGH);
1931 1932 1933 1934 1935
  thread_pools_[pri].Schedule(function, arg, tag);
}

int PosixEnv::UnSchedule(void* arg, Priority pri) {
  return thread_pools_[pri].UnSchedule(arg);
J
jorlow@chromium.org 已提交
1936 1937
}

1938 1939 1940 1941 1942
unsigned int PosixEnv::GetThreadPoolQueueLen(Priority pri) const {
  assert(pri >= Priority::LOW && pri <= Priority::HIGH);
  return thread_pools_[pri].GetQueueLen();
}

J
jorlow@chromium.org 已提交
1943 1944 1945 1946
struct StartThreadState {
  void (*user_function)(void*);
  void* arg;
};
1947

J
jorlow@chromium.org 已提交
1948 1949 1950 1951
static void* StartThreadWrapper(void* arg) {
  StartThreadState* state = reinterpret_cast<StartThreadState*>(arg);
  state->user_function(state->arg);
  delete state;
A
Abhishek Kona 已提交
1952
  return nullptr;
J
jorlow@chromium.org 已提交
1953 1954 1955 1956 1957 1958 1959 1960
}

void PosixEnv::StartThread(void (*function)(void* arg), void* arg) {
  pthread_t t;
  StartThreadState* state = new StartThreadState;
  state->user_function = function;
  state->arg = arg;
  PthreadCall("start thread",
A
Abhishek Kona 已提交
1961
              pthread_create(&t, nullptr,  &StartThreadWrapper, state));
1962
  PthreadCall("lock", pthread_mutex_lock(&mu_));
1963
  threads_to_join_.push_back(t);
1964
  PthreadCall("unlock", pthread_mutex_unlock(&mu_));
J
jorlow@chromium.org 已提交
1965 1966
}

L
Lei Jin 已提交
1967 1968 1969 1970 1971 1972 1973
void PosixEnv::WaitForJoin() {
  for (const auto tid : threads_to_join_) {
    pthread_join(tid, nullptr);
  }
  threads_to_join_.clear();
}

H
Hans Wennborg 已提交
1974
}  // namespace
J
jorlow@chromium.org 已提交
1975

M
Mayank Agarwal 已提交
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
std::string Env::GenerateUniqueId() {
  std::string uuid_file = "/proc/sys/kernel/random/uuid";
  if (FileExists(uuid_file)) {
    std::string uuid;
    Status s = ReadFileToString(this, uuid_file, &uuid);
    if (s.ok()) {
      return uuid;
    }
  }
  // Could not read uuid_file - generate uuid using "nanos-random"
  Random64 r(time(nullptr));
  uint64_t random_uuid_portion =
    r.Uniform(std::numeric_limits<uint64_t>::max());
  uint64_t nanos_uuid_portion = NowNanos();
  char uuid2[200];
K
kailiu 已提交
1991 1992 1993 1994 1995
  snprintf(uuid2,
           200,
           "%lx-%lx",
           (unsigned long)nanos_uuid_portion,
           (unsigned long)random_uuid_portion);
M
Mayank Agarwal 已提交
1996 1997 1998
  return uuid2;
}

J
jorlow@chromium.org 已提交
1999
Env* Env::Default() {
2000
  static PosixEnv default_env;
2001
  return &default_env;
J
jorlow@chromium.org 已提交
2002 2003
}

2004
}  // namespace rocksdb