]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/clock-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010-2012 Lennart Poettering
13 #include <linux/rtc.h>
15 #include <sys/ioctl.h>
18 #include "clock-util.h"
21 #include "string-util.h"
24 int clock_get_hwclock(struct tm
*tm
) {
25 _cleanup_close_
int fd
= -1;
29 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
33 /* This leaves the timezone fields of struct tm
35 if (ioctl(fd
, RTC_RD_TIME
, tm
) < 0)
38 /* We don't know daylight saving, so we reset this in order not
39 * to confuse mktime(). */
45 int clock_set_hwclock(const struct tm
*tm
) {
46 _cleanup_close_
int fd
= -1;
50 fd
= open("/dev/rtc", O_RDONLY
|O_CLOEXEC
);
54 if (ioctl(fd
, RTC_SET_TIME
, tm
) < 0)
60 int clock_is_localtime(const char* adjtime_path
) {
61 _cleanup_fclose_
FILE *f
;
64 adjtime_path
= "/etc/adjtime";
67 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
73 f
= fopen(adjtime_path
, "re");
78 b
= fgets(line
, sizeof(line
), f
) &&
79 fgets(line
, sizeof(line
), f
) &&
80 fgets(line
, sizeof(line
), f
);
82 /* less than three lines -> default to UTC */
86 return streq(line
, "LOCAL");
88 } else if (errno
!= ENOENT
)
91 /* adjtime not present -> default to UTC */
95 int clock_set_timezone(int *min
) {
96 const struct timeval
*tv_null
= NULL
;
102 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
103 assert_se(tm
= localtime(&ts
.tv_sec
));
104 minutesdelta
= tm
->tm_gmtoff
/ 60;
106 tz
.tz_minuteswest
= -minutesdelta
;
107 tz
.tz_dsttime
= 0; /* DST_NONE */
110 * If the RTC does not run in UTC but in local time, the very first
111 * call to settimeofday() will set the kernel's timezone and will warp the
112 * system clock, so that it runs in UTC instead of the local time we
113 * have read from the RTC.
115 if (settimeofday(tv_null
, &tz
) < 0)
116 return negative_errno();
123 int clock_reset_timewarp(void) {
124 const struct timeval
*tv_null
= NULL
;
127 tz
.tz_minuteswest
= 0;
128 tz
.tz_dsttime
= 0; /* DST_NONE */
131 * The very first call to settimeofday() does time warp magic. Do a
132 * dummy call here, so the time warping is sealed and all later calls
133 * behave as expected.
135 if (settimeofday(tv_null
, &tz
) < 0)
141 #define TIME_EPOCH_USEC ((usec_t) TIME_EPOCH * USEC_PER_SEC)
143 int clock_apply_epoch(void) {
146 if (now(CLOCK_REALTIME
) >= TIME_EPOCH_USEC
)
149 if (clock_settime(CLOCK_REALTIME
, timespec_store(&ts
, TIME_EPOCH_USEC
)) < 0)