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