]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/clock-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010-2012 Lennart Poettering
11 #include <linux/rtc.h>
13 #include <sys/ioctl.h>
16 #include "clock-util.h"
19 #include "string-util.h"
22 int clock_get_hwclock(struct tm
*tm
) {
23 _cleanup_close_
int fd
= -1;
27 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
31 /* This leaves the timezone fields of struct tm
33 if (ioctl(fd
, RTC_RD_TIME
, tm
) < 0)
36 /* We don't know daylight saving, so we reset this in order not
37 * to confuse mktime(). */
43 int clock_set_hwclock(const struct tm
*tm
) {
44 _cleanup_close_
int fd
= -1;
48 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
52 if (ioctl(fd
, RTC_SET_TIME
, tm
) < 0)
58 int clock_is_localtime(const char* adjtime_path
) {
59 _cleanup_fclose_
FILE *f
;
62 adjtime_path
= "/etc/adjtime";
65 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
71 f
= fopen(adjtime_path
, "re");
76 b
= fgets(line
, sizeof(line
), f
) &&
77 fgets(line
, sizeof(line
), f
) &&
78 fgets(line
, sizeof(line
), f
);
80 /* less than three lines -> default to UTC */
84 return streq(line
, "LOCAL");
86 } else if (errno
!= ENOENT
)
89 /* adjtime not present -> default to UTC */
93 int clock_set_timezone(int *min
) {
94 const struct timeval
*tv_null
= NULL
;
100 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
101 assert_se(tm
= localtime(&ts
.tv_sec
));
102 minutesdelta
= tm
->tm_gmtoff
/ 60;
104 tz
.tz_minuteswest
= -minutesdelta
;
105 tz
.tz_dsttime
= 0; /* DST_NONE */
108 * If the RTC does not run in UTC but in local time, the very first
109 * call to settimeofday() will set the kernel's timezone and will warp the
110 * system clock, so that it runs in UTC instead of the local time we
111 * have read from the RTC.
113 if (settimeofday(tv_null
, &tz
) < 0)
114 return negative_errno();
121 int clock_reset_timewarp(void) {
122 const struct timeval
*tv_null
= NULL
;
125 tz
.tz_minuteswest
= 0;
126 tz
.tz_dsttime
= 0; /* DST_NONE */
129 * The very first call to settimeofday() does time warp magic. Do a
130 * dummy call here, so the time warping is sealed and all later calls
131 * behave as expected.
133 if (settimeofday(tv_null
, &tz
) < 0)
139 #define TIME_EPOCH_USEC ((usec_t) TIME_EPOCH * USEC_PER_SEC)
141 int clock_apply_epoch(void) {
144 if (now(CLOCK_REALTIME
) >= TIME_EPOCH_USEC
)
147 if (clock_settime(CLOCK_REALTIME
, timespec_store(&ts
, TIME_EPOCH_USEC
)) < 0)