HWPMC(4)
π HWPMC(4) β Hardware Performance Monitoring Counter support π
Kernel Interfaces Manual Β· manual name: hwpmc(4) Β· bestie edition π
πΈ NAME πΈ
hwpmc β Hardware Performance Monitoring Counter support
β¨ SYNOPSIS β¨
Bestie, this option must be present in your kernel configuration file:
options HWPMC_HOOKS
Also, for i386 systems, add this too:
device apic
To load the driver as a module at boot time, drop this in:
sysrc kld_list+=hwpmc
Or, alternatively, compile the driver into the kernel with:
device hwpmc
Wanna turn on debugging features? Peep DEBUGGING:
options KTR
options KTR_COMPILE=(KTR_SUBSYS)
options KTR_MASK=(KTR_SUBSYS)
options HWPMC_DEBUG
π DESCRIPTION π
Okay so the hwpmc driver virtualizes the hardware performance monitoring facilities inside modern CPUs and gives user-level processes support for using them. And yes, it supports multi-processor systems. π
PMCs are allocated using the PMC_OP_PMCALLOCATE request. A successful PMC_OP_PMCALLOCATE request returns a handle to the requesting process. Every later operation on that allocated PMC uses this handle to denote the specific PMC. A process that has successfully allocated a PMC is called an βowner process.β π
PMCs may be allocated with process scope or system scope:
- Process-scope β The PMC is active only when a thread belonging to a process it is attached to is scheduled on a CPU.
- System-scope β The PMC operates independently of processes and measures hardware events for the system as a whole.
PMCs may be allocated for counting or for sampling:
- Counting β In counting modes, the PMCs count hardware events. These counts are retrievable using the
PMC_OP_PMCREADsystem call on all architectures. Some architectures offer faster methods of reading these counts. - Sampling β In sampling modes, the PMCs are configured to sample the CPU instruction pointer (and optionally to capture the call chain leading up to the sampled instruction pointer) after a configurable number of hardware events have been observed. Instruction pointer samples and call chain records are usually directed to a log file for subsequent analysis.
Scope and operational mode are orthogonal, so a PMC may thus be configured to operate in one of the following four modes:
- Process-scope, counting β These PMCs count hardware events whenever a thread in their attached process is scheduled on a CPU. These PMCs normally count from zero, but the initial count may be set using the
PMC_OP_SETCOUNToperation. Applications can read the value of the PMC anytime using thePMC_OP_PMCRWoperation. - Process-scope, sampling β These PMCs sample the target processβs instruction pointer after they have seen the configured number of hardware events. The PMCs only count events when a thread belonging to their attached process is active. The desired frequency of sampling is set using the
PMC_OP_SETCOUNToperation prior to starting the PMC. Log files are configured using thePMC_OP_CONFIGURELOGoperation. - System-scope, counting β These PMCs count hardware events seen by them independent of the processes that are executing. The current count on these PMCs can be read using the
PMC_OP_PMCRWrequest. These PMCs normally count from zero, but the initial count may be set using thePMC_OP_SETCOUNToperation. - System-scope, sampling β These PMCs will periodically sample the instruction pointer of the CPU they are allocated on, and will write the sample to a log for further processing. The desired frequency of sampling is set using the
PMC_OP_SETCOUNToperation prior to starting the PMC. Log files are configured using thePMC_OP_CONFIGURELOGoperation.
System-wide statistical sampling can only be enabled by a process with super-user privileges. π«Ά
Processes are allowed to allocate as many PMCs as the hardware and current operating conditions permit. Processes may mix allocations of system-wide and process-private PMCs. Multiple processes may be using PMCs simultaneously. Iconic.
Allocated PMCs are started using the PMC_OP_PMCSTART operation, and stopped using the PMC_OP_PMCSTOP operation. Stopping and starting a PMC is permitted at any time the owner process has a valid handle to the PMC.
Process-private PMCs need to be attached to a target process before they can be used. Attaching a process to a PMC is done using the PMC_OP_PMCATTACH operation. An already attached PMC may be detached from its target process using the converse PMC_OP_PMCDETACH operation. Issuing a PMC_OP_PMCSTART operation on an as yet unattached PMC will cause it to be attached to its owner process. The following rules determine whether a given process may attach a PMC to another target process:
- A non-jailed process with super-user privileges is allowed to attach to any other process in the system.
- Other processes are only allowed to attach to targets that they would be able to attach to for debugging (as determined by
p_candebug(9)).
PMCs are released using PMC_OP_PMCRELEASE. After a successful PMC_OP_PMCRELEASE operation the handle to the PMC will become invalid. β¨
π Modifier Flags π
The PMC_OP_PMCALLOCATE operation supports the following flags that modify the behavior of an allocated PMC:
PMC_F_CALLCHAINβ This modifier informs sampling PMCs to record a callchain when capturing a sample. The maximum depth to which call chains are recorded is specified by thekern.hwpmc.callchaindepthkernel tunable.PMC_F_DESCENDANTSβ This modifier is valid only for a PMC being allocated in process-private mode. It signifies that the PMC will track hardware events for its target process and the targetβs current and future descendants.PMC_F_LOG_PROCCSWβ This modifier is valid only for a PMC being allocated in process-private mode. When this modifier is present, at every context switch,hwpmcwill log a record containing the number of hardware events seen by the target process when it was scheduled on the CPU.PMC_F_LOG_PROCEXITβ This modifier is valid only for a PMC being allocated in process-private mode. With this modifier present,hwpmcwill maintain per-process counts for each target process attached to a PMC. At process exit time, a record containing the target processβ PID and the accumulated per-process count for that process will be written to the configured log file.
Modifiers PMC_F_LOG_PROCEXIT and PMC_F_LOG_PROCCSW may be used in combination with modifier PMC_F_DESCENDANTS to track the behavior of complex pipelines of processes. PMCs with modifiers PMC_F_LOG_PROCEXIT and PMC_F_LOG_PROCCSW cannot be started until their owner process has configured a log file. π¦
π Signals π
The hwpmc driver may deliver signals to processes that have allocated PMCs:
SIGIOβ APMC_OP_PMCRWoperation was attempted on a process-private PMC that does not have attached target processes.SIGBUSβ Thehwpmcdriver is being unloaded from the kernel.
π PMC ROW DISPOSITIONS π
A PMC row is defined as the set of PMC resources at the same hardware address in the CPUs in a system. Since process scope PMCs need to move between CPUs following their target threads, allocation of a process scope PMC reserves all PMCs in a PMC row for use only with process scope PMCs. Accordingly a PMC row will be in one of the following dispositions:
PMC_DISP_FREEβ Hardware counters in this row are free and may be used to satisfy either of system scope or process scope allocation requests.PMC_DISP_THREADβ Hardware counters in this row are in use by process scope PMCs and are only available for process scope allocation requests.PMC_DISP_STANDALONEβ Some hardware counters in this row have been administratively disabled or are in use by system scope PMCs. Non-disabled hardware counters in such a row may be used for satisfying system scope allocation requests. No process scope PMCs will use hardware counters in this row.
β COMPATIBILITY β
Heads up, bestie: the API and ABI documented in this manual page may change in the future. This interface is intended to be consumed by the pmc(3) library; other consumers are unsupported. Applications targeting PMCs should use the pmc(3) library API. π«Ά
π» PROGRAMMING API π»
okay so bestie, the hwpmc driver operates using a system call number that is dynamically allotted to it when it is loaded into the kernel.
The hwpmc driver supports the following operations:
PMC_OP_CONFIGURELOGβ Configure a log file for PMCs that require a log file. Thehwpmcdriver will write log data to this file asynchronously. If it encounters an error, logging will be stopped and the error code encountered will be saved for subsequent retrieval by aPMC_OP_FLUSHLOGrequest.PMC_OP_FLUSHLOGβ Transfer buffered log data insidehwpmcto a configured output file. This operation returns to the caller after the write operation has returned. The returned error code reflects any pending error state insidehwpmc.PMC_OP_GETCPUINFOβ Retrieve information about the highest possible CPU number for the system, and the number of hardware performance monitoring counters available per CPU.PMC_OP_GETDRIVERSTATSβ Retrieve module statistics (for analyzing the behavior ofhwpmcitself).PMC_OP_GETMODULEVERSIONβ Retrieve the version number of API.PMC_OP_GETPMCINFOβ Retrieve information about the current state of the PMCs on a given CPU.PMC_OP_PMCADMINβ Set the administrative state (i.e., whether enabled or disabled) for the hardware PMCs managed by thehwpmcdriver. The invoking process needs to possess thePRIV_PMC_MANAGEprivilege.PMC_OP_PMCALLOCATEβ Allocate and configure a PMC. On successful allocation, a handle to the PMC (a 32 bit value) is returned.PMC_OP_PMCATTACHβ Attach a process mode PMC to a target process. The PMC will be active whenever a thread in the target process is scheduled on a CPU.
If the PMC_F_DESCENDANTS flag had been specified at PMC allocation time, then the PMC is attached to all current and future descendants of the target process.
PMC_OP_PMCDETACHβ Detach a PMC from its target process.PMC_OP_PMCRELEASEβ Release a PMC.PMC_OP_PMCRWβ Read and write a PMC. This operation is valid only for PMCs configured in counting modes.PMC_OP_SETCOUNTβ Set the initial count (for counting mode PMCs) or the desired sampling rate (for sampling mode PMCs).PMC_OP_PMCSTARTβ Start a PMC.PMC_OP_PMCSTOPβ Stop a PMC.PMC_OP_WRITELOGβ Insert a timestamped user record into the log file.
π i386 Specific API π
Some i386 family CPUs support the RDPMC instruction which allows a user process to read a PMC value without needing to invoke a PMC_OP_PMCRW operation. On such CPUs, the machine address associated with an allocated PMC is retrievable using the PMC_OP_PMCX86GETMSR system call.
PMC_OP_PMCX86GETMSRβ Retrieve the MSR (machine specific register) number associated with the given PMC handle.
The PMC needs to be in process-private mode and allocated without the PMC_F_DESCENDANTS modifier flag, and should be attached only to its owner process at the time of the call.
π amd64 Specific API π
AMD64 CPUs support the RDPMC instruction which allows a user process to read a PMC value without needing to invoke a PMC_OP_PMCRW operation. The machine address associated with an allocated PMC is retrievable using the PMC_OP_PMCX86GETMSR system call.
PMC_OP_PMCX86GETMSRβ Retrieve the MSR (machine specific register) number associated with the given PMC handle.
The PMC needs to be in process-private mode and allocated without the PMC_F_DESCENDANTS modifier flag, and should be attached only to its owner process at the time of the call.
πΈ SYSCTL VARIABLES AND LOADER TUNABLES πΈ
The behavior of hwpmc is influenced by the following sysctl(8) and loader(8) tunables:
kern.hwpmc.callchaindepth(integer, read-only) β The maximum number of call chain records to capture per sample. The default is8.kern.hwpmc.debugflags(string, read-write) β (Only available if thehwpmcdriver was compiled with-DDEBUG.) Control the verbosity of debug messages from thehwpmcdriver.kern.hwpmc.hashsize(integer, read-only) β The number of rows in the hash tables used to keep track of owner and target processes. The default is16.kern.hwpmc.logbuffersize(integer, read-only) β The size in kilobytes of each log buffer used byhwpmc's logging function. The default buffer size is256KB. The maximum value is16MB.kern.hwpmc.mincount(integer, read-write) β The minimum sampling rate for sampling mode PMCs. The default count is1000events.kern.hwpmc.mtxpoolsize(integer, read-only) β The size of the spin mutex pool used by the PMC driver. The default is32.kern.hwpmc.nbuffers_pcpu(integer, read-only) β The number of log buffers per CPU used byhwpmcfor logging. The default is32. The product ofkern.hwpmc.nbuffers_pcpuandkern.hwpmc.logbuffersizemust not exceed32MBper CPU.kern.hwpmc.nsamples(integer, read-only) β The number of entries in the per-CPU ring buffer used during sampling. The default is512.security.bsd.unprivileged_syspmcs(boolean, read-write) β If set to non-zero, allow unprivileged processes to allocate system-wide PMCs. The default value is0.security.bsd.unprivileged_proc_debug(boolean, read-write) β If set to0, thehwpmcdriver will only allow privileged processes to attach PMCs to other processes.
These variables may be set in the kernel environment using kenv(1) before hwpmc is loaded.
π§ IMPLEMENTATION NOTES π§
π§© SMP Symmetry π§©
The kernel driver requires all physical CPUs in an SMP system to have identical performance monitoring counter hardware.
π§© Sparse CPU Numbering π§©
On platforms that sparsely number CPUs and which support hot-plugging of CPUs, requests that specify non-existent or disabled CPUs will fail with an error. Applications allocating system-scope PMCs need to be aware of the possibility of such transient failures.
π§© x86 TSC Handling π§©
Historically, on the x86 architecture, FreeBSD has permitted user processes running at a processor CPL of 3 to read the TSC using the RDTSC instruction. The hwpmc driver preserves this behavior.
π§© Intel P4/HTT Handling π§©
On CPUs with HTT support, Intel P4 PMCs are capable of qualifying only a subset of hardware events on a per-logical CPU basis. Consequently, if HTT is enabled on a system with Intel Pentium P4 PMCs, then the hwpmc driver will reject allocation requests for process-private PMCs that request counting of hardware events that cannot be counted separately for each logical CPU.
π¨ DIAGNOSTICS π¨
hwpmc: [class/npmc/capabilities]...β Announce the presence ofnpmcPMCs of class class, with capabilities described by bit string capabilities.hwpmc: kernel version (0x%x) does not match module version (0x%x).β The module loading process failed because a version mismatch was detected between the currently executing kernel and the module being loaded.hwpmc: this kernel has not been compiled with 'options HWPMC_HOOKS'.β The module loading process failed because the currently executing kernel was not configured with the required configuration optionHWPMC_HOOKS.hwpmc: tunable hashsize=%d must be greater than zero.β A negative value was supplied for tunablekern.hwpmc.hashsize.hwpmc: logbuffersize=%d must be greater than zero and less than or equal to %d, resetting to %d.β A negative value was supplied for tunablekern.hwpmc.logbuffersize.hwpmc: nbuffers_pcpu=%d must be greater than zero, resetting to %d.β A negative value was supplied for tunablekern.hwpmc.nbuffers_pcpu.hwpmc: tunable nsamples=%d out of range.β The value for tunablekern.hwpmc.nsampleswas negative or greater than65535.hwpmc: nbuffers_pcpu=%d * logbuffersize=%d exceeds %dMB per CPU limit, resetting to defaults (%d * %d).β The product of tunableskern.hwpmc.nbuffers_pcpuandkern.hwpmc.logbuffersizeexceeds the maximum per-CPU memory limit. Both tunables are reset to their compiled defaults.
π DEBUGGING π
The hwpmc module can be configured to record trace entries using the ktr(4) interface. This is useful for debugging the driver's functionality, primarily during development. This debugging functionality is not enabled by default, and requires recompiling the kernel and hwpmc module after adding the following to the kernel config:
options KTR
options KTR_COMPILE=(KTR_SUBSYS)
options KTR_MASK=(KTR_SUBSYS)
options HWPMC_DEBUG
This alone is not enough to enable tracing; one must also configure the kern.hwpmc.debugflags sysctl(8) variable, which provides fine-grained control over which types of events are logged to the trace buffer.
hwpmc trace events are grouped by 'major' and 'minor' flag types. The major flag names are as follows:
cpuβ CPU eventscswβ Context switch eventsloggingβ Logging eventsmdβ Machine-dependent/class-dependent eventsmoduleβ Miscellaneous eventsownerβ PMC owner eventspmcβ PMC management eventsprocessβ Process eventssamplingβ Sampling events
The minor flags for each major flag group can vary. The individual minor flag names are:
allocaterow, allocate, attach, bind, config, exec, exit, find,
flush, fork, getbuf, hook, init, intr, linktarget, mayberemove,
ops, read, register, release, remove, sample, scheduleio, select,
signal, swi, swo, start, stop, syscall, unlinktarget, write
The kern.hwpmc.debugflags variable is a string with a custom format. The string should contain a space-separated list of event specifiers. Each event specifier consists of the major flag name, followed by an equal sign (=), followed by a comma-separated list of minor event types. To track all events for a major group, an asterisk (*) can be given instead of minor event names.
For example, to trace all allocation and release events, set debugflags as follows:
kern.hwpmc.debugflags="pmc=allocate,release md=allocate,release"
To trace all events in the process and context switch major flag groups:
kern.hwpmc.debugflags="process=* csw=*"
To disable all trace events, set the variable to an empty string.
kern.hwpmc.debugflags=""
Trace events are recorded by ktr(4), and can be inspected at run-time using the ktrdump(8) utility, or at the ddb(4) prompt after a panic with the 'show ktr' command.
π₯ ERRORS π₯
Okay so when you send a command to the hwpmc driver, it can absolutely fail with any of these errors β here's the full rundown, no skips:
[EAGAIN]β The helper process creation failed for aPMC_OP_CONFIGURELOGrequest because the kernel hit a temporary resource shortage. π[EBUSY]β APMC_OP_CONFIGURELOGoperation was requested while an existing log was already active.[EBUSY]β ADISABLEoperation was requested using thePMC_OP_PMCADMINrequest for a set of hardware resources currently in use for process-private PMCs.[EBUSY]β APMC_OP_PMCADMINoperation was requested on an active system mode PMC.[EBUSY]β APMC_OP_PMCATTACHoperation was requested for a target process that already had another PMC using the same hardware resources attached to it.[EBUSY]β APMC_OP_PMCRWrequest writing a new value was issued on a PMC that was active.[EBUSY]β APMC_OP_PMCSETCOUNTrequest was issued on a PMC that was active.[EDOOFUS]β Yes bestie, that is literally the name. APMC_OP_PMCSTARToperation was requested without a log file being configured for a PMC allocated withPMC_F_LOG_PROCCSWandPMC_F_LOG_PROCEXITmodifiers. π[EDOOFUS]β APMC_OP_PMCSTARToperation was requested on a system-wide sampling PMC without a log file being configured.[EEXIST]β APMC_OP_PMCATTACHrequest was reissued for a target process that already is the target of this PMC.[EFAULT]β A bad address was passed in to the driver.[EINVAL]β An invalid PMC handle was specified.[EINVAL]β An invalid CPU number was passed in for aPMC_OP_GETPMCINFOoperation.[EINVAL]β Thepm_flagsargument to aPMC_OP_CONFIGURELOGrequest contained unknown flags.[EINVAL]β APMC_OP_CONFIGURELOGrequest to de-configure a log file was issued without a log file being configured.[EINVAL]β APMC_OP_FLUSHLOGrequest was issued without a log file being configured.[EINVAL]β An invalid CPU number was passed in for aPMC_OP_PMCADMINoperation.[EINVAL]β An invalid operation request was passed in for aPMC_OP_PMCADMINoperation.[EINVAL]β An invalid PMC ID was passed in for aPMC_OP_PMCADMINoperation.[EINVAL]β A suitable PMC matching the parameters passed in to aPMC_OP_PMCALLOCATErequest could not be allocated.[EINVAL]β An invalid PMC mode was requested during aPMC_OP_PMCALLOCATErequest.[EINVAL]β An invalid CPU number was specified during aPMC_OP_PMCALLOCATErequest.[EINVAL]β A CPU other thanPMC_CPU_ANYwas specified in aPMC_OP_PMCALLOCATErequest for a process-private PMC.[EINVAL]β A CPU number ofPMC_CPU_ANYwas specified in aPMC_OP_PMCALLOCATErequest for a system-wide PMC.[EINVAL]β Thepm_flagsargument to anPMC_OP_PMCALLOCATErequest contained unknown flags.[EINVAL]β (On Intel Pentium 4 CPUs with HTT support) APMC_OP_PMCALLOCATErequest for a process-private PMC was issued for an event that does not support counting on a per-logical CPU basis.[EINVAL]β A PMC allocated for system-wide operation was specified with aPMC_OP_PMCATTACHorPMC_OP_PMCDETACHrequest.[EINVAL]β Thepm_pidargument to aPMC_OP_PMCATTACHorPMC_OP_PMCDETACHrequest specified an illegal process ID.[EINVAL]β APMC_OP_PMCDETACHrequest was issued for a PMC not attached to the target process.[EINVAL]β Argumentpm_flagsto aPMC_OP_PMCRWrequest contained illegal flags.[EINVAL]β APMC_OP_PMCX86GETMSRoperation was requested for a PMC not in process-virtual mode, or for a PMC that is not solely attached to its owner process, or for a PMC that was allocated with flagPMC_F_DESCENDANTS.[EINVAL]β APMC_OP_WRITELOGrequest was issued for an owner process without a log file configured.[ENOMEM]β The system was not able to allocate kernel memory.[ENOSYS]β (On i386 and amd64 architectures) APMC_OP_PMCX86GETMSRoperation was requested for hardware that does not support reading PMCs directly with theRDPMCinstruction.[ENXIO]β APMC_OP_GETPMCINFOoperation was requested for an absent or disabled CPU.[ENXIO]β APMC_OP_PMCALLOCATEoperation specified allocation of a system-wide PMC on an absent or disabled CPU.[ENXIO]β APMC_OP_PMCSTARTorPMC_OP_PMCSTOPrequest was issued for a system-wide PMC that was allocated on a CPU that is currently absent or disabled.[EOPNOTSUPP]β APMC_OP_PMCALLOCATErequest was issued for PMC capabilities not supported by the specified PMC class.[EOPNOTSUPP]β (i386 architectures) A sampling mode PMC was requested on a CPU lacking an APIC.[EPERM]β APMC_OP_PMCADMINrequest was issued by a process without super-user privilege or by a jailed super-user process.[EPERM]β APMC_OP_PMCATTACHoperation was issued for a target process that the current process does not have permission to attach to.[EPERM]β (i386 and amd64 architectures) APMC_OP_PMCATTACHoperation was issued on a PMC whose MSR has been retrieved usingPMC_OP_PMCX86GETMSR.[ESRCH]β A process issued a PMC operation request without having allocated any PMCs.[ESRCH]β A process issued a PMC operation request after the PMC was detached from all of its target processes.[ESRCH]β APMC_OP_PMCATTACHorPMC_OP_PMCDETACHrequest specified a non-existent process ID.[ESRCH]β The target process for aPMC_OP_PMCDETACHoperation is not being monitored byhwpmc.
π SEE ALSO π
Go read these next, bestie β they're all part of the lore:
kenv(1)pmc(3)pmclog(3)ddb(4)ktr(4)kldload(8)ktrdump(8)pmccontrol(8)pmcstat(8)sysctl(8)kproc_create(9)p_candebug(9)
πΈ HISTORY πΈ
The hwpmc driver first appeared in FreeBSD 6.0. Iconic debut behavior, honestly. β¨
π AUTHORS π
The hwpmc driver was written by Joseph Koshy jkoshy@FreeBSD.org. We stan a legend. π«Ά
π BUGS π
The driver samples the state of the kernel's logical processor support at the time of initialization (i.e., at module load time). On CPUs supporting logical processors, the driver could misbehave if logical processors are subsequently enabled or disabled while the driver is active. So yeah β that's a real one, be aware. π
On the i386 architecture, the driver requires that the local APIC on the CPU be enabled for sampling mode to be supported. Many single-processor motherboards keep the APIC disabled in BIOS; on such systems hwpmc will not support sampling PMCs. Not a vibe, but it's the facts.
π SECURITY CONSIDERATIONS π
PMCs may be used to monitor the actual behavior of the system on hardware. In situations where this constitutes an undesirable information leak, the following options are available:
- Set the
sysctl(8)tunablesecurity.bsd.unprivileged_syspmcsto0. This ensures that unprivileged processes cannot allocate system-wide PMCs and thus cannot observe the hardware behavior of the system as a whole. This tunable may also be set at boot time usingloader(8), or withkenv(1)prior to loading thehwpmcdriver into the kernel. - Set the
sysctl(8)tunablesecurity.bsd.unprivileged_proc_debugto0. This will ensure that an unprivileged process cannot attach a PMC to any process other than itself and thus cannot observe the hardware behavior of other processes with the same credentials.
System administrators should note that on IA-32 platforms FreeBSD makes the content of the IA-32 TSC counter available to all processes via the RDTSC instruction.
π That's the whole page, bestie! This edition is the Debian source/version, dated July 8, 2023, for HWPMC(4) β and yes, it ate. π
β¨
π¦ where this page comes from
- freebsd 15.1: base 15.1
- Copyright (c) 2003-2008 Joseph Koshy
- Copyright (c) 2007,2023 The FreeBSD Foundation
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms