4 * clock.c was written by Charles Hedrick, hedrick@cs.rutgers.edu, Apr 1992
5 * Modified for clock adjustments - Rob Hooft <hooft@chem.ruu.nl>, Nov 1992
6 * Improvements by Harald Koenig <koenig@nova.tat.physik.uni-tuebingen.de>
7 * and Alan Modra <alan@spri.levels.unisa.edu.au>.
9 * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19.
10 * The new program is called hwclock. New features:
12 * - You can set the hardware clock without also modifying the system
14 * - You can read and set the clock with finer than 1 second precision.
15 * - When you set the clock, hwclock automatically refigures the drift
16 * rate, based on how far off the clock was before you set it.
18 * Reshuffled things, added sparc code, and re-added alpha stuff
19 * by David Mosberger <davidm@azstarnet.com>
20 * and Jay Estabrook <jestabro@amt.tay1.dec.com>
21 * and Martin Ostermann <ost@coments.rwth-aachen.de>, aeb@cwi.nl, 990212.
23 * Fix for Award 2094 bug, Dave Coffin (dcoffin@shore.net) 11/12/98
24 * Change of local time handling, Stefan Ring <e9725446@stud3.tuwien.ac.at>
25 * Change of adjtime handling, James P. Rutledge <ao112@rgfn.epcc.edu>.
27 * Distributed under GPL
30 * Explanation of `adjusting' (Rob Hooft):
32 * The problem with my machine is that its CMOS clock is 10 seconds
33 * per day slow. With this version of clock.c, and my '/etc/rc.local'
34 * reading '/etc/clock -au' instead of '/etc/clock -u -s', this error
35 * is automatically corrected at every boot.
37 * To do this job, the program reads and writes the file '/etc/adjtime'
38 * to determine the correction, and to save its data. In this file are
41 * 1) the correction in seconds per day. (So if your clock runs 5
42 * seconds per day fast, the first number should read -5.0)
43 * 2) the number of seconds since 1/1/1970 the last time the program
45 * 3) the remaining part of a second which was leftover after the last
48 * Installation and use of this program:
50 * a) create a file '/etc/adjtime' containing as the first and only
52 * b) run 'clock -au' or 'clock -a', depending on whether your cmos is
53 * in universal or local time. This updates the second number.
54 * c) set your system time using the 'date' command.
55 * d) update your cmos time using 'clock -wu' or 'clock -w'
56 * e) replace the first number in /etc/adjtime by your correction.
57 * f) put the command 'clock -au' or 'clock -a' in your '/etc/rc.local'
74 #define OPTUTILS_EXIT_CODE EX_USAGE
77 #include "closestream.h"
80 #include "pathnames.h"
83 #include "timeutils.h"
89 static int hwaudit_fd
= -1;
92 /* The struct that holds our hardware access routines */
93 static struct clock_ops
*ur
;
95 /* Maximal clock adjustment in seconds per day.
96 (adjtime() glibc call has 2145 seconds limit on i386, so it is good enough for us as well,
97 43219 is a maximal safe value preventing exact_adjustment overflow.) */
98 #define MAX_DRIFT 2145.0
102 * This is information we keep in the adjtime file that tells us how
103 * to do drift corrections. Elements are all straight from the
104 * adjtime file, so see documentation of that file for details.
105 * Exception is <dirty>, which is an indication that what's in this
106 * structure is not what's in the disk file (because it has been
107 * updated since read from the disk file).
112 time_t last_adj_time
;
115 time_t last_calib_time
;
117 * The most recent time that we set the clock from an external
118 * authority (as opposed to just doing a drift adjustment)
121 enum a_local_utc
{ UTC
= 0, LOCAL
, UNKNOWN
} local_utc
;
123 * To which time zone, local or UTC, we most recently set the
129 * Almost all Award BIOS's made between 04/26/94 and 05/31/95 have a nasty
130 * bug limiting the RTC year byte to the range 94-99. Any year between 2000
131 * and 2093 gets changed to 2094, every time you start the system.
133 * With the --badyear option, we write the date to file and hope that the
134 * file is updated at least once a year. I recommend putting this command
135 * "hwclock --badyear" in the monthly crontab, just to be safe.
137 * -- Dave Coffin 11/12/98
139 static void write_date_to_file(struct tm
*tm
)
143 if ((fp
= fopen(_PATH_LASTDATE
, "w"))) {
144 fprintf(fp
, "%02d.%02d.%04d\n", tm
->tm_mday
, tm
->tm_mon
+ 1,
146 if (close_stream(fp
) != 0)
147 warn(_("cannot write %s"), _PATH_LASTDATE
);
149 warn(_("cannot write %s"), _PATH_LASTDATE
);
152 static void read_date_from_file(struct tm
*tm
)
154 int last_mday
, last_mon
, last_year
;
157 if ((fp
= fopen(_PATH_LASTDATE
, "r"))) {
158 if (fscanf(fp
, "%d.%d.%d\n", &last_mday
, &last_mon
, &last_year
)
160 tm
->tm_year
= last_year
- 1900;
161 if ((tm
->tm_mon
<< 5) + tm
->tm_mday
<
162 ((last_mon
- 1) << 5) + last_mday
)
167 write_date_to_file(tm
);
171 * time_t to timeval conversion.
173 static struct timeval
t2tv(time_t timet
)
175 struct timeval rettimeval
;
177 rettimeval
.tv_sec
= timet
;
178 rettimeval
.tv_usec
= 0;
183 * The difference in seconds between two times in "timeval" format.
185 double time_diff(struct timeval subtrahend
, struct timeval subtractor
)
187 return (subtrahend
.tv_sec
- subtractor
.tv_sec
)
188 + (subtrahend
.tv_usec
- subtractor
.tv_usec
) / 1E6
;
192 * The time, in "timeval" format, which is <increment> seconds after the
193 * time <addend>. Of course, <increment> may be negative.
195 static struct timeval
time_inc(struct timeval addend
, double increment
)
197 struct timeval newtime
;
199 newtime
.tv_sec
= addend
.tv_sec
+ (int)increment
;
200 newtime
.tv_usec
= addend
.tv_usec
+ (increment
- (int)increment
) * 1E6
;
203 * Now adjust it so that the microsecond value is between 0 and 1
206 if (newtime
.tv_usec
< 0) {
207 newtime
.tv_usec
+= 1E6
;
209 } else if (newtime
.tv_usec
>= 1E6
) {
210 newtime
.tv_usec
-= 1E6
;
217 hw_clock_is_utc(const struct hwclock_control
*ctl
,
218 const struct adjtime adjtime
)
223 ret
= TRUE
; /* --utc explicitly given on command line */
224 else if (ctl
->local_opt
)
225 ret
= FALSE
; /* --localtime explicitly given */
227 /* get info from adjtime file - default is UTC */
228 ret
= (adjtime
.local_utc
!= LOCAL
);
230 printf(_("Assuming hardware clock is kept in %s time.\n"),
231 ret
? _("UTC") : _("local"));
236 * Read the adjustment parameters out of the /etc/adjtime file.
238 * Return them as the adjtime structure <*adjtime_p>. If there is no
239 * /etc/adjtime file, return defaults. If values are missing from the file,
240 * return defaults for them.
242 * return value 0 if all OK, !=0 otherwise.
244 static int read_adjtime(const struct hwclock_control
*ctl
,
245 struct adjtime
*adjtime_p
)
248 char line1
[81]; /* String: first line of adjtime file */
249 char line2
[81]; /* String: second line of adjtime file */
250 char line3
[81]; /* String: third line of adjtime file */
252 if (access(ctl
->adj_file_name
, R_OK
) != 0)
255 adjfile
= fopen(ctl
->adj_file_name
, "r"); /* open file for reading */
256 if (adjfile
== NULL
) {
257 warn(_("cannot open %s"), ctl
->adj_file_name
);
261 if (!fgets(line1
, sizeof(line1
), adjfile
))
262 line1
[0] = '\0'; /* In case fgets fails */
263 if (!fgets(line2
, sizeof(line2
), adjfile
))
264 line2
[0] = '\0'; /* In case fgets fails */
265 if (!fgets(line3
, sizeof(line3
), adjfile
))
266 line3
[0] = '\0'; /* In case fgets fails */
270 sscanf(line1
, "%lf %ld %lf",
271 &adjtime_p
->drift_factor
,
272 &adjtime_p
->last_adj_time
,
273 &adjtime_p
->not_adjusted
);
275 sscanf(line2
, "%ld", &adjtime_p
->last_calib_time
);
277 if (!strcmp(line3
, "UTC\n")) {
278 adjtime_p
->local_utc
= UTC
;
279 } else if (!strcmp(line3
, "LOCAL\n")) {
280 adjtime_p
->local_utc
= LOCAL
;
282 adjtime_p
->local_utc
= UNKNOWN
;
284 warnx(_("Warning: unrecognized third line in adjtime file\n"
285 "(Expected: `UTC' or `LOCAL' or nothing.)"));
291 ("Last drift adjustment done at %ld seconds after 1969\n"),
292 (long)adjtime_p
->last_adj_time
);
293 printf(_("Last calibration done at %ld seconds after 1969\n"),
294 (long)adjtime_p
->last_calib_time
);
295 printf(_("Hardware clock is on %s time\n"),
296 (adjtime_p
->local_utc
==
297 LOCAL
) ? _("local") : (adjtime_p
->local_utc
==
298 UTC
) ? _("UTC") : _("unknown"));
305 * Wait until the falling edge of the Hardware Clock's update flag so that
306 * any time that is read from the clock immediately after we return will be
309 * The clock only has 1 second precision, so it gives the exact time only
310 * once per second, right on the falling edge of the update flag.
312 * We wait (up to one second) either blocked waiting for an rtc device or in
313 * a CPU spin loop. The former is probably not very accurate.
315 * Return 0 if it worked, nonzero if it didn't.
317 static int synchronize_to_clock_tick(const struct hwclock_control
*ctl
)
322 printf(_("Waiting for clock tick...\n"));
324 rc
= ur
->synchronize_to_clock_tick(ctl
);
328 printf(_("...synchronization failed\n"));
330 printf(_("...got clock tick\n"));
337 * Convert a time in broken down format (hours, minutes, etc.) into standard
338 * unix time (seconds into epoch). Return it as *systime_p.
340 * The broken down time is argument <tm>. This broken down time is either
341 * in local time zone or UTC, depending on value of logical argument
342 * "universal". True means it is in UTC.
344 * If the argument contains values that do not constitute a valid time, and
345 * mktime() recognizes this, return *valid_p == false and *systime_p
346 * undefined. However, mktime() sometimes goes ahead and computes a
347 * fictional time "as if" the input values were valid, e.g. if they indicate
348 * the 31st day of April, mktime() may compute the time of May 1. In such a
349 * case, we return the same fictional value mktime() does as *systime_p and
350 * return *valid_p == true.
353 mktime_tz(const struct hwclock_control
*ctl
, struct tm tm
,
354 bool *valid_p
, time_t *systime_p
)
357 *systime_p
= timegm(&tm
);
359 *systime_p
= mktime(&tm
);
360 if (*systime_p
== -1) {
362 * This apparently (not specified in mktime() documentation)
363 * means the 'tm' structure does not contain valid values
364 * (however, not containing valid values does _not_ imply
365 * mktime() returns -1).
369 printf(_("Invalid values in hardware clock: "
370 "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"),
371 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
,
372 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
377 ("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
378 "%ld seconds since 1969\n"), tm
.tm_year
+ 1900,
379 tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
, tm
.tm_min
,
380 tm
.tm_sec
, (long)*systime_p
);
385 * Read the hardware clock and return the current time via <tm> argument.
387 * Use the method indicated by <method> argument to access the hardware
391 read_hardware_clock(const struct hwclock_control
*ctl
,
392 bool * valid_p
, time_t *systime_p
)
397 err
= ur
->read_hardware_clock(ctl
, &tm
);
402 read_date_from_file(&tm
);
406 ("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
407 tm
.tm_year
+ 1900, tm
.tm_mon
+ 1, tm
.tm_mday
, tm
.tm_hour
,
408 tm
.tm_min
, tm
.tm_sec
);
409 mktime_tz(ctl
, tm
, valid_p
, systime_p
);
415 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
416 * according to <universal>.
419 set_hardware_clock(const struct hwclock_control
*ctl
, const time_t newtime
)
421 struct tm new_broken_time
;
423 * Time to which we will set Hardware Clock, in broken down format,
424 * in the time zone of caller's choice
428 new_broken_time
= *gmtime(&newtime
);
430 new_broken_time
= *localtime(&newtime
);
433 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
434 "= %ld seconds since 1969\n"),
435 new_broken_time
.tm_hour
, new_broken_time
.tm_min
,
436 new_broken_time
.tm_sec
, (long)newtime
);
439 printf(_("Clock not changed - testing only.\n"));
443 * Write the real year to a file, then write a fake
444 * year between 1995 and 1998 to the RTC. This way,
445 * Award BIOS boots on 29 Feb 2000 thinking that
448 write_date_to_file(&new_broken_time
);
449 new_broken_time
.tm_year
=
450 95 + ((new_broken_time
.tm_year
+ 1) & 3);
452 ur
->set_hardware_clock(ctl
, &new_broken_time
);
457 * Set the Hardware Clock to the time "sethwtime", in local time zone or
458 * UTC, according to "universal".
460 * Wait for a fraction of a second so that "sethwtime" is the value of the
461 * Hardware Clock as of system time "refsystime", which is in the past. For
462 * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and
463 * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2
464 * seconds since "refsystime") and then set the Hardware Clock to 14:03:07,
465 * thus getting a precise and retroactive setting of the clock.
467 * (Don't be confused by the fact that the system clock and the Hardware
468 * Clock differ by two hours in the above example. That's just to remind you
469 * that there are two independent time scales here).
471 * This function ought to be able to accept set times as fractional times.
472 * Idea for future enhancement.
475 set_hardware_clock_exact(const struct hwclock_control
*ctl
,
476 const time_t sethwtime
,
477 const struct timeval refsystime
)
480 * The Hardware Clock can only be set to any integer time plus one
481 * half second. The integer time is required because there is no
482 * interface to set or get a fractional second. The additional half
483 * second is because the Hardware Clock updates to the following
484 * second precisely 500 ms (not 1 second!) after you release the
485 * divider reset (after setting the new time) - see description of
486 * DV2, DV1, DV0 in Register A in the MC146818A data sheet (and note
487 * that although that document doesn't say so, real-world code seems
488 * to expect that the SET bit in Register B functions the same way).
489 * That means that, e.g., when you set the clock to 1:02:03, it
490 * effectively really sets it to 1:02:03.5, because it will update to
491 * 1:02:04 only half a second later. Our caller passes the desired
492 * integer Hardware Clock time in sethwtime, and the corresponding
493 * system time (which may have a fractional part, and which may or may
494 * not be the same!) in refsystime. In an ideal situation, we would
495 * then apply sethwtime to the Hardware Clock at refsystime+500ms, so
496 * that when the Hardware Clock ticks forward to sethwtime+1s half a
497 * second later at refsystime+1000ms, everything is in sync. So we
498 * spin, waiting for gettimeofday() to return a time at or after that
499 * time (refsystime+500ms) up to a tolerance value, initially 1ms. If
500 * we miss that time due to being preempted for some other process,
501 * then we increase the margin a little bit (initially 1ms, doubling
502 * each time), add 1 second (or more, if needed to get a time that is
503 * in the future) to both the time for which we are waiting and the
504 * time that we will apply to the Hardware Clock, and start waiting
507 * For example, the caller requests that we set the Hardware Clock to
508 * 1:02:03, with reference time (current system time) = 6:07:08.250.
509 * We want the Hardware Clock to update to 1:02:04 at 6:07:09.250 on
510 * the system clock, and the first such update will occur 0.500
511 * seconds after we write to the Hardware Clock, so we spin until the
512 * system clock reads 6:07:08.750. If we get there, great, but let's
513 * imagine the system is so heavily loaded that our process is
514 * preempted and by the time we get to run again, the system clock
515 * reads 6:07:11.990. We now want to wait until the next xx:xx:xx.750
516 * time, which is 6:07:12.750 (4.5 seconds after the reference time),
517 * at which point we will set the Hardware Clock to 1:02:07 (4 seconds
518 * after the originally requested time). If we do that successfully,
519 * then at 6:07:13.250 (5 seconds after the reference time), the
520 * Hardware Clock will update to 1:02:08 (5 seconds after the
521 * originally requested time), and all is well thereafter.
524 time_t newhwtime
= sethwtime
;
525 double target_time_tolerance_secs
= 0.001; /* initial value */
526 double tolerance_incr_secs
= 0.001; /* initial value */
527 const double RTC_SET_DELAY_SECS
= 0.5; /* 500 ms */
528 const struct timeval RTC_SET_DELAY_TV
= { 0, RTC_SET_DELAY_SECS
* 1E6
};
530 struct timeval targetsystime
;
531 struct timeval nowsystime
;
532 struct timeval prevsystime
= refsystime
;
533 double deltavstarget
;
535 timeradd(&refsystime
, &RTC_SET_DELAY_TV
, &targetsystime
);
540 /* FOR TESTING ONLY: inject random delays of up to 1000ms */
541 if (ctl
->debug
>= 10) {
542 int usec
= random() % 1000000;
543 printf(_("sleeping ~%d usec\n"), usec
);
547 gettimeofday(&nowsystime
, NULL
);
548 deltavstarget
= time_diff(nowsystime
, targetsystime
);
549 ticksize
= time_diff(nowsystime
, prevsystime
);
550 prevsystime
= nowsystime
;
554 printf(_("time jumped backward %.6f seconds "
555 "to %ld.%06ld - retargeting\n"),
556 ticksize
, nowsystime
.tv_sec
,
558 /* The retarget is handled at the end of the loop. */
559 } else if (deltavstarget
< 0) {
560 /* deltavstarget < 0 if current time < target time */
562 printf(_("%ld.%06ld < %ld.%06ld (%.6f)\n"),
565 targetsystime
.tv_sec
,
566 targetsystime
.tv_usec
,
568 continue; /* not there yet - keep spinning */
569 } else if (deltavstarget
<= target_time_tolerance_secs
) {
570 /* Close enough to the target time; done waiting. */
572 } else /* (deltavstarget > target_time_tolerance_secs) */ {
574 * We missed our window. Increase the tolerance and
575 * aim for the next opportunity.
578 printf(_("missed it - %ld.%06ld is too far "
579 "past %ld.%06ld (%.6f > %.6f)\n"),
582 targetsystime
.tv_sec
,
583 targetsystime
.tv_usec
,
585 target_time_tolerance_secs
);
586 target_time_tolerance_secs
+= tolerance_incr_secs
;
587 tolerance_incr_secs
*= 2;
591 * Aim for the same offset (tv_usec) within the second in
592 * either the current second (if that offset hasn't arrived
593 * yet), or the next second.
595 if (nowsystime
.tv_usec
< targetsystime
.tv_usec
)
596 targetsystime
.tv_sec
= nowsystime
.tv_sec
;
598 targetsystime
.tv_sec
= nowsystime
.tv_sec
+ 1;
601 newhwtime
= sethwtime
602 + (int)(time_diff(nowsystime
, refsystime
)
603 - RTC_SET_DELAY_SECS
/* don't count this */
604 + 0.5 /* for rounding */);
606 printf(_("%ld.%06ld is close enough to %ld.%06ld (%.6f < %.6f)\n"
607 "Set RTC to %ld (%ld + %d; refsystime = %ld.%06ld)\n"),
608 nowsystime
.tv_sec
, nowsystime
.tv_usec
,
609 targetsystime
.tv_sec
, targetsystime
.tv_usec
,
610 deltavstarget
, target_time_tolerance_secs
,
611 newhwtime
, sethwtime
,
612 (int)(newhwtime
- sethwtime
),
613 refsystime
.tv_sec
, refsystime
.tv_usec
);
615 set_hardware_clock(ctl
, newhwtime
);
619 * Put the time "hwctime" on standard output in display format. Except if
620 * hclock_valid == false, just tell standard output that we don't know what
624 display_time(const bool hclock_valid
, struct timeval hwctime
)
628 ("The Hardware Clock registers contain values that are "
629 "either invalid (e.g. 50th day of month) or beyond the range "
630 "we can handle (e.g. Year 2095)."));
632 char buf
[ISO_8601_BUFSIZ
];
634 strtimeval_iso(&hwctime
, ISO_8601_DATE
|ISO_8601_TIME
|ISO_8601_DOTUSEC
|
635 ISO_8601_TIMEZONE
|ISO_8601_SPACE
,
642 * Interpret the value of the --date option, which is something like
643 * "13:05:01". In fact, it can be any of the myriad ASCII strings that
644 * specify a time which the "date" program can understand. The date option
645 * value in question is our "dateopt" argument.
647 * The specified time is in the local time zone.
649 * Our output, "*time_p", is a seconds-into-epoch time.
651 * We use the "date" program to interpret the date string. "date" must be
652 * runnable by issuing the command "date" to the /bin/sh shell. That means
653 * in must be in the current PATH.
655 * If anything goes wrong (and many things can), we return code 10
656 * and arbitrary *time_p. Otherwise, return code is 0 and *time_p is valid.
658 static int interpret_date_string(const struct hwclock_control
*ctl
,
659 time_t *const time_p
)
661 FILE *date_child_fp
= NULL
;
662 char *date_command
= NULL
;
663 char *date_resp
= NULL
;
665 const char magic
[] = "seconds-into-epoch=";
667 long seconds_since_epoch
;
669 if (!ctl
->date_opt
) {
670 warnx(_("No --date option specified."));
674 /* Quotes in date_opt would ruin the date command we construct. */
675 if (strchr(ctl
->date_opt
, '"') != NULL
||
676 strchr(ctl
->date_opt
, '`') != NULL
||
677 strchr(ctl
->date_opt
, '$') != NULL
) {
679 ("The value of the --date option is not a valid date.\n"
680 "In particular, it contains illegal character(s)."));
684 xasprintf(&date_command
, "date --date=\"%s\" +%s%%s",
685 ctl
->date_opt
, magic
);
687 printf(_("Issuing date command: %s\n"), date_command
);
689 date_child_fp
= popen(date_command
, "r");
690 if (date_child_fp
== NULL
) {
691 warn(_("Unable to run 'date' program in /bin/sh shell. "
696 if (getline(&date_resp
, &len
, date_child_fp
) < 0) {
697 warn(_("getline() failed"));
701 printf(_("response from date command = %s\n"), date_resp
);
702 if (strncmp(date_resp
, magic
, sizeof(magic
) - 1) != 0) {
703 warnx(_("The date command issued by %s returned "
704 "unexpected results.\n"
705 "The command was:\n %s\n"
706 "The response was:\n %s"),
707 program_invocation_short_name
, date_command
, date_resp
);
711 if (sscanf(date_resp
+ sizeof(magic
) - 1, "%ld", &seconds_since_epoch
) < 1) {
712 warnx(_("The date command issued by %s returned "
713 "something other than an integer where the "
714 "converted time value was expected.\n"
715 "The command was:\n %s\n"
716 "The response was:\n %s\n"),
717 program_invocation_short_name
, date_command
, date_resp
);
720 *time_p
= seconds_since_epoch
;
722 printf(_("date string %s equates to "
723 "%ld seconds since 1969.\n"),
724 ctl
->date_opt
, *time_p
);
730 pclose(date_child_fp
);
736 * Set the System Clock to time 'newtime'.
738 * Also set the kernel time zone value to the value indicated by the TZ
739 * environment variable and/or /usr/lib/zoneinfo/, interpreted as tzset()
740 * would interpret them.
742 * If this is the first call of settimeofday since boot, then this also sets
743 * the kernel variable persistent_clock_is_local so that NTP 11 minute mode
744 * will update the Hardware Clock with the proper timescale. If the Hardware
745 * Clock's timescale configuration is changed then a reboot is required for
746 * persistent_clock_is_local to be updated.
748 * EXCEPT: if hclock_valid is false, just issue an error message saying
749 * there is no valid time in the Hardware Clock to which to set the system
752 * If 'testing' is true, don't actually update anything -- just say we would
756 set_system_clock(const struct hwclock_control
*ctl
, const bool hclock_valid
,
757 const struct timeval newtime
)
763 ("The Hardware Clock does not contain a valid time, so "
764 "we cannot set the System Time from it."));
767 const struct timeval
*tv_null
= NULL
;
772 broken
= localtime(&newtime
.tv_sec
);
773 #ifdef HAVE_TM_GMTOFF
774 minuteswest
= -broken
->tm_gmtoff
/ 60; /* GNU extension */
776 minuteswest
= timezone
/ 60;
777 if (broken
->tm_isdst
)
782 printf(_("Calling settimeofday:\n"));
783 printf(_("\ttv.tv_sec = %ld, tv.tv_usec = %ld\n"),
784 newtime
.tv_sec
, newtime
.tv_usec
);
785 printf(_("\ttz.tz_minuteswest = %d\n"), minuteswest
);
789 ("Not setting system clock because running in test mode.\n"));
792 const struct timezone tz
= { minuteswest
, 0 };
794 /* Set kernel persistent_clock_is_local so that 11 minute
795 * mode does not clobber the Hardware Clock with UTC. This
796 * is only available on first call of settimeofday after boot.
799 rc
= settimeofday(tv_null
, &tz
);
801 rc
= settimeofday(&newtime
, &tz
);
803 if (errno
== EPERM
) {
805 ("Must be superuser to set system clock."));
808 warn(_("settimeofday() failed"));
819 * Reset the System Clock from local time to UTC, based on its current value
820 * and the timezone unless universal is TRUE.
822 * Also set the kernel time zone value to the value indicated by the TZ
823 * environment variable and/or /usr/lib/zoneinfo/, interpreted as tzset()
824 * would interpret them.
826 * If 'testing' is true, don't actually update anything -- just say we would
829 static int set_system_clock_timezone(const struct hwclock_control
*ctl
)
836 gettimeofday(&tv
, NULL
);
838 struct tm broken_time
;
841 broken_time
= *gmtime(&tv
.tv_sec
);
842 strftime(ctime_now
, sizeof(ctime_now
), "%Y/%m/%d %H:%M:%S",
844 printf(_("Current system time: %ld = %s\n"), tv
.tv_sec
,
848 broken
= localtime(&tv
.tv_sec
);
849 #ifdef HAVE_TM_GMTOFF
850 minuteswest
= -broken
->tm_gmtoff
/ 60; /* GNU extension */
852 minuteswest
= timezone
/ 60;
853 if (broken
->tm_isdst
)
858 struct tm broken_time
;
861 gettimeofday(&tv
, NULL
);
863 tv
.tv_sec
+= minuteswest
* 60;
865 broken_time
= *gmtime(&tv
.tv_sec
);
866 strftime(ctime_now
, sizeof(ctime_now
), "%Y/%m/%d %H:%M:%S",
869 printf(_("Calling settimeofday:\n"));
870 printf(_("\tUTC: %s\n"), ctime_now
);
871 printf(_("\ttv.tv_sec = %ld, tv.tv_usec = %ld\n"),
872 tv
.tv_sec
, tv
.tv_usec
);
873 printf(_("\ttz.tz_minuteswest = %d\n"), minuteswest
);
877 ("Not setting system clock because running in test mode.\n"));
880 const struct timezone tz_utc
= { 0, 0 };
881 const struct timezone tz
= { minuteswest
, 0 };
882 const struct timeval
*tv_null
= NULL
;
885 /* The first call to settimeofday after boot will assume the systemtime
886 * is in localtime, and adjust it according to the given timezone to
887 * compensate. If the systemtime is in fact in UTC, then this is wrong
888 * so we first do a dummy call to make sure the time is not shifted.
891 rc
= settimeofday(tv_null
, &tz_utc
);
893 /* Now we set the real timezone. Due to the above dummy call, this will
894 * only warp the systemtime if the RTC is not in UTC. */
896 rc
= settimeofday(tv_null
, &tz
);
899 if (errno
== EPERM
) {
901 ("Must be superuser to set system clock."));
904 warn(_("settimeofday() failed"));
914 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
915 * to facilitate future drift calculations based on this set point.
917 * With the --update-drift option:
918 * Update the drift factor in <*adjtime_p> based on the fact that the
919 * Hardware Clock was just calibrated to <nowtime> and before that was
920 * set to the <hclocktime> time scale.
922 * EXCEPT: if <hclock_valid> is false, assume Hardware Clock was not set
923 * before to anything meaningful and regular adjustments have not been done,
924 * so don't adjust the drift factor.
927 adjust_drift_factor(const struct hwclock_control
*ctl
,
928 struct adjtime
*adjtime_p
,
929 const struct timeval nowtime
,
930 const bool hclock_valid
,
931 const struct timeval hclocktime
)
935 printf(_("Not adjusting drift factor because the "
936 "--update-drift option was not used.\n"));
937 } else if (!hclock_valid
) {
939 printf(_("Not adjusting drift factor because the "
940 "Hardware Clock previously contained "
942 } else if (adjtime_p
->last_calib_time
== 0) {
944 printf(_("Not adjusting drift factor because last "
945 "calibration time is zero,\n"
946 "so history is bad and calibration startover "
948 } else if ((hclocktime
.tv_sec
- adjtime_p
->last_calib_time
) < 4 * 60 * 60) {
950 printf(_("Not adjusting drift factor because it has "
951 "been less than four hours since the last "
955 * At adjustment time we drift correct the hardware clock
956 * according to the contents of the adjtime file and refresh
957 * its last adjusted timestamp.
959 * At calibration time we set the Hardware Clock and refresh
960 * both timestamps in <*adjtime_p>.
962 * Here, with the --update-drift option, we also update the
963 * drift factor in <*adjtime_p>.
965 * Let us do computation in doubles. (Floats almost suffice,
966 * but 195 days + 1 second equals 195 days in floats.)
968 const double sec_per_day
= 24.0 * 60.0 * 60.0;
969 double factor_adjust
;
971 struct timeval last_calib
;
973 last_calib
= t2tv(adjtime_p
->last_calib_time
);
975 * Correction to apply to the current drift factor.
977 * Simplified: uncorrected_drift / days_since_calibration.
979 * hclocktime is fully corrected with the current drift factor.
980 * Its difference from nowtime is the missed drift correction.
982 factor_adjust
= time_diff(nowtime
, hclocktime
) /
983 (time_diff(nowtime
, last_calib
) / sec_per_day
);
985 drift_factor
= adjtime_p
->drift_factor
+ factor_adjust
;
986 if (fabs(drift_factor
) > MAX_DRIFT
) {
988 printf(_("Clock drift factor was calculated as "
990 "It is far too much. Resetting to zero.\n"),
995 printf(_("Clock drifted %f seconds in the past "
996 "%f seconds\nin spite of a drift factor of "
998 "Adjusting drift factor by %f seconds/day\n"),
999 time_diff(nowtime
, hclocktime
),
1000 time_diff(nowtime
, last_calib
),
1001 adjtime_p
->drift_factor
, factor_adjust
);
1004 adjtime_p
->drift_factor
= drift_factor
;
1006 adjtime_p
->last_calib_time
= nowtime
.tv_sec
;
1008 adjtime_p
->last_adj_time
= nowtime
.tv_sec
;
1010 adjtime_p
->not_adjusted
= 0;
1012 adjtime_p
->dirty
= TRUE
;
1016 * Calculate the drift correction currently needed for the
1017 * Hardware Clock based on the last time it was adjusted,
1018 * and the current drift factor, as stored in the adjtime file.
1020 * The total drift adjustment needed is stored at tdrift_p.
1024 calculate_adjustment(const struct hwclock_control
*ctl
,
1025 const double factor
,
1026 const time_t last_time
,
1027 const double not_adjusted
,
1028 const time_t systime
, struct timeval
*tdrift_p
)
1030 double exact_adjustment
;
1033 ((double)(systime
- last_time
)) * factor
/ (24 * 60 * 60)
1035 tdrift_p
->tv_sec
= (time_t) floor(exact_adjustment
);
1036 tdrift_p
->tv_usec
= (exact_adjustment
-
1037 (double)tdrift_p
->tv_sec
) * 1E6
;
1039 printf(P_("Time since last adjustment is %ld second\n",
1040 "Time since last adjustment is %ld seconds\n",
1041 (systime
- last_time
)),
1042 (systime
- last_time
));
1043 printf(_("Calculated Hardware Clock drift is %ld.%06ld seconds\n"),
1044 tdrift_p
->tv_sec
, tdrift_p
->tv_usec
);
1049 * Write the contents of the <adjtime> structure to its disk file.
1051 * But if the contents are clean (unchanged since read from disk), don't
1054 static void save_adjtime(const struct hwclock_control
*ctl
,
1055 const struct adjtime
*adjtime
)
1057 char *content
; /* Stuff to write to disk file */
1061 if (!adjtime
->dirty
)
1064 xasprintf(&content
, "%f %ld %f\n%ld\n%s\n",
1065 adjtime
->drift_factor
,
1066 adjtime
->last_adj_time
,
1067 adjtime
->not_adjusted
,
1068 adjtime
->last_calib_time
,
1069 (adjtime
->local_utc
== LOCAL
) ? "LOCAL" : "UTC");
1073 ("Not updating adjtime file because of testing mode.\n"));
1074 printf(_("Would have written the following to %s:\n%s"),
1075 ctl
->adj_file_name
, content
);
1080 fp
= fopen(ctl
->adj_file_name
, "w");
1082 warn(_("Could not open file with the clock adjustment parameters "
1083 "in it (%s) for writing"), ctl
->adj_file_name
);
1085 } else if (fputs(content
, fp
) < 0 || close_stream(fp
) != 0) {
1086 warn(_("Could not update file with the clock adjustment "
1087 "parameters (%s) in it"), ctl
->adj_file_name
);
1092 warnx(_("Drift adjustment parameters not updated."));
1096 * Do the adjustment requested, by 1) setting the Hardware Clock (if
1097 * necessary), and 2) updating the last-adjusted time in the adjtime
1100 * Do not update anything if the Hardware Clock does not currently present a
1103 * <hclock_valid> means the Hardware Clock contains a valid time.
1105 * <hclocktime> is the drift corrected time read from the Hardware Clock.
1107 * <read_time> was the system time when the <hclocktime> was read, which due
1108 * to computational delay could be a short time ago. It is used to define a
1109 * trigger point for setting the Hardware Clock. The fractional part of the
1110 * Hardware clock set time is subtracted from read_time to 'refer back', or
1111 * delay, the trigger point. Fractional parts must be accounted for in this
1112 * way, because the Hardware Clock can only be set to a whole second.
1114 * <universal>: the Hardware Clock is kept in UTC.
1116 * <testing>: We are running in test mode (no updating of clock).
1120 do_adjustment(const struct hwclock_control
*ctl
, struct adjtime
*adjtime_p
,
1121 const bool hclock_valid
, const struct timeval hclocktime
,
1122 const struct timeval read_time
)
1124 if (!hclock_valid
) {
1125 warnx(_("The Hardware Clock does not contain a valid time, "
1126 "so we cannot adjust it."));
1127 adjtime_p
->last_calib_time
= 0; /* calibration startover is required */
1128 adjtime_p
->last_adj_time
= 0;
1129 adjtime_p
->not_adjusted
= 0;
1130 adjtime_p
->dirty
= TRUE
;
1131 } else if (adjtime_p
->last_adj_time
== 0) {
1133 printf(_("Not setting clock because last adjustment time is zero, "
1134 "so history is bad.\n"));
1135 } else if (fabs(adjtime_p
->drift_factor
) > MAX_DRIFT
) {
1137 printf(_("Not setting clock because drift factor %f is far too high.\n"),
1138 adjtime_p
->drift_factor
);
1140 set_hardware_clock_exact(ctl
, hclocktime
.tv_sec
,
1142 -(hclocktime
.tv_usec
/ 1E6
)));
1143 adjtime_p
->last_adj_time
= hclocktime
.tv_sec
;
1144 adjtime_p
->not_adjusted
= 0;
1145 adjtime_p
->dirty
= TRUE
;
1149 static void determine_clock_access_method(const struct hwclock_control
*ctl
)
1154 ur
= probe_for_cmos_clock();
1157 ur
= probe_for_rtc_clock(ctl
);
1161 puts(ur
->interface_name
);
1165 printf(_("No usable clock interface found.\n"));
1166 warnx(_("Cannot access the Hardware Clock via "
1167 "any known method."));
1169 warnx(_("Use the --debug option to see the "
1170 "details of our search for an access "
1172 hwclock_exit(ctl
, EX_SOFTWARE
);
1177 * Do all the normal work of hwclock - read, set clock, etc.
1179 * Issue output to stdout and error message to stderr where appropriate.
1181 * Return rc == 0 if everything went OK, rc != 0 if not.
1184 manipulate_clock(const struct hwclock_control
*ctl
, const time_t set_time
,
1185 const struct timeval startup_time
, struct adjtime
*adjtime
)
1187 /* The time at which we read the Hardware Clock */
1188 struct timeval read_time
;
1190 * The Hardware Clock gives us a valid time, or at
1191 * least something close enough to fool mktime().
1193 bool hclock_valid
= FALSE
;
1195 * Tick synchronized time read from the Hardware Clock and
1196 * then drift correct for all operations except --show.
1198 struct timeval hclocktime
= { 0, 0 };
1199 /* Total Hardware Clock drift correction needed. */
1200 struct timeval tdrift
;
1201 /* local return code */
1204 if (!ctl
->systz
&& !ctl
->predict
&& ur
->get_permissions())
1207 if ((ctl
->set
|| ctl
->systohc
|| ctl
->adjust
) &&
1208 (adjtime
->local_utc
== UTC
) != ctl
->universal
) {
1209 adjtime
->local_utc
= ctl
->universal
? UTC
: LOCAL
;
1210 adjtime
->dirty
= TRUE
;
1213 if (ctl
->show
|| ctl
->get
|| ctl
->adjust
|| ctl
->hctosys
1214 || (!ctl
->noadjfile
&& !ctl
->systz
&& !ctl
->predict
)) {
1215 /* data from HW-clock are required */
1216 rc
= synchronize_to_clock_tick(ctl
);
1219 * We don't error out if the user is attempting to set the
1220 * RTC and synchronization timeout happens - the RTC could
1221 * be functioning but contain invalid time data so we still
1222 * want to allow a user to set the RTC time.
1224 if (rc
== RTC_BUSYWAIT_FAILED
&& !ctl
->set
&& !ctl
->systohc
)
1226 gettimeofday(&read_time
, NULL
);
1229 * If we can't synchronize to a clock tick,
1230 * we likely can't read from the RTC so
1231 * don't bother reading it again.
1234 rc
= read_hardware_clock(ctl
, &hclock_valid
,
1235 &hclocktime
.tv_sec
);
1236 if (rc
&& !ctl
->set
&& !ctl
->systohc
)
1241 * Calculate Hardware Clock drift for --predict with the user
1242 * supplied --date option time, and with the time read from the
1243 * Hardware Clock for all other operations. Apply drift correction
1244 * to the Hardware Clock time for everything except --show and
1245 * --predict. For --predict negate the drift correction, because we
1246 * want to 'predict' a future Hardware Clock time that includes drift.
1248 hclocktime
= ctl
->predict
? t2tv(set_time
) : hclocktime
;
1249 calculate_adjustment(ctl
, adjtime
->drift_factor
,
1250 adjtime
->last_adj_time
,
1251 adjtime
->not_adjusted
,
1252 hclocktime
.tv_sec
, &tdrift
);
1253 if (!ctl
->show
&& !ctl
->predict
)
1254 hclocktime
= time_inc(tdrift
, hclocktime
.tv_sec
);
1255 if (ctl
->show
|| ctl
->get
) {
1256 display_time(hclock_valid
,
1257 time_inc(hclocktime
, -time_diff
1258 (read_time
, startup_time
)));
1259 } else if (ctl
->set
) {
1260 set_hardware_clock_exact(ctl
, set_time
, startup_time
);
1261 if (!ctl
->noadjfile
)
1262 adjust_drift_factor(ctl
, adjtime
,
1263 time_inc(t2tv(set_time
), time_diff
1264 (read_time
, startup_time
)),
1265 hclock_valid
, hclocktime
);
1266 } else if (ctl
->adjust
) {
1267 if (tdrift
.tv_sec
> 0 || tdrift
.tv_sec
< -1)
1268 do_adjustment(ctl
, adjtime
, hclock_valid
,
1269 hclocktime
, read_time
);
1271 printf(_("Needed adjustment is less than one second, "
1272 "so not setting clock.\n"));
1273 } else if (ctl
->systohc
) {
1274 struct timeval nowtime
, reftime
;
1276 * We can only set_hardware_clock_exact to a
1277 * whole seconds time, so we set it with
1278 * reference to the most recent whole
1281 gettimeofday(&nowtime
, NULL
);
1282 reftime
.tv_sec
= nowtime
.tv_sec
;
1283 reftime
.tv_usec
= 0;
1284 set_hardware_clock_exact(ctl
, (time_t) reftime
.tv_sec
, reftime
);
1285 if (!ctl
->noadjfile
)
1286 adjust_drift_factor(ctl
, adjtime
, nowtime
,
1287 hclock_valid
, hclocktime
);
1288 } else if (ctl
->hctosys
) {
1289 rc
= set_system_clock(ctl
, hclock_valid
, hclocktime
);
1291 printf(_("Unable to set system clock.\n"));
1294 } else if (ctl
->systz
) {
1295 rc
= set_system_clock_timezone(ctl
);
1297 printf(_("Unable to set system clock.\n"));
1300 } else if (ctl
->predict
) {
1301 hclocktime
= time_inc(hclocktime
, (double)
1302 -(tdrift
.tv_sec
+ tdrift
.tv_usec
/ 1E6
));
1305 ("At %ld seconds after 1969, RTC is predicted to read %ld seconds after 1969.\n"),
1306 set_time
, hclocktime
.tv_sec
);
1308 display_time(TRUE
, hclocktime
);
1310 if (!ctl
->noadjfile
)
1311 save_adjtime(ctl
, adjtime
);
1316 * Get or set the Hardware Clock epoch value in the kernel, as appropriate.
1317 * <getepoch>, <setepoch>, and <epoch> are hwclock invocation options.
1319 * <epoch> == -1 if the user did not specify an "epoch" option.
1323 * Maintenance note: This should work on non-Alpha machines, but the
1324 * evidence today (98.03.04) indicates that the kernel only keeps the epoch
1325 * value on Alphas. If that is ever fixed, this function should be changed.
1329 manipulate_epoch(const struct hwclock_control
*ctl
__attribute__((__unused__
)))
1331 warnx(_("The kernel keeps an epoch value for the Hardware Clock "
1332 "only on an Alpha machine.\nThis copy of hwclock was built for "
1333 "a machine other than Alpha\n(and thus is presumably not running "
1334 "on an Alpha now). No action taken."));
1338 manipulate_epoch(const struct hwclock_control
*ctl
)
1340 if (ctl
->getepoch
) {
1341 unsigned long epoch
;
1343 if (get_epoch_rtc(ctl
, &epoch
, 0))
1345 ("Unable to get the epoch value from the kernel."));
1347 printf(_("Kernel is assuming an epoch value of %lu\n"),
1349 } else if (ctl
->setepoch
) {
1350 if (ctl
->epoch_option
== 0)
1352 ("To set the epoch value, you must use the 'epoch' "
1353 "option to tell to what value to set it."));
1354 else if (ctl
->testing
)
1356 ("Not setting the epoch to %lu - testing only.\n"),
1358 else if (set_epoch_rtc(ctl
))
1360 ("Unable to set the epoch value in the kernel.\n"));
1363 # endif /* __alpha__ */
1364 #endif /* __linux__ */
1366 static void out_version(void)
1368 printf(UTIL_LINUX_VERSION
);
1372 * usage - Output (error and) usage information
1374 * This function is called both directly from main to show usage information
1375 * and as fatal function from shhopt if some argument is not understood. In
1376 * case of normal usage info FMT should be NULL. In that case the info is
1377 * printed to stdout. If FMT is given usage will act like fprintf( stderr,
1378 * fmt, ... ), show a usage information and terminate the program
1381 static void usage(const struct hwclock_control
*ctl
, const char *fmt
, ...)
1386 usageto
= fmt
? stderr
: stdout
;
1388 fputs(USAGE_HEADER
, usageto
);
1389 fputs(_(" hwclock [function] [option...]\n"), usageto
);
1391 fputs(USAGE_SEPARATOR
, usageto
);
1392 fputs(_("Query or set the hardware clock.\n"), usageto
);
1394 fputs(_("\nFunctions:\n"), usageto
);
1395 fputs(_(" -h, --help show this help text and exit\n"
1396 " -r, --show read hardware clock and print result\n"
1397 " --get read hardware clock and print drift corrected result\n"
1398 " --set set the RTC to the time given with --date\n"), usageto
);
1399 fputs(_(" -s, --hctosys set the system time from the hardware clock\n"
1400 " -w, --systohc set the hardware clock from the current system time\n"
1401 " --systz set the system time based on the current timezone\n"
1402 " --adjust adjust the RTC to account for systematic drift since\n"
1403 " the clock was last set or adjusted\n"), usageto
);
1405 fputs(_(" --getepoch print out the kernel's hardware clock epoch value\n"
1406 " --setepoch set the kernel's hardware clock epoch value to the \n"
1407 " value given with --epoch\n"), usageto
);
1409 fputs(_(" --predict predict RTC reading at time given with --date\n"
1410 " -V, --version display version information and exit\n"), usageto
);
1412 fputs(USAGE_OPTIONS
, usageto
);
1413 fputs(_(" -u, --utc the hardware clock is kept in UTC\n"
1414 " --localtime the hardware clock is kept in local time\n"), usageto
);
1416 fputs(_(" -f, --rtc <file> special /dev/... file to use instead of default\n"), usageto
);
1419 " --directisa access the ISA bus directly instead of %s\n"
1420 " --badyear ignore RTC's year because the BIOS is broken\n"
1421 " --date <time> specifies the time to which to set the hardware clock\n"
1422 " --epoch <year> specifies the year which is the beginning of the\n"
1423 " hardware clock's epoch value\n"), _PATH_RTC_DEV
);
1425 " --update-drift update drift factor in %1$s (requires\n"
1426 " --set or --systohc)\n"
1427 " --noadjfile do not access %1$s; this requires the use of\n"
1428 " either --utc or --localtime\n"
1429 " --adjfile <file> specifies the path to the adjust file;\n"
1430 " the default is %1$s\n"), _PATH_ADJTIME
);
1431 fputs(_(" --test do not update anything, just show what would happen\n"
1432 " -D, --debug debugging mode\n" "\n"), usageto
);
1434 fputs(_(" -J|--jensen, -A|--arc, -S|--srm, -F|--funky-toy\n"
1435 " tell hwclock the type of Alpha you have (see hwclock(8))\n"
1441 vfprintf(usageto
, fmt
, ap
);
1446 hwclock_exit(ctl
, fmt
? EX_USAGE
: EX_OK
);
1451 * EX_USAGE: bad invocation
1452 * EX_NOPERM: no permission
1453 * EX_OSFILE: cannot open /dev/rtc or /etc/adjtime
1454 * EX_IOERR: ioctl error getting or setting the time
1458 int main(int argc
, char **argv
)
1460 struct hwclock_control ctl
= { NULL
};
1461 struct timeval startup_time
;
1462 struct adjtime adjtime
= { 0 };
1464 * The time we started up, in seconds into the epoch, including
1467 time_t set_time
= 0; /* Time to which user said to set Hardware Clock */
1470 /* Long only options. */
1472 OPT_ADJFILE
= CHAR_MAX
+ 1,
1489 static const struct option longopts
[] = {
1490 { "adjust", no_argument
, NULL
, 'a' },
1491 { "help", no_argument
, NULL
, 'h' },
1492 { "show", no_argument
, NULL
, 'r' },
1493 { "hctosys", no_argument
, NULL
, 's' },
1494 { "utc", no_argument
, NULL
, 'u' },
1495 { "version", no_argument
, NULL
, 'v' },
1496 { "systohc", no_argument
, NULL
, 'w' },
1497 { "debug", no_argument
, NULL
, 'D' },
1499 { "ARC", no_argument
, NULL
, 'A' },
1500 { "arc", no_argument
, NULL
, 'A' },
1501 { "Jensen", no_argument
, NULL
, 'J' },
1502 { "jensen", no_argument
, NULL
, 'J' },
1503 { "SRM", no_argument
, NULL
, 'S' },
1504 { "srm", no_argument
, NULL
, 'S' },
1505 { "funky-toy", no_argument
, NULL
, 'F' },
1507 { "set", no_argument
, NULL
, OPT_SET
},
1509 { "getepoch", no_argument
, NULL
, OPT_GETEPOCH
},
1510 { "setepoch", no_argument
, NULL
, OPT_SETEPOCH
},
1512 { "noadjfile", no_argument
, NULL
, OPT_NOADJFILE
},
1513 { "localtime", no_argument
, NULL
, OPT_LOCALTIME
},
1514 { "badyear", no_argument
, NULL
, OPT_BADYEAR
},
1515 { "directisa", no_argument
, NULL
, OPT_DIRECTISA
},
1516 { "test", no_argument
, NULL
, OPT_TEST
},
1517 { "date", required_argument
, NULL
, OPT_DATE
},
1518 { "epoch", required_argument
, NULL
, OPT_EPOCH
},
1520 { "rtc", required_argument
, NULL
, 'f' },
1522 { "adjfile", required_argument
, NULL
, OPT_ADJFILE
},
1523 { "systz", no_argument
, NULL
, OPT_SYSTZ
},
1524 { "predict-hc", no_argument
, NULL
, OPT_PREDICT_HC
},
1525 { "get", no_argument
, NULL
, OPT_GET
},
1526 { "update-drift", no_argument
, NULL
, OPT_UPDATE
},
1527 { NULL
, 0, NULL
, 0 }
1530 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
1532 OPT_GET
, OPT_GETEPOCH
, OPT_PREDICT_HC
,
1533 OPT_SET
, OPT_SETEPOCH
, OPT_SYSTZ
},
1534 { 'u', OPT_LOCALTIME
},
1535 { OPT_ADJFILE
, OPT_NOADJFILE
},
1536 { OPT_NOADJFILE
, OPT_UPDATE
},
1539 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1541 /* Remember what time we were invoked */
1542 gettimeofday(&startup_time
, NULL
);
1544 #ifdef HAVE_LIBAUDIT
1545 hwaudit_fd
= audit_open();
1546 if (hwaudit_fd
< 0 && !(errno
== EINVAL
|| errno
== EPROTONOSUPPORT
||
1547 errno
== EAFNOSUPPORT
)) {
1549 * You get these error codes only when the kernel doesn't
1550 * have audit compiled in.
1552 warnx(_("Unable to connect to audit system"));
1556 setlocale(LC_ALL
, "");
1559 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1560 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1561 * - gqueri@mail.dotcom.fr
1563 setlocale(LC_NUMERIC
, "C");
1565 bindtextdomain(PACKAGE
, LOCALEDIR
);
1566 textdomain(PACKAGE
);
1567 atexit(close_stdout
);
1569 while ((c
= getopt_long(argc
, argv
,
1570 "?hvVDarsuwAJSFf:", longopts
, NULL
)) != -1) {
1572 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1622 ctl
.local_opt
= 1; /* --localtime */
1631 ctl
.testing
= 1; /* --test */
1634 ctl
.date_opt
= optarg
; /* --date */
1637 ctl
.epoch_option
= /* --epoch */
1638 strtoul_or_err(optarg
, _("invalid epoch argument"));
1641 ctl
.adj_file_name
= optarg
; /* --adjfile */
1644 ctl
.systz
= 1; /* --systz */
1646 case OPT_PREDICT_HC
:
1647 ctl
.predict
= 1; /* --predict-hc */
1650 ctl
.get
= 1; /* --get */
1653 ctl
.update
= 1; /* --update-drift */
1657 ctl
.rtc_dev_name
= optarg
; /* --rtc */
1660 case 'v': /* --version */
1664 case 'h': /* --help */
1674 #ifdef HAVE_LIBAUDIT
1676 if (ctl
.adjust
|| ctl
.hctosys
|| ctl
.systohc
||
1677 ctl
.set
|| ctl
.setepoch
) {
1683 usage(&ctl
, _("%s takes no non-option arguments. "
1684 "You supplied %d.\n"), program_invocation_short_name
,
1688 if (!ctl
.adj_file_name
)
1689 ctl
.adj_file_name
= _PATH_ADJTIME
;
1691 if (ctl
.noadjfile
&& !ctl
.utc
&& !ctl
.local_opt
) {
1692 warnx(_("With --noadjfile, you must specify "
1693 "either --utc or --localtime"));
1694 hwclock_exit(&ctl
, EX_USAGE
);
1697 set_cmos_epoch(&ctl
);
1698 set_cmos_access(&ctl
);
1701 if (ctl
.set
|| ctl
.predict
) {
1702 rc
= interpret_date_string(&ctl
, &set_time
);
1703 /* (time-consuming) */
1705 warnx(_("No usable set-to time. "
1706 "Cannot set clock."));
1707 hwclock_exit(&ctl
, EX_USAGE
);
1711 if (!(ctl
.show
| ctl
.set
| ctl
.systohc
| ctl
.hctosys
|
1712 ctl
.systz
| ctl
.adjust
| ctl
.getepoch
| ctl
.setepoch
|
1713 ctl
.predict
| ctl
.get
))
1714 ctl
.show
= 1; /* default to show */
1717 if (ctl
.getepoch
|| ctl
.setepoch
) {
1718 manipulate_epoch(&ctl
);
1719 hwclock_exit(&ctl
, EX_OK
);
1726 if (!ctl
.systz
&& !ctl
.predict
)
1727 determine_clock_access_method(&ctl
);
1729 if (!ctl
.noadjfile
&& !(ctl
.systz
&& (ctl
.utc
|| ctl
.local_opt
))) {
1730 if ((rc
= read_adjtime(&ctl
, &adjtime
)) != 0)
1731 hwclock_exit(&ctl
, rc
);
1733 /* Avoid writing adjtime file if we don't have to. */
1734 adjtime
.dirty
= FALSE
;
1735 ctl
.universal
= hw_clock_is_utc(&ctl
, adjtime
);
1736 rc
= manipulate_clock(&ctl
, set_time
, startup_time
, &adjtime
);
1737 hwclock_exit(&ctl
, rc
);
1738 return rc
; /* Not reached */
1741 void __attribute__((__noreturn__
))
1742 hwclock_exit(const struct hwclock_control
*ctl
1743 #ifndef HAVE_LIBAUDIT
1744 __attribute__((__unused__
))
1748 #ifdef HAVE_LIBAUDIT
1749 if (ctl
->hwaudit_on
) {
1750 audit_log_user_message(hwaudit_fd
, AUDIT_USYS_CONFIG
,
1751 "op=change-system-time", NULL
, NULL
, NULL
,
1760 * History of this program:
1762 * 98.08.12 BJH Version 2.4
1764 * Don't use century byte from Hardware Clock. Add comments telling why.
1766 * 98.06.20 BJH Version 2.3.
1768 * Make --hctosys set the kernel timezone from TZ environment variable
1769 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1771 * 98.03.05 BJH. Version 2.2.
1773 * Add --getepoch and --setepoch.
1775 * Fix some word length things so it works on Alpha.
1777 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1778 * case, busywait for the top of a second instead of blocking and waiting
1779 * for the update complete interrupt.
1781 * Fix a bunch of bugs too numerous to mention.
1783 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1784 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1785 * job (jei@iclnl.icl.nl).
1787 * Use the rtc clock access method in preference to the KDGHWCLK method.
1788 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1790 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1791 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1792 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1793 * and wrote feature test code to detect absence of rtc headers.
1795 ***************************************************************************
1798 * To compile this, you must use GNU compiler optimization (-O option) in
1799 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1800 * compile. If you don't optimize, which means the compiler will generate no
1801 * inline functions, the references to these functions in this program will
1802 * be compiled as external references. Since you probably won't be linking
1803 * with any functions by these names, you will have unresolved external
1804 * references when you link.
1806 * Here's some info on how we must deal with the time that elapses while
1807 * this program runs: There are two major delays as we run:
1809 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1810 * we are synchronized to the Hardware Clock.
1811 * 2) Running the "date" program to interpret the value of our --date
1814 * Reading the /etc/adjtime file is the next biggest source of delay and
1817 * The user wants to know what time it was at the moment he invoked us, not
1818 * some arbitrary time later. And in setting the clock, he is giving us the
1819 * time at the moment we are invoked, so if we set the clock some time
1820 * later, we have to add some time to that.
1822 * So we check the system time as soon as we start up, then run "date" and
1823 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1824 * edge, then check the system time again to see how much time we spent. We
1825 * immediately read the clock then and (if appropriate) report that time,
1826 * and additionally, the delay we measured.
1828 * If we're setting the clock to a time given by the user, we wait some more
1829 * so that the total delay is an integral number of seconds, then set the
1830 * Hardware Clock to the time the user requested plus that integral number
1831 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1833 * If we're setting the clock to the system clock value, we wait for the
1834 * system clock to reach the top of a second, and then set the Hardware
1835 * Clock to the system clock's value.
1837 * Here's an interesting point about setting the Hardware Clock: On my
1838 * machine, when you set it, it sets to that precise time. But one can
1839 * imagine another clock whose update oscillator marches on a steady one
1840 * second period, so updating the clock between any two oscillator ticks is
1841 * the same as updating it right at the earlier tick. To avoid any
1842 * complications that might cause, we set the clock as soon as possible
1843 * after an oscillator tick.
1845 * About synchronizing to the Hardware Clock when reading the time: The
1846 * precision of the Hardware Clock counters themselves is one second. You
1847 * can't read the counters and find out that is 12:01:02.5. But if you
1848 * consider the location in time of the counter's ticks as part of its
1849 * value, then its precision is as infinite as time is continuous! What I'm
1850 * saying is this: To find out the _exact_ time in the hardware clock, we
1851 * wait until the next clock tick (the next time the second counter changes)
1852 * and measure how long we had to wait. We then read the value of the clock
1853 * counters and subtract the wait time and we know precisely what time it
1854 * was when we set out to query the time.
1856 * hwclock uses this method, and considers the Hardware Clock to have
1857 * infinite precision.