RISC-V: Add macros for reading performance counter CSRs.

The RISC-V spec defines several performance counter CSRs such as: cycle,
time, instret, hpmcounter(3...31).  They are defined to be 64-bits wide
on all RISC-V architectures.  On RV64 and RV128 they can be read from a
single CSR.  On RV32, additional CSRs (given the suffix "h") are present
which contain the upper 32 bits of these counters, and must be read as
well.  (See section 2.8 in the User ISA Spec for full details.)

This change adds macros for reading these values safely on any RISC-V
ISA length.  Obviously we aren't supporting anything other than RV64
at the moment, but this ensures we won't need to change how we read
these values if we ever do.

Submitted by:	Mitchell Horne <mhorne063@gmail.com>
Reviewed by:	jhb
MFC after:	2 weeks
Differential Revision:	https://reviews.freebsd.org/D17952
This commit is contained in:
Mark Johnston 2018-11-13 18:12:06 +00:00
parent b7305f91e4
commit 1e2ceeb16a
2 changed files with 24 additions and 0 deletions

View File

@ -104,6 +104,11 @@ sfence_vma_page(uintptr_t addr)
__asm __volatile("sfence.vma %0" :: "r" (addr) : "memory");
}
#define rdcycle() csr_read64(cycle)
#define rdtime() csr_read64(time)
#define rdinstret() csr_read64(instret)
#define rdhpmcounter(n) csr_read64(hpmcounter##n)
#define cpufunc_nullop() riscv_nullop()
void riscv_nullop(void);

View File

@ -223,4 +223,23 @@
val; \
})
#if __riscv_xlen == 32
#define csr_read64(csr) \
({ uint64_t val; \
uint32_t high, low; \
__asm __volatile("1: " \
"csrr t0, " #csr "h\n" \
"csrr %0, " #csr "\n" \
"csrr %1, " #csr "h\n" \
"bne t0, %1, 1b" \
: "=r" (low), "=r" (high) \
: \
: "t0"); \
val = (low | ((uint64_t)high << 32)); \
val; \
})
#else
#define csr_read64(csr) ((uint64_t)csr_read(csr))
#endif
#endif /* !_MACHINE_RISCVREG_H_ */