okami.mom/strata

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

Niko1221Merge f-park-pool ef371eba8 into f-p4-inta46c667cc

main
2.4 KiB86 linesraw
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)
21    struct rusage ru;
22    if (getrusage(RUSAGE_THREAD, &ru) == 0) return ru.ru_minflt;
23#endif
24    return 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");
31    if (!f) return -1;
32    char line[256];
33    long kb = -1;
34    while (std::fgets(line, sizeof line, f))
35        if (std::strncmp(line, "AnonHugePages:", 14) == 0) { kb = std::atol(line + 14); break; }
36    std::fclose(f);
37    return kb;
38#else
39    return -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__)
47    if (std::FILE* f = std::fopen(path, "r")) {
48        char line[256];
49        if (std::fgets(line, sizeof line, f)) {
50            out = line;
51            while (!out.empty() && (out.back() == '\n' || out.back() == '\r')) out.pop_back();
52        }
53        std::fclose(f);
54    }
55#else
56    (void) path;
57#endif
58    return out;
59}
60
61inline long page_size() {
62#if defined(__linux__)
63    return (long) ::sysconf(_SC_PAGESIZE);
64#else
65    return 0;
66#endif
67}
68inline const void* brk_end() {
69#if defined(__linux__)
70    return ::sbrk(0);
71#else
72    return 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__)
79    return (const char*) p < (const char*) ::sbrk(0) ? "brk" : "map";
80#else
81    (void) p;
82    return "?";
83#endif
84}
85
86}  // namespace strata::core::conversation_trace