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