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
);
91 static inline void set_running_timer(tvec_base_t
*base
,
92 struct timer_list
*timer
)
95 base
->t_base
.running_timer
= timer
;
99 static void internal_add_timer(tvec_base_t
*base
, struct timer_list
*timer
)
101 unsigned long expires
= timer
->expires
;
102 unsigned long idx
= expires
- base
->timer_jiffies
;
103 struct list_head
*vec
;
105 if (idx
< TVR_SIZE
) {
106 int i
= expires
& TVR_MASK
;
107 vec
= base
->tv1
.vec
+ i
;
108 } else if (idx
< 1 << (TVR_BITS
+ TVN_BITS
)) {
109 int i
= (expires
>> TVR_BITS
) & TVN_MASK
;
110 vec
= base
->tv2
.vec
+ i
;
111 } else if (idx
< 1 << (TVR_BITS
+ 2 * TVN_BITS
)) {
112 int i
= (expires
>> (TVR_BITS
+ TVN_BITS
)) & TVN_MASK
;
113 vec
= base
->tv3
.vec
+ i
;
114 } else if (idx
< 1 << (TVR_BITS
+ 3 * TVN_BITS
)) {
115 int i
= (expires
>> (TVR_BITS
+ 2 * TVN_BITS
)) & TVN_MASK
;
116 vec
= base
->tv4
.vec
+ i
;
117 } else if ((signed long) idx
< 0) {
119 * Can happen if you add a timer with expires == jiffies,
120 * or you set a timer to go off in the past
122 vec
= base
->tv1
.vec
+ (base
->timer_jiffies
& TVR_MASK
);
125 /* If the timeout is larger than 0xffffffff on 64-bit
126 * architectures then we use the maximum timeout:
128 if (idx
> 0xffffffffUL
) {
130 expires
= idx
+ base
->timer_jiffies
;
132 i
= (expires
>> (TVR_BITS
+ 3 * TVN_BITS
)) & TVN_MASK
;
133 vec
= base
->tv5
.vec
+ i
;
138 list_add_tail(&timer
->entry
, vec
);
141 typedef struct timer_base_s timer_base_t
;
143 * Used by TIMER_INITIALIZER, we can't use per_cpu(tvec_bases)
144 * at compile time, and we need timer->base to lock the timer.
146 timer_base_t __init_timer_base
147 ____cacheline_aligned_in_smp
= { .lock
= SPIN_LOCK_UNLOCKED
};
148 EXPORT_SYMBOL(__init_timer_base
);
151 * init_timer - initialize a timer.
152 * @timer: the timer to be initialized
154 * init_timer() must be done to a timer prior calling *any* of the
155 * other timer functions.
157 void fastcall
init_timer(struct timer_list
*timer
)
159 timer
->entry
.next
= NULL
;
160 timer
->base
= &per_cpu(tvec_bases
, raw_smp_processor_id()).t_base
;
162 EXPORT_SYMBOL(init_timer
);
164 static inline void detach_timer(struct timer_list
*timer
,
167 struct list_head
*entry
= &timer
->entry
;
169 __list_del(entry
->prev
, entry
->next
);
172 entry
->prev
= LIST_POISON2
;
176 * We are using hashed locking: holding per_cpu(tvec_bases).t_base.lock
177 * means that all timers which are tied to this base via timer->base are
178 * locked, and the base itself is locked too.
180 * So __run_timers/migrate_timers can safely modify all timers which could
181 * be found on ->tvX lists.
183 * When the timer's base is locked, and the timer removed from list, it is
184 * possible to set timer->base = NULL and drop the lock: the timer remains
187 static timer_base_t
*lock_timer_base(struct timer_list
*timer
,
188 unsigned long *flags
)
194 if (likely(base
!= NULL
)) {
195 spin_lock_irqsave(&base
->lock
, *flags
);
196 if (likely(base
== timer
->base
))
198 /* The timer has migrated to another CPU */
199 spin_unlock_irqrestore(&base
->lock
, *flags
);
205 int __mod_timer(struct timer_list
*timer
, unsigned long expires
)
208 tvec_base_t
*new_base
;
212 BUG_ON(!timer
->function
);
214 base
= lock_timer_base(timer
, &flags
);
216 if (timer_pending(timer
)) {
217 detach_timer(timer
, 0);
221 new_base
= &__get_cpu_var(tvec_bases
);
223 if (base
!= &new_base
->t_base
) {
225 * We are trying to schedule the timer on the local CPU.
226 * However we can't change timer's base while it is running,
227 * otherwise del_timer_sync() can't detect that the timer's
228 * handler yet has not finished. This also guarantees that
229 * the timer is serialized wrt itself.
231 if (unlikely(base
->running_timer
== timer
)) {
232 /* The timer remains on a former base */
233 new_base
= container_of(base
, tvec_base_t
, t_base
);
235 /* See the comment in lock_timer_base() */
237 spin_unlock(&base
->lock
);
238 spin_lock(&new_base
->t_base
.lock
);
239 timer
->base
= &new_base
->t_base
;
243 timer
->expires
= expires
;
244 internal_add_timer(new_base
, timer
);
245 spin_unlock_irqrestore(&new_base
->t_base
.lock
, flags
);
250 EXPORT_SYMBOL(__mod_timer
);
253 * add_timer_on - start a timer on a particular CPU
254 * @timer: the timer to be added
255 * @cpu: the CPU to start it on
257 * This is not very scalable on SMP. Double adds are not possible.
259 void add_timer_on(struct timer_list
*timer
, int cpu
)
261 tvec_base_t
*base
= &per_cpu(tvec_bases
, cpu
);
264 BUG_ON(timer_pending(timer
) || !timer
->function
);
265 spin_lock_irqsave(&base
->t_base
.lock
, flags
);
266 timer
->base
= &base
->t_base
;
267 internal_add_timer(base
, timer
);
268 spin_unlock_irqrestore(&base
->t_base
.lock
, flags
);
273 * mod_timer - modify a timer's timeout
274 * @timer: the timer to be modified
276 * mod_timer is a more efficient way to update the expire field of an
277 * active timer (if the timer is inactive it will be activated)
279 * mod_timer(timer, expires) is equivalent to:
281 * del_timer(timer); timer->expires = expires; add_timer(timer);
283 * Note that if there are multiple unserialized concurrent users of the
284 * same timer, then mod_timer() is the only safe way to modify the timeout,
285 * since add_timer() cannot modify an already running timer.
287 * The function returns whether it has modified a pending timer or not.
288 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
289 * active timer returns 1.)
291 int mod_timer(struct timer_list
*timer
, unsigned long expires
)
293 BUG_ON(!timer
->function
);
296 * This is a common optimization triggered by the
297 * networking code - if the timer is re-modified
298 * to be the same thing then just return:
300 if (timer
->expires
== expires
&& timer_pending(timer
))
303 return __mod_timer(timer
, expires
);
306 EXPORT_SYMBOL(mod_timer
);
309 * del_timer - deactive a timer.
310 * @timer: the timer to be deactivated
312 * del_timer() deactivates a timer - this works on both active and inactive
315 * The function returns whether it has deactivated a pending timer or not.
316 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
317 * active timer returns 1.)
319 int del_timer(struct timer_list
*timer
)
325 if (timer_pending(timer
)) {
326 base
= lock_timer_base(timer
, &flags
);
327 if (timer_pending(timer
)) {
328 detach_timer(timer
, 1);
331 spin_unlock_irqrestore(&base
->lock
, flags
);
337 EXPORT_SYMBOL(del_timer
);
341 * This function tries to deactivate a timer. Upon successful (ret >= 0)
342 * exit the timer is not queued and the handler is not running on any CPU.
344 * It must not be called from interrupt contexts.
346 int try_to_del_timer_sync(struct timer_list
*timer
)
352 base
= lock_timer_base(timer
, &flags
);
354 if (base
->running_timer
== timer
)
358 if (timer_pending(timer
)) {
359 detach_timer(timer
, 1);
363 spin_unlock_irqrestore(&base
->lock
, flags
);
369 * del_timer_sync - deactivate a timer and wait for the handler to finish.
370 * @timer: the timer to be deactivated
372 * This function only differs from del_timer() on SMP: besides deactivating
373 * the timer it also makes sure the handler has finished executing on other
376 * Synchronization rules: callers must prevent restarting of the timer,
377 * otherwise this function is meaningless. It must not be called from
378 * interrupt contexts. The caller must not hold locks which would prevent
379 * completion of the timer's handler. The timer's handler must not call
380 * add_timer_on(). Upon exit the timer is not queued and the handler is
381 * not running on any CPU.
383 * The function returns whether it has deactivated a pending timer or not.
385 int del_timer_sync(struct timer_list
*timer
)
388 int ret
= try_to_del_timer_sync(timer
);
394 EXPORT_SYMBOL(del_timer_sync
);
397 static int cascade(tvec_base_t
*base
, tvec_t
*tv
, int index
)
399 /* cascade all the timers from tv up one level */
400 struct list_head
*head
, *curr
;
402 head
= tv
->vec
+ index
;
405 * We are removing _all_ timers from the list, so we don't have to
406 * detach them individually, just clear the list afterwards.
408 while (curr
!= head
) {
409 struct timer_list
*tmp
;
411 tmp
= list_entry(curr
, struct timer_list
, entry
);
412 BUG_ON(tmp
->base
!= &base
->t_base
);
414 internal_add_timer(base
, tmp
);
416 INIT_LIST_HEAD(head
);
422 * __run_timers - run all expired timers (if any) on this CPU.
423 * @base: the timer vector to be processed.
425 * This function cascades all vectors and executes all expired timer
428 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
430 static inline void __run_timers(tvec_base_t
*base
)
432 struct timer_list
*timer
;
434 spin_lock_irq(&base
->t_base
.lock
);
435 while (time_after_eq(jiffies
, base
->timer_jiffies
)) {
436 struct list_head work_list
= LIST_HEAD_INIT(work_list
);
437 struct list_head
*head
= &work_list
;
438 int index
= base
->timer_jiffies
& TVR_MASK
;
444 (!cascade(base
, &base
->tv2
, INDEX(0))) &&
445 (!cascade(base
, &base
->tv3
, INDEX(1))) &&
446 !cascade(base
, &base
->tv4
, INDEX(2)))
447 cascade(base
, &base
->tv5
, INDEX(3));
448 ++base
->timer_jiffies
;
449 list_splice_init(base
->tv1
.vec
+ index
, &work_list
);
450 while (!list_empty(head
)) {
451 void (*fn
)(unsigned long);
454 timer
= list_entry(head
->next
,struct timer_list
,entry
);
455 fn
= timer
->function
;
458 set_running_timer(base
, timer
);
459 detach_timer(timer
, 1);
460 spin_unlock_irq(&base
->t_base
.lock
);
462 int preempt_count
= preempt_count();
464 if (preempt_count
!= preempt_count()) {
465 printk(KERN_WARNING
"huh, entered %p "
466 "with preempt_count %08x, exited"
473 spin_lock_irq(&base
->t_base
.lock
);
476 set_running_timer(base
, NULL
);
477 spin_unlock_irq(&base
->t_base
.lock
);
480 #ifdef CONFIG_NO_IDLE_HZ
482 * Find out when the next timer event is due to happen. This
483 * is used on S/390 to stop all activity when a cpus is idle.
484 * This functions needs to be called disabled.
486 unsigned long next_timer_interrupt(void)
489 struct list_head
*list
;
490 struct timer_list
*nte
;
491 unsigned long expires
;
495 base
= &__get_cpu_var(tvec_bases
);
496 spin_lock(&base
->t_base
.lock
);
497 expires
= base
->timer_jiffies
+ (LONG_MAX
>> 1);
500 /* Look for timer events in tv1. */
501 j
= base
->timer_jiffies
& TVR_MASK
;
503 list_for_each_entry(nte
, base
->tv1
.vec
+ j
, entry
) {
504 expires
= nte
->expires
;
505 if (j
< (base
->timer_jiffies
& TVR_MASK
))
506 list
= base
->tv2
.vec
+ (INDEX(0));
509 j
= (j
+ 1) & TVR_MASK
;
510 } while (j
!= (base
->timer_jiffies
& TVR_MASK
));
513 varray
[0] = &base
->tv2
;
514 varray
[1] = &base
->tv3
;
515 varray
[2] = &base
->tv4
;
516 varray
[3] = &base
->tv5
;
517 for (i
= 0; i
< 4; i
++) {
520 if (list_empty(varray
[i
]->vec
+ j
)) {
521 j
= (j
+ 1) & TVN_MASK
;
524 list_for_each_entry(nte
, varray
[i
]->vec
+ j
, entry
)
525 if (time_before(nte
->expires
, expires
))
526 expires
= nte
->expires
;
527 if (j
< (INDEX(i
)) && i
< 3)
528 list
= varray
[i
+ 1]->vec
+ (INDEX(i
+ 1));
530 } while (j
!= (INDEX(i
)));
535 * The search wrapped. We need to look at the next list
536 * from next tv element that would cascade into tv element
537 * where we found the timer element.
539 list_for_each_entry(nte
, list
, entry
) {
540 if (time_before(nte
->expires
, expires
))
541 expires
= nte
->expires
;
544 spin_unlock(&base
->t_base
.lock
);
549 /******************************************************************/
552 * Timekeeping variables
554 unsigned long tick_usec
= TICK_USEC
; /* USER_HZ period (usec) */
555 unsigned long tick_nsec
= TICK_NSEC
; /* ACTHZ period (nsec) */
559 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
560 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
561 * at zero at system boot time, so wall_to_monotonic will be negative,
562 * however, we will ALWAYS keep the tv_nsec part positive so we can use
563 * the usual normalization.
565 struct timespec xtime
__attribute__ ((aligned (16)));
566 struct timespec wall_to_monotonic
__attribute__ ((aligned (16)));
568 EXPORT_SYMBOL(xtime
);
570 /* Don't completely fail for HZ > 500. */
571 int tickadj
= 500/HZ
? : 1; /* microsecs */
575 * phase-lock loop variables
577 /* TIME_ERROR prevents overwriting the CMOS clock */
578 int time_state
= TIME_OK
; /* clock synchronization status */
579 int time_status
= STA_UNSYNC
; /* clock status bits */
580 long time_offset
; /* time adjustment (us) */
581 long time_constant
= 2; /* pll time constant */
582 long time_tolerance
= MAXFREQ
; /* frequency tolerance (ppm) */
583 long time_precision
= 1; /* clock precision (us) */
584 long time_maxerror
= NTP_PHASE_LIMIT
; /* maximum error (us) */
585 long time_esterror
= NTP_PHASE_LIMIT
; /* estimated error (us) */
586 static long time_phase
; /* phase offset (scaled us) */
587 long time_freq
= (((NSEC_PER_SEC
+ HZ
/2) % HZ
- HZ
/2) << SHIFT_USEC
) / NSEC_PER_USEC
;
588 /* frequency offset (scaled ppm)*/
589 static long time_adj
; /* tick adjust (scaled 1 / HZ) */
590 long time_reftime
; /* time at last adjustment (s) */
592 long time_next_adjust
;
595 * this routine handles the overflow of the microsecond field
597 * The tricky bits of code to handle the accurate clock support
598 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
599 * They were originally developed for SUN and DEC kernels.
600 * All the kudos should go to Dave for this stuff.
603 static void second_overflow(void)
607 /* Bump the maxerror field */
608 time_maxerror
+= time_tolerance
>> SHIFT_USEC
;
609 if (time_maxerror
> NTP_PHASE_LIMIT
) {
610 time_maxerror
= NTP_PHASE_LIMIT
;
611 time_status
|= STA_UNSYNC
;
615 * Leap second processing. If in leap-insert state at the end of the
616 * day, the system clock is set back one second; if in leap-delete
617 * state, the system clock is set ahead one second. The microtime()
618 * routine or external clock driver will insure that reported time is
619 * always monotonic. The ugly divides should be replaced.
621 switch (time_state
) {
623 if (time_status
& STA_INS
)
624 time_state
= TIME_INS
;
625 else if (time_status
& STA_DEL
)
626 time_state
= TIME_DEL
;
629 if (xtime
.tv_sec
% 86400 == 0) {
631 wall_to_monotonic
.tv_sec
++;
633 * The timer interpolator will make time change
634 * gradually instead of an immediate jump by one second
636 time_interpolator_update(-NSEC_PER_SEC
);
637 time_state
= TIME_OOP
;
639 printk(KERN_NOTICE
"Clock: inserting leap second "
644 if ((xtime
.tv_sec
+ 1) % 86400 == 0) {
646 wall_to_monotonic
.tv_sec
--;
648 * Use of time interpolator for a gradual change of
651 time_interpolator_update(NSEC_PER_SEC
);
652 time_state
= TIME_WAIT
;
654 printk(KERN_NOTICE
"Clock: deleting leap second "
659 time_state
= TIME_WAIT
;
662 if (!(time_status
& (STA_INS
| STA_DEL
)))
663 time_state
= TIME_OK
;
667 * Compute the phase adjustment for the next second. In PLL mode, the
668 * offset is reduced by a fixed factor times the time constant. In FLL
669 * mode the offset is used directly. In either mode, the maximum phase
670 * adjustment for each second is clamped so as to spread the adjustment
671 * over not more than the number of seconds between updates.
674 if (!(time_status
& STA_FLL
))
675 ltemp
= shift_right(ltemp
, SHIFT_KG
+ time_constant
);
676 ltemp
= min(ltemp
, (MAXPHASE
/ MINSEC
) << SHIFT_UPDATE
);
677 ltemp
= max(ltemp
, -(MAXPHASE
/ MINSEC
) << SHIFT_UPDATE
);
678 time_offset
-= ltemp
;
679 time_adj
= ltemp
<< (SHIFT_SCALE
- SHIFT_HZ
- SHIFT_UPDATE
);
682 * Compute the frequency estimate and additional phase adjustment due
683 * to frequency error for the next second. When the PPS signal is
684 * engaged, gnaw on the watchdog counter and update the frequency
685 * computed by the pll and the PPS signal.
688 if (pps_valid
== PPS_VALID
) { /* PPS signal lost */
689 pps_jitter
= MAXTIME
;
690 pps_stabil
= MAXFREQ
;
691 time_status
&= ~(STA_PPSSIGNAL
| STA_PPSJITTER
|
692 STA_PPSWANDER
| STA_PPSERROR
);
694 ltemp
= time_freq
+ pps_freq
;
695 time_adj
+= shift_right(ltemp
,(SHIFT_USEC
+ SHIFT_HZ
- SHIFT_SCALE
));
699 * Compensate for (HZ==100) != (1 << SHIFT_HZ). Add 25% and 3.125% to
700 * get 128.125; => only 0.125% error (p. 14)
702 time_adj
+= shift_right(time_adj
, 2) + shift_right(time_adj
, 5);
706 * Compensate for (HZ==250) != (1 << SHIFT_HZ). Add 1.5625% and
707 * 0.78125% to get 255.85938; => only 0.05% error (p. 14)
709 time_adj
+= shift_right(time_adj
, 6) + shift_right(time_adj
, 7);
713 * Compensate for (HZ==1000) != (1 << SHIFT_HZ). Add 1.5625% and
714 * 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
716 time_adj
+= shift_right(time_adj
, 6) + shift_right(time_adj
, 7);
720 /* in the NTP reference this is called "hardclock()" */
721 static void update_wall_time_one_tick(void)
723 long time_adjust_step
, delta_nsec
;
725 if ((time_adjust_step
= time_adjust
) != 0 ) {
727 * We are doing an adjtime thing. Prepare time_adjust_step to
728 * be within bounds. Note that a positive time_adjust means we
729 * want the clock to run faster.
731 * Limit the amount of the step to be in the range
732 * -tickadj .. +tickadj
734 time_adjust_step
= min(time_adjust_step
, (long)tickadj
);
735 time_adjust_step
= max(time_adjust_step
, (long)-tickadj
);
737 /* Reduce by this step the amount of time left */
738 time_adjust
-= time_adjust_step
;
740 delta_nsec
= tick_nsec
+ time_adjust_step
* 1000;
742 * Advance the phase, once it gets to one microsecond, then
743 * advance the tick more.
745 time_phase
+= time_adj
;
746 if ((time_phase
>= FINENSEC
) || (time_phase
<= -FINENSEC
)) {
747 long ltemp
= shift_right(time_phase
, (SHIFT_SCALE
- 10));
748 time_phase
-= ltemp
<< (SHIFT_SCALE
- 10);
751 xtime
.tv_nsec
+= delta_nsec
;
752 time_interpolator_update(delta_nsec
);
754 /* Changes by adjtime() do not take effect till next tick. */
755 if (time_next_adjust
!= 0) {
756 time_adjust
= time_next_adjust
;
757 time_next_adjust
= 0;
762 * Using a loop looks inefficient, but "ticks" is
763 * usually just one (we shouldn't be losing ticks,
764 * we're doing this this way mainly for interrupt
765 * latency reasons, not because we think we'll
766 * have lots of lost timer ticks
768 static void update_wall_time(unsigned long ticks
)
772 update_wall_time_one_tick();
773 if (xtime
.tv_nsec
>= 1000000000) {
774 xtime
.tv_nsec
-= 1000000000;
782 * Called from the timer interrupt handler to charge one tick to the current
783 * process. user_tick is 1 if the tick is user time, 0 for system.
785 void update_process_times(int user_tick
)
787 struct task_struct
*p
= current
;
788 int cpu
= smp_processor_id();
790 /* Note: this timer irq context must be accounted for as well. */
792 account_user_time(p
, jiffies_to_cputime(1));
794 account_system_time(p
, HARDIRQ_OFFSET
, jiffies_to_cputime(1));
796 if (rcu_pending(cpu
))
797 rcu_check_callbacks(cpu
, user_tick
);
799 run_posix_cpu_timers(p
);
803 * Nr of active tasks - counted in fixed-point numbers
805 static unsigned long count_active_tasks(void)
807 return (nr_running() + nr_uninterruptible()) * FIXED_1
;
811 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
812 * imply that avenrun[] is the standard name for this kind of thing.
813 * Nothing else seems to be standardized: the fractional size etc
814 * all seem to differ on different machines.
816 * Requires xtime_lock to access.
818 unsigned long avenrun
[3];
820 EXPORT_SYMBOL(avenrun
);
823 * calc_load - given tick count, update the avenrun load estimates.
824 * This is called while holding a write_lock on xtime_lock.
826 static inline void calc_load(unsigned long ticks
)
828 unsigned long active_tasks
; /* fixed-point */
829 static int count
= LOAD_FREQ
;
834 active_tasks
= count_active_tasks();
835 CALC_LOAD(avenrun
[0], EXP_1
, active_tasks
);
836 CALC_LOAD(avenrun
[1], EXP_5
, active_tasks
);
837 CALC_LOAD(avenrun
[2], EXP_15
, active_tasks
);
841 /* jiffies at the most recent update of wall time */
842 unsigned long wall_jiffies
= INITIAL_JIFFIES
;
845 * This read-write spinlock protects us from races in SMP while
846 * playing with xtime and avenrun.
848 #ifndef ARCH_HAVE_XTIME_LOCK
849 seqlock_t xtime_lock __cacheline_aligned_in_smp
= SEQLOCK_UNLOCKED
;
851 EXPORT_SYMBOL(xtime_lock
);
855 * This function runs timers and the timer-tq in bottom half context.
857 static void run_timer_softirq(struct softirq_action
*h
)
859 tvec_base_t
*base
= &__get_cpu_var(tvec_bases
);
861 if (time_after_eq(jiffies
, base
->timer_jiffies
))
866 * Called by the local, per-CPU timer interrupt on SMP.
868 void run_local_timers(void)
870 raise_softirq(TIMER_SOFTIRQ
);
874 * Called by the timer interrupt. xtime_lock must already be taken
877 static inline void update_times(void)
881 ticks
= jiffies
- wall_jiffies
;
883 wall_jiffies
+= ticks
;
884 update_wall_time(ticks
);
890 * The 64-bit jiffies value is not atomic - you MUST NOT read it
891 * without sampling the sequence number in xtime_lock.
892 * jiffies is defined in the linker script...
895 void do_timer(struct pt_regs
*regs
)
899 softlockup_tick(regs
);
902 #ifdef __ARCH_WANT_SYS_ALARM
905 * For backwards compatibility? This can be done in libc so Alpha
906 * and all newer ports shouldn't need it.
908 asmlinkage
unsigned long sys_alarm(unsigned int seconds
)
910 struct itimerval it_new
, it_old
;
911 unsigned int oldalarm
;
913 it_new
.it_interval
.tv_sec
= it_new
.it_interval
.tv_usec
= 0;
914 it_new
.it_value
.tv_sec
= seconds
;
915 it_new
.it_value
.tv_usec
= 0;
916 do_setitimer(ITIMER_REAL
, &it_new
, &it_old
);
917 oldalarm
= it_old
.it_value
.tv_sec
;
918 /* ehhh.. We can't return 0 if we have an alarm pending.. */
919 /* And we'd better return too much than too little anyway */
920 if ((!oldalarm
&& it_old
.it_value
.tv_usec
) || it_old
.it_value
.tv_usec
>= 500000)
930 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
931 * should be moved into arch/i386 instead?
935 * sys_getpid - return the thread group id of the current process
937 * Note, despite the name, this returns the tgid not the pid. The tgid and
938 * the pid are identical unless CLONE_THREAD was specified on clone() in
939 * which case the tgid is the same in all threads of the same group.
941 * This is SMP safe as current->tgid does not change.
943 asmlinkage
long sys_getpid(void)
945 return current
->tgid
;
949 * Accessing ->group_leader->real_parent is not SMP-safe, it could
950 * change from under us. However, rather than getting any lock
951 * we can use an optimistic algorithm: get the parent
952 * pid, and go back and check that the parent is still
953 * the same. If it has changed (which is extremely unlikely
954 * indeed), we just try again..
956 * NOTE! This depends on the fact that even if we _do_
957 * get an old value of "parent", we can happily dereference
958 * the pointer (it was and remains a dereferencable kernel pointer
959 * no matter what): we just can't necessarily trust the result
960 * until we know that the parent pointer is valid.
962 * NOTE2: ->group_leader never changes from under us.
964 asmlinkage
long sys_getppid(void)
967 struct task_struct
*me
= current
;
968 struct task_struct
*parent
;
970 parent
= me
->group_leader
->real_parent
;
973 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
975 struct task_struct
*old
= parent
;
978 * Make sure we read the pid before re-reading the
982 parent
= me
->group_leader
->real_parent
;
992 asmlinkage
long sys_getuid(void)
994 /* Only we change this so SMP safe */
998 asmlinkage
long sys_geteuid(void)
1000 /* Only we change this so SMP safe */
1001 return current
->euid
;
1004 asmlinkage
long sys_getgid(void)
1006 /* Only we change this so SMP safe */
1007 return current
->gid
;
1010 asmlinkage
long sys_getegid(void)
1012 /* Only we change this so SMP safe */
1013 return current
->egid
;
1018 static void process_timeout(unsigned long __data
)
1020 wake_up_process((task_t
*)__data
);
1024 * schedule_timeout - sleep until timeout
1025 * @timeout: timeout value in jiffies
1027 * Make the current task sleep until @timeout jiffies have
1028 * elapsed. The routine will return immediately unless
1029 * the current task state has been set (see set_current_state()).
1031 * You can set the task state as follows -
1033 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1034 * pass before the routine returns. The routine will return 0
1036 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1037 * delivered to the current task. In this case the remaining time
1038 * in jiffies will be returned, or 0 if the timer expired in time
1040 * The current task state is guaranteed to be TASK_RUNNING when this
1043 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1044 * the CPU away without a bound on the timeout. In this case the return
1045 * value will be %MAX_SCHEDULE_TIMEOUT.
1047 * In all cases the return value is guaranteed to be non-negative.
1049 fastcall
signed long __sched
schedule_timeout(signed long timeout
)
1051 struct timer_list timer
;
1052 unsigned long expire
;
1056 case MAX_SCHEDULE_TIMEOUT
:
1058 * These two special cases are useful to be comfortable
1059 * in the caller. Nothing more. We could take
1060 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1061 * but I' d like to return a valid offset (>=0) to allow
1062 * the caller to do everything it want with the retval.
1068 * Another bit of PARANOID. Note that the retval will be
1069 * 0 since no piece of kernel is supposed to do a check
1070 * for a negative retval of schedule_timeout() (since it
1071 * should never happens anyway). You just have the printk()
1072 * that will tell you if something is gone wrong and where.
1076 printk(KERN_ERR
"schedule_timeout: wrong timeout "
1077 "value %lx from %p\n", timeout
,
1078 __builtin_return_address(0));
1079 current
->state
= TASK_RUNNING
;
1084 expire
= timeout
+ jiffies
;
1086 setup_timer(&timer
, process_timeout
, (unsigned long)current
);
1087 __mod_timer(&timer
, expire
);
1089 del_singleshot_timer_sync(&timer
);
1091 timeout
= expire
- jiffies
;
1094 return timeout
< 0 ? 0 : timeout
;
1096 EXPORT_SYMBOL(schedule_timeout
);
1099 * We can use __set_current_state() here because schedule_timeout() calls
1100 * schedule() unconditionally.
1102 signed long __sched
schedule_timeout_interruptible(signed long timeout
)
1104 __set_current_state(TASK_INTERRUPTIBLE
);
1105 return schedule_timeout(timeout
);
1107 EXPORT_SYMBOL(schedule_timeout_interruptible
);
1109 signed long __sched
schedule_timeout_uninterruptible(signed long timeout
)
1111 __set_current_state(TASK_UNINTERRUPTIBLE
);
1112 return schedule_timeout(timeout
);
1114 EXPORT_SYMBOL(schedule_timeout_uninterruptible
);
1116 /* Thread ID - the internal kernel "pid" */
1117 asmlinkage
long sys_gettid(void)
1119 return current
->pid
;
1122 static long __sched
nanosleep_restart(struct restart_block
*restart
)
1124 unsigned long expire
= restart
->arg0
, now
= jiffies
;
1125 struct timespec __user
*rmtp
= (struct timespec __user
*) restart
->arg1
;
1128 /* Did it expire while we handled signals? */
1129 if (!time_after(expire
, now
))
1132 expire
= schedule_timeout_interruptible(expire
- now
);
1137 jiffies_to_timespec(expire
, &t
);
1139 ret
= -ERESTART_RESTARTBLOCK
;
1140 if (rmtp
&& copy_to_user(rmtp
, &t
, sizeof(t
)))
1142 /* The 'restart' block is already filled in */
1147 asmlinkage
long sys_nanosleep(struct timespec __user
*rqtp
, struct timespec __user
*rmtp
)
1150 unsigned long expire
;
1153 if (copy_from_user(&t
, rqtp
, sizeof(t
)))
1156 if ((t
.tv_nsec
>= 1000000000L) || (t
.tv_nsec
< 0) || (t
.tv_sec
< 0))
1159 expire
= timespec_to_jiffies(&t
) + (t
.tv_sec
|| t
.tv_nsec
);
1160 expire
= schedule_timeout_interruptible(expire
);
1164 struct restart_block
*restart
;
1165 jiffies_to_timespec(expire
, &t
);
1166 if (rmtp
&& copy_to_user(rmtp
, &t
, sizeof(t
)))
1169 restart
= ¤t_thread_info()->restart_block
;
1170 restart
->fn
= nanosleep_restart
;
1171 restart
->arg0
= jiffies
+ expire
;
1172 restart
->arg1
= (unsigned long) rmtp
;
1173 ret
= -ERESTART_RESTARTBLOCK
;
1179 * sys_sysinfo - fill in sysinfo struct
1181 asmlinkage
long sys_sysinfo(struct sysinfo __user
*info
)
1184 unsigned long mem_total
, sav_total
;
1185 unsigned int mem_unit
, bitcount
;
1188 memset((char *)&val
, 0, sizeof(struct sysinfo
));
1192 seq
= read_seqbegin(&xtime_lock
);
1195 * This is annoying. The below is the same thing
1196 * posix_get_clock_monotonic() does, but it wants to
1197 * take the lock which we want to cover the loads stuff
1201 getnstimeofday(&tp
);
1202 tp
.tv_sec
+= wall_to_monotonic
.tv_sec
;
1203 tp
.tv_nsec
+= wall_to_monotonic
.tv_nsec
;
1204 if (tp
.tv_nsec
- NSEC_PER_SEC
>= 0) {
1205 tp
.tv_nsec
= tp
.tv_nsec
- NSEC_PER_SEC
;
1208 val
.uptime
= tp
.tv_sec
+ (tp
.tv_nsec
? 1 : 0);
1210 val
.loads
[0] = avenrun
[0] << (SI_LOAD_SHIFT
- FSHIFT
);
1211 val
.loads
[1] = avenrun
[1] << (SI_LOAD_SHIFT
- FSHIFT
);
1212 val
.loads
[2] = avenrun
[2] << (SI_LOAD_SHIFT
- FSHIFT
);
1214 val
.procs
= nr_threads
;
1215 } while (read_seqretry(&xtime_lock
, seq
));
1221 * If the sum of all the available memory (i.e. ram + swap)
1222 * is less than can be stored in a 32 bit unsigned long then
1223 * we can be binary compatible with 2.2.x kernels. If not,
1224 * well, in that case 2.2.x was broken anyways...
1226 * -Erik Andersen <andersee@debian.org>
1229 mem_total
= val
.totalram
+ val
.totalswap
;
1230 if (mem_total
< val
.totalram
|| mem_total
< val
.totalswap
)
1233 mem_unit
= val
.mem_unit
;
1234 while (mem_unit
> 1) {
1237 sav_total
= mem_total
;
1239 if (mem_total
< sav_total
)
1244 * If mem_total did not overflow, multiply all memory values by
1245 * val.mem_unit and set it to 1. This leaves things compatible
1246 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1251 val
.totalram
<<= bitcount
;
1252 val
.freeram
<<= bitcount
;
1253 val
.sharedram
<<= bitcount
;
1254 val
.bufferram
<<= bitcount
;
1255 val
.totalswap
<<= bitcount
;
1256 val
.freeswap
<<= bitcount
;
1257 val
.totalhigh
<<= bitcount
;
1258 val
.freehigh
<<= bitcount
;
1261 if (copy_to_user(info
, &val
, sizeof(struct sysinfo
)))
1267 static void __devinit
init_timers_cpu(int cpu
)
1272 base
= &per_cpu(tvec_bases
, cpu
);
1273 spin_lock_init(&base
->t_base
.lock
);
1274 for (j
= 0; j
< TVN_SIZE
; j
++) {
1275 INIT_LIST_HEAD(base
->tv5
.vec
+ j
);
1276 INIT_LIST_HEAD(base
->tv4
.vec
+ j
);
1277 INIT_LIST_HEAD(base
->tv3
.vec
+ j
);
1278 INIT_LIST_HEAD(base
->tv2
.vec
+ j
);
1280 for (j
= 0; j
< TVR_SIZE
; j
++)
1281 INIT_LIST_HEAD(base
->tv1
.vec
+ j
);
1283 base
->timer_jiffies
= jiffies
;
1286 #ifdef CONFIG_HOTPLUG_CPU
1287 static void migrate_timer_list(tvec_base_t
*new_base
, struct list_head
*head
)
1289 struct timer_list
*timer
;
1291 while (!list_empty(head
)) {
1292 timer
= list_entry(head
->next
, struct timer_list
, entry
);
1293 detach_timer(timer
, 0);
1294 timer
->base
= &new_base
->t_base
;
1295 internal_add_timer(new_base
, timer
);
1299 static void __devinit
migrate_timers(int cpu
)
1301 tvec_base_t
*old_base
;
1302 tvec_base_t
*new_base
;
1305 BUG_ON(cpu_online(cpu
));
1306 old_base
= &per_cpu(tvec_bases
, cpu
);
1307 new_base
= &get_cpu_var(tvec_bases
);
1309 local_irq_disable();
1310 spin_lock(&new_base
->t_base
.lock
);
1311 spin_lock(&old_base
->t_base
.lock
);
1313 if (old_base
->t_base
.running_timer
)
1315 for (i
= 0; i
< TVR_SIZE
; i
++)
1316 migrate_timer_list(new_base
, old_base
->tv1
.vec
+ i
);
1317 for (i
= 0; i
< TVN_SIZE
; i
++) {
1318 migrate_timer_list(new_base
, old_base
->tv2
.vec
+ i
);
1319 migrate_timer_list(new_base
, old_base
->tv3
.vec
+ i
);
1320 migrate_timer_list(new_base
, old_base
->tv4
.vec
+ i
);
1321 migrate_timer_list(new_base
, old_base
->tv5
.vec
+ i
);
1324 spin_unlock(&old_base
->t_base
.lock
);
1325 spin_unlock(&new_base
->t_base
.lock
);
1327 put_cpu_var(tvec_bases
);
1329 #endif /* CONFIG_HOTPLUG_CPU */
1331 static int __devinit
timer_cpu_notify(struct notifier_block
*self
,
1332 unsigned long action
, void *hcpu
)
1334 long cpu
= (long)hcpu
;
1336 case CPU_UP_PREPARE
:
1337 init_timers_cpu(cpu
);
1339 #ifdef CONFIG_HOTPLUG_CPU
1341 migrate_timers(cpu
);
1350 static struct notifier_block __devinitdata timers_nb
= {
1351 .notifier_call
= timer_cpu_notify
,
1355 void __init
init_timers(void)
1357 timer_cpu_notify(&timers_nb
, (unsigned long)CPU_UP_PREPARE
,
1358 (void *)(long)smp_processor_id());
1359 register_cpu_notifier(&timers_nb
);
1360 open_softirq(TIMER_SOFTIRQ
, run_timer_softirq
, NULL
);
1363 #ifdef CONFIG_TIME_INTERPOLATION
1365 struct time_interpolator
*time_interpolator
;
1366 static struct time_interpolator
*time_interpolator_list
;
1367 static DEFINE_SPINLOCK(time_interpolator_lock
);
1369 static inline u64
time_interpolator_get_cycles(unsigned int src
)
1371 unsigned long (*x
)(void);
1375 case TIME_SOURCE_FUNCTION
:
1376 x
= time_interpolator
->addr
;
1379 case TIME_SOURCE_MMIO64
:
1380 return readq((void __iomem
*) time_interpolator
->addr
);
1382 case TIME_SOURCE_MMIO32
:
1383 return readl((void __iomem
*) time_interpolator
->addr
);
1385 default: return get_cycles();
1389 static inline u64
time_interpolator_get_counter(int writelock
)
1391 unsigned int src
= time_interpolator
->source
;
1393 if (time_interpolator
->jitter
)
1399 lcycle
= time_interpolator
->last_cycle
;
1400 now
= time_interpolator_get_cycles(src
);
1401 if (lcycle
&& time_after(lcycle
, now
))
1404 /* When holding the xtime write lock, there's no need
1405 * to add the overhead of the cmpxchg. Readers are
1406 * force to retry until the write lock is released.
1409 time_interpolator
->last_cycle
= now
;
1412 /* Keep track of the last timer value returned. The use of cmpxchg here
1413 * will cause contention in an SMP environment.
1415 } while (unlikely(cmpxchg(&time_interpolator
->last_cycle
, lcycle
, now
) != lcycle
));
1419 return time_interpolator_get_cycles(src
);
1422 void time_interpolator_reset(void)
1424 time_interpolator
->offset
= 0;
1425 time_interpolator
->last_counter
= time_interpolator_get_counter(1);
1428 #define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
1430 unsigned long time_interpolator_get_offset(void)
1432 /* If we do not have a time interpolator set up then just return zero */
1433 if (!time_interpolator
)
1436 return time_interpolator
->offset
+
1437 GET_TI_NSECS(time_interpolator_get_counter(0), time_interpolator
);
1440 #define INTERPOLATOR_ADJUST 65536
1441 #define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
1443 static void time_interpolator_update(long delta_nsec
)
1446 unsigned long offset
;
1448 /* If there is no time interpolator set up then do nothing */
1449 if (!time_interpolator
)
1453 * The interpolator compensates for late ticks by accumulating the late
1454 * time in time_interpolator->offset. A tick earlier than expected will
1455 * lead to a reset of the offset and a corresponding jump of the clock
1456 * forward. Again this only works if the interpolator clock is running
1457 * slightly slower than the regular clock and the tuning logic insures
1461 counter
= time_interpolator_get_counter(1);
1462 offset
= time_interpolator
->offset
+
1463 GET_TI_NSECS(counter
, time_interpolator
);
1465 if (delta_nsec
< 0 || (unsigned long) delta_nsec
< offset
)
1466 time_interpolator
->offset
= offset
- delta_nsec
;
1468 time_interpolator
->skips
++;
1469 time_interpolator
->ns_skipped
+= delta_nsec
- offset
;
1470 time_interpolator
->offset
= 0;
1472 time_interpolator
->last_counter
= counter
;
1474 /* Tuning logic for time interpolator invoked every minute or so.
1475 * Decrease interpolator clock speed if no skips occurred and an offset is carried.
1476 * Increase interpolator clock speed if we skip too much time.
1478 if (jiffies
% INTERPOLATOR_ADJUST
== 0)
1480 if (time_interpolator
->skips
== 0 && time_interpolator
->offset
> TICK_NSEC
)
1481 time_interpolator
->nsec_per_cyc
--;
1482 if (time_interpolator
->ns_skipped
> INTERPOLATOR_MAX_SKIP
&& time_interpolator
->offset
== 0)
1483 time_interpolator
->nsec_per_cyc
++;
1484 time_interpolator
->skips
= 0;
1485 time_interpolator
->ns_skipped
= 0;
1490 is_better_time_interpolator(struct time_interpolator
*new)
1492 if (!time_interpolator
)
1494 return new->frequency
> 2*time_interpolator
->frequency
||
1495 (unsigned long)new->drift
< (unsigned long)time_interpolator
->drift
;
1499 register_time_interpolator(struct time_interpolator
*ti
)
1501 unsigned long flags
;
1504 if (ti
->frequency
== 0 || ti
->mask
== 0)
1507 ti
->nsec_per_cyc
= ((u64
)NSEC_PER_SEC
<< ti
->shift
) / ti
->frequency
;
1508 spin_lock(&time_interpolator_lock
);
1509 write_seqlock_irqsave(&xtime_lock
, flags
);
1510 if (is_better_time_interpolator(ti
)) {
1511 time_interpolator
= ti
;
1512 time_interpolator_reset();
1514 write_sequnlock_irqrestore(&xtime_lock
, flags
);
1516 ti
->next
= time_interpolator_list
;
1517 time_interpolator_list
= ti
;
1518 spin_unlock(&time_interpolator_lock
);
1522 unregister_time_interpolator(struct time_interpolator
*ti
)
1524 struct time_interpolator
*curr
, **prev
;
1525 unsigned long flags
;
1527 spin_lock(&time_interpolator_lock
);
1528 prev
= &time_interpolator_list
;
1529 for (curr
= *prev
; curr
; curr
= curr
->next
) {
1537 write_seqlock_irqsave(&xtime_lock
, flags
);
1538 if (ti
== time_interpolator
) {
1539 /* we lost the best time-interpolator: */
1540 time_interpolator
= NULL
;
1541 /* find the next-best interpolator */
1542 for (curr
= time_interpolator_list
; curr
; curr
= curr
->next
)
1543 if (is_better_time_interpolator(curr
))
1544 time_interpolator
= curr
;
1545 time_interpolator_reset();
1547 write_sequnlock_irqrestore(&xtime_lock
, flags
);
1548 spin_unlock(&time_interpolator_lock
);
1550 #endif /* CONFIG_TIME_INTERPOLATION */
1553 * msleep - sleep safely even with waitqueue interruptions
1554 * @msecs: Time in milliseconds to sleep for
1556 void msleep(unsigned int msecs
)
1558 unsigned long timeout
= msecs_to_jiffies(msecs
) + 1;
1561 timeout
= schedule_timeout_uninterruptible(timeout
);
1564 EXPORT_SYMBOL(msleep
);
1567 * msleep_interruptible - sleep waiting for signals
1568 * @msecs: Time in milliseconds to sleep for
1570 unsigned long msleep_interruptible(unsigned int msecs
)
1572 unsigned long timeout
= msecs_to_jiffies(msecs
) + 1;
1574 while (timeout
&& !signal_pending(current
))
1575 timeout
= schedule_timeout_interruptible(timeout
);
1576 return jiffies_to_msecs(timeout
);
1579 EXPORT_SYMBOL(msleep_interruptible
);