]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/hwclock.c
hwclock: make --date=argument less prone to injection
[thirdparty/util-linux.git] / sys-utils / hwclock.c
1 /*
2 * hwclock.c
3 *
4 * clock.c was written by Charles Hedrick, hedrick@cs.rutgers.edu, Apr 1992
5 * Modified for clock adjustments - Rob Hooft <hooft@chem.ruu.nl>, Nov 1992
6 * Improvements by Harald Koenig <koenig@nova.tat.physik.uni-tuebingen.de>
7 * and Alan Modra <alan@spri.levels.unisa.edu.au>.
8 *
9 * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19.
10 * The new program is called hwclock. New features:
11 *
12 * - You can set the hardware clock without also modifying the system
13 * clock.
14 * - You can read and set the clock with finer than 1 second precision.
15 * - When you set the clock, hwclock automatically refigures the drift
16 * rate, based on how far off the clock was before you set it.
17 *
18 * Reshuffled things, added sparc code, and re-added alpha stuff
19 * by David Mosberger <davidm@azstarnet.com>
20 * and Jay Estabrook <jestabro@amt.tay1.dec.com>
21 * and Martin Ostermann <ost@coments.rwth-aachen.de>, aeb@cwi.nl, 990212.
22 *
23 * Fix for Award 2094 bug, Dave Coffin (dcoffin@shore.net) 11/12/98
24 * Change of local time handling, Stefan Ring <e9725446@stud3.tuwien.ac.at>
25 * Change of adjtime handling, James P. Rutledge <ao112@rgfn.epcc.edu>.
26 *
27 * Distributed under GPL
28 */
29 /*
30 * Explanation of `adjusting' (Rob Hooft):
31 *
32 * The problem with my machine is that its CMOS clock is 10 seconds
33 * per day slow. With this version of clock.c, and my '/etc/rc.local'
34 * reading '/etc/clock -au' instead of '/etc/clock -u -s', this error
35 * is automatically corrected at every boot.
36 *
37 * To do this job, the program reads and writes the file '/etc/adjtime'
38 * to determine the correction, and to save its data. In this file are
39 * three numbers:
40 *
41 * 1) the correction in seconds per day. (So if your clock runs 5
42 * seconds per day fast, the first number should read -5.0)
43 * 2) the number of seconds since 1/1/1970 the last time the program
44 * was used
45 * 3) the remaining part of a second which was leftover after the last
46 * adjustment
47 *
48 * Installation and use of this program:
49 *
50 * a) create a file '/etc/adjtime' containing as the first and only
51 * line: '0.0 0 0.0'
52 * b) run 'clock -au' or 'clock -a', depending on whether your cmos is
53 * in universal or local time. This updates the second number.
54 * c) set your system time using the 'date' command.
55 * d) update your cmos time using 'clock -wu' or 'clock -w'
56 * e) replace the first number in /etc/adjtime by your correction.
57 * f) put the command 'clock -au' or 'clock -a' in your '/etc/rc.local'
58 */
59
60 #include <errno.h>
61 #include <getopt.h>
62 #include <limits.h>
63 #include <math.h>
64 #include <stdarg.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <sysexits.h>
69 #include <sys/stat.h>
70 #include <sys/time.h>
71 #include <time.h>
72 #include <unistd.h>
73
74 #define OPTUTILS_EXIT_CODE EX_USAGE
75
76 #include "c.h"
77 #include "closestream.h"
78 #include "nls.h"
79 #include "optutils.h"
80 #include "pathnames.h"
81 #include "strutils.h"
82 #include "hwclock.h"
83 #include "timeutils.h"
84 #include "env.h"
85 #include "xalloc.h"
86
87 #ifdef HAVE_LIBAUDIT
88 #include <libaudit.h>
89 static int hwaudit_fd = -1;
90 #endif
91
92 /* The struct that holds our hardware access routines */
93 struct clock_ops *ur;
94
95 /* Maximal clock adjustment in seconds per day.
96 (adjtime() glibc call has 2145 seconds limit on i386, so it is good enough for us as well,
97 43219 is a maximal safe value preventing exact_adjustment overflow.) */
98 #define MAX_DRIFT 2145.0
99
100 struct adjtime {
101 /*
102 * This is information we keep in the adjtime file that tells us how
103 * to do drift corrections. Elements are all straight from the
104 * adjtime file, so see documentation of that file for details.
105 * Exception is <dirty>, which is an indication that what's in this
106 * structure is not what's in the disk file (because it has been
107 * updated since read from the disk file).
108 */
109 bool dirty;
110 /* line 1 */
111 double drift_factor;
112 time_t last_adj_time;
113 double not_adjusted;
114 /* line 2 */
115 time_t last_calib_time;
116 /*
117 * The most recent time that we set the clock from an external
118 * authority (as opposed to just doing a drift adjustment)
119 */
120 /* line 3 */
121 enum a_local_utc { UTC = 0, LOCAL, UNKNOWN } local_utc;
122 /*
123 * To which time zone, local or UTC, we most recently set the
124 * hardware clock.
125 */
126 };
127
128 /*
129 * Almost all Award BIOS's made between 04/26/94 and 05/31/95 have a nasty
130 * bug limiting the RTC year byte to the range 94-99. Any year between 2000
131 * and 2093 gets changed to 2094, every time you start the system.
132 *
133 * With the --badyear option, we write the date to file and hope that the
134 * file is updated at least once a year. I recommend putting this command
135 * "hwclock --badyear" in the monthly crontab, just to be safe.
136 *
137 * -- Dave Coffin 11/12/98
138 */
139 static void write_date_to_file(struct tm *tm)
140 {
141 FILE *fp;
142
143 if ((fp = fopen(_PATH_LASTDATE, "w"))) {
144 fprintf(fp, "%02d.%02d.%04d\n", tm->tm_mday, tm->tm_mon + 1,
145 tm->tm_year + 1900);
146 if (close_stream(fp) != 0)
147 warn(_("cannot write %s"), _PATH_LASTDATE);
148 } else
149 warn(_("cannot write %s"), _PATH_LASTDATE);
150 }
151
152 static void read_date_from_file(struct tm *tm)
153 {
154 int last_mday, last_mon, last_year;
155 FILE *fp;
156
157 if ((fp = fopen(_PATH_LASTDATE, "r"))) {
158 if (fscanf(fp, "%d.%d.%d\n", &last_mday, &last_mon, &last_year)
159 == 3) {
160 tm->tm_year = last_year - 1900;
161 if ((tm->tm_mon << 5) + tm->tm_mday <
162 ((last_mon - 1) << 5) + last_mday)
163 tm->tm_year++;
164 }
165 fclose(fp);
166 }
167 write_date_to_file(tm);
168 }
169
170 /*
171 * time_t to timeval conversion.
172 */
173 static struct timeval t2tv(time_t timet)
174 {
175 struct timeval rettimeval;
176
177 rettimeval.tv_sec = timet;
178 rettimeval.tv_usec = 0;
179 return rettimeval;
180 }
181
182 /*
183 * The difference in seconds between two times in "timeval" format.
184 */
185 double time_diff(struct timeval subtrahend, struct timeval subtractor)
186 {
187 return (subtrahend.tv_sec - subtractor.tv_sec)
188 + (subtrahend.tv_usec - subtractor.tv_usec) / 1E6;
189 }
190
191 /*
192 * The time, in "timeval" format, which is <increment> seconds after the
193 * time <addend>. Of course, <increment> may be negative.
194 */
195 static struct timeval time_inc(struct timeval addend, double increment)
196 {
197 struct timeval newtime;
198
199 newtime.tv_sec = addend.tv_sec + (int)increment;
200 newtime.tv_usec = addend.tv_usec + (increment - (int)increment) * 1E6;
201
202 /*
203 * Now adjust it so that the microsecond value is between 0 and 1
204 * million.
205 */
206 if (newtime.tv_usec < 0) {
207 newtime.tv_usec += 1E6;
208 newtime.tv_sec -= 1;
209 } else if (newtime.tv_usec >= 1E6) {
210 newtime.tv_usec -= 1E6;
211 newtime.tv_sec += 1;
212 }
213 return newtime;
214 }
215
216 static bool
217 hw_clock_is_utc(const struct hwclock_control *ctl,
218 const struct adjtime adjtime)
219 {
220 bool ret;
221
222 if (ctl->utc)
223 ret = TRUE; /* --utc explicitly given on command line */
224 else if (ctl->local_opt)
225 ret = FALSE; /* --localtime explicitly given */
226 else
227 /* get info from adjtime file - default is UTC */
228 ret = (adjtime.local_utc != LOCAL);
229 if (ctl->debug)
230 printf(_("Assuming hardware clock is kept in %s time.\n"),
231 ret ? _("UTC") : _("local"));
232 return ret;
233 }
234
235 /*
236 * Read the adjustment parameters out of the /etc/adjtime file.
237 *
238 * Return them as the adjtime structure <*adjtime_p>. If there is no
239 * /etc/adjtime file, return defaults. If values are missing from the file,
240 * return defaults for them.
241 *
242 * return value 0 if all OK, !=0 otherwise.
243 */
244 static int read_adjtime(const struct hwclock_control *ctl,
245 struct adjtime *adjtime_p)
246 {
247 FILE *adjfile;
248 char line1[81]; /* String: first line of adjtime file */
249 char line2[81]; /* String: second line of adjtime file */
250 char line3[81]; /* String: third line of adjtime file */
251
252 if (access(ctl->adj_file_name, R_OK) != 0)
253 return 0;
254
255 adjfile = fopen(ctl->adj_file_name, "r"); /* open file for reading */
256 if (adjfile == NULL) {
257 warn(_("cannot open %s"), ctl->adj_file_name);
258 return EX_OSFILE;
259 }
260
261 if (!fgets(line1, sizeof(line1), adjfile))
262 line1[0] = '\0'; /* In case fgets fails */
263 if (!fgets(line2, sizeof(line2), adjfile))
264 line2[0] = '\0'; /* In case fgets fails */
265 if (!fgets(line3, sizeof(line3), adjfile))
266 line3[0] = '\0'; /* In case fgets fails */
267
268 fclose(adjfile);
269
270 sscanf(line1, "%lf %ld %lf",
271 &adjtime_p->drift_factor,
272 &adjtime_p->last_adj_time,
273 &adjtime_p->not_adjusted);
274
275 sscanf(line2, "%ld", &adjtime_p->last_calib_time);
276
277 if (!strcmp(line3, "UTC\n")) {
278 adjtime_p->local_utc = UTC;
279 } else if (!strcmp(line3, "LOCAL\n")) {
280 adjtime_p->local_utc = LOCAL;
281 } else {
282 adjtime_p->local_utc = UNKNOWN;
283 if (line3[0]) {
284 warnx(_("Warning: unrecognized third line in adjtime file\n"
285 "(Expected: `UTC' or `LOCAL' or nothing.)"));
286 }
287 }
288
289 if (ctl->debug) {
290 printf(_
291 ("Last drift adjustment done at %ld seconds after 1969\n"),
292 (long)adjtime_p->last_adj_time);
293 printf(_("Last calibration done at %ld seconds after 1969\n"),
294 (long)adjtime_p->last_calib_time);
295 printf(_("Hardware clock is on %s time\n"),
296 (adjtime_p->local_utc ==
297 LOCAL) ? _("local") : (adjtime_p->local_utc ==
298 UTC) ? _("UTC") : _("unknown"));
299 }
300
301 return 0;
302 }
303
304 /*
305 * Wait until the falling edge of the Hardware Clock's update flag so that
306 * any time that is read from the clock immediately after we return will be
307 * exact.
308 *
309 * The clock only has 1 second precision, so it gives the exact time only
310 * once per second, right on the falling edge of the update flag.
311 *
312 * We wait (up to one second) either blocked waiting for an rtc device or in
313 * a CPU spin loop. The former is probably not very accurate.
314 *
315 * Return 0 if it worked, nonzero if it didn't.
316 */
317 static int synchronize_to_clock_tick(const struct hwclock_control *ctl)
318 {
319 int rc;
320
321 if (ctl->debug)
322 printf(_("Waiting for clock tick...\n"));
323
324 rc = ur->synchronize_to_clock_tick(ctl);
325
326 if (ctl->debug) {
327 if (rc)
328 printf(_("...synchronization failed\n"));
329 else
330 printf(_("...got clock tick\n"));
331 }
332
333 return rc;
334 }
335
336 /*
337 * Convert a time in broken down format (hours, minutes, etc.) into standard
338 * unix time (seconds into epoch). Return it as *systime_p.
339 *
340 * The broken down time is argument <tm>. This broken down time is either
341 * in local time zone or UTC, depending on value of logical argument
342 * "universal". True means it is in UTC.
343 *
344 * If the argument contains values that do not constitute a valid time, and
345 * mktime() recognizes this, return *valid_p == false and *systime_p
346 * undefined. However, mktime() sometimes goes ahead and computes a
347 * fictional time "as if" the input values were valid, e.g. if they indicate
348 * the 31st day of April, mktime() may compute the time of May 1. In such a
349 * case, we return the same fictional value mktime() does as *systime_p and
350 * return *valid_p == true.
351 */
352 static void
353 mktime_tz(const struct hwclock_control *ctl, struct tm tm,
354 bool *valid_p, time_t *systime_p)
355 {
356 if (ctl->universal)
357 *systime_p = timegm(&tm);
358 else
359 *systime_p = mktime(&tm);
360 if (*systime_p == -1) {
361 /*
362 * This apparently (not specified in mktime() documentation)
363 * means the 'tm' structure does not contain valid values
364 * (however, not containing valid values does _not_ imply
365 * mktime() returns -1).
366 */
367 *valid_p = FALSE;
368 if (ctl->debug)
369 printf(_("Invalid values in hardware clock: "
370 "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"),
371 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
372 tm.tm_hour, tm.tm_min, tm.tm_sec);
373 } else {
374 *valid_p = TRUE;
375 if (ctl->debug)
376 printf(_
377 ("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
378 "%ld seconds since 1969\n"), tm.tm_year + 1900,
379 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min,
380 tm.tm_sec, (long)*systime_p);
381 }
382 }
383
384 /*
385 * Read the hardware clock and return the current time via <tm> argument.
386 *
387 * Use the method indicated by <method> argument to access the hardware
388 * clock.
389 */
390 static int
391 read_hardware_clock(const struct hwclock_control *ctl,
392 bool * valid_p, time_t *systime_p)
393 {
394 struct tm tm;
395 int err;
396
397 err = ur->read_hardware_clock(ctl, &tm);
398 if (err)
399 return err;
400
401 if (ctl->badyear)
402 read_date_from_file(&tm);
403
404 if (ctl->debug)
405 printf(_
406 ("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
407 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
408 tm.tm_min, tm.tm_sec);
409 mktime_tz(ctl, tm, valid_p, systime_p);
410
411 return 0;
412 }
413
414 /*
415 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
416 * according to <universal>.
417 */
418 static void
419 set_hardware_clock(const struct hwclock_control *ctl, const time_t newtime)
420 {
421 struct tm new_broken_time;
422 /*
423 * Time to which we will set Hardware Clock, in broken down format,
424 * in the time zone of caller's choice
425 */
426
427 if (ctl->universal)
428 new_broken_time = *gmtime(&newtime);
429 else
430 new_broken_time = *localtime(&newtime);
431
432 if (ctl->debug)
433 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
434 "= %ld seconds since 1969\n"),
435 new_broken_time.tm_hour, new_broken_time.tm_min,
436 new_broken_time.tm_sec, (long)newtime);
437
438 if (ctl->testing)
439 printf(_("Clock not changed - testing only.\n"));
440 else {
441 if (ctl->badyear) {
442 /*
443 * Write the real year to a file, then write a fake
444 * year between 1995 and 1998 to the RTC. This way,
445 * Award BIOS boots on 29 Feb 2000 thinking that
446 * it's 29 Feb 1996.
447 */
448 write_date_to_file(&new_broken_time);
449 new_broken_time.tm_year =
450 95 + ((new_broken_time.tm_year + 1) & 3);
451 }
452 ur->set_hardware_clock(ctl, &new_broken_time);
453 }
454 }
455
456 /*
457 * Set the Hardware Clock to the time "sethwtime", in local time zone or
458 * UTC, according to "universal".
459 *
460 * Wait for a fraction of a second so that "sethwtime" is the value of the
461 * Hardware Clock as of system time "refsystime", which is in the past. For
462 * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and
463 * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2
464 * seconds since "refsystime") and then set the Hardware Clock to 14:03:07,
465 * thus getting a precise and retroactive setting of the clock.
466 *
467 * (Don't be confused by the fact that the system clock and the Hardware
468 * Clock differ by two hours in the above example. That's just to remind you
469 * that there are two independent time scales here).
470 *
471 * This function ought to be able to accept set times as fractional times.
472 * Idea for future enhancement.
473 */
474 static void
475 set_hardware_clock_exact(const struct hwclock_control *ctl,
476 const time_t sethwtime,
477 const struct timeval refsystime)
478 {
479 /*
480 * The Hardware Clock can only be set to any integer time plus one
481 * half second. The integer time is required because there is no
482 * interface to set or get a fractional second. The additional half
483 * second is because the Hardware Clock updates to the following
484 * second precisely 500 ms (not 1 second!) after you release the
485 * divider reset (after setting the new time) - see description of
486 * DV2, DV1, DV0 in Register A in the MC146818A data sheet (and note
487 * that although that document doesn't say so, real-world code seems
488 * to expect that the SET bit in Register B functions the same way).
489 * That means that, e.g., when you set the clock to 1:02:03, it
490 * effectively really sets it to 1:02:03.5, because it will update to
491 * 1:02:04 only half a second later. Our caller passes the desired
492 * integer Hardware Clock time in sethwtime, and the corresponding
493 * system time (which may have a fractional part, and which may or may
494 * not be the same!) in refsystime. In an ideal situation, we would
495 * then apply sethwtime to the Hardware Clock at refsystime+500ms, so
496 * that when the Hardware Clock ticks forward to sethwtime+1s half a
497 * second later at refsystime+1000ms, everything is in sync. So we
498 * spin, waiting for gettimeofday() to return a time at or after that
499 * time (refsystime+500ms) up to a tolerance value, initially 1ms. If
500 * we miss that time due to being preempted for some other process,
501 * then we increase the margin a little bit (initially 1ms, doubling
502 * each time), add 1 second (or more, if needed to get a time that is
503 * in the future) to both the time for which we are waiting and the
504 * time that we will apply to the Hardware Clock, and start waiting
505 * again.
506 *
507 * For example, the caller requests that we set the Hardware Clock to
508 * 1:02:03, with reference time (current system time) = 6:07:08.250.
509 * We want the Hardware Clock to update to 1:02:04 at 6:07:09.250 on
510 * the system clock, and the first such update will occur 0.500
511 * seconds after we write to the Hardware Clock, so we spin until the
512 * system clock reads 6:07:08.750. If we get there, great, but let's
513 * imagine the system is so heavily loaded that our process is
514 * preempted and by the time we get to run again, the system clock
515 * reads 6:07:11.990. We now want to wait until the next xx:xx:xx.750
516 * time, which is 6:07:12.750 (4.5 seconds after the reference time),
517 * at which point we will set the Hardware Clock to 1:02:07 (4 seconds
518 * after the originally requested time). If we do that successfully,
519 * then at 6:07:13.250 (5 seconds after the reference time), the
520 * Hardware Clock will update to 1:02:08 (5 seconds after the
521 * originally requested time), and all is well thereafter.
522 */
523
524 time_t newhwtime = sethwtime;
525 double target_time_tolerance_secs = 0.001; /* initial value */
526 double tolerance_incr_secs = 0.001; /* initial value */
527 const double RTC_SET_DELAY_SECS = 0.5; /* 500 ms */
528 const struct timeval RTC_SET_DELAY_TV = { 0, RTC_SET_DELAY_SECS * 1E6 };
529
530 struct timeval targetsystime;
531 struct timeval nowsystime;
532 struct timeval prevsystime = refsystime;
533 double deltavstarget;
534
535 timeradd(&refsystime, &RTC_SET_DELAY_TV, &targetsystime);
536
537 while (1) {
538 double ticksize;
539
540 /* FOR TESTING ONLY: inject random delays of up to 1000ms */
541 if (ctl->debug >= 10) {
542 int usec = random() % 1000000;
543 printf(_("sleeping ~%d usec\n"), usec);
544 xusleep(usec);
545 }
546
547 gettimeofday(&nowsystime, NULL);
548 deltavstarget = time_diff(nowsystime, targetsystime);
549 ticksize = time_diff(nowsystime, prevsystime);
550 prevsystime = nowsystime;
551
552 if (ticksize < 0) {
553 if (ctl->debug)
554 printf(_("time jumped backward %.6f seconds "
555 "to %ld.%06ld - retargeting\n"),
556 ticksize, nowsystime.tv_sec,
557 nowsystime.tv_usec);
558 /* The retarget is handled at the end of the loop. */
559 } else if (deltavstarget < 0) {
560 /* deltavstarget < 0 if current time < target time */
561 if (ctl->debug >= 2)
562 printf(_("%ld.%06ld < %ld.%06ld (%.6f)\n"),
563 nowsystime.tv_sec,
564 nowsystime.tv_usec,
565 targetsystime.tv_sec,
566 targetsystime.tv_usec,
567 deltavstarget);
568 continue; /* not there yet - keep spinning */
569 } else if (deltavstarget <= target_time_tolerance_secs) {
570 /* Close enough to the target time; done waiting. */
571 break;
572 } else /* (deltavstarget > target_time_tolerance_secs) */ {
573 /*
574 * We missed our window. Increase the tolerance and
575 * aim for the next opportunity.
576 */
577 if (ctl->debug)
578 printf(_("missed it - %ld.%06ld is too far "
579 "past %ld.%06ld (%.6f > %.6f)\n"),
580 nowsystime.tv_sec,
581 nowsystime.tv_usec,
582 targetsystime.tv_sec,
583 targetsystime.tv_usec,
584 deltavstarget,
585 target_time_tolerance_secs);
586 target_time_tolerance_secs += tolerance_incr_secs;
587 tolerance_incr_secs *= 2;
588 }
589
590 /*
591 * Aim for the same offset (tv_usec) within the second in
592 * either the current second (if that offset hasn't arrived
593 * yet), or the next second.
594 */
595 if (nowsystime.tv_usec < targetsystime.tv_usec)
596 targetsystime.tv_sec = nowsystime.tv_sec;
597 else
598 targetsystime.tv_sec = nowsystime.tv_sec + 1;
599 }
600
601 newhwtime = sethwtime
602 + (int)(time_diff(nowsystime, refsystime)
603 - RTC_SET_DELAY_SECS /* don't count this */
604 + 0.5 /* for rounding */);
605 if (ctl->debug)
606 printf(_("%ld.%06ld is close enough to %ld.%06ld (%.6f < %.6f)\n"
607 "Set RTC to %ld (%ld + %d; refsystime = %ld.%06ld)\n"),
608 nowsystime.tv_sec, nowsystime.tv_usec,
609 targetsystime.tv_sec, targetsystime.tv_usec,
610 deltavstarget, target_time_tolerance_secs,
611 newhwtime, sethwtime,
612 (int)(newhwtime - sethwtime),
613 refsystime.tv_sec, refsystime.tv_usec);
614
615 set_hardware_clock(ctl, newhwtime);
616 }
617
618 /*
619 * Put the time "hwctime" on standard output in display format. Except if
620 * hclock_valid == false, just tell standard output that we don't know what
621 * time it is.
622 */
623 static void
624 display_time(const bool hclock_valid, struct timeval hwctime)
625 {
626 if (!hclock_valid)
627 warnx(_
628 ("The Hardware Clock registers contain values that are "
629 "either invalid (e.g. 50th day of month) or beyond the range "
630 "we can handle (e.g. Year 2095)."));
631 else {
632 char buf[ISO_8601_BUFSIZ];
633
634 strtimeval_iso(&hwctime, ISO_8601_DATE|ISO_8601_TIME|ISO_8601_DOTUSEC|
635 ISO_8601_TIMEZONE|ISO_8601_SPACE,
636 buf, sizeof(buf));
637 printf("%s\n", buf);
638 }
639 }
640
641 /*
642 * Interpret the value of the --date option, which is something like
643 * "13:05:01". In fact, it can be any of the myriad ASCII strings that
644 * specify a time which the "date" program can understand. The date option
645 * value in question is our "dateopt" argument.
646 *
647 * The specified time is in the local time zone.
648 *
649 * Our output, "*time_p", is a seconds-into-epoch time.
650 *
651 * We use the "date" program to interpret the date string. "date" must be
652 * runnable by issuing the command "date" to the /bin/sh shell. That means
653 * in must be in the current PATH.
654 *
655 * If anything goes wrong (and many things can), we return return code 10
656 * and arbitrary *time_p. Otherwise, return code is 0 and *time_p is valid.
657 */
658 static int interpret_date_string(const struct hwclock_control *ctl,
659 time_t *const time_p)
660 {
661 FILE *date_child_fp = NULL;
662 char *date_command = NULL;
663 char *date_resp = NULL;
664 size_t len = 0;
665 const char magic[] = "seconds-into-epoch=";
666 int retcode = 1;
667 long seconds_since_epoch;
668
669 if (!ctl->date_opt) {
670 warnx(_("No --date option specified."));
671 return retcode;
672 }
673
674 /* Quotes in date_opt would ruin the date command we construct. */
675 if (strchr(ctl->date_opt, '"') != NULL ||
676 strchr(ctl->date_opt, '`') != NULL ||
677 strchr(ctl->date_opt, '$') != NULL) {
678 warnx(_
679 ("The value of the --date option is not a valid date.\n"
680 "In particular, it contains illegal character(s)."));
681 return retcode;
682 }
683
684 xasprintf(&date_command, "date --date=\"%s\" +%s%%s",
685 ctl->date_opt, magic);
686 if (ctl->debug)
687 printf(_("Issuing date command: %s\n"), date_command);
688
689 date_child_fp = popen(date_command, "r");
690 if (date_child_fp == NULL) {
691 warn(_("Unable to run 'date' program in /bin/sh shell. "
692 "popen() failed"));
693 goto out;
694 }
695
696 if (getline(&date_resp, &len, date_child_fp) < 0) {
697 warn(_("getline() failed"));
698 goto out;
699 }
700 if (ctl->debug)
701 printf(_("response from date command = %s\n"), date_resp);
702 if (strncmp(date_resp, magic, sizeof(magic) - 1) != 0) {
703 warnx(_("The date command issued by %s returned "
704 "unexpected results.\n"
705 "The command was:\n %s\n"
706 "The response was:\n %s"),
707 program_invocation_short_name, date_command, date_resp);
708 goto out;
709 }
710
711 if (sscanf(date_resp + sizeof(magic) - 1, "%ld", &seconds_since_epoch) < 1) {
712 warnx(_("The date command issued by %s returned "
713 "something other than an integer where the "
714 "converted time value was expected.\n"
715 "The command was:\n %s\n"
716 "The response was:\n %s\n"),
717 program_invocation_short_name, date_command, date_resp);
718 } else {
719 retcode = 0;
720 *time_p = seconds_since_epoch;
721 if (ctl->debug)
722 printf(_("date string %s equates to "
723 "%ld seconds since 1969.\n"),
724 ctl->date_opt, *time_p);
725 }
726 out:
727 free(date_command);
728 free(date_resp);
729 if (date_child_fp)
730 pclose(date_child_fp);
731
732 return retcode;
733 }
734
735 /*
736 * Set the System Clock to time 'newtime'.
737 *
738 * Also set the kernel time zone value to the value indicated by the TZ
739 * environment variable and/or /usr/lib/zoneinfo/, interpreted as tzset()
740 * would interpret them.
741 *
742 * If this is the first call of settimeofday since boot, then this also sets
743 * the kernel variable persistent_clock_is_local so that NTP 11 minute mode
744 * will update the Hardware Clock with the proper timescale. If the Hardware
745 * Clock's timescale configuration is changed then a reboot is required for
746 * persistent_clock_is_local to be updated.
747 *
748 * EXCEPT: if hclock_valid is false, just issue an error message saying
749 * there is no valid time in the Hardware Clock to which to set the system
750 * time.
751 *
752 * If 'testing' is true, don't actually update anything -- just say we would
753 * have.
754 */
755 static int
756 set_system_clock(const struct hwclock_control *ctl, const bool hclock_valid,
757 const struct timeval newtime)
758 {
759 int retcode;
760
761 if (!hclock_valid) {
762 warnx(_
763 ("The Hardware Clock does not contain a valid time, so "
764 "we cannot set the System Time from it."));
765 retcode = 1;
766 } else {
767 const struct timeval *tv_null = NULL;
768 struct tm *broken;
769 int minuteswest;
770 int rc = 0;
771
772 broken = localtime(&newtime.tv_sec);
773 #ifdef HAVE_TM_GMTOFF
774 minuteswest = -broken->tm_gmtoff / 60; /* GNU extension */
775 #else
776 minuteswest = timezone / 60;
777 if (broken->tm_isdst)
778 minuteswest -= 60;
779 #endif
780
781 if (ctl->debug) {
782 printf(_("Calling settimeofday:\n"));
783 printf(_("\ttv.tv_sec = %ld, tv.tv_usec = %ld\n"),
784 newtime.tv_sec, newtime.tv_usec);
785 printf(_("\ttz.tz_minuteswest = %d\n"), minuteswest);
786 }
787 if (ctl->testing) {
788 printf(_
789 ("Not setting system clock because running in test mode.\n"));
790 retcode = 0;
791 } else {
792 const struct timezone tz = { minuteswest, 0 };
793
794 /* Set kernel persistent_clock_is_local so that 11 minute
795 * mode does not clobber the Hardware Clock with UTC. This
796 * is only available on first call of settimeofday after boot.
797 */
798 if (!ctl->universal)
799 rc = settimeofday(tv_null, &tz);
800 if (!rc)
801 rc = settimeofday(&newtime, &tz);
802 if (rc) {
803 if (errno == EPERM) {
804 warnx(_
805 ("Must be superuser to set system clock."));
806 retcode = EX_NOPERM;
807 } else {
808 warn(_("settimeofday() failed"));
809 retcode = 1;
810 }
811 } else
812 retcode = 0;
813 }
814 }
815 return retcode;
816 }
817
818 /*
819 * Reset the System Clock from local time to UTC, based on its current value
820 * and the timezone unless universal is TRUE.
821 *
822 * Also set the kernel time zone value to the value indicated by the TZ
823 * environment variable and/or /usr/lib/zoneinfo/, interpreted as tzset()
824 * would interpret them.
825 *
826 * If 'testing' is true, don't actually update anything -- just say we would
827 * have.
828 */
829 static int set_system_clock_timezone(const struct hwclock_control *ctl)
830 {
831 int retcode;
832 struct timeval tv;
833 struct tm *broken;
834 int minuteswest;
835
836 gettimeofday(&tv, NULL);
837 if (ctl->debug) {
838 struct tm broken_time;
839 char ctime_now[200];
840
841 broken_time = *gmtime(&tv.tv_sec);
842 strftime(ctime_now, sizeof(ctime_now), "%Y/%m/%d %H:%M:%S",
843 &broken_time);
844 printf(_("Current system time: %ld = %s\n"), tv.tv_sec,
845 ctime_now);
846 }
847
848 broken = localtime(&tv.tv_sec);
849 #ifdef HAVE_TM_GMTOFF
850 minuteswest = -broken->tm_gmtoff / 60; /* GNU extension */
851 #else
852 minuteswest = timezone / 60;
853 if (broken->tm_isdst)
854 minuteswest -= 60;
855 #endif
856
857 if (ctl->debug) {
858 struct tm broken_time;
859 char ctime_now[200];
860
861 gettimeofday(&tv, NULL);
862 if (!ctl->universal)
863 tv.tv_sec += minuteswest * 60;
864
865 broken_time = *gmtime(&tv.tv_sec);
866 strftime(ctime_now, sizeof(ctime_now), "%Y/%m/%d %H:%M:%S",
867 &broken_time);
868
869 printf(_("Calling settimeofday:\n"));
870 printf(_("\tUTC: %s\n"), ctime_now);
871 printf(_("\ttv.tv_sec = %ld, tv.tv_usec = %ld\n"),
872 tv.tv_sec, tv.tv_usec);
873 printf(_("\ttz.tz_minuteswest = %d\n"), minuteswest);
874 }
875 if (ctl->testing) {
876 printf(_
877 ("Not setting system clock because running in test mode.\n"));
878 retcode = 0;
879 } else {
880 const struct timezone tz_utc = { 0, 0 };
881 const struct timezone tz = { minuteswest, 0 };
882 const struct timeval *tv_null = NULL;
883 int rc = 0;
884
885 /* The first call to settimeofday after boot will assume the systemtime
886 * is in localtime, and adjust it according to the given timezone to
887 * compensate. If the systemtime is in fact in UTC, then this is wrong
888 * so we first do a dummy call to make sure the time is not shifted.
889 */
890 if (ctl->universal)
891 rc = settimeofday(tv_null, &tz_utc);
892
893 /* Now we set the real timezone. Due to the above dummy call, this will
894 * only warp the systemtime if the RTC is not in UTC. */
895 if (!rc)
896 rc = settimeofday(tv_null, &tz);
897
898 if (rc) {
899 if (errno == EPERM) {
900 warnx(_
901 ("Must be superuser to set system clock."));
902 retcode = EX_NOPERM;
903 } else {
904 warn(_("settimeofday() failed"));
905 retcode = 1;
906 }
907 } else
908 retcode = 0;
909 }
910 return retcode;
911 }
912
913 /*
914 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
915 * to facilitate future drift calculations based on this set point.
916 *
917 * With the --update-drift option:
918 * Update the drift factor in <*adjtime_p> based on the fact that the
919 * Hardware Clock was just calibrated to <nowtime> and before that was
920 * set to the <hclocktime> time scale.
921 *
922 * EXCEPT: if <hclock_valid> is false, assume Hardware Clock was not set
923 * before to anything meaningful and regular adjustments have not been done,
924 * so don't adjust the drift factor.
925 */
926 static void
927 adjust_drift_factor(const struct hwclock_control *ctl,
928 struct adjtime *adjtime_p,
929 const struct timeval nowtime,
930 const bool hclock_valid,
931 const struct timeval hclocktime)
932 {
933 if (!ctl->update) {
934 if (ctl->debug)
935 printf(_("Not adjusting drift factor because the "
936 "--update-drift option was not used.\n"));
937 } else if (!hclock_valid) {
938 if (ctl->debug)
939 printf(_("Not adjusting drift factor because the "
940 "Hardware Clock previously contained "
941 "garbage.\n"));
942 } else if (adjtime_p->last_calib_time == 0) {
943 if (ctl->debug)
944 printf(_("Not adjusting drift factor because last "
945 "calibration time is zero,\n"
946 "so history is bad and calibration startover "
947 "is necessary.\n"));
948 } else if ((hclocktime.tv_sec - adjtime_p->last_calib_time) < 4 * 60 * 60) {
949 if (ctl->debug)
950 printf(_("Not adjusting drift factor because it has "
951 "been less than four hours since the last "
952 "calibration.\n"));
953 } else {
954 /*
955 * At adjustment time we drift correct the hardware clock
956 * according to the contents of the adjtime file and refresh
957 * its last adjusted timestamp.
958 *
959 * At calibration time we set the Hardware Clock and refresh
960 * both timestamps in <*adjtime_p>.
961 *
962 * Here, with the --update-drift option, we also update the
963 * drift factor in <*adjtime_p>.
964 *
965 * Let us do computation in doubles. (Floats almost suffice,
966 * but 195 days + 1 second equals 195 days in floats.)
967 */
968 const double sec_per_day = 24.0 * 60.0 * 60.0;
969 double factor_adjust;
970 double drift_factor;
971 struct timeval last_calib;
972
973 last_calib = t2tv(adjtime_p->last_calib_time);
974 /*
975 * Correction to apply to the current drift factor.
976 *
977 * Simplified: uncorrected_drift / days_since_calibration.
978 *
979 * hclocktime is fully corrected with the current drift factor.
980 * Its difference from nowtime is the missed drift correction.
981 */
982 factor_adjust = time_diff(nowtime, hclocktime) /
983 (time_diff(nowtime, last_calib) / sec_per_day);
984
985 drift_factor = adjtime_p->drift_factor + factor_adjust;
986 if (fabs(drift_factor) > MAX_DRIFT) {
987 if (ctl->debug)
988 printf(_("Clock drift factor was calculated as "
989 "%f seconds/day.\n"
990 "It is far too much. Resetting to zero.\n"),
991 drift_factor);
992 drift_factor = 0;
993 } else {
994 if (ctl->debug)
995 printf(_("Clock drifted %f seconds in the past "
996 "%f seconds\nin spite of a drift factor of "
997 "%f seconds/day.\n"
998 "Adjusting drift factor by %f seconds/day\n"),
999 time_diff(nowtime, hclocktime),
1000 time_diff(nowtime, last_calib),
1001 adjtime_p->drift_factor, factor_adjust);
1002 }
1003
1004 adjtime_p->drift_factor = drift_factor;
1005 }
1006 adjtime_p->last_calib_time = nowtime.tv_sec;
1007
1008 adjtime_p->last_adj_time = nowtime.tv_sec;
1009
1010 adjtime_p->not_adjusted = 0;
1011
1012 adjtime_p->dirty = TRUE;
1013 }
1014
1015 /*
1016 * Calculate the drift correction currently needed for the
1017 * Hardware Clock based on the last time it was adjusted,
1018 * and the current drift factor, as stored in the adjtime file.
1019 *
1020 * The total drift adjustment needed is stored at tdrift_p.
1021 *
1022 */
1023 static void
1024 calculate_adjustment(const struct hwclock_control *ctl,
1025 const double factor,
1026 const time_t last_time,
1027 const double not_adjusted,
1028 const time_t systime, struct timeval *tdrift_p)
1029 {
1030 double exact_adjustment;
1031
1032 exact_adjustment =
1033 ((double)(systime - last_time)) * factor / (24 * 60 * 60)
1034 + not_adjusted;
1035 tdrift_p->tv_sec = (time_t) floor(exact_adjustment);
1036 tdrift_p->tv_usec = (exact_adjustment -
1037 (double)tdrift_p->tv_sec) * 1E6;
1038 if (ctl->debug) {
1039 printf(P_("Time since last adjustment is %ld second\n",
1040 "Time since last adjustment is %ld seconds\n",
1041 (systime - last_time)),
1042 (systime - last_time));
1043 printf(_("Calculated Hardware Clock drift is %ld.%06ld seconds\n"),
1044 tdrift_p->tv_sec, tdrift_p->tv_usec);
1045 }
1046 }
1047
1048 /*
1049 * Write the contents of the <adjtime> structure to its disk file.
1050 *
1051 * But if the contents are clean (unchanged since read from disk), don't
1052 * bother.
1053 */
1054 static void save_adjtime(const struct hwclock_control *ctl,
1055 const struct adjtime *adjtime)
1056 {
1057 char *content; /* Stuff to write to disk file */
1058 FILE *fp;
1059 int err = 0;
1060
1061 if (!adjtime->dirty)
1062 return;
1063
1064 xasprintf(&content, "%f %ld %f\n%ld\n%s\n",
1065 adjtime->drift_factor,
1066 adjtime->last_adj_time,
1067 adjtime->not_adjusted,
1068 adjtime->last_calib_time,
1069 (adjtime->local_utc == LOCAL) ? "LOCAL" : "UTC");
1070
1071 if (ctl->testing) {
1072 printf(_
1073 ("Not updating adjtime file because of testing mode.\n"));
1074 printf(_("Would have written the following to %s:\n%s"),
1075 ctl->adj_file_name, content);
1076 free(content);
1077 return;
1078 }
1079
1080 fp = fopen(ctl->adj_file_name, "w");
1081 if (fp == NULL) {
1082 warn(_("Could not open file with the clock adjustment parameters "
1083 "in it (%s) for writing"), ctl->adj_file_name);
1084 err = 1;
1085 } else if (fputs(content, fp) < 0 || close_stream(fp) != 0) {
1086 warn(_("Could not update file with the clock adjustment "
1087 "parameters (%s) in it"), ctl->adj_file_name);
1088 err = 1;
1089 }
1090 free(content);
1091 if (err)
1092 warnx(_("Drift adjustment parameters not updated."));
1093 }
1094
1095 /*
1096 * Do the adjustment requested, by 1) setting the Hardware Clock (if
1097 * necessary), and 2) updating the last-adjusted time in the adjtime
1098 * structure.
1099 *
1100 * Do not update anything if the Hardware Clock does not currently present a
1101 * valid time.
1102 *
1103 * <hclock_valid> means the Hardware Clock contains a valid time.
1104 *
1105 * <hclocktime> is the drift corrected time read from the Hardware Clock.
1106 *
1107 * <read_time> was the system time when the <hclocktime> was read, which due
1108 * to computational delay could be a short time ago. It is used to define a
1109 * trigger point for setting the Hardware Clock. The fractional part of the
1110 * Hardware clock set time is subtracted from read_time to 'refer back', or
1111 * delay, the trigger point. Fractional parts must be accounted for in this
1112 * way, because the Hardware Clock can only be set to a whole second.
1113 *
1114 * <universal>: the Hardware Clock is kept in UTC.
1115 *
1116 * <testing>: We are running in test mode (no updating of clock).
1117 *
1118 */
1119 static void
1120 do_adjustment(const struct hwclock_control *ctl, struct adjtime *adjtime_p,
1121 const bool hclock_valid, const struct timeval hclocktime,
1122 const struct timeval read_time)
1123 {
1124 if (!hclock_valid) {
1125 warnx(_("The Hardware Clock does not contain a valid time, "
1126 "so we cannot adjust it."));
1127 adjtime_p->last_calib_time = 0; /* calibration startover is required */
1128 adjtime_p->last_adj_time = 0;
1129 adjtime_p->not_adjusted = 0;
1130 adjtime_p->dirty = TRUE;
1131 } else if (adjtime_p->last_adj_time == 0) {
1132 if (ctl->debug)
1133 printf(_("Not setting clock because last adjustment time is zero, "
1134 "so history is bad.\n"));
1135 } else if (fabs(adjtime_p->drift_factor) > MAX_DRIFT) {
1136 if (ctl->debug)
1137 printf(_("Not setting clock because drift factor %f is far too high.\n"),
1138 adjtime_p->drift_factor);
1139 } else {
1140 set_hardware_clock_exact(ctl, hclocktime.tv_sec,
1141 time_inc(read_time,
1142 -(hclocktime.tv_usec / 1E6)));
1143 adjtime_p->last_adj_time = hclocktime.tv_sec;
1144 adjtime_p->not_adjusted = 0;
1145 adjtime_p->dirty = TRUE;
1146 }
1147 }
1148
1149 static void determine_clock_access_method(const struct hwclock_control *ctl)
1150 {
1151 ur = NULL;
1152
1153 if (ctl->directisa)
1154 ur = probe_for_cmos_clock();
1155 #ifdef __linux__
1156 if (!ur)
1157 ur = probe_for_rtc_clock(ctl);
1158 #endif
1159 if (ur) {
1160 if (ctl->debug)
1161 puts(ur->interface_name);
1162
1163 } else {
1164 if (ctl->debug)
1165 printf(_("No usable clock interface found.\n"));
1166 warnx(_("Cannot access the Hardware Clock via "
1167 "any known method."));
1168 if (!ctl->debug)
1169 warnx(_("Use the --debug option to see the "
1170 "details of our search for an access "
1171 "method."));
1172 hwclock_exit(ctl, EX_SOFTWARE);
1173 }
1174 }
1175
1176 /*
1177 * Do all the normal work of hwclock - read, set clock, etc.
1178 *
1179 * Issue output to stdout and error message to stderr where appropriate.
1180 *
1181 * Return rc == 0 if everything went OK, rc != 0 if not.
1182 */
1183 static int
1184 manipulate_clock(const struct hwclock_control *ctl, const time_t set_time,
1185 const struct timeval startup_time, struct adjtime *adjtime)
1186 {
1187 /* The time at which we read the Hardware Clock */
1188 struct timeval read_time;
1189 /*
1190 * The Hardware Clock gives us a valid time, or at
1191 * least something close enough to fool mktime().
1192 */
1193 bool hclock_valid = FALSE;
1194 /*
1195 * Tick synchronized time read from the Hardware Clock and
1196 * then drift correct for all operations except --show.
1197 */
1198 struct timeval hclocktime = { 0, 0 };
1199 /* Total Hardware Clock drift correction needed. */
1200 struct timeval tdrift;
1201 /* local return code */
1202 int rc = 0;
1203
1204 if (!ctl->systz && !ctl->predict)
1205 if (ur->get_permissions())
1206 return EX_NOPERM;
1207
1208 if ((ctl->set || ctl->systohc || ctl->adjust) &&
1209 (adjtime->local_utc == UTC) != ctl->universal) {
1210 adjtime->local_utc = ctl->universal ? UTC : LOCAL;
1211 adjtime->dirty = TRUE;
1212 }
1213
1214 if (ctl->show || ctl->get || ctl->adjust || ctl->hctosys
1215 || (!ctl->noadjfile && !ctl->systz && !ctl->predict)) {
1216 /* data from HW-clock are required */
1217 rc = synchronize_to_clock_tick(ctl);
1218
1219 /*
1220 * We don't error out if the user is attempting to set the
1221 * RTC and synchronization timeout happens - the RTC could
1222 * be functioning but contain invalid time data so we still
1223 * want to allow a user to set the RTC time.
1224 */
1225 if (rc == RTC_BUSYWAIT_FAILED && !ctl->set && !ctl->systohc)
1226 return EX_IOERR;
1227 gettimeofday(&read_time, NULL);
1228
1229 /*
1230 * If we can't synchronize to a clock tick,
1231 * we likely can't read from the RTC so
1232 * don't bother reading it again.
1233 */
1234 if (!rc) {
1235 rc = read_hardware_clock(ctl, &hclock_valid,
1236 &hclocktime.tv_sec);
1237 if (rc && !ctl->set && !ctl->systohc)
1238 return EX_IOERR;
1239 }
1240 }
1241 /*
1242 * Calculate Hardware Clock drift for --predict with the user
1243 * supplied --date option time, and with the time read from the
1244 * Hardware Clock for all other operations. Apply drift correction
1245 * to the Hardware Clock time for everything except --show and
1246 * --predict. For --predict negate the drift correction, because we
1247 * want to 'predict' a future Hardware Clock time that includes drift.
1248 */
1249 hclocktime = ctl->predict ? t2tv(set_time) : hclocktime;
1250 calculate_adjustment(ctl, adjtime->drift_factor,
1251 adjtime->last_adj_time,
1252 adjtime->not_adjusted,
1253 hclocktime.tv_sec, &tdrift);
1254 if (!ctl->show && !ctl->predict)
1255 hclocktime = time_inc(tdrift, hclocktime.tv_sec);
1256 if (ctl->show || ctl->get) {
1257 display_time(hclock_valid,
1258 time_inc(hclocktime, -time_diff
1259 (read_time, startup_time)));
1260 } else if (ctl->set) {
1261 set_hardware_clock_exact(ctl, set_time, startup_time);
1262 if (!ctl->noadjfile)
1263 adjust_drift_factor(ctl, adjtime,
1264 time_inc(t2tv(set_time), time_diff
1265 (read_time, startup_time)),
1266 hclock_valid, hclocktime);
1267 } else if (ctl->adjust) {
1268 if (tdrift.tv_sec > 0 || tdrift.tv_sec < -1)
1269 do_adjustment(ctl, adjtime, hclock_valid,
1270 hclocktime, read_time);
1271 else
1272 printf(_("Needed adjustment is less than one second, "
1273 "so not setting clock.\n"));
1274 } else if (ctl->systohc) {
1275 struct timeval nowtime, reftime;
1276 /*
1277 * We can only set_hardware_clock_exact to a
1278 * whole seconds time, so we set it with
1279 * reference to the most recent whole
1280 * seconds time.
1281 */
1282 gettimeofday(&nowtime, NULL);
1283 reftime.tv_sec = nowtime.tv_sec;
1284 reftime.tv_usec = 0;
1285 set_hardware_clock_exact(ctl, (time_t) reftime.tv_sec, reftime);
1286 if (!ctl->noadjfile)
1287 adjust_drift_factor(ctl, adjtime, nowtime,
1288 hclock_valid, hclocktime);
1289 } else if (ctl->hctosys) {
1290 rc = set_system_clock(ctl, hclock_valid, hclocktime);
1291 if (rc) {
1292 printf(_("Unable to set system clock.\n"));
1293 return rc;
1294 }
1295 } else if (ctl->systz) {
1296 rc = set_system_clock_timezone(ctl);
1297 if (rc) {
1298 printf(_("Unable to set system clock.\n"));
1299 return rc;
1300 }
1301 } else if (ctl->predict) {
1302 hclocktime = time_inc(hclocktime, (double)
1303 -(tdrift.tv_sec + tdrift.tv_usec / 1E6));
1304 if (ctl->debug) {
1305 printf(_
1306 ("At %ld seconds after 1969, RTC is predicted to read %ld seconds after 1969.\n"),
1307 set_time, hclocktime.tv_sec);
1308 }
1309 display_time(TRUE, hclocktime);
1310 }
1311 if (!ctl->noadjfile)
1312 save_adjtime(ctl, adjtime);
1313 return 0;
1314 }
1315
1316 /*
1317 * Get or set the Hardware Clock epoch value in the kernel, as appropriate.
1318 * <getepoch>, <setepoch>, and <epoch> are hwclock invocation options.
1319 *
1320 * <epoch> == -1 if the user did not specify an "epoch" option.
1321 */
1322 #ifdef __linux__
1323 /*
1324 * Maintenance note: This should work on non-Alpha machines, but the
1325 * evidence today (98.03.04) indicates that the kernel only keeps the epoch
1326 * value on Alphas. If that is ever fixed, this function should be changed.
1327 */
1328 # ifndef __alpha__
1329 static void
1330 manipulate_epoch(const struct hwclock_control *ctl __attribute__((__unused__)))
1331 {
1332 warnx(_("The kernel keeps an epoch value for the Hardware Clock "
1333 "only on an Alpha machine.\nThis copy of hwclock was built for "
1334 "a machine other than Alpha\n(and thus is presumably not running "
1335 "on an Alpha now). No action taken."));
1336 }
1337 # else
1338 static void
1339 manipulate_epoch(const struct hwclock_control *ctl)
1340 {
1341 if (ctl->getepoch) {
1342 unsigned long epoch;
1343
1344 if (get_epoch_rtc(ctl, &epoch, 0))
1345 warnx(_
1346 ("Unable to get the epoch value from the kernel."));
1347 else
1348 printf(_("Kernel is assuming an epoch value of %lu\n"),
1349 epoch);
1350 } else if (ctl->setepoch) {
1351 if (ctl->epoch_option == 0)
1352 warnx(_
1353 ("To set the epoch value, you must use the 'epoch' "
1354 "option to tell to what value to set it."));
1355 else if (ctl->testing)
1356 printf(_
1357 ("Not setting the epoch to %lu - testing only.\n"),
1358 ctl->epoch_option);
1359 else if (set_epoch_rtc(ctl))
1360 printf(_
1361 ("Unable to set the epoch value in the kernel.\n"));
1362 }
1363 }
1364 # endif /* __alpha__ */
1365 #endif /* __linux__ */
1366
1367 /*
1368 * Compare the system and CMOS time and output the drift
1369 * in 10 second intervals.
1370 */
1371 static int compare_clock(const struct hwclock_control *ctl)
1372 {
1373 struct tm tm;
1374 struct timeval tv;
1375 double time1_sys, time2_sys;
1376 time_t time1_hw, time2_hw;
1377 bool hclock_valid = FALSE, first_pass = TRUE;
1378
1379 if (ur->get_permissions())
1380 return EX_NOPERM;
1381
1382 /* dummy call for increased precision */
1383 gettimeofday(&tv, NULL);
1384
1385 synchronize_to_clock_tick(ctl);
1386 ur->read_hardware_clock(ctl, &tm);
1387
1388 gettimeofday(&tv, NULL);
1389 time1_sys = tv.tv_sec + tv.tv_usec / 1000000.0;
1390
1391 mktime_tz(ctl, tm, &hclock_valid, &time1_hw);
1392
1393 while (1) {
1394 double res;
1395
1396 synchronize_to_clock_tick(ctl);
1397 ur->read_hardware_clock(ctl, &tm);
1398
1399 gettimeofday(&tv, NULL);
1400 time2_sys = tv.tv_sec + tv.tv_usec / 1000000.0;
1401
1402 mktime_tz(ctl, tm, &hclock_valid, &time2_hw);
1403
1404 if ((res = time2_hw - time1_hw))
1405 res = (((double)time1_hw - time1_sys) -
1406 ((double)time2_hw - time2_sys))
1407 / res;
1408
1409 if (!first_pass)
1410 printf("%10.0f %10.6f %15.0f %4.0f\n",
1411 (double) time2_hw, time2_sys, res * 1e6, res *1e4);
1412 else {
1413 first_pass = FALSE;
1414 printf("hw-time system-time freq-offset-ppm tick\n");
1415 printf("%10.0f %10.6f\n", (double) time1_hw, time1_sys);
1416 }
1417 fflush(stdout);
1418 sleep(10);
1419 }
1420
1421 return 0;
1422 }
1423
1424 static void out_version(void)
1425 {
1426 printf(UTIL_LINUX_VERSION);
1427 }
1428
1429 /*
1430 * usage - Output (error and) usage information
1431 *
1432 * This function is called both directly from main to show usage information
1433 * and as fatal function from shhopt if some argument is not understood. In
1434 * case of normal usage info FMT should be NULL. In that case the info is
1435 * printed to stdout. If FMT is given usage will act like fprintf( stderr,
1436 * fmt, ... ), show a usage information and terminate the program
1437 * afterwards.
1438 */
1439 static void usage(const struct hwclock_control *ctl, const char *fmt, ...)
1440 {
1441 FILE *usageto;
1442 va_list ap;
1443
1444 usageto = fmt ? stderr : stdout;
1445
1446 fputs(USAGE_HEADER, usageto);
1447 fputs(_(" hwclock [function] [option...]\n"), usageto);
1448
1449 fputs(USAGE_SEPARATOR, usageto);
1450 fputs(_("Query or set the hardware clock.\n"), usageto);
1451
1452 fputs(_("\nFunctions:\n"), usageto);
1453 fputs(_(" -h, --help show this help text and exit\n"
1454 " -r, --show read hardware clock and print result\n"
1455 " --get read hardware clock and print drift corrected result\n"
1456 " --set set the RTC to the time given with --date\n"), usageto);
1457 fputs(_(" -s, --hctosys set the system time from the hardware clock\n"
1458 " -w, --systohc set the hardware clock from the current system time\n"
1459 " --systz set the system time based on the current timezone\n"
1460 " --adjust adjust the RTC to account for systematic drift since\n"
1461 " the clock was last set or adjusted\n"), usageto);
1462 fputs(_(" -c, --compare periodically compare the system clock with the CMOS clock\n"), usageto);
1463 #ifdef __linux__
1464 fputs(_(" --getepoch print out the kernel's hardware clock epoch value\n"
1465 " --setepoch set the kernel's hardware clock epoch value to the \n"
1466 " value given with --epoch\n"), usageto);
1467 #endif
1468 fputs(_(" --predict predict RTC reading at time given with --date\n"
1469 " -V, --version display version information and exit\n"), usageto);
1470
1471 fputs(USAGE_OPTIONS, usageto);
1472 fputs(_(" -u, --utc the hardware clock is kept in UTC\n"
1473 " --localtime the hardware clock is kept in local time\n"), usageto);
1474 #ifdef __linux__
1475 fputs(_(" -f, --rtc <file> special /dev/... file to use instead of default\n"), usageto);
1476 #endif
1477 fprintf(usageto, _(
1478 " --directisa access the ISA bus directly instead of %s\n"
1479 " --badyear ignore RTC's year because the BIOS is broken\n"
1480 " --date <time> specifies the time to which to set the hardware clock\n"
1481 " --epoch <year> specifies the year which is the beginning of the\n"
1482 " hardware clock's epoch value\n"), _PATH_RTC_DEV);
1483 fprintf(usageto, _(
1484 " --update-drift update drift factor in %1$s (requires\n"
1485 " --set or --systohc)\n"
1486 " --noadjfile do not access %1$s; this requires the use of\n"
1487 " either --utc or --localtime\n"
1488 " --adjfile <file> specifies the path to the adjust file;\n"
1489 " the default is %1$s\n"), _PATH_ADJTIME);
1490 fputs(_(" --test do not update anything, just show what would happen\n"
1491 " -D, --debug debugging mode\n" "\n"), usageto);
1492 #ifdef __alpha__
1493 fputs(_(" -J|--jensen, -A|--arc, -S|--srm, -F|--funky-toy\n"
1494 " tell hwclock the type of Alpha you have (see hwclock(8))\n"
1495 "\n"), usageto);
1496 #endif
1497
1498 if (fmt) {
1499 va_start(ap, fmt);
1500 vfprintf(usageto, fmt, ap);
1501 va_end(ap);
1502 }
1503
1504 fflush(usageto);
1505 hwclock_exit(ctl, fmt ? EX_USAGE : EX_OK);
1506 }
1507
1508 /*
1509 * Returns:
1510 * EX_USAGE: bad invocation
1511 * EX_NOPERM: no permission
1512 * EX_OSFILE: cannot open /dev/rtc or /etc/adjtime
1513 * EX_IOERR: ioctl error getting or setting the time
1514 * 0: OK (or not)
1515 * 1: failure
1516 */
1517 int main(int argc, char **argv)
1518 {
1519 struct hwclock_control ctl = { 0 };
1520 struct timeval startup_time;
1521 struct adjtime adjtime = { 0 };
1522 /*
1523 * The time we started up, in seconds into the epoch, including
1524 * fractions.
1525 */
1526 time_t set_time = 0; /* Time to which user said to set Hardware Clock */
1527 int rc, c;
1528
1529 /* Long only options. */
1530 enum {
1531 OPT_ADJFILE = CHAR_MAX + 1,
1532 OPT_BADYEAR,
1533 OPT_DATE,
1534 OPT_DIRECTISA,
1535 OPT_EPOCH,
1536 OPT_GET,
1537 OPT_GETEPOCH,
1538 OPT_LOCALTIME,
1539 OPT_NOADJFILE,
1540 OPT_PREDICT_HC,
1541 OPT_SET,
1542 OPT_SETEPOCH,
1543 OPT_SYSTZ,
1544 OPT_TEST,
1545 OPT_UPDATE
1546 };
1547
1548 static const struct option longopts[] = {
1549 {"adjust", 0, 0, 'a'},
1550 {"compare", 0, 0, 'c'},
1551 {"help", 0, 0, 'h'},
1552 {"show", 0, 0, 'r'},
1553 {"hctosys", 0, 0, 's'},
1554 {"utc", 0, 0, 'u'},
1555 {"version", 0, 0, 'v'},
1556 {"systohc", 0, 0, 'w'},
1557 {"debug", 0, 0, 'D'},
1558 #ifdef __alpha__
1559 {"ARC", 0, 0, 'A'},
1560 {"arc", 0, 0, 'A'},
1561 {"Jensen", 0, 0, 'J'},
1562 {"jensen", 0, 0, 'J'},
1563 {"SRM", 0, 0, 'S'},
1564 {"srm", 0, 0, 'S'},
1565 {"funky-toy", 0, 0, 'F'},
1566 #endif
1567 {"set", 0, 0, OPT_SET},
1568 #ifdef __linux__
1569 {"getepoch", 0, 0, OPT_GETEPOCH},
1570 {"setepoch", 0, 0, OPT_SETEPOCH},
1571 #endif
1572 {"noadjfile", 0, 0, OPT_NOADJFILE},
1573 {"localtime", 0, 0, OPT_LOCALTIME},
1574 {"badyear", 0, 0, OPT_BADYEAR},
1575 {"directisa", 0, 0, OPT_DIRECTISA},
1576 {"test", 0, 0, OPT_TEST},
1577 {"date", 1, 0, OPT_DATE},
1578 {"epoch", 1, 0, OPT_EPOCH},
1579 #ifdef __linux__
1580 {"rtc", 1, 0, 'f'},
1581 #endif
1582 {"adjfile", 1, 0, OPT_ADJFILE},
1583 {"systz", 0, 0, OPT_SYSTZ},
1584 {"predict-hc", 0, 0, OPT_PREDICT_HC},
1585 {"get", 0, 0, OPT_GET},
1586 {"update-drift",0, 0, OPT_UPDATE},
1587 {NULL, 0, NULL, 0}
1588 };
1589
1590 static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */
1591 { 'a','r','s','w',
1592 OPT_GET, OPT_GETEPOCH, OPT_PREDICT_HC,
1593 OPT_SET, OPT_SETEPOCH, OPT_SYSTZ },
1594 { 'u', OPT_LOCALTIME},
1595 { OPT_ADJFILE, OPT_NOADJFILE },
1596 { OPT_NOADJFILE, OPT_UPDATE },
1597 { 0 }
1598 };
1599 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1600
1601 /* Remember what time we were invoked */
1602 gettimeofday(&startup_time, NULL);
1603
1604 #ifdef HAVE_LIBAUDIT
1605 hwaudit_fd = audit_open();
1606 if (hwaudit_fd < 0 && !(errno == EINVAL || errno == EPROTONOSUPPORT ||
1607 errno == EAFNOSUPPORT)) {
1608 /*
1609 * You get these error codes only when the kernel doesn't
1610 * have audit compiled in.
1611 */
1612 warnx(_("Unable to connect to audit system"));
1613 return EX_NOPERM;
1614 }
1615 #endif
1616 setlocale(LC_ALL, "");
1617 #ifdef LC_NUMERIC
1618 /*
1619 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1620 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1621 * - gqueri@mail.dotcom.fr
1622 */
1623 setlocale(LC_NUMERIC, "C");
1624 #endif
1625 bindtextdomain(PACKAGE, LOCALEDIR);
1626 textdomain(PACKAGE);
1627 atexit(close_stdout);
1628
1629 while ((c = getopt_long(argc, argv,
1630 "?hvVDacrsuwAJSFf:", longopts, NULL)) != -1) {
1631
1632 err_exclusive_options(c, longopts, excl, excl_st);
1633
1634 switch (c) {
1635 case 'D':
1636 ctl.debug++;
1637 break;
1638 case 'a':
1639 ctl.adjust = 1;
1640 break;
1641 case 'c':
1642 ctl.compare = 1;
1643 break;
1644 case 'r':
1645 ctl.show = 1;
1646 break;
1647 case 's':
1648 ctl.hctosys = 1;
1649 break;
1650 case 'u':
1651 ctl.utc = 1;
1652 break;
1653 case 'w':
1654 ctl.systohc = 1;
1655 break;
1656 #ifdef __alpha__
1657 case 'A':
1658 ctl.ARCconsole = 1;
1659 break;
1660 case 'J':
1661 ctl.Jensen = 1;
1662 break;
1663 case 'S':
1664 ctl.SRM = 1;
1665 break;
1666 case 'F':
1667 ctl.funky_toy = 1;
1668 break;
1669 #endif
1670 case OPT_SET:
1671 ctl.set = 1;
1672 break;
1673 #ifdef __linux__
1674 case OPT_GETEPOCH:
1675 ctl.getepoch = 1;
1676 break;
1677 case OPT_SETEPOCH:
1678 ctl.setepoch = 1;
1679 break;
1680 #endif
1681 case OPT_NOADJFILE:
1682 ctl.noadjfile = 1;
1683 break;
1684 case OPT_LOCALTIME:
1685 ctl.local_opt = 1; /* --localtime */
1686 break;
1687 case OPT_BADYEAR:
1688 ctl.badyear = 1;
1689 break;
1690 case OPT_DIRECTISA:
1691 ctl.directisa = 1;
1692 break;
1693 case OPT_TEST:
1694 ctl.testing = 1; /* --test */
1695 break;
1696 case OPT_DATE:
1697 ctl.date_opt = optarg; /* --date */
1698 break;
1699 case OPT_EPOCH:
1700 ctl.epoch_option = /* --epoch */
1701 strtoul_or_err(optarg, _("invalid epoch argument"));
1702 break;
1703 case OPT_ADJFILE:
1704 ctl.adj_file_name = optarg; /* --adjfile */
1705 break;
1706 case OPT_SYSTZ:
1707 ctl.systz = 1; /* --systz */
1708 break;
1709 case OPT_PREDICT_HC:
1710 ctl.predict = 1; /* --predict-hc */
1711 break;
1712 case OPT_GET:
1713 ctl.get = 1; /* --get */
1714 break;
1715 case OPT_UPDATE:
1716 ctl.update = 1; /* --update-drift */
1717 break;
1718 #ifdef __linux__
1719 case 'f':
1720 ctl.rtc_dev_name = optarg; /* --rtc */
1721 break;
1722 #endif
1723 case 'v': /* --version */
1724 case 'V':
1725 out_version();
1726 return 0;
1727 case 'h': /* --help */
1728 case '?':
1729 default:
1730 usage(&ctl, NULL);
1731 }
1732 }
1733
1734 argc -= optind;
1735 argv += optind;
1736
1737 #ifdef HAVE_LIBAUDIT
1738 if (!ctl.testing) {
1739 if (ctl.adjust || ctl.hctosys || ctl.systohc ||
1740 ctl.set || ctl.setepoch) {
1741 ctl.hwaudit_on = 1;
1742 }
1743 }
1744 #endif
1745 if (argc > 0) {
1746 usage(&ctl, _("%s takes no non-option arguments. "
1747 "You supplied %d.\n"), program_invocation_short_name,
1748 argc);
1749 }
1750
1751 if (!ctl.adj_file_name)
1752 ctl.adj_file_name = _PATH_ADJTIME;
1753
1754 if (ctl.noadjfile && !ctl.utc && !ctl.local_opt) {
1755 warnx(_("With --noadjfile, you must specify "
1756 "either --utc or --localtime"));
1757 hwclock_exit(&ctl, EX_USAGE);
1758 }
1759 #ifdef __alpha__
1760 set_cmos_epoch(&ctl);
1761 set_cmos_access(&ctl);
1762 #endif
1763
1764 if (ctl.set || ctl.predict) {
1765 rc = interpret_date_string(&ctl, &set_time);
1766 /* (time-consuming) */
1767 if (rc != 0) {
1768 warnx(_("No usable set-to time. "
1769 "Cannot set clock."));
1770 hwclock_exit(&ctl, EX_USAGE);
1771 }
1772 }
1773
1774 if (!(ctl.show | ctl.set | ctl.systohc | ctl.hctosys |
1775 ctl.systz | ctl.adjust | ctl.getepoch | ctl.setepoch |
1776 ctl.predict | ctl.compare | ctl.get))
1777 ctl.show = 1; /* default to show */
1778
1779 #ifdef __linux__
1780 if (ctl.getepoch || ctl.setepoch) {
1781 manipulate_epoch(&ctl);
1782 hwclock_exit(&ctl, EX_OK);
1783 }
1784 #endif
1785
1786 if (ctl.debug)
1787 out_version();
1788
1789 if (!ctl.systz && !ctl.predict)
1790 determine_clock_access_method(&ctl);
1791
1792 if (!ctl.noadjfile && !(ctl.systz && (ctl.utc || ctl.local_opt))) {
1793 if ((rc = read_adjtime(&ctl, &adjtime)) != 0)
1794 hwclock_exit(&ctl, rc);
1795 } else
1796 /* Avoid writing adjtime file if we don't have to. */
1797 adjtime.dirty = FALSE;
1798 ctl.universal = hw_clock_is_utc(&ctl, adjtime);
1799 if (ctl.compare) {
1800 if (compare_clock(&ctl))
1801 hwclock_exit(&ctl, EX_NOPERM);
1802
1803 rc = EX_OK;
1804 } else
1805 rc = manipulate_clock(&ctl, set_time, startup_time, &adjtime);
1806
1807 hwclock_exit(&ctl, rc);
1808 return rc; /* Not reached */
1809 }
1810
1811 void __attribute__((__noreturn__))
1812 hwclock_exit(const struct hwclock_control *ctl
1813 #ifndef HAVE_LIBAUDIT
1814 __attribute__((__unused__))
1815 #endif
1816 , int status)
1817 {
1818 #ifdef HAVE_LIBAUDIT
1819 if (ctl->hwaudit_on) {
1820 audit_log_user_message(hwaudit_fd, AUDIT_USYS_CONFIG,
1821 "op=change-system-time", NULL, NULL, NULL,
1822 status ? 0 : 1);
1823 close(hwaudit_fd);
1824 }
1825 #endif
1826 exit(status);
1827 }
1828
1829 /*
1830 * History of this program:
1831 *
1832 * 98.08.12 BJH Version 2.4
1833 *
1834 * Don't use century byte from Hardware Clock. Add comments telling why.
1835 *
1836 * 98.06.20 BJH Version 2.3.
1837 *
1838 * Make --hctosys set the kernel timezone from TZ environment variable
1839 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1840 *
1841 * 98.03.05 BJH. Version 2.2.
1842 *
1843 * Add --getepoch and --setepoch.
1844 *
1845 * Fix some word length things so it works on Alpha.
1846 *
1847 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1848 * case, busywait for the top of a second instead of blocking and waiting
1849 * for the update complete interrupt.
1850 *
1851 * Fix a bunch of bugs too numerous to mention.
1852 *
1853 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1854 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1855 * job (jei@iclnl.icl.nl).
1856 *
1857 * Use the rtc clock access method in preference to the KDGHWCLK method.
1858 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1859 *
1860 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1861 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1862 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1863 * and wrote feature test code to detect absence of rtc headers.
1864 *
1865 ***************************************************************************
1866 * Maintenance notes
1867 *
1868 * To compile this, you must use GNU compiler optimization (-O option) in
1869 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1870 * compile. If you don't optimize, which means the compiler will generate no
1871 * inline functions, the references to these functions in this program will
1872 * be compiled as external references. Since you probably won't be linking
1873 * with any functions by these names, you will have unresolved external
1874 * references when you link.
1875 *
1876 * Here's some info on how we must deal with the time that elapses while
1877 * this program runs: There are two major delays as we run:
1878 *
1879 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1880 * we are synchronized to the Hardware Clock.
1881 * 2) Running the "date" program to interpret the value of our --date
1882 * option.
1883 *
1884 * Reading the /etc/adjtime file is the next biggest source of delay and
1885 * uncertainty.
1886 *
1887 * The user wants to know what time it was at the moment he invoked us, not
1888 * some arbitrary time later. And in setting the clock, he is giving us the
1889 * time at the moment we are invoked, so if we set the clock some time
1890 * later, we have to add some time to that.
1891 *
1892 * So we check the system time as soon as we start up, then run "date" and
1893 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1894 * edge, then check the system time again to see how much time we spent. We
1895 * immediately read the clock then and (if appropriate) report that time,
1896 * and additionally, the delay we measured.
1897 *
1898 * If we're setting the clock to a time given by the user, we wait some more
1899 * so that the total delay is an integral number of seconds, then set the
1900 * Hardware Clock to the time the user requested plus that integral number
1901 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1902 *
1903 * If we're setting the clock to the system clock value, we wait for the
1904 * system clock to reach the top of a second, and then set the Hardware
1905 * Clock to the system clock's value.
1906 *
1907 * Here's an interesting point about setting the Hardware Clock: On my
1908 * machine, when you set it, it sets to that precise time. But one can
1909 * imagine another clock whose update oscillator marches on a steady one
1910 * second period, so updating the clock between any two oscillator ticks is
1911 * the same as updating it right at the earlier tick. To avoid any
1912 * complications that might cause, we set the clock as soon as possible
1913 * after an oscillator tick.
1914 *
1915 * About synchronizing to the Hardware Clock when reading the time: The
1916 * precision of the Hardware Clock counters themselves is one second. You
1917 * can't read the counters and find out that is 12:01:02.5. But if you
1918 * consider the location in time of the counter's ticks as part of its
1919 * value, then its precision is as infinite as time is continuous! What I'm
1920 * saying is this: To find out the _exact_ time in the hardware clock, we
1921 * wait until the next clock tick (the next time the second counter changes)
1922 * and measure how long we had to wait. We then read the value of the clock
1923 * counters and subtract the wait time and we know precisely what time it
1924 * was when we set out to query the time.
1925 *
1926 * hwclock uses this method, and considers the Hardware Clock to have
1927 * infinite precision.
1928 */