From: Chanho Park <chanho61.park@samsung.com>
Date: Wed, 6 Sep 2023 05:18:13 +0000 (+0900)
Subject: riscv: timer: add timer_get_boot_us for BOOTSTAGE
X-Git-Tag: v2025.01-rc5-pxa1908~841^2~9
X-Git-Url: http://git.dujemihanovic.xyz/img/html/static/%7B%7B%20%24style.Permalink%20%7D%7D?a=commitdiff_plain;h=74fbd74ed2069985c9d7dd15ffe94f8a95f1022a;p=u-boot.git

riscv: timer: add timer_get_boot_us for BOOTSTAGE

timer_get_boot_us function is required to record the boot stages as
us-based timestamp.
To get a micro-second time from a timer tick, this converts the
formula like below to avoid zero result of (tick / rate) part.

From: time(us) = (tick / rate) * 1000000
To  : time(us) = (tick * 1000) / (rate / 1000)

Signed-off-by: Chanho Park <chanho61.park@samsung.com>
Reviewed-by: Leo Yu-Chi Liang <ycliang@andestech.com>
---

diff --git a/drivers/timer/riscv_timer.c b/drivers/timer/riscv_timer.c
index 28a6a6870b..169c03dcb5 100644
--- a/drivers/timer/riscv_timer.c
+++ b/drivers/timer/riscv_timer.c
@@ -11,6 +11,7 @@
  */
 
 #include <common.h>
+#include <div64.h>
 #include <dm.h>
 #include <errno.h>
 #include <fdt_support.h>
@@ -51,6 +52,27 @@ u64 notrace timer_early_get_count(void)
 }
 #endif
 
+#if CONFIG_IS_ENABLED(RISCV_SMODE) && CONFIG_IS_ENABLED(BOOTSTAGE)
+ulong timer_get_boot_us(void)
+{
+	int ret;
+	u64 ticks = 0;
+	u32 rate;
+
+	ret = dm_timer_init();
+	if (!ret) {
+		rate = timer_get_rate(gd->timer);
+		timer_get_count(gd->timer, &ticks);
+	} else {
+		rate = RISCV_SMODE_TIMER_FREQ;
+		ticks = riscv_timer_get_count(NULL);
+	}
+
+	/* Below is converted from time(us) = (tick / rate) * 10000000 */
+	return lldiv(ticks * 1000, (rate / 1000));
+}
+#endif
+
 static int riscv_timer_probe(struct udevice *dev)
 {
 	struct timer_dev_priv *uc_priv = dev_get_uclass_priv(dev);