more changes on original files
[linux-2.4.git] / arch / i386 / kernel / time.c
1 /*
2  *  linux/arch/i386/kernel/time.c
3  *
4  *  Copyright (C) 1991, 1992, 1995  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  * 1996-05-03    Ingo Molnar
14  *      fixed time warps in do_[slow|fast]_gettimeoffset()
15  * 1997-09-10   Updated NTP code according to technical memorandum Jan '96
16  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
17  * 1998-09-05    (Various)
18  *      More robust do_fast_gettimeoffset() algorithm implemented
19  *      (works with APM, Cyrix 6x86MX and Centaur C6),
20  *      monotonic gettimeofday() with fast_get_timeoffset(),
21  *      drift-proof precision TSC calibration on boot
22  *      (C. Scott Ananian <cananian@alumni.princeton.edu>, Andrew D.
23  *      Balsa <andrebalsa@altern.org>, Philip Gladstone <philip@raptor.com>;
24  *      ported from 2.0.35 Jumbo-9 by Michael Krause <m.krause@tu-harburg.de>).
25  * 1998-12-16    Andrea Arcangeli
26  *      Fixed Jumbo-9 code in 2.1.131: do_gettimeofday was missing 1 jiffy
27  *      because was not accounting lost_ticks.
28  * 1998-12-24 Copyright (C) 1998  Andrea Arcangeli
29  *      Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
30  *      serialize accesses to xtime/lost_ticks).
31  */
32
33 #include <linux/errno.h>
34 #include <linux/module.h>
35 #include <linux/sched.h>
36 #include <linux/kernel.h>
37 #include <linux/param.h>
38 #include <linux/string.h>
39 #include <linux/mm.h>
40 #include <linux/interrupt.h>
41 #include <linux/time.h>
42 #include <linux/delay.h>
43 #include <linux/init.h>
44 #include <linux/smp.h>
45
46 #include <asm/io.h>
47 #include <asm/smp.h>
48 #include <asm/irq.h>
49 #include <asm/msr.h>
50 #include <asm/delay.h>
51 #include <asm/mpspec.h>
52 #include <asm/uaccess.h>
53 #include <asm/processor.h>
54
55 #include <linux/mc146818rtc.h>
56 #include <linux/timex.h>
57 #include <linux/config.h>
58
59 #include <asm/fixmap.h>
60 #include <asm/cobalt.h>
61
62 /*
63  * for x86_do_profile()
64  */
65 #include <linux/irq.h>
66
67
68 unsigned long cpu_khz;  /* Detected as we calibrate the TSC */
69
70 /* Number of usecs that the last interrupt was delayed */
71 static int delay_at_last_interrupt;
72
73 static unsigned long last_tsc_low; /* lsb 32 bits of Time Stamp Counter */
74
75 /* Cached *multiplier* to convert TSC counts to microseconds.
76  * (see the equation below).
77  * Equal to 2^32 * (1 / (clocks per usec) ).
78  * Initialized in time_init.
79  */
80 unsigned long fast_gettimeoffset_quotient;
81
82 extern rwlock_t xtime_lock;
83 extern unsigned long wall_jiffies;
84
85 spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
86
87 static inline unsigned long do_fast_gettimeoffset(void)
88 {
89         register unsigned long eax, edx;
90
91         /* Read the Time Stamp Counter */
92
93         rdtsc(eax,edx);
94
95         /* .. relative to previous jiffy (32 bits is enough) */
96         eax -= last_tsc_low;    /* tsc_low delta */
97
98         /*
99          * Time offset = (tsc_low delta) * fast_gettimeoffset_quotient
100          *             = (tsc_low delta) * (usecs_per_clock)
101          *             = (tsc_low delta) * (usecs_per_jiffy / clocks_per_jiffy)
102          *
103          * Using a mull instead of a divl saves up to 31 clock cycles
104          * in the critical path.
105          */
106
107         __asm__("mull %2"
108                 :"=a" (eax), "=d" (edx)
109                 :"rm" (fast_gettimeoffset_quotient),
110                  "0" (eax));
111
112         /* our adjusted time offset in microseconds */
113         return delay_at_last_interrupt + edx;
114 }
115
116 #define TICK_SIZE tick
117
118 spinlock_t i8253_lock = SPIN_LOCK_UNLOCKED;
119
120 EXPORT_SYMBOL(i8253_lock);
121
122 extern spinlock_t i8259A_lock;
123
124 #ifndef CONFIG_X86_TSC
125
126 /* This function must be called with interrupts disabled 
127  * It was inspired by Steve McCanne's microtime-i386 for BSD.  -- jrs
128  * 
129  * However, the pc-audio speaker driver changes the divisor so that
130  * it gets interrupted rather more often - it loads 64 into the
131  * counter rather than 11932! This has an adverse impact on
132  * do_gettimeoffset() -- it stops working! What is also not
133  * good is that the interval that our timer function gets called
134  * is no longer 10.0002 ms, but 9.9767 ms. To get around this
135  * would require using a different timing source. Maybe someone
136  * could use the RTC - I know that this can interrupt at frequencies
137  * ranging from 8192Hz to 2Hz. If I had the energy, I'd somehow fix
138  * it so that at startup, the timer code in sched.c would select
139  * using either the RTC or the 8253 timer. The decision would be
140  * based on whether there was any other device around that needed
141  * to trample on the 8253. I'd set up the RTC to interrupt at 1024 Hz,
142  * and then do some jiggery to have a version of do_timer that 
143  * advanced the clock by 1/1024 s. Every time that reached over 1/100
144  * of a second, then do all the old code. If the time was kept correct
145  * then do_gettimeoffset could just return 0 - there is no low order
146  * divider that can be accessed.
147  *
148  * Ideally, you would be able to use the RTC for the speaker driver,
149  * but it appears that the speaker driver really needs interrupt more
150  * often than every 120 us or so.
151  *
152  * Anyway, this needs more thought....          pjsg (1993-08-28)
153  * 
154  * If you are really that interested, you should be reading
155  * comp.protocols.time.ntp!
156  */
157
158 static unsigned long do_slow_gettimeoffset(void)
159 {
160         int count;
161
162         static int count_p = LATCH;    /* for the first call after boot */
163         static unsigned long jiffies_p = 0;
164
165         /*
166          * cache volatile jiffies temporarily; we have IRQs turned off. 
167          */
168         unsigned long jiffies_t;
169
170         /* gets recalled with irq locally disabled */
171         spin_lock(&i8253_lock);
172         /* timer count may underflow right here */
173         outb_p(0x00, 0x43);     /* latch the count ASAP */
174
175         count = inb_p(0x40);    /* read the latched count */
176
177         /*
178          * We do this guaranteed double memory access instead of a _p 
179          * postfix in the previous port access. Wheee, hackady hack
180          */
181         jiffies_t = jiffies;
182
183         count |= inb_p(0x40) << 8;
184         
185         /* VIA686a test code... reset the latch if count > max + 1 */
186         if (count > LATCH) {
187                 outb_p(0x34, 0x43);
188                 outb_p(LATCH & 0xff, 0x40);
189                 outb(LATCH >> 8, 0x40);
190                 count = LATCH - 1;
191         }
192         
193         spin_unlock(&i8253_lock);
194
195         /*
196          * avoiding timer inconsistencies (they are rare, but they happen)...
197          * there are two kinds of problems that must be avoided here:
198          *  1. the timer counter underflows
199          *  2. hardware problem with the timer, not giving us continuous time,
200          *     the counter does small "jumps" upwards on some Pentium systems,
201          *     (see c't 95/10 page 335 for Neptun bug.)
202          */
203
204 /* you can safely undefine this if you don't have the Neptune chipset */
205
206 #define BUGGY_NEPTUN_TIMER
207
208         if( jiffies_t == jiffies_p ) {
209                 if( count > count_p ) {
210                         /* the nutcase */
211
212                         int i;
213
214                         spin_lock(&i8259A_lock);
215                         /*
216                          * This is tricky when I/O APICs are used;
217                          * see do_timer_interrupt().
218                          */
219                         i = inb(0x20);
220                         spin_unlock(&i8259A_lock);
221
222                         /* assumption about timer being IRQ0 */
223                         if (i & 0x01) {
224                                 /*
225                                  * We cannot detect lost timer interrupts ... 
226                                  * well, that's why we call them lost, don't we? :)
227                                  * [hmm, on the Pentium and Alpha we can ... sort of]
228                                  */
229                                 count -= LATCH;
230                         } else {
231 #ifdef BUGGY_NEPTUN_TIMER
232                                 /*
233                                  * for the Neptun bug we know that the 'latch'
234                                  * command doesnt latch the high and low value
235                                  * of the counter atomically. Thus we have to 
236                                  * substract 256 from the counter 
237                                  * ... funny, isnt it? :)
238                                  */
239
240                                 count -= 256;
241 #else
242                                 printk("do_slow_gettimeoffset(): hardware timer problem?\n");
243 #endif
244                         }
245                 }
246         } else
247                 jiffies_p = jiffies_t;
248
249         count_p = count;
250
251         count = ((LATCH-1) - count) * TICK_SIZE;
252         count = (count + LATCH/2) / LATCH;
253
254         return count;
255 }
256
257 static unsigned long (*do_gettimeoffset)(void) = do_slow_gettimeoffset;
258
259
260 /* IBM Summit (EXA) Cyclone Timer code*/
261 #ifdef CONFIG_X86_SUMMIT
262
263 #define CYCLONE_CBAR_ADDR 0xFEB00CD0
264 #define CYCLONE_PMCC_OFFSET 0x51A0
265 #define CYCLONE_MPMC_OFFSET 0x51D0
266 #define CYCLONE_MPCS_OFFSET 0x51A8
267 #define CYCLONE_TIMER_FREQ 100000000
268
269 int use_cyclone = 0;
270 int __init cyclone_setup(char *str) 
271 {
272         use_cyclone = 1;
273         return 1;
274 }
275
276 static u32* volatile cyclone_timer;     /* Cyclone MPMC0 register */
277 static u32 last_cyclone_timer;
278
279 static inline void mark_timeoffset_cyclone(void)
280 {
281         int count;
282         unsigned long lost;
283         unsigned long delta = last_cyclone_timer;
284         spin_lock(&i8253_lock);
285         /* quickly read the cyclone timer */
286         if(cyclone_timer)
287                 last_cyclone_timer = cyclone_timer[0];
288
289         /* calculate delay_at_last_interrupt */
290         outb_p(0x00, 0x43);     /* latch the count ASAP */
291
292         count = inb_p(0x40);    /* read the latched count */
293         count |= inb(0x40) << 8;
294         spin_unlock(&i8253_lock);
295
296         /*lost tick compensation*/
297         delta = last_cyclone_timer - delta;     
298         delta /= (CYCLONE_TIMER_FREQ/1000000);
299         delta += delay_at_last_interrupt;
300         lost = delta/(1000000/HZ);
301         if (lost >= 2)
302                 jiffies += lost-1;
303                
304         count = ((LATCH-1) - count) * TICK_SIZE;
305         delay_at_last_interrupt = (count + LATCH/2) / LATCH;
306 }
307
308 static unsigned long do_gettimeoffset_cyclone(void)
309 {
310         u32 offset;
311
312         if(!cyclone_timer)
313                 return delay_at_last_interrupt;
314
315         /* Read the cyclone timer */
316         offset = cyclone_timer[0];
317
318         /* .. relative to previous jiffy */
319         offset = offset - last_cyclone_timer;
320
321         /* convert cyclone ticks to microseconds */     
322         /* XXX slow, can we speed this up? */
323         offset = offset/(CYCLONE_TIMER_FREQ/1000000);
324
325         /* our adjusted time offset in microseconds */
326         return delay_at_last_interrupt + offset;
327 }
328
329 static void __init init_cyclone_clock(void)
330 {
331         u32* reg;       
332         u32 base;               /* saved cyclone base address */
333         u32 pageaddr;   /* page that contains cyclone_timer register */
334         u32 offset;             /* offset from pageaddr to cyclone_timer register */
335         int i;
336         
337         printk(KERN_INFO "Summit chipset: Starting Cyclone Counter.\n");
338
339         /* find base address */
340         pageaddr = (CYCLONE_CBAR_ADDR)&PAGE_MASK;
341         offset = (CYCLONE_CBAR_ADDR)&(~PAGE_MASK);
342         set_fixmap_nocache(FIX_CYCLONE_TIMER, pageaddr);
343         reg = (u32*)(fix_to_virt(FIX_CYCLONE_TIMER) + offset);
344         if(!reg){
345                 printk(KERN_ERR "Summit chipset: Could not find valid CBAR register.\n");
346                 use_cyclone = 0;
347                 return;
348         }
349         base = *reg;    
350         if(!base){
351                 printk(KERN_ERR "Summit chipset: Could not find valid CBAR value.\n");
352                 use_cyclone = 0;
353                 return;
354         }
355         
356         /* setup PMCC */
357         pageaddr = (base + CYCLONE_PMCC_OFFSET)&PAGE_MASK;
358         offset = (base + CYCLONE_PMCC_OFFSET)&(~PAGE_MASK);
359         set_fixmap_nocache(FIX_CYCLONE_TIMER, pageaddr);
360         reg = (u32*)(fix_to_virt(FIX_CYCLONE_TIMER) + offset);
361         if(!reg){
362                 printk(KERN_ERR "Summit chipset: Could not find valid PMCC register.\n");
363                 use_cyclone = 0;
364                 return;
365         }
366         reg[0] = 0x00000001;
367
368         /* setup MPCS */
369         pageaddr = (base + CYCLONE_MPCS_OFFSET)&PAGE_MASK;
370         offset = (base + CYCLONE_MPCS_OFFSET)&(~PAGE_MASK);
371         set_fixmap_nocache(FIX_CYCLONE_TIMER, pageaddr);
372         reg = (u32*)(fix_to_virt(FIX_CYCLONE_TIMER) + offset);
373         if(!reg){
374                 printk(KERN_ERR "Summit chipset: Could not find valid MPCS register.\n");
375                 use_cyclone = 0;
376                 return;
377         }
378         reg[0] = 0x00000001;
379
380         /* map in cyclone_timer */
381         pageaddr = (base + CYCLONE_MPMC_OFFSET)&PAGE_MASK;
382         offset = (base + CYCLONE_MPMC_OFFSET)&(~PAGE_MASK);
383         set_fixmap_nocache(FIX_CYCLONE_TIMER, pageaddr);
384         cyclone_timer = (u32*)(fix_to_virt(FIX_CYCLONE_TIMER) + offset);
385         if(!cyclone_timer){
386                 printk(KERN_ERR "Summit chipset: Could not find valid MPMC register.\n");
387                 use_cyclone = 0;
388                 return;
389         }
390
391         /*quick test to make sure its ticking*/
392         for(i=0; i<3; i++){
393                 u32 old = cyclone_timer[0];
394                 int stall = 100;
395                 while(stall--) barrier();
396                 if(cyclone_timer[0] == old){
397                         printk(KERN_ERR "Summit chipset: Counter not counting! DISABLED\n");
398                         cyclone_timer = 0;
399                         use_cyclone = 0;
400                         return;
401                 }
402         }
403         /* Everything looks good, so set do_gettimeoffset */
404         do_gettimeoffset = do_gettimeoffset_cyclone;    
405 }
406 void __cyclone_delay(unsigned long loops)
407 {
408         unsigned long bclock, now;
409         if(!cyclone_timer)
410                 return;
411         bclock = cyclone_timer[0];
412         do {
413                 rep_nop();
414                 now = cyclone_timer[0];
415         } while ((now-bclock) < loops);
416 }
417 #endif /* CONFIG_X86_SUMMIT */
418
419 #else
420
421 #define do_gettimeoffset()      do_fast_gettimeoffset()
422
423 #endif
424
425 /* No-cyclone stubs */
426 #ifndef CONFIG_X86_SUMMIT
427 int __init cyclone_setup(char *str) 
428 {
429         printk(KERN_ERR "cyclone: Kernel not compiled with CONFIG_X86_SUMMIT, cannot use the cyclone-timer.\n");
430         return 1;
431 }
432
433 const int use_cyclone = 0;
434 static void mark_timeoffset_cyclone(void) {}
435 static void init_cyclone_clock(void) {}
436 void __cyclone_delay(unsigned long loops) {}
437 #endif /* CONFIG_X86_SUMMIT */
438
439 /*
440  * This version of gettimeofday has microsecond resolution
441  * and better than microsecond precision on fast x86 machines with TSC.
442  */
443 void do_gettimeofday(struct timeval *tv)
444 {
445         unsigned long flags;
446         unsigned long usec, sec;
447
448         read_lock_irqsave(&xtime_lock, flags);
449         usec = do_gettimeoffset();
450         {
451                 unsigned long lost = jiffies - wall_jiffies;
452                 if (lost)
453                         usec += lost * (1000000 / HZ);
454         }
455         sec = xtime.tv_sec;
456         usec += xtime.tv_usec;
457         read_unlock_irqrestore(&xtime_lock, flags);
458
459         while (usec >= 1000000) {
460                 usec -= 1000000;
461                 sec++;
462         }
463
464         tv->tv_sec = sec;
465         tv->tv_usec = usec;
466 }
467
468 void do_settimeofday(struct timeval *tv)
469 {
470         write_lock_irq(&xtime_lock);
471         /*
472          * This is revolting. We need to set "xtime" correctly. However, the
473          * value in this location is the value at the most recent update of
474          * wall time.  Discover what correction gettimeofday() would have
475          * made, and then undo it!
476          */
477         tv->tv_usec -= do_gettimeoffset();
478         tv->tv_usec -= (jiffies - wall_jiffies) * (1000000 / HZ);
479
480         while (tv->tv_usec < 0) {
481                 tv->tv_usec += 1000000;
482                 tv->tv_sec--;
483         }
484
485         xtime = *tv;
486         time_adjust = 0;                /* stop active adjtime() */
487         time_status |= STA_UNSYNC;
488         time_maxerror = NTP_PHASE_LIMIT;
489         time_esterror = NTP_PHASE_LIMIT;
490         write_unlock_irq(&xtime_lock);
491 }
492
493 /*
494  * In order to set the CMOS clock precisely, set_rtc_mmss has to be
495  * called 500 ms after the second nowtime has started, because when
496  * nowtime is written into the registers of the CMOS clock, it will
497  * jump to the next second precisely 500 ms later. Check the Motorola
498  * MC146818A or Dallas DS12887 data sheet for details.
499  *
500  * BUG: This routine does not handle hour overflow properly; it just
501  *      sets the minutes. Usually you'll only notice that after reboot!
502  */
503 static int set_rtc_mmss(unsigned long nowtime)
504 {
505         int retval = 0;
506         int real_seconds, real_minutes, cmos_minutes;
507         unsigned char save_control, save_freq_select;
508
509         /* gets recalled with irq locally disabled */
510         spin_lock(&rtc_lock);
511         save_control = CMOS_READ(RTC_CONTROL); /* tell the clock it's being set */
512         CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
513
514         save_freq_select = CMOS_READ(RTC_FREQ_SELECT); /* stop and reset prescaler */
515         CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
516
517         cmos_minutes = CMOS_READ(RTC_MINUTES);
518         if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
519                 BCD_TO_BIN(cmos_minutes);
520
521         /*
522          * since we're only adjusting minutes and seconds,
523          * don't interfere with hour overflow. This avoids
524          * messing with unknown time zones but requires your
525          * RTC not to be off by more than 15 minutes
526          */
527         real_seconds = nowtime % 60;
528         real_minutes = nowtime / 60;
529         if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1)
530                 real_minutes += 30;             /* correct for half hour time zone */
531         real_minutes %= 60;
532
533         if (abs(real_minutes - cmos_minutes) < 30) {
534                 if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
535                         BIN_TO_BCD(real_seconds);
536                         BIN_TO_BCD(real_minutes);
537                 }
538                 CMOS_WRITE(real_seconds,RTC_SECONDS);
539                 CMOS_WRITE(real_minutes,RTC_MINUTES);
540         } else {
541                 printk(KERN_WARNING
542                        "set_rtc_mmss: can't update from %d to %d\n",
543                        cmos_minutes, real_minutes);
544                 retval = -1;
545         }
546
547         /* The following flags have to be released exactly in this order,
548          * otherwise the DS12887 (popular MC146818A clone with integrated
549          * battery and quartz) will not reset the oscillator and will not
550          * update precisely 500 ms later. You won't find this mentioned in
551          * the Dallas Semiconductor data sheets, but who believes data
552          * sheets anyway ...                           -- Markus Kuhn
553          */
554         CMOS_WRITE(save_control, RTC_CONTROL);
555         CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
556         spin_unlock(&rtc_lock);
557
558         return retval;
559 }
560
561 /* last time the cmos clock got updated */
562 static long last_rtc_update;
563
564 int timer_ack;
565
566 /*
567  * timer_interrupt() needs to keep up the real-time clock,
568  * as well as call the "do_timer()" routine every clocktick
569  */
570 static inline void do_timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
571 {
572 #ifdef CONFIG_X86_IO_APIC
573         if (timer_ack) {
574                 /*
575                  * Subtle, when I/O APICs are used we have to ack timer IRQ
576                  * manually to reset the IRR bit for do_slow_gettimeoffset().
577                  * This will also deassert NMI lines for the watchdog if run
578                  * on an 82489DX-based system.
579                  */
580                 spin_lock(&i8259A_lock);
581                 outb(0x0c, 0x20);
582                 /* Ack the IRQ; AEOI will end it automatically. */
583                 inb(0x20);
584                 spin_unlock(&i8259A_lock);
585         }
586 #endif
587
588 #ifdef CONFIG_VISWS
589         /* Clear the interrupt */
590         co_cpu_write(CO_CPU_STAT,co_cpu_read(CO_CPU_STAT) & ~CO_STAT_TIMEINTR);
591 #endif
592         do_timer(regs);
593 /*
594  * In the SMP case we use the local APIC timer interrupt to do the
595  * profiling, except when we simulate SMP mode on a uniprocessor
596  * system, in that case we have to call the local interrupt handler.
597  */
598 #ifndef CONFIG_X86_LOCAL_APIC
599         if (!user_mode(regs))
600                 x86_do_profile(regs->eip);
601 #else
602         if (!using_apic_timer)
603                 smp_local_timer_interrupt(regs);
604 #endif
605
606         /*
607          * If we have an externally synchronized Linux clock, then update
608          * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
609          * called as close as possible to 500 ms before the new second starts.
610          */
611         if ((time_status & STA_UNSYNC) == 0 &&
612             xtime.tv_sec > last_rtc_update + 660 &&
613             xtime.tv_usec >= 500000 - ((unsigned) tick) / 2 &&
614             xtime.tv_usec <= 500000 + ((unsigned) tick) / 2) {
615                 if (set_rtc_mmss(xtime.tv_sec) == 0)
616                         last_rtc_update = xtime.tv_sec;
617                 else
618                         last_rtc_update = xtime.tv_sec - 600; /* do it again in 60 s */
619         }
620             
621 #ifdef CONFIG_MCA
622         if( MCA_bus ) {
623                 /* The PS/2 uses level-triggered interrupts.  You can't
624                 turn them off, nor would you want to (any attempt to
625                 enable edge-triggered interrupts usually gets intercepted by a
626                 special hardware circuit).  Hence we have to acknowledge
627                 the timer interrupt.  Through some incredibly stupid
628                 design idea, the reset for IRQ 0 is done by setting the
629                 high bit of the PPI port B (0x61).  Note that some PS/2s,
630                 notably the 55SX, work fine if this is removed.  */
631
632                 irq = inb_p( 0x61 );    /* read the current state */
633                 outb_p( irq|0x80, 0x61 );       /* reset the IRQ */
634         }
635 #endif
636 }
637
638 static int use_tsc;
639
640 /*
641  * This is the same as the above, except we _also_ save the current
642  * Time Stamp Counter value at the time of the timer interrupt, so that
643  * we later on can estimate the time of day more exactly.
644  */
645 static void timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
646 {
647         int count;
648
649         /*
650          * Here we are in the timer irq handler. We just have irqs locally
651          * disabled but we don't know if the timer_bh is running on the other
652          * CPU. We need to avoid to SMP race with it. NOTE: we don' t need
653          * the irq version of write_lock because as just said we have irq
654          * locally disabled. -arca
655          */
656         write_lock(&xtime_lock);
657
658         if(use_cyclone)
659                 mark_timeoffset_cyclone();
660         else if (use_tsc) {
661                 /*
662                  * It is important that these two operations happen almost at
663                  * the same time. We do the RDTSC stuff first, since it's
664                  * faster. To avoid any inconsistencies, we need interrupts
665                  * disabled locally.
666                  */
667
668                 /*
669                  * Interrupts are just disabled locally since the timer irq
670                  * has the SA_INTERRUPT flag set. -arca
671                  */
672         
673                 /* read Pentium cycle counter */
674
675                 rdtscl(last_tsc_low);
676
677                 spin_lock(&i8253_lock);
678                 outb_p(0x00, 0x43);     /* latch the count ASAP */
679
680                 count = inb_p(0x40);    /* read the latched count */
681                 count |= inb(0x40) << 8;
682
683                 /* Any unpaired read will cause the above to swap MSB/LSB
684                    forever.  Try to detect this and reset the counter. 
685                    
686                    This happens very occasionally with buggy SMM bios
687                    code at least */
688                    
689                 if (count > LATCH) {
690                         printk(KERN_WARNING 
691                                "i8253 count too high! resetting..\n");
692                         outb_p(0x34, 0x43);
693                         outb_p(LATCH & 0xff, 0x40);
694                         outb(LATCH >> 8, 0x40);
695                         count = LATCH - 1;
696                 }
697
698                 spin_unlock(&i8253_lock);
699
700                 /* Some i8253 clones hold the LATCH value visible
701                    momentarily as they flip back to zero */
702                 if (count == LATCH) {
703                         count--;
704                 }
705
706                 count = ((LATCH-1) - count) * TICK_SIZE;
707                 delay_at_last_interrupt = (count + LATCH/2) / LATCH;
708         }
709
710         do_timer_interrupt(irq, NULL, regs);
711
712         write_unlock(&xtime_lock);
713
714 }
715
716 /* not static: needed by APM */
717 unsigned long get_cmos_time(void)
718 {
719         unsigned int year, mon, day, hour, min, sec;
720         int i;
721
722         spin_lock(&rtc_lock);
723         /* The Linux interpretation of the CMOS clock register contents:
724          * When the Update-In-Progress (UIP) flag goes from 1 to 0, the
725          * RTC registers show the second which has precisely just started.
726          * Let's hope other operating systems interpret the RTC the same way.
727          */
728         /* read RTC exactly on falling edge of update flag */
729         for (i = 0 ; i < 1000000 ; i++) /* may take up to 1 second... */
730                 if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP)
731                         break;
732         for (i = 0 ; i < 1000000 ; i++) /* must try at least 2.228 ms */
733                 if (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP))
734                         break;
735         do { /* Isn't this overkill ? UIP above should guarantee consistency */
736                 sec = CMOS_READ(RTC_SECONDS);
737                 min = CMOS_READ(RTC_MINUTES);
738                 hour = CMOS_READ(RTC_HOURS);
739                 day = CMOS_READ(RTC_DAY_OF_MONTH);
740                 mon = CMOS_READ(RTC_MONTH);
741                 year = CMOS_READ(RTC_YEAR);
742         } while (sec != CMOS_READ(RTC_SECONDS));
743         if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
744           {
745             BCD_TO_BIN(sec);
746             BCD_TO_BIN(min);
747             BCD_TO_BIN(hour);
748             BCD_TO_BIN(day);
749             BCD_TO_BIN(mon);
750             BCD_TO_BIN(year);
751           }
752         spin_unlock(&rtc_lock);
753         if ((year += 1900) < 1970)
754                 year += 100;
755         return mktime(year, mon, day, hour, min, sec);
756 }
757
758 static struct irqaction irq0  = { timer_interrupt, SA_INTERRUPT, 0, "timer", NULL, NULL};
759
760 /* ------ Calibrate the TSC ------- 
761  * Return 2^32 * (1 / (TSC clocks per usec)) for do_fast_gettimeoffset().
762  * Too much 64-bit arithmetic here to do this cleanly in C, and for
763  * accuracy's sake we want to keep the overhead on the CTC speaker (channel 2)
764  * output busy loop as low as possible. We avoid reading the CTC registers
765  * directly because of the awkward 8-bit access mechanism of the 82C54
766  * device.
767  */
768
769 #define CALIBRATE_LATCH (5 * LATCH)
770 #define CALIBRATE_TIME  (5 * 1000020/HZ)
771
772 static unsigned long __init calibrate_tsc(void)
773 {
774        /* Set the Gate high, disable speaker */
775         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
776
777         /*
778          * Now let's take care of CTC channel 2
779          *
780          * Set the Gate high, program CTC channel 2 for mode 0,
781          * (interrupt on terminal count mode), binary count,
782          * load 5 * LATCH count, (LSB and MSB) to begin countdown.
783          */
784         outb(0xb0, 0x43);                       /* binary, mode 0, LSB/MSB, Ch 2 */
785         outb(CALIBRATE_LATCH & 0xff, 0x42);     /* LSB of count */
786         outb(CALIBRATE_LATCH >> 8, 0x42);       /* MSB of count */
787
788         {
789                 unsigned long startlow, starthigh;
790                 unsigned long endlow, endhigh;
791                 unsigned long count;
792
793                 rdtsc(startlow,starthigh);
794                 count = 0;
795                 do {
796                         count++;
797                 } while ((inb(0x61) & 0x20) == 0);
798                 rdtsc(endlow,endhigh);
799
800                 last_tsc_low = endlow;
801
802                 /* Error: ECTCNEVERSET */
803                 if (count <= 1)
804                         goto bad_ctc;
805
806                 /* 64-bit subtract - gcc just messes up with long longs */
807                 __asm__("subl %2,%0\n\t"
808                         "sbbl %3,%1"
809                         :"=a" (endlow), "=d" (endhigh)
810                         :"g" (startlow), "g" (starthigh),
811                          "0" (endlow), "1" (endhigh));
812
813                 /* Error: ECPUTOOFAST */
814                 if (endhigh)
815                         goto bad_ctc;
816
817                 /* Error: ECPUTOOSLOW */
818                 if (endlow <= CALIBRATE_TIME)
819                         goto bad_ctc;
820
821                 __asm__("divl %2"
822                         :"=a" (endlow), "=d" (endhigh)
823                         :"r" (endlow), "0" (0), "1" (CALIBRATE_TIME));
824
825                 return endlow;
826         }
827
828         /*
829          * The CTC wasn't reliable: we got a hit on the very first read,
830          * or the CPU was so fast/slow that the quotient wouldn't fit in
831          * 32 bits..
832          */
833 bad_ctc:
834         return 0;
835 }
836
837 void __init time_init(void)
838 {
839         extern int x86_udelay_tsc;
840         
841         xtime.tv_sec = get_cmos_time();
842         xtime.tv_usec = 0;
843
844 /*
845  * If we have APM enabled or the CPU clock speed is variable
846  * (CPU stops clock on HLT or slows clock to save power)
847  * then the TSC timestamps may diverge by up to 1 jiffy from
848  * 'real time' but nothing will break.
849  * The most frequent case is that the CPU is "woken" from a halt
850  * state by the timer interrupt itself, so we get 0 error. In the
851  * rare cases where a driver would "wake" the CPU and request a
852  * timestamp, the maximum error is < 1 jiffy. But timestamps are
853  * still perfectly ordered.
854  * Note that the TSC counter will be reset if APM suspends
855  * to disk; this won't break the kernel, though, 'cuz we're
856  * smart.  See arch/i386/kernel/apm.c.
857  */
858         /*
859          *      Firstly we have to do a CPU check for chips with
860          *      a potentially buggy TSC. At this point we haven't run
861          *      the ident/bugs checks so we must run this hook as it
862          *      may turn off the TSC flag.
863          *
864          *      NOTE: this doesnt yet handle SMP 486 machines where only
865          *      some CPU's have a TSC. Thats never worked and nobody has
866          *      moaned if you have the only one in the world - you fix it!
867          */
868  
869         dodgy_tsc();
870
871         if(use_cyclone)
872                 init_cyclone_clock();
873                 
874         if (cpu_has_tsc) {
875                 unsigned long tsc_quotient = calibrate_tsc();
876                 if (tsc_quotient) {
877                         fast_gettimeoffset_quotient = tsc_quotient;
878                         /* XXX: This is messy
879                          * However, we want to allow for the cyclone timer 
880                          * to work w/ or w/o the TSCs being avaliable
881                          *      -johnstul@us.ibm.com
882                          */
883                         if(!use_cyclone){
884                                 /*
885                                  *      We could be more selective here I suspect
886                                  *      and just enable this for the next intel chips ?
887                                  */
888                                 use_tsc = 1;
889                                 x86_udelay_tsc = 1;
890 #ifndef do_gettimeoffset
891                                 do_gettimeoffset = do_fast_gettimeoffset;
892 #endif
893                         }
894                         /* report CPU clock rate in Hz.
895                          * The formula is (10^6 * 2^32) / (2^32 * 1 / (clocks/us)) =
896                          * clock/second. Our precision is about 100 ppm.
897                          */
898                         {       unsigned long eax=0, edx=1000;
899                                 __asm__("divl %2"
900                                 :"=a" (cpu_khz), "=d" (edx)
901                                 :"r" (tsc_quotient),
902                                 "0" (eax), "1" (edx));
903                                 printk("Detected %lu.%03lu MHz processor.\n", cpu_khz / 1000, cpu_khz % 1000);
904                         }
905                 }
906         }
907
908
909 #ifdef CONFIG_VISWS
910         printk("Starting Cobalt Timer system clock\n");
911
912         /* Set the countdown value */
913         co_cpu_write(CO_CPU_TIMEVAL, CO_TIME_HZ/HZ);
914
915         /* Start the timer */
916         co_cpu_write(CO_CPU_CTRL, co_cpu_read(CO_CPU_CTRL) | CO_CTRL_TIMERUN);
917
918         /* Enable (unmask) the timer interrupt */
919         co_cpu_write(CO_CPU_CTRL, co_cpu_read(CO_CPU_CTRL) & ~CO_CTRL_TIMEMASK);
920
921         /* Wire cpu IDT entry to s/w handler (and Cobalt APIC to IDT) */
922         setup_irq(CO_IRQ_TIMER, &irq0);
923 #else
924         setup_irq(0, &irq0);
925 #endif
926 }