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 NSEC_PER_HZ (NSEC_PER_SEC / 100) /* nsec per tick */
78 #define UI_CPUFREQ_ROUNDING_FACTOR 10000000
80 int rtclock_config(void);
82 int rtclock_init(void);
84 uint64_t rtc_decrementer_min
;
86 uint64_t tsc_rebase_abs_time
= 0;
88 void rtclock_intr(x86_saved_state_t
*regs
);
89 static uint64_t maxDec
; /* longest interval our hardware timer can handle (nsec) */
91 static void rtc_set_timescale(uint64_t cycles
);
92 static uint64_t rtc_export_speed(uint64_t cycles
);
94 rtc_nanotime_t rtc_nanotime_info
= {0,0,0,0,1,0};
99 * Basic routine to convert a raw 64 bit TSC value to a
100 * 64 bit nanosecond value. The conversion is implemented
101 * based on the scale factor and an implicit 32 bit shift.
103 static inline uint64_t
104 _tsc_to_nanoseconds(uint64_t value
)
106 #if defined(__i386__)
107 asm volatile("movl %%edx,%%esi ;"
115 : "c" (current_cpu_datap()->cpu_nanotime
->scale
)
117 #elif defined(__x86_64__)
118 asm volatile("mul %%rcx;"
123 : "a"(value
), "c"(rtc_nanotime_info
.scale
)
126 #error Unsupported architecture
132 static inline uint32_t
133 _absolutetime_to_microtime(uint64_t abstime
, clock_sec_t
*secs
, clock_usec_t
*microsecs
)
136 #if defined(__i386__)
139 : "=a" (*secs
), "=d" (remain
)
140 : "A" (abstime
), "r" (NSEC_PER_SEC
));
144 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
145 #elif defined(__x86_64__)
146 *secs
= abstime
/ (uint64_t)NSEC_PER_SEC
;
147 remain
= (uint32_t)(abstime
% (uint64_t)NSEC_PER_SEC
);
148 *microsecs
= remain
/ NSEC_PER_USEC
;
150 #error Unsupported architecture
156 _absolutetime_to_nanotime(uint64_t abstime
, clock_sec_t
*secs
, clock_usec_t
*nanosecs
)
158 #if defined(__i386__)
161 : "=a" (*secs
), "=d" (*nanosecs
)
162 : "A" (abstime
), "r" (NSEC_PER_SEC
));
163 #elif defined(__x86_64__)
164 *secs
= abstime
/ (uint64_t)NSEC_PER_SEC
;
165 *nanosecs
= (clock_usec_t
)(abstime
% (uint64_t)NSEC_PER_SEC
);
167 #error Unsupported architecture
172 deadline_to_decrementer(
179 return (uint32_t)rtc_decrementer_min
;
181 delta
= deadline
- now
;
182 return (uint32_t)MIN(MAX(rtc_decrementer_min
,delta
),maxDec
);
187 rtc_lapic_start_ticking(void)
189 x86_lcpu_t
*lcpu
= x86_lcpu();
192 * Force a complete re-evaluation of timer deadlines.
194 lcpu
->rtcPop
= EndOfAllTime
;
195 etimer_resync_deadlines();
199 * Configure the real-time clock device. Return success (1)
212 * Nanotime/mach_absolutime_time
213 * -----------------------------
214 * The timestamp counter (TSC) - which counts cpu clock cycles and can be read
215 * efficiently by the kernel and in userspace - is the reference for all timing.
216 * The cpu clock rate is platform-dependent and may stop or be reset when the
217 * processor is napped/slept. As a result, nanotime is the software abstraction
218 * used to maintain a monotonic clock, adjusted from an outside reference as needed.
220 * The kernel maintains nanotime information recording:
221 * - the ratio of tsc to nanoseconds
222 * with this ratio expressed as a 32-bit scale and shift
223 * (power of 2 divider);
224 * - { tsc_base, ns_base } pair of corresponding timestamps.
226 * The tuple {tsc_base, ns_base, scale, shift} is exported in the commpage
227 * for the userspace nanotime routine to read.
229 * All of the routines which update the nanotime data are non-reentrant. This must
230 * be guaranteed by the caller.
233 rtc_nanotime_set_commpage(rtc_nanotime_t
*rntp
)
235 commpage_set_nanotime(rntp
->tsc_base
, rntp
->ns_base
, rntp
->scale
, rntp
->shift
);
241 * Intialize the nanotime info from the base time.
244 _rtc_nanotime_init(rtc_nanotime_t
*rntp
, uint64_t base
)
246 uint64_t tsc
= rdtsc64();
248 _rtc_nanotime_store(tsc
, base
, rntp
->scale
, rntp
->shift
, rntp
);
252 rtc_nanotime_init(uint64_t base
)
254 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
256 _rtc_nanotime_init(rntp
, base
);
257 rtc_nanotime_set_commpage(rntp
);
261 * rtc_nanotime_init_commpage:
263 * Call back from the commpage initialization to
264 * cause the commpage data to be filled in once the
265 * commpages have been created.
268 rtc_nanotime_init_commpage(void)
270 spl_t s
= splclock();
272 rtc_nanotime_set_commpage(current_cpu_datap()->cpu_nanotime
);
280 * Returns the current nanotime value, accessable from any
283 static inline uint64_t
284 rtc_nanotime_read(void)
288 if (gPEClockFrequencyInfo
.timebase_frequency_hz
> SLOW_TSC_THRESHOLD
)
289 return _rtc_nanotime_read(current_cpu_datap()->cpu_nanotime
, 1); /* slow processor */
292 return _rtc_nanotime_read(current_cpu_datap()->cpu_nanotime
, 0); /* assume fast processor */
298 * Invoked from power management when we exit from a low C-State (>= C4)
299 * and the TSC has stopped counting. The nanotime data is updated according
300 * to the provided value which represents the new value for nanotime.
303 rtc_clock_napped(uint64_t base
, uint64_t tsc_base
)
305 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
310 assert(!ml_get_interrupts_enabled());
312 oldnsecs
= rntp
->ns_base
+ _tsc_to_nanoseconds(tsc
- rntp
->tsc_base
);
313 newnsecs
= base
+ _tsc_to_nanoseconds(tsc
- tsc_base
);
316 * Only update the base values if time using the new base values
317 * is later than the time using the old base values.
319 if (oldnsecs
< newnsecs
) {
320 _rtc_nanotime_store(tsc_base
, base
, rntp
->scale
, rntp
->shift
, rntp
);
321 rtc_nanotime_set_commpage(rntp
);
327 * Invoked from power management to correct the SFLM TSC entry drift problem:
328 * a small delta is added to the tsc_base. This is equivalent to nudging time
329 * backwards. We require this of the order of a TSC quantum which won't cause
330 * callers of mach_absolute_time() to see time going backwards!
333 rtc_clock_adjust(uint64_t tsc_base_delta
)
335 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
337 assert(!ml_get_interrupts_enabled());
338 assert(tsc_base_delta
< 100ULL); /* i.e. it's small */
339 _rtc_nanotime_adjust(tsc_base_delta
, rntp
);
340 rtc_nanotime_set_commpage(rntp
);
345 rtc_clock_stepping(__unused
uint32_t new_frequency
,
346 __unused
uint32_t old_frequency
)
348 panic("rtc_clock_stepping unsupported");
352 rtc_clock_stepped(__unused
uint32_t new_frequency
,
353 __unused
uint32_t old_frequency
)
355 panic("rtc_clock_stepped unsupported");
361 * Invoked from power manageent when we have awoken from a sleep (S3)
362 * and the TSC has been reset. The nanotime data is updated based on
363 * the passed in value.
365 * The caller must guarantee non-reentrancy.
373 * The timestamp counter will have been reset
374 * but nanotime (uptime) marches onward.
376 rtc_nanotime_init(base
);
380 * Initialize the real-time clock device.
381 * In addition, various variables used to support the clock are initialized.
388 assert(!ml_get_interrupts_enabled());
390 if (cpu_number() == master_cpu
) {
393 rtc_set_timescale(tscFreq
);
396 * Adjust and set the exported cpu speed.
398 cycles
= rtc_export_speed(tscFreq
);
401 * Set min/max to actual.
402 * ACPI may update these later if speed-stepping is detected.
404 gPEClockFrequencyInfo
.cpu_frequency_min_hz
= cycles
;
405 gPEClockFrequencyInfo
.cpu_frequency_max_hz
= cycles
;
408 * Compute the longest interval we can represent.
410 maxDec
= tmrCvt(0x7fffffffULL
, busFCvtt2n
);
411 kprintf("maxDec: %lld\n", maxDec
);
413 /* Minimum interval is 1usec */
414 rtc_decrementer_min
= deadline_to_decrementer(NSEC_PER_USEC
, 0ULL);
415 /* Point LAPIC interrupts to hardclock() */
416 lapic_set_timer_func((i386_intr_func_t
) rtclock_intr
);
418 clock_timebase_init();
419 ml_init_lock_timeout();
422 rtc_lapic_start_ticking();
428 // Code to calculate how many processor cycles are in a second...
431 rtc_set_timescale(uint64_t cycles
)
433 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
434 rntp
->scale
= (uint32_t)(((uint64_t)NSEC_PER_SEC
<< 32) / cycles
);
436 if (cycles
<= SLOW_TSC_THRESHOLD
)
437 rntp
->shift
= (uint32_t)cycles
;
441 if (tsc_rebase_abs_time
== 0)
442 tsc_rebase_abs_time
= mach_absolute_time();
444 rtc_nanotime_init(0);
448 rtc_export_speed(uint64_t cyc_per_sec
)
453 cycles
= ((cyc_per_sec
+ (UI_CPUFREQ_ROUNDING_FACTOR
/2))
454 / UI_CPUFREQ_ROUNDING_FACTOR
)
455 * UI_CPUFREQ_ROUNDING_FACTOR
;
458 * Set current measured speed.
460 if (cycles
>= 0x100000000ULL
) {
461 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= 0xFFFFFFFFUL
;
463 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= (unsigned long)cycles
;
465 gPEClockFrequencyInfo
.cpu_frequency_hz
= cycles
;
467 kprintf("[RTCLOCK] frequency %llu (%llu)\n", cycles
, cyc_per_sec
);
472 clock_get_system_microtime(
474 clock_usec_t
*microsecs
)
476 uint64_t now
= rtc_nanotime_read();
478 _absolutetime_to_microtime(now
, secs
, microsecs
);
482 clock_get_system_nanotime(
484 clock_nsec_t
*nanosecs
)
486 uint64_t now
= rtc_nanotime_read();
488 _absolutetime_to_nanotime(now
, secs
, nanosecs
);
492 clock_gettimeofday_set_commpage(
497 clock_usec_t
*microsecs
)
499 uint64_t now
= abstime
+ offset
;
502 remain
= _absolutetime_to_microtime(now
, secs
, microsecs
);
504 *secs
+= (clock_sec_t
)epoch
;
506 commpage_set_timestamp(abstime
- remain
, *secs
);
511 mach_timebase_info_t info
)
513 info
->numer
= info
->denom
= 1;
517 * Real-time clock device interrupt.
521 x86_saved_state_t
*tregs
)
524 boolean_t user_mode
= FALSE
;
527 x86_lcpu_t
*lcpu
= x86_lcpu();
529 assert(get_preemption_level() > 0);
530 assert(!ml_get_interrupts_enabled());
532 abstime
= rtc_nanotime_read();
533 latency
= (uint32_t)(abstime
- lcpu
->rtcDeadline
);
534 if (abstime
< lcpu
->rtcDeadline
)
537 if (is_saved_state64(tregs
) == TRUE
) {
538 x86_saved_state64_t
*regs
;
540 regs
= saved_state64(tregs
);
542 if (regs
->isf
.cs
& 0x03)
546 x86_saved_state32_t
*regs
;
548 regs
= saved_state32(tregs
);
555 /* Log the interrupt service latency (-ve value expected by tool) */
556 KERNEL_DEBUG_CONSTANT(
557 MACHDBG_CODE(DBG_MACH_EXCP_DECI
, 0) | DBG_FUNC_NONE
,
558 -(int32_t)latency
, (uint32_t)rip
, user_mode
, 0, 0);
560 /* call the generic etimer */
561 etimer_intr(user_mode
, rip
);
565 * Request timer pop from the hardware
577 now
= rtc_nanotime_read(); /* The time in nanoseconds */
578 decr
= deadline_to_decrementer(time
, now
);
580 count
= tmrCvt(decr
, busFCvtn2t
);
581 lapic_set_timer(TRUE
, one_shot
, divide_by_1
, (uint32_t) count
);
583 return decr
; /* Pass back what we set */
588 mach_absolute_time(void)
590 return rtc_nanotime_read();
594 clock_interval_to_absolutetime_interval(
596 uint32_t scale_factor
,
599 *result
= (uint64_t)interval
* scale_factor
;
603 absolutetime_to_microtime(
606 clock_usec_t
*microsecs
)
608 _absolutetime_to_microtime(abstime
, secs
, microsecs
);
612 absolutetime_to_nanotime(
615 clock_nsec_t
*nanosecs
)
617 _absolutetime_to_nanotime(abstime
, secs
, nanosecs
);
621 nanotime_to_absolutetime(
623 clock_nsec_t nanosecs
,
626 *result
= ((uint64_t)secs
* NSEC_PER_SEC
) + nanosecs
;
630 absolutetime_to_nanoseconds(
638 nanoseconds_to_absolutetime(
639 uint64_t nanoseconds
,
642 *result
= nanoseconds
;
653 now
= mach_absolute_time();
654 } while (now
< deadline
);