2 * SPDX-License-Identifier: GPL-2.0-or-later
4 * Since 7a3000f7ba548cf7d74ac77cc63fe8de228a669e (v2.30) hwclock is linked
5 * with parse_date.y from gnullib. This gnulib code is distributed with GPLv3.
6 * Use --disable-hwclock-gplv3 to exclude this code.
9 * clock.c was written by Charles Hedrick, hedrick@cs.rutgers.edu, Apr 1992
10 * Modified for clock adjustments - Rob Hooft <hooft@chem.ruu.nl>, Nov 1992
11 * Improvements by Harald Koenig <koenig@nova.tat.physik.uni-tuebingen.de>
12 * and Alan Modra <alan@spri.levels.unisa.edu.au>.
14 * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19.
15 * The new program is called hwclock. New features:
17 * - You can set the hardware clock without also modifying the system
19 * - You can read and set the clock with finer than 1 second precision.
20 * - When you set the clock, hwclock automatically refigures the drift
21 * rate, based on how far off the clock was before you set it.
23 * Reshuffled things, added sparc code, and re-added alpha stuff
24 * by David Mosberger <davidm@azstarnet.com>
25 * and Jay Estabrook <jestabro@amt.tay1.dec.com>
26 * and Martin Ostermann <ost@comnets.rwth-aachen.de>, aeb@cwi.nl, 990212.
28 * Fix for Award 2094 bug, Dave Coffin (dcoffin@shore.net) 11/12/98
29 * Change of local time handling, Stefan Ring <e9725446@stud3.tuwien.ac.at>
30 * Change of adjtime handling, James P. Rutledge <ao112@rgfn.epcc.edu>.
35 * Explanation of `adjusting' (Rob Hooft):
37 * The problem with my machine is that its CMOS clock is 10 seconds
38 * per day slow. With this version of clock.c, and my '/etc/rc.local'
39 * reading '/etc/clock -au' instead of '/etc/clock -u -s', this error
40 * is automatically corrected at every boot.
42 * To do this job, the program reads and writes the file '/etc/adjtime'
43 * to determine the correction, and to save its data. In this file are
46 * 1) the correction in seconds per day. (So if your clock runs 5
47 * seconds per day fast, the first number should read -5.0)
48 * 2) the number of seconds since 1/1/1970 the last time the program
50 * 3) the remaining part of a second which was leftover after the last
53 * Installation and use of this program:
55 * a) create a file '/etc/adjtime' containing as the first and only
57 * b) run 'clock -au' or 'clock -a', depending on whether your cmos is
58 * in universal or local time. This updates the second number.
59 * c) set your system time using the 'date' command.
60 * d) update your cmos time using 'clock -wu' or 'clock -w'
61 * e) replace the first number in /etc/adjtime by your correction.
62 * f) put the command 'clock -au' or 'clock -a' in your '/etc/rc.local'
74 #include <sys/syscall.h>
80 #include "closestream.h"
83 #include "pathnames.h"
85 #include "timeutils.h"
93 static int hwaudit_fd
= -1;
96 UL_DEBUG_DEFINE_MASK(hwclock
);
97 UL_DEBUG_DEFINE_MASKNAMES(hwclock
) = UL_DEBUG_EMPTY_MASKNAMES
;
99 /* The struct that holds our hardware access routines */
100 static struct clock_ops
*ur
;
102 /* Maximal clock adjustment in seconds per day.
103 (adjtime() glibc call has 2145 seconds limit on i386, so it is good enough for us as well,
104 43219 is a maximal safe value preventing exact_adjustment overflow.) */
105 #define MAX_DRIFT 2145.0
109 * This is information we keep in the adjtime file that tells us how
110 * to do drift corrections. Elements are all straight from the
111 * adjtime file, so see documentation of that file for details.
112 * Exception is <dirty>, which is an indication that what's in this
113 * structure is not what's in the disk file (because it has been
114 * updated since read from the disk file).
119 time_t last_adj_time
;
122 time_t last_calib_time
;
124 * The most recent time that we set the clock from an external
125 * authority (as opposed to just doing a drift adjustment)
128 enum a_local_utc
{ UTC
= 0, LOCAL
, UNKNOWN
} local_utc
;
130 * To which time zone, local or UTC, we most recently set the
135 static void hwclock_init_debug(const char *str
)
137 __UL_INIT_DEBUG_FROM_STRING(hwclock
, HWCLOCK_DEBUG_
, 0, str
);
139 DBG(INIT
, ul_debug("hwclock debug mask: 0x%04x", hwclock_debug_mask
));
140 DBG(INIT
, ul_debug("hwclock version: %s", PACKAGE_STRING
));
143 /* FOR TESTING ONLY: inject random delays of up to 1000ms */
144 static void up_to_1000ms_sleep(void)
146 int usec
= random() % 1000000;
148 DBG(RANDOM_SLEEP
, ul_debug("sleeping ~%d usec", usec
));
153 * time_t to timeval conversion.
155 static struct timeval
t2tv(time_t timet
)
157 struct timeval rettimeval
;
159 rettimeval
.tv_sec
= timet
;
160 rettimeval
.tv_usec
= 0;
165 * The difference in seconds between two times in "timeval" format.
167 double time_diff(struct timeval subtrahend
, struct timeval subtractor
)
169 return (subtrahend
.tv_sec
- subtractor
.tv_sec
)
170 + (subtrahend
.tv_usec
- subtractor
.tv_usec
) / 1E6
;
174 * The time, in "timeval" format, which is <increment> seconds after the
175 * time <addend>. Of course, <increment> may be negative.
177 static struct timeval
time_inc(struct timeval addend
, double increment
)
179 struct timeval newtime
;
181 newtime
.tv_sec
= addend
.tv_sec
+ (time_t)increment
;
182 newtime
.tv_usec
= addend
.tv_usec
+ (increment
- (time_t)increment
) * 1E6
;
185 * Now adjust it so that the microsecond value is between 0 and 1
188 if (newtime
.tv_usec
< 0) {
189 newtime
.tv_usec
+= 1E6
;
191 } else if (newtime
.tv_usec
>= 1E6
) {
192 newtime
.tv_usec
-= 1E6
;
199 hw_clock_is_utc(const struct hwclock_control
*ctl
,
200 const struct adjtime
*adjtime
)
205 ret
= 1; /* --utc explicitly given on command line */
206 else if (ctl
->local_opt
)
207 ret
= 0; /* --localtime explicitly given */
209 /* get info from adjtime file - default is UTC */
210 ret
= (adjtime
->local_utc
!= LOCAL
);
213 printf(_("Assuming hardware clock is kept in %s time.\n"),
214 ret
? _("UTC") : _("local"));
219 * Read the adjustment parameters out of the /etc/adjtime file.
221 * Return them as the adjtime structure <*adjtime_p>. Its defaults are
222 * initialized in main().
224 static int read_adjtime(const struct hwclock_control
*ctl
,
225 struct adjtime
*adjtime_p
)
228 char line1
[81]; /* String: first line of adjtime file */
229 char line2
[81]; /* String: second line of adjtime file */
230 char line3
[81]; /* String: third line of adjtime file */
231 int64_t last_adj_time
;
232 int64_t last_calib_time
;
234 if (access(ctl
->adj_file_name
, R_OK
) != 0)
237 adjfile
= fopen(ctl
->adj_file_name
, "r"); /* open file for reading */
238 if (adjfile
== NULL
) {
239 warn(_("cannot open %s"), ctl
->adj_file_name
);
243 if (!fgets(line1
, sizeof(line1
), adjfile
))
244 line1
[0] = '\0'; /* In case fgets fails */
245 if (!fgets(line2
, sizeof(line2
), adjfile
))
246 line2
[0] = '\0'; /* In case fgets fails */
247 if (!fgets(line3
, sizeof(line3
), adjfile
))
248 line3
[0] = '\0'; /* In case fgets fails */
252 sscanf(line1
, "%lf %"SCNd64
" %lf",
253 &adjtime_p
->drift_factor
,
255 &adjtime_p
->not_adjusted
);
257 sscanf(line2
, "%"SCNd64
, &last_calib_time
);
259 adjtime_p
->last_adj_time
= (time_t)last_adj_time
;
260 adjtime_p
->last_calib_time
= (time_t)last_calib_time
;
262 if (!strcmp(line3
, "UTC\n")) {
263 adjtime_p
->local_utc
= UTC
;
264 } else if (!strcmp(line3
, "LOCAL\n")) {
265 adjtime_p
->local_utc
= LOCAL
;
267 adjtime_p
->local_utc
= UNKNOWN
;
269 warnx(_("Warning: unrecognized third line in adjtime file\n"
270 "(Expected: `UTC' or `LOCAL' or nothing.)"));
275 printf(_("Last drift adjustment done at %"PRId64
" seconds after 1969\n"),
276 (int64_t)adjtime_p
->last_adj_time
);
277 printf(_("Last calibration done at %"PRId64
" seconds after 1969\n"),
278 (int64_t)adjtime_p
->last_calib_time
);
279 printf(_("Hardware clock is on %s time\n"),
280 (adjtime_p
->local_utc
==
281 LOCAL
) ? _("local") : (adjtime_p
->local_utc
==
282 UTC
) ? _("UTC") : _("unknown"));
289 * Wait until the falling edge of the Hardware Clock's update flag so that
290 * any time that is read from the clock immediately after we return will be
293 * The clock only has 1 second precision, so it gives the exact time only
294 * once per second, right on the falling edge of the update flag.
296 * We wait (up to one second) either blocked waiting for an rtc device or in
297 * a CPU spin loop. The former is probably not very accurate.
299 * Return 0 if it worked, nonzero if it didn't.
301 static int synchronize_to_clock_tick(const struct hwclock_control
*ctl
)
306 printf(_("Waiting for clock tick...\n"));
308 rc
= ur
->synchronize_to_clock_tick(ctl
);
312 printf(_("...synchronization failed\n"));
314 printf(_("...got clock tick\n"));
321 * Convert a time in broken down format (hours, minutes, etc.) into standard
322 * unix time (seconds into epoch). Return it as *systime_p.
324 * The broken down time is argument <tm>. This broken down time is either
325 * in local time zone or UTC, depending on value of logical argument
326 * "universal". True means it is in UTC.
328 * If the argument contains values that do not constitute a valid time, and
329 * mktime() recognizes this, return *valid_p == false and *systime_p
330 * undefined. However, mktime() sometimes goes ahead and computes a
331 * fictional time "as if" the input values were valid, e.g. if they indicate
332 * the 31st day of April, mktime() may compute the time of May 1. In such a
333 * case, we return the same fictional value mktime() does as *systime_p and
334 * return *valid_p == true.
337 mktime_tz(const struct hwclock_control
*ctl
, struct tm tm
,
343 *systime_p
= timegm(&tm
);
345 *systime_p
= mktime(&tm
);
346 if (*systime_p
== -1) {
348 * This apparently (not specified in mktime() documentation)
349 * means the 'tm' structure does not contain valid values
350 * (however, not containing valid values does _not_ imply
351 * mktime() returns -1).
355 printf(_("Invalid values in hardware clock: "
356 "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"),
357 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
,
358 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
362 printf(_("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
363 "%"PRId64
" seconds since 1969\n"), tm
.tm_year
+ 1900,
364 tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
, tm
.tm_min
,
365 tm
.tm_sec
, (int64_t)*systime_p
);
371 * Read the hardware clock and return the current time via <tm> argument.
373 * Use the method indicated by <method> argument to access the hardware
377 read_hardware_clock(const struct hwclock_control
*ctl
,
378 int *valid_p
, time_t *systime_p
)
383 err
= ur
->read_hardware_clock(ctl
, &tm
);
388 printf(_("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
389 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
,
390 tm
.tm_min
, tm
.tm_sec
);
391 *valid_p
= mktime_tz(ctl
, tm
, systime_p
);
397 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
398 * according to <universal>.
401 set_hardware_clock(const struct hwclock_control
*ctl
, const time_t newtime
)
403 struct tm new_broken_time
;
405 * Time to which we will set Hardware Clock, in broken down format,
406 * in the time zone of caller's choice
410 gmtime_r(&newtime
, &new_broken_time
);
412 localtime_r(&newtime
, &new_broken_time
);
415 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
416 "= %"PRId64
" seconds since 1969\n"),
417 new_broken_time
.tm_hour
, new_broken_time
.tm_min
,
418 new_broken_time
.tm_sec
, (int64_t)newtime
);
421 ur
->set_hardware_clock(ctl
, &new_broken_time
);
425 get_hardware_delay(const struct hwclock_control
*ctl
)
427 const char *devpath
, *rtcname
;
432 devpath
= ur
->get_device_path();
436 rtcname
= strrchr(devpath
, '/');
437 if (!rtcname
|| !*(rtcname
+ 1))
441 pc
= ul_new_path("/sys/class/rtc/%s", rtcname
);
444 rc
= ul_path_scanf(pc
, "name", "%128[^\n ]", name
);
447 if (rc
!= 1 || !*name
)
451 printf(_("RTC type: '%s'\n"), name
);
453 /* MC146818A-compatible (x86) */
454 if (strcmp(name
, "rtc_cmos") == 0)
460 /* Let's be backwardly compatible */
466 * Set the Hardware Clock to the time "sethwtime", in local time zone or
467 * UTC, according to "universal".
469 * Wait for a fraction of a second so that "sethwtime" is the value of the
470 * Hardware Clock as of system time "refsystime", which is in the past. For
471 * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and
472 * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2
473 * seconds since "refsystime") and then set the Hardware Clock to 14:03:07,
474 * thus getting a precise and retroactive setting of the clock. The .5 delay is
475 * default on x86, see --delay and get_hardware_delay().
477 * (Don't be confused by the fact that the system clock and the Hardware
478 * Clock differ by two hours in the above example. That's just to remind you
479 * that there are two independent time scales here).
481 * This function ought to be able to accept set times as fractional times.
482 * Idea for future enhancement.
485 set_hardware_clock_exact(const struct hwclock_control
*ctl
,
486 const time_t sethwtime
,
487 const struct timeval refsystime
)
490 * The Hardware Clock can only be set to any integer time plus one
491 * half second. The integer time is required because there is no
492 * interface to set or get a fractional second. The additional half
493 * second is because the Hardware Clock updates to the following
494 * second precisely 500 ms (not 1 second!) after you release the
495 * divider reset (after setting the new time) - see description of
496 * DV2, DV1, DV0 in Register A in the MC146818A data sheet (and note
497 * that although that document doesn't say so, real-world code seems
498 * to expect that the SET bit in Register B functions the same way).
499 * That means that, e.g., when you set the clock to 1:02:03, it
500 * effectively really sets it to 1:02:03.5, because it will update to
501 * 1:02:04 only half a second later. Our caller passes the desired
502 * integer Hardware Clock time in sethwtime, and the corresponding
503 * system time (which may have a fractional part, and which may or may
504 * not be the same!) in refsystime. In an ideal situation, we would
505 * then apply sethwtime to the Hardware Clock at refsystime+500ms, so
506 * that when the Hardware Clock ticks forward to sethwtime+1s half a
507 * second later at refsystime+1000ms, everything is in sync. So we
508 * spin, waiting for gettimeofday() to return a time at or after that
509 * time (refsystime+500ms) up to a tolerance value, initially 1ms. If
510 * we miss that time due to being preempted for some other process,
511 * then we increase the margin a little bit (initially 1ms, doubling
512 * each time), add 1 second (or more, if needed to get a time that is
513 * in the future) to both the time for which we are waiting and the
514 * time that we will apply to the Hardware Clock, and start waiting
517 * For example, the caller requests that we set the Hardware Clock to
518 * 1:02:03, with reference time (current system time) = 6:07:08.250.
519 * We want the Hardware Clock to update to 1:02:04 at 6:07:09.250 on
520 * the system clock, and the first such update will occur 0.500
521 * seconds after we write to the Hardware Clock, so we spin until the
522 * system clock reads 6:07:08.750. If we get there, great, but let's
523 * imagine the system is so heavily loaded that our process is
524 * preempted and by the time we get to run again, the system clock
525 * reads 6:07:11.990. We now want to wait until the next xx:xx:xx.750
526 * time, which is 6:07:12.750 (4.5 seconds after the reference time),
527 * at which point we will set the Hardware Clock to 1:02:07 (4 seconds
528 * after the originally requested time). If we do that successfully,
529 * then at 6:07:13.250 (5 seconds after the reference time), the
530 * Hardware Clock will update to 1:02:08 (5 seconds after the
531 * originally requested time), and all is well thereafter.
534 time_t newhwtime
= sethwtime
;
535 double target_time_tolerance_secs
= 0.001; /* initial value */
536 double tolerance_incr_secs
= 0.001; /* initial value */
538 struct timeval rtc_set_delay_tv
;
540 struct timeval targetsystime
;
541 struct timeval nowsystime
;
542 struct timeval prevsystime
= refsystime
;
543 double deltavstarget
;
545 if (ctl
->rtc_delay
!= -1.0) /* --delay specified */
546 delay
= ctl
->rtc_delay
;
548 delay
= get_hardware_delay(ctl
);
551 printf(_("Using delay: %.6f seconds\n"), delay
);
553 rtc_set_delay_tv
.tv_sec
= 0;
554 rtc_set_delay_tv
.tv_usec
= delay
* 1E6
;
556 timeradd(&refsystime
, &rtc_set_delay_tv
, &targetsystime
);
561 ON_DBG(RANDOM_SLEEP
, up_to_1000ms_sleep());
563 gettimeofday(&nowsystime
, NULL
);
564 deltavstarget
= time_diff(nowsystime
, targetsystime
);
565 ticksize
= time_diff(nowsystime
, prevsystime
);
566 prevsystime
= nowsystime
;
570 printf(_("time jumped backward %.6f seconds "
571 "to %"PRId64
".%06"PRId64
" - retargeting\n"),
572 ticksize
, (int64_t)nowsystime
.tv_sec
,
573 (int64_t)nowsystime
.tv_usec
);
574 /* The retarget is handled at the end of the loop. */
575 } else if (deltavstarget
< 0) {
576 /* deltavstarget < 0 if current time < target time */
578 ul_debug("%"PRId64
".%06"PRId64
" < %"PRId64
".%06"PRId64
" (%.6f)",
579 (int64_t)nowsystime
.tv_sec
, (int64_t)nowsystime
.tv_usec
,
580 (int64_t)targetsystime
.tv_sec
,
581 (int64_t)targetsystime
.tv_usec
, deltavstarget
));
582 continue; /* not there yet - keep spinning */
583 } else if (deltavstarget
<= target_time_tolerance_secs
) {
584 /* Close enough to the target time; done waiting. */
586 } else /* (deltavstarget > target_time_tolerance_secs) */ {
588 * We missed our window. Increase the tolerance and
589 * aim for the next opportunity.
592 printf(_("missed it - %"PRId64
".%06"PRId64
" is too far "
593 "past %"PRId64
".%06"PRId64
" (%.6f > %.6f)\n"),
594 (int64_t)nowsystime
.tv_sec
,
595 (int64_t)nowsystime
.tv_usec
,
596 (int64_t)targetsystime
.tv_sec
,
597 (int64_t)targetsystime
.tv_usec
,
599 target_time_tolerance_secs
);
600 target_time_tolerance_secs
+= tolerance_incr_secs
;
601 tolerance_incr_secs
*= 2;
605 * Aim for the same offset (tv_usec) within the second in
606 * either the current second (if that offset hasn't arrived
607 * yet), or the next second.
609 if (nowsystime
.tv_usec
< targetsystime
.tv_usec
)
610 targetsystime
.tv_sec
= nowsystime
.tv_sec
;
612 targetsystime
.tv_sec
= nowsystime
.tv_sec
+ 1;
615 newhwtime
= sethwtime
616 + ceil(time_diff(nowsystime
, refsystime
)
617 - delay
/* don't count this */);
619 printf(_("%"PRId64
".%06"PRId64
" is close enough to %"PRId64
".%06"PRId64
" (%.6f < %.6f)\n"
620 "Set RTC to %"PRId64
" (%"PRId64
" + %d; refsystime = %"PRId64
".%06"PRId64
")\n"),
621 (int64_t)nowsystime
.tv_sec
, (int64_t)nowsystime
.tv_usec
,
622 (int64_t)targetsystime
.tv_sec
, (int64_t)targetsystime
.tv_usec
,
623 deltavstarget
, target_time_tolerance_secs
,
624 (int64_t)newhwtime
, (int64_t)sethwtime
,
625 (int)((int64_t)newhwtime
- (int64_t)sethwtime
),
626 (int64_t)refsystime
.tv_sec
, (int64_t)refsystime
.tv_usec
);
628 set_hardware_clock(ctl
, newhwtime
);
632 display_time(struct timeval hwctime
)
634 char buf
[ISO_BUFSIZ
];
636 if (strtimeval_iso(&hwctime
, ISO_TIMESTAMP_DOT
, buf
, sizeof(buf
)))
644 * Adjusts System time, sets the kernel's timezone and RTC timescale.
646 * The kernel warp_clock function adjusts the System time according to the
647 * tz.tz_minuteswest argument and sets PCIL (see below). At boot settimeofday(2)
648 * has one-shot access to this function as shown in the table below.
650 * +-------------------------------------------------------------------------+
651 * | settimeofday(tv, tz) |
652 * |-------------------------------------------------------------------------|
653 * | Arguments | System Time | TZ | PCIL | | warp_clock |
654 * | tv | tz | set | warped | set | set | firsttime | locked |
655 * |---------|---------|---------------|-----|------|-----------|------------|
656 * | pointer | NULL | yes | no | no | no | 1 | no |
657 * | NULL | ptr2utc | no | no | yes | no | 0 | yes |
658 * | NULL | pointer | no | yes | yes | yes | 0 | yes |
659 * +-------------------------------------------------------------------------+
660 * ptr2utc: tz.tz_minuteswest is zero (UTC).
661 * PCIL: persistent_clock_is_local, sets the "11 minute mode" timescale.
662 * firsttime: locks the warp_clock function (initialized to 1 at boot).
664 * +---------------------------------------------------------------------------+
665 * | op | RTC scale | settimeofday calls |
666 * |---------|-----------|-----------------------------------------------------|
667 * | systz | Local | 1) warps system time*, sets PCIL* and kernel tz |
668 * | systz | UTC | 1st) locks warp_clock* 2nd) sets kernel tz |
669 * | hctosys | Local | 1st) sets PCIL* & kernel tz 2nd) sets system time |
670 * | hctosys | UTC | 1st) locks warp* 2nd) sets tz 3rd) sets system time |
671 * +---------------------------------------------------------------------------+
672 * * only on first call after boot
674 * POSIX 2008 marked TZ in settimeofday() as deprecated. Unfortunately,
675 * different C libraries react to this deprecation in a different way. Since
676 * glibc v2.31 settimeofday() will fail if both args are not NULL, Musl-C
677 * ignores TZ at all, etc. We use __set_time() and __set_timezone() to hide
678 * these portability issues and to keep code readable.
680 #define __set_time(_tv) settimeofday(_tv, NULL)
682 #ifndef SYS_settimeofday
683 # ifdef __NR_settimeofday
684 # define SYS_settimeofday __NR_settimeofday
685 # elif defined(__NR_settimeofday_time32)
686 # define SYS_settimeofday __NR_settimeofday_time32
690 static inline int __set_timezone(const struct timezone
*tz
)
692 #ifdef SYS_settimeofday
694 return syscall(SYS_settimeofday
, NULL
, tz
);
696 return settimeofday(NULL
, tz
);
701 set_system_clock(const struct hwclock_control
*ctl
,
702 const struct timeval newtime
)
708 localtime_r(&newtime
.tv_sec
, &broken
);
709 minuteswest
= -get_gmtoff(&broken
) / 60;
712 if (ctl
->universal
) {
713 puts(_("Calling settimeofday(NULL, 0) "
714 "to lock the warp_clock function."));
715 if (!( ctl
->universal
&& !minuteswest
))
716 printf(_("Calling settimeofday(NULL, %d) "
717 "to set the kernel timezone.\n"),
720 printf(_("Calling settimeofday(NULL, %d) to warp "
721 "System time, set PCIL and the kernel tz.\n"),
725 printf(_("Calling settimeofday(%"PRId64
".%06"PRId64
", NULL) "
726 "to set the System time.\n"),
727 (int64_t)newtime
.tv_sec
, (int64_t)newtime
.tv_usec
);
731 const struct timezone tz_utc
= { 0 };
732 const struct timezone tz
= { minuteswest
};
734 /* If UTC RTC: lock warp_clock and PCIL */
736 rc
= __set_timezone(&tz_utc
);
738 /* Set kernel tz; if localtime RTC: warp_clock and set PCIL */
739 if (!rc
&& !( ctl
->universal
&& !minuteswest
))
740 rc
= __set_timezone(&tz
);
742 /* Set the System Clock */
743 if ((!rc
|| errno
== ENOSYS
) && ctl
->hctosys
)
744 rc
= __set_time(&newtime
);
747 warn(_("settimeofday() failed"));
755 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
756 * to facilitate future drift calculations based on this set point.
758 * With the --update-drift option:
759 * Update the drift factor in <*adjtime_p> based on the fact that the
760 * Hardware Clock was just calibrated to <nowtime> and before that was
761 * set to the <hclocktime> time scale.
764 adjust_drift_factor(const struct hwclock_control
*ctl
,
765 struct adjtime
*adjtime_p
,
766 const struct timeval nowtime
,
767 const struct timeval hclocktime
)
771 printf(_("Not adjusting drift factor because the "
772 "--update-drift option was not used.\n"));
773 } else if (adjtime_p
->last_calib_time
== 0) {
775 printf(_("Not adjusting drift factor because last "
776 "calibration time is zero,\n"
777 "so history is bad and calibration startover "
779 } else if ((hclocktime
.tv_sec
- adjtime_p
->last_calib_time
) < 4 * 60 * 60) {
781 printf(_("Not adjusting drift factor because it has "
782 "been less than four hours since the last "
786 * At adjustment time we drift correct the hardware clock
787 * according to the contents of the adjtime file and refresh
788 * its last adjusted timestamp.
790 * At calibration time we set the Hardware Clock and refresh
791 * both timestamps in <*adjtime_p>.
793 * Here, with the --update-drift option, we also update the
794 * drift factor in <*adjtime_p>.
796 * Let us do computation in doubles. (Floats almost suffice,
797 * but 195 days + 1 second equals 195 days in floats.)
799 const double sec_per_day
= 24.0 * 60.0 * 60.0;
800 double factor_adjust
;
802 struct timeval last_calib
;
804 last_calib
= t2tv(adjtime_p
->last_calib_time
);
806 * Correction to apply to the current drift factor.
808 * Simplified: uncorrected_drift / days_since_calibration.
810 * hclocktime is fully corrected with the current drift factor.
811 * Its difference from nowtime is the missed drift correction.
813 factor_adjust
= time_diff(nowtime
, hclocktime
) /
814 (time_diff(nowtime
, last_calib
) / sec_per_day
);
816 drift_factor
= adjtime_p
->drift_factor
+ factor_adjust
;
817 if (fabs(drift_factor
) > MAX_DRIFT
) {
819 printf(_("Clock drift factor was calculated as "
821 "It is far too much. Resetting to zero.\n"),
826 printf(_("Clock drifted %f seconds in the past "
827 "%f seconds\nin spite of a drift factor of "
829 "Adjusting drift factor by %f seconds/day\n"),
830 time_diff(nowtime
, hclocktime
),
831 time_diff(nowtime
, last_calib
),
832 adjtime_p
->drift_factor
, factor_adjust
);
835 adjtime_p
->drift_factor
= drift_factor
;
837 adjtime_p
->last_calib_time
= nowtime
.tv_sec
;
839 adjtime_p
->last_adj_time
= nowtime
.tv_sec
;
841 adjtime_p
->not_adjusted
= 0;
843 adjtime_p
->dirty
= 1;
847 * Calculate the drift correction currently needed for the
848 * Hardware Clock based on the last time it was adjusted,
849 * and the current drift factor, as stored in the adjtime file.
851 * The total drift adjustment needed is stored at tdrift_p.
855 calculate_adjustment(const struct hwclock_control
*ctl
,
857 const time_t last_time
,
858 const double not_adjusted
,
859 const time_t systime
, struct timeval
*tdrift_p
)
861 double exact_adjustment
;
864 ((double)(systime
- last_time
)) * factor
/ (24 * 60 * 60)
866 tdrift_p
->tv_sec
= (time_t) floor(exact_adjustment
);
867 tdrift_p
->tv_usec
= (exact_adjustment
-
868 (double)tdrift_p
->tv_sec
) * 1E6
;
870 printf(P_("Time since last adjustment is %"PRId64
" second\n",
871 "Time since last adjustment is %"PRId64
" seconds\n",
872 ((int64_t)systime
- (int64_t)last_time
)),
873 ((int64_t)systime
- (int64_t)last_time
));
874 printf(_("Calculated Hardware Clock drift is %"PRId64
".%06"PRId64
" seconds\n"),
875 (int64_t)tdrift_p
->tv_sec
, (int64_t)tdrift_p
->tv_usec
);
880 * Write the contents of the <adjtime> structure to its disk file.
882 * But if the contents are clean (unchanged since read from disk), don't
885 static int save_adjtime(const struct hwclock_control
*ctl
,
886 const struct adjtime
*adjtime
)
888 char *content
; /* Stuff to write to disk file */
891 xasprintf(&content
, "%f %"PRId64
" %f\n%"PRId64
"\n%s\n",
892 adjtime
->drift_factor
,
893 (int64_t)adjtime
->last_adj_time
,
894 adjtime
->not_adjusted
,
895 (int64_t)adjtime
->last_calib_time
,
896 (adjtime
->local_utc
== LOCAL
) ? "LOCAL" : "UTC");
899 printf(_("New %s data:\n%s"),
900 ctl
->adj_file_name
, content
);
906 fp
= fopen(ctl
->adj_file_name
, "w");
908 warn(_("cannot open %s"), ctl
->adj_file_name
);
912 rc
= fputs(content
, fp
) < 0;
913 rc
+= close_stream(fp
);
916 warn(_("cannot update %s"), ctl
->adj_file_name
);
924 * Do the adjustment requested, by 1) setting the Hardware Clock (if
925 * necessary), and 2) updating the last-adjusted time in the adjtime
928 * Do not update anything if the Hardware Clock does not currently present a
931 * <hclocktime> is the drift corrected time read from the Hardware Clock.
933 * <read_time> was the system time when the <hclocktime> was read, which due
934 * to computational delay could be a short time ago. It is used to define a
935 * trigger point for setting the Hardware Clock. The fractional part of the
936 * Hardware clock set time is subtracted from read_time to 'refer back', or
937 * delay, the trigger point. Fractional parts must be accounted for in this
938 * way, because the Hardware Clock can only be set to a whole second.
940 * <universal>: the Hardware Clock is kept in UTC.
942 * <testing>: We are running in test mode (no updating of clock).
946 do_adjustment(const struct hwclock_control
*ctl
, struct adjtime
*adjtime_p
,
947 const struct timeval hclocktime
,
948 const struct timeval read_time
)
950 if (adjtime_p
->last_adj_time
== 0) {
952 printf(_("Not setting clock because last adjustment time is zero, "
953 "so history is bad.\n"));
954 } else if (fabs(adjtime_p
->drift_factor
) > MAX_DRIFT
) {
956 printf(_("Not setting clock because drift factor %f is far too high.\n"),
957 adjtime_p
->drift_factor
);
959 set_hardware_clock_exact(ctl
, hclocktime
.tv_sec
,
961 -(hclocktime
.tv_usec
/ 1E6
)));
962 adjtime_p
->last_adj_time
= hclocktime
.tv_sec
;
963 adjtime_p
->not_adjusted
= 0;
964 adjtime_p
->dirty
= 1;
968 static void determine_clock_access_method(const struct hwclock_control
*ctl
)
972 #ifdef USE_HWCLOCK_CMOS
974 ur
= probe_for_cmos_clock();
978 ur
= probe_for_rtc_clock(ctl
);
982 puts(ur
->interface_name
);
986 printf(_("No usable clock interface found.\n"));
988 warnx(_("Cannot access the Hardware Clock via "
989 "any known method."));
992 warnx(_("Use the --verbose option to see the "
993 "details of our search for an access "
995 hwclock_exit(ctl
, EXIT_FAILURE
);
999 /* Do all the normal work of hwclock - read, set clock, etc. */
1001 manipulate_clock(const struct hwclock_control
*ctl
, const time_t set_time
,
1002 const struct timeval startup_time
, struct adjtime
*adjtime
)
1004 /* The time at which we read the Hardware Clock */
1005 struct timeval read_time
= { 0 };
1007 * The Hardware Clock gives us a valid time, or at
1008 * least something close enough to fool mktime().
1010 int hclock_valid
= 0;
1012 * Tick synchronized time read from the Hardware Clock and
1013 * then drift corrected for all operations except --show.
1015 struct timeval hclocktime
= { 0 };
1017 * hclocktime correlated to startup_time. That is, what drift
1018 * corrected Hardware Clock time would have been at start up.
1020 struct timeval startup_hclocktime
= { 0 };
1021 /* Total Hardware Clock drift correction needed. */
1022 struct timeval tdrift
= { 0 };
1024 if ((ctl
->set
|| ctl
->systohc
|| ctl
->adjust
) &&
1025 (adjtime
->local_utc
== UTC
) != ctl
->universal
) {
1026 adjtime
->local_utc
= ctl
->universal
? UTC
: LOCAL
;
1030 * Negate the drift correction, because we want to 'predict' a
1031 * Hardware Clock time that includes drift.
1034 hclocktime
= t2tv(set_time
);
1035 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1036 adjtime
->last_adj_time
,
1037 adjtime
->not_adjusted
,
1038 hclocktime
.tv_sec
, &tdrift
);
1039 hclocktime
= time_inc(hclocktime
, (double)
1040 -(tdrift
.tv_sec
+ tdrift
.tv_usec
/ 1E6
));
1042 printf(_("Target date: %"PRId64
"\n"), (int64_t)set_time
);
1043 printf(_("Predicted RTC: %"PRId64
"\n"), (int64_t)hclocktime
.tv_sec
);
1045 return display_time(hclocktime
);
1049 return set_system_clock(ctl
, startup_time
);
1051 if (ur
->get_permissions())
1052 return EXIT_FAILURE
;
1055 * Read and drift correct RTC time; except for RTC set functions
1056 * without the --update-drift option because: 1) it's not needed;
1057 * 2) it enables setting a corrupted RTC without reading it first;
1058 * 3) it significantly reduces system shutdown time.
1060 if ( ! ((ctl
->set
|| ctl
->systohc
) && !ctl
->update
)) {
1062 * Timing critical - do not change the order of, or put
1063 * anything between the follow three statements.
1064 * Synchronization failure MUST exit, because all drift
1065 * operations are invalid without it.
1067 if (synchronize_to_clock_tick(ctl
))
1068 return EXIT_FAILURE
;
1069 read_hardware_clock(ctl
, &hclock_valid
, &hclocktime
.tv_sec
);
1070 gettimeofday(&read_time
, NULL
);
1072 if (!hclock_valid
) {
1073 warnx(_("RTC read returned an invalid value."));
1074 return EXIT_FAILURE
;
1077 * Calculate and apply drift correction to the Hardware Clock
1078 * time for everything except --show
1080 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1081 adjtime
->last_adj_time
,
1082 adjtime
->not_adjusted
,
1083 hclocktime
.tv_sec
, &tdrift
);
1085 hclocktime
= time_inc(tdrift
, hclocktime
.tv_sec
);
1087 startup_hclocktime
=
1088 time_inc(hclocktime
, time_diff(startup_time
, read_time
));
1090 if (ctl
->show
|| ctl
->get
) {
1091 return display_time(startup_hclocktime
);
1095 set_hardware_clock_exact(ctl
, set_time
, startup_time
);
1096 if (!ctl
->noadjfile
)
1097 adjust_drift_factor(ctl
, adjtime
, t2tv(set_time
),
1098 startup_hclocktime
);
1099 } else if (ctl
->adjust
) {
1100 if (tdrift
.tv_sec
> 0 || tdrift
.tv_sec
< -1)
1101 do_adjustment(ctl
, adjtime
, hclocktime
, read_time
);
1103 printf(_("Needed adjustment is less than one second, "
1104 "so not setting clock.\n"));
1105 } else if (ctl
->systohc
) {
1106 struct timeval nowtime
, reftime
;
1108 * We can only set_hardware_clock_exact to a
1109 * whole seconds time, so we set it with
1110 * reference to the most recent whole
1113 gettimeofday(&nowtime
, NULL
);
1114 reftime
.tv_sec
= nowtime
.tv_sec
;
1115 reftime
.tv_usec
= 0;
1116 set_hardware_clock_exact(ctl
, (time_t) reftime
.tv_sec
, reftime
);
1117 if (!ctl
->noadjfile
)
1118 adjust_drift_factor(ctl
, adjtime
, nowtime
,
1120 } else if (ctl
->hctosys
) {
1121 return set_system_clock(ctl
, hclocktime
);
1123 if (!ctl
->noadjfile
&& adjtime
->dirty
)
1124 return save_adjtime(ctl
, adjtime
);
1125 return EXIT_SUCCESS
;
1129 * Get or set the kernel RTC driver's epoch on Alpha machines.
1130 * ISA machines are hard coded for 1900.
1132 #if defined(__linux__) && defined(__alpha__)
1134 manipulate_epoch(const struct hwclock_control
*ctl
)
1136 if (ctl
->getepoch
) {
1137 unsigned long epoch
;
1139 if (get_epoch_rtc(ctl
, &epoch
))
1140 warnx(_("unable to read the RTC epoch."));
1142 printf(_("The RTC epoch is set to %lu.\n"), epoch
);
1143 } else if (ctl
->setepoch
) {
1144 if (!ctl
->epoch_option
)
1145 warnx(_("--epoch is required for --setepoch."));
1146 else if (!ctl
->testing
)
1147 if (set_epoch_rtc(ctl
))
1148 warnx(_("unable to set the RTC epoch."));
1151 #endif /* __linux__ __alpha__ */
1153 static void out_version(void)
1155 printf(UTIL_LINUX_VERSION
);
1158 static void __attribute__((__noreturn__
))
1161 fputs(USAGE_HEADER
, stdout
);
1162 printf(_(" %s [function] [option...]\n"), program_invocation_short_name
);
1164 fputs(USAGE_SEPARATOR
, stdout
);
1165 puts(_("Time clocks utility."));
1167 fputs(USAGE_FUNCTIONS
, stdout
);
1168 puts(_(" -r, --show display the RTC time"));
1169 puts(_(" --get display drift corrected RTC time"));
1170 puts(_(" --set set the RTC according to --date"));
1171 puts(_(" -s, --hctosys set the system time from the RTC"));
1172 puts(_(" -w, --systohc set the RTC from the system time"));
1173 puts(_(" --systz send timescale configurations to the kernel"));
1174 puts(_(" -a, --adjust adjust the RTC to account for systematic drift"));
1175 #if defined(__linux__) && defined(__alpha__)
1176 puts(_(" --getepoch display the RTC epoch"));
1177 puts(_(" --setepoch set the RTC epoch according to --epoch"));
1179 puts(_(" --predict predict the drifted RTC time according to --date"));
1180 fputs(USAGE_OPTIONS
, stdout
);
1181 puts(_(" -u, --utc the RTC timescale is UTC"));
1182 puts(_(" -l, --localtime the RTC timescale is Local"));
1185 " -f, --rtc <file> use an alternate file to %1$s\n"), _PATH_RTC_DEV
);
1188 " --directisa use the ISA bus instead of %1$s access\n"), _PATH_RTC_DEV
);
1189 puts(_(" --date <time> date/time input for --set and --predict"));
1190 puts(_(" --delay <sec> delay used when set new RTC time"));
1191 #if defined(__linux__) && defined(__alpha__)
1192 puts(_(" --epoch <year> epoch input for --setepoch"));
1194 puts(_(" --update-drift update the RTC drift factor"));
1196 " --noadjfile do not use %1$s\n"), _PATH_ADJTIME
);
1198 " --adjfile <file> use an alternate file to %1$s\n"), _PATH_ADJTIME
);
1199 puts(_(" --test dry run; implies --verbose"));
1200 puts(_(" -v, --verbose display more details"));
1201 fputs(USAGE_SEPARATOR
, stdout
);
1202 printf(USAGE_HELP_OPTIONS(22));
1203 printf(USAGE_MAN_TAIL("hwclock(8)"));
1207 int main(int argc
, char **argv
)
1209 struct hwclock_control ctl
= {
1210 .show
= 1, /* default op is show */
1211 .rtc_delay
= -1.0 /* unspecified */
1213 struct timeval startup_time
;
1214 struct adjtime adjtime
= { 0 };
1216 * The time we started up, in seconds into the epoch, including
1219 time_t set_time
= 0; /* Time to which user said to set Hardware Clock */
1222 /* Long only options. */
1224 OPT_ADJFILE
= CHAR_MAX
+ 1,
1240 static const struct option longopts
[] = {
1241 { "adjust", no_argument
, NULL
, 'a' },
1242 { "help", no_argument
, NULL
, 'h' },
1243 { "localtime", no_argument
, NULL
, 'l' },
1244 { "show", no_argument
, NULL
, 'r' },
1245 { "hctosys", no_argument
, NULL
, 's' },
1246 { "utc", no_argument
, NULL
, 'u' },
1247 { "version", no_argument
, NULL
, 'V' },
1248 { "systohc", no_argument
, NULL
, 'w' },
1249 { "debug", no_argument
, NULL
, 'D' },
1250 { "ul-debug", required_argument
, NULL
, 'd' },
1251 { "verbose", no_argument
, NULL
, 'v' },
1252 { "set", no_argument
, NULL
, OPT_SET
},
1253 #if defined(__linux__) && defined(__alpha__)
1254 { "getepoch", no_argument
, NULL
, OPT_GETEPOCH
},
1255 { "setepoch", no_argument
, NULL
, OPT_SETEPOCH
},
1256 { "epoch", required_argument
, NULL
, OPT_EPOCH
},
1258 { "noadjfile", no_argument
, NULL
, OPT_NOADJFILE
},
1259 { "directisa", no_argument
, NULL
, OPT_DIRECTISA
},
1260 { "test", no_argument
, NULL
, OPT_TEST
},
1261 { "date", required_argument
, NULL
, OPT_DATE
},
1262 { "delay", required_argument
, NULL
, OPT_DELAY
},
1264 { "rtc", required_argument
, NULL
, 'f' },
1266 { "adjfile", required_argument
, NULL
, OPT_ADJFILE
},
1267 { "systz", no_argument
, NULL
, OPT_SYSTZ
},
1268 { "predict", no_argument
, NULL
, OPT_PREDICT
},
1269 { "get", no_argument
, NULL
, OPT_GET
},
1270 { "update-drift", no_argument
, NULL
, OPT_UPDATE
},
1271 { NULL
, 0, NULL
, 0 }
1274 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
1276 OPT_GET
, OPT_GETEPOCH
, OPT_PREDICT
,
1277 OPT_SET
, OPT_SETEPOCH
, OPT_SYSTZ
},
1279 { OPT_ADJFILE
, OPT_NOADJFILE
},
1280 { OPT_NOADJFILE
, OPT_UPDATE
},
1283 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1285 /* Remember what time we were invoked */
1286 gettimeofday(&startup_time
, NULL
);
1288 #ifdef HAVE_LIBAUDIT
1289 hwaudit_fd
= audit_open();
1290 if (hwaudit_fd
< 0 && !(errno
== EINVAL
|| errno
== EPROTONOSUPPORT
||
1291 errno
== EAFNOSUPPORT
)) {
1293 * You get these error codes only when the kernel doesn't
1294 * have audit compiled in.
1296 warnx(_("Unable to connect to audit system"));
1297 return EXIT_FAILURE
;
1300 setlocale(LC_ALL
, "");
1303 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1304 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1305 * - gqueri@mail.dotcom.fr
1307 setlocale(LC_NUMERIC
, "C");
1309 bindtextdomain(PACKAGE
, LOCALEDIR
);
1310 textdomain(PACKAGE
);
1311 close_stdout_atexit();
1313 while ((c
= getopt_long(argc
, argv
,
1314 "hvVDd:alrsuwf:", longopts
, NULL
)) != -1) {
1316 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1320 warnx(_("use --verbose, --debug has been deprecated."));
1326 hwclock_init_debug(optarg
);
1334 ctl
.local_opt
= 1; /* --localtime */
1357 #if defined(__linux__) && defined(__alpha__)
1368 ctl
.epoch_option
= optarg
; /* --epoch */
1378 ctl
.testing
= 1; /* --test */
1382 ctl
.date_opt
= optarg
; /* --date */
1385 ctl
.rtc_delay
= strtod_or_err(optarg
, "invalid --delay argument");
1388 ctl
.adj_file_name
= optarg
; /* --adjfile */
1391 ctl
.systz
= 1; /* --systz */
1396 ctl
.predict
= 1; /* --predict */
1400 ctl
.get
= 1; /* --get */
1404 ctl
.update
= 1; /* --update-drift */
1408 ctl
.rtc_dev_name
= optarg
; /* --rtc */
1412 case 'V': /* --version */
1413 print_version(EXIT_SUCCESS
);
1414 case 'h': /* --help */
1417 errtryhelp(EXIT_FAILURE
);
1421 if (argc
-= optind
) {
1422 warnx(_("%d too many arguments given"), argc
);
1423 errtryhelp(EXIT_FAILURE
);
1426 if (!ctl
.adj_file_name
)
1427 ctl
.adj_file_name
= _PATH_ADJTIME
;
1429 if (ctl
.update
&& !ctl
.set
&& !ctl
.systohc
) {
1430 warnx(_("--update-drift requires --set or --systohc"));
1434 if (ctl
.noadjfile
&& !ctl
.utc
&& !ctl
.local_opt
) {
1435 warnx(_("With --noadjfile, you must specify "
1436 "either --utc or --localtime"));
1440 if (ctl
.set
|| ctl
.predict
) {
1441 if (!ctl
.date_opt
) {
1442 warnx(_("--date is required for --set or --predict"));
1445 #ifdef USE_HWCLOCK_GPLv3_DATETIME
1446 /* date(1) compatible GPLv3 parser */
1447 struct timespec when
= { 0 };
1449 if (parse_date(&when
, ctl
.date_opt
, NULL
))
1450 set_time
= when
.tv_sec
;
1452 /* minimalistic GPLv2 based parser */
1455 if (parse_timestamp(ctl
.date_opt
, &usec
) == 0)
1456 set_time
= (time_t) (usec
/ 1000000);
1459 warnx(_("invalid date '%s'"), ctl
.date_opt
);
1464 #if defined(__linux__) && defined(__alpha__)
1465 if (ctl
.getepoch
|| ctl
.setepoch
) {
1466 manipulate_epoch(&ctl
);
1467 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1473 printf(_("System Time: %"PRId64
".%06"PRId64
"\n"),
1474 (int64_t)startup_time
.tv_sec
, (int64_t)startup_time
.tv_usec
);
1477 if (!ctl
.systz
&& !ctl
.predict
)
1478 determine_clock_access_method(&ctl
);
1480 if (!ctl
.noadjfile
&& !(ctl
.systz
&& (ctl
.utc
|| ctl
.local_opt
))) {
1481 if ((rc
= read_adjtime(&ctl
, &adjtime
)) != 0)
1482 hwclock_exit(&ctl
, rc
);
1484 /* Avoid writing adjtime file if we don't have to. */
1487 ctl
.universal
= hw_clock_is_utc(&ctl
, &adjtime
);
1488 rc
= manipulate_clock(&ctl
, set_time
, startup_time
, &adjtime
);
1490 puts(_("Test mode: nothing was changed."));
1491 hwclock_exit(&ctl
, rc
);
1492 return rc
; /* Not reached */
1496 hwclock_exit(const struct hwclock_control
*ctl
1497 #ifndef HAVE_LIBAUDIT
1498 __attribute__((__unused__
))
1502 #ifdef HAVE_LIBAUDIT
1503 if (ctl
->hwaudit_on
&& !ctl
->testing
) {
1504 audit_log_user_message(hwaudit_fd
, AUDIT_USYS_CONFIG
,
1505 "op=change-system-time", NULL
, NULL
, NULL
,
1506 status
== EXIT_SUCCESS
? 1 : 0);
1514 * History of this program:
1516 * 98.08.12 BJH Version 2.4
1518 * Don't use century byte from Hardware Clock. Add comments telling why.
1520 * 98.06.20 BJH Version 2.3.
1522 * Make --hctosys set the kernel timezone from TZ environment variable
1523 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1525 * 98.03.05 BJH. Version 2.2.
1527 * Add --getepoch and --setepoch.
1529 * Fix some word length things so it works on Alpha.
1531 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1532 * case, busywait for the top of a second instead of blocking and waiting
1533 * for the update complete interrupt.
1535 * Fix a bunch of bugs too numerous to mention.
1537 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1538 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1539 * job (jei@iclnl.icl.nl).
1541 * Use the rtc clock access method in preference to the KDGHWCLK method.
1542 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1544 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1545 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1546 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1547 * and wrote feature test code to detect absence of rtc headers.
1549 ***************************************************************************
1552 * To compile this, you must use GNU compiler optimization (-O option) in
1553 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1554 * compile. If you don't optimize, which means the compiler will generate no
1555 * inline functions, the references to these functions in this program will
1556 * be compiled as external references. Since you probably won't be linking
1557 * with any functions by these names, you will have unresolved external
1558 * references when you link.
1560 * Here's some info on how we must deal with the time that elapses while
1561 * this program runs: There are two major delays as we run:
1563 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1564 * we are synchronized to the Hardware Clock.
1565 * 2) Running the "date" program to interpret the value of our --date
1568 * Reading the /etc/adjtime file is the next biggest source of delay and
1571 * The user wants to know what time it was at the moment they invoked us, not
1572 * some arbitrary time later. And in setting the clock, they are giving us the
1573 * time at the moment we are invoked, so if we set the clock some time
1574 * later, we have to add some time to that.
1576 * So we check the system time as soon as we start up, then run "date" and
1577 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1578 * edge, then check the system time again to see how much time we spent. We
1579 * immediately read the clock then and (if appropriate) report that time,
1580 * and additionally, the delay we measured.
1582 * If we're setting the clock to a time given by the user, we wait some more
1583 * so that the total delay is an integral number of seconds, then set the
1584 * Hardware Clock to the time the user requested plus that integral number
1585 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1587 * If we're setting the clock to the system clock value, we wait for the
1588 * system clock to reach the top of a second, and then set the Hardware
1589 * Clock to the system clock's value.
1591 * Here's an interesting point about setting the Hardware Clock: On my
1592 * machine, when you set it, it sets to that precise time. But one can
1593 * imagine another clock whose update oscillator marches on a steady one
1594 * second period, so updating the clock between any two oscillator ticks is
1595 * the same as updating it right at the earlier tick. To avoid any
1596 * complications that might cause, we set the clock as soon as possible
1597 * after an oscillator tick.
1599 * About synchronizing to the Hardware Clock when reading the time: The
1600 * precision of the Hardware Clock counters themselves is one second. You
1601 * can't read the counters and find out that is 12:01:02.5. But if you
1602 * consider the location in time of the counter's ticks as part of its
1603 * value, then its precision is as infinite as time is continuous! What I'm
1604 * saying is this: To find out the _exact_ time in the hardware clock, we
1605 * wait until the next clock tick (the next time the second counter changes)
1606 * and measure how long we had to wait. We then read the value of the clock
1607 * counters and subtract the wait time and we know precisely what time it
1608 * was when we set out to query the time.
1610 * hwclock uses this method, and considers the Hardware Clock to have
1611 * infinite precision.