File size: 8,721 Bytes
68888be | 1 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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | // Windows file primitives and the completion-port engine.
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <malloc.h>
#include <deque>
#include <filesystem>
#include <vector>
#include "common/base.h"
#include "io/os_file.h"
namespace hk {
namespace os {
static std::wstring widen(const std::string& utf8) { return std::filesystem::u8path(utf8).wstring(); }
Handle open_read(const std::string& path, bool direct, bool overlapped, bool* got_direct) {
*got_direct = false;
std::wstring w = widen(path);
DWORD flags = FILE_ATTRIBUTE_NORMAL;
if (overlapped) flags |= FILE_FLAG_OVERLAPPED;
HANDLE h = INVALID_HANDLE_VALUE;
if (direct) {
// FILE_FLAG_NO_BUFFERING: offsets, lengths and buffers must be multiples of the
// sector size (4096 here)
h = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
flags | FILE_FLAG_NO_BUFFERING, nullptr);
if (h != INVALID_HANDLE_VALUE) *got_direct = true;
}
if (h == INVALID_HANDLE_VALUE) {
h = CreateFileW(w.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, flags, nullptr);
HK_CHECK(h != INVALID_HANDLE_VALUE, "cannot open %s: %s", path.c_str(),
error_text((int64_t)GetLastError()).c_str());
}
return (Handle)h;
}
void close(Handle h) {
if (h != kBadHandle) CloseHandle((HANDLE)h);
}
int64_t file_size(Handle h) {
LARGE_INTEGER sz;
HK_CHECK(GetFileSizeEx((HANDLE)h, &sz) != 0, "GetFileSizeEx failed: %s",
error_text((int64_t)GetLastError()).c_str());
return (int64_t)sz.QuadPart;
}
int64_t pread(Handle h, uint8_t* dst, int64_t len, int64_t offset) {
// Without FILE_FLAG_OVERLAPPED, ReadFile with an OVERLAPPED struct is a synchronous
// positional read that does not move the file pointer: threads can share the handle.
const int64_t kMax = (int64_t)1 << 30;
DWORD want = (DWORD)(len > kMax ? kMax : len);
OVERLAPPED ov;
ZeroMemory(&ov, sizeof(ov));
ov.Offset = (DWORD)((uint64_t)offset & 0xFFFFFFFFull);
ov.OffsetHigh = (DWORD)((uint64_t)offset >> 32);
DWORD got = 0;
if (ReadFile((HANDLE)h, dst, want, &got, &ov)) return (int64_t)got;
DWORD err = GetLastError();
if (err == ERROR_HANDLE_EOF) return 0;
return -(int64_t)err;
}
std::string error_text(int64_t code) {
DWORD err = (DWORD)(code < 0 ? -code : code);
char buf[512];
DWORD n = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, err, 0, buf,
(DWORD)sizeof(buf), nullptr);
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r' || buf[n - 1] == ' ')) --n;
return n ? strfmt("%.*s (Windows error %lu)", (int)n, buf, (unsigned long)err)
: strfmt("Windows error %lu", (unsigned long)err);
}
void* aligned_alloc_bytes(int64_t size, int64_t align) { return _aligned_malloc((size_t)size, (size_t)align); }
void aligned_free(void* p) { _aligned_free(p); }
} // namespace os
// Overlapped I/O through a completion port. Every read goes out with ReadFile +
// OVERLAPPED and is queued to the driver right away (real queue depth, no thread per
// request); a finished read posts a packet to the port, which wait() collects.
namespace {
class IocpIo : public IoEngine {
public:
explicit IocpIo(const IoOptions& opt) : opt_(opt) {
port_ = CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 0);
HK_CHECK(port_ != nullptr, "CreateIoCompletionPort failed: %s",
os::error_text((int64_t)GetLastError()).c_str());
}
~IocpIo() override {
// let reads in flight finish before their buffers and OVERLAPPED blocks go
IoCompletion c;
while (in_flight_ > 0) wait(&c, 1, 1);
for (auto& f : files_) os::close(f.h);
if (port_) CloseHandle(port_);
}
const char* name() const override { return "iocp"; }
int open(const std::string& path) override {
File f;
f.h = os::open_read(path, opt_.direct, /*overlapped=*/true, &f.direct);
f.size = os::file_size(f.h);
if (opt_.direct && !f.direct) HK_WARN("%s: unbuffered I/O refused, using buffered reads", path.c_str());
HANDLE r = CreateIoCompletionPort((HANDLE)f.h, port_, (ULONG_PTR)files_.size(), 0);
HK_CHECK(r != nullptr, "cannot attach %s to the completion port: %s", path.c_str(),
os::error_text((int64_t)GetLastError()).c_str());
files_.push_back(f);
return (int)files_.size() - 1;
}
int64_t file_size(int file) const override { return files_.at((size_t)file).size; }
bool is_direct(int file) const override { return files_.at((size_t)file).direct; }
int in_flight() const override { return in_flight_ + (int)pending_.size(); }
void submit(const IoRequest& r) override {
Op* op = new Op();
op->req = r;
pending_.push_back(op);
pump();
}
int wait(IoCompletion* out, int max, int min_complete) override {
int n = 0;
while (n < max) {
// what failed at submit time never reached the kernel: hand it back here
if (!ready_.empty()) {
out[n++] = ready_.front();
ready_.pop_front();
continue;
}
if (in_flight_ == 0 && pending_.empty()) break;
bool block = n < min_complete;
DWORD bytes = 0;
ULONG_PTR key = 0;
OVERLAPPED* pov = nullptr;
BOOL ok = GetQueuedCompletionStatus(port_, &bytes, &key, &pov, block ? INFINITE : 0);
if (pov == nullptr) {
if (!block) break; // nothing ready right now
HK_FAIL("GetQueuedCompletionStatus failed: %s", os::error_text((int64_t)GetLastError()).c_str());
}
Op* op = reinterpret_cast<Op*>(pov); // OVERLAPPED is the first member of Op
--in_flight_;
int64_t err = 0;
if (!ok) {
DWORD e = GetLastError();
if (e != ERROR_HANDLE_EOF) err = (int64_t)e;
bytes = 0;
}
op->done += (int64_t)bytes;
bool eof = op->req.offset + op->done >= files_[(size_t)op->req.file].size;
if (err == 0 && bytes > 0 && op->done < op->req.len && !eof) {
pending_.push_front(op); // short read in the middle of the file: read the rest
} else {
out[n++] = IoCompletion{op->req.tag, op->done, err};
delete op;
}
pump();
}
return n;
}
private:
struct Op {
OVERLAPPED ov; // must stay first
IoRequest req;
int64_t done = 0;
};
struct File {
os::Handle h = os::kBadHandle;
int64_t size = 0;
bool direct = false;
};
// issue queued requests while under the queue depth
void pump() {
while (!pending_.empty() && in_flight_ < opt_.queue_depth) {
Op* op = pending_.front();
pending_.pop_front();
const File& f = files_.at((size_t)op->req.file);
int64_t off = op->req.offset + op->done;
int64_t left = op->req.len - op->done;
const int64_t kMax = (int64_t)1 << 30; // ReadFile takes a 32-bit length
ZeroMemory(&op->ov, sizeof(op->ov));
op->ov.Offset = (DWORD)((uint64_t)off & 0xFFFFFFFFull);
op->ov.OffsetHigh = (DWORD)((uint64_t)off >> 32);
BOOL ok = ReadFile((HANDLE)f.h, op->req.dst + op->done, (DWORD)(left > kMax ? kMax : left), nullptr,
&op->ov);
DWORD e = ok ? ERROR_SUCCESS : GetLastError();
if (ok || e == ERROR_IO_PENDING) {
// a read that completed synchronously still posts a packet
++in_flight_;
} else {
// rejected at submit time: no packet will come
int64_t err = (e == ERROR_HANDLE_EOF) ? 0 : (int64_t)e;
ready_.push_back(IoCompletion{op->req.tag, op->done, err});
delete op;
}
}
}
IoOptions opt_;
HANDLE port_ = nullptr;
std::vector<File> files_;
std::deque<Op*> pending_;
std::deque<IoCompletion> ready_;
int in_flight_ = 0;
};
} // namespace
std::unique_ptr<IoEngine> make_iocp_io(const IoOptions& opt) { return std::unique_ptr<IoEngine>(new IocpIo(opt)); }
std::unique_ptr<IoEngine> make_uring_io(const IoOptions&) { return nullptr; }
} // namespace hk
#endif // _WIN32
|