1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#define FOR_hwclock
27#include "toys.h"
28#include <linux/rtc.h>
29
30GLOBALS(
31 char *f;
32
33 int utc;
34)
35
36static int rtc_find(struct dirtree* node)
37{
38 FILE *fp;
39
40 if (!node->parent) return DIRTREE_RECURSE;
41
42 sprintf(toybuf, "/sys/class/rtc/%s/hctosys", node->name);
43 fp = fopen(toybuf, "r");
44 if (fp) {
45 int hctosys = 0, items = fscanf(fp, "%d", &hctosys);
46
47 fclose(fp);
48 if (items == 1 && hctosys == 1) {
49 sprintf(toybuf, "/dev/%s", node->name);
50 TT.f = toybuf;
51
52 return DIRTREE_ABORT;
53 }
54 }
55
56 return 0;
57}
58
59void hwclock_main()
60{
61 struct timezone tzone;
62 struct timeval timeval;
63 struct tm tm;
64 time_t time;
65 int fd = -1;
66
67
68 if (toys.optflags & FLAG_u) TT.utc = 1;
69 else {
70 FILE *fp;
71 char *s = 0;
72
73 for (fp = fopen("/etc/adjtime", "r");
74 fp && getline(&s, (void *)toybuf, fp)>0;
75 free(s), s = 0) TT.utc += !strncmp(s, "UTC", 3);
76 if (fp) fclose(fp);
77 }
78
79 if (!(toys.optflags&FLAG_t)) {
80 int w = toys.optflags & FLAG_w, flag = O_WRONLY*w;
81
82
83 if (!TT.f && (fd = open("/dev/rtc", flag)) == -1) {
84 dirtree_read("/sys/class/rtc", rtc_find);
85 if (!TT.f) TT.f = "/dev/misc/rtc";
86 }
87 if (fd == -1) fd = xopen(TT.f, flag);
88
89
90 if (!w) {
91 char *s = s;
92
93 xioctl(fd, RTC_RD_TIME, &tm);
94 if (TT.utc) s = xtzset("UTC0");
95 if ((time = mktime(&tm)) < 0) error_exit("mktime failed");
96 if (TT.utc) {
97 free(xtzset(s));
98 free(s);
99 }
100 }
101 }
102
103 if (toys.optflags & (FLAG_w|FLAG_t)) {
104 if (gettimeofday(&timeval, 0)) perror_exit("gettimeofday failed");
105 if (!(TT.utc ? gmtime_r : localtime_r)(&timeval.tv_sec, &tm))
106 error_exit(TT.utc ? "gmtime_r failed" : "localtime_r failed");
107 }
108
109 if (toys.optflags & FLAG_w) {
110
111
112
113 tm.tm_isdst = 0;
114 xioctl(fd, RTC_SET_TIME, &tm);
115 } else if (toys.optflags & FLAG_s) {
116 tzone.tz_minuteswest = timezone / 60 - 60 * daylight;
117 timeval.tv_sec = time;
118 timeval.tv_usec = 0;
119 } else if (toys.optflags & FLAG_t) {
120
121
122 tzone.tz_minuteswest = timezone / 60;
123 if (tm.tm_isdst) tzone.tz_minuteswest -= 60;
124 if (!TT.utc) timeval.tv_sec += tzone.tz_minuteswest * 60;
125 } else {
126 char *c = ctime(&time), *s = strrchr(c, '\n');
127
128 if (s) *s = '\0';
129
130 xprintf("%s 0.000000 seconds\n", c);
131 }
132 if (toys.optflags & (FLAG_t|FLAG_s)) {
133 tzone.tz_dsttime = 0;
134 if (settimeofday(&timeval, &tzone)) perror_exit("settimeofday failed");
135 }
136
137 if (fd != -1) close(fd);
138}
139