2 * Copyright (c) 2000-2005 Apple Computer, 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 static void clock_track_calend_nowait(void);
56 decl_simple_lock_data(static,clock_lock
)
59 * Time of day (calendar) variables.
63 * TOD <- (seconds + epoch, fraction) <- CONV(current absolute time + offset)
65 * where CONV converts absolute time units into seconds and a fraction.
67 static struct clock_calend
{
71 int64_t adjtotal
; /* Nanosecond remaining total adjustment */
72 uint64_t adjdeadline
; /* Absolute time value for next adjustment period */
73 uint32_t adjinterval
; /* Absolute time interval of adjustment period */
74 int32_t adjdelta
; /* Nanosecond time delta for this adjustment period */
75 uint64_t adjstart
; /* Absolute time value for start of this adjustment period */
76 uint32_t adjoffset
; /* Absolute time offset for this adjustment period as absolute value */
78 timer_call_data_t adjcall
;
83 * Unlocked calendar flipflop; this is used to track a clock_calend such
84 * that we can safely access a snapshot of a valid clock_calend structure
85 * without needing to take any locks to do it.
87 * The trick is to use a generation count and set the low bit when it is
88 * being updated/read; by doing this, we guarantee, through use of the
89 * hw_atomic functions, that the generation is incremented when the bit
90 * is cleared atomically (by using a 1 bit add).
92 static struct unlocked_clock_calend
{
93 struct clock_calend calend
; /* copy of calendar */
94 uint32_t gen
; /* generation count */
99 * Calendar adjustment variables and values.
101 #define calend_adjperiod (NSEC_PER_SEC / 100) /* adjustment period, ns */
102 #define calend_adjskew (40 * NSEC_PER_USEC) /* "standard" skew, ns / period */
103 #define calend_adjbig (NSEC_PER_SEC) /* use 10x skew above adjbig ns */
105 static uint32_t calend_set_adjustment(
109 static void calend_adjust_call(void);
110 static uint32_t calend_adjust(void);
112 static thread_call_data_t calend_wakecall
;
114 extern void IOKitResetTime(void);
116 static uint64_t clock_boottime
; /* Seconds boottime epoch */
118 #define TIME_ADD(rsecs, secs, rfrac, frac, unit) \
120 if (((rfrac) += (frac)) >= (unit)) { \
127 #define TIME_SUB(rsecs, secs, rfrac, frac, unit) \
129 if ((int32_t)((rfrac) -= (frac)) < 0) { \
139 * Called once at boot to configure the clock subsystem.
144 simple_lock_init(&clock_lock
, 0);
146 timer_call_setup(&clock_calend
.adjcall
, (timer_call_func_t
)calend_adjust_call
, NULL
);
147 thread_call_setup(&calend_wakecall
, (thread_call_func_t
)IOKitResetTime
, NULL
);
152 * Initialize the timer callouts.
154 timer_call_initialize();
160 * Called on a processor each time started.
169 * clock_timebase_init:
171 * Called by machine dependent code
172 * to initialize areas dependent on the
173 * timebase value. May be called multiple
174 * times during start up.
177 clock_timebase_init(void)
181 nanoseconds_to_absolutetime(calend_adjperiod
, &abstime
);
182 clock_calend
.adjinterval
= abstime
;
184 nanoseconds_to_absolutetime(NSEC_PER_SEC
/ 100, &abstime
);
185 hz_tick_interval
= abstime
;
187 sched_timebase_init();
191 * mach_timebase_info_trap:
193 * User trap returns timebase constant.
196 mach_timebase_info_trap(
197 struct mach_timebase_info_trap_args
*args
)
199 mach_vm_address_t out_info_addr
= args
->info
;
200 mach_timebase_info_data_t info
;
202 clock_timebase_info(&info
);
204 copyout((void *)&info
, out_info_addr
, sizeof (info
));
206 return (KERN_SUCCESS
);
214 * clock_get_calendar_microtime:
216 * Returns the current calendar value,
217 * microseconds as the fraction.
220 clock_get_calendar_microtime(
228 simple_lock(&clock_lock
);
230 now
= mach_absolute_time();
232 if (clock_calend
.adjdelta
< 0) {
235 if (now
> clock_calend
.adjstart
) {
236 t32
= now
- clock_calend
.adjstart
;
238 if (t32
> clock_calend
.adjoffset
)
239 now
-= clock_calend
.adjoffset
;
241 now
= clock_calend
.adjstart
;
245 now
+= clock_calend
.offset
;
247 absolutetime_to_microtime(now
, secs
, microsecs
);
249 *secs
+= clock_calend
.epoch
;
251 simple_unlock(&clock_lock
);
256 * clock_get_calendar_nanotime:
258 * Returns the current calendar value,
259 * nanoseconds as the fraction.
261 * Since we do not have an interface to
262 * set the calendar with resolution greater
263 * than a microsecond, we honor that here.
266 clock_get_calendar_nanotime(
274 simple_lock(&clock_lock
);
276 now
= mach_absolute_time();
278 if (clock_calend
.adjdelta
< 0) {
281 if (now
> clock_calend
.adjstart
) {
282 t32
= now
- clock_calend
.adjstart
;
284 if (t32
> clock_calend
.adjoffset
)
285 now
-= clock_calend
.adjoffset
;
287 now
= clock_calend
.adjstart
;
291 now
+= clock_calend
.offset
;
293 absolutetime_to_microtime(now
, secs
, nanosecs
);
294 *nanosecs
*= NSEC_PER_USEC
;
296 *secs
+= clock_calend
.epoch
;
298 simple_unlock(&clock_lock
);
303 * clock_gettimeofday:
305 * Kernel interface for commpage implementation of
306 * gettimeofday() syscall.
308 * Returns the current calendar value, and updates the
309 * commpage info as appropriate. Because most calls to
310 * gettimeofday() are handled in user mode by the commpage,
311 * this routine should be used infrequently.
322 simple_lock(&clock_lock
);
324 now
= mach_absolute_time();
326 if (clock_calend
.adjdelta
>= 0) {
327 clock_gettimeofday_set_commpage(now
, clock_calend
.epoch
, clock_calend
.offset
, secs
, microsecs
);
332 if (now
> clock_calend
.adjstart
) {
333 t32
= now
- clock_calend
.adjstart
;
335 if (t32
> clock_calend
.adjoffset
)
336 now
-= clock_calend
.adjoffset
;
338 now
= clock_calend
.adjstart
;
341 now
+= clock_calend
.offset
;
343 absolutetime_to_microtime(now
, secs
, microsecs
);
345 *secs
+= clock_calend
.epoch
;
348 simple_unlock(&clock_lock
);
353 * clock_set_calendar_microtime:
355 * Sets the current calendar value by
356 * recalculating the epoch and offset
357 * from the system clock.
359 * Also adjusts the boottime to keep the
360 * value consistent, writes the new
361 * calendar value to the platform clock,
362 * and sends calendar change notifications.
365 clock_set_calendar_microtime(
369 uint32_t sys
, microsys
;
373 newsecs
= (microsecs
< 500*USEC_PER_SEC
)?
377 simple_lock(&clock_lock
);
379 commpage_disable_timestamp();
382 * Calculate the new calendar epoch based on
383 * the new value and the system clock.
385 clock_get_system_microtime(&sys
, µsys
);
386 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
389 * Adjust the boottime based on the delta.
391 clock_boottime
+= secs
- clock_calend
.epoch
;
394 * Set the new calendar epoch.
396 clock_calend
.epoch
= secs
;
397 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
400 * Cancel any adjustment in progress.
402 clock_calend
.adjdelta
= clock_calend
.adjtotal
= 0;
404 simple_unlock(&clock_lock
);
407 * Set the new value for the platform clock.
409 PESetGMTTimeOfDay(newsecs
);
414 * Send host notifications.
416 host_notify_calendar_change();
419 clock_track_calend_nowait();
424 * clock_initialize_calendar:
426 * Set the calendar and related clocks
427 * from the platform clock at boot or
430 * Also sends host notifications.
433 clock_initialize_calendar(void)
435 uint32_t sys
, microsys
;
436 uint32_t microsecs
= 0, secs
= PEGetGMTTimeOfDay();
440 simple_lock(&clock_lock
);
442 commpage_disable_timestamp();
444 if ((int32_t)secs
>= (int32_t)clock_boottime
) {
446 * Initialize the boot time based on the platform clock.
448 if (clock_boottime
== 0)
449 clock_boottime
= secs
;
452 * Calculate the new calendar epoch based on
453 * the platform clock and the system clock.
455 clock_get_system_microtime(&sys
, µsys
);
456 TIME_SUB(secs
, sys
, microsecs
, microsys
, USEC_PER_SEC
);
459 * Set the new calendar epoch.
461 clock_calend
.epoch
= secs
;
462 nanoseconds_to_absolutetime((uint64_t)microsecs
* NSEC_PER_USEC
, &clock_calend
.offset
);
465 * Cancel any adjustment in progress.
467 clock_calend
.adjdelta
= clock_calend
.adjtotal
= 0;
470 simple_unlock(&clock_lock
);
474 * Send host notifications.
476 host_notify_calendar_change();
479 clock_track_calend_nowait();
484 * clock_get_boottime_nanotime:
486 * Return the boottime, used by sysctl.
489 clock_get_boottime_nanotime(
493 *secs
= clock_boottime
;
500 * Interface to adjtime() syscall.
502 * Calculates adjustment variables and
503 * initiates adjustment.
514 simple_lock(&clock_lock
);
516 interval
= calend_set_adjustment(secs
, microsecs
);
518 clock_calend
.adjdeadline
= mach_absolute_time() + interval
;
519 if (!timer_call_enter(&clock_calend
.adjcall
, clock_calend
.adjdeadline
))
520 clock_calend
.adjactive
++;
523 if (timer_call_cancel(&clock_calend
.adjcall
))
524 clock_calend
.adjactive
--;
526 simple_unlock(&clock_lock
);
531 calend_set_adjustment(
536 int64_t total
, ototal
;
537 uint32_t interval
= 0;
539 total
= (int64_t)*secs
* NSEC_PER_SEC
+ *microsecs
* NSEC_PER_USEC
;
541 commpage_disable_timestamp();
543 now
= mach_absolute_time();
545 ototal
= clock_calend
.adjtotal
;
548 int32_t delta
= calend_adjskew
;
551 if (total
> calend_adjbig
)
556 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
557 clock_calend
.adjoffset
= t64
;
560 if (total
< -calend_adjbig
)
566 clock_calend
.adjstart
= now
;
568 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
569 clock_calend
.adjoffset
= t64
;
572 clock_calend
.adjtotal
= total
;
573 clock_calend
.adjdelta
= delta
;
575 interval
= clock_calend
.adjinterval
;
578 clock_calend
.adjdelta
= clock_calend
.adjtotal
= 0;
581 *secs
= ototal
/ NSEC_PER_SEC
;
582 *microsecs
= (ototal
% NSEC_PER_SEC
) / NSEC_PER_USEC
;
585 *secs
= *microsecs
= 0;
588 clock_track_calend_nowait();
595 calend_adjust_call(void)
601 simple_lock(&clock_lock
);
603 if (--clock_calend
.adjactive
== 0) {
604 interval
= calend_adjust();
606 clock_deadline_for_periodic_event(interval
, mach_absolute_time(),
607 &clock_calend
.adjdeadline
);
609 if (!timer_call_enter(&clock_calend
.adjcall
, clock_calend
.adjdeadline
))
610 clock_calend
.adjactive
++;
614 simple_unlock(&clock_lock
);
623 uint32_t interval
= 0;
625 commpage_disable_timestamp();
627 now
= mach_absolute_time();
629 delta
= clock_calend
.adjdelta
;
632 clock_calend
.offset
+= clock_calend
.adjoffset
;
634 clock_calend
.adjtotal
-= delta
;
635 if (delta
> clock_calend
.adjtotal
) {
636 clock_calend
.adjdelta
= delta
= clock_calend
.adjtotal
;
638 nanoseconds_to_absolutetime((uint64_t)delta
, &t64
);
639 clock_calend
.adjoffset
= t64
;
644 clock_calend
.offset
-= clock_calend
.adjoffset
;
646 clock_calend
.adjtotal
-= delta
;
647 if (delta
< clock_calend
.adjtotal
) {
648 clock_calend
.adjdelta
= delta
= clock_calend
.adjtotal
;
650 nanoseconds_to_absolutetime((uint64_t)-delta
, &t64
);
651 clock_calend
.adjoffset
= t64
;
654 if (clock_calend
.adjdelta
!= 0)
655 clock_calend
.adjstart
= now
;
658 if (clock_calend
.adjdelta
!= 0)
659 interval
= clock_calend
.adjinterval
;
662 clock_track_calend_nowait();
669 * clock_wakeup_calendar:
671 * Interface to power management, used
672 * to initiate the reset of the calendar
673 * on wake from sleep event.
676 clock_wakeup_calendar(void)
678 thread_call_enter(&calend_wakecall
);
682 * Wait / delay routines.
685 mach_wait_until_continue(
686 __unused
void *parameter
,
687 wait_result_t wresult
)
689 thread_syscall_return((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
694 mach_wait_until_trap(
695 struct mach_wait_until_trap_args
*args
)
697 uint64_t deadline
= args
->deadline
;
698 wait_result_t wresult
;
700 wresult
= assert_wait_deadline((event_t
)mach_wait_until_trap
, THREAD_ABORTSAFE
, deadline
);
701 if (wresult
== THREAD_WAITING
)
702 wresult
= thread_block(mach_wait_until_continue
);
704 return ((wresult
== THREAD_INTERRUPTED
)? KERN_ABORTED
: KERN_SUCCESS
);
711 uint64_t now
= mach_absolute_time();
716 if ( (deadline
- now
) < (8 * sched_cswtime
) ||
717 get_preemption_level() != 0 ||
718 ml_get_interrupts_enabled() == FALSE
)
719 machine_delay_until(deadline
);
721 assert_wait_deadline((event_t
)clock_delay_until
, THREAD_UNINT
, deadline
- sched_cswtime
);
723 thread_block(THREAD_CONTINUE_NULL
);
730 uint32_t scale_factor
)
734 clock_interval_to_deadline(interval
, scale_factor
, &end
);
736 clock_delay_until(end
);
743 delay_for_interval((usec
< 0)? -usec
: usec
, NSEC_PER_USEC
);
747 * Miscellaneous routines.
750 clock_interval_to_deadline(
752 uint32_t scale_factor
,
757 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
759 *result
= mach_absolute_time() + abstime
;
763 clock_absolutetime_interval_to_deadline(
767 *result
= mach_absolute_time() + abstime
;
774 *result
= mach_absolute_time();
778 clock_deadline_for_periodic_event(
783 assert(interval
!= 0);
785 *deadline
+= interval
;
787 if (*deadline
<= abstime
) {
788 *deadline
= abstime
+ interval
;
789 abstime
= mach_absolute_time();
791 if (*deadline
<= abstime
)
792 *deadline
= abstime
+ interval
;
799 * clock_get_calendar_nanotime_nowait
801 * Description: Non-blocking version of clock_get_calendar_nanotime()
803 * Notes: This function operates by separately tracking calendar time
804 * updates using a two element structure to copy the calendar
805 * state, which may be asynchronously modified. It utilizes
806 * barrier instructions in the tracking process and in the local
807 * stable snapshot process in order to ensure that a consistent
808 * snapshot is used to perform the calculation.
811 clock_get_calendar_nanotime_nowait(
817 struct unlocked_clock_calend stable
;
820 stable
= flipflop
[i
]; /* take snapshot */
823 * Use a barrier instructions to ensure atomicity. We AND
824 * off the "in progress" bit to get the current generation
827 (void)hw_atomic_and(&stable
.gen
, ~(uint32_t)1);
830 * If an update _is_ in progress, the generation count will be
831 * off by one, if it _was_ in progress, it will be off by two,
832 * and if we caught it at a good time, it will be equal (and
833 * our snapshot is threfore stable).
835 if (flipflop
[i
].gen
== stable
.gen
)
838 /* Switch to the oher element of the flipflop, and try again. */
842 now
= mach_absolute_time();
844 if (stable
.calend
.adjdelta
< 0) {
847 if (now
> stable
.calend
.adjstart
) {
848 t32
= now
- stable
.calend
.adjstart
;
850 if (t32
> stable
.calend
.adjoffset
)
851 now
-= stable
.calend
.adjoffset
;
853 now
= stable
.calend
.adjstart
;
857 now
+= stable
.calend
.offset
;
859 absolutetime_to_microtime(now
, secs
, nanosecs
);
860 *nanosecs
*= NSEC_PER_USEC
;
862 *secs
+= stable
.calend
.epoch
;
866 clock_track_calend_nowait(void)
870 for (i
= 0; i
< 2; i
++) {
871 struct clock_calend tmp
= clock_calend
;
874 * Set the low bit if the generation count; since we use a
875 * barrier instruction to do this, we are guaranteed that this
876 * will flag an update in progress to an async caller trying
877 * to examine the contents.
879 (void)hw_atomic_or(&flipflop
[i
].gen
, 1);
881 flipflop
[i
].calend
= tmp
;
884 * Increment the generation count to clear the low bit to
885 * signal completion. If a caller compares the generation
886 * count after taking a copy while in progress, the count
887 * will be off by two.
889 (void)hw_atomic_add(&flipflop
[i
].gen
, 1);
892 #endif /* CONFIG_DTRACE */