Merge branch 'devel' of master.kernel.org:/home/rmk/linux-2.6-serial
[pandora-kernel.git] / arch / alpha / kernel / time.c
1 /*
2  *  linux/arch/alpha/kernel/time.c
3  *
4  *  Copyright (C) 1991, 1992, 1995, 1999, 2000  Linus Torvalds
5  *
6  * This file contains the PC-specific time handling details:
7  * reading the RTC at bootup, etc..
8  * 1994-07-02    Alan Modra
9  *      fixed set_rtc_mmss, fixed time.year for >= 2000, new mktime
10  * 1995-03-26    Markus Kuhn
11  *      fixed 500 ms bug at call to set_rtc_mmss, fixed DS12887
12  *      precision CMOS clock update
13  * 1997-09-10   Updated NTP code according to technical memorandum Jan '96
14  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
15  * 1997-01-09    Adrian Sun
16  *      use interval timer if CONFIG_RTC=y
17  * 1997-10-29    John Bowman (bowman@math.ualberta.ca)
18  *      fixed tick loss calculation in timer_interrupt
19  *      (round system clock to nearest tick instead of truncating)
20  *      fixed algorithm in time_init for getting time from CMOS clock
21  * 1999-04-16   Thorsten Kranzkowski (dl8bcu@gmx.net)
22  *      fixed algorithm in do_gettimeofday() for calculating the precise time
23  *      from processor cycle counter (now taking lost_ticks into account)
24  * 2000-08-13   Jan-Benedict Glaw <jbglaw@lug-owl.de>
25  *      Fixed time_init to be aware of epoches != 1900. This prevents
26  *      booting up in 2048 for me;) Code is stolen from rtc.c.
27  * 2003-06-03   R. Scott Bailey <scott.bailey@eds.com>
28  *      Tighten sanity in time_init from 1% (10,000 PPM) to 250 PPM
29  */
30 #include <linux/errno.h>
31 #include <linux/module.h>
32 #include <linux/sched.h>
33 #include <linux/kernel.h>
34 #include <linux/param.h>
35 #include <linux/string.h>
36 #include <linux/mm.h>
37 #include <linux/delay.h>
38 #include <linux/ioport.h>
39 #include <linux/irq.h>
40 #include <linux/interrupt.h>
41 #include <linux/init.h>
42 #include <linux/bcd.h>
43 #include <linux/profile.h>
44
45 #include <asm/uaccess.h>
46 #include <asm/io.h>
47 #include <asm/hwrpb.h>
48 #include <asm/8253pit.h>
49
50 #include <linux/mc146818rtc.h>
51 #include <linux/time.h>
52 #include <linux/timex.h>
53
54 #include "proto.h"
55 #include "irq_impl.h"
56
57 static int set_rtc_mmss(unsigned long);
58
59 DEFINE_SPINLOCK(rtc_lock);
60
61 #define TICK_SIZE (tick_nsec / 1000)
62
63 /*
64  * Shift amount by which scaled_ticks_per_cycle is scaled.  Shifting
65  * by 48 gives us 16 bits for HZ while keeping the accuracy good even
66  * for large CPU clock rates.
67  */
68 #define FIX_SHIFT       48
69
70 /* lump static variables together for more efficient access: */
71 static struct {
72         /* cycle counter last time it got invoked */
73         __u32 last_time;
74         /* ticks/cycle * 2^48 */
75         unsigned long scaled_ticks_per_cycle;
76         /* last time the CMOS clock got updated */
77         time_t last_rtc_update;
78         /* partial unused tick */
79         unsigned long partial_tick;
80 } state;
81
82 unsigned long est_cycle_freq;
83
84
85 static inline __u32 rpcc(void)
86 {
87     __u32 result;
88     asm volatile ("rpcc %0" : "=r"(result));
89     return result;
90 }
91
92 /*
93  * Scheduler clock - returns current time in nanosec units.
94  *
95  * Copied from ARM code for expediency... ;-}
96  */
97 unsigned long long sched_clock(void)
98 {
99         return (unsigned long long)jiffies * (1000000000 / HZ);
100 }
101
102
103 /*
104  * timer_interrupt() needs to keep up the real-time clock,
105  * as well as call the "do_timer()" routine every clocktick
106  */
107 irqreturn_t timer_interrupt(int irq, void *dev, struct pt_regs * regs)
108 {
109         unsigned long delta;
110         __u32 now;
111         long nticks;
112
113 #ifndef CONFIG_SMP
114         /* Not SMP, do kernel PC profiling here.  */
115         profile_tick(CPU_PROFILING, regs);
116 #endif
117
118         write_seqlock(&xtime_lock);
119
120         /*
121          * Calculate how many ticks have passed since the last update,
122          * including any previous partial leftover.  Save any resulting
123          * fraction for the next pass.
124          */
125         now = rpcc();
126         delta = now - state.last_time;
127         state.last_time = now;
128         delta = delta * state.scaled_ticks_per_cycle + state.partial_tick;
129         state.partial_tick = delta & ((1UL << FIX_SHIFT) - 1); 
130         nticks = delta >> FIX_SHIFT;
131
132         while (nticks > 0) {
133                 do_timer(1);
134 #ifndef CONFIG_SMP
135                 update_process_times(user_mode(regs));
136 #endif
137                 nticks--;
138         }
139
140         /*
141          * If we have an externally synchronized Linux clock, then update
142          * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
143          * called as close as possible to 500 ms before the new second starts.
144          */
145         if (ntp_synced()
146             && xtime.tv_sec > state.last_rtc_update + 660
147             && xtime.tv_nsec >= 500000 - ((unsigned) TICK_SIZE) / 2
148             && xtime.tv_nsec <= 500000 + ((unsigned) TICK_SIZE) / 2) {
149                 int tmp = set_rtc_mmss(xtime.tv_sec);
150                 state.last_rtc_update = xtime.tv_sec - (tmp ? 600 : 0);
151         }
152
153         write_sequnlock(&xtime_lock);
154         return IRQ_HANDLED;
155 }
156
157 void
158 common_init_rtc(void)
159 {
160         unsigned char x;
161
162         /* Reset periodic interrupt frequency.  */
163         x = CMOS_READ(RTC_FREQ_SELECT) & 0x3f;
164         /* Test includes known working values on various platforms
165            where 0x26 is wrong; we refuse to change those. */
166         if (x != 0x26 && x != 0x25 && x != 0x19 && x != 0x06) {
167                 printk("Setting RTC_FREQ to 1024 Hz (%x)\n", x);
168                 CMOS_WRITE(0x26, RTC_FREQ_SELECT);
169         }
170
171         /* Turn on periodic interrupts.  */
172         x = CMOS_READ(RTC_CONTROL);
173         if (!(x & RTC_PIE)) {
174                 printk("Turning on RTC interrupts.\n");
175                 x |= RTC_PIE;
176                 x &= ~(RTC_AIE | RTC_UIE);
177                 CMOS_WRITE(x, RTC_CONTROL);
178         }
179         (void) CMOS_READ(RTC_INTR_FLAGS);
180
181         outb(0x36, 0x43);       /* pit counter 0: system timer */
182         outb(0x00, 0x40);
183         outb(0x00, 0x40);
184
185         outb(0xb6, 0x43);       /* pit counter 2: speaker */
186         outb(0x31, 0x42);
187         outb(0x13, 0x42);
188
189         init_rtc_irq();
190 }
191
192
193 /* Validate a computed cycle counter result against the known bounds for
194    the given processor core.  There's too much brokenness in the way of
195    timing hardware for any one method to work everywhere.  :-(
196
197    Return 0 if the result cannot be trusted, otherwise return the argument.  */
198
199 static unsigned long __init
200 validate_cc_value(unsigned long cc)
201 {
202         static struct bounds {
203                 unsigned int min, max;
204         } cpu_hz[] __initdata = {
205                 [EV3_CPU]    = {   50000000,  200000000 },      /* guess */
206                 [EV4_CPU]    = {  100000000,  300000000 },
207                 [LCA4_CPU]   = {  100000000,  300000000 },      /* guess */
208                 [EV45_CPU]   = {  200000000,  300000000 },
209                 [EV5_CPU]    = {  250000000,  433000000 },
210                 [EV56_CPU]   = {  333000000,  667000000 },
211                 [PCA56_CPU]  = {  400000000,  600000000 },      /* guess */
212                 [PCA57_CPU]  = {  500000000,  600000000 },      /* guess */
213                 [EV6_CPU]    = {  466000000,  600000000 },
214                 [EV67_CPU]   = {  600000000,  750000000 },
215                 [EV68AL_CPU] = {  750000000,  940000000 },
216                 [EV68CB_CPU] = { 1000000000, 1333333333 },
217                 /* None of the following are shipping as of 2001-11-01.  */
218                 [EV68CX_CPU] = { 1000000000, 1700000000 },      /* guess */
219                 [EV69_CPU]   = { 1000000000, 1700000000 },      /* guess */
220                 [EV7_CPU]    = {  800000000, 1400000000 },      /* guess */
221                 [EV79_CPU]   = { 1000000000, 2000000000 },      /* guess */
222         };
223
224         /* Allow for some drift in the crystal.  10MHz is more than enough.  */
225         const unsigned int deviation = 10000000;
226
227         struct percpu_struct *cpu;
228         unsigned int index;
229
230         cpu = (struct percpu_struct *)((char*)hwrpb + hwrpb->processor_offset);
231         index = cpu->type & 0xffffffff;
232
233         /* If index out of bounds, no way to validate.  */
234         if (index >= ARRAY_SIZE(cpu_hz))
235                 return cc;
236
237         /* If index contains no data, no way to validate.  */
238         if (cpu_hz[index].max == 0)
239                 return cc;
240
241         if (cc < cpu_hz[index].min - deviation
242             || cc > cpu_hz[index].max + deviation)
243                 return 0;
244
245         return cc;
246 }
247
248
249 /*
250  * Calibrate CPU clock using legacy 8254 timer/counter. Stolen from
251  * arch/i386/time.c.
252  */
253
254 #define CALIBRATE_LATCH 0xffff
255 #define TIMEOUT_COUNT   0x100000
256
257 static unsigned long __init
258 calibrate_cc_with_pit(void)
259 {
260         int cc, count = 0;
261
262         /* Set the Gate high, disable speaker */
263         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
264
265         /*
266          * Now let's take care of CTC channel 2
267          *
268          * Set the Gate high, program CTC channel 2 for mode 0,
269          * (interrupt on terminal count mode), binary count,
270          * load 5 * LATCH count, (LSB and MSB) to begin countdown.
271          */
272         outb(0xb0, 0x43);               /* binary, mode 0, LSB/MSB, Ch 2 */
273         outb(CALIBRATE_LATCH & 0xff, 0x42);     /* LSB of count */
274         outb(CALIBRATE_LATCH >> 8, 0x42);       /* MSB of count */
275
276         cc = rpcc();
277         do {
278                 count++;
279         } while ((inb(0x61) & 0x20) == 0 && count < TIMEOUT_COUNT);
280         cc = rpcc() - cc;
281
282         /* Error: ECTCNEVERSET or ECPUTOOFAST.  */
283         if (count <= 1 || count == TIMEOUT_COUNT)
284                 return 0;
285
286         return ((long)cc * PIT_TICK_RATE) / (CALIBRATE_LATCH + 1);
287 }
288
289 /* The Linux interpretation of the CMOS clock register contents:
290    When the Update-In-Progress (UIP) flag goes from 1 to 0, the
291    RTC registers show the second which has precisely just started.
292    Let's hope other operating systems interpret the RTC the same way.  */
293
294 static unsigned long __init
295 rpcc_after_update_in_progress(void)
296 {
297         do { } while (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP));
298         do { } while (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
299
300         return rpcc();
301 }
302
303 void __init
304 time_init(void)
305 {
306         unsigned int year, mon, day, hour, min, sec, cc1, cc2, epoch;
307         unsigned long cycle_freq, tolerance;
308         long diff;
309
310         /* Calibrate CPU clock -- attempt #1.  */
311         if (!est_cycle_freq)
312                 est_cycle_freq = validate_cc_value(calibrate_cc_with_pit());
313
314         cc1 = rpcc();
315
316         /* Calibrate CPU clock -- attempt #2.  */
317         if (!est_cycle_freq) {
318                 cc1 = rpcc_after_update_in_progress();
319                 cc2 = rpcc_after_update_in_progress();
320                 est_cycle_freq = validate_cc_value(cc2 - cc1);
321                 cc1 = cc2;
322         }
323
324         cycle_freq = hwrpb->cycle_freq;
325         if (est_cycle_freq) {
326                 /* If the given value is within 250 PPM of what we calculated,
327                    accept it.  Otherwise, use what we found.  */
328                 tolerance = cycle_freq / 4000;
329                 diff = cycle_freq - est_cycle_freq;
330                 if (diff < 0)
331                         diff = -diff;
332                 if ((unsigned long)diff > tolerance) {
333                         cycle_freq = est_cycle_freq;
334                         printk("HWRPB cycle frequency bogus.  "
335                                "Estimated %lu Hz\n", cycle_freq);
336                 } else {
337                         est_cycle_freq = 0;
338                 }
339         } else if (! validate_cc_value (cycle_freq)) {
340                 printk("HWRPB cycle frequency bogus, "
341                        "and unable to estimate a proper value!\n");
342         }
343
344         /* From John Bowman <bowman@math.ualberta.ca>: allow the values
345            to settle, as the Update-In-Progress bit going low isn't good
346            enough on some hardware.  2ms is our guess; we haven't found 
347            bogomips yet, but this is close on a 500Mhz box.  */
348         __delay(1000000);
349
350         sec = CMOS_READ(RTC_SECONDS);
351         min = CMOS_READ(RTC_MINUTES);
352         hour = CMOS_READ(RTC_HOURS);
353         day = CMOS_READ(RTC_DAY_OF_MONTH);
354         mon = CMOS_READ(RTC_MONTH);
355         year = CMOS_READ(RTC_YEAR);
356
357         if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
358                 BCD_TO_BIN(sec);
359                 BCD_TO_BIN(min);
360                 BCD_TO_BIN(hour);
361                 BCD_TO_BIN(day);
362                 BCD_TO_BIN(mon);
363                 BCD_TO_BIN(year);
364         }
365
366         /* PC-like is standard; used for year >= 70 */
367         epoch = 1900;
368         if (year < 20)
369                 epoch = 2000;
370         else if (year >= 20 && year < 48)
371                 /* NT epoch */
372                 epoch = 1980;
373         else if (year >= 48 && year < 70)
374                 /* Digital UNIX epoch */
375                 epoch = 1952;
376
377         printk(KERN_INFO "Using epoch = %d\n", epoch);
378
379         if ((year += epoch) < 1970)
380                 year += 100;
381
382         xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
383         xtime.tv_nsec = 0;
384
385         wall_to_monotonic.tv_sec -= xtime.tv_sec;
386         wall_to_monotonic.tv_nsec = 0;
387
388         if (HZ > (1<<16)) {
389                 extern void __you_loose (void);
390                 __you_loose();
391         }
392
393         state.last_time = cc1;
394         state.scaled_ticks_per_cycle
395                 = ((unsigned long) HZ << FIX_SHIFT) / cycle_freq;
396         state.last_rtc_update = 0;
397         state.partial_tick = 0L;
398
399         /* Startup the timer source. */
400         alpha_mv.init_rtc();
401 }
402
403 /*
404  * Use the cycle counter to estimate an displacement from the last time
405  * tick.  Unfortunately the Alpha designers made only the low 32-bits of
406  * the cycle counter active, so we overflow on 8.2 seconds on a 500MHz
407  * part.  So we can't do the "find absolute time in terms of cycles" thing
408  * that the other ports do.
409  */
410 void
411 do_gettimeofday(struct timeval *tv)
412 {
413         unsigned long flags;
414         unsigned long sec, usec, seq;
415         unsigned long delta_cycles, delta_usec, partial_tick;
416
417         do {
418                 seq = read_seqbegin_irqsave(&xtime_lock, flags);
419
420                 delta_cycles = rpcc() - state.last_time;
421                 sec = xtime.tv_sec;
422                 usec = (xtime.tv_nsec / 1000);
423                 partial_tick = state.partial_tick;
424
425         } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
426
427 #ifdef CONFIG_SMP
428         /* Until and unless we figure out how to get cpu cycle counters
429            in sync and keep them there, we can't use the rpcc tricks.  */
430         delta_usec = 0;
431 #else
432         /*
433          * usec = cycles * ticks_per_cycle * 2**48 * 1e6 / (2**48 * ticks)
434          *      = cycles * (s_t_p_c) * 1e6 / (2**48 * ticks)
435          *      = cycles * (s_t_p_c) * 15625 / (2**42 * ticks)
436          *
437          * which, given a 600MHz cycle and a 1024Hz tick, has a
438          * dynamic range of about 1.7e17, which is less than the
439          * 1.8e19 in an unsigned long, so we are safe from overflow.
440          *
441          * Round, but with .5 up always, since .5 to even is harder
442          * with no clear gain.
443          */
444
445         delta_usec = (delta_cycles * state.scaled_ticks_per_cycle 
446                       + partial_tick) * 15625;
447         delta_usec = ((delta_usec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
448 #endif
449
450         usec += delta_usec;
451         if (usec >= 1000000) {
452                 sec += 1;
453                 usec -= 1000000;
454         }
455
456         tv->tv_sec = sec;
457         tv->tv_usec = usec;
458 }
459
460 EXPORT_SYMBOL(do_gettimeofday);
461
462 int
463 do_settimeofday(struct timespec *tv)
464 {
465         time_t wtm_sec, sec = tv->tv_sec;
466         long wtm_nsec, nsec = tv->tv_nsec;
467         unsigned long delta_nsec;
468
469         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
470                 return -EINVAL;
471
472         write_seqlock_irq(&xtime_lock);
473
474         /* The offset that is added into time in do_gettimeofday above
475            must be subtracted out here to keep a coherent view of the
476            time.  Without this, a full-tick error is possible.  */
477
478 #ifdef CONFIG_SMP
479         delta_nsec = 0;
480 #else
481         delta_nsec = rpcc() - state.last_time;
482         delta_nsec = (delta_nsec * state.scaled_ticks_per_cycle 
483                       + state.partial_tick) * 15625;
484         delta_nsec = ((delta_nsec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
485         delta_nsec *= 1000;
486 #endif
487
488         nsec -= delta_nsec;
489
490         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
491         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
492
493         set_normalized_timespec(&xtime, sec, nsec);
494         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
495
496         ntp_clear();
497
498         write_sequnlock_irq(&xtime_lock);
499         clock_was_set();
500         return 0;
501 }
502
503 EXPORT_SYMBOL(do_settimeofday);
504
505
506 /*
507  * In order to set the CMOS clock precisely, set_rtc_mmss has to be
508  * called 500 ms after the second nowtime has started, because when
509  * nowtime is written into the registers of the CMOS clock, it will
510  * jump to the next second precisely 500 ms later. Check the Motorola
511  * MC146818A or Dallas DS12887 data sheet for details.
512  *
513  * BUG: This routine does not handle hour overflow properly; it just
514  *      sets the minutes. Usually you won't notice until after reboot!
515  */
516
517
518 static int
519 set_rtc_mmss(unsigned long nowtime)
520 {
521         int retval = 0;
522         int real_seconds, real_minutes, cmos_minutes;
523         unsigned char save_control, save_freq_select;
524
525         /* irq are locally disabled here */
526         spin_lock(&rtc_lock);
527         /* Tell the clock it's being set */
528         save_control = CMOS_READ(RTC_CONTROL);
529         CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
530
531         /* Stop and reset prescaler */
532         save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
533         CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
534
535         cmos_minutes = CMOS_READ(RTC_MINUTES);
536         if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
537                 BCD_TO_BIN(cmos_minutes);
538
539         /*
540          * since we're only adjusting minutes and seconds,
541          * don't interfere with hour overflow. This avoids
542          * messing with unknown time zones but requires your
543          * RTC not to be off by more than 15 minutes
544          */
545         real_seconds = nowtime % 60;
546         real_minutes = nowtime / 60;
547         if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) {
548                 /* correct for half hour time zone */
549                 real_minutes += 30;
550         }
551         real_minutes %= 60;
552
553         if (abs(real_minutes - cmos_minutes) < 30) {
554                 if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
555                         BIN_TO_BCD(real_seconds);
556                         BIN_TO_BCD(real_minutes);
557                 }
558                 CMOS_WRITE(real_seconds,RTC_SECONDS);
559                 CMOS_WRITE(real_minutes,RTC_MINUTES);
560         } else {
561                 printk(KERN_WARNING
562                        "set_rtc_mmss: can't update from %d to %d\n",
563                        cmos_minutes, real_minutes);
564                 retval = -1;
565         }
566
567         /* The following flags have to be released exactly in this order,
568          * otherwise the DS12887 (popular MC146818A clone with integrated
569          * battery and quartz) will not reset the oscillator and will not
570          * update precisely 500 ms later. You won't find this mentioned in
571          * the Dallas Semiconductor data sheets, but who believes data
572          * sheets anyway ...                           -- Markus Kuhn
573          */
574         CMOS_WRITE(save_control, RTC_CONTROL);
575         CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
576         spin_unlock(&rtc_lock);
577
578         return retval;
579 }