]> git.ipfire.org Git - thirdparty/util-linux.git/blame - lib/monotonic.c
libblkid: don't include endian.h
[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.
4 */
2c5484f7 5#include <time.h>
378543e1 6#include <signal.h>
2c5484f7
KZ
7#include <sys/sysinfo.h>
8#include <sys/time.h>
9
10#include "c.h"
cd2876d2 11#include "monotonic.h"
2c5484f7
KZ
12
13int get_boot_time(struct timeval *boot_time)
14{
60cb2c37 15#ifdef CLOCK_BOOTTIME
2c5484f7 16 struct timespec hires_uptime;
60cb2c37
RM
17 struct timeval lores_uptime;
18#endif
19 struct timeval now;
88e0f3df 20#ifdef HAVE_SYSINFO
2c5484f7 21 struct sysinfo info;
88e0f3df 22#endif
2c5484f7 23
26e8964b 24 if (gettimeofday(&now, NULL) != 0)
2c5484f7 25 return -errno;
2c5484f7
KZ
26#ifdef CLOCK_BOOTTIME
27 if (clock_gettime(CLOCK_BOOTTIME, &hires_uptime) == 0) {
28 TIMESPEC_TO_TIMEVAL(&lores_uptime, &hires_uptime);
29 timersub(&now, &lores_uptime, boot_time);
30 return 0;
31 }
32#endif
88e0f3df 33#ifdef HAVE_SYSINFO
2c5484f7
KZ
34 /* fallback */
35 if (sysinfo(&info) != 0)
26e8964b 36 return -errno;
2c5484f7
KZ
37
38 boot_time->tv_sec = now.tv_sec - info.uptime;
39 boot_time->tv_usec = 0;
40 return 0;
88e0f3df
ST
41#else
42 return -ENOSYS;
43#endif
2c5484f7 44}
cd2876d2
KZ
45
46int gettime_monotonic(struct timeval *tv)
47{
48#ifdef CLOCK_MONOTONIC
49 /* Can slew only by ntp and adjtime */
50 int ret;
51 struct timespec ts;
52
53# ifdef CLOCK_MONOTONIC_RAW
3fd1f771 54 /* Linux specific, can't slew */
cd2876d2
KZ
55 if (!(ret = clock_gettime(CLOCK_MONOTONIC_RAW, &ts))) {
56# else
57 if (!(ret = clock_gettime(CLOCK_MONOTONIC, &ts))) {
58# endif
59 tv->tv_sec = ts.tv_sec;
60 tv->tv_usec = ts.tv_nsec / 1000;
61 }
62 return ret;
63#else
64 return gettimeofday(tv, NULL);
65#endif
66}
378543e1 67
46cd5b17 68