]> git.ipfire.org Git - thirdparty/util-linux.git/blame - sys-utils/hwclock.c
misc: fix more strutils related exit codes
[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
SK
73#define OPTUTILS_EXIT_CODE EX_USAGE
74
998f392a 75#include "c.h"
db116df7 76#include "closestream.h"
7eda085c 77#include "nls.h"
e1f4706d 78#include "optutils.h"
9d413ecb 79#include "pathnames.h"
4ac41d61 80#include "strutils.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
SK
650 if (rc) {
651 if (errno == EPERM) {
111c05d3
SK
652 warnx(_
653 ("Must be superuser to set system clock."));
ef71b8f1
SK
654 retcode = EX_NOPERM;
655 } else {
111c05d3 656 warn(_("settimeofday() failed"));
ef71b8f1
SK
657 retcode = 1;
658 }
659 } else
660 retcode = 0;
661 }
662 }
663 return retcode;
7eda085c
KZ
664}
665
ef71b8f1
SK
666/*
667 * Reset the System Clock from local time to UTC, based on its current value
668 * and the timezone unless universal is TRUE.
669 *
670 * Also set the kernel time zone value to the value indicated by the TZ
671 * environment variable and/or /usr/lib/zoneinfo/, interpreted as tzset()
672 * would interpret them.
673 *
674 * If 'testing' is true, don't actually update anything -- just say we would
675 * have.
676 */
336f7c5f 677static int set_system_clock_timezone(const struct hwclock_control *ctl)
ef71b8f1
SK
678{
679 int retcode;
680 struct timeval tv;
681 struct tm *broken;
682 int minuteswest;
ef71b8f1
SK
683
684 gettimeofday(&tv, NULL);
336f7c5f 685 if (ctl->debug) {
ef71b8f1
SK
686 struct tm broken_time;
687 char ctime_now[200];
688
689 broken_time = *gmtime(&tv.tv_sec);
690 strftime(ctime_now, sizeof(ctime_now), "%Y/%m/%d %H:%M:%S",
691 &broken_time);
b68e1f44 692 printf(_("Current system time: %ld = %s\n"), tv.tv_sec,
ef71b8f1
SK
693 ctime_now);
694 }
7eda085c 695
ef71b8f1 696 broken = localtime(&tv.tv_sec);
88a3372e 697#ifdef HAVE_TM_GMTOFF
ef71b8f1 698 minuteswest = -broken->tm_gmtoff / 60; /* GNU extension */
88a3372e 699#else
ef71b8f1
SK
700 minuteswest = timezone / 60;
701 if (broken->tm_isdst)
702 minuteswest -= 60;
88a3372e
SJR
703#endif
704
336f7c5f 705 if (ctl->debug) {
ef71b8f1
SK
706 struct tm broken_time;
707 char ctime_now[200];
708
839be2ba 709 gettimeofday(&tv, NULL);
336f7c5f 710 if (!ctl->universal)
839be2ba
KZ
711 tv.tv_sec += minuteswest * 60;
712
ef71b8f1
SK
713 broken_time = *gmtime(&tv.tv_sec);
714 strftime(ctime_now, sizeof(ctime_now), "%Y/%m/%d %H:%M:%S",
715 &broken_time);
716
717 printf(_("Calling settimeofday:\n"));
718 printf(_("\tUTC: %s\n"), ctime_now);
719 printf(_("\ttv.tv_sec = %ld, tv.tv_usec = %ld\n"),
b68e1f44 720 tv.tv_sec, tv.tv_usec);
ef71b8f1
SK
721 printf(_("\ttz.tz_minuteswest = %d\n"), minuteswest);
722 }
336f7c5f 723 if (ctl->testing) {
ef71b8f1 724 printf(_
142efd24 725 ("Test mode: clock was not changed\n"));
ef71b8f1
SK
726 retcode = 0;
727 } else {
910a0900 728 const struct timezone tz_utc = { 0, 0 };
ef71b8f1 729 const struct timezone tz = { minuteswest, 0 };
839be2ba 730 const struct timeval *tv_null = NULL;
910a0900
TG
731 int rc = 0;
732
733 /* The first call to settimeofday after boot will assume the systemtime
734 * is in localtime, and adjust it according to the given timezone to
735 * compensate. If the systemtime is in fact in UTC, then this is wrong
736 * so we first do a dummy call to make sure the time is not shifted.
737 */
336f7c5f 738 if (ctl->universal)
910a0900
TG
739 rc = settimeofday(tv_null, &tz_utc);
740
741 /* Now we set the real timezone. Due to the above dummy call, this will
742 * only warp the systemtime if the RTC is not in UTC. */
743 if (!rc)
744 rc = settimeofday(tv_null, &tz);
88a3372e 745
ef71b8f1
SK
746 if (rc) {
747 if (errno == EPERM) {
111c05d3
SK
748 warnx(_
749 ("Must be superuser to set system clock."));
ef71b8f1
SK
750 retcode = EX_NOPERM;
751 } else {
111c05d3 752 warn(_("settimeofday() failed"));
ef71b8f1
SK
753 retcode = 1;
754 }
755 } else
756 retcode = 0;
757 }
758 return retcode;
759}
760
761/*
f276d71a
WP
762 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
763 * to facilitate future drift calculations based on this set point.
ef71b8f1 764 *
f276d71a
WP
765 * With the --update-drift option:
766 * Update the drift factor in <*adjtime_p> based on the fact that the
767 * Hardware Clock was just calibrated to <nowtime> and before that was
768 * set to the <hclocktime> time scale.
ef71b8f1
SK
769 *
770 * EXCEPT: if <hclock_valid> is false, assume Hardware Clock was not set
771 * before to anything meaningful and regular adjustments have not been done,
772 * so don't adjust the drift factor.
773 */
7eda085c 774static void
336f7c5f
SK
775adjust_drift_factor(const struct hwclock_control *ctl,
776 struct adjtime *adjtime_p,
2794995a 777 const struct timeval nowtime,
ef71b8f1 778 const bool hclock_valid,
336f7c5f 779 const struct timeval hclocktime)
ef71b8f1 780{
336f7c5f
SK
781 if (!ctl->update) {
782 if (ctl->debug)
f276d71a
WP
783 printf(_("Not adjusting drift factor because the "
784 "--update-drift option was not used.\n"));
785 } else if (!hclock_valid) {
336f7c5f 786 if (ctl->debug)
63cccae4
KZ
787 printf(_("Not adjusting drift factor because the "
788 "Hardware Clock previously contained "
789 "garbage.\n"));
790 } else if (adjtime_p->last_calib_time == 0) {
336f7c5f 791 if (ctl->debug)
63cccae4
KZ
792 printf(_("Not adjusting drift factor because last "
793 "calibration time is zero,\n"
794 "so history is bad and calibration startover "
795 "is necessary.\n"));
bbb4c273 796 } else if ((hclocktime.tv_sec - adjtime_p->last_calib_time) < 4 * 60 * 60) {
336f7c5f 797 if (ctl->debug)
63cccae4 798 printf(_("Not adjusting drift factor because it has "
bbb4c273 799 "been less than four hours since the last "
63cccae4 800 "calibration.\n"));
c6ea9ef6 801 } else {
63cccae4 802 /*
f276d71a
WP
803 * At adjustment time we drift correct the hardware clock
804 * according to the contents of the adjtime file and refresh
805 * its last adjusted timestamp.
63cccae4 806 *
f276d71a
WP
807 * At calibration time we set the Hardware Clock and refresh
808 * both timestamps in <*adjtime_p>.
63cccae4 809 *
f276d71a
WP
810 * Here, with the --update-drift option, we also update the
811 * drift factor in <*adjtime_p>.
63cccae4
KZ
812 *
813 * Let us do computation in doubles. (Floats almost suffice,
814 * but 195 days + 1 second equals 195 days in floats.)
815 */
816 const double sec_per_day = 24.0 * 60.0 * 60.0;
63cccae4 817 double factor_adjust;
f196fd1a 818 double drift_factor;
2794995a 819 struct timeval last_calib;
63cccae4 820
2794995a 821 last_calib = t2tv(adjtime_p->last_calib_time);
ede32597
WP
822 /*
823 * Correction to apply to the current drift factor.
824 *
825 * Simplified: uncorrected_drift / days_since_calibration.
826 *
827 * hclocktime is fully corrected with the current drift factor.
828 * Its difference from nowtime is the missed drift correction.
829 */
2794995a
WP
830 factor_adjust = time_diff(nowtime, hclocktime) /
831 (time_diff(nowtime, last_calib) / sec_per_day);
63cccae4 832
f196fd1a 833 drift_factor = adjtime_p->drift_factor + factor_adjust;
83aa4ad7 834 if (fabs(drift_factor) > MAX_DRIFT) {
336f7c5f 835 if (ctl->debug)
f196fd1a
SB
836 printf(_("Clock drift factor was calculated as "
837 "%f seconds/day.\n"
838 "It is far too much. Resetting to zero.\n"),
839 drift_factor);
840 drift_factor = 0;
841 } else {
336f7c5f 842 if (ctl->debug)
a36a9026
WP
843 printf(_("Clock drifted %f seconds in the past "
844 "%f seconds\nin spite of a drift factor of "
f196fd1a
SB
845 "%f seconds/day.\n"
846 "Adjusting drift factor by %f seconds/day\n"),
2794995a
WP
847 time_diff(nowtime, hclocktime),
848 time_diff(nowtime, last_calib),
f196fd1a
SB
849 adjtime_p->drift_factor, factor_adjust);
850 }
851
852 adjtime_p->drift_factor = drift_factor;
63cccae4 853 }
2794995a 854 adjtime_p->last_calib_time = nowtime.tv_sec;
9abb2685 855
2794995a 856 adjtime_p->last_adj_time = nowtime.tv_sec;
9abb2685 857
63cccae4 858 adjtime_p->not_adjusted = 0;
9abb2685 859
63cccae4 860 adjtime_p->dirty = TRUE;
7eda085c
KZ
861}
862
ef71b8f1 863/*
ede32597
WP
864 * Calculate the drift correction currently needed for the
865 * Hardware Clock based on the last time it was adjusted,
866 * and the current drift factor, as stored in the adjtime file.
ef71b8f1 867 *
ede32597 868 * The total drift adjustment needed is stored at tdrift_p.
ef71b8f1 869 *
ef71b8f1 870 */
7eda085c 871static void
336f7c5f
SK
872calculate_adjustment(const struct hwclock_control *ctl,
873 const double factor,
ef71b8f1
SK
874 const time_t last_time,
875 const double not_adjusted,
2794995a 876 const time_t systime, struct timeval *tdrift_p)
ef71b8f1
SK
877{
878 double exact_adjustment;
7eda085c 879
ef71b8f1
SK
880 exact_adjustment =
881 ((double)(systime - last_time)) * factor / (24 * 60 * 60)
882 + not_adjusted;
1030c325 883 tdrift_p->tv_sec = (time_t) floor(exact_adjustment);
2794995a
WP
884 tdrift_p->tv_usec = (exact_adjustment -
885 (double)tdrift_p->tv_sec) * 1E6;
336f7c5f 886 if (ctl->debug) {
b68e1f44
SK
887 printf(P_("Time since last adjustment is %ld second\n",
888 "Time since last adjustment is %ld seconds\n",
889 (systime - last_time)),
890 (systime - last_time));
c2114018 891 printf(_("Calculated Hardware Clock drift is %ld.%06ld seconds\n"),
b68e1f44 892 tdrift_p->tv_sec, tdrift_p->tv_usec);
ef71b8f1 893 }
7eda085c
KZ
894}
895
ef71b8f1
SK
896/*
897 * Write the contents of the <adjtime> structure to its disk file.
898 *
899 * But if the contents are clean (unchanged since read from disk), don't
900 * bother.
901 */
336f7c5f
SK
902static void save_adjtime(const struct hwclock_control *ctl,
903 const struct adjtime *adjtime)
ef71b8f1 904{
4aca5fe2
SK
905 char *content; /* Stuff to write to disk file */
906 FILE *fp;
907 int err = 0;
7eda085c 908
4aca5fe2
SK
909 if (!adjtime->dirty)
910 return;
ef71b8f1 911
4aca5fe2
SK
912 xasprintf(&content, "%f %ld %f\n%ld\n%s\n",
913 adjtime->drift_factor,
914 adjtime->last_adj_time,
915 adjtime->not_adjusted,
916 adjtime->last_calib_time,
917 (adjtime->local_utc == LOCAL) ? "LOCAL" : "UTC");
918
919 if (ctl->testing) {
66c83c1c
WP
920 if (ctl->debug){
921 printf(_("Test mode: %s was not updated with:\n%s"),
922 ctl->adj_file_name, content);
923 }
4aca5fe2
SK
924 free(content);
925 return;
926 }
927
928 fp = fopen(ctl->adj_file_name, "w");
929 if (fp == NULL) {
930 warn(_("Could not open file with the clock adjustment parameters "
931 "in it (%s) for writing"), ctl->adj_file_name);
932 err = 1;
933 } else if (fputs(content, fp) < 0 || close_stream(fp) != 0) {
934 warn(_("Could not update file with the clock adjustment "
935 "parameters (%s) in it"), ctl->adj_file_name);
936 err = 1;
ef71b8f1 937 }
4aca5fe2
SK
938 free(content);
939 if (err)
940 warnx(_("Drift adjustment parameters not updated."));
ef71b8f1 941}
7eda085c 942
ef71b8f1
SK
943/*
944 * Do the adjustment requested, by 1) setting the Hardware Clock (if
945 * necessary), and 2) updating the last-adjusted time in the adjtime
946 * structure.
947 *
948 * Do not update anything if the Hardware Clock does not currently present a
949 * valid time.
950 *
ede32597 951 * <hclock_valid> means the Hardware Clock contains a valid time.
ef71b8f1 952 *
ede32597 953 * <hclocktime> is the drift corrected time read from the Hardware Clock.
ef71b8f1 954 *
ede32597
WP
955 * <read_time> was the system time when the <hclocktime> was read, which due
956 * to computational delay could be a short time ago. It is used to define a
957 * trigger point for setting the Hardware Clock. The fractional part of the
958 * Hardware clock set time is subtracted from read_time to 'refer back', or
959 * delay, the trigger point. Fractional parts must be accounted for in this
960 * way, because the Hardware Clock can only be set to a whole second.
ef71b8f1
SK
961 *
962 * <universal>: the Hardware Clock is kept in UTC.
963 *
964 * <testing>: We are running in test mode (no updating of clock).
965 *
ef71b8f1 966 */
7eda085c 967static void
336f7c5f 968do_adjustment(const struct hwclock_control *ctl, struct adjtime *adjtime_p,
2794995a 969 const bool hclock_valid, const struct timeval hclocktime,
336f7c5f 970 const struct timeval read_time)
ef71b8f1
SK
971{
972 if (!hclock_valid) {
111c05d3
SK
973 warnx(_("The Hardware Clock does not contain a valid time, "
974 "so we cannot adjust it."));
ef71b8f1
SK
975 adjtime_p->last_calib_time = 0; /* calibration startover is required */
976 adjtime_p->last_adj_time = 0;
977 adjtime_p->not_adjusted = 0;
978 adjtime_p->dirty = TRUE;
979 } else if (adjtime_p->last_adj_time == 0) {
336f7c5f 980 if (ctl->debug)
f55b4b45
KZ
981 printf(_("Not setting clock because last adjustment time is zero, "
982 "so history is bad.\n"));
83aa4ad7 983 } else if (fabs(adjtime_p->drift_factor) > MAX_DRIFT) {
336f7c5f 984 if (ctl->debug)
f55b4b45
KZ
985 printf(_("Not setting clock because drift factor %f is far too high.\n"),
986 adjtime_p->drift_factor);
ef71b8f1 987 } else {
336f7c5f 988 set_hardware_clock_exact(ctl, hclocktime.tv_sec,
2794995a 989 time_inc(read_time,
336f7c5f 990 -(hclocktime.tv_usec / 1E6)));
2794995a
WP
991 adjtime_p->last_adj_time = hclocktime.tv_sec;
992 adjtime_p->not_adjusted = 0;
993 adjtime_p->dirty = TRUE;
ef71b8f1 994 }
7eda085c
KZ
995}
996
336f7c5f 997static void determine_clock_access_method(const struct hwclock_control *ctl)
ef71b8f1
SK
998{
999 ur = NULL;
7eda085c 1000
336f7c5f 1001 if (ctl->directisa)
ef71b8f1 1002 ur = probe_for_cmos_clock();
465e9973 1003#ifdef __linux__
ef71b8f1 1004 if (!ur)
336f7c5f 1005 ur = probe_for_rtc_clock(ctl);
465e9973 1006#endif
8f729d60
SK
1007 if (ur) {
1008 if (ctl->debug)
1009 puts(ur->interface_name);
7eda085c 1010
8f729d60
SK
1011 } else {
1012 if (ctl->debug)
ef71b8f1 1013 printf(_("No usable clock interface found.\n"));
8f729d60
SK
1014 warnx(_("Cannot access the Hardware Clock via "
1015 "any known method."));
1016 if (!ctl->debug)
1017 warnx(_("Use the --debug option to see the "
1018 "details of our search for an access "
1019 "method."));
1020 hwclock_exit(ctl, EX_SOFTWARE);
ef71b8f1 1021 }
7eda085c
KZ
1022}
1023
ef71b8f1
SK
1024/*
1025 * Do all the normal work of hwclock - read, set clock, etc.
1026 *
1027 * Issue output to stdout and error message to stderr where appropriate.
1028 *
1029 * Return rc == 0 if everything went OK, rc != 0 if not.
1030 */
63cccae4 1031static int
336f7c5f
SK
1032manipulate_clock(const struct hwclock_control *ctl, const time_t set_time,
1033 const struct timeval startup_time, struct adjtime *adjtime)
ef71b8f1 1034{
ef71b8f1
SK
1035 /* The time at which we read the Hardware Clock */
1036 struct timeval read_time;
1037 /*
1038 * The Hardware Clock gives us a valid time, or at
1039 * least something close enough to fool mktime().
1040 */
1041 bool hclock_valid = FALSE;
1042 /*
ede32597
WP
1043 * Tick synchronized time read from the Hardware Clock and
1044 * then drift correct for all operations except --show.
ef71b8f1 1045 */
2794995a 1046 struct timeval hclocktime = { 0, 0 };
ede32597 1047 /* Total Hardware Clock drift correction needed. */
2794995a 1048 struct timeval tdrift;
ef71b8f1 1049 /* local return code */
23341bd4 1050 int rc = 0;
ef71b8f1 1051
a18f17ad
KZ
1052 if (!ctl->systz && !ctl->predict && ur->get_permissions())
1053 return EX_NOPERM;
ef71b8f1 1054
336f7c5f
SK
1055 if ((ctl->set || ctl->systohc || ctl->adjust) &&
1056 (adjtime->local_utc == UTC) != ctl->universal) {
1057 adjtime->local_utc = ctl->universal ? UTC : LOCAL;
1058 adjtime->dirty = TRUE;
ef71b8f1 1059 }
9abb2685 1060
336f7c5f
SK
1061 if (ctl->show || ctl->get || ctl->adjust || ctl->hctosys
1062 || (!ctl->noadjfile && !ctl->systz && !ctl->predict)) {
ef71b8f1 1063 /* data from HW-clock are required */
336f7c5f 1064 rc = synchronize_to_clock_tick(ctl);
ef71b8f1
SK
1065
1066 /*
0f32118e
SK
1067 * We don't error out if the user is attempting to set the
1068 * RTC and synchronization timeout happens - the RTC could
1069 * be functioning but contain invalid time data so we still
1070 * want to allow a user to set the RTC time.
ef71b8f1 1071 */
0f32118e 1072 if (rc == RTC_BUSYWAIT_FAILED && !ctl->set && !ctl->systohc)
ef71b8f1
SK
1073 return EX_IOERR;
1074 gettimeofday(&read_time, NULL);
1075
1076 /*
1077 * If we can't synchronize to a clock tick,
1078 * we likely can't read from the RTC so
1079 * don't bother reading it again.
1080 */
1081 if (!rc) {
336f7c5f
SK
1082 rc = read_hardware_clock(ctl, &hclock_valid,
1083 &hclocktime.tv_sec);
1084 if (rc && !ctl->set && !ctl->systohc)
ef71b8f1
SK
1085 return EX_IOERR;
1086 }
cdedde03 1087 }
ede32597
WP
1088 /*
1089 * Calculate Hardware Clock drift for --predict with the user
1090 * supplied --date option time, and with the time read from the
1091 * Hardware Clock for all other operations. Apply drift correction
1092 * to the Hardware Clock time for everything except --show and
1093 * --predict. For --predict negate the drift correction, because we
1094 * want to 'predict' a future Hardware Clock time that includes drift.
1095 */
336f7c5f
SK
1096 hclocktime = ctl->predict ? t2tv(set_time) : hclocktime;
1097 calculate_adjustment(ctl, adjtime->drift_factor,
1098 adjtime->last_adj_time,
1099 adjtime->not_adjusted,
2794995a 1100 hclocktime.tv_sec, &tdrift);
336f7c5f 1101 if (!ctl->show && !ctl->predict)
2794995a 1102 hclocktime = time_inc(tdrift, hclocktime.tv_sec);
336f7c5f 1103 if (ctl->show || ctl->get) {
2794995a
WP
1104 display_time(hclock_valid,
1105 time_inc(hclocktime, -time_diff
1106 (read_time, startup_time)));
336f7c5f
SK
1107 } else if (ctl->set) {
1108 set_hardware_clock_exact(ctl, set_time, startup_time);
1109 if (!ctl->noadjfile)
1110 adjust_drift_factor(ctl, adjtime,
2794995a
WP
1111 time_inc(t2tv(set_time), time_diff
1112 (read_time, startup_time)),
336f7c5f
SK
1113 hclock_valid, hclocktime);
1114 } else if (ctl->adjust) {
2794995a 1115 if (tdrift.tv_sec > 0 || tdrift.tv_sec < -1)
336f7c5f
SK
1116 do_adjustment(ctl, adjtime, hclock_valid,
1117 hclocktime, read_time);
2794995a
WP
1118 else
1119 printf(_("Needed adjustment is less than one second, "
1120 "so not setting clock.\n"));
336f7c5f 1121 } else if (ctl->systohc) {
ef71b8f1
SK
1122 struct timeval nowtime, reftime;
1123 /*
1124 * We can only set_hardware_clock_exact to a
1125 * whole seconds time, so we set it with
1126 * reference to the most recent whole
1127 * seconds time.
1128 */
1129 gettimeofday(&nowtime, NULL);
1130 reftime.tv_sec = nowtime.tv_sec;
1131 reftime.tv_usec = 0;
336f7c5f
SK
1132 set_hardware_clock_exact(ctl, (time_t) reftime.tv_sec, reftime);
1133 if (!ctl->noadjfile)
1134 adjust_drift_factor(ctl, adjtime, nowtime,
1135 hclock_valid, hclocktime);
1136 } else if (ctl->hctosys) {
1137 rc = set_system_clock(ctl, hclock_valid, hclocktime);
ef71b8f1
SK
1138 if (rc) {
1139 printf(_("Unable to set system clock.\n"));
1140 return rc;
1141 }
336f7c5f
SK
1142 } else if (ctl->systz) {
1143 rc = set_system_clock_timezone(ctl);
ef71b8f1
SK
1144 if (rc) {
1145 printf(_("Unable to set system clock.\n"));
1146 return rc;
1147 }
336f7c5f 1148 } else if (ctl->predict) {
66af1c0f
WP
1149 hclocktime = time_inc(hclocktime, (double)
1150 -(tdrift.tv_sec + tdrift.tv_usec / 1E6));
336f7c5f 1151 if (ctl->debug) {
ef71b8f1
SK
1152 printf(_
1153 ("At %ld seconds after 1969, RTC is predicted to read %ld seconds after 1969.\n"),
b68e1f44 1154 set_time, hclocktime.tv_sec);
ef71b8f1 1155 }
2794995a 1156 display_time(TRUE, hclocktime);
ef71b8f1 1157 }
336f7c5f
SK
1158 if (!ctl->noadjfile)
1159 save_adjtime(ctl, adjtime);
ef71b8f1 1160 return 0;
7eda085c
KZ
1161}
1162
039a0cec
WP
1163/**
1164 * Get or set the kernel RTC driver's epoch on Alpha machines.
1165 * ISA machines are hard coded for 1900.
390c72eb 1166 */
039a0cec 1167#if defined(__linux__) && defined(__alpha__)
390c72eb 1168static void
336f7c5f 1169manipulate_epoch(const struct hwclock_control *ctl)
390c72eb 1170{
336f7c5f 1171 if (ctl->getepoch) {
ef71b8f1
SK
1172 unsigned long epoch;
1173
af68bd01 1174 if (get_epoch_rtc(ctl, &epoch))
111c05d3
SK
1175 warnx(_
1176 ("Unable to get the epoch value from the kernel."));
ef71b8f1
SK
1177 else
1178 printf(_("Kernel is assuming an epoch value of %lu\n"),
1179 epoch);
336f7c5f
SK
1180 } else if (ctl->setepoch) {
1181 if (ctl->epoch_option == 0)
111c05d3
SK
1182 warnx(_
1183 ("To set the epoch value, you must use the 'epoch' "
1184 "option to tell to what value to set it."));
336f7c5f 1185 else if (ctl->testing)
ef71b8f1 1186 printf(_
e8c00034 1187 ("Not setting the epoch to %lu - testing only.\n"),
336f7c5f
SK
1188 ctl->epoch_option);
1189 else if (set_epoch_rtc(ctl))
ef71b8f1
SK
1190 printf(_
1191 ("Unable to set the epoch value in the kernel.\n"));
1192 }
7eda085c 1193}
039a0cec 1194#endif /* __linux__ __alpha__ */
7eda085c 1195
ef71b8f1
SK
1196static void out_version(void)
1197{
f6277500 1198 printf(UTIL_LINUX_VERSION);
63cccae4
KZ
1199}
1200
b1557fe9 1201static void __attribute__((__noreturn__))
7d9a866d 1202usage(const struct hwclock_control *ctl, FILE *out)
ef71b8f1 1203{
7d9a866d
WP
1204 fputs(USAGE_HEADER, out);
1205 fputs(_(" hwclock [function] [option...]\n"), out);
49deeeac 1206
7d9a866d 1207 fputs(USAGE_SEPARATOR, out);
3d27fdba 1208 fputs(_("Query or set the RTC (Real Time Clock / Hardware Clock)\n"), out);
451dbcfa 1209
513bfbef 1210 fputs(USAGE_FUNCTIONS, out);
d4affe81
WP
1211 fputs(_(" -r, --show display the RTC time\n"), out);
1212 fputs(_(" --get display drift corrected RTC time\n"), out);
1213 fputs(_(" --set set the RTC according to --date\n"), out);
1214 fputs(_(" -s, --hctosys set the system time from the RTC\n"), out);
1215 fputs(_(" -w, --systohc set the RTC from the system time\n"), out);
1216 fputs(_(" --systz send timescale configurations to the kernel\n"), out);
1217 fputs(_(" --adjust adjust the RTC to account for systematic drift\n"), out);
039a0cec 1218#if defined(__linux__) && defined(__alpha__)
d4affe81
WP
1219 fputs(_(" --getepoch display the RTC epoch\n"), out);
1220 fputs(_(" --setepoch set the RTC epoch according to --epoch\n"), out);
465e9973 1221#endif
cc7cb070 1222 fputs(_(" --predict predict the drifted RTC time according to --date\n"), out);
7d9a866d 1223 fputs(USAGE_OPTIONS, out);
d4affe81
WP
1224 fputs(_(" -u, --utc inform hwclock the RTC timescale is UTC\n"), out);
1225 fputs(_(" -l, --localtime inform hwclock the RTC timescale is Local\n"), out);
cc7cb070 1226 fprintf(out, _(
465e9973 1227#ifdef __linux__
cc7cb070 1228 " -f, --rtc <file> use an alternate file to %1$s\n"
465e9973 1229#endif
d4affe81
WP
1230 " --directisa use the ISA bus instead of %1$s access\n"), _PATH_RTC_DEV);
1231 fputs(_(" --date <time> date/time input for --set and --predict\n"), out);
039a0cec 1232#if defined(__linux__) && defined(__alpha__)
cc7cb070 1233 fputs(_(" --epoch <year> epoch input for --setepoch\n"), out);
039a0cec 1234#endif
891b4343 1235 fputs(_(" --update-drift update the RTC drift factor\n"), out);
7d9a866d 1236 fprintf(out, _(
cc7cb070
WP
1237 " --noadjfile do not use %1$s\n"
1238 " --adjfile <file> use an alternate file to %1$s\n"), _PATH_ADJTIME);
d4affe81
WP
1239 fputs(_(" --test dry run; use -D to view what would have happened\n"), out);
1240 fputs(_(" -D, --debug use debug mode\n"), out);
7d9a866d
WP
1241 fputs(USAGE_SEPARATOR, out);
1242 fputs(USAGE_HELP, out);
1243 fputs(USAGE_VERSION, out);
1244 fprintf(out, USAGE_MAN_TAIL("hwclock(8)"));
ea298feb 1245 hwclock_exit(ctl, EXIT_SUCCESS);
eb63b9b8
KZ
1246}
1247
63cccae4
KZ
1248/*
1249 * Returns:
1250 * EX_USAGE: bad invocation
1251 * EX_NOPERM: no permission
1252 * EX_OSFILE: cannot open /dev/rtc or /etc/adjtime
1253 * EX_IOERR: ioctl error getting or setting the time
1254 * 0: OK (or not)
1255 * 1: failure
1256 */
ef71b8f1
SK
1257int main(int argc, char **argv)
1258{
8b73ff96 1259 struct hwclock_control ctl = { .show = 1 }; /* default op is show */
63cccae4 1260 struct timeval startup_time;
336f7c5f 1261 struct adjtime adjtime = { 0 };
7a3000f7 1262 struct timespec when = { 0 };
ef71b8f1
SK
1263 /*
1264 * The time we started up, in seconds into the epoch, including
1265 * fractions.
1266 */
1267 time_t set_time = 0; /* Time to which user said to set Hardware Clock */
63cccae4 1268 int rc, c;
7eda085c 1269
dade002a
KZ
1270 /* Long only options. */
1271 enum {
1272 OPT_ADJFILE = CHAR_MAX + 1,
dade002a
KZ
1273 OPT_DATE,
1274 OPT_DIRECTISA,
1275 OPT_EPOCH,
2794995a 1276 OPT_GET,
dade002a 1277 OPT_GETEPOCH,
dade002a 1278 OPT_NOADJFILE,
57415653 1279 OPT_PREDICT,
dade002a
KZ
1280 OPT_SET,
1281 OPT_SETEPOCH,
1282 OPT_SYSTZ,
f276d71a
WP
1283 OPT_TEST,
1284 OPT_UPDATE
dade002a 1285 };
33ed2d02
SK
1286
1287 static const struct option longopts[] = {
87918040
SK
1288 { "adjust", no_argument, NULL, 'a' },
1289 { "help", no_argument, NULL, 'h' },
37526942 1290 { "localtime", no_argument, NULL, 'l' },
87918040
SK
1291 { "show", no_argument, NULL, 'r' },
1292 { "hctosys", no_argument, NULL, 's' },
1293 { "utc", no_argument, NULL, 'u' },
1294 { "version", no_argument, NULL, 'v' },
1295 { "systohc", no_argument, NULL, 'w' },
1296 { "debug", no_argument, NULL, 'D' },
87918040 1297 { "set", no_argument, NULL, OPT_SET },
039a0cec 1298#if defined(__linux__) && defined(__alpha__)
87918040
SK
1299 { "getepoch", no_argument, NULL, OPT_GETEPOCH },
1300 { "setepoch", no_argument, NULL, OPT_SETEPOCH },
039a0cec 1301 { "epoch", required_argument, NULL, OPT_EPOCH },
33ed2d02 1302#endif
87918040 1303 { "noadjfile", no_argument, NULL, OPT_NOADJFILE },
87918040
SK
1304 { "directisa", no_argument, NULL, OPT_DIRECTISA },
1305 { "test", no_argument, NULL, OPT_TEST },
1306 { "date", required_argument, NULL, OPT_DATE },
33ed2d02 1307#ifdef __linux__
87918040 1308 { "rtc", required_argument, NULL, 'f' },
33ed2d02 1309#endif
87918040
SK
1310 { "adjfile", required_argument, NULL, OPT_ADJFILE },
1311 { "systz", no_argument, NULL, OPT_SYSTZ },
57415653 1312 { "predict", no_argument, NULL, OPT_PREDICT },
87918040
SK
1313 { "get", no_argument, NULL, OPT_GET },
1314 { "update-drift", no_argument, NULL, OPT_UPDATE },
1315 { NULL, 0, NULL, 0 }
33ed2d02
SK
1316 };
1317
a7349ee3 1318 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
dade002a 1319 { 'a','r','s','w',
57415653 1320 OPT_GET, OPT_GETEPOCH, OPT_PREDICT,
2794995a 1321 OPT_SET, OPT_SETEPOCH, OPT_SYSTZ },
37526942 1322 { 'l', 'u' },
dade002a 1323 { OPT_ADJFILE, OPT_NOADJFILE },
f276d71a 1324 { OPT_NOADJFILE, OPT_UPDATE },
dade002a
KZ
1325 { 0 }
1326 };
1327 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1328
0b2b32e8
RM
1329 strutils_set_exitcode(EX_USAGE);
1330
63cccae4
KZ
1331 /* Remember what time we were invoked */
1332 gettimeofday(&startup_time, NULL);
7eda085c 1333
88058a71
KZ
1334#ifdef HAVE_LIBAUDIT
1335 hwaudit_fd = audit_open();
1336 if (hwaudit_fd < 0 && !(errno == EINVAL || errno == EPROTONOSUPPORT ||
1337 errno == EAFNOSUPPORT)) {
ef71b8f1
SK
1338 /*
1339 * You get these error codes only when the kernel doesn't
1340 * have audit compiled in.
1341 */
111c05d3 1342 warnx(_("Unable to connect to audit system"));
88058a71
KZ
1343 return EX_NOPERM;
1344 }
1345#endif
63cccae4 1346 setlocale(LC_ALL, "");
66ee8158 1347#ifdef LC_NUMERIC
ef71b8f1
SK
1348 /*
1349 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1350 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1351 * - gqueri@mail.dotcom.fr
1352 */
63cccae4 1353 setlocale(LC_NUMERIC, "C");
66ee8158 1354#endif
63cccae4
KZ
1355 bindtextdomain(PACKAGE, LOCALEDIR);
1356 textdomain(PACKAGE);
db116df7 1357 atexit(close_stdout);
63cccae4 1358
dade002a 1359 while ((c = getopt_long(argc, argv,
37526942 1360 "?hvVDalrsuwAJSFf:", longopts, NULL)) != -1) {
dade002a
KZ
1361
1362 err_exclusive_options(c, longopts, excl, excl_st);
1363
63cccae4
KZ
1364 switch (c) {
1365 case 'D':
336f7c5f 1366 ctl.debug++;
63cccae4
KZ
1367 break;
1368 case 'a':
336f7c5f 1369 ctl.adjust = 1;
8b73ff96 1370 ctl.show = 0;
d8949aca 1371 ctl.hwaudit_on = 1;
63cccae4 1372 break;
37526942
RV
1373 case 'l':
1374 ctl.local_opt = 1; /* --localtime */
1375 break;
63cccae4 1376 case 'r':
336f7c5f 1377 ctl.show = 1;
63cccae4
KZ
1378 break;
1379 case 's':
336f7c5f 1380 ctl.hctosys = 1;
8b73ff96 1381 ctl.show = 0;
d8949aca 1382 ctl.hwaudit_on = 1;
63cccae4
KZ
1383 break;
1384 case 'u':
336f7c5f 1385 ctl.utc = 1;
63cccae4
KZ
1386 break;
1387 case 'w':
336f7c5f 1388 ctl.systohc = 1;
8b73ff96 1389 ctl.show = 0;
d8949aca 1390 ctl.hwaudit_on = 1;
63cccae4 1391 break;
33ed2d02 1392 case OPT_SET:
336f7c5f 1393 ctl.set = 1;
8b73ff96 1394 ctl.show = 0;
d8949aca 1395 ctl.hwaudit_on = 1;
63cccae4 1396 break;
039a0cec 1397#if defined(__linux__) && defined(__alpha__)
33ed2d02 1398 case OPT_GETEPOCH:
336f7c5f 1399 ctl.getepoch = 1;
8b73ff96 1400 ctl.show = 0;
63cccae4 1401 break;
33ed2d02 1402 case OPT_SETEPOCH:
336f7c5f 1403 ctl.setepoch = 1;
8b73ff96 1404 ctl.show = 0;
d8949aca 1405 ctl.hwaudit_on = 1;
63cccae4 1406 break;
039a0cec
WP
1407 case OPT_EPOCH:
1408 ctl.epoch_option = /* --epoch */
1409 strtoul_or_err(optarg, _("invalid epoch argument"));
1410 break;
465e9973 1411#endif
33ed2d02 1412 case OPT_NOADJFILE:
336f7c5f 1413 ctl.noadjfile = 1;
63cccae4 1414 break;
33ed2d02 1415 case OPT_DIRECTISA:
336f7c5f 1416 ctl.directisa = 1;
63cccae4 1417 break;
33ed2d02 1418 case OPT_TEST:
336f7c5f 1419 ctl.testing = 1; /* --test */
63cccae4 1420 break;
33ed2d02 1421 case OPT_DATE:
336f7c5f 1422 ctl.date_opt = optarg; /* --date */
63cccae4 1423 break;
33ed2d02 1424 case OPT_ADJFILE:
336f7c5f 1425 ctl.adj_file_name = optarg; /* --adjfile */
da82f6fe 1426 break;
33ed2d02 1427 case OPT_SYSTZ:
336f7c5f 1428 ctl.systz = 1; /* --systz */
8b73ff96 1429 ctl.show = 0;
88a3372e 1430 break;
57415653
WP
1431 case OPT_PREDICT:
1432 ctl.predict = 1; /* --predict */
8b73ff96 1433 ctl.show = 0;
2e5627fa 1434 break;
2794995a 1435 case OPT_GET:
336f7c5f 1436 ctl.get = 1; /* --get */
8b73ff96 1437 ctl.show = 0;
2794995a 1438 break;
f276d71a 1439 case OPT_UPDATE:
336f7c5f 1440 ctl.update = 1; /* --update-drift */
f276d71a 1441 break;
465e9973 1442#ifdef __linux__
88681c5f 1443 case 'f':
336f7c5f 1444 ctl.rtc_dev_name = optarg; /* --rtc */
88681c5f 1445 break;
465e9973 1446#endif
ef71b8f1 1447 case 'v': /* --version */
63cccae4
KZ
1448 case 'V':
1449 out_version();
1450 return 0;
ef71b8f1 1451 case 'h': /* --help */
ea298feb 1452 usage(&ctl, stdout);
657a5568
WP
1453 default:
1454 errtryhelp(EXIT_FAILURE);
63cccae4
KZ
1455 }
1456 }
7eda085c 1457
63cccae4
KZ
1458 argc -= optind;
1459 argv += optind;
eb63b9b8 1460
63cccae4 1461 if (argc > 0) {
657a5568
WP
1462 warnx(_("%d too many arguments given"), argc);
1463 errtryhelp(EXIT_FAILURE);
63cccae4 1464 }
7eda085c 1465
336f7c5f
SK
1466 if (!ctl.adj_file_name)
1467 ctl.adj_file_name = _PATH_ADJTIME;
da82f6fe 1468
891b4343
WP
1469 if (ctl.update && !ctl.set && !ctl.systohc) {
1470 warnx(_("--update-drift requires --set or --systohc"));
1471 hwclock_exit(&ctl, EX_USAGE);
1472 }
1473
336f7c5f 1474 if (ctl.noadjfile && !ctl.utc && !ctl.local_opt) {
111c05d3
SK
1475 warnx(_("With --noadjfile, you must specify "
1476 "either --utc or --localtime"));
336f7c5f 1477 hwclock_exit(&ctl, EX_USAGE);
63cccae4 1478 }
7eda085c 1479
336f7c5f 1480 if (ctl.set || ctl.predict) {
969bffb7
WP
1481 if (!ctl.date_opt){
1482 warnx(_("--date is required for --set or --predict"));
1483 hwclock_exit(&ctl, EX_USAGE);
1484 }
7a3000f7
WP
1485 if (parse_date(&when, ctl.date_opt, NULL))
1486 set_time = when.tv_sec;
1487 else {
1488 warnx(_("invalid date '%s'"), ctl.date_opt);
336f7c5f 1489 hwclock_exit(&ctl, EX_USAGE);
63cccae4
KZ
1490 }
1491 }
7eda085c 1492
039a0cec 1493#if defined(__linux__) && defined(__alpha__)
336f7c5f
SK
1494 if (ctl.getepoch || ctl.setepoch) {
1495 manipulate_epoch(&ctl);
1496 hwclock_exit(&ctl, EX_OK);
63cccae4 1497 }
465e9973 1498#endif
63cccae4 1499
336f7c5f 1500 if (ctl.debug)
63cccae4 1501 out_version();
111c05d3 1502
8f729d60 1503 if (!ctl.systz && !ctl.predict)
336f7c5f 1504 determine_clock_access_method(&ctl);
63cccae4 1505
336f7c5f
SK
1506 if (!ctl.noadjfile && !(ctl.systz && (ctl.utc || ctl.local_opt))) {
1507 if ((rc = read_adjtime(&ctl, &adjtime)) != 0)
1508 hwclock_exit(&ctl, rc);
1509 } else
1510 /* Avoid writing adjtime file if we don't have to. */
1511 adjtime.dirty = FALSE;
1512 ctl.universal = hw_clock_is_utc(&ctl, adjtime);
92931ab2 1513 rc = manipulate_clock(&ctl, set_time, startup_time, &adjtime);
336f7c5f 1514 hwclock_exit(&ctl, rc);
ef71b8f1 1515 return rc; /* Not reached */
7eda085c
KZ
1516}
1517
39ff5b34 1518void
336f7c5f
SK
1519hwclock_exit(const struct hwclock_control *ctl
1520#ifndef HAVE_LIBAUDIT
1521 __attribute__((__unused__))
1522#endif
1523 , int status)
88058a71 1524{
48e7ed5e 1525#ifdef HAVE_LIBAUDIT
d8949aca 1526 if (ctl->hwaudit_on && !ctl->testing) {
88058a71 1527 audit_log_user_message(hwaudit_fd, AUDIT_USYS_CONFIG,
fbed7e09 1528 "op=change-system-time", NULL, NULL, NULL,
ef71b8f1 1529 status ? 0 : 1);
88058a71
KZ
1530 close(hwaudit_fd);
1531 }
48e7ed5e 1532#endif
88058a71
KZ
1533 exit(status);
1534}
88058a71 1535
ef71b8f1
SK
1536/*
1537 * History of this program:
1538 *
1539 * 98.08.12 BJH Version 2.4
1540 *
1541 * Don't use century byte from Hardware Clock. Add comments telling why.
1542 *
1543 * 98.06.20 BJH Version 2.3.
1544 *
1545 * Make --hctosys set the kernel timezone from TZ environment variable
1546 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1547 *
1548 * 98.03.05 BJH. Version 2.2.
1549 *
1550 * Add --getepoch and --setepoch.
1551 *
1552 * Fix some word length things so it works on Alpha.
1553 *
1554 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1555 * case, busywait for the top of a second instead of blocking and waiting
1556 * for the update complete interrupt.
1557 *
1558 * Fix a bunch of bugs too numerous to mention.
1559 *
1560 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1561 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1562 * job (jei@iclnl.icl.nl).
1563 *
1564 * Use the rtc clock access method in preference to the KDGHWCLK method.
1565 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1566 *
1567 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1568 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1569 * more recent versions of the kernel. Introduced the NO_CLOCK access method
455fe9a0 1570 * and wrote feature test code to detect absence of rtc headers.
ef71b8f1
SK
1571 *
1572 ***************************************************************************
1573 * Maintenance notes
1574 *
1575 * To compile this, you must use GNU compiler optimization (-O option) in
1576 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1577 * compile. If you don't optimize, which means the compiler will generate no
1578 * inline functions, the references to these functions in this program will
1579 * be compiled as external references. Since you probably won't be linking
1580 * with any functions by these names, you will have unresolved external
1581 * references when you link.
1582 *
ef71b8f1
SK
1583 * Here's some info on how we must deal with the time that elapses while
1584 * this program runs: There are two major delays as we run:
1585 *
1586 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1587 * we are synchronized to the Hardware Clock.
1588 * 2) Running the "date" program to interpret the value of our --date
1589 * option.
1590 *
1591 * Reading the /etc/adjtime file is the next biggest source of delay and
1592 * uncertainty.
1593 *
1594 * The user wants to know what time it was at the moment he invoked us, not
1595 * some arbitrary time later. And in setting the clock, he is giving us the
1596 * time at the moment we are invoked, so if we set the clock some time
1597 * later, we have to add some time to that.
1598 *
1599 * So we check the system time as soon as we start up, then run "date" and
1600 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1601 * edge, then check the system time again to see how much time we spent. We
1602 * immediately read the clock then and (if appropriate) report that time,
1603 * and additionally, the delay we measured.
1604 *
1605 * If we're setting the clock to a time given by the user, we wait some more
1606 * so that the total delay is an integral number of seconds, then set the
1607 * Hardware Clock to the time the user requested plus that integral number
1608 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1609 *
1610 * If we're setting the clock to the system clock value, we wait for the
1611 * system clock to reach the top of a second, and then set the Hardware
1612 * Clock to the system clock's value.
1613 *
1614 * Here's an interesting point about setting the Hardware Clock: On my
1615 * machine, when you set it, it sets to that precise time. But one can
1616 * imagine another clock whose update oscillator marches on a steady one
1617 * second period, so updating the clock between any two oscillator ticks is
1618 * the same as updating it right at the earlier tick. To avoid any
1619 * complications that might cause, we set the clock as soon as possible
1620 * after an oscillator tick.
1621 *
1622 * About synchronizing to the Hardware Clock when reading the time: The
1623 * precision of the Hardware Clock counters themselves is one second. You
1624 * can't read the counters and find out that is 12:01:02.5. But if you
1625 * consider the location in time of the counter's ticks as part of its
1626 * value, then its precision is as infinite as time is continuous! What I'm
1627 * saying is this: To find out the _exact_ time in the hardware clock, we
1628 * wait until the next clock tick (the next time the second counter changes)
1629 * and measure how long we had to wait. We then read the value of the clock
1630 * counters and subtract the wait time and we know precisely what time it
1631 * was when we set out to query the time.
1632 *
1633 * hwclock uses this method, and considers the Hardware Clock to have
1634 * infinite precision.
ef71b8f1 1635 */