]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/clock-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/ioctl.h>
13 #include "clock-util.h"
16 #include "string-util.h"
19 int clock_get_hwclock(struct tm
*tm
) {
20 _cleanup_close_
int fd
= -1;
24 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
28 /* This leaves the timezone fields of struct tm
30 if (ioctl(fd
, RTC_RD_TIME
, tm
) < 0)
33 /* We don't know daylight saving, so we reset this in order not
34 * to confuse mktime(). */
40 int clock_set_hwclock(const struct tm
*tm
) {
41 _cleanup_close_
int fd
= -1;
45 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
49 if (ioctl(fd
, RTC_SET_TIME
, tm
) < 0)
55 int clock_is_localtime(const char* adjtime_path
) {
56 _cleanup_fclose_
FILE *f
;
59 adjtime_path
= "/etc/adjtime";
62 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
68 f
= fopen(adjtime_path
, "re");
73 b
= fgets(line
, sizeof(line
), f
) &&
74 fgets(line
, sizeof(line
), f
) &&
75 fgets(line
, sizeof(line
), f
);
77 /* less than three lines -> default to UTC */
81 return streq(line
, "LOCAL");
83 } else if (errno
!= ENOENT
)
86 /* adjtime not present -> default to UTC */
90 int clock_set_timezone(int *min
) {
91 const struct timeval
*tv_null
= NULL
;
97 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
98 assert_se(tm
= localtime(&ts
.tv_sec
));
99 minutesdelta
= tm
->tm_gmtoff
/ 60;
101 tz
.tz_minuteswest
= -minutesdelta
;
102 tz
.tz_dsttime
= 0; /* DST_NONE */
105 * If the RTC does not run in UTC but in local time, the very first
106 * call to settimeofday() will set the kernel's timezone and will warp the
107 * system clock, so that it runs in UTC instead of the local time we
108 * have read from the RTC.
110 if (settimeofday(tv_null
, &tz
) < 0)
111 return negative_errno();
118 int clock_reset_timewarp(void) {
119 const struct timeval
*tv_null
= NULL
;
122 tz
.tz_minuteswest
= 0;
123 tz
.tz_dsttime
= 0; /* DST_NONE */
126 * The very first call to settimeofday() does time warp magic. Do a
127 * dummy call here, so the time warping is sealed and all later calls
128 * behave as expected.
130 if (settimeofday(tv_null
, &tz
) < 0)
136 #define TIME_EPOCH_USEC ((usec_t) TIME_EPOCH * USEC_PER_SEC)
138 int clock_apply_epoch(void) {
141 if (now(CLOCK_REALTIME
) >= TIME_EPOCH_USEC
)
144 if (clock_settime(CLOCK_REALTIME
, timespec_store(&ts
, TIME_EPOCH_USEC
)) < 0)