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