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