VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / arch / ppc / kernel / time.c
1 /*
2  * Common time routines among all ppc machines.
3  *
4  * Written by Cort Dougan (cort@cs.nmt.edu) to merge
5  * Paul Mackerras' version and mine for PReP and Pmac.
6  * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
7  *
8  * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
9  * to make clock more stable (2.4.0-test5). The only thing
10  * that this code assumes is that the timebases have been synchronized
11  * by firmware on SMP and are never stopped (never do sleep
12  * on SMP then, nap and doze are OK).
13  *
14  * TODO (not necessarily in this file):
15  * - improve precision and reproducibility of timebase frequency
16  * measurement at boot time.
17  * - get rid of xtime_lock for gettimeofday (generic kernel problem
18  * to be implemented on all architectures for SMP scalability and
19  * eventually implementing gettimeofday without entering the kernel).
20  * - put all time/clock related variables in a single structure
21  * to minimize number of cache lines touched by gettimeofday()
22  * - for astronomical applications: add a new function to get
23  * non ambiguous timestamps even around leap seconds. This needs
24  * a new timestamp format and a good name.
25  *
26  *
27  * The following comment is partially obsolete (at least the long wait
28  * is no more a valid reason):
29  * Since the MPC8xx has a programmable interrupt timer, I decided to
30  * use that rather than the decrementer.  Two reasons: 1.) the clock
31  * frequency is low, causing 2.) a long wait in the timer interrupt
32  *              while ((d = get_dec()) == dval)
33  * loop.  The MPC8xx can be driven from a variety of input clocks,
34  * so a number of assumptions have been made here because the kernel
35  * parameter HZ is a constant.  We assume (correctly, today :-) that
36  * the MPC8xx on the MBX board is driven from a 32.768 kHz crystal.
37  * This is then divided by 4, providing a 8192 Hz clock into the PIT.
38  * Since it is not possible to get a nice 100 Hz clock out of this, without
39  * creating a software PLL, I have set HZ to 128.  -- Dan
40  *
41  * 1997-09-10  Updated NTP code according to technical memorandum Jan '96
42  *             "A Kernel Model for Precision Timekeeping" by Dave Mills
43  */
44
45 #include <linux/config.h>
46 #include <linux/errno.h>
47 #include <linux/sched.h>
48 #include <linux/kernel.h>
49 #include <linux/param.h>
50 #include <linux/string.h>
51 #include <linux/mm.h>
52 #include <linux/module.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>
59 #include <linux/profile.h>
60
61 #include <asm/segment.h>
62 #include <asm/io.h>
63 #include <asm/nvram.h>
64 #include <asm/cache.h>
65 #include <asm/8xx_immap.h>
66 #include <asm/machdep.h>
67
68 #include <asm/time.h>
69
70 /* XXX false sharing with below? */
71 u64 jiffies_64 = INITIAL_JIFFIES;
72
73 EXPORT_SYMBOL(jiffies_64);
74
75 unsigned long disarm_decr[NR_CPUS];
76
77 extern struct timezone sys_tz;
78
79 /* keep track of when we need to update the rtc */
80 time_t last_rtc_update;
81
82 /* The decrementer counts down by 128 every 128ns on a 601. */
83 #define DECREMENTER_COUNT_601   (1000000000 / HZ)
84
85 unsigned tb_ticks_per_jiffy;
86 unsigned tb_to_us;
87 unsigned tb_last_stamp;
88 unsigned long tb_to_ns_scale;
89
90 extern unsigned long wall_jiffies;
91
92 static long time_offset;
93
94 spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
95
96 EXPORT_SYMBOL(rtc_lock);
97
98 /* Timer interrupt helper function */
99 static inline int tb_delta(unsigned *jiffy_stamp) {
100         int delta;
101         if (__USE_RTC()) {
102                 delta = get_rtcl();
103                 if (delta < *jiffy_stamp) *jiffy_stamp -= 1000000000;
104                 delta -= *jiffy_stamp;
105         } else {
106                 delta = get_tbl() - *jiffy_stamp;
107         }
108         return delta;
109 }
110
111 extern char _stext;
112
113 static inline void ppc_do_profile (struct pt_regs *regs)
114 {
115         unsigned long nip;
116         extern unsigned long prof_cpu_mask;
117
118         profile_hook(regs);
119
120         if (user_mode(regs))
121                 return;
122
123         if (!prof_buffer)
124                 return;
125
126         nip = instruction_pointer(regs);
127
128         /*
129          * Only measure the CPUs specified by /proc/irq/prof_cpu_mask.
130          * (default is all CPUs.)
131          */
132         if (!((1<<smp_processor_id()) & prof_cpu_mask))
133                 return;
134
135         nip -= (unsigned long) &_stext;
136         nip >>= prof_shift;
137         /*
138          * Don't ignore out-of-bounds EIP values silently,
139          * put them into the last histogram slot, so if
140          * present, they will show up as a sharp peak.
141          */
142         if (nip > prof_len-1)
143                 nip = prof_len-1;
144         atomic_inc((atomic_t *)&prof_buffer[nip]);
145 }
146
147 /*
148  * timer_interrupt - gets called when the decrementer overflows,
149  * with interrupts disabled.
150  * We set it up to overflow again in 1/HZ seconds.
151  */
152 void timer_interrupt(struct pt_regs * regs)
153 {
154         int next_dec;
155         unsigned long cpu = smp_processor_id();
156         unsigned jiffy_stamp = last_jiffy_stamp(cpu);
157         extern void do_IRQ(struct pt_regs *);
158
159         if (atomic_read(&ppc_n_lost_interrupts) != 0)
160                 do_IRQ(regs);
161
162         irq_enter();
163
164         while ((next_dec = tb_ticks_per_jiffy - tb_delta(&jiffy_stamp)) < 0) {
165                 jiffy_stamp += tb_ticks_per_jiffy;
166                 
167                 ppc_do_profile(regs);
168
169                 if (smp_processor_id())
170                         continue;
171
172                 /* We are in an interrupt, no need to save/restore flags */
173                 write_seqlock(&xtime_lock);
174                 tb_last_stamp = jiffy_stamp;
175                 do_timer(regs);
176
177                 /*
178                  * update the rtc when needed, this should be performed on the
179                  * right fraction of a second. Half or full second ?
180                  * Full second works on mk48t59 clocks, others need testing.
181                  * Note that this update is basically only used through
182                  * the adjtimex system calls. Setting the HW clock in
183                  * any other way is a /dev/rtc and userland business.
184                  * This is still wrong by -0.5/+1.5 jiffies because of the
185                  * timer interrupt resolution and possible delay, but here we
186                  * hit a quantization limit which can only be solved by higher
187                  * resolution timers and decoupling time management from timer
188                  * interrupts. This is also wrong on the clocks
189                  * which require being written at the half second boundary.
190                  * We should have an rtc call that only sets the minutes and
191                  * seconds like on Intel to avoid problems with non UTC clocks.
192                  */
193                 if ( ppc_md.set_rtc_time && (time_status & STA_UNSYNC) == 0 &&
194                      xtime.tv_sec - last_rtc_update >= 659 &&
195                      abs((xtime.tv_nsec / 1000) - (1000000-1000000/HZ)) < 500000/HZ &&
196                      jiffies - wall_jiffies == 1) {
197                         if (ppc_md.set_rtc_time(xtime.tv_sec+1 + time_offset) == 0)
198                                 last_rtc_update = xtime.tv_sec+1;
199                         else
200                                 /* Try again one minute later */
201                                 last_rtc_update += 60;
202                 }
203                 write_sequnlock(&xtime_lock);
204         }
205         if ( !disarm_decr[smp_processor_id()] )
206                 set_dec(next_dec);
207         last_jiffy_stamp(cpu) = jiffy_stamp;
208
209 #ifdef CONFIG_SMP
210         smp_local_timer_interrupt(regs);
211 #endif /* CONFIG_SMP */
212
213         if (ppc_md.heartbeat && !ppc_md.heartbeat_count--)
214                 ppc_md.heartbeat();
215
216         irq_exit();
217 }
218
219 /*
220  * This version of gettimeofday has microsecond resolution.
221  */
222 void do_gettimeofday(struct timeval *tv)
223 {
224         unsigned long flags;
225         unsigned long seq;
226         unsigned delta, lost_ticks, usec, sec;
227
228         do {
229                 seq = read_seqbegin_irqsave(&xtime_lock, flags);
230                 sec = xtime.tv_sec;
231                 usec = (xtime.tv_nsec / 1000);
232                 delta = tb_ticks_since(tb_last_stamp);
233 #ifdef CONFIG_SMP
234                 /* As long as timebases are not in sync, gettimeofday can only
235                  * have jiffy resolution on SMP.
236                  */
237                 if (!smp_tb_synchronized)
238                         delta = 0;
239 #endif /* CONFIG_SMP */
240                 lost_ticks = jiffies - wall_jiffies;
241         } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
242
243         usec += mulhwu(tb_to_us, tb_ticks_per_jiffy * lost_ticks + delta);
244         while (usec >= 1000000) {
245                 sec++;
246                 usec -= 1000000;
247         }
248         tv->tv_sec = sec;
249         tv->tv_usec = usec;
250 }
251
252 EXPORT_SYMBOL(do_gettimeofday);
253
254 int do_settimeofday(struct timespec *tv)
255 {
256         time_t wtm_sec, new_sec = tv->tv_sec;
257         long wtm_nsec, new_nsec = tv->tv_nsec;
258         unsigned long flags;
259         int tb_delta;
260
261         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
262                 return -EINVAL;
263
264         write_seqlock_irqsave(&xtime_lock, flags);
265         /* Updating the RTC is not the job of this code. If the time is
266          * stepped under NTP, the RTC will be update after STA_UNSYNC
267          * is cleared. Tool like clock/hwclock either copy the RTC
268          * to the system time, in which case there is no point in writing
269          * to the RTC again, or write to the RTC but then they don't call
270          * settimeofday to perform this operation. Note also that
271          * we don't touch the decrementer since:
272          * a) it would lose timer interrupt synchronization on SMP
273          * (if it is working one day)
274          * b) it could make one jiffy spuriously shorter or longer
275          * which would introduce another source of uncertainty potentially
276          * harmful to relatively short timers.
277          */
278
279         /* This works perfectly on SMP only if the tb are in sync but
280          * guarantees an error < 1 jiffy even if they are off by eons,
281          * still reasonable when gettimeofday resolution is 1 jiffy.
282          */
283         tb_delta = tb_ticks_since(last_jiffy_stamp(smp_processor_id()));
284         tb_delta += (jiffies - wall_jiffies) * tb_ticks_per_jiffy;
285
286         new_nsec -= 1000 * mulhwu(tb_to_us, tb_delta);
287
288         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
289         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
290
291         set_normalized_timespec(&xtime, new_sec, new_nsec);
292         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
293
294         /* In case of a large backwards jump in time with NTP, we want the
295          * clock to be updated as soon as the PLL is again in lock.
296          */
297         last_rtc_update = new_sec - 658;
298
299         time_adjust = 0;                /* stop active adjtime() */
300         time_status |= STA_UNSYNC;
301         time_state = TIME_ERROR;        /* p. 24, (a) */
302         time_maxerror = NTP_PHASE_LIMIT;
303         time_esterror = NTP_PHASE_LIMIT;
304         write_sequnlock_irqrestore(&xtime_lock, flags);
305         clock_was_set();
306         return 0;
307 }
308
309 EXPORT_SYMBOL(do_settimeofday);
310
311 /* This function is only called on the boot processor */
312 void __init time_init(void)
313 {
314         time_t sec, old_sec;
315         unsigned old_stamp, stamp, elapsed;
316
317         if (ppc_md.time_init != NULL)
318                 time_offset = ppc_md.time_init();
319
320         if (__USE_RTC()) {
321                 /* 601 processor: dec counts down by 128 every 128ns */
322                 tb_ticks_per_jiffy = DECREMENTER_COUNT_601;
323                 /* mulhwu_scale_factor(1000000000, 1000000) is 0x418937 */
324                 tb_to_us = 0x418937;
325         } else {
326                 ppc_md.calibrate_decr();
327                 tb_to_ns_scale = mulhwu(tb_to_us, 1000 << 10);
328         }
329
330         /* Now that the decrementer is calibrated, it can be used in case the
331          * clock is stuck, but the fact that we have to handle the 601
332          * makes things more complex. Repeatedly read the RTC until the
333          * next second boundary to try to achieve some precision.  If there
334          * is no RTC, we still need to set tb_last_stamp and
335          * last_jiffy_stamp(cpu 0) to the current stamp.
336          */
337         stamp = get_native_tbl();
338         if (ppc_md.get_rtc_time) {
339                 sec = ppc_md.get_rtc_time();
340                 elapsed = 0;
341                 do {
342                         old_stamp = stamp;
343                         old_sec = sec;
344                         stamp = get_native_tbl();
345                         if (__USE_RTC() && stamp < old_stamp)
346                                 old_stamp -= 1000000000;
347                         elapsed += stamp - old_stamp;
348                         sec = ppc_md.get_rtc_time();
349                 } while ( sec == old_sec && elapsed < 2*HZ*tb_ticks_per_jiffy);
350                 if (sec==old_sec)
351                         printk("Warning: real time clock seems stuck!\n");
352                 xtime.tv_sec = sec;
353                 xtime.tv_nsec = 0;
354                 /* No update now, we just read the time from the RTC ! */
355                 last_rtc_update = xtime.tv_sec;
356         }
357         last_jiffy_stamp(0) = tb_last_stamp = stamp;
358
359         /* Not exact, but the timer interrupt takes care of this */
360         set_dec(tb_ticks_per_jiffy);
361
362         /* If platform provided a timezone (pmac), we correct the time */
363         if (time_offset) {
364                 sys_tz.tz_minuteswest = -time_offset / 60;
365                 sys_tz.tz_dsttime = 0;
366                 xtime.tv_sec -= time_offset;
367         }
368         set_normalized_timespec(&wall_to_monotonic,
369                                 -xtime.tv_sec, -xtime.tv_nsec);
370 }
371
372 #define FEBRUARY                2
373 #define STARTOFTIME             1970
374 #define SECDAY                  86400L
375 #define SECYR                   (SECDAY * 365)
376
377 /*
378  * Note: this is wrong for 2100, but our signed 32-bit time_t will
379  * have overflowed long before that, so who cares.  -- paulus
380  */
381 #define leapyear(year)          ((year) % 4 == 0)
382 #define days_in_year(a)         (leapyear(a) ? 366 : 365)
383 #define days_in_month(a)        (month_days[(a) - 1])
384
385 static int month_days[12] = {
386         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
387 };
388
389 void to_tm(int tim, struct rtc_time * tm)
390 {
391         register int i;
392         register long hms, day, gday;
393
394         gday = day = tim / SECDAY;
395         hms = tim % SECDAY;
396
397         /* Hours, minutes, seconds are easy */
398         tm->tm_hour = hms / 3600;
399         tm->tm_min = (hms % 3600) / 60;
400         tm->tm_sec = (hms % 3600) % 60;
401
402         /* Number of years in days */
403         for (i = STARTOFTIME; day >= days_in_year(i); i++)
404                 day -= days_in_year(i);
405         tm->tm_year = i;
406
407         /* Number of months in days left */
408         if (leapyear(tm->tm_year))
409                 days_in_month(FEBRUARY) = 29;
410         for (i = 1; day >= days_in_month(i); i++)
411                 day -= days_in_month(i);
412         days_in_month(FEBRUARY) = 28;
413         tm->tm_mon = i;
414
415         /* Days are what is left over (+1) from all that. */
416         tm->tm_mday = day + 1;
417
418         /*
419          * Determine the day of week. Jan. 1, 1970 was a Thursday.
420          */
421         tm->tm_wday = (gday + 4) % 7;
422 }
423
424 /* Auxiliary function to compute scaling factors */
425 /* Actually the choice of a timebase running at 1/4 the of the bus
426  * frequency giving resolution of a few tens of nanoseconds is quite nice.
427  * It makes this computation very precise (27-28 bits typically) which
428  * is optimistic considering the stability of most processor clock
429  * oscillators and the precision with which the timebase frequency
430  * is measured but does not harm.
431  */
432 unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale) {
433         unsigned mlt=0, tmp, err;
434         /* No concern for performance, it's done once: use a stupid
435          * but safe and compact method to find the multiplier.
436          */
437         for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
438                 if (mulhwu(inscale, mlt|tmp) < outscale) mlt|=tmp;
439         }
440         /* We might still be off by 1 for the best approximation.
441          * A side effect of this is that if outscale is too large
442          * the returned value will be zero.
443          * Many corner cases have been checked and seem to work,
444          * some might have been forgotten in the test however.
445          */
446         err = inscale*(mlt+1);
447         if (err <= inscale/2) mlt++;
448         return mlt;
449 }
450
451 unsigned long long sched_clock(void)
452 {
453         unsigned long lo, hi, hi2;
454         unsigned long long tb;
455
456         if (!__USE_RTC()) {
457                 do {
458                         hi = get_tbu();
459                         lo = get_tbl();
460                         hi2 = get_tbu();
461                 } while (hi2 != hi);
462                 tb = ((unsigned long long) hi << 32) | lo;
463                 tb = (tb * tb_to_ns_scale) >> 10;
464         } else {
465                 do {
466                         hi = get_rtcu();
467                         lo = get_rtcl();
468                         hi2 = get_rtcu();
469                 } while (hi2 != hi);
470                 tb = ((unsigned long long) hi) * 1000000000 + lo;
471         }
472         return tb;
473 }