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
)
241 now
= mach_absolute_time();
243 if (clock_calend
.adjdelta
< 0) {
247 * Since offset is decremented during a negative adjustment,
248 * ensure that time increases monotonically without going
249 * temporarily backwards.
250 * If the delta has not yet passed, now is set to the start
251 * of the current adjustment period; otherwise, we're between
252 * the expiry of the delta and the next call to calend_adjust(),
253 * and we offset accordingly.
255 if (now
> clock_calend
.adjstart
) {
256 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
258 if (t32
> clock_calend
.adjoffset
)
259 now
-= clock_calend
.adjoffset
;
261 now
= clock_calend
.adjstart
;
265 now
+= clock_calend
.offset
;
267 absolutetime_to_microtime(now
, secs
, microsecs
);
269 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
276 * clock_get_calendar_nanotime:
278 * Returns the current calendar value,
279 * nanoseconds as the fraction.
281 * Since we do not have an interface to
282 * set the calendar with resolution greater
283 * than a microsecond, we honor that here.
286 clock_get_calendar_nanotime(
288 clock_nsec_t
*nanosecs
)
296 now
= mach_absolute_time();
298 if (clock_calend
.adjdelta
< 0) {
301 if (now
> clock_calend
.adjstart
) {
302 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
304 if (t32
> clock_calend
.adjoffset
)
305 now
-= clock_calend
.adjoffset
;
307 now
= clock_calend
.adjstart
;
311 now
+= clock_calend
.offset
;
313 absolutetime_to_microtime(now
, secs
, nanosecs
);
315 *nanosecs
*= NSEC_PER_USEC
;
317 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
324 * clock_gettimeofday:
326 * Kernel interface for commpage implementation of
327 * gettimeofday() syscall.
329 * Returns the current calendar value, and updates the
330 * commpage info as appropriate. Because most calls to
331 * gettimeofday() are handled in user mode by the commpage,
332 * this routine should be used infrequently.
337 clock_usec_t
*microsecs
)
345 now
= mach_absolute_time();
347 if (clock_calend
.adjdelta
>= 0) {
348 clock_gettimeofday_set_commpage(now
, clock_calend
.epoch
, clock_calend
.offset
, secs
, microsecs
);
353 if (now
> clock_calend
.adjstart
) {
354 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
356 if (t32
> clock_calend
.adjoffset
)
357 now
-= clock_calend
.adjoffset
;
359 now
= clock_calend
.adjstart
;
362 now
+= clock_calend
.offset
;
364 absolutetime_to_microtime(now
, secs
, microsecs
);
366 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
374 * clock_set_calendar_microtime:
376 * Sets the current calendar value by
377 * recalculating the epoch and offset
378 * from the system clock.
380 * Also adjusts the boottime to keep the
381 * value consistent, writes the new
382 * calendar value to the platform clock,
383 * and sends calendar change notifications.
386 clock_set_calendar_microtime(
388 clock_usec_t microsecs
)
391 clock_usec_t microsys
;
395 newsecs
= (microsecs
< 500*USEC_PER_SEC
)? secs
: secs
+ 1;
400 commpage_disable_timestamp();
403 * Calculate the new calendar epoch based on
404 * the new value and the system clock.
406 clock_get_system_microtime(&sys
, µsys
);
407 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
410 * Adjust the boottime based on the delta.
412 clock_boottime
+= secs
- clock_calend
.epoch
;
415 * Set the new calendar epoch.
417 clock_calend
.epoch
= secs
;
419 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
422 * Cancel any adjustment in progress.
424 calend_adjtotal
= clock_calend
.adjdelta
= 0;
429 * Set the new value for the platform clock.
431 PESetGMTTimeOfDay(newsecs
);
436 * Send host notifications.
438 host_notify_calendar_change();
441 clock_track_calend_nowait();
446 * clock_initialize_calendar:
448 * Set the calendar and related clocks
449 * from the platform clock at boot or
452 * Also sends host notifications.
455 clock_initialize_calendar(void)
457 clock_sec_t sys
, secs
= PEGetGMTTimeOfDay();
458 clock_usec_t microsys
, microsecs
= 0;
464 commpage_disable_timestamp();
466 if ((long)secs
>= (long)clock_boottime
) {
468 * Initialize the boot time based on the platform clock.
470 if (clock_boottime
== 0)
471 clock_boottime
= secs
;
474 * Calculate the new calendar epoch based on
475 * the platform clock and the system clock.
477 clock_get_system_microtime(&sys
, µsys
);
478 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
481 * Set the new calendar epoch.
483 clock_calend
.epoch
= secs
;
485 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
488 * Cancel any adjustment in progress.
490 calend_adjtotal
= clock_calend
.adjdelta
= 0;
497 * Send host notifications.
499 host_notify_calendar_change();
502 clock_track_calend_nowait();
507 * clock_get_boottime_nanotime:
509 * Return the boottime, used by sysctl.
512 clock_get_boottime_nanotime(
514 clock_nsec_t
*nanosecs
)
521 *secs
= (clock_sec_t
)clock_boottime
;
531 * Interface to adjtime() syscall.
533 * Calculates adjustment variables and
534 * initiates adjustment.
547 interval
= calend_set_adjustment(secs
, microsecs
);
549 calend_adjdeadline
= mach_absolute_time() + interval
;
550 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_CRITICAL
))
554 if (timer_call_cancel(&calend_adjcall
))
562 calend_set_adjustment(
567 int64_t total
, ototal
;
568 uint32_t interval
= 0;
571 * Compute the total adjustment time in nanoseconds.
573 total
= (int64_t)*secs
* NSEC_PER_SEC
+ *microsecs
* NSEC_PER_USEC
;
576 * Disable commpage gettimeofday().
578 commpage_disable_timestamp();
581 * Get current absolute time.
583 now
= mach_absolute_time();
586 * Save the old adjustment total for later return.
588 ototal
= calend_adjtotal
;
591 * Is a new correction specified?
595 * Set delta to the standard, small, adjustment skew.
597 int32_t delta
= calend_adjskew
;
601 * Positive adjustment. If greater than the preset 'big'
602 * threshold, slew at a faster rate, capping if necessary.
604 if (total
> calend_adjbig
)
607 delta
= (int32_t)total
;
610 * Convert the delta back from ns to absolute time and store in adjoffset.
612 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
613 clock_calend
.adjoffset
= (uint32_t)t64
;
617 * Negative adjustment; therefore, negate the delta. If
618 * greater than the preset 'big' threshold, slew at a faster
619 * rate, capping if necessary.
621 if (total
< -calend_adjbig
)
625 delta
= (int32_t)total
;
628 * Save the current absolute time. Subsequent time operations occuring
629 * during this negative correction can make use of this value to ensure
630 * that time increases monotonically.
632 clock_calend
.adjstart
= now
;
635 * Convert the delta back from ns to absolute time and store in adjoffset.
637 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
638 clock_calend
.adjoffset
= (uint32_t)t64
;
642 * Store the total adjustment time in ns.
644 calend_adjtotal
= total
;
647 * Store the delta for this adjustment period in ns.
649 clock_calend
.adjdelta
= delta
;
652 * Set the interval in absolute time for later return.
654 interval
= calend_adjinterval
;
658 * No change; clear any prior adjustment.
660 calend_adjtotal
= clock_calend
.adjdelta
= 0;
664 * If an prior correction was in progress, return the
665 * remaining uncorrected time from it.
668 *secs
= (long)(ototal
/ NSEC_PER_SEC
);
669 *microsecs
= (int)((ototal
% NSEC_PER_SEC
) / NSEC_PER_USEC
);
672 *secs
= *microsecs
= 0;
675 clock_track_calend_nowait();
682 calend_adjust_call(void)
690 if (--calend_adjactive
== 0) {
691 interval
= calend_adjust();
693 clock_deadline_for_periodic_event(interval
, mach_absolute_time(), &calend_adjdeadline
);
695 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_CRITICAL
))
709 uint32_t interval
= 0;
711 commpage_disable_timestamp();
713 now
= mach_absolute_time();
715 delta
= clock_calend
.adjdelta
;
718 clock_calend
.offset
+= clock_calend
.adjoffset
;
720 calend_adjtotal
-= delta
;
721 if (delta
> calend_adjtotal
) {
722 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
724 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
725 clock_calend
.adjoffset
= (uint32_t)t64
;
730 clock_calend
.offset
-= clock_calend
.adjoffset
;
732 calend_adjtotal
-= delta
;
733 if (delta
< calend_adjtotal
) {
734 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
736 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
737 clock_calend
.adjoffset
= (uint32_t)t64
;
740 if (clock_calend
.adjdelta
!= 0)
741 clock_calend
.adjstart
= now
;
744 if (clock_calend
.adjdelta
!= 0)
745 interval
= calend_adjinterval
;
748 clock_track_calend_nowait();
755 * clock_wakeup_calendar:
757 * Interface to power management, used
758 * to initiate the reset of the calendar
759 * on wake from sleep event.
762 clock_wakeup_calendar(void)
764 thread_call_enter(&calend_wakecall
);
768 * Wait / delay routines.
771 mach_wait_until_continue(
772 __unused
void *parameter
,
773 wait_result_t wresult
)
775 thread_syscall_return((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
780 * mach_wait_until_trap: Suspend execution of calling thread until the specified time has passed
782 * Parameters: args->deadline Amount of time to wait
789 mach_wait_until_trap(
790 struct mach_wait_until_trap_args
*args
)
792 uint64_t deadline
= args
->deadline
;
793 wait_result_t wresult
;
795 wresult
= assert_wait_deadline((event_t
)mach_wait_until_trap
, THREAD_ABORTSAFE
, deadline
);
796 if (wresult
== THREAD_WAITING
)
797 wresult
= thread_block(mach_wait_until_continue
);
799 return ((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
806 uint64_t now
= mach_absolute_time();
811 _clock_delay_until_deadline(deadline
- now
, deadline
);
815 * Preserve the original precise interval that the client
816 * requested for comparison to the spin threshold.
819 _clock_delay_until_deadline(
827 if ( ml_delay_should_spin(interval
) ||
828 get_preemption_level() != 0 ||
829 ml_get_interrupts_enabled() == FALSE
) {
830 machine_delay_until(interval
, deadline
);
832 assert_wait_deadline((event_t
)clock_delay_until
, THREAD_UNINT
, deadline
);
834 thread_block(THREAD_CONTINUE_NULL
);
842 uint32_t scale_factor
)
846 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
848 _clock_delay_until_deadline(abstime
, mach_absolute_time() + abstime
);
855 delay_for_interval((usec
< 0)? -usec
: usec
, NSEC_PER_USEC
);
859 * Miscellaneous routines.
862 clock_interval_to_deadline(
864 uint32_t scale_factor
,
869 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
871 *result
= mach_absolute_time() + abstime
;
875 clock_absolutetime_interval_to_deadline(
879 *result
= mach_absolute_time() + abstime
;
886 *result
= mach_absolute_time();
890 clock_deadline_for_periodic_event(
895 assert(interval
!= 0);
897 *deadline
+= interval
;
899 if (*deadline
<= abstime
) {
900 *deadline
= abstime
+ interval
;
901 abstime
= mach_absolute_time();
903 if (*deadline
<= abstime
)
904 *deadline
= abstime
+ interval
;
911 * clock_get_calendar_nanotime_nowait
913 * Description: Non-blocking version of clock_get_calendar_nanotime()
915 * Notes: This function operates by separately tracking calendar time
916 * updates using a two element structure to copy the calendar
917 * state, which may be asynchronously modified. It utilizes
918 * barrier instructions in the tracking process and in the local
919 * stable snapshot process in order to ensure that a consistent
920 * snapshot is used to perform the calculation.
923 clock_get_calendar_nanotime_nowait(
925 clock_nsec_t
*nanosecs
)
929 struct unlocked_clock_calend stable
;
932 stable
= flipflop
[i
]; /* take snapshot */
935 * Use a barrier instructions to ensure atomicity. We AND
936 * off the "in progress" bit to get the current generation
939 (void)hw_atomic_and(&stable
.gen
, ~(uint32_t)1);
942 * If an update _is_ in progress, the generation count will be
943 * off by one, if it _was_ in progress, it will be off by two,
944 * and if we caught it at a good time, it will be equal (and
945 * our snapshot is threfore stable).
947 if (flipflop
[i
].gen
== stable
.gen
)
950 /* Switch to the oher element of the flipflop, and try again. */
954 now
= mach_absolute_time();
956 if (stable
.calend
.adjdelta
< 0) {
959 if (now
> stable
.calend
.adjstart
) {
960 t32
= (uint32_t)(now
- stable
.calend
.adjstart
);
962 if (t32
> stable
.calend
.adjoffset
)
963 now
-= stable
.calend
.adjoffset
;
965 now
= stable
.calend
.adjstart
;
969 now
+= stable
.calend
.offset
;
971 absolutetime_to_microtime(now
, secs
, nanosecs
);
972 *nanosecs
*= NSEC_PER_USEC
;
974 *secs
+= (clock_sec_t
)stable
.calend
.epoch
;
978 clock_track_calend_nowait(void)
982 for (i
= 0; i
< 2; i
++) {
983 struct clock_calend tmp
= clock_calend
;
986 * Set the low bit if the generation count; since we use a
987 * barrier instruction to do this, we are guaranteed that this
988 * will flag an update in progress to an async caller trying
989 * to examine the contents.
991 (void)hw_atomic_or(&flipflop
[i
].gen
, 1);
993 flipflop
[i
].calend
= tmp
;
996 * Increment the generation count to clear the low bit to
997 * signal completion. If a caller compares the generation
998 * count after taking a copy while in progress, the count
999 * will be off by two.
1001 (void)hw_atomic_add(&flipflop
[i
].gen
, 1);
1005 #endif /* CONFIG_DTRACE */