okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
00c004617
main
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 ) 48const char * v = std::getenv ("DS4_TIMER_MS" ); 49const int ms = v != nullptr ? std::atoi (v ) :0 ; 50if (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) 59const int n = MultiByteToWideChar (CP_UTF8 ,0 ,s .c_str (),-1 ,nullptr ,0 ); 60 std::wstring w ((size_t ) (n > 0 ?n :1 ),L'\0' ); 61if (n > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,s .c_str (),-1 ,& w [0 ],n ); 62return 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 ) 69HANDLE h = CreateFileW (wide (path ).c_str (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 70FILE_ATTRIBUTE_NORMAL ,nullptr ); 71return h == INVALID_HANDLE_VALUE ?kBadFd : (fd_t )h ; 72#else 73const int fd = ::open (path .c_str (),O_RDONLY ); 74return 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) 83static const bool off = [] { 84const char * v = std::getenv ("DS4_WIN_DIRECT" ); 85return v != nullptr && std::atoi (v )== 0 ; 86 }(); 87if (off )return kBadFd ; 88HANDLE h = CreateFileW (wide (path ).c_str (),GENERIC_READ ,FILE_SHARE_READ |FILE_SHARE_WRITE ,nullptr ,OPEN_EXISTING , 89FILE_FLAG_NO_BUFFERING |FILE_FLAG_OVERLAPPED ,nullptr ); 90return h == INVALID_HANDLE_VALUE ?kBadFd : (fd_t )h ; 91#else 92const int fd = ::open (path .c_str (),O_RDONLY |O_DIRECT ); 93return 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 ) { 101const uint64_t a0 = off & ~(kDirectAlign - 1 ),a1 = (off + n + kDirectAlign - 1 )& ~(kDirectAlign - 1 ); 102return a1 - a0 ; 103} 104inline bool pread_direct (fd_t f ,void * dst ,uint64_t n ,uint64_t off ) { 105#if defined(_WIN32 ) 106struct Ev {// (each thread its own, closed when it ends) 107HANDLE h = CreateEventW (nullptr , TRUE, FALSE,nullptr ); 108 ~Ev () { 109if (h != nullptr )CloseHandle (h ); 110 } 111 }; 112static thread_localEv ev ; 113if (ev .h == nullptr )return false; 114const uint64_t a0 = off & ~(kDirectAlign - 1 ),need = direct_span (off ,n ),want = (off - a0 )+ n ; 115uint8_t * p = (uint8_t * )dst ; 116uint64_t got = 0 ; 117while (got < need ) { 118const DWORD ask = (DWORD ) std::min < uint64_t > (need - got ,1ull <<30 );// (a multiple of 4096) 119OVERLAPPED ov {}; 120const uint64_t at = a0 + got ; 121ov .Offset = (DWORD ) (at & 0xffffffffu ); 122ov .OffsetHigh = (DWORD ) (at >>32 ); 123ov .hEvent = ev .h ; 124ResetEvent (ev .h ); 125DWORD r = 0 ; 126if (!ReadFile ((HANDLE )f ,p + got ,ask ,nullptr ,& ov )) { 127const DWORD e = GetLastError (); 128if (e == ERROR_HANDLE_EOF )break ; 129if (e != ERROR_IO_PENDING )return false; 130 } 131if (!GetOverlappedResult ((HANDLE )f ,& ov ,& r , TRUE)) { 132if (GetLastError ()== ERROR_HANDLE_EOF )break ; 133return false; 134 } 135if (r == 0 )break ;// (the file's end: the last aligned read is short) 136got += r ; 137if (r %kDirectAlign != 0 )break ; 138 } 139return got >=want ; 140#else 141const uint64_t a0 = off & ~(kDirectAlign - 1 ),need = direct_span (off ,n ),want = (off - a0 )+ n ; 142uint8_t * p = (uint8_t * )dst ; 143uint64_t got = 0 ; 144while (got < need ) { 145const ssize_t r = ::pread ((int )f ,p + got , (size_t ) std::min < uint64_t > (need - got ,1ull <<30 ), (off_t ) (a0 + got )); 146if (r < 0 )return false; 147if (r == 0 )break ;// (the file's end: the last aligned read is short) 148got += (uint64_t )r ; 149if ((uint64_t )r %kDirectAlign != 0 )break ; 150 } 151return 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 ; 159return false; 160#else 161 std::vector < iovec > iov ((size_t )n ); 162for (int i = 0 ;i < n ;++ i )iov [(size_t )i ]= iovec {bufs [i ], (size_t )lens [i ]}; 163uint64_t got = 0 ; 164size_t first = 0 ; 165while (got < want && first < iov .size ()) {// (a short read ends on a 512-byte boundary: the rest from there) 166const ssize_t r = ::preadv ((int )f ,iov .data ()+ first , (int ) (iov .size ()- first ), (off_t ) (off + got )); 167if (r <=0 || r %512 != 0 )return got + (uint64_t ) std::max < ssize_t > (r ,0 ) >=want ; 168got += (uint64_t )r ; 169for (uint64_t k = (uint64_t )r ;k > 0 && first < iov .size ();) { 170const uint64_t t = std::min < uint64_t > (k ,iov [first ].iov_len ); 171iov [first ].iov_base = (uint8_t * )iov [first ].iov_base + t ; 172iov [first ].iov_len -= t ; 173k -= t ; 174if (iov [first ].iov_len == 0 )++ first ; 175 } 176 } 177return 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 ) 184HANDLE h = CreateFileW (wide (path ).c_str (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 185FILE_ATTRIBUTE_NORMAL |FILE_FLAG_NO_BUFFERING ,nullptr ); 186return h == INVALID_HANDLE_VALUE ?kBadFd : (fd_t )h ; 187#else 188 (void )path ; 189return 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 ) 196const uint64_t a0 = off & ~(kDirectAlign - 1 ),span = direct_span (off ,n ); 197OVERLAPPED ov {}; 198ov .Offset = (DWORD )a0 ; 199ov .OffsetHigh = (DWORD ) (a0 >>32 ); 200DWORD got = 0 ; 201return ReadFile ((HANDLE )f ,buf , (DWORD )span ,& got ,& ov )&& got >= (off - a0 )+ n ; 202#else 203 (void )f , (void )buf , (void )n , (void )off ; 204return 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 ) 211HANDLE h = CreateFileW (wide (path ).c_str (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 212FILE_ATTRIBUTE_NORMAL |FILE_FLAG_OVERLAPPED ,nullptr ); 213return h == INVALID_HANDLE_VALUE ?kBadFd : (fd_t )h ; 214#else 215const int fd = ::open (path .c_str (),O_RDONLY ); 216return 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 ) 222struct Ev {// (each thread its own, closed when it ends) 223HANDLE h = CreateEventW (nullptr , TRUE, FALSE,nullptr ); 224 ~Ev () { 225if (h != nullptr )CloseHandle (h ); 226 } 227 }; 228static thread_localEv ev ; 229if (ev .h == nullptr )return false; 230uint8_t * p = (uint8_t * )dst ; 231while (n > 0 ) { 232const DWORD want = (DWORD ) std::min < uint64_t > (n ,1ull <<30 ); 233OVERLAPPED ov {}; 234ov .Offset = (DWORD ) (off & 0xffffffffu ); 235ov .OffsetHigh = (DWORD ) (off >>32 ); 236ov .hEvent = ev .h ; 237ResetEvent (ev .h ); 238DWORD got = 0 ; 239if (!ReadFile ((HANDLE )f ,p ,want ,nullptr ,& ov )&& GetLastError ()!= ERROR_IO_PENDING )return false; 240if (!GetOverlappedResult ((HANDLE )f ,& ov ,& got , TRUE)|| got == 0 )return false; 241p += got ,off += got ,n -= got ; 242 } 243return true; 244#else 245uint8_t * p = (uint8_t * )dst ; 246while (n > 0 ) { 247const ssize_t r = ::pread ((int )f ,p , (size_t ) std::min < uint64_t > (n ,1ull <<30 ), (off_t )off ); 248if (r <=0 )return false; 249p += r ,off += (uint64_t )r ,n -= (uint64_t )r ; 250 } 251return 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 ) 258return MoveFileExW (wide (from ).c_str (),wide (to ).c_str (),MOVEFILE_REPLACE_EXISTING |MOVEFILE_WRITE_THROUGH )!= 0 ; 259#else 260return std::rename (from .c_str (),to .c_str ())== 0 ; 261#endif 262} 263inline void close_fd (fd_t f ) { 264if (f == kBadFd )return ; 265#if defined(_WIN32 ) 266CloseHandle ((HANDLE )f ); 267#else 268 ::close ((int )f ); 269#endif 270} 271inline uint64_t file_size (fd_t f ) { 272#if defined(_WIN32 ) 273LARGE_INTEGER sz {}; 274return GetFileSizeEx ((HANDLE )f ,& sz ) ? (uint64_t )sz .QuadPart :0 ; 275#else 276struct stat sb ; 277return ::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 ) { 282uint8_t * p = (uint8_t * )dst ; 283while (n > 0 ) { 284const uint64_t want = std::min < uint64_t > (n ,1ull <<30 ); 285#if defined(_WIN32 ) 286OVERLAPPED ov {}; 287ov .Offset = (DWORD ) (off & 0xffffffffu ); 288ov .OffsetHigh = (DWORD ) (off >>32 ); 289DWORD got = 0 ; 290if (!ReadFile ((HANDLE )f ,p , (DWORD )want ,& got ,& ov )|| got == 0 )return false; 291const uint64_t r = got ; 292#else 293const ssize_t rr = ::pread ((int )f ,p , (size_t )want , (off_t )off ); 294if (rr <=0 )return false; 295const uint64_t r = (uint64_t )rr ; 296#endif 297p += r ,off += r ,n -= r ; 298 } 299return true; 300} 301/// The whole file mapped read-only (nullptr: it could not be). 302inline void * map_ro (fd_t f ,uint64_t bytes ) { 303if (bytes == 0 )return nullptr ; 304#if defined(_WIN32 ) 305HANDLE m = CreateFileMappingW ((HANDLE )f ,nullptr ,PAGE_READONLY ,0 ,0 ,nullptr ); 306if (m == nullptr )return nullptr ; 307void * v = MapViewOfFile (m ,FILE_MAP_READ ,0 ,0 ,0 ); 308CloseHandle (m );// (the view keeps the mapping) 309return v ; 310#else 311void * p = ::mmap (nullptr , (size_t )bytes ,PROT_READ ,MAP_SHARED , (int )f ,0 ); 312return p == MAP_FAILED ?nullptr :p ; 313#endif 314} 315inline void unmap (void * p ,uint64_t bytes ) { 316if (p == nullptr )return ; 317#if defined(_WIN32 ) 318 (void )bytes ; 319UnmapViewOfFile (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 330posix_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 ) { 338if (ranges .empty ())return ; 339#if defined(_WIN32 ) 340 std::vector < WIN32_MEMORY_RANGE_ENTRY > r (ranges .size ()); 341for (size_t i = 0 ;i < ranges .size ();++ i ) { 342r [i ].VirtualAddress = const_cast < void *> (ranges [i ].first ); 343r [i ].NumberOfBytes = ranges [i ].second ; 344 } 345PrefetchVirtualMemory (GetCurrentProcess (), (ULONG_PTR )r .size (),r .data (),0 ); 346#else 347const uintptr_t pg = 4096 ; 348for (const auto & x :ranges ) { 349const uintptr_t a = (uintptr_t )x .first ,b = a & ~(pg - 1 ); 350madvise ((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 ; 360return false; 361#else 362const uintptr_t pg = 4096 ,a = (uintptr_t )p ,b = a & ~(pg - 1 ); 363const size_t len = n + (a - b ),np = (len + pg - 1 ) /pg ; 364 thread_local std::vector < unsigned char > v ; 365if (v .size ()< np )v .resize (np ); 366if (mincore ((void * )b ,len ,v .data ())!= 0 )return false; 367for (size_t i = 0 ;i < np ;++ i ) 368if ((v [i ]& 1 )== 0 )return false; 369return 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 ) { 379if (bytes == 0 )return true; 380const uintptr_t pg = 4096 ,a = (uintptr_t )p ,span = bytes - 1 ; 381samples = std::max (1 , std::min (samples ,16 )); 382#if defined(_WIN32 ) 383PSAPI_WORKING_SET_EX_INFORMATION w [16 ]= {}; 384for (int i = 0 ;i < samples ;++ i ) 385w [i ].VirtualAddress = (PVOID ) ((a + (samples > 1 ?span / (samples - 1 )* i :0 ))& ~(pg - 1 )); 386if (!K32QueryWorkingSetEx (GetCurrentProcess (),w , (DWORD ) (samples * sizeof w [0 ])))return false; 387for (int i = 0 ;i < samples ;++ i ) 388if (!w [i ].VirtualAttributes .Valid )return false; 389return true; 390#else 391for (int i = 0 ;i < samples ;++ i ) { 392unsigned char v = 0 ; 393const uintptr_t at = (a + (samples > 1 ?span / (samples - 1 )* i :0 ))& ~(pg - 1 ); 394if (mincore ((void * )at ,pg ,& v )!= 0 || !(v & 1 ))return false; 395 } 396return 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 ) 404static const bool all = [] {// (DS4_PF_ALL=1: every range, as before) 405const char * v = std::getenv ("DS4_PF_ALL" ); 406return v != nullptr && std::atoi (v )!= 0 ; 407 }(); 408if (all )return prefetch (ranges ); 409 std::vector < std::pair < const void * ,size_t >> cold ; 410for (const auto & x :ranges ) 411if (!resident_sampled (x .first ,x .second ))cold .push_back (x ); 412prefetch (cold ); 413#else 414prefetch (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 ) 422return resident_sampled (p ,n ,8 ); 423#else 424return 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 ) 432if (node >=0 && nodes > 1 ) 433return VirtualAllocExNuma (GetCurrentProcess (),nullptr ,bytes ,MEM_RESERVE |MEM_COMMIT ,PAGE_READWRITE , 434 (DWORD )node ); 435return VirtualAlloc (nullptr ,bytes ,MEM_RESERVE |MEM_COMMIT ,PAGE_READWRITE ); 436#else 437void * m = ::mmap (nullptr ,bytes ,PROT_READ |PROT_WRITE ,MAP_PRIVATE |MAP_ANONYMOUS ,-1 ,0 ); 438if (m == MAP_FAILED )return nullptr ; 439madvise (m ,bytes ,MADV_HUGEPAGE ); 440if (node >=0 && nodes > 1 ) { 441unsigned long mask [4 ]= {0 ,0 ,0 ,0 }; 442mask [node /64 ]= 1ul << (node %64 ); 443syscall (SYS_mbind ,m ,bytes ,2 /* MPOL_BIND */ ,mask ,256 ,0 ); 444 } 445return 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 ) 452return VirtualAlloc (nullptr ,bytes ,MEM_RESERVE ,PAGE_READWRITE ); 453#else 454void * m = ::mmap (nullptr ,bytes ,PROT_NONE ,MAP_PRIVATE |MAP_ANONYMOUS |MAP_NORESERVE ,-1 ,0 ); 455return m == MAP_FAILED ?nullptr :m ; 456#endif 457} 458inline bool range_commit (void * p ,size_t bytes ) { 459#if defined(_WIN32 ) 460return VirtualAlloc (p ,bytes ,MEM_COMMIT ,PAGE_READWRITE )!= nullptr ; 461#else 462return ::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 ) 468VirtualFree (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 ) { 475if (p == nullptr )return ; 476#if defined(_WIN32 ) 477 (void )bytes ; 478VirtualFree (p ,0 ,MEM_RELEASE ); 479#else 480 ::munmap (p ,bytes ); 481#endif 482} 483inline void anon_free (void * p ,size_t bytes ) { 484if (p == nullptr )return ; 485#if defined(_WIN32 ) 486 (void )bytes ; 487VirtualFree (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 ) 496if (cpu >=0 && cpu < 64 )SetThreadAffinityMask (GetCurrentThread (), (DWORD_PTR )1 <<cpu ); 497#else 498cpu_set_t set ; 499CPU_ZERO (& set ); 500CPU_SET (cpu ,& set ); 501sched_setaffinity (0 ,sizeof set ,& set ); 502#endif 503} 504inline void pin_thread (std::thread & t ,int cpu ) { 505#if defined(_WIN32 ) 506if (cpu >=0 && cpu < 64 )SetThreadAffinityMask ((HANDLE )t .native_handle (), (DWORD_PTR )1 <<cpu ); 507#else 508cpu_set_t set ; 509CPU_ZERO (& set ); 510CPU_SET (cpu ,& set ); 511pthread_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 ; 520auto query = [](LOGICAL_PROCESSOR_RELATIONSHIP rel , std::vector < uint8_t >& buf ) { 521DWORD len = 0 ; 522GetLogicalProcessorInformationEx (rel ,nullptr ,& len ); 523buf .resize (len ); 524return len > 0 && GetLogicalProcessorInformationEx (rel , (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX )buf .data (),& len ); 525 }; 526 std::vector < uint8_t > nb ,cb ; 527if (!query (RelationNumaNode ,nb )|| !query (RelationProcessorCore ,cb ))return nodes ; 528 std::vector < KAFFINITY > masks ; 529for (size_t o = 0 ;o < nb .size ();) { 530auto * e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX ) (nb .data ()+ o ); 531if (e -> NumaNode .GroupMask .Group == 0 )masks .push_back (e -> NumaNode .GroupMask .Mask ); 532o += e -> Size ; 533 } 534nodes .resize (masks .size ()); 535for (size_t o = 0 ;o < cb .size ();) { 536auto * e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX ) (cb .data ()+ o ); 537if (e -> Processor .GroupCount > 0 && e -> Processor .GroupMask [0 ].Group == 0 ) { 538const KAFFINITY m = e -> Processor .GroupMask [0 ].Mask ; 539int first = -1 ; 540for (int b = 0 ;b < 64 ;++ b ) 541if ((m >>b )& 1 ) { 542first = b ; 543break ; 544 } 545for (size_t n = 0 ;n < masks .size ()&& first >=0 ;++ n ) 546if ((masks [n ] >>first )& 1 ) { 547nodes [n ].push_back (first ); 548if (smt ) 549for (int b = first + 1 ;b < 64 ;++ b ) 550if ((m >>b )& 1 )nodes [n ].push_back (b ); 551 } 552 } 553o += e -> Size ; 554 } 555nodes .erase (std::remove_if (nodes .begin (),nodes .end (), [](const std::vector < int >& v ) {return v .empty (); }), 556nodes .end ()); 557for (auto & v :nodes ) std::sort (v .begin (),v .end ()); 558return nodes ; 559} 560/// The RAM this process can still get (~0: not known). 561inline uint64_t ram_avail () { 562MEMORYSTATUSEX s {}; 563s .dwLength = sizeof (s ); 564return 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 { 572uint64_t limit = ~uint64_t {0 },avail = ~uint64_t {0 },ram = ~uint64_t {0 }; 573}; 574inline Commit commit () { 575Commit c ; 576#if defined(_WIN32 ) 577MEMORYSTATUSEX s {}; 578s .dwLength = sizeof (s ); 579if (GlobalMemoryStatusEx (& s )) { 580c .limit = (uint64_t )s .ullTotalPageFile ; 581c .avail = (uint64_t )s .ullAvailPageFile ; 582c .ram = (uint64_t )s .ullTotalPhys ; 583 } 584#endif 585return c ; 586} 587 588}// namespace strata::ds4::os