okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a46c667cc
main
1#pragma once 2// STRATA_PARK_TRACE helpers (diagnostics only, nothing here changes what the engine does): minor page faults of the 3// calling thread, the process's AnonHugePages, THP settings, and where a buffer sits relative to the C heap. Read by 4// the park trace lines in conversation_state.cpp / conversation_snapshot.cpp. Linux only; elsewhere every figure is 0. 5#include <cstdint> 6#include <cstdio> 7#include <cstdlib> 8#include <cstring> 9#include <string> 10 11#if defined(__linux__ ) 12#include <sys/resource.h> 13#include <unistd.h> 14#endif 15 16namespace strata::core::conversation_trace { 17 18/// Minor page faults taken by the calling thread so far (a 4 KiB first touch is one; a 2 MiB huge page is one) 19inline long thread_minflt () { 20#if defined(__linux__ )&& defined(RUSAGE_THREAD ) 21struct rusage ru ; 22if (getrusage (RUSAGE_THREAD ,& ru )== 0 )return ru .ru_minflt ; 23#endif 24return 0 ; 25} 26 27/// AnonHugePages of this process in kB (from /proc/self/smaps_rollup), -1 when it cannot be read 28inline long anon_huge_kb () { 29#if defined(__linux__ ) 30 std::FILE * f = std::fopen ("/proc/self/smaps_rollup" ,"r" ); 31if (!f )return -1 ; 32char line [256 ]; 33long kb = -1 ; 34while (std::fgets (line ,sizeof line ,f )) 35if (std::strncmp (line ,"AnonHugePages:" ,14 )== 0 ) {kb = std::atol (line + 14 );break ; } 36 std::fclose (f ); 37return kb ; 38#else 39return -1 ; 40#endif 41} 42 43/// The first line of a /sys file ("always [madvise] never"), "?" when it cannot be read 44inline std::string sys_line (const char * path ) { 45 std::string out = "?" ; 46#if defined(__linux__ ) 47if (std::FILE * f = std::fopen (path ,"r" )) { 48char line [256 ]; 49if (std::fgets (line ,sizeof line ,f )) { 50out = line ; 51while (!out .empty ()&& (out .back ()== '\n' || out .back ()== '\r' ))out .pop_back (); 52 } 53 std::fclose (f ); 54 } 55#else 56 (void )path ; 57#endif 58return out ; 59} 60 61inline long page_size () { 62#if defined(__linux__ ) 63return (long ) ::sysconf (_SC_PAGESIZE ); 64#else 65return 0 ; 66#endif 67} 68inline const void * brk_end () { 69#if defined(__linux__ ) 70return ::sbrk (0 ); 71#else 72return nullptr ; 73#endif 74} 75 76/// Where `p` sits against the C heap's break: "brk" below sbrk(0) (the main heap), "map" above it (a mapping) 77inline const char * where (const void * p ) { 78#if defined(__linux__ ) 79return (const char * )p < (const char * ) ::sbrk (0 ) ?"brk" :"map" ; 80#else 81 (void )p ; 82return "?" ; 83#endif 84} 85 86}// namespace strata::core::conversation_trace