From f813b62316395205f4c744cde43885081b5f88ae Mon Sep 17 00:00:00 2001 From: caoxia2008cxx <78151946+caoxia2008cxx@users.noreply.github.com> Date: Thu, 29 Apr 2021 17:05:01 +0800 Subject: set boot time from monotonic time (#19444) utmp: calculate boot timestamp from monotonic timestamp instead of realtime timestamp --- src/update-utmp/update-utmp.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'src/update-utmp') diff --git a/src/update-utmp/update-utmp.c b/src/update-utmp/update-utmp.c index 38df4cddf0..0995e3557e 100644 --- a/src/update-utmp/update-utmp.c +++ b/src/update-utmp/update-utmp.c @@ -44,7 +44,7 @@ static void context_clear(Context *c) { #endif } -static usec_t get_startup_time(Context *c) { +static usec_t get_startup_monotonic_time(Context *c) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; usec_t t = 0; int r; @@ -56,7 +56,7 @@ static usec_t get_startup_time(Context *c) { "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", - "UserspaceTimestamp", + "UserspaceTimestampMonotonic", &error, 't', &t); if (r < 0) { @@ -115,6 +115,7 @@ static int get_current_runlevel(Context *c) { static int on_reboot(Context *c) { int r = 0, q; usec_t t; + usec_t boottime; assert(c); @@ -130,9 +131,15 @@ static int on_reboot(Context *c) { /* If this call fails it will return 0, which * utmp_put_reboot() will then fix to the current time */ - t = get_startup_time(c); - - q = utmp_put_reboot(t); + t = get_startup_monotonic_time(c); + boottime = map_clock_usec(t, CLOCK_MONOTONIC, CLOCK_REALTIME); + /* We query the recorded monotonic time here (instead of the system clock CLOCK_REALTIME), + * even though we actually want the system clock time. That's because there's a likely + * chance that the system clock wasn't set right during early boot. By manually converting + * the monotonic clock to the system clock here we can compensate + * for incorrectly set clocks during early boot. */ + + q = utmp_put_reboot(boottime); if (q < 0) r = log_error_errno(q, "Failed to write utmp record: %m"); -- cgit v1.2.1