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 #ifdef HAVE_SYS_SYSCALL_H
75 #include <sys/syscall.h>
82 #include "closestream.h"
85 #include "pathnames.h"
87 #include "timeutils.h"
95 static int hwaudit_fd
= -1;
98 UL_DEBUG_DEFINE_MASK(hwclock
);
99 UL_DEBUG_DEFINE_MASKNAMES(hwclock
) = UL_DEBUG_EMPTY_MASKNAMES
;
101 /* The struct that holds our hardware access routines */
102 static const struct clock_ops
*ur
;
104 /* Maximal clock adjustment in seconds per day.
105 (adjtime() glibc call has 2145 seconds limit on i386, so it is good enough for us as well,
106 43219 is a maximal safe value preventing exact_adjustment overflow.) */
107 #define MAX_DRIFT 2145.0
111 * This is information we keep in the adjtime file that tells us how
112 * to do drift corrections. Elements are all straight from the
113 * adjtime file, so see documentation of that file for details.
114 * Exception is <dirty>, which is an indication that what's in this
115 * structure is not what's in the disk file (because it has been
116 * updated since read from the disk file).
121 time_t last_adj_time
;
124 time_t last_calib_time
;
126 * The most recent time that we set the clock from an external
127 * authority (as opposed to just doing a drift adjustment)
130 enum a_local_utc
{ UTC
= 0, LOCAL
, UNKNOWN
} local_utc
;
132 * To which time zone, local or UTC, we most recently set the
137 static void hwclock_init_debug(const char *str
)
139 __UL_INIT_DEBUG_FROM_STRING(hwclock
, HWCLOCK_DEBUG_
, 0, str
);
141 DBG(INIT
, ul_debug("hwclock debug mask: 0x%04x", hwclock_debug_mask
));
142 DBG(INIT
, ul_debug("hwclock version: %s", PACKAGE_STRING
));
145 /* FOR TESTING ONLY: inject random delays of up to 1000ms */
146 static void up_to_1000ms_sleep(void)
148 int usec
= random() % 1000000;
150 DBG(RANDOM_SLEEP
, ul_debug("sleeping ~%d usec", usec
));
155 * time_t to timeval conversion.
157 static struct timeval
t2tv(time_t timet
)
159 struct timeval rettimeval
;
161 rettimeval
.tv_sec
= timet
;
162 rettimeval
.tv_usec
= 0;
167 * The difference in seconds between two times in "timeval" format.
169 double time_diff(struct timeval subtrahend
, struct timeval subtractor
)
171 return (subtrahend
.tv_sec
- subtractor
.tv_sec
)
172 + (subtrahend
.tv_usec
- subtractor
.tv_usec
) / 1E6
;
176 * The time, in "timeval" format, which is <increment> seconds after the
177 * time <addend>. Of course, <increment> may be negative.
179 static struct timeval
time_inc(struct timeval addend
, double increment
)
181 struct timeval newtime
;
183 newtime
.tv_sec
= addend
.tv_sec
+ (time_t)increment
;
184 newtime
.tv_usec
= addend
.tv_usec
+ (increment
- (time_t)increment
) * 1E6
;
187 * Now adjust it so that the microsecond value is between 0 and 1
190 if (newtime
.tv_usec
< 0) {
191 newtime
.tv_usec
+= 1E6
;
193 } else if (newtime
.tv_usec
>= 1E6
) {
194 newtime
.tv_usec
-= 1E6
;
201 hw_clock_is_utc(const struct hwclock_control
*ctl
,
202 const struct adjtime
*adjtime
)
207 ret
= 1; /* --utc explicitly given on command line */
208 else if (ctl
->local_opt
)
209 ret
= 0; /* --localtime explicitly given */
211 /* get info from adjtime file - default is UTC */
212 ret
= (adjtime
->local_utc
!= LOCAL
);
215 printf(_("Assuming hardware clock is kept in %s time.\n"),
216 ret
? _("UTC") : _("local"));
221 * Read the adjustment parameters out of the /etc/adjtime file.
223 * Return them as the adjtime structure <*adjtime_p>. Its defaults are
224 * initialized in main().
226 static int read_adjtime(const struct hwclock_control
*ctl
,
227 struct adjtime
*adjtime_p
)
230 char line1
[81]; /* String: first line of adjtime file */
231 char line2
[81]; /* String: second line of adjtime file */
232 char line3
[81]; /* String: third line of adjtime file */
233 int64_t last_adj_time
;
234 int64_t last_calib_time
;
236 if (access(ctl
->adj_file_name
, R_OK
) != 0)
239 adjfile
= fopen(ctl
->adj_file_name
, "r"); /* open file for reading */
240 if (adjfile
== NULL
) {
241 warn(_("cannot open %s"), ctl
->adj_file_name
);
245 if (!fgets(line1
, sizeof(line1
), adjfile
))
246 line1
[0] = '\0'; /* In case fgets fails */
247 if (!fgets(line2
, sizeof(line2
), adjfile
))
248 line2
[0] = '\0'; /* In case fgets fails */
249 if (!fgets(line3
, sizeof(line3
), adjfile
))
250 line3
[0] = '\0'; /* In case fgets fails */
254 if (sscanf(line1
, "%lf %"SCNd64
" %lf",
255 &adjtime_p
->drift_factor
,
257 &adjtime_p
->not_adjusted
) != 3)
258 warnx(_("Warning: unrecognized line in adjtime file: %s"), line1
);
260 if (sscanf(line2
, "%"SCNd64
, &last_calib_time
) != 1)
261 warnx(_("Warning: unrecognized line in adjtime file: %s"), line2
);
263 adjtime_p
->last_adj_time
= (time_t)last_adj_time
;
264 adjtime_p
->last_calib_time
= (time_t)last_calib_time
;
266 if (!strcmp(line3
, "UTC\n")) {
267 adjtime_p
->local_utc
= UTC
;
268 } else if (!strcmp(line3
, "LOCAL\n")) {
269 adjtime_p
->local_utc
= LOCAL
;
271 adjtime_p
->local_utc
= UNKNOWN
;
273 warnx(_("Warning: unrecognized third line in adjtime file\n"
274 "(Expected: `UTC' or `LOCAL' or nothing.)"));
279 printf(_("Last drift adjustment done at %"PRId64
" seconds after 1969\n"),
280 (int64_t)adjtime_p
->last_adj_time
);
281 printf(_("Last calibration done at %"PRId64
" seconds after 1969\n"),
282 (int64_t)adjtime_p
->last_calib_time
);
283 printf(_("Hardware clock is on %s time\n"),
284 (adjtime_p
->local_utc
==
285 LOCAL
) ? _("local") : (adjtime_p
->local_utc
==
286 UTC
) ? _("UTC") : _("unknown"));
293 * Wait until the falling edge of the Hardware Clock's update flag so that
294 * any time that is read from the clock immediately after we return will be
297 * The clock only has 1 second precision, so it gives the exact time only
298 * once per second, right on the falling edge of the update flag.
300 * We wait (up to one second) either blocked waiting for an rtc device or in
301 * a CPU spin loop. The former is probably not very accurate.
303 * Return 0 if it worked, nonzero if it didn't.
305 static int synchronize_to_clock_tick(const struct hwclock_control
*ctl
)
310 printf(_("Waiting for clock tick...\n"));
312 rc
= ur
->synchronize_to_clock_tick(ctl
);
316 printf(_("...synchronization failed\n"));
318 printf(_("...got clock tick\n"));
325 * Convert a time in broken down format (hours, minutes, etc.) into standard
326 * unix time (seconds into epoch). Return it as *systime_p.
328 * The broken down time is argument <tm>. This broken down time is either
329 * in local time zone or UTC, depending on value of logical argument
330 * "universal". True means it is in UTC.
332 * If the argument contains values that do not constitute a valid time, and
333 * mktime() recognizes this, return *valid_p == false and *systime_p
334 * undefined. However, mktime() sometimes goes ahead and computes a
335 * fictional time "as if" the input values were valid, e.g. if they indicate
336 * the 31st day of April, mktime() may compute the time of May 1. In such a
337 * case, we return the same fictional value mktime() does as *systime_p and
338 * return *valid_p == true.
341 mktime_tz(const struct hwclock_control
*ctl
, struct tm tm
,
347 *systime_p
= timegm(&tm
);
349 *systime_p
= mktime(&tm
);
350 if (*systime_p
== -1) {
352 * This apparently (not specified in mktime() documentation)
353 * means the 'tm' structure does not contain valid values
354 * (however, not containing valid values does _not_ imply
355 * mktime() returns -1).
359 printf(_("Invalid values in hardware clock: "
360 "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"),
361 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
,
362 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
366 printf(_("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
367 "%"PRId64
" seconds since 1969\n"), tm
.tm_year
+ 1900,
368 tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
, tm
.tm_min
,
369 tm
.tm_sec
, (int64_t)*systime_p
);
375 * Read the hardware clock and return the current time via <tm> argument.
377 * Use the method indicated by <method> argument to access the hardware
381 read_hardware_clock(const struct hwclock_control
*ctl
,
382 int *valid_p
, time_t *systime_p
)
384 struct tm tm
= { 0 };
387 err
= ur
->read_hardware_clock(ctl
, &tm
);
392 printf(_("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
393 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
,
394 tm
.tm_min
, tm
.tm_sec
);
395 *valid_p
= mktime_tz(ctl
, tm
, systime_p
);
401 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
402 * according to <universal>.
405 set_hardware_clock(const struct hwclock_control
*ctl
, const time_t newtime
)
407 struct tm new_broken_time
= { 0 };
409 * Time to which we will set Hardware Clock, in broken down format,
410 * in the time zone of caller's choice
414 gmtime_r(&newtime
, &new_broken_time
);
416 localtime_r(&newtime
, &new_broken_time
);
419 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
420 "= %"PRId64
" seconds since 1969\n"),
421 new_broken_time
.tm_hour
, new_broken_time
.tm_min
,
422 new_broken_time
.tm_sec
, (int64_t)newtime
);
425 ur
->set_hardware_clock(ctl
, &new_broken_time
);
429 get_hardware_delay(const struct hwclock_control
*ctl
)
431 const char *devpath
, *rtcname
;
436 devpath
= ur
->get_device_path();
440 rtcname
= strrchr(devpath
, '/');
441 if (!rtcname
|| !*(rtcname
+ 1))
445 pc
= ul_new_path("/sys/class/rtc/%s", rtcname
);
448 rc
= ul_path_scanf(pc
, "name", "%128[^\n ]", name
);
451 if (rc
!= 1 || !*name
)
455 printf(_("RTC type: '%s'\n"), name
);
457 /* MC146818A-compatible (x86) */
458 if (strcmp(name
, "rtc_cmos") == 0)
464 /* Let's be backwardly compatible */
470 * Set the Hardware Clock to the time "sethwtime", in local time zone or
471 * UTC, according to "universal".
473 * Wait for a fraction of a second so that "sethwtime" is the value of the
474 * Hardware Clock as of system time "refsystime", which is in the past. For
475 * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and
476 * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2
477 * seconds since "refsystime") and then set the Hardware Clock to 14:03:07,
478 * thus getting a precise and retroactive setting of the clock. The .5 delay is
479 * default on x86, see --delay and get_hardware_delay().
481 * (Don't be confused by the fact that the system clock and the Hardware
482 * Clock differ by two hours in the above example. That's just to remind you
483 * that there are two independent time scales here).
485 * This function ought to be able to accept set times as fractional times.
486 * Idea for future enhancement.
489 set_hardware_clock_exact(const struct hwclock_control
*ctl
,
490 const time_t sethwtime
,
491 const struct timeval refsystime
)
494 * The Hardware Clock can only be set to any integer time plus one
495 * half second. The integer time is required because there is no
496 * interface to set or get a fractional second. The additional half
497 * second is because the Hardware Clock updates to the following
498 * second precisely 500 ms (not 1 second!) after you release the
499 * divider reset (after setting the new time) - see description of
500 * DV2, DV1, DV0 in Register A in the MC146818A data sheet (and note
501 * that although that document doesn't say so, real-world code seems
502 * to expect that the SET bit in Register B functions the same way).
503 * That means that, e.g., when you set the clock to 1:02:03, it
504 * effectively really sets it to 1:02:03.5, because it will update to
505 * 1:02:04 only half a second later. Our caller passes the desired
506 * integer Hardware Clock time in sethwtime, and the corresponding
507 * system time (which may have a fractional part, and which may or may
508 * not be the same!) in refsystime. In an ideal situation, we would
509 * then apply sethwtime to the Hardware Clock at refsystime+500ms, so
510 * that when the Hardware Clock ticks forward to sethwtime+1s half a
511 * second later at refsystime+1000ms, everything is in sync. So we
512 * spin, waiting for gettimeofday() to return a time at or after that
513 * time (refsystime+500ms) up to a tolerance value, initially 1ms. If
514 * we miss that time due to being preempted for some other process,
515 * then we increase the margin a little bit (initially 1ms, doubling
516 * each time), add 1 second (or more, if needed to get a time that is
517 * in the future) to both the time for which we are waiting and the
518 * time that we will apply to the Hardware Clock, and start waiting
521 * For example, the caller requests that we set the Hardware Clock to
522 * 1:02:03, with reference time (current system time) = 6:07:08.250.
523 * We want the Hardware Clock to update to 1:02:04 at 6:07:09.250 on
524 * the system clock, and the first such update will occur 0.500
525 * seconds after we write to the Hardware Clock, so we spin until the
526 * system clock reads 6:07:08.750. If we get there, great, but let's
527 * imagine the system is so heavily loaded that our process is
528 * preempted and by the time we get to run again, the system clock
529 * reads 6:07:11.990. We now want to wait until the next xx:xx:xx.750
530 * time, which is 6:07:12.750 (4.5 seconds after the reference time),
531 * at which point we will set the Hardware Clock to 1:02:07 (4 seconds
532 * after the originally requested time). If we do that successfully,
533 * then at 6:07:13.250 (5 seconds after the reference time), the
534 * Hardware Clock will update to 1:02:08 (5 seconds after the
535 * originally requested time), and all is well thereafter.
538 time_t newhwtime
= sethwtime
;
539 double target_time_tolerance_secs
= 0.001; /* initial value */
540 double tolerance_incr_secs
= 0.001; /* initial value */
542 struct timeval rtc_set_delay_tv
;
544 struct timeval targetsystime
;
545 struct timeval nowsystime
;
546 struct timeval prevsystime
= refsystime
;
547 double deltavstarget
;
549 if (ctl
->rtc_delay
!= -1.0) /* --delay specified */
550 delay
= ctl
->rtc_delay
;
552 delay
= get_hardware_delay(ctl
);
555 printf(_("Using delay: %.6f seconds\n"), delay
);
557 rtc_set_delay_tv
.tv_sec
= 0;
558 rtc_set_delay_tv
.tv_usec
= delay
* 1E6
;
560 timeradd(&refsystime
, &rtc_set_delay_tv
, &targetsystime
);
565 ON_DBG(RANDOM_SLEEP
, up_to_1000ms_sleep());
567 gettimeofday(&nowsystime
, NULL
);
568 deltavstarget
= time_diff(nowsystime
, targetsystime
);
569 ticksize
= time_diff(nowsystime
, prevsystime
);
570 prevsystime
= nowsystime
;
574 printf(_("time jumped backward %.6f seconds "
575 "to %"PRId64
".%06"PRId64
" - retargeting\n"),
576 ticksize
, (int64_t)nowsystime
.tv_sec
,
577 (int64_t)nowsystime
.tv_usec
);
578 /* The retarget is handled at the end of the loop. */
579 } else if (deltavstarget
< 0) {
580 /* deltavstarget < 0 if current time < target time */
582 ul_debug("%"PRId64
".%06"PRId64
" < %"PRId64
".%06"PRId64
" (%.6f)",
583 (int64_t)nowsystime
.tv_sec
, (int64_t)nowsystime
.tv_usec
,
584 (int64_t)targetsystime
.tv_sec
,
585 (int64_t)targetsystime
.tv_usec
, deltavstarget
));
586 continue; /* not there yet - keep spinning */
587 } else if (deltavstarget
<= target_time_tolerance_secs
) {
588 /* Close enough to the target time; done waiting. */
590 } else /* (deltavstarget > target_time_tolerance_secs) */ {
592 * We missed our window. Increase the tolerance and
593 * aim for the next opportunity.
596 printf(_("missed it - %"PRId64
".%06"PRId64
" is too far "
597 "past %"PRId64
".%06"PRId64
" (%.6f > %.6f)\n"),
598 (int64_t)nowsystime
.tv_sec
,
599 (int64_t)nowsystime
.tv_usec
,
600 (int64_t)targetsystime
.tv_sec
,
601 (int64_t)targetsystime
.tv_usec
,
603 target_time_tolerance_secs
);
604 target_time_tolerance_secs
+= tolerance_incr_secs
;
605 tolerance_incr_secs
*= 2;
609 * Aim for the same offset (tv_usec) within the second in
610 * either the current second (if that offset hasn't arrived
611 * yet), or the next second.
613 if (nowsystime
.tv_usec
< targetsystime
.tv_usec
)
614 targetsystime
.tv_sec
= nowsystime
.tv_sec
;
616 targetsystime
.tv_sec
= nowsystime
.tv_sec
+ 1;
619 newhwtime
= sethwtime
620 + ceil(time_diff(nowsystime
, refsystime
)
621 - delay
/* don't count this */);
623 printf(_("%"PRId64
".%06"PRId64
" is close enough to %"PRId64
".%06"PRId64
" (%.6f < %.6f)\n"
624 "Set RTC to %"PRId64
" (%"PRId64
" + %d; refsystime = %"PRId64
".%06"PRId64
")\n"),
625 (int64_t)nowsystime
.tv_sec
, (int64_t)nowsystime
.tv_usec
,
626 (int64_t)targetsystime
.tv_sec
, (int64_t)targetsystime
.tv_usec
,
627 deltavstarget
, target_time_tolerance_secs
,
628 (int64_t)newhwtime
, (int64_t)sethwtime
,
629 (int)((int64_t)newhwtime
- (int64_t)sethwtime
),
630 (int64_t)refsystime
.tv_sec
, (int64_t)refsystime
.tv_usec
);
632 set_hardware_clock(ctl
, newhwtime
);
636 display_time(struct timeval hwctime
)
638 char buf
[ISO_BUFSIZ
];
640 if (strtimeval_iso(&hwctime
, ISO_TIMESTAMP_DOT
, buf
, sizeof(buf
)))
648 * Adjusts System time, sets the kernel's timezone and RTC timescale.
650 * The kernel warp_clock function adjusts the System time according to the
651 * tz.tz_minuteswest argument and sets PCIL (see below). At boot settimeofday(2)
652 * has one-shot access to this function as shown in the table below.
654 * +-------------------------------------------------------------------------+
655 * | settimeofday(tv, tz) |
656 * |-------------------------------------------------------------------------|
657 * | Arguments | System Time | TZ | PCIL | | warp_clock |
658 * | tv | tz | set | warped | set | set | firsttime | locked |
659 * |---------|---------|---------------|-----|------|-----------|------------|
660 * | pointer | NULL | yes | no | no | no | 1 | no |
661 * | NULL | ptr2utc | no | no | yes | no | 0 | yes |
662 * | NULL | pointer | no | yes | yes | yes | 0 | yes |
663 * +-------------------------------------------------------------------------+
664 * ptr2utc: tz.tz_minuteswest is zero (UTC).
665 * PCIL: persistent_clock_is_local, sets the "11 minute mode" timescale.
666 * firsttime: locks the warp_clock function (initialized to 1 at boot).
668 * +---------------------------------------------------------------------------+
669 * | op | RTC scale | settimeofday calls |
670 * |---------|-----------|-----------------------------------------------------|
671 * | systz | Local | 1) warps system time*, sets PCIL* and kernel tz |
672 * | systz | UTC | 1st) locks warp_clock* 2nd) sets kernel tz |
673 * | hctosys | Local | 1st) sets PCIL* & kernel tz 2nd) sets system time |
674 * | hctosys | UTC | 1st) locks warp* 2nd) sets tz 3rd) sets system time |
675 * +---------------------------------------------------------------------------+
676 * * only on first call after boot
678 * POSIX 2008 marked TZ in settimeofday() as deprecated. Unfortunately,
679 * different C libraries react to this deprecation in a different way. Since
680 * glibc v2.31 settimeofday() will fail if both args are not NULL, Musl-C
681 * ignores TZ at all, etc. We use __set_time() and __set_timezone() to hide
682 * these portability issues and to keep code readable.
684 #define __set_time(_tv) settimeofday(_tv, NULL)
686 #ifndef SYS_settimeofday
687 # ifdef __NR_settimeofday
688 # define SYS_settimeofday __NR_settimeofday
689 # elif defined(__NR_settimeofday_time32)
690 # define SYS_settimeofday __NR_settimeofday_time32
694 static inline int __set_timezone(const struct timezone
*tz
)
696 #ifdef SYS_settimeofday
698 return syscall(SYS_settimeofday
, NULL
, tz
);
700 return settimeofday(NULL
, tz
);
705 set_system_clock(const struct hwclock_control
*ctl
,
706 const struct timeval newtime
)
708 struct tm broken
= { 0 };
712 localtime_r(&newtime
.tv_sec
, &broken
);
713 minuteswest
= -get_gmtoff(&broken
) / 60;
716 if (ctl
->universal
) {
717 puts(_("Calling settimeofday(NULL, 0) "
718 "to lock the warp_clock function."));
719 if (!( ctl
->universal
&& !minuteswest
))
720 printf(_("Calling settimeofday(NULL, %d) "
721 "to set the kernel timezone.\n"),
724 printf(_("Calling settimeofday(NULL, %d) to warp "
725 "System time, set PCIL and the kernel tz.\n"),
729 printf(_("Calling settimeofday(%"PRId64
".%06"PRId64
", NULL) "
730 "to set the System time.\n"),
731 (int64_t)newtime
.tv_sec
, (int64_t)newtime
.tv_usec
);
735 const struct timezone tz_utc
= { 0 };
736 const struct timezone tz
= { minuteswest
};
738 /* If UTC RTC: lock warp_clock and PCIL */
740 rc
= __set_timezone(&tz_utc
);
742 /* Set kernel tz; if localtime RTC: warp_clock and set PCIL */
743 if (!rc
&& !( ctl
->universal
&& !minuteswest
))
744 rc
= __set_timezone(&tz
);
746 /* Set the System Clock */
747 if ((!rc
|| errno
== ENOSYS
) && ctl
->hctosys
)
748 rc
= __set_time(&newtime
);
751 warn(_("settimeofday() failed"));
759 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
760 * to facilitate future drift calculations based on this set point.
762 * With the --update-drift option:
763 * Update the drift factor in <*adjtime_p> based on the fact that the
764 * Hardware Clock was just calibrated to <nowtime> and before that was
765 * set to the <hclocktime> time scale.
768 adjust_drift_factor(const struct hwclock_control
*ctl
,
769 struct adjtime
*adjtime_p
,
770 const struct timeval nowtime
,
771 const struct timeval hclocktime
)
775 printf(_("Not adjusting drift factor because the "
776 "--update-drift option was not used.\n"));
777 } else if (adjtime_p
->last_calib_time
== 0) {
779 printf(_("Not adjusting drift factor because last "
780 "calibration time is zero,\n"
781 "so history is bad and calibration startover "
783 } else if ((hclocktime
.tv_sec
- adjtime_p
->last_calib_time
) < 4 * 60 * 60) {
785 printf(_("Not adjusting drift factor because it has "
786 "been less than four hours since the last "
790 * At adjustment time we drift correct the hardware clock
791 * according to the contents of the adjtime file and refresh
792 * its last adjusted timestamp.
794 * At calibration time we set the Hardware Clock and refresh
795 * both timestamps in <*adjtime_p>.
797 * Here, with the --update-drift option, we also update the
798 * drift factor in <*adjtime_p>.
800 * Let us do computation in doubles. (Floats almost suffice,
801 * but 195 days + 1 second equals 195 days in floats.)
803 const double sec_per_day
= 24.0 * 60.0 * 60.0;
804 double factor_adjust
;
806 struct timeval last_calib
;
808 last_calib
= t2tv(adjtime_p
->last_calib_time
);
810 * Correction to apply to the current drift factor.
812 * Simplified: uncorrected_drift / days_since_calibration.
814 * hclocktime is fully corrected with the current drift factor.
815 * Its difference from nowtime is the missed drift correction.
817 factor_adjust
= time_diff(nowtime
, hclocktime
) /
818 (time_diff(nowtime
, last_calib
) / sec_per_day
);
820 drift_factor
= adjtime_p
->drift_factor
+ factor_adjust
;
821 if (fabs(drift_factor
) > MAX_DRIFT
) {
823 printf(_("Clock drift factor was calculated as "
825 "It is far too much. Resetting to zero.\n"),
830 printf(_("Clock drifted %f seconds in the past "
831 "%f seconds\nin spite of a drift factor of "
833 "Adjusting drift factor by %f seconds/day\n"),
834 time_diff(nowtime
, hclocktime
),
835 time_diff(nowtime
, last_calib
),
836 adjtime_p
->drift_factor
, factor_adjust
);
839 adjtime_p
->drift_factor
= drift_factor
;
841 adjtime_p
->last_calib_time
= nowtime
.tv_sec
;
843 adjtime_p
->last_adj_time
= nowtime
.tv_sec
;
845 adjtime_p
->not_adjusted
= 0;
847 adjtime_p
->dirty
= 1;
851 * Calculate the drift correction currently needed for the
852 * Hardware Clock based on the last time it was adjusted,
853 * and the current drift factor, as stored in the adjtime file.
855 * The total drift adjustment needed is stored at tdrift_p.
859 calculate_adjustment(const struct hwclock_control
*ctl
,
861 const time_t last_time
,
862 const double not_adjusted
,
863 const time_t systime
, struct timeval
*tdrift_p
)
865 double exact_adjustment
;
868 ((double)(systime
- last_time
)) * factor
/ (24 * 60 * 60)
870 tdrift_p
->tv_sec
= (time_t) floor(exact_adjustment
);
871 tdrift_p
->tv_usec
= (exact_adjustment
-
872 (double)tdrift_p
->tv_sec
) * 1E6
;
874 printf(P_("Time since last adjustment is %"PRId64
" second\n",
875 "Time since last adjustment is %"PRId64
" seconds\n",
876 ((int64_t)systime
- (int64_t)last_time
)),
877 ((int64_t)systime
- (int64_t)last_time
));
878 printf(_("Calculated Hardware Clock drift is %"PRId64
".%06"PRId64
" seconds\n"),
879 (int64_t)tdrift_p
->tv_sec
, (int64_t)tdrift_p
->tv_usec
);
884 * Write the contents of the <adjtime> structure to its disk file.
886 * But if the contents are clean (unchanged since read from disk), don't
889 static int save_adjtime(const struct hwclock_control
*ctl
,
890 const struct adjtime
*adjtime
)
892 char *content
; /* Stuff to write to disk file */
895 xasprintf(&content
, "%f %"PRId64
" %f\n%"PRId64
"\n%s\n",
896 adjtime
->drift_factor
,
897 (int64_t)adjtime
->last_adj_time
,
898 adjtime
->not_adjusted
,
899 (int64_t)adjtime
->last_calib_time
,
900 (adjtime
->local_utc
== LOCAL
) ? "LOCAL" : "UTC");
903 printf(_("New %s data:\n%s"),
904 ctl
->adj_file_name
, content
);
910 fp
= fopen(ctl
->adj_file_name
, "w");
912 warn(_("cannot open %s"), ctl
->adj_file_name
);
916 rc
= fputs(content
, fp
) < 0;
917 rc
+= close_stream(fp
);
920 warn(_("cannot update %s"), ctl
->adj_file_name
);
928 * Do the adjustment requested, by 1) setting the Hardware Clock (if
929 * necessary), and 2) updating the last-adjusted time in the adjtime
932 * Do not update anything if the Hardware Clock does not currently present a
935 * <hclocktime> is the drift corrected time read from the Hardware Clock.
937 * <read_time> was the system time when the <hclocktime> was read, which due
938 * to computational delay could be a short time ago. It is used to define a
939 * trigger point for setting the Hardware Clock. The fractional part of the
940 * Hardware clock set time is subtracted from read_time to 'refer back', or
941 * delay, the trigger point. Fractional parts must be accounted for in this
942 * way, because the Hardware Clock can only be set to a whole second.
944 * <universal>: the Hardware Clock is kept in UTC.
946 * <testing>: We are running in test mode (no updating of clock).
950 do_adjustment(const struct hwclock_control
*ctl
, struct adjtime
*adjtime_p
,
951 const struct timeval hclocktime
,
952 const struct timeval read_time
)
954 if (adjtime_p
->last_adj_time
== 0) {
956 printf(_("Not setting clock because last adjustment time is zero, "
957 "so history is bad.\n"));
958 } else if (fabs(adjtime_p
->drift_factor
) > MAX_DRIFT
) {
960 printf(_("Not setting clock because drift factor %f is far too high.\n"),
961 adjtime_p
->drift_factor
);
963 set_hardware_clock_exact(ctl
, hclocktime
.tv_sec
,
965 -(hclocktime
.tv_usec
/ 1E6
)));
966 adjtime_p
->last_adj_time
= hclocktime
.tv_sec
;
967 adjtime_p
->not_adjusted
= 0;
968 adjtime_p
->dirty
= 1;
972 static void determine_clock_access_method(const struct hwclock_control
*ctl
)
976 #ifdef USE_HWCLOCK_CMOS
978 ur
= probe_for_cmos_clock();
982 ur
= probe_for_rtc_clock(ctl
);
986 puts(ur
->interface_name
);
990 printf(_("No usable clock interface found.\n"));
992 warnx(_("Cannot access the Hardware Clock via "
993 "any known method."));
996 warnx(_("Use the --verbose option to see the "
997 "details of our search for an access "
999 hwclock_exit(ctl
, EXIT_FAILURE
);
1003 /* Do all the normal work of hwclock - read, set clock, etc. */
1005 manipulate_clock(const struct hwclock_control
*ctl
, const time_t set_time
,
1006 const struct timeval startup_time
, struct adjtime
*adjtime
)
1008 /* The time at which we read the Hardware Clock */
1009 struct timeval read_time
= { 0 };
1011 * The Hardware Clock gives us a valid time, or at
1012 * least something close enough to fool mktime().
1014 int hclock_valid
= 0;
1016 * Tick synchronized time read from the Hardware Clock and
1017 * then drift corrected for all operations except --show.
1019 struct timeval hclocktime
= { 0 };
1021 * hclocktime correlated to startup_time. That is, what drift
1022 * corrected Hardware Clock time would have been at start up.
1024 struct timeval startup_hclocktime
= { 0 };
1025 /* Total Hardware Clock drift correction needed. */
1026 struct timeval tdrift
= { 0 };
1028 if ((ctl
->set
|| ctl
->systohc
|| ctl
->adjust
) &&
1029 (adjtime
->local_utc
== UTC
) != ctl
->universal
) {
1030 adjtime
->local_utc
= ctl
->universal
? UTC
: LOCAL
;
1034 * Negate the drift correction, because we want to 'predict' a
1035 * Hardware Clock time that includes drift.
1038 hclocktime
= t2tv(set_time
);
1039 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1040 adjtime
->last_adj_time
,
1041 adjtime
->not_adjusted
,
1042 hclocktime
.tv_sec
, &tdrift
);
1043 hclocktime
= time_inc(hclocktime
, (double)
1044 -(tdrift
.tv_sec
+ tdrift
.tv_usec
/ 1E6
));
1046 printf(_("Target date: %"PRId64
"\n"), (int64_t)set_time
);
1047 printf(_("Predicted RTC: %"PRId64
"\n"), (int64_t)hclocktime
.tv_sec
);
1049 return display_time(hclocktime
);
1053 return set_system_clock(ctl
, startup_time
);
1055 if (ur
->get_permissions())
1056 return EXIT_FAILURE
;
1059 * Read and drift correct RTC time; except for RTC set functions
1060 * without the --update-drift option because: 1) it's not needed;
1061 * 2) it enables setting a corrupted RTC without reading it first;
1062 * 3) it significantly reduces system shutdown time.
1064 if ( ! ((ctl
->set
|| ctl
->systohc
) && !ctl
->update
)) {
1066 * Timing critical - do not change the order of, or put
1067 * anything between the follow three statements.
1068 * Synchronization failure MUST exit, because all drift
1069 * operations are invalid without it.
1071 if (synchronize_to_clock_tick(ctl
))
1072 return EXIT_FAILURE
;
1073 read_hardware_clock(ctl
, &hclock_valid
, &hclocktime
.tv_sec
);
1074 gettimeofday(&read_time
, NULL
);
1076 if (!hclock_valid
) {
1077 warnx(_("RTC read returned an invalid value."));
1078 return EXIT_FAILURE
;
1081 * Calculate and apply drift correction to the Hardware Clock
1082 * time for everything except --show
1084 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1085 adjtime
->last_adj_time
,
1086 adjtime
->not_adjusted
,
1087 hclocktime
.tv_sec
, &tdrift
);
1089 hclocktime
= time_inc(tdrift
, hclocktime
.tv_sec
);
1091 startup_hclocktime
=
1092 time_inc(hclocktime
, time_diff(startup_time
, read_time
));
1094 if (ctl
->show
|| ctl
->get
) {
1095 return display_time(startup_hclocktime
);
1099 set_hardware_clock_exact(ctl
, set_time
, startup_time
);
1100 if (!ctl
->noadjfile
)
1101 adjust_drift_factor(ctl
, adjtime
, t2tv(set_time
),
1102 startup_hclocktime
);
1103 } else if (ctl
->adjust
) {
1104 if (tdrift
.tv_sec
> 0 || tdrift
.tv_sec
< -1)
1105 do_adjustment(ctl
, adjtime
, hclocktime
, read_time
);
1107 printf(_("Needed adjustment is less than one second, "
1108 "so not setting clock.\n"));
1109 } else if (ctl
->systohc
) {
1110 struct timeval nowtime
, reftime
;
1112 * We can only set_hardware_clock_exact to a
1113 * whole seconds time, so we set it with
1114 * reference to the most recent whole
1117 gettimeofday(&nowtime
, NULL
);
1118 reftime
.tv_sec
= nowtime
.tv_sec
;
1119 reftime
.tv_usec
= 0;
1120 set_hardware_clock_exact(ctl
, (time_t) reftime
.tv_sec
, reftime
);
1121 if (!ctl
->noadjfile
)
1122 adjust_drift_factor(ctl
, adjtime
, nowtime
,
1124 } else if (ctl
->hctosys
) {
1125 return set_system_clock(ctl
, hclocktime
);
1127 if (!ctl
->noadjfile
&& adjtime
->dirty
)
1128 return save_adjtime(ctl
, adjtime
);
1129 return EXIT_SUCCESS
;
1133 * Get or set the kernel RTC driver's epoch on Alpha machines.
1134 * ISA machines are hard coded for 1900.
1136 #if defined(__linux__) && defined(__alpha__)
1138 manipulate_epoch(const struct hwclock_control
*ctl
)
1140 if (ctl
->getepoch
) {
1141 unsigned long epoch
;
1143 if (get_epoch_rtc(ctl
, &epoch
))
1144 warnx(_("unable to read the RTC epoch."));
1146 printf(_("The RTC epoch is set to %lu.\n"), epoch
);
1147 } else if (ctl
->setepoch
) {
1148 if (!ctl
->epoch_option
)
1149 warnx(_("--epoch is required for --setepoch."));
1150 else if (!ctl
->testing
)
1151 if (set_epoch_rtc(ctl
))
1152 warnx(_("unable to set the RTC epoch."));
1155 #endif /* __linux__ __alpha__ */
1159 manipulate_rtc_param(const struct hwclock_control
*ctl
)
1161 if (ctl
->param_get_option
) {
1162 uint64_t id
= 0, value
= 0;
1164 if (get_param_rtc(ctl
, ctl
->param_get_option
, &id
, &value
)) {
1165 warnx(_("unable to read the RTC parameter %s"),
1166 ctl
->param_get_option
);
1170 printf(_("The RTC parameter 0x%jx is set to 0x%jx.\n"),
1171 (uintmax_t) id
, (uintmax_t) value
);
1174 } else if (ctl
->param_set_option
) {
1178 return set_param_rtc(ctl
, ctl
->param_set_option
);
1185 manipulate_rtc_voltage_low(const struct hwclock_control
*ctl
)
1188 if (rtc_vl_read(ctl
))
1191 if (ctl
->vl_clear
) {
1192 if (rtc_vl_clear(ctl
))
1199 static void out_version(void)
1201 printf(UTIL_LINUX_VERSION
);
1204 static void __attribute__((__noreturn__
))
1208 const struct hwclock_param
*param
= get_hwclock_params();
1211 fputs(USAGE_HEADER
, stdout
);
1212 printf(_(" %s [function] [option...]\n"), program_invocation_short_name
);
1214 fputs(USAGE_SEPARATOR
, stdout
);
1215 puts(_("Time clocks utility."));
1217 fputs(USAGE_FUNCTIONS
, stdout
);
1218 puts(_(" -r, --show display the RTC time"));
1219 puts(_(" --get display drift corrected RTC time"));
1220 puts(_(" --set set the RTC according to --date"));
1221 puts(_(" -s, --hctosys set the system time from the RTC"));
1222 puts(_(" -w, --systohc set the RTC from the system time"));
1223 puts(_(" --systz send timescale configurations to the kernel"));
1224 puts(_(" -a, --adjust adjust the RTC to account for systematic drift"));
1225 #if defined(__linux__) && defined(__alpha__)
1226 puts(_(" --getepoch display the RTC epoch"));
1227 puts(_(" --setepoch set the RTC epoch according to --epoch"));
1230 puts(_(" --param-get <param> display the RTC parameter"));
1231 puts(_(" --param-set <param>=<value> set the RTC parameter"));
1232 puts(_(" --vl-read read voltage low information"));
1233 puts(_(" --vl-clear clear voltage low information"));
1235 puts(_(" --predict predict the drifted RTC time according to --date"));
1236 fputs(USAGE_OPTIONS
, stdout
);
1237 puts(_(" -u, --utc the RTC timescale is UTC"));
1238 puts(_(" -l, --localtime the RTC timescale is Local"));
1241 " -f, --rtc <file> use an alternate file to %1$s\n"), _PATH_RTC_DEV
);
1244 " --directisa use the ISA bus instead of %1$s access\n"), _PATH_RTC_DEV
);
1245 puts(_(" --date <time> date/time input for --set and --predict"));
1246 puts(_(" --delay <sec> delay used when set new RTC time"));
1247 #if defined(__linux__) && defined(__alpha__)
1248 puts(_(" --epoch <year> epoch input for --setepoch"));
1250 puts(_(" --update-drift update the RTC drift factor"));
1252 " --noadjfile do not use %1$s\n"), _PATH_ADJTIME
);
1254 " --adjfile <file> use an alternate file to %1$s\n"), _PATH_ADJTIME
);
1255 puts(_(" --test dry run; implies --verbose"));
1256 puts(_(" -v, --verbose display more details"));
1258 fputs(USAGE_SEPARATOR
, stdout
);
1259 fprintf(stdout
, USAGE_HELP_OPTIONS(33));
1262 fputs(USAGE_ARGUMENTS
, stdout
);
1263 fputs(_(" <param> is either a numeric RTC parameter value or one of these aliases:"), stdout
);
1265 while (param
->name
) {
1266 fprintf(stdout
, _(" - %1$s: %2$s (0x%3$x)\n"), param
->name
, param
->help
, param
->id
);
1270 fputs(_(" See Kernel's include/uapi/linux/rtc.h for parameters and values."), stdout
);
1271 fputs(USAGE_ARG_SEPARATOR
, stdout
);
1272 fputs(_(" <param> and <value> accept hexadecimal values if prefixed with 0x, otherwise decimal."), stdout
);
1274 fprintf(stdout
, USAGE_MAN_TAIL("hwclock(8)"));
1278 int main(int argc
, char **argv
)
1280 struct hwclock_control ctl
= {
1281 .show
= 1, /* default op is show */
1282 .rtc_delay
= -1.0 /* unspecified */
1284 struct timeval startup_time
;
1285 struct adjtime adjtime
= { 0 };
1287 * The time we started up, in seconds into the epoch, including
1290 time_t set_time
= 0; /* Time to which user said to set Hardware Clock */
1293 /* Long only options. */
1295 OPT_ADJFILE
= CHAR_MAX
+ 1,
1315 static const struct option longopts
[] = {
1316 { "adjust", no_argument
, NULL
, 'a' },
1317 { "help", no_argument
, NULL
, 'h' },
1318 { "localtime", no_argument
, NULL
, 'l' },
1319 { "show", no_argument
, NULL
, 'r' },
1320 { "hctosys", no_argument
, NULL
, 's' },
1321 { "utc", no_argument
, NULL
, 'u' },
1322 { "version", no_argument
, NULL
, 'V' },
1323 { "systohc", no_argument
, NULL
, 'w' },
1324 { "debug", no_argument
, NULL
, 'D' },
1325 { "ul-debug", required_argument
, NULL
, 'd' },
1326 { "verbose", no_argument
, NULL
, 'v' },
1327 { "set", no_argument
, NULL
, OPT_SET
},
1328 #if defined(__linux__) && defined(__alpha__)
1329 { "getepoch", no_argument
, NULL
, OPT_GETEPOCH
},
1330 { "setepoch", no_argument
, NULL
, OPT_SETEPOCH
},
1331 { "epoch", required_argument
, NULL
, OPT_EPOCH
},
1334 { "param-get", required_argument
, NULL
, OPT_PARAM_GET
},
1335 { "param-set", required_argument
, NULL
, OPT_PARAM_SET
},
1336 { "vl-read", no_argument
, NULL
, OPT_VL_READ
},
1337 { "vl-clear", no_argument
, NULL
, OPT_VL_CLEAR
},
1339 { "noadjfile", no_argument
, NULL
, OPT_NOADJFILE
},
1340 { "directisa", no_argument
, NULL
, OPT_DIRECTISA
},
1341 { "test", no_argument
, NULL
, OPT_TEST
},
1342 { "date", required_argument
, NULL
, OPT_DATE
},
1343 { "delay", required_argument
, NULL
, OPT_DELAY
},
1345 { "rtc", required_argument
, NULL
, 'f' },
1347 { "adjfile", required_argument
, NULL
, OPT_ADJFILE
},
1348 { "systz", no_argument
, NULL
, OPT_SYSTZ
},
1349 { "predict", no_argument
, NULL
, OPT_PREDICT
},
1350 { "get", no_argument
, NULL
, OPT_GET
},
1351 { "update-drift", no_argument
, NULL
, OPT_UPDATE
},
1352 { NULL
, 0, NULL
, 0 }
1355 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
1357 OPT_GET
, OPT_GETEPOCH
, OPT_PREDICT
,
1358 OPT_SET
, OPT_SETEPOCH
, OPT_SYSTZ
},
1360 { OPT_ADJFILE
, OPT_NOADJFILE
},
1361 { OPT_NOADJFILE
, OPT_UPDATE
},
1364 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1366 /* Remember what time we were invoked */
1367 gettimeofday(&startup_time
, NULL
);
1369 #ifdef HAVE_LIBAUDIT
1370 hwaudit_fd
= audit_open();
1371 if (hwaudit_fd
< 0 && !(errno
== EINVAL
|| errno
== EPROTONOSUPPORT
||
1372 errno
== EAFNOSUPPORT
)) {
1374 * You get these error codes only when the kernel doesn't
1375 * have audit compiled in.
1377 warnx(_("Unable to connect to audit system"));
1378 return EXIT_FAILURE
;
1381 setlocale(LC_ALL
, "");
1384 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1385 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1386 * - gqueri@mail.dotcom.fr
1388 setlocale(LC_NUMERIC
, "C");
1390 bindtextdomain(PACKAGE
, LOCALEDIR
);
1391 textdomain(PACKAGE
);
1392 close_stdout_atexit();
1394 while ((c
= getopt_long(argc
, argv
,
1395 "hvVDd:alrsuwf:", longopts
, NULL
)) != -1) {
1397 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1401 warnx(_("use --verbose, --debug has been deprecated."));
1407 hwclock_init_debug(optarg
);
1415 ctl
.local_opt
= 1; /* --localtime */
1438 #if defined(__linux__) && defined(__alpha__)
1449 ctl
.epoch_option
= optarg
; /* --epoch */
1454 ctl
.param_get_option
= optarg
;
1458 ctl
.param_set_option
= optarg
;
1478 ctl
.testing
= 1; /* --test */
1482 ctl
.date_opt
= optarg
; /* --date */
1485 ctl
.rtc_delay
= strtod_or_err(optarg
, "invalid --delay argument");
1488 ctl
.adj_file_name
= optarg
; /* --adjfile */
1491 ctl
.systz
= 1; /* --systz */
1496 ctl
.predict
= 1; /* --predict */
1500 ctl
.get
= 1; /* --get */
1504 ctl
.update
= 1; /* --update-drift */
1508 ctl
.rtc_dev_name
= optarg
; /* --rtc */
1512 case 'V': /* --version */
1513 print_version(EXIT_SUCCESS
);
1514 case 'h': /* --help */
1517 errtryhelp(EXIT_FAILURE
);
1521 if (argc
-= optind
) {
1522 warnx(_("too many arguments"));
1523 errtryhelp(EXIT_FAILURE
);
1526 if (!ctl
.adj_file_name
)
1527 ctl
.adj_file_name
= _PATH_ADJTIME
;
1529 if (ctl
.update
&& !ctl
.set
&& !ctl
.systohc
) {
1530 warnx(_("--update-drift requires --set or --systohc"));
1534 if (ctl
.noadjfile
&& !ctl
.utc
&& !ctl
.local_opt
) {
1535 warnx(_("With --noadjfile, you must specify "
1536 "either --utc or --localtime"));
1540 if (ctl
.set
|| ctl
.predict
) {
1541 if (!ctl
.date_opt
) {
1542 warnx(_("--date is required for --set or --predict"));
1545 #ifdef USE_HWCLOCK_GPLv3_DATETIME
1546 /* date(1) compatible GPLv3 parser */
1547 struct timespec when
= { 0 };
1549 if (parse_date(&when
, ctl
.date_opt
, NULL
))
1550 set_time
= when
.tv_sec
;
1552 /* minimalistic GPLv2 based parser */
1555 if (parse_timestamp(ctl
.date_opt
, &usec
) == 0)
1556 set_time
= (time_t) (usec
/ 1000000);
1559 warnx(_("invalid date '%s'"), ctl
.date_opt
);
1565 if (ctl
.param_get_option
|| ctl
.param_set_option
) {
1566 if (manipulate_rtc_param(&ctl
))
1567 hwclock_exit(&ctl
, EXIT_FAILURE
);
1569 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1572 if (ctl
.vl_read
|| ctl
.vl_clear
) {
1573 if (manipulate_rtc_voltage_low(&ctl
))
1574 hwclock_exit(&ctl
, EXIT_FAILURE
);
1576 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1580 #if defined(__linux__) && defined(__alpha__)
1581 if (ctl
.getepoch
|| ctl
.setepoch
) {
1582 manipulate_epoch(&ctl
);
1583 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1589 printf(_("System Time: %"PRId64
".%06"PRId64
"\n"),
1590 (int64_t)startup_time
.tv_sec
, (int64_t)startup_time
.tv_usec
);
1593 if (!ctl
.systz
&& !ctl
.predict
)
1594 determine_clock_access_method(&ctl
);
1596 if (!ctl
.noadjfile
&& !(ctl
.systz
&& (ctl
.utc
|| ctl
.local_opt
))) {
1597 if ((rc
= read_adjtime(&ctl
, &adjtime
)) != 0)
1598 hwclock_exit(&ctl
, rc
);
1600 /* Avoid writing adjtime file if we don't have to. */
1603 ctl
.universal
= hw_clock_is_utc(&ctl
, &adjtime
);
1604 rc
= manipulate_clock(&ctl
, set_time
, startup_time
, &adjtime
);
1606 puts(_("Test mode: nothing was changed."));
1607 hwclock_exit(&ctl
, rc
);
1608 return rc
; /* Not reached */
1612 hwclock_exit(const struct hwclock_control
*ctl
1613 #ifndef HAVE_LIBAUDIT
1614 __attribute__((__unused__
))
1618 #ifdef HAVE_LIBAUDIT
1619 if (ctl
->hwaudit_on
&& !ctl
->testing
) {
1620 audit_log_user_message(hwaudit_fd
, AUDIT_USYS_CONFIG
,
1621 "op=change-system-time", NULL
, NULL
, NULL
,
1622 status
== EXIT_SUCCESS
? 1 : 0);
1630 * History of this program:
1632 * 98.08.12 BJH Version 2.4
1634 * Don't use century byte from Hardware Clock. Add comments telling why.
1636 * 98.06.20 BJH Version 2.3.
1638 * Make --hctosys set the kernel timezone from TZ environment variable
1639 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1641 * 98.03.05 BJH. Version 2.2.
1643 * Add --getepoch and --setepoch.
1645 * Fix some word length things so it works on Alpha.
1647 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1648 * case, busywait for the top of a second instead of blocking and waiting
1649 * for the update complete interrupt.
1651 * Fix a bunch of bugs too numerous to mention.
1653 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1654 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1655 * job (jei@iclnl.icl.nl).
1657 * Use the rtc clock access method in preference to the KDGHWCLK method.
1658 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1660 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1661 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1662 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1663 * and wrote feature test code to detect absence of rtc headers.
1665 ***************************************************************************
1668 * To compile this, you must use GNU compiler optimization (-O option) in
1669 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1670 * compile. If you don't optimize, which means the compiler will generate no
1671 * inline functions, the references to these functions in this program will
1672 * be compiled as external references. Since you probably won't be linking
1673 * with any functions by these names, you will have unresolved external
1674 * references when you link.
1676 * Here's some info on how we must deal with the time that elapses while
1677 * this program runs: There are two major delays as we run:
1679 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1680 * we are synchronized to the Hardware Clock.
1681 * 2) Running the "date" program to interpret the value of our --date
1684 * Reading the /etc/adjtime file is the next biggest source of delay and
1687 * The user wants to know what time it was at the moment they invoked us, not
1688 * some arbitrary time later. And in setting the clock, they are giving us the
1689 * time at the moment we are invoked, so if we set the clock some time
1690 * later, we have to add some time to that.
1692 * So we check the system time as soon as we start up, then run "date" and
1693 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1694 * edge, then check the system time again to see how much time we spent. We
1695 * immediately read the clock then and (if appropriate) report that time,
1696 * and additionally, the delay we measured.
1698 * If we're setting the clock to a time given by the user, we wait some more
1699 * so that the total delay is an integral number of seconds, then set the
1700 * Hardware Clock to the time the user requested plus that integral number
1701 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1703 * If we're setting the clock to the system clock value, we wait for the
1704 * system clock to reach the top of a second, and then set the Hardware
1705 * Clock to the system clock's value.
1707 * Here's an interesting point about setting the Hardware Clock: On my
1708 * machine, when you set it, it sets to that precise time. But one can
1709 * imagine another clock whose update oscillator marches on a steady one
1710 * second period, so updating the clock between any two oscillator ticks is
1711 * the same as updating it right at the earlier tick. To avoid any
1712 * complications that might cause, we set the clock as soon as possible
1713 * after an oscillator tick.
1715 * About synchronizing to the Hardware Clock when reading the time: The
1716 * precision of the Hardware Clock counters themselves is one second. You
1717 * can't read the counters and find out that is 12:01:02.5. But if you
1718 * consider the location in time of the counter's ticks as part of its
1719 * value, then its precision is as infinite as time is continuous! What I'm
1720 * saying is this: To find out the _exact_ time in the hardware clock, we
1721 * wait until the next clock tick (the next time the second counter changes)
1722 * and measure how long we had to wait. We then read the value of the clock
1723 * counters and subtract the wait time and we know precisely what time it
1724 * was when we set out to query the time.
1726 * hwclock uses this method, and considers the Hardware Clock to have
1727 * infinite precision.