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