2 * Copyright (c) 2000-2005 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_OSREFERENCE_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
10 * License may not be used to create, or enable the creation or
11 * redistribution of, unlawful or unlicensed copies of an Apple operating
12 * system, or to circumvent, violate, or enable the circumvention or
13 * violation of, any terms of an Apple operating system software license
16 * Please obtain a copy of the License at
17 * http://www.opensource.apple.com/apsl/ and read it before using this
20 * The Original Code and all software distributed under the License are
21 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
22 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
23 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
25 * Please see the License for the specific language governing rights and
26 * limitations under the License.
28 * @APPLE_LICENSE_OSREFERENCE_HEADER_END@
35 * File: i386/rtclock.c
36 * Purpose: Routines for handling the machine dependent
37 * real-time clock. Historically, this clock is
38 * generated by the Intel 8254 Programmable Interval
39 * Timer, but local apic timers are now used for
40 * this purpose with the master time reference being
41 * the cpu clock counted by the timestamp MSR.
44 #include <platforms.h>
47 #include <mach/mach_types.h>
49 #include <kern/cpu_data.h>
50 #include <kern/cpu_number.h>
51 #include <kern/clock.h>
52 #include <kern/host_notify.h>
53 #include <kern/macro_help.h>
54 #include <kern/misc_protos.h>
56 #include <kern/assert.h>
57 #include <mach/vm_prot.h>
59 #include <vm/vm_kern.h> /* for kernel_map */
62 #include <architecture/i386/pio.h>
63 #include <i386/misc_protos.h>
64 #include <i386/proc_reg.h>
65 #include <i386/machine_cpu.h>
67 #include <i386/cpuid.h>
68 #include <i386/cpu_data.h>
69 #include <i386/cpu_threads.h>
70 #include <i386/perfmon.h>
71 #include <i386/machine_routines.h>
72 #include <pexpert/pexpert.h>
73 #include <machine/limits.h>
74 #include <machine/commpage.h>
75 #include <sys/kdebug.h>
77 #include <i386/hpet.h>
78 #include <i386/rtclock.h>
80 #define MAX(a,b) (((a)>(b))?(a):(b))
81 #define MIN(a,b) (((a)>(b))?(b):(a))
83 #define NSEC_PER_HZ (NSEC_PER_SEC / 100) /* nsec per tick */
85 #define UI_CPUFREQ_ROUNDING_FACTOR 10000000
87 int rtclock_config(void);
89 int rtclock_init(void);
91 uint64_t rtc_decrementer_min
;
93 void rtclock_intr(x86_saved_state_t
*regs
);
94 static uint64_t maxDec
; /* longest interval our hardware timer can handle (nsec) */
96 /* XXX this should really be in a header somewhere */
97 extern clock_timer_func_t rtclock_timer_expire
;
99 static void rtc_set_timescale(uint64_t cycles
);
100 static uint64_t rtc_export_speed(uint64_t cycles
);
102 extern void rtc_nanotime_store(
107 rtc_nanotime_t
*dst
);
109 extern void rtc_nanotime_load(
111 rtc_nanotime_t
*dst
);
113 rtc_nanotime_t rtc_nanotime_info
;
116 * tsc_to_nanoseconds:
118 * Basic routine to convert a raw 64 bit TSC value to a
119 * 64 bit nanosecond value. The conversion is implemented
120 * based on the scale factor and an implicit 32 bit shift.
122 static inline uint64_t
123 _tsc_to_nanoseconds(uint64_t value
)
125 asm volatile("movl %%edx,%%esi ;"
132 : "+A" (value
) : "c" (rtc_nanotime_info
.scale
) : "esi", "edi");
138 tsc_to_nanoseconds(uint64_t value
)
140 return _tsc_to_nanoseconds(value
);
144 deadline_to_decrementer(
151 return rtc_decrementer_min
;
153 delta
= deadline
- now
;
154 return MIN(MAX(rtc_decrementer_min
,delta
),maxDec
);
159 rtc_lapic_start_ticking(void)
163 cpu_data_t
*cdp
= current_cpu_datap();
165 abstime
= mach_absolute_time();
166 rtclock_tick_interval
= NSEC_PER_HZ
;
168 first_tick
= abstime
+ rtclock_tick_interval
;
169 cdp
->rtclock_intr_deadline
= first_tick
;
172 * Force a complete re-evaluation of timer deadlines.
174 cdp
->rtcPop
= EndOfAllTime
;
175 etimer_resync_deadlines();
179 * Configure the real-time clock device. Return success (1)
192 * Nanotime/mach_absolutime_time
193 * -----------------------------
194 * The timestamp counter (TSC) - which counts cpu clock cycles and can be read
195 * efficiently by the kernel and in userspace - is the reference for all timing.
196 * The cpu clock rate is platform-dependent and may stop or be reset when the
197 * processor is napped/slept. As a result, nanotime is the software abstraction
198 * used to maintain a monotonic clock, adjusted from an outside reference as needed.
200 * The kernel maintains nanotime information recording:
201 * - the ratio of tsc to nanoseconds
202 * with this ratio expressed as a 32-bit scale and shift
203 * (power of 2 divider);
204 * - { tsc_base, ns_base } pair of corresponding timestamps.
206 * The tuple {tsc_base, ns_base, scale, shift} is exported in the commpage
207 * for the userspace nanotime routine to read.
209 * All of the routines which update the nanotime data are non-reentrant. This must
210 * be guaranteed by the caller.
213 rtc_nanotime_set_commpage(rtc_nanotime_t
*rntp
)
215 commpage_set_nanotime(rntp
->tsc_base
, rntp
->ns_base
, rntp
->scale
, rntp
->shift
);
221 * Intialize the nanotime info from the base time. Since
222 * the base value might be from a lower resolution clock,
223 * we compare it to the TSC derived value, and use the
224 * greater of the two values.
227 _rtc_nanotime_init(rtc_nanotime_t
*rntp
, uint64_t base
)
229 uint64_t nsecs
, tsc
= rdtsc64();
231 nsecs
= _tsc_to_nanoseconds(tsc
);
232 rtc_nanotime_store(tsc
, MAX(nsecs
, base
), rntp
->scale
, rntp
->shift
, rntp
);
236 rtc_nanotime_init(uint64_t base
)
238 rtc_nanotime_t
*rntp
= &rtc_nanotime_info
;
240 _rtc_nanotime_init(rntp
, base
);
241 rtc_nanotime_set_commpage(rntp
);
247 * Call back from the commpage initialization to
248 * cause the commpage data to be filled in once the
249 * commpages have been created.
252 rtc_nanotime_init_commpage(void)
254 spl_t s
= splclock();
256 rtc_nanotime_set_commpage(&rtc_nanotime_info
);
262 * rtc_nanotime_update:
264 * Update the nanotime info from the base time. Since
265 * the base value might be from a lower resolution clock,
266 * we compare it to the TSC derived value, and use the
267 * greater of the two values.
269 * N.B. In comparison to the above init routine, this assumes
270 * that the TSC has remained monotonic compared to the tsc_base
271 * value, which is not the case after S3 sleep.
274 _rtc_nanotime_update(rtc_nanotime_t
*rntp
, uint64_t base
)
276 uint64_t nsecs
, tsc
= rdtsc64();
278 nsecs
= rntp
->ns_base
+ _tsc_to_nanoseconds(tsc
- rntp
->tsc_base
);
279 rtc_nanotime_store(tsc
, MAX(nsecs
, base
), rntp
->scale
, rntp
->shift
, rntp
);
286 rtc_nanotime_t
*rntp
= &rtc_nanotime_info
;
288 assert(!ml_get_interrupts_enabled());
290 _rtc_nanotime_update(rntp
, base
);
291 rtc_nanotime_set_commpage(rntp
);
297 * Returns the current nanotime value, accessable from any
301 rtc_nanotime_read(void)
303 rtc_nanotime_t rnt
, *rntp
= &rtc_nanotime_info
;
307 rtc_nanotime_load(rntp
, &rnt
);
308 result
= rnt
.ns_base
+ _tsc_to_nanoseconds(rdtsc64() - rnt
.tsc_base
);
309 } while (rntp
->tsc_base
!= rnt
.tsc_base
);
317 * Invoked from power manangement when we have awoken from a nap (C3/C4)
318 * during which the TSC lost counts. The nanotime data is updated according
319 * to the provided nanosecond base value.
321 * The caller must guarantee non-reentrancy.
327 rtc_nanotime_update(base
);
331 rtc_clock_stepping(__unused
uint32_t new_frequency
,
332 __unused
uint32_t old_frequency
)
334 panic("rtc_clock_stepping unsupported");
338 rtc_clock_stepped(__unused
uint32_t new_frequency
,
339 __unused
uint32_t old_frequency
)
341 panic("rtc_clock_stepping unsupported");
347 * Invoked from power manageent when we have awoken from a sleep (S3)
348 * and the TSC has been reset. The nanotime data is updated based on
351 * The caller must guarantee non-reentrancy.
354 rtc_sleep_wakeup(void)
358 istate
= ml_set_interrupts_enabled(FALSE
);
362 * The timestamp counter will have been reset
363 * but nanotime (uptime) marches onward.
365 rtc_nanotime_init(tmrCvt(rdHPET(), hpetCvtt2n
));
367 /* Restart tick interrupts from the LAPIC timer */
368 rtc_lapic_start_ticking();
370 ml_set_interrupts_enabled(istate
);
374 * Initialize the real-time clock device.
375 * In addition, various variables used to support the clock are initialized.
382 assert(!ml_get_interrupts_enabled());
384 if (cpu_number() == master_cpu
) {
387 rtc_set_timescale(tscFreq
);
390 * Adjust and set the exported cpu speed.
392 cycles
= rtc_export_speed(tscFreq
);
395 * Set min/max to actual.
396 * ACPI may update these later if speed-stepping is detected.
398 gPEClockFrequencyInfo
.cpu_frequency_min_hz
= cycles
;
399 gPEClockFrequencyInfo
.cpu_frequency_max_hz
= cycles
;
402 * Compute the longest interval we can represent.
404 maxDec
= tmrCvt(0x7fffffffULL
, busFCvtt2n
);
405 kprintf("maxDec: %lld\n", maxDec
);
407 /* Minimum interval is 1usec */
408 rtc_decrementer_min
= deadline_to_decrementer(NSEC_PER_USEC
, 0ULL);
409 /* Point LAPIC interrupts to hardclock() */
410 lapic_set_timer_func((i386_intr_func_t
) rtclock_intr
);
412 clock_timebase_init();
413 ml_init_lock_timeout();
416 rtc_lapic_start_ticking();
422 // Code to calculate how many processor cycles are in a second...
425 rtc_set_timescale(uint64_t cycles
)
427 rtc_nanotime_info
.scale
= ((uint64_t)NSEC_PER_SEC
<< 32) / cycles
;
428 rtc_nanotime_info
.shift
= 32;
430 rtc_nanotime_init(0);
434 rtc_export_speed(uint64_t cyc_per_sec
)
439 cycles
= ((cyc_per_sec
+ (UI_CPUFREQ_ROUNDING_FACTOR
/2))
440 / UI_CPUFREQ_ROUNDING_FACTOR
)
441 * UI_CPUFREQ_ROUNDING_FACTOR
;
444 * Set current measured speed.
446 if (cycles
>= 0x100000000ULL
) {
447 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= 0xFFFFFFFFUL
;
449 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= (unsigned long)cycles
;
451 gPEClockFrequencyInfo
.cpu_frequency_hz
= cycles
;
453 kprintf("[RTCLOCK] frequency %llu (%llu)\n", cycles
, cyc_per_sec
);
458 clock_get_system_microtime(
462 uint64_t now
= rtc_nanotime_read();
467 : "=a" (*secs
), "=d" (remain
)
468 : "A" (now
), "r" (NSEC_PER_SEC
));
472 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
476 clock_get_system_nanotime(
480 uint64_t now
= rtc_nanotime_read();
484 : "=a" (*secs
), "=d" (*nanosecs
)
485 : "A" (now
), "r" (NSEC_PER_SEC
));
489 clock_gettimeofday_set_commpage(
496 uint64_t now
= abstime
;
503 : "=a" (*secs
), "=d" (remain
)
504 : "A" (now
), "r" (NSEC_PER_SEC
));
508 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
512 commpage_set_timestamp(abstime
- remain
, *secs
, NSEC_PER_SEC
);
517 mach_timebase_info_t info
)
519 info
->numer
= info
->denom
= 1;
523 clock_set_timer_func(
524 clock_timer_func_t func
)
526 if (rtclock_timer_expire
== NULL
)
527 rtclock_timer_expire
= func
;
531 * Real-time clock device interrupt.
535 x86_saved_state_t
*tregs
)
538 boolean_t user_mode
= FALSE
;
541 cpu_data_t
*pp
= current_cpu_datap();
543 assert(get_preemption_level() > 0);
544 assert(!ml_get_interrupts_enabled());
546 abstime
= rtc_nanotime_read();
547 latency
= (uint32_t) abstime
- pp
->rtcPop
;
549 if (is_saved_state64(tregs
) == TRUE
) {
550 x86_saved_state64_t
*regs
;
552 regs
= saved_state64(tregs
);
557 x86_saved_state32_t
*regs
;
559 regs
= saved_state32(tregs
);
566 /* Log the interrupt service latency (-ve value expected by tool) */
567 KERNEL_DEBUG_CONSTANT(
568 MACHDBG_CODE(DBG_MACH_EXCP_DECI
, 0) | DBG_FUNC_NONE
,
569 -latency
, (uint32_t)rip
, user_mode
, 0, 0);
571 /* call the generic etimer */
572 etimer_intr(user_mode
, rip
);
576 * Request timer pop from the hardware
587 now
= rtc_nanotime_read(); /* The time in nanoseconds */
588 decr
= deadline_to_decrementer(time
, now
);
590 count
= tmrCvt(decr
, busFCvtn2t
);
591 lapic_set_timer(TRUE
, one_shot
, divide_by_1
, (uint32_t) count
);
593 return decr
; /* Pass back what we set */
603 cpu_data_t
*cdp
= current_cpu_datap();
605 now
= rtc_nanotime_read();
607 decr
= deadline_to_decrementer(cdp
->rtcPop
, now
);
609 count
= tmrCvt(decr
, busFCvtn2t
);
610 lapic_set_timer(TRUE
, one_shot
, divide_by_1
, (uint32_t)count
);
615 mach_absolute_time(void)
617 return rtc_nanotime_read();
621 clock_interval_to_absolutetime_interval(
623 uint32_t scale_factor
,
626 *result
= (uint64_t)interval
* scale_factor
;
630 absolutetime_to_microtime(
639 : "=a" (*secs
), "=d" (remain
)
640 : "A" (abstime
), "r" (NSEC_PER_SEC
));
644 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
648 absolutetime_to_nanotime(
655 : "=a" (*secs
), "=d" (*nanosecs
)
656 : "A" (abstime
), "r" (NSEC_PER_SEC
));
660 nanotime_to_absolutetime(
665 *result
= ((uint64_t)secs
* NSEC_PER_SEC
) + nanosecs
;
669 absolutetime_to_nanoseconds(
677 nanoseconds_to_absolutetime(
678 uint64_t nanoseconds
,
681 *result
= nanoseconds
;
692 now
= mach_absolute_time();
693 } while (now
< deadline
);