]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/hwclock.c
sys-utils: cleanup license lines, add SPDX
[thirdparty/util-linux.git] / sys-utils / hwclock.c
1 /*
2 * SPDX-License-Identifier: GPL-2.0-or-later
3 *
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 *
10 * Since 7a3000f7ba548cf7d74ac77cc63fe8de228a669e (v2.30) hwclock is linked
11 * with parse_date.y from gnullib. This gnulib code is distributed with GPLv3.
12 * Use --disable-hwclock-gplv3 to exclude this code.
13 *
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>
18 *
19 * Copyright (C) 2007-2023 Karel Zak <kzak@redhat.com>
20 *
21 * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19.
22 * The new program is called hwclock. New features:
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.
29 *
30 * Reshuffled things, added sparc code, and re-added alpha stuff
31 * by David Mosberger <davidm@azstarnet.com>
32 * and Jay Estabrook <jestabro@amt.tay1.dec.com>
33 * and Martin Ostermann <ost@comnets.rwth-aachen.de>, aeb@cwi.nl, 990212.
34 *
35 * Fix for Award 2094 bug, Dave Coffin (dcoffin@shore.net) 11/12/98
36 * Change of local time handling, Stefan Ring <e9725446@stud3.tuwien.ac.at>
37 * Change of adjtime handling, James P. Rutledge <ao112@rgfn.epcc.edu>.
38 *
39 *
40 */
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 *
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
59 *
60 * Installation and use of this program:
61 *
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'
70 */
71
72 #include <errno.h>
73 #include <getopt.h>
74 #include <limits.h>
75 #include <math.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <sys/stat.h>
80 #include <sys/time.h>
81 #ifdef HAVE_SYS_SYSCALL_H
82 #include <sys/syscall.h>
83 #endif
84 #include <time.h>
85 #include <unistd.h>
86 #include <inttypes.h>
87
88 #include "c.h"
89 #include "closestream.h"
90 #include "nls.h"
91 #include "optutils.h"
92 #include "pathnames.h"
93 #include "hwclock.h"
94 #include "timeutils.h"
95 #include "env.h"
96 #include "xalloc.h"
97 #include "path.h"
98 #include "strutils.h"
99
100 #ifdef HAVE_LIBAUDIT
101 #include <libaudit.h>
102 static int hwaudit_fd = -1;
103 #endif
104
105 UL_DEBUG_DEFINE_MASK(hwclock);
106 UL_DEBUG_DEFINE_MASKNAMES(hwclock) = UL_DEBUG_EMPTY_MASKNAMES;
107
108 /* The struct that holds our hardware access routines */
109 static const struct clock_ops *ur;
110
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
116 struct adjtime {
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 */
125 int dirty;
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 */
137 enum a_local_utc { UTC = 0, LOCAL, UNKNOWN } local_utc;
138 /*
139 * To which time zone, local or UTC, we most recently set the
140 * hardware clock.
141 */
142 };
143
144 static 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 */
153 static 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
161 /*
162 * time_t to timeval conversion.
163 */
164 static 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
173 /*
174 * The difference in seconds between two times in "timeval" format.
175 */
176 double 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;
180 }
181
182 /*
183 * The time, in "timeval" format, which is <increment> seconds after the
184 * time <addend>. Of course, <increment> may be negative.
185 */
186 static struct timeval time_inc(struct timeval addend, double increment)
187 {
188 struct timeval newtime;
189
190 newtime.tv_sec = addend.tv_sec + (time_t)increment;
191 newtime.tv_usec = addend.tv_usec + (increment - (time_t)increment) * 1E6;
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;
205 }
206
207 static int
208 hw_clock_is_utc(const struct hwclock_control *ctl,
209 const struct adjtime *adjtime)
210 {
211 int ret;
212
213 if (ctl->utc)
214 ret = 1; /* --utc explicitly given on command line */
215 else if (ctl->local_opt)
216 ret = 0; /* --localtime explicitly given */
217 else
218 /* get info from adjtime file - default is UTC */
219 ret = (adjtime->local_utc != LOCAL);
220
221 if (ctl->verbose)
222 printf(_("Assuming hardware clock is kept in %s time.\n"),
223 ret ? _("UTC") : _("local"));
224 return ret;
225 }
226
227 /*
228 * Read the adjustment parameters out of the /etc/adjtime file.
229 *
230 * Return them as the adjtime structure <*adjtime_p>. Its defaults are
231 * initialized in main().
232 */
233 static int read_adjtime(const struct hwclock_control *ctl,
234 struct adjtime *adjtime_p)
235 {
236 FILE *adjfile;
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 */
240 int64_t last_adj_time;
241 int64_t last_calib_time;
242
243 if (access(ctl->adj_file_name, R_OK) != 0)
244 return EXIT_SUCCESS;
245
246 adjfile = fopen(ctl->adj_file_name, "r"); /* open file for reading */
247 if (adjfile == NULL) {
248 warn(_("cannot open %s"), ctl->adj_file_name);
249 return EXIT_FAILURE;
250 }
251
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
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);
266
267 if (sscanf(line2, "%"SCNd64, &last_calib_time) != 1)
268 warnx(_("Warning: unrecognized line in adjtime file: %s"), line2);
269
270 adjtime_p->last_adj_time = (time_t)last_adj_time;
271 adjtime_p->last_calib_time = (time_t)last_calib_time;
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]) {
280 warnx(_("Warning: unrecognized third line in adjtime file\n"
281 "(Expected: `UTC' or `LOCAL' or nothing.)"));
282 }
283 }
284
285 if (ctl->verbose) {
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);
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
296 return EXIT_SUCCESS;
297 }
298
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 */
312 static int synchronize_to_clock_tick(const struct hwclock_control *ctl)
313 {
314 int rc;
315
316 if (ctl->verbose)
317 printf(_("Waiting for clock tick...\n"));
318
319 rc = ur->synchronize_to_clock_tick(ctl);
320
321 if (ctl->verbose) {
322 if (rc)
323 printf(_("...synchronization failed\n"));
324 else
325 printf(_("...got clock tick\n"));
326 }
327
328 return rc;
329 }
330
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 */
347 static int
348 mktime_tz(const struct hwclock_control *ctl, struct tm tm,
349 time_t *systime_p)
350 {
351 int valid;
352
353 if (ctl->universal)
354 *systime_p = timegm(&tm);
355 else
356 *systime_p = mktime(&tm);
357 if (*systime_p == -1) {
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 */
364 valid = 0;
365 if (ctl->verbose)
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 {
371 valid = 1;
372 if (ctl->verbose)
373 printf(_("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
374 "%"PRId64" seconds since 1969\n"), tm.tm_year + 1900,
375 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min,
376 tm.tm_sec, (int64_t)*systime_p);
377 }
378 return valid;
379 }
380
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 */
387 static int
388 read_hardware_clock(const struct hwclock_control *ctl,
389 int *valid_p, time_t *systime_p)
390 {
391 struct tm tm = { 0 };
392 int err;
393
394 err = ur->read_hardware_clock(ctl, &tm);
395 if (err)
396 return err;
397
398 if (ctl->verbose)
399 printf(_("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
400 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
401 tm.tm_min, tm.tm_sec);
402 *valid_p = mktime_tz(ctl, tm, systime_p);
403
404 return 0;
405 }
406
407 /*
408 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
409 * according to <universal>.
410 */
411 static void
412 set_hardware_clock(const struct hwclock_control *ctl, const time_t newtime)
413 {
414 struct tm new_broken_time = { 0 };
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
420 if (ctl->universal)
421 gmtime_r(&newtime, &new_broken_time);
422 else
423 localtime_r(&newtime, &new_broken_time);
424
425 if (ctl->verbose)
426 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
427 "= %"PRId64" seconds since 1969\n"),
428 new_broken_time.tm_hour, new_broken_time.tm_min,
429 new_broken_time.tm_sec, (int64_t)newtime);
430
431 if (!ctl->testing)
432 ur->set_hardware_clock(ctl, &new_broken_time);
433 }
434
435 static double
436 get_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;
455 rc = ul_path_scanf(pc, "name", "%128[^\n ]", name);
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;
470 unknown:
471 /* Let's be backwardly compatible */
472 return 0.5;
473 }
474
475
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,
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().
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 */
495 static void
496 set_hardware_clock_exact(const struct hwclock_control *ctl,
497 const time_t sethwtime,
498 const struct timeval refsystime)
499 {
500 /*
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.
527 *
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.
543 */
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 */
548 double delay;
549 struct timeval rtc_set_delay_tv;
550
551 struct timeval targetsystime;
552 struct timeval nowsystime;
553 struct timeval prevsystime = refsystime;
554 double deltavstarget;
555
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);
568
569 while (1) {
570 double ticksize;
571
572 ON_DBG(RANDOM_SLEEP, up_to_1000ms_sleep());
573
574 gettimeofday(&nowsystime, NULL);
575 deltavstarget = time_diff(nowsystime, targetsystime);
576 ticksize = time_diff(nowsystime, prevsystime);
577 prevsystime = nowsystime;
578
579 if (ticksize < 0) {
580 if (ctl->verbose)
581 printf(_("time jumped backward %.6f seconds "
582 "to %"PRId64".%06"PRId64" - retargeting\n"),
583 ticksize, (int64_t)nowsystime.tv_sec,
584 (int64_t)nowsystime.tv_usec);
585 /* The retarget is handled at the end of the loop. */
586 } else if (deltavstarget < 0) {
587 /* deltavstarget < 0 if current time < target time */
588 DBG(DELTA_VS_TARGET,
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));
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 */
602 if (ctl->verbose)
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,
609 deltavstarget,
610 target_time_tolerance_secs);
611 target_time_tolerance_secs += tolerance_incr_secs;
612 tolerance_incr_secs *= 2;
613 }
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
627 + ceil(time_diff(nowsystime, refsystime)
628 - delay /* don't count this */);
629 if (ctl->verbose)
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,
634 deltavstarget, target_time_tolerance_secs,
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);
638
639 set_hardware_clock(ctl, newhwtime);
640 }
641
642 static int
643 display_time(struct timeval hwctime)
644 {
645 char buf[ISO_BUFSIZ];
646
647 if (strtimeval_iso(&hwctime, ISO_TIMESTAMP_DOT, buf, sizeof(buf)))
648 return EXIT_FAILURE;
649
650 printf("%s\n", buf);
651 return EXIT_SUCCESS;
652 }
653
654 /*
655 * Adjusts System time, sets the kernel's timezone and RTC timescale.
656 *
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.
660 *
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 * +-------------------------------------------------------------------------+
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).
674 *
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 |
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 |
682 * +---------------------------------------------------------------------------+
683 * * only on first call after boot
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.
690 */
691 #define __set_time(_tv) settimeofday(_tv, NULL)
692
693 #ifndef SYS_settimeofday
694 # ifdef __NR_settimeofday
695 # define SYS_settimeofday __NR_settimeofday
696 # elif defined(__NR_settimeofday_time32)
697 # define SYS_settimeofday __NR_settimeofday_time32
698 # endif
699 #endif
700
701 static 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
711 static int
712 set_system_clock(const struct hwclock_control *ctl,
713 const struct timeval newtime)
714 {
715 struct tm broken = { 0 };
716 int minuteswest;
717 int rc = 0;
718
719 localtime_r(&newtime.tv_sec, &broken);
720 minuteswest = -get_gmtoff(&broken) / 60;
721
722 if (ctl->verbose) {
723 if (ctl->universal) {
724 puts(_("Calling settimeofday(NULL, 0) "
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
735 if (ctl->hctosys)
736 printf(_("Calling settimeofday(%"PRId64".%06"PRId64", NULL) "
737 "to set the System time.\n"),
738 (int64_t)newtime.tv_sec, (int64_t)newtime.tv_usec);
739 }
740
741 if (!ctl->testing) {
742 const struct timezone tz_utc = { 0 };
743 const struct timezone tz = { minuteswest };
744
745 /* If UTC RTC: lock warp_clock and PCIL */
746 if (ctl->universal)
747 rc = __set_timezone(&tz_utc);
748
749 /* Set kernel tz; if localtime RTC: warp_clock and set PCIL */
750 if (!rc && !( ctl->universal && !minuteswest ))
751 rc = __set_timezone(&tz);
752
753 /* Set the System Clock */
754 if ((!rc || errno == ENOSYS) && ctl->hctosys)
755 rc = __set_time(&newtime);
756
757 if (rc) {
758 warn(_("settimeofday() failed"));
759 return EXIT_FAILURE;
760 }
761 }
762 return EXIT_SUCCESS;
763 }
764
765 /*
766 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
767 * to facilitate future drift calculations based on this set point.
768 *
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.
773 */
774 static void
775 adjust_drift_factor(const struct hwclock_control *ctl,
776 struct adjtime *adjtime_p,
777 const struct timeval nowtime,
778 const struct timeval hclocktime)
779 {
780 if (!ctl->update) {
781 if (ctl->verbose)
782 printf(_("Not adjusting drift factor because the "
783 "--update-drift option was not used.\n"));
784 } else if (adjtime_p->last_calib_time == 0) {
785 if (ctl->verbose)
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"));
790 } else if ((hclocktime.tv_sec - adjtime_p->last_calib_time) < 4 * 60 * 60) {
791 if (ctl->verbose)
792 printf(_("Not adjusting drift factor because it has "
793 "been less than four hours since the last "
794 "calibration.\n"));
795 } else {
796 /*
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.
800 *
801 * At calibration time we set the Hardware Clock and refresh
802 * both timestamps in <*adjtime_p>.
803 *
804 * Here, with the --update-drift option, we also update the
805 * drift factor in <*adjtime_p>.
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;
811 double factor_adjust;
812 double drift_factor;
813 struct timeval last_calib;
814
815 last_calib = t2tv(adjtime_p->last_calib_time);
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 */
824 factor_adjust = time_diff(nowtime, hclocktime) /
825 (time_diff(nowtime, last_calib) / sec_per_day);
826
827 drift_factor = adjtime_p->drift_factor + factor_adjust;
828 if (fabs(drift_factor) > MAX_DRIFT) {
829 if (ctl->verbose)
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 {
836 if (ctl->verbose)
837 printf(_("Clock drifted %f seconds in the past "
838 "%f seconds\nin spite of a drift factor of "
839 "%f seconds/day.\n"
840 "Adjusting drift factor by %f seconds/day\n"),
841 time_diff(nowtime, hclocktime),
842 time_diff(nowtime, last_calib),
843 adjtime_p->drift_factor, factor_adjust);
844 }
845
846 adjtime_p->drift_factor = drift_factor;
847 }
848 adjtime_p->last_calib_time = nowtime.tv_sec;
849
850 adjtime_p->last_adj_time = nowtime.tv_sec;
851
852 adjtime_p->not_adjusted = 0;
853
854 adjtime_p->dirty = 1;
855 }
856
857 /*
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.
861 *
862 * The total drift adjustment needed is stored at tdrift_p.
863 *
864 */
865 static void
866 calculate_adjustment(const struct hwclock_control *ctl,
867 const double factor,
868 const time_t last_time,
869 const double not_adjusted,
870 const time_t systime, struct timeval *tdrift_p)
871 {
872 double exact_adjustment;
873
874 exact_adjustment =
875 ((double)(systime - last_time)) * factor / (24 * 60 * 60)
876 + not_adjusted;
877 tdrift_p->tv_sec = (time_t) floor(exact_adjustment);
878 tdrift_p->tv_usec = (exact_adjustment -
879 (double)tdrift_p->tv_sec) * 1E6;
880 if (ctl->verbose) {
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);
887 }
888 }
889
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 */
896 static int save_adjtime(const struct hwclock_control *ctl,
897 const struct adjtime *adjtime)
898 {
899 char *content; /* Stuff to write to disk file */
900 FILE *fp;
901
902 xasprintf(&content, "%f %"PRId64" %f\n%"PRId64"\n%s\n",
903 adjtime->drift_factor,
904 (int64_t)adjtime->last_adj_time,
905 adjtime->not_adjusted,
906 (int64_t)adjtime->last_calib_time,
907 (adjtime->local_utc == LOCAL) ? "LOCAL" : "UTC");
908
909 if (ctl->verbose){
910 printf(_("New %s data:\n%s"),
911 ctl->adj_file_name, content);
912 }
913
914 if (!ctl->testing) {
915 int rc;
916
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;
921 }
922
923 rc = fputs(content, fp) < 0;
924 rc += close_stream(fp);
925
926 if (rc) {
927 warn(_("cannot update %s"), ctl->adj_file_name);
928 return EXIT_FAILURE;
929 }
930 }
931 return EXIT_SUCCESS;
932 }
933
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 *
942 * <hclocktime> is the drift corrected time read from the Hardware Clock.
943 *
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.
950 *
951 * <universal>: the Hardware Clock is kept in UTC.
952 *
953 * <testing>: We are running in test mode (no updating of clock).
954 *
955 */
956 static void
957 do_adjustment(const struct hwclock_control *ctl, struct adjtime *adjtime_p,
958 const struct timeval hclocktime,
959 const struct timeval read_time)
960 {
961 if (adjtime_p->last_adj_time == 0) {
962 if (ctl->verbose)
963 printf(_("Not setting clock because last adjustment time is zero, "
964 "so history is bad.\n"));
965 } else if (fabs(adjtime_p->drift_factor) > MAX_DRIFT) {
966 if (ctl->verbose)
967 printf(_("Not setting clock because drift factor %f is far too high.\n"),
968 adjtime_p->drift_factor);
969 } else {
970 set_hardware_clock_exact(ctl, hclocktime.tv_sec,
971 time_inc(read_time,
972 -(hclocktime.tv_usec / 1E6)));
973 adjtime_p->last_adj_time = hclocktime.tv_sec;
974 adjtime_p->not_adjusted = 0;
975 adjtime_p->dirty = 1;
976 }
977 }
978
979 static void determine_clock_access_method(const struct hwclock_control *ctl)
980 {
981 ur = NULL;
982
983 #ifdef USE_HWCLOCK_CMOS
984 if (ctl->directisa)
985 ur = probe_for_cmos_clock();
986 #endif
987 #ifdef __linux__
988 if (!ur)
989 ur = probe_for_rtc_clock(ctl);
990 #endif
991 if (ur) {
992 if (ctl->verbose)
993 puts(ur->interface_name);
994
995 } else {
996 if (ctl->verbose)
997 printf(_("No usable clock interface found.\n"));
998
999 warnx(_("Cannot access the Hardware Clock via "
1000 "any known method."));
1001
1002 if (!ctl->verbose)
1003 warnx(_("Use the --verbose option to see the "
1004 "details of our search for an access "
1005 "method."));
1006 hwclock_exit(ctl, EXIT_FAILURE);
1007 }
1008 }
1009
1010 /* Do all the normal work of hwclock - read, set clock, etc. */
1011 static int
1012 manipulate_clock(const struct hwclock_control *ctl, const time_t set_time,
1013 const struct timeval startup_time, struct adjtime *adjtime)
1014 {
1015 /* The time at which we read the Hardware Clock */
1016 struct timeval read_time = { 0 };
1017 /*
1018 * The Hardware Clock gives us a valid time, or at
1019 * least something close enough to fool mktime().
1020 */
1021 int hclock_valid = 0;
1022 /*
1023 * Tick synchronized time read from the Hardware Clock and
1024 * then drift corrected for all operations except --show.
1025 */
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 };
1032 /* Total Hardware Clock drift correction needed. */
1033 struct timeval tdrift = { 0 };
1034
1035 if ((ctl->set || ctl->systohc || ctl->adjust) &&
1036 (adjtime->local_utc == UTC) != ctl->universal) {
1037 adjtime->local_utc = ctl->universal ? UTC : LOCAL;
1038 adjtime->dirty = 1;
1039 }
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));
1052 if (ctl->verbose) {
1053 printf(_("Target date: %"PRId64"\n"), (int64_t)set_time);
1054 printf(_("Predicted RTC: %"PRId64"\n"), (int64_t)hclocktime.tv_sec);
1055 }
1056 return display_time(hclocktime);
1057 }
1058
1059 if (ctl->systz)
1060 return set_system_clock(ctl, startup_time);
1061
1062 if (ur->get_permissions())
1063 return EXIT_FAILURE;
1064
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)) {
1072 /*
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.
1077 */
1078 if (synchronize_to_clock_tick(ctl))
1079 return EXIT_FAILURE;
1080 read_hardware_clock(ctl, &hclock_valid, &hclocktime.tv_sec);
1081 gettimeofday(&read_time, NULL);
1082
1083 if (!hclock_valid) {
1084 warnx(_("RTC read returned an invalid value."));
1085 return EXIT_FAILURE;
1086 }
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);
1097
1098 startup_hclocktime =
1099 time_inc(hclocktime, time_diff(startup_time, read_time));
1100 }
1101 if (ctl->show || ctl->get) {
1102 return display_time(startup_hclocktime);
1103 }
1104
1105 if (ctl->set) {
1106 set_hardware_clock_exact(ctl, set_time, startup_time);
1107 if (!ctl->noadjfile)
1108 adjust_drift_factor(ctl, adjtime, t2tv(set_time),
1109 startup_hclocktime);
1110 } else if (ctl->adjust) {
1111 if (tdrift.tv_sec > 0 || tdrift.tv_sec < -1)
1112 do_adjustment(ctl, adjtime, hclocktime, read_time);
1113 else
1114 printf(_("Needed adjustment is less than one second, "
1115 "so not setting clock.\n"));
1116 } else if (ctl->systohc) {
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;
1127 set_hardware_clock_exact(ctl, (time_t) reftime.tv_sec, reftime);
1128 if (!ctl->noadjfile)
1129 adjust_drift_factor(ctl, adjtime, nowtime,
1130 hclocktime);
1131 } else if (ctl->hctosys) {
1132 return set_system_clock(ctl, hclocktime);
1133 }
1134 if (!ctl->noadjfile && adjtime->dirty)
1135 return save_adjtime(ctl, adjtime);
1136 return EXIT_SUCCESS;
1137 }
1138
1139 /**
1140 * Get or set the kernel RTC driver's epoch on Alpha machines.
1141 * ISA machines are hard coded for 1900.
1142 */
1143 #if defined(__linux__) && defined(__alpha__)
1144 static void
1145 manipulate_epoch(const struct hwclock_control *ctl)
1146 {
1147 if (ctl->getepoch) {
1148 unsigned long epoch;
1149
1150 if (get_epoch_rtc(ctl, &epoch))
1151 warnx(_("unable to read the RTC epoch."));
1152 else
1153 printf(_("The RTC epoch is set to %lu.\n"), epoch);
1154 } else if (ctl->setepoch) {
1155 if (!ctl->epoch_option)
1156 warnx(_("--epoch is required for --setepoch."));
1157 else if (!ctl->testing)
1158 if (set_epoch_rtc(ctl))
1159 warnx(_("unable to set the RTC epoch."));
1160 }
1161 }
1162 #endif /* __linux__ __alpha__ */
1163
1164 #ifdef __linux__
1165 static int
1166 manipulate_rtc_param(const struct hwclock_control *ctl)
1167 {
1168 if (ctl->param_get_option) {
1169 uint64_t id = 0, value = 0;
1170
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);
1174 return 1;
1175 }
1176
1177 printf(_("The RTC parameter 0x%jx is set to 0x%jx.\n"),
1178 (uintmax_t) id, (uintmax_t) value);
1179 return 0;
1180
1181 } else if (ctl->param_set_option) {
1182 if (ctl->testing)
1183 return 0;
1184
1185 return set_param_rtc(ctl, ctl->param_set_option);
1186 }
1187
1188 return 1;
1189 }
1190
1191 static int
1192 manipulate_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 }
1204 #endif
1205
1206 static void out_version(void)
1207 {
1208 printf(UTIL_LINUX_VERSION);
1209 }
1210
1211 static void __attribute__((__noreturn__))
1212 usage(void)
1213 {
1214 #ifdef __linux__
1215 const struct hwclock_param *param = get_hwclock_params();
1216 #endif
1217
1218 fputs(USAGE_HEADER, stdout);
1219 printf(_(" %s [function] [option...]\n"), program_invocation_short_name);
1220
1221 fputs(USAGE_SEPARATOR, stdout);
1222 puts(_("Time clocks utility."));
1223
1224 fputs(USAGE_FUNCTIONS, stdout);
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"));
1232 #if defined(__linux__) && defined(__alpha__)
1233 puts(_(" --getepoch display the RTC epoch"));
1234 puts(_(" --setepoch set the RTC epoch according to --epoch"));
1235 #endif
1236 #ifdef __linux__
1237 puts(_(" --param-get <param> display the RTC parameter"));
1238 puts(_(" --param-set <param>=<value> set the RTC parameter"));
1239 puts(_(" --vl-read read voltage low information"));
1240 puts(_(" --vl-clear clear voltage low information"));
1241 #endif
1242 puts(_(" --predict predict the drifted RTC time according to --date"));
1243 fputs(USAGE_OPTIONS, stdout);
1244 puts(_(" -u, --utc the RTC timescale is UTC"));
1245 puts(_(" -l, --localtime the RTC timescale is Local"));
1246 #ifdef __linux__
1247 printf(_(
1248 " -f, --rtc <file> use an alternate file to %1$s\n"), _PATH_RTC_DEV);
1249 #endif
1250 printf(_(
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"));
1254 #if defined(__linux__) && defined(__alpha__)
1255 puts(_(" --epoch <year> epoch input for --setepoch"));
1256 #endif
1257 puts(_(" --update-drift update the RTC drift factor"));
1258 printf(_(
1259 " --noadjfile do not use %1$s\n"), _PATH_ADJTIME);
1260 printf(_(
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
1265 fputs(USAGE_SEPARATOR, stdout);
1266 fprintf(stdout, USAGE_HELP_OPTIONS(33));
1267
1268 #ifdef __linux__
1269 fputs(USAGE_ARGUMENTS, stdout);
1270 fputs(_(" <param> is either a numeric RTC parameter value or one of these aliases:"), stdout);
1271
1272 while (param->name) {
1273 fprintf(stdout, _(" - %1$s: %2$s (0x%3$x)\n"), param->name, param->help, param->id);
1274 param++;
1275 }
1276
1277 fputs(_(" See Kernel's include/uapi/linux/rtc.h for parameters and values."), stdout);
1278 fputs(USAGE_ARG_SEPARATOR, stdout);
1279 fputs(_(" <param> and <value> accept hexadecimal values if prefixed with 0x, otherwise decimal."), stdout);
1280 #endif
1281 fprintf(stdout, USAGE_MAN_TAIL("hwclock(8)"));
1282 exit(EXIT_SUCCESS);
1283 }
1284
1285 int main(int argc, char **argv)
1286 {
1287 struct hwclock_control ctl = {
1288 .show = 1, /* default op is show */
1289 .rtc_delay = -1.0 /* unspecified */
1290 };
1291 struct timeval startup_time;
1292 struct adjtime adjtime = { 0 };
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 */
1298 int rc, c;
1299
1300 /* Long only options. */
1301 enum {
1302 OPT_ADJFILE = CHAR_MAX + 1,
1303 OPT_DATE,
1304 OPT_DELAY,
1305 OPT_DIRECTISA,
1306 OPT_EPOCH,
1307 OPT_GET,
1308 OPT_GETEPOCH,
1309 OPT_NOADJFILE,
1310 OPT_PARAM_GET,
1311 OPT_PARAM_SET,
1312 OPT_VL_READ,
1313 OPT_VL_CLEAR,
1314 OPT_PREDICT,
1315 OPT_SET,
1316 OPT_SETEPOCH,
1317 OPT_SYSTZ,
1318 OPT_TEST,
1319 OPT_UPDATE
1320 };
1321
1322 static const struct option longopts[] = {
1323 { "adjust", no_argument, NULL, 'a' },
1324 { "help", no_argument, NULL, 'h' },
1325 { "localtime", no_argument, NULL, 'l' },
1326 { "show", no_argument, NULL, 'r' },
1327 { "hctosys", no_argument, NULL, 's' },
1328 { "utc", no_argument, NULL, 'u' },
1329 { "version", no_argument, NULL, 'V' },
1330 { "systohc", no_argument, NULL, 'w' },
1331 { "debug", no_argument, NULL, 'D' },
1332 { "ul-debug", required_argument, NULL, 'd' },
1333 { "verbose", no_argument, NULL, 'v' },
1334 { "set", no_argument, NULL, OPT_SET },
1335 #if defined(__linux__) && defined(__alpha__)
1336 { "getepoch", no_argument, NULL, OPT_GETEPOCH },
1337 { "setepoch", no_argument, NULL, OPT_SETEPOCH },
1338 { "epoch", required_argument, NULL, OPT_EPOCH },
1339 #endif
1340 #ifdef __linux__
1341 { "param-get", required_argument, NULL, OPT_PARAM_GET },
1342 { "param-set", required_argument, NULL, OPT_PARAM_SET },
1343 { "vl-read", no_argument, NULL, OPT_VL_READ },
1344 { "vl-clear", no_argument, NULL, OPT_VL_CLEAR },
1345 #endif
1346 { "noadjfile", no_argument, NULL, OPT_NOADJFILE },
1347 { "directisa", no_argument, NULL, OPT_DIRECTISA },
1348 { "test", no_argument, NULL, OPT_TEST },
1349 { "date", required_argument, NULL, OPT_DATE },
1350 { "delay", required_argument, NULL, OPT_DELAY },
1351 #ifdef __linux__
1352 { "rtc", required_argument, NULL, 'f' },
1353 #endif
1354 { "adjfile", required_argument, NULL, OPT_ADJFILE },
1355 { "systz", no_argument, NULL, OPT_SYSTZ },
1356 { "predict", no_argument, NULL, OPT_PREDICT },
1357 { "get", no_argument, NULL, OPT_GET },
1358 { "update-drift", no_argument, NULL, OPT_UPDATE },
1359 { NULL, 0, NULL, 0 }
1360 };
1361
1362 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
1363 { 'a','r','s','w',
1364 OPT_GET, OPT_GETEPOCH, OPT_PREDICT,
1365 OPT_SET, OPT_SETEPOCH, OPT_SYSTZ },
1366 { 'l', 'u' },
1367 { OPT_ADJFILE, OPT_NOADJFILE },
1368 { OPT_NOADJFILE, OPT_UPDATE },
1369 { 0 }
1370 };
1371 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1372
1373 /* Remember what time we were invoked */
1374 gettimeofday(&startup_time, NULL);
1375
1376 #ifdef HAVE_LIBAUDIT
1377 hwaudit_fd = audit_open();
1378 if (hwaudit_fd < 0 && !(errno == EINVAL || errno == EPROTONOSUPPORT ||
1379 errno == EAFNOSUPPORT)) {
1380 /*
1381 * You get these error codes only when the kernel doesn't
1382 * have audit compiled in.
1383 */
1384 warnx(_("Unable to connect to audit system"));
1385 return EXIT_FAILURE;
1386 }
1387 #endif
1388 setlocale(LC_ALL, "");
1389 #ifdef LC_NUMERIC
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 */
1395 setlocale(LC_NUMERIC, "C");
1396 #endif
1397 bindtextdomain(PACKAGE, LOCALEDIR);
1398 textdomain(PACKAGE);
1399 close_stdout_atexit();
1400
1401 while ((c = getopt_long(argc, argv,
1402 "hvVDd:alrsuwf:", longopts, NULL)) != -1) {
1403
1404 err_exclusive_options(c, longopts, excl, excl_st);
1405
1406 switch (c) {
1407 case 'D':
1408 warnx(_("use --verbose, --debug has been deprecated."));
1409 break;
1410 case 'v':
1411 ctl.verbose = 1;
1412 break;
1413 case 'd':
1414 hwclock_init_debug(optarg);
1415 break;
1416 case 'a':
1417 ctl.adjust = 1;
1418 ctl.show = 0;
1419 ctl.hwaudit_on = 1;
1420 break;
1421 case 'l':
1422 ctl.local_opt = 1; /* --localtime */
1423 break;
1424 case 'r':
1425 ctl.show = 1;
1426 break;
1427 case 's':
1428 ctl.hctosys = 1;
1429 ctl.show = 0;
1430 ctl.hwaudit_on = 1;
1431 break;
1432 case 'u':
1433 ctl.utc = 1;
1434 break;
1435 case 'w':
1436 ctl.systohc = 1;
1437 ctl.show = 0;
1438 ctl.hwaudit_on = 1;
1439 break;
1440 case OPT_SET:
1441 ctl.set = 1;
1442 ctl.show = 0;
1443 ctl.hwaudit_on = 1;
1444 break;
1445 #if defined(__linux__) && defined(__alpha__)
1446 case OPT_GETEPOCH:
1447 ctl.getepoch = 1;
1448 ctl.show = 0;
1449 break;
1450 case OPT_SETEPOCH:
1451 ctl.setepoch = 1;
1452 ctl.show = 0;
1453 ctl.hwaudit_on = 1;
1454 break;
1455 case OPT_EPOCH:
1456 ctl.epoch_option = optarg; /* --epoch */
1457 break;
1458 #endif
1459 #ifdef __linux__
1460 case OPT_PARAM_GET:
1461 ctl.param_get_option = optarg;
1462 ctl.show = 0;
1463 break;
1464 case OPT_PARAM_SET:
1465 ctl.param_set_option = optarg;
1466 ctl.show = 0;
1467 ctl.hwaudit_on = 1;
1468 break;
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;
1477 #endif
1478 case OPT_NOADJFILE:
1479 ctl.noadjfile = 1;
1480 break;
1481 case OPT_DIRECTISA:
1482 ctl.directisa = 1;
1483 break;
1484 case OPT_TEST:
1485 ctl.testing = 1; /* --test */
1486 ctl.verbose = 1;
1487 break;
1488 case OPT_DATE:
1489 ctl.date_opt = optarg; /* --date */
1490 break;
1491 case OPT_DELAY:
1492 ctl.rtc_delay = strtod_or_err(optarg, "invalid --delay argument");
1493 break;
1494 case OPT_ADJFILE:
1495 ctl.adj_file_name = optarg; /* --adjfile */
1496 break;
1497 case OPT_SYSTZ:
1498 ctl.systz = 1; /* --systz */
1499 ctl.show = 0;
1500 ctl.hwaudit_on = 1;
1501 break;
1502 case OPT_PREDICT:
1503 ctl.predict = 1; /* --predict */
1504 ctl.show = 0;
1505 break;
1506 case OPT_GET:
1507 ctl.get = 1; /* --get */
1508 ctl.show = 0;
1509 break;
1510 case OPT_UPDATE:
1511 ctl.update = 1; /* --update-drift */
1512 break;
1513 #ifdef __linux__
1514 case 'f':
1515 ctl.rtc_dev_name = optarg; /* --rtc */
1516 break;
1517 #endif
1518
1519 case 'V': /* --version */
1520 print_version(EXIT_SUCCESS);
1521 case 'h': /* --help */
1522 usage();
1523 default:
1524 errtryhelp(EXIT_FAILURE);
1525 }
1526 }
1527
1528 if (argc -= optind) {
1529 warnx(_("too many arguments"));
1530 errtryhelp(EXIT_FAILURE);
1531 }
1532
1533 if (!ctl.adj_file_name)
1534 ctl.adj_file_name = _PATH_ADJTIME;
1535
1536 if (ctl.update && !ctl.set && !ctl.systohc) {
1537 warnx(_("--update-drift requires --set or --systohc"));
1538 exit(EXIT_FAILURE);
1539 }
1540
1541 if (ctl.noadjfile && !ctl.utc && !ctl.local_opt) {
1542 warnx(_("With --noadjfile, you must specify "
1543 "either --utc or --localtime"));
1544 exit(EXIT_FAILURE);
1545 }
1546
1547 if (ctl.set || ctl.predict) {
1548 if (!ctl.date_opt) {
1549 warnx(_("--date is required for --set or --predict"));
1550 exit(EXIT_FAILURE);
1551 }
1552 #ifdef USE_HWCLOCK_GPLv3_DATETIME
1553 /* date(1) compatible GPLv3 parser */
1554 struct timespec when = { 0 };
1555
1556 if (parse_date(&when, ctl.date_opt, NULL))
1557 set_time = when.tv_sec;
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
1565 else {
1566 warnx(_("invalid date '%s'"), ctl.date_opt);
1567 exit(EXIT_FAILURE);
1568 }
1569 }
1570
1571 #ifdef __linux__
1572 if (ctl.param_get_option || ctl.param_set_option) {
1573 if (manipulate_rtc_param(&ctl))
1574 hwclock_exit(&ctl, EXIT_FAILURE);
1575
1576 hwclock_exit(&ctl, EXIT_SUCCESS);
1577 }
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 }
1585 #endif
1586
1587 #if defined(__linux__) && defined(__alpha__)
1588 if (ctl.getepoch || ctl.setepoch) {
1589 manipulate_epoch(&ctl);
1590 hwclock_exit(&ctl, EXIT_SUCCESS);
1591 }
1592 #endif
1593
1594 if (ctl.verbose) {
1595 out_version();
1596 printf(_("System Time: %"PRId64".%06"PRId64"\n"),
1597 (int64_t)startup_time.tv_sec, (int64_t)startup_time.tv_usec);
1598 }
1599
1600 if (!ctl.systz && !ctl.predict)
1601 determine_clock_access_method(&ctl);
1602
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. */
1608 adjtime.dirty = 0;
1609
1610 ctl.universal = hw_clock_is_utc(&ctl, &adjtime);
1611 rc = manipulate_clock(&ctl, set_time, startup_time, &adjtime);
1612 if (ctl.testing)
1613 puts(_("Test mode: nothing was changed."));
1614 hwclock_exit(&ctl, rc);
1615 return rc; /* Not reached */
1616 }
1617
1618 void
1619 hwclock_exit(const struct hwclock_control *ctl
1620 #ifndef HAVE_LIBAUDIT
1621 __attribute__((__unused__))
1622 #endif
1623 , int status)
1624 {
1625 #ifdef HAVE_LIBAUDIT
1626 if (ctl->hwaudit_on && !ctl->testing) {
1627 audit_log_user_message(hwaudit_fd, AUDIT_USYS_CONFIG,
1628 "op=change-system-time", NULL, NULL, NULL,
1629 status == EXIT_SUCCESS ? 1 : 0);
1630 }
1631 close(hwaudit_fd);
1632 #endif
1633 exit(status);
1634 }
1635
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
1670 * and wrote feature test code to detect absence of rtc headers.
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 *
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 *
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
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.
1735 */