2 * Copyright (c) 2000-2005 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
27 * File: i386/rtclock.c
28 * Purpose: Routines for handling the machine dependent
29 * real-time clock. Historically, this clock is
30 * generated by the Intel 8254 Programmable Interval
31 * Timer, but local apic timers are now used for
32 * this purpose with the master time reference being
33 * the cpu clock counted by the timestamp MSR.
36 #include <platforms.h>
39 #include <mach/mach_types.h>
41 #include <kern/cpu_data.h>
42 #include <kern/cpu_number.h>
43 #include <kern/clock.h>
44 #include <kern/host_notify.h>
45 #include <kern/macro_help.h>
46 #include <kern/misc_protos.h>
48 #include <kern/assert.h>
49 #include <mach/vm_prot.h>
51 #include <vm/vm_kern.h> /* for kernel_map */
54 #include <architecture/i386/pio.h>
55 #include <i386/misc_protos.h>
56 #include <i386/proc_reg.h>
57 #include <i386/machine_cpu.h>
59 #include <i386/cpuid.h>
60 #include <i386/cpu_data.h>
61 #include <i386/cpu_threads.h>
62 #include <i386/perfmon.h>
63 #include <i386/machine_routines.h>
64 #include <pexpert/pexpert.h>
65 #include <machine/limits.h>
66 #include <machine/commpage.h>
67 #include <sys/kdebug.h>
69 #include <i386/hpet.h>
70 #include <i386/rtclock.h>
72 #define MAX(a,b) (((a)>(b))?(a):(b))
73 #define MIN(a,b) (((a)>(b))?(b):(a))
75 #define NSEC_PER_HZ (NSEC_PER_SEC / 100) /* nsec per tick */
77 #define UI_CPUFREQ_ROUNDING_FACTOR 10000000
79 int rtclock_config(void);
81 int rtclock_init(void);
83 uint64_t rtc_decrementer_min
;
85 void rtclock_intr(x86_saved_state_t
*regs
);
86 static uint64_t maxDec
; /* longest interval our hardware timer can handle (nsec) */
88 /* XXX this should really be in a header somewhere */
89 extern clock_timer_func_t rtclock_timer_expire
;
91 static void rtc_set_timescale(uint64_t cycles
);
92 static uint64_t rtc_export_speed(uint64_t cycles
);
94 extern void rtc_nanotime_store(
101 extern void rtc_nanotime_load(
103 rtc_nanotime_t
*dst
);
105 rtc_nanotime_t rtc_nanotime_info
;
108 * tsc_to_nanoseconds:
110 * Basic routine to convert a raw 64 bit TSC value to a
111 * 64 bit nanosecond value. The conversion is implemented
112 * based on the scale factor and an implicit 32 bit shift.
114 static inline uint64_t
115 _tsc_to_nanoseconds(uint64_t value
)
117 asm volatile("movl %%edx,%%esi ;"
124 : "+A" (value
) : "c" (rtc_nanotime_info
.scale
) : "esi", "edi");
130 tsc_to_nanoseconds(uint64_t value
)
132 return _tsc_to_nanoseconds(value
);
136 deadline_to_decrementer(
143 return rtc_decrementer_min
;
145 delta
= deadline
- now
;
146 return MIN(MAX(rtc_decrementer_min
,delta
),maxDec
);
151 rtc_lapic_start_ticking(void)
155 cpu_data_t
*cdp
= current_cpu_datap();
157 abstime
= mach_absolute_time();
158 rtclock_tick_interval
= NSEC_PER_HZ
;
160 first_tick
= abstime
+ rtclock_tick_interval
;
161 cdp
->rtclock_intr_deadline
= first_tick
;
164 * Force a complete re-evaluation of timer deadlines.
166 cdp
->rtcPop
= EndOfAllTime
;
167 etimer_resync_deadlines();
171 * Configure the real-time clock device. Return success (1)
184 * Nanotime/mach_absolutime_time
185 * -----------------------------
186 * The timestamp counter (TSC) - which counts cpu clock cycles and can be read
187 * efficiently by the kernel and in userspace - is the reference for all timing.
188 * The cpu clock rate is platform-dependent and may stop or be reset when the
189 * processor is napped/slept. As a result, nanotime is the software abstraction
190 * used to maintain a monotonic clock, adjusted from an outside reference as needed.
192 * The kernel maintains nanotime information recording:
193 * - the ratio of tsc to nanoseconds
194 * with this ratio expressed as a 32-bit scale and shift
195 * (power of 2 divider);
196 * - { tsc_base, ns_base } pair of corresponding timestamps.
198 * The tuple {tsc_base, ns_base, scale, shift} is exported in the commpage
199 * for the userspace nanotime routine to read.
201 * All of the routines which update the nanotime data are non-reentrant. This must
202 * be guaranteed by the caller.
205 rtc_nanotime_set_commpage(rtc_nanotime_t
*rntp
)
207 commpage_set_nanotime(rntp
->tsc_base
, rntp
->ns_base
, rntp
->scale
, rntp
->shift
);
213 * Intialize the nanotime info from the base time.
216 _rtc_nanotime_init(rtc_nanotime_t
*rntp
, uint64_t base
)
218 uint64_t tsc
= rdtsc64();
220 rtc_nanotime_store(tsc
, base
, rntp
->scale
, rntp
->shift
, rntp
);
224 rtc_nanotime_init(uint64_t base
)
226 rtc_nanotime_t
*rntp
= &rtc_nanotime_info
;
228 _rtc_nanotime_init(rntp
, base
);
229 rtc_nanotime_set_commpage(rntp
);
233 * rtc_nanotime_init_commpage:
235 * Call back from the commpage initialization to
236 * cause the commpage data to be filled in once the
237 * commpages have been created.
240 rtc_nanotime_init_commpage(void)
242 spl_t s
= splclock();
244 rtc_nanotime_set_commpage(&rtc_nanotime_info
);
250 * rtc_nanotime_update:
252 * Update the nanotime info from the base time. Since
253 * the base value might be from a lower resolution clock,
254 * we compare it to the TSC derived value, and use the
255 * greater of the two values.
257 * N.B. In comparison to the above init routine, this assumes
258 * that the TSC has remained monotonic compared to the tsc_base
259 * value, which is not the case after S3 sleep.
262 _rtc_nanotime_update(rtc_nanotime_t
*rntp
, uint64_t base
)
264 uint64_t nsecs
, tsc
= rdtsc64();
266 nsecs
= rntp
->ns_base
+ _tsc_to_nanoseconds(tsc
- rntp
->tsc_base
);
267 rtc_nanotime_store(tsc
, MAX(nsecs
, base
), rntp
->scale
, rntp
->shift
, rntp
);
274 rtc_nanotime_t
*rntp
= &rtc_nanotime_info
;
276 assert(!ml_get_interrupts_enabled());
278 _rtc_nanotime_update(rntp
, base
);
279 rtc_nanotime_set_commpage(rntp
);
285 * Returns the current nanotime value, accessable from any
289 rtc_nanotime_read(void)
291 rtc_nanotime_t rnt
, *rntp
= &rtc_nanotime_info
;
295 rtc_nanotime_load(rntp
, &rnt
);
296 result
= rnt
.ns_base
+ _tsc_to_nanoseconds(rdtsc64() - rnt
.tsc_base
);
297 } while (rntp
->tsc_base
!= rnt
.tsc_base
);
305 * Invoked from power manangement when we have awoken from a nap (C3/C4)
306 * during which the TSC lost counts. The nanotime data is updated according
307 * to the provided nanosecond base value.
309 * The caller must guarantee non-reentrancy.
315 rtc_nanotime_update(base
);
319 rtc_clock_stepping(__unused
uint32_t new_frequency
,
320 __unused
uint32_t old_frequency
)
322 panic("rtc_clock_stepping unsupported");
326 rtc_clock_stepped(__unused
uint32_t new_frequency
,
327 __unused
uint32_t old_frequency
)
329 panic("rtc_clock_stepping unsupported");
335 * Invoked from power manageent when we have awoken from a sleep (S3)
336 * and the TSC has been reset. The nanotime data is updated based on
337 * the passed in value.
339 * The caller must guarantee non-reentrancy.
347 * The timestamp counter will have been reset
348 * but nanotime (uptime) marches onward.
350 rtc_nanotime_init(base
);
354 * Initialize the real-time clock device.
355 * In addition, various variables used to support the clock are initialized.
362 assert(!ml_get_interrupts_enabled());
364 if (cpu_number() == master_cpu
) {
367 rtc_set_timescale(tscFreq
);
370 * Adjust and set the exported cpu speed.
372 cycles
= rtc_export_speed(tscFreq
);
375 * Set min/max to actual.
376 * ACPI may update these later if speed-stepping is detected.
378 gPEClockFrequencyInfo
.cpu_frequency_min_hz
= cycles
;
379 gPEClockFrequencyInfo
.cpu_frequency_max_hz
= cycles
;
382 * Compute the longest interval we can represent.
384 maxDec
= tmrCvt(0x7fffffffULL
, busFCvtt2n
);
385 kprintf("maxDec: %lld\n", maxDec
);
387 /* Minimum interval is 1usec */
388 rtc_decrementer_min
= deadline_to_decrementer(NSEC_PER_USEC
, 0ULL);
389 /* Point LAPIC interrupts to hardclock() */
390 lapic_set_timer_func((i386_intr_func_t
) rtclock_intr
);
392 clock_timebase_init();
393 ml_init_lock_timeout();
396 rtc_lapic_start_ticking();
402 // Code to calculate how many processor cycles are in a second...
405 rtc_set_timescale(uint64_t cycles
)
407 rtc_nanotime_info
.scale
= ((uint64_t)NSEC_PER_SEC
<< 32) / cycles
;
408 rtc_nanotime_info
.shift
= 32;
410 rtc_nanotime_init(0);
414 rtc_export_speed(uint64_t cyc_per_sec
)
419 cycles
= ((cyc_per_sec
+ (UI_CPUFREQ_ROUNDING_FACTOR
/2))
420 / UI_CPUFREQ_ROUNDING_FACTOR
)
421 * UI_CPUFREQ_ROUNDING_FACTOR
;
424 * Set current measured speed.
426 if (cycles
>= 0x100000000ULL
) {
427 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= 0xFFFFFFFFUL
;
429 gPEClockFrequencyInfo
.cpu_clock_rate_hz
= (unsigned long)cycles
;
431 gPEClockFrequencyInfo
.cpu_frequency_hz
= cycles
;
433 kprintf("[RTCLOCK] frequency %llu (%llu)\n", cycles
, cyc_per_sec
);
438 clock_get_system_microtime(
442 uint64_t now
= rtc_nanotime_read();
447 : "=a" (*secs
), "=d" (remain
)
448 : "A" (now
), "r" (NSEC_PER_SEC
));
452 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
456 clock_get_system_nanotime(
460 uint64_t now
= rtc_nanotime_read();
464 : "=a" (*secs
), "=d" (*nanosecs
)
465 : "A" (now
), "r" (NSEC_PER_SEC
));
469 clock_gettimeofday_set_commpage(
476 uint64_t now
= abstime
;
483 : "=a" (*secs
), "=d" (remain
)
484 : "A" (now
), "r" (NSEC_PER_SEC
));
488 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
492 commpage_set_timestamp(abstime
- remain
, *secs
, NSEC_PER_SEC
);
497 mach_timebase_info_t info
)
499 info
->numer
= info
->denom
= 1;
503 clock_set_timer_func(
504 clock_timer_func_t func
)
506 if (rtclock_timer_expire
== NULL
)
507 rtclock_timer_expire
= func
;
511 * Real-time clock device interrupt.
515 x86_saved_state_t
*tregs
)
518 boolean_t user_mode
= FALSE
;
521 cpu_data_t
*pp
= current_cpu_datap();
523 assert(get_preemption_level() > 0);
524 assert(!ml_get_interrupts_enabled());
526 abstime
= rtc_nanotime_read();
527 latency
= (uint32_t) abstime
- pp
->rtcPop
;
529 if (is_saved_state64(tregs
) == TRUE
) {
530 x86_saved_state64_t
*regs
;
532 regs
= saved_state64(tregs
);
537 x86_saved_state32_t
*regs
;
539 regs
= saved_state32(tregs
);
546 /* Log the interrupt service latency (-ve value expected by tool) */
547 KERNEL_DEBUG_CONSTANT(
548 MACHDBG_CODE(DBG_MACH_EXCP_DECI
, 0) | DBG_FUNC_NONE
,
549 -latency
, (uint32_t)rip
, user_mode
, 0, 0);
551 /* call the generic etimer */
552 etimer_intr(user_mode
, rip
);
556 * Request timer pop from the hardware
567 now
= rtc_nanotime_read(); /* The time in nanoseconds */
568 decr
= deadline_to_decrementer(time
, now
);
570 count
= tmrCvt(decr
, busFCvtn2t
);
571 lapic_set_timer(TRUE
, one_shot
, divide_by_1
, (uint32_t) count
);
573 return decr
; /* Pass back what we set */
583 cpu_data_t
*cdp
= current_cpu_datap();
585 now
= rtc_nanotime_read();
587 decr
= deadline_to_decrementer(cdp
->rtcPop
, now
);
589 count
= tmrCvt(decr
, busFCvtn2t
);
590 lapic_set_timer(TRUE
, one_shot
, divide_by_1
, (uint32_t)count
);
595 mach_absolute_time(void)
597 return rtc_nanotime_read();
601 clock_interval_to_absolutetime_interval(
603 uint32_t scale_factor
,
606 *result
= (uint64_t)interval
* scale_factor
;
610 absolutetime_to_microtime(
619 : "=a" (*secs
), "=d" (remain
)
620 : "A" (abstime
), "r" (NSEC_PER_SEC
));
624 : "0" (remain
), "d" (0), "r" (NSEC_PER_USEC
));
628 absolutetime_to_nanotime(
635 : "=a" (*secs
), "=d" (*nanosecs
)
636 : "A" (abstime
), "r" (NSEC_PER_SEC
));
640 nanotime_to_absolutetime(
645 *result
= ((uint64_t)secs
* NSEC_PER_SEC
) + nanosecs
;
649 absolutetime_to_nanoseconds(
657 nanoseconds_to_absolutetime(
658 uint64_t nanoseconds
,
661 *result
= nanoseconds
;
672 now
= mach_absolute_time();
673 } while (now
< deadline
);