debuggers.hg

view xen/arch/x86/time.c @ 17986:f2148e532c81

x86 hvm: Fix RTC handling.
1. Clean up initialisation/destruction.
2. Better handle per-domain time-offset changes.
Signed-off-by: Keir Fraser <keir.fraser@citrix.com>
author Keir Fraser <keir.fraser@citrix.com>
date Wed Jul 02 17:25:05 2008 +0100 (2008-07-02)
parents 8182f5158dc2
children 79517ed2a108
line source
1 /******************************************************************************
2 * arch/x86/time.c
3 *
4 * Per-CPU time calibration and management.
5 *
6 * Copyright (c) 2002-2005, K A Fraser
7 *
8 * Portions from Linux are:
9 * Copyright (c) 1991, 1992, 1995 Linus Torvalds
10 */
12 #include <xen/config.h>
13 #include <xen/errno.h>
14 #include <xen/event.h>
15 #include <xen/sched.h>
16 #include <xen/lib.h>
17 #include <xen/config.h>
18 #include <xen/init.h>
19 #include <xen/time.h>
20 #include <xen/timer.h>
21 #include <xen/smp.h>
22 #include <xen/irq.h>
23 #include <xen/softirq.h>
24 #include <asm/io.h>
25 #include <asm/msr.h>
26 #include <asm/mpspec.h>
27 #include <asm/processor.h>
28 #include <asm/fixmap.h>
29 #include <asm/mc146818rtc.h>
30 #include <asm/div64.h>
31 #include <asm/hpet.h>
32 #include <io_ports.h>
34 /* opt_clocksource: Force clocksource to one of: pit, hpet, cyclone, acpi. */
35 static char opt_clocksource[10];
36 string_param("clocksource", opt_clocksource);
38 #define EPOCH MILLISECS(1000)
40 unsigned long cpu_khz; /* CPU clock frequency in kHz. */
41 DEFINE_SPINLOCK(rtc_lock);
42 unsigned long pit0_ticks;
43 static u32 wc_sec, wc_nsec; /* UTC time at last 'time update'. */
44 static DEFINE_SPINLOCK(wc_lock);
46 struct time_scale {
47 int shift;
48 u32 mul_frac;
49 };
51 struct cpu_time {
52 u64 local_tsc_stamp;
53 u64 cstate_tsc_stamp;
54 s_time_t stime_local_stamp;
55 s_time_t stime_master_stamp;
56 struct time_scale tsc_scale;
57 u32 cstate_plt_count_stamp;
58 struct timer calibration_timer;
59 };
61 struct platform_timesource {
62 char *name;
63 u64 frequency;
64 u32 (*read_counter)(void);
65 int counter_bits;
66 };
68 static DEFINE_PER_CPU(struct cpu_time, cpu_time);
70 /* TSC is invariant on C state entry? */
71 static bool_t tsc_invariant;
73 /*
74 * We simulate a 32-bit platform timer from the 16-bit PIT ch2 counter.
75 * Otherwise overflow happens too quickly (~50ms) for us to guarantee that
76 * softirq handling will happen in time.
77 *
78 * The pit_lock protects the 16- and 32-bit stamp fields as well as the
79 */
80 static DEFINE_SPINLOCK(pit_lock);
81 static u16 pit_stamp16;
82 static u32 pit_stamp32;
83 static int using_pit;
85 /*
86 * 32-bit division of integer dividend and integer divisor yielding
87 * 32-bit fractional quotient.
88 */
89 static inline u32 div_frac(u32 dividend, u32 divisor)
90 {
91 u32 quotient, remainder;
92 ASSERT(dividend < divisor);
93 asm (
94 "divl %4"
95 : "=a" (quotient), "=d" (remainder)
96 : "0" (0), "1" (dividend), "r" (divisor) );
97 return quotient;
98 }
100 /*
101 * 32-bit multiplication of multiplicand and fractional multiplier
102 * yielding 32-bit product (radix point at same position as in multiplicand).
103 */
104 static inline u32 mul_frac(u32 multiplicand, u32 multiplier)
105 {
106 u32 product_int, product_frac;
107 asm (
108 "mul %3"
109 : "=a" (product_frac), "=d" (product_int)
110 : "0" (multiplicand), "r" (multiplier) );
111 return product_int;
112 }
114 /*
115 * Scale a 64-bit delta by scaling and multiplying by a 32-bit fraction,
116 * yielding a 64-bit result.
117 */
118 static inline u64 scale_delta(u64 delta, struct time_scale *scale)
119 {
120 u64 product;
121 #ifdef CONFIG_X86_32
122 u32 tmp1, tmp2;
123 #endif
125 if ( scale->shift < 0 )
126 delta >>= -scale->shift;
127 else
128 delta <<= scale->shift;
130 #ifdef CONFIG_X86_32
131 asm (
132 "mul %5 ; "
133 "mov %4,%%eax ; "
134 "mov %%edx,%4 ; "
135 "mul %5 ; "
136 "xor %5,%5 ; "
137 "add %4,%%eax ; "
138 "adc %5,%%edx ; "
139 : "=A" (product), "=r" (tmp1), "=r" (tmp2)
140 : "a" ((u32)delta), "1" ((u32)(delta >> 32)), "2" (scale->mul_frac) );
141 #else
142 asm (
143 "mul %%rdx ; shrd $32,%%rdx,%%rax"
144 : "=a" (product) : "0" (delta), "d" ((u64)scale->mul_frac) );
145 #endif
147 return product;
148 }
150 static void timer_interrupt(int irq, void *dev_id, struct cpu_user_regs *regs)
151 {
152 ASSERT(local_irq_is_enabled());
154 if ( hpet_legacy_irq_tick() )
155 return;
157 /* Only for start-of-day interruopt tests in io_apic.c. */
158 (*(volatile unsigned long *)&pit0_ticks)++;
160 /* Rough hack to allow accurate timers to sort-of-work with no APIC. */
161 if ( !cpu_has_apic )
162 raise_softirq(TIMER_SOFTIRQ);
164 /* Emulate a 32-bit PIT counter. */
165 if ( using_pit )
166 {
167 u16 count;
169 spin_lock_irq(&pit_lock);
171 outb(0x80, PIT_MODE);
172 count = inb(PIT_CH2);
173 count |= inb(PIT_CH2) << 8;
175 pit_stamp32 += (u16)(pit_stamp16 - count);
176 pit_stamp16 = count;
178 spin_unlock_irq(&pit_lock);
179 }
180 }
182 static struct irqaction irq0 = { timer_interrupt, "timer", NULL };
184 /* ------ Calibrate the TSC -------
185 * Return processor ticks per second / CALIBRATE_FRAC.
186 */
188 #define CLOCK_TICK_RATE 1193180 /* system crystal frequency (Hz) */
189 #define CALIBRATE_FRAC 20 /* calibrate over 50ms */
190 #define CALIBRATE_LATCH ((CLOCK_TICK_RATE+(CALIBRATE_FRAC/2))/CALIBRATE_FRAC)
192 static u64 init_pit_and_calibrate_tsc(void)
193 {
194 u64 start, end;
195 unsigned long count;
197 /* Set PIT channel 0 to HZ Hz. */
198 #define LATCH (((CLOCK_TICK_RATE)+(HZ/2))/HZ)
199 outb_p(0x34, PIT_MODE); /* binary, mode 2, LSB/MSB, ch 0 */
200 outb_p(LATCH & 0xff, PIT_CH0); /* LSB */
201 outb(LATCH >> 8, PIT_CH0); /* MSB */
203 /* Set the Gate high, disable speaker */
204 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
206 /*
207 * Now let's take care of CTC channel 2
208 *
209 * Set the Gate high, program CTC channel 2 for mode 0, (interrupt on
210 * terminal count mode), binary count, load 5 * LATCH count, (LSB and MSB)
211 * to begin countdown.
212 */
213 outb(0xb0, PIT_MODE); /* binary, mode 0, LSB/MSB, Ch 2 */
214 outb(CALIBRATE_LATCH & 0xff, PIT_CH2); /* LSB of count */
215 outb(CALIBRATE_LATCH >> 8, PIT_CH2); /* MSB of count */
217 rdtscll(start);
218 for ( count = 0; (inb(0x61) & 0x20) == 0; count++ )
219 continue;
220 rdtscll(end);
222 /* Error if the CTC doesn't behave itself. */
223 if ( count == 0 )
224 return 0;
226 return ((end - start) * (u64)CALIBRATE_FRAC);
227 }
229 static void set_time_scale(struct time_scale *ts, u64 ticks_per_sec)
230 {
231 u64 tps64 = ticks_per_sec;
232 u32 tps32;
233 int shift = 0;
235 ASSERT(tps64 != 0);
237 while ( tps64 > (MILLISECS(1000)*2) )
238 {
239 tps64 >>= 1;
240 shift--;
241 }
243 tps32 = (u32)tps64;
244 while ( tps32 <= (u32)MILLISECS(1000) )
245 {
246 tps32 <<= 1;
247 shift++;
248 }
250 ts->mul_frac = div_frac(MILLISECS(1000), tps32);
251 ts->shift = shift;
252 }
254 static atomic_t tsc_calibrate_gang = ATOMIC_INIT(0);
255 static unsigned int tsc_calibrate_status = 0;
257 void calibrate_tsc_bp(void)
258 {
259 while ( atomic_read(&tsc_calibrate_gang) != (num_booting_cpus() - 1) )
260 mb();
262 outb(CALIBRATE_LATCH & 0xff, PIT_CH2);
263 outb(CALIBRATE_LATCH >> 8, PIT_CH2);
265 tsc_calibrate_status = 1;
266 wmb();
268 while ( (inb(0x61) & 0x20) == 0 )
269 continue;
271 tsc_calibrate_status = 2;
272 wmb();
274 while ( atomic_read(&tsc_calibrate_gang) != 0 )
275 mb();
276 }
278 void calibrate_tsc_ap(void)
279 {
280 u64 t1, t2, ticks_per_sec;
282 atomic_inc(&tsc_calibrate_gang);
284 while ( tsc_calibrate_status < 1 )
285 mb();
287 rdtscll(t1);
289 while ( tsc_calibrate_status < 2 )
290 mb();
292 rdtscll(t2);
294 ticks_per_sec = (t2 - t1) * (u64)CALIBRATE_FRAC;
295 set_time_scale(&this_cpu(cpu_time).tsc_scale, ticks_per_sec);
297 atomic_dec(&tsc_calibrate_gang);
298 }
300 static char *freq_string(u64 freq)
301 {
302 static char s[20];
303 unsigned int x, y;
304 y = (unsigned int)do_div(freq, 1000000) / 1000;
305 x = (unsigned int)freq;
306 snprintf(s, sizeof(s), "%u.%03uMHz", x, y);
307 return s;
308 }
310 /************************************************************
311 * PLATFORM TIMER 1: PROGRAMMABLE INTERVAL TIMER (LEGACY PIT)
312 */
314 static u32 read_pit_count(void)
315 {
316 u16 count16;
317 u32 count32;
318 unsigned long flags;
320 spin_lock_irqsave(&pit_lock, flags);
322 outb(0x80, PIT_MODE);
323 count16 = inb(PIT_CH2);
324 count16 |= inb(PIT_CH2) << 8;
326 count32 = pit_stamp32 + (u16)(pit_stamp16 - count16);
328 spin_unlock_irqrestore(&pit_lock, flags);
330 return count32;
331 }
333 static void init_pit(struct platform_timesource *pts)
334 {
335 pts->name = "PIT";
336 pts->frequency = CLOCK_TICK_RATE;
337 pts->read_counter = read_pit_count;
338 pts->counter_bits = 32;
339 using_pit = 1;
340 }
342 /************************************************************
343 * PLATFORM TIMER 2: HIGH PRECISION EVENT TIMER (HPET)
344 */
346 static u32 read_hpet_count(void)
347 {
348 return hpet_read32(HPET_COUNTER);
349 }
351 static int init_hpet(struct platform_timesource *pts)
352 {
353 u64 hpet_rate = hpet_setup();
355 if ( hpet_rate == 0 )
356 return 0;
358 pts->name = "HPET";
359 pts->frequency = hpet_rate;
360 pts->read_counter = read_hpet_count;
361 pts->counter_bits = 32;
363 return 1;
364 }
366 /************************************************************
367 * PLATFORM TIMER 3: IBM 'CYCLONE' TIMER
368 */
370 int use_cyclone;
372 /*
373 * Although the counter is read via a 64-bit register, I believe it is actually
374 * a 40-bit counter. Since this will wrap, I read only the low 32 bits and
375 * periodically fold into a 64-bit software counter, just as for PIT and HPET.
376 */
377 #define CYCLONE_CBAR_ADDR 0xFEB00CD0
378 #define CYCLONE_PMCC_OFFSET 0x51A0
379 #define CYCLONE_MPMC_OFFSET 0x51D0
380 #define CYCLONE_MPCS_OFFSET 0x51A8
381 #define CYCLONE_TIMER_FREQ 100000000
383 /* Cyclone MPMC0 register. */
384 static volatile u32 *cyclone_timer;
386 static u32 read_cyclone_count(void)
387 {
388 return *cyclone_timer;
389 }
391 static volatile u32 *map_cyclone_reg(unsigned long regaddr)
392 {
393 unsigned long pageaddr = regaddr & PAGE_MASK;
394 unsigned long offset = regaddr & ~PAGE_MASK;
395 set_fixmap_nocache(FIX_CYCLONE_TIMER, pageaddr);
396 return (volatile u32 *)(fix_to_virt(FIX_CYCLONE_TIMER) + offset);
397 }
399 static int init_cyclone(struct platform_timesource *pts)
400 {
401 u32 base;
403 if ( !use_cyclone )
404 return 0;
406 /* Find base address. */
407 base = *(map_cyclone_reg(CYCLONE_CBAR_ADDR));
408 if ( base == 0 )
409 {
410 printk(KERN_ERR "Cyclone: Could not find valid CBAR value.\n");
411 return 0;
412 }
414 /* Enable timer and map the counter register. */
415 *(map_cyclone_reg(base + CYCLONE_PMCC_OFFSET)) = 1;
416 *(map_cyclone_reg(base + CYCLONE_MPCS_OFFSET)) = 1;
417 cyclone_timer = map_cyclone_reg(base + CYCLONE_MPMC_OFFSET);
419 pts->name = "IBM Cyclone";
420 pts->frequency = CYCLONE_TIMER_FREQ;
421 pts->read_counter = read_cyclone_count;
422 pts->counter_bits = 32;
424 return 1;
425 }
427 /************************************************************
428 * PLATFORM TIMER 4: ACPI PM TIMER
429 */
431 u32 pmtmr_ioport;
433 /* ACPI PM timer ticks at 3.579545 MHz. */
434 #define ACPI_PM_FREQUENCY 3579545
436 static u32 read_pmtimer_count(void)
437 {
438 return inl(pmtmr_ioport);
439 }
441 static int init_pmtimer(struct platform_timesource *pts)
442 {
443 if ( pmtmr_ioport == 0 )
444 return 0;
446 pts->name = "ACPI PM Timer";
447 pts->frequency = ACPI_PM_FREQUENCY;
448 pts->read_counter = read_pmtimer_count;
449 pts->counter_bits = 24;
451 return 1;
452 }
454 /************************************************************
455 * GENERIC PLATFORM TIMER INFRASTRUCTURE
456 */
458 static struct platform_timesource plt_src; /* details of chosen timesource */
459 static u32 plt_mask; /* hardware-width mask */
460 static u64 plt_overflow_period; /* ns between calls to plt_overflow() */
461 static struct time_scale plt_scale; /* scale: platform counter -> nanosecs */
463 /* Protected by platform_timer_lock. */
464 static DEFINE_SPINLOCK(platform_timer_lock);
465 static s_time_t stime_platform_stamp; /* System time at below platform time */
466 static u64 platform_timer_stamp; /* Platform time at above system time */
467 static u64 plt_stamp64; /* 64-bit platform counter stamp */
468 static u32 plt_stamp; /* hardware-width platform counter stamp */
469 static struct timer plt_overflow_timer;
471 static void plt_overflow(void *unused)
472 {
473 u32 count;
475 spin_lock(&platform_timer_lock);
476 count = plt_src.read_counter();
477 plt_stamp64 += (count - plt_stamp) & plt_mask;
478 plt_stamp = count;
479 spin_unlock(&platform_timer_lock);
481 set_timer(&plt_overflow_timer, NOW() + plt_overflow_period);
482 }
484 static s_time_t __read_platform_stime(u64 platform_time)
485 {
486 u64 diff = platform_time - platform_timer_stamp;
487 ASSERT(spin_is_locked(&platform_timer_lock));
488 return (stime_platform_stamp + scale_delta(diff, &plt_scale));
489 }
491 static s_time_t read_platform_stime(void)
492 {
493 u64 count;
494 s_time_t stime;
496 spin_lock(&platform_timer_lock);
497 count = plt_stamp64 + ((plt_src.read_counter() - plt_stamp) & plt_mask);
498 stime = __read_platform_stime(count);
499 spin_unlock(&platform_timer_lock);
501 return stime;
502 }
504 static void platform_time_calibration(void)
505 {
506 u64 count;
507 s_time_t stamp;
509 spin_lock(&platform_timer_lock);
510 count = plt_stamp64 + ((plt_src.read_counter() - plt_stamp) & plt_mask);
511 stamp = __read_platform_stime(count);
512 stime_platform_stamp = stamp;
513 platform_timer_stamp = count;
514 spin_unlock(&platform_timer_lock);
515 }
517 static void resume_platform_timer(void)
518 {
519 /* No change in platform_stime across suspend/resume. */
520 platform_timer_stamp = plt_stamp64;
521 plt_stamp = plt_src.read_counter();
522 }
524 static void init_platform_timer(void)
525 {
526 struct platform_timesource *pts = &plt_src;
527 int rc = -1;
529 if ( opt_clocksource[0] != '\0' )
530 {
531 if ( !strcmp(opt_clocksource, "pit") )
532 rc = (init_pit(pts), 1);
533 else if ( !strcmp(opt_clocksource, "hpet") )
534 rc = init_hpet(pts);
535 else if ( !strcmp(opt_clocksource, "cyclone") )
536 rc = init_cyclone(pts);
537 else if ( !strcmp(opt_clocksource, "acpi") )
538 rc = init_pmtimer(pts);
540 if ( rc <= 0 )
541 printk("WARNING: %s clocksource '%s'.\n",
542 (rc == 0) ? "Could not initialise" : "Unrecognised",
543 opt_clocksource);
544 }
546 if ( (rc <= 0) &&
547 !init_cyclone(pts) &&
548 !init_hpet(pts) &&
549 !init_pmtimer(pts) )
550 init_pit(pts);
552 plt_mask = (u32)~0u >> (32 - pts->counter_bits);
554 set_time_scale(&plt_scale, pts->frequency);
556 plt_overflow_period = scale_delta(
557 1ull << (pts->counter_bits-1), &plt_scale);
558 init_timer(&plt_overflow_timer, plt_overflow, NULL, 0);
559 plt_overflow(NULL);
561 platform_timer_stamp = plt_stamp64;
563 printk("Platform timer is %s %s\n",
564 freq_string(pts->frequency), pts->name);
565 }
567 void cstate_save_tsc(void)
568 {
569 struct cpu_time *t = &this_cpu(cpu_time);
571 if (!tsc_invariant){
572 t->cstate_plt_count_stamp = plt_src.read_counter();
573 rdtscll(t->cstate_tsc_stamp);
574 }
575 }
577 void cstate_restore_tsc(void)
578 {
579 struct cpu_time *t;
580 u32 plt_count_delta;
581 u64 tsc_delta;
583 if (!tsc_invariant){
584 t = &this_cpu(cpu_time);
586 /* if platform counter overflow happens, interrupt will bring CPU from
587 C state to working state, so the platform counter won't wrap the
588 cstate_plt_count_stamp, and the 32 bit unsigned platform counter
589 is enough for delta calculation
590 */
591 plt_count_delta =
592 (plt_src.read_counter() - t->cstate_plt_count_stamp) & plt_mask;
593 tsc_delta = scale_delta(plt_count_delta, &plt_scale)*cpu_khz/1000000UL;
594 wrmsrl(MSR_IA32_TSC, t->cstate_tsc_stamp + tsc_delta);
595 }
596 }
598 /***************************************************************************
599 * CMOS Timer functions
600 ***************************************************************************/
602 /* Converts Gregorian date to seconds since 1970-01-01 00:00:00.
603 * Assumes input in normal date format, i.e. 1980-12-31 23:59:59
604 * => year=1980, mon=12, day=31, hour=23, min=59, sec=59.
605 *
606 * [For the Julian calendar (which was used in Russia before 1917,
607 * Britain & colonies before 1752, anywhere else before 1582,
608 * and is still in use by some communities) leave out the
609 * -year/100+year/400 terms, and add 10.]
610 *
611 * This algorithm was first published by Gauss (I think).
612 *
613 * WARNING: this function will overflow on 2106-02-07 06:28:16 on
614 * machines were long is 32-bit! (However, as time_t is signed, we
615 * will already get problems at other places on 2038-01-19 03:14:08)
616 */
617 unsigned long
618 mktime (unsigned int year, unsigned int mon,
619 unsigned int day, unsigned int hour,
620 unsigned int min, unsigned int sec)
621 {
622 /* 1..12 -> 11,12,1..10: put Feb last since it has a leap day. */
623 if ( 0 >= (int) (mon -= 2) )
624 {
625 mon += 12;
626 year -= 1;
627 }
629 return ((((unsigned long)(year/4 - year/100 + year/400 + 367*mon/12 + day)+
630 year*365 - 719499
631 )*24 + hour /* now have hours */
632 )*60 + min /* now have minutes */
633 )*60 + sec; /* finally seconds */
634 }
636 static unsigned long __get_cmos_time(void)
637 {
638 unsigned int year, mon, day, hour, min, sec;
640 sec = CMOS_READ(RTC_SECONDS);
641 min = CMOS_READ(RTC_MINUTES);
642 hour = CMOS_READ(RTC_HOURS);
643 day = CMOS_READ(RTC_DAY_OF_MONTH);
644 mon = CMOS_READ(RTC_MONTH);
645 year = CMOS_READ(RTC_YEAR);
647 if ( !(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD )
648 {
649 BCD_TO_BIN(sec);
650 BCD_TO_BIN(min);
651 BCD_TO_BIN(hour);
652 BCD_TO_BIN(day);
653 BCD_TO_BIN(mon);
654 BCD_TO_BIN(year);
655 }
657 if ( (year += 1900) < 1970 )
658 year += 100;
660 return mktime(year, mon, day, hour, min, sec);
661 }
663 static unsigned long get_cmos_time(void)
664 {
665 unsigned long res, flags;
666 int i;
668 spin_lock_irqsave(&rtc_lock, flags);
670 /* read RTC exactly on falling edge of update flag */
671 for ( i = 0 ; i < 1000000 ; i++ ) /* may take up to 1 second... */
672 if ( (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) )
673 break;
674 for ( i = 0 ; i < 1000000 ; i++ ) /* must try at least 2.228 ms */
675 if ( !(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) )
676 break;
678 res = __get_cmos_time();
680 spin_unlock_irqrestore(&rtc_lock, flags);
681 return res;
682 }
684 /***************************************************************************
685 * System Time
686 ***************************************************************************/
688 s_time_t get_s_time(void)
689 {
690 struct cpu_time *t = &this_cpu(cpu_time);
691 u64 tsc, delta;
692 s_time_t now;
694 rdtscll(tsc);
695 delta = tsc - t->local_tsc_stamp;
696 now = t->stime_local_stamp + scale_delta(delta, &t->tsc_scale);
698 return now;
699 }
701 static inline void version_update_begin(u32 *version)
702 {
703 /* Explicitly OR with 1 just in case version number gets out of sync. */
704 *version = (*version + 1) | 1;
705 wmb();
706 }
708 static inline void version_update_end(u32 *version)
709 {
710 wmb();
711 (*version)++;
712 }
714 void update_vcpu_system_time(struct vcpu *v)
715 {
716 struct cpu_time *t;
717 struct vcpu_time_info *u;
719 if ( v->vcpu_info == NULL )
720 return;
722 t = &this_cpu(cpu_time);
723 u = &vcpu_info(v, time);
725 if ( u->tsc_timestamp == t->local_tsc_stamp )
726 return;
728 version_update_begin(&u->version);
730 u->tsc_timestamp = t->local_tsc_stamp;
731 u->system_time = t->stime_local_stamp;
732 u->tsc_to_system_mul = t->tsc_scale.mul_frac;
733 u->tsc_shift = (s8)t->tsc_scale.shift;
735 version_update_end(&u->version);
736 }
738 void update_domain_wallclock_time(struct domain *d)
739 {
740 spin_lock(&wc_lock);
741 version_update_begin(&shared_info(d, wc_version));
742 shared_info(d, wc_sec) = wc_sec + d->time_offset_seconds;
743 shared_info(d, wc_nsec) = wc_nsec;
744 version_update_end(&shared_info(d, wc_version));
745 spin_unlock(&wc_lock);
746 }
748 void domain_set_time_offset(struct domain *d, int32_t time_offset_seconds)
749 {
750 d->time_offset_seconds = time_offset_seconds;
751 if ( is_hvm_domain(d) )
752 rtc_update_clock(d);
753 }
755 int cpu_frequency_change(u64 freq)
756 {
757 struct cpu_time *t = &this_cpu(cpu_time);
758 u64 curr_tsc;
760 /* Sanity check: CPU frequency allegedly dropping below 1MHz? */
761 if ( freq < 1000000u )
762 {
763 gdprintk(XENLOG_WARNING, "Rejecting CPU frequency change "
764 "to %"PRIu64" Hz.\n", freq);
765 return -EINVAL;
766 }
768 local_irq_disable();
769 /* Platform time /first/, as we may be delayed by platform_timer_lock. */
770 t->stime_master_stamp = read_platform_stime();
771 /* TSC-extrapolated time may be bogus after frequency change. */
772 /*t->stime_local_stamp = get_s_time();*/
773 t->stime_local_stamp = t->stime_master_stamp;
774 rdtscll(curr_tsc);
775 t->local_tsc_stamp = curr_tsc;
776 set_time_scale(&t->tsc_scale, freq);
777 local_irq_enable();
779 /* A full epoch should pass before we check for deviation. */
780 set_timer(&t->calibration_timer, NOW() + EPOCH);
781 if ( smp_processor_id() == 0 )
782 platform_time_calibration();
784 return 0;
785 }
787 /* Set clock to <secs,usecs> after 00:00:00 UTC, 1 January, 1970. */
788 void do_settime(unsigned long secs, unsigned long nsecs, u64 system_time_base)
789 {
790 u64 x;
791 u32 y, _wc_sec, _wc_nsec;
792 struct domain *d;
794 x = (secs * 1000000000ULL) + (u64)nsecs - system_time_base;
795 y = do_div(x, 1000000000);
797 spin_lock(&wc_lock);
798 wc_sec = _wc_sec = (u32)x;
799 wc_nsec = _wc_nsec = (u32)y;
800 spin_unlock(&wc_lock);
802 rcu_read_lock(&domlist_read_lock);
803 for_each_domain ( d )
804 update_domain_wallclock_time(d);
805 rcu_read_unlock(&domlist_read_lock);
806 }
808 static void local_time_calibration(void *unused)
809 {
810 struct cpu_time *t = &this_cpu(cpu_time);
812 /*
813 * System timestamps, extrapolated from local and master oscillators,
814 * taken during this calibration and the previous calibration.
815 */
816 s_time_t prev_local_stime, curr_local_stime;
817 s_time_t prev_master_stime, curr_master_stime;
819 /* TSC timestamps taken during this calibration and prev calibration. */
820 u64 prev_tsc, curr_tsc;
822 /*
823 * System time and TSC ticks elapsed during the previous calibration
824 * 'epoch'. These values are down-shifted to fit in 32 bits.
825 */
826 u64 stime_elapsed64, tsc_elapsed64;
827 u32 stime_elapsed32, tsc_elapsed32;
829 /* The accumulated error in the local estimate. */
830 u64 local_stime_err;
832 /* Error correction to slow down a fast local clock. */
833 u32 error_factor = 0;
835 /* Calculated TSC shift to ensure 32-bit scale multiplier. */
836 int tsc_shift = 0;
838 /* The overall calibration scale multiplier. */
839 u32 calibration_mul_frac;
841 prev_tsc = t->local_tsc_stamp;
842 prev_local_stime = t->stime_local_stamp;
843 prev_master_stime = t->stime_master_stamp;
845 /*
846 * Disable IRQs to get 'instantaneous' current timestamps. We read platform
847 * time first, as we may be delayed when acquiring platform_timer_lock.
848 */
849 local_irq_disable();
850 curr_master_stime = read_platform_stime();
851 curr_local_stime = get_s_time();
852 rdtscll(curr_tsc);
853 local_irq_enable();
855 #if 0
856 printk("PRE%d: tsc=%"PRIu64" stime=%"PRIu64" master=%"PRIu64"\n",
857 smp_processor_id(), prev_tsc, prev_local_stime, prev_master_stime);
858 printk("CUR%d: tsc=%"PRIu64" stime=%"PRIu64" master=%"PRIu64
859 " -> %"PRId64"\n",
860 smp_processor_id(), curr_tsc, curr_local_stime, curr_master_stime,
861 curr_master_stime - curr_local_stime);
862 #endif
864 /* Local time warps forward if it lags behind master time. */
865 if ( curr_local_stime < curr_master_stime )
866 curr_local_stime = curr_master_stime;
868 stime_elapsed64 = curr_master_stime - prev_master_stime;
869 tsc_elapsed64 = curr_tsc - prev_tsc;
871 /*
872 * Weirdness can happen if we lose sync with the platform timer.
873 * We could be smarter here: resync platform timer with local timer?
874 */
875 if ( ((s64)stime_elapsed64 < (EPOCH / 2)) )
876 goto out;
878 /*
879 * Calculate error-correction factor. This only slows down a fast local
880 * clock (slow clocks are warped forwards). The scale factor is clamped
881 * to >= 0.5.
882 */
883 if ( curr_local_stime != curr_master_stime )
884 {
885 local_stime_err = curr_local_stime - curr_master_stime;
886 if ( local_stime_err > EPOCH )
887 local_stime_err = EPOCH;
888 error_factor = div_frac(EPOCH, EPOCH + (u32)local_stime_err);
889 }
891 /*
892 * We require 0 < stime_elapsed < 2^31.
893 * This allows us to binary shift a 32-bit tsc_elapsed such that:
894 * stime_elapsed < tsc_elapsed <= 2*stime_elapsed
895 */
896 while ( ((u32)stime_elapsed64 != stime_elapsed64) ||
897 ((s32)stime_elapsed64 < 0) )
898 {
899 stime_elapsed64 >>= 1;
900 tsc_elapsed64 >>= 1;
901 }
903 /* stime_master_diff now fits in a 32-bit word. */
904 stime_elapsed32 = (u32)stime_elapsed64;
906 /* tsc_elapsed <= 2*stime_elapsed */
907 while ( tsc_elapsed64 > (stime_elapsed32 * 2) )
908 {
909 tsc_elapsed64 >>= 1;
910 tsc_shift--;
911 }
913 /* Local difference must now fit in 32 bits. */
914 ASSERT((u32)tsc_elapsed64 == tsc_elapsed64);
915 tsc_elapsed32 = (u32)tsc_elapsed64;
917 /* tsc_elapsed > stime_elapsed */
918 ASSERT(tsc_elapsed32 != 0);
919 while ( tsc_elapsed32 <= stime_elapsed32 )
920 {
921 tsc_elapsed32 <<= 1;
922 tsc_shift++;
923 }
925 calibration_mul_frac = div_frac(stime_elapsed32, tsc_elapsed32);
926 if ( error_factor != 0 )
927 calibration_mul_frac = mul_frac(calibration_mul_frac, error_factor);
929 #if 0
930 printk("---%d: %08x %08x %d\n", smp_processor_id(),
931 error_factor, calibration_mul_frac, tsc_shift);
932 #endif
934 /* Record new timestamp information, atomically w.r.t. interrupts. */
935 local_irq_disable();
936 t->tsc_scale.mul_frac = calibration_mul_frac;
937 t->tsc_scale.shift = tsc_shift;
938 t->local_tsc_stamp = curr_tsc;
939 t->stime_local_stamp = curr_local_stime;
940 t->stime_master_stamp = curr_master_stime;
941 local_irq_enable();
943 update_vcpu_system_time(current);
945 out:
946 set_timer(&t->calibration_timer, NOW() + EPOCH);
948 if ( smp_processor_id() == 0 )
949 platform_time_calibration();
950 }
952 void init_percpu_time(void)
953 {
954 struct cpu_time *t = &this_cpu(cpu_time);
955 unsigned long flags;
956 s_time_t now;
958 local_irq_save(flags);
959 rdtscll(t->local_tsc_stamp);
960 now = !plt_src.read_counter ? 0 : read_platform_stime();
961 local_irq_restore(flags);
963 t->stime_master_stamp = now;
964 t->stime_local_stamp = now;
966 init_timer(&t->calibration_timer, local_time_calibration,
967 NULL, smp_processor_id());
968 set_timer(&t->calibration_timer, NOW() + EPOCH);
969 }
971 /* Late init function (after all CPUs are booted). */
972 int __init init_xen_time(void)
973 {
974 wc_sec = get_cmos_time();
976 local_irq_disable();
978 init_percpu_time();
980 stime_platform_stamp = 0;
981 init_platform_timer();
983 /* check if TSC is invariant during deep C state
984 this is a new feature introduced by Nehalem*/
985 if ( cpuid_edx(0x80000007) & (1U<<8) )
986 tsc_invariant = 1;
988 local_irq_enable();
990 return 0;
991 }
994 /* Early init function. */
995 void __init early_time_init(void)
996 {
997 u64 tmp = init_pit_and_calibrate_tsc();
999 set_time_scale(&this_cpu(cpu_time).tsc_scale, tmp);
1001 do_div(tmp, 1000);
1002 cpu_khz = (unsigned long)tmp;
1003 printk("Detected %lu.%03lu MHz processor.\n",
1004 cpu_khz / 1000, cpu_khz % 1000);
1006 setup_irq(0, &irq0);
1009 static int disable_pit_irq(void)
1011 if ( !using_pit && cpu_has_apic )
1013 /* Disable PIT CH0 timer interrupt. */
1014 outb_p(0x30, PIT_MODE);
1015 outb_p(0, PIT_CH0);
1016 outb_p(0, PIT_CH0);
1018 /*
1019 * If we do not rely on PIT CH0 then we can use HPET for one-shot
1020 * timer emulation when entering deep C states.
1021 */
1022 /*hpet_broadcast_init(); XXX dom0 may rely on RTC interrupt delivery */
1025 return 0;
1027 __initcall(disable_pit_irq);
1029 void send_timer_event(struct vcpu *v)
1031 send_guest_vcpu_virq(v, VIRQ_TIMER);
1034 /* Return secs after 00:00:00 localtime, 1 January, 1970. */
1035 unsigned long get_localtime(struct domain *d)
1037 return wc_sec + (wc_nsec + NOW()) / 1000000000ULL
1038 + d->time_offset_seconds;
1041 /* "cmos_utc_offset" is the difference between UTC time and CMOS time. */
1042 static long cmos_utc_offset; /* in seconds */
1044 int time_suspend(void)
1046 if ( smp_processor_id() == 0 )
1048 cmos_utc_offset = -get_cmos_time();
1049 cmos_utc_offset += (wc_sec + (wc_nsec + NOW()) / 1000000000ULL);
1052 /* Better to cancel calibration timer for accuracy. */
1053 kill_timer(&this_cpu(cpu_time).calibration_timer);
1055 return 0;
1058 int time_resume(void)
1060 u64 tmp = init_pit_and_calibrate_tsc();
1062 disable_pit_irq();
1064 set_time_scale(&this_cpu(cpu_time).tsc_scale, tmp);
1066 resume_platform_timer();
1068 do_settime(get_cmos_time() + cmos_utc_offset, 0, read_platform_stime());
1070 init_percpu_time();
1072 if ( !is_idle_vcpu(current) )
1073 update_vcpu_system_time(current);
1075 return 0;
1078 int dom0_pit_access(struct ioreq *ioreq)
1080 /* Is Xen using Channel 2? Then disallow direct dom0 access. */
1081 if ( using_pit )
1082 return 0;
1084 switch ( ioreq->addr )
1086 case PIT_CH2:
1087 if ( ioreq->dir == IOREQ_READ )
1088 ioreq->data = inb(PIT_CH2);
1089 else
1090 outb(ioreq->data, PIT_CH2);
1091 return 1;
1093 case PIT_MODE:
1094 if ( ioreq->dir == IOREQ_READ )
1095 return 0; /* urk! */
1096 switch ( ioreq->data & 0xc0 )
1098 case 0xc0: /* Read Back */
1099 if ( ioreq->data & 0x08 ) /* Select Channel 2? */
1100 outb(ioreq->data & 0xf8, PIT_MODE);
1101 if ( !(ioreq->data & 0x06) ) /* Select Channel 0/1? */
1102 return 1; /* no - we're done */
1103 /* Filter Channel 2 and reserved bit 0. */
1104 ioreq->data &= ~0x09;
1105 return 0; /* emulate ch0/1 readback */
1106 case 0x80: /* Select Counter 2 */
1107 outb(ioreq->data, PIT_MODE);
1108 return 1;
1111 case 0x61:
1112 if ( ioreq->dir == IOREQ_READ )
1113 ioreq->data = inb(0x61);
1114 else
1115 outb((inb(0x61) & ~3) | (ioreq->data & 3), 0x61);
1116 return 1;
1119 return 0;
1122 struct tm wallclock_time(void)
1124 uint64_t seconds;
1126 if ( !wc_sec )
1127 return (struct tm) { 0 };
1129 seconds = NOW() + (wc_sec * 1000000000ull) + wc_nsec;
1130 do_div(seconds, 1000000000);
1131 return gmtime(seconds);
1134 /*
1135 * Local variables:
1136 * mode: C
1137 * c-set-style: "BSD"
1138 * c-basic-offset: 4
1139 * tab-width: 4
1140 * indent-tabs-mode: nil
1141 * End:
1142 */