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