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>
44 #include <mach/mach_types.h>
46 #include <kern/cpu_data.h>
47 #include <kern/cpu_number.h>
48 #include <kern/clock.h>
49 #include <kern/host_notify.h>
50 #include <kern/macro_help.h>
51 #include <kern/misc_protos.h>
53 #include <kern/assert.h>
54 #include <kern/etimer.h>
55 #include <mach/vm_prot.h>
57 #include <vm/vm_kern.h> /* for kernel_map */
58 #include <architecture/i386/pio.h>
59 #include <i386/machine_cpu.h>
60 #include <i386/cpuid.h>
61 #include <i386/cpu_threads.h>
63 #include <i386/machine_routines.h>
64 #include <i386/pal_routines.h>
65 #include <i386/proc_reg.h>
66 #include <i386/misc_protos.h>
67 #include <pexpert/pexpert.h>
68 #include <machine/limits.h>
69 #include <machine/commpage.h>
70 #include <sys/kdebug.h>
72 #include <i386/rtclock_protos.h>
74 #define UI_CPUFREQ_ROUNDING_FACTOR 10000000
76 int rtclock_config(void);
78 int rtclock_init(void);
80 uint64_t tsc_rebase_abs_time
= 0;
82 static void rtc_set_timescale(uint64_t cycles
);
83 static uint64_t rtc_export_speed(uint64_t cycles
);
89 * Force a complete re-evaluation of timer deadlines.
91 etimer_resync_deadlines();
97 * Basic routine to convert a raw 64 bit TSC value to a
98 * 64 bit nanosecond value. The conversion is implemented
99 * based on the scale factor and an implicit 32 bit shift.
101 static inline uint64_t
102 _tsc_to_nanoseconds(uint64_t value
)
104 #if defined(__i386__)
105 asm volatile("movl %%edx,%%esi ;"
113 : "c" (pal_rtc_nanotime_info
.scale
)
115 #elif defined(__x86_64__)
116 asm volatile("mul %%rcx;"
121 : "a"(value
), "c"(pal_rtc_nanotime_info
.scale
)
124 #error Unsupported architecture
130 static inline uint32_t
131 _absolutetime_to_microtime(uint64_t abstime
, clock_sec_t
*secs
, clock_usec_t
*microsecs
)
134 #if defined(__i386__)
137 : "=a" (*secs
), "=d" (remain
)
138 : "A" (abstime
), "r" (NSEC_PER_SEC
));
142 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
143 #elif defined(__x86_64__)
144 *secs
= abstime
/ (uint64_t)NSEC_PER_SEC
;
145 remain
= (uint32_t)(abstime
% (uint64_t)NSEC_PER_SEC
);
146 *microsecs
= remain
/ NSEC_PER_USEC
;
148 #error Unsupported architecture
154 _absolutetime_to_nanotime(uint64_t abstime
, clock_sec_t
*secs
, clock_usec_t
*nanosecs
)
156 #if defined(__i386__)
159 : "=a" (*secs
), "=d" (*nanosecs
)
160 : "A" (abstime
), "r" (NSEC_PER_SEC
));
161 #elif defined(__x86_64__)
162 *secs
= abstime
/ (uint64_t)NSEC_PER_SEC
;
163 *nanosecs
= (clock_usec_t
)(abstime
% (uint64_t)NSEC_PER_SEC
);
165 #error Unsupported architecture
170 * Configure the real-time clock device. Return success (1)
183 * Nanotime/mach_absolutime_time
184 * -----------------------------
185 * The timestamp counter (TSC) - which counts cpu clock cycles and can be read
186 * efficiently by the kernel and in userspace - is the reference for all timing.
187 * The cpu clock rate is platform-dependent and may stop or be reset when the
188 * processor is napped/slept. As a result, nanotime is the software abstraction
189 * used to maintain a monotonic clock, adjusted from an outside reference as needed.
191 * The kernel maintains nanotime information recording:
192 * - the ratio of tsc to nanoseconds
193 * with this ratio expressed as a 32-bit scale and shift
194 * (power of 2 divider);
195 * - { tsc_base, ns_base } pair of corresponding timestamps.
197 * The tuple {tsc_base, ns_base, scale, shift} is exported in the commpage
198 * for the userspace nanotime routine to read.
200 * All of the routines which update the nanotime data are non-reentrant. This must
201 * be guaranteed by the caller.
204 rtc_nanotime_set_commpage(pal_rtc_nanotime_t
*rntp
)
206 commpage_set_nanotime(rntp
->tsc_base
, rntp
->ns_base
, rntp
->scale
, rntp
->shift
);
212 * Intialize the nanotime info from the base time.
215 _rtc_nanotime_init(pal_rtc_nanotime_t
*rntp
, uint64_t base
)
217 uint64_t tsc
= rdtsc64();
219 _pal_rtc_nanotime_store(tsc
, base
, rntp
->scale
, rntp
->shift
, rntp
);
223 rtc_nanotime_init(uint64_t base
)
225 _rtc_nanotime_init(&pal_rtc_nanotime_info
, base
);
226 rtc_nanotime_set_commpage(&pal_rtc_nanotime_info
);
230 * rtc_nanotime_init_commpage:
232 * Call back from the commpage initialization to
233 * cause the commpage data to be filled in once the
234 * commpages have been created.
237 rtc_nanotime_init_commpage(void)
239 spl_t s
= splclock();
241 rtc_nanotime_set_commpage(&pal_rtc_nanotime_info
);
248 * Returns the current nanotime value, accessable from any
251 static inline uint64_t
252 rtc_nanotime_read(void)
256 if (gPEClockFrequencyInfo
.timebase_frequency_hz
> SLOW_TSC_THRESHOLD
)
257 return _rtc_nanotime_read(&rtc_nanotime_info
, 1); /* slow processor */
260 return _rtc_nanotime_read(&pal_rtc_nanotime_info
, 0); /* assume fast processor */
266 * Invoked from power management when we exit from a low C-State (>= C4)
267 * and the TSC has stopped counting. The nanotime data is updated according
268 * to the provided value which represents the new value for nanotime.
271 rtc_clock_napped(uint64_t base
, uint64_t tsc_base
)
273 pal_rtc_nanotime_t
*rntp
= &pal_rtc_nanotime_info
;
278 assert(!ml_get_interrupts_enabled());
280 oldnsecs
= rntp
->ns_base
+ _tsc_to_nanoseconds(tsc
- rntp
->tsc_base
);
281 newnsecs
= base
+ _tsc_to_nanoseconds(tsc
- tsc_base
);
284 * Only update the base values if time using the new base values
285 * is later than the time using the old base values.
287 if (oldnsecs
< newnsecs
) {
288 _pal_rtc_nanotime_store(tsc_base
, base
, rntp
->scale
, rntp
->shift
, rntp
);
289 rtc_nanotime_set_commpage(rntp
);
290 trace_set_timebases(tsc_base
, base
);
295 * Invoked from power management to correct the SFLM TSC entry drift problem:
296 * a small delta is added to the tsc_base. This is equivalent to nudgin time
297 * backwards. We require this to be on the order of a TSC quantum which won't
298 * cause callers of mach_absolute_time() to see time going backwards!
301 rtc_clock_adjust(uint64_t tsc_base_delta
)
303 pal_rtc_nanotime_t
*rntp
= &pal_rtc_nanotime_info
;
305 assert(!ml_get_interrupts_enabled());
306 assert(tsc_base_delta
< 100ULL); /* i.e. it's small */
307 _rtc_nanotime_adjust(tsc_base_delta
, rntp
);
308 rtc_nanotime_set_commpage(rntp
);
312 rtc_clock_stepping(__unused
uint32_t new_frequency
,
313 __unused
uint32_t old_frequency
)
315 panic("rtc_clock_stepping unsupported");
319 rtc_clock_stepped(__unused
uint32_t new_frequency
,
320 __unused
uint32_t old_frequency
)
322 panic("rtc_clock_stepped unsupported");
328 * Invoked from power management when we have awoken from a sleep (S3)
329 * and the TSC has been reset. The nanotime data is updated based on
330 * the passed in value.
332 * The caller must guarantee non-reentrancy.
338 /* Set fixed configuration for lapic timers */
343 * The timestamp counter will have been reset
344 * but nanotime (uptime) marches onward.
346 rtc_nanotime_init(base
);
350 * Initialize the real-time clock device.
351 * In addition, various variables used to support the clock are initialized.
358 assert(!ml_get_interrupts_enabled());
360 if (cpu_number() == master_cpu
) {
363 rtc_set_timescale(tscFreq
);
366 * Adjust and set the exported cpu speed.
368 cycles
= rtc_export_speed(tscFreq
);
371 * Set min/max to actual.
372 * ACPI may update these later if speed-stepping is detected.
374 gPEClockFrequencyInfo
.cpu_frequency_min_hz
= cycles
;
375 gPEClockFrequencyInfo
.cpu_frequency_max_hz
= cycles
;
378 clock_timebase_init();
379 ml_init_lock_timeout();
380 ml_init_delay_spin_threshold();
383 /* Set fixed configuration for lapic timers */
391 // Code to calculate how many processor cycles are in a second...
394 rtc_set_timescale(uint64_t cycles
)
396 pal_rtc_nanotime_t
*rntp
= &pal_rtc_nanotime_info
;
397 rntp
->scale
= (uint32_t)(((uint64_t)NSEC_PER_SEC
<< 32) / cycles
);
400 if (cycles
<= SLOW_TSC_THRESHOLD
)
401 rntp
->shift
= (uint32_t)cycles
;
406 if (tsc_rebase_abs_time
== 0)
407 tsc_rebase_abs_time
= mach_absolute_time();
409 rtc_nanotime_init(0);
413 rtc_export_speed(uint64_t cyc_per_sec
)
418 cycles
= ((cyc_per_sec
+ (UI_CPUFREQ_ROUNDING_FACTOR
/2))
419 / UI_CPUFREQ_ROUNDING_FACTOR
)
420 * UI_CPUFREQ_ROUNDING_FACTOR
;
423 * Set current measured speed.
425 if (cycles
>= 0x100000000ULL
) {
426 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= 0xFFFFFFFFUL
;
428 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= (unsigned long)cycles
;
430 gPEClockFrequencyInfo
.cpu_frequency_hz
= cycles
;
432 kprintf("[RTCLOCK] frequency %llu (%llu)\n", cycles
, cyc_per_sec
);
437 clock_get_system_microtime(
439 clock_usec_t
*microsecs
)
441 uint64_t now
= rtc_nanotime_read();
443 _absolutetime_to_microtime(now
, secs
, microsecs
);
447 clock_get_system_nanotime(
449 clock_nsec_t
*nanosecs
)
451 uint64_t now
= rtc_nanotime_read();
453 _absolutetime_to_nanotime(now
, secs
, nanosecs
);
457 clock_gettimeofday_set_commpage(
462 clock_usec_t
*microsecs
)
464 uint64_t now
= abstime
+ offset
;
467 remain
= _absolutetime_to_microtime(now
, secs
, microsecs
);
469 *secs
+= (clock_sec_t
)epoch
;
471 commpage_set_timestamp(abstime
- remain
, *secs
);
476 mach_timebase_info_t info
)
478 info
->numer
= info
->denom
= 1;
482 * Real-time clock device interrupt.
486 x86_saved_state_t
*tregs
)
489 boolean_t user_mode
= FALSE
;
491 assert(get_preemption_level() > 0);
492 assert(!ml_get_interrupts_enabled());
494 if (is_saved_state64(tregs
) == TRUE
) {
495 x86_saved_state64_t
*regs
;
497 regs
= saved_state64(tregs
);
499 if (regs
->isf
.cs
& 0x03)
503 x86_saved_state32_t
*regs
;
505 regs
= saved_state32(tregs
);
512 /* call the generic etimer */
513 etimer_intr(user_mode
, rip
);
518 * Request timer pop from the hardware
528 /* 0 and EndOfAllTime are special-cases for "clear the timer" */
529 if (time
== 0 || time
== EndOfAllTime
) {
532 pop
= rtc_timer
->set(0, 0);
534 now
= rtc_nanotime_read(); /* The time in nanoseconds */
535 pop
= rtc_timer
->set(time
, now
);
538 /* Record requested and actual deadlines set */
539 x86_lcpu()->rtcDeadline
= time
;
540 x86_lcpu()->rtcPop
= pop
;
546 mach_absolute_time(void)
548 return rtc_nanotime_read();
552 clock_interval_to_absolutetime_interval(
554 uint32_t scale_factor
,
557 *result
= (uint64_t)interval
* scale_factor
;
561 absolutetime_to_microtime(
564 clock_usec_t
*microsecs
)
566 _absolutetime_to_microtime(abstime
, secs
, microsecs
);
570 absolutetime_to_nanotime(
573 clock_nsec_t
*nanosecs
)
575 _absolutetime_to_nanotime(abstime
, secs
, nanosecs
);
579 nanotime_to_absolutetime(
581 clock_nsec_t nanosecs
,
584 *result
= ((uint64_t)secs
* NSEC_PER_SEC
) + nanosecs
;
588 absolutetime_to_nanoseconds(
596 nanoseconds_to_absolutetime(
597 uint64_t nanoseconds
,
600 *result
= nanoseconds
;
611 now
= mach_absolute_time();
612 } while (now
< deadline
);