]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - arch/ppc/kernel/time.c
Merge changes from linux-2.6 by hand
[linux-2.6-omap-h63xx.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/io.h>
62 #include <asm/nvram.h>
63 #include <asm/cache.h>
64 #include <asm/8xx_immap.h>
65 #include <asm/machdep.h>
66
67 #include <asm/time.h>
68
69 /* XXX false sharing with below? */
70 u64 jiffies_64 = INITIAL_JIFFIES;
71
72 EXPORT_SYMBOL(jiffies_64);
73
74 unsigned long disarm_decr[NR_CPUS];
75
76 extern struct timezone sys_tz;
77
78 /* keep track of when we need to update the rtc */
79 time_t last_rtc_update;
80
81 /* The decrementer counts down by 128 every 128ns on a 601. */
82 #define DECREMENTER_COUNT_601   (1000000000 / HZ)
83
84 unsigned tb_ticks_per_jiffy;
85 unsigned tb_to_us;
86 unsigned tb_last_stamp;
87 unsigned long tb_to_ns_scale;
88
89 extern unsigned long wall_jiffies;
90
91 /* used for timezone offset */
92 static long timezone_offset;
93
94 DEFINE_SPINLOCK(rtc_lock);
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 #ifdef CONFIG_SMP
112 unsigned long profile_pc(struct pt_regs *regs)
113 {
114         unsigned long pc = instruction_pointer(regs);
115
116         if (in_lock_functions(pc))
117                 return regs->link;
118
119         return pc;
120 }
121 EXPORT_SYMBOL(profile_pc);
122 #endif
123
124 void wakeup_decrementer(void)
125 {
126         set_dec(tb_ticks_per_jiffy);
127         /* No currently-supported powerbook has a 601,
128          * so use get_tbl, not native
129          */
130         last_jiffy_stamp(0) = tb_last_stamp = get_tbl();
131 }
132
133 /*
134  * timer_interrupt - gets called when the decrementer overflows,
135  * with interrupts disabled.
136  * We set it up to overflow again in 1/HZ seconds.
137  */
138 void timer_interrupt(struct pt_regs * regs)
139 {
140         int next_dec;
141         unsigned long cpu = smp_processor_id();
142         unsigned jiffy_stamp = last_jiffy_stamp(cpu);
143         extern void do_IRQ(struct pt_regs *);
144
145         if (atomic_read(&ppc_n_lost_interrupts) != 0)
146                 do_IRQ(regs);
147
148         irq_enter();
149
150         while ((next_dec = tb_ticks_per_jiffy - tb_delta(&jiffy_stamp)) <= 0) {
151                 jiffy_stamp += tb_ticks_per_jiffy;
152                 
153                 profile_tick(CPU_PROFILING, regs);
154                 update_process_times(user_mode(regs));
155
156                 if (smp_processor_id())
157                         continue;
158
159                 /* We are in an interrupt, no need to save/restore flags */
160                 write_seqlock(&xtime_lock);
161                 tb_last_stamp = jiffy_stamp;
162                 do_timer(regs);
163
164                 /*
165                  * update the rtc when needed, this should be performed on the
166                  * right fraction of a second. Half or full second ?
167                  * Full second works on mk48t59 clocks, others need testing.
168                  * Note that this update is basically only used through
169                  * the adjtimex system calls. Setting the HW clock in
170                  * any other way is a /dev/rtc and userland business.
171                  * This is still wrong by -0.5/+1.5 jiffies because of the
172                  * timer interrupt resolution and possible delay, but here we
173                  * hit a quantization limit which can only be solved by higher
174                  * resolution timers and decoupling time management from timer
175                  * interrupts. This is also wrong on the clocks
176                  * which require being written at the half second boundary.
177                  * We should have an rtc call that only sets the minutes and
178                  * seconds like on Intel to avoid problems with non UTC clocks.
179                  */
180                 if ( ppc_md.set_rtc_time && ntp_synced() &&
181                      xtime.tv_sec - last_rtc_update >= 659 &&
182                      abs((xtime.tv_nsec / 1000) - (1000000-1000000/HZ)) < 500000/HZ &&
183                      jiffies - wall_jiffies == 1) {
184                         if (ppc_md.set_rtc_time(xtime.tv_sec+1 + timezone_offset) == 0)
185                                 last_rtc_update = xtime.tv_sec+1;
186                         else
187                                 /* Try again one minute later */
188                                 last_rtc_update += 60;
189                 }
190                 write_sequnlock(&xtime_lock);
191         }
192         if ( !disarm_decr[smp_processor_id()] )
193                 set_dec(next_dec);
194         last_jiffy_stamp(cpu) = jiffy_stamp;
195
196         if (ppc_md.heartbeat && !ppc_md.heartbeat_count--)
197                 ppc_md.heartbeat();
198
199         irq_exit();
200 }
201
202 /*
203  * This version of gettimeofday has microsecond resolution.
204  */
205 void do_gettimeofday(struct timeval *tv)
206 {
207         unsigned long flags;
208         unsigned long seq;
209         unsigned delta, lost_ticks, usec, sec;
210
211         do {
212                 seq = read_seqbegin_irqsave(&xtime_lock, flags);
213                 sec = xtime.tv_sec;
214                 usec = (xtime.tv_nsec / 1000);
215                 delta = tb_ticks_since(tb_last_stamp);
216 #ifdef CONFIG_SMP
217                 /* As long as timebases are not in sync, gettimeofday can only
218                  * have jiffy resolution on SMP.
219                  */
220                 if (!smp_tb_synchronized)
221                         delta = 0;
222 #endif /* CONFIG_SMP */
223                 lost_ticks = jiffies - wall_jiffies;
224         } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
225
226         usec += mulhwu(tb_to_us, tb_ticks_per_jiffy * lost_ticks + delta);
227         while (usec >= 1000000) {
228                 sec++;
229                 usec -= 1000000;
230         }
231         tv->tv_sec = sec;
232         tv->tv_usec = usec;
233 }
234
235 EXPORT_SYMBOL(do_gettimeofday);
236
237 int do_settimeofday(struct timespec *tv)
238 {
239         time_t wtm_sec, new_sec = tv->tv_sec;
240         long wtm_nsec, new_nsec = tv->tv_nsec;
241         unsigned long flags;
242         int tb_delta;
243
244         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
245                 return -EINVAL;
246
247         write_seqlock_irqsave(&xtime_lock, flags);
248         /* Updating the RTC is not the job of this code. If the time is
249          * stepped under NTP, the RTC will be update after STA_UNSYNC
250          * is cleared. Tool like clock/hwclock either copy the RTC
251          * to the system time, in which case there is no point in writing
252          * to the RTC again, or write to the RTC but then they don't call
253          * settimeofday to perform this operation. Note also that
254          * we don't touch the decrementer since:
255          * a) it would lose timer interrupt synchronization on SMP
256          * (if it is working one day)
257          * b) it could make one jiffy spuriously shorter or longer
258          * which would introduce another source of uncertainty potentially
259          * harmful to relatively short timers.
260          */
261
262         /* This works perfectly on SMP only if the tb are in sync but
263          * guarantees an error < 1 jiffy even if they are off by eons,
264          * still reasonable when gettimeofday resolution is 1 jiffy.
265          */
266         tb_delta = tb_ticks_since(last_jiffy_stamp(smp_processor_id()));
267         tb_delta += (jiffies - wall_jiffies) * tb_ticks_per_jiffy;
268
269         new_nsec -= 1000 * mulhwu(tb_to_us, tb_delta);
270
271         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
272         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
273
274         set_normalized_timespec(&xtime, new_sec, new_nsec);
275         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
276
277         /* In case of a large backwards jump in time with NTP, we want the
278          * clock to be updated as soon as the PLL is again in lock.
279          */
280         last_rtc_update = new_sec - 658;
281
282         ntp_clear();
283         write_sequnlock_irqrestore(&xtime_lock, flags);
284         clock_was_set();
285         return 0;
286 }
287
288 EXPORT_SYMBOL(do_settimeofday);
289
290 /* This function is only called on the boot processor */
291 void __init time_init(void)
292 {
293         time_t sec, old_sec;
294         unsigned old_stamp, stamp, elapsed;
295
296         if (ppc_md.time_init != NULL)
297                 timezone_offset = ppc_md.time_init();
298
299         if (__USE_RTC()) {
300                 /* 601 processor: dec counts down by 128 every 128ns */
301                 tb_ticks_per_jiffy = DECREMENTER_COUNT_601;
302                 /* mulhwu_scale_factor(1000000000, 1000000) is 0x418937 */
303                 tb_to_us = 0x418937;
304         } else {
305                 ppc_md.calibrate_decr();
306                 tb_to_ns_scale = mulhwu(tb_to_us, 1000 << 10);
307         }
308
309         /* Now that the decrementer is calibrated, it can be used in case the
310          * clock is stuck, but the fact that we have to handle the 601
311          * makes things more complex. Repeatedly read the RTC until the
312          * next second boundary to try to achieve some precision.  If there
313          * is no RTC, we still need to set tb_last_stamp and
314          * last_jiffy_stamp(cpu 0) to the current stamp.
315          */
316         stamp = get_native_tbl();
317         if (ppc_md.get_rtc_time) {
318                 sec = ppc_md.get_rtc_time();
319                 elapsed = 0;
320                 do {
321                         old_stamp = stamp;
322                         old_sec = sec;
323                         stamp = get_native_tbl();
324                         if (__USE_RTC() && stamp < old_stamp)
325                                 old_stamp -= 1000000000;
326                         elapsed += stamp - old_stamp;
327                         sec = ppc_md.get_rtc_time();
328                 } while ( sec == old_sec && elapsed < 2*HZ*tb_ticks_per_jiffy);
329                 if (sec==old_sec)
330                         printk("Warning: real time clock seems stuck!\n");
331                 xtime.tv_sec = sec;
332                 xtime.tv_nsec = 0;
333                 /* No update now, we just read the time from the RTC ! */
334                 last_rtc_update = xtime.tv_sec;
335         }
336         last_jiffy_stamp(0) = tb_last_stamp = stamp;
337
338         /* Not exact, but the timer interrupt takes care of this */
339         set_dec(tb_ticks_per_jiffy);
340
341         /* If platform provided a timezone (pmac), we correct the time */
342         if (timezone_offset) {
343                 sys_tz.tz_minuteswest = -timezone_offset / 60;
344                 sys_tz.tz_dsttime = 0;
345                 xtime.tv_sec -= timezone_offset;
346         }
347         set_normalized_timespec(&wall_to_monotonic,
348                                 -xtime.tv_sec, -xtime.tv_nsec);
349 }
350
351 #define FEBRUARY                2
352 #define STARTOFTIME             1970
353 #define SECDAY                  86400L
354 #define SECYR                   (SECDAY * 365)
355
356 /*
357  * Note: this is wrong for 2100, but our signed 32-bit time_t will
358  * have overflowed long before that, so who cares.  -- paulus
359  */
360 #define leapyear(year)          ((year) % 4 == 0)
361 #define days_in_year(a)         (leapyear(a) ? 366 : 365)
362 #define days_in_month(a)        (month_days[(a) - 1])
363
364 static int month_days[12] = {
365         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
366 };
367
368 void to_tm(int tim, struct rtc_time * tm)
369 {
370         register int i;
371         register long hms, day, gday;
372
373         gday = day = tim / SECDAY;
374         hms = tim % SECDAY;
375
376         /* Hours, minutes, seconds are easy */
377         tm->tm_hour = hms / 3600;
378         tm->tm_min = (hms % 3600) / 60;
379         tm->tm_sec = (hms % 3600) % 60;
380
381         /* Number of years in days */
382         for (i = STARTOFTIME; day >= days_in_year(i); i++)
383                 day -= days_in_year(i);
384         tm->tm_year = i;
385
386         /* Number of months in days left */
387         if (leapyear(tm->tm_year))
388                 days_in_month(FEBRUARY) = 29;
389         for (i = 1; day >= days_in_month(i); i++)
390                 day -= days_in_month(i);
391         days_in_month(FEBRUARY) = 28;
392         tm->tm_mon = i;
393
394         /* Days are what is left over (+1) from all that. */
395         tm->tm_mday = day + 1;
396
397         /*
398          * Determine the day of week. Jan. 1, 1970 was a Thursday.
399          */
400         tm->tm_wday = (gday + 4) % 7;
401 }
402
403 /* Auxiliary function to compute scaling factors */
404 /* Actually the choice of a timebase running at 1/4 the of the bus
405  * frequency giving resolution of a few tens of nanoseconds is quite nice.
406  * It makes this computation very precise (27-28 bits typically) which
407  * is optimistic considering the stability of most processor clock
408  * oscillators and the precision with which the timebase frequency
409  * is measured but does not harm.
410  */
411 unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale) {
412         unsigned mlt=0, tmp, err;
413         /* No concern for performance, it's done once: use a stupid
414          * but safe and compact method to find the multiplier.
415          */
416         for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
417                 if (mulhwu(inscale, mlt|tmp) < outscale) mlt|=tmp;
418         }
419         /* We might still be off by 1 for the best approximation.
420          * A side effect of this is that if outscale is too large
421          * the returned value will be zero.
422          * Many corner cases have been checked and seem to work,
423          * some might have been forgotten in the test however.
424          */
425         err = inscale*(mlt+1);
426         if (err <= inscale/2) mlt++;
427         return mlt;
428 }
429
430 unsigned long long sched_clock(void)
431 {
432         unsigned long lo, hi, hi2;
433         unsigned long long tb;
434
435         if (!__USE_RTC()) {
436                 do {
437                         hi = get_tbu();
438                         lo = get_tbl();
439                         hi2 = get_tbu();
440                 } while (hi2 != hi);
441                 tb = ((unsigned long long) hi << 32) | lo;
442                 tb = (tb * tb_to_ns_scale) >> 10;
443         } else {
444                 do {
445                         hi = get_rtcu();
446                         lo = get_rtcl();
447                         hi2 = get_rtcu();
448                 } while (hi2 != hi);
449                 tb = ((unsigned long long) hi) * 1000000000 + lo;
450         }
451         return tb;
452 }