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