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