ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / arch / x86_64 / kernel / time.c
1 /*
2  *  linux/arch/x86-64/kernel/time.c
3  *
4  *  "High Precision Event Timer" based timekeeping.
5  *
6  *  Copyright (c) 1991,1992,1995  Linus Torvalds
7  *  Copyright (c) 1994  Alan Modra
8  *  Copyright (c) 1995  Markus Kuhn
9  *  Copyright (c) 1996  Ingo Molnar
10  *  Copyright (c) 1998  Andrea Arcangeli
11  *  Copyright (c) 2002  Vojtech Pavlik
12  *  Copyright (c) 2003  Andi Kleen
13  *  RTC support code taken from arch/i386/kernel/timers/time_hpet.c
14  *
15  */
16
17 #include <linux/kernel.h>
18 #include <linux/sched.h>
19 #include <linux/interrupt.h>
20 #include <linux/init.h>
21 #include <linux/mc146818rtc.h>
22 #include <linux/irq.h>
23 #include <linux/time.h>
24 #include <linux/ioport.h>
25 #include <linux/module.h>
26 #include <linux/device.h>
27 #include <linux/sysdev.h>
28 #include <linux/bcd.h>
29 #include <linux/kallsyms.h>
30 #include <asm/pgtable.h>
31 #include <asm/vsyscall.h>
32 #include <asm/timex.h>
33 #include <asm/proto.h>
34 #include <asm/hpet.h>
35 #include <linux/cpufreq.h>
36 #ifdef CONFIG_X86_LOCAL_APIC
37 #include <asm/apic.h>
38 #endif
39
40 u64 jiffies_64 = INITIAL_JIFFIES;
41
42 EXPORT_SYMBOL(jiffies_64);
43
44 extern int using_apic_timer;
45
46 spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
47 spinlock_t i8253_lock = SPIN_LOCK_UNLOCKED;
48
49 static int nohpet __initdata = 0;
50
51 #undef HPET_HACK_ENABLE_DANGEROUS
52
53
54 unsigned int cpu_khz;                                   /* TSC clocks / usec, not used here */
55 unsigned long hpet_period;                              /* fsecs / HPET clock */
56 unsigned long hpet_tick;                                /* HPET clocks / interrupt */
57 unsigned long vxtime_hz = 1193182;
58 int report_lost_ticks;                          /* command line option */
59 unsigned long long monotonic_base;
60
61 struct vxtime_data __vxtime __section_vxtime;   /* for vsyscalls */
62
63 volatile unsigned long __jiffies __section_jiffies = INITIAL_JIFFIES;
64 unsigned long __wall_jiffies __section_wall_jiffies = INITIAL_JIFFIES;
65 struct timespec __xtime __section_xtime;
66 struct timezone __sys_tz __section_sys_tz;
67
68 static inline void rdtscll_sync(unsigned long *tsc)
69 {
70 #ifdef CONFIG_SMP
71         sync_core();
72 #endif
73         rdtscll(*tsc);
74 }
75
76 /*
77  * do_gettimeoffset() returns microseconds since last timer interrupt was
78  * triggered by hardware. A memory read of HPET is slower than a register read
79  * of TSC, but much more reliable. It's also synchronized to the timer
80  * interrupt. Note that do_gettimeoffset() may return more than hpet_tick, if a
81  * timer interrupt has happened already, but vxtime.trigger wasn't updated yet.
82  * This is not a problem, because jiffies hasn't updated either. They are bound
83  * together by xtime_lock.
84          */
85
86 static inline unsigned int do_gettimeoffset_tsc(void)
87 {
88         unsigned long t;
89         unsigned long x;
90         rdtscll_sync(&t);
91         if (t < vxtime.last_tsc) t = vxtime.last_tsc; /* hack */
92         x = ((t - vxtime.last_tsc) * vxtime.tsc_quot) >> 32;
93         return x;
94 }
95
96 static inline unsigned int do_gettimeoffset_hpet(void)
97 {
98         return ((hpet_readl(HPET_COUNTER) - vxtime.last) * vxtime.quot) >> 32;
99 }
100
101 unsigned int (*do_gettimeoffset)(void) = do_gettimeoffset_tsc;
102
103 /*
104  * This version of gettimeofday() has microsecond resolution and better than
105  * microsecond precision, as we're using at least a 10 MHz (usually 14.31818
106  * MHz) HPET timer.
107  */
108
109 void do_gettimeofday(struct timeval *tv)
110 {
111         unsigned long seq, t;
112         unsigned int sec, usec;
113
114         do {
115                 seq = read_seqbegin(&xtime_lock);
116
117                 sec = xtime.tv_sec;
118                 usec = xtime.tv_nsec / 1000;
119
120                 /* i386 does some correction here to keep the clock 
121                    monotonus even when ntpd is fixing drift.
122                    But they didn't work for me, there is a non monotonic
123                    clock anyways with ntp.
124                    I dropped all corrections now until a real solution can
125                    be found. Note when you fix it here you need to do the same
126                    in arch/x86_64/kernel/vsyscall.c and export all needed
127                    variables in vmlinux.lds. -AK */ 
128
129                 t = (jiffies - wall_jiffies) * (1000000L / HZ) +
130                         do_gettimeoffset();
131                 usec += t;
132
133         } while (read_seqretry(&xtime_lock, seq));
134
135         tv->tv_sec = sec + usec / 1000000;
136         tv->tv_usec = usec % 1000000;
137 }
138
139 EXPORT_SYMBOL(do_gettimeofday);
140
141 /*
142  * settimeofday() first undoes the correction that gettimeofday would do
143  * on the time, and then saves it. This is ugly, but has been like this for
144  * ages already.
145  */
146
147 int do_settimeofday(struct timespec *tv)
148 {
149         time_t wtm_sec, sec = tv->tv_sec;
150         long wtm_nsec, nsec = tv->tv_nsec;
151
152         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
153                 return -EINVAL;
154
155         write_seqlock_irq(&xtime_lock);
156
157         nsec -= do_gettimeoffset() * 1000 +
158                 (jiffies - wall_jiffies) * (NSEC_PER_SEC/HZ);
159
160         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
161         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
162
163         set_normalized_timespec(&xtime, sec, nsec);
164         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
165
166         time_adjust = 0;                /* stop active adjtime() */
167         time_status |= STA_UNSYNC;
168         time_maxerror = NTP_PHASE_LIMIT;
169         time_esterror = NTP_PHASE_LIMIT;
170
171         write_sequnlock_irq(&xtime_lock);
172         clock_was_set();
173         return 0;
174 }
175
176 EXPORT_SYMBOL(do_settimeofday);
177
178 /*
179  * In order to set the CMOS clock precisely, set_rtc_mmss has to be called 500
180  * ms after the second nowtime has started, because when nowtime is written
181  * into the registers of the CMOS clock, it will jump to the next second
182  * precisely 500 ms later. Check the Motorola MC146818A or Dallas DS12887 data
183  * sheet for details.
184  */
185
186 static void set_rtc_mmss(unsigned long nowtime)
187 {
188         int real_seconds, real_minutes, cmos_minutes;
189         unsigned char control, freq_select;
190
191 /*
192  * IRQs are disabled when we're called from the timer interrupt,
193  * no need for spin_lock_irqsave()
194  */
195
196         spin_lock(&rtc_lock);
197
198 /*
199  * Tell the clock it's being set and stop it.
200  */
201
202         control = CMOS_READ(RTC_CONTROL);
203         CMOS_WRITE(control | RTC_SET, RTC_CONTROL);
204
205         freq_select = CMOS_READ(RTC_FREQ_SELECT);
206         CMOS_WRITE(freq_select | RTC_DIV_RESET2, RTC_FREQ_SELECT);
207
208         cmos_minutes = CMOS_READ(RTC_MINUTES);
209                 BCD_TO_BIN(cmos_minutes);
210
211 /*
212  * since we're only adjusting minutes and seconds, don't interfere with hour
213  * overflow. This avoids messing with unknown time zones but requires your RTC
214  * not to be off by more than 15 minutes. Since we're calling it only when
215  * our clock is externally synchronized using NTP, this shouldn't be a problem.
216          */
217
218         real_seconds = nowtime % 60;
219         real_minutes = nowtime / 60;
220         if (((abs(real_minutes - cmos_minutes) + 15) / 30) & 1)
221                 real_minutes += 30;             /* correct for half hour time zone */
222         real_minutes %= 60;
223
224 #if 0
225         /* AMD 8111 is a really bad time keeper and hits this regularly. 
226            It probably was an attempt to avoid screwing up DST, but ignore
227            that for now. */        
228         if (abs(real_minutes - cmos_minutes) >= 30) {
229                 printk(KERN_WARNING "time.c: can't update CMOS clock "
230                        "from %d to %d\n", cmos_minutes, real_minutes);
231         } else
232 #endif
233
234         {
235                         BIN_TO_BCD(real_seconds);
236                         BIN_TO_BCD(real_minutes);
237                 CMOS_WRITE(real_seconds, RTC_SECONDS);
238                 CMOS_WRITE(real_minutes, RTC_MINUTES);
239         }
240
241 /*
242  * The following flags have to be released exactly in this order, otherwise the
243  * DS12887 (popular MC146818A clone with integrated battery and quartz) will
244  * not reset the oscillator and will not update precisely 500 ms later. You
245  * won't find this mentioned in the Dallas Semiconductor data sheets, but who
246  * believes data sheets anyway ... -- Markus Kuhn
247  */
248
249         CMOS_WRITE(control, RTC_CONTROL);
250         CMOS_WRITE(freq_select, RTC_FREQ_SELECT);
251
252         spin_unlock(&rtc_lock);
253 }
254
255
256 /* monotonic_clock(): returns # of nanoseconds passed since time_init()
257  *              Note: This function is required to return accurate
258  *              time even in the absence of multiple timer ticks.
259  */
260 unsigned long long monotonic_clock(void)
261 {
262         unsigned long seq;
263         u32 last_offset, this_offset, offset;
264         unsigned long long base;
265
266         if (vxtime.mode == VXTIME_HPET) {
267                 do {
268                         seq = read_seqbegin(&xtime_lock);
269
270                         last_offset = vxtime.last;
271                         base = monotonic_base;
272                         this_offset = hpet_readl(HPET_T0_CMP) - hpet_tick;
273
274                 } while (read_seqretry(&xtime_lock, seq));
275                 offset = (this_offset - last_offset);
276                 offset *=(NSEC_PER_SEC/HZ)/hpet_tick;
277                 return base + offset;
278         }else{
279                 do {
280                         seq = read_seqbegin(&xtime_lock);
281
282                         last_offset = vxtime.last_tsc;
283                         base = monotonic_base;
284                 } while (read_seqretry(&xtime_lock, seq));
285                 sync_core();
286                 rdtscll(this_offset);
287                 offset = (this_offset - last_offset)*1000/cpu_khz; 
288                 return base + offset;
289         }
290
291
292 }
293 EXPORT_SYMBOL(monotonic_clock);
294
295
296 static irqreturn_t timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
297 {
298         static unsigned long rtc_update = 0;
299         unsigned long tsc, lost = 0;
300         int delay, offset = 0;
301
302 /*
303  * Here we are in the timer irq handler. We have irqs locally disabled (so we
304  * don't need spin_lock_irqsave()) but we don't know if the timer_bh is running
305  * on the other CPU, so we need a lock. We also need to lock the vsyscall
306  * variables, because both do_timer() and us change them -arca+vojtech
307          */
308
309         write_seqlock(&xtime_lock);
310
311         if (vxtime.hpet_address) {
312                 offset = hpet_readl(HPET_T0_CMP) - hpet_tick;
313                 delay = hpet_readl(HPET_COUNTER) - offset;
314         } else {
315                 spin_lock(&i8253_lock);
316                 outb_p(0x00, 0x43);
317                 delay = inb_p(0x40);
318                 delay |= inb(0x40) << 8;
319                 spin_unlock(&i8253_lock);
320                 delay = LATCH - 1 - delay;
321         }
322
323         rdtscll_sync(&tsc);
324
325         if (vxtime.mode == VXTIME_HPET) {
326                 if (offset - vxtime.last > hpet_tick) {
327                         lost = (offset - vxtime.last) / hpet_tick - 1;
328                 }
329
330                 monotonic_base += 
331                         (offset - vxtime.last)*(NSEC_PER_SEC/HZ) / hpet_tick;
332
333                 vxtime.last = offset;
334         } else {
335                 offset = (((tsc - vxtime.last_tsc) *
336                            vxtime.tsc_quot) >> 32) - (USEC_PER_SEC / HZ);
337
338                 if (offset < 0)
339                         offset = 0;
340
341                 if (offset > (USEC_PER_SEC / HZ)) {
342                         lost = offset / (USEC_PER_SEC / HZ);
343                         offset %= (USEC_PER_SEC / HZ);
344                 }
345
346                 monotonic_base += (tsc - vxtime.last_tsc)*1000000/cpu_khz ;
347
348                 vxtime.last_tsc = tsc - vxtime.quot * delay / vxtime.tsc_quot;
349
350                 if ((((tsc - vxtime.last_tsc) *
351                       vxtime.tsc_quot) >> 32) < offset)
352                         vxtime.last_tsc = tsc -
353                                 (((long) offset << 32) / vxtime.tsc_quot) - 1;
354         }
355
356         if (lost) {
357                 if (report_lost_ticks) {
358                         printk(KERN_WARNING "time.c: Lost %ld timer "
359                                "tick(s)! ", lost);
360                         print_symbol("rip %s)\n", regs->rip);
361                 }
362                 jiffies += lost;
363         }
364
365 /*
366  * Do the timer stuff.
367  */
368
369         do_timer(regs);
370
371 /*
372  * In the SMP case we use the local APIC timer interrupt to do the profiling,
373  * except when we simulate SMP mode on a uniprocessor system, in that case we
374  * have to call the local interrupt handler.
375  */
376
377 #ifndef CONFIG_X86_LOCAL_APIC
378         x86_do_profile(regs);
379 #else
380         if (!using_apic_timer)
381                 smp_local_timer_interrupt(regs);
382 #endif
383
384 /*
385  * If we have an externally synchronized Linux clock, then update CMOS clock
386  * accordingly every ~11 minutes. set_rtc_mmss() will be called in the jiffy
387  * closest to exactly 500 ms before the next second. If the update fails, we
388  * don't care, as it'll be updated on the next turn, and the problem (time way
389  * off) isn't likely to go away much sooner anyway.
390  */
391
392         if ((~time_status & STA_UNSYNC) && xtime.tv_sec > rtc_update &&
393                 abs(xtime.tv_nsec - 500000000) <= tick_nsec / 2) {
394                 set_rtc_mmss(xtime.tv_sec);
395                 rtc_update = xtime.tv_sec + 660;
396         }
397  
398         write_sequnlock(&xtime_lock);
399
400         return IRQ_HANDLED;
401 }
402
403 static unsigned int cyc2ns_scale;
404 #define CYC2NS_SCALE_FACTOR 10 /* 2^10, carefully chosen */
405
406 static inline void set_cyc2ns_scale(unsigned long cpu_mhz)
407 {
408         cyc2ns_scale = (1000 << CYC2NS_SCALE_FACTOR)/cpu_mhz;
409 }
410
411 static inline unsigned long long cycles_2_ns(unsigned long long cyc)
412 {
413         return (cyc * cyc2ns_scale) >> CYC2NS_SCALE_FACTOR;
414 }
415
416 unsigned long long sched_clock(void)
417 {
418         unsigned long a = 0;
419
420 #if 0
421         /* Don't do a HPET read here. Using TSC always is much faster
422            and HPET may not be mapped yet when the scheduler first runs.
423            Disadvantage is a small drift between CPUs in some configurations,
424            but that should be tolerable. */
425         if (__vxtime.mode == VXTIME_HPET)
426                 return (hpet_readl(HPET_COUNTER) * vxtime.quot) >> 32;
427 #endif
428
429         /* Could do CPU core sync here. Opteron can execute rdtsc speculatively,
430            which means it is not completely exact and may not be monotonous between
431            CPUs. But the errors should be too small to matter for scheduling
432            purposes. */
433
434         rdtscll(a);
435         return cycles_2_ns(a);
436 }
437
438 unsigned long get_cmos_time(void)
439 {
440         unsigned int timeout, year, mon, day, hour, min, sec;
441         unsigned char last, this;
442         unsigned long flags;
443
444 /*
445  * The Linux interpretation of the CMOS clock register contents: When the
446  * Update-In-Progress (UIP) flag goes from 1 to 0, the RTC registers show the
447  * second which has precisely just started. Waiting for this can take up to 1
448  * second, we timeout approximately after 2.4 seconds on a machine with
449  * standard 8.3 MHz ISA bus.
450  */
451
452         spin_lock_irqsave(&rtc_lock, flags);
453
454         timeout = 1000000;
455         last = this = 0;
456
457         while (timeout && last && !this) {
458                 last = this;
459                 this = CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP;
460                 timeout--;
461         }
462
463 /*
464  * Here we are safe to assume the registers won't change for a whole second, so
465  * we just go ahead and read them.
466          */
467
468                 sec = CMOS_READ(RTC_SECONDS);
469                 min = CMOS_READ(RTC_MINUTES);
470                 hour = CMOS_READ(RTC_HOURS);
471                 day = CMOS_READ(RTC_DAY_OF_MONTH);
472                 mon = CMOS_READ(RTC_MONTH);
473                 year = CMOS_READ(RTC_YEAR);
474
475         spin_unlock_irqrestore(&rtc_lock, flags);
476
477 /*
478  * We know that x86-64 always uses BCD format, no need to check the config
479  * register.
480  */
481
482             BCD_TO_BIN(sec);
483             BCD_TO_BIN(min);
484             BCD_TO_BIN(hour);
485             BCD_TO_BIN(day);
486             BCD_TO_BIN(mon);
487             BCD_TO_BIN(year);
488
489 /*
490  * This will work up to Dec 31, 2069.
491  */
492
493         if ((year += 1900) < 1970)
494                 year += 100;
495
496         return mktime(year, mon, day, hour, min, sec);
497 }
498
499 #ifdef CONFIG_CPU_FREQ
500
501 /* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
502    changes.
503    
504    RED-PEN: On SMP we assume all CPUs run with the same frequency.  It's
505    not that important because current Opteron setups do not support
506    scaling on SMP anyroads.
507
508    Should fix up last_tsc too. Currently gettimeofday in the
509    first tick after the change will be slightly wrong. */
510
511 static unsigned int  ref_freq = 0;
512 static unsigned long loops_per_jiffy_ref = 0;
513
514 static unsigned long cpu_khz_ref = 0;
515
516 static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
517                                  void *data)
518 {
519         struct cpufreq_freqs *freq = data;
520         unsigned long *lpj;
521
522 #ifdef CONFIG_SMP
523         lpj = &cpu_data[freq->cpu].loops_per_jiffy;
524 #else
525         lpj = &boot_cpu_data.loops_per_jiffy;
526 #endif
527
528         if (!ref_freq) {
529                 ref_freq = freq->old;
530                 loops_per_jiffy_ref = *lpj;
531                 cpu_khz_ref = cpu_khz;
532         }
533         if ((val == CPUFREQ_PRECHANGE  && freq->old < freq->new) ||
534             (val == CPUFREQ_POSTCHANGE && freq->old > freq->new)) {
535                 *lpj =
536                 cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
537
538                 cpu_khz = cpufreq_scale(cpu_khz_ref, ref_freq, freq->new);
539                 vxtime.tsc_quot = (1000L << 32) / cpu_khz;
540         }
541         
542         set_cyc2ns_scale(cpu_khz_ref / 1000);
543
544         return 0;
545 }
546  
547 static struct notifier_block time_cpufreq_notifier_block = {
548          .notifier_call  = time_cpufreq_notifier
549 };
550 #endif
551
552 /*
553  * calibrate_tsc() calibrates the processor TSC in a very simple way, comparing
554  * it to the HPET timer of known frequency.
555  */
556
557 #define TICK_COUNT 100000000
558
559 static unsigned int __init hpet_calibrate_tsc(void)
560 {
561         int tsc_start, hpet_start;
562         int tsc_now, hpet_now;
563         unsigned long flags;
564
565         local_irq_save(flags);
566         local_irq_disable();
567
568         hpet_start = hpet_readl(HPET_COUNTER);
569         rdtscl(tsc_start);
570
571         do {
572                 local_irq_disable();
573                 hpet_now = hpet_readl(HPET_COUNTER);
574                 sync_core();
575                 rdtscl(tsc_now);
576                 local_irq_restore(flags);
577         } while ((tsc_now - tsc_start) < TICK_COUNT &&
578                  (hpet_now - hpet_start) < TICK_COUNT);
579
580         return (tsc_now - tsc_start) * 1000000000L
581                 / ((hpet_now - hpet_start) * hpet_period / 1000);
582 }
583
584
585 /*
586  * pit_calibrate_tsc() uses the speaker output (channel 2) of
587  * the PIT. This is better than using the timer interrupt output,
588  * because we can read the value of the speaker with just one inb(),
589  * where we need three i/o operations for the interrupt channel.
590  * We count how many ticks the TSC does in 50 ms.
591  */
592
593 static unsigned int __init pit_calibrate_tsc(void)
594 {
595         unsigned long start, end;
596         unsigned long flags;
597
598         spin_lock_irqsave(&i8253_lock, flags);
599
600         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
601
602         outb(0xb0, 0x43);
603         outb((1193182 / (1000 / 50)) & 0xff, 0x42);
604         outb((1193182 / (1000 / 50)) >> 8, 0x42);
605         rdtscll(start);
606         sync_core();
607         while ((inb(0x61) & 0x20) == 0);
608         sync_core();
609         rdtscll(end);
610
611         spin_unlock_irqrestore(&i8253_lock, flags);
612         
613         return (end - start) / 50;
614 }
615
616 static int hpet_init(void)
617 {
618         unsigned int cfg, id;
619
620         if (!vxtime.hpet_address)
621                 return -1;
622         set_fixmap_nocache(FIX_HPET_BASE, vxtime.hpet_address);
623         __set_fixmap(VSYSCALL_HPET, vxtime.hpet_address, PAGE_KERNEL_VSYSCALL_NOCACHE);
624
625 /*
626  * Read the period, compute tick and quotient.
627  */
628
629         id = hpet_readl(HPET_ID);
630
631         if (!(id & HPET_ID_VENDOR) || !(id & HPET_ID_NUMBER) ||
632             !(id & HPET_ID_LEGSUP))
633                 return -1;
634
635         hpet_period = hpet_readl(HPET_PERIOD);
636         if (hpet_period < 100000 || hpet_period > 100000000)
637                 return -1;
638
639         hpet_tick = (1000000000L * (USEC_PER_SEC / HZ) + hpet_period / 2) /
640                 hpet_period;
641
642 /*
643  * Stop the timers and reset the main counter.
644  */
645
646         cfg = hpet_readl(HPET_CFG);
647         cfg &= ~(HPET_CFG_ENABLE | HPET_CFG_LEGACY);
648         hpet_writel(cfg, HPET_CFG);
649         hpet_writel(0, HPET_COUNTER);
650         hpet_writel(0, HPET_COUNTER + 4);
651
652 /*
653  * Set up timer 0, as periodic with first interrupt to happen at hpet_tick,
654  * and period also hpet_tick.
655  */
656
657         hpet_writel(HPET_TN_ENABLE | HPET_TN_PERIODIC | HPET_TN_SETVAL |
658                     HPET_TN_32BIT, HPET_T0_CFG);
659         hpet_writel(hpet_tick, HPET_T0_CMP);
660         hpet_writel(hpet_tick, HPET_T0_CMP); /* AK: why twice? */
661
662 /*
663  * Go!
664  */
665
666         cfg |= HPET_CFG_ENABLE | HPET_CFG_LEGACY;
667         hpet_writel(cfg, HPET_CFG);
668
669         return 0;
670 }
671
672 void __init pit_init(void)
673 {
674         unsigned long flags;
675
676         spin_lock_irqsave(&i8253_lock, flags);
677         outb_p(0x34, 0x43);             /* binary, mode 2, LSB/MSB, ch 0 */
678         outb_p(LATCH & 0xff, 0x40);     /* LSB */
679         outb_p(LATCH >> 8, 0x40);       /* MSB */
680         spin_unlock_irqrestore(&i8253_lock, flags);
681 }
682
683 int __init time_setup(char *str)
684 {
685         report_lost_ticks = 1;
686         return 1;
687 }
688
689 static struct irqaction irq0 = {
690         timer_interrupt, SA_INTERRUPT, 0, "timer", NULL, NULL
691 };
692
693 extern void __init config_acpi_tables(void);
694
695 void __init time_init(void)
696 {
697         char *timename;
698
699 #ifdef HPET_HACK_ENABLE_DANGEROUS
700         if (!vxtime.hpet_address) {
701                 printk(KERN_WARNING "time.c: WARNING: Enabling HPET base "
702                        "manually!\n");
703                 outl(0x800038a0, 0xcf8);
704                 outl(0xff000001, 0xcfc);
705                 outl(0x800038a0, 0xcf8);
706                 hpet_address = inl(0xcfc) & 0xfffffffe;
707                 printk(KERN_WARNING "time.c: WARNING: Enabled HPET "
708                        "at %#lx.\n", hpet_address);
709         }
710 #endif
711         if (nohpet)
712                 vxtime.hpet_address = 0;
713
714         xtime.tv_sec = get_cmos_time();
715         xtime.tv_nsec = 0;
716
717         set_normalized_timespec(&wall_to_monotonic,
718                                 -xtime.tv_sec, -xtime.tv_nsec);
719
720         if (!hpet_init()) {
721                 vxtime_hz = (1000000000000000L + hpet_period / 2) /
722                         hpet_period;
723                 cpu_khz = hpet_calibrate_tsc();
724                 timename = "HPET";
725         } else {
726         pit_init();
727         cpu_khz = pit_calibrate_tsc();
728                 timename = "PIT";
729         }
730
731         printk(KERN_INFO "time.c: Using %ld.%06ld MHz %s timer.\n",
732                vxtime_hz / 1000000, vxtime_hz % 1000000, timename);
733         printk(KERN_INFO "time.c: Detected %d.%03d MHz processor.\n",
734                 cpu_khz / 1000, cpu_khz % 1000);
735         vxtime.mode = VXTIME_TSC;
736         vxtime.quot = (1000000L << 32) / vxtime_hz;
737         vxtime.tsc_quot = (1000L << 32) / cpu_khz;
738         vxtime.hz = vxtime_hz;
739         rdtscll_sync(&vxtime.last_tsc);
740         setup_irq(0, &irq0);
741
742         set_cyc2ns_scale(cpu_khz / 1000);
743
744 #ifdef CONFIG_CPU_FREQ
745         cpufreq_register_notifier(&time_cpufreq_notifier_block, 
746                                   CPUFREQ_TRANSITION_NOTIFIER);
747 #endif
748 }
749
750 void __init time_init_smp(void)
751 {
752         char *timetype;
753
754         if (vxtime.hpet_address) {
755                 timetype = "HPET";
756                 vxtime.last = hpet_readl(HPET_T0_CMP) - hpet_tick;
757                 vxtime.mode = VXTIME_HPET;
758                 do_gettimeoffset = do_gettimeoffset_hpet;
759         } else {
760                 timetype = "PIT/TSC";
761                 vxtime.mode = VXTIME_TSC;
762         }
763         printk(KERN_INFO "time.c: Using %s based timekeeping.\n", timetype);
764 }
765
766 __setup("report_lost_ticks", time_setup);
767
768 static long clock_cmos_diff;
769
770 static int time_suspend(struct sys_device *dev, u32 state)
771 {
772         /*
773          * Estimate time zone so that set_time can update the clock
774          */
775         clock_cmos_diff = -get_cmos_time();
776         clock_cmos_diff += get_seconds();
777         return 0;
778 }
779
780 static int time_resume(struct sys_device *dev)
781 {
782         unsigned long sec = get_cmos_time() + clock_cmos_diff;
783         write_seqlock_irq(&xtime_lock);
784         xtime.tv_sec = sec;
785         xtime.tv_nsec = 0;
786         write_sequnlock_irq(&xtime_lock);
787         return 0;
788 }
789
790 static struct sysdev_class pit_sysclass = {
791         .resume = time_resume,
792         .suspend = time_suspend,
793         set_kset_name("pit"),
794 };
795
796
797 /* XXX this driverfs stuff should probably go elsewhere later -john */
798 static struct sys_device device_i8253 = {
799         .id     = 0,
800         .cls    = &pit_sysclass,
801 };
802
803 static int time_init_device(void)
804 {
805         int error = sysdev_class_register(&pit_sysclass);
806         if (!error)
807                 error = sysdev_register(&device_i8253);
808         return error;
809 }
810
811 device_initcall(time_init_device);
812
813 #ifdef CONFIG_HPET_EMULATE_RTC
814 /* HPET in LegacyReplacement Mode eats up RTC interrupt line. When, HPET
815  * is enabled, we support RTC interrupt functionality in software.
816  * RTC has 3 kinds of interrupts:
817  * 1) Update Interrupt - generate an interrupt, every sec, when RTC clock
818  *    is updated
819  * 2) Alarm Interrupt - generate an interrupt at a specific time of day
820  * 3) Periodic Interrupt - generate periodic interrupt, with frequencies
821  *    2Hz-8192Hz (2Hz-64Hz for non-root user) (all freqs in powers of 2)
822  * (1) and (2) above are implemented using polling at a frequency of
823  * 64 Hz. The exact frequency is a tradeoff between accuracy and interrupt
824  * overhead. (DEFAULT_RTC_INT_FREQ)
825  * For (3), we use interrupts at 64Hz or user specified periodic
826  * frequency, whichever is higher.
827  */
828 #include <linux/mc146818rtc.h>
829 #include <linux/rtc.h>
830
831 extern irqreturn_t rtc_interrupt(int irq, void *dev_id, struct pt_regs *regs);
832
833 #define DEFAULT_RTC_INT_FREQ    64
834 #define RTC_NUM_INTS            1
835
836 static unsigned long UIE_on;
837 static unsigned long prev_update_sec;
838
839 static unsigned long AIE_on;
840 static struct rtc_time alarm_time;
841
842 static unsigned long PIE_on;
843 static unsigned long PIE_freq = DEFAULT_RTC_INT_FREQ;
844 static unsigned long PIE_count;
845
846 static unsigned long hpet_rtc_int_freq; /* RTC interrupt frequency */
847
848 int is_hpet_enabled(void)
849 {
850         return vxtime.hpet_address != 0;
851 }
852
853 /*
854  * Timer 1 for RTC, we do not use periodic interrupt feature,
855  * even if HPET supports periodic interrupts on Timer 1.
856  * The reason being, to set up a periodic interrupt in HPET, we need to
857  * stop the main counter. And if we do that everytime someone diables/enables
858  * RTC, we will have adverse effect on main kernel timer running on Timer 0.
859  * So, for the time being, simulate the periodic interrupt in software.
860  *
861  * hpet_rtc_timer_init() is called for the first time and during subsequent
862  * interuppts reinit happens through hpet_rtc_timer_reinit().
863  */
864 int hpet_rtc_timer_init(void)
865 {
866         unsigned int cfg, cnt;
867         unsigned long flags;
868
869         if (!is_hpet_enabled())
870                 return 0;
871         /*
872          * Set the counter 1 and enable the interrupts.
873          */
874         if (PIE_on && (PIE_freq > DEFAULT_RTC_INT_FREQ))
875                 hpet_rtc_int_freq = PIE_freq;
876         else
877                 hpet_rtc_int_freq = DEFAULT_RTC_INT_FREQ;
878
879         local_irq_save(flags);
880         cnt = hpet_readl(HPET_COUNTER);
881         cnt += ((hpet_tick*HZ)/hpet_rtc_int_freq);
882         hpet_writel(cnt, HPET_T1_CMP);
883         local_irq_restore(flags);
884
885         cfg = hpet_readl(HPET_T1_CFG);
886         cfg |= HPET_TN_ENABLE | HPET_TN_SETVAL | HPET_TN_32BIT;
887         hpet_writel(cfg, HPET_T1_CFG);
888
889         return 1;
890 }
891
892 static void hpet_rtc_timer_reinit(void)
893 {
894         unsigned int cfg, cnt;
895
896         if (!(PIE_on | AIE_on | UIE_on))
897                 return;
898
899         if (PIE_on && (PIE_freq > DEFAULT_RTC_INT_FREQ))
900                 hpet_rtc_int_freq = PIE_freq;
901         else
902                 hpet_rtc_int_freq = DEFAULT_RTC_INT_FREQ;
903
904         /* It is more accurate to use the comparator value than current count.*/
905         cnt = hpet_readl(HPET_T1_CMP);
906         cnt += hpet_tick*HZ/hpet_rtc_int_freq;
907         hpet_writel(cnt, HPET_T1_CMP);
908
909         cfg = hpet_readl(HPET_T1_CFG);
910         cfg |= HPET_TN_ENABLE | HPET_TN_SETVAL | HPET_TN_32BIT;
911         hpet_writel(cfg, HPET_T1_CFG);
912
913         return;
914 }
915
916 /*
917  * The functions below are called from rtc driver.
918  * Return 0 if HPET is not being used.
919  * Otherwise do the necessary changes and return 1.
920  */
921 int hpet_mask_rtc_irq_bit(unsigned long bit_mask)
922 {
923         if (!is_hpet_enabled())
924                 return 0;
925
926         if (bit_mask & RTC_UIE)
927                 UIE_on = 0;
928         if (bit_mask & RTC_PIE)
929                 PIE_on = 0;
930         if (bit_mask & RTC_AIE)
931                 AIE_on = 0;
932
933         return 1;
934 }
935
936 int hpet_set_rtc_irq_bit(unsigned long bit_mask)
937 {
938         int timer_init_reqd = 0;
939
940         if (!is_hpet_enabled())
941                 return 0;
942
943         if (!(PIE_on | AIE_on | UIE_on))
944                 timer_init_reqd = 1;
945
946         if (bit_mask & RTC_UIE) {
947                 UIE_on = 1;
948         }
949         if (bit_mask & RTC_PIE) {
950                 PIE_on = 1;
951                 PIE_count = 0;
952         }
953         if (bit_mask & RTC_AIE) {
954                 AIE_on = 1;
955         }
956
957         if (timer_init_reqd)
958                 hpet_rtc_timer_init();
959
960         return 1;
961 }
962
963 int hpet_set_alarm_time(unsigned char hrs, unsigned char min, unsigned char sec)
964 {
965         if (!is_hpet_enabled())
966                 return 0;
967
968         alarm_time.tm_hour = hrs;
969         alarm_time.tm_min = min;
970         alarm_time.tm_sec = sec;
971
972         return 1;
973 }
974
975 int hpet_set_periodic_freq(unsigned long freq)
976 {
977         if (!is_hpet_enabled())
978                 return 0;
979
980         PIE_freq = freq;
981         PIE_count = 0;
982
983         return 1;
984 }
985
986 int hpet_rtc_dropped_irq(void)
987 {
988         if (!is_hpet_enabled())
989                 return 0;
990
991         return 1;
992 }
993
994 irqreturn_t hpet_rtc_interrupt(int irq, void *dev_id, struct pt_regs *regs)
995 {
996         struct rtc_time curr_time;
997         unsigned long rtc_int_flag = 0;
998         int call_rtc_interrupt = 0;
999
1000         hpet_rtc_timer_reinit();
1001
1002         if (UIE_on | AIE_on) {
1003                 rtc_get_rtc_time(&curr_time);
1004         }
1005         if (UIE_on) {
1006                 if (curr_time.tm_sec != prev_update_sec) {
1007                         /* Set update int info, call real rtc int routine */
1008                         call_rtc_interrupt = 1;
1009                         rtc_int_flag = RTC_UF;
1010                         prev_update_sec = curr_time.tm_sec;
1011                 }
1012         }
1013         if (PIE_on) {
1014                 PIE_count++;
1015                 if (PIE_count >= hpet_rtc_int_freq/PIE_freq) {
1016                         /* Set periodic int info, call real rtc int routine */
1017                         call_rtc_interrupt = 1;
1018                         rtc_int_flag |= RTC_PF;
1019                         PIE_count = 0;
1020                 }
1021         }
1022         if (AIE_on) {
1023                 if ((curr_time.tm_sec == alarm_time.tm_sec) &&
1024                     (curr_time.tm_min == alarm_time.tm_min) &&
1025                     (curr_time.tm_hour == alarm_time.tm_hour)) {
1026                         /* Set alarm int info, call real rtc int routine */
1027                         call_rtc_interrupt = 1;
1028                         rtc_int_flag |= RTC_AF;
1029                 }
1030         }
1031         if (call_rtc_interrupt) {
1032                 rtc_int_flag |= (RTC_IRQF | (RTC_NUM_INTS << 8));
1033                 rtc_interrupt(rtc_int_flag, dev_id, regs);
1034         }
1035         return IRQ_HANDLED;
1036 }
1037 #endif
1038
1039 static int __init nohpet_setup(char *s) 
1040
1041         nohpet = 1;
1042         return 0;
1043
1044
1045 __setup("nohpet", nohpet_setup);