okami.mom/strata

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

Niko1221Merge f-gfx11-reset 5450e4344: the unregistered expert arena only on the Radeon 780M classe1a17f116

main
69.8 KiB1387 linesraw
1// src/core/pinned.cu - P2.S1: the pinned host arena and the parallel expert load.
2#include "strata/core/pinned.hpp"
3#include "strata/platform/memory.hpp"
4#include "strata/core/pin_budget.hpp"
5#include "strata/core/arch_defaults.hpp"   // arena_skip_thp_request
6#include "strata/core/page_cache_drop.hpp"   // drop_range (the drop behind the arena read, Linux)
7#if defined(STRATA_USE_HIP) && defined(__linux__)   // kfd_quiet NOREG scope: Linux HIP only, every other build keeps its old text
8#include "strata/core/kfd_quiet.hpp"   // NOREG: the arena's mode and its lock (the Radeon 780M class, Linux HIP)
9#endif
10#include <cstddef>
11
12#include <cuda_runtime.h>
13
14#include <atomic>
15#include <climits>
16#include <cerrno>
17#include <cstdlib>
18#include <cstdio>
19#include <cstring>
20#include <algorithm>
21#include <fstream>
22#include <iterator>
23#include <map>
24#include <mutex>
25#include <thread>
26
27// Loader fix: `fseek`/`ftell` are 32-bit on Windows by default (and the pack is 42.9 GB), and the 64-bit
28// spelling is not the same on the two platforms the engine builds for.
29#ifdef _WIN32
30#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
31#else
32#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
33#endif
34
35#ifdef _WIN32
36#include <windows.h>
37#else
38#include <fcntl.h>
39#include <sys/mman.h>
40#include <sys/stat.h>
41#ifdef __linux__
42#include <sys/vfs.h>
43#endif
44#include <unistd.h>
45#include <linux/mman.h>
46#ifndef MAP_HUGE_2MB
47#define MAP_HUGE_2MB (21 << 26)
48#endif
49#endif
50
51namespace strata::core {
52
53namespace {
54
55constexpr uint64_t kSharedArenaHeaderBytes = 4096;
56constexpr char kSharedArenaMagic[16] = "STRATA-ARENA-V1";
57
58struct SharedArenaHeader {
59    char magic[16];
60    uint32_t version;
61    uint32_t header_bytes;
62    uint64_t arena_bytes;
63    uint64_t pack_hash;
64    uint64_t reserved[4];
65};
66static_assert(sizeof(SharedArenaHeader) <= kSharedArenaHeaderBytes);
67
68#ifdef _WIN32
69// Shared-section views: MapViewOfFile address -> the section handle, so release() unmaps and closes instead of VirtualFree.
70std::mutex g_views_mu;
71std::map<void*, HANDLE> g_views;
72#endif
73
74#ifndef _WIN32
75// MemAvailable and, in a cgroup v2 group with a limit, the room left under it; ~0 when neither can be read
76uint64_t free_ram_room() {
77    uint64_t room = ~uint64_t{0};
78    if (std::FILE* f = std::fopen("/proc/meminfo", "r")) {
79        char line[256];
80        while (std::fgets(line, sizeof line, f) != nullptr) {
81            unsigned long long kb = 0;
82            if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { room = (uint64_t) kb * 1024u; break; }
83        }
84        std::fclose(f);
85    }
86    std::string cg;
87    if (std::FILE* f = std::fopen("/proc/self/cgroup", "r")) {
88        char line[512];
89        while (std::fgets(line, sizeof line, f) != nullptr)
90            if (std::strncmp(line, "0::", 3) == 0) { cg = line + 3; break; }
91        std::fclose(f);
92    }
93    while (!cg.empty() && (cg.back() == '\n' || cg.back() == '\r')) cg.pop_back();
94    if (!cg.empty()) {
95        unsigned long long lim = 0, cur = 0;
96        bool have_lim = false;
97        if (std::FILE* f = std::fopen(("/sys/fs/cgroup" + cg + "/memory.max").c_str(), "r")) {
98            have_lim = std::fscanf(f, "%llu", &lim) == 1;   // ("max" does not parse: no limit)
99            std::fclose(f);
100        }
101        if (have_lim) {
102            if (std::FILE* f = std::fopen(("/sys/fs/cgroup" + cg + "/memory.current").c_str(), "r")) {
103                if (std::fscanf(f, "%llu", &cur) != 1) cur = 0;
104                std::fclose(f);
105            }
106            room = std::min<uint64_t>(room, lim > cur ? (uint64_t) (lim - cur) : 0);
107        }
108    }
109    return room;
110}
111#endif
112
113#ifndef _WIN32
114// bytes in free blocks of 2 MiB or more (/proc/buddyinfo, order >= 9): what MADV_HUGEPAGE can get without compaction
115uint64_t free_huge_bytes() {
116    uint64_t total = 0;
117    if (std::FILE* f = std::fopen("/proc/buddyinfo", "r")) {
118        char line[512];
119        while (std::fgets(line, sizeof line, f) != nullptr) {
120            const char* z = std::strstr(line, "zone");
121            if (z == nullptr) continue;
122            const char* q = z + 4;
123            while (*q == ' ') ++q;
124            while (*q != '\0' && *q != ' ') ++q;   // the zone's name
125            unsigned long long c[11] = {0};
126            int n = 0;
127            for (; n < 11; ++n) {
128                char* e = nullptr;
129                const unsigned long long v = std::strtoull(q, &e, 10);
130                if (e == q) break;
131                c[n] = v;
132                q = e;
133            }
134            for (int o = 9; o < n; ++o) total += c[o] * (4096ull << o);
135        }
136        std::fclose(f);
137    }
138    return total;
139}
140#endif
141
142// A 2 MB-aligned reservation.  Large pages first, then the largest alignment the OS will give us for free.
143// A non-empty shared_file instead maps one file whose first 4 KiB identify the pack and whose remaining bytes
144// are the resident arena.  This shared-file layout is intended for tmpfs (/dev/shm); hugetlbfs would need
145// hugepage-aligned file size and arena offset rather than the 4 KiB header layout used here.
146void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::string& shared_file,
147              uint64_t shared_pack_hash, void*& mapping_base, uint64_t& mapping_bytes) {
148    mapping_base = nullptr;
149    mapping_bytes = 0;
150
151#ifdef _WIN32
152    if (!shared_file.empty()) {
153        // The shared arena on Windows is a named, pagefile-backed section (CreateFileMappingW) that every engine of the
154        // replicas opens by name: "win:Local\\strata-replicas-<server pid>" (a name without the prefix is used as it is).
155        // The first engine creates it at the full size, the others open it; it lives while any process holds a handle or
156        // a view, so a replica that restarts joins the same pages.  The first 4 KiB are the same header as on Linux (the
157        // pack hash, the size, the load state word); a new section is all zeros, so "no magic" means "nobody has been
158        // here" - two engines that both find it empty write the same header.
159        if (shared_pack_hash == 0) {
160            note = "shared arena requires a nonzero pack hash";
161            return nullptr;
162        }
163        if (bytes > UINT64_MAX - kSharedArenaHeaderBytes) {
164            note = "shared arena size overflows its header";
165            return nullptr;
166        }
167        const uint64_t file_bytes = bytes + kSharedArenaHeaderBytes;
168        std::string nm = shared_file.rfind("win:", 0) == 0 ? shared_file.substr(4) : shared_file;
169        std::wstring wname(nm.begin(), nm.end());
170        // the section is committed memory (RAM plus pagefile) from the moment it exists: say so before taking it
171        MEMORYSTATUSEX ms{};
172        ms.dwLength = sizeof ms;
173        if (GlobalMemoryStatusEx(&ms) && file_bytes + (2ull << 30) > ms.ullAvailPageFile) {
174            HANDLE probe = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, wname.c_str());   // (already there: nothing new is committed)
175            if (probe == nullptr) {
176                note = "not enough free memory (RAM + pagefile) for the shared arena " + nm + ": it needs " +
177                       std::to_string((unsigned long long) (file_bytes >> 20)) + " MiB and " +
178                       std::to_string((unsigned long long) (ms.ullAvailPageFile >> 20)) + " MiB are available (2 GiB are kept back)";
179                return nullptr;
180            }
181            CloseHandle(probe);
182        }
183        HANDLE h = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, (DWORD) (file_bytes >> 32),
184                                      (DWORD) (file_bytes & 0xffffffffu), wname.c_str());
185        if (h == nullptr) {
186            note = "cannot create shared arena section " + nm + ": Windows error " + std::to_string((unsigned long long) GetLastError());
187            return nullptr;
188        }
189        void* view = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 0);   // (0: the whole section, as big as it was created)
190        if (view == nullptr) {
191            const DWORD e = GetLastError();
192            CloseHandle(h);
193            note = "cannot map shared arena section " + nm + ": Windows error " + std::to_string((unsigned long long) e);
194            return nullptr;
195        }
196        MEMORY_BASIC_INFORMATION mbi{};
197        if (VirtualQuery(view, &mbi, sizeof mbi) == 0 || (uint64_t) mbi.RegionSize < file_bytes) {
198            UnmapViewOfFile(view);
199            CloseHandle(h);
200            note = "shared arena section " + nm + " is smaller than the " + std::to_string((unsigned long long) file_bytes) +
201                   " B this engine needs (including its header)";
202            return nullptr;
203        }
204        auto* hdr = static_cast<SharedArenaHeader*>(view);
205        bool empty = true;
206        for (char c : hdr->magic) empty = empty && c == 0;
207        if (empty) {
208            SharedArenaHeader fresh{};
209            std::memcpy(fresh.magic, kSharedArenaMagic, sizeof fresh.magic);
210            fresh.version = 1;
211            fresh.header_bytes = (uint32_t) kSharedArenaHeaderBytes;
212            fresh.arena_bytes = bytes;
213            fresh.pack_hash = shared_pack_hash;
214            // fields after the magic first, the magic last: an engine that sees the magic sees a complete header (the
215            // state word, reserved[0], stays zero)
216            std::memcpy(reinterpret_cast<char*>(hdr) + sizeof fresh.magic, reinterpret_cast<char*>(&fresh) + sizeof fresh.magic,
217                        sizeof fresh - sizeof fresh.magic);
218            MemoryBarrier();
219            std::memcpy(hdr->magic, fresh.magic, sizeof fresh.magic);
220        } else {
221            // (an engine that arrives in the instant between another one's header fields and its magic never sees a
222            // half header: the magic is written last)
223            if (std::memcmp(hdr->magic, kSharedArenaMagic, sizeof hdr->magic) != 0 || hdr->version != 1 ||
224                hdr->header_bytes != kSharedArenaHeaderBytes || hdr->arena_bytes != bytes) {
225                UnmapViewOfFile(view);
226                CloseHandle(h);
227                note = "shared arena section " + nm + " has an incompatible or missing header";
228                return nullptr;
229            }
230            if (hdr->pack_hash != shared_pack_hash) {
231                char b[256];
232                std::snprintf(b, sizeof b, "shared arena %s was written for pack hash %016llx, expected %016llx", nm.c_str(),
233                              (unsigned long long) hdr->pack_hash, (unsigned long long) shared_pack_hash);
234                UnmapViewOfFile(view);
235                CloseHandle(h);
236                note = b;
237                return nullptr;
238            }
239        }
240        {
241            std::lock_guard<std::mutex> lk(g_views_mu);
242            g_views[view] = h;
243        }
244        mapping_base = view;
245        mapping_bytes = file_bytes;
246        got = PageBacking::NormalPages;
247        note = "shared section " + nm + " (pack hash checked)";
248        return static_cast<uint8_t*>(view) + kSharedArenaHeaderBytes;
249    }
250    // MEM_LARGE_PAGES needs SeLockMemoryPrivilege.  Having it assigned to the account is not enough: the
251    // PROCESS must enable it in its own token (AdjustTokenPrivileges) before VirtualAlloc, or the call fails.
252    // An account without the assignment, or a failure to enable, leaves the process as it was: VirtualAlloc
253    // then refuses and the 4 KB fallback below runs - that is the EXPECTED outcome on a desktop.
254    {
255        HANDLE tok = nullptr;
256        if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tok)) {
257            TOKEN_PRIVILEGES tp{};
258            tp.PrivilegeCount = 1;
259            if (LookupPrivilegeValueW(nullptr, L"SeLockMemoryPrivilege", &tp.Privileges[0].Luid)) {
260                tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
261                if (!AdjustTokenPrivileges(tok, FALSE, &tp, 0, nullptr, nullptr) && GetLastError() != ERROR_NOT_ALL_ASSIGNED)
262                    (void) 0;   // nothing actionable: the large-page attempt below reports the outcome
263            }
264            CloseHandle(tok);
265        }
266    }
267    // MEM_LARGE_PAGES needs SeLockMemoryPrivilege; a normal account does not have it and VirtualAlloc then
268    // fails with ERROR_PRIVILEGE_NOT_HELD.  That is the EXPECTED outcome on a desktop, not an error.
269    SIZE_T large = GetLargePageMinimum();
270    // A/B switch: STRATA_NO_LARGEPAGES=1 skips the large-page attempt, same run, same boot.
271    if (large > 0 && std::getenv("STRATA_NO_LARGEPAGES") == nullptr) {
272        // MEM_LARGE_PAGES requires the allocation size to be an exact multiple of the large page size -
273        // anything else is ERROR_INVALID_PARAMETER (87), which reads like a privilege problem but is not.
274        // Round up: the slack is under 2 MB and the tail stays unused.
275        const SIZE_T lbytes = (SIZE_T) (((SIZE_T) bytes + large - 1) / large * large);
276        void* p = VirtualAlloc(nullptr, lbytes, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
277                               PAGE_READWRITE);
278        if (p) {
279            got = PageBacking::LargePages;
280            note = "large pages (" + std::to_string((unsigned long long) large) + " B)";
281            return p;
282        }
283        // 1450 (ERROR_NO_SYSTEM_RESOURCES) is the large-page pool saying no, 87 is a size that is not a
284        // multiple of the minimum, 1314 is the privilege: without the byte count the three read as one bug.
285        note = "large pages refused for " + std::to_string((unsigned long long) lbytes) + " B (GetLargePageMinimum=" +
286               std::to_string((unsigned long long) large) + ", VirtualAlloc error " +
287               std::to_string((unsigned long long) GetLastError()) + "); using 4 KB pages";
288    } else if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) {
289        note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages";
290    } else {
291        note = "this system has no large-page minimum; using 4 KB pages";
292    }
293    void* p = VirtualAlloc(nullptr, (SIZE_T) bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
294    got = PageBacking::NormalPages;
295    return p;
296#else
297    if (!shared_file.empty()) {
298        if (shared_pack_hash == 0) {
299            note = "shared arena requires a nonzero pack hash";
300            return nullptr;
301        }
302        if (bytes > UINT64_MAX - kSharedArenaHeaderBytes) {
303            note = "shared arena size overflows its header";
304            return nullptr;
305        }
306        const uint64_t file_bytes = kSharedArenaHeaderBytes + bytes;
307        const int fd = open(shared_file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
308        if (fd < 0) {
309            note = "cannot open shared arena " + shared_file + ": " + std::strerror(errno);
310            return nullptr;
311        }
312        struct stat st{};
313        if (fstat(fd, &st) != 0) {
314            const int e = errno;
315            close(fd);
316            note = "cannot stat shared arena " + shared_file + ": " + std::strerror(e);
317            return nullptr;
318        }
319
320        const bool fresh = st.st_size == 0;
321        if (fresh) {
322            if (ftruncate(fd, (off_t) file_bytes) != 0) {
323                const int e = errno;
324                close(fd);
325                note = "cannot size shared arena " + shared_file + ": " + std::strerror(e);
326                return nullptr;
327            }
328            SharedArenaHeader hdr{};
329            std::memcpy(hdr.magic, kSharedArenaMagic, sizeof hdr.magic);
330            hdr.version = 1;
331            hdr.header_bytes = (uint32_t) kSharedArenaHeaderBytes;
332            hdr.arena_bytes = bytes;
333            hdr.pack_hash = shared_pack_hash;
334            const ssize_t written = pwrite(fd, &hdr, sizeof hdr, 0);
335            if (written != (ssize_t) sizeof hdr) {
336                const int e = errno;
337                close(fd);
338                note = "cannot write shared arena header " + shared_file + ": " +
339                       (written < 0 ? std::string(std::strerror(e)) : std::string("short write"));
340                return nullptr;
341            }
342        } else {
343            if (st.st_size < 0 || (uint64_t) st.st_size != file_bytes) {
344                close(fd);
345                note = "shared arena " + shared_file + " is " +
346                       std::to_string((unsigned long long) st.st_size) + " B, expected " +
347                       std::to_string((unsigned long long) file_bytes) + " B including its header";
348                return nullptr;
349            }
350            SharedArenaHeader hdr{};
351            ssize_t got_header = pread(fd, &hdr, sizeof hdr, 0);
352            // the creator sizes the file first and writes the header right after: an engine that starts in that gap waits
353            // for it (up to 10 s) instead of calling the file broken
354            for (int w = 0; w < 100 && got_header == (ssize_t) sizeof hdr &&
355                                std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 &&
356                                hdr.magic[0] == 0 && hdr.magic[1] == 0; ++w) {
357                usleep(100 * 1000);
358                got_header = pread(fd, &hdr, sizeof hdr, 0);
359            }
360            if (got_header == (ssize_t) sizeof hdr && std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 &&
361                hdr.magic[0] == 0 && hdr.magic[1] == 0) {
362                // still no header after 10 s: the engine that sized the file died before writing it.  Every engine
363                // fills the arena itself, so nothing in the file is worth keeping: write the header as the creator would
364                std::memset(&hdr, 0, sizeof hdr);
365                std::memcpy(hdr.magic, kSharedArenaMagic, sizeof hdr.magic);
366                hdr.version = 1;
367                hdr.header_bytes = (uint32_t) kSharedArenaHeaderBytes;
368                hdr.arena_bytes = bytes;
369                hdr.pack_hash = shared_pack_hash;
370                got_header = pwrite(fd, &hdr, sizeof hdr, 0);
371            }
372            if (got_header != (ssize_t) sizeof hdr ||
373                std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 ||
374                hdr.version != 1 || hdr.header_bytes != kSharedArenaHeaderBytes || hdr.arena_bytes != bytes) {
375                close(fd);
376                note = "shared arena " + shared_file + " has an incompatible or missing header";
377                return nullptr;
378            }
379            if (hdr.pack_hash != shared_pack_hash) {
380                close(fd);
381                char b[256];
382                std::snprintf(b, sizeof b,
383                              "shared arena %s was written for pack hash %016llx, expected %016llx",
384                              shared_file.c_str(), (unsigned long long) hdr.pack_hash,
385                              (unsigned long long) shared_pack_hash);
386                note = b;
387                return nullptr;
388            }
389        }
390
391        // tmpfs: take the pages now (ftruncate only sets the length).  With /dev/shm too small the load would die with a bus
392        // error part-way; here a full tmpfs is a plain error at start, for every engine that maps the file (pages already
393        // taken cost nothing), and the server then starts its replicas with private copies.  A file on a disk stays sparse.
394#ifdef __linux__
395        {
396            struct statfs sf{};
397            if (fstatfs(fd, &sf) == 0 && (unsigned long) sf.f_type == 0x01021994ul) {
398                // a memfd (or any tmpfs file not capped by a mount size) would take the RAM and then the OOM killer: check the
399                // free RAM and the cgroup's room for the pages that are not there yet before taking them
400                struct stat st2{};
401                const uint64_t have = fstat(fd, &st2) == 0 ? (uint64_t) st2.st_blocks * 512u : 0;
402                const uint64_t need = file_bytes > have ? file_bytes - have : 0;
403                if (need > 0) {
404                    const uint64_t room = free_ram_room();
405                    if (room != ~uint64_t{0} && need + (2ull << 30) > room) {
406                        close(fd);
407                        note = "not enough free RAM for the shared arena " + shared_file + ": it needs " +
408                               std::to_string((unsigned long long) (need >> 20)) + " MiB more and " +
409                               std::to_string((unsigned long long) (room >> 20)) + " MiB are free (2 GiB are kept back)";
410                        return nullptr;
411                    }
412                }
413                const int fe = posix_fallocate(fd, 0, (off_t) file_bytes);
414                if (fe != 0 && fe != EOPNOTSUPP && fe != EINVAL) {
415                    close(fd);
416                    note = "not enough room for the shared arena " + shared_file + " (" +
417                           std::to_string((unsigned long long) (file_bytes >> 20)) + " MiB): " + std::strerror(fe);
418                    return nullptr;
419                }
420            }
421        }
422#endif
423        void* map = mmap(nullptr, (size_t) file_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
424        const int e = errno;
425        close(fd);
426        if (map == MAP_FAILED) {
427            note = "cannot map shared arena " + shared_file + ": " + std::strerror(e);
428            return nullptr;
429        }
430        mapping_base = map;
431        mapping_bytes = file_bytes;
432        got = PageBacking::NormalPages;
433        note = "MAP_SHARED file " + shared_file + " (pack hash checked)";
434        return (uint8_t*) map + kSharedArenaHeaderBytes;
435    }
436
437    // STRATA_NO_LARGEPAGES=1 is the same-run A/B switch the Windows branch documents; honor it
438    // here too, so the large-page path can be compared without changing the pool or rebooting.
439    if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) {
440        note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages";
441    } else {
442        void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE,
443                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0);
444        if (p != MAP_FAILED) {
445            got = PageBacking::LargePages;
446            note = "hugetlb 2 MB pages";
447            return p;
448        }
449        // MAP_HUGETLB is all-or-nothing: a pool smaller than the mapping fails exactly like an absent
450        // one, and the old message guessed "no hugetlb pool configured" either way. Name the shortfall:
451        // how many 2 MiB pages the mapping needs against what vm.nr_hugepages actually holds.
452        const unsigned long long need = ((unsigned long long) bytes + (1ull << 21) - 1) / (1ull << 21);
453        unsigned long long pool = 0;
454        bool have_pool = false;
455        if (std::FILE* f = std::fopen("/proc/sys/vm/nr_hugepages", "r")) {
456            have_pool = std::fscanf(f, "%llu", &pool) == 1;
457            std::fclose(f);
458        }
459        note = "MAP_HUGETLB unavailable (needed " + std::to_string(need) + " 2 MiB pages, vm.nr_hugepages=" +
460               (have_pool ? std::to_string(pool) : std::string("?")) + "); using 4 KB pages";
461    }
462    // No hugetlb mapping: a 2 MiB-aligned anonymous mapping with MADV_HUGEPAGE, so transparent huge pages back
463    // it where THP is "madvise" (the common distro default). The CPU expert pool streams whole experts out of
464    // this arena; with 4 KB pages every 3 MB expert costs ~750 TLB misses.
465    constexpr uint64_t kAlign = 2ull << 20;
466    const uint64_t padded = bytes + kAlign;
467    void* raw = mmap(nullptr, padded, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
468    got = PageBacking::NormalPages;
469    if (raw == MAP_FAILED) return nullptr;
470    const uintptr_t start = (uintptr_t) raw;
471    const uintptr_t aligned = (start + kAlign - 1) & ~(uintptr_t) (kAlign - 1);
472    if (aligned > start) munmap(raw, aligned - start);
473    const uintptr_t end = aligned + bytes, raw_end = start + padded;
474    if (raw_end > end) munmap((void*) end, raw_end - end);
475    void* p = (void*) aligned;
476    // #771: with THP "always" the kernel already backs this mapping with huge pages where it can; the extra
477    // MADV_HUGEPAGE only adds direct reclaim and compaction on every fault (defrag=madvise), which on a fragmented
478    // machine stretched a 25 s start to 432 s.  So it is not asked for there.  STRATA_NO_ARENA_THP=1 skips it
479    // anywhere (the request alone; STRATA_NO_LARGEPAGES also skips the hugetlb try).
480    std::string thp_mode;
481    if (std::FILE* f = std::fopen("/sys/kernel/mm/transparent_hugepage/enabled", "r")) {
482        char line[128] = {0};
483        if (std::fgets(line, sizeof line, f) != nullptr) {
484            const char* open = std::strchr(line, '[');
485            const char* close = open ? std::strchr(open, ']') : nullptr;
486            if (open && close) thp_mode.assign(open + 1, close);
487        }
488        std::fclose(f);
489    }
490    // STRATA_NO_ARENA_THP unset = the engine decides: an integrated gfx11 GPU under Linux asks for none (arena_no_thp_flag, set
491    // from the device before the arena is made; a huge-page move inside the registered arena resets that GPU in a prompt), every other
492    // device as before.  =0 asks for them there too (the user's choice; #2126's free-block check below still applies); any other value
493    // skips the request on any device (as before).
494    const char* no_thp = std::getenv("STRATA_NO_ARENA_THP");
495    const bool user_no_thp = no_thp != nullptr && no_thp[0] != '0';
496    const bool skip_thp_request = arena_skip_thp_request(no_thp, thp_mode == "always", arena_no_thp_flag().load(std::memory_order_relaxed));
497    if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && skip_thp_request) {
498        const std::string four_k = "; using 4 KB pages";
499        if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0)
500            note.resize(note.size() - four_k.size());
501        note += user_no_thp
502                    ? "; transparent huge pages skipped (STRATA_NO_ARENA_THP)"
503                    : thp_mode == "always"
504                    ? "; transparent huge pages are on for every mapping (THP always): MADV_HUGEPAGE not requested"
505                    : "; huge pages not requested on this graphics chip";
506    } else if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && std::getenv("STRATA_ARENA_THP") == nullptr &&
507               free_huge_bytes() < bytes / 2) {
508        // #2126: THP "madvise" + defrag "madvise" makes every fault of a MADV_HUGEPAGE mapping reclaim and compact
509        // until it finds a 2 MiB block.  When less than half of the arena could be backed by blocks that are free
510        // now (a 62 GB box holding 47 GB of anonymous memory: 148K failed compactions, 100% system time, the load
511        // never ended), that is minutes of kernel work per GiB for a TLB gain.  Said, and STRATA_ARENA_THP=1 asks for it anyway.
512        const std::string four_k = "; using 4 KB pages";
513        if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0)
514            note.resize(note.size() - four_k.size());
515        note += "; transparent huge pages NOT requested: only " + std::to_string(free_huge_bytes() >> 30) +
516                " GiB of free 2 MiB blocks for a " + std::to_string(bytes >> 30) +
517                " GiB arena, compaction would stall the load (STRATA_ARENA_THP=1 requests them anyway) (#2126)";
518        std::fprintf(stderr, "strata: expert arena: %s\n", note.c_str());   // said now: the load that follows can take minutes
519    } else if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && madvise(p, bytes, MADV_HUGEPAGE) == 0) {
520        const std::string four_k = "; using 4 KB pages";
521        if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0)
522            note.resize(note.size() - four_k.size());
523        note += "; transparent huge pages requested (MADV_HUGEPAGE)";
524    }
525    return p;
526#endif
527}
528
529void release(void* p, uint64_t bytes) {
530    if (!p) return;
531#ifdef _WIN32
532    (void) bytes;
533    HANDLE section = nullptr;
534    {
535        std::lock_guard<std::mutex> lk(g_views_mu);
536        auto it = g_views.find(p);
537        if (it != g_views.end()) {
538            section = it->second;
539            g_views.erase(it);
540        }
541    }
542    if (section != nullptr) {          // a shared-section view: the pages stay while another engine has the section
543        UnmapViewOfFile(p);
544        CloseHandle(section);
545        return;
546    }
547    VirtualFree(p, 0, MEM_RELEASE);
548#else
549    munmap(p, bytes);
550#endif
551}
552
553}  // namespace
554
555uint64_t fnv1a64(const uint8_t* p, uint64_t n, uint64_t seed) {
556    uint64_t h = seed;
557    for (uint64_t i = 0; i < n; ++i) {
558        h ^= p[i];
559        h *= 1099511628211ull;
560    }
561    return h;
562}
563
564namespace {
565bool clear_error() { (void) cudaGetLastError(); return true; }
566}  // namespace
567
568namespace {
569std::atomic<uint64_t> g_idle_stack_lo{0}, g_idle_stack_hi{0};
570std::vector<uint64_t> g_held;   // sorted; set once by main() before any thread that pins exists
571}  // namespace
572
573void set_idle_thread_stack(uint64_t lo, uint64_t hi) {
574    g_idle_stack_lo.store(lo);
575    g_idle_stack_hi.store(hi);
576}
577
578void set_held_address_space(std::vector<uint64_t> bases) {
579    std::sort(bases.begin(), bases.end());
580    g_held = std::move(bases);
581}
582
583bool arena_no_register() {
584#if defined(STRATA_USE_HIP) && defined(__linux__)   // kfd_quiet NOREG scope: Linux HIP only, every other build keeps its old text
585    // an explicit setting wins over the engine's flag (kfd_quiet.hpp arena_unregistered: the same rule as before, testable)
586    return strata::core::kfd_quiet::arena_unregistered(std::getenv("STRATA_ARENA_PIN_GIB"),
587                                                       arena_uma_no_register_flag().load(std::memory_order_relaxed));
588#else
589    const char* e = std::getenv("STRATA_ARENA_PIN_GIB");
590    if (e != nullptr && *e != '\0') return std::string(e) == "none";   // an explicit setting wins over the engine's flag
591    return arena_uma_no_register_flag().load(std::memory_order_relaxed);
592#endif
593}
594
595int arena_pin_cap_gib() {
596    const char* e = std::getenv("STRATA_ARENA_PIN_GIB");
597    if (e == nullptr || *e == '\0') return -1;
598    if (std::string(e) == "none") return -1;   // 153-igpu: handled by arena_no_register(); no cap otherwise
599    if (std::string(e) == "auto") return -2;   // #243: the Windows shared-memory budget sets the sliced pin's cap
600    const int v = std::atoi(e);
601    return v < 0 ? -1 : v;
602}
603
604namespace {
605#ifdef _WIN32
606// #243: how much of the arena the sliced registration may pin on Windows when the whole arena was refused.
607// Page-locked memory the GPU maps is charged to its shared (non-local) WDDM segment; pinned slice by slice until
608// the driver refused one (28 GiB of a 63 GB PC), that segment was left full and every later cudaMalloc failed
609// "out of memory".  4 GiB of the budget stay free for what the engine allocates after the arena; without the DXGI
610// numbers, RAM/2 - 8 GiB (the budget is about half the RAM).  False: no limit could be worked out.
611bool sliced_pin_limit(uint64_t& limit, std::string& why) {
612    constexpr uint64_t GiB = 1ull << 30;
613    char buf[256];
614    int dev = 0;
615    cudaDeviceProp p{};
616    uint64_t budget = 0, usage = 0;
617    std::string err = "no CUDA device properties";
618    if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
619        strata::platform::gpu_shared_memory_budget(p.luid, budget, usage, err)) {
620        limit = budget > usage + 4 * GiB ? budget - usage - 4 * GiB : 0;
621        std::snprintf(buf, sizeof buf, "the GPU's shared-memory budget %.1f GiB - %.1f GiB in use - 4 GiB",
622                      (double) budget / GiB, (double) usage / GiB);
623        why = buf;
624        return true;
625    }
626    (void) cudaGetLastError();
627    const uint64_t ram = strata::platform::total_physical_memory();
628    if (ram == 0) return false;
629    limit = ram / 2 > 8 * GiB ? ram / 2 - 8 * GiB : 0;
630    std::snprintf(buf, sizeof buf, "%s: RAM/2 - 8 GiB of %.1f GiB", err.c_str(), (double) ram / GiB);
631    why = buf;
632    return true;
633}
634#endif
635}  // namespace
636
637namespace {
638std::vector<uint64_t> uniform_bounds(uint64_t bytes, uint64_t slice) {
639    std::vector<uint64_t> b;
640    if (slice == 0) return b;
641    for (uint64_t off = 0; off + slice <= bytes; off += slice) b.push_back(off);
642    if (!b.empty()) b.push_back(b.back() + slice);
643    return b;
644}
645
646#if defined(_WIN32) && defined(STRATA_USE_HIP)
647// #3431.  On Windows the HIP runtime gives every cudaHostRegister'ed range a second address for the GPU (its alias), and it
648// takes any host pointer inside that alias for the registered memory.  Unlike the addresses of cudaMalloc, the alias is not
649// reserved in the process's own address space, so a thread stack, a heap block or a mapping can be placed there.  In about one
650// engine start in ten one was (the stack of the thread that pins the arena): a cudaMemcpy from a local variable then read the
651// arena, a copy back into one wrote the arena, and every long prompt was read wrong until the process ended, with no error.
652// So the alias range is reserved here (address space only, nothing committed), and a range whose alias already covers memory
653// in use is not kept: true when the alias is clear (or there is none), with its reservations added to `claims`.  A runtime that
654// reserves the alias itself would have every range refused here, and logged.
655bool claim_alias(void* host, uint64_t n, std::vector<void*>& claims, std::string& why) {
656    void* d = nullptr;
657    if (cudaHostGetDevicePointer(&d, host, 0) != cudaSuccess || d == nullptr || d == host) {
658        (void) cudaGetLastError();
659        return true;
660    }
661    SYSTEM_INFO si;
662    GetSystemInfo(&si);
663    const uint64_t gran = si.dwAllocationGranularity;                 // where VirtualAlloc can start a reservation
664    const uint64_t top = (uint64_t) si.lpMaximumApplicationAddress;  // nothing of the process lies above
665    const uint64_t a = (uint64_t) d, end = std::min<uint64_t>(a + n, top);
666    std::vector<void*> got;
667    MEMORY_BASIC_INFORMATION mbi;
668    char msg[256] = "";
669    // the granule the alias starts in: when it is free in front of the alias too, the reservation starts at its boundary, or a
670    // small allocation could still be placed there and reach into the alias
671    uint64_t at = a;
672    const uint64_t a0 = a & ~(gran - 1);
673    if (a0 < a && a0 < end && VirtualQuery((void*) a0, &mbi, sizeof mbi) == sizeof mbi && mbi.State == MEM_FREE &&
674        (uint64_t) mbi.BaseAddress + mbi.RegionSize > a)
675        at = a0;
676    while (at < end) {
677        if (VirtualQuery((void*) at, &mbi, sizeof mbi) != sizeof mbi) {
678            std::snprintf(msg, sizeof msg, "VirtualQuery failed at %#llx", (unsigned long long) at);
679            break;
680        }
681        const uint64_t re = std::min<uint64_t>((uint64_t) mbi.BaseAddress + mbi.RegionSize, end);
682        const uint64_t idle_lo = g_idle_stack_lo.load(), idle_hi = g_idle_stack_hi.load();
683        const bool held = mbi.State == MEM_RESERVE && std::binary_search(g_held.begin(), g_held.end(), (uint64_t) mbi.AllocationBase);
684        const bool idle = mbi.State != MEM_FREE && idle_lo < idle_hi && (uint64_t) mbi.AllocationBase == idle_lo && re <= idle_hi;
685        if (held || idle) {
686            // held: main()'s reservation, kept for the life of the process.  idle: the first thread's stack, which only waits
687            at = (uint64_t) mbi.BaseAddress + mbi.RegionSize;
688            continue;
689        }
690        if (mbi.State != MEM_FREE) {
691            ULONG_PTR lo = 0, hi = 0;
692            GetCurrentThreadStackLimits(&lo, &hi);
693            const bool own_stack = at < (uint64_t) hi && (uint64_t) lo < re;
694            const char* kind = own_stack ? "this thread's stack" : mbi.Type == MEM_IMAGE ? "a module" :
695                               mbi.Type == MEM_MAPPED ? "a mapped view" : "private memory";
696            std::snprintf(msg, sizeof msg, "the GPU alias [%#llx, +%llu MiB) of the range at %p covers memory in use at %#llx (%s, from %p)",
697                          (unsigned long long) a, (unsigned long long) (n >> 20), host, (unsigned long long) at, kind,
698                          mbi.AllocationBase);
699            break;
700        }
701        // a free piece that starts inside a granule shares it with an allocation: nothing new can start there
702        const uint64_t b = (at + gran - 1) & ~(gran - 1);
703        if (b < re) {
704            void* r = VirtualAlloc((void*) b, (SIZE_T) (re - b), MEM_RESERVE, PAGE_NOACCESS);
705            if (r == nullptr) {
706                std::snprintf(msg, sizeof msg, "could not reserve the GPU alias [%#llx, +%llu MiB) of the range at %p (error %lu)",
707                              (unsigned long long) a, (unsigned long long) (n >> 20), host, GetLastError());
708                break;
709            }
710            got.push_back(r);
711        }
712        at = (uint64_t) mbi.BaseAddress + mbi.RegionSize;
713    }
714    if (msg[0] != '\0') {
715        for (void* g : got) VirtualFree(g, 0, MEM_RELEASE);
716        why = msg;
717        return false;
718    }
719    claims.insert(claims.end(), got.begin(), got.end());
720    return true;
721}
722#endif
723
724// after the ranges are unregistered
725void release_alias_claims(std::vector<void*>& claims) {
726#ifdef _WIN32
727    for (void* c : claims) VirtualFree(c, 0, MEM_RELEASE);
728#endif
729    claims.clear();
730}
731
732// pin_register for the arena's ranges.  Windows HIP: a range whose GPU alias covers memory in use is unregistered again and
733// reported as refused, so the caller's "the driver refused it" path applies to it (#3431).
734#if defined(__linux__)
735// every range start registered here, for unregister_arena_ranges (kfd_quiet.hpp, EXIT); bookkeeping only
736std::mutex g_reg_mu;
737std::vector<void*> g_reg_starts;
738#endif
739
740cudaError_t register_range(PinnedArena& arena, void* p, uint64_t n) {
741    const cudaError_t e = pin_register(p, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped);
742#if defined(__linux__)
743    if (e == cudaSuccess) {
744        std::lock_guard<std::mutex> lk(g_reg_mu);
745        g_reg_starts.push_back(p);
746    }
747#endif
748#if defined(_WIN32) && defined(STRATA_USE_HIP)
749    std::string why;
750    if (e == cudaSuccess && !claim_alias(p, n, arena.alias_claims, why)) {
751        (void) pin_unregister(p);
752        (void) cudaGetLastError();
753        std::fprintf(stderr, "strata pin: %s; that range stays unregistered (#3431)\n", why.c_str());
754        arena.note = "left unregistered: " + why + " (#3431); " + arena.note;
755        return cudaErrorMemoryAllocation;
756    }
757#else
758    (void) arena;
759#endif
760    return e;
761}
762}  // namespace
763
764int unregister_arena_ranges() {
765#if defined(__linux__)
766    std::lock_guard<std::mutex> lk(g_reg_mu);
767    int n = 0;
768    for (void* p : g_reg_starts)
769        if (pin_unregister(p) == cudaSuccess) ++n;
770    (void) cudaGetLastError();
771    g_reg_starts.clear();
772    return n;
773#else
774    return 0;
775#endif
776}
777
778PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, uniform_bounds(bytes, slice)) {
779    if (slice_bytes) slice_bytes = slice;   // sliced registration: record the uniform size
780}
781
782PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds,
783                         uint64_t max_pinned_bytes, const std::string& shared_file,
784                         uint64_t shared_pack_hash) : capacity(bytes) {
785    if (bytes == 0) return;
786    base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes);
787    if (!shared_file.empty() && base != nullptr && mapping_base != nullptr)
788        shared_state = reinterpret_cast<std::atomic<uint64_t>*>(static_cast<char*>(mapping_base) +
789                                                                offsetof(SharedArenaHeader, reserved));
790    if (base != nullptr && mapping_base == nullptr) {
791        mapping_base = base;
792        mapping_bytes = bytes;
793    }
794
795    // Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region
796    // that has already been faulted in page by page is far more expensive to register and may fail outright.
797    if (base && arena_no_register()) {
798        // 153-igpu (UMA mode): nothing is registered; the whole arena stays resident through the working-set lock instead
799        slice_bytes = 1;   // "sliced" with no slice registered: the destructor unlocks from offset registered_bytes (0)
800        const char* env = std::getenv("STRATA_ARENA_LOCK");
801#if defined(STRATA_USE_HIP) && defined(__linux__)   // kfd_quiet NOREG scope: Linux HIP only, every other build keeps its old text
802        // (kfd_quiet.hpp NOREG, the Radeon 780M class under Linux: when the engine chose this mode, no mlock is tried and nothing is said
803        // about it; a STRATA_ARENA_LOCK the user set decides as before)
804        const bool noreg = strata::core::kfd_quiet::noreg_flag().load(std::memory_order_relaxed);
805        if (backing == PageBacking::LargePages) {
806            note = "large pages are resident without a lock; " + note;
807        } else if (strata::core::kfd_quiet::arena_lock_wanted(noreg, env)) {
808            const strata::platform::LockResult lr = strata::platform::lock_resident((uint8_t*) base, bytes);
809            locked_bytes = lr.locked_bytes;
810            note = lr.note + "; " + note;
811        } else if (!noreg || env != nullptr) {
812            note = "arena lock disabled (STRATA_ARENA_LOCK=0); " + note;
813        }
814#else
815        if (backing == PageBacking::LargePages) {
816            note = "large pages are resident without a lock; " + note;
817        } else if (env == nullptr || std::string(env) != "0") {
818            const strata::platform::LockResult lr = strata::platform::lock_resident((uint8_t*) base, bytes);
819            locked_bytes = lr.locked_bytes;
820            note = lr.note + "; " + note;
821        } else {
822            note = "arena lock disabled (STRATA_ARENA_LOCK=0); " + note;
823        }
824#endif
825        note = "NOT registered with the GPU driver (integrated GPU, UMA mode; STRATA_ARENA_PIN_GIB=0 registers it); " + note;
826        return;
827    }
828    if (base) {
829        // #243: STRATA_ARENA_PIN_GIB=N caps the registration from the start where the caller set no cap
830        const int env_gib = arena_pin_cap_gib();
831        uint64_t cap = max_pinned_bytes;
832        std::string cap_why = "by the engine (multi-GPU under WDDM, or remote experts)";
833        if (cap == 0 && env_gib > 0) {
834            cap = (uint64_t) env_gib << 30;
835            cap_why = "by STRATA_ARENA_PIN_GIB";
836        }
837        const bool capped = cap > 0 && cap < bytes && bounds.size() >= 2;
838        const cudaError_t e = capped ? cudaSuccess :
839            register_range(*this, base, bytes);
840        if (!capped && e == cudaSuccess) {
841            note = "cudaHostRegister PORTABLE ok; " + note;
842            registered_bytes = bytes;
843        } else if (bounds.size() >= 2 && (capped || clear_error())) {
844            // Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start.  The rest stays
845            // resident through the working-set lock below.  (P6: slices may differ in size, one per layer.)
846            slice_bytes = 1;   // sliced; the uniform constructor records the size
847            bool limited = capped;
848            uint64_t limit = cap;
849            std::string limit_why;
850#ifdef _WIN32
851            // #243 (opt-in, STRATA_ARENA_PIN_GIB=auto): not up to the driver's refusal but below the shared-memory
852            // budget, for a PC where the full sliced pin leaves WDDM refusing later allocations.  Not the default: a
853            // 64 GB PC pins 30 GiB past that budget without trouble, and capping it at 26 cost ~20% prompt speed.
854            if (!capped && env_gib == -2) limited = sliced_pin_limit(limit, limit_why);
855#endif
856            for (size_t i = 0; i + 1 < bounds.size(); ++i) {
857                const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i];
858                if (limited && (off > limit || n > limit - off)) break;
859                if (register_range(*this, (uint8_t*) base + off, n) != cudaSuccess) {
860                    (void) cudaGetLastError();
861                    break;
862                }
863                slice_starts.push_back(off);
864                registered_bytes = off + n;
865                ++registered_slices;
866            }
867            char gib[32];
868            std::snprintf(gib, sizeof gib, "%.1f", (double) limit / (double) (1ull << 30));
869            note = (capped ? "cudaHostRegister limited to " + std::to_string(cap >> 30) + " GiB " + cap_why + "; " :
870                             "cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); " +
871                             (limited ? "slices capped at " + std::string(gib) + " GiB (" + limit_why +
872                                        "; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); " : std::string())) +
873                   std::to_string(registered_slices) + " slices pinned (" + std::to_string(registered_bytes >> 30) +
874                   " GiB); " + note;
875            if (registered_bytes < bytes) {
876                const char* env = std::getenv("STRATA_ARENA_LOCK");
877                if (backing == PageBacking::LargePages) {   // #779: large pages cannot be paged out: nothing to lock
878                    note = "large pages are resident without a lock; " + note;
879                } else if (env == nullptr || std::string(env) != "0") {
880                    const strata::platform::LockResult lr =
881                        strata::platform::lock_resident((uint8_t*) base + registered_bytes, bytes - registered_bytes);
882                    locked_bytes = lr.locked_bytes;
883                    note = lr.note + "; " + note;
884                }
885            }
886        } else {
887            note = std::string("cudaHostRegister FAILED (") + cudaGetErrorString(e) +
888                   ") - the arena is NOT pinned, so copies will be slow; " + note;
889            // **CONSUME THE ERROR, OR IT LIES ABOUT SOMETHING ELSE LATER.**
890            //
891            // `cudaGetLastError()` returns the last error and CLEARS it; until something reads it, the error
892            // state is sticky.  This failure is caught and handled right here - the arena is simply not pinned -
893            // but leaving it set meant the next `cudaGetLastError()` in the engine, which is `gr_read`'s launch
894            // check, reported "out of memory" for kernels that allocate nothing.  That cost a round: the arena
895            // was written off as not fitting the machine when in fact the only thing wrong was a stale error
896            // from this line.
897            //
898            // It is the same trap `gr.cu` warns about for ASYNC faults, in the other direction: a synchronous
899            // failure is sticky too, and it lies about where it happened just as convincingly.
900            (void) cudaGetLastError();
901            // Plan v0.3 P0.1: keep it RESIDENT instead. Unpinned, Windows trims the arena under memory pressure
902            // and the CPU pool's rate then depends on the OS; locking it through the working set needs no
903            // special privilege. STRATA_ARENA_LOCK=0 is the A/B arm.
904            const char* env = std::getenv("STRATA_ARENA_LOCK");
905            if (backing == PageBacking::LargePages) {       // #779: large pages cannot be paged out: nothing to lock
906                note = "large pages are resident without a lock; " + note;
907            } else if (env == nullptr || std::string(env) != "0") {
908                const strata::platform::LockResult lr = strata::platform::lock_resident(base, bytes);
909                locked_bytes = lr.locked_bytes;
910                note = lr.note + "; " + note;
911            } else {
912                note = "arena lock disabled (STRATA_ARENA_LOCK=0); " + note;
913            }
914        }
915    }
916}
917
918PinnedArena::PinnedArena(uint64_t bytes, ByNeed, const std::vector<std::pair<uint64_t, uint64_t>>& ranges,
919                         uint64_t max_pinned_bytes, const std::string& shared_file,
920                         uint64_t shared_pack_hash) : capacity(bytes) {
921    by_need = true;
922    if (bytes == 0) return;
923    base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes);
924    if (!shared_file.empty() && base != nullptr && mapping_base != nullptr)
925        shared_state = reinterpret_cast<std::atomic<uint64_t>*>(static_cast<char*>(mapping_base) +
926                                                                offsetof(SharedArenaHeader, reserved));
927    if (base != nullptr && mapping_base == nullptr) {
928        mapping_base = base;
929        mapping_bytes = bytes;
930    }
931    if (base == nullptr) return;
932    // Register BEFORE any page is touched (see the first constructor).  Same caps as there: the engine's
933    // `max_pinned_bytes`, else STRATA_ARENA_PIN_GIB=N (> 0); "auto" (-2) is the sliced pin's and does not apply.
934    const int env_gib = arena_pin_cap_gib();
935    uint64_t cap = max_pinned_bytes;
936    if (cap == 0 && env_gib > 0) cap = (uint64_t) env_gib << 30;
937#ifdef _WIN32
938    // WDDM: the pin must leave margin (the budget is ~RAM/2 and later cudaMallocs need room).  Unset: 29 GiB;
939    // "auto" (-2): the sliced pin's shared-memory-budget limit (29 GiB when it cannot be worked out);
940    // STRATA_ARENA_PIN_GIB=0 ("the whole arena"): no cap, up to the driver's refusal.
941    if (cap == 0 && env_gib != 0) {
942        uint64_t lim = 0;
943        std::string why;
944        cap = env_gib == -2 && sliced_pin_limit(lim, why) && lim > 0 ? lim : (29ull << 30);
945    }
946#endif
947    constexpr uint64_t kPage = 4096;
948    std::map<uint64_t, uint64_t> done;   // registered [start, end), by start: ranges never overlap
949    uint64_t total = 0;
950    int refused = 0;
951    bool capped = false;
952    const bool none = arena_no_register();   // 153-igpu UMA mode: register no range at all; every byte is a locked "hole" below
953    for (const auto& rg : ranges) {
954        if (none) break;
955        if (rg.second == 0 || rg.first >= bytes) continue;
956        // INWARD: a registered page holds no byte of an unpinned neighbour blob (a copy that STARTS in a registered page
957        // and runs past the registration is rejected by CUDA); the boundary pages stay unregistered
958        uint64_t a = (rg.first + kPage - 1) & ~(kPage - 1);
959        uint64_t b = std::min<uint64_t>(rg.first + rg.second, bytes) & ~(kPage - 1);
960        // a page shared with a range registered before (blobs smaller than a page, or odd offsets) is already
961        // registered: registering it twice is an error, so trim to what is left; a range inside one is skipped
962        auto it = done.upper_bound(a);
963        if (it != done.begin()) {
964            auto p = std::prev(it);
965            if (p->second > a) a = p->second;
966        }
967        if (it != done.end() && it->first < b) b = it->first;
968        if (a >= b) continue;
969        if (cap > 0 && total + (b - a) > cap) { capped = true; break; }
970        if (register_range(*this, (uint8_t*) base + a, b - a) != cudaSuccess) {
971            (void) cudaGetLastError();
972            refused = 1;
973            break;
974        }
975        done[a] = b;
976        total += b - a;
977    }
978    for (const auto& d : done) pin_ranges.emplace_back(d.first, d.second - d.first);
979    registered_bytes = total;
980    registered_slices = (int) pin_ranges.size();
981    // the holes stay resident through the working-set lock, as the sliced fallback does for its tail
982    std::vector<std::pair<void*, uint64_t>> holes;
983    uint64_t cur = 0, hole_bytes = 0;
984    for (const auto& r : pin_ranges) {
985        if (r.first > cur) { locked_ranges.emplace_back(cur, r.first - cur); hole_bytes += r.first - cur; }
986        cur = r.first + r.second;
987    }
988    if (cur < bytes) { locked_ranges.emplace_back(cur, bytes - cur); hole_bytes += bytes - cur; }
989    note = "pin by need: " + std::to_string(pin_ranges.size()) + " ranges registered (" + std::to_string(total >> 20) +
990           " MiB)" + (refused ? ", the driver refused the next one" : capped ? ", the cap was reached" : "") +
991           "; " + note;
992    const char* env = std::getenv("STRATA_ARENA_LOCK");
993    if (backing == PageBacking::LargePages) {   // #779: large pages cannot be paged out: nothing to lock
994        note = "large pages are resident without a lock; " + note;
995        locked_ranges.clear();
996    } else if (env != nullptr && std::string(env) == "0") {
997        note = "arena lock disabled (STRATA_ARENA_LOCK=0); " + note;
998        locked_ranges.clear();
999#if defined(STRATA_USE_HIP) && defined(__linux__)   // kfd_quiet NOREG scope: Linux HIP only, every other build keeps its old text
1000    } else if (none && !strata::core::kfd_quiet::arena_lock_wanted(strata::core::kfd_quiet::noreg_flag().load(std::memory_order_relaxed), env)) {
1001        locked_ranges.clear();   // kfd_quiet.hpp NOREG chose the unregistered arena: no mlock tried, nothing said (as in the constructor above)
1002#endif
1003    } else {
1004        for (const auto& r : locked_ranges) holes.emplace_back((uint8_t*) base + r.first, r.second);
1005        const strata::platform::LockResult lr = strata::platform::lock_resident_ranges(holes);
1006        locked_bytes = lr.locked_bytes;
1007        note = lr.note + " (" + std::to_string(hole_bytes >> 20) + " MiB of holes); " + note;
1008        // a partial lock is unlocked region by region in the destructor; what it did not reach was never locked
1009        // (VirtualUnlock/munlock of an unlocked page is harmless), so the list is kept whole
1010    }
1011}
1012
1013PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds, Deferred)
1014    : capacity(bytes), bounds_(bounds) {
1015    if (bytes == 0 || bounds.size() < 2) return;
1016    base = reserve(bytes, backing, note, std::string{}, 0, mapping_base, mapping_bytes);
1017    if (base != nullptr && mapping_base == nullptr) {
1018        mapping_base = base;
1019        mapping_bytes = bytes;
1020    }
1021    slice_bytes = 1;   // sliced: one registration per layer
1022}
1023
1024void PinnedArena::register_slices(std::atomic<int>& ready) {
1025    const int n = (int) bounds_.size() - 1;
1026    int i = 0;
1027    for (; base != nullptr && i < n; ++i) {
1028        const uint64_t off = bounds_[(size_t) i], len = bounds_[(size_t) i + 1] - off;
1029        if (register_range(*this, (uint8_t*) base + off, len) != cudaSuccess) {
1030            (void) cudaGetLastError();
1031            break;
1032        }
1033        slice_starts.push_back(off);
1034        registered_bytes = off + len;
1035        ++registered_slices;
1036        ready.store(i + 1, std::memory_order_release);
1037    }
1038    note = "cudaHostRegister per layer, pipelined with the load: " + std::to_string(registered_slices) + " of " +
1039           std::to_string(n) + " slices pinned; " + note;
1040    if (i < n && base != nullptr) {   // the rest stays resident through the working-set lock, as the sliced fallback does
1041        const char* env = std::getenv("STRATA_ARENA_LOCK");
1042        if (backing == PageBacking::LargePages) {           // #779: large pages cannot be paged out: nothing to lock
1043            note = "large pages are resident without a lock; " + note;
1044        } else if (env == nullptr || std::string(env) != "0") {
1045            const strata::platform::LockResult lr =
1046                strata::platform::lock_resident((uint8_t*) base + registered_bytes, capacity - registered_bytes);
1047            locked_bytes = lr.locked_bytes;
1048            note = lr.note + "; " + note;
1049        }
1050    }
1051    ready.store(INT_MAX, std::memory_order_release);   // every slice done (or given up on)
1052}
1053
1054PinnedArena::~PinnedArena() {
1055    if (base && by_need) {
1056        for (const auto& r : locked_ranges) strata::platform::unlock_resident((uint8_t*) base + r.first, r.second);
1057        for (const auto& r : pin_ranges) pin_unregister((uint8_t*) base + r.first);
1058        release_alias_claims(alias_claims);
1059        release(mapping_base ? mapping_base : base, mapping_bytes ? mapping_bytes : capacity);
1060        base = nullptr;
1061        mapping_base = nullptr;
1062        mapping_bytes = 0;
1063        return;
1064    }
1065    if (base) {
1066        if (locked_bytes) strata::platform::unlock_resident((uint8_t*) base + (slice_bytes ? registered_bytes : 0), locked_bytes);
1067        if (slice_bytes) {
1068            for (uint64_t off : slice_starts) pin_unregister((uint8_t*) base + off);
1069        } else {
1070            pin_unregister(base);
1071        }
1072        release_alias_claims(alias_claims);
1073        release(mapping_base ? mapping_base : base, mapping_bytes ? mapping_bytes : capacity);
1074        base = nullptr;
1075        mapping_base = nullptr;
1076        mapping_bytes = 0;
1077    }
1078}
1079
1080LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer,
1081                       uint64_t layers, int threads, uint64_t chunk) {
1082    std::vector<uint64_t> off((size_t) layers), n((size_t) layers, blobs_per_layer * blob_bytes);
1083    for (uint64_t L = 0; L < layers; ++L) off[(size_t) L] = L * blobs_per_layer * blob_bytes;
1084    return load_experts_ranges(path, dst, off, n, threads, chunk);
1085}
1086
1087LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
1088                              const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk,
1089                              const std::atomic<int>* ready) {
1090    LoadStats st;
1091    st.ok = false;
1092#ifdef _WIN32
1093    constexpr uint64_t kAlign = 4096;
1094    if (((uintptr_t) dst % kAlign) != 0 || chunk == 0 || chunk % kAlign != 0) return st;
1095    struct Piece { uint64_t off, n; int layer; };
1096    std::vector<Piece> pieces;
1097    uint64_t bytes = 0;
1098    for (size_t L = 0; L < layer_off.size(); ++L) {
1099        if (layer_off[L] % kAlign != 0 || layer_bytes[L] % kAlign != 0) return st;
1100        for (uint64_t p = 0; p < layer_bytes[L]; p += chunk)
1101            pieces.push_back({layer_off[L] + p, std::min<uint64_t>(chunk, layer_bytes[L] - p), (int) L});
1102        bytes += layer_bytes[L];
1103    }
1104    if (threads < 1) threads = 1;
1105    const auto t0 = std::chrono::steady_clock::now();
1106    std::atomic<size_t> next{0};
1107    std::mutex err_mu;
1108    std::string err;
1109    const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
1110    std::vector<wchar_t> wpath((size_t) (std::max)(wide, 1), L'\0');
1111    if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
1112    auto worker = [&]() {
1113        HANDLE h = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1114                               FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
1115        if (h == INVALID_HANDLE_VALUE) {
1116            std::lock_guard<std::mutex> g(err_mu);
1117            if (err.empty())
1118                err = "cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) + ")";
1119            next = pieces.size();
1120            return;
1121        }
1122        for (;;) {
1123            const size_t i = next.fetch_add(1);
1124            if (i >= pieces.size()) break;
1125            if (ready != nullptr)      // the slice must be registered before its pages are touched
1126                while (ready->load(std::memory_order_acquire) <= pieces[i].layer + 1) std::this_thread::yield();
1127            OVERLAPPED ov{};
1128            ov.Offset = (DWORD) pieces[i].off;
1129            ov.OffsetHigh = (DWORD) (pieces[i].off >> 32);
1130            DWORD got = 0;
1131            if (!ReadFile(h, dst + pieces[i].off, (DWORD) pieces[i].n, &got, &ov) || got != pieces[i].n) {
1132                std::lock_guard<std::mutex> g(err_mu);
1133                if (err.empty())
1134                    err = "short unbuffered read at offset " + std::to_string(pieces[i].off) + ": got " + std::to_string(got) +
1135                          " of " + std::to_string(pieces[i].n) + " B (error " +
1136                          std::to_string((unsigned long long) GetLastError()) + ")";
1137                next = pieces.size();
1138                break;
1139            }
1140        }
1141        CloseHandle(h);
1142    };
1143    std::vector<std::thread> pool;
1144    for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
1145    worker();
1146    for (auto& t : pool) t.join();
1147    st.layers = layer_off.size();
1148    if (!err.empty()) {
1149        st.seconds = -1.0;
1150        st.error = err;
1151        return st;
1152    }
1153    st.ok = true;
1154    st.bytes = bytes;
1155    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
1156#else
1157    (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; (void) ready;
1158#endif
1159    return st;
1160}
1161
1162bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_bytes, std::string& why,
1163                        bool cache_counts, uint64_t read_bytes) {
1164    const char* env = std::getenv("STRATA_UNBUFFERED_LOAD");
1165    if (env != nullptr && env[0] != '\0') {
1166        why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
1167        return env[0] != '0';
1168    }
1169#ifdef _WIN32
1170    LARGE_INTEGER freq{}, a{}, b{};
1171    QueryPerformanceFrequency(&freq);
1172    constexpr DWORD kRead = 64 << 10;
1173    constexpr int kSamples = 16;
1174    std::vector<uint8_t> buf(kRead);
1175    uint64_t total_bytes = 0;
1176    int fast = 0, n = 0;
1177    uint64_t seed = (uint64_t) GetTickCount64() * 6364136223846793005ull + 1442695040888963407ull;
1178    for (const std::string& f : files) {
1179        const int wide = MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, nullptr, 0);
1180        std::vector<wchar_t> w((size_t) (std::max)(wide, 1), L'\0');
1181        if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, w.data(), wide);
1182        HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,
1183                               nullptr);
1184        if (h == INVALID_HANDLE_VALUE) continue;
1185        LARGE_INTEGER size{};
1186        GetFileSizeEx(h, &size);
1187        total_bytes += (uint64_t) size.QuadPart;
1188        // random offsets: a probe must not find the blocks an earlier probe put into the cache
1189        for (int i = 0; i < kSamples && (uint64_t) size.QuadPart > 2ull * kRead; ++i) {
1190            seed = seed * 6364136223846793005ull + 1442695040888963407ull;
1191            const uint64_t off = ((seed >> 17) % ((uint64_t) size.QuadPart - kRead)) / kRead * kRead;
1192            OVERLAPPED ov{};
1193            ov.Offset = (DWORD) off;
1194            ov.OffsetHigh = (DWORD) (off >> 32);
1195            DWORD got = 0;
1196            QueryPerformanceCounter(&a);
1197            const BOOL ok = ReadFile(h, buf.data(), kRead, &got, &ov);
1198            QueryPerformanceCounter(&b);
1199            if (!ok) continue;
1200            ++n;
1201            fast += (double) (b.QuadPart - a.QuadPart) * 1e6 / (double) freq.QuadPart < 30.0;
1202        }
1203        CloseHandle(h);
1204    }
1205    const bool cached = n > 0 && fast * 4 >= n * 3;
1206    MEMORYSTATUSEX ms{};
1207    ms.dwLength = sizeof ms;
1208    GlobalMemoryStatusEx(&ms);
1209    const uint64_t avail = ms.ullAvailPhys;
1210    // what the cache could keep beside the arena (~4 GiB for everything else)
1211    const uint64_t need = read_bytes == kAllFileBytes ? total_bytes : read_bytes;
1212    const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, need);
1213    char msg[256];
1214    if (read_bytes == kAllFileBytes)
1215        std::snprintf(msg, sizeof msg, "%d of %d probe reads from the file cache; %.1f GiB available, %.1f GiB of files",
1216                      fast, n, (double) avail / (1ull << 30), (double) total_bytes / (1ull << 30));
1217    else
1218        std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB "
1219                      "of experts read from the files: the file cache %s keep them",
1220                      (double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) need / (1ull << 30),
1221                      keepable ? "can" : "cannot");
1222    why = msg;
1223    return (!cached || !cache_counts) && !keepable;
1224#else
1225    (void) files; (void) arena_bytes; (void) cache_counts; (void) read_bytes;
1226    why = "buffered (not Windows)";
1227    return false;
1228#endif
1229}
1230
1231LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
1232                              const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk,
1233                              const std::atomic<int>* ready) {
1234    return load_experts_ranges(path, dst, layer_off, layer_bytes, threads, chunk, ready, nullptr);
1235}
1236
1237LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
1238                              const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk,
1239                              const std::atomic<int>* ready, const PadMap* pad, bool drop_behind) {
1240    LoadStats st;
1241    const uint64_t layers = (uint64_t) layer_off.size();
1242    st.layers = layers;
1243    st.bytes = 0;
1244    for (uint64_t b : layer_bytes) st.bytes += b;
1245    if (threads < 1) threads = 1;
1246
1247    const auto t0 = std::chrono::steady_clock::now();
1248    std::vector<uint64_t> layer_hash((size_t) layers, 1469598103934665603ull);
1249    std::atomic<uint64_t> next_layer{0};
1250    std::atomic<uint64_t> read_ns_sum{0};   // summed over the threads: see LoadStats::read_seconds
1251    std::atomic<uint64_t> copy_ns_sum{0};
1252    std::mutex err_mu;
1253    std::string err;
1254
1255    auto worker = [&]() {
1256        std::vector<uint8_t> buf((size_t) chunk);
1257        // One handle per thread, seeked once per layer: a shared handle would need a lock around the seek and
1258        // would serialise the very thing the threads are here to parallelise.  `fread` on a `FILE*` rather than
1259        // `std::ifstream`: see the header - MSVC's `basic_filebuf::xsgetn` splits any request larger than
1260        // `_INTERNAL_BUFSIZ - 1` into 4095-byte freads, which turned one 8 MiB chunk into ~2048 4 KiB reads.
1261        // `fread` sees a request bigger than the stream buffer and passes it to `_read()`/
1262        // `ReadFile()` unchanged, so the chunk size reaches the disk.  Buffered, not `FILE_FLAG_NO_BUFFERING`:
1263        // the cache should still hold what it can.
1264        FILE* f = std::fopen(path.c_str(), "rb");
1265        if (f == nullptr) {
1266            std::lock_guard<std::mutex> g(err_mu);
1267            err = "cannot open " + path;
1268            return;
1269        }
1270        // A `FILE*` has no destructor that closes it, and this function has early returns below (open, seek and
1271        // short-read failures), so the guard is what keeps the closing correct on every path.
1272        struct Closer {
1273            FILE* f;
1274            ~Closer() { if (f != nullptr) std::fclose(f); }
1275        } closer{f};
1276        uint64_t read_ns = 0, copy_ns = 0;
1277        for (;;) {
1278            const uint64_t L = next_layer.fetch_add(1);
1279            if (L >= layers) break;
1280            if (ready != nullptr)      // the slice must be registered before its pages are touched
1281                while (ready->load(std::memory_order_acquire) <= (int) L + 1) std::this_thread::yield();
1282            const uint64_t off = layer_off[(size_t) L];
1283            uint64_t remaining = layer_bytes[(size_t) L];
1284            uint64_t pos = 0;
1285            uint64_t h = 1469598103934665603ull;
1286            // 64-bit seek: the pack is 42.9 GB, so the 32-bit `fseek` would wrap past 4 GiB
1287            if (STRATA_FSEEK64(f, off) != 0) {
1288                std::lock_guard<std::mutex> g(err_mu);
1289                err = "seek to " + std::to_string(off) + " B failed in layer " + std::to_string(L);
1290                return;
1291            }
1292            while (remaining > 0) {
1293                const uint64_t n = remaining < chunk ? remaining : chunk;
1294                const auto t_read = std::chrono::steady_clock::now();
1295                const size_t got = std::fread(buf.data(), 1, (size_t) n, f);
1296                read_ns += (uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(
1297                               std::chrono::steady_clock::now() - t_read).count();
1298                // A short read is EOF or an I/O error, never a silent zero fill: say WHERE and HOW SHORT, and
1299                // keep going no further - the caller turns this into a refused load, not a wrong answer.
1300                if (got != (size_t) n) {
1301                    std::lock_guard<std::mutex> g(err_mu);
1302                    err = "short read in layer " + std::to_string(L) + ": got " + std::to_string(got) + " of "
1303                          + std::to_string(n) + " B at offset " + std::to_string(off + pos)
1304                          + (std::ferror(f) != 0 ? " (ferror set)" : "");
1305                    return;
1306                }
1307                const auto t_copy = std::chrono::steady_clock::now();
1308                if (pad == nullptr) {
1309                    std::memcpy(dst + off + pos, buf.data(), (size_t) n);
1310                } else {   // the padded layout: a chunk may span blobs, each lands at its own page-aligned start
1311                    const uint64_t B = pad->blob[(size_t) L], S = pad->stride[(size_t) L];
1312                    for (uint64_t q = 0; q < n;) {
1313                        const uint64_t p = pos + q, bi = p / B, in = p % B;
1314                        const uint64_t m = std::min<uint64_t>(n - q, B - in);
1315                        std::memcpy(dst + pad->dst_off[(size_t) L] + bi * S + in, buf.data() + q, (size_t) m);
1316                        q += m;
1317                    }
1318                }
1319                h = fnv1a64(buf.data(), n, h);
1320                copy_ns += (uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(
1321                               std::chrono::steady_clock::now() - t_copy).count();
1322#if defined(__linux__)
1323                // this chunk is in the arena now: its file-cache pages are only a second copy.  Advice; a failure is ignored.
1324                if (drop_behind) (void) strata::core::page_cache_drop::drop_range(::fileno(f), off + pos, n);
1325#endif
1326                pos += n;
1327                remaining -= n;
1328            }
1329            layer_hash[(size_t) L] = h;
1330        }
1331        read_ns_sum.fetch_add(read_ns);
1332        copy_ns_sum.fetch_add(copy_ns);
1333    };
1334
1335    std::vector<std::thread> pool;
1336    for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
1337    worker();
1338    for (auto& t : pool) t.join();
1339
1340    if (!err.empty()) {
1341        std::fprintf(stderr, "load_experts: %s\n", err.c_str());
1342        st.seconds = -1.0;
1343        st.ok = false;
1344        st.error = err;
1345        return st;
1346    }
1347    st.read_seconds = (double) read_ns_sum.load() / 1e9;
1348    st.copy_seconds = (double) copy_ns_sum.load() / 1e9;
1349    st.layer_checksums = std::move(layer_hash);
1350    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
1351    return st;
1352}
1353
1354StreamStats stream_bandwidth(const uint8_t* src, uint64_t bytes, uint64_t chunk, int iters) {
1355    StreamStats st;
1356    st.bytes = bytes * (uint64_t) iters;
1357    st.chunk = chunk;
1358    uint8_t* dst = nullptr;
1359    cudaStream_t s{};
1360    if (cudaMalloc(&dst, (size_t) chunk) != cudaSuccess) {
1361        std::fprintf(stderr, "stream_bandwidth: cudaMalloc failed for %llu B\n", (unsigned long long) chunk);
1362        st.seconds = -1.0;
1363        return st;
1364    }
1365    cudaStreamCreate(&s);
1366
1367    // one untimed pass so the first transfer's page-fault and setup cost is not in the measurement
1368    for (uint64_t off = 0; off + chunk <= bytes; off += chunk) {
1369        cudaMemcpyAsync(dst, src + off, (size_t) chunk, cudaMemcpyHostToDevice, s);
1370    }
1371    cudaStreamSynchronize(s);
1372
1373    const auto t0 = std::chrono::steady_clock::now();
1374    for (int it = 0; it < iters; ++it) {
1375        for (uint64_t off = 0; off + chunk <= bytes; off += chunk) {
1376            cudaMemcpyAsync(dst, src + off, (size_t) chunk, cudaMemcpyHostToDevice, s);
1377        }
1378    }
1379    cudaStreamSynchronize(s);
1380    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
1381
1382    cudaStreamDestroy(s);
1383    cudaFree(dst);
1384    return st;
1385}
1386
1387}  // namespace strata::core