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