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