bigbiff | 7b4c7a6 | 2015-01-01 19:44:14 -0500 | [diff] [blame] | 1 | /* |
| 2 | * Please, don't add this file to libcommon because clock_gettime() requires |
| 3 | * -lrt on systems with old libc. |
| 4 | */ |
| 5 | #include <time.h> |
| 6 | #include <sys/sysinfo.h> |
| 7 | #include <sys/time.h> |
| 8 | |
| 9 | #include "c.h" |
| 10 | #include "nls.h" |
| 11 | #include "monotonic.h" |
| 12 | |
| 13 | int get_boot_time(struct timeval *boot_time) |
| 14 | { |
| 15 | #ifdef CLOCK_BOOTTIME |
| 16 | struct timespec hires_uptime; |
| 17 | struct timeval lores_uptime; |
| 18 | #endif |
| 19 | struct timeval now; |
| 20 | #ifdef HAVE_SYSINFO |
| 21 | struct sysinfo info; |
| 22 | #endif |
| 23 | |
| 24 | if (gettimeofday(&now, NULL) != 0) { |
| 25 | warn(_("gettimeofday failed")); |
| 26 | return -errno; |
| 27 | } |
| 28 | #ifdef CLOCK_BOOTTIME |
| 29 | if (clock_gettime(CLOCK_BOOTTIME, &hires_uptime) == 0) { |
| 30 | TIMESPEC_TO_TIMEVAL(&lores_uptime, &hires_uptime); |
| 31 | timersub(&now, &lores_uptime, boot_time); |
| 32 | return 0; |
| 33 | } |
| 34 | #endif |
| 35 | #ifdef HAVE_SYSINFO |
| 36 | /* fallback */ |
| 37 | if (sysinfo(&info) != 0) |
| 38 | warn(_("sysinfo failed")); |
| 39 | |
| 40 | boot_time->tv_sec = now.tv_sec - info.uptime; |
| 41 | boot_time->tv_usec = 0; |
| 42 | return 0; |
| 43 | #else |
| 44 | return -ENOSYS; |
| 45 | #endif |
| 46 | } |
| 47 | |
| 48 | int gettime_monotonic(struct timeval *tv) |
| 49 | { |
| 50 | #ifdef CLOCK_MONOTONIC |
| 51 | /* Can slew only by ntp and adjtime */ |
| 52 | int ret; |
| 53 | struct timespec ts; |
| 54 | |
| 55 | # ifdef CLOCK_MONOTONIC_RAW |
| 56 | /* Linux specific, cant slew */ |
| 57 | if (!(ret = clock_gettime(CLOCK_MONOTONIC_RAW, &ts))) { |
| 58 | # else |
| 59 | if (!(ret = clock_gettime(CLOCK_MONOTONIC, &ts))) { |
| 60 | # endif |
| 61 | tv->tv_sec = ts.tv_sec; |
| 62 | tv->tv_usec = ts.tv_nsec / 1000; |
| 63 | } |
| 64 | return ret; |
| 65 | #else |
| 66 | return gettimeofday(tv, NULL); |
| 67 | #endif |
| 68 | } |