io_posix.cc 29.3 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
5 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.

#ifdef ROCKSDB_LIB_IO_POSIX
11
#include "env/io_posix.h"
S
sdong 已提交
12 13
#include <errno.h>
#include <fcntl.h>
K
krad 已提交
14
#include <algorithm>
S
sdong 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27
#if defined(OS_LINUX)
#include <linux/fs.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef OS_LINUX
#include <sys/statfs.h>
#include <sys/syscall.h>
28
#include <sys/sysmacros.h>
S
sdong 已提交
29
#endif
30 31
#include "env/posix_logger.h"
#include "monitoring/iostats_context_imp.h"
S
sdong 已提交
32 33 34 35 36
#include "port/port.h"
#include "rocksdb/slice.h"
#include "util/coding.h"
#include "util/string_util.h"
#include "util/sync_point.h"
37

S
Stream  
Shaohua Li 已提交
38 39 40 41 42
#if defined(OS_LINUX) && !defined(F_SET_RW_HINT)
#define F_LINUX_SPECIFIC_BASE 1024
#define F_SET_RW_HINT         (F_LINUX_SPECIFIC_BASE + 12)
#endif

43 44 45
namespace rocksdb {

// A wrapper for fadvise, if the platform doesn't support fadvise,
46
// it will simply return 0.
47 48 49 50
int Fadvise(int fd, off_t offset, size_t len, int advice) {
#ifdef OS_LINUX
  return posix_fadvise(fd, offset, len, advice);
#else
51 52 53 54
  (void)fd;
  (void)offset;
  (void)len;
  (void)advice;
55 56 57 58
  return 0;  // simply do nothing.
#endif
}

A
Aaron Gao 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
namespace {
size_t GetLogicalBufferSize(int __attribute__((__unused__)) fd) {
#ifdef OS_LINUX
  struct stat buf;
  int result = fstat(fd, &buf);
  if (result == -1) {
    return kDefaultPageSize;
  }
  if (major(buf.st_dev) == 0) {
    // Unnamed devices (e.g. non-device mounts), reserved as null device number.
    // These don't have an entry in /sys/dev/block/. Return a sensible default.
    return kDefaultPageSize;
  }

  // Reading queue/logical_block_size does not require special permissions.
  const int kBufferSize = 100;
  char path[kBufferSize];
  char real_path[PATH_MAX + 1];
  snprintf(path, kBufferSize, "/sys/dev/block/%u:%u", major(buf.st_dev),
           minor(buf.st_dev));
  if (realpath(path, real_path) == nullptr) {
    return kDefaultPageSize;
  }
  std::string device_dir(real_path);
  if (!device_dir.empty() && device_dir.back() == '/') {
    device_dir.pop_back();
  }
  // NOTE: sda3 does not have a `queue/` subdir, only the parent sda has it.
  // $ ls -al '/sys/dev/block/8:3'
  // lrwxrwxrwx. 1 root root 0 Jun 26 01:38 /sys/dev/block/8:3 ->
  // ../../block/sda/sda3
  size_t parent_end = device_dir.rfind('/', device_dir.length() - 1);
  if (parent_end == std::string::npos) {
    return kDefaultPageSize;
  }
  size_t parent_begin = device_dir.rfind('/', parent_end - 1);
  if (parent_begin == std::string::npos) {
    return kDefaultPageSize;
  }
  if (device_dir.substr(parent_begin + 1, parent_end - parent_begin - 1) !=
      "block") {
    device_dir = device_dir.substr(0, parent_end);
  }
  std::string fname = device_dir + "/queue/logical_block_size";
  FILE* fp;
  size_t size = 0;
  fp = fopen(fname.c_str(), "r");
  if (fp != nullptr) {
    char* line = nullptr;
    size_t len = 0;
    if (getline(&line, &len, fp) != -1) {
      sscanf(line, "%zu", &size);
    }
    free(line);
    fclose(fp);
  }
  if (size != 0 && (size & (size - 1)) == 0) {
    return size;
  }
#endif
  return kDefaultPageSize;
}
} //  namespace

K
krad 已提交
123 124 125
/*
 * DirectIOHelper
 */
126
#ifndef NDEBUG
K
krad 已提交
127 128
namespace {

A
Aaron Gao 已提交
129 130 131
bool IsSectorAligned(const size_t off, size_t sector_size) {
  return off % sector_size == 0;
}
K
krad 已提交
132

133 134
bool IsSectorAligned(const void* ptr, size_t sector_size) {
  return uintptr_t(ptr) % sector_size == 0;
K
krad 已提交
135 136 137
}

}
138
#endif
K
krad 已提交
139

140 141 142
/*
 * PosixSequentialFile
 */
A
Aaron Gao 已提交
143 144
PosixSequentialFile::PosixSequentialFile(const std::string& fname, FILE* file,
                                         int fd, const EnvOptions& options)
145
    : filename_(fname),
A
Aaron Gao 已提交
146 147
      file_(file),
      fd_(fd),
A
Aaron Gao 已提交
148 149
      use_direct_io_(options.use_direct_reads),
      logical_sector_size_(GetLogicalBufferSize(fd_)) {
A
Aaron Gao 已提交
150 151
  assert(!options.use_direct_reads || !options.use_mmap_reads);
}
152

A
Aaron Gao 已提交
153
PosixSequentialFile::~PosixSequentialFile() {
154
  if (!use_direct_io()) {
A
Aaron Gao 已提交
155 156 157 158 159 160 161
    assert(file_);
    fclose(file_);
  } else {
    assert(fd_);
    close(fd_);
  }
}
162 163

Status PosixSequentialFile::Read(size_t n, Slice* result, char* scratch) {
164
  assert(result != nullptr && !use_direct_io());
165 166 167 168 169 170 171 172 173 174 175 176 177 178
  Status s;
  size_t r = 0;
  do {
    r = fread_unlocked(scratch, 1, n, file_);
  } while (r == 0 && ferror(file_) && errno == EINTR);
  *result = Slice(scratch, r);
  if (r < n) {
    if (feof(file_)) {
      // We leave status as ok if we hit the end of the file
      // We also clear the error so that the reads can continue
      // if a new data is written to the file
      clearerr(file_);
    } else {
      // A partial read with an error: return a non-ok status
179
      s = IOError("While reading file sequentially", filename_, errno);
180 181
    }
  }
A
Aaron Gao 已提交
182 183 184 185 186
  return s;
}

Status PosixSequentialFile::PositionedRead(uint64_t offset, size_t n,
                                           Slice* result, char* scratch) {
187 188 189 190 191
  if (use_direct_io()) {
    assert(IsSectorAligned(offset, GetRequiredBufferAlignment()));
    assert(IsSectorAligned(n, GetRequiredBufferAlignment()));
    assert(IsSectorAligned(scratch, GetRequiredBufferAlignment()));
  }
A
Aaron Gao 已提交
192 193 194 195
  Status s;
  ssize_t r = -1;
  size_t left = n;
  char* ptr = scratch;
196
  assert(use_direct_io());
A
Aaron Gao 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  while (left > 0) {
    r = pread(fd_, ptr, left, static_cast<off_t>(offset));
    if (r <= 0) {
      if (r == -1 && errno == EINTR) {
        continue;
      }
      break;
    }
    ptr += r;
    offset += r;
    left -= r;
    if (r % static_cast<ssize_t>(GetRequiredBufferAlignment()) != 0) {
      // Bytes reads don't fill sectors. Should only happen at the end
      // of the file.
      break;
    }
213
  }
A
Aaron Gao 已提交
214 215
  if (r < 0) {
    // An error: return a non-ok status
216 217 218
    s = IOError(
        "While pread " + ToString(n) + " bytes from offset " + ToString(offset),
        filename_, errno);
A
Aaron Gao 已提交
219 220
  }
  *result = Slice(scratch, (r < 0) ? 0 : n - left);
221 222 223 224 225
  return s;
}

Status PosixSequentialFile::Skip(uint64_t n) {
  if (fseek(file_, static_cast<long int>(n), SEEK_CUR)) {
226 227
    return IOError("While fseek to skip " + ToString(n) + " bytes", filename_,
                   errno);
228 229 230 231 232 233
  }
  return Status::OK();
}

Status PosixSequentialFile::InvalidateCache(size_t offset, size_t length) {
#ifndef OS_LINUX
234 235
  (void)offset;
  (void)length;
236 237
  return Status::OK();
#else
238
  if (!use_direct_io()) {
A
Aaron Gao 已提交
239 240 241
    // free OS pages
    int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
    if (ret != 0) {
242 243 244
      return IOError("While fadvise NotNeeded offset " + ToString(offset) +
                         " len " + ToString(length),
                     filename_, errno);
A
Aaron Gao 已提交
245
    }
246
  }
K
krad 已提交
247
  return Status::OK();
A
Aaron Gao 已提交
248
#endif
K
krad 已提交
249 250 251 252 253
}

/*
 * PosixRandomAccessFile
 */
254
#if defined(OS_LINUX)
K
krad 已提交
255
size_t PosixHelper::GetUniqueIdFromFile(int fd, char* id, size_t max_size) {
256 257 258 259 260 261
  if (max_size < kMaxVarint64Length * 3) {
    return 0;
  }

  struct stat buf;
  int result = fstat(fd, &buf);
K
krad 已提交
262
  assert(result != -1);
263 264 265 266 267 268
  if (result == -1) {
    return 0;
  }

  long version = 0;
  result = ioctl(fd, FS_IOC_GETVERSION, &version);
K
krad 已提交
269
  TEST_SYNC_POINT_CALLBACK("GetUniqueIdFromFile:FS_IOC_GETVERSION", &result);
270 271 272 273 274 275 276 277 278 279 280 281
  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);
}
K
krad 已提交
282 283
#endif

T
Tomas Kolda 已提交
284
#if defined(OS_MACOSX) || defined(OS_AIX)
K
krad 已提交
285
size_t PosixHelper::GetUniqueIdFromFile(int fd, char* id, size_t max_size) {
K
krad 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  if (max_size < kMaxVarint64Length * 3) {
    return 0;
  }

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

  char* rid = id;
  rid = EncodeVarint64(rid, buf.st_dev);
  rid = EncodeVarint64(rid, buf.st_ino);
  rid = EncodeVarint64(rid, buf.st_gen);
  assert(rid >= id);
  return static_cast<size_t>(rid - id);
302 303 304 305 306 307 308 309 310
}
#endif
/*
 * PosixRandomAccessFile
 *
 * pread() based random-access
 */
PosixRandomAccessFile::PosixRandomAccessFile(const std::string& fname, int fd,
                                             const EnvOptions& options)
A
Aaron Gao 已提交
311 312 313 314
    : filename_(fname),
      fd_(fd),
      use_direct_io_(options.use_direct_reads),
      logical_sector_size_(GetLogicalBufferSize(fd_)) {
A
Aaron Gao 已提交
315
  assert(!options.use_direct_reads || !options.use_mmap_reads);
316 317 318 319 320 321 322
  assert(!options.use_mmap_reads || sizeof(void*) < 8);
}

PosixRandomAccessFile::~PosixRandomAccessFile() { close(fd_); }

Status PosixRandomAccessFile::Read(uint64_t offset, size_t n, Slice* result,
                                   char* scratch) const {
323 324 325 326 327
  if (use_direct_io()) {
    assert(IsSectorAligned(offset, GetRequiredBufferAlignment()));
    assert(IsSectorAligned(n, GetRequiredBufferAlignment()));
    assert(IsSectorAligned(scratch, GetRequiredBufferAlignment()));
  }
328 329 330 331 332 333 334
  Status s;
  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) {
A
Aaron Gao 已提交
335
      if (r == -1 && errno == EINTR) {
336 337 338 339 340 341 342
        continue;
      }
      break;
    }
    ptr += r;
    offset += r;
    left -= r;
343
    if (use_direct_io() &&
A
Aaron Gao 已提交
344 345 346 347 348
        r % static_cast<ssize_t>(GetRequiredBufferAlignment()) != 0) {
      // Bytes reads don't fill sectors. Should only happen at the end
      // of the file.
      break;
    }
349 350 351
  }
  if (r < 0) {
    // An error: return a non-ok status
352 353 354
    s = IOError(
        "While pread offset " + ToString(offset) + " len " + ToString(n),
        filename_, errno);
355
  }
A
Aaron Gao 已提交
356
  *result = Slice(scratch, (r < 0) ? 0 : n - left);
357 358 359
  return s;
}

360 361 362 363 364 365 366 367 368 369 370 371 372 373
Status PosixRandomAccessFile::Prefetch(uint64_t offset, size_t n) {
  Status s;
  if (!use_direct_io()) {
    ssize_t r = 0;
#ifdef OS_LINUX
    r = readahead(fd_, offset, n);
#endif
#ifdef OS_MACOSX
    radvisory advice;
    advice.ra_offset = static_cast<off_t>(offset);
    advice.ra_count = static_cast<int>(n);
    r = fcntl(fd_, F_RDADVISE, &advice);
#endif
    if (r == -1) {
374 375 376
      s = IOError("While prefetching offset " + ToString(offset) + " len " +
                      ToString(n),
                  filename_, errno);
377 378 379 380 381
    }
  }
  return s;
}

T
Tomas Kolda 已提交
382
#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_AIX)
383
size_t PosixRandomAccessFile::GetUniqueId(char* id, size_t max_size) const {
K
krad 已提交
384
  return PosixHelper::GetUniqueIdFromFile(fd_, id, max_size);
385 386 387 388
}
#endif

void PosixRandomAccessFile::Hint(AccessPattern pattern) {
389
  if (use_direct_io()) {
A
Aaron Gao 已提交
390 391
    return;
  }
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  switch (pattern) {
    case NORMAL:
      Fadvise(fd_, 0, 0, POSIX_FADV_NORMAL);
      break;
    case RANDOM:
      Fadvise(fd_, 0, 0, POSIX_FADV_RANDOM);
      break;
    case SEQUENTIAL:
      Fadvise(fd_, 0, 0, POSIX_FADV_SEQUENTIAL);
      break;
    case WILLNEED:
      Fadvise(fd_, 0, 0, POSIX_FADV_WILLNEED);
      break;
    case DONTNEED:
      Fadvise(fd_, 0, 0, POSIX_FADV_DONTNEED);
      break;
    default:
      assert(false);
      break;
  }
}

Status PosixRandomAccessFile::InvalidateCache(size_t offset, size_t length) {
415
  if (use_direct_io()) {
A
Aaron Gao 已提交
416 417
    return Status::OK();
  }
418
#ifndef OS_LINUX
419 420
  (void)offset;
  (void)length;
421 422 423 424 425 426 427
  return Status::OK();
#else
  // free OS pages
  int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
  if (ret == 0) {
    return Status::OK();
  }
428 429 430
  return IOError("While fadvise NotNeeded offset " + ToString(offset) +
                     " len " + ToString(length),
                 filename_, errno);
431 432 433 434 435 436 437 438 439 440 441 442 443 444
#endif
}

/*
 * PosixMmapReadableFile
 *
 * mmap() based random-access
 */
// base[0,length-1] contains the mmapped contents of the file.
PosixMmapReadableFile::PosixMmapReadableFile(const int fd,
                                             const std::string& fname,
                                             void* base, size_t length,
                                             const EnvOptions& options)
    : fd_(fd), filename_(fname), mmapped_region_(base), length_(length) {
445 446 447
#ifdef NDEBUG
  (void)options;
#endif
448 449
  fd_ = fd_ + 0;  // suppress the warning for used variables
  assert(options.use_mmap_reads);
A
Aaron Gao 已提交
450
  assert(!options.use_direct_reads);
451 452 453 454 455 456 457 458
}

PosixMmapReadableFile::~PosixMmapReadableFile() {
  int ret = munmap(mmapped_region_, length_);
  if (ret != 0) {
    fprintf(stdout, "failed to munmap %p length %" ROCKSDB_PRIszt " \n",
            mmapped_region_, length_);
  }
459
  close(fd_);
460 461 462
}

Status PosixMmapReadableFile::Read(uint64_t offset, size_t n, Slice* result,
A
Andrew Kryczka 已提交
463
                                   char* /*scratch*/) const {
464 465 466
  Status s;
  if (offset > length_) {
    *result = Slice();
467 468 469
    return IOError("While mmap read offset " + ToString(offset) +
                       " larger than file length " + ToString(length_),
                   filename_, EINVAL);
470 471 472 473 474 475 476 477 478
  } else if (offset + n > length_) {
    n = static_cast<size_t>(length_ - offset);
  }
  *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
  return s;
}

Status PosixMmapReadableFile::InvalidateCache(size_t offset, size_t length) {
#ifndef OS_LINUX
479 480
  (void)offset;
  (void)length;
481 482 483 484 485 486 487
  return Status::OK();
#else
  // free OS pages
  int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
  if (ret == 0) {
    return Status::OK();
  }
488 489 490
  return IOError("While fadvise not needed. Offset " + ToString(offset) +
                     " len" + ToString(length),
                 filename_, errno);
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
#endif
}

/*
 * PosixMmapFile
 *
 * 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.
 */
Status PosixMmapFile::UnmapCurrentRegion() {
  TEST_KILL_RANDOM("PosixMmapFile::UnmapCurrentRegion:0", rocksdb_kill_odds);
  if (base_ != nullptr) {
    int munmap_status = munmap(base_, limit_ - base_);
    if (munmap_status != 0) {
507
      return IOError("While munmap", filename_, munmap_status);
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    }
    file_offset_ += limit_ - base_;
    base_ = nullptr;
    limit_ = nullptr;
    last_sync_ = nullptr;
    dst_ = nullptr;

    // Increase the amount we map the next time, but capped at 1MB
    if (map_size_ < (1 << 20)) {
      map_size_ *= 2;
    }
  }
  return Status::OK();
}

Status PosixMmapFile::MapNewRegion() {
#ifdef ROCKSDB_FALLOCATE_PRESENT
  assert(base_ == nullptr);
  TEST_KILL_RANDOM("PosixMmapFile::UnmapCurrentRegion:0", rocksdb_kill_odds);
  // we can't fallocate with FALLOC_FL_KEEP_SIZE here
  if (allow_fallocate_) {
    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));
    }
  }

  TEST_KILL_RANDOM("PosixMmapFile::Append:1", rocksdb_kill_odds);
  void* ptr = mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_,
                   file_offset_);
  if (ptr == MAP_FAILED) {
    return Status::IOError("MMap failed on " + filename_);
  }
  TEST_KILL_RANDOM("PosixMmapFile::Append:2", rocksdb_kill_odds);

  base_ = reinterpret_cast<char*>(ptr);
  limit_ = base_ + map_size_;
  dst_ = base_;
  last_sync_ = base_;
  return Status::OK();
#else
  return Status::NotSupported("This platform doesn't support fallocate()");
#endif
}

Status PosixMmapFile::Msync() {
  if (dst_ == last_sync_) {
    return Status::OK();
  }
  // 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_;
  TEST_KILL_RANDOM("PosixMmapFile::Msync:0", rocksdb_kill_odds);
  if (msync(base_ + p1, p2 - p1 + page_size_, MS_SYNC) < 0) {
570
    return IOError("While msync", filename_, errno);
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
  }
  return Status::OK();
}

PosixMmapFile::PosixMmapFile(const std::string& fname, int fd, size_t page_size,
                             const EnvOptions& options)
    : filename_(fname),
      fd_(fd),
      page_size_(page_size),
      map_size_(Roundup(65536, page_size)),
      base_(nullptr),
      limit_(nullptr),
      dst_(nullptr),
      last_sync_(nullptr),
      file_offset_(0) {
#ifdef ROCKSDB_FALLOCATE_PRESENT
  allow_fallocate_ = options.allow_fallocate;
  fallocate_with_keep_size_ = options.fallocate_with_keep_size;
589 590
#else
  (void)options;
591 592 593
#endif
  assert((page_size & (page_size - 1)) == 0);
  assert(options.use_mmap_writes);
A
Aaron Gao 已提交
594
  assert(!options.use_direct_writes);
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
}

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

Status PosixMmapFile::Append(const Slice& data) {
  const char* src = data.data();
  size_t left = data.size();
  while (left > 0) {
    assert(base_ <= dst_);
    assert(dst_ <= limit_);
    size_t avail = limit_ - dst_;
    if (avail == 0) {
      Status s = UnmapCurrentRegion();
      if (!s.ok()) {
        return s;
      }
      s = MapNewRegion();
      if (!s.ok()) {
        return s;
      }
      TEST_KILL_RANDOM("PosixMmapFile::Append:0", rocksdb_kill_odds);
    }

    size_t n = (left <= avail) ? left : avail;
623
    assert(dst_);
624 625 626 627 628 629 630 631 632 633 634 635 636 637
    memcpy(dst_, src, n);
    dst_ += n;
    src += n;
    left -= n;
  }
  return Status::OK();
}

Status PosixMmapFile::Close() {
  Status s;
  size_t unused = limit_ - dst_;

  s = UnmapCurrentRegion();
  if (!s.ok()) {
638
    s = IOError("While closing mmapped file", filename_, errno);
639 640 641
  } else if (unused > 0) {
    // Trim the extra space at the end of the file
    if (ftruncate(fd_, file_offset_ - unused) < 0) {
642
      s = IOError("While ftruncating mmaped file", filename_, errno);
643 644 645 646 647
    }
  }

  if (close(fd_) < 0) {
    if (s.ok()) {
648
      s = IOError("While closing mmapped file", filename_, errno);
649 650 651 652 653 654 655 656 657 658 659 660 661
    }
  }

  fd_ = -1;
  base_ = nullptr;
  limit_ = nullptr;
  return s;
}

Status PosixMmapFile::Flush() { return Status::OK(); }

Status PosixMmapFile::Sync() {
  if (fdatasync(fd_) < 0) {
662
    return IOError("While fdatasync mmapped file", filename_, errno);
663 664 665 666 667 668 669 670 671 672
  }

  return Msync();
}

/**
 * Flush data as well as metadata to stable storage.
 */
Status PosixMmapFile::Fsync() {
  if (fsync(fd_) < 0) {
673
    return IOError("While fsync mmaped file", filename_, errno);
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
  }

  return Msync();
}

/**
 * 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.
 */
uint64_t PosixMmapFile::GetFileSize() {
  size_t used = dst_ - base_;
  return file_offset_ + used;
}

Status PosixMmapFile::InvalidateCache(size_t offset, size_t length) {
#ifndef OS_LINUX
691 692
  (void)offset;
  (void)length;
693 694 695 696 697 698 699
  return Status::OK();
#else
  // free OS pages
  int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
  if (ret == 0) {
    return Status::OK();
  }
700
  return IOError("While fadvise NotNeeded mmapped file", filename_, errno);
701 702 703
#endif
}

704
#ifdef ROCKSDB_FALLOCATE_PRESENT
705 706 707
Status PosixMmapFile::Allocate(uint64_t offset, uint64_t len) {
  assert(offset <= std::numeric_limits<off_t>::max());
  assert(len <= std::numeric_limits<off_t>::max());
708 709 710 711
  TEST_KILL_RANDOM("PosixMmapFile::Allocate:0", rocksdb_kill_odds);
  int alloc_status = 0;
  if (allow_fallocate_) {
    alloc_status = fallocate(
712 713
        fd_, fallocate_with_keep_size_ ? FALLOC_FL_KEEP_SIZE : 0,
          static_cast<off_t>(offset), static_cast<off_t>(len));
714 715 716 717
  }
  if (alloc_status == 0) {
    return Status::OK();
  } else {
718 719 720
    return IOError(
        "While fallocate offset " + ToString(offset) + " len " + ToString(len),
        filename_, errno);
721
  }
722
}
723
#endif
724 725 726 727 728 729 730 731

/*
 * PosixWritableFile
 *
 * Use posix write to write data to a file.
 */
PosixWritableFile::PosixWritableFile(const std::string& fname, int fd,
                                     const EnvOptions& options)
A
Aaron Gao 已提交
732
    : filename_(fname),
733
      use_direct_io_(options.use_direct_writes),
A
Aaron Gao 已提交
734
      fd_(fd),
A
Aaron Gao 已提交
735 736
      filesize_(0),
      logical_sector_size_(GetLogicalBufferSize(fd_)) {
737 738 739 740 741 742 743 744 745 746 747 748 749 750
#ifdef ROCKSDB_FALLOCATE_PRESENT
  allow_fallocate_ = options.allow_fallocate;
  fallocate_with_keep_size_ = options.fallocate_with_keep_size;
#endif
  assert(!options.use_mmap_writes);
}

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

Status PosixWritableFile::Append(const Slice& data) {
751 752 753 754
  if (use_direct_io()) {
    assert(IsSectorAligned(data.size(), GetRequiredBufferAlignment()));
    assert(IsSectorAligned(data.data(), GetRequiredBufferAlignment()));
  }
755 756 757 758 759 760 761 762
  const char* src = data.data();
  size_t left = data.size();
  while (left != 0) {
    ssize_t done = write(fd_, src, left);
    if (done < 0) {
      if (errno == EINTR) {
        continue;
      }
763
      return IOError("While appending to file", filename_, errno);
764 765 766 767 768 769 770 771
    }
    left -= done;
    src += done;
  }
  filesize_ += data.size();
  return Status::OK();
}

772
Status PosixWritableFile::PositionedAppend(const Slice& data, uint64_t offset) {
773 774 775 776 777
  if (use_direct_io()) {
    assert(IsSectorAligned(offset, GetRequiredBufferAlignment()));
    assert(IsSectorAligned(data.size(), GetRequiredBufferAlignment()));
    assert(IsSectorAligned(data.data(), GetRequiredBufferAlignment()));
  }
778 779 780 781 782 783 784 785 786
  assert(offset <= std::numeric_limits<off_t>::max());
  const char* src = data.data();
  size_t left = data.size();
  while (left != 0) {
    ssize_t done = pwrite(fd_, src, left, static_cast<off_t>(offset));
    if (done < 0) {
      if (errno == EINTR) {
        continue;
      }
787 788
      return IOError("While pwrite to file at offset " + ToString(offset),
                     filename_, errno);
789 790 791 792 793
    }
    left -= done;
    offset += done;
    src += done;
  }
A
Aaron Gao 已提交
794
  filesize_ = offset;
795 796 797
  return Status::OK();
}

A
Aaron Gao 已提交
798 799 800 801
Status PosixWritableFile::Truncate(uint64_t size) {
  Status s;
  int r = ftruncate(fd_, size);
  if (r < 0) {
802 803
    s = IOError("While ftruncate file to size " + ToString(size), filename_,
                errno);
A
Aaron Gao 已提交
804 805 806 807 808 809
  } else {
    filesize_ = size;
  }
  return s;
}

810 811 812 813 814 815 816 817 818 819
Status PosixWritableFile::Close() {
  Status s;

  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
    // NOTE(ljin): we probably don't want to surface failure as an IOError,
    // but it will be nice to log these errors.
T
Tamir Duberstein 已提交
820
    int dummy __attribute__((__unused__));
821
    dummy = ftruncate(fd_, filesize_);
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
#if defined(ROCKSDB_FALLOCATE_PRESENT) && !defined(TRAVIS)
    // 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.
    // TRAVIS - this code does not work on TRAVIS filesystems.
    // the FALLOC_FL_KEEP_SIZE option is expected to not change the size
    // of the file, but it does. Simple strace report will show that.
    // While we work with Travis-CI team to figure out if this is a
    // quirk of Docker/AUFS, we will comment this out.
839
    struct stat file_stats;
840
    int result = fstat(fd_, &file_stats);
841 842
    // After ftruncate, we check whether ftruncate has the correct behavior.
    // If not, we should hack it with FALLOC_FL_PUNCH_HOLE
843 844
    if (result == 0 &&
        (file_stats.st_size + file_stats.st_blksize - 1) /
845 846 847 848 849 850 851
            file_stats.st_blksize !=
        file_stats.st_blocks / (file_stats.st_blksize / 512)) {
      IOSTATS_TIMER_GUARD(allocate_nanos);
      if (allow_fallocate_) {
        fallocate(fd_, FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE, filesize_,
                  block_size * last_allocated_block - filesize_);
      }
852 853
    }
#endif
854 855 856
  }

  if (close(fd_) < 0) {
857
    s = IOError("While closing file after writing", filename_, errno);
858 859 860 861 862 863 864 865 866 867
  }
  fd_ = -1;
  return s;
}

// write out the cached data to the OS cache
Status PosixWritableFile::Flush() { return Status::OK(); }

Status PosixWritableFile::Sync() {
  if (fdatasync(fd_) < 0) {
868
    return IOError("While fdatasync", filename_, errno);
869 870 871 872 873 874
  }
  return Status::OK();
}

Status PosixWritableFile::Fsync() {
  if (fsync(fd_) < 0) {
875
    return IOError("While fsync", filename_, errno);
876 877 878 879 880 881 882 883
  }
  return Status::OK();
}

bool PosixWritableFile::IsSyncThreadSafe() const { return true; }

uint64_t PosixWritableFile::GetFileSize() { return filesize_; }

S
Stream  
Shaohua Li 已提交
884 885
void PosixWritableFile::SetWriteLifeTimeHint(Env::WriteLifeTimeHint hint) {
#ifdef OS_LINUX
886 887
// Suppress Valgrind "Unimplemented functionality" error.
#ifndef ROCKSDB_VALGRIND_RUN
S
Stream  
Shaohua Li 已提交
888 889 890 891 892 893
  if (hint == write_hint_) {
    return;
  }
  if (fcntl(fd_, F_SET_RW_HINT, &hint) == 0) {
    write_hint_ = hint;
  }
894 895
#else
  (void)hint;
896 897 898 899
#endif // ROCKSDB_VALGRIND_RUN
#else
  (void)hint;
#endif // OS_LINUX
S
Stream  
Shaohua Li 已提交
900 901
}

902
Status PosixWritableFile::InvalidateCache(size_t offset, size_t length) {
903
  if (use_direct_io()) {
A
Aaron Gao 已提交
904 905
    return Status::OK();
  }
906
#ifndef OS_LINUX
907 908
  (void)offset;
  (void)length;
909 910 911 912 913 914 915
  return Status::OK();
#else
  // free OS pages
  int ret = Fadvise(fd_, offset, length, POSIX_FADV_DONTNEED);
  if (ret == 0) {
    return Status::OK();
  }
916
  return IOError("While fadvise NotNeeded", filename_, errno);
917 918 919
#endif
}

920
#ifdef ROCKSDB_FALLOCATE_PRESENT
921 922 923
Status PosixWritableFile::Allocate(uint64_t offset, uint64_t len) {
  assert(offset <= std::numeric_limits<off_t>::max());
  assert(len <= std::numeric_limits<off_t>::max());
924 925 926 927 928
  TEST_KILL_RANDOM("PosixWritableFile::Allocate:0", rocksdb_kill_odds);
  IOSTATS_TIMER_GUARD(allocate_nanos);
  int alloc_status = 0;
  if (allow_fallocate_) {
    alloc_status = fallocate(
929 930
        fd_, fallocate_with_keep_size_ ? FALLOC_FL_KEEP_SIZE : 0,
        static_cast<off_t>(offset), static_cast<off_t>(len));
931 932 933 934
  }
  if (alloc_status == 0) {
    return Status::OK();
  } else {
935 936 937
    return IOError(
        "While fallocate offset " + ToString(offset) + " len " + ToString(len),
        filename_, errno);
938 939
  }
}
940
#endif
941

T
Tomas Kolda 已提交
942
#ifdef ROCKSDB_RANGESYNC_PRESENT
943 944 945 946 947
Status PosixWritableFile::RangeSync(uint64_t offset, uint64_t nbytes) {
  assert(offset <= std::numeric_limits<off_t>::max());
  assert(nbytes <= std::numeric_limits<off_t>::max());
  if (sync_file_range(fd_, static_cast<off_t>(offset),
      static_cast<off_t>(nbytes), SYNC_FILE_RANGE_WRITE) == 0) {
948 949
    return Status::OK();
  } else {
950 951 952
    return IOError("While sync_file_range offset " + ToString(offset) +
                       " bytes " + ToString(nbytes),
                   filename_, errno);
953 954
  }
}
T
Tomas Kolda 已提交
955
#endif
956

T
Tomas Kolda 已提交
957
#ifdef OS_LINUX
958
size_t PosixWritableFile::GetUniqueId(char* id, size_t max_size) const {
K
krad 已提交
959
  return PosixHelper::GetUniqueIdFromFile(fd_, id, max_size);
960
}
961
#endif
962

I
Islam AbdelRahman 已提交
963 964 965 966 967
/*
 * PosixRandomRWFile
 */

PosixRandomRWFile::PosixRandomRWFile(const std::string& fname, int fd,
A
Andrew Kryczka 已提交
968
                                     const EnvOptions& /*options*/)
I
Islam AbdelRahman 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    : filename_(fname), fd_(fd) {}

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

Status PosixRandomRWFile::Write(uint64_t offset, const Slice& data) {
  const char* src = data.data();
  size_t left = data.size();
  while (left != 0) {
    ssize_t done = pwrite(fd_, src, left, offset);
    if (done < 0) {
      // error while writing to file
      if (errno == EINTR) {
        // write was interrupted, try again.
        continue;
      }
988 989 990
      return IOError(
          "While write random read/write file at offset " + ToString(offset),
          filename_, errno);
I
Islam AbdelRahman 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    }

    // Wrote `done` bytes
    left -= done;
    offset += done;
    src += done;
  }

  return Status::OK();
}

Status PosixRandomRWFile::Read(uint64_t offset, size_t n, Slice* result,
                               char* scratch) const {
  size_t left = n;
  char* ptr = scratch;
  while (left > 0) {
    ssize_t done = pread(fd_, ptr, left, offset);
    if (done < 0) {
      // error while reading from file
      if (errno == EINTR) {
        // read was interrupted, try again.
        continue;
      }
1014 1015 1016
      return IOError("While reading random read/write file offset " +
                         ToString(offset) + " len " + ToString(n),
                     filename_, errno);
I
Islam AbdelRahman 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    } else if (done == 0) {
      // Nothing more to read
      break;
    }

    // Read `done` bytes
    ptr += done;
    offset += done;
    left -= done;
  }

  *result = Slice(scratch, n - left);
  return Status::OK();
}

Status PosixRandomRWFile::Flush() { return Status::OK(); }

Status PosixRandomRWFile::Sync() {
  if (fdatasync(fd_) < 0) {
1036
    return IOError("While fdatasync random read/write file", filename_, errno);
I
Islam AbdelRahman 已提交
1037 1038 1039 1040 1041 1042
  }
  return Status::OK();
}

Status PosixRandomRWFile::Fsync() {
  if (fsync(fd_) < 0) {
1043
    return IOError("While fsync random read/write file", filename_, errno);
I
Islam AbdelRahman 已提交
1044 1045 1046 1047 1048 1049
  }
  return Status::OK();
}

Status PosixRandomRWFile::Close() {
  if (close(fd_) < 0) {
1050
    return IOError("While close random read/write file", filename_, errno);
I
Islam AbdelRahman 已提交
1051 1052 1053 1054 1055
  }
  fd_ = -1;
  return Status::OK();
}

1056 1057
PosixMemoryMappedFileBuffer::~PosixMemoryMappedFileBuffer() {
  // TODO should have error handling though not much we can do...
D
Dmitri Smirnov 已提交
1058
  munmap(this->base_, length_);
1059 1060
}

K
krad 已提交
1061 1062 1063 1064
/*
 * PosixDirectory
 */

1065 1066 1067
PosixDirectory::~PosixDirectory() { close(fd_); }

Status PosixDirectory::Fsync() {
T
Tomas Kolda 已提交
1068
#ifndef OS_AIX
1069
  if (fsync(fd_) == -1) {
1070
    return IOError("While fsync", "a directory", errno);
1071
  }
T
Tomas Kolda 已提交
1072
#endif
1073 1074
  return Status::OK();
}
1075 1076
}  // namespace rocksdb
#endif