okami.mom/strata

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

Niko1221Merge f-144-ruben (RubenTorney's #1904 --adapt-async in the arena and #1905 pin by need, as opt-ins) into f-144-relc7cbf787a

main
10.3 KiB260 linesraw
1// src/platform/memory.cpp - see include/strata/platform/memory.hpp.
2#include "strata/platform/memory.hpp"
3
4#if defined(_WIN32)
5#define WIN32_LEAN_AND_MEAN
6#define NOMINMAX
7#include <windows.h>
8#include <dxgi1_4.h>
9#include <cstring>
10#else
11#include <algorithm>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <fcntl.h>
16#include <sys/mman.h>
17#include <unistd.h>
18#endif
19
20namespace strata::platform {
21
22#if defined(_WIN32)
23LockResult lock_resident(void* p, uint64_t bytes) {
24    LockResult r;
25    if (p == nullptr || bytes == 0) { r.note = "nothing to lock"; return r; }
26    HANDLE self = GetCurrentProcess();
27    SIZE_T min_ws = 0, max_ws = 0;
28    DWORD flags = 0;
29    if (!GetProcessWorkingSetSizeEx(self, &min_ws, &max_ws, &flags)) {
30        r.note = "GetProcessWorkingSetSizeEx failed (error " + std::to_string(GetLastError()) + ")";
31        return r;
32    }
33    // Locked pages count against the minimum working set, so it must grow by the region plus headroom for the
34    // rest of the process. Soft limits: the maximum is not enforced, only the minimum is raised.
35    const SIZE_T margin = (SIZE_T) 512 << 20;
36    const SIZE_T new_min = min_ws + (SIZE_T) bytes + margin;
37    const SIZE_T new_max = max_ws > new_min + margin ? max_ws : new_min + margin;
38    if (!SetProcessWorkingSetSizeEx(self, new_min, new_max,
39                                    QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE)) {
40        r.note = "SetProcessWorkingSetSizeEx(" + std::to_string((unsigned long long) (new_min >> 20)) +
41                 " MiB) failed (error " + std::to_string(GetLastError()) + ")";
42        return r;
43    }
44    const uint64_t chunk = 1ull << 30;
45    uint8_t* base = (uint8_t*) p;
46    for (uint64_t off = 0; off < bytes; off += chunk) {
47        const uint64_t n = bytes - off < chunk ? bytes - off : chunk;
48        if (!VirtualLock(base + off, (SIZE_T) n)) {
49            r.note = "VirtualLock stopped at " + std::to_string((unsigned long long) (off >> 20)) + " of " +
50                     std::to_string((unsigned long long) (bytes >> 20)) + " MiB (error " +
51                     std::to_string(GetLastError()) + ")";
52            r.ok = off > 0;
53            return r;
54        }
55        r.locked_bytes = off + n;
56    }
57    r.ok = true;
58    r.note = "locked " + std::to_string((unsigned long long) (bytes >> 20)) + " MiB via working-set minimum + VirtualLock";
59    return r;
60}
61
62LockResult lock_resident_ranges(const std::vector<std::pair<void*, uint64_t>>& regions) {
63    LockResult r;
64    uint64_t total = 0;
65    for (const auto& g : regions) total += g.second;
66    if (total == 0) { r.note = "nothing to lock"; return r; }
67    HANDLE self = GetCurrentProcess();
68    SIZE_T min_ws = 0, max_ws = 0;
69    DWORD flags = 0;
70    if (!GetProcessWorkingSetSizeEx(self, &min_ws, &max_ws, &flags)) {
71        r.note = "GetProcessWorkingSetSizeEx failed (error " + std::to_string(GetLastError()) + ")";
72        return r;
73    }
74    // same growth as lock_resident, but for the sum of the regions and with ONE margin
75    const SIZE_T margin = (SIZE_T) 512 << 20;
76    const SIZE_T new_min = min_ws + (SIZE_T) total + margin;
77    const SIZE_T new_max = max_ws > new_min + margin ? max_ws : new_min + margin;
78    if (!SetProcessWorkingSetSizeEx(self, new_min, new_max,
79                                    QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE)) {
80        r.note = "SetProcessWorkingSetSizeEx(" + std::to_string((unsigned long long) (new_min >> 20)) +
81                 " MiB) failed (error " + std::to_string(GetLastError()) + ")";
82        return r;
83    }
84    const uint64_t chunk = 1ull << 30;
85    for (const auto& g : regions) {
86        uint8_t* base = (uint8_t*) g.first;
87        for (uint64_t off = 0; off < g.second; off += chunk) {
88            const uint64_t n = g.second - off < chunk ? g.second - off : chunk;
89            if (!VirtualLock(base + off, (SIZE_T) n)) {
90                r.note = "VirtualLock stopped after " + std::to_string((unsigned long long) (r.locked_bytes >> 20)) +
91                         " of " + std::to_string((unsigned long long) (total >> 20)) + " MiB (error " +
92                         std::to_string(GetLastError()) + ")";
93                r.ok = r.locked_bytes > 0;
94                return r;
95            }
96            r.locked_bytes += n;
97        }
98    }
99    r.ok = true;
100    r.note = "locked " + std::to_string((unsigned long long) (total >> 20)) + " MiB in " +
101             std::to_string(regions.size()) + " regions via working-set minimum + VirtualLock";
102    return r;
103}
104
105void unlock_resident(void* p, uint64_t bytes) {
106    if (p == nullptr || bytes == 0) return;
107    const uint64_t chunk = 1ull << 30;
108    for (uint64_t off = 0; off < bytes; off += chunk)
109        VirtualUnlock((uint8_t*) p + off, (SIZE_T) (bytes - off < chunk ? bytes - off : chunk));
110}
111
112bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usage, std::string& why) {
113    budget = usage = 0;
114    // dxgi.dll is loaded when asked, not linked: a start that never needs this keeps the imports it had
115    HMODULE dxgi = LoadLibraryA("dxgi.dll");
116    if (dxgi == nullptr) { why = "dxgi.dll not found"; return false; }
117    using CreateFactory = HRESULT(WINAPI*)(REFIID, void**);
118    const auto create = (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1");
119    IDXGIFactory1* factory = nullptr;
120    if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory1), (void**) &factory)) || factory == nullptr) {
121        why = "CreateDXGIFactory1 failed";
122        FreeLibrary(dxgi);
123        return false;
124    }
125    bool ok = false;
126    why = "no DXGI adapter has the CUDA device's LUID";
127    for (UINT i = 0; !ok; ++i) {
128        IDXGIAdapter1* a = nullptr;
129        if (factory->EnumAdapters1(i, &a) == DXGI_ERROR_NOT_FOUND || a == nullptr) break;
130        DXGI_ADAPTER_DESC1 d{};
131        if (SUCCEEDED(a->GetDesc1(&d)) && std::memcmp(&d.AdapterLuid, luid, sizeof d.AdapterLuid) == 0) {
132            IDXGIAdapter3* a3 = nullptr;
133            DXGI_QUERY_VIDEO_MEMORY_INFO info{};
134            if (SUCCEEDED(a->QueryInterface(__uuidof(IDXGIAdapter3), (void**) &a3)) && a3 != nullptr &&
135                SUCCEEDED(a3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &info))) {
136                budget = info.Budget;
137                usage = info.CurrentUsage;
138                ok = budget > 0;
139                why = ok ? "" : "the adapter reports no shared-memory budget";
140            } else {
141                why = "QueryVideoMemoryInfo failed";
142            }
143            if (a3 != nullptr) a3->Release();
144            a->Release();
145            break;
146        }
147        a->Release();
148    }
149    factory->Release();
150    FreeLibrary(dxgi);
151    return ok;
152}
153
154uint64_t total_physical_memory() {
155    MEMORYSTATUSEX ms{};
156    ms.dwLength = sizeof ms;
157    return GlobalMemoryStatusEx(&ms) ? (uint64_t) ms.ullTotalPhys : 0;
158}
159
160bool read_ahead_enabled() { return false; }
161void advise_willneed(const void*, uint64_t) {}
162void advise_willneed(int, uint64_t, uint64_t) {}
163#else
164LockResult lock_resident(void* p, uint64_t bytes) {
165    LockResult r;
166    if (p == nullptr || bytes == 0) { r.note = "nothing to lock"; return r; }
167    if (mlock(p, bytes) != 0) { r.note = "mlock failed (raise ulimit -l)"; return r; }
168    r.ok = true;
169    r.locked_bytes = bytes;
170    r.note = "mlock";
171    return r;
172}
173
174LockResult lock_resident_ranges(const std::vector<std::pair<void*, uint64_t>>& regions) {
175    LockResult r;
176    for (const auto& g : regions) {
177        if (g.first == nullptr || g.second == 0) continue;
178        if (mlock(g.first, g.second) != 0) { r.note = "mlock failed (raise ulimit -l)"; r.ok = r.locked_bytes > 0; return r; }
179        r.locked_bytes += g.second;
180    }
181    r.ok = r.locked_bytes > 0;
182    r.note = r.ok ? "mlock of " + std::to_string(regions.size()) + " regions" : "nothing to lock";
183    return r;
184}
185
186void unlock_resident(void* p, uint64_t bytes) {
187    if (p != nullptr && bytes != 0) munlock(p, bytes);
188}
189
190bool gpu_shared_memory_budget(const void*, uint64_t& budget, uint64_t& usage, std::string& why) {
191    budget = usage = 0;
192    why = "DXGI is Windows-only";
193    return false;
194}
195
196uint64_t total_physical_memory() {
197    const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE);
198    return pages > 0 && page > 0 ? (uint64_t) pages * (uint64_t) page : 0;
199}
200
201namespace {
202constexpr uint64_t kAdviseStep = 128ull << 10;
203}
204
205bool read_ahead_enabled() {
206    static const bool on = [] {
207        const char* v = std::getenv("STRATA_READ_AHEAD");
208        return v == nullptr || std::atoi(v) != 0;
209    }();
210    return on;
211}
212
213void advise_willneed(const void* p, uint64_t bytes) {
214    if (p == nullptr || bytes == 0 || !read_ahead_enabled()) return;
215    const long ps = sysconf(_SC_PAGE_SIZE);
216    const uintptr_t pg = ps > 0 ? (uintptr_t) ps : 4096, end = (uintptr_t) p + bytes;
217    for (uintptr_t a = (uintptr_t) p & ~(pg - 1); a < end; a += kAdviseStep)
218        (void) madvise((void*) a, (size_t) std::min<uintptr_t>(kAdviseStep, end - a), MADV_WILLNEED);
219}
220
221void advise_willneed(int fd, uint64_t offset, uint64_t bytes) {
222    if (fd < 0 || !read_ahead_enabled()) return;
223    for (uint64_t at = 0; at < bytes; at += kAdviseStep)
224#if defined(__APPLE__)   // macOS: F_RDADVISE is the read-ahead hint
225    {
226        radvisory ra{(off_t) (offset + at), (int) std::min(kAdviseStep, bytes - at)};
227        (void) fcntl(fd, F_RDADVISE, &ra);
228    }
229#else
230        (void) posix_fadvise(fd, (off_t) (offset + at), (off_t) std::min(kAdviseStep, bytes - at), POSIX_FADV_WILLNEED);
231#endif
232}
233#endif
234
235ProcIo proc_io_sample() {
236    ProcIo r;
237#if defined(__linux__)
238    if (std::FILE* f = std::fopen("/proc/self/io", "r")) {
239        char key[64];
240        unsigned long long v;
241        while (std::fscanf(f, "%63[^:]: %llu\n", key, &v) == 2)
242            if (std::strcmp(key, "read_bytes") == 0) { r.read_bytes = v; r.valid = true; }
243        std::fclose(f);
244    }
245    if (std::FILE* f = std::fopen("/proc/self/stat", "r")) {
246        char buf[1024];
247        const size_t n = std::fread(buf, 1, sizeof buf - 1, f);
248        buf[n] = 0;
249        std::fclose(f);
250        if (const char* p = std::strrchr(buf, ')')) {   // fields after the command: state ppid ... minflt cminflt majflt
251            unsigned long long minflt = 0, cminflt = 0, majflt = 0;
252            if (std::sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %llu %llu %llu", &minflt, &cminflt, &majflt) == 3)
253                r.major_faults = majflt;
254        }
255    }
256#endif
257    return r;
258}
259
260}  // namespace strata::platform