2 * Copyright (c) 2000-2010 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
33 * File: i386/rtclock.c
34 * Purpose: Routines for handling the machine dependent
35 * real-time clock. Historically, this clock is
36 * generated by the Intel 8254 Programmable Interval
37 * Timer, but local apic timers are now used for
38 * this purpose with the master time reference being
39 * the cpu clock counted by the timestamp MSR.
42 #include <platforms.h>
45 #include <mach/mach_types.h>
47 #include <kern/cpu_data.h>
48 #include <kern/cpu_number.h>
49 #include <kern/clock.h>
50 #include <kern/host_notify.h>
51 #include <kern/macro_help.h>
52 #include <kern/misc_protos.h>
54 #include <kern/assert.h>
55 #include <kern/etimer.h>
56 #include <mach/vm_prot.h>
58 #include <vm/vm_kern.h> /* for kernel_map */
60 #include <architecture/i386/pio.h>
61 #include <i386/machine_cpu.h>
62 #include <i386/cpuid.h>
63 #include <i386/cpu_threads.h>
65 #include <i386/machine_routines.h>
66 #include <i386/proc_reg.h>
67 #include <i386/misc_protos.h>
68 #include <i386/lapic.h>
69 #include <pexpert/pexpert.h>
70 #include <machine/limits.h>
71 #include <machine/commpage.h>
72 #include <sys/kdebug.h>
74 #include <i386/rtclock.h>
76 #define UI_CPUFREQ_ROUNDING_FACTOR 10000000
78 int rtclock_config(void);
80 int rtclock_init(void);
82 uint64_t tsc_rebase_abs_time
= 0;
84 void rtclock_intr(x86_saved_state_t
*regs
);
86 static void rtc_set_timescale(uint64_t cycles
);
87 static uint64_t rtc_export_speed(uint64_t cycles
);
89 rtc_nanotime_t rtc_nanotime_info
= {0,0,0,0,1,0};
91 static uint64_t rtc_decrementer_min
;
92 static uint64_t rtc_decrementer_max
;
95 deadline_to_decrementer(
102 return rtc_decrementer_min
;
104 delta
= deadline
- now
;
105 return MIN(MAX(rtc_decrementer_min
,delta
),rtc_decrementer_max
);
109 static inline uint64_t
110 _absolutetime_to_tsc(uint64_t ns
)
116 generation
= rtc_nanotime_info
.generation
;
117 tsc
= tmrCvt(ns
- rtc_nanotime_info
.ns_base
, tscFCvtn2t
)
118 + rtc_nanotime_info
.tsc_base
;
119 } while (generation
== 0 ||
120 generation
!= rtc_nanotime_info
.generation
);
126 * Regular local APIC timer case:
129 rtc_lapic_config_timer(void)
131 lapic_config_timer(TRUE
, one_shot
, divide_by_1
);
134 rtc_lapic_set_timer(uint64_t deadline
, uint64_t now
)
141 * Convert delta to bus ticks
142 * - time now is not relevant
144 count
= deadline_to_decrementer(deadline
, now
);
146 lapic_set_timer_fast((uint32_t) tmrCvt(count
, busFCvtn2t
));
148 lapic_set_timer(FALSE
, one_shot
, divide_by_1
, 0);
154 * TSC-deadline timer case:
157 rtc_lapic_config_tsc_deadline_timer(void)
159 lapic_config_tsc_deadline_timer();
162 rtc_lapic_set_tsc_deadline_timer(uint64_t deadline
, uint64_t now
)
170 set
= now
+ deadline_to_decrementer(deadline
, now
);
171 lapic_set_tsc_deadline_timer(_absolutetime_to_tsc(set
));
173 lapic_set_tsc_deadline_timer(0);
179 * Definitions for timer operations table
182 void (*config
)(void);
183 uint64_t (*set
) (uint64_t, uint64_t);
186 rtc_timer_t rtc_timer_lapic
= {
187 rtc_lapic_config_timer
,
191 rtc_timer_t rtc_timer_tsc_deadline
= {
192 rtc_lapic_config_tsc_deadline_timer
,
193 rtc_lapic_set_tsc_deadline_timer
196 rtc_timer_t
*rtc_timer
= &rtc_timer_lapic
; /* defaults to LAPIC timer */
199 * rtc_timer_init() is called at startup on the boot processor only.
204 int TSC_deadline_timer
= 0;
206 /* See whether we can use the local apic in TSC-deadline mode */
207 if ((cpuid_features() & CPUID_FEATURE_TSCTMR
)) {
208 TSC_deadline_timer
= 1;
209 PE_parse_boot_argn("TSC_deadline_timer", &TSC_deadline_timer
,
210 sizeof(TSC_deadline_timer
));
211 printf("TSC Deadline Timer supported %s enabled\n",
212 TSC_deadline_timer
? "and" : "but not");
215 if (TSC_deadline_timer
) {
216 rtc_timer
= &rtc_timer_tsc_deadline
;
217 rtc_decrementer_max
= UINT64_MAX
; /* effectively none */
219 * The min could be as low as 1nsec,
220 * but we're being conservative for now and making it the same
221 * as for the local apic timer.
223 rtc_decrementer_min
= 1*NSEC_PER_USEC
; /* 1 usec */
226 * Compute the longest interval using LAPIC timer.
228 rtc_decrementer_max
= tmrCvt(0x7fffffffULL
, busFCvtt2n
);
229 kprintf("maxDec: %lld\n", rtc_decrementer_max
);
230 rtc_decrementer_min
= 1*NSEC_PER_USEC
; /* 1 usec */
233 /* Point LAPIC interrupts to hardclock() */
234 lapic_set_timer_func((i386_intr_func_t
) rtclock_intr
);
237 static inline uint64_t
238 rtc_timer_set(uint64_t deadline
, uint64_t now
)
240 return rtc_timer
->set(deadline
, now
);
244 rtc_timer_start(void)
247 * Force a complete re-evaluation of timer deadlines.
249 etimer_resync_deadlines();
253 * tsc_to_nanoseconds:
255 * Basic routine to convert a raw 64 bit TSC value to a
256 * 64 bit nanosecond value. The conversion is implemented
257 * based on the scale factor and an implicit 32 bit shift.
259 static inline uint64_t
260 _tsc_to_nanoseconds(uint64_t value
)
262 #if defined(__i386__)
263 asm volatile("movl %%edx,%%esi ;"
271 : "c" (rtc_nanotime_info
.scale
)
273 #elif defined(__x86_64__)
274 asm volatile("mul %%rcx;"
279 : "a"(value
), "c"(rtc_nanotime_info
.scale
)
282 #error Unsupported architecture
288 static inline uint32_t
289 _absolutetime_to_microtime(uint64_t abstime
, clock_sec_t
*secs
, clock_usec_t
*microsecs
)
292 #if defined(__i386__)
295 : "=a" (*secs
), "=d" (remain
)
296 : "A" (abstime
), "r" (NSEC_PER_SEC
));
300 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
301 #elif defined(__x86_64__)
302 *secs
= abstime
/ (uint64_t)NSEC_PER_SEC
;
303 remain
= (uint32_t)(abstime
% (uint64_t)NSEC_PER_SEC
);
304 *microsecs
= remain
/ NSEC_PER_USEC
;
306 #error Unsupported architecture
312 _absolutetime_to_nanotime(uint64_t abstime
, clock_sec_t
*secs
, clock_usec_t
*nanosecs
)
314 #if defined(__i386__)
317 : "=a" (*secs
), "=d" (*nanosecs
)
318 : "A" (abstime
), "r" (NSEC_PER_SEC
));
319 #elif defined(__x86_64__)
320 *secs
= abstime
/ (uint64_t)NSEC_PER_SEC
;
321 *nanosecs
= (clock_usec_t
)(abstime
% (uint64_t)NSEC_PER_SEC
);
323 #error Unsupported architecture
328 * Configure the real-time clock device. Return success (1)
341 * Nanotime/mach_absolutime_time
342 * -----------------------------
343 * The timestamp counter (TSC) - which counts cpu clock cycles and can be read
344 * efficiently by the kernel and in userspace - is the reference for all timing.
345 * The cpu clock rate is platform-dependent and may stop or be reset when the
346 * processor is napped/slept. As a result, nanotime is the software abstraction
347 * used to maintain a monotonic clock, adjusted from an outside reference as needed.
349 * The kernel maintains nanotime information recording:
350 * - the ratio of tsc to nanoseconds
351 * with this ratio expressed as a 32-bit scale and shift
352 * (power of 2 divider);
353 * - { tsc_base, ns_base } pair of corresponding timestamps.
355 * The tuple {tsc_base, ns_base, scale, shift} is exported in the commpage
356 * for the userspace nanotime routine to read.
358 * All of the routines which update the nanotime data are non-reentrant. This must
359 * be guaranteed by the caller.
362 rtc_nanotime_set_commpage(rtc_nanotime_t
*rntp
)
364 commpage_set_nanotime(rntp
->tsc_base
, rntp
->ns_base
, rntp
->scale
, rntp
->shift
);
370 * Intialize the nanotime info from the base time.
373 _rtc_nanotime_init(rtc_nanotime_t
*rntp
, uint64_t base
)
375 uint64_t tsc
= rdtsc64();
377 _rtc_nanotime_store(tsc
, base
, rntp
->scale
, rntp
->shift
, rntp
);
381 rtc_nanotime_init(uint64_t base
)
383 _rtc_nanotime_init(&rtc_nanotime_info
, base
);
384 rtc_nanotime_set_commpage(&rtc_nanotime_info
);
388 * rtc_nanotime_init_commpage:
390 * Call back from the commpage initialization to
391 * cause the commpage data to be filled in once the
392 * commpages have been created.
395 rtc_nanotime_init_commpage(void)
397 spl_t s
= splclock();
399 rtc_nanotime_set_commpage(&rtc_nanotime_info
);
407 * Returns the current nanotime value, accessable from any
410 static inline uint64_t
411 rtc_nanotime_read(void)
415 if (gPEClockFrequencyInfo
.timebase_frequency_hz
> SLOW_TSC_THRESHOLD
)
416 return _rtc_nanotime_read(&rtc_nanotime_info
, 1); /* slow processor */
419 return _rtc_nanotime_read(&rtc_nanotime_info
, 0); /* assume fast processor */
425 * Invoked from power management when we exit from a low C-State (>= C4)
426 * and the TSC has stopped counting. The nanotime data is updated according
427 * to the provided value which represents the new value for nanotime.
430 rtc_clock_napped(uint64_t base
, uint64_t tsc_base
)
432 rtc_nanotime_t
*rntp
= &rtc_nanotime_info
;
437 assert(!ml_get_interrupts_enabled());
439 oldnsecs
= rntp
->ns_base
+ _tsc_to_nanoseconds(tsc
- rntp
->tsc_base
);
440 newnsecs
= base
+ _tsc_to_nanoseconds(tsc
- tsc_base
);
443 * Only update the base values if time using the new base values
444 * is later than the time using the old base values.
446 if (oldnsecs
< newnsecs
) {
447 _rtc_nanotime_store(tsc_base
, base
, rntp
->scale
, rntp
->shift
, rntp
);
448 rtc_nanotime_set_commpage(rntp
);
454 * Invoked from power management to correct the SFLM TSC entry drift problem:
455 * a small delta is added to the tsc_base. This is equivalent to nudging time
456 * backwards. We require this of the order of a TSC quantum which won't cause
457 * callers of mach_absolute_time() to see time going backwards!
460 rtc_clock_adjust(uint64_t tsc_base_delta
)
462 rtc_nanotime_t
*rntp
= &rtc_nanotime_info
;
464 assert(!ml_get_interrupts_enabled());
465 assert(tsc_base_delta
< 100ULL); /* i.e. it's small */
466 _rtc_nanotime_adjust(tsc_base_delta
, rntp
);
467 rtc_nanotime_set_commpage(rntp
);
472 rtc_clock_stepping(__unused
uint32_t new_frequency
,
473 __unused
uint32_t old_frequency
)
475 panic("rtc_clock_stepping unsupported");
479 rtc_clock_stepped(__unused
uint32_t new_frequency
,
480 __unused
uint32_t old_frequency
)
482 panic("rtc_clock_stepped unsupported");
488 * Invoked from power manageent when we have awoken from a sleep (S3)
489 * and the TSC has been reset. The nanotime data is updated based on
490 * the passed in value.
492 * The caller must guarantee non-reentrancy.
498 /* Set fixed configuration for lapic timers */
503 * The timestamp counter will have been reset
504 * but nanotime (uptime) marches onward.
506 rtc_nanotime_init(base
);
510 * Initialize the real-time clock device.
511 * In addition, various variables used to support the clock are initialized.
518 assert(!ml_get_interrupts_enabled());
520 if (cpu_number() == master_cpu
) {
523 rtc_set_timescale(tscFreq
);
526 * Adjust and set the exported cpu speed.
528 cycles
= rtc_export_speed(tscFreq
);
531 * Set min/max to actual.
532 * ACPI may update these later if speed-stepping is detected.
534 gPEClockFrequencyInfo
.cpu_frequency_min_hz
= cycles
;
535 gPEClockFrequencyInfo
.cpu_frequency_max_hz
= cycles
;
538 clock_timebase_init();
539 ml_init_lock_timeout();
542 /* Set fixed configuration for lapic timers */
551 // Code to calculate how many processor cycles are in a second...
554 rtc_set_timescale(uint64_t cycles
)
556 rtc_nanotime_t
*rntp
= &rtc_nanotime_info
;
557 rntp
->scale
= (uint32_t)(((uint64_t)NSEC_PER_SEC
<< 32) / cycles
);
559 if (cycles
<= SLOW_TSC_THRESHOLD
)
560 rntp
->shift
= (uint32_t)cycles
;
564 if (tsc_rebase_abs_time
== 0)
565 tsc_rebase_abs_time
= mach_absolute_time();
567 rtc_nanotime_init(0);
571 rtc_export_speed(uint64_t cyc_per_sec
)
576 cycles
= ((cyc_per_sec
+ (UI_CPUFREQ_ROUNDING_FACTOR
/2))
577 / UI_CPUFREQ_ROUNDING_FACTOR
)
578 * UI_CPUFREQ_ROUNDING_FACTOR
;
581 * Set current measured speed.
583 if (cycles
>= 0x100000000ULL
) {
584 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= 0xFFFFFFFFUL
;
586 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= (unsigned long)cycles
;
588 gPEClockFrequencyInfo
.cpu_frequency_hz
= cycles
;
590 kprintf("[RTCLOCK] frequency %llu (%llu)\n", cycles
, cyc_per_sec
);
595 clock_get_system_microtime(
597 clock_usec_t
*microsecs
)
599 uint64_t now
= rtc_nanotime_read();
601 _absolutetime_to_microtime(now
, secs
, microsecs
);
605 clock_get_system_nanotime(
607 clock_nsec_t
*nanosecs
)
609 uint64_t now
= rtc_nanotime_read();
611 _absolutetime_to_nanotime(now
, secs
, nanosecs
);
615 clock_gettimeofday_set_commpage(
620 clock_usec_t
*microsecs
)
622 uint64_t now
= abstime
+ offset
;
625 remain
= _absolutetime_to_microtime(now
, secs
, microsecs
);
627 *secs
+= (clock_sec_t
)epoch
;
629 commpage_set_timestamp(abstime
- remain
, *secs
);
634 mach_timebase_info_t info
)
636 info
->numer
= info
->denom
= 1;
640 * Real-time clock device interrupt.
644 x86_saved_state_t
*tregs
)
647 boolean_t user_mode
= FALSE
;
649 assert(get_preemption_level() > 0);
650 assert(!ml_get_interrupts_enabled());
652 if (is_saved_state64(tregs
) == TRUE
) {
653 x86_saved_state64_t
*regs
;
655 regs
= saved_state64(tregs
);
657 if (regs
->isf
.cs
& 0x03)
661 x86_saved_state32_t
*regs
;
663 regs
= saved_state32(tregs
);
670 /* call the generic etimer */
671 etimer_intr(user_mode
, rip
);
676 * Request timer pop from the hardware
686 /* 0 and EndOfAllTime are special-cases for "clear the timer" */
687 if (time
== 0 || time
== EndOfAllTime
) {
690 pop
= rtc_timer_set(0, 0);
692 now
= rtc_nanotime_read();
693 pop
= rtc_timer_set(time
, now
);
696 /* Record actual deadline set */
697 x86_lcpu()->rtcDeadline
= time
;
698 x86_lcpu()->rtcPop
= pop
;
701 * Pass back the delta we set
707 mach_absolute_time(void)
709 return rtc_nanotime_read();
713 clock_interval_to_absolutetime_interval(
715 uint32_t scale_factor
,
718 *result
= (uint64_t)interval
* scale_factor
;
722 absolutetime_to_microtime(
725 clock_usec_t
*microsecs
)
727 _absolutetime_to_microtime(abstime
, secs
, microsecs
);
731 absolutetime_to_nanotime(
734 clock_nsec_t
*nanosecs
)
736 _absolutetime_to_nanotime(abstime
, secs
, nanosecs
);
740 nanotime_to_absolutetime(
742 clock_nsec_t nanosecs
,
745 *result
= ((uint64_t)secs
* NSEC_PER_SEC
) + nanosecs
;
749 absolutetime_to_nanoseconds(
757 nanoseconds_to_absolutetime(
758 uint64_t nanoseconds
,
761 *result
= nanoseconds
;
772 now
= mach_absolute_time();
773 } while (now
< deadline
);