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