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