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