]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/clock-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/ioctl.h>
13 #include "alloc-util.h"
14 #include "clock-util.h"
15 #include "errno-util.h"
19 #include "string-util.h"
21 int clock_get_hwclock(struct tm
*tm
) {
22 _cleanup_close_
int fd
= -1;
26 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
30 /* This leaves the timezone fields of struct tm
32 if (ioctl(fd
, RTC_RD_TIME
, tm
) < 0)
35 /* We don't know daylight saving, so we reset this in order not
36 * to confuse mktime(). */
42 int clock_set_hwclock(const struct tm
*tm
) {
43 _cleanup_close_
int fd
= -1;
47 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
51 if (ioctl(fd
, RTC_SET_TIME
, tm
) < 0)
57 int clock_is_localtime(const char* adjtime_path
) {
58 _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");
73 _cleanup_free_
char *line
= NULL
;
76 for (i
= 0; i
< 2; i
++) { /* skip the first two lines */
77 r
= read_line(f
, LONG_LINE_MAX
, NULL
);
81 return false; /* less than three lines → default to UTC */
84 r
= read_line(f
, LONG_LINE_MAX
, &line
);
88 return false; /* less than three lines → default to UTC */
90 return streq(line
, "LOCAL");
92 } else if (errno
!= ENOENT
)
95 /* adjtime not present → default to UTC */
99 int clock_set_timezone(int *min
) {
100 const struct timeval
*tv_null
= NULL
;
106 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
107 assert_se(localtime_r(&ts
.tv_sec
, &tm
));
108 minutesdelta
= tm
.tm_gmtoff
/ 60;
110 tz
.tz_minuteswest
= -minutesdelta
;
111 tz
.tz_dsttime
= 0; /* DST_NONE */
114 * If the RTC does not run in UTC but in local time, the very first
115 * call to settimeofday() will set the kernel's timezone and will warp the
116 * system clock, so that it runs in UTC instead of the local time we
117 * have read from the RTC.
119 if (settimeofday(tv_null
, &tz
) < 0)
120 return negative_errno();
127 int clock_reset_timewarp(void) {
128 const struct timeval
*tv_null
= NULL
;
131 tz
.tz_minuteswest
= 0;
132 tz
.tz_dsttime
= 0; /* DST_NONE */
135 * The very first call to settimeofday() does time warp magic. Do a
136 * dummy call here, so the time warping is sealed and all later calls
137 * behave as expected.
139 if (settimeofday(tv_null
, &tz
) < 0)
145 #define TIME_EPOCH_USEC ((usec_t) TIME_EPOCH * USEC_PER_SEC)
147 int clock_apply_epoch(void) {
150 if (now(CLOCK_REALTIME
) >= TIME_EPOCH_USEC
)
153 if (clock_settime(CLOCK_REALTIME
, timespec_store(&ts
, TIME_EPOCH_USEC
)) < 0)