okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-mac-rel (Mac Metal support) into f-144-rel6a74320ca

main
12.6 KiB371 linesraw
1// src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp.
2#include "strata/platform/direct_file.hpp"
3#include "strata/platform/aux_cpus.hpp"
4
5#include <algorithm>
6#include <chrono>
7#include <condition_variable>
8#include <cstdlib>
9#include <cstring>
10#include <deque>
11#include <mutex>
12#include <thread>
13#include <vector>
14
15#if defined(_WIN32)
16#define WIN32_LEAN_AND_MEAN
17#define NOMINMAX
18#include <windows.h>
19#else
20#include <fcntl.h>
21#include <sys/stat.h>
22#include <unistd.h>
23#endif
24
25namespace strata::platform {
26
27double now_us() {
28    using namespace std::chrono;
29    return (double) duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count() / 1000.0;
30}
31
32void* DirectFile::alloc_aligned(size_t bytes) {
33#if defined(_WIN32)
34    return VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
35#else
36    void* p = nullptr;
37    return posix_memalign(&p, alignment(), bytes) == 0 ? p : nullptr;
38#endif
39}
40
41void DirectFile::free_aligned(void* p) {
42    if (p == nullptr) return;
43#if defined(_WIN32)
44    VirtualFree(p, 0, MEM_RELEASE);
45#else
46    std::free(p);
47#endif
48}
49
50namespace {
51/// A queued read: `submit` only queues it; the pool's threads issue it (perf-review C-4 / F-2).  One thread
52/// issuing every read was the limit of the n-gram table's prompt reads: ~12 us of kernel time per read, ~80K
53/// reads/s, while an NVMe drive serves several times that at depth.
54struct Pending {
55    uint64_t offset;
56    void* buffer;
57    uint32_t length;
58    uint64_t tag;
59};
60
61/// The number of issuing threads: STRATA_IO_THREADS, else 4 (Windows: overlapped submits) / 16 (Linux: each
62/// thread does one blocking pread, so the thread count is the queue depth).
63int io_threads(int dflt) {
64    const char* v = std::getenv("STRATA_IO_THREADS");
65    const int n = v ? std::atoi(v) : dflt;
66    return std::clamp(n, 1, 64);
67}
68}  // namespace
69
70#if defined(_WIN32)
71// ------------------------------------------------------------------------------------------------ Windows
72namespace {
73/// One in-flight request. The OVERLAPPED must be the first member so a completion packet's OVERLAPPED*
74/// converts back to the request.
75struct Req {
76    OVERLAPPED ov;
77    uint64_t tag;
78};
79}  // namespace
80
81struct DirectFile::Impl {
82    HANDLE file = INVALID_HANDLE_VALUE;
83    HANDLE port = nullptr;
84    uint64_t size = 0;
85    std::mutex mu;                      // everything below
86    std::deque<Req*> free_reqs;
87    std::vector<Req*> all_reqs;
88    std::deque<Completion> immediate;   // requests that completed without a port packet (EOF) or failed
89    std::deque<Pending> queue;          // submitted, not yet issued
90    std::condition_variable cv;
91    bool stop = false;
92    std::vector<std::thread> pool;
93
94    Req* take() {
95        if (free_reqs.empty()) {
96            Req* r = new Req();
97            all_reqs.push_back(r);
98            return r;
99        }
100        Req* r = free_reqs.front();
101        free_reqs.pop_front();
102        return r;
103    }
104
105    void issue(const Pending& p) {
106        Req* r;
107        {
108            std::lock_guard<std::mutex> lk(mu);
109            r = take();
110        }
111        std::memset(&r->ov, 0, sizeof r->ov);
112        r->ov.Offset = (DWORD) (p.offset & 0xFFFFFFFFull);
113        r->ov.OffsetHigh = (DWORD) (p.offset >> 32);
114        r->tag = p.tag;
115        if (!ReadFile(file, p.buffer, p.length, nullptr, &r->ov)) {
116            const DWORD e = GetLastError();
117            if (e != ERROR_IO_PENDING) {
118                std::lock_guard<std::mutex> lk(mu);
119                free_reqs.push_back(r);
120                // at or past end of file: a zero-byte completion; anything else: a failed one
121                immediate.push_back(Completion{p.tag, 0, e == ERROR_HANDLE_EOF});
122                PostQueuedCompletionStatus(port, 0, 0, nullptr);   // wake a waiter to collect it
123            }
124        }
125    }
126
127    void worker() {
128        std::unique_lock<std::mutex> lk(mu);
129        for (;;) {
130            cv.wait(lk, [&] { return stop || !queue.empty(); });
131            if (stop && queue.empty()) return;
132            const Pending p = queue.front();
133            queue.pop_front();
134            lk.unlock();
135            issue(p);
136            lk.lock();
137        }
138    }
139
140    void stop_pool() {
141        {
142            std::lock_guard<std::mutex> lk(mu);
143            stop = true;
144        }
145        cv.notify_all();
146        for (std::thread& t : pool) t.join();
147        pool.clear();
148        stop = false;
149    }
150};
151
152DirectFile::DirectFile() : impl_(new Impl) {}
153DirectFile::~DirectFile() {
154    close();
155    for (Req* r : impl_->all_reqs) delete r;
156    delete impl_;
157}
158
159bool DirectFile::open(const std::string& path, std::string& err) {
160    close();
161    const int wlen = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
162    std::wstring wpath((size_t) (wlen > 0 ? wlen : 1), L'\0');
163    MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wlen);
164    // NO_BUFFERING: the cache manager never holds these pages, so the table cannot grow into RAM.
165    // RANDOM_ACCESS: no read-ahead. OVERLAPPED: many reads in flight, completed through the port below.
166    impl_->file = CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
167                              FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED | FILE_FLAG_RANDOM_ACCESS, nullptr);
168    if (impl_->file == INVALID_HANDLE_VALUE) {
169        err = "DirectFile: cannot open " + path + " (error " + std::to_string(GetLastError()) + ")";
170        return false;
171    }
172    LARGE_INTEGER sz;
173    if (!GetFileSizeEx(impl_->file, &sz)) {
174        err = "DirectFile: cannot size " + path;
175        close();
176        return false;
177    }
178    impl_->size = (uint64_t) sz.QuadPart;
179    impl_->port = CreateIoCompletionPort(impl_->file, nullptr, 0, 1);
180    if (impl_->port == nullptr) {
181        err = "DirectFile: CreateIoCompletionPort failed (error " + std::to_string(GetLastError()) + ")";
182        close();
183        return false;
184    }
185    // Completions of reads that finish synchronously are still queued to the port, so every issued read
186    // produces exactly one packet; `wait` is the only completion path.
187    const int n = io_threads(4);
188    for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); });
189    return true;
190}
191
192void DirectFile::close() {
193    impl_->stop_pool();
194    if (impl_->port != nullptr) CloseHandle(impl_->port);
195    if (impl_->file != INVALID_HANDLE_VALUE) CloseHandle(impl_->file);
196    impl_->port = nullptr;
197    impl_->file = INVALID_HANDLE_VALUE;
198    impl_->size = 0;
199    impl_->immediate.clear();
200    impl_->queue.clear();
201}
202
203bool DirectFile::is_open() const { return impl_->file != INVALID_HANDLE_VALUE; }
204uint64_t DirectFile::size() const { return impl_->size; }
205
206bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err) {
207    if (!is_open()) { err = "DirectFile: not open"; return false; }
208    if (offset % alignment() || length % alignment() || ((uintptr_t) buffer) % alignment() || length == 0) {
209        err = "DirectFile: unaligned request";
210        return false;
211    }
212    {
213        std::lock_guard<std::mutex> lk(impl_->mu);
214        impl_->queue.push_back(Pending{offset, buffer, length, tag});
215    }
216    impl_->cv.notify_one();
217    return true;
218}
219
220int DirectFile::wait(Completion* out, int max, int timeout_ms) {
221    int n = 0;
222    {
223        std::lock_guard<std::mutex> lk(impl_->mu);
224        while (n < max && !impl_->immediate.empty()) {
225            out[n++] = impl_->immediate.front();
226            impl_->immediate.pop_front();
227        }
228    }
229    if (n == max || !is_open()) return n;
230    OVERLAPPED_ENTRY entries[64];
231    const ULONG want = (ULONG) (max - n < 64 ? max - n : 64);
232    ULONG got = 0;
233    const DWORD t = timeout_ms < 0 ? INFINITE : (DWORD) timeout_ms;
234    if (!GetQueuedCompletionStatusEx(impl_->port, entries, want, &got, n > 0 ? 0 : t, FALSE)) return n;
235    std::lock_guard<std::mutex> lk(impl_->mu);
236    for (ULONG i = 0; i < got; ++i) {
237        if (entries[i].lpOverlapped == nullptr) {          // a wake() packet (or an immediate completion's nudge)
238            while (n < max && !impl_->immediate.empty()) {
239                out[n++] = impl_->immediate.front();
240                impl_->immediate.pop_front();
241            }
242            if (n < max) out[n++] = Completion{WAKE_TAG, 0, true};
243            continue;
244        }
245        Req* r = (Req*) entries[i].lpOverlapped;
246        const uint32_t status = (uint32_t) r->ov.Internal;   // an NTSTATUS
247        Completion c;
248        c.tag = r->tag;
249        c.bytes = entries[i].dwNumberOfBytesTransferred;
250        // STATUS_END_OF_FILE (0xC0000011) is a legal short read at the table's last page.
251        c.ok = status == 0 || status == 0xC0000011u;
252        out[n++] = c;
253        impl_->free_reqs.push_back(r);
254    }
255    return n;
256}
257
258void DirectFile::wake() {
259    if (impl_->port != nullptr) PostQueuedCompletionStatus(impl_->port, 0, 0, nullptr);
260}
261
262#else
263// ------------------------------------------------------------------------------------------------ POSIX
264// perf-review F-2: a pool of threads, each doing blocking O_DIRECT preads, so reads run in parallel (the thread
265// count is the queue depth).  It replaced one synchronous pread inside `submit`, which read the n-gram table's
266// rows one at a time.
267struct DirectFile::Impl {
268    int fd = -1;
269    uint64_t size = 0;
270    std::mutex mu;
271    std::condition_variable cv_work, cv_done;
272    std::deque<Pending> queue;
273    std::deque<Completion> done;
274    bool stop = false;
275    std::vector<std::thread> pool;
276
277    void worker() {
278        std::unique_lock<std::mutex> lk(mu);
279        for (;;) {
280            cv_work.wait(lk, [&] { return stop || !queue.empty(); });
281            if (stop && queue.empty()) return;
282            const Pending p = queue.front();
283            queue.pop_front();
284            lk.unlock();
285            const ssize_t got = pread(fd, p.buffer, p.length, (off_t) p.offset);
286            lk.lock();
287            done.push_back(Completion{p.tag, got < 0 ? 0u : (uint32_t) got, got >= 0});
288            cv_done.notify_all();
289        }
290    }
291
292    void stop_pool() {
293        {
294            std::lock_guard<std::mutex> lk(mu);
295            stop = true;
296        }
297        cv_work.notify_all();
298        for (std::thread& t : pool) t.join();
299        pool.clear();
300        stop = false;
301    }
302};
303
304DirectFile::DirectFile() : impl_(new Impl) {}
305DirectFile::~DirectFile() { close(); delete impl_; }
306
307bool DirectFile::open(const std::string& path, std::string& err) {
308    close();
309#if defined(__APPLE__)   // macOS has no O_DIRECT: F_NOCACHE keeps the reads out of the unified buffer cache
310    impl_->fd = ::open(path.c_str(), O_RDONLY);
311    if (impl_->fd >= 0 && fcntl(impl_->fd, F_NOCACHE, 1) != 0) { ::close(impl_->fd); impl_->fd = -1; }
312#else
313    impl_->fd = ::open(path.c_str(), O_RDONLY | O_DIRECT);
314#endif
315    if (impl_->fd < 0) { err = "DirectFile: cannot open " + path; return false; }
316    struct stat st;
317    if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; }
318    impl_->size = (uint64_t) st.st_size;
319    const int n = io_threads(16);
320    for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); });
321    return true;
322}
323
324void DirectFile::close() {
325    impl_->stop_pool();
326    if (impl_->fd >= 0) ::close(impl_->fd);
327    impl_->fd = -1;
328    impl_->size = 0;
329    impl_->done.clear();
330    impl_->queue.clear();
331}
332
333bool DirectFile::is_open() const { return impl_->fd >= 0; }
334uint64_t DirectFile::size() const { return impl_->size; }
335
336bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err) {
337    if (offset % alignment() || length % alignment() || ((uintptr_t) buffer) % alignment() || length == 0) {
338        err = "DirectFile: unaligned request";
339        return false;
340    }
341    {
342        std::lock_guard<std::mutex> lk(impl_->mu);
343        impl_->queue.push_back(Pending{offset, buffer, length, tag});
344    }
345    impl_->cv_work.notify_one();
346    return true;
347}
348
349void DirectFile::wake() {
350    std::lock_guard<std::mutex> lk(impl_->mu);
351    impl_->done.push_back(Completion{WAKE_TAG, 0, true});
352    impl_->cv_done.notify_all();
353}
354
355int DirectFile::wait(Completion* out, int max, int timeout_ms) {
356    std::unique_lock<std::mutex> lk(impl_->mu);
357    if (impl_->done.empty() && timeout_ms != 0) {
358        auto ready = [&] { return !impl_->done.empty(); };
359        if (timeout_ms < 0) impl_->cv_done.wait(lk, ready);
360        else impl_->cv_done.wait_for(lk, std::chrono::milliseconds(timeout_ms), ready);
361    }
362    int n = 0;
363    while (n < max && !impl_->done.empty()) {
364        out[n++] = impl_->done.front();
365        impl_->done.pop_front();
366    }
367    return n;
368}
369#endif
370
371}  // namespace strata::platform