4 * Kernel internal timers, kernel timekeeping, basic process system calls
6 * Copyright (C) 1991, 1992 Linus Torvalds
8 * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better.
10 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
11 * "A Kernel Model for Precision Timekeeping" by Dave Mills
12 * 1998-12-24 Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
13 * serialize accesses to xtime/lost_ticks).
14 * Copyright (C) 1998 Andrea Arcangeli
15 * 1999-03-10 Improved NTP compatibility by Ulrich Windl
16 * 2002-05-31 Move sys_sysinfo here and make its locking sane, Robert Love
17 * 2000-10-05 Implemented scalable SMP per-CPU timer handling.
18 * Copyright (C) 2000, 2001, 2002 Ingo Molnar
19 * Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar
22 #include <linux/kernel_stat.h>
23 #include <linux/module.h>
24 #include <linux/interrupt.h>
25 #include <linux/percpu.h>
26 #include <linux/init.h>
28 #include <linux/swap.h>
29 #include <linux/notifier.h>
30 #include <linux/thread_info.h>
31 #include <linux/time.h>
32 #include <linux/jiffies.h>
33 #include <linux/posix-timers.h>
34 #include <linux/cpu.h>
35 #include <linux/syscalls.h>
36 #include <linux/delay.h>
38 #include <asm/uaccess.h>
39 #include <asm/unistd.h>
40 #include <asm/div64.h>
41 #include <asm/timex.h>
44 #ifdef CONFIG_TIME_INTERPOLATION
45 static void time_interpolator_update(long delta_nsec
);
47 #define time_interpolator_update(x)
50 u64 jiffies_64 __cacheline_aligned_in_smp
= INITIAL_JIFFIES
;
52 EXPORT_SYMBOL(jiffies_64
);
55 * per-CPU timer vector definitions:
58 #define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
59 #define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
60 #define TVN_SIZE (1 << TVN_BITS)
61 #define TVR_SIZE (1 << TVR_BITS)
62 #define TVN_MASK (TVN_SIZE - 1)
63 #define TVR_MASK (TVR_SIZE - 1)
67 struct timer_list
*running_timer
;
70 typedef struct tvec_s
{
71 struct list_head vec
[TVN_SIZE
];
74 typedef struct tvec_root_s
{
75 struct list_head vec
[TVR_SIZE
];
78 struct tvec_t_base_s
{
79 struct timer_base_s t_base
;
80 unsigned long timer_jiffies
;
86 } ____cacheline_aligned_in_smp
;
88 typedef struct tvec_t_base_s tvec_base_t
;
89 static DEFINE_PER_CPU(tvec_base_t
*, tvec_bases
);
90 static tvec_base_t boot_tvec_bases
;
92 static inline void set_running_timer(tvec_base_t
*base
,
93 struct timer_list
*timer
)
96 base
->t_base
.running_timer
= timer
;
100 static void internal_add_timer(tvec_base_t
*base
, struct timer_list
*timer
)
102 unsigned long expires
= timer
->expires
;
103 unsigned long idx
= expires
- base
->timer_jiffies
;
104 struct list_head
*vec
;
106 if (idx
< TVR_SIZE
) {
107 int i
= expires
& TVR_MASK
;
108 vec
= base
->tv1
.vec
+ i
;
109 } else if (idx
< 1 << (TVR_BITS
+ TVN_BITS
)) {
110 int i
= (expires
>> TVR_BITS
) & TVN_MASK
;
111 vec
= base
->tv2
.vec
+ i
;
112 } else if (idx
< 1 << (TVR_BITS
+ 2 * TVN_BITS
)) {
113 int i
= (expires
>> (TVR_BITS
+ TVN_BITS
)) & TVN_MASK
;
114 vec
= base
->tv3
.vec
+ i
;
115 } else if (idx
< 1 << (TVR_BITS
+ 3 * TVN_BITS
)) {
116 int i
= (expires
>> (TVR_BITS
+ 2 * TVN_BITS
)) & TVN_MASK
;
117 vec
= base
->tv4
.vec
+ i
;
118 } else if ((signed long) idx
< 0) {
120 * Can happen if you add a timer with expires == jiffies,
121 * or you set a timer to go off in the past
123 vec
= base
->tv1
.vec
+ (base
->timer_jiffies
& TVR_MASK
);
126 /* If the timeout is larger than 0xffffffff on 64-bit
127 * architectures then we use the maximum timeout:
129 if (idx
> 0xffffffffUL
) {
131 expires
= idx
+ base
->timer_jiffies
;
133 i
= (expires
>> (TVR_BITS
+ 3 * TVN_BITS
)) & TVN_MASK
;
134 vec
= base
->tv5
.vec
+ i
;
139 list_add_tail(&timer
->entry
, vec
);
142 typedef struct timer_base_s timer_base_t
;
144 * Used by TIMER_INITIALIZER, we can't use per_cpu(tvec_bases)
145 * at compile time, and we need timer->base to lock the timer.
147 timer_base_t __init_timer_base
148 ____cacheline_aligned_in_smp
= { .lock
= SPIN_LOCK_UNLOCKED
};
149 EXPORT_SYMBOL(__init_timer_base
);
152 * init_timer - initialize a timer.
153 * @timer: the timer to be initialized
155 * init_timer() must be done to a timer prior calling *any* of the
156 * other timer functions.
158 void fastcall
init_timer(struct timer_list
*timer
)
160 timer
->entry
.next
= NULL
;
161 timer
->base
= &per_cpu(tvec_bases
, raw_smp_processor_id())->t_base
;
163 EXPORT_SYMBOL(init_timer
);
165 static inline void detach_timer(struct timer_list
*timer
,
168 struct list_head
*entry
= &timer
->entry
;
170 __list_del(entry
->prev
, entry
->next
);
173 entry
->prev
= LIST_POISON2
;
177 * We are using hashed locking: holding per_cpu(tvec_bases).t_base.lock
178 * means that all timers which are tied to this base via timer->base are
179 * locked, and the base itself is locked too.
181 * So __run_timers/migrate_timers can safely modify all timers which could
182 * be found on ->tvX lists.
184 * When the timer's base is locked, and the timer removed from list, it is
185 * possible to set timer->base = NULL and drop the lock: the timer remains
188 static timer_base_t
*lock_timer_base(struct timer_list
*timer
,
189 unsigned long *flags
)
195 if (likely(base
!= NULL
)) {
196 spin_lock_irqsave(&base
->lock
, *flags
);
197 if (likely(base
== timer
->base
))
199 /* The timer has migrated to another CPU */
200 spin_unlock_irqrestore(&base
->lock
, *flags
);
206 int __mod_timer(struct timer_list
*timer
, unsigned long expires
)
209 tvec_base_t
*new_base
;
213 BUG_ON(!timer
->function
);
215 base
= lock_timer_base(timer
, &flags
);
217 if (timer_pending(timer
)) {
218 detach_timer(timer
, 0);
222 new_base
= __get_cpu_var(tvec_bases
);
224 if (base
!= &new_base
->t_base
) {
226 * We are trying to schedule the timer on the local CPU.
227 * However we can't change timer's base while it is running,
228 * otherwise del_timer_sync() can't detect that the timer's
229 * handler yet has not finished. This also guarantees that
230 * the timer is serialized wrt itself.
232 if (unlikely(base
->running_timer
== timer
)) {
233 /* The timer remains on a former base */
234 new_base
= container_of(base
, tvec_base_t
, t_base
);
236 /* See the comment in lock_timer_base() */
238 spin_unlock(&base
->lock
);
239 spin_lock(&new_base
->t_base
.lock
);
240 timer
->base
= &new_base
->t_base
;
244 timer
->expires
= expires
;
245 internal_add_timer(new_base
, timer
);
246 spin_unlock_irqrestore(&new_base
->t_base
.lock
, flags
);
251 EXPORT_SYMBOL(__mod_timer
);
254 * add_timer_on - start a timer on a particular CPU
255 * @timer: the timer to be added
256 * @cpu: the CPU to start it on
258 * This is not very scalable on SMP. Double adds are not possible.
260 void add_timer_on(struct timer_list
*timer
, int cpu
)
262 tvec_base_t
*base
= per_cpu(tvec_bases
, cpu
);
265 BUG_ON(timer_pending(timer
) || !timer
->function
);
266 spin_lock_irqsave(&base
->t_base
.lock
, flags
);
267 timer
->base
= &base
->t_base
;
268 internal_add_timer(base
, timer
);
269 spin_unlock_irqrestore(&base
->t_base
.lock
, flags
);
274 * mod_timer - modify a timer's timeout
275 * @timer: the timer to be modified
277 * mod_timer is a more efficient way to update the expire field of an
278 * active timer (if the timer is inactive it will be activated)
280 * mod_timer(timer, expires) is equivalent to:
282 * del_timer(timer); timer->expires = expires; add_timer(timer);
284 * Note that if there are multiple unserialized concurrent users of the
285 * same timer, then mod_timer() is the only safe way to modify the timeout,
286 * since add_timer() cannot modify an already running timer.
288 * The function returns whether it has modified a pending timer or not.
289 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
290 * active timer returns 1.)
292 int mod_timer(struct timer_list
*timer
, unsigned long expires
)
294 BUG_ON(!timer
->function
);
297 * This is a common optimization triggered by the
298 * networking code - if the timer is re-modified
299 * to be the same thing then just return:
301 if (timer
->expires
== expires
&& timer_pending(timer
))
304 return __mod_timer(timer
, expires
);
307 EXPORT_SYMBOL(mod_timer
);
310 * del_timer - deactive a timer.
311 * @timer: the timer to be deactivated
313 * del_timer() deactivates a timer - this works on both active and inactive
316 * The function returns whether it has deactivated a pending timer or not.
317 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
318 * active timer returns 1.)
320 int del_timer(struct timer_list
*timer
)
326 if (timer_pending(timer
)) {
327 base
= lock_timer_base(timer
, &flags
);
328 if (timer_pending(timer
)) {
329 detach_timer(timer
, 1);
332 spin_unlock_irqrestore(&base
->lock
, flags
);
338 EXPORT_SYMBOL(del_timer
);
342 * This function tries to deactivate a timer. Upon successful (ret >= 0)
343 * exit the timer is not queued and the handler is not running on any CPU.
345 * It must not be called from interrupt contexts.
347 int try_to_del_timer_sync(struct timer_list
*timer
)
353 base
= lock_timer_base(timer
, &flags
);
355 if (base
->running_timer
== timer
)
359 if (timer_pending(timer
)) {
360 detach_timer(timer
, 1);
364 spin_unlock_irqrestore(&base
->lock
, flags
);
370 * del_timer_sync - deactivate a timer and wait for the handler to finish.
371 * @timer: the timer to be deactivated
373 * This function only differs from del_timer() on SMP: besides deactivating
374 * the timer it also makes sure the handler has finished executing on other
377 * Synchronization rules: callers must prevent restarting of the timer,
378 * otherwise this function is meaningless. It must not be called from
379 * interrupt contexts. The caller must not hold locks which would prevent
380 * completion of the timer's handler. The timer's handler must not call
381 * add_timer_on(). Upon exit the timer is not queued and the handler is
382 * not running on any CPU.
384 * The function returns whether it has deactivated a pending timer or not.
386 int del_timer_sync(struct timer_list
*timer
)
389 int ret
= try_to_del_timer_sync(timer
);
395 EXPORT_SYMBOL(del_timer_sync
);
398 static int cascade(tvec_base_t
*base
, tvec_t
*tv
, int index
)
400 /* cascade all the timers from tv up one level */
401 struct list_head
*head
, *curr
;
403 head
= tv
->vec
+ index
;
406 * We are removing _all_ timers from the list, so we don't have to
407 * detach them individually, just clear the list afterwards.
409 while (curr
!= head
) {
410 struct timer_list
*tmp
;
412 tmp
= list_entry(curr
, struct timer_list
, entry
);
413 BUG_ON(tmp
->base
!= &base
->t_base
);
415 internal_add_timer(base
, tmp
);
417 INIT_LIST_HEAD(head
);
423 * __run_timers - run all expired timers (if any) on this CPU.
424 * @base: the timer vector to be processed.
426 * This function cascades all vectors and executes all expired timer
429 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
431 static inline void __run_timers(tvec_base_t
*base
)
433 struct timer_list
*timer
;
435 spin_lock_irq(&base
->t_base
.lock
);
436 while (time_after_eq(jiffies
, base
->timer_jiffies
)) {
437 struct list_head work_list
= LIST_HEAD_INIT(work_list
);
438 struct list_head
*head
= &work_list
;
439 int index
= base
->timer_jiffies
& TVR_MASK
;
445 (!cascade(base
, &base
->tv2
, INDEX(0))) &&
446 (!cascade(base
, &base
->tv3
, INDEX(1))) &&
447 !cascade(base
, &base
->tv4
, INDEX(2)))
448 cascade(base
, &base
->tv5
, INDEX(3));
449 ++base
->timer_jiffies
;
450 list_splice_init(base
->tv1
.vec
+ index
, &work_list
);
451 while (!list_empty(head
)) {
452 void (*fn
)(unsigned long);
455 timer
= list_entry(head
->next
,struct timer_list
,entry
);
456 fn
= timer
->function
;
459 set_running_timer(base
, timer
);
460 detach_timer(timer
, 1);
461 spin_unlock_irq(&base
->t_base
.lock
);
463 int preempt_count
= preempt_count();
465 if (preempt_count
!= preempt_count()) {
466 printk(KERN_WARNING
"huh, entered %p "
467 "with preempt_count %08x, exited"
474 spin_lock_irq(&base
->t_base
.lock
);
477 set_running_timer(base
, NULL
);
478 spin_unlock_irq(&base
->t_base
.lock
);
481 #ifdef CONFIG_NO_IDLE_HZ
483 * Find out when the next timer event is due to happen. This
484 * is used on S/390 to stop all activity when a cpus is idle.
485 * This functions needs to be called disabled.
487 unsigned long next_timer_interrupt(void)
490 struct list_head
*list
;
491 struct timer_list
*nte
;
492 unsigned long expires
;
493 unsigned long hr_expires
= MAX_JIFFY_OFFSET
;
498 hr_delta
= hrtimer_get_next_event();
499 if (hr_delta
.tv64
!= KTIME_MAX
) {
500 struct timespec tsdelta
;
501 tsdelta
= ktime_to_timespec(hr_delta
);
502 hr_expires
= timespec_to_jiffies(&tsdelta
);
504 return hr_expires
+ jiffies
;
506 hr_expires
+= jiffies
;
508 base
= __get_cpu_var(tvec_bases
);
509 spin_lock(&base
->t_base
.lock
);
510 expires
= base
->timer_jiffies
+ (LONG_MAX
>> 1);
513 /* Look for timer events in tv1. */
514 j
= base
->timer_jiffies
& TVR_MASK
;
516 list_for_each_entry(nte
, base
->tv1
.vec
+ j
, entry
) {
517 expires
= nte
->expires
;
518 if (j
< (base
->timer_jiffies
& TVR_MASK
))
519 list
= base
->tv2
.vec
+ (INDEX(0));
522 j
= (j
+ 1) & TVR_MASK
;
523 } while (j
!= (base
->timer_jiffies
& TVR_MASK
));
526 varray
[0] = &base
->tv2
;
527 varray
[1] = &base
->tv3
;
528 varray
[2] = &base
->tv4
;
529 varray
[3] = &base
->tv5
;
530 for (i
= 0; i
< 4; i
++) {
533 if (list_empty(varray
[i
]->vec
+ j
)) {
534 j
= (j
+ 1) & TVN_MASK
;
537 list_for_each_entry(nte
, varray
[i
]->vec
+ j
, entry
)
538 if (time_before(nte
->expires
, expires
))
539 expires
= nte
->expires
;
540 if (j
< (INDEX(i
)) && i
< 3)
541 list
= varray
[i
+ 1]->vec
+ (INDEX(i
+ 1));
543 } while (j
!= (INDEX(i
)));
548 * The search wrapped. We need to look at the next list
549 * from next tv element that would cascade into tv element
550 * where we found the timer element.
552 list_for_each_entry(nte
, list
, entry
) {
553 if (time_before(nte
->expires
, expires
))
554 expires
= nte
->expires
;
557 spin_unlock(&base
->t_base
.lock
);
559 if (time_before(hr_expires
, expires
))
566 /******************************************************************/
569 * Timekeeping variables
571 unsigned long tick_usec
= TICK_USEC
; /* USER_HZ period (usec) */
572 unsigned long tick_nsec
= TICK_NSEC
; /* ACTHZ period (nsec) */
576 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
577 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
578 * at zero at system boot time, so wall_to_monotonic will be negative,
579 * however, we will ALWAYS keep the tv_nsec part positive so we can use
580 * the usual normalization.
582 struct timespec xtime
__attribute__ ((aligned (16)));
583 struct timespec wall_to_monotonic
__attribute__ ((aligned (16)));
585 EXPORT_SYMBOL(xtime
);
587 /* Don't completely fail for HZ > 500. */
588 int tickadj
= 500/HZ
? : 1; /* microsecs */
592 * phase-lock loop variables
594 /* TIME_ERROR prevents overwriting the CMOS clock */
595 int time_state
= TIME_OK
; /* clock synchronization status */
596 int time_status
= STA_UNSYNC
; /* clock status bits */
597 long time_offset
; /* time adjustment (us) */
598 long time_constant
= 2; /* pll time constant */
599 long time_tolerance
= MAXFREQ
; /* frequency tolerance (ppm) */
600 long time_precision
= 1; /* clock precision (us) */
601 long time_maxerror
= NTP_PHASE_LIMIT
; /* maximum error (us) */
602 long time_esterror
= NTP_PHASE_LIMIT
; /* estimated error (us) */
603 static long time_phase
; /* phase offset (scaled us) */
604 long time_freq
= (((NSEC_PER_SEC
+ HZ
/2) % HZ
- HZ
/2) << SHIFT_USEC
) / NSEC_PER_USEC
;
605 /* frequency offset (scaled ppm)*/
606 static long time_adj
; /* tick adjust (scaled 1 / HZ) */
607 long time_reftime
; /* time at last adjustment (s) */
609 long time_next_adjust
;
612 * this routine handles the overflow of the microsecond field
614 * The tricky bits of code to handle the accurate clock support
615 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
616 * They were originally developed for SUN and DEC kernels.
617 * All the kudos should go to Dave for this stuff.
620 static void second_overflow(void)
624 /* Bump the maxerror field */
625 time_maxerror
+= time_tolerance
>> SHIFT_USEC
;
626 if (time_maxerror
> NTP_PHASE_LIMIT
) {
627 time_maxerror
= NTP_PHASE_LIMIT
;
628 time_status
|= STA_UNSYNC
;
632 * Leap second processing. If in leap-insert state at the end of the
633 * day, the system clock is set back one second; if in leap-delete
634 * state, the system clock is set ahead one second. The microtime()
635 * routine or external clock driver will insure that reported time is
636 * always monotonic. The ugly divides should be replaced.
638 switch (time_state
) {
640 if (time_status
& STA_INS
)
641 time_state
= TIME_INS
;
642 else if (time_status
& STA_DEL
)
643 time_state
= TIME_DEL
;
646 if (xtime
.tv_sec
% 86400 == 0) {
648 wall_to_monotonic
.tv_sec
++;
650 * The timer interpolator will make time change
651 * gradually instead of an immediate jump by one second
653 time_interpolator_update(-NSEC_PER_SEC
);
654 time_state
= TIME_OOP
;
656 printk(KERN_NOTICE
"Clock: inserting leap second "
661 if ((xtime
.tv_sec
+ 1) % 86400 == 0) {
663 wall_to_monotonic
.tv_sec
--;
665 * Use of time interpolator for a gradual change of
668 time_interpolator_update(NSEC_PER_SEC
);
669 time_state
= TIME_WAIT
;
671 printk(KERN_NOTICE
"Clock: deleting leap second "
676 time_state
= TIME_WAIT
;
679 if (!(time_status
& (STA_INS
| STA_DEL
)))
680 time_state
= TIME_OK
;
684 * Compute the phase adjustment for the next second. In PLL mode, the
685 * offset is reduced by a fixed factor times the time constant. In FLL
686 * mode the offset is used directly. In either mode, the maximum phase
687 * adjustment for each second is clamped so as to spread the adjustment
688 * over not more than the number of seconds between updates.
691 if (!(time_status
& STA_FLL
))
692 ltemp
= shift_right(ltemp
, SHIFT_KG
+ time_constant
);
693 ltemp
= min(ltemp
, (MAXPHASE
/ MINSEC
) << SHIFT_UPDATE
);
694 ltemp
= max(ltemp
, -(MAXPHASE
/ MINSEC
) << SHIFT_UPDATE
);
695 time_offset
-= ltemp
;
696 time_adj
= ltemp
<< (SHIFT_SCALE
- SHIFT_HZ
- SHIFT_UPDATE
);
699 * Compute the frequency estimate and additional phase adjustment due
700 * to frequency error for the next second. When the PPS signal is
701 * engaged, gnaw on the watchdog counter and update the frequency
702 * computed by the pll and the PPS signal.
705 if (pps_valid
== PPS_VALID
) { /* PPS signal lost */
706 pps_jitter
= MAXTIME
;
707 pps_stabil
= MAXFREQ
;
708 time_status
&= ~(STA_PPSSIGNAL
| STA_PPSJITTER
|
709 STA_PPSWANDER
| STA_PPSERROR
);
711 ltemp
= time_freq
+ pps_freq
;
712 time_adj
+= shift_right(ltemp
,(SHIFT_USEC
+ SHIFT_HZ
- SHIFT_SCALE
));
716 * Compensate for (HZ==100) != (1 << SHIFT_HZ). Add 25% and 3.125% to
717 * get 128.125; => only 0.125% error (p. 14)
719 time_adj
+= shift_right(time_adj
, 2) + shift_right(time_adj
, 5);
723 * Compensate for (HZ==250) != (1 << SHIFT_HZ). Add 1.5625% and
724 * 0.78125% to get 255.85938; => only 0.05% error (p. 14)
726 time_adj
+= shift_right(time_adj
, 6) + shift_right(time_adj
, 7);
730 * Compensate for (HZ==1000) != (1 << SHIFT_HZ). Add 1.5625% and
731 * 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
733 time_adj
+= shift_right(time_adj
, 6) + shift_right(time_adj
, 7);
738 * Returns how many microseconds we need to add to xtime this tick
739 * in doing an adjustment requested with adjtime.
741 static long adjtime_adjustment(void)
743 long time_adjust_step
;
745 time_adjust_step
= time_adjust
;
746 if (time_adjust_step
) {
748 * We are doing an adjtime thing. Prepare time_adjust_step to
749 * be within bounds. Note that a positive time_adjust means we
750 * want the clock to run faster.
752 * Limit the amount of the step to be in the range
753 * -tickadj .. +tickadj
755 time_adjust_step
= min(time_adjust_step
, (long)tickadj
);
756 time_adjust_step
= max(time_adjust_step
, (long)-tickadj
);
758 return time_adjust_step
;
761 /* in the NTP reference this is called "hardclock()" */
762 static void update_wall_time_one_tick(void)
764 long time_adjust_step
, delta_nsec
;
766 time_adjust_step
= adjtime_adjustment();
767 if (time_adjust_step
)
768 /* Reduce by this step the amount of time left */
769 time_adjust
-= time_adjust_step
;
770 delta_nsec
= tick_nsec
+ time_adjust_step
* 1000;
772 * Advance the phase, once it gets to one microsecond, then
773 * advance the tick more.
775 time_phase
+= time_adj
;
776 if ((time_phase
>= FINENSEC
) || (time_phase
<= -FINENSEC
)) {
777 long ltemp
= shift_right(time_phase
, (SHIFT_SCALE
- 10));
778 time_phase
-= ltemp
<< (SHIFT_SCALE
- 10);
781 xtime
.tv_nsec
+= delta_nsec
;
782 time_interpolator_update(delta_nsec
);
784 /* Changes by adjtime() do not take effect till next tick. */
785 if (time_next_adjust
!= 0) {
786 time_adjust
= time_next_adjust
;
787 time_next_adjust
= 0;
792 * Return how long ticks are at the moment, that is, how much time
793 * update_wall_time_one_tick will add to xtime next time we call it
794 * (assuming no calls to do_adjtimex in the meantime).
795 * The return value is in fixed-point nanoseconds with SHIFT_SCALE-10
796 * bits to the right of the binary point.
797 * This function has no side-effects.
799 u64
current_tick_length(void)
803 delta_nsec
= tick_nsec
+ adjtime_adjustment() * 1000;
804 return ((u64
) delta_nsec
<< (SHIFT_SCALE
- 10)) + time_adj
;
808 * Using a loop looks inefficient, but "ticks" is
809 * usually just one (we shouldn't be losing ticks,
810 * we're doing this this way mainly for interrupt
811 * latency reasons, not because we think we'll
812 * have lots of lost timer ticks
814 static void update_wall_time(unsigned long ticks
)
818 update_wall_time_one_tick();
819 if (xtime
.tv_nsec
>= 1000000000) {
820 xtime
.tv_nsec
-= 1000000000;
828 * Called from the timer interrupt handler to charge one tick to the current
829 * process. user_tick is 1 if the tick is user time, 0 for system.
831 void update_process_times(int user_tick
)
833 struct task_struct
*p
= current
;
834 int cpu
= smp_processor_id();
836 /* Note: this timer irq context must be accounted for as well. */
838 account_user_time(p
, jiffies_to_cputime(1));
840 account_system_time(p
, HARDIRQ_OFFSET
, jiffies_to_cputime(1));
842 if (rcu_pending(cpu
))
843 rcu_check_callbacks(cpu
, user_tick
);
845 run_posix_cpu_timers(p
);
849 * Nr of active tasks - counted in fixed-point numbers
851 static unsigned long count_active_tasks(void)
853 return (nr_running() + nr_uninterruptible()) * FIXED_1
;
857 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
858 * imply that avenrun[] is the standard name for this kind of thing.
859 * Nothing else seems to be standardized: the fractional size etc
860 * all seem to differ on different machines.
862 * Requires xtime_lock to access.
864 unsigned long avenrun
[3];
866 EXPORT_SYMBOL(avenrun
);
869 * calc_load - given tick count, update the avenrun load estimates.
870 * This is called while holding a write_lock on xtime_lock.
872 static inline void calc_load(unsigned long ticks
)
874 unsigned long active_tasks
; /* fixed-point */
875 static int count
= LOAD_FREQ
;
880 active_tasks
= count_active_tasks();
881 CALC_LOAD(avenrun
[0], EXP_1
, active_tasks
);
882 CALC_LOAD(avenrun
[1], EXP_5
, active_tasks
);
883 CALC_LOAD(avenrun
[2], EXP_15
, active_tasks
);
887 /* jiffies at the most recent update of wall time */
888 unsigned long wall_jiffies
= INITIAL_JIFFIES
;
891 * This read-write spinlock protects us from races in SMP while
892 * playing with xtime and avenrun.
894 #ifndef ARCH_HAVE_XTIME_LOCK
895 seqlock_t xtime_lock __cacheline_aligned_in_smp
= SEQLOCK_UNLOCKED
;
897 EXPORT_SYMBOL(xtime_lock
);
901 * This function runs timers and the timer-tq in bottom half context.
903 static void run_timer_softirq(struct softirq_action
*h
)
905 tvec_base_t
*base
= __get_cpu_var(tvec_bases
);
907 hrtimer_run_queues();
908 if (time_after_eq(jiffies
, base
->timer_jiffies
))
913 * Called by the local, per-CPU timer interrupt on SMP.
915 void run_local_timers(void)
917 raise_softirq(TIMER_SOFTIRQ
);
922 * Called by the timer interrupt. xtime_lock must already be taken
925 static inline void update_times(void)
929 ticks
= jiffies
- wall_jiffies
;
931 wall_jiffies
+= ticks
;
932 update_wall_time(ticks
);
938 * The 64-bit jiffies value is not atomic - you MUST NOT read it
939 * without sampling the sequence number in xtime_lock.
940 * jiffies is defined in the linker script...
943 void do_timer(struct pt_regs
*regs
)
946 /* prevent loading jiffies before storing new jiffies_64 value. */
951 #ifdef __ARCH_WANT_SYS_ALARM
954 * For backwards compatibility? This can be done in libc so Alpha
955 * and all newer ports shouldn't need it.
957 asmlinkage
unsigned long sys_alarm(unsigned int seconds
)
959 struct itimerval it_new
, it_old
;
960 unsigned int oldalarm
;
962 it_new
.it_interval
.tv_sec
= it_new
.it_interval
.tv_usec
= 0;
963 it_new
.it_value
.tv_sec
= seconds
;
964 it_new
.it_value
.tv_usec
= 0;
965 do_setitimer(ITIMER_REAL
, &it_new
, &it_old
);
966 oldalarm
= it_old
.it_value
.tv_sec
;
967 /* ehhh.. We can't return 0 if we have an alarm pending.. */
968 /* And we'd better return too much than too little anyway */
969 if ((!oldalarm
&& it_old
.it_value
.tv_usec
) || it_old
.it_value
.tv_usec
>= 500000)
979 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
980 * should be moved into arch/i386 instead?
984 * sys_getpid - return the thread group id of the current process
986 * Note, despite the name, this returns the tgid not the pid. The tgid and
987 * the pid are identical unless CLONE_THREAD was specified on clone() in
988 * which case the tgid is the same in all threads of the same group.
990 * This is SMP safe as current->tgid does not change.
992 asmlinkage
long sys_getpid(void)
994 return current
->tgid
;
998 * Accessing ->group_leader->real_parent is not SMP-safe, it could
999 * change from under us. However, rather than getting any lock
1000 * we can use an optimistic algorithm: get the parent
1001 * pid, and go back and check that the parent is still
1002 * the same. If it has changed (which is extremely unlikely
1003 * indeed), we just try again..
1005 * NOTE! This depends on the fact that even if we _do_
1006 * get an old value of "parent", we can happily dereference
1007 * the pointer (it was and remains a dereferencable kernel pointer
1008 * no matter what): we just can't necessarily trust the result
1009 * until we know that the parent pointer is valid.
1011 * NOTE2: ->group_leader never changes from under us.
1013 asmlinkage
long sys_getppid(void)
1016 struct task_struct
*me
= current
;
1017 struct task_struct
*parent
;
1019 parent
= me
->group_leader
->real_parent
;
1022 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
1024 struct task_struct
*old
= parent
;
1027 * Make sure we read the pid before re-reading the
1031 parent
= me
->group_leader
->real_parent
;
1041 asmlinkage
long sys_getuid(void)
1043 /* Only we change this so SMP safe */
1044 return current
->uid
;
1047 asmlinkage
long sys_geteuid(void)
1049 /* Only we change this so SMP safe */
1050 return current
->euid
;
1053 asmlinkage
long sys_getgid(void)
1055 /* Only we change this so SMP safe */
1056 return current
->gid
;
1059 asmlinkage
long sys_getegid(void)
1061 /* Only we change this so SMP safe */
1062 return current
->egid
;
1067 static void process_timeout(unsigned long __data
)
1069 wake_up_process((task_t
*)__data
);
1073 * schedule_timeout - sleep until timeout
1074 * @timeout: timeout value in jiffies
1076 * Make the current task sleep until @timeout jiffies have
1077 * elapsed. The routine will return immediately unless
1078 * the current task state has been set (see set_current_state()).
1080 * You can set the task state as follows -
1082 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1083 * pass before the routine returns. The routine will return 0
1085 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1086 * delivered to the current task. In this case the remaining time
1087 * in jiffies will be returned, or 0 if the timer expired in time
1089 * The current task state is guaranteed to be TASK_RUNNING when this
1092 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1093 * the CPU away without a bound on the timeout. In this case the return
1094 * value will be %MAX_SCHEDULE_TIMEOUT.
1096 * In all cases the return value is guaranteed to be non-negative.
1098 fastcall
signed long __sched
schedule_timeout(signed long timeout
)
1100 struct timer_list timer
;
1101 unsigned long expire
;
1105 case MAX_SCHEDULE_TIMEOUT
:
1107 * These two special cases are useful to be comfortable
1108 * in the caller. Nothing more. We could take
1109 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1110 * but I' d like to return a valid offset (>=0) to allow
1111 * the caller to do everything it want with the retval.
1117 * Another bit of PARANOID. Note that the retval will be
1118 * 0 since no piece of kernel is supposed to do a check
1119 * for a negative retval of schedule_timeout() (since it
1120 * should never happens anyway). You just have the printk()
1121 * that will tell you if something is gone wrong and where.
1125 printk(KERN_ERR
"schedule_timeout: wrong timeout "
1126 "value %lx from %p\n", timeout
,
1127 __builtin_return_address(0));
1128 current
->state
= TASK_RUNNING
;
1133 expire
= timeout
+ jiffies
;
1135 setup_timer(&timer
, process_timeout
, (unsigned long)current
);
1136 __mod_timer(&timer
, expire
);
1138 del_singleshot_timer_sync(&timer
);
1140 timeout
= expire
- jiffies
;
1143 return timeout
< 0 ? 0 : timeout
;
1145 EXPORT_SYMBOL(schedule_timeout
);
1148 * We can use __set_current_state() here because schedule_timeout() calls
1149 * schedule() unconditionally.
1151 signed long __sched
schedule_timeout_interruptible(signed long timeout
)
1153 __set_current_state(TASK_INTERRUPTIBLE
);
1154 return schedule_timeout(timeout
);
1156 EXPORT_SYMBOL(schedule_timeout_interruptible
);
1158 signed long __sched
schedule_timeout_uninterruptible(signed long timeout
)
1160 __set_current_state(TASK_UNINTERRUPTIBLE
);
1161 return schedule_timeout(timeout
);
1163 EXPORT_SYMBOL(schedule_timeout_uninterruptible
);
1165 /* Thread ID - the internal kernel "pid" */
1166 asmlinkage
long sys_gettid(void)
1168 return current
->pid
;
1172 * sys_sysinfo - fill in sysinfo struct
1174 asmlinkage
long sys_sysinfo(struct sysinfo __user
*info
)
1177 unsigned long mem_total
, sav_total
;
1178 unsigned int mem_unit
, bitcount
;
1181 memset((char *)&val
, 0, sizeof(struct sysinfo
));
1185 seq
= read_seqbegin(&xtime_lock
);
1188 * This is annoying. The below is the same thing
1189 * posix_get_clock_monotonic() does, but it wants to
1190 * take the lock which we want to cover the loads stuff
1194 getnstimeofday(&tp
);
1195 tp
.tv_sec
+= wall_to_monotonic
.tv_sec
;
1196 tp
.tv_nsec
+= wall_to_monotonic
.tv_nsec
;
1197 if (tp
.tv_nsec
- NSEC_PER_SEC
>= 0) {
1198 tp
.tv_nsec
= tp
.tv_nsec
- NSEC_PER_SEC
;
1201 val
.uptime
= tp
.tv_sec
+ (tp
.tv_nsec
? 1 : 0);
1203 val
.loads
[0] = avenrun
[0] << (SI_LOAD_SHIFT
- FSHIFT
);
1204 val
.loads
[1] = avenrun
[1] << (SI_LOAD_SHIFT
- FSHIFT
);
1205 val
.loads
[2] = avenrun
[2] << (SI_LOAD_SHIFT
- FSHIFT
);
1207 val
.procs
= nr_threads
;
1208 } while (read_seqretry(&xtime_lock
, seq
));
1214 * If the sum of all the available memory (i.e. ram + swap)
1215 * is less than can be stored in a 32 bit unsigned long then
1216 * we can be binary compatible with 2.2.x kernels. If not,
1217 * well, in that case 2.2.x was broken anyways...
1219 * -Erik Andersen <andersee@debian.org>
1222 mem_total
= val
.totalram
+ val
.totalswap
;
1223 if (mem_total
< val
.totalram
|| mem_total
< val
.totalswap
)
1226 mem_unit
= val
.mem_unit
;
1227 while (mem_unit
> 1) {
1230 sav_total
= mem_total
;
1232 if (mem_total
< sav_total
)
1237 * If mem_total did not overflow, multiply all memory values by
1238 * val.mem_unit and set it to 1. This leaves things compatible
1239 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1244 val
.totalram
<<= bitcount
;
1245 val
.freeram
<<= bitcount
;
1246 val
.sharedram
<<= bitcount
;
1247 val
.bufferram
<<= bitcount
;
1248 val
.totalswap
<<= bitcount
;
1249 val
.freeswap
<<= bitcount
;
1250 val
.totalhigh
<<= bitcount
;
1251 val
.freehigh
<<= bitcount
;
1254 if (copy_to_user(info
, &val
, sizeof(struct sysinfo
)))
1260 static int __devinit
init_timers_cpu(int cpu
)
1265 base
= per_cpu(tvec_bases
, cpu
);
1267 static char boot_done
;
1270 * Cannot do allocation in init_timers as that runs before the
1271 * allocator initializes (and would waste memory if there are
1272 * more possible CPUs than will ever be installed/brought up).
1275 base
= kmalloc_node(sizeof(*base
), GFP_KERNEL
,
1279 memset(base
, 0, sizeof(*base
));
1281 base
= &boot_tvec_bases
;
1284 per_cpu(tvec_bases
, cpu
) = base
;
1286 spin_lock_init(&base
->t_base
.lock
);
1287 for (j
= 0; j
< TVN_SIZE
; j
++) {
1288 INIT_LIST_HEAD(base
->tv5
.vec
+ j
);
1289 INIT_LIST_HEAD(base
->tv4
.vec
+ j
);
1290 INIT_LIST_HEAD(base
->tv3
.vec
+ j
);
1291 INIT_LIST_HEAD(base
->tv2
.vec
+ j
);
1293 for (j
= 0; j
< TVR_SIZE
; j
++)
1294 INIT_LIST_HEAD(base
->tv1
.vec
+ j
);
1296 base
->timer_jiffies
= jiffies
;
1300 #ifdef CONFIG_HOTPLUG_CPU
1301 static void migrate_timer_list(tvec_base_t
*new_base
, struct list_head
*head
)
1303 struct timer_list
*timer
;
1305 while (!list_empty(head
)) {
1306 timer
= list_entry(head
->next
, struct timer_list
, entry
);
1307 detach_timer(timer
, 0);
1308 timer
->base
= &new_base
->t_base
;
1309 internal_add_timer(new_base
, timer
);
1313 static void __devinit
migrate_timers(int cpu
)
1315 tvec_base_t
*old_base
;
1316 tvec_base_t
*new_base
;
1319 BUG_ON(cpu_online(cpu
));
1320 old_base
= per_cpu(tvec_bases
, cpu
);
1321 new_base
= get_cpu_var(tvec_bases
);
1323 local_irq_disable();
1324 spin_lock(&new_base
->t_base
.lock
);
1325 spin_lock(&old_base
->t_base
.lock
);
1327 if (old_base
->t_base
.running_timer
)
1329 for (i
= 0; i
< TVR_SIZE
; i
++)
1330 migrate_timer_list(new_base
, old_base
->tv1
.vec
+ i
);
1331 for (i
= 0; i
< TVN_SIZE
; i
++) {
1332 migrate_timer_list(new_base
, old_base
->tv2
.vec
+ i
);
1333 migrate_timer_list(new_base
, old_base
->tv3
.vec
+ i
);
1334 migrate_timer_list(new_base
, old_base
->tv4
.vec
+ i
);
1335 migrate_timer_list(new_base
, old_base
->tv5
.vec
+ i
);
1338 spin_unlock(&old_base
->t_base
.lock
);
1339 spin_unlock(&new_base
->t_base
.lock
);
1341 put_cpu_var(tvec_bases
);
1343 #endif /* CONFIG_HOTPLUG_CPU */
1345 static int __devinit
timer_cpu_notify(struct notifier_block
*self
,
1346 unsigned long action
, void *hcpu
)
1348 long cpu
= (long)hcpu
;
1350 case CPU_UP_PREPARE
:
1351 if (init_timers_cpu(cpu
) < 0)
1354 #ifdef CONFIG_HOTPLUG_CPU
1356 migrate_timers(cpu
);
1365 static struct notifier_block __devinitdata timers_nb
= {
1366 .notifier_call
= timer_cpu_notify
,
1370 void __init
init_timers(void)
1372 timer_cpu_notify(&timers_nb
, (unsigned long)CPU_UP_PREPARE
,
1373 (void *)(long)smp_processor_id());
1374 register_cpu_notifier(&timers_nb
);
1375 open_softirq(TIMER_SOFTIRQ
, run_timer_softirq
, NULL
);
1378 #ifdef CONFIG_TIME_INTERPOLATION
1380 struct time_interpolator
*time_interpolator __read_mostly
;
1381 static struct time_interpolator
*time_interpolator_list __read_mostly
;
1382 static DEFINE_SPINLOCK(time_interpolator_lock
);
1384 static inline u64
time_interpolator_get_cycles(unsigned int src
)
1386 unsigned long (*x
)(void);
1390 case TIME_SOURCE_FUNCTION
:
1391 x
= time_interpolator
->addr
;
1394 case TIME_SOURCE_MMIO64
:
1395 return readq_relaxed((void __iomem
*)time_interpolator
->addr
);
1397 case TIME_SOURCE_MMIO32
:
1398 return readl_relaxed((void __iomem
*)time_interpolator
->addr
);
1400 default: return get_cycles();
1404 static inline u64
time_interpolator_get_counter(int writelock
)
1406 unsigned int src
= time_interpolator
->source
;
1408 if (time_interpolator
->jitter
)
1414 lcycle
= time_interpolator
->last_cycle
;
1415 now
= time_interpolator_get_cycles(src
);
1416 if (lcycle
&& time_after(lcycle
, now
))
1419 /* When holding the xtime write lock, there's no need
1420 * to add the overhead of the cmpxchg. Readers are
1421 * force to retry until the write lock is released.
1424 time_interpolator
->last_cycle
= now
;
1427 /* Keep track of the last timer value returned. The use of cmpxchg here
1428 * will cause contention in an SMP environment.
1430 } while (unlikely(cmpxchg(&time_interpolator
->last_cycle
, lcycle
, now
) != lcycle
));
1434 return time_interpolator_get_cycles(src
);
1437 void time_interpolator_reset(void)
1439 time_interpolator
->offset
= 0;
1440 time_interpolator
->last_counter
= time_interpolator_get_counter(1);
1443 #define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
1445 unsigned long time_interpolator_get_offset(void)
1447 /* If we do not have a time interpolator set up then just return zero */
1448 if (!time_interpolator
)
1451 return time_interpolator
->offset
+
1452 GET_TI_NSECS(time_interpolator_get_counter(0), time_interpolator
);
1455 #define INTERPOLATOR_ADJUST 65536
1456 #define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
1458 static void time_interpolator_update(long delta_nsec
)
1461 unsigned long offset
;
1463 /* If there is no time interpolator set up then do nothing */
1464 if (!time_interpolator
)
1468 * The interpolator compensates for late ticks by accumulating the late
1469 * time in time_interpolator->offset. A tick earlier than expected will
1470 * lead to a reset of the offset and a corresponding jump of the clock
1471 * forward. Again this only works if the interpolator clock is running
1472 * slightly slower than the regular clock and the tuning logic insures
1476 counter
= time_interpolator_get_counter(1);
1477 offset
= time_interpolator
->offset
+
1478 GET_TI_NSECS(counter
, time_interpolator
);
1480 if (delta_nsec
< 0 || (unsigned long) delta_nsec
< offset
)
1481 time_interpolator
->offset
= offset
- delta_nsec
;
1483 time_interpolator
->skips
++;
1484 time_interpolator
->ns_skipped
+= delta_nsec
- offset
;
1485 time_interpolator
->offset
= 0;
1487 time_interpolator
->last_counter
= counter
;
1489 /* Tuning logic for time interpolator invoked every minute or so.
1490 * Decrease interpolator clock speed if no skips occurred and an offset is carried.
1491 * Increase interpolator clock speed if we skip too much time.
1493 if (jiffies
% INTERPOLATOR_ADJUST
== 0)
1495 if (time_interpolator
->skips
== 0 && time_interpolator
->offset
> TICK_NSEC
)
1496 time_interpolator
->nsec_per_cyc
--;
1497 if (time_interpolator
->ns_skipped
> INTERPOLATOR_MAX_SKIP
&& time_interpolator
->offset
== 0)
1498 time_interpolator
->nsec_per_cyc
++;
1499 time_interpolator
->skips
= 0;
1500 time_interpolator
->ns_skipped
= 0;
1505 is_better_time_interpolator(struct time_interpolator
*new)
1507 if (!time_interpolator
)
1509 return new->frequency
> 2*time_interpolator
->frequency
||
1510 (unsigned long)new->drift
< (unsigned long)time_interpolator
->drift
;
1514 register_time_interpolator(struct time_interpolator
*ti
)
1516 unsigned long flags
;
1519 if (ti
->frequency
== 0 || ti
->mask
== 0)
1522 ti
->nsec_per_cyc
= ((u64
)NSEC_PER_SEC
<< ti
->shift
) / ti
->frequency
;
1523 spin_lock(&time_interpolator_lock
);
1524 write_seqlock_irqsave(&xtime_lock
, flags
);
1525 if (is_better_time_interpolator(ti
)) {
1526 time_interpolator
= ti
;
1527 time_interpolator_reset();
1529 write_sequnlock_irqrestore(&xtime_lock
, flags
);
1531 ti
->next
= time_interpolator_list
;
1532 time_interpolator_list
= ti
;
1533 spin_unlock(&time_interpolator_lock
);
1537 unregister_time_interpolator(struct time_interpolator
*ti
)
1539 struct time_interpolator
*curr
, **prev
;
1540 unsigned long flags
;
1542 spin_lock(&time_interpolator_lock
);
1543 prev
= &time_interpolator_list
;
1544 for (curr
= *prev
; curr
; curr
= curr
->next
) {
1552 write_seqlock_irqsave(&xtime_lock
, flags
);
1553 if (ti
== time_interpolator
) {
1554 /* we lost the best time-interpolator: */
1555 time_interpolator
= NULL
;
1556 /* find the next-best interpolator */
1557 for (curr
= time_interpolator_list
; curr
; curr
= curr
->next
)
1558 if (is_better_time_interpolator(curr
))
1559 time_interpolator
= curr
;
1560 time_interpolator_reset();
1562 write_sequnlock_irqrestore(&xtime_lock
, flags
);
1563 spin_unlock(&time_interpolator_lock
);
1565 #endif /* CONFIG_TIME_INTERPOLATION */
1568 * msleep - sleep safely even with waitqueue interruptions
1569 * @msecs: Time in milliseconds to sleep for
1571 void msleep(unsigned int msecs
)
1573 unsigned long timeout
= msecs_to_jiffies(msecs
) + 1;
1576 timeout
= schedule_timeout_uninterruptible(timeout
);
1579 EXPORT_SYMBOL(msleep
);
1582 * msleep_interruptible - sleep waiting for signals
1583 * @msecs: Time in milliseconds to sleep for
1585 unsigned long msleep_interruptible(unsigned int msecs
)
1587 unsigned long timeout
= msecs_to_jiffies(msecs
) + 1;
1589 while (timeout
&& !signal_pending(current
))
1590 timeout
= schedule_timeout_interruptible(timeout
);
1591 return jiffies_to_msecs(timeout
);
1594 EXPORT_SYMBOL(msleep_interruptible
);