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>.
9 * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19.
10 * The new program is called hwclock. New features:
12 * - You can set the hardware clock without also modifying the system
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.
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.
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>.
27 * Distributed under GPL
30 * Explanation of `adjusting' (Rob Hooft):
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.
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
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
45 * 3) the remaining part of a second which was leftover after the last
48 * Installation and use of this program:
50 * a) create a file '/etc/adjtime' containing as the first and only
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'
73 #include "closestream.h"
76 #include "pathnames.h"
78 #include "timeutils.h"
86 static int hwaudit_fd
= -1;
89 UL_DEBUG_DEFINE_MASK(hwclock
);
90 UL_DEBUG_DEFINE_MASKNAMES(hwclock
) = UL_DEBUG_EMPTY_MASKNAMES
;
92 /* The struct that holds our hardware access routines */
93 static struct clock_ops
*ur
;
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
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).
112 time_t last_adj_time
;
115 time_t last_calib_time
;
117 * The most recent time that we set the clock from an external
118 * authority (as opposed to just doing a drift adjustment)
121 enum a_local_utc
{ UTC
= 0, LOCAL
, UNKNOWN
} local_utc
;
123 * To which time zone, local or UTC, we most recently set the
128 static void hwclock_init_debug(const char *str
)
130 __UL_INIT_DEBUG_FROM_STRING(hwclock
, HWCLOCK_DEBUG_
, 0, str
);
132 DBG(INIT
, ul_debug("hwclock debug mask: 0x%04x", hwclock_debug_mask
));
133 DBG(INIT
, ul_debug("hwclock version: %s", PACKAGE_STRING
));
136 /* FOR TESTING ONLY: inject random delays of up to 1000ms */
137 static void up_to_1000ms_sleep(void)
139 int usec
= random() % 1000000;
141 DBG(RANDOM_SLEEP
, ul_debug("sleeping ~%d usec", usec
));
146 * time_t to timeval conversion.
148 static struct timeval
t2tv(time_t timet
)
150 struct timeval rettimeval
;
152 rettimeval
.tv_sec
= timet
;
153 rettimeval
.tv_usec
= 0;
158 * The difference in seconds between two times in "timeval" format.
160 double time_diff(struct timeval subtrahend
, struct timeval subtractor
)
162 return (subtrahend
.tv_sec
- subtractor
.tv_sec
)
163 + (subtrahend
.tv_usec
- subtractor
.tv_usec
) / 1E6
;
167 * The time, in "timeval" format, which is <increment> seconds after the
168 * time <addend>. Of course, <increment> may be negative.
170 static struct timeval
time_inc(struct timeval addend
, double increment
)
172 struct timeval newtime
;
174 newtime
.tv_sec
= addend
.tv_sec
+ (int)increment
;
175 newtime
.tv_usec
= addend
.tv_usec
+ (increment
- (int)increment
) * 1E6
;
178 * Now adjust it so that the microsecond value is between 0 and 1
181 if (newtime
.tv_usec
< 0) {
182 newtime
.tv_usec
+= 1E6
;
184 } else if (newtime
.tv_usec
>= 1E6
) {
185 newtime
.tv_usec
-= 1E6
;
192 hw_clock_is_utc(const struct hwclock_control
*ctl
,
193 const struct adjtime adjtime
)
198 ret
= 1; /* --utc explicitly given on command line */
199 else if (ctl
->local_opt
)
200 ret
= 0; /* --localtime explicitly given */
202 /* get info from adjtime file - default is UTC */
203 ret
= (adjtime
.local_utc
!= LOCAL
);
205 printf(_("Assuming hardware clock is kept in %s time.\n"),
206 ret
? _("UTC") : _("local"));
211 * Read the adjustment parameters out of the /etc/adjtime file.
213 * Return them as the adjtime structure <*adjtime_p>. Its defaults are
214 * initialized in main().
216 static int read_adjtime(const struct hwclock_control
*ctl
,
217 struct adjtime
*adjtime_p
)
220 char line1
[81]; /* String: first line of adjtime file */
221 char line2
[81]; /* String: second line of adjtime file */
222 char line3
[81]; /* String: third line of adjtime file */
224 if (access(ctl
->adj_file_name
, R_OK
) != 0)
227 adjfile
= fopen(ctl
->adj_file_name
, "r"); /* open file for reading */
228 if (adjfile
== NULL
) {
229 warn(_("cannot open %s"), ctl
->adj_file_name
);
233 if (!fgets(line1
, sizeof(line1
), adjfile
))
234 line1
[0] = '\0'; /* In case fgets fails */
235 if (!fgets(line2
, sizeof(line2
), adjfile
))
236 line2
[0] = '\0'; /* In case fgets fails */
237 if (!fgets(line3
, sizeof(line3
), adjfile
))
238 line3
[0] = '\0'; /* In case fgets fails */
242 sscanf(line1
, "%lf %ld %lf",
243 &adjtime_p
->drift_factor
,
244 &adjtime_p
->last_adj_time
,
245 &adjtime_p
->not_adjusted
);
247 sscanf(line2
, "%ld", &adjtime_p
->last_calib_time
);
249 if (!strcmp(line3
, "UTC\n")) {
250 adjtime_p
->local_utc
= UTC
;
251 } else if (!strcmp(line3
, "LOCAL\n")) {
252 adjtime_p
->local_utc
= LOCAL
;
254 adjtime_p
->local_utc
= UNKNOWN
;
256 warnx(_("Warning: unrecognized third line in adjtime file\n"
257 "(Expected: `UTC' or `LOCAL' or nothing.)"));
263 ("Last drift adjustment done at %ld seconds after 1969\n"),
264 (long)adjtime_p
->last_adj_time
);
265 printf(_("Last calibration done at %ld seconds after 1969\n"),
266 (long)adjtime_p
->last_calib_time
);
267 printf(_("Hardware clock is on %s time\n"),
268 (adjtime_p
->local_utc
==
269 LOCAL
) ? _("local") : (adjtime_p
->local_utc
==
270 UTC
) ? _("UTC") : _("unknown"));
277 * Wait until the falling edge of the Hardware Clock's update flag so that
278 * any time that is read from the clock immediately after we return will be
281 * The clock only has 1 second precision, so it gives the exact time only
282 * once per second, right on the falling edge of the update flag.
284 * We wait (up to one second) either blocked waiting for an rtc device or in
285 * a CPU spin loop. The former is probably not very accurate.
287 * Return 0 if it worked, nonzero if it didn't.
289 static int synchronize_to_clock_tick(const struct hwclock_control
*ctl
)
294 printf(_("Waiting for clock tick...\n"));
296 rc
= ur
->synchronize_to_clock_tick(ctl
);
300 printf(_("...synchronization failed\n"));
302 printf(_("...got clock tick\n"));
309 * Convert a time in broken down format (hours, minutes, etc.) into standard
310 * unix time (seconds into epoch). Return it as *systime_p.
312 * The broken down time is argument <tm>. This broken down time is either
313 * in local time zone or UTC, depending on value of logical argument
314 * "universal". True means it is in UTC.
316 * If the argument contains values that do not constitute a valid time, and
317 * mktime() recognizes this, return *valid_p == false and *systime_p
318 * undefined. However, mktime() sometimes goes ahead and computes a
319 * fictional time "as if" the input values were valid, e.g. if they indicate
320 * the 31st day of April, mktime() may compute the time of May 1. In such a
321 * case, we return the same fictional value mktime() does as *systime_p and
322 * return *valid_p == true.
325 mktime_tz(const struct hwclock_control
*ctl
, struct tm tm
,
331 *systime_p
= timegm(&tm
);
333 *systime_p
= mktime(&tm
);
334 if (*systime_p
== -1) {
336 * This apparently (not specified in mktime() documentation)
337 * means the 'tm' structure does not contain valid values
338 * (however, not containing valid values does _not_ imply
339 * mktime() returns -1).
343 printf(_("Invalid values in hardware clock: "
344 "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"),
345 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
,
346 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
351 ("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
352 "%ld seconds since 1969\n"), tm
.tm_year
+ 1900,
353 tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
, tm
.tm_min
,
354 tm
.tm_sec
, (long)*systime_p
);
360 * Read the hardware clock and return the current time via <tm> argument.
362 * Use the method indicated by <method> argument to access the hardware
366 read_hardware_clock(const struct hwclock_control
*ctl
,
367 int *valid_p
, time_t *systime_p
)
372 err
= ur
->read_hardware_clock(ctl
, &tm
);
378 ("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
379 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
,
380 tm
.tm_min
, tm
.tm_sec
);
381 *valid_p
= mktime_tz(ctl
, tm
, systime_p
);
387 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
388 * according to <universal>.
391 set_hardware_clock(const struct hwclock_control
*ctl
, const time_t newtime
)
393 struct tm new_broken_time
;
395 * Time to which we will set Hardware Clock, in broken down format,
396 * in the time zone of caller's choice
400 gmtime_r(&newtime
, &new_broken_time
);
402 localtime_r(&newtime
, &new_broken_time
);
405 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
406 "= %ld seconds since 1969\n"),
407 new_broken_time
.tm_hour
, new_broken_time
.tm_min
,
408 new_broken_time
.tm_sec
, (long)newtime
);
411 ur
->set_hardware_clock(ctl
, &new_broken_time
);
415 get_hardware_delay(const struct hwclock_control
*ctl
)
417 const char *devpath
, *rtcname
;
422 devpath
= ur
->get_device_path();
426 rtcname
= strrchr(devpath
, '/');
427 if (!rtcname
|| !*(rtcname
+ 1))
431 pc
= ul_new_path("/sys/class/rtc/%s", rtcname
);
434 rc
= ul_path_scanf(pc
, "name", "%128[^\n ]", &name
);
437 if (rc
!= 1 || !*name
)
441 printf(_("RTC type: '%s'\n"), name
);
443 /* MC146818A-compatible (x86) */
444 if (strcmp(name
, "rtc_cmos") == 0)
450 /* Let's be backwardly compatible */
456 * Set the Hardware Clock to the time "sethwtime", in local time zone or
457 * UTC, according to "universal".
459 * Wait for a fraction of a second so that "sethwtime" is the value of the
460 * Hardware Clock as of system time "refsystime", which is in the past. For
461 * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and
462 * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2
463 * seconds since "refsystime") and then set the Hardware Clock to 14:03:07,
464 * thus getting a precise and retroactive setting of the clock. The .5 delay is
465 * default on x86, see --delay and get_hardware_delay().
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).
471 * This function ought to be able to accept set times as fractional times.
472 * Idea for future enhancement.
475 set_hardware_clock_exact(const struct hwclock_control
*ctl
,
476 const time_t sethwtime
,
477 const struct timeval refsystime
)
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
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.
524 time_t newhwtime
= sethwtime
;
525 double target_time_tolerance_secs
= 0.001; /* initial value */
526 double tolerance_incr_secs
= 0.001; /* initial value */
528 struct timeval rtc_set_delay_tv
;
530 struct timeval targetsystime
;
531 struct timeval nowsystime
;
532 struct timeval prevsystime
= refsystime
;
533 double deltavstarget
;
535 if (ctl
->rtc_delay
!= -1.0) /* --delay specified */
536 delay
= ctl
->rtc_delay
;
538 delay
= get_hardware_delay(ctl
);
541 printf(_("Using delay: %.6f seconds\n"), delay
);
543 rtc_set_delay_tv
.tv_sec
= 0;
544 rtc_set_delay_tv
.tv_usec
= delay
* 1E6
;
546 timeradd(&refsystime
, &rtc_set_delay_tv
, &targetsystime
);
551 ON_DBG(RANDOM_SLEEP
, up_to_1000ms_sleep());
553 gettimeofday(&nowsystime
, NULL
);
554 deltavstarget
= time_diff(nowsystime
, targetsystime
);
555 ticksize
= time_diff(nowsystime
, prevsystime
);
556 prevsystime
= nowsystime
;
560 printf(_("time jumped backward %.6f seconds "
561 "to %ld.%06ld - retargeting\n"),
562 ticksize
, nowsystime
.tv_sec
,
564 /* The retarget is handled at the end of the loop. */
565 } else if (deltavstarget
< 0) {
566 /* deltavstarget < 0 if current time < target time */
568 ul_debug("%ld.%06ld < %ld.%06ld (%.6f)",
569 nowsystime
.tv_sec
, nowsystime
.tv_usec
,
570 targetsystime
.tv_sec
,
571 targetsystime
.tv_usec
, deltavstarget
));
572 continue; /* not there yet - keep spinning */
573 } else if (deltavstarget
<= target_time_tolerance_secs
) {
574 /* Close enough to the target time; done waiting. */
576 } else /* (deltavstarget > target_time_tolerance_secs) */ {
578 * We missed our window. Increase the tolerance and
579 * aim for the next opportunity.
582 printf(_("missed it - %ld.%06ld is too far "
583 "past %ld.%06ld (%.6f > %.6f)\n"),
586 targetsystime
.tv_sec
,
587 targetsystime
.tv_usec
,
589 target_time_tolerance_secs
);
590 target_time_tolerance_secs
+= tolerance_incr_secs
;
591 tolerance_incr_secs
*= 2;
595 * Aim for the same offset (tv_usec) within the second in
596 * either the current second (if that offset hasn't arrived
597 * yet), or the next second.
599 if (nowsystime
.tv_usec
< targetsystime
.tv_usec
)
600 targetsystime
.tv_sec
= nowsystime
.tv_sec
;
602 targetsystime
.tv_sec
= nowsystime
.tv_sec
+ 1;
605 newhwtime
= sethwtime
606 + (int)(time_diff(nowsystime
, refsystime
)
607 - delay
/* don't count this */
608 + 0.5 /* for rounding */);
610 printf(_("%ld.%06ld is close enough to %ld.%06ld (%.6f < %.6f)\n"
611 "Set RTC to %ld (%ld + %d; refsystime = %ld.%06ld)\n"),
612 nowsystime
.tv_sec
, nowsystime
.tv_usec
,
613 targetsystime
.tv_sec
, targetsystime
.tv_usec
,
614 deltavstarget
, target_time_tolerance_secs
,
615 newhwtime
, sethwtime
,
616 (int)(newhwtime
- sethwtime
),
617 refsystime
.tv_sec
, refsystime
.tv_usec
);
619 set_hardware_clock(ctl
, newhwtime
);
623 display_time(struct timeval hwctime
)
625 char buf
[ISO_BUFSIZ
];
627 if (strtimeval_iso(&hwctime
, ISO_TIMESTAMP_DOT
, buf
, sizeof(buf
)))
635 * Adjusts System time, sets the kernel's timezone and RTC timescale.
637 * The kernel warp_clock function adjusts the System time according to the
638 * tz.tz_minuteswest argument and sets PCIL (see below). At boot settimeofday(2)
639 * has one-shot access to this function as shown in the table below.
641 * +-------------------------------------------------------------------+
642 * | settimeofday(tv, tz) |
643 * |-------------------------------------------------------------------|
644 * | Arguments | System Time | PCIL | | warp_clock |
645 * | tv | tz | set | warped | set | firsttime | locked |
646 * |---------|---------|---------------|------|-----------|------------|
647 * | pointer | NULL | yes | no | no | 1 | no |
648 * | pointer | pointer | yes | no | no | 0 | yes |
649 * | NULL | ptr2utc | no | no | no | 0 | yes |
650 * | NULL | pointer | no | yes | yes | 0 | yes |
651 * +-------------------------------------------------------------------+
652 * ptr2utc: tz.tz_minuteswest is zero (UTC).
653 * PCIL: persistent_clock_is_local, sets the "11 minute mode" timescale.
654 * firsttime: locks the warp_clock function (initialized to 1 at boot).
656 * +---------------------------------------------------------------------------+
657 * | op | RTC scale | settimeofday calls |
658 * |---------|-----------|-----------------------------------------------------|
659 * | systz | Local | 1) warps system time*, sets PCIL* and kernel tz |
660 * | systz | UTC | 1st) locks warp_clock* 2nd) sets kernel tz |
661 * | hctosys | Local | 1st) sets PCIL* 2nd) sets system time and kernel tz |
662 * | hctosys | UTC | 1) sets system time and kernel tz |
663 * +---------------------------------------------------------------------------+
664 * * only on first call after boot
667 set_system_clock(const struct hwclock_control
*ctl
,
668 const struct timeval newtime
)
673 const struct timezone tz_utc
= { 0 };
675 localtime_r(&newtime
.tv_sec
, &broken
);
676 minuteswest
= -get_gmtoff(&broken
) / 60;
679 if (ctl
->hctosys
&& !ctl
->universal
)
680 printf(_("Calling settimeofday(NULL, %d) to set "
681 "persistent_clock_is_local.\n"), minuteswest
);
682 if (ctl
->systz
&& ctl
->universal
)
683 puts(_("Calling settimeofday(NULL, 0) "
684 "to lock the warp function."));
686 printf(_("Calling settimeofday(%ld.%06ld, %d)\n"),
687 newtime
.tv_sec
, newtime
.tv_usec
, minuteswest
);
689 printf(_("Calling settimeofday(NULL, %d) "), minuteswest
);
691 puts(_("to set the kernel timezone."));
693 puts(_("to warp System time."));
698 const struct timezone tz
= { minuteswest
};
700 if (ctl
->hctosys
&& !ctl
->universal
) /* set PCIL */
701 rc
= settimeofday(NULL
, &tz
);
702 if (ctl
->systz
&& ctl
->universal
) /* lock warp_clock */
703 rc
= settimeofday(NULL
, &tz_utc
);
704 if (!rc
&& ctl
->hctosys
)
705 rc
= settimeofday(&newtime
, &tz
);
707 rc
= settimeofday(NULL
, &tz
);
710 warn(_("settimeofday() failed"));
718 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
719 * to facilitate future drift calculations based on this set point.
721 * With the --update-drift option:
722 * Update the drift factor in <*adjtime_p> based on the fact that the
723 * Hardware Clock was just calibrated to <nowtime> and before that was
724 * set to the <hclocktime> time scale.
727 adjust_drift_factor(const struct hwclock_control
*ctl
,
728 struct adjtime
*adjtime_p
,
729 const struct timeval nowtime
,
730 const struct timeval hclocktime
)
734 printf(_("Not adjusting drift factor because the "
735 "--update-drift option was not used.\n"));
736 } else if (adjtime_p
->last_calib_time
== 0) {
738 printf(_("Not adjusting drift factor because last "
739 "calibration time is zero,\n"
740 "so history is bad and calibration startover "
742 } else if ((hclocktime
.tv_sec
- adjtime_p
->last_calib_time
) < 4 * 60 * 60) {
744 printf(_("Not adjusting drift factor because it has "
745 "been less than four hours since the last "
749 * At adjustment time we drift correct the hardware clock
750 * according to the contents of the adjtime file and refresh
751 * its last adjusted timestamp.
753 * At calibration time we set the Hardware Clock and refresh
754 * both timestamps in <*adjtime_p>.
756 * Here, with the --update-drift option, we also update the
757 * drift factor in <*adjtime_p>.
759 * Let us do computation in doubles. (Floats almost suffice,
760 * but 195 days + 1 second equals 195 days in floats.)
762 const double sec_per_day
= 24.0 * 60.0 * 60.0;
763 double factor_adjust
;
765 struct timeval last_calib
;
767 last_calib
= t2tv(adjtime_p
->last_calib_time
);
769 * Correction to apply to the current drift factor.
771 * Simplified: uncorrected_drift / days_since_calibration.
773 * hclocktime is fully corrected with the current drift factor.
774 * Its difference from nowtime is the missed drift correction.
776 factor_adjust
= time_diff(nowtime
, hclocktime
) /
777 (time_diff(nowtime
, last_calib
) / sec_per_day
);
779 drift_factor
= adjtime_p
->drift_factor
+ factor_adjust
;
780 if (fabs(drift_factor
) > MAX_DRIFT
) {
782 printf(_("Clock drift factor was calculated as "
784 "It is far too much. Resetting to zero.\n"),
789 printf(_("Clock drifted %f seconds in the past "
790 "%f seconds\nin spite of a drift factor of "
792 "Adjusting drift factor by %f seconds/day\n"),
793 time_diff(nowtime
, hclocktime
),
794 time_diff(nowtime
, last_calib
),
795 adjtime_p
->drift_factor
, factor_adjust
);
798 adjtime_p
->drift_factor
= drift_factor
;
800 adjtime_p
->last_calib_time
= nowtime
.tv_sec
;
802 adjtime_p
->last_adj_time
= nowtime
.tv_sec
;
804 adjtime_p
->not_adjusted
= 0;
806 adjtime_p
->dirty
= 1;
810 * Calculate the drift correction currently needed for the
811 * Hardware Clock based on the last time it was adjusted,
812 * and the current drift factor, as stored in the adjtime file.
814 * The total drift adjustment needed is stored at tdrift_p.
818 calculate_adjustment(const struct hwclock_control
*ctl
,
820 const time_t last_time
,
821 const double not_adjusted
,
822 const time_t systime
, struct timeval
*tdrift_p
)
824 double exact_adjustment
;
827 ((double)(systime
- last_time
)) * factor
/ (24 * 60 * 60)
829 tdrift_p
->tv_sec
= (time_t) floor(exact_adjustment
);
830 tdrift_p
->tv_usec
= (exact_adjustment
-
831 (double)tdrift_p
->tv_sec
) * 1E6
;
833 printf(P_("Time since last adjustment is %ld second\n",
834 "Time since last adjustment is %ld seconds\n",
835 (systime
- last_time
)),
836 (systime
- last_time
));
837 printf(_("Calculated Hardware Clock drift is %ld.%06ld seconds\n"),
838 tdrift_p
->tv_sec
, tdrift_p
->tv_usec
);
843 * Write the contents of the <adjtime> structure to its disk file.
845 * But if the contents are clean (unchanged since read from disk), don't
848 static int save_adjtime(const struct hwclock_control
*ctl
,
849 const struct adjtime
*adjtime
)
851 char *content
; /* Stuff to write to disk file */
854 xasprintf(&content
, "%f %ld %f\n%ld\n%s\n",
855 adjtime
->drift_factor
,
856 adjtime
->last_adj_time
,
857 adjtime
->not_adjusted
,
858 adjtime
->last_calib_time
,
859 (adjtime
->local_utc
== LOCAL
) ? "LOCAL" : "UTC");
862 printf(_("New %s data:\n%s"),
863 ctl
->adj_file_name
, content
);
867 fp
= fopen(ctl
->adj_file_name
, "w");
869 warn(_("cannot open %s"), ctl
->adj_file_name
);
871 } else if (fputs(content
, fp
) < 0 || close_stream(fp
) != 0) {
872 warn(_("cannot update %s"), ctl
->adj_file_name
);
880 * Do the adjustment requested, by 1) setting the Hardware Clock (if
881 * necessary), and 2) updating the last-adjusted time in the adjtime
884 * Do not update anything if the Hardware Clock does not currently present a
887 * <hclocktime> is the drift corrected time read from the Hardware Clock.
889 * <read_time> was the system time when the <hclocktime> was read, which due
890 * to computational delay could be a short time ago. It is used to define a
891 * trigger point for setting the Hardware Clock. The fractional part of the
892 * Hardware clock set time is subtracted from read_time to 'refer back', or
893 * delay, the trigger point. Fractional parts must be accounted for in this
894 * way, because the Hardware Clock can only be set to a whole second.
896 * <universal>: the Hardware Clock is kept in UTC.
898 * <testing>: We are running in test mode (no updating of clock).
902 do_adjustment(const struct hwclock_control
*ctl
, struct adjtime
*adjtime_p
,
903 const struct timeval hclocktime
,
904 const struct timeval read_time
)
906 if (adjtime_p
->last_adj_time
== 0) {
908 printf(_("Not setting clock because last adjustment time is zero, "
909 "so history is bad.\n"));
910 } else if (fabs(adjtime_p
->drift_factor
) > MAX_DRIFT
) {
912 printf(_("Not setting clock because drift factor %f is far too high.\n"),
913 adjtime_p
->drift_factor
);
915 set_hardware_clock_exact(ctl
, hclocktime
.tv_sec
,
917 -(hclocktime
.tv_usec
/ 1E6
)));
918 adjtime_p
->last_adj_time
= hclocktime
.tv_sec
;
919 adjtime_p
->not_adjusted
= 0;
920 adjtime_p
->dirty
= 1;
924 static void determine_clock_access_method(const struct hwclock_control
*ctl
)
929 ur
= probe_for_cmos_clock();
932 ur
= probe_for_rtc_clock(ctl
);
936 puts(ur
->interface_name
);
940 printf(_("No usable clock interface found.\n"));
941 warnx(_("Cannot access the Hardware Clock via "
942 "any known method."));
944 warnx(_("Use the --verbose option to see the "
945 "details of our search for an access "
947 hwclock_exit(ctl
, EXIT_FAILURE
);
951 /* Do all the normal work of hwclock - read, set clock, etc. */
953 manipulate_clock(const struct hwclock_control
*ctl
, const time_t set_time
,
954 const struct timeval startup_time
, struct adjtime
*adjtime
)
956 /* The time at which we read the Hardware Clock */
957 struct timeval read_time
= { 0 };
959 * The Hardware Clock gives us a valid time, or at
960 * least something close enough to fool mktime().
962 int hclock_valid
= 0;
964 * Tick synchronized time read from the Hardware Clock and
965 * then drift corrected for all operations except --show.
967 struct timeval hclocktime
= { 0 };
969 * hclocktime correlated to startup_time. That is, what drift
970 * corrected Hardware Clock time would have been at start up.
972 struct timeval startup_hclocktime
= { 0 };
973 /* Total Hardware Clock drift correction needed. */
974 struct timeval tdrift
;
976 if ((ctl
->set
|| ctl
->systohc
|| ctl
->adjust
) &&
977 (adjtime
->local_utc
== UTC
) != ctl
->universal
) {
978 adjtime
->local_utc
= ctl
->universal
? UTC
: LOCAL
;
982 * Negate the drift correction, because we want to 'predict' a
983 * Hardware Clock time that includes drift.
986 hclocktime
= t2tv(set_time
);
987 calculate_adjustment(ctl
, adjtime
->drift_factor
,
988 adjtime
->last_adj_time
,
989 adjtime
->not_adjusted
,
990 hclocktime
.tv_sec
, &tdrift
);
991 hclocktime
= time_inc(hclocktime
, (double)
992 -(tdrift
.tv_sec
+ tdrift
.tv_usec
/ 1E6
));
994 printf(_ ("Target date: %ld\n"), set_time
);
995 printf(_ ("Predicted RTC: %ld\n"), hclocktime
.tv_sec
);
997 return display_time(hclocktime
);
1001 return set_system_clock(ctl
, startup_time
);
1003 if (ur
->get_permissions())
1004 return EXIT_FAILURE
;
1007 * Read and drift correct RTC time; except for RTC set functions
1008 * without the --update-drift option because: 1) it's not needed;
1009 * 2) it enables setting a corrupted RTC without reading it first;
1010 * 3) it significantly reduces system shutdown time.
1012 if ( ! ((ctl
->set
|| ctl
->systohc
) && !ctl
->update
)) {
1014 * Timing critical - do not change the order of, or put
1015 * anything between the follow three statements.
1016 * Synchronization failure MUST exit, because all drift
1017 * operations are invalid without it.
1019 if (synchronize_to_clock_tick(ctl
))
1020 return EXIT_FAILURE
;
1021 read_hardware_clock(ctl
, &hclock_valid
, &hclocktime
.tv_sec
);
1022 gettimeofday(&read_time
, NULL
);
1024 if (!hclock_valid
) {
1025 warnx(_("RTC read returned an invalid value."));
1026 return EXIT_FAILURE
;
1029 * Calculate and apply drift correction to the Hardware Clock
1030 * time for everything except --show
1032 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1033 adjtime
->last_adj_time
,
1034 adjtime
->not_adjusted
,
1035 hclocktime
.tv_sec
, &tdrift
);
1037 hclocktime
= time_inc(tdrift
, hclocktime
.tv_sec
);
1039 startup_hclocktime
=
1040 time_inc(hclocktime
, time_diff(startup_time
, read_time
));
1042 if (ctl
->show
|| ctl
->get
) {
1043 return display_time(startup_hclocktime
);
1044 } else if (ctl
->set
) {
1045 set_hardware_clock_exact(ctl
, set_time
, startup_time
);
1046 if (!ctl
->noadjfile
)
1047 adjust_drift_factor(ctl
, adjtime
, t2tv(set_time
),
1048 startup_hclocktime
);
1049 } else if (ctl
->adjust
) {
1050 if (tdrift
.tv_sec
> 0 || tdrift
.tv_sec
< -1)
1051 do_adjustment(ctl
, adjtime
, hclocktime
, read_time
);
1053 printf(_("Needed adjustment is less than one second, "
1054 "so not setting clock.\n"));
1055 } else if (ctl
->systohc
) {
1056 struct timeval nowtime
, reftime
;
1058 * We can only set_hardware_clock_exact to a
1059 * whole seconds time, so we set it with
1060 * reference to the most recent whole
1063 gettimeofday(&nowtime
, NULL
);
1064 reftime
.tv_sec
= nowtime
.tv_sec
;
1065 reftime
.tv_usec
= 0;
1066 set_hardware_clock_exact(ctl
, (time_t) reftime
.tv_sec
, reftime
);
1067 if (!ctl
->noadjfile
)
1068 adjust_drift_factor(ctl
, adjtime
, nowtime
,
1070 } else if (ctl
->hctosys
) {
1071 return set_system_clock(ctl
, hclocktime
);
1073 if (!ctl
->noadjfile
&& adjtime
->dirty
)
1074 return save_adjtime(ctl
, adjtime
);
1075 return EXIT_SUCCESS
;
1079 * Get or set the kernel RTC driver's epoch on Alpha machines.
1080 * ISA machines are hard coded for 1900.
1082 #if defined(__linux__) && defined(__alpha__)
1084 manipulate_epoch(const struct hwclock_control
*ctl
)
1086 if (ctl
->getepoch
) {
1087 unsigned long epoch
;
1089 if (get_epoch_rtc(ctl
, &epoch
))
1090 warnx(_("unable to read the RTC epoch."));
1092 printf(_("The RTC epoch is set to %lu.\n"), epoch
);
1093 } else if (ctl
->setepoch
) {
1094 if (!ctl
->epoch_option
)
1095 warnx(_("--epoch is required for --setepoch."));
1096 else if (!ctl
->testing
)
1097 if (set_epoch_rtc(ctl
))
1098 warnx(_("unable to set the RTC epoch."));
1101 #endif /* __linux__ __alpha__ */
1103 static void out_version(void)
1105 printf(UTIL_LINUX_VERSION
);
1108 static void __attribute__((__noreturn__
))
1111 fputs(USAGE_HEADER
, stdout
);
1112 printf(_(" %s [function] [option...]\n"), program_invocation_short_name
);
1114 fputs(USAGE_SEPARATOR
, stdout
);
1115 puts(_("Time clocks utility."));
1117 fputs(USAGE_FUNCTIONS
, stdout
);
1118 puts(_(" -r, --show display the RTC time"));
1119 puts(_(" --get display drift corrected RTC time"));
1120 puts(_(" --set set the RTC according to --date"));
1121 puts(_(" -s, --hctosys set the system time from the RTC"));
1122 puts(_(" -w, --systohc set the RTC from the system time"));
1123 puts(_(" --systz send timescale configurations to the kernel"));
1124 puts(_(" -a, --adjust adjust the RTC to account for systematic drift"));
1125 #if defined(__linux__) && defined(__alpha__)
1126 puts(_(" --getepoch display the RTC epoch"));
1127 puts(_(" --setepoch set the RTC epoch according to --epoch"));
1129 puts(_(" --predict predict the drifted RTC time according to --date"));
1130 fputs(USAGE_OPTIONS
, stdout
);
1131 puts(_(" -u, --utc the RTC timescale is UTC"));
1132 puts(_(" -l, --localtime the RTC timescale is Local"));
1135 " -f, --rtc <file> use an alternate file to %1$s\n"), _PATH_RTC_DEV
);
1138 " --directisa use the ISA bus instead of %1$s access\n"), _PATH_RTC_DEV
);
1139 puts(_(" --date <time> date/time input for --set and --predict"));
1140 puts(_(" --delay <sec> delay used when set new RTC time"));
1141 #if defined(__linux__) && defined(__alpha__)
1142 puts(_(" --epoch <year> epoch input for --setepoch"));
1144 puts(_(" --update-drift update the RTC drift factor"));
1146 " --noadjfile do not use %1$s\n"), _PATH_ADJTIME
);
1148 " --adjfile <file> use an alternate file to %1$s\n"), _PATH_ADJTIME
);
1149 puts(_(" --test dry run; implies --verbose"));
1150 puts(_(" -v, --verbose display more details"));
1151 fputs(USAGE_SEPARATOR
, stdout
);
1152 printf(USAGE_HELP_OPTIONS(22));
1153 printf(USAGE_MAN_TAIL("hwclock(8)"));
1157 int main(int argc
, char **argv
)
1159 struct hwclock_control ctl
= {
1160 .show
= 1, /* default op is show */
1161 .rtc_delay
= -1.0 /* unspecified */
1163 struct timeval startup_time
;
1164 struct adjtime adjtime
= { 0 };
1165 struct timespec when
= { 0 };
1167 * The time we started up, in seconds into the epoch, including
1170 time_t set_time
= 0; /* Time to which user said to set Hardware Clock */
1173 /* Long only options. */
1175 OPT_ADJFILE
= CHAR_MAX
+ 1,
1191 static const struct option longopts
[] = {
1192 { "adjust", no_argument
, NULL
, 'a' },
1193 { "help", no_argument
, NULL
, 'h' },
1194 { "localtime", no_argument
, NULL
, 'l' },
1195 { "show", no_argument
, NULL
, 'r' },
1196 { "hctosys", no_argument
, NULL
, 's' },
1197 { "utc", no_argument
, NULL
, 'u' },
1198 { "version", no_argument
, NULL
, 'V' },
1199 { "systohc", no_argument
, NULL
, 'w' },
1200 { "debug", no_argument
, NULL
, 'D' },
1201 { "ul-debug", required_argument
, NULL
, 'd' },
1202 { "verbose", no_argument
, NULL
, 'v' },
1203 { "set", no_argument
, NULL
, OPT_SET
},
1204 #if defined(__linux__) && defined(__alpha__)
1205 { "getepoch", no_argument
, NULL
, OPT_GETEPOCH
},
1206 { "setepoch", no_argument
, NULL
, OPT_SETEPOCH
},
1207 { "epoch", required_argument
, NULL
, OPT_EPOCH
},
1209 { "noadjfile", no_argument
, NULL
, OPT_NOADJFILE
},
1210 { "directisa", no_argument
, NULL
, OPT_DIRECTISA
},
1211 { "test", no_argument
, NULL
, OPT_TEST
},
1212 { "date", required_argument
, NULL
, OPT_DATE
},
1213 { "delay", required_argument
, NULL
, OPT_DELAY
},
1215 { "rtc", required_argument
, NULL
, 'f' },
1217 { "adjfile", required_argument
, NULL
, OPT_ADJFILE
},
1218 { "systz", no_argument
, NULL
, OPT_SYSTZ
},
1219 { "predict", no_argument
, NULL
, OPT_PREDICT
},
1220 { "get", no_argument
, NULL
, OPT_GET
},
1221 { "update-drift", no_argument
, NULL
, OPT_UPDATE
},
1222 { NULL
, 0, NULL
, 0 }
1225 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
1227 OPT_GET
, OPT_GETEPOCH
, OPT_PREDICT
,
1228 OPT_SET
, OPT_SETEPOCH
, OPT_SYSTZ
},
1230 { OPT_ADJFILE
, OPT_NOADJFILE
},
1231 { OPT_NOADJFILE
, OPT_UPDATE
},
1234 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1236 /* Remember what time we were invoked */
1237 gettimeofday(&startup_time
, NULL
);
1239 #ifdef HAVE_LIBAUDIT
1240 hwaudit_fd
= audit_open();
1241 if (hwaudit_fd
< 0 && !(errno
== EINVAL
|| errno
== EPROTONOSUPPORT
||
1242 errno
== EAFNOSUPPORT
)) {
1244 * You get these error codes only when the kernel doesn't
1245 * have audit compiled in.
1247 warnx(_("Unable to connect to audit system"));
1248 return EXIT_FAILURE
;
1251 setlocale(LC_ALL
, "");
1254 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1255 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1256 * - gqueri@mail.dotcom.fr
1258 setlocale(LC_NUMERIC
, "C");
1260 bindtextdomain(PACKAGE
, LOCALEDIR
);
1261 textdomain(PACKAGE
);
1262 atexit(close_stdout
);
1264 while ((c
= getopt_long(argc
, argv
,
1265 "hvVDd:alrsuwf:", longopts
, NULL
)) != -1) {
1267 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1271 warnx(_("use --verbose, --debug has been deprecated."));
1277 hwclock_init_debug(optarg
);
1285 ctl
.local_opt
= 1; /* --localtime */
1308 #if defined(__linux__) && defined(__alpha__)
1319 ctl
.epoch_option
= optarg
; /* --epoch */
1329 ctl
.testing
= 1; /* --test */
1333 ctl
.date_opt
= optarg
; /* --date */
1336 ctl
.rtc_delay
= strtod_or_err(optarg
, "invalid --delay argument");
1339 ctl
.adj_file_name
= optarg
; /* --adjfile */
1342 ctl
.systz
= 1; /* --systz */
1347 ctl
.predict
= 1; /* --predict */
1351 ctl
.get
= 1; /* --get */
1355 ctl
.update
= 1; /* --update-drift */
1359 ctl
.rtc_dev_name
= optarg
; /* --rtc */
1362 case 'V': /* --version */
1365 case 'h': /* --help */
1368 errtryhelp(EXIT_FAILURE
);
1372 if (argc
-= optind
) {
1373 warnx(_("%d too many arguments given"), argc
);
1374 errtryhelp(EXIT_FAILURE
);
1377 if (!ctl
.adj_file_name
)
1378 ctl
.adj_file_name
= _PATH_ADJTIME
;
1380 if (ctl
.update
&& !ctl
.set
&& !ctl
.systohc
) {
1381 warnx(_("--update-drift requires --set or --systohc"));
1385 if (ctl
.noadjfile
&& !ctl
.utc
&& !ctl
.local_opt
) {
1386 warnx(_("With --noadjfile, you must specify "
1387 "either --utc or --localtime"));
1391 if (ctl
.set
|| ctl
.predict
) {
1392 if (!ctl
.date_opt
) {
1393 warnx(_("--date is required for --set or --predict"));
1396 if (parse_date(&when
, ctl
.date_opt
, NULL
))
1397 set_time
= when
.tv_sec
;
1399 warnx(_("invalid date '%s'"), ctl
.date_opt
);
1404 #if defined(__linux__) && defined(__alpha__)
1405 if (ctl
.getepoch
|| ctl
.setepoch
) {
1406 manipulate_epoch(&ctl
);
1407 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1413 printf(_("System Time: %ld.%06ld\n"),
1414 startup_time
.tv_sec
, startup_time
.tv_usec
);
1417 if (!ctl
.systz
&& !ctl
.predict
)
1418 determine_clock_access_method(&ctl
);
1420 if (!ctl
.noadjfile
&& !(ctl
.systz
&& (ctl
.utc
|| ctl
.local_opt
))) {
1421 if ((rc
= read_adjtime(&ctl
, &adjtime
)) != 0)
1422 hwclock_exit(&ctl
, rc
);
1424 /* Avoid writing adjtime file if we don't have to. */
1426 ctl
.universal
= hw_clock_is_utc(&ctl
, adjtime
);
1427 rc
= manipulate_clock(&ctl
, set_time
, startup_time
, &adjtime
);
1429 puts(_("Test mode: nothing was changed."));
1430 hwclock_exit(&ctl
, rc
);
1431 return rc
; /* Not reached */
1435 hwclock_exit(const struct hwclock_control
*ctl
1436 #ifndef HAVE_LIBAUDIT
1437 __attribute__((__unused__
))
1441 #ifdef HAVE_LIBAUDIT
1442 if (ctl
->hwaudit_on
&& !ctl
->testing
) {
1443 audit_log_user_message(hwaudit_fd
, AUDIT_USYS_CONFIG
,
1444 "op=change-system-time", NULL
, NULL
, NULL
,
1453 * History of this program:
1455 * 98.08.12 BJH Version 2.4
1457 * Don't use century byte from Hardware Clock. Add comments telling why.
1459 * 98.06.20 BJH Version 2.3.
1461 * Make --hctosys set the kernel timezone from TZ environment variable
1462 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1464 * 98.03.05 BJH. Version 2.2.
1466 * Add --getepoch and --setepoch.
1468 * Fix some word length things so it works on Alpha.
1470 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1471 * case, busywait for the top of a second instead of blocking and waiting
1472 * for the update complete interrupt.
1474 * Fix a bunch of bugs too numerous to mention.
1476 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1477 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1478 * job (jei@iclnl.icl.nl).
1480 * Use the rtc clock access method in preference to the KDGHWCLK method.
1481 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1483 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1484 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1485 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1486 * and wrote feature test code to detect absence of rtc headers.
1488 ***************************************************************************
1491 * To compile this, you must use GNU compiler optimization (-O option) in
1492 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1493 * compile. If you don't optimize, which means the compiler will generate no
1494 * inline functions, the references to these functions in this program will
1495 * be compiled as external references. Since you probably won't be linking
1496 * with any functions by these names, you will have unresolved external
1497 * references when you link.
1499 * Here's some info on how we must deal with the time that elapses while
1500 * this program runs: There are two major delays as we run:
1502 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1503 * we are synchronized to the Hardware Clock.
1504 * 2) Running the "date" program to interpret the value of our --date
1507 * Reading the /etc/adjtime file is the next biggest source of delay and
1510 * The user wants to know what time it was at the moment he invoked us, not
1511 * some arbitrary time later. And in setting the clock, he is giving us the
1512 * time at the moment we are invoked, so if we set the clock some time
1513 * later, we have to add some time to that.
1515 * So we check the system time as soon as we start up, then run "date" and
1516 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1517 * edge, then check the system time again to see how much time we spent. We
1518 * immediately read the clock then and (if appropriate) report that time,
1519 * and additionally, the delay we measured.
1521 * If we're setting the clock to a time given by the user, we wait some more
1522 * so that the total delay is an integral number of seconds, then set the
1523 * Hardware Clock to the time the user requested plus that integral number
1524 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1526 * If we're setting the clock to the system clock value, we wait for the
1527 * system clock to reach the top of a second, and then set the Hardware
1528 * Clock to the system clock's value.
1530 * Here's an interesting point about setting the Hardware Clock: On my
1531 * machine, when you set it, it sets to that precise time. But one can
1532 * imagine another clock whose update oscillator marches on a steady one
1533 * second period, so updating the clock between any two oscillator ticks is
1534 * the same as updating it right at the earlier tick. To avoid any
1535 * complications that might cause, we set the clock as soon as possible
1536 * after an oscillator tick.
1538 * About synchronizing to the Hardware Clock when reading the time: The
1539 * precision of the Hardware Clock counters themselves is one second. You
1540 * can't read the counters and find out that is 12:01:02.5. But if you
1541 * consider the location in time of the counter's ticks as part of its
1542 * value, then its precision is as infinite as time is continuous! What I'm
1543 * saying is this: To find out the _exact_ time in the hardware clock, we
1544 * wait until the next clock tick (the next time the second counter changes)
1545 * and measure how long we had to wait. We then read the value of the clock
1546 * counters and subtract the wait time and we know precisely what time it
1547 * was when we set out to query the time.
1549 * hwclock uses this method, and considers the Hardware Clock to have
1550 * infinite precision.