In this lesson, you will learn how to interface with hardware-level Performance Monitoring Units (PMUs) using the perf subsystem to extract low-level CPU telemetry.
The PMU and the Kernel
At the heart of modern CPU performance analysis is the PMU—a specialized hardware component that counts microarchitectural events, such as cache misses, branch mispredictions, or retired instructions. The perf subsystem acts as the kernel-side arbiter between this hardware and your userspace tools.
When you request telemetry, the kernel maps these hardware events to "virtualized" counters. Because hardware registers are finite, the kernel performs multiplexing: it time-slices the counters so that you can monitor more events than the CPU physically supports simultaneously.
Configuring Hardware Counters
To extract telemetry, you define a perf_event_attr structure (if writing a driver) or use the perf command-line utility. The kernel exposes these via the perf_event_open system call, which links the requested event to the specific CPU core's PMU.
Consider the task of measuring L1 cache misses. You don't interact with the hardware registers directly; instead, you ask the kernel to track a specific PERF_TYPE_HARDWARE event:
# Capture L1 cache misses on the current CPU
perf stat -e L1-dcache-load-misses -p <PID> sleep 5
When you run this command, perf communicates with the kernel to:
- Initialize: Verify that the PMU supports the specific hardware event.
- Program: Write to the CPU’s control registers (MSRs) to start counting.
- Aggregate: Periodically drain the counter values into a ring buffer shared between kernel and userspace (via
mmap), minimizing the overhead of context switching.
Interpreting Telemetry
Because the PMU captures hardware state, the data is incredibly precise but context-heavy. If your telemetry shows high "stalled-cycles-backend," the perf subsystem is telling you that the CPU execution units are waiting on memory subsystems, not that your code is logically inefficient. By understanding this architecture, you move beyond mere "process tracing" and into the realm of hardware-level cycle accounting.
Key Takeaway: The perf subsystem bridges the gap between opaque hardware registers and actionable observability by managing PMU multiplexing and providing a low-overhead ring buffer for high-fidelity telemetry extraction.