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 <jta...@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