[PATCH 1/3] clocksource: timer-riscv: adapt riscv_timer_get_count_rdcycle() for RV32

Antony Pavlov antonynpavlov at gmail.com
Mon Mar 29 23:31:18 BST 2021


On RV64 rdcycle instruction reads 64-bit counter which holds
a count of the number of clock cycles executed by the processor
core.
On RV32 rdcycle instruction reads only bits 31-0 of the same
counter; RDCYCLEH should be used to read bits 63–32.

The code of this patch is based on Figure 2.5: 'Sample code
for reading the 64-bit cycle counter in RV32' [1]:

    again:
      rdcycleh     x3
      rdcycle      x2
      rdcycleh     x4
      bne          x3, x4, again

  [1] The RISC-V Instruction Set Manual. Volume I:
        User-Level ISA, Document Version 2.2

Signed-off-by: Antony Pavlov <antonynpavlov at gmail.com>
---
 drivers/clocksource/timer-riscv.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/drivers/clocksource/timer-riscv.c b/drivers/clocksource/timer-riscv.c
index eb5ba2d8c2..ef67cff475 100644
--- a/drivers/clocksource/timer-riscv.c
+++ b/drivers/clocksource/timer-riscv.c
@@ -30,10 +30,17 @@ static u64 notrace riscv_timer_get_count_sbi(void)
 
 static u64 notrace riscv_timer_get_count_rdcycle(void)
 {
-	u64 ticks;
-	asm volatile("rdcycle %0" : "=r" (ticks));
+	__maybe_unused u32 hi, lo;
 
-	return ticks;
+	if (IS_ENABLED(CONFIG_64BIT))
+		return csr_read(CSR_CYCLE);
+
+	do {
+		hi = csr_read(CSR_CYCLEH);
+		lo = csr_read(CSR_CYCLE);
+	} while (hi != csr_read(CSR_CYCLEH));
+
+	return ((u64)hi << 32) | lo;
 }
 
 static u64 notrace riscv_timer_get_count(void)
-- 
2.30.1




More information about the barebox mailing list