From f5d2cd9b85e9cdbe8fe20c962810e3141ccd08fb Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 16:54:10 +0000 Subject: [PATCH 01/33] elfhacks: define ElfW() when libc does not provide it --- include/elfhacks.h | 9 +++++++++ mangohud-next/client/elfhacks.h | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/include/elfhacks.h b/include/elfhacks.h index 4fdbfe3c12..1f4b037580 100644 --- a/include/elfhacks.h +++ b/include/elfhacks.h @@ -46,6 +46,15 @@ extern "C" { # define __elf32 #endif +/* glibc provides ElfW() in , other libcs do not */ +#ifndef ElfW +# ifdef __elf64 +# define ElfW(type) Elf64_##type +# else +# define ElfW(type) Elf32_##type +# endif +#endif + #ifdef __elf64 # define ELFW_R_SYM ELF64_R_SYM # define ElfW_Sword Elf64_Sxword diff --git a/mangohud-next/client/elfhacks.h b/mangohud-next/client/elfhacks.h index 4fdbfe3c12..1f4b037580 100644 --- a/mangohud-next/client/elfhacks.h +++ b/mangohud-next/client/elfhacks.h @@ -46,6 +46,15 @@ extern "C" { # define __elf32 #endif +/* glibc provides ElfW() in , other libcs do not */ +#ifndef ElfW +# ifdef __elf64 +# define ElfW(type) Elf64_##type +# else +# define ElfW(type) Elf32_##type +# endif +#endif + #ifdef __elf64 # define ELFW_R_SYM ELF64_R_SYM # define ElfW_Sword Elf64_Sxword From fc5f1eb22be6726e9e9e9261858a7ab2cc69aca2 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 20:37:03 +0000 Subject: [PATCH 02/33] overlay_params: don't require std::atomic from the standard library --- src/overlay_params.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/overlay_params.cpp b/src/overlay_params.cpp index f7265285e0..f4cbb401ab 100644 --- a/src/overlay_params.cpp +++ b/src/overlay_params.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -49,7 +50,24 @@ std::unique_ptr fpsmetrics; std::mutex config_mtx; std::condition_variable config_cv; bool config_ready = false; + +#ifdef __cpp_lib_atomic_shared_ptr static std::atomic> g_params; +#else +// Not every standard library implements std::atomic> (e.g. libc++) +class AtomicParams { +public: + void store(std::shared_ptr p, std::memory_order order = std::memory_order_seq_cst) { + std::atomic_store_explicit(&ptr, std::move(p), order); + } + std::shared_ptr load(std::memory_order order = std::memory_order_seq_cst) const { + return std::atomic_load_explicit(&ptr, order); + } +private: + std::shared_ptr ptr; +}; +static AtomicParams g_params; +#endif std::shared_ptr fps_limiter; #if __cplusplus >= 201703L From 30fc26786cd0d9cfdb52612891bddda20757e66f Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 16:56:57 +0000 Subject: [PATCH 03/33] file_utils: split process introspection into per-platform files --- src/file_utils.cpp | 51 +++++++--------------------------- src/file_utils.h | 10 +++++-- src/file_utils_linux.cpp | 59 ++++++++++++++++++++++++++++++++++++++++ src/meson.build | 1 + 4 files changed, 78 insertions(+), 43 deletions(-) create mode 100644 src/file_utils_linux.cpp diff --git a/src/file_utils.cpp b/src/file_utils.cpp index 2b67a64875..1690a9a0bf 100644 --- a/src/file_utils.cpp +++ b/src/file_utils.cpp @@ -6,14 +6,11 @@ #include #include #include +#include #include #include #include -#ifndef PROCDIR -#define PROCDIR "/proc" -#endif - std::string read_line(const std::string& filename) { std::string line; @@ -36,7 +33,7 @@ std::string get_basename(const std::string&& path) return path; } -#ifdef __linux__ +#ifndef _WIN32 std::vector ls(const char* root, const char* prefix, LS_FLAGS flags) { std::vector list; @@ -110,28 +107,27 @@ std::string read_symlink(const std::string&& link) return read_symlink(link.c_str()); } -std::string get_exe_path() -{ - return read_symlink(PROCDIR "/self/exe"); -} - std::string get_wine_exe_name(bool keep_ext) { const std::string exe_path = get_exe_path(); - if (!ends_with(exe_path, "wine-preloader") && !ends_with(exe_path, "wine64-preloader")) { + if (!is_wine_loader(get_basename(std::string(exe_path)))) { return std::string(); } - std::string line = read_line(PROCDIR "/self/comm"); // max 16 characters though + std::string line = get_proc_comm(); // max 16 characters though if (ends_with(line, ".exe", true)) { auto dot = keep_ext ? std::string::npos : line.find_last_of('.'); return line.substr(0, dot); } - std::ifstream cmdline(PROCDIR "/self/cmdline"); + std::istringstream cmdline(get_proc_cmdline()); // Iterate over arguments (separated by NUL byte). while (std::getline(cmdline, line, '\0')) { + // skip the Wine loader itself + if (is_wine_loader(get_basename(std::string(line)))) + continue; + auto n = std::string::npos; if (!line.empty() && ((n = line.find_last_of("/\\")) != std::string::npos) @@ -185,33 +181,6 @@ std::string get_config_dir() return path; } -bool lib_loaded(const std::string& lib, pid_t pid) { - - std::string who = pid != -1 ? std::to_string(pid) : "self"; - auto paths = { fs::path("/proc") / who / "map_files", - fs::path("/proc") / who / "fd" }; - for (const auto& path : paths) { - try { - std::error_code iterator_ec; - for (fs::directory_iterator it(path, iterator_ec), end; - !iterator_ec && it != end; it.increment(iterator_ec)) { - const auto& p = *it; - auto file = p.path().string(); - auto sym = read_symlink(file.c_str()); - if (to_lower(sym).find(lib) != std::string::npos) { - return true; - } - } - if (iterator_ec) - SPDLOG_DEBUG("Failed to iterate {}: {}", fs::path(path).string(), iterator_ec.message()); - } - catch (const fs::filesystem_error& e) { - SPDLOG_DEBUG("failed to iterate {}: {}", path.string(), e.what()); - } - } - return false; -} - std::string remove_parentheses(const std::string& text) { // Remove parentheses and text between them std::regex pattern("\\([^)]*\\)"); @@ -225,4 +194,4 @@ std::string to_lower(const std::string& str) { return lowered; } -#endif // __linux__ +#endif // !_WIN32 diff --git a/src/file_utils.h b/src/file_utils.h index 864f0b02fa..180800e1fa 100644 --- a/src/file_utils.h +++ b/src/file_utils.h @@ -22,12 +22,18 @@ bool dir_exists(const std::string& path); std::string read_symlink(const char * link); std::string read_symlink(const std::string&& link); std::string get_basename(const std::string&& path); //prefix so it doesn't conflict libgen -std::string get_exe_path(); std::string get_wine_exe_name(bool keep_ext = false); std::string get_home_dir(); std::string get_data_dir(); std::string get_config_dir(); -bool lib_loaded(const std::string& lib, pid_t pid); + +// Per-platform, implemented in file_utils_.cpp +std::string get_exe_path(); +std::string get_proc_comm(); // process name, 15-16 characters at most +std::string get_proc_cmdline(); // arguments separated by NUL bytes +bool is_wine_loader(const std::string& name); // name of the executable, not the path +bool lib_loaded(const std::string& lib, pid_t pid); // pid -1 is this process + std::string remove_parentheses(const std::string&); std::string to_lower(const std::string& str); diff --git a/src/file_utils_linux.cpp b/src/file_utils_linux.cpp new file mode 100644 index 0000000000..b8f32ee30d --- /dev/null +++ b/src/file_utils_linux.cpp @@ -0,0 +1,59 @@ +#include "file_utils.h" +#include "string_utils.h" +#include +#include +#include + +#ifndef PROCDIR +#define PROCDIR "/proc" +#endif + +std::string get_exe_path() +{ + return read_symlink(PROCDIR "/self/exe"); +} + +std::string get_proc_comm() +{ + return read_line(PROCDIR "/self/comm"); +} + +std::string get_proc_cmdline() +{ + std::ifstream file(PROCDIR "/self/cmdline"); + std::stringstream ss; + ss << file.rdbuf(); + return ss.str(); +} + +bool is_wine_loader(const std::string& name) +{ + return ends_with(name, "wine-preloader") || ends_with(name, "wine64-preloader"); +} + +bool lib_loaded(const std::string& lib, pid_t pid) { + + std::string who = pid != -1 ? std::to_string(pid) : "self"; + auto paths = { fs::path("/proc") / who / "map_files", + fs::path("/proc") / who / "fd" }; + for (const auto& path : paths) { + try { + std::error_code iterator_ec; + for (fs::directory_iterator it(path, iterator_ec), end; + !iterator_ec && it != end; it.increment(iterator_ec)) { + const auto& p = *it; + auto file = p.path().string(); + auto sym = read_symlink(file.c_str()); + if (to_lower(sym).find(lib) != std::string::npos) { + return true; + } + } + if (iterator_ec) + SPDLOG_DEBUG("Failed to iterate {}: {}", fs::path(path).string(), iterator_ec.message()); + } + catch (const fs::filesystem_error& e) { + SPDLOG_DEBUG("failed to iterate {}: {}", path.string(), e.what()); + } + } + return false; +} diff --git a/src/meson.build b/src/meson.build index 77f9b95ce3..b2cd30be33 100644 --- a/src/meson.build +++ b/src/meson.build @@ -77,6 +77,7 @@ endif if is_unixy vklayer_files += files( + 'file_utils_linux.cpp', 'cpu.cpp', 'memory.cpp', 'iostats.cpp', From ab53931b70ac3795d5d9bbcde5cac78d0cb2f7d9 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 17:14:28 +0000 Subject: [PATCH 04/33] cpu: share tick accounting between platforms --- src/cpu.cpp | 91 -------------------------------------------- src/cpu.h | 16 +++++++- src/cpu_common.cpp | 94 ++++++++++++++++++++++++++++++++++++++++++++++ src/meson.build | 1 + 4 files changed, 110 insertions(+), 92 deletions(-) create mode 100644 src/cpu_common.cpp diff --git a/src/cpu.cpp b/src/cpu.cpp index 559fa18160..b5aa9e4932 100644 --- a/src/cpu.cpp +++ b/src/cpu.cpp @@ -36,91 +36,6 @@ #include "file_utils.h" -static void calculateCPUData(CPUData& cpuData, - unsigned long long int usertime, - unsigned long long int nicetime, - unsigned long long int systemtime, - unsigned long long int idletime, - unsigned long long int ioWait, - unsigned long long int irq, - unsigned long long int softIrq, - unsigned long long int steal, - unsigned long long int guest, - unsigned long long int guestnice) -{ - // Guest time is already accounted in usertime - usertime = usertime - guest; - nicetime = nicetime - guestnice; - // Fields existing on kernels >= 2.6 - // (and RHEL's patched kernel 2.4...) - unsigned long long int idlealltime = idletime + ioWait; - unsigned long long int systemalltime = systemtime + irq + softIrq; - unsigned long long int virtalltime = guest + guestnice; - unsigned long long int totaltime = usertime + nicetime + systemalltime + idlealltime + steal + virtalltime; - - // Since we do a subtraction (usertime - guest) and cputime64_to_clock_t() - // used in /proc/stat rounds down numbers, it can lead to a case where the - // integer overflow. - #define WRAP_SUBTRACT(a,b) (a > b) ? a - b : 0 - cpuData.userPeriod = WRAP_SUBTRACT(usertime, cpuData.userTime); - cpuData.nicePeriod = WRAP_SUBTRACT(nicetime, cpuData.niceTime); - cpuData.systemPeriod = WRAP_SUBTRACT(systemtime, cpuData.systemTime); - cpuData.systemAllPeriod = WRAP_SUBTRACT(systemalltime, cpuData.systemAllTime); - cpuData.idleAllPeriod = WRAP_SUBTRACT(idlealltime, cpuData.idleAllTime); - cpuData.idlePeriod = WRAP_SUBTRACT(idletime, cpuData.idleTime); - cpuData.ioWaitPeriod = WRAP_SUBTRACT(ioWait, cpuData.ioWaitTime); - cpuData.irqPeriod = WRAP_SUBTRACT(irq, cpuData.irqTime); - cpuData.softIrqPeriod = WRAP_SUBTRACT(softIrq, cpuData.softIrqTime); - cpuData.stealPeriod = WRAP_SUBTRACT(steal, cpuData.stealTime); - cpuData.guestPeriod = WRAP_SUBTRACT(virtalltime, cpuData.guestTime); - cpuData.totalPeriod = WRAP_SUBTRACT(totaltime, cpuData.totalTime); - #undef WRAP_SUBTRACT - cpuData.userTime = usertime; - cpuData.niceTime = nicetime; - cpuData.systemTime = systemtime; - cpuData.systemAllTime = systemalltime; - cpuData.idleAllTime = idlealltime; - cpuData.idleTime = idletime; - cpuData.ioWaitTime = ioWait; - cpuData.irqTime = irq; - cpuData.softIrqTime = softIrq; - cpuData.stealTime = steal; - cpuData.guestTime = virtalltime; - cpuData.totalTime = totaltime; - - if (cpuData.totalPeriod == 0) - return; - float total = (float)cpuData.totalPeriod; - float v[4]; - v[0] = cpuData.nicePeriod * 100.0f / total; - v[1] = cpuData.userPeriod * 100.0f / total; - - /* if not detailed */ - v[2] = cpuData.systemAllPeriod * 100.0f / total; - v[3] = (cpuData.stealPeriod + cpuData.guestPeriod) * 100.0f / total; - //cpuData.percent = std::clamp(v[0]+v[1]+v[2]+v[3], 0.0f, 100.0f); - cpuData.percent = std::min(std::max(v[0]+v[1]+v[2]+v[3], 0.0f), 100.0f); -} - -CPUStats::CPUStats() -{ -} - -CPUStats::~CPUStats() -{ - if (m_cpuTempFile) { - fclose(m_cpuTempFile); - m_cpuTempFile = nullptr; - } - for (auto file : m_cpuTempFiles) - fclose(file); - m_cpuTempFiles.clear(); - if (m_platformFanFile) { - fclose(m_platformFanFile); - m_platformFanFile = nullptr; - } -} - bool CPUStats::Init() { if (m_inited) @@ -175,12 +90,6 @@ bool CPUStats::Init() return UpdateCPUData(); } -bool CPUStats::Reinit() -{ - m_inited = false; - return Init(); -} - //TODO take sampling interval into account? bool CPUStats::UpdateCPUData() { diff --git a/src/cpu.h b/src/cpu.h index d904f4a9e8..5141b90756 100644 --- a/src/cpu.h +++ b/src/cpu.h @@ -51,6 +51,19 @@ typedef struct CPUData_ { std::string label = "unknown"; } CPUData; +// Fills the per-interval fields of cpuData from cumulative tick counters +void calculateCPUData(CPUData& cpuData, + unsigned long long int usertime, + unsigned long long int nicetime, + unsigned long long int systemtime, + unsigned long long int idletime, + unsigned long long int ioWait, + unsigned long long int irq, + unsigned long long int softIrq, + unsigned long long int steal, + unsigned long long int guest, + unsigned long long int guestnice); + enum { CPU_POWER_K10TEMP, CPU_POWER_ZENPOWER, @@ -58,7 +71,8 @@ enum { CPU_POWER_RAPL, CPU_POWER_AMDGPU, CPU_POWER_XGENE, - CPU_POWER_DECKARD + CPU_POWER_DECKARD, + CPU_POWER_CPUCTL }; struct CPUPowerData { diff --git a/src/cpu_common.cpp b/src/cpu_common.cpp new file mode 100644 index 0000000000..f868a8b2c3 --- /dev/null +++ b/src/cpu_common.cpp @@ -0,0 +1,94 @@ +#include "cpu.h" +#include +#include + +void calculateCPUData(CPUData& cpuData, + unsigned long long int usertime, + unsigned long long int nicetime, + unsigned long long int systemtime, + unsigned long long int idletime, + unsigned long long int ioWait, + unsigned long long int irq, + unsigned long long int softIrq, + unsigned long long int steal, + unsigned long long int guest, + unsigned long long int guestnice) +{ + // Guest time is already accounted in usertime + usertime = usertime - guest; + nicetime = nicetime - guestnice; + // Fields existing on kernels >= 2.6 + // (and RHEL's patched kernel 2.4...) + unsigned long long int idlealltime = idletime + ioWait; + unsigned long long int systemalltime = systemtime + irq + softIrq; + unsigned long long int virtalltime = guest + guestnice; + unsigned long long int totaltime = usertime + nicetime + systemalltime + idlealltime + steal + virtalltime; + + // Since we do a subtraction (usertime - guest) and cputime64_to_clock_t() + // used in /proc/stat rounds down numbers, it can lead to a case where the + // integer overflow. + #define WRAP_SUBTRACT(a,b) (a > b) ? a - b : 0 + cpuData.userPeriod = WRAP_SUBTRACT(usertime, cpuData.userTime); + cpuData.nicePeriod = WRAP_SUBTRACT(nicetime, cpuData.niceTime); + cpuData.systemPeriod = WRAP_SUBTRACT(systemtime, cpuData.systemTime); + cpuData.systemAllPeriod = WRAP_SUBTRACT(systemalltime, cpuData.systemAllTime); + cpuData.idleAllPeriod = WRAP_SUBTRACT(idlealltime, cpuData.idleAllTime); + cpuData.idlePeriod = WRAP_SUBTRACT(idletime, cpuData.idleTime); + cpuData.ioWaitPeriod = WRAP_SUBTRACT(ioWait, cpuData.ioWaitTime); + cpuData.irqPeriod = WRAP_SUBTRACT(irq, cpuData.irqTime); + cpuData.softIrqPeriod = WRAP_SUBTRACT(softIrq, cpuData.softIrqTime); + cpuData.stealPeriod = WRAP_SUBTRACT(steal, cpuData.stealTime); + cpuData.guestPeriod = WRAP_SUBTRACT(virtalltime, cpuData.guestTime); + cpuData.totalPeriod = WRAP_SUBTRACT(totaltime, cpuData.totalTime); + #undef WRAP_SUBTRACT + cpuData.userTime = usertime; + cpuData.niceTime = nicetime; + cpuData.systemTime = systemtime; + cpuData.systemAllTime = systemalltime; + cpuData.idleAllTime = idlealltime; + cpuData.idleTime = idletime; + cpuData.ioWaitTime = ioWait; + cpuData.irqTime = irq; + cpuData.softIrqTime = softIrq; + cpuData.stealTime = steal; + cpuData.guestTime = virtalltime; + cpuData.totalTime = totaltime; + + if (cpuData.totalPeriod == 0) + return; + float total = (float)cpuData.totalPeriod; + float v[4]; + v[0] = cpuData.nicePeriod * 100.0f / total; + v[1] = cpuData.userPeriod * 100.0f / total; + + /* if not detailed */ + v[2] = cpuData.systemAllPeriod * 100.0f / total; + v[3] = (cpuData.stealPeriod + cpuData.guestPeriod) * 100.0f / total; + //cpuData.percent = std::clamp(v[0]+v[1]+v[2]+v[3], 0.0f, 100.0f); + cpuData.percent = std::min(std::max(v[0]+v[1]+v[2]+v[3], 0.0f), 100.0f); +} + +CPUStats::CPUStats() +{ +} + +CPUStats::~CPUStats() +{ + if (m_cpuTempFile) { + fclose(m_cpuTempFile); + m_cpuTempFile = nullptr; + } + for (auto file : m_cpuTempFiles) + fclose(file); + m_cpuTempFiles.clear(); + if (m_platformFanFile) { + fclose(m_platformFanFile); + m_platformFanFile = nullptr; + } +} + +bool CPUStats::Reinit() +{ + m_inited = false; + return Init(); +} diff --git a/src/meson.build b/src/meson.build index b2cd30be33..e157651d3e 100644 --- a/src/meson.build +++ b/src/meson.build @@ -79,6 +79,7 @@ if is_unixy vklayer_files += files( 'file_utils_linux.cpp', 'cpu.cpp', + 'cpu_common.cpp', 'memory.cpp', 'iostats.cpp', 'notify.cpp', From 0c47f0eef8a447b62f895931d35ecc52571def20 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 22:16:21 +0000 Subject: [PATCH 05/33] memory: move globals to a platform independent file --- src/memory.cpp | 5 ----- src/memory_common.cpp | 6 ++++++ src/meson.build | 1 + 3 files changed, 7 insertions(+), 5 deletions(-) create mode 100644 src/memory_common.cpp diff --git a/src/memory.cpp b/src/memory.cpp index eed8da4b3e..83331a11cc 100644 --- a/src/memory.cpp +++ b/src/memory.cpp @@ -13,11 +13,6 @@ #include "hud_elements.h" #include "string_utils.h" -float memused, memmax, swapused; -int mem_temp = -1; -uint64_t proc_mem_resident, proc_mem_shared, proc_mem_virt; -uint64_t cgroup_mem_used; - void update_meminfo() { std::ifstream file("/proc/meminfo"); std::map meminfo; diff --git a/src/memory_common.cpp b/src/memory_common.cpp new file mode 100644 index 0000000000..faeb52819d --- /dev/null +++ b/src/memory_common.cpp @@ -0,0 +1,6 @@ +#include "memory.h" + +float memused, memmax, swapused; +int mem_temp = -1; +uint64_t proc_mem_resident, proc_mem_shared, proc_mem_virt; +uint64_t cgroup_mem_used; diff --git a/src/meson.build b/src/meson.build index e157651d3e..94b4461f1a 100644 --- a/src/meson.build +++ b/src/meson.build @@ -81,6 +81,7 @@ if is_unixy 'cpu.cpp', 'cpu_common.cpp', 'memory.cpp', + 'memory_common.cpp', 'iostats.cpp', 'notify.cpp', 'elfhacks.c', From 51bd49144cfb13c4d5941d33560f1fe58c5981eb Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 22:19:50 +0000 Subject: [PATCH 06/33] iostats: split counter source into per-platform files --- src/iostats.cpp | 26 +------------------------- src/iostats.h | 4 ++++ src/iostats_linux.cpp | 32 ++++++++++++++++++++++++++++++++ src/meson.build | 1 + 4 files changed, 38 insertions(+), 25 deletions(-) create mode 100644 src/iostats_linux.cpp diff --git a/src/iostats.cpp b/src/iostats.cpp index 0da526b3e1..60836463b8 100644 --- a/src/iostats.cpp +++ b/src/iostats.cpp @@ -1,7 +1,4 @@ #include "iostats.h" -#include "string_utils.h" -#include -#include "hud_elements.h" struct iostats g_io_stats; @@ -12,29 +9,8 @@ void getIoStats(iostats& io) { io.prev.read_bytes = io.curr.read_bytes; io.prev.write_bytes = io.curr.write_bytes; - std::string f = "/proc/"; - - { - auto gs_pid = HUDElements.g_gamescopePid; - f += gs_pid < 1 ? "self" : std::to_string(gs_pid); - f += "/io"; - } - - std::ifstream file(f); - - if (!file.is_open()) { - SPDLOG_ERROR("can't open {}", f); + if (!read_io_counters(io.curr.read_bytes, io.curr.write_bytes)) return; - } - - for (std::string line; std::getline(file, line);) { - if (starts_with(line, "read_bytes:")) { - try_stoull(io.curr.read_bytes, line.substr(12)); - } - else if (starts_with(line, "write_bytes:")) { - try_stoull(io.curr.write_bytes, line.substr(13)); - } - } if (io.last_update.time_since_epoch().count()) { io.diff.read = (io.curr.read_bytes - io.prev.read_bytes) / (1024.f * 1024.f); diff --git a/src/iostats.h b/src/iostats.h index e1a18b2a4b..0e359d6b8b 100644 --- a/src/iostats.h +++ b/src/iostats.h @@ -28,4 +28,8 @@ struct iostats { extern iostats g_io_stats; void getIoStats(iostats& io); +// Cumulative bytes read and written by the process, per platform. Leaves the +// values alone and returns false when they can't be read. +bool read_io_counters(unsigned long long& read_bytes, unsigned long long& write_bytes); + #endif //MANGOHUD_IOSTATS_H diff --git a/src/iostats_linux.cpp b/src/iostats_linux.cpp new file mode 100644 index 0000000000..a4d8177247 --- /dev/null +++ b/src/iostats_linux.cpp @@ -0,0 +1,32 @@ +#include "iostats.h" +#include "string_utils.h" +#include +#include "hud_elements.h" + +bool read_io_counters(unsigned long long& read_bytes, unsigned long long& write_bytes) { + std::string f = "/proc/"; + + { + auto gs_pid = HUDElements.g_gamescopePid; + f += gs_pid < 1 ? "self" : std::to_string(gs_pid); + f += "/io"; + } + + std::ifstream file(f); + + if (!file.is_open()) { + SPDLOG_ERROR("can't open {}", f); + return false; + } + + for (std::string line; std::getline(file, line);) { + if (starts_with(line, "read_bytes:")) { + try_stoull(read_bytes, line.substr(12)); + } + else if (starts_with(line, "write_bytes:")) { + try_stoull(write_bytes, line.substr(13)); + } + } + + return true; +} diff --git a/src/meson.build b/src/meson.build index 94b4461f1a..2562048736 100644 --- a/src/meson.build +++ b/src/meson.build @@ -83,6 +83,7 @@ if is_unixy 'memory.cpp', 'memory_common.cpp', 'iostats.cpp', + 'iostats_linux.cpp', 'notify.cpp', 'elfhacks.c', '../mangohud-next/client/real_dlsym.c', From 8a4f972b63779315c199a51c91c7cd5de5baa69e Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 22:24:50 +0000 Subject: [PATCH 07/33] notify: split the file watcher backend into per-platform files --- src/meson.build | 1 + src/notify.cpp | 57 +++++++++++++------------------------------- src/notify.h | 13 ++++++++++ src/notify_linux.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+), 41 deletions(-) create mode 100644 src/notify_linux.cpp diff --git a/src/meson.build b/src/meson.build index 2562048736..7f87b7afe4 100644 --- a/src/meson.build +++ b/src/meson.build @@ -85,6 +85,7 @@ if is_unixy 'iostats.cpp', 'iostats_linux.cpp', 'notify.cpp', + 'notify_linux.cpp', 'elfhacks.c', '../mangohud-next/client/real_dlsym.c', 'pci_ids.cpp', diff --git a/src/notify.cpp b/src/notify.cpp index 2d0f5b0fa9..690de89c2d 100644 --- a/src/notify.cpp +++ b/src/notify.cpp @@ -1,41 +1,26 @@ #include -#include -#include -#include -#include +#include #include #include "config.h" #include "notify.h" -#define EVENT_SIZE ( sizeof (struct inotify_event) ) -#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) - static void fileChanged(notify_thread *nt) { - int length, i = 0; - char buffer[EVENT_BUF_LEN]; overlay_params local_params = *nt->params; while (!nt->quit.load()) { - length = read( nt->fd, buffer, EVENT_BUF_LEN ); - while (i < length) { - struct inotify_event *event = - (struct inotify_event *) &buffer[i]; - i += EVENT_SIZE + event->len; - if (event->mask & IN_MODIFY || event->mask & IN_DELETE_SELF) { - // In the case of IN_DELETE_SELF, some editors may do a save-to-temp-file/delete-original/move-temp-file - // so sleep a little to let file to be replaced - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - parse_overlay_config(&local_params, getenv("MANGOHUD_CONFIG"), false); - if ((event->mask & IN_DELETE_SELF) || (nt->params->config_file_path != local_params.config_file_path)) { - SPDLOG_DEBUG("Watching config file: {}", local_params.config_file_path.c_str()); - inotify_rm_watch(nt->fd, nt->wd); - nt->wd = inotify_add_watch(nt->fd, local_params.config_file_path.c_str(), IN_MODIFY | IN_DELETE_SELF); - } - std::lock_guard lk(nt->mutex); - *nt->params = local_params; + const unsigned events = notify_poll(*nt); + if (events) { + // With NOTIFY_REMOVED, some editors may do a save-to-temp-file/delete-original/move-temp-file + // so sleep a little to let file to be replaced + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + parse_overlay_config(&local_params, getenv("MANGOHUD_CONFIG"), false); + if ((events & NOTIFY_REMOVED) || (nt->params->config_file_path != local_params.config_file_path)) { + SPDLOG_DEBUG("Watching config file: {}", local_params.config_file_path.c_str()); + notify_watch(*nt, local_params.config_file_path.c_str()); } + std::lock_guard lk(nt->mutex); + *nt->params = local_params; } - i = 0; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } @@ -43,16 +28,11 @@ static void fileChanged(notify_thread *nt) { bool start_notifier(notify_thread& nt) { nt.quit.store(false); - nt.fd = inotify_init1(IN_NONBLOCK); - if (nt.fd < 0) { - SPDLOG_ERROR("inotify_init1 failed: {}", strerror(errno)); + if (!notify_open(nt)) return false; - } - nt.wd = inotify_add_watch(nt.fd, nt.params->config_file_path.c_str(), IN_MODIFY | IN_DELETE_SELF); - if (nt.wd < 0) { - close(nt.fd); - nt.fd = -1; + if (!notify_watch(nt, nt.params->config_file_path.c_str())) { + notify_close(nt); return false; } @@ -68,10 +48,5 @@ notify_thread::~notify_thread() if (thread.joinable()) thread.join(); - if (fd < 0) - return; - - inotify_rm_watch(fd, wd); - close(fd); - fd = -1; + notify_close(*this); } diff --git a/src/notify.h b/src/notify.h index 20f9b93257..dce0e423da 100644 --- a/src/notify.h +++ b/src/notify.h @@ -20,4 +20,17 @@ struct notify_thread bool start_notifier(notify_thread& nt); +// Backend of the config file watcher, implemented per platform in +// notify_.cpp. nt.fd is the event queue and nt.wd the watch, in whatever +// form the platform has them. The queue is non-blocking. +enum { + NOTIFY_MODIFIED = 1 << 0, // contents changed + NOTIFY_REMOVED = 1 << 1, // file deleted or replaced, the watch has to be added again +}; + +bool notify_open(notify_thread& nt); +bool notify_watch(notify_thread& nt, const char* path); // replaces the current watch +unsigned notify_poll(notify_thread& nt); // NOTIFY_* flags, 0 if nothing happened +void notify_close(notify_thread& nt); + #endif //MANGOHUD_NOTIFY_H diff --git a/src/notify_linux.cpp b/src/notify_linux.cpp new file mode 100644 index 0000000000..433c71eefb --- /dev/null +++ b/src/notify_linux.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include +#include +#include "notify.h" + +#define EVENT_SIZE ( sizeof (struct inotify_event) ) +#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) + +bool notify_open(notify_thread& nt) +{ + nt.fd = inotify_init1(IN_NONBLOCK); + if (nt.fd < 0) { + SPDLOG_ERROR("inotify_init1 failed: {}", strerror(errno)); + return false; + } + return true; +} + +bool notify_watch(notify_thread& nt, const char* path) +{ + if (nt.wd >= 0) + inotify_rm_watch(nt.fd, nt.wd); + nt.wd = inotify_add_watch(nt.fd, path, IN_MODIFY | IN_DELETE_SELF); + return nt.wd >= 0; +} + +unsigned notify_poll(notify_thread& nt) +{ + char buffer[EVENT_BUF_LEN]; + unsigned events = 0; + + int length = read(nt.fd, buffer, EVENT_BUF_LEN); + for (int i = 0; i < length;) { + struct inotify_event *event = (struct inotify_event *) &buffer[i]; + i += EVENT_SIZE + event->len; + if (event->mask & IN_MODIFY) + events |= NOTIFY_MODIFIED; + if (event->mask & IN_DELETE_SELF) + events |= NOTIFY_REMOVED; + } + return events; +} + +void notify_close(notify_thread& nt) +{ + if (nt.fd < 0) + return; + + inotify_rm_watch(nt.fd, nt.wd); + close(nt.fd); + nt.fd = -1; +} From 9f9e76a858da6a5dc586327076ea17a60401eef7 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:10:02 +0000 Subject: [PATCH 08/33] Guard unix code with _WIN32 instead of __linux__ --- src/app/main.cpp | 4 ++-- src/gl/gl_hud.cpp | 2 +- src/hud_elements.cpp | 22 +++++++++++----------- src/hud_elements.h | 2 +- src/imgui_utils.h | 2 +- src/logging.cpp | 2 +- src/overlay.cpp | 16 ++++++++-------- src/overlay_params.cpp | 2 +- src/shell.h | 4 ++-- src/vulkan.cpp | 10 +++++----- 10 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/app/main.cpp b/src/app/main.cpp index 2371feac57..2d4f9fbd6d 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -22,7 +22,7 @@ #include "mangoapp.h" #include "mangoapp_proto.h" #include -#ifdef __linux__ +#ifndef _WIN32 #include "implot.h" #endif @@ -466,7 +466,7 @@ static GLFWwindow* init(const char* glsl_version){ glfwMakeContextCurrent(window); glfwSwapInterval(1); // Enable vsync ImGui::CreateContext(); -#ifdef __linux__ +#ifndef _WIN32 ImPlot::CreateContext(); #endif ImGuiIO& io = ImGui::GetIO(); (void)io; diff --git a/src/gl/gl_hud.cpp b/src/gl/gl_hud.cpp index 3249a8ef59..6744db6fde 100644 --- a/src/gl/gl_hud.cpp +++ b/src/gl/gl_hud.cpp @@ -8,7 +8,7 @@ #include #include #include -#ifdef __linux__ +#ifndef _WIN32 #include #endif #include "imgui_utils.h" diff --git a/src/hud_elements.cpp b/src/hud_elements.cpp index 3c6c94250d..845b66d5ab 100644 --- a/src/hud_elements.cpp +++ b/src/hud_elements.cpp @@ -20,7 +20,7 @@ #include #include "version.h" #include "blacklist.h" -#ifdef __linux__ +#ifndef _WIN32 #include "implot.h" #endif #include "amdgpu.h" @@ -138,7 +138,7 @@ static bool ImGuiTextOverflow(const char* text) { } // This function is only used in battery and battery is not used in windows builds // Battery should probably be reworked to not use this func since nothing else needs it -#ifdef __linux__ +#ifndef _WIN32 static void ImGuiTableSetColumnIndex(int column) { ImGui::TableSetColumnIndex(std::max(0, std::min(column, ImGui::TableGetColumnCount() - 1))); @@ -657,7 +657,7 @@ void HudElements::proc_vram() { } void HudElements::ram(){ -#ifdef __linux__ +#ifndef _WIN32 if (HUDElements.params->enabled[OVERLAY_PARAM_ENABLED_ram] || (HUDElements.params->enabled[OVERLAY_PARAM_ENABLED_ram_temp] && mem_temp > -1)) { ImguiNextColumnFirstItem(); @@ -703,7 +703,7 @@ void HudElements::ram(){ void HudElements::procmem() { -#ifdef __linux__ +#ifndef _WIN32 const char* unit = nullptr; if (!HUDElements.params->enabled[OVERLAY_PARAM_ENABLED_procmem]) @@ -740,7 +740,7 @@ void HudElements::procmem() void HudElements::cgroup_mem() { -#ifdef __linux__ +#ifndef _WIN32 const char* unit = nullptr; uint64_t used = cgroup_mem_used; @@ -944,7 +944,7 @@ void HudElements::frame_timing(){ NULL, min_time, max_time, ImVec2(width, height)); } else { -#ifndef __linux__ +#ifdef _WIN32 ImGui::PlotLines(hash, get_time_stat, HUDElements.sw_stats, ARRAY_SIZE(HUDElements.sw_stats->frames_stats), 0, NULL, min_time, max_time, @@ -1147,7 +1147,7 @@ void HudElements::vkbasalt(){ } void HudElements::battery(){ -#ifdef __linux__ +#ifndef _WIN32 if (Battery_Stats.batt_count > 0) { if (HUDElements.params->enabled[OVERLAY_PARAM_ENABLED_battery]) { ImguiNextColumnFirstItem(); @@ -1319,7 +1319,7 @@ void HudElements::gamescope_frame_timing(){ void HudElements::device_battery() { -#ifdef __linux__ +#ifndef _WIN32 std::unique_lock l(device_lock); if (!HUDElements.params->device_battery.empty()) { if (device_found) { @@ -1531,7 +1531,7 @@ void HudElements::graphs(){ HUDElements.min = 0; HUDElements.TextColored(HUDElements.colors.engine, "%s", "VRAM"); } -#ifdef __linux__ +#ifndef _WIN32 if (value == "ram"){ for (auto& it : graph_data){ @@ -1660,7 +1660,7 @@ void HudElements::present_mode() { } void HudElements::network() { -#ifdef __linux__ +#ifndef _WIN32 if (HUDElements.net && HUDElements.net->should_reset) HUDElements.net.reset(new Net); @@ -2081,7 +2081,7 @@ void HudElements::legacy_elements(const overlay_params* temp_params){ } void HudElements::update_exec(){ -#ifdef __linux__ +#ifndef _WIN32 // TODO: exec needs a rewrite using as using fork() is not safe in multithread. // We should probably use posix_spawn instead. // This currently stalls games using feral launcher. diff --git a/src/hud_elements.h b/src/hud_elements.h index 1a53242d0f..de924775d6 100644 --- a/src/hud_elements.h +++ b/src/hud_elements.h @@ -70,7 +70,7 @@ class HudElements{ display_servers display_server = UNKNOWN; std::unique_ptr net = nullptr; -#ifdef __linux__ +#ifndef _WIN32 std::unique_ptr shell = nullptr; #endif diff --git a/src/imgui_utils.h b/src/imgui_utils.h index f2797e4076..303062d935 100644 --- a/src/imgui_utils.h +++ b/src/imgui_utils.h @@ -2,7 +2,7 @@ #include -#ifdef __linux__ +#ifndef _WIN32 #include #endif diff --git a/src/logging.cpp b/src/logging.cpp index f542fcfbf0..1fd16e85f1 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -297,7 +297,7 @@ void Logger::stop_logging() { SPDLOG_INFO("Can't write summary because m_log_files is empty"); clear_log_data(); -#ifdef __linux__ +#ifndef _WIN32 control_client_check(get_params()->control, global_control_client, gpu.c_str()); const char * cmd = "LoggingFinished"; control_send(global_control_client, cmd, strlen(cmd), 0, 0); diff --git a/src/overlay.cpp b/src/overlay.cpp index 0bdc9ee9a5..dcbec6bd19 100644 --- a/src/overlay.cpp +++ b/src/overlay.cpp @@ -29,7 +29,7 @@ #include "fex.h" #include "ftrace.h" -#ifdef __linux__ +#ifndef _WIN32 #include #include #endif @@ -104,7 +104,7 @@ void update_hw_info(const struct overlay_params& params, uint32_t vendorID) if (real_params->enabled[OVERLAY_PARAM_ENABLED_cpu_stats] || logger->is_active()) { cpuStats.UpdateCPUData(); -#ifdef __linux__ +#ifndef _WIN32 if (real_params->enabled[OVERLAY_PARAM_ENABLED_core_load] || real_params->enabled[OVERLAY_PARAM_ENABLED_cpu_mhz] || logger->is_active()) cpuStats.UpdateCoreMhz(); if (real_params->enabled[OVERLAY_PARAM_ENABLED_cpu_temp] || logger->is_active() || real_params->enabled[OVERLAY_PARAM_ENABLED_graphs]) @@ -118,7 +118,7 @@ void update_hw_info(const struct overlay_params& params, uint32_t vendorID) gpus->get_metrics(); } -#ifdef __linux__ +#ifndef _WIN32 if (real_params->enabled[OVERLAY_PARAM_ENABLED_fan]) cpuStats.UpdatePlatformFanSpeed(); if (real_params->enabled[OVERLAY_PARAM_ENABLED_battery]) @@ -148,7 +148,7 @@ void update_hw_info(const struct overlay_params& params, uint32_t vendorID) currentLogData.gpu_vram_used = gpus->active_gpu()->metrics.sys_vram_used; currentLogData.gpu_power = gpus->active_gpu()->metrics.powerUsage; } -#ifdef __linux__ +#ifndef _WIN32 currentLogData.ram_used = memused; currentLogData.swap_used = swapused; currentLogData.process_rss = proc_mem_resident / float((2 << 29)); // GiB, consistent w/ other mem stats @@ -266,7 +266,7 @@ void update_hud_info_with_frametime(struct swapchain_stats& sw_stats, const stru hw_update_thread->update(¶ms, vendorID); if (fpsmetrics) fpsmetrics->update_thread(); -#ifdef __linux__ +#ifndef _WIN32 if (HUDElements.net) HUDElements.net->update(); #endif @@ -748,7 +748,7 @@ void render_imgui(swapchain_stats& data, struct overlay_params& params, ImVec2& void init_cpu_stats(overlay_params& params) { -#ifdef __linux__ +#ifndef _WIN32 auto& enabled = params.enabled; enabled[OVERLAY_PARAM_ENABLED_cpu_stats] = cpuStats.Init() && enabled[OVERLAY_PARAM_ENABLED_cpu_stats]; @@ -764,7 +764,7 @@ struct pci_bus { int func; }; -#ifdef __linux__ +#ifndef _WIN32 static void parse_proton_version(std::string wineProcess, std::string postfix) { stringstream ss; @@ -869,7 +869,7 @@ void init_system_info(){ } void check_for_vkbasalt_and_gamemode() { -#ifdef __linux__ +#ifndef _WIN32 static bool checked = false; if (checked) return; diff --git a/src/overlay_params.cpp b/src/overlay_params.cpp index f7265285e0..315dfd8ce0 100644 --- a/src/overlay_params.cpp +++ b/src/overlay_params.cpp @@ -6,7 +6,7 @@ #include #include #include -#ifdef __linux__ +#ifndef _WIN32 #include #include #endif diff --git a/src/shell.h b/src/shell.h index f2f14ed366..6cac2c3321 100644 --- a/src/shell.h +++ b/src/shell.h @@ -2,7 +2,7 @@ #include #include #include -#ifdef __linux__ +#ifndef _WIN32 #include #endif #include @@ -18,7 +18,7 @@ class Shell { struct stat stat_buffer; bool runtime = false; -#ifdef __linux__ +#ifndef _WIN32 void setNonBlocking(int fd) { int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); diff --git a/src/vulkan.cpp b/src/vulkan.cpp index 81cc01a81c..51b512a893 100644 --- a/src/vulkan.cpp +++ b/src/vulkan.cpp @@ -59,7 +59,7 @@ #endif #include "real_dlsym.h" #include "file_utils.h" -#ifdef __linux__ +#ifndef _WIN32 #include #include "implot.h" #endif @@ -537,7 +537,7 @@ static void snapshot_swapchain_frame(struct swapchain_data *data) struct instance_data *instance_data = device_data->instance; update_hud_info(data->sw_stats, instance_data->params, device_data->properties.vendorID); check_keybinds(instance_data->params); -#ifdef __linux__ +#ifndef _WIN32 if (instance_data->params.control >= 0) { control_client_check(instance_data->params.control, instance_data->control_client, gpu.c_str()); process_control_socket(instance_data->control_client, instance_data->params); @@ -1696,7 +1696,7 @@ static VkResult overlay_CreateSwapchainKHR( std::string deviceName = prop.deviceName; if (!is_blacklisted()) { -#ifdef __linux__ +#ifndef _WIN32 swapchain_data->sw_stats.gpuName = remove_parentheses(deviceName); #endif } @@ -2159,7 +2159,7 @@ static VkResult overlay_CreateDevice( SPDLOG_DEBUG("{} overlay queue from family {}", queues.private_queue ? "Reserved" : "Synchronizing shared", device_data->graphic_queue->family_index); -#ifdef __linux__ +#ifndef _WIN32 gpu = device_data->properties.deviceName; SPDLOG_DEBUG("gpu: {}", gpu); #endif @@ -2270,7 +2270,7 @@ static VkResult overlay_CreateInstance( } if (!is_blacklisted()) { -#ifdef __linux__ +#ifndef _WIN32 init_system_info(); instance_data->notifier.params = &instance_data->params; start_notifier(instance_data->notifier); From ab97c10639577794009ee02ab97d862d68c1c330 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Tue, 17 Nov 2026 01:22:16 +0000 Subject: [PATCH 09/33] shim: find the adjacent OpenGL library with dladdr() where dladdr1() is missing --- src/gl/shim.c | 52 ++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/src/gl/shim.c b/src/gl/shim.c index 6a1e150f9d..df0f886c77 100644 --- a/src/gl/shim.c +++ b/src/gl/shim.c @@ -16,41 +16,74 @@ static void* handle = NULL; static bool mangoHudLoaded = false; -#ifdef __GLIBC__ static inline void free_indirect(char **p) { free(*p); } -static bool load_adjacent_opengl_lib(void) +// Path of this shared library as it was loaded +static const char *get_own_path(void) { - __attribute__((cleanup(free_indirect))) char *location = NULL; - __attribute__((cleanup(free_indirect))) char *lib = NULL; Dl_info info = {}; - void *extra_info = NULL; // The first argument can be any symbol in this shared library, // mangoHudLoaded is a convenient one +#ifdef RTLD_DL_LINKMAP + void *extra_info = NULL; + if (!dladdr1(&mangoHudLoaded, &info, &extra_info, RTLD_DL_LINKMAP)) { fprintf(stderr, "shim: Unable to find my own location: %s\n", dlerror()); - return false; + return NULL; } const struct link_map *map = extra_info; if (map == NULL) { fprintf(stderr, "shim: Unable to find my own location: NULL link_map\n"); - return false; + return NULL; } if (map->l_name == NULL) { fprintf(stderr, "shim: Unable to find my own location: NULL l_name\n"); + return NULL; + } + + return map->l_name; +#else + // No dladdr1() outside of glibc (BSDs, musl) + if (!dladdr(&mangoHudLoaded, &info)) + { + fprintf(stderr, "shim: Unable to find my own location: %s\n", dlerror()); + return NULL; + } + if (info.dli_fname == NULL) + { + fprintf(stderr, "shim: Unable to find my own location: NULL dli_fname\n"); + return NULL; + } + + return info.dli_fname; +#endif +} + +static bool load_adjacent_opengl_lib(void) +{ + __attribute__((cleanup(free_indirect))) char *location = NULL; + __attribute__((cleanup(free_indirect))) char *lib = NULL; + + const char *own_path = get_own_path(); + if (own_path == NULL) + return false; + + location = realpath(own_path, NULL); + if (location == NULL) + { + fprintf(stderr, "shim: Unable to find my own location: realpath: %s\n", strerror(errno)); return false; } - location = realpath(map->l_name, NULL); char *slash = strrchr(location, '/'); if (slash == NULL) @@ -77,7 +110,6 @@ static bool load_adjacent_opengl_lib(void) return true; } -#endif // Load MangoHud after EGL/GLX functions have been intercepted static void loadMangoHud(void); @@ -110,13 +142,11 @@ static void loadMangoHud() { } } -#ifdef __GLIBC__ if (load_adjacent_opengl_lib()) { mangoHudLoaded = true; return; } -#endif if (!mangoHudLoaded) { From 5ef32fb8fd3dfc1d075f2947bc03d212379a0e4d Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:10:02 +0000 Subject: [PATCH 10/33] winesync: hide the element where it can't work --- src/winesync.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/winesync.h b/src/winesync.h index 06e1c3d0c0..096ad15087 100644 --- a/src/winesync.h +++ b/src/winesync.h @@ -18,7 +18,12 @@ class WineSync { pid_t pid; std::string method = "NONE"; +#ifdef __linux__ bool inside_wine = true; +#else + // esync, fsync and ntsync only exist on Linux + bool inside_wine = false; +#endif public: void determine_sync_variant() { #ifdef __linux__ From c4a030165f44764f7a82be2daa8badd70a1ad4d8 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:11:29 +0000 Subject: [PATCH 11/33] net: split interface enumeration and counters into a platform backend --- src/meson.build | 1 + src/net.cpp | 56 ++++++++-------------------------------------- src/net.h | 16 +++++-------- src/net_linux.cpp | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 58 deletions(-) create mode 100644 src/net_linux.cpp diff --git a/src/meson.build b/src/meson.build index 7f87b7afe4..a34145e325 100644 --- a/src/meson.build +++ b/src/meson.build @@ -93,6 +93,7 @@ if is_unixy 'control.cpp', 'device.cpp', 'net.cpp', + 'net_linux.cpp', 'shell.cpp', 'ftrace.cpp', ) diff --git a/src/net.cpp b/src/net.cpp index 66f58c0abe..d41cf8d075 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -1,69 +1,31 @@ #include "net.h" +#include #include "hud_elements.h" Net::Net() { - std::error_code ec; auto params = get_params(); should_reset = false; - fs::path net_dir(NETDIR); - if (fs::is_directory(net_dir, ec)) { - std::error_code iterator_ec; - for (fs::directory_iterator it(net_dir, iterator_ec), end; - !iterator_ec && it != end; it.increment(iterator_ec)) { - const auto& entry = *it; - if (entry.is_directory(ec)) { - auto val = entry.path().filename().string(); - if (val == "lo") - continue; - - if (!params->network.empty() && params->network.front() == "1") { - interfaces.push_back({entry.path().filename().string(), 0, 0}); - } else if (!params->network.empty()){ - auto it = std::find(params->network.begin(), params->network.end(), val); - if (it != params->network.end()) - interfaces.push_back({entry.path().filename().string(), 0, 0}); - } - } - } - if (iterator_ec) - SPDLOG_DEBUG("Failed to iterate {}: {}", fs::path(net_dir).string(), iterator_ec.message()); + for (const auto& val : net_list_interfaces()) { + if (params->network.empty()) + continue; + if (params->network.front() == "1" || + std::find(params->network.begin(), params->network.end(), val) != params->network.end()) + interfaces.push_back({val, 0, 0}); } - + if (interfaces.empty()) SPDLOG_ERROR("Network: couldn't find any interfaces"); } -long long safe_stoll(const std::string& str, long long default_value); -long long safe_stoll(const std::string& str, long long default_value = 0) { - if (str.empty()) { - SPDLOG_DEBUG("tx or rx returned an empty string"); - return default_value; - } - - try { - return std::stoll(str); - } catch (const std::invalid_argument& e) { - SPDLOG_DEBUG("stoll invalid argument"); - } catch (const std::out_of_range& e) { - SPDLOG_DEBUG("stoll out of range"); - } - return default_value; -} - void Net::update() { if (!interfaces.empty()) { for (auto& iface : interfaces) { - // path to tx_bytes and rx_bytes - std::string txfile = (NETDIR + iface.name + TXFILE); - std::string rxfile = (NETDIR + iface.name + RXFILE); - // amount of bytes at previous update uint64_t prevTx = iface.txBytes; uint64_t prevRx = iface.rxBytes; // current amount of bytes - iface.txBytes = safe_stoll(read_line(txfile)); - iface.rxBytes = safe_stoll(read_line(rxfile)); + net_read_counters(iface.name, iface.txBytes, iface.rxBytes); auto now = std::chrono::steady_clock::now(); // calculate the bytes per second since last update diff --git a/src/net.h b/src/net.h index 88623132be..7f293da89b 100644 --- a/src/net.h +++ b/src/net.h @@ -9,17 +9,11 @@ namespace fs = ghc::filesystem; -#ifndef NETDIR -#define NETDIR "/sys/class/net/" -#endif - -#ifndef TXFILE -#define TXFILE "/statistics/tx_bytes" -#endif - -#ifndef RXFILE -#define RXFILE "/statistics/rx_bytes" -#endif +// Platform backend (net_linux.cpp) +// Names of the non-loopback network interfaces. +std::vector net_list_interfaces(); +// Cumulative bytes transmitted/received by an interface. +void net_read_counters(const std::string& name, uint64_t& tx, uint64_t& rx); class Net { public: diff --git a/src/net_linux.cpp b/src/net_linux.cpp new file mode 100644 index 0000000000..e6db59d10a --- /dev/null +++ b/src/net_linux.cpp @@ -0,0 +1,57 @@ +#include "net.h" + +#ifndef NETDIR +#define NETDIR "/sys/class/net/" +#endif + +#ifndef TXFILE +#define TXFILE "/statistics/tx_bytes" +#endif + +#ifndef RXFILE +#define RXFILE "/statistics/rx_bytes" +#endif + +long long safe_stoll(const std::string& str, long long default_value = 0) { + if (str.empty()) { + SPDLOG_DEBUG("tx or rx returned an empty string"); + return default_value; + } + + try { + return std::stoll(str); + } catch (const std::invalid_argument& e) { + SPDLOG_DEBUG("stoll invalid argument"); + } catch (const std::out_of_range& e) { + SPDLOG_DEBUG("stoll out of range"); + } + return default_value; +} + +std::vector net_list_interfaces() { + std::vector names; + std::error_code ec; + fs::path net_dir(NETDIR); + if (!fs::is_directory(net_dir, ec)) + return names; + + std::error_code iterator_ec; + for (fs::directory_iterator it(net_dir, iterator_ec), end; + !iterator_ec && it != end; it.increment(iterator_ec)) { + const auto& entry = *it; + if (!entry.is_directory(ec)) + continue; + auto val = entry.path().filename().string(); + if (val == "lo") + continue; + names.push_back(val); + } + if (iterator_ec) + SPDLOG_DEBUG("Failed to iterate {}: {}", net_dir.string(), iterator_ec.message()); + return names; +} + +void net_read_counters(const std::string& name, uint64_t& tx, uint64_t& rx) { + tx = safe_stoll(read_line(NETDIR + name + TXFILE)); + rx = safe_stoll(read_line(NETDIR + name + RXFILE)); +} From bc3fa2dfee63477586eee25852caa7405654688d Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:12:11 +0000 Subject: [PATCH 12/33] overlay: move system info gathering into a platform backend --- src/logging.h | 2 ++ src/meson.build | 1 + src/overlay.cpp | 13 ++----------- src/system_info_linux.cpp | 17 +++++++++++++++++ 4 files changed, 22 insertions(+), 11 deletions(-) create mode 100644 src/system_info_linux.cpp diff --git a/src/logging.h b/src/logging.h index 62d34c7a58..3085dd7926 100644 --- a/src/logging.h +++ b/src/logging.h @@ -85,6 +85,8 @@ extern float frametime; extern logData currentLogData; std::string exec(std::string command); +// Fill os, cpu, kernel, ram, cpusched (platform backend) +void get_system_info(); void autostart_log(int sleep); #endif //MANGOHUD_LOGGING_H diff --git a/src/meson.build b/src/meson.build index a34145e325..e47b1b5ee1 100644 --- a/src/meson.build +++ b/src/meson.build @@ -94,6 +94,7 @@ if is_unixy 'device.cpp', 'net.cpp', 'net_linux.cpp', + 'system_info_linux.cpp', 'shell.cpp', 'ftrace.cpp', ) diff --git a/src/overlay.cpp b/src/overlay.cpp index dcbec6bd19..68e07cbbc5 100644 --- a/src/overlay.cpp +++ b/src/overlay.cpp @@ -789,21 +789,12 @@ static void parse_proton_version(std::string wineProcess, std::string postfix) #endif void init_system_info(){ - #ifdef __linux__ + #ifndef _WIN32 const char* ld_preload = getenv("LD_PRELOAD"); if (ld_preload) unsetenv("LD_PRELOAD"); - ram = exec("sed -n 's/^MemTotal: *\\([0-9]*\\).*/\\1/p' /proc/meminfo"); - trim(ram); - cpu = exec("sed -n 's/^model name.*: \\(.*\\)/\\1/p' /proc/cpuinfo | sed 's/([^)]*)//g' | tail -n1"); - trim(cpu); - kernel = exec("uname -r"); - trim(kernel); - os = exec("sed -n 's/PRETTY_NAME=\\(.*\\)/\\1/p' /etc/os-release"); - os.erase(remove(os.begin(), os.end(), '\"' ), os.end()); - trim(os); - cpusched = read_line("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"); + get_system_info(); const char* mangohud_recursion = getenv("MANGOHUD_RECURSION"); if (!mangohud_recursion) { diff --git a/src/system_info_linux.cpp b/src/system_info_linux.cpp new file mode 100644 index 0000000000..f432ffd37a --- /dev/null +++ b/src/system_info_linux.cpp @@ -0,0 +1,17 @@ +#include +#include "logging.h" +#include "file_utils.h" +#include "string_utils.h" + +void get_system_info() { + ram = exec("sed -n 's/^MemTotal: *\\([0-9]*\\).*/\\1/p' /proc/meminfo"); + trim(ram); + cpu = exec("sed -n 's/^model name.*: \\(.*\\)/\\1/p' /proc/cpuinfo | sed 's/([^)]*)//g' | tail -n1"); + trim(cpu); + kernel = exec("uname -r"); + trim(kernel); + os = exec("sed -n 's/PRETTY_NAME=\\(.*\\)/\\1/p' /etc/os-release"); + os.erase(remove(os.begin(), os.end(), '\"' ), os.end()); + trim(os); + cpusched = read_line("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"); +} From 78790796b5dba0f4fb64d4b23716ab479439a509 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:20:18 +0000 Subject: [PATCH 13/33] gpu: move device enumeration into a platform backend --- src/gpu.cpp | 106 ++++---------------------------------------- src/gpu.h | 15 +++++-- src/gpu_linux.cpp | 109 ++++++++++++++++++++++++++++++++++++++++++++++ src/meson.build | 1 + 4 files changed, 130 insertions(+), 101 deletions(-) create mode 100644 src/gpu_linux.cpp diff --git a/src/gpu.cpp b/src/gpu.cpp index 8122d9f458..174f94f204 100644 --- a/src/gpu.cpp +++ b/src/gpu.cpp @@ -1,46 +1,19 @@ -#include #include "gpu.h" #include "file_utils.h" #include "hud_elements.h" -namespace fs = ghc::filesystem; - GPUS::GPUS(const overlay_params* early_params) { - std::error_code ec; - std::set gpu_entries; auto params = early_params ? early_params : get_params().get(); - std::error_code iterator_ec; - for (fs::directory_iterator it("/sys/class/drm", iterator_ec), end; - !iterator_ec && it != end; it.increment(iterator_ec)) { - const auto& entry = *it; - if (!entry.is_directory(ec)) - continue; - - std::string node_name = entry.path().filename().string(); - - // Check if the directory is a render node (e.g., renderD128, renderD129, etc.) - if (node_name.find("renderD") == 0 && node_name.length() > 7) { - // Ensure the rest of the string after "renderD" is numeric - std::string render_number = node_name.substr(7); - if (std::all_of(render_number.begin(), render_number.end(), ::isdigit)) { - gpu_entries.insert(node_name); // Store the render entry - } - } - } - if (iterator_ec) - SPDLOG_DEBUG("Failed to iterate {}: {}", fs::path("/sys/class/drm").string(), iterator_ec.message()); + // Sorted by node name + const auto devices = gpu_enumerate(); // Now process the sorted GPU entries uint8_t idx = 0, total_active = 0; - for (const auto& node_name : gpu_entries) { - const std::string driver = get_driver(node_name); - - if (driver.empty()) { - SPDLOG_DEBUG("Failed to query driver name of node \"{}\"", node_name); - continue; - } + for (const auto& dev : devices) { + const std::string& node_name = dev.node; + const std::string& driver = dev.driver; { const std::string* d = @@ -55,27 +28,9 @@ GPUS::GPUS(const overlay_params* early_params) { } } - std::string path = "/sys/class/drm/" + node_name; - std::string device_address = get_pci_device_address(path); // Store the result - const char* pci_dev = device_address.c_str(); - - uint32_t vendor_id = 0; - uint32_t device_id = 0; - - if (!device_address.empty()) - { - try { - vendor_id = std::stoul(read_line("/sys/bus/pci/devices/" + device_address + "/vendor"), nullptr, 16); - } catch(...) { - SPDLOG_ERROR("stoul failed on: {}", "/sys/bus/pci/devices/" + device_address + "/vendor"); - } - - try { - device_id = std::stoul(read_line("/sys/bus/pci/devices/" + device_address + "/device"), nullptr, 16); - } catch (...) { - SPDLOG_ERROR("stoul failed on: {}", "/sys/bus/pci/devices/" + device_address + "/device"); - } - } + const char* pci_dev = dev.pci_dev.c_str(); + const uint32_t vendor_id = dev.vendor_id; + const uint32_t device_id = dev.device_id; std::shared_ptr ptr = std::make_shared(node_name, vendor_id, device_id, pci_dev, driver); @@ -128,51 +83,6 @@ bool GPU::is_steam_frame() { return drm_node_is_steam_frame(drm_node); } -std::string GPUS::get_driver(const std::string& node) { - std::error_code ec; - std::string path = "/sys/class/drm/" + node + "/device/driver"; - - if (!fs::exists(path, ec)) { - SPDLOG_ERROR("{} doesn't exist", path); - return ""; - } - - if (!fs::is_symlink(path, ec)) { - SPDLOG_ERROR("{} is not a symlink (it should be)", path); - return ""; - } - - std::string driver = fs::read_symlink(path, ec).string(); - if (ec) - return ""; - driver = driver.substr(driver.rfind("/") + 1); - - return driver; -} - -std::string GPUS::get_pci_device_address(const std::string& drm_card_path) { - std::error_code ec; - // /sys/class/drm/renderD128/device/subsystem -> /sys/bus/pci - auto subsystem = fs::canonical(drm_card_path + "/device/subsystem", ec).string(); - if (ec) - return ""; - auto idx = subsystem.rfind("/") + 1; // /sys/bus/pci - // ^ - // |- find this guy - if (subsystem.substr(idx) != "pci") - return ""; - - // /sys/class/drm/renderD128/device -> /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/0000:02:01.0/0000:03:00.0 - auto pci_addr = fs::read_symlink(drm_card_path + "/device", ec).string(); - if (ec) - return ""; - idx = pci_addr.rfind("/") + 1; // /sys/.../0000:03:00.0 - // ^ - // |- find this guy - - return pci_addr.substr(idx); // 0000:03:00.0 -} - int GPU::index_in_selected_gpus() { auto selected_gpus = gpus->selected_gpus(); auto it = std::find_if(selected_gpus.begin(), selected_gpus.end(), diff --git a/src/gpu.h b/src/gpu.h index 155c5a33c5..d400844c43 100644 --- a/src/gpu.h +++ b/src/gpu.h @@ -17,6 +17,18 @@ #include "gpu_metrics_util.h" #include "gpu_fdinfo.h" +// A GPU as found by the platform backend (gpu_linux.cpp) +struct gpu_device { + std::string node; // DRM render node name, e.g. "renderD128" (may be empty) + std::string driver; // kernel driver name, e.g. "amdgpu", "nvidia" + std::string pci_dev; // PCI address, e.g. "0000:03:00.0" + uint32_t vendor_id = 0; + uint32_t device_id = 0; +}; + +// All GPUs of the system, sorted by node name +std::vector gpu_enumerate(); + class GPU { public: gpu_metrics metrics; @@ -198,9 +210,6 @@ class GPUS { } private: - std::string get_pci_device_address(const std::string& drm_card_path); - std::string get_driver(const std::string& node); - const std::array supported_drivers = { "amdgpu", "nvidia", "i915", "xe", "panfrost", "panthor", "msm_dpu", "msm_drm" }; diff --git a/src/gpu_linux.cpp b/src/gpu_linux.cpp new file mode 100644 index 0000000000..e28daa6be3 --- /dev/null +++ b/src/gpu_linux.cpp @@ -0,0 +1,109 @@ +#include +#include +#include "gpu.h" +#include "file_utils.h" + +namespace fs = ghc::filesystem; + +static std::string get_driver(const std::string& node) { + std::error_code ec; + std::string path = "/sys/class/drm/" + node + "/device/driver"; + + if (!fs::exists(path, ec)) { + SPDLOG_ERROR("{} doesn't exist", path); + return ""; + } + + if (!fs::is_symlink(path, ec)) { + SPDLOG_ERROR("{} is not a symlink (it should be)", path); + return ""; + } + + std::string driver = fs::read_symlink(path, ec).string(); + if (ec) + return ""; + driver = driver.substr(driver.rfind("/") + 1); + + return driver; +} + +static std::string get_pci_device_address(const std::string& drm_card_path) { + std::error_code ec; + // /sys/class/drm/renderD128/device/subsystem -> /sys/bus/pci + auto subsystem = fs::canonical(drm_card_path + "/device/subsystem", ec).string(); + if (ec) + return ""; + auto idx = subsystem.rfind("/") + 1; // /sys/bus/pci + // ^ + // |- find this guy + if (subsystem.substr(idx) != "pci") + return ""; + + // /sys/class/drm/renderD128/device -> /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/0000:02:01.0/0000:03:00.0 + auto pci_addr = fs::read_symlink(drm_card_path + "/device", ec).string(); + if (ec) + return ""; + idx = pci_addr.rfind("/") + 1; // /sys/.../0000:03:00.0 + // ^ + // |- find this guy + + return pci_addr.substr(idx); // 0000:03:00.0 +} + +std::vector gpu_enumerate() { + std::error_code ec; + std::set gpu_entries; + + std::error_code iterator_ec; + for (fs::directory_iterator it("/sys/class/drm", iterator_ec), end; + !iterator_ec && it != end; it.increment(iterator_ec)) { + const auto& entry = *it; + if (!entry.is_directory(ec)) + continue; + + std::string node_name = entry.path().filename().string(); + + // Check if the directory is a render node (e.g., renderD128, renderD129, etc.) + if (node_name.find("renderD") == 0 && node_name.length() > 7) { + // Ensure the rest of the string after "renderD" is numeric + std::string render_number = node_name.substr(7); + if (std::all_of(render_number.begin(), render_number.end(), ::isdigit)) { + gpu_entries.insert(node_name); // Store the render entry + } + } + } + if (iterator_ec) + SPDLOG_DEBUG("Failed to iterate {}: {}", fs::path("/sys/class/drm").string(), iterator_ec.message()); + + std::vector devices; + for (const auto& node_name : gpu_entries) { + gpu_device dev; + dev.node = node_name; + dev.driver = get_driver(node_name); + + if (dev.driver.empty()) { + SPDLOG_DEBUG("Failed to query driver name of node \"{}\"", node_name); + continue; + } + + dev.pci_dev = get_pci_device_address("/sys/class/drm/" + node_name); + + if (!dev.pci_dev.empty()) + { + try { + dev.vendor_id = std::stoul(read_line("/sys/bus/pci/devices/" + dev.pci_dev + "/vendor"), nullptr, 16); + } catch(...) { + SPDLOG_ERROR("stoul failed on: {}", "/sys/bus/pci/devices/" + dev.pci_dev + "/vendor"); + } + + try { + dev.device_id = std::stoul(read_line("/sys/bus/pci/devices/" + dev.pci_dev + "/device"), nullptr, 16); + } catch (...) { + SPDLOG_ERROR("stoul failed on: {}", "/sys/bus/pci/devices/" + dev.pci_dev + "/device"); + } + } + + devices.push_back(std::move(dev)); + } + return devices; +} diff --git a/src/meson.build b/src/meson.build index e47b1b5ee1..89c3673a92 100644 --- a/src/meson.build +++ b/src/meson.build @@ -53,6 +53,7 @@ vklayer_files = files( 'logging.cpp', 'config.cpp', 'gpu.cpp', + 'gpu_linux.cpp', 'blacklist.cpp', 'file_utils.cpp', 'nvidia.cpp', From 29da725f10d02748b5b9678a47a381ba942eaced Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:25:52 +0000 Subject: [PATCH 14/33] amdgpu: move sysfs access into a platform backend --- src/amdgpu.cpp | 441 +----------------------------------------- src/amdgpu.h | 3 + src/amdgpu_linux.cpp | 447 +++++++++++++++++++++++++++++++++++++++++++ src/meson.build | 3 +- 4 files changed, 453 insertions(+), 441 deletions(-) create mode 100644 src/amdgpu_linux.cpp diff --git a/src/amdgpu.cpp b/src/amdgpu.cpp index 8ccc81215b..462f50c2c4 100644 --- a/src/amdgpu.cpp +++ b/src/amdgpu.cpp @@ -1,8 +1,5 @@ #include #include -#ifdef __linux__ -#include -#endif #include "amdgpu.h" #include "gpu.h" #include "cpu.h" @@ -11,266 +8,6 @@ #include "logging.h" #include "mesa/util/macros.h" - -#define IS_VALID_METRIC(FIELD) (FIELD != 0xffff) -bool AMDGPU::get_instant_metrics(struct amdgpu_common_metrics *metrics) { - FILE *f; - metrics_table_header header {}; - f = fopen(gpu_metrics_path.c_str(), "rb"); - if (!f) - return false; - - size_t nread = fread(&header, 1, sizeof(header), f); - - if (nread < sizeof(header)) { - SPDLOG_DEBUG("amdgpu metrics file '{}' may be corrupted (read {} bytes, need at least {})", - gpu_metrics_path, nread, sizeof(header)); - fclose(f); - return false; - } - - if (header.structure_size < sizeof(header)) { - SPDLOG_DEBUG( - "amdgpu metrics file '{}' has invalid structure_size {}", - gpu_metrics_path, header.structure_size); - fclose(f); - return false; - } - - std::vector buf(header.structure_size); - rewind(f); - nread = fread(buf.data(), 1, buf.size(), f); - fclose(f); - - if (nread < buf.size()) { - SPDLOG_DEBUG( - "amdgpu metrics file '{}' short read (read {} bytes, expected {})", - gpu_metrics_path, nread, buf.size()); - return false; - } - - bool is_power=false, is_current=false, is_temp=false, is_other=false; - if (header.format_revision == 1) { - // Desktop GPUs - if (buf.size() < sizeof(gpu_metrics_v1_3)) { - SPDLOG_DEBUG( - "amdgpu metrics file '{}' too small for gpu_metrics_v1_3 " - "(have {}, need {})", - gpu_metrics_path, buf.size(), sizeof(gpu_metrics_v1_3)); - return false; - } - - const auto *amdgpu_metrics = reinterpret_cast(buf.data()); - metrics->gpu_load_percent = amdgpu_metrics->average_gfx_activity; - - metrics->average_gfx_power_w = amdgpu_metrics->average_socket_power; - - metrics->current_gfxclk_mhz = amdgpu_metrics->current_gfxclk; - metrics->current_uclk_mhz = amdgpu_metrics->current_uclk; - - metrics->gpu_temp_c = amdgpu_metrics->temperature_edge; - metrics->fan_speed = amdgpu_metrics->current_fan_speed; - - uint64_t indep = amdgpu_metrics->indep_throttle_status; - // RDNA 3 almost always shows the TEMP_HOTSPOT throtting flag, - // so clear that bit - indep &= ~(1ull << TEMP_HOTSPOT_BIT); // your existing quirk - - is_power = ((indep >> 0) & 0xFF) != 0; - is_current = ((indep >> 16) & 0xFF) != 0; - is_temp = ((indep >> 32) & 0xFFFF) != 0; - is_other = ((indep >> 56) & 0xFF) != 0; - if (throttling) - throttling->indep_throttle_status = indep; - } else if (header.format_revision == 2) { - // APUS - size_t needed = 0; - - if (header.content_revision >= 3) - needed = sizeof(gpu_metrics_v2_3); - else if (header.content_revision >= 2) - needed = sizeof(gpu_metrics_v2_2); - else - needed = sizeof(gpu_metrics_v2_1); - - if (buf.size() < needed) { - SPDLOG_DEBUG( - "amdgpu metrics file '{}' too small for gpu_metrics_v2_{} " - "(have {}, need {})", - gpu_metrics_path, - header.content_revision >= 3 ? 3 : header.content_revision >= 2 ? 2 : 1, - buf.size(), - needed); - return false; - } - - const auto *amdgpu_metrics = reinterpret_cast(buf.data()); - this->is_apu = true; - - metrics->gpu_load_percent = amdgpu_metrics->average_gfx_activity; - - metrics->average_gfx_power_w = amdgpu_metrics->average_gfx_power / 1000.f; - - if( IS_VALID_METRIC(amdgpu_metrics->average_cpu_power) ) { - // prefered method - metrics->average_cpu_power_w = amdgpu_metrics->average_cpu_power / 1000.f; - } else if( IS_VALID_METRIC(amdgpu_metrics->average_core_power[0]) ) { - // fallback 1: sum of core power - metrics->average_cpu_power_w = 0; - unsigned i = 0; - do metrics->average_cpu_power_w = metrics->average_cpu_power_w + amdgpu_metrics->average_core_power[i] / 1000.f; - while (++i < ARRAY_SIZE(amdgpu_metrics->average_core_power) && IS_VALID_METRIC(amdgpu_metrics->average_core_power[i])); - } else if( IS_VALID_METRIC(amdgpu_metrics->average_socket_power) && IS_VALID_METRIC(amdgpu_metrics->average_gfx_power) ) { - // fallback 2: estimate cpu power frostd::string pci_dev, uint32_t deviceID, uint32_t vendorID - metrics->soc_temp_c = 0; - } - if( IS_VALID_METRIC(amdgpu_metrics->temperature_gfx) ) { - // prefered method - metrics->gpu_temp_c = amdgpu_metrics->temperature_gfx / 100; - } else if( header.content_revision >= 3 && IS_VALID_METRIC(amdgpu_metrics->average_temperature_gfx) ) { - // fallback 1 - metrics->gpu_temp_c = amdgpu_metrics->average_temperature_gfx / 100; - } else { - // giving up - metrics->gpu_temp_c = 0; - } - - int cpu_temp = 0; - if( IS_VALID_METRIC(amdgpu_metrics->temperature_core[0]) ) { - // prefered method - unsigned i = 0; - do cpu_temp = MAX(cpu_temp, amdgpu_metrics->temperature_core[i]); - while (++i < ARRAY_SIZE(amdgpu_metrics->temperature_core) && IS_VALID_METRIC(amdgpu_metrics->temperature_core[i])); - metrics->apu_cpu_temp_c = cpu_temp / 100; - } else if( header.content_revision >= 3 && IS_VALID_METRIC(amdgpu_metrics->average_temperature_core[0]) ) { - // fallback 1 - unsigned i = 0; - do cpu_temp = MAX(cpu_temp, amdgpu_metrics->average_temperature_core[i]); - while (++i < ARRAY_SIZE(amdgpu_metrics->average_temperature_core) && IS_VALID_METRIC(amdgpu_metrics->average_temperature_core[i])); - metrics->apu_cpu_temp_c = cpu_temp / 100; - } else if( cpuStats.ReadcpuTempFile(cpu_temp) ) { - // fallback 2: Try temp from file 'm_cpuTempFile' of 'cpu.cpp' - metrics->apu_cpu_temp_c = cpu_temp; - } else { - // giving up - metrics->apu_cpu_temp_c = 0; - } - - if( IS_VALID_METRIC(amdgpu_metrics->current_gfxclk) ) { - // prefered method - metrics->current_gfxclk_mhz = amdgpu_metrics->current_gfxclk; - } else if( IS_VALID_METRIC(amdgpu_metrics->average_gfxclk_frequency) ) { - // fallback 1 - metrics->current_gfxclk_mhz = amdgpu_metrics->average_gfxclk_frequency; - } else { - // giving up - metrics->current_gfxclk_mhz = 0; - } - - if( IS_VALID_METRIC(amdgpu_metrics->current_uclk) ) { - // prefered method - metrics->current_uclk_mhz = amdgpu_metrics->current_uclk; - } else if( IS_VALID_METRIC(amdgpu_metrics->average_uclk_frequency) ) { - // fallback 1 - metrics->current_uclk_mhz = amdgpu_metrics->average_uclk_frequency; - } else { - // giving up - metrics->current_uclk_mhz = 0; - } - - if(header.content_revision >= 2) { - uint64_t indep = amdgpu_metrics->indep_throttle_status; - is_power = ((indep >> 0) & 0xFF) != 0; - is_current = ((indep >> 16) & 0xFF) != 0; - is_temp = ((indep >> 32) & 0xFFFF) != 0; - is_other = ((indep >> 56) & 0xFF) != 0; - if (throttling) - throttling->indep_throttle_status = indep; - } - } else if (header.format_revision == 3) { - if (buf.size() < sizeof(gpu_metrics_v3_0)) { - SPDLOG_DEBUG( - "amdgpu metrics file '{}' too small for gpu_metrics_v3_0 " - "(have {}, need {})", - gpu_metrics_path, buf.size(), sizeof(gpu_metrics_v3_0)); - return false; - } - struct gpu_metrics_v3_0 *amdgpu_metrics = (struct gpu_metrics_v3_0 *) buf.data(); - this->is_apu = true; - - metrics->gpu_temp_c = amdgpu_metrics->temperature_gfx / 100; - metrics->soc_temp_c = amdgpu_metrics->temperature_soc / 100; - - uint16_t cpu_temp = 0; - - for (unsigned i = 0; i < ARRAY_SIZE(amdgpu_metrics->temperature_core); i++) { - if (!IS_VALID_METRIC(amdgpu_metrics->temperature_core[i])) - break; - - cpu_temp = MAX(cpu_temp, amdgpu_metrics->temperature_core[i]); - } - metrics->apu_cpu_temp_c = cpu_temp / 100; - - metrics->gpu_load_percent = amdgpu_metrics->average_gfx_activity; - // average_apu_power includes gfx_power so remove that from cpu_power - int64_t apu_power = amdgpu_metrics->average_apu_power; - int64_t gfx_power = amdgpu_metrics->average_gfx_power; - metrics->average_cpu_power_w = float(apu_power - gfx_power) / 1000.0; - if (metrics->average_cpu_power_w < 0) metrics->average_cpu_power_w = 0; - metrics->average_gfx_power_w = amdgpu_metrics->average_gfx_power / 1000.0; - metrics->current_gfxclk_mhz = amdgpu_metrics->average_gfxclk_frequency; - metrics->current_uclk_mhz = amdgpu_metrics->average_uclk_frequency; - - if (previous_metrics.common_header.structure_size == 0) { - previous_metrics = *amdgpu_metrics; - is_temp = false; - is_power = false; - is_current = false; - is_other = false; - if (throttling) { - throttling->use_v3 = true; - throttling->v3_power.store(false); - throttling->v3_thermal.store(false); - } - } else { - uint32_t d_thm_core = V3_THROTTLING_DELTA(thm_core); - uint32_t d_thm_gfx = V3_THROTTLING_DELTA(thm_gfx); - uint32_t d_thm_soc = V3_THROTTLING_DELTA(thm_soc); - uint32_t d_spl = V3_THROTTLING_DELTA(spl); - uint32_t d_fppt = V3_THROTTLING_DELTA(fppt); - uint32_t d_sppt = V3_THROTTLING_DELTA(sppt); - uint32_t d_prochot = V3_THROTTLING_DELTA(prochot); - is_temp = (d_thm_core | d_thm_gfx | d_thm_soc | d_prochot) > 0; - is_power = (d_spl | d_fppt | d_sppt) > 0; - // there is no current throttling flags in v3_0 - is_current = false; - // also no "other" throttling in v3_0 - is_other = false; - - previous_metrics = *amdgpu_metrics; - - if (throttling) { - throttling->use_v3 = true; - // we only check spl, this attempts to match how we handle it in v1 and v2 - // as close as we can - throttling->v3_power.store(d_spl > 0); - throttling->v3_thermal.store(is_temp); - } - } - } else { - return false; - } - - /* Throttling: See - https://elixir.bootlin.com/linux/latest/source/drivers/gpu/drm/amd/pm/swsmu/inc/amdgpu_smu.h - for the offsets */ - metrics->is_power_throttled = is_power; - metrics->is_current_throttled = is_current; - metrics->is_temp_throttled = is_temp; - metrics->is_other_throttled = is_other; - return true; -} - void AMDGPU::get_samples_and_copy(struct amdgpu_common_metrics metrics_buffer[METRICS_SAMPLE_COUNT], bool &gpu_load_needs_dividing) { while (!stop_thread) { size_t sample_count = 0; @@ -385,188 +122,12 @@ void AMDGPU::metrics_polling_thread() { } } -void AMDGPU::get_sysfs_metrics() { - int64_t value = 0; - if (sysfs_nodes.busy) { - rewind(sysfs_nodes.busy); - fflush(sysfs_nodes.busy); - int value = 0; - if (fscanf(sysfs_nodes.busy, "%d", &value) != 1) - value = 0; - metrics.load = value; - } - - if (sysfs_nodes.memory_clock) { - rewind(sysfs_nodes.memory_clock); - fflush(sysfs_nodes.memory_clock); - if (fscanf(sysfs_nodes.memory_clock, "%" PRId64, &value) != 1) - value = 0; - - metrics.MemClock = value / 1000000; - } - - // TODO: on some gpus this will use the power1_input instead - // this value is instantaneous and should be averaged over time - // probably just average everything in this function to be safe -#ifndef TEST_ONLY - if (!get_params()->enabled[OVERLAY_PARAM_ENABLED_gpu_power]) { - // NOTE: Do not read power1_average if it is not enabled, as some - // older GPUs may hang when reading the sysfs node. - metrics.powerUsage = 0; - } else -#endif - if (sysfs_nodes.power_usage) { - rewind(sysfs_nodes.power_usage); - fflush(sysfs_nodes.power_usage); - if (fscanf(sysfs_nodes.power_usage, "%" PRId64, &value) != 1) - value = 0; - - metrics.powerUsage = value / 1000000; - } - -#ifndef TEST_ONLY - if (!get_params()->enabled[OVERLAY_PARAM_ENABLED_gpu_power_limit]) { - // NOTE: Do not read power1_cap if it is not enabled, as some - // older GPUs may hang when reading the sysfs node. - metrics.powerLimit = 0; - } else -#endif - if (sysfs_nodes.power_limit) { - rewind(sysfs_nodes.power_limit); - fflush(sysfs_nodes.power_limit); - if (fscanf(sysfs_nodes.power_limit, "%" PRId64, &value) != 1) - value = 0; - - metrics.powerLimit = value / 1000000; - } - - if (sysfs_nodes.fan) { - rewind(sysfs_nodes.fan); - fflush(sysfs_nodes.fan); - if (fscanf(sysfs_nodes.fan, "%" PRId64, &value) != 1) - value = 0; - metrics.fan_speed = value; - metrics.fan_rpm = true; - } - - if (sysfs_nodes.vram_total) { - rewind(sysfs_nodes.vram_total); - fflush(sysfs_nodes.vram_total); - if (fscanf(sysfs_nodes.vram_total, "%" PRId64, &value) != 1) - value = 0; - metrics.memoryTotal = float(value) / (1024 * 1024 * 1024); - } - - if (sysfs_nodes.vram_used) { - rewind(sysfs_nodes.vram_used); - fflush(sysfs_nodes.vram_used); - if (fscanf(sysfs_nodes.vram_used, "%" PRId64, &value) != 1) - value = 0; - metrics.sys_vram_used = float(value) / (1024 * 1024 * 1024); - } - // On some GPUs SMU can sometimes return the wrong temperature. - // As HWMON is way more visible than the SMU metrics, let's always trust it as it is the most likely to work - if (sysfs_nodes.core_clock) { - rewind(sysfs_nodes.core_clock); - fflush(sysfs_nodes.core_clock); - if (fscanf(sysfs_nodes.core_clock, "%" PRId64, &value) != 1) - value = 0; - - metrics.CoreClock = value / 1000000; - } - - if (sysfs_nodes.temp){ - rewind(sysfs_nodes.temp); - fflush(sysfs_nodes.temp); - int value = 0; - if (fscanf(sysfs_nodes.temp, "%d", &value) != 1) - value = 0; - metrics.temp = value / 1000; - } - - if (sysfs_nodes.junction_temp){ - rewind(sysfs_nodes.junction_temp); - fflush(sysfs_nodes.junction_temp); - int value = 0; - if (fscanf(sysfs_nodes.junction_temp, "%d", &value) != 1) - value = 0; - metrics.junction_temp = value / 1000; - } - - if (sysfs_nodes.memory_temp){ - rewind(sysfs_nodes.memory_temp); - fflush(sysfs_nodes.memory_temp); - int value = 0; - if (fscanf(sysfs_nodes.memory_temp, "%d", &value) != 1) - value = 0; - metrics.memory_temp = value / 1000; - } - - if (sysfs_nodes.gtt_used) { - rewind(sysfs_nodes.gtt_used); - fflush(sysfs_nodes.gtt_used); - if (fscanf(sysfs_nodes.gtt_used, "%" PRId64, &value) != 1) - value = 0; - metrics.gtt_used = float(value) / (1024 * 1024 * 1024); - } - - if (sysfs_nodes.gpu_voltage_soc) { - rewind(sysfs_nodes.gpu_voltage_soc); - fflush(sysfs_nodes.gpu_voltage_soc); - if (fscanf(sysfs_nodes.gpu_voltage_soc, "%" PRId64, &value) != 1) - value = 0; - metrics.voltage = value; - } -} - AMDGPU::AMDGPU(std::string pci_dev, uint32_t device_id, uint32_t vendor_id, std::string drm_node) : fdinfo(drm_node) { - std::error_code ec; this->pci_dev = pci_dev; this->device_id = device_id; this->vendor_id = vendor_id; - const std::string device_path = "/sys/bus/pci/devices/" + pci_dev; - gpu_metrics_path = device_path + "/gpu_metrics"; - // Just check that the metrics file exists and is readable - FILE *f = fopen(gpu_metrics_path.c_str(), "rb"); - if (f) { - gpu_metrics_is_valid = true; - fclose(f); - } else { - gpu_metrics_is_valid = false; - SPDLOG_DEBUG("Failed to open gpu_metrics at '{}'", gpu_metrics_path); - } - - sysfs_nodes.busy = fopen((device_path + "/gpu_busy_percent").c_str(), "r"); - sysfs_nodes.vram_total = fopen((device_path + "/mem_info_vram_total").c_str(), "r"); - sysfs_nodes.vram_used = fopen((device_path + "/mem_info_vram_used").c_str(), "r"); - sysfs_nodes.gtt_used = fopen((device_path + "/mem_info_gtt_used").c_str(), "r"); - - const std::string hwmon_path = device_path + "/hwmon/"; - if (fs::exists(hwmon_path, ec)){ - const auto dirs = ls(hwmon_path.c_str(), "hwmon", LS_DIRS); - for (const auto& dir : dirs) { - sysfs_nodes.temp = fopen((hwmon_path + dir + "/temp1_input").c_str(), "r"); - sysfs_nodes.junction_temp = fopen((hwmon_path + dir + "/temp2_input").c_str(), "r"); - sysfs_nodes.memory_temp = fopen((hwmon_path + dir + "/temp3_input").c_str(), "r"); - sysfs_nodes.core_clock = fopen((hwmon_path + dir + "/freq1_input").c_str(), "r"); - sysfs_nodes.gpu_voltage_soc = fopen((hwmon_path + dir + "/in0_input").c_str(), "r"); - sysfs_nodes.memory_clock = fopen((hwmon_path + dir + "/freq2_input").c_str(), "r"); - - for (std::string p : { "power1_average", "power1_input" }) { - std::string sensor = hwmon_path + dir + "/" + p; - - if (!fs::exists(sensor, ec)) - continue; - - sysfs_nodes.power_usage = fopen(sensor.c_str(), "r"); - break; - } - - sysfs_nodes.power_limit = fopen((hwmon_path + dir + "/power1_cap").c_str(), "r"); - sysfs_nodes.fan = fopen((hwmon_path + dir + "/fan1_input").c_str(), "r"); - } - } + platform_init(drm_node); fdinfo.add_pid(pid); diff --git a/src/amdgpu.h b/src/amdgpu.h index ca4b8956c7..e2f4e2a052 100644 --- a/src/amdgpu.h +++ b/src/amdgpu.h @@ -513,6 +513,7 @@ class AMDGPU { std::thread thread; struct amdgpu_files sysfs_nodes = {}; bool gpu_metrics_is_valid = false; + std::shared_ptr platform; // backend private data std::condition_variable cond_var; std::atomic stop_thread{false}; std::atomic paused{false}; @@ -525,6 +526,8 @@ class AMDGPU { #define V3_THROTTLING_DELTA(name) \ ((amdgpu_metrics)->throttle_residency_##name - (previous_metrics).throttle_residency_##name) + // Platform backend (amdgpu_linux.cpp) + void platform_init(const std::string& drm_node); void get_sysfs_metrics(); void metrics_polling_thread(); }; diff --git a/src/amdgpu_linux.cpp b/src/amdgpu_linux.cpp new file mode 100644 index 0000000000..3b4b323ffa --- /dev/null +++ b/src/amdgpu_linux.cpp @@ -0,0 +1,447 @@ +#include +#include +#include "amdgpu.h" +#include "gpu.h" +#include "cpu.h" +#include "overlay.h" +#include "hud_elements.h" +#include "logging.h" +#include "mesa/util/macros.h" + +#define IS_VALID_METRIC(FIELD) (FIELD != 0xffff) +bool AMDGPU::get_instant_metrics(struct amdgpu_common_metrics *metrics) { + FILE *f; + metrics_table_header header {}; + f = fopen(gpu_metrics_path.c_str(), "rb"); + if (!f) + return false; + + size_t nread = fread(&header, 1, sizeof(header), f); + + if (nread < sizeof(header)) { + SPDLOG_DEBUG("amdgpu metrics file '{}' may be corrupted (read {} bytes, need at least {})", + gpu_metrics_path, nread, sizeof(header)); + fclose(f); + return false; + } + + if (header.structure_size < sizeof(header)) { + SPDLOG_DEBUG( + "amdgpu metrics file '{}' has invalid structure_size {}", + gpu_metrics_path, header.structure_size); + fclose(f); + return false; + } + + std::vector buf(header.structure_size); + rewind(f); + nread = fread(buf.data(), 1, buf.size(), f); + fclose(f); + + if (nread < buf.size()) { + SPDLOG_DEBUG( + "amdgpu metrics file '{}' short read (read {} bytes, expected {})", + gpu_metrics_path, nread, buf.size()); + return false; + } + + bool is_power=false, is_current=false, is_temp=false, is_other=false; + if (header.format_revision == 1) { + // Desktop GPUs + if (buf.size() < sizeof(gpu_metrics_v1_3)) { + SPDLOG_DEBUG( + "amdgpu metrics file '{}' too small for gpu_metrics_v1_3 " + "(have {}, need {})", + gpu_metrics_path, buf.size(), sizeof(gpu_metrics_v1_3)); + return false; + } + + const auto *amdgpu_metrics = reinterpret_cast(buf.data()); + metrics->gpu_load_percent = amdgpu_metrics->average_gfx_activity; + + metrics->average_gfx_power_w = amdgpu_metrics->average_socket_power; + + metrics->current_gfxclk_mhz = amdgpu_metrics->current_gfxclk; + metrics->current_uclk_mhz = amdgpu_metrics->current_uclk; + + metrics->gpu_temp_c = amdgpu_metrics->temperature_edge; + metrics->fan_speed = amdgpu_metrics->current_fan_speed; + + uint64_t indep = amdgpu_metrics->indep_throttle_status; + // RDNA 3 almost always shows the TEMP_HOTSPOT throtting flag, + // so clear that bit + indep &= ~(1ull << TEMP_HOTSPOT_BIT); // your existing quirk + + is_power = ((indep >> 0) & 0xFF) != 0; + is_current = ((indep >> 16) & 0xFF) != 0; + is_temp = ((indep >> 32) & 0xFFFF) != 0; + is_other = ((indep >> 56) & 0xFF) != 0; + if (throttling) + throttling->indep_throttle_status = indep; + } else if (header.format_revision == 2) { + // APUS + size_t needed = 0; + + if (header.content_revision >= 3) + needed = sizeof(gpu_metrics_v2_3); + else if (header.content_revision >= 2) + needed = sizeof(gpu_metrics_v2_2); + else + needed = sizeof(gpu_metrics_v2_1); + + if (buf.size() < needed) { + SPDLOG_DEBUG( + "amdgpu metrics file '{}' too small for gpu_metrics_v2_{} " + "(have {}, need {})", + gpu_metrics_path, + header.content_revision >= 3 ? 3 : header.content_revision >= 2 ? 2 : 1, + buf.size(), + needed); + return false; + } + + const auto *amdgpu_metrics = reinterpret_cast(buf.data()); + this->is_apu = true; + + metrics->gpu_load_percent = amdgpu_metrics->average_gfx_activity; + + metrics->average_gfx_power_w = amdgpu_metrics->average_gfx_power / 1000.f; + + if( IS_VALID_METRIC(amdgpu_metrics->average_cpu_power) ) { + // prefered method + metrics->average_cpu_power_w = amdgpu_metrics->average_cpu_power / 1000.f; + } else if( IS_VALID_METRIC(amdgpu_metrics->average_core_power[0]) ) { + // fallback 1: sum of core power + metrics->average_cpu_power_w = 0; + unsigned i = 0; + do metrics->average_cpu_power_w = metrics->average_cpu_power_w + amdgpu_metrics->average_core_power[i] / 1000.f; + while (++i < ARRAY_SIZE(amdgpu_metrics->average_core_power) && IS_VALID_METRIC(amdgpu_metrics->average_core_power[i])); + } else if( IS_VALID_METRIC(amdgpu_metrics->average_socket_power) && IS_VALID_METRIC(amdgpu_metrics->average_gfx_power) ) { + // fallback 2: estimate cpu power frostd::string pci_dev, uint32_t deviceID, uint32_t vendorID + metrics->soc_temp_c = 0; + } + if( IS_VALID_METRIC(amdgpu_metrics->temperature_gfx) ) { + // prefered method + metrics->gpu_temp_c = amdgpu_metrics->temperature_gfx / 100; + } else if( header.content_revision >= 3 && IS_VALID_METRIC(amdgpu_metrics->average_temperature_gfx) ) { + // fallback 1 + metrics->gpu_temp_c = amdgpu_metrics->average_temperature_gfx / 100; + } else { + // giving up + metrics->gpu_temp_c = 0; + } + + int cpu_temp = 0; + if( IS_VALID_METRIC(amdgpu_metrics->temperature_core[0]) ) { + // prefered method + unsigned i = 0; + do cpu_temp = MAX(cpu_temp, amdgpu_metrics->temperature_core[i]); + while (++i < ARRAY_SIZE(amdgpu_metrics->temperature_core) && IS_VALID_METRIC(amdgpu_metrics->temperature_core[i])); + metrics->apu_cpu_temp_c = cpu_temp / 100; + } else if( header.content_revision >= 3 && IS_VALID_METRIC(amdgpu_metrics->average_temperature_core[0]) ) { + // fallback 1 + unsigned i = 0; + do cpu_temp = MAX(cpu_temp, amdgpu_metrics->average_temperature_core[i]); + while (++i < ARRAY_SIZE(amdgpu_metrics->average_temperature_core) && IS_VALID_METRIC(amdgpu_metrics->average_temperature_core[i])); + metrics->apu_cpu_temp_c = cpu_temp / 100; + } else if( cpuStats.ReadcpuTempFile(cpu_temp) ) { + // fallback 2: Try temp from file 'm_cpuTempFile' of 'cpu.cpp' + metrics->apu_cpu_temp_c = cpu_temp; + } else { + // giving up + metrics->apu_cpu_temp_c = 0; + } + + if( IS_VALID_METRIC(amdgpu_metrics->current_gfxclk) ) { + // prefered method + metrics->current_gfxclk_mhz = amdgpu_metrics->current_gfxclk; + } else if( IS_VALID_METRIC(amdgpu_metrics->average_gfxclk_frequency) ) { + // fallback 1 + metrics->current_gfxclk_mhz = amdgpu_metrics->average_gfxclk_frequency; + } else { + // giving up + metrics->current_gfxclk_mhz = 0; + } + + if( IS_VALID_METRIC(amdgpu_metrics->current_uclk) ) { + // prefered method + metrics->current_uclk_mhz = amdgpu_metrics->current_uclk; + } else if( IS_VALID_METRIC(amdgpu_metrics->average_uclk_frequency) ) { + // fallback 1 + metrics->current_uclk_mhz = amdgpu_metrics->average_uclk_frequency; + } else { + // giving up + metrics->current_uclk_mhz = 0; + } + + if(header.content_revision >= 2) { + uint64_t indep = amdgpu_metrics->indep_throttle_status; + is_power = ((indep >> 0) & 0xFF) != 0; + is_current = ((indep >> 16) & 0xFF) != 0; + is_temp = ((indep >> 32) & 0xFFFF) != 0; + is_other = ((indep >> 56) & 0xFF) != 0; + if (throttling) + throttling->indep_throttle_status = indep; + } + } else if (header.format_revision == 3) { + if (buf.size() < sizeof(gpu_metrics_v3_0)) { + SPDLOG_DEBUG( + "amdgpu metrics file '{}' too small for gpu_metrics_v3_0 " + "(have {}, need {})", + gpu_metrics_path, buf.size(), sizeof(gpu_metrics_v3_0)); + return false; + } + struct gpu_metrics_v3_0 *amdgpu_metrics = (struct gpu_metrics_v3_0 *) buf.data(); + this->is_apu = true; + + metrics->gpu_temp_c = amdgpu_metrics->temperature_gfx / 100; + metrics->soc_temp_c = amdgpu_metrics->temperature_soc / 100; + + uint16_t cpu_temp = 0; + + for (unsigned i = 0; i < ARRAY_SIZE(amdgpu_metrics->temperature_core); i++) { + if (!IS_VALID_METRIC(amdgpu_metrics->temperature_core[i])) + break; + + cpu_temp = MAX(cpu_temp, amdgpu_metrics->temperature_core[i]); + } + metrics->apu_cpu_temp_c = cpu_temp / 100; + + metrics->gpu_load_percent = amdgpu_metrics->average_gfx_activity; + // average_apu_power includes gfx_power so remove that from cpu_power + int64_t apu_power = amdgpu_metrics->average_apu_power; + int64_t gfx_power = amdgpu_metrics->average_gfx_power; + metrics->average_cpu_power_w = float(apu_power - gfx_power) / 1000.0; + if (metrics->average_cpu_power_w < 0) metrics->average_cpu_power_w = 0; + metrics->average_gfx_power_w = amdgpu_metrics->average_gfx_power / 1000.0; + metrics->current_gfxclk_mhz = amdgpu_metrics->average_gfxclk_frequency; + metrics->current_uclk_mhz = amdgpu_metrics->average_uclk_frequency; + + if (previous_metrics.common_header.structure_size == 0) { + previous_metrics = *amdgpu_metrics; + is_temp = false; + is_power = false; + is_current = false; + is_other = false; + if (throttling) { + throttling->use_v3 = true; + throttling->v3_power.store(false); + throttling->v3_thermal.store(false); + } + } else { + uint32_t d_thm_core = V3_THROTTLING_DELTA(thm_core); + uint32_t d_thm_gfx = V3_THROTTLING_DELTA(thm_gfx); + uint32_t d_thm_soc = V3_THROTTLING_DELTA(thm_soc); + uint32_t d_spl = V3_THROTTLING_DELTA(spl); + uint32_t d_fppt = V3_THROTTLING_DELTA(fppt); + uint32_t d_sppt = V3_THROTTLING_DELTA(sppt); + uint32_t d_prochot = V3_THROTTLING_DELTA(prochot); + is_temp = (d_thm_core | d_thm_gfx | d_thm_soc | d_prochot) > 0; + is_power = (d_spl | d_fppt | d_sppt) > 0; + // there is no current throttling flags in v3_0 + is_current = false; + // also no "other" throttling in v3_0 + is_other = false; + + previous_metrics = *amdgpu_metrics; + + if (throttling) { + throttling->use_v3 = true; + // we only check spl, this attempts to match how we handle it in v1 and v2 + // as close as we can + throttling->v3_power.store(d_spl > 0); + throttling->v3_thermal.store(is_temp); + } + } + } else { + return false; + } + + /* Throttling: See + https://elixir.bootlin.com/linux/latest/source/drivers/gpu/drm/amd/pm/swsmu/inc/amdgpu_smu.h + for the offsets */ + metrics->is_power_throttled = is_power; + metrics->is_current_throttled = is_current; + metrics->is_temp_throttled = is_temp; + metrics->is_other_throttled = is_other; + return true; +} +void AMDGPU::get_sysfs_metrics() { + int64_t value = 0; + if (sysfs_nodes.busy) { + rewind(sysfs_nodes.busy); + fflush(sysfs_nodes.busy); + int value = 0; + if (fscanf(sysfs_nodes.busy, "%d", &value) != 1) + value = 0; + metrics.load = value; + } + + if (sysfs_nodes.memory_clock) { + rewind(sysfs_nodes.memory_clock); + fflush(sysfs_nodes.memory_clock); + if (fscanf(sysfs_nodes.memory_clock, "%" PRId64, &value) != 1) + value = 0; + + metrics.MemClock = value / 1000000; + } + + // TODO: on some gpus this will use the power1_input instead + // this value is instantaneous and should be averaged over time + // probably just average everything in this function to be safe +#ifndef TEST_ONLY + if (!get_params()->enabled[OVERLAY_PARAM_ENABLED_gpu_power]) { + // NOTE: Do not read power1_average if it is not enabled, as some + // older GPUs may hang when reading the sysfs node. + metrics.powerUsage = 0; + } else +#endif + if (sysfs_nodes.power_usage) { + rewind(sysfs_nodes.power_usage); + fflush(sysfs_nodes.power_usage); + if (fscanf(sysfs_nodes.power_usage, "%" PRId64, &value) != 1) + value = 0; + + metrics.powerUsage = value / 1000000; + } + +#ifndef TEST_ONLY + if (!get_params()->enabled[OVERLAY_PARAM_ENABLED_gpu_power_limit]) { + // NOTE: Do not read power1_cap if it is not enabled, as some + // older GPUs may hang when reading the sysfs node. + metrics.powerLimit = 0; + } else +#endif + if (sysfs_nodes.power_limit) { + rewind(sysfs_nodes.power_limit); + fflush(sysfs_nodes.power_limit); + if (fscanf(sysfs_nodes.power_limit, "%" PRId64, &value) != 1) + value = 0; + + metrics.powerLimit = value / 1000000; + } + + if (sysfs_nodes.fan) { + rewind(sysfs_nodes.fan); + fflush(sysfs_nodes.fan); + if (fscanf(sysfs_nodes.fan, "%" PRId64, &value) != 1) + value = 0; + metrics.fan_speed = value; + metrics.fan_rpm = true; + } + + if (sysfs_nodes.vram_total) { + rewind(sysfs_nodes.vram_total); + fflush(sysfs_nodes.vram_total); + if (fscanf(sysfs_nodes.vram_total, "%" PRId64, &value) != 1) + value = 0; + metrics.memoryTotal = float(value) / (1024 * 1024 * 1024); + } + + if (sysfs_nodes.vram_used) { + rewind(sysfs_nodes.vram_used); + fflush(sysfs_nodes.vram_used); + if (fscanf(sysfs_nodes.vram_used, "%" PRId64, &value) != 1) + value = 0; + metrics.sys_vram_used = float(value) / (1024 * 1024 * 1024); + } + // On some GPUs SMU can sometimes return the wrong temperature. + // As HWMON is way more visible than the SMU metrics, let's always trust it as it is the most likely to work + if (sysfs_nodes.core_clock) { + rewind(sysfs_nodes.core_clock); + fflush(sysfs_nodes.core_clock); + if (fscanf(sysfs_nodes.core_clock, "%" PRId64, &value) != 1) + value = 0; + + metrics.CoreClock = value / 1000000; + } + + if (sysfs_nodes.temp){ + rewind(sysfs_nodes.temp); + fflush(sysfs_nodes.temp); + int value = 0; + if (fscanf(sysfs_nodes.temp, "%d", &value) != 1) + value = 0; + metrics.temp = value / 1000; + } + + if (sysfs_nodes.junction_temp){ + rewind(sysfs_nodes.junction_temp); + fflush(sysfs_nodes.junction_temp); + int value = 0; + if (fscanf(sysfs_nodes.junction_temp, "%d", &value) != 1) + value = 0; + metrics.junction_temp = value / 1000; + } + + if (sysfs_nodes.memory_temp){ + rewind(sysfs_nodes.memory_temp); + fflush(sysfs_nodes.memory_temp); + int value = 0; + if (fscanf(sysfs_nodes.memory_temp, "%d", &value) != 1) + value = 0; + metrics.memory_temp = value / 1000; + } + + if (sysfs_nodes.gtt_used) { + rewind(sysfs_nodes.gtt_used); + fflush(sysfs_nodes.gtt_used); + if (fscanf(sysfs_nodes.gtt_used, "%" PRId64, &value) != 1) + value = 0; + metrics.gtt_used = float(value) / (1024 * 1024 * 1024); + } + + if (sysfs_nodes.gpu_voltage_soc) { + rewind(sysfs_nodes.gpu_voltage_soc); + fflush(sysfs_nodes.gpu_voltage_soc); + if (fscanf(sysfs_nodes.gpu_voltage_soc, "%" PRId64, &value) != 1) + value = 0; + metrics.voltage = value; + } +} + +void AMDGPU::platform_init(const std::string& drm_node) { + std::error_code ec; + const std::string device_path = "/sys/bus/pci/devices/" + pci_dev; + gpu_metrics_path = device_path + "/gpu_metrics"; + // Just check that the metrics file exists and is readable + FILE *f = fopen(gpu_metrics_path.c_str(), "rb"); + if (f) { + gpu_metrics_is_valid = true; + fclose(f); + } else { + gpu_metrics_is_valid = false; + SPDLOG_DEBUG("Failed to open gpu_metrics at '{}'", gpu_metrics_path); + } + + sysfs_nodes.busy = fopen((device_path + "/gpu_busy_percent").c_str(), "r"); + sysfs_nodes.vram_total = fopen((device_path + "/mem_info_vram_total").c_str(), "r"); + sysfs_nodes.vram_used = fopen((device_path + "/mem_info_vram_used").c_str(), "r"); + sysfs_nodes.gtt_used = fopen((device_path + "/mem_info_gtt_used").c_str(), "r"); + + const std::string hwmon_path = device_path + "/hwmon/"; + if (fs::exists(hwmon_path, ec)){ + const auto dirs = ls(hwmon_path.c_str(), "hwmon", LS_DIRS); + for (const auto& dir : dirs) { + sysfs_nodes.temp = fopen((hwmon_path + dir + "/temp1_input").c_str(), "r"); + sysfs_nodes.junction_temp = fopen((hwmon_path + dir + "/temp2_input").c_str(), "r"); + sysfs_nodes.memory_temp = fopen((hwmon_path + dir + "/temp3_input").c_str(), "r"); + sysfs_nodes.core_clock = fopen((hwmon_path + dir + "/freq1_input").c_str(), "r"); + sysfs_nodes.gpu_voltage_soc = fopen((hwmon_path + dir + "/in0_input").c_str(), "r"); + sysfs_nodes.memory_clock = fopen((hwmon_path + dir + "/freq2_input").c_str(), "r"); + + for (std::string p : { "power1_average", "power1_input" }) { + std::string sensor = hwmon_path + dir + "/" + p; + + if (!fs::exists(sensor, ec)) + continue; + + sysfs_nodes.power_usage = fopen(sensor.c_str(), "r"); + break; + } + + sysfs_nodes.power_limit = fopen((hwmon_path + dir + "/power1_cap").c_str(), "r"); + sysfs_nodes.fan = fopen((hwmon_path + dir + "/fan1_input").c_str(), "r"); + } + } +} diff --git a/src/meson.build b/src/meson.build index 89c3673a92..10020572e7 100644 --- a/src/meson.build +++ b/src/meson.build @@ -58,7 +58,8 @@ vklayer_files = files( 'file_utils.cpp', 'nvidia.cpp', 'gpu_fdinfo.cpp', - 'amdgpu.cpp' + 'amdgpu.cpp', + 'amdgpu_linux.cpp' ) opengl_files = [] From 2d7507cf3d7ccf2c094cf193b54d66db1ee808dd Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 20:41:37 +0000 Subject: [PATCH 15/33] cpu: define cpuStats in the common part --- src/cpu.cpp | 2 -- src/cpu_common.cpp | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cpu.cpp b/src/cpu.cpp index b5aa9e4932..b1907ac69c 100644 --- a/src/cpu.cpp +++ b/src/cpu.cpp @@ -1004,5 +1004,3 @@ void CPUStats::get_cpu_cores_types_arm() { } } } - -CPUStats cpuStats; diff --git a/src/cpu_common.cpp b/src/cpu_common.cpp index f868a8b2c3..0eff59e8df 100644 --- a/src/cpu_common.cpp +++ b/src/cpu_common.cpp @@ -92,3 +92,5 @@ bool CPUStats::Reinit() m_inited = false; return Init(); } + +CPUStats cpuStats; From 1d1f4d30e3e6f958b33e2f404f2daac969003149 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 16:54:19 +0000 Subject: [PATCH 16/33] real_dlsym: look up dlopen/dlsym in rtld on FreeBSD and DragonFly --- mangohud-next/client/real_dlsym.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mangohud-next/client/real_dlsym.c b/mangohud-next/client/real_dlsym.c index f765fb812e..33fcc3a47c 100644 --- a/mangohud-next/client/real_dlsym.c +++ b/mangohud-next/client/real_dlsym.c @@ -26,6 +26,10 @@ static void get_real_functions() const char* libs[] = { #if defined(__GLIBC__) "*libdl.so*", +#elif defined(__FreeBSD__) || defined(__DragonFly__) + // libc only has dlopen()/dlsym() stubs, the real ones are in rtld. + // The pattern also matches the 32-bit ld-elf32.so.1. + "*ld-elf*.so*", #endif "*libc.so*", "*libc.*.so*", From 95ac50a8dccfd711c9544039f9301f2dda121475 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 16:56:57 +0000 Subject: [PATCH 17/33] file_utils: add FreeBSD implementation without procfs --- src/file_utils_freebsd.cpp | 109 +++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 src/file_utils_freebsd.cpp diff --git a/src/file_utils_freebsd.cpp b/src/file_utils_freebsd.cpp new file mode 100644 index 0000000000..07f16a394b --- /dev/null +++ b/src/file_utils_freebsd.cpp @@ -0,0 +1,109 @@ +#include "file_utils.h" +#include "string_utils.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Everything here works without procfs/linprocfs mounted. + +std::string get_exe_path() +{ + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; + char buf[PATH_MAX]; + size_t len = sizeof(buf); + + if (sysctl(mib, 4, buf, &len, nullptr, 0) != 0 || len == 0) + return std::string(); + return std::string(buf, strnlen(buf, len)); +} + +std::string get_proc_comm() +{ + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, static_cast(getpid()) }; + struct kinfo_proc kp; + size_t len = sizeof(kp); + + if (sysctl(mib, 4, &kp, &len, nullptr, 0) != 0 || len < sizeof(kp)) + return std::string(); + return std::string(kp.ki_comm, strnlen(kp.ki_comm, sizeof(kp.ki_comm))); +} + +std::string get_proc_cmdline() +{ + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ARGS, static_cast(getpid()) }; + size_t len = 0; + + if (sysctl(mib, 4, nullptr, &len, nullptr, 0) != 0 || len == 0) + return std::string(); + + std::string buf(len, '\0'); + if (sysctl(mib, 4, &buf[0], &len, nullptr, 0) != 0) + return std::string(); + buf.resize(len); + return buf; +} + +bool is_wine_loader(const std::string& name) +{ + // Wine here is usually started without the preloader + return name == "wine" || name == "wine64" + || name == "wine-preloader" || name == "wine64-preloader"; +} + +static int lib_loaded_cb(struct dl_phdr_info* info, size_t, void* data) +{ + auto* args = static_cast*>(data); + + if (info->dlpi_name && *info->dlpi_name + && to_lower(info->dlpi_name).find(*args->first) != std::string::npos) { + args->second = true; + return 1; // stop iterating + } + return 0; +} + +// Mappings of another process, from its VM map +static bool lib_mapped_in(const std::string& lib, pid_t pid) +{ + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, static_cast(pid) }; + size_t len = 0; + + if (sysctl(mib, 4, nullptr, &len, nullptr, 0) != 0 || len == 0) + return false; + + // the map can grow between the two calls + len += len / 4 + 16 * sizeof(struct kinfo_vmentry); + std::vector buf(len); + if (sysctl(mib, 4, buf.data(), &len, nullptr, 0) != 0) + return false; + + // entries are packed, their size varies with the path + const char* end = buf.data() + len; + for (const char* p = buf.data(); p + sizeof(int) <= end;) { + const auto* kve = reinterpret_cast(p); + if (kve->kve_structsize <= 0 || p + kve->kve_structsize > end) + break; + if (kve->kve_path[0] && to_lower(kve->kve_path).find(lib) != std::string::npos) + return true; + p += kve->kve_structsize; + } + return false; +} + +bool lib_loaded(const std::string& lib, pid_t pid) +{ + if (pid != -1 && pid != getpid()) + return lib_mapped_in(lib, pid); + + std::pair args(&lib, false); + dl_iterate_phdr(lib_loaded_cb, &args); + return args.second; +} From d6830344e08fa106dbec65e244a4ea000c8fe326 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 17:14:34 +0000 Subject: [PATCH 18/33] cpu: add FreeBSD implementation --- src/cpu_freebsd.cpp | 292 ++++++++++++++++++++++++++++++++++++++++++++ src/sysctl_utils.h | 39 ++++++ 2 files changed, 331 insertions(+) create mode 100644 src/cpu_freebsd.cpp create mode 100644 src/sysctl_utils.h diff --git a/src/cpu_freebsd.cpp b/src/cpu_freebsd.cpp new file mode 100644 index 0000000000..5f75f0028e --- /dev/null +++ b/src/cpu_freebsd.cpp @@ -0,0 +1,292 @@ +#include "cpu.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "sysctl_utils.h" + +// Per-CPU tick counters, CPUSTATES longs per CPU id: +// CP_USER, CP_NICE, CP_SYS, CP_INTR, CP_IDLE. Slots of absent CPUs are zero. +static bool read_cp_times(std::vector& out) +{ + size_t len = 0; + + if (sysctlbyname("kern.cp_times", nullptr, &len, nullptr, 0) != 0 + || len < CPUSTATES * sizeof(long)) + return false; + + out.resize(len / sizeof(long)); + len = out.size() * sizeof(long); + return sysctlbyname("kern.cp_times", out.data(), &len, nullptr, 0) == 0; +} + +static void calculate(CPUData& cpu, const long* t) +{ + calculateCPUData(cpu, + t[CP_USER], t[CP_NICE], t[CP_SYS], t[CP_IDLE], + 0 /* iowait */, t[CP_INTR], 0 /* softirq */, 0 /* steal */, 0 /* guest */, 0 /* guestnice */); +} + +bool CPUStats::Init() +{ + if (m_inited) + return true; + + std::vector times; + if (!read_cp_times(times)) { + SPDLOG_ERROR("Failed to query kern.cp_times"); + return false; + } + + m_cpuData.clear(); + for (size_t i = 0; i < times.size() / CPUSTATES; i++) { + const long* t = ×[i * CPUSTATES]; + if (!(t[CP_USER] | t[CP_NICE] | t[CP_SYS] | t[CP_INTR] | t[CP_IDLE])) + continue; // no such CPU + + CPUData cpu = {}; + cpu.totalTime = 1; + cpu.totalPeriod = 1; + cpu.cpu_id = static_cast(i); + m_cpuData.push_back(cpu); + } + + if (m_cpuData.empty()) + return false; + + m_inited = true; + return UpdateCPUData(); +} + +bool CPUStats::UpdateCPUData() +{ + if (!m_inited) + return false; + + long total[CPUSTATES]; + size_t len = sizeof(total); + if (sysctlbyname("kern.cp_time", total, &len, nullptr, 0) != 0) + return false; + calculate(m_cpuDataTotal, total); + + std::vector times; + if (!read_cp_times(times)) + return false; + + for (auto& cpu : m_cpuData) { + if ((static_cast(cpu.cpu_id) + 1) * CPUSTATES > times.size()) + continue; + calculate(cpu, ×[cpu.cpu_id * CPUSTATES]); + } + + m_cpuDataTotal.max_core_load = 0; + for (const auto& data : m_cpuData) + if (data.percent > m_cpuDataTotal.max_core_load) + m_cpuDataTotal.max_core_load = data.percent; + + m_cpuPeriod = static_cast(m_cpuData[0].totalPeriod) / m_cpuData.size(); + m_updatedCPUs = true; + return true; +} + +// The selected P-state of cpufreq(4), not a measured clock. Some drivers only +// provide dev.cpu.0.freq, the other cores show 0. +bool CPUStats::UpdateCoreMhz() +{ + m_coreMhz.clear(); + + for (auto& cpu : m_cpuData) { + int mhz = 0; + const std::string name = "dev.cpu." + std::to_string(cpu.cpu_id) + ".freq"; + if (!sysctl_read(name.c_str(), mhz) || mhz < 0) + mhz = 0; + cpu.mhz = mhz; + } + + m_cpuDataTotal.cpu_mhz = 0; + for (const auto& data : m_cpuData) + if (data.mhz > m_cpuDataTotal.cpu_mhz) + m_cpuDataTotal.cpu_mhz = data.mhz; + + return true; +} + +// coretemp(4) and amdtemp(4) report dev.cpu.N.temperature in deci-Kelvin +bool CPUStats::ReadcpuTempFile(int& temp) +{ + long sum = 0, count = 0; + + for (const auto& cpu : m_cpuData) { + int deci_kelvin = 0; + const std::string name = "dev.cpu." + std::to_string(cpu.cpu_id) + ".temperature"; + if (!sysctl_read(name.c_str(), deci_kelvin) || deci_kelvin <= 0) + continue; // no sensor on this CPU + + sum += deci_kelvin - 2731; + count++; + } + + if (!count) + return false; + + temp = static_cast(sum / (10 * count)); + return true; +} + +bool CPUStats::UpdateCpuTemp() +{ + int temp = 0; + bool ret = ReadcpuTempFile(temp); + m_cpuDataTotal.temp = temp; + + return ret; +} + +// Usable if coretemp(4) or amdtemp(4) provides a sensor +bool CPUStats::GetCpuFile() +{ + int temp = 0; + return ReadcpuTempFile(temp); +} + +bool CPUStats::UpdatePlatformFanSpeed() +{ + m_platformFanSpeed = -1; + return false; +} + +// Package power from the RAPL energy counter, read through cpuctl(4): +// Intel: MSR_RAPL_POWER_UNIT 0x606, MSR_PKG_ENERGY_STATUS 0x611 +// AMD: MSR_AMD_RAPL_POWER_UNIT 0xc0010299, MSR_AMD_PKG_ENERGY_STATUS 0xc001029b +// Energy unit is 1 / 2^((unit >> 8) & 0x1f) joules, the counter is 32 bits wide. +// Needs `kldload cpuctl` and read access to /dev/cpuctl0. +struct CPUPowerData_cpuctl : public CPUPowerData { + CPUPowerData_cpuctl() { + this->source = CPU_POWER_CPUCTL; + }; + + ~CPUPowerData_cpuctl() { + if (this->fd >= 0) + close(this->fd); + }; + + int fd {-1}; + uint32_t energy_msr {0}; + double joules_per_count {0}; + uint32_t lastCounterValue {0}; + bool haveLast {false}; + Clock::time_point lastCounterValueTime; +}; + +static bool cpuctl_rdmsr(int fd, uint32_t msr, uint64_t& out) +{ + cpuctl_msr_args_t args; + args.msr = static_cast(msr); // the kernel reads it back as unsigned + args.data = 0; + + if (ioctl(fd, CPUCTL_RDMSR, &args) != 0) + return false; // MSR not supported on this CPU + out = args.data; + return true; +} + +static bool get_cpu_power_cpuctl(CPUPowerData_cpuctl* pd, float& power) +{ + uint64_t raw = 0; + if (pd->fd < 0 || !cpuctl_rdmsr(pd->fd, pd->energy_msr, raw)) + return false; + + const uint32_t counter = static_cast(raw); + const Clock::time_point now = Clock::now(); + + if (pd->haveLast) { + const double dt = std::chrono::duration(now - pd->lastCounterValueTime).count(); + if (dt < 0.1) + return false; // too soon for a meaningful reading, keep the old value + + const uint32_t diff = counter - pd->lastCounterValue; // wraps correctly + power = static_cast(diff * pd->joules_per_count / dt); + } + + pd->lastCounterValue = counter; + pd->lastCounterValueTime = now; + pd->haveLast = true; + return true; +} + +static CPUPowerData_cpuctl* init_cpu_power_data_cpuctl() +{ + int fd = open("/dev/cpuctl0", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + SPDLOG_WARN("cpu_power: can't open /dev/cpuctl0 ({}); load cpuctl(4) and make the device readable", strerror(errno)); + return nullptr; + } + + struct Candidate { uint32_t unit_msr; uint32_t energy_msr; }; + const Candidate amd = { 0xc0010299, 0xc001029b }; + const Candidate intel = { 0x606, 0x611 }; + + // try the CPU's own vendor first + const bool is_intel = sysctl_read_string("hw.model").find("Intel") != std::string::npos; + const Candidate order[2] = { is_intel ? intel : amd, is_intel ? amd : intel }; + + for (const auto& c : order) { + uint64_t unit = 0, energy = 0; + if (!cpuctl_rdmsr(fd, c.unit_msr, unit) || !cpuctl_rdmsr(fd, c.energy_msr, energy)) + continue; + + const unsigned esu = (unit >> 8) & 0x1f; + if (esu == 0) + continue; // implausible, not a RAPL unit register + + auto powerData = std::make_unique(); + powerData->fd = fd; + powerData->energy_msr = c.energy_msr; + powerData->joules_per_count = std::ldexp(1.0, -static_cast(esu)); + SPDLOG_DEBUG("cpu_power: using MSR {:#x}, {} joules per count", c.energy_msr, powerData->joules_per_count); + return powerData.release(); + } + + SPDLOG_WARN("cpu_power: no readable package energy MSR on this CPU"); + close(fd); + return nullptr; +} + +bool CPUStats::InitCpuPowerData() +{ + static bool tried = false; + + if (m_cpuPowerData) + return true; + if (tried) + return false; + tried = true; + + CPUPowerData_cpuctl* powerData = init_cpu_power_data_cpuctl(); + if (!powerData) + return false; + + m_cpuPowerData.reset(powerData); + return true; +} + +bool CPUStats::UpdateCpuPower() +{ + if (!InitCpuPowerData()) + return false; + + float power = m_cpuDataTotal.power; // keep the last value on a skipped sample + if (!get_cpu_power_cpuctl(static_cast(m_cpuPowerData.get()), power)) + return false; + + m_cpuDataTotal.power = power; + return true; +} diff --git a/src/sysctl_utils.h b/src/sysctl_utils.h new file mode 100644 index 0000000000..3b748a65ba --- /dev/null +++ b/src/sysctl_utils.h @@ -0,0 +1,39 @@ +#pragma once +#ifndef MANGOHUD_SYSCTL_UTILS_H +#define MANGOHUD_SYSCTL_UTILS_H + +// Helpers for the sysctl(3) interface of the BSDs +#include +#include +#include +#include + +// Reads a fixed-size value, fails if the kernel's type has a different size +template +static inline bool sysctl_read(const char* name, T& out) +{ + T value {}; + size_t len = sizeof(value); + + if (sysctlbyname(name, &value, &len, nullptr, 0) != 0 || len != sizeof(value)) + return false; + out = value; + return true; +} + +static inline std::string sysctl_read_string(const char* name) +{ + size_t len = 0; + + if (sysctlbyname(name, nullptr, &len, nullptr, 0) != 0 || len == 0) + return std::string(); + + std::string value(len, '\0'); + if (sysctlbyname(name, &value[0], &len, nullptr, 0) != 0) + return std::string(); + + value.resize(strnlen(value.c_str(), len)); // drop the trailing NUL + return value; +} + +#endif // MANGOHUD_SYSCTL_UTILS_H From a94c2810f86c9b6e1c85441e1699e7fcb21365b4 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 22:16:21 +0000 Subject: [PATCH 19/33] memory: add FreeBSD implementation --- src/memory_freebsd.cpp | 69 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/memory_freebsd.cpp diff --git a/src/memory_freebsd.cpp b/src/memory_freebsd.cpp new file mode 100644 index 0000000000..e2948b48c7 --- /dev/null +++ b/src/memory_freebsd.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "memory.h" +#include "hud_elements.h" +#include "sysctl_utils.h" + +static constexpr float GiB = 1024.f * 1024.f * 1024.f; + +// "Available" is free plus inactive pages, the pages the VM hands out without +// paging anything. Wired memory, ZFS ARC included, counts as used. +void update_meminfo() { + uint32_t page_size = 0, total = 0, free_pages = 0, inactive = 0; + + if (!sysctl_read("vm.stats.vm.v_page_size", page_size) || + !sysctl_read("vm.stats.vm.v_page_count", total) || + !sysctl_read("vm.stats.vm.v_free_count", free_pages) || + !sysctl_read("vm.stats.vm.v_inactive_count", inactive)) { + SPDLOG_ERROR("can't read vm.stats.vm"); + return; + } + + const uint32_t available = std::min(total, free_pages + inactive); + memmax = static_cast(total) * page_size / GiB; + memused = static_cast(total - available) * page_size / GiB; + + // NULL kvm descriptor: uses sysctl vm.swap_info, no privileges needed. + // With maxswap 1 the only entry holds the totals of all devices, in pages. + struct kvm_swap swap {}; + if (kvm_getswapinfo(nullptr, &swap, 1, 0) >= 0) + swapused = static_cast(swap.ksw_used) * page_size / GiB; +} + +// No sensor driver for RAM temperatures is supported, mem_temp stays at -1 +void update_mem_temp() { +} + +// Shared memory is not reported: it would need a walk of the whole VM map +void update_procmem() +{ + auto gs_pid = HUDElements.g_gamescopePid; + const int pid = gs_pid < 1 ? static_cast(getpid()) : static_cast(gs_pid); + + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }; + struct kinfo_proc kp; + size_t len = sizeof(kp); + + if (sysctl(mib, 4, &kp, &len, nullptr, 0) != 0 || len < sizeof(kp)) { + SPDLOG_ERROR("can't read process info of {}", pid); + return; + } + + proc_mem_virt = kp.ki_size; + proc_mem_resident = static_cast(kp.ki_rssize) * getpagesize(); + proc_mem_shared = 0; +} + +// No cgroups, the HUD hides the element while this is 0 +void update_cgroup_mem() +{ + cgroup_mem_used = 0; +} From 503d0960c03b680097717ca27552409eb15be580 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 22:19:50 +0000 Subject: [PATCH 20/33] iostats: add FreeBSD implementation --- src/iostats_freebsd.cpp | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/iostats_freebsd.cpp diff --git a/src/iostats_freebsd.cpp b/src/iostats_freebsd.cpp new file mode 100644 index 0000000000..0d9ef7903f --- /dev/null +++ b/src/iostats_freebsd.cpp @@ -0,0 +1,54 @@ +#include "iostats.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "hud_elements.h" + +// FreeBSD has no per-process byte counters, like /proc/self/io. The closest +// is the resource usage: ru_inblock and ru_oublock count filesystem I/O +// operations (UFS: buffer cache misses and flushes, OpenZFS: reads and writes +// that reach the pool). The byte counts here are an estimate, those counts +// scaled by the I/O size of the filesystem the process works in. +static unsigned long long io_block_size() +{ + static unsigned long long size = 0; + + if (!size) { + struct statfs sfs; + if (statfs(".", &sfs) == 0 && sfs.f_iosize > 0) + size = sfs.f_iosize; + else if (statfs("/", &sfs) == 0 && sfs.f_iosize > 0) + size = sfs.f_iosize; + else + size = 32768; + + size = std::min(std::max(size, 4096), 1024 * 1024); + } + + return size; +} + +bool read_io_counters(unsigned long long& read_bytes, unsigned long long& write_bytes) +{ + auto gs_pid = HUDElements.g_gamescopePid; + const int pid = gs_pid < 1 ? static_cast(getpid()) : static_cast(gs_pid); + + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }; + struct kinfo_proc kp; + size_t len = sizeof(kp); + + if (sysctl(mib, 4, &kp, &len, nullptr, 0) != 0 || len < sizeof(kp)) { + SPDLOG_ERROR("can't read process info of {}", pid); + return false; + } + + const unsigned long long size = io_block_size(); + read_bytes = static_cast(kp.ki_rusage.ru_inblock) * size; + write_bytes = static_cast(kp.ki_rusage.ru_oublock) * size; + return true; +} From 7e155a187e0e8bb422587252132b86fbb9ba9188 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 22:19:50 +0000 Subject: [PATCH 21/33] battery: add FreeBSD implementation --- src/battery.h | 1 + src/battery_freebsd.cpp | 121 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 src/battery_freebsd.cpp diff --git a/src/battery.h b/src/battery.h index 47312bda97..38f85b9081 100644 --- a/src/battery.h +++ b/src/battery.h @@ -1,5 +1,6 @@ #pragma once #include +#include static constexpr int battery_count_max = 2; diff --git a/src/battery_freebsd.cpp b/src/battery_freebsd.cpp new file mode 100644 index 0000000000..e6870ca2b7 --- /dev/null +++ b/src/battery_freebsd.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "battery.h" +#include "sysctl_utils.h" + +// Percentage, minutes left and charge state come from the hw.acpi.battery +// sysctls, which anyone can read and combine all batteries. The power draw is +// not exported there, it comes from the ACPI ioctl on /dev/acpi, like acpiconf(8). + +static bool is_discharging() +{ + int state = 0; + return sysctl_read("hw.acpi.battery.state", state) && state >= 0 + && (state & ACPI_BATT_STAT_DISCHARG); +} + +void BatteryStats::numBattery() +{ + int units = 0; + if (!sysctl_read("hw.acpi.battery.units", units) || units < 0) + units = 0; + + batt_count = units < battery_count_max ? units : battery_count_max; + batt_check = true; +} + +void BatteryStats::update() +{ + if (!batt_check) { + numBattery(); + if (batt_count == 0) + SPDLOG_ERROR("No battery found"); + } + + if (batt_count <= 0) + return; + + int state = 0; + if (!sysctl_read("hw.acpi.battery.state", state)) + state = -1; + + const bool discharging = state >= 0 && (state & ACPI_BATT_STAT_DISCHARG); + + current_percent = getPercent(); + remaining_time = discharging ? getTimeRemaining() : 0.0f; + current_watt = discharging ? getPower() : 0.0f; + + if (state >= 0 && (state & ACPI_BATT_STAT_CHARGING)) + current_status = "Charging"; + else if (discharging) + current_status = "Discharging"; + else + current_status = current_percent >= 100.0f ? "Full" : "Not charging"; +} + +float BatteryStats::getPercent() +{ + int life = -1; // percent, -1 when unknown + if (!sysctl_read("hw.acpi.battery.life", life) || life < 0) + return 0.0f; + return static_cast(life); +} + +// Hours, like the Linux code +float BatteryStats::getTimeRemaining() +{ + int minutes = -1; // -1 when unknown + if (!sysctl_read("hw.acpi.battery.time", minutes) || minutes <= 0 || !is_discharging()) + return 0.0f; + return static_cast(minutes) / 60.0f; +} + +float BatteryStats::getPower() +{ + static int fd = -1; + static bool tried = false; + + if (!tried) { + tried = true; + fd = open("/dev/acpi", O_RDONLY | O_CLOEXEC); + if (fd < 0) + SPDLOG_WARN("battery: can't open /dev/acpi ({}), no power draw", strerror(errno)); + } + if (fd < 0) + return 0.0f; + + float watts = 0.0f; + for (int unit = 0; unit < batt_count; unit++) { + union acpi_battery_ioctl_arg io; + + io.unit = unit; + if (ioctl(fd, ACPIIO_BATT_GET_BIX, &io) == -1) + continue; + const uint32_t power_units = io.bix.units; + + io.unit = unit; + if (ioctl(fd, ACPIIO_BATT_GET_BST, &io) == -1) + continue; + // a charging unit reports its charge rate, only the draw counts + if (io.bst.state == ACPI_BATT_STAT_NOT_PRESENT || !(io.bst.state & ACPI_BATT_STAT_DISCHARG) + || io.bst.rate == ACPI_BATT_UNKNOWN) + continue; + + if (power_units == ACPI_BIX_UNITS_MA) { + if (io.bst.volt != ACPI_BATT_UNKNOWN) + watts += static_cast(io.bst.rate) * io.bst.volt / 1000000.0f; // mA * mV + } else { + watts += static_cast(io.bst.rate) / 1000.0f; // mW + } + } + + return watts; +} + +BatteryStats Battery_Stats; From b7b1717b1ab9b00635aa363cc24e64a4e54d9eda Mon Sep 17 00:00:00 2001 From: Renkoto Date: Sun, 15 Nov 2026 22:24:50 +0000 Subject: [PATCH 22/33] notify: add kqueue implementation --- src/notify_kqueue.cpp | 76 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/notify_kqueue.cpp diff --git a/src/notify_kqueue.cpp b/src/notify_kqueue.cpp new file mode 100644 index 0000000000..2cfb30048e --- /dev/null +++ b/src/notify_kqueue.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "notify.h" + +// nt.fd is the kqueue, nt.wd the open config file the vnode filter watches. +// Closing the file removes its event. + +bool notify_open(notify_thread& nt) +{ + nt.fd = kqueue(); + if (nt.fd < 0) { + SPDLOG_ERROR("kqueue failed: {}", strerror(errno)); + return false; + } + fcntl(nt.fd, F_SETFD, FD_CLOEXEC); + return true; +} + +bool notify_watch(notify_thread& nt, const char* path) +{ + if (nt.wd >= 0) { + close(nt.wd); + nt.wd = -1; + } + + nt.wd = open(path, O_RDONLY | O_CLOEXEC); + if (nt.wd < 0) + return false; + + struct kevent change; + // EV_CLEAR: report each change once, not for as long as it holds + EV_SET(&change, nt.wd, EVFILT_VNODE, EV_ADD | EV_CLEAR, + NOTE_WRITE | NOTE_EXTEND | NOTE_DELETE | NOTE_RENAME, 0, nullptr); + + if (kevent(nt.fd, &change, 1, nullptr, 0, nullptr) < 0) { + close(nt.wd); + nt.wd = -1; + return false; + } + return true; +} + +unsigned notify_poll(notify_thread& nt) +{ + struct kevent events[4]; + const struct timespec no_wait = { 0, 0 }; + unsigned flags = 0; + + int count = kevent(nt.fd, nullptr, 0, events, 4, &no_wait); + for (int i = 0; i < count; i++) { + if (events[i].fflags & (NOTE_WRITE | NOTE_EXTEND)) + flags |= NOTIFY_MODIFIED; + // an editor that saves through a temporary file removes or renames the original + if (events[i].fflags & (NOTE_DELETE | NOTE_RENAME)) + flags |= NOTIFY_REMOVED; + } + return flags; +} + +void notify_close(notify_thread& nt) +{ + if (nt.wd >= 0) { + close(nt.wd); + nt.wd = -1; + } + if (nt.fd >= 0) { + close(nt.fd); + nt.fd = -1; + } +} From db86918de7a6a2c2bdde22405e4ac1dd532fee75 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:11:29 +0000 Subject: [PATCH 23/33] net: add FreeBSD implementation --- src/net.h | 2 +- src/net_getifaddrs.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/net_getifaddrs.cpp diff --git a/src/net.h b/src/net.h index 7f293da89b..cfab14670d 100644 --- a/src/net.h +++ b/src/net.h @@ -9,7 +9,7 @@ namespace fs = ghc::filesystem; -// Platform backend (net_linux.cpp) +// Platform backend (net_linux.cpp, net_getifaddrs.cpp) // Names of the non-loopback network interfaces. std::vector net_list_interfaces(); // Cumulative bytes transmitted/received by an interface. diff --git a/src/net_getifaddrs.cpp b/src/net_getifaddrs.cpp new file mode 100644 index 0000000000..5f14b07f6f --- /dev/null +++ b/src/net_getifaddrs.cpp @@ -0,0 +1,51 @@ +#include "net.h" + +#include +#include +#include +#include +#include +#include + +// Interface counters come from the link-level (AF_LINK) entry of getifaddrs(), +// which is available on every BSD. + +std::vector net_list_interfaces() { + std::vector names; + struct ifaddrs *ifap = nullptr; + if (getifaddrs(&ifap) != 0) { + SPDLOG_DEBUG("getifaddrs failed"); + return names; + } + + for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_LINK) + continue; + if (ifa->ifa_flags & IFF_LOOPBACK) + continue; + std::string name = ifa->ifa_name; + if (std::find(names.begin(), names.end(), name) == names.end()) + names.push_back(name); + } + freeifaddrs(ifap); + return names; +} + +void net_read_counters(const std::string& name, uint64_t& tx, uint64_t& rx) { + tx = rx = 0; + struct ifaddrs *ifap = nullptr; + if (getifaddrs(&ifap) != 0) + return; + + for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_LINK || !ifa->ifa_data) + continue; + if (name != ifa->ifa_name) + continue; + const struct if_data *d = static_cast(ifa->ifa_data); + tx = d->ifi_obytes; + rx = d->ifi_ibytes; + break; + } + freeifaddrs(ifap); +} From 1cdb49a6789f26ff0c032929deabd4d7017c73ad Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:12:11 +0000 Subject: [PATCH 24/33] overlay: add FreeBSD system info backend --- src/system_info_freebsd.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/system_info_freebsd.cpp diff --git a/src/system_info_freebsd.cpp b/src/system_info_freebsd.cpp new file mode 100644 index 0000000000..df357a05d7 --- /dev/null +++ b/src/system_info_freebsd.cpp @@ -0,0 +1,16 @@ +#include "logging.h" +#include "file_utils.h" +#include "string_utils.h" +#include "sysctl_utils.h" + +void get_system_info() { + unsigned long physmem = 0; + if (sysctl_read("hw.physmem", physmem)) + ram = std::to_string(physmem / 1024); // kB, like MemTotal + + cpu = remove_parentheses(sysctl_read_string("hw.model")); + trim(cpu); + kernel = sysctl_read_string("kern.osrelease"); + os = sysctl_read_string("kern.ostype") + " " + kernel; + cpusched.clear(); +} From 5f6f855e83f7c14cccbbf50df3b666a4c6abd52b Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:20:18 +0000 Subject: [PATCH 25/33] gpu: add FreeBSD device enumeration --- src/gpu.h | 2 +- src/gpu_freebsd.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 src/gpu_freebsd.cpp diff --git a/src/gpu.h b/src/gpu.h index d400844c43..1f35f2a9d5 100644 --- a/src/gpu.h +++ b/src/gpu.h @@ -17,7 +17,7 @@ #include "gpu_metrics_util.h" #include "gpu_fdinfo.h" -// A GPU as found by the platform backend (gpu_linux.cpp) +// A GPU as found by the platform backend (gpu_linux.cpp, gpu_freebsd.cpp) struct gpu_device { std::string node; // DRM render node name, e.g. "renderD128" (may be empty) std::string driver; // kernel driver name, e.g. "amdgpu", "nvidia" diff --git a/src/gpu_freebsd.cpp b/src/gpu_freebsd.cpp new file mode 100644 index 0000000000..d8e096f45c --- /dev/null +++ b/src/gpu_freebsd.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +#include +#include "gpu.h" + +// Devices are found on the PCI bus rather than through /dev/dri: the +// proprietary NVIDIA driver doesn't always provide a DRM render node. + +#ifndef PCIC_DISPLAY +#define PCIC_DISPLAY 0x03 +#endif + +static std::string driver_for_vendor(const struct pci_conf& pc) { + switch (pc.pc_vendor) { + case 0x1002: return "amdgpu"; + case 0x10de: return "nvidia"; + default: return pc.pd_name; // reported as unsupported by the caller + } +} + +std::vector gpu_enumerate() { + std::vector devices; + + int fd = open("/dev/pci", O_RDONLY); + if (fd < 0) { + SPDLOG_ERROR("Failed to open /dev/pci"); + return devices; + } + + struct pci_conf matches[32]; + struct pci_conf_io pc {}; + pc.match_buf_len = sizeof(matches); + pc.matches = matches; + + do { + if (ioctl(fd, PCIOCGETCONF, &pc) == -1) { + SPDLOG_ERROR("PCIOCGETCONF failed"); + break; + } + if (pc.status == PCI_GETCONF_ERROR) { + SPDLOG_ERROR("PCIOCGETCONF reported an error"); + break; + } + + for (unsigned i = 0; i < pc.num_matches; i++) { + const struct pci_conf& c = matches[i]; + if (c.pc_class != PCIC_DISPLAY) + continue; + + gpu_device dev; + char addr[16]; + snprintf(addr, sizeof(addr), "%04x:%02x:%02x.%x", + (unsigned)c.pc_sel.pc_domain, (unsigned)c.pc_sel.pc_bus, + (unsigned)c.pc_sel.pc_dev, (unsigned)c.pc_sel.pc_func); + dev.pci_dev = addr; + dev.vendor_id = c.pc_vendor; + dev.device_id = c.pc_device; + dev.driver = driver_for_vendor(c); + devices.push_back(std::move(dev)); + } + } while (pc.status == PCI_GETCONF_MORE_DEVS); + + close(fd); + + std::sort(devices.begin(), devices.end(), + [](const gpu_device& a, const gpu_device& b) { return a.pci_dev < b.pci_dev; }); + return devices; +} From cdfe7913f66c20336a7249a2c0a75b2cd78007c4 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:26:06 +0000 Subject: [PATCH 26/33] amdgpu: add FreeBSD backend using libdrm_amdgpu --- src/amdgpu.h | 2 +- src/amdgpu_freebsd.cpp | 140 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 src/amdgpu_freebsd.cpp diff --git a/src/amdgpu.h b/src/amdgpu.h index e2f4e2a052..ea64efa10f 100644 --- a/src/amdgpu.h +++ b/src/amdgpu.h @@ -526,7 +526,7 @@ class AMDGPU { #define V3_THROTTLING_DELTA(name) \ ((amdgpu_metrics)->throttle_residency_##name - (previous_metrics).throttle_residency_##name) - // Platform backend (amdgpu_linux.cpp) + // Platform backend (amdgpu_linux.cpp, amdgpu_freebsd.cpp) void platform_init(const std::string& drm_node); void get_sysfs_metrics(); void metrics_polling_thread(); diff --git a/src/amdgpu_freebsd.cpp b/src/amdgpu_freebsd.cpp new file mode 100644 index 0000000000..2fe618e317 --- /dev/null +++ b/src/amdgpu_freebsd.cpp @@ -0,0 +1,140 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "amdgpu.h" +#include "overlay.h" +#include "hud_elements.h" + +// There is no sysfs on the BSDs, so everything is queried from the kernel +// through libdrm_amdgpu (the same path Mesa uses). + +namespace { + +struct amdgpu_handle { + int fd = -1; + amdgpu_device_handle dev = nullptr; + + ~amdgpu_handle() { + if (dev) + amdgpu_device_deinitialize(dev); + if (fd >= 0) + close(fd); + } +}; + +// Find the render node of a PCI device ("0000:03:00.0") when it's not known +std::string find_render_node(const std::string& pci_dev) { + unsigned domain, bus, dev, func; + if (sscanf(pci_dev.c_str(), "%x:%x:%x.%x", &domain, &bus, &dev, &func) != 4) + return ""; + + int n = drmGetDevices2(0, nullptr, 0); + if (n <= 0) + return ""; + + std::vector devices(n); + n = drmGetDevices2(0, devices.data(), n); + + std::string node; + for (int i = 0; i < n; i++) { + const drmDevicePtr d = devices[i]; + if (d->bustype != DRM_BUS_PCI || !(d->available_nodes & (1 << DRM_NODE_RENDER))) + continue; + if (d->businfo.pci->domain == domain && d->businfo.pci->bus == bus && + d->businfo.pci->dev == dev && d->businfo.pci->func == func) { + node = d->nodes[DRM_NODE_RENDER]; + break; + } + } + if (n > 0) + drmFreeDevices(devices.data(), n); + return node; +} + +bool query_sensor(amdgpu_device_handle dev, unsigned type, uint32_t& value) { + return amdgpu_query_sensor_info(dev, type, sizeof(value), &value) == 0; +} + +} // namespace + +void AMDGPU::platform_init(const std::string& drm_node) { + std::string path = drm_node.empty() ? find_render_node(pci_dev) : "/dev/dri/" + drm_node; + if (path.empty()) { + SPDLOG_DEBUG("amdgpu: no render node found for {}", pci_dev); + return; + } + + auto h = std::make_shared(); + h->fd = open(path.c_str(), O_RDWR | O_CLOEXEC); + if (h->fd < 0) { + SPDLOG_ERROR("amdgpu: failed to open {}", path); + return; + } + + uint32_t major, minor; + if (amdgpu_device_initialize(h->fd, &major, &minor, &h->dev) != 0) { + SPDLOG_ERROR("amdgpu: amdgpu_device_initialize failed for {}", path); + return; + } + + platform = h; + gpu_metrics_is_valid = true; // sensors are available +} + +bool AMDGPU::get_instant_metrics(struct amdgpu_common_metrics *metrics) { + auto h = std::static_pointer_cast(platform); + if (!h) + return false; + + uint32_t v; + bool any = false; + if (query_sensor(h->dev, AMDGPU_INFO_SENSOR_GPU_LOAD, v)) { + metrics->gpu_load_percent = v; + any = true; + } + if (query_sensor(h->dev, AMDGPU_INFO_SENSOR_GPU_AVG_POWER, v)) { // watts + metrics->average_gfx_power_w = v; + any = true; + } + if (query_sensor(h->dev, AMDGPU_INFO_SENSOR_GFX_SCLK, v)) { + metrics->current_gfxclk_mhz = v; + any = true; + } + if (query_sensor(h->dev, AMDGPU_INFO_SENSOR_GFX_MCLK, v)) { + metrics->current_uclk_mhz = v; + any = true; + } + if (query_sensor(h->dev, AMDGPU_INFO_SENSOR_GPU_TEMP, v)) { + metrics->gpu_temp_c = v / 1000; // millidegrees Celsius + any = true; + } + return any; +} + +void AMDGPU::get_sysfs_metrics() { + auto h = std::static_pointer_cast(platform); + if (!h) + return; + + constexpr float GiB = 1024.f * 1024.f * 1024.f; + + struct amdgpu_heap_info heap {}; + if (amdgpu_query_heap_info(h->dev, AMDGPU_GEM_DOMAIN_VRAM, 0, &heap) == 0) { + metrics.memoryTotal = heap.heap_size / GiB; + metrics.sys_vram_used = heap.heap_usage / GiB; + } + + if (amdgpu_query_heap_info(h->dev, AMDGPU_GEM_DOMAIN_GTT, 0, &heap) == 0) + metrics.gtt_used = heap.heap_usage / GiB; + + uint32_t v; + if (query_sensor(h->dev, AMDGPU_INFO_SENSOR_GFX_SCLK, v)) + metrics.CoreClock = v; + if (query_sensor(h->dev, AMDGPU_INFO_SENSOR_VDDGFX, v)) + metrics.voltage = v; // mV +} From 61bebffdf92f24b67822078d2df4ae966ad6ae2e Mon Sep 17 00:00:00 2001 From: Renkoto Date: Mon, 16 Nov 2026 03:29:06 +0000 Subject: [PATCH 27/33] legacy_gpu_wrapper: add a stub for platforms without sysfs/procfs --- mangohud-next/legacy_gpu_wrapper/meson.build | 68 +++++++++++-------- .../legacy_gpu_wrapper/wrapper_stub.cpp | 51 ++++++++++++++ 2 files changed, 90 insertions(+), 29 deletions(-) create mode 100644 mangohud-next/legacy_gpu_wrapper/wrapper_stub.cpp diff --git a/mangohud-next/legacy_gpu_wrapper/meson.build b/mangohud-next/legacy_gpu_wrapper/meson.build index 81c6bd61c8..7c2b4dfb72 100644 --- a/mangohud-next/legacy_gpu_wrapper/meson.build +++ b/mangohud-next/legacy_gpu_wrapper/meson.build @@ -1,29 +1,39 @@ -mangohud_legacy_gpu_wrapper = static_library( - 'MangoHud_LegacyGPUWrapper', - files( - 'wrapper.cpp', - '../server/common/helpers.cpp', - '../server/metrics/fdinfo.cpp', - '../server/metrics/hwmon.cpp', - '../server/metrics/gpu/gpu.cpp', - '../server/metrics/gpu/intel/i915/i915.cpp', - '../server/metrics/gpu/intel/i915/i915_drm.cpp', - '../server/metrics/gpu/intel/xe/xe.cpp', - '../server/metrics/gpu/intel/xe/xe_drm.cpp', - '../server/metrics/gpu/amdgpu/amdgpu.cpp', - '../server/metrics/gpu/amdgpu/gpu_metrics.cpp', - '../server/metrics/gpu/nvidia/nvidia.cpp', - '../server/metrics/gpu/nvidia/nvml_loader.cpp', - '../server/metrics/gpu/msm/dpu.cpp', - '../server/metrics/gpu/msm/kgsl.cpp', - '../server/metrics/gpu/panfrost.cpp', - '../server/metrics/gpu/panthor.cpp' - ), - cpp_args: ['-DMANGOHUD_LEGACY', '-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE', gpu_tracefs_args], - include_directories: [ - '../server/metrics', - '../server/metrics/gpu', - '../../src' - ], - dependencies: [spdlog_dep, libdrm_dep, gpu_tracefs_deps] -) +if host_machine.system() == 'linux' + mangohud_legacy_gpu_wrapper = static_library( + 'MangoHud_LegacyGPUWrapper', + files( + 'wrapper.cpp', + '../server/common/helpers.cpp', + '../server/metrics/fdinfo.cpp', + '../server/metrics/hwmon.cpp', + '../server/metrics/gpu/gpu.cpp', + '../server/metrics/gpu/intel/i915/i915.cpp', + '../server/metrics/gpu/intel/i915/i915_drm.cpp', + '../server/metrics/gpu/intel/xe/xe.cpp', + '../server/metrics/gpu/intel/xe/xe_drm.cpp', + '../server/metrics/gpu/amdgpu/amdgpu.cpp', + '../server/metrics/gpu/amdgpu/gpu_metrics.cpp', + '../server/metrics/gpu/nvidia/nvidia.cpp', + '../server/metrics/gpu/nvidia/nvml_loader.cpp', + '../server/metrics/gpu/msm/dpu.cpp', + '../server/metrics/gpu/msm/kgsl.cpp', + '../server/metrics/gpu/panfrost.cpp', + '../server/metrics/gpu/panthor.cpp' + ), + cpp_args: ['-DMANGOHUD_LEGACY', '-DSPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_TRACE', gpu_tracefs_args], + include_directories: [ + '../server/metrics', + '../server/metrics/gpu', + '../../src' + ], + dependencies: [spdlog_dep, libdrm_dep, gpu_tracefs_deps] + ) +else + # sysfs, procfs and tracefs based backends are Linux only + mangohud_legacy_gpu_wrapper = static_library( + 'MangoHud_LegacyGPUWrapper', + files('wrapper_stub.cpp'), + cpp_args: ['-DMANGOHUD_LEGACY'], + include_directories: ['../../src'] + ) +endif diff --git a/mangohud-next/legacy_gpu_wrapper/wrapper_stub.cpp b/mangohud-next/legacy_gpu_wrapper/wrapper_stub.cpp new file mode 100644 index 0000000000..9d65460f3c --- /dev/null +++ b/mangohud-next/legacy_gpu_wrapper/wrapper_stub.cpp @@ -0,0 +1,51 @@ +#include "wrapper.hpp" + +// Used where the Linux specific GPU backends (sysfs, procfs fdinfo, tracefs) +// can't work. Every metric reads as unavailable. + +struct LegacyGPUWrapper::Impl {}; + +LegacyGPUWrapper::LegacyGPUWrapper( + const std::string&, const std::string&, const std::string&, uint16_t, uint16_t +) : m_impl(std::make_unique()) {} + +LegacyGPUWrapper::~LegacyGPUWrapper() {} + +void LegacyGPUWrapper::poll() {} +void LegacyGPUWrapper::add_pid(pid_t) {} + +int LegacyGPUWrapper::get_load() { return 0; } +float LegacyGPUWrapper::get_vram_used() { return 0; } +float LegacyGPUWrapper::get_gtt_used() { return 0; } +float LegacyGPUWrapper::get_memory_total() { return 0; } +int LegacyGPUWrapper::get_memory_clock() { return 0; } +int LegacyGPUWrapper::get_memory_temp() { return 0; } +int LegacyGPUWrapper::get_temperature() { return 0; } +int LegacyGPUWrapper::get_junction_temperature() { return 0; } +int LegacyGPUWrapper::get_core_clock() { return 0; } +int LegacyGPUWrapper::get_voltage() { return 0; } +float LegacyGPUWrapper::get_power_usage() { return 0; } +float LegacyGPUWrapper::get_power_limit() { return 0; } +bool LegacyGPUWrapper::get_is_apu() { return false; } +float LegacyGPUWrapper::get_apu_cpu_power() { return 0; } +int LegacyGPUWrapper::get_apu_cpu_temp() { return 0; } +bool LegacyGPUWrapper::get_is_power_throttled() { return false; } +bool LegacyGPUWrapper::get_is_current_throttled() { return false; } +bool LegacyGPUWrapper::get_is_temp_throttled() { return false; } +bool LegacyGPUWrapper::get_is_other_throttled() { return false; } +int LegacyGPUWrapper::get_fan_speed() { return 0; } +bool LegacyGPUWrapper::get_fan_rpm() { return false; } +int LegacyGPUWrapper::get_process_load(pid_t) { return 0; } +float LegacyGPUWrapper::get_process_vram_used(pid_t) { return 0; } +float LegacyGPUWrapper::get_process_gtt_used(pid_t) { return 0; } + +struct LegacyFDInfoWrapper::Impl {}; + +LegacyFDInfoWrapper::LegacyFDInfoWrapper(const std::string&) + : m_impl(std::make_unique()) {} + +LegacyFDInfoWrapper::~LegacyFDInfoWrapper() {} + +void LegacyFDInfoWrapper::add_pid(pid_t) {} +void LegacyFDInfoWrapper::poll_all() {} +float LegacyFDInfoWrapper::get_memory_used(pid_t, const std::string&) { return 0; } From e5416995484b4f33a76ea373de133a31b4b36efc Mon Sep 17 00:00:00 2001 From: Renkoto Date: Tue, 17 Nov 2026 01:26:27 +0000 Subject: [PATCH 28/33] gpu: name the PCI device when an unsupported driver has no DRM node --- src/gpu.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gpu.cpp b/src/gpu.cpp index 174f94f204..2c1f8de994 100644 --- a/src/gpu.cpp +++ b/src/gpu.cpp @@ -20,9 +20,10 @@ GPUS::GPUS(const overlay_params* early_params) { std::find(std::begin(supported_drivers), std::end(supported_drivers), driver); if (d == std::end(supported_drivers)) { + // Backends that don't go through DRM nodes only know the PCI address SPDLOG_WARN( "node \"{}\" is using driver \"{}\" which is unsupported by MangoHud. Skipping...", - node_name, driver + node_name.empty() ? dev.pci_dev : node_name, driver ); continue; } From cbb50812d4636597905c5da73acb87e9f1a25115 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Tue, 17 Nov 2026 06:23:13 +0000 Subject: [PATCH 29/33] overlay: use is_wine_loader() for the Wine version lookup --- src/overlay.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/overlay.cpp b/src/overlay.cpp index 68e07cbbc5..d77945384c 100644 --- a/src/overlay.cpp +++ b/src/overlay.cpp @@ -811,7 +811,7 @@ void init_system_info(){ wineProcess = get_exe_path(); auto n = wineProcess.find_last_of('/'); string preloader = wineProcess.substr(n + 1); - if (preloader == "wine-preloader" || preloader == "wine64-preloader") { + if (is_wine_loader(preloader)) { // Check if using Proton if (wineProcess.find("/dist/bin/wine") != std::string::npos || wineProcess.find("/files/bin/wine") != std::string::npos @@ -827,10 +827,12 @@ void init_system_info(){ else { char *dir = dirname((char*)wineProcess.c_str()); stringstream findVersion; - if (preloader == "wine-preloader") - findVersion << "\"" << dir << "/wine\" --version"; - else - findVersion << "\"" << dir << "/wine64\" --version"; + // "wine64-preloader" -> "wine64"; a loader without the suffix is used as is + string loader = preloader; + const string suffix = "-preloader"; + if (loader.size() > suffix.size() && loader.compare(loader.size() - suffix.size(), suffix.size(), suffix) == 0) + loader.erase(loader.size() - suffix.size()); + findVersion << "\"" << dir << "/" << loader << "\" --version"; const char *wine_env = getenv("WINELOADERNOEXEC"); if (wine_env) unsetenv("WINELOADERNOEXEC"); From 7ad9698714764e73e38d9ae783c48f7a82174bb9 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Tue, 17 Nov 2026 06:47:52 +0000 Subject: [PATCH 30/33] meson: select platform backends by OS and build on FreeBSD --- meson.build | 18 ++++++++++++- src/meson.build | 69 +++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 72 insertions(+), 15 deletions(-) diff --git a/meson.build b/meson.build index 1cbb8caaae..91df946d08 100644 --- a/meson.build +++ b/meson.build @@ -51,6 +51,17 @@ if ['linux', 'cygwin', 'gnu'].contains(host_machine.system()) is_unixy = true endif +# Other Unix systems have their own backends in src/, see src/meson.build +is_freebsd = host_machine.system() == 'freebsd' +if ['freebsd', 'netbsd', 'openbsd', 'dragonfly'].contains(host_machine.system()) + pre_args += '-DHAVE_PTHREAD' + is_unixy = true +endif + +if not is_unixy and not ['windows', 'mingw'].contains(host_machine.system()) + error('MangoHud does not support @0@ yet'.format(host_machine.system())) +endif + if host_machine.system() == 'linux' pre_args += '-DHAVE_FTRACE' endif @@ -368,6 +379,11 @@ if get_option('mangoplot').enabled() subdir('bin') endif +# mangohud-next needs sd-bus (systemd/elogind), Wayland and Linux-only IPC if get_option('with_mangohud_next') - subdir('mangohud-next') + if host_machine.system() == 'linux' + subdir('mangohud-next') + else + message('mangohud-next is only supported on Linux, not building it') + endif endif diff --git a/src/meson.build b/src/meson.build index 10020572e7..3a3d971d30 100644 --- a/src/meson.build +++ b/src/meson.build @@ -1,6 +1,7 @@ glslang = find_program('glslang', 'glslangValidator') -if get_option('dynamic_string_tokens') +# Only glibc and musl expand $LIB; other rtlds (FreeBSD, ...) take it literally +if get_option('dynamic_string_tokens') and host_machine.system() == 'linux' ld_prefix = get_option('prefix') + '/\$LIB/' else ld_prefix = join_paths(get_option('prefix') ,get_option('libdir')) + '/' @@ -53,15 +54,42 @@ vklayer_files = files( 'logging.cpp', 'config.cpp', 'gpu.cpp', - 'gpu_linux.cpp', 'blacklist.cpp', 'file_utils.cpp', 'nvidia.cpp', 'gpu_fdinfo.cpp', 'amdgpu.cpp', - 'amdgpu_linux.cpp' ) +# Platform backends: the common part of each module is in the files above and +# below, the part that talks to the OS is _.cpp. Linux (also used +# on cygwin and gnu) keeps the original names. Porting to another Unix means +# adding those files, the BSDs share notify_kqueue.cpp and net_getifaddrs.cpp. +fs = import('fs') +backend_modules = ['gpu', 'amdgpu', 'file_utils', 'cpu', 'memory', 'iostats', 'battery', 'system_info'] +platform_deps = [] +if is_unixy and not ['linux', 'cygwin', 'gnu'].contains(host_machine.system()) + foreach m : backend_modules + f = '@0@_@1@.cpp'.format(m, host_machine.system()) + if not fs.exists(f) + error('No @0@ backend for @1@: src/@2@ is missing'.format(m, host_machine.system(), f)) + endif + vklayer_files += files(f) + endforeach + vklayer_files += files('notify_kqueue.cpp', 'net_getifaddrs.cpp') +else + vklayer_files += files( + 'gpu_linux.cpp', + 'amdgpu_linux.cpp', + ) +endif +if is_freebsd + # sysfs doesn't exist, AMD GPUs are queried through libdrm_amdgpu + platform_deps += [libdrm_dep, dependency('libdrm_amdgpu')] + # kvm_getswapinfo() + platform_deps += cc.find_library('kvm') +endif + opengl_files = [] if ['windows', 'mingw'].contains(host_machine.system()) vklayer_files += files( @@ -79,28 +107,33 @@ endif if is_unixy vklayer_files += files( - 'file_utils_linux.cpp', - 'cpu.cpp', 'cpu_common.cpp', - 'memory.cpp', 'memory_common.cpp', 'iostats.cpp', - 'iostats_linux.cpp', 'notify.cpp', - 'notify_linux.cpp', 'elfhacks.c', '../mangohud-next/client/real_dlsym.c', 'pci_ids.cpp', - 'battery.cpp', 'control.cpp', 'device.cpp', 'net.cpp', - 'net_linux.cpp', - 'system_info_linux.cpp', 'shell.cpp', 'ftrace.cpp', ) + if ['linux', 'cygwin', 'gnu'].contains(host_machine.system()) + vklayer_files += files( + 'file_utils_linux.cpp', + 'cpu.cpp', + 'memory.cpp', + 'iostats_linux.cpp', + 'notify_linux.cpp', + 'battery.cpp', + 'net_linux.cpp', + 'system_info_linux.cpp', + ) + endif + if get_option('with_fex') pre_args += '-DHAVE_FEX' vklayer_files += files( @@ -138,7 +171,8 @@ if is_unixy error('XNVCtrl also needs \'with_x11\'') endif - xnvctrl_h_found = cc.has_header('NVCtrl/NVCtrl.h') + # dep_x11 also provides the include path of systems that don't search /usr/local + xnvctrl_h_found = cc.has_header('NVCtrl/NVCtrl.h', dependencies: dep_x11) if not xnvctrl_h_found error('NVCtrl.h was not found. Disable with \'-Dwith_xnvctrl=disabled\' if gpu stats by XNVCtrl are not needed.') endif @@ -181,6 +215,10 @@ if is_unixy endif link_args = cc.get_supported_link_arguments(['-Wl,-Bsymbolic-functions', '-Wl,-z,relro', '-Wl,--exclude-libs,ALL', '-lGL', '-static-libstdc++']) +if is_freebsd + # lld refuses version scripts naming symbols that aren't defined + link_args += cc.get_supported_link_arguments(['-Wl,--undefined-version']) +endif # meson fails to check version-script so just force add link_args += '-Wl,--version-script,@0@'.format(join_paths(meson.current_source_dir(), 'mangohud.version')) @@ -216,6 +254,7 @@ mangohud_static_lib = static_library( dep_vulkan_utility_libraries, windows_deps, implot_dep, + platform_deps, mangohud_version_dep], include_directories : [inc_common, next_client_inc], link_args : link_args, @@ -259,7 +298,8 @@ mangohud_opengl_shared_lib = shared_library( vulkan_headers_dep, dep_vulkan_utility_libraries, windows_deps, - implot_dep], + implot_dep, + platform_deps], include_directories : [inc_common, next_client_inc], link_args : link_args, link_with: mangohud_static_lib, @@ -297,7 +337,8 @@ if get_option('mangoapp') dep_wayland_client, glfw3_dep, xi_dep, - implot_dep + implot_dep, + platform_deps ], include_directories : [inc_common], install_tag : 'mangoapp', From 80a13ceeffd0986a1c17145d372b956db32bca8d Mon Sep 17 00:00:00 2001 From: Renkoto Date: Tue, 17 Nov 2026 19:47:20 +0000 Subject: [PATCH 31/33] hud_elements: pop frame_timing's font and style color on every platform --- src/hud_elements.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hud_elements.cpp b/src/hud_elements.cpp index 845b66d5ab..44fa908fb4 100644 --- a/src/hud_elements.cpp +++ b/src/hud_elements.cpp @@ -1005,9 +1005,9 @@ void HudElements::frame_timing(){ ImGui::Text("Thermal throttling"); } } +#endif ImGui::PopFont(); ImGui::PopStyleColor(); -#endif } } From 5632b446c73aed6204348d1c3499b33353c9b84f Mon Sep 17 00:00:00 2001 From: Renkoto Date: Tue, 17 Nov 2026 19:56:18 +0000 Subject: [PATCH 32/33] meson: don't pass -static-libstdc++ with libc++ --- src/meson.build | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/meson.build b/src/meson.build index 3a3d971d30..dfc0c52c0a 100644 --- a/src/meson.build +++ b/src/meson.build @@ -214,7 +214,11 @@ if is_unixy endif endif -link_args = cc.get_supported_link_arguments(['-Wl,-Bsymbolic-functions', '-Wl,-z,relro', '-Wl,--exclude-libs,ALL', '-lGL', '-static-libstdc++']) +link_args = cc.get_supported_link_arguments(['-Wl,-Bsymbolic-functions', '-Wl,-z,relro', '-Wl,--exclude-libs,ALL', '-lGL']) +# libc++ is not libstdc++, clang only warns that the flag is unused +if not cpp.has_header_symbol('version', '_LIBCPP_VERSION') + link_args += cc.get_supported_link_arguments(['-static-libstdc++']) +endif if is_freebsd # lld refuses version scripts naming symbols that aren't defined link_args += cc.get_supported_link_arguments(['-Wl,--undefined-version']) From 27694febe9b0722cacc93e6b02ed029a3c30fd58 Mon Sep 17 00:00:00 2001 From: Renkoto Date: Tue, 17 Nov 2026 19:56:18 +0000 Subject: [PATCH 33/33] meson: keep the libraries loaded on FreeBSD --- src/meson.build | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/meson.build b/src/meson.build index dfc0c52c0a..496d9cb0d1 100644 --- a/src/meson.build +++ b/src/meson.build @@ -220,8 +220,9 @@ if not cpp.has_header_symbol('version', '_LIBCPP_VERSION') link_args += cc.get_supported_link_arguments(['-static-libstdc++']) endif if is_freebsd - # lld refuses version scripts naming symbols that aren't defined - link_args += cc.get_supported_link_arguments(['-Wl,--undefined-version']) + # lld refuses version scripts naming symbols that aren't defined, and libc + # skips the thread_local destructors of an unloaded library, so keep it loaded + link_args += cc.get_supported_link_arguments(['-Wl,--undefined-version', '-Wl,-z,nodelete']) endif # meson fails to check version-script so just force add link_args += '-Wl,--version-script,@0@'.format(join_paths(meson.current_source_dir(), 'mangohud.version'))