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@
34 #include <mach/mach_types.h>
36 #include <kern/lock.h>
38 #include <kern/sched_prim.h>
39 #include <kern/thread.h>
40 #include <kern/clock.h>
41 #include <kern/host_notify.h>
43 #include <IOKit/IOPlatformExpert.h>
45 #include <machine/commpage.h>
47 #include <mach/mach_traps.h>
48 #include <mach/mach_time.h>
50 uint32_t hz_tick_interval
= 1;
53 decl_simple_lock_data(,clock_lock
)
55 #define clock_lock() \
56 simple_lock(&clock_lock)
58 #define clock_unlock() \
59 simple_unlock(&clock_lock)
61 #define clock_lock_init() \
62 simple_lock_init(&clock_lock, 0)
66 * Time of day (calendar) variables.
70 * TOD <- (seconds + epoch, fraction) <- CONV(current absolute time + offset)
72 * where CONV converts absolute time units into seconds and a fraction.
74 static struct clock_calend
{
78 int32_t adjdelta
; /* Nanosecond time delta for this adjustment period */
79 uint64_t adjstart
; /* Absolute time value for start of this adjustment period */
80 uint32_t adjoffset
; /* Absolute time offset for this adjustment period as absolute value */
86 * Unlocked calendar flipflop; this is used to track a clock_calend such
87 * that we can safely access a snapshot of a valid clock_calend structure
88 * without needing to take any locks to do it.
90 * The trick is to use a generation count and set the low bit when it is
91 * being updated/read; by doing this, we guarantee, through use of the
92 * hw_atomic functions, that the generation is incremented when the bit
93 * is cleared atomically (by using a 1 bit add).
95 static struct unlocked_clock_calend
{
96 struct clock_calend calend
; /* copy of calendar */
97 uint32_t gen
; /* generation count */
100 static void clock_track_calend_nowait(void);
105 * Calendar adjustment variables and values.
107 #define calend_adjperiod (NSEC_PER_SEC / 100) /* adjustment period, ns */
108 #define calend_adjskew (40 * NSEC_PER_USEC) /* "standard" skew, ns / period */
109 #define calend_adjbig (NSEC_PER_SEC) /* use 10x skew above adjbig ns */
111 static int64_t calend_adjtotal
; /* Nanosecond remaining total adjustment */
112 static uint64_t calend_adjdeadline
; /* Absolute time value for next adjustment period */
113 static uint32_t calend_adjinterval
; /* Absolute time interval of adjustment period */
115 static timer_call_data_t calend_adjcall
;
116 static uint32_t calend_adjactive
;
118 static uint32_t calend_set_adjustment(
122 static void calend_adjust_call(void);
123 static uint32_t calend_adjust(void);
125 static thread_call_data_t calend_wakecall
;
127 extern void IOKitResetTime(void);
129 void _clock_delay_until_deadline(uint64_t interval
,
132 static uint64_t clock_boottime
; /* Seconds boottime epoch */
134 #define TIME_ADD(rsecs, secs, rfrac, frac, unit) \
136 if (((rfrac) += (frac)) >= (unit)) { \
143 #define TIME_SUB(rsecs, secs, rfrac, frac, unit) \
145 if ((int)((rfrac) -= (frac)) < 0) { \
155 * Called once at boot to configure the clock subsystem.
162 timer_call_setup(&calend_adjcall
, (timer_call_func_t
)calend_adjust_call
, NULL
);
163 thread_call_setup(&calend_wakecall
, (thread_call_func_t
)IOKitResetTime
, NULL
);
171 * Called on a processor each time started.
180 * clock_timebase_init:
182 * Called by machine dependent code
183 * to initialize areas dependent on the
184 * timebase value. May be called multiple
185 * times during start up.
188 clock_timebase_init(void)
192 nanoseconds_to_absolutetime(calend_adjperiod
, &abstime
);
193 calend_adjinterval
= (uint32_t)abstime
;
195 nanoseconds_to_absolutetime(NSEC_PER_SEC
/ 100, &abstime
);
196 hz_tick_interval
= (uint32_t)abstime
;
198 sched_timebase_init();
202 * mach_timebase_info_trap:
204 * User trap returns timebase constant.
207 mach_timebase_info_trap(
208 struct mach_timebase_info_trap_args
*args
)
210 mach_vm_address_t out_info_addr
= args
->info
;
211 mach_timebase_info_data_t info
;
213 clock_timebase_info(&info
);
215 copyout((void *)&info
, out_info_addr
, sizeof (info
));
217 return (KERN_SUCCESS
);
225 * clock_get_calendar_microtime:
227 * Returns the current calendar value,
228 * microseconds as the fraction.
231 clock_get_calendar_microtime(
233 clock_usec_t
*microsecs
)
235 clock_get_calendar_absolute_and_microtime(secs
, microsecs
, NULL
);
239 * clock_get_calendar_absolute_and_microtime:
241 * Returns the current calendar value,
242 * microseconds as the fraction. Also
243 * returns mach_absolute_time if abstime
247 clock_get_calendar_absolute_and_microtime(
249 clock_usec_t
*microsecs
,
258 now
= mach_absolute_time();
262 if (clock_calend
.adjdelta
< 0) {
266 * Since offset is decremented during a negative adjustment,
267 * ensure that time increases monotonically without going
268 * temporarily backwards.
269 * If the delta has not yet passed, now is set to the start
270 * of the current adjustment period; otherwise, we're between
271 * the expiry of the delta and the next call to calend_adjust(),
272 * and we offset accordingly.
274 if (now
> clock_calend
.adjstart
) {
275 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
277 if (t32
> clock_calend
.adjoffset
)
278 now
-= clock_calend
.adjoffset
;
280 now
= clock_calend
.adjstart
;
284 now
+= clock_calend
.offset
;
286 absolutetime_to_microtime(now
, secs
, microsecs
);
288 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
295 * clock_get_calendar_nanotime:
297 * Returns the current calendar value,
298 * nanoseconds as the fraction.
300 * Since we do not have an interface to
301 * set the calendar with resolution greater
302 * than a microsecond, we honor that here.
305 clock_get_calendar_nanotime(
307 clock_nsec_t
*nanosecs
)
315 now
= mach_absolute_time();
317 if (clock_calend
.adjdelta
< 0) {
320 if (now
> clock_calend
.adjstart
) {
321 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
323 if (t32
> clock_calend
.adjoffset
)
324 now
-= clock_calend
.adjoffset
;
326 now
= clock_calend
.adjstart
;
330 now
+= clock_calend
.offset
;
332 absolutetime_to_microtime(now
, secs
, nanosecs
);
334 *nanosecs
*= NSEC_PER_USEC
;
336 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
343 * clock_gettimeofday:
345 * Kernel interface for commpage implementation of
346 * gettimeofday() syscall.
348 * Returns the current calendar value, and updates the
349 * commpage info as appropriate. Because most calls to
350 * gettimeofday() are handled in user mode by the commpage,
351 * this routine should be used infrequently.
356 clock_usec_t
*microsecs
)
364 now
= mach_absolute_time();
366 if (clock_calend
.adjdelta
>= 0) {
367 clock_gettimeofday_set_commpage(now
, clock_calend
.epoch
, clock_calend
.offset
, secs
, microsecs
);
372 if (now
> clock_calend
.adjstart
) {
373 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
375 if (t32
> clock_calend
.adjoffset
)
376 now
-= clock_calend
.adjoffset
;
378 now
= clock_calend
.adjstart
;
381 now
+= clock_calend
.offset
;
383 absolutetime_to_microtime(now
, secs
, microsecs
);
385 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
393 * clock_set_calendar_microtime:
395 * Sets the current calendar value by
396 * recalculating the epoch and offset
397 * from the system clock.
399 * Also adjusts the boottime to keep the
400 * value consistent, writes the new
401 * calendar value to the platform clock,
402 * and sends calendar change notifications.
405 clock_set_calendar_microtime(
407 clock_usec_t microsecs
)
410 clock_usec_t microsys
;
414 newsecs
= (microsecs
< 500*USEC_PER_SEC
)? secs
: secs
+ 1;
419 commpage_disable_timestamp();
422 * Calculate the new calendar epoch based on
423 * the new value and the system clock.
425 clock_get_system_microtime(&sys
, µsys
);
426 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
429 * Adjust the boottime based on the delta.
431 clock_boottime
+= secs
- clock_calend
.epoch
;
434 * Set the new calendar epoch.
436 clock_calend
.epoch
= secs
;
438 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
441 * Cancel any adjustment in progress.
443 calend_adjtotal
= clock_calend
.adjdelta
= 0;
448 * Set the new value for the platform clock.
450 PESetGMTTimeOfDay(newsecs
);
455 * Send host notifications.
457 host_notify_calendar_change();
460 clock_track_calend_nowait();
465 * clock_initialize_calendar:
467 * Set the calendar and related clocks
468 * from the platform clock at boot or
471 * Also sends host notifications.
474 clock_initialize_calendar(void)
476 clock_sec_t sys
, secs
= PEGetGMTTimeOfDay();
477 clock_usec_t microsys
, microsecs
= 0;
483 commpage_disable_timestamp();
485 if ((long)secs
>= (long)clock_boottime
) {
487 * Initialize the boot time based on the platform clock.
489 if (clock_boottime
== 0)
490 clock_boottime
= secs
;
493 * Calculate the new calendar epoch based on
494 * the platform clock and the system clock.
496 clock_get_system_microtime(&sys
, µsys
);
497 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
500 * Set the new calendar epoch.
502 clock_calend
.epoch
= secs
;
504 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
507 * Cancel any adjustment in progress.
509 calend_adjtotal
= clock_calend
.adjdelta
= 0;
516 * Send host notifications.
518 host_notify_calendar_change();
521 clock_track_calend_nowait();
526 * clock_get_boottime_nanotime:
528 * Return the boottime, used by sysctl.
531 clock_get_boottime_nanotime(
533 clock_nsec_t
*nanosecs
)
540 *secs
= (clock_sec_t
)clock_boottime
;
550 * Interface to adjtime() syscall.
552 * Calculates adjustment variables and
553 * initiates adjustment.
566 interval
= calend_set_adjustment(secs
, microsecs
);
568 calend_adjdeadline
= mach_absolute_time() + interval
;
569 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_SYS_CRITICAL
))
573 if (timer_call_cancel(&calend_adjcall
))
581 calend_set_adjustment(
586 int64_t total
, ototal
;
587 uint32_t interval
= 0;
590 * Compute the total adjustment time in nanoseconds.
592 total
= ((int64_t)*secs
* (int64_t)NSEC_PER_SEC
) + (*microsecs
* (int64_t)NSEC_PER_USEC
);
595 * Disable commpage gettimeofday().
597 commpage_disable_timestamp();
600 * Get current absolute time.
602 now
= mach_absolute_time();
605 * Save the old adjustment total for later return.
607 ototal
= calend_adjtotal
;
610 * Is a new correction specified?
614 * Set delta to the standard, small, adjustment skew.
616 int32_t delta
= calend_adjskew
;
620 * Positive adjustment. If greater than the preset 'big'
621 * threshold, slew at a faster rate, capping if necessary.
623 if (total
> (int64_t) calend_adjbig
)
626 delta
= (int32_t)total
;
629 * Convert the delta back from ns to absolute time and store in adjoffset.
631 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
632 clock_calend
.adjoffset
= (uint32_t)t64
;
636 * Negative adjustment; therefore, negate the delta. If
637 * greater than the preset 'big' threshold, slew at a faster
638 * rate, capping if necessary.
640 if (total
< (int64_t) -calend_adjbig
)
644 delta
= (int32_t)total
;
647 * Save the current absolute time. Subsequent time operations occuring
648 * during this negative correction can make use of this value to ensure
649 * that time increases monotonically.
651 clock_calend
.adjstart
= now
;
654 * Convert the delta back from ns to absolute time and store in adjoffset.
656 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
657 clock_calend
.adjoffset
= (uint32_t)t64
;
661 * Store the total adjustment time in ns.
663 calend_adjtotal
= total
;
666 * Store the delta for this adjustment period in ns.
668 clock_calend
.adjdelta
= delta
;
671 * Set the interval in absolute time for later return.
673 interval
= calend_adjinterval
;
677 * No change; clear any prior adjustment.
679 calend_adjtotal
= clock_calend
.adjdelta
= 0;
683 * If an prior correction was in progress, return the
684 * remaining uncorrected time from it.
687 *secs
= (long)(ototal
/ (long)NSEC_PER_SEC
);
688 *microsecs
= (int)((ototal
% (int)NSEC_PER_SEC
) / (int)NSEC_PER_USEC
);
691 *secs
= *microsecs
= 0;
694 clock_track_calend_nowait();
701 calend_adjust_call(void)
709 if (--calend_adjactive
== 0) {
710 interval
= calend_adjust();
712 clock_deadline_for_periodic_event(interval
, mach_absolute_time(), &calend_adjdeadline
);
714 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_SYS_CRITICAL
))
728 uint32_t interval
= 0;
730 commpage_disable_timestamp();
732 now
= mach_absolute_time();
734 delta
= clock_calend
.adjdelta
;
737 clock_calend
.offset
+= clock_calend
.adjoffset
;
739 calend_adjtotal
-= delta
;
740 if (delta
> calend_adjtotal
) {
741 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
743 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
744 clock_calend
.adjoffset
= (uint32_t)t64
;
749 clock_calend
.offset
-= clock_calend
.adjoffset
;
751 calend_adjtotal
-= delta
;
752 if (delta
< calend_adjtotal
) {
753 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
755 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
756 clock_calend
.adjoffset
= (uint32_t)t64
;
759 if (clock_calend
.adjdelta
!= 0)
760 clock_calend
.adjstart
= now
;
763 if (clock_calend
.adjdelta
!= 0)
764 interval
= calend_adjinterval
;
767 clock_track_calend_nowait();
774 * clock_wakeup_calendar:
776 * Interface to power management, used
777 * to initiate the reset of the calendar
778 * on wake from sleep event.
781 clock_wakeup_calendar(void)
783 thread_call_enter(&calend_wakecall
);
787 * Wait / delay routines.
790 mach_wait_until_continue(
791 __unused
void *parameter
,
792 wait_result_t wresult
)
794 thread_syscall_return((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
799 * mach_wait_until_trap: Suspend execution of calling thread until the specified time has passed
801 * Parameters: args->deadline Amount of time to wait
808 mach_wait_until_trap(
809 struct mach_wait_until_trap_args
*args
)
811 uint64_t deadline
= args
->deadline
;
812 wait_result_t wresult
;
814 wresult
= assert_wait_deadline_with_leeway((event_t
)mach_wait_until_trap
, THREAD_ABORTSAFE
,
815 TIMEOUT_URGENCY_USER_NORMAL
, deadline
, 0);
816 if (wresult
== THREAD_WAITING
)
817 wresult
= thread_block(mach_wait_until_continue
);
819 return ((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
826 uint64_t now
= mach_absolute_time();
831 _clock_delay_until_deadline(deadline
- now
, deadline
);
835 * Preserve the original precise interval that the client
836 * requested for comparison to the spin threshold.
839 _clock_delay_until_deadline(
847 if ( ml_delay_should_spin(interval
) ||
848 get_preemption_level() != 0 ||
849 ml_get_interrupts_enabled() == FALSE
) {
850 machine_delay_until(interval
, deadline
);
852 assert_wait_deadline((event_t
)clock_delay_until
, THREAD_UNINT
, deadline
);
854 thread_block(THREAD_CONTINUE_NULL
);
862 uint32_t scale_factor
)
866 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
868 _clock_delay_until_deadline(abstime
, mach_absolute_time() + abstime
);
875 delay_for_interval((usec
< 0)? -usec
: usec
, NSEC_PER_USEC
);
879 * Miscellaneous routines.
882 clock_interval_to_deadline(
884 uint32_t scale_factor
,
889 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
891 *result
= mach_absolute_time() + abstime
;
895 clock_absolutetime_interval_to_deadline(
899 *result
= mach_absolute_time() + abstime
;
906 *result
= mach_absolute_time();
910 clock_deadline_for_periodic_event(
915 assert(interval
!= 0);
917 *deadline
+= interval
;
919 if (*deadline
<= abstime
) {
920 *deadline
= abstime
+ interval
;
921 abstime
= mach_absolute_time();
923 if (*deadline
<= abstime
)
924 *deadline
= abstime
+ interval
;
931 * clock_get_calendar_nanotime_nowait
933 * Description: Non-blocking version of clock_get_calendar_nanotime()
935 * Notes: This function operates by separately tracking calendar time
936 * updates using a two element structure to copy the calendar
937 * state, which may be asynchronously modified. It utilizes
938 * barrier instructions in the tracking process and in the local
939 * stable snapshot process in order to ensure that a consistent
940 * snapshot is used to perform the calculation.
943 clock_get_calendar_nanotime_nowait(
945 clock_nsec_t
*nanosecs
)
949 struct unlocked_clock_calend stable
;
952 stable
= flipflop
[i
]; /* take snapshot */
955 * Use a barrier instructions to ensure atomicity. We AND
956 * off the "in progress" bit to get the current generation
959 (void)hw_atomic_and(&stable
.gen
, ~(uint32_t)1);
962 * If an update _is_ in progress, the generation count will be
963 * off by one, if it _was_ in progress, it will be off by two,
964 * and if we caught it at a good time, it will be equal (and
965 * our snapshot is threfore stable).
967 if (flipflop
[i
].gen
== stable
.gen
)
970 /* Switch to the oher element of the flipflop, and try again. */
974 now
= mach_absolute_time();
976 if (stable
.calend
.adjdelta
< 0) {
979 if (now
> stable
.calend
.adjstart
) {
980 t32
= (uint32_t)(now
- stable
.calend
.adjstart
);
982 if (t32
> stable
.calend
.adjoffset
)
983 now
-= stable
.calend
.adjoffset
;
985 now
= stable
.calend
.adjstart
;
989 now
+= stable
.calend
.offset
;
991 absolutetime_to_microtime(now
, secs
, nanosecs
);
992 *nanosecs
*= NSEC_PER_USEC
;
994 *secs
+= (clock_sec_t
)stable
.calend
.epoch
;
998 clock_track_calend_nowait(void)
1002 for (i
= 0; i
< 2; i
++) {
1003 struct clock_calend tmp
= clock_calend
;
1006 * Set the low bit if the generation count; since we use a
1007 * barrier instruction to do this, we are guaranteed that this
1008 * will flag an update in progress to an async caller trying
1009 * to examine the contents.
1011 (void)hw_atomic_or(&flipflop
[i
].gen
, 1);
1013 flipflop
[i
].calend
= tmp
;
1016 * Increment the generation count to clear the low bit to
1017 * signal completion. If a caller compares the generation
1018 * count after taking a copy while in progress, the count
1019 * will be off by two.
1021 (void)hw_atomic_add(&flipflop
[i
].gen
, 1);
1025 #endif /* CONFIG_DTRACE */