]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/hwclock.c
hwclock: don't use uninitialized value [coverity scan]
[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 if (ctl->directisa)
929 ur = probe_for_cmos_clock();
930 #ifdef __linux__
931 if (!ur)
932 ur = probe_for_rtc_clock(ctl);
933 #endif
934 if (ur) {
935 if (ctl->verbose)
936 puts(ur->interface_name);
937
938 } else {
939 if (ctl->verbose)
940 printf(_("No usable clock interface found.\n"));
941 warnx(_("Cannot access the Hardware Clock via "
942 "any known method."));
943 if (!ctl->verbose)
944 warnx(_("Use the --verbose option to see the "
945 "details of our search for an access "
946 "method."));
947 hwclock_exit(ctl, EXIT_FAILURE);
948 }
949 }
950
951 /* Do all the normal work of hwclock - read, set clock, etc. */
952 static int
953 manipulate_clock(const struct hwclock_control *ctl, const time_t set_time,
954 const struct timeval startup_time, struct adjtime *adjtime)
955 {
956 /* The time at which we read the Hardware Clock */
957 struct timeval read_time = { 0 };
958 /*
959 * The Hardware Clock gives us a valid time, or at
960 * least something close enough to fool mktime().
961 */
962 int hclock_valid = 0;
963 /*
964 * Tick synchronized time read from the Hardware Clock and
965 * then drift corrected for all operations except --show.
966 */
967 struct timeval hclocktime = { 0 };
968 /*
969 * hclocktime correlated to startup_time. That is, what drift
970 * corrected Hardware Clock time would have been at start up.
971 */
972 struct timeval startup_hclocktime = { 0 };
973 /* Total Hardware Clock drift correction needed. */
974 struct timeval tdrift = { 0 };
975
976 if ((ctl->set || ctl->systohc || ctl->adjust) &&
977 (adjtime->local_utc == UTC) != ctl->universal) {
978 adjtime->local_utc = ctl->universal ? UTC : LOCAL;
979 adjtime->dirty = 1;
980 }
981 /*
982 * Negate the drift correction, because we want to 'predict' a
983 * Hardware Clock time that includes drift.
984 */
985 if (ctl->predict) {
986 hclocktime = t2tv(set_time);
987 calculate_adjustment(ctl, adjtime->drift_factor,
988 adjtime->last_adj_time,
989 adjtime->not_adjusted,
990 hclocktime.tv_sec, &tdrift);
991 hclocktime = time_inc(hclocktime, (double)
992 -(tdrift.tv_sec + tdrift.tv_usec / 1E6));
993 if (ctl->verbose) {
994 printf(_ ("Target date: %ld\n"), set_time);
995 printf(_ ("Predicted RTC: %ld\n"), hclocktime.tv_sec);
996 }
997 return display_time(hclocktime);
998 }
999
1000 if (ctl->systz)
1001 return set_system_clock(ctl, startup_time);
1002
1003 if (ur->get_permissions())
1004 return EXIT_FAILURE;
1005
1006 /*
1007 * Read and drift correct RTC time; except for RTC set functions
1008 * without the --update-drift option because: 1) it's not needed;
1009 * 2) it enables setting a corrupted RTC without reading it first;
1010 * 3) it significantly reduces system shutdown time.
1011 */
1012 if ( ! ((ctl->set || ctl->systohc) && !ctl->update)) {
1013 /*
1014 * Timing critical - do not change the order of, or put
1015 * anything between the follow three statements.
1016 * Synchronization failure MUST exit, because all drift
1017 * operations are invalid without it.
1018 */
1019 if (synchronize_to_clock_tick(ctl))
1020 return EXIT_FAILURE;
1021 read_hardware_clock(ctl, &hclock_valid, &hclocktime.tv_sec);
1022 gettimeofday(&read_time, NULL);
1023
1024 if (!hclock_valid) {
1025 warnx(_("RTC read returned an invalid value."));
1026 return EXIT_FAILURE;
1027 }
1028 /*
1029 * Calculate and apply drift correction to the Hardware Clock
1030 * time for everything except --show
1031 */
1032 calculate_adjustment(ctl, adjtime->drift_factor,
1033 adjtime->last_adj_time,
1034 adjtime->not_adjusted,
1035 hclocktime.tv_sec, &tdrift);
1036 if (!ctl->show)
1037 hclocktime = time_inc(tdrift, hclocktime.tv_sec);
1038
1039 startup_hclocktime =
1040 time_inc(hclocktime, time_diff(startup_time, read_time));
1041 }
1042 if (ctl->show || ctl->get) {
1043 return display_time(startup_hclocktime);
1044 } else if (ctl->set) {
1045 set_hardware_clock_exact(ctl, set_time, startup_time);
1046 if (!ctl->noadjfile)
1047 adjust_drift_factor(ctl, adjtime, t2tv(set_time),
1048 startup_hclocktime);
1049 } else if (ctl->adjust) {
1050 if (tdrift.tv_sec > 0 || tdrift.tv_sec < -1)
1051 do_adjustment(ctl, adjtime, hclocktime, read_time);
1052 else
1053 printf(_("Needed adjustment is less than one second, "
1054 "so not setting clock.\n"));
1055 } else if (ctl->systohc) {
1056 struct timeval nowtime, reftime;
1057 /*
1058 * We can only set_hardware_clock_exact to a
1059 * whole seconds time, so we set it with
1060 * reference to the most recent whole
1061 * seconds time.
1062 */
1063 gettimeofday(&nowtime, NULL);
1064 reftime.tv_sec = nowtime.tv_sec;
1065 reftime.tv_usec = 0;
1066 set_hardware_clock_exact(ctl, (time_t) reftime.tv_sec, reftime);
1067 if (!ctl->noadjfile)
1068 adjust_drift_factor(ctl, adjtime, nowtime,
1069 hclocktime);
1070 } else if (ctl->hctosys) {
1071 return set_system_clock(ctl, hclocktime);
1072 }
1073 if (!ctl->noadjfile && adjtime->dirty)
1074 return save_adjtime(ctl, adjtime);
1075 return EXIT_SUCCESS;
1076 }
1077
1078 /**
1079 * Get or set the kernel RTC driver's epoch on Alpha machines.
1080 * ISA machines are hard coded for 1900.
1081 */
1082 #if defined(__linux__) && defined(__alpha__)
1083 static void
1084 manipulate_epoch(const struct hwclock_control *ctl)
1085 {
1086 if (ctl->getepoch) {
1087 unsigned long epoch;
1088
1089 if (get_epoch_rtc(ctl, &epoch))
1090 warnx(_("unable to read the RTC epoch."));
1091 else
1092 printf(_("The RTC epoch is set to %lu.\n"), epoch);
1093 } else if (ctl->setepoch) {
1094 if (!ctl->epoch_option)
1095 warnx(_("--epoch is required for --setepoch."));
1096 else if (!ctl->testing)
1097 if (set_epoch_rtc(ctl))
1098 warnx(_("unable to set the RTC epoch."));
1099 }
1100 }
1101 #endif /* __linux__ __alpha__ */
1102
1103 static void out_version(void)
1104 {
1105 printf(UTIL_LINUX_VERSION);
1106 }
1107
1108 static void __attribute__((__noreturn__))
1109 usage(void)
1110 {
1111 fputs(USAGE_HEADER, stdout);
1112 printf(_(" %s [function] [option...]\n"), program_invocation_short_name);
1113
1114 fputs(USAGE_SEPARATOR, stdout);
1115 puts(_("Time clocks utility."));
1116
1117 fputs(USAGE_FUNCTIONS, stdout);
1118 puts(_(" -r, --show display the RTC time"));
1119 puts(_(" --get display drift corrected RTC time"));
1120 puts(_(" --set set the RTC according to --date"));
1121 puts(_(" -s, --hctosys set the system time from the RTC"));
1122 puts(_(" -w, --systohc set the RTC from the system time"));
1123 puts(_(" --systz send timescale configurations to the kernel"));
1124 puts(_(" -a, --adjust adjust the RTC to account for systematic drift"));
1125 #if defined(__linux__) && defined(__alpha__)
1126 puts(_(" --getepoch display the RTC epoch"));
1127 puts(_(" --setepoch set the RTC epoch according to --epoch"));
1128 #endif
1129 puts(_(" --predict predict the drifted RTC time according to --date"));
1130 fputs(USAGE_OPTIONS, stdout);
1131 puts(_(" -u, --utc the RTC timescale is UTC"));
1132 puts(_(" -l, --localtime the RTC timescale is Local"));
1133 #ifdef __linux__
1134 printf(_(
1135 " -f, --rtc <file> use an alternate file to %1$s\n"), _PATH_RTC_DEV);
1136 #endif
1137 printf(_(
1138 " --directisa use the ISA bus instead of %1$s access\n"), _PATH_RTC_DEV);
1139 puts(_(" --date <time> date/time input for --set and --predict"));
1140 puts(_(" --delay <sec> delay used when set new RTC time"));
1141 #if defined(__linux__) && defined(__alpha__)
1142 puts(_(" --epoch <year> epoch input for --setepoch"));
1143 #endif
1144 puts(_(" --update-drift update the RTC drift factor"));
1145 printf(_(
1146 " --noadjfile do not use %1$s\n"), _PATH_ADJTIME);
1147 printf(_(
1148 " --adjfile <file> use an alternate file to %1$s\n"), _PATH_ADJTIME);
1149 puts(_(" --test dry run; implies --verbose"));
1150 puts(_(" -v, --verbose display more details"));
1151 fputs(USAGE_SEPARATOR, stdout);
1152 printf(USAGE_HELP_OPTIONS(22));
1153 printf(USAGE_MAN_TAIL("hwclock(8)"));
1154 exit(EXIT_SUCCESS);
1155 }
1156
1157 int main(int argc, char **argv)
1158 {
1159 struct hwclock_control ctl = {
1160 .show = 1, /* default op is show */
1161 .rtc_delay = -1.0 /* unspecified */
1162 };
1163 struct timeval startup_time;
1164 struct adjtime adjtime = { 0 };
1165 struct timespec when = { 0 };
1166 /*
1167 * The time we started up, in seconds into the epoch, including
1168 * fractions.
1169 */
1170 time_t set_time = 0; /* Time to which user said to set Hardware Clock */
1171 int rc, c;
1172
1173 /* Long only options. */
1174 enum {
1175 OPT_ADJFILE = CHAR_MAX + 1,
1176 OPT_DATE,
1177 OPT_DELAY,
1178 OPT_DIRECTISA,
1179 OPT_EPOCH,
1180 OPT_GET,
1181 OPT_GETEPOCH,
1182 OPT_NOADJFILE,
1183 OPT_PREDICT,
1184 OPT_SET,
1185 OPT_SETEPOCH,
1186 OPT_SYSTZ,
1187 OPT_TEST,
1188 OPT_UPDATE
1189 };
1190
1191 static const struct option longopts[] = {
1192 { "adjust", no_argument, NULL, 'a' },
1193 { "help", no_argument, NULL, 'h' },
1194 { "localtime", no_argument, NULL, 'l' },
1195 { "show", no_argument, NULL, 'r' },
1196 { "hctosys", no_argument, NULL, 's' },
1197 { "utc", no_argument, NULL, 'u' },
1198 { "version", no_argument, NULL, 'V' },
1199 { "systohc", no_argument, NULL, 'w' },
1200 { "debug", no_argument, NULL, 'D' },
1201 { "ul-debug", required_argument, NULL, 'd' },
1202 { "verbose", no_argument, NULL, 'v' },
1203 { "set", no_argument, NULL, OPT_SET },
1204 #if defined(__linux__) && defined(__alpha__)
1205 { "getepoch", no_argument, NULL, OPT_GETEPOCH },
1206 { "setepoch", no_argument, NULL, OPT_SETEPOCH },
1207 { "epoch", required_argument, NULL, OPT_EPOCH },
1208 #endif
1209 { "noadjfile", no_argument, NULL, OPT_NOADJFILE },
1210 { "directisa", no_argument, NULL, OPT_DIRECTISA },
1211 { "test", no_argument, NULL, OPT_TEST },
1212 { "date", required_argument, NULL, OPT_DATE },
1213 { "delay", required_argument, NULL, OPT_DELAY },
1214 #ifdef __linux__
1215 { "rtc", required_argument, NULL, 'f' },
1216 #endif
1217 { "adjfile", required_argument, NULL, OPT_ADJFILE },
1218 { "systz", no_argument, NULL, OPT_SYSTZ },
1219 { "predict", no_argument, NULL, OPT_PREDICT },
1220 { "get", no_argument, NULL, OPT_GET },
1221 { "update-drift", no_argument, NULL, OPT_UPDATE },
1222 { NULL, 0, NULL, 0 }
1223 };
1224
1225 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
1226 { 'a','r','s','w',
1227 OPT_GET, OPT_GETEPOCH, OPT_PREDICT,
1228 OPT_SET, OPT_SETEPOCH, OPT_SYSTZ },
1229 { 'l', 'u' },
1230 { OPT_ADJFILE, OPT_NOADJFILE },
1231 { OPT_NOADJFILE, OPT_UPDATE },
1232 { 0 }
1233 };
1234 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1235
1236 /* Remember what time we were invoked */
1237 gettimeofday(&startup_time, NULL);
1238
1239 #ifdef HAVE_LIBAUDIT
1240 hwaudit_fd = audit_open();
1241 if (hwaudit_fd < 0 && !(errno == EINVAL || errno == EPROTONOSUPPORT ||
1242 errno == EAFNOSUPPORT)) {
1243 /*
1244 * You get these error codes only when the kernel doesn't
1245 * have audit compiled in.
1246 */
1247 warnx(_("Unable to connect to audit system"));
1248 return EXIT_FAILURE;
1249 }
1250 #endif
1251 setlocale(LC_ALL, "");
1252 #ifdef LC_NUMERIC
1253 /*
1254 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1255 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1256 * - gqueri@mail.dotcom.fr
1257 */
1258 setlocale(LC_NUMERIC, "C");
1259 #endif
1260 bindtextdomain(PACKAGE, LOCALEDIR);
1261 textdomain(PACKAGE);
1262 close_stdout_atexit();
1263
1264 while ((c = getopt_long(argc, argv,
1265 "hvVDd:alrsuwf:", longopts, NULL)) != -1) {
1266
1267 err_exclusive_options(c, longopts, excl, excl_st);
1268
1269 switch (c) {
1270 case 'D':
1271 warnx(_("use --verbose, --debug has been deprecated."));
1272 break;
1273 case 'v':
1274 ctl.verbose = 1;
1275 break;
1276 case 'd':
1277 hwclock_init_debug(optarg);
1278 break;
1279 case 'a':
1280 ctl.adjust = 1;
1281 ctl.show = 0;
1282 ctl.hwaudit_on = 1;
1283 break;
1284 case 'l':
1285 ctl.local_opt = 1; /* --localtime */
1286 break;
1287 case 'r':
1288 ctl.show = 1;
1289 break;
1290 case 's':
1291 ctl.hctosys = 1;
1292 ctl.show = 0;
1293 ctl.hwaudit_on = 1;
1294 break;
1295 case 'u':
1296 ctl.utc = 1;
1297 break;
1298 case 'w':
1299 ctl.systohc = 1;
1300 ctl.show = 0;
1301 ctl.hwaudit_on = 1;
1302 break;
1303 case OPT_SET:
1304 ctl.set = 1;
1305 ctl.show = 0;
1306 ctl.hwaudit_on = 1;
1307 break;
1308 #if defined(__linux__) && defined(__alpha__)
1309 case OPT_GETEPOCH:
1310 ctl.getepoch = 1;
1311 ctl.show = 0;
1312 break;
1313 case OPT_SETEPOCH:
1314 ctl.setepoch = 1;
1315 ctl.show = 0;
1316 ctl.hwaudit_on = 1;
1317 break;
1318 case OPT_EPOCH:
1319 ctl.epoch_option = optarg; /* --epoch */
1320 break;
1321 #endif
1322 case OPT_NOADJFILE:
1323 ctl.noadjfile = 1;
1324 break;
1325 case OPT_DIRECTISA:
1326 ctl.directisa = 1;
1327 break;
1328 case OPT_TEST:
1329 ctl.testing = 1; /* --test */
1330 ctl.verbose = 1;
1331 break;
1332 case OPT_DATE:
1333 ctl.date_opt = optarg; /* --date */
1334 break;
1335 case OPT_DELAY:
1336 ctl.rtc_delay = strtod_or_err(optarg, "invalid --delay argument");
1337 break;
1338 case OPT_ADJFILE:
1339 ctl.adj_file_name = optarg; /* --adjfile */
1340 break;
1341 case OPT_SYSTZ:
1342 ctl.systz = 1; /* --systz */
1343 ctl.show = 0;
1344 ctl.hwaudit_on = 1;
1345 break;
1346 case OPT_PREDICT:
1347 ctl.predict = 1; /* --predict */
1348 ctl.show = 0;
1349 break;
1350 case OPT_GET:
1351 ctl.get = 1; /* --get */
1352 ctl.show = 0;
1353 break;
1354 case OPT_UPDATE:
1355 ctl.update = 1; /* --update-drift */
1356 break;
1357 #ifdef __linux__
1358 case 'f':
1359 ctl.rtc_dev_name = optarg; /* --rtc */
1360 break;
1361 #endif
1362
1363 case 'V': /* --version */
1364 print_version(EXIT_SUCCESS);
1365 case 'h': /* --help */
1366 usage();
1367 default:
1368 errtryhelp(EXIT_FAILURE);
1369 }
1370 }
1371
1372 if (argc -= optind) {
1373 warnx(_("%d too many arguments given"), argc);
1374 errtryhelp(EXIT_FAILURE);
1375 }
1376
1377 if (!ctl.adj_file_name)
1378 ctl.adj_file_name = _PATH_ADJTIME;
1379
1380 if (ctl.update && !ctl.set && !ctl.systohc) {
1381 warnx(_("--update-drift requires --set or --systohc"));
1382 exit(EXIT_FAILURE);
1383 }
1384
1385 if (ctl.noadjfile && !ctl.utc && !ctl.local_opt) {
1386 warnx(_("With --noadjfile, you must specify "
1387 "either --utc or --localtime"));
1388 exit(EXIT_FAILURE);
1389 }
1390
1391 if (ctl.set || ctl.predict) {
1392 if (!ctl.date_opt) {
1393 warnx(_("--date is required for --set or --predict"));
1394 exit(EXIT_FAILURE);
1395 }
1396 if (parse_date(&when, ctl.date_opt, NULL))
1397 set_time = when.tv_sec;
1398 else {
1399 warnx(_("invalid date '%s'"), ctl.date_opt);
1400 exit(EXIT_FAILURE);
1401 }
1402 }
1403
1404 #if defined(__linux__) && defined(__alpha__)
1405 if (ctl.getepoch || ctl.setepoch) {
1406 manipulate_epoch(&ctl);
1407 hwclock_exit(&ctl, EXIT_SUCCESS);
1408 }
1409 #endif
1410
1411 if (ctl.verbose) {
1412 out_version();
1413 printf(_("System Time: %ld.%06ld\n"),
1414 startup_time.tv_sec, startup_time.tv_usec);
1415 }
1416
1417 if (!ctl.systz && !ctl.predict)
1418 determine_clock_access_method(&ctl);
1419
1420 if (!ctl.noadjfile && !(ctl.systz && (ctl.utc || ctl.local_opt))) {
1421 if ((rc = read_adjtime(&ctl, &adjtime)) != 0)
1422 hwclock_exit(&ctl, rc);
1423 } else
1424 /* Avoid writing adjtime file if we don't have to. */
1425 adjtime.dirty = 0;
1426 ctl.universal = hw_clock_is_utc(&ctl, adjtime);
1427 rc = manipulate_clock(&ctl, set_time, startup_time, &adjtime);
1428 if (ctl.testing)
1429 puts(_("Test mode: nothing was changed."));
1430 hwclock_exit(&ctl, rc);
1431 return rc; /* Not reached */
1432 }
1433
1434 void
1435 hwclock_exit(const struct hwclock_control *ctl
1436 #ifndef HAVE_LIBAUDIT
1437 __attribute__((__unused__))
1438 #endif
1439 , int status)
1440 {
1441 #ifdef HAVE_LIBAUDIT
1442 if (ctl->hwaudit_on && !ctl->testing) {
1443 audit_log_user_message(hwaudit_fd, AUDIT_USYS_CONFIG,
1444 "op=change-system-time", NULL, NULL, NULL,
1445 status);
1446 }
1447 close(hwaudit_fd);
1448 #endif
1449 exit(status);
1450 }
1451
1452 /*
1453 * History of this program:
1454 *
1455 * 98.08.12 BJH Version 2.4
1456 *
1457 * Don't use century byte from Hardware Clock. Add comments telling why.
1458 *
1459 * 98.06.20 BJH Version 2.3.
1460 *
1461 * Make --hctosys set the kernel timezone from TZ environment variable
1462 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1463 *
1464 * 98.03.05 BJH. Version 2.2.
1465 *
1466 * Add --getepoch and --setepoch.
1467 *
1468 * Fix some word length things so it works on Alpha.
1469 *
1470 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1471 * case, busywait for the top of a second instead of blocking and waiting
1472 * for the update complete interrupt.
1473 *
1474 * Fix a bunch of bugs too numerous to mention.
1475 *
1476 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1477 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1478 * job (jei@iclnl.icl.nl).
1479 *
1480 * Use the rtc clock access method in preference to the KDGHWCLK method.
1481 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1482 *
1483 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1484 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1485 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1486 * and wrote feature test code to detect absence of rtc headers.
1487 *
1488 ***************************************************************************
1489 * Maintenance notes
1490 *
1491 * To compile this, you must use GNU compiler optimization (-O option) in
1492 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1493 * compile. If you don't optimize, which means the compiler will generate no
1494 * inline functions, the references to these functions in this program will
1495 * be compiled as external references. Since you probably won't be linking
1496 * with any functions by these names, you will have unresolved external
1497 * references when you link.
1498 *
1499 * Here's some info on how we must deal with the time that elapses while
1500 * this program runs: There are two major delays as we run:
1501 *
1502 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1503 * we are synchronized to the Hardware Clock.
1504 * 2) Running the "date" program to interpret the value of our --date
1505 * option.
1506 *
1507 * Reading the /etc/adjtime file is the next biggest source of delay and
1508 * uncertainty.
1509 *
1510 * The user wants to know what time it was at the moment he invoked us, not
1511 * some arbitrary time later. And in setting the clock, he is giving us the
1512 * time at the moment we are invoked, so if we set the clock some time
1513 * later, we have to add some time to that.
1514 *
1515 * So we check the system time as soon as we start up, then run "date" and
1516 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1517 * edge, then check the system time again to see how much time we spent. We
1518 * immediately read the clock then and (if appropriate) report that time,
1519 * and additionally, the delay we measured.
1520 *
1521 * If we're setting the clock to a time given by the user, we wait some more
1522 * so that the total delay is an integral number of seconds, then set the
1523 * Hardware Clock to the time the user requested plus that integral number
1524 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1525 *
1526 * If we're setting the clock to the system clock value, we wait for the
1527 * system clock to reach the top of a second, and then set the Hardware
1528 * Clock to the system clock's value.
1529 *
1530 * Here's an interesting point about setting the Hardware Clock: On my
1531 * machine, when you set it, it sets to that precise time. But one can
1532 * imagine another clock whose update oscillator marches on a steady one
1533 * second period, so updating the clock between any two oscillator ticks is
1534 * the same as updating it right at the earlier tick. To avoid any
1535 * complications that might cause, we set the clock as soon as possible
1536 * after an oscillator tick.
1537 *
1538 * About synchronizing to the Hardware Clock when reading the time: The
1539 * precision of the Hardware Clock counters themselves is one second. You
1540 * can't read the counters and find out that is 12:01:02.5. But if you
1541 * consider the location in time of the counter's ticks as part of its
1542 * value, then its precision is as infinite as time is continuous! What I'm
1543 * saying is this: To find out the _exact_ time in the hardware clock, we
1544 * wait until the next clock tick (the next time the second counter changes)
1545 * and measure how long we had to wait. We then read the value of the clock
1546 * counters and subtract the wait time and we know precisely what time it
1547 * was when we set out to query the time.
1548 *
1549 * hwclock uses this method, and considers the Hardware Clock to have
1550 * infinite precision.
1551 */