2 * SPDX-License-Identifier: GPL-2.0-or-later
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
10 * Since 7a3000f7ba548cf7d74ac77cc63fe8de228a669e (v2.30) hwclock is linked
11 * with parse_date.y from gnullib. This gnulib code is distributed with GPLv3.
12 * Use --disable-hwclock-gplv3 to exclude this code.
14 * Copyright (C) 1992 Charles Hedrick, hedrick@cs.rutgers.edu
15 * Rob Hooft <hooft@chem.ruu.nl>
16 * Harald Koenig <koenig@nova.tat.physik.uni-tuebingen.de>
17 * Alan Modra <alan@spri.levels.unisa.edu.au>
19 * Copyright (C) 2007-2023 Karel Zak <kzak@redhat.com>
21 * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19.
22 * The new program is called hwclock. New features:
24 * - You can set the hardware clock without also modifying the system
26 * - You can read and set the clock with finer than 1 second precision.
27 * - When you set the clock, hwclock automatically refigures the drift
28 * rate, based on how far off the clock was before you set it.
30 * Reshuffled things, added sparc code, and re-added alpha stuff
31 * by David Mosberger <davidm@azstarnet.com>
32 * and Jay Estabrook <jestabro@amt.tay1.dec.com>
33 * and Martin Ostermann <ost@comnets.rwth-aachen.de>, aeb@cwi.nl, 990212.
35 * Fix for Award 2094 bug, Dave Coffin (dcoffin@shore.net) 11/12/98
36 * Change of local time handling, Stefan Ring <e9725446@stud3.tuwien.ac.at>
37 * Change of adjtime handling, James P. Rutledge <ao112@rgfn.epcc.edu>.
42 * Explanation of `adjusting' (Rob Hooft):
44 * The problem with my machine is that its CMOS clock is 10 seconds
45 * per day slow. With this version of clock.c, and my '/etc/rc.local'
46 * reading '/etc/clock -au' instead of '/etc/clock -u -s', this error
47 * is automatically corrected at every boot.
49 * To do this job, the program reads and writes the file '/etc/adjtime'
50 * to determine the correction, and to save its data. In this file are
53 * 1) the correction in seconds per day. (So if your clock runs 5
54 * seconds per day fast, the first number should read -5.0)
55 * 2) the number of seconds since 1/1/1970 the last time the program
57 * 3) the remaining part of a second which was leftover after the last
60 * Installation and use of this program:
62 * a) create a file '/etc/adjtime' containing as the first and only
64 * b) run 'clock -au' or 'clock -a', depending on whether your cmos is
65 * in universal or local time. This updates the second number.
66 * c) set your system time using the 'date' command.
67 * d) update your cmos time using 'clock -wu' or 'clock -w'
68 * e) replace the first number in /etc/adjtime by your correction.
69 * f) put the command 'clock -au' or 'clock -a' in your '/etc/rc.local'
81 #ifdef HAVE_SYS_SYSCALL_H
82 #include <sys/syscall.h>
89 #include "closestream.h"
92 #include "pathnames.h"
94 #include "timeutils.h"
101 #include <libaudit.h>
102 static int hwaudit_fd
= -1;
105 UL_DEBUG_DEFINE_MASK(hwclock
);
106 UL_DEBUG_DEFINE_MASKNAMES(hwclock
) = UL_DEBUG_EMPTY_MASKNAMES
;
108 /* The struct that holds our hardware access routines */
109 static const struct clock_ops
*ur
;
111 /* Maximal clock adjustment in seconds per day.
112 (adjtime() glibc call has 2145 seconds limit on i386, so it is good enough for us as well,
113 43219 is a maximal safe value preventing exact_adjustment overflow.) */
114 #define MAX_DRIFT 2145.0
118 * This is information we keep in the adjtime file that tells us how
119 * to do drift corrections. Elements are all straight from the
120 * adjtime file, so see documentation of that file for details.
121 * Exception is <dirty>, which is an indication that what's in this
122 * structure is not what's in the disk file (because it has been
123 * updated since read from the disk file).
128 time_t last_adj_time
;
131 time_t last_calib_time
;
133 * The most recent time that we set the clock from an external
134 * authority (as opposed to just doing a drift adjustment)
137 enum a_local_utc
{ UTC
= 0, LOCAL
, UNKNOWN
} local_utc
;
139 * To which time zone, local or UTC, we most recently set the
144 static void hwclock_init_debug(const char *str
)
146 __UL_INIT_DEBUG_FROM_STRING(hwclock
, HWCLOCK_DEBUG_
, 0, str
);
148 DBG(INIT
, ul_debug("hwclock debug mask: 0x%04x", hwclock_debug_mask
));
149 DBG(INIT
, ul_debug("hwclock version: %s", PACKAGE_STRING
));
152 /* FOR TESTING ONLY: inject random delays of up to 1000ms */
153 static void up_to_1000ms_sleep(void)
155 int usec
= random() % 1000000;
157 DBG(RANDOM_SLEEP
, ul_debug("sleeping ~%d usec", usec
));
162 * time_t to timeval conversion.
164 static struct timeval
t2tv(time_t timet
)
166 struct timeval rettimeval
;
168 rettimeval
.tv_sec
= timet
;
169 rettimeval
.tv_usec
= 0;
174 * The difference in seconds between two times in "timeval" format.
176 double time_diff(struct timeval subtrahend
, struct timeval subtractor
)
178 return (subtrahend
.tv_sec
- subtractor
.tv_sec
)
179 + (subtrahend
.tv_usec
- subtractor
.tv_usec
) / 1E6
;
183 * The time, in "timeval" format, which is <increment> seconds after the
184 * time <addend>. Of course, <increment> may be negative.
186 static struct timeval
time_inc(struct timeval addend
, double increment
)
188 struct timeval newtime
;
190 newtime
.tv_sec
= addend
.tv_sec
+ (time_t)increment
;
191 newtime
.tv_usec
= addend
.tv_usec
+ (increment
- (time_t)increment
) * 1E6
;
194 * Now adjust it so that the microsecond value is between 0 and 1
197 if (newtime
.tv_usec
< 0) {
198 newtime
.tv_usec
+= 1E6
;
200 } else if (newtime
.tv_usec
>= 1E6
) {
201 newtime
.tv_usec
-= 1E6
;
208 hw_clock_is_utc(const struct hwclock_control
*ctl
,
209 const struct adjtime
*adjtime
)
214 ret
= 1; /* --utc explicitly given on command line */
215 else if (ctl
->local_opt
)
216 ret
= 0; /* --localtime explicitly given */
218 /* get info from adjtime file - default is UTC */
219 ret
= (adjtime
->local_utc
!= LOCAL
);
222 printf(_("Assuming hardware clock is kept in %s time.\n"),
223 ret
? _("UTC") : _("local"));
228 * Read the adjustment parameters out of the /etc/adjtime file.
230 * Return them as the adjtime structure <*adjtime_p>. Its defaults are
231 * initialized in main().
233 static int read_adjtime(const struct hwclock_control
*ctl
,
234 struct adjtime
*adjtime_p
)
237 char line1
[81]; /* String: first line of adjtime file */
238 char line2
[81]; /* String: second line of adjtime file */
239 char line3
[81]; /* String: third line of adjtime file */
240 int64_t last_adj_time
;
241 int64_t last_calib_time
;
243 if (access(ctl
->adj_file_name
, R_OK
) != 0)
246 adjfile
= fopen(ctl
->adj_file_name
, "r"); /* open file for reading */
247 if (adjfile
== NULL
) {
248 warn(_("cannot open %s"), ctl
->adj_file_name
);
252 if (!fgets(line1
, sizeof(line1
), adjfile
))
253 line1
[0] = '\0'; /* In case fgets fails */
254 if (!fgets(line2
, sizeof(line2
), adjfile
))
255 line2
[0] = '\0'; /* In case fgets fails */
256 if (!fgets(line3
, sizeof(line3
), adjfile
))
257 line3
[0] = '\0'; /* In case fgets fails */
261 if (sscanf(line1
, "%lf %"SCNd64
" %lf",
262 &adjtime_p
->drift_factor
,
264 &adjtime_p
->not_adjusted
) != 3)
265 warnx(_("Warning: unrecognized line in adjtime file: %s"), line1
);
267 if (sscanf(line2
, "%"SCNd64
, &last_calib_time
) != 1)
268 warnx(_("Warning: unrecognized line in adjtime file: %s"), line2
);
270 adjtime_p
->last_adj_time
= (time_t)last_adj_time
;
271 adjtime_p
->last_calib_time
= (time_t)last_calib_time
;
273 if (!strcmp(line3
, "UTC\n")) {
274 adjtime_p
->local_utc
= UTC
;
275 } else if (!strcmp(line3
, "LOCAL\n")) {
276 adjtime_p
->local_utc
= LOCAL
;
278 adjtime_p
->local_utc
= UNKNOWN
;
280 warnx(_("Warning: unrecognized third line in adjtime file\n"
281 "(Expected: `UTC' or `LOCAL' or nothing.)"));
286 printf(_("Last drift adjustment done at %"PRId64
" seconds after 1969\n"),
287 (int64_t)adjtime_p
->last_adj_time
);
288 printf(_("Last calibration done at %"PRId64
" seconds after 1969\n"),
289 (int64_t)adjtime_p
->last_calib_time
);
290 printf(_("Hardware clock is on %s time\n"),
291 (adjtime_p
->local_utc
==
292 LOCAL
) ? _("local") : (adjtime_p
->local_utc
==
293 UTC
) ? _("UTC") : _("unknown"));
300 * Wait until the falling edge of the Hardware Clock's update flag so that
301 * any time that is read from the clock immediately after we return will be
304 * The clock only has 1 second precision, so it gives the exact time only
305 * once per second, right on the falling edge of the update flag.
307 * We wait (up to one second) either blocked waiting for an rtc device or in
308 * a CPU spin loop. The former is probably not very accurate.
310 * Return 0 if it worked, nonzero if it didn't.
312 static int synchronize_to_clock_tick(const struct hwclock_control
*ctl
)
317 printf(_("Waiting for clock tick...\n"));
319 rc
= ur
->synchronize_to_clock_tick(ctl
);
323 printf(_("...synchronization failed\n"));
325 printf(_("...got clock tick\n"));
332 * Convert a time in broken down format (hours, minutes, etc.) into standard
333 * unix time (seconds into epoch). Return it as *systime_p.
335 * The broken down time is argument <tm>. This broken down time is either
336 * in local time zone or UTC, depending on value of logical argument
337 * "universal". True means it is in UTC.
339 * If the argument contains values that do not constitute a valid time, and
340 * mktime() recognizes this, return *valid_p == false and *systime_p
341 * undefined. However, mktime() sometimes goes ahead and computes a
342 * fictional time "as if" the input values were valid, e.g. if they indicate
343 * the 31st day of April, mktime() may compute the time of May 1. In such a
344 * case, we return the same fictional value mktime() does as *systime_p and
345 * return *valid_p == true.
348 mktime_tz(const struct hwclock_control
*ctl
, struct tm tm
,
354 *systime_p
= timegm(&tm
);
356 *systime_p
= mktime(&tm
);
357 if (*systime_p
== -1) {
359 * This apparently (not specified in mktime() documentation)
360 * means the 'tm' structure does not contain valid values
361 * (however, not containing valid values does _not_ imply
362 * mktime() returns -1).
366 printf(_("Invalid values in hardware clock: "
367 "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"),
368 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
,
369 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
373 printf(_("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
374 "%"PRId64
" seconds since 1969\n"), tm
.tm_year
+ 1900,
375 tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
, tm
.tm_min
,
376 tm
.tm_sec
, (int64_t)*systime_p
);
382 * Read the hardware clock and return the current time via <tm> argument.
384 * Use the method indicated by <method> argument to access the hardware
388 read_hardware_clock(const struct hwclock_control
*ctl
,
389 int *valid_p
, time_t *systime_p
)
391 struct tm tm
= { 0 };
394 err
= ur
->read_hardware_clock(ctl
, &tm
);
399 printf(_("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
400 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
,
401 tm
.tm_min
, tm
.tm_sec
);
402 *valid_p
= mktime_tz(ctl
, tm
, systime_p
);
408 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
409 * according to <universal>.
412 set_hardware_clock(const struct hwclock_control
*ctl
, const time_t newtime
)
414 struct tm new_broken_time
= { 0 };
416 * Time to which we will set Hardware Clock, in broken down format,
417 * in the time zone of caller's choice
421 gmtime_r(&newtime
, &new_broken_time
);
423 localtime_r(&newtime
, &new_broken_time
);
426 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
427 "= %"PRId64
" seconds since 1969\n"),
428 new_broken_time
.tm_hour
, new_broken_time
.tm_min
,
429 new_broken_time
.tm_sec
, (int64_t)newtime
);
432 ur
->set_hardware_clock(ctl
, &new_broken_time
);
436 get_hardware_delay(const struct hwclock_control
*ctl
)
438 const char *devpath
, *rtcname
;
443 devpath
= ur
->get_device_path();
447 rtcname
= strrchr(devpath
, '/');
448 if (!rtcname
|| !*(rtcname
+ 1))
452 pc
= ul_new_path("/sys/class/rtc/%s", rtcname
);
455 rc
= ul_path_scanf(pc
, "name", "%128[^\n ]", name
);
458 if (rc
!= 1 || !*name
)
462 printf(_("RTC type: '%s'\n"), name
);
464 /* MC146818A-compatible (x86) */
465 if (strcmp(name
, "rtc_cmos") == 0)
471 /* Let's be backwardly compatible */
477 * Set the Hardware Clock to the time "sethwtime", in local time zone or
478 * UTC, according to "universal".
480 * Wait for a fraction of a second so that "sethwtime" is the value of the
481 * Hardware Clock as of system time "refsystime", which is in the past. For
482 * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and
483 * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2
484 * seconds since "refsystime") and then set the Hardware Clock to 14:03:07,
485 * thus getting a precise and retroactive setting of the clock. The .5 delay is
486 * default on x86, see --delay and get_hardware_delay().
488 * (Don't be confused by the fact that the system clock and the Hardware
489 * Clock differ by two hours in the above example. That's just to remind you
490 * that there are two independent time scales here).
492 * This function ought to be able to accept set times as fractional times.
493 * Idea for future enhancement.
496 set_hardware_clock_exact(const struct hwclock_control
*ctl
,
497 const time_t sethwtime
,
498 const struct timeval refsystime
)
501 * The Hardware Clock can only be set to any integer time plus one
502 * half second. The integer time is required because there is no
503 * interface to set or get a fractional second. The additional half
504 * second is because the Hardware Clock updates to the following
505 * second precisely 500 ms (not 1 second!) after you release the
506 * divider reset (after setting the new time) - see description of
507 * DV2, DV1, DV0 in Register A in the MC146818A data sheet (and note
508 * that although that document doesn't say so, real-world code seems
509 * to expect that the SET bit in Register B functions the same way).
510 * That means that, e.g., when you set the clock to 1:02:03, it
511 * effectively really sets it to 1:02:03.5, because it will update to
512 * 1:02:04 only half a second later. Our caller passes the desired
513 * integer Hardware Clock time in sethwtime, and the corresponding
514 * system time (which may have a fractional part, and which may or may
515 * not be the same!) in refsystime. In an ideal situation, we would
516 * then apply sethwtime to the Hardware Clock at refsystime+500ms, so
517 * that when the Hardware Clock ticks forward to sethwtime+1s half a
518 * second later at refsystime+1000ms, everything is in sync. So we
519 * spin, waiting for gettimeofday() to return a time at or after that
520 * time (refsystime+500ms) up to a tolerance value, initially 1ms. If
521 * we miss that time due to being preempted for some other process,
522 * then we increase the margin a little bit (initially 1ms, doubling
523 * each time), add 1 second (or more, if needed to get a time that is
524 * in the future) to both the time for which we are waiting and the
525 * time that we will apply to the Hardware Clock, and start waiting
528 * For example, the caller requests that we set the Hardware Clock to
529 * 1:02:03, with reference time (current system time) = 6:07:08.250.
530 * We want the Hardware Clock to update to 1:02:04 at 6:07:09.250 on
531 * the system clock, and the first such update will occur 0.500
532 * seconds after we write to the Hardware Clock, so we spin until the
533 * system clock reads 6:07:08.750. If we get there, great, but let's
534 * imagine the system is so heavily loaded that our process is
535 * preempted and by the time we get to run again, the system clock
536 * reads 6:07:11.990. We now want to wait until the next xx:xx:xx.750
537 * time, which is 6:07:12.750 (4.5 seconds after the reference time),
538 * at which point we will set the Hardware Clock to 1:02:07 (4 seconds
539 * after the originally requested time). If we do that successfully,
540 * then at 6:07:13.250 (5 seconds after the reference time), the
541 * Hardware Clock will update to 1:02:08 (5 seconds after the
542 * originally requested time), and all is well thereafter.
545 time_t newhwtime
= sethwtime
;
546 double target_time_tolerance_secs
= 0.001; /* initial value */
547 double tolerance_incr_secs
= 0.001; /* initial value */
549 struct timeval rtc_set_delay_tv
;
551 struct timeval targetsystime
;
552 struct timeval nowsystime
;
553 struct timeval prevsystime
= refsystime
;
554 double deltavstarget
;
556 if (ctl
->rtc_delay
!= -1.0) /* --delay specified */
557 delay
= ctl
->rtc_delay
;
559 delay
= get_hardware_delay(ctl
);
562 printf(_("Using delay: %.6f seconds\n"), delay
);
564 rtc_set_delay_tv
.tv_sec
= 0;
565 rtc_set_delay_tv
.tv_usec
= delay
* 1E6
;
567 timeradd(&refsystime
, &rtc_set_delay_tv
, &targetsystime
);
572 ON_DBG(RANDOM_SLEEP
, up_to_1000ms_sleep());
574 gettimeofday(&nowsystime
, NULL
);
575 deltavstarget
= time_diff(nowsystime
, targetsystime
);
576 ticksize
= time_diff(nowsystime
, prevsystime
);
577 prevsystime
= nowsystime
;
581 printf(_("time jumped backward %.6f seconds "
582 "to %"PRId64
".%06"PRId64
" - retargeting\n"),
583 ticksize
, (int64_t)nowsystime
.tv_sec
,
584 (int64_t)nowsystime
.tv_usec
);
585 /* The retarget is handled at the end of the loop. */
586 } else if (deltavstarget
< 0) {
587 /* deltavstarget < 0 if current time < target time */
589 ul_debug("%"PRId64
".%06"PRId64
" < %"PRId64
".%06"PRId64
" (%.6f)",
590 (int64_t)nowsystime
.tv_sec
, (int64_t)nowsystime
.tv_usec
,
591 (int64_t)targetsystime
.tv_sec
,
592 (int64_t)targetsystime
.tv_usec
, deltavstarget
));
593 continue; /* not there yet - keep spinning */
594 } else if (deltavstarget
<= target_time_tolerance_secs
) {
595 /* Close enough to the target time; done waiting. */
597 } else /* (deltavstarget > target_time_tolerance_secs) */ {
599 * We missed our window. Increase the tolerance and
600 * aim for the next opportunity.
603 printf(_("missed it - %"PRId64
".%06"PRId64
" is too far "
604 "past %"PRId64
".%06"PRId64
" (%.6f > %.6f)\n"),
605 (int64_t)nowsystime
.tv_sec
,
606 (int64_t)nowsystime
.tv_usec
,
607 (int64_t)targetsystime
.tv_sec
,
608 (int64_t)targetsystime
.tv_usec
,
610 target_time_tolerance_secs
);
611 target_time_tolerance_secs
+= tolerance_incr_secs
;
612 tolerance_incr_secs
*= 2;
616 * Aim for the same offset (tv_usec) within the second in
617 * either the current second (if that offset hasn't arrived
618 * yet), or the next second.
620 if (nowsystime
.tv_usec
< targetsystime
.tv_usec
)
621 targetsystime
.tv_sec
= nowsystime
.tv_sec
;
623 targetsystime
.tv_sec
= nowsystime
.tv_sec
+ 1;
626 newhwtime
= sethwtime
627 + ceil(time_diff(nowsystime
, refsystime
)
628 - delay
/* don't count this */);
630 printf(_("%"PRId64
".%06"PRId64
" is close enough to %"PRId64
".%06"PRId64
" (%.6f < %.6f)\n"
631 "Set RTC to %"PRId64
" (%"PRId64
" + %d; refsystime = %"PRId64
".%06"PRId64
")\n"),
632 (int64_t)nowsystime
.tv_sec
, (int64_t)nowsystime
.tv_usec
,
633 (int64_t)targetsystime
.tv_sec
, (int64_t)targetsystime
.tv_usec
,
634 deltavstarget
, target_time_tolerance_secs
,
635 (int64_t)newhwtime
, (int64_t)sethwtime
,
636 (int)((int64_t)newhwtime
- (int64_t)sethwtime
),
637 (int64_t)refsystime
.tv_sec
, (int64_t)refsystime
.tv_usec
);
639 set_hardware_clock(ctl
, newhwtime
);
643 display_time(struct timeval hwctime
)
645 char buf
[ISO_BUFSIZ
];
647 if (strtimeval_iso(&hwctime
, ISO_TIMESTAMP_DOT
, buf
, sizeof(buf
)))
655 * Adjusts System time, sets the kernel's timezone and RTC timescale.
657 * The kernel warp_clock function adjusts the System time according to the
658 * tz.tz_minuteswest argument and sets PCIL (see below). At boot settimeofday(2)
659 * has one-shot access to this function as shown in the table below.
661 * +-------------------------------------------------------------------------+
662 * | settimeofday(tv, tz) |
663 * |-------------------------------------------------------------------------|
664 * | Arguments | System Time | TZ | PCIL | | warp_clock |
665 * | tv | tz | set | warped | set | set | firsttime | locked |
666 * |---------|---------|---------------|-----|------|-----------|------------|
667 * | pointer | NULL | yes | no | no | no | 1 | no |
668 * | NULL | ptr2utc | no | no | yes | no | 0 | yes |
669 * | NULL | pointer | no | yes | yes | yes | 0 | yes |
670 * +-------------------------------------------------------------------------+
671 * ptr2utc: tz.tz_minuteswest is zero (UTC).
672 * PCIL: persistent_clock_is_local, sets the "11 minute mode" timescale.
673 * firsttime: locks the warp_clock function (initialized to 1 at boot).
675 * +---------------------------------------------------------------------------+
676 * | op | RTC scale | settimeofday calls |
677 * |---------|-----------|-----------------------------------------------------|
678 * | systz | Local | 1) warps system time*, sets PCIL* and kernel tz |
679 * | systz | UTC | 1st) locks warp_clock* 2nd) sets kernel tz |
680 * | hctosys | Local | 1st) sets PCIL* & kernel tz 2nd) sets system time |
681 * | hctosys | UTC | 1st) locks warp* 2nd) sets tz 3rd) sets system time |
682 * +---------------------------------------------------------------------------+
683 * * only on first call after boot
685 * POSIX 2008 marked TZ in settimeofday() as deprecated. Unfortunately,
686 * different C libraries react to this deprecation in a different way. Since
687 * glibc v2.31 settimeofday() will fail if both args are not NULL, Musl-C
688 * ignores TZ at all, etc. We use __set_time() and __set_timezone() to hide
689 * these portability issues and to keep code readable.
691 #define __set_time(_tv) settimeofday(_tv, NULL)
693 #ifndef SYS_settimeofday
694 # ifdef __NR_settimeofday
695 # define SYS_settimeofday __NR_settimeofday
696 # elif defined(__NR_settimeofday_time32)
697 # define SYS_settimeofday __NR_settimeofday_time32
701 static inline int __set_timezone(const struct timezone
*tz
)
703 #ifdef SYS_settimeofday
705 return syscall(SYS_settimeofday
, NULL
, tz
);
707 return settimeofday(NULL
, tz
);
712 set_system_clock(const struct hwclock_control
*ctl
,
713 const struct timeval newtime
)
715 struct tm broken
= { 0 };
719 localtime_r(&newtime
.tv_sec
, &broken
);
720 minuteswest
= -get_gmtoff(&broken
) / 60;
723 if (ctl
->universal
) {
724 puts(_("Calling settimeofday(NULL, 0) "
725 "to lock the warp_clock function."));
726 if (!( ctl
->universal
&& !minuteswest
))
727 printf(_("Calling settimeofday(NULL, %d) "
728 "to set the kernel timezone.\n"),
731 printf(_("Calling settimeofday(NULL, %d) to warp "
732 "System time, set PCIL and the kernel tz.\n"),
736 printf(_("Calling settimeofday(%"PRId64
".%06"PRId64
", NULL) "
737 "to set the System time.\n"),
738 (int64_t)newtime
.tv_sec
, (int64_t)newtime
.tv_usec
);
742 const struct timezone tz_utc
= { 0 };
743 const struct timezone tz
= { minuteswest
};
745 /* If UTC RTC: lock warp_clock and PCIL */
747 rc
= __set_timezone(&tz_utc
);
749 /* Set kernel tz; if localtime RTC: warp_clock and set PCIL */
750 if (!rc
&& !( ctl
->universal
&& !minuteswest
))
751 rc
= __set_timezone(&tz
);
753 /* Set the System Clock */
754 if ((!rc
|| errno
== ENOSYS
) && ctl
->hctosys
)
755 rc
= __set_time(&newtime
);
758 warn(_("settimeofday() failed"));
766 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
767 * to facilitate future drift calculations based on this set point.
769 * With the --update-drift option:
770 * Update the drift factor in <*adjtime_p> based on the fact that the
771 * Hardware Clock was just calibrated to <nowtime> and before that was
772 * set to the <hclocktime> time scale.
775 adjust_drift_factor(const struct hwclock_control
*ctl
,
776 struct adjtime
*adjtime_p
,
777 const struct timeval nowtime
,
778 const struct timeval hclocktime
)
782 printf(_("Not adjusting drift factor because the "
783 "--update-drift option was not used.\n"));
784 } else if (adjtime_p
->last_calib_time
== 0) {
786 printf(_("Not adjusting drift factor because last "
787 "calibration time is zero,\n"
788 "so history is bad and calibration startover "
790 } else if ((hclocktime
.tv_sec
- adjtime_p
->last_calib_time
) < 4 * 60 * 60) {
792 printf(_("Not adjusting drift factor because it has "
793 "been less than four hours since the last "
797 * At adjustment time we drift correct the hardware clock
798 * according to the contents of the adjtime file and refresh
799 * its last adjusted timestamp.
801 * At calibration time we set the Hardware Clock and refresh
802 * both timestamps in <*adjtime_p>.
804 * Here, with the --update-drift option, we also update the
805 * drift factor in <*adjtime_p>.
807 * Let us do computation in doubles. (Floats almost suffice,
808 * but 195 days + 1 second equals 195 days in floats.)
810 const double sec_per_day
= 24.0 * 60.0 * 60.0;
811 double factor_adjust
;
813 struct timeval last_calib
;
815 last_calib
= t2tv(adjtime_p
->last_calib_time
);
817 * Correction to apply to the current drift factor.
819 * Simplified: uncorrected_drift / days_since_calibration.
821 * hclocktime is fully corrected with the current drift factor.
822 * Its difference from nowtime is the missed drift correction.
824 factor_adjust
= time_diff(nowtime
, hclocktime
) /
825 (time_diff(nowtime
, last_calib
) / sec_per_day
);
827 drift_factor
= adjtime_p
->drift_factor
+ factor_adjust
;
828 if (fabs(drift_factor
) > MAX_DRIFT
) {
830 printf(_("Clock drift factor was calculated as "
832 "It is far too much. Resetting to zero.\n"),
837 printf(_("Clock drifted %f seconds in the past "
838 "%f seconds\nin spite of a drift factor of "
840 "Adjusting drift factor by %f seconds/day\n"),
841 time_diff(nowtime
, hclocktime
),
842 time_diff(nowtime
, last_calib
),
843 adjtime_p
->drift_factor
, factor_adjust
);
846 adjtime_p
->drift_factor
= drift_factor
;
848 adjtime_p
->last_calib_time
= nowtime
.tv_sec
;
850 adjtime_p
->last_adj_time
= nowtime
.tv_sec
;
852 adjtime_p
->not_adjusted
= 0;
854 adjtime_p
->dirty
= 1;
858 * Calculate the drift correction currently needed for the
859 * Hardware Clock based on the last time it was adjusted,
860 * and the current drift factor, as stored in the adjtime file.
862 * The total drift adjustment needed is stored at tdrift_p.
866 calculate_adjustment(const struct hwclock_control
*ctl
,
868 const time_t last_time
,
869 const double not_adjusted
,
870 const time_t systime
, struct timeval
*tdrift_p
)
872 double exact_adjustment
;
875 ((double)(systime
- last_time
)) * factor
/ (24 * 60 * 60)
877 tdrift_p
->tv_sec
= (time_t) floor(exact_adjustment
);
878 tdrift_p
->tv_usec
= (exact_adjustment
-
879 (double)tdrift_p
->tv_sec
) * 1E6
;
881 printf(P_("Time since last adjustment is %"PRId64
" second\n",
882 "Time since last adjustment is %"PRId64
" seconds\n",
883 ((int64_t)systime
- (int64_t)last_time
)),
884 ((int64_t)systime
- (int64_t)last_time
));
885 printf(_("Calculated Hardware Clock drift is %"PRId64
".%06"PRId64
" seconds\n"),
886 (int64_t)tdrift_p
->tv_sec
, (int64_t)tdrift_p
->tv_usec
);
891 * Write the contents of the <adjtime> structure to its disk file.
893 * But if the contents are clean (unchanged since read from disk), don't
896 static int save_adjtime(const struct hwclock_control
*ctl
,
897 const struct adjtime
*adjtime
)
899 char *content
; /* Stuff to write to disk file */
902 xasprintf(&content
, "%f %"PRId64
" %f\n%"PRId64
"\n%s\n",
903 adjtime
->drift_factor
,
904 (int64_t)adjtime
->last_adj_time
,
905 adjtime
->not_adjusted
,
906 (int64_t)adjtime
->last_calib_time
,
907 (adjtime
->local_utc
== LOCAL
) ? "LOCAL" : "UTC");
910 printf(_("New %s data:\n%s"),
911 ctl
->adj_file_name
, content
);
917 fp
= fopen(ctl
->adj_file_name
, "w");
919 warn(_("cannot open %s"), ctl
->adj_file_name
);
923 rc
= fputs(content
, fp
) < 0;
924 rc
+= close_stream(fp
);
927 warn(_("cannot update %s"), ctl
->adj_file_name
);
935 * Do the adjustment requested, by 1) setting the Hardware Clock (if
936 * necessary), and 2) updating the last-adjusted time in the adjtime
939 * Do not update anything if the Hardware Clock does not currently present a
942 * <hclocktime> is the drift corrected time read from the Hardware Clock.
944 * <read_time> was the system time when the <hclocktime> was read, which due
945 * to computational delay could be a short time ago. It is used to define a
946 * trigger point for setting the Hardware Clock. The fractional part of the
947 * Hardware clock set time is subtracted from read_time to 'refer back', or
948 * delay, the trigger point. Fractional parts must be accounted for in this
949 * way, because the Hardware Clock can only be set to a whole second.
951 * <universal>: the Hardware Clock is kept in UTC.
953 * <testing>: We are running in test mode (no updating of clock).
957 do_adjustment(const struct hwclock_control
*ctl
, struct adjtime
*adjtime_p
,
958 const struct timeval hclocktime
,
959 const struct timeval read_time
)
961 if (adjtime_p
->last_adj_time
== 0) {
963 printf(_("Not setting clock because last adjustment time is zero, "
964 "so history is bad.\n"));
965 } else if (fabs(adjtime_p
->drift_factor
) > MAX_DRIFT
) {
967 printf(_("Not setting clock because drift factor %f is far too high.\n"),
968 adjtime_p
->drift_factor
);
970 set_hardware_clock_exact(ctl
, hclocktime
.tv_sec
,
972 -(hclocktime
.tv_usec
/ 1E6
)));
973 adjtime_p
->last_adj_time
= hclocktime
.tv_sec
;
974 adjtime_p
->not_adjusted
= 0;
975 adjtime_p
->dirty
= 1;
979 static void determine_clock_access_method(const struct hwclock_control
*ctl
)
983 #ifdef USE_HWCLOCK_CMOS
985 ur
= probe_for_cmos_clock();
989 ur
= probe_for_rtc_clock(ctl
);
993 puts(ur
->interface_name
);
997 printf(_("No usable clock interface found.\n"));
999 warnx(_("Cannot access the Hardware Clock via "
1000 "any known method."));
1003 warnx(_("Use the --verbose option to see the "
1004 "details of our search for an access "
1006 hwclock_exit(ctl
, EXIT_FAILURE
);
1010 /* Do all the normal work of hwclock - read, set clock, etc. */
1012 manipulate_clock(const struct hwclock_control
*ctl
, const time_t set_time
,
1013 const struct timeval startup_time
, struct adjtime
*adjtime
)
1015 /* The time at which we read the Hardware Clock */
1016 struct timeval read_time
= { 0 };
1018 * The Hardware Clock gives us a valid time, or at
1019 * least something close enough to fool mktime().
1021 int hclock_valid
= 0;
1023 * Tick synchronized time read from the Hardware Clock and
1024 * then drift corrected for all operations except --show.
1026 struct timeval hclocktime
= { 0 };
1028 * hclocktime correlated to startup_time. That is, what drift
1029 * corrected Hardware Clock time would have been at start up.
1031 struct timeval startup_hclocktime
= { 0 };
1032 /* Total Hardware Clock drift correction needed. */
1033 struct timeval tdrift
= { 0 };
1035 if ((ctl
->set
|| ctl
->systohc
|| ctl
->adjust
) &&
1036 (adjtime
->local_utc
== UTC
) != ctl
->universal
) {
1037 adjtime
->local_utc
= ctl
->universal
? UTC
: LOCAL
;
1041 * Negate the drift correction, because we want to 'predict' a
1042 * Hardware Clock time that includes drift.
1045 hclocktime
= t2tv(set_time
);
1046 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1047 adjtime
->last_adj_time
,
1048 adjtime
->not_adjusted
,
1049 hclocktime
.tv_sec
, &tdrift
);
1050 hclocktime
= time_inc(hclocktime
, (double)
1051 -(tdrift
.tv_sec
+ tdrift
.tv_usec
/ 1E6
));
1053 printf(_("Target date: %"PRId64
"\n"), (int64_t)set_time
);
1054 printf(_("Predicted RTC: %"PRId64
"\n"), (int64_t)hclocktime
.tv_sec
);
1056 return display_time(hclocktime
);
1060 return set_system_clock(ctl
, startup_time
);
1062 if (ur
->get_permissions())
1063 return EXIT_FAILURE
;
1066 * Read and drift correct RTC time; except for RTC set functions
1067 * without the --update-drift option because: 1) it's not needed;
1068 * 2) it enables setting a corrupted RTC without reading it first;
1069 * 3) it significantly reduces system shutdown time.
1071 if ( ! ((ctl
->set
|| ctl
->systohc
) && !ctl
->update
)) {
1073 * Timing critical - do not change the order of, or put
1074 * anything between the follow three statements.
1075 * Synchronization failure MUST exit, because all drift
1076 * operations are invalid without it.
1078 if (synchronize_to_clock_tick(ctl
))
1079 return EXIT_FAILURE
;
1080 read_hardware_clock(ctl
, &hclock_valid
, &hclocktime
.tv_sec
);
1081 gettimeofday(&read_time
, NULL
);
1083 if (!hclock_valid
) {
1084 warnx(_("RTC read returned an invalid value."));
1085 return EXIT_FAILURE
;
1088 * Calculate and apply drift correction to the Hardware Clock
1089 * time for everything except --show
1091 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1092 adjtime
->last_adj_time
,
1093 adjtime
->not_adjusted
,
1094 hclocktime
.tv_sec
, &tdrift
);
1096 hclocktime
= time_inc(tdrift
, hclocktime
.tv_sec
);
1098 startup_hclocktime
=
1099 time_inc(hclocktime
, time_diff(startup_time
, read_time
));
1101 if (ctl
->show
|| ctl
->get
) {
1102 return display_time(startup_hclocktime
);
1106 set_hardware_clock_exact(ctl
, set_time
, startup_time
);
1107 if (!ctl
->noadjfile
)
1108 adjust_drift_factor(ctl
, adjtime
, t2tv(set_time
),
1109 startup_hclocktime
);
1110 } else if (ctl
->adjust
) {
1111 if (tdrift
.tv_sec
> 0 || tdrift
.tv_sec
< -1)
1112 do_adjustment(ctl
, adjtime
, hclocktime
, read_time
);
1114 printf(_("Needed adjustment is less than one second, "
1115 "so not setting clock.\n"));
1116 } else if (ctl
->systohc
) {
1117 struct timeval nowtime
, reftime
;
1119 * We can only set_hardware_clock_exact to a
1120 * whole seconds time, so we set it with
1121 * reference to the most recent whole
1124 gettimeofday(&nowtime
, NULL
);
1125 reftime
.tv_sec
= nowtime
.tv_sec
;
1126 reftime
.tv_usec
= 0;
1127 set_hardware_clock_exact(ctl
, (time_t) reftime
.tv_sec
, reftime
);
1128 if (!ctl
->noadjfile
)
1129 adjust_drift_factor(ctl
, adjtime
, nowtime
,
1131 } else if (ctl
->hctosys
) {
1132 return set_system_clock(ctl
, hclocktime
);
1134 if (!ctl
->noadjfile
&& adjtime
->dirty
)
1135 return save_adjtime(ctl
, adjtime
);
1136 return EXIT_SUCCESS
;
1140 * Get or set the kernel RTC driver's epoch on Alpha machines.
1141 * ISA machines are hard coded for 1900.
1143 #if defined(__linux__) && defined(__alpha__)
1145 manipulate_epoch(const struct hwclock_control
*ctl
)
1147 if (ctl
->getepoch
) {
1148 unsigned long epoch
;
1150 if (get_epoch_rtc(ctl
, &epoch
))
1151 warnx(_("unable to read the RTC epoch."));
1153 printf(_("The RTC epoch is set to %lu.\n"), epoch
);
1154 } else if (ctl
->setepoch
) {
1155 if (!ctl
->epoch_option
)
1156 warnx(_("--epoch is required for --setepoch."));
1157 else if (!ctl
->testing
)
1158 if (set_epoch_rtc(ctl
))
1159 warnx(_("unable to set the RTC epoch."));
1162 #endif /* __linux__ __alpha__ */
1166 manipulate_rtc_param(const struct hwclock_control
*ctl
)
1168 if (ctl
->param_get_option
) {
1169 uint64_t id
= 0, value
= 0;
1171 if (get_param_rtc(ctl
, ctl
->param_get_option
, &id
, &value
)) {
1172 warnx(_("unable to read the RTC parameter %s"),
1173 ctl
->param_get_option
);
1177 printf(_("The RTC parameter 0x%jx is set to 0x%jx.\n"),
1178 (uintmax_t) id
, (uintmax_t) value
);
1181 } else if (ctl
->param_set_option
) {
1185 return set_param_rtc(ctl
, ctl
->param_set_option
);
1192 manipulate_rtc_voltage_low(const struct hwclock_control
*ctl
)
1195 if (rtc_vl_read(ctl
))
1198 if (ctl
->vl_clear
) {
1199 if (rtc_vl_clear(ctl
))
1206 static void out_version(void)
1208 printf(UTIL_LINUX_VERSION
);
1211 static void __attribute__((__noreturn__
))
1215 const struct hwclock_param
*param
= get_hwclock_params();
1218 fputs(USAGE_HEADER
, stdout
);
1219 printf(_(" %s [function] [option...]\n"), program_invocation_short_name
);
1221 fputs(USAGE_SEPARATOR
, stdout
);
1222 puts(_("Time clocks utility."));
1224 fputs(USAGE_FUNCTIONS
, stdout
);
1225 puts(_(" -r, --show display the RTC time"));
1226 puts(_(" --get display drift corrected RTC time"));
1227 puts(_(" --set set the RTC according to --date"));
1228 puts(_(" -s, --hctosys set the system time from the RTC"));
1229 puts(_(" -w, --systohc set the RTC from the system time"));
1230 puts(_(" --systz send timescale configurations to the kernel"));
1231 puts(_(" -a, --adjust adjust the RTC to account for systematic drift"));
1232 #if defined(__linux__) && defined(__alpha__)
1233 puts(_(" --getepoch display the RTC epoch"));
1234 puts(_(" --setepoch set the RTC epoch according to --epoch"));
1237 puts(_(" --param-get <param> display the RTC parameter"));
1238 puts(_(" --param-set <param>=<value> set the RTC parameter"));
1239 puts(_(" --vl-read read voltage low information"));
1240 puts(_(" --vl-clear clear voltage low information"));
1242 puts(_(" --predict predict the drifted RTC time according to --date"));
1243 fputs(USAGE_OPTIONS
, stdout
);
1244 puts(_(" -u, --utc the RTC timescale is UTC"));
1245 puts(_(" -l, --localtime the RTC timescale is Local"));
1248 " -f, --rtc <file> use an alternate file to %1$s\n"), _PATH_RTC_DEV
);
1251 " --directisa use the ISA bus instead of %1$s access\n"), _PATH_RTC_DEV
);
1252 puts(_(" --date <time> date/time input for --set and --predict"));
1253 puts(_(" --delay <sec> delay used when set new RTC time"));
1254 #if defined(__linux__) && defined(__alpha__)
1255 puts(_(" --epoch <year> epoch input for --setepoch"));
1257 puts(_(" --update-drift update the RTC drift factor"));
1259 " --noadjfile do not use %1$s\n"), _PATH_ADJTIME
);
1261 " --adjfile <file> use an alternate file to %1$s\n"), _PATH_ADJTIME
);
1262 puts(_(" --test dry run; implies --verbose"));
1263 puts(_(" -v, --verbose display more details"));
1265 fputs(USAGE_SEPARATOR
, stdout
);
1266 fprintf(stdout
, USAGE_HELP_OPTIONS(33));
1269 fputs(USAGE_ARGUMENTS
, stdout
);
1270 fputs(_(" <param> is either a numeric RTC parameter value or one of these aliases:"), stdout
);
1272 while (param
->name
) {
1273 fprintf(stdout
, _(" - %1$s: %2$s (0x%3$x)\n"), param
->name
, param
->help
, param
->id
);
1277 fputs(_(" See Kernel's include/uapi/linux/rtc.h for parameters and values."), stdout
);
1278 fputs(USAGE_ARG_SEPARATOR
, stdout
);
1279 fputs(_(" <param> and <value> accept hexadecimal values if prefixed with 0x, otherwise decimal."), stdout
);
1281 fprintf(stdout
, USAGE_MAN_TAIL("hwclock(8)"));
1285 int main(int argc
, char **argv
)
1287 struct hwclock_control ctl
= {
1288 .show
= 1, /* default op is show */
1289 .rtc_delay
= -1.0 /* unspecified */
1291 struct timeval startup_time
;
1292 struct adjtime adjtime
= { 0 };
1294 * The time we started up, in seconds into the epoch, including
1297 time_t set_time
= 0; /* Time to which user said to set Hardware Clock */
1300 /* Long only options. */
1302 OPT_ADJFILE
= CHAR_MAX
+ 1,
1322 static const struct option longopts
[] = {
1323 { "adjust", no_argument
, NULL
, 'a' },
1324 { "help", no_argument
, NULL
, 'h' },
1325 { "localtime", no_argument
, NULL
, 'l' },
1326 { "show", no_argument
, NULL
, 'r' },
1327 { "hctosys", no_argument
, NULL
, 's' },
1328 { "utc", no_argument
, NULL
, 'u' },
1329 { "version", no_argument
, NULL
, 'V' },
1330 { "systohc", no_argument
, NULL
, 'w' },
1331 { "debug", no_argument
, NULL
, 'D' },
1332 { "ul-debug", required_argument
, NULL
, 'd' },
1333 { "verbose", no_argument
, NULL
, 'v' },
1334 { "set", no_argument
, NULL
, OPT_SET
},
1335 #if defined(__linux__) && defined(__alpha__)
1336 { "getepoch", no_argument
, NULL
, OPT_GETEPOCH
},
1337 { "setepoch", no_argument
, NULL
, OPT_SETEPOCH
},
1338 { "epoch", required_argument
, NULL
, OPT_EPOCH
},
1341 { "param-get", required_argument
, NULL
, OPT_PARAM_GET
},
1342 { "param-set", required_argument
, NULL
, OPT_PARAM_SET
},
1343 { "vl-read", no_argument
, NULL
, OPT_VL_READ
},
1344 { "vl-clear", no_argument
, NULL
, OPT_VL_CLEAR
},
1346 { "noadjfile", no_argument
, NULL
, OPT_NOADJFILE
},
1347 { "directisa", no_argument
, NULL
, OPT_DIRECTISA
},
1348 { "test", no_argument
, NULL
, OPT_TEST
},
1349 { "date", required_argument
, NULL
, OPT_DATE
},
1350 { "delay", required_argument
, NULL
, OPT_DELAY
},
1352 { "rtc", required_argument
, NULL
, 'f' },
1354 { "adjfile", required_argument
, NULL
, OPT_ADJFILE
},
1355 { "systz", no_argument
, NULL
, OPT_SYSTZ
},
1356 { "predict", no_argument
, NULL
, OPT_PREDICT
},
1357 { "get", no_argument
, NULL
, OPT_GET
},
1358 { "update-drift", no_argument
, NULL
, OPT_UPDATE
},
1359 { NULL
, 0, NULL
, 0 }
1362 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
1364 OPT_GET
, OPT_GETEPOCH
, OPT_PREDICT
,
1365 OPT_SET
, OPT_SETEPOCH
, OPT_SYSTZ
},
1367 { OPT_ADJFILE
, OPT_NOADJFILE
},
1368 { OPT_NOADJFILE
, OPT_UPDATE
},
1371 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1373 /* Remember what time we were invoked */
1374 gettimeofday(&startup_time
, NULL
);
1376 #ifdef HAVE_LIBAUDIT
1377 hwaudit_fd
= audit_open();
1378 if (hwaudit_fd
< 0 && !(errno
== EINVAL
|| errno
== EPROTONOSUPPORT
||
1379 errno
== EAFNOSUPPORT
)) {
1381 * You get these error codes only when the kernel doesn't
1382 * have audit compiled in.
1384 warnx(_("Unable to connect to audit system"));
1385 return EXIT_FAILURE
;
1388 setlocale(LC_ALL
, "");
1391 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1392 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1393 * - gqueri@mail.dotcom.fr
1395 setlocale(LC_NUMERIC
, "C");
1397 bindtextdomain(PACKAGE
, LOCALEDIR
);
1398 textdomain(PACKAGE
);
1399 close_stdout_atexit();
1401 while ((c
= getopt_long(argc
, argv
,
1402 "hvVDd:alrsuwf:", longopts
, NULL
)) != -1) {
1404 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1408 warnx(_("use --verbose, --debug has been deprecated."));
1414 hwclock_init_debug(optarg
);
1422 ctl
.local_opt
= 1; /* --localtime */
1445 #if defined(__linux__) && defined(__alpha__)
1456 ctl
.epoch_option
= optarg
; /* --epoch */
1461 ctl
.param_get_option
= optarg
;
1465 ctl
.param_set_option
= optarg
;
1485 ctl
.testing
= 1; /* --test */
1489 ctl
.date_opt
= optarg
; /* --date */
1492 ctl
.rtc_delay
= strtod_or_err(optarg
, "invalid --delay argument");
1495 ctl
.adj_file_name
= optarg
; /* --adjfile */
1498 ctl
.systz
= 1; /* --systz */
1503 ctl
.predict
= 1; /* --predict */
1507 ctl
.get
= 1; /* --get */
1511 ctl
.update
= 1; /* --update-drift */
1515 ctl
.rtc_dev_name
= optarg
; /* --rtc */
1519 case 'V': /* --version */
1520 print_version(EXIT_SUCCESS
);
1521 case 'h': /* --help */
1524 errtryhelp(EXIT_FAILURE
);
1528 if (argc
-= optind
) {
1529 warnx(_("too many arguments"));
1530 errtryhelp(EXIT_FAILURE
);
1533 if (!ctl
.adj_file_name
)
1534 ctl
.adj_file_name
= _PATH_ADJTIME
;
1536 if (ctl
.update
&& !ctl
.set
&& !ctl
.systohc
) {
1537 warnx(_("--update-drift requires --set or --systohc"));
1541 if (ctl
.noadjfile
&& !ctl
.utc
&& !ctl
.local_opt
) {
1542 warnx(_("With --noadjfile, you must specify "
1543 "either --utc or --localtime"));
1547 if (ctl
.set
|| ctl
.predict
) {
1548 if (!ctl
.date_opt
) {
1549 warnx(_("--date is required for --set or --predict"));
1552 #ifdef USE_HWCLOCK_GPLv3_DATETIME
1553 /* date(1) compatible GPLv3 parser */
1554 struct timespec when
= { 0 };
1556 if (parse_date(&when
, ctl
.date_opt
, NULL
))
1557 set_time
= when
.tv_sec
;
1559 /* minimalistic GPLv2 based parser */
1562 if (parse_timestamp(ctl
.date_opt
, &usec
) == 0)
1563 set_time
= (time_t) (usec
/ 1000000);
1566 warnx(_("invalid date '%s'"), ctl
.date_opt
);
1572 if (ctl
.param_get_option
|| ctl
.param_set_option
) {
1573 if (manipulate_rtc_param(&ctl
))
1574 hwclock_exit(&ctl
, EXIT_FAILURE
);
1576 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1579 if (ctl
.vl_read
|| ctl
.vl_clear
) {
1580 if (manipulate_rtc_voltage_low(&ctl
))
1581 hwclock_exit(&ctl
, EXIT_FAILURE
);
1583 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1587 #if defined(__linux__) && defined(__alpha__)
1588 if (ctl
.getepoch
|| ctl
.setepoch
) {
1589 manipulate_epoch(&ctl
);
1590 hwclock_exit(&ctl
, EXIT_SUCCESS
);
1596 printf(_("System Time: %"PRId64
".%06"PRId64
"\n"),
1597 (int64_t)startup_time
.tv_sec
, (int64_t)startup_time
.tv_usec
);
1600 if (!ctl
.systz
&& !ctl
.predict
)
1601 determine_clock_access_method(&ctl
);
1603 if (!ctl
.noadjfile
&& !(ctl
.systz
&& (ctl
.utc
|| ctl
.local_opt
))) {
1604 if ((rc
= read_adjtime(&ctl
, &adjtime
)) != 0)
1605 hwclock_exit(&ctl
, rc
);
1607 /* Avoid writing adjtime file if we don't have to. */
1610 ctl
.universal
= hw_clock_is_utc(&ctl
, &adjtime
);
1611 rc
= manipulate_clock(&ctl
, set_time
, startup_time
, &adjtime
);
1613 puts(_("Test mode: nothing was changed."));
1614 hwclock_exit(&ctl
, rc
);
1615 return rc
; /* Not reached */
1619 hwclock_exit(const struct hwclock_control
*ctl
1620 #ifndef HAVE_LIBAUDIT
1621 __attribute__((__unused__
))
1625 #ifdef HAVE_LIBAUDIT
1626 if (ctl
->hwaudit_on
&& !ctl
->testing
) {
1627 audit_log_user_message(hwaudit_fd
, AUDIT_USYS_CONFIG
,
1628 "op=change-system-time", NULL
, NULL
, NULL
,
1629 status
== EXIT_SUCCESS
? 1 : 0);
1637 * History of this program:
1639 * 98.08.12 BJH Version 2.4
1641 * Don't use century byte from Hardware Clock. Add comments telling why.
1643 * 98.06.20 BJH Version 2.3.
1645 * Make --hctosys set the kernel timezone from TZ environment variable
1646 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1648 * 98.03.05 BJH. Version 2.2.
1650 * Add --getepoch and --setepoch.
1652 * Fix some word length things so it works on Alpha.
1654 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1655 * case, busywait for the top of a second instead of blocking and waiting
1656 * for the update complete interrupt.
1658 * Fix a bunch of bugs too numerous to mention.
1660 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1661 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1662 * job (jei@iclnl.icl.nl).
1664 * Use the rtc clock access method in preference to the KDGHWCLK method.
1665 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1667 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1668 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1669 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1670 * and wrote feature test code to detect absence of rtc headers.
1672 ***************************************************************************
1675 * To compile this, you must use GNU compiler optimization (-O option) in
1676 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1677 * compile. If you don't optimize, which means the compiler will generate no
1678 * inline functions, the references to these functions in this program will
1679 * be compiled as external references. Since you probably won't be linking
1680 * with any functions by these names, you will have unresolved external
1681 * references when you link.
1683 * Here's some info on how we must deal with the time that elapses while
1684 * this program runs: There are two major delays as we run:
1686 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1687 * we are synchronized to the Hardware Clock.
1688 * 2) Running the "date" program to interpret the value of our --date
1691 * Reading the /etc/adjtime file is the next biggest source of delay and
1694 * The user wants to know what time it was at the moment they invoked us, not
1695 * some arbitrary time later. And in setting the clock, they are giving us the
1696 * time at the moment we are invoked, so if we set the clock some time
1697 * later, we have to add some time to that.
1699 * So we check the system time as soon as we start up, then run "date" and
1700 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1701 * edge, then check the system time again to see how much time we spent. We
1702 * immediately read the clock then and (if appropriate) report that time,
1703 * and additionally, the delay we measured.
1705 * If we're setting the clock to a time given by the user, we wait some more
1706 * so that the total delay is an integral number of seconds, then set the
1707 * Hardware Clock to the time the user requested plus that integral number
1708 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1710 * If we're setting the clock to the system clock value, we wait for the
1711 * system clock to reach the top of a second, and then set the Hardware
1712 * Clock to the system clock's value.
1714 * Here's an interesting point about setting the Hardware Clock: On my
1715 * machine, when you set it, it sets to that precise time. But one can
1716 * imagine another clock whose update oscillator marches on a steady one
1717 * second period, so updating the clock between any two oscillator ticks is
1718 * the same as updating it right at the earlier tick. To avoid any
1719 * complications that might cause, we set the clock as soon as possible
1720 * after an oscillator tick.
1722 * About synchronizing to the Hardware Clock when reading the time: The
1723 * precision of the Hardware Clock counters themselves is one second. You
1724 * can't read the counters and find out that is 12:01:02.5. But if you
1725 * consider the location in time of the counter's ticks as part of its
1726 * value, then its precision is as infinite as time is continuous! What I'm
1727 * saying is this: To find out the _exact_ time in the hardware clock, we
1728 * wait until the next clock tick (the next time the second counter changes)
1729 * and measure how long we had to wait. We then read the value of the clock
1730 * counters and subtract the wait time and we know precisely what time it
1731 * was when we set out to query the time.
1733 * hwclock uses this method, and considers the Hardware Clock to have
1734 * infinite precision.