Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

711 Zeilen
21 KiB

  1. // Copyright (c) 2018 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. // Prevent Windows headers from defining min/max macros and instead
  5. // use STL.
  6. #ifndef NOMINMAX
  7. #define NOMINMAX
  8. #endif // ifndef NOMINMAX
  9. #include <windows.h>
  10. #include <algorithm>
  11. #include <atomic>
  12. #include <chrono>
  13. #include <condition_variable>
  14. #include <deque>
  15. #include <memory>
  16. #include <mutex>
  17. #include <sstream>
  18. #include <string>
  19. #include <vector>
  20. #include "leveldb/env.h"
  21. #include "leveldb/slice.h"
  22. #include "port/port.h"
  23. #include "port/thread_annotations.h"
  24. #include "util/env_windows_test_helper.h"
  25. #include "util/logging.h"
  26. #include "util/mutexlock.h"
  27. #include "util/windows_logger.h"
  28. #if defined(DeleteFile)
  29. #undef DeleteFile
  30. #endif // defined(DeleteFile)
  31. namespace leveldb {
  32. namespace {
  33. constexpr const size_t kWritableFileBufferSize = 65536;
  34. // Up to 1000 mmaps for 64-bit binaries; none for 32-bit.
  35. constexpr int kDefaultMmapLimit = sizeof(void*) >= 8 ? 1000 : 0;
  36. // Modified by EnvWindowsTestHelper::SetReadOnlyMMapLimit().
  37. int g_mmap_limit = kDefaultMmapLimit;
  38. std::string GetWindowsErrorMessage(DWORD error_code) {
  39. std::string message;
  40. char* error_text = nullptr;
  41. // Use MBCS version of FormatMessage to match return value.
  42. size_t error_text_size = ::FormatMessageA(
  43. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER |
  44. FORMAT_MESSAGE_IGNORE_INSERTS,
  45. nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  46. reinterpret_cast<char*>(&error_text), 0, nullptr);
  47. if (!error_text) {
  48. return message;
  49. }
  50. message.assign(error_text, error_text_size);
  51. ::LocalFree(error_text);
  52. return message;
  53. }
  54. Status WindowsError(const std::string& context, DWORD error_code) {
  55. if (error_code == ERROR_FILE_NOT_FOUND || error_code == ERROR_PATH_NOT_FOUND)
  56. return Status::NotFound(context, GetWindowsErrorMessage(error_code));
  57. return Status::IOError(context, GetWindowsErrorMessage(error_code));
  58. }
  59. class ScopedHandle {
  60. public:
  61. ScopedHandle(HANDLE handle) : handle_(handle) {}
  62. ScopedHandle(ScopedHandle&& other) noexcept : handle_(other.Release()) {}
  63. ~ScopedHandle() { Close(); }
  64. ScopedHandle& operator=(ScopedHandle&& rhs) noexcept {
  65. if (this != &rhs) handle_ = rhs.Release();
  66. return *this;
  67. }
  68. bool Close() {
  69. if (!is_valid()) {
  70. return true;
  71. }
  72. HANDLE h = handle_;
  73. handle_ = INVALID_HANDLE_VALUE;
  74. return ::CloseHandle(h);
  75. }
  76. bool is_valid() const {
  77. return handle_ != INVALID_HANDLE_VALUE && handle_ != nullptr;
  78. }
  79. HANDLE get() const { return handle_; }
  80. HANDLE Release() {
  81. HANDLE h = handle_;
  82. handle_ = INVALID_HANDLE_VALUE;
  83. return h;
  84. }
  85. private:
  86. HANDLE handle_;
  87. };
  88. // Helper class to limit resource usage to avoid exhaustion.
  89. // Currently used to limit read-only file descriptors and mmap file usage
  90. // so that we do not run out of file descriptors or virtual memory, or run into
  91. // kernel performance problems for very large databases.
  92. class Limiter {
  93. public:
  94. // Limit maximum number of resources to |max_acquires|.
  95. Limiter(int max_acquires) : acquires_allowed_(max_acquires) {}
  96. Limiter(const Limiter&) = delete;
  97. Limiter operator=(const Limiter&) = delete;
  98. // If another resource is available, acquire it and return true.
  99. // Else return false.
  100. bool Acquire() {
  101. int old_acquires_allowed =
  102. acquires_allowed_.fetch_sub(1, std::memory_order_relaxed);
  103. if (old_acquires_allowed > 0) return true;
  104. acquires_allowed_.fetch_add(1, std::memory_order_relaxed);
  105. return false;
  106. }
  107. // Release a resource acquired by a previous call to Acquire() that returned
  108. // true.
  109. void Release() { acquires_allowed_.fetch_add(1, std::memory_order_relaxed); }
  110. private:
  111. // The number of available resources.
  112. //
  113. // This is a counter and is not tied to the invariants of any other class, so
  114. // it can be operated on safely using std::memory_order_relaxed.
  115. std::atomic<int> acquires_allowed_;
  116. };
  117. class WindowsSequentialFile : public SequentialFile {
  118. public:
  119. WindowsSequentialFile(std::string fname, ScopedHandle file)
  120. : filename_(fname), file_(std::move(file)) {}
  121. ~WindowsSequentialFile() override {}
  122. Status Read(size_t n, Slice* result, char* scratch) override {
  123. Status s;
  124. DWORD bytes_read;
  125. // DWORD is 32-bit, but size_t could technically be larger. However leveldb
  126. // files are limited to leveldb::Options::max_file_size which is clamped to
  127. // 1<<30 or 1 GiB.
  128. assert(n <= std::numeric_limits<DWORD>::max());
  129. if (!::ReadFile(file_.get(), scratch, static_cast<DWORD>(n), &bytes_read,
  130. nullptr)) {
  131. s = WindowsError(filename_, ::GetLastError());
  132. } else {
  133. *result = Slice(scratch, bytes_read);
  134. }
  135. return s;
  136. }
  137. Status Skip(uint64_t n) override {
  138. LARGE_INTEGER distance;
  139. distance.QuadPart = n;
  140. if (!::SetFilePointerEx(file_.get(), distance, nullptr, FILE_CURRENT)) {
  141. return WindowsError(filename_, ::GetLastError());
  142. }
  143. return Status::OK();
  144. }
  145. private:
  146. std::string filename_;
  147. ScopedHandle file_;
  148. };
  149. class WindowsRandomAccessFile : public RandomAccessFile {
  150. public:
  151. WindowsRandomAccessFile(std::string fname, ScopedHandle handle)
  152. : filename_(fname), handle_(std::move(handle)) {}
  153. ~WindowsRandomAccessFile() override = default;
  154. Status Read(uint64_t offset, size_t n, Slice* result,
  155. char* scratch) const override {
  156. DWORD bytes_read = 0;
  157. OVERLAPPED overlapped = {0};
  158. overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
  159. overlapped.Offset = static_cast<DWORD>(offset);
  160. if (!::ReadFile(handle_.get(), scratch, static_cast<DWORD>(n), &bytes_read,
  161. &overlapped)) {
  162. DWORD error_code = ::GetLastError();
  163. if (error_code != ERROR_HANDLE_EOF) {
  164. *result = Slice(scratch, 0);
  165. return Status::IOError(filename_, GetWindowsErrorMessage(error_code));
  166. }
  167. }
  168. *result = Slice(scratch, bytes_read);
  169. return Status::OK();
  170. }
  171. private:
  172. std::string filename_;
  173. ScopedHandle handle_;
  174. };
  175. class WindowsMmapReadableFile : public RandomAccessFile {
  176. public:
  177. // base[0,length-1] contains the mmapped contents of the file.
  178. WindowsMmapReadableFile(std::string fname, void* base, size_t length,
  179. Limiter* limiter)
  180. : filename_(std::move(fname)),
  181. mmapped_region_(base),
  182. length_(length),
  183. limiter_(limiter) {}
  184. ~WindowsMmapReadableFile() override {
  185. ::UnmapViewOfFile(mmapped_region_);
  186. limiter_->Release();
  187. }
  188. Status Read(uint64_t offset, size_t n, Slice* result,
  189. char* scratch) const override {
  190. Status s;
  191. if (offset + n > length_) {
  192. *result = Slice();
  193. s = WindowsError(filename_, ERROR_INVALID_PARAMETER);
  194. } else {
  195. *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
  196. }
  197. return s;
  198. }
  199. private:
  200. std::string filename_;
  201. void* mmapped_region_;
  202. size_t length_;
  203. Limiter* limiter_;
  204. };
  205. class WindowsWritableFile : public WritableFile {
  206. public:
  207. WindowsWritableFile(std::string fname, ScopedHandle handle)
  208. : filename_(std::move(fname)), handle_(std::move(handle)), pos_(0) {}
  209. ~WindowsWritableFile() override = default;
  210. Status Append(const Slice& data) override {
  211. size_t n = data.size();
  212. const char* p = data.data();
  213. // Fit as much as possible into buffer.
  214. size_t copy = std::min(n, kWritableFileBufferSize - pos_);
  215. memcpy(buf_ + pos_, p, copy);
  216. p += copy;
  217. n -= copy;
  218. pos_ += copy;
  219. if (n == 0) {
  220. return Status::OK();
  221. }
  222. // Can't fit in buffer, so need to do at least one write.
  223. Status s = FlushBuffered();
  224. if (!s.ok()) {
  225. return s;
  226. }
  227. // Small writes go to buffer, large writes are written directly.
  228. if (n < kWritableFileBufferSize) {
  229. memcpy(buf_, p, n);
  230. pos_ = n;
  231. return Status::OK();
  232. }
  233. return WriteRaw(p, n);
  234. }
  235. Status Close() override {
  236. Status result = FlushBuffered();
  237. if (!handle_.Close() && result.ok()) {
  238. result = WindowsError(filename_, ::GetLastError());
  239. }
  240. return result;
  241. }
  242. Status Flush() override { return FlushBuffered(); }
  243. Status Sync() override {
  244. // On Windows no need to sync parent directory. It's metadata will be
  245. // updated via the creation of the new file, without an explicit sync.
  246. return FlushBuffered();
  247. }
  248. private:
  249. Status FlushBuffered() {
  250. Status s = WriteRaw(buf_, pos_);
  251. pos_ = 0;
  252. return s;
  253. }
  254. Status WriteRaw(const char* p, size_t n) {
  255. DWORD bytes_written;
  256. if (!::WriteFile(handle_.get(), p, static_cast<DWORD>(n), &bytes_written,
  257. nullptr)) {
  258. return Status::IOError(filename_,
  259. GetWindowsErrorMessage(::GetLastError()));
  260. }
  261. return Status::OK();
  262. }
  263. // buf_[0, pos_-1] contains data to be written to handle_.
  264. const std::string filename_;
  265. ScopedHandle handle_;
  266. char buf_[kWritableFileBufferSize];
  267. size_t pos_;
  268. };
  269. // Lock or unlock the entire file as specified by |lock|. Returns true
  270. // when successful, false upon failure. Caller should call ::GetLastError()
  271. // to determine cause of failure
  272. bool LockOrUnlock(HANDLE handle, bool lock) {
  273. if (lock) {
  274. return ::LockFile(handle,
  275. /*dwFileOffsetLow=*/0, /*dwFileOffsetHigh=*/0,
  276. /*nNumberOfBytesToLockLow=*/MAXDWORD,
  277. /*nNumberOfBytesToLockHigh=*/MAXDWORD);
  278. } else {
  279. return ::UnlockFile(handle,
  280. /*dwFileOffsetLow=*/0, /*dwFileOffsetHigh=*/0,
  281. /*nNumberOfBytesToLockLow=*/MAXDWORD,
  282. /*nNumberOfBytesToLockHigh=*/MAXDWORD);
  283. }
  284. }
  285. class WindowsFileLock : public FileLock {
  286. public:
  287. WindowsFileLock(ScopedHandle handle, std::string name)
  288. : handle_(std::move(handle)), name_(std::move(name)) {}
  289. ScopedHandle& handle() { return handle_; }
  290. const std::string& name() const { return name_; }
  291. private:
  292. ScopedHandle handle_;
  293. std::string name_;
  294. };
  295. class WindowsEnv : public Env {
  296. public:
  297. WindowsEnv();
  298. ~WindowsEnv() override {
  299. static char msg[] = "Destroying Env::Default()\n";
  300. fwrite(msg, 1, sizeof(msg), stderr);
  301. abort();
  302. }
  303. Status NewSequentialFile(const std::string& fname,
  304. SequentialFile** result) override {
  305. *result = nullptr;
  306. DWORD desired_access = GENERIC_READ;
  307. DWORD share_mode = FILE_SHARE_READ;
  308. ScopedHandle handle =
  309. ::CreateFileA(fname.c_str(), desired_access, share_mode, nullptr,
  310. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  311. if (!handle.is_valid()) {
  312. return WindowsError(fname, ::GetLastError());
  313. }
  314. *result = new WindowsSequentialFile(fname, std::move(handle));
  315. return Status::OK();
  316. }
  317. Status NewRandomAccessFile(const std::string& fname,
  318. RandomAccessFile** result) override {
  319. *result = nullptr;
  320. DWORD desired_access = GENERIC_READ;
  321. DWORD share_mode = FILE_SHARE_READ;
  322. DWORD file_flags = FILE_ATTRIBUTE_READONLY;
  323. ScopedHandle handle =
  324. ::CreateFileA(fname.c_str(), desired_access, share_mode, nullptr,
  325. OPEN_EXISTING, file_flags, nullptr);
  326. if (!handle.is_valid()) {
  327. return WindowsError(fname, ::GetLastError());
  328. }
  329. if (!mmap_limiter_.Acquire()) {
  330. *result = new WindowsRandomAccessFile(fname, std::move(handle));
  331. return Status::OK();
  332. }
  333. LARGE_INTEGER file_size;
  334. if (!::GetFileSizeEx(handle.get(), &file_size)) {
  335. return WindowsError(fname, ::GetLastError());
  336. }
  337. ScopedHandle mapping =
  338. ::CreateFileMappingA(handle.get(),
  339. /*security attributes=*/nullptr, PAGE_READONLY,
  340. /*dwMaximumSizeHigh=*/0,
  341. /*dwMaximumSizeLow=*/0, nullptr);
  342. if (mapping.is_valid()) {
  343. void* base = MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0);
  344. if (base) {
  345. *result = new WindowsMmapReadableFile(
  346. fname, base, static_cast<size_t>(file_size.QuadPart),
  347. &mmap_limiter_);
  348. return Status::OK();
  349. }
  350. }
  351. Status s = WindowsError(fname, ::GetLastError());
  352. if (!s.ok()) {
  353. mmap_limiter_.Release();
  354. }
  355. return s;
  356. }
  357. Status NewWritableFile(const std::string& fname,
  358. WritableFile** result) override {
  359. DWORD desired_access = GENERIC_WRITE;
  360. DWORD share_mode = 0;
  361. ScopedHandle handle =
  362. ::CreateFileA(fname.c_str(), desired_access, share_mode, nullptr,
  363. CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
  364. if (!handle.is_valid()) {
  365. *result = nullptr;
  366. return WindowsError(fname, ::GetLastError());
  367. }
  368. *result = new WindowsWritableFile(fname, std::move(handle));
  369. return Status::OK();
  370. }
  371. Status NewAppendableFile(const std::string& fname,
  372. WritableFile** result) override {
  373. ScopedHandle handle =
  374. ::CreateFileA(fname.c_str(), FILE_APPEND_DATA, 0, nullptr, OPEN_ALWAYS,
  375. FILE_ATTRIBUTE_NORMAL, nullptr);
  376. if (!handle.is_valid()) {
  377. *result = nullptr;
  378. return WindowsError(fname, ::GetLastError());
  379. }
  380. *result = new WindowsWritableFile(fname, std::move(handle));
  381. return Status::OK();
  382. }
  383. bool FileExists(const std::string& fname) override {
  384. return GetFileAttributesA(fname.c_str()) != INVALID_FILE_ATTRIBUTES;
  385. }
  386. Status GetChildren(const std::string& dir,
  387. std::vector<std::string>* result) override {
  388. const std::string find_pattern = dir + "\\*";
  389. WIN32_FIND_DATAA find_data;
  390. HANDLE dir_handle = ::FindFirstFileA(find_pattern.c_str(), &find_data);
  391. if (dir_handle == INVALID_HANDLE_VALUE) {
  392. DWORD last_error = ::GetLastError();
  393. if (last_error == ERROR_FILE_NOT_FOUND) {
  394. return Status::OK();
  395. }
  396. return WindowsError(dir, last_error);
  397. }
  398. do {
  399. char base_name[_MAX_FNAME];
  400. char ext[_MAX_EXT];
  401. if (!_splitpath_s(find_data.cFileName, nullptr, 0, nullptr, 0, base_name,
  402. ARRAYSIZE(base_name), ext, ARRAYSIZE(ext))) {
  403. result->emplace_back(std::string(base_name) + ext);
  404. }
  405. } while (::FindNextFileA(dir_handle, &find_data));
  406. DWORD last_error = ::GetLastError();
  407. ::FindClose(dir_handle);
  408. if (last_error != ERROR_NO_MORE_FILES) {
  409. return WindowsError(dir, last_error);
  410. }
  411. return Status::OK();
  412. }
  413. Status DeleteFile(const std::string& fname) override {
  414. if (!::DeleteFileA(fname.c_str())) {
  415. return WindowsError(fname, ::GetLastError());
  416. }
  417. return Status::OK();
  418. }
  419. Status CreateDir(const std::string& name) override {
  420. if (!::CreateDirectoryA(name.c_str(), nullptr)) {
  421. return WindowsError(name, ::GetLastError());
  422. }
  423. return Status::OK();
  424. }
  425. Status DeleteDir(const std::string& name) override {
  426. if (!::RemoveDirectoryA(name.c_str())) {
  427. return WindowsError(name, ::GetLastError());
  428. }
  429. return Status::OK();
  430. }
  431. Status GetFileSize(const std::string& fname, uint64_t* size) override {
  432. WIN32_FILE_ATTRIBUTE_DATA attrs;
  433. if (!::GetFileAttributesExA(fname.c_str(), GetFileExInfoStandard, &attrs)) {
  434. return WindowsError(fname, ::GetLastError());
  435. }
  436. ULARGE_INTEGER file_size;
  437. file_size.HighPart = attrs.nFileSizeHigh;
  438. file_size.LowPart = attrs.nFileSizeLow;
  439. *size = file_size.QuadPart;
  440. return Status::OK();
  441. }
  442. Status RenameFile(const std::string& src,
  443. const std::string& target) override {
  444. // Try a simple move first. It will only succeed when |to_path| doesn't
  445. // already exist.
  446. if (::MoveFileA(src.c_str(), target.c_str())) {
  447. return Status::OK();
  448. }
  449. DWORD move_error = ::GetLastError();
  450. // Try the full-blown replace if the move fails, as ReplaceFile will only
  451. // succeed when |to_path| does exist. When writing to a network share, we
  452. // may not be able to change the ACLs. Ignore ACL errors then
  453. // (REPLACEFILE_IGNORE_MERGE_ERRORS).
  454. if (::ReplaceFileA(target.c_str(), src.c_str(), nullptr,
  455. REPLACEFILE_IGNORE_MERGE_ERRORS, nullptr, nullptr)) {
  456. return Status::OK();
  457. }
  458. DWORD replace_error = ::GetLastError();
  459. // In the case of FILE_ERROR_NOT_FOUND from ReplaceFile, it is likely
  460. // that |to_path| does not exist. In this case, the more relevant error
  461. // comes from the call to MoveFile.
  462. if (replace_error == ERROR_FILE_NOT_FOUND ||
  463. replace_error == ERROR_PATH_NOT_FOUND) {
  464. return WindowsError(src, move_error);
  465. } else {
  466. return WindowsError(src, replace_error);
  467. }
  468. }
  469. Status LockFile(const std::string& fname, FileLock** lock) override {
  470. *lock = nullptr;
  471. Status result;
  472. ScopedHandle handle = ::CreateFileA(
  473. fname.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
  474. /*lpSecurityAttributes=*/nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL,
  475. nullptr);
  476. if (!handle.is_valid()) {
  477. result = WindowsError(fname, ::GetLastError());
  478. } else if (!LockOrUnlock(handle.get(), true)) {
  479. result = WindowsError("lock " + fname, ::GetLastError());
  480. } else {
  481. *lock = new WindowsFileLock(std::move(handle), std::move(fname));
  482. }
  483. return result;
  484. }
  485. Status UnlockFile(FileLock* lock) override {
  486. std::unique_ptr<WindowsFileLock> my_lock(
  487. reinterpret_cast<WindowsFileLock*>(lock));
  488. Status result;
  489. if (!LockOrUnlock(my_lock->handle().get(), false)) {
  490. result = WindowsError("unlock", ::GetLastError());
  491. }
  492. return result;
  493. }
  494. void Schedule(void (*function)(void*), void* arg) override;
  495. void StartThread(void (*function)(void* arg), void* arg) override {
  496. std::thread t(function, arg);
  497. t.detach();
  498. }
  499. Status GetTestDirectory(std::string* result) override {
  500. const char* env = getenv("TEST_TMPDIR");
  501. if (env && env[0] != '\0') {
  502. *result = env;
  503. return Status::OK();
  504. }
  505. char tmp_path[MAX_PATH];
  506. if (!GetTempPathA(ARRAYSIZE(tmp_path), tmp_path)) {
  507. return WindowsError("GetTempPath", ::GetLastError());
  508. }
  509. std::stringstream ss;
  510. ss << tmp_path << "leveldbtest-" << std::this_thread::get_id();
  511. *result = ss.str();
  512. // Directory may already exist
  513. CreateDir(*result);
  514. return Status::OK();
  515. }
  516. Status NewLogger(const std::string& filename, Logger** result) override {
  517. std::FILE* fp = std::fopen(filename.c_str(), "w");
  518. if (fp == nullptr) {
  519. *result = nullptr;
  520. return WindowsError("NewLogger", ::GetLastError());
  521. } else {
  522. *result = new WindowsLogger(fp);
  523. return Status::OK();
  524. }
  525. }
  526. uint64_t NowMicros() override {
  527. // GetSystemTimeAsFileTime typically has a resolution of 10-20 msec.
  528. // TODO(cmumford): Switch to GetSystemTimePreciseAsFileTime which is
  529. // available in Windows 8 and later.
  530. FILETIME ft;
  531. ::GetSystemTimeAsFileTime(&ft);
  532. // Each tick represents a 100-nanosecond intervals since January 1, 1601
  533. // (UTC).
  534. uint64_t num_ticks =
  535. (static_cast<uint64_t>(ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
  536. return num_ticks / 10;
  537. }
  538. void SleepForMicroseconds(int micros) override {
  539. std::this_thread::sleep_for(std::chrono::microseconds(micros));
  540. }
  541. private:
  542. // Entry per Schedule() call
  543. struct BGItem {
  544. void* arg;
  545. void (*function)(void*);
  546. };
  547. // BGThread() is the body of the background thread
  548. void BGThread();
  549. std::mutex mu_;
  550. std::condition_variable bgsignal_;
  551. bool started_bgthread_;
  552. std::deque<BGItem> queue_;
  553. Limiter mmap_limiter_;
  554. };
  555. // Return the maximum number of concurrent mmaps.
  556. int MaxMmaps() {
  557. if (g_mmap_limit >= 0) {
  558. return g_mmap_limit;
  559. }
  560. // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
  561. g_mmap_limit = sizeof(void*) >= 8 ? 1000 : 0;
  562. return g_mmap_limit;
  563. }
  564. WindowsEnv::WindowsEnv()
  565. : started_bgthread_(false), mmap_limiter_(MaxMmaps()) {}
  566. void WindowsEnv::Schedule(void (*function)(void*), void* arg) {
  567. std::lock_guard<std::mutex> guard(mu_);
  568. // Start background thread if necessary
  569. if (!started_bgthread_) {
  570. started_bgthread_ = true;
  571. std::thread t(&WindowsEnv::BGThread, this);
  572. t.detach();
  573. }
  574. // If the queue is currently empty, the background thread may currently be
  575. // waiting.
  576. if (queue_.empty()) {
  577. bgsignal_.notify_one();
  578. }
  579. // Add to priority queue
  580. queue_.push_back(BGItem());
  581. queue_.back().function = function;
  582. queue_.back().arg = arg;
  583. }
  584. void WindowsEnv::BGThread() {
  585. while (true) {
  586. // Wait until there is an item that is ready to run
  587. std::unique_lock<std::mutex> lk(mu_);
  588. bgsignal_.wait(lk, [this] { return !queue_.empty(); });
  589. void (*function)(void*) = queue_.front().function;
  590. void* arg = queue_.front().arg;
  591. queue_.pop_front();
  592. lk.unlock();
  593. (*function)(arg);
  594. }
  595. }
  596. } // namespace
  597. static std::once_flag once;
  598. static Env* default_env;
  599. static void InitDefaultEnv() { default_env = new WindowsEnv(); }
  600. void EnvWindowsTestHelper::SetReadOnlyMMapLimit(int limit) {
  601. assert(default_env == nullptr);
  602. g_mmap_limit = limit;
  603. }
  604. Env* Env::Default() {
  605. std::call_once(once, InitDefaultEnv);
  606. return default_env;
  607. }
  608. } // namespace leveldb