]>
Commit | Line | Data |
---|---|---|
1 | /* | |
2 | * SPDX-License-Identifier: GPL-2.0-or-later | |
3 | * | |
4 | * Since 7a3000f7ba548cf7d74ac77cc63fe8de228a669e (v2.30) hwclock is linked | |
5 | * with parse_date.y from gnullib. This gnulib code is distributed with GPLv3. | |
6 | * | |
7 | * | |
8 | * clock.c was written by Charles Hedrick, hedrick@cs.rutgers.edu, Apr 1992 | |
9 | * Modified for clock adjustments - Rob Hooft <hooft@chem.ruu.nl>, Nov 1992 | |
10 | * Improvements by Harald Koenig <koenig@nova.tat.physik.uni-tuebingen.de> | |
11 | * and Alan Modra <alan@spri.levels.unisa.edu.au>. | |
12 | * | |
13 | * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19. | |
14 | * The new program is called hwclock. New features: | |
15 | * | |
16 | * - You can set the hardware clock without also modifying the system | |
17 | * clock. | |
18 | * - You can read and set the clock with finer than 1 second precision. | |
19 | * - When you set the clock, hwclock automatically refigures the drift | |
20 | * rate, based on how far off the clock was before you set it. | |
21 | * | |
22 | * Reshuffled things, added sparc code, and re-added alpha stuff | |
23 | * by David Mosberger <davidm@azstarnet.com> | |
24 | * and Jay Estabrook <jestabro@amt.tay1.dec.com> | |
25 | * and Martin Ostermann <ost@coments.rwth-aachen.de>, aeb@cwi.nl, 990212. | |
26 | * | |
27 | * Fix for Award 2094 bug, Dave Coffin (dcoffin@shore.net) 11/12/98 | |
28 | * Change of local time handling, Stefan Ring <e9725446@stud3.tuwien.ac.at> | |
29 | * Change of adjtime handling, James P. Rutledge <ao112@rgfn.epcc.edu>. | |
30 | * | |
31 | * | |
32 | */ | |
33 | /* | |
34 | * Explanation of `adjusting' (Rob Hooft): | |
35 | * | |
36 | * The problem with my machine is that its CMOS clock is 10 seconds | |
37 | * per day slow. With this version of clock.c, and my '/etc/rc.local' | |
38 | * reading '/etc/clock -au' instead of '/etc/clock -u -s', this error | |
39 | * is automatically corrected at every boot. | |
40 | * | |
41 | * To do this job, the program reads and writes the file '/etc/adjtime' | |
42 | * to determine the correction, and to save its data. In this file are | |
43 | * three numbers: | |
44 | * | |
45 | * 1) the correction in seconds per day. (So if your clock runs 5 | |
46 | * seconds per day fast, the first number should read -5.0) | |
47 | * 2) the number of seconds since 1/1/1970 the last time the program | |
48 | * was used | |
49 | * 3) the remaining part of a second which was leftover after the last | |
50 | * adjustment | |
51 | * | |
52 | * Installation and use of this program: | |
53 | * | |
54 | * a) create a file '/etc/adjtime' containing as the first and only | |
55 | * line: '0.0 0 0.0' | |
56 | * b) run 'clock -au' or 'clock -a', depending on whether your cmos is | |
57 | * in universal or local time. This updates the second number. | |
58 | * c) set your system time using the 'date' command. | |
59 | * d) update your cmos time using 'clock -wu' or 'clock -w' | |
60 | * e) replace the first number in /etc/adjtime by your correction. | |
61 | * f) put the command 'clock -au' or 'clock -a' in your '/etc/rc.local' | |
62 | */ | |
63 | ||
64 | #include <errno.h> | |
65 | #include <getopt.h> | |
66 | #include <limits.h> | |
67 | #include <math.h> | |
68 | #include <stdio.h> | |
69 | #include <stdlib.h> | |
70 | #include <string.h> | |
71 | #include <sys/stat.h> | |
72 | #include <sys/time.h> | |
73 | #include <time.h> | |
74 | #include <unistd.h> | |
75 | ||
76 | #include "c.h" | |
77 | #include "closestream.h" | |
78 | #include "nls.h" | |
79 | #include "optutils.h" | |
80 | #include "pathnames.h" | |
81 | #include "hwclock.h" | |
82 | #include "timeutils.h" | |
83 | #include "env.h" | |
84 | #include "xalloc.h" | |
85 | #include "path.h" | |
86 | #include "strutils.h" | |
87 | ||
88 | #ifdef HAVE_LIBAUDIT | |
89 | #include <libaudit.h> | |
90 | static int hwaudit_fd = -1; | |
91 | #endif | |
92 | ||
93 | UL_DEBUG_DEFINE_MASK(hwclock); | |
94 | UL_DEBUG_DEFINE_MASKNAMES(hwclock) = UL_DEBUG_EMPTY_MASKNAMES; | |
95 | ||
96 | /* The struct that holds our hardware access routines */ | |
97 | static struct clock_ops *ur; | |
98 | ||
99 | /* Maximal clock adjustment in seconds per day. | |
100 | (adjtime() glibc call has 2145 seconds limit on i386, so it is good enough for us as well, | |
101 | 43219 is a maximal safe value preventing exact_adjustment overflow.) */ | |
102 | #define MAX_DRIFT 2145.0 | |
103 | ||
104 | struct adjtime { | |
105 | /* | |
106 | * This is information we keep in the adjtime file that tells us how | |
107 | * to do drift corrections. Elements are all straight from the | |
108 | * adjtime file, so see documentation of that file for details. | |
109 | * Exception is <dirty>, which is an indication that what's in this | |
110 | * structure is not what's in the disk file (because it has been | |
111 | * updated since read from the disk file). | |
112 | */ | |
113 | int dirty; | |
114 | /* line 1 */ | |
115 | double drift_factor; | |
116 | time_t last_adj_time; | |
117 | double not_adjusted; | |
118 | /* line 2 */ | |
119 | time_t last_calib_time; | |
120 | /* | |
121 | * The most recent time that we set the clock from an external | |
122 | * authority (as opposed to just doing a drift adjustment) | |
123 | */ | |
124 | /* line 3 */ | |
125 | enum a_local_utc { UTC = 0, LOCAL, UNKNOWN } local_utc; | |
126 | /* | |
127 | * To which time zone, local or UTC, we most recently set the | |
128 | * hardware clock. | |
129 | */ | |
130 | }; | |
131 | ||
132 | static void hwclock_init_debug(const char *str) | |
133 | { | |
134 | __UL_INIT_DEBUG_FROM_STRING(hwclock, HWCLOCK_DEBUG_, 0, str); | |
135 | ||
136 | DBG(INIT, ul_debug("hwclock debug mask: 0x%04x", hwclock_debug_mask)); | |
137 | DBG(INIT, ul_debug("hwclock version: %s", PACKAGE_STRING)); | |
138 | } | |
139 | ||
140 | /* FOR TESTING ONLY: inject random delays of up to 1000ms */ | |
141 | static void up_to_1000ms_sleep(void) | |
142 | { | |
143 | int usec = random() % 1000000; | |
144 | ||
145 | DBG(RANDOM_SLEEP, ul_debug("sleeping ~%d usec", usec)); | |
146 | xusleep(usec); | |
147 | } | |
148 | ||
149 | /* | |
150 | * time_t to timeval conversion. | |
151 | */ | |
152 | static struct timeval t2tv(time_t timet) | |
153 | { | |
154 | struct timeval rettimeval; | |
155 | ||
156 | rettimeval.tv_sec = timet; | |
157 | rettimeval.tv_usec = 0; | |
158 | return rettimeval; | |
159 | } | |
160 | ||
161 | /* | |
162 | * The difference in seconds between two times in "timeval" format. | |
163 | */ | |
164 | double time_diff(struct timeval subtrahend, struct timeval subtractor) | |
165 | { | |
166 | return (subtrahend.tv_sec - subtractor.tv_sec) | |
167 | + (subtrahend.tv_usec - subtractor.tv_usec) / 1E6; | |
168 | } | |
169 | ||
170 | /* | |
171 | * The time, in "timeval" format, which is <increment> seconds after the | |
172 | * time <addend>. Of course, <increment> may be negative. | |
173 | */ | |
174 | static struct timeval time_inc(struct timeval addend, double increment) | |
175 | { | |
176 | struct timeval newtime; | |
177 | ||
178 | newtime.tv_sec = addend.tv_sec + (int)increment; | |
179 | newtime.tv_usec = addend.tv_usec + (increment - (int)increment) * 1E6; | |
180 | ||
181 | /* | |
182 | * Now adjust it so that the microsecond value is between 0 and 1 | |
183 | * million. | |
184 | */ | |
185 | if (newtime.tv_usec < 0) { | |
186 | newtime.tv_usec += 1E6; | |
187 | newtime.tv_sec -= 1; | |
188 | } else if (newtime.tv_usec >= 1E6) { | |
189 | newtime.tv_usec -= 1E6; | |
190 | newtime.tv_sec += 1; | |
191 | } | |
192 | return newtime; | |
193 | } | |
194 | ||
195 | static int | |
196 | hw_clock_is_utc(const struct hwclock_control *ctl, | |
197 | const struct adjtime adjtime) | |
198 | { | |
199 | int ret; | |
200 | ||
201 | if (ctl->utc) | |
202 | ret = 1; /* --utc explicitly given on command line */ | |
203 | else if (ctl->local_opt) | |
204 | ret = 0; /* --localtime explicitly given */ | |
205 | else | |
206 | /* get info from adjtime file - default is UTC */ | |
207 | ret = (adjtime.local_utc != LOCAL); | |
208 | if (ctl->verbose) | |
209 | printf(_("Assuming hardware clock is kept in %s time.\n"), | |
210 | ret ? _("UTC") : _("local")); | |
211 | return ret; | |
212 | } | |
213 | ||
214 | /* | |
215 | * Read the adjustment parameters out of the /etc/adjtime file. | |
216 | * | |
217 | * Return them as the adjtime structure <*adjtime_p>. Its defaults are | |
218 | * initialized in main(). | |
219 | */ | |
220 | static int read_adjtime(const struct hwclock_control *ctl, | |
221 | struct adjtime *adjtime_p) | |
222 | { | |
223 | FILE *adjfile; | |
224 | char line1[81]; /* String: first line of adjtime file */ | |
225 | char line2[81]; /* String: second line of adjtime file */ | |
226 | char line3[81]; /* String: third line of adjtime file */ | |
227 | ||
228 | if (access(ctl->adj_file_name, R_OK) != 0) | |
229 | return EXIT_SUCCESS; | |
230 | ||
231 | adjfile = fopen(ctl->adj_file_name, "r"); /* open file for reading */ | |
232 | if (adjfile == NULL) { | |
233 | warn(_("cannot open %s"), ctl->adj_file_name); | |
234 | return EXIT_FAILURE; | |
235 | } | |
236 | ||
237 | if (!fgets(line1, sizeof(line1), adjfile)) | |
238 | line1[0] = '\0'; /* In case fgets fails */ | |
239 | if (!fgets(line2, sizeof(line2), adjfile)) | |
240 | line2[0] = '\0'; /* In case fgets fails */ | |
241 | if (!fgets(line3, sizeof(line3), adjfile)) | |
242 | line3[0] = '\0'; /* In case fgets fails */ | |
243 | ||
244 | fclose(adjfile); | |
245 | ||
246 | sscanf(line1, "%lf %ld %lf", | |
247 | &adjtime_p->drift_factor, | |
248 | &adjtime_p->last_adj_time, | |
249 | &adjtime_p->not_adjusted); | |
250 | ||
251 | sscanf(line2, "%ld", &adjtime_p->last_calib_time); | |
252 | ||
253 | if (!strcmp(line3, "UTC\n")) { | |
254 | adjtime_p->local_utc = UTC; | |
255 | } else if (!strcmp(line3, "LOCAL\n")) { | |
256 | adjtime_p->local_utc = LOCAL; | |
257 | } else { | |
258 | adjtime_p->local_utc = UNKNOWN; | |
259 | if (line3[0]) { | |
260 | warnx(_("Warning: unrecognized third line in adjtime file\n" | |
261 | "(Expected: `UTC' or `LOCAL' or nothing.)")); | |
262 | } | |
263 | } | |
264 | ||
265 | if (ctl->verbose) { | |
266 | printf(_ | |
267 | ("Last drift adjustment done at %ld seconds after 1969\n"), | |
268 | (long)adjtime_p->last_adj_time); | |
269 | printf(_("Last calibration done at %ld seconds after 1969\n"), | |
270 | (long)adjtime_p->last_calib_time); | |
271 | printf(_("Hardware clock is on %s time\n"), | |
272 | (adjtime_p->local_utc == | |
273 | LOCAL) ? _("local") : (adjtime_p->local_utc == | |
274 | UTC) ? _("UTC") : _("unknown")); | |
275 | } | |
276 | ||
277 | return EXIT_SUCCESS; | |
278 | } | |
279 | ||
280 | /* | |
281 | * Wait until the falling edge of the Hardware Clock's update flag so that | |
282 | * any time that is read from the clock immediately after we return will be | |
283 | * exact. | |
284 | * | |
285 | * The clock only has 1 second precision, so it gives the exact time only | |
286 | * once per second, right on the falling edge of the update flag. | |
287 | * | |
288 | * We wait (up to one second) either blocked waiting for an rtc device or in | |
289 | * a CPU spin loop. The former is probably not very accurate. | |
290 | * | |
291 | * Return 0 if it worked, nonzero if it didn't. | |
292 | */ | |
293 | static int synchronize_to_clock_tick(const struct hwclock_control *ctl) | |
294 | { | |
295 | int rc; | |
296 | ||
297 | if (ctl->verbose) | |
298 | printf(_("Waiting for clock tick...\n")); | |
299 | ||
300 | rc = ur->synchronize_to_clock_tick(ctl); | |
301 | ||
302 | if (ctl->verbose) { | |
303 | if (rc) | |
304 | printf(_("...synchronization failed\n")); | |
305 | else | |
306 | printf(_("...got clock tick\n")); | |
307 | } | |
308 | ||
309 | return rc; | |
310 | } | |
311 | ||
312 | /* | |
313 | * Convert a time in broken down format (hours, minutes, etc.) into standard | |
314 | * unix time (seconds into epoch). Return it as *systime_p. | |
315 | * | |
316 | * The broken down time is argument <tm>. This broken down time is either | |
317 | * in local time zone or UTC, depending on value of logical argument | |
318 | * "universal". True means it is in UTC. | |
319 | * | |
320 | * If the argument contains values that do not constitute a valid time, and | |
321 | * mktime() recognizes this, return *valid_p == false and *systime_p | |
322 | * undefined. However, mktime() sometimes goes ahead and computes a | |
323 | * fictional time "as if" the input values were valid, e.g. if they indicate | |
324 | * the 31st day of April, mktime() may compute the time of May 1. In such a | |
325 | * case, we return the same fictional value mktime() does as *systime_p and | |
326 | * return *valid_p == true. | |
327 | */ | |
328 | static int | |
329 | mktime_tz(const struct hwclock_control *ctl, struct tm tm, | |
330 | time_t *systime_p) | |
331 | { | |
332 | int valid; | |
333 | ||
334 | if (ctl->universal) | |
335 | *systime_p = timegm(&tm); | |
336 | else | |
337 | *systime_p = mktime(&tm); | |
338 | if (*systime_p == -1) { | |
339 | /* | |
340 | * This apparently (not specified in mktime() documentation) | |
341 | * means the 'tm' structure does not contain valid values | |
342 | * (however, not containing valid values does _not_ imply | |
343 | * mktime() returns -1). | |
344 | */ | |
345 | valid = 0; | |
346 | if (ctl->verbose) | |
347 | printf(_("Invalid values in hardware clock: " | |
348 | "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"), | |
349 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, | |
350 | tm.tm_hour, tm.tm_min, tm.tm_sec); | |
351 | } else { | |
352 | valid = 1; | |
353 | if (ctl->verbose) | |
354 | printf(_ | |
355 | ("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = " | |
356 | "%ld seconds since 1969\n"), tm.tm_year + 1900, | |
357 | tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, | |
358 | tm.tm_sec, (long)*systime_p); | |
359 | } | |
360 | return valid; | |
361 | } | |
362 | ||
363 | /* | |
364 | * Read the hardware clock and return the current time via <tm> argument. | |
365 | * | |
366 | * Use the method indicated by <method> argument to access the hardware | |
367 | * clock. | |
368 | */ | |
369 | static int | |
370 | read_hardware_clock(const struct hwclock_control *ctl, | |
371 | int *valid_p, time_t *systime_p) | |
372 | { | |
373 | struct tm tm; | |
374 | int err; | |
375 | ||
376 | err = ur->read_hardware_clock(ctl, &tm); | |
377 | if (err) | |
378 | return err; | |
379 | ||
380 | if (ctl->verbose) | |
381 | printf(_ | |
382 | ("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"), | |
383 | tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, | |
384 | tm.tm_min, tm.tm_sec); | |
385 | *valid_p = mktime_tz(ctl, tm, systime_p); | |
386 | ||
387 | return 0; | |
388 | } | |
389 | ||
390 | /* | |
391 | * Set the Hardware Clock to the time <newtime>, in local time zone or UTC, | |
392 | * according to <universal>. | |
393 | */ | |
394 | static void | |
395 | set_hardware_clock(const struct hwclock_control *ctl, const time_t newtime) | |
396 | { | |
397 | struct tm new_broken_time; | |
398 | /* | |
399 | * Time to which we will set Hardware Clock, in broken down format, | |
400 | * in the time zone of caller's choice | |
401 | */ | |
402 | ||
403 | if (ctl->universal) | |
404 | gmtime_r(&newtime, &new_broken_time); | |
405 | else | |
406 | localtime_r(&newtime, &new_broken_time); | |
407 | ||
408 | if (ctl->verbose) | |
409 | printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d " | |
410 | "= %ld seconds since 1969\n"), | |
411 | new_broken_time.tm_hour, new_broken_time.tm_min, | |
412 | new_broken_time.tm_sec, (long)newtime); | |
413 | ||
414 | if (!ctl->testing) | |
415 | ur->set_hardware_clock(ctl, &new_broken_time); | |
416 | } | |
417 | ||
418 | static double | |
419 | get_hardware_delay(const struct hwclock_control *ctl) | |
420 | { | |
421 | const char *devpath, *rtcname; | |
422 | char name[128 + 1]; | |
423 | struct path_cxt *pc; | |
424 | int rc; | |
425 | ||
426 | devpath = ur->get_device_path(); | |
427 | if (!devpath) | |
428 | goto unknown; | |
429 | ||
430 | rtcname = strrchr(devpath, '/'); | |
431 | if (!rtcname || !*(rtcname + 1)) | |
432 | goto unknown; | |
433 | rtcname++; | |
434 | ||
435 | pc = ul_new_path("/sys/class/rtc/%s", rtcname); | |
436 | if (!pc) | |
437 | goto unknown; | |
438 | rc = ul_path_scanf(pc, "name", "%128[^\n ]", &name); | |
439 | ul_unref_path(pc); | |
440 | ||
441 | if (rc != 1 || !*name) | |
442 | goto unknown; | |
443 | ||
444 | if (ctl->verbose) | |
445 | printf(_("RTC type: '%s'\n"), name); | |
446 | ||
447 | /* MC146818A-compatible (x86) */ | |
448 | if (strcmp(name, "rtc_cmos") == 0) | |
449 | return 0.5; | |
450 | ||
451 | /* Another HW */ | |
452 | return 0; | |
453 | unknown: | |
454 | /* Let's be backwardly compatible */ | |
455 | return 0.5; | |
456 | } | |
457 | ||
458 | ||
459 | /* | |
460 | * Set the Hardware Clock to the time "sethwtime", in local time zone or | |
461 | * UTC, according to "universal". | |
462 | * | |
463 | * Wait for a fraction of a second so that "sethwtime" is the value of the | |
464 | * Hardware Clock as of system time "refsystime", which is in the past. For | |
465 | * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and | |
466 | * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2 | |
467 | * seconds since "refsystime") and then set the Hardware Clock to 14:03:07, | |
468 | * thus getting a precise and retroactive setting of the clock. The .5 delay is | |
469 | * default on x86, see --delay and get_hardware_delay(). | |
470 | * | |
471 | * (Don't be confused by the fact that the system clock and the Hardware | |
472 | * Clock differ by two hours in the above example. That's just to remind you | |
473 | * that there are two independent time scales here). | |
474 | * | |
475 | * This function ought to be able to accept set times as fractional times. | |
476 | * Idea for future enhancement. | |
477 | */ | |
478 | static void | |
479 | set_hardware_clock_exact(const struct hwclock_control *ctl, | |
480 | const time_t sethwtime, | |
481 | const struct timeval refsystime) | |
482 | { | |
483 | /* | |
484 | * The Hardware Clock can only be set to any integer time plus one | |
485 | * half second. The integer time is required because there is no | |
486 | * interface to set or get a fractional second. The additional half | |
487 | * second is because the Hardware Clock updates to the following | |
488 | * second precisely 500 ms (not 1 second!) after you release the | |
489 | * divider reset (after setting the new time) - see description of | |
490 | * DV2, DV1, DV0 in Register A in the MC146818A data sheet (and note | |
491 | * that although that document doesn't say so, real-world code seems | |
492 | * to expect that the SET bit in Register B functions the same way). | |
493 | * That means that, e.g., when you set the clock to 1:02:03, it | |
494 | * effectively really sets it to 1:02:03.5, because it will update to | |
495 | * 1:02:04 only half a second later. Our caller passes the desired | |
496 | * integer Hardware Clock time in sethwtime, and the corresponding | |
497 | * system time (which may have a fractional part, and which may or may | |
498 | * not be the same!) in refsystime. In an ideal situation, we would | |
499 | * then apply sethwtime to the Hardware Clock at refsystime+500ms, so | |
500 | * that when the Hardware Clock ticks forward to sethwtime+1s half a | |
501 | * second later at refsystime+1000ms, everything is in sync. So we | |
502 | * spin, waiting for gettimeofday() to return a time at or after that | |
503 | * time (refsystime+500ms) up to a tolerance value, initially 1ms. If | |
504 | * we miss that time due to being preempted for some other process, | |
505 | * then we increase the margin a little bit (initially 1ms, doubling | |
506 | * each time), add 1 second (or more, if needed to get a time that is | |
507 | * in the future) to both the time for which we are waiting and the | |
508 | * time that we will apply to the Hardware Clock, and start waiting | |
509 | * again. | |
510 | * | |
511 | * For example, the caller requests that we set the Hardware Clock to | |
512 | * 1:02:03, with reference time (current system time) = 6:07:08.250. | |
513 | * We want the Hardware Clock to update to 1:02:04 at 6:07:09.250 on | |
514 | * the system clock, and the first such update will occur 0.500 | |
515 | * seconds after we write to the Hardware Clock, so we spin until the | |
516 | * system clock reads 6:07:08.750. If we get there, great, but let's | |
517 | * imagine the system is so heavily loaded that our process is | |
518 | * preempted and by the time we get to run again, the system clock | |
519 | * reads 6:07:11.990. We now want to wait until the next xx:xx:xx.750 | |
520 | * time, which is 6:07:12.750 (4.5 seconds after the reference time), | |
521 | * at which point we will set the Hardware Clock to 1:02:07 (4 seconds | |
522 | * after the originally requested time). If we do that successfully, | |
523 | * then at 6:07:13.250 (5 seconds after the reference time), the | |
524 | * Hardware Clock will update to 1:02:08 (5 seconds after the | |
525 | * originally requested time), and all is well thereafter. | |
526 | */ | |
527 | ||
528 | time_t newhwtime = sethwtime; | |
529 | double target_time_tolerance_secs = 0.001; /* initial value */ | |
530 | double tolerance_incr_secs = 0.001; /* initial value */ | |
531 | double delay; | |
532 | struct timeval rtc_set_delay_tv; | |
533 | ||
534 | struct timeval targetsystime; | |
535 | struct timeval nowsystime; | |
536 | struct timeval prevsystime = refsystime; | |
537 | double deltavstarget; | |
538 | ||
539 | if (ctl->rtc_delay != -1.0) /* --delay specified */ | |
540 | delay = ctl->rtc_delay; | |
541 | else | |
542 | delay = get_hardware_delay(ctl); | |
543 | ||
544 | if (ctl->verbose) | |
545 | printf(_("Using delay: %.6f seconds\n"), delay); | |
546 | ||
547 | rtc_set_delay_tv.tv_sec = 0; | |
548 | rtc_set_delay_tv.tv_usec = delay * 1E6; | |
549 | ||
550 | timeradd(&refsystime, &rtc_set_delay_tv, &targetsystime); | |
551 | ||
552 | while (1) { | |
553 | double ticksize; | |
554 | ||
555 | ON_DBG(RANDOM_SLEEP, up_to_1000ms_sleep()); | |
556 | ||
557 | gettimeofday(&nowsystime, NULL); | |
558 | deltavstarget = time_diff(nowsystime, targetsystime); | |
559 | ticksize = time_diff(nowsystime, prevsystime); | |
560 | prevsystime = nowsystime; | |
561 | ||
562 | if (ticksize < 0) { | |
563 | if (ctl->verbose) | |
564 | printf(_("time jumped backward %.6f seconds " | |
565 | "to %ld.%06ld - retargeting\n"), | |
566 | ticksize, nowsystime.tv_sec, | |
567 | nowsystime.tv_usec); | |
568 | /* The retarget is handled at the end of the loop. */ | |
569 | } else if (deltavstarget < 0) { | |
570 | /* deltavstarget < 0 if current time < target time */ | |
571 | DBG(DELTA_VS_TARGET, | |
572 | ul_debug("%ld.%06ld < %ld.%06ld (%.6f)", | |
573 | nowsystime.tv_sec, nowsystime.tv_usec, | |
574 | targetsystime.tv_sec, | |
575 | targetsystime.tv_usec, deltavstarget)); | |
576 | continue; /* not there yet - keep spinning */ | |
577 | } else if (deltavstarget <= target_time_tolerance_secs) { | |
578 | /* Close enough to the target time; done waiting. */ | |
579 | break; | |
580 | } else /* (deltavstarget > target_time_tolerance_secs) */ { | |
581 | /* | |
582 | * We missed our window. Increase the tolerance and | |
583 | * aim for the next opportunity. | |
584 | */ | |
585 | if (ctl->verbose) | |
586 | printf(_("missed it - %ld.%06ld is too far " | |
587 | "past %ld.%06ld (%.6f > %.6f)\n"), | |
588 | nowsystime.tv_sec, | |
589 | nowsystime.tv_usec, | |
590 | targetsystime.tv_sec, | |
591 | targetsystime.tv_usec, | |
592 | deltavstarget, | |
593 | target_time_tolerance_secs); | |
594 | target_time_tolerance_secs += tolerance_incr_secs; | |
595 | tolerance_incr_secs *= 2; | |
596 | } | |
597 | ||
598 | /* | |
599 | * Aim for the same offset (tv_usec) within the second in | |
600 | * either the current second (if that offset hasn't arrived | |
601 | * yet), or the next second. | |
602 | */ | |
603 | if (nowsystime.tv_usec < targetsystime.tv_usec) | |
604 | targetsystime.tv_sec = nowsystime.tv_sec; | |
605 | else | |
606 | targetsystime.tv_sec = nowsystime.tv_sec + 1; | |
607 | } | |
608 | ||
609 | newhwtime = sethwtime | |
610 | + (int)(time_diff(nowsystime, refsystime) | |
611 | - delay /* don't count this */ | |
612 | + 0.5 /* for rounding */); | |
613 | if (ctl->verbose) | |
614 | printf(_("%ld.%06ld is close enough to %ld.%06ld (%.6f < %.6f)\n" | |
615 | "Set RTC to %ld (%ld + %d; refsystime = %ld.%06ld)\n"), | |
616 | nowsystime.tv_sec, nowsystime.tv_usec, | |
617 | targetsystime.tv_sec, targetsystime.tv_usec, | |
618 | deltavstarget, target_time_tolerance_secs, | |
619 | newhwtime, sethwtime, | |
620 | (int)(newhwtime - sethwtime), | |
621 | refsystime.tv_sec, refsystime.tv_usec); | |
622 | ||
623 | set_hardware_clock(ctl, newhwtime); | |
624 | } | |
625 | ||
626 | static int | |
627 | display_time(struct timeval hwctime) | |
628 | { | |
629 | char buf[ISO_BUFSIZ]; | |
630 | ||
631 | if (strtimeval_iso(&hwctime, ISO_TIMESTAMP_DOT, buf, sizeof(buf))) | |
632 | return EXIT_FAILURE; | |
633 | ||
634 | printf("%s\n", buf); | |
635 | return EXIT_SUCCESS; | |
636 | } | |
637 | ||
638 | /* | |
639 | * Adjusts System time, sets the kernel's timezone and RTC timescale. | |
640 | * | |
641 | * The kernel warp_clock function adjusts the System time according to the | |
642 | * tz.tz_minuteswest argument and sets PCIL (see below). At boot settimeofday(2) | |
643 | * has one-shot access to this function as shown in the table below. | |
644 | * | |
645 | * +-------------------------------------------------------------------+ | |
646 | * | settimeofday(tv, tz) | | |
647 | * |-------------------------------------------------------------------| | |
648 | * | Arguments | System Time | PCIL | | warp_clock | | |
649 | * | tv | tz | set | warped | set | firsttime | locked | | |
650 | * |---------|---------|---------------|------|-----------|------------| | |
651 | * | pointer | NULL | yes | no | no | 1 | no | | |
652 | * | pointer | pointer | yes | no | no | 0 | yes | | |
653 | * | NULL | ptr2utc | no | no | no | 0 | yes | | |
654 | * | NULL | pointer | no | yes | yes | 0 | yes | | |
655 | * +-------------------------------------------------------------------+ | |
656 | * ptr2utc: tz.tz_minuteswest is zero (UTC). | |
657 | * PCIL: persistent_clock_is_local, sets the "11 minute mode" timescale. | |
658 | * firsttime: locks the warp_clock function (initialized to 1 at boot). | |
659 | * | |
660 | * +---------------------------------------------------------------------------+ | |
661 | * | op | RTC scale | settimeofday calls | | |
662 | * |---------|-----------|-----------------------------------------------------| | |
663 | * | systz | Local | 1) warps system time*, sets PCIL* and kernel tz | | |
664 | * | systz | UTC | 1st) locks warp_clock* 2nd) sets kernel tz | | |
665 | * | hctosys | Local | 1st) sets PCIL* 2nd) sets system time and kernel tz | | |
666 | * | hctosys | UTC | 1) sets system time and kernel tz | | |
667 | * +---------------------------------------------------------------------------+ | |
668 | * * only on first call after boot | |
669 | */ | |
670 | static int | |
671 | set_system_clock(const struct hwclock_control *ctl, | |
672 | const struct timeval newtime) | |
673 | { | |
674 | struct tm broken; | |
675 | int minuteswest; | |
676 | int rc = 0; | |
677 | const struct timezone tz_utc = { 0 }; | |
678 | ||
679 | localtime_r(&newtime.tv_sec, &broken); | |
680 | minuteswest = -get_gmtoff(&broken) / 60; | |
681 | ||
682 | if (ctl->verbose) { | |
683 | if (ctl->hctosys && !ctl->universal) | |
684 | printf(_("Calling settimeofday(NULL, %d) to set " | |
685 | "persistent_clock_is_local.\n"), minuteswest); | |
686 | if (ctl->systz && ctl->universal) | |
687 | puts(_("Calling settimeofday(NULL, 0) " | |
688 | "to lock the warp function.")); | |
689 | if (ctl->hctosys) | |
690 | printf(_("Calling settimeofday(%ld.%06ld, %d)\n"), | |
691 | newtime.tv_sec, newtime.tv_usec, minuteswest); | |
692 | else { | |
693 | printf(_("Calling settimeofday(NULL, %d) "), minuteswest); | |
694 | if (ctl->universal) | |
695 | puts(_("to set the kernel timezone.")); | |
696 | else | |
697 | puts(_("to warp System time.")); | |
698 | } | |
699 | } | |
700 | ||
701 | if (!ctl->testing) { | |
702 | const struct timezone tz = { minuteswest }; | |
703 | ||
704 | if (ctl->hctosys && !ctl->universal) /* set PCIL */ | |
705 | rc = settimeofday(NULL, &tz); | |
706 | if (ctl->systz && ctl->universal) /* lock warp_clock */ | |
707 | rc = settimeofday(NULL, &tz_utc); | |
708 | if (!rc && ctl->hctosys) | |
709 | rc = settimeofday(&newtime, &tz); | |
710 | else if (!rc) | |
711 | rc = settimeofday(NULL, &tz); | |
712 | ||
713 | if (rc) { | |
714 | warn(_("settimeofday() failed")); | |
715 | return EXIT_FAILURE; | |
716 | } | |
717 | } | |
718 | return EXIT_SUCCESS; | |
719 | } | |
720 | ||
721 | /* | |
722 | * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p> | |
723 | * to facilitate future drift calculations based on this set point. | |
724 | * | |
725 | * With the --update-drift option: | |
726 | * Update the drift factor in <*adjtime_p> based on the fact that the | |
727 | * Hardware Clock was just calibrated to <nowtime> and before that was | |
728 | * set to the <hclocktime> time scale. | |
729 | */ | |
730 | static void | |
731 | adjust_drift_factor(const struct hwclock_control *ctl, | |
732 | struct adjtime *adjtime_p, | |
733 | const struct timeval nowtime, | |
734 | const struct timeval hclocktime) | |
735 | { | |
736 | if (!ctl->update) { | |
737 | if (ctl->verbose) | |
738 | printf(_("Not adjusting drift factor because the " | |
739 | "--update-drift option was not used.\n")); | |
740 | } else if (adjtime_p->last_calib_time == 0) { | |
741 | if (ctl->verbose) | |
742 | printf(_("Not adjusting drift factor because last " | |
743 | "calibration time is zero,\n" | |
744 | "so history is bad and calibration startover " | |
745 | "is necessary.\n")); | |
746 | } else if ((hclocktime.tv_sec - adjtime_p->last_calib_time) < 4 * 60 * 60) { | |
747 | if (ctl->verbose) | |
748 | printf(_("Not adjusting drift factor because it has " | |
749 | "been less than four hours since the last " | |
750 | "calibration.\n")); | |
751 | } else { | |
752 | /* | |
753 | * At adjustment time we drift correct the hardware clock | |
754 | * according to the contents of the adjtime file and refresh | |
755 | * its last adjusted timestamp. | |
756 | * | |
757 | * At calibration time we set the Hardware Clock and refresh | |
758 | * both timestamps in <*adjtime_p>. | |
759 | * | |
760 | * Here, with the --update-drift option, we also update the | |
761 | * drift factor in <*adjtime_p>. | |
762 | * | |
763 | * Let us do computation in doubles. (Floats almost suffice, | |
764 | * but 195 days + 1 second equals 195 days in floats.) | |
765 | */ | |
766 | const double sec_per_day = 24.0 * 60.0 * 60.0; | |
767 | double factor_adjust; | |
768 | double drift_factor; | |
769 | struct timeval last_calib; | |
770 | ||
771 | last_calib = t2tv(adjtime_p->last_calib_time); | |
772 | /* | |
773 | * Correction to apply to the current drift factor. | |
774 | * | |
775 | * Simplified: uncorrected_drift / days_since_calibration. | |
776 | * | |
777 | * hclocktime is fully corrected with the current drift factor. | |
778 | * Its difference from nowtime is the missed drift correction. | |
779 | */ | |
780 | factor_adjust = time_diff(nowtime, hclocktime) / | |
781 | (time_diff(nowtime, last_calib) / sec_per_day); | |
782 | ||
783 | drift_factor = adjtime_p->drift_factor + factor_adjust; | |
784 | if (fabs(drift_factor) > MAX_DRIFT) { | |
785 | if (ctl->verbose) | |
786 | printf(_("Clock drift factor was calculated as " | |
787 | "%f seconds/day.\n" | |
788 | "It is far too much. Resetting to zero.\n"), | |
789 | drift_factor); | |
790 | drift_factor = 0; | |
791 | } else { | |
792 | if (ctl->verbose) | |
793 | printf(_("Clock drifted %f seconds in the past " | |
794 | "%f seconds\nin spite of a drift factor of " | |
795 | "%f seconds/day.\n" | |
796 | "Adjusting drift factor by %f seconds/day\n"), | |
797 | time_diff(nowtime, hclocktime), | |
798 | time_diff(nowtime, last_calib), | |
799 | adjtime_p->drift_factor, factor_adjust); | |
800 | } | |
801 | ||
802 | adjtime_p->drift_factor = drift_factor; | |
803 | } | |
804 | adjtime_p->last_calib_time = nowtime.tv_sec; | |
805 | ||
806 | adjtime_p->last_adj_time = nowtime.tv_sec; | |
807 | ||
808 | adjtime_p->not_adjusted = 0; | |
809 | ||
810 | adjtime_p->dirty = 1; | |
811 | } | |
812 | ||
813 | /* | |
814 | * Calculate the drift correction currently needed for the | |
815 | * Hardware Clock based on the last time it was adjusted, | |
816 | * and the current drift factor, as stored in the adjtime file. | |
817 | * | |
818 | * The total drift adjustment needed is stored at tdrift_p. | |
819 | * | |
820 | */ | |
821 | static void | |
822 | calculate_adjustment(const struct hwclock_control *ctl, | |
823 | const double factor, | |
824 | const time_t last_time, | |
825 | const double not_adjusted, | |
826 | const time_t systime, struct timeval *tdrift_p) | |
827 | { | |
828 | double exact_adjustment; | |
829 | ||
830 | exact_adjustment = | |
831 | ((double)(systime - last_time)) * factor / (24 * 60 * 60) | |
832 | + not_adjusted; | |
833 | tdrift_p->tv_sec = (time_t) floor(exact_adjustment); | |
834 | tdrift_p->tv_usec = (exact_adjustment - | |
835 | (double)tdrift_p->tv_sec) * 1E6; | |
836 | if (ctl->verbose) { | |
837 | printf(P_("Time since last adjustment is %ld second\n", | |
838 | "Time since last adjustment is %ld seconds\n", | |
839 | (systime - last_time)), | |
840 | (systime - last_time)); | |
841 | printf(_("Calculated Hardware Clock drift is %ld.%06ld seconds\n"), | |
842 | tdrift_p->tv_sec, tdrift_p->tv_usec); | |
843 | } | |
844 | } | |
845 | ||
846 | /* | |
847 | * Write the contents of the <adjtime> structure to its disk file. | |
848 | * | |
849 | * But if the contents are clean (unchanged since read from disk), don't | |
850 | * bother. | |
851 | */ | |
852 | static int save_adjtime(const struct hwclock_control *ctl, | |
853 | const struct adjtime *adjtime) | |
854 | { | |
855 | char *content; /* Stuff to write to disk file */ | |
856 | FILE *fp; | |
857 | ||
858 | xasprintf(&content, "%f %ld %f\n%ld\n%s\n", | |
859 | adjtime->drift_factor, | |
860 | adjtime->last_adj_time, | |
861 | adjtime->not_adjusted, | |
862 | adjtime->last_calib_time, | |
863 | (adjtime->local_utc == LOCAL) ? "LOCAL" : "UTC"); | |
864 | ||
865 | if (ctl->verbose){ | |
866 | printf(_("New %s data:\n%s"), | |
867 | ctl->adj_file_name, content); | |
868 | } | |
869 | ||
870 | if (!ctl->testing) { | |
871 | fp = fopen(ctl->adj_file_name, "w"); | |
872 | if (fp == NULL) { | |
873 | warn(_("cannot open %s"), ctl->adj_file_name); | |
874 | return EXIT_FAILURE; | |
875 | } else if (fputs(content, fp) < 0 || close_stream(fp) != 0) { | |
876 | warn(_("cannot update %s"), ctl->adj_file_name); | |
877 | return EXIT_FAILURE; | |
878 | } | |
879 | } | |
880 | return EXIT_SUCCESS; | |
881 | } | |
882 | ||
883 | /* | |
884 | * Do the adjustment requested, by 1) setting the Hardware Clock (if | |
885 | * necessary), and 2) updating the last-adjusted time in the adjtime | |
886 | * structure. | |
887 | * | |
888 | * Do not update anything if the Hardware Clock does not currently present a | |
889 | * valid time. | |
890 | * | |
891 | * <hclocktime> is the drift corrected time read from the Hardware Clock. | |
892 | * | |
893 | * <read_time> was the system time when the <hclocktime> was read, which due | |
894 | * to computational delay could be a short time ago. It is used to define a | |
895 | * trigger point for setting the Hardware Clock. The fractional part of the | |
896 | * Hardware clock set time is subtracted from read_time to 'refer back', or | |
897 | * delay, the trigger point. Fractional parts must be accounted for in this | |
898 | * way, because the Hardware Clock can only be set to a whole second. | |
899 | * | |
900 | * <universal>: the Hardware Clock is kept in UTC. | |
901 | * | |
902 | * <testing>: We are running in test mode (no updating of clock). | |
903 | * | |
904 | */ | |
905 | static void | |
906 | do_adjustment(const struct hwclock_control *ctl, struct adjtime *adjtime_p, | |
907 | const struct timeval hclocktime, | |
908 | const struct timeval read_time) | |
909 | { | |
910 | if (adjtime_p->last_adj_time == 0) { | |
911 | if (ctl->verbose) | |
912 | printf(_("Not setting clock because last adjustment time is zero, " | |
913 | "so history is bad.\n")); | |
914 | } else if (fabs(adjtime_p->drift_factor) > MAX_DRIFT) { | |
915 | if (ctl->verbose) | |
916 | printf(_("Not setting clock because drift factor %f is far too high.\n"), | |
917 | adjtime_p->drift_factor); | |
918 | } else { | |
919 | set_hardware_clock_exact(ctl, hclocktime.tv_sec, | |
920 | time_inc(read_time, | |
921 | -(hclocktime.tv_usec / 1E6))); | |
922 | adjtime_p->last_adj_time = hclocktime.tv_sec; | |
923 | adjtime_p->not_adjusted = 0; | |
924 | adjtime_p->dirty = 1; | |
925 | } | |
926 | } | |
927 | ||
928 | static void determine_clock_access_method(const struct hwclock_control *ctl) | |
929 | { | |
930 | ur = NULL; | |
931 | ||
932 | #ifdef USE_HWCLOCK_CMOS | |
933 | if (ctl->directisa) | |
934 | ur = probe_for_cmos_clock(); | |
935 | #endif | |
936 | #ifdef __linux__ | |
937 | if (!ur) | |
938 | ur = probe_for_rtc_clock(ctl); | |
939 | #endif | |
940 | if (ur) { | |
941 | if (ctl->verbose) | |
942 | puts(ur->interface_name); | |
943 | ||
944 | } else { | |
945 | if (ctl->verbose) | |
946 | printf(_("No usable clock interface found.\n")); | |
947 | ||
948 | warnx(_("Cannot access the Hardware Clock via " | |
949 | "any known method.")); | |
950 | ||
951 | if (!ctl->verbose) | |
952 | warnx(_("Use the --verbose option to see the " | |
953 | "details of our search for an access " | |
954 | "method.")); | |
955 | hwclock_exit(ctl, EXIT_FAILURE); | |
956 | } | |
957 | } | |
958 | ||
959 | /* Do all the normal work of hwclock - read, set clock, etc. */ | |
960 | static int | |
961 | manipulate_clock(const struct hwclock_control *ctl, const time_t set_time, | |
962 | const struct timeval startup_time, struct adjtime *adjtime) | |
963 | { | |
964 | /* The time at which we read the Hardware Clock */ | |
965 | struct timeval read_time = { 0 }; | |
966 | /* | |
967 | * The Hardware Clock gives us a valid time, or at | |
968 | * least something close enough to fool mktime(). | |
969 | */ | |
970 | int hclock_valid = 0; | |
971 | /* | |
972 | * Tick synchronized time read from the Hardware Clock and | |
973 | * then drift corrected for all operations except --show. | |
974 | */ | |
975 | struct timeval hclocktime = { 0 }; | |
976 | /* | |
977 | * hclocktime correlated to startup_time. That is, what drift | |
978 | * corrected Hardware Clock time would have been at start up. | |
979 | */ | |
980 | struct timeval startup_hclocktime = { 0 }; | |
981 | /* Total Hardware Clock drift correction needed. */ | |
982 | struct timeval tdrift = { 0 }; | |
983 | ||
984 | if ((ctl->set || ctl->systohc || ctl->adjust) && | |
985 | (adjtime->local_utc == UTC) != ctl->universal) { | |
986 | adjtime->local_utc = ctl->universal ? UTC : LOCAL; | |
987 | adjtime->dirty = 1; | |
988 | } | |
989 | /* | |
990 | * Negate the drift correction, because we want to 'predict' a | |
991 | * Hardware Clock time that includes drift. | |
992 | */ | |
993 | if (ctl->predict) { | |
994 | hclocktime = t2tv(set_time); | |
995 | calculate_adjustment(ctl, adjtime->drift_factor, | |
996 | adjtime->last_adj_time, | |
997 | adjtime->not_adjusted, | |
998 | hclocktime.tv_sec, &tdrift); | |
999 | hclocktime = time_inc(hclocktime, (double) | |
1000 | -(tdrift.tv_sec + tdrift.tv_usec / 1E6)); | |
1001 | if (ctl->verbose) { | |
1002 | printf(_ ("Target date: %ld\n"), set_time); | |
1003 | printf(_ ("Predicted RTC: %ld\n"), hclocktime.tv_sec); | |
1004 | } | |
1005 | return display_time(hclocktime); | |
1006 | } | |
1007 | ||
1008 | if (ctl->systz) | |
1009 | return set_system_clock(ctl, startup_time); | |
1010 | ||
1011 | if (ur->get_permissions()) | |
1012 | return EXIT_FAILURE; | |
1013 | ||
1014 | /* | |
1015 | * Read and drift correct RTC time; except for RTC set functions | |
1016 | * without the --update-drift option because: 1) it's not needed; | |
1017 | * 2) it enables setting a corrupted RTC without reading it first; | |
1018 | * 3) it significantly reduces system shutdown time. | |
1019 | */ | |
1020 | if ( ! ((ctl->set || ctl->systohc) && !ctl->update)) { | |
1021 | /* | |
1022 | * Timing critical - do not change the order of, or put | |
1023 | * anything between the follow three statements. | |
1024 | * Synchronization failure MUST exit, because all drift | |
1025 | * operations are invalid without it. | |
1026 | */ | |
1027 | if (synchronize_to_clock_tick(ctl)) | |
1028 | return EXIT_FAILURE; | |
1029 | read_hardware_clock(ctl, &hclock_valid, &hclocktime.tv_sec); | |
1030 | gettimeofday(&read_time, NULL); | |
1031 | ||
1032 | if (!hclock_valid) { | |
1033 | warnx(_("RTC read returned an invalid value.")); | |
1034 | return EXIT_FAILURE; | |
1035 | } | |
1036 | /* | |
1037 | * Calculate and apply drift correction to the Hardware Clock | |
1038 | * time for everything except --show | |
1039 | */ | |
1040 | calculate_adjustment(ctl, adjtime->drift_factor, | |
1041 | adjtime->last_adj_time, | |
1042 | adjtime->not_adjusted, | |
1043 | hclocktime.tv_sec, &tdrift); | |
1044 | if (!ctl->show) | |
1045 | hclocktime = time_inc(tdrift, hclocktime.tv_sec); | |
1046 | ||
1047 | startup_hclocktime = | |
1048 | time_inc(hclocktime, time_diff(startup_time, read_time)); | |
1049 | } | |
1050 | if (ctl->show || ctl->get) { | |
1051 | return display_time(startup_hclocktime); | |
1052 | } else if (ctl->set) { | |
1053 | set_hardware_clock_exact(ctl, set_time, startup_time); | |
1054 | if (!ctl->noadjfile) | |
1055 | adjust_drift_factor(ctl, adjtime, t2tv(set_time), | |
1056 | startup_hclocktime); | |
1057 | } else if (ctl->adjust) { | |
1058 | if (tdrift.tv_sec > 0 || tdrift.tv_sec < -1) | |
1059 | do_adjustment(ctl, adjtime, hclocktime, read_time); | |
1060 | else | |
1061 | printf(_("Needed adjustment is less than one second, " | |
1062 | "so not setting clock.\n")); | |
1063 | } else if (ctl->systohc) { | |
1064 | struct timeval nowtime, reftime; | |
1065 | /* | |
1066 | * We can only set_hardware_clock_exact to a | |
1067 | * whole seconds time, so we set it with | |
1068 | * reference to the most recent whole | |
1069 | * seconds time. | |
1070 | */ | |
1071 | gettimeofday(&nowtime, NULL); | |
1072 | reftime.tv_sec = nowtime.tv_sec; | |
1073 | reftime.tv_usec = 0; | |
1074 | set_hardware_clock_exact(ctl, (time_t) reftime.tv_sec, reftime); | |
1075 | if (!ctl->noadjfile) | |
1076 | adjust_drift_factor(ctl, adjtime, nowtime, | |
1077 | hclocktime); | |
1078 | } else if (ctl->hctosys) { | |
1079 | return set_system_clock(ctl, hclocktime); | |
1080 | } | |
1081 | if (!ctl->noadjfile && adjtime->dirty) | |
1082 | return save_adjtime(ctl, adjtime); | |
1083 | return EXIT_SUCCESS; | |
1084 | } | |
1085 | ||
1086 | /** | |
1087 | * Get or set the kernel RTC driver's epoch on Alpha machines. | |
1088 | * ISA machines are hard coded for 1900. | |
1089 | */ | |
1090 | #if defined(__linux__) && defined(__alpha__) | |
1091 | static void | |
1092 | manipulate_epoch(const struct hwclock_control *ctl) | |
1093 | { | |
1094 | if (ctl->getepoch) { | |
1095 | unsigned long epoch; | |
1096 | ||
1097 | if (get_epoch_rtc(ctl, &epoch)) | |
1098 | warnx(_("unable to read the RTC epoch.")); | |
1099 | else | |
1100 | printf(_("The RTC epoch is set to %lu.\n"), epoch); | |
1101 | } else if (ctl->setepoch) { | |
1102 | if (!ctl->epoch_option) | |
1103 | warnx(_("--epoch is required for --setepoch.")); | |
1104 | else if (!ctl->testing) | |
1105 | if (set_epoch_rtc(ctl)) | |
1106 | warnx(_("unable to set the RTC epoch.")); | |
1107 | } | |
1108 | } | |
1109 | #endif /* __linux__ __alpha__ */ | |
1110 | ||
1111 | static void out_version(void) | |
1112 | { | |
1113 | printf(UTIL_LINUX_VERSION); | |
1114 | } | |
1115 | ||
1116 | static void __attribute__((__noreturn__)) | |
1117 | usage(void) | |
1118 | { | |
1119 | fputs(USAGE_HEADER, stdout); | |
1120 | printf(_(" %s [function] [option...]\n"), program_invocation_short_name); | |
1121 | ||
1122 | fputs(USAGE_SEPARATOR, stdout); | |
1123 | puts(_("Time clocks utility.")); | |
1124 | ||
1125 | fputs(USAGE_FUNCTIONS, stdout); | |
1126 | puts(_(" -r, --show display the RTC time")); | |
1127 | puts(_(" --get display drift corrected RTC time")); | |
1128 | puts(_(" --set set the RTC according to --date")); | |
1129 | puts(_(" -s, --hctosys set the system time from the RTC")); | |
1130 | puts(_(" -w, --systohc set the RTC from the system time")); | |
1131 | puts(_(" --systz send timescale configurations to the kernel")); | |
1132 | puts(_(" -a, --adjust adjust the RTC to account for systematic drift")); | |
1133 | #if defined(__linux__) && defined(__alpha__) | |
1134 | puts(_(" --getepoch display the RTC epoch")); | |
1135 | puts(_(" --setepoch set the RTC epoch according to --epoch")); | |
1136 | #endif | |
1137 | puts(_(" --predict predict the drifted RTC time according to --date")); | |
1138 | fputs(USAGE_OPTIONS, stdout); | |
1139 | puts(_(" -u, --utc the RTC timescale is UTC")); | |
1140 | puts(_(" -l, --localtime the RTC timescale is Local")); | |
1141 | #ifdef __linux__ | |
1142 | printf(_( | |
1143 | " -f, --rtc <file> use an alternate file to %1$s\n"), _PATH_RTC_DEV); | |
1144 | #endif | |
1145 | printf(_( | |
1146 | " --directisa use the ISA bus instead of %1$s access\n"), _PATH_RTC_DEV); | |
1147 | puts(_(" --date <time> date/time input for --set and --predict")); | |
1148 | puts(_(" --delay <sec> delay used when set new RTC time")); | |
1149 | #if defined(__linux__) && defined(__alpha__) | |
1150 | puts(_(" --epoch <year> epoch input for --setepoch")); | |
1151 | #endif | |
1152 | puts(_(" --update-drift update the RTC drift factor")); | |
1153 | printf(_( | |
1154 | " --noadjfile do not use %1$s\n"), _PATH_ADJTIME); | |
1155 | printf(_( | |
1156 | " --adjfile <file> use an alternate file to %1$s\n"), _PATH_ADJTIME); | |
1157 | puts(_(" --test dry run; implies --verbose")); | |
1158 | puts(_(" -v, --verbose display more details")); | |
1159 | fputs(USAGE_SEPARATOR, stdout); | |
1160 | printf(USAGE_HELP_OPTIONS(22)); | |
1161 | printf(USAGE_MAN_TAIL("hwclock(8)")); | |
1162 | exit(EXIT_SUCCESS); | |
1163 | } | |
1164 | ||
1165 | int main(int argc, char **argv) | |
1166 | { | |
1167 | struct hwclock_control ctl = { | |
1168 | .show = 1, /* default op is show */ | |
1169 | .rtc_delay = -1.0 /* unspecified */ | |
1170 | }; | |
1171 | struct timeval startup_time; | |
1172 | struct adjtime adjtime = { 0 }; | |
1173 | struct timespec when = { 0 }; | |
1174 | /* | |
1175 | * The time we started up, in seconds into the epoch, including | |
1176 | * fractions. | |
1177 | */ | |
1178 | time_t set_time = 0; /* Time to which user said to set Hardware Clock */ | |
1179 | int rc, c; | |
1180 | ||
1181 | /* Long only options. */ | |
1182 | enum { | |
1183 | OPT_ADJFILE = CHAR_MAX + 1, | |
1184 | OPT_DATE, | |
1185 | OPT_DELAY, | |
1186 | OPT_DIRECTISA, | |
1187 | OPT_EPOCH, | |
1188 | OPT_GET, | |
1189 | OPT_GETEPOCH, | |
1190 | OPT_NOADJFILE, | |
1191 | OPT_PREDICT, | |
1192 | OPT_SET, | |
1193 | OPT_SETEPOCH, | |
1194 | OPT_SYSTZ, | |
1195 | OPT_TEST, | |
1196 | OPT_UPDATE | |
1197 | }; | |
1198 | ||
1199 | static const struct option longopts[] = { | |
1200 | { "adjust", no_argument, NULL, 'a' }, | |
1201 | { "help", no_argument, NULL, 'h' }, | |
1202 | { "localtime", no_argument, NULL, 'l' }, | |
1203 | { "show", no_argument, NULL, 'r' }, | |
1204 | { "hctosys", no_argument, NULL, 's' }, | |
1205 | { "utc", no_argument, NULL, 'u' }, | |
1206 | { "version", no_argument, NULL, 'V' }, | |
1207 | { "systohc", no_argument, NULL, 'w' }, | |
1208 | { "debug", no_argument, NULL, 'D' }, | |
1209 | { "ul-debug", required_argument, NULL, 'd' }, | |
1210 | { "verbose", no_argument, NULL, 'v' }, | |
1211 | { "set", no_argument, NULL, OPT_SET }, | |
1212 | #if defined(__linux__) && defined(__alpha__) | |
1213 | { "getepoch", no_argument, NULL, OPT_GETEPOCH }, | |
1214 | { "setepoch", no_argument, NULL, OPT_SETEPOCH }, | |
1215 | { "epoch", required_argument, NULL, OPT_EPOCH }, | |
1216 | #endif | |
1217 | { "noadjfile", no_argument, NULL, OPT_NOADJFILE }, | |
1218 | { "directisa", no_argument, NULL, OPT_DIRECTISA }, | |
1219 | { "test", no_argument, NULL, OPT_TEST }, | |
1220 | { "date", required_argument, NULL, OPT_DATE }, | |
1221 | { "delay", required_argument, NULL, OPT_DELAY }, | |
1222 | #ifdef __linux__ | |
1223 | { "rtc", required_argument, NULL, 'f' }, | |
1224 | #endif | |
1225 | { "adjfile", required_argument, NULL, OPT_ADJFILE }, | |
1226 | { "systz", no_argument, NULL, OPT_SYSTZ }, | |
1227 | { "predict", no_argument, NULL, OPT_PREDICT }, | |
1228 | { "get", no_argument, NULL, OPT_GET }, | |
1229 | { "update-drift", no_argument, NULL, OPT_UPDATE }, | |
1230 | { NULL, 0, NULL, 0 } | |
1231 | }; | |
1232 | ||
1233 | static const ul_excl_t excl[] = { /* rows and cols in ASCII order */ | |
1234 | { 'a','r','s','w', | |
1235 | OPT_GET, OPT_GETEPOCH, OPT_PREDICT, | |
1236 | OPT_SET, OPT_SETEPOCH, OPT_SYSTZ }, | |
1237 | { 'l', 'u' }, | |
1238 | { OPT_ADJFILE, OPT_NOADJFILE }, | |
1239 | { OPT_NOADJFILE, OPT_UPDATE }, | |
1240 | { 0 } | |
1241 | }; | |
1242 | int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT; | |
1243 | ||
1244 | /* Remember what time we were invoked */ | |
1245 | gettimeofday(&startup_time, NULL); | |
1246 | ||
1247 | #ifdef HAVE_LIBAUDIT | |
1248 | hwaudit_fd = audit_open(); | |
1249 | if (hwaudit_fd < 0 && !(errno == EINVAL || errno == EPROTONOSUPPORT || | |
1250 | errno == EAFNOSUPPORT)) { | |
1251 | /* | |
1252 | * You get these error codes only when the kernel doesn't | |
1253 | * have audit compiled in. | |
1254 | */ | |
1255 | warnx(_("Unable to connect to audit system")); | |
1256 | return EXIT_FAILURE; | |
1257 | } | |
1258 | #endif | |
1259 | setlocale(LC_ALL, ""); | |
1260 | #ifdef LC_NUMERIC | |
1261 | /* | |
1262 | * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid | |
1263 | * LC_NUMERIC since it gives problems when we write to /etc/adjtime. | |
1264 | * - gqueri@mail.dotcom.fr | |
1265 | */ | |
1266 | setlocale(LC_NUMERIC, "C"); | |
1267 | #endif | |
1268 | bindtextdomain(PACKAGE, LOCALEDIR); | |
1269 | textdomain(PACKAGE); | |
1270 | close_stdout_atexit(); | |
1271 | ||
1272 | while ((c = getopt_long(argc, argv, | |
1273 | "hvVDd:alrsuwf:", longopts, NULL)) != -1) { | |
1274 | ||
1275 | err_exclusive_options(c, longopts, excl, excl_st); | |
1276 | ||
1277 | switch (c) { | |
1278 | case 'D': | |
1279 | warnx(_("use --verbose, --debug has been deprecated.")); | |
1280 | break; | |
1281 | case 'v': | |
1282 | ctl.verbose = 1; | |
1283 | break; | |
1284 | case 'd': | |
1285 | hwclock_init_debug(optarg); | |
1286 | break; | |
1287 | case 'a': | |
1288 | ctl.adjust = 1; | |
1289 | ctl.show = 0; | |
1290 | ctl.hwaudit_on = 1; | |
1291 | break; | |
1292 | case 'l': | |
1293 | ctl.local_opt = 1; /* --localtime */ | |
1294 | break; | |
1295 | case 'r': | |
1296 | ctl.show = 1; | |
1297 | break; | |
1298 | case 's': | |
1299 | ctl.hctosys = 1; | |
1300 | ctl.show = 0; | |
1301 | ctl.hwaudit_on = 1; | |
1302 | break; | |
1303 | case 'u': | |
1304 | ctl.utc = 1; | |
1305 | break; | |
1306 | case 'w': | |
1307 | ctl.systohc = 1; | |
1308 | ctl.show = 0; | |
1309 | ctl.hwaudit_on = 1; | |
1310 | break; | |
1311 | case OPT_SET: | |
1312 | ctl.set = 1; | |
1313 | ctl.show = 0; | |
1314 | ctl.hwaudit_on = 1; | |
1315 | break; | |
1316 | #if defined(__linux__) && defined(__alpha__) | |
1317 | case OPT_GETEPOCH: | |
1318 | ctl.getepoch = 1; | |
1319 | ctl.show = 0; | |
1320 | break; | |
1321 | case OPT_SETEPOCH: | |
1322 | ctl.setepoch = 1; | |
1323 | ctl.show = 0; | |
1324 | ctl.hwaudit_on = 1; | |
1325 | break; | |
1326 | case OPT_EPOCH: | |
1327 | ctl.epoch_option = optarg; /* --epoch */ | |
1328 | break; | |
1329 | #endif | |
1330 | case OPT_NOADJFILE: | |
1331 | ctl.noadjfile = 1; | |
1332 | break; | |
1333 | case OPT_DIRECTISA: | |
1334 | ctl.directisa = 1; | |
1335 | break; | |
1336 | case OPT_TEST: | |
1337 | ctl.testing = 1; /* --test */ | |
1338 | ctl.verbose = 1; | |
1339 | break; | |
1340 | case OPT_DATE: | |
1341 | ctl.date_opt = optarg; /* --date */ | |
1342 | break; | |
1343 | case OPT_DELAY: | |
1344 | ctl.rtc_delay = strtod_or_err(optarg, "invalid --delay argument"); | |
1345 | break; | |
1346 | case OPT_ADJFILE: | |
1347 | ctl.adj_file_name = optarg; /* --adjfile */ | |
1348 | break; | |
1349 | case OPT_SYSTZ: | |
1350 | ctl.systz = 1; /* --systz */ | |
1351 | ctl.show = 0; | |
1352 | ctl.hwaudit_on = 1; | |
1353 | break; | |
1354 | case OPT_PREDICT: | |
1355 | ctl.predict = 1; /* --predict */ | |
1356 | ctl.show = 0; | |
1357 | break; | |
1358 | case OPT_GET: | |
1359 | ctl.get = 1; /* --get */ | |
1360 | ctl.show = 0; | |
1361 | break; | |
1362 | case OPT_UPDATE: | |
1363 | ctl.update = 1; /* --update-drift */ | |
1364 | break; | |
1365 | #ifdef __linux__ | |
1366 | case 'f': | |
1367 | ctl.rtc_dev_name = optarg; /* --rtc */ | |
1368 | break; | |
1369 | #endif | |
1370 | ||
1371 | case 'V': /* --version */ | |
1372 | print_version(EXIT_SUCCESS); | |
1373 | case 'h': /* --help */ | |
1374 | usage(); | |
1375 | default: | |
1376 | errtryhelp(EXIT_FAILURE); | |
1377 | } | |
1378 | } | |
1379 | ||
1380 | if (argc -= optind) { | |
1381 | warnx(_("%d too many arguments given"), argc); | |
1382 | errtryhelp(EXIT_FAILURE); | |
1383 | } | |
1384 | ||
1385 | if (!ctl.adj_file_name) | |
1386 | ctl.adj_file_name = _PATH_ADJTIME; | |
1387 | ||
1388 | if (ctl.update && !ctl.set && !ctl.systohc) { | |
1389 | warnx(_("--update-drift requires --set or --systohc")); | |
1390 | exit(EXIT_FAILURE); | |
1391 | } | |
1392 | ||
1393 | if (ctl.noadjfile && !ctl.utc && !ctl.local_opt) { | |
1394 | warnx(_("With --noadjfile, you must specify " | |
1395 | "either --utc or --localtime")); | |
1396 | exit(EXIT_FAILURE); | |
1397 | } | |
1398 | ||
1399 | if (ctl.set || ctl.predict) { | |
1400 | if (!ctl.date_opt) { | |
1401 | warnx(_("--date is required for --set or --predict")); | |
1402 | exit(EXIT_FAILURE); | |
1403 | } | |
1404 | if (parse_date(&when, ctl.date_opt, NULL)) | |
1405 | set_time = when.tv_sec; | |
1406 | else { | |
1407 | warnx(_("invalid date '%s'"), ctl.date_opt); | |
1408 | exit(EXIT_FAILURE); | |
1409 | } | |
1410 | } | |
1411 | ||
1412 | #if defined(__linux__) && defined(__alpha__) | |
1413 | if (ctl.getepoch || ctl.setepoch) { | |
1414 | manipulate_epoch(&ctl); | |
1415 | hwclock_exit(&ctl, EXIT_SUCCESS); | |
1416 | } | |
1417 | #endif | |
1418 | ||
1419 | if (ctl.verbose) { | |
1420 | out_version(); | |
1421 | printf(_("System Time: %ld.%06ld\n"), | |
1422 | startup_time.tv_sec, startup_time.tv_usec); | |
1423 | } | |
1424 | ||
1425 | if (!ctl.systz && !ctl.predict) | |
1426 | determine_clock_access_method(&ctl); | |
1427 | ||
1428 | if (!ctl.noadjfile && !(ctl.systz && (ctl.utc || ctl.local_opt))) { | |
1429 | if ((rc = read_adjtime(&ctl, &adjtime)) != 0) | |
1430 | hwclock_exit(&ctl, rc); | |
1431 | } else | |
1432 | /* Avoid writing adjtime file if we don't have to. */ | |
1433 | adjtime.dirty = 0; | |
1434 | ctl.universal = hw_clock_is_utc(&ctl, adjtime); | |
1435 | rc = manipulate_clock(&ctl, set_time, startup_time, &adjtime); | |
1436 | if (ctl.testing) | |
1437 | puts(_("Test mode: nothing was changed.")); | |
1438 | hwclock_exit(&ctl, rc); | |
1439 | return rc; /* Not reached */ | |
1440 | } | |
1441 | ||
1442 | void | |
1443 | hwclock_exit(const struct hwclock_control *ctl | |
1444 | #ifndef HAVE_LIBAUDIT | |
1445 | __attribute__((__unused__)) | |
1446 | #endif | |
1447 | , int status) | |
1448 | { | |
1449 | #ifdef HAVE_LIBAUDIT | |
1450 | if (ctl->hwaudit_on && !ctl->testing) { | |
1451 | audit_log_user_message(hwaudit_fd, AUDIT_USYS_CONFIG, | |
1452 | "op=change-system-time", NULL, NULL, NULL, | |
1453 | status); | |
1454 | } | |
1455 | close(hwaudit_fd); | |
1456 | #endif | |
1457 | exit(status); | |
1458 | } | |
1459 | ||
1460 | /* | |
1461 | * History of this program: | |
1462 | * | |
1463 | * 98.08.12 BJH Version 2.4 | |
1464 | * | |
1465 | * Don't use century byte from Hardware Clock. Add comments telling why. | |
1466 | * | |
1467 | * 98.06.20 BJH Version 2.3. | |
1468 | * | |
1469 | * Make --hctosys set the kernel timezone from TZ environment variable | |
1470 | * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com). | |
1471 | * | |
1472 | * 98.03.05 BJH. Version 2.2. | |
1473 | * | |
1474 | * Add --getepoch and --setepoch. | |
1475 | * | |
1476 | * Fix some word length things so it works on Alpha. | |
1477 | * | |
1478 | * Make it work when /dev/rtc doesn't have the interrupt functions. In this | |
1479 | * case, busywait for the top of a second instead of blocking and waiting | |
1480 | * for the update complete interrupt. | |
1481 | * | |
1482 | * Fix a bunch of bugs too numerous to mention. | |
1483 | * | |
1484 | * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of | |
1485 | * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by | |
1486 | * job (jei@iclnl.icl.nl). | |
1487 | * | |
1488 | * Use the rtc clock access method in preference to the KDGHWCLK method. | |
1489 | * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>. | |
1490 | * | |
1491 | * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt | |
1492 | * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as | |
1493 | * more recent versions of the kernel. Introduced the NO_CLOCK access method | |
1494 | * and wrote feature test code to detect absence of rtc headers. | |
1495 | * | |
1496 | *************************************************************************** | |
1497 | * Maintenance notes | |
1498 | * | |
1499 | * To compile this, you must use GNU compiler optimization (-O option) in | |
1500 | * order to make the "extern inline" functions from asm/io.h (inb(), etc.) | |
1501 | * compile. If you don't optimize, which means the compiler will generate no | |
1502 | * inline functions, the references to these functions in this program will | |
1503 | * be compiled as external references. Since you probably won't be linking | |
1504 | * with any functions by these names, you will have unresolved external | |
1505 | * references when you link. | |
1506 | * | |
1507 | * Here's some info on how we must deal with the time that elapses while | |
1508 | * this program runs: There are two major delays as we run: | |
1509 | * | |
1510 | * 1) Waiting up to 1 second for a transition of the Hardware Clock so | |
1511 | * we are synchronized to the Hardware Clock. | |
1512 | * 2) Running the "date" program to interpret the value of our --date | |
1513 | * option. | |
1514 | * | |
1515 | * Reading the /etc/adjtime file is the next biggest source of delay and | |
1516 | * uncertainty. | |
1517 | * | |
1518 | * The user wants to know what time it was at the moment he invoked us, not | |
1519 | * some arbitrary time later. And in setting the clock, he is giving us the | |
1520 | * time at the moment we are invoked, so if we set the clock some time | |
1521 | * later, we have to add some time to that. | |
1522 | * | |
1523 | * So we check the system time as soon as we start up, then run "date" and | |
1524 | * do file I/O if necessary, then wait to synchronize with a Hardware Clock | |
1525 | * edge, then check the system time again to see how much time we spent. We | |
1526 | * immediately read the clock then and (if appropriate) report that time, | |
1527 | * and additionally, the delay we measured. | |
1528 | * | |
1529 | * If we're setting the clock to a time given by the user, we wait some more | |
1530 | * so that the total delay is an integral number of seconds, then set the | |
1531 | * Hardware Clock to the time the user requested plus that integral number | |
1532 | * of seconds. N.B. The Hardware Clock can only be set in integral seconds. | |
1533 | * | |
1534 | * If we're setting the clock to the system clock value, we wait for the | |
1535 | * system clock to reach the top of a second, and then set the Hardware | |
1536 | * Clock to the system clock's value. | |
1537 | * | |
1538 | * Here's an interesting point about setting the Hardware Clock: On my | |
1539 | * machine, when you set it, it sets to that precise time. But one can | |
1540 | * imagine another clock whose update oscillator marches on a steady one | |
1541 | * second period, so updating the clock between any two oscillator ticks is | |
1542 | * the same as updating it right at the earlier tick. To avoid any | |
1543 | * complications that might cause, we set the clock as soon as possible | |
1544 | * after an oscillator tick. | |
1545 | * | |
1546 | * About synchronizing to the Hardware Clock when reading the time: The | |
1547 | * precision of the Hardware Clock counters themselves is one second. You | |
1548 | * can't read the counters and find out that is 12:01:02.5. But if you | |
1549 | * consider the location in time of the counter's ticks as part of its | |
1550 | * value, then its precision is as infinite as time is continuous! What I'm | |
1551 | * saying is this: To find out the _exact_ time in the hardware clock, we | |
1552 | * wait until the next clock tick (the next time the second counter changes) | |
1553 | * and measure how long we had to wait. We then read the value of the clock | |
1554 | * counters and subtract the wait time and we know precisely what time it | |
1555 | * was when we set out to query the time. | |
1556 | * | |
1557 | * hwclock uses this method, and considers the Hardware Clock to have | |
1558 | * infinite precision. | |
1559 | */ |