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 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 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 1ceb7c55..915f4aeb 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(); @@ -608,8 +587,41 @@ 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 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 joinCounterWidthExtenders(Container & c) +{ + for (auto & counter : c) + { + if (counter.get()) + { + counter->stopAndJoinUpdateThread(); + } + } +} + void PCM::initRDT() { + if (RDTInitialized) + return; if (!(QOSMetricAvailable() && L3QOSMetricAvailable())) return; #ifdef __linux__ @@ -620,8 +632,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()) @@ -630,8 +645,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()) @@ -640,11 +658,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; @@ -653,20 +679,37 @@ 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 */ - 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; + 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(); //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); @@ -674,15 +717,31 @@ 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; + coreRMIDs[core] = rmid[topology[core].socket_id]; + } 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()) { @@ -692,10 +751,38 @@ 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) + { + std::cerr << "ERROR: failed to program RMIDs via MSR access. RDT metrics will not be available.\n"; + /* 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 ++ ) + { + 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(); + coreRMIDs.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) @@ -735,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: @@ -778,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: @@ -1118,324 +1205,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); @@ -3549,8 +3331,6 @@ PCM::PCM() : initUncoreObjects(); - initRDT(); - readCPUMicrocodeLevel(); #ifdef PCM_USE_PERF @@ -5594,6 +5374,9 @@ void PCM::resetPMU() } void PCM::cleanupRDT(const bool silent) { + if (!RDTInitialized) { + return; + } if(!(QOSMetricAvailable() && L3QOSMetricAvailable())) { return; } @@ -5601,9 +5384,24 @@ void PCM::cleanupRDT(const bool silent) if (useResctrl) { resctrl.cleanup(); + useResctrl = false; + RDTInitialized = false; return; } #endif + if (MSR.empty() || noMSRMode()) + { + return; + } + + // 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 ++ ) { @@ -5629,6 +5427,10 @@ 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"; } @@ -5672,6 +5474,8 @@ void PCM::restoreOutput() void PCM::cleanup(const bool silent) { + cleanupRDT(silent); + if (MSR.empty()) return; if (!silent) std::cerr << "Cleaning up\n"; @@ -5681,7 +5485,6 @@ void PCM::cleanup(const bool silent) disableForceRTMAbortMode(silent); cleanupUncorePMUs(silent); - cleanupRDT(silent); #ifdef __linux__ if (needToRestoreNMIWatchdog) { @@ -6018,7 +5821,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; @@ -6047,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; @@ -8156,7 +7984,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; @@ -11557,9 +11385,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(); } @@ -11579,8 +11419,27 @@ CounterWidthExtender::CounterWidthExtender(AbstractRawCounter * raw_counter_, ui throw; // re-throw } } +void CounterWidthExtender::stopAndJoinUpdateThread() +{ + requestStopUpdateThread(); + 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"; + } + } +} + 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/cpucounters.h b/src/cpucounters.h index ac56a33d..552abb64 100644 --- a/src/cpucounters.h +++ b/src/cpucounters.h @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -863,6 +864,9 @@ class PCM_API PCM Resctrl resctrl; #endif 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; @@ -1227,16 +1231,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 - */ - 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) - */ void initQOSevent(const uint64 event, const int32 core); void programBecktonUncore(int core); void programNehalemEPUncore(int core); @@ -1352,6 +1346,102 @@ 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). + * 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 + */ + void initRDT(); + + //! \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 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. 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 && perfStatusMetricAvailable(); } + + //! \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 @@ -3250,6 +3340,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; @@ -3262,6 +3360,10 @@ class BasicCounterState MemoryBWLocal(0), MemoryBWTotal(0), SMICount(0), + PerfStatusRatioSum(0), + PerfStatusRatioCores(0), + PerfStatusVoltageSum(0), + PerfStatusVoltageCores(0), FrontendBoundSlots(0), BadSpeculationSlots(0), BackendBoundSlots(0), @@ -3297,6 +3399,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; @@ -3325,6 +3431,50 @@ 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 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() + */ + 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() @@ -3373,6 +3523,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 @@ -3798,6 +3966,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); @@ -4261,7 +4433,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; } @@ -5545,6 +5758,334 @@ 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 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) + { + const bool valid = i < beforeValidBits.size() && beforeValidBits[i] != 0 && + i < afterValidBits.size() && afterValidBits[i] != 0; + result.push_back(AETCounterValue{ values[i], valid }); + } + 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) { 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/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/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); } } 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; } 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); } diff --git a/src/pcm-sensor-server.cpp b/src/pcm-sensor-server.cpp index a17289f4..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 @@ -3779,12 +3892,21 @@ 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; #else - ssize_t bytes = ::recv( fd, &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() ); @@ -3796,9 +3918,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" ); @@ -4077,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 ); @@ -4095,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 ); @@ -4772,8 +4905,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..17e9e71e 100644 --- a/src/pcm.cpp +++ b/src/pcm.cpp @@ -54,6 +54,40 @@ 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 +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 +std::string ratio_format(const State & state) +{ + if (state.isPerfStatusRatioAvailable() == false) + return "N/A"; + + char buffer[1024]; + // no field width: the text output pads with setw(), the CSV output must not be padded + snprintf(buffer, 1024, "%.1f", state.getPerfStatusRatio()); + 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) +{ + if (state.isPerfStatusVoltageAvailable() == false) + return "N/A"; + + return volt_format(state.getPerfStatusVoltage()); +} + std::string l3cache_occ_format(uint64 o) { char buffer[1024]; @@ -70,6 +104,95 @@ 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; + } + 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) + { + continue; + } + const auto row = get_aet_row(m, core, before, after); + anyCore = true; + if (row.energy.valid) + { + result.energy.value += row.energy.value; + } + else + { + allEnergyValid = false; + } + if (row.cdyn.valid) + { + result.cdyn.value += row.cdyn.value; + } + 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; +} + +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 +214,20 @@ 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 << " -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 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" @@ -149,7 +286,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,7 +294,18 @@ 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); - cout << setNextColor() << " " << temp_format(state2.getThermalHeadroom()) << "\n"; + 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()); + 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, @@ -232,7 +380,24 @@ 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"; + 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 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"; @@ -280,8 +445,13 @@ 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"; + cout << setNextColor() << " TEMP"; + if (perf_status_metrics) + cout << " |" << setNextColor() << " RATIO |" << setNextColor() << " VOLT"; + cout << "\n\n"; cout << resetColor(); @@ -300,7 +470,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 +492,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 +507,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,8 +530,20 @@ 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 << 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)) << " ;" @@ -582,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 << "|" ; @@ -640,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) { - cout << setNextColor() << " " << std::setw(4) << d/1e9 << " "; + 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 + { + for (auto & d: uncoreFrequencies) + { + cout << setNextColor() << " " << std::setw(4) << d/1e9 << " "; + } } } cout << resetColor() << "\n"; @@ -774,6 +977,12 @@ 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 + + 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()) @@ -814,6 +1023,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()) @@ -824,6 +1035,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%, } @@ -851,8 +1064,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); + } } } @@ -902,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); + } } } } @@ -925,7 +1148,11 @@ 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 + 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% } } @@ -947,11 +1174,15 @@ 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)) 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%, } } @@ -975,6 +1206,12 @@ void print_csv_header(PCM * m, if (m->HBMmemoryTrafficMetricsAvailable()) cout << "HBM_READ,HBM_WRITE,"; + 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()) @@ -1020,6 +1257,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()) @@ -1030,7 +1269,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 @@ -1055,6 +1297,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 << ","; } @@ -1104,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)); } } @@ -1127,7 +1371,11 @@ void print_csv_header(PCM * m, cout << "LMB,"; if (m->CoreRemoteMemoryBWMetricAvailable()) cout << "RMB,"; + 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%,"; } } @@ -1146,12 +1394,16 @@ 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)) cout << "C" << s << "res%,"; cout << "TEMP,"; + if (perf_status_metrics) + cout << "RATIO,VOLT,"; cout << "INST,ACYC,TIME(ticks),PhysIPC,PhysIPC%,INSTnom,INSTnom%,"; } } @@ -1203,7 +1455,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 +1463,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 +1504,15 @@ 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) << ','; + } + + 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])) << "," @@ -1293,7 +1556,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); @@ -1311,6 +1575,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])) << "," @@ -1346,8 +1612,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)) << "%,"; + } } } @@ -1391,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) + { + 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 { - cout << f/1e9 << ","; + for (auto & f : freqs) + { + cout << f/1e9 << ","; + } } } } @@ -1414,8 +1695,12 @@ 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()) << ','; + 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])) << "," @@ -1435,7 +1720,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) @@ -1443,6 +1728,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])) << "," @@ -1455,6 +1742,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; @@ -1506,6 +1842,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++; @@ -1581,6 +1919,21 @@ 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, {"--perf-status", "-ps", "/ps"})) + { + 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(); @@ -1700,6 +2053,17 @@ int mainThrows(int argc, char * argv[]) exit(EXIT_FAILURE); } + program_aet(m); + + 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(); std::vector cstates1, cstates2; @@ -1727,6 +2091,29 @@ int mainThrows(int argc, char * argv[]) m->getAllCounterStates(sstate1, sktstate1, cstates1); + 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(); + 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 (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); } 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 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/types.h b/src/types.h index 6fb1f296..94128b32 100644 --- a/src/types.h +++ b/src/types.h @@ -1476,6 +1476,32 @@ 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 + +// 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; diff --git a/src/width_extender.h b/src/width_extender.h index abcfc929..060564d3 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; @@ -202,6 +204,18 @@ 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 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 { diff --git a/tests/pcm-sensor-server-fuzz.cpp b/tests/pcm-sensor-server-fuzz.cpp index 9efa027c..2c81e668 100644 --- a/tests/pcm-sensor-server-fuzz.cpp +++ b/tests/pcm-sensor-server-fuzz.cpp @@ -7,6 +7,9 @@ #include #include #include +#include +#include +#include #define UNIT_TEST 1 @@ -17,18 +20,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; @@ -37,18 +32,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; } @@ -57,8 +62,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 +86,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 ); @@ -142,7 +153,45 @@ 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; + // 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 { + 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) { + 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 @@ -155,7 +204,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);