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>
37 #include <linux/vs_cvirt.h>
38 #include <linux/vserver/sched.h>
40 #include <asm/uaccess.h>
41 #include <asm/unistd.h>
42 #include <asm/div64.h>
43 #include <asm/timex.h>
46 #ifdef CONFIG_TIME_INTERPOLATION
47 static void time_interpolator_update(long delta_nsec);
49 #define time_interpolator_update(x)
52 u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
54 EXPORT_SYMBOL(jiffies_64);
57 * per-CPU timer vector definitions:
60 #define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
61 #define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
62 #define TVN_SIZE (1 << TVN_BITS)
63 #define TVR_SIZE (1 << TVR_BITS)
64 #define TVN_MASK (TVN_SIZE - 1)
65 #define TVR_MASK (TVR_SIZE - 1)
69 struct timer_list *running_timer;
72 typedef struct tvec_s {
73 struct list_head vec[TVN_SIZE];
76 typedef struct tvec_root_s {
77 struct list_head vec[TVR_SIZE];
80 struct tvec_t_base_s {
81 struct timer_base_s t_base;
82 unsigned long timer_jiffies;
88 } ____cacheline_aligned_in_smp;
90 typedef struct tvec_t_base_s tvec_base_t;
91 static DEFINE_PER_CPU(tvec_base_t, tvec_bases);
93 static inline void set_running_timer(tvec_base_t *base,
94 struct timer_list *timer)
97 base->t_base.running_timer = timer;
101 static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
103 unsigned long expires = timer->expires;
104 unsigned long idx = expires - base->timer_jiffies;
105 struct list_head *vec;
107 if (idx < TVR_SIZE) {
108 int i = expires & TVR_MASK;
109 vec = base->tv1.vec + i;
110 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
111 int i = (expires >> TVR_BITS) & TVN_MASK;
112 vec = base->tv2.vec + i;
113 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
114 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
115 vec = base->tv3.vec + i;
116 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
117 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
118 vec = base->tv4.vec + i;
119 } else if ((signed long) idx < 0) {
121 * Can happen if you add a timer with expires == jiffies,
122 * or you set a timer to go off in the past
124 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
127 /* If the timeout is larger than 0xffffffff on 64-bit
128 * architectures then we use the maximum timeout:
130 if (idx > 0xffffffffUL) {
132 expires = idx + base->timer_jiffies;
134 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
135 vec = base->tv5.vec + i;
140 list_add_tail(&timer->entry, vec);
143 typedef struct timer_base_s timer_base_t;
145 * Used by TIMER_INITIALIZER, we can't use per_cpu(tvec_bases)
146 * at compile time, and we need timer->base to lock the timer.
148 timer_base_t __init_timer_base
149 ____cacheline_aligned_in_smp = { .lock = SPIN_LOCK_UNLOCKED };
150 EXPORT_SYMBOL(__init_timer_base);
153 * init_timer - initialize a timer.
154 * @timer: the timer to be initialized
156 * init_timer() must be done to a timer prior calling *any* of the
157 * other timer functions.
159 void fastcall init_timer(struct timer_list *timer)
161 timer->entry.next = NULL;
162 timer->base = &per_cpu(tvec_bases, raw_smp_processor_id()).t_base;
164 EXPORT_SYMBOL(init_timer);
166 static inline void detach_timer(struct timer_list *timer,
169 struct list_head *entry = &timer->entry;
171 __list_del(entry->prev, entry->next);
174 entry->prev = LIST_POISON2;
178 * We are using hashed locking: holding per_cpu(tvec_bases).t_base.lock
179 * means that all timers which are tied to this base via timer->base are
180 * locked, and the base itself is locked too.
182 * So __run_timers/migrate_timers can safely modify all timers which could
183 * be found on ->tvX lists.
185 * When the timer's base is locked, and the timer removed from list, it is
186 * possible to set timer->base = NULL and drop the lock: the timer remains
189 static timer_base_t *lock_timer_base(struct timer_list *timer,
190 unsigned long *flags)
196 if (likely(base != NULL)) {
197 spin_lock_irqsave(&base->lock, *flags);
198 if (likely(base == timer->base))
200 /* The timer has migrated to another CPU */
201 spin_unlock_irqrestore(&base->lock, *flags);
207 int __mod_timer(struct timer_list *timer, unsigned long expires)
210 tvec_base_t *new_base;
214 BUG_ON(!timer->function);
216 base = lock_timer_base(timer, &flags);
218 if (timer_pending(timer)) {
219 detach_timer(timer, 0);
223 new_base = &__get_cpu_var(tvec_bases);
225 if (base != &new_base->t_base) {
227 * We are trying to schedule the timer on the local CPU.
228 * However we can't change timer's base while it is running,
229 * otherwise del_timer_sync() can't detect that the timer's
230 * handler yet has not finished. This also guarantees that
231 * the timer is serialized wrt itself.
233 if (unlikely(base->running_timer == timer)) {
234 /* The timer remains on a former base */
235 new_base = container_of(base, tvec_base_t, t_base);
237 /* See the comment in lock_timer_base() */
239 spin_unlock(&base->lock);
240 spin_lock(&new_base->t_base.lock);
241 timer->base = &new_base->t_base;
245 timer->expires = expires;
246 internal_add_timer(new_base, timer);
247 spin_unlock_irqrestore(&new_base->t_base.lock, flags);
252 EXPORT_SYMBOL(__mod_timer);
255 * add_timer_on - start a timer on a particular CPU
256 * @timer: the timer to be added
257 * @cpu: the CPU to start it on
259 * This is not very scalable on SMP. Double adds are not possible.
261 void add_timer_on(struct timer_list *timer, int cpu)
263 tvec_base_t *base = &per_cpu(tvec_bases, cpu);
266 BUG_ON(timer_pending(timer) || !timer->function);
267 spin_lock_irqsave(&base->t_base.lock, flags);
268 timer->base = &base->t_base;
269 internal_add_timer(base, timer);
270 spin_unlock_irqrestore(&base->t_base.lock, flags);
275 * mod_timer - modify a timer's timeout
276 * @timer: the timer to be modified
278 * mod_timer is a more efficient way to update the expire field of an
279 * active timer (if the timer is inactive it will be activated)
281 * mod_timer(timer, expires) is equivalent to:
283 * del_timer(timer); timer->expires = expires; add_timer(timer);
285 * Note that if there are multiple unserialized concurrent users of the
286 * same timer, then mod_timer() is the only safe way to modify the timeout,
287 * since add_timer() cannot modify an already running timer.
289 * The function returns whether it has modified a pending timer or not.
290 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
291 * active timer returns 1.)
293 int mod_timer(struct timer_list *timer, unsigned long expires)
295 BUG_ON(!timer->function);
298 * This is a common optimization triggered by the
299 * networking code - if the timer is re-modified
300 * to be the same thing then just return:
302 if (timer->expires == expires && timer_pending(timer))
305 return __mod_timer(timer, expires);
308 EXPORT_SYMBOL(mod_timer);
311 * del_timer - deactive a timer.
312 * @timer: the timer to be deactivated
314 * del_timer() deactivates a timer - this works on both active and inactive
317 * The function returns whether it has deactivated a pending timer or not.
318 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
319 * active timer returns 1.)
321 int del_timer(struct timer_list *timer)
327 if (timer_pending(timer)) {
328 base = lock_timer_base(timer, &flags);
329 if (timer_pending(timer)) {
330 detach_timer(timer, 1);
333 spin_unlock_irqrestore(&base->lock, flags);
339 EXPORT_SYMBOL(del_timer);
343 * This function tries to deactivate a timer. Upon successful (ret >= 0)
344 * exit the timer is not queued and the handler is not running on any CPU.
346 * It must not be called from interrupt contexts.
348 int try_to_del_timer_sync(struct timer_list *timer)
354 base = lock_timer_base(timer, &flags);
356 if (base->running_timer == timer)
360 if (timer_pending(timer)) {
361 detach_timer(timer, 1);
365 spin_unlock_irqrestore(&base->lock, flags);
371 * del_timer_sync - deactivate a timer and wait for the handler to finish.
372 * @timer: the timer to be deactivated
374 * This function only differs from del_timer() on SMP: besides deactivating
375 * the timer it also makes sure the handler has finished executing on other
378 * Synchronization rules: callers must prevent restarting of the timer,
379 * otherwise this function is meaningless. It must not be called from
380 * interrupt contexts. The caller must not hold locks which would prevent
381 * completion of the timer's handler. The timer's handler must not call
382 * add_timer_on(). Upon exit the timer is not queued and the handler is
383 * not running on any CPU.
385 * The function returns whether it has deactivated a pending timer or not.
387 int del_timer_sync(struct timer_list *timer)
390 int ret = try_to_del_timer_sync(timer);
396 EXPORT_SYMBOL(del_timer_sync);
399 static int cascade(tvec_base_t *base, tvec_t *tv, int index)
401 /* cascade all the timers from tv up one level */
402 struct list_head *head, *curr;
404 head = tv->vec + index;
407 * We are removing _all_ timers from the list, so we don't have to
408 * detach them individually, just clear the list afterwards.
410 while (curr != head) {
411 struct timer_list *tmp;
413 tmp = list_entry(curr, struct timer_list, entry);
414 BUG_ON(tmp->base != &base->t_base);
416 internal_add_timer(base, tmp);
418 INIT_LIST_HEAD(head);
424 * __run_timers - run all expired timers (if any) on this CPU.
425 * @base: the timer vector to be processed.
427 * This function cascades all vectors and executes all expired timer
430 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
432 static inline void __run_timers(tvec_base_t *base)
434 struct timer_list *timer;
436 spin_lock_irq(&base->t_base.lock);
437 while (time_after_eq(jiffies, base->timer_jiffies)) {
438 struct list_head work_list = LIST_HEAD_INIT(work_list);
439 struct list_head *head = &work_list;
440 int index = base->timer_jiffies & TVR_MASK;
446 (!cascade(base, &base->tv2, INDEX(0))) &&
447 (!cascade(base, &base->tv3, INDEX(1))) &&
448 !cascade(base, &base->tv4, INDEX(2)))
449 cascade(base, &base->tv5, INDEX(3));
450 ++base->timer_jiffies;
451 list_splice_init(base->tv1.vec + index, &work_list);
452 while (!list_empty(head)) {
453 void (*fn)(unsigned long);
456 timer = list_entry(head->next,struct timer_list,entry);
457 fn = timer->function;
460 set_running_timer(base, timer);
461 detach_timer(timer, 1);
462 spin_unlock_irq(&base->t_base.lock);
464 int preempt_count = preempt_count();
466 if (preempt_count != preempt_count()) {
467 printk(KERN_WARNING "huh, entered %p "
468 "with preempt_count %08x, exited"
475 spin_lock_irq(&base->t_base.lock);
478 set_running_timer(base, NULL);
479 spin_unlock_irq(&base->t_base.lock);
482 #ifdef CONFIG_NO_IDLE_HZ
484 * Find out when the next timer event is due to happen. This
485 * is used on S/390 to stop all activity when a cpus is idle.
486 * This functions needs to be called disabled.
488 unsigned long next_timer_interrupt(void)
491 struct list_head *list;
492 struct timer_list *nte;
493 unsigned long expires;
494 unsigned long hr_expires = MAX_JIFFY_OFFSET;
499 hr_delta = hrtimer_get_next_event();
500 if (hr_delta.tv64 != KTIME_MAX) {
501 struct timespec tsdelta;
502 tsdelta = ktime_to_timespec(hr_delta);
503 hr_expires = timespec_to_jiffies(&tsdelta);
505 return hr_expires + jiffies;
507 hr_expires += jiffies;
509 base = &__get_cpu_var(tvec_bases);
510 spin_lock(&base->t_base.lock);
511 expires = base->timer_jiffies + (LONG_MAX >> 1);
514 /* Look for timer events in tv1. */
515 j = base->timer_jiffies & TVR_MASK;
517 list_for_each_entry(nte, base->tv1.vec + j, entry) {
518 expires = nte->expires;
519 if (j < (base->timer_jiffies & TVR_MASK))
520 list = base->tv2.vec + (INDEX(0));
523 j = (j + 1) & TVR_MASK;
524 } while (j != (base->timer_jiffies & TVR_MASK));
527 varray[0] = &base->tv2;
528 varray[1] = &base->tv3;
529 varray[2] = &base->tv4;
530 varray[3] = &base->tv5;
531 for (i = 0; i < 4; i++) {
534 if (list_empty(varray[i]->vec + j)) {
535 j = (j + 1) & TVN_MASK;
538 list_for_each_entry(nte, varray[i]->vec + j, entry)
539 if (time_before(nte->expires, expires))
540 expires = nte->expires;
541 if (j < (INDEX(i)) && i < 3)
542 list = varray[i + 1]->vec + (INDEX(i + 1));
544 } while (j != (INDEX(i)));
549 * The search wrapped. We need to look at the next list
550 * from next tv element that would cascade into tv element
551 * where we found the timer element.
553 list_for_each_entry(nte, list, entry) {
554 if (time_before(nte->expires, expires))
555 expires = nte->expires;
558 spin_unlock(&base->t_base.lock);
560 if (time_before(hr_expires, expires))
567 /******************************************************************/
570 * Timekeeping variables
572 unsigned long tick_usec = TICK_USEC; /* USER_HZ period (usec) */
573 unsigned long tick_nsec = TICK_NSEC; /* ACTHZ period (nsec) */
577 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
578 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
579 * at zero at system boot time, so wall_to_monotonic will be negative,
580 * however, we will ALWAYS keep the tv_nsec part positive so we can use
581 * the usual normalization.
583 struct timespec xtime __attribute__ ((aligned (16)));
584 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
586 EXPORT_SYMBOL(xtime);
588 /* Don't completely fail for HZ > 500. */
589 int tickadj = 500/HZ ? : 1; /* microsecs */
593 * phase-lock loop variables
595 /* TIME_ERROR prevents overwriting the CMOS clock */
596 int time_state = TIME_OK; /* clock synchronization status */
597 int time_status = STA_UNSYNC; /* clock status bits */
598 long time_offset; /* time adjustment (us) */
599 long time_constant = 2; /* pll time constant */
600 long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
601 long time_precision = 1; /* clock precision (us) */
602 long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
603 long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
604 static long time_phase; /* phase offset (scaled us) */
605 long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
606 /* frequency offset (scaled ppm)*/
607 static long time_adj; /* tick adjust (scaled 1 / HZ) */
608 long time_reftime; /* time at last adjustment (s) */
610 long time_next_adjust;
613 * this routine handles the overflow of the microsecond field
615 * The tricky bits of code to handle the accurate clock support
616 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
617 * They were originally developed for SUN and DEC kernels.
618 * All the kudos should go to Dave for this stuff.
621 static void second_overflow(void)
625 /* Bump the maxerror field */
626 time_maxerror += time_tolerance >> SHIFT_USEC;
627 if (time_maxerror > NTP_PHASE_LIMIT) {
628 time_maxerror = NTP_PHASE_LIMIT;
629 time_status |= STA_UNSYNC;
633 * Leap second processing. If in leap-insert state at the end of the
634 * day, the system clock is set back one second; if in leap-delete
635 * state, the system clock is set ahead one second. The microtime()
636 * routine or external clock driver will insure that reported time is
637 * always monotonic. The ugly divides should be replaced.
639 switch (time_state) {
641 if (time_status & STA_INS)
642 time_state = TIME_INS;
643 else if (time_status & STA_DEL)
644 time_state = TIME_DEL;
647 if (xtime.tv_sec % 86400 == 0) {
649 wall_to_monotonic.tv_sec++;
651 * The timer interpolator will make time change
652 * gradually instead of an immediate jump by one second
654 time_interpolator_update(-NSEC_PER_SEC);
655 time_state = TIME_OOP;
657 printk(KERN_NOTICE "Clock: inserting leap second "
662 if ((xtime.tv_sec + 1) % 86400 == 0) {
664 wall_to_monotonic.tv_sec--;
666 * Use of time interpolator for a gradual change of
669 time_interpolator_update(NSEC_PER_SEC);
670 time_state = TIME_WAIT;
672 printk(KERN_NOTICE "Clock: deleting leap second "
677 time_state = TIME_WAIT;
680 if (!(time_status & (STA_INS | STA_DEL)))
681 time_state = TIME_OK;
685 * Compute the phase adjustment for the next second. In PLL mode, the
686 * offset is reduced by a fixed factor times the time constant. In FLL
687 * mode the offset is used directly. In either mode, the maximum phase
688 * adjustment for each second is clamped so as to spread the adjustment
689 * over not more than the number of seconds between updates.
692 if (!(time_status & STA_FLL))
693 ltemp = shift_right(ltemp, SHIFT_KG + time_constant);
694 ltemp = min(ltemp, (MAXPHASE / MINSEC) << SHIFT_UPDATE);
695 ltemp = max(ltemp, -(MAXPHASE / MINSEC) << SHIFT_UPDATE);
696 time_offset -= ltemp;
697 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
700 * Compute the frequency estimate and additional phase adjustment due
701 * to frequency error for the next second. When the PPS signal is
702 * engaged, gnaw on the watchdog counter and update the frequency
703 * computed by the pll and the PPS signal.
706 if (pps_valid == PPS_VALID) { /* PPS signal lost */
707 pps_jitter = MAXTIME;
708 pps_stabil = MAXFREQ;
709 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
710 STA_PPSWANDER | STA_PPSERROR);
712 ltemp = time_freq + pps_freq;
713 time_adj += shift_right(ltemp,(SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE));
717 * Compensate for (HZ==100) != (1 << SHIFT_HZ). Add 25% and 3.125% to
718 * get 128.125; => only 0.125% error (p. 14)
720 time_adj += shift_right(time_adj, 2) + shift_right(time_adj, 5);
724 * Compensate for (HZ==250) != (1 << SHIFT_HZ). Add 1.5625% and
725 * 0.78125% to get 255.85938; => only 0.05% error (p. 14)
727 time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
731 * Compensate for (HZ==1000) != (1 << SHIFT_HZ). Add 1.5625% and
732 * 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
734 time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
739 * Returns how many microseconds we need to add to xtime this tick
740 * in doing an adjustment requested with adjtime.
742 static long adjtime_adjustment(void)
744 long time_adjust_step;
746 time_adjust_step = time_adjust;
747 if (time_adjust_step) {
749 * We are doing an adjtime thing. Prepare time_adjust_step to
750 * be within bounds. Note that a positive time_adjust means we
751 * want the clock to run faster.
753 * Limit the amount of the step to be in the range
754 * -tickadj .. +tickadj
756 time_adjust_step = min(time_adjust_step, (long)tickadj);
757 time_adjust_step = max(time_adjust_step, (long)-tickadj);
759 return time_adjust_step;
762 /* in the NTP reference this is called "hardclock()" */
763 static void update_wall_time_one_tick(void)
765 long time_adjust_step, delta_nsec;
767 time_adjust_step = adjtime_adjustment();
768 if (time_adjust_step)
769 /* Reduce by this step the amount of time left */
770 time_adjust -= time_adjust_step;
771 delta_nsec = tick_nsec + time_adjust_step * 1000;
773 * Advance the phase, once it gets to one microsecond, then
774 * advance the tick more.
776 time_phase += time_adj;
777 if ((time_phase >= FINENSEC) || (time_phase <= -FINENSEC)) {
778 long ltemp = shift_right(time_phase, (SHIFT_SCALE - 10));
779 time_phase -= ltemp << (SHIFT_SCALE - 10);
782 xtime.tv_nsec += delta_nsec;
783 time_interpolator_update(delta_nsec);
785 /* Changes by adjtime() do not take effect till next tick. */
786 if (time_next_adjust != 0) {
787 time_adjust = time_next_adjust;
788 time_next_adjust = 0;
793 * Return how long ticks are at the moment, that is, how much time
794 * update_wall_time_one_tick will add to xtime next time we call it
795 * (assuming no calls to do_adjtimex in the meantime).
796 * The return value is in fixed-point nanoseconds with SHIFT_SCALE-10
797 * bits to the right of the binary point.
798 * This function has no side-effects.
800 u64 current_tick_length(void)
804 delta_nsec = tick_nsec + adjtime_adjustment() * 1000;
805 return ((u64) delta_nsec << (SHIFT_SCALE - 10)) + time_adj;
809 * Using a loop looks inefficient, but "ticks" is
810 * usually just one (we shouldn't be losing ticks,
811 * we're doing this this way mainly for interrupt
812 * latency reasons, not because we think we'll
813 * have lots of lost timer ticks
815 static void update_wall_time(unsigned long ticks)
819 update_wall_time_one_tick();
820 if (xtime.tv_nsec >= 1000000000) {
821 xtime.tv_nsec -= 1000000000;
829 * Called from the timer interrupt handler to charge one tick to the current
830 * process. user_tick is 1 if the tick is user time, 0 for system.
832 void update_process_times(int user_tick)
834 struct task_struct *p = current;
835 int cpu = smp_processor_id();
837 /* Note: this timer irq context must be accounted for as well. */
839 account_user_time(p, jiffies_to_cputime(1));
841 account_system_time(p, HARDIRQ_OFFSET, jiffies_to_cputime(1));
843 if (rcu_pending(cpu))
844 rcu_check_callbacks(cpu, user_tick);
846 run_posix_cpu_timers(p);
850 * Nr of active tasks - counted in fixed-point numbers
852 static unsigned long count_active_tasks(void)
854 return (nr_running() + nr_uninterruptible()) * FIXED_1;
858 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
859 * imply that avenrun[] is the standard name for this kind of thing.
860 * Nothing else seems to be standardized: the fractional size etc
861 * all seem to differ on different machines.
863 * Requires xtime_lock to access.
865 unsigned long avenrun[3];
867 EXPORT_SYMBOL(avenrun);
870 * calc_load - given tick count, update the avenrun load estimates.
871 * This is called while holding a write_lock on xtime_lock.
873 static inline void calc_load(unsigned long ticks)
875 unsigned long active_tasks; /* fixed-point */
876 static int count = LOAD_FREQ;
881 active_tasks = count_active_tasks();
882 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
883 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
884 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
888 /* jiffies at the most recent update of wall time */
889 unsigned long wall_jiffies = INITIAL_JIFFIES;
892 * This read-write spinlock protects us from races in SMP while
893 * playing with xtime and avenrun.
895 #ifndef ARCH_HAVE_XTIME_LOCK
896 seqlock_t xtime_lock __cacheline_aligned_in_smp = SEQLOCK_UNLOCKED;
898 EXPORT_SYMBOL(xtime_lock);
902 * This function runs timers and the timer-tq in bottom half context.
904 static void run_timer_softirq(struct softirq_action *h)
906 tvec_base_t *base = &__get_cpu_var(tvec_bases);
908 hrtimer_run_queues();
909 if (time_after_eq(jiffies, base->timer_jiffies))
914 * Called by the local, per-CPU timer interrupt on SMP.
916 void run_local_timers(void)
918 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. */
949 softlockup_tick(regs);
952 #ifdef __ARCH_WANT_SYS_ALARM
955 * For backwards compatibility? This can be done in libc so Alpha
956 * and all newer ports shouldn't need it.
958 asmlinkage unsigned long sys_alarm(unsigned int seconds)
960 struct itimerval it_new, it_old;
961 unsigned int oldalarm;
963 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
964 it_new.it_value.tv_sec = seconds;
965 it_new.it_value.tv_usec = 0;
966 do_setitimer(ITIMER_REAL, &it_new, &it_old);
967 oldalarm = it_old.it_value.tv_sec;
968 /* ehhh.. We can't return 0 if we have an alarm pending.. */
969 /* And we'd better return too much than too little anyway */
970 if ((!oldalarm && it_old.it_value.tv_usec) || it_old.it_value.tv_usec >= 500000)
979 * sys_getpid - return the thread group id of the current process
981 * Note, despite the name, this returns the tgid not the pid. The tgid and
982 * the pid are identical unless CLONE_THREAD was specified on clone() in
983 * which case the tgid is the same in all threads of the same group.
985 * This is SMP safe as current->tgid does not change.
987 asmlinkage long sys_getpid(void)
989 return vx_map_tgid(current->tgid);
993 * Accessing ->real_parent is not SMP-safe, it could
994 * change from under us. However, we can use a stale
995 * value of ->real_parent under rcu_read_lock(), see
996 * release_task()->call_rcu(delayed_put_task_struct).
998 asmlinkage long sys_getppid(void)
1003 pid = rcu_dereference(current->real_parent)->tgid;
1006 return vx_map_pid(pid);
1012 * The Alpha uses getxpid, getxuid, and getxgid instead.
1015 asmlinkage long do_getxpid(long *ppid)
1017 *ppid = sys_getppid();
1018 return sys_getpid();
1023 asmlinkage long sys_getuid(void)
1025 /* Only we change this so SMP safe */
1026 return current->uid;
1029 asmlinkage long sys_geteuid(void)
1031 /* Only we change this so SMP safe */
1032 return current->euid;
1035 asmlinkage long sys_getgid(void)
1037 /* Only we change this so SMP safe */
1038 return current->gid;
1041 asmlinkage long sys_getegid(void)
1043 /* Only we change this so SMP safe */
1044 return current->egid;
1049 static void process_timeout(unsigned long __data)
1051 wake_up_process((task_t *)__data);
1055 * schedule_timeout - sleep until timeout
1056 * @timeout: timeout value in jiffies
1058 * Make the current task sleep until @timeout jiffies have
1059 * elapsed. The routine will return immediately unless
1060 * the current task state has been set (see set_current_state()).
1062 * You can set the task state as follows -
1064 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1065 * pass before the routine returns. The routine will return 0
1067 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1068 * delivered to the current task. In this case the remaining time
1069 * in jiffies will be returned, or 0 if the timer expired in time
1071 * The current task state is guaranteed to be TASK_RUNNING when this
1074 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1075 * the CPU away without a bound on the timeout. In this case the return
1076 * value will be %MAX_SCHEDULE_TIMEOUT.
1078 * In all cases the return value is guaranteed to be non-negative.
1080 fastcall signed long __sched schedule_timeout(signed long timeout)
1082 struct timer_list timer;
1083 unsigned long expire;
1087 case MAX_SCHEDULE_TIMEOUT:
1089 * These two special cases are useful to be comfortable
1090 * in the caller. Nothing more. We could take
1091 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1092 * but I' d like to return a valid offset (>=0) to allow
1093 * the caller to do everything it want with the retval.
1099 * Another bit of PARANOID. Note that the retval will be
1100 * 0 since no piece of kernel is supposed to do a check
1101 * for a negative retval of schedule_timeout() (since it
1102 * should never happens anyway). You just have the printk()
1103 * that will tell you if something is gone wrong and where.
1107 printk(KERN_ERR "schedule_timeout: wrong timeout "
1108 "value %lx from %p\n", timeout,
1109 __builtin_return_address(0));
1110 current->state = TASK_RUNNING;
1115 expire = timeout + jiffies;
1117 setup_timer(&timer, process_timeout, (unsigned long)current);
1118 __mod_timer(&timer, expire);
1120 del_singleshot_timer_sync(&timer);
1122 timeout = expire - jiffies;
1125 return timeout < 0 ? 0 : timeout;
1127 EXPORT_SYMBOL(schedule_timeout);
1130 * We can use __set_current_state() here because schedule_timeout() calls
1131 * schedule() unconditionally.
1133 signed long __sched schedule_timeout_interruptible(signed long timeout)
1135 __set_current_state(TASK_INTERRUPTIBLE);
1136 return schedule_timeout(timeout);
1138 EXPORT_SYMBOL(schedule_timeout_interruptible);
1140 signed long __sched schedule_timeout_uninterruptible(signed long timeout)
1142 __set_current_state(TASK_UNINTERRUPTIBLE);
1143 return schedule_timeout(timeout);
1145 EXPORT_SYMBOL(schedule_timeout_uninterruptible);
1147 /* Thread ID - the internal kernel "pid" */
1148 asmlinkage long sys_gettid(void)
1150 return current->pid;
1154 * sys_sysinfo - fill in sysinfo struct
1156 asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1159 unsigned long mem_total, sav_total;
1160 unsigned int mem_unit, bitcount;
1163 memset((char *)&val, 0, sizeof(struct sysinfo));
1167 seq = read_seqbegin(&xtime_lock);
1170 * This is annoying. The below is the same thing
1171 * posix_get_clock_monotonic() does, but it wants to
1172 * take the lock which we want to cover the loads stuff
1176 getnstimeofday(&tp);
1177 tp.tv_sec += wall_to_monotonic.tv_sec;
1178 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1179 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1180 tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1183 if (vx_flags(VXF_VIRT_UPTIME, 0))
1184 vx_vsi_uptime(&tp, NULL);
1185 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1187 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1188 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1189 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1191 val.procs = nr_threads;
1192 } while (read_seqretry(&xtime_lock, seq));
1198 * If the sum of all the available memory (i.e. ram + swap)
1199 * is less than can be stored in a 32 bit unsigned long then
1200 * we can be binary compatible with 2.2.x kernels. If not,
1201 * well, in that case 2.2.x was broken anyways...
1203 * -Erik Andersen <andersee@debian.org>
1206 mem_total = val.totalram + val.totalswap;
1207 if (mem_total < val.totalram || mem_total < val.totalswap)
1210 mem_unit = val.mem_unit;
1211 while (mem_unit > 1) {
1214 sav_total = mem_total;
1216 if (mem_total < sav_total)
1221 * If mem_total did not overflow, multiply all memory values by
1222 * val.mem_unit and set it to 1. This leaves things compatible
1223 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1228 val.totalram <<= bitcount;
1229 val.freeram <<= bitcount;
1230 val.sharedram <<= bitcount;
1231 val.bufferram <<= bitcount;
1232 val.totalswap <<= bitcount;
1233 val.freeswap <<= bitcount;
1234 val.totalhigh <<= bitcount;
1235 val.freehigh <<= bitcount;
1238 if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1244 static void __devinit init_timers_cpu(int cpu)
1249 base = &per_cpu(tvec_bases, cpu);
1250 spin_lock_init(&base->t_base.lock);
1251 for (j = 0; j < TVN_SIZE; j++) {
1252 INIT_LIST_HEAD(base->tv5.vec + j);
1253 INIT_LIST_HEAD(base->tv4.vec + j);
1254 INIT_LIST_HEAD(base->tv3.vec + j);
1255 INIT_LIST_HEAD(base->tv2.vec + j);
1257 for (j = 0; j < TVR_SIZE; j++)
1258 INIT_LIST_HEAD(base->tv1.vec + j);
1260 base->timer_jiffies = jiffies;
1263 #ifdef CONFIG_HOTPLUG_CPU
1264 static void migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
1266 struct timer_list *timer;
1268 while (!list_empty(head)) {
1269 timer = list_entry(head->next, struct timer_list, entry);
1270 detach_timer(timer, 0);
1271 timer->base = &new_base->t_base;
1272 internal_add_timer(new_base, timer);
1276 static void __devinit migrate_timers(int cpu)
1278 tvec_base_t *old_base;
1279 tvec_base_t *new_base;
1282 BUG_ON(cpu_online(cpu));
1283 old_base = &per_cpu(tvec_bases, cpu);
1284 new_base = &get_cpu_var(tvec_bases);
1286 local_irq_disable();
1287 spin_lock(&new_base->t_base.lock);
1288 spin_lock(&old_base->t_base.lock);
1290 if (old_base->t_base.running_timer)
1292 for (i = 0; i < TVR_SIZE; i++)
1293 migrate_timer_list(new_base, old_base->tv1.vec + i);
1294 for (i = 0; i < TVN_SIZE; i++) {
1295 migrate_timer_list(new_base, old_base->tv2.vec + i);
1296 migrate_timer_list(new_base, old_base->tv3.vec + i);
1297 migrate_timer_list(new_base, old_base->tv4.vec + i);
1298 migrate_timer_list(new_base, old_base->tv5.vec + i);
1301 spin_unlock(&old_base->t_base.lock);
1302 spin_unlock(&new_base->t_base.lock);
1304 put_cpu_var(tvec_bases);
1306 #endif /* CONFIG_HOTPLUG_CPU */
1308 static int __devinit timer_cpu_notify(struct notifier_block *self,
1309 unsigned long action, void *hcpu)
1311 long cpu = (long)hcpu;
1313 case CPU_UP_PREPARE:
1314 init_timers_cpu(cpu);
1316 #ifdef CONFIG_HOTPLUG_CPU
1318 migrate_timers(cpu);
1327 static struct notifier_block __devinitdata timers_nb = {
1328 .notifier_call = timer_cpu_notify,
1332 void __init init_timers(void)
1334 timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1335 (void *)(long)smp_processor_id());
1336 register_cpu_notifier(&timers_nb);
1337 open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1340 #ifdef CONFIG_TIME_INTERPOLATION
1342 struct time_interpolator *time_interpolator __read_mostly;
1343 static struct time_interpolator *time_interpolator_list __read_mostly;
1344 static DEFINE_SPINLOCK(time_interpolator_lock);
1346 static inline u64 time_interpolator_get_cycles(unsigned int src)
1348 unsigned long (*x)(void);
1352 case TIME_SOURCE_FUNCTION:
1353 x = time_interpolator->addr;
1356 case TIME_SOURCE_MMIO64 :
1357 return readq_relaxed((void __iomem *)time_interpolator->addr);
1359 case TIME_SOURCE_MMIO32 :
1360 return readl_relaxed((void __iomem *)time_interpolator->addr);
1362 default: return get_cycles();
1366 static inline u64 time_interpolator_get_counter(int writelock)
1368 unsigned int src = time_interpolator->source;
1370 if (time_interpolator->jitter)
1376 lcycle = time_interpolator->last_cycle;
1377 now = time_interpolator_get_cycles(src);
1378 if (lcycle && time_after(lcycle, now))
1381 /* When holding the xtime write lock, there's no need
1382 * to add the overhead of the cmpxchg. Readers are
1383 * force to retry until the write lock is released.
1386 time_interpolator->last_cycle = now;
1389 /* Keep track of the last timer value returned. The use of cmpxchg here
1390 * will cause contention in an SMP environment.
1392 } while (unlikely(cmpxchg(&time_interpolator->last_cycle, lcycle, now) != lcycle));
1396 return time_interpolator_get_cycles(src);
1399 void time_interpolator_reset(void)
1401 time_interpolator->offset = 0;
1402 time_interpolator->last_counter = time_interpolator_get_counter(1);
1405 #define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
1407 unsigned long time_interpolator_get_offset(void)
1409 /* If we do not have a time interpolator set up then just return zero */
1410 if (!time_interpolator)
1413 return time_interpolator->offset +
1414 GET_TI_NSECS(time_interpolator_get_counter(0), time_interpolator);
1417 #define INTERPOLATOR_ADJUST 65536
1418 #define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
1420 static void time_interpolator_update(long delta_nsec)
1423 unsigned long offset;
1425 /* If there is no time interpolator set up then do nothing */
1426 if (!time_interpolator)
1430 * The interpolator compensates for late ticks by accumulating the late
1431 * time in time_interpolator->offset. A tick earlier than expected will
1432 * lead to a reset of the offset and a corresponding jump of the clock
1433 * forward. Again this only works if the interpolator clock is running
1434 * slightly slower than the regular clock and the tuning logic insures
1438 counter = time_interpolator_get_counter(1);
1439 offset = time_interpolator->offset +
1440 GET_TI_NSECS(counter, time_interpolator);
1442 if (delta_nsec < 0 || (unsigned long) delta_nsec < offset)
1443 time_interpolator->offset = offset - delta_nsec;
1445 time_interpolator->skips++;
1446 time_interpolator->ns_skipped += delta_nsec - offset;
1447 time_interpolator->offset = 0;
1449 time_interpolator->last_counter = counter;
1451 /* Tuning logic for time interpolator invoked every minute or so.
1452 * Decrease interpolator clock speed if no skips occurred and an offset is carried.
1453 * Increase interpolator clock speed if we skip too much time.
1455 if (jiffies % INTERPOLATOR_ADJUST == 0)
1457 if (time_interpolator->skips == 0 && time_interpolator->offset > TICK_NSEC)
1458 time_interpolator->nsec_per_cyc--;
1459 if (time_interpolator->ns_skipped > INTERPOLATOR_MAX_SKIP && time_interpolator->offset == 0)
1460 time_interpolator->nsec_per_cyc++;
1461 time_interpolator->skips = 0;
1462 time_interpolator->ns_skipped = 0;
1467 is_better_time_interpolator(struct time_interpolator *new)
1469 if (!time_interpolator)
1471 return new->frequency > 2*time_interpolator->frequency ||
1472 (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1476 register_time_interpolator(struct time_interpolator *ti)
1478 unsigned long flags;
1481 if (ti->frequency == 0 || ti->mask == 0)
1484 ti->nsec_per_cyc = ((u64)NSEC_PER_SEC << ti->shift) / ti->frequency;
1485 spin_lock(&time_interpolator_lock);
1486 write_seqlock_irqsave(&xtime_lock, flags);
1487 if (is_better_time_interpolator(ti)) {
1488 time_interpolator = ti;
1489 time_interpolator_reset();
1491 write_sequnlock_irqrestore(&xtime_lock, flags);
1493 ti->next = time_interpolator_list;
1494 time_interpolator_list = ti;
1495 spin_unlock(&time_interpolator_lock);
1499 unregister_time_interpolator(struct time_interpolator *ti)
1501 struct time_interpolator *curr, **prev;
1502 unsigned long flags;
1504 spin_lock(&time_interpolator_lock);
1505 prev = &time_interpolator_list;
1506 for (curr = *prev; curr; curr = curr->next) {
1514 write_seqlock_irqsave(&xtime_lock, flags);
1515 if (ti == time_interpolator) {
1516 /* we lost the best time-interpolator: */
1517 time_interpolator = NULL;
1518 /* find the next-best interpolator */
1519 for (curr = time_interpolator_list; curr; curr = curr->next)
1520 if (is_better_time_interpolator(curr))
1521 time_interpolator = curr;
1522 time_interpolator_reset();
1524 write_sequnlock_irqrestore(&xtime_lock, flags);
1525 spin_unlock(&time_interpolator_lock);
1527 #endif /* CONFIG_TIME_INTERPOLATION */
1530 * msleep - sleep safely even with waitqueue interruptions
1531 * @msecs: Time in milliseconds to sleep for
1533 void msleep(unsigned int msecs)
1535 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1538 timeout = schedule_timeout_uninterruptible(timeout);
1541 EXPORT_SYMBOL(msleep);
1544 * msleep_interruptible - sleep waiting for signals
1545 * @msecs: Time in milliseconds to sleep for
1547 unsigned long msleep_interruptible(unsigned int msecs)
1549 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1551 while (timeout && !signal_pending(current))
1552 timeout = schedule_timeout_interruptible(timeout);
1553 return jiffies_to_msecs(timeout);
1556 EXPORT_SYMBOL(msleep_interruptible);