[PATCH v2 11/13] tools/nolibc: sys_gettimeofday: add pure 64bit gettimeofday

Zhangjin Wu falcon at tinylab.org
Mon May 29 12:59:57 PDT 2023


It's time to provide 64bit time structs for all platforms, for y2038 is
near.

clock_gettime64 has been added from at least v5.0.0.

Suggested-by: Arnd Bergmann <arnd at arndb.de>
Link: https://lore.kernel.org/linux-riscv/afc4944f-9494-4367-906d-06ac47648ab7@app.fastmail.com/
Signed-off-by: Zhangjin Wu <falcon at tinylab.org>
---
 tools/include/nolibc/sys.h | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)

diff --git a/tools/include/nolibc/sys.h b/tools/include/nolibc/sys.h
index ca802627e88f..533233094733 100644
--- a/tools/include/nolibc/sys.h
+++ b/tools/include/nolibc/sys.h
@@ -25,6 +25,7 @@
 
 #include "arch.h"
 #include "errno.h"
+#include "string.h"
 #include "types.h"
 
 /* Functions in this file only describe syscalls. They're declared static so
@@ -552,7 +553,34 @@ long getpagesize(void)
 static __attribute__((unused))
 int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
 {
-	return my_syscall2(__NR_gettimeofday, tv, tz);
+#if defined(__NR_clock_gettime) || defined(__NR_clock_gettime64)
+#ifdef __NR_clock_gettime64
+	const long nr_clock_gettime = __NR_clock_gettime64;
+#elif __SIZEOF_LONG__ == 8
+	const long nr_clock_gettime = __NR_clock_gettime;
+#else
+#error No __NR_clock_gettime64 defined, cannot implement time64 sys_gettimeofday()
+#endif
+	struct timespec ts;
+	int ret;
+
+	/* set tz to zero to avoid random number */
+	if (tz != NULL)
+		memset(tz, 0, sizeof(struct timezone));
+
+	if (tv == NULL)
+		return 0;
+
+	ret = my_syscall2(nr_clock_gettime, CLOCK_REALTIME, &ts);
+	if (ret)
+		return ret;
+
+	tv->tv_sec = ts.tv_sec;
+	tv->tv_usec = (unsigned int)ts.tv_nsec / 1000;
+	return 0;
+#else
+#error Neither __NR_clock_gettime nor __NR_clock_gettime64 defined, cannot implement sys_gettimeofday()
+#endif
 }
 
 static __attribute__((unused))
-- 
2.25.1




More information about the linux-riscv mailing list