From 98bcd01f0385100e7f35e0bead61d17b7d1e58c3 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Thu, 20 Aug 2026 08:47:58 +0200 Subject: [PATCH 01/40] add an optional RAPL TPMI path for reading the package energy PCM_USE_TPMI_RAPL=1 makes PCM read the package (socket) energy through the architectural RAPL TPMI interface instead of MSR_PKG_ENERGY_STATUS, see RAPL_TPMI_public_disclosure_FINAL-rev3.pdf in https://github.com/intel/tpmi_power_management PCM::initPackageEnergyTPMI enumerates the RAPL domains (128 byte register blocks) of every entry of every TPMI instance, selects the domains with DOMAIN_HEADER.TYPE = package, maps the TPMI instances to sockets through their NUMA node and derives the energy/power units and the package power info from the POWER_UNIT and PL_INFO registers of the domain. It falls back to the MSR-based counters if the package RAPL domain can not be found on every socket. TPMIHandle gets a getEntrySize() method to report the size of a TPMI entry which is needed to enumerate the RAPL domains of an entry. Two out-of-range accesses in the driver-based TPMI implementation (a requested TPMI ID that the instance does not implement and an offset outside of the entry) now throw instead of relying on an assert. Co-Authored-By: Claude Opus 5 (1M context) --- doc/ENVVAR_README.md | 4 + src/cpucounters.cpp | 186 ++++++++++++++++++++++++++++++++++++++++++- src/cpucounters.h | 21 +++++ src/tpmi.cpp | 36 ++++++++- src/tpmi.h | 3 + src/width_extender.h | 21 +++++ 6 files changed, 269 insertions(+), 2 deletions(-) diff --git a/doc/ENVVAR_README.md b/doc/ENVVAR_README.md index cba089ca..c9013e82 100644 --- a/doc/ENVVAR_README.md +++ b/doc/ENVVAR_README.md @@ -14,6 +14,10 @@ `PCM_ENFORCE_MBM=1` : force-enable Memory Bandwidth Monitoring (MBM) metrics (LocalMemoryBW = LMB) and (RemoteMemoryBW = RMB) on processors with RDT/MBM errata +`PCM_USE_TPMI_RAPL=1` : read the package (CPU socket) energy/power through the architectural RAPL TPMI interface instead of MSRs (default is to use MSRs). Requires a processor and BIOS supporting the RAPL TPMI feature (TPMI ID 0) and either the Linux TPMI driver (debugfs) or direct MMIO access. PCM falls back to MSRs if the package RAPL TPMI domain can not be found on every socket. The RAPL TPMI interface is described in https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf + +`PCM_NO_TPMI_DRIVER=1` : don't use the Linux TPMI driver (debugfs) to access TPMI registers, access them through MMIO instead + `PCM_QUIET=1` : enable quiet mode for PCM initialization. In quiet mode, only error messages are output during PCM initialization, suppressing informational output such as processor information and topology details `PCM_DEBUG_LEVEL=x` : x is an integer defining debug output level. level = 0 (default): minimal or no debug info, > 0 increases verbosity diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 3b45a179..5baa41ef 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1725,6 +1725,183 @@ bool PCM::detectNominalFrequency() return true; } +constexpr auto PCM_USE_TPMI_RAPL_STR = "PCM_USE_TPMI_RAPL"; + +bool PCM::initPackageEnergyTPMI() +{ + if (safe_getenv(PCM_USE_TPMI_RAPL_STR) != std::string("1")) + { + return false; // MSR-based package energy monitoring (default) + } + + if (energy_status.empty() == false && packageEnergyTPMI == false) + { + return false; // MSR-based package energy counters have been initialized already + } + + size_t nInstances = 0; + try { + nInstances = TPMIHandle::getNumInstances(); + } + catch (std::exception & e) + { + std::cerr << "ERROR: Could not detect TPMI instances. Exception details: " << e.what() << "\n"; + nInstances = 0; + } + DBG(1, "RAPL TPMI: TPMI instances detected: ", nInstances); + if (nInstances == 0) + { + std::cerr << "ERROR: No TPMI instances detected: can not use the RAPL TPMI interface. Falling back to MSRs.\n"; + return false; + } + + // ENERGY_STATUS register handle, POWER_UNIT and PL_INFO register values of the package RAPL domain of every socket + struct PackageRAPLDomain + { + std::shared_ptr energyStatus{}; + size_t entry{0}; + uint64 powerUnit{0ULL}; + uint64 plInfo{0ULL}; + bool plInfoValid{false}; + }; + std::vector packageDomain(num_sockets); + + for (uint32 instance = 0; instance < (uint32)nInstances; ++instance) + { + try { + TPMIHandle firstDomainHeader(instance, RAPL_TPMI_ID, RAPL_TPMI_DOMAIN_HEADER * sizeof(uint64)); + const auto nEntries = firstDomainHeader.getNumEntries(); + if (nEntries == 0) + { + DBG(1, "RAPL TPMI: instance ", instance, " does not implement the RAPL TPMI ID"); + continue; + } + // the register block of every TPMI entry (punit) holds an array of RAPL domains + const auto entrySize = firstDomainHeader.getEntrySize(); + const size_t nDomains = (entrySize >= RAPL_TPMI_DOMAIN_SIZE) ? (entrySize / RAPL_TPMI_DOMAIN_SIZE) : 1; + DBG(1, "RAPL TPMI: instance ", instance, " entries: ", nEntries, " entry size: ", entrySize, " domains: ", nDomains); + + uint32 socket = 0; + const auto numaNode = firstDomainHeader.getNUMANode(); + const auto socketTmp = (numaNode >= 0) ? mapNUMANodeToSocket(numaNode) : -1; + DBG(1, "RAPL TPMI: instance ", instance, " NUMA node: ", numaNode, " socket: ", socketTmp); + if (socketTmp >= 0 && socketTmp < (int32)num_sockets) + { + socket = (uint32)socketTmp; + } + else + { + std::cerr << "WARNING: Could not map RAPL TPMI instance " << instance << " (NUMA node " << numaNode << ") to a socket. Assuming socket 0.\n"; + } + + for (size_t domain = 0; domain < nDomains; ++domain) + { + const auto domainOffset = domain * (size_t)RAPL_TPMI_DOMAIN_SIZE; + TPMIHandle domainHeader(instance, RAPL_TPMI_ID, domainOffset + RAPL_TPMI_DOMAIN_HEADER * sizeof(uint64)); + for (size_t entry = 0; entry < domainHeader.getNumEntries(); ++entry) + { + const auto header = domainHeader.read64(entry); + if (header == ~0ULL || header == 0ULL) + { + DBG(2, "RAPL TPMI: instance ", instance, " entry ", entry, " domain ", domain, ": invalid domain header"); + continue; + } + const auto type = extract_bits_64(header, 15, 8); + const auto flags = extract_bits_64(header, 47, 32); + DBG(1, "RAPL TPMI: instance ", instance, " entry ", entry, " domain ", domain, + ": interface version ", extract_bits_64(header, 7, 0), + " type ", type, + " size ", extract_bits_64(header, 23, 16), + " flags 0x", std::hex, flags, std::dec); + if (type != RAPL_TPMI_DOMAIN_TYPE_PACKAGE) + { + continue; // not a package (socket) RAPL domain + } + if ((flags & (1ULL << RAPL_TPMI_ENERGY_STATUS)) == 0 || (flags & (1ULL << RAPL_TPMI_POWER_UNIT)) == 0) + { + std::cerr << "WARNING: RAPL TPMI package domain " << domain << " of TPMI instance " << instance << + " does not support the ENERGY_STATUS and/or POWER_UNIT register (flags 0x" << std::hex << flags << std::dec << ").\n"; + continue; + } + if (packageDomain[socket].energyStatus.get() != nullptr) + { + // the package RAPL registers are package-scoped and therefore replicated in every punit of the package + DBG(1, "RAPL TPMI: ignoring the redundant package domain ", domain, " of entry ", entry, + " in TPMI instance ", instance, ": socket ", socket, " has been initialized already"); + continue; + } + PackageRAPLDomain d; + d.entry = entry; + TPMIHandle powerUnitHandle(instance, RAPL_TPMI_ID, domainOffset + RAPL_TPMI_POWER_UNIT * sizeof(uint64)); + d.powerUnit = powerUnitHandle.read64(entry); + if (flags & (1ULL << RAPL_TPMI_PL_INFO)) + { + TPMIHandle plInfoHandle(instance, RAPL_TPMI_ID, domainOffset + RAPL_TPMI_PL_INFO * sizeof(uint64)); + d.plInfo = plInfoHandle.read64(entry); + d.plInfoValid = true; + } + d.energyStatus = std::make_shared(instance, RAPL_TPMI_ID, domainOffset + RAPL_TPMI_ENERGY_STATUS * sizeof(uint64)); + packageDomain[socket] = d; + DBG(1, "RAPL TPMI: socket ", socket, " package energy counter: instance ", instance, " entry ", entry, " domain ", domain); + } + } + } + catch (std::exception & e) + { + DBG(1, "RAPL TPMI: could not access the RAPL registers of TPMI instance ", instance, ". Exception details: ", e.what()); + } + } + + for (uint32 socket = 0; socket < (uint32)num_sockets; ++socket) + { + if (packageDomain[socket].energyStatus.get() == nullptr) + { + std::cerr << "ERROR: Could not find the package RAPL TPMI domain of socket " << socket << + ". Falling back to MSR-based package energy metrics.\n"; + return false; + } + } + + // POWER_UNIT.ENERGY_UNIT: energy unit is 1/(2^ENERGY_UNIT) Joules + const double tpmiJoulesPerEnergyUnit = 1. / double(1ULL << extract_bits_64(packageDomain[0].powerUnit, 10, 6)); + // POWER_UNIT.PWR_UNIT: power unit is 1/(2^PWR_UNIT) Watts + const double wattsPerPowerUnit = 1. / double(1ULL << extract_bits_64(packageDomain[0].powerUnit, 3, 0)); + DBG(2, "RAPL TPMI POWER_UNIT: 0x", std::hex, packageDomain[0].powerUnit, std::dec, "; Joules/unit ", tpmiJoulesPerEnergyUnit); + if (tpmiJoulesPerEnergyUnit != joulesPerEnergyUnit) + { + std::cerr << "WARNING: the RAPL TPMI energy unit (" << tpmiJoulesPerEnergyUnit << + " Joules) differs from the MSR-based energy unit (" << joulesPerEnergyUnit << " Joules).\n"; + } + joulesPerEnergyUnit = tpmiJoulesPerEnergyUnit; + + if (packageDomain[0].plInfoValid) + { + // PL_INFO: MAX_PL1 (TDP) in bits 17:0, MIN_PL in bits 35:18, MAX_PL2 in bits 53:36 + pkgThermalSpecPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 17, 0)) * wattsPerPowerUnit); + pkgMinimumPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 35, 18)) * wattsPerPowerUnit); + pkgMaximumPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 53, 36)) * wattsPerPowerUnit); + } + + if (energy_status.empty()) + { + for (const auto & d : packageDomain) + { + // ENERGY_STATUS.ENERGY is a 32-bit wrapping counter in bits 31:0 (bits 63:32 hold a timestamp) + energy_status.push_back(std::make_shared( + new CounterWidthExtender::TPMICounter(d.energyStatus, d.entry, 0x00000000FFFFFFFFULL), 32, 10000)); + } + } + packageEnergyTPMI = true; + +#ifndef PCM_SILENT + if (!quietMode) + { + std::cerr << "Reading the package energy through the RAPL TPMI interface (" << PCM_USE_TPMI_RAPL_STR << "=1).\n"; + } +#endif + return true; +} + void PCM::initEnergyMonitoring() { if(packageEnergyMetricsAvailable() && MSR.size()) @@ -1746,6 +1923,13 @@ void PCM::initEnergyMonitoring() pkgMinimumPower = (int32) (double(extract_bits(package_power_info, 16, 30))*wattsPerPowerUnit); pkgMaximumPower = (int32) (double(extract_bits(package_power_info, 32, 46))*wattsPerPowerUnit); + // optional alternative path: read the package energy through the architectural RAPL TPMI + // interface instead of MSRs (it also updates the energy unit and the package power info above) + if (initPackageEnergyTPMI()) + { + DBG(1, "Using the RAPL TPMI interface for package energy metrics"); + } + #ifndef PCM_SILENT if (!quietMode) { @@ -1757,7 +1941,7 @@ void PCM::initEnergyMonitoring() int i = 0; - if(energy_status.empty()) + if (energy_status.empty()) for (i = 0; i < (int)num_sockets; ++i) energy_status.push_back( std::make_shared( diff --git a/src/cpucounters.h b/src/cpucounters.h index c1498132..60038bd4 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -662,6 +662,23 @@ class PCM_API PCM }; std::vector > UFSStatus; + // architectural RAPL TPMI interface, see + // https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf + enum RAPL_TPMI + { + RAPL_TPMI_ID = 0, + RAPL_TPMI_DOMAIN_SIZE = 128, // size of the register block of a single RAPL domain in bytes + // indices of the registers inside of a RAPL domain register block: + RAPL_TPMI_DOMAIN_HEADER = 0, + RAPL_TPMI_POWER_UNIT = 1, + RAPL_TPMI_ENERGY_STATUS = 7, + RAPL_TPMI_PL_INFO = 9, + // RAPL domain types (DOMAIN_HEADER.TYPE): + RAPL_TPMI_DOMAIN_TYPE_SYSTEM = 1, + RAPL_TPMI_DOMAIN_TYPE_PACKAGE = 2, + RAPL_TPMI_DOMAIN_TYPE_MEMORY = 4 + }; + std::vector topology; mutable std::unordered_map numaNodeToSocketCache; // Cache for mapNUMANodeToSocket mutable pcm::Mutex numaNodeToSocketCacheMutex; // Mutex to protect cache access @@ -829,6 +846,7 @@ class PCM_API PCM std::vector > idxPMUs; double joulesPerEnergyUnit; + bool packageEnergyTPMI{false}; // package energy is read through the RAPL TPMI interface (instead of MSRs) std::vector > energy_status; std::vector > dram_energy_status; std::vector > pp_energy_status; @@ -1201,6 +1219,9 @@ class PCM_API PCM bool detectNominalFrequency(); void showSpecControlMSRs(); void initEnergyMonitoring(); + //! \brief initializes the package energy counters using the architectural RAPL TPMI interface (instead of MSRs) + //! \return true if the package energy counters of all sockets have been initialized successfully + bool initPackageEnergyTPMI(); void initUncoreObjects(); /*! * \brief initializes each core with an RMID diff --git a/src/tpmi.cpp b/src/tpmi.cpp index c3dd837f..5080d534 100644 --- a/src/tpmi.cpp +++ b/src/tpmi.cpp @@ -28,6 +28,7 @@ class PFSInstances struct PFSInstance { PFSMapType pfsMap{}; // [TPMI ID][entry] -> base address + std::unordered_map entrySizeMap{}; // [TPMI ID] -> entry size in bytes int32 NUMANode{-1}; }; typedef std::vector PFSInstancesType; @@ -84,6 +85,7 @@ class PFSInstances "\t Attribute: " << pfs.Attribute << "\n"; } + PFSInstancesSingletonInit->back().entrySizeMap[pfs.TPMI_ID] = pfs.EntrySize * sizeof(uint32); DBG(1, " PFS TPMI_ID: ", pfs.TPMI_ID, " NumEntries: ", pfs.NumEntries, " EntrySize: ", pfs.EntrySize, @@ -158,6 +160,7 @@ class TPMIHandleMMIO : public TPMIHandleInterface }; std::vector entries; int32 numaNode{-1}; + size_t entrySize{0}; public: static size_t getNumInstances(); static void setVerbose(const bool); @@ -166,6 +169,10 @@ class TPMIHandleMMIO : public TPMIHandleInterface { return entries.size(); } + size_t getEntrySize() const override + { + return entrySize; + } uint64 read64(size_t entryPos) override; void write64(size_t entryPos, uint64 val) override; int32 getNUMANode() override @@ -189,6 +196,12 @@ TPMIHandleMMIO::TPMIHandleMMIO(const size_t instance_, const size_t ID_, const s auto & pfsInstances = PFSInstances::get(); assert(instance_ < pfsInstances.size()); numaNode = pfsInstances[instance_].NUMANode; + const auto & entrySizeMap = pfsInstances[instance_].entrySizeMap; + const auto entrySizeIter = entrySizeMap.find(ID_); + if (entrySizeIter != entrySizeMap.end()) + { + entrySize = entrySizeIter->second; + } for (const auto & addr: pfsInstances[instance_].pfsMap[ID_]) { const auto requestedAddr = addr + requestedRelativeOffset; @@ -232,6 +245,7 @@ class TPMIHandleDriver : public TPMIHandleInterface int32 numaNode{ -1 }; // const bool readonly; // not used size_t nentries; + size_t entrySize{0}; struct TPMIEntry { unsigned int offset{0}; std::vector data; @@ -313,6 +327,10 @@ class TPMIHandleDriver : public TPMIHandleInterface { assert(available > 0); assert(instance < getNumInstances()); + if (AllIDPaths[instance].find(ID) == AllIDPaths[instance].end()) + { + throw std::runtime_error("TPMI ID " + std::to_string(ID) + " is not available in TPMI instance " + std::to_string(instance)); + } const auto path = AllIDPaths[instance][ID]; const auto entries = readTPMIFile(path); for (auto & e: entries) @@ -321,6 +339,7 @@ class TPMIHandleDriver : public TPMIHandleInterface { // count valid entries ++nentries; + entrySize = (std::max)(entrySize, e.data.size() * sizeof(uint32)); } } // path is like /sys/kernel/debug/tpmi-0000:80:03.1/tpmi-id-0a @@ -353,6 +372,11 @@ class TPMIHandleDriver : public TPMIHandleInterface assert(available > 0); return nentries; } + size_t getEntrySize() const override + { + assert(available > 0); + return entrySize; + } uint64 read64(size_t entryPos) override { assert(available > 0); @@ -361,7 +385,11 @@ class TPMIHandleDriver : public TPMIHandleInterface size_t i = findValidIndex(entries, entryPos); cvt_ds result; const auto i4 = offset / 4; - assert(i4 + 1 < entries[i].data.size()); + if (i4 + 1 >= entries[i].data.size()) + { + throw std::runtime_error("TPMI offset " + std::to_string(offset) + " is out of range of TPMI ID " + + std::to_string(ID) + " entry " + std::to_string(i)); + } result.ui32.low = entries[i].data[i4]; result.ui32.high = entries[i].data[i4 + 1]; return result.ui64; @@ -469,6 +497,12 @@ size_t TPMIHandle::getNumEntries() const return impl->getNumEntries(); } +size_t TPMIHandle::getEntrySize() const +{ + assert(impl.get()); + return impl->getEntrySize(); +} + uint64 TPMIHandle::read64(size_t entryPos) { assert(impl.get()); diff --git a/src/tpmi.h b/src/tpmi.h index 09223f26..b54846ba 100644 --- a/src/tpmi.h +++ b/src/tpmi.h @@ -19,6 +19,8 @@ class TPMIHandleInterface { public: virtual size_t getNumEntries() const = 0; + //! \brief Returns the size of a single TPMI entry (instance) in bytes, 0 if unknown + virtual size_t getEntrySize() const = 0; virtual uint64 read64(size_t entryPos) = 0; virtual void write64(size_t entryPos, uint64 val) = 0; virtual int32 getNUMANode() = 0; @@ -35,6 +37,7 @@ class TPMIHandle : public TPMIHandleInterface static void setVerbose(const bool); TPMIHandle(const size_t instance_, const size_t ID_, const size_t offset_, const bool readonly_ = true); size_t getNumEntries() const override; + size_t getEntrySize() const override; uint64 read64(size_t entryPos) override; void write64(size_t entryPos, uint64 val) override; int32 getNUMANode() override; diff --git a/src/width_extender.h b/src/width_extender.h index 1043667c..014e2910 100644 --- a/src/width_extender.h +++ b/src/width_extender.h @@ -15,6 +15,7 @@ #include "utils.h" #include "bw.h" #include "mutex.h" +#include "tpmi.h" #include #ifndef _MSC_VER // the header can not be included into code using CLR @@ -57,6 +58,26 @@ class CounterWidthExtender } }; + //! \brief Raw counter reading a 64-bit TPMI register (see tpmi.h) + struct TPMICounter : public AbstractRawCounter + { + std::shared_ptr tpmiHandle; + size_t entryPos; + uint64 mask; + TPMICounter(const std::shared_ptr & tpmiHandle_, + const size_t entryPos_, + const uint64 mask_ = ~uint64(0ULL)) : + tpmiHandle(tpmiHandle_), + entryPos(entryPos_), + mask(mask_) + { + } + uint64 operator () () + { + return tpmiHandle->read64(entryPos) & mask; + } + }; + template struct ClientImcCounter : public AbstractRawCounter { From 14e459d0ff37ce032a8b7942692fb4b107ff39bb Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Thu, 20 Aug 2026 09:25:49 +0200 Subject: [PATCH 02/40] read also the DRAM energy through the RAPL TPMI interface PCM_USE_TPMI_RAPL=1 now additionally replaces MSR_DRAM_ENERGY_STATUS with the ENERGY_STATUS register of the memory RAPL TPMI domain (domain type 4). The energy unit of the DRAM domain is taken from the POWER_UNIT register of that domain, so PCM::getDRAMJoulesPerEnergyUnit() is used for the DRAM domain now (it returns the package energy unit as before when no separate DRAM unit is known). The domain discovery in PCM::initRAPLTPMI (renamed from initPackageEnergyTPMI) collects the package and the memory domain of every socket in one pass. The DRAM part falls back to MSRs on its own if the memory RAPL domain is not present on every socket. Co-Authored-By: Claude Opus 5 (1M context) --- doc/ENVVAR_README.md | 2 +- src/cpucounters.cpp | 88 ++++++++++++++++++++++++++++++++++---------- src/cpucounters.h | 14 +++++-- 3 files changed, 79 insertions(+), 25 deletions(-) diff --git a/doc/ENVVAR_README.md b/doc/ENVVAR_README.md index c9013e82..09a80e37 100644 --- a/doc/ENVVAR_README.md +++ b/doc/ENVVAR_README.md @@ -14,7 +14,7 @@ `PCM_ENFORCE_MBM=1` : force-enable Memory Bandwidth Monitoring (MBM) metrics (LocalMemoryBW = LMB) and (RemoteMemoryBW = RMB) on processors with RDT/MBM errata -`PCM_USE_TPMI_RAPL=1` : read the package (CPU socket) energy/power through the architectural RAPL TPMI interface instead of MSRs (default is to use MSRs). Requires a processor and BIOS supporting the RAPL TPMI feature (TPMI ID 0) and either the Linux TPMI driver (debugfs) or direct MMIO access. PCM falls back to MSRs if the package RAPL TPMI domain can not be found on every socket. The RAPL TPMI interface is described in https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf +`PCM_USE_TPMI_RAPL=1` : read the package (CPU socket) and DRAM energy/power through the architectural RAPL TPMI interface instead of MSRs (default is to use MSRs). Requires a processor and BIOS supporting the RAPL TPMI feature (TPMI ID 0) and either the Linux TPMI driver (debugfs) or direct MMIO access. PCM falls back to MSRs if the package RAPL TPMI domain can not be found on every socket (and, independently, to MSR-based DRAM energy metrics if the memory RAPL TPMI domain can not be found on every socket). The RAPL TPMI interface is described in https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf `PCM_NO_TPMI_DRIVER=1` : don't use the Linux TPMI driver (debugfs) to access TPMI registers, access them through MMIO instead diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 5baa41ef..7515b344 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1727,7 +1727,7 @@ bool PCM::detectNominalFrequency() constexpr auto PCM_USE_TPMI_RAPL_STR = "PCM_USE_TPMI_RAPL"; -bool PCM::initPackageEnergyTPMI() +bool PCM::initRAPLTPMI() { if (safe_getenv(PCM_USE_TPMI_RAPL_STR) != std::string("1")) { @@ -1755,8 +1755,8 @@ bool PCM::initPackageEnergyTPMI() return false; } - // ENERGY_STATUS register handle, POWER_UNIT and PL_INFO register values of the package RAPL domain of every socket - struct PackageRAPLDomain + // ENERGY_STATUS register handle, POWER_UNIT and PL_INFO register values of a RAPL domain + struct RAPLDomain { std::shared_ptr energyStatus{}; size_t entry{0}; @@ -1764,7 +1764,9 @@ bool PCM::initPackageEnergyTPMI() uint64 plInfo{0ULL}; bool plInfoValid{false}; }; - std::vector packageDomain(num_sockets); + // the package and memory (DRAM) RAPL domain of every socket + std::vector packageDomain(num_sockets), memoryDomain(num_sockets); + const bool findMemoryDomains = dramEnergyMetricsAvailable(); for (uint32 instance = 0; instance < (uint32)nInstances; ++instance) { @@ -1813,24 +1815,36 @@ bool PCM::initPackageEnergyTPMI() " type ", type, " size ", extract_bits_64(header, 23, 16), " flags 0x", std::hex, flags, std::dec); - if (type != RAPL_TPMI_DOMAIN_TYPE_PACKAGE) + RAPLDomain * target = nullptr; + const char * domainName = nullptr; + if (type == RAPL_TPMI_DOMAIN_TYPE_PACKAGE) { - continue; // not a package (socket) RAPL domain + target = &(packageDomain[socket]); + domainName = "package"; + } + else if (type == RAPL_TPMI_DOMAIN_TYPE_MEMORY && findMemoryDomains) + { + target = &(memoryDomain[socket]); + domainName = "memory"; + } + if (target == nullptr) + { + continue; // not a RAPL domain we are interested in } if ((flags & (1ULL << RAPL_TPMI_ENERGY_STATUS)) == 0 || (flags & (1ULL << RAPL_TPMI_POWER_UNIT)) == 0) { - std::cerr << "WARNING: RAPL TPMI package domain " << domain << " of TPMI instance " << instance << + std::cerr << "WARNING: RAPL TPMI " << domainName << " domain " << domain << " of TPMI instance " << instance << " does not support the ENERGY_STATUS and/or POWER_UNIT register (flags 0x" << std::hex << flags << std::dec << ").\n"; continue; } - if (packageDomain[socket].energyStatus.get() != nullptr) + if (target->energyStatus.get() != nullptr) { - // the package RAPL registers are package-scoped and therefore replicated in every punit of the package - DBG(1, "RAPL TPMI: ignoring the redundant package domain ", domain, " of entry ", entry, + // the RAPL registers are package-scoped and therefore replicated in every punit of the package + DBG(1, "RAPL TPMI: ignoring the redundant ", domainName, " domain ", domain, " of entry ", entry, " in TPMI instance ", instance, ": socket ", socket, " has been initialized already"); continue; } - PackageRAPLDomain d; + RAPLDomain d; d.entry = entry; TPMIHandle powerUnitHandle(instance, RAPL_TPMI_ID, domainOffset + RAPL_TPMI_POWER_UNIT * sizeof(uint64)); d.powerUnit = powerUnitHandle.read64(entry); @@ -1841,8 +1855,8 @@ bool PCM::initPackageEnergyTPMI() d.plInfoValid = true; } d.energyStatus = std::make_shared(instance, RAPL_TPMI_ID, domainOffset + RAPL_TPMI_ENERGY_STATUS * sizeof(uint64)); - packageDomain[socket] = d; - DBG(1, "RAPL TPMI: socket ", socket, " package energy counter: instance ", instance, " entry ", entry, " domain ", domain); + *target = d; + DBG(1, "RAPL TPMI: socket ", socket, " ", domainName, " energy counter: instance ", instance, " entry ", entry, " domain ", domain); } } } @@ -1882,21 +1896,54 @@ bool PCM::initPackageEnergyTPMI() pkgMaximumPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 53, 36)) * wattsPerPowerUnit); } + // ENERGY_STATUS.ENERGY is a 32-bit wrapping counter in bits 31:0 (bits 63:32 hold a timestamp) + auto makeEnergyCounter = [](const RAPLDomain & d) + { + return std::make_shared( + new CounterWidthExtender::TPMICounter(d.energyStatus, d.entry, 0x00000000FFFFFFFFULL), 32, 10000); + }; + if (energy_status.empty()) { for (const auto & d : packageDomain) { - // ENERGY_STATUS.ENERGY is a 32-bit wrapping counter in bits 31:0 (bits 63:32 hold a timestamp) - energy_status.push_back(std::make_shared( - new CounterWidthExtender::TPMICounter(d.energyStatus, d.entry, 0x00000000FFFFFFFFULL), 32, 10000)); + energy_status.push_back(makeEnergyCounter(d)); } } packageEnergyTPMI = true; + // don't use the TPMI energy unit of the memory domain if the MSR-based DRAM counters are in use already + bool memoryDomainsFound = findMemoryDomains && (dram_energy_status.empty() || dramEnergyTPMI); + for (uint32 socket = 0; memoryDomainsFound && socket < (uint32)num_sockets; ++socket) + { + if (memoryDomain[socket].energyStatus.get() == nullptr) + { + std::cerr << "WARNING: Could not find the memory (DRAM) RAPL TPMI domain of socket " << socket << + ". Falling back to MSR-based DRAM energy metrics.\n"; + memoryDomainsFound = false; + } + } + if (memoryDomainsFound) + { + // the memory RAPL domain has its own POWER_UNIT register + dramJoulesPerEnergyUnit = 1. / double(1ULL << extract_bits_64(memoryDomain[0].powerUnit, 10, 6)); + DBG(2, "RAPL TPMI memory domain POWER_UNIT: 0x", std::hex, memoryDomain[0].powerUnit, std::dec, + "; Joules/unit ", dramJoulesPerEnergyUnit); + if (dram_energy_status.empty()) + { + for (const auto & d : memoryDomain) + { + dram_energy_status.push_back(makeEnergyCounter(d)); + } + } + dramEnergyTPMI = true; + } + #ifndef PCM_SILENT if (!quietMode) { - std::cerr << "Reading the package energy through the RAPL TPMI interface (" << PCM_USE_TPMI_RAPL_STR << "=1).\n"; + std::cerr << "Reading the package " << (memoryDomainsFound ? "and DRAM " : "") << + "energy through the RAPL TPMI interface (" << PCM_USE_TPMI_RAPL_STR << "=1).\n"; } #endif return true; @@ -1913,6 +1960,7 @@ void PCM::initEnergyMonitoring() joulesPerEnergyUnit = double(1ULL << energy_status_unit)/1000000.; // (2)^energy_status_unit microJoules else joulesPerEnergyUnit = 1./double(1ULL< > idxPMUs; double joulesPerEnergyUnit; + double dramJoulesPerEnergyUnit{0.}; // energy unit of the DRAM domain (usually the same as joulesPerEnergyUnit) bool packageEnergyTPMI{false}; // package energy is read through the RAPL TPMI interface (instead of MSRs) + bool dramEnergyTPMI{false}; // DRAM energy is read through the RAPL TPMI interface (instead of MSRs) std::vector > energy_status; std::vector > dram_energy_status; std::vector > pp_energy_status; @@ -1219,9 +1221,9 @@ class PCM_API PCM bool detectNominalFrequency(); void showSpecControlMSRs(); void initEnergyMonitoring(); - //! \brief initializes the package energy counters using the architectural RAPL TPMI interface (instead of MSRs) + //! \brief initializes the package and DRAM energy counters using the architectural RAPL TPMI interface (instead of MSRs) //! \return true if the package energy counters of all sockets have been initialized successfully - bool initPackageEnergyTPMI(); + bool initRAPLTPMI(); void initUncoreObjects(); /*! * \brief initializes each core with an RMID @@ -2413,6 +2415,9 @@ class PCM_API PCM //! \brief Returns how many joules are in an internal processor energy unit double getJoulesPerEnergyUnit() const { return joulesPerEnergyUnit; } + //! \brief Returns how many joules are in an internal energy unit of the DRAM domain + double getDRAMJoulesPerEnergyUnit() const { return (dramJoulesPerEnergyUnit != 0.) ? dramJoulesPerEnergyUnit : joulesPerEnergyUnit; } + //! \brief Returns thermal specification power of the package domain in Watt int32 getPackageThermalSpecPower() const { return pkgThermalSpecPower; } @@ -3720,9 +3725,10 @@ double getDRAMConsumedJoules(const CounterStateType & before, const CounterState dram_joules_per_energy_unit = 0.0000153; } else { /* for all other processors (including Haswell client/mobile SKUs) the ENERGY_UNIT for DRAM domain - * should be read from PACKAGE_POWER_SKU register (usually value around ~61uJ) + * should be read from PACKAGE_POWER_SKU register (usually value around ~61uJ) or, if the RAPL TPMI + * interface is used, from the POWER_UNIT register of the memory RAPL domain */ - dram_joules_per_energy_unit = m->getJoulesPerEnergyUnit(); + dram_joules_per_energy_unit = m->getDRAMJoulesPerEnergyUnit(); } return double(getDRAMConsumedEnergy(before, after)) * dram_joules_per_energy_unit; } From 6e3681f883e8ab04a72ef2c16b12fbef45f308fc Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Thu, 20 Aug 2026 09:33:14 +0200 Subject: [PATCH 03/40] read also the system energy through the RAPL TPMI interface PCM_USE_TPMI_RAPL=1 now additionally replaces MSR_SYS_ENERGY_STATUS with the ENERGY_STATUS register of the system (platform) RAPL TPMI domain (domain type 1) of socket 0, mirroring the MSR-based counter which is also read on socket 0 only. On GNR the register of the system TPMI domain reports the same raw values as MSR_SYS_ENERGY_STATUS, therefore the energy unit handling of getSystemConsumedJoules stays unchanged. The system energy metric falls back to the MSR-based counter on its own if the system RAPL domain is not present. Co-Authored-By: Claude Opus 5 (1M context) --- doc/ENVVAR_README.md | 2 +- src/cpucounters.cpp | 34 ++++++++++++++++++++++++++++++---- src/cpucounters.h | 3 ++- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/doc/ENVVAR_README.md b/doc/ENVVAR_README.md index 09a80e37..31793a46 100644 --- a/doc/ENVVAR_README.md +++ b/doc/ENVVAR_README.md @@ -14,7 +14,7 @@ `PCM_ENFORCE_MBM=1` : force-enable Memory Bandwidth Monitoring (MBM) metrics (LocalMemoryBW = LMB) and (RemoteMemoryBW = RMB) on processors with RDT/MBM errata -`PCM_USE_TPMI_RAPL=1` : read the package (CPU socket) and DRAM energy/power through the architectural RAPL TPMI interface instead of MSRs (default is to use MSRs). Requires a processor and BIOS supporting the RAPL TPMI feature (TPMI ID 0) and either the Linux TPMI driver (debugfs) or direct MMIO access. PCM falls back to MSRs if the package RAPL TPMI domain can not be found on every socket (and, independently, to MSR-based DRAM energy metrics if the memory RAPL TPMI domain can not be found on every socket). The RAPL TPMI interface is described in https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf +`PCM_USE_TPMI_RAPL=1` : read the package (CPU socket), DRAM and system (platform) energy/power through the architectural RAPL TPMI interface instead of MSRs (default is to use MSRs). Requires a processor and BIOS supporting the RAPL TPMI feature (TPMI ID 0) and either the Linux TPMI driver (debugfs) or direct MMIO access. PCM falls back to MSRs if the package RAPL TPMI domain can not be found on every socket. The DRAM and system energy metrics fall back to MSRs independently of each other if their RAPL TPMI domains (memory and system) are not found. The RAPL TPMI interface is described in https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf `PCM_NO_TPMI_DRIVER=1` : don't use the Linux TPMI driver (debugfs) to access TPMI registers, access them through MMIO instead diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 7515b344..84ecb6de 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1764,9 +1764,10 @@ bool PCM::initRAPLTPMI() uint64 plInfo{0ULL}; bool plInfoValid{false}; }; - // the package and memory (DRAM) RAPL domain of every socket - std::vector packageDomain(num_sockets), memoryDomain(num_sockets); + // the package, memory (DRAM) and system (platform) RAPL domain of every socket + std::vector packageDomain(num_sockets), memoryDomain(num_sockets), systemDomain(num_sockets); const bool findMemoryDomains = dramEnergyMetricsAvailable(); + const bool findSystemDomains = systemEnergyMetricAvailable(); for (uint32 instance = 0; instance < (uint32)nInstances; ++instance) { @@ -1827,6 +1828,11 @@ bool PCM::initRAPLTPMI() target = &(memoryDomain[socket]); domainName = "memory"; } + else if (type == RAPL_TPMI_DOMAIN_TYPE_SYSTEM && findSystemDomains) + { + target = &(systemDomain[socket]); + domainName = "system"; + } if (target == nullptr) { continue; // not a RAPL domain we are interested in @@ -1939,11 +1945,31 @@ bool PCM::initRAPLTPMI() dramEnergyTPMI = true; } + // the system (platform) energy counter is a single counter read from socket 0, like the MSR-based one + if (findSystemDomains && (system_energy_status.get() == nullptr || systemEnergyTPMI)) + { + if (systemDomain[0].energyStatus.get() != nullptr) + { + if (system_energy_status.get() == nullptr) + { + system_energy_status = makeEnergyCounter(systemDomain[0]); + } + systemEnergyTPMI = true; + } + else + { + std::cerr << "WARNING: Could not find the system (platform) RAPL TPMI domain of socket 0." + " Falling back to MSR-based system energy metrics.\n"; + } + } + #ifndef PCM_SILENT if (!quietMode) { - std::cerr << "Reading the package " << (memoryDomainsFound ? "and DRAM " : "") << - "energy through the RAPL TPMI interface (" << PCM_USE_TPMI_RAPL_STR << "=1).\n"; + std::cerr << "Reading the package"; + if (dramEnergyTPMI) std::cerr << ", DRAM"; + if (systemEnergyTPMI) std::cerr << ", system"; + std::cerr << " energy through the RAPL TPMI interface (" << PCM_USE_TPMI_RAPL_STR << "=1).\n"; } #endif return true; diff --git a/src/cpucounters.h b/src/cpucounters.h index ba42ed04..7aac09d3 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -849,6 +849,7 @@ class PCM_API PCM double dramJoulesPerEnergyUnit{0.}; // energy unit of the DRAM domain (usually the same as joulesPerEnergyUnit) bool packageEnergyTPMI{false}; // package energy is read through the RAPL TPMI interface (instead of MSRs) bool dramEnergyTPMI{false}; // DRAM energy is read through the RAPL TPMI interface (instead of MSRs) + bool systemEnergyTPMI{false}; // system (platform) energy is read through the RAPL TPMI interface (instead of MSRs) std::vector > energy_status; std::vector > dram_energy_status; std::vector > pp_energy_status; @@ -1221,7 +1222,7 @@ class PCM_API PCM bool detectNominalFrequency(); void showSpecControlMSRs(); void initEnergyMonitoring(); - //! \brief initializes the package and DRAM energy counters using the architectural RAPL TPMI interface (instead of MSRs) + //! \brief initializes the package, DRAM and system energy counters using the architectural RAPL TPMI interface (instead of MSRs) //! \return true if the package energy counters of all sockets have been initialized successfully bool initRAPLTPMI(); void initUncoreObjects(); From cddd948cf07ca81f3a491e0470ce5ded45deebbd Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Thu, 20 Aug 2026 09:40:40 +0200 Subject: [PATCH 04/40] use the RAPL TPMI interface by default when it is available The package, DRAM and system energy metrics are read through the architectural RAPL TPMI interface whenever the RAPL TPMI feature is discovered on a server processor and fall back to the legacy RAPL MSRs otherwise. PCM_USE_TPMI_RAPL is replaced by PCM_NO_TPMI_RAPL=1 which disables the RAPL TPMI usage and enforces the legacy MSR interfaces. Since the fallback is a normal situation now (processors without the RAPL TPMI feature) it is reported through the debug output instead of error and warning messages. The RAPL TPMI discovery is skipped on client processors to avoid the TPMI/PCI enumeration there. Co-Authored-By: Claude Opus 5 (1M context) --- doc/ENVVAR_README.md | 2 +- src/cpucounters.cpp | 34 +++++++++++++++++++--------------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/doc/ENVVAR_README.md b/doc/ENVVAR_README.md index 31793a46..ac323f00 100644 --- a/doc/ENVVAR_README.md +++ b/doc/ENVVAR_README.md @@ -14,7 +14,7 @@ `PCM_ENFORCE_MBM=1` : force-enable Memory Bandwidth Monitoring (MBM) metrics (LocalMemoryBW = LMB) and (RemoteMemoryBW = RMB) on processors with RDT/MBM errata -`PCM_USE_TPMI_RAPL=1` : read the package (CPU socket), DRAM and system (platform) energy/power through the architectural RAPL TPMI interface instead of MSRs (default is to use MSRs). Requires a processor and BIOS supporting the RAPL TPMI feature (TPMI ID 0) and either the Linux TPMI driver (debugfs) or direct MMIO access. PCM falls back to MSRs if the package RAPL TPMI domain can not be found on every socket. The DRAM and system energy metrics fall back to MSRs independently of each other if their RAPL TPMI domains (memory and system) are not found. The RAPL TPMI interface is described in https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf +`PCM_NO_TPMI_RAPL=1` : don't use the architectural RAPL TPMI interface for the package (CPU socket), DRAM and system (platform) energy/power metrics, use the legacy RAPL MSRs instead. By default PCM uses the RAPL TPMI interface whenever it is available, i.e. on server processors exposing the RAPL TPMI feature (TPMI ID 0) either through the Linux TPMI driver (debugfs) or through direct MMIO access, and falls back to the legacy RAPL MSRs otherwise. The package, DRAM and system energy metrics fall back to the MSRs independently of each other if their RAPL TPMI domains (package, memory and system) are not found. The RAPL TPMI interface is described in https://github.com/intel/tpmi_power_management/blob/main/RAPL_TPMI_public_disclosure_FINAL-rev3.pdf `PCM_NO_TPMI_DRIVER=1` : don't use the Linux TPMI driver (debugfs) to access TPMI registers, access them through MMIO instead diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 84ecb6de..13ce82ec 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1725,13 +1725,19 @@ bool PCM::detectNominalFrequency() return true; } -constexpr auto PCM_USE_TPMI_RAPL_STR = "PCM_USE_TPMI_RAPL"; +constexpr auto PCM_NO_TPMI_RAPL_STR = "PCM_NO_TPMI_RAPL"; bool PCM::initRAPLTPMI() { - if (safe_getenv(PCM_USE_TPMI_RAPL_STR) != std::string("1")) + if (safe_getenv(PCM_NO_TPMI_RAPL_STR) == std::string("1")) { - return false; // MSR-based package energy monitoring (default) + DBG(1, "RAPL TPMI: disabled by ", PCM_NO_TPMI_RAPL_STR, ": using the MSR-based energy metrics"); + return false; + } + + if (isServerCPU() == false) + { + return false; // the RAPL TPMI interface is available on server processors only } if (energy_status.empty() == false && packageEnergyTPMI == false) @@ -1745,13 +1751,13 @@ bool PCM::initRAPLTPMI() } catch (std::exception & e) { - std::cerr << "ERROR: Could not detect TPMI instances. Exception details: " << e.what() << "\n"; + DBG(1, "RAPL TPMI: could not detect TPMI instances. Exception details: ", e.what()); nInstances = 0; } DBG(1, "RAPL TPMI: TPMI instances detected: ", nInstances); if (nInstances == 0) { - std::cerr << "ERROR: No TPMI instances detected: can not use the RAPL TPMI interface. Falling back to MSRs.\n"; + DBG(1, "RAPL TPMI: no TPMI instances detected: using the MSR-based energy metrics"); return false; } @@ -1792,8 +1798,9 @@ bool PCM::initRAPLTPMI() { socket = (uint32)socketTmp; } - else + else if (num_sockets > 1) { + // on a single socket system socket 0 is the only possible answer std::cerr << "WARNING: Could not map RAPL TPMI instance " << instance << " (NUMA node " << numaNode << ") to a socket. Assuming socket 0.\n"; } @@ -1839,8 +1846,8 @@ bool PCM::initRAPLTPMI() } if ((flags & (1ULL << RAPL_TPMI_ENERGY_STATUS)) == 0 || (flags & (1ULL << RAPL_TPMI_POWER_UNIT)) == 0) { - std::cerr << "WARNING: RAPL TPMI " << domainName << " domain " << domain << " of TPMI instance " << instance << - " does not support the ENERGY_STATUS and/or POWER_UNIT register (flags 0x" << std::hex << flags << std::dec << ").\n"; + DBG(1, "RAPL TPMI: ", domainName, " domain ", domain, " of TPMI instance ", instance, + " does not support the ENERGY_STATUS and/or POWER_UNIT register (flags 0x", std::hex, flags, std::dec, ")"); continue; } if (target->energyStatus.get() != nullptr) @@ -1876,8 +1883,7 @@ bool PCM::initRAPLTPMI() { if (packageDomain[socket].energyStatus.get() == nullptr) { - std::cerr << "ERROR: Could not find the package RAPL TPMI domain of socket " << socket << - ". Falling back to MSR-based package energy metrics.\n"; + DBG(1, "RAPL TPMI: no package RAPL domain found for socket ", socket, ": using the MSR-based energy metrics"); return false; } } @@ -1924,8 +1930,7 @@ bool PCM::initRAPLTPMI() { if (memoryDomain[socket].energyStatus.get() == nullptr) { - std::cerr << "WARNING: Could not find the memory (DRAM) RAPL TPMI domain of socket " << socket << - ". Falling back to MSR-based DRAM energy metrics.\n"; + DBG(1, "RAPL TPMI: no memory (DRAM) RAPL domain found for socket ", socket, ": using the MSR-based DRAM energy metrics"); memoryDomainsFound = false; } } @@ -1958,8 +1963,7 @@ bool PCM::initRAPLTPMI() } else { - std::cerr << "WARNING: Could not find the system (platform) RAPL TPMI domain of socket 0." - " Falling back to MSR-based system energy metrics.\n"; + DBG(1, "RAPL TPMI: no system (platform) RAPL domain found for socket 0: using the MSR-based system energy metrics"); } } @@ -1969,7 +1973,7 @@ bool PCM::initRAPLTPMI() std::cerr << "Reading the package"; if (dramEnergyTPMI) std::cerr << ", DRAM"; if (systemEnergyTPMI) std::cerr << ", system"; - std::cerr << " energy through the RAPL TPMI interface (" << PCM_USE_TPMI_RAPL_STR << "=1).\n"; + std::cerr << " energy through the RAPL TPMI interface (disable with " << PCM_NO_TPMI_RAPL_STR << "=1)\n"; } #endif return true; From f1878293eb69e6fbf7e9d5b479d7edbd8538f6e6 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Thu, 20 Aug 2026 09:48:16 +0200 Subject: [PATCH 05/40] drop the warning about the RAPL TPMI energy unit Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 13ce82ec..9afbdb82 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1893,11 +1893,6 @@ bool PCM::initRAPLTPMI() // POWER_UNIT.PWR_UNIT: power unit is 1/(2^PWR_UNIT) Watts const double wattsPerPowerUnit = 1. / double(1ULL << extract_bits_64(packageDomain[0].powerUnit, 3, 0)); DBG(2, "RAPL TPMI POWER_UNIT: 0x", std::hex, packageDomain[0].powerUnit, std::dec, "; Joules/unit ", tpmiJoulesPerEnergyUnit); - if (tpmiJoulesPerEnergyUnit != joulesPerEnergyUnit) - { - std::cerr << "WARNING: the RAPL TPMI energy unit (" << tpmiJoulesPerEnergyUnit << - " Joules) differs from the MSR-based energy unit (" << joulesPerEnergyUnit << " Joules).\n"; - } joulesPerEnergyUnit = tpmiJoulesPerEnergyUnit; if (packageDomain[0].plInfoValid) From c519aec5898a3e9943cedb1a2a1819dea7b215ec Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Thu, 20 Aug 2026 09:58:31 +0200 Subject: [PATCH 06/40] report the RAPL TPMI usage through the debug output only Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.cpp | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 9afbdb82..9f599963 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1962,15 +1962,8 @@ bool PCM::initRAPLTPMI() } } -#ifndef PCM_SILENT - if (!quietMode) - { - std::cerr << "Reading the package"; - if (dramEnergyTPMI) std::cerr << ", DRAM"; - if (systemEnergyTPMI) std::cerr << ", system"; - std::cerr << " energy through the RAPL TPMI interface (disable with " << PCM_NO_TPMI_RAPL_STR << "=1)\n"; - } -#endif + DBG(1, "Reading the package", (dramEnergyTPMI ? ", DRAM" : ""), (systemEnergyTPMI ? ", system" : ""), + " energy through the RAPL TPMI interface (disable with ", PCM_NO_TPMI_RAPL_STR, "=1)"); return true; } From 0965fc2f4b7490e1afcba01397a62111a41fcc4a Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Thu, 20 Aug 2026 10:11:57 +0200 Subject: [PATCH 07/40] take the system energy unit from the system RAPL TPMI domain getSystemConsumedJoules used the package energy unit (or the fixed 1 Joule granularity of SPR/EMR/GNR/SRF) also when the system energy is read through the RAPL TPMI interface. The energy unit of the system (platform) domain is read from the POWER_UNIT register of that domain now and returned by the new PCM::getSystemJoulesPerEnergyUnit(), which also hosts the model specific granularity that was inline in getSystemConsumedJoules before. Note that the fixed 1 Joule granularity keeps precedence on SPR/EMR/GNR/SRF: the system RAPL TPMI domain of these processors reports the architectural default energy unit (61 uJ) in its POWER_UNIT register while its ENERGY_STATUS register is the same counter as MSR_SYS_ENERGY_STATUS and counts Joules (measured on GNR: 318 counts/s at idle, 548 counts/s under load). Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.cpp | 4 ++++ src/cpucounters.h | 37 ++++++++++++++++++++++++------------- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 9f599963..cef45545 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1950,6 +1950,10 @@ bool PCM::initRAPLTPMI() { if (systemDomain[0].energyStatus.get() != nullptr) { + // the system RAPL domain has its own POWER_UNIT register + systemJoulesPerEnergyUnit = 1. / double(1ULL << extract_bits_64(systemDomain[0].powerUnit, 10, 6)); + DBG(2, "RAPL TPMI system domain POWER_UNIT: 0x", std::hex, systemDomain[0].powerUnit, std::dec, + "; Joules/unit ", systemJoulesPerEnergyUnit); if (system_energy_status.get() == nullptr) { system_energy_status = makeEnergyCounter(systemDomain[0]); diff --git a/src/cpucounters.h b/src/cpucounters.h index 7aac09d3..6c8cd335 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -847,6 +847,7 @@ class PCM_API PCM double joulesPerEnergyUnit; double dramJoulesPerEnergyUnit{0.}; // energy unit of the DRAM domain (usually the same as joulesPerEnergyUnit) + double systemJoulesPerEnergyUnit{0.}; // energy unit of the system (platform) domain, 0 if unknown bool packageEnergyTPMI{false}; // package energy is read through the RAPL TPMI interface (instead of MSRs) bool dramEnergyTPMI{false}; // DRAM energy is read through the RAPL TPMI interface (instead of MSRs) bool systemEnergyTPMI{false}; // system (platform) energy is read through the RAPL TPMI interface (instead of MSRs) @@ -2419,6 +2420,28 @@ class PCM_API PCM //! \brief Returns how many joules are in an internal energy unit of the DRAM domain double getDRAMJoulesPerEnergyUnit() const { return (dramJoulesPerEnergyUnit != 0.) ? dramJoulesPerEnergyUnit : joulesPerEnergyUnit; } + //! \brief Returns how many joules are in an internal energy unit of the system (platform) domain + double getSystemJoulesPerEnergyUnit() const + { + switch (cpu_family_model) + { + case SPR: + case EMR: + case GNR: + case SRF: + // the system (platform) energy counter of these processors has a fixed 1 Joule granularity. + // The POWER_UNIT register of the system RAPL TPMI domain does not describe it: it reports the + // architectural default energy unit while the counter (the same one as MSR_SYS_ENERGY_STATUS) + // counts Joules. + return 1.0; + } + if (systemJoulesPerEnergyUnit != 0.) + { + return systemJoulesPerEnergyUnit; // POWER_UNIT of the system RAPL TPMI domain + } + return joulesPerEnergyUnit; + } + //! \brief Returns thermal specification power of the package domain in Watt int32 getPackageThermalSpecPower() const { return pkgThermalSpecPower; } @@ -3684,19 +3707,7 @@ double getSystemConsumedJoules(const CounterStateType& before, const CounterStat PCM* m = PCM::getInstance(); if (!m) return -1.; - auto unit = m->getJoulesPerEnergyUnit(); - - switch (m->getCPUFamilyModel()) - { - case PCM::SPR: - case PCM::EMR: - case PCM::GNR: - case PCM::SRF: - unit = 1.0; - break; - } - - return double(getSystemConsumedEnergy(before, after)) * unit; + return double(getSystemConsumedEnergy(before, after)) * m->getSystemJoulesPerEnergyUnit(); } /*! \brief Returns Joules consumed by DRAM From da15ede19d938f5f3b654593ee4d1327c1a9bc1a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 20 Aug 2026 10:03:54 +0000 Subject: [PATCH 08/40] make the RAPL TPMI package/DRAM/system domain initialization independent and MSR-free Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --- src/cpucounters.cpp | 120 +++++++++++++++++++++++++------------------- 1 file changed, 69 insertions(+), 51 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index cef45545..0caf5448 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -1740,9 +1740,15 @@ bool PCM::initRAPLTPMI() return false; // the RAPL TPMI interface is available on server processors only } - if (energy_status.empty() == false && packageEnergyTPMI == false) + // every energy domain is searched only if it is supported and its counters have not been + // initialized through the MSRs already + const bool findPackageDomains = packageEnergyMetricsAvailable() && (energy_status.empty() || packageEnergyTPMI); + const bool findMemoryDomains = dramEnergyMetricsAvailable() && (dram_energy_status.empty() || dramEnergyTPMI); + const bool findSystemDomains = systemEnergyMetricAvailable() && (system_energy_status.get() == nullptr || systemEnergyTPMI); + + if (findPackageDomains == false && findMemoryDomains == false && findSystemDomains == false) { - return false; // MSR-based package energy counters have been initialized already + return false; // nothing to initialize through the RAPL TPMI interface } size_t nInstances = 0; @@ -1772,8 +1778,6 @@ bool PCM::initRAPLTPMI() }; // the package, memory (DRAM) and system (platform) RAPL domain of every socket std::vector packageDomain(num_sockets), memoryDomain(num_sockets), systemDomain(num_sockets); - const bool findMemoryDomains = dramEnergyMetricsAvailable(); - const bool findSystemDomains = systemEnergyMetricAvailable(); for (uint32 instance = 0; instance < (uint32)nInstances; ++instance) { @@ -1825,7 +1829,7 @@ bool PCM::initRAPLTPMI() " flags 0x", std::hex, flags, std::dec); RAPLDomain * target = nullptr; const char * domainName = nullptr; - if (type == RAPL_TPMI_DOMAIN_TYPE_PACKAGE) + if (type == RAPL_TPMI_DOMAIN_TYPE_PACKAGE && findPackageDomains) { target = &(packageDomain[socket]); domainName = "package"; @@ -1879,48 +1883,51 @@ bool PCM::initRAPLTPMI() } } - for (uint32 socket = 0; socket < (uint32)num_sockets; ++socket) + // ENERGY_STATUS.ENERGY is a 32-bit wrapping counter in bits 31:0 (bits 63:32 hold a timestamp) + auto makeEnergyCounter = [](const RAPLDomain & d) + { + return std::make_shared( + new CounterWidthExtender::TPMICounter(d.energyStatus, d.entry, 0x00000000FFFFFFFFULL), 32, 10000); + }; + + // every energy domain falls back to the MSRs independently of the other domains + bool packageDomainsFound = findPackageDomains; + for (uint32 socket = 0; packageDomainsFound && socket < (uint32)num_sockets; ++socket) { if (packageDomain[socket].energyStatus.get() == nullptr) { DBG(1, "RAPL TPMI: no package RAPL domain found for socket ", socket, ": using the MSR-based energy metrics"); - return false; + packageDomainsFound = false; } } - - // POWER_UNIT.ENERGY_UNIT: energy unit is 1/(2^ENERGY_UNIT) Joules - const double tpmiJoulesPerEnergyUnit = 1. / double(1ULL << extract_bits_64(packageDomain[0].powerUnit, 10, 6)); - // POWER_UNIT.PWR_UNIT: power unit is 1/(2^PWR_UNIT) Watts - const double wattsPerPowerUnit = 1. / double(1ULL << extract_bits_64(packageDomain[0].powerUnit, 3, 0)); - DBG(2, "RAPL TPMI POWER_UNIT: 0x", std::hex, packageDomain[0].powerUnit, std::dec, "; Joules/unit ", tpmiJoulesPerEnergyUnit); - joulesPerEnergyUnit = tpmiJoulesPerEnergyUnit; - - if (packageDomain[0].plInfoValid) + if (packageDomainsFound) { - // PL_INFO: MAX_PL1 (TDP) in bits 17:0, MIN_PL in bits 35:18, MAX_PL2 in bits 53:36 - pkgThermalSpecPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 17, 0)) * wattsPerPowerUnit); - pkgMinimumPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 35, 18)) * wattsPerPowerUnit); - pkgMaximumPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 53, 36)) * wattsPerPowerUnit); - } + // POWER_UNIT.ENERGY_UNIT: energy unit is 1/(2^ENERGY_UNIT) Joules + const double tpmiJoulesPerEnergyUnit = 1. / double(1ULL << extract_bits_64(packageDomain[0].powerUnit, 10, 6)); + // POWER_UNIT.PWR_UNIT: power unit is 1/(2^PWR_UNIT) Watts + const double wattsPerPowerUnit = 1. / double(1ULL << extract_bits_64(packageDomain[0].powerUnit, 3, 0)); + DBG(2, "RAPL TPMI POWER_UNIT: 0x", std::hex, packageDomain[0].powerUnit, std::dec, "; Joules/unit ", tpmiJoulesPerEnergyUnit); + joulesPerEnergyUnit = tpmiJoulesPerEnergyUnit; - // ENERGY_STATUS.ENERGY is a 32-bit wrapping counter in bits 31:0 (bits 63:32 hold a timestamp) - auto makeEnergyCounter = [](const RAPLDomain & d) - { - return std::make_shared( - new CounterWidthExtender::TPMICounter(d.energyStatus, d.entry, 0x00000000FFFFFFFFULL), 32, 10000); - }; + if (packageDomain[0].plInfoValid) + { + // PL_INFO: MAX_PL1 (TDP) in bits 17:0, MIN_PL in bits 35:18, MAX_PL2 in bits 53:36 + pkgThermalSpecPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 17, 0)) * wattsPerPowerUnit); + pkgMinimumPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 35, 18)) * wattsPerPowerUnit); + pkgMaximumPower = (int32)(double(extract_bits_64(packageDomain[0].plInfo, 53, 36)) * wattsPerPowerUnit); + } - if (energy_status.empty()) - { - for (const auto & d : packageDomain) + if (energy_status.empty()) { - energy_status.push_back(makeEnergyCounter(d)); + for (const auto & d : packageDomain) + { + energy_status.push_back(makeEnergyCounter(d)); + } } + packageEnergyTPMI = true; } - packageEnergyTPMI = true; - // don't use the TPMI energy unit of the memory domain if the MSR-based DRAM counters are in use already - bool memoryDomainsFound = findMemoryDomains && (dram_energy_status.empty() || dramEnergyTPMI); + bool memoryDomainsFound = findMemoryDomains; for (uint32 socket = 0; memoryDomainsFound && socket < (uint32)num_sockets; ++socket) { if (memoryDomain[socket].energyStatus.get() == nullptr) @@ -1946,7 +1953,7 @@ bool PCM::initRAPLTPMI() } // the system (platform) energy counter is a single counter read from socket 0, like the MSR-based one - if (findSystemDomains && (system_energy_status.get() == nullptr || systemEnergyTPMI)) + if (findSystemDomains) { if (systemDomain[0].energyStatus.get() != nullptr) { @@ -1966,38 +1973,49 @@ bool PCM::initRAPLTPMI() } } - DBG(1, "Reading the package", (dramEnergyTPMI ? ", DRAM" : ""), (systemEnergyTPMI ? ", system" : ""), - " energy through the RAPL TPMI interface (disable with ", PCM_NO_TPMI_RAPL_STR, "=1)"); + if (packageEnergyTPMI == false && dramEnergyTPMI == false && systemEnergyTPMI == false) + { + return false; + } + + DBG(1, "Reading the ", (packageEnergyTPMI ? "package " : ""), (dramEnergyTPMI ? "DRAM " : ""), (systemEnergyTPMI ? "system " : ""), + "energy through the RAPL TPMI interface (disable with ", PCM_NO_TPMI_RAPL_STR, "=1)"); return true; } void PCM::initEnergyMonitoring() { + // optional alternative transport: read the package, DRAM and system (platform) energy through the + // architectural RAPL TPMI interface instead of MSRs (it also provides the energy units and the + // package power info). It is attempted before the MSR-based initialization because it does not + // require MSR access. Every energy domain falls back to the MSRs independently of the other domains. + initRAPLTPMI(); + if(packageEnergyMetricsAvailable() && MSR.size()) { uint64 rapl_power_unit = 0; MSR[socketRefCore[0]]->read(MSR_RAPL_POWER_UNIT,&rapl_power_unit); uint64 energy_status_unit = extract_bits(rapl_power_unit,8,12); + double msrJoulesPerEnergyUnit = 0.; if (cpu_family_model == PCM::CHERRYTRAIL || cpu_family_model == PCM::BAYTRAIL) - joulesPerEnergyUnit = double(1ULL << energy_status_unit)/1000000.; // (2)^energy_status_unit microJoules + msrJoulesPerEnergyUnit = double(1ULL << energy_status_unit)/1000000.; // (2)^energy_status_unit microJoules else - joulesPerEnergyUnit = 1./double(1ULL<read(MSR_PKG_POWER_INFO,&package_power_info); - pkgThermalSpecPower = (int32) (double(extract_bits(package_power_info, 0, 14))*wattsPerPowerUnit); - pkgMinimumPower = (int32) (double(extract_bits(package_power_info, 16, 30))*wattsPerPowerUnit); - pkgMaximumPower = (int32) (double(extract_bits(package_power_info, 32, 46))*wattsPerPowerUnit); - - // optional alternative path: read the package and DRAM energy through the architectural RAPL - // TPMI interface instead of MSRs (it also updates the energy units and the package power info above) - if (initRAPLTPMI()) + if (pkgThermalSpecPower < 0) // the package power info has not been read through the RAPL TPMI interface { - DBG(1, "Using the RAPL TPMI interface for package energy metrics"); + uint64 package_power_info = 0; + MSR[socketRefCore[0]]->read(MSR_PKG_POWER_INFO,&package_power_info); + pkgThermalSpecPower = (int32) (double(extract_bits(package_power_info, 0, 14))*wattsPerPowerUnit); + pkgMinimumPower = (int32) (double(extract_bits(package_power_info, 16, 30))*wattsPerPowerUnit); + pkgMaximumPower = (int32) (double(extract_bits(package_power_info, 32, 46))*wattsPerPowerUnit); } #ifndef PCM_SILENT From 76480af117706adef145f387cdd46519f223b0fa Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 20 Aug 2026 10:43:52 +0000 Subject: [PATCH 09/40] handle raw counter read failures in CounterWidthExtender without terminating Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --- src/cpucounters.cpp | 11 +++++++++-- src/width_extender.h | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 0caf5448..f627800b 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -11562,7 +11562,7 @@ void PCM::initCHARequestEvents(uint64 * config) } } -CounterWidthExtender::CounterWidthExtender(AbstractRawCounter * raw_counter_, uint64 counter_width_, uint32 watchdog_delay_ms_) : raw_counter(raw_counter_), counter_width(counter_width_), watchdog_delay_ms(watchdog_delay_ms_) +CounterWidthExtender::CounterWidthExtender(AbstractRawCounter * raw_counter_, uint64 counter_width_, uint32 watchdog_delay_ms_) : raw_counter(raw_counter_), counter_width(counter_width_), watchdog_delay_ms(watchdog_delay_ms_), read_failed(false) { last_raw_value = (*raw_counter)(); extended_value = last_raw_value; @@ -11573,7 +11573,14 @@ CounterWidthExtender::CounterWidthExtender(AbstractRawCounter * raw_counter_, ui while (1) { MySleepMs(static_cast(this->watchdog_delay_ms)); - /* uint64 dummy = */ this->read(); + try { + /* uint64 dummy = */ this->read(); + } + catch (const std::exception & e) + { + // never let an exception escape the watchdog thread + std::cerr << "PCM Error: caught exception " << e.what() << " in the CounterWidthExtender watchdog thread\n"; + } } } ); diff --git a/src/width_extender.h b/src/width_extender.h index 014e2910..abcfc929 100644 --- a/src/width_extender.h +++ b/src/width_extender.h @@ -16,6 +16,9 @@ #include "bw.h" #include "mutex.h" #include "tpmi.h" +#include +#include +#include #include #ifndef _MSC_VER // the header can not be included into code using CLR @@ -148,6 +151,7 @@ class CounterWidthExtender uint64 last_raw_value; uint64 counter_width; uint32 watchdog_delay_ms; + std::atomic read_failed; CounterWidthExtender(); // forbidden CounterWidthExtender(CounterWidthExtender &); // forbidden @@ -159,7 +163,19 @@ class CounterWidthExtender uint64 result = 0, new_raw_value = 0; CounterMutex.lock(); - new_raw_value = (*raw_counter)(); + try { + new_raw_value = (*raw_counter)(); + } + catch (const std::exception & e) + { + // keep the extended value intact and report the failure to the callers + read_failed.store(true, std::memory_order_relaxed); + result = extended_value; + CounterMutex.unlock(); + std::cerr << "PCM Error: caught exception " << e.what() << " while reading a raw counter in CounterWidthExtender\n"; + return result; + } + read_failed.store(false, std::memory_order_relaxed); if (new_raw_value < last_raw_value) { extended_value += ((1ULL << counter_width) - last_raw_value) + new_raw_value; @@ -186,10 +202,26 @@ class CounterWidthExtender { return internal_read(); } + //! \brief returns true if the last attempt to read the raw counter failed + bool readFailed() const + { + return read_failed.load(std::memory_order_relaxed); + } void reset() { CounterMutex.lock(); - extended_value = last_raw_value = (*raw_counter)(); + try { + extended_value = last_raw_value = (*raw_counter)(); + read_failed.store(false, std::memory_order_relaxed); + } + catch (const std::exception & e) + { + // keep the extended value intact and report the failure to the callers + read_failed.store(true, std::memory_order_relaxed); + CounterMutex.unlock(); + std::cerr << "PCM Error: caught exception " << e.what() << " while resetting a raw counter in CounterWidthExtender\n"; + return; + } CounterMutex.unlock(); } }; From 921237dd374ad92a549b1382988a20b450fe615a Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 8 Sep 2026 13:37:26 +0200 Subject: [PATCH 10/40] Fix sensor-server SSL fuzz shutdown use-after-free (#969) * Fix sensor-server fuzz shutdown ordering Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --- tests/pcm-sensor-server-fuzz.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/pcm-sensor-server-fuzz.cpp b/tests/pcm-sensor-server-fuzz.cpp index 9efa027c..ed635ea1 100644 --- a/tests/pcm-sensor-server-fuzz.cpp +++ b/tests/pcm-sensor-server-fuzz.cpp @@ -57,8 +57,13 @@ std::thread * serverThread; void cleanup() { - DBG( 0, "Client: Stopping HTTPServer" ); - httpServer->stop(); + if (auto* pcieCollector = PCIeCollector::getInstance()) { + pcieCollector->stop(); + } + if (httpServer) { + DBG( 0, "Client: Stopping HTTPServer" ); + httpServer->stop(); + } DBG( 0, "Client: Cleaning up PMU:" ); PCM::getInstance()->cleanup(); } @@ -76,6 +81,7 @@ bool init() DBG( 0, "Client: Error in program() function" ); exit(1); } + (void)PCIeCollector::getInstance(); debug::dyn_debug_level(1); #ifdef FUZZ_USE_SSL DBG( 0, "Client: Starting SSL enabled server on https://localhost:", port ); From 63f2f33f363359fac43db3d4c3dcf1b1a61391ec Mon Sep 17 00:00:00 2001 From: "Dementiev, Roman" Date: Mon, 7 Sep 2026 17:29:34 +0200 Subject: [PATCH 11/40] drop unused captures Change-Id: I8b0402e259c9480bac2a0774dbeb14f7e19196bb --- src/cpucounters.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 1ceb7c55..d41fbcbb 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -8156,7 +8156,7 @@ void PCM::getPCICFGPMUsFromDiscovery(const unsigned int BoxType, const size_t s, { std::vector > CounterControlRegs, CounterValueRegs; const auto n_regs = uncorePMUDiscovery->getBoxNumRegs(BoxType, s, die, pos); - auto makeRegister = [&pos, &numBoxes, &BoxType, &s](const uint64 rawAddr) + auto makeRegister = [](const uint64 rawAddr) { UncorePMUDiscovery::PCICFGAddress Addr; Addr.raw = rawAddr; From 7f7f4daf43d6e8187ea7684cd206a283693963a5 Mon Sep 17 00:00:00 2001 From: "Dementiev, Roman" Date: Thu, 10 Sep 2026 10:23:31 +0200 Subject: [PATCH 12/40] add ufs-die-freq.sh script to change uncore die frequencies (based on TPMI) Change-Id: I686c8db1c3ac090f242c22d718d13677b98124fd --- scripts/ufs-die-freq.sh | 370 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 370 insertions(+) create mode 100644 scripts/ufs-die-freq.sh diff --git a/scripts/ufs-die-freq.sh b/scripts/ufs-die-freq.sh new file mode 100644 index 00000000..45ccdb2b --- /dev/null +++ b/scripts/ufs-die-freq.sh @@ -0,0 +1,370 @@ +#!/bin/bash + +echo "Intel(r) Performance Counter Monitor" +echo "Uncore Frequency Scaling: Die Frequency Control Utility" +echo + +print_usage() { + echo " Usage: $(basename "$0") --die-type [--min ] [--max ]" + echo " [--socket ] [--numa-node ] [--instance ] [--die ]" + echo + echo " --die-type : die type to configure: compute, LLC, memory or IO" + echo " --min : set the minimum uncore frequency (100 MHz granularity, 0..12700)" + echo " --max : set the maximum uncore frequency (100 MHz granularity, 0..12700)" + echo " --socket : restrict the operation to socket N (default: all sockets)" + echo " (examples: --socket 1 --socket 0,1 --socket 0,2-3)" + echo " --numa-node : restrict the operation to NUMA node N (default: all NUMA nodes)" + echo " (examples: --numa-node 1 --numa-node 0,1 --numa-node 0,2-3)" + echo " --instance : restrict the operation to TPMI instance N (default: all instances)" + echo " --die : restrict the operation to die (TPMI entry) N (default: all dies)" + echo + echo " Without --min/--max the current frequency limits of the matching dies are printed only." + echo " Note: a die can have several types (e.g. compute/LLC/memory) and is selected by any of them." + echo + echo " Examples:" + echo " $(basename "$0") --die-type compute --min 2000 # pin compute dies to at least 2 GHz" + echo " $(basename "$0") --die-type IO --min 800 --max 2400 # set the IO die frequency window" + echo " $(basename "$0") --die-type memory # show the memory die frequency limits" + echo " $(basename "$0") --die-type compute --max 2400 --socket 0 # limit the compute dies of socket 0" + echo " $(basename "$0") --die-type LLC --min 1600 --numa-node 2 # tune the LLC dies of NUMA node 2" + echo +} + +# TPMI UFS (Uncore Frequency Scaling) register offsets and bit fields +UFS_STATUS=0x10 # bits 6:0 current ratio, bits 26:23 die type +UFS_CONTROL=0x18 # bits 14:8 MAX_RATIO, bits 21:15 MIN_RATIO +MAX_RATIO_BITS="14:8" +MIN_RATIO_BITS="21:15" +MIN_MAX_RATIO_BITS="21:8" # both fields, to update them in a single write + +die_type="" +min_freq="" +max_freq="" +socket_filter="" +numa_filter="" +instance_filter="" +die_filter="" + +while [ $# -gt 0 ]; do + # accept both "--option value" and "--option=value" + opt="${1%%=*}" + if [[ $1 == *=* ]]; then + val="${1#*=}" + shift + else + val="$2" + shift + [ $# -gt 0 ] && shift + fi + case "$opt" in + -h|--help) print_usage; exit 0 ;; + --die-type|--min|--max|--socket|--numa-node|--instance|--die) + if [ -z "$val" ] || [[ $val == -* ]]; then + echo "Error: option '$opt' requires a value" + echo + print_usage + exit 1 + fi + case "$opt" in + --die-type) die_type="$val" ;; + --min) min_freq="$val" ;; + --max) max_freq="$val" ;; + --socket) socket_filter="$val" ;; + --numa-node) numa_filter="$val" ;; + --instance) instance_filter="$val" ;; + --die) die_filter="$val" ;; + esac + ;; + *) + echo "Error: unknown option '$opt'" + echo + print_usage + exit 1 + ;; + esac +done + +if ! command -v pcm-tpmi > /dev/null 2>&1; then + echo "Error: pcm-tpmi utility is not found in PATH." + echo " Please build PCM or install the PCM package (see doc/LATENCY-OPTIMIZED-MODE.md)." + exit 1 +fi + +# select the die type bit in the UFS_STATUS register +case "$(echo "$die_type" | tr '[:upper:]' '[:lower:]')" in + compute|core|cor) die_type_bit=23; die_type_name="compute" ;; + llc|cache) die_type_bit=24; die_type_name="LLC" ;; + memory|mem) die_type_bit=25; die_type_name="memory" ;; + io) die_type_bit=26; die_type_name="IO" ;; + "") + echo "Error: --die-type is required." + echo + print_usage + exit 1 + ;; + *) + echo "Error: unknown die type '$die_type'." + echo + print_usage + exit 1 + ;; +esac + +# Convert a frequency in MHz into an uncore ratio (100 MHz units) +freq_to_ratio() { + local mhz=$1 + local name=$2 + if ! [[ $mhz =~ ^[0-9]+$ ]]; then + echo "Error: invalid $name frequency '$mhz' (expected a number in MHz)" >&2 + return 1 + fi + local ratio=$(( (mhz + 50) / 100 )) + if [ "$ratio" -gt 127 ]; then + echo "Error: $name frequency $mhz MHz is out of range (max 12700 MHz)" >&2 + return 1 + fi + if [ $(( ratio * 100 )) -ne "$mhz" ]; then + echo "Warning: $name frequency $mhz MHz is rounded to $(( ratio * 100 )) MHz (100 MHz granularity)" >&2 + fi + echo "$ratio" +} + +min_ratio="" +max_ratio="" +if [ -n "$min_freq" ]; then + min_ratio=$(freq_to_ratio "$min_freq" "minimum") || exit 1 +fi +if [ -n "$max_freq" ]; then + max_ratio=$(freq_to_ratio "$max_freq" "maximum") || exit 1 +fi +if [ -n "$min_ratio" ] && [ -n "$max_ratio" ] && [ "$min_ratio" -gt "$max_ratio" ]; then + echo "Error: minimum frequency $(( min_ratio * 100 )) MHz is higher than maximum frequency $(( max_ratio * 100 )) MHz" + exit 1 +fi + +# Expand an integer list like "0,2-3" into "0 2 3" +expand_integer_list() { + local list=$1 + local name=$2 + local item start end i + local result="" + for item in ${list//,/ }; do + if [[ $item =~ ^([0-9]+)-([0-9]+)$ ]]; then + start=${BASH_REMATCH[1]} + end=${BASH_REMATCH[2]} + if [ "$start" -gt "$end" ]; then + echo "Error: invalid $name range '$item'" >&2 + return 1 + fi + for (( i = start; i <= end; ++i )); do + result="$result $i" + done + elif [[ $item =~ ^[0-9]+$ ]]; then + result="$result $item" + else + echo "Error: invalid $name '$item' (expected a list like 1, 0,1 or 0,2-3)" >&2 + return 1 + fi + done + echo "$result" +} + +sockets="" +numa_nodes="" +location_suffix="" +if [ -n "$socket_filter" ]; then + sockets=$(expand_integer_list "$socket_filter" "socket") || exit 1 + location_suffix=" on socket(s)${sockets}" +fi +if [ -n "$numa_filter" ]; then + numa_nodes=$(expand_integer_list "$numa_filter" "NUMA node") || exit 1 + location_suffix="$location_suffix on NUMA node(s)${numa_nodes}" +fi + +# Check if the value is in the list (an empty list selects everything) +in_list() { + local list=$1 + local value=$2 + local i + [ -z "$list" ] && return 0 + [ -z "$value" ] && return 1 + for i in $list; do + if [ "$i" -eq "$value" ]; then + return 0 + fi + done + return 1 +} + +# Check if the die is selected by --socket and --numa-node +die_selected() { + local socket=$1 + local numa_node=$2 + in_list "$sockets" "$socket" && in_list "$numa_nodes" "$numa_node" +} + +# pcm-tpmi instance/entry selection options +select_opts=() +if [ -n "$instance_filter" ]; then + select_opts+=(-i "$instance_filter") +fi +if [ -n "$die_filter" ]; then + select_opts+=(-e "$die_filter") +fi + +# Read a single TPMI register of one die and print its value +read_die_register() { + local instance=$1 + local entry=$2 + local offset=$3 + local out + out=$(pcm-tpmi 2 "$offset" -d -i "$instance" -e "$entry") + while read -r line; do + if [[ $line =~ Read\ value\ ([0-9]+) ]]; then + echo "${BASH_REMATCH[1]}" + return 0 + fi + done <<< "$out" + return 1 +} + +# Build the die type string out of the UFS_STATUS register value +die_type_string() { + local value=$1 + local str="" + if [ $(( (value >> 23) & 1 )) -ne 0 ]; then + str="compute/" + fi + if [ $(( (value >> 24) & 1 )) -ne 0 ]; then + str="${str}LLC/" + fi + if [ $(( (value >> 25) & 1 )) -ne 0 ]; then + str="${str}memory/" + fi + if [ $(( (value >> 26) & 1 )) -ne 0 ]; then + str="${str}IO/" + fi + echo "${str%/}" +} + +# Discover the dies and their types +declare -A die_types +declare -A die_locations +matching_dies=() + +output=$(pcm-tpmi 2 $UFS_STATUS -d "${select_opts[@]}") + +while read -r line; do + if [[ $line =~ Read\ value\ ([0-9]+)\ from\ TPMI\ ID\ [0-9]+@[0-9]+\ for\ entry\ ([0-9]+)\ in\ instance\ ([0-9]+) ]]; then + value=${BASH_REMATCH[1]} + die=${BASH_REMATCH[2]} + instance=${BASH_REMATCH[3]} + + # Extract socket ID if present in the output (format: "(socket X)") + if [[ $line =~ \(socket\ ([0-9]+)\) ]]; then + socket=${BASH_REMATCH[1]} + else + # Fallback to instance ID if socket info is not available + socket=$instance + fi + + # Extract NUMA node ID if present in the output (format: "(NUMA node X)") + numa_node="" + location="Socket $socket" + if [[ $line =~ \(NUMA\ node\ ([0-9]+)\) ]]; then + numa_node=${BASH_REMATCH[1]} + location="$location NUMA node $numa_node" + fi + location="$location instance $instance die $die" + + die_key="${instance}:${die}" + die_types[$die_key]=$(die_type_string "$value") + die_locations[$die_key]="$location" + + if [ $(( (value >> die_type_bit) & 1 )) -ne 0 ] && die_selected "$socket" "$numa_node"; then + matching_dies+=("$die_key") + fi + fi +done <<< "$output" + +if [ ${#die_types[@]} -eq 0 ]; then + echo "Error: no uncore frequency scaling dies found." + echo " The platform may not support TPMI UFS or the utility has no access to MSR/PCICFG drivers" + echo " (root privileges are required)." + exit 1 +fi + +if [ ${#matching_dies[@]} -eq 0 ]; then + echo "Error: no $die_type_name dies found$location_suffix. Available dies:" + for die_key in $(printf '%s\n' "${!die_types[@]}" | sort -t: -k1,1n -k2,2n); do + echo " ${die_locations[$die_key]} (${die_types[$die_key]})" + done + exit 1 +fi + +# Apply the requested frequency limits +if [ -n "$min_ratio" ] || [ -n "$max_ratio" ]; then + echo -n "Setting" + if [ -n "$min_ratio" ]; then + echo -n " minimum $(( min_ratio * 100 )) MHz" + fi + if [ -n "$max_ratio" ]; then + echo -n " maximum $(( max_ratio * 100 )) MHz" + fi + echo " uncore frequency of the $die_type_name dies$location_suffix..." + echo + + for die_key in "${matching_dies[@]}"; do + instance="${die_key%:*}" + entry="${die_key#*:}" + + control=$(read_die_register "$instance" "$entry" $UFS_CONTROL) + if [ -z "$control" ]; then + echo "Warning: can not read the control register of ${die_locations[$die_key]}, skipping it" + continue + fi + current_min=$(( (control >> 15) & 0x7F )) + current_max=$(( (control >> 8) & 0x7F )) + new_min=${min_ratio:-$current_min} + new_max=${max_ratio:-$current_max} + + if [ "$new_min" -gt "$new_max" ]; then + echo "Warning: ${die_locations[$die_key]}: requested minimum $(( new_min * 100 )) MHz is higher than" \ + "the maximum $(( new_max * 100 )) MHz, skipping it" + continue + fi + + if [ -n "$min_ratio" ] && [ -n "$max_ratio" ]; then + # MIN_RATIO and MAX_RATIO are adjacent fields: update both in one write + pcm-tpmi 2 $UFS_CONTROL -d -i "$instance" -e "$entry" -b $MIN_MAX_RATIO_BITS \ + -w $(( (new_min << 7) | new_max )) > /dev/null + elif [ -n "$min_ratio" ]; then + pcm-tpmi 2 $UFS_CONTROL -d -i "$instance" -e "$entry" -b $MIN_RATIO_BITS -w "$new_min" > /dev/null + else + pcm-tpmi 2 $UFS_CONTROL -d -i "$instance" -e "$entry" -b $MAX_RATIO_BITS -w "$new_max" > /dev/null + fi + done +fi + +# Print the resulting state of the selected dies +echo "$die_type_name die uncore frequency limits$location_suffix:" +echo + +for die_key in "${matching_dies[@]}"; do + instance="${die_key%:*}" + entry="${die_key#*:}" + + control=$(read_die_register "$instance" "$entry" $UFS_CONTROL) + status=$(read_die_register "$instance" "$entry" $UFS_STATUS) + if [ -z "$control" ] || [ -z "$status" ]; then + echo "Warning: can not read the registers of ${die_locations[$die_key]}" + continue + fi + + min=$(( ((control >> 15) & 0x7F) * 100 )) + max=$(( ((control >> 8) & 0x7F) * 100 )) + current=$(( (status & 0x7F) * 100 )) + + printf "%-60s: min %5d MHz, max %5d MHz, current %5d MHz\n" \ + "${die_locations[$die_key]} (${die_types[$die_key]})" "$min" "$max" "$current" +done From aac1dcee001cd4a187ac36f3e0149ac6c6cc75f4 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 16 Sep 2026 12:13:44 +0200 Subject: [PATCH 13/40] Split CPU topology discovery out of PCM into independent CPUTopology object (#979) * Split CPU topology discovery into independent CoreTopology used by PCM and pcm-msr Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> * set_signal_handlers() not needed since we don't create PCM object Change-Id: I58b66c8d7161c74b5d77121eb97cc62d6f16a645 --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> Co-authored-by: Dementiev, Roman --- src/CMakeLists.txt | 2 +- src/cpucounters.cpp | 344 +------------------------------------ src/cputopology.cpp | 400 ++++++++++++++++++++++++++++++++++++++++++++ src/cputopology.h | 80 +++++++++ src/pcm-msr.cpp | 19 ++- 5 files changed, 505 insertions(+), 340 deletions(-) create mode 100644 src/cputopology.cpp create mode 100644 src/cputopology.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 946cf40d..3e5e5b4a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -6,7 +6,7 @@ set(PROJECT_NAMES pcm pcm-numa pcm-latency pcm-power pcm-msr pcm-memory pcm-tsx set(MINIMUM_OPENSSL_VERSION 1.1.1) -file(GLOB COMMON_SOURCES pcm-accel-common.cpp msr.cpp cpucounters.cpp pci.cpp mmio.cpp tpmi.cpp pmt.cpp bw.cpp utils.cpp topology.cpp debug.cpp threadpool.cpp uncore_pmu_discovery.cpp pcm-iio-pmu.cpp pcm-iio-topology.cpp lspci.cpp dashboard.cpp ${PCM_PUGIXML_CPP}) +file(GLOB COMMON_SOURCES pcm-accel-common.cpp msr.cpp cpucounters.cpp cputopology.cpp pci.cpp mmio.cpp tpmi.cpp pmt.cpp bw.cpp utils.cpp topology.cpp debug.cpp threadpool.cpp uncore_pmu_discovery.cpp pcm-iio-pmu.cpp pcm-iio-topology.cpp lspci.cpp dashboard.cpp ${PCM_PUGIXML_CPP}) file(GLOB UNIX_SOURCES resctrl.cpp) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index d41fbcbb..65107f55 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -27,6 +27,7 @@ #include "types.h" #include "utils.h" #include "topology.h" +#include "cputopology.h" #if defined (__FreeBSD__) || defined(__DragonFly__) #include @@ -209,28 +210,6 @@ int32 extractThermalHeadroom(uint64 val) uint64 get_frequency_from_cpuid(); - - -#if defined(__FreeBSD__) || defined(__DragonFly__) -void pcm_cpuid_bsd(int leaf, PCM_CPUID_INFO& info, int core) -{ - cpuctl_cpuid_args_t cpuid_args_freebsd; - char cpuctl_name[64]; - - snprintf(cpuctl_name, 64, "/dev/cpuctl%d", core); - auto fd = ::open(cpuctl_name, O_RDWR); - - cpuid_args_freebsd.level = leaf; - - ::ioctl(fd, CPUCTL_CPUID, &cpuid_args_freebsd); - for (int i = 0; i < 4; ++i) - { - info.array[i] = cpuid_args_freebsd.data[i]; - } - ::close(fd); -} -#endif - #ifdef __linux__ bool isNMIWatchdogEnabled(const bool silent); bool keepNMIWatchdogEnabled(); @@ -1118,324 +1097,19 @@ bool PCM::discoverSystemTopology() typedef std::map socketIdMap_type; socketIdMap_type socketIdMap; - PCM_CPUID_INFO cpuid_args; - uint32 smtMaskWidth = 0; - uint32 coreMaskWidth = 0; - uint32 l2CacheMaskShift = 0; - uint32 l3CacheMaskShift = 0; - - struct domain - { - TopologyEntry::DomainTypeID type = TopologyEntry::DomainTypeID::InvalidDomainTypeID; - unsigned levelShift = 0, nextLevelShift = 0, width = 0; - }; - std::unordered_map topologyDomainMap; - { - const int32 maxTopoDomainAff = 1<<16; - int32 topoDomainAff = -1; - - for (int32 core = 0; core < maxTopoDomainAff; ++core) - { - try { - TemporalThreadAffinity _(core); - topoDomainAff = core; - } - catch (...) - { - } - if (topoDomainAff != -1) break; - } - - TemporalThreadAffinity _(topoDomainAff); - - if (initCoreMasks(smtMaskWidth, coreMaskWidth, l2CacheMaskShift, l3CacheMaskShift) == false) - { - std::cerr << "ERROR: Major problem? No leaf 0 under cpuid function 11.\n"; - return false; - } - - int subleaf = 0; - - std::vector topologyDomains; - if (max_cpuid >= 0x1F) - { - subleaf = 0; - do - { - pcm_cpuid(0x1F, subleaf, cpuid_args); - domain d; - d.type = (TopologyEntry::DomainTypeID)extract_bits_32(cpuid_args.reg.ecx, 8, 15); - DBG(1 , "pcm_cpuid 0x1F cpuid_args.reg.ecx = " , cpuid_args.reg.ecx , " d.type = ", d.type); - if (d.type == TopologyEntry::DomainTypeID::InvalidDomainTypeID) - { - break; - } - d.nextLevelShift = extract_bits_32(cpuid_args.reg.eax, 0, 4); - d.levelShift = topologyDomains.empty() ? 0 : topologyDomains.back().nextLevelShift; - d.width = d.nextLevelShift - d.levelShift; - topologyDomains.push_back(d); - ++subleaf; - } while (true); - - if (topologyDomains.size()) - { - domain d; - d.type = TopologyEntry::DomainTypeID::SocketPackageDomain; - d.levelShift = topologyDomains.back().nextLevelShift; - d.nextLevelShift = 32; - d.width = d.nextLevelShift - d.levelShift; - topologyDomains.push_back(d); - } - for (size_t l = 0; l < topologyDomains.size(); ++l) - { - topologyDomainMap[topologyDomains[l].type] = topologyDomains[l]; - DBG(1 , "Topology level: " , l , - " type: " , topologyDomains[l].type , - " (" , TopologyEntry::getDomainTypeStr(topologyDomains[l].type) , ")" , - " width: " , topologyDomains[l].width , - " levelShift: " , topologyDomains[l].levelShift , - " nextLevelShift: " , topologyDomains[l].nextLevelShift); - } - } - } - - auto populateEntry = [&topologyDomainMap,&smtMaskWidth, &coreMaskWidth, &l2CacheMaskShift, &l3CacheMaskShift](TopologyEntry& entry) - { - auto getAPICID = [&](const uint32 leaf) - { - PCM_CPUID_INFO cpuid_args; -#if defined(__FreeBSD__) || defined(__DragonFly__) - pcm_cpuid_bsd(leaf, cpuid_args, entry.os_id); -#else - pcm_cpuid(leaf, 0x0, cpuid_args); -#endif - return cpuid_args.array[3]; - }; - if (topologyDomainMap.size()) - { - auto getID = [&topologyDomainMap](const int apic_id, const TopologyEntry::DomainTypeID t) - { - const auto di = topologyDomainMap.find(t); - if (di != topologyDomainMap.end()) - { - const auto & d = di->second; - return extract_bits_32(apic_id, d.levelShift, d.nextLevelShift - 1); - } - return 0U; - }; - entry.tile_id = extract_bits_32(getAPICID(0xb), l2CacheMaskShift, 31); - const int apic_id = getAPICID(0x1F); - entry.thread_id = getID(apic_id, TopologyEntry::DomainTypeID::LogicalProcessorDomain); - entry.core_id = getID(apic_id, TopologyEntry::DomainTypeID::CoreDomain); - entry.module_id = getID(apic_id, TopologyEntry::DomainTypeID::ModuleDomain); - if (entry.tile_id == 0) - { - entry.tile_id = getID(apic_id, TopologyEntry::DomainTypeID::TileDomain); - } - entry.die_id = getID(apic_id, TopologyEntry::DomainTypeID::DieDomain); - entry.die_grp_id = getID(apic_id, TopologyEntry::DomainTypeID::DieGrpDomain); - entry.socket_id = getID(apic_id, TopologyEntry::DomainTypeID::SocketPackageDomain); - - auto getDomain = [&topologyDomainMap](const TopologyEntry::DomainTypeID t) - { - auto di = topologyDomainMap.find(t); - if (di != topologyDomainMap.end()) - { - return di->second; - } - throw std::runtime_error("DomainType not found"); - }; - domain d1 = getDomain( TopologyEntry::DomainTypeID::CoreDomain ); - domain d2 = getDomain( TopologyEntry::DomainTypeID::SocketPackageDomain ); - entry.socket_unique_core_id = extract_bits_32( apic_id, d1.levelShift, d2.levelShift - 1 ); - } - else - { - fillEntry(entry, smtMaskWidth, coreMaskWidth, l2CacheMaskShift, getAPICID(0xb)); - } - entry.l3_cache_id = extract_bits_32(getAPICID(0xb), l3CacheMaskShift, 31); - }; - - auto populateHybridEntry = [this](TopologyEntry& entry, int core) -> bool - { - if (hybrid == false) return true; - PCM_CPUID_INFO cpuid_args; -#if defined(__FreeBSD__) || defined(__DragonFly__) - pcm_cpuid_bsd(0x1a, cpuid_args, core); -#elif defined (_MSC_VER) || defined(__linux__) - pcm_cpuid(0x1a, 0x0, cpuid_args); - (void)core; -#else - std::cerr << "PCM Error: Hybrid processors are not supported for your OS\n"; - (void)core; - return false; -#endif - entry.native_cpu_model = extract_bits_32(cpuid_args.reg.eax, 0, 23); - entry.core_type = (TopologyEntry::CoreType) extract_bits_32(cpuid_args.reg.eax, 24, 31); - return true; - }; - -#ifdef _MSC_VER -// version for Windows 7 and later version - - char * slpi = new char[sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)]; - DWORD len = (DWORD)sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX); - BOOL res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len); - - while (res == FALSE) - { - deleteAndNullifyArray(slpi); - - if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) - { - slpi = new char[len]; - res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len); - } - else - { - tcerr << "Error in Windows function 'GetLogicalProcessorInformationEx': " << - GetLastError() << " "; - const TCHAR * strError = _com_error(GetLastError()).ErrorMessage(); - if (strError) tcerr << strError; - tcerr << "\n"; - return false; - } - } - - char * base_slpi = slpi; - PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pi = NULL; - - for ( ; slpi < base_slpi + len; slpi += (DWORD)pi->Size) - { - pi = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi; - if (pi->Relationship == RelationProcessorCore) - { - const auto current_threads_per_core = (pi->Processor.Flags == LTP_PC_SMT) ? 2 : 1; - DBG(3, "thr per core: " , current_threads_per_core ); - num_cores += current_threads_per_core; - } - } - - num_online_cores = num_cores; - - if (num_cores != GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)) - { - std::cerr << "Error in processor group size counting: " << num_cores << "!=" << GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) << "\n"; - std::cerr << "Make sure your binary is compiled for 64-bit: using 'x64' platform configuration.\n"; - return false; - } - - for (int i = 0; i < (int)num_cores; i++) - { - ThreadGroupTempAffinity affinity(i); - - TopologyEntry entry; - entry.os_id = i; - - populateEntry(entry); - if (populateHybridEntry(entry, i) == false) - { - return false; - } - - topology.push_back(entry); - socketIdMap[entry.socket_id] = 0; - } - - deleteAndNullifyArray(base_slpi); - -#else - // for Linux, FreeBSD and DragonFlyBSD - - TopologyEntry entry; - -#ifdef __linux__ - num_cores = readMaxFromSysFS("/sys/devices/system/cpu/present"); - if(num_cores == -1) - { - std::cerr << "Cannot read number of present cores\n"; - return false; - } - ++num_cores; - - // open /proc/cpuinfo - FILE * f_cpuinfo = fopen("/proc/cpuinfo", "r"); - if (!f_cpuinfo) - { - std::cerr << "Cannot open /proc/cpuinfo file.\n"; - return false; - } - - // map with key=pkg_apic_id (not necessarily zero based or sequential) and - // associated value=socket_id that should be 0 based and sequential - std::map found_pkg_ids; - topology.resize(num_cores); - char buffer[1024]; - while (0 != fgets(buffer, 1024, f_cpuinfo)) - { - if (strncmp(buffer, "processor", sizeof("processor") - 1) == 0) - { - pcm_sscanf(buffer) >> s_expect("processor\t: ") >> entry.os_id; - DBG(3, "os_core_id: " , entry.os_id ); - try { - TemporalThreadAffinity _(entry.os_id); - - populateEntry(entry); - if (populateHybridEntry(entry, entry.os_id) == false) - { - return false; - } - - topology[entry.os_id] = entry; - socketIdMap[entry.socket_id] = 0; - ++num_online_cores; - } - catch (std::exception &) - { - std::cerr << "Marking core " << entry.os_id << " offline\n"; - } - } - } - fclose(f_cpuinfo); - -#elif defined(__FreeBSD__) || defined(__DragonFly__) - - size_t size = sizeof(num_cores); - - if(0 != sysctlbyname("hw.ncpu", &num_cores, &size, NULL, 0)) - { - std::cerr << "Unable to get hw.ncpu from sysctl.\n"; - return false; + try { + CPUTopology cpuTopology(max_cpuid, hybrid); + topology = std::move(cpuTopology.topology); + num_cores = cpuTopology.num_cores; + num_online_cores = cpuTopology.num_online_cores; + socketIdMap = std::move(cpuTopology.socketIdMap); } - num_online_cores = num_cores; - - if (modfind("cpuctl") == -1) + catch (std::exception & e) { - std::cerr << "cpuctl(4) not loaded.\n"; + std::cerr << "ERROR: " << e.what() << "\n"; return false; } - for (int i = 0; i < num_cores; i++) - { - entry.os_id = i; - - populateEntry(entry); - if (populateHybridEntry(entry, i) == false) - { - return false; - } - - topology.push_back(entry); - socketIdMap[entry.socket_id] = 0; - } - -#endif - -#endif //end of ifdef _MSC_VER - - if(num_cores == 0) { - num_cores = (int32)topology.size(); - } if(num_sockets == 0) { num_sockets = (int32)(std::max)(socketIdMap.size(), (size_t)1); DBG(1, " num_sockets = ", num_sockets); diff --git a/src/cputopology.cpp b/src/cputopology.cpp new file mode 100644 index 00000000..bceab8ac --- /dev/null +++ b/src/cputopology.cpp @@ -0,0 +1,400 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2009-2024, Intel Corporation + +/*! \file cputopology.cpp + \brief CPU core topology discovery independent of the PCM object +*/ + +#include "cputopology.h" +#include "utils.h" +#include "debug.h" + +#if defined (__FreeBSD__) || defined(__DragonFly__) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#ifdef _MSC_VER +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +namespace pcm +{ + +#if defined(__FreeBSD__) || defined(__DragonFly__) +void pcm_cpuid_bsd(int leaf, PCM_CPUID_INFO& info, int core) +{ + cpuctl_cpuid_args_t cpuid_args_freebsd; + char cpuctl_name[64]; + + snprintf(cpuctl_name, 64, "/dev/cpuctl%d", core); + auto fd = ::open(cpuctl_name, O_RDWR); + + cpuid_args_freebsd.level = leaf; + + ::ioctl(fd, CPUCTL_CPUID, &cpuid_args_freebsd); + for (int i = 0; i < 4; ++i) + { + info.array[i] = cpuid_args_freebsd.data[i]; + } + ::close(fd); +} +#endif + +bool CPUTopology::discover() +{ + PCM_CPUID_INFO cpuinfo; + pcm_cpuid(0, cpuinfo); + const uint32 max_cpuid = cpuinfo.array[0]; + bool hybrid = false; + if (max_cpuid >= 0x7) + { + pcm_cpuid(7, 0, cpuinfo); + hybrid = (cpuinfo.reg.edx & (1 << 15)) ? true : false; + } + return discover(max_cpuid, hybrid); +} + +bool CPUTopology::discover(const uint32 max_cpuid, const bool hybrid) +{ + PCM_CPUID_INFO cpuid_args; + uint32 smtMaskWidth = 0; + uint32 coreMaskWidth = 0; + uint32 l2CacheMaskShift = 0; + uint32 l3CacheMaskShift = 0; + + struct domain + { + TopologyEntry::DomainTypeID type = TopologyEntry::DomainTypeID::InvalidDomainTypeID; + unsigned levelShift = 0, nextLevelShift = 0, width = 0; + }; + std::unordered_map topologyDomainMap; + { + const int32 maxTopoDomainAff = 1<<16; + int32 topoDomainAff = -1; + + for (int32 core = 0; core < maxTopoDomainAff; ++core) + { + try { + TemporalThreadAffinity _(core); + topoDomainAff = core; + } + catch (...) + { + } + if (topoDomainAff != -1) break; + } + + TemporalThreadAffinity _(topoDomainAff); + + if (initCoreMasks(smtMaskWidth, coreMaskWidth, l2CacheMaskShift, l3CacheMaskShift) == false) + { + std::cerr << "ERROR: Major problem? No leaf 0 under cpuid function 11.\n"; + return false; + } + + int subleaf = 0; + + std::vector topologyDomains; + if (max_cpuid >= 0x1F) + { + subleaf = 0; + do + { + pcm_cpuid(0x1F, subleaf, cpuid_args); + domain d; + d.type = (TopologyEntry::DomainTypeID)extract_bits_32(cpuid_args.reg.ecx, 8, 15); + DBG(1 , "pcm_cpuid 0x1F cpuid_args.reg.ecx = " , cpuid_args.reg.ecx , " d.type = ", d.type); + if (d.type == TopologyEntry::DomainTypeID::InvalidDomainTypeID) + { + break; + } + d.nextLevelShift = extract_bits_32(cpuid_args.reg.eax, 0, 4); + d.levelShift = topologyDomains.empty() ? 0 : topologyDomains.back().nextLevelShift; + d.width = d.nextLevelShift - d.levelShift; + topologyDomains.push_back(d); + ++subleaf; + } while (true); + + if (topologyDomains.size()) + { + domain d; + d.type = TopologyEntry::DomainTypeID::SocketPackageDomain; + d.levelShift = topologyDomains.back().nextLevelShift; + d.nextLevelShift = 32; + d.width = d.nextLevelShift - d.levelShift; + topologyDomains.push_back(d); + } + for (size_t l = 0; l < topologyDomains.size(); ++l) + { + topologyDomainMap[topologyDomains[l].type] = topologyDomains[l]; + DBG(1 , "Topology level: " , l , + " type: " , topologyDomains[l].type , + " (" , TopologyEntry::getDomainTypeStr(topologyDomains[l].type) , ")" , + " width: " , topologyDomains[l].width , + " levelShift: " , topologyDomains[l].levelShift , + " nextLevelShift: " , topologyDomains[l].nextLevelShift); + } + } + } + + auto populateEntry = [&topologyDomainMap,&smtMaskWidth, &coreMaskWidth, &l2CacheMaskShift, &l3CacheMaskShift](TopologyEntry& entry) + { + auto getAPICID = [&](const uint32 leaf) + { + PCM_CPUID_INFO cpuid_args; +#if defined(__FreeBSD__) || defined(__DragonFly__) + pcm_cpuid_bsd(leaf, cpuid_args, entry.os_id); +#else + pcm_cpuid(leaf, 0x0, cpuid_args); +#endif + return cpuid_args.array[3]; + }; + if (topologyDomainMap.size()) + { + auto getID = [&topologyDomainMap](const int apic_id, const TopologyEntry::DomainTypeID t) + { + const auto di = topologyDomainMap.find(t); + if (di != topologyDomainMap.end()) + { + const auto & d = di->second; + return extract_bits_32(apic_id, d.levelShift, d.nextLevelShift - 1); + } + return 0U; + }; + entry.tile_id = extract_bits_32(getAPICID(0xb), l2CacheMaskShift, 31); + const int apic_id = getAPICID(0x1F); + entry.thread_id = getID(apic_id, TopologyEntry::DomainTypeID::LogicalProcessorDomain); + entry.core_id = getID(apic_id, TopologyEntry::DomainTypeID::CoreDomain); + entry.module_id = getID(apic_id, TopologyEntry::DomainTypeID::ModuleDomain); + if (entry.tile_id == 0) + { + entry.tile_id = getID(apic_id, TopologyEntry::DomainTypeID::TileDomain); + } + entry.die_id = getID(apic_id, TopologyEntry::DomainTypeID::DieDomain); + entry.die_grp_id = getID(apic_id, TopologyEntry::DomainTypeID::DieGrpDomain); + entry.socket_id = getID(apic_id, TopologyEntry::DomainTypeID::SocketPackageDomain); + + auto getDomain = [&topologyDomainMap](const TopologyEntry::DomainTypeID t) + { + auto di = topologyDomainMap.find(t); + if (di != topologyDomainMap.end()) + { + return di->second; + } + throw std::runtime_error("DomainType not found"); + }; + domain d1 = getDomain( TopologyEntry::DomainTypeID::CoreDomain ); + domain d2 = getDomain( TopologyEntry::DomainTypeID::SocketPackageDomain ); + entry.socket_unique_core_id = extract_bits_32( apic_id, d1.levelShift, d2.levelShift - 1 ); + } + else + { + fillEntry(entry, smtMaskWidth, coreMaskWidth, l2CacheMaskShift, getAPICID(0xb)); + } + entry.l3_cache_id = extract_bits_32(getAPICID(0xb), l3CacheMaskShift, 31); + }; + + auto populateHybridEntry = [&hybrid](TopologyEntry& entry, int core) -> bool + { + if (hybrid == false) return true; + PCM_CPUID_INFO cpuid_args; +#if defined(__FreeBSD__) || defined(__DragonFly__) + pcm_cpuid_bsd(0x1a, cpuid_args, core); +#elif defined (_MSC_VER) || defined(__linux__) + pcm_cpuid(0x1a, 0x0, cpuid_args); + (void)core; +#else + std::cerr << "PCM Error: Hybrid processors are not supported for your OS\n"; + (void)core; + return false; +#endif + entry.native_cpu_model = extract_bits_32(cpuid_args.reg.eax, 0, 23); + entry.core_type = (TopologyEntry::CoreType) extract_bits_32(cpuid_args.reg.eax, 24, 31); + return true; + }; + +#ifdef _MSC_VER +// version for Windows 7 and later version + + char * slpi = new char[sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)]; + DWORD len = (DWORD)sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX); + BOOL res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len); + + while (res == FALSE) + { + deleteAndNullifyArray(slpi); + + if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) + { + slpi = new char[len]; + res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len); + } + else + { + tcerr << "Error in Windows function 'GetLogicalProcessorInformationEx': " << + GetLastError() << " "; + const TCHAR * strError = _com_error(GetLastError()).ErrorMessage(); + if (strError) tcerr << strError; + tcerr << "\n"; + return false; + } + } + + char * base_slpi = slpi; + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pi = NULL; + + for ( ; slpi < base_slpi + len; slpi += (DWORD)pi->Size) + { + pi = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi; + if (pi->Relationship == RelationProcessorCore) + { + const auto current_threads_per_core = (pi->Processor.Flags == LTP_PC_SMT) ? 2 : 1; + DBG(3, "thr per core: " , current_threads_per_core ); + num_cores += current_threads_per_core; + } + } + + num_online_cores = num_cores; + + if (num_cores != GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)) + { + std::cerr << "Error in processor group size counting: " << num_cores << "!=" << GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) << "\n"; + std::cerr << "Make sure your binary is compiled for 64-bit: using 'x64' platform configuration.\n"; + return false; + } + + for (int i = 0; i < (int)num_cores; i++) + { + ThreadGroupTempAffinity affinity(i); + + TopologyEntry entry; + entry.os_id = i; + + populateEntry(entry); + if (populateHybridEntry(entry, i) == false) + { + return false; + } + + topology.push_back(entry); + socketIdMap[entry.socket_id] = 0; + } + + deleteAndNullifyArray(base_slpi); + +#else + // for Linux, FreeBSD and DragonFlyBSD + + TopologyEntry entry; + +#ifdef __linux__ + num_cores = readMaxFromSysFS("/sys/devices/system/cpu/present"); + if(num_cores == -1) + { + std::cerr << "Cannot read number of present cores\n"; + return false; + } + ++num_cores; + + // open /proc/cpuinfo + FILE * f_cpuinfo = fopen("/proc/cpuinfo", "r"); + if (!f_cpuinfo) + { + std::cerr << "Cannot open /proc/cpuinfo file.\n"; + return false; + } + + // map with key=pkg_apic_id (not necessarily zero based or sequential) and + // associated value=socket_id that should be 0 based and sequential + std::map found_pkg_ids; + topology.resize(num_cores); + char buffer[1024]; + while (0 != fgets(buffer, 1024, f_cpuinfo)) + { + if (strncmp(buffer, "processor", sizeof("processor") - 1) == 0) + { + pcm_sscanf(buffer) >> s_expect("processor\t: ") >> entry.os_id; + DBG(3, "os_core_id: " , entry.os_id ); + try { + TemporalThreadAffinity _(entry.os_id); + + populateEntry(entry); + if (populateHybridEntry(entry, entry.os_id) == false) + { + return false; + } + + topology[entry.os_id] = entry; + socketIdMap[entry.socket_id] = 0; + ++num_online_cores; + } + catch (std::exception &) + { + std::cerr << "Marking core " << entry.os_id << " offline\n"; + } + } + } + fclose(f_cpuinfo); + +#elif defined(__FreeBSD__) || defined(__DragonFly__) + + size_t size = sizeof(num_cores); + + if(0 != sysctlbyname("hw.ncpu", &num_cores, &size, NULL, 0)) + { + std::cerr << "Unable to get hw.ncpu from sysctl.\n"; + return false; + } + num_online_cores = num_cores; + + if (modfind("cpuctl") == -1) + { + std::cerr << "cpuctl(4) not loaded.\n"; + return false; + } + + for (int i = 0; i < num_cores; i++) + { + entry.os_id = i; + + populateEntry(entry); + if (populateHybridEntry(entry, i) == false) + { + return false; + } + + topology.push_back(entry); + socketIdMap[entry.socket_id] = 0; + } + +#endif + +#endif //end of ifdef _MSC_VER + + if(num_cores == 0) { + num_cores = (int32)topology.size(); + } + + return true; +} + +} // namespace pcm diff --git a/src/cputopology.h b/src/cputopology.h new file mode 100644 index 00000000..cdeea2b0 --- /dev/null +++ b/src/cputopology.h @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2009-2024, Intel Corporation + +/*! \file cputopology.h + \brief CPU core topology discovery independent of the PCM object +*/ + +#pragma once + +#ifndef PCM_API +#define PCM_API +#endif + +#include "types.h" +#include "topologyentry.h" + +#include +#include +#include + +namespace pcm +{ + +#if defined(__FreeBSD__) || defined(__DragonFly__) +void pcm_cpuid_bsd(int leaf, PCM_CPUID_INFO& info, int core); +#endif + +/*! \brief Discovers the CPU core topology without creating a PCM object + + Enumerates all cores in the system (with their APIC-derived thread/core/module/ + tile/die/socket ids), the total number of cores, the number of online cores and + the map of package/socket APIC ids. It has no side effects (does not program any + PMU or access MSRs) and can be used by the PCM object as well as by simple + utilities like pcm-msr that only need topology information. +*/ +class PCM_API CPUTopology +{ +public: + std::vector topology; + int32 num_cores = 0; + int32 num_online_cores = 0; + //! map with key = pkg apic id (not necessarily zero based or sequential) and + //! value initialized to 0 (can be remapped to a logical socket id by the caller) + std::map socketIdMap; + + //! \brief discovers the topology using the supplied max cpuid leaf and hybrid flag + //! \throw std::runtime_error if the topology can not be discovered + CPUTopology(const uint32 max_cpuid, const bool hybrid) + { + if (discover(max_cpuid, hybrid) == false) + { + throw std::runtime_error("Cannot discover CPU topology"); + } + } + + //! \brief discovers the topology, detecting the max cpuid leaf and hybrid flag automatically + //! \throw std::runtime_error if the topology can not be discovered + CPUTopology() + { + if (discover() == false) + { + throw std::runtime_error("Cannot discover CPU topology"); + } + } + + int32 getNumCores() const { return num_cores; } + int32 getNumOnlineCores() const { return num_online_cores; } + + //! \brief checks if the core is online + bool isCoreOnline(const int32 os_core_id) const + { + return (topology[os_core_id].os_id != -1) && (topology[os_core_id].core_id != -1) && (topology[os_core_id].socket_id != -1); + } + +private: + bool discover(const uint32 max_cpuid, const bool hybrid); + bool discover(); +}; + +} // namespace pcm diff --git a/src/pcm-msr.cpp b/src/pcm-msr.cpp index 9cca616d..ac26bdbc 100644 --- a/src/pcm-msr.cpp +++ b/src/pcm-msr.cpp @@ -3,6 +3,7 @@ // written by Roman Dementiev #include "cpucounters.h" +#include "cputopology.h" #ifdef _MSC_VER #include #include "windows/windriver.h" @@ -157,6 +158,7 @@ int mainThrows(int argc, char * argv[]) outflag = false; } } + std::shared_ptr cpuTopology; // initialized on first use (for the "all cores" mode) while(1){ for (std::list::iterator it=corelist.begin(); it != corelist.end(); ++it){ int core = *it; @@ -222,11 +224,20 @@ int mainThrows(int argc, char * argv[]) } else { - set_signal_handlers(); - auto m = PCM::getInstance(); - for (uint32 i = 0; i < m->getNumCores(); ++i) + if (!cpuTopology) { - if (m->isCoreOnline(i)) + try { + cpuTopology = std::make_shared(); + } + catch (std::exception & e) + { + std::cerr << "ERROR: " << e.what() << "\n"; + return -1; + } + } + for (int32 i = 0; i < cpuTopology->getNumCores(); ++i) + { + if (cpuTopology->isCoreOnline(i)) { doOne(i, value); } From 264908499261920bd2255b0e89a69ab3cf3fb0ae Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Wed, 16 Sep 2026 17:36:50 +0200 Subject: [PATCH 14/40] Make RDT initialization on demand via public PCM::initRDT() API (#980) * Make RDT initialization on-demand via public PCM::initRDT() API Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> Co-authored-by: Roman Dementiev Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) --- src/cpucounters.cpp | 125 +++++++++++++++++++++++++++++++++----- src/cpucounters.h | 28 +++++---- src/daemon/daemon.cpp | 1 + src/pcm-sensor-server.cpp | 3 +- src/pcm.cpp | 2 + src/resctrl.cpp | 77 ++++++++++++++++++----- src/resctrl.h | 2 +- src/width_extender.h | 2 + 8 files changed, 195 insertions(+), 45 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 65107f55..333f0265 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -589,6 +589,8 @@ unsigned PCM::getMaxRMID() const void PCM::initRDT() { + if (RDTInitialized) + return; if (!(QOSMetricAvailable() && L3QOSMetricAvailable())) return; #ifdef __linux__ @@ -599,8 +601,11 @@ void PCM::initRDT() { std::cerr << "INFO: using Linux resctrl driver for RDT metrics (L3OCC, LMB, RMB) because environment variable PCM_USE_RESCTRL=1\n"; } - resctrl.init(); - useResctrl = true; + if (resctrl.init()) + { + useResctrl = true; + RDTInitialized = true; + } return; } if (resctrl.isMounted()) @@ -609,8 +614,11 @@ void PCM::initRDT() { std::cerr << "INFO: using Linux resctrl driver for RDT metrics (L3OCC, LMB, RMB) because resctrl driver is mounted.\n"; } - resctrl.init(); - useResctrl = true; + if (resctrl.init()) + { + useResctrl = true; + RDTInitialized = true; + } return; } if (isSecureBoot()) @@ -619,11 +627,19 @@ void PCM::initRDT() { std::cerr << "INFO: using Linux resctrl driver for RDT metrics (L3OCC, LMB, RMB) because Secure Boot mode is enabled.\n"; } - resctrl.init(); - useResctrl = true; + if (resctrl.init()) + { + useResctrl = true; + RDTInitialized = true; + } return; } #endif + if (MSR.empty() || noMSRMode()) + { + std::cerr << "ERROR: cannot initialize RDT metrics via MSR programming because MSR access is not available.\n"; + return; + } if (!quietMode) { std::cerr << "Initializing RMIDs" << std::endl; @@ -637,7 +653,9 @@ void PCM::initRDT() rmid[i] = maxRMID - 1; /* Associate each core with 1 RMID */ - for(int32 core = 0; core < num_cores; core ++ ) + bool success = true; + int32 lastProgrammedCore = -1; + for(int32 core = 0; core < num_cores && success; core ++ ) { if(!isCoreOnline(core)) continue; @@ -645,7 +663,10 @@ void PCM::initRDT() uint64 msr_qm_evtsel = 0 ; MSR[core]->lock(); //Read 0xC8F MSR for each core - MSR[core]->read(IA32_PQR_ASSOC, &msr_pqr_assoc); + if (MSR[core]->read(IA32_PQR_ASSOC, &msr_pqr_assoc) != (int32)sizeof(uint64)) + { + success = false; + } DBG(3, "initRMID reading IA32_PQR_ASSOC 0x" , std::hex , msr_pqr_assoc , std::dec); DBG(3, "Socket Id : " , topology[core].socket_id); @@ -653,15 +674,30 @@ void PCM::initRDT() msr_pqr_assoc |= (uint64)(rmid[topology[core].socket_id] & ((1ULL<<10)-1ULL)); DBG(3, "initRMID writing IA32_PQR_ASSOC 0x" , std::hex , msr_pqr_assoc , std::dec); //Write 0xC8F MSR with new RMID for each core - MSR[core]->write(IA32_PQR_ASSOC,msr_pqr_assoc); + if (success && MSR[core]->write(IA32_PQR_ASSOC,msr_pqr_assoc) != (int32)sizeof(uint64)) + { + success = false; + } + if (success) + { + lastProgrammedCore = core; + } msr_qm_evtsel = static_cast(rmid[topology[core].socket_id] & ((1ULL<<10)-1ULL)); msr_qm_evtsel <<= 32; //Write 0xC8D MSR with new RMID for each core DBG(3, "initRMID writing IA32_QM_EVTSEL 0x" , std::hex , msr_qm_evtsel , std::dec); - MSR[core]->write(IA32_QM_EVTSEL,msr_qm_evtsel); + if (success && MSR[core]->write(IA32_QM_EVTSEL,msr_qm_evtsel) != (int32)sizeof(uint64)) + { + success = false; + } MSR[core]->unlock(); + if (!success) + { + break; + } + /* Initializing the memory bandwidth counters */ if (CoreLocalMemoryBWMetricAvailable()) { @@ -673,8 +709,28 @@ void PCM::initRDT() } rmid[topology[core].socket_id] --; } + if (!success) + { + std::cerr << "ERROR: failed to program RMIDs via MSR access. RDT metrics will not be available.\n"; + /* Undo any completed RMID programming (reset to RMID 0 and event 0 as in cleanupRDT) */ + for(int32 core = 0; core <= lastProgrammedCore; core ++ ) + { + if(!isCoreOnline(core)) continue; + uint64 msr_pqr_assoc = 0; + MSR[core]->lock(); + MSR[core]->read(IA32_PQR_ASSOC, &msr_pqr_assoc); + msr_pqr_assoc &= 0xffffffff00000000ULL; + MSR[core]->write(IA32_PQR_ASSOC, msr_pqr_assoc); + MSR[core]->write(IA32_QM_EVTSEL, 0ULL); + MSR[core]->unlock(); + } + memory_bw_local.clear(); + memory_bw_total.clear(); + return; + } /* Get The scaling factor by running CPUID.0xF.0x1 instruction */ L3ScalingFactor = getL3ScalingFactor(); + RDTInitialized = true; } void PCM::initQOSevent(const uint64 event, const int32 core) @@ -3223,8 +3279,6 @@ PCM::PCM() : initUncoreObjects(); - initRDT(); - readCPUMicrocodeLevel(); #ifdef PCM_USE_PERF @@ -5268,6 +5322,9 @@ void PCM::resetPMU() } void PCM::cleanupRDT(const bool silent) { + if (!RDTInitialized) { + return; + } if(!(QOSMetricAvailable() && L3QOSMetricAvailable())) { return; } @@ -5275,9 +5332,15 @@ void PCM::cleanupRDT(const bool silent) if (useResctrl) { resctrl.cleanup(); + useResctrl = false; + RDTInitialized = false; return; } #endif + if (MSR.empty() || noMSRMode()) + { + return; + } for(int32 core = 0; core < num_cores; core ++ ) { @@ -5303,6 +5366,9 @@ void PCM::cleanupRDT(const bool silent) } + memory_bw_local.clear(); + memory_bw_total.clear(); + RDTInitialized = false; if (!silent) std::cerr << " Freeing up all RMIDs\n"; } @@ -5346,6 +5412,8 @@ void PCM::restoreOutput() void PCM::cleanup(const bool silent) { + cleanupRDT(silent); + if (MSR.empty()) return; if (!silent) std::cerr << "Cleaning up\n"; @@ -5355,7 +5423,6 @@ void PCM::cleanup(const bool silent) disableForceRTMAbortMode(silent); cleanupUncorePMUs(silent); - cleanupRDT(silent); #ifdef __linux__ if (needToRestoreNMIWatchdog) { @@ -5692,7 +5759,7 @@ void BasicCounterState::readAndAggregate(std::shared_ptr msr) } DBG(3, msr->getCoreId() , " " , cInstRetiredAny); - if (m->L3CacheOccupancyMetricAvailable() && m->useResctrl == false) + if (m->isRDTInitialized() && m->L3CacheOccupancyMetricAvailable() && m->useResctrl == false) { msr->lock(); uint64 event = 1; @@ -11231,9 +11298,21 @@ CounterWidthExtender::CounterWidthExtender(AbstractRawCounter * raw_counter_, ui try { UpdateThread = new std::thread( [&]() { - while (1) + // sleep in short slices so that the destructor can join this thread promptly + constexpr int sleepSliceMs = 50; + while (this->stopUpdateThread.load(std::memory_order_relaxed) == false) { - MySleepMs(static_cast(this->watchdog_delay_ms)); + for (int slept = 0; slept < static_cast(this->watchdog_delay_ms) + && this->stopUpdateThread.load(std::memory_order_relaxed) == false; + slept += sleepSliceMs) + { + const int remaining = static_cast(this->watchdog_delay_ms) - slept; + MySleepMs(remaining < sleepSliceMs ? remaining : sleepSliceMs); + } + if (this->stopUpdateThread.load(std::memory_order_relaxed)) + { + break; + } try { /* uint64 dummy = */ this->read(); } @@ -11255,6 +11334,20 @@ CounterWidthExtender::CounterWidthExtender(AbstractRawCounter * raw_counter_, ui } CounterWidthExtender::~CounterWidthExtender() { + // the watchdog thread accesses raw_counter, therefore it must be stopped and + // joined before the counter is destroyed. Destroying a still joinable + // std::thread would also call std::terminate(). + stopUpdateThread.store(true, std::memory_order_relaxed); + if (UpdateThread != nullptr && UpdateThread->joinable()) + { + try { + UpdateThread->join(); + } + catch (const std::exception & e) + { + std::cerr << "PCM Error: caught exception " << e.what() << " while joining the CounterWidthExtender watchdog thread\n"; + } + } deleteAndNullify(UpdateThread); deleteAndNullify(raw_counter); } diff --git a/src/cpucounters.h b/src/cpucounters.h index 6c8cd335..9aa3e8e8 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -863,6 +863,7 @@ class PCM_API PCM Resctrl resctrl; #endif bool useResctrl; + bool RDTInitialized{false}; std::shared_ptr clientBW; std::shared_ptr clientImcReads; @@ -1227,19 +1228,6 @@ class PCM_API PCM //! \return true if the package energy counters of all sockets have been initialized successfully bool initRAPLTPMI(); void initUncoreObjects(); - /*! - * \brief initializes each core with an RMID - * - * \returns nothing - */ - void initRDT(); - /*! - * \brief Initializes RDT - * - * Initializes RDT infrastructure through resctrl Linux driver or direct MSR programming. - * For the latter: initializes each core event MSR with an RMID for QOS event (L3 cache monitoring or memory bandwidth monitoring) - * \returns nothing - */ void initQOSevent(const uint64 event, const int32 core); void programBecktonUncore(int core); void programNehalemEPUncore(int core); @@ -1355,6 +1343,20 @@ class PCM_API PCM public: static bool isInitialized() { return instance != nullptr; } + /*! + * \brief Initializes RDT (on demand) + * + * Initializes RDT infrastructure through resctrl Linux driver or direct MSR programming. + * For the latter: initializes each core event MSR with an RMID for QOS event (L3 cache monitoring or memory bandwidth monitoring). + * RDT is not initialized by default: tools that need RDT-based metrics (L3OCC, LMB, RMB) + * must call this method explicitly after getInstance(). Calls after successful initialization are ignored; failed attempts may be retried. + * \returns nothing + */ + void initRDT(); + + //! \brief Returns true if RDT has been initialized via initRDT() + bool isRDTInitialized() const { return RDTInitialized; } + /*! \brief Set quiet mode for PCM initialization diff --git a/src/daemon/daemon.cpp b/src/daemon/daemon.cpp index d64318d7..13edf4c3 100644 --- a/src/daemon/daemon.cpp +++ b/src/daemon/daemon.cpp @@ -97,6 +97,7 @@ namespace PCMDaemon { void Daemon::setupPCM() { pcmInstance_ = PCM::getInstance(); + pcmInstance_->initRDT(); // the daemon exposes RDT-based metrics (L3OCC, LMB, RMB): initialize RDT on demand pcmInstance_->setBlocked(false); set_signal_handlers(); set_post_cleanup_callback(&Daemon::cleanup); diff --git a/src/pcm-sensor-server.cpp b/src/pcm-sensor-server.cpp index a17289f4..8c49e7c5 100644 --- a/src/pcm-sensor-server.cpp +++ b/src/pcm-sensor-server.cpp @@ -4772,8 +4772,9 @@ int mainThrows(int argc, char * argv[]) { // A HTTP interface to change the programming is planned PCM::ErrorCode status; PCM * pcmInstance = PCM::getInstance(); - pcmInstance->setAccel(accel); assert(pcmInstance); + pcmInstance->initRDT(); // pcm-sensor-server exposes RDT-based metrics (L3OCC, LMB, RMB): initialize RDT on demand + pcmInstance->setAccel(accel); if (forceRTMAbortMode) { pcmInstance->enableForceRTMAbortMode(); diff --git a/src/pcm.cpp b/src/pcm.cpp index ba34a7bf..e01b4a31 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -1506,6 +1506,8 @@ int mainThrows(int argc, char * argv[]) PCM * m = PCM::getInstance(); + m->initRDT(); // pcm uses RDT-based metrics (L3OCC, LMB, RMB): initialize RDT on demand + if (argc > 1) do { argv++; diff --git a/src/resctrl.cpp b/src/resctrl.cpp index 8d96858c..7d36a6b6 100644 --- a/src/resctrl.cpp +++ b/src/resctrl.cpp @@ -23,15 +23,24 @@ namespace pcm } return true; } - void Resctrl::init() + bool Resctrl::init() { if (isMounted() == false) { std::cerr << "ERROR: /sys/fs/resctrl is not mounted\n"; std::cerr << "ERROR: RDT metrics (L3OCC,LMB,RMB) will not be available\n"; std::cerr << "Mount it to make it work: mount -t resctrl resctrl /sys/fs/resctrl\n"; - return; + return false; } + FileMapType newL3OCC, newMBL, newMBT; + std::vector createdDirs; + const auto rollback = [&createdDirs]() + { + for (auto it = createdDirs.rbegin(); it != createdDirs.rend(); ++it) + { + rmdir(it->c_str()); + } + }; const auto numCores = pcm.getNumCores(); for (unsigned int c = 0; c < numCores; ++c) { @@ -39,20 +48,56 @@ namespace pcm { const auto C = std::to_string(c); const auto dir = std::string(PCMPath) + C; + auto groupDir = dir; // path used to write cpus_list (may switch to the container fallback path) struct stat st; - if (stat(dir.c_str(), &st) < 0 && mkdir(dir.c_str(), 0700) < 0) + if (stat(dir.c_str(), &st) < 0) { - std::cerr << "INFO: can't create directory " << dir << " error: " << strerror(errno) << "\n"; - const auto containerDir = std::string("/pcm") + dir; - if (stat(containerDir.c_str(), &st) < 0 && mkdir(containerDir.c_str(), 0700) < 0) + if (mkdir(dir.c_str(), 0700) < 0) { - std::cerr << "INFO: can't create directory " << containerDir << " error: " << strerror(errno) << "\n"; - std::cerr << "ERROR: RDT metrics (L3OCC,LMB,RMB) will not be available\n"; - break; + const auto mkdirErrno = errno; + if (stat(dir.c_str(), &st) < 0) + { + std::cerr << "INFO: can't create directory " << dir << " error: " << strerror(mkdirErrno) << "\n"; +const auto containerDir = std::string("/pcm") + dir; +bool createdContainerDir = false; +if (stat(containerDir.c_str(), &st) < 0) +{ + if (mkdir(containerDir.c_str(), 0700) < 0) + { + const auto containerMkdirErrno = errno; + if (stat(containerDir.c_str(), &st) < 0) + { + std::cerr << "INFO: can't create directory " << containerDir << " error: " << strerror(containerMkdirErrno) << "\n"; + std::cerr << "ERROR: RDT metrics (L3OCC,LMB,RMB) will not be available\n"; + rollback(); + return false; + } + } + else + { + createdContainerDir = true; + } +} +if (createdContainerDir) +{ + createdDirs.push_back(containerDir); +} +groupDir = containerDir; + } } + else + { + createdDirs.push_back(dir); + } + } + const auto cpus_listFilename = groupDir + "/cpus_list"; + if (writeSysFS(cpus_listFilename.c_str(), C, false) == false) + { + std::cerr << "ERROR: can't assign core " << C << " to monitoring group " << groupDir << "\n"; + std::cerr << "ERROR: RDT metrics (L3OCC,LMB,RMB) will not be available\n"; + rollback(); + return false; } - const auto cpus_listFilename = dir + "/cpus_list"; - writeSysFS(cpus_listFilename.c_str(), C, false); auto generateMetricFiles = [&dir, c] (PCM & pcm, const std::string & metric, FileMapType & fileMap) { auto getMetricFilename = [] (const std::string & dir, const uint64 s, const std::string & metric) @@ -68,18 +113,22 @@ namespace pcm }; if (pcm.L3CacheOccupancyMetricAvailable()) { - generateMetricFiles(pcm, "llc_occupancy", L3OCC); + generateMetricFiles(pcm, "llc_occupancy", newL3OCC); } if (pcm.CoreLocalMemoryBWMetricAvailable()) { - generateMetricFiles(pcm, "mbm_local_bytes", MBL); + generateMetricFiles(pcm, "mbm_local_bytes", newMBL); } if (pcm.CoreRemoteMemoryBWMetricAvailable()) { - generateMetricFiles(pcm, "mbm_total_bytes", MBT); + generateMetricFiles(pcm, "mbm_total_bytes", newMBT); } } } + L3OCC.swap(newL3OCC); + MBL.swap(newMBL); + MBT.swap(newMBT); + return true; } void Resctrl::cleanup() { diff --git a/src/resctrl.h b/src/resctrl.h index 70a87378..c1632f63 100644 --- a/src/resctrl.h +++ b/src/resctrl.h @@ -32,7 +32,7 @@ namespace pcm public: Resctrl(PCM & m) : pcm(m) {} bool isMounted(); - void init(); + bool init(); size_t getL3OCC(int core); size_t getMBL(int core); size_t getMBT(int core); diff --git a/src/width_extender.h b/src/width_extender.h index abcfc929..4e03be11 100644 --- a/src/width_extender.h +++ b/src/width_extender.h @@ -143,6 +143,8 @@ class CounterWidthExtender private: std::thread * UpdateThread; + //! \brief set by the destructor to request the watchdog thread to finish + std::atomic stopUpdateThread{false}; Mutex CounterMutex; From d71c7b9e7de3e9781f13267e07e387e5bc845482 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Fri, 18 Sep 2026 09:56:21 +0200 Subject: [PATCH 15/40] Expose the NUMA node of a PMT telemetry instance The telemetry instances of a socket are children of the same PCI device, so the NUMA node of that device identifies the socket an instance belongs to. This is needed to attribute per-instance telemetry (e.g. one instance per compute die) to a socket. Co-Authored-By: Claude Opus 5 (1M context) --- src/pmt.cpp | 35 +++++++++++++++++++++++++++++------ src/pmt.h | 6 ++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/pmt.cpp b/src/pmt.cpp index b99f4a5c..53f8539c 100644 --- a/src/pmt.cpp +++ b/src/pmt.cpp @@ -24,7 +24,12 @@ namespace pcm { class TelemetryArrayLinux : public TelemetryArrayInterface { TelemetryArrayLinux() = delete; - typedef std::vector FileVector; + struct TelemetryFile + { + std::FILE * file = nullptr; + int32 numaNode = -1; // NUMA node of the device exposing the telemetry instance + }; + typedef std::vector FileVector; typedef std::unordered_map FileMap; static std::shared_ptr TelemetryFiles; static FileMap & getTelemetryFiles() @@ -46,21 +51,29 @@ class TelemetryArrayLinux : public TelemetryArrayInterface std::cerr << "Error: failed to open " << path << "/telem" << std::endl; continue; } - TelemetryFilesTemp->operator[](guid).push_back(file); + TelemetryFile telemetryFile; + telemetryFile.file = file; + // the NUMA node of the PCI device the telemetry instance belongs to ("device" is the child of the PCI device) + const auto numaNodeStr = readSysFS((path + "/device/../numa_node").c_str(), true); + if (numaNodeStr.empty() == false) + { + telemetryFile.numaNode = (int32)std::atoi(numaNodeStr.c_str()); + } + TelemetryFilesTemp->operator[](guid).push_back(telemetryFile); } - + // print the telemetry files for (auto & guid : *TelemetryFilesTemp) { auto & files = guid.second; for (auto & file : files) { - if (!file) + if (!file.file) { std::cerr << "Error: file is null" << std::endl; continue; } - // std::cout << "guid: 0x" << std::hex << guid.first << " file: " << file << std::endl; + // std::cout << "guid: 0x" << std::hex << guid.first << " file: " << file.file << " numa node: " << file.numaNode << std::endl; } } @@ -102,9 +115,13 @@ class TelemetryArrayLinux : public TelemetryArrayInterface { return data.size(); } + int32 numaNode() override + { + return getTelemetryFiles().at(uid).at(instance).numaNode; + } void load() override { - FILE * file = getTelemetryFiles().at(uid).at(instance); + FILE * file = getTelemetryFiles().at(uid).at(instance).file; assert(file); // get the file size fseek(file, 0, SEEK_END); @@ -196,6 +213,12 @@ uint64 TelemetryArray::get(size_t qWordOffset, size_t lsb, size_t msb) return impl->get(qWordOffset, lsb, msb); } +int32 TelemetryArray::numaNode() +{ + assert(impl.get()); + return impl->numaNode(); +} + bool TelemetryDB::loadFromXML(const std::string& pmtXMLPath) { diff --git a/src/pmt.h b/src/pmt.h index 71f28103..9fc95662 100644 --- a/src/pmt.h +++ b/src/pmt.h @@ -19,6 +19,11 @@ class TelemetryArrayInterface } virtual void load() = 0; virtual uint64 get(size_t qWordOffset, size_t lsb, size_t msb) = 0; + //! \brief NUMA node of the device exposing the telemetry instance (-1 if unknown) + virtual int32 numaNode() + { + return -1; + } virtual ~TelemetryArrayInterface() {}; }; @@ -34,6 +39,7 @@ class TelemetryArray : public TelemetryArrayInterface size_t size() override; // in bytes void load() override; uint64 get(size_t qWordOffset, size_t lsb, size_t msb) override; + int32 numaNode() override; }; class TelemetryDB From a0d86a66ad20235140a400659a4b8ed8eceab74c Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Fri, 18 Sep 2026 09:56:30 +0200 Subject: [PATCH 16/40] Track RMIDs programmed by initRDT and allocate them from RMID 1 initRDT() associated the cores with RMIDs counting down from the maximum supported RMID and did not remember the association, so users of RDT-based metrics had no way to tell which RMID belongs to a core. Record the association in PCM (getCoreRMID(), getUsedRMIDs()) and allocate the RMIDs per socket in increasing order instead, starting at firstUsableRMID (1). RMID 0 is skipped because it is the default RMID (resctrl root group) which other software may use at the same time. Programming more cores than the socket supports RMIDs is now reported as an error instead of writing a wrapped-around (invalid) RMID. Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.cpp | 23 ++++++++++++++++++---- src/cpucounters.h | 48 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 333f0265..56fba920 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -648,9 +648,13 @@ void PCM::initRDT() /* Calculate maximum number of RMID supported by socket */ maxRMID = getMaxRMID(); DBG(2, "Maximum RMIDs per socket in the system : " , maxRMID ); - std::vector rmid(num_sockets); - for(int32 i = 0; i < num_sockets; i ++) - rmid[i] = maxRMID - 1; + /* Next RMID to be assigned on each socket: allocate RMIDs starting from 1. + RMID 0 is skipped because it is the default RMID (resctrl root group) and + therefore may be used by other software at the same time. */ + std::vector rmid(num_sockets, firstUsableRMID); + + coreRMIDs.clear(); + coreRMIDs.resize(num_cores, invalidRMID); /* Associate each core with 1 RMID */ bool success = true; @@ -659,6 +663,14 @@ void PCM::initRDT() { if(!isCoreOnline(core)) continue; + if (rmid[topology[core].socket_id] >= maxRMID) + { + std::cerr << "ERROR: number of cores on socket " << topology[core].socket_id << + " exceeds the number of usable RMIDs of the socket (" << (maxRMID - firstUsableRMID) << ").\n"; + success = false; + break; + } + uint64 msr_pqr_assoc = 0 ; uint64 msr_qm_evtsel = 0 ; MSR[core]->lock(); @@ -681,6 +693,7 @@ void PCM::initRDT() if (success) { lastProgrammedCore = core; + coreRMIDs[core] = rmid[topology[core].socket_id]; } msr_qm_evtsel = static_cast(rmid[topology[core].socket_id] & ((1ULL<<10)-1ULL)); @@ -707,7 +720,7 @@ void PCM::initRDT() memory_bw_total.push_back(std::make_shared(new CounterWidthExtender::MBTCounter(MSR[core]), 24, 1000)); } } - rmid[topology[core].socket_id] --; + rmid[topology[core].socket_id] ++; } if (!success) { @@ -726,6 +739,7 @@ void PCM::initRDT() } memory_bw_local.clear(); memory_bw_total.clear(); + coreRMIDs.clear(); return; } /* Get The scaling factor by running CPUID.0xF.0x1 instruction */ @@ -5368,6 +5382,7 @@ void PCM::cleanupRDT(const bool silent) memory_bw_local.clear(); memory_bw_total.clear(); + coreRMIDs.clear(); RDTInitialized = false; if (!silent) std::cerr << " Freeing up all RMIDs\n"; diff --git a/src/cpucounters.h b/src/cpucounters.h index 9aa3e8e8..0c015495 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -864,6 +865,7 @@ class PCM_API PCM #endif bool useResctrl; bool RDTInitialized{false}; + std::vector coreRMIDs{}; // RMID associated with each core by initRDT() via direct MSR programming (invalidRMID if none) std::shared_ptr clientBW; std::shared_ptr clientImcReads; @@ -1348,6 +1350,7 @@ class PCM_API PCM * * Initializes RDT infrastructure through resctrl Linux driver or direct MSR programming. * For the latter: initializes each core event MSR with an RMID for QOS event (L3 cache monitoring or memory bandwidth monitoring). + * RMIDs are allocated per socket in increasing order starting from firstUsableRMID. * RDT is not initialized by default: tools that need RDT-based metrics (L3OCC, LMB, RMB) * must call this method explicitly after getInstance(). Calls after successful initialization are ignored; failed attempts may be retried. * \returns nothing @@ -1357,6 +1360,51 @@ class PCM_API PCM //! \brief Returns true if RDT has been initialized via initRDT() bool isRDTInitialized() const { return RDTInitialized; } + //! \brief Value returned by getCoreRMID() for cores without an RMID association + enum : uint32 { invalidRMID = ~0U }; + + /*! \brief First RMID used by initRDT() for direct MSR programming + + RMID 0 is skipped because it is the default RMID (resctrl root group) which + other software may use at the same time. + */ + enum : uint32 { firstUsableRMID = 1 }; + + /*! + * \brief Returns the RMID associated with the core by initRDT() via direct MSR programming + * + * \returns invalidRMID if the core has no RMID association, e.g. it is offline, RDT is not + * initialized or RDT uses the resctrl driver instead of direct MSR programming + */ + uint32 getCoreRMID(const int32 core) const + { + if (core < 0 || (size_t)core >= coreRMIDs.size()) + { + return invalidRMID; + } + return coreRMIDs[core]; + } + + /*! + * \brief Returns the RMIDs programmed by initRDT() via direct MSR programming + * + * \returns sorted list of used RMIDs, empty if RDT is not initialized or RDT uses the resctrl driver + */ + std::vector getUsedRMIDs() const + { + std::vector result; + for (const auto & rmid : coreRMIDs) + { + if (rmid != invalidRMID) + { + result.push_back(rmid); + } + } + std::sort(result.begin(), result.end()); + result.erase(std::unique(result.begin(), result.end()), result.end()); + return result; + } + /*! \brief Set quiet mode for PCM initialization From 99a2c0511aeea50ce6d8192c103617cbb0369c63 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Fri, 18 Sep 2026 10:15:22 +0200 Subject: [PATCH 17/40] Add helpers for the per-RMID Application Energy Telemetry (AET) counters The AET PMT telemetry aggregator (CWF) reports per RMID a core energy counter in Joule and an activity (Cdyn) counter in nanofarad, both in the "U63.45.18" fixed point format with a valid bit, in one telemetry instance per compute die. Add helpers to build and program the PMT events of chosen RMIDs (AETEventEncoding(), addAETEvents(), programAET()), to read them back as raw counters or as metrics in Joule/nanofarad, either accumulated or for the sample interval (getAETCounter(), getAETMetric(), getAETCoreEnergyJoule(), getAETActivityNanoFarad()), and to map the telemetry instances to sockets (getAETNumInstances(), getAETInstanceSocket()). Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.h | 324 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 324 insertions(+) diff --git a/src/cpucounters.h b/src/cpucounters.h index 0c015495..29574e04 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -5598,6 +5598,330 @@ inline std::vector getPMTEvent(const PCM::RawEventEncoding& eventEnc, co return getRegisterEvent(eventEnc, before.PMTValues, after.PMTValues); } +/*! \brief description of the per-RMID Application Energy Telemetry (AET) PMT counters + + The AET telemetry aggregator is processor-specific (currently only CWF is + supported) and exposes two qwords per RMID: + + qword 2 * rmid : RMID__CORE_ENERGY, core energy in Joule + qword 2 * rmid + 1 : RMID__ACTIVITY, dynamic capacitance (Cdyn) of the cores in nanofarad + + In both qwords bits 0..62 hold the (monotonically increasing) counter value in + the "U63.45.18" fixed point format (45 integer and 18 fractional bits) and bit + 63 indicates that the counter value is valid. + + Note that the per-RMID core energy metric is not comparable to the package/CPU + energy of MSR_PKG_ENERGY_STATUS. +*/ +struct AET +{ + //! \brief returns the UID (GUID) of the PMT telemetry aggregator holding the AET counters of this processor (0 if the processor does not support AET) + static uint64 UID() + { + switch (PCM::getCPUFamilyModelFromCPUID()) + { + case PCM::CWF: + return 0x26696143ULL; + } + return 0; + } + //! \brief returns the name of the AET telemetry aggregator of this processor as used in the PMT telemetry database ("" if the processor does not support AET) + static const char * aggregatorName() + { + switch (PCM::getCPUFamilyModelFromCPUID()) + { + case PCM::CWF: + return "cwf"; + } + return ""; + } + //! \brief returns true if this processor supports AET + static bool supported() + { + return UID() != 0; + } + enum Counter + { + CoreEnergy = 0, + Activity = 1, + NumCounters // number of AET counters (= qwords) per RMID + }; + /*! \brief sample semantics of an AET counter + + The AET counters are accumulators: Total is the value accumulated since the + counter was reset, Interval the value accumulated during the sample interval. + */ + enum Sample + { + Total = PCM::MSRType::Static, + Interval = PCM::MSRType::Freerun + }; + enum + { + valueLSB = 0, + valueMSB = 62, + validBit = 63, + fractionalBits = 18 // number of fractional bits of the "U63.45.18" fixed point format + }; + static const char * counterName(const Counter counter) + { + return (counter == CoreEnergy) ? "CORE_ENERGY" : "ACTIVITY"; + } + //! \brief returns the unit symbol of an AET counter: Joule for the core energy, nanofarad for the Cdyn activity + static const char * counterUnit(const Counter counter) + { + return (counter == CoreEnergy) ? "J" : "nF"; + } + /*! \brief converts a raw AET counter value in the "U63.45.18" fixed point format to a metric value + + \return core energy in Joule for AET::CoreEnergy, dynamic capacitance (Cdyn) in nanofarad for AET::Activity + */ + static double toMetric(const uint64 rawValue) + { + return double(rawValue) / double(1ULL << fractionalBits); + } +}; + +//! \brief returns the PMT event encoding of an AET counter (or of its valid bit) of the given RMID +inline PCM::RawEventEncoding AETEventEncoding(const size_t rmid, const AET::Counter counter, const bool validBit = false, + const AET::Sample sample = AET::Total) +{ + PCM::RawEventEncoding enc{}; + enc[PCM::PMTEventPosition::UID] = AET::UID(); + enc[PCM::PMTEventPosition::offset] = rmid * AET::NumCounters + counter; + enc[PCM::PMTEventPosition::type] = validBit ? AET::Total : sample; // the valid bit is always a snapshot + enc[PCM::PMTEventPosition::lsb] = validBit ? AET::validBit : AET::valueLSB; + enc[PCM::PMTEventPosition::msb] = validBit ? AET::validBit : AET::valueMSB; + return enc; +} + +//! \brief returns the name of an AET counter as used in the PMT telemetry database, e.g. "cwf.RMID_0_CORE_ENERGY.RMID_0_CORE_ENERGY_VALID" +inline std::string AETEventName(const size_t rmid, const AET::Counter counter, const bool validBit = false) +{ + const std::string sample = "RMID_" + std::to_string(rmid) + "_" + AET::counterName(counter); + return std::string(AET::aggregatorName()) + "." + sample + "." + sample + (validBit ? "_VALID" : ""); +} + +/*! \brief returns the number of AET telemetry instances in the system + + There is one AET telemetry instance per compute die (3 per socket on CWF). The + instance is the index into the vectors returned by getAETCounter()/getAETMetric(). + + \return 0 if AET telemetry is not available +*/ +inline size_t getAETNumInstances() +{ + const auto uid = AET::UID(); + return (uid == 0) ? 0 : TelemetryArray::numInstances(uid); +} + +//! \brief returns the socket of every AET telemetry instance (-1 for instances with unknown socket) +inline const std::vector & getAETInstanceSockets() +{ + static const std::vector sockets = []() + { + std::vector result; + const auto numInstances = getAETNumInstances(); + for (size_t instance = 0; instance < numInstances; ++instance) + { + const auto node = TelemetryArray(AET::UID(), instance).numaNode(); + result.push_back((node < 0) ? -1 : PCM::getInstance()->mapNUMANodeToSocket((uint32)node)); + } + return result; + }(); + return sockets; +} + +//! \brief returns the socket of an AET telemetry instance (-1 if unknown) +inline int32 getAETInstanceSocket(const size_t instance) +{ + const auto & sockets = getAETInstanceSockets(); + return (instance < sockets.size()) ? sockets[instance] : -1; +} + +/*! \brief returns the number of RMIDs whose AET counters can be collected on this system + + This is the minimum of the number of RMIDs in the AET telemetry array and the number + of RMIDs supported by RDT: the trailing qwords of the telemetry array may hold samples + which do not belong to any RMID. + + \return 0 if AET telemetry is not available +*/ +inline size_t getAETNumRMIDs() +{ + if (getAETNumInstances() == 0) + { + return 0; + } + const auto inTelemetryArray = TelemetryArray(AET::UID(), 0).numQWords() / AET::NumCounters; + return (std::min)((size_t)PCM::getInstance()->getMaxRMID(), inTelemetryArray); +} + +/*! \brief adds the AET events of the given RMIDs to a raw PMU configuration + + Both the accumulated (AET::Total) and the interval (AET::Interval) samples of the + counters are added together with their valid bits. +*/ +inline void addAETEvents(PCM::RawPMUConfigs & configs, const std::vector & rmids) +{ + auto & pmtConfig = configs["pmt"]; + for (const auto & rmid : rmids) + { + for (const auto counter : { AET::CoreEnergy, AET::Activity }) + { + for (const auto sample : { AET::Total, AET::Interval }) + { + pmtConfig.fixed.push_back(PCM::RawEventConfig{ AETEventEncoding(rmid, counter, false, sample), + AETEventName(rmid, counter, false) }); + } + pmtConfig.fixed.push_back(PCM::RawEventConfig{ AETEventEncoding(rmid, counter, true), + AETEventName(rmid, counter, true) }); + } + } +} + +/*! \brief programs the AET counters of the given RMIDs + + Discards the programming of all other raw (register) events. To collect AET + counters together with other raw events call addAETEvents(..) and pass the + resulting configuration to PCM::program(..) instead. + + \param rmids RMIDs to collect the AET counters for + \param silent suppress informational output +*/ +inline PCM::ErrorCode programAET(const std::vector & rmids, const bool silent = false) +{ + if (AET::supported() == false) + { + std::cerr << "ERROR: AET telemetry is not supported on this processor\n"; + return PCM::UnknownError; + } + const auto numRMIDs = getAETNumRMIDs(); + if (numRMIDs == 0) + { + std::cerr << "ERROR: AET telemetry (PMT UID 0x" << std::hex << AET::UID() << std::dec << ") is not available on this system\n"; + return PCM::UnknownError; + } + for (const auto & rmid : rmids) + { + if (rmid >= numRMIDs) + { + std::cerr << "ERROR: RMID " << rmid << " is out of range, AET telemetry supports RMIDs 0.." << (numRMIDs - 1) << "\n"; + return PCM::UnknownError; + } + } + PCM::RawPMUConfigs configs; + addAETEvents(configs, rmids); + return PCM::getInstance()->program(configs, silent); +} + +//! \brief value of an AET counter of a single telemetry instance +struct AETCounterValue +{ + uint64 value = 0; + bool valid = false; +}; + +/*! \brief reads a programmed AET counter of the given RMID + + \return the counter value of every AET telemetry instance in the system +*/ +inline std::vector getAETCounter(const size_t rmid, const AET::Counter counter, + const SystemCounterState & before, const SystemCounterState & after, + const AET::Sample sample = AET::Total) +{ + const auto values = getPMTEvent(AETEventEncoding(rmid, counter, false, sample), before, after); + const auto validBits = getPMTEvent(AETEventEncoding(rmid, counter, true), before, after); + std::vector result; + for (size_t i = 0; i < values.size(); ++i) + { + result.push_back(AETCounterValue{ values[i], i < validBits.size() && validBits[i] != 0 }); + } + return result; +} + +//! \brief metric value of an AET counter of a single telemetry instance +struct AETMetricValue +{ + double value = 0.; //!< core energy in Joule or dynamic capacitance (Cdyn) in nanofarad, see AET::counterUnit() + bool valid = false; +}; + +/*! \brief reads a programmed AET counter of the given RMID and converts it to its metric + + \return core energy in Joule (AET::CoreEnergy) or dynamic capacitance (Cdyn) in + nanofarad (AET::Activity) of every AET telemetry instance (compute die) in the system, + indexed as in getAETInstanceSocket() +*/ +inline std::vector getAETMetric(const size_t rmid, const AET::Counter counter, + const SystemCounterState & before, const SystemCounterState & after, + const AET::Sample sample = AET::Total) +{ + std::vector result; + for (const auto & counterValue : getAETCounter(rmid, counter, before, after, sample)) + { + result.push_back(AETMetricValue{ AET::toMetric(counterValue.value), counterValue.valid }); + } + return result; +} + +/*! \brief reads a programmed AET counter of the given RMID on the given socket and converts it to its metric + + RDT associates the cores of a socket with different RMIDs while the AET telemetry is + reported per compute die (3 per socket on CWF): the metric of an RMID on a socket is + therefore the sum of the valid values of the compute dies of that socket. + + Note that the per-RMID core energy metric is not comparable to the package/CPU + energy of MSR_PKG_ENERGY_STATUS, also not when summed up over the RMIDs. + + \return core energy in Joule (AET::CoreEnergy) or dynamic capacitance (Cdyn) in + nanofarad (AET::Activity), invalid if no compute die of the socket reports the RMID +*/ +inline AETMetricValue getAETMetric(const size_t rmid, const AET::Counter counter, const int32 socket, + const SystemCounterState & before, const SystemCounterState & after, + const AET::Sample sample = AET::Total) +{ + AETMetricValue result{}; + const auto perInstance = getAETMetric(rmid, counter, before, after, sample); + for (size_t instance = 0; instance < perInstance.size(); ++instance) + { + if (perInstance[instance].valid && getAETInstanceSocket(instance) == socket) + { + result.value += perInstance[instance].value; + result.valid = true; + } + } + return result; +} + +//! \brief reads the core energy in Joule of the given RMID (one value per AET telemetry instance) +inline std::vector getAETCoreEnergyJoule(const size_t rmid, const SystemCounterState & before, const SystemCounterState & after, + const AET::Sample sample = AET::Total) +{ + return getAETMetric(rmid, AET::CoreEnergy, before, after, sample); +} + +//! \brief reads the core energy in Joule of the given RMID on the given socket +inline AETMetricValue getAETCoreEnergyJoule(const size_t rmid, const int32 socket, const SystemCounterState & before, const SystemCounterState & after, + const AET::Sample sample = AET::Total) +{ + return getAETMetric(rmid, AET::CoreEnergy, socket, before, after, sample); +} + +//! \brief reads the dynamic capacitance (Cdyn) in nanofarad of the given RMID (one value per AET telemetry instance) +inline std::vector getAETActivityNanoFarad(const size_t rmid, const SystemCounterState & before, const SystemCounterState & after, + const AET::Sample sample = AET::Total) +{ + return getAETMetric(rmid, AET::Activity, before, after, sample); +} + +//! \brief reads the dynamic capacitance (Cdyn) in nanofarad of the given RMID on the given socket +inline AETMetricValue getAETActivityNanoFarad(const size_t rmid, const int32 socket, const SystemCounterState & before, const SystemCounterState & after, + const AET::Sample sample = AET::Total) +{ + return getAETMetric(rmid, AET::Activity, socket, before, after, sample); +} + template uint64 getMSREvent(const uint64& index, const PCM::MSRType& type, const CounterStateType& before, const CounterStateType& after) { From 6b59ef32b76af3a922dfee8fe3eccee1caea1767 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Fri, 18 Sep 2026 10:15:22 +0200 Subject: [PATCH 18/40] pcm: display AET metrics CENRG and CDYN with the new --aet option With --aet the pcm utility programs the AET counters of the RMIDs that RDT associated with the cores (direct MSR programming only, in resctrl mode the RMIDs of the driver are unknown) and shows two new columns per core, die, socket and for the whole system, in the text and in the CSV output: CENRG : core energy consumed in the sample interval (in Joules) CDYN : dynamic capacitance (Cdyn) of the cores in the sample interval (in nanofarad) Without the option nothing is programmed and the output is unchanged. If the metrics are requested but unavailable (processor without AET support, no AET telemetry exposed by the OS, RDT via resctrl) the reason is reported. Co-Authored-By: Claude Opus 5 (1M context) --- src/pcm.cpp | 203 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 195 insertions(+), 8 deletions(-) diff --git a/src/pcm.cpp b/src/pcm.cpp index e01b4a31..165cf7be 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -70,6 +70,82 @@ double getAverageUncoreFrequencyGhz(const UncoreStateType& before, const UncoreS return getAverageUncoreFrequency(before, after) / 1e9; } +//! \brief AET (Application Energy Telemetry) metrics of the sample interval, see program_aet() +struct AETRow +{ + bool available = false; // AET metrics are collected on this system + AETMetricValue energy{}; // CENRG: core energy in Joule + AETMetricValue cdyn{}; // CDYN: dynamic capacitance in nanofarad +}; + +bool aet_metrics = false; // request the AET metrics (CENRG, CDYN), see the --aet command line option + +//! \brief returns true if the AET metrics are collected on this system +bool aet_available(const PCM * m) +{ + // AET is programmed once (see program_aet()) before any output is printed + static const bool available = aet_metrics && AET::supported() && getAETNumRMIDs() > 0 + && m->getUsedRMIDs().empty() == false; + return available; +} + +//! \brief returns the AET metrics of the interval for a single core +AETRow get_aet_row(const PCM * m, const uint32 core, const SystemCounterState & before, const SystemCounterState & after) +{ + AETRow row; + row.available = aet_available(m); + const auto rmid = m->getCoreRMID(core); + if (row.available == false || rmid == PCM::invalidRMID) + { + return row; // metrics stay invalid and are printed as "N/A" + } + const auto socket = m->getSocketId(core); + row.energy = getAETCoreEnergyJoule(rmid, socket, before, after, AET::Interval); + row.cdyn = getAETActivityNanoFarad(rmid, socket, before, after, AET::Interval); + return row; +} + +//! \brief returns the sum of the AET metrics of the interval over all online cores selected by the filter +template +AETRow get_aet_row_sum(const PCM * m, const CoreFilter & filter, const SystemCounterState & before, const SystemCounterState & after) +{ + AETRow result; + result.available = aet_available(m); + if (result.available == false) + { + return result; + } + for (uint32 core = 0; core < m->getNumCores(); ++core) + { + if (m->isCoreOnline(core) == false || filter(core) == false) + { + continue; + } + const auto row = get_aet_row(m, core, before, after); + if (row.energy.valid) + { + result.energy.value += row.energy.value; + result.energy.valid = true; + } + if (row.cdyn.valid) + { + result.cdyn.value += row.cdyn.value; + result.cdyn.valid = true; + } + } + return result; +} + +std::string aet_format(const AETMetricValue & metric) +{ + if (metric.valid == false) + return "N/A"; + + char buffer[1024]; + snprintf(buffer, 1024, "%6.2f", metric.value); + return buffer; +} + void print_help(const string & prog_name) { cout << "\n Usage: \n " << prog_name @@ -91,6 +167,11 @@ void print_help(const string & prog_name) cout << " -ns | --nosockets | /ns => hide socket related output\n"; cout << " -nsys | --nosystem | /nsys => hide system related output\n"; cout << " --die => show aggregated core metrics per die\n"; + cout << " -aet | --aet | /aet => show per-RMID AET metrics (CENRG: core energy in Joules,\n" + << " CDYN: dynamic capacitance in nanofarad). Requires a processor\n" + << " with AET support and RDT monitoring via direct MSR programming.\n" + << " The per-RMID core energy metric is not comparable to the\n" + << " package/CPU energy of MSR_PKG_ENERGY_STATUS\n"; cout << " --color => use ASCII colors\n"; cout << " --no-color => don't use ASCII colors\n"; cout << " -csv[=file.csv] | /csv[=file.csv] => output compact CSV format to screen or\n" @@ -149,7 +230,7 @@ void print_basic_metrics(const PCM * m, const State & state1, const State & stat } template -void print_other_metrics(const PCM * m, const State & state1, const State & state2) +void print_other_metrics(const PCM * m, const State & state1, const State & state2, const AETRow & aet = AETRow{}) { if (m->L3CacheOccupancyMetricAvailable()) cout << setNextColor() << " " << setw(6) << l3cache_occ_format(getL3CacheOccupancy(state2)); @@ -157,6 +238,11 @@ void print_other_metrics(const PCM * m, const State & state1, const State & stat cout << setNextColor() << " " << setw(6) << getLocalMemoryBW(state1, state2); if (m->CoreRemoteMemoryBWMetricAvailable()) cout << setNextColor() << " " << setw(6) << getRemoteMemoryBW(state1, state2); + if (aet.available) + { + cout << setNextColor() << " " << setw(6) << aet_format(aet.energy); + cout << setNextColor() << " " << setw(6) << aet_format(aet.cdyn); + } cout << setNextColor() << " " << temp_format(state2.getThermalHeadroom()) << "\n"; } @@ -232,6 +318,11 @@ void print_output(PCM * m, if (m->L3CacheOccupancyMetricAvailable()) cout << " L3OCC : L3 occupancy (in KBytes)\n"; if (m->CoreLocalMemoryBWMetricAvailable()) cout << " LMB : L3 cache external bandwidth satisfied by local memory (in MBytes)\n"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << " RMB : L3 cache external bandwidth satisfied by remote memory (in MBytes)\n"; + if (aet_available(m)) + { + cout << " CENRG : core energy consumed in the sample interval (in Joules). Note that this per-RMID metric is not comparable to the package/CPU energy of MSR_PKG_ENERGY_STATUS\n"; + cout << " CDYN : dynamic capacitance (Cdyn) of the cores in the sample interval (in nanofarad)\n"; + } cout << " TEMP : Temperature reading in 1 degree Celsius relative to the TjMax temperature (thermal headroom): 0 corresponds to the max temperature\n"; cout << " energy: Energy in Joules\n"; cout << "\n"; @@ -280,6 +371,8 @@ void print_output(PCM * m, cout << setNextColor() << " LMB |"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << setNextColor() << " RMB |"; + if (aet_available(m)) + cout << setNextColor() << " CENRG |" << setNextColor() << " CDYN |"; cout << setNextColor() << " TEMP\n\n"; @@ -300,7 +393,7 @@ void print_output(PCM * m, cout << " " << setw(3) << i << " " << setw(2) << m->getSocketId(i); print_basic_metrics(m, cstates1[i], cstates2[i], metricVersion); - print_other_metrics(m, cstates1[i], cstates2[i]); + print_other_metrics(m, cstates1[i], cstates2[i], get_aet_row(m, i, sstate1, sstate2)); cout << resetColor(); } } @@ -322,7 +415,9 @@ void print_output(PCM * m, const auto & key = entry.first; cout << " SKT " << setw(4) << (std::to_string(key.first) + "." + std::to_string(key.second)); print_basic_metrics(m, die_cstates1[key], die_cstates2[key], metricVersion); - print_other_metrics(m, die_cstates1[key], die_cstates2[key]); + print_other_metrics(m, die_cstates1[key], die_cstates2[key], + get_aet_row_sum(m, [&m, &key](const uint32 core) { return m->getSocketId(core) == key.first && m->getDieId(core) == key.second; }, + sstate1, sstate2)); cout << resetColor(); } } @@ -335,7 +430,8 @@ void print_output(PCM * m, { cout << " SKT " << setw(2) << i; print_basic_metrics(m, sktstate1[i], sktstate2[i], metricVersion); - print_other_metrics(m, sktstate1[i], sktstate2[i]); + print_other_metrics(m, sktstate1[i], sktstate2[i], + get_aet_row_sum(m, [&m, &i](const uint32 core) { return m->getSocketId(core) == (int32)i; }, sstate1, sstate2)); cout << resetColor(); } } @@ -357,6 +453,12 @@ void print_output(PCM * m, cout << setNextColor() <<" N/A "; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << setNextColor() <<" N/A "; + if (aet_available(m)) + { + const auto aet = get_aet_row_sum(m, [](const uint32) { return true; }, sstate1, sstate2); + cout << setNextColor() << " " << setw(6) << aet_format(aet.energy); + cout << setNextColor() << " " << setw(6) << aet_format(aet.cdyn); + } cout << setNextColor() << " N/A\n"; cout << resetColor(); @@ -774,6 +876,9 @@ void print_csv_header(PCM * m, if (m->HBMmemoryTrafficMetricsAvailable()) print_csv_header_helper(header,2); + if (aet_available(m)) + print_csv_header_helper(header, 2); // CENRG,CDYN + print_csv_header_helper(header,7); if (m->getNumSockets() > 1) { // QPI info only for multi socket systems if (m->incomingQPITrafficMetricsAvailable()) @@ -814,6 +919,8 @@ void print_csv_header(PCM * m, print_csv_header_helper(header); if (m->CoreRemoteMemoryBWMetricAvailable()) print_csv_header_helper(header); + if (aet_available(m)) + print_csv_header_helper(header, 2); // CENRG,CDYN if (m->memoryTrafficMetricsAvailable()) print_csv_header_helper(header,2); if (m->localMemoryRequestRatioMetricAvailable()) @@ -925,6 +1032,8 @@ void print_csv_header(PCM * m, print_csv_header_helper(header); if (m->CoreRemoteMemoryBWMetricAvailable()) print_csv_header_helper(header); + if (aet_available(m)) + print_csv_header_helper(header, 2); // CENRG,CDYN print_csv_header_helper(header); // TEMP print_csv_header_helper(header, 7); // INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom% } @@ -947,6 +1056,8 @@ void print_csv_header(PCM * m, print_csv_header_helper(header); if (m->CoreRemoteMemoryBWMetricAvailable()) print_csv_header_helper(header); + if (aet_available(m)) + print_csv_header_helper(header, 2); // CENRG,CDYN for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) @@ -975,6 +1086,9 @@ void print_csv_header(PCM * m, if (m->HBMmemoryTrafficMetricsAvailable()) cout << "HBM_READ,HBM_WRITE,"; + if (aet_available(m)) + cout << "CENRG,CDYN,"; + cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; if (m->getNumSockets() > 1) { // QPI info only for multi socket systems if (m->incomingQPITrafficMetricsAvailable()) @@ -1020,6 +1134,8 @@ void print_csv_header(PCM * m, cout << "LMB,"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << "RMB,"; + if (aet_available(m)) + cout << "CENRG,CDYN,"; if (m->memoryTrafficMetricsAvailable()) cout << "READ,WRITE,"; if (m->localMemoryRequestRatioMetricAvailable()) @@ -1127,6 +1243,8 @@ void print_csv_header(PCM * m, cout << "LMB,"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << "RMB,"; + if (aet_available(m)) + cout << "CENRG,CDYN,"; cout << "TEMP,"; cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; } @@ -1146,6 +1264,8 @@ void print_csv_header(PCM * m, cout << "LMB,"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << "RMB,"; + if (aet_available(m)) + cout << "CENRG,CDYN,"; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) if (m->isCoreCStateResidencySupported(s)) @@ -1203,7 +1323,7 @@ void print_basic_metrics_csv(const PCM * m, const State & state1, const State & } template -void print_other_metrics_csv(const PCM * m, const State & state1, const State & state2) +void print_other_metrics_csv(const PCM * m, const State & state1, const State & state2, const AETRow & aet = AETRow{}) { if (m->L3CacheOccupancyMetricAvailable()) cout << ',' << l3cache_occ_format(getL3CacheOccupancy(state2)); @@ -1211,6 +1331,8 @@ void print_other_metrics_csv(const PCM * m, const State & state1, const State & cout << ',' << getLocalMemoryBW(state1, state2); if (m->CoreRemoteMemoryBWMetricAvailable()) cout << ',' << getRemoteMemoryBW(state1, state2); + if (aet.available) + cout << ',' << aet_format(aet.energy) << ',' << aet_format(aet.cdyn); } void print_csv(PCM * m, @@ -1250,6 +1372,12 @@ void print_csv(PCM * m, cout << getBytesReadFromEDC(sstate1, sstate2) / double(1e9) << ',' << getBytesWrittenToEDC(sstate1, sstate2) / double(1e9) << ','; + if (aet_available(m)) + { + const auto aet = get_aet_row_sum(m, [](const uint32) { return true; }, sstate1, sstate2); + cout << aet_format(aet.energy) << ',' << aet_format(aet.cdyn) << ','; + } + cout << float_format(getInstructionsRetired(sstate1, sstate2)) << "," << float_format(getCycles(sstate1, sstate2)) << "," << float_format(getInvariantTSC(cstates1[0], cstates2[0])) << "," @@ -1293,7 +1421,8 @@ void print_csv(PCM * m, for (uint32 i = 0; i < m->getNumSockets(); ++i) { print_basic_metrics_csv(m, sktstate1[i], sktstate2[i], false); - print_other_metrics_csv(m, sktstate1[i], sktstate2[i]); + print_other_metrics_csv(m, sktstate1[i], sktstate2[i], + get_aet_row_sum(m, [&m, &i](const uint32 core) { return m->getSocketId(core) == (int32)i; }, sstate1, sstate2)); if (m->memoryTrafficMetricsAvailable()) cout << ',' << getBytesReadFromMC(sktstate1[i], sktstate2[i]) / double(1e9) << ',' << getBytesWrittenToMC(sktstate1[i], sktstate2[i]) / double(1e9); @@ -1414,7 +1543,9 @@ void print_csv(PCM * m, { const auto & key = entry.first; print_basic_metrics_csv(m, die_cstates1[key], die_cstates2[key], false); - print_other_metrics_csv(m, die_cstates1[key], die_cstates2[key]); + print_other_metrics_csv(m, die_cstates1[key], die_cstates2[key], + get_aet_row_sum(m, [&m, &key](const uint32 core) { return m->getSocketId(core) == key.first && m->getDieId(core) == key.second; }, + sstate1, sstate2)); cout << ',' << temp_format(die_cstates2[key].getThermalHeadroom()) << ','; cout << float_format(getInstructionsRetired(die_cstates1[key], die_cstates2[key])) << "," @@ -1435,7 +1566,7 @@ void print_csv(PCM * m, continue; print_basic_metrics_csv(m, cstates1[i], cstates2[i], false); - print_other_metrics_csv(m, cstates1[i], cstates2[i]); + print_other_metrics_csv(m, cstates1[i], cstates2[i], get_aet_row(m, i, sstate1, sstate2)); cout << ','; for (int s = 0; s <= PCM::MAX_C_STATE; ++s) @@ -1455,6 +1586,55 @@ void print_csv(PCM * m, } } +/*! \brief programs the per-RMID AET (Application Energy Telemetry) counters + + Does nothing unless the AET metrics are requested with the --aet command line + option. Only processors supporting AET (CWF) are affected and only the RMIDs that + RDT associated with the cores via direct MSR programming are collected: in resctrl + mode the RMIDs used by the driver are unknown to PCM. +*/ +void program_aet(PCM * m) +{ + if (aet_metrics == false) + { + return; + } + if (AET::supported() == false) + { + cerr << "ERROR: AET metrics (CENRG, CDYN) are not supported on this processor.\n"; + return; + } + const auto numRMIDs = getAETNumRMIDs(); // 0 if the AET telemetry is not exposed by the OS + if (numRMIDs == 0) + { + cerr << "ERROR: AET metrics (CENRG, CDYN) are not available: the AET telemetry is not exposed by the OS.\n"; + return; + } + const auto usedRMIDs = m->getUsedRMIDs(); + std::vector rmids; + for (const auto & rmid : usedRMIDs) + { + if (rmid < numRMIDs) + { + rmids.push_back(rmid); + } + } + if (rmids.empty()) + { + cerr << "ERROR: AET metrics (CENRG, CDYN) are not available: no RMID in the AET range 0.." << (numRMIDs - 1) + << " is associated with a core. RDT must use direct MSR programming (not the resctrl driver).\n"; + return; + } + if (programAET(rmids, PCM::getQuietMode()) != PCM::Success) + { + cerr << "WARNING: could not program AET counters for the RMIDs used by RDT.\n"; + } + else if (PCM::getQuietMode() == false) + { + cerr << "INFO: programmed AET counters for " << rmids.size() << " of " << usedRMIDs.size() << " RMID(s) used by RDT (AET supports RMIDs 0.." << (numRMIDs - 1) << ").\n"; + } +} + #ifndef UNIT_TEST PCM_MAIN_NOTHROW; @@ -1583,6 +1763,11 @@ int mainThrows(int argc, char * argv[]) show_die_output = true; continue; } + else if (check_argument_equals(*argv, {"--aet", "-aet", "/aet"})) + { + aet_metrics = true; + continue; + } else if (check_argument_equals(*argv, {"--color"})) { setColorEnabled(); @@ -1702,6 +1887,8 @@ int mainThrows(int argc, char * argv[]) exit(EXIT_FAILURE); } + program_aet(m); + print_cpu_details(); std::vector cstates1, cstates2; From 1f831fdcccfa3581f8f07c7d7fb16576ed49e998 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Fri, 18 Sep 2026 11:11:00 +0200 Subject: [PATCH 19/40] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/cpucounters.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cpucounters.h b/src/cpucounters.h index 29574e04..b9280ff5 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -5831,11 +5831,15 @@ inline std::vector getAETCounter(const size_t rmid, const AET:: const AET::Sample sample = AET::Total) { const auto values = getPMTEvent(AETEventEncoding(rmid, counter, false, sample), before, after); - const auto validBits = getPMTEvent(AETEventEncoding(rmid, counter, true), before, after); + const auto validEncoding = AETEventEncoding(rmid, counter, true); + const auto afterValidBits = getPMTEvent(validEncoding, before, after); + const auto beforeValidBits = (sample == AET::Interval) ? getPMTEvent(validEncoding, before, before) : afterValidBits; std::vector result; for (size_t i = 0; i < values.size(); ++i) { - result.push_back(AETCounterValue{ values[i], i < validBits.size() && validBits[i] != 0 }); + const bool valid = i < beforeValidBits.size() && beforeValidBits[i] != 0 && + i < afterValidBits.size() && afterValidBits[i] != 0; + result.push_back(AETCounterValue{ values[i], valid }); } return result; } From 60827fdda941b443bf1f9b980d3645652ceedca0 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 18 Sep 2026 09:14:13 +0000 Subject: [PATCH 20/40] pcm: mark AET aggregate metrics invalid unless every selected core is valid Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --- src/pcm.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/pcm.cpp b/src/pcm.cpp index 165cf7be..07582c07 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -115,6 +115,9 @@ AETRow get_aet_row_sum(const PCM * m, const CoreFilter & filter, const SystemCou { return result; } + bool anyCore = false; + bool allEnergyValid = true; + bool allCdynValid = true; for (uint32 core = 0; core < m->getNumCores(); ++core) { if (m->isCoreOnline(core) == false || filter(core) == false) @@ -122,17 +125,27 @@ AETRow get_aet_row_sum(const PCM * m, const CoreFilter & filter, const SystemCou continue; } const auto row = get_aet_row(m, core, before, after); + anyCore = true; if (row.energy.valid) { result.energy.value += row.energy.value; - result.energy.valid = true; + } + else + { + allEnergyValid = false; } if (row.cdyn.valid) { result.cdyn.value += row.cdyn.value; - result.cdyn.valid = true; + } + else + { + allCdynValid = false; } } + // report the aggregate only if every selected core contributed a valid sample (no partial sums) + result.energy.valid = anyCore && allEnergyValid; + result.cdyn.valid = anyCore && allCdynValid; return result; } From 1dfa97f758d042a33f981744487859b5de9d1d56 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Fri, 18 Sep 2026 13:54:13 +0200 Subject: [PATCH 21/40] pcm: speed up cleanupRDT by stopping the MBW watchdog threads concurrently memory_bw_local/memory_bw_total hold one CounterWidthExtender per online core and each of them runs a watchdog thread that polls the stop request in 50 ms sleep slices. Clearing the vectors destroyed the counters one by one and every destructor set the stop flag and only then joined its thread, so the wake-up latency was paid serially: on a 384-thread system (768 counters) cleanupRDT took about 19 seconds. Add CounterWidthExtender::requestStopUpdateThread() which only requests the watchdog thread to finish (the destructor still joins it) and ask all counters to stop before destroying them. cleanupRDT() sends the requests before the loop resetting the RMID MSRs, so the threads exit while that loop is running. The initRDT() error path does the same. Runtime of "pcm 1 -i=1 -nc -ns" on a 2-socket 384-thread Granite Rapids system drops from 18.8 to 3.7 seconds. Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.cpp | 44 +++++++++++++++++++++++++++++++++++++++----- src/width_extender.h | 8 ++++++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 56fba920..58340c7a 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -587,6 +587,31 @@ unsigned PCM::getMaxRMID() const return maxRMID; } +//! \brief asks the watchdog threads of all CounterWidthExtender instances in a container to finish +//! \details Only call it for containers holding the last reference to the instances. +template +inline void requestStopCounterWidthExtenders(Container & c) +{ + for (auto & counter : c) + { + if (counter.get()) + { + counter->requestStopUpdateThread(); + } + } +} + +//! \brief destroys a container of CounterWidthExtender instances +//! \details Asks all watchdog threads to finish first, so that they wake up and exit +//! concurrently. Destroying the instances one by one would otherwise serialize the +//! wake-up latency of every single watchdog thread. +template +inline void clearCounterWidthExtenders(Container & c) +{ + requestStopCounterWidthExtenders(c); + c.clear(); +} + void PCM::initRDT() { if (RDTInitialized) @@ -725,6 +750,9 @@ void PCM::initRDT() if (!success) { std::cerr << "ERROR: failed to program RMIDs via MSR access. RDT metrics will not be available.\n"; + /* stop the watchdog threads first, they exit while the loop below is undoing the programming */ + requestStopCounterWidthExtenders(memory_bw_local); + requestStopCounterWidthExtenders(memory_bw_total); /* Undo any completed RMID programming (reset to RMID 0 and event 0 as in cleanupRDT) */ for(int32 core = 0; core <= lastProgrammedCore; core ++ ) { @@ -737,8 +765,8 @@ void PCM::initRDT() MSR[core]->write(IA32_QM_EVTSEL, 0ULL); MSR[core]->unlock(); } - memory_bw_local.clear(); - memory_bw_total.clear(); + clearCounterWidthExtenders(memory_bw_local); + clearCounterWidthExtenders(memory_bw_total); coreRMIDs.clear(); return; } @@ -5356,6 +5384,12 @@ void PCM::cleanupRDT(const bool silent) return; } + // stop the watchdog threads of the memory bandwidth counters before touching the RMID MSRs: + // they exit while the loop below is running, therefore the destructors called by + // clearCounterWidthExtenders(..) at the end do not have to wait for them + requestStopCounterWidthExtenders(memory_bw_local); + requestStopCounterWidthExtenders(memory_bw_total); + for(int32 core = 0; core < num_cores; core ++ ) { if(!isCoreOnline(core)) continue; @@ -5380,8 +5414,8 @@ void PCM::cleanupRDT(const bool silent) } - memory_bw_local.clear(); - memory_bw_total.clear(); + clearCounterWidthExtenders(memory_bw_local); + clearCounterWidthExtenders(memory_bw_total); coreRMIDs.clear(); RDTInitialized = false; @@ -11352,7 +11386,7 @@ CounterWidthExtender::~CounterWidthExtender() // the watchdog thread accesses raw_counter, therefore it must be stopped and // joined before the counter is destroyed. Destroying a still joinable // std::thread would also call std::terminate(). - stopUpdateThread.store(true, std::memory_order_relaxed); + requestStopUpdateThread(); if (UpdateThread != nullptr && UpdateThread->joinable()) { try { diff --git a/src/width_extender.h b/src/width_extender.h index 4e03be11..e074dbd6 100644 --- a/src/width_extender.h +++ b/src/width_extender.h @@ -204,6 +204,14 @@ class CounterWidthExtender { return internal_read(); } + //! \brief asks the watchdog thread to finish without waiting for it + //! \details The destructor still joins the thread. Calling this method on many + //! CounterWidthExtender instances before destroying them lets their watchdog threads + //! wake up and exit concurrently instead of paying the wake-up latency for every instance. + void requestStopUpdateThread() + { + stopUpdateThread.store(true, std::memory_order_relaxed); + } //! \brief returns true if the last attempt to read the raw counter failed bool readFailed() const { From e39039664ea5ab138cbda4d0a48c852036effacb Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 18 Sep 2026 12:11:28 +0000 Subject: [PATCH 22/40] pcm: join MBW watchdog threads before RMID rollback/cleanup MSR writes Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --- src/cpucounters.cpp | 56 +++++++++++++++++++++++++++++--------------- src/width_extender.h | 4 ++++ 2 files changed, 41 insertions(+), 19 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 58340c7a..f5d3dc8d 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -601,15 +601,21 @@ inline void requestStopCounterWidthExtenders(Container & c) } } -//! \brief destroys a container of CounterWidthExtender instances -//! \details Asks all watchdog threads to finish first, so that they wake up and exit -//! concurrently. Destroying the instances one by one would otherwise serialize the -//! wake-up latency of every single watchdog thread. +//! \brief waits until the watchdog threads of all CounterWidthExtender instances in a container have exited +//! \details Call requestStopCounterWidthExtenders(..) on all involved containers first, so that the +//! watchdog threads wake up and exit concurrently instead of paying the wake-up latency for every +//! single thread. After this function returns none of the watchdog threads accesses its raw counter +//! (e.g. the RMID MSRs of MBL/MBT counters) anymore. template -inline void clearCounterWidthExtenders(Container & c) +inline void joinCounterWidthExtenders(Container & c) { - requestStopCounterWidthExtenders(c); - c.clear(); + for (auto & counter : c) + { + if (counter.get()) + { + counter->stopAndJoinUpdateThread(); + } + } } void PCM::initRDT() @@ -750,9 +756,13 @@ void PCM::initRDT() if (!success) { std::cerr << "ERROR: failed to program RMIDs via MSR access. RDT metrics will not be available.\n"; - /* stop the watchdog threads first, they exit while the loop below is undoing the programming */ + /* stop the watchdog threads and wait for them to exit before undoing the programming: + a watchdog thread that already passed its stop check could otherwise reprogram + IA32_QM_EVTSEL after the rollback writes below */ requestStopCounterWidthExtenders(memory_bw_local); requestStopCounterWidthExtenders(memory_bw_total); + joinCounterWidthExtenders(memory_bw_local); + joinCounterWidthExtenders(memory_bw_total); /* Undo any completed RMID programming (reset to RMID 0 and event 0 as in cleanupRDT) */ for(int32 core = 0; core <= lastProgrammedCore; core ++ ) { @@ -765,8 +775,8 @@ void PCM::initRDT() MSR[core]->write(IA32_QM_EVTSEL, 0ULL); MSR[core]->unlock(); } - clearCounterWidthExtenders(memory_bw_local); - clearCounterWidthExtenders(memory_bw_total); + memory_bw_local.clear(); + memory_bw_total.clear(); coreRMIDs.clear(); return; } @@ -5384,11 +5394,14 @@ void PCM::cleanupRDT(const bool silent) return; } - // stop the watchdog threads of the memory bandwidth counters before touching the RMID MSRs: - // they exit while the loop below is running, therefore the destructors called by - // clearCounterWidthExtenders(..) at the end do not have to wait for them + // stop the watchdog threads of the memory bandwidth counters and wait for them to exit + // before touching the RMID MSRs: a watchdog thread that already passed its stop check + // could otherwise reprogram IA32_QM_EVTSEL after the cleanup writes below. + // Requesting the stop of all threads first lets them wake up and exit concurrently. requestStopCounterWidthExtenders(memory_bw_local); requestStopCounterWidthExtenders(memory_bw_total); + joinCounterWidthExtenders(memory_bw_local); + joinCounterWidthExtenders(memory_bw_total); for(int32 core = 0; core < num_cores; core ++ ) { @@ -5414,8 +5427,8 @@ void PCM::cleanupRDT(const bool silent) } - clearCounterWidthExtenders(memory_bw_local); - clearCounterWidthExtenders(memory_bw_total); + memory_bw_local.clear(); + memory_bw_total.clear(); coreRMIDs.clear(); RDTInitialized = false; @@ -11381,11 +11394,8 @@ CounterWidthExtender::CounterWidthExtender(AbstractRawCounter * raw_counter_, ui throw; // re-throw } } -CounterWidthExtender::~CounterWidthExtender() +void CounterWidthExtender::stopAndJoinUpdateThread() { - // the watchdog thread accesses raw_counter, therefore it must be stopped and - // joined before the counter is destroyed. Destroying a still joinable - // std::thread would also call std::terminate(). requestStopUpdateThread(); if (UpdateThread != nullptr && UpdateThread->joinable()) { @@ -11397,6 +11407,14 @@ CounterWidthExtender::~CounterWidthExtender() std::cerr << "PCM Error: caught exception " << e.what() << " while joining the CounterWidthExtender watchdog thread\n"; } } +} + +CounterWidthExtender::~CounterWidthExtender() +{ + // the watchdog thread accesses raw_counter, therefore it must be stopped and + // joined before the counter is destroyed. Destroying a still joinable + // std::thread would also call std::terminate(). + stopAndJoinUpdateThread(); deleteAndNullify(UpdateThread); deleteAndNullify(raw_counter); } diff --git a/src/width_extender.h b/src/width_extender.h index e074dbd6..060564d3 100644 --- a/src/width_extender.h +++ b/src/width_extender.h @@ -212,6 +212,10 @@ class CounterWidthExtender { stopUpdateThread.store(true, std::memory_order_relaxed); } + //! \brief asks the watchdog thread to finish and waits until it has exited + //! \details After this method returns the watchdog thread does not access the + //! raw counter (e.g. the RMID MSRs of MBL/MBT counters) anymore. + void stopAndJoinUpdateThread(); //! \brief returns true if the last attempt to read the raw counter failed bool readFailed() const { From 0fc0c32df13b45d46e947077e66a6eb3397ca690 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Mon, 21 Sep 2026 10:00:55 +0200 Subject: [PATCH 23/40] pcm-sensor-server: do not mistake a 0xff first byte for EOF in SSL detection checkForIncomingSSLConnection() peeked the first byte of a new connection into a (signed) char and compared it with EOF. A first byte of 0xff is sign extended to -1 and was therefore rejected as "Peeking for SSL resulted in EOF", even though recv() had just returned one byte of data and 0xff is a valid start of an SSLv2 record header (bit 7 set) that the very next check is looking for. Peek into an unsigned char instead, which also makes the bit test below independent of integer promotion of a signed value, and drop the EOF comparison: after a successful one byte peek there is no EOF to detect. The debug output now prints the byte as hex. It used to write the raw byte into the log, which was invisible for exactly the bytes of interest (0x16 for a TLS ClientHello), making the logs of a failed handshake ambiguous. Co-Authored-By: Claude Opus 5 (1M context) --- src/pcm-sensor-server.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/pcm-sensor-server.cpp b/src/pcm-sensor-server.cpp index 8c49e7c5..3893a9b4 100644 --- a/src/pcm-sensor-server.cpp +++ b/src/pcm-sensor-server.cpp @@ -3779,11 +3779,14 @@ class HTTPServer : public Server { } bool checkForIncomingSSLConnection( socket_t fd ) { - char ch = ' '; + // Unsigned on purpose: the byte is only inspected bit wise below and a + // signed char would sign extend a first byte of 0xff into EOF (-1), even + // though 0xff is a perfectly valid start of an SSLv2 record header. + unsigned char ch = ' '; #ifdef _WIN32 - int bytes = ::recv( fd, &ch, 1, MSG_PEEK ); + int bytes = ::recv( fd, reinterpret_cast( &ch ), 1, MSG_PEEK ); #else - ssize_t bytes = ::recv( fd, &ch, 1, MSG_PEEK ); + ssize_t bytes = ::recv( fd, reinterpret_cast( &ch ), 1, MSG_PEEK ); #endif if ( SOCKET_ERROR == bytes ) { #ifdef _WIN32 @@ -3796,9 +3799,9 @@ class HTTPServer : public Server { DBG( 0, "Connection was properly closed by the client, no bytes to read" ); throw std::runtime_error( "No error but the connecton is closed so we should just wait for a new connection again" ); } - DBG( 1, "SSL: Peeked Char: ", (EOF == ch) ? std::string("EOF") : std::string(1, ch) ); - if ( ch == EOF ) - throw std::runtime_error( "Peeking for SSL resulted in EOF" ); + // Exactly one byte was peeked, so it is data, never EOF. Print it as hex + // because the bytes we are looking for here are not printable anyway. + DBG( 1, "SSL: Peeked Char: 0x", std::hex, static_cast( ch ), std::dec ); // for SSLv2 bit 7 is set and for SSLv3 and up the first ClientHello Message is 0x16 if ( ( ch & 0x80 ) || ( ch == 0x16 ) ) { DBG( 3, "SSL detected" ); From bc163b601992bfb5aa84f55996596078f4afda5a Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Mon, 21 Sep 2026 10:41:42 +0200 Subject: [PATCH 24/40] pcm-sensor-server: retry socket operations interrupted by a signal None of the signal handlers the server installs use SA_RESTART, so any signal delivered to a thread that is blocked in a socket operation makes that operation fail with EINTR. The server treated such a failure as a broken connection: the MSG_PEEK that detects whether a client speaks SSL threw and closed the connection, reads and writes returned eof (turning a request into a 400 Bad Request), and SSL_accept() gave up on the handshake. A client doing nothing wrong was disconnected. This is easy to observe when fuzzing: libFuzzer arms a repeating SIGALRM timer, and once every few hundred connections that signal lands inside the TLS handshake. The SSL fuzz target then fails with "Failed to establish SSL connection" and aborts the whole run. Retry the operation instead, which is what SA_RESTART would do: - recv(MSG_PEEK) in checkForIncomingSSLConnection() - read()/recv() in underflow() and send() in writeToSocket() - SSL_read()/SSL_write() on SSL_ERROR_SYSCALL with EINTR - SSL_accept() on SSL_ERROR_SYSCALL with EINTR (SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE, which is how OpenSSL usually reports an interrupted handshake on a blocking socket, were already retried) Retrying a receive must stay bounded. A receive on a socket with SO_RCVTIMEO set is never restarted after a signal, not even for an SA_RESTART handler (signal(7)), and each new receive starts the timeout over. Unbounded retries would therefore let a client that connects and sends nothing keep a worker thread for as long as signals keep arriving, defeating both the receive timeout and the request deadline that readLineBounded() enforces. underflow() now derives a deadline from the timeout currently set on the socket - read with getsockopt because ScopedRecvTimeout tightens SO_RCVTIMEO directly, on purpose without touching timeout_ - and gives up once it passes, exactly as a timeout would. A timeout of zero keeps the "block indefinitely" semantics. The error code is snapshotted immediately after each OpenSSL call because SSL_get_error(), the ERR_* helpers and DBG() may all overwrite it before the checks run, and it is cleared before the call so that no stale value from an unrelated operation can be mistaken for EINTR (which would retry a call that can never succeed). Both the new checks and the pre-existing EAGAIN ones use that snapshot now. It is read and cleared through helpers because Windows keeps the code in WSAGetLastError() rather than in errno, where the previous direct errno comparisons could never match. writeToSocket() returns early when there is nothing to send. sync() is called that way on every flush that has nothing left and on close(), and OpenSSL documents SSL_write() with num == 0 as undefined: it returns 0, which SSL_get_error() reports as SSL_ERROR_SYSCALL with no error queued and no error code, i.e. indistinguishable from a real transport failure. Co-Authored-By: Claude Opus 5 (1M context) --- src/pcm-sensor-server.cpp | 160 ++++++++++++++++++++++++++++--- tests/pcm-sensor-server-fuzz.cpp | 55 ++++++++++- 2 files changed, 198 insertions(+), 17 deletions(-) diff --git a/src/pcm-sensor-server.cpp b/src/pcm-sensor-server.cpp index 3893a9b4..aeb1bc8b 100644 --- a/src/pcm-sensor-server.cpp +++ b/src/pcm-sensor-server.cpp @@ -32,6 +32,7 @@ typedef SOCKET socket_t; // PCM errno values mapped to Windows socket errors #define PCM_EAGAIN WSAEWOULDBLOCK #define PCM_EWOULDBLOCK WSAEWOULDBLOCK +#define PCM_EINTR WSAEINTR inline int close(SOCKET s) { return closesocket(s); } #else #include @@ -46,9 +47,40 @@ typedef int socket_t; // PCM errno values mapped to POSIX errors #define PCM_EAGAIN EAGAIN #define PCM_EWOULDBLOCK EWOULDBLOCK +#define PCM_EINTR EINTR #define SOCKET_ERROR (-1) #endif +#include + +// Error code of the last socket operation. Windows keeps it in WSAGetLastError(), +// POSIX in errno. Needed to recognize an operation that was merely interrupted by +// a signal (PCM_EINTR) and therefore has to be retried: none of the signal +// handlers we install use SA_RESTART and, when running under a fuzzer or a +// profiler, the process receives periodic signals (libFuzzer arms a repeating +// SIGALRM timer). Without the retries a signal arriving at the wrong moment +// tears down a perfectly healthy client connection. +inline int lastSocketError() { +#ifdef _WIN32 + return WSAGetLastError(); +#else + return errno; +#endif +} + +// Clears the error code before an OpenSSL call so that the code read afterwards +// cannot be a stale value from an unrelated earlier operation. OpenSSL only +// promises a meaningful error code for SSL_ERROR_SYSCALL, it does not clear it +// itself, and acting on a stale PCM_EINTR would retry a call that can never +// succeed. +inline void clearLastSocketError() { +#ifdef _WIN32 + WSASetLastError( 0 ); +#else + errno = 0; +#endif +} + #include #include #include @@ -1093,6 +1125,28 @@ class basic_socketbuf : public std::basic_streambuf { } } + // The receive timeout currently in effect for the socket. Queried from the + // socket instead of returning timeout_ because ScopedRecvTimeout tightens + // SO_RCVTIMEO directly, on purpose without touching timeout_, to enforce the + // per-request deadline. A zero duration means "block indefinitely". + std::chrono::microseconds currentReceiveTimeout() const { + if ( INVALID_SOCKET == socketFD_ ) + return std::chrono::microseconds::zero(); +#ifdef _WIN32 + DWORD current = 0; + int len = sizeof( current ); + if ( getsockopt( socketFD_, SOL_SOCKET, SO_RCVTIMEO, (char*)¤t, &len ) != 0 ) + current = timeout_; + return std::chrono::milliseconds( current ); +#else + struct timeval current; + socklen_t len = sizeof( current ); + if ( getsockopt( socketFD_, SOL_SOCKET, SO_RCVTIMEO, (char*)¤t, &len ) != 0 ) + current = timeout_; + return std::chrono::seconds( current.tv_sec ) + std::chrono::microseconds( current.tv_usec ); +#endif + } + #ifdef _WIN32 void setTimeout( DWORD t ) { timeout_ = t; @@ -1150,14 +1204,26 @@ class basic_socketbuf : public std::basic_streambuf { bytesToSend = (char*)Base::pptr() - (char*)Base::pbase(); DBG( 3, dbg, "wts: Bytes to send: ", bytesToSend ); + // sync() is called with an empty put area on every flush() that has + // nothing left to write and on close(). There is nothing to send then, + // and OpenSSL explicitly documents SSL_write() with num == 0 as + // undefined behavior (it returns 0, which SSL_get_error() reports as + // SSL_ERROR_SYSCALL without any error queued, i.e. indistinguishable + // from a real transport failure). Handle it here instead. + if ( 0 == bytesToSend ) + return 0; + #if defined (USE_SSL) if ( nullptr == ssl_ ) { #endif + // Retry when only interrupted by a signal, see lastSocketError() + do { #ifdef _WIN32 - bytesSent= ::send( socketFD_, (const char*)outputBuffer_, static_cast(bytesToSend), MSG_NOSIGNAL ); + bytesSent= ::send( socketFD_, (const char*)outputBuffer_, static_cast(bytesToSend), MSG_NOSIGNAL ); #else - bytesSent= ::send( socketFD_, (void*)outputBuffer_, bytesToSend, MSG_NOSIGNAL ); + bytesSent= ::send( socketFD_, (void*)outputBuffer_, bytesToSend, MSG_NOSIGNAL ); #endif + } while ( SOCKET_ERROR == bytesSent && PCM_EINTR == lastSocketError() ); if ( SOCKET_ERROR == bytesSent ) { #ifdef _WIN32 DBG( 3, "bytesSent == SOCKET_ERROR: WSAGetLastError: ", WSAGetLastError(), ", returning eof..." ); @@ -1172,7 +1238,11 @@ class basic_socketbuf : public std::basic_streambuf { while( 1 ) { // openSSL has no support for setting the MSG_NOSIGNAL during send // but we ignore sigpipe so we should be fine + clearLastSocketError(); bytesSent = SSL_write( ssl_, (void*)outputBuffer_, bytesToSend ); + // Snapshot the error code right away: SSL_get_error(), the ERR_* + // calls and DBG() below are all allowed to overwrite it. + const int socketErrno = lastSocketError(); DBG( 3, dbg, "wts: SSL_write returned for bytesSent: ", bytesSent ); if ( 0 >= bytesSent ) { int sslError = SSL_get_error( ssl_, bytesSent ); @@ -1190,9 +1260,15 @@ class basic_socketbuf : public std::basic_streambuf { continue; // Should continue in the while loop and attempt to write again // break; case SSL_ERROR_SYSCALL: - DBG( 3, dbg, "wts: errno is: ", errno, " strerror(errno): ", strerror(errno) ); - if ( errno == 0 ) - return 0; + DBG( 3, dbg, "wts: socket error is: ", socketErrno, " strerror: ", strerror(socketErrno) ); + if ( socketErrno == PCM_EINTR ) { + DBG( 3, dbg, "wts: Interrupted by a signal. Trying SSL_write again..." ); + continue; // retry the very same SSL_write + } + // We never call SSL_write() with a length of 0, so + // there is no error code only when the transport + // reported an EOF, which OpenSSL documents as + // non-recoverable for a write. /* fall-through */ case SSL_ERROR_SSL: default: @@ -1245,15 +1321,33 @@ class basic_socketbuf : public std::basic_streambuf { std::fill(inputBuffer_, inputBuffer_ + SIZE, 0); int bytesReceived; + // A receive on a socket with SO_RCVTIMEO set is never restarted after a + // signal, not even for an SA_RESTART handler (see signal(7)), and every + // new receive starts the timeout over. Retrying an interrupted receive + // must therefore not be unbounded: with signals arriving more often than + // the timeout, a client that sends nothing would keep this worker thread + // for as long as the signals keep coming, which is exactly the resource + // exhaustion that the receive timeout and the request deadline in + // readLineBounded() exist to prevent. + const auto recvTimeout = currentReceiveTimeout(); + const auto recvDeadline = std::chrono::steady_clock::now() + recvTimeout; + const bool recvBounded = recvTimeout > std::chrono::microseconds::zero(); + auto mayRetryReceive = [&]() { + return !recvBounded || std::chrono::steady_clock::now() < recvDeadline; + }; + #if defined (USE_SSL) if ( nullptr == ssl_ ) { #endif DBG( 3, dbg, "Socketbuf: Read from socket:" ); + // Retry when only interrupted by a signal, see lastSocketError() + do { #ifdef _WIN32 - bytesReceived = ::recv( socketFD_, static_cast(inputBuffer_), SIZE * sizeof( char_type ), 0 ); + bytesReceived = ::recv( socketFD_, static_cast(inputBuffer_), SIZE * sizeof( char_type ), 0 ); #else - bytesReceived = ::read( socketFD_, static_cast(inputBuffer_), SIZE * sizeof( char_type ) ); + bytesReceived = ::read( socketFD_, static_cast(inputBuffer_), SIZE * sizeof( char_type ) ); #endif + } while ( SOCKET_ERROR == bytesReceived && PCM_EINTR == lastSocketError() && mayRetryReceive() ); if ( 0 == bytesReceived ) { // Client closed the socket normally, we will do the same close(); @@ -1280,7 +1374,11 @@ class basic_socketbuf : public std::basic_streambuf { else { bool loopAgain = true; while (loopAgain) { + clearLastSocketError(); bytesReceived = SSL_read( ssl_, static_cast(inputBuffer_), SIZE * sizeof( char_type ) ); + // Snapshot the error code right away: SSL_get_error(), the ERR_* + // calls and DBG() below are all allowed to overwrite it. + const int socketErrno = lastSocketError(); DBG( 3, dbg, "SSL_read: bytesReceived: ", bytesReceived ); if ( 0 >= bytesReceived ) { int sslError = SSL_get_error( ssl_, bytesReceived ); @@ -1299,8 +1397,8 @@ class basic_socketbuf : public std::basic_streambuf { //ERR_print_errors_fp(stderr); switch ( sslError ) { case SSL_ERROR_WANT_READ: - DBG( 3, "SSL_ERROR_WANT_READ: Errno = ", errno, ", strerror(errno): ", strerror(errno) ); - if ( errno == PCM_EAGAIN || errno == PCM_EWOULDBLOCK ) { + DBG( 3, "SSL_ERROR_WANT_READ: socket error = ", socketErrno, ", strerror: ", strerror(socketErrno) ); + if ( socketErrno == PCM_EAGAIN || socketErrno == PCM_EWOULDBLOCK ) { DBG( 3, dbg, "Most likely the set timeout, so aborting..." ); close(); Base::setg( nullptr, nullptr, nullptr ); @@ -1309,18 +1407,24 @@ class basic_socketbuf : public std::basic_streambuf { } /* fall-through */ case SSL_ERROR_WANT_WRITE: - // retry + // retry, an interrupted handshake or read is + // reported as want read / want write here loopAgain = true; // Should continue in the while loop and attempt to read again break; case SSL_ERROR_SYSCALL: - DBG( 3, "SSL_ERROR_SYSCALL: Errno = ", errno ); - if ( errno == PCM_EAGAIN || errno == PCM_EWOULDBLOCK ) { + DBG( 3, "SSL_ERROR_SYSCALL: socket error = ", socketErrno ); + if ( socketErrno == PCM_EAGAIN || socketErrno == PCM_EWOULDBLOCK ) { DBG( 3, dbg, "Most likely the set timeout, so aborting..." ); close(); Base::setg( nullptr, nullptr, nullptr ); DBG( 3, dbg, "return eof" ); return traits_type::eof(); } + if ( socketErrno == PCM_EINTR ) { + DBG( 3, dbg, "Interrupted by a signal. Trying SSL_read again..." ); + loopAgain = true; // retry the very same SSL_read + break; + } /* fall-through */ case SSL_ERROR_SSL: default: @@ -1329,6 +1433,15 @@ class basic_socketbuf : public std::basic_streambuf { DBG( 3, dbg, "return eof" ); return traits_type::eof(); } + // Every retry above starts the receive timeout over, so + // honour the deadline computed for this call instead of + // looping for as long as signals keep arriving. + if ( loopAgain && !mayRetryReceive() ) { + DBG( 3, dbg, "Receive deadline expired while retrying, aborting" ); + close(); + Base::setg( nullptr, nullptr, nullptr ); + return traits_type::eof(); + } } } else { // Valid read @@ -3784,10 +3897,16 @@ class HTTPServer : public Server { // though 0xff is a perfectly valid start of an SSLv2 record header. unsigned char ch = ' '; #ifdef _WIN32 - int bytes = ::recv( fd, reinterpret_cast( &ch ), 1, MSG_PEEK ); + int bytes; #else - ssize_t bytes = ::recv( fd, reinterpret_cast( &ch ), 1, MSG_PEEK ); + ssize_t bytes; #endif + // Waiting for the first byte can be interrupted by a signal. That is not a + // connection error, so peek again instead of dropping the client. See the + // comment on lastSocketError(). + do { + bytes = ::recv( fd, reinterpret_cast( &ch ), 1, MSG_PEEK ); + } while ( SOCKET_ERROR == bytes && PCM_EINTR == lastSocketError() ); if ( SOCKET_ERROR == bytes ) { #ifdef _WIN32 DBG( 1, "recv call to peek for the first incoming character failed, WSAGetLastError = ", WSAGetLastError() ); @@ -4080,7 +4199,11 @@ void HTTPSServer::run() { while (1) { bool leaveLoop = true; // Check if the SSL handshake worked + clearLastSocketError(); int accept = SSL_accept( ssl ); + // Snapshot the error code right away: SSL_get_error(), the ERR_* + // calls and DBG() below are all allowed to overwrite it. + const int socketErrno = lastSocketError(); DBG( 3, "SSL_accept: ", accept ); if ( 0 >= accept ) { int errorCode = SSL_get_error( ssl, accept ); @@ -4098,8 +4221,15 @@ void HTTPSServer::run() { // All good, just try again leaveLoop = false; break; - case SSL_ERROR_SSL: case SSL_ERROR_SYSCALL: + if ( socketErrno == PCM_EINTR ) { + // Only interrupted by a signal, the handshake can continue + DBG( 3, "SSL_accept was interrupted by a signal, trying again" ); + leaveLoop = false; + break; + } + /* fall-through */ + case SSL_ERROR_SSL: err = ERR_get_error(); DBG( 3, "ERR_get_error(): ", err ); ERR_error_string( err, buf ); diff --git a/tests/pcm-sensor-server-fuzz.cpp b/tests/pcm-sensor-server-fuzz.cpp index ed635ea1..e700e817 100644 --- a/tests/pcm-sensor-server-fuzz.cpp +++ b/tests/pcm-sensor-server-fuzz.cpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include #define UNIT_TEST 1 @@ -148,7 +150,33 @@ std::string make_request(const std::string& request) { std::memcpy(&server_addr.sin_addr, host->h_addr, host->h_length); // Connect to server - if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { + int connect_ret = connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)); + if (connect_ret < 0 && errno == EINTR) { + // A signal was delivered while connect() was waiting (libFuzzer arms a + // repeating SIGALRM timer and installs its handlers without SA_RESTART). + // The connect continues asynchronously, so wait for it to finish instead + // of reporting a failure. Calling connect() again is not allowed here. + DBG( 1, "Client: connect was interrupted by a signal, waiting for it to complete" ); + struct pollfd pfd; + pfd.fd = sock; + pfd.events = POLLOUT; + pfd.revents = 0; + int poll_ret; + do { + poll_ret = poll(&pfd, 1, 60000); + } while (poll_ret < 0 && errno == EINTR); + int socketError = ETIMEDOUT; + if (poll_ret > 0) { + socklen_t len = sizeof(socketError); + if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &socketError, &len) < 0) + socketError = errno; + } + if (socketError == 0) + connect_ret = 0; + else + errno = socketError; + } + if (connect_ret < 0) { DBG( 0, "Failed to connect to server. Error: ", strerror(errno) ); close(sock); #ifdef FUZZ_USE_SSL @@ -161,7 +189,30 @@ std::string make_request(const std::string& request) { // Create SSL structure SSL* ssl = SSL_new(ctx); SSL_set_fd(ssl, sock); - int con_ret = SSL_connect(ssl); + // The handshake runs on a blocking socket, but a signal can still interrupt it: + // libFuzzer arms a repeating SIGALRM timer and installs its signal handlers + // without SA_RESTART. OpenSSL then reports the interrupted read/write as + // retryable (SSL_ERROR_WANT_READ/WANT_WRITE, or SSL_ERROR_SYSCALL with EINTR) + // and SSL_connect returns -1 without the connection being broken at all. + // Retry in that case, otherwise a healthy connection is reported as a + // failure of the server, aborting the whole fuzzing run. + int con_ret = 0; + while ( true ) { + ERR_clear_error(); + errno = 0; + con_ret = SSL_connect(ssl); + if ( con_ret > 0 ) + break; + const int sslError = SSL_get_error(ssl, con_ret); + if ( sslError == SSL_ERROR_WANT_READ || sslError == SSL_ERROR_WANT_WRITE || + ( sslError == SSL_ERROR_SYSCALL && errno == EINTR ) ) { + DBG( 1, "Client: SSL_connect was interrupted (SSL error ", sslError, "), trying again" ); + continue; + } + DBG( 0, "Client: SSL_connect failed, SSL error: ", sslError, ", errno: ", errno, + " (", strerror(errno), "), OpenSSL error: ", ERR_error_string( ERR_get_error(), nullptr ) ); + break; + } DBG( 1, "Client: SSL_connect returned ", con_ret ); if ( con_ret <= 0) { SSL_free(ssl); From 3cb31c1edea30bda5ceb3f64a9a0ea7af19dbfc8 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Mon, 21 Sep 2026 10:41:55 +0200 Subject: [PATCH 25/40] tests: do not fail the sensor server fuzz run on an interrupted handshake libFuzzer arms a repeating SIGALRM timer and installs its signal handlers without SA_RESTART, so a signal can interrupt the client side of the TLS handshake even though the socket is blocking. OpenSSL reports the interrupted read as retryable, SSL_connect() returns -1 and the harness turned that into a fatal "Failed to establish SSL connection", calling exit(1). libFuzzer reported it as "fuzz target exited" and wrote a crash artifact for an input that the server had not even received yet, because the handshake happens before the fuzz data is sent. Retry SSL_connect() while the error is SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE or SSL_ERROR_SYSCALL with EINTR. A handshake that fails for any other reason stays fatal, but now logs the SSL error code, errno and the OpenSSL error string so the next real failure can be diagnosed from the CI log alone. connect() gets the same treatment in both places it is called: - make_request() waits for an interrupted connect() to complete with poll() and checks SO_ERROR, since calling connect() again on the same socket would fail with EALREADY - waitForPort() creates a fresh socket for every attempt instead of reusing one whose connect() was interrupted, where every later attempt would have failed with EALREADY / EISCONN until the 60 second timeout expired and init() called exit(1) Co-Authored-By: Claude Opus 5 (1M context) --- tests/pcm-sensor-server-fuzz.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/tests/pcm-sensor-server-fuzz.cpp b/tests/pcm-sensor-server-fuzz.cpp index e700e817..cc8416dd 100644 --- a/tests/pcm-sensor-server-fuzz.cpp +++ b/tests/pcm-sensor-server-fuzz.cpp @@ -19,18 +19,10 @@ int port = 0; bool waitForPort(int port, int timeoutSeconds) { - int sockfd; struct sockaddr_in address; bool isBound = false; time_t startTime = time(nullptr); - // Create a socket - sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd < 0) { - DBG( 0, "Client: Error creating socket" ); - return false; - } - // Set up the address structure memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; @@ -39,18 +31,28 @@ bool waitForPort(int port, int timeoutSeconds) { // Loop until the port is bound or the timeout is reached while (!isBound && (time(nullptr) - startTime) < timeoutSeconds) { + // A fresh socket for every attempt: a socket whose connect() failed must + // not be reused. In particular an interrupted connect() keeps completing + // in the background (libFuzzer's SIGALRM timer makes that possible even + // on loopback) and every further connect() on the same socket would then + // fail with EALREADY / EISCONN, so the port would never be seen as bound. + int sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd < 0) { + DBG( 0, "Client: Error creating socket" ); + return false; + } // Attempt to connect to the port if (connect(sockfd, (struct sockaddr *)&address, sizeof(address)) < 0) { // Connection failed, wait a bit before retrying + close(sockfd); sleep(1); } else { // Connection succeeded, the port is bound isBound = true; + close(sockfd); } } - // Clean up the socket - close(sockfd); return isBound; } From f05d1e367d933357369c350abb2c3ca06e2cfc26 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Mon, 21 Sep 2026 11:24:46 +0200 Subject: [PATCH 26/40] tests: bound the wait for an interrupted connect by an absolute deadline poll() is interrupted by a signal just like connect() was, and its timeout is relative, so retrying it with the full 60 seconds started a fresh minute of waiting on every SIGALRM. With libFuzzer's repeating timer the loop could therefore never reach its timeout and a connection that never completes would hang the fuzz target instead of failing it. Compute the deadline once and pass the remaining time to each poll() call. Reaching the deadline yields a poll_ret of 0, which the existing code already treats as the timeout it is. Co-Authored-By: Claude Opus 5 (1M context) --- tests/pcm-sensor-server-fuzz.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/pcm-sensor-server-fuzz.cpp b/tests/pcm-sensor-server-fuzz.cpp index cc8416dd..2c81e668 100644 --- a/tests/pcm-sensor-server-fuzz.cpp +++ b/tests/pcm-sensor-server-fuzz.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #define UNIT_TEST 1 @@ -163,9 +164,21 @@ std::string make_request(const std::string& request) { pfd.fd = sock; pfd.events = POLLOUT; pfd.revents = 0; + // poll() is interrupted by a signal as well, and its timeout is relative, + // so retrying with the full timeout would start a new minute of waiting on + // every SIGALRM and could never expire. Wait until an absolute deadline + // instead: a poll_ret of 0 then means the deadline passed and is handled as + // the timeout it is. + const auto pollDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); int poll_ret; do { - poll_ret = poll(&pfd, 1, 60000); + const auto remaining = std::chrono::duration_cast( + pollDeadline - std::chrono::steady_clock::now() ).count(); + if (remaining <= 0) { + poll_ret = 0; + break; + } + poll_ret = poll(&pfd, 1, static_cast(remaining)); } while (poll_ret < 0 && errno == EINTR); int socketError = ETIMEDOUT; if (poll_ret > 0) { From bdb0badbf23445904b921315c49e973b64dd3340 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:32:27 +0200 Subject: [PATCH 27/40] Fix unused variable warnings in event-resolver.cpp using PCM_UNUSED (#988) * Fix unused variable warnings in PerfmonEventResolver::getEventNames --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --- src/event-resolver.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/event-resolver.cpp b/src/event-resolver.cpp index 36094123..8f3f88a8 100644 --- a/src/event-resolver.cpp +++ b/src/event-resolver.cpp @@ -404,12 +404,17 @@ std::vector PerfmonEventResolver::getEventNames() const { std::vector names; names.reserve(m_eventMapJSON.size()); - for (const auto& [event, _] : m_eventMapJSON) names.push_back(event); + for (const auto& [event, _] : m_eventMapJSON) + { + PCM_UNUSED(_); + names.push_back(event); + } for (const auto& tsvMap : m_eventMapsTSV) { for (const auto& [event, _] : tsvMap) { + PCM_UNUSED(_); if (event != "COL_NAMES") names.push_back(event); } } From 871ae4e045eb0752aa22fb222d8ad503f3433c5a Mon Sep 17 00:00:00 2001 From: "Dementiev, Roman" Date: Thu, 24 Sep 2026 15:21:41 +0200 Subject: [PATCH 28/40] fix csv fields when qpi util metrics are not available Change-Id: Ibc1d054679398369a11260472095f5a97ea6838c --- src/pcm.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/pcm.cpp b/src/pcm.cpp index 07582c07..21f765c0 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -971,8 +971,11 @@ void print_csv_header(PCM * m, { header = "SKT" + std::to_string(s) + "trafficOut"; print_csv_header_helper(header,qpiLinks); - header = "SKT" + std::to_string(s) + "trafficOut (percent)"; - print_csv_header_helper(header,qpiLinks); + if (m->qpiUtilizationMetricsAvailable()) + { + header = "SKT" + std::to_string(s) + "trafficOut (percent)"; + print_csv_header_helper(header,qpiLinks); + } } } From 880e38493343f67f0e2deef3a54b4aee55b1b5bb Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 24 Sep 2026 13:37:39 +0000 Subject: [PATCH 29/40] guard outgoing QPI utilization CSV output with qpiUtilizationMetricsAvailable Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com> --- src/pcm.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/pcm.cpp b/src/pcm.cpp index 21f765c0..5de5c8bb 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -1187,6 +1187,8 @@ void print_csv_header(PCM * m, { for (uint32 i = 0; i < qpiLinks; ++i) cout << m->xPI() << i << ","; + + if (m->qpiUtilizationMetricsAvailable()) for (uint32 i = 0; i < qpiLinks; ++i) cout << m->xPI() << i << ","; } @@ -1491,8 +1493,11 @@ void print_csv(PCM * m, for (uint32 l = 0; l < qpiLinks; ++l) cout << float_format(getOutgoingQPILinkBytes(i, l, sstate1, sstate2)) << ","; - for (uint32 l = 0; l < qpiLinks; ++l) - cout << setw(3) << std::dec << int(100. * getOutgoingQPILinkUtilization(i, l, sstate1, sstate2)) << "%,"; + if (m->qpiUtilizationMetricsAvailable()) + { + for (uint32 l = 0; l < qpiLinks; ++l) + cout << setw(3) << std::dec << int(100. * getOutgoingQPILinkUtilization(i, l, sstate1, sstate2)) << "%,"; + } } } From fd6599a6aeb69bea30404299360ffaf485fe8356 Mon Sep 17 00:00:00 2001 From: "Dementiev, Roman" Date: Mon, 27 Jul 2026 15:33:47 +0200 Subject: [PATCH 30/40] use (bar + 8ULL * vsec.fields.Address) instead of bar in discovery Change-Id: I2b26cc3a49cc177118a2f5114ebbd3fe0051380e --- src/uncore_pmu_discovery.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/uncore_pmu_discovery.cpp b/src/uncore_pmu_discovery.cpp index 9cbc6f94..44be2a09 100644 --- a/src/uncore_pmu_discovery.cpp +++ b/src/uncore_pmu_discovery.cpp @@ -21,7 +21,7 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) auto processTables = [this, &debug, &m](const uint64 bar, const VSEC & vsec, const int32 NUMANode) { try { - DBG(1, "Uncore discovery detection. Reading from bar 0x", std::hex, bar, std::dec, + DBG(1, "Uncore discovery detection. Reading from bar 0x", std::hex, bar, " Address 0x", vsec.fields.Address, std::dec, " NUMANode: ", NUMANode); constexpr size_t UncoreDiscoverySize = 3UL; union UncoreGlobalDiscovery { @@ -29,7 +29,8 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) uint64 table[UncoreDiscoverySize]; }; UncoreGlobalDiscovery global; - mmio_memcpy(global.table, bar, UncoreDiscoverySize * sizeof(uint64), true); + const auto fullAddress = bar + 8ULL * vsec.fields.Address; + mmio_memcpy(global.table, fullAddress, UncoreDiscoverySize * sizeof(uint64), true); size_t socket = 0; // default socket if NUMA node -> socket mapping fails if (NUMANode >= 0) { @@ -45,7 +46,7 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) globalPMUs[socket].push_back(global.pmu); if (debug) { - std::cerr << "Read global.pmu from 0x" << std::hex << bar << std::dec << "\n"; + std::cerr << "Read global.pmu from 0x" << std::hex << fullAddress << std::dec << "\n"; global.pmu.print(); std::cout.flush(); } @@ -58,10 +59,10 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) BoxPMUMap boxPMUMap; for (size_t u = 0; u < global.pmu.maxUnits; ++u) { - mmio_memcpy(unit.table, bar + (u + 1) * step, UncoreDiscoverySize * sizeof(uint64), true); + mmio_memcpy(unit.table, fullAddress + (u + 1) * step, UncoreDiscoverySize * sizeof(uint64), true); if (debug) { - std::cerr << "Read unit.pmu " << u << " from 0x" << std::hex << (bar + (u + 1) * step) << std::dec << "\n"; + std::cerr << "Read unit.pmu " << u << " from 0x" << std::hex << (fullAddress + (u + 1) * step) << std::dec << "\n"; unit.pmu.print(); std::cout.flush(); } From 551bd8e5a4baad825b959b2eb817d8f3a30d2e1f Mon Sep 17 00:00:00 2001 From: "Dementiev, Roman" Date: Fri, 25 Sep 2026 14:09:12 +0200 Subject: [PATCH 31/40] Revert "use (bar + 8ULL * vsec.fields.Address) instead of bar in discovery" This reverts commit fd6599a6aeb69bea30404299360ffaf485fe8356. --- src/uncore_pmu_discovery.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/uncore_pmu_discovery.cpp b/src/uncore_pmu_discovery.cpp index 44be2a09..9cbc6f94 100644 --- a/src/uncore_pmu_discovery.cpp +++ b/src/uncore_pmu_discovery.cpp @@ -21,7 +21,7 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) auto processTables = [this, &debug, &m](const uint64 bar, const VSEC & vsec, const int32 NUMANode) { try { - DBG(1, "Uncore discovery detection. Reading from bar 0x", std::hex, bar, " Address 0x", vsec.fields.Address, std::dec, + DBG(1, "Uncore discovery detection. Reading from bar 0x", std::hex, bar, std::dec, " NUMANode: ", NUMANode); constexpr size_t UncoreDiscoverySize = 3UL; union UncoreGlobalDiscovery { @@ -29,8 +29,7 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) uint64 table[UncoreDiscoverySize]; }; UncoreGlobalDiscovery global; - const auto fullAddress = bar + 8ULL * vsec.fields.Address; - mmio_memcpy(global.table, fullAddress, UncoreDiscoverySize * sizeof(uint64), true); + mmio_memcpy(global.table, bar, UncoreDiscoverySize * sizeof(uint64), true); size_t socket = 0; // default socket if NUMA node -> socket mapping fails if (NUMANode >= 0) { @@ -46,7 +45,7 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) globalPMUs[socket].push_back(global.pmu); if (debug) { - std::cerr << "Read global.pmu from 0x" << std::hex << fullAddress << std::dec << "\n"; + std::cerr << "Read global.pmu from 0x" << std::hex << bar << std::dec << "\n"; global.pmu.print(); std::cout.flush(); } @@ -59,10 +58,10 @@ UncorePMUDiscovery::UncorePMUDiscovery(PCM & m) BoxPMUMap boxPMUMap; for (size_t u = 0; u < global.pmu.maxUnits; ++u) { - mmio_memcpy(unit.table, fullAddress + (u + 1) * step, UncoreDiscoverySize * sizeof(uint64), true); + mmio_memcpy(unit.table, bar + (u + 1) * step, UncoreDiscoverySize * sizeof(uint64), true); if (debug) { - std::cerr << "Read unit.pmu " << u << " from 0x" << std::hex << (fullAddress + (u + 1) * step) << std::dec << "\n"; + std::cerr << "Read unit.pmu " << u << " from 0x" << std::hex << (bar + (u + 1) * step) << std::dec << "\n"; unit.pmu.print(); std::cout.flush(); } From e5c5d445461e7b5da70575008ac9090f1ad6c0ca Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Tue, 22 Sep 2026 17:30:40 +0200 Subject: [PATCH 32/40] cpucounters: collect the IA32_PERF_STATUS metrics on demand IA32_PERF_STATUS (0x198) reports the current operating point of a core: the RATIO field (bits 15:8) holds the performance state value, i.e. the multiplier of the bus clock, and the VOLTAGE field (bits 47:32) holds the operating voltage in 3.13 fixed point format. Neither was available through the counter states so far, although both are cheap to read alongside the temperature. Read the MSR in BasicCounterState::readAndAggregate() and expose the two fields via getPerfStatusRatio() and getPerfStatusVoltage(). Both are instantaneous values rather than deltas over the measurement interval, so they are averaged over the logical cores a state aggregates instead of being added up, which makes the socket, die and system states report the mean operating point of their cores. The register is not architectural, therefore the two fields are validated and counted separately: a platform may leave one of them reserved, where it reads back as 0. Since neither the ratio nor the voltage of a running core can be 0, a zero field is treated as not populated and the corresponding getter returns PCM_INVALID_PERF_STATUS_METRIC instead of a fabricated measurement. The same applies to cores whose MSR read fails outright. Reading one more MSR per core per sample is not free on a machine with a few hundred cores, so the collection is off by default and has to be requested with enablePerfStatusCollection(), the way initRDT() gates the RDT metrics. Tools that do not ask for it are unaffected. Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.cpp | 25 ++++++++++++ src/cpucounters.h | 92 +++++++++++++++++++++++++++++++++++++++++++++ src/types.h | 14 +++++++ 3 files changed, 131 insertions(+) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index f5d3dc8d..39f6e5b8 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -5850,6 +5850,31 @@ void BasicCounterState::readAndAggregate(std::shared_ptr msr) msr->read(MSR_IA32_THERM_STATUS, &thermStatus); MSRValues[MSR_IA32_THERM_STATUS] = thermStatus; + // reading the current performance state value (RATIO) and the operating voltage (VOLTAGE) + if (m->isPerfStatusCollectionEnabled()) + { + uint64 cPerfStatus = 0; + if (msr->read(MSR_IA32_PERF_STATUS, &cPerfStatus) == sizeof(uint64)) + { + MSRValues[MSR_IA32_PERF_STATUS] = cPerfStatus; + // IA32_PERF_STATUS is not architectural: a platform may leave one of the fields reserved + // (reading as 0). Neither the ratio nor the voltage of a running core can be 0, therefore + // each field is accounted for only if it is populated. + const auto cRatio = extract_bits(cPerfStatus, MSR_IA32_PERF_STATUS_RATIO_FIRST_BIT, MSR_IA32_PERF_STATUS_RATIO_LAST_BIT); + if (cRatio != 0) + { + PerfStatusRatioSum += cRatio; + ++PerfStatusRatioCores; + } + const auto cVoltage = extract_bits(cPerfStatus, MSR_IA32_PERF_STATUS_VOLTAGE_FIRST_BIT, MSR_IA32_PERF_STATUS_VOLTAGE_LAST_BIT); + if (cVoltage != 0) + { + PerfStatusVoltageSum += cVoltage; + ++PerfStatusVoltageCores; + } + } + } + msr->read(MSR_SMI_COUNT, &cSMICount); MSRValues[MSR_SMI_COUNT] = cSMICount; diff --git a/src/cpucounters.h b/src/cpucounters.h index b9280ff5..3c14f992 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -866,6 +866,7 @@ class PCM_API PCM bool useResctrl; bool RDTInitialized{false}; std::vector coreRMIDs{}; // RMID associated with each core by initRDT() via direct MSR programming (invalidRMID if none) + bool perfStatusCollection{false}; // read IA32_PERF_STATUS in the core counter states, see enablePerfStatusCollection() std::shared_ptr clientBW; std::shared_ptr clientImcReads; @@ -1405,6 +1406,20 @@ class PCM_API PCM return result; } + /*! + \brief Enables the collection of IA32_PERF_STATUS (RATIO, VOLTAGE) in the core counter states + + IA32_PERF_STATUS is not collected by default: tools that need the RATIO and VOLTAGE metrics + (see BasicCounterState::getPerfStatusRatio() and BasicCounterState::getPerfStatusVoltage()) + must call this method explicitly before reading the counter states. + + \param enable true to read IA32_PERF_STATUS on every core, false to stop reading it + */ + void enablePerfStatusCollection(const bool enable = true) { perfStatusCollection = enable; } + + //! \brief Returns true if the collection of IA32_PERF_STATUS is enabled, see enablePerfStatusCollection() + bool isPerfStatusCollectionEnabled() const { return perfStatusCollection; } + /*! \brief Set quiet mode for PCM initialization @@ -3303,6 +3318,14 @@ class BasicCounterState uint64 MemoryBWLocal; uint64 MemoryBWTotal; uint64 SMICount; + // IA32_PERF_STATUS data: sums over the logical cores aggregated in this state and the number of + // those cores. The RATIO and VOLTAGE fields are instantaneous values, therefore they are averaged + // (and not added up) by the getters below. The two fields are counted separately because + // IA32_PERF_STATUS is not architectural: a platform may populate only one of them. + uint64 PerfStatusRatioSum; + uint64 PerfStatusRatioCores; + uint64 PerfStatusVoltageSum; // in 3.13 fixed point format + uint64 PerfStatusVoltageCores; uint64 FrontendBoundSlots, BadSpeculationSlots, BackendBoundSlots, RetiringSlots, AllSlotsRaw; uint64 MemBoundSlots, FetchLatSlots, BrMispredSlots, HeavyOpsSlots; std::unordered_map MSRValues; @@ -3315,6 +3338,10 @@ class BasicCounterState MemoryBWLocal(0), MemoryBWTotal(0), SMICount(0), + PerfStatusRatioSum(0), + PerfStatusRatioCores(0), + PerfStatusVoltageSum(0), + PerfStatusVoltageCores(0), FrontendBoundSlots(0), BadSpeculationSlots(0), BackendBoundSlots(0), @@ -3350,6 +3377,10 @@ class BasicCounterState MemoryBWLocal += o.MemoryBWLocal; MemoryBWTotal += o.MemoryBWTotal; SMICount += o.SMICount; + PerfStatusRatioSum += o.PerfStatusRatioSum; + PerfStatusRatioCores += o.PerfStatusRatioCores; + PerfStatusVoltageSum += o.PerfStatusVoltageSum; + PerfStatusVoltageCores += o.PerfStatusVoltageCores; DBG(4, "before PCM debug aggregate ", FrontendBoundSlots , " " , BadSpeculationSlots , " " , BackendBoundSlots , " " , RetiringSlots ); BasicCounterState old = *this; FrontendBoundSlots += o.FrontendBoundSlots; @@ -3378,6 +3409,49 @@ class BasicCounterState //! Returns current thermal headroom below TjMax int32 getThermalHeadroom() const { return ThermalHeadroom; } + + //! Returns true if the RATIO field of IA32_PERF_STATUS was populated on at least one logical core of this state + bool isPerfStatusRatioAvailable() const { return PerfStatusRatioCores != 0; } + + //! Returns true if the VOLTAGE field of IA32_PERF_STATUS was populated on at least one logical core of this state + bool isPerfStatusVoltageAvailable() const { return PerfStatusVoltageCores != 0; } + + /*! \brief Returns the current performance state value (RATIO field of IA32_PERF_STATUS) + + The ratio is the multiplier of the bus clock (usually 100 MHz), e.g. the ratio 30 corresponds + to the core frequency of 3 GHz. + + The value is an instantaneous sample taken while the counter state was read and not an average + over the measurement interval (use getActiveAverageFrequency() for the latter). For states + aggregating several logical cores the average over those cores is returned: every logical core + counts once, therefore both SMT threads of a physical core (which read the same core scoped + MSR at different points in time) contribute to the average. + + \return PCM_INVALID_PERF_STATUS_METRIC if the metric is not available, see isPerfStatusRatioAvailable() + */ + double getPerfStatusRatio() const + { + if (isPerfStatusRatioAvailable() == false) + return PCM_INVALID_PERF_STATUS_METRIC; + + return double(PerfStatusRatioSum) / double(PerfStatusRatioCores); + } + + /*! \brief Returns the current operating voltage in Volt (VOLTAGE field of IA32_PERF_STATUS) + + The value is an instantaneous sample taken while the counter state was read and not an average + over the measurement interval. For states aggregating several logical cores the average over + those cores is returned, see getPerfStatusRatio() for the details of the averaging. + + \return PCM_INVALID_PERF_STATUS_METRIC if the metric is not available, see isPerfStatusVoltageAvailable() + */ + double getPerfStatusVoltage() const + { + if (isPerfStatusVoltageAvailable() == false) + return PCM_INVALID_PERF_STATUS_METRIC; + + return double(PerfStatusVoltageSum) / double(PerfStatusVoltageCores) / double(1ULL << MSR_IA32_PERF_STATUS_VOLTAGE_FRACTION_BITS); + } }; inline uint64 RDTSC() @@ -3426,6 +3500,24 @@ int32 getThermalHeadroom(const CounterStateType & /* before */, const CounterSta return after.getThermalHeadroom(); } +/*! \brief Returns the current performance state value (RATIO field of IA32_PERF_STATUS) of the state + after the measurement interval, see BasicCounterState::getPerfStatusRatio() +*/ +template +double getPerfStatusRatio(const CounterStateType & /* before */, const CounterStateType & after) +{ + return after.getPerfStatusRatio(); +} + +/*! \brief Returns the current operating voltage in Volt (VOLTAGE field of IA32_PERF_STATUS) of the + state after the measurement interval, see BasicCounterState::getPerfStatusVoltage() +*/ +template +double getPerfStatusVoltage(const CounterStateType & /* before */, const CounterStateType & after) +{ + return after.getPerfStatusVoltage(); +} + /*! \brief Returns the ratio of QPI cycles in power saving half-lane mode \param port QPI port number \param before CPU counter state before the experiment diff --git a/src/types.h b/src/types.h index 6fb1f296..a69e8452 100644 --- a/src/types.h +++ b/src/types.h @@ -1476,6 +1476,20 @@ constexpr auto MSR_IA32_THERM_STATUS = 0x019C; constexpr auto PCM_INVALID_THERMAL_HEADROOM = (std::numeric_limits::min)(); #endif +constexpr auto MSR_IA32_PERF_STATUS = 0x0198; +// RATIO: current performance state value (bus clock multiplier) +constexpr auto MSR_IA32_PERF_STATUS_RATIO_FIRST_BIT = 8; +constexpr auto MSR_IA32_PERF_STATUS_RATIO_LAST_BIT = 15; +// VOLTAGE: current operating voltage in 3.13 fixed point format, i.e. voltage in Volt = VOLTAGE / 2^13 +constexpr auto MSR_IA32_PERF_STATUS_VOLTAGE_FIRST_BIT = 32; +constexpr auto MSR_IA32_PERF_STATUS_VOLTAGE_LAST_BIT = 47; +constexpr auto MSR_IA32_PERF_STATUS_VOLTAGE_FRACTION_BITS = 13; +#ifndef KERNEL +// returned by the IA32_PERF_STATUS getters if the metric is not available: both metrics are positive +// on a running core, therefore a negative value can not be mistaken for a measurement +constexpr auto PCM_INVALID_PERF_STATUS_METRIC = -1.; +#endif + constexpr auto MSR_IA32_BIOS_SIGN_ID = 0x8B; constexpr auto MSR_DRAM_ENERGY_STATUS = 0x0619; From 0b7217f414cf627ce553d121327a8b65eae65e84 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Tue, 22 Sep 2026 17:31:22 +0200 Subject: [PATCH 33/40] pcm: add the --perf-status option for the RATIO and VOLT metrics Report the operating point of the cores from IA32_PERF_STATUS in two new columns: RATIO, the current performance state value, and VOLT, the current operating voltage in Volt. Both are shown for every kind of row, per core as well as aggregated per die, per socket and for the whole system, and in the CSV output as well as in the text output. The metrics are opt in. They cost one MSR read per core per sample, and adding two columns unconditionally would change the CSV column layout that existing scripts parse, so the option enables the collection in PCM and both outputs keep their current shape without it. RATIO and VOLT are instantaneous samples, unlike every other metric of the tool, which is a delta over the sample interval. The values of the cores are read one after another during a sweep over the cores, so a row aggregating several cores averages samples taken at slightly different points in time and the ratio of a core does not have to agree with its CFREQ. Both the legend and the help text say so, and point at CFREQ for the core frequency over the interval. A field that the processor does not populate is printed as "N/A" rather than as a zero measurement, and a diagnostic names the affected field once at startup. Co-Authored-By: Claude Opus 5 (1M context) --- src/pcm.cpp | 117 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 113 insertions(+), 4 deletions(-) diff --git a/src/pcm.cpp b/src/pcm.cpp index 5de5c8bb..74d31a99 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -54,6 +54,32 @@ std::string temp_format(int32 t) return buffer; } +bool perf_status_metrics = false; // request the IA32_PERF_STATUS metrics (RATIO, VOLT), see the --perf-status command line option + +//! \brief formats the current performance state value (RATIO field of IA32_PERF_STATUS) +template +std::string ratio_format(const State & state) +{ + if (state.isPerfStatusRatioAvailable() == false) + return "N/A"; + + char buffer[1024]; + snprintf(buffer, 1024, "%5.1f", state.getPerfStatusRatio()); + return buffer; +} + +//! \brief formats the current operating voltage in Volt (VOLTAGE field of IA32_PERF_STATUS) +template +std::string voltage_format(const State & state) +{ + if (state.isPerfStatusVoltageAvailable() == false) + return "N/A"; + + char buffer[1024]; + snprintf(buffer, 1024, "%5.3f", state.getPerfStatusVoltage()); + return buffer; +} + std::string l3cache_occ_format(uint64 o) { char buffer[1024]; @@ -185,6 +211,11 @@ void print_help(const string & prog_name) << " with AET support and RDT monitoring via direct MSR programming.\n" << " The per-RMID core energy metric is not comparable to the\n" << " package/CPU energy of MSR_PKG_ENERGY_STATUS\n"; + cout << " -ps | --perf-status | /ps => show the IA32_PERF_STATUS metrics (RATIO: current\n" + << " performance state value, VOLT: current operating voltage\n" + << " in Volt). Both are instantaneous samples and not averages\n" + << " over the sample interval. Rows aggregating several logical\n" + << " cores show the average over those cores\n"; cout << " --color => use ASCII colors\n"; cout << " --no-color => don't use ASCII colors\n"; cout << " -csv[=file.csv] | /csv[=file.csv] => output compact CSV format to screen or\n" @@ -256,7 +287,13 @@ void print_other_metrics(const PCM * m, const State & state1, const State & stat cout << setNextColor() << " " << setw(6) << aet_format(aet.energy); cout << setNextColor() << " " << setw(6) << aet_format(aet.cdyn); } - cout << setNextColor() << " " << temp_format(state2.getThermalHeadroom()) << "\n"; + cout << setNextColor() << " " << temp_format(state2.getThermalHeadroom()); + if (perf_status_metrics) + { + cout << setNextColor() << " " << setw(5) << ratio_format(state2); + cout << setNextColor() << " " << setw(5) << voltage_format(state2); + } + cout << "\n"; } void print_output(PCM * m, @@ -337,6 +374,13 @@ void print_output(PCM * m, cout << " CDYN : dynamic capacitance (Cdyn) of the cores in the sample interval (in nanofarad)\n"; } cout << " TEMP : Temperature reading in 1 degree Celsius relative to the TjMax temperature (thermal headroom): 0 corresponds to the max temperature\n"; + if (perf_status_metrics) + { + cout << " RATIO : current performance state value (RATIO field of IA32_PERF_STATUS): multiplier of the bus clock (usually 100 MHz), e.g. 30 corresponds to 3 GHz\n"; + cout << " VOLT : current operating voltage in Volt (VOLTAGE field of IA32_PERF_STATUS)\n"; + cout << " RATIO and VOLT are instantaneous samples taken while the counters are read and not averages over the sample interval (unlike all other metrics above): use CFREQ to compare the core frequency over the interval.\n"; + cout << " Rows aggregating several logical cores show the average over those cores, each of them sampled at a slightly different point in time.\n"; + } cout << " energy: Energy in Joules\n"; cout << "\n"; cout << "\n"; @@ -387,7 +431,10 @@ void print_output(PCM * m, if (aet_available(m)) cout << setNextColor() << " CENRG |" << setNextColor() << " CDYN |"; - cout << setNextColor() << " TEMP\n\n"; + cout << setNextColor() << " TEMP"; + if (perf_status_metrics) + cout << " |" << setNextColor() << " RATIO |" << setNextColor() << " VOLT"; + cout << "\n\n"; cout << resetColor(); @@ -473,7 +520,13 @@ void print_output(PCM * m, cout << setNextColor() << " " << setw(6) << aet_format(aet.cdyn); } - cout << setNextColor() << " N/A\n"; + cout << setNextColor() << " N/A"; // TEMP + if (perf_status_metrics) + { + cout << setNextColor() << " " << setw(5) << ratio_format(sstate2); + cout << setNextColor() << " " << setw(5) << voltage_format(sstate2); + } + cout << "\n"; cout << resetColor(); cout << setNextColor() << "\n Instructions retired: " << unit_format(getInstructionsRetired(sstate1, sstate2)) << " ;" << setNextColor() << " Active cycles: " << unit_format(getCycles(sstate1, sstate2)) << " ;" @@ -892,6 +945,9 @@ void print_csv_header(PCM * m, if (aet_available(m)) print_csv_header_helper(header, 2); // CENRG,CDYN + if (perf_status_metrics) + print_csv_header_helper(header, 2); // RATIO,VOLT + print_csv_header_helper(header,7); if (m->getNumSockets() > 1) { // QPI info only for multi socket systems if (m->incomingQPITrafficMetricsAvailable()) @@ -944,6 +1000,8 @@ void print_csv_header(PCM * m, print_csv_header_helper(header,2); if (m->memoryIOTrafficMetricAvailable()) print_csv_header_helper(header,3); + if (perf_status_metrics) + print_csv_header_helper(header, 2); // RATIO,VOLT print_csv_header_helper(header, 8); //TEMP,INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%, } @@ -1051,6 +1109,8 @@ void print_csv_header(PCM * m, if (aet_available(m)) print_csv_header_helper(header, 2); // CENRG,CDYN print_csv_header_helper(header); // TEMP + if (perf_status_metrics) + print_csv_header_helper(header, 2); // RATIO,VOLT print_csv_header_helper(header, 7); // INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom% } } @@ -1079,6 +1139,8 @@ void print_csv_header(PCM * m, if (m->isCoreCStateResidencySupported(s)) print_csv_header_helper(header); print_csv_header_helper(header);// TEMP + if (perf_status_metrics) + print_csv_header_helper(header, 2); // RATIO,VOLT print_csv_header_helper(header,7); //ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%, } } @@ -1105,6 +1167,9 @@ void print_csv_header(PCM * m, if (aet_available(m)) cout << "CENRG,CDYN,"; + if (perf_status_metrics) + cout << "RATIO,VOLT,"; + cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; if (m->getNumSockets() > 1) { // QPI info only for multi socket systems if (m->incomingQPITrafficMetricsAvailable()) @@ -1162,7 +1227,10 @@ void print_csv_header(PCM * m, cout << "HBM_READ,HBM_WRITE,"; if (m->memoryIOTrafficMetricAvailable()) cout << "IO,IA,GT,"; - cout << "TEMP,INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; + cout << "TEMP,"; + if (perf_status_metrics) + cout << "RATIO,VOLT,"; + cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; } if (m->getNumSockets() > 1 && (m->incomingQPITrafficMetricsAvailable())) // QPI info only for multi socket systems @@ -1264,6 +1332,8 @@ void print_csv_header(PCM * m, if (aet_available(m)) cout << "CENRG,CDYN,"; cout << "TEMP,"; + if (perf_status_metrics) + cout << "RATIO,VOLT,"; cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; } } @@ -1290,6 +1360,8 @@ void print_csv_header(PCM * m, cout << "C" << s << "res%,"; cout << "TEMP,"; + if (perf_status_metrics) + cout << "RATIO,VOLT,"; cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; } } @@ -1396,6 +1468,9 @@ void print_csv(PCM * m, cout << aet_format(aet.energy) << ',' << aet_format(aet.cdyn) << ','; } + if (perf_status_metrics) + cout << ratio_format(sstate2) << ',' << voltage_format(sstate2) << ','; + cout << float_format(getInstructionsRetired(sstate1, sstate2)) << "," << float_format(getCycles(sstate1, sstate2)) << "," << float_format(getInvariantTSC(cstates1[0], cstates2[0])) << "," @@ -1458,6 +1533,8 @@ void print_csv(PCM * m, << ',' << getGTRequestBytesFromMC(sktstate1[i], sktstate2[i]) / double(1e9); } cout << ',' << temp_format(sktstate2[i].getThermalHeadroom()) << ','; + if (perf_status_metrics) + cout << ratio_format(sktstate2[i]) << ',' << voltage_format(sktstate2[i]) << ','; cout << float_format(getInstructionsRetired(sktstate1[i], sktstate2[i])) << "," << float_format(getCycles(sktstate1[i], sktstate2[i])) << "," @@ -1568,6 +1645,8 @@ void print_csv(PCM * m, get_aet_row_sum(m, [&m, &key](const uint32 core) { return m->getSocketId(core) == key.first && m->getDieId(core) == key.second; }, sstate1, sstate2)); cout << ',' << temp_format(die_cstates2[key].getThermalHeadroom()) << ','; + if (perf_status_metrics) + cout << ratio_format(die_cstates2[key]) << ',' << voltage_format(die_cstates2[key]) << ','; cout << float_format(getInstructionsRetired(die_cstates1[key], die_cstates2[key])) << "," << float_format(getCycles(die_cstates1[key], die_cstates2[key])) << "," @@ -1595,6 +1674,8 @@ void print_csv(PCM * m, cout << getCoreCStateResidency(s, cstates1[i], cstates2[i]) * 100 << ","; cout << temp_format(cstates2[i].getThermalHeadroom()) << ','; + if (perf_status_metrics) + cout << ratio_format(cstates2[i]) << ',' << voltage_format(cstates2[i]) << ','; cout << float_format(getInstructionsRetired(cstates1[i], cstates2[i])) << "," << float_format(getCycles(cstates1[i], cstates2[i])) << "," @@ -1789,6 +1870,11 @@ int mainThrows(int argc, char * argv[]) aet_metrics = true; continue; } + else if (check_argument_equals(*argv, {"--perf-status", "-ps", "/ps"})) + { + perf_status_metrics = true; + continue; + } else if (check_argument_equals(*argv, {"--color"})) { setColorEnabled(); @@ -1910,6 +1996,11 @@ int mainThrows(int argc, char * argv[]) program_aet(m); + if (perf_status_metrics) + { + m->enablePerfStatusCollection(); // pcm reads IA32_PERF_STATUS (RATIO, VOLT) only on demand + } + print_cpu_details(); std::vector cstates1, cstates2; @@ -1937,6 +2028,24 @@ int mainThrows(int argc, char * argv[]) m->getAllCounterStates(sstate1, sktstate1, cstates1); + if (perf_status_metrics) + { // report the fields of IA32_PERF_STATUS that this system does not populate + const bool ratioAvailable = sstate1.isPerfStatusRatioAvailable(); + const bool voltageAvailable = sstate1.isPerfStatusVoltageAvailable(); + if (ratioAvailable == false && voltageAvailable == false) + { + cerr << "ERROR: the RATIO and VOLT metrics are not available: IA32_PERF_STATUS (0x198) could not be read on this system.\n"; + } + else if (ratioAvailable == false) + { + cerr << "ERROR: the RATIO metric is not available: the RATIO field of IA32_PERF_STATUS (0x198) is not populated on this system.\n"; + } + else if (voltageAvailable == false) + { + cerr << "ERROR: the VOLT metric is not available: the VOLTAGE field of IA32_PERF_STATUS (0x198) is not populated on this system.\n"; + } + } + if (sysCmd != NULL) { MySystem(sysCmd, sysArgv); } From 766652aa4d5ddecd1f7296c7a73996178202c8db Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Wed, 23 Sep 2026 12:22:01 +0200 Subject: [PATCH 34/40] pcm: do not pad the RATIO field of the CSV output ratio_format() formatted with a field width of 5, which is what the text output needs, but the CSV output shares the same helper and wrote " 30.0" instead of "30.0". Format without a field width and leave the padding to the setw() that both text call sites already apply, so the text output is unchanged. Also describe the averaging of the two metrics more precisely: a logical core whose RATIO or VOLTAGE field is not populated is left out of the average, so the aggregated rows show the mean over the cores that report the metric and not over every core of the row. Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.h | 7 ++++--- src/pcm.cpp | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/cpucounters.h b/src/cpucounters.h index 3c14f992..a780fbba 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -3423,9 +3423,10 @@ class BasicCounterState The value is an instantaneous sample taken while the counter state was read and not an average over the measurement interval (use getActiveAverageFrequency() for the latter). For states - aggregating several logical cores the average over those cores is returned: every logical core - counts once, therefore both SMT threads of a physical core (which read the same core scoped - MSR at different points in time) contribute to the average. + aggregating several logical cores the average over the cores that report the field is returned: + every reporting logical core counts once, therefore both SMT threads of a physical core (which + read the same core scoped MSR at different points in time) contribute to the average, while a + core that leaves the field unpopulated is left out of it. \return PCM_INVALID_PERF_STATUS_METRIC if the metric is not available, see isPerfStatusRatioAvailable() */ diff --git a/src/pcm.cpp b/src/pcm.cpp index 74d31a99..f746ae9c 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -64,7 +64,8 @@ std::string ratio_format(const State & state) return "N/A"; char buffer[1024]; - snprintf(buffer, 1024, "%5.1f", state.getPerfStatusRatio()); + // no field width: the text output pads with setw(), the CSV output must not be padded + snprintf(buffer, 1024, "%.1f", state.getPerfStatusRatio()); return buffer; } @@ -215,7 +216,7 @@ void print_help(const string & prog_name) << " performance state value, VOLT: current operating voltage\n" << " in Volt). Both are instantaneous samples and not averages\n" << " over the sample interval. Rows aggregating several logical\n" - << " cores show the average over those cores\n"; + << " cores show the average over the cores reporting the metric\n"; cout << " --color => use ASCII colors\n"; cout << " --no-color => don't use ASCII colors\n"; cout << " -csv[=file.csv] | /csv[=file.csv] => output compact CSV format to screen or\n" @@ -379,7 +380,7 @@ void print_output(PCM * m, cout << " RATIO : current performance state value (RATIO field of IA32_PERF_STATUS): multiplier of the bus clock (usually 100 MHz), e.g. 30 corresponds to 3 GHz\n"; cout << " VOLT : current operating voltage in Volt (VOLTAGE field of IA32_PERF_STATUS)\n"; cout << " RATIO and VOLT are instantaneous samples taken while the counters are read and not averages over the sample interval (unlike all other metrics above): use CFREQ to compare the core frequency over the interval.\n"; - cout << " Rows aggregating several logical cores show the average over those cores, each of them sampled at a slightly different point in time.\n"; + cout << " Rows aggregating several logical cores show the average over the cores that report the metric, each of them sampled at a slightly different point in time.\n"; } cout << " energy: Energy in Joules\n"; cout << "\n"; From 957e50affbe8f79fde558f58ebfef6d1c2971a72 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Wed, 23 Sep 2026 12:23:17 +0200 Subject: [PATCH 35/40] cpucounters: expose the uncore voltage and throttling of UFS_STATUS The UFS (Uncore Frequency Scaling) TPMI UFS_STATUS register is already read once per sample for the per die uncore frequency, but only its CURRENT_RATIO and agent type fields were decoded. Two more fields of the same register are useful and come for free: - CURRENT_VOLTAGE (bits 22:7), the fabric voltage in U3.13 format, exposed by getUncoreVoltage() in Volt. Like the frequency it is an instantaneous sample and not an average over the measurement interval. - THROTTLE_COUNTER (bits 63:32), which the hardware increments at most once per 1ms interval in which the fabric frequency violated the bound programmed in UFS_CONTROL. getUncoreThrottleCount() returns the difference between the two states, i.e. the number of milliseconds of the interval in which the uncore frequency was clipped. The counter is 32 bit wide and the subtraction is masked accordingly, so a wrap around after ~50 days of uninterrupted throttling does not produce a bogus delta. The field positions get named constants and the existing frequency decoding uses them as well, which also documents why a bus clock of 100MHz is assumed: it is the only encoding defined by UFS_HEADER.RATIO_UNIT. Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.h | 47 ++++++++++++++++++++++++++++++++++++++++++++++- src/types.h | 12 ++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/cpucounters.h b/src/cpucounters.h index a780fbba..51284532 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -3944,6 +3944,10 @@ class UncoreCounterState template friend std::vector getUncoreFrequency(const CounterStateType& state); template + friend std::vector getUncoreVoltage(const CounterStateType& state); + template + friend std::vector getUncoreThrottleCount(const CounterStateType& before, const CounterStateType& after); + template friend std::vector getUncoreDieTypes(const CounterStateType& state); template friend double getAverageFrequencyFromClocks(const int64 clocks, const CounterStateType& before, const CounterStateType& after); @@ -4407,7 +4411,48 @@ std::vector getUncoreFrequency(const CounterStateType& state) std::vector result; for (auto & e : state.UFSStatus) { - result.push_back(extract_bits(e, 0, 6) * 100000000.); + // the ratio unit of 100MHz is the only one defined by UFS_HEADER.RATIO_UNIT + result.push_back(extract_bits(e, UFS_STATUS_CURRENT_RATIO_FIRST_BIT, UFS_STATUS_CURRENT_RATIO_LAST_BIT) * 100000000.); + } + return result; +} + +/*! \brief Returns the current uncore (fabric) voltage vector in Volt + + One entry per uncore die, in the same order as getUncoreFrequency(). Like the uncore frequency + the voltage is an instantaneous sample and not an average over the measurement interval. +*/ +template +std::vector getUncoreVoltage(const CounterStateType& state) +{ + std::vector result; + for (auto & e : state.UFSStatus) + { + result.push_back(double(extract_bits(e, UFS_STATUS_CURRENT_VOLTAGE_FIRST_BIT, UFS_STATUS_CURRENT_VOLTAGE_LAST_BIT)) + / double(1ULL << UFS_STATUS_CURRENT_VOLTAGE_FRACTION_BITS)); + } + return result; +} + +/*! \brief Returns the number of 1ms intervals in which the uncore frequency was throttled below the + bound programmed in UFS_CONTROL during the measurement interval + + One entry per uncore die, in the same order as getUncoreFrequency(). The hardware increments the + counter at most once per 1ms interval, therefore the value is also the number of milliseconds of + the interval in which the fabric frequency was clipped. +*/ +template +std::vector getUncoreThrottleCount(const CounterStateType& before, const CounterStateType& after) +{ + std::vector result; + for (size_t die = 0; die < after.UFSStatus.size(); ++die) + { + const auto afterCount = extract_bits(after.UFSStatus[die], UFS_STATUS_THROTTLE_COUNTER_FIRST_BIT, UFS_STATUS_THROTTLE_COUNTER_LAST_BIT); + // a die missing from the "before" state (e.g. discovered later) reports no throttling + const auto beforeCount = (die < before.UFSStatus.size()) ? + extract_bits(before.UFSStatus[die], UFS_STATUS_THROTTLE_COUNTER_FIRST_BIT, UFS_STATUS_THROTTLE_COUNTER_LAST_BIT) : afterCount; + // the counter is 32 bit wide and wraps around after ~50 days of uninterrupted throttling + result.push_back((afterCount - beforeCount) & 0xffffffffULL); } return result; } diff --git a/src/types.h b/src/types.h index a69e8452..94128b32 100644 --- a/src/types.h +++ b/src/types.h @@ -1490,6 +1490,18 @@ constexpr auto MSR_IA32_PERF_STATUS_VOLTAGE_FRACTION_BITS = 13; constexpr auto PCM_INVALID_PERF_STATUS_METRIC = -1.; #endif +// UFS_STATUS register of the Uncore Frequency Scaling (UFS) TPMI interface, see PCM::UFS_TPMI +constexpr auto UFS_STATUS_CURRENT_RATIO_FIRST_BIT = 0; +constexpr auto UFS_STATUS_CURRENT_RATIO_LAST_BIT = 6; +// CURRENT_VOLTAGE: current fabric voltage in U3.13 format, i.e. voltage in Volt = CURRENT_VOLTAGE / 2^13 +constexpr auto UFS_STATUS_CURRENT_VOLTAGE_FIRST_BIT = 7; +constexpr auto UFS_STATUS_CURRENT_VOLTAGE_LAST_BIT = 22; +constexpr auto UFS_STATUS_CURRENT_VOLTAGE_FRACTION_BITS = 13; +// THROTTLE_COUNTER: number of 1ms intervals in which the fabric frequency violated the bound +// programmed in UFS_CONTROL. Incremented at most once per 1ms interval. +constexpr auto UFS_STATUS_THROTTLE_COUNTER_FIRST_BIT = 32; +constexpr auto UFS_STATUS_THROTTLE_COUNTER_LAST_BIT = 63; + constexpr auto MSR_IA32_BIOS_SIGN_ID = 0x8B; constexpr auto MSR_DRAM_ENERGY_STATUS = 0x0619; From 87715bad04a94cfcd9c382b4bfeb306c9b2a781e Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Wed, 23 Sep 2026 12:23:41 +0200 Subject: [PATCH 36/40] pcm: add the --ufs-status option for the uncore voltage and throttling The per die uncore columns showed the fabric frequency only. With --ufs-status every die cell also holds the fabric voltage in Volt and the number of milliseconds of the sample interval in which the uncore frequency was clipped below the bound programmed in UFS_CONTROL, in the text as well as in the CSV output. The metrics are opt in because the two extra values per die widen a table that already has one column per uncore die, and because adding them unconditionally would change the CSV column layout that existing scripts parse. Unlike --perf-status the option does not enable any additional hardware access: UFS_STATUS is read in full for the frequency column anyway. Both new values keep the per die cells of the header and of the data rows the same width, so every die column stays under its own header. The throttling field is six characters wide, which covers a fully throttled sample interval of about 16 minutes. Frequency and voltage are instantaneous samples while the throttling is a count over the interval; the legend and the help text say so. Co-Authored-By: Claude Opus 5 (1M context) --- src/pcm.cpp | 87 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 75 insertions(+), 12 deletions(-) diff --git a/src/pcm.cpp b/src/pcm.cpp index f746ae9c..6212f3ce 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -55,6 +55,7 @@ std::string temp_format(int32 t) } bool perf_status_metrics = false; // request the IA32_PERF_STATUS metrics (RATIO, VOLT), see the --perf-status command line option +bool ufs_status_metrics = false; // request the additional UFS_STATUS metrics (uncore voltage and throttling), see the --ufs-status command line option //! \brief formats the current performance state value (RATIO field of IA32_PERF_STATUS) template @@ -69,6 +70,14 @@ std::string ratio_format(const State & state) return buffer; } +//! \brief formats a voltage in Volt, independently of the stream precision +std::string volt_format(const double volts) +{ + char buffer[1024]; + snprintf(buffer, 1024, "%5.3f", volts); + return buffer; +} + //! \brief formats the current operating voltage in Volt (VOLTAGE field of IA32_PERF_STATUS) template std::string voltage_format(const State & state) @@ -76,9 +85,7 @@ std::string voltage_format(const State & state) if (state.isPerfStatusVoltageAvailable() == false) return "N/A"; - char buffer[1024]; - snprintf(buffer, 1024, "%5.3f", state.getPerfStatusVoltage()); - return buffer; + return volt_format(state.getPerfStatusVoltage()); } std::string l3cache_occ_format(uint64 o) @@ -217,6 +224,10 @@ void print_help(const string & prog_name) << " in Volt). Both are instantaneous samples and not averages\n" << " over the sample interval. Rows aggregating several logical\n" << " cores show the average over the cores reporting the metric\n"; + cout << " -us | --ufs-status | /us => add the uncore voltage in Volt and the uncore throttling\n" + << " (number of milliseconds of the sample interval in which the\n" + << " uncore frequency was clipped) to the per die uncore\n" + << " frequency columns. Requires the UFS TPMI interface\n"; cout << " --color => use ASCII colors\n"; cout << " --no-color => don't use ASCII colors\n"; cout << " -csv[=file.csv] | /csv[=file.csv] => output compact CSV format to screen or\n" @@ -382,6 +393,11 @@ void print_output(PCM * m, cout << " RATIO and VOLT are instantaneous samples taken while the counters are read and not averages over the sample interval (unlike all other metrics above): use CFREQ to compare the core frequency over the interval.\n"; cout << " Rows aggregating several logical cores show the average over the cores that report the metric, each of them sampled at a slightly different point in time.\n"; } + if (ufs_status_metrics) + { + cout << " Unc(Ghz|V|THR): per uncore die frequency in GHz, operating voltage in Volt and throttling, i.e. the number of milliseconds of the sample interval\n"; + cout << " in which the uncore frequency was clipped below the configured bound. Frequency and voltage are instantaneous samples, the throttling is a count over the interval.\n"; + } cout << " energy: Energy in Joules\n"; cout << "\n"; cout << "\n"; @@ -751,11 +767,12 @@ void print_output(PCM * m, DBG(2, " Uncore die types count: ", uncoreDieTypes.size()); if (uncoreDieTypes.empty() == false) { - cout << setNextColor() << " Unc(Ghz) "; + // with --ufs-status every die cell holds the frequency, the voltage and the throttling + cout << setNextColor() << (ufs_status_metrics ? " Unc(Ghz|V|THR) " : " Unc(Ghz) "); for (auto & d: uncoreDieTypes) { cout << setNextColor(); - printCentered(UncoreCounterState::getDieTypeStr(d), 7); + printCentered(UncoreCounterState::getDieTypeStr(d), ufs_status_metrics ? 18 : 7); cout << " "; } std::cout << "|" ; @@ -809,10 +826,27 @@ void print_output(PCM * m, if (uncoreFrequencies.empty() == false) { - cout << setNextColor() << " "; - for (auto & d: uncoreFrequencies) + // the wider header prefix of --ufs-status is padded here as well to keep the + // values of a die under its column header + cout << setNextColor() << (ufs_status_metrics ? " " : " "); + if (ufs_status_metrics) + { + const std::vector uncoreVoltages{getUncoreVoltage(sktstate2[i])}; + const std::vector uncoreThrottling{getUncoreThrottleCount(sktstate1[i], sktstate2[i])}; + for (size_t die = 0; die < uncoreFrequencies.size(); ++die) + { + // the throttling field is wide enough for a sample interval of ~16 minutes + cout << setNextColor() << " " << std::setw(4) << uncoreFrequencies[die]/1e9 + << " " << std::setw(5) << volt_format(uncoreVoltages[die]) + << " " << std::setw(6) << uncoreThrottling[die]; + } + } + else { - cout << setNextColor() << " " << std::setw(4) << d/1e9 << " "; + for (auto & d: uncoreFrequencies) + { + cout << setNextColor() << " " << std::setw(4) << d/1e9 << " "; + } } } cout << resetColor() << "\n"; @@ -1084,6 +1118,13 @@ void print_csv_header(PCM * m, { header = "UncFREQ Die " + std::to_string(die) + " (Ghz)"; print_csv_header_helper(header); + if (ufs_status_metrics) + { + header = "UncVOLT Die " + std::to_string(die) + " (V)"; + print_csv_header_helper(header); + header = "UncTHROTTLE Die " + std::to_string(die) + " (ms)"; + print_csv_header_helper(header); + } } } } @@ -1307,8 +1348,8 @@ void print_csv_header(PCM * m, printSKT(i); } for (uint32 i = 0; i < m->getNumSockets(); ++i) - { - printSKT(i, m->getNumUFSDies()); + { // UncFREQ and, with --ufs-status, UncVOLT and UncTHROTTLE of every uncore die + printSKT(i, m->getNumUFSDies() * (ufs_status_metrics ? 3 : 1)); } } @@ -1619,9 +1660,21 @@ void print_csv(PCM * m, { const auto freqs = getUncoreFrequency(sktstate2[i]); assert(freqs.size() == (size_t)m->getNumUFSDies()); - for (auto & f : freqs) + if (ufs_status_metrics) { - cout << f/1e9 << ","; + const auto volts = getUncoreVoltage(sktstate2[i]); + const auto throttling = getUncoreThrottleCount(sktstate1[i], sktstate2[i]); + for (size_t die = 0; die < freqs.size(); ++die) + { + cout << freqs[die]/1e9 << "," << volt_format(volts[die]) << "," << throttling[die] << ","; + } + } + else + { + for (auto & f : freqs) + { + cout << f/1e9 << ","; + } } } } @@ -1876,6 +1929,11 @@ int mainThrows(int argc, char * argv[]) perf_status_metrics = true; continue; } + else if (check_argument_equals(*argv, {"--ufs-status", "-us", "/us"})) + { + ufs_status_metrics = true; + continue; + } else if (check_argument_equals(*argv, {"--color"})) { setColorEnabled(); @@ -2047,6 +2105,11 @@ int mainThrows(int argc, char * argv[]) } } + if (ufs_status_metrics && m->getNumUFSDies() == 0) + { + cerr << "ERROR: the uncore voltage and throttling metrics are not available: no UFS TPMI instance was found on this system.\n"; + } + if (sysCmd != NULL) { MySystem(sysCmd, sysArgv); } From 562ccb634f61a80ea66a66c3b9fc5f6229f1b45b Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Wed, 23 Sep 2026 12:42:18 +0200 Subject: [PATCH 37/40] cpucounters: read IA32_PERF_STATUS only where its fields are validated The register is not architectural and the collection probed it on every processor, relying on the read failing gracefully where it is not implemented. That is not failure-safe on Windows: the bundled MSR driver reports the exception of an unimplemented register as an error and MsrHandle::read asserts on it, so a debug build could abort before reaching the code that reports the metrics as unavailable. Add perfStatusMetricAvailable() and enable the collection only on the server processors on which the RATIO and VOLTAGE fields have been validated: SKX (and with it the CLX and CPX steppings of the same model), ICX, ICX_D, SPR, EMR, GNR and GNR_D. enablePerfStatusCollection() ignores the request everywhere else, so no tool can trigger the read on a processor that may not implement the register, and pcm reports the option as unsupported instead of printing N/A columns without an explanation. MSR 0x198 is now read 768 times on a 384 thread GNR machine sampled twice with --perf-status, and not at all without the option or on a processor outside the list. Co-Authored-By: Claude Opus 5 (1M context) --- src/cpucounters.h | 26 ++++++++++++++++++++++++-- src/pcm.cpp | 6 +++++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/cpucounters.h b/src/cpucounters.h index 51284532..49823f4e 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -1406,16 +1406,38 @@ class PCM_API PCM return result; } + /*! + \brief Returns true if the IA32_PERF_STATUS metrics (RATIO, VOLTAGE) are supported + + IA32_PERF_STATUS is not an architectural register, therefore it is read only on the + processors on which its RATIO and VOLTAGE fields have been validated. Reading an MSR that + the processor does not implement is not failure-safe on every platform: the Windows MSR + driver reports the resulting exception as an error and MsrHandle::read asserts on it. + */ + bool perfStatusMetricAvailable() const + { + return ( + cpu_family_model == PCM::SKX // covers CLX and CPX as well: they are steppings of this model + || cpu_family_model == PCM::ICX + || cpu_family_model == PCM::ICX_D + || cpu_family_model == PCM::SPR + || cpu_family_model == PCM::EMR + || cpu_family_model == PCM::GNR + || cpu_family_model == PCM::GNR_D + ); + } + /*! \brief Enables the collection of IA32_PERF_STATUS (RATIO, VOLTAGE) in the core counter states IA32_PERF_STATUS is not collected by default: tools that need the RATIO and VOLTAGE metrics (see BasicCounterState::getPerfStatusRatio() and BasicCounterState::getPerfStatusVoltage()) - must call this method explicitly before reading the counter states. + must call this method explicitly before reading the counter states. The request is ignored + on processors without perfStatusMetricAvailable(), where the register is never read. \param enable true to read IA32_PERF_STATUS on every core, false to stop reading it */ - void enablePerfStatusCollection(const bool enable = true) { perfStatusCollection = enable; } + void enablePerfStatusCollection(const bool enable = true) { perfStatusCollection = enable && perfStatusMetricAvailable(); } //! \brief Returns true if the collection of IA32_PERF_STATUS is enabled, see enablePerfStatusCollection() bool isPerfStatusCollectionEnabled() const { return perfStatusCollection; } diff --git a/src/pcm.cpp b/src/pcm.cpp index 6212f3ce..17e9e71e 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -2058,6 +2058,10 @@ int mainThrows(int argc, char * argv[]) if (perf_status_metrics) { m->enablePerfStatusCollection(); // pcm reads IA32_PERF_STATUS (RATIO, VOLT) only on demand + if (m->isPerfStatusCollectionEnabled() == false) + { + cerr << "ERROR: the RATIO and VOLT metrics are not supported on this processor: IA32_PERF_STATUS (0x198) is read only on the processors on which its fields have been validated.\n"; + } } print_cpu_details(); @@ -2087,7 +2091,7 @@ int mainThrows(int argc, char * argv[]) m->getAllCounterStates(sstate1, sktstate1, cstates1); - if (perf_status_metrics) + if (perf_status_metrics && m->isPerfStatusCollectionEnabled()) { // report the fields of IA32_PERF_STATUS that this system does not populate const bool ratioAvailable = sstate1.isPerfStatusRatioAvailable(); const bool voltageAvailable = sstate1.isPerfStatusVoltageAvailable(); From 5fbbbe0ec994091170ba52ca5954bedb350b1a06 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Wed, 23 Sep 2026 14:16:34 +0200 Subject: [PATCH 38/40] msr: report a failed MSR read on Windows instead of asserting MsrHandle::read asserted on a failing DeviceIoControl and then returned the length reported by the driver regardless. The MSR driver catches the exception of a register the processor does not implement and completes the request with the exception code, so reading such a register aborted a debug build and looked like a successful read in a release build, where the output buffer keeps whatever the caller had put there. Return 0 for a failed read, which is what the winring0 path in the same function, the Linux path and the FreeBSD path already do, and which the callers that test the result against sizeof(uint64) already expect: the probes of MSR_TSX_FORCE_ABORT, MSR_PERF_CAPABILITIES, MSR_IA32_BIOS_SIGN_ID and IA32_PERF_STATUS now detect an unimplemented register on Windows as they do everywhere else. The failure is no longer silent for developers either: the driver prints the exception code with DbgPrint and the host side logs the core and the register number at debug level 2. Co-Authored-By: Claude Opus 5 (1M context) --- src/msr.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/msr.cpp b/src/msr.cpp index 9f33711f..868a0f5a 100644 --- a/src/msr.cpp +++ b/src/msr.cpp @@ -86,7 +86,13 @@ int32 MsrHandle::read(uint64 msr_number, uint64 * value) req.core_id = cpu_id; req.msr_address = msr_number; BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_READ, &req, sizeof(MSR_Request), value, sizeof(uint64), &reslength, NULL); - assert(status && "Error in DeviceIoControl"); + if (status == FALSE) + { + // the driver reports the exception of an unimplemented register as an error: report the + // failed read to the caller like the winring0 path below and the other platforms do + DBG(2, "core_id = ", cpu_id, " reading MSR 0x", std::hex, msr_number, std::dec, " failed"); + return 0; + } return (int32)reslength; } From 7953b2696fad38798798f9d8c2db6159f8e35ab7 Mon Sep 17 00:00:00 2001 From: twillhal Date: Mon, 5 Oct 2026 15:46:39 +0200 Subject: [PATCH 39/40] Use Core client package C-state MSRs for ADL/RPL/MTL/LNL/ARL/PTL The hybrid client models were grouped with the Atom parts in the package C-state table (PC2=0x3F8, PC4=0x3F9, PC6=0x3FA). On these Core client parts MSR_PKG_C2_RESIDENCY is 0x60D and 0x3F8/0x3F9/0x3FA are PC3/PC6/PC7, with PC8-PC10 at 0x630-0x632, the same layout as the Skylake-path clients. As a result PC2 was never read and package C0 was always reported as 100%. Verified on Panther Lake (Core Ultra X7 358H): idle system now reports ~92-95% PC2 (raw 0x60D/TSC ratio: ~97%) instead of C0=100%; under full load package C0 is 100%. Other listed models share the same layout but were not tested on hardware. Fixes #995 Co-Authored-By: Claude Opus 5.5 --- src/cpucounters.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cpucounters.cpp b/src/cpucounters.cpp index 39f6e5b8..915f4aeb 100644 --- a/src/cpucounters.cpp +++ b/src/cpucounters.cpp @@ -822,12 +822,6 @@ void PCM::initCStateSupportTables() case APOLLO_LAKE: case GEMINI_LAKE: case DENVERTON: - case ADL: - case RPL: - case MTL: - case LNL: - case ARL: - case PTL: case SNOWRIDGE: case ELKHART_LAKE: case JASPER_LAKE: @@ -865,6 +859,12 @@ void PCM::initCStateSupportTables() case BROADWELL: PCM_SKL_PATH_CASES case BROADWELL_XEON_E3: + case ADL: + case RPL: + case MTL: + case LNL: + case ARL: + case PTL: PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0x630, 0x631, 0x632}) ); default: From bce9ac83cdc25d2cb811ee38dc02222ccdcff576 Mon Sep 17 00:00:00 2001 From: Roman Dementiev Date: Wed, 7 Oct 2026 13:54:59 +0200 Subject: [PATCH 40/40] Potential fix for pull request finding 'Validate targets before generating Telegraf configuration' Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- scripts/grafana/start.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/grafana/start.sh b/scripts/grafana/start.sh index b48cf95d..d4d5f062 100755 --- a/scripts/grafana/start.sh +++ b/scripts/grafana/start.sh @@ -36,7 +36,12 @@ if [ "$#" -ne 1 ]; then usage fi -if [ ! -f "$1" ]; then +if [ -f "$1" ]; then + [ -s "$1" ] || { echo "Error: targets file is empty."; exit 1; } + while IFS= read -r line || [[ -n "$line" ]]; do + validate_url "http://$line" + done < "$1" +else validate_url "$1" fi