1 /* Copyright (C) 1996 N.M. Maclaren
2 Copyright (C) 1996 The University of Cambridge
4 This includes all of the code needed to handle the time. It assumes rather
5 more than is defined by POSIX, unfortunately. Systems that do not have the
6 'X/Open' extensions may need changes. */
12 #include <sys/types.h>
15 #include <config/autoconf.h>
23 #define MILLION_L 1000000l /* For conversion to/from timeval */
24 #define MILLION_D 1.0e6 /* Must be equal to MILLION_L */
27 #define UPDATE_RTC_MIN_DIFF 60 /* Minimum time step before RTC is updated */
29 double current_time (double offset) {
31 /* Get the current UTC time in seconds since the Epoch plus an offset (usually
32 the time from the beginning of the century to the Epoch!) */
34 struct timeval current;
37 if (gettimeofday(¤t,NULL))
38 fatal(1,"unable to read current machine/system time",NULL);
39 return offset+current.tv_sec+1.0e-6*current.tv_usec;
44 time_t convert_time (double value, int *millisecs) {
46 /* Convert the time to the ANSI C form. */
48 time_t result = (time_t)value;
50 if ((*millisecs = (int)(1000.0*(value-result))) >= 1000) {
59 void adjust_time (double difference, int immediate, double ignore) {
61 /* Adjust the current UTC time. This is portable, even if struct timeval uses
62 an unsigned long for tv_sec. */
64 struct timeval old, new, adjust, previous;
68 /* Start by converting to timeval format. Note that we have to cater for
69 negative, unsigned values. */
71 if ((n = (long)difference) > difference) --n;
73 adjust.tv_usec = (long)(MILLION_D*(difference-n));
75 if (gettimeofday(&old,NULL))
76 fatal(1,"unable to read machine/system time",NULL);
77 new.tv_sec = old.tv_sec+adjust.tv_sec;
78 new.tv_usec = (n = (long)old.tv_usec+(long)adjust.tv_usec);
80 new.tv_usec += MILLION_L;
82 } else if (n >= MILLION_L) {
83 new.tv_usec -= MILLION_L;
87 /* Now diagnose the situation if necessary, and perform the dirty deed. */
91 "Times: old=(%ld,%.6ld) new=(%ld,%.6ld) adjust=(%ld,%.6ld)\n",
92 (long)old.tv_sec,(long)old.tv_usec,
93 (long)new.tv_sec,(long)new.tv_usec,
94 (long)adjust.tv_sec,(long)adjust.tv_usec);
97 if (settimeofday(&new,NULL))
98 fatal(1,"unable to reset current system time",NULL);
101 if (adjtime(&adjust,&previous))
102 fatal(1,"unable to adjust current system time",NULL);
103 if (previous.tv_sec != 0 || previous.tv_usec != 0) {
104 sprintf(text,"(%ld,%.6ld)",
105 (long)previous.tv_sec,(long)previous.tv_usec);
106 if (previous.tv_sec+1.0e-6*previous.tv_usec > ignore)
107 fatal(0,"outstanding time adjustment %s",text);
109 fprintf(stderr,"%s: outstanding time adjustment %s\n",
114 /* Now if the time has changed by a lot, update the RTC */
115 if (adjust.tv_sec >= UPDATE_RTC_MIN_DIFF || adjust.tv_sec < -UPDATE_RTC_MIN_DIFF) {
117 fprintf(stderr,"%s: setting RTC due to time step of %ld seconds\n", argv0, adjust.tv_sec);
119 #ifdef CONFIG_USER_HWCLOCK_HWCLOCK
120 system("hwclock --systohc --utc");
121 #elif defined(CONFIG_USER_RTC_M41T11) || defined (CONFIG_USER_RTC_DS1302)