All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v1] Use CLOCK_MONOTONIC_RAW if available for get_clock().
@ 2021-09-30 15:52 Joe Tanen
  2021-09-30 16:10 ` Peter Maydell
  0 siblings, 1 reply; 3+ messages in thread
From: Joe Tanen @ 2021-09-30 15:52 UTC (permalink / raw)
  To: qemu-devel; +Cc: Joe Tanen, dirty

CLOCK_MONOTONIC_RAW provides an unadjusted system clock on some platforms,
which is closer in spirit to providing a guest with a raw hardware clock than
CLOCK_MONOTONIC.

Using CLOCK_MONOTONIC_RAW also works around a current issue in OSX where
CLOCK_MONOTONIC has been observed to go backwards.

Since CLOCK_MONOTONIC_RAW might not be available on all platforms, revert to
using CLOCK_MONOTONIC if it is not present.

Signed-off-by: Joe Tanen <jtanen@fb.com>
---
 include/qemu/timer.h     |  3 ++-
 util/qemu-timer-common.c | 11 +++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/include/qemu/timer.h b/include/qemu/timer.h
index 88ef114689..fb8f5074df 100644
--- a/include/qemu/timer.h
+++ b/include/qemu/timer.h
@@ -828,12 +828,13 @@ static inline int64_t get_clock(void)
 #else
 
 extern int use_rt_clock;
+extern clockid_t rt_clock;
 
 static inline int64_t get_clock(void)
 {
     if (use_rt_clock) {
         struct timespec ts;
-        clock_gettime(CLOCK_MONOTONIC, &ts);
+        clock_gettime(rt_clock, &ts);
         return ts.tv_sec * 1000000000LL + ts.tv_nsec;
     } else {
         /* XXX: using gettimeofday leads to problems if the date
diff --git a/util/qemu-timer-common.c b/util/qemu-timer-common.c
index cc1326f726..5039c5406c 100644
--- a/util/qemu-timer-common.c
+++ b/util/qemu-timer-common.c
@@ -49,13 +49,24 @@ static void __attribute__((constructor)) init_get_clock(void)
 #else
 
 int use_rt_clock;
+clockid_t rt_clock;
 
 static void __attribute__((constructor)) init_get_clock(void)
 {
     struct timespec ts;
 
     use_rt_clock = 0;
+#if (defined(__APPLE__) || defined(__linux__)) && defined(CLOCK_MONOTONIC_RAW)
+    /* CLOCK_MONOTONIC_RAW is not available on all platforms or with all
+     * compiler flags.
+     */
+    if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == 0) {
+        rt_clock = CLOCK_MONOTONIC_RAW;
+        use_rt_clock = 1;
+    } else
+#endif
     if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
+        rt_clock = CLOCK_MONOTONIC;
         use_rt_clock = 1;
     }
     clock_start = get_clock();
-- 
2.31.1


^ permalink raw reply related	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2021-09-30 19:19 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2021-09-30 15:52 [PATCH v1] Use CLOCK_MONOTONIC_RAW if available for get_clock() Joe Tanen
2021-09-30 16:10 ` Peter Maydell
2021-09-30 19:17   ` Joe Tanen

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.