Skip to contentSkip to conversation

More extendable PMU subsystem.

RFC PATCH In review Aleksandr Sergeev 2 participants 8 messages Dec 18, 2025 – Dec 19, 2025

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover More extendable PMU subsystem.

Currently, the pmu implementation consists of two parts:
the first part is mcycle & minstret registers (let's call them "builtin events") and the second part is mhpmcounters.

The builtin events are supported well, including implementation of inhibiting, filtering, etc.

But the implementation of mhpmcounters has few problems:
1. Non-builtin events are vendor-specific.
The vendor, who wants to implement them (including filtering, interrupts, etc), has to write exactly the same code
as which is already written for mcycle & minstret events.
2. To implement custom events vendor must
hardcode it right inside the general methods.
So if there are two different vendors with
their own events, they would write their code
right beside each other, making the code
harder to support.
Also some collisions may occur in event indexes,
as it is a global enum.
3. SBI events hardcoded right inside the general code.
As they are not a part of RISCV specification,
it should be up to vendor to implement them or not.

To solve these problems, let's:
1. Generalize code, handling builtin events & mhpmcounters the same way. So if some vendors want to get logic of builtin events, it would take minimum affort.
2. Add special callbacks for custom events. So when vendors want custom events for their machine, they would not have to change the common code.
3. SBI events are now implemented for virt machine only as a demo of how a new pmu subsystem works.

Aleksandr Sergeev (6):
target/riscv: Refactor counter index calculation. target/riscv: Reimplement Smcdeleg/Ssccfg via read_*, write_* methods target/riscv: Get rid of hardcoded SBI events. target/riscv: Rearrange custom hpm counter api target/riscv: Add PMU events implementation for virt target/riscv/machine: Add smcntrpmf registers to VMStateDescription

 hw/misc/Kconfig            |   3 +
 hw/misc/meson.build        |   1 +
 hw/misc/virt_pmu.c         | 142 ++++++++
 hw/riscv/Kconfig           |   1 +
 hw/riscv/virt.c            |   4 +-
 include/hw/misc/virt_pmu.h |  91 +++++
 target/riscv/cpu.c         |   8 +
 target/riscv/cpu.h         |  96 +++--
 target/riscv/cpu_bits.h    |   4 +
 target/riscv/cpu_helper.c  |  34 +-
 target/riscv/csr.c         | 470 ++++++++----------------
 target/riscv/machine.c     |  11 +-
 target/riscv/pmu.c         | 708 ++++++++++++++-----------------------
 target/riscv/pmu.h         |  26 +-
 14 files changed, 769 insertions(+), 830 deletions(-)
 create mode 100644 hw/misc/virt_pmu.c
 create mode 100644 include/hw/misc/virt_pmu.h
Signature · 1 line
2.51.0
#1 lore raw

RFC PATCH 1/6 target/riscv: Refactor counter index calculation.

When working with hpm registers, we need to calculate counter index by csr number. By now it was done manually. Let's add a function -- riscv_pmu_csrno_to_ctr_idx(), which incapsulates this action.

---
 target/riscv/cpu_bits.h |  4 +++
 target/riscv/csr.c      | 73 ++++++++++++++---------------------------
 target/riscv/pmu.c      | 44 +++++++++++++++++++++++++
 target/riscv/pmu.h      |  1 +
 4 files changed, 73 insertions(+), 49 deletions(-)
target/riscv/cpu_bits.h +4 -0
index b62dd82fe7..5c3c1af64e 100644
@@ -1145,6 +1145,10 @@ typedef enum CTRType {
 /* RISC-V-specific interrupt pending bits. */
 #define CPU_INTERRUPT_RNMI                 CPU_INTERRUPT_TGT_EXT_0
 
+#define HPM_MCYCLE_IDX                     0
+#define HPM_MTIME_IDX                      1
+#define HPM_MINSTRET_IDX                   2
+
 /* JVT CSR bits */
 #define JVT_MODE                           0x3F
 #define JVT_BASE                           (~0x3F)
target/riscv/csr.c +24 -49

156 lines not on this page · raw message

target/riscv/pmu.c +44 -0

47 lines not on this page · raw message

target/riscv/pmu.h +1 -0
index 3853d0e262..8f019bea9f 100644
@@ -38,5 +38,6 @@ void riscv_pmu_update_fixed_ctrs(CPURISCVState *env, target_ulong newpriv,
                                  bool new_virt);
 RISCVException riscv_pmu_read_ctr(CPURISCVState *env, target_ulong *val,
                                   bool upper_half, uint32_t ctr_idx);
+uint32_t riscv_pmu_csrno_to_ctr_idx(int csrno);
 
 #endif /* RISCV_PMU_H */
Signature · 1 line
2.51.0
#2 lore raw

RFC PATCH 2/6 target/riscv: Reimplement Smcdeleg/Ssccfg via read_*, write_* methods

In reply to Aleksandr Sergeev

Methods rmw_cd_mhpmcounter(), rmw_cd_mhpmcounterh(), rmw_cd_mhpmevent(), rmw_cd_mhpmeventh(), rmw_cd_ctr_cfg(), rmw_cd_ctr_cfgh() contain the same code as read_hmpcounter(), write_mhpmcounter(), etc. To avoid the same logic being implemented twice, lets re-call methods from one another.

---
 target/riscv/csr.c | 80 +++++++++++++---------------------------------
 1 file changed, 22 insertions(+), 58 deletions(-)
target/riscv/csr.c +22 -58
index 8bdbc71160..81475ec9a3 100644
@@ -1419,9 +1419,9 @@ static int rmw_cd_mhpmcounter(CPURISCVState *env, int ctr_idx,
     }
 
     if (!wr_mask && val) {
-        riscv_pmu_read_ctr(env, val, false, ctr_idx);
+        read_hpmcounter(env, CSR_MCYCLE + ctr_idx, val);
     } else if (wr_mask) {
-        riscv_pmu_write_ctr(env, new_val, ctr_idx);
+        write_mhpmcounter(env, CSR_MCYCLE + ctr_idx, new_val, 0);
     } else {
         return -EINVAL;
     }
@@ -1438,9 +1438,9 @@ static int rmw_cd_mhpmcounterh(CPURISCVState *env, int ctr_idx,
     }
 
     if (!wr_mask && val) {
-        riscv_pmu_read_ctr(env, val, true, ctr_idx);
+        read_hpmcounterh(env, CSR_MCYCLEH + ctr_idx, val);
     } else if (wr_mask) {
-        riscv_pmu_write_ctrh(env, new_val, ctr_idx);
+        write_mhpmcounterh(env, CSR_MCYCLEH + ctr_idx, new_val, 0);
     } else {
         return -EINVAL;
     }
@@ -1448,31 +1448,18 @@ static int rmw_cd_mhpmcounterh(CPURISCVState *env, int ctr_idx,
     return 0;
 }
 
-static int rmw_cd_mhpmevent(CPURISCVState *env, int evt_index,
+static int rmw_cd_mhpmevent(CPURISCVState *env, int ctr_idx,
                             target_ulong *val, target_ulong new_val,
                             target_ulong wr_mask)
 {
-    uint64_t mhpmevt_val = new_val;
-
     if (wr_mask != 0 && wr_mask != -1) {
         return -EINVAL;
     }
 
     if (!wr_mask && val) {
-        *val = env->mhpmevent_val[evt_index];
-        if (riscv_cpu_cfg(env)->ext_sscofpmf) {
-            *val &= ~MHPMEVENT_BIT_MINH;
-        }
+        read_mhpmevent(env, ctr_idx - 3 + CSR_MHPMEVENT3, val);
     } else if (wr_mask) {
-        wr_mask &= ~MHPMEVENT_BIT_MINH;
-        mhpmevt_val = (new_val & wr_mask) |
-                      (env->mhpmevent_val[evt_index] & ~wr_mask);
-        if (riscv_cpu_mxl(env) == MXL_RV32) {
-            mhpmevt_val = mhpmevt_val |
-                          ((uint64_t)env->mhpmeventh_val[evt_index] << 32);
-        }
-        env->mhpmevent_val[evt_index] = mhpmevt_val;
-        riscv_pmu_update_event_map(env, mhpmevt_val, evt_index);
+        write_mhpmevent(env, ctr_idx - 3 + CSR_MHPMEVENT3, new_val, 0);
     } else {
         return -EINVAL;
     }
@@ -1480,29 +1467,18 @@ static int rmw_cd_mhpmevent(CPURISCVState *env, int evt_index,
     return 0;
 }
 
-static int rmw_cd_mhpmeventh(CPURISCVState *env, int evt_index,
+static int rmw_cd_mhpmeventh(CPURISCVState *env, int ctr_idx,
                              target_ulong *val, target_ulong new_val,
                              target_ulong wr_mask)
 {
-    uint64_t mhpmevth_val;
-    uint64_t mhpmevt_val = env->mhpmevent_val[evt_index];
-
     if (wr_mask != 0 && wr_mask != -1) {
         return -EINVAL;
     }
 
     if (!wr_mask && val) {
-        *val = env->mhpmeventh_val[evt_index];
-        if (riscv_cpu_cfg(env)->ext_sscofpmf) {
-            *val &= ~MHPMEVENTH_BIT_MINH;
-        }
+        read_mhpmeventh(env, ctr_idx - 3 + CSR_MHPMEVENT3H, val);
     } else if (wr_mask) {
-        wr_mask &= ~MHPMEVENTH_BIT_MINH;
-        env->mhpmeventh_val[evt_index] =
-            (new_val & wr_mask) | (env->mhpmeventh_val[evt_index] & ~wr_mask);
-        mhpmevth_val = env->mhpmeventh_val[evt_index];
-        mhpmevt_val = mhpmevt_val | (mhpmevth_val << 32);
-        riscv_pmu_update_event_map(env, mhpmevt_val, evt_index);
+        write_mhpmeventh(env, ctr_idx - 3 + CSR_MHPMEVENT3H, new_val, 0);
     } else {
         return -EINVAL;
     }
@@ -1514,21 +1490,18 @@ static int rmw_cd_ctr_cfg(CPURISCVState *env, int cfg_index, target_ulong *val,
                             target_ulong new_val, target_ulong wr_mask)
 {
     switch (cfg_index) {
-    case 0:             /* CYCLECFG */
+    case HPM_MCYCLE_IDX:
         if (wr_mask) {
-            wr_mask &= ~MCYCLECFG_BIT_MINH;
-            env->mcyclecfg = (new_val & wr_mask) | (env->mcyclecfg & ~wr_mask);
+            write_mcyclecfg(env, CSR_MCYCLE, new_val, 0);
         } else {
-            *val = env->mcyclecfg &= ~MHPMEVENTH_BIT_MINH;
+            read_mcyclecfg(env, CSR_MCYCLE, val);
         }
         break;
-    case 2:             /* INSTRETCFG */
+    case HPM_MINSTRET_IDX:
         if (wr_mask) {
-            wr_mask &= ~MINSTRETCFG_BIT_MINH;
-            env->minstretcfg = (new_val & wr_mask) |
-                               (env->minstretcfg & ~wr_mask);
+            write_minstretcfg(env, CSR_MINSTRET, new_val, 0);
         } else {
-            *val = env->minstretcfg &= ~MHPMEVENTH_BIT_MINH;
+            read_minstretcfg(env, CSR_MINSTRET, val);
         }
         break;
     default:
@@ -1540,28 +1513,19 @@ static int rmw_cd_ctr_cfg(CPURISCVState *env, int cfg_index, target_ulong *val,
 static int rmw_cd_ctr_cfgh(CPURISCVState *env, int cfg_index, target_ulong *val,
                             target_ulong new_val, target_ulong wr_mask)
 {
-
-    if (riscv_cpu_mxl(env) != MXL_RV32) {
-        return RISCV_EXCP_ILLEGAL_INST;
-    }
-
     switch (cfg_index) {
-    case 0:         /* CYCLECFGH */
+    case HPM_MCYCLE_IDX:
         if (wr_mask) {
-            wr_mask &= ~MCYCLECFGH_BIT_MINH;
-            env->mcyclecfgh = (new_val & wr_mask) |
-                              (env->mcyclecfgh & ~wr_mask);
+            write_mcyclecfgh(env, CSR_MCYCLEH, new_val, 0);
         } else {
-            *val = env->mcyclecfgh;
+            read_mcyclecfgh(env, CSR_MCYCLEH, val);
         }
         break;
-    case 2:          /* INSTRETCFGH */
+    case HPM_MINSTRET_IDX:
         if (wr_mask) {
-            wr_mask &= ~MINSTRETCFGH_BIT_MINH;
-            env->minstretcfgh = (new_val & wr_mask) |
-                                (env->minstretcfgh & ~wr_mask);
+            write_minstretcfgh(env, CSR_MINSTRETH, new_val, 0);
         } else {
-            *val = env->minstretcfgh;
+            read_minstretcfgh(env, CSR_MINSTRETH, val);
         }
         break;
     default:
Signature · 1 line
2.51.0
#3 lore raw

RFC PATCH 3/6 target/riscv: Get rid of hardcoded SBI events.

In reply to Aleksandr Sergeev

SBI events are not a part of RISC-V specification
and should not be hardcoded right in QEMU.
It's up to vendor to implement them.

Also, we can get rid of event->ctr mapping,
as it is used only for SBI event handling.

---
 target/riscv/cpu.h        |  15 ---
 target/riscv/cpu_helper.c |  23 ----
 target/riscv/csr.c        |  18 +--
 target/riscv/pmu.c        | 240 ++------------------------------------
 target/riscv/pmu.h        |   7 --
 5 files changed, 16 insertions(+), 287 deletions(-)
target/riscv/cpu.h +0 -15
index 36e7f10037..8ab5fa0afb 100644
@@ -550,8 +550,6 @@ struct ArchCPU {
     QEMUTimer *pmu_timer;
     /* A bitmask of Available programmable counters */
     uint32_t pmu_avail_ctrs;
-    /* Mapping of events to counters */
-    GHashTable *pmu_event_ctr_map;
     const GPtrArray *decoders;
 };
 
@@ -925,19 +923,6 @@ enum {
     CSR_TABLE_SIZE = 0x1000
 };
 
-/*
- * The event id are encoded based on the encoding specified in the
- * SBI specification v0.3
- */
-
-enum riscv_pmu_event_idx {
-    RISCV_PMU_EVENT_HW_CPU_CYCLES = 0x01,
-    RISCV_PMU_EVENT_HW_INSTRUCTIONS = 0x02,
-    RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS = 0x10019,
-    RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS = 0x1001B,
-    RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS = 0x10021,
-};
-
 /* used by tcg/tcg-cpu.c*/
 void isa_ext_update_enabled(RISCVCPU *cpu, uint32_t ext_offset, bool en);
 bool isa_ext_is_enabled(RISCVCPU *cpu, uint32_t ext_offset);
target/riscv/cpu_helper.c +0 -23
index c4fb68b5de..b3780cf8a8 100644
@@ -1736,28 +1736,6 @@ void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
     cpu_loop_exit_restore(cs, retaddr);
 }
 
-
-static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
-{
-    enum riscv_pmu_event_idx pmu_event_type;
-
-    switch (access_type) {
-    case MMU_INST_FETCH:
-        pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
-        break;
-    case MMU_DATA_LOAD:
-        pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
-        break;
-    case MMU_DATA_STORE:
-        pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
-        break;
-    default:
-        return;
-    }
-
-    riscv_pmu_incr_ctr(cpu, pmu_event_type);
-}
-
 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
                         MMUAccessType access_type, int mmu_idx,
                         bool probe, uintptr_t retaddr)
@@ -1781,7 +1759,6 @@ bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
                   __func__, address, access_type, mmu_idx);
 
-    pmu_tlb_fill_incr_ctr(cpu, access_type);
     if (two_stage_lookup) {
         /* Two stage lookup */
         ret = get_physical_address(env, &pa, &prot, address,
target/riscv/csr.c +5 -13
index 81475ec9a3..fb052725fe 100644
@@ -1188,8 +1188,6 @@ static RISCVException write_mhpmevent(CPURISCVState *env, int csrno,
         env->mhpmevent_val[ctr_idx] = mhpmevt_val;
     }
 
-    riscv_pmu_update_event_map(env, mhpmevt_val, ctr_idx);
-
     return RISCV_EXCP_NONE;
 }
 
@@ -1223,8 +1221,6 @@ static RISCVException write_mhpmeventh(CPURISCVState *env, int csrno,
     mhpmevt_val = mhpmevt_val | (mhpmevth_val << 32);
     env->mhpmeventh_val[ctr_idx] = mhpmevth_val;
 
-    riscv_pmu_update_event_map(env, mhpmevt_val, ctr_idx);
-
     return RISCV_EXCP_NONE;
 }
 
@@ -1232,7 +1228,7 @@ static target_ulong riscv_pmu_ctr_get_fixed_counters_val(CPURISCVState *env,
                                                          int counter_idx,
                                                          bool upper_half)
 {
-    int inst = riscv_pmu_ctr_monitor_instructions(env, counter_idx);
+    int inst = (counter_idx == HPM_MINSTRET_IDX);
     uint64_t *counter_arr_virt = env->pmu_fixed_ctrs[inst].counter_virt;
     uint64_t *counter_arr = env->pmu_fixed_ctrs[inst].counter;
     target_ulong result = 0;
@@ -1303,8 +1299,7 @@ static RISCVException riscv_pmu_write_ctr(CPURISCVState *env, target_ulong val,
 
     counter->mhpmcounter_val = val;
     if (!get_field(env->mcountinhibit, BIT(ctr_idx)) &&
-        (riscv_pmu_ctr_monitor_cycles(env, ctr_idx) ||
-         riscv_pmu_ctr_monitor_instructions(env, ctr_idx))) {
+        (ctr_idx == HPM_MCYCLE_IDX || ctr_idx == HPM_MINSTRET_IDX)) {
         counter->mhpmcounter_prev = riscv_pmu_ctr_get_fixed_counters_val(env,
                                                                 ctr_idx, false);
         if (ctr_idx > 2) {
@@ -1332,8 +1327,7 @@ static RISCVException riscv_pmu_write_ctrh(CPURISCVState *env, target_ulong val,
     counter->mhpmcounterh_val = val;
     mhpmctr_val = mhpmctr_val | (mhpmctrh_val << 32);
     if (!get_field(env->mcountinhibit, BIT(ctr_idx)) &&
-        (riscv_pmu_ctr_monitor_cycles(env, ctr_idx) ||
-         riscv_pmu_ctr_monitor_instructions(env, ctr_idx))) {
+        (ctr_idx == HPM_MCYCLE_IDX || ctr_idx == HPM_MINSTRET_IDX)) {
         counter->mhpmcounterh_prev = riscv_pmu_ctr_get_fixed_counters_val(env,
                                                                  ctr_idx, true);
         if (ctr_idx > 2) {
@@ -1384,8 +1378,7 @@ RISCVException riscv_pmu_read_ctr(CPURISCVState *env, target_ulong *val,
      * The kernel computes the perf delta by subtracting the current value from
      * the value it initialized previously (ctr_val).
      */
-    if (riscv_pmu_ctr_monitor_cycles(env, ctr_idx) ||
-        riscv_pmu_ctr_monitor_instructions(env, ctr_idx)) {
+    if (ctr_idx == HPM_MCYCLE_IDX || ctr_idx == HPM_MINSTRET_IDX) {
         *val = riscv_pmu_ctr_get_fixed_counters_val(env, ctr_idx, upper_half) -
                                                     ctr_prev + ctr_val;
     } else {
@@ -2955,8 +2948,7 @@ static RISCVException write_mcountinhibit(CPURISCVState *env, int csrno,
     /* Check if any other counter is also monitoring cycles/instructions */
     for (cidx = 0; cidx < RV_MAX_MHPMCOUNTERS; cidx++) {
         if (!(updated_ctrs & BIT(cidx)) ||
-            (!riscv_pmu_ctr_monitor_cycles(env, cidx) &&
-            !riscv_pmu_ctr_monitor_instructions(env, cidx))) {
+            (cidx != HPM_MCYCLE_IDX && cidx != HPM_MINSTRET_IDX)) {
             continue;
         }
 
target/riscv/pmu.c +11 -229

293 lines not on this page · raw message

target/riscv/pmu.h +0 -7
index 8f019bea9f..97b167d8f2 100644
@@ -22,15 +22,8 @@
 #include "cpu.h"
 #include "qapi/error.h"
 
-bool riscv_pmu_ctr_monitor_instructions(CPURISCVState *env,
-                                        uint32_t target_ctr);
-bool riscv_pmu_ctr_monitor_cycles(CPURISCVState *env,
-                                  uint32_t target_ctr);
 void riscv_pmu_timer_cb(void *priv);
 void riscv_pmu_init(RISCVCPU *cpu, Error **errp);
-int riscv_pmu_update_event_map(CPURISCVState *env, uint64_t value,
-                               uint32_t ctr_idx);
-int riscv_pmu_incr_ctr(RISCVCPU *cpu, enum riscv_pmu_event_idx event_idx);
 void riscv_pmu_generate_fdt_node(void *fdt, uint32_t cmask, char *pmu_name);
 int riscv_pmu_setup_timer(CPURISCVState *env, uint64_t value,
                           uint32_t ctr_idx);
Signature · 1 line
2.51.0
#4 lore raw

RFC PATCH 4/6 target/riscv: Rearrange custom hpm counter api

In reply to Aleksandr Sergeev

Current counter api lacks extendability.
Vendor may want to implement some custom logic for the events To do that, vendor must hardcode it right inside the general methods. So if there are two different vendors with their own events, they would write their code right beside each other.

The counter api was unified to make it extendable, letting vendor fully customize the logic.

The counter is now described with 2 actions:
- read:
returns the current value of the counter
- write:
sets the value of the counter

All the logic for the counters, including inhibiting, filtering, etc, is written in terms of read/write and completely determined by the vendor. Vendor is up to choose how to use prev & val variables. (including totally ignoring them), so we can't rely on any values in it.

Also 64bit variables are now used for prev & val,
avoiding manual handling of 32bit overflows
and making code a bit more clean & simple.

---
 target/riscv/cpu.h        |  81 ++++++--
 target/riscv/cpu_helper.c |  11 +-
 target/riscv/csr.c        | 337 ++++++++++++---------------------
 target/riscv/machine.c    |   7 +-
 target/riscv/pmu.c        | 383 ++++++++++++++++++++++----------------
 target/riscv/pmu.h        |  17 +-
 6 files changed, 431 insertions(+), 405 deletions(-)
target/riscv/cpu.h +62 -19
index 8ab5fa0afb..d8d20559d1 100644
@@ -194,28 +194,44 @@ FIELD(VTYPE, VMA, 7, 1)
 FIELD(VTYPE, VEDIV, 8, 2)
 FIELD(VTYPE, RESERVED, 10, sizeof(target_ulong) * 8 - 11)
 
+/*
+ * Let the counter count some event E.
+ *
+ * Lets call a `raw` value of the counter some arbitrary value,
+ * which increases as event E happens.
+ * Lets also assume the `raw` value is read-only and can't be changed by us.
+ *
+ * Now we want to initialize the counter with some value X.
+ * For that lets add a few more variables:
+ * `val` would contain our initial value X,
+ * `prev` would contain the `raw` value of the counter at the moment of the write.
+ * `(raw - prev)` is `delta` -- the number of events,
+ *  which happened since the last write.
+ *
+ * So the current value of the counter can be calculated as
+ * `(delta + val) == (raw - prev + val)`.
+ *
+ * Each time you write X to the counter, just do:
+ * `val = X; prev = raw`
+ * We can also avoid manual usage of `raw` in code by doing:
+ * `val = X; prev += delta`
+ *
+ * We also want to inhibit our counter sometimes.
+ * If the counter is inhibited, just assume `delta == 0`.
+ *
+ * Text above describes the way builtin counters (mcycle, minstret)
+ * work. However, when implementing vendor events, you are
+ * free to use `prev` and `val` registers whatever you want.
+ */
 typedef struct PMUCTRState {
     /* Current value of a counter */
-    target_ulong mhpmcounter_val;
-    /* Current value of a counter in RV32 */
-    target_ulong mhpmcounterh_val;
+    uint64_t mhpmcounter_val;
     /* Snapshot values of counter */
-    target_ulong mhpmcounter_prev;
-    /* Snapshort value of a counter in RV32 */
-    target_ulong mhpmcounterh_prev;
-    /* Value beyond UINT32_MAX/UINT64_MAX before overflow interrupt trigger */
-    target_ulong irq_overflow_left;
+    uint64_t mhpmcounter_prev;
+    /* Is counter overflowed */
+    bool overflowed;
 } PMUCTRState;
 
-typedef struct PMUFixedCtrState {
-        /* Track cycle and icount for each privilege mode */
-        uint64_t counter[4];
-        uint64_t counter_prev[4];
-        /* Track cycle and icount for each privilege mode when V = 1*/
-        uint64_t counter_virt[2];
-        uint64_t counter_virt_prev[2];
-} PMUFixedCtrState;
-
 struct CPUArchState {
     target_ulong gpr[32];
     target_ulong gprh[32]; /* 64 top bits of the 128-bit registers */
@@ -434,8 +450,6 @@ struct CPUArchState {
     /* PMU event selector configured values for RV32 */
     target_ulong mhpmeventh_val[RV_MAX_MHPMEVENTS];
 
-    PMUFixedCtrState pmu_fixed_ctrs[2];
-
     target_ulong sscratch;
     target_ulong mscratch;
 
@@ -464,6 +478,35 @@ struct CPUArchState {
     uint64_t (*rdtime_fn)(void *);
     void *rdtime_fn_arg;
 
+    /*machine specific pmu callback */
+
+    /*
+     * Returns uint64 value of the counter `ctr_idx`.
+     *
+     * Should also set `PMUCTRState::overflowed`,
+     * if the counter overflows.
+     *
+     * See `riscv_pmu_ctr_read_general` for the example.
+     */
+    RISCVException (*pmu_ctr_read)(CPURISCVState *env, uint32_t ctr_idx,
+                                   uint64_t *value);
+    /*
+     * Writes value to the counter `ctr_idx`.
+     *
+     * Guarantied to be called for vendor events, when:
+     * - inhibiting/uninhibiting
+     * - switching cpu mode (to support filtering)
+     * - changing mhpmevent/mhpmeventh
+     *
+     * See `riscv_pmu_ctr_write_general` for the example.
+     */
+    RISCVException (*pmu_ctr_write)(CPURISCVState *env, uint32_t ctr_idx,
+                                    uint64_t value);
+    /*
+     * Returns true, if the event is supported by vendor.
+     */
+    bool (*pmu_vendor_support)(CPURISCVState *env, uint32_t ctr_idx);
+
     /* machine specific AIA ireg read-modify-write callback */
 #define AIA_MAKE_IREG(__isel, __priv, __virt, __vgein, __xlen) \
     ((((__xlen) & 0xff) << 24) | \
target/riscv/cpu_helper.c +9 -2
index b3780cf8a8..2703279847 100644
@@ -1036,10 +1036,15 @@ void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv, bool virt_en)
         if (icount_enabled()) {
             riscv_itrigger_update_priv(env);
         }
-
-        riscv_pmu_update_fixed_ctrs(env, newpriv, virt_en);
     }
 
+    /*
+     * Preserve pmu ctr values and
+     * restore them after the mode change.
+     */
+    riscv_pmu_preserved_ctrs_t preserved_ctrs;
+    riscv_pmu_preserve_ctrs(env, preserved_ctrs);
+
     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
     env->priv = newpriv;
     env->xl = cpu_recompute_xl(env);
@@ -1075,6 +1080,8 @@ void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv, bool virt_en)
             riscv_cpu_update_mip(env, 0, 0);
         }
     }
+
+    riscv_pmu_restore_ctrs(env, preserved_ctrs);
 }
 
 /*
target/riscv/csr.c +124 -213

465 lines not on this page · raw message

target/riscv/machine.c +3 -4
index 18d790af0d..5083bbb1f2 100644
@@ -339,10 +339,9 @@ static const VMStateDescription vmstate_pmu_ctr_state = {
     .minimum_version_id = 2,
     .needed = pmu_needed,
     .fields = (const VMStateField[]) {
-        VMSTATE_UINTTL(mhpmcounter_val, PMUCTRState),
-        VMSTATE_UINTTL(mhpmcounterh_val, PMUCTRState),
-        VMSTATE_UINTTL(mhpmcounter_prev, PMUCTRState),
-        VMSTATE_UINTTL(mhpmcounterh_prev, PMUCTRState),
+        VMSTATE_UINT64(mhpmcounter_val, PMUCTRState),
+        VMSTATE_UINT64(mhpmcounter_prev, PMUCTRState),
+        VMSTATE_BOOL(overflowed, PMUCTRState),
         VMSTATE_END_OF_LIST()
     }
 };
target/riscv/pmu.c +220 -163

441 lines not on this page · raw message

target/riscv/pmu.h +13 -4
index 97b167d8f2..283e311b04 100644
@@ -22,15 +22,24 @@
 #include "cpu.h"
 #include "qapi/error.h"
 
+#define RISCV_PMU_CTR_IS_HPM(x) ((x) > HPM_MINSTRET_IDX)
+
 void riscv_pmu_timer_cb(void *priv);
 void riscv_pmu_init(RISCVCPU *cpu, Error **errp);
 void riscv_pmu_generate_fdt_node(void *fdt, uint32_t cmask, char *pmu_name);
 int riscv_pmu_setup_timer(CPURISCVState *env, uint64_t value,
                           uint32_t ctr_idx);
-void riscv_pmu_update_fixed_ctrs(CPURISCVState *env, target_ulong newpriv,
-                                 bool new_virt);
-RISCVException riscv_pmu_read_ctr(CPURISCVState *env, target_ulong *val,
-                                  bool upper_half, uint32_t ctr_idx);
 uint32_t riscv_pmu_csrno_to_ctr_idx(int csrno);
+RISCVException riscv_pmu_ctr_read(CPURISCVState *env, uint32_t ctr_idx,
+                                  uint64_t *val);
+RISCVException riscv_pmu_ctr_write(CPURISCVState *env, uint32_t ctr_idx,
+                                   uint64_t val);
+RISCVException riscv_pmu_ctr_read_general(CPURISCVState *env, uint32_t ctr_idx,
+                                          uint64_t *val);
+RISCVException riscv_pmu_ctr_write_general(CPURISCVState *env, uint32_t ctr_idx,
+                                           uint64_t val);
+typedef uint64_t riscv_pmu_preserved_ctrs_t[RV_MAX_MHPMCOUNTERS];
+void riscv_pmu_preserve_ctrs(CPURISCVState *env, riscv_pmu_preserved_ctrs_t data);
+void riscv_pmu_restore_ctrs(CPURISCVState *env, riscv_pmu_preserved_ctrs_t data);
 
 #endif /* RISCV_PMU_H */
Signature · 1 line
2.51.0
#5 lore raw

RFC PATCH 5/6 target/riscv: Add PMU events implementation for `virt`

In reply to Aleksandr Sergeev

Add PMU events implementation for virt machine
according to SBI spec.

---
 hw/misc/Kconfig            |   3 +
 hw/misc/meson.build        |   1 +
 hw/misc/virt_pmu.c         | 142 +++++++++++++++++++++++++++++++++++++
 hw/riscv/Kconfig           |   1 +
 hw/riscv/virt.c            |   4 +-
 include/hw/misc/virt_pmu.h |  91 ++++++++++++++++++++++++
 target/riscv/cpu.c         |   8 +++
 target/riscv/pmu.c         |  53 --------------
 target/riscv/pmu.h         |   1 -
 9 files changed, 248 insertions(+), 56 deletions(-)
 create mode 100644 hw/misc/virt_pmu.c
 create mode 100644 include/hw/misc/virt_pmu.h
hw/misc/Kconfig +3 -0
index fccd735c24..099200f711 100644
@@ -150,6 +150,9 @@ config IOTKIT_SYSINFO
 config PVPANIC_COMMON
     bool
 
+config VIRT_PMU
+    bool
+
 config PVPANIC_PCI
     bool
     default y if PCI_DEVICES
hw/misc/meson.build +1 -0
index b1d8d8e5d2..977a3ac620 100644
@@ -34,6 +34,7 @@ system_ss.add(when: 'CONFIG_SIFIVE_E_PRCI', if_true: files('sifive_e_prci.c'))
 system_ss.add(when: 'CONFIG_SIFIVE_E_AON', if_true: files('sifive_e_aon.c'))
 system_ss.add(when: 'CONFIG_SIFIVE_U_OTP', if_true: files('sifive_u_otp.c'))
 system_ss.add(when: 'CONFIG_SIFIVE_U_PRCI', if_true: files('sifive_u_prci.c'))
+specific_ss.add(when: 'CONFIG_VIRT_PMU', if_true: files('virt_pmu.c'))
 
 subdir('macio')
 
hw/misc/virt_pmu.c new file +142 -0

142 lines not on this page · raw message

hw/riscv/Kconfig +1 -0
index fc9c35bd98..920b65d733 100644
@@ -49,6 +49,7 @@ config RISCV_VIRT
     imply VIRTIO_VGA
     imply TEST_DEVICES
     imply TPM_TIS_SYSBUS
+    select VIRT_PMU
     select DEVICE_TREE
     select RISCV_NUMA
     select GOLDFISH_RTC
hw/riscv/virt.c +2 -2
index 17909206c7..7b0e6869db 100644
@@ -30,7 +30,6 @@
 #include "hw/char/serial-mm.h"
 #include "target/riscv/cpu.h"
 #include "hw/core/sysbus-fdt.h"
-#include "target/riscv/pmu.h"
 #include "hw/riscv/riscv_hart.h"
 #include "hw/riscv/iommu.h"
 #include "hw/riscv/riscv-iommu-bits.h"
@@ -58,6 +57,7 @@
 #include "qapi/qapi-visit-common.h"
 #include "hw/virtio/virtio-iommu.h"
 #include "hw/uefi/var-service-api.h"
+#include "hw/misc/virt_pmu.h"
 
 /* KVM AIA only supports APLIC MSI. APLIC Wired is always emulated by QEMU. */
 static bool virt_use_kvm_aia_aplic_imsic(RISCVVirtAIAType aia_type)
@@ -735,7 +735,7 @@ static void create_fdt_pmu(RISCVVirtState *s)
 
     qemu_fdt_add_subnode(ms->fdt, pmu_name);
     qemu_fdt_setprop_string(ms->fdt, pmu_name, "compatible", "riscv,pmu");
-    riscv_pmu_generate_fdt_node(ms->fdt, hart.pmu_avail_ctrs, pmu_name);
+    riscv_virt_pmu_generate_fdt_node(ms->fdt, hart.pmu_avail_ctrs, pmu_name);
 }
 
 static void create_fdt_sockets(RISCVVirtState *s,
include/hw/misc/virt_pmu.h new file +91 -0

91 lines not on this page · raw message

target/riscv/cpu.c +8 -0
index 73d4280d7c..40853d7214 100644
@@ -37,6 +37,7 @@
 #include "kvm/kvm_riscv.h"
 #include "tcg/tcg-cpu.h"
 #include "tcg/tcg.h"
+#include "hw/misc/virt_pmu.h"
 
 /* RISC-V CPU definitions */
 static const char riscv_single_letter_exts[] = "IEMAFDQCBPVH";
@@ -1125,6 +1126,13 @@ static void riscv_cpu_init(Object *obj)
     cpu->env.vext_ver = VEXT_VERSION_1_00_0;
     cpu->cfg.max_satp_mode = -1;
 
+#ifndef CONFIG_USER_ONLY
+    /* Default PMU implementation */
+    env->pmu_ctr_write = riscv_virt_pmu_ctr_write;
+    env->pmu_ctr_read = riscv_virt_pmu_ctr_read;
+    env->pmu_vendor_support = riscv_virt_supported_events;
+#endif /* CONFIG_USER_ONLY */
+
     if (mcc->def->profile) {
         mcc->def->profile->enabled = true;
     }
target/riscv/pmu.c +0 -53

62 lines not on this page · raw message

target/riscv/pmu.h +0 -1
index 283e311b04..e0603b7e33 100644
@@ -26,7 +26,6 @@
 
 void riscv_pmu_timer_cb(void *priv);
 void riscv_pmu_init(RISCVCPU *cpu, Error **errp);
-void riscv_pmu_generate_fdt_node(void *fdt, uint32_t cmask, char *pmu_name);
 int riscv_pmu_setup_timer(CPURISCVState *env, uint64_t value,
                           uint32_t ctr_idx);
 uint32_t riscv_pmu_csrno_to_ctr_idx(int csrno);
Signature · 1 line
2.51.0
#6 lore raw

Re: [RFC PATCH 5/6] target/riscv: Add PMU events implementation for `virt`

Quoted 14 lines · Aleksandr Sergeev
hw/misc/virt_pmu.c new file +7 -0
new file mode 100644
index 0000000000..afba06de0e
@@ -0,0 +1,142 @@
+/*
+ * RISC-V Virt machine PMU emulation.
+ *
+ * Copyright (c) 2025 Syntacore.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms and conditions of the GNU General Public License,

hw/misc/virt_pmu.c line 17

Quoted 10 lines
hw/misc/virt_pmu.c new file +10 -0
+ * version 2 or later, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program.  If not, see <http://www.gnu.org/licenses/>.
+ */

The virt_pmu.c requires 'SPDX-License-Identifier: GPL-2.0-or-later'

...

Quoted 13 lines
include/hw/misc/virt_pmu.h new file +10 -0
@@ -0,0 +1,91 @@
+/*
+ * RISC-V Virt machine PMU header file.
+ * Copyright (C) 2025, Syntacore Ltd.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,

include/hw/misc/virt_pmu.h line 20

Quoted 10 lines
include/hw/misc/virt_pmu.h new file +10 -0
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * Also add information on how to contact you by electronic and paper mail.
+ */
+

The virt_pmu.h requires 'SPDX-License-Identifier: GPL-2.0-or-later'

include/hw/misc/virt_pmu.h line 23

Quoted 3 lines
include/hw/misc/virt_pmu.h new file +3 -0
+#ifndef RISCV_VIRT_PMU_H
+#define RISCV_VIRT_PMU_H
+

...

Additionally, some code lines exceed 80 columns in length. It is recommended to run ./scripts/checkpatch.pl for further checks.

P.S. The file virt_pmu.c is a new addition. Does the MAINTAINERS file need to be updated? :)

Thanks,
Chao

#7 lore raw

RFC PATCH 6/6 target/riscv/machine: Add smcntrpmf registers to VMStateDescription

In reply to Aleksandr Sergeev
---
 target/riscv/machine.c | 4 ++++
 1 file changed, 4 insertions(+)
target/riscv/machine.c +4 -0
index 5083bbb1f2..2f6a5fc25c 100644
@@ -474,6 +474,10 @@ const VMStateDescription vmstate_riscv_cpu = {
         VMSTATE_UINT32(env.mcounteren, RISCVCPU),
         VMSTATE_UINT32(env.scountinhibit, RISCVCPU),
         VMSTATE_UINT32(env.mcountinhibit, RISCVCPU),
+        VMSTATE_UINTTL(env.mcyclecfg, RISCVCPU),
+        VMSTATE_UINTTL(env.mcyclecfgh, RISCVCPU),
+        VMSTATE_UINTTL(env.minstretcfg, RISCVCPU),
+        VMSTATE_UINTTL(env.minstretcfgh, RISCVCPU),
         VMSTATE_STRUCT_ARRAY(env.pmu_ctrs, RISCVCPU, RV_MAX_MHPMCOUNTERS, 0,
                              vmstate_pmu_ctr_state, PMUCTRState),
         VMSTATE_UINTTL_ARRAY(env.mhpmevent_val, RISCVCPU, RV_MAX_MHPMEVENTS),
Signature · 1 line
2.51.0