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(static,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
{
79 int32_t adjdelta
; /* Nanosecond time delta for this adjustment period */
80 uint64_t adjstart
; /* Absolute time value for start of this adjustment period */
81 uint32_t adjoffset
; /* Absolute time offset for this adjustment period as absolute value */
87 * Unlocked calendar flipflop; this is used to track a clock_calend such
88 * that we can safely access a snapshot of a valid clock_calend structure
89 * without needing to take any locks to do it.
91 * The trick is to use a generation count and set the low bit when it is
92 * being updated/read; by doing this, we guarantee, through use of the
93 * hw_atomic functions, that the generation is incremented when the bit
94 * is cleared atomically (by using a 1 bit add).
96 static struct unlocked_clock_calend
{
97 struct clock_calend calend
; /* copy of calendar */
98 uint32_t gen
; /* generation count */
101 static void clock_track_calend_nowait(void);
106 * Calendar adjustment variables and values.
108 #define calend_adjperiod (NSEC_PER_SEC / 100) /* adjustment period, ns */
109 #define calend_adjskew (40 * NSEC_PER_USEC) /* "standard" skew, ns / period */
110 #define calend_adjbig (NSEC_PER_SEC) /* use 10x skew above adjbig ns */
112 static int64_t calend_adjtotal
; /* Nanosecond remaining total adjustment */
113 static uint64_t calend_adjdeadline
; /* Absolute time value for next adjustment period */
114 static uint32_t calend_adjinterval
; /* Absolute time interval of adjustment period */
116 static timer_call_data_t calend_adjcall
;
117 static uint32_t calend_adjactive
;
119 static uint32_t calend_set_adjustment(
123 static void calend_adjust_call(void);
124 static uint32_t calend_adjust(void);
126 static thread_call_data_t calend_wakecall
;
128 extern void IOKitResetTime(void);
130 static uint64_t clock_boottime
; /* Seconds boottime epoch */
132 #define TIME_ADD(rsecs, secs, rfrac, frac, unit) \
134 if (((rfrac) += (frac)) >= (unit)) { \
141 #define TIME_SUB(rsecs, secs, rfrac, frac, unit) \
143 if ((int)((rfrac) -= (frac)) < 0) { \
153 * Called once at boot to configure the clock subsystem.
160 timer_call_setup(&calend_adjcall
, (timer_call_func_t
)calend_adjust_call
, NULL
);
161 thread_call_setup(&calend_wakecall
, (thread_call_func_t
)IOKitResetTime
, NULL
);
166 * Initialize the timer callouts.
168 timer_call_initialize();
174 * Called on a processor each time started.
183 * clock_timebase_init:
185 * Called by machine dependent code
186 * to initialize areas dependent on the
187 * timebase value. May be called multiple
188 * times during start up.
191 clock_timebase_init(void)
195 nanoseconds_to_absolutetime(calend_adjperiod
, &abstime
);
196 calend_adjinterval
= (uint32_t)abstime
;
198 nanoseconds_to_absolutetime(NSEC_PER_SEC
/ 100, &abstime
);
199 hz_tick_interval
= (uint32_t)abstime
;
201 sched_timebase_init();
205 * mach_timebase_info_trap:
207 * User trap returns timebase constant.
210 mach_timebase_info_trap(
211 struct mach_timebase_info_trap_args
*args
)
213 mach_vm_address_t out_info_addr
= args
->info
;
214 mach_timebase_info_data_t info
;
216 clock_timebase_info(&info
);
218 copyout((void *)&info
, out_info_addr
, sizeof (info
));
220 return (KERN_SUCCESS
);
228 * clock_get_calendar_microtime:
230 * Returns the current calendar value,
231 * microseconds as the fraction.
234 clock_get_calendar_microtime(
236 clock_usec_t
*microsecs
)
244 now
= mach_absolute_time();
246 if (clock_calend
.adjdelta
< 0) {
249 if (now
> clock_calend
.adjstart
) {
250 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
252 if (t32
> clock_calend
.adjoffset
)
253 now
-= clock_calend
.adjoffset
;
255 now
= clock_calend
.adjstart
;
259 now
+= clock_calend
.offset
;
261 absolutetime_to_microtime(now
, secs
, microsecs
);
263 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
270 * clock_get_calendar_nanotime:
272 * Returns the current calendar value,
273 * nanoseconds as the fraction.
275 * Since we do not have an interface to
276 * set the calendar with resolution greater
277 * than a microsecond, we honor that here.
280 clock_get_calendar_nanotime(
282 clock_nsec_t
*nanosecs
)
290 now
= mach_absolute_time();
292 if (clock_calend
.adjdelta
< 0) {
295 if (now
> clock_calend
.adjstart
) {
296 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
298 if (t32
> clock_calend
.adjoffset
)
299 now
-= clock_calend
.adjoffset
;
301 now
= clock_calend
.adjstart
;
305 now
+= clock_calend
.offset
;
307 absolutetime_to_microtime(now
, secs
, nanosecs
);
308 *nanosecs
*= NSEC_PER_USEC
;
310 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
317 * clock_gettimeofday:
319 * Kernel interface for commpage implementation of
320 * gettimeofday() syscall.
322 * Returns the current calendar value, and updates the
323 * commpage info as appropriate. Because most calls to
324 * gettimeofday() are handled in user mode by the commpage,
325 * this routine should be used infrequently.
330 clock_usec_t
*microsecs
)
338 now
= mach_absolute_time();
340 if (clock_calend
.adjdelta
>= 0) {
341 clock_gettimeofday_set_commpage(now
, clock_calend
.epoch
, clock_calend
.offset
, secs
, microsecs
);
346 if (now
> clock_calend
.adjstart
) {
347 t32
= (uint32_t)(now
- clock_calend
.adjstart
);
349 if (t32
> clock_calend
.adjoffset
)
350 now
-= clock_calend
.adjoffset
;
352 now
= clock_calend
.adjstart
;
355 now
+= clock_calend
.offset
;
357 absolutetime_to_microtime(now
, secs
, microsecs
);
359 *secs
+= (clock_sec_t
)clock_calend
.epoch
;
367 * clock_set_calendar_microtime:
369 * Sets the current calendar value by
370 * recalculating the epoch and offset
371 * from the system clock.
373 * Also adjusts the boottime to keep the
374 * value consistent, writes the new
375 * calendar value to the platform clock,
376 * and sends calendar change notifications.
379 clock_set_calendar_microtime(
381 clock_usec_t microsecs
)
384 clock_usec_t microsys
;
388 newsecs
= (microsecs
< 500*USEC_PER_SEC
)? secs
: secs
+ 1;
393 commpage_disable_timestamp();
396 * Calculate the new calendar epoch based on
397 * the new value and the system clock.
399 clock_get_system_microtime(&sys
, µsys
);
400 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
403 * Adjust the boottime based on the delta.
405 clock_boottime
+= secs
- clock_calend
.epoch
;
408 * Set the new calendar epoch.
410 clock_calend
.epoch
= secs
;
411 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
414 * Cancel any adjustment in progress.
416 calend_adjtotal
= clock_calend
.adjdelta
= 0;
421 * Set the new value for the platform clock.
423 PESetGMTTimeOfDay(newsecs
);
428 * Send host notifications.
430 host_notify_calendar_change();
433 clock_track_calend_nowait();
438 * clock_initialize_calendar:
440 * Set the calendar and related clocks
441 * from the platform clock at boot or
444 * Also sends host notifications.
447 clock_initialize_calendar(void)
449 clock_sec_t sys
, secs
= PEGetGMTTimeOfDay();
450 clock_usec_t microsys
, microsecs
= 0;
456 commpage_disable_timestamp();
458 if ((long)secs
>= (long)clock_boottime
) {
460 * Initialize the boot time based on the platform clock.
462 if (clock_boottime
== 0)
463 clock_boottime
= secs
;
466 * Calculate the new calendar epoch based on
467 * the platform clock and the system clock.
469 clock_get_system_microtime(&sys
, µsys
);
470 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
473 * Set the new calendar epoch.
475 clock_calend
.epoch
= secs
;
476 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
479 * Cancel any adjustment in progress.
481 calend_adjtotal
= clock_calend
.adjdelta
= 0;
488 * Send host notifications.
490 host_notify_calendar_change();
493 clock_track_calend_nowait();
498 * clock_get_boottime_nanotime:
500 * Return the boottime, used by sysctl.
503 clock_get_boottime_nanotime(
505 clock_nsec_t
*nanosecs
)
512 *secs
= (clock_sec_t
)clock_boottime
;
522 * Interface to adjtime() syscall.
524 * Calculates adjustment variables and
525 * initiates adjustment.
538 interval
= calend_set_adjustment(secs
, microsecs
);
540 calend_adjdeadline
= mach_absolute_time() + interval
;
541 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
))
545 if (timer_call_cancel(&calend_adjcall
))
553 calend_set_adjustment(
558 int64_t total
, ototal
;
559 uint32_t interval
= 0;
561 total
= (int64_t)*secs
* NSEC_PER_SEC
+ *microsecs
* NSEC_PER_USEC
;
563 commpage_disable_timestamp();
565 now
= mach_absolute_time();
567 ototal
= calend_adjtotal
;
570 int32_t delta
= calend_adjskew
;
573 if (total
> calend_adjbig
)
576 delta
= (int32_t)total
;
578 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
579 clock_calend
.adjoffset
= (uint32_t)t64
;
582 if (total
< -calend_adjbig
)
586 delta
= (int32_t)total
;
588 clock_calend
.adjstart
= now
;
590 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
591 clock_calend
.adjoffset
= (uint32_t)t64
;
594 calend_adjtotal
= total
;
595 clock_calend
.adjdelta
= delta
;
597 interval
= calend_adjinterval
;
600 calend_adjtotal
= clock_calend
.adjdelta
= 0;
603 *secs
= (long)(ototal
/ NSEC_PER_SEC
);
604 *microsecs
= (int)((ototal
% NSEC_PER_SEC
) / NSEC_PER_USEC
);
607 *secs
= *microsecs
= 0;
610 clock_track_calend_nowait();
617 calend_adjust_call(void)
625 if (--calend_adjactive
== 0) {
626 interval
= calend_adjust();
628 clock_deadline_for_periodic_event(interval
, mach_absolute_time(), &calend_adjdeadline
);
630 if (!timer_call_enter(&calend_adjcall
, calend_adjdeadline
))
644 uint32_t interval
= 0;
646 commpage_disable_timestamp();
648 now
= mach_absolute_time();
650 delta
= clock_calend
.adjdelta
;
653 clock_calend
.offset
+= clock_calend
.adjoffset
;
655 calend_adjtotal
-= delta
;
656 if (delta
> calend_adjtotal
) {
657 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
659 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
660 clock_calend
.adjoffset
= (uint32_t)t64
;
665 clock_calend
.offset
-= clock_calend
.adjoffset
;
667 calend_adjtotal
-= delta
;
668 if (delta
< calend_adjtotal
) {
669 clock_calend
.adjdelta
= delta
= (int32_t)calend_adjtotal
;
671 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
672 clock_calend
.adjoffset
= (uint32_t)t64
;
675 if (clock_calend
.adjdelta
!= 0)
676 clock_calend
.adjstart
= now
;
679 if (clock_calend
.adjdelta
!= 0)
680 interval
= calend_adjinterval
;
683 clock_track_calend_nowait();
690 * clock_wakeup_calendar:
692 * Interface to power management, used
693 * to initiate the reset of the calendar
694 * on wake from sleep event.
697 clock_wakeup_calendar(void)
699 thread_call_enter(&calend_wakecall
);
703 * Wait / delay routines.
706 mach_wait_until_continue(
707 __unused
void *parameter
,
708 wait_result_t wresult
)
710 thread_syscall_return((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
715 mach_wait_until_trap(
716 struct mach_wait_until_trap_args
*args
)
718 uint64_t deadline
= args
->deadline
;
719 wait_result_t wresult
;
721 wresult
= assert_wait_deadline((event_t
)mach_wait_until_trap
, THREAD_ABORTSAFE
, deadline
);
722 if (wresult
== THREAD_WAITING
)
723 wresult
= thread_block(mach_wait_until_continue
);
725 return ((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
732 uint64_t now
= mach_absolute_time();
737 if ( (deadline
- now
) < (8 * sched_cswtime
) ||
738 get_preemption_level() != 0 ||
739 ml_get_interrupts_enabled() == FALSE
)
740 machine_delay_until(deadline
);
742 assert_wait_deadline((event_t
)clock_delay_until
, THREAD_UNINT
, deadline
- sched_cswtime
);
744 thread_block(THREAD_CONTINUE_NULL
);
751 uint32_t scale_factor
)
755 clock_interval_to_deadline(interval
, scale_factor
, &end
);
757 clock_delay_until(end
);
764 delay_for_interval((usec
< 0)? -usec
: usec
, NSEC_PER_USEC
);
768 * Miscellaneous routines.
771 clock_interval_to_deadline(
773 uint32_t scale_factor
,
778 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
780 *result
= mach_absolute_time() + abstime
;
784 clock_absolutetime_interval_to_deadline(
788 *result
= mach_absolute_time() + abstime
;
795 *result
= mach_absolute_time();
799 clock_deadline_for_periodic_event(
804 assert(interval
!= 0);
806 *deadline
+= interval
;
808 if (*deadline
<= abstime
) {
809 *deadline
= abstime
+ interval
;
810 abstime
= mach_absolute_time();
812 if (*deadline
<= abstime
)
813 *deadline
= abstime
+ interval
;
820 * clock_get_calendar_nanotime_nowait
822 * Description: Non-blocking version of clock_get_calendar_nanotime()
824 * Notes: This function operates by separately tracking calendar time
825 * updates using a two element structure to copy the calendar
826 * state, which may be asynchronously modified. It utilizes
827 * barrier instructions in the tracking process and in the local
828 * stable snapshot process in order to ensure that a consistent
829 * snapshot is used to perform the calculation.
832 clock_get_calendar_nanotime_nowait(
834 clock_nsec_t
*nanosecs
)
838 struct unlocked_clock_calend stable
;
841 stable
= flipflop
[i
]; /* take snapshot */
844 * Use a barrier instructions to ensure atomicity. We AND
845 * off the "in progress" bit to get the current generation
848 (void)hw_atomic_and(&stable
.gen
, ~(uint32_t)1);
851 * If an update _is_ in progress, the generation count will be
852 * off by one, if it _was_ in progress, it will be off by two,
853 * and if we caught it at a good time, it will be equal (and
854 * our snapshot is threfore stable).
856 if (flipflop
[i
].gen
== stable
.gen
)
859 /* Switch to the oher element of the flipflop, and try again. */
863 now
= mach_absolute_time();
865 if (stable
.calend
.adjdelta
< 0) {
868 if (now
> stable
.calend
.adjstart
) {
869 t32
= (uint32_t)(now
- stable
.calend
.adjstart
);
871 if (t32
> stable
.calend
.adjoffset
)
872 now
-= stable
.calend
.adjoffset
;
874 now
= stable
.calend
.adjstart
;
878 now
+= stable
.calend
.offset
;
880 absolutetime_to_microtime(now
, secs
, nanosecs
);
881 *nanosecs
*= NSEC_PER_USEC
;
883 *secs
+= (clock_sec_t
)stable
.calend
.epoch
;
887 clock_track_calend_nowait(void)
891 for (i
= 0; i
< 2; i
++) {
892 struct clock_calend tmp
= clock_calend
;
895 * Set the low bit if the generation count; since we use a
896 * barrier instruction to do this, we are guaranteed that this
897 * will flag an update in progress to an async caller trying
898 * to examine the contents.
900 (void)hw_atomic_or(&flipflop
[i
].gen
, 1);
902 flipflop
[i
].calend
= tmp
;
905 * Increment the generation count to clear the low bit to
906 * signal completion. If a caller compares the generation
907 * count after taking a copy while in progress, the count
908 * will be off by two.
910 (void)hw_atomic_add(&flipflop
[i
].gen
, 1);
914 #endif /* CONFIG_DTRACE */