env_win.cc 68.3 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
D
Dmitri Smirnov 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
//  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.
//
// 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 <algorithm>
#include <deque>
#include <thread>
#include <ctime>

#include <errno.h>
#include <process.h>
#include <io.h>
#include <direct.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "rocksdb/env.h"
#include "rocksdb/slice.h"

#include "port/port.h"
#include "port/dirent.h"
#include "port/win/win_logger.h"

#include "util/random.h"
#include "util/iostats_context_imp.h"
#include "util/rate_limiter.h"
32
#include "util/sync_point.h"
33
#include "util/aligned_buffer.h"
D
Dmitri Smirnov 已提交
34 35 36 37

#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"

S
sdong 已提交
38
#include <Rpc.h>  // For UUID generation
D
Dmitri Smirnov 已提交
39 40
#include <Windows.h>

S
sdong 已提交
41
namespace rocksdb {
D
Dmitri Smirnov 已提交
42 43 44

std::string GetWindowsErrSz(DWORD err) {
  LPSTR lpMsgBuf;
S
sdong 已提交
45 46 47 48 49
  FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                     FORMAT_MESSAGE_IGNORE_INSERTS,
                 NULL, err,
                 0,  // Default language
                 reinterpret_cast<LPSTR>(&lpMsgBuf), 0, NULL);
D
Dmitri Smirnov 已提交
50 51 52 53 54 55

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

S
sdong 已提交
56
namespace {
D
Dmitri Smirnov 已提交
57 58 59 60 61 62 63

const size_t c_OneMB = (1 << 20);

ThreadStatusUpdater* CreateThreadStatusUpdater() {
  return new ThreadStatusUpdater();
}

S
sdong 已提交
64
inline Status IOErrorFromWindowsError(const std::string& context, DWORD err) {
D
Dmitri Smirnov 已提交
65 66 67
  return Status::IOError(context, GetWindowsErrSz(err));
}

S
sdong 已提交
68
inline Status IOErrorFromLastWindowsError(const std::string& context) {
D
Dmitri Smirnov 已提交
69 70 71
  return IOErrorFromWindowsError(context, GetLastError());
}

S
sdong 已提交
72
inline Status IOError(const std::string& context, int err_number) {
D
Dmitri Smirnov 已提交
73 74 75 76 77 78 79 80 81 82
  return Status::IOError(context, strerror(err_number));
}

// TODO(sdong): temp logging. Need to help debugging. Remove it when
// the feature is proved to be stable.
inline void PrintThreadInfo(size_t thread_id, size_t terminatingId) {
  fprintf(stdout, "Bg thread %Iu terminates %Iu\n", thread_id, terminatingId);
}

// returns the ID of the current process
S
sdong 已提交
83
inline int current_process_id() { return _getpid(); }
D
Dmitri Smirnov 已提交
84 85 86 87 88

// RAII helpers for HANDLEs
const auto CloseHandleFunc = [](HANDLE h) { ::CloseHandle(h); };
typedef std::unique_ptr<void, decltype(CloseHandleFunc)> UniqueCloseHandlePtr;

S
sdong 已提交
89 90
// We preserve the original name of this interface to denote the original idea
// behind it.
D
Dmitri Smirnov 已提交
91
// All reads happen by a specified offset and pwrite interface does not change
S
sdong 已提交
92 93 94 95 96 97
// 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
D
Dmitri Smirnov 已提交
98
// which is fine for writes because they are (should be) sequential.
S
sdong 已提交
99 100
// Because all the reads/writes happen by the specified offset, the caller in
// theory should not
D
Dmitri Smirnov 已提交
101
// rely on the current file offset.
S
sdong 已提交
102 103
SSIZE_T pwrite(HANDLE hFile, const char* src, size_t numBytes,
               uint64_t offset) {
V
Vasili Svirski 已提交
104
  assert(numBytes <= std::numeric_limits<DWORD>::max());
S
sdong 已提交
105
  OVERLAPPED overlapped = {0};
D
Dmitri Smirnov 已提交
106 107 108 109 110 111 112 113 114 115
  ULARGE_INTEGER offsetUnion;
  offsetUnion.QuadPart = offset;

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

  SSIZE_T result = 0;

  unsigned long bytesWritten = 0;

V
Vasili Svirski 已提交
116 117
  if (FALSE == WriteFile(hFile, src, static_cast<DWORD>(numBytes), &bytesWritten,
    &overlapped)) {
S
sdong 已提交
118 119 120
    result = -1;
  } else {
    result = bytesWritten;
D
Dmitri Smirnov 已提交
121 122 123 124 125 126
  }

  return result;
}

// See comments for pwrite above
127 128
// PLEASE NOTE: hFile is expected to be an async handle 
// (i.e. opened with FILE_FLAG_OVERLAPPED)
S
sdong 已提交
129
SSIZE_T pread(HANDLE hFile, char* src, size_t numBytes, uint64_t offset) {
V
Vasili Svirski 已提交
130
  assert(numBytes <= std::numeric_limits<DWORD>::max());
S
sdong 已提交
131
  OVERLAPPED overlapped = {0};
D
Dmitri Smirnov 已提交
132 133 134 135 136
  ULARGE_INTEGER offsetUnion;
  offsetUnion.QuadPart = offset;

  overlapped.Offset = offsetUnion.LowPart;
  overlapped.OffsetHigh = offsetUnion.HighPart;
137 138 139 140 141
  overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

  if (NULL == overlapped.hEvent) {
    return -1;
  }
D
Dmitri Smirnov 已提交
142 143 144 145

  SSIZE_T result = 0;

  unsigned long bytesRead = 0;
146
  DWORD lastError = ERROR_SUCCESS;
D
Dmitri Smirnov 已提交
147

148 149 150
  if ((FALSE == ReadFile(hFile, src, static_cast<DWORD>(numBytes), &bytesRead,
    &overlapped)) && ((lastError = GetLastError()) != ERROR_IO_PENDING)) {
    result = (lastError == ERROR_HANDLE_EOF) ? 0 : -1;
S
sdong 已提交
151
  } else {
152 153 154 155 156 157 158 159
    if (lastError == ERROR_IO_PENDING) { //otherwise bytesRead already has the result
      if (FALSE == GetOverlappedResult(hFile, &overlapped, &bytesRead, TRUE)) {
        result = (GetLastError() == ERROR_HANDLE_EOF) ? 0 : -1;
      }
      else {
        result = bytesRead;
      }
    }
D
Dmitri Smirnov 已提交
160 161
  }

162 163
  CloseHandle(overlapped.hEvent);

D
Dmitri Smirnov 已提交
164 165 166
  return result;
}

S
sdong 已提交
167 168 169 170
// Note the below two do not set errno because they are used only here in this
// file
// on a Windows handle and, therefore, not necessary. Translating GetLastError()
// to errno
D
Dmitri Smirnov 已提交
171
// is a sad business
S
sdong 已提交
172
inline int fsync(HANDLE hFile) {
D
Dmitri Smirnov 已提交
173
  if (!FlushFileBuffers(hFile)) {
S
sdong 已提交
174
    return -1;
D
Dmitri Smirnov 已提交
175 176 177 178 179
  }

  return 0;
}

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.
S
sdong 已提交
183 184
inline Status fallocate(const std::string& filename, HANDLE hFile,
                        uint64_t to_size) {
D
Dmitri Smirnov 已提交
185 186 187 188 189
  Status status;

  FILE_ALLOCATION_INFO alloc_info;
  alloc_info.AllocationSize.QuadPart = to_size;

S
sdong 已提交
190 191
  if (!SetFileInformationByHandle(hFile, FileAllocationInfo, &alloc_info,
                                  sizeof(FILE_ALLOCATION_INFO))) {
D
Dmitri Smirnov 已提交
192
    auto lastError = GetLastError();
S
sdong 已提交
193 194
    status = IOErrorFromWindowsError(
        "Failed to pre-allocate space: " + filename, lastError);
D
Dmitri Smirnov 已提交
195 196 197 198 199
  }

  return status;
}

S
sdong 已提交
200 201
inline Status ftruncate(const std::string& filename, HANDLE hFile,
                        uint64_t toSize) {
D
Dmitri Smirnov 已提交
202 203 204 205 206
  Status status;

  FILE_END_OF_FILE_INFO end_of_file;
  end_of_file.EndOfFile.QuadPart = toSize;

S
sdong 已提交
207 208
  if (!SetFileInformationByHandle(hFile, FileEndOfFileInfo, &end_of_file,
                                  sizeof(FILE_END_OF_FILE_INFO))) {
D
Dmitri Smirnov 已提交
209
    auto lastError = GetLastError();
S
sdong 已提交
210 211
    status = IOErrorFromWindowsError("Failed to Set end of file: " + filename,
                                     lastError);
D
Dmitri Smirnov 已提交
212 213 214 215 216 217 218
  }

  return status;
}

// mmap() based random-access
class WinMmapReadableFile : public RandomAccessFile {
S
sdong 已提交
219 220 221
  const std::string fileName_;
  HANDLE hFile_;
  HANDLE hMap_;
D
Dmitri Smirnov 已提交
222

S
sdong 已提交
223 224
  const void* mapped_region_;
  const size_t length_;
D
Dmitri Smirnov 已提交
225

S
sdong 已提交
226
 public:
227
  // mapped_region_[0,length-1] contains the mmapped contents of the file.
S
sdong 已提交
228 229 230 231 232 233 234
  WinMmapReadableFile(const std::string& fileName, HANDLE hFile, HANDLE hMap,
                      const void* mapped_region, size_t length)
      : fileName_(fileName),
        hFile_(hFile),
        hMap_(hMap),
        mapped_region_(mapped_region),
        length_(length) {}
D
Dmitri Smirnov 已提交
235 236 237 238 239 240 241 242 243 244 245 246

  ~WinMmapReadableFile() {
    BOOL ret = ::UnmapViewOfFile(mapped_region_);
    assert(ret);

    ret = ::CloseHandle(hMap_);
    assert(ret);

    ret = ::CloseHandle(hFile_);
    assert(ret);
  }

S
sdong 已提交
247 248
  virtual Status Read(uint64_t offset, size_t n, Slice* result,
                      char* scratch) const override {
D
Dmitri Smirnov 已提交
249 250
    Status s;

251
    if (offset > length_) {
S
sdong 已提交
252
      *result = Slice();
253 254 255
      return IOError(fileName_, EINVAL);
    } else if (offset + n > length_) {
      n = length_ - offset;
D
Dmitri Smirnov 已提交
256
    }
257 258
    *result =
        Slice(reinterpret_cast<const char*>(mapped_region_) + offset, n);
D
Dmitri Smirnov 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271
    return s;
  }

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

// 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 WinMmapFile : public WritableFile {
S
sdong 已提交
272
 private:
D
Dmitri Smirnov 已提交
273
  const std::string filename_;
S
sdong 已提交
274 275
  HANDLE hFile_;
  HANDLE hMap_;
D
Dmitri Smirnov 已提交
276

S
sdong 已提交
277 278 279 280 281 282 283 284
  const size_t page_size_;  // We flush the mapping view in page_size
                            // increments. We may decide if this is a memory
                            // page size or SSD page size
  const size_t
      allocation_granularity_;  // View must start at such a granularity
  size_t mapping_size_;         // We want file mapping to be of a specific size
                                // because then the file is expandable
  size_t view_size_;            // How much memory to map into a view at a time
D
Dmitri Smirnov 已提交
285

S
sdong 已提交
286 287 288 289 290
  char* mapped_begin_;  // Must begin at the file offset that is aligned with
                        // allocation_granularity_
  char* mapped_end_;
  char* dst_;  // Where to write next  (in range [mapped_begin_,mapped_end_])
  char* last_sync_;  // Where have we synced up to
D
Dmitri Smirnov 已提交
291

S
sdong 已提交
292
  uint64_t file_offset_;  // Offset of mapped_begin_ in file
D
Dmitri Smirnov 已提交
293 294

  // Do we have unsynced writes?
S
sdong 已提交
295
  bool pending_sync_;
D
Dmitri Smirnov 已提交
296 297 298 299

  // Can only truncate or reserve to a sector size aligned if
  // used on files that are opened with Unbuffered I/O
  Status TruncateFile(uint64_t toSize) {
S
sdong 已提交
300
    return ftruncate(filename_, hFile_, toSize);
D
Dmitri Smirnov 已提交
301 302 303 304 305 306 307
  }

  // Can only truncate or reserve to a sector size aligned if
  // used on files that are opened with Unbuffered I/O
  // Normally it does not present a problem since in memory mapped files
  // we do not disable buffering
  Status ReserveFileSpace(uint64_t toSize) {
308
    IOSTATS_TIMER_GUARD(allocate_nanos);
D
Dmitri Smirnov 已提交
309 310 311 312 313 314 315 316
    return fallocate(filename_, hFile_, toSize);
  }

  Status UnmapCurrentRegion() {
    Status status;

    if (mapped_begin_ != nullptr) {
      if (!::UnmapViewOfFile(mapped_begin_)) {
S
sdong 已提交
317 318
        status = IOErrorFromWindowsError(
            "Failed to unmap file view: " + filename_, GetLastError());
D
Dmitri Smirnov 已提交
319 320 321 322 323 324 325
      }

      // 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
      pending_sync_ = false;
      mapped_begin_ = nullptr;
S
sdong 已提交
326 327 328
      mapped_end_ = nullptr;
      dst_ = nullptr;
      last_sync_ = nullptr;
D
Dmitri Smirnov 已提交
329 330 331 332 333

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

      // Increase the amount we map the next time, but capped at 1MB
S
sdong 已提交
334
      view_size_ *= 2;
D
Dmitri Smirnov 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347
      view_size_ = std::min(view_size_, c_OneMB);
    }

    return status;
  }

  Status MapNewRegion() {
    Status status;

    assert(mapped_begin_ == nullptr);

    size_t minMappingSize = file_offset_ + view_size_;

S
sdong 已提交
348 349
    // Check if we need to create a new mapping since we want to write beyond
    // the current one
D
Dmitri Smirnov 已提交
350
    // If the mapping view is now too short
S
sdong 已提交
351 352 353 354
    // CreateFileMapping will extend the size of the file automatically if the
    // mapping size is greater than
    // the current length of the file, which reserves the space and makes
    // writing faster, except, windows can not map an empty file.
D
Dmitri Smirnov 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    // Thus the first time around we must actually extend the file ourselves
    if (hMap_ == NULL || minMappingSize > mapping_size_) {
      if (NULL == hMap_) {
        // Creating mapping for the first time so reserve the space on disk
        status = ReserveFileSpace(minMappingSize);
        if (!status.ok()) {
          return status;
        }
      }

      if (hMap_) {
        // Unmap the previous one
        BOOL ret = ::CloseHandle(hMap_);
        assert(ret);
        hMap_ = NULL;
      }

S
sdong 已提交
372 373
      // Calculate the new mapping size which will hopefully reserve space for
      // several consecutive sliding views
D
Dmitri Smirnov 已提交
374 375
      // Query preallocation block size if set
      size_t preallocationBlockSize = 0;
S
sdong 已提交
376
      size_t lastAllocatedBlockSize = 0;  // Not used
D
Dmitri Smirnov 已提交
377 378 379
      GetPreallocationStatus(&preallocationBlockSize, &lastAllocatedBlockSize);

      if (preallocationBlockSize) {
S
sdong 已提交
380 381
        preallocationBlockSize =
            Roundup(preallocationBlockSize, allocation_granularity_);
D
Dmitri Smirnov 已提交
382 383 384 385 386 387 388 389 390 391 392
      } else {
        preallocationBlockSize = 2 * view_size_;
      }

      mapping_size_ += preallocationBlockSize;

      ULARGE_INTEGER mappingSize;
      mappingSize.QuadPart = mapping_size_;

      hMap_ = CreateFileMappingA(
          hFile_,
S
sdong 已提交
393 394 395 396
          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
D
Dmitri Smirnov 已提交
397 398 399
          mappingSize.LowPart,
          NULL);  // Mapping name

S
sdong 已提交
400 401 402 403 404
      if (NULL == hMap_) {
        return IOErrorFromWindowsError(
            "WindowsMmapFile failed to create file mapping for: " + filename_,
            GetLastError());
      }
D
Dmitri Smirnov 已提交
405 406 407 408 409 410
    }

    ULARGE_INTEGER offset;
    offset.QuadPart = file_offset_;

    // View must begin at the granularity aligned offset
S
sdong 已提交
411 412 413
    mapped_begin_ = reinterpret_cast<char*>(
        MapViewOfFileEx(hMap_, FILE_MAP_WRITE, offset.HighPart, offset.LowPart,
                        view_size_, NULL));
D
Dmitri Smirnov 已提交
414 415

    if (!mapped_begin_) {
S
sdong 已提交
416 417 418
      status = IOErrorFromWindowsError(
          "WindowsMmapFile failed to map file view: " + filename_,
          GetLastError());
D
Dmitri Smirnov 已提交
419
    } else {
S
sdong 已提交
420 421 422 423
      mapped_end_ = mapped_begin_ + view_size_;
      dst_ = mapped_begin_;
      last_sync_ = mapped_begin_;
      pending_sync_ = false;
D
Dmitri Smirnov 已提交
424 425 426 427
    }
    return status;
  }

S
sdong 已提交
428 429 430
 public:
  WinMmapFile(const std::string& fname, HANDLE hFile, size_t page_size,
              size_t allocation_granularity, const EnvOptions& options)
D
Dmitri Smirnov 已提交
431
      : filename_(fname),
S
sdong 已提交
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
        hFile_(hFile),
        hMap_(NULL),
        page_size_(page_size),
        allocation_granularity_(allocation_granularity),
        mapping_size_(0),
        view_size_(0),
        mapped_begin_(nullptr),
        mapped_end_(nullptr),
        dst_(nullptr),
        last_sync_(nullptr),
        file_offset_(0),
        pending_sync_(false) {
    // 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);

    // Make sure buffering is not disabled. It is ignored for mapping
    // purposes but also imposes restriction on moving file position
    // it is not a problem so much with reserving space since it is probably a
    // factor
    // of allocation_granularity but we also want to truncate the file in
    // Close() at
    // arbitrary position so we do not have to feel this with zeros.
    assert(options.use_os_buffer);

    // View size must be both the multiple of allocation_granularity AND the
    // page size
    if ((allocation_granularity_ % page_size_) == 0) {
      view_size_ = 2 * allocation_granularity;
    } else if ((page_size_ % allocation_granularity_) == 0) {
      view_size_ = 2 * page_size_;
    } else {
      // we can multiply them together
      assert(false);
    }
D
Dmitri Smirnov 已提交
474 475 476
  }

  ~WinMmapFile() {
S
sdong 已提交
477 478 479
    if (hFile_) {
      this->Close();
    }
D
Dmitri Smirnov 已提交
480 481 482 483 484 485 486 487 488 489 490
  }

  virtual Status Append(const Slice& data) override {
    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) {
S
sdong 已提交
491 492 493 494
        Status s = UnmapCurrentRegion();
        if (s.ok()) {
          s = MapNewRegion();
        }
D
Dmitri Smirnov 已提交
495

S
sdong 已提交
496 497 498
        if (!s.ok()) {
          return s;
        }
D
Dmitri Smirnov 已提交
499 500 501 502 503 504 505 506 507 508 509 510 511
      }

      size_t n = std::min(left, avail);
      memcpy(dst_, src, n);
      dst_ += n;
      src += n;
      left -= n;
      pending_sync_ = true;
    }

    return Status::OK();
  }

512 513 514 515 516 517
  // Means Close() will properly take care of truncate
  // and it does not need any additional information
  virtual Status Truncate(uint64_t size) override {
    return Status::OK();
  }

D
Dmitri Smirnov 已提交
518 519 520 521 522 523 524 525 526 527 528 529
  virtual Status Close() override {
    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();

    s = UnmapCurrentRegion();

S
sdong 已提交
530
    if (NULL != hMap_) {
D
Dmitri Smirnov 已提交
531 532
      BOOL ret = ::CloseHandle(hMap_);
      if (!ret && s.ok()) {
S
sdong 已提交
533 534 535
        auto lastError = GetLastError();
        s = IOErrorFromWindowsError(
            "Failed to Close mapping for file: " + filename_, lastError);
D
Dmitri Smirnov 已提交
536 537 538 539 540 541 542 543 544 545 546
      }

      hMap_ = NULL;
    }

    TruncateFile(targetSize);

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

    if (!ret && s.ok()) {
S
sdong 已提交
547 548 549
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError(
          "Failed to close file map handle: " + filename_, lastError);
D
Dmitri Smirnov 已提交
550 551 552 553 554
    }

    return s;
  }

S
sdong 已提交
555
  virtual Status Flush() override { return Status::OK(); }
D
Dmitri Smirnov 已提交
556 557 558 559 560 561 562 563 564 565 566 567

  // Flush only data
  virtual Status Sync() override {
    Status s;

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

S
sdong 已提交
568 569 570 571
      size_t page_begin =
          TruncateToPageBoundary(page_size_, last_sync_ - mapped_begin_);
      size_t page_end =
          TruncateToPageBoundary(page_size_, dst_ - mapped_begin_ - 1);
D
Dmitri Smirnov 已提交
572 573 574
      last_sync_ = dst_;

      // Flush only the amount of that is a multiple of pages
S
sdong 已提交
575 576 577 578
      if (!::FlushViewOfFile(mapped_begin_ + page_begin,
                             (page_end - page_begin) + page_size_)) {
        s = IOErrorFromWindowsError("Failed to FlushViewOfFile: " + filename_,
                                    GetLastError());
D
Dmitri Smirnov 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
      }

      pending_sync_ = false;
    }

    return s;
  }

  /**
  * Flush data as well as metadata to stable storage.
  */
  virtual Status Fsync() override {
    Status s;

    // Flush metadata if pending
    const bool pending = pending_sync_;

    s = Sync();

    // Flush metadata
    if (s.ok() && pending) {
      if (!::FlushFileBuffers(hFile_)) {
S
sdong 已提交
601 602
        s = IOErrorFromWindowsError("Failed to FlushFileBuffers: " + filename_,
                                    GetLastError());
D
Dmitri Smirnov 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
      }
    }

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

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

623
  virtual Status Allocate(uint64_t offset, uint64_t len) override {
D
Dmitri Smirnov 已提交
624 625 626 627
    return Status::OK();
  }
};

S
sdong 已提交
628 629
class WinSequentialFile : public SequentialFile {
 private:
D
Dmitri Smirnov 已提交
630
  const std::string filename_;
631 632 633
  HANDLE file_;

  // There is no equivalent of advising away buffered pages as in posix.
I
Islam AbdelRahman 已提交
634
  // To implement this flag we would need to do unbuffered reads which
635 636 637 638 639 640
  // will need to be aligned (not sure there is a guarantee that the buffer
  // passed in is aligned).
  // Hence we currently ignore this flag. It is used only in a few cases
  // which should not be perf critical.
  // If perf evaluation finds this to be a problem, we can look into
  // implementing this.
S
sdong 已提交
641
  bool use_os_buffer_;
D
Dmitri Smirnov 已提交
642

S
sdong 已提交
643
 public:
644
  WinSequentialFile(const std::string& fname, HANDLE f,
S
sdong 已提交
645 646 647 648 649 650
                    const EnvOptions& options)
      : filename_(fname),
        file_(f),
        use_os_buffer_(options.use_os_buffer) {}

  virtual ~WinSequentialFile() {
651 652
    assert(file_ != INVALID_HANDLE_VALUE);
    CloseHandle(file_);
D
Dmitri Smirnov 已提交
653 654 655 656 657 658
  }

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

659 660 661
    // Windows ReadFile API accepts a DWORD.
    // While it is possible to read in a loop if n is > UINT_MAX
    // it is a highly unlikely case.
662
    if (n > UINT_MAX) {
663 664 665 666 667 668 669 670 671 672 673
      return IOErrorFromWindowsError(filename_, ERROR_INVALID_PARAMETER);
    }

    DWORD bytesToRead = static_cast<DWORD>(n); //cast is safe due to the check above
    DWORD bytesRead = 0;
    BOOL ret = ReadFile(file_, scratch, bytesToRead, &bytesRead, NULL);
    if (ret == TRUE) {
      r = bytesRead;
    } else {
      return IOErrorFromWindowsError(filename_, GetLastError());
    }
D
Dmitri Smirnov 已提交
674 675 676 677 678 679 680

    *result = Slice(scratch, r);

    return s;
  }

  virtual Status Skip(uint64_t n) override {
681 682 683 684 685 686 687 688 689 690 691
    // 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.
    if (n > _I64_MAX) {
      return IOErrorFromWindowsError(filename_, ERROR_INVALID_PARAMETER);
    }

    LARGE_INTEGER li;
    li.QuadPart = static_cast<int64_t>(n); //cast is safe due to the check above
    BOOL ret = SetFilePointerEx(file_, li, NULL, FILE_CURRENT);
    if (ret == FALSE) {
      return IOErrorFromWindowsError(filename_, GetLastError());
D
Dmitri Smirnov 已提交
692 693 694 695
    }
    return Status::OK();
  }

S
sdong 已提交
696 697 698
  virtual Status InvalidateCache(size_t offset, size_t length) override {
    return Status::OK();
  }
D
Dmitri Smirnov 已提交
699 700 701
};

// pread() based random-access
S
sdong 已提交
702 703
class WinRandomAccessFile : public RandomAccessFile {
  const std::string filename_;
704 705
  // PLEASE NOTE: hFile is expected to be an async handle 
  // (i.e. opened with FILE_FLAG_OVERLAPPED)
S
sdong 已提交
706 707
  HANDLE hFile_;
  const bool use_os_buffer_;
S
sdong 已提交
708 709 710
  bool read_ahead_;
  const size_t compaction_readahead_size_;
  const size_t random_access_max_buffer_size_;
S
sdong 已提交
711 712 713 714 715
  mutable std::mutex buffer_mut_;
  mutable AlignedBuffer buffer_;
  mutable uint64_t
      buffered_start_;  // file offset set that is currently buffered

716
  /*
S
sdong 已提交
717 718 719 720 721 722
   * The function reads a requested amount of bytes into the specified aligned
   * buffer Upon success the function sets the length of the buffer to the
   * amount of bytes actually read even though it might be less than actually
   * requested. It then copies the amount of bytes requested by the user (left)
   * to the user supplied buffer (dest) and reduces left by the amount of bytes
   * copied to the user buffer
723 724
   *
   * @user_offset [in] - offset on disk where the read was requested by the user
S
sdong 已提交
725 726 727 728 729 730 731 732 733 734
   * @first_page_start [in] - actual page aligned disk offset that we want to
   *                          read from
   * @bytes_to_read [in] - total amount of bytes that will be read from disk
   *                       which is generally greater or equal to the amount
   *                       that the user has requested due to the
   *                       either alignment requirements or read_ahead in
   *                       effect.
   * @left [in/out] total amount of bytes that needs to be copied to the user
   *                buffer. It is reduced by the amount of bytes that actually
   *                copied
735 736 737 738
   * @buffer - buffer to use
   * @dest - user supplied buffer
  */
  SSIZE_T ReadIntoBuffer(uint64_t user_offset, uint64_t first_page_start,
S
sdong 已提交
739 740
                         size_t bytes_to_read, size_t& left,
                         AlignedBuffer& buffer, char* dest) const {
741 742 743
    assert(buffer.CurrentSize() == 0);
    assert(buffer.Capacity() >= bytes_to_read);

S
sdong 已提交
744 745
    SSIZE_T read =
        pread(hFile_, buffer.Destination(), bytes_to_read, first_page_start);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763

    if (read > 0) {
      buffer.Size(read);

      // Let's figure out how much we read from the users standpoint
      if ((first_page_start + buffer.CurrentSize()) > user_offset) {
        assert(first_page_start <= user_offset);
        size_t buffer_offset = user_offset - first_page_start;
        read = buffer.Read(dest, buffer_offset, left);
      } else {
        read = 0;
      }
      left -= read;
    }
    return read;
  }

  SSIZE_T ReadIntoOneShotBuffer(uint64_t user_offset, uint64_t first_page_start,
S
sdong 已提交
764 765
                                size_t bytes_to_read, size_t& left,
                                char* dest) const {
766 767 768 769 770
    AlignedBuffer bigBuffer;
    bigBuffer.Alignment(buffer_.Alignment());
    bigBuffer.AllocateNewBuffer(bytes_to_read);

    return ReadIntoBuffer(user_offset, first_page_start, bytes_to_read, left,
S
sdong 已提交
771
                          bigBuffer, dest);
772 773
  }

S
sdong 已提交
774 775 776 777
  SSIZE_T ReadIntoInstanceBuffer(uint64_t user_offset,
                                 uint64_t first_page_start,
                                 size_t bytes_to_read, size_t& left,
                                 char* dest) const {
778
    SSIZE_T read = ReadIntoBuffer(user_offset, first_page_start, bytes_to_read,
S
sdong 已提交
779
                                  left, buffer_, dest);
780 781 782 783 784 785 786 787

    if (read > 0) {
      buffered_start_ = first_page_start;
    }

    return read;
  }

788 789 790 791 792 793 794 795 796 797 798 799
  void CalculateReadParameters(uint64_t offset, size_t bytes_requested,
                                size_t& actual_bytes_toread,
                                uint64_t& first_page_start) const {

    const size_t alignment = buffer_.Alignment();

    first_page_start = TruncateToPageBoundary(alignment, offset);
    const uint64_t last_page_start =
      TruncateToPageBoundary(alignment, offset + bytes_requested - 1);
    actual_bytes_toread = (last_page_start - first_page_start) + alignment;
  }

S
sdong 已提交
800 801 802 803 804 805
 public:
  WinRandomAccessFile(const std::string& fname, HANDLE hFile, size_t alignment,
                      const EnvOptions& options)
      : filename_(fname),
        hFile_(hFile),
        use_os_buffer_(options.use_os_buffer),
806 807 808
        read_ahead_(false),
        compaction_readahead_size_(options.compaction_readahead_size),
        random_access_max_buffer_size_(options.random_access_max_buffer_size),
809
        buffer_(),
S
sdong 已提交
810
        buffered_start_(0) {
D
Dmitri Smirnov 已提交
811 812 813 814
    assert(!options.use_mmap_reads);

    // Unbuffered access, use internal buffer for reads
    if (!use_os_buffer_) {
815 816
      // Do not allocate the buffer either until the first request or
      // until there is a call to allocate a read-ahead buffer
817
      buffer_.Alignment(alignment);
D
Dmitri Smirnov 已提交
818 819
    }
  }
S
sdong 已提交
820 821

  virtual ~WinRandomAccessFile() {
D
Dmitri Smirnov 已提交
822
    if (hFile_ != NULL && hFile_ != INVALID_HANDLE_VALUE) {
S
sdong 已提交
823
      ::CloseHandle(hFile_);
D
Dmitri Smirnov 已提交
824 825 826
    }
  }

S
sdong 已提交
827
  virtual void EnableReadAhead() override { this->Hint(SEQUENTIAL); }
828

S
sdong 已提交
829 830
  virtual Status Read(uint64_t offset, size_t n, Slice* result,
                      char* scratch) const override {
831

D
Dmitri Smirnov 已提交
832 833 834 835 836
    Status s;
    SSIZE_T r = -1;
    size_t left = n;
    char* dest = scratch;

837 838 839 840 841
    if (n == 0) {
      *result = Slice(scratch, 0);
      return s;
    }

D
Dmitri Smirnov 已提交
842 843 844 845 846
    // When in unbuffered mode we need to do the following changes:
    // - use our own aligned buffer
    // - always read at the offset of that is a multiple of alignment
    if (!use_os_buffer_) {

847 848 849
      uint64_t first_page_start = 0;
      size_t actual_bytes_toread = 0;
      size_t bytes_requested = left;
D
Dmitri Smirnov 已提交
850

851 852 853
      if (!read_ahead_ && random_access_max_buffer_size_ == 0) {
        CalculateReadParameters(offset, bytes_requested, actual_bytes_toread,
          first_page_start);
D
Dmitri Smirnov 已提交
854

855
        assert(actual_bytes_toread > 0);
D
Dmitri Smirnov 已提交
856

857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
        r = ReadIntoOneShotBuffer(offset, first_page_start,
          actual_bytes_toread, left, dest);
      } else {

        std::unique_lock<std::mutex> lock(buffer_mut_);

        // Let's see if at least some of the requested data is already
        // in the buffer
        if (offset >= buffered_start_ &&
          offset < (buffered_start_ + buffer_.CurrentSize())) {
          size_t buffer_offset = offset - buffered_start_;
          r = buffer_.Read(dest, buffer_offset, left);
          assert(r >= 0);

          left -= size_t(r);
          offset += r;
          dest += r;
D
Dmitri Smirnov 已提交
874
        }
S
sdong 已提交
875

876 877 878 879
        // Still some left or none was buffered
        if (left > 0) {
          // Figure out the start/end offset for reading and amount to read
          bytes_requested = left;
D
Dmitri Smirnov 已提交
880

881 882 883 884 885 886 887 888 889 890 891 892 893 894
          if (read_ahead_ && bytes_requested < compaction_readahead_size_) {
            bytes_requested = compaction_readahead_size_;
          }

          CalculateReadParameters(offset, bytes_requested, actual_bytes_toread,
            first_page_start);

          assert(actual_bytes_toread > 0);

          if (buffer_.Capacity() < actual_bytes_toread) {
            // If we are in read-ahead mode or the requested size
            // exceeds max buffer size then use one-shot
            // big buffer otherwise reallocate main buffer
            if (read_ahead_ ||
S
sdong 已提交
895
              (actual_bytes_toread > random_access_max_buffer_size_)) {
896 897 898 899 900 901 902 903 904 905 906 907 908
              // Unlock the mutex since we are not using instance buffer
              lock.unlock();
              r = ReadIntoOneShotBuffer(offset, first_page_start,
                actual_bytes_toread, left, dest);
            }
            else {
              buffer_.AllocateNewBuffer(actual_bytes_toread);
              r = ReadIntoInstanceBuffer(offset, first_page_start,
                actual_bytes_toread, left, dest);
            }
          }
          else {
            buffer_.Clear();
909
            r = ReadIntoInstanceBuffer(offset, first_page_start,
910
              actual_bytes_toread, left, dest);
D
Dmitri Smirnov 已提交
911 912 913 914
          }
        }
      }
    } else {
S
sdong 已提交
915 916 917 918
      r = pread(hFile_, scratch, left, offset);
      if (r > 0) {
        left -= r;
      }
D
Dmitri Smirnov 已提交
919 920 921 922 923 924 925 926 927 928
    }

    *result = Slice(scratch, (r < 0) ? 0 : n - left);

    if (r < 0) {
      s = IOErrorFromLastWindowsError(filename_);
    }
    return s;
  }

929
  virtual bool ShouldForwardRawRequest() const override {
930 931 932
    return true;
  }

933
  virtual void Hint(AccessPattern pattern) override {
S
sdong 已提交
934
    if (pattern == SEQUENTIAL && !use_os_buffer_ &&
935 936 937 938 939 940 941 942
        compaction_readahead_size_ > 0) {
      std::lock_guard<std::mutex> lg(buffer_mut_);
      if (!read_ahead_) {
        read_ahead_ = true;
        // This would allocate read-ahead size + 2 alignments
        // - one for memory alignment which added implicitly by AlignedBuffer
        // - We add one more alignment because we will read one alignment more
        // from disk
S
sdong 已提交
943 944
        buffer_.AllocateNewBuffer(compaction_readahead_size_ +
                                  buffer_.Alignment());
945 946 947 948
      }
    }
  }

S
sdong 已提交
949 950 951
  virtual Status InvalidateCache(size_t offset, size_t length) override {
    return Status::OK();
  }
D
Dmitri Smirnov 已提交
952 953 954
};

// This is a sequential write class. It has been mimicked (as others) after
S
sdong 已提交
955 956 957 958 959 960
// the original Posix class. We add support for unbuffered I/O on windows as
// well
// we utilize the original buffer as an alignment buffer to write directly to
// file with no buffering.
// No buffering requires that the provided buffer is aligned to the physical
// sector size (SSD page size) and
D
Dmitri Smirnov 已提交
961 962
// that all SetFilePointer() operations to occur with such an alignment.
// We thus always write in sector/page size increments to the drive and leave
S
sdong 已提交
963 964
// the tail for the next write OR for Close() at which point we pad with zeros.
// No padding is required for
D
Dmitri Smirnov 已提交
965 966
// buffered access.
class WinWritableFile : public WritableFile {
S
sdong 已提交
967 968
 private:
  const std::string filename_;
969 970 971 972 973 974
  HANDLE            hFile_;
  const bool        use_os_buffer_;  // Used to indicate unbuffered access, the file
  const uint64_t    alignment_;
  // must be opened as unbuffered if false
  uint64_t          filesize_;      // How much data is actually written disk
  uint64_t          reservedsize_;  // how far we have reserved space
D
Dmitri Smirnov 已提交
975

S
sdong 已提交
976 977 978 979 980
 public:
  WinWritableFile(const std::string& fname, HANDLE hFile, size_t alignment,
                  size_t capacity, const EnvOptions& options)
      : filename_(fname),
        hFile_(hFile),
981 982
        use_os_buffer_(options.use_os_buffer),
        alignment_(alignment),
S
sdong 已提交
983
        filesize_(0),
984
        reservedsize_(0) {
S
sdong 已提交
985
    assert(!options.use_mmap_writes);
D
Dmitri Smirnov 已提交
986 987 988 989
  }

  ~WinWritableFile() {
    if (NULL != hFile_ && INVALID_HANDLE_VALUE != hFile_) {
S
sdong 已提交
990
      WinWritableFile::Close();
D
Dmitri Smirnov 已提交
991 992 993
    }
  }

994 995 996 997
  // Indicates if the class makes use of unbuffered I/O
  virtual bool UseOSBuffer() const override {
    return use_os_buffer_;
  }
D
Dmitri Smirnov 已提交
998

999 1000 1001
  virtual size_t GetRequiredBufferAlignment() const override {
    return alignment_;
  }
D
Dmitri Smirnov 已提交
1002

1003
  virtual Status Append(const Slice& data) override {
D
Dmitri Smirnov 已提交
1004

1005 1006
    // Used for buffered access ONLY
    assert(use_os_buffer_);
V
Vasili Svirski 已提交
1007
    assert(data.size() < std::numeric_limits<DWORD>::max());
D
Dmitri Smirnov 已提交
1008

1009
    Status s;
D
Dmitri Smirnov 已提交
1010

1011 1012
    DWORD bytesWritten = 0;
    if (!WriteFile(hFile_, data.data(),
V
Vasili Svirski 已提交
1013
        static_cast<DWORD>(data.size()), &bytesWritten, NULL)) {
1014 1015 1016 1017 1018 1019 1020
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError(
        "Failed to WriteFile: " + filename_,
        lastError);
    } else {
      assert(size_t(bytesWritten) == data.size());
      filesize_ += data.size();
D
Dmitri Smirnov 已提交
1021 1022
    }

1023 1024
    return s;
  }
D
Dmitri Smirnov 已提交
1025

1026
  virtual Status PositionedAppend(const Slice& data, uint64_t offset) override {
1027
    Status s;
D
Dmitri Smirnov 已提交
1028

I
Islam AbdelRahman 已提交
1029
    SSIZE_T ret = pwrite(hFile_, data.data(), data.size(), offset);
D
Dmitri Smirnov 已提交
1030

1031 1032 1033 1034 1035
    // Error break
    if (ret < 0) {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError(
        "Failed to pwrite for: " + filename_, lastError);
D
Dmitri Smirnov 已提交
1036
    } else {
1037 1038 1039 1040
      // With positional write it is not clear at all
      // if this actually extends the filesize
      assert(size_t(ret) == data.size());
      filesize_ += data.size();
D
Dmitri Smirnov 已提交
1041
    }
1042 1043
    return s;
  }
D
Dmitri Smirnov 已提交
1044

1045 1046 1047 1048 1049 1050 1051
  // Need to implement this so the file is truncated correctly
  // when buffered and unbuffered mode
  virtual Status Truncate(uint64_t size) override {
    Status s =  ftruncate(filename_, hFile_, size);
    if (s.ok()) {
      filesize_ = size;
    }
D
Dmitri Smirnov 已提交
1052 1053 1054 1055 1056
    return s;
  }

  virtual Status Close() override {

1057
    Status s;
D
Dmitri Smirnov 已提交
1058

1059
    assert(INVALID_HANDLE_VALUE != hFile_);
D
Dmitri Smirnov 已提交
1060

1061
    if (fsync(hFile_) < 0) {
D
Dmitri Smirnov 已提交
1062
      auto lastError = GetLastError();
S
sdong 已提交
1063
      s = IOErrorFromWindowsError("fsync failed at Close() for: " + filename_,
1064
        lastError);
D
Dmitri Smirnov 已提交
1065 1066 1067
    }

    if (FALSE == ::CloseHandle(hFile_)) {
1068 1069 1070
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError("CloseHandle failed for: " + filename_,
                                  lastError);
D
Dmitri Smirnov 已提交
1071 1072 1073 1074 1075 1076 1077
    }

    hFile_ = INVALID_HANDLE_VALUE;
    return s;
  }

  // write out the cached data to the OS cache
1078
  // This is now taken care of the WritableFileWriter
D
Dmitri Smirnov 已提交
1079
  virtual Status Flush() override {
1080
    return Status::OK();
D
Dmitri Smirnov 已提交
1081 1082 1083
  }

  virtual Status Sync() override {
1084
    Status s;
D
Dmitri Smirnov 已提交
1085
    // Calls flush buffers
1086
    if (fsync(hFile_) < 0) {
S
sdong 已提交
1087 1088 1089
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError("fsync failed at Sync() for: " + filename_,
                                  lastError);
D
Dmitri Smirnov 已提交
1090 1091 1092 1093
    }
    return s;
  }

S
sdong 已提交
1094
  virtual Status Fsync() override { return Sync(); }
D
Dmitri Smirnov 已提交
1095 1096

  virtual uint64_t GetFileSize() override {
1097 1098 1099 1100 1101 1102
    // Double accounting now here with WritableFileWriter
    // and this size will be wrong when unbuffered access is used
    // but tests implement their own writable files and do not use WritableFileWrapper
    // so we need to squeeze a square peg through
    // a round hole here.
    return filesize_;
D
Dmitri Smirnov 已提交
1103 1104
  }

1105
  virtual Status Allocate(uint64_t offset, uint64_t len) override {
D
Dmitri Smirnov 已提交
1106
    Status status;
1107
    TEST_KILL_RANDOM("WinWritableFile::Allocate", rocksdb_kill_odds);
D
Dmitri Smirnov 已提交
1108 1109 1110 1111

    // 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
1112
    size_t spaceToReserve = Roundup(offset + len, alignment_);
D
Dmitri Smirnov 已提交
1113 1114 1115 1116 1117
    // Nothing to do
    if (spaceToReserve <= reservedsize_) {
      return status;
    }

1118
    IOSTATS_TIMER_GUARD(allocate_nanos);
D
Dmitri Smirnov 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127
    status = fallocate(filename_, hFile_, spaceToReserve);
    if (status.ok()) {
      reservedsize_ = spaceToReserve;
    }
    return status;
  }
};

class WinDirectory : public Directory {
S
sdong 已提交
1128 1129
 public:
  WinDirectory() {}
D
Dmitri Smirnov 已提交
1130

S
sdong 已提交
1131
  virtual Status Fsync() override { return Status::OK(); }
D
Dmitri Smirnov 已提交
1132 1133 1134
};

class WinFileLock : public FileLock {
S
sdong 已提交
1135 1136
 public:
  explicit WinFileLock(HANDLE hFile) : hFile_(hFile) {
D
Dmitri Smirnov 已提交
1137 1138 1139 1140
    assert(hFile != NULL);
    assert(hFile != INVALID_HANDLE_VALUE);
  }

S
sdong 已提交
1141
  ~WinFileLock() {
D
Dmitri Smirnov 已提交
1142 1143 1144 1145
    BOOL ret = ::CloseHandle(hFile_);
    assert(ret);
  }

S
sdong 已提交
1146
 private:
D
Dmitri Smirnov 已提交
1147 1148 1149
  HANDLE hFile_;
};

S
sdong 已提交
1150
namespace {
D
Dmitri Smirnov 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159

void WinthreadCall(const char* label, std::error_code result) {
  if (0 != result.value()) {
    fprintf(stderr, "pthread %s: %s\n", label, strerror(result.value()));
    abort();
  }
}
}

1160 1161
typedef VOID(WINAPI * FnGetSystemTimePreciseAsFileTime)(LPFILETIME);

D
Dmitri Smirnov 已提交
1162
class WinEnv : public Env {
S
sdong 已提交
1163
 public:
D
Dmitri Smirnov 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
  WinEnv();

  virtual ~WinEnv() {
    for (auto& th : threads_to_join_) {
      th.join();
    }

    threads_to_join_.clear();

    for (auto& thpool : thread_pools_) {
      thpool.JoinAllThreads();
    }
    // All threads must be joined before the deletion of
    // thread_status_updater_.
    delete thread_status_updater_;
  }

  virtual Status DeleteFile(const std::string& fname) override {
    Status result;

    if (_unlink(fname.c_str())) {
      result = IOError("Failed to delete: " + fname, errno);
    }

    return result;
  }

  Status GetCurrentTime(int64_t* unix_time) override {
    time_t time = std::time(nullptr);
    if (time == (time_t)(-1)) {
      return Status::NotSupported("Failed to get time");
    }

    *unix_time = time;
    return Status::OK();
  }

S
sdong 已提交
1201 1202 1203
  virtual Status NewSequentialFile(const std::string& fname,
                                   std::unique_ptr<SequentialFile>* result,
                                   const EnvOptions& options) override {
D
Dmitri Smirnov 已提交
1204 1205 1206 1207 1208 1209 1210
    Status s;

    result->reset();

    // Corruption test needs to rename and delete files of these kind
    // while they are still open with another handle. For that reason we
    // allow share_write and delete(allows rename).
1211
    HANDLE hFile = INVALID_HANDLE_VALUE;
1212 1213
    {
      IOSTATS_TIMER_GUARD(open_nanos);
S
sdong 已提交
1214 1215 1216 1217 1218
      hFile = CreateFileA(
          fname.c_str(), GENERIC_READ,
          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
          OPEN_EXISTING,  // Original fopen mode is "rb"
          FILE_ATTRIBUTE_NORMAL, NULL);
1219
    }
D
Dmitri Smirnov 已提交
1220

1221
    if (INVALID_HANDLE_VALUE == hFile) {
D
Dmitri Smirnov 已提交
1222
      auto lastError = GetLastError();
S
sdong 已提交
1223 1224
      s = IOErrorFromWindowsError("Failed to open NewSequentialFile" + fname,
                                  lastError);
D
Dmitri Smirnov 已提交
1225
    } else {
1226
      result->reset(new WinSequentialFile(fname, hFile, options));
D
Dmitri Smirnov 已提交
1227 1228 1229 1230
    }
    return s;
  }

S
sdong 已提交
1231 1232 1233
  virtual Status NewRandomAccessFile(const std::string& fname,
                                     std::unique_ptr<RandomAccessFile>* result,
                                     const EnvOptions& options) override {
D
Dmitri Smirnov 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    result->reset();
    Status s;

    // Open the file for read-only random access
    // Random access is to disable read-ahead as the system reads too much data
    DWORD fileFlags = FILE_ATTRIBUTE_READONLY;

    if (!options.use_os_buffer && !options.use_mmap_reads) {
      fileFlags |= FILE_FLAG_NO_BUFFERING;
    } else {
      fileFlags |= FILE_FLAG_RANDOM_ACCESS;
    }

1247 1248 1249 1250 1251 1252
    if (!options.use_mmap_reads) {
      // Open in async mode which makes Windows allow more parallelism even
      // if we need to do sync I/O on top of it.
      fileFlags |= FILE_FLAG_OVERLAPPED;
    }

D
Dmitri Smirnov 已提交
1253
    /// Shared access is necessary for corruption test to pass
1254
    // almost all tests would work with a possible exception of fault_injection
1255
    HANDLE hFile = 0;
1256 1257
    {
      IOSTATS_TIMER_GUARD(open_nanos);
S
sdong 已提交
1258 1259 1260 1261
      hFile =
          CreateFileA(fname.c_str(), GENERIC_READ,
                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                      NULL, OPEN_EXISTING, fileFlags, NULL);
1262
    }
D
Dmitri Smirnov 已提交
1263 1264 1265

    if (INVALID_HANDLE_VALUE == hFile) {
      auto lastError = GetLastError();
S
sdong 已提交
1266 1267
      return IOErrorFromWindowsError(
          "NewRandomAccessFile failed to Create/Open: " + fname, lastError);
D
Dmitri Smirnov 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    }

    UniqueCloseHandlePtr fileGuard(hFile, CloseHandleFunc);

    // CAUTION! This will map the entire file into the process address space
    if (options.use_mmap_reads && sizeof(void*) >= 8) {
      // Use mmap when virtual address-space is plentiful.
      uint64_t fileSize;

      s = GetFileSize(fname, &fileSize);

      if (s.ok()) {
        // Will not map empty files
        if (fileSize == 0) {
S
sdong 已提交
1282 1283
          return IOError(
              "NewRandomAccessFile failed to map empty file: " + fname, EINVAL);
D
Dmitri Smirnov 已提交
1284 1285
        }

S
sdong 已提交
1286 1287 1288 1289
        HANDLE hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY,
                                         0,  // Whole file at its present length
                                         0,
                                         NULL);  // Mapping name
D
Dmitri Smirnov 已提交
1290 1291 1292

        if (!hMap) {
          auto lastError = GetLastError();
S
sdong 已提交
1293 1294 1295
          return IOErrorFromWindowsError(
              "Failed to create file mapping for NewRandomAccessFile: " + fname,
              lastError);
D
Dmitri Smirnov 已提交
1296 1297
        }

S
sdong 已提交
1298
        UniqueCloseHandlePtr mapGuard(hMap, CloseHandleFunc);
D
Dmitri Smirnov 已提交
1299

S
sdong 已提交
1300 1301 1302 1303 1304 1305
        const void* mapped_region =
            MapViewOfFileEx(hMap, FILE_MAP_READ,
                            0,  // High DWORD of access start
                            0,  // Low DWORD
                            fileSize,
                            NULL);  // Let the OS choose the mapping
D
Dmitri Smirnov 已提交
1306 1307 1308

        if (!mapped_region) {
          auto lastError = GetLastError();
S
sdong 已提交
1309 1310 1311
          return IOErrorFromWindowsError(
              "Failed to MapViewOfFile for NewRandomAccessFile: " + fname,
              lastError);
D
Dmitri Smirnov 已提交
1312 1313
        }

S
sdong 已提交
1314 1315
        result->reset(new WinMmapReadableFile(fname, hFile, hMap, mapped_region,
                                              fileSize));
D
Dmitri Smirnov 已提交
1316 1317 1318 1319

        mapGuard.release();
        fileGuard.release();
      }
S
sdong 已提交
1320
    } else {
D
Dmitri Smirnov 已提交
1321 1322 1323 1324 1325 1326
      result->reset(new WinRandomAccessFile(fname, hFile, page_size_, options));
      fileGuard.release();
    }
    return s;
  }

S
sdong 已提交
1327 1328 1329
  virtual Status NewWritableFile(const std::string& fname,
                                 std::unique_ptr<WritableFile>* result,
                                 const EnvOptions& options) override {
D
Dmitri Smirnov 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    const size_t c_BufferCapacity = 64 * 1024;

    EnvOptions local_options(options);

    result->reset();
    Status s;

    DWORD fileFlags = FILE_ATTRIBUTE_NORMAL;

    if (!local_options.use_os_buffer && !local_options.use_mmap_writes) {
S
sdong 已提交
1340
      fileFlags = FILE_FLAG_NO_BUFFERING;
D
Dmitri Smirnov 已提交
1341 1342
    }

S
sdong 已提交
1343 1344 1345 1346
    // Desired access. We are want to write only here but if we want to memory
    // map
    // the file then there is no write only mode so we have to create it
    // Read/Write
D
Dmitri Smirnov 已提交
1347 1348 1349 1350 1351 1352 1353
    // However, MapViewOfFile specifies only Write only
    DWORD desired_access = GENERIC_WRITE;
    DWORD shared_mode = FILE_SHARE_READ;

    if (local_options.use_mmap_writes) {
      desired_access |= GENERIC_READ;
    } else {
S
sdong 已提交
1354 1355
      // Adding this solely for tests to pass (fault_injection_test,
      // wal_manager_test).
D
Dmitri Smirnov 已提交
1356 1357 1358
      shared_mode |= (FILE_SHARE_WRITE | FILE_SHARE_DELETE);
    }

1359 1360 1361
    HANDLE hFile = 0;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
S
sdong 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
      hFile = CreateFileA(
          fname.c_str(),
          desired_access,  // Access desired
          shared_mode,
          NULL,           // Security attributes
          CREATE_ALWAYS,  // Posix env says O_CREAT | O_RDWR | O_TRUNC
          fileFlags,      // Flags
          NULL);          // Template File
    }

D
Dmitri Smirnov 已提交
1372 1373
    if (INVALID_HANDLE_VALUE == hFile) {
      auto lastError = GetLastError();
S
sdong 已提交
1374 1375
      return IOErrorFromWindowsError(
          "Failed to create a NewWriteableFile: " + fname, lastError);
D
Dmitri Smirnov 已提交
1376 1377 1378
    }

    if (options.use_mmap_writes) {
S
sdong 已提交
1379 1380 1381 1382
      // We usually do not use mmmapping on SSD and thus we pass memory
      // page_size
      result->reset(new WinMmapFile(fname, hFile, page_size_,
                                    allocation_granularity_, local_options));
D
Dmitri Smirnov 已提交
1383
    } else {
S
sdong 已提交
1384 1385 1386 1387
      // Here we want the buffer allocation to be aligned by the SSD page size
      // and to be a multiple of it
      result->reset(new WinWritableFile(fname, hFile, page_size_,
                                        c_BufferCapacity, local_options));
D
Dmitri Smirnov 已提交
1388 1389 1390 1391
    }
    return s;
  }

S
sdong 已提交
1392 1393
  virtual Status NewDirectory(const std::string& name,
                              std::unique_ptr<Directory>* result) override {
D
Dmitri Smirnov 已提交
1394 1395 1396 1397 1398 1399 1400
    Status s;
    // Must be nullptr on failure
    result->reset();
    // Must fail if directory does not exist
    if (!DirExists(name)) {
      s = IOError("Directory does not exist: " + name, EEXIST);
    } else {
1401
      IOSTATS_TIMER_GUARD(open_nanos);
D
Dmitri Smirnov 已提交
1402 1403 1404 1405 1406
      result->reset(new WinDirectory);
    }
    return s;
  }

A
agiardullo 已提交
1407
  virtual Status FileExists(const std::string& fname) override {
D
Dmitri Smirnov 已提交
1408 1409
    // F_OK == 0
    const int F_OK_ = 0;
A
agiardullo 已提交
1410 1411
    return _access(fname.c_str(), F_OK_) == 0 ? Status::OK()
                                              : Status::NotFound();
D
Dmitri Smirnov 已提交
1412 1413
  }

S
sdong 已提交
1414 1415
  virtual Status GetChildren(const std::string& dir,
                             std::vector<std::string>* result) override {
D
Dmitri Smirnov 已提交
1416 1417 1418 1419 1420
    std::vector<std::string> output;

    Status status;

    auto CloseDir = [](DIR* p) { closedir(p); };
S
sdong 已提交
1421 1422
    std::unique_ptr<DIR, decltype(CloseDir)> dirp(opendir(dir.c_str()),
                                                  CloseDir);
D
Dmitri Smirnov 已提交
1423 1424 1425

    if (!dirp) {
      status = IOError(dir, errno);
S
sdong 已提交
1426
    } else {
D
Dmitri Smirnov 已提交
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
      if (result->capacity() > 0) {
        output.reserve(result->capacity());
      }

      struct dirent* ent = readdir(dirp.get());
      while (ent) {
        output.push_back(ent->d_name);
        ent = readdir(dirp.get());
      }
    }

    output.swap(*result);

    return status;
  }

  virtual Status CreateDir(const std::string& name) override {
    Status result;

    if (_mkdir(name.c_str()) != 0) {
S
sdong 已提交
1447 1448
      auto code = errno;
      result = IOError("Failed to create dir: " + name, code);
D
Dmitri Smirnov 已提交
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    }

    return result;
  }

  virtual Status CreateDirIfMissing(const std::string& name) override {
    Status result;

    if (DirExists(name)) {
      return result;
    }

    if (_mkdir(name.c_str()) != 0) {
      if (errno == EEXIST) {
S
sdong 已提交
1463 1464 1465 1466 1467
        result =
            Status::IOError("`" + name + "' exists but is not a directory");
      } else {
        auto code = errno;
        result = IOError("Failed to create dir: " + name, code);
D
Dmitri Smirnov 已提交
1468 1469 1470 1471 1472 1473 1474 1475 1476
      }
    }

    return result;
  }

  virtual Status DeleteDir(const std::string& name) override {
    Status result;
    if (_rmdir(name.c_str()) != 0) {
S
sdong 已提交
1477 1478
      auto code = errno;
      result = IOError("Failed to remove dir: " + name, code);
D
Dmitri Smirnov 已提交
1479 1480 1481 1482
    }
    return result;
  }

S
sdong 已提交
1483 1484 1485
  virtual Status GetFileSize(const std::string& fname,
                             uint64_t* size) override {
    Status s;
D
Dmitri Smirnov 已提交
1486

S
sdong 已提交
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
    WIN32_FILE_ATTRIBUTE_DATA attrs;
    if (GetFileAttributesExA(fname.c_str(), GetFileExInfoStandard, &attrs)) {
      ULARGE_INTEGER file_size;
      file_size.HighPart = attrs.nFileSizeHigh;
      file_size.LowPart = attrs.nFileSizeLow;
      *size = file_size.QuadPart;
    } else {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError("Can not get size for: " + fname, lastError);
    }
    return s;
D
Dmitri Smirnov 已提交
1498 1499 1500 1501 1502 1503 1504
  }

  static inline uint64_t FileTimeToUnixTime(const FILETIME& ftTime) {
    const uint64_t c_FileTimePerSecond = 10000000U;
    // UNIX epoch starts on 1970-01-01T00:00:00Z
    // Windows FILETIME starts on 1601-01-01T00:00:00Z
    // Therefore, we need to subtract the below number of seconds from
S
sdong 已提交
1505 1506
    // the seconds that we obtain from FILETIME with an obvious loss of
    // precision
D
Dmitri Smirnov 已提交
1507 1508 1509 1510 1511 1512
    const uint64_t c_SecondBeforeUnixEpoch = 11644473600U;

    ULARGE_INTEGER li;
    li.HighPart = ftTime.dwHighDateTime;
    li.LowPart = ftTime.dwLowDateTime;

S
sdong 已提交
1513 1514
    uint64_t result =
        (li.QuadPart / c_FileTimePerSecond) - c_SecondBeforeUnixEpoch;
D
Dmitri Smirnov 已提交
1515 1516 1517
    return result;
  }

S
sdong 已提交
1518 1519
  virtual Status GetFileModificationTime(const std::string& fname,
                                         uint64_t* file_mtime) override {
D
Dmitri Smirnov 已提交
1520 1521 1522 1523 1524 1525 1526
    Status s;

    WIN32_FILE_ATTRIBUTE_DATA attrs;
    if (GetFileAttributesExA(fname.c_str(), GetFileExInfoStandard, &attrs)) {
      *file_mtime = FileTimeToUnixTime(attrs.ftLastWriteTime);
    } else {
      auto lastError = GetLastError();
S
sdong 已提交
1527 1528
      s = IOErrorFromWindowsError(
          "Can not get file modification time for: " + fname, lastError);
D
Dmitri Smirnov 已提交
1529 1530 1531 1532 1533 1534
      *file_mtime = 0;
    }

    return s;
  }

S
sdong 已提交
1535 1536
  virtual Status RenameFile(const std::string& src,
                            const std::string& target) override {
D
Dmitri Smirnov 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
    Status result;

    // rename() is not capable of replacing the existing file as on Linux
    // so use OS API directly
    if (!MoveFileExA(src.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING)) {
      DWORD lastError = GetLastError();

      std::string text("Failed to rename: ");
      text.append(src).append(" to: ").append(target);

      result = IOErrorFromWindowsError(text, lastError);
    }

    return result;
  }

S
sdong 已提交
1553 1554
  virtual Status LinkFile(const std::string& src,
                          const std::string& target) override {
D
Dmitri Smirnov 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    Status result;

    if (!CreateHardLinkA(target.c_str(), src.c_str(), NULL)) {
      DWORD lastError = GetLastError();

      std::string text("Failed to link: ");
      text.append(src).append(" to: ").append(target);

      result = IOErrorFromWindowsError(text, lastError);
    }

    return result;
  }

S
sdong 已提交
1569 1570
  virtual Status LockFile(const std::string& lockFname,
                          FileLock** lock) override {
D
Dmitri Smirnov 已提交
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
    assert(lock != nullptr);

    *lock = NULL;
    Status result;

    // No-sharing, this is a LOCK file
    const DWORD ExclusiveAccessON = 0;

    // Obtain exclusive access to the LOCK file
    // Previously, instead of NORMAL attr we set DELETE on close and that worked
    // well except with fault_injection test that insists on deleting it.
1582 1583 1584 1585
    HANDLE hFile = 0;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
      hFile = CreateFileA(lockFname.c_str(), (GENERIC_READ | GENERIC_WRITE),
S
sdong 已提交
1586 1587
                          ExclusiveAccessON, NULL, CREATE_ALWAYS,
                          FILE_ATTRIBUTE_NORMAL, NULL);
1588
    }
D
Dmitri Smirnov 已提交
1589 1590 1591

    if (INVALID_HANDLE_VALUE == hFile) {
      auto lastError = GetLastError();
S
sdong 已提交
1592 1593
      result = IOErrorFromWindowsError(
          "Failed to create lock file: " + lockFname, lastError);
D
Dmitri Smirnov 已提交
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
    } else {
      *lock = new WinFileLock(hFile);
    }

    return result;
  }

  virtual Status UnlockFile(FileLock* lock) override {
    Status result;

    assert(lock != nullptr);

    delete lock;

    return result;
  }

S
sdong 已提交
1611
  virtual void Schedule(void (*function)(void*), void* arg, Priority pri = LOW,
1612 1613
                        void* tag = nullptr,
                        void (*unschedFunction)(void* arg) = 0) override;
S
sdong 已提交
1614

D
Dmitri Smirnov 已提交
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
  virtual int UnSchedule(void* arg, Priority pri) override;

  virtual void StartThread(void (*function)(void* arg), void* arg) override;

  virtual void WaitForJoin() override;

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

  virtual Status GetTestDirectory(std::string* result) override {
    std::string output;

    const char* env = getenv("TEST_TMPDIR");
    if (env && env[0] != '\0') {
      output = env;
      CreateDir(output);
S
sdong 已提交
1630
    } else {
D
Dmitri Smirnov 已提交
1631 1632 1633
      env = getenv("TMP");

      if (env && env[0] != '\0') {
S
sdong 已提交
1634 1635 1636
        output = env;
      } else {
        output = "c:\\tmp";
D
Dmitri Smirnov 已提交
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
      }

      CreateDir(output);
    }

    output.append("\\testrocksdb-");
    output.append(std::to_string(_getpid()));

    CreateDir(output);

    output.swap(*result);

    return Status::OK();
  }

  virtual Status GetThreadList(
S
sdong 已提交
1653
      std::vector<ThreadStatus>* thread_list) override {
D
Dmitri Smirnov 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662
    assert(thread_status_updater_);
    return thread_status_updater_->GetThreadList(thread_list);
  }

  static uint64_t gettid() {
    uint64_t thread_id = GetCurrentThreadId();
    return thread_id;
  }

S
sdong 已提交
1663
  virtual uint64_t GetThreadID() const override { return gettid(); }
D
Dmitri Smirnov 已提交
1664

S
sdong 已提交
1665 1666
  virtual Status NewLogger(const std::string& fname,
                           std::shared_ptr<Logger>* result) override {
D
Dmitri Smirnov 已提交
1667 1668 1669 1670
    Status s;

    result->reset();

1671 1672 1673
    HANDLE hFile = 0;
    {
      IOSTATS_TIMER_GUARD(open_nanos);
S
sdong 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682
      hFile = CreateFileA(
          fname.c_str(), GENERIC_WRITE,
          FILE_SHARE_READ | FILE_SHARE_DELETE,  // In RocksDb log files are
                                                // renamed and deleted before
                                                // they are closed. This enables
                                                // doing so.
          NULL,
          CREATE_ALWAYS,  // Original fopen mode is "w"
          FILE_ATTRIBUTE_NORMAL, NULL);
1683
    }
D
Dmitri Smirnov 已提交
1684

1685
    if (INVALID_HANDLE_VALUE == hFile) {
D
Dmitri Smirnov 已提交
1686 1687 1688 1689
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError("Failed to open LogFile" + fname, lastError);
    } else {
      {
S
sdong 已提交
1690 1691 1692 1693
        // With log files we want to set the true creation time as of now
        // because the system
        // for some reason caches the attributes of the previous file that just
        // been renamed from
D
Dmitri Smirnov 已提交
1694 1695 1696 1697 1698 1699
        // this name so auto_roll_logger_test fails
        FILETIME ft;
        GetSystemTimeAsFileTime(&ft);
        // Set creation, last access and last write time to the same value
        SetFileTime(hFile, &ft, &ft, &ft);
      }
1700
      result->reset(new WinLogger(&WinEnv::gettid, this, hFile));
D
Dmitri Smirnov 已提交
1701 1702 1703 1704 1705
    }
    return s;
  }

  virtual uint64_t NowMicros() override {
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    if (GetSystemTimePreciseAsFileTime_ != NULL) {
      // all std::chrono clocks on windows proved to return
      // values that may repeat that is not good enough for some uses.
      const int64_t c_UnixEpochStartTicks = 116444736000000000i64;
      const int64_t c_FtToMicroSec = 10;

      // This interface needs to return system time and not
      // just any microseconds because it is often used as an argument
      // to TimedWait() on condition variable
      FILETIME ftSystemTime;
      GetSystemTimePreciseAsFileTime_(&ftSystemTime);

      LARGE_INTEGER li;
      li.LowPart = ftSystemTime.dwLowDateTime;
      li.HighPart = ftSystemTime.dwHighDateTime;
      // Subtract unix epoch start
      li.QuadPart -= c_UnixEpochStartTicks;
      // Convert to microsecs
      li.QuadPart /= c_FtToMicroSec;
      return li.QuadPart;
    }
    using namespace std::chrono;
    return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
D
Dmitri Smirnov 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
  }

  virtual uint64_t NowNanos() override {
    // all std::chrono clocks on windows have the same resolution that is only
    // good enough for microseconds but not nanoseconds
    // On Windows 8 and Windows 2012 Server
    // GetSystemTimePreciseAsFileTime(&current_time) can be used
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    // Convert to nanoseconds first to avoid loss of precision
    // and divide by frequency
    li.QuadPart *= std::nano::den;
    li.QuadPart /= perf_counter_frequency_;
    return li.QuadPart;
  }

S
sdong 已提交
1745
  virtual void SleepForMicroseconds(int micros) override {
D
Dmitri Smirnov 已提交
1746 1747 1748 1749 1750
    std::this_thread::sleep_for(std::chrono::microseconds(micros));
  }

  virtual Status GetHostName(char* name, uint64_t len) override {
    Status s;
1751 1752
    DWORD nSize = static_cast<DWORD>(
        std::min<uint64_t>(len, std::numeric_limits<DWORD>::max()));
D
Dmitri Smirnov 已提交
1753 1754 1755 1756 1757

    if (!::GetComputerNameA(name, &nSize)) {
      auto lastError = GetLastError();
      s = IOErrorFromWindowsError("GetHostName", lastError);
    } else {
S
sdong 已提交
1758
      name[nSize] = 0;
D
Dmitri Smirnov 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767
    }

    return s;
  }

  virtual Status GetCurrTime(int64_t* unix_time) {
    Status s;

    time_t ret = time(nullptr);
S
sdong 已提交
1768 1769 1770
    if (ret == (time_t)-1) {
      *unix_time = 0;
      s = IOError("GetCurrTime", errno);
D
Dmitri Smirnov 已提交
1771
    } else {
S
sdong 已提交
1772
      *unix_time = (int64_t)ret;
D
Dmitri Smirnov 已提交
1773 1774 1775 1776 1777
    }

    return s;
  }

S
sdong 已提交
1778 1779
  virtual Status GetAbsolutePath(const std::string& db_path,
                                 std::string* output_path) override {
D
Dmitri Smirnov 已提交
1780 1781
    // Check if we already have an absolute path
    // that starts with non dot and has a semicolon in it
S
sdong 已提交
1782 1783 1784 1785 1786 1787
    if ((!db_path.empty() && (db_path[0] == '/' || db_path[0] == '\\')) ||
        (db_path.size() > 2 && db_path[0] != '.' &&
         ((db_path[1] == ':' && db_path[2] == '\\') ||
          (db_path[1] == ':' && db_path[2] == '/')))) {
      *output_path = db_path;
      return Status::OK();
D
Dmitri Smirnov 已提交
1788 1789 1790 1791 1792 1793 1794
    }

    std::string result;
    result.resize(_MAX_PATH);

    char* ret = _getcwd(&result[0], _MAX_PATH);
    if (ret == nullptr) {
S
sdong 已提交
1795 1796
      return Status::IOError("Failed to get current working directory",
                             strerror(errno));
D
Dmitri Smirnov 已提交
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
    }

    result.resize(strlen(result.data()));

    result.swap(*output_path);
    return Status::OK();
  }

  // Allow increasing the number of worker threads.
  virtual void SetBackgroundThreads(int num, Priority pri) override {
    assert(pri >= Priority::LOW && pri <= Priority::HIGH);
    thread_pools_[pri].SetBackgroundThreads(num);
  }

  virtual void IncBackgroundThreadsIfNeeded(int num, Priority pri) override {
    assert(pri >= Priority::LOW && pri <= Priority::HIGH);
    thread_pools_[pri].IncBackgroundThreadsIfNeeded(num);
  }

  virtual std::string TimeToString(uint64_t secondsSince1970) override {
    std::string result;

    const time_t seconds = secondsSince1970;
    const int maxsize = 64;

    struct tm t;
    errno_t ret = localtime_s(&t, &seconds);

    if (ret) {
      result = std::to_string(seconds);
    } else {
      result.resize(maxsize);
      char* p = &result[0];

S
sdong 已提交
1831 1832 1833
      int len = 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);
D
Dmitri Smirnov 已提交
1834 1835 1836 1837 1838 1839 1840 1841
      assert(len > 0);

      result.resize(len);
    }

    return result;
  }

S
sdong 已提交
1842 1843
  EnvOptions OptimizeForLogWrite(const EnvOptions& env_options,
                                 const DBOptions& db_options) const override {
D
Dmitri Smirnov 已提交
1844 1845 1846
    EnvOptions optimized = env_options;
    optimized.use_mmap_writes = false;
    optimized.bytes_per_sync = db_options.wal_bytes_per_sync;
S
sdong 已提交
1847 1848 1849
    optimized.use_os_buffer =
        true;  // This is because we flush only whole pages on unbuffered io and
               // the last records are not guaranteed to be flushed.
D
Dmitri Smirnov 已提交
1850 1851 1852 1853 1854 1855 1856
    // 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;
    return optimized;
  }

S
sdong 已提交
1857 1858
  EnvOptions OptimizeForManifestWrite(
      const EnvOptions& env_options) const override {
D
Dmitri Smirnov 已提交
1859 1860 1861 1862 1863 1864 1865 1866
    EnvOptions optimized = env_options;
    optimized.use_mmap_writes = false;
    optimized.use_os_buffer = true;
    optimized.fallocate_with_keep_size = true;
    return optimized;
  }

 private:
S
sdong 已提交
1867 1868 1869 1870 1871
  // Returns true iff the named directory exists and is a directory.
  virtual bool DirExists(const std::string& dname) {
    WIN32_FILE_ATTRIBUTE_DATA attrs;
    if (GetFileAttributesExA(dname.c_str(), GetFileExInfoStandard, &attrs)) {
      return 0 != (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
D
Dmitri Smirnov 已提交
1872
    }
S
sdong 已提交
1873 1874
    return false;
  }
D
Dmitri Smirnov 已提交
1875

S
sdong 已提交
1876
  bool SupportsFastAllocate(const std::string& /* path */) { return false; }
D
Dmitri Smirnov 已提交
1877 1878

  class ThreadPool {
S
sdong 已提交
1879 1880 1881
   public:
    ThreadPool()
        : total_threads_limit_(1),
D
Dmitri Smirnov 已提交
1882 1883 1884 1885 1886
          bgthreads_(0),
          queue_(),
          queue_len_(0U),
          exit_all_threads_(false),
          low_io_priority_(false),
S
sdong 已提交
1887
          env_(nullptr) {}
D
Dmitri Smirnov 已提交
1888

S
sdong 已提交
1889
    ~ThreadPool() { assert(bgthreads_.size() == 0U); }
D
Dmitri Smirnov 已提交
1890

S
sdong 已提交
1891 1892 1893 1894 1895 1896
    void JoinAllThreads() {
      {
        std::lock_guard<std::mutex> lock(mu_);
        assert(!exit_all_threads_);
        exit_all_threads_ = true;
        bgsignal_.notify_all();
D
Dmitri Smirnov 已提交
1897 1898
      }

S
sdong 已提交
1899 1900
      for (std::thread& th : bgthreads_) {
        th.join();
D
Dmitri Smirnov 已提交
1901 1902
      }

S
sdong 已提交
1903 1904 1905
      // Subject to assert in the __dtor
      bgthreads_.clear();
    }
D
Dmitri Smirnov 已提交
1906

S
sdong 已提交
1907
    void SetHostEnv(Env* env) { env_ = env; }
D
Dmitri Smirnov 已提交
1908

S
sdong 已提交
1909 1910 1911 1912
    // Return true if there is at least one thread needs to terminate.
    bool HasExcessiveThread() const {
      return bgthreads_.size() > total_threads_limit_;
    }
D
Dmitri Smirnov 已提交
1913

S
sdong 已提交
1914 1915 1916 1917 1918 1919
    // 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) const {
      return HasExcessiveThread() && thread_id == bgthreads_.size() - 1;
    }
D
Dmitri Smirnov 已提交
1920

S
sdong 已提交
1921 1922 1923 1924
    // Is one of the threads to terminate.
    bool IsExcessiveThread(size_t thread_id) const {
      return thread_id >= total_threads_limit_;
    }
D
Dmitri Smirnov 已提交
1925

S
sdong 已提交
1926 1927 1928 1929 1930 1931
    // 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; }
D
Dmitri Smirnov 已提交
1932

S
sdong 已提交
1933
    void BGThread(size_t thread_id) {
D
Dmitri Smirnov 已提交
1934 1935 1936
      while (true) {
        // Wait until there is an item that is ready to run
        std::unique_lock<std::mutex> uniqueLock(mu_);
S
sdong 已提交
1937

D
Dmitri Smirnov 已提交
1938
        // Stop waiting if the thread needs to do work or needs to terminate.
S
sdong 已提交
1939 1940
        while (!exit_all_threads_ && !IsLastExcessiveThread(thread_id) &&
               (queue_.empty() || IsExcessiveThread(thread_id))) {
D
Dmitri Smirnov 已提交
1941 1942 1943
          bgsignal_.wait(uniqueLock);
        }

S
sdong 已提交
1944
        if (exit_all_threads_) {
D
Dmitri Smirnov 已提交
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
          // mechanism to let BG threads exit safely
          uniqueLock.unlock();
          break;
        }

        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.
          std::thread& terminating_thread = bgthreads_.back();
          auto tid = terminating_thread.get_id();
1956
          // Ensure that this thread is ours
D
Dmitri Smirnov 已提交
1957 1958 1959 1960 1961
          assert(tid == std::this_thread::get_id());
          terminating_thread.detach();
          bgthreads_.pop_back();

          if (HasExcessiveThread()) {
S
sdong 已提交
1962 1963
            // There is still at least more excessive thread to terminate.
            WakeUpAllThreads();
D
Dmitri Smirnov 已提交
1964 1965 1966 1967 1968 1969 1970 1971
          }

          uniqueLock.unlock();

          PrintThreadInfo(thread_id, gettid());
          break;
        }

S
sdong 已提交
1972
        void (*function)(void*) = queue_.front().function;
D
Dmitri Smirnov 已提交
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
        void* arg = queue_.front().arg;
        queue_.pop_front();
        queue_len_.store(queue_.size(), std::memory_order_relaxed);

        uniqueLock.unlock();
        (*function)(arg);
      }
    }

    // Helper struct for passing arguments when creating threads.
    struct BGThreadMetadata {
      ThreadPool* thread_pool_;
S
sdong 已提交
1985
      size_t thread_id_;  // Thread count in the thread.
D
Dmitri Smirnov 已提交
1986

1987
      BGThreadMetadata(ThreadPool* thread_pool, size_t thread_id)
S
sdong 已提交
1988
          : thread_pool_(thread_pool), thread_id_(thread_id) {}
D
Dmitri Smirnov 已提交
1989 1990 1991
    };

    static void* BGThreadWrapper(void* arg) {
S
sdong 已提交
1992 1993
      std::unique_ptr<BGThreadMetadata> meta(
          reinterpret_cast<BGThreadMetadata*>(arg));
D
Dmitri Smirnov 已提交
1994 1995 1996 1997 1998 1999

      size_t thread_id = meta->thread_id_;
      ThreadPool* tp = meta->thread_pool_;

#if ROCKSDB_USING_THREAD_STATUS
      // for thread-status
S
sdong 已提交
2000 2001 2002 2003
      ThreadStatusUtil::RegisterThread(
          tp->env_, (tp->GetThreadPriority() == Env::Priority::HIGH
                         ? ThreadStatus::HIGH_PRIORITY
                         : ThreadStatus::LOW_PRIORITY));
D
Dmitri Smirnov 已提交
2004 2005 2006 2007 2008 2009 2010 2011
#endif
      tp->BGThread(thread_id);
#if ROCKSDB_USING_THREAD_STATUS
      ThreadStatusUtil::UnregisterThread();
#endif
      return nullptr;
    }

S
sdong 已提交
2012
    void WakeUpAllThreads() { bgsignal_.notify_all(); }
D
Dmitri Smirnov 已提交
2013

S
sdong 已提交
2014 2015
    void SetBackgroundThreadsInternal(size_t num, bool allow_reduce) {
      std::lock_guard<std::mutex> lg(mu_);
D
Dmitri Smirnov 已提交
2016

S
sdong 已提交
2017 2018 2019
      if (exit_all_threads_) {
        return;
      }
D
Dmitri Smirnov 已提交
2020

S
sdong 已提交
2021
      if (num > total_threads_limit_ ||
D
Dmitri Smirnov 已提交
2022
          (num < total_threads_limit_ && allow_reduce)) {
S
sdong 已提交
2023 2024 2025
        total_threads_limit_ = std::max(size_t(1), num);
        WakeUpAllThreads();
        StartBGThreads();
D
Dmitri Smirnov 已提交
2026
      }
S
sdong 已提交
2027 2028
      assert(total_threads_limit_ > 0);
    }
D
Dmitri Smirnov 已提交
2029

S
sdong 已提交
2030 2031 2032
    void IncBackgroundThreadsIfNeeded(int num) {
      SetBackgroundThreadsInternal(num, false);
    }
D
Dmitri Smirnov 已提交
2033

S
sdong 已提交
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
    void SetBackgroundThreads(int num) {
      SetBackgroundThreadsInternal(num, true);
    }

    void StartBGThreads() {
      // Start background thread if necessary
      while (bgthreads_.size() < total_threads_limit_) {
        std::thread p_t(&ThreadPool::BGThreadWrapper,
                        new BGThreadMetadata(this, bgthreads_.size()));
        bgthreads_.push_back(std::move(p_t));
D
Dmitri Smirnov 已提交
2044
      }
S
sdong 已提交
2045
    }
D
Dmitri Smirnov 已提交
2046

2047 2048
    void Schedule(void (*function)(void* arg1), void* arg, void* tag,
                  void (*unschedFunction)(void* arg)) {
S
sdong 已提交
2049 2050 2051 2052
      std::lock_guard<std::mutex> lg(mu_);

      if (exit_all_threads_) {
        return;
D
Dmitri Smirnov 已提交
2053 2054
      }

S
sdong 已提交
2055
      StartBGThreads();
D
Dmitri Smirnov 已提交
2056

S
sdong 已提交
2057 2058 2059 2060 2061
      // Add to priority queue
      queue_.push_back(BGItem());
      queue_.back().function = function;
      queue_.back().arg = arg;
      queue_.back().tag = tag;
2062
      queue_.back().unschedFunction = unschedFunction;
S
sdong 已提交
2063
      queue_len_.store(queue_.size(), std::memory_order_relaxed);
D
Dmitri Smirnov 已提交
2064

S
sdong 已提交
2065 2066 2067 2068 2069 2070 2071 2072 2073
      if (!HasExcessiveThread()) {
        // Wake up at least one waiting thread.
        bgsignal_.notify_one();
      } else {
        // Need to wake up all threads to make sure the one woken
        // up is not the one to terminate.
        WakeUpAllThreads();
      }
    }
D
Dmitri Smirnov 已提交
2074

S
sdong 已提交
2075 2076
    int UnSchedule(void* arg) {
      int count = 0;
D
Dmitri Smirnov 已提交
2077

S
sdong 已提交
2078
      std::lock_guard<std::mutex> lg(mu_);
D
Dmitri Smirnov 已提交
2079

S
sdong 已提交
2080 2081 2082 2083
      // Remove from priority queue
      BGQueue::iterator it = queue_.begin();
      while (it != queue_.end()) {
        if (arg == (*it).tag) {
2084 2085 2086 2087 2088
          void (*unschedFunction)(void*) = (*it).unschedFunction;
          void* arg1 = (*it).arg;
          if (unschedFunction != nullptr) {
            (*unschedFunction)(arg1);
          }
S
sdong 已提交
2089 2090
          it = queue_.erase(it);
          count++;
D
Dmitri Smirnov 已提交
2091
        } else {
S
sdong 已提交
2092
          ++it;
D
Dmitri Smirnov 已提交
2093 2094 2095
        }
      }

S
sdong 已提交
2096
      queue_len_.store(queue_.size(), std::memory_order_relaxed);
D
Dmitri Smirnov 已提交
2097

S
sdong 已提交
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
      return count;
    }

    unsigned int GetQueueLen() const {
      return static_cast<unsigned int>(
          queue_len_.load(std::memory_order_relaxed));
    }

   private:
    // Entry per Schedule() call
    struct BGItem {
      void* arg;
      void (*function)(void*);
      void* tag;
2112
      void (*unschedFunction)(void*);
S
sdong 已提交
2113
    };
D
Dmitri Smirnov 已提交
2114

S
sdong 已提交
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
    typedef std::deque<BGItem> BGQueue;

    std::mutex mu_;
    std::condition_variable bgsignal_;
    size_t total_threads_limit_;
    std::vector<std::thread> bgthreads_;
    BGQueue queue_;
    std::atomic_size_t queue_len_;  // Queue length. Used for stats reporting
    bool exit_all_threads_;
    bool low_io_priority_;
    Env::Priority priority_;
    Env* env_;
D
Dmitri Smirnov 已提交
2127 2128
  };

S
sdong 已提交
2129 2130 2131 2132 2133 2134 2135 2136
  bool checkedDiskForMmap_;
  bool forceMmapOff;  // do we override Env options?
  size_t page_size_;
  size_t allocation_granularity_;
  uint64_t perf_counter_frequency_;
  std::vector<ThreadPool> thread_pools_;
  mutable std::mutex mu_;
  std::vector<std::thread> threads_to_join_;
2137
  FnGetSystemTimePreciseAsFileTime GetSystemTimePreciseAsFileTime_;
D
Dmitri Smirnov 已提交
2138 2139
};

S
sdong 已提交
2140 2141 2142 2143 2144 2145
WinEnv::WinEnv()
    : checkedDiskForMmap_(false),
      forceMmapOff(false),
      page_size_(4 * 1012),
      allocation_granularity_(page_size_),
      perf_counter_frequency_(0),
2146 2147
      thread_pools_(Priority::TOTAL),
      GetSystemTimePreciseAsFileTime_(NULL) {
2148

2149 2150 2151 2152
  HMODULE module = GetModuleHandle("kernel32.dll");
  if (module != NULL) {
    GetSystemTimePreciseAsFileTime_ = (FnGetSystemTimePreciseAsFileTime)GetProcAddress(
      module, "GetSystemTimePreciseAsFileTime");
2153 2154
  }

D
Dmitri Smirnov 已提交
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
  SYSTEM_INFO sinfo;
  GetSystemInfo(&sinfo);

  page_size_ = sinfo.dwPageSize;
  allocation_granularity_ = sinfo.dwAllocationGranularity;

  {
    LARGE_INTEGER qpf;
    BOOL ret = QueryPerformanceFrequency(&qpf);
    assert(ret == TRUE);
    perf_counter_frequency_ = qpf.QuadPart;
  }

  for (int pool_id = 0; pool_id < Env::Priority::TOTAL; ++pool_id) {
    thread_pools_[pool_id].SetThreadPriority(
S
sdong 已提交
2170
        static_cast<Env::Priority>(pool_id));
D
Dmitri Smirnov 已提交
2171 2172 2173 2174 2175 2176 2177 2178
    // This allows later initializing the thread-local-env of each thread.
    thread_pools_[pool_id].SetHostEnv(this);
  }

  // Protected member of the base class
  thread_status_updater_ = CreateThreadStatusUpdater();
}

S
sdong 已提交
2179
void WinEnv::Schedule(void (*function)(void*), void* arg, Priority pri,
2180
                      void* tag, void (*unschedFunction)(void* arg)) {
D
Dmitri Smirnov 已提交
2181
  assert(pri >= Priority::LOW && pri <= Priority::HIGH);
2182
  thread_pools_[pri].Schedule(function, arg, tag, unschedFunction);
D
Dmitri Smirnov 已提交
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
}

int WinEnv::UnSchedule(void* arg, Priority pri) {
  return thread_pools_[pri].UnSchedule(arg);
}

unsigned int WinEnv::GetThreadPoolQueueLen(Priority pri) const {
  assert(pri >= Priority::LOW && pri <= Priority::HIGH);
  return thread_pools_[pri].GetQueueLen();
}

S
sdong 已提交
2194
namespace {
D
Dmitri Smirnov 已提交
2195
struct StartThreadState {
S
sdong 已提交
2196 2197
  void (*user_function)(void*);
  void* arg;
D
Dmitri Smirnov 已提交
2198 2199 2200 2201
};
}

static void* StartThreadWrapper(void* arg) {
S
sdong 已提交
2202 2203
  std::unique_ptr<StartThreadState> state(
      reinterpret_cast<StartThreadState*>(arg));
D
Dmitri Smirnov 已提交
2204 2205 2206 2207 2208 2209 2210 2211 2212
  state->user_function(state->arg);
  return nullptr;
}

void WinEnv::StartThread(void (*function)(void* arg), void* arg) {
  StartThreadState* state = new StartThreadState;
  state->user_function = function;
  state->arg = arg;
  try {
S
sdong 已提交
2213
    std::thread th(&StartThreadWrapper, state);
D
Dmitri Smirnov 已提交
2214

S
sdong 已提交
2215 2216
    std::lock_guard<std::mutex> lg(mu_);
    threads_to_join_.push_back(std::move(th));
D
Dmitri Smirnov 已提交
2217

S
sdong 已提交
2218 2219
  } catch (const std::system_error& ex) {
    WinthreadCall("start thread", ex.code());
D
Dmitri Smirnov 已提交
2220 2221 2222 2223 2224
  }
}

void WinEnv::WaitForJoin() {
  for (auto& th : threads_to_join_) {
S
sdong 已提交
2225
    th.join();
D
Dmitri Smirnov 已提交
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
  }

  threads_to_join_.clear();
}

}  // namespace

std::string Env::GenerateUniqueId() {
  std::string result;

  UUID uuid;
  UuidCreateSequential(&uuid);

  RPC_CSTR rpc_str;
  auto status = UuidToStringA(&uuid, &rpc_str);
  assert(status == RPC_S_OK);

  result = reinterpret_cast<char*>(rpc_str);

  status = RpcStringFreeA(&rpc_str);
  assert(status == RPC_S_OK);

  return result;
}

S
sdong 已提交
2251 2252 2253 2254
// We choose to create this on the heap and using std::once for the following
// reasons
// 1) Currently available MS compiler does not implement atomic C++11
// initialization of
D
Dmitri Smirnov 已提交
2255
//    function local statics
S
sdong 已提交
2256 2257 2258 2259
// 2) We choose not to destroy the env because joining the threads from the
// system loader
//    which destroys the statics (same as from DLLMain) creates a system loader
//    dead-lock.
D
Dmitri Smirnov 已提交
2260 2261
//    in this manner any remaining threads are terminated OK.
namespace {
S
sdong 已提交
2262 2263
std::once_flag winenv_once_flag;
Env* envptr;
D
Dmitri Smirnov 已提交
2264 2265 2266 2267 2268 2269 2270 2271
};

Env* Env::Default() {
  std::call_once(winenv_once_flag, []() { envptr = new WinEnv(); });
  return envptr;
}

}  // namespace rocksdb