1 /* hwclock.c - get and set the hwclock
2 *
3 * Copyright 2014 Bilal Qureshi <[email protected]>
4 *
5 * No standard, but see Documentation/rtc.txt in the linux kernel source.
6 *
7 * TODO: get/set subsecond time
8 USE_HWCLOCK(NEWTOY(hwclock, ">0(fast)f(rtc):u(utc)l(localtime)t(systz)s(hctosys)r(show)w(systohc)[-ul][!rtsw]", TOYFLAG_SBIN))
9
10 config HWCLOCK
11 bool "hwclock"
12 default y
13 help
14 usage: hwclock [-rswtlu] [-f FILE]
15
16 Get/set the hardware clock. Default is hwclock -ruf /dev/rtc0
17
18 -f Use specified device FILE instead of /dev/rtc0 (--rtc)
19 -l Hardware clock uses localtime (--localtime)
20 -r Show hardware clock time (--show)
21 -s Set system time from hardware clock (--hctosys)
22 -t Inform kernel of non-UTC clock's timezone so it returns UTC (--systz)
23 -u Hardware clock uses UTC (--utc)
24 -w Set hardware clock from system time (--systohc)
25 */
26
27
28 // Bug workaround for musl commit 5a105f19b5aa which removed a symbol the
29 // kernel headers have. (Can't copy it here, varies wildly by architecture.)
30 #if __has_include(<asm/unistd.h>)
31 #include <asm/unistd.h>
32 #endif
33
34 #define FOR_hwclock
35 #include "toys.h"
36 #include <linux/rtc.h>
37
GLOBALS(char * f;)38 GLOBALS(
39 char *f;
40 )
41
42 // Bug workaround for musl commit 2c2c3605d3b3 which rewrote the syscall
43 // wrapper to not use the syscall, which is the only way to set kernel's sys_tz
44 #ifdef _NR_settimeofday
45 #define settimeofday(x, tz) syscall(__NR_settimeofday, (void *)0, (void *)tz)
46 #else
47 #define settimeofday(x, tz) ((tz)->tz_minuteswest = 0)
48 #endif
49
50 void hwclock_main()
51 {
52 struct timezone tz = {0};
53 struct timespec ts = {0};
54 struct tm tm;
55 int fd = -1;
56
57 // -t without -u implies -l
58 if (FLAG(t)&&!FLAG(u)) toys.optflags |= FLAG_l;
59 if (FLAG(l)) {
60 // sets globals timezone and daylight from sys/time.h
61 // Handle dst adjustment ourselves. (Rebooting during dst transition is
62 // just conceptually unpleasant, linux uses UTC for a reason.)
63 tzset();
64 tz.tz_minuteswest = timezone/60 - 60*daylight;
65 }
66
67 if (!FLAG(t)) {
68 fd = xopen(TT.f ? : "/dev/rtc0", O_WRONLY*FLAG(w));
69
70 // Get current time in seconds from rtc device.
71 if (!FLAG(w)) {
72 xioctl(fd, RTC_RD_TIME, &tm);
73 ts.tv_sec = xmktime(&tm, !FLAG(l));
74 }
75 }
76
77 if (FLAG(w) || FLAG(t)) {
78 if (FLAG(w)) {
79 if (clock_gettime(CLOCK_REALTIME, &ts)) perror_exit("clock_gettime");
80 if (!(FLAG(l) ? localtime_r : gmtime_r)(&ts.tv_sec, &tm))
81 error_exit("%s failed", FLAG(l) ? "localtime_r" : "gmtime_r");
82 xioctl(fd, RTC_SET_TIME, &tm);
83 }
84 if (settimeofday(0, &tz)) perror_exit("settimeofday");
85 } else if (FLAG(s)) {
86 if (clock_settime(CLOCK_REALTIME, &ts)) perror_exit("clock_settime");
87 } else {
88 strftime(toybuf, sizeof(toybuf), "%F %T%z", &tm);
89 xputs(toybuf);
90 }
91
92 if (CFG_TOYBOX_FREE) xclose(fd);
93 }
94