2 * $Id: time.c,v 1.57 1999/10/21 03:08:16 cort Exp $
3 * Common time routines among all ppc machines.
5 * Written by Cort Dougan (cort@cs.nmt.edu) to merge
6 * Paul Mackerras' version and mine for PReP and Pmac.
7 * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
9 * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
10 * to make clock more stable (2.4.0-test5). The only thing
11 * that this code assumes is that the timebases have been synchronized
12 * by firmware on SMP and are never stopped (never do sleep
13 * on SMP then, nap and doze are OK).
15 * TODO (not necessarily in this file):
16 * - improve precision and reproducibility of timebase frequency
17 * measurement at boot time.
18 * - get rid of xtime_lock for gettimeofday (generic kernel problem
19 * to be implemented on all architectures for SMP scalability and
20 * eventually implementing gettimeofday without entering the kernel).
21 * - put all time/clock related variables in a single structure
22 * to minimize number of cache lines touched by gettimeofday()
23 * - for astronomical applications: add a new function to get
24 * non ambiguous timestamps even around leap seconds. This needs
25 * a new timestamp format and a good name.
28 * The following comment is partially obsolete (at least the long wait
29 * is no more a valid reason):
30 * Since the MPC8xx has a programmable interrupt timer, I decided to
31 * use that rather than the decrementer. Two reasons: 1.) the clock
32 * frequency is low, causing 2.) a long wait in the timer interrupt
33 * while ((d = get_dec()) == dval)
34 * loop. The MPC8xx can be driven from a variety of input clocks,
35 * so a number of assumptions have been made here because the kernel
36 * parameter HZ is a constant. We assume (correctly, today :-) that
37 * the MPC8xx on the MBX board is driven from a 32.768 kHz crystal.
38 * This is then divided by 4, providing a 8192 Hz clock into the PIT.
39 * Since it is not possible to get a nice 100 Hz clock out of this, without
40 * creating a software PLL, I have set HZ to 128. -- Dan
42 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
43 * "A Kernel Model for Precision Timekeeping" by Dave Mills
46 #include <linux/config.h>
47 #include <linux/errno.h>
48 #include <linux/sched.h>
49 #include <linux/kernel.h>
50 #include <linux/param.h>
51 #include <linux/string.h>
53 #include <linux/interrupt.h>
54 #include <linux/timex.h>
55 #include <linux/kernel_stat.h>
56 #include <linux/mc146818rtc.h>
57 #include <linux/time.h>
58 #include <linux/init.h>
60 #include <asm/segment.h>
62 #include <asm/processor.h>
63 #include <asm/nvram.h>
64 #include <asm/cache.h>
65 #include <asm/8xx_immap.h>
66 #include <asm/machdep.h>
70 void smp_local_timer_interrupt(struct pt_regs
*);
72 /* keep track of when we need to update the rtc */
73 time_t last_rtc_update
;
74 extern rwlock_t xtime_lock
;
76 /* The decrementer counts down by 128 every 128ns on a 601. */
77 #define DECREMENTER_COUNT_601 (1000000000 / HZ)
79 unsigned tb_ticks_per_jiffy
;
81 unsigned tb_last_stamp
;
83 extern unsigned long wall_jiffies
;
85 static long time_offset
;
87 /* Timer interrupt helper function */
88 static inline int tb_delta(unsigned *jiffy_stamp
) {
92 if (delta
< *jiffy_stamp
) *jiffy_stamp
-= 1000000000;
93 delta
-= *jiffy_stamp
;
95 delta
= get_tbl() - *jiffy_stamp
;
101 * timer_interrupt - gets called when the decrementer overflows,
102 * with interrupts disabled.
103 * We set it up to overflow again in 1/HZ seconds.
105 int timer_interrupt(struct pt_regs
* regs
)
108 unsigned long cpu
= smp_processor_id();
109 unsigned jiffy_stamp
= last_jiffy_stamp(cpu
);
114 jiffy_stamp
+= tb_ticks_per_jiffy
;
115 if (smp_processor_id()) continue;
116 /* We are in an interrupt, no need to save/restore flags */
117 write_lock(&xtime_lock
);
118 tb_last_stamp
= jiffy_stamp
;
122 * update the rtc when needed, this should be performed on the
123 * right fraction of a second. Half or full second ?
124 * Full second works on mk48t59 clocks, others need testing.
125 * Note that this update is basically only used through
126 * the adjtimex system calls. Setting the HW clock in
127 * any other way is a /dev/rtc and userland business.
128 * This is still wrong by -0.5/+1.5 jiffies because of the
129 * timer interrupt resolution and possible delay, but here we
130 * hit a quantization limit which can only be solved by higher
131 * resolution timers and decoupling time management from timer
132 * interrupts. This is also wrong on the clocks
133 * which require being written at the half second boundary.
134 * We should have an rtc call that only sets the minutes and
135 * seconds like on Intel to avoid problems with non UTC clocks.
137 if ( (time_status
& STA_UNSYNC
) == 0 &&
138 xtime
.tv_sec
- last_rtc_update
>= 659 &&
139 abs(xtime
.tv_usec
- (1000000-1000000/HZ
)) < 500000/HZ
&&
140 jiffies
- wall_jiffies
== 1) {
141 if (ppc_md
.set_rtc_time(xtime
.tv_sec
+1 + time_offset
) == 0)
142 last_rtc_update
= xtime
.tv_sec
+1;
144 /* Try again one minute later */
145 last_rtc_update
+= 60;
147 write_unlock(&xtime_lock
);
148 } while((next_dec
= tb_ticks_per_jiffy
- tb_delta(&jiffy_stamp
)) < 0);
150 last_jiffy_stamp(cpu
) = jiffy_stamp
;
153 smp_local_timer_interrupt(regs
);
156 if (ppc_md
.heartbeat
&& !ppc_md
.heartbeat_count
--)
160 return 1; /* lets ret_from_int know we can do checks */
164 * This version of gettimeofday has microsecond resolution.
166 void do_gettimeofday(struct timeval
*tv
)
169 unsigned delta
, lost_ticks
, usec
, sec
;
171 read_lock_irqsave(&xtime_lock
, flags
);
173 usec
= xtime
.tv_usec
;
174 delta
= tb_ticks_since(tb_last_stamp
);
176 /* As long as timebases are not in sync, gettimeofday can only
177 * have jiffy resolution on SMP.
179 if (_machine
!= _MACH_Pmac
)
181 #endif /* CONFIG_SMP */
182 lost_ticks
= jiffies
- wall_jiffies
;
183 read_unlock_irqrestore(&xtime_lock
, flags
);
185 usec
+= mulhwu(tb_to_us
, tb_ticks_per_jiffy
* lost_ticks
+ delta
);
186 while (usec
> 1000000) {
194 void do_settimeofday(struct timeval
*tv
)
197 int tb_delta
, new_usec
, new_sec
;
199 write_lock_irqsave(&xtime_lock
, flags
);
200 /* Updating the RTC is not the job of this code. If the time is
201 * stepped under NTP, the RTC will be update after STA_UNSYNC
202 * is cleared. Tool like clock/hwclock either copy the RTC
203 * to the system time, in which case there is no point in writing
204 * to the RTC again, or write to the RTC but then they don't call
205 * settimeofday to perform this operation. Note also that
206 * we don't touch the decrementer since:
207 * a) it would lose timer interrupt synchronization on SMP
208 * (if it is working one day)
209 * b) it could make one jiffy spuriously shorter or longer
210 * which would introduce another source of uncertainty potentially
211 * harmful to relatively short timers.
214 /* This works perfectly on SMP only if the tb are in sync but
215 * guarantees an error < 1 jiffy even if they are off by eons,
216 * still reasonable when gettimeofday resolution is 1 jiffy.
218 tb_delta
= tb_ticks_since(last_jiffy_stamp(smp_processor_id()));
219 tb_delta
+= (jiffies
- wall_jiffies
) * tb_ticks_per_jiffy
;
220 new_sec
= tv
->tv_sec
;
221 new_usec
= tv
->tv_usec
- mulhwu(tb_to_us
, tb_delta
);
222 while (new_usec
<0) {
226 xtime
.tv_usec
= new_usec
;
227 xtime
.tv_sec
= new_sec
;
229 /* In case of a large backwards jump in time with NTP, we want the
230 * clock to be updated as soon as the PLL is again in lock.
232 last_rtc_update
= new_sec
- 658;
234 time_adjust
= 0; /* stop active adjtime() */
235 time_status
|= STA_UNSYNC
;
236 time_state
= TIME_ERROR
; /* p. 24, (a) */
237 time_maxerror
= NTP_PHASE_LIMIT
;
238 time_esterror
= NTP_PHASE_LIMIT
;
239 write_unlock_irqrestore(&xtime_lock
, flags
);
243 void __init
time_init(void)
246 unsigned old_stamp
, stamp
, elapsed
;
247 /* This function is only called on the boot processor */
250 if (ppc_md
.time_init
!= NULL
)
251 time_offset
= ppc_md
.time_init();
254 /* 601 processor: dec counts down by 128 every 128ns */
255 tb_ticks_per_jiffy
= DECREMENTER_COUNT_601
;
256 /* mulhwu_scale_factor(1000000000, 1000000) is 0x418937 */
259 ppc_md
.calibrate_decr();
262 /* Now that the decrementer is calibrated, it can be used in case the
263 * clock is stuck, but the fact that we have to handle the 601
264 * makes things more complex. Repeatedly read the RTC until the
265 * next second boundary to try to achieve some precision...
267 stamp
= get_native_tbl();
268 sec
= ppc_md
.get_rtc_time();
273 stamp
= get_native_tbl();
274 if (__USE_RTC() && stamp
< old_stamp
) old_stamp
-= 1000000000;
275 elapsed
+= stamp
- old_stamp
;
276 sec
= ppc_md
.get_rtc_time();
277 } while ( sec
== old_sec
&& elapsed
< 2*HZ
*tb_ticks_per_jiffy
);
279 printk("Warning: real time clock seems stuck!\n");
281 write_lock_irqsave(&xtime_lock
, flags
);
283 last_jiffy_stamp(0) = tb_last_stamp
= stamp
;
285 /* No update now, we just read the time from the RTC ! */
286 last_rtc_update
= xtime
.tv_sec
;
287 write_unlock_irqrestore(&xtime_lock
, flags
);
288 /* Not exact, but the timer interrupt takes care of this */
289 set_dec(tb_ticks_per_jiffy
);
291 /* If platform provided a timezone (pmac), we correct the time
292 * using do_sys_settimeofday() which in turn calls warp_clock()
296 tz
.tz_minuteswest
= -time_offset
/ 60;
298 do_sys_settimeofday(NULL
, &tz
);
302 #define TICK_SIZE tick
304 #define STARTOFTIME 1970
305 #define SECDAY 86400L
306 #define SECYR (SECDAY * 365)
307 #define leapyear(year) ((year) % 4 == 0)
308 #define days_in_year(a) (leapyear(a) ? 366 : 365)
309 #define days_in_month(a) (month_days[(a) - 1])
311 static int month_days
[12] = {
312 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
316 * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
318 void GregorianDay(struct rtc_time
* tm
)
323 int MonthOffset
[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
325 lastYear
=tm
->tm_year
-1;
328 * Number of leap corrections to apply up to end of last year
330 leapsToDate
= lastYear
/4 - lastYear
/100 + lastYear
/400;
333 * This year is a leap year if it is divisible by 4 except when it is
334 * divisible by 100 unless it is divisible by 400
336 * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 will be
338 if((tm
->tm_year
%4==0) &&
339 ((tm
->tm_year
%100!=0) || (tm
->tm_year
%400==0)) &&
343 * We are past Feb. 29 in a leap year
352 day
+= lastYear
*365 + leapsToDate
+ MonthOffset
[tm
->tm_mon
-1] +
358 void to_tm(int tim
, struct rtc_time
* tm
)
361 register long hms
, day
;
366 /* Hours, minutes, seconds are easy */
367 tm
->tm_hour
= hms
/ 3600;
368 tm
->tm_min
= (hms
% 3600) / 60;
369 tm
->tm_sec
= (hms
% 3600) % 60;
371 /* Number of years in days */
372 for (i
= STARTOFTIME
; day
>= days_in_year(i
); i
++)
373 day
-= days_in_year(i
);
376 /* Number of months in days left */
377 if (leapyear(tm
->tm_year
))
378 days_in_month(FEBRUARY
) = 29;
379 for (i
= 1; day
>= days_in_month(i
); i
++)
380 day
-= days_in_month(i
);
381 days_in_month(FEBRUARY
) = 28;
384 /* Days are what is left over (+1) from all that. */
385 tm
->tm_mday
= day
+ 1;
388 * Determine the day of week
393 /* Auxiliary function to compute scaling factors */
394 /* Actually the choice of a timebase running at 1/4 the of the bus
395 * frequency giving resolution of a few tens of nanoseconds is quite nice.
396 * It makes this computation very precise (27-28 bits typically) which
397 * is optimistic considering the stability of most processor clock
398 * oscillators and the precision with which the timebase frequency
399 * is measured but does not harm.
401 unsigned mulhwu_scale_factor(unsigned inscale
, unsigned outscale
) {
402 unsigned mlt
=0, tmp
, err
;
403 /* No concern for performance, it's done once: use a stupid
404 * but safe and compact method to find the multiplier.
406 for (tmp
= 1U<<31; tmp
!= 0; tmp
>>= 1) {
407 if (mulhwu(inscale
, mlt
|tmp
) < outscale
) mlt
|=tmp
;
409 /* We might still be off by 1 for the best approximation.
410 * A side effect of this is that if outscale is too large
411 * the returned value will be zero.
412 * Many corner cases have been checked and seem to work,
413 * some might have been forgotten in the test however.
415 err
= inscale
*(mlt
+1);
416 if (err
<= inscale
/2) mlt
++;