2 * Copyright (c) 2000-2008 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 <mach/vm_prot.h>
57 #include <vm/vm_kern.h> /* for kernel_map */
59 #include <architecture/i386/pio.h>
60 #include <i386/misc_protos.h>
61 #include <i386/proc_reg.h>
62 #include <i386/machine_cpu.h>
63 #include <i386/lapic.h>
64 #include <i386/cpuid.h>
65 #include <i386/cpu_data.h>
66 #include <i386/cpu_threads.h>
67 #include <i386/perfmon.h>
68 #include <i386/machine_routines.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 void rtclock_intr(x86_saved_state_t
*regs
);
87 static uint64_t maxDec
; /* longest interval our hardware timer can handle (nsec) */
89 /* XXX this should really be in a header somewhere */
90 extern clock_timer_func_t rtclock_timer_expire
;
92 static void rtc_set_timescale(uint64_t cycles
);
93 static uint64_t rtc_export_speed(uint64_t cycles
);
95 rtc_nanotime_t rtc_nanotime_info
= {0,0,0,0,1,0};
100 * Basic routine to convert a raw 64 bit TSC value to a
101 * 64 bit nanosecond value. The conversion is implemented
102 * based on the scale factor and an implicit 32 bit shift.
104 static inline uint64_t
105 _tsc_to_nanoseconds(uint64_t value
)
107 asm volatile("movl %%edx,%%esi ;"
115 : "c" (current_cpu_datap()->cpu_nanotime
->scale
)
122 deadline_to_decrementer(
129 return rtc_decrementer_min
;
131 delta
= deadline
- now
;
132 return MIN(MAX(rtc_decrementer_min
,delta
),maxDec
);
137 rtc_lapic_start_ticking(void)
139 x86_lcpu_t
*lcpu
= x86_lcpu();
142 * Force a complete re-evaluation of timer deadlines.
144 lcpu
->rtcPop
= EndOfAllTime
;
145 etimer_resync_deadlines();
149 * Configure the real-time clock device. Return success (1)
162 * Nanotime/mach_absolutime_time
163 * -----------------------------
164 * The timestamp counter (TSC) - which counts cpu clock cycles and can be read
165 * efficiently by the kernel and in userspace - is the reference for all timing.
166 * The cpu clock rate is platform-dependent and may stop or be reset when the
167 * processor is napped/slept. As a result, nanotime is the software abstraction
168 * used to maintain a monotonic clock, adjusted from an outside reference as needed.
170 * The kernel maintains nanotime information recording:
171 * - the ratio of tsc to nanoseconds
172 * with this ratio expressed as a 32-bit scale and shift
173 * (power of 2 divider);
174 * - { tsc_base, ns_base } pair of corresponding timestamps.
176 * The tuple {tsc_base, ns_base, scale, shift} is exported in the commpage
177 * for the userspace nanotime routine to read.
179 * All of the routines which update the nanotime data are non-reentrant. This must
180 * be guaranteed by the caller.
183 rtc_nanotime_set_commpage(rtc_nanotime_t
*rntp
)
185 commpage_set_nanotime(rntp
->tsc_base
, rntp
->ns_base
, rntp
->scale
, rntp
->shift
);
191 * Intialize the nanotime info from the base time.
194 _rtc_nanotime_init(rtc_nanotime_t
*rntp
, uint64_t base
)
196 uint64_t tsc
= rdtsc64();
198 _rtc_nanotime_store(tsc
, base
, rntp
->scale
, rntp
->shift
, rntp
);
202 rtc_nanotime_init(uint64_t base
)
204 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
206 _rtc_nanotime_init(rntp
, base
);
207 rtc_nanotime_set_commpage(rntp
);
211 * rtc_nanotime_init_commpage:
213 * Call back from the commpage initialization to
214 * cause the commpage data to be filled in once the
215 * commpages have been created.
218 rtc_nanotime_init_commpage(void)
220 spl_t s
= splclock();
222 rtc_nanotime_set_commpage(current_cpu_datap()->cpu_nanotime
);
230 * Returns the current nanotime value, accessable from any
233 static inline uint64_t
234 rtc_nanotime_read(void)
238 if (gPEClockFrequencyInfo
.timebase_frequency_hz
> SLOW_TSC_THRESHOLD
)
239 return _rtc_nanotime_read(current_cpu_datap()->cpu_nanotime
, 1); /* slow processor */
242 return _rtc_nanotime_read(current_cpu_datap()->cpu_nanotime
, 0); /* assume fast processor */
248 * Invoked from power management when we exit from a low C-State (>= C4)
249 * and the TSC has stopped counting. The nanotime data is updated according
250 * to the provided value which represents the new value for nanotime.
253 rtc_clock_napped(uint64_t base
, uint64_t tsc_base
)
255 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
260 assert(!ml_get_interrupts_enabled());
262 oldnsecs
= rntp
->ns_base
+ _tsc_to_nanoseconds(tsc
- rntp
->tsc_base
);
263 newnsecs
= base
+ _tsc_to_nanoseconds(tsc
- tsc_base
);
266 * Only update the base values if time using the new base values
267 * is later than the time using the old base values.
269 if (oldnsecs
< newnsecs
) {
270 _rtc_nanotime_store(tsc_base
, base
, rntp
->scale
, rntp
->shift
, rntp
);
271 rtc_nanotime_set_commpage(rntp
);
276 rtc_clock_stepping(__unused
uint32_t new_frequency
,
277 __unused
uint32_t old_frequency
)
279 panic("rtc_clock_stepping unsupported");
283 rtc_clock_stepped(__unused
uint32_t new_frequency
,
284 __unused
uint32_t old_frequency
)
286 panic("rtc_clock_stepped unsupported");
292 * Invoked from power manageent when we have awoken from a sleep (S3)
293 * and the TSC has been reset. The nanotime data is updated based on
294 * the passed in value.
296 * The caller must guarantee non-reentrancy.
304 * The timestamp counter will have been reset
305 * but nanotime (uptime) marches onward.
307 rtc_nanotime_init(base
);
311 * Initialize the real-time clock device.
312 * In addition, various variables used to support the clock are initialized.
319 assert(!ml_get_interrupts_enabled());
321 if (cpu_number() == master_cpu
) {
324 rtc_set_timescale(tscFreq
);
327 * Adjust and set the exported cpu speed.
329 cycles
= rtc_export_speed(tscFreq
);
332 * Set min/max to actual.
333 * ACPI may update these later if speed-stepping is detected.
335 gPEClockFrequencyInfo
.cpu_frequency_min_hz
= cycles
;
336 gPEClockFrequencyInfo
.cpu_frequency_max_hz
= cycles
;
339 * Compute the longest interval we can represent.
341 maxDec
= tmrCvt(0x7fffffffULL
, busFCvtt2n
);
342 kprintf("maxDec: %lld\n", maxDec
);
344 /* Minimum interval is 1usec */
345 rtc_decrementer_min
= deadline_to_decrementer(NSEC_PER_USEC
, 0ULL);
346 /* Point LAPIC interrupts to hardclock() */
347 lapic_set_timer_func((i386_intr_func_t
) rtclock_intr
);
349 clock_timebase_init();
350 ml_init_lock_timeout();
353 rtc_lapic_start_ticking();
359 // Code to calculate how many processor cycles are in a second...
362 rtc_set_timescale(uint64_t cycles
)
364 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
365 rntp
->scale
= ((uint64_t)NSEC_PER_SEC
<< 32) / cycles
;
367 if (cycles
<= SLOW_TSC_THRESHOLD
)
368 rntp
->shift
= cycles
;
372 rtc_nanotime_init(0);
376 rtc_export_speed(uint64_t cyc_per_sec
)
381 cycles
= ((cyc_per_sec
+ (UI_CPUFREQ_ROUNDING_FACTOR
/2))
382 / UI_CPUFREQ_ROUNDING_FACTOR
)
383 * UI_CPUFREQ_ROUNDING_FACTOR
;
386 * Set current measured speed.
388 if (cycles
>= 0x100000000ULL
) {
389 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= 0xFFFFFFFFUL
;
391 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= (unsigned long)cycles
;
393 gPEClockFrequencyInfo
.cpu_frequency_hz
= cycles
;
395 kprintf("[RTCLOCK] frequency %llu (%llu)\n", cycles
, cyc_per_sec
);
400 clock_get_system_microtime(
404 uint64_t now
= rtc_nanotime_read();
409 : "=a" (*secs
), "=d" (remain
)
410 : "A" (now
), "r" (NSEC_PER_SEC
));
414 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
418 clock_get_system_nanotime(
422 uint64_t now
= rtc_nanotime_read();
426 : "=a" (*secs
), "=d" (*nanosecs
)
427 : "A" (now
), "r" (NSEC_PER_SEC
));
431 clock_gettimeofday_set_commpage(
438 uint64_t now
= abstime
;
445 : "=a" (*secs
), "=d" (remain
)
446 : "A" (now
), "r" (NSEC_PER_SEC
));
450 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
454 commpage_set_timestamp(abstime
- remain
, *secs
);
459 mach_timebase_info_t info
)
461 info
->numer
= info
->denom
= 1;
465 clock_set_timer_func(
466 clock_timer_func_t func
)
468 if (rtclock_timer_expire
== NULL
)
469 rtclock_timer_expire
= func
;
473 * Real-time clock device interrupt.
477 x86_saved_state_t
*tregs
)
480 boolean_t user_mode
= FALSE
;
483 x86_lcpu_t
*lcpu
= x86_lcpu();
485 assert(get_preemption_level() > 0);
486 assert(!ml_get_interrupts_enabled());
488 abstime
= rtc_nanotime_read();
489 latency
= (uint32_t)(abstime
- lcpu
->rtcDeadline
);
490 if (abstime
< lcpu
->rtcDeadline
)
493 if (is_saved_state64(tregs
) == TRUE
) {
494 x86_saved_state64_t
*regs
;
496 regs
= saved_state64(tregs
);
501 x86_saved_state32_t
*regs
;
503 regs
= saved_state32(tregs
);
510 /* Log the interrupt service latency (-ve value expected by tool) */
511 KERNEL_DEBUG_CONSTANT(
512 MACHDBG_CODE(DBG_MACH_EXCP_DECI
, 0) | DBG_FUNC_NONE
,
513 -latency
, (uint32_t)rip
, user_mode
, 0, 0);
515 /* call the generic etimer */
516 etimer_intr(user_mode
, rip
);
520 * Request timer pop from the hardware
531 now
= rtc_nanotime_read(); /* The time in nanoseconds */
532 decr
= deadline_to_decrementer(time
, now
);
534 count
= tmrCvt(decr
, busFCvtn2t
);
535 lapic_set_timer(TRUE
, one_shot
, divide_by_1
, (uint32_t) count
);
537 return decr
; /* Pass back what we set */
542 mach_absolute_time(void)
544 return rtc_nanotime_read();
548 clock_interval_to_absolutetime_interval(
550 uint32_t scale_factor
,
553 *result
= (uint64_t)interval
* scale_factor
;
557 absolutetime_to_microtime(
566 : "=a" (*secs
), "=d" (remain
)
567 : "A" (abstime
), "r" (NSEC_PER_SEC
));
571 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
575 absolutetime_to_nanotime(
582 : "=a" (*secs
), "=d" (*nanosecs
)
583 : "A" (abstime
), "r" (NSEC_PER_SEC
));
587 nanotime_to_absolutetime(
592 *result
= ((uint64_t)secs
* NSEC_PER_SEC
) + nanosecs
;
596 absolutetime_to_nanoseconds(
604 nanoseconds_to_absolutetime(
605 uint64_t nanoseconds
,
608 *result
= nanoseconds
;
619 now
= mach_absolute_time();
620 } while (now
< deadline
);