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