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 static void rtc_set_timescale(uint64_t cycles
);
90 static uint64_t rtc_export_speed(uint64_t cycles
);
92 rtc_nanotime_t rtc_nanotime_info
= {0,0,0,0,1,0};
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 asm volatile("movl %%edx,%%esi ;"
112 : "c" (current_cpu_datap()->cpu_nanotime
->scale
)
119 deadline_to_decrementer(
126 return rtc_decrementer_min
;
128 delta
= deadline
- now
;
129 return MIN(MAX(rtc_decrementer_min
,delta
),maxDec
);
134 rtc_lapic_start_ticking(void)
136 x86_lcpu_t
*lcpu
= x86_lcpu();
139 * Force a complete re-evaluation of timer deadlines.
141 lcpu
->rtcPop
= EndOfAllTime
;
142 etimer_resync_deadlines();
146 * Configure the real-time clock device. Return success (1)
159 * Nanotime/mach_absolutime_time
160 * -----------------------------
161 * The timestamp counter (TSC) - which counts cpu clock cycles and can be read
162 * efficiently by the kernel and in userspace - is the reference for all timing.
163 * The cpu clock rate is platform-dependent and may stop or be reset when the
164 * processor is napped/slept. As a result, nanotime is the software abstraction
165 * used to maintain a monotonic clock, adjusted from an outside reference as needed.
167 * The kernel maintains nanotime information recording:
168 * - the ratio of tsc to nanoseconds
169 * with this ratio expressed as a 32-bit scale and shift
170 * (power of 2 divider);
171 * - { tsc_base, ns_base } pair of corresponding timestamps.
173 * The tuple {tsc_base, ns_base, scale, shift} is exported in the commpage
174 * for the userspace nanotime routine to read.
176 * All of the routines which update the nanotime data are non-reentrant. This must
177 * be guaranteed by the caller.
180 rtc_nanotime_set_commpage(rtc_nanotime_t
*rntp
)
182 commpage_set_nanotime(rntp
->tsc_base
, rntp
->ns_base
, rntp
->scale
, rntp
->shift
);
188 * Intialize the nanotime info from the base time.
191 _rtc_nanotime_init(rtc_nanotime_t
*rntp
, uint64_t base
)
193 uint64_t tsc
= rdtsc64();
195 _rtc_nanotime_store(tsc
, base
, rntp
->scale
, rntp
->shift
, rntp
);
199 rtc_nanotime_init(uint64_t base
)
201 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
203 _rtc_nanotime_init(rntp
, base
);
204 rtc_nanotime_set_commpage(rntp
);
208 * rtc_nanotime_init_commpage:
210 * Call back from the commpage initialization to
211 * cause the commpage data to be filled in once the
212 * commpages have been created.
215 rtc_nanotime_init_commpage(void)
217 spl_t s
= splclock();
219 rtc_nanotime_set_commpage(current_cpu_datap()->cpu_nanotime
);
227 * Returns the current nanotime value, accessable from any
230 static inline uint64_t
231 rtc_nanotime_read(void)
235 if (gPEClockFrequencyInfo
.timebase_frequency_hz
> SLOW_TSC_THRESHOLD
)
236 return _rtc_nanotime_read(current_cpu_datap()->cpu_nanotime
, 1); /* slow processor */
239 return _rtc_nanotime_read(current_cpu_datap()->cpu_nanotime
, 0); /* assume fast processor */
245 * Invoked from power management when we exit from a low C-State (>= C4)
246 * and the TSC has stopped counting. The nanotime data is updated according
247 * to the provided value which represents the new value for nanotime.
250 rtc_clock_napped(uint64_t base
, uint64_t tsc_base
)
252 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
257 assert(!ml_get_interrupts_enabled());
259 oldnsecs
= rntp
->ns_base
+ _tsc_to_nanoseconds(tsc
- rntp
->tsc_base
);
260 newnsecs
= base
+ _tsc_to_nanoseconds(tsc
- tsc_base
);
263 * Only update the base values if time using the new base values
264 * is later than the time using the old base values.
266 if (oldnsecs
< newnsecs
) {
267 _rtc_nanotime_store(tsc_base
, base
, rntp
->scale
, rntp
->shift
, rntp
);
268 rtc_nanotime_set_commpage(rntp
);
273 rtc_clock_stepping(__unused
uint32_t new_frequency
,
274 __unused
uint32_t old_frequency
)
276 panic("rtc_clock_stepping unsupported");
280 rtc_clock_stepped(__unused
uint32_t new_frequency
,
281 __unused
uint32_t old_frequency
)
283 panic("rtc_clock_stepped unsupported");
289 * Invoked from power manageent when we have awoken from a sleep (S3)
290 * and the TSC has been reset. The nanotime data is updated based on
291 * the passed in value.
293 * The caller must guarantee non-reentrancy.
301 * The timestamp counter will have been reset
302 * but nanotime (uptime) marches onward.
304 rtc_nanotime_init(base
);
308 * Initialize the real-time clock device.
309 * In addition, various variables used to support the clock are initialized.
316 assert(!ml_get_interrupts_enabled());
318 if (cpu_number() == master_cpu
) {
321 rtc_set_timescale(tscFreq
);
324 * Adjust and set the exported cpu speed.
326 cycles
= rtc_export_speed(tscFreq
);
329 * Set min/max to actual.
330 * ACPI may update these later if speed-stepping is detected.
332 gPEClockFrequencyInfo
.cpu_frequency_min_hz
= cycles
;
333 gPEClockFrequencyInfo
.cpu_frequency_max_hz
= cycles
;
336 * Compute the longest interval we can represent.
338 maxDec
= tmrCvt(0x7fffffffULL
, busFCvtt2n
);
339 kprintf("maxDec: %lld\n", maxDec
);
341 /* Minimum interval is 1usec */
342 rtc_decrementer_min
= deadline_to_decrementer(NSEC_PER_USEC
, 0ULL);
343 /* Point LAPIC interrupts to hardclock() */
344 lapic_set_timer_func((i386_intr_func_t
) rtclock_intr
);
346 clock_timebase_init();
347 ml_init_lock_timeout();
350 rtc_lapic_start_ticking();
356 // Code to calculate how many processor cycles are in a second...
359 rtc_set_timescale(uint64_t cycles
)
361 rtc_nanotime_t
*rntp
= current_cpu_datap()->cpu_nanotime
;
362 rntp
->scale
= ((uint64_t)NSEC_PER_SEC
<< 32) / cycles
;
364 if (cycles
<= SLOW_TSC_THRESHOLD
)
365 rntp
->shift
= cycles
;
369 rtc_nanotime_init(0);
373 rtc_export_speed(uint64_t cyc_per_sec
)
378 cycles
= ((cyc_per_sec
+ (UI_CPUFREQ_ROUNDING_FACTOR
/2))
379 / UI_CPUFREQ_ROUNDING_FACTOR
)
380 * UI_CPUFREQ_ROUNDING_FACTOR
;
383 * Set current measured speed.
385 if (cycles
>= 0x100000000ULL
) {
386 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= 0xFFFFFFFFUL
;
388 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= (unsigned long)cycles
;
390 gPEClockFrequencyInfo
.cpu_frequency_hz
= cycles
;
392 kprintf("[RTCLOCK] frequency %llu (%llu)\n", cycles
, cyc_per_sec
);
397 clock_get_system_microtime(
401 uint64_t now
= rtc_nanotime_read();
406 : "=a" (*secs
), "=d" (remain
)
407 : "A" (now
), "r" (NSEC_PER_SEC
));
411 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
415 clock_get_system_nanotime(
419 uint64_t now
= rtc_nanotime_read();
423 : "=a" (*secs
), "=d" (*nanosecs
)
424 : "A" (now
), "r" (NSEC_PER_SEC
));
428 clock_gettimeofday_set_commpage(
435 uint64_t now
= abstime
;
442 : "=a" (*secs
), "=d" (remain
)
443 : "A" (now
), "r" (NSEC_PER_SEC
));
447 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
451 commpage_set_timestamp(abstime
- remain
, *secs
);
456 mach_timebase_info_t info
)
458 info
->numer
= info
->denom
= 1;
462 * Real-time clock device interrupt.
466 x86_saved_state_t
*tregs
)
469 boolean_t user_mode
= FALSE
;
472 x86_lcpu_t
*lcpu
= x86_lcpu();
474 assert(get_preemption_level() > 0);
475 assert(!ml_get_interrupts_enabled());
477 abstime
= rtc_nanotime_read();
478 latency
= (uint32_t)(abstime
- lcpu
->rtcDeadline
);
479 if (abstime
< lcpu
->rtcDeadline
)
482 if (is_saved_state64(tregs
) == TRUE
) {
483 x86_saved_state64_t
*regs
;
485 regs
= saved_state64(tregs
);
490 x86_saved_state32_t
*regs
;
492 regs
= saved_state32(tregs
);
499 /* Log the interrupt service latency (-ve value expected by tool) */
500 KERNEL_DEBUG_CONSTANT(
501 MACHDBG_CODE(DBG_MACH_EXCP_DECI
, 0) | DBG_FUNC_NONE
,
502 -latency
, (uint32_t)rip
, user_mode
, 0, 0);
504 /* call the generic etimer */
505 etimer_intr(user_mode
, rip
);
509 * Request timer pop from the hardware
520 now
= rtc_nanotime_read(); /* The time in nanoseconds */
521 decr
= deadline_to_decrementer(time
, now
);
523 count
= tmrCvt(decr
, busFCvtn2t
);
524 lapic_set_timer(TRUE
, one_shot
, divide_by_1
, (uint32_t) count
);
526 return decr
; /* Pass back what we set */
531 mach_absolute_time(void)
533 return rtc_nanotime_read();
537 clock_interval_to_absolutetime_interval(
539 uint32_t scale_factor
,
542 *result
= (uint64_t)interval
* scale_factor
;
546 absolutetime_to_microtime(
555 : "=a" (*secs
), "=d" (remain
)
556 : "A" (abstime
), "r" (NSEC_PER_SEC
));
560 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
564 absolutetime_to_nanotime(
571 : "=a" (*secs
), "=d" (*nanosecs
)
572 : "A" (abstime
), "r" (NSEC_PER_SEC
));
576 nanotime_to_absolutetime(
581 *result
= ((uint64_t)secs
* NSEC_PER_SEC
) + nanosecs
;
585 absolutetime_to_nanoseconds(
593 nanoseconds_to_absolutetime(
594 uint64_t nanoseconds
,
597 *result
= nanoseconds
;
608 now
= mach_absolute_time();
609 } while (now
< deadline
);