sync hh.org
[hh.org.git] / arch / x86_64 / kernel / time.c
blobe3ef544d2cfb514f1894c232c0e8d38e456a49f7
1 /*
2 * linux/arch/x86-64/kernel/time.c
4 * "High Precision Event Timer" based timekeeping.
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
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/notifier.h>
28 #include <linux/cpu.h>
29 #include <linux/kallsyms.h>
30 #include <linux/acpi.h>
31 #ifdef CONFIG_ACPI
32 #include <acpi/achware.h> /* for PM timer frequency */
33 #include <acpi/acpi_bus.h>
34 #endif
35 #include <asm/8253pit.h>
36 #include <asm/pgtable.h>
37 #include <asm/vsyscall.h>
38 #include <asm/timex.h>
39 #include <asm/proto.h>
40 #include <asm/hpet.h>
41 #include <asm/sections.h>
42 #include <linux/cpufreq.h>
43 #include <linux/hpet.h>
44 #include <asm/apic.h>
46 #ifdef CONFIG_CPU_FREQ
47 static void cpufreq_delayed_get(void);
48 #endif
49 extern void i8254_timer_resume(void);
50 extern int using_apic_timer;
52 static char *timename = NULL;
54 DEFINE_SPINLOCK(rtc_lock);
55 EXPORT_SYMBOL(rtc_lock);
56 DEFINE_SPINLOCK(i8253_lock);
58 int nohpet __initdata = 0;
59 static int notsc __initdata = 0;
61 #define USEC_PER_TICK (USEC_PER_SEC / HZ)
62 #define NSEC_PER_TICK (NSEC_PER_SEC / HZ)
63 #define FSEC_PER_TICK (FSEC_PER_SEC / HZ)
65 #define NS_SCALE 10 /* 2^10, carefully chosen */
66 #define US_SCALE 32 /* 2^32, arbitralrily chosen */
68 unsigned int cpu_khz; /* TSC clocks / usec, not used here */
69 EXPORT_SYMBOL(cpu_khz);
70 static unsigned long hpet_period; /* fsecs / HPET clock */
71 unsigned long hpet_tick; /* HPET clocks / interrupt */
72 int hpet_use_timer; /* Use counter of hpet for time keeping, otherwise PIT */
73 unsigned long vxtime_hz = PIT_TICK_RATE;
74 int report_lost_ticks; /* command line option */
75 unsigned long long monotonic_base;
77 struct vxtime_data __vxtime __section_vxtime; /* for vsyscalls */
79 volatile unsigned long __jiffies __section_jiffies = INITIAL_JIFFIES;
80 struct timespec __xtime __section_xtime;
81 struct timezone __sys_tz __section_sys_tz;
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.
93 static inline unsigned int do_gettimeoffset_tsc(void)
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;
104 static inline unsigned int do_gettimeoffset_hpet(void)
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;
111 unsigned int (*do_gettimeoffset)(void) = do_gettimeoffset_tsc;
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.
119 void do_gettimeofday(struct timeval *tv)
121 unsigned long seq;
122 unsigned int sec, usec;
124 do {
125 seq = read_seqbegin(&xtime_lock);
127 sec = xtime.tv_sec;
128 usec = xtime.tv_nsec / NSEC_PER_USEC;
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 usec += do_gettimeoffset();
140 } while (read_seqretry(&xtime_lock, seq));
142 tv->tv_sec = sec + usec / USEC_PER_SEC;
143 tv->tv_usec = usec % USEC_PER_SEC;
146 EXPORT_SYMBOL(do_gettimeofday);
149 * settimeofday() first undoes the correction that gettimeofday would do
150 * on the time, and then saves it. This is ugly, but has been like this for
151 * ages already.
154 int do_settimeofday(struct timespec *tv)
156 time_t wtm_sec, sec = tv->tv_sec;
157 long wtm_nsec, nsec = tv->tv_nsec;
159 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
160 return -EINVAL;
162 write_seqlock_irq(&xtime_lock);
164 nsec -= do_gettimeoffset() * NSEC_PER_USEC;
166 wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
167 wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
169 set_normalized_timespec(&xtime, sec, nsec);
170 set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
172 ntp_clear();
174 write_sequnlock_irq(&xtime_lock);
175 clock_was_set();
176 return 0;
179 EXPORT_SYMBOL(do_settimeofday);
181 unsigned long profile_pc(struct pt_regs *regs)
183 unsigned long pc = instruction_pointer(regs);
185 /* Assume the lock function has either no stack frame or a copy
186 of eflags from PUSHF
187 Eflags always has bits 22 and up cleared unlike kernel addresses. */
188 if (!user_mode(regs) && in_lock_functions(pc)) {
189 unsigned long *sp = (unsigned long *)regs->rsp;
190 if (sp[0] >> 22)
191 return sp[0];
192 if (sp[1] >> 22)
193 return sp[1];
195 return pc;
197 EXPORT_SYMBOL(profile_pc);
200 * In order to set the CMOS clock precisely, set_rtc_mmss has to be called 500
201 * ms after the second nowtime has started, because when nowtime is written
202 * into the registers of the CMOS clock, it will jump to the next second
203 * precisely 500 ms later. Check the Motorola MC146818A or Dallas DS12887 data
204 * sheet for details.
207 static void set_rtc_mmss(unsigned long nowtime)
209 int real_seconds, real_minutes, cmos_minutes;
210 unsigned char control, freq_select;
213 * IRQs are disabled when we're called from the timer interrupt,
214 * no need for spin_lock_irqsave()
217 spin_lock(&rtc_lock);
220 * Tell the clock it's being set and stop it.
223 control = CMOS_READ(RTC_CONTROL);
224 CMOS_WRITE(control | RTC_SET, RTC_CONTROL);
226 freq_select = CMOS_READ(RTC_FREQ_SELECT);
227 CMOS_WRITE(freq_select | RTC_DIV_RESET2, RTC_FREQ_SELECT);
229 cmos_minutes = CMOS_READ(RTC_MINUTES);
230 BCD_TO_BIN(cmos_minutes);
233 * since we're only adjusting minutes and seconds, don't interfere with hour
234 * overflow. This avoids messing with unknown time zones but requires your RTC
235 * not to be off by more than 15 minutes. Since we're calling it only when
236 * our clock is externally synchronized using NTP, this shouldn't be a problem.
239 real_seconds = nowtime % 60;
240 real_minutes = nowtime / 60;
241 if (((abs(real_minutes - cmos_minutes) + 15) / 30) & 1)
242 real_minutes += 30; /* correct for half hour time zone */
243 real_minutes %= 60;
245 if (abs(real_minutes - cmos_minutes) >= 30) {
246 printk(KERN_WARNING "time.c: can't update CMOS clock "
247 "from %d to %d\n", cmos_minutes, real_minutes);
248 } else {
249 BIN_TO_BCD(real_seconds);
250 BIN_TO_BCD(real_minutes);
251 CMOS_WRITE(real_seconds, RTC_SECONDS);
252 CMOS_WRITE(real_minutes, RTC_MINUTES);
256 * The following flags have to be released exactly in this order, otherwise the
257 * DS12887 (popular MC146818A clone with integrated battery and quartz) will
258 * not reset the oscillator and will not update precisely 500 ms later. You
259 * won't find this mentioned in the Dallas Semiconductor data sheets, but who
260 * believes data sheets anyway ... -- Markus Kuhn
263 CMOS_WRITE(control, RTC_CONTROL);
264 CMOS_WRITE(freq_select, RTC_FREQ_SELECT);
266 spin_unlock(&rtc_lock);
270 /* monotonic_clock(): returns # of nanoseconds passed since time_init()
271 * Note: This function is required to return accurate
272 * time even in the absence of multiple timer ticks.
274 static inline unsigned long long cycles_2_ns(unsigned long long cyc);
275 unsigned long long monotonic_clock(void)
277 unsigned long seq;
278 u32 last_offset, this_offset, offset;
279 unsigned long long base;
281 if (vxtime.mode == VXTIME_HPET) {
282 do {
283 seq = read_seqbegin(&xtime_lock);
285 last_offset = vxtime.last;
286 base = monotonic_base;
287 this_offset = hpet_readl(HPET_COUNTER);
288 } while (read_seqretry(&xtime_lock, seq));
289 offset = (this_offset - last_offset);
290 offset *= NSEC_PER_TICK / hpet_tick;
291 } else {
292 do {
293 seq = read_seqbegin(&xtime_lock);
295 last_offset = vxtime.last_tsc;
296 base = monotonic_base;
297 } while (read_seqretry(&xtime_lock, seq));
298 this_offset = get_cycles_sync();
299 offset = cycles_2_ns(this_offset - last_offset);
301 return base + offset;
303 EXPORT_SYMBOL(monotonic_clock);
305 static noinline void handle_lost_ticks(int lost)
307 static long lost_count;
308 static int warned;
309 if (report_lost_ticks) {
310 printk(KERN_WARNING "time.c: Lost %d timer tick(s)! ", lost);
311 print_symbol("rip %s)\n", get_irq_regs()->rip);
314 if (lost_count == 1000 && !warned) {
315 printk(KERN_WARNING "warning: many lost ticks.\n"
316 KERN_WARNING "Your time source seems to be instable or "
317 "some driver is hogging interupts\n");
318 print_symbol("rip %s\n", get_irq_regs()->rip);
319 if (vxtime.mode == VXTIME_TSC && vxtime.hpet_address) {
320 printk(KERN_WARNING "Falling back to HPET\n");
321 if (hpet_use_timer)
322 vxtime.last = hpet_readl(HPET_T0_CMP) -
323 hpet_tick;
324 else
325 vxtime.last = hpet_readl(HPET_COUNTER);
326 vxtime.mode = VXTIME_HPET;
327 do_gettimeoffset = do_gettimeoffset_hpet;
329 /* else should fall back to PIT, but code missing. */
330 warned = 1;
331 } else
332 lost_count++;
334 #ifdef CONFIG_CPU_FREQ
335 /* In some cases the CPU can change frequency without us noticing
336 Give cpufreq a change to catch up. */
337 if ((lost_count+1) % 25 == 0)
338 cpufreq_delayed_get();
339 #endif
342 void main_timer_handler(void)
344 static unsigned long rtc_update = 0;
345 unsigned long tsc;
346 int delay = 0, offset = 0, lost = 0;
349 * Here we are in the timer irq handler. We have irqs locally disabled (so we
350 * don't need spin_lock_irqsave()) but we don't know if the timer_bh is running
351 * on the other CPU, so we need a lock. We also need to lock the vsyscall
352 * variables, because both do_timer() and us change them -arca+vojtech
355 write_seqlock(&xtime_lock);
357 if (vxtime.hpet_address)
358 offset = hpet_readl(HPET_COUNTER);
360 if (hpet_use_timer) {
361 /* if we're using the hpet timer functionality,
362 * we can more accurately know the counter value
363 * when the timer interrupt occured.
365 offset = hpet_readl(HPET_T0_CMP) - hpet_tick;
366 delay = hpet_readl(HPET_COUNTER) - offset;
367 } else if (!pmtmr_ioport) {
368 spin_lock(&i8253_lock);
369 outb_p(0x00, 0x43);
370 delay = inb_p(0x40);
371 delay |= inb(0x40) << 8;
372 spin_unlock(&i8253_lock);
373 delay = LATCH - 1 - delay;
376 tsc = get_cycles_sync();
378 if (vxtime.mode == VXTIME_HPET) {
379 if (offset - vxtime.last > hpet_tick) {
380 lost = (offset - vxtime.last) / hpet_tick - 1;
383 monotonic_base +=
384 (offset - vxtime.last) * NSEC_PER_TICK / hpet_tick;
386 vxtime.last = offset;
387 #ifdef CONFIG_X86_PM_TIMER
388 } else if (vxtime.mode == VXTIME_PMTMR) {
389 lost = pmtimer_mark_offset();
390 #endif
391 } else {
392 offset = (((tsc - vxtime.last_tsc) *
393 vxtime.tsc_quot) >> US_SCALE) - USEC_PER_TICK;
395 if (offset < 0)
396 offset = 0;
398 if (offset > USEC_PER_TICK) {
399 lost = offset / USEC_PER_TICK;
400 offset %= USEC_PER_TICK;
403 monotonic_base += cycles_2_ns(tsc - vxtime.last_tsc);
405 vxtime.last_tsc = tsc - vxtime.quot * delay / vxtime.tsc_quot;
407 if ((((tsc - vxtime.last_tsc) *
408 vxtime.tsc_quot) >> US_SCALE) < offset)
409 vxtime.last_tsc = tsc -
410 (((long) offset << US_SCALE) / vxtime.tsc_quot) - 1;
413 if (lost > 0)
414 handle_lost_ticks(lost);
415 else
416 lost = 0;
419 * Do the timer stuff.
422 do_timer(lost + 1);
423 #ifndef CONFIG_SMP
424 update_process_times(user_mode(get_irq_regs()));
425 #endif
428 * In the SMP case we use the local APIC timer interrupt to do the profiling,
429 * except when we simulate SMP mode on a uniprocessor system, in that case we
430 * have to call the local interrupt handler.
433 if (!using_apic_timer)
434 smp_local_timer_interrupt();
437 * If we have an externally synchronized Linux clock, then update CMOS clock
438 * accordingly every ~11 minutes. set_rtc_mmss() will be called in the jiffy
439 * closest to exactly 500 ms before the next second. If the update fails, we
440 * don't care, as it'll be updated on the next turn, and the problem (time way
441 * off) isn't likely to go away much sooner anyway.
444 if (ntp_synced() && xtime.tv_sec > rtc_update &&
445 abs(xtime.tv_nsec - 500000000) <= tick_nsec / 2) {
446 set_rtc_mmss(xtime.tv_sec);
447 rtc_update = xtime.tv_sec + 660;
450 write_sequnlock(&xtime_lock);
453 static irqreturn_t timer_interrupt(int irq, void *dev_id)
455 if (apic_runs_main_timer > 1)
456 return IRQ_HANDLED;
457 main_timer_handler();
458 if (using_apic_timer)
459 smp_send_timer_broadcast_ipi();
460 return IRQ_HANDLED;
463 static unsigned int cyc2ns_scale __read_mostly;
465 static inline void set_cyc2ns_scale(unsigned long cpu_khz)
467 cyc2ns_scale = (NSEC_PER_MSEC << NS_SCALE) / cpu_khz;
470 static inline unsigned long long cycles_2_ns(unsigned long long cyc)
472 return (cyc * cyc2ns_scale) >> NS_SCALE;
475 unsigned long long sched_clock(void)
477 unsigned long a = 0;
479 #if 0
480 /* Don't do a HPET read here. Using TSC always is much faster
481 and HPET may not be mapped yet when the scheduler first runs.
482 Disadvantage is a small drift between CPUs in some configurations,
483 but that should be tolerable. */
484 if (__vxtime.mode == VXTIME_HPET)
485 return (hpet_readl(HPET_COUNTER) * vxtime.quot) >> US_SCALE;
486 #endif
488 /* Could do CPU core sync here. Opteron can execute rdtsc speculatively,
489 which means it is not completely exact and may not be monotonous between
490 CPUs. But the errors should be too small to matter for scheduling
491 purposes. */
493 rdtscll(a);
494 return cycles_2_ns(a);
497 static unsigned long get_cmos_time(void)
499 unsigned int year, mon, day, hour, min, sec;
500 unsigned long flags;
501 unsigned extyear = 0;
503 spin_lock_irqsave(&rtc_lock, flags);
505 do {
506 sec = CMOS_READ(RTC_SECONDS);
507 min = CMOS_READ(RTC_MINUTES);
508 hour = CMOS_READ(RTC_HOURS);
509 day = CMOS_READ(RTC_DAY_OF_MONTH);
510 mon = CMOS_READ(RTC_MONTH);
511 year = CMOS_READ(RTC_YEAR);
512 #ifdef CONFIG_ACPI
513 if (acpi_fadt.revision >= FADT2_REVISION_ID &&
514 acpi_fadt.century)
515 extyear = CMOS_READ(acpi_fadt.century);
516 #endif
517 } while (sec != CMOS_READ(RTC_SECONDS));
519 spin_unlock_irqrestore(&rtc_lock, flags);
522 * We know that x86-64 always uses BCD format, no need to check the
523 * config register.
526 BCD_TO_BIN(sec);
527 BCD_TO_BIN(min);
528 BCD_TO_BIN(hour);
529 BCD_TO_BIN(day);
530 BCD_TO_BIN(mon);
531 BCD_TO_BIN(year);
533 if (extyear) {
534 BCD_TO_BIN(extyear);
535 year += extyear;
536 printk(KERN_INFO "Extended CMOS year: %d\n", extyear);
537 } else {
539 * x86-64 systems only exists since 2002.
540 * This will work up to Dec 31, 2100
542 year += 2000;
545 return mktime(year, mon, day, hour, min, sec);
548 #ifdef CONFIG_CPU_FREQ
550 /* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
551 changes.
553 RED-PEN: On SMP we assume all CPUs run with the same frequency. It's
554 not that important because current Opteron setups do not support
555 scaling on SMP anyroads.
557 Should fix up last_tsc too. Currently gettimeofday in the
558 first tick after the change will be slightly wrong. */
560 #include <linux/workqueue.h>
562 static unsigned int cpufreq_delayed_issched = 0;
563 static unsigned int cpufreq_init = 0;
564 static struct work_struct cpufreq_delayed_get_work;
566 static void handle_cpufreq_delayed_get(void *v)
568 unsigned int cpu;
569 for_each_online_cpu(cpu) {
570 cpufreq_get(cpu);
572 cpufreq_delayed_issched = 0;
575 /* if we notice lost ticks, schedule a call to cpufreq_get() as it tries
576 * to verify the CPU frequency the timing core thinks the CPU is running
577 * at is still correct.
579 static void cpufreq_delayed_get(void)
581 static int warned;
582 if (cpufreq_init && !cpufreq_delayed_issched) {
583 cpufreq_delayed_issched = 1;
584 if (!warned) {
585 warned = 1;
586 printk(KERN_DEBUG
587 "Losing some ticks... checking if CPU frequency changed.\n");
589 schedule_work(&cpufreq_delayed_get_work);
593 static unsigned int ref_freq = 0;
594 static unsigned long loops_per_jiffy_ref = 0;
596 static unsigned long cpu_khz_ref = 0;
598 static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
599 void *data)
601 struct cpufreq_freqs *freq = data;
602 unsigned long *lpj, dummy;
604 if (cpu_has(&cpu_data[freq->cpu], X86_FEATURE_CONSTANT_TSC))
605 return 0;
607 lpj = &dummy;
608 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
609 #ifdef CONFIG_SMP
610 lpj = &cpu_data[freq->cpu].loops_per_jiffy;
611 #else
612 lpj = &boot_cpu_data.loops_per_jiffy;
613 #endif
615 if (!ref_freq) {
616 ref_freq = freq->old;
617 loops_per_jiffy_ref = *lpj;
618 cpu_khz_ref = cpu_khz;
620 if ((val == CPUFREQ_PRECHANGE && freq->old < freq->new) ||
621 (val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
622 (val == CPUFREQ_RESUMECHANGE)) {
623 *lpj =
624 cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
626 cpu_khz = cpufreq_scale(cpu_khz_ref, ref_freq, freq->new);
627 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
628 vxtime.tsc_quot = (USEC_PER_MSEC << US_SCALE) / cpu_khz;
631 set_cyc2ns_scale(cpu_khz_ref);
633 return 0;
636 static struct notifier_block time_cpufreq_notifier_block = {
637 .notifier_call = time_cpufreq_notifier
640 static int __init cpufreq_tsc(void)
642 INIT_WORK(&cpufreq_delayed_get_work, handle_cpufreq_delayed_get, NULL);
643 if (!cpufreq_register_notifier(&time_cpufreq_notifier_block,
644 CPUFREQ_TRANSITION_NOTIFIER))
645 cpufreq_init = 1;
646 return 0;
649 core_initcall(cpufreq_tsc);
651 #endif
654 * calibrate_tsc() calibrates the processor TSC in a very simple way, comparing
655 * it to the HPET timer of known frequency.
658 #define TICK_COUNT 100000000
660 static unsigned int __init hpet_calibrate_tsc(void)
662 int tsc_start, hpet_start;
663 int tsc_now, hpet_now;
664 unsigned long flags;
666 local_irq_save(flags);
667 local_irq_disable();
669 hpet_start = hpet_readl(HPET_COUNTER);
670 rdtscl(tsc_start);
672 do {
673 local_irq_disable();
674 hpet_now = hpet_readl(HPET_COUNTER);
675 tsc_now = get_cycles_sync();
676 local_irq_restore(flags);
677 } while ((tsc_now - tsc_start) < TICK_COUNT &&
678 (hpet_now - hpet_start) < TICK_COUNT);
680 return (tsc_now - tsc_start) * 1000000000L
681 / ((hpet_now - hpet_start) * hpet_period / 1000);
686 * pit_calibrate_tsc() uses the speaker output (channel 2) of
687 * the PIT. This is better than using the timer interrupt output,
688 * because we can read the value of the speaker with just one inb(),
689 * where we need three i/o operations for the interrupt channel.
690 * We count how many ticks the TSC does in 50 ms.
693 static unsigned int __init pit_calibrate_tsc(void)
695 unsigned long start, end;
696 unsigned long flags;
698 spin_lock_irqsave(&i8253_lock, flags);
700 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
702 outb(0xb0, 0x43);
703 outb((PIT_TICK_RATE / (1000 / 50)) & 0xff, 0x42);
704 outb((PIT_TICK_RATE / (1000 / 50)) >> 8, 0x42);
705 start = get_cycles_sync();
706 while ((inb(0x61) & 0x20) == 0);
707 end = get_cycles_sync();
709 spin_unlock_irqrestore(&i8253_lock, flags);
711 return (end - start) / 50;
714 #ifdef CONFIG_HPET
715 static __init int late_hpet_init(void)
717 struct hpet_data hd;
718 unsigned int ntimer;
720 if (!vxtime.hpet_address)
721 return 0;
723 memset(&hd, 0, sizeof (hd));
725 ntimer = hpet_readl(HPET_ID);
726 ntimer = (ntimer & HPET_ID_NUMBER) >> HPET_ID_NUMBER_SHIFT;
727 ntimer++;
730 * Register with driver.
731 * Timer0 and Timer1 is used by platform.
733 hd.hd_phys_address = vxtime.hpet_address;
734 hd.hd_address = (void __iomem *)fix_to_virt(FIX_HPET_BASE);
735 hd.hd_nirqs = ntimer;
736 hd.hd_flags = HPET_DATA_PLATFORM;
737 hpet_reserve_timer(&hd, 0);
738 #ifdef CONFIG_HPET_EMULATE_RTC
739 hpet_reserve_timer(&hd, 1);
740 #endif
741 hd.hd_irq[0] = HPET_LEGACY_8254;
742 hd.hd_irq[1] = HPET_LEGACY_RTC;
743 if (ntimer > 2) {
744 struct hpet *hpet;
745 struct hpet_timer *timer;
746 int i;
748 hpet = (struct hpet *) fix_to_virt(FIX_HPET_BASE);
749 timer = &hpet->hpet_timers[2];
750 for (i = 2; i < ntimer; timer++, i++)
751 hd.hd_irq[i] = (timer->hpet_config &
752 Tn_INT_ROUTE_CNF_MASK) >>
753 Tn_INT_ROUTE_CNF_SHIFT;
757 hpet_alloc(&hd);
758 return 0;
760 fs_initcall(late_hpet_init);
761 #endif
763 static int hpet_timer_stop_set_go(unsigned long tick)
765 unsigned int cfg;
768 * Stop the timers and reset the main counter.
771 cfg = hpet_readl(HPET_CFG);
772 cfg &= ~(HPET_CFG_ENABLE | HPET_CFG_LEGACY);
773 hpet_writel(cfg, HPET_CFG);
774 hpet_writel(0, HPET_COUNTER);
775 hpet_writel(0, HPET_COUNTER + 4);
778 * Set up timer 0, as periodic with first interrupt to happen at hpet_tick,
779 * and period also hpet_tick.
781 if (hpet_use_timer) {
782 hpet_writel(HPET_TN_ENABLE | HPET_TN_PERIODIC | HPET_TN_SETVAL |
783 HPET_TN_32BIT, HPET_T0_CFG);
784 hpet_writel(hpet_tick, HPET_T0_CMP); /* next interrupt */
785 hpet_writel(hpet_tick, HPET_T0_CMP); /* period */
786 cfg |= HPET_CFG_LEGACY;
789 * Go!
792 cfg |= HPET_CFG_ENABLE;
793 hpet_writel(cfg, HPET_CFG);
795 return 0;
798 static int hpet_init(void)
800 unsigned int id;
802 if (!vxtime.hpet_address)
803 return -1;
804 set_fixmap_nocache(FIX_HPET_BASE, vxtime.hpet_address);
805 __set_fixmap(VSYSCALL_HPET, vxtime.hpet_address, PAGE_KERNEL_VSYSCALL_NOCACHE);
808 * Read the period, compute tick and quotient.
811 id = hpet_readl(HPET_ID);
813 if (!(id & HPET_ID_VENDOR) || !(id & HPET_ID_NUMBER))
814 return -1;
816 hpet_period = hpet_readl(HPET_PERIOD);
817 if (hpet_period < 100000 || hpet_period > 100000000)
818 return -1;
820 hpet_tick = (FSEC_PER_TICK + hpet_period / 2) / hpet_period;
822 hpet_use_timer = (id & HPET_ID_LEGSUP);
824 return hpet_timer_stop_set_go(hpet_tick);
827 static int hpet_reenable(void)
829 return hpet_timer_stop_set_go(hpet_tick);
832 #define PIT_MODE 0x43
833 #define PIT_CH0 0x40
835 static void __init __pit_init(int val, u8 mode)
837 unsigned long flags;
839 spin_lock_irqsave(&i8253_lock, flags);
840 outb_p(mode, PIT_MODE);
841 outb_p(val & 0xff, PIT_CH0); /* LSB */
842 outb_p(val >> 8, PIT_CH0); /* MSB */
843 spin_unlock_irqrestore(&i8253_lock, flags);
846 void __init pit_init(void)
848 __pit_init(LATCH, 0x34); /* binary, mode 2, LSB/MSB, ch 0 */
851 void __init pit_stop_interrupt(void)
853 __pit_init(0, 0x30); /* mode 0 */
856 void __init stop_timer_interrupt(void)
858 char *name;
859 if (vxtime.hpet_address) {
860 name = "HPET";
861 hpet_timer_stop_set_go(0);
862 } else {
863 name = "PIT";
864 pit_stop_interrupt();
866 printk(KERN_INFO "timer: %s interrupt stopped.\n", name);
869 int __init time_setup(char *str)
871 report_lost_ticks = 1;
872 return 1;
875 static struct irqaction irq0 = {
876 timer_interrupt, IRQF_DISABLED, CPU_MASK_NONE, "timer", NULL, NULL
879 void __init time_init(void)
881 if (nohpet)
882 vxtime.hpet_address = 0;
884 xtime.tv_sec = get_cmos_time();
885 xtime.tv_nsec = 0;
887 set_normalized_timespec(&wall_to_monotonic,
888 -xtime.tv_sec, -xtime.tv_nsec);
890 if (!hpet_init())
891 vxtime_hz = (FSEC_PER_SEC + hpet_period / 2) / hpet_period;
892 else
893 vxtime.hpet_address = 0;
895 if (hpet_use_timer) {
896 /* set tick_nsec to use the proper rate for HPET */
897 tick_nsec = TICK_NSEC_HPET;
898 cpu_khz = hpet_calibrate_tsc();
899 timename = "HPET";
900 #ifdef CONFIG_X86_PM_TIMER
901 } else if (pmtmr_ioport && !vxtime.hpet_address) {
902 vxtime_hz = PM_TIMER_FREQUENCY;
903 timename = "PM";
904 pit_init();
905 cpu_khz = pit_calibrate_tsc();
906 #endif
907 } else {
908 pit_init();
909 cpu_khz = pit_calibrate_tsc();
910 timename = "PIT";
913 vxtime.mode = VXTIME_TSC;
914 vxtime.quot = (USEC_PER_SEC << US_SCALE) / vxtime_hz;
915 vxtime.tsc_quot = (USEC_PER_MSEC << US_SCALE) / cpu_khz;
916 vxtime.last_tsc = get_cycles_sync();
917 set_cyc2ns_scale(cpu_khz);
918 setup_irq(0, &irq0);
920 #ifndef CONFIG_SMP
921 time_init_gtod();
922 #endif
926 * Make an educated guess if the TSC is trustworthy and synchronized
927 * over all CPUs.
929 __cpuinit int unsynchronized_tsc(void)
931 #ifdef CONFIG_SMP
932 if (apic_is_clustered_box())
933 return 1;
934 #endif
935 /* Most intel systems have synchronized TSCs except for
936 multi node systems */
937 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) {
938 #ifdef CONFIG_ACPI
939 /* But TSC doesn't tick in C3 so don't use it there */
940 if (acpi_fadt.length > 0 && acpi_fadt.plvl3_lat < 1000)
941 return 1;
942 #endif
943 return 0;
946 /* Assume multi socket systems are not synchronized */
947 return num_present_cpus() > 1;
951 * Decide what mode gettimeofday should use.
953 void time_init_gtod(void)
955 char *timetype;
957 if (unsynchronized_tsc())
958 notsc = 1;
960 if (cpu_has(&boot_cpu_data, X86_FEATURE_RDTSCP))
961 vgetcpu_mode = VGETCPU_RDTSCP;
962 else
963 vgetcpu_mode = VGETCPU_LSL;
965 if (vxtime.hpet_address && notsc) {
966 timetype = hpet_use_timer ? "HPET" : "PIT/HPET";
967 if (hpet_use_timer)
968 vxtime.last = hpet_readl(HPET_T0_CMP) - hpet_tick;
969 else
970 vxtime.last = hpet_readl(HPET_COUNTER);
971 vxtime.mode = VXTIME_HPET;
972 do_gettimeoffset = do_gettimeoffset_hpet;
973 #ifdef CONFIG_X86_PM_TIMER
974 /* Using PM for gettimeofday is quite slow, but we have no other
975 choice because the TSC is too unreliable on some systems. */
976 } else if (pmtmr_ioport && !vxtime.hpet_address && notsc) {
977 timetype = "PM";
978 do_gettimeoffset = do_gettimeoffset_pm;
979 vxtime.mode = VXTIME_PMTMR;
980 sysctl_vsyscall = 0;
981 printk(KERN_INFO "Disabling vsyscall due to use of PM timer\n");
982 #endif
983 } else {
984 timetype = hpet_use_timer ? "HPET/TSC" : "PIT/TSC";
985 vxtime.mode = VXTIME_TSC;
988 printk(KERN_INFO "time.c: Using %ld.%06ld MHz WALL %s GTOD %s timer.\n",
989 vxtime_hz / 1000000, vxtime_hz % 1000000, timename, timetype);
990 printk(KERN_INFO "time.c: Detected %d.%03d MHz processor.\n",
991 cpu_khz / 1000, cpu_khz % 1000);
992 vxtime.quot = (USEC_PER_SEC << US_SCALE) / vxtime_hz;
993 vxtime.tsc_quot = (USEC_PER_MSEC << US_SCALE) / cpu_khz;
994 vxtime.last_tsc = get_cycles_sync();
996 set_cyc2ns_scale(cpu_khz);
999 __setup("report_lost_ticks", time_setup);
1001 static long clock_cmos_diff;
1002 static unsigned long sleep_start;
1005 * sysfs support for the timer.
1008 static int timer_suspend(struct sys_device *dev, pm_message_t state)
1011 * Estimate time zone so that set_time can update the clock
1013 long cmos_time = get_cmos_time();
1015 clock_cmos_diff = -cmos_time;
1016 clock_cmos_diff += get_seconds();
1017 sleep_start = cmos_time;
1018 return 0;
1021 static int timer_resume(struct sys_device *dev)
1023 unsigned long flags;
1024 unsigned long sec;
1025 unsigned long ctime = get_cmos_time();
1026 long sleep_length = (ctime - sleep_start) * HZ;
1028 if (sleep_length < 0) {
1029 printk(KERN_WARNING "Time skew detected in timer resume!\n");
1030 /* The time after the resume must not be earlier than the time
1031 * before the suspend or some nasty things will happen
1033 sleep_length = 0;
1034 ctime = sleep_start;
1036 if (vxtime.hpet_address)
1037 hpet_reenable();
1038 else
1039 i8254_timer_resume();
1041 sec = ctime + clock_cmos_diff;
1042 write_seqlock_irqsave(&xtime_lock,flags);
1043 xtime.tv_sec = sec;
1044 xtime.tv_nsec = 0;
1045 if (vxtime.mode == VXTIME_HPET) {
1046 if (hpet_use_timer)
1047 vxtime.last = hpet_readl(HPET_T0_CMP) - hpet_tick;
1048 else
1049 vxtime.last = hpet_readl(HPET_COUNTER);
1050 #ifdef CONFIG_X86_PM_TIMER
1051 } else if (vxtime.mode == VXTIME_PMTMR) {
1052 pmtimer_resume();
1053 #endif
1054 } else
1055 vxtime.last_tsc = get_cycles_sync();
1056 write_sequnlock_irqrestore(&xtime_lock,flags);
1057 jiffies += sleep_length;
1058 monotonic_base += sleep_length * (NSEC_PER_SEC/HZ);
1059 touch_softlockup_watchdog();
1060 return 0;
1063 static struct sysdev_class timer_sysclass = {
1064 .resume = timer_resume,
1065 .suspend = timer_suspend,
1066 set_kset_name("timer"),
1069 /* XXX this driverfs stuff should probably go elsewhere later -john */
1070 static struct sys_device device_timer = {
1071 .id = 0,
1072 .cls = &timer_sysclass,
1075 static int time_init_device(void)
1077 int error = sysdev_class_register(&timer_sysclass);
1078 if (!error)
1079 error = sysdev_register(&device_timer);
1080 return error;
1083 device_initcall(time_init_device);
1085 #ifdef CONFIG_HPET_EMULATE_RTC
1086 /* HPET in LegacyReplacement Mode eats up RTC interrupt line. When, HPET
1087 * is enabled, we support RTC interrupt functionality in software.
1088 * RTC has 3 kinds of interrupts:
1089 * 1) Update Interrupt - generate an interrupt, every sec, when RTC clock
1090 * is updated
1091 * 2) Alarm Interrupt - generate an interrupt at a specific time of day
1092 * 3) Periodic Interrupt - generate periodic interrupt, with frequencies
1093 * 2Hz-8192Hz (2Hz-64Hz for non-root user) (all freqs in powers of 2)
1094 * (1) and (2) above are implemented using polling at a frequency of
1095 * 64 Hz. The exact frequency is a tradeoff between accuracy and interrupt
1096 * overhead. (DEFAULT_RTC_INT_FREQ)
1097 * For (3), we use interrupts at 64Hz or user specified periodic
1098 * frequency, whichever is higher.
1100 #include <linux/rtc.h>
1102 #define DEFAULT_RTC_INT_FREQ 64
1103 #define RTC_NUM_INTS 1
1105 static unsigned long UIE_on;
1106 static unsigned long prev_update_sec;
1108 static unsigned long AIE_on;
1109 static struct rtc_time alarm_time;
1111 static unsigned long PIE_on;
1112 static unsigned long PIE_freq = DEFAULT_RTC_INT_FREQ;
1113 static unsigned long PIE_count;
1115 static unsigned long hpet_rtc_int_freq; /* RTC interrupt frequency */
1116 static unsigned int hpet_t1_cmp; /* cached comparator register */
1118 int is_hpet_enabled(void)
1120 return vxtime.hpet_address != 0;
1124 * Timer 1 for RTC, we do not use periodic interrupt feature,
1125 * even if HPET supports periodic interrupts on Timer 1.
1126 * The reason being, to set up a periodic interrupt in HPET, we need to
1127 * stop the main counter. And if we do that everytime someone diables/enables
1128 * RTC, we will have adverse effect on main kernel timer running on Timer 0.
1129 * So, for the time being, simulate the periodic interrupt in software.
1131 * hpet_rtc_timer_init() is called for the first time and during subsequent
1132 * interuppts reinit happens through hpet_rtc_timer_reinit().
1134 int hpet_rtc_timer_init(void)
1136 unsigned int cfg, cnt;
1137 unsigned long flags;
1139 if (!is_hpet_enabled())
1140 return 0;
1142 * Set the counter 1 and enable the interrupts.
1144 if (PIE_on && (PIE_freq > DEFAULT_RTC_INT_FREQ))
1145 hpet_rtc_int_freq = PIE_freq;
1146 else
1147 hpet_rtc_int_freq = DEFAULT_RTC_INT_FREQ;
1149 local_irq_save(flags);
1151 cnt = hpet_readl(HPET_COUNTER);
1152 cnt += ((hpet_tick*HZ)/hpet_rtc_int_freq);
1153 hpet_writel(cnt, HPET_T1_CMP);
1154 hpet_t1_cmp = cnt;
1156 cfg = hpet_readl(HPET_T1_CFG);
1157 cfg &= ~HPET_TN_PERIODIC;
1158 cfg |= HPET_TN_ENABLE | HPET_TN_32BIT;
1159 hpet_writel(cfg, HPET_T1_CFG);
1161 local_irq_restore(flags);
1163 return 1;
1166 static void hpet_rtc_timer_reinit(void)
1168 unsigned int cfg, cnt, ticks_per_int, lost_ints;
1170 if (unlikely(!(PIE_on | AIE_on | UIE_on))) {
1171 cfg = hpet_readl(HPET_T1_CFG);
1172 cfg &= ~HPET_TN_ENABLE;
1173 hpet_writel(cfg, HPET_T1_CFG);
1174 return;
1177 if (PIE_on && (PIE_freq > DEFAULT_RTC_INT_FREQ))
1178 hpet_rtc_int_freq = PIE_freq;
1179 else
1180 hpet_rtc_int_freq = DEFAULT_RTC_INT_FREQ;
1182 /* It is more accurate to use the comparator value than current count.*/
1183 ticks_per_int = hpet_tick * HZ / hpet_rtc_int_freq;
1184 hpet_t1_cmp += ticks_per_int;
1185 hpet_writel(hpet_t1_cmp, HPET_T1_CMP);
1188 * If the interrupt handler was delayed too long, the write above tries
1189 * to schedule the next interrupt in the past and the hardware would
1190 * not interrupt until the counter had wrapped around.
1191 * So we have to check that the comparator wasn't set to a past time.
1193 cnt = hpet_readl(HPET_COUNTER);
1194 if (unlikely((int)(cnt - hpet_t1_cmp) > 0)) {
1195 lost_ints = (cnt - hpet_t1_cmp) / ticks_per_int + 1;
1196 /* Make sure that, even with the time needed to execute
1197 * this code, the next scheduled interrupt has been moved
1198 * back to the future: */
1199 lost_ints++;
1201 hpet_t1_cmp += lost_ints * ticks_per_int;
1202 hpet_writel(hpet_t1_cmp, HPET_T1_CMP);
1204 if (PIE_on)
1205 PIE_count += lost_ints;
1207 printk(KERN_WARNING "rtc: lost some interrupts at %ldHz.\n",
1208 hpet_rtc_int_freq);
1213 * The functions below are called from rtc driver.
1214 * Return 0 if HPET is not being used.
1215 * Otherwise do the necessary changes and return 1.
1217 int hpet_mask_rtc_irq_bit(unsigned long bit_mask)
1219 if (!is_hpet_enabled())
1220 return 0;
1222 if (bit_mask & RTC_UIE)
1223 UIE_on = 0;
1224 if (bit_mask & RTC_PIE)
1225 PIE_on = 0;
1226 if (bit_mask & RTC_AIE)
1227 AIE_on = 0;
1229 return 1;
1232 int hpet_set_rtc_irq_bit(unsigned long bit_mask)
1234 int timer_init_reqd = 0;
1236 if (!is_hpet_enabled())
1237 return 0;
1239 if (!(PIE_on | AIE_on | UIE_on))
1240 timer_init_reqd = 1;
1242 if (bit_mask & RTC_UIE) {
1243 UIE_on = 1;
1245 if (bit_mask & RTC_PIE) {
1246 PIE_on = 1;
1247 PIE_count = 0;
1249 if (bit_mask & RTC_AIE) {
1250 AIE_on = 1;
1253 if (timer_init_reqd)
1254 hpet_rtc_timer_init();
1256 return 1;
1259 int hpet_set_alarm_time(unsigned char hrs, unsigned char min, unsigned char sec)
1261 if (!is_hpet_enabled())
1262 return 0;
1264 alarm_time.tm_hour = hrs;
1265 alarm_time.tm_min = min;
1266 alarm_time.tm_sec = sec;
1268 return 1;
1271 int hpet_set_periodic_freq(unsigned long freq)
1273 if (!is_hpet_enabled())
1274 return 0;
1276 PIE_freq = freq;
1277 PIE_count = 0;
1279 return 1;
1282 int hpet_rtc_dropped_irq(void)
1284 if (!is_hpet_enabled())
1285 return 0;
1287 return 1;
1290 irqreturn_t hpet_rtc_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1292 struct rtc_time curr_time;
1293 unsigned long rtc_int_flag = 0;
1294 int call_rtc_interrupt = 0;
1296 hpet_rtc_timer_reinit();
1298 if (UIE_on | AIE_on) {
1299 rtc_get_rtc_time(&curr_time);
1301 if (UIE_on) {
1302 if (curr_time.tm_sec != prev_update_sec) {
1303 /* Set update int info, call real rtc int routine */
1304 call_rtc_interrupt = 1;
1305 rtc_int_flag = RTC_UF;
1306 prev_update_sec = curr_time.tm_sec;
1309 if (PIE_on) {
1310 PIE_count++;
1311 if (PIE_count >= hpet_rtc_int_freq/PIE_freq) {
1312 /* Set periodic int info, call real rtc int routine */
1313 call_rtc_interrupt = 1;
1314 rtc_int_flag |= RTC_PF;
1315 PIE_count = 0;
1318 if (AIE_on) {
1319 if ((curr_time.tm_sec == alarm_time.tm_sec) &&
1320 (curr_time.tm_min == alarm_time.tm_min) &&
1321 (curr_time.tm_hour == alarm_time.tm_hour)) {
1322 /* Set alarm int info, call real rtc int routine */
1323 call_rtc_interrupt = 1;
1324 rtc_int_flag |= RTC_AF;
1327 if (call_rtc_interrupt) {
1328 rtc_int_flag |= (RTC_IRQF | (RTC_NUM_INTS << 8));
1329 rtc_interrupt(rtc_int_flag, dev_id);
1331 return IRQ_HANDLED;
1333 #endif
1335 static int __init nohpet_setup(char *s)
1337 nohpet = 1;
1338 return 1;
1341 __setup("nohpet", nohpet_setup);
1343 int __init notsc_setup(char *s)
1345 notsc = 1;
1346 return 1;
1349 __setup("notsc", notsc_setup);