]> git.ipfire.org Git - thirdparty/util-linux.git/blame - lib/monotonic.c
Merge branch 'clock' of https://github.com/t-8ch/util-linux
[thirdparty/util-linux.git] / lib / monotonic.c
CommitLineData
cd2876d2
KZ
1/*
2 * Please, don't add this file to libcommon because clock_gettime() requires
3 * -lrt on systems with old libc.
40f8c5e4
KZ
4 *
5 * No copyright is claimed. This code is in the public domain; do with
6 * it what you wish.
cd2876d2 7 */
2c5484f7 8#include <time.h>
378543e1 9#include <signal.h>
440d1db7 10#ifdef HAVE_SYSINFO
2c5484f7 11#include <sys/sysinfo.h>
440d1db7 12#endif
2c5484f7
KZ
13#include <sys/time.h>
14
15#include "c.h"
cd2876d2 16#include "monotonic.h"
2c5484f7
KZ
17
18int get_boot_time(struct timeval *boot_time)
19{
60cb2c37 20#ifdef CLOCK_BOOTTIME
2c5484f7 21 struct timespec hires_uptime;
60cb2c37
RM
22 struct timeval lores_uptime;
23#endif
24 struct timeval now;
88e0f3df 25#ifdef HAVE_SYSINFO
2c5484f7 26 struct sysinfo info;
88e0f3df 27#endif
2c5484f7 28
26e8964b 29 if (gettimeofday(&now, NULL) != 0)
2c5484f7 30 return -errno;
2c5484f7
KZ
31#ifdef CLOCK_BOOTTIME
32 if (clock_gettime(CLOCK_BOOTTIME, &hires_uptime) == 0) {
33 TIMESPEC_TO_TIMEVAL(&lores_uptime, &hires_uptime);
34 timersub(&now, &lores_uptime, boot_time);
35 return 0;
36 }
37#endif
88e0f3df 38#ifdef HAVE_SYSINFO
2c5484f7
KZ
39 /* fallback */
40 if (sysinfo(&info) != 0)
26e8964b 41 return -errno;
2c5484f7
KZ
42
43 boot_time->tv_sec = now.tv_sec - info.uptime;
44 boot_time->tv_usec = 0;
45 return 0;
88e0f3df
ST
46#else
47 return -ENOSYS;
48#endif
2c5484f7 49}
cd2876d2 50
02f3ecd6 51usec_t get_suspended_time(void)
9bf622da
KK
52{
53#if defined(CLOCK_BOOTTIME) && defined(CLOCK_MONOTONIC)
54 struct timespec boot, mono;
55
56 if (clock_gettime(CLOCK_BOOTTIME, &boot) == 0 &&
57 clock_gettime(CLOCK_MONOTONIC, &mono) == 0)
02f3ecd6 58 return timespec_to_usec(&boot) - timespec_to_usec(&mono);
9bf622da
KK
59#endif
60 return 0;
61}
62
cd2876d2
KZ
63int gettime_monotonic(struct timeval *tv)
64{
65#ifdef CLOCK_MONOTONIC
66 /* Can slew only by ntp and adjtime */
67 int ret;
68 struct timespec ts;
69
3fd1f771 70 /* Linux specific, can't slew */
ee6e3930 71 if (!(ret = clock_gettime(UL_CLOCK_MONOTONIC, &ts))) {
cd2876d2
KZ
72 tv->tv_sec = ts.tv_sec;
73 tv->tv_usec = ts.tv_nsec / 1000;
74 }
75 return ret;
76#else
77 return gettimeofday(tv, NULL);
78#endif
79}
378543e1 80
46cd5b17 81