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