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