io_win.cc 30.8 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 11
//
// 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 "port/win/io_win.h"

12
#include "monitoring/iostats_context_imp.h"
13
#include "util/aligned_buffer.h"
14
#include "util/coding.h"
15
#include "test_util/sync_point.h"
16 17 18 19

namespace rocksdb {
namespace port {

D
Dmitri Smirnov 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32
/*
* DirectIOHelper
*/
namespace {

const size_t kSectorSize = 512;

inline
bool IsPowerOfTwo(const size_t alignment) {
  return ((alignment) & (alignment - 1)) == 0;
}

inline
33
bool IsSectorAligned(const size_t off) {
D
Dmitri Smirnov 已提交
34 35 36 37 38 39 40 41 42 43
  return (off & (kSectorSize - 1)) == 0;
}

inline
bool IsAligned(size_t alignment, const void* ptr) {
  return ((uintptr_t(ptr)) & (alignment - 1)) == 0;
}
}


44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
std::string GetWindowsErrSz(DWORD err) {
  LPSTR lpMsgBuf;
  FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
    FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL, err,
    0,  // Default language
    reinterpret_cast<LPSTR>(&lpMsgBuf), 0, NULL);

  std::string Err = lpMsgBuf;
  LocalFree(lpMsgBuf);
  return Err;
}

// We preserve the original name of this interface to denote the original idea
// behind it.
// All reads happen by a specified offset and pwrite interface does not change
// the position of the file pointer. Judging from the man page and errno it does
// execute
// lseek atomically to return the position of the file back where it was.
// WriteFile() does not
// have this capability. Therefore, for both pread and pwrite the pointer is
// advanced to the next position
// which is fine for writes because they are (should be) sequential.
// Because all the reads/writes happen by the specified offset, the caller in
// theory should not
// rely on the current file offset.
70 71 72 73 74 75 76 77 78 79 80 81 82 83
Status pwrite(const WinFileData* file_data, const Slice& data,
  uint64_t offset, size_t& bytes_written) {

  Status s;
  bytes_written = 0;

  size_t num_bytes = data.size();
  if (num_bytes > std::numeric_limits<DWORD>::max()) {
    // May happen in 64-bit builds where size_t is 64-bits but
    // long is still 32-bit, but that's the API here at the moment
    return Status::InvalidArgument("num_bytes is too large for a single write: " +
          file_data->GetName());
  }

84 85 86 87 88 89 90
  OVERLAPPED overlapped = { 0 };
  ULARGE_INTEGER offsetUnion;
  offsetUnion.QuadPart = offset;

  overlapped.Offset = offsetUnion.LowPart;
  overlapped.OffsetHigh = offsetUnion.HighPart;

91
  DWORD bytesWritten = 0;
92

93 94 95 96 97
  if (FALSE == WriteFile(file_data->GetFileHandle(), data.data(), static_cast<DWORD>(num_bytes),
    &bytesWritten, &overlapped)) {
    auto lastError = GetLastError();
    s = IOErrorFromWindowsError("WriteFile failed: " + file_data->GetName(),
      lastError);
98
  } else {
99
    bytes_written = bytesWritten;
100 101
  }

102
  return s;
103 104 105
}

// See comments for pwrite above
106 107 108 109 110 111 112 113 114 115 116
Status pread(const WinFileData* file_data, char* src, size_t num_bytes,
  uint64_t offset, size_t& bytes_read) {

  Status s;
  bytes_read = 0;

  if (num_bytes > std::numeric_limits<DWORD>::max()) {
    return Status::InvalidArgument("num_bytes is too large for a single read: " +
      file_data->GetName());
  }

117 118 119 120 121 122 123
  OVERLAPPED overlapped = { 0 };
  ULARGE_INTEGER offsetUnion;
  offsetUnion.QuadPart = offset;

  overlapped.Offset = offsetUnion.LowPart;
  overlapped.OffsetHigh = offsetUnion.HighPart;

124
  DWORD bytesRead = 0;
125

126 127 128 129 130 131 132 133
  if (FALSE == ReadFile(file_data->GetFileHandle(), src, static_cast<DWORD>(num_bytes),
    &bytesRead, &overlapped)) {
    auto lastError = GetLastError();
    // EOF is OK with zero bytes read
    if (lastError != ERROR_HANDLE_EOF) {
      s = IOErrorFromWindowsError("ReadFile failed: " + file_data->GetName(),
        lastError);
    }
134
  } else {
135
    bytes_read = bytesRead;
136 137
  }

138
  return s;
139 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 170 171 172 173 174 175 176 177 178 179 180 181 182
}

// SetFileInformationByHandle() is capable of fast pre-allocates.
// However, this does not change the file end position unless the file is
// truncated and the pre-allocated space is not considered filled with zeros.
Status fallocate(const std::string& filename, HANDLE hFile,
  uint64_t to_size) {
  Status status;

  FILE_ALLOCATION_INFO alloc_info;
  alloc_info.AllocationSize.QuadPart = to_size;

  if (!SetFileInformationByHandle(hFile, FileAllocationInfo, &alloc_info,
    sizeof(FILE_ALLOCATION_INFO))) {
    auto lastError = GetLastError();
    status = IOErrorFromWindowsError(
      "Failed to pre-allocate space: " + filename, lastError);
  }

  return status;
}

Status ftruncate(const std::string& filename, HANDLE hFile,
  uint64_t toSize) {
  Status status;

  FILE_END_OF_FILE_INFO end_of_file;
  end_of_file.EndOfFile.QuadPart = toSize;

  if (!SetFileInformationByHandle(hFile, FileEndOfFileInfo, &end_of_file,
    sizeof(FILE_END_OF_FILE_INFO))) {
    auto lastError = GetLastError();
    status = IOErrorFromWindowsError("Failed to Set end of file: " + filename,
      lastError);
  }

  return status;
}

size_t GetUniqueIdFromFile(HANDLE hFile, char* id, size_t max_size) {

  if (max_size < kMaxVarint64Length * 3) {
    return 0;
  }
D
Dmitri Smirnov 已提交
183 184 185 186 187
#if (_WIN32_WINNT == _WIN32_WINNT_VISTA)
  // MINGGW as defined by CMake file.
  // yuslepukhin: I hate the guts of the above macros.
  // This impl does not guarantee uniqueness everywhere
  // is reasonably good
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  BY_HANDLE_FILE_INFORMATION FileInfo;

  BOOL result = GetFileInformationByHandle(hFile, &FileInfo);

  TEST_SYNC_POINT_CALLBACK("GetUniqueIdFromFile:FS_IOC_GETVERSION", &result);

  if (!result) {
    return 0;
  }

  char* rid = id;
  rid = EncodeVarint64(rid, uint64_t(FileInfo.dwVolumeSerialNumber));
  rid = EncodeVarint64(rid, uint64_t(FileInfo.nFileIndexHigh));
  rid = EncodeVarint64(rid, uint64_t(FileInfo.nFileIndexLow));

  assert(rid >= id);
  return static_cast<size_t>(rid - id);
D
Dmitri Smirnov 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
#else
  FILE_ID_INFO FileInfo;
  BOOL result = GetFileInformationByHandleEx(hFile, FileIdInfo, &FileInfo,
    sizeof(FileInfo));

  TEST_SYNC_POINT_CALLBACK("GetUniqueIdFromFile:FS_IOC_GETVERSION", &result);

  if (!result) {
    return 0;
  }

  static_assert(sizeof(uint64_t) == sizeof(FileInfo.VolumeSerialNumber),
    "Wrong sizeof expectations");
  // FileId.Identifier is an array of 16 BYTEs, we encode them as two uint64_t
  static_assert(sizeof(uint64_t) * 2 == sizeof(FileInfo.FileId.Identifier),
    "Wrong sizeof expectations");

  char* rid = id;
  rid = EncodeVarint64(rid, uint64_t(FileInfo.VolumeSerialNumber));
  uint64_t* file_id = reinterpret_cast<uint64_t*>(&FileInfo.FileId.Identifier[0]);
  rid = EncodeVarint64(rid, *file_id);
  ++file_id;
  rid = EncodeVarint64(rid, *file_id);

  assert(rid >= id);
  return static_cast<size_t>(rid - id);
#endif
232 233
}

234 235 236
////////////////////////////////////////////////////////////////////////////////////////////////////
// WinMmapReadableFile

A
Aaron Gao 已提交
237 238 239 240 241 242 243 244
WinMmapReadableFile::WinMmapReadableFile(const std::string& fileName,
                                         HANDLE hFile, HANDLE hMap,
                                         const void* mapped_region,
                                         size_t length)
    : WinFileData(fileName, hFile, false /* use_direct_io */),
      hMap_(hMap),
      mapped_region_(mapped_region),
      length_(length) {}
245 246

WinMmapReadableFile::~WinMmapReadableFile() {
T
Tamir Duberstein 已提交
247 248
  BOOL ret __attribute__((__unused__));
  ret = ::UnmapViewOfFile(mapped_region_);
O
Orgad Shaneh 已提交
249 250 251 252
  assert(ret);

  ret = ::CloseHandle(hMap_);
  assert(ret);
253 254 255 256 257 258 259 260
}

Status WinMmapReadableFile::Read(uint64_t offset, size_t n, Slice* result,
  char* scratch) const {
  Status s;

  if (offset > length_) {
    *result = Slice();
261
    return IOError(filename_, EINVAL);
262
  } else if (offset + n > length_) {
263
    n = length_ - static_cast<size_t>(offset);
264 265 266 267 268 269 270 271 272 273 274 275 276 277
  }
  *result =
    Slice(reinterpret_cast<const char*>(mapped_region_)+offset, n);
  return s;
}

Status WinMmapReadableFile::InvalidateCache(size_t offset, size_t length) {
  return Status::OK();
}

size_t WinMmapReadableFile::GetUniqueId(char* id, size_t max_size) const {
  return GetUniqueIdFromFile(hFile_, id, max_size);
}

278 279 280 281
///////////////////////////////////////////////////////////////////////////////
/// WinMmapFile


282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
// Can only truncate or reserve to a sector size aligned if
// used on files that are opened with Unbuffered I/O
Status WinMmapFile::TruncateFile(uint64_t toSize) {
  return ftruncate(filename_, hFile_, toSize);
}

Status WinMmapFile::UnmapCurrentRegion() {
  Status status;

  if (mapped_begin_ != nullptr) {
    if (!::UnmapViewOfFile(mapped_begin_)) {
      status = IOErrorFromWindowsError(
        "Failed to unmap file view: " + filename_, GetLastError());
    }

    // Move on to the next portion of the file
    file_offset_ += view_size_;

    // UnmapView automatically sends data to disk but not the metadata
    // which is good and provides some equivalent of fdatasync() on Linux
    // therefore, we donot need separate flag for metadata
    mapped_begin_ = nullptr;
    mapped_end_ = nullptr;
    dst_ = nullptr;

    last_sync_ = nullptr;
    pending_sync_ = false;
  }

  return status;
}

Status WinMmapFile::MapNewRegion() {

  Status status;

  assert(mapped_begin_ == nullptr);

320
  size_t minDiskSize = static_cast<size_t>(file_offset_) + view_size_;
321 322 323 324 325 326 327 328 329 330 331 332 333

  if (minDiskSize > reserved_size_) {
    status = Allocate(file_offset_, view_size_);
    if (!status.ok()) {
      return status;
    }
  }

  // Need to remap
  if (hMap_ == NULL || reserved_size_ > mapping_size_) {

    if (hMap_ != NULL) {
      // Unmap the previous one
T
Tamir Duberstein 已提交
334
      BOOL ret __attribute__((__unused__));
335
      ret = ::CloseHandle(hMap_);
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
      assert(ret);
      hMap_ = NULL;
    }

    ULARGE_INTEGER mappingSize;
    mappingSize.QuadPart = reserved_size_;

    hMap_ = CreateFileMappingA(
      hFile_,
      NULL,                  // Security attributes
      PAGE_READWRITE,        // There is not a write only mode for mapping
      mappingSize.HighPart,  // Enable mapping the whole file but the actual
      // amount mapped is determined by MapViewOfFile
      mappingSize.LowPart,
      NULL);  // Mapping name

    if (NULL == hMap_) {
      return IOErrorFromWindowsError(
        "WindowsMmapFile failed to create file mapping for: " + filename_,
        GetLastError());
    }

    mapping_size_ = reserved_size_;
  }

  ULARGE_INTEGER offset;
  offset.QuadPart = file_offset_;

  // View must begin at the granularity aligned offset
  mapped_begin_ = reinterpret_cast<char*>(
    MapViewOfFileEx(hMap_, FILE_MAP_WRITE, offset.HighPart, offset.LowPart,
    view_size_, NULL));

  if (!mapped_begin_) {
    status = IOErrorFromWindowsError(
      "WindowsMmapFile failed to map file view: " + filename_,
      GetLastError());
  } else {
    mapped_end_ = mapped_begin_ + view_size_;
    dst_ = mapped_begin_;
    last_sync_ = mapped_begin_;
    pending_sync_ = false;
  }
  return status;
}

Status WinMmapFile::PreallocateInternal(uint64_t spaceToReserve) {
  return fallocate(filename_, hFile_, spaceToReserve);
}

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
WinMmapFile::WinMmapFile(const std::string& fname, HANDLE hFile,
                         size_t page_size, size_t allocation_granularity,
                         const EnvOptions& options)
    : WinFileData(fname, hFile, false),
      WritableFile(options),
      hMap_(NULL),
      page_size_(page_size),
      allocation_granularity_(allocation_granularity),
      reserved_size_(0),
      mapping_size_(0),
      view_size_(0),
      mapped_begin_(nullptr),
      mapped_end_(nullptr),
      dst_(nullptr),
      last_sync_(nullptr),
      file_offset_(0),
      pending_sync_(false) {
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 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 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  // Allocation granularity must be obtained from GetSystemInfo() and must be
  // a power of two.
  assert(allocation_granularity > 0);
  assert((allocation_granularity & (allocation_granularity - 1)) == 0);

  assert(page_size > 0);
  assert((page_size & (page_size - 1)) == 0);

  // Only for memory mapped writes
  assert(options.use_mmap_writes);

  // View size must be both the multiple of allocation_granularity AND the
  // page size and the granularity is usually a multiple of a page size.
  const size_t viewSize = 32 * 1024; // 32Kb similar to the Windows File Cache in buffered mode
  view_size_ = Roundup(viewSize, allocation_granularity_);
}

WinMmapFile::~WinMmapFile() {
  if (hFile_) {
    this->Close();
  }
}

Status WinMmapFile::Append(const Slice& data) {
  const char* src = data.data();
  size_t left = data.size();

  while (left > 0) {
    assert(mapped_begin_ <= dst_);
    size_t avail = mapped_end_ - dst_;

    if (avail == 0) {
      Status s = UnmapCurrentRegion();
      if (s.ok()) {
        s = MapNewRegion();
      }

      if (!s.ok()) {
        return s;
      }
    } else {
      size_t n = std::min(left, avail);
      memcpy(dst_, src, n);
      dst_ += n;
      src += n;
      left -= n;
      pending_sync_ = true;
    }
  }

  // Now make sure that the last partial page is padded with zeros if needed
  size_t bytesToPad = Roundup(size_t(dst_), page_size_) - size_t(dst_);
  if (bytesToPad > 0) {
    memset(dst_, 0, bytesToPad);
  }

  return Status::OK();
}

// Means Close() will properly take care of truncate
// and it does not need any additional information
Status WinMmapFile::Truncate(uint64_t size) {
  return Status::OK();
}

Status WinMmapFile::Close() {
  Status s;

  assert(NULL != hFile_);

  // We truncate to the precise size so no
  // uninitialized data at the end. SetEndOfFile
  // which we use does not write zeros and it is good.
  uint64_t targetSize = GetFileSize();

  if (mapped_begin_ != nullptr) {
    // Sync before unmapping to make sure everything
    // is on disk and there is not a lazy writing
    // so we are deterministic with the tests
    Sync();
    s = UnmapCurrentRegion();
  }

  if (NULL != hMap_) {
    BOOL ret = ::CloseHandle(hMap_);
    if (!ret && s.ok()) {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError(
        "Failed to Close mapping for file: " + filename_, lastError);
    }

    hMap_ = NULL;
  }

  if (hFile_ != NULL) {

    TruncateFile(targetSize);

    BOOL ret = ::CloseHandle(hFile_);
    hFile_ = NULL;

    if (!ret && s.ok()) {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError(
        "Failed to close file map handle: " + filename_, lastError);
    }
  }

  return s;
}

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

// Flush only data
Status WinMmapFile::Sync() {
  Status s;

  // Some writes occurred since last sync
  if (dst_ > last_sync_) {
    assert(mapped_begin_);
    assert(dst_);
    assert(dst_ > mapped_begin_);
    assert(dst_ < mapped_end_);

    size_t page_begin =
      TruncateToPageBoundary(page_size_, last_sync_ - mapped_begin_);
    size_t page_end =
      TruncateToPageBoundary(page_size_, dst_ - mapped_begin_ - 1);

    // Flush only the amount of that is a multiple of pages
    if (!::FlushViewOfFile(mapped_begin_ + page_begin,
      (page_end - page_begin) + page_size_)) {
      s = IOErrorFromWindowsError("Failed to FlushViewOfFile: " + filename_,
        GetLastError());
    } else {
      last_sync_ = dst_;
    }
  }

  return s;
}

/**
* Flush data as well as metadata to stable storage.
*/
Status WinMmapFile::Fsync() {
  Status s = Sync();

  // Flush metadata
  if (s.ok() && pending_sync_) {
    if (!::FlushFileBuffers(hFile_)) {
      s = IOErrorFromWindowsError("Failed to FlushFileBuffers: " + filename_,
        GetLastError());
    }
    pending_sync_ = false;
  }

  return s;
}

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

Status WinMmapFile::InvalidateCache(size_t offset, size_t length) {
  return Status::OK();
}

Status WinMmapFile::Allocate(uint64_t offset, uint64_t len) {
  Status status;
  TEST_KILL_RANDOM("WinMmapFile::Allocate", rocksdb_kill_odds);

  // Make sure that we reserve an aligned amount of space
  // since the reservation block size is driven outside so we want
  // to check if we are ok with reservation here
584
  size_t spaceToReserve = Roundup(static_cast<size_t>(offset + len), view_size_);
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
  // Nothing to do
  if (spaceToReserve <= reserved_size_) {
    return status;
  }

  IOSTATS_TIMER_GUARD(allocate_nanos);
  status = PreallocateInternal(spaceToReserve);
  if (status.ok()) {
    reserved_size_ = spaceToReserve;
  }
  return status;
}

size_t WinMmapFile::GetUniqueId(char* id, size_t max_size) const {
  return GetUniqueIdFromFile(hFile_, id, max_size);
}

602 603 604
//////////////////////////////////////////////////////////////////////////////////
// WinSequentialFile

605
WinSequentialFile::WinSequentialFile(const std::string& fname, HANDLE f,
A
Aaron Gao 已提交
606 607
                                     const EnvOptions& options)
    : WinFileData(fname, f, options.use_direct_reads) {}
608 609

WinSequentialFile::~WinSequentialFile() {
610
  assert(hFile_ != INVALID_HANDLE_VALUE);
611 612 613 614 615 616
}

Status WinSequentialFile::Read(size_t n, Slice* result, char* scratch) {
  Status s;
  size_t r = 0;

617 618 619 620 621
  assert(result != nullptr);
  if (WinFileData::use_direct_io()) {
    return Status::NotSupported("Read() does not support direct_io");
  }

622
  // Windows ReadFile API accepts a DWORD.
623 624 625 626 627
  // While it is possible to read in a loop if n is too big
  // it is an unlikely case.
  if (n > std::numeric_limits<DWORD>::max()) {
    return Status::InvalidArgument("n is too big for a single ReadFile: "
      + filename_);
628 629 630 631
  }

  DWORD bytesToRead = static_cast<DWORD>(n); //cast is safe due to the check above
  DWORD bytesRead = 0;
632
  BOOL ret = ReadFile(hFile_, scratch, bytesToRead, &bytesRead, NULL);
633
  if (ret != FALSE) {
634 635
    r = bytesRead;
  } else {
636 637 638 639 640
    auto lastError = GetLastError();
    if (lastError != ERROR_HANDLE_EOF) {
      s = IOErrorFromWindowsError("ReadFile failed: " + filename_,
        lastError);
    }
641 642 643 644 645 646
  }

  *result = Slice(scratch, r);
  return s;
}

647 648 649
Status WinSequentialFile::PositionedReadInternal(char* src, size_t numBytes,
  uint64_t offset, size_t& bytes_read) const {
  return pread(this, src, numBytes, offset, bytes_read);
D
Dmitri Smirnov 已提交
650 651 652 653 654 655 656
}

Status WinSequentialFile::PositionedRead(uint64_t offset, size_t n, Slice* result,
  char* scratch) {

  Status s;

657 658
  if (!WinFileData::use_direct_io()) {
    return Status::NotSupported("This function is only used for direct_io");
D
Dmitri Smirnov 已提交
659 660
  }

661
  if (!IsSectorAligned(static_cast<size_t>(offset)) ||
662 663 664
      !IsSectorAligned(n)) {
      return Status::InvalidArgument(
        "WinSequentialFile::PositionedRead: offset is not properly aligned");
D
Dmitri Smirnov 已提交
665 666
  }

667
  size_t bytes_read = 0; // out param
668
  s = PositionedReadInternal(scratch, static_cast<size_t>(n), offset, bytes_read);
669
  *result = Slice(scratch, bytes_read);
D
Dmitri Smirnov 已提交
670 671 672 673
  return s;
}


674 675 676
Status WinSequentialFile::Skip(uint64_t n) {
  // Can't handle more than signed max as SetFilePointerEx accepts a signed 64-bit
  // integer. As such it is a highly unlikley case to have n so large.
677 678 679
  if (n > static_cast<uint64_t>(std::numeric_limits<LONGLONG>::max())) {
    return Status::InvalidArgument("n is too large for a single SetFilePointerEx() call" +
      filename_);
680 681 682
  }

  LARGE_INTEGER li;
683
  li.QuadPart = static_cast<LONGLONG>(n); //cast is safe due to the check above
684
  BOOL ret = SetFilePointerEx(hFile_, li, NULL, FILE_CURRENT);
685
  if (ret == FALSE) {
686 687 688
    auto lastError = GetLastError();
    return IOErrorFromWindowsError("Skip SetFilePointerEx():" + filename_, 
      lastError);
689 690 691 692 693 694 695 696
  }
  return Status::OK();
}

Status WinSequentialFile::InvalidateCache(size_t offset, size_t length) {
  return Status::OK();
}

697 698 699
//////////////////////////////////////////////////////////////////////////////////////////////////
/// WinRandomAccessBase

700
inline
701
Status WinRandomAccessImpl::PositionedReadInternal(char* src,
702
  size_t numBytes,
703 704 705
  uint64_t offset,
  size_t& bytes_read) const {
  return pread(file_base_, src, numBytes, offset, bytes_read);
706 707
}

708 709 710 711 712
inline
WinRandomAccessImpl::WinRandomAccessImpl(WinFileData* file_base,
  size_t alignment,
  const EnvOptions& options) :
    file_base_(file_base),
713
    alignment_(alignment) {
714

715 716 717
  assert(!options.use_mmap_reads);
}

718 719
inline
Status WinRandomAccessImpl::ReadImpl(uint64_t offset, size_t n, Slice* result,
720 721 722
  char* scratch) const {

  Status s;
723 724 725

  // Check buffer alignment
  if (file_base_->use_direct_io()) {
726
    if (!IsSectorAligned(static_cast<size_t>(offset)) ||
727 728 729
        !IsAligned(alignment_, scratch)) {
      return Status::InvalidArgument(
        "WinRandomAccessImpl::ReadImpl: offset or scratch is not properly aligned");
730 731
    }
  }
732 733 734 735 736 737

  if (n == 0) {
    *result = Slice(scratch, 0);
    return s;
  }

738 739 740
  size_t bytes_read = 0;
  s = PositionedReadInternal(scratch, n, offset, bytes_read);
  *result = Slice(scratch, bytes_read);
741 742 743
  return s;
}

744 745 746
///////////////////////////////////////////////////////////////////////////////////////////////////
/// WinRandomAccessFile

A
Aaron Gao 已提交
747 748 749 750 751
WinRandomAccessFile::WinRandomAccessFile(const std::string& fname, HANDLE hFile,
                                         size_t alignment,
                                         const EnvOptions& options)
    : WinFileData(fname, hFile, options.use_direct_reads),
      WinRandomAccessImpl(this, alignment, options) {}
752

753
WinRandomAccessFile::~WinRandomAccessFile() {
754 755
}

756 757 758
Status WinRandomAccessFile::Read(uint64_t offset, size_t n, Slice* result,
  char* scratch) const {
  return ReadImpl(offset, n, result, scratch);
759 760
}

761 762
Status WinRandomAccessFile::InvalidateCache(size_t offset, size_t length) {
  return Status::OK();
763 764
}

765 766 767 768
size_t WinRandomAccessFile::GetUniqueId(char* id, size_t max_size) const {
  return GetUniqueIdFromFile(GetFileHandle(), id, max_size);
}

D
Dmitri Smirnov 已提交
769 770 771 772
size_t WinRandomAccessFile::GetRequiredBufferAlignment() const {
  return GetAlignment();
}

773 774 775 776 777 778 779 780 781
/////////////////////////////////////////////////////////////////////////////
// WinWritableImpl
//

inline
Status WinWritableImpl::PreallocateInternal(uint64_t spaceToReserve) {
  return fallocate(file_data_->GetName(), file_data_->GetFileHandle(), spaceToReserve);
}

782
inline
783 784 785
WinWritableImpl::WinWritableImpl(WinFileData* file_data, size_t alignment)
  : file_data_(file_data),
  alignment_(alignment),
786
  next_write_offset_(0),
787
  reservedsize_(0) {
788 789 790 791 792 793 794 795 796 797 798

  // Query current position in case ReopenWritableFile is called
  // This position is only important for buffered writes
  // for unbuffered writes we explicitely specify the position.
  LARGE_INTEGER zero_move;
  zero_move.QuadPart = 0; // Do not move
  LARGE_INTEGER pos;
  pos.QuadPart = 0;
  BOOL ret = SetFilePointerEx(file_data_->GetFileHandle(), zero_move, &pos,
      FILE_CURRENT);
  // Querying no supped to fail
799
  if (ret != 0) {
800 801 802 803
    next_write_offset_ = pos.QuadPart;
  } else {
    assert(false);
  }
804 805
}

806
inline
807
Status WinWritableImpl::AppendImpl(const Slice& data) {
808

D
Dmitri Smirnov 已提交
809 810
  Status s;

811 812 813 814
  if (data.size() > std::numeric_limits<DWORD>::max()) {
    return Status::InvalidArgument("data is too long for a single write" + 
      file_data_->GetName());
  }
815

816
  size_t bytes_written = 0; // out param
817

818
  if (file_data_->use_direct_io()) {
D
Dmitri Smirnov 已提交
819 820
    // With no offset specified we are appending
    // to the end of the file
821
    assert(IsSectorAligned(next_write_offset_));
822
    if (!IsSectorAligned(data.size()) ||
823
        !IsAligned(static_cast<size_t>(GetAlignement()), data.data())) {
824 825
      s = Status::InvalidArgument(
        "WriteData must be page aligned, size must be sector aligned");
D
Dmitri Smirnov 已提交
826
    } else {
827
      s = pwrite(file_data_, data, next_write_offset_, bytes_written);
D
Dmitri Smirnov 已提交
828 829 830 831 832 833 834 835 836 837
    }
  } else {

    DWORD bytesWritten = 0;
    if (!WriteFile(file_data_->GetFileHandle(), data.data(),
      static_cast<DWORD>(data.size()), &bytesWritten, NULL)) {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError(
        "Failed to WriteFile: " + file_data_->GetName(),
        lastError);
838 839
    } else {
      bytes_written = bytesWritten;
D
Dmitri Smirnov 已提交
840
    }
841
  }
D
Dmitri Smirnov 已提交
842 843

  if(s.ok()) {
844 845 846 847 848 849 850 851 852
    if (bytes_written == data.size()) {
      // This matters for direct_io cases where
      // we rely on the fact that next_write_offset_
      // is sector aligned
      next_write_offset_ += bytes_written;
    } else {
      s = Status::IOError("Failed to write all bytes: " + 
        file_data_->GetName());
    }
853 854 855 856 857
  }

  return s;
}

858
inline
859
Status WinWritableImpl::PositionedAppendImpl(const Slice& data, uint64_t offset) {
D
Dmitri Smirnov 已提交
860

861
  if(file_data_->use_direct_io()) {
862
    if (!IsSectorAligned(static_cast<size_t>(offset)) ||
863
        !IsSectorAligned(data.size()) ||
864
        !IsAligned(static_cast<size_t>(GetAlignement()), data.data())) {
865 866 867
      return Status::InvalidArgument(
        "Data and offset must be page aligned, size must be sector aligned");
    }
D
Dmitri Smirnov 已提交
868 869
  }

870 871
  size_t bytes_written = 0;
  Status s = pwrite(file_data_, data, offset, bytes_written);
872

873 874 875 876 877 878 879 880 881 882 883
  if(s.ok()) {
    if (bytes_written == data.size()) {
      // For sequential write this would be simple
      // size extension by data.size()
      uint64_t write_end = offset + bytes_written;
      if (write_end >= next_write_offset_) {
        next_write_offset_ = write_end;
      }
    } else {
      s = Status::IOError("Failed to write all of the requested data: " +
        file_data_->GetName());
884
    }
885 886 887 888
  }
  return s;
}

889 890
inline
Status WinWritableImpl::TruncateImpl(uint64_t size) {
891 892 893 894 895 896

  // It is tempting to check for the size for sector alignment
  // but truncation may come at the end and there is not a requirement
  // for this to be sector aligned so long as we do not attempt to write
  // after that. The interface docs state that the behavior is undefined
  // in that case.
897 898
  Status s = ftruncate(file_data_->GetName(), file_data_->GetFileHandle(),
    size);
899

900
  if (s.ok()) {
901
    next_write_offset_ = size;
902 903 904 905
  }
  return s;
}

906
inline
907
Status WinWritableImpl::CloseImpl() {
908 909 910

  Status s;

911 912
  auto hFile = file_data_->GetFileHandle();
  assert(INVALID_HANDLE_VALUE != hFile);
913

914
  if (!::FlushFileBuffers(hFile)) {
915
    auto lastError = GetLastError();
916
    s = IOErrorFromWindowsError("FlushFileBuffers failed at Close() for: " +
917
      file_data_->GetName(),
918 919 920
      lastError);
  }

921
  if(!file_data_->CloseFile() && s.ok()) {
922
    auto lastError = GetLastError();
923
    s = IOErrorFromWindowsError("CloseHandle failed for: " + file_data_->GetName(),
924 925 926 927 928
      lastError);
  }
  return s;
}

929
inline
930
Status WinWritableImpl::SyncImpl() {
931
  Status s;
932
  if (!::FlushFileBuffers (file_data_->GetFileHandle())) {
933
    auto lastError = GetLastError();
A
Aaron Gao 已提交
934
    s = IOErrorFromWindowsError(
935
        "FlushFileBuffers failed at Sync() for: " + file_data_->GetName(), lastError);
936 937 938 939 940
  }
  return s;
}


941
inline
942
Status WinWritableImpl::AllocateImpl(uint64_t offset, uint64_t len) {
943 944 945 946 947 948
  Status status;
  TEST_KILL_RANDOM("WinWritableFile::Allocate", rocksdb_kill_odds);

  // Make sure that we reserve an aligned amount of space
  // since the reservation block size is driven outside so we want
  // to check if we are ok with reservation here
949
  size_t spaceToReserve = Roundup(static_cast<size_t>(offset + len), static_cast<size_t>(alignment_));
950 951 952 953 954 955 956 957 958 959 960 961 962
  // Nothing to do
  if (spaceToReserve <= reservedsize_) {
    return status;
  }

  IOSTATS_TIMER_GUARD(allocate_nanos);
  status = PreallocateInternal(spaceToReserve);
  if (status.ok()) {
    reservedsize_ = spaceToReserve;
  }
  return status;
}

963 964 965 966

////////////////////////////////////////////////////////////////////////////////
/// WinWritableFile

A
Aaron Gao 已提交
967 968 969 970
WinWritableFile::WinWritableFile(const std::string& fname, HANDLE hFile,
                                 size_t alignment, size_t /* capacity */,
                                 const EnvOptions& options)
    : WinFileData(fname, hFile, options.use_direct_writes),
971 972
      WinWritableImpl(this, alignment),
      WritableFile(options) {
973 974 975 976 977 978
  assert(!options.use_mmap_writes);
}

WinWritableFile::~WinWritableFile() {
}

A
Aaron Gao 已提交
979
// Indicates if the class makes use of direct I/O
980
bool WinWritableFile::use_direct_io() const { return WinFileData::use_direct_io(); }
981 982

size_t WinWritableFile::GetRequiredBufferAlignment() const {
983
  return static_cast<size_t>(GetAlignement());
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
}

Status WinWritableFile::Append(const Slice& data) {
  return AppendImpl(data);
}

Status WinWritableFile::PositionedAppend(const Slice& data, uint64_t offset) {
  return PositionedAppendImpl(data, offset);
}

// Need to implement this so the file is truncated correctly
// when buffered and unbuffered mode
Status WinWritableFile::Truncate(uint64_t size) {
  return TruncateImpl(size);
}

Status WinWritableFile::Close() {
  return CloseImpl();
}

  // write out the cached data to the OS cache
  // This is now taken care of the WritableFileWriter
Status WinWritableFile::Flush() {
  return Status::OK();
}

Status WinWritableFile::Sync() {
  return SyncImpl();
}

1014
Status WinWritableFile::Fsync() { return SyncImpl(); }
1015 1016

bool WinWritableFile::IsSyncThreadSafe() const { return true; }
1017 1018

uint64_t WinWritableFile::GetFileSize() {
1019
  return GetFileNextWriteOffset();
1020 1021 1022 1023 1024 1025
}

Status WinWritableFile::Allocate(uint64_t offset, uint64_t len) {
  return AllocateImpl(offset, len);
}

1026
size_t WinWritableFile::GetUniqueId(char* id, size_t max_size) const {
1027 1028 1029 1030 1031 1032
  return GetUniqueIdFromFile(GetFileHandle(), id, max_size);
}

/////////////////////////////////////////////////////////////////////////
/// WinRandomRWFile

A
Aaron Gao 已提交
1033 1034 1035 1036 1037 1038
WinRandomRWFile::WinRandomRWFile(const std::string& fname, HANDLE hFile,
                                 size_t alignment, const EnvOptions& options)
    : WinFileData(fname, hFile,
                  options.use_direct_reads && options.use_direct_writes),
      WinRandomAccessImpl(this, alignment, options),
      WinWritableImpl(this, alignment) {}
1039

1040
bool WinRandomRWFile::use_direct_io() const { return WinFileData::use_direct_io(); }
1041

1042
size_t WinRandomRWFile::GetRequiredBufferAlignment() const {
1043
  return static_cast<size_t>(GetAlignement());
1044 1045 1046 1047 1048 1049
}

Status WinRandomRWFile::Write(uint64_t offset, const Slice & data) {
  return PositionedAppendImpl(data, offset);
}

A
Aaron Gao 已提交
1050 1051
Status WinRandomRWFile::Read(uint64_t offset, size_t n, Slice* result,
                             char* scratch) const {
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
  return ReadImpl(offset, n, result, scratch);
}

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

Status WinRandomRWFile::Sync() {
  return SyncImpl();
}

Status WinRandomRWFile::Close() {
  return CloseImpl();
}

D
Dmitri Smirnov 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
//////////////////////////////////////////////////////////////////////////
/// WinMemoryMappedBufer
WinMemoryMappedBuffer::~WinMemoryMappedBuffer() {
  BOOL ret = FALSE;
  if (base_ != nullptr) {
    ret = ::UnmapViewOfFile(base_);
    assert(ret);
    base_ = nullptr;
  }
  if (map_handle_ != NULL && map_handle_ != INVALID_HANDLE_VALUE) {
    ret = ::CloseHandle(map_handle_);
    assert(ret);
    map_handle_ = NULL;
  }
  if (file_handle_ != NULL && file_handle_ != INVALID_HANDLE_VALUE) {
    ret = ::CloseHandle(file_handle_);
    assert(ret);
    file_handle_ = NULL;
  }
}

1088 1089 1090
//////////////////////////////////////////////////////////////////////////
/// WinDirectory

1091 1092
Status WinDirectory::Fsync() { return Status::OK(); }

D
Dmitri Smirnov 已提交
1093 1094 1095
size_t WinDirectory::GetUniqueId(char* id, size_t max_size) const {
  return GetUniqueIdFromFile(handle_, id, max_size);
}
1096 1097 1098
//////////////////////////////////////////////////////////////////////////
/// WinFileLock

1099
WinFileLock::~WinFileLock() {
T
Tamir Duberstein 已提交
1100
  BOOL ret __attribute__((__unused__));
1101
  ret = ::CloseHandle(hFile_);
1102 1103 1104 1105 1106
  assert(ret);
}

}
}