[[ext:zihpm]]
=== ext:zihpm[] Extension for Hardware Performance Counters

[#norm:hpmcounter_op_sz_mode]#The ext:zihpm[] extension comprises up to 29 additional unprivileged 64-bit
hardware performance counters, csr:hpmcounter3[]-csr:hpmcounter31[].# [#norm:hpm_counter_op_sz_mode_xlen32]#When
XLEN=32, the upper 32 bits of these performance counters are accessible
via additional CSRs csr:hpmcounter3h[]-csr:hpmcounter31h[].# [#norm:hpm_counter_op_sz_mode_dependency]#The ext:zihpm[] extension
depends on the ext:zicsr[] extension.#
[NOTE]
====
In some applications, it is important to be able to read multiple
counters at the same instant in time. When run under a multitasking
environment, a user thread can suffer a context switch while attempting
to read the counters. One solution is for the user thread to read the
real-time counter before and after reading the other counters to
determine if a context switch occurred in the middle of the sequence, in
which case the reads can be retried. We considered adding output latches
to allow a user thread to snapshot the counter values atomically, but
this would increase the size of the user context, especially for
implementations with a richer set of counters.
====

[#norm:hpm_platform_specific_impl]#The implemented number and width of these additional counters, and the
set of events they count, are platform-specific.# [#norm:hpm_unimplemented_counter_access]#Accessing an
unimplemented counter may cause an illegal-instruction exception or may
return a constant value.# [#norm:hpm_misconfigured_event_behavior]#If the configuration used to select the events
counted by a counter is misconfigured, the counter may return a constant
value.#

The execution environment should provide a means to determine the number
and width of the implemented counters, and an interface to configure the
events to be counted by each counter.
[NOTE]
====
For execution environments implemented on RISC-V privileged platforms,
the privileged architecture manual describes privileged CSRs controlling
access by lower privileged modes to these counters, and to set the
events to be counted.

Alternative execution environments (e.g., user-level-only software
performance models) may provide alternative mechanisms to configure the
events counted by the performance counters.

It would be useful to eventually standardize event settings to count
ISA-level metrics, such as the number of floating-point instructions
executed for example, and possibly a few common microarchitectural
metrics, such as "`L1 instruction cache misses`".
====
