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