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