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>
37 #include <asm/uaccess.h>
38 #include <asm/unistd.h>
39 #include <asm/div64.h>
40 #include <asm/timex.h>
43 #ifdef CONFIG_TIME_INTERPOLATION
44 static void time_interpolator_update(long delta_nsec);
46 #define time_interpolator_update(x)
50 * per-CPU timer vector definitions:
53 #define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
54 #define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
55 #define TVN_SIZE (1 << TVN_BITS)
56 #define TVR_SIZE (1 << TVR_BITS)
57 #define TVN_MASK (TVN_SIZE - 1)
58 #define TVR_MASK (TVR_SIZE - 1)
62 struct timer_list *running_timer;
65 typedef struct tvec_s {
66 struct list_head vec[TVN_SIZE];
69 typedef struct tvec_root_s {
70 struct list_head vec[TVR_SIZE];
73 struct tvec_t_base_s {
74 struct timer_base_s t_base;
75 unsigned long timer_jiffies;
81 } ____cacheline_aligned_in_smp;
83 typedef struct tvec_t_base_s tvec_base_t;
84 static DEFINE_PER_CPU(tvec_base_t, tvec_bases);
86 static inline void set_running_timer(tvec_base_t *base,
87 struct timer_list *timer)
90 base->t_base.running_timer = timer;
94 static void check_timer_failed(struct timer_list *timer)
96 static int whine_count;
97 if (whine_count < 16) {
99 printk("Uninitialised timer!\n");
100 printk("This is just a warning. Your computer is OK\n");
101 printk("function=0x%p, data=0x%lx\n",
102 timer->function, timer->data);
108 timer->magic = TIMER_MAGIC;
111 static inline void check_timer(struct timer_list *timer)
113 if (timer->magic != TIMER_MAGIC)
114 check_timer_failed(timer);
118 static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
120 unsigned long expires = timer->expires;
121 unsigned long idx = expires - base->timer_jiffies;
122 struct list_head *vec;
124 if (idx < TVR_SIZE) {
125 int i = expires & TVR_MASK;
126 vec = base->tv1.vec + i;
127 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
128 int i = (expires >> TVR_BITS) & TVN_MASK;
129 vec = base->tv2.vec + i;
130 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
131 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
132 vec = base->tv3.vec + i;
133 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
134 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
135 vec = base->tv4.vec + i;
136 } else if ((signed long) idx < 0) {
138 * Can happen if you add a timer with expires == jiffies,
139 * or you set a timer to go off in the past
141 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
144 /* If the timeout is larger than 0xffffffff on 64-bit
145 * architectures then we use the maximum timeout:
147 if (idx > 0xffffffffUL) {
149 expires = idx + base->timer_jiffies;
151 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
152 vec = base->tv5.vec + i;
157 list_add_tail(&timer->entry, vec);
160 typedef struct timer_base_s timer_base_t;
162 * Used by TIMER_INITIALIZER, we can't use per_cpu(tvec_bases)
163 * at compile time, and we need timer->base to lock the timer.
165 timer_base_t __init_timer_base
166 ____cacheline_aligned_in_smp = { .lock = SPIN_LOCK_UNLOCKED };
167 EXPORT_SYMBOL(__init_timer_base);
170 * init_timer - initialize a timer.
171 * @timer: the timer to be initialized
173 * init_timer() must be done to a timer prior calling *any* of the
174 * other timer functions.
176 void fastcall init_timer(struct timer_list *timer)
178 timer->entry.next = NULL;
179 timer->base = &per_cpu(tvec_bases, raw_smp_processor_id()).t_base;
180 timer->magic = TIMER_MAGIC;
182 EXPORT_SYMBOL(init_timer);
184 static inline void detach_timer(struct timer_list *timer,
187 struct list_head *entry = &timer->entry;
189 __list_del(entry->prev, entry->next);
192 entry->prev = LIST_POISON2;
196 * We are using hashed locking: holding per_cpu(tvec_bases).t_base.lock
197 * means that all timers which are tied to this base via timer->base are
198 * locked, and the base itself is locked too.
200 * So __run_timers/migrate_timers can safely modify all timers which could
201 * be found on ->tvX lists.
203 * When the timer's base is locked, and the timer removed from list, it is
204 * possible to set timer->base = NULL and drop the lock: the timer remains
207 static timer_base_t *lock_timer_base(struct timer_list *timer,
208 unsigned long *flags)
214 if (likely(base != NULL)) {
215 spin_lock_irqsave(&base->lock, *flags);
216 if (likely(base == timer->base))
218 /* The timer has migrated to another CPU */
219 spin_unlock_irqrestore(&base->lock, *flags);
225 int __mod_timer(struct timer_list *timer, unsigned long expires)
228 tvec_base_t *new_base;
232 BUG_ON(!timer->function);
235 base = lock_timer_base(timer, &flags);
237 if (timer_pending(timer)) {
238 detach_timer(timer, 0);
242 new_base = &__get_cpu_var(tvec_bases);
244 if (base != &new_base->t_base) {
246 * We are trying to schedule the timer on the local CPU.
247 * However we can't change timer's base while it is running,
248 * otherwise del_timer_sync() can't detect that the timer's
249 * handler yet has not finished. This also guarantees that
250 * the timer is serialized wrt itself.
252 if (unlikely(base->running_timer == timer)) {
253 /* The timer remains on a former base */
254 new_base = container_of(base, tvec_base_t, t_base);
256 /* See the comment in lock_timer_base() */
258 spin_unlock(&base->lock);
259 spin_lock(&new_base->t_base.lock);
260 timer->base = &new_base->t_base;
264 timer->expires = expires;
265 internal_add_timer(new_base, timer);
266 spin_unlock_irqrestore(&new_base->t_base.lock, flags);
271 EXPORT_SYMBOL(__mod_timer);
274 * add_timer_on - start a timer on a particular CPU
275 * @timer: the timer to be added
276 * @cpu: the CPU to start it on
278 * This is not very scalable on SMP. Double adds are not possible.
280 void add_timer_on(struct timer_list *timer, int cpu)
282 tvec_base_t *base = &per_cpu(tvec_bases, cpu);
285 BUG_ON(timer_pending(timer) || !timer->function);
289 spin_lock_irqsave(&base->t_base.lock, flags);
290 timer->base = &base->t_base;
291 internal_add_timer(base, timer);
292 spin_unlock_irqrestore(&base->t_base.lock, flags);
297 * mod_timer - modify a timer's timeout
298 * @timer: the timer to be modified
300 * mod_timer is a more efficient way to update the expire field of an
301 * active timer (if the timer is inactive it will be activated)
303 * mod_timer(timer, expires) is equivalent to:
305 * del_timer(timer); timer->expires = expires; add_timer(timer);
307 * Note that if there are multiple unserialized concurrent users of the
308 * same timer, then mod_timer() is the only safe way to modify the timeout,
309 * since add_timer() cannot modify an already running timer.
311 * The function returns whether it has modified a pending timer or not.
312 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
313 * active timer returns 1.)
315 int mod_timer(struct timer_list *timer, unsigned long expires)
317 BUG_ON(!timer->function);
322 * This is a common optimization triggered by the
323 * networking code - if the timer is re-modified
324 * to be the same thing then just return:
326 if (timer->expires == expires && timer_pending(timer))
329 return __mod_timer(timer, expires);
332 EXPORT_SYMBOL(mod_timer);
335 * del_timer - deactive a timer.
336 * @timer: the timer to be deactivated
338 * del_timer() deactivates a timer - this works on both active and inactive
341 * The function returns whether it has deactivated a pending timer or not.
342 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
343 * active timer returns 1.)
345 int del_timer(struct timer_list *timer)
353 if (timer_pending(timer)) {
354 base = lock_timer_base(timer, &flags);
355 if (timer_pending(timer)) {
356 detach_timer(timer, 1);
359 spin_unlock_irqrestore(&base->lock, flags);
365 EXPORT_SYMBOL(del_timer);
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)
394 base = lock_timer_base(timer, &flags);
396 if (base->running_timer == timer)
400 if (timer_pending(timer)) {
401 detach_timer(timer, 1);
405 spin_unlock_irqrestore(&base->lock, flags);
411 EXPORT_SYMBOL(del_timer_sync);
414 static int cascade(tvec_base_t *base, tvec_t *tv, int index)
416 /* cascade all the timers from tv up one level */
417 struct list_head *head, *curr;
419 head = tv->vec + index;
422 * We are removing _all_ timers from the list, so we don't have to
423 * detach them individually, just clear the list afterwards.
425 while (curr != head) {
426 struct timer_list *tmp;
428 tmp = list_entry(curr, struct timer_list, entry);
429 BUG_ON(tmp->base != &base->t_base);
431 internal_add_timer(base, tmp);
433 INIT_LIST_HEAD(head);
439 * __run_timers - run all expired timers (if any) on this CPU.
440 * @base: the timer vector to be processed.
442 * This function cascades all vectors and executes all expired timer
445 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
447 static inline void __run_timers(tvec_base_t *base)
449 struct timer_list *timer;
451 spin_lock_irq(&base->t_base.lock);
452 while (time_after_eq(jiffies, base->timer_jiffies)) {
453 struct list_head work_list = LIST_HEAD_INIT(work_list);
454 struct list_head *head = &work_list;
455 int index = base->timer_jiffies & TVR_MASK;
461 (!cascade(base, &base->tv2, INDEX(0))) &&
462 (!cascade(base, &base->tv3, INDEX(1))) &&
463 !cascade(base, &base->tv4, INDEX(2)))
464 cascade(base, &base->tv5, INDEX(3));
465 ++base->timer_jiffies;
466 list_splice_init(base->tv1.vec + index, &work_list);
467 while (!list_empty(head)) {
468 void (*fn)(unsigned long);
471 timer = list_entry(head->next,struct timer_list,entry);
472 fn = timer->function;
475 set_running_timer(base, timer);
476 detach_timer(timer, 1);
477 spin_unlock_irq(&base->t_base.lock);
479 u32 preempt_count = preempt_count();
481 if (preempt_count != preempt_count()) {
482 printk("huh, entered %p with %08x, exited with %08x?\n", fn, preempt_count, preempt_count());
486 spin_lock_irq(&base->t_base.lock);
489 set_running_timer(base, NULL);
490 spin_unlock_irq(&base->t_base.lock);
493 #ifdef CONFIG_NO_IDLE_HZ
495 * Find out when the next timer event is due to happen. This
496 * is used on S/390 to stop all activity when a cpus is idle.
497 * This functions needs to be called disabled.
499 unsigned long next_timer_interrupt(void)
502 struct list_head *list;
503 struct timer_list *nte;
504 unsigned long expires;
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);
562 /******************************************************************/
565 * Timekeeping variables
567 unsigned long tick_usec = TICK_USEC; /* USER_HZ period (usec) */
568 unsigned long tick_nsec = TICK_NSEC; /* ACTHZ period (nsec) */
572 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
573 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
574 * at zero at system boot time, so wall_to_monotonic will be negative,
575 * however, we will ALWAYS keep the tv_nsec part positive so we can use
576 * the usual normalization.
578 struct timespec xtime __attribute__ ((aligned (16)));
579 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
581 EXPORT_SYMBOL(xtime);
583 /* Don't completely fail for HZ > 500. */
584 int tickadj = 500/HZ ? : 1; /* microsecs */
588 * phase-lock loop variables
590 /* TIME_ERROR prevents overwriting the CMOS clock */
591 int time_state = TIME_OK; /* clock synchronization status */
592 int time_status = STA_UNSYNC; /* clock status bits */
593 long time_offset; /* time adjustment (us) */
594 long time_constant = 2; /* pll time constant */
595 long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
596 long time_precision = 1; /* clock precision (us) */
597 long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
598 long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
599 static long time_phase; /* phase offset (scaled us) */
600 long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
601 /* frequency offset (scaled ppm)*/
602 static long time_adj; /* tick adjust (scaled 1 / HZ) */
603 long time_reftime; /* time at last adjustment (s) */
605 long time_next_adjust;
608 * this routine handles the overflow of the microsecond field
610 * The tricky bits of code to handle the accurate clock support
611 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
612 * They were originally developed for SUN and DEC kernels.
613 * All the kudos should go to Dave for this stuff.
616 static void second_overflow(void)
620 /* Bump the maxerror field */
621 time_maxerror += time_tolerance >> SHIFT_USEC;
622 if ( time_maxerror > NTP_PHASE_LIMIT ) {
623 time_maxerror = NTP_PHASE_LIMIT;
624 time_status |= STA_UNSYNC;
628 * Leap second processing. If in leap-insert state at
629 * the end of the day, the system clock is set back one
630 * second; if in leap-delete state, the system clock is
631 * set ahead one second. The microtime() routine or
632 * external clock driver will insure that reported time
633 * is always monotonic. The ugly divides should be
636 switch (time_state) {
639 if (time_status & STA_INS)
640 time_state = TIME_INS;
641 else if (time_status & STA_DEL)
642 time_state = TIME_DEL;
646 if (xtime.tv_sec % 86400 == 0) {
648 wall_to_monotonic.tv_sec++;
649 /* The timer interpolator will make time change gradually instead
650 * of an immediate jump by one second.
652 time_interpolator_update(-NSEC_PER_SEC);
653 time_state = TIME_OOP;
655 printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
660 if ((xtime.tv_sec + 1) % 86400 == 0) {
662 wall_to_monotonic.tv_sec--;
663 /* Use of time interpolator for a gradual change of time */
664 time_interpolator_update(NSEC_PER_SEC);
665 time_state = TIME_WAIT;
667 printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
672 time_state = TIME_WAIT;
676 if (!(time_status & (STA_INS | STA_DEL)))
677 time_state = TIME_OK;
681 * Compute the phase adjustment for the next second. In
682 * PLL mode, the offset is reduced by a fixed factor
683 * times the time constant. In FLL mode the offset is
684 * used directly. In either mode, the maximum phase
685 * adjustment for each second is clamped so as to spread
686 * the adjustment over not more than the number of
687 * seconds between updates.
689 if (time_offset < 0) {
690 ltemp = -time_offset;
691 if (!(time_status & STA_FLL))
692 ltemp >>= SHIFT_KG + time_constant;
693 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
694 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
695 time_offset += ltemp;
696 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
699 if (!(time_status & STA_FLL))
700 ltemp >>= SHIFT_KG + time_constant;
701 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
702 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
703 time_offset -= ltemp;
704 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
708 * Compute the frequency estimate and additional phase
709 * adjustment due to frequency error for the next
710 * second. When the PPS signal is engaged, gnaw on the
711 * watchdog counter and update the frequency computed by
712 * the pll and the PPS signal.
715 if (pps_valid == PPS_VALID) { /* PPS signal lost */
716 pps_jitter = MAXTIME;
717 pps_stabil = MAXFREQ;
718 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
719 STA_PPSWANDER | STA_PPSERROR);
721 ltemp = time_freq + pps_freq;
723 time_adj -= -ltemp >>
724 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
727 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
730 /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
731 * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
734 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
736 time_adj += (time_adj >> 2) + (time_adj >> 5);
739 /* Compensate for (HZ==1000) != (1 << SHIFT_HZ).
740 * Add 1.5625% and 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
743 time_adj -= (-time_adj >> 6) + (-time_adj >> 7);
745 time_adj += (time_adj >> 6) + (time_adj >> 7);
749 /* in the NTP reference this is called "hardclock()" */
750 static void update_wall_time_one_tick(void)
752 long time_adjust_step, delta_nsec;
754 if ( (time_adjust_step = time_adjust) != 0 ) {
755 /* We are doing an adjtime thing.
757 * Prepare time_adjust_step to be within bounds.
758 * Note that a positive time_adjust means we want the clock
761 * Limit the amount of the step to be in the range
762 * -tickadj .. +tickadj
764 if (time_adjust > tickadj)
765 time_adjust_step = tickadj;
766 else if (time_adjust < -tickadj)
767 time_adjust_step = -tickadj;
769 /* Reduce by this step the amount of time left */
770 time_adjust -= time_adjust_step;
772 delta_nsec = tick_nsec + time_adjust_step * 1000;
774 * Advance the phase, once it gets to one microsecond, then
775 * advance the tick more.
777 time_phase += time_adj;
778 if (time_phase <= -FINENSEC) {
779 long ltemp = -time_phase >> (SHIFT_SCALE - 10);
780 time_phase += ltemp << (SHIFT_SCALE - 10);
783 else if (time_phase >= FINENSEC) {
784 long ltemp = time_phase >> (SHIFT_SCALE - 10);
785 time_phase -= ltemp << (SHIFT_SCALE - 10);
788 xtime.tv_nsec += delta_nsec;
789 time_interpolator_update(delta_nsec);
791 /* Changes by adjtime() do not take effect till next tick. */
792 if (time_next_adjust != 0) {
793 time_adjust = time_next_adjust;
794 time_next_adjust = 0;
799 * Using a loop looks inefficient, but "ticks" is
800 * usually just one (we shouldn't be losing ticks,
801 * we're doing this this way mainly for interrupt
802 * latency reasons, not because we think we'll
803 * have lots of lost timer ticks
805 static void update_wall_time(unsigned long ticks)
809 update_wall_time_one_tick();
810 if (xtime.tv_nsec >= 1000000000) {
811 xtime.tv_nsec -= 1000000000;
819 * Called from the timer interrupt handler to charge one tick to the current
820 * process. user_tick is 1 if the tick is user time, 0 for system.
822 void update_process_times(int user_tick)
824 struct task_struct *p = current;
825 int cpu = smp_processor_id();
827 /* Note: this timer irq context must be accounted for as well. */
829 account_user_time(p, jiffies_to_cputime(1));
831 account_system_time(p, HARDIRQ_OFFSET, jiffies_to_cputime(1));
833 if (rcu_pending(cpu))
834 rcu_check_callbacks(cpu, user_tick);
836 run_posix_cpu_timers(p);
840 * Nr of active tasks - counted in fixed-point numbers
842 static unsigned long count_active_tasks(void)
844 return (nr_running() + nr_uninterruptible()) * FIXED_1;
848 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
849 * imply that avenrun[] is the standard name for this kind of thing.
850 * Nothing else seems to be standardized: the fractional size etc
851 * all seem to differ on different machines.
853 * Requires xtime_lock to access.
855 unsigned long avenrun[3];
857 EXPORT_SYMBOL(avenrun);
860 * calc_load - given tick count, update the avenrun load estimates.
861 * This is called while holding a write_lock on xtime_lock.
863 static inline void calc_load(unsigned long ticks)
865 unsigned long active_tasks; /* fixed-point */
866 static int count = LOAD_FREQ;
871 active_tasks = count_active_tasks();
872 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
873 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
874 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
878 /* jiffies at the most recent update of wall time */
879 unsigned long wall_jiffies = INITIAL_JIFFIES;
882 * This read-write spinlock protects us from races in SMP while
883 * playing with xtime and avenrun.
885 #ifndef ARCH_HAVE_XTIME_LOCK
886 seqlock_t xtime_lock __cacheline_aligned_in_smp = SEQLOCK_UNLOCKED;
888 EXPORT_SYMBOL(xtime_lock);
892 * This function runs timers and the timer-tq in bottom half context.
894 static void run_timer_softirq(struct softirq_action *h)
896 tvec_base_t *base = &__get_cpu_var(tvec_bases);
898 if (time_after_eq(jiffies, base->timer_jiffies))
903 * Called by the local, per-CPU timer interrupt on SMP.
905 void run_local_timers(void)
907 raise_softirq(TIMER_SOFTIRQ);
911 * Called by the timer interrupt. xtime_lock must already be taken
914 static inline void update_times(void)
918 ticks = jiffies - wall_jiffies;
920 wall_jiffies += ticks;
921 update_wall_time(ticks);
927 * The 64-bit jiffies value is not atomic - you MUST NOT read it
928 * without sampling the sequence number in xtime_lock.
929 * jiffies is defined in the linker script...
932 void do_timer(struct pt_regs *regs)
938 #ifdef __ARCH_WANT_SYS_ALARM
941 * For backwards compatibility? This can be done in libc so Alpha
942 * and all newer ports shouldn't need it.
944 asmlinkage unsigned long sys_alarm(unsigned int seconds)
946 struct itimerval it_new, it_old;
947 unsigned int oldalarm;
949 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
950 it_new.it_value.tv_sec = seconds;
951 it_new.it_value.tv_usec = 0;
952 do_setitimer(ITIMER_REAL, &it_new, &it_old);
953 oldalarm = it_old.it_value.tv_sec;
954 /* ehhh.. We can't return 0 if we have an alarm pending.. */
955 /* And we'd better return too much than too little anyway */
956 if ((!oldalarm && it_old.it_value.tv_usec) || it_old.it_value.tv_usec >= 500000)
966 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
967 * should be moved into arch/i386 instead?
971 * sys_getpid - return the thread group id of the current process
973 * Note, despite the name, this returns the tgid not the pid. The tgid and
974 * the pid are identical unless CLONE_THREAD was specified on clone() in
975 * which case the tgid is the same in all threads of the same group.
977 * This is SMP safe as current->tgid does not change.
979 asmlinkage long sys_getpid(void)
981 return current->tgid;
985 * Accessing ->group_leader->real_parent is not SMP-safe, it could
986 * change from under us. However, rather than getting any lock
987 * we can use an optimistic algorithm: get the parent
988 * pid, and go back and check that the parent is still
989 * the same. If it has changed (which is extremely unlikely
990 * indeed), we just try again..
992 * NOTE! This depends on the fact that even if we _do_
993 * get an old value of "parent", we can happily dereference
994 * the pointer (it was and remains a dereferencable kernel pointer
995 * no matter what): we just can't necessarily trust the result
996 * until we know that the parent pointer is valid.
998 * NOTE2: ->group_leader never changes from under us.
1000 asmlinkage long sys_getppid(void)
1003 struct task_struct *me = current;
1004 struct task_struct *parent;
1006 parent = me->group_leader->real_parent;
1011 struct task_struct *old = parent;
1014 * Make sure we read the pid before re-reading the
1018 parent = me->group_leader->real_parent;
1028 asmlinkage long sys_getuid(void)
1030 /* Only we change this so SMP safe */
1031 return current->uid;
1034 asmlinkage long sys_geteuid(void)
1036 /* Only we change this so SMP safe */
1037 return current->euid;
1040 asmlinkage long sys_getgid(void)
1042 /* Only we change this so SMP safe */
1043 return current->gid;
1046 asmlinkage long sys_getegid(void)
1048 /* Only we change this so SMP safe */
1049 return current->egid;
1054 static void process_timeout(unsigned long __data)
1056 wake_up_process((task_t *)__data);
1060 * schedule_timeout - sleep until timeout
1061 * @timeout: timeout value in jiffies
1063 * Make the current task sleep until @timeout jiffies have
1064 * elapsed. The routine will return immediately unless
1065 * the current task state has been set (see set_current_state()).
1067 * You can set the task state as follows -
1069 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1070 * pass before the routine returns. The routine will return 0
1072 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1073 * delivered to the current task. In this case the remaining time
1074 * in jiffies will be returned, or 0 if the timer expired in time
1076 * The current task state is guaranteed to be TASK_RUNNING when this
1079 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1080 * the CPU away without a bound on the timeout. In this case the return
1081 * value will be %MAX_SCHEDULE_TIMEOUT.
1083 * In all cases the return value is guaranteed to be non-negative.
1085 fastcall signed long __sched schedule_timeout(signed long timeout)
1087 struct timer_list timer;
1088 unsigned long expire;
1092 case MAX_SCHEDULE_TIMEOUT:
1094 * These two special cases are useful to be comfortable
1095 * in the caller. Nothing more. We could take
1096 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1097 * but I' d like to return a valid offset (>=0) to allow
1098 * the caller to do everything it want with the retval.
1104 * Another bit of PARANOID. Note that the retval will be
1105 * 0 since no piece of kernel is supposed to do a check
1106 * for a negative retval of schedule_timeout() (since it
1107 * should never happens anyway). You just have the printk()
1108 * that will tell you if something is gone wrong and where.
1112 printk(KERN_ERR "schedule_timeout: wrong timeout "
1113 "value %lx from %p\n", timeout,
1114 __builtin_return_address(0));
1115 current->state = TASK_RUNNING;
1120 expire = timeout + jiffies;
1123 timer.expires = expire;
1124 timer.data = (unsigned long) current;
1125 timer.function = process_timeout;
1129 del_singleshot_timer_sync(&timer);
1131 timeout = expire - jiffies;
1134 return timeout < 0 ? 0 : timeout;
1137 EXPORT_SYMBOL(schedule_timeout);
1139 /* Thread ID - the internal kernel "pid" */
1140 asmlinkage long sys_gettid(void)
1142 return current->pid;
1145 static long __sched nanosleep_restart(struct restart_block *restart)
1147 unsigned long expire = restart->arg0, now = jiffies;
1148 struct timespec __user *rmtp = (struct timespec __user *) restart->arg1;
1151 /* Did it expire while we handled signals? */
1152 if (!time_after(expire, now))
1155 current->state = TASK_INTERRUPTIBLE;
1156 expire = schedule_timeout(expire - now);
1161 jiffies_to_timespec(expire, &t);
1163 ret = -ERESTART_RESTARTBLOCK;
1164 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1166 /* The 'restart' block is already filled in */
1171 asmlinkage long sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1174 unsigned long expire;
1177 if (copy_from_user(&t, rqtp, sizeof(t)))
1180 if ((t.tv_nsec >= 1000000000L) || (t.tv_nsec < 0) || (t.tv_sec < 0))
1183 expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1184 current->state = TASK_INTERRUPTIBLE;
1185 expire = schedule_timeout(expire);
1189 struct restart_block *restart;
1190 jiffies_to_timespec(expire, &t);
1191 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1194 restart = ¤t_thread_info()->restart_block;
1195 restart->fn = nanosleep_restart;
1196 restart->arg0 = jiffies + expire;
1197 restart->arg1 = (unsigned long) rmtp;
1198 ret = -ERESTART_RESTARTBLOCK;
1204 * sys_sysinfo - fill in sysinfo struct
1206 asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1209 unsigned long mem_total, sav_total;
1210 unsigned int mem_unit, bitcount;
1213 memset((char *)&val, 0, sizeof(struct sysinfo));
1217 seq = read_seqbegin(&xtime_lock);
1220 * This is annoying. The below is the same thing
1221 * posix_get_clock_monotonic() does, but it wants to
1222 * take the lock which we want to cover the loads stuff
1226 getnstimeofday(&tp);
1227 tp.tv_sec += wall_to_monotonic.tv_sec;
1228 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1229 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1230 tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1233 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1235 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1236 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1237 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1239 val.procs = nr_threads;
1240 } while (read_seqretry(&xtime_lock, seq));
1246 * If the sum of all the available memory (i.e. ram + swap)
1247 * is less than can be stored in a 32 bit unsigned long then
1248 * we can be binary compatible with 2.2.x kernels. If not,
1249 * well, in that case 2.2.x was broken anyways...
1251 * -Erik Andersen <andersee@debian.org>
1254 mem_total = val.totalram + val.totalswap;
1255 if (mem_total < val.totalram || mem_total < val.totalswap)
1258 mem_unit = val.mem_unit;
1259 while (mem_unit > 1) {
1262 sav_total = mem_total;
1264 if (mem_total < sav_total)
1269 * If mem_total did not overflow, multiply all memory values by
1270 * val.mem_unit and set it to 1. This leaves things compatible
1271 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1276 val.totalram <<= bitcount;
1277 val.freeram <<= bitcount;
1278 val.sharedram <<= bitcount;
1279 val.bufferram <<= bitcount;
1280 val.totalswap <<= bitcount;
1281 val.freeswap <<= bitcount;
1282 val.totalhigh <<= bitcount;
1283 val.freehigh <<= bitcount;
1286 if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1292 static void __devinit init_timers_cpu(int cpu)
1297 base = &per_cpu(tvec_bases, cpu);
1298 spin_lock_init(&base->t_base.lock);
1299 for (j = 0; j < TVN_SIZE; j++) {
1300 INIT_LIST_HEAD(base->tv5.vec + j);
1301 INIT_LIST_HEAD(base->tv4.vec + j);
1302 INIT_LIST_HEAD(base->tv3.vec + j);
1303 INIT_LIST_HEAD(base->tv2.vec + j);
1305 for (j = 0; j < TVR_SIZE; j++)
1306 INIT_LIST_HEAD(base->tv1.vec + j);
1308 base->timer_jiffies = jiffies;
1311 #ifdef CONFIG_HOTPLUG_CPU
1312 static void migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
1314 struct timer_list *timer;
1316 while (!list_empty(head)) {
1317 timer = list_entry(head->next, struct timer_list, entry);
1318 detach_timer(timer, 0);
1319 timer->base = &new_base->t_base;
1320 internal_add_timer(new_base, timer);
1324 static void __devinit migrate_timers(int cpu)
1326 tvec_base_t *old_base;
1327 tvec_base_t *new_base;
1330 BUG_ON(cpu_online(cpu));
1331 old_base = &per_cpu(tvec_bases, cpu);
1332 new_base = &get_cpu_var(tvec_bases);
1334 local_irq_disable();
1335 spin_lock(&new_base->t_base.lock);
1336 spin_lock(&old_base->t_base.lock);
1338 if (old_base->t_base.running_timer)
1340 for (i = 0; i < TVR_SIZE; i++)
1341 migrate_timer_list(new_base, old_base->tv1.vec + i);
1342 for (i = 0; i < TVN_SIZE; i++) {
1343 migrate_timer_list(new_base, old_base->tv2.vec + i);
1344 migrate_timer_list(new_base, old_base->tv3.vec + i);
1345 migrate_timer_list(new_base, old_base->tv4.vec + i);
1346 migrate_timer_list(new_base, old_base->tv5.vec + i);
1349 spin_unlock(&old_base->t_base.lock);
1350 spin_unlock(&new_base->t_base.lock);
1352 put_cpu_var(tvec_bases);
1354 #endif /* CONFIG_HOTPLUG_CPU */
1356 static int __devinit timer_cpu_notify(struct notifier_block *self,
1357 unsigned long action, void *hcpu)
1359 long cpu = (long)hcpu;
1361 case CPU_UP_PREPARE:
1362 init_timers_cpu(cpu);
1364 #ifdef CONFIG_HOTPLUG_CPU
1366 migrate_timers(cpu);
1375 static struct notifier_block __devinitdata timers_nb = {
1376 .notifier_call = timer_cpu_notify,
1380 void __init init_timers(void)
1382 timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1383 (void *)(long)smp_processor_id());
1384 register_cpu_notifier(&timers_nb);
1385 open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1388 #ifdef CONFIG_TIME_INTERPOLATION
1390 struct time_interpolator *time_interpolator;
1391 static struct time_interpolator *time_interpolator_list;
1392 static DEFINE_SPINLOCK(time_interpolator_lock);
1394 static inline u64 time_interpolator_get_cycles(unsigned int src)
1396 unsigned long (*x)(void);
1400 case TIME_SOURCE_FUNCTION:
1401 x = time_interpolator->addr;
1404 case TIME_SOURCE_MMIO64 :
1405 return readq((void __iomem *) time_interpolator->addr);
1407 case TIME_SOURCE_MMIO32 :
1408 return readl((void __iomem *) time_interpolator->addr);
1410 default: return get_cycles();
1414 static inline u64 time_interpolator_get_counter(void)
1416 unsigned int src = time_interpolator->source;
1418 if (time_interpolator->jitter)
1424 lcycle = time_interpolator->last_cycle;
1425 now = time_interpolator_get_cycles(src);
1426 if (lcycle && time_after(lcycle, now))
1428 /* Keep track of the last timer value returned. The use of cmpxchg here
1429 * will cause contention in an SMP environment.
1431 } while (unlikely(cmpxchg(&time_interpolator->last_cycle, lcycle, now) != lcycle));
1435 return time_interpolator_get_cycles(src);
1438 void time_interpolator_reset(void)
1440 time_interpolator->offset = 0;
1441 time_interpolator->last_counter = time_interpolator_get_counter();
1444 #define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
1446 unsigned long time_interpolator_get_offset(void)
1448 /* If we do not have a time interpolator set up then just return zero */
1449 if (!time_interpolator)
1452 return time_interpolator->offset +
1453 GET_TI_NSECS(time_interpolator_get_counter(), time_interpolator);
1456 #define INTERPOLATOR_ADJUST 65536
1457 #define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
1459 static void time_interpolator_update(long delta_nsec)
1462 unsigned long offset;
1464 /* If there is no time interpolator set up then do nothing */
1465 if (!time_interpolator)
1468 /* The interpolator compensates for late ticks by accumulating
1469 * the late time in time_interpolator->offset. A tick earlier than
1470 * expected will lead to a reset of the offset and a corresponding
1471 * jump of the clock forward. Again this only works if the
1472 * interpolator clock is running slightly slower than the regular clock
1473 * and the tuning logic insures that.
1476 counter = time_interpolator_get_counter();
1477 offset = time_interpolator->offset + GET_TI_NSECS(counter, time_interpolator);
1479 if (delta_nsec < 0 || (unsigned long) delta_nsec < offset)
1480 time_interpolator->offset = offset - delta_nsec;
1482 time_interpolator->skips++;
1483 time_interpolator->ns_skipped += delta_nsec - offset;
1484 time_interpolator->offset = 0;
1486 time_interpolator->last_counter = counter;
1488 /* Tuning logic for time interpolator invoked every minute or so.
1489 * Decrease interpolator clock speed if no skips occurred and an offset is carried.
1490 * Increase interpolator clock speed if we skip too much time.
1492 if (jiffies % INTERPOLATOR_ADJUST == 0)
1494 if (time_interpolator->skips == 0 && time_interpolator->offset > TICK_NSEC)
1495 time_interpolator->nsec_per_cyc--;
1496 if (time_interpolator->ns_skipped > INTERPOLATOR_MAX_SKIP && time_interpolator->offset == 0)
1497 time_interpolator->nsec_per_cyc++;
1498 time_interpolator->skips = 0;
1499 time_interpolator->ns_skipped = 0;
1504 is_better_time_interpolator(struct time_interpolator *new)
1506 if (!time_interpolator)
1508 return new->frequency > 2*time_interpolator->frequency ||
1509 (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1513 register_time_interpolator(struct time_interpolator *ti)
1515 unsigned long flags;
1518 if (ti->frequency == 0 || ti->mask == 0)
1521 ti->nsec_per_cyc = ((u64)NSEC_PER_SEC << ti->shift) / ti->frequency;
1522 spin_lock(&time_interpolator_lock);
1523 write_seqlock_irqsave(&xtime_lock, flags);
1524 if (is_better_time_interpolator(ti)) {
1525 time_interpolator = ti;
1526 time_interpolator_reset();
1528 write_sequnlock_irqrestore(&xtime_lock, flags);
1530 ti->next = time_interpolator_list;
1531 time_interpolator_list = ti;
1532 spin_unlock(&time_interpolator_lock);
1536 unregister_time_interpolator(struct time_interpolator *ti)
1538 struct time_interpolator *curr, **prev;
1539 unsigned long flags;
1541 spin_lock(&time_interpolator_lock);
1542 prev = &time_interpolator_list;
1543 for (curr = *prev; curr; curr = curr->next) {
1551 write_seqlock_irqsave(&xtime_lock, flags);
1552 if (ti == time_interpolator) {
1553 /* we lost the best time-interpolator: */
1554 time_interpolator = NULL;
1555 /* find the next-best interpolator */
1556 for (curr = time_interpolator_list; curr; curr = curr->next)
1557 if (is_better_time_interpolator(curr))
1558 time_interpolator = curr;
1559 time_interpolator_reset();
1561 write_sequnlock_irqrestore(&xtime_lock, flags);
1562 spin_unlock(&time_interpolator_lock);
1564 #endif /* CONFIG_TIME_INTERPOLATION */
1567 * msleep - sleep safely even with waitqueue interruptions
1568 * @msecs: Time in milliseconds to sleep for
1570 void msleep(unsigned int msecs)
1572 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1575 set_current_state(TASK_UNINTERRUPTIBLE);
1576 timeout = schedule_timeout(timeout);
1580 EXPORT_SYMBOL(msleep);
1583 * msleep_interruptible - sleep waiting for waitqueue interruptions
1584 * @msecs: Time in milliseconds to sleep for
1586 unsigned long msleep_interruptible(unsigned int msecs)
1588 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1590 while (timeout && !signal_pending(current)) {
1591 set_current_state(TASK_INTERRUPTIBLE);
1592 timeout = schedule_timeout(timeout);
1594 return jiffies_to_msecs(timeout);
1597 EXPORT_SYMBOL(msleep_interruptible);