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 static uint64_t clock_boottime
; /* Seconds boottime epoch */
131 #define TIME_ADD(rsecs, secs, rfrac, frac, unit) \
133 if (((rfrac) += (frac)) >= (unit)) { \
140 #define TIME_SUB(rsecs, secs, rfrac, frac, unit) \
142 if ((int)((rfrac) -= (frac)) < 0) { \
152 * Called once at boot to configure the clock subsystem.
159 timer_call_setup(&calend_adjcall
, (timer_call_func_t
)calend_adjust_call
, NULL
);
160 thread_call_setup(&calend_wakecall
, (thread_call_func_t
)IOKitResetTime
, NULL
);
168 * Called on a processor each time started.
177 * clock_timebase_init:
179 * Called by machine dependent code
180 * to initialize areas dependent on the
181 * timebase value. May be called multiple
182 * times during start up.
185 clock_timebase_init(void)
189 nanoseconds_to_absolutetime(calend_adjperiod
, &abstime
);
190 calend_adjinterval
= (uint32_t)abstime
;
192 nanoseconds_to_absolutetime(NSEC_PER_SEC
/ 100, &abstime
);
193 hz_tick_interval
= (uint32_t)abstime
;
195 sched_timebase_init();
199 * mach_timebase_info_trap:
201 * User trap returns timebase constant.
204 mach_timebase_info_trap(
205 struct mach_timebase_info_trap_args
*args
)
207 mach_vm_address_t out_info_addr
= args
->info
;
208 mach_timebase_info_data_t info
;
210 clock_timebase_info(&info
);
212 copyout((void *)&info
, out_info_addr
, sizeof (info
));
214 return (KERN_SUCCESS
);
222 * clock_get_calendar_microtime:
224 * Returns the current calendar value,
225 * microseconds as the fraction.
228 clock_get_calendar_microtime(
230 clock_usec_t
*microsecs
)
238 now
= mach_absolute_time();
240 if (clock_calend
.adjdelta
< 0) {
244 * Since offset is decremented during a negative adjustment,
245 * ensure that time increases monotonically without going
246 * temporarily backwards.
247 * If the delta has not yet passed, now is set to the start
248 * of the current adjustment period; otherwise, we're between
249 * the expiry of the delta and the next call to calend_adjust(),
250 * and we offset accordingly.
252 if (now
> clock_calend
.adjstart
) {
253 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
255 if (t32
> clock_calend
.adjoffset
)
256 now
-= clock_calend
.adjoffset
;
258 now
= clock_calend
.adjstart
;
262 now
+= clock_calend
.offset
;
264 absolutetime_to_microtime(now
, secs
, microsecs
);
266 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
273 * clock_get_calendar_nanotime:
275 * Returns the current calendar value,
276 * nanoseconds as the fraction.
278 * Since we do not have an interface to
279 * set the calendar with resolution greater
280 * than a microsecond, we honor that here.
283 clock_get_calendar_nanotime(
285 clock_nsec_t
*nanosecs
)
293 now
= mach_absolute_time();
295 if (clock_calend
.adjdelta
< 0) {
298 if (now
> clock_calend
.adjstart
) {
299 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
301 if (t32
> clock_calend
.adjoffset
)
302 now
-= clock_calend
.adjoffset
;
304 now
= clock_calend
.adjstart
;
308 now
+= clock_calend
.offset
;
310 absolutetime_to_microtime(now
, secs
, nanosecs
);
312 *nanosecs
*= NSEC_PER_USEC
;
314 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
321 * clock_gettimeofday:
323 * Kernel interface for commpage implementation of
324 * gettimeofday() syscall.
326 * Returns the current calendar value, and updates the
327 * commpage info as appropriate. Because most calls to
328 * gettimeofday() are handled in user mode by the commpage,
329 * this routine should be used infrequently.
334 clock_usec_t
*microsecs
)
342 now
= mach_absolute_time();
344 if (clock_calend
.adjdelta
>= 0) {
345 clock_gettimeofday_set_commpage(now
, clock_calend
.epoch
, clock_calend
.offset
, secs
, microsecs
);
350 if (now
> clock_calend
.adjstart
) {
351 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
353 if (t32
> clock_calend
.adjoffset
)
354 now
-= clock_calend
.adjoffset
;
356 now
= clock_calend
.adjstart
;
359 now
+= clock_calend
.offset
;
361 absolutetime_to_microtime(now
, secs
, microsecs
);
363 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
371 * clock_set_calendar_microtime:
373 * Sets the current calendar value by
374 * recalculating the epoch and offset
375 * from the system clock.
377 * Also adjusts the boottime to keep the
378 * value consistent, writes the new
379 * calendar value to the platform clock,
380 * and sends calendar change notifications.
383 clock_set_calendar_microtime(
385 clock_usec_t microsecs
)
388 clock_usec_t microsys
;
392 newsecs
= (microsecs
< 500*USEC_PER_SEC
)? secs
: secs
+ 1;
397 commpage_disable_timestamp();
400 * Calculate the new calendar epoch based on
401 * the new value and the system clock.
403 clock_get_system_microtime(&sys
, µsys
);
404 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
407 * Adjust the boottime based on the delta.
409 clock_boottime
+= secs
- clock_calend
.epoch
;
412 * Set the new calendar epoch.
414 clock_calend
.epoch
= secs
;
416 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
419 * Cancel any adjustment in progress.
421 calend_adjtotal
= clock_calend
.adjdelta
= 0;
426 * Set the new value for the platform clock.
428 PESetGMTTimeOfDay(newsecs
);
433 * Send host notifications.
435 host_notify_calendar_change();
438 clock_track_calend_nowait();
443 * clock_initialize_calendar:
445 * Set the calendar and related clocks
446 * from the platform clock at boot or
449 * Also sends host notifications.
452 clock_initialize_calendar(void)
454 clock_sec_t sys
, secs
= PEGetGMTTimeOfDay();
455 clock_usec_t microsys
, microsecs
= 0;
461 commpage_disable_timestamp();
463 if ((long)secs
>= (long)clock_boottime
) {
465 * Initialize the boot time based on the platform clock.
467 if (clock_boottime
== 0)
468 clock_boottime
= secs
;
471 * Calculate the new calendar epoch based on
472 * the platform clock and the system clock.
474 clock_get_system_microtime(&sys
, µsys
);
475 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
478 * Set the new calendar epoch.
480 clock_calend
.epoch
= secs
;
482 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
485 * Cancel any adjustment in progress.
487 calend_adjtotal
= clock_calend
.adjdelta
= 0;
494 * Send host notifications.
496 host_notify_calendar_change();
499 clock_track_calend_nowait();
504 * clock_get_boottime_nanotime:
506 * Return the boottime, used by sysctl.
509 clock_get_boottime_nanotime(
511 clock_nsec_t
*nanosecs
)
518 *secs
= (clock_sec_t
)clock_boottime
;
528 * Interface to adjtime() syscall.
530 * Calculates adjustment variables and
531 * initiates adjustment.
544 interval
= calend_set_adjustment(secs
, microsecs
);
546 calend_adjdeadline
= mach_absolute_time() + interval
;
547 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_CRITICAL
))
551 if (timer_call_cancel(&calend_adjcall
))
559 calend_set_adjustment(
564 int64_t total
, ototal
;
565 uint32_t interval
= 0;
568 * Compute the total adjustment time in nanoseconds.
570 total
= (int64_t)*secs
* NSEC_PER_SEC
+ *microsecs
* NSEC_PER_USEC
;
573 * Disable commpage gettimeofday().
575 commpage_disable_timestamp();
578 * Get current absolute time.
580 now
= mach_absolute_time();
583 * Save the old adjustment total for later return.
585 ototal
= calend_adjtotal
;
588 * Is a new correction specified?
592 * Set delta to the standard, small, adjustment skew.
594 int32_t delta
= calend_adjskew
;
598 * Positive adjustment. If greater than the preset 'big'
599 * threshold, slew at a faster rate, capping if necessary.
601 if (total
> calend_adjbig
)
604 delta
= (int32_t)total
;
607 * Convert the delta back from ns to absolute time and store in adjoffset.
609 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
610 clock_calend
.adjoffset
= (uint32_t)t64
;
614 * Negative adjustment; therefore, negate the delta. If
615 * greater than the preset 'big' threshold, slew at a faster
616 * rate, capping if necessary.
618 if (total
< -calend_adjbig
)
622 delta
= (int32_t)total
;
625 * Save the current absolute time. Subsequent time operations occuring
626 * during this negative correction can make use of this value to ensure
627 * that time increases monotonically.
629 clock_calend
.adjstart
= now
;
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 * Store the total adjustment time in ns.
641 calend_adjtotal
= total
;
644 * Store the delta for this adjustment period in ns.
646 clock_calend
.adjdelta
= delta
;
649 * Set the interval in absolute time for later return.
651 interval
= calend_adjinterval
;
655 * No change; clear any prior adjustment.
657 calend_adjtotal
= clock_calend
.adjdelta
= 0;
661 * If an prior correction was in progress, return the
662 * remaining uncorrected time from it.
665 *secs
= (long)(ototal
/ NSEC_PER_SEC
);
666 *microsecs
= (int)((ototal
% NSEC_PER_SEC
) / NSEC_PER_USEC
);
669 *secs
= *microsecs
= 0;
672 clock_track_calend_nowait();
679 calend_adjust_call(void)
687 if (--calend_adjactive
== 0) {
688 interval
= calend_adjust();
690 clock_deadline_for_periodic_event(interval
, mach_absolute_time(), &calend_adjdeadline
);
692 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
, TIMER_CALL_CRITICAL
))
706 uint32_t interval
= 0;
708 commpage_disable_timestamp();
710 now
= mach_absolute_time();
712 delta
= clock_calend
.adjdelta
;
715 clock_calend
.offset
+= clock_calend
.adjoffset
;
717 calend_adjtotal
-= delta
;
718 if (delta
> calend_adjtotal
) {
719 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
721 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
722 clock_calend
.adjoffset
= (uint32_t)t64
;
727 clock_calend
.offset
-= clock_calend
.adjoffset
;
729 calend_adjtotal
-= delta
;
730 if (delta
< calend_adjtotal
) {
731 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
733 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
734 clock_calend
.adjoffset
= (uint32_t)t64
;
737 if (clock_calend
.adjdelta
!= 0)
738 clock_calend
.adjstart
= now
;
741 if (clock_calend
.adjdelta
!= 0)
742 interval
= calend_adjinterval
;
745 clock_track_calend_nowait();
752 * clock_wakeup_calendar:
754 * Interface to power management, used
755 * to initiate the reset of the calendar
756 * on wake from sleep event.
759 clock_wakeup_calendar(void)
761 thread_call_enter(&calend_wakecall
);
765 * Wait / delay routines.
768 mach_wait_until_continue(
769 __unused
void *parameter
,
770 wait_result_t wresult
)
772 thread_syscall_return((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
777 mach_wait_until_trap(
778 struct mach_wait_until_trap_args
*args
)
780 uint64_t deadline
= args
->deadline
;
781 wait_result_t wresult
;
783 wresult
= assert_wait_deadline((event_t
)mach_wait_until_trap
, THREAD_ABORTSAFE
, deadline
);
784 if (wresult
== THREAD_WAITING
)
785 wresult
= thread_block(mach_wait_until_continue
);
787 return ((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
794 uint64_t now
= mach_absolute_time();
799 if ( (deadline
- now
) < (8 * sched_cswtime
) ||
800 get_preemption_level() != 0 ||
801 ml_get_interrupts_enabled() == FALSE
)
802 machine_delay_until(deadline
);
804 assert_wait_deadline((event_t
)clock_delay_until
, THREAD_UNINT
, deadline
- sched_cswtime
);
806 thread_block(THREAD_CONTINUE_NULL
);
813 uint32_t scale_factor
)
817 clock_interval_to_deadline(interval
, scale_factor
, &end
);
819 clock_delay_until(end
);
826 delay_for_interval((usec
< 0)? -usec
: usec
, NSEC_PER_USEC
);
830 * Miscellaneous routines.
833 clock_interval_to_deadline(
835 uint32_t scale_factor
,
840 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
842 *result
= mach_absolute_time() + abstime
;
846 clock_absolutetime_interval_to_deadline(
850 *result
= mach_absolute_time() + abstime
;
857 *result
= mach_absolute_time();
861 clock_deadline_for_periodic_event(
866 assert(interval
!= 0);
868 *deadline
+= interval
;
870 if (*deadline
<= abstime
) {
871 *deadline
= abstime
+ interval
;
872 abstime
= mach_absolute_time();
874 if (*deadline
<= abstime
)
875 *deadline
= abstime
+ interval
;
882 * clock_get_calendar_nanotime_nowait
884 * Description: Non-blocking version of clock_get_calendar_nanotime()
886 * Notes: This function operates by separately tracking calendar time
887 * updates using a two element structure to copy the calendar
888 * state, which may be asynchronously modified. It utilizes
889 * barrier instructions in the tracking process and in the local
890 * stable snapshot process in order to ensure that a consistent
891 * snapshot is used to perform the calculation.
894 clock_get_calendar_nanotime_nowait(
896 clock_nsec_t
*nanosecs
)
900 struct unlocked_clock_calend stable
;
903 stable
= flipflop
[i
]; /* take snapshot */
906 * Use a barrier instructions to ensure atomicity. We AND
907 * off the "in progress" bit to get the current generation
910 (void)hw_atomic_and(&stable
.gen
, ~(uint32_t)1);
913 * If an update _is_ in progress, the generation count will be
914 * off by one, if it _was_ in progress, it will be off by two,
915 * and if we caught it at a good time, it will be equal (and
916 * our snapshot is threfore stable).
918 if (flipflop
[i
].gen
== stable
.gen
)
921 /* Switch to the oher element of the flipflop, and try again. */
925 now
= mach_absolute_time();
927 if (stable
.calend
.adjdelta
< 0) {
930 if (now
> stable
.calend
.adjstart
) {
931 t32
= (uint32_t)(now
- stable
.calend
.adjstart
);
933 if (t32
> stable
.calend
.adjoffset
)
934 now
-= stable
.calend
.adjoffset
;
936 now
= stable
.calend
.adjstart
;
940 now
+= stable
.calend
.offset
;
942 absolutetime_to_microtime(now
, secs
, nanosecs
);
943 *nanosecs
*= NSEC_PER_USEC
;
945 *secs
+= (clock_sec_t
)stable
.calend
.epoch
;
949 clock_track_calend_nowait(void)
953 for (i
= 0; i
< 2; i
++) {
954 struct clock_calend tmp
= clock_calend
;
957 * Set the low bit if the generation count; since we use a
958 * barrier instruction to do this, we are guaranteed that this
959 * will flag an update in progress to an async caller trying
960 * to examine the contents.
962 (void)hw_atomic_or(&flipflop
[i
].gen
, 1);
964 flipflop
[i
].calend
= tmp
;
967 * Increment the generation count to clear the low bit to
968 * signal completion. If a caller compares the generation
969 * count after taking a copy while in progress, the count
970 * will be off by two.
972 (void)hw_atomic_add(&flipflop
[i
].gen
, 1);
976 #endif /* CONFIG_DTRACE */