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