Skip to contentSkip to conversation

SBI PMU extension support

PATCH Superseded Atish Patra 7 participants 46 messages May 27, 2021 – Jun 25, 2021 RISC-V

v2 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v2 cover SBI PMU extension support

The latest version of the SBI specification includes a Performance Monitoring Unit(PMU) extension[1] which allows the supervisor to start/stop/configure various PMU events. This series implements the SBI PMU extension in OpenSBI.

It doesn't implement the bits required to support "Sscof" extension yet. That will be added later along with qemu support. This series can be found at github[4] as well. It has been tested with Linux kernel patches[3] for different hardware/firmware events on Qemu.

This patch requires basic QEMU support series[2] to work. As the Qemu did not support mhpmevent/mhpmcounter before this series, these changes are not backward compatible to avoid code churn. Anybody who wants to use perf must include Qemu, OpenSBI, Linux kernel patches.

[1] https://lists.riscv.org/g/tech-unixplatformspec/message/598
[2] https://github.com/atishp04/qemu/tree/riscv_pmu_v1
[3] https://github.com/atishp04/linux/tree/riscv_pmu_v2
[4] https://github.com/atishp04/opensbi/tree/riscv_pmu_v2

Changes from v1->v2:
1. Addressed all the comments from v1.
2. Improved the series by following latest SBI PMU extension[1]

Atish Patra (15):
docs: Add device tree bindings for SBI PMU extension
lib: sbi: Detect mcountinihibit support at runtime
lib: sbi: Remove stray '' character
lib: sbi: Detect number of bits implemented in mhpmcounter
lib: sbi: Disable m/scounteren & enable mcountinhibit
include: Add a list empty check function
lib: sbi: Remove redundant boot time print statement
lib: sbi: Use csr_read/write_num to read/update PMU counters
lib: sbi: Add PMU specific platform hooks
lib: sbi: Add PMU support
utils: fdt: Add fdt helper functions to parse PMU DT nodes
lib: sbi: Implement SBI PMU extension
lib: sbi: Implement firmware counters
lib:sbi:tlb: Improve function naming
platform: generic: Add PMU support

docs/pmu_support.md               |  83 +++++
include/sbi/sbi_ecall.h           |   1 +
include/sbi/sbi_ecall_interface.h | 138 ++++++-
include/sbi/sbi_error.h           |   2 +
include/sbi/sbi_hart.h            |   5 +-
include/sbi/sbi_list.h            |  11 +
include/sbi/sbi_platform.h        |  39 ++
include/sbi/sbi_pmu.h             |  73 ++++
include/sbi_utils/fdt/fdt_pmu.h   |  46 +++
lib/sbi/objects.mk                |   2 +
lib/sbi/riscv_asm.c               |  35 ++
lib/sbi/sbi_ecall.c               |   9 +
lib/sbi/sbi_ecall_pmu.c           |  78 ++++
lib/sbi/sbi_ecall_replace.c       |   1 +
lib/sbi/sbi_hart.c                |  84 ++++-
lib/sbi/sbi_illegal_insn.c        |   2 +
lib/sbi/sbi_init.c                |  11 +-
lib/sbi/sbi_ipi.c                 |   6 +
lib/sbi/sbi_misaligned_ldst.c     |   5 +
lib/sbi/sbi_pmu.c                 | 600 ++++++++++++++++++++++++++++++
lib/sbi/sbi_timer.c               |   2 +
lib/sbi/sbi_tlb.c                 |  78 +++-
lib/sbi/sbi_trap.c                |   5 +
lib/utils/fdt/fdt_fixup.c         |   2 +
lib/utils/fdt/fdt_pmu.c           | 111 ++++++
lib/utils/fdt/objects.mk          |   1 +
platform/generic/platform.c       |  30 ++
27 files changed, 1431 insertions(+), 29 deletions(-)

create mode 100644 docs/pmu_support.md create mode 100644 include/sbi/sbi_pmu.h create mode 100644 include/sbi_utils/fdt/fdt_pmu.h create mode 100644 lib/sbi/sbi_ecall_pmu.c create mode 100644 lib/sbi/sbi_pmu.c create mode 100644 lib/utils/fdt/fdt_pmu.c

--
2.25.1

#1 lore raw

PATCH v2 1/15 docs: Add device tree bindings for SBI PMU extension

SBI PMU extension requires a firmware to be aware of the event to counter/mhpmevent mappings supported by the hardware. One approach is to encode that information in the device tree.

Define a device tree binding that allows a hardware to describe all the PMU mappings required in concise format.

---
 docs/pmu_support.md | 83 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 83 insertions(+)
 create mode 100644 docs/pmu_support.md
docs/pmu_support.md new file +83 -0
new file mode 100644
index 000000000000..8535a1dccbeb
@@ -0,0 +1,83 @@
+OpenSBI SBI PMU extension support
+==================================
+SBI PMU extension supports allow supervisor software to configure/start/stop
+any performance counter at anytime. Thus, an user can leverage full
+capability of performance analysis tools such as perf if SBI PMU extension is
+enabled. The OpenSBI implementation makes the following assumptions about the
+hardware platform.
+
+ * MCOUNTINHIBIT CSR must be implemented in the hardware. Otherwise, SBI PMU
+extension will not be enabled.
+
+ * The platform must provide information about PMU event to counter mapping
+via device tree or platform specific hooks. Otherwise, SBI PMU extension will
+not be enabled.
+
+ * The platforms should provide information about the PMU event selector values
+that should be encoded in the expected value of MHPMEVENTx while configuring
+MHPMCOUNTERx for that specific event. This can be done via a device tree or
+platform specific hooks. The exact value to be written to he MHPMEVENTx is
+completely platform specific. Generic platform writes a default value <xyz> to
+the MHPMEVENTx CSR where <xyz> is formatted as described below.
+```
+  	xyz[0:19]    : event_idx
+        xyz[20:XLEN] : event_data[0:(XLEN-20)]
+
+```
+
+SBI PMU Device Tree Bindings
+----------------------------
+
+Platforms may choose to describe PMU event selector and event to counter mapping
+values via device tree. The following sections describes the PMU DT node
+bindings in details.
+
+* **compatible** (Mandatory) - The compatible string of SBI PMU device tree node.
+This DT property must have the value **riscv,pmu**.
+
+* **opensbi,event-to-mhpmevent**(Optional) - It represents an ONE-to-ONE mapping
+between a PMU event and the event selector value that platform expects to be
+written to the MHPMEVENTx CSR for that event. The mapping is encoded in a
+table format where each row represents an event. The first column represent the
+event idx where the 2nd & 3rd column represent the event selector value that
+should be encoded in the expected value to be written in MHPMEVENTx.
+This property shouldn't encode any raw hardware event.
+
+* **opensbi,event-to-counters**(Optional) - It represents a MANY-to-MANY
+mapping between a range of events and all the MHPMCOUNTERx in a bitmap format
+that can be used to monitor these range of events. The information is encoded in
+a table format where each row represent a certain range of events and
+corresponding counters. The first column represents starting of the pmu event id
+and 2nd column represents the end of the pmu event id. The third column
+represent a bitmap of all the MHPMCOUNTERx. This property is mandatory if
+event-to-mhpmevent is present. Otherwise, it can be omitted. This property
+shouldn't encode any raw event.
+
+* **opensbi,raw-event-to-counters**(Optional) - It represents an ONE-to-MANY
+mapping between a raw event and all the MHPMCOUNTERx in a bitmap format that can
+be used to monitor that raw event. The information is encoded in a table format
+where each raw represent a specific raw event. The first column stores the
+expected event selector value that should be encoded in the expected value to be
+written in MHPMEVENTx. The second column stores a bitmap of all the MHPMCOUNTERx
+that can be used for monitoring the specified event.
+
+*Note:* A platform may choose to provide the mapping between event & counters
+via platform hooks rather than the device tree.
+
+### Example
+
+```
+pmu {
+      compatible 			= "riscv,pmu";
+      interrupts 			= <0x100>;
+      interrupt-parent 			= <&plic>
+      opensbi,event-to-mhpmevent 	= <0x0000B  0x0000 0x0001>,
+      opensbi,event-to-counters 	= <0x00001 0x00001 0x00000001>,
+      					  <0x00002 0x00002 0x00000004>,
+      					  <0x00003 0x0000A 0x00000ff8>,
+      				 	  <0x10000 0x10033 0x000ff000>,
+      opensbi,raw-event-to-counters 	= <0x0000 0x0002 0x00000f8>,
+					  <0x0000 0x0003 0x00000ff0>,
+};
+
+```
Signature · 1 line
2.25.1
#2 lore raw

PATCH v2 1/15 docs: Add device tree bindings for SBI PMU extension

Quoted 10 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 01/15] docs: Add device tree bindings for SBI PMU extension

Quoted 8 lines

SBI PMU extension requires a firmware to be aware of the event to counter/mhpmevent mappings supported by the hardware. One approach is to encode that information in the device tree.

Define a device tree binding that allows a hardware to describe all the PMU mappings required in concise format.

Looks good to me.

Regards,
Anup

Quoted 104 lines
---
 docs/pmu_support.md | 83
+++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 83 insertions(+)
 create mode 100644 docs/pmu_support.md
docs/pmu_support.md new file mode renamed from docs/pmu_support.md +0 -0

100644 index 000000000000..8535a1dccbeb

docs/pmu_support.md new file +18 -0
@@ -0,0 +1,83 @@
+OpenSBI SBI PMU extension support
+==================================
+SBI PMU extension supports allow supervisor software to
+configure/start/stop any performance counter at anytime. Thus, an user
+can leverage full capability of performance analysis tools such as perf
+if SBI PMU extension is enabled. The OpenSBI implementation makes the
+following assumptions about the hardware platform.
+
+ * MCOUNTINHIBIT CSR must be implemented in the hardware. Otherwise,
+SBI PMU extension will not be enabled.
+
+ * The platform must provide information about PMU event to counter
+mapping via device tree or platform specific hooks. Otherwise, SBI PMU
+extension will not be enabled.
+
+ * The platforms should provide information about the PMU event
+selector values that should be encoded in the expected value of
+MHPMEVENTx while configuring MHPMCOUNTERx for that specific event.

This

docs/pmu_support.md new file +3 -0
+can be done via a device tree or platform specific hooks. The exact
+value to be written to he MHPMEVENTx is completely platform specific.
+Generic platform writes a default value <xyz> to the MHPMEVENTx CSR

where <xyz> is formatted as described below.
+```

docs/pmu_support.md new file +13 -0
+  	xyz[0:19]    : event_idx
+        xyz[20:XLEN] : event_data[0:(XLEN-20)]
+
+```
+
+SBI PMU Device Tree Bindings
+----------------------------
+
+Platforms may choose to describe PMU event selector and event to
+counter mapping values via device tree. The following sections
+describes the PMU DT node bindings in details.
+
+* **compatible** (Mandatory) - The compatible string of SBI PMU device

tree node.

docs/pmu_support.md new file +8 -0
+This DT property must have the value **riscv,pmu**.
+
+* **opensbi,event-to-mhpmevent**(Optional) - It represents an
+ONE-to-ONE mapping between a PMU event and the event selector value
+that platform expects to be written to the MHPMEVENTx CSR for that
+event. The mapping is encoded in a table format where each row
+represents an event. The first column represent the event idx where the
+2nd & 3rd column represent the event selector value that should be

encoded in the expected value to be written in MHPMEVENTx.

docs/pmu_support.md new file +4 -0
+This property shouldn't encode any raw hardware event.
+
+* **opensbi,event-to-counters**(Optional) - It represents a
+MANY-to-MANY mapping between a range of events and all the

MHPMCOUNTERx

docs/pmu_support.md new file +7 -0
+in a bitmap format that can be used to monitor these range of events.
+The information is encoded in a table format where each row represent a
+certain range of events and corresponding counters. The first column
+represents starting of the pmu event id and 2nd column represents the
+end of the pmu event id. The third column represent a bitmap of all the
+MHPMCOUNTERx. This property is mandatory if event-to-mhpmevent is
+present. Otherwise, it can be omitted. This property shouldn't encode any

raw event.

docs/pmu_support.md new file +3 -0
+
+* **opensbi,raw-event-to-counters**(Optional) - It represents an
+ONE-to-MANY mapping between a raw event and all the MHPMCOUNTERx in

a

docs/pmu_support.md new file +5 -0
+bitmap format that can be used to monitor that raw event. The
+information is encoded in a table format where each raw represent a
+specific raw event. The first column stores the expected event selector
+value that should be encoded in the expected value to be written in
+MHPMEVENTx. The second column stores a bitmap of all the

MHPMCOUNTERx that can be used for monitoring the specified event.

docs/pmu_support.md new file +21 -1
+
+*Note:* A platform may choose to provide the mapping between event &
+counters via platform hooks rather than the device tree.
+
+### Example
+
+```
+pmu {
+      compatible 			= "riscv,pmu";
+      interrupts 			= <0x100>;
+      interrupt-parent 			= <&plic>
+      opensbi,event-to-mhpmevent 	= <0x0000B  0x0000 0x0001>,
+      opensbi,event-to-counters 	= <0x00001 0x00001 0x00000001>,
+      					  <0x00002 0x00002 0x00000004>,
+      					  <0x00003 0x0000A 0x00000ff8>,
+      				 	  <0x10000 0x10033 0x000ff000>,
+      opensbi,raw-event-to-counters 	= <0x0000 0x0002 0x00000f8>,
+					  <0x0000 0x0003 0x00000ff0>,
+};
+
+```
--

2.25.1

#3 lore raw

PATCH v2 2/15 lib: sbi: Detect mcountinihibit support at runtime

In reply to Atish Patra

RISC-V ISA specification v1.11 defined mcountinhibit CSR that allows software to stop any counter from incrementing. The SBI PMU extension depends on this CSR support in hardware.

Define mcountinhibit as a hart specific feature and detect it at runtime.

---
 include/sbi/sbi_hart.h |  4 +++-
 lib/sbi/sbi_hart.c     | 11 +++++++++++
 2 files changed, 14 insertions(+), 1 deletion(-)
include/sbi/sbi_hart.h +3 -1
index 031c7b08a815..9e317c52008c 100644
@@ -18,8 +18,10 @@ enum sbi_hart_features {
 	SBI_HART_HAS_SCOUNTEREN = (1 << 0),
 	/** Hart has M-mode counter enable */
 	SBI_HART_HAS_MCOUNTEREN = (1 << 1),
+	/** Hart has counter inhibit CSR */
+	SBI_HART_HAS_MCOUNTINHIBIT = (1 << 2),
 	/** HART has timer csr implementation in hardware */
-	SBI_HART_HAS_TIME = (1 << 2),
+	SBI_HART_HAS_TIME = (1 << 3),
 
 	/** Last index of Hart features*/
 	SBI_HART_HAS_LAST_FEATURE = SBI_HART_HAS_TIME,
lib/sbi/sbi_hart.c +11 -0
index de59b1431b5b..8fae20891bde 100644
@@ -259,6 +259,9 @@ static inline char *sbi_hart_feature_id2string(unsigned long feature)
 	case SBI_HART_HAS_MCOUNTEREN:
 		fstr = "mcounteren";
 		break;
+	case SBI_HART_HAS_MCOUNTINHIBIT:
+		fstr = "mcountinhibit";
+		break;
 	case SBI_HART_HAS_TIME:
 		fstr = "time";
 		break;
@@ -421,6 +424,14 @@ __mhpm_skip:
 			hfeatures->features |= SBI_HART_HAS_MCOUNTEREN;
 	}
 
+	/* Detect if hart supports MCOUNTINHIBIT feature */
+	val = csr_read_allowed(CSR_MCOUNTINHIBIT, (unsigned long)&trap);
+	if (!trap.cause) {
+		csr_write_allowed(CSR_MCOUNTINHIBIT, (unsigned long)&trap, val);
+		if (!trap.cause)
+			hfeatures->features |= SBI_HART_HAS_MCOUNTINHIBIT;
+	}
+
 	/* Detect if hart supports time CSR */
 	csr_read_allowed(CSR_TIME, (unsigned long)&trap);
 	if (!trap.cause)
Signature · 1 line
2.25.1
#4 lore raw

PATCH v2 2/15 lib: sbi: Detect mcountinihibit support at runtime

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 9 lines

RISC-V ISA specification v1.11 defined mcountinhibit CSR that allows software to stop any counter from incrementing. The SBI PMU extension depends on this CSR support in hardware.

Define mcountinhibit as a hart specific feature and detect it at runtime.

Quoted 59 lines

---
?include/sbi/sbi_hart.h |? 4 +++-
?lib/sbi/sbi_hart.c???? | 11 +++++++++++
?2 files changed, 14 insertions(+), 1 deletion(-)

include/sbi/sbi_hart.h +0 -0
index 031c7b08a815..9e317c52008c 100644
@@ -18,8 +18,10 @@ enum sbi_hart_features {
 ????????SBI_HART_HAS_SCOUNTEREN = (1 << 0),

????????/** Hart has M-mode counter enable */ ????????SBI_HART_HAS_MCOUNTEREN = (1 << 1), +???????/** Hart has counter inhibit CSR */ +???????SBI_HART_HAS_MCOUNTINHIBIT = (1 << 2), ????????/** HART has timer csr implementation in hardware */ -???????SBI_HART_HAS_TIME = (1 << 2), +???????SBI_HART_HAS_TIME = (1 << 3),
?
????????/** Last index of Hart features*/ ????????SBI_HART_HAS_LAST_FEATURE = SBI_HART_HAS_TIME,

lib/sbi/sbi_hart.c +0 -0
index de59b1431b5b..8fae20891bde 100644
@@ -259,6 +259,9 @@ static inline char
 *sbi_hart_feature_id2string(unsigned long feature)

????????case SBI_HART_HAS_MCOUNTEREN:
????????????????fstr = "mcounteren";
????????????????break;
+???????case SBI_HART_HAS_MCOUNTINHIBIT:
+???????????????fstr = "mcountinhibit";
+???????????????break;
????????case SBI_HART_HAS_TIME:
????????????????fstr = "time";
????????????????break;

lib/sbi/sbi_hart.c +0 -0
@@ -421,6 +424,14 @@ __mhpm_skip:

????????????????????????hfeatures->features |= SBI_HART_HAS_MCOUNTEREN;
????????}
?
+???????/* Detect if hart supports MCOUNTINHIBIT feature */ +???????val = csr_read_allowed(CSR_MCOUNTINHIBIT, (unsigned long)&trap);
+???????if (!trap.cause) { +???????????????csr_write_allowed(CSR_MCOUNTINHIBIT, (unsigned long)&trap, val);
+???????????????if (!trap.cause) +???????????????????????hfeatures->features |= SBI_HART_HAS_MCOUNTINHIBIT;
+???????}
+
????????/* Detect if hart supports time CSR */ ????????csr_read_allowed(CSR_TIME, (unsigned long)&trap); ????????if (!trap.cause)

Signature · 1 line
2.25.1
#5 lore raw

PATCH v2 3/15 lib: sbi: Remove stray '\' character

In reply to Atish Patra
---
 lib/sbi/sbi_hart.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/sbi/sbi_hart.c +1 -1
index 8fae20891bde..e5e5781ff412 100644
@@ -320,7 +320,7 @@ static unsigned long hart_pmp_get_allowed_addr(void)
 	unsigned long val = 0;
 	struct sbi_trap_info trap = {0};
 
-	csr_write_allowed(CSR_PMPADDR0, (ulong)&trap, PMP_ADDR_MASK);			\
+	csr_write_allowed(CSR_PMPADDR0, (ulong)&trap, PMP_ADDR_MASK);
 	if (!trap.cause) {
 		val = csr_read_allowed(CSR_PMPADDR0, (ulong)&trap);
 		if (trap.cause)
Signature · 1 line
2.25.1
#6 lore raw

PATCH v2 4/15 lib: sbi: Detect number of bits implemented in mhpmcounter

In reply to Atish Patra

RISC-V privilege specification allows the implementation to have less than 64 bits.

Add a function to detect the number of implemented bits in mhpmcounter dynamically at runtime.

---
 include/sbi/sbi_hart.h |  1 +
 lib/sbi/sbi_hart.c     | 49 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+)
include/sbi/sbi_hart.h +1 -0
index 9e317c52008c..0c18ef9325b2 100644
@@ -44,6 +44,7 @@ void sbi_hart_delegation_dump(struct sbi_scratch *scratch,
 unsigned int sbi_hart_pmp_count(struct sbi_scratch *scratch);
 unsigned long sbi_hart_pmp_granularity(struct sbi_scratch *scratch);
 unsigned int sbi_hart_pmp_addrbits(struct sbi_scratch *scratch);
+unsigned int sbi_hart_mhpm_bits(struct sbi_scratch *scratch);
 int sbi_hart_pmp_configure(struct sbi_scratch *scratch);
 bool sbi_hart_has_feature(struct sbi_scratch *scratch, unsigned long feature);
 void sbi_hart_get_features_str(struct sbi_scratch *scratch,
lib/sbi/sbi_hart.c +49 -0

77 lines not on this page · raw message

Signature · 1 line
2.25.1
#7 lore raw

PATCH v2 4/15 lib: sbi: Detect number of bits implemented in mhpmcounter

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 101 lines

RISC-V privilege specification allows the implementation to have less than 64 bits.

Add a function to detect the number of implemented bits in mhpmcounter
dynamically at runtime.

---
?include/sbi/sbi_hart.h |? 1 +
?lib/sbi/sbi_hart.c???? | 49
++++++++++++++++++++++++++++++++++++++++++
?2 files changed, 50 insertions(+)

include/sbi/sbi_hart.h +1 -0
index 9e317c52008c..0c18ef9325b2 100644
@@ -44,6 +44,7 @@ void sbi_hart_delegation_dump(struct sbi_scratch
 *scratch,
 ?unsigned int sbi_hart_pmp_count(struct sbi_scratch *scratch);
 ?unsigned long sbi_hart_pmp_granularity(struct sbi_scratch *scratch);
 ?unsigned int sbi_hart_pmp_addrbits(struct sbi_scratch *scratch);
+unsigned int sbi_hart_mhpm_bits(struct sbi_scratch *scratch);
 ?int sbi_hart_pmp_configure(struct sbi_scratch *scratch);

?bool sbi_hart_has_feature(struct sbi_scratch *scratch, unsigned long feature);
?void sbi_hart_get_features_str(struct sbi_scratch *scratch,

lib/sbi/sbi_hart.c +1 -0
index e5e5781ff412..0d5b7b8d3509 100644
@@ -33,6 +33,7 @@ struct hart_features {
 ????????unsigned int pmp_addr_bits;
 ????????unsigned long pmp_gran;
 ????????unsigned int mhpm_count;
+???????unsigned int mhpm_bits;
 ?};
 ?static unsigned long hart_features_offset;

?

lib/sbi/sbi_hart.c +0 -0
@@ -177,6 +178,14 @@ unsigned int sbi_hart_pmp_addrbits(struct
 sbi_scratch *scratch)
 ????????return hfeatures->pmp_addr_bits;
 ?}

?

lib/sbi/sbi_hart.c +4 -0
+unsigned int sbi_hart_mhpm_bits(struct sbi_scratch *scratch)
+{
+???????struct hart_features *hfeatures =
+???????????????????????sbi_scratch_offset_ptr(scratch,

hart_features_offset);

lib/sbi/sbi_hart.c +4 -0
+
+???????return hfeatures->mhpm_bits;
+}
+

?int sbi_hart_pmp_configure(struct sbi_scratch *scratch) ?{
????????struct sbi_domain_memregion *reg;

lib/sbi/sbi_hart.c +0 -0
@@ -330,6 +339,37 @@ static unsigned long
 hart_pmp_get_allowed_addr(void)
 ????????return val;
 ?}

?

lib/sbi/sbi_hart.c +8 -0
+static int hart_pmu_get_allowed_bits(void)
+{
+???????unsigned long val = ~(0UL);
+???????struct sbi_trap_info trap = {0};
+???????int num_bits = 0;
+
+???????/**
+??????? * It is assumed that platforms will implement same number of

bits for
+??????? * all the performance counters including mcycle/minstret. +??????? */
+???????csr_write_allowed(CSR_MHPMCOUNTER3, (ulong)&trap, val); +???????if (!trap.cause) {
+???????????????val = csr_read_allowed(CSR_MHPMCOUNTER3, (ulong)&trap);
+???????????????if (trap.cause) +???????????????????????return 0;
+???????}
+???????num_bits = __fls(val) + 1;
+#if __riscv_xlen == 32 +???????csr_write_allowed(CSR_MHPMCOUNTER3H, (ulong)&trap, val); +???????if (!trap.cause) {
+???????????????val = csr_read_allowed(CSR_MHPMCOUNTER3H, (ulong)&trap);
+???????????????if (trap.cause) +???????????????????????return num_bits;
+???????}
+???????num_bits += __fls(val) + 1;

lib/sbi/sbi_hart.c +6 -0
+
+#endif
+
+???????return num_bits;
+}
+

?static void hart_detect_features(struct sbi_scratch *scratch) ?{
????????struct sbi_trap_info trap = {0};

lib/sbi/sbi_hart.c +0 -0
@@ -394,10 +434,19 @@ static void hart_detect_features(struct
 sbi_scratch *scratch)
Quoted 4 lines

?__pmp_skip:
?
????????/* Detect number of MHPM counters */
+???????trap.cause = 0;

The previous line can be deleted

Quoted 24 lines

????????__check_csr(CSR_MHPMCOUNTER3, 0, 1UL, mhpm_count, __mhpm_skip);
+???????hfeatures->mhpm_bits = hart_pmu_get_allowed_bits(); +
????????__check_csr_4(CSR_MHPMCOUNTER4, 0, 1UL, mhpm_count, __mhpm_skip);
????????__check_csr_8(CSR_MHPMCOUNTER8, 0, 1UL, mhpm_count, __mhpm_skip);
????????__check_csr_16(CSR_MHPMCOUNTER16, 0, 1UL, mhpm_count, __mhpm_skip);
+
+???????/**
+??????? * No need to check for MHPMCOUNTERH for RV32 as they are expected to be
+??????? * implemented if MHPMCOUNTER is implemented. +??????? */
+
?__mhpm_skip:
?
?#undef __check_csr_64

Signature · 1 line
2.25.1
#8 lore raw

PATCH v2 4/15 lib: sbi: Detect number of bits implemented in mhpmcounter

In reply to Atish Patra
Quoted 10 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 04/15] lib: sbi: Detect number of bits implemented in mhpmcounter

Quoted 7 lines

RISC-V privilege specification allows the implementation to have less than 64 bits.

Add a function to detect the number of implemented bits in mhpmcounter dynamically at runtime.

No comments other than what Xiang already commented.

Regards,
Anup

Quoted 112 lines
---
 include/sbi/sbi_hart.h |  1 +
 lib/sbi/sbi_hart.c     | 49
++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+)
include/sbi/sbi_hart.h index renamed from include/sbi/sbi_hart.h +0 -0

9e317c52008c..0c18ef9325b2 100644

include/sbi/sbi_hart.h +1 -0
@@ -44,6 +44,7 @@ void sbi_hart_delegation_dump(struct sbi_scratch
 *scratch,  unsigned int sbi_hart_pmp_count(struct sbi_scratch *scratch);
 unsigned long sbi_hart_pmp_granularity(struct sbi_scratch *scratch);
 unsigned int sbi_hart_pmp_addrbits(struct sbi_scratch *scratch);
+unsigned int sbi_hart_mhpm_bits(struct sbi_scratch *scratch);
 int sbi_hart_pmp_configure(struct sbi_scratch *scratch);  bool
 sbi_hart_has_feature(struct sbi_scratch *scratch, unsigned long feature);

void sbi_hart_get_features_str(struct sbi_scratch *scratch, diff --git a/lib/sbi/sbi_hart.c b/lib/sbi/sbi_hart.c index e5e5781ff412..0d5b7b8d3509 100644

lib/sbi/sbi_hart.c +15 -0
@@ -33,6 +33,7 @@ struct hart_features {
 	unsigned int pmp_addr_bits;
 	unsigned long pmp_gran;
 	unsigned int mhpm_count;
+	unsigned int mhpm_bits;
 };
 static unsigned long hart_features_offset;
 
@@ -177,6 +178,14 @@ unsigned int sbi_hart_pmp_addrbits(struct
 sbi_scratch *scratch)
 	return hfeatures->pmp_addr_bits;
 }
 
+unsigned int sbi_hart_mhpm_bits(struct sbi_scratch *scratch) {
+	struct hart_features *hfeatures =
+			sbi_scratch_offset_ptr(scratch, hart_features_offset);
+
+	return hfeatures->mhpm_bits;
+}
+
 int sbi_hart_pmp_configure(struct sbi_scratch *scratch)  {
 	struct sbi_domain_memregion *reg;
@@ -330,6 +339,37 @@ static unsigned long
 hart_pmp_get_allowed_addr(void)
 	return val;
 }
 
+static int hart_pmu_get_allowed_bits(void) {
+	unsigned long val = ~(0UL);
+	struct sbi_trap_info trap = {0};
+	int num_bits = 0;
+
+	/**
+	 * It is assumed that platforms will implement same number of bits

for

lib/sbi/sbi_hart.c +5 -0
+	 * all the performance counters including mcycle/minstret.
+	 */
+	csr_write_allowed(CSR_MHPMCOUNTER3, (ulong)&trap, val);
+	if (!trap.cause) {
+		val = csr_read_allowed(CSR_MHPMCOUNTER3,

(ulong)&trap);

lib/sbi/sbi_hart.c +8 -0
+		if (trap.cause)
+			return 0;
+	}
+	num_bits = __fls(val) + 1;
+#if __riscv_xlen == 32
+	csr_write_allowed(CSR_MHPMCOUNTER3H, (ulong)&trap, val);
+	if (!trap.cause) {
+		val = csr_read_allowed(CSR_MHPMCOUNTER3H,

(ulong)&trap);

lib/sbi/sbi_hart.c +13 -0
+		if (trap.cause)
+			return num_bits;
+	}
+	num_bits += __fls(val) + 1;
+
+#endif
+
+	return num_bits;
+}
+
 static void hart_detect_features(struct sbi_scratch *scratch)  {
 	struct sbi_trap_info trap = {0};
@@ -394,10 +434,19 @@ static void hart_detect_features(struct sbi_scratch
 *scratch)
 __pmp_skip:
 
 	/* Detect number of MHPM counters */
+	trap.cause = 0;
 	__check_csr(CSR_MHPMCOUNTER3, 0, 1UL, mhpm_count,
 __mhpm_skip);
+	hfeatures->mhpm_bits = hart_pmu_get_allowed_bits();
+
 	__check_csr_4(CSR_MHPMCOUNTER4, 0, 1UL, mhpm_count,
 __mhpm_skip);
 	__check_csr_8(CSR_MHPMCOUNTER8, 0, 1UL, mhpm_count,
 __mhpm_skip);
 	__check_csr_16(CSR_MHPMCOUNTER16, 0, 1UL, mhpm_count,

__mhpm_skip);

lib/sbi/sbi_hart.c +3 -0
+
+	/**
+	 * No need to check for MHPMCOUNTERH for RV32 as they are

expected to be

lib/sbi/sbi_hart.c +3 -1
+	 * implemented if MHPMCOUNTER is implemented.
+	 */
+
 __mhpm_skip:
 
 #undef __check_csr_64
--

2.25.1

#9 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

In reply to Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

---
 lib/sbi/sbi_hart.c | 22 ++++++++++++++++++----
 1 file changed, 18 insertions(+), 4 deletions(-)
lib/sbi/sbi_hart.c +18 -4
index 0d5b7b8d3509..9f1ee20fa978 100644
@@ -51,12 +51,26 @@ static void mstatus_init(struct sbi_scratch *scratch)
 
 	csr_write(CSR_MSTATUS, mstatus_val);
 
-	/* Enable user/supervisor use of perf counters */
+	/* Disable user mode usage of perf counters */
 	if (misa_extension('S') &&
 	    sbi_hart_has_feature(scratch, SBI_HART_HAS_SCOUNTEREN))
-		csr_write(CSR_SCOUNTEREN, -1);
-	if (sbi_hart_has_feature(scratch, SBI_HART_HAS_MCOUNTEREN))
-		csr_write(CSR_MCOUNTEREN, -1);
+		csr_write(CSR_SCOUNTEREN, 0);
+
+	if (sbi_hart_has_feature(scratch, SBI_HART_HAS_MCOUNTEREN)) {
+		if (sbi_hart_has_feature(scratch, SBI_HART_HAS_MCOUNTINHIBIT))
+			/**
+			 * Just enable TM bit now. All other counters will be
+			 * enabled at runtime after S-mode request
+			 */
+			csr_write(CSR_MCOUNTEREN, 2);
+		else
+			/* Supervisor mode usage are enabled by default */
+			csr_write(CSR_MCOUNTEREN, -1);
+	}
+
+	/* Counters will start running at runtime after S-mode request */
+	if (sbi_hart_has_feature(scratch, SBI_HART_HAS_MCOUNTINHIBIT))
+		csr_write(CSR_MCOUNTINHIBIT, -1);
 
 	/* Disable all interrupts */
 	csr_write(CSR_MIE, 0);
Signature · 1 line
2.25.1
#10 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 9 lines · Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

Turning off CY or IR seems like a bad idea to me. Similarly, all of CY, IR and TM should be enabled in scounteren by default, this is just needlessly hostile. IMO both mcounteren and scounteren should be initialised to 7 on boot.

Jess

#11 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 9 lines · Jessica Clarke
Quoted 7 lines · Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Quoted 5 lines
Quoted 2 lines

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

Turning off CY or IR seems like a bad idea to me. Similarly, all of CY, IR and TM should be enabled in scounteren by default, this is just needlessly hostile.

This happens only if the platform supports mcountinhibit. As per the priv spec, no counter should run unless the corresponding bit in mcountinhibit
is cleared. This patch just follows the spec.

Quoted 9 lines

IMO both mcounteren and scounteren should be initialised to 7 on boot.

Jess

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

Signature · 2 lines
Regards,
Atish
#12 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 14 lines · Atish Patra
Quoted 12 lines · Jessica Clarke
Quoted 9 lines · Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

Quoted 7 lines
Quoted 2 lines

Turning off CY or IR seems like a bad idea to me. Similarly, all of CY, IR and TM should be enabled in scounteren by default, this is just needlessly hostile.

This happens only if the platform supports mcountinhibit. As per the priv spec, no counter should run unless the corresponding bit in mcountinhibit
is cleared. This patch just follows the spec.

I don?t understand your reply. The privileged spec just says how the CSRs behave, it doesn?t say that you need to make an SBI call (which isn?t part of the privileged spec) for cycle and instret to count. Requiring that is unnecessarily hostile; in practice, everything will want those two counters to be enabled, because arbitrary userspace software wants to use them. They should never be disabled by OpenSBI unless S-mode explicitly asks for them to be disabled.

Jess

#13 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 24 lines · Jessica Clarke
Quoted 14 lines · Atish Patra
Quoted 12 lines · Jessica Clarke
Quoted 9 lines · Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

Quoted 7 lines
Quoted 2 lines

Turning off CY or IR seems like a bad idea to me. Similarly, all of CY, IR and TM should be enabled in scounteren by default, this is just needlessly hostile.

This happens only if the platform supports mcountinhibit. As per the priv spec, no counter should run unless the corresponding bit in mcountinhibit
is cleared. This patch just follows the spec.

Quoted 5 lines

I don?t understand your reply. The privileged spec just says how the CSRs behave, it doesn?t say that you need to make an SBI call (which isn?t part of the privileged spec) for cycle and instret to count. Requiring that is unnecessarily hostile; in practice, everything will want those two counters to be enabled, because arbitrary userspace software wants to use them.

That's a security risk. One rogue process can have access to cycle & instructions of the entire kernel & M-mode firmware.
The counters should report a value only if it is being asked to start/stop a userspace application (e.g. perf).

We can keep CY & IR bits enabled in OpenSBI but it must be disabled by the Linux kernel PMU driver by default.
The effect will remain the same.

Once sscopmf is implemented, there is a plan to set MINH bit always so that supervisor/userspace don't know how many cycles
are spent while running OpenSBI.

They should

Quoted 5 lines

never be disabled by OpenSBI unless S-mode explicitly asks for them to be disabled.

Jess

Signature · 2 lines
Regards,
Atish
#14 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 37 lines · Atish Patra
Quoted 24 lines · Jessica Clarke
Quoted 14 lines · Atish Patra
Quoted 12 lines · Jessica Clarke
Quoted 9 lines · Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

Quoted 7 lines
Quoted 2 lines

Turning off CY or IR seems like a bad idea to me. Similarly, all of CY, IR and TM should be enabled in scounteren by default, this is just needlessly hostile.

This happens only if the platform supports mcountinhibit. As per the priv spec, no counter should run unless the corresponding bit in mcountinhibit
is cleared. This patch just follows the spec.

Quoted 5 lines

I don?t understand your reply. The privileged spec just says how the CSRs behave, it doesn?t say that you need to make an SBI call (which isn?t part of the privileged spec) for cycle and instret to count. Requiring that is unnecessarily hostile; in practice, everything will want those two counters to be enabled, because arbitrary userspace software wants to use them.

That's a security risk. One rogue process can have access to cycle & instructions of the entire kernel & M-mode firmware.
The counters should report a value only if it is being asked to start/stop a userspace application (e.g. perf).

Quoted 7 lines

We can keep CY & IR bits enabled in OpenSBI but it must be disabled by the Linux kernel PMU driver by default.
The effect will remain the same.

Once sscopmf is implemented, there is a plan to set MINH bit always so that supervisor/userspace don't know how many cycles
are spent while running OpenSBI.

That side-channel will always exist by measuring time. This just breaks valid use-cases in the name of ?security?.

__builtin_readcyclecounter is a thing and needs to work otherwise you *will* break software. At the end of the day I don?t care what you do in the Linux kernel, but I do care what gets done in the platform firmware that breaks existing 3rd-party userspace software on FreeBSD.

Jess

#15 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 47 lines · Jessica Clarke
Quoted 37 lines · Atish Patra
Quoted 24 lines · Jessica Clarke
Quoted 14 lines · Atish Patra
Quoted 12 lines · Jessica Clarke
Quoted 9 lines · Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

Quoted 7 lines
Quoted 2 lines

Turning off CY or IR seems like a bad idea to me. Similarly, all of CY, IR and TM should be enabled in scounteren by default, this is just needlessly hostile.

This happens only if the platform supports mcountinhibit. As per the priv spec, no counter should run unless the corresponding bit in mcountinhibit
is cleared. This patch just follows the spec.

Quoted 5 lines

I don?t understand your reply. The privileged spec just says how the CSRs behave, it doesn?t say that you need to make an SBI call (which isn?t part of the privileged spec) for cycle and instret to count. Requiring that is unnecessarily hostile; in practice, everything will want those two counters to be enabled, because arbitrary userspace software wants to use them.

That's a security risk. One rogue process can have access to cycle & instructions of the entire kernel & M-mode firmware.
The counters should report a value only if it is being asked to start/stop a userspace application (e.g. perf).

Quoted 7 lines

We can keep CY & IR bits enabled in OpenSBI but it must be disabled by the Linux kernel PMU driver by default.
The effect will remain the same.

Once sscopmf is implemented, there is a plan to set MINH bit always so that supervisor/userspace don't know how many cycles
are spent while running OpenSBI.

Quoted 8 lines

That side-channel will always exist by measuring time. This just breaks valid use-cases in the name of ?security?.

__builtin_readcyclecounter is a thing and needs to work otherwise you *will* break software. At the end of the day I don?t care what you do in the Linux kernel, but I do care what gets done in the platform firmware that breaks existing 3rd-party userspace software on FreeBSD.

Ahh okay. I didn't know about __builtin_readcyclecounter. Ofcourse, we can't break userspace. I will revise the patch to enable CY & IR.

I will check if Linux user space has such a requirement too.

What about a setting MINH bit in sscofpmf extension[1] implementation? Does __builtin_readcyclecounter expect to report the counter for all the modes ?

[1] https://lists.riscv.org/g/tech-privileged/message/452?p=,,,20,0,0,0::Created,,fast+track,20,2,20,80278800

Quoted 2 lines

Jess

Signature · 2 lines
Regards,
Atish
#16 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

In reply to Atish Patra
Quoted 26 lines · Atish Patra
Quoted 24 lines · Jessica Clarke
Quoted 21 lines · Atish Patra
Quoted 9 lines · Jessica Clarke
Quoted 7 lines · Atish Patra

Currently, all bits in mcountern are enabled unconditionally at boot time. With SBI PMU extension, this should enabled only during performance monitoring for a particular event except the TM bit. However, this is done only if mcountinhibit is implemented because the supervisor mode can not start/stop any event without mcountinhibit.

Quoted 5 lines
Quoted 2 lines

Similarly, supervisor should take care enabling scounteren which allows U-mode to access pmu counters. Disable all bits in scounteren in M-mode.

Turning off CY or IR seems like a bad idea to me. Similarly, all of CY, IR and TM should be enabled in scounteren by default, this is just needlessly hostile.

This happens only if the platform supports mcountinhibit. As per the priv spec, no counter should run unless the corresponding bit in mcountinhibit
is cleared. This patch just follows the spec.

Quoted 8 lines
Quoted 5 lines

I don?t understand your reply. The privileged spec just says how the CSRs behave, it doesn?t say that you need to make an SBI call (which isn?t part of the privileged spec) for cycle and instret to count. Requiring that is unnecessarily hostile; in practice, everything will want those two counters to be enabled, because arbitrary userspace software wants to use them.

That's a security risk. One rogue process can have access to cycle & instructions of the entire kernel & M-mode firmware.

For the uninformed (me), can you elaborate on this risk?

Quoted 27 lines

The counters should report a value only if it is being asked to start/stop a userspace application (e.g. perf).

We can keep CY & IR bits enabled in OpenSBI but it must be disabled by the Linux kernel PMU driver by default.
The effect will remain the same.

Once sscopmf is implemented, there is a plan to set MINH bit always so that supervisor/userspace don't know how many cycles
are spent while running OpenSBI.

They should

Quoted 5 lines

never be disabled by OpenSBI unless S-mode explicitly asks for them to be disabled.

Jess

--
Regards,
Atish

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

#17 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

In reply to Atish Patra
Quoted 1 line

What about a setting MINH bit in sscofpmf extension[1] implementation?

Sorry for getting late to the discussion. I think it needs to be re-iterated that CY and IR are not part of Sscofpmf extension. There are no corresponding mhpmevent registers for them. I asked Greg about this in a private thread and if I understood it correctly, the reason for not tackling CY and IR is that it would cause the extension to fall out of the fast-track process.

So all in all, Sscofpmf will not be enough to tackle the sampling of neither of those two. Unless there will be a copy of those counters in mhpmcounters.

--
Best Regards,
Stan Kardach

#18 lore raw

PATCH v2 5/15 lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 12 lines

-----Original Message-----
From: opensbi <[email protected]> On Behalf Of Stanislaw Kardach
Sent: 05 June 2021 21:47
To: Atish Patra <[email protected]>
Cc: opensbi at lists.infradead.org
Subject: [v2,05/15] lib: sbi: Disable m/scounteren & enable mcountinhibit

Quoted 1 line

What about a setting MINH bit in sscofpmf extension[1] implementation?

Quoted 8 lines

Sorry for getting late to the discussion. I think it needs to be re-iterated that CY and IR are not part of Sscofpmf extension. There are no corresponding mhpmevent registers for them. I asked Greg about this in a private thread and if I understood it correctly, the reason for not tackling CY and IR is that it would cause the extension to fall out of the fast-track process.

So all in all, Sscofpmf will not be enough to tackle the sampling of neither of those two. Unless there will be a copy of those counters in mhpmcounters.

Even if CY and IR are not part of Sscofpmf extension, we still have mechanism to start/stop these counters via mcountinhibit so software (Kernel and and Hypervisors) can use SBI PMU calls to start/stop these counters only for Processes/Guest/VMs that have explicitly requested it.

To address this nature of CY and IR, the filter flags of SBI PMU config matching call are defined as optional for the SBI implementation so these filter flags can be ignored for CY and IR counters.

Regards,
Anup

Quoted 10 lines

--
Best Regards,
Stan Kardach

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

#19 lore raw

PATCH v2 6/15 include: Add a list empty check function

In reply to Atish Patra

Implement a list helper function that checks for empty lists.

---
 include/sbi/sbi_list.h | 11 +++++++++++
 1 file changed, 11 insertions(+)
include/sbi/sbi_list.h +11 -0
index 1174ad274c54..b1178dfc9b8e 100644
@@ -43,6 +43,17 @@ static inline void __sbi_list_add(struct sbi_dlist *new,
 	next->prev = new;
 }
 
+/**
+ * Checks if the list is empty or not.
+ * @param head List head
+ *
+ * Retruns TRUE if list is empty, FALSE otherwise.
+ */
+static inline bool sbi_list_empty(struct sbi_dlist *head)
+{
+	return head->next == head;
+}
+
 /**
  * Adds the new node after the given head.
  * @param new New node that needs to be added to list.
Signature · 1 line
2.25.1
#20 lore raw

PATCH v2 7/15 lib: sbi: Remove redundant boot time print statement

In reply to Atish Patra
---
 lib/sbi/sbi_init.c | 2 --
 1 file changed, 2 deletions(-)
lib/sbi/sbi_init.c +0 -2
index 3f44a2b87152..65af5705f484 100644
@@ -137,8 +137,6 @@ static void sbi_boot_print_hart(struct sbi_scratch *scratch, u32 hartid)
 		   sbi_hart_pmp_addrbits(scratch));
 	sbi_printf("Boot HART MHPM Count      : %d\n",
 		   sbi_hart_mhpm_count(scratch));
-	sbi_printf("Boot HART MHPM Count      : %d\n",
-		   sbi_hart_mhpm_count(scratch));
 	sbi_hart_delegation_dump(scratch, "Boot HART ", "         ");
 }
 
Signature · 1 line
2.25.1
#21 lore raw

PATCH v2 7/15 lib: sbi: Remove redundant boot time print statement

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 2 lines
Quoted 22 lines

---
?lib/sbi/sbi_init.c | 2 --
?1 file changed, 2 deletions(-)

lib/sbi/sbi_init.c +0 -2
index 3f44a2b87152..65af5705f484 100644
@@ -137,8 +137,6 @@ static void sbi_boot_print_hart(struct
 sbi_scratch *scratch, u32 hartid)
 ?????????????????? sbi_hart_pmp_addrbits(scratch));
 ????????sbi_printf("Boot HART MHPM Count????? : %d\n",
 ?????????????????? sbi_hart_mhpm_count(scratch));
-???????sbi_printf("Boot HART MHPM Count????? : %d\n",
-????????????????? sbi_hart_mhpm_count(scratch));
 ????????sbi_hart_delegation_dump(scratch, "Boot HART ", "???????? ");
 ?}

?

Signature · 1 line
2.25.1
#22 lore raw

PATCH v2 8/15 lib: sbi: Use csr_read/write_num to read/update PMU counters

In reply to Atish Patra

Currently, csr_read/write_num functions are used to read/write PMP related CSRs where CSR value is decided at runtime. Expand this function to include PMU related CSRs as well.

---
 lib/sbi/riscv_asm.c | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
lib/sbi/riscv_asm.c +35 -0
index 8c54c11147e7..4c24a5132195 100644
@@ -118,6 +118,21 @@ unsigned long csr_read_num(int csr_num)
 	switch (csr_num) {
 	switchcase_csr_read_16(CSR_PMPCFG0, ret)
 	switchcase_csr_read_64(CSR_PMPADDR0, ret)
+	switchcase_csr_read(CSR_MCYCLE, ret)
+	switchcase_csr_read(CSR_MINSTRET, ret)
+	switchcase_csr_read(CSR_MHPMCOUNTER3, ret)
+	switchcase_csr_read_4(CSR_MHPMCOUNTER4, ret)
+	switchcase_csr_read_8(CSR_MHPMCOUNTER8, ret)
+	switchcase_csr_read_16(CSR_MHPMCOUNTER16, ret)
+#if __riscv_xlen == 32
+	switchcase_csr_read(CSR_MCYCLEH, ret)
+	switchcase_csr_read(CSR_MINSTRETH, ret)
+	switchcase_csr_read(CSR_MHPMCOUNTER3H, ret)
+	switchcase_csr_read_4(CSR_MHPMCOUNTER4H, ret)
+	switchcase_csr_read_8(CSR_MHPMCOUNTER8H, ret)
+	switchcase_csr_read_16(CSR_MHPMCOUNTER16H, ret)
+#endif
+
 	default:
 		break;
 	};
@@ -161,6 +176,26 @@ void csr_write_num(int csr_num, unsigned long val)
 	switch (csr_num) {
 	switchcase_csr_write_16(CSR_PMPCFG0, val)
 	switchcase_csr_write_64(CSR_PMPADDR0, val)
+	switchcase_csr_write(CSR_MCYCLE, val)
+	switchcase_csr_write(CSR_MINSTRET, val)
+	switchcase_csr_write(CSR_MHPMCOUNTER3, val)
+	switchcase_csr_write_4(CSR_MHPMCOUNTER4, val)
+	switchcase_csr_write_8(CSR_MHPMCOUNTER8, val)
+	switchcase_csr_write_16(CSR_MHPMCOUNTER16, val)
+#if __riscv_xlen == 32
+	switchcase_csr_write(CSR_MCYCLEH, val)
+	switchcase_csr_write(CSR_MINSTRETH, val)
+	switchcase_csr_write(CSR_MHPMCOUNTER3H, val)
+	switchcase_csr_write_4(CSR_MHPMCOUNTER4H, val)
+	switchcase_csr_write_8(CSR_MHPMCOUNTER8H, val)
+	switchcase_csr_write_16(CSR_MHPMCOUNTER16H, val)
+#endif
+	switchcase_csr_write(CSR_MCOUNTINHIBIT, val)
+	switchcase_csr_write(CSR_MHPMEVENT3, val)
+	switchcase_csr_write_4(CSR_MHPMEVENT4, val)
+	switchcase_csr_write_8(CSR_MHPMEVENT8, val)
+	switchcase_csr_write_16(CSR_MHPMEVENT16, val)
+
 	default:
 		break;
 	};
Signature · 1 line
2.25.1
#23 lore raw

PATCH v2 8/15 lib: sbi: Use csr_read/write_num to read/update PMU counters

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 7 lines

Currently, csr_read/write_num functions are used to read/write PMP related
CSRs where CSR value is decided at runtime. Expand this function to include
PMU related CSRs as well.

Quoted 62 lines

---
?lib/sbi/riscv_asm.c | 35 +++++++++++++++++++++++++++++++++++ ?1 file changed, 35 insertions(+)

lib/sbi/riscv_asm.c +15 -0
index 8c54c11147e7..4c24a5132195 100644
@@ -118,6 +118,21 @@ unsigned long csr_read_num(int csr_num)
 ????????switch (csr_num) {
 ????????switchcase_csr_read_16(CSR_PMPCFG0, ret)
 ????????switchcase_csr_read_64(CSR_PMPADDR0, ret)
+???????switchcase_csr_read(CSR_MCYCLE, ret)
+???????switchcase_csr_read(CSR_MINSTRET, ret)
+???????switchcase_csr_read(CSR_MHPMCOUNTER3, ret)
+???????switchcase_csr_read_4(CSR_MHPMCOUNTER4, ret)
+???????switchcase_csr_read_8(CSR_MHPMCOUNTER8, ret)
+???????switchcase_csr_read_16(CSR_MHPMCOUNTER16, ret)
+#if __riscv_xlen == 32
+???????switchcase_csr_read(CSR_MCYCLEH, ret)
+???????switchcase_csr_read(CSR_MINSTRETH, ret)
+???????switchcase_csr_read(CSR_MHPMCOUNTER3H, ret)
+???????switchcase_csr_read_4(CSR_MHPMCOUNTER4H, ret)
+???????switchcase_csr_read_8(CSR_MHPMCOUNTER8H, ret)
+???????switchcase_csr_read_16(CSR_MHPMCOUNTER16H, ret)
+#endif
+

????????default:
????????????????break;
????????};

lib/sbi/riscv_asm.c +20 -0
@@ -161,6 +176,26 @@ void csr_write_num(int csr_num, unsigned long
 val)
 ????????switch (csr_num) {
 ????????switchcase_csr_write_16(CSR_PMPCFG0, val)
 ????????switchcase_csr_write_64(CSR_PMPADDR0, val)
+???????switchcase_csr_write(CSR_MCYCLE, val)
+???????switchcase_csr_write(CSR_MINSTRET, val)
+???????switchcase_csr_write(CSR_MHPMCOUNTER3, val)
+???????switchcase_csr_write_4(CSR_MHPMCOUNTER4, val)
+???????switchcase_csr_write_8(CSR_MHPMCOUNTER8, val)
+???????switchcase_csr_write_16(CSR_MHPMCOUNTER16, val)
+#if __riscv_xlen == 32
+???????switchcase_csr_write(CSR_MCYCLEH, val)
+???????switchcase_csr_write(CSR_MINSTRETH, val)
+???????switchcase_csr_write(CSR_MHPMCOUNTER3H, val)
+???????switchcase_csr_write_4(CSR_MHPMCOUNTER4H, val)
+???????switchcase_csr_write_8(CSR_MHPMCOUNTER8H, val)
+???????switchcase_csr_write_16(CSR_MHPMCOUNTER16H, val)
+#endif
+???????switchcase_csr_write(CSR_MCOUNTINHIBIT, val)
+???????switchcase_csr_write(CSR_MHPMEVENT3, val)
+???????switchcase_csr_write_4(CSR_MHPMEVENT4, val)
+???????switchcase_csr_write_8(CSR_MHPMEVENT8, val)
+???????switchcase_csr_write_16(CSR_MHPMEVENT16, val)
+

????????default:
????????????????break;
????????};

Signature · 1 line
2.25.1
#24 lore raw

PATCH v2 8/15 lib: sbi: Use csr_read/write_num to read/update PMU counters

In reply to Atish Patra
Quoted 10 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 08/15] lib: sbi: Use csr_read/write_num to read/update PMU counters

Quoted 5 lines

Currently, csr_read/write_num functions are used to read/write PMP related CSRs where CSR value is decided at runtime. Expand this function to include PMU related CSRs as well.

Looks good to me.

Regards,
Anup

Quoted 57 lines
---
 lib/sbi/riscv_asm.c | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
lib/sbi/riscv_asm.c index renamed from lib/sbi/riscv_asm.c +0 -0

8c54c11147e7..4c24a5132195 100644

lib/sbi/riscv_asm.c +6 -0
@@ -118,6 +118,21 @@ unsigned long csr_read_num(int csr_num)
 	switch (csr_num) {
 	switchcase_csr_read_16(CSR_PMPCFG0, ret)
 	switchcase_csr_read_64(CSR_PMPADDR0, ret)
+	switchcase_csr_read(CSR_MCYCLE, ret)
+	switchcase_csr_read(CSR_MINSTRET, ret)
+	switchcase_csr_read(CSR_MHPMCOUNTER3, ret)
+	switchcase_csr_read_4(CSR_MHPMCOUNTER4, ret)
+	switchcase_csr_read_8(CSR_MHPMCOUNTER8, ret)
+	switchcase_csr_read_16(CSR_MHPMCOUNTER16, ret) #if

__riscv_xlen == 32

lib/sbi/riscv_asm.c +13 -0
+	switchcase_csr_read(CSR_MCYCLEH, ret)
+	switchcase_csr_read(CSR_MINSTRETH, ret)
+	switchcase_csr_read(CSR_MHPMCOUNTER3H, ret)
+	switchcase_csr_read_4(CSR_MHPMCOUNTER4H, ret)
+	switchcase_csr_read_8(CSR_MHPMCOUNTER8H, ret)
+	switchcase_csr_read_16(CSR_MHPMCOUNTER16H, ret) #endif
+
 	default:
 		break;
 	};
@@ -161,6 +176,26 @@ void csr_write_num(int csr_num, unsigned long val)
 	switch (csr_num) {
 	switchcase_csr_write_16(CSR_PMPCFG0, val)
 	switchcase_csr_write_64(CSR_PMPADDR0, val)
+	switchcase_csr_write(CSR_MCYCLE, val)
+	switchcase_csr_write(CSR_MINSTRET, val)
+	switchcase_csr_write(CSR_MHPMCOUNTER3, val)
+	switchcase_csr_write_4(CSR_MHPMCOUNTER4, val)
+	switchcase_csr_write_8(CSR_MHPMCOUNTER8, val)
+	switchcase_csr_write_16(CSR_MHPMCOUNTER16, val) #if

__riscv_xlen == 32

lib/sbi/riscv_asm.c +12 -1
+	switchcase_csr_write(CSR_MCYCLEH, val)
+	switchcase_csr_write(CSR_MINSTRETH, val)
+	switchcase_csr_write(CSR_MHPMCOUNTER3H, val)
+	switchcase_csr_write_4(CSR_MHPMCOUNTER4H, val)
+	switchcase_csr_write_8(CSR_MHPMCOUNTER8H, val)
+	switchcase_csr_write_16(CSR_MHPMCOUNTER16H, val) #endif
+	switchcase_csr_write(CSR_MCOUNTINHIBIT, val)
+	switchcase_csr_write(CSR_MHPMEVENT3, val)
+	switchcase_csr_write_4(CSR_MHPMEVENT4, val)
+	switchcase_csr_write_8(CSR_MHPMEVENT8, val)
+	switchcase_csr_write_16(CSR_MHPMEVENT16, val)
+
 	default:
 		break;
 	};
--

2.25.1

#25 lore raw

PATCH v2 9/15 lib: sbi: Add PMU specific platform hooks

In reply to Atish Patra

A platform hook to initialize PMU allows platform vendors to provide their own mechanism to define pmu event-counter mappings in addition to the DT based approach.

Another platform hook that allows platform vendors customize the final mhpmevent value configuration.

---
 include/sbi/sbi_platform.h | 39 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)
include/sbi/sbi_platform.h +39 -0
index f8074d28db65..8e6caea6965b 100644
@@ -89,6 +89,12 @@ struct sbi_platform_operations {
 	/** Initialize (or populate) domains for the platform */
 	int (*domains_init)(void);
 
+	/** Initialize hw performance counters */
+	int (*pmu_init)(void);
+
+	/** Get platform specific mhpmevent value */
+	uint64_t (*pmu_xlate_to_mhpmevent)(uint32_t event_idx, uint64_t data);
+
 	/** Initialize the platform console */
 	int (*console_init)(void);
 
@@ -391,6 +397,39 @@ static inline int sbi_platform_domains_init(const struct sbi_platform *plat)
 	return 0;
 }
 
+/**
+ * Setup hw PMU events for the platform
+ *
+ * @param plat pointer to struct sbi_platform
+ *
+ * @return 0 on success and negative error code on failure
+ */
+static inline int sbi_platform_pmu_init(const struct sbi_platform *plat)
+{
+	if (plat && sbi_platform_ops(plat)->pmu_init)
+		return sbi_platform_ops(plat)->pmu_init();
+	return 0;
+}
+
+/**
+ * Get the value to be written in mhpmeventx for event_idx
+ *
+ * @param plat pointer to struct sbi_platform
+ * @param event_idx ID of the PMU event
+ * @param data Additional configuration data passed from supervisor software
+ *
+ * @return expected value by the platform or 0 if platform doesn't know about
+ * the event
+ */
+static inline int sbi_platform_pmu_xlate_to_mhpmevent(const struct sbi_platform *plat,
+						      uint32_t event_idx, uint64_t data)
+{
+	if (plat && sbi_platform_ops(plat)->pmu_xlate_to_mhpmevent)
+		return sbi_platform_ops(plat)->pmu_xlate_to_mhpmevent(event_idx,
+								      data);
+	return 0;
+}
+
 /**
  * Initialize the platform console
  *
Signature · 1 line
2.25.1
#26 lore raw

PATCH v2 9/15 lib: sbi: Add PMU specific platform hooks

Quoted 63 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 09/15] lib: sbi: Add PMU specific platform hooks

A platform hook to initialize PMU allows platform vendors to provide their own mechanism to define pmu event-counter mappings in addition to the DT based approach.

Another platform hook that allows platform vendors customize the final mhpmevent value configuration.

---
 include/sbi/sbi_platform.h | 39
++++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)
include/sbi/sbi_platform.h index renamed from include/sbi/sbi_platform.h +0 -0

f8074d28db65..8e6caea6965b 100644

include/sbi/sbi_platform.h +24 -0
@@ -89,6 +89,12 @@ struct sbi_platform_operations {
 	/** Initialize (or populate) domains for the platform */
 	int (*domains_init)(void);
 
+	/** Initialize hw performance counters */
+	int (*pmu_init)(void);
+
+	/** Get platform specific mhpmevent value */
+	uint64_t (*pmu_xlate_to_mhpmevent)(uint32_t event_idx, uint64_t
 data);
+
 	/** Initialize the platform console */
 	int (*console_init)(void);
@@ -391,6 +397,39 @@ static inline int sbi_platform_domains_init(const
 struct sbi_platform *plat)
 	return 0;
 }
 
+/**
+ * Setup hw PMU events for the platform
+ *
+ * @param plat pointer to struct sbi_platform
+ *
+ * @return 0 on success and negative error code on failure  */ static
+inline int sbi_platform_pmu_init(const struct sbi_platform *plat) {
+	if (plat && sbi_platform_ops(plat)->pmu_init)
+		return sbi_platform_ops(plat)->pmu_init();
+	return 0;
+}
+
+/**
+ * Get the value to be written in mhpmeventx for event_idx
+ *
+ * @param plat pointer to struct sbi_platform
+ * @param event_idx ID of the PMU event
+ * @param data Additional configuration data passed from supervisor

include/sbi/sbi_platform.h static inline int sbi_platform_domains_init(const · line 428

Quoted 10 lines
include/sbi/sbi_platform.h +8 -0
+software
+ *
+ * @return expected value by the platform or 0 if platform doesn't know
+about
+ * the event
+ */
+static inline int sbi_platform_pmu_xlate_to_mhpmevent(const struct
 sbi_platform *plat,
+						      uint32_t event_idx,
 uint64_t data) {

Return value should be "uint64_t" instead of "int"

Quoted 11 lines
include/sbi/sbi_platform.h +2 -0
+	if (plat && sbi_platform_ops(plat)->pmu_xlate_to_mhpmevent)
+		return sbi_platform_ops(plat)-
Quoted 1 line

pmu_xlate_to_mhpmevent(event_idx,

include/sbi/sbi_platform.h +4 -1
+								      data);
+	return 0;
+}
+
 /**
  * Initialize the platform console
  *
--
Quoted 1 line

2.25.1

Otherwise looks good to me.

Regards,
Anup

#27 lore raw

PATCH v2 9/15 lib: sbi: Add PMU specific platform hooks

Quoted 68 lines · Anup Patel
Quoted 68 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 09/15] lib: sbi: Add PMU specific platform hooks

A platform hook to initialize PMU allows platform vendors to provide their own mechanism to define pmu event-counter mappings in addition to the DT based approach.

Another platform hook that allows platform vendors customize the final mhpmevent value configuration.

---
 include/sbi/sbi_platform.h | 39
++++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)
include/sbi/sbi_platform.h index renamed from include/sbi/sbi_platform.h +0 -0

f8074d28db65..8e6caea6965b 100644

include/sbi/sbi_platform.h +28 -0
@@ -89,6 +89,12 @@ struct sbi_platform_operations {
      /** Initialize (or populate) domains for the platform */
      int (*domains_init)(void);
 
+     /** Initialize hw performance counters */
+     int (*pmu_init)(void);
+
+     /** Get platform specific mhpmevent value */
+     uint64_t (*pmu_xlate_to_mhpmevent)(uint32_t event_idx, uint64_t
 data);
+
      /** Initialize the platform console */
      int (*console_init)(void);
@@ -391,6 +397,39 @@ static inline int sbi_platform_domains_init(const
 struct sbi_platform *plat)
      return 0;
 }
 
+/**
+ * Setup hw PMU events for the platform
+ *
+ * @param plat pointer to struct sbi_platform
+ *
+ * @return 0 on success and negative error code on failure  */ static
+inline int sbi_platform_pmu_init(const struct sbi_platform *plat) {
+     if (plat && sbi_platform_ops(plat)->pmu_init)
+             return sbi_platform_ops(plat)->pmu_init();
+     return 0;
+}
+
+/**
+ * Get the value to be written in mhpmeventx for event_idx
+ *
+ * @param plat pointer to struct sbi_platform
+ * @param event_idx ID of the PMU event
+ * @param data Additional configuration data passed from supervisor
+software
+ *
+ * @return expected value by the platform or 0 if platform doesn't know
+about
Quoted 9 lines

include/sbi/sbi_platform.h static inline int sbi_platform_domains_init(const · line 428

Quoted 6 lines
include/sbi/sbi_platform.h +4 -0
+ * the event
+ */
+static inline int sbi_platform_pmu_xlate_to_mhpmevent(const struct
 sbi_platform *plat,
+                                                   uint32_t event_idx,
 uint64_t data) {

Return value should be "uint64_t" instead of "int"

Thanks for catching it.

Quoted 24 lines
Quoted 11 lines
include/sbi/sbi_platform.h +2 -0
+     if (plat && sbi_platform_ops(plat)->pmu_xlate_to_mhpmevent)
+             return sbi_platform_ops(plat)-
Quoted 1 line

pmu_xlate_to_mhpmevent(event_idx,

include/sbi/sbi_platform.h +4 -1
+                                                                   data);
+     return 0;
+}
+
 /**
  * Initialize the platform console
  *
--
Quoted 1 line

2.25.1

Otherwise looks good to me.

Regards,
Anup

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

Signature · 2 lines
Regards,
Atish
#28 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

In reply to Atish Patra

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of event to counter mapping & mhpmevent value configuration. That means, it expects platform hooks will be used to set up the mapping and provide the mhpmevent value at runtime.

---
 include/sbi/sbi_ecall_interface.h | 138 ++++++-
 include/sbi/sbi_error.h           |   2 +
 include/sbi/sbi_pmu.h             |  73 ++++
 lib/sbi/objects.mk                |   1 +
 lib/sbi/sbi_init.c                |   9 +
 lib/sbi/sbi_pmu.c                 | 600 ++++++++++++++++++++++++++++++
 6 files changed, 822 insertions(+), 1 deletion(-)
 create mode 100644 include/sbi/sbi_pmu.h
 create mode 100644 lib/sbi/sbi_pmu.c
include/sbi/sbi_ecall_interface.h +137 -1
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@
 #define SBI_EXT_RFENCE				0x52464E43
 #define SBI_EXT_HSM				0x48534D
 #define SBI_EXT_SRST				0x53525354
+#define SBI_EXT_PMU				0x504D55
 
 /* SBI function IDs for BASE extension*/
 #define SBI_EXT_BASE_GET_SPEC_VERSION		0x0
@@ -91,6 +92,139 @@
 #define SBI_SRST_RESET_REASON_NONE	0x0
 #define SBI_SRST_RESET_REASON_SYSFAIL	0x1
 
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS	0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO	0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH	0x2
+#define SBI_EXT_PMU_COUNTER_START	0x3
+#define SBI_EXT_PMU_COUNTER_STOP	0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ	0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+	SBI_PMU_HW_NO_EVENT			= 0,
+	SBI_PMU_HW_CPU_CYCLES			= 1,
+	SBI_PMU_HW_INSTRUCTIONS			= 2,
+	SBI_PMU_HW_CACHE_REFERENCES		= 3,
+	SBI_PMU_HW_CACHE_MISSES			= 4,
+	SBI_PMU_HW_BRANCH_INSTRUCTIONS		= 5,
+	SBI_PMU_HW_BRANCH_MISSES		= 6,
+	SBI_PMU_HW_BUS_CYCLES			= 7,
+	SBI_PMU_HW_STALLED_CYCLES_FRONTEND	= 8,
+	SBI_PMU_HW_STALLED_CYCLES_BACKEND	= 9,
+	SBI_PMU_HW_REF_CPU_CYCLES		= 10,
+
+	SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *       { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *       { read, write, prefetch } x
+ *       { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+	SBI_PMU_HW_CACHE_L1D		= 0,
+	SBI_PMU_HW_CACHE_L1I		= 1,
+	SBI_PMU_HW_CACHE_LL		= 2,
+	SBI_PMU_HW_CACHE_DTLB		= 3,
+	SBI_PMU_HW_CACHE_ITLB		= 4,
+	SBI_PMU_HW_CACHE_BPU		= 5,
+	SBI_PMU_HW_CACHE_NODE		= 6,
+
+	SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+	SBI_PMU_HW_CACHE_OP_READ	= 0,
+	SBI_PMU_HW_CACHE_OP_WRITE	= 1,
+	SBI_PMU_HW_CACHE_OP_PREFETCH	= 2,
+
+	SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+	SBI_PMU_HW_CACHE_RESULT_ACCESS	= 0,
+	SBI_PMU_HW_CACHE_RESULT_MISS	= 1,
+
+	SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if the hardware
+ * does not support performance events. These events are encoded as a raw
+ * event type in Linux kernel perf framework.
+ */
+enum sbi_pmu_fw_event_code_id {
+	SBI_PMU_FW_MISALIGNED_LOAD	= 0,
+	SBI_PMU_FW_MISALIGNED_STORE	= 1,
+	SBI_PMU_FW_ACCESS_LOAD		= 2,
+	SBI_PMU_FW_ACCESS_STORE		= 3,
+	SBI_PMU_FW_ILLEGAL_INSN		= 4,
+	SBI_PMU_FW_SET_TIMER		= 5,
+	SBI_PMU_FW_IPI_SENT		= 6,
+	SBI_PMU_FW_IPI_RECVD		= 7,
+	SBI_PMU_FW_FENCE_I_SENT		= 8,
+	SBI_PMU_FW_FENCE_I_RECVD	= 9,
+	SBI_PMU_FW_SFENCE_VMA_SENT	= 10,
+	SBI_PMU_FW_SFENCE_VMA_RCVD	= 11,
+	SBI_PMU_FW_SFENCE_VMA_ASID_SENT	= 12,
+	SBI_PMU_FW_SFENCE_VMA_ASID_RCVD	= 13,
+
+	SBI_PMU_FW_HFENCE_GVMA_SENT	= 14,
+	SBI_PMU_FW_HFENCE_GVMA_RCVD	= 15,
+	SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+	SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+	SBI_PMU_FW_HFENCE_VVMA_SENT	= 18,
+	SBI_PMU_FW_HFENCE_VVMA_RCVD	= 19,
+	SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+	SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+	SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+	SBI_PMU_EVENT_TYPE_HW				= 0x0,
+	SBI_PMU_EVENT_TYPE_HW_CACHE			= 0x1,
+	SBI_PMU_EVENT_TYPE_HW_RAW			= 0x2,
+	SBI_PMU_EVENT_TYPE_FW				= 0xf,
+	SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+	SBI_PMU_CTR_TYPE_HW = 0,
+	SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH	(1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE	(1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START	(1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH	(1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH	(1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH	(1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH	(1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH	(1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */
 #define SBI_SPEC_VERSION_MAJOR_OFFSET		24
 #define SBI_SPEC_VERSION_MAJOR_MASK		0x7f
 #define SBI_SPEC_VERSION_MINOR_MASK		0xffffff
@@ -107,8 +241,10 @@
 #define SBI_ERR_DENIED				-4
 #define SBI_ERR_INVALID_ADDRESS			-5
 #define SBI_ERR_ALREADY_AVAILABLE		-6
+#define SBI_ERR_ALREADY_STARTED			-7
+#define SBI_ERR_ALREADY_STOPPED			-8
 
-#define SBI_LAST_ERR				SBI_ERR_ALREADY_AVAILABLE
+#define SBI_LAST_ERR				SBI_ERR_ALREADY_STOPPED
 
 /* clang-format on */
 
include/sbi/sbi_error.h +2 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@
 #define SBI_EDENIED		SBI_ERR_DENIED
 #define SBI_EINVALID_ADDR	SBI_ERR_INVALID_ADDRESS
 #define SBI_EALREADY		SBI_ERR_ALREADY_AVAILABLE
+#define SBI_EALREADY_STARTED	SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED	SBI_ERR_ALREADY_STOPPED
 
 #define SBI_ENODEV		-1000
 #define SBI_ENOSYS		-1001
include/sbi/sbi_pmu.h new file +73 -0

73 lines not on this page · raw message

lib/sbi/objects.mk +1 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o
 libsbi-objs-y += sbi_ipi.o
 libsbi-objs-y += sbi_misaligned_ldst.o
 libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
 libsbi-objs-y += sbi_scratch.o
 libsbi-objs-y += sbi_string.o
 libsbi-objs-y += sbi_system.o
lib/sbi/sbi_init.c +9 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@
 #include <sbi/sbi_hsm.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_system.h>
 #include <sbi/sbi_string.h>
 #include <sbi/sbi_timer.h>
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct sbi_scratch *scratch, u32 hartid)
 	if (rc)
 		sbi_hart_hang();
 
+	sbi_pmu_init(scratch, TRUE);
+
 	sbi_boot_print_banner(scratch);
 
 	rc = sbi_platform_irqchip_init(plat, TRUE);
@@ -353,6 +356,8 @@ static void init_warm_startup(struct sbi_scratch *scratch, u32 hartid)
 	if (rc)
 		sbi_hart_hang();
 
+	sbi_pmu_init(scratch, FALSE);
+
 	rc = sbi_platform_irqchip_init(plat, FALSE);
 	if (rc)
 		sbi_hart_hang();
@@ -393,6 +398,8 @@ static void init_warm_resume(struct sbi_scratch *scratch)
 	if (rc)
 		sbi_hart_hang();
 
+	sbi_pmu_init(scratch, FALSE);
+
 	rc = sbi_hart_pmp_configure(scratch);
 	if (rc)
 		sbi_hart_hang();
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch *scratch)
 
 	sbi_platform_early_exit(plat);
 
+	sbi_pmu_exit(scratch);
+
 	sbi_timer_exit(scratch);
 
 	sbi_ipi_exit(scratch);
lib/sbi/sbi_pmu.c new file +600 -0

600 lines not on this page · raw message

Signature · 1 line
2.25.1
#29 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 513 lines

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop
the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of
event to counter mapping & mhpmevent value configuration. That means, it
expects platform hooks will be used to set up the mapping and provide the mhpmevent value at runtime.

---

?include/sbi/sbi_ecall_interface.h | 138 ++++++-
?include/sbi/sbi_error.h?????????? |?? 2 +
?include/sbi/sbi_pmu.h???????????? |? 73 ++++
?lib/sbi/objects.mk??????????????? |?? 1 +
?lib/sbi/sbi_init.c??????????????? |?? 9 +
?lib/sbi/sbi_pmu.c???????????????? | 600

++++++++++++++++++++++++++++++
?6 files changed, 822 insertions(+), 1 deletion(-) ?create mode 100644 include/sbi/sbi_pmu.h ?create mode 100644 lib/sbi/sbi_pmu.c

include/sbi/sbi_ecall_interface.h +0 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@

?#define SBI_EXT_RFENCE?????????????????????????0x52464E43 ?#define SBI_EXT_HSM????????????????????????????0x48534D ?#define SBI_EXT_SRST???????????????????????????0x53525354 +#define SBI_EXT_PMU????????????????????????????0x504D55 ?
?/* SBI function IDs for BASE extension*/ ?#define SBI_EXT_BASE_GET_SPEC_VERSION??????????0x0

include/sbi/sbi_ecall_interface.h +0 -0
@@ -91,6 +92,139 @@

?#define SBI_SRST_RESET_REASON_NONE?????0x0
?#define SBI_SRST_RESET_REASON_SYSFAIL??0x1
?

include/sbi/sbi_ecall_interface.h +61 -0
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS???????0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO???0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH??0x2
+#define SBI_EXT_PMU_COUNTER_START??????0x3
+#define SBI_EXT_PMU_COUNTER_STOP???????0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ????0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+???????SBI_PMU_HW_NO_EVENT?????????????????????= 0,
+???????SBI_PMU_HW_CPU_CYCLES???????????????????= 1,
+???????SBI_PMU_HW_INSTRUCTIONS?????????????????= 2,
+???????SBI_PMU_HW_CACHE_REFERENCES?????????????= 3,
+???????SBI_PMU_HW_CACHE_MISSES?????????????????= 4,
+???????SBI_PMU_HW_BRANCH_INSTRUCTIONS??????????= 5,
+???????SBI_PMU_HW_BRANCH_MISSES????????????????= 6,
+???????SBI_PMU_HW_BUS_CYCLES???????????????????= 7,
+???????SBI_PMU_HW_STALLED_CYCLES_FRONTEND??????= 8,
+???????SBI_PMU_HW_STALLED_CYCLES_BACKEND???????= 9,
+???????SBI_PMU_HW_REF_CPU_CYCLES???????????????= 10,
+
+???????SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *?????? { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *?????? { read, write, prefetch } x
+ *?????? { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+???????SBI_PMU_HW_CACHE_L1D????????????= 0,
+???????SBI_PMU_HW_CACHE_L1I????????????= 1,
+???????SBI_PMU_HW_CACHE_LL?????????????= 2,
+???????SBI_PMU_HW_CACHE_DTLB???????????= 3,
+???????SBI_PMU_HW_CACHE_ITLB???????????= 4,
+???????SBI_PMU_HW_CACHE_BPU????????????= 5,
+???????SBI_PMU_HW_CACHE_NODE???????????= 6,
+
+???????SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+???????SBI_PMU_HW_CACHE_OP_READ????????= 0,
+???????SBI_PMU_HW_CACHE_OP_WRITE???????= 1,
+???????SBI_PMU_HW_CACHE_OP_PREFETCH????= 2,
+
+???????SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+???????SBI_PMU_HW_CACHE_RESULT_ACCESS??= 0,
+???????SBI_PMU_HW_CACHE_RESULT_MISS????= 1,
+
+???????SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if the

hardware
+ * does not support performance events. These events are encoded as a raw
+ * event type in Linux kernel perf framework.
+ */

include/sbi/sbi_ecall_interface.h +69 -0
+enum sbi_pmu_fw_event_code_id {
+???????SBI_PMU_FW_MISALIGNED_LOAD??????= 0,
+???????SBI_PMU_FW_MISALIGNED_STORE?????= 1,
+???????SBI_PMU_FW_ACCESS_LOAD??????????= 2,
+???????SBI_PMU_FW_ACCESS_STORE?????????= 3,
+???????SBI_PMU_FW_ILLEGAL_INSN?????????= 4,
+???????SBI_PMU_FW_SET_TIMER????????????= 5,
+???????SBI_PMU_FW_IPI_SENT?????????????= 6,
+???????SBI_PMU_FW_IPI_RECVD????????????= 7,
+???????SBI_PMU_FW_FENCE_I_SENT?????????= 8,
+???????SBI_PMU_FW_FENCE_I_RECVD????????= 9,
+???????SBI_PMU_FW_SFENCE_VMA_SENT??????= 10,
+???????SBI_PMU_FW_SFENCE_VMA_RCVD??????= 11,
+???????SBI_PMU_FW_SFENCE_VMA_ASID_SENT?= 12,
+???????SBI_PMU_FW_SFENCE_VMA_ASID_RCVD?= 13,
+
+???????SBI_PMU_FW_HFENCE_GVMA_SENT?????= 14,
+???????SBI_PMU_FW_HFENCE_GVMA_RCVD?????= 15,
+???????SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+???????SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+???????SBI_PMU_FW_HFENCE_VVMA_SENT?????= 18,
+???????SBI_PMU_FW_HFENCE_VVMA_RCVD?????= 19,
+???????SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+???????SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+???????SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+???????SBI_PMU_EVENT_TYPE_HW???????????????????????????= 0x0,
+???????SBI_PMU_EVENT_TYPE_HW_CACHE?????????????????????= 0x1,
+???????SBI_PMU_EVENT_TYPE_HW_RAW???????????????????????= 0x2,
+???????SBI_PMU_EVENT_TYPE_FW???????????????????????????= 0xf,
+???????SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+???????SBI_PMU_CTR_TYPE_HW = 0,
+???????SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH????(1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE???(1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START????(1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH??????(1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH??????(1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH??????(1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH?????(1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH?????(1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */

?#define SBI_SPEC_VERSION_MAJOR_OFFSET??????????24 ?#define SBI_SPEC_VERSION_MAJOR_MASK????????????0x7f ?#define SBI_SPEC_VERSION_MINOR_MASK????????????0xffffff

include/sbi/sbi_ecall_interface.h +0 -0
@@ -107,8 +241,10 @@

?#define SBI_ERR_DENIED?????????????????????????-4 ?#define SBI_ERR_INVALID_ADDRESS????????????????????????-5 ?#define SBI_ERR_ALREADY_AVAILABLE??????????????-6

include/sbi/sbi_ecall_interface.h +2 -0
+#define SBI_ERR_ALREADY_STARTED????????????????????????-7
+#define SBI_ERR_ALREADY_STOPPED????????????????????????-8

?
-#define SBI_LAST_ERR???????????????????????????SBI_ERR_ALREADY_AVAILABLE +#define SBI_LAST_ERR???????????????????????????SBI_ERR_ALREADY_STOPPED ?
?/* clang-format on */
?

include/sbi/sbi_error.h +0 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@

?#define SBI_EDENIED????????????SBI_ERR_DENIED ?#define SBI_EINVALID_ADDR??????SBI_ERR_INVALID_ADDRESS ?#define SBI_EALREADY???????????SBI_ERR_ALREADY_AVAILABLE

include/sbi/sbi_error.h +2 -0
+#define SBI_EALREADY_STARTED???SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED???SBI_ERR_ALREADY_STOPPED

?
?#define SBI_ENODEV?????????????-1000
?#define SBI_ENOSYS?????????????-1001

include/sbi/sbi_pmu.h new file +28 -0
new file mode 100644
index 000000000000..b3010cc5c1ce
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI */
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI */
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX?????????? (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +9 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This

should be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end?? End of the event idx range for supported counters
+ * @param cmap?????? A bitmap representing counters supporting the event range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap);

include/sbi/sbi_pmu.h new file +3 -0
+
+/**
+ * Add the raw hardware event selector and supported counter

information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info? a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap);
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long

cidx_mask,
+??????????????????? unsigned long flag);

include/sbi/sbi_pmu.h new file +2 -0
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????? unsigned long flags, uint64_t ival);

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info);
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data);

include/sbi/sbi_pmu.h new file +4 -0
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk +0 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o

?libsbi-objs-y += sbi_ipi.o
?libsbi-objs-y += sbi_misaligned_ldst.o
?libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
?libsbi-objs-y += sbi_scratch.o
?libsbi-objs-y += sbi_string.o
?libsbi-objs-y += sbi_system.o

lib/sbi/sbi_init.c +0 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@

?#include <sbi/sbi_hsm.h>
?#include <sbi/sbi_ipi.h>
?#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
?#include <sbi/sbi_system.h>
?#include <sbi/sbi_string.h>
?#include <sbi/sbi_timer.h>

lib/sbi/sbi_init.c +0 -0
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, TRUE);
+
????????sbi_boot_print_banner(scratch);
?
????????rc = sbi_platform_irqchip_init(plat, TRUE);

lib/sbi/sbi_init.c +0 -0
@@ -353,6 +356,8 @@ static void init_warm_startup(struct sbi_scratch
 *scratch, u32 hartid)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, FALSE);
+
????????rc = sbi_platform_irqchip_init(plat, FALSE); ????????if (rc) ????????????????sbi_hart_hang();

lib/sbi/sbi_init.c +0 -0
@@ -393,6 +398,8 @@ static void init_warm_resume(struct sbi_scratch
 *scratch)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, FALSE);
+
????????rc = sbi_hart_pmp_configure(scratch);
????????if (rc)
????????????????sbi_hart_hang();

lib/sbi/sbi_init.c +0 -0
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch
 *scratch)

?
????????sbi_platform_early_exit(plat);
?
+???????sbi_pmu_exit(scratch);
+
????????sbi_timer_exit(scratch);
?
????????sbi_ipi_exit(scratch);

lib/sbi/sbi_pmu.c new file +57 -0
new file mode 100644
index 000000000000..ed519dfcc860
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */
+struct sbi_pmu_hw_event {
+???????unsigned long counters;
+???????unsigned long start_idx;
+???????unsigned long end_idx;
+???????/* Event selector value used only for raw events */
+???????uint64_t select;
+};
+
+/** Representation of a firmware event */
+struct sbi_pmu_fw_event {
+
+???????/* Event associated with the particular counter */
+???????unsigned long event_idx;
+
+???????/* Current value of the counter */
+???????unsigned long curr_count;
+
+???????/* A flag indicating pmu event monitoring is started */
+???????bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */
+union sbi_pmu_ctr_info {
+???????unsigned long value;
+???????struct {
+???????????????unsigned long csr:12;
+???????????????unsigned long width:6;
+#if __riscv_xlen == 32
+???????????????unsigned long reserved:13;
+#else
+???????????????unsigned long reserved:45;
+#endif
+???????????????unsigned long type:1;
+???????};
+};
+
+/* Mapping between event range and possible counters? */
+static struct sbi_pmu_hw_event hw_event_map[SBI_PMU_HW_EVENT_MAX] =

{0};

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX + SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* Contains all the information about firmwares events */
+static struct sbi_pmu_fw_event

fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] = {0};

lib/sbi/sbi_pmu.c new file +15 -0
+
+/* Maximum number of hardware events available */
+static uint32_t num_hw_events;
+/* Maximum number of hardware counters available */
+static uint32_t num_hw_ctrs;
+
+/* Maximum number of counters available */
+static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */
+#define get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >> 16)
+#define get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event

range overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise
+ */

lib/sbi/sbi_pmu.c new file +4 -0
+static bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+?????????????????????????????????? struct sbi_pmu_hw_event *evtB)
+{
+???????/* check if the range of events overlap with a previous entry

*/
+???????if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx < evtB->end_idx)) ||
+????????? ((evtA->start_idx > evtB->start_idx) && (evtA->start_idx > evtB->end_idx)))
+???????????????return FALSE;
+???????return TRUE;

lib/sbi/sbi_pmu.c new file +21 -0
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event *evt,
+??????????????????????????????????? uint64_t select_val)
+{
+
+???????if (evt->select == select_val)
+???????????????return TRUE;
+
+???????return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t *event_idx_code)
+{
+???????uint32_t event_idx_val;
+???????uint32_t event_idx_type;
+???????u32 hartid = current_hartid();
+
+???????event_idx_val = active_events[hartid][cidx];
+
+???????if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))
+???????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +23 -0
+
+???????event_idx_type = get_cidx_type(event_idx_val);
+???????if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+???????????????return SBI_EINVAL;
+
+???????*event_idx_code = get_cidx_code(event_idx_val);
+
+???????return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+????????????????????????????? uint32_t fw_evt_code)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event fevent;
+
+???????fevent = fw_event_map[hartid][fw_evt_code];
+???????*cval = fevent.curr_count;
+
+???????return 0;
+}
+
+/* Add a hardware counter read for completeness for future purpose

*/

lib/sbi/sbi_pmu.c

Quoted 8 lines
lib/sbi/sbi_pmu.c new file +8 -0
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval)
+{
+#if __riscv_xlen == 32
+???????uint32_t temp, temph = 0;
+
+???????temp = csr_read_num(CSR_MCYCLE + cidx);
+???????temph = csr_read_num(CSR_MCYCLEH + cidx);
+???????*cval = ((uint64_t)temph << 32) | temp;

The code for reading the timer is recommended to be changed to the following to prevent large discrepancies in the reading of the counter value

	do {
		temph = csr_read_num(CSR_MCYCLEH + cidx);
		temp = csr_read_num(CSR_MCYCLE + cidx);
	} while(temph != csr_read_num(CSR_MCYCLEH + cidx));
	*cval = ((uint64_t)temph << 32) | temp;
Quoted 505 lines
lib/sbi/sbi_pmu.c new file +25 -0
+#else
+???????*cval = csr_read_num(CSR_MCYCLE + cidx);
+#endif
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval)
+{
+???????int event_idx_type;
+???????uint32_t event_code;
+???????uint64_t cval64;
+
+???????event_idx_type = pmu_ctr_validate(cidx, &event_code);
+???????if (event_idx_type < 0)
+???????????????return SBI_EINVAL;
+???????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+???????????????pmu_ctr_read_fw(cidx, cval, event_code);
+???????else
+???????????????pmu_ctr_read_hw(cidx, &cval64);
+
+???????return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end, u32

cmap,
+???????????????????????????????uint64_t select)
+{
+???????int i = 0;
+???????bool is_overlap;
+???????struct sbi_pmu_hw_event *event =
&hw_event_map[num_hw_events];

lib/sbi/sbi_pmu.c new file +9 -0
+
+???????/* The first two counters are reserved by priv spec */
+???????if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1) ||
+?????????? (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap != 0x4) ||
+?????????? (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap < 0x08))
+???????????????return SBI_EDENIED;
+
+???????if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) {
+???????????????sbi_printf("Can not handle more than %d perf

events\n",
+?????????????????????????? SBI_PMU_HW_EVENT_MAX); +???????????????return SBI_EFAIL; +???????}

lib/sbi/sbi_pmu.c new file +10 -0
+
+???????event->start_idx = eidx_start;
+???????event->end_idx = eidx_end;
+???????event->counters = cmap;
+???????event->select = select;
+
+???????/* Sanity check */
+???????for (i = 0; i < num_hw_events; i++) {
+???????????????if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+???????????????/* All raw events have same event idx. Just do sanity

check on select */ +???????????????????????is_overlap = pmu_event_select_overlap(&hw_event_map[i], select); +???????????????else +???????????????????????is_overlap = pmu_event_range_overlap(&hw_event_map[i], event); +???????????????if (is_overlap) +???????????????????????return SBI_EINVALID_ADDR; +???????}
+???????num_hw_events++;

lib/sbi/sbi_pmu.c new file +6 -0
+
+???????return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are

assigned consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret. Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap)
+{
+???????if ((eidx_start > eidx_end) || eidx_start == SBI_PMU_EVENT_RAW_IDX ||
+??????????? eidx_end == SBI_PMU_EVENT_RAW_IDX) +???????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????return pmu_add_hw_event_map(eidx_start, eidx_end, cmap, 0);
+}
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap)
+{
+???????return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+?????????????????????????????????? SBI_PMU_EVENT_RAW_IDX, cmap,

select);

lib/sbi/sbi_pmu.c new file +13 -0
+}
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival)
+{
+#if __riscv_xlen == 32
+???????csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
+???????csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);
+#else
+???????csr_write_num(CSR_MCYCLE + cidx, ival);
+#endif
+}
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool

ival_update)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+???????if (cidx > num_hw_ctrs)
+???????????????return SBI_EINVAL;
+
+???????if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt))
+???????????????return SBI_EALREADY_STARTED;

lib/sbi/sbi_pmu.c new file +44 -0
+
+???????__set_bit(cidx, &mctr_en);
+???????__clear_bit(cidx, &mctr_inhbt);
+
+???????if (ival_update)
+???????????????pmu_ctr_write_hw(cidx, ival);
+
+???????csr_write(CSR_MCOUNTEREN, mctr_en);
+???????csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+???????return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+?????????????????????????? uint64_t ival, bool ival_update)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event *fevent;
+
+???????fevent = &fw_event_map[hartid][fw_evt_code];
+???????if (ival_update)
+???????????????fevent->curr_count = ival;
+???????fevent->bStarted = TRUE;
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+???????????????????? unsigned long flags, uint64_t ival)
+{
+???????int event_idx_type;
+???????uint32_t event_code;
+???????unsigned long ctr_mask = cmask << cbase;
+???????int ret = SBI_EINVAL;
+???????bool bUpdate = FALSE;
+
+???????if (cbase >= total_ctrs)
+???????????????return ret;
+
+???????if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+???????????????bUpdate = TRUE;
+
+???????for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+???????????????event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+???????????????if (event_idx_type < 0) +???????????????????????return SBI_EINVAL; +???????????????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW) +???????????????????????ret = pmu_ctr_start_fw(cbase, event_code, ival, bUpdate);
+???????????????else
+???????????????????????ret = pmu_ctr_start_hw(cbase, ival, bUpdate); +???????}

lib/sbi/sbi_pmu.c new file +10 -0
+
+???????return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx)
+{
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+???????if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt)) {
+???????????????__set_bit(cidx, &mctr_inhbt); +???????????????__clear_bit(cidx, &mctr_en); +???????????????csr_write(CSR_MCOUNTEREN, mctr_en); +???????????????csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt); +???????????????return 0;
+???????} else
+???????????????return SBI_EALREADY_STOPPED;

lib/sbi/sbi_pmu.c new file +25 -0
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code)
+{
+???????u32 hartid = current_hartid();
+
+???????fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+??????????????????? unsigned long flag)
+{
+???????u32 hartid = current_hartid();
+???????int ret = SBI_EINVAL;
+???????int event_idx_type;
+???????uint32_t event_code;
+???????unsigned long ctr_mask = cmask << cbase;
+
+???????if (cbase >= total_ctrs)
+???????????????return SBI_EINVAL;
+
+???????for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+???????????????event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+???????????????if (event_idx_type < 0)
+???????????????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????????????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+???????????????????????ret = pmu_ctr_stop_fw(cbase, event_code);
+???????????????else
+???????????????????????ret = pmu_ctr_stop_hw(cbase);
+
+???????????????if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+???????????????????????active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;
+???????}

lib/sbi/sbi_pmu.c new file +5 -0
+
+???????return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event *hw_evt,

int ctr_idx,
+?????????????????????????????????? unsigned long eindex, uint64_t data)

lib/sbi/sbi_pmu.c new file +6 -0
+{
+???????struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+???????const struct sbi_platform *plat = sbi_platform_ptr(scratch);
+???????uint64_t mhpmevent_val;
+
+???????/* Get the final mhpmevent value to be written from platform

*/
+???????mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat, eindex, data);
+
+???????if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >= SBI_PMU_HW_CTR_MAX)
+???????????????return SBI_EFAIL;
+
+???????/* TODO: The upper 8 bits of mhpmevent is reserved by sscofpmf extension.
+??????? * Update those bits based on the flags received from supervisor.
+??????? * The OVF bit also should be cleared here in case it was not cleared
+??????? * during event stop.
+??????? */
+???????csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx, mhpmevent_val);

lib/sbi/sbi_pmu.c new file +20 -0
+
+???????return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long cmask,
+????????????????????????? unsigned long event_idx, uint64_t data)
+{
+???????unsigned long ctr_mask;
+???????int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+???????struct sbi_pmu_hw_event *temp;
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+???????int evt_idx_code = get_cidx_code(event_idx);
+
+???????if (cbase > num_hw_ctrs)
+???????????????return SBI_EINVAL;
+
+???????for (i = 0; i < num_hw_events; i++) {
+???????????????temp = &hw_event_map[i];
+???????????????if ((temp->start_idx > event_idx && event_idx < temp-
Quoted 1 line

end_idx) ||

+?????????????????? (temp->start_idx < event_idx && event_idx > temp-

Quoted 1 line

end_idx))

+???????????????????????continue;
+
+???????????????/* For raw events, event data is used as the select value */
+???????????????if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-

Quoted 1 line

select != data)

+???????????????????????continue;
+
+???????????????ctr_mask = temp->counters & (cmask << cbase); +???????????????for_each_set_bit_from(cbase, &ctr_mask, SBI_PMU_HW_CTR_MAX) {
+???????????????????????if (!__test_bit(cbase, &mctr_en) && +?????????????????????????? __test_bit(cbase, &mctr_inhbt)) { +???????????????????????????????ctr_idx = cbase; +???????????????????????????????break; +???????????????????????}
+???????????????}
+???????}

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????if (ctr_idx == SBI_ENOTSUPP)
+???????????????return SBI_EFAIL;
+
+???????/* No need to update the? event selectors for fixed events */
+???????if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES &&
+?????????? evt_idx_code != SBI_PMU_HW_INSTRUCTIONS)
+???????????????ret = pmu_update_hw_mhpmevent(temp, ctr_idx,

event_idx, data);

lib/sbi/sbi_pmu.c new file +14 -0
+
+???????if (!ret)
+???????????????ret = ctr_idx;
+
+???????return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long cmask,

u32 hartid)

lib/sbi/sbi_pmu.c new file +12 -0
+{
+???????int i = 0;
+???????int fw_base;
+???????unsigned long ctr_mask = cmask << cbase;
+
+???????if (cbase <= num_hw_ctrs)
+???????????????fw_base = num_hw_ctrs + 1;
+???????else
+???????????????fw_base = cbase;
+
+???????for (i = fw_base; i < total_ctrs; i++)
+???????????????if ((active_events[hartid][i] ==

SBI_PMU_EVENT_IDX_INVALID) &&
+?????????????????? ((1UL << i) & ctr_mask))
+???????????????????????return i;

lib/sbi/sbi_pmu.c new file +5 -0
+
+???????return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data)

lib/sbi/sbi_pmu.c new file +15 -0
+{
+???????int ctr_idx = SBI_ENOTSUPP;
+???????u32 hartid = current_hartid();
+???????int event_type = get_cidx_type(event_idx);
+???????struct sbi_pmu_fw_event *fevent;
+???????uint32_t fw_evt_code;
+???????unsigned long tmp = cidx_mask << cidx_base;
+
+???????/* Do a basic sanity check of counter base & mask */
+???????if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs ||
+?????????? event_type >= SBI_PMU_EVENT_TYPE_MAX)
+???????????????return SBI_EINVAL;
+
+???????if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) {
+???????????????/* The caller wants to skip the match because it

already knows the
+??????????????? * counter idx for the given event. Verify that the counter idx
+??????????????? * is still valid.
+??????????????? */
+???????????????if (active_events[hartid][cidx_base] == SBI_PMU_EVENT_IDX_INVALID) +???????????????????????return SBI_EINVAL; +???????????????ctr_idx = cidx_base; +???????????????goto skip_match;
+???????}
+
+???????if (event_type == SBI_PMU_EVENT_TYPE_FW) { +???????????????/* Any firmware counter can be used track any firmware event */
+???????????????ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask, hartid);
+???????} else {
+???????????????ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask, event_idx, event_data);
+???????}

lib/sbi/sbi_pmu.c new file +34 -0
+
+???????if (ctr_idx < 0)
+???????????????return SBI_ENOTSUPP;
+
+???????active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+???????if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+???????????????if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+???????????????????????pmu_ctr_write_hw(ctr_idx, 0);
+???????????????if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+???????????????????????pmu_ctr_start_hw(ctr_idx, 0, false);
+???????} else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+???????????????fw_evt_code = get_cidx_code(event_idx);
+???????????????fevent = &fw_event_map[hartid][fw_evt_code];
+???????????????if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+???????????????????????fevent->curr_count = 0;
+???????????????if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+???????????????????????fevent->bStarted = TRUE;
+???????}
+
+???????return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event *fevent;
+
+???????if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+???????????????return SBI_EINVAL;
+
+???????fevent = &fw_event_map[hartid][fw_id];
+
+???????/* PMU counters will be only enabled during performance

debugging */
+???????if (unlikely(fevent->bStarted))
+???????????????fevent->curr_count++;

lib/sbi/sbi_pmu.c new file +19 -0
+
+???????return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+???????return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX);
+}
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info)
+{
+???????union sbi_pmu_ctr_info cinfo = {0};
+???????struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+???????/* Sanity check. Counter1 is not mapped at all */
+???????if (cidx >= total_ctrs || cidx == 1)
+???????????????return SBI_EINVAL;
+
+???????/* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */
+???????if (cidx <= num_hw_ctrs) { +???????????????cinfo.type = SBI_PMU_CTR_TYPE_HW; +???????????????cinfo.csr = CSR_CYCLE + cidx; +???????????????/* mcycle & minstret are always 64 bit */ +???????????????if (cidx == 0 || cidx == 2) +???????????????????????cinfo.width = 63; +???????????????else +???????????????????????cinfo.width = sbi_hart_mhpm_bits(scratch); +???????} else {
+???????????????/* it's a firmware counter */ +???????????????cinfo.type = SBI_PMU_CTR_TYPE_FW; +???????????????/* Firmware counters are XLEN bits wide */ +???????????????cinfo.width = BITS_PER_LONG - 1; +???????}

lib/sbi/sbi_pmu.c new file +32 -0
+
+???????*ctr_info = cinfo.value;
+
+???????return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid)
+{
+???????int j;
+
+???????/* Initialize the counter to event mapping table */
+???????for (j = 0; j < total_ctrs; j++)
+???????????????active_events[hartid][j] = SBI_PMU_EVENT_IDX_INVALID;
+???????for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++)
+???????????????sbi_memset(&fw_event_map[hartid][j], 0,
+????????????????????????? sizeof(struct sbi_pmu_fw_event));
+}
+
+void sbi_pmu_exit(struct sbi_scratch *scratch)
+{
+???????u32 hartid = current_hartid();
+
+???????csr_write(CSR_MCOUNTINHIBIT, -1);
+???????csr_write(CSR_MCOUNTEREN, 2);
+???????pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot)
+{
+???????const struct sbi_platform *plat;
+
+???????if (!sbi_hart_has_feature(scratch,

SBI_HART_HAS_MCOUNTINHIBIT))
+???????????????return SBI_ENOTSUPP;

lib/sbi/sbi_pmu.c new file +15 -0
+
+???????if (cold_boot) {
+???????????????plat = sbi_platform_ptr(scratch);
+???????????????/* Initialize hw pmu events */
+???????????????sbi_platform_pmu_init(plat);
+
+???????????????/* mcycle & minstret is available always */
+???????????????num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+???????????????total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+???????}
+
+???????pmu_reset_event_map(current_hartid());
+
+???????return 0;
+}
Signature · 1 line
2.25.1
#30 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

In reply to Atish Patra

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 613 lines

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop
the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of
event to counter mapping & mhpmevent value configuration. That means, it
expects platform hooks will be used to set up the mapping and provide the mhpmevent value at runtime.

---

?include/sbi/sbi_ecall_interface.h | 138 ++++++-
?include/sbi/sbi_error.h?????????? |?? 2 +
?include/sbi/sbi_pmu.h???????????? |? 73 ++++
?lib/sbi/objects.mk??????????????? |?? 1 +
?lib/sbi/sbi_init.c??????????????? |?? 9 +
?lib/sbi/sbi_pmu.c???????????????? | 600

++++++++++++++++++++++++++++++
?6 files changed, 822 insertions(+), 1 deletion(-) ?create mode 100644 include/sbi/sbi_pmu.h ?create mode 100644 lib/sbi/sbi_pmu.c

include/sbi/sbi_ecall_interface.h +0 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@

?#define SBI_EXT_RFENCE?????????????????????????0x52464E43 ?#define SBI_EXT_HSM????????????????????????????0x48534D ?#define SBI_EXT_SRST???????????????????????????0x53525354 +#define SBI_EXT_PMU????????????????????????????0x504D55 ?
?/* SBI function IDs for BASE extension*/ ?#define SBI_EXT_BASE_GET_SPEC_VERSION??????????0x0

include/sbi/sbi_ecall_interface.h +0 -0
@@ -91,6 +92,139 @@

?#define SBI_SRST_RESET_REASON_NONE?????0x0
?#define SBI_SRST_RESET_REASON_SYSFAIL??0x1
?

include/sbi/sbi_ecall_interface.h +61 -0
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS???????0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO???0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH??0x2
+#define SBI_EXT_PMU_COUNTER_START??????0x3
+#define SBI_EXT_PMU_COUNTER_STOP???????0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ????0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+???????SBI_PMU_HW_NO_EVENT?????????????????????= 0,
+???????SBI_PMU_HW_CPU_CYCLES???????????????????= 1,
+???????SBI_PMU_HW_INSTRUCTIONS?????????????????= 2,
+???????SBI_PMU_HW_CACHE_REFERENCES?????????????= 3,
+???????SBI_PMU_HW_CACHE_MISSES?????????????????= 4,
+???????SBI_PMU_HW_BRANCH_INSTRUCTIONS??????????= 5,
+???????SBI_PMU_HW_BRANCH_MISSES????????????????= 6,
+???????SBI_PMU_HW_BUS_CYCLES???????????????????= 7,
+???????SBI_PMU_HW_STALLED_CYCLES_FRONTEND??????= 8,
+???????SBI_PMU_HW_STALLED_CYCLES_BACKEND???????= 9,
+???????SBI_PMU_HW_REF_CPU_CYCLES???????????????= 10,
+
+???????SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *?????? { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *?????? { read, write, prefetch } x
+ *?????? { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+???????SBI_PMU_HW_CACHE_L1D????????????= 0,
+???????SBI_PMU_HW_CACHE_L1I????????????= 1,
+???????SBI_PMU_HW_CACHE_LL?????????????= 2,
+???????SBI_PMU_HW_CACHE_DTLB???????????= 3,
+???????SBI_PMU_HW_CACHE_ITLB???????????= 4,
+???????SBI_PMU_HW_CACHE_BPU????????????= 5,
+???????SBI_PMU_HW_CACHE_NODE???????????= 6,
+
+???????SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+???????SBI_PMU_HW_CACHE_OP_READ????????= 0,
+???????SBI_PMU_HW_CACHE_OP_WRITE???????= 1,
+???????SBI_PMU_HW_CACHE_OP_PREFETCH????= 2,
+
+???????SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+???????SBI_PMU_HW_CACHE_RESULT_ACCESS??= 0,
+???????SBI_PMU_HW_CACHE_RESULT_MISS????= 1,
+
+???????SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if the

hardware
+ * does not support performance events. These events are encoded as a raw
+ * event type in Linux kernel perf framework.
+ */

include/sbi/sbi_ecall_interface.h +69 -0
+enum sbi_pmu_fw_event_code_id {
+???????SBI_PMU_FW_MISALIGNED_LOAD??????= 0,
+???????SBI_PMU_FW_MISALIGNED_STORE?????= 1,
+???????SBI_PMU_FW_ACCESS_LOAD??????????= 2,
+???????SBI_PMU_FW_ACCESS_STORE?????????= 3,
+???????SBI_PMU_FW_ILLEGAL_INSN?????????= 4,
+???????SBI_PMU_FW_SET_TIMER????????????= 5,
+???????SBI_PMU_FW_IPI_SENT?????????????= 6,
+???????SBI_PMU_FW_IPI_RECVD????????????= 7,
+???????SBI_PMU_FW_FENCE_I_SENT?????????= 8,
+???????SBI_PMU_FW_FENCE_I_RECVD????????= 9,
+???????SBI_PMU_FW_SFENCE_VMA_SENT??????= 10,
+???????SBI_PMU_FW_SFENCE_VMA_RCVD??????= 11,
+???????SBI_PMU_FW_SFENCE_VMA_ASID_SENT?= 12,
+???????SBI_PMU_FW_SFENCE_VMA_ASID_RCVD?= 13,
+
+???????SBI_PMU_FW_HFENCE_GVMA_SENT?????= 14,
+???????SBI_PMU_FW_HFENCE_GVMA_RCVD?????= 15,
+???????SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+???????SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+???????SBI_PMU_FW_HFENCE_VVMA_SENT?????= 18,
+???????SBI_PMU_FW_HFENCE_VVMA_RCVD?????= 19,
+???????SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+???????SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+???????SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+???????SBI_PMU_EVENT_TYPE_HW???????????????????????????= 0x0,
+???????SBI_PMU_EVENT_TYPE_HW_CACHE?????????????????????= 0x1,
+???????SBI_PMU_EVENT_TYPE_HW_RAW???????????????????????= 0x2,
+???????SBI_PMU_EVENT_TYPE_FW???????????????????????????= 0xf,
+???????SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+???????SBI_PMU_CTR_TYPE_HW = 0,
+???????SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH????(1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE???(1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START????(1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH??????(1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH??????(1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH??????(1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH?????(1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH?????(1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */

?#define SBI_SPEC_VERSION_MAJOR_OFFSET??????????24 ?#define SBI_SPEC_VERSION_MAJOR_MASK????????????0x7f ?#define SBI_SPEC_VERSION_MINOR_MASK????????????0xffffff

include/sbi/sbi_ecall_interface.h +0 -0
@@ -107,8 +241,10 @@

?#define SBI_ERR_DENIED?????????????????????????-4 ?#define SBI_ERR_INVALID_ADDRESS????????????????????????-5 ?#define SBI_ERR_ALREADY_AVAILABLE??????????????-6

include/sbi/sbi_ecall_interface.h +2 -0
+#define SBI_ERR_ALREADY_STARTED????????????????????????-7
+#define SBI_ERR_ALREADY_STOPPED????????????????????????-8

?
-#define SBI_LAST_ERR???????????????????????????SBI_ERR_ALREADY_AVAILABLE +#define SBI_LAST_ERR???????????????????????????SBI_ERR_ALREADY_STOPPED ?
?/* clang-format on */
?

include/sbi/sbi_error.h +0 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@

?#define SBI_EDENIED????????????SBI_ERR_DENIED ?#define SBI_EINVALID_ADDR??????SBI_ERR_INVALID_ADDRESS ?#define SBI_EALREADY???????????SBI_ERR_ALREADY_AVAILABLE

include/sbi/sbi_error.h +2 -0
+#define SBI_EALREADY_STARTED???SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED???SBI_ERR_ALREADY_STOPPED

?
?#define SBI_ENODEV?????????????-1000
?#define SBI_ENOSYS?????????????-1001

include/sbi/sbi_pmu.h new file +28 -0
new file mode 100644
index 000000000000..b3010cc5c1ce
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI */
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI */
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX?????????? (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +9 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This

should be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end?? End of the event idx range for supported counters
+ * @param cmap?????? A bitmap representing counters supporting the event range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap);

include/sbi/sbi_pmu.h new file +3 -0
+
+/**
+ * Add the raw hardware event selector and supported counter

information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info? a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap);
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long

cidx_mask,
+??????????????????? unsigned long flag);

include/sbi/sbi_pmu.h new file +2 -0
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????? unsigned long flags, uint64_t ival);

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info);
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data);

include/sbi/sbi_pmu.h new file +4 -0
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk +0 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o

?libsbi-objs-y += sbi_ipi.o
?libsbi-objs-y += sbi_misaligned_ldst.o
?libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
?libsbi-objs-y += sbi_scratch.o
?libsbi-objs-y += sbi_string.o
?libsbi-objs-y += sbi_system.o

lib/sbi/sbi_init.c +0 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@

?#include <sbi/sbi_hsm.h>
?#include <sbi/sbi_ipi.h>
?#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
?#include <sbi/sbi_system.h>
?#include <sbi/sbi_string.h>
?#include <sbi/sbi_timer.h>

lib/sbi/sbi_init.c +0 -0
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, TRUE);
+
????????sbi_boot_print_banner(scratch);
?
????????rc = sbi_platform_irqchip_init(plat, TRUE);

lib/sbi/sbi_init.c +0 -0
@@ -353,6 +356,8 @@ static void init_warm_startup(struct sbi_scratch
 *scratch, u32 hartid)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, FALSE);
+
????????rc = sbi_platform_irqchip_init(plat, FALSE); ????????if (rc) ????????????????sbi_hart_hang();

lib/sbi/sbi_init.c +0 -0
@@ -393,6 +398,8 @@ static void init_warm_resume(struct sbi_scratch
 *scratch)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, FALSE);
+
????????rc = sbi_hart_pmp_configure(scratch);
????????if (rc)
????????????????sbi_hart_hang();

lib/sbi/sbi_init.c +0 -0
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch
 *scratch)

?
????????sbi_platform_early_exit(plat);
?
+???????sbi_pmu_exit(scratch);
+
????????sbi_timer_exit(scratch);
?
????????sbi_ipi_exit(scratch);

lib/sbi/sbi_pmu.c new file +57 -0
new file mode 100644
index 000000000000..ed519dfcc860
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */
+struct sbi_pmu_hw_event {
+???????unsigned long counters;
+???????unsigned long start_idx;
+???????unsigned long end_idx;
+???????/* Event selector value used only for raw events */
+???????uint64_t select;
+};
+
+/** Representation of a firmware event */
+struct sbi_pmu_fw_event {
+
+???????/* Event associated with the particular counter */
+???????unsigned long event_idx;
+
+???????/* Current value of the counter */
+???????unsigned long curr_count;
+
+???????/* A flag indicating pmu event monitoring is started */
+???????bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */
+union sbi_pmu_ctr_info {
+???????unsigned long value;
+???????struct {
+???????????????unsigned long csr:12;
+???????????????unsigned long width:6;
+#if __riscv_xlen == 32
+???????????????unsigned long reserved:13;
+#else
+???????????????unsigned long reserved:45;
+#endif
+???????????????unsigned long type:1;
+???????};
+};
+
+/* Mapping between event range and possible counters? */
+static struct sbi_pmu_hw_event hw_event_map[SBI_PMU_HW_EVENT_MAX] =

{0};

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX + SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* Contains all the information about firmwares events */
+static struct sbi_pmu_fw_event

fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] = {0};

lib/sbi/sbi_pmu.c new file +15 -0
+
+/* Maximum number of hardware events available */
+static uint32_t num_hw_events;
+/* Maximum number of hardware counters available */
+static uint32_t num_hw_ctrs;
+
+/* Maximum number of counters available */
+static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */
+#define get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >> 16)
+#define get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event

range overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise
+ */

lib/sbi/sbi_pmu.c new file +4 -0
+static bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+?????????????????????????????????? struct sbi_pmu_hw_event *evtB)
+{
+???????/* check if the range of events overlap with a previous entry

*/
+???????if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx < evtB->end_idx)) ||
+????????? ((evtA->start_idx > evtB->start_idx) && (evtA->start_idx > evtB->end_idx)))
+???????????????return FALSE;
+???????return TRUE;

lib/sbi/sbi_pmu.c new file +21 -0
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event *evt,
+??????????????????????????????????? uint64_t select_val)
+{
+
+???????if (evt->select == select_val)
+???????????????return TRUE;
+
+???????return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t *event_idx_code)
+{
+???????uint32_t event_idx_val;
+???????uint32_t event_idx_type;
+???????u32 hartid = current_hartid();
+
+???????event_idx_val = active_events[hartid][cidx];
+
+???????if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))
+???????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +23 -0
+
+???????event_idx_type = get_cidx_type(event_idx_val);
+???????if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+???????????????return SBI_EINVAL;
+
+???????*event_idx_code = get_cidx_code(event_idx_val);
+
+???????return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+????????????????????????????? uint32_t fw_evt_code)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event fevent;
+
+???????fevent = fw_event_map[hartid][fw_evt_code];
+???????*cval = fevent.curr_count;
+
+???????return 0;
+}
+
+/* Add a hardware counter read for completeness for future purpose

*/

lib/sbi/sbi_pmu.c new file +33 -0
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval)
+{
+#if __riscv_xlen == 32
+???????uint32_t temp, temph = 0;
+
+???????temp = csr_read_num(CSR_MCYCLE + cidx);
+???????temph = csr_read_num(CSR_MCYCLEH + cidx);
+???????*cval = ((uint64_t)temph << 32) | temp;
+#else
+???????*cval = csr_read_num(CSR_MCYCLE + cidx);
+#endif
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval)
+{
+???????int event_idx_type;
+???????uint32_t event_code;
+???????uint64_t cval64;
+
+???????event_idx_type = pmu_ctr_validate(cidx, &event_code);
+???????if (event_idx_type < 0)
+???????????????return SBI_EINVAL;
+???????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+???????????????pmu_ctr_read_fw(cidx, cval, event_code);
+???????else
+???????????????pmu_ctr_read_hw(cidx, &cval64);
+
+???????return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end, u32

cmap,
+???????????????????????????????uint64_t select)
+{
+???????int i = 0;
+???????bool is_overlap;
+???????struct sbi_pmu_hw_event *event =
&hw_event_map[num_hw_events];

lib/sbi/sbi_pmu.c new file +9 -0
+
+???????/* The first two counters are reserved by priv spec */
+???????if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1) ||
+?????????? (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap != 0x4) ||
+?????????? (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap < 0x08))
+???????????????return SBI_EDENIED;
+
+???????if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) {
+???????????????sbi_printf("Can not handle more than %d perf

events\n",
+?????????????????????????? SBI_PMU_HW_EVENT_MAX); +???????????????return SBI_EFAIL; +???????}

lib/sbi/sbi_pmu.c new file +10 -0
+
+???????event->start_idx = eidx_start;
+???????event->end_idx = eidx_end;
+???????event->counters = cmap;
+???????event->select = select;
+
+???????/* Sanity check */
+???????for (i = 0; i < num_hw_events; i++) {
+???????????????if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+???????????????/* All raw events have same event idx. Just do sanity

check on select */ +???????????????????????is_overlap = pmu_event_select_overlap(&hw_event_map[i], select); +???????????????else +???????????????????????is_overlap = pmu_event_range_overlap(&hw_event_map[i], event); +???????????????if (is_overlap) +???????????????????????return SBI_EINVALID_ADDR; +???????}
+???????num_hw_events++;

lib/sbi/sbi_pmu.c new file +6 -0
+
+???????return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are

assigned consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret. Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap)
+{
+???????if ((eidx_start > eidx_end) || eidx_start == SBI_PMU_EVENT_RAW_IDX ||
+??????????? eidx_end == SBI_PMU_EVENT_RAW_IDX) +???????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????return pmu_add_hw_event_map(eidx_start, eidx_end, cmap, 0);
+}
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap)
+{
+???????return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+?????????????????????????????????? SBI_PMU_EVENT_RAW_IDX, cmap,

select);

lib/sbi/sbi_pmu.c

Quoted 7 lines
lib/sbi/sbi_pmu.c new file +7 -0
+}
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival)
+{
+#if __riscv_xlen == 32
+???????csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
+???????csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);

The above code is recommended to be modified to:

	csr_write_num(CSR_MCYCLE + cidx, 0);
	csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);
	csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);

Regards,
Xiang W

Quoted 406 lines
lib/sbi/sbi_pmu.c new file +6 -0
+#else
+???????csr_write_num(CSR_MCYCLE + cidx, ival);
+#endif
+}
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool

ival_update)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+???????if (cidx > num_hw_ctrs)
+???????????????return SBI_EINVAL;
+
+???????if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt))
+???????????????return SBI_EALREADY_STARTED;

lib/sbi/sbi_pmu.c new file +44 -0
+
+???????__set_bit(cidx, &mctr_en);
+???????__clear_bit(cidx, &mctr_inhbt);
+
+???????if (ival_update)
+???????????????pmu_ctr_write_hw(cidx, ival);
+
+???????csr_write(CSR_MCOUNTEREN, mctr_en);
+???????csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+???????return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+?????????????????????????? uint64_t ival, bool ival_update)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event *fevent;
+
+???????fevent = &fw_event_map[hartid][fw_evt_code];
+???????if (ival_update)
+???????????????fevent->curr_count = ival;
+???????fevent->bStarted = TRUE;
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+???????????????????? unsigned long flags, uint64_t ival)
+{
+???????int event_idx_type;
+???????uint32_t event_code;
+???????unsigned long ctr_mask = cmask << cbase;
+???????int ret = SBI_EINVAL;
+???????bool bUpdate = FALSE;
+
+???????if (cbase >= total_ctrs)
+???????????????return ret;
+
+???????if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+???????????????bUpdate = TRUE;
+
+???????for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+???????????????event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+???????????????if (event_idx_type < 0) +???????????????????????return SBI_EINVAL; +???????????????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW) +???????????????????????ret = pmu_ctr_start_fw(cbase, event_code, ival, bUpdate);
+???????????????else
+???????????????????????ret = pmu_ctr_start_hw(cbase, ival, bUpdate); +???????}

lib/sbi/sbi_pmu.c new file +10 -0
+
+???????return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx)
+{
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+???????if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt)) {
+???????????????__set_bit(cidx, &mctr_inhbt); +???????????????__clear_bit(cidx, &mctr_en); +???????????????csr_write(CSR_MCOUNTEREN, mctr_en); +???????????????csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt); +???????????????return 0;
+???????} else
+???????????????return SBI_EALREADY_STOPPED;

lib/sbi/sbi_pmu.c new file +25 -0
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code)
+{
+???????u32 hartid = current_hartid();
+
+???????fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+??????????????????? unsigned long flag)
+{
+???????u32 hartid = current_hartid();
+???????int ret = SBI_EINVAL;
+???????int event_idx_type;
+???????uint32_t event_code;
+???????unsigned long ctr_mask = cmask << cbase;
+
+???????if (cbase >= total_ctrs)
+???????????????return SBI_EINVAL;
+
+???????for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+???????????????event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+???????????????if (event_idx_type < 0)
+???????????????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????????????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+???????????????????????ret = pmu_ctr_stop_fw(cbase, event_code);
+???????????????else
+???????????????????????ret = pmu_ctr_stop_hw(cbase);
+
+???????????????if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+???????????????????????active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;
+???????}

lib/sbi/sbi_pmu.c new file +5 -0
+
+???????return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event *hw_evt,

int ctr_idx,
+?????????????????????????????????? unsigned long eindex, uint64_t data)

lib/sbi/sbi_pmu.c new file +6 -0
+{
+???????struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+???????const struct sbi_platform *plat = sbi_platform_ptr(scratch);
+???????uint64_t mhpmevent_val;
+
+???????/* Get the final mhpmevent value to be written from platform

*/
+???????mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat, eindex, data);
+
+???????if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >= SBI_PMU_HW_CTR_MAX)
+???????????????return SBI_EFAIL;
+
+???????/* TODO: The upper 8 bits of mhpmevent is reserved by sscofpmf extension.
+??????? * Update those bits based on the flags received from supervisor.
+??????? * The OVF bit also should be cleared here in case it was not cleared
+??????? * during event stop.
+??????? */
+???????csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx, mhpmevent_val);

lib/sbi/sbi_pmu.c new file +20 -0
+
+???????return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long cmask,
+????????????????????????? unsigned long event_idx, uint64_t data)
+{
+???????unsigned long ctr_mask;
+???????int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+???????struct sbi_pmu_hw_event *temp;
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+???????int evt_idx_code = get_cidx_code(event_idx);
+
+???????if (cbase > num_hw_ctrs)
+???????????????return SBI_EINVAL;
+
+???????for (i = 0; i < num_hw_events; i++) {
+???????????????temp = &hw_event_map[i];
+???????????????if ((temp->start_idx > event_idx && event_idx < temp-
Quoted 1 line

end_idx) ||

+?????????????????? (temp->start_idx < event_idx && event_idx > temp-

Quoted 1 line

end_idx))

+???????????????????????continue;
+
+???????????????/* For raw events, event data is used as the select value */
+???????????????if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-

Quoted 1 line

select != data)

+???????????????????????continue;
+
+???????????????ctr_mask = temp->counters & (cmask << cbase); +???????????????for_each_set_bit_from(cbase, &ctr_mask, SBI_PMU_HW_CTR_MAX) {
+???????????????????????if (!__test_bit(cbase, &mctr_en) && +?????????????????????????? __test_bit(cbase, &mctr_inhbt)) { +???????????????????????????????ctr_idx = cbase; +???????????????????????????????break; +???????????????????????}
+???????????????}
+???????}

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????if (ctr_idx == SBI_ENOTSUPP)
+???????????????return SBI_EFAIL;
+
+???????/* No need to update the? event selectors for fixed events */
+???????if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES &&
+?????????? evt_idx_code != SBI_PMU_HW_INSTRUCTIONS)
+???????????????ret = pmu_update_hw_mhpmevent(temp, ctr_idx,

event_idx, data);

lib/sbi/sbi_pmu.c new file +14 -0
+
+???????if (!ret)
+???????????????ret = ctr_idx;
+
+???????return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long cmask,

u32 hartid)

lib/sbi/sbi_pmu.c new file +12 -0
+{
+???????int i = 0;
+???????int fw_base;
+???????unsigned long ctr_mask = cmask << cbase;
+
+???????if (cbase <= num_hw_ctrs)
+???????????????fw_base = num_hw_ctrs + 1;
+???????else
+???????????????fw_base = cbase;
+
+???????for (i = fw_base; i < total_ctrs; i++)
+???????????????if ((active_events[hartid][i] ==

SBI_PMU_EVENT_IDX_INVALID) &&
+?????????????????? ((1UL << i) & ctr_mask))
+???????????????????????return i;

lib/sbi/sbi_pmu.c new file +5 -0
+
+???????return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data)

lib/sbi/sbi_pmu.c new file +15 -0
+{
+???????int ctr_idx = SBI_ENOTSUPP;
+???????u32 hartid = current_hartid();
+???????int event_type = get_cidx_type(event_idx);
+???????struct sbi_pmu_fw_event *fevent;
+???????uint32_t fw_evt_code;
+???????unsigned long tmp = cidx_mask << cidx_base;
+
+???????/* Do a basic sanity check of counter base & mask */
+???????if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs ||
+?????????? event_type >= SBI_PMU_EVENT_TYPE_MAX)
+???????????????return SBI_EINVAL;
+
+???????if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) {
+???????????????/* The caller wants to skip the match because it

already knows the
+??????????????? * counter idx for the given event. Verify that the counter idx
+??????????????? * is still valid.
+??????????????? */
+???????????????if (active_events[hartid][cidx_base] == SBI_PMU_EVENT_IDX_INVALID) +???????????????????????return SBI_EINVAL; +???????????????ctr_idx = cidx_base; +???????????????goto skip_match;
+???????}
+
+???????if (event_type == SBI_PMU_EVENT_TYPE_FW) { +???????????????/* Any firmware counter can be used track any firmware event */
+???????????????ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask, hartid);
+???????} else {
+???????????????ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask, event_idx, event_data);
+???????}

lib/sbi/sbi_pmu.c new file +34 -0
+
+???????if (ctr_idx < 0)
+???????????????return SBI_ENOTSUPP;
+
+???????active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+???????if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+???????????????if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+???????????????????????pmu_ctr_write_hw(ctr_idx, 0);
+???????????????if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+???????????????????????pmu_ctr_start_hw(ctr_idx, 0, false);
+???????} else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+???????????????fw_evt_code = get_cidx_code(event_idx);
+???????????????fevent = &fw_event_map[hartid][fw_evt_code];
+???????????????if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+???????????????????????fevent->curr_count = 0;
+???????????????if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+???????????????????????fevent->bStarted = TRUE;
+???????}
+
+???????return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event *fevent;
+
+???????if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+???????????????return SBI_EINVAL;
+
+???????fevent = &fw_event_map[hartid][fw_id];
+
+???????/* PMU counters will be only enabled during performance

debugging */
+???????if (unlikely(fevent->bStarted))
+???????????????fevent->curr_count++;

lib/sbi/sbi_pmu.c new file +19 -0
+
+???????return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+???????return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX);
+}
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info)
+{
+???????union sbi_pmu_ctr_info cinfo = {0};
+???????struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+???????/* Sanity check. Counter1 is not mapped at all */
+???????if (cidx >= total_ctrs || cidx == 1)
+???????????????return SBI_EINVAL;
+
+???????/* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */
+???????if (cidx <= num_hw_ctrs) { +???????????????cinfo.type = SBI_PMU_CTR_TYPE_HW; +???????????????cinfo.csr = CSR_CYCLE + cidx; +???????????????/* mcycle & minstret are always 64 bit */ +???????????????if (cidx == 0 || cidx == 2) +???????????????????????cinfo.width = 63; +???????????????else +???????????????????????cinfo.width = sbi_hart_mhpm_bits(scratch); +???????} else {
+???????????????/* it's a firmware counter */ +???????????????cinfo.type = SBI_PMU_CTR_TYPE_FW; +???????????????/* Firmware counters are XLEN bits wide */ +???????????????cinfo.width = BITS_PER_LONG - 1; +???????}

lib/sbi/sbi_pmu.c new file +32 -0
+
+???????*ctr_info = cinfo.value;
+
+???????return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid)
+{
+???????int j;
+
+???????/* Initialize the counter to event mapping table */
+???????for (j = 0; j < total_ctrs; j++)
+???????????????active_events[hartid][j] = SBI_PMU_EVENT_IDX_INVALID;
+???????for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++)
+???????????????sbi_memset(&fw_event_map[hartid][j], 0,
+????????????????????????? sizeof(struct sbi_pmu_fw_event));
+}
+
+void sbi_pmu_exit(struct sbi_scratch *scratch)
+{
+???????u32 hartid = current_hartid();
+
+???????csr_write(CSR_MCOUNTINHIBIT, -1);
+???????csr_write(CSR_MCOUNTEREN, 2);
+???????pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot)
+{
+???????const struct sbi_platform *plat;
+
+???????if (!sbi_hart_has_feature(scratch,

SBI_HART_HAS_MCOUNTINHIBIT))
+???????????????return SBI_ENOTSUPP;

lib/sbi/sbi_pmu.c new file +15 -0
+
+???????if (cold_boot) {
+???????????????plat = sbi_platform_ptr(scratch);
+???????????????/* Initialize hw pmu events */
+???????????????sbi_platform_pmu_init(plat);
+
+???????????????/* mcycle & minstret is available always */
+???????????????num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+???????????????total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+???????}
+
+???????pmu_reset_event_map(current_hartid());
+
+???????return 0;
+}
Signature · 1 line
2.25.1
#31 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

Quoted 624 lines · Xiang W

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 613 lines

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop
the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of
event to counter mapping & mhpmevent value configuration. That means, it
expects platform hooks will be used to set up the mapping and provide the mhpmevent value at runtime.

---
 include/sbi/sbi_ecall_interface.h | 138 ++++++-
 include/sbi/sbi_error.h           |   2 +
 include/sbi/sbi_pmu.h             |  73 ++++
 lib/sbi/objects.mk                |   1 +
 lib/sbi/sbi_init.c                |   9 +
 lib/sbi/sbi_pmu.c                 | 600
++++++++++++++++++++++++++++++
 6 files changed, 822 insertions(+), 1 deletion(-)
 create mode 100644 include/sbi/sbi_pmu.h
 create mode 100644 lib/sbi/sbi_pmu.c
include/sbi/sbi_ecall_interface.h +62 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@
 #define SBI_EXT_RFENCE                         0x52464E43
 #define SBI_EXT_HSM                            0x48534D
 #define SBI_EXT_SRST                           0x53525354
+#define SBI_EXT_PMU                            0x504D55
 
 /* SBI function IDs for BASE extension*/
 #define SBI_EXT_BASE_GET_SPEC_VERSION          0x0
@@ -91,6 +92,139 @@
 #define SBI_SRST_RESET_REASON_NONE     0x0
 #define SBI_SRST_RESET_REASON_SYSFAIL  0x1
 
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS       0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO   0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH  0x2
+#define SBI_EXT_PMU_COUNTER_START      0x3
+#define SBI_EXT_PMU_COUNTER_STOP       0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ    0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+       SBI_PMU_HW_NO_EVENT                     = 0,
+       SBI_PMU_HW_CPU_CYCLES                   = 1,
+       SBI_PMU_HW_INSTRUCTIONS                 = 2,
+       SBI_PMU_HW_CACHE_REFERENCES             = 3,
+       SBI_PMU_HW_CACHE_MISSES                 = 4,
+       SBI_PMU_HW_BRANCH_INSTRUCTIONS          = 5,
+       SBI_PMU_HW_BRANCH_MISSES                = 6,
+       SBI_PMU_HW_BUS_CYCLES                   = 7,
+       SBI_PMU_HW_STALLED_CYCLES_FRONTEND      = 8,
+       SBI_PMU_HW_STALLED_CYCLES_BACKEND       = 9,
+       SBI_PMU_HW_REF_CPU_CYCLES               = 10,
+
+       SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *       { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *       { read, write, prefetch } x
+ *       { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+       SBI_PMU_HW_CACHE_L1D            = 0,
+       SBI_PMU_HW_CACHE_L1I            = 1,
+       SBI_PMU_HW_CACHE_LL             = 2,
+       SBI_PMU_HW_CACHE_DTLB           = 3,
+       SBI_PMU_HW_CACHE_ITLB           = 4,
+       SBI_PMU_HW_CACHE_BPU            = 5,
+       SBI_PMU_HW_CACHE_NODE           = 6,
+
+       SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+       SBI_PMU_HW_CACHE_OP_READ        = 0,
+       SBI_PMU_HW_CACHE_OP_WRITE       = 1,
+       SBI_PMU_HW_CACHE_OP_PREFETCH    = 2,
+
+       SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+       SBI_PMU_HW_CACHE_RESULT_ACCESS  = 0,
+       SBI_PMU_HW_CACHE_RESULT_MISS    = 1,
+
+       SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if the

hardware
+ * does not support performance events. These events are encoded as a raw
+ * event type in Linux kernel perf framework.
+ */

include/sbi/sbi_ecall_interface.h +71 -1
+enum sbi_pmu_fw_event_code_id {
+       SBI_PMU_FW_MISALIGNED_LOAD      = 0,
+       SBI_PMU_FW_MISALIGNED_STORE     = 1,
+       SBI_PMU_FW_ACCESS_LOAD          = 2,
+       SBI_PMU_FW_ACCESS_STORE         = 3,
+       SBI_PMU_FW_ILLEGAL_INSN         = 4,
+       SBI_PMU_FW_SET_TIMER            = 5,
+       SBI_PMU_FW_IPI_SENT             = 6,
+       SBI_PMU_FW_IPI_RECVD            = 7,
+       SBI_PMU_FW_FENCE_I_SENT         = 8,
+       SBI_PMU_FW_FENCE_I_RECVD        = 9,
+       SBI_PMU_FW_SFENCE_VMA_SENT      = 10,
+       SBI_PMU_FW_SFENCE_VMA_RCVD      = 11,
+       SBI_PMU_FW_SFENCE_VMA_ASID_SENT = 12,
+       SBI_PMU_FW_SFENCE_VMA_ASID_RCVD = 13,
+
+       SBI_PMU_FW_HFENCE_GVMA_SENT     = 14,
+       SBI_PMU_FW_HFENCE_GVMA_RCVD     = 15,
+       SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+       SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+       SBI_PMU_FW_HFENCE_VVMA_SENT     = 18,
+       SBI_PMU_FW_HFENCE_VVMA_RCVD     = 19,
+       SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+       SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+       SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+       SBI_PMU_EVENT_TYPE_HW                           = 0x0,
+       SBI_PMU_EVENT_TYPE_HW_CACHE                     = 0x1,
+       SBI_PMU_EVENT_TYPE_HW_RAW                       = 0x2,
+       SBI_PMU_EVENT_TYPE_FW                           = 0xf,
+       SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+       SBI_PMU_CTR_TYPE_HW = 0,
+       SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH    (1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE   (1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START    (1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH      (1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH      (1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH      (1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH     (1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH     (1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */
 #define SBI_SPEC_VERSION_MAJOR_OFFSET          24
 #define SBI_SPEC_VERSION_MAJOR_MASK            0x7f
 #define SBI_SPEC_VERSION_MINOR_MASK            0xffffff
@@ -107,8 +241,10 @@
 #define SBI_ERR_DENIED                         -4
 #define SBI_ERR_INVALID_ADDRESS                        -5
 #define SBI_ERR_ALREADY_AVAILABLE              -6
+#define SBI_ERR_ALREADY_STARTED                        -7
+#define SBI_ERR_ALREADY_STOPPED                        -8
 
-#define

SBI_LAST_ERR SBI_ERR_ALREADY_AVAILABLE
+#define
SBI_LAST_ERR SBI_ERR_ALREADY_STOPPED

/* clang-format on */

include/sbi/sbi_error.h +2 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@
 #define SBI_EDENIED            SBI_ERR_DENIED
 #define SBI_EINVALID_ADDR      SBI_ERR_INVALID_ADDRESS
 #define SBI_EALREADY           SBI_ERR_ALREADY_AVAILABLE
+#define SBI_EALREADY_STARTED   SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED   SBI_ERR_ALREADY_STOPPED
 
 #define SBI_ENODEV             -1000
 #define SBI_ENOSYS             -1001
include/sbi/sbi_pmu.h new file +28 -0
new file mode 100644
index 000000000000..b3010cc5c1ce
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI */
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI */
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX           (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +9 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This

should be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end End of the event idx range for supported
counters
+ * @param cmap A bitmap representing counters supporting the
event range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap);

include/sbi/sbi_pmu.h new file +3 -0
+
+/**
+ * Add the raw hardware event selector and supported counter

information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap);
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long

cidx_mask,

include/sbi/sbi_pmu.h new file +3 -0
+                    unsigned long flag);
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long

cidx_mask,

include/sbi/sbi_pmu.h new file +7 -0
+                     unsigned long flags, uint64_t ival);
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info);
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+ unsigned long flags, unsigned long
event_idx,

include/sbi/sbi_pmu.h new file +5 -0
+                         uint64_t event_data);
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk +1 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o
 libsbi-objs-y += sbi_ipi.o
 libsbi-objs-y += sbi_misaligned_ldst.o
 libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
 libsbi-objs-y += sbi_scratch.o
 libsbi-objs-y += sbi_string.o
 libsbi-objs-y += sbi_system.o
lib/sbi/sbi_init.c +3 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@
 #include <sbi/sbi_hsm.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_system.h>
 #include <sbi/sbi_string.h>
 #include <sbi/sbi_timer.h>
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
        if (rc)
                sbi_hart_hang();
 
+       sbi_pmu_init(scratch, TRUE);
+
        sbi_boot_print_banner(scratch);
 
        rc = sbi_platform_irqchip_init(plat, TRUE);
lib/sbi/sbi_init.c +2 -0
@@ -353,6 +356,8 @@ static void init_warm_startup(struct sbi_scratch
 *scratch, u32 hartid)
        if (rc)
                sbi_hart_hang();
 
+       sbi_pmu_init(scratch, FALSE);
+
        rc = sbi_platform_irqchip_init(plat, FALSE);
        if (rc)
                sbi_hart_hang();
lib/sbi/sbi_init.c +2 -0
@@ -393,6 +398,8 @@ static void init_warm_resume(struct sbi_scratch
 *scratch)
        if (rc)
                sbi_hart_hang();
 
+       sbi_pmu_init(scratch, FALSE);
+
        rc = sbi_hart_pmp_configure(scratch);
        if (rc)
                sbi_hart_hang();
lib/sbi/sbi_init.c +2 -0
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch
 *scratch)
 
        sbi_platform_early_exit(plat);
 
+       sbi_pmu_exit(scratch);
+
        sbi_timer_exit(scratch);
 
        sbi_ipi_exit(scratch);
lib/sbi/sbi_pmu.c new file +57 -0
new file mode 100644
index 000000000000..ed519dfcc860
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */
+struct sbi_pmu_hw_event {
+       unsigned long counters;
+       unsigned long start_idx;
+       unsigned long end_idx;
+       /* Event selector value used only for raw events */
+       uint64_t select;
+};
+
+/** Representation of a firmware event */
+struct sbi_pmu_fw_event {
+
+       /* Event associated with the particular counter */
+       unsigned long event_idx;
+
+       /* Current value of the counter */
+       unsigned long curr_count;
+
+       /* A flag indicating pmu event monitoring is started */
+       bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */
+union sbi_pmu_ctr_info {
+       unsigned long value;
+       struct {
+               unsigned long csr:12;
+               unsigned long width:6;
+#if __riscv_xlen == 32
+               unsigned long reserved:13;
+#else
+               unsigned long reserved:45;
+#endif
+               unsigned long type:1;
+       };
+};
+
+/* Mapping between event range and possible counters  */
+static struct sbi_pmu_hw_event hw_event_map[SBI_PMU_HW_EVENT_MAX] =

{0};

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX + SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* Contains all the information about firmwares events */
+static struct sbi_pmu_fw_event

fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] = {0};

lib/sbi/sbi_pmu.c new file +15 -0
+
+/* Maximum number of hardware events available */
+static uint32_t num_hw_events;
+/* Maximum number of hardware counters available */
+static uint32_t num_hw_ctrs;
+
+/* Maximum number of counters available */
+static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */
+#define get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >> 16)
+#define get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event

range overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise
+ */

lib/sbi/sbi_pmu.c new file +4 -0
+static bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+                                   struct sbi_pmu_hw_event *evtB)
+{
+       /* check if the range of events overlap with a previous entry

*/
+ if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx <
evtB->end_idx)) ||
+ ((evtA->start_idx > evtB->start_idx) && (evtA->start_idx >
evtB->end_idx)))

lib/sbi/sbi_pmu.c new file +23 -0
+               return FALSE;
+       return TRUE;
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event *evt,
+                                    uint64_t select_val)
+{
+
+       if (evt->select == select_val)
+               return TRUE;
+
+       return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t *event_idx_code)
+{
+       uint32_t event_idx_val;
+       uint32_t event_idx_type;
+       u32 hartid = current_hartid();
+
+       event_idx_val = active_events[hartid][cidx];
+
+       if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))

lib/sbi/sbi_pmu.c new file +24 -0
+               return SBI_EINVAL;
+
+       event_idx_type = get_cidx_type(event_idx_val);
+       if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+               return SBI_EINVAL;
+
+       *event_idx_code = get_cidx_code(event_idx_val);
+
+       return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+                              uint32_t fw_evt_code)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event fevent;
+
+       fevent = fw_event_map[hartid][fw_evt_code];
+       *cval = fevent.curr_count;
+
+       return 0;
+}
+
+/* Add a hardware counter read for completeness for future purpose

*/

lib/sbi/sbi_pmu.c new file +33 -0
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval)
+{
+#if __riscv_xlen == 32
+       uint32_t temp, temph = 0;
+
+       temp = csr_read_num(CSR_MCYCLE + cidx);
+       temph = csr_read_num(CSR_MCYCLEH + cidx);
+       *cval = ((uint64_t)temph << 32) | temp;
+#else
+       *cval = csr_read_num(CSR_MCYCLE + cidx);
+#endif
+
+       return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval)
+{
+       int event_idx_type;
+       uint32_t event_code;
+       uint64_t cval64;
+
+       event_idx_type = pmu_ctr_validate(cidx, &event_code);
+       if (event_idx_type < 0)
+               return SBI_EINVAL;
+       else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+               pmu_ctr_read_fw(cidx, cval, event_code);
+       else
+               pmu_ctr_read_hw(cidx, &cval64);
+
+       return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end, u32

cmap,

lib/sbi/sbi_pmu.c new file +5 -0
+                               uint64_t select)
+{
+       int i = 0;
+       bool is_overlap;
+       struct sbi_pmu_hw_event *event =

&hw_event_map[num_hw_events];

lib/sbi/sbi_pmu.c new file +9 -0
+
+       /* The first two counters are reserved by priv spec */
+       if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1) ||
+           (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap != 0x4) ||
+           (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap < 0x08))
+               return SBI_EDENIED;
+
+       if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) {
+               sbi_printf("Can not handle more than %d perf

events\n",

lib/sbi/sbi_pmu.c new file +13 -0
+                           SBI_PMU_HW_EVENT_MAX);
+               return SBI_EFAIL;
+       }
+
+       event->start_idx = eidx_start;
+       event->end_idx = eidx_end;
+       event->counters = cmap;
+       event->select = select;
+
+       /* Sanity check */
+       for (i = 0; i < num_hw_events; i++) {
+               if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+               /* All raw events have same event idx. Just do sanity

check on select */
+ is_overlap =
pmu_event_select_overlap(&hw_event_map[i], select);

lib/sbi/sbi_pmu.c new file +2 -0
+               else
+                       is_overlap =

pmu_event_range_overlap(&hw_event_map[i], event);

lib/sbi/sbi_pmu.c new file +10 -0
+               if (is_overlap)
+                       return SBI_EINVALID_ADDR;
+       }
+       num_hw_events++;
+
+       return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are

assigned consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret. Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap)

lib/sbi/sbi_pmu.c new file +2 -0
+{
+       if ((eidx_start > eidx_end) || eidx_start ==

SBI_PMU_EVENT_RAW_IDX ||

lib/sbi/sbi_pmu.c new file +10 -0
+            eidx_end == SBI_PMU_EVENT_RAW_IDX)
+               return SBI_EINVAL;
+
+       return pmu_add_hw_event_map(eidx_start, eidx_end, cmap, 0);
+}
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap)
+{
+       return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+                                   SBI_PMU_EVENT_RAW_IDX, cmap,

select);

lib/sbi/sbi_pmu.c line 232

Quoted 7 lines
lib/sbi/sbi_pmu.c new file +7 -0
+}
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival)
+{
+#if __riscv_xlen == 32
+       csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
+       csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);

The above code is recommended to be modified to:

Quoted 4 lines
        csr_write_num(CSR_MCYCLE + cidx, 0);
        csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);
        csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);

why ?

Quoted 415 lines

Regards,
Xiang W

Quoted 403 lines
lib/sbi/sbi_pmu.c new file +6 -0
+#else
+       csr_write_num(CSR_MCYCLE + cidx, ival);
+#endif
+}
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool

ival_update)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+       if (cidx > num_hw_ctrs)
+               return SBI_EINVAL;
+
+       if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt))

lib/sbi/sbi_pmu.c new file +45 -0
+               return SBI_EALREADY_STARTED;
+
+       __set_bit(cidx, &mctr_en);
+       __clear_bit(cidx, &mctr_inhbt);
+
+       if (ival_update)
+               pmu_ctr_write_hw(cidx, ival);
+
+       csr_write(CSR_MCOUNTEREN, mctr_en);
+       csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+       return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+                           uint64_t ival, bool ival_update)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event *fevent;
+
+       fevent = &fw_event_map[hartid][fw_evt_code];
+       if (ival_update)
+               fevent->curr_count = ival;
+       fevent->bStarted = TRUE;
+
+       return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+                     unsigned long flags, uint64_t ival)
+{
+       int event_idx_type;
+       uint32_t event_code;
+       unsigned long ctr_mask = cmask << cbase;
+       int ret = SBI_EINVAL;
+       bool bUpdate = FALSE;
+
+       if (cbase >= total_ctrs)
+               return ret;
+
+       if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+               bUpdate = TRUE;
+
+       for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+               event_idx_type = pmu_ctr_validate(cbase,

&event_code);

lib/sbi/sbi_pmu.c new file +4 -0
+               if (event_idx_type < 0)
+                       return SBI_EINVAL;
+               else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+                       ret = pmu_ctr_start_fw(cbase, event_code,

ival, bUpdate);

lib/sbi/sbi_pmu.c new file +13 -0
+               else
+                       ret = pmu_ctr_start_hw(cbase, ival, bUpdate);
+       }
+
+       return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx)
+{
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+       if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt)) {

lib/sbi/sbi_pmu.c new file +32 -0
+               __set_bit(cidx, &mctr_inhbt);
+               __clear_bit(cidx, &mctr_en);
+               csr_write(CSR_MCOUNTEREN, mctr_en);
+               csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+               return 0;
+       } else
+               return SBI_EALREADY_STOPPED;
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code)
+{
+       u32 hartid = current_hartid();
+
+       fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+       return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+                    unsigned long flag)
+{
+       u32 hartid = current_hartid();
+       int ret = SBI_EINVAL;
+       int event_idx_type;
+       uint32_t event_code;
+       unsigned long ctr_mask = cmask << cbase;
+
+       if (cbase >= total_ctrs)
+               return SBI_EINVAL;
+
+       for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+               event_idx_type = pmu_ctr_validate(cbase,

&event_code);

lib/sbi/sbi_pmu.c new file +10 -0
+               if (event_idx_type < 0)
+                       return SBI_EINVAL;
+
+               else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+                       ret = pmu_ctr_stop_fw(cbase, event_code);
+               else
+                       ret = pmu_ctr_stop_hw(cbase);
+
+               if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+                       active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;

lib/sbi/sbi_pmu.c new file +6 -0
+       }
+
+       return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event *hw_evt,

int ctr_idx,
+ unsigned long eindex, uint64_t
data)

lib/sbi/sbi_pmu.c new file +6 -0
+{
+       struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+       const struct sbi_platform *plat = sbi_platform_ptr(scratch);
+       uint64_t mhpmevent_val;
+
+       /* Get the final mhpmevent value to be written from platform

*/
+ mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat,
eindex, data);

lib/sbi/sbi_pmu.c new file +2 -0
+
+       if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >=

SBI_PMU_HW_CTR_MAX)

lib/sbi/sbi_pmu.c new file +3 -0
+               return SBI_EFAIL;
+
+       /* TODO: The upper 8 bits of mhpmevent is reserved by

sscofpmf extension.
+ * Update those bits based on the flags received from
supervisor.
+ * The OVF bit also should be cleared here in case it was not
cleared

lib/sbi/sbi_pmu.c new file +23 -0
+        * during event stop.
+        */
+       csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx, mhpmevent_val);
+
+       return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long cmask,
+                          unsigned long event_idx, uint64_t data)
+{
+       unsigned long ctr_mask;
+       int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+       struct sbi_pmu_hw_event *temp;
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+       int evt_idx_code = get_cidx_code(event_idx);
+
+       if (cbase > num_hw_ctrs)
+               return SBI_EINVAL;
+
+       for (i = 0; i < num_hw_events; i++) {
+               temp = &hw_event_map[i];
+               if ((temp->start_idx > event_idx && event_idx < temp-
Quoted 1 line

end_idx) ||

+ (temp->start_idx < event_idx && event_idx > temp-

Quoted 1 line

end_idx))

lib/sbi/sbi_pmu.c new file +3 -0
+                       continue;
+
+               /* For raw events, event data is used as the select

value */
+ if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-

Quoted 1 line

select != data)

lib/sbi/sbi_pmu.c new file +4 -0
+                       continue;
+
+               ctr_mask = temp->counters & (cmask << cbase);
+               for_each_set_bit_from(cbase, &ctr_mask,

SBI_PMU_HW_CTR_MAX) {

lib/sbi/sbi_pmu.c new file +15 -0
+                       if (!__test_bit(cbase, &mctr_en) &&
+                           __test_bit(cbase, &mctr_inhbt)) {
+                               ctr_idx = cbase;
+                               break;
+                       }
+               }
+       }
+
+       if (ctr_idx == SBI_ENOTSUPP)
+               return SBI_EFAIL;
+
+       /* No need to update the  event selectors for fixed events */
+       if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES &&
+           evt_idx_code != SBI_PMU_HW_INSTRUCTIONS)
+               ret = pmu_update_hw_mhpmevent(temp, ctr_idx,

event_idx, data);

lib/sbi/sbi_pmu.c new file +14 -0
+
+       if (!ret)
+               ret = ctr_idx;
+
+       return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long cmask,

u32 hartid)

lib/sbi/sbi_pmu.c new file +12 -0
+{
+       int i = 0;
+       int fw_base;
+       unsigned long ctr_mask = cmask << cbase;
+
+       if (cbase <= num_hw_ctrs)
+               fw_base = num_hw_ctrs + 1;
+       else
+               fw_base = cbase;
+
+       for (i = fw_base; i < total_ctrs; i++)
+               if ((active_events[hartid][i] ==

SBI_PMU_EVENT_IDX_INVALID) &&

lib/sbi/sbi_pmu.c new file +7 -0
+                   ((1UL << i) & ctr_mask))
+                       return i;
+
+       return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+ unsigned long flags, unsigned long
event_idx,

lib/sbi/sbi_pmu.c new file +16 -0
+                         uint64_t event_data)
+{
+       int ctr_idx = SBI_ENOTSUPP;
+       u32 hartid = current_hartid();
+       int event_type = get_cidx_type(event_idx);
+       struct sbi_pmu_fw_event *fevent;
+       uint32_t fw_evt_code;
+       unsigned long tmp = cidx_mask << cidx_base;
+
+       /* Do a basic sanity check of counter base & mask */
+       if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs ||
+           event_type >= SBI_PMU_EVENT_TYPE_MAX)
+               return SBI_EINVAL;
+
+       if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) {
+               /* The caller wants to skip the match because it

already knows the
+ * counter idx for the given event. Verify that the
counter idx

lib/sbi/sbi_pmu.c new file +3 -0
+                * is still valid.
+                */
+               if (active_events[hartid][cidx_base] ==

SBI_PMU_EVENT_IDX_INVALID)

lib/sbi/sbi_pmu.c new file +7 -0
+                       return SBI_EINVAL;
+               ctr_idx = cidx_base;
+               goto skip_match;
+       }
+
+       if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+               /* Any firmware counter can be used track any

firmware event */
+ ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask,
hartid);

lib/sbi/sbi_pmu.c new file +2 -0
+       } else {
+               ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask,

event_idx, event_data);

lib/sbi/sbi_pmu.c new file +35 -0
+       }
+
+       if (ctr_idx < 0)
+               return SBI_ENOTSUPP;
+
+       active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+       if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+               if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+                       pmu_ctr_write_hw(ctr_idx, 0);
+               if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+                       pmu_ctr_start_hw(ctr_idx, 0, false);
+       } else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+               fw_evt_code = get_cidx_code(event_idx);
+               fevent = &fw_event_map[hartid][fw_evt_code];
+               if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+                       fevent->curr_count = 0;
+               if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+                       fevent->bStarted = TRUE;
+       }
+
+       return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event *fevent;
+
+       if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+               return SBI_EINVAL;
+
+       fevent = &fw_event_map[hartid][fw_id];
+
+       /* PMU counters will be only enabled during performance

debugging */

lib/sbi/sbi_pmu.c new file +21 -0
+       if (unlikely(fevent->bStarted))
+               fevent->curr_count++;
+
+       return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+       return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX);
+}
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info)
+{
+       union sbi_pmu_ctr_info cinfo = {0};
+       struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+       /* Sanity check. Counter1 is not mapped at all */
+       if (cidx >= total_ctrs || cidx == 1)
+               return SBI_EINVAL;
+
+       /* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */

lib/sbi/sbi_pmu.c new file +46 -0
+       if (cidx <= num_hw_ctrs) {
+               cinfo.type = SBI_PMU_CTR_TYPE_HW;
+               cinfo.csr = CSR_CYCLE + cidx;
+               /* mcycle & minstret are always 64 bit */
+               if (cidx == 0 || cidx == 2)
+                       cinfo.width = 63;
+               else
+                       cinfo.width = sbi_hart_mhpm_bits(scratch);
+       } else {
+               /* it's a firmware counter */
+               cinfo.type = SBI_PMU_CTR_TYPE_FW;
+               /* Firmware counters are XLEN bits wide */
+               cinfo.width = BITS_PER_LONG - 1;
+       }
+
+       *ctr_info = cinfo.value;
+
+       return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid)
+{
+       int j;
+
+       /* Initialize the counter to event mapping table */
+       for (j = 0; j < total_ctrs; j++)
+               active_events[hartid][j] = SBI_PMU_EVENT_IDX_INVALID;
+       for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++)
+               sbi_memset(&fw_event_map[hartid][j], 0,
+                          sizeof(struct sbi_pmu_fw_event));
+}
+
+void sbi_pmu_exit(struct sbi_scratch *scratch)
+{
+       u32 hartid = current_hartid();
+
+       csr_write(CSR_MCOUNTINHIBIT, -1);
+       csr_write(CSR_MCOUNTEREN, 2);
+       pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot)
+{
+       const struct sbi_platform *plat;
+
+       if (!sbi_hart_has_feature(scratch,

SBI_HART_HAS_MCOUNTINHIBIT))

lib/sbi/sbi_pmu.c new file +16 -1
+               return SBI_ENOTSUPP;
+
+       if (cold_boot) {
+               plat = sbi_platform_ptr(scratch);
+               /* Initialize hw pmu events */
+               sbi_platform_pmu_init(plat);
+
+               /* mcycle & minstret is available always */
+               num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+               total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+       }
+
+       pmu_reset_event_map(current_hartid());
+
+       return 0;
+}
--
Quoted 3 lines

2.25.1

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

Signature · 2 lines
Regards,
Atish
#32 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

? 2021-06-18???? 17:08 -0700?Atish Patra???

Quoted 661 lines · Xiang W
Quoted 650 lines

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 648 lines

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop
the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of
event to counter mapping & mhpmevent value configuration. That means,
it
expects platform hooks will be used to set up the mapping and provide
the mhpmevent value at runtime.

---

?include/sbi/sbi_ecall_interface.h | 138 ++++++-
?include/sbi/sbi_error.h?????????? |?? 2 +
?include/sbi/sbi_pmu.h???????????? |? 73 ++++
?lib/sbi/objects.mk??????????????? |?? 1 +
?lib/sbi/sbi_init.c??????????????? |?? 9 +
?lib/sbi/sbi_pmu.c???????????????? | 600

++++++++++++++++++++++++++++++
?6 files changed, 822 insertions(+), 1 deletion(-) ?create mode 100644 include/sbi/sbi_pmu.h ?create mode 100644 lib/sbi/sbi_pmu.c

include/sbi/sbi_ecall_interface.h +0 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@

?#define SBI_EXT_RFENCE???????????????????????? 0x52464E43 ?#define SBI_EXT_HSM??????????????????????????? 0x48534D ?#define SBI_EXT_SRST?????????????????????????? 0x53525354 +#define SBI_EXT_PMU??????????????????????????? 0x504D55

?/* SBI function IDs for BASE extension*/ ?#define SBI_EXT_BASE_GET_SPEC_VERSION????????? 0x0

include/sbi/sbi_ecall_interface.h +0 -0
@@ -91,6 +92,139 @@

?#define SBI_SRST_RESET_REASON_NONE???? 0x0
?#define SBI_SRST_RESET_REASON_SYSFAIL? 0x1

include/sbi/sbi_ecall_interface.h +61 -0
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS?????? 0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO?? 0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH? 0x2
+#define SBI_EXT_PMU_COUNTER_START????? 0x3
+#define SBI_EXT_PMU_COUNTER_STOP?????? 0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ??? 0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+?????? SBI_PMU_HW_NO_EVENT???????????????????? = 0,
+?????? SBI_PMU_HW_CPU_CYCLES?????????????????? = 1,
+?????? SBI_PMU_HW_INSTRUCTIONS???????????????? = 2,
+?????? SBI_PMU_HW_CACHE_REFERENCES???????????? = 3,
+?????? SBI_PMU_HW_CACHE_MISSES???????????????? = 4,
+?????? SBI_PMU_HW_BRANCH_INSTRUCTIONS????????? = 5,
+?????? SBI_PMU_HW_BRANCH_MISSES??????????????? = 6,
+?????? SBI_PMU_HW_BUS_CYCLES?????????????????? = 7,
+?????? SBI_PMU_HW_STALLED_CYCLES_FRONTEND????? = 8,
+?????? SBI_PMU_HW_STALLED_CYCLES_BACKEND?????? = 9,
+?????? SBI_PMU_HW_REF_CPU_CYCLES?????????????? = 10,
+
+?????? SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *?????? { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *?????? { read, write, prefetch } x
+ *?????? { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+?????? SBI_PMU_HW_CACHE_L1D??????????? = 0,
+?????? SBI_PMU_HW_CACHE_L1I??????????? = 1,
+?????? SBI_PMU_HW_CACHE_LL???????????? = 2,
+?????? SBI_PMU_HW_CACHE_DTLB?????????? = 3,
+?????? SBI_PMU_HW_CACHE_ITLB?????????? = 4,
+?????? SBI_PMU_HW_CACHE_BPU??????????? = 5,
+?????? SBI_PMU_HW_CACHE_NODE?????????? = 6,
+
+?????? SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+?????? SBI_PMU_HW_CACHE_OP_READ??????? = 0,
+?????? SBI_PMU_HW_CACHE_OP_WRITE?????? = 1,
+?????? SBI_PMU_HW_CACHE_OP_PREFETCH??? = 2,
+
+?????? SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+?????? SBI_PMU_HW_CACHE_RESULT_ACCESS? = 0,
+?????? SBI_PMU_HW_CACHE_RESULT_MISS??? = 1,
+
+?????? SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if

the
hardware
+ * does not support performance events. These events are encoded as
a raw
+ * event type in Linux kernel perf framework.
+ */

include/sbi/sbi_ecall_interface.h +69 -0
+enum sbi_pmu_fw_event_code_id {
+?????? SBI_PMU_FW_MISALIGNED_LOAD????? = 0,
+?????? SBI_PMU_FW_MISALIGNED_STORE???? = 1,
+?????? SBI_PMU_FW_ACCESS_LOAD????????? = 2,
+?????? SBI_PMU_FW_ACCESS_STORE???????? = 3,
+?????? SBI_PMU_FW_ILLEGAL_INSN???????? = 4,
+?????? SBI_PMU_FW_SET_TIMER??????????? = 5,
+?????? SBI_PMU_FW_IPI_SENT???????????? = 6,
+?????? SBI_PMU_FW_IPI_RECVD??????????? = 7,
+?????? SBI_PMU_FW_FENCE_I_SENT???????? = 8,
+?????? SBI_PMU_FW_FENCE_I_RECVD??????? = 9,
+?????? SBI_PMU_FW_SFENCE_VMA_SENT????? = 10,
+?????? SBI_PMU_FW_SFENCE_VMA_RCVD????? = 11,
+?????? SBI_PMU_FW_SFENCE_VMA_ASID_SENT = 12,
+?????? SBI_PMU_FW_SFENCE_VMA_ASID_RCVD = 13,
+
+?????? SBI_PMU_FW_HFENCE_GVMA_SENT???? = 14,
+?????? SBI_PMU_FW_HFENCE_GVMA_RCVD???? = 15,
+?????? SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+?????? SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+?????? SBI_PMU_FW_HFENCE_VVMA_SENT???? = 18,
+?????? SBI_PMU_FW_HFENCE_VVMA_RCVD???? = 19,
+?????? SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+?????? SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+?????? SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+?????? SBI_PMU_EVENT_TYPE_HW?????????????????????????? = 0x0,
+?????? SBI_PMU_EVENT_TYPE_HW_CACHE???????????????????? = 0x1,
+?????? SBI_PMU_EVENT_TYPE_HW_RAW?????????????????????? = 0x2,
+?????? SBI_PMU_EVENT_TYPE_FW?????????????????????????? = 0xf,
+?????? SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+?????? SBI_PMU_CTR_TYPE_HW = 0,
+?????? SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH??? (1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE?? (1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START??? (1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH????? (1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH????? (1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH????? (1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH???? (1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH???? (1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */

?#define SBI_SPEC_VERSION_MAJOR_OFFSET????????? 24 ?#define SBI_SPEC_VERSION_MAJOR_MASK??????????? 0x7f ?#define SBI_SPEC_VERSION_MINOR_MASK??????????? 0xffffff

include/sbi/sbi_ecall_interface.h +0 -0
@@ -107,8 +241,10 @@

?#define SBI_ERR_DENIED???????????????????????? -4 ?#define SBI_ERR_INVALID_ADDRESS??????????????????????? -5 ?#define SBI_ERR_ALREADY_AVAILABLE????????????? -6

include/sbi/sbi_ecall_interface.h +2 -1
+#define SBI_ERR_ALREADY_STARTED??????????????????????? -7
+#define SBI_ERR_ALREADY_STOPPED??????????????????????? -8
 
-#define

SBI_LAST_ERR?????????????????????????? SBI_ERR_ALREADY_AVAILABLE +#define
SBI_LAST_ERR?????????????????????????? SBI_ERR_ALREADY_STOPPED

?/* clang-format on */

include/sbi/sbi_error.h +0 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@

?#define SBI_EDENIED??????????? SBI_ERR_DENIED ?#define SBI_EINVALID_ADDR????? SBI_ERR_INVALID_ADDRESS ?#define SBI_EALREADY?????????? SBI_ERR_ALREADY_AVAILABLE

include/sbi/sbi_error.h +2 -0
+#define SBI_EALREADY_STARTED?? SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED?? SBI_ERR_ALREADY_STOPPED

?#define SBI_ENODEV???????????? -1000
?#define SBI_ENOSYS???????????? -1001

include/sbi/sbi_pmu.h new file +4 -0
new file mode 100644
index 000000000000..b3010cc5c1ce
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its

affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */

include/sbi/sbi_pmu.h new file +11 -0
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI

*/

include/sbi/sbi_pmu.h new file +3 -0
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI

*/

include/sbi/sbi_pmu.h new file +6 -0
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX?????????? (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +9 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This

should be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end?? End of the event idx range for supported counters
+ * @param cmap?????? A bitmap representing counters supporting the
event range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end,
u32 cmap);

include/sbi/sbi_pmu.h new file +3 -0
+
+/**
+ * Add the raw hardware event selector and supported counter

information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info? a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */

include/sbi/sbi_pmu.h new file +2 -0
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32

cmap);

include/sbi/sbi_pmu.h new file +4 -0
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long

cidx_mask,
+??????????????????? unsigned long flag);

include/sbi/sbi_pmu.h new file +2 -0
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????? unsigned long flags, uint64_t ival);

include/sbi/sbi_pmu.h new file +2 -0
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long

*ctr_info);

include/sbi/sbi_pmu.h new file +4 -0
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data);

include/sbi/sbi_pmu.h new file +4 -0
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk +0 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o

?libsbi-objs-y += sbi_ipi.o
?libsbi-objs-y += sbi_misaligned_ldst.o
?libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
?libsbi-objs-y += sbi_scratch.o
?libsbi-objs-y += sbi_string.o
?libsbi-objs-y += sbi_system.o

lib/sbi/sbi_init.c +0 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@

?#include <sbi/sbi_hsm.h>
?#include <sbi/sbi_ipi.h>
?#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
?#include <sbi/sbi_system.h>
?#include <sbi/sbi_string.h>
?#include <sbi/sbi_timer.h>

lib/sbi/sbi_init.c +2 -0
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
 ??????? if (rc)
 ??????????????? sbi_hart_hang();
 
+?????? sbi_pmu_init(scratch, TRUE);
+
 ??????? sbi_boot_print_banner(scratch);
 

??????? rc = sbi_platform_irqchip_init(plat, TRUE);

lib/sbi/sbi_init.c +0 -0
@@ -353,6 +356,8 @@ static void init_warm_startup(struct

sbi_scratch
*scratch, u32 hartid)
??????? if (rc)
??????????????? sbi_hart_hang();

+?????? sbi_pmu_init(scratch, FALSE);
+
??????? rc = sbi_platform_irqchip_init(plat, FALSE); ??????? if (rc)
??????????????? sbi_hart_hang();

lib/sbi/sbi_init.c +0 -0
@@ -393,6 +398,8 @@ static void init_warm_resume(struct

sbi_scratch
*scratch)
??????? if (rc)
??????????????? sbi_hart_hang();

+?????? sbi_pmu_init(scratch, FALSE);
+
??????? rc = sbi_hart_pmp_configure(scratch);
??????? if (rc)
??????????????? sbi_hart_hang();

lib/sbi/sbi_init.c +2 -0
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch
 *scratch)
 
 ??????? sbi_platform_early_exit(plat);
 
+?????? sbi_pmu_exit(scratch);
+
 ??????? sbi_timer_exit(scratch);
 

??????? sbi_ipi_exit(scratch);

lib/sbi/sbi_pmu.c new file +4 -0
new file mode 100644
index 000000000000..ed519dfcc860
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its

affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */

lib/sbi/sbi_pmu.c new file +49 -0
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */
+struct sbi_pmu_hw_event {
+?????? unsigned long counters;
+?????? unsigned long start_idx;
+?????? unsigned long end_idx;
+?????? /* Event selector value used only for raw events */
+?????? uint64_t select;
+};
+
+/** Representation of a firmware event */
+struct sbi_pmu_fw_event {
+
+?????? /* Event associated with the particular counter */
+?????? unsigned long event_idx;
+
+?????? /* Current value of the counter */
+?????? unsigned long curr_count;
+
+?????? /* A flag indicating pmu event monitoring is started */
+?????? bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */
+union sbi_pmu_ctr_info {
+?????? unsigned long value;
+?????? struct {
+?????????????? unsigned long csr:12;
+?????????????? unsigned long width:6;
+#if __riscv_xlen == 32
+?????????????? unsigned long reserved:13;
+#else
+?????????????? unsigned long reserved:45;
+#endif
+?????????????? unsigned long type:1;
+?????? };
+};
+
+/* Mapping between event range and possible counters? */
+static struct sbi_pmu_hw_event

hw_event_map[SBI_PMU_HW_EVENT_MAX] =
{0};

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX + SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* Contains all the information about firmwares events */
+static struct sbi_pmu_fw_event

fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] = {0};

lib/sbi/sbi_pmu.c new file +11 -0
+
+/* Maximum number of hardware events available */
+static uint32_t num_hw_events;
+/* Maximum number of hardware counters available */
+static uint32_t num_hw_ctrs;
+
+/* Maximum number of counters available */
+static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */
+#define get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >>

16)

lib/sbi/sbi_pmu.c new file +4 -0
+#define get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event

range overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise
+ */
+static bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+?????????????????????????????????? struct sbi_pmu_hw_event *evtB)
+{
+?????? /* check if the range of events overlap with a previous entry
*/
+?????? if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx <
evtB->end_idx)) ||
+????????? ((evtA->start_idx > evtB->start_idx) && (evtA-

Quoted 1 line

start_idx >

evtB->end_idx)))
+?????????????? return FALSE;
+?????? return TRUE;

lib/sbi/sbi_pmu.c new file +3 -0
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event

*evt,
+??????????????????????????????????? uint64_t select_val)

lib/sbi/sbi_pmu.c new file +9 -0
+{
+
+?????? if (evt->select == select_val)
+?????????????? return TRUE;
+
+?????? return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t

*event_idx_code)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+?????? uint32_t event_idx_val;
+?????? uint32_t event_idx_type;
+?????? u32 hartid = current_hartid();
+
+?????? event_idx_val = active_events[hartid][cidx];
+
+?????? if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))
+?????????????? return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +23 -0
+
+?????? event_idx_type = get_cidx_type(event_idx_val);
+?????? if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+?????????????? return SBI_EINVAL;
+
+?????? *event_idx_code = get_cidx_code(event_idx_val);
+
+?????? return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+????????????????????????????? uint32_t fw_evt_code)
+{
+?????? u32 hartid = current_hartid();
+?????? struct sbi_pmu_fw_event fevent;
+
+?????? fevent = fw_event_map[hartid][fw_evt_code];
+?????? *cval = fevent.curr_count;
+
+?????? return 0;
+}
+
+/* Add a hardware counter read for completeness for future

purpose
*/

lib/sbi/sbi_pmu.c new file +33 -0
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval)
+{
+#if __riscv_xlen == 32
+?????? uint32_t temp, temph = 0;
+
+?????? temp = csr_read_num(CSR_MCYCLE + cidx);
+?????? temph = csr_read_num(CSR_MCYCLEH + cidx);
+?????? *cval = ((uint64_t)temph << 32) | temp;
+#else
+?????? *cval = csr_read_num(CSR_MCYCLE + cidx);
+#endif
+
+?????? return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval)
+{
+?????? int event_idx_type;
+?????? uint32_t event_code;
+?????? uint64_t cval64;
+
+?????? event_idx_type = pmu_ctr_validate(cidx, &event_code);
+?????? if (event_idx_type < 0)
+?????????????? return SBI_EINVAL;
+?????? else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+?????????????? pmu_ctr_read_fw(cidx, cval, event_code);
+?????? else
+?????????????? pmu_ctr_read_hw(cidx, &cval64);
+
+?????? return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end,

u32
cmap,
+?????????????????????????????? uint64_t select)
+{
+?????? int i = 0;
+?????? bool is_overlap;
+?????? struct sbi_pmu_hw_event *event = &hw_event_map[num_hw_events];
+
+?????? /* The first two counters are reserved by priv spec */ +?????? if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1) ||
+?????????? (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap != 0x4) ||
+?????????? (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap < 0x08))
+?????????????? return SBI_EDENIED;
+
+?????? if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) { +?????????????? sbi_printf("Can not handle more than %d perf events\n",
+?????????????????????????? SBI_PMU_HW_EVENT_MAX); +?????????????? return SBI_EFAIL;
+?????? }

lib/sbi/sbi_pmu.c new file +10 -0
+
+?????? event->start_idx = eidx_start;
+?????? event->end_idx = eidx_end;
+?????? event->counters = cmap;
+?????? event->select = select;
+
+?????? /* Sanity check */
+?????? for (i = 0; i < num_hw_events; i++) {
+?????????????? if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+?????????????? /* All raw events have same event idx. Just do

sanity
check on select */
+?????????????????????? is_overlap = pmu_event_select_overlap(&hw_event_map[i], select); +?????????????? else +?????????????????????? is_overlap = pmu_event_range_overlap(&hw_event_map[i], event); +?????????????? if (is_overlap) +?????????????????????? return SBI_EINVALID_ADDR; +?????? }
+?????? num_hw_events++;

lib/sbi/sbi_pmu.c new file +6 -0
+
+?????? return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are

assigned consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret. Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end,
u32 cmap)
+{
+?????? if ((eidx_start > eidx_end) || eidx_start == SBI_PMU_EVENT_RAW_IDX ||
+??????????? eidx_end == SBI_PMU_EVENT_RAW_IDX) +?????????????? return SBI_EINVAL;
+
+?????? return pmu_add_hw_event_map(eidx_start, eidx_end, cmap, 0);

lib/sbi/sbi_pmu.c new file +6 -0
+}
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap)
+{
+?????? return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+?????????????????????????????????? SBI_PMU_EVENT_RAW_IDX, cmap,

select);

lib/sbi/sbi_pmu.c new file +4 -0
+}
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival)
+{
Quoted 9 lines
Quoted 3 lines

+#if __riscv_xlen == 32
+?????? csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF); +?????? csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);

The above code is recommended to be modified to:
??????? csr_write_num(CSR_MCYCLE + cidx, 0);
??????? csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG); ??????? csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);

Quoted 1 line

why ?

Assuming that the counter changes quickly, write the low bit first and then the high bit. The status may have changed when the high bit is written. For example, if you want to write 0x00000001ffffffff, the result after writing may be 0x0000000100000000. If the high bit is written first, the state of the low bit is uncertain, and a carry may occur before the low bit is written. For example, if you want to write 0x00000001ffffffff, the result may be 0x00000002ffffffff after writing.

Quoted 438 lines
Quoted 435 lines

Regards,
Xiang W

Quoted 422 lines
lib/sbi/sbi_pmu.c new file +6 -0
+#else
+?????? csr_write_num(CSR_MCYCLE + cidx, ival);
+#endif
+}
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool

ival_update)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+?????? unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+?????? unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+?????? if (cidx > num_hw_ctrs)
+?????????????? return SBI_EINVAL;
+
+?????? if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt))
+?????????????? return SBI_EALREADY_STARTED;

lib/sbi/sbi_pmu.c new file +44 -0
+
+?????? __set_bit(cidx, &mctr_en);
+?????? __clear_bit(cidx, &mctr_inhbt);
+
+?????? if (ival_update)
+?????????????? pmu_ctr_write_hw(cidx, ival);
+
+?????? csr_write(CSR_MCOUNTEREN, mctr_en);
+?????? csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+?????? return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+?????????????????????????? uint64_t ival, bool ival_update)
+{
+?????? u32 hartid = current_hartid();
+?????? struct sbi_pmu_fw_event *fevent;
+
+?????? fevent = &fw_event_map[hartid][fw_evt_code];
+?????? if (ival_update)
+?????????????? fevent->curr_count = ival;
+?????? fevent->bStarted = TRUE;
+
+?????? return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+???????????????????? unsigned long flags, uint64_t ival)
+{
+?????? int event_idx_type;
+?????? uint32_t event_code;
+?????? unsigned long ctr_mask = cmask << cbase;
+?????? int ret = SBI_EINVAL;
+?????? bool bUpdate = FALSE;
+
+?????? if (cbase >= total_ctrs)
+?????????????? return ret;
+
+?????? if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+?????????????? bUpdate = TRUE;
+
+?????? for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+?????????????? event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+?????????????? if (event_idx_type < 0) +?????????????????????? return SBI_EINVAL; +?????????????? else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW) +?????????????????????? ret = pmu_ctr_start_fw(cbase, event_code, ival, bUpdate);
+?????????????? else
+?????????????????????? ret = pmu_ctr_start_hw(cbase, ival, bUpdate);
+?????? }

lib/sbi/sbi_pmu.c new file +10 -0
+
+?????? return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx)
+{
+?????? unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+?????? unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+?????? if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt)) {
+?????????????? __set_bit(cidx, &mctr_inhbt); +?????????????? __clear_bit(cidx, &mctr_en); +?????????????? csr_write(CSR_MCOUNTEREN, mctr_en); +?????????????? csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt); +?????????????? return 0;
+?????? } else
+?????????????? return SBI_EALREADY_STOPPED;

lib/sbi/sbi_pmu.c new file +25 -0
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code)
+{
+?????? u32 hartid = current_hartid();
+
+?????? fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+?????? return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+??????????????????? unsigned long flag)
+{
+?????? u32 hartid = current_hartid();
+?????? int ret = SBI_EINVAL;
+?????? int event_idx_type;
+?????? uint32_t event_code;
+?????? unsigned long ctr_mask = cmask << cbase;
+
+?????? if (cbase >= total_ctrs)
+?????????????? return SBI_EINVAL;
+
+?????? for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+?????????????? event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+?????????????? if (event_idx_type < 0)
+?????????????????????? return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +8 -0
+
+?????????????? else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+?????????????????????? ret = pmu_ctr_stop_fw(cbase, event_code);
+?????????????? else
+?????????????????????? ret = pmu_ctr_stop_hw(cbase);
+
+?????????????? if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+?????????????????????? active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;
+?????? }

lib/sbi/sbi_pmu.c new file +5 -0
+
+?????? return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event

*hw_evt,
int ctr_idx,
+?????????????????????????????????? unsigned long eindex, uint64_t
data)
+{
+?????? struct sbi_scratch *scratch = sbi_scratch_thishart_ptr(); +?????? const struct sbi_platform *plat = sbi_platform_ptr(scratch);
+?????? uint64_t mhpmevent_val;
+
+?????? /* Get the final mhpmevent value to be written from platform
*/
+?????? mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat, eindex, data);
+
+?????? if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >= SBI_PMU_HW_CTR_MAX)
+?????????????? return SBI_EFAIL;
+
+?????? /* TODO: The upper 8 bits of mhpmevent is reserved by sscofpmf extension.
+??????? * Update those bits based on the flags received from supervisor.
+??????? * The OVF bit also should be cleared here in case it was not
cleared
+??????? * during event stop.
+??????? */
+?????? csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx, mhpmevent_val);

lib/sbi/sbi_pmu.c new file +5 -0
+
+?????? return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long

cmask,
+????????????????????????? unsigned long event_idx, uint64_t data)

lib/sbi/sbi_pmu.c new file +14 -0
+{
+?????? unsigned long ctr_mask;
+?????? int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+?????? struct sbi_pmu_hw_event *temp;
+?????? unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+?????? unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+?????? int evt_idx_code = get_cidx_code(event_idx);
+
+?????? if (cbase > num_hw_ctrs)
+?????????????? return SBI_EINVAL;
+
+?????? for (i = 0; i < num_hw_events; i++) {
+?????????????? temp = &hw_event_map[i];
+?????????????? if ((temp->start_idx > event_idx && event_idx <

temp-

Quoted 1 line

end_idx) ||

+?????????????????? (temp->start_idx < event_idx && event_idx > temp-

Quoted 1 line

end_idx))

+?????????????????????? continue;
+
+?????????????? /* For raw events, event data is used as the select
value */
+?????????????? if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-

Quoted 1 line

select != data)

+?????????????????????? continue;
+
+?????????????? ctr_mask = temp->counters & (cmask << cbase); +?????????????? for_each_set_bit_from(cbase, &ctr_mask, SBI_PMU_HW_CTR_MAX) {
+?????????????????????? if (!__test_bit(cbase, &mctr_en) && +?????????????????????????? __test_bit(cbase, &mctr_inhbt)) { +?????????????????????????????? ctr_idx = cbase; +?????????????????????????????? break; +?????????????????????? }
+?????????????? }
+?????? }

lib/sbi/sbi_pmu.c new file +5 -0
+
+?????? if (ctr_idx == SBI_ENOTSUPP)
+?????????????? return SBI_EFAIL;
+
+?????? /* No need to update the? event selectors for fixed

events */
+?????? if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES && +?????????? evt_idx_code != SBI_PMU_HW_INSTRUCTIONS) +?????????????? ret = pmu_update_hw_mhpmevent(temp, ctr_idx, event_idx, data);

lib/sbi/sbi_pmu.c new file +14 -0
+
+?????? if (!ret)
+?????????????? ret = ctr_idx;
+
+?????? return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long

cmask,
u32 hartid)

lib/sbi/sbi_pmu.c new file +12 -0
+{
+?????? int i = 0;
+?????? int fw_base;
+?????? unsigned long ctr_mask = cmask << cbase;
+
+?????? if (cbase <= num_hw_ctrs)
+?????????????? fw_base = num_hw_ctrs + 1;
+?????? else
+?????????????? fw_base = cbase;
+
+?????? for (i = fw_base; i < total_ctrs; i++)
+?????????????? if ((active_events[hartid][i] ==

SBI_PMU_EVENT_IDX_INVALID) &&
+?????????????????? ((1UL << i) & ctr_mask))
+?????????????????????? return i;

lib/sbi/sbi_pmu.c new file +5 -0
+
+?????? return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data)

lib/sbi/sbi_pmu.c new file +10 -0
+{
+?????? int ctr_idx = SBI_ENOTSUPP;
+?????? u32 hartid = current_hartid();
+?????? int event_type = get_cidx_type(event_idx);
+?????? struct sbi_pmu_fw_event *fevent;
+?????? uint32_t fw_evt_code;
+?????? unsigned long tmp = cidx_mask << cidx_base;
+
+?????? /* Do a basic sanity check of counter base & mask */
+?????? if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs

||
+?????????? event_type >= SBI_PMU_EVENT_TYPE_MAX) +?????????????? return SBI_EINVAL;
+
+?????? if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) { +?????????????? /* The caller wants to skip the match because it already knows the
+??????????????? * counter idx for the given event. Verify that the
counter idx
+??????????????? * is still valid.
+??????????????? */
+?????????????? if (active_events[hartid][cidx_base] == SBI_PMU_EVENT_IDX_INVALID)
+?????????????????????? return SBI_EINVAL; +?????????????? ctr_idx = cidx_base;
+?????????????? goto skip_match;
+?????? }
+
+?????? if (event_type == SBI_PMU_EVENT_TYPE_FW) { +?????????????? /* Any firmware counter can be used track any firmware event */
+?????????????? ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask, hartid);
+?????? } else {
+?????????????? ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask, event_idx, event_data);
+?????? }

lib/sbi/sbi_pmu.c new file +24 -0
+
+?????? if (ctr_idx < 0)
+?????????????? return SBI_ENOTSUPP;
+
+?????? active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+?????? if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+?????????????? if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+?????????????????????? pmu_ctr_write_hw(ctr_idx, 0);
+?????????????? if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+?????????????????????? pmu_ctr_start_hw(ctr_idx, 0, false);
+?????? } else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+?????????????? fw_evt_code = get_cidx_code(event_idx);
+?????????????? fevent = &fw_event_map[hartid][fw_evt_code];
+?????????????? if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+?????????????????????? fevent->curr_count = 0;
+?????????????? if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+?????????????????????? fevent->bStarted = TRUE;
+?????? }
+
+?????? return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id

fw_id)

lib/sbi/sbi_pmu.c new file +10 -0
+{
+?????? u32 hartid = current_hartid();
+?????? struct sbi_pmu_fw_event *fevent;
+
+?????? if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+?????????????? return SBI_EINVAL;
+
+?????? fevent = &fw_event_map[hartid][fw_id];
+
+?????? /* PMU counters will be only enabled during performance

debugging */
+?????? if (unlikely(fevent->bStarted))
+?????????????? fevent->curr_count++;

lib/sbi/sbi_pmu.c new file +19 -0
+
+?????? return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+?????? return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX);
+}
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info)
+{
+?????? union sbi_pmu_ctr_info cinfo = {0};
+?????? struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+?????? /* Sanity check. Counter1 is not mapped at all */
+?????? if (cidx >= total_ctrs || cidx == 1)
+?????????????? return SBI_EINVAL;
+
+?????? /* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */
+?????? if (cidx <= num_hw_ctrs) { +?????????????? cinfo.type = SBI_PMU_CTR_TYPE_HW; +?????????????? cinfo.csr = CSR_CYCLE + cidx; +?????????????? /* mcycle & minstret are always 64 bit */ +?????????????? if (cidx == 0 || cidx == 2) +?????????????????????? cinfo.width = 63; +?????????????? else
+?????????????????????? cinfo.width = sbi_hart_mhpm_bits(scratch);
+?????? } else {
+?????????????? /* it's a firmware counter */ +?????????????? cinfo.type = SBI_PMU_CTR_TYPE_FW; +?????????????? /* Firmware counters are XLEN bits wide */ +?????????????? cinfo.width = BITS_PER_LONG - 1; +?????? }

lib/sbi/sbi_pmu.c new file +13 -0
+
+?????? *ctr_info = cinfo.value;
+
+?????? return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid)
+{
+?????? int j;
+
+?????? /* Initialize the counter to event mapping table */
+?????? for (j = 0; j < total_ctrs; j++)
+?????????????? active_events[hartid][j] =

SBI_PMU_EVENT_IDX_INVALID;
+?????? for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++) +?????????????? sbi_memset(&fw_event_map[hartid][j], 0, +????????????????????????? sizeof(struct sbi_pmu_fw_event));

lib/sbi/sbi_pmu.c new file +16 -0
+}
+
+void sbi_pmu_exit(struct sbi_scratch *scratch)
+{
+?????? u32 hartid = current_hartid();
+
+?????? csr_write(CSR_MCOUNTINHIBIT, -1);
+?????? csr_write(CSR_MCOUNTEREN, 2);
+?????? pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot)
+{
+?????? const struct sbi_platform *plat;
+
+?????? if (!sbi_hart_has_feature(scratch,

SBI_HART_HAS_MCOUNTINHIBIT))
+?????????????? return SBI_ENOTSUPP;

lib/sbi/sbi_pmu.c new file +15 -1
+
+?????? if (cold_boot) {
+?????????????? plat = sbi_platform_ptr(scratch);
+?????????????? /* Initialize hw pmu events */
+?????????????? sbi_platform_pmu_init(plat);
+
+?????????????? /* mcycle & minstret is available always */
+?????????????? num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+?????????????? total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+?????? }
+
+?????? pmu_reset_event_map(current_hartid());
+
+?????? return 0;
+}
--
Quoted 3 lines

2.25.1

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

#33 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

Quoted 663 lines · Xiang W

? 2021-06-18???? 17:08 -0700?Atish Patra???

Quoted 661 lines · Xiang W
Quoted 659 lines

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 644 lines

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop
the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of
event to counter mapping & mhpmevent value configuration. That means,
it
expects platform hooks will be used to set up the mapping and provide
the mhpmevent value at runtime.

---
 include/sbi/sbi_ecall_interface.h | 138 ++++++-
 include/sbi/sbi_error.h           |   2 +
 include/sbi/sbi_pmu.h             |  73 ++++
 lib/sbi/objects.mk                |   1 +
 lib/sbi/sbi_init.c                |   9 +
 lib/sbi/sbi_pmu.c                 | 600
++++++++++++++++++++++++++++++
 6 files changed, 822 insertions(+), 1 deletion(-)
 create mode 100644 include/sbi/sbi_pmu.h
 create mode 100644 lib/sbi/sbi_pmu.c
include/sbi/sbi_ecall_interface.h +62 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@
 #define SBI_EXT_RFENCE                         0x52464E43
 #define SBI_EXT_HSM                            0x48534D
 #define SBI_EXT_SRST                           0x53525354
+#define SBI_EXT_PMU                            0x504D55
 
 /* SBI function IDs for BASE extension*/
 #define SBI_EXT_BASE_GET_SPEC_VERSION          0x0
@@ -91,6 +92,139 @@
 #define SBI_SRST_RESET_REASON_NONE     0x0
 #define SBI_SRST_RESET_REASON_SYSFAIL  0x1
 
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS       0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO   0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH  0x2
+#define SBI_EXT_PMU_COUNTER_START      0x3
+#define SBI_EXT_PMU_COUNTER_STOP       0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ    0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+       SBI_PMU_HW_NO_EVENT                     = 0,
+       SBI_PMU_HW_CPU_CYCLES                   = 1,
+       SBI_PMU_HW_INSTRUCTIONS                 = 2,
+       SBI_PMU_HW_CACHE_REFERENCES             = 3,
+       SBI_PMU_HW_CACHE_MISSES                 = 4,
+       SBI_PMU_HW_BRANCH_INSTRUCTIONS          = 5,
+       SBI_PMU_HW_BRANCH_MISSES                = 6,
+       SBI_PMU_HW_BUS_CYCLES                   = 7,
+       SBI_PMU_HW_STALLED_CYCLES_FRONTEND      = 8,
+       SBI_PMU_HW_STALLED_CYCLES_BACKEND       = 9,
+       SBI_PMU_HW_REF_CPU_CYCLES               = 10,
+
+       SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *       { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *       { read, write, prefetch } x
+ *       { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+       SBI_PMU_HW_CACHE_L1D            = 0,
+       SBI_PMU_HW_CACHE_L1I            = 1,
+       SBI_PMU_HW_CACHE_LL             = 2,
+       SBI_PMU_HW_CACHE_DTLB           = 3,
+       SBI_PMU_HW_CACHE_ITLB           = 4,
+       SBI_PMU_HW_CACHE_BPU            = 5,
+       SBI_PMU_HW_CACHE_NODE           = 6,
+
+       SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+       SBI_PMU_HW_CACHE_OP_READ        = 0,
+       SBI_PMU_HW_CACHE_OP_WRITE       = 1,
+       SBI_PMU_HW_CACHE_OP_PREFETCH    = 2,
+
+       SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+       SBI_PMU_HW_CACHE_RESULT_ACCESS  = 0,
+       SBI_PMU_HW_CACHE_RESULT_MISS    = 1,
+
+       SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if

the
hardware
+ * does not support performance events. These events are encoded as
a raw
+ * event type in Linux kernel perf framework.
+ */

include/sbi/sbi_ecall_interface.h +71 -1
+enum sbi_pmu_fw_event_code_id {
+       SBI_PMU_FW_MISALIGNED_LOAD      = 0,
+       SBI_PMU_FW_MISALIGNED_STORE     = 1,
+       SBI_PMU_FW_ACCESS_LOAD          = 2,
+       SBI_PMU_FW_ACCESS_STORE         = 3,
+       SBI_PMU_FW_ILLEGAL_INSN         = 4,
+       SBI_PMU_FW_SET_TIMER            = 5,
+       SBI_PMU_FW_IPI_SENT             = 6,
+       SBI_PMU_FW_IPI_RECVD            = 7,
+       SBI_PMU_FW_FENCE_I_SENT         = 8,
+       SBI_PMU_FW_FENCE_I_RECVD        = 9,
+       SBI_PMU_FW_SFENCE_VMA_SENT      = 10,
+       SBI_PMU_FW_SFENCE_VMA_RCVD      = 11,
+       SBI_PMU_FW_SFENCE_VMA_ASID_SENT = 12,
+       SBI_PMU_FW_SFENCE_VMA_ASID_RCVD = 13,
+
+       SBI_PMU_FW_HFENCE_GVMA_SENT     = 14,
+       SBI_PMU_FW_HFENCE_GVMA_RCVD     = 15,
+       SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+       SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+       SBI_PMU_FW_HFENCE_VVMA_SENT     = 18,
+       SBI_PMU_FW_HFENCE_VVMA_RCVD     = 19,
+       SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+       SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+       SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+       SBI_PMU_EVENT_TYPE_HW                           = 0x0,
+       SBI_PMU_EVENT_TYPE_HW_CACHE                     = 0x1,
+       SBI_PMU_EVENT_TYPE_HW_RAW                       = 0x2,
+       SBI_PMU_EVENT_TYPE_FW                           = 0xf,
+       SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+       SBI_PMU_CTR_TYPE_HW = 0,
+       SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH    (1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE   (1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START    (1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH      (1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH      (1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH      (1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH     (1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH     (1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */
 #define SBI_SPEC_VERSION_MAJOR_OFFSET          24
 #define SBI_SPEC_VERSION_MAJOR_MASK            0x7f
 #define SBI_SPEC_VERSION_MINOR_MASK            0xffffff
@@ -107,8 +241,10 @@
 #define SBI_ERR_DENIED                         -4
 #define SBI_ERR_INVALID_ADDRESS                        -5
 #define SBI_ERR_ALREADY_AVAILABLE              -6
+#define SBI_ERR_ALREADY_STARTED                        -7
+#define SBI_ERR_ALREADY_STOPPED                        -8
 
-#define

SBI_LAST_ERR SBI_ERR_ALREADY_AVAILABLE
+#define
SBI_LAST_ERR SBI_ERR_ALREADY_STOPPED

/* clang-format on */

include/sbi/sbi_error.h +2 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@
 #define SBI_EDENIED            SBI_ERR_DENIED
 #define SBI_EINVALID_ADDR      SBI_ERR_INVALID_ADDRESS
 #define SBI_EALREADY           SBI_ERR_ALREADY_AVAILABLE
+#define SBI_EALREADY_STARTED   SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED   SBI_ERR_ALREADY_STOPPED
 
 #define SBI_ENODEV             -1000
 #define SBI_ENOSYS             -1001
include/sbi/sbi_pmu.h new file +4 -0
new file mode 100644
index 000000000000..b3010cc5c1ce
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its

affiliates.
+ *
+ * Authors:
+ * Atish Patra <[email protected]>
+ */

include/sbi/sbi_pmu.h new file +11 -0
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI

*/

include/sbi/sbi_pmu.h new file +3 -0
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI

*/

include/sbi/sbi_pmu.h new file +6 -0
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX           (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +9 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This

should be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end End of the event idx range for supported
counters
+ * @param cmap A bitmap representing counters supporting
the
event range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end,
u32 cmap);

include/sbi/sbi_pmu.h new file +3 -0
+
+/**
+ * Add the raw hardware event selector and supported counter

information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */

include/sbi/sbi_pmu.h new file +2 -0
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32

cmap);

include/sbi/sbi_pmu.h new file +4 -0
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long

cidx_mask,

include/sbi/sbi_pmu.h new file +3 -0
+                    unsigned long flag);
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long

cidx_mask,

include/sbi/sbi_pmu.h new file +3 -0
+                     unsigned long flags, uint64_t ival);
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long

*ctr_info);

include/sbi/sbi_pmu.h new file +4 -0
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+ unsigned long flags, unsigned long
event_idx,

include/sbi/sbi_pmu.h new file +5 -0
+                         uint64_t event_data);
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk +1 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o
 libsbi-objs-y += sbi_ipi.o
 libsbi-objs-y += sbi_misaligned_ldst.o
 libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
 libsbi-objs-y += sbi_scratch.o
 libsbi-objs-y += sbi_string.o
 libsbi-objs-y += sbi_system.o
lib/sbi/sbi_init.c +3 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@
 #include <sbi/sbi_hsm.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_system.h>
 #include <sbi/sbi_string.h>
 #include <sbi/sbi_timer.h>
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
        if (rc)
                sbi_hart_hang();
 
+       sbi_pmu_init(scratch, TRUE);
+
        sbi_boot_print_banner(scratch);
 
        rc = sbi_platform_irqchip_init(plat, TRUE);
lib/sbi/sbi_init.c +0 -0
@@ -353,6 +356,8 @@ static void init_warm_startup(struct

sbi_scratch
*scratch, u32 hartid)

        if (rc)
                sbi_hart_hang();
lib/sbi/sbi_init.c +2 -0
+       sbi_pmu_init(scratch, FALSE);
+
        rc = sbi_platform_irqchip_init(plat, FALSE);
        if (rc)
                sbi_hart_hang();
@@ -393,6 +398,8 @@ static void init_warm_resume(struct

sbi_scratch
*scratch)

        if (rc)
                sbi_hart_hang();
lib/sbi/sbi_init.c +4 -0
+       sbi_pmu_init(scratch, FALSE);
+
        rc = sbi_hart_pmp_configure(scratch);
        if (rc)
                sbi_hart_hang();
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch
 *scratch)
 
        sbi_platform_early_exit(plat);
 
+       sbi_pmu_exit(scratch);
+
        sbi_timer_exit(scratch);
 
        sbi_ipi_exit(scratch);
lib/sbi/sbi_pmu.c new file +4 -0
new file mode 100644
index 000000000000..ed519dfcc860
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its

affiliates.
+ *
+ * Authors:
+ * Atish Patra <[email protected]>
+ */

lib/sbi/sbi_pmu.c new file +49 -0
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */
+struct sbi_pmu_hw_event {
+       unsigned long counters;
+       unsigned long start_idx;
+       unsigned long end_idx;
+       /* Event selector value used only for raw events */
+       uint64_t select;
+};
+
+/** Representation of a firmware event */
+struct sbi_pmu_fw_event {
+
+       /* Event associated with the particular counter */
+       unsigned long event_idx;
+
+       /* Current value of the counter */
+       unsigned long curr_count;
+
+       /* A flag indicating pmu event monitoring is started */
+       bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */
+union sbi_pmu_ctr_info {
+       unsigned long value;
+       struct {
+               unsigned long csr:12;
+               unsigned long width:6;
+#if __riscv_xlen == 32
+               unsigned long reserved:13;
+#else
+               unsigned long reserved:45;
+#endif
+               unsigned long type:1;
+       };
+};
+
+/* Mapping between event range and possible counters  */
+static struct sbi_pmu_hw_event

hw_event_map[SBI_PMU_HW_EVENT_MAX] =
{0};

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX + SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* Contains all the information about firmwares events */
+static struct sbi_pmu_fw_event

fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] = {0};

lib/sbi/sbi_pmu.c new file +11 -0
+
+/* Maximum number of hardware events available */
+static uint32_t num_hw_events;
+/* Maximum number of hardware counters available */
+static uint32_t num_hw_ctrs;
+
+/* Maximum number of counters available */
+static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */
+#define get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >>

16)

lib/sbi/sbi_pmu.c new file +4 -0
+#define get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event

range overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise
+ */
+static bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+ struct sbi_pmu_hw_event
*evtB)

lib/sbi/sbi_pmu.c new file +2 -0
+{
+       /* check if the range of events overlap with a previous

entry
*/
+ if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx
<
evtB->end_idx)) ||
+ ((evtA->start_idx > evtB->start_idx) && (evtA-

Quoted 1 line

start_idx >

evtB->end_idx)))

lib/sbi/sbi_pmu.c new file +5 -0
+               return FALSE;
+       return TRUE;
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event

*evt,

lib/sbi/sbi_pmu.c new file +10 -0
+                                    uint64_t select_val)
+{
+
+       if (evt->select == select_val)
+               return TRUE;
+
+       return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t

*event_idx_code)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+       uint32_t event_idx_val;
+       uint32_t event_idx_type;
+       u32 hartid = current_hartid();
+
+       event_idx_val = active_events[hartid][cidx];
+
+       if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))

lib/sbi/sbi_pmu.c new file +24 -0
+               return SBI_EINVAL;
+
+       event_idx_type = get_cidx_type(event_idx_val);
+       if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+               return SBI_EINVAL;
+
+       *event_idx_code = get_cidx_code(event_idx_val);
+
+       return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+                              uint32_t fw_evt_code)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event fevent;
+
+       fevent = fw_event_map[hartid][fw_evt_code];
+       *cval = fevent.curr_count;
+
+       return 0;
+}
+
+/* Add a hardware counter read for completeness for future

purpose
*/

lib/sbi/sbi_pmu.c new file +33 -0
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval)
+{
+#if __riscv_xlen == 32
+       uint32_t temp, temph = 0;
+
+       temp = csr_read_num(CSR_MCYCLE + cidx);
+       temph = csr_read_num(CSR_MCYCLEH + cidx);
+       *cval = ((uint64_t)temph << 32) | temp;
+#else
+       *cval = csr_read_num(CSR_MCYCLE + cidx);
+#endif
+
+       return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval)
+{
+       int event_idx_type;
+       uint32_t event_code;
+       uint64_t cval64;
+
+       event_idx_type = pmu_ctr_validate(cidx, &event_code);
+       if (event_idx_type < 0)
+               return SBI_EINVAL;
+       else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+               pmu_ctr_read_fw(cidx, cval, event_code);
+       else
+               pmu_ctr_read_hw(cidx, &cval64);
+
+       return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end,

u32
cmap,

lib/sbi/sbi_pmu.c new file +5 -0
+                               uint64_t select)
+{
+       int i = 0;
+       bool is_overlap;
+       struct sbi_pmu_hw_event *event =

&hw_event_map[num_hw_events];

lib/sbi/sbi_pmu.c new file +3 -0
+
+       /* The first two counters are reserved by priv spec */
+       if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1)
||
+           (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap !=
0x4) ||
+           (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap <

0x08))

lib/sbi/sbi_pmu.c new file +4 -0
+               return SBI_EDENIED;
+
+       if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) {
+               sbi_printf("Can not handle more than %d perf

events\n",

lib/sbi/sbi_pmu.c new file +13 -0
+                           SBI_PMU_HW_EVENT_MAX);
+               return SBI_EFAIL;
+       }
+
+       event->start_idx = eidx_start;
+       event->end_idx = eidx_end;
+       event->counters = cmap;
+       event->select = select;
+
+       /* Sanity check */
+       for (i = 0; i < num_hw_events; i++) {
+               if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+               /* All raw events have same event idx. Just do

sanity
check on select */
+ is_overlap =
pmu_event_select_overlap(&hw_event_map[i], select);

lib/sbi/sbi_pmu.c new file +2 -0
+               else
+                       is_overlap =

pmu_event_range_overlap(&hw_event_map[i], event);

lib/sbi/sbi_pmu.c new file +10 -0
+               if (is_overlap)
+                       return SBI_EINVALID_ADDR;
+       }
+       num_hw_events++;
+
+       return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are

assigned consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret. Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end,
u32 cmap)

lib/sbi/sbi_pmu.c new file +2 -0
+{
+       if ((eidx_start > eidx_end) || eidx_start ==

SBI_PMU_EVENT_RAW_IDX ||

lib/sbi/sbi_pmu.c new file +4 -0
+            eidx_end == SBI_PMU_EVENT_RAW_IDX)
+               return SBI_EINVAL;
+
+       return pmu_add_hw_event_map(eidx_start, eidx_end, cmap,

0);

lib/sbi/sbi_pmu.c new file +6 -0
+}
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap)
+{
+       return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+                                   SBI_PMU_EVENT_RAW_IDX, cmap,

select);

lib/sbi/sbi_pmu.c line 232

Quoted 7 lines
lib/sbi/sbi_pmu.c new file +7 -0
+}
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival)
+{
+#if __riscv_xlen == 32
+       csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
+       csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);

The above code is recommended to be modified to:

        csr_write_num(CSR_MCYCLE + cidx, 0);
        csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);
        csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
Quoted 9 lines
Quoted 1 line

why ?

Assuming that the counter changes quickly, write the low bit first and then the high bit. The status may have changed when the high bit is written. For example, if you want to write 0x00000001ffffffff, the result after writing may be 0x0000000100000000. If the high bit is written first, the state of the low bit is uncertain, and a carry may occur before the low bit is written. For example, if you want to write 0x00000001ffffffff, the result may be 0x00000002ffffffff after writing.

Quoted 1 line

Got it. Thanks. Fixed it in v3.

Quoted 439 lines
Quoted 437 lines
Quoted 434 lines

Regards,
Xiang W

Quoted 422 lines
lib/sbi/sbi_pmu.c new file +6 -0
+#else
+       csr_write_num(CSR_MCYCLE + cidx, ival);
+#endif
+}
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool

ival_update)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+       if (cidx > num_hw_ctrs)
+               return SBI_EINVAL;
+
+       if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt))

lib/sbi/sbi_pmu.c new file +45 -0
+               return SBI_EALREADY_STARTED;
+
+       __set_bit(cidx, &mctr_en);
+       __clear_bit(cidx, &mctr_inhbt);
+
+       if (ival_update)
+               pmu_ctr_write_hw(cidx, ival);
+
+       csr_write(CSR_MCOUNTEREN, mctr_en);
+       csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+       return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+                           uint64_t ival, bool ival_update)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event *fevent;
+
+       fevent = &fw_event_map[hartid][fw_evt_code];
+       if (ival_update)
+               fevent->curr_count = ival;
+       fevent->bStarted = TRUE;
+
+       return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+                     unsigned long flags, uint64_t ival)
+{
+       int event_idx_type;
+       uint32_t event_code;
+       unsigned long ctr_mask = cmask << cbase;
+       int ret = SBI_EINVAL;
+       bool bUpdate = FALSE;
+
+       if (cbase >= total_ctrs)
+               return ret;
+
+       if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+               bUpdate = TRUE;
+
+       for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+               event_idx_type = pmu_ctr_validate(cbase,

&event_code);

lib/sbi/sbi_pmu.c new file +4 -0
+               if (event_idx_type < 0)
+                       return SBI_EINVAL;
+               else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+                       ret = pmu_ctr_start_fw(cbase, event_code,

ival, bUpdate);

lib/sbi/sbi_pmu.c new file +2 -0
+               else
+                       ret = pmu_ctr_start_hw(cbase, ival,

bUpdate);

lib/sbi/sbi_pmu.c new file +11 -0
+       }
+
+       return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx)
+{
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+       if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt)) {

lib/sbi/sbi_pmu.c new file +32 -0
+               __set_bit(cidx, &mctr_inhbt);
+               __clear_bit(cidx, &mctr_en);
+               csr_write(CSR_MCOUNTEREN, mctr_en);
+               csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+               return 0;
+       } else
+               return SBI_EALREADY_STOPPED;
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code)
+{
+       u32 hartid = current_hartid();
+
+       fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+       return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+                    unsigned long flag)
+{
+       u32 hartid = current_hartid();
+       int ret = SBI_EINVAL;
+       int event_idx_type;
+       uint32_t event_code;
+       unsigned long ctr_mask = cmask << cbase;
+
+       if (cbase >= total_ctrs)
+               return SBI_EINVAL;
+
+       for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+               event_idx_type = pmu_ctr_validate(cbase,

&event_code);

lib/sbi/sbi_pmu.c new file +10 -0
+               if (event_idx_type < 0)
+                       return SBI_EINVAL;
+
+               else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+                       ret = pmu_ctr_stop_fw(cbase, event_code);
+               else
+                       ret = pmu_ctr_stop_hw(cbase);
+
+               if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+                       active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;

lib/sbi/sbi_pmu.c new file +6 -0
+       }
+
+       return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event

*hw_evt,
int ctr_idx,
+ unsigned long eindex,
uint64_t
data)

lib/sbi/sbi_pmu.c new file +3 -0
+{
+       struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+       const struct sbi_platform *plat =

sbi_platform_ptr(scratch);

lib/sbi/sbi_pmu.c new file +3 -0
+       uint64_t mhpmevent_val;
+
+       /* Get the final mhpmevent value to be written from

platform
*/
+ mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat,
eindex, data);

lib/sbi/sbi_pmu.c new file +2 -0
+
+       if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >=

SBI_PMU_HW_CTR_MAX)

lib/sbi/sbi_pmu.c new file +3 -0
+               return SBI_EFAIL;
+
+       /* TODO: The upper 8 bits of mhpmevent is reserved by

sscofpmf extension.
+ * Update those bits based on the flags received from
supervisor.
+ * The OVF bit also should be cleared here in case it was
not
cleared

lib/sbi/sbi_pmu.c new file +3 -0
+        * during event stop.
+        */
+       csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx,

mhpmevent_val);

lib/sbi/sbi_pmu.c new file +5 -0
+
+       return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long

cmask,
+ unsigned long event_idx, uint64_t
data)

lib/sbi/sbi_pmu.c new file +14 -0
+{
+       unsigned long ctr_mask;
+       int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+       struct sbi_pmu_hw_event *temp;
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+       int evt_idx_code = get_cidx_code(event_idx);
+
+       if (cbase > num_hw_ctrs)
+               return SBI_EINVAL;
+
+       for (i = 0; i < num_hw_events; i++) {
+               temp = &hw_event_map[i];
+               if ((temp->start_idx > event_idx && event_idx <

temp-

Quoted 1 line

end_idx) ||

+ (temp->start_idx < event_idx && event_idx >
temp-

Quoted 1 line

end_idx))

lib/sbi/sbi_pmu.c new file +3 -0
+                       continue;
+
+               /* For raw events, event data is used as the

select
value */
+ if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-

Quoted 1 line

select != data)

lib/sbi/sbi_pmu.c new file +4 -0
+                       continue;
+
+               ctr_mask = temp->counters & (cmask << cbase);
+               for_each_set_bit_from(cbase, &ctr_mask,

SBI_PMU_HW_CTR_MAX) {

lib/sbi/sbi_pmu.c new file +12 -0
+                       if (!__test_bit(cbase, &mctr_en) &&
+                           __test_bit(cbase, &mctr_inhbt)) {
+                               ctr_idx = cbase;
+                               break;
+                       }
+               }
+       }
+
+       if (ctr_idx == SBI_ENOTSUPP)
+               return SBI_EFAIL;
+
+       /* No need to update the  event selectors for fixed

events */

lib/sbi/sbi_pmu.c new file +3 -0
+       if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES &&
+           evt_idx_code != SBI_PMU_HW_INSTRUCTIONS)
+               ret = pmu_update_hw_mhpmevent(temp, ctr_idx,

event_idx, data);

lib/sbi/sbi_pmu.c new file +14 -0
+
+       if (!ret)
+               ret = ctr_idx;
+
+       return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long

cmask,
u32 hartid)

lib/sbi/sbi_pmu.c new file +12 -0
+{
+       int i = 0;
+       int fw_base;
+       unsigned long ctr_mask = cmask << cbase;
+
+       if (cbase <= num_hw_ctrs)
+               fw_base = num_hw_ctrs + 1;
+       else
+               fw_base = cbase;
+
+       for (i = fw_base; i < total_ctrs; i++)
+               if ((active_events[hartid][i] ==

SBI_PMU_EVENT_IDX_INVALID) &&

lib/sbi/sbi_pmu.c new file +7 -0
+                   ((1UL << i) & ctr_mask))
+                       return i;
+
+       return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+ unsigned long flags, unsigned long
event_idx,

lib/sbi/sbi_pmu.c new file +11 -0
+                         uint64_t event_data)
+{
+       int ctr_idx = SBI_ENOTSUPP;
+       u32 hartid = current_hartid();
+       int event_type = get_cidx_type(event_idx);
+       struct sbi_pmu_fw_event *fevent;
+       uint32_t fw_evt_code;
+       unsigned long tmp = cidx_mask << cidx_base;
+
+       /* Do a basic sanity check of counter base & mask */
+       if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs

||

lib/sbi/sbi_pmu.c new file +5 -0
+           event_type >= SBI_PMU_EVENT_TYPE_MAX)
+               return SBI_EINVAL;
+
+       if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) {
+               /* The caller wants to skip the match because it

already knows the
+ * counter idx for the given event. Verify that
the
counter idx

lib/sbi/sbi_pmu.c new file +3 -0
+                * is still valid.
+                */
+               if (active_events[hartid][cidx_base] ==

SBI_PMU_EVENT_IDX_INVALID)

lib/sbi/sbi_pmu.c new file +7 -0
+                       return SBI_EINVAL;
+               ctr_idx = cidx_base;
+               goto skip_match;
+       }
+
+       if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+               /* Any firmware counter can be used track any

firmware event */
+ ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask,
hartid);

lib/sbi/sbi_pmu.c new file +2 -0
+       } else {
+               ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask,

event_idx, event_data);

lib/sbi/sbi_pmu.c new file +25 -0
+       }
+
+       if (ctr_idx < 0)
+               return SBI_ENOTSUPP;
+
+       active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+       if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+               if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+                       pmu_ctr_write_hw(ctr_idx, 0);
+               if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+                       pmu_ctr_start_hw(ctr_idx, 0, false);
+       } else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+               fw_evt_code = get_cidx_code(event_idx);
+               fevent = &fw_event_map[hartid][fw_evt_code];
+               if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+                       fevent->curr_count = 0;
+               if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+                       fevent->bStarted = TRUE;
+       }
+
+       return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id

fw_id)

lib/sbi/sbi_pmu.c new file +10 -0
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event *fevent;
+
+       if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+               return SBI_EINVAL;
+
+       fevent = &fw_event_map[hartid][fw_id];
+
+       /* PMU counters will be only enabled during performance

debugging */

lib/sbi/sbi_pmu.c new file +21 -0
+       if (unlikely(fevent->bStarted))
+               fevent->curr_count++;
+
+       return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+       return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX);
+}
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info)
+{
+       union sbi_pmu_ctr_info cinfo = {0};
+       struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+       /* Sanity check. Counter1 is not mapped at all */
+       if (cidx >= total_ctrs || cidx == 1)
+               return SBI_EINVAL;
+
+       /* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */

lib/sbi/sbi_pmu.c new file +8 -0
+       if (cidx <= num_hw_ctrs) {
+               cinfo.type = SBI_PMU_CTR_TYPE_HW;
+               cinfo.csr = CSR_CYCLE + cidx;
+               /* mcycle & minstret are always 64 bit */
+               if (cidx == 0 || cidx == 2)
+                       cinfo.width = 63;
+               else
+                       cinfo.width =

sbi_hart_mhpm_bits(scratch);

lib/sbi/sbi_pmu.c new file +19 -0
+       } else {
+               /* it's a firmware counter */
+               cinfo.type = SBI_PMU_CTR_TYPE_FW;
+               /* Firmware counters are XLEN bits wide */
+               cinfo.width = BITS_PER_LONG - 1;
+       }
+
+       *ctr_info = cinfo.value;
+
+       return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid)
+{
+       int j;
+
+       /* Initialize the counter to event mapping table */
+       for (j = 0; j < total_ctrs; j++)
+               active_events[hartid][j] =

SBI_PMU_EVENT_IDX_INVALID;

lib/sbi/sbi_pmu.c new file +19 -0
+       for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++)
+               sbi_memset(&fw_event_map[hartid][j], 0,
+                          sizeof(struct sbi_pmu_fw_event));
+}
+
+void sbi_pmu_exit(struct sbi_scratch *scratch)
+{
+       u32 hartid = current_hartid();
+
+       csr_write(CSR_MCOUNTINHIBIT, -1);
+       csr_write(CSR_MCOUNTEREN, 2);
+       pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot)
+{
+       const struct sbi_platform *plat;
+
+       if (!sbi_hart_has_feature(scratch,

SBI_HART_HAS_MCOUNTINHIBIT))

lib/sbi/sbi_pmu.c new file +16 -1
+               return SBI_ENOTSUPP;
+
+       if (cold_boot) {
+               plat = sbi_platform_ptr(scratch);
+               /* Initialize hw pmu events */
+               sbi_platform_pmu_init(plat);
+
+               /* mcycle & minstret is available always */
+               num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+               total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+       }
+
+       pmu_reset_event_map(current_hartid());
+
+       return 0;
+}
--
Quoted 3 lines

2.25.1

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

Signature · 2 lines
Regards,
Atish
#34 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

In reply to Atish Patra

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 459 lines

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop
the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of
event to counter mapping & mhpmevent value configuration. That means, it
expects platform hooks will be used to set up the mapping and provide the mhpmevent value at runtime.

---

?include/sbi/sbi_ecall_interface.h | 138 ++++++-
?include/sbi/sbi_error.h?????????? |?? 2 +
?include/sbi/sbi_pmu.h???????????? |? 73 ++++
?lib/sbi/objects.mk??????????????? |?? 1 +
?lib/sbi/sbi_init.c??????????????? |?? 9 +
?lib/sbi/sbi_pmu.c???????????????? | 600

++++++++++++++++++++++++++++++
?6 files changed, 822 insertions(+), 1 deletion(-) ?create mode 100644 include/sbi/sbi_pmu.h ?create mode 100644 lib/sbi/sbi_pmu.c

include/sbi/sbi_ecall_interface.h +0 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@

?#define SBI_EXT_RFENCE?????????????????????????0x52464E43 ?#define SBI_EXT_HSM????????????????????????????0x48534D ?#define SBI_EXT_SRST???????????????????????????0x53525354 +#define SBI_EXT_PMU????????????????????????????0x504D55 ?
?/* SBI function IDs for BASE extension*/ ?#define SBI_EXT_BASE_GET_SPEC_VERSION??????????0x0

include/sbi/sbi_ecall_interface.h +0 -0
@@ -91,6 +92,139 @@

?#define SBI_SRST_RESET_REASON_NONE?????0x0
?#define SBI_SRST_RESET_REASON_SYSFAIL??0x1
?

include/sbi/sbi_ecall_interface.h +61 -0
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS???????0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO???0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH??0x2
+#define SBI_EXT_PMU_COUNTER_START??????0x3
+#define SBI_EXT_PMU_COUNTER_STOP???????0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ????0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+???????SBI_PMU_HW_NO_EVENT?????????????????????= 0,
+???????SBI_PMU_HW_CPU_CYCLES???????????????????= 1,
+???????SBI_PMU_HW_INSTRUCTIONS?????????????????= 2,
+???????SBI_PMU_HW_CACHE_REFERENCES?????????????= 3,
+???????SBI_PMU_HW_CACHE_MISSES?????????????????= 4,
+???????SBI_PMU_HW_BRANCH_INSTRUCTIONS??????????= 5,
+???????SBI_PMU_HW_BRANCH_MISSES????????????????= 6,
+???????SBI_PMU_HW_BUS_CYCLES???????????????????= 7,
+???????SBI_PMU_HW_STALLED_CYCLES_FRONTEND??????= 8,
+???????SBI_PMU_HW_STALLED_CYCLES_BACKEND???????= 9,
+???????SBI_PMU_HW_REF_CPU_CYCLES???????????????= 10,
+
+???????SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *?????? { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *?????? { read, write, prefetch } x
+ *?????? { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+???????SBI_PMU_HW_CACHE_L1D????????????= 0,
+???????SBI_PMU_HW_CACHE_L1I????????????= 1,
+???????SBI_PMU_HW_CACHE_LL?????????????= 2,
+???????SBI_PMU_HW_CACHE_DTLB???????????= 3,
+???????SBI_PMU_HW_CACHE_ITLB???????????= 4,
+???????SBI_PMU_HW_CACHE_BPU????????????= 5,
+???????SBI_PMU_HW_CACHE_NODE???????????= 6,
+
+???????SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+???????SBI_PMU_HW_CACHE_OP_READ????????= 0,
+???????SBI_PMU_HW_CACHE_OP_WRITE???????= 1,
+???????SBI_PMU_HW_CACHE_OP_PREFETCH????= 2,
+
+???????SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+???????SBI_PMU_HW_CACHE_RESULT_ACCESS??= 0,
+???????SBI_PMU_HW_CACHE_RESULT_MISS????= 1,
+
+???????SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if the

hardware
+ * does not support performance events. These events are encoded as a raw
+ * event type in Linux kernel perf framework.
+ */

include/sbi/sbi_ecall_interface.h +69 -0
+enum sbi_pmu_fw_event_code_id {
+???????SBI_PMU_FW_MISALIGNED_LOAD??????= 0,
+???????SBI_PMU_FW_MISALIGNED_STORE?????= 1,
+???????SBI_PMU_FW_ACCESS_LOAD??????????= 2,
+???????SBI_PMU_FW_ACCESS_STORE?????????= 3,
+???????SBI_PMU_FW_ILLEGAL_INSN?????????= 4,
+???????SBI_PMU_FW_SET_TIMER????????????= 5,
+???????SBI_PMU_FW_IPI_SENT?????????????= 6,
+???????SBI_PMU_FW_IPI_RECVD????????????= 7,
+???????SBI_PMU_FW_FENCE_I_SENT?????????= 8,
+???????SBI_PMU_FW_FENCE_I_RECVD????????= 9,
+???????SBI_PMU_FW_SFENCE_VMA_SENT??????= 10,
+???????SBI_PMU_FW_SFENCE_VMA_RCVD??????= 11,
+???????SBI_PMU_FW_SFENCE_VMA_ASID_SENT?= 12,
+???????SBI_PMU_FW_SFENCE_VMA_ASID_RCVD?= 13,
+
+???????SBI_PMU_FW_HFENCE_GVMA_SENT?????= 14,
+???????SBI_PMU_FW_HFENCE_GVMA_RCVD?????= 15,
+???????SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+???????SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+???????SBI_PMU_FW_HFENCE_VVMA_SENT?????= 18,
+???????SBI_PMU_FW_HFENCE_VVMA_RCVD?????= 19,
+???????SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+???????SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+???????SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+???????SBI_PMU_EVENT_TYPE_HW???????????????????????????= 0x0,
+???????SBI_PMU_EVENT_TYPE_HW_CACHE?????????????????????= 0x1,
+???????SBI_PMU_EVENT_TYPE_HW_RAW???????????????????????= 0x2,
+???????SBI_PMU_EVENT_TYPE_FW???????????????????????????= 0xf,
+???????SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+???????SBI_PMU_CTR_TYPE_HW = 0,
+???????SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH????(1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE???(1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START????(1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH??????(1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH??????(1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH??????(1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH?????(1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH?????(1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */

?#define SBI_SPEC_VERSION_MAJOR_OFFSET??????????24 ?#define SBI_SPEC_VERSION_MAJOR_MASK????????????0x7f ?#define SBI_SPEC_VERSION_MINOR_MASK????????????0xffffff

include/sbi/sbi_ecall_interface.h +0 -0
@@ -107,8 +241,10 @@

?#define SBI_ERR_DENIED?????????????????????????-4 ?#define SBI_ERR_INVALID_ADDRESS????????????????????????-5 ?#define SBI_ERR_ALREADY_AVAILABLE??????????????-6

include/sbi/sbi_ecall_interface.h +2 -0
+#define SBI_ERR_ALREADY_STARTED????????????????????????-7
+#define SBI_ERR_ALREADY_STOPPED????????????????????????-8

?
-#define SBI_LAST_ERR???????????????????????????SBI_ERR_ALREADY_AVAILABLE +#define SBI_LAST_ERR???????????????????????????SBI_ERR_ALREADY_STOPPED ?
?/* clang-format on */
?

include/sbi/sbi_error.h +0 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@

?#define SBI_EDENIED????????????SBI_ERR_DENIED ?#define SBI_EINVALID_ADDR??????SBI_ERR_INVALID_ADDRESS ?#define SBI_EALREADY???????????SBI_ERR_ALREADY_AVAILABLE

include/sbi/sbi_error.h +2 -0
+#define SBI_EALREADY_STARTED???SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED???SBI_ERR_ALREADY_STOPPED

?
?#define SBI_ENODEV?????????????-1000
?#define SBI_ENOSYS?????????????-1001

include/sbi/sbi_pmu.h new file +28 -0
new file mode 100644
index 000000000000..b3010cc5c1ce
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI */
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI */
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX?????????? (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +9 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This

should be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end?? End of the event idx range for supported counters
+ * @param cmap?????? A bitmap representing counters supporting the event range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap);

include/sbi/sbi_pmu.h new file +3 -0
+
+/**
+ * Add the raw hardware event selector and supported counter

information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info? a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap);
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long

cidx_mask,
+??????????????????? unsigned long flag);

include/sbi/sbi_pmu.h new file +2 -0
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????? unsigned long flags, uint64_t ival);

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info);
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data);

include/sbi/sbi_pmu.h new file +4 -0
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk +0 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o

?libsbi-objs-y += sbi_ipi.o
?libsbi-objs-y += sbi_misaligned_ldst.o
?libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
?libsbi-objs-y += sbi_scratch.o
?libsbi-objs-y += sbi_string.o
?libsbi-objs-y += sbi_system.o

lib/sbi/sbi_init.c +0 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@

?#include <sbi/sbi_hsm.h>
?#include <sbi/sbi_ipi.h>
?#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
?#include <sbi/sbi_system.h>
?#include <sbi/sbi_string.h>
?#include <sbi/sbi_timer.h>

lib/sbi/sbi_init.c +0 -0
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, TRUE);
+
????????sbi_boot_print_banner(scratch);
?
????????rc = sbi_platform_irqchip_init(plat, TRUE);

lib/sbi/sbi_init.c +0 -0
@@ -353,6 +356,8 @@ static void init_warm_startup(struct sbi_scratch
 *scratch, u32 hartid)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, FALSE);
+
????????rc = sbi_platform_irqchip_init(plat, FALSE); ????????if (rc) ????????????????sbi_hart_hang();

lib/sbi/sbi_init.c +0 -0
@@ -393,6 +398,8 @@ static void init_warm_resume(struct sbi_scratch
 *scratch)
 ????????if (rc)
 ????????????????sbi_hart_hang();

?
+???????sbi_pmu_init(scratch, FALSE);
+
????????rc = sbi_hart_pmp_configure(scratch);
????????if (rc)
????????????????sbi_hart_hang();

lib/sbi/sbi_init.c +0 -0
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch
 *scratch)

?
????????sbi_platform_early_exit(plat);
?
+???????sbi_pmu_exit(scratch);
+
????????sbi_timer_exit(scratch);
?
????????sbi_ipi_exit(scratch);

lib/sbi/sbi_pmu.c new file +57 -0
new file mode 100644
index 000000000000..ed519dfcc860
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *?? Atish Patra <[email protected]>
+ */
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */
+struct sbi_pmu_hw_event {
+???????unsigned long counters;
+???????unsigned long start_idx;
+???????unsigned long end_idx;
+???????/* Event selector value used only for raw events */
+???????uint64_t select;
+};
+
+/** Representation of a firmware event */
+struct sbi_pmu_fw_event {
+
+???????/* Event associated with the particular counter */
+???????unsigned long event_idx;
+
+???????/* Current value of the counter */
+???????unsigned long curr_count;
+
+???????/* A flag indicating pmu event monitoring is started */
+???????bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */
+union sbi_pmu_ctr_info {
+???????unsigned long value;
+???????struct {
+???????????????unsigned long csr:12;
+???????????????unsigned long width:6;
+#if __riscv_xlen == 32
+???????????????unsigned long reserved:13;
+#else
+???????????????unsigned long reserved:45;
+#endif
+???????????????unsigned long type:1;
+???????};
+};
+
+/* Mapping between event range and possible counters? */
+static struct sbi_pmu_hw_event hw_event_map[SBI_PMU_HW_EVENT_MAX] =

{0};

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX + SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* Contains all the information about firmwares events */
+static struct sbi_pmu_fw_event

fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] = {0};

lib/sbi/sbi_pmu.c new file +15 -0
+
+/* Maximum number of hardware events available */
+static uint32_t num_hw_events;
+/* Maximum number of hardware counters available */
+static uint32_t num_hw_ctrs;
+
+/* Maximum number of counters available */
+static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */
+#define get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >> 16)
+#define get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event

range overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise
+ */

lib/sbi/sbi_pmu.c new file +4 -0
+static bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+?????????????????????????????????? struct sbi_pmu_hw_event *evtB)
+{
+???????/* check if the range of events overlap with a previous entry
Quoted 5 lines

*/
+???????if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx < evtB->end_idx)) ||
+????????? ((evtA->start_idx > evtB->start_idx) && (evtA->start_idx > evtB->end_idx)))

Because start_idx is always less than or equal to end_idx, the above condition can be simplified to?

	            if (evtA->end_idx < evtB->start_idx?
			|| evtA->start_idx > evtB->end_idx)
Quoted 87 lines

+???????????????return FALSE;
+???????return TRUE;

lib/sbi/sbi_pmu.c new file +21 -0
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event *evt,
+??????????????????????????????????? uint64_t select_val)
+{
+
+???????if (evt->select == select_val)
+???????????????return TRUE;
+
+???????return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t *event_idx_code)
+{
+???????uint32_t event_idx_val;
+???????uint32_t event_idx_type;
+???????u32 hartid = current_hartid();
+
+???????event_idx_val = active_events[hartid][cidx];
+
+???????if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))
+???????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +23 -0
+
+???????event_idx_type = get_cidx_type(event_idx_val);
+???????if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+???????????????return SBI_EINVAL;
+
+???????*event_idx_code = get_cidx_code(event_idx_val);
+
+???????return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+????????????????????????????? uint32_t fw_evt_code)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event fevent;
+
+???????fevent = fw_event_map[hartid][fw_evt_code];
+???????*cval = fevent.curr_count;
+
+???????return 0;
+}
+
+/* Add a hardware counter read for completeness for future purpose

*/

lib/sbi/sbi_pmu.c new file +33 -0
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval)
+{
+#if __riscv_xlen == 32
+???????uint32_t temp, temph = 0;
+
+???????temp = csr_read_num(CSR_MCYCLE + cidx);
+???????temph = csr_read_num(CSR_MCYCLEH + cidx);
+???????*cval = ((uint64_t)temph << 32) | temp;
+#else
+???????*cval = csr_read_num(CSR_MCYCLE + cidx);
+#endif
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval)
+{
+???????int event_idx_type;
+???????uint32_t event_code;
+???????uint64_t cval64;
+
+???????event_idx_type = pmu_ctr_validate(cidx, &event_code);
+???????if (event_idx_type < 0)
+???????????????return SBI_EINVAL;
+???????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+???????????????pmu_ctr_read_fw(cidx, cval, event_code);
+???????else
+???????????????pmu_ctr_read_hw(cidx, &cval64);
+
+???????return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end, u32

cmap,
+???????????????????????????????uint64_t select)
+{
+???????int i = 0;
+???????bool is_overlap;

Quoted 8 lines

+???????struct sbi_pmu_hw_event *event = &hw_event_map[num_hw_events];
+
+???????/* The first two counters are reserved by priv spec */ +???????if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1) || +?????????? (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap != 0x4) || +?????????? (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap < 0x08)) +???????????????return SBI_EDENIED;

Should we add restriction eidx_start <= eidx_end

can cmap have a gaps?
The above test may not be appropriate.
ex:
eidx_start = SBI_PMU_HW_CPU_CYCLES
eidx_end = 8
cmap = 0xd0

Quoted 308 lines

+
+???????if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) { +???????????????sbi_printf("Can not handle more than %d perf events\n",
+?????????????????????????? SBI_PMU_HW_EVENT_MAX); +???????????????return SBI_EFAIL;
+???????}

lib/sbi/sbi_pmu.c new file +10 -0
+
+???????event->start_idx = eidx_start;
+???????event->end_idx = eidx_end;
+???????event->counters = cmap;
+???????event->select = select;
+
+???????/* Sanity check */
+???????for (i = 0; i < num_hw_events; i++) {
+???????????????if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+???????????????/* All raw events have same event idx. Just do sanity

check on select */ +???????????????????????is_overlap = pmu_event_select_overlap(&hw_event_map[i], select); +???????????????else +???????????????????????is_overlap = pmu_event_range_overlap(&hw_event_map[i], event); +???????????????if (is_overlap) +???????????????????????return SBI_EINVALID_ADDR; +???????}
+???????num_hw_events++;

lib/sbi/sbi_pmu.c new file +6 -0
+
+???????return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are

assigned consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret. Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap)
+{
+???????if ((eidx_start > eidx_end) || eidx_start == SBI_PMU_EVENT_RAW_IDX ||
+??????????? eidx_end == SBI_PMU_EVENT_RAW_IDX) +???????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????return pmu_add_hw_event_map(eidx_start, eidx_end, cmap, 0);
+}
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap)
+{
+???????return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+?????????????????????????????????? SBI_PMU_EVENT_RAW_IDX, cmap,

select);

lib/sbi/sbi_pmu.c new file +13 -0
+}
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival)
+{
+#if __riscv_xlen == 32
+???????csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
+???????csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);
+#else
+???????csr_write_num(CSR_MCYCLE + cidx, ival);
+#endif
+}
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool

ival_update)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+???????if (cidx > num_hw_ctrs)
+???????????????return SBI_EINVAL;
+
+???????if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt))
+???????????????return SBI_EALREADY_STARTED;

lib/sbi/sbi_pmu.c new file +44 -0
+
+???????__set_bit(cidx, &mctr_en);
+???????__clear_bit(cidx, &mctr_inhbt);
+
+???????if (ival_update)
+???????????????pmu_ctr_write_hw(cidx, ival);
+
+???????csr_write(CSR_MCOUNTEREN, mctr_en);
+???????csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+???????return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+?????????????????????????? uint64_t ival, bool ival_update)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event *fevent;
+
+???????fevent = &fw_event_map[hartid][fw_evt_code];
+???????if (ival_update)
+???????????????fevent->curr_count = ival;
+???????fevent->bStarted = TRUE;
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+???????????????????? unsigned long flags, uint64_t ival)
+{
+???????int event_idx_type;
+???????uint32_t event_code;
+???????unsigned long ctr_mask = cmask << cbase;
+???????int ret = SBI_EINVAL;
+???????bool bUpdate = FALSE;
+
+???????if (cbase >= total_ctrs)
+???????????????return ret;
+
+???????if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+???????????????bUpdate = TRUE;
+
+???????for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+???????????????event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+???????????????if (event_idx_type < 0) +???????????????????????return SBI_EINVAL; +???????????????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW) +???????????????????????ret = pmu_ctr_start_fw(cbase, event_code, ival, bUpdate);
+???????????????else
+???????????????????????ret = pmu_ctr_start_hw(cbase, ival, bUpdate); +???????}

lib/sbi/sbi_pmu.c new file +10 -0
+
+???????return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx)
+{
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+???????if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt)) {
+???????????????__set_bit(cidx, &mctr_inhbt); +???????????????__clear_bit(cidx, &mctr_en); +???????????????csr_write(CSR_MCOUNTEREN, mctr_en); +???????????????csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt); +???????????????return 0;
+???????} else
+???????????????return SBI_EALREADY_STOPPED;

lib/sbi/sbi_pmu.c new file +25 -0
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code)
+{
+???????u32 hartid = current_hartid();
+
+???????fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+???????return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+??????????????????? unsigned long flag)
+{
+???????u32 hartid = current_hartid();
+???????int ret = SBI_EINVAL;
+???????int event_idx_type;
+???????uint32_t event_code;
+???????unsigned long ctr_mask = cmask << cbase;
+
+???????if (cbase >= total_ctrs)
+???????????????return SBI_EINVAL;
+
+???????for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+???????????????event_idx_type = pmu_ctr_validate(cbase,

&event_code);
+???????????????if (event_idx_type < 0)
+???????????????????????return SBI_EINVAL;

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????????????else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+???????????????????????ret = pmu_ctr_stop_fw(cbase, event_code);
+???????????????else
+???????????????????????ret = pmu_ctr_stop_hw(cbase);
+
+???????????????if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+???????????????????????active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;
+???????}

lib/sbi/sbi_pmu.c new file +5 -0
+
+???????return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event *hw_evt,

int ctr_idx,
+?????????????????????????????????? unsigned long eindex, uint64_t data)

lib/sbi/sbi_pmu.c new file +6 -0
+{
+???????struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+???????const struct sbi_platform *plat = sbi_platform_ptr(scratch);
+???????uint64_t mhpmevent_val;
+
+???????/* Get the final mhpmevent value to be written from platform

*/
+???????mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat, eindex, data);
+
+???????if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >= SBI_PMU_HW_CTR_MAX)
+???????????????return SBI_EFAIL;
+
+???????/* TODO: The upper 8 bits of mhpmevent is reserved by sscofpmf extension.
+??????? * Update those bits based on the flags received from supervisor.
+??????? * The OVF bit also should be cleared here in case it was not cleared
+??????? * during event stop.
+??????? */
+???????csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx, mhpmevent_val);

lib/sbi/sbi_pmu.c new file +20 -0
+
+???????return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long cmask,
+????????????????????????? unsigned long event_idx, uint64_t data)
+{
+???????unsigned long ctr_mask;
+???????int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+???????struct sbi_pmu_hw_event *temp;
+???????unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+???????unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+???????int evt_idx_code = get_cidx_code(event_idx);
+
+???????if (cbase > num_hw_ctrs)
+???????????????return SBI_EINVAL;
+
+???????for (i = 0; i < num_hw_events; i++) {
+???????????????temp = &hw_event_map[i];
+???????????????if ((temp->start_idx > event_idx && event_idx < temp-
Quoted 1 line

end_idx) ||

+?????????????????? (temp->start_idx < event_idx && event_idx > temp-

Quoted 1 line

end_idx))

+???????????????????????continue;
+
+???????????????/* For raw events, event data is used as the select value */
+???????????????if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-

Quoted 1 line

select != data)

+???????????????????????continue;
+
+???????????????ctr_mask = temp->counters & (cmask << cbase); +???????????????for_each_set_bit_from(cbase, &ctr_mask, SBI_PMU_HW_CTR_MAX) {
+???????????????????????if (!__test_bit(cbase, &mctr_en) && +?????????????????????????? __test_bit(cbase, &mctr_inhbt)) { +???????????????????????????????ctr_idx = cbase; +???????????????????????????????break; +???????????????????????}
+???????????????}
+???????}

lib/sbi/sbi_pmu.c new file +8 -0
+
+???????if (ctr_idx == SBI_ENOTSUPP)
+???????????????return SBI_EFAIL;
+
+???????/* No need to update the? event selectors for fixed events */
+???????if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES &&
+?????????? evt_idx_code != SBI_PMU_HW_INSTRUCTIONS)
+???????????????ret = pmu_update_hw_mhpmevent(temp, ctr_idx,

event_idx, data);

lib/sbi/sbi_pmu.c new file +14 -0
+
+???????if (!ret)
+???????????????ret = ctr_idx;
+
+???????return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long cmask,

u32 hartid)

lib/sbi/sbi_pmu.c new file +12 -0
+{
+???????int i = 0;
+???????int fw_base;
+???????unsigned long ctr_mask = cmask << cbase;
+
+???????if (cbase <= num_hw_ctrs)
+???????????????fw_base = num_hw_ctrs + 1;
+???????else
+???????????????fw_base = cbase;
+
+???????for (i = fw_base; i < total_ctrs; i++)
+???????????????if ((active_events[hartid][i] ==

SBI_PMU_EVENT_IDX_INVALID) &&
+?????????????????? ((1UL << i) & ctr_mask))
+???????????????????????return i;

lib/sbi/sbi_pmu.c new file +5 -0
+
+???????return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+???????????????????????? unsigned long flags, unsigned long event_idx,
+???????????????????????? uint64_t event_data)

lib/sbi/sbi_pmu.c new file +1 -0
+{

lib/sbi/sbi_pmu.c

Quoted 10 lines
lib/sbi/sbi_pmu.c new file +10 -0
+???????int ctr_idx = SBI_ENOTSUPP;
+???????u32 hartid = current_hartid();
+???????int event_type = get_cidx_type(event_idx);
+???????struct sbi_pmu_fw_event *fevent;
+???????uint32_t fw_evt_code;
+???????unsigned long tmp = cidx_mask << cidx_base;
+
+???????/* Do a basic sanity check of counter base & mask */
+???????if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs ||
+?????????? event_type >= SBI_PMU_EVENT_TYPE_MAX)

We can remove cidx_base >= total_ctrs, because __fls(tmp) always large then cidx_base

Quoted 149 lines

+???????????????return SBI_EINVAL;
+
+???????if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) { +???????????????/* The caller wants to skip the match because it already knows the
+??????????????? * counter idx for the given event. Verify that the counter idx
+??????????????? * is still valid.
+??????????????? */
+???????????????if (active_events[hartid][cidx_base] == SBI_PMU_EVENT_IDX_INVALID) +???????????????????????return SBI_EINVAL; +???????????????ctr_idx = cidx_base; +???????????????goto skip_match;
+???????}
+
+???????if (event_type == SBI_PMU_EVENT_TYPE_FW) { +???????????????/* Any firmware counter can be used track any firmware event */
+???????????????ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask, hartid);
+???????} else {
+???????????????ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask, event_idx, event_data);
+???????}

lib/sbi/sbi_pmu.c new file +34 -0
+
+???????if (ctr_idx < 0)
+???????????????return SBI_ENOTSUPP;
+
+???????active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+???????if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+???????????????if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+???????????????????????pmu_ctr_write_hw(ctr_idx, 0);
+???????????????if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+???????????????????????pmu_ctr_start_hw(ctr_idx, 0, false);
+???????} else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+???????????????fw_evt_code = get_cidx_code(event_idx);
+???????????????fevent = &fw_event_map[hartid][fw_evt_code];
+???????????????if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+???????????????????????fevent->curr_count = 0;
+???????????????if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+???????????????????????fevent->bStarted = TRUE;
+???????}
+
+???????return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id)
+{
+???????u32 hartid = current_hartid();
+???????struct sbi_pmu_fw_event *fevent;
+
+???????if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+???????????????return SBI_EINVAL;
+
+???????fevent = &fw_event_map[hartid][fw_id];
+
+???????/* PMU counters will be only enabled during performance

debugging */
+???????if (unlikely(fevent->bStarted))
+???????????????fevent->curr_count++;

lib/sbi/sbi_pmu.c new file +19 -0
+
+???????return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+???????return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX);
+}
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info)
+{
+???????union sbi_pmu_ctr_info cinfo = {0};
+???????struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+???????/* Sanity check. Counter1 is not mapped at all */
+???????if (cidx >= total_ctrs || cidx == 1)
+???????????????return SBI_EINVAL;
+
+???????/* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */
+???????if (cidx <= num_hw_ctrs) { +???????????????cinfo.type = SBI_PMU_CTR_TYPE_HW; +???????????????cinfo.csr = CSR_CYCLE + cidx; +???????????????/* mcycle & minstret are always 64 bit */ +???????????????if (cidx == 0 || cidx == 2) +???????????????????????cinfo.width = 63; +???????????????else +???????????????????????cinfo.width = sbi_hart_mhpm_bits(scratch); +???????} else {
+???????????????/* it's a firmware counter */ +???????????????cinfo.type = SBI_PMU_CTR_TYPE_FW; +???????????????/* Firmware counters are XLEN bits wide */ +???????????????cinfo.width = BITS_PER_LONG - 1; +???????}

lib/sbi/sbi_pmu.c new file +32 -0
+
+???????*ctr_info = cinfo.value;
+
+???????return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid)
+{
+???????int j;
+
+???????/* Initialize the counter to event mapping table */
+???????for (j = 0; j < total_ctrs; j++)
+???????????????active_events[hartid][j] = SBI_PMU_EVENT_IDX_INVALID;
+???????for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++)
+???????????????sbi_memset(&fw_event_map[hartid][j], 0,
+????????????????????????? sizeof(struct sbi_pmu_fw_event));
+}
+
+void sbi_pmu_exit(struct sbi_scratch *scratch)
+{
+???????u32 hartid = current_hartid();
+
+???????csr_write(CSR_MCOUNTINHIBIT, -1);
+???????csr_write(CSR_MCOUNTEREN, 2);
+???????pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot)
+{
+???????const struct sbi_platform *plat;
+
+???????if (!sbi_hart_has_feature(scratch,

SBI_HART_HAS_MCOUNTINHIBIT))
+???????????????return SBI_ENOTSUPP;

lib/sbi/sbi_pmu.c new file +15 -0
+
+???????if (cold_boot) {
+???????????????plat = sbi_platform_ptr(scratch);
+???????????????/* Initialize hw pmu events */
+???????????????sbi_platform_pmu_init(plat);
+
+???????????????/* mcycle & minstret is available always */
+???????????????num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+???????????????total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+???????}
+
+???????pmu_reset_event_map(current_hartid());
+
+???????return 0;
+}
Signature · 1 line
2.25.1
#35 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

Quoted 469 lines · Xiang W

? 2021-05-26???? 17:30 -0700?Atish Patra???

Quoted 459 lines

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop
the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of
event to counter mapping & mhpmevent value configuration. That means, it
expects platform hooks will be used to set up the mapping and provide the mhpmevent value at runtime.

---
 include/sbi/sbi_ecall_interface.h | 138 ++++++-
 include/sbi/sbi_error.h           |   2 +
 include/sbi/sbi_pmu.h             |  73 ++++
 lib/sbi/objects.mk                |   1 +
 lib/sbi/sbi_init.c                |   9 +
 lib/sbi/sbi_pmu.c                 | 600
++++++++++++++++++++++++++++++
 6 files changed, 822 insertions(+), 1 deletion(-)
 create mode 100644 include/sbi/sbi_pmu.h
 create mode 100644 lib/sbi/sbi_pmu.c
include/sbi/sbi_ecall_interface.h +62 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@
 #define SBI_EXT_RFENCE                         0x52464E43
 #define SBI_EXT_HSM                            0x48534D
 #define SBI_EXT_SRST                           0x53525354
+#define SBI_EXT_PMU                            0x504D55
 
 /* SBI function IDs for BASE extension*/
 #define SBI_EXT_BASE_GET_SPEC_VERSION          0x0
@@ -91,6 +92,139 @@
 #define SBI_SRST_RESET_REASON_NONE     0x0
 #define SBI_SRST_RESET_REASON_SYSFAIL  0x1
 
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS       0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO   0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH  0x2
+#define SBI_EXT_PMU_COUNTER_START      0x3
+#define SBI_EXT_PMU_COUNTER_STOP       0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ    0x5
+
+/** General pmu event codes specified in SBI PMU extension */
+enum sbi_pmu_hw_generic_events_t {
+       SBI_PMU_HW_NO_EVENT                     = 0,
+       SBI_PMU_HW_CPU_CYCLES                   = 1,
+       SBI_PMU_HW_INSTRUCTIONS                 = 2,
+       SBI_PMU_HW_CACHE_REFERENCES             = 3,
+       SBI_PMU_HW_CACHE_MISSES                 = 4,
+       SBI_PMU_HW_BRANCH_INSTRUCTIONS          = 5,
+       SBI_PMU_HW_BRANCH_MISSES                = 6,
+       SBI_PMU_HW_BUS_CYCLES                   = 7,
+       SBI_PMU_HW_STALLED_CYCLES_FRONTEND      = 8,
+       SBI_PMU_HW_STALLED_CYCLES_BACKEND       = 9,
+       SBI_PMU_HW_REF_CPU_CYCLES               = 10,
+
+       SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *       { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *       { read, write, prefetch } x
+ *       { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+       SBI_PMU_HW_CACHE_L1D            = 0,
+       SBI_PMU_HW_CACHE_L1I            = 1,
+       SBI_PMU_HW_CACHE_LL             = 2,
+       SBI_PMU_HW_CACHE_DTLB           = 3,
+       SBI_PMU_HW_CACHE_ITLB           = 4,
+       SBI_PMU_HW_CACHE_BPU            = 5,
+       SBI_PMU_HW_CACHE_NODE           = 6,
+
+       SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+       SBI_PMU_HW_CACHE_OP_READ        = 0,
+       SBI_PMU_HW_CACHE_OP_WRITE       = 1,
+       SBI_PMU_HW_CACHE_OP_PREFETCH    = 2,
+
+       SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+       SBI_PMU_HW_CACHE_RESULT_ACCESS  = 0,
+       SBI_PMU_HW_CACHE_RESULT_MISS    = 1,
+
+       SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if the

hardware
+ * does not support performance events. These events are encoded as a raw
+ * event type in Linux kernel perf framework.
+ */

include/sbi/sbi_ecall_interface.h +71 -1
+enum sbi_pmu_fw_event_code_id {
+       SBI_PMU_FW_MISALIGNED_LOAD      = 0,
+       SBI_PMU_FW_MISALIGNED_STORE     = 1,
+       SBI_PMU_FW_ACCESS_LOAD          = 2,
+       SBI_PMU_FW_ACCESS_STORE         = 3,
+       SBI_PMU_FW_ILLEGAL_INSN         = 4,
+       SBI_PMU_FW_SET_TIMER            = 5,
+       SBI_PMU_FW_IPI_SENT             = 6,
+       SBI_PMU_FW_IPI_RECVD            = 7,
+       SBI_PMU_FW_FENCE_I_SENT         = 8,
+       SBI_PMU_FW_FENCE_I_RECVD        = 9,
+       SBI_PMU_FW_SFENCE_VMA_SENT      = 10,
+       SBI_PMU_FW_SFENCE_VMA_RCVD      = 11,
+       SBI_PMU_FW_SFENCE_VMA_ASID_SENT = 12,
+       SBI_PMU_FW_SFENCE_VMA_ASID_RCVD = 13,
+
+       SBI_PMU_FW_HFENCE_GVMA_SENT     = 14,
+       SBI_PMU_FW_HFENCE_GVMA_RCVD     = 15,
+       SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+       SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+       SBI_PMU_FW_HFENCE_VVMA_SENT     = 18,
+       SBI_PMU_FW_HFENCE_VVMA_RCVD     = 19,
+       SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+       SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+       SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+       SBI_PMU_EVENT_TYPE_HW                           = 0x0,
+       SBI_PMU_EVENT_TYPE_HW_CACHE                     = 0x1,
+       SBI_PMU_EVENT_TYPE_HW_RAW                       = 0x2,
+       SBI_PMU_EVENT_TYPE_FW                           = 0xf,
+       SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+       SBI_PMU_CTR_TYPE_HW = 0,
+       SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */
+#define SBI_PMU_EVENT_IDX_OFFSET 20
+#define SBI_PMU_EVENT_IDX_MASK 0xFFFFF
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF
+#define SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000
+#define SBI_PMU_EVENT_RAW_IDX 0x20000
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH    (1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE   (1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START    (1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH      (1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH      (1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH      (1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH     (1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH     (1 << 7)
+
+/* Flags defined for counter start function */
+#define SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */
+#define SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */
 #define SBI_SPEC_VERSION_MAJOR_OFFSET          24
 #define SBI_SPEC_VERSION_MAJOR_MASK            0x7f
 #define SBI_SPEC_VERSION_MINOR_MASK            0xffffff
@@ -107,8 +241,10 @@
 #define SBI_ERR_DENIED                         -4
 #define SBI_ERR_INVALID_ADDRESS                        -5
 #define SBI_ERR_ALREADY_AVAILABLE              -6
+#define SBI_ERR_ALREADY_STARTED                        -7
+#define SBI_ERR_ALREADY_STOPPED                        -8
 
-#define

SBI_LAST_ERR SBI_ERR_ALREADY_AVAILABLE
+#define
SBI_LAST_ERR SBI_ERR_ALREADY_STOPPED

/* clang-format on */

include/sbi/sbi_error.h +2 -0
index 3655d122006b..dd65e14b6fcd 100644
@@ -21,6 +21,8 @@
 #define SBI_EDENIED            SBI_ERR_DENIED
 #define SBI_EINVALID_ADDR      SBI_ERR_INVALID_ADDRESS
 #define SBI_EALREADY           SBI_ERR_ALREADY_AVAILABLE
+#define SBI_EALREADY_STARTED   SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED   SBI_ERR_ALREADY_STOPPED
 
 #define SBI_ENODEV             -1000
 #define SBI_ENOSYS             -1001
include/sbi/sbi_pmu.h new file +28 -0
new file mode 100644
index 000000000000..b3010cc5c1ce
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI */
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI */
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX           (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +9 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This

should be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end End of the event idx range for supported
counters
+ * @param cmap A bitmap representing counters supporting the
event range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap);

include/sbi/sbi_pmu.h new file +3 -0
+
+/**
+ * Add the raw hardware event selector and supported counter

information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */

include/sbi/sbi_pmu.h new file +6 -0
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap);
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long

cidx_mask,

include/sbi/sbi_pmu.h new file +3 -0
+                    unsigned long flag);
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long

cidx_mask,

include/sbi/sbi_pmu.h new file +7 -0
+                     unsigned long flags, uint64_t ival);
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info);
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+ unsigned long flags, unsigned long
event_idx,

include/sbi/sbi_pmu.h new file +5 -0
+                         uint64_t event_data);
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk +1 -0
index 6f2c06f5b501..d9068b707854 100644
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o
 libsbi-objs-y += sbi_ipi.o
 libsbi-objs-y += sbi_misaligned_ldst.o
 libsbi-objs-y += sbi_platform.o
+libsbi-objs-y += sbi_pmu.o
 libsbi-objs-y += sbi_scratch.o
 libsbi-objs-y += sbi_string.o
 libsbi-objs-y += sbi_system.o
lib/sbi/sbi_init.c +3 -0
index 65af5705f484..143b98f93c02 100644
@@ -19,6 +19,7 @@
 #include <sbi/sbi_hsm.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_system.h>
 #include <sbi/sbi_string.h>
 #include <sbi/sbi_timer.h>
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
        if (rc)
                sbi_hart_hang();
 
+       sbi_pmu_init(scratch, TRUE);
+
        sbi_boot_print_banner(scratch);
 
        rc = sbi_platform_irqchip_init(plat, TRUE);
lib/sbi/sbi_init.c +2 -0
@@ -353,6 +356,8 @@ static void init_warm_startup(struct sbi_scratch
 *scratch, u32 hartid)
        if (rc)
                sbi_hart_hang();
 
+       sbi_pmu_init(scratch, FALSE);
+
        rc = sbi_platform_irqchip_init(plat, FALSE);
        if (rc)
                sbi_hart_hang();
lib/sbi/sbi_init.c +2 -0
@@ -393,6 +398,8 @@ static void init_warm_resume(struct sbi_scratch
 *scratch)
        if (rc)
                sbi_hart_hang();
 
+       sbi_pmu_init(scratch, FALSE);
+
        rc = sbi_hart_pmp_configure(scratch);
        if (rc)
                sbi_hart_hang();
lib/sbi/sbi_init.c +2 -0
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch
 *scratch)
 
        sbi_platform_early_exit(plat);
 
+       sbi_pmu_exit(scratch);
+
        sbi_timer_exit(scratch);
 
        sbi_ipi_exit(scratch);
lib/sbi/sbi_pmu.c new file +57 -0
new file mode 100644
index 000000000000..ed519dfcc860
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */
+struct sbi_pmu_hw_event {
+       unsigned long counters;
+       unsigned long start_idx;
+       unsigned long end_idx;
+       /* Event selector value used only for raw events */
+       uint64_t select;
+};
+
+/** Representation of a firmware event */
+struct sbi_pmu_fw_event {
+
+       /* Event associated with the particular counter */
+       unsigned long event_idx;
+
+       /* Current value of the counter */
+       unsigned long curr_count;
+
+       /* A flag indicating pmu event monitoring is started */
+       bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */
+union sbi_pmu_ctr_info {
+       unsigned long value;
+       struct {
+               unsigned long csr:12;
+               unsigned long width:6;
+#if __riscv_xlen == 32
+               unsigned long reserved:13;
+#else
+               unsigned long reserved:45;
+#endif
+               unsigned long type:1;
+       };
+};
+
+/* Mapping between event range and possible counters  */
+static struct sbi_pmu_hw_event hw_event_map[SBI_PMU_HW_EVENT_MAX] =

{0};

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX + SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +3 -0
+
+/* Contains all the information about firmwares events */
+static struct sbi_pmu_fw_event

fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] = {0};

lib/sbi/sbi_pmu.c new file +15 -0
+
+/* Maximum number of hardware events available */
+static uint32_t num_hw_events;
+/* Maximum number of hardware counters available */
+static uint32_t num_hw_ctrs;
+
+/* Maximum number of counters available */
+static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */
+#define get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >> 16)
+#define get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event

range overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise
+ */

lib/sbi/sbi_pmu.c new file +4 -0
+static bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+                                   struct sbi_pmu_hw_event *evtB)
+{
+       /* check if the range of events overlap with a previous entry
Quoted 5 lines

*/
+ if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx <
evtB->end_idx)) ||
+ ((evtA->start_idx > evtB->start_idx) && (evtA->start_idx >
evtB->end_idx)))

Because start_idx is always less than or equal to end_idx, the above condition can be simplified to?

Quoted 3 lines
                    if (evtA->end_idx < evtB->start_idx
                        || evtA->start_idx > evtB->end_idx)

Sure. Thanks for the review.

Quoted 88 lines
Quoted 88 lines
lib/sbi/sbi_pmu.c new file +23 -0
+               return FALSE;
+       return TRUE;
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event *evt,
+                                    uint64_t select_val)
+{
+
+       if (evt->select == select_val)
+               return TRUE;
+
+       return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t *event_idx_code)
+{
+       uint32_t event_idx_val;
+       uint32_t event_idx_type;
+       u32 hartid = current_hartid();
+
+       event_idx_val = active_events[hartid][cidx];
+
+       if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))

lib/sbi/sbi_pmu.c new file +24 -0
+               return SBI_EINVAL;
+
+       event_idx_type = get_cidx_type(event_idx_val);
+       if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+               return SBI_EINVAL;
+
+       *event_idx_code = get_cidx_code(event_idx_val);
+
+       return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+                              uint32_t fw_evt_code)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event fevent;
+
+       fevent = fw_event_map[hartid][fw_evt_code];
+       *cval = fevent.curr_count;
+
+       return 0;
+}
+
+/* Add a hardware counter read for completeness for future purpose

*/

lib/sbi/sbi_pmu.c new file +33 -0
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval)
+{
+#if __riscv_xlen == 32
+       uint32_t temp, temph = 0;
+
+       temp = csr_read_num(CSR_MCYCLE + cidx);
+       temph = csr_read_num(CSR_MCYCLEH + cidx);
+       *cval = ((uint64_t)temph << 32) | temp;
+#else
+       *cval = csr_read_num(CSR_MCYCLE + cidx);
+#endif
+
+       return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval)
+{
+       int event_idx_type;
+       uint32_t event_code;
+       uint64_t cval64;
+
+       event_idx_type = pmu_ctr_validate(cidx, &event_code);
+       if (event_idx_type < 0)
+               return SBI_EINVAL;
+       else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+               pmu_ctr_read_fw(cidx, cval, event_code);
+       else
+               pmu_ctr_read_hw(cidx, &cval64);
+
+       return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end, u32

cmap,

lib/sbi/sbi_pmu.c new file +5 -0
+                               uint64_t select)
+{
+       int i = 0;
+       bool is_overlap;
+       struct sbi_pmu_hw_event *event =
Quoted 9 lines

lib/sbi/sbi_pmu.c line 180

Quoted 7 lines

&hw_event_map[num_hw_events];

lib/sbi/sbi_pmu.c new file +6 -0
+
+       /* The first two counters are reserved by priv spec */
+       if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1) ||
+           (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap != 0x4) ||
+           (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap < 0x08))
+               return SBI_EDENIED;

Should we add restriction eidx_start <= eidx_end

Yeah. I will add that in v3.

Quoted 1 line

can cmap have a gaps?

Yes. But the example is not valid because the cmap is a bitmap of all the counters
that can be programmed to monitor specified events between eidx_start and eidx_end.
In this example, cmap can't handle SBI_PMU_HW_CPU_CYCLES/INSTRUCTIONS.

Quoted 318 lines

The above test may not be appropriate.
ex:
eidx_start = SBI_PMU_HW_CPU_CYCLES
eidx_end = 8
cmap = 0xd0

Quoted 312 lines
lib/sbi/sbi_pmu.c new file +3 -0
+
+       if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) {
+               sbi_printf("Can not handle more than %d perf

events\n",

lib/sbi/sbi_pmu.c new file +13 -0
+                           SBI_PMU_HW_EVENT_MAX);
+               return SBI_EFAIL;
+       }
+
+       event->start_idx = eidx_start;
+       event->end_idx = eidx_end;
+       event->counters = cmap;
+       event->select = select;
+
+       /* Sanity check */
+       for (i = 0; i < num_hw_events; i++) {
+               if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+               /* All raw events have same event idx. Just do sanity

check on select */
+ is_overlap =
pmu_event_select_overlap(&hw_event_map[i], select);

lib/sbi/sbi_pmu.c new file +2 -0
+               else
+                       is_overlap =

pmu_event_range_overlap(&hw_event_map[i], event);

lib/sbi/sbi_pmu.c new file +10 -0
+               if (is_overlap)
+                       return SBI_EINVALID_ADDR;
+       }
+       num_hw_events++;
+
+       return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are

assigned consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret. Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32 cmap)

lib/sbi/sbi_pmu.c new file +2 -0
+{
+       if ((eidx_start > eidx_end) || eidx_start ==

SBI_PMU_EVENT_RAW_IDX ||

lib/sbi/sbi_pmu.c new file +10 -0
+            eidx_end == SBI_PMU_EVENT_RAW_IDX)
+               return SBI_EINVAL;
+
+       return pmu_add_hw_event_map(eidx_start, eidx_end, cmap, 0);
+}
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap)
+{
+       return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+                                   SBI_PMU_EVENT_RAW_IDX, cmap,

select);

lib/sbi/sbi_pmu.c new file +13 -0
+}
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival)
+{
+#if __riscv_xlen == 32
+       csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
+       csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG);
+#else
+       csr_write_num(CSR_MCYCLE + cidx, ival);
+#endif
+}
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool

ival_update)

lib/sbi/sbi_pmu.c new file +8 -0
+{
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+       if (cidx > num_hw_ctrs)
+               return SBI_EINVAL;
+
+       if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt))

lib/sbi/sbi_pmu.c new file +45 -0
+               return SBI_EALREADY_STARTED;
+
+       __set_bit(cidx, &mctr_en);
+       __clear_bit(cidx, &mctr_inhbt);
+
+       if (ival_update)
+               pmu_ctr_write_hw(cidx, ival);
+
+       csr_write(CSR_MCOUNTEREN, mctr_en);
+       csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+       return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+                           uint64_t ival, bool ival_update)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event *fevent;
+
+       fevent = &fw_event_map[hartid][fw_evt_code];
+       if (ival_update)
+               fevent->curr_count = ival;
+       fevent->bStarted = TRUE;
+
+       return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+                     unsigned long flags, uint64_t ival)
+{
+       int event_idx_type;
+       uint32_t event_code;
+       unsigned long ctr_mask = cmask << cbase;
+       int ret = SBI_EINVAL;
+       bool bUpdate = FALSE;
+
+       if (cbase >= total_ctrs)
+               return ret;
+
+       if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+               bUpdate = TRUE;
+
+       for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+               event_idx_type = pmu_ctr_validate(cbase,

&event_code);

lib/sbi/sbi_pmu.c new file +4 -0
+               if (event_idx_type < 0)
+                       return SBI_EINVAL;
+               else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+                       ret = pmu_ctr_start_fw(cbase, event_code,

ival, bUpdate);

lib/sbi/sbi_pmu.c new file +13 -0
+               else
+                       ret = pmu_ctr_start_hw(cbase, ival, bUpdate);
+       }
+
+       return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx)
+{
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+       if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx,

&mctr_inhbt)) {

lib/sbi/sbi_pmu.c new file +32 -0
+               __set_bit(cidx, &mctr_inhbt);
+               __clear_bit(cidx, &mctr_en);
+               csr_write(CSR_MCOUNTEREN, mctr_en);
+               csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+               return 0;
+       } else
+               return SBI_EALREADY_STOPPED;
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code)
+{
+       u32 hartid = current_hartid();
+
+       fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+       return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+                    unsigned long flag)
+{
+       u32 hartid = current_hartid();
+       int ret = SBI_EINVAL;
+       int event_idx_type;
+       uint32_t event_code;
+       unsigned long ctr_mask = cmask << cbase;
+
+       if (cbase >= total_ctrs)
+               return SBI_EINVAL;
+
+       for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+               event_idx_type = pmu_ctr_validate(cbase,

&event_code);

lib/sbi/sbi_pmu.c new file +10 -0
+               if (event_idx_type < 0)
+                       return SBI_EINVAL;
+
+               else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+                       ret = pmu_ctr_stop_fw(cbase, event_code);
+               else
+                       ret = pmu_ctr_stop_hw(cbase);
+
+               if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+                       active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;

lib/sbi/sbi_pmu.c new file +6 -0
+       }
+
+       return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event *hw_evt,

int ctr_idx,
+ unsigned long eindex, uint64_t
data)

lib/sbi/sbi_pmu.c new file +6 -0
+{
+       struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+       const struct sbi_platform *plat = sbi_platform_ptr(scratch);
+       uint64_t mhpmevent_val;
+
+       /* Get the final mhpmevent value to be written from platform

*/
+ mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat,
eindex, data);

lib/sbi/sbi_pmu.c new file +2 -0
+
+       if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >=

SBI_PMU_HW_CTR_MAX)

lib/sbi/sbi_pmu.c new file +3 -0
+               return SBI_EFAIL;
+
+       /* TODO: The upper 8 bits of mhpmevent is reserved by

sscofpmf extension.
+ * Update those bits based on the flags received from
supervisor.
+ * The OVF bit also should be cleared here in case it was not
cleared

lib/sbi/sbi_pmu.c new file +23 -0
+        * during event stop.
+        */
+       csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx, mhpmevent_val);
+
+       return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long cmask,
+                          unsigned long event_idx, uint64_t data)
+{
+       unsigned long ctr_mask;
+       int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+       struct sbi_pmu_hw_event *temp;
+       unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+       unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+       int evt_idx_code = get_cidx_code(event_idx);
+
+       if (cbase > num_hw_ctrs)
+               return SBI_EINVAL;
+
+       for (i = 0; i < num_hw_events; i++) {
+               temp = &hw_event_map[i];
+               if ((temp->start_idx > event_idx && event_idx < temp-
Quoted 1 line

end_idx) ||

+ (temp->start_idx < event_idx && event_idx > temp-

Quoted 1 line

end_idx))

lib/sbi/sbi_pmu.c new file +3 -0
+                       continue;
+
+               /* For raw events, event data is used as the select

value */
+ if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-

Quoted 1 line

select != data)

lib/sbi/sbi_pmu.c new file +4 -0
+                       continue;
+
+               ctr_mask = temp->counters & (cmask << cbase);
+               for_each_set_bit_from(cbase, &ctr_mask,

SBI_PMU_HW_CTR_MAX) {

lib/sbi/sbi_pmu.c new file +15 -0
+                       if (!__test_bit(cbase, &mctr_en) &&
+                           __test_bit(cbase, &mctr_inhbt)) {
+                               ctr_idx = cbase;
+                               break;
+                       }
+               }
+       }
+
+       if (ctr_idx == SBI_ENOTSUPP)
+               return SBI_EFAIL;
+
+       /* No need to update the  event selectors for fixed events */
+       if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES &&
+           evt_idx_code != SBI_PMU_HW_INSTRUCTIONS)
+               ret = pmu_update_hw_mhpmevent(temp, ctr_idx,

event_idx, data);

lib/sbi/sbi_pmu.c new file +14 -0
+
+       if (!ret)
+               ret = ctr_idx;
+
+       return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long cmask,

u32 hartid)

lib/sbi/sbi_pmu.c new file +12 -0
+{
+       int i = 0;
+       int fw_base;
+       unsigned long ctr_mask = cmask << cbase;
+
+       if (cbase <= num_hw_ctrs)
+               fw_base = num_hw_ctrs + 1;
+       else
+               fw_base = cbase;
+
+       for (i = fw_base; i < total_ctrs; i++)
+               if ((active_events[hartid][i] ==

SBI_PMU_EVENT_IDX_INVALID) &&

lib/sbi/sbi_pmu.c new file +7 -0
+                   ((1UL << i) & ctr_mask))
+                       return i;
+
+       return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,
+ unsigned long flags, unsigned long
event_idx,

lib/sbi/sbi_pmu.c new file +6 -0
+                         uint64_t event_data)
+{
+       int ctr_idx = SBI_ENOTSUPP;
+       u32 hartid = current_hartid();
+       int event_type = get_cidx_type(event_idx);
+       struct sbi_pmu_fw_event *fevent;
Quoted 9 lines

lib/sbi/sbi_pmu.c line 464

Quoted 6 lines
lib/sbi/sbi_pmu.c new file +6 -0
+       uint32_t fw_evt_code;
+       unsigned long tmp = cidx_mask << cidx_base;
+
+       /* Do a basic sanity check of counter base & mask */
+       if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs ||
+           event_type >= SBI_PMU_EVENT_TYPE_MAX)

We can remove cidx_base >= total_ctrs, because __fls(tmp) always large then cidx_base

Correct. Removed in v3. Thanks.

Quoted 156 lines
Quoted 146 lines
lib/sbi/sbi_pmu.c new file +4 -0
+               return SBI_EINVAL;
+
+       if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) {
+               /* The caller wants to skip the match because it

already knows the
+ * counter idx for the given event. Verify that the
counter idx

lib/sbi/sbi_pmu.c new file +3 -0
+                * is still valid.
+                */
+               if (active_events[hartid][cidx_base] ==

SBI_PMU_EVENT_IDX_INVALID)

lib/sbi/sbi_pmu.c new file +7 -0
+                       return SBI_EINVAL;
+               ctr_idx = cidx_base;
+               goto skip_match;
+       }
+
+       if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+               /* Any firmware counter can be used track any

firmware event */
+ ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask,
hartid);

lib/sbi/sbi_pmu.c new file +2 -0
+       } else {
+               ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask,

event_idx, event_data);

lib/sbi/sbi_pmu.c new file +35 -0
+       }
+
+       if (ctr_idx < 0)
+               return SBI_ENOTSUPP;
+
+       active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+       if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+               if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+                       pmu_ctr_write_hw(ctr_idx, 0);
+               if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+                       pmu_ctr_start_hw(ctr_idx, 0, false);
+       } else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+               fw_evt_code = get_cidx_code(event_idx);
+               fevent = &fw_event_map[hartid][fw_evt_code];
+               if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+                       fevent->curr_count = 0;
+               if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+                       fevent->bStarted = TRUE;
+       }
+
+       return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id)
+{
+       u32 hartid = current_hartid();
+       struct sbi_pmu_fw_event *fevent;
+
+       if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+               return SBI_EINVAL;
+
+       fevent = &fw_event_map[hartid][fw_id];
+
+       /* PMU counters will be only enabled during performance

debugging */

lib/sbi/sbi_pmu.c new file +21 -0
+       if (unlikely(fevent->bStarted))
+               fevent->curr_count++;
+
+       return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+       return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX);
+}
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info)
+{
+       union sbi_pmu_ctr_info cinfo = {0};
+       struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+       /* Sanity check. Counter1 is not mapped at all */
+       if (cidx >= total_ctrs || cidx == 1)
+               return SBI_EINVAL;
+
+       /* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */

lib/sbi/sbi_pmu.c new file +46 -0
+       if (cidx <= num_hw_ctrs) {
+               cinfo.type = SBI_PMU_CTR_TYPE_HW;
+               cinfo.csr = CSR_CYCLE + cidx;
+               /* mcycle & minstret are always 64 bit */
+               if (cidx == 0 || cidx == 2)
+                       cinfo.width = 63;
+               else
+                       cinfo.width = sbi_hart_mhpm_bits(scratch);
+       } else {
+               /* it's a firmware counter */
+               cinfo.type = SBI_PMU_CTR_TYPE_FW;
+               /* Firmware counters are XLEN bits wide */
+               cinfo.width = BITS_PER_LONG - 1;
+       }
+
+       *ctr_info = cinfo.value;
+
+       return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid)
+{
+       int j;
+
+       /* Initialize the counter to event mapping table */
+       for (j = 0; j < total_ctrs; j++)
+               active_events[hartid][j] = SBI_PMU_EVENT_IDX_INVALID;
+       for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++)
+               sbi_memset(&fw_event_map[hartid][j], 0,
+                          sizeof(struct sbi_pmu_fw_event));
+}
+
+void sbi_pmu_exit(struct sbi_scratch *scratch)
+{
+       u32 hartid = current_hartid();
+
+       csr_write(CSR_MCOUNTINHIBIT, -1);
+       csr_write(CSR_MCOUNTEREN, 2);
+       pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot)
+{
+       const struct sbi_platform *plat;
+
+       if (!sbi_hart_has_feature(scratch,

SBI_HART_HAS_MCOUNTINHIBIT))

lib/sbi/sbi_pmu.c new file +16 -1
+               return SBI_ENOTSUPP;
+
+       if (cold_boot) {
+               plat = sbi_platform_ptr(scratch);
+               /* Initialize hw pmu events */
+               sbi_platform_pmu_init(plat);
+
+               /* mcycle & minstret is available always */
+               num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+               total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+       }
+
+       pmu_reset_event_map(current_hartid());
+
+       return 0;
+}
--
Quoted 3 lines

2.25.1

--
opensbi mailing list
opensbi at lists.infradead.org
http://lists.infradead.org/mailman/listinfo/opensbi

Signature · 2 lines
Regards,
Atish
#36 lore raw

PATCH v2 10/15 lib: sbi: Add PMU support

In reply to Atish Patra
Quoted 163 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 10/15] lib: sbi: Add PMU support

RISC-V SBI v0.3 specification defined a PMU extension to configure/start/stop the hardware/firmware pmu events.

Implement PMU support in OpenSBI library. The implementation is agnostic of event to counter mapping & mhpmevent value configuration. That means, it expects platform hooks will be used to set up the mapping and provide the mhpmevent value at runtime.

---
 include/sbi/sbi_ecall_interface.h | 138 ++++++-
 include/sbi/sbi_error.h           |   2 +
 include/sbi/sbi_pmu.h             |  73 ++++
 lib/sbi/objects.mk                |   1 +
 lib/sbi/sbi_init.c                |   9 +
 lib/sbi/sbi_pmu.c                 | 600 ++++++++++++++++++++++++++++++
 6 files changed, 822 insertions(+), 1 deletion(-)  create mode 100644

include/sbi/sbi_pmu.h create mode 100644 lib/sbi/sbi_pmu.c

include/sbi/sbi_ecall_interface.h +112 -0
index 559a33e7ced0..8fc723bc212c 100644
@@ -28,6 +28,7 @@
 #define SBI_EXT_RFENCE				0x52464E43
 #define SBI_EXT_HSM				0x48534D
 #define SBI_EXT_SRST				0x53525354
+#define SBI_EXT_PMU				0x504D55
 
 /* SBI function IDs for BASE extension*/
 #define SBI_EXT_BASE_GET_SPEC_VERSION		0x0
@@ -91,6 +92,139 @@
 #define SBI_SRST_RESET_REASON_NONE	0x0
 #define SBI_SRST_RESET_REASON_SYSFAIL	0x1
 
+/* SBI function IDs for PMU extension */
+#define SBI_EXT_PMU_NUM_COUNTERS	0x0
+#define SBI_EXT_PMU_COUNTER_GET_INFO	0x1
+#define SBI_EXT_PMU_COUNTER_CFG_MATCH	0x2
+#define SBI_EXT_PMU_COUNTER_START	0x3
+#define SBI_EXT_PMU_COUNTER_STOP	0x4
+#define SBI_EXT_PMU_COUNTER_FW_READ	0x5
+
+/** General pmu event codes specified in SBI PMU extension */ enum
+sbi_pmu_hw_generic_events_t {
+	SBI_PMU_HW_NO_EVENT			= 0,
+	SBI_PMU_HW_CPU_CYCLES			= 1,
+	SBI_PMU_HW_INSTRUCTIONS			= 2,
+	SBI_PMU_HW_CACHE_REFERENCES		= 3,
+	SBI_PMU_HW_CACHE_MISSES			= 4,
+	SBI_PMU_HW_BRANCH_INSTRUCTIONS		= 5,
+	SBI_PMU_HW_BRANCH_MISSES		= 6,
+	SBI_PMU_HW_BUS_CYCLES			= 7,
+	SBI_PMU_HW_STALLED_CYCLES_FRONTEND	= 8,
+	SBI_PMU_HW_STALLED_CYCLES_BACKEND	= 9,
+	SBI_PMU_HW_REF_CPU_CYCLES		= 10,
+
+	SBI_PMU_HW_GENERAL_MAX,
+};
+
+/**
+ * Generalized hardware cache events:
+ *
+ *       { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x
+ *       { read, write, prefetch } x
+ *       { accesses, misses }
+ */
+enum sbi_pmu_hw_cache_id {
+	SBI_PMU_HW_CACHE_L1D		= 0,
+	SBI_PMU_HW_CACHE_L1I		= 1,
+	SBI_PMU_HW_CACHE_LL		= 2,
+	SBI_PMU_HW_CACHE_DTLB		= 3,
+	SBI_PMU_HW_CACHE_ITLB		= 4,
+	SBI_PMU_HW_CACHE_BPU		= 5,
+	SBI_PMU_HW_CACHE_NODE		= 6,
+
+	SBI_PMU_HW_CACHE_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_id {
+	SBI_PMU_HW_CACHE_OP_READ	= 0,
+	SBI_PMU_HW_CACHE_OP_WRITE	= 1,
+	SBI_PMU_HW_CACHE_OP_PREFETCH	= 2,
+
+	SBI_PMU_HW_CACHE_OP_MAX,
+};
+
+enum sbi_pmu_hw_cache_op_result_id {
+	SBI_PMU_HW_CACHE_RESULT_ACCESS	= 0,
+	SBI_PMU_HW_CACHE_RESULT_MISS	= 1,
+
+	SBI_PMU_HW_CACHE_RESULT_MAX,
+};
+
+/**
+ * Special "firmware" events provided by the OpenSBI, even if the
+hardware
+ * does not support performance events. These events are encoded as a
+raw
+ * event type in Linux kernel perf framework.
+ */
+enum sbi_pmu_fw_event_code_id {
+	SBI_PMU_FW_MISALIGNED_LOAD	= 0,
+	SBI_PMU_FW_MISALIGNED_STORE	= 1,
+	SBI_PMU_FW_ACCESS_LOAD		= 2,
+	SBI_PMU_FW_ACCESS_STORE		= 3,
+	SBI_PMU_FW_ILLEGAL_INSN		= 4,
+	SBI_PMU_FW_SET_TIMER		= 5,
+	SBI_PMU_FW_IPI_SENT		= 6,
+	SBI_PMU_FW_IPI_RECVD		= 7,
+	SBI_PMU_FW_FENCE_I_SENT		= 8,
+	SBI_PMU_FW_FENCE_I_RECVD	= 9,
+	SBI_PMU_FW_SFENCE_VMA_SENT	= 10,
+	SBI_PMU_FW_SFENCE_VMA_RCVD	= 11,
+	SBI_PMU_FW_SFENCE_VMA_ASID_SENT	= 12,
+	SBI_PMU_FW_SFENCE_VMA_ASID_RCVD	= 13,
+
+	SBI_PMU_FW_HFENCE_GVMA_SENT	= 14,
+	SBI_PMU_FW_HFENCE_GVMA_RCVD	= 15,
+	SBI_PMU_FW_HFENCE_GVMA_VMID_SENT = 16,
+	SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD = 17,
+
+	SBI_PMU_FW_HFENCE_VVMA_SENT	= 18,
+	SBI_PMU_FW_HFENCE_VVMA_RCVD	= 19,
+	SBI_PMU_FW_HFENCE_VVMA_ASID_SENT = 20,
+	SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD = 21,
+	SBI_PMU_FW_MAX,
+};
+
+/** SBI PMU event idx type */
+enum sbi_pmu_event_type_id {
+	SBI_PMU_EVENT_TYPE_HW				= 0x0,
+	SBI_PMU_EVENT_TYPE_HW_CACHE			= 0x1,
+	SBI_PMU_EVENT_TYPE_HW_RAW			= 0x2,
+	SBI_PMU_EVENT_TYPE_FW				= 0xf,
+	SBI_PMU_EVENT_TYPE_MAX,
+};
+
+/** SBI PMU counter type */
+enum sbi_pmu_ctr_type {
+	SBI_PMU_CTR_TYPE_HW = 0,
+	SBI_PMU_CTR_TYPE_FW,
+};
+
+/* Helper macros to decode event idx */ #define
+SBI_PMU_EVENT_IDX_OFFSET 20 #define SBI_PMU_EVENT_IDX_MASK

0xFFFFF

include/sbi/sbi_ecall_interface.h +2 -0
+#define SBI_PMU_EVENT_IDX_CODE_MASK 0xFFFF #define
+SBI_PMU_EVENT_IDX_TYPE_MASK 0xF0000 #define

SBI_PMU_EVENT_RAW_IDX
+0x20000

include/sbi/sbi_ecall_interface.h +2 -0
+
+#define SBI_PMU_EVENT_IDX_INVALID 0xFFFFFFFF

include/sbi/sbi_ecall_interface.h line 219

Quoted 10 lines
include/sbi/sbi_ecall_interface.h +10 -0
+
+/* Flags defined for config matching function */
+#define SBI_PMU_CFG_FLAG_SKIP_MATCH	(1 << 0)
+#define SBI_PMU_CFG_FLAG_CLEAR_VALUE	(1 << 1)
+#define SBI_PMU_CFG_FLAG_AUTO_START	(1 << 2)
+#define SBI_PMU_CFG_FLAG_SET_MINH	(1 << 3)
+#define SBI_PMU_CFG_FLAG_SET_SINH	(1 << 4)
+#define SBI_PMU_CFG_FLAG_SET_UINH	(1 << 5)
+#define SBI_PMU_CFG_FLAG_SET_VSINH	(1 << 6)
+#define SBI_PMU_CFG_FLAG_SET_VUINH	(1 << 7)

Make sure to sync-up these flags from latest SBI PMU spec.

Quoted 797 lines
include/sbi/sbi_ecall_interface.h +11 -1
+
+/* Flags defined for counter start function */ #define
+SBI_PMU_START_FLAG_SET_INIT_VALUE (1 << 0)
+
+/* Flags defined for counter stop function */ #define
+SBI_PMU_STOP_FLAG_RESET (1 << 0)
+
+/* SBI base specification related macros */
 #define SBI_SPEC_VERSION_MAJOR_OFFSET		24
 #define SBI_SPEC_VERSION_MAJOR_MASK		0x7f
 #define SBI_SPEC_VERSION_MINOR_MASK		0xffffff
@@ -107,8 +241,10 @@
 #define SBI_ERR_DENIED				-4
 #define SBI_ERR_INVALID_ADDRESS			-5
 #define SBI_ERR_ALREADY_AVAILABLE		-6
+#define SBI_ERR_ALREADY_STARTED			-7
+#define SBI_ERR_ALREADY_STOPPED			-8
 
-#define SBI_LAST_ERR
 	SBI_ERR_ALREADY_AVAILABLE
+#define SBI_LAST_ERR				SBI_ERR_ALREADY_STOPPED
 
 /* clang-format on */
include/sbi/sbi_error.h index renamed from include/sbi/sbi_error.h +0 -0

3655d122006b..dd65e14b6fcd 100644

include/sbi/sbi_error.h +2 -0
@@ -21,6 +21,8 @@
 #define SBI_EDENIED		SBI_ERR_DENIED
 #define SBI_EINVALID_ADDR	SBI_ERR_INVALID_ADDRESS
 #define SBI_EALREADY		SBI_ERR_ALREADY_AVAILABLE
+#define SBI_EALREADY_STARTED	SBI_ERR_ALREADY_STARTED
+#define SBI_EALREADY_STOPPED	SBI_ERR_ALREADY_STOPPED
 
 #define SBI_ENODEV		-1000
 #define SBI_ENOSYS		-1001
include/sbi/sbi_pmu.h new file mode renamed from include/sbi/sbi_pmu.h +0 -0

100644 index 000000000000..b3010cc5c1ce

include/sbi/sbi_pmu.h new file +28 -0
@@ -0,0 +1,73 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#ifndef __SBI_PMU_H__
+#define __SBI_PMU_H__
+
+#include <sbi/sbi_types.h>
+#include <sbi/sbi_hartmask.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_ecall_interface.h>
+
+/* Event related macros */
+/* Maximum number of hardware events that can mapped by OpenSBI */
+#define SBI_PMU_HW_EVENT_MAX 64
+
+/* Maximum number of firmware events that can mapped by OpenSBI */
+#define SBI_PMU_FW_EVENT_MAX 32
+
+/* Counter related macros */
+#define SBI_PMU_FW_CTR_MAX 16
+#define SBI_PMU_HW_CTR_MAX 32
+#define SBI_PMU_CTR_MAX	   (SBI_PMU_HW_CTR_MAX +

SBI_PMU_FW_CTR_MAX)

include/sbi/sbi_pmu.h new file +14 -0
+
+/** Initialize PMU */
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot);
+
+/** Reset PMU during hart exit */
+void sbi_pmu_exit(struct sbi_scratch *scratch);
+
+/**
+ * Add the hardware event to counter mapping information. This should
+be called
+ * from the platform code to update the mapping table.
+ * @param eidx_start Start of the event idx range for supported counters
+ * @param eidx_end   End of the event idx range for supported counters
+ * @param cmap       A bitmap representing counters supporting the event

range
+ * @return 0 on success, error otherwise.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end, u32

include/sbi/sbi_pmu.h new file +25 -0
+cmap);
+
+/**
+ * Add the raw hardware event selector and supported counter
+information. This
+ * should be called from the platform code to update the mapping table.
+ * @param info  a pointer to the hardware event info
+ * @return 0 on success, error otherwise.
+ */
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap);
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval);
+
+int sbi_pmu_ctr_stop(unsigned long cidx_base, unsigned long cidx_mask,
+		     unsigned long flag);
+
+int sbi_pmu_ctr_start(unsigned long cidx_base, unsigned long cidx_mask,
+		      unsigned long flags, uint64_t ival);
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info);
+
+unsigned long sbi_pmu_num_ctr(void);
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,

include/sbi/sbi_pmu.h new file +6 -0
+			  unsigned long flags, unsigned long event_idx,
+			  uint64_t event_data);
+
+int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id);
+
+#endif
lib/sbi/objects.mk index renamed from lib/sbi/objects.mk +0 -0

6f2c06f5b501..d9068b707854 100644

lib/sbi/objects.mk +0 -0
@@ -33,6 +33,7 @@ libsbi-objs-y += sbi_init.o  libsbi-objs-y += sbi_ipi.o

libsbi-objs-y += sbi_misaligned_ldst.o libsbi-objs-y += sbi_platform.o

lib/sbi/objects.mk +1 -0
+libsbi-objs-y += sbi_pmu.o
 libsbi-objs-y += sbi_scratch.o
 libsbi-objs-y += sbi_string.o
 libsbi-objs-y += sbi_system.o
lib/sbi/sbi_init.c index renamed from lib/sbi/sbi_init.c +0 -0

65af5705f484..143b98f93c02 100644

lib/sbi/sbi_init.c +3 -0
@@ -19,6 +19,7 @@
 #include <sbi/sbi_hsm.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_system.h>
 #include <sbi/sbi_string.h>
 #include <sbi/sbi_timer.h>
@@ -252,6 +253,8 @@ static void __noreturn init_coldboot(struct
 sbi_scratch *scratch, u32 hartid)
 	if (rc)
 		sbi_hart_hang();
 
+	sbi_pmu_init(scratch, TRUE);
+
 	sbi_boot_print_banner(scratch);
 

rc = sbi_platform_irqchip_init(plat, TRUE); @@ -353,6 +356,8 @@
static void init_warm_startup(struct sbi_scratch *scratch, u32 hartid)

lib/sbi/sbi_init.c +4 -0
 	if (rc)
 		sbi_hart_hang();
 
+	sbi_pmu_init(scratch, FALSE);
+
 	rc = sbi_platform_irqchip_init(plat, FALSE);
 	if (rc)
 		sbi_hart_hang();
@@ -393,6 +398,8 @@ static void init_warm_resume(struct sbi_scratch
 *scratch)
 	if (rc)
 		sbi_hart_hang();
 
+	sbi_pmu_init(scratch, FALSE);
+
 	rc = sbi_hart_pmp_configure(scratch);
 	if (rc)
lib/sbi/sbi_init.c +2 -0
 		sbi_hart_hang();
@@ -516,6 +523,8 @@ void __noreturn sbi_exit(struct sbi_scratch *scratch)
 
 	sbi_platform_early_exit(plat);
 
+	sbi_pmu_exit(scratch);
+
 	sbi_timer_exit(scratch);
 
 	sbi_ipi_exit(scratch);
lib/sbi/sbi_pmu.c new file mode 100644 index renamed from lib/sbi/sbi_pmu.c +0 -0

000000000000..ed519dfcc860

lib/sbi/sbi_pmu.c new file +58 -0
@@ -0,0 +1,600 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#include <sbi/riscv_asm.h>
+#include <sbi/sbi_bitops.h>
+#include <sbi/sbi_console.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/sbi_string.h>
+
+/** Information about hardware counters */ struct sbi_pmu_hw_event {
+	unsigned long counters;
+	unsigned long start_idx;
+	unsigned long end_idx;
+	/* Event selector value used only for raw events */
+	uint64_t select;
+};
+
+/** Representation of a firmware event */ struct sbi_pmu_fw_event {
+
+	/* Event associated with the particular counter */
+	unsigned long event_idx;
+
+	/* Current value of the counter */
+	unsigned long curr_count;
+
+	/* A flag indicating pmu event monitoring is started */
+	bool bStarted;
+};
+
+/* Information about PMU counters as per SBI specification */ union
+sbi_pmu_ctr_info {
+	unsigned long value;
+	struct {
+		unsigned long csr:12;
+		unsigned long width:6;
+#if __riscv_xlen == 32
+		unsigned long reserved:13;
+#else
+		unsigned long reserved:45;
+#endif
+		unsigned long type:1;
+	};
+};
+
+/* Mapping between event range and possible counters  */ static struct
+sbi_pmu_hw_event hw_event_map[SBI_PMU_HW_EVENT_MAX] = {0};
+
+/* counter to enabled event mapping */
+static uint32_t

active_events[SBI_HARTMASK_MAX_BITS][SBI_PMU_HW_CTR_MAX ++ SBI_PMU_FW_CTR_MAX];

lib/sbi/sbi_pmu.c new file +4 -0
+
+/* Contains all the information about firmwares events */ static struct
+sbi_pmu_fw_event
+fw_event_map[SBI_HARTMASK_MAX_BITS][SBI_PMU_FW_EVENT_MAX] =

{0};

lib/sbi/sbi_pmu.c new file +24 -0
+
+/* Maximum number of hardware events available */ static uint32_t
+num_hw_events;
+/* Maximum number of hardware counters available */ static uint32_t
+num_hw_ctrs;
+
+/* Maximum number of counters available */ static uint32_t total_ctrs;
+
+/* Helper macros to retrieve event idx and code type */ #define
+get_cidx_type(x) ((x & SBI_PMU_EVENT_IDX_TYPE_MASK) >> 16) #define
+get_cidx_code(x) (x & SBI_PMU_EVENT_IDX_CODE_MASK)
+
+/**
+ * Perform a sanity check on event & counter mappings with event range
+overlap check
+ * @param evtA Pointer to the existing hw event structure
+ * @param evtB Pointer to the new hw event structure
+ *
+ * Return FALSE if the range doesn't overlap, TRUE otherwise  */ static
+bool pmu_event_range_overlap(struct sbi_pmu_hw_event *evtA,
+				    struct sbi_pmu_hw_event *evtB)
+{
+	/* check if the range of events overlap with a previous entry */
+	if (((evtA->end_idx < evtB->start_idx) && (evtA->end_idx < evtB-
Quoted 1 line

end_idx)) ||

lib/sbi/sbi_pmu.c new file +1 -0
+	   ((evtA->start_idx > evtB->start_idx) && (evtA->start_idx > evtB-
Quoted 1 line

end_idx)))

lib/sbi/sbi_pmu.c new file +22 -0
+		return FALSE;
+	return TRUE;
+}
+
+static bool pmu_event_select_overlap(struct sbi_pmu_hw_event *evt,
+				     uint64_t select_val)
+{
+
+	if (evt->select == select_val)
+		return TRUE;
+
+	return FALSE;
+}
+
+static int pmu_ctr_validate(uint32_t cidx, uint32_t *event_idx_code) {
+	uint32_t event_idx_val;
+	uint32_t event_idx_type;
+	u32 hartid = current_hartid();
+
+	event_idx_val = active_events[hartid][cidx];
+
+	if (cidx >= total_ctrs || (event_idx_val ==

SBI_PMU_EVENT_IDX_INVALID))

lib/sbi/sbi_pmu.c new file +53 -0
+		return SBI_EINVAL;
+
+	event_idx_type = get_cidx_type(event_idx_val);
+	if (event_idx_type >= SBI_PMU_EVENT_TYPE_MAX)
+		return SBI_EINVAL;
+
+	*event_idx_code = get_cidx_code(event_idx_val);
+
+	return event_idx_type;
+}
+
+static int pmu_ctr_read_fw(uint32_t cidx, unsigned long *cval,
+			       uint32_t fw_evt_code)
+{
+	u32 hartid = current_hartid();
+	struct sbi_pmu_fw_event fevent;
+
+	fevent = fw_event_map[hartid][fw_evt_code];
+	*cval = fevent.curr_count;
+
+	return 0;
+}
+
+/* Add a hardware counter read for completeness for future purpose */
+static int pmu_ctr_read_hw(uint32_t cidx, uint64_t *cval) { #if
+__riscv_xlen == 32
+	uint32_t temp, temph = 0;
+
+	temp = csr_read_num(CSR_MCYCLE + cidx);
+	temph = csr_read_num(CSR_MCYCLEH + cidx);
+	*cval = ((uint64_t)temph << 32) | temp; #else
+	*cval = csr_read_num(CSR_MCYCLE + cidx); #endif
+
+	return 0;
+}
+
+int sbi_pmu_ctr_read(uint32_t cidx, unsigned long *cval) {
+	int event_idx_type;
+	uint32_t event_code;
+	uint64_t cval64;
+
+	event_idx_type = pmu_ctr_validate(cidx, &event_code);
+	if (event_idx_type < 0)
+		return SBI_EINVAL;
+	else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+		pmu_ctr_read_fw(cidx, cval, event_code);
+	else
+		pmu_ctr_read_hw(cidx, &cval64);
+
+	return 0;
+}
+
+static int pmu_add_hw_event_map(u32 eidx_start, u32 eidx_end, u32

cmap,

lib/sbi/sbi_pmu.c new file +5 -0
+				uint64_t select)
+{
+	int i = 0;
+	bool is_overlap;
+	struct sbi_pmu_hw_event *event =

&hw_event_map[num_hw_events];

lib/sbi/sbi_pmu.c new file +22 -0
+
+	/* The first two counters are reserved by priv spec */
+	if ((eidx_start == SBI_PMU_HW_CPU_CYCLES && cmap != 0x1) ||
+	    (eidx_start == SBI_PMU_HW_INSTRUCTIONS && cmap != 0x4) ||
+	    (eidx_start > SBI_PMU_HW_INSTRUCTIONS && cmap < 0x08))
+		return SBI_EDENIED;
+
+	if (num_hw_events >= SBI_PMU_HW_EVENT_MAX - 1) {
+		sbi_printf("Can not handle more than %d perf events\n",
+			    SBI_PMU_HW_EVENT_MAX);
+		return SBI_EFAIL;
+	}
+
+	event->start_idx = eidx_start;
+	event->end_idx = eidx_end;
+	event->counters = cmap;
+	event->select = select;
+
+	/* Sanity check */
+	for (i = 0; i < num_hw_events; i++) {
+		if (eidx_start == SBI_PMU_EVENT_RAW_IDX)
+		/* All raw events have same event idx. Just do sanity check on

select */

lib/sbi/sbi_pmu.c new file +1 -0
+			is_overlap =

pmu_event_select_overlap(&hw_event_map[i], select);

lib/sbi/sbi_pmu.c new file +2 -0
+		else
+			is_overlap =

pmu_event_range_overlap(&hw_event_map[i], event);

lib/sbi/sbi_pmu.c new file +10 -0
+		if (is_overlap)
+			return SBI_EINVALID_ADDR;
+	}
+	num_hw_events++;
+
+	return 0;
+}
+
+/**
+ * Logical counter ids are assigned to hardware counters are assigned

consecutively.
+ * E.g. counter0 must count MCYCLE where counter2 must count minstret.

lib/sbi/sbi_pmu.c new file +4 -0
+Similarly,
+ * counterX will mhpmcounterX.
+ */
+int sbi_pmu_add_hw_event_counter_map(u32 eidx_start, u32 eidx_end,

u32

lib/sbi/sbi_pmu.c new file +2 -0
+cmap) {
+	if ((eidx_start > eidx_end) || eidx_start ==

SBI_PMU_EVENT_RAW_IDX ||

lib/sbi/sbi_pmu.c new file +8 -0
+	     eidx_end == SBI_PMU_EVENT_RAW_IDX)
+		return SBI_EINVAL;
+
+	return pmu_add_hw_event_map(eidx_start, eidx_end, cmap, 0); }
+
+int sbi_pmu_add_raw_event_counter_map(uint64_t select, u32 cmap) {
+	return pmu_add_hw_event_map(SBI_PMU_EVENT_RAW_IDX,
+				    SBI_PMU_EVENT_RAW_IDX, cmap, select);

}

lib/sbi/sbi_pmu.c new file +63 -0
+
+static void pmu_ctr_write_hw(uint32_t cidx, uint64_t ival) { #if
+__riscv_xlen == 32
+	csr_write_num(CSR_MCYCLE + cidx, ival & 0xFFFF);
+	csr_write_num(CSR_MCYCLEH + cidx, ival >> BITS_PER_LONG); #else
+	csr_write_num(CSR_MCYCLE + cidx, ival); #endif }
+
+static int pmu_ctr_start_hw(uint32_t cidx, uint64_t ival, bool
+ival_update) {
+	unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+	unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+	if (cidx > num_hw_ctrs)
+		return SBI_EINVAL;
+
+	if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx, &mctr_inhbt))
+		return SBI_EALREADY_STARTED;
+
+	__set_bit(cidx, &mctr_en);
+	__clear_bit(cidx, &mctr_inhbt);
+
+	if (ival_update)
+		pmu_ctr_write_hw(cidx, ival);
+
+	csr_write(CSR_MCOUNTEREN, mctr_en);
+	csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+
+	return 0;
+}
+
+static int pmu_ctr_start_fw(uint32_t cidx, uint32_t fw_evt_code,
+			    uint64_t ival, bool ival_update) {
+	u32 hartid = current_hartid();
+	struct sbi_pmu_fw_event *fevent;
+
+	fevent = &fw_event_map[hartid][fw_evt_code];
+	if (ival_update)
+		fevent->curr_count = ival;
+	fevent->bStarted = TRUE;
+
+	return 0;
+}
+
+int sbi_pmu_ctr_start(unsigned long cbase, unsigned long cmask,
+		      unsigned long flags, uint64_t ival) {
+	int event_idx_type;
+	uint32_t event_code;
+	unsigned long ctr_mask = cmask << cbase;
+	int ret = SBI_EINVAL;
+	bool bUpdate = FALSE;
+
+	if (cbase >= total_ctrs)
+		return ret;
+
+	if (flags & SBI_PMU_START_FLAG_SET_INIT_VALUE)
+		bUpdate = TRUE;
+
+	for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+		event_idx_type = pmu_ctr_validate(cbase, &event_code);
+		if (event_idx_type < 0)
+			return SBI_EINVAL;
+		else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+			ret = pmu_ctr_start_fw(cbase, event_code, ival,

bUpdate);

lib/sbi/sbi_pmu.c new file +53 -0
+		else
+			ret = pmu_ctr_start_hw(cbase, ival, bUpdate);
+	}
+
+	return ret;
+}
+
+static int pmu_ctr_stop_hw(uint32_t cidx) {
+	unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+	unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+
+	if (__test_bit(cidx, &mctr_en) && !__test_bit(cidx, &mctr_inhbt)) {
+		__set_bit(cidx, &mctr_inhbt);
+		__clear_bit(cidx, &mctr_en);
+		csr_write(CSR_MCOUNTEREN, mctr_en);
+		csr_write(CSR_MCOUNTINHIBIT, mctr_inhbt);
+		return 0;
+	} else
+		return SBI_EALREADY_STOPPED;
+}
+
+static int pmu_ctr_stop_fw(uint32_t cidx, uint32_t fw_evt_code) {
+	u32 hartid = current_hartid();
+
+	fw_event_map[hartid][fw_evt_code].bStarted = FALSE;
+
+	return 0;
+}
+
+int sbi_pmu_ctr_stop(unsigned long cbase, unsigned long cmask,
+		     unsigned long flag)
+{
+	u32 hartid = current_hartid();
+	int ret = SBI_EINVAL;
+	int event_idx_type;
+	uint32_t event_code;
+	unsigned long ctr_mask = cmask << cbase;
+
+	if (cbase >= total_ctrs)
+		return SBI_EINVAL;
+
+	for_each_set_bit_from(cbase, &ctr_mask, total_ctrs) {
+		event_idx_type = pmu_ctr_validate(cbase, &event_code);
+		if (event_idx_type < 0)
+			return SBI_EINVAL;
+
+		else if (event_idx_type == SBI_PMU_EVENT_TYPE_FW)
+			ret = pmu_ctr_stop_fw(cbase, event_code);
+		else
+			ret = pmu_ctr_stop_hw(cbase);
+
+		if (!ret && (flag & SBI_PMU_STOP_FLAG_RESET))
+			active_events[hartid][cbase] =

SBI_PMU_EVENT_IDX_INVALID;

lib/sbi/sbi_pmu.c new file +6 -0
+	}
+
+	return ret;
+}
+
+static int pmu_update_hw_mhpmevent(struct sbi_pmu_hw_event

*hw_evt, int ctr_idx,

lib/sbi/sbi_pmu.c new file +7 -0
+				    unsigned long eindex, uint64_t data) {
+	struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+	const struct sbi_platform *plat = sbi_platform_ptr(scratch);
+	uint64_t mhpmevent_val;
+
+	/* Get the final mhpmevent value to be written from platform */
+	mhpmevent_val = sbi_platform_pmu_xlate_to_mhpmevent(plat,

eindex,

lib/sbi/sbi_pmu.c new file +3 -0
+data);
+
+	if (!mhpmevent_val || ctr_idx < 3 || ctr_idx >=

SBI_PMU_HW_CTR_MAX)

lib/sbi/sbi_pmu.c new file +3 -0
+		return SBI_EFAIL;
+
+	/* TODO: The upper 8 bits of mhpmevent is reserved by sscofpmf

extension.

lib/sbi/sbi_pmu.c new file +24 -0
+	 * Update those bits based on the flags received from supervisor.
+	 * The OVF bit also should be cleared here in case it was not cleared
+	 * during event stop.
+	 */
+	csr_write_num(CSR_MCOUNTINHIBIT + ctr_idx, mhpmevent_val);
+
+	return 0;
+}
+
+static int pmu_ctr_find_hw(unsigned long cbase, unsigned long cmask,
+			   unsigned long event_idx, uint64_t data) {
+	unsigned long ctr_mask;
+	int i, ret = 0, ctr_idx = SBI_ENOTSUPP;
+	struct sbi_pmu_hw_event *temp;
+	unsigned long mctr_en = csr_read(CSR_MCOUNTEREN);
+	unsigned long mctr_inhbt = csr_read(CSR_MCOUNTINHIBIT);
+	int evt_idx_code = get_cidx_code(event_idx);
+
+	if (cbase > num_hw_ctrs)
+		return SBI_EINVAL;
+
+	for (i = 0; i < num_hw_events; i++) {
+		temp = &hw_event_map[i];
+		if ((temp->start_idx > event_idx && event_idx < temp-
Quoted 1 line

end_idx) ||

lib/sbi/sbi_pmu.c new file +1 -0
+		    (temp->start_idx < event_idx && event_idx > temp-
Quoted 1 line

end_idx))

lib/sbi/sbi_pmu.c new file +4 -0
+			continue;
+
+		/* For raw events, event data is used as the select value */
+		if ((event_idx == SBI_PMU_EVENT_RAW_IDX) && temp-
Quoted 1 line

select != data)

lib/sbi/sbi_pmu.c new file +4 -0
+			continue;
+
+		ctr_mask = temp->counters & (cmask << cbase);
+		for_each_set_bit_from(cbase, &ctr_mask,

SBI_PMU_HW_CTR_MAX) {

lib/sbi/sbi_pmu.c new file +15 -0
+			if (!__test_bit(cbase, &mctr_en) &&
+			    __test_bit(cbase, &mctr_inhbt)) {
+				ctr_idx = cbase;
+				break;
+			}
+		}
+	}
+
+	if (ctr_idx == SBI_ENOTSUPP)
+		return SBI_EFAIL;
+
+	/* No need to update the  event selectors for fixed events */
+	if (evt_idx_code != SBI_PMU_HW_CPU_CYCLES &&
+	    evt_idx_code != SBI_PMU_HW_INSTRUCTIONS)
+		ret = pmu_update_hw_mhpmevent(temp, ctr_idx, event_idx,

data);

lib/sbi/sbi_pmu.c new file +26 -0
+
+	if (!ret)
+		ret = ctr_idx;
+
+	return ret;
+}
+
+
+/**
+ * Any firmware counter can map to any firmware event.
+ * Thus, select the first available fw counter after sanity
+ * check.
+ */
+static int pmu_ctr_find_fw(unsigned long cbase, unsigned long cmask,
+u32 hartid) {
+	int i = 0;
+	int fw_base;
+	unsigned long ctr_mask = cmask << cbase;
+
+	if (cbase <= num_hw_ctrs)
+		fw_base = num_hw_ctrs + 1;
+	else
+		fw_base = cbase;
+
+	for (i = fw_base; i < total_ctrs; i++)
+		if ((active_events[hartid][i] == SBI_PMU_EVENT_IDX_INVALID)

&&

lib/sbi/sbi_pmu.c new file +7 -0
+		    ((1UL << i) & ctr_mask))
+			return i;
+
+	return SBI_ENOTSUPP;
+}
+
+int sbi_pmu_ctr_cfg_match(unsigned long cidx_base, unsigned long

cidx_mask,

lib/sbi/sbi_pmu.c new file +17 -0
+			  unsigned long flags, unsigned long event_idx,
+			  uint64_t event_data)
+{
+	int ctr_idx = SBI_ENOTSUPP;
+	u32 hartid = current_hartid();
+	int event_type = get_cidx_type(event_idx);
+	struct sbi_pmu_fw_event *fevent;
+	uint32_t fw_evt_code;
+	unsigned long tmp = cidx_mask << cidx_base;
+
+	/* Do a basic sanity check of counter base & mask */
+	if (cidx_base >= total_ctrs || __fls(tmp) >= total_ctrs ||
+	    event_type >= SBI_PMU_EVENT_TYPE_MAX)
+		return SBI_EINVAL;
+
+	if (flags & SBI_PMU_CFG_FLAG_SKIP_MATCH) {
+		/* The caller wants to skip the match because it already

knows the

lib/sbi/sbi_pmu.c new file +4 -0
+		 * counter idx for the given event. Verify that the counter idx
+		 * is still valid.
+		 */
+		if (active_events[hartid][cidx_base] ==

SBI_PMU_EVENT_IDX_INVALID)

lib/sbi/sbi_pmu.c new file +7 -0
+			return SBI_EINVAL;
+		ctr_idx = cidx_base;
+		goto skip_match;
+	}
+
+	if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+		/* Any firmware counter can be used track any firmware

event */

lib/sbi/sbi_pmu.c new file +3 -0
+		ctr_idx = pmu_ctr_find_fw(cidx_base, cidx_mask, hartid);
+	} else {
+		ctr_idx = pmu_ctr_find_hw(cidx_base, cidx_mask, event_idx,

event_data);

lib/sbi/sbi_pmu.c new file +34 -0
+	}
+
+	if (ctr_idx < 0)
+		return SBI_ENOTSUPP;
+
+	active_events[hartid][ctr_idx] = event_idx;
+skip_match:
+	if (event_type == SBI_PMU_EVENT_TYPE_HW) {
+		if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+			pmu_ctr_write_hw(ctr_idx, 0);
+		if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+			pmu_ctr_start_hw(ctr_idx, 0, false);
+	} else if (event_type == SBI_PMU_EVENT_TYPE_FW) {
+		fw_evt_code = get_cidx_code(event_idx);
+		fevent = &fw_event_map[hartid][fw_evt_code];
+		if (flags & SBI_PMU_CFG_FLAG_CLEAR_VALUE)
+			fevent->curr_count = 0;
+		if (flags & SBI_PMU_CFG_FLAG_AUTO_START)
+			fevent->bStarted = TRUE;
+	}
+
+	return ctr_idx;
+}
+
+inline int sbi_pmu_ctr_incr_fw(enum sbi_pmu_fw_event_code_id fw_id) {
+	u32 hartid = current_hartid();
+	struct sbi_pmu_fw_event *fevent;
+
+	if (unlikely(fw_id >= SBI_PMU_FW_MAX))
+		return SBI_EINVAL;
+
+	fevent = &fw_event_map[hartid][fw_id];
+
+	/* PMU counters will be only enabled during performance debugging

*/

lib/sbi/sbi_pmu.c new file +19 -0
+	if (unlikely(fevent->bStarted))
+		fevent->curr_count++;
+
+	return 0;
+}
+
+unsigned long sbi_pmu_num_ctr(void)
+{
+	return (num_hw_ctrs + SBI_PMU_FW_CTR_MAX); }
+
+int sbi_pmu_ctr_get_info(uint32_t cidx, unsigned long *ctr_info) {
+	union sbi_pmu_ctr_info cinfo = {0};
+	struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
+
+	/* Sanity check. Counter1 is not mapped at all */
+	if (cidx >= total_ctrs || cidx == 1)
+		return SBI_EINVAL;
+
+	/* We have 31 HW counters with 31 being the last

index(MHPMCOUNTER31) */

lib/sbi/sbi_pmu.c new file +58 -1
+	if (cidx <= num_hw_ctrs) {
+		cinfo.type = SBI_PMU_CTR_TYPE_HW;
+		cinfo.csr = CSR_CYCLE + cidx;
+		/* mcycle & minstret are always 64 bit */
+		if (cidx == 0 || cidx == 2)
+			cinfo.width = 63;
+		else
+			cinfo.width = sbi_hart_mhpm_bits(scratch);
+	} else {
+		/* it's a firmware counter */
+		cinfo.type = SBI_PMU_CTR_TYPE_FW;
+		/* Firmware counters are XLEN bits wide */
+		cinfo.width = BITS_PER_LONG - 1;
+	}
+
+	*ctr_info = cinfo.value;
+
+	return 0;
+}
+
+static void pmu_reset_event_map(u32 hartid) {
+	int j;
+
+	/* Initialize the counter to event mapping table */
+	for (j = 0; j < total_ctrs; j++)
+		active_events[hartid][j] = SBI_PMU_EVENT_IDX_INVALID;
+	for (j = 0; j < SBI_PMU_FW_CTR_MAX; j++)
+		sbi_memset(&fw_event_map[hartid][j], 0,
+			   sizeof(struct sbi_pmu_fw_event)); }
+
+void sbi_pmu_exit(struct sbi_scratch *scratch) {
+	u32 hartid = current_hartid();
+
+	csr_write(CSR_MCOUNTINHIBIT, -1);
+	csr_write(CSR_MCOUNTEREN, 2);
+	pmu_reset_event_map(hartid);
+}
+
+int sbi_pmu_init(struct sbi_scratch *scratch, bool cold_boot) {
+	const struct sbi_platform *plat;
+
+	if (!sbi_hart_has_feature(scratch, SBI_HART_HAS_MCOUNTINHIBIT))
+		return SBI_ENOTSUPP;
+
+	if (cold_boot) {
+		plat = sbi_platform_ptr(scratch);
+		/* Initialize hw pmu events */
+		sbi_platform_pmu_init(plat);
+
+		/* mcycle & minstret is available always */
+		num_hw_ctrs = sbi_hart_mhpm_count(scratch) + 2;
+		total_ctrs = num_hw_ctrs + SBI_PMU_FW_CTR_MAX;
+	}
+
+	pmu_reset_event_map(current_hartid());
+
+	return 0;
+}
--
Quoted 1 line

2.25.1

I don't have much comments for now.

Regards,
Anup

#37 lore raw

PATCH v2 11/15 utils: fdt: Add fdt helper functions to parse PMU DT nodes

In reply to Atish Patra

The PMU DT node bindings are defined in docs/pmu_support.md Add few fdt helper functions to parse the DT node and update the event-counter mapping tables.

---
 include/sbi_utils/fdt/fdt_pmu.h |  46 +++++++++++++
 lib/utils/fdt/fdt_fixup.c       |   2 +
 lib/utils/fdt/fdt_pmu.c         | 111 ++++++++++++++++++++++++++++++++
 lib/utils/fdt/objects.mk        |   1 +
 4 files changed, 160 insertions(+)
 create mode 100644 include/sbi_utils/fdt/fdt_pmu.h
 create mode 100644 lib/utils/fdt/fdt_pmu.c
include/sbi_utils/fdt/fdt_pmu.h new file +46 -0
new file mode 100644
index 000000000000..2fa01edc0743
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * fdt_pmu.c - Flat Device Tree PMU helper routines
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#ifndef __FDT_PMU_H__
+#define __FDT_PMU_H__
+
+#include <sbi/sbi_types.h>
+
+/**
+ * Fix up the PMU node in the device tree
+ *
+ * This routine:
+ * 1. Disables opensbi specific properties from the DT
+ *
+ * It is recommended that platform support call this function in
+ * their final_init() platform operation.
+ *
+ * @param fdt device tree blob
+ */
+void fdt_pmu_fixup(void *fdt);
+
+/**
+ * Setup PMU data from device tree
+ *
+ * @param fdt device tree blob
+ *
+ * @return 0 on success and negative error code on failure
+ */
+int fdt_pmu_setup(void *fdt);
+
+/**
+ * Get the mhpmevent select value read from DT for a given event
+ * @param event_idx Event ID of the given event
+ *
+ * @return The select value read from DT or 0 if given index was not found
+ */
+uint64_t fdt_pmu_get_select_value(uint32_t event_idx);
+
+#endif
lib/utils/fdt/fdt_fixup.c +2 -0
index 14655000b815..ac01ba3dfac1 100644
@@ -15,6 +15,7 @@
 #include <sbi/sbi_scratch.h>
 #include <sbi/sbi_string.h>
 #include <sbi_utils/fdt/fdt_fixup.h>
+#include <sbi_utils/fdt/fdt_pmu.h>
 #include <sbi_utils/fdt/fdt_helper.h>
 
 void fdt_cpu_fixup(void *fdt)
@@ -263,6 +264,7 @@ void fdt_fixups(void *fdt)
 	fdt_plic_fixup(fdt);
 
 	fdt_reserved_memory_fixup(fdt);
+	fdt_pmu_fixup(fdt);
 }
 
 
lib/utils/fdt/fdt_pmu.c new file +111 -0

111 lines not on this page · raw message

lib/utils/fdt/objects.mk +1 -0
index d9f1eae19292..03800f96d74d 100644
@@ -5,5 +5,6 @@
 #
 
 libsbiutils-objs-y += fdt/fdt_domain.o
+libsbiutils-objs-y += fdt/fdt_pmu.o
 libsbiutils-objs-y += fdt/fdt_helper.o
 libsbiutils-objs-y += fdt/fdt_fixup.o
Signature · 1 line
2.25.1
#38 lore raw

PATCH v2 12/15 lib: sbi: Implement SBI PMU extension

In reply to Atish Patra

RISC-V SBI specfication 0.3 defines a PMU extension that allows supervisor mode to start/stop/configure pmu related events. This patch implements all of the functionality defined in the specification.

---
 include/sbi/sbi_ecall.h |  1 +
 lib/sbi/objects.mk      |  1 +
 lib/sbi/sbi_ecall.c     |  9 +++++
 lib/sbi/sbi_ecall_pmu.c | 78 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 89 insertions(+)
 create mode 100644 lib/sbi/sbi_ecall_pmu.c
include/sbi/sbi_ecall.h +1 -0
index 63ef866ba2d4..9500d0430429 100644
@@ -39,6 +39,7 @@ extern struct sbi_ecall_extension ecall_ipi;
 extern struct sbi_ecall_extension ecall_vendor;
 extern struct sbi_ecall_extension ecall_hsm;
 extern struct sbi_ecall_extension ecall_srst;
+extern struct sbi_ecall_extension ecall_pmu;
 
 u16 sbi_ecall_version_major(void);
 
lib/sbi/objects.mk +1 -0
index d9068b707854..7096f245ae0c 100644
@@ -20,6 +20,7 @@ libsbi-objs-y += sbi_ecall.o
 libsbi-objs-y += sbi_ecall_base.o
 libsbi-objs-y += sbi_ecall_hsm.o
 libsbi-objs-y += sbi_ecall_legacy.o
+libsbi-objs-y += sbi_ecall_pmu.o
 libsbi-objs-y += sbi_ecall_replace.o
 libsbi-objs-y += sbi_ecall_vendor.o
 libsbi-objs-y += sbi_emulate_csr.o
lib/sbi/sbi_ecall.c +9 -0
index e92a53930460..a87bb7ad1c8d 100644
@@ -11,6 +11,8 @@
 #include <sbi/sbi_ecall.h>
 #include <sbi/sbi_ecall_interface.h>
 #include <sbi/sbi_error.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_scratch.h>
 #include <sbi/sbi_trap.h>
 
 u16 sbi_ecall_version_major(void)
@@ -144,6 +146,7 @@ int sbi_ecall_handler(struct sbi_trap_regs *regs)
 int sbi_ecall_init(void)
 {
 	int ret;
+	struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
 
 	/* The order of below registrations is performance optimized */
 	ret = sbi_ecall_register_extension(&ecall_time);
@@ -164,6 +167,12 @@ int sbi_ecall_init(void)
 	ret = sbi_ecall_register_extension(&ecall_srst);
 	if (ret)
 		return ret;
+	/* SBI PMU extension is useless without mcount inhibit features */
+	if (sbi_hart_has_feature(scratch, SBI_HART_HAS_MCOUNTINHIBIT)) {
+		ret = sbi_ecall_register_extension(&ecall_pmu);
+		if (ret)
+			return ret;
+	}
 	ret = sbi_ecall_register_extension(&ecall_legacy);
 	if (ret)
 		return ret;
lib/sbi/sbi_ecall_pmu.c new file +78 -0

78 lines not on this page · raw message

Signature · 1 line
2.25.1
#39 lore raw

PATCH v2 12/15 lib: sbi: Implement SBI PMU extension

Quoted 66 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 12/15] lib: sbi: Implement SBI PMU extension

RISC-V SBI specfication 0.3 defines a PMU extension that allows supervisor mode to start/stop/configure pmu related events. This patch implements all of the functionality defined in the specification.

---
 include/sbi/sbi_ecall.h |  1 +
 lib/sbi/objects.mk      |  1 +
 lib/sbi/sbi_ecall.c     |  9 +++++
 lib/sbi/sbi_ecall_pmu.c | 78
+++++++++++++++++++++++++++++++++++++++++
 4 files changed, 89 insertions(+)
 create mode 100644 lib/sbi/sbi_ecall_pmu.c
include/sbi/sbi_ecall.h index renamed from include/sbi/sbi_ecall.h +0 -0

63ef866ba2d4..9500d0430429 100644

include/sbi/sbi_ecall.h +0 -0
@@ -39,6 +39,7 @@ extern struct sbi_ecall_extension ecall_ipi;  extern struct

sbi_ecall_extension ecall_vendor; extern struct sbi_ecall_extension ecall_hsm; extern struct sbi_ecall_extension ecall_srst;

include/sbi/sbi_ecall.h +1 -0
+extern struct sbi_ecall_extension ecall_pmu;
 
 u16 sbi_ecall_version_major(void);
lib/sbi/objects.mk index renamed from lib/sbi/objects.mk +0 -0

d9068b707854..7096f245ae0c 100644

lib/sbi/objects.mk +0 -0
@@ -20,6 +20,7 @@ libsbi-objs-y += sbi_ecall.o  libsbi-objs-y +=

sbi_ecall_base.o libsbi-objs-y += sbi_ecall_hsm.o libsbi-objs-y += sbi_ecall_legacy.o

lib/sbi/objects.mk +1 -0
+libsbi-objs-y += sbi_ecall_pmu.o
 libsbi-objs-y += sbi_ecall_replace.o
 libsbi-objs-y += sbi_ecall_vendor.o
 libsbi-objs-y += sbi_emulate_csr.o
lib/sbi/sbi_ecall.c index renamed from lib/sbi/sbi_ecall.c +0 -0

e92a53930460..a87bb7ad1c8d 100644

lib/sbi/sbi_ecall.c +3 -0
@@ -11,6 +11,8 @@
 #include <sbi/sbi_ecall.h>
 #include <sbi/sbi_ecall_interface.h>
 #include <sbi/sbi_error.h>
+#include <sbi/sbi_hart.h>
+#include <sbi/sbi_scratch.h>
 #include <sbi/sbi_trap.h>
 
 u16 sbi_ecall_version_major(void)
@@ -144,6 +146,7 @@ int sbi_ecall_handler(struct sbi_trap_regs *regs)  int
 sbi_ecall_init(void)  {
 	int ret;
+	struct sbi_scratch *scratch = sbi_scratch_thishart_ptr();
 
 	/* The order of below registrations is performance optimized */
 	ret = sbi_ecall_register_extension(&ecall_time);

lib/sbi/sbi_ecall.c int sbi_ecall_init(void) · line 175

Quoted 9 lines
lib/sbi/sbi_ecall.c +6 -0
@@ -164,6 +167,12 @@ int sbi_ecall_init(void)
 	ret = sbi_ecall_register_extension(&ecall_srst);
 	if (ret)
 		return ret;
+	/* SBI PMU extension is useless without mcount inhibit features */
+	if (sbi_hart_has_feature(scratch, SBI_HART_HAS_MCOUNTINHIBIT)) {
+		ret = sbi_ecall_register_extension(&ecall_pmu);
+		if (ret)
+			return ret;
+	}

Instead of this, I would suggest to implement probe() callback of extension just like SBI SRST extension.

Don't worry about SBI extension look-up performance for now, we will optimize this separately in sbi_ecall.c

Regards,
Anup

Quoted 86 lines
lib/sbi/sbi_ecall.c +0 -0
 	ret = sbi_ecall_register_extension(&ecall_legacy);
 	if (ret)
 		return ret;
lib/sbi/sbi_ecall_pmu.c new file mode renamed from lib/sbi/sbi_ecall_pmu.c +0 -0

100644 index 000000000000..938bf31b907e

lib/sbi/sbi_ecall_pmu.c new file +76 -1
@@ -0,0 +1,78 @@
+/*
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2021 Western Digital Corporation or its affiliates.
+ *
+ * Authors:
+ *   Atish Patra <[email protected]>
+ */
+
+#include <sbi/sbi_ecall.h>
+#include <sbi/sbi_ecall_interface.h>
+#include <sbi/sbi_error.h>
+#include <sbi/sbi_trap.h>
+#include <sbi/sbi_version.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_scratch.h>
+#include <sbi/riscv_asm.h>
+
+static int sbi_ecall_pmu_handler(unsigned long extid, unsigned long funcid,
+				 const struct sbi_trap_regs *regs,
+				 unsigned long *out_val,
+				 struct sbi_trap_info *out_trap)
+{
+	int ret = 0;
+	uint64_t temp;
+
+	switch (funcid) {
+	case SBI_EXT_PMU_NUM_COUNTERS:
+		ret = sbi_pmu_num_ctr();
+		if (ret >= 0) {
+			*out_val = ret;
+			ret = 0;
+		}
+		break;
+	case SBI_EXT_PMU_COUNTER_GET_INFO:
+		ret = sbi_pmu_ctr_get_info(regs->a0, out_val);
+		break;
+	case SBI_EXT_PMU_COUNTER_CFG_MATCH:
+#if __riscv_xlen == 32
+		temp = ((uint64_t)regs->a5 << 32) | regs->a4; #else
+		temp = regs->a4;
+#endif
+		ret = sbi_pmu_ctr_cfg_match(regs->a0, regs->a1, regs->a2,
+					    regs->a3, temp);
+		if (ret >= 0) {
+			*out_val = ret;
+			ret = 0;
+		}
+
+		break;
+	case SBI_EXT_PMU_COUNTER_FW_READ:
+		ret = sbi_pmu_ctr_read(regs->a0, out_val);
+		break;
+	case SBI_EXT_PMU_COUNTER_START:
+
+#if __riscv_xlen == 32
+		temp = ((uint64_t)regs->a4 << 32) | regs->a3; #else
+		temp = regs->a3;
+#endif
+		ret = sbi_pmu_ctr_start(regs->a0, regs->a1, regs->a2, temp);
+		break;
+	case SBI_EXT_PMU_COUNTER_STOP:
+		ret = sbi_pmu_ctr_stop(regs->a0, regs->a1, regs->a2);
+		break;
+	default:
+		ret = SBI_ENOTSUPP;
+	};
+
+	return ret;
+}
+
+struct sbi_ecall_extension ecall_pmu = {
+	.extid_start = SBI_EXT_PMU,
+	.extid_end = SBI_EXT_PMU,
+	.handle = sbi_ecall_pmu_handler,
+};
--

2.25.1

#40 lore raw

PATCH v2 13/15 lib: sbi: Implement firmware counters

In reply to Atish Patra

RISC-V SBI v0.3 specification defines a set of firmware events that can provide additional information about the current firmware context. All of the firmware event monitoring are enabled now. The firmware events must be defined as raw perf event with MSB set as specified in the specification.

---
 lib/sbi/sbi_ecall_replace.c   |  1 +
 lib/sbi/sbi_illegal_insn.c    |  2 ++
 lib/sbi/sbi_ipi.c             |  6 ++++++
 lib/sbi/sbi_misaligned_ldst.c |  5 +++++
 lib/sbi/sbi_timer.c           |  2 ++
 lib/sbi/sbi_tlb.c             | 38 +++++++++++++++++++++++++++++++++++
 lib/sbi/sbi_trap.c            |  5 +++++
 7 files changed, 59 insertions(+)
lib/sbi/sbi_ecall_replace.c +1 -0
index a7935d97300d..fb1235d66fa9 100644
@@ -14,6 +14,7 @@
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_hart.h>
 #include <sbi/sbi_ipi.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_system.h>
 #include <sbi/sbi_timer.h>
 #include <sbi/sbi_tlb.h>
lib/sbi/sbi_illegal_insn.c +2 -0
index 9af3d24d797e..bfe7d6195898 100644
@@ -13,6 +13,7 @@
 #include <sbi/sbi_emulate_csr.h>
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_illegal_insn.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_trap.h>
 #include <sbi/sbi_unpriv.h>
 
@@ -129,6 +130,7 @@ int sbi_illegal_insn_handler(ulong insn, struct sbi_trap_regs *regs)
 	 * instruction trap.
 	 */
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_ILLEGAL_INSN);
 	if (unlikely((insn & 3) != 3)) {
 		insn = sbi_get_insn(regs->mepc, &uptrap);
 		if (uptrap.cause) {
lib/sbi/sbi_ipi.c +6 -0
index bfaf4e9766e1..563db2cf9e55 100644
@@ -19,6 +19,9 @@
 #include <sbi/sbi_init.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_string.h>
+#include <sbi/sbi_tlb.h>
 
 struct sbi_ipi_data {
 	unsigned long ipi_type;
@@ -64,6 +67,8 @@ static int sbi_ipi_send(struct sbi_scratch *scratch, u32 remote_hartid,
 	if (ipi_dev && ipi_dev->ipi_send)
 		ipi_dev->ipi_send(remote_hartid);
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_IPI_SENT);
+
 	if (ipi_ops->sync)
 		ipi_ops->sync(scratch);
 
@@ -183,6 +188,7 @@ void sbi_ipi_process(void)
 			sbi_scratch_offset_ptr(scratch, ipi_data_off);
 	u32 hartid = current_hartid();
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_IPI_RECVD);
 	if (ipi_dev && ipi_dev->ipi_clear)
 		ipi_dev->ipi_clear(hartid);
 
lib/sbi/sbi_misaligned_ldst.c +5 -0
index 5057cb5ecd58..c879ce72f61a 100644
@@ -12,6 +12,7 @@
 #include <sbi/riscv_fp.h>
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_misaligned_ldst.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_trap.h>
 #include <sbi/sbi_unpriv.h>
 
@@ -29,6 +30,8 @@ int sbi_misaligned_load_handler(ulong addr, ulong tval2, ulong tinst,
 	struct sbi_trap_info uptrap;
 	int i, fp = 0, shift = 0, len = 0;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_MISALIGNED_LOAD);
+
 	if (tinst & 0x1) {
 		/*
 		 * Bit[0] == 1 implies trapped instruction value is
@@ -149,6 +152,8 @@ int sbi_misaligned_store_handler(ulong addr, ulong tval2, ulong tinst,
 	struct sbi_trap_info uptrap;
 	int i, len = 0;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_MISALIGNED_STORE);
+
 	if (tinst & 0x1) {
 		/*
 		 * Bit[0] == 1 implies trapped instruction value is
lib/sbi/sbi_timer.c +2 -0
index 63e8ea98eadc..c7f1c80b8939 100644
@@ -12,6 +12,7 @@
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_hart.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_scratch.h>
 #include <sbi/sbi_timer.h>
 
@@ -88,6 +89,7 @@ void sbi_timer_set_delta_upper(ulong delta_upper)
 
 void sbi_timer_event_start(u64 next_event)
 {
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SET_TIMER);
 	if (timer_dev && timer_dev->timer_event_start)
 		timer_dev->timer_event_start(next_event);
 	csr_clear(CSR_MIP, MIP_STIP);
lib/sbi/sbi_tlb.c +38 -0
index 73f59e8681e2..6e9e4f0b1916 100644
@@ -21,6 +21,7 @@
 #include <sbi/sbi_string.h>
 #include <sbi/sbi_console.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 
 static unsigned long tlb_sync_off;
 static unsigned long tlb_fifo_off;
@@ -39,6 +40,8 @@ void sbi_tlb_local_hfence_vvma(struct sbi_tlb_info *tinfo)
 	unsigned long vmid  = tinfo->vmid;
 	unsigned long i, hgatp;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_RCVD);
+
 	hgatp = csr_swap(CSR_HGATP,
 			 (vmid << HGATP_VMID_SHIFT) & HGATP_VMID_MASK);
 
@@ -61,6 +64,8 @@ void sbi_tlb_local_hfence_gvma(struct sbi_tlb_info *tinfo)
 	unsigned long size  = tinfo->size;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_RCVD);
+
 	if ((start == 0 && size == 0) || (size == SBI_TLB_FLUSH_ALL)) {
 		__sbi_hfence_gvma_all();
 		return;
@@ -77,6 +82,8 @@ void sbi_tlb_local_sfence_vma(struct sbi_tlb_info *tinfo)
 	unsigned long size  = tinfo->size;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_RCVD);
+
 	if ((start == 0 && size == 0) || (size == SBI_TLB_FLUSH_ALL)) {
 		sbi_tlb_flush_all();
 		return;
@@ -98,6 +105,8 @@ void sbi_tlb_local_hfence_vvma_asid(struct sbi_tlb_info *tinfo)
 	unsigned long vmid  = tinfo->vmid;
 	unsigned long i, hgatp;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD);
+
 	hgatp = csr_swap(CSR_HGATP,
 			 (vmid << HGATP_VMID_SHIFT) & HGATP_VMID_MASK);
 
@@ -126,6 +135,8 @@ void sbi_tlb_local_hfence_gvma_vmid(struct sbi_tlb_info *tinfo)
 	unsigned long vmid  = tinfo->vmid;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD);
+
 	if (start == 0 && size == 0) {
 		__sbi_hfence_gvma_all();
 		return;
@@ -148,6 +159,8 @@ void sbi_tlb_local_sfence_vma_asid(struct sbi_tlb_info *tinfo)
 	unsigned long asid  = tinfo->asid;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_ASID_RCVD);
+
 	if (start == 0 && size == 0) {
 		sbi_tlb_flush_all();
 		return;
@@ -172,9 +185,32 @@ void sbi_tlb_local_sfence_vma_asid(struct sbi_tlb_info *tinfo)
 
 void sbi_tlb_local_fence_i(struct sbi_tlb_info *tinfo)
 {
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_FENCE_I_RECVD);
+
 	__asm__ __volatile("fence.i");
 }
 
+static void tlb_pmu_incr_fw_ctr(struct sbi_tlb_info *data)
+{
+	if (unlikely(!data))
+		return;
+
+	if (data->local_fn == sbi_tlb_local_fence_i)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_FENCE_I_SENT);
+	else if (data->local_fn == sbi_tlb_local_sfence_vma)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_SENT);
+	else if (data->local_fn == sbi_tlb_local_sfence_vma_asid)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_ASID_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_gvma)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_gvma_vmid)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_VMID_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_vvma)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_vvma_asid)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_ASID_SENT);
+}
+
 static void sbi_tlb_entry_process(struct sbi_tlb_info *tinfo)
 {
 	u32 rhartid;
@@ -368,6 +404,8 @@ int sbi_tlb_request(ulong hmask, ulong hbase, struct sbi_tlb_info *tinfo)
 	if (!tinfo->local_fn)
 		return SBI_EINVAL;
 
+	tlb_pmu_incr_fw_ctr(tinfo);
+
 	return sbi_ipi_send_many(hmask, hbase, tlb_event, tinfo);
 }
 
lib/sbi/sbi_trap.c +5 -0
index 1ba649074b75..dda68d4375af 100644
@@ -16,6 +16,7 @@
 #include <sbi/sbi_illegal_insn.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_misaligned_ldst.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_scratch.h>
 #include <sbi/sbi_timer.h>
 #include <sbi/sbi_trap.h>
@@ -257,6 +258,10 @@ struct sbi_trap_regs *sbi_trap_handler(struct sbi_trap_regs *regs)
 		rc  = sbi_ecall_handler(regs);
 		msg = "ecall handler failed";
 		break;
+	case CAUSE_LOAD_ACCESS:
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_ACCESS_LOAD);
+	case CAUSE_STORE_ACCESS:
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_ACCESS_STORE);
 	default:
 		/* If the trap came from S or U mode, redirect it there */
 		trap.epc = regs->mepc;
Signature · 1 line
2.25.1
#41 lore raw

PATCH v2 13/15 lib: sbi: Implement firmware counters

Quoted 30 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 13/15] lib: sbi: Implement firmware counters

RISC-V SBI v0.3 specification defines a set of firmware events that can provide additional information about the current firmware context. All of the firmware event monitoring are enabled now. The firmware events must be defined as raw perf event with MSB set as specified in the specification.

---
 lib/sbi/sbi_ecall_replace.c   |  1 +
 lib/sbi/sbi_illegal_insn.c    |  2 ++
 lib/sbi/sbi_ipi.c             |  6 ++++++
 lib/sbi/sbi_misaligned_ldst.c |  5 +++++
 lib/sbi/sbi_timer.c           |  2 ++
 lib/sbi/sbi_tlb.c             | 38 +++++++++++++++++++++++++++++++++++
 lib/sbi/sbi_trap.c            |  5 +++++
 7 files changed, 59 insertions(+)
lib/sbi/sbi_ecall_replace.c index renamed from lib/sbi/sbi_ecall_replace.c +0 -0

a7935d97300d..fb1235d66fa9 100644

lib/sbi/sbi_ecall_replace.c line 20

Quoted 7 lines
lib/sbi/sbi_ecall_replace.c +1 -0
@@ -14,6 +14,7 @@
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_hart.h>
 #include <sbi/sbi_ipi.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_system.h>
 #include <sbi/sbi_timer.h>
 #include <sbi/sbi_tlb.h>

Drop this change in lib/sbi/sbi_ecall_replace.c

Quoted 234 lines
lib/sbi/sbi_illegal_insn.c index renamed from lib/sbi/sbi_illegal_insn.c +0 -0

9af3d24d797e..bfe7d6195898 100644

lib/sbi/sbi_illegal_insn.c +2 -0
@@ -13,6 +13,7 @@
 #include <sbi/sbi_emulate_csr.h>
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_illegal_insn.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_trap.h>
 #include <sbi/sbi_unpriv.h>
 
@@ -129,6 +130,7 @@ int sbi_illegal_insn_handler(ulong insn, struct
 sbi_trap_regs *regs)
 	 * instruction trap.
 	 */
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_ILLEGAL_INSN);
 	if (unlikely((insn & 3) != 3)) {
 		insn = sbi_get_insn(regs->mepc, &uptrap);
lib/sbi/sbi_illegal_insn.c +0 -0
 		if (uptrap.cause) {
lib/sbi/sbi_ipi.c index renamed from lib/sbi/sbi_ipi.c +0 -0

bfaf4e9766e1..563db2cf9e55 100644

lib/sbi/sbi_ipi.c +6 -0
@@ -19,6 +19,9 @@
 #include <sbi/sbi_init.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
+#include <sbi/sbi_string.h>
+#include <sbi/sbi_tlb.h>
 
 struct sbi_ipi_data {
 	unsigned long ipi_type;
@@ -64,6 +67,8 @@ static int sbi_ipi_send(struct sbi_scratch *scratch, u32
 remote_hartid,
 	if (ipi_dev && ipi_dev->ipi_send)
 		ipi_dev->ipi_send(remote_hartid);
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_IPI_SENT);
+
 	if (ipi_ops->sync)
 		ipi_ops->sync(scratch);
@@ -183,6 +188,7 @@ void sbi_ipi_process(void)
 			sbi_scratch_offset_ptr(scratch, ipi_data_off);
 	u32 hartid = current_hartid();
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_IPI_RECVD);
 	if (ipi_dev && ipi_dev->ipi_clear)
 		ipi_dev->ipi_clear(hartid);
 
lib/sbi/sbi_misaligned_ldst.c index renamed from lib/sbi/sbi_misaligned_ldst.c +0 -0

5057cb5ecd58..c879ce72f61a 100644

lib/sbi/sbi_misaligned_ldst.c +3 -0
@@ -12,6 +12,7 @@
 #include <sbi/riscv_fp.h>
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_misaligned_ldst.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_trap.h>
 #include <sbi/sbi_unpriv.h>
 
@@ -29,6 +30,8 @@ int sbi_misaligned_load_handler(ulong addr, ulong
 tval2, ulong tinst,
 	struct sbi_trap_info uptrap;
 	int i, fp = 0, shift = 0, len = 0;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_MISALIGNED_LOAD);
+
 	if (tinst & 0x1) {
 		/*

* Bit[0] == 1 implies trapped instruction value is @@ -149,6
+152,8 @@ int sbi_misaligned_store_handler(ulong addr, ulong tval2, ulong tinst,

lib/sbi/sbi_misaligned_ldst.c +2 -0
 	struct sbi_trap_info uptrap;
 	int i, len = 0;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_MISALIGNED_STORE);
+
 	if (tinst & 0x1) {
 		/*
 		 * Bit[0] == 1 implies trapped instruction value is diff --git

a/lib/sbi/sbi_timer.c b/lib/sbi/sbi_timer.c index
63e8ea98eadc..c7f1c80b8939 100644

lib/sbi/sbi_timer.c +2 -0
@@ -12,6 +12,7 @@
 #include <sbi/sbi_error.h>
 #include <sbi/sbi_hart.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_scratch.h>
 #include <sbi/sbi_timer.h>
 
@@ -88,6 +89,7 @@ void sbi_timer_set_delta_upper(ulong delta_upper)
 
 void sbi_timer_event_start(u64 next_event)  {
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SET_TIMER);
 	if (timer_dev && timer_dev->timer_event_start)
 		timer_dev->timer_event_start(next_event);
 	csr_clear(CSR_MIP, MIP_STIP);
lib/sbi/sbi_tlb.c index renamed from lib/sbi/sbi_tlb.c +0 -0

73f59e8681e2..6e9e4f0b1916 100644

lib/sbi/sbi_tlb.c +3 -0
@@ -21,6 +21,7 @@
 #include <sbi/sbi_string.h>
 #include <sbi/sbi_console.h>
 #include <sbi/sbi_platform.h>
+#include <sbi/sbi_pmu.h>
 
 static unsigned long tlb_sync_off;
 static unsigned long tlb_fifo_off;
@@ -39,6 +40,8 @@ void sbi_tlb_local_hfence_vvma(struct sbi_tlb_info
 *tinfo)
 	unsigned long vmid  = tinfo->vmid;
 	unsigned long i, hgatp;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_RCVD);
+
 	hgatp = csr_swap(CSR_HGATP,
 			 (vmid << HGATP_VMID_SHIFT) &

HGATP_VMID_MASK);

lib/sbi/sbi_tlb.c +2 -0
@@ -61,6 +64,8 @@ void sbi_tlb_local_hfence_gvma(struct sbi_tlb_info
 *tinfo)
 	unsigned long size  = tinfo->size;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_RCVD);
+
 	if ((start == 0 && size == 0) || (size == SBI_TLB_FLUSH_ALL)) {
 		__sbi_hfence_gvma_all();
lib/sbi/sbi_tlb.c +2 -0
 		return;
@@ -77,6 +82,8 @@ void sbi_tlb_local_sfence_vma(struct sbi_tlb_info
 *tinfo)
 	unsigned long size  = tinfo->size;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_RCVD);
+
 	if ((start == 0 && size == 0) || (size == SBI_TLB_FLUSH_ALL)) {
 		sbi_tlb_flush_all();
lib/sbi/sbi_tlb.c +2 -0
 		return;
@@ -98,6 +105,8 @@ void sbi_tlb_local_hfence_vvma_asid(struct
 sbi_tlb_info *tinfo)
 	unsigned long vmid  = tinfo->vmid;
 	unsigned long i, hgatp;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_ASID_RCVD);
+
 	hgatp = csr_swap(CSR_HGATP,
 			 (vmid << HGATP_VMID_SHIFT) &

HGATP_VMID_MASK);

lib/sbi/sbi_tlb.c +2 -0
@@ -126,6 +135,8 @@ void sbi_tlb_local_hfence_gvma_vmid(struct
 sbi_tlb_info *tinfo)
 	unsigned long vmid  = tinfo->vmid;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_VMID_RCVD);
+
 	if (start == 0 && size == 0) {
 		__sbi_hfence_gvma_all();
lib/sbi/sbi_tlb.c +2 -0
 		return;
@@ -148,6 +159,8 @@ void sbi_tlb_local_sfence_vma_asid(struct
 sbi_tlb_info *tinfo)
 	unsigned long asid  = tinfo->asid;
 	unsigned long i;
 
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_ASID_RCVD);
+
 	if (start == 0 && size == 0) {
 		sbi_tlb_flush_all();
lib/sbi/sbi_tlb.c +24 -0
 		return;
@@ -172,9 +185,32 @@ void sbi_tlb_local_sfence_vma_asid(struct
 sbi_tlb_info *tinfo)
 
 void sbi_tlb_local_fence_i(struct sbi_tlb_info *tinfo)  {
+	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_FENCE_I_RECVD);
+
 	__asm__ __volatile("fence.i");
 }
 
+static void tlb_pmu_incr_fw_ctr(struct sbi_tlb_info *data) {
+	if (unlikely(!data))
+		return;
+
+	if (data->local_fn == sbi_tlb_local_fence_i)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_FENCE_I_SENT);
+	else if (data->local_fn == sbi_tlb_local_sfence_vma)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_SENT);
+	else if (data->local_fn == sbi_tlb_local_sfence_vma_asid)
+
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_ASID_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_gvma)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_gvma_vmid)
+
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_GVMA_VMID_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_vvma)
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_SENT);
+	else if (data->local_fn == sbi_tlb_local_hfence_vvma_asid)
+
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_ASID_SENT);
+}
+
 static void sbi_tlb_entry_process(struct sbi_tlb_info *tinfo)  {
 	u32 rhartid;
@@ -368,6 +404,8 @@ int sbi_tlb_request(ulong hmask, ulong hbase, struct
 sbi_tlb_info *tinfo)
 	if (!tinfo->local_fn)
 		return SBI_EINVAL;
 
+	tlb_pmu_incr_fw_ctr(tinfo);
+
 	return sbi_ipi_send_many(hmask, hbase, tlb_event, tinfo);  }
 
lib/sbi/sbi_trap.c index renamed from lib/sbi/sbi_trap.c +0 -0

1ba649074b75..dda68d4375af 100644

lib/sbi/sbi_trap.c +1 -0
@@ -16,6 +16,7 @@
 #include <sbi/sbi_illegal_insn.h>
 #include <sbi/sbi_ipi.h>
 #include <sbi/sbi_misaligned_ldst.h>
+#include <sbi/sbi_pmu.h>
 #include <sbi/sbi_scratch.h>
 #include <sbi/sbi_timer.h>
 #include <sbi/sbi_trap.h>

lib/sbi/sbi_trap.c struct sbi_trap_regs *sbi_trap_handler(struct · line 263

Quoted 6 lines
lib/sbi/sbi_trap.c +2 -0
@@ -257,6 +258,10 @@ struct sbi_trap_regs *sbi_trap_handler(struct
 sbi_trap_regs *regs)
 		rc  = sbi_ecall_handler(regs);
 		msg = "ecall handler failed";
 		break;
+	case CAUSE_LOAD_ACCESS:
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_ACCESS_LOAD);

Need a "break; " here

lib/sbi/sbi_trap.c struct sbi_trap_regs *sbi_trap_handler(struct sbi_trap_regs *regs) · line 264

Quoted 2 lines
lib/sbi/sbi_trap.c +2 -0
+	case CAUSE_STORE_ACCESS:
+		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_ACCESS_STORE);

Need a "break;" here as well.

Quoted 5 lines
lib/sbi/sbi_trap.c +0 -0
 	default:
 		/* If the trap came from S or U mode, redirect it there */

trap.epc = regs->mepc;
--
2.25.1

Otherwise looks good to me.

Regards,
Anup

#42 lore raw

PATCH v2 14/15 lib:sbi:tlb: Improve function naming

In reply to Atish Patra

Follow the standard conventon for static function names:

All global functions should be start with sbi_<module name>_ All static functions should be start with <module name>_

---
 lib/sbi/sbi_tlb.c | 40 ++++++++++++++++++++--------------------
 1 file changed, 20 insertions(+), 20 deletions(-)
lib/sbi/sbi_tlb.c +20 -20
index 6e9e4f0b1916..bddf2654005e 100644
@@ -28,7 +28,7 @@ static unsigned long tlb_fifo_off;
 static unsigned long tlb_fifo_mem_off;
 static unsigned long tlb_range_flush_limit;
 
-static void sbi_tlb_flush_all(void)
+static void tlb_flush_all(void)
 {
 	__asm__ __volatile("sfence.vma");
 }
@@ -85,7 +85,7 @@ void sbi_tlb_local_sfence_vma(struct sbi_tlb_info *tinfo)
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_RCVD);
 
 	if ((start == 0 && size == 0) || (size == SBI_TLB_FLUSH_ALL)) {
-		sbi_tlb_flush_all();
+		tlb_flush_all();
 		return;
 	}
 
@@ -162,7 +162,7 @@ void sbi_tlb_local_sfence_vma_asid(struct sbi_tlb_info *tinfo)
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_ASID_RCVD);
 
 	if (start == 0 && size == 0) {
-		sbi_tlb_flush_all();
+		tlb_flush_all();
 		return;
 	}
 
@@ -211,7 +211,7 @@ static void tlb_pmu_incr_fw_ctr(struct sbi_tlb_info *data)
 		sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_ASID_SENT);
 }
 
-static void sbi_tlb_entry_process(struct sbi_tlb_info *tinfo)
+static void tlb_entry_process(struct sbi_tlb_info *tinfo)
 {
 	u32 rhartid;
 	struct sbi_scratch *rscratch = NULL;
@@ -229,7 +229,7 @@ static void sbi_tlb_entry_process(struct sbi_tlb_info *tinfo)
 	}
 }
 
-static void sbi_tlb_process_count(struct sbi_scratch *scratch, int count)
+static void tlb_process_count(struct sbi_scratch *scratch, int count)
 {
 	struct sbi_tlb_info tinfo;
 	u32 deq_count = 0;
@@ -237,7 +237,7 @@ static void sbi_tlb_process_count(struct sbi_scratch *scratch, int count)
 			sbi_scratch_offset_ptr(scratch, tlb_fifo_off);
 
 	while (!sbi_fifo_dequeue(tlb_fifo, &tinfo)) {
-		sbi_tlb_entry_process(&tinfo);
+		tlb_entry_process(&tinfo);
 		deq_count++;
 		if (deq_count > count)
 			break;
@@ -245,17 +245,17 @@ static void sbi_tlb_process_count(struct sbi_scratch *scratch, int count)
 	}
 }
 
-static void sbi_tlb_process(struct sbi_scratch *scratch)
+static void tlb_process(struct sbi_scratch *scratch)
 {
 	struct sbi_tlb_info tinfo;
 	struct sbi_fifo *tlb_fifo =
 			sbi_scratch_offset_ptr(scratch, tlb_fifo_off);
 
 	while (!sbi_fifo_dequeue(tlb_fifo, &tinfo))
-		sbi_tlb_entry_process(&tinfo);
+		tlb_entry_process(&tinfo);
 }
 
-static void sbi_tlb_sync(struct sbi_scratch *scratch)
+static void tlb_sync(struct sbi_scratch *scratch)
 {
 	unsigned long *tlb_sync =
 			sbi_scratch_offset_ptr(scratch, tlb_sync_off);
@@ -265,13 +265,13 @@ static void sbi_tlb_sync(struct sbi_scratch *scratch)
 		 * While we are waiting for remote hart to set the sync,
 		 * consume fifo requests to avoid deadlock.
 		 */
-		sbi_tlb_process_count(scratch, 1);
+		tlb_process_count(scratch, 1);
 	}
 
 	return;
 }
 
-static inline int __sbi_tlb_range_check(struct sbi_tlb_info *curr,
+static inline int tlb_range_check(struct sbi_tlb_info *curr,
 					struct sbi_tlb_info *next)
 {
 	unsigned long curr_end;
@@ -314,7 +314,7 @@ static inline int __sbi_tlb_range_check(struct sbi_tlb_info *curr,
  *	before continuing the while loop. This method is preferred over wfi/ipi because
  *	of MMIO cost involved in later method.
  */
-static int sbi_tlb_update_cb(void *in, void *data)
+static int tlb_update_cb(void *in, void *data)
 {
 	struct sbi_tlb_info *curr;
 	struct sbi_tlb_info *next;
@@ -329,16 +329,16 @@ static int sbi_tlb_update_cb(void *in, void *data)
 	if (next->local_fn == sbi_tlb_local_sfence_vma_asid &&
 	    curr->local_fn == sbi_tlb_local_sfence_vma_asid) {
 		if (next->asid == curr->asid)
-			ret = __sbi_tlb_range_check(curr, next);
+			ret = tlb_range_check(curr, next);
 	} else if (next->local_fn == sbi_tlb_local_sfence_vma &&
 		   curr->local_fn == sbi_tlb_local_sfence_vma) {
-		ret = __sbi_tlb_range_check(curr, next);
+		ret = tlb_range_check(curr, next);
 	}
 
 	return ret;
 }
 
-static int sbi_tlb_update(struct sbi_scratch *scratch,
+static int tlb_update(struct sbi_scratch *scratch,
 			  struct sbi_scratch *remote_scratch,
 			  u32 remote_hartid, void *data)
 {
@@ -368,7 +368,7 @@ static int sbi_tlb_update(struct sbi_scratch *scratch,
 
 	tlb_fifo_r = sbi_scratch_offset_ptr(remote_scratch, tlb_fifo_off);
 
-	ret = sbi_fifo_inplace_update(tlb_fifo_r, data, sbi_tlb_update_cb);
+	ret = sbi_fifo_inplace_update(tlb_fifo_r, data, tlb_update_cb);
 	if (ret != SBI_FIFO_UNCHANGED) {
 		return 1;
 	}
@@ -382,7 +382,7 @@ static int sbi_tlb_update(struct sbi_scratch *scratch,
 		 * TODO: Introduce a wait/wakeup event mechanism to handle
 		 * this properly.
 		 */
-		sbi_tlb_process_count(scratch, 1);
+		tlb_process_count(scratch, 1);
 		sbi_dprintf("hart%d: hart%d tlb fifo full\n",
 			    curr_hartid, remote_hartid);
 	}
@@ -392,9 +392,9 @@ static int sbi_tlb_update(struct sbi_scratch *scratch,
 
 static struct sbi_ipi_event_ops tlb_ops = {
 	.name = "IPI_TLB",
-	.update = sbi_tlb_update,
-	.sync = sbi_tlb_sync,
-	.process = sbi_tlb_process,
+	.update = tlb_update,
+	.sync = tlb_sync,
+	.process = tlb_process,
 };
 
 static u32 tlb_event = SBI_IPI_EVENT_MAX;
Signature · 1 line
2.25.1
#43 lore raw

PATCH v2 14/15 lib:sbi:tlb: Improve function naming

Quoted 9 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 14/15] lib:sbi:tlb: Improve function naming

Quoted 6 lines

Follow the standard conventon for static function names:

All global functions should be start with sbi_<module name>_ All static functions should be start with <module name>_

Looks good to me.

Regards,
Anup

Quoted 170 lines
---
 lib/sbi/sbi_tlb.c | 40 ++++++++++++++++++++--------------------
 1 file changed, 20 insertions(+), 20 deletions(-)
lib/sbi/sbi_tlb.c index renamed from lib/sbi/sbi_tlb.c +0 -0

6e9e4f0b1916..bddf2654005e 100644

lib/sbi/sbi_tlb.c +4 -4
@@ -28,7 +28,7 @@ static unsigned long tlb_fifo_off;  static unsigned long
 tlb_fifo_mem_off;  static unsigned long tlb_range_flush_limit;
 
-static void sbi_tlb_flush_all(void)
+static void tlb_flush_all(void)
 {
 	__asm__ __volatile("sfence.vma");
 }
@@ -85,7 +85,7 @@ void sbi_tlb_local_sfence_vma(struct sbi_tlb_info
 *tinfo)
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_RCVD);
 
 	if ((start == 0 && size == 0) || (size == SBI_TLB_FLUSH_ALL)) {
-		sbi_tlb_flush_all();
+		tlb_flush_all();
 		return;
 	}
@@ -162,7 +162,7 @@ void sbi_tlb_local_sfence_vma_asid(struct
 sbi_tlb_info *tinfo)
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_SFENCE_VMA_ASID_RCVD);
 
 	if (start == 0 && size == 0) {
-		sbi_tlb_flush_all();
+		tlb_flush_all();
 		return;
 	}
@@ -211,7 +211,7 @@ static void tlb_pmu_incr_fw_ctr(struct sbi_tlb_info
 *data)
 
 	sbi_pmu_ctr_incr_fw(SBI_PMU_FW_HFENCE_VVMA_ASID_SENT);
 }
 
-static void sbi_tlb_entry_process(struct sbi_tlb_info *tinfo)
+static void tlb_entry_process(struct sbi_tlb_info *tinfo)
 {
lib/sbi/sbi_tlb.c +1 -1
 	u32 rhartid;
 	struct sbi_scratch *rscratch = NULL;
@@ -229,7 +229,7 @@ static void sbi_tlb_entry_process(struct sbi_tlb_info
 *tinfo)
 	}
 }
 
-static void sbi_tlb_process_count(struct sbi_scratch *scratch, int count)
+static void tlb_process_count(struct sbi_scratch *scratch, int count)
 {
 	struct sbi_tlb_info tinfo;
lib/sbi/sbi_tlb.c +1 -1
 	u32 deq_count = 0;
@@ -237,7 +237,7 @@ static void sbi_tlb_process_count(struct sbi_scratch
 *scratch, int count)
 			sbi_scratch_offset_ptr(scratch, tlb_fifo_off);
 
 	while (!sbi_fifo_dequeue(tlb_fifo, &tinfo)) {
-		sbi_tlb_entry_process(&tinfo);
+		tlb_entry_process(&tinfo);
 		deq_count++;
 		if (deq_count > count)
lib/sbi/sbi_tlb.c +3 -3
 			break;
@@ -245,17 +245,17 @@ static void sbi_tlb_process_count(struct
 sbi_scratch *scratch, int count)
 	}
 }
 
-static void sbi_tlb_process(struct sbi_scratch *scratch)
+static void tlb_process(struct sbi_scratch *scratch)
 {
 	struct sbi_tlb_info tinfo;
 	struct sbi_fifo *tlb_fifo =
 			sbi_scratch_offset_ptr(scratch, tlb_fifo_off);
 
 	while (!sbi_fifo_dequeue(tlb_fifo, &tinfo))
-		sbi_tlb_entry_process(&tinfo);
+		tlb_entry_process(&tinfo);
 }
 
-static void sbi_tlb_sync(struct sbi_scratch *scratch)
+static void tlb_sync(struct sbi_scratch *scratch)
 {
 	unsigned long *tlb_sync =

sbi_scratch_offset_ptr(scratch, tlb_sync_off); @@ -
265,13 +265,13 @@ static void sbi_tlb_sync(struct sbi_scratch *scratch)

lib/sbi/sbi_tlb.c +2 -2
 		 * While we are waiting for remote hart to set the sync,
 		 * consume fifo requests to avoid deadlock.
 		 */
-		sbi_tlb_process_count(scratch, 1);
+		tlb_process_count(scratch, 1);
 	}
 
 	return;
 }
 
-static inline int __sbi_tlb_range_check(struct sbi_tlb_info *curr,
+static inline int tlb_range_check(struct sbi_tlb_info *curr,
 					struct sbi_tlb_info *next)
 {
 	unsigned long curr_end;
@@ -314,7 +314,7 @@ static inline int __sbi_tlb_range_check(struct
 sbi_tlb_info *curr,
  *	before continuing the while loop. This method is preferred over

wfi/ipi because
* of MMIO cost involved in later method.
*/

lib/sbi/sbi_tlb.c +5 -5
-static int sbi_tlb_update_cb(void *in, void *data)
+static int tlb_update_cb(void *in, void *data)
 {
 	struct sbi_tlb_info *curr;
 	struct sbi_tlb_info *next;
@@ -329,16 +329,16 @@ static int sbi_tlb_update_cb(void *in, void *data)
 	if (next->local_fn == sbi_tlb_local_sfence_vma_asid &&
 	    curr->local_fn == sbi_tlb_local_sfence_vma_asid) {
 		if (next->asid == curr->asid)
-			ret = __sbi_tlb_range_check(curr, next);
+			ret = tlb_range_check(curr, next);
 	} else if (next->local_fn == sbi_tlb_local_sfence_vma &&
 		   curr->local_fn == sbi_tlb_local_sfence_vma) {
-		ret = __sbi_tlb_range_check(curr, next);
+		ret = tlb_range_check(curr, next);
 	}
 
 	return ret;
 }
 
-static int sbi_tlb_update(struct sbi_scratch *scratch,
+static int tlb_update(struct sbi_scratch *scratch,
 			  struct sbi_scratch *remote_scratch,
 			  u32 remote_hartid, void *data)
 {
@@ -368,7 +368,7 @@ static int sbi_tlb_update(struct sbi_scratch *scratch,
 
 	tlb_fifo_r = sbi_scratch_offset_ptr(remote_scratch, tlb_fifo_off);
 
-	ret = sbi_fifo_inplace_update(tlb_fifo_r, data, sbi_tlb_update_cb);
+	ret = sbi_fifo_inplace_update(tlb_fifo_r, data, tlb_update_cb);
 	if (ret != SBI_FIFO_UNCHANGED) {
 		return 1;
 	}
@@ -382,7 +382,7 @@ static int sbi_tlb_update(struct sbi_scratch *scratch,
 		 * TODO: Introduce a wait/wakeup event mechanism to

handle

lib/sbi/sbi_tlb.c +4 -5
 		 * this properly.
 		 */
-		sbi_tlb_process_count(scratch, 1);
+		tlb_process_count(scratch, 1);
 		sbi_dprintf("hart%d: hart%d tlb fifo full\n",
 			    curr_hartid, remote_hartid);
 	}
@@ -392,9 +392,9 @@ static int sbi_tlb_update(struct sbi_scratch *scratch,
 
 static struct sbi_ipi_event_ops tlb_ops = {
 	.name = "IPI_TLB",
-	.update = sbi_tlb_update,
-	.sync = sbi_tlb_sync,
-	.process = sbi_tlb_process,
+	.update = tlb_update,
+	.sync = tlb_sync,
+	.process = tlb_process,
 };
 
 static u32 tlb_event = SBI_IPI_EVENT_MAX;
--

2.25.1

#44 lore raw

PATCH v2 15/15 platform: generic: Add PMU support

In reply to Atish Patra

Add PMU support for generic platform. Generic platform solely relies on the device tree to parse all pmu related information. If any event is not described in device tree, generic platform will not support it.

---
 platform/generic/platform.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
platform/generic/platform.c +30 -0
index da0c1af8f92e..44a9c73fba0c 100644
@@ -16,6 +16,7 @@
 #include <sbi_utils/fdt/fdt_domain.h>
 #include <sbi_utils/fdt/fdt_fixup.h>
 #include <sbi_utils/fdt/fdt_helper.h>
+#include <sbi_utils/fdt/fdt_pmu.h>
 #include <sbi_utils/irqchip/fdt_irqchip.h>
 #include <sbi_utils/serial/fdt_serial.h>
 #include <sbi_utils/timer/fdt_timer.h>
@@ -184,6 +185,33 @@ static u64 generic_tlbr_flush_limit(void)
 	return SBI_PLATFORM_TLB_RANGE_FLUSH_LIMIT_DEFAULT;
 }
 
+static int generic_pmu_init(void)
+{
+	return fdt_pmu_setup(sbi_scratch_thishart_arg1_ptr());
+}
+
+static uint64_t generic_pmu_xlate_to_mhpmevent(uint32_t event_idx,
+					       uint64_t data)
+{
+	uint64_t evt_val = 0;
+
+	/* data is valid only for raw events and is equal to event selector */
+	if (event_idx == SBI_PMU_EVENT_RAW_IDX)
+		evt_val = data;
+	else {
+		/**
+		 * Generic platform follows the SBI specification recommendation
+		 * i.e. zero extended event_idx is used as mhpmevent value for
+		 * hardware general/cache events if platform does't define one.
+		 */
+		evt_val = fdt_pmu_get_select_value(event_idx);
+		if (!evt_val)
+			evt_val = (uint64_t)event_idx;
+	}
+
+	return evt_val;
+}
+
 const struct sbi_platform_operations platform_ops = {
 	.early_init		= generic_early_init,
 	.final_init		= generic_final_init,
@@ -195,6 +223,8 @@ const struct sbi_platform_operations platform_ops = {
 	.irqchip_exit		= fdt_irqchip_exit,
 	.ipi_init		= fdt_ipi_init,
 	.ipi_exit		= fdt_ipi_exit,
+	.pmu_init		= generic_pmu_init,
+	.pmu_xlate_to_mhpmevent = generic_pmu_xlate_to_mhpmevent,
 	.get_tlbr_flush_limit	= generic_tlbr_flush_limit,
 	.timer_init		= fdt_timer_init,
 	.timer_exit		= fdt_timer_exit,
Signature · 1 line
2.25.1
#45 lore raw

PATCH v2 15/15 platform: generic: Add PMU support

Quoted 9 lines

-----Original Message-----
From: Atish Patra <[email protected]>
Sent: 27 May 2021 06:01
To: opensbi at lists.infradead.org
Cc: Atish Patra <[email protected]>; Anup Patel <[email protected]>
Subject: [PATCH v2 15/15] platform: generic: Add PMU support

Quoted 5 lines

Add PMU support for generic platform. Generic platform solely relies on the device tree to parse all pmu related information. If any event is not described in device tree, generic platform will not support it.

Looks good to me.

Regards,
Anup

Quoted 64 lines
---
 platform/generic/platform.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
platform/generic/platform.c index renamed from platform/generic/platform.c +0 -0

da0c1af8f92e..44a9c73fba0c 100644

platform/generic/platform.c +1 -0
@@ -16,6 +16,7 @@
 #include <sbi_utils/fdt/fdt_domain.h>
 #include <sbi_utils/fdt/fdt_fixup.h>
 #include <sbi_utils/fdt/fdt_helper.h>
+#include <sbi_utils/fdt/fdt_pmu.h>
 #include <sbi_utils/irqchip/fdt_irqchip.h>  #include

<sbi_utils/serial/fdt_serial.h> #include <sbi_utils/timer/fdt_timer.h> @@ - 184,6 +185,33 @@ static u64 generic_tlbr_flush_limit(void)

platform/generic/platform.c +16 -0
 	return SBI_PLATFORM_TLB_RANGE_FLUSH_LIMIT_DEFAULT;
 }
 
+static int generic_pmu_init(void)
+{
+	return fdt_pmu_setup(sbi_scratch_thishart_arg1_ptr());
+}
+
+static uint64_t generic_pmu_xlate_to_mhpmevent(uint32_t event_idx,
+					       uint64_t data)
+{
+	uint64_t evt_val = 0;
+
+	/* data is valid only for raw events and is equal to event selector */
+	if (event_idx == SBI_PMU_EVENT_RAW_IDX)
+		evt_val = data;
+	else {
+		/**
+		 * Generic platform follows the SBI specification

recommendation

platform/generic/platform.c +1 -0
+		 * i.e. zero extended event_idx is used as mhpmevent value

for

platform/generic/platform.c +1 -0
+		 * hardware general/cache events if platform does't define

one.

platform/generic/platform.c +11 -0
+		 */
+		evt_val = fdt_pmu_get_select_value(event_idx);
+		if (!evt_val)
+			evt_val = (uint64_t)event_idx;
+	}
+
+	return evt_val;
+}
+
 const struct sbi_platform_operations platform_ops = {
 	.early_init		= generic_early_init,
 	.final_init		= generic_final_init,
@@ -195,6 +223,8 @@ const struct sbi_platform_operations platform_ops =
 {
 	.irqchip_exit		= fdt_irqchip_exit,
 	.ipi_init		= fdt_ipi_init,
 	.ipi_exit		= fdt_ipi_exit,
+	.pmu_init		= generic_pmu_init,
+	.pmu_xlate_to_mhpmevent = generic_pmu_xlate_to_mhpmevent,
 	.get_tlbr_flush_limit	= generic_tlbr_flush_limit,
 	.timer_init		= fdt_timer_init,

.timer_exit = fdt_timer_exit,
--
2.25.1