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>
37 #include <kern/sched_prim.h>
38 #include <kern/thread.h>
39 #include <kern/clock.h>
40 #include <kern/host_notify.h>
42 #include <IOKit/IOPlatformExpert.h>
44 #include <machine/commpage.h>
46 #include <mach/mach_traps.h>
47 #include <mach/mach_time.h>
49 uint32_t hz_tick_interval
= 1;
52 decl_simple_lock_data(,clock_lock
)
54 #define clock_lock() \
55 simple_lock(&clock_lock)
57 #define clock_unlock() \
58 simple_unlock(&clock_lock)
60 #define clock_lock_init() \
61 simple_lock_init(&clock_lock, 0)
65 * Time of day (calendar) variables.
69 * TOD <- (seconds + epoch, fraction) <- CONV(current absolute time + offset)
71 * where CONV converts absolute time units into seconds and a fraction.
73 static struct clock_calend
{
77 int32_t adjdelta
; /* Nanosecond time delta for this adjustment period */
78 uint64_t adjstart
; /* Absolute time value for start of this adjustment period */
79 uint32_t adjoffset
; /* Absolute time offset for this adjustment period as absolute value */
85 * Unlocked calendar flipflop; this is used to track a clock_calend such
86 * that we can safely access a snapshot of a valid clock_calend structure
87 * without needing to take any locks to do it.
89 * The trick is to use a generation count and set the low bit when it is
90 * being updated/read; by doing this, we guarantee, through use of the
91 * hw_atomic functions, that the generation is incremented when the bit
92 * is cleared atomically (by using a 1 bit add).
94 static struct unlocked_clock_calend
{
95 struct clock_calend calend
; /* copy of calendar */
96 uint32_t gen
; /* generation count */
99 static void clock_track_calend_nowait(void);
104 * Calendar adjustment variables and values.
106 #define calend_adjperiod (NSEC_PER_SEC / 100) /* adjustment period, ns */
107 #define calend_adjskew (40 * NSEC_PER_USEC) /* "standard" skew, ns / period */
108 #define calend_adjbig (NSEC_PER_SEC) /* use 10x skew above adjbig ns */
110 static int64_t calend_adjtotal
; /* Nanosecond remaining total adjustment */
111 static uint64_t calend_adjdeadline
; /* Absolute time value for next adjustment period */
112 static uint32_t calend_adjinterval
; /* Absolute time interval of adjustment period */
114 static timer_call_data_t calend_adjcall
;
115 static uint32_t calend_adjactive
;
117 static uint32_t calend_set_adjustment(
121 static void calend_adjust_call(void);
122 static uint32_t calend_adjust(void);
124 static thread_call_data_t calend_wakecall
;
126 extern void IOKitResetTime(void);
128 void _clock_delay_until_deadline(uint64_t interval
,
131 static uint64_t clock_boottime
; /* Seconds boottime epoch */
133 #define TIME_ADD(rsecs, secs, rfrac, frac, unit) \
135 if (((rfrac) += (frac)) >= (unit)) { \
142 #define TIME_SUB(rsecs, secs, rfrac, frac, unit) \
144 if ((int)((rfrac) -= (frac)) < 0) { \
154 * Called once at boot to configure the clock subsystem.
161 timer_call_setup(&calend_adjcall
, (timer_call_func_t
)calend_adjust_call
, NULL
);
162 thread_call_setup(&calend_wakecall
, (thread_call_func_t
)IOKitResetTime
, NULL
);
170 * Called on a processor each time started.
179 * clock_timebase_init:
181 * Called by machine dependent code
182 * to initialize areas dependent on the
183 * timebase value. May be called multiple
184 * times during start up.
187 clock_timebase_init(void)
191 nanoseconds_to_absolutetime(calend_adjperiod
, &abstime
);
192 calend_adjinterval
= (uint32_t)abstime
;
194 nanoseconds_to_absolutetime(NSEC_PER_SEC
/ 100, &abstime
);
195 hz_tick_interval
= (uint32_t)abstime
;
197 sched_timebase_init();
201 * mach_timebase_info_trap:
203 * User trap returns timebase constant.
206 mach_timebase_info_trap(
207 struct mach_timebase_info_trap_args
*args
)
209 mach_vm_address_t out_info_addr
= args
->info
;
210 mach_timebase_info_data_t info
;
212 clock_timebase_info(&info
);
214 copyout((void *)&info
, out_info_addr
, sizeof (info
));
216 return (KERN_SUCCESS
);
224 * clock_get_calendar_microtime:
226 * Returns the current calendar value,
227 * microseconds as the fraction.
230 clock_get_calendar_microtime(
232 clock_usec_t
*microsecs
)
234 clock_get_calendar_absolute_and_microtime(secs
, microsecs
, NULL
);
238 * clock_get_calendar_absolute_and_microtime:
240 * Returns the current calendar value,
241 * microseconds as the fraction. Also
242 * returns mach_absolute_time if abstime
246 clock_get_calendar_absolute_and_microtime(
248 clock_usec_t
*microsecs
,
257 now
= mach_absolute_time();
261 if (clock_calend
.adjdelta
< 0) {
265 * Since offset is decremented during a negative adjustment,
266 * ensure that time increases monotonically without going
267 * temporarily backwards.
268 * If the delta has not yet passed, now is set to the start
269 * of the current adjustment period; otherwise, we're between
270 * the expiry of the delta and the next call to calend_adjust(),
271 * and we offset accordingly.
273 if (now
> clock_calend
.adjstart
) {
274 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
276 if (t32
> clock_calend
.adjoffset
)
277 now
-= clock_calend
.adjoffset
;
279 now
= clock_calend
.adjstart
;
283 now
+= clock_calend
.offset
;
285 absolutetime_to_microtime(now
, secs
, microsecs
);
287 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
294 * clock_get_calendar_nanotime:
296 * Returns the current calendar value,
297 * nanoseconds as the fraction.
299 * Since we do not have an interface to
300 * set the calendar with resolution greater
301 * than a microsecond, we honor that here.
304 clock_get_calendar_nanotime(
306 clock_nsec_t
*nanosecs
)
314 now
= mach_absolute_time();
316 if (clock_calend
.adjdelta
< 0) {
319 if (now
> clock_calend
.adjstart
) {
320 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
322 if (t32
> clock_calend
.adjoffset
)
323 now
-= clock_calend
.adjoffset
;
325 now
= clock_calend
.adjstart
;
329 now
+= clock_calend
.offset
;
331 absolutetime_to_microtime(now
, secs
, nanosecs
);
333 *nanosecs
*= NSEC_PER_USEC
;
335 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
342 * clock_gettimeofday:
344 * Kernel interface for commpage implementation of
345 * gettimeofday() syscall.
347 * Returns the current calendar value, and updates the
348 * commpage info as appropriate. Because most calls to
349 * gettimeofday() are handled in user mode by the commpage,
350 * this routine should be used infrequently.
355 clock_usec_t
*microsecs
)
363 now
= mach_absolute_time();
365 if (clock_calend
.adjdelta
>= 0) {
366 clock_gettimeofday_set_commpage(now
, clock_calend
.epoch
, clock_calend
.offset
, secs
, microsecs
);
371 if (now
> clock_calend
.adjstart
) {
372 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
374 if (t32
> clock_calend
.adjoffset
)
375 now
-= clock_calend
.adjoffset
;
377 now
= clock_calend
.adjstart
;
380 now
+= clock_calend
.offset
;
382 absolutetime_to_microtime(now
, secs
, microsecs
);
384 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
392 * clock_set_calendar_microtime:
394 * Sets the current calendar value by
395 * recalculating the epoch and offset
396 * from the system clock.
398 * Also adjusts the boottime to keep the
399 * value consistent, writes the new
400 * calendar value to the platform clock,
401 * and sends calendar change notifications.
404 clock_set_calendar_microtime(
406 clock_usec_t microsecs
)
409 clock_usec_t microsys
;
411 clock_usec_t newmicrosecs
;
415 newmicrosecs
= microsecs
;
420 commpage_disable_timestamp();
423 * Calculate the new calendar epoch based on
424 * the new value and the system clock.
426 clock_get_system_microtime(&sys
, µsys
);
427 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
430 * Adjust the boottime based on the delta.
432 clock_boottime
+= secs
- clock_calend
.epoch
;
435 * Set the new calendar epoch.
437 clock_calend
.epoch
= secs
;
439 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
442 * Cancel any adjustment in progress.
444 calend_adjtotal
= clock_calend
.adjdelta
= 0;
449 * Set the new value for the platform clock.
451 PESetUTCTimeOfDay(newsecs
, newmicrosecs
);
456 * Send host notifications.
458 host_notify_calendar_change();
461 clock_track_calend_nowait();
466 * clock_initialize_calendar:
468 * Set the calendar and related clocks
469 * from the platform clock at boot or
472 * Also sends host notifications.
475 clock_initialize_calendar(void)
477 clock_sec_t sys
, secs
;
478 clock_usec_t microsys
, microsecs
;
481 PEGetUTCTimeOfDay(&secs
, µsecs
);
486 commpage_disable_timestamp();
488 if ((long)secs
>= (long)clock_boottime
) {
490 * Initialize the boot time based on the platform clock.
492 if (clock_boottime
== 0)
493 clock_boottime
= secs
;
496 * Calculate the new calendar epoch based on
497 * the platform clock and the system clock.
499 clock_get_system_microtime(&sys
, µsys
);
500 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
503 * Set the new calendar epoch.
505 clock_calend
.epoch
= secs
;
507 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
510 * Cancel any adjustment in progress.
512 calend_adjtotal
= clock_calend
.adjdelta
= 0;
519 * Send host notifications.
521 host_notify_calendar_change();
524 clock_track_calend_nowait();
529 * clock_get_boottime_nanotime:
531 * Return the boottime, used by sysctl.
534 clock_get_boottime_nanotime(
536 clock_nsec_t
*nanosecs
)
543 *secs
= (clock_sec_t
)clock_boottime
;
553 * Interface to adjtime() syscall.
555 * Calculates adjustment variables and
556 * initiates adjustment.
569 interval
= calend_set_adjustment(secs
, microsecs
);
571 calend_adjdeadline
= mach_absolute_time() + interval
;
572 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_SYS_CRITICAL
))
576 if (timer_call_cancel(&calend_adjcall
))
584 calend_set_adjustment(
589 int64_t total
, ototal
;
590 uint32_t interval
= 0;
593 * Compute the total adjustment time in nanoseconds.
595 total
= ((int64_t)*secs
* (int64_t)NSEC_PER_SEC
) + (*microsecs
* (int64_t)NSEC_PER_USEC
);
598 * Disable commpage gettimeofday().
600 commpage_disable_timestamp();
603 * Get current absolute time.
605 now
= mach_absolute_time();
608 * Save the old adjustment total for later return.
610 ototal
= calend_adjtotal
;
613 * Is a new correction specified?
617 * Set delta to the standard, small, adjustment skew.
619 int32_t delta
= calend_adjskew
;
623 * Positive adjustment. If greater than the preset 'big'
624 * threshold, slew at a faster rate, capping if necessary.
626 if (total
> (int64_t) calend_adjbig
)
629 delta
= (int32_t)total
;
632 * Convert the delta back from ns to absolute time and store in adjoffset.
634 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
635 clock_calend
.adjoffset
= (uint32_t)t64
;
639 * Negative adjustment; therefore, negate the delta. If
640 * greater than the preset 'big' threshold, slew at a faster
641 * rate, capping if necessary.
643 if (total
< (int64_t) -calend_adjbig
)
647 delta
= (int32_t)total
;
650 * Save the current absolute time. Subsequent time operations occuring
651 * during this negative correction can make use of this value to ensure
652 * that time increases monotonically.
654 clock_calend
.adjstart
= now
;
657 * Convert the delta back from ns to absolute time and store in adjoffset.
659 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
660 clock_calend
.adjoffset
= (uint32_t)t64
;
664 * Store the total adjustment time in ns.
666 calend_adjtotal
= total
;
669 * Store the delta for this adjustment period in ns.
671 clock_calend
.adjdelta
= delta
;
674 * Set the interval in absolute time for later return.
676 interval
= calend_adjinterval
;
680 * No change; clear any prior adjustment.
682 calend_adjtotal
= clock_calend
.adjdelta
= 0;
686 * If an prior correction was in progress, return the
687 * remaining uncorrected time from it.
690 *secs
= (long)(ototal
/ (long)NSEC_PER_SEC
);
691 *microsecs
= (int)((ototal
% (int)NSEC_PER_SEC
) / (int)NSEC_PER_USEC
);
694 *secs
= *microsecs
= 0;
697 clock_track_calend_nowait();
704 calend_adjust_call(void)
712 if (--calend_adjactive
== 0) {
713 interval
= calend_adjust();
715 clock_deadline_for_periodic_event(interval
, mach_absolute_time(), &calend_adjdeadline
);
717 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_SYS_CRITICAL
))
731 uint32_t interval
= 0;
733 commpage_disable_timestamp();
735 now
= mach_absolute_time();
737 delta
= clock_calend
.adjdelta
;
740 clock_calend
.offset
+= clock_calend
.adjoffset
;
742 calend_adjtotal
-= delta
;
743 if (delta
> calend_adjtotal
) {
744 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
746 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
747 clock_calend
.adjoffset
= (uint32_t)t64
;
752 clock_calend
.offset
-= clock_calend
.adjoffset
;
754 calend_adjtotal
-= delta
;
755 if (delta
< calend_adjtotal
) {
756 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
758 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
759 clock_calend
.adjoffset
= (uint32_t)t64
;
762 if (clock_calend
.adjdelta
!= 0)
763 clock_calend
.adjstart
= now
;
766 if (clock_calend
.adjdelta
!= 0)
767 interval
= calend_adjinterval
;
770 clock_track_calend_nowait();
777 * clock_wakeup_calendar:
779 * Interface to power management, used
780 * to initiate the reset of the calendar
781 * on wake from sleep event.
784 clock_wakeup_calendar(void)
786 thread_call_enter(&calend_wakecall
);
790 * Wait / delay routines.
793 mach_wait_until_continue(
794 __unused
void *parameter
,
795 wait_result_t wresult
)
797 thread_syscall_return((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
802 * mach_wait_until_trap: Suspend execution of calling thread until the specified time has passed
804 * Parameters: args->deadline Amount of time to wait
811 mach_wait_until_trap(
812 struct mach_wait_until_trap_args
*args
)
814 uint64_t deadline
= args
->deadline
;
815 wait_result_t wresult
;
817 wresult
= assert_wait_deadline_with_leeway((event_t
)mach_wait_until_trap
, THREAD_ABORTSAFE
,
818 TIMEOUT_URGENCY_USER_NORMAL
, deadline
, 0);
819 if (wresult
== THREAD_WAITING
)
820 wresult
= thread_block(mach_wait_until_continue
);
822 return ((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
829 uint64_t now
= mach_absolute_time();
834 _clock_delay_until_deadline(deadline
- now
, deadline
);
838 * Preserve the original precise interval that the client
839 * requested for comparison to the spin threshold.
842 _clock_delay_until_deadline(
850 if ( ml_delay_should_spin(interval
) ||
851 get_preemption_level() != 0 ||
852 ml_get_interrupts_enabled() == FALSE
) {
853 machine_delay_until(interval
, deadline
);
855 assert_wait_deadline((event_t
)clock_delay_until
, THREAD_UNINT
, deadline
);
857 thread_block(THREAD_CONTINUE_NULL
);
865 uint32_t scale_factor
)
869 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
871 _clock_delay_until_deadline(abstime
, mach_absolute_time() + abstime
);
878 delay_for_interval((usec
< 0)? -usec
: usec
, NSEC_PER_USEC
);
882 * Miscellaneous routines.
885 clock_interval_to_deadline(
887 uint32_t scale_factor
,
892 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
894 *result
= mach_absolute_time() + abstime
;
898 clock_absolutetime_interval_to_deadline(
902 *result
= mach_absolute_time() + abstime
;
909 *result
= mach_absolute_time();
913 clock_deadline_for_periodic_event(
918 assert(interval
!= 0);
920 *deadline
+= interval
;
922 if (*deadline
<= abstime
) {
923 *deadline
= abstime
+ interval
;
924 abstime
= mach_absolute_time();
926 if (*deadline
<= abstime
)
927 *deadline
= abstime
+ interval
;
934 * clock_get_calendar_nanotime_nowait
936 * Description: Non-blocking version of clock_get_calendar_nanotime()
938 * Notes: This function operates by separately tracking calendar time
939 * updates using a two element structure to copy the calendar
940 * state, which may be asynchronously modified. It utilizes
941 * barrier instructions in the tracking process and in the local
942 * stable snapshot process in order to ensure that a consistent
943 * snapshot is used to perform the calculation.
946 clock_get_calendar_nanotime_nowait(
948 clock_nsec_t
*nanosecs
)
952 struct unlocked_clock_calend stable
;
955 stable
= flipflop
[i
]; /* take snapshot */
958 * Use a barrier instructions to ensure atomicity. We AND
959 * off the "in progress" bit to get the current generation
962 (void)hw_atomic_and(&stable
.gen
, ~(uint32_t)1);
965 * If an update _is_ in progress, the generation count will be
966 * off by one, if it _was_ in progress, it will be off by two,
967 * and if we caught it at a good time, it will be equal (and
968 * our snapshot is threfore stable).
970 if (flipflop
[i
].gen
== stable
.gen
)
973 /* Switch to the oher element of the flipflop, and try again. */
977 now
= mach_absolute_time();
979 if (stable
.calend
.adjdelta
< 0) {
982 if (now
> stable
.calend
.adjstart
) {
983 t32
= (uint32_t)(now
- stable
.calend
.adjstart
);
985 if (t32
> stable
.calend
.adjoffset
)
986 now
-= stable
.calend
.adjoffset
;
988 now
= stable
.calend
.adjstart
;
992 now
+= stable
.calend
.offset
;
994 absolutetime_to_microtime(now
, secs
, nanosecs
);
995 *nanosecs
*= NSEC_PER_USEC
;
997 *secs
+= (clock_sec_t
)stable
.calend
.epoch
;
1001 clock_track_calend_nowait(void)
1005 for (i
= 0; i
< 2; i
++) {
1006 struct clock_calend tmp
= clock_calend
;
1009 * Set the low bit if the generation count; since we use a
1010 * barrier instruction to do this, we are guaranteed that this
1011 * will flag an update in progress to an async caller trying
1012 * to examine the contents.
1014 (void)hw_atomic_or(&flipflop
[i
].gen
, 1);
1016 flipflop
[i
].calend
= tmp
;
1019 * Increment the generation count to clear the low bit to
1020 * signal completion. If a caller compares the generation
1021 * count after taking a copy while in progress, the count
1022 * will be off by two.
1024 (void)hw_atomic_add(&flipflop
[i
].gen
, 1);
1028 #endif /* CONFIG_DTRACE */