debuggers.hg

view xen/arch/x86/time.c @ 20672:2d072636c4f8

Pvrdtscp: move write_rdtscp_aux() to paravirt_ctxt_switch_to() -
Currently write_rdtscp_aux() is placed in update_vcpu_system_time(),
which is called by schedule() before context_switch(). This will break
the HVM guest TSC_AUX state because at this point, MSR hasn't beed
saved for HVM guests.So put the function in the point when a PV vcpu
is really scheduled in.

Signed-off-by: Dongxiao Xu <dongxiao.xu@intel.com>
author Keir Fraser <keir.fraser@citrix.com>
date Mon Dec 14 07:45:04 2009 +0000 (2009-12-14)
parents 1396dfb8d6ba
children a74aca4b9386
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 <xen/keyhandler.h>
25 #include <xen/guest_access.h>
26 #include <asm/io.h>
27 #include <asm/msr.h>
28 #include <asm/mpspec.h>
29 #include <asm/processor.h>
30 #include <asm/fixmap.h>
31 #include <asm/mc146818rtc.h>
32 #include <asm/div64.h>
33 #include <asm/acpi.h>
34 #include <asm/hpet.h>
35 #include <io_ports.h>
36 #include <asm/setup.h> /* for early_time_init */
37 #include <public/arch-x86/cpuid.h>
39 /* opt_clocksource: Force clocksource to one of: pit, hpet, cyclone, acpi. */
40 static char __initdata opt_clocksource[10];
41 string_param("clocksource", opt_clocksource);
43 unsigned long cpu_khz; /* CPU clock frequency in kHz. */
44 DEFINE_SPINLOCK(rtc_lock);
45 unsigned long pit0_ticks;
46 static u32 wc_sec, wc_nsec; /* UTC time at last 'time update'. */
47 static DEFINE_SPINLOCK(wc_lock);
49 struct cpu_time {
50 u64 local_tsc_stamp;
51 s_time_t stime_local_stamp;
52 s_time_t stime_master_stamp;
53 struct time_scale tsc_scale;
54 };
56 struct platform_timesource {
57 char *id;
58 char *name;
59 u64 frequency;
60 u64 (*read_counter)(void);
61 int (*init)(struct platform_timesource *);
62 void (*resume)(struct platform_timesource *);
63 int counter_bits;
64 };
66 static DEFINE_PER_CPU(struct cpu_time, cpu_time);
68 /* Calibrate all CPUs to platform timer every EPOCH. */
69 #define EPOCH MILLISECS(1000)
70 static struct timer calibration_timer;
72 /*
73 * We simulate a 32-bit platform timer from the 16-bit PIT ch2 counter.
74 * Otherwise overflow happens too quickly (~50ms) for us to guarantee that
75 * softirq handling will happen in time.
76 *
77 * The pit_lock protects the 16- and 32-bit stamp fields as well as the
78 */
79 static DEFINE_SPINLOCK(pit_lock);
80 static u16 pit_stamp16;
81 static u32 pit_stamp32;
82 static int using_pit;
84 /*
85 * 32-bit division of integer dividend and integer divisor yielding
86 * 32-bit fractional quotient.
87 */
88 static inline u32 div_frac(u32 dividend, u32 divisor)
89 {
90 u32 quotient, remainder;
91 ASSERT(dividend < divisor);
92 asm (
93 "divl %4"
94 : "=a" (quotient), "=d" (remainder)
95 : "0" (0), "1" (dividend), "r" (divisor) );
96 return quotient;
97 }
99 /*
100 * 32-bit multiplication of multiplicand and fractional multiplier
101 * yielding 32-bit product (radix point at same position as in multiplicand).
102 */
103 static inline u32 mul_frac(u32 multiplicand, u32 multiplier)
104 {
105 u32 product_int, product_frac;
106 asm (
107 "mul %3"
108 : "=a" (product_frac), "=d" (product_int)
109 : "0" (multiplicand), "r" (multiplier) );
110 return product_int;
111 }
113 /*
114 * Scale a 64-bit delta by scaling and multiplying by a 32-bit fraction,
115 * yielding a 64-bit result.
116 */
117 static inline u64 scale_delta(u64 delta, struct time_scale *scale)
118 {
119 u64 product;
120 #ifdef CONFIG_X86_32
121 u32 tmp1, tmp2;
122 #endif
124 if ( scale->shift < 0 )
125 delta >>= -scale->shift;
126 else
127 delta <<= scale->shift;
129 #ifdef CONFIG_X86_32
130 asm (
131 "mul %5 ; "
132 "mov %4,%%eax ; "
133 "mov %%edx,%4 ; "
134 "mul %5 ; "
135 "xor %5,%5 ; "
136 "add %4,%%eax ; "
137 "adc %5,%%edx ; "
138 : "=A" (product), "=r" (tmp1), "=r" (tmp2)
139 : "a" ((u32)delta), "1" ((u32)(delta >> 32)), "2" (scale->mul_frac) );
140 #else
141 asm (
142 "mul %%rdx ; shrd $32,%%rdx,%%rax"
143 : "=a" (product) : "0" (delta), "d" ((u64)scale->mul_frac) );
144 #endif
146 return product;
147 }
149 #define _TS_MUL_FRAC_IDENTITY 0x80000000UL
151 /* Compute the reciprocal of the given time_scale. */
152 static inline struct time_scale scale_reciprocal(struct time_scale scale)
153 {
154 struct time_scale reciprocal;
155 u32 dividend;
157 ASSERT(scale.mul_frac != 0);
158 dividend = _TS_MUL_FRAC_IDENTITY;
159 reciprocal.shift = 1 - scale.shift;
160 while ( unlikely(dividend >= scale.mul_frac) )
161 {
162 dividend >>= 1;
163 reciprocal.shift++;
164 }
166 asm (
167 "divl %4"
168 : "=a" (reciprocal.mul_frac), "=d" (dividend)
169 : "0" (0), "1" (dividend), "r" (scale.mul_frac) );
171 return reciprocal;
172 }
174 /*
175 * cpu_mask that denotes the CPUs that needs timer interrupt coming in as
176 * IPIs in place of local APIC timers
177 */
178 extern int xen_cpuidle;
179 static cpumask_t pit_broadcast_mask;
181 static void smp_send_timer_broadcast_ipi(void)
182 {
183 int cpu = smp_processor_id();
184 cpumask_t mask;
186 cpus_and(mask, cpu_online_map, pit_broadcast_mask);
188 if ( cpu_isset(cpu, mask) )
189 {
190 cpu_clear(cpu, mask);
191 raise_softirq(TIMER_SOFTIRQ);
192 }
194 if ( !cpus_empty(mask) )
195 {
196 cpumask_raise_softirq(mask, TIMER_SOFTIRQ);
197 }
198 }
200 static void timer_interrupt(int irq, void *dev_id, struct cpu_user_regs *regs)
201 {
202 ASSERT(local_irq_is_enabled());
204 if ( hpet_legacy_irq_tick() )
205 return;
207 /* Only for start-of-day interruopt tests in io_apic.c. */
208 (*(volatile unsigned long *)&pit0_ticks)++;
210 /* Rough hack to allow accurate timers to sort-of-work with no APIC. */
211 if ( !cpu_has_apic )
212 raise_softirq(TIMER_SOFTIRQ);
214 if ( xen_cpuidle )
215 smp_send_timer_broadcast_ipi();
217 /* Emulate a 32-bit PIT counter. */
218 if ( using_pit )
219 {
220 u16 count;
222 spin_lock_irq(&pit_lock);
224 outb(0x80, PIT_MODE);
225 count = inb(PIT_CH2);
226 count |= inb(PIT_CH2) << 8;
228 pit_stamp32 += (u16)(pit_stamp16 - count);
229 pit_stamp16 = count;
231 spin_unlock_irq(&pit_lock);
232 }
233 }
235 static struct irqaction __read_mostly irq0 = { timer_interrupt, "timer", NULL };
237 /* ------ Calibrate the TSC -------
238 * Return processor ticks per second / CALIBRATE_FRAC.
239 */
241 #define CLOCK_TICK_RATE 1193182 /* system crystal frequency (Hz) */
242 #define CALIBRATE_FRAC 20 /* calibrate over 50ms */
243 #define CALIBRATE_LATCH ((CLOCK_TICK_RATE+(CALIBRATE_FRAC/2))/CALIBRATE_FRAC)
245 static u64 init_pit_and_calibrate_tsc(void)
246 {
247 u64 start, end;
248 unsigned long count;
250 /* Set PIT channel 0 to HZ Hz. */
251 #define LATCH (((CLOCK_TICK_RATE)+(HZ/2))/HZ)
252 outb_p(0x34, PIT_MODE); /* binary, mode 2, LSB/MSB, ch 0 */
253 outb_p(LATCH & 0xff, PIT_CH0); /* LSB */
254 outb(LATCH >> 8, PIT_CH0); /* MSB */
256 /* Set the Gate high, disable speaker */
257 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
259 /*
260 * Now let's take care of CTC channel 2
261 *
262 * Set the Gate high, program CTC channel 2 for mode 0, (interrupt on
263 * terminal count mode), binary count, load 5 * LATCH count, (LSB and MSB)
264 * to begin countdown.
265 */
266 outb(0xb0, PIT_MODE); /* binary, mode 0, LSB/MSB, Ch 2 */
267 outb(CALIBRATE_LATCH & 0xff, PIT_CH2); /* LSB of count */
268 outb(CALIBRATE_LATCH >> 8, PIT_CH2); /* MSB of count */
270 rdtscll(start);
271 for ( count = 0; (inb(0x61) & 0x20) == 0; count++ )
272 continue;
273 rdtscll(end);
275 /* Error if the CTC doesn't behave itself. */
276 if ( count == 0 )
277 return 0;
279 return ((end - start) * (u64)CALIBRATE_FRAC);
280 }
282 static void set_time_scale(struct time_scale *ts, u64 ticks_per_sec)
283 {
284 u64 tps64 = ticks_per_sec;
285 u32 tps32;
286 int shift = 0;
288 ASSERT(tps64 != 0);
290 while ( tps64 > (MILLISECS(1000)*2) )
291 {
292 tps64 >>= 1;
293 shift--;
294 }
296 tps32 = (u32)tps64;
297 while ( tps32 <= (u32)MILLISECS(1000) )
298 {
299 tps32 <<= 1;
300 shift++;
301 }
303 ts->mul_frac = div_frac(MILLISECS(1000), tps32);
304 ts->shift = shift;
305 }
307 static atomic_t tsc_calibrate_gang = ATOMIC_INIT(0);
308 static unsigned int tsc_calibrate_status = 0;
310 void calibrate_tsc_bp(void)
311 {
312 while ( atomic_read(&tsc_calibrate_gang) != (num_booting_cpus() - 1) )
313 mb();
315 outb(CALIBRATE_LATCH & 0xff, PIT_CH2);
316 outb(CALIBRATE_LATCH >> 8, PIT_CH2);
318 tsc_calibrate_status = 1;
319 wmb();
321 while ( (inb(0x61) & 0x20) == 0 )
322 continue;
324 tsc_calibrate_status = 2;
325 wmb();
327 while ( atomic_read(&tsc_calibrate_gang) != 0 )
328 mb();
329 }
331 void calibrate_tsc_ap(void)
332 {
333 u64 t1, t2, ticks_per_sec;
335 atomic_inc(&tsc_calibrate_gang);
337 while ( tsc_calibrate_status < 1 )
338 mb();
340 rdtscll(t1);
342 while ( tsc_calibrate_status < 2 )
343 mb();
345 rdtscll(t2);
347 ticks_per_sec = (t2 - t1) * (u64)CALIBRATE_FRAC;
348 set_time_scale(&this_cpu(cpu_time).tsc_scale, ticks_per_sec);
350 atomic_dec(&tsc_calibrate_gang);
351 }
353 static char *freq_string(u64 freq)
354 {
355 static char s[20];
356 unsigned int x, y;
357 y = (unsigned int)do_div(freq, 1000000) / 1000;
358 x = (unsigned int)freq;
359 snprintf(s, sizeof(s), "%u.%03uMHz", x, y);
360 return s;
361 }
363 /************************************************************
364 * PLATFORM TIMER 1: PROGRAMMABLE INTERVAL TIMER (LEGACY PIT)
365 */
367 static u64 read_pit_count(void)
368 {
369 u16 count16;
370 u32 count32;
371 unsigned long flags;
373 spin_lock_irqsave(&pit_lock, flags);
375 outb(0x80, PIT_MODE);
376 count16 = inb(PIT_CH2);
377 count16 |= inb(PIT_CH2) << 8;
379 count32 = pit_stamp32 + (u16)(pit_stamp16 - count16);
381 spin_unlock_irqrestore(&pit_lock, flags);
383 return count32;
384 }
386 static int __init init_pit(struct platform_timesource *pts)
387 {
388 using_pit = 1;
389 return 1;
390 }
392 static struct platform_timesource __initdata plt_pit =
393 {
394 .id = "pit",
395 .name = "PIT",
396 .frequency = CLOCK_TICK_RATE,
397 .read_counter = read_pit_count,
398 .counter_bits = 32,
399 .init = init_pit
400 };
402 /************************************************************
403 * PLATFORM TIMER 2: HIGH PRECISION EVENT TIMER (HPET)
404 */
406 static u64 read_hpet_count(void)
407 {
408 return hpet_read32(HPET_COUNTER);
409 }
411 static int __init init_hpet(struct platform_timesource *pts)
412 {
413 u64 hpet_rate = hpet_setup();
415 if ( hpet_rate == 0 )
416 return 0;
418 pts->frequency = hpet_rate;
419 return 1;
420 }
422 static void resume_hpet(struct platform_timesource *pts)
423 {
424 u64 hpet_rate = hpet_setup();
426 BUG_ON(hpet_rate == 0);
427 pts->frequency = hpet_rate;
428 }
430 static struct platform_timesource __initdata plt_hpet =
431 {
432 .id = "hpet",
433 .name = "HPET",
434 .read_counter = read_hpet_count,
435 .counter_bits = 32,
436 .init = init_hpet,
437 .resume = resume_hpet
438 };
440 /************************************************************
441 * PLATFORM TIMER 3: IBM 'CYCLONE' TIMER
442 */
444 int use_cyclone;
446 /*
447 * Although the counter is read via a 64-bit register, I believe it is actually
448 * a 40-bit counter. Since this will wrap, I read only the low 32 bits and
449 * periodically fold into a 64-bit software counter, just as for PIT and HPET.
450 */
451 #define CYCLONE_CBAR_ADDR 0xFEB00CD0
452 #define CYCLONE_PMCC_OFFSET 0x51A0
453 #define CYCLONE_MPMC_OFFSET 0x51D0
454 #define CYCLONE_MPCS_OFFSET 0x51A8
455 #define CYCLONE_TIMER_FREQ 100000000
457 /* Cyclone MPMC0 register. */
458 static volatile u32 *cyclone_timer;
460 static u64 read_cyclone_count(void)
461 {
462 return *cyclone_timer;
463 }
465 static volatile u32 *__init map_cyclone_reg(unsigned long regaddr)
466 {
467 unsigned long pageaddr = regaddr & PAGE_MASK;
468 unsigned long offset = regaddr & ~PAGE_MASK;
469 set_fixmap_nocache(FIX_CYCLONE_TIMER, pageaddr);
470 return (volatile u32 *)(fix_to_virt(FIX_CYCLONE_TIMER) + offset);
471 }
473 static int __init init_cyclone(struct platform_timesource *pts)
474 {
475 u32 base;
477 if ( !use_cyclone )
478 return 0;
480 /* Find base address. */
481 base = *(map_cyclone_reg(CYCLONE_CBAR_ADDR));
482 if ( base == 0 )
483 {
484 printk(KERN_ERR "Cyclone: Could not find valid CBAR value.\n");
485 return 0;
486 }
488 /* Enable timer and map the counter register. */
489 *(map_cyclone_reg(base + CYCLONE_PMCC_OFFSET)) = 1;
490 *(map_cyclone_reg(base + CYCLONE_MPCS_OFFSET)) = 1;
491 cyclone_timer = map_cyclone_reg(base + CYCLONE_MPMC_OFFSET);
492 return 1;
493 }
495 static struct platform_timesource __initdata plt_cyclone =
496 {
497 .id = "cyclone",
498 .name = "IBM Cyclone",
499 .frequency = CYCLONE_TIMER_FREQ,
500 .read_counter = read_cyclone_count,
501 .counter_bits = 32,
502 .init = init_cyclone
503 };
505 /************************************************************
506 * PLATFORM TIMER 4: ACPI PM TIMER
507 */
509 u32 pmtmr_ioport;
511 /* ACPI PM timer ticks at 3.579545 MHz. */
512 #define ACPI_PM_FREQUENCY 3579545
514 static u64 read_pmtimer_count(void)
515 {
516 return inl(pmtmr_ioport);
517 }
519 static int __init init_pmtimer(struct platform_timesource *pts)
520 {
521 if ( pmtmr_ioport == 0 )
522 return 0;
524 return 1;
525 }
527 static struct platform_timesource __initdata plt_pmtimer =
528 {
529 .id = "acpi",
530 .name = "ACPI PM Timer",
531 .frequency = ACPI_PM_FREQUENCY,
532 .read_counter = read_pmtimer_count,
533 .counter_bits = 24,
534 .init = init_pmtimer
535 };
537 static struct time_scale pmt_scale;
538 static struct time_scale pmt_scale_r;
539 static __init int init_pmtmr_scale(void)
540 {
541 set_time_scale(&pmt_scale, ACPI_PM_FREQUENCY);
542 pmt_scale_r = scale_reciprocal(pmt_scale);
543 return 0;
544 }
545 __initcall(init_pmtmr_scale);
547 uint64_t acpi_pm_tick_to_ns(uint64_t ticks)
548 {
549 return scale_delta(ticks, &pmt_scale);
550 }
552 uint64_t ns_to_acpi_pm_tick(uint64_t ns)
553 {
554 return scale_delta(ns, &pmt_scale_r);
555 }
557 /************************************************************
558 * GENERIC PLATFORM TIMER INFRASTRUCTURE
559 */
561 static struct platform_timesource plt_src; /* details of chosen timesource */
562 static u64 plt_mask; /* hardware-width mask */
563 static u64 plt_overflow_period; /* ns between calls to plt_overflow() */
564 static struct time_scale plt_scale; /* scale: platform counter -> nanosecs */
566 /* Protected by platform_timer_lock. */
567 static DEFINE_SPINLOCK(platform_timer_lock);
568 static s_time_t stime_platform_stamp; /* System time at below platform time */
569 static u64 platform_timer_stamp; /* Platform time at above system time */
570 static u64 plt_stamp64; /* 64-bit platform counter stamp */
571 static u64 plt_stamp; /* hardware-width platform counter stamp */
572 static struct timer plt_overflow_timer;
574 static void plt_overflow(void *unused)
575 {
576 u64 count;
578 spin_lock_irq(&platform_timer_lock);
579 count = plt_src.read_counter();
580 plt_stamp64 += (count - plt_stamp) & plt_mask;
581 plt_stamp = count;
582 spin_unlock_irq(&platform_timer_lock);
584 set_timer(&plt_overflow_timer, NOW() + plt_overflow_period);
585 }
587 static s_time_t __read_platform_stime(u64 platform_time)
588 {
589 u64 diff = platform_time - platform_timer_stamp;
590 ASSERT(spin_is_locked(&platform_timer_lock));
591 return (stime_platform_stamp + scale_delta(diff, &plt_scale));
592 }
594 static s_time_t read_platform_stime(void)
595 {
596 u64 count;
597 s_time_t stime;
599 ASSERT(!local_irq_is_enabled());
601 spin_lock(&platform_timer_lock);
602 count = plt_stamp64 + ((plt_src.read_counter() - plt_stamp) & plt_mask);
603 stime = __read_platform_stime(count);
604 spin_unlock(&platform_timer_lock);
606 return stime;
607 }
609 static void platform_time_calibration(void)
610 {
611 u64 count;
612 s_time_t stamp;
613 unsigned long flags;
615 spin_lock_irqsave(&platform_timer_lock, flags);
616 count = plt_stamp64 + ((plt_src.read_counter() - plt_stamp) & plt_mask);
617 stamp = __read_platform_stime(count);
618 stime_platform_stamp = stamp;
619 platform_timer_stamp = count;
620 spin_unlock_irqrestore(&platform_timer_lock, flags);
621 }
623 static void resume_platform_timer(void)
624 {
625 /* Timer source can be reset when backing from S3 to S0 */
626 if ( plt_src.resume )
627 plt_src.resume(&plt_src);
629 plt_stamp64 = platform_timer_stamp;
630 plt_stamp = plt_src.read_counter();
631 }
633 static void __init init_platform_timer(void)
634 {
635 static struct platform_timesource * __initdata plt_timers[] = {
636 &plt_cyclone, &plt_hpet, &plt_pmtimer, &plt_pit
637 };
639 struct platform_timesource *pts = NULL;
640 int i, rc = -1;
642 if ( opt_clocksource[0] != '\0' )
643 {
644 for ( i = 0; i < ARRAY_SIZE(plt_timers); i++ )
645 {
646 pts = plt_timers[i];
647 if ( !strcmp(opt_clocksource, pts->id) )
648 {
649 rc = pts->init(pts);
650 break;
651 }
652 }
654 if ( rc <= 0 )
655 printk("WARNING: %s clocksource '%s'.\n",
656 (rc == 0) ? "Could not initialise" : "Unrecognised",
657 opt_clocksource);
658 }
660 if ( rc <= 0 )
661 {
662 for ( i = 0; i < ARRAY_SIZE(plt_timers); i++ )
663 {
664 pts = plt_timers[i];
665 if ( (rc = pts->init(pts)) > 0 )
666 break;
667 }
668 }
670 BUG_ON(rc <= 0);
672 plt_mask = (u64)~0ull >> (64 - pts->counter_bits);
674 set_time_scale(&plt_scale, pts->frequency);
676 plt_overflow_period = scale_delta(
677 1ull << (pts->counter_bits-1), &plt_scale);
678 init_timer(&plt_overflow_timer, plt_overflow, NULL, 0);
679 plt_src = *pts;
680 plt_overflow(NULL);
682 platform_timer_stamp = plt_stamp64;
683 stime_platform_stamp = NOW();
685 printk("Platform timer is %s %s\n",
686 freq_string(pts->frequency), pts->name);
687 }
689 void cstate_restore_tsc(void)
690 {
691 struct cpu_time *t = &this_cpu(cpu_time);
692 struct time_scale sys_to_tsc = scale_reciprocal(t->tsc_scale);
693 s_time_t stime_delta;
694 u64 new_tsc;
696 if ( boot_cpu_has(X86_FEATURE_NONSTOP_TSC) )
697 return;
699 stime_delta = read_platform_stime() - t->stime_master_stamp;
700 if ( stime_delta < 0 )
701 stime_delta = 0;
703 new_tsc = t->local_tsc_stamp + scale_delta(stime_delta, &sys_to_tsc);
705 write_tsc(new_tsc);
706 }
708 /***************************************************************************
709 * CMOS Timer functions
710 ***************************************************************************/
712 /* Converts Gregorian date to seconds since 1970-01-01 00:00:00.
713 * Assumes input in normal date format, i.e. 1980-12-31 23:59:59
714 * => year=1980, mon=12, day=31, hour=23, min=59, sec=59.
715 *
716 * [For the Julian calendar (which was used in Russia before 1917,
717 * Britain & colonies before 1752, anywhere else before 1582,
718 * and is still in use by some communities) leave out the
719 * -year/100+year/400 terms, and add 10.]
720 *
721 * This algorithm was first published by Gauss (I think).
722 *
723 * WARNING: this function will overflow on 2106-02-07 06:28:16 on
724 * machines were long is 32-bit! (However, as time_t is signed, we
725 * will already get problems at other places on 2038-01-19 03:14:08)
726 */
727 unsigned long
728 mktime (unsigned int year, unsigned int mon,
729 unsigned int day, unsigned int hour,
730 unsigned int min, unsigned int sec)
731 {
732 /* 1..12 -> 11,12,1..10: put Feb last since it has a leap day. */
733 if ( 0 >= (int) (mon -= 2) )
734 {
735 mon += 12;
736 year -= 1;
737 }
739 return ((((unsigned long)(year/4 - year/100 + year/400 + 367*mon/12 + day)+
740 year*365 - 719499
741 )*24 + hour /* now have hours */
742 )*60 + min /* now have minutes */
743 )*60 + sec; /* finally seconds */
744 }
746 static unsigned long __get_cmos_time(void)
747 {
748 unsigned int year, mon, day, hour, min, sec;
750 sec = CMOS_READ(RTC_SECONDS);
751 min = CMOS_READ(RTC_MINUTES);
752 hour = CMOS_READ(RTC_HOURS);
753 day = CMOS_READ(RTC_DAY_OF_MONTH);
754 mon = CMOS_READ(RTC_MONTH);
755 year = CMOS_READ(RTC_YEAR);
757 if ( !(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD )
758 {
759 BCD_TO_BIN(sec);
760 BCD_TO_BIN(min);
761 BCD_TO_BIN(hour);
762 BCD_TO_BIN(day);
763 BCD_TO_BIN(mon);
764 BCD_TO_BIN(year);
765 }
767 if ( (year += 1900) < 1970 )
768 year += 100;
770 return mktime(year, mon, day, hour, min, sec);
771 }
773 static unsigned long get_cmos_time(void)
774 {
775 unsigned long res, flags;
776 int i;
778 spin_lock_irqsave(&rtc_lock, flags);
780 /* read RTC exactly on falling edge of update flag */
781 for ( i = 0 ; i < 1000000 ; i++ ) /* may take up to 1 second... */
782 if ( (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) )
783 break;
784 for ( i = 0 ; i < 1000000 ; i++ ) /* must try at least 2.228 ms */
785 if ( !(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP) )
786 break;
788 res = __get_cmos_time();
790 spin_unlock_irqrestore(&rtc_lock, flags);
791 return res;
792 }
794 /***************************************************************************
795 * System Time
796 ***************************************************************************/
798 s_time_t get_s_time(void)
799 {
800 struct cpu_time *t = &this_cpu(cpu_time);
801 u64 tsc, delta;
802 s_time_t now;
804 rdtscll(tsc);
805 delta = tsc - t->local_tsc_stamp;
806 now = t->stime_local_stamp + scale_delta(delta, &t->tsc_scale);
808 return now;
809 }
811 /* Explicitly OR with 1 just in case version number gets out of sync. */
812 #define version_update_begin(v) (((v)+1)|1)
813 #define version_update_end(v) ((v)+1)
815 static void __update_vcpu_system_time(struct vcpu *v, int force)
816 {
817 struct cpu_time *t;
818 struct vcpu_time_info *u, _u;
819 XEN_GUEST_HANDLE(vcpu_time_info_t) user_u;
820 struct domain *d = v->domain;
821 s_time_t tsc_stamp = 0;
823 if ( v->vcpu_info == NULL )
824 return;
826 t = &this_cpu(cpu_time);
827 u = &vcpu_info(v, time);
829 if ( d->arch.vtsc )
830 tsc_stamp = scale_delta(t->stime_local_stamp - d->arch.vtsc_offset,
831 &d->arch.ns_to_vtsc);
832 else
833 tsc_stamp = t->local_tsc_stamp;
835 /* Don't bother unless timestamps have changed or we are forced. */
836 if ( !force && (u->tsc_timestamp == tsc_stamp) )
837 return;
839 memset(&_u, 0, sizeof(_u));
841 if ( d->arch.vtsc )
842 {
843 _u.tsc_timestamp = tsc_stamp;
844 _u.system_time = t->stime_local_stamp;
845 _u.tsc_to_system_mul = d->arch.vtsc_to_ns.mul_frac;
846 _u.tsc_shift = d->arch.vtsc_to_ns.shift;
847 }
848 else
849 {
850 _u.tsc_timestamp = t->local_tsc_stamp;
851 _u.system_time = t->stime_local_stamp;
852 _u.tsc_to_system_mul = t->tsc_scale.mul_frac;
853 _u.tsc_shift = (s8)t->tsc_scale.shift;
854 }
856 /* 1. Update guest kernel version. */
857 _u.version = u->version = version_update_begin(u->version);
858 wmb();
859 /* 2. Update all other guest kernel fields. */
860 *u = _u;
861 wmb();
862 /* 3. Update guest kernel version. */
863 u->version = version_update_end(u->version);
865 user_u = v->arch.time_info_guest;
866 if ( !guest_handle_is_null(user_u) )
867 {
868 /* 1. Update userspace version. */
869 __copy_field_to_guest(user_u, &_u, version);
870 wmb();
871 /* 2. Update all other userspavce fields. */
872 __copy_to_guest(user_u, &_u, 1);
873 wmb();
874 /* 3. Update userspace version. */
875 _u.version = version_update_end(_u.version);
876 __copy_field_to_guest(user_u, &_u, version);
877 }
878 }
880 void update_vcpu_system_time(struct vcpu *v)
881 {
882 __update_vcpu_system_time(v, 0);
883 }
885 void force_update_vcpu_system_time(struct vcpu *v)
886 {
887 __update_vcpu_system_time(v, 1);
888 }
890 void update_domain_wallclock_time(struct domain *d)
891 {
892 uint32_t *wc_version;
894 spin_lock(&wc_lock);
896 wc_version = &shared_info(d, wc_version);
897 *wc_version = version_update_begin(*wc_version);
898 wmb();
900 shared_info(d, wc_sec) = wc_sec + d->time_offset_seconds;
901 shared_info(d, wc_nsec) = wc_nsec;
903 wmb();
904 *wc_version = version_update_end(*wc_version);
906 spin_unlock(&wc_lock);
907 }
909 void domain_set_time_offset(struct domain *d, int32_t time_offset_seconds)
910 {
911 d->time_offset_seconds = time_offset_seconds;
912 if ( is_hvm_domain(d) )
913 rtc_update_clock(d);
914 }
916 int cpu_frequency_change(u64 freq)
917 {
918 struct cpu_time *t = &this_cpu(cpu_time);
919 u64 curr_tsc;
921 /* Sanity check: CPU frequency allegedly dropping below 1MHz? */
922 if ( freq < 1000000u )
923 {
924 gdprintk(XENLOG_WARNING, "Rejecting CPU frequency change "
925 "to %"PRIu64" Hz.\n", freq);
926 return -EINVAL;
927 }
929 local_irq_disable();
930 /* Platform time /first/, as we may be delayed by platform_timer_lock. */
931 t->stime_master_stamp = read_platform_stime();
932 /* TSC-extrapolated time may be bogus after frequency change. */
933 /*t->stime_local_stamp = get_s_time();*/
934 t->stime_local_stamp = t->stime_master_stamp;
935 rdtscll(curr_tsc);
936 t->local_tsc_stamp = curr_tsc;
937 set_time_scale(&t->tsc_scale, freq);
938 local_irq_enable();
940 update_vcpu_system_time(current);
942 /* A full epoch should pass before we check for deviation. */
943 if ( smp_processor_id() == 0 )
944 {
945 set_timer(&calibration_timer, NOW() + EPOCH);
946 platform_time_calibration();
947 }
949 return 0;
950 }
952 /* Set clock to <secs,usecs> after 00:00:00 UTC, 1 January, 1970. */
953 void do_settime(unsigned long secs, unsigned long nsecs, u64 system_time_base)
954 {
955 u64 x;
956 u32 y, _wc_sec, _wc_nsec;
957 struct domain *d;
959 x = (secs * 1000000000ULL) + (u64)nsecs - system_time_base;
960 y = do_div(x, 1000000000);
962 spin_lock(&wc_lock);
963 wc_sec = _wc_sec = (u32)x;
964 wc_nsec = _wc_nsec = (u32)y;
965 spin_unlock(&wc_lock);
967 rcu_read_lock(&domlist_read_lock);
968 for_each_domain ( d )
969 update_domain_wallclock_time(d);
970 rcu_read_unlock(&domlist_read_lock);
971 }
973 /* Per-CPU communication between rendezvous IRQ and softirq handler. */
974 struct cpu_calibration {
975 u64 local_tsc_stamp;
976 s_time_t stime_local_stamp;
977 s_time_t stime_master_stamp;
978 };
979 static DEFINE_PER_CPU(struct cpu_calibration, cpu_calibration);
981 /* Softirq handler for per-CPU time calibration. */
982 static void local_time_calibration(void)
983 {
984 struct cpu_time *t = &this_cpu(cpu_time);
985 struct cpu_calibration *c = &this_cpu(cpu_calibration);
987 /*
988 * System timestamps, extrapolated from local and master oscillators,
989 * taken during this calibration and the previous calibration.
990 */
991 s_time_t prev_local_stime, curr_local_stime;
992 s_time_t prev_master_stime, curr_master_stime;
994 /* TSC timestamps taken during this calibration and prev calibration. */
995 u64 prev_tsc, curr_tsc;
997 /*
998 * System time and TSC ticks elapsed during the previous calibration
999 * 'epoch'. These values are down-shifted to fit in 32 bits.
1000 */
1001 u64 stime_elapsed64, tsc_elapsed64;
1002 u32 stime_elapsed32, tsc_elapsed32;
1004 /* The accumulated error in the local estimate. */
1005 u64 local_stime_err;
1007 /* Error correction to slow down a fast local clock. */
1008 u32 error_factor = 0;
1010 /* Calculated TSC shift to ensure 32-bit scale multiplier. */
1011 int tsc_shift = 0;
1013 /* The overall calibration scale multiplier. */
1014 u32 calibration_mul_frac;
1016 if ( boot_cpu_has(X86_FEATURE_CONSTANT_TSC) )
1018 /* Atomically read cpu_calibration struct and write cpu_time struct. */
1019 local_irq_disable();
1020 t->local_tsc_stamp = c->local_tsc_stamp;
1021 t->stime_local_stamp = c->stime_master_stamp;
1022 t->stime_master_stamp = c->stime_master_stamp;
1023 local_irq_enable();
1024 update_vcpu_system_time(current);
1025 goto out;
1028 prev_tsc = t->local_tsc_stamp;
1029 prev_local_stime = t->stime_local_stamp;
1030 prev_master_stime = t->stime_master_stamp;
1032 /* Disabling IRQs ensures we atomically read cpu_calibration struct. */
1033 local_irq_disable();
1034 curr_tsc = c->local_tsc_stamp;
1035 curr_local_stime = c->stime_local_stamp;
1036 curr_master_stime = c->stime_master_stamp;
1037 local_irq_enable();
1039 #if 0
1040 printk("PRE%d: tsc=%"PRIu64" stime=%"PRIu64" master=%"PRIu64"\n",
1041 smp_processor_id(), prev_tsc, prev_local_stime, prev_master_stime);
1042 printk("CUR%d: tsc=%"PRIu64" stime=%"PRIu64" master=%"PRIu64
1043 " -> %"PRId64"\n",
1044 smp_processor_id(), curr_tsc, curr_local_stime, curr_master_stime,
1045 curr_master_stime - curr_local_stime);
1046 #endif
1048 /* Local time warps forward if it lags behind master time. */
1049 if ( curr_local_stime < curr_master_stime )
1050 curr_local_stime = curr_master_stime;
1052 stime_elapsed64 = curr_master_stime - prev_master_stime;
1053 tsc_elapsed64 = curr_tsc - prev_tsc;
1055 /*
1056 * Weirdness can happen if we lose sync with the platform timer.
1057 * We could be smarter here: resync platform timer with local timer?
1058 */
1059 if ( ((s64)stime_elapsed64 < (EPOCH / 2)) )
1060 goto out;
1062 /*
1063 * Calculate error-correction factor. This only slows down a fast local
1064 * clock (slow clocks are warped forwards). The scale factor is clamped
1065 * to >= 0.5.
1066 */
1067 if ( curr_local_stime != curr_master_stime )
1069 local_stime_err = curr_local_stime - curr_master_stime;
1070 if ( local_stime_err > EPOCH )
1071 local_stime_err = EPOCH;
1072 error_factor = div_frac(EPOCH, EPOCH + (u32)local_stime_err);
1075 /*
1076 * We require 0 < stime_elapsed < 2^31.
1077 * This allows us to binary shift a 32-bit tsc_elapsed such that:
1078 * stime_elapsed < tsc_elapsed <= 2*stime_elapsed
1079 */
1080 while ( ((u32)stime_elapsed64 != stime_elapsed64) ||
1081 ((s32)stime_elapsed64 < 0) )
1083 stime_elapsed64 >>= 1;
1084 tsc_elapsed64 >>= 1;
1087 /* stime_master_diff now fits in a 32-bit word. */
1088 stime_elapsed32 = (u32)stime_elapsed64;
1090 /* tsc_elapsed <= 2*stime_elapsed */
1091 while ( tsc_elapsed64 > (stime_elapsed32 * 2) )
1093 tsc_elapsed64 >>= 1;
1094 tsc_shift--;
1097 /* Local difference must now fit in 32 bits. */
1098 ASSERT((u32)tsc_elapsed64 == tsc_elapsed64);
1099 tsc_elapsed32 = (u32)tsc_elapsed64;
1101 /* tsc_elapsed > stime_elapsed */
1102 ASSERT(tsc_elapsed32 != 0);
1103 while ( tsc_elapsed32 <= stime_elapsed32 )
1105 tsc_elapsed32 <<= 1;
1106 tsc_shift++;
1109 calibration_mul_frac = div_frac(stime_elapsed32, tsc_elapsed32);
1110 if ( error_factor != 0 )
1111 calibration_mul_frac = mul_frac(calibration_mul_frac, error_factor);
1113 #if 0
1114 printk("---%d: %08x %08x %d\n", smp_processor_id(),
1115 error_factor, calibration_mul_frac, tsc_shift);
1116 #endif
1118 /* Record new timestamp information, atomically w.r.t. interrupts. */
1119 local_irq_disable();
1120 t->tsc_scale.mul_frac = calibration_mul_frac;
1121 t->tsc_scale.shift = tsc_shift;
1122 t->local_tsc_stamp = curr_tsc;
1123 t->stime_local_stamp = curr_local_stime;
1124 t->stime_master_stamp = curr_master_stime;
1125 local_irq_enable();
1127 update_vcpu_system_time(current);
1129 out:
1130 if ( smp_processor_id() == 0 )
1132 set_timer(&calibration_timer, NOW() + EPOCH);
1133 platform_time_calibration();
1137 /*
1138 * Rendezvous for all CPUs in IRQ context.
1139 * Master CPU snapshots the platform timer.
1140 * All CPUS snapshot their local TSC and extrapolation of system time.
1141 */
1142 struct calibration_rendezvous {
1143 cpumask_t cpu_calibration_map;
1144 atomic_t semaphore;
1145 s_time_t master_stime;
1146 u64 master_tsc_stamp;
1147 };
1149 /*
1150 * Keep TSCs in sync when they run at the same rate, but may stop in
1151 * deep-sleep C states.
1152 */
1153 static void time_calibration_tsc_rendezvous(void *_r)
1155 int i;
1156 struct cpu_calibration *c = &this_cpu(cpu_calibration);
1157 struct calibration_rendezvous *r = _r;
1158 unsigned int total_cpus = cpus_weight(r->cpu_calibration_map);
1160 /* Loop to get rid of cache effects on TSC skew. */
1161 for ( i = 4; i >= 0; i-- )
1163 if ( smp_processor_id() == 0 )
1165 while ( atomic_read(&r->semaphore) != (total_cpus - 1) )
1166 mb();
1168 if ( r->master_stime == 0 )
1170 r->master_stime = read_platform_stime();
1171 rdtscll(r->master_tsc_stamp);
1173 atomic_inc(&r->semaphore);
1175 if ( i == 0 )
1176 write_tsc(r->master_tsc_stamp);
1178 while ( atomic_read(&r->semaphore) != (2*total_cpus - 1) )
1179 mb();
1180 atomic_set(&r->semaphore, 0);
1182 else
1184 atomic_inc(&r->semaphore);
1185 while ( atomic_read(&r->semaphore) < total_cpus )
1186 mb();
1188 if ( i == 0 )
1189 write_tsc(r->master_tsc_stamp);
1191 atomic_inc(&r->semaphore);
1192 while ( atomic_read(&r->semaphore) > total_cpus )
1193 mb();
1197 rdtscll(c->local_tsc_stamp);
1198 c->stime_local_stamp = get_s_time();
1199 c->stime_master_stamp = r->master_stime;
1201 raise_softirq(TIME_CALIBRATE_SOFTIRQ);
1204 /* Ordinary rendezvous function which does not modify TSC values. */
1205 static void time_calibration_std_rendezvous(void *_r)
1207 struct cpu_calibration *c = &this_cpu(cpu_calibration);
1208 struct calibration_rendezvous *r = _r;
1209 unsigned int total_cpus = cpus_weight(r->cpu_calibration_map);
1211 if ( smp_processor_id() == 0 )
1213 while ( atomic_read(&r->semaphore) != (total_cpus - 1) )
1214 cpu_relax();
1215 r->master_stime = read_platform_stime();
1216 mb(); /* write r->master_stime /then/ signal */
1217 atomic_inc(&r->semaphore);
1219 else
1221 atomic_inc(&r->semaphore);
1222 while ( atomic_read(&r->semaphore) != total_cpus )
1223 cpu_relax();
1224 mb(); /* receive signal /then/ read r->master_stime */
1227 rdtscll(c->local_tsc_stamp);
1228 c->stime_local_stamp = get_s_time();
1229 c->stime_master_stamp = r->master_stime;
1231 raise_softirq(TIME_CALIBRATE_SOFTIRQ);
1234 static void (*time_calibration_rendezvous_fn)(void *) =
1235 time_calibration_std_rendezvous;
1237 static void time_calibration(void *unused)
1239 struct calibration_rendezvous r = {
1240 .cpu_calibration_map = cpu_online_map,
1241 .semaphore = ATOMIC_INIT(0)
1242 };
1244 /* @wait=1 because we must wait for all cpus before freeing @r. */
1245 on_selected_cpus(&r.cpu_calibration_map,
1246 time_calibration_rendezvous_fn,
1247 &r, 1);
1250 void init_percpu_time(void)
1252 struct cpu_time *t = &this_cpu(cpu_time);
1253 unsigned long flags;
1254 s_time_t now;
1256 local_irq_save(flags);
1257 rdtscll(t->local_tsc_stamp);
1258 now = read_platform_stime();
1259 local_irq_restore(flags);
1261 t->stime_master_stamp = now;
1262 t->stime_local_stamp = now;
1264 if ( smp_processor_id() == 0 )
1266 init_timer(&calibration_timer, time_calibration, NULL, 0);
1267 set_timer(&calibration_timer, NOW() + EPOCH);
1271 /* Late init function (after all CPUs are booted). */
1272 int __init init_xen_time(void)
1274 /* If we have constant-rate TSCs then scale factor can be shared. */
1275 if ( boot_cpu_has(X86_FEATURE_CONSTANT_TSC) )
1277 int cpu;
1278 for_each_possible_cpu ( cpu )
1279 per_cpu(cpu_time, cpu).tsc_scale = per_cpu(cpu_time, 0).tsc_scale;
1280 /* If TSCs are not marked as 'reliable', re-sync during rendezvous. */
1281 if ( !boot_cpu_has(X86_FEATURE_TSC_RELIABLE) )
1282 time_calibration_rendezvous_fn = time_calibration_tsc_rendezvous;
1285 open_softirq(TIME_CALIBRATE_SOFTIRQ, local_time_calibration);
1287 /* System time (get_s_time()) starts ticking from now. */
1288 rdtscll(this_cpu(cpu_time).local_tsc_stamp);
1290 /* NB. get_cmos_time() can take over one second to execute. */
1291 do_settime(get_cmos_time(), 0, NOW());
1293 init_platform_timer();
1295 init_percpu_time();
1297 return 0;
1301 /* Early init function. */
1302 void __init early_time_init(void)
1304 u64 tmp = init_pit_and_calibrate_tsc();
1306 set_time_scale(&this_cpu(cpu_time).tsc_scale, tmp);
1308 do_div(tmp, 1000);
1309 cpu_khz = (unsigned long)tmp;
1310 printk("Detected %lu.%03lu MHz processor.\n",
1311 cpu_khz / 1000, cpu_khz % 1000);
1313 setup_irq(0, &irq0);
1316 /* keep pit enabled for pit_broadcast working while cpuidle enabled */
1317 static int disable_pit_irq(void)
1319 if ( using_pit || !cpu_has_apic )
1320 return 0;
1322 /*
1323 * If we do not rely on PIT CH0 then we can use HPET for one-shot timer
1324 * emulation when entering deep C states.
1325 * XXX dom0 may rely on RTC interrupt delivery, so only enable
1326 * hpet_broadcast if FSB mode available or if force_hpet_broadcast.
1327 */
1328 if ( xen_cpuidle && !boot_cpu_has(X86_FEATURE_ARAT) )
1330 hpet_broadcast_init();
1331 if ( !hpet_broadcast_is_available() )
1333 if ( xen_cpuidle == -1 )
1335 xen_cpuidle = 0;
1336 printk("CPUIDLE: disabled due to no HPET. "
1337 "Force enable with 'cpuidle'.\n");
1339 else
1341 printk("HPET broadcast init failed, turn to PIT broadcast.\n");
1342 return 0;
1347 /* Disable PIT CH0 timer interrupt. */
1348 outb_p(0x30, PIT_MODE);
1349 outb_p(0, PIT_CH0);
1350 outb_p(0, PIT_CH0);
1352 return 0;
1354 __initcall(disable_pit_irq);
1356 void pit_broadcast_enter(void)
1358 cpu_set(smp_processor_id(), pit_broadcast_mask);
1361 void pit_broadcast_exit(void)
1363 int cpu = smp_processor_id();
1365 if ( cpu_test_and_clear(cpu, pit_broadcast_mask) )
1366 reprogram_timer(per_cpu(timer_deadline_start, cpu));
1369 int pit_broadcast_is_available(void)
1371 return xen_cpuidle;
1374 void send_timer_event(struct vcpu *v)
1376 send_guest_vcpu_virq(v, VIRQ_TIMER);
1379 /* Return secs after 00:00:00 localtime, 1 January, 1970. */
1380 unsigned long get_localtime(struct domain *d)
1382 return wc_sec + (wc_nsec + NOW()) / 1000000000ULL
1383 + d->time_offset_seconds;
1386 /* "cmos_utc_offset" is the difference between UTC time and CMOS time. */
1387 static long cmos_utc_offset; /* in seconds */
1389 int time_suspend(void)
1391 if ( smp_processor_id() == 0 )
1393 cmos_utc_offset = -get_cmos_time();
1394 cmos_utc_offset += (wc_sec + (wc_nsec + NOW()) / 1000000000ULL);
1395 kill_timer(&calibration_timer);
1397 /* Sync platform timer stamps. */
1398 platform_time_calibration();
1401 /* Better to cancel calibration timer for accuracy. */
1402 clear_bit(TIME_CALIBRATE_SOFTIRQ, &softirq_pending(smp_processor_id()));
1404 return 0;
1407 int time_resume(void)
1409 /*u64 tmp = */init_pit_and_calibrate_tsc();
1411 /* Disable this while calibrate_tsc_ap() also is skipped. */
1412 /*set_time_scale(&this_cpu(cpu_time).tsc_scale, tmp);*/
1414 resume_platform_timer();
1416 disable_pit_irq();
1418 init_percpu_time();
1420 do_settime(get_cmos_time() + cmos_utc_offset, 0, NOW());
1422 update_vcpu_system_time(current);
1424 return 0;
1427 int dom0_pit_access(struct ioreq *ioreq)
1429 /* Is Xen using Channel 2? Then disallow direct dom0 access. */
1430 if ( using_pit )
1431 return 0;
1433 switch ( ioreq->addr )
1435 case PIT_CH2:
1436 if ( ioreq->dir == IOREQ_READ )
1437 ioreq->data = inb(PIT_CH2);
1438 else
1439 outb(ioreq->data, PIT_CH2);
1440 return 1;
1442 case PIT_MODE:
1443 if ( ioreq->dir == IOREQ_READ )
1444 return 0; /* urk! */
1445 switch ( ioreq->data & 0xc0 )
1447 case 0xc0: /* Read Back */
1448 if ( ioreq->data & 0x08 ) /* Select Channel 2? */
1449 outb(ioreq->data & 0xf8, PIT_MODE);
1450 if ( !(ioreq->data & 0x06) ) /* Select Channel 0/1? */
1451 return 1; /* no - we're done */
1452 /* Filter Channel 2 and reserved bit 0. */
1453 ioreq->data &= ~0x09;
1454 return 0; /* emulate ch0/1 readback */
1455 case 0x80: /* Select Counter 2 */
1456 outb(ioreq->data, PIT_MODE);
1457 return 1;
1460 case 0x61:
1461 if ( ioreq->dir == IOREQ_READ )
1462 ioreq->data = inb(0x61);
1463 else
1464 outb((inb(0x61) & ~3) | (ioreq->data & 3), 0x61);
1465 return 1;
1468 return 0;
1471 struct tm wallclock_time(void)
1473 uint64_t seconds;
1475 if ( !wc_sec )
1476 return (struct tm) { 0 };
1478 seconds = NOW() + (wc_sec * 1000000000ull) + wc_nsec;
1479 do_div(seconds, 1000000000);
1480 return gmtime(seconds);
1483 /*
1484 * TSC Reliability check
1485 */
1487 /*
1488 * The Linux original version of this function is
1489 * Copyright (c) 2006, Red Hat, Inc., Ingo Molnar
1490 */
1491 void check_tsc_warp(unsigned long tsc_khz, unsigned long *max_warp)
1493 #define rdtsc_barrier() mb()
1494 static DEFINE_SPINLOCK(sync_lock);
1495 static cycles_t last_tsc;
1497 cycles_t start, now, prev, end;
1498 int i;
1500 rdtsc_barrier();
1501 start = get_cycles();
1502 rdtsc_barrier();
1504 /* The measurement runs for 20 msecs: */
1505 end = start + tsc_khz * 20ULL;
1506 now = start;
1508 for ( i = 0; ; i++ )
1510 /*
1511 * We take the global lock, measure TSC, save the
1512 * previous TSC that was measured (possibly on
1513 * another CPU) and update the previous TSC timestamp.
1514 */
1515 spin_lock(&sync_lock);
1516 prev = last_tsc;
1517 rdtsc_barrier();
1518 now = get_cycles();
1519 rdtsc_barrier();
1520 last_tsc = now;
1521 spin_unlock(&sync_lock);
1523 /*
1524 * Be nice every now and then (and also check whether measurement is
1525 * done [we also insert a 10 million loops safety exit, so we dont
1526 * lock up in case the TSC readout is totally broken]):
1527 */
1528 if ( unlikely(!(i & 7)) )
1530 if ( (now > end) || (i > 10000000) )
1531 break;
1532 cpu_relax();
1533 /*touch_nmi_watchdog();*/
1536 /*
1537 * Outside the critical section we can now see whether we saw a
1538 * time-warp of the TSC going backwards:
1539 */
1540 if ( unlikely(prev > now) )
1542 spin_lock(&sync_lock);
1543 if ( *max_warp < prev - now )
1544 *max_warp = prev - now;
1545 spin_unlock(&sync_lock);
1550 static unsigned long tsc_max_warp, tsc_check_count;
1551 static cpumask_t tsc_check_cpumask = CPU_MASK_NONE;
1553 static void tsc_check_slave(void *unused)
1555 unsigned int cpu = smp_processor_id();
1556 local_irq_disable();
1557 while ( !cpu_isset(cpu, tsc_check_cpumask) )
1558 mb();
1559 check_tsc_warp(cpu_khz, &tsc_max_warp);
1560 cpu_clear(cpu, tsc_check_cpumask);
1561 local_irq_enable();
1564 void tsc_check_reliability(void)
1566 unsigned int cpu = smp_processor_id();
1567 static DEFINE_SPINLOCK(lock);
1569 spin_lock(&lock);
1571 tsc_check_count++;
1572 smp_call_function(tsc_check_slave, NULL, 0);
1573 tsc_check_cpumask = cpu_online_map;
1574 local_irq_disable();
1575 check_tsc_warp(cpu_khz, &tsc_max_warp);
1576 cpu_clear(cpu, tsc_check_cpumask);
1577 local_irq_enable();
1578 while ( !cpus_empty(tsc_check_cpumask) )
1579 cpu_relax();
1581 spin_unlock(&lock);
1584 /*
1585 * PV SoftTSC Emulation.
1586 */
1588 void pv_soft_rdtsc(struct vcpu *v, struct cpu_user_regs *regs, int rdtscp)
1590 s_time_t now = get_s_time();
1591 struct domain *d = v->domain;
1593 spin_lock(&d->arch.vtsc_lock);
1595 if ( guest_kernel_mode(v, regs) )
1596 d->arch.vtsc_kerncount++;
1597 else
1598 d->arch.vtsc_usercount++;
1600 if ( (int64_t)(now - d->arch.vtsc_last) > 0 )
1601 d->arch.vtsc_last = now;
1602 else
1603 now = ++d->arch.vtsc_last;
1605 spin_unlock(&d->arch.vtsc_lock);
1607 now = scale_delta(now - d->arch.vtsc_offset, &d->arch.ns_to_vtsc);
1609 regs->eax = (uint32_t)now;
1610 regs->edx = (uint32_t)(now >> 32);
1612 if ( rdtscp )
1613 regs->ecx =
1614 (d->arch.tsc_mode == TSC_MODE_PVRDTSCP) ? d->arch.incarnation : 0;
1617 static int host_tsc_is_safe(void)
1619 extern unsigned int max_cstate;
1621 if ( boot_cpu_has(X86_FEATURE_TSC_RELIABLE) )
1622 return 1;
1623 if ( num_online_cpus() == 1 )
1624 return 1;
1625 if ( boot_cpu_has(X86_FEATURE_CONSTANT_TSC) && max_cstate <= 2 )
1627 if ( !tsc_check_count )
1628 tsc_check_reliability();
1629 if ( tsc_max_warp == 0 )
1630 return 1;
1632 return 0;
1635 void cpuid_time_leaf(uint32_t sub_idx, uint32_t *eax, uint32_t *ebx,
1636 uint32_t *ecx, uint32_t *edx)
1638 struct domain *d = current->domain;
1639 uint64_t offset;
1641 switch ( sub_idx )
1643 case 0: /* features */
1644 *eax = ( ( (!!d->arch.vtsc) << 0 ) |
1645 ( (!!host_tsc_is_safe()) << 1 ) |
1646 ( (!!boot_cpu_has(X86_FEATURE_RDTSCP)) << 2 ) |
1647 0 );
1648 *ebx = d->arch.tsc_mode;
1649 *ecx = d->arch.tsc_khz;
1650 *edx = d->arch.incarnation;
1651 break;
1652 case 1: /* scale and offset */
1653 if ( !d->arch.vtsc )
1654 offset = d->arch.vtsc_offset;
1655 else
1656 /* offset already applied to value returned by virtual rdtscp */
1657 offset = 0;
1658 *eax = (uint32_t)offset;
1659 *ebx = (uint32_t)(offset >> 32);
1660 *ecx = d->arch.vtsc_to_ns.mul_frac;
1661 *edx = (s8)d->arch.vtsc_to_ns.shift;
1662 break;
1663 case 2: /* physical cpu_khz */
1664 *eax = cpu_khz;
1665 *ebx = *ecx = *edx = 0;
1666 break;
1667 default:
1668 *eax = *ebx = *ecx = *edx = 0;
1672 /*
1673 * called to collect tsc-related data only for save file or live
1674 * migrate; called after last rdtsc is done on this incarnation
1675 */
1676 void tsc_get_info(struct domain *d, uint32_t *tsc_mode,
1677 uint64_t *elapsed_nsec, uint32_t *gtsc_khz,
1678 uint32_t *incarnation)
1680 *incarnation = d->arch.incarnation;
1681 switch ( *tsc_mode = d->arch.tsc_mode )
1683 case TSC_MODE_NEVER_EMULATE:
1684 *elapsed_nsec = *gtsc_khz = 0;
1685 break;
1686 case TSC_MODE_ALWAYS_EMULATE:
1687 *elapsed_nsec = get_s_time() - d->arch.vtsc_offset;
1688 *gtsc_khz = d->arch.tsc_khz;
1689 break;
1690 case TSC_MODE_DEFAULT:
1691 if ( d->arch.vtsc )
1693 *elapsed_nsec = get_s_time() - d->arch.vtsc_offset;
1694 *gtsc_khz = d->arch.tsc_khz;
1695 } else {
1696 uint64_t tsc = 0;
1697 rdtscll(tsc);
1698 *elapsed_nsec = scale_delta(tsc,&d->arch.vtsc_to_ns);
1699 *gtsc_khz = cpu_khz;
1701 break;
1702 case TSC_MODE_PVRDTSCP:
1703 if ( d->arch.vtsc )
1705 *elapsed_nsec = get_s_time() - d->arch.vtsc_offset;
1706 *gtsc_khz = cpu_khz;
1707 } else {
1708 uint64_t tsc = 0;
1709 rdtscll(tsc);
1710 *elapsed_nsec = scale_delta(tsc,&d->arch.vtsc_to_ns) -
1711 d->arch.vtsc_offset;
1712 *gtsc_khz = 0; /* ignored by tsc_set_info */
1714 break;
1718 /*
1719 * This may be called as many as three times for a domain, once when the
1720 * hypervisor creates the domain, once when the toolstack creates the
1721 * domain and, if restoring/migrating, once when saved/migrated values
1722 * are restored. Care must be taken that, if multiple calls occur,
1723 * only the last "sticks" and all are completed before the guest executes
1724 * an rdtsc instruction
1725 */
1726 void tsc_set_info(struct domain *d,
1727 uint32_t tsc_mode, uint64_t elapsed_nsec,
1728 uint32_t gtsc_khz, uint32_t incarnation)
1730 if ( d->domain_id == 0 || d->domain_id == DOMID_INVALID )
1732 d->arch.vtsc = 0;
1733 return;
1735 switch ( d->arch.tsc_mode = tsc_mode )
1737 case TSC_MODE_NEVER_EMULATE:
1738 d->arch.vtsc = 0;
1739 break;
1740 case TSC_MODE_ALWAYS_EMULATE:
1741 d->arch.vtsc = 1;
1742 d->arch.vtsc_offset = get_s_time() - elapsed_nsec;
1743 d->arch.tsc_khz = gtsc_khz ? gtsc_khz : cpu_khz;
1744 set_time_scale(&d->arch.vtsc_to_ns, d->arch.tsc_khz * 1000 );
1745 d->arch.ns_to_vtsc = scale_reciprocal(d->arch.vtsc_to_ns);
1746 break;
1747 case TSC_MODE_DEFAULT:
1748 d->arch.vtsc = 1;
1749 d->arch.vtsc_offset = get_s_time() - elapsed_nsec;
1750 d->arch.tsc_khz = gtsc_khz ? gtsc_khz : cpu_khz;
1751 set_time_scale(&d->arch.vtsc_to_ns, d->arch.tsc_khz * 1000 );
1752 /* use native TSC if initial host has safe TSC and not migrated yet */
1753 if ( host_tsc_is_safe() && incarnation == 0 )
1754 d->arch.vtsc = 0;
1755 else
1756 d->arch.ns_to_vtsc = scale_reciprocal(d->arch.vtsc_to_ns);
1757 break;
1758 case TSC_MODE_PVRDTSCP:
1759 d->arch.vtsc = boot_cpu_has(X86_FEATURE_RDTSCP) &&
1760 host_tsc_is_safe() ? 0 : 1;
1761 d->arch.tsc_khz = cpu_khz;
1762 set_time_scale(&d->arch.vtsc_to_ns, d->arch.tsc_khz * 1000 );
1763 d->arch.ns_to_vtsc = scale_reciprocal(d->arch.vtsc_to_ns);
1764 if ( d->arch.vtsc )
1765 d->arch.vtsc_offset = get_s_time() - elapsed_nsec;
1766 else {
1767 /* when using native TSC, offset is nsec relative to power-on
1768 * of physical machine */
1769 uint64_t tsc = 0;
1770 rdtscll(tsc);
1771 d->arch.vtsc_offset = scale_delta(tsc,&d->arch.vtsc_to_ns) -
1772 elapsed_nsec;
1774 break;
1776 d->arch.incarnation = incarnation + 1;
1777 if ( is_hvm_domain(d) )
1778 hvm_set_rdtsc_exiting(d, d->arch.vtsc || hvm_gtsc_need_scale(d));
1781 /* vtsc may incur measurable performance degradation, diagnose with this */
1782 static void dump_softtsc(unsigned char key)
1784 struct domain *d;
1785 int domcnt = 0;
1786 extern unsigned int max_cstate;
1788 tsc_check_reliability();
1789 if ( boot_cpu_has(X86_FEATURE_TSC_RELIABLE) )
1790 printk("TSC marked as reliable, "
1791 "warp = %lu (count=%lu)\n", tsc_max_warp, tsc_check_count);
1792 else if ( boot_cpu_has(X86_FEATURE_CONSTANT_TSC ) )
1794 printk("TSC has constant rate, ");
1795 if (max_cstate <= 2 && tsc_max_warp == 0)
1796 printk("no deep Cstates, passed warp test, deemed reliable, ");
1797 else
1798 printk("deep Cstates possible, so not reliable, ");
1799 printk("warp=%lu (count=%lu)\n", tsc_max_warp, tsc_check_count);
1800 } else
1801 printk("TSC not marked as either constant or reliable, "
1802 "warp=%lu (count=%lu)\n", tsc_max_warp, tsc_check_count);
1803 for_each_domain ( d )
1805 if ( d->domain_id == 0 && d->arch.tsc_mode == TSC_MODE_DEFAULT )
1806 continue;
1807 printk("dom%u%s: mode=%d",d->domain_id,
1808 is_hvm_domain(d) ? "(hvm)" : "", d->arch.tsc_mode);
1809 if ( d->arch.vtsc_offset )
1810 printk(",ofs=0x%"PRIx64"",d->arch.vtsc_offset);
1811 if ( d->arch.tsc_khz )
1812 printk(",khz=%"PRIu32"",d->arch.tsc_khz);
1813 if ( d->arch.incarnation )
1814 printk(",inc=%"PRIu32"",d->arch.incarnation);
1815 if ( !(d->arch.vtsc_kerncount | d->arch.vtsc_usercount) )
1817 printk("\n");
1818 continue;
1820 if ( is_hvm_domain(d) )
1821 printk(",vtsc count: %"PRIu64" total\n",
1822 d->arch.vtsc_kerncount);
1823 else
1824 printk(",vtsc count: %"PRIu64" kernel, %"PRIu64" user\n",
1825 d->arch.vtsc_kerncount, d->arch.vtsc_usercount);
1826 domcnt++;
1829 if ( !domcnt )
1830 printk("No domains have emulated TSC\n");
1833 static struct keyhandler dump_softtsc_keyhandler = {
1834 .diagnostic = 1,
1835 .u.fn = dump_softtsc,
1836 .desc = "dump softtsc stats"
1837 };
1839 static int __init setup_dump_softtsc(void)
1841 register_keyhandler('s', &dump_softtsc_keyhandler);
1842 return 0;
1844 __initcall(setup_dump_softtsc);
1846 /*
1847 * Local variables:
1848 * mode: C
1849 * c-set-style: "BSD"
1850 * c-basic-offset: 4
1851 * tab-width: 4
1852 * indent-tabs-mode: nil
1853 * End:
1854 */