okami.mom/strata

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

waveringanadsv41: opt-in DS4_STAGE_MB staging that lets prompt reads run ahead, DS4_READ_RUN_MB merged preadv of adjacent expert reads, reader occupancy in the prompt-stream line00c004617

main
23.7 KiB588 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// src/ds4/ds4_os.hpp - the few OS services maya-ds4 needs, on Linux and on Windows: files read at an offset and
4// mapped read-only (the experts read in place), page-cache hints, anonymous host memory on a NUMA node, thread pinning,
5// each NUMA node's physical cores, the RAM this process can still get.  (On Windows as src/core/expert_source.cpp
6// does it for GLM: no FILE_FLAG_RANDOM_ACCESS - the page cache must keep what it read.)
7#pragma once
8
9#include <algorithm>
10#include <cstdint>
11#include <cstdio>
12#include <cstdlib>
13#include <sstream>
14#include <string>
15#include <thread>
16#include <vector>
17
18#if defined(_WIN32)
19#define WIN32_LEAN_AND_MEAN
20#ifndef NOMINMAX
21#define NOMINMAX
22#endif
23#include <windows.h>
24#include <psapi.h>   // (K32QueryWorkingSetEx: kernel32's, no psapi.lib)
25#include <timeapi.h>
26#ifdef _MSC_VER
27#pragma comment(lib, "winmm.lib")
28#endif
29#else
30#include <fcntl.h>
31#include <pthread.h>
32#include <sched.h>
33#include <sys/mman.h>
34#include <sys/stat.h>
35#include <sys/syscall.h>
36#include <sys/uio.h>
37#include <unistd.h>
38#endif
39
40namespace strata::ds4::os {
41
42/// Windows sleeps in 15.6 ms ticks unless a process asks for finer ones: the CPU lane's service thread naps (sleep_for 20 us)
43/// between tokens, and the device's first wait of the next token then waits out the tick.  1 ms for the process's life
44/// (Project Maya #358).  Off by default (owner PC, shipped profile, 3 pairs: not faster in every pair); DS4_TIMER_MS=1 turns it on.
45/// Elsewhere nothing.
46inline void fine_timer() {
47#if defined(_WIN32)
48    const char* v = std::getenv("DS4_TIMER_MS");
49    const int ms = v != nullptr ? std::atoi(v) : 0;
50    if (ms > 0) timeBeginPeriod((UINT) ms);
51#endif
52}
53
54using fd_t = intptr_t;
55constexpr fd_t kBadFd = -1;
56
57#if defined(_WIN32)
58inline std::wstring wide(const std::string& s) {   // UTF-8 -> UTF-16 (a path with non-ASCII characters)
59    const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
60    std::wstring w((size_t) (n > 0 ? n : 1), L'\0');
61    if (n > 0) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, &w[0], n);
62    return w;
63}
64#endif
65
66/// A file opened for reading (kBadFd: it could not be).
67inline fd_t open_ro(const std::string& path) {
68#if defined(_WIN32)
69    HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
70                           FILE_ATTRIBUTE_NORMAL, nullptr);
71    return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
72#else
73    const int fd = ::open(path.c_str(), O_RDONLY);
74    return fd < 0 ? kBadFd : (fd_t) fd;
75#endif
76}
77/// The same file opened for unbuffered reads (Linux: O_DIRECT - no page cache, the disk straight into the buffer;
78/// kBadFd where the filesystem refuses it, or on Windows, whose unbuffered reads of a mapped file take a slow path)
79inline fd_t open_direct(const std::string& path) {
80#if defined(_WIN32)
81    // FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED: the disk straight into an aligned buffer, any number of reads in flight on
82    // one handle (DS4_WIN_DIRECT=0: none, the page cache's buffered reads as before)
83    static const bool off = [] {
84        const char* v = std::getenv("DS4_WIN_DIRECT");
85        return v != nullptr && std::atoi(v) == 0;
86    }();
87    if (off) return kBadFd;
88    HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
89                           FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, nullptr);
90    return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
91#else
92    const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT);
93    return fd < 0 ? kBadFd : (fd_t) fd;
94#endif
95}
96/// [off, off + n) through an unbuffered descriptor into dst, a kDirectAlign-aligned buffer of at least
97/// direct_span(off, n) bytes: the file read from off rounded down, so the bytes land at dst + (off % kDirectAlign).
98/// False if a read fails (the caller reads buffered instead).
99constexpr uint64_t kDirectAlign = 4096;
100inline uint64_t direct_span(uint64_t off, uint64_t n) {
101    const uint64_t a0 = off & ~(kDirectAlign - 1), a1 = (off + n + kDirectAlign - 1) & ~(kDirectAlign - 1);
102    return a1 - a0;
103}
104inline bool pread_direct(fd_t f, void* dst, uint64_t n, uint64_t off) {
105#if defined(_WIN32)
106    struct Ev {   // (each thread its own, closed when it ends)
107        HANDLE h = CreateEventW(nullptr, TRUE, FALSE, nullptr);
108        ~Ev() {
109            if (h != nullptr) CloseHandle(h);
110        }
111    };
112    static thread_local Ev ev;
113    if (ev.h == nullptr) return false;
114    const uint64_t a0 = off & ~(kDirectAlign - 1), need = direct_span(off, n), want = (off - a0) + n;
115    uint8_t* p = (uint8_t*) dst;
116    uint64_t got = 0;
117    while (got < need) {
118        const DWORD ask = (DWORD) std::min<uint64_t>(need - got, 1ull << 30);   // (a multiple of 4096)
119        OVERLAPPED ov{};
120        const uint64_t at = a0 + got;
121        ov.Offset = (DWORD) (at & 0xffffffffu);
122        ov.OffsetHigh = (DWORD) (at >> 32);
123        ov.hEvent = ev.h;
124        ResetEvent(ev.h);
125        DWORD r = 0;
126        if (!ReadFile((HANDLE) f, p + got, ask, nullptr, &ov)) {
127            const DWORD e = GetLastError();
128            if (e == ERROR_HANDLE_EOF) break;
129            if (e != ERROR_IO_PENDING) return false;
130        }
131        if (!GetOverlappedResult((HANDLE) f, &ov, &r, TRUE)) {
132            if (GetLastError() == ERROR_HANDLE_EOF) break;
133            return false;
134        }
135        if (r == 0) break;   // (the file's end: the last aligned read is short)
136        got += r;
137        if (r % kDirectAlign != 0) break;
138    }
139    return got >= want;
140#else
141    const uint64_t a0 = off & ~(kDirectAlign - 1), need = direct_span(off, n), want = (off - a0) + n;
142    uint8_t* p = (uint8_t*) dst;
143    uint64_t got = 0;
144    while (got < need) {
145        const ssize_t r = ::pread((int) f, p + got, (size_t) std::min<uint64_t>(need - got, 1ull << 30), (off_t) (a0 + got));
146        if (r < 0) return false;
147        if (r == 0) break;   // (the file's end: the last aligned read is short)
148        got += (uint64_t) r;
149        if ((uint64_t) r % kDirectAlign != 0) break;
150    }
151    return got >= want;
152#endif
153}
154/// One unbuffered read from off (kDirectAlign-aligned) scattered over n buffers in order, each 512-aligned and each
155/// length a multiple of 512; true if at least `want` bytes came (Windows: false, the caller reads each part alone)
156inline bool preadv_direct(fd_t f, uint8_t* const* bufs, const uint64_t* lens, int n, uint64_t off, uint64_t want) {
157#if defined(_WIN32)
158    (void) f, (void) bufs, (void) lens, (void) n, (void) off, (void) want;
159    return false;
160#else
161    std::vector<iovec> iov((size_t) n);
162    for (int i = 0; i < n; ++i) iov[(size_t) i] = iovec{bufs[i], (size_t) lens[i]};
163    uint64_t got = 0;
164    size_t first = 0;
165    while (got < want && first < iov.size()) {   // (a short read ends on a 512-byte boundary: the rest from there)
166        const ssize_t r = ::preadv((int) f, iov.data() + first, (int) (iov.size() - first), (off_t) (off + got));
167        if (r <= 0 || r % 512 != 0) return got + (uint64_t) std::max<ssize_t>(r, 0) >= want;
168        got += (uint64_t) r;
169        for (uint64_t k = (uint64_t) r; k > 0 && first < iov.size();) {
170            const uint64_t t = std::min<uint64_t>(k, iov[first].iov_len);
171            iov[first].iov_base = (uint8_t*) iov[first].iov_base + t;
172            iov[first].iov_len -= t;
173            k -= t;
174            if (iov[first].iov_len == 0) ++first;
175        }
176    }
177    return got >= want;
178#endif
179}
180/// Windows: the file opened for unbuffered reads (FILE_FLAG_NO_BUFFERING), for a file no view of this process maps -
181/// unbuffered reads of a mapped file take a slow path there (open_direct); kBadFd elsewhere
182inline fd_t open_unbuffered(const std::string& path) {
183#if defined(_WIN32)
184    HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
185                           FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING, nullptr);
186    return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
187#else
188    (void) path;
189    return kBadFd;
190#endif
191}
192/// [off, off + n) through open_unbuffered's handle (one thread's) into buf, kDirectAlign-aligned and at least
193/// direct_span(off, n) bytes: the bytes land at buf + off % kDirectAlign
194inline bool pread_unbuffered(fd_t f, void* buf, uint64_t n, uint64_t off) {
195#if defined(_WIN32)
196    const uint64_t a0 = off & ~(kDirectAlign - 1), span = direct_span(off, n);
197    OVERLAPPED ov{};
198    ov.Offset = (DWORD) a0;
199    ov.OffsetHigh = (DWORD) (a0 >> 32);
200    DWORD got = 0;
201    return ReadFile((HANDLE) f, buf, (DWORD) span, &got, &ov) && got >= (off - a0) + n;
202#else
203    (void) f, (void) buf, (void) n, (void) off;
204    return false;
205#endif
206}
207/// The same file opened for reads from many threads at once (Windows runs the reads of a synchronous handle one at a
208/// time, so an overlapped one; Linux: a plain descriptor, pread is concurrent anyway)
209inline fd_t open_par(const std::string& path) {
210#if defined(_WIN32)
211    HANDLE h = CreateFileW(wide(path).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
212                           FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, nullptr);
213    return h == INVALID_HANDLE_VALUE ? kBadFd : (fd_t) h;
214#else
215    const int fd = ::open(path.c_str(), O_RDONLY);
216    return fd < 0 ? kBadFd : (fd_t) fd;
217#endif
218}
219/// n bytes at off through open_par's handle (any thread, concurrently)
220inline bool pread_par(fd_t f, void* dst, uint64_t n, uint64_t off) {
221#if defined(_WIN32)
222    struct Ev {   // (each thread its own, closed when it ends)
223        HANDLE h = CreateEventW(nullptr, TRUE, FALSE, nullptr);
224        ~Ev() {
225            if (h != nullptr) CloseHandle(h);
226        }
227    };
228    static thread_local Ev ev;
229    if (ev.h == nullptr) return false;
230    uint8_t* p = (uint8_t*) dst;
231    while (n > 0) {
232        const DWORD want = (DWORD) std::min<uint64_t>(n, 1ull << 30);
233        OVERLAPPED ov{};
234        ov.Offset = (DWORD) (off & 0xffffffffu);
235        ov.OffsetHigh = (DWORD) (off >> 32);
236        ov.hEvent = ev.h;
237        ResetEvent(ev.h);
238        DWORD got = 0;
239        if (!ReadFile((HANDLE) f, p, want, nullptr, &ov) && GetLastError() != ERROR_IO_PENDING) return false;
240        if (!GetOverlappedResult((HANDLE) f, &ov, &got, TRUE) || got == 0) return false;
241        p += got, off += got, n -= got;
242    }
243    return true;
244#else
245    uint8_t* p = (uint8_t*) dst;
246    while (n > 0) {
247        const ssize_t r = ::pread((int) f, p, (size_t) std::min<uint64_t>(n, 1ull << 30), (off_t) off);
248        if (r <= 0) return false;
249        p += r, off += (uint64_t) r, n -= (uint64_t) r;
250    }
251    return true;
252#endif
253}
254/// `from` renamed to `to`, replacing `to` if it exists (rename(2) does; Windows' rename fails on an existing file, so
255/// MoveFileExW with MOVEFILE_REPLACE_EXISTING)
256inline bool replace_file(const std::string& from, const std::string& to) {
257#if defined(_WIN32)
258    return MoveFileExW(wide(from).c_str(), wide(to).c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
259#else
260    return std::rename(from.c_str(), to.c_str()) == 0;
261#endif
262}
263inline void close_fd(fd_t f) {
264    if (f == kBadFd) return;
265#if defined(_WIN32)
266    CloseHandle((HANDLE) f);
267#else
268    ::close((int) f);
269#endif
270}
271inline uint64_t file_size(fd_t f) {
272#if defined(_WIN32)
273    LARGE_INTEGER sz{};
274    return GetFileSizeEx((HANDLE) f, &sz) ? (uint64_t) sz.QuadPart : 0;
275#else
276    struct stat sb;
277    return ::fstat((int) f, &sb) == 0 && sb.st_size > 0 ? (uint64_t) sb.st_size : 0;
278#endif
279}
280/// n bytes at offset off into dst (any thread, concurrently); false if the file ends first or a read fails.
281inline bool pread_full(fd_t f, void* dst, uint64_t n, uint64_t off) {
282    uint8_t* p = (uint8_t*) dst;
283    while (n > 0) {
284        const uint64_t want = std::min<uint64_t>(n, 1ull << 30);
285#if defined(_WIN32)
286        OVERLAPPED ov{};
287        ov.Offset = (DWORD) (off & 0xffffffffu);
288        ov.OffsetHigh = (DWORD) (off >> 32);
289        DWORD got = 0;
290        if (!ReadFile((HANDLE) f, p, (DWORD) want, &got, &ov) || got == 0) return false;
291        const uint64_t r = got;
292#else
293        const ssize_t rr = ::pread((int) f, p, (size_t) want, (off_t) off);
294        if (rr <= 0) return false;
295        const uint64_t r = (uint64_t) rr;
296#endif
297        p += r, off += r, n -= r;
298    }
299    return true;
300}
301/// The whole file mapped read-only (nullptr: it could not be).
302inline void* map_ro(fd_t f, uint64_t bytes) {
303    if (bytes == 0) return nullptr;
304#if defined(_WIN32)
305    HANDLE m = CreateFileMappingW((HANDLE) f, nullptr, PAGE_READONLY, 0, 0, nullptr);
306    if (m == nullptr) return nullptr;
307    void* v = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
308    CloseHandle(m);   // (the view keeps the mapping)
309    return v;
310#else
311    void* p = ::mmap(nullptr, (size_t) bytes, PROT_READ, MAP_SHARED, (int) f, 0);
312    return p == MAP_FAILED ? nullptr : p;
313#endif
314}
315inline void unmap(void* p, uint64_t bytes) {
316    if (p == nullptr) return;
317#if defined(_WIN32)
318    (void) bytes;
319    UnmapViewOfFile(p);
320#else
321    ::munmap(p, (size_t) bytes);
322#endif
323}
324/// A hint that [off, off + n) of the file is needed soon (need) or not again soon (!need); nothing where the OS has
325/// no such hint for a file (Windows' page cache reads ahead on its own).
326inline void advise(fd_t f, uint64_t off, uint64_t n, bool need) {
327#if defined(_WIN32)
328    (void) f, (void) off, (void) n, (void) need;
329#else
330    posix_fadvise((int) f, (off_t) off, (off_t) n, need ? POSIX_FADV_WILLNEED : POSIX_FADV_DONTNEED);
331#endif
332}
333
334/// Ranges of a file's mapping about to be read: the OS reads them in now, with large requests side by side, instead of
335/// a page fault at a time later (Windows: PrefetchVirtualMemory - cold expert-sized pieces came in 5x faster on an NVMe;
336/// Linux: madvise WILLNEED, the kernel's read-ahead of the whole range).  Best effort: a failure changes nothing.
337inline void prefetch(const std::vector<std::pair<const void*, size_t>>& ranges) {
338    if (ranges.empty()) return;
339#if defined(_WIN32)
340    std::vector<WIN32_MEMORY_RANGE_ENTRY> r(ranges.size());
341    for (size_t i = 0; i < ranges.size(); ++i) {
342        r[i].VirtualAddress = const_cast<void*>(ranges[i].first);
343        r[i].NumberOfBytes = ranges[i].second;
344    }
345    PrefetchVirtualMemory(GetCurrentProcess(), (ULONG_PTR) r.size(), r.data(), 0);
346#else
347    const uintptr_t pg = 4096;
348    for (const auto& x : ranges) {
349        const uintptr_t a = (uintptr_t) x.first, b = a & ~(pg - 1);
350        madvise((void*) b, x.second + (a - b), MADV_WILLNEED);
351    }
352#endif
353}
354
355/// Whether every page of [p, p + n) of a file's mapping is in the page cache (Linux mincore; elsewhere false: the
356/// caller reads buffered anyway, which the cache serves)
357inline bool resident(const void* p, size_t n) {
358#if defined(_WIN32)
359    (void) p, (void) n;
360    return false;
361#else
362    const uintptr_t pg = 4096, a = (uintptr_t) p, b = a & ~(pg - 1);
363    const size_t len = n + (a - b), np = (len + pg - 1) / pg;
364    thread_local std::vector<unsigned char> v;
365    if (v.size() < np) v.resize(np);
366    if (mincore((void*) b, len, v.data()) != 0) return false;
367    for (size_t i = 0; i < np; ++i)
368        if ((v[i] & 1) == 0) return false;
369    return true;
370#endif
371}
372
373/// Whether a range of a file's mapping looks resident, so that prefetch() would only cost CPU time (it walks every page:
374/// ~50 ns a 4 KiB page on Windows - 0.34 ms for a 6.3 MB expert matrix on a Strix Halo): `samples` pages spread over
375/// it all resident (Linux: mincore, the page cache; Windows: QueryWorkingSetEx, the process's working set - a page on
376/// the standby list counts as not resident, and prefetch() is what brings those back cheaply).  An expert's pages are
377/// read together, so they come and go together: a wrong "yes" costs page faults, a wrong "no" a prefetch.
378inline bool resident_sampled(const void* p, size_t bytes, int samples = 8) {
379    if (bytes == 0) return true;
380    const uintptr_t pg = 4096, a = (uintptr_t) p, span = bytes - 1;
381    samples = std::max(1, std::min(samples, 16));
382#if defined(_WIN32)
383    PSAPI_WORKING_SET_EX_INFORMATION w[16] = {};
384    for (int i = 0; i < samples; ++i)
385        w[i].VirtualAddress = (PVOID) ((a + (samples > 1 ? span / (samples - 1) * i : 0)) & ~(pg - 1));
386    if (!K32QueryWorkingSetEx(GetCurrentProcess(), w, (DWORD) (samples * sizeof w[0]))) return false;
387    for (int i = 0; i < samples; ++i)
388        if (!w[i].VirtualAttributes.Valid) return false;
389    return true;
390#else
391    for (int i = 0; i < samples; ++i) {
392        unsigned char v = 0;
393        const uintptr_t at = (a + (samples > 1 ? span / (samples - 1) * i : 0)) & ~(pg - 1);
394        if (mincore((void*) at, pg, &v) != 0 || !(v & 1)) return false;
395    }
396    return true;
397#endif
398}
399/// prefetch() of the ranges that do not look resident (resident_sampled) - on Windows, where PrefetchVirtualMemory walks
400/// every page of a resident range (0.34 ms a 6.3 MB expert matrix on a Strix Halo); Linux's madvise(WILLNEED) on cached
401/// pages costs ~1 us a matrix (a Core i5-12600T), less than the residency check (2.5 us): every range there
402inline void prefetch_cold(const std::vector<std::pair<const void*, size_t>>& ranges) {
403#if defined(_WIN32)
404    static const bool all = [] {   // (DS4_PF_ALL=1: every range, as before)
405        const char* v = std::getenv("DS4_PF_ALL");
406        return v != nullptr && std::atoi(v) != 0;
407    }();
408    if (all) return prefetch(ranges);
409    std::vector<std::pair<const void*, size_t>> cold;
410    for (const auto& x : ranges)
411        if (!resident_sampled(x.first, x.second)) cold.push_back(x);
412    prefetch(cold);
413#else
414    prefetch(ranges);
415#endif
416}
417
418/// Whether [p, p + n) of a file's mapping is in RAM now: every page (Linux, one mincore), sampled pages of the working
419/// set (Windows; a page on the standby list counts as not in RAM)
420inline bool in_ram(const void* p, size_t n) {
421#if defined(_WIN32)
422    return resident_sampled(p, n, 8);
423#else
424    return resident(p, n);
425#endif
426}
427
428/// Anonymous memory on NUMA node `node` of `nodes` (node < 0 or nodes < 2: wherever the first touch puts it), on huge
429/// pages where the OS gives them; nullptr if it cannot be had.
430inline void* anon_alloc(size_t bytes, int node, int nodes) {
431#if defined(_WIN32)
432    if (node >= 0 && nodes > 1)
433        return VirtualAllocExNuma(GetCurrentProcess(), nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE,
434                                  (DWORD) node);
435    return VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
436#else
437    void* m = ::mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
438    if (m == MAP_FAILED) return nullptr;
439    madvise(m, bytes, MADV_HUGEPAGE);
440    if (node >= 0 && nodes > 1) {
441        unsigned long mask[4] = {0, 0, 0, 0};
442        mask[node / 64] = 1ul << (node % 64);
443        syscall(SYS_mbind, m, bytes, 2 /* MPOL_BIND */, mask, 256, 0);
444    }
445    return m;
446#endif
447}
448/// An address range of `bytes` reserved (no memory behind it yet), and pieces of it made real: the store's arena is one range so a
449/// kernel can tell its pointers by [lo, hi).  nullptr: it could not be had.
450inline void* range_reserve(size_t bytes) {
451#if defined(_WIN32)
452    return VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_READWRITE);
453#else
454    void* m = ::mmap(nullptr, bytes, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
455    return m == MAP_FAILED ? nullptr : m;
456#endif
457}
458inline bool range_commit(void* p, size_t bytes) {
459#if defined(_WIN32)
460    return VirtualAlloc(p, bytes, MEM_COMMIT, PAGE_READWRITE) != nullptr;
461#else
462    return ::mprotect(p, bytes, PROT_READ | PROT_WRITE) == 0;
463#endif
464}
465/// A committed piece of a reserved range given back to the system (its address range stays reserved)
466inline void range_decommit(void* p, size_t bytes) {
467#if defined(_WIN32)
468    VirtualFree(p, bytes, MEM_DECOMMIT);
469#else
470    ::madvise(p, bytes, MADV_DONTNEED);
471    ::mprotect(p, bytes, PROT_NONE);
472#endif
473}
474inline void range_release(void* p, size_t bytes) {
475    if (p == nullptr) return;
476#if defined(_WIN32)
477    (void) bytes;
478    VirtualFree(p, 0, MEM_RELEASE);
479#else
480    ::munmap(p, bytes);
481#endif
482}
483inline void anon_free(void* p, size_t bytes) {
484    if (p == nullptr) return;
485#if defined(_WIN32)
486    (void) bytes;
487    VirtualFree(p, 0, MEM_RELEASE);
488#else
489    ::munmap(p, bytes);
490#endif
491}
492
493/// The calling thread, or `t`, on logical CPU `cpu` (Windows: the first 64 CPUs, processor group 0).
494inline void pin_self(int cpu) {
495#if defined(_WIN32)
496    if (cpu >= 0 && cpu < 64) SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR) 1 << cpu);
497#else
498    cpu_set_t set;
499    CPU_ZERO(&set);
500    CPU_SET(cpu, &set);
501    sched_setaffinity(0, sizeof set, &set);
502#endif
503}
504inline void pin_thread(std::thread& t, int cpu) {
505#if defined(_WIN32)
506    if (cpu >= 0 && cpu < 64) SetThreadAffinityMask((HANDLE) t.native_handle(), (DWORD_PTR) 1 << cpu);
507#else
508    cpu_set_t set;
509    CPU_ZERO(&set);
510    CPU_SET(cpu, &set);
511    pthread_setaffinity_np(t.native_handle(), sizeof(set), &set);
512#endif
513}
514
515#if defined(_WIN32)
516/// Each NUMA node's physical cores (the first logical CPU of each), processor group 0 - Windows' answer to
517/// /sys/devices/system/node; empty if the OS does not say.
518inline std::vector<std::vector<int>> node_cores(bool smt = false) {   // (smt: every logical CPU of a core, not its first)
519    std::vector<std::vector<int>> nodes;
520    auto query = [](LOGICAL_PROCESSOR_RELATIONSHIP rel, std::vector<uint8_t>& buf) {
521        DWORD len = 0;
522        GetLogicalProcessorInformationEx(rel, nullptr, &len);
523        buf.resize(len);
524        return len > 0 && GetLogicalProcessorInformationEx(rel, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len);
525    };
526    std::vector<uint8_t> nb, cb;
527    if (!query(RelationNumaNode, nb) || !query(RelationProcessorCore, cb)) return nodes;
528    std::vector<KAFFINITY> masks;
529    for (size_t o = 0; o < nb.size();) {
530        auto* e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) (nb.data() + o);
531        if (e->NumaNode.GroupMask.Group == 0) masks.push_back(e->NumaNode.GroupMask.Mask);
532        o += e->Size;
533    }
534    nodes.resize(masks.size());
535    for (size_t o = 0; o < cb.size();) {
536        auto* e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) (cb.data() + o);
537        if (e->Processor.GroupCount > 0 && e->Processor.GroupMask[0].Group == 0) {
538            const KAFFINITY m = e->Processor.GroupMask[0].Mask;
539            int first = -1;
540            for (int b = 0; b < 64; ++b)
541                if ((m >> b) & 1) {
542                    first = b;
543                    break;
544                }
545            for (size_t n = 0; n < masks.size() && first >= 0; ++n)
546                if ((masks[n] >> first) & 1) {
547                    nodes[n].push_back(first);
548                    if (smt)
549                        for (int b = first + 1; b < 64; ++b)
550                            if ((m >> b) & 1) nodes[n].push_back(b);
551                }
552        }
553        o += e->Size;
554    }
555    nodes.erase(std::remove_if(nodes.begin(), nodes.end(), [](const std::vector<int>& v) { return v.empty(); }),
556                nodes.end());
557    for (auto& v : nodes) std::sort(v.begin(), v.end());
558    return nodes;
559}
560/// The RAM this process can still get (~0: not known).
561inline uint64_t ram_avail() {
562    MEMORYSTATUSEX s{};
563    s.dwLength = sizeof(s);
564    return GlobalMemoryStatusEx(&s) ? (uint64_t) s.ullAvailPhys : ~uint64_t{0};
565}
566#endif
567
568/// Windows' commit (RAM + page file, what every private allocation is charged to - on an integrated GPU the GPU's
569/// own allocations too): the limit, what this process can still commit, the RAM; all ~0 where there is no such limit
570/// (Linux overcommits; its RAM is ram_avail's business).
571struct Commit {
572    uint64_t limit = ~uint64_t{0}, avail = ~uint64_t{0}, ram = ~uint64_t{0};
573};
574inline Commit commit() {
575    Commit c;
576#if defined(_WIN32)
577    MEMORYSTATUSEX s{};
578    s.dwLength = sizeof(s);
579    if (GlobalMemoryStatusEx(&s)) {
580        c.limit = (uint64_t) s.ullTotalPageFile;
581        c.avail = (uint64_t) s.ullAvailPageFile;
582        c.ram = (uint64_t) s.ullTotalPhys;
583    }
584#endif
585    return c;
586}
587
588}  // namespace strata::ds4::os