]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/hwclock.c
hwclock: improve audit control
[thirdparty/util-linux.git] / sys-utils / hwclock.c
1 /*
2 * hwclock.c
3 *
4 * clock.c was written by Charles Hedrick, hedrick@cs.rutgers.edu, Apr 1992
5 * Modified for clock adjustments - Rob Hooft <hooft@chem.ruu.nl>, Nov 1992
6 * Improvements by Harald Koenig <koenig@nova.tat.physik.uni-tuebingen.de>
7 * and Alan Modra <alan@spri.levels.unisa.edu.au>.
8 *
9 * Major rewrite by Bryan Henderson <bryanh@giraffe-data.com>, 96.09.19.
10 * The new program is called hwclock. New features:
11 *
12 * - You can set the hardware clock without also modifying the system
13 * clock.
14 * - You can read and set the clock with finer than 1 second precision.
15 * - When you set the clock, hwclock automatically refigures the drift
16 * rate, based on how far off the clock was before you set it.
17 *
18 * Reshuffled things, added sparc code, and re-added alpha stuff
19 * by David Mosberger <davidm@azstarnet.com>
20 * and Jay Estabrook <jestabro@amt.tay1.dec.com>
21 * and Martin Ostermann <ost@coments.rwth-aachen.de>, aeb@cwi.nl, 990212.
22 *
23 * Fix for Award 2094 bug, Dave Coffin (dcoffin@shore.net) 11/12/98
24 * Change of local time handling, Stefan Ring <e9725446@stud3.tuwien.ac.at>
25 * Change of adjtime handling, James P. Rutledge <ao112@rgfn.epcc.edu>.
26 *
27 * Distributed under GPL
28 */
29 /*
30 * Explanation of `adjusting' (Rob Hooft):
31 *
32 * The problem with my machine is that its CMOS clock is 10 seconds
33 * per day slow. With this version of clock.c, and my '/etc/rc.local'
34 * reading '/etc/clock -au' instead of '/etc/clock -u -s', this error
35 * is automatically corrected at every boot.
36 *
37 * To do this job, the program reads and writes the file '/etc/adjtime'
38 * to determine the correction, and to save its data. In this file are
39 * three numbers:
40 *
41 * 1) the correction in seconds per day. (So if your clock runs 5
42 * seconds per day fast, the first number should read -5.0)
43 * 2) the number of seconds since 1/1/1970 the last time the program
44 * was used
45 * 3) the remaining part of a second which was leftover after the last
46 * adjustment
47 *
48 * Installation and use of this program:
49 *
50 * a) create a file '/etc/adjtime' containing as the first and only
51 * line: '0.0 0 0.0'
52 * b) run 'clock -au' or 'clock -a', depending on whether your cmos is
53 * in universal or local time. This updates the second number.
54 * c) set your system time using the 'date' command.
55 * d) update your cmos time using 'clock -wu' or 'clock -w'
56 * e) replace the first number in /etc/adjtime by your correction.
57 * f) put the command 'clock -au' or 'clock -a' in your '/etc/rc.local'
58 */
59
60 #include <errno.h>
61 #include <getopt.h>
62 #include <limits.h>
63 #include <math.h>
64 #include <stdarg.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <sysexits.h>
69 #include <sys/stat.h>
70 #include <sys/time.h>
71 #include <time.h>
72 #include <unistd.h>
73
74 #define OPTUTILS_EXIT_CODE EX_USAGE
75
76 #include "c.h"
77 #include "closestream.h"
78 #include "nls.h"
79 #include "optutils.h"
80 #include "pathnames.h"
81 #include "strutils.h"
82 #include "hwclock.h"
83 #include "timeutils.h"
84 #include "env.h"
85 #include "xalloc.h"
86
87 #ifdef HAVE_LIBAUDIT
88 #include <libaudit.h>
89 static int hwaudit_fd = -1;
90 #endif
91
92 /* The struct that holds our hardware access routines */
93 static struct clock_ops *ur;
94
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
99
100 struct adjtime {
101 /*
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).
108 */
109 bool dirty;
110 /* line 1 */
111 double drift_factor;
112 time_t last_adj_time;
113 double not_adjusted;
114 /* line 2 */
115 time_t last_calib_time;
116 /*
117 * The most recent time that we set the clock from an external
118 * authority (as opposed to just doing a drift adjustment)
119 */
120 /* line 3 */
121 enum a_local_utc { UTC = 0, LOCAL, UNKNOWN } local_utc;
122 /*
123 * To which time zone, local or UTC, we most recently set the
124 * hardware clock.
125 */
126 };
127
128 /*
129 * time_t to timeval conversion.
130 */
131 static struct timeval t2tv(time_t timet)
132 {
133 struct timeval rettimeval;
134
135 rettimeval.tv_sec = timet;
136 rettimeval.tv_usec = 0;
137 return rettimeval;
138 }
139
140 /*
141 * The difference in seconds between two times in "timeval" format.
142 */
143 double time_diff(struct timeval subtrahend, struct timeval subtractor)
144 {
145 return (subtrahend.tv_sec - subtractor.tv_sec)
146 + (subtrahend.tv_usec - subtractor.tv_usec) / 1E6;
147 }
148
149 /*
150 * The time, in "timeval" format, which is <increment> seconds after the
151 * time <addend>. Of course, <increment> may be negative.
152 */
153 static struct timeval time_inc(struct timeval addend, double increment)
154 {
155 struct timeval newtime;
156
157 newtime.tv_sec = addend.tv_sec + (int)increment;
158 newtime.tv_usec = addend.tv_usec + (increment - (int)increment) * 1E6;
159
160 /*
161 * Now adjust it so that the microsecond value is between 0 and 1
162 * million.
163 */
164 if (newtime.tv_usec < 0) {
165 newtime.tv_usec += 1E6;
166 newtime.tv_sec -= 1;
167 } else if (newtime.tv_usec >= 1E6) {
168 newtime.tv_usec -= 1E6;
169 newtime.tv_sec += 1;
170 }
171 return newtime;
172 }
173
174 static bool
175 hw_clock_is_utc(const struct hwclock_control *ctl,
176 const struct adjtime adjtime)
177 {
178 bool ret;
179
180 if (ctl->utc)
181 ret = TRUE; /* --utc explicitly given on command line */
182 else if (ctl->local_opt)
183 ret = FALSE; /* --localtime explicitly given */
184 else
185 /* get info from adjtime file - default is UTC */
186 ret = (adjtime.local_utc != LOCAL);
187 if (ctl->debug)
188 printf(_("Assuming hardware clock is kept in %s time.\n"),
189 ret ? _("UTC") : _("local"));
190 return ret;
191 }
192
193 /*
194 * Read the adjustment parameters out of the /etc/adjtime file.
195 *
196 * Return them as the adjtime structure <*adjtime_p>. If there is no
197 * /etc/adjtime file, return defaults. If values are missing from the file,
198 * return defaults for them.
199 *
200 * return value 0 if all OK, !=0 otherwise.
201 */
202 static int read_adjtime(const struct hwclock_control *ctl,
203 struct adjtime *adjtime_p)
204 {
205 FILE *adjfile;
206 char line1[81]; /* String: first line of adjtime file */
207 char line2[81]; /* String: second line of adjtime file */
208 char line3[81]; /* String: third line of adjtime file */
209
210 if (access(ctl->adj_file_name, R_OK) != 0)
211 return 0;
212
213 adjfile = fopen(ctl->adj_file_name, "r"); /* open file for reading */
214 if (adjfile == NULL) {
215 warn(_("cannot open %s"), ctl->adj_file_name);
216 return EX_OSFILE;
217 }
218
219 if (!fgets(line1, sizeof(line1), adjfile))
220 line1[0] = '\0'; /* In case fgets fails */
221 if (!fgets(line2, sizeof(line2), adjfile))
222 line2[0] = '\0'; /* In case fgets fails */
223 if (!fgets(line3, sizeof(line3), adjfile))
224 line3[0] = '\0'; /* In case fgets fails */
225
226 fclose(adjfile);
227
228 sscanf(line1, "%lf %ld %lf",
229 &adjtime_p->drift_factor,
230 &adjtime_p->last_adj_time,
231 &adjtime_p->not_adjusted);
232
233 sscanf(line2, "%ld", &adjtime_p->last_calib_time);
234
235 if (!strcmp(line3, "UTC\n")) {
236 adjtime_p->local_utc = UTC;
237 } else if (!strcmp(line3, "LOCAL\n")) {
238 adjtime_p->local_utc = LOCAL;
239 } else {
240 adjtime_p->local_utc = UNKNOWN;
241 if (line3[0]) {
242 warnx(_("Warning: unrecognized third line in adjtime file\n"
243 "(Expected: `UTC' or `LOCAL' or nothing.)"));
244 }
245 }
246
247 if (ctl->debug) {
248 printf(_
249 ("Last drift adjustment done at %ld seconds after 1969\n"),
250 (long)adjtime_p->last_adj_time);
251 printf(_("Last calibration done at %ld seconds after 1969\n"),
252 (long)adjtime_p->last_calib_time);
253 printf(_("Hardware clock is on %s time\n"),
254 (adjtime_p->local_utc ==
255 LOCAL) ? _("local") : (adjtime_p->local_utc ==
256 UTC) ? _("UTC") : _("unknown"));
257 }
258
259 return 0;
260 }
261
262 /*
263 * Wait until the falling edge of the Hardware Clock's update flag so that
264 * any time that is read from the clock immediately after we return will be
265 * exact.
266 *
267 * The clock only has 1 second precision, so it gives the exact time only
268 * once per second, right on the falling edge of the update flag.
269 *
270 * We wait (up to one second) either blocked waiting for an rtc device or in
271 * a CPU spin loop. The former is probably not very accurate.
272 *
273 * Return 0 if it worked, nonzero if it didn't.
274 */
275 static int synchronize_to_clock_tick(const struct hwclock_control *ctl)
276 {
277 int rc;
278
279 if (ctl->debug)
280 printf(_("Waiting for clock tick...\n"));
281
282 rc = ur->synchronize_to_clock_tick(ctl);
283
284 if (ctl->debug) {
285 if (rc)
286 printf(_("...synchronization failed\n"));
287 else
288 printf(_("...got clock tick\n"));
289 }
290
291 return rc;
292 }
293
294 /*
295 * Convert a time in broken down format (hours, minutes, etc.) into standard
296 * unix time (seconds into epoch). Return it as *systime_p.
297 *
298 * The broken down time is argument <tm>. This broken down time is either
299 * in local time zone or UTC, depending on value of logical argument
300 * "universal". True means it is in UTC.
301 *
302 * If the argument contains values that do not constitute a valid time, and
303 * mktime() recognizes this, return *valid_p == false and *systime_p
304 * undefined. However, mktime() sometimes goes ahead and computes a
305 * fictional time "as if" the input values were valid, e.g. if they indicate
306 * the 31st day of April, mktime() may compute the time of May 1. In such a
307 * case, we return the same fictional value mktime() does as *systime_p and
308 * return *valid_p == true.
309 */
310 static void
311 mktime_tz(const struct hwclock_control *ctl, struct tm tm,
312 bool *valid_p, time_t *systime_p)
313 {
314 if (ctl->universal)
315 *systime_p = timegm(&tm);
316 else
317 *systime_p = mktime(&tm);
318 if (*systime_p == -1) {
319 /*
320 * This apparently (not specified in mktime() documentation)
321 * means the 'tm' structure does not contain valid values
322 * (however, not containing valid values does _not_ imply
323 * mktime() returns -1).
324 */
325 *valid_p = FALSE;
326 if (ctl->debug)
327 printf(_("Invalid values in hardware clock: "
328 "%4d/%.2d/%.2d %.2d:%.2d:%.2d\n"),
329 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
330 tm.tm_hour, tm.tm_min, tm.tm_sec);
331 } else {
332 *valid_p = TRUE;
333 if (ctl->debug)
334 printf(_
335 ("Hw clock time : %4d/%.2d/%.2d %.2d:%.2d:%.2d = "
336 "%ld seconds since 1969\n"), tm.tm_year + 1900,
337 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min,
338 tm.tm_sec, (long)*systime_p);
339 }
340 }
341
342 /*
343 * Read the hardware clock and return the current time via <tm> argument.
344 *
345 * Use the method indicated by <method> argument to access the hardware
346 * clock.
347 */
348 static int
349 read_hardware_clock(const struct hwclock_control *ctl,
350 bool * valid_p, time_t *systime_p)
351 {
352 struct tm tm;
353 int err;
354
355 err = ur->read_hardware_clock(ctl, &tm);
356 if (err)
357 return err;
358
359 if (ctl->debug)
360 printf(_
361 ("Time read from Hardware Clock: %4d/%.2d/%.2d %02d:%02d:%02d\n"),
362 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
363 tm.tm_min, tm.tm_sec);
364 mktime_tz(ctl, tm, valid_p, systime_p);
365
366 return 0;
367 }
368
369 /*
370 * Set the Hardware Clock to the time <newtime>, in local time zone or UTC,
371 * according to <universal>.
372 */
373 static void
374 set_hardware_clock(const struct hwclock_control *ctl, const time_t newtime)
375 {
376 struct tm new_broken_time;
377 /*
378 * Time to which we will set Hardware Clock, in broken down format,
379 * in the time zone of caller's choice
380 */
381
382 if (ctl->universal)
383 new_broken_time = *gmtime(&newtime);
384 else
385 new_broken_time = *localtime(&newtime);
386
387 if (ctl->debug)
388 printf(_("Setting Hardware Clock to %.2d:%.2d:%.2d "
389 "= %ld seconds since 1969\n"),
390 new_broken_time.tm_hour, new_broken_time.tm_min,
391 new_broken_time.tm_sec, (long)newtime);
392
393 if (ctl->testing)
394 printf(_("Clock not changed - testing only.\n"));
395 else {
396 ur->set_hardware_clock(ctl, &new_broken_time);
397 }
398 }
399
400 /*
401 * Set the Hardware Clock to the time "sethwtime", in local time zone or
402 * UTC, according to "universal".
403 *
404 * Wait for a fraction of a second so that "sethwtime" is the value of the
405 * Hardware Clock as of system time "refsystime", which is in the past. For
406 * example, if "sethwtime" is 14:03:05 and "refsystime" is 12:10:04.5 and
407 * the current system time is 12:10:06.0: Wait .5 seconds (to make exactly 2
408 * seconds since "refsystime") and then set the Hardware Clock to 14:03:07,
409 * thus getting a precise and retroactive setting of the clock.
410 *
411 * (Don't be confused by the fact that the system clock and the Hardware
412 * Clock differ by two hours in the above example. That's just to remind you
413 * that there are two independent time scales here).
414 *
415 * This function ought to be able to accept set times as fractional times.
416 * Idea for future enhancement.
417 */
418 static void
419 set_hardware_clock_exact(const struct hwclock_control *ctl,
420 const time_t sethwtime,
421 const struct timeval refsystime)
422 {
423 /*
424 * The Hardware Clock can only be set to any integer time plus one
425 * half second. The integer time is required because there is no
426 * interface to set or get a fractional second. The additional half
427 * second is because the Hardware Clock updates to the following
428 * second precisely 500 ms (not 1 second!) after you release the
429 * divider reset (after setting the new time) - see description of
430 * DV2, DV1, DV0 in Register A in the MC146818A data sheet (and note
431 * that although that document doesn't say so, real-world code seems
432 * to expect that the SET bit in Register B functions the same way).
433 * That means that, e.g., when you set the clock to 1:02:03, it
434 * effectively really sets it to 1:02:03.5, because it will update to
435 * 1:02:04 only half a second later. Our caller passes the desired
436 * integer Hardware Clock time in sethwtime, and the corresponding
437 * system time (which may have a fractional part, and which may or may
438 * not be the same!) in refsystime. In an ideal situation, we would
439 * then apply sethwtime to the Hardware Clock at refsystime+500ms, so
440 * that when the Hardware Clock ticks forward to sethwtime+1s half a
441 * second later at refsystime+1000ms, everything is in sync. So we
442 * spin, waiting for gettimeofday() to return a time at or after that
443 * time (refsystime+500ms) up to a tolerance value, initially 1ms. If
444 * we miss that time due to being preempted for some other process,
445 * then we increase the margin a little bit (initially 1ms, doubling
446 * each time), add 1 second (or more, if needed to get a time that is
447 * in the future) to both the time for which we are waiting and the
448 * time that we will apply to the Hardware Clock, and start waiting
449 * again.
450 *
451 * For example, the caller requests that we set the Hardware Clock to
452 * 1:02:03, with reference time (current system time) = 6:07:08.250.
453 * We want the Hardware Clock to update to 1:02:04 at 6:07:09.250 on
454 * the system clock, and the first such update will occur 0.500
455 * seconds after we write to the Hardware Clock, so we spin until the
456 * system clock reads 6:07:08.750. If we get there, great, but let's
457 * imagine the system is so heavily loaded that our process is
458 * preempted and by the time we get to run again, the system clock
459 * reads 6:07:11.990. We now want to wait until the next xx:xx:xx.750
460 * time, which is 6:07:12.750 (4.5 seconds after the reference time),
461 * at which point we will set the Hardware Clock to 1:02:07 (4 seconds
462 * after the originally requested time). If we do that successfully,
463 * then at 6:07:13.250 (5 seconds after the reference time), the
464 * Hardware Clock will update to 1:02:08 (5 seconds after the
465 * originally requested time), and all is well thereafter.
466 */
467
468 time_t newhwtime = sethwtime;
469 double target_time_tolerance_secs = 0.001; /* initial value */
470 double tolerance_incr_secs = 0.001; /* initial value */
471 const double RTC_SET_DELAY_SECS = 0.5; /* 500 ms */
472 const struct timeval RTC_SET_DELAY_TV = { 0, RTC_SET_DELAY_SECS * 1E6 };
473
474 struct timeval targetsystime;
475 struct timeval nowsystime;
476 struct timeval prevsystime = refsystime;
477 double deltavstarget;
478
479 timeradd(&refsystime, &RTC_SET_DELAY_TV, &targetsystime);
480
481 while (1) {
482 double ticksize;
483
484 /* FOR TESTING ONLY: inject random delays of up to 1000ms */
485 if (ctl->debug >= 10) {
486 int usec = random() % 1000000;
487 printf(_("sleeping ~%d usec\n"), usec);
488 xusleep(usec);
489 }
490
491 gettimeofday(&nowsystime, NULL);
492 deltavstarget = time_diff(nowsystime, targetsystime);
493 ticksize = time_diff(nowsystime, prevsystime);
494 prevsystime = nowsystime;
495
496 if (ticksize < 0) {
497 if (ctl->debug)
498 printf(_("time jumped backward %.6f seconds "
499 "to %ld.%06ld - retargeting\n"),
500 ticksize, nowsystime.tv_sec,
501 nowsystime.tv_usec);
502 /* The retarget is handled at the end of the loop. */
503 } else if (deltavstarget < 0) {
504 /* deltavstarget < 0 if current time < target time */
505 if (ctl->debug >= 2)
506 printf(_("%ld.%06ld < %ld.%06ld (%.6f)\n"),
507 nowsystime.tv_sec,
508 nowsystime.tv_usec,
509 targetsystime.tv_sec,
510 targetsystime.tv_usec,
511 deltavstarget);
512 continue; /* not there yet - keep spinning */
513 } else if (deltavstarget <= target_time_tolerance_secs) {
514 /* Close enough to the target time; done waiting. */
515 break;
516 } else /* (deltavstarget > target_time_tolerance_secs) */ {
517 /*
518 * We missed our window. Increase the tolerance and
519 * aim for the next opportunity.
520 */
521 if (ctl->debug)
522 printf(_("missed it - %ld.%06ld is too far "
523 "past %ld.%06ld (%.6f > %.6f)\n"),
524 nowsystime.tv_sec,
525 nowsystime.tv_usec,
526 targetsystime.tv_sec,
527 targetsystime.tv_usec,
528 deltavstarget,
529 target_time_tolerance_secs);
530 target_time_tolerance_secs += tolerance_incr_secs;
531 tolerance_incr_secs *= 2;
532 }
533
534 /*
535 * Aim for the same offset (tv_usec) within the second in
536 * either the current second (if that offset hasn't arrived
537 * yet), or the next second.
538 */
539 if (nowsystime.tv_usec < targetsystime.tv_usec)
540 targetsystime.tv_sec = nowsystime.tv_sec;
541 else
542 targetsystime.tv_sec = nowsystime.tv_sec + 1;
543 }
544
545 newhwtime = sethwtime
546 + (int)(time_diff(nowsystime, refsystime)
547 - RTC_SET_DELAY_SECS /* don't count this */
548 + 0.5 /* for rounding */);
549 if (ctl->debug)
550 printf(_("%ld.%06ld is close enough to %ld.%06ld (%.6f < %.6f)\n"
551 "Set RTC to %ld (%ld + %d; refsystime = %ld.%06ld)\n"),
552 nowsystime.tv_sec, nowsystime.tv_usec,
553 targetsystime.tv_sec, targetsystime.tv_usec,
554 deltavstarget, target_time_tolerance_secs,
555 newhwtime, sethwtime,
556 (int)(newhwtime - sethwtime),
557 refsystime.tv_sec, refsystime.tv_usec);
558
559 set_hardware_clock(ctl, newhwtime);
560 }
561
562 /*
563 * Put the time "hwctime" on standard output in display format. Except if
564 * hclock_valid == false, just tell standard output that we don't know what
565 * time it is.
566 */
567 static void
568 display_time(const bool hclock_valid, struct timeval hwctime)
569 {
570 if (!hclock_valid)
571 warnx(_
572 ("The Hardware Clock registers contain values that are "
573 "either invalid (e.g. 50th day of month) or beyond the range "
574 "we can handle (e.g. Year 2095)."));
575 else {
576 char buf[ISO_8601_BUFSIZ];
577
578 strtimeval_iso(&hwctime, ISO_8601_DATE|ISO_8601_TIME|ISO_8601_DOTUSEC|
579 ISO_8601_TIMEZONE|ISO_8601_SPACE,
580 buf, sizeof(buf));
581 printf("%s\n", buf);
582 }
583 }
584
585 /*
586 * Set the System Clock to time 'newtime'.
587 *
588 * Also set the kernel time zone value to the value indicated by the TZ
589 * environment variable and/or /usr/lib/zoneinfo/, interpreted as tzset()
590 * would interpret them.
591 *
592 * If this is the first call of settimeofday since boot, then this also sets
593 * the kernel variable persistent_clock_is_local so that NTP 11 minute mode
594 * will update the Hardware Clock with the proper timescale. If the Hardware
595 * Clock's timescale configuration is changed then a reboot is required for
596 * persistent_clock_is_local to be updated.
597 *
598 * EXCEPT: if hclock_valid is false, just issue an error message saying
599 * there is no valid time in the Hardware Clock to which to set the system
600 * time.
601 *
602 * If 'testing' is true, don't actually update anything -- just say we would
603 * have.
604 */
605 static int
606 set_system_clock(const struct hwclock_control *ctl, const bool hclock_valid,
607 const struct timeval newtime)
608 {
609 int retcode;
610
611 if (!hclock_valid) {
612 warnx(_
613 ("The Hardware Clock does not contain a valid time, so "
614 "we cannot set the System Time from it."));
615 retcode = 1;
616 } else {
617 const struct timeval *tv_null = NULL;
618 struct tm *broken;
619 int minuteswest;
620 int rc = 0;
621
622 broken = localtime(&newtime.tv_sec);
623 #ifdef HAVE_TM_GMTOFF
624 minuteswest = -broken->tm_gmtoff / 60; /* GNU extension */
625 #else
626 minuteswest = timezone / 60;
627 if (broken->tm_isdst)
628 minuteswest -= 60;
629 #endif
630
631 if (ctl->debug) {
632 printf(_("Calling settimeofday:\n"));
633 printf(_("\ttv.tv_sec = %ld, tv.tv_usec = %ld\n"),
634 newtime.tv_sec, newtime.tv_usec);
635 printf(_("\ttz.tz_minuteswest = %d\n"), minuteswest);
636 }
637 if (ctl->testing) {
638 printf(_
639 ("Not setting system clock because running in test mode.\n"));
640 retcode = 0;
641 } else {
642 const struct timezone tz = { minuteswest, 0 };
643
644 /* Set kernel persistent_clock_is_local so that 11 minute
645 * mode does not clobber the Hardware Clock with UTC. This
646 * is only available on first call of settimeofday after boot.
647 */
648 if (!ctl->universal)
649 rc = settimeofday(tv_null, &tz);
650 if (!rc)
651 rc = settimeofday(&newtime, &tz);
652 if (rc) {
653 if (errno == EPERM) {
654 warnx(_
655 ("Must be superuser to set system clock."));
656 retcode = EX_NOPERM;
657 } else {
658 warn(_("settimeofday() failed"));
659 retcode = 1;
660 }
661 } else
662 retcode = 0;
663 }
664 }
665 return retcode;
666 }
667
668 /*
669 * Reset the System Clock from local time to UTC, based on its current value
670 * and the timezone unless universal is TRUE.
671 *
672 * Also set the kernel time zone value to the value indicated by the TZ
673 * environment variable and/or /usr/lib/zoneinfo/, interpreted as tzset()
674 * would interpret them.
675 *
676 * If 'testing' is true, don't actually update anything -- just say we would
677 * have.
678 */
679 static int set_system_clock_timezone(const struct hwclock_control *ctl)
680 {
681 int retcode;
682 struct timeval tv;
683 struct tm *broken;
684 int minuteswest;
685
686 gettimeofday(&tv, NULL);
687 if (ctl->debug) {
688 struct tm broken_time;
689 char ctime_now[200];
690
691 broken_time = *gmtime(&tv.tv_sec);
692 strftime(ctime_now, sizeof(ctime_now), "%Y/%m/%d %H:%M:%S",
693 &broken_time);
694 printf(_("Current system time: %ld = %s\n"), tv.tv_sec,
695 ctime_now);
696 }
697
698 broken = localtime(&tv.tv_sec);
699 #ifdef HAVE_TM_GMTOFF
700 minuteswest = -broken->tm_gmtoff / 60; /* GNU extension */
701 #else
702 minuteswest = timezone / 60;
703 if (broken->tm_isdst)
704 minuteswest -= 60;
705 #endif
706
707 if (ctl->debug) {
708 struct tm broken_time;
709 char ctime_now[200];
710
711 gettimeofday(&tv, NULL);
712 if (!ctl->universal)
713 tv.tv_sec += minuteswest * 60;
714
715 broken_time = *gmtime(&tv.tv_sec);
716 strftime(ctime_now, sizeof(ctime_now), "%Y/%m/%d %H:%M:%S",
717 &broken_time);
718
719 printf(_("Calling settimeofday:\n"));
720 printf(_("\tUTC: %s\n"), ctime_now);
721 printf(_("\ttv.tv_sec = %ld, tv.tv_usec = %ld\n"),
722 tv.tv_sec, tv.tv_usec);
723 printf(_("\ttz.tz_minuteswest = %d\n"), minuteswest);
724 }
725 if (ctl->testing) {
726 printf(_
727 ("Not setting system clock because running in test mode.\n"));
728 retcode = 0;
729 } else {
730 const struct timezone tz_utc = { 0, 0 };
731 const struct timezone tz = { minuteswest, 0 };
732 const struct timeval *tv_null = NULL;
733 int rc = 0;
734
735 /* The first call to settimeofday after boot will assume the systemtime
736 * is in localtime, and adjust it according to the given timezone to
737 * compensate. If the systemtime is in fact in UTC, then this is wrong
738 * so we first do a dummy call to make sure the time is not shifted.
739 */
740 if (ctl->universal)
741 rc = settimeofday(tv_null, &tz_utc);
742
743 /* Now we set the real timezone. Due to the above dummy call, this will
744 * only warp the systemtime if the RTC is not in UTC. */
745 if (!rc)
746 rc = settimeofday(tv_null, &tz);
747
748 if (rc) {
749 if (errno == EPERM) {
750 warnx(_
751 ("Must be superuser to set system clock."));
752 retcode = EX_NOPERM;
753 } else {
754 warn(_("settimeofday() failed"));
755 retcode = 1;
756 }
757 } else
758 retcode = 0;
759 }
760 return retcode;
761 }
762
763 /*
764 * Refresh the last calibrated and last adjusted timestamps in <*adjtime_p>
765 * to facilitate future drift calculations based on this set point.
766 *
767 * With the --update-drift option:
768 * Update the drift factor in <*adjtime_p> based on the fact that the
769 * Hardware Clock was just calibrated to <nowtime> and before that was
770 * set to the <hclocktime> time scale.
771 *
772 * EXCEPT: if <hclock_valid> is false, assume Hardware Clock was not set
773 * before to anything meaningful and regular adjustments have not been done,
774 * so don't adjust the drift factor.
775 */
776 static void
777 adjust_drift_factor(const struct hwclock_control *ctl,
778 struct adjtime *adjtime_p,
779 const struct timeval nowtime,
780 const bool hclock_valid,
781 const struct timeval hclocktime)
782 {
783 if (!ctl->update) {
784 if (ctl->debug)
785 printf(_("Not adjusting drift factor because the "
786 "--update-drift option was not used.\n"));
787 } else if (!hclock_valid) {
788 if (ctl->debug)
789 printf(_("Not adjusting drift factor because the "
790 "Hardware Clock previously contained "
791 "garbage.\n"));
792 } else if (adjtime_p->last_calib_time == 0) {
793 if (ctl->debug)
794 printf(_("Not adjusting drift factor because last "
795 "calibration time is zero,\n"
796 "so history is bad and calibration startover "
797 "is necessary.\n"));
798 } else if ((hclocktime.tv_sec - adjtime_p->last_calib_time) < 4 * 60 * 60) {
799 if (ctl->debug)
800 printf(_("Not adjusting drift factor because it has "
801 "been less than four hours since the last "
802 "calibration.\n"));
803 } else {
804 /*
805 * At adjustment time we drift correct the hardware clock
806 * according to the contents of the adjtime file and refresh
807 * its last adjusted timestamp.
808 *
809 * At calibration time we set the Hardware Clock and refresh
810 * both timestamps in <*adjtime_p>.
811 *
812 * Here, with the --update-drift option, we also update the
813 * drift factor in <*adjtime_p>.
814 *
815 * Let us do computation in doubles. (Floats almost suffice,
816 * but 195 days + 1 second equals 195 days in floats.)
817 */
818 const double sec_per_day = 24.0 * 60.0 * 60.0;
819 double factor_adjust;
820 double drift_factor;
821 struct timeval last_calib;
822
823 last_calib = t2tv(adjtime_p->last_calib_time);
824 /*
825 * Correction to apply to the current drift factor.
826 *
827 * Simplified: uncorrected_drift / days_since_calibration.
828 *
829 * hclocktime is fully corrected with the current drift factor.
830 * Its difference from nowtime is the missed drift correction.
831 */
832 factor_adjust = time_diff(nowtime, hclocktime) /
833 (time_diff(nowtime, last_calib) / sec_per_day);
834
835 drift_factor = adjtime_p->drift_factor + factor_adjust;
836 if (fabs(drift_factor) > MAX_DRIFT) {
837 if (ctl->debug)
838 printf(_("Clock drift factor was calculated as "
839 "%f seconds/day.\n"
840 "It is far too much. Resetting to zero.\n"),
841 drift_factor);
842 drift_factor = 0;
843 } else {
844 if (ctl->debug)
845 printf(_("Clock drifted %f seconds in the past "
846 "%f seconds\nin spite of a drift factor of "
847 "%f seconds/day.\n"
848 "Adjusting drift factor by %f seconds/day\n"),
849 time_diff(nowtime, hclocktime),
850 time_diff(nowtime, last_calib),
851 adjtime_p->drift_factor, factor_adjust);
852 }
853
854 adjtime_p->drift_factor = drift_factor;
855 }
856 adjtime_p->last_calib_time = nowtime.tv_sec;
857
858 adjtime_p->last_adj_time = nowtime.tv_sec;
859
860 adjtime_p->not_adjusted = 0;
861
862 adjtime_p->dirty = TRUE;
863 }
864
865 /*
866 * Calculate the drift correction currently needed for the
867 * Hardware Clock based on the last time it was adjusted,
868 * and the current drift factor, as stored in the adjtime file.
869 *
870 * The total drift adjustment needed is stored at tdrift_p.
871 *
872 */
873 static void
874 calculate_adjustment(const struct hwclock_control *ctl,
875 const double factor,
876 const time_t last_time,
877 const double not_adjusted,
878 const time_t systime, struct timeval *tdrift_p)
879 {
880 double exact_adjustment;
881
882 exact_adjustment =
883 ((double)(systime - last_time)) * factor / (24 * 60 * 60)
884 + not_adjusted;
885 tdrift_p->tv_sec = (time_t) floor(exact_adjustment);
886 tdrift_p->tv_usec = (exact_adjustment -
887 (double)tdrift_p->tv_sec) * 1E6;
888 if (ctl->debug) {
889 printf(P_("Time since last adjustment is %ld second\n",
890 "Time since last adjustment is %ld seconds\n",
891 (systime - last_time)),
892 (systime - last_time));
893 printf(_("Calculated Hardware Clock drift is %ld.%06ld seconds\n"),
894 tdrift_p->tv_sec, tdrift_p->tv_usec);
895 }
896 }
897
898 /*
899 * Write the contents of the <adjtime> structure to its disk file.
900 *
901 * But if the contents are clean (unchanged since read from disk), don't
902 * bother.
903 */
904 static void save_adjtime(const struct hwclock_control *ctl,
905 const struct adjtime *adjtime)
906 {
907 char *content; /* Stuff to write to disk file */
908 FILE *fp;
909 int err = 0;
910
911 if (!adjtime->dirty)
912 return;
913
914 xasprintf(&content, "%f %ld %f\n%ld\n%s\n",
915 adjtime->drift_factor,
916 adjtime->last_adj_time,
917 adjtime->not_adjusted,
918 adjtime->last_calib_time,
919 (adjtime->local_utc == LOCAL) ? "LOCAL" : "UTC");
920
921 if (ctl->testing) {
922 printf(_
923 ("Not updating adjtime file because of testing mode.\n"));
924 printf(_("Would have written the following to %s:\n%s"),
925 ctl->adj_file_name, content);
926 free(content);
927 return;
928 }
929
930 fp = fopen(ctl->adj_file_name, "w");
931 if (fp == NULL) {
932 warn(_("Could not open file with the clock adjustment parameters "
933 "in it (%s) for writing"), ctl->adj_file_name);
934 err = 1;
935 } else if (fputs(content, fp) < 0 || close_stream(fp) != 0) {
936 warn(_("Could not update file with the clock adjustment "
937 "parameters (%s) in it"), ctl->adj_file_name);
938 err = 1;
939 }
940 free(content);
941 if (err)
942 warnx(_("Drift adjustment parameters not updated."));
943 }
944
945 /*
946 * Do the adjustment requested, by 1) setting the Hardware Clock (if
947 * necessary), and 2) updating the last-adjusted time in the adjtime
948 * structure.
949 *
950 * Do not update anything if the Hardware Clock does not currently present a
951 * valid time.
952 *
953 * <hclock_valid> means the Hardware Clock contains a valid time.
954 *
955 * <hclocktime> is the drift corrected time read from the Hardware Clock.
956 *
957 * <read_time> was the system time when the <hclocktime> was read, which due
958 * to computational delay could be a short time ago. It is used to define a
959 * trigger point for setting the Hardware Clock. The fractional part of the
960 * Hardware clock set time is subtracted from read_time to 'refer back', or
961 * delay, the trigger point. Fractional parts must be accounted for in this
962 * way, because the Hardware Clock can only be set to a whole second.
963 *
964 * <universal>: the Hardware Clock is kept in UTC.
965 *
966 * <testing>: We are running in test mode (no updating of clock).
967 *
968 */
969 static void
970 do_adjustment(const struct hwclock_control *ctl, struct adjtime *adjtime_p,
971 const bool hclock_valid, const struct timeval hclocktime,
972 const struct timeval read_time)
973 {
974 if (!hclock_valid) {
975 warnx(_("The Hardware Clock does not contain a valid time, "
976 "so we cannot adjust it."));
977 adjtime_p->last_calib_time = 0; /* calibration startover is required */
978 adjtime_p->last_adj_time = 0;
979 adjtime_p->not_adjusted = 0;
980 adjtime_p->dirty = TRUE;
981 } else if (adjtime_p->last_adj_time == 0) {
982 if (ctl->debug)
983 printf(_("Not setting clock because last adjustment time is zero, "
984 "so history is bad.\n"));
985 } else if (fabs(adjtime_p->drift_factor) > MAX_DRIFT) {
986 if (ctl->debug)
987 printf(_("Not setting clock because drift factor %f is far too high.\n"),
988 adjtime_p->drift_factor);
989 } else {
990 set_hardware_clock_exact(ctl, hclocktime.tv_sec,
991 time_inc(read_time,
992 -(hclocktime.tv_usec / 1E6)));
993 adjtime_p->last_adj_time = hclocktime.tv_sec;
994 adjtime_p->not_adjusted = 0;
995 adjtime_p->dirty = TRUE;
996 }
997 }
998
999 static void determine_clock_access_method(const struct hwclock_control *ctl)
1000 {
1001 ur = NULL;
1002
1003 if (ctl->directisa)
1004 ur = probe_for_cmos_clock();
1005 #ifdef __linux__
1006 if (!ur)
1007 ur = probe_for_rtc_clock(ctl);
1008 #endif
1009 if (ur) {
1010 if (ctl->debug)
1011 puts(ur->interface_name);
1012
1013 } else {
1014 if (ctl->debug)
1015 printf(_("No usable clock interface found.\n"));
1016 warnx(_("Cannot access the Hardware Clock via "
1017 "any known method."));
1018 if (!ctl->debug)
1019 warnx(_("Use the --debug option to see the "
1020 "details of our search for an access "
1021 "method."));
1022 hwclock_exit(ctl, EX_SOFTWARE);
1023 }
1024 }
1025
1026 /*
1027 * Do all the normal work of hwclock - read, set clock, etc.
1028 *
1029 * Issue output to stdout and error message to stderr where appropriate.
1030 *
1031 * Return rc == 0 if everything went OK, rc != 0 if not.
1032 */
1033 static int
1034 manipulate_clock(const struct hwclock_control *ctl, const time_t set_time,
1035 const struct timeval startup_time, struct adjtime *adjtime)
1036 {
1037 /* The time at which we read the Hardware Clock */
1038 struct timeval read_time;
1039 /*
1040 * The Hardware Clock gives us a valid time, or at
1041 * least something close enough to fool mktime().
1042 */
1043 bool hclock_valid = FALSE;
1044 /*
1045 * Tick synchronized time read from the Hardware Clock and
1046 * then drift correct for all operations except --show.
1047 */
1048 struct timeval hclocktime = { 0, 0 };
1049 /* Total Hardware Clock drift correction needed. */
1050 struct timeval tdrift;
1051 /* local return code */
1052 int rc = 0;
1053
1054 if (!ctl->systz && !ctl->predict && ur->get_permissions())
1055 return EX_NOPERM;
1056
1057 if ((ctl->set || ctl->systohc || ctl->adjust) &&
1058 (adjtime->local_utc == UTC) != ctl->universal) {
1059 adjtime->local_utc = ctl->universal ? UTC : LOCAL;
1060 adjtime->dirty = TRUE;
1061 }
1062
1063 if (ctl->show || ctl->get || ctl->adjust || ctl->hctosys
1064 || (!ctl->noadjfile && !ctl->systz && !ctl->predict)) {
1065 /* data from HW-clock are required */
1066 rc = synchronize_to_clock_tick(ctl);
1067
1068 /*
1069 * We don't error out if the user is attempting to set the
1070 * RTC and synchronization timeout happens - the RTC could
1071 * be functioning but contain invalid time data so we still
1072 * want to allow a user to set the RTC time.
1073 */
1074 if (rc == RTC_BUSYWAIT_FAILED && !ctl->set && !ctl->systohc)
1075 return EX_IOERR;
1076 gettimeofday(&read_time, NULL);
1077
1078 /*
1079 * If we can't synchronize to a clock tick,
1080 * we likely can't read from the RTC so
1081 * don't bother reading it again.
1082 */
1083 if (!rc) {
1084 rc = read_hardware_clock(ctl, &hclock_valid,
1085 &hclocktime.tv_sec);
1086 if (rc && !ctl->set && !ctl->systohc)
1087 return EX_IOERR;
1088 }
1089 }
1090 /*
1091 * Calculate Hardware Clock drift for --predict with the user
1092 * supplied --date option time, and with the time read from the
1093 * Hardware Clock for all other operations. Apply drift correction
1094 * to the Hardware Clock time for everything except --show and
1095 * --predict. For --predict negate the drift correction, because we
1096 * want to 'predict' a future Hardware Clock time that includes drift.
1097 */
1098 hclocktime = ctl->predict ? t2tv(set_time) : hclocktime;
1099 calculate_adjustment(ctl, adjtime->drift_factor,
1100 adjtime->last_adj_time,
1101 adjtime->not_adjusted,
1102 hclocktime.tv_sec, &tdrift);
1103 if (!ctl->show && !ctl->predict)
1104 hclocktime = time_inc(tdrift, hclocktime.tv_sec);
1105 if (ctl->show || ctl->get) {
1106 display_time(hclock_valid,
1107 time_inc(hclocktime, -time_diff
1108 (read_time, startup_time)));
1109 } else if (ctl->set) {
1110 set_hardware_clock_exact(ctl, set_time, startup_time);
1111 if (!ctl->noadjfile)
1112 adjust_drift_factor(ctl, adjtime,
1113 time_inc(t2tv(set_time), time_diff
1114 (read_time, startup_time)),
1115 hclock_valid, hclocktime);
1116 } else if (ctl->adjust) {
1117 if (tdrift.tv_sec > 0 || tdrift.tv_sec < -1)
1118 do_adjustment(ctl, adjtime, hclock_valid,
1119 hclocktime, read_time);
1120 else
1121 printf(_("Needed adjustment is less than one second, "
1122 "so not setting clock.\n"));
1123 } else if (ctl->systohc) {
1124 struct timeval nowtime, reftime;
1125 /*
1126 * We can only set_hardware_clock_exact to a
1127 * whole seconds time, so we set it with
1128 * reference to the most recent whole
1129 * seconds time.
1130 */
1131 gettimeofday(&nowtime, NULL);
1132 reftime.tv_sec = nowtime.tv_sec;
1133 reftime.tv_usec = 0;
1134 set_hardware_clock_exact(ctl, (time_t) reftime.tv_sec, reftime);
1135 if (!ctl->noadjfile)
1136 adjust_drift_factor(ctl, adjtime, nowtime,
1137 hclock_valid, hclocktime);
1138 } else if (ctl->hctosys) {
1139 rc = set_system_clock(ctl, hclock_valid, hclocktime);
1140 if (rc) {
1141 printf(_("Unable to set system clock.\n"));
1142 return rc;
1143 }
1144 } else if (ctl->systz) {
1145 rc = set_system_clock_timezone(ctl);
1146 if (rc) {
1147 printf(_("Unable to set system clock.\n"));
1148 return rc;
1149 }
1150 } else if (ctl->predict) {
1151 hclocktime = time_inc(hclocktime, (double)
1152 -(tdrift.tv_sec + tdrift.tv_usec / 1E6));
1153 if (ctl->debug) {
1154 printf(_
1155 ("At %ld seconds after 1969, RTC is predicted to read %ld seconds after 1969.\n"),
1156 set_time, hclocktime.tv_sec);
1157 }
1158 display_time(TRUE, hclocktime);
1159 }
1160 if (!ctl->noadjfile)
1161 save_adjtime(ctl, adjtime);
1162 return 0;
1163 }
1164
1165 /**
1166 * Get or set the kernel RTC driver's epoch on Alpha machines.
1167 * ISA machines are hard coded for 1900.
1168 */
1169 #if defined(__linux__) && defined(__alpha__)
1170 static void
1171 manipulate_epoch(const struct hwclock_control *ctl)
1172 {
1173 if (ctl->getepoch) {
1174 unsigned long epoch;
1175
1176 if (get_epoch_rtc(ctl, &epoch))
1177 warnx(_
1178 ("Unable to get the epoch value from the kernel."));
1179 else
1180 printf(_("Kernel is assuming an epoch value of %lu\n"),
1181 epoch);
1182 } else if (ctl->setepoch) {
1183 if (ctl->epoch_option == 0)
1184 warnx(_
1185 ("To set the epoch value, you must use the 'epoch' "
1186 "option to tell to what value to set it."));
1187 else if (ctl->testing)
1188 printf(_
1189 ("Not setting the epoch to %lu - testing only.\n"),
1190 ctl->epoch_option);
1191 else if (set_epoch_rtc(ctl))
1192 printf(_
1193 ("Unable to set the epoch value in the kernel.\n"));
1194 }
1195 }
1196 #endif /* __linux__ __alpha__ */
1197
1198 static void out_version(void)
1199 {
1200 printf(UTIL_LINUX_VERSION);
1201 }
1202
1203 /*
1204 * usage - Output (error and) usage information
1205 *
1206 * This function is called both directly from main to show usage information
1207 * and as fatal function from shhopt if some argument is not understood. In
1208 * case of normal usage info FMT should be NULL. In that case the info is
1209 * printed to stdout. If FMT is given usage will act like fprintf( stderr,
1210 * fmt, ... ), show a usage information and terminate the program
1211 * afterwards.
1212 */
1213 static void usage(const struct hwclock_control *ctl, const char *fmt, ...)
1214 {
1215 FILE *usageto;
1216 va_list ap;
1217
1218 usageto = fmt ? stderr : stdout;
1219
1220 fputs(USAGE_HEADER, usageto);
1221 fputs(_(" hwclock [function] [option...]\n"), usageto);
1222
1223 fputs(USAGE_SEPARATOR, usageto);
1224 fputs(_("Query or set the hardware clock.\n"), usageto);
1225
1226 fputs(_("\nFunctions:\n"), usageto);
1227 fputs(_(" -h, --help show this help text and exit\n"
1228 " -r, --show read hardware clock and print result\n"
1229 " --get read hardware clock and print drift corrected result\n"
1230 " --set set the RTC to the time given with --date\n"), usageto);
1231 fputs(_(" -s, --hctosys set the system time from the hardware clock\n"
1232 " -w, --systohc set the hardware clock from the current system time\n"
1233 " --systz set the system time based on the current timezone\n"
1234 " --adjust adjust the RTC to account for systematic drift since\n"
1235 " the clock was last set or adjusted\n"), usageto);
1236 #if defined(__linux__) && defined(__alpha__)
1237 fputs(_(" --getepoch print out the kernel's hardware clock epoch value\n"
1238 " --setepoch set the kernel's hardware clock epoch value to the \n"
1239 " value given with --epoch\n"), usageto);
1240 #endif
1241 fputs(_(" --predict predict RTC reading at time given with --date\n"
1242 " -V, --version display version information and exit\n"), usageto);
1243
1244 fputs(USAGE_OPTIONS, usageto);
1245 fputs(_(" -u, --utc the hardware clock is kept in UTC\n"
1246 " --localtime the hardware clock is kept in local time\n"), usageto);
1247 #ifdef __linux__
1248 fputs(_(" -f, --rtc <file> special /dev/... file to use instead of default\n"), usageto);
1249 #endif
1250 fprintf(usageto, _(
1251 " --directisa access the ISA bus directly instead of %s\n"
1252 " --date <time> specifies the time to which to set the hardware clock\n"), _PATH_RTC_DEV);
1253 #if defined(__linux__) && defined(__alpha__)
1254 fputs(_(" --epoch <year> specifies the hardware clock's epoch value\n"), usageto);
1255 #endif
1256 fprintf(usageto, _(
1257 " --update-drift update drift factor in %1$s (requires\n"
1258 " --set or --systohc)\n"
1259 " --noadjfile do not access %1$s; this requires the use of\n"
1260 " either --utc or --localtime\n"
1261 " --adjfile <file> specifies the path to the adjust file;\n"
1262 " the default is %1$s\n"), _PATH_ADJTIME);
1263 fputs(_(" --test do not update anything, just show what would happen\n"
1264 " -D, --debug debugging mode\n" "\n"), usageto);
1265
1266 if (fmt) {
1267 va_start(ap, fmt);
1268 vfprintf(usageto, fmt, ap);
1269 va_end(ap);
1270 }
1271
1272 fflush(usageto);
1273 hwclock_exit(ctl, fmt ? EX_USAGE : EX_OK);
1274 }
1275
1276 /*
1277 * Returns:
1278 * EX_USAGE: bad invocation
1279 * EX_NOPERM: no permission
1280 * EX_OSFILE: cannot open /dev/rtc or /etc/adjtime
1281 * EX_IOERR: ioctl error getting or setting the time
1282 * 0: OK (or not)
1283 * 1: failure
1284 */
1285 int main(int argc, char **argv)
1286 {
1287 struct hwclock_control ctl = { .show = 1 }; /* default op is show */
1288 struct timeval startup_time;
1289 struct adjtime adjtime = { 0 };
1290 struct timespec when = { 0 };
1291 /*
1292 * The time we started up, in seconds into the epoch, including
1293 * fractions.
1294 */
1295 time_t set_time = 0; /* Time to which user said to set Hardware Clock */
1296 int rc, c;
1297
1298 /* Long only options. */
1299 enum {
1300 OPT_ADJFILE = CHAR_MAX + 1,
1301 OPT_DATE,
1302 OPT_DIRECTISA,
1303 OPT_EPOCH,
1304 OPT_GET,
1305 OPT_GETEPOCH,
1306 OPT_LOCALTIME,
1307 OPT_NOADJFILE,
1308 OPT_PREDICT_HC,
1309 OPT_SET,
1310 OPT_SETEPOCH,
1311 OPT_SYSTZ,
1312 OPT_TEST,
1313 OPT_UPDATE
1314 };
1315
1316 static const struct option longopts[] = {
1317 { "adjust", no_argument, NULL, 'a' },
1318 { "help", no_argument, NULL, 'h' },
1319 { "show", no_argument, NULL, 'r' },
1320 { "hctosys", no_argument, NULL, 's' },
1321 { "utc", no_argument, NULL, 'u' },
1322 { "version", no_argument, NULL, 'v' },
1323 { "systohc", no_argument, NULL, 'w' },
1324 { "debug", no_argument, NULL, 'D' },
1325 { "set", no_argument, NULL, OPT_SET },
1326 #if defined(__linux__) && defined(__alpha__)
1327 { "getepoch", no_argument, NULL, OPT_GETEPOCH },
1328 { "setepoch", no_argument, NULL, OPT_SETEPOCH },
1329 { "epoch", required_argument, NULL, OPT_EPOCH },
1330 #endif
1331 { "noadjfile", no_argument, NULL, OPT_NOADJFILE },
1332 { "localtime", no_argument, NULL, OPT_LOCALTIME },
1333 { "directisa", no_argument, NULL, OPT_DIRECTISA },
1334 { "test", no_argument, NULL, OPT_TEST },
1335 { "date", required_argument, NULL, OPT_DATE },
1336 #ifdef __linux__
1337 { "rtc", required_argument, NULL, 'f' },
1338 #endif
1339 { "adjfile", required_argument, NULL, OPT_ADJFILE },
1340 { "systz", no_argument, NULL, OPT_SYSTZ },
1341 { "predict-hc", no_argument, NULL, OPT_PREDICT_HC },
1342 { "get", no_argument, NULL, OPT_GET },
1343 { "update-drift", no_argument, NULL, OPT_UPDATE },
1344 { NULL, 0, NULL, 0 }
1345 };
1346
1347 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
1348 { 'a','r','s','w',
1349 OPT_GET, OPT_GETEPOCH, OPT_PREDICT_HC,
1350 OPT_SET, OPT_SETEPOCH, OPT_SYSTZ },
1351 { 'u', OPT_LOCALTIME},
1352 { OPT_ADJFILE, OPT_NOADJFILE },
1353 { OPT_NOADJFILE, OPT_UPDATE },
1354 { 0 }
1355 };
1356 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1357
1358 /* Remember what time we were invoked */
1359 gettimeofday(&startup_time, NULL);
1360
1361 #ifdef HAVE_LIBAUDIT
1362 hwaudit_fd = audit_open();
1363 if (hwaudit_fd < 0 && !(errno == EINVAL || errno == EPROTONOSUPPORT ||
1364 errno == EAFNOSUPPORT)) {
1365 /*
1366 * You get these error codes only when the kernel doesn't
1367 * have audit compiled in.
1368 */
1369 warnx(_("Unable to connect to audit system"));
1370 return EX_NOPERM;
1371 }
1372 #endif
1373 setlocale(LC_ALL, "");
1374 #ifdef LC_NUMERIC
1375 /*
1376 * We need LC_CTYPE and LC_TIME and LC_MESSAGES, but must avoid
1377 * LC_NUMERIC since it gives problems when we write to /etc/adjtime.
1378 * - gqueri@mail.dotcom.fr
1379 */
1380 setlocale(LC_NUMERIC, "C");
1381 #endif
1382 bindtextdomain(PACKAGE, LOCALEDIR);
1383 textdomain(PACKAGE);
1384 atexit(close_stdout);
1385
1386 while ((c = getopt_long(argc, argv,
1387 "?hvVDarsuwAJSFf:", longopts, NULL)) != -1) {
1388
1389 err_exclusive_options(c, longopts, excl, excl_st);
1390
1391 switch (c) {
1392 case 'D':
1393 ctl.debug++;
1394 break;
1395 case 'a':
1396 ctl.adjust = 1;
1397 ctl.show = 0;
1398 ctl.hwaudit_on = 1;
1399 break;
1400 case 'r':
1401 ctl.show = 1;
1402 break;
1403 case 's':
1404 ctl.hctosys = 1;
1405 ctl.show = 0;
1406 ctl.hwaudit_on = 1;
1407 break;
1408 case 'u':
1409 ctl.utc = 1;
1410 break;
1411 case 'w':
1412 ctl.systohc = 1;
1413 ctl.show = 0;
1414 ctl.hwaudit_on = 1;
1415 break;
1416 case OPT_SET:
1417 ctl.set = 1;
1418 ctl.show = 0;
1419 ctl.hwaudit_on = 1;
1420 break;
1421 #if defined(__linux__) && defined(__alpha__)
1422 case OPT_GETEPOCH:
1423 ctl.getepoch = 1;
1424 ctl.show = 0;
1425 break;
1426 case OPT_SETEPOCH:
1427 ctl.setepoch = 1;
1428 ctl.show = 0;
1429 ctl.hwaudit_on = 1;
1430 break;
1431 case OPT_EPOCH:
1432 ctl.epoch_option = /* --epoch */
1433 strtoul_or_err(optarg, _("invalid epoch argument"));
1434 break;
1435 #endif
1436 case OPT_NOADJFILE:
1437 ctl.noadjfile = 1;
1438 break;
1439 case OPT_LOCALTIME:
1440 ctl.local_opt = 1; /* --localtime */
1441 break;
1442 case OPT_DIRECTISA:
1443 ctl.directisa = 1;
1444 break;
1445 case OPT_TEST:
1446 ctl.testing = 1; /* --test */
1447 break;
1448 case OPT_DATE:
1449 ctl.date_opt = optarg; /* --date */
1450 break;
1451 case OPT_ADJFILE:
1452 ctl.adj_file_name = optarg; /* --adjfile */
1453 break;
1454 case OPT_SYSTZ:
1455 ctl.systz = 1; /* --systz */
1456 ctl.show = 0;
1457 break;
1458 case OPT_PREDICT_HC:
1459 ctl.predict = 1; /* --predict-hc */
1460 ctl.show = 0;
1461 break;
1462 case OPT_GET:
1463 ctl.get = 1; /* --get */
1464 ctl.show = 0;
1465 break;
1466 case OPT_UPDATE:
1467 ctl.update = 1; /* --update-drift */
1468 break;
1469 #ifdef __linux__
1470 case 'f':
1471 ctl.rtc_dev_name = optarg; /* --rtc */
1472 break;
1473 #endif
1474 case 'v': /* --version */
1475 case 'V':
1476 out_version();
1477 return 0;
1478 case 'h': /* --help */
1479 usage(&ctl, NULL);
1480 default:
1481 errtryhelp(EXIT_FAILURE);
1482 }
1483 }
1484
1485 argc -= optind;
1486 argv += optind;
1487
1488 if (argc > 0) {
1489 warnx(_("%d too many arguments given"), argc);
1490 errtryhelp(EXIT_FAILURE);
1491 }
1492
1493 if (!ctl.adj_file_name)
1494 ctl.adj_file_name = _PATH_ADJTIME;
1495
1496 if (ctl.noadjfile && !ctl.utc && !ctl.local_opt) {
1497 warnx(_("With --noadjfile, you must specify "
1498 "either --utc or --localtime"));
1499 hwclock_exit(&ctl, EX_USAGE);
1500 }
1501
1502 if (ctl.set || ctl.predict) {
1503 if (!ctl.date_opt){
1504 warnx(_("--date is required for --set or --predict"));
1505 hwclock_exit(&ctl, EX_USAGE);
1506 }
1507 if (parse_date(&when, ctl.date_opt, NULL))
1508 set_time = when.tv_sec;
1509 else {
1510 warnx(_("invalid date '%s'"), ctl.date_opt);
1511 hwclock_exit(&ctl, EX_USAGE);
1512 }
1513 }
1514
1515 #if defined(__linux__) && defined(__alpha__)
1516 if (ctl.getepoch || ctl.setepoch) {
1517 manipulate_epoch(&ctl);
1518 hwclock_exit(&ctl, EX_OK);
1519 }
1520 #endif
1521
1522 if (ctl.debug)
1523 out_version();
1524
1525 if (!ctl.systz && !ctl.predict)
1526 determine_clock_access_method(&ctl);
1527
1528 if (!ctl.noadjfile && !(ctl.systz && (ctl.utc || ctl.local_opt))) {
1529 if ((rc = read_adjtime(&ctl, &adjtime)) != 0)
1530 hwclock_exit(&ctl, rc);
1531 } else
1532 /* Avoid writing adjtime file if we don't have to. */
1533 adjtime.dirty = FALSE;
1534 ctl.universal = hw_clock_is_utc(&ctl, adjtime);
1535 rc = manipulate_clock(&ctl, set_time, startup_time, &adjtime);
1536 hwclock_exit(&ctl, rc);
1537 return rc; /* Not reached */
1538 }
1539
1540 void __attribute__((__noreturn__))
1541 hwclock_exit(const struct hwclock_control *ctl
1542 #ifndef HAVE_LIBAUDIT
1543 __attribute__((__unused__))
1544 #endif
1545 , int status)
1546 {
1547 #ifdef HAVE_LIBAUDIT
1548 if (ctl->hwaudit_on && !ctl->testing) {
1549 audit_log_user_message(hwaudit_fd, AUDIT_USYS_CONFIG,
1550 "op=change-system-time", NULL, NULL, NULL,
1551 status ? 0 : 1);
1552 close(hwaudit_fd);
1553 }
1554 #endif
1555 exit(status);
1556 }
1557
1558 /*
1559 * History of this program:
1560 *
1561 * 98.08.12 BJH Version 2.4
1562 *
1563 * Don't use century byte from Hardware Clock. Add comments telling why.
1564 *
1565 * 98.06.20 BJH Version 2.3.
1566 *
1567 * Make --hctosys set the kernel timezone from TZ environment variable
1568 * and/or /usr/lib/zoneinfo. From Klaus Ripke (klaus@ripke.com).
1569 *
1570 * 98.03.05 BJH. Version 2.2.
1571 *
1572 * Add --getepoch and --setepoch.
1573 *
1574 * Fix some word length things so it works on Alpha.
1575 *
1576 * Make it work when /dev/rtc doesn't have the interrupt functions. In this
1577 * case, busywait for the top of a second instead of blocking and waiting
1578 * for the update complete interrupt.
1579 *
1580 * Fix a bunch of bugs too numerous to mention.
1581 *
1582 * 97.06.01: BJH. Version 2.1. Read and write the century byte (Byte 50) of
1583 * the ISA Hardware Clock when using direct ISA I/O. Problem discovered by
1584 * job (jei@iclnl.icl.nl).
1585 *
1586 * Use the rtc clock access method in preference to the KDGHWCLK method.
1587 * Problem discovered by Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>.
1588 *
1589 * November 1996: Version 2.0.1. Modifications by Nicolai Langfeldt
1590 * (janl@math.uio.no) to make it compile on linux 1.2 machines as well as
1591 * more recent versions of the kernel. Introduced the NO_CLOCK access method
1592 * and wrote feature test code to detect absence of rtc headers.
1593 *
1594 ***************************************************************************
1595 * Maintenance notes
1596 *
1597 * To compile this, you must use GNU compiler optimization (-O option) in
1598 * order to make the "extern inline" functions from asm/io.h (inb(), etc.)
1599 * compile. If you don't optimize, which means the compiler will generate no
1600 * inline functions, the references to these functions in this program will
1601 * be compiled as external references. Since you probably won't be linking
1602 * with any functions by these names, you will have unresolved external
1603 * references when you link.
1604 *
1605 * Here's some info on how we must deal with the time that elapses while
1606 * this program runs: There are two major delays as we run:
1607 *
1608 * 1) Waiting up to 1 second for a transition of the Hardware Clock so
1609 * we are synchronized to the Hardware Clock.
1610 * 2) Running the "date" program to interpret the value of our --date
1611 * option.
1612 *
1613 * Reading the /etc/adjtime file is the next biggest source of delay and
1614 * uncertainty.
1615 *
1616 * The user wants to know what time it was at the moment he invoked us, not
1617 * some arbitrary time later. And in setting the clock, he is giving us the
1618 * time at the moment we are invoked, so if we set the clock some time
1619 * later, we have to add some time to that.
1620 *
1621 * So we check the system time as soon as we start up, then run "date" and
1622 * do file I/O if necessary, then wait to synchronize with a Hardware Clock
1623 * edge, then check the system time again to see how much time we spent. We
1624 * immediately read the clock then and (if appropriate) report that time,
1625 * and additionally, the delay we measured.
1626 *
1627 * If we're setting the clock to a time given by the user, we wait some more
1628 * so that the total delay is an integral number of seconds, then set the
1629 * Hardware Clock to the time the user requested plus that integral number
1630 * of seconds. N.B. The Hardware Clock can only be set in integral seconds.
1631 *
1632 * If we're setting the clock to the system clock value, we wait for the
1633 * system clock to reach the top of a second, and then set the Hardware
1634 * Clock to the system clock's value.
1635 *
1636 * Here's an interesting point about setting the Hardware Clock: On my
1637 * machine, when you set it, it sets to that precise time. But one can
1638 * imagine another clock whose update oscillator marches on a steady one
1639 * second period, so updating the clock between any two oscillator ticks is
1640 * the same as updating it right at the earlier tick. To avoid any
1641 * complications that might cause, we set the clock as soon as possible
1642 * after an oscillator tick.
1643 *
1644 * About synchronizing to the Hardware Clock when reading the time: The
1645 * precision of the Hardware Clock counters themselves is one second. You
1646 * can't read the counters and find out that is 12:01:02.5. But if you
1647 * consider the location in time of the counter's ticks as part of its
1648 * value, then its precision is as infinite as time is continuous! What I'm
1649 * saying is this: To find out the _exact_ time in the hardware clock, we
1650 * wait until the next clock tick (the next time the second counter changes)
1651 * and measure how long we had to wait. We then read the value of the clock
1652 * counters and subtract the wait time and we know precisely what time it
1653 * was when we set out to query the time.
1654 *
1655 * hwclock uses this method, and considers the Hardware Clock to have
1656 * infinite precision.
1657 */