This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / kernel / timer.c
1 /*
2  *  linux/kernel/timer.c
3  *
4  *  Kernel internal timers, kernel timekeeping, basic process system calls
5  *
6  *  Copyright (C) 1991, 1992  Linus Torvalds
7  *
8  *  1997-01-28  Modified by Finn Arne Gangstad to make timers scale better.
9  *
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
20  */
21
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>
27 #include <linux/mm.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/cpu.h>
34 #include <linux/vs_cvirt.h>
35 #include <linux/vserver/sched.h>
36
37 #include <asm/uaccess.h>
38 #include <asm/unistd.h>
39 #include <asm/div64.h>
40 #include <asm/timex.h>
41 #include <asm/io.h>
42
43 #ifdef CONFIG_TIME_INTERPOLATION
44 static void time_interpolator_update(long delta_nsec);
45 #else
46 #define time_interpolator_update(x)
47 #endif
48
49 /*
50  * per-CPU timer vector definitions:
51  */
52 #define TVN_BITS 6
53 #define TVR_BITS 8
54 #define TVN_SIZE (1 << TVN_BITS)
55 #define TVR_SIZE (1 << TVR_BITS)
56 #define TVN_MASK (TVN_SIZE - 1)
57 #define TVR_MASK (TVR_SIZE - 1)
58
59 typedef struct tvec_s {
60         struct list_head vec[TVN_SIZE];
61 } tvec_t;
62
63 typedef struct tvec_root_s {
64         struct list_head vec[TVR_SIZE];
65 } tvec_root_t;
66
67 struct tvec_t_base_s {
68         spinlock_t lock;
69         unsigned long timer_jiffies;
70         struct timer_list *running_timer;
71         tvec_root_t tv1;
72         tvec_t tv2;
73         tvec_t tv3;
74         tvec_t tv4;
75         tvec_t tv5;
76 } ____cacheline_aligned_in_smp;
77
78 typedef struct tvec_t_base_s tvec_base_t;
79
80 static inline void set_running_timer(tvec_base_t *base,
81                                         struct timer_list *timer)
82 {
83 #ifdef CONFIG_SMP
84         base->running_timer = timer;
85 #endif
86 }
87
88 /* Fake initialization */
89 static DEFINE_PER_CPU(tvec_base_t, tvec_bases) = { SPIN_LOCK_UNLOCKED };
90
91 static void check_timer_failed(struct timer_list *timer)
92 {
93         static int whine_count;
94         if (whine_count < 16) {
95                 whine_count++;
96                 printk("Uninitialised timer!\n");
97                 printk("This is just a warning.  Your computer is OK\n");
98                 printk("function=0x%p, data=0x%lx\n",
99                         timer->function, timer->data);
100                 dump_stack();
101         }
102         /*
103          * Now fix it up
104          */
105         spin_lock_init(&timer->lock);
106         timer->magic = TIMER_MAGIC;
107 }
108
109 static inline void check_timer(struct timer_list *timer)
110 {
111         if (timer->magic != TIMER_MAGIC)
112                 check_timer_failed(timer);
113 }
114
115
116 static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
117 {
118         unsigned long expires = timer->expires;
119         unsigned long idx = expires - base->timer_jiffies;
120         struct list_head *vec;
121
122         if (idx < TVR_SIZE) {
123                 int i = expires & TVR_MASK;
124                 vec = base->tv1.vec + i;
125         } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
126                 int i = (expires >> TVR_BITS) & TVN_MASK;
127                 vec = base->tv2.vec + i;
128         } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
129                 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
130                 vec = base->tv3.vec + i;
131         } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
132                 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
133                 vec = base->tv4.vec + i;
134         } else if ((signed long) idx < 0) {
135                 /*
136                  * Can happen if you add a timer with expires == jiffies,
137                  * or you set a timer to go off in the past
138                  */
139                 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
140         } else {
141                 int i;
142                 /* If the timeout is larger than 0xffffffff on 64-bit
143                  * architectures then we use the maximum timeout:
144                  */
145                 if (idx > 0xffffffffUL) {
146                         idx = 0xffffffffUL;
147                         expires = idx + base->timer_jiffies;
148                 }
149                 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
150                 vec = base->tv5.vec + i;
151         }
152         /*
153          * Timers are FIFO:
154          */
155         list_add_tail(&timer->entry, vec);
156 }
157
158 int __mod_timer(struct timer_list *timer, unsigned long expires)
159 {
160         tvec_base_t *old_base, *new_base;
161         unsigned long flags;
162         int ret = 0;
163
164         BUG_ON(!timer->function);
165
166         check_timer(timer);
167
168         spin_lock_irqsave(&timer->lock, flags);
169         new_base = &__get_cpu_var(tvec_bases);
170 repeat:
171         old_base = timer->base;
172
173         /*
174          * Prevent deadlocks via ordering by old_base < new_base.
175          */
176         if (old_base && (new_base != old_base)) {
177                 if (old_base < new_base) {
178                         spin_lock(&new_base->lock);
179                         spin_lock(&old_base->lock);
180                 } else {
181                         spin_lock(&old_base->lock);
182                         spin_lock(&new_base->lock);
183                 }
184                 /*
185                  * The timer base might have been cancelled while we were
186                  * trying to take the lock(s):
187                  */
188                 if (timer->base != old_base) {
189                         spin_unlock(&new_base->lock);
190                         spin_unlock(&old_base->lock);
191                         goto repeat;
192                 }
193         } else {
194                 spin_lock(&new_base->lock);
195                 if (timer->base != old_base) {
196                         spin_unlock(&new_base->lock);
197                         goto repeat;
198                 }
199         }
200
201         /*
202          * Delete the previous timeout (if there was any), and install
203          * the new one:
204          */
205         if (old_base) {
206                 list_del(&timer->entry);
207                 ret = 1;
208         }
209         timer->expires = expires;
210         internal_add_timer(new_base, timer);
211         timer->base = new_base;
212
213         if (old_base && (new_base != old_base))
214                 spin_unlock(&old_base->lock);
215         spin_unlock(&new_base->lock);
216         spin_unlock_irqrestore(&timer->lock, flags);
217
218         return ret;
219 }
220
221 EXPORT_SYMBOL(__mod_timer);
222
223 /***
224  * add_timer_on - start a timer on a particular CPU
225  * @timer: the timer to be added
226  * @cpu: the CPU to start it on
227  *
228  * This is not very scalable on SMP. Double adds are not possible.
229  */
230 void add_timer_on(struct timer_list *timer, int cpu)
231 {
232         tvec_base_t *base = &per_cpu(tvec_bases, cpu);
233         unsigned long flags;
234   
235         BUG_ON(timer_pending(timer) || !timer->function);
236
237         check_timer(timer);
238
239         spin_lock_irqsave(&base->lock, flags);
240         internal_add_timer(base, timer);
241         timer->base = base;
242         spin_unlock_irqrestore(&base->lock, flags);
243 }
244
245 EXPORT_SYMBOL_GPL(add_timer_on);
246
247 /***
248  * mod_timer - modify a timer's timeout
249  * @timer: the timer to be modified
250  *
251  * mod_timer is a more efficient way to update the expire field of an
252  * active timer (if the timer is inactive it will be activated)
253  *
254  * mod_timer(timer, expires) is equivalent to:
255  *
256  *     del_timer(timer); timer->expires = expires; add_timer(timer);
257  *
258  * Note that if there are multiple unserialized concurrent users of the
259  * same timer, then mod_timer() is the only safe way to modify the timeout,
260  * since add_timer() cannot modify an already running timer.
261  *
262  * The function returns whether it has modified a pending timer or not.
263  * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
264  * active timer returns 1.)
265  */
266 int mod_timer(struct timer_list *timer, unsigned long expires)
267 {
268         BUG_ON(!timer->function);
269
270         check_timer(timer);
271
272         /*
273          * This is a common optimization triggered by the
274          * networking code - if the timer is re-modified
275          * to be the same thing then just return:
276          */
277         if (timer->expires == expires && timer_pending(timer))
278                 return 1;
279
280         return __mod_timer(timer, expires);
281 }
282
283 EXPORT_SYMBOL(mod_timer);
284
285 /***
286  * del_timer - deactive a timer.
287  * @timer: the timer to be deactivated
288  *
289  * del_timer() deactivates a timer - this works on both active and inactive
290  * timers.
291  *
292  * The function returns whether it has deactivated a pending timer or not.
293  * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
294  * active timer returns 1.)
295  */
296 int del_timer(struct timer_list *timer)
297 {
298         unsigned long flags;
299         tvec_base_t *base;
300
301         check_timer(timer);
302
303 repeat:
304         base = timer->base;
305         if (!base)
306                 return 0;
307         spin_lock_irqsave(&base->lock, flags);
308         if (base != timer->base) {
309                 spin_unlock_irqrestore(&base->lock, flags);
310                 goto repeat;
311         }
312         list_del(&timer->entry);
313         smp_wmb(); /* the list del must have taken effect before timer->base
314                     * change is visible to other CPUs, or a concurrent mod_timer
315                     * would cause a race with list_add
316                     */
317         timer->base = NULL;
318         spin_unlock_irqrestore(&base->lock, flags);
319
320         return 1;
321 }
322
323 EXPORT_SYMBOL(del_timer);
324
325 #ifdef CONFIG_SMP
326 /***
327  * del_timer_sync - deactivate a timer and wait for the handler to finish.
328  * @timer: the timer to be deactivated
329  *
330  * This function only differs from del_timer() on SMP: besides deactivating
331  * the timer it also makes sure the handler has finished executing on other
332  * CPUs.
333  *
334  * Synchronization rules: callers must prevent restarting of the timer,
335  * otherwise this function is meaningless. It must not be called from
336  * interrupt contexts. The caller must not hold locks which would prevent
337  * completion of the timer's handler.  Upon exit the timer is not queued and
338  * the handler is not running on any CPU.
339  *
340  * The function returns whether it has deactivated a pending timer or not.
341  *
342  * del_timer_sync() is slow and complicated because it copes with timer
343  * handlers which re-arm the timer (periodic timers).  If the timer handler
344  * is known to not do this (a single shot timer) then use
345  * del_singleshot_timer_sync() instead.
346  */
347 int del_timer_sync(struct timer_list *timer)
348 {
349         tvec_base_t *base;
350         int i, ret = 0;
351
352         check_timer(timer);
353
354 del_again:
355         ret += del_timer(timer);
356
357         for_each_online_cpu(i) {
358                 base = &per_cpu(tvec_bases, i);
359                 if (base->running_timer == timer) {
360                         while (base->running_timer == timer) {
361                                 cpu_relax();
362                                 preempt_check_resched();
363                         }
364                         break;
365                 }
366         }
367         smp_rmb();
368         if (timer_pending(timer))
369                 goto del_again;
370
371         return ret;
372 }
373 EXPORT_SYMBOL(del_timer_sync);
374
375 /***
376  * del_singleshot_timer_sync - deactivate a non-recursive timer
377  * @timer: the timer to be deactivated
378  *
379  * This function is an optimization of del_timer_sync for the case where the
380  * caller can guarantee the timer does not reschedule itself in its timer
381  * function.
382  *
383  * Synchronization rules: callers must prevent restarting of the timer,
384  * otherwise this function is meaningless. It must not be called from
385  * interrupt contexts. The caller must not hold locks which wold prevent
386  * completion of the timer's handler.  Upon exit the timer is not queued and
387  * the handler is not running on any CPU.
388  *
389  * The function returns whether it has deactivated a pending timer or not.
390  */
391 int del_singleshot_timer_sync(struct timer_list *timer)
392 {
393         int ret = del_timer(timer);
394
395         if (!ret) {
396                 ret = del_timer_sync(timer);
397                 BUG_ON(ret);
398         }
399
400         return ret;
401 }
402 EXPORT_SYMBOL(del_singleshot_timer_sync);
403 #endif
404
405 static int cascade(tvec_base_t *base, tvec_t *tv, int index)
406 {
407         /* cascade all the timers from tv up one level */
408         struct list_head *head, *curr;
409
410         head = tv->vec + index;
411         curr = head->next;
412         /*
413          * We are removing _all_ timers from the list, so we don't  have to
414          * detach them individually, just clear the list afterwards.
415          */
416         while (curr != head) {
417                 struct timer_list *tmp;
418
419                 tmp = list_entry(curr, struct timer_list, entry);
420                 BUG_ON(tmp->base != base);
421                 curr = curr->next;
422                 internal_add_timer(base, tmp);
423         }
424         INIT_LIST_HEAD(head);
425
426         return index;
427 }
428
429 /***
430  * __run_timers - run all expired timers (if any) on this CPU.
431  * @base: the timer vector to be processed.
432  *
433  * This function cascades all vectors and executes all expired timer
434  * vectors.
435  */
436 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
437
438 static inline void __run_timers(tvec_base_t *base)
439 {
440         struct timer_list *timer;
441
442         spin_lock_irq(&base->lock);
443         while (time_after_eq(jiffies, base->timer_jiffies)) {
444                 struct list_head work_list = LIST_HEAD_INIT(work_list);
445                 struct list_head *head = &work_list;
446                 int index = base->timer_jiffies & TVR_MASK;
447  
448                 /*
449                  * Cascade timers:
450                  */
451                 if (!index &&
452                         (!cascade(base, &base->tv2, INDEX(0))) &&
453                                 (!cascade(base, &base->tv3, INDEX(1))) &&
454                                         !cascade(base, &base->tv4, INDEX(2)))
455                         cascade(base, &base->tv5, INDEX(3));
456                 ++base->timer_jiffies; 
457                 list_splice_init(base->tv1.vec + index, &work_list);
458 repeat:
459                 if (!list_empty(head)) {
460                         void (*fn)(unsigned long);
461                         unsigned long data;
462
463                         timer = list_entry(head->next,struct timer_list,entry);
464                         fn = timer->function;
465                         data = timer->data;
466
467                         list_del(&timer->entry);
468                         set_running_timer(base, timer);
469                         smp_wmb(); /* the list del must have taken effect before timer->base
470                                     * change is visible to other CPUs, or a concurrent mod_timer
471                                     * would cause a race with list_add
472                                     */
473                         timer->base = NULL;
474                         spin_unlock_irq(&base->lock);
475                         fn(data);
476                         spin_lock_irq(&base->lock);
477                         goto repeat;
478                 }
479         }
480         set_running_timer(base, NULL);
481         spin_unlock_irq(&base->lock);
482 }
483
484 #ifdef CONFIG_NO_IDLE_HZ
485 /*
486  * Find out when the next timer event is due to happen. This
487  * is used on S/390 to stop all activity when a cpus is idle.
488  * This functions needs to be called disabled.
489  */
490 unsigned long next_timer_interrupt(void)
491 {
492         tvec_base_t *base;
493         struct list_head *list;
494         struct timer_list *nte;
495         unsigned long expires;
496         tvec_t *varray[4];
497         int i, j;
498
499         base = &__get_cpu_var(tvec_bases);
500         spin_lock(&base->lock);
501         expires = base->timer_jiffies + (LONG_MAX >> 1);
502         list = 0;
503
504         /* Look for timer events in tv1. */
505         j = base->timer_jiffies & TVR_MASK;
506         do {
507                 list_for_each_entry(nte, base->tv1.vec + j, entry) {
508                         expires = nte->expires;
509                         if (j < (base->timer_jiffies & TVR_MASK))
510                                 list = base->tv2.vec + (INDEX(0));
511                         goto found;
512                 }
513                 j = (j + 1) & TVR_MASK;
514         } while (j != (base->timer_jiffies & TVR_MASK));
515
516         /* Check tv2-tv5. */
517         varray[0] = &base->tv2;
518         varray[1] = &base->tv3;
519         varray[2] = &base->tv4;
520         varray[3] = &base->tv5;
521         for (i = 0; i < 4; i++) {
522                 j = INDEX(i);
523                 do {
524                         if (list_empty(varray[i]->vec + j)) {
525                                 j = (j + 1) & TVN_MASK;
526                                 continue;
527                         }
528                         list_for_each_entry(nte, varray[i]->vec + j, entry)
529                                 if (time_before(nte->expires, expires))
530                                         expires = nte->expires;
531                         if (j < (INDEX(i)) && i < 3)
532                                 list = varray[i + 1]->vec + (INDEX(i + 1));
533                         goto found;
534                 } while (j != (INDEX(i)));
535         }
536 found:
537         if (list) {
538                 /*
539                  * The search wrapped. We need to look at the next list
540                  * from next tv element that would cascade into tv element
541                  * where we found the timer element.
542                  */
543                 list_for_each_entry(nte, list, entry) {
544                         if (time_before(nte->expires, expires))
545                                 expires = nte->expires;
546                 }
547         }
548         spin_unlock(&base->lock);
549         return expires;
550 }
551 #endif
552
553 /******************************************************************/
554
555 /*
556  * Timekeeping variables
557  */
558 unsigned long tick_usec = TICK_USEC;            /* USER_HZ period (usec) */
559 unsigned long tick_nsec = TICK_NSEC;            /* ACTHZ period (nsec) */
560
561 /* 
562  * The current time 
563  * wall_to_monotonic is what we need to add to xtime (or xtime corrected 
564  * for sub jiffie times) to get to monotonic time.  Monotonic is pegged at zero
565  * at zero at system boot time, so wall_to_monotonic will be negative,
566  * however, we will ALWAYS keep the tv_nsec part positive so we can use
567  * the usual normalization.
568  */
569 struct timespec xtime __attribute__ ((aligned (16)));
570 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
571
572 EXPORT_SYMBOL(xtime);
573
574 /* Don't completely fail for HZ > 500.  */
575 int tickadj = 500/HZ ? : 1;             /* microsecs */
576
577
578 /*
579  * phase-lock loop variables
580  */
581 /* TIME_ERROR prevents overwriting the CMOS clock */
582 int time_state = TIME_OK;               /* clock synchronization status */
583 int time_status = STA_UNSYNC;           /* clock status bits            */
584 long time_offset;                       /* time adjustment (us)         */
585 long time_constant = 2;                 /* pll time constant            */
586 long time_tolerance = MAXFREQ;          /* frequency tolerance (ppm)    */
587 long time_precision = 1;                /* clock precision (us)         */
588 long time_maxerror = NTP_PHASE_LIMIT;   /* maximum error (us)           */
589 long time_esterror = NTP_PHASE_LIMIT;   /* estimated error (us)         */
590 long time_phase;                        /* phase offset (scaled us)     */
591 long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
592                                         /* frequency offset (scaled ppm)*/
593 long time_adj;                          /* tick adjust (scaled 1 / HZ)  */
594 long time_reftime;                      /* time at last adjustment (s)  */
595 long time_adjust;
596 long time_next_adjust;
597
598 /*
599  * this routine handles the overflow of the microsecond field
600  *
601  * The tricky bits of code to handle the accurate clock support
602  * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
603  * They were originally developed for SUN and DEC kernels.
604  * All the kudos should go to Dave for this stuff.
605  *
606  */
607 static void second_overflow(void)
608 {
609     long ltemp;
610
611     /* Bump the maxerror field */
612     time_maxerror += time_tolerance >> SHIFT_USEC;
613     if ( time_maxerror > NTP_PHASE_LIMIT ) {
614         time_maxerror = NTP_PHASE_LIMIT;
615         time_status |= STA_UNSYNC;
616     }
617
618     /*
619      * Leap second processing. If in leap-insert state at
620      * the end of the day, the system clock is set back one
621      * second; if in leap-delete state, the system clock is
622      * set ahead one second. The microtime() routine or
623      * external clock driver will insure that reported time
624      * is always monotonic. The ugly divides should be
625      * replaced.
626      */
627     switch (time_state) {
628
629     case TIME_OK:
630         if (time_status & STA_INS)
631             time_state = TIME_INS;
632         else if (time_status & STA_DEL)
633             time_state = TIME_DEL;
634         break;
635
636     case TIME_INS:
637         if (xtime.tv_sec % 86400 == 0) {
638             xtime.tv_sec--;
639             wall_to_monotonic.tv_sec++;
640             /* The timer interpolator will make time change gradually instead
641              * of an immediate jump by one second.
642              */
643             time_interpolator_update(-NSEC_PER_SEC);
644             time_state = TIME_OOP;
645             clock_was_set();
646             printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
647         }
648         break;
649
650     case TIME_DEL:
651         if ((xtime.tv_sec + 1) % 86400 == 0) {
652             xtime.tv_sec++;
653             wall_to_monotonic.tv_sec--;
654             /* Use of time interpolator for a gradual change of time */
655             time_interpolator_update(NSEC_PER_SEC);
656             time_state = TIME_WAIT;
657             clock_was_set();
658             printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
659         }
660         break;
661
662     case TIME_OOP:
663         time_state = TIME_WAIT;
664         break;
665
666     case TIME_WAIT:
667         if (!(time_status & (STA_INS | STA_DEL)))
668             time_state = TIME_OK;
669     }
670
671     /*
672      * Compute the phase adjustment for the next second. In
673      * PLL mode, the offset is reduced by a fixed factor
674      * times the time constant. In FLL mode the offset is
675      * used directly. In either mode, the maximum phase
676      * adjustment for each second is clamped so as to spread
677      * the adjustment over not more than the number of
678      * seconds between updates.
679      */
680     if (time_offset < 0) {
681         ltemp = -time_offset;
682         if (!(time_status & STA_FLL))
683             ltemp >>= SHIFT_KG + time_constant;
684         if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
685             ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
686         time_offset += ltemp;
687         time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
688     } else {
689         ltemp = time_offset;
690         if (!(time_status & STA_FLL))
691             ltemp >>= SHIFT_KG + time_constant;
692         if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
693             ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
694         time_offset -= ltemp;
695         time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
696     }
697
698     /*
699      * Compute the frequency estimate and additional phase
700      * adjustment due to frequency error for the next
701      * second. When the PPS signal is engaged, gnaw on the
702      * watchdog counter and update the frequency computed by
703      * the pll and the PPS signal.
704      */
705     pps_valid++;
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);
711     }
712     ltemp = time_freq + pps_freq;
713     if (ltemp < 0)
714         time_adj -= -ltemp >>
715             (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
716     else
717         time_adj += ltemp >>
718             (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
719
720 #if HZ == 100
721     /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
722      * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
723      */
724     if (time_adj < 0)
725         time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
726     else
727         time_adj += (time_adj >> 2) + (time_adj >> 5);
728 #endif
729 #if HZ == 1000
730     /* Compensate for (HZ==1000) != (1 << SHIFT_HZ).
731      * Add 1.5625% and 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
732      */
733     if (time_adj < 0)
734         time_adj -= (-time_adj >> 6) + (-time_adj >> 7);
735     else
736         time_adj += (time_adj >> 6) + (time_adj >> 7);
737 #endif
738 }
739
740 /* in the NTP reference this is called "hardclock()" */
741 static void update_wall_time_one_tick(void)
742 {
743         long time_adjust_step, delta_nsec;
744
745         if ( (time_adjust_step = time_adjust) != 0 ) {
746             /* We are doing an adjtime thing. 
747              *
748              * Prepare time_adjust_step to be within bounds.
749              * Note that a positive time_adjust means we want the clock
750              * to run faster.
751              *
752              * Limit the amount of the step to be in the range
753              * -tickadj .. +tickadj
754              */
755              if (time_adjust > tickadj)
756                 time_adjust_step = tickadj;
757              else if (time_adjust < -tickadj)
758                 time_adjust_step = -tickadj;
759
760             /* Reduce by this step the amount of time left  */
761             time_adjust -= time_adjust_step;
762         }
763         delta_nsec = tick_nsec + time_adjust_step * 1000;
764         /*
765          * Advance the phase, once it gets to one microsecond, then
766          * advance the tick more.
767          */
768         time_phase += time_adj;
769         if (time_phase <= -FINENSEC) {
770                 long ltemp = -time_phase >> (SHIFT_SCALE - 10);
771                 time_phase += ltemp << (SHIFT_SCALE - 10);
772                 delta_nsec -= ltemp;
773         }
774         else if (time_phase >= FINENSEC) {
775                 long ltemp = time_phase >> (SHIFT_SCALE - 10);
776                 time_phase -= ltemp << (SHIFT_SCALE - 10);
777                 delta_nsec += ltemp;
778         }
779         xtime.tv_nsec += delta_nsec;
780         time_interpolator_update(delta_nsec);
781
782         /* Changes by adjtime() do not take effect till next tick. */
783         if (time_next_adjust != 0) {
784                 time_adjust = time_next_adjust;
785                 time_next_adjust = 0;
786         }
787 }
788
789 /*
790  * Using a loop looks inefficient, but "ticks" is
791  * usually just one (we shouldn't be losing ticks,
792  * we're doing this this way mainly for interrupt
793  * latency reasons, not because we think we'll
794  * have lots of lost timer ticks
795  */
796 static void update_wall_time(unsigned long ticks)
797 {
798         do {
799                 ticks--;
800                 update_wall_time_one_tick();
801                 if (xtime.tv_nsec >= 1000000000) {
802                         xtime.tv_nsec -= 1000000000;
803                         xtime.tv_sec++;
804                         second_overflow();
805                 }
806         } while (ticks);
807 }
808
809 static inline void do_process_times(struct task_struct *p,
810         unsigned long user, unsigned long system)
811 {
812         unsigned long psecs;
813
814         psecs = (p->utime += user);
815         psecs += (p->stime += system);
816         if (p->signal && !unlikely(p->state & (EXIT_DEAD|EXIT_ZOMBIE)) &&
817                         (psecs / HZ >= p->rlim[RLIMIT_CPU].rlim_cur)) {
818                 /* Send SIGXCPU every second.. */
819                 if (!(psecs % HZ))
820                         send_sig(SIGXCPU, p, 1);
821                 /* and SIGKILL when we go over max.. */
822                 if (psecs / HZ >= p->rlim[RLIMIT_CPU].rlim_max)
823                         send_sig(SIGKILL, p, 1);
824         }
825 }
826
827 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
828 {
829         unsigned long it_virt = p->it_virt_value;
830
831         if (it_virt) {
832                 it_virt -= ticks;
833                 if (!it_virt) {
834                         it_virt = p->it_virt_incr;
835                         send_sig(SIGVTALRM, p, 1);
836                 }
837                 p->it_virt_value = it_virt;
838         }
839 }
840
841 static inline void do_it_prof(struct task_struct *p)
842 {
843         unsigned long it_prof = p->it_prof_value;
844
845         if (it_prof) {
846                 if (--it_prof == 0) {
847                         it_prof = p->it_prof_incr;
848                         send_sig(SIGPROF, p, 1);
849                 }
850                 p->it_prof_value = it_prof;
851         }
852 }
853
854 static void update_one_process(struct task_struct *p, unsigned long user,
855                         unsigned long system, int cpu)
856 {
857         do_process_times(p, user, system);
858         do_it_virt(p, user);
859         do_it_prof(p);
860 }       
861
862 /*
863  * Called from the timer interrupt handler to charge one tick to the current 
864  * process.  user_tick is 1 if the tick is user time, 0 for system.
865  */
866 void update_process_times(int user_tick)
867 {
868         struct task_struct *p = current;
869         int cpu = smp_processor_id(), system = user_tick ^ 1;
870
871         update_one_process(p, user_tick, system, cpu);
872         run_local_timers();
873         scheduler_tick(user_tick, system);
874 }
875
876 /*
877  * Nr of active tasks - counted in fixed-point numbers
878  */
879 static unsigned long count_active_tasks(void)
880 {
881         return (nr_running() + nr_uninterruptible()) * FIXED_1;
882 }
883
884 /*
885  * Hmm.. Changed this, as the GNU make sources (load.c) seems to
886  * imply that avenrun[] is the standard name for this kind of thing.
887  * Nothing else seems to be standardized: the fractional size etc
888  * all seem to differ on different machines.
889  *
890  * Requires xtime_lock to access.
891  */
892 unsigned long avenrun[3];
893
894 /*
895  * calc_load - given tick count, update the avenrun load estimates.
896  * This is called while holding a write_lock on xtime_lock.
897  */
898 static inline void calc_load(unsigned long ticks)
899 {
900         unsigned long active_tasks; /* fixed-point */
901         static int count = LOAD_FREQ;
902
903         count -= ticks;
904         if (count < 0) {
905                 count += LOAD_FREQ;
906                 active_tasks = count_active_tasks();
907                 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
908                 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
909                 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
910         }
911 }
912
913 /* jiffies at the most recent update of wall time */
914 unsigned long wall_jiffies = INITIAL_JIFFIES;
915
916 /*
917  * This read-write spinlock protects us from races in SMP while
918  * playing with xtime and avenrun.
919  */
920 #ifndef ARCH_HAVE_XTIME_LOCK
921 seqlock_t xtime_lock __cacheline_aligned_in_smp = SEQLOCK_UNLOCKED;
922
923 EXPORT_SYMBOL(xtime_lock);
924 #endif
925
926 /*
927  * This function runs timers and the timer-tq in bottom half context.
928  */
929 static void run_timer_softirq(struct softirq_action *h)
930 {
931         tvec_base_t *base = &__get_cpu_var(tvec_bases);
932
933         if (time_after_eq(jiffies, base->timer_jiffies))
934                 __run_timers(base);
935 }
936
937 /*
938  * Called by the local, per-CPU timer interrupt on SMP.
939  */
940 void run_local_timers(void)
941 {
942         raise_softirq(TIMER_SOFTIRQ);
943 }
944
945 /*
946  * Called by the timer interrupt. xtime_lock must already be taken
947  * by the timer IRQ!
948  */
949 static inline void update_times(void)
950 {
951         unsigned long ticks;
952
953         ticks = jiffies - wall_jiffies;
954         if (ticks) {
955                 wall_jiffies += ticks;
956                 update_wall_time(ticks);
957         }
958         calc_load(ticks);
959 }
960   
961 /*
962  * The 64-bit jiffies value is not atomic - you MUST NOT read it
963  * without sampling the sequence number in xtime_lock.
964  * jiffies is defined in the linker script...
965  */
966
967 void do_timer(struct pt_regs *regs)
968 {
969         jiffies_64++;
970 #ifndef CONFIG_SMP
971         /* SMP process accounting uses the local APIC timer */
972
973         update_process_times(user_mode(regs));
974 #endif
975         update_times();
976 }
977
978 #ifdef __ARCH_WANT_SYS_ALARM
979
980 /*
981  * For backwards compatibility?  This can be done in libc so Alpha
982  * and all newer ports shouldn't need it.
983  */
984 asmlinkage unsigned long sys_alarm(unsigned int seconds)
985 {
986         struct itimerval it_new, it_old;
987         unsigned int oldalarm;
988
989         it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
990         it_new.it_value.tv_sec = seconds;
991         it_new.it_value.tv_usec = 0;
992         do_setitimer(ITIMER_REAL, &it_new, &it_old);
993         oldalarm = it_old.it_value.tv_sec;
994         /* ehhh.. We can't return 0 if we have an alarm pending.. */
995         /* And we'd better return too much than too little anyway */
996         if ((!oldalarm && it_old.it_value.tv_usec) || it_old.it_value.tv_usec >= 500000)
997                 oldalarm++;
998         return oldalarm;
999 }
1000
1001 #endif
1002
1003 #ifndef __alpha__
1004
1005 /*
1006  * The Alpha uses getxpid, getxuid, and getxgid instead.  Maybe this
1007  * should be moved into arch/i386 instead?
1008  */
1009
1010 /**
1011  * sys_getpid - return the thread group id of the current process
1012  *
1013  * Note, despite the name, this returns the tgid not the pid.  The tgid and
1014  * the pid are identical unless CLONE_THREAD was specified on clone() in
1015  * which case the tgid is the same in all threads of the same group.
1016  *
1017  * This is SMP safe as current->tgid does not change.
1018  */
1019 asmlinkage long sys_getpid(void)
1020 {
1021         return vx_map_tgid(current->tgid);
1022 }
1023
1024 /*
1025  * Accessing ->group_leader->real_parent is not SMP-safe, it could
1026  * change from under us. However, rather than getting any lock
1027  * we can use an optimistic algorithm: get the parent
1028  * pid, and go back and check that the parent is still
1029  * the same. If it has changed (which is extremely unlikely
1030  * indeed), we just try again..
1031  *
1032  * NOTE! This depends on the fact that even if we _do_
1033  * get an old value of "parent", we can happily dereference
1034  * the pointer (it was and remains a dereferencable kernel pointer
1035  * no matter what): we just can't necessarily trust the result
1036  * until we know that the parent pointer is valid.
1037  *
1038  * NOTE2: ->group_leader never changes from under us.
1039  */
1040 asmlinkage long sys_getppid(void)
1041 {
1042         int pid;
1043         struct task_struct *me = current;
1044         struct task_struct *parent;
1045
1046         parent = me->group_leader->real_parent;
1047         for (;;) {
1048                 pid = parent->tgid;
1049 #ifdef CONFIG_SMP
1050 {
1051                 struct task_struct *old = parent;
1052
1053                 /*
1054                  * Make sure we read the pid before re-reading the
1055                  * parent pointer:
1056                  */
1057                 rmb();
1058                 parent = me->group_leader->real_parent;
1059                 if (old != parent)
1060                         continue;
1061 }
1062 #endif
1063                 break;
1064         }
1065         return vx_map_pid(pid);
1066 }
1067
1068 asmlinkage long sys_getuid(void)
1069 {
1070         /* Only we change this so SMP safe */
1071         return current->uid;
1072 }
1073
1074 asmlinkage long sys_geteuid(void)
1075 {
1076         /* Only we change this so SMP safe */
1077         return current->euid;
1078 }
1079
1080 asmlinkage long sys_getgid(void)
1081 {
1082         /* Only we change this so SMP safe */
1083         return current->gid;
1084 }
1085
1086 asmlinkage long sys_getegid(void)
1087 {
1088         /* Only we change this so SMP safe */
1089         return  current->egid;
1090 }
1091
1092 #endif
1093
1094 static void process_timeout(unsigned long __data)
1095 {
1096         wake_up_process((task_t *)__data);
1097 }
1098
1099 /**
1100  * schedule_timeout - sleep until timeout
1101  * @timeout: timeout value in jiffies
1102  *
1103  * Make the current task sleep until @timeout jiffies have
1104  * elapsed. The routine will return immediately unless
1105  * the current task state has been set (see set_current_state()).
1106  *
1107  * You can set the task state as follows -
1108  *
1109  * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1110  * pass before the routine returns. The routine will return 0
1111  *
1112  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1113  * delivered to the current task. In this case the remaining time
1114  * in jiffies will be returned, or 0 if the timer expired in time
1115  *
1116  * The current task state is guaranteed to be TASK_RUNNING when this
1117  * routine returns.
1118  *
1119  * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1120  * the CPU away without a bound on the timeout. In this case the return
1121  * value will be %MAX_SCHEDULE_TIMEOUT.
1122  *
1123  * In all cases the return value is guaranteed to be non-negative.
1124  */
1125 fastcall signed long __sched schedule_timeout(signed long timeout)
1126 {
1127         struct timer_list timer;
1128         unsigned long expire;
1129
1130         switch (timeout)
1131         {
1132         case MAX_SCHEDULE_TIMEOUT:
1133                 /*
1134                  * These two special cases are useful to be comfortable
1135                  * in the caller. Nothing more. We could take
1136                  * MAX_SCHEDULE_TIMEOUT from one of the negative value
1137                  * but I' d like to return a valid offset (>=0) to allow
1138                  * the caller to do everything it want with the retval.
1139                  */
1140                 schedule();
1141                 goto out;
1142         default:
1143                 /*
1144                  * Another bit of PARANOID. Note that the retval will be
1145                  * 0 since no piece of kernel is supposed to do a check
1146                  * for a negative retval of schedule_timeout() (since it
1147                  * should never happens anyway). You just have the printk()
1148                  * that will tell you if something is gone wrong and where.
1149                  */
1150                 if (timeout < 0)
1151                 {
1152                         printk(KERN_ERR "schedule_timeout: wrong timeout "
1153                                "value %lx from %p\n", timeout,
1154                                __builtin_return_address(0));
1155                         current->state = TASK_RUNNING;
1156                         goto out;
1157                 }
1158         }
1159
1160         expire = timeout + jiffies;
1161
1162         init_timer(&timer);
1163         timer.expires = expire;
1164         timer.data = (unsigned long) current;
1165         timer.function = process_timeout;
1166
1167         add_timer(&timer);
1168         schedule();
1169         del_singleshot_timer_sync(&timer);
1170
1171         timeout = expire - jiffies;
1172
1173  out:
1174         return timeout < 0 ? 0 : timeout;
1175 }
1176
1177 EXPORT_SYMBOL(schedule_timeout);
1178
1179 /* Thread ID - the internal kernel "pid" */
1180 asmlinkage long sys_gettid(void)
1181 {
1182         return current->pid;
1183 }
1184
1185 static long __sched nanosleep_restart(struct restart_block *restart)
1186 {
1187         unsigned long expire = restart->arg0, now = jiffies;
1188         struct timespec __user *rmtp = (struct timespec __user *) restart->arg1;
1189         long ret;
1190
1191         /* Did it expire while we handled signals? */
1192         if (!time_after(expire, now))
1193                 return 0;
1194
1195         current->state = TASK_INTERRUPTIBLE;
1196         expire = schedule_timeout(expire - now);
1197
1198         ret = 0;
1199         if (expire) {
1200                 struct timespec t;
1201                 jiffies_to_timespec(expire, &t);
1202
1203                 ret = -ERESTART_RESTARTBLOCK;
1204                 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1205                         ret = -EFAULT;
1206                 /* The 'restart' block is already filled in */
1207         }
1208         return ret;
1209 }
1210
1211 asmlinkage long sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1212 {
1213         struct timespec t;
1214         unsigned long expire;
1215         long ret;
1216
1217         if (copy_from_user(&t, rqtp, sizeof(t)))
1218                 return -EFAULT;
1219
1220         if ((t.tv_nsec >= 1000000000L) || (t.tv_nsec < 0) || (t.tv_sec < 0))
1221                 return -EINVAL;
1222
1223         expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1224         current->state = TASK_INTERRUPTIBLE;
1225         expire = schedule_timeout(expire);
1226
1227         ret = 0;
1228         if (expire) {
1229                 struct restart_block *restart;
1230                 jiffies_to_timespec(expire, &t);
1231                 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1232                         return -EFAULT;
1233
1234                 restart = &current_thread_info()->restart_block;
1235                 restart->fn = nanosleep_restart;
1236                 restart->arg0 = jiffies + expire;
1237                 restart->arg1 = (unsigned long) rmtp;
1238                 ret = -ERESTART_RESTARTBLOCK;
1239         }
1240         return ret;
1241 }
1242
1243 /*
1244  * sys_sysinfo - fill in sysinfo struct
1245  */ 
1246 asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1247 {
1248         struct sysinfo val;
1249         unsigned long mem_total, sav_total;
1250         unsigned int mem_unit, bitcount;
1251         unsigned long seq;
1252
1253         memset((char *)&val, 0, sizeof(struct sysinfo));
1254
1255         do {
1256                 struct timespec tp;
1257                 seq = read_seqbegin(&xtime_lock);
1258
1259                 /*
1260                  * This is annoying.  The below is the same thing
1261                  * posix_get_clock_monotonic() does, but it wants to
1262                  * take the lock which we want to cover the loads stuff
1263                  * too.
1264                  */
1265
1266                 getnstimeofday(&tp);
1267                 tp.tv_sec += wall_to_monotonic.tv_sec;
1268                 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1269                 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1270                         tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1271                         tp.tv_sec++;
1272                 }
1273                 if (vx_flags(VXF_VIRT_UPTIME, 0))
1274                         vx_vsi_uptime(&tp, NULL);
1275                 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1276
1277                 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1278                 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1279                 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1280
1281                 val.procs = nr_threads;
1282         } while (read_seqretry(&xtime_lock, seq));
1283
1284 /*      if (vx_flags(VXF_VIRT_CPU, 0))
1285                 vx_vsi_cpu(val);
1286 */
1287         si_meminfo(&val);
1288         si_swapinfo(&val);
1289
1290         /*
1291          * If the sum of all the available memory (i.e. ram + swap)
1292          * is less than can be stored in a 32 bit unsigned long then
1293          * we can be binary compatible with 2.2.x kernels.  If not,
1294          * well, in that case 2.2.x was broken anyways...
1295          *
1296          *  -Erik Andersen <andersee@debian.org>
1297          */
1298
1299         mem_total = val.totalram + val.totalswap;
1300         if (mem_total < val.totalram || mem_total < val.totalswap)
1301                 goto out;
1302         bitcount = 0;
1303         mem_unit = val.mem_unit;
1304         while (mem_unit > 1) {
1305                 bitcount++;
1306                 mem_unit >>= 1;
1307                 sav_total = mem_total;
1308                 mem_total <<= 1;
1309                 if (mem_total < sav_total)
1310                         goto out;
1311         }
1312
1313         /*
1314          * If mem_total did not overflow, multiply all memory values by
1315          * val.mem_unit and set it to 1.  This leaves things compatible
1316          * with 2.2.x, and also retains compatibility with earlier 2.4.x
1317          * kernels...
1318          */
1319
1320         val.mem_unit = 1;
1321         val.totalram <<= bitcount;
1322         val.freeram <<= bitcount;
1323         val.sharedram <<= bitcount;
1324         val.bufferram <<= bitcount;
1325         val.totalswap <<= bitcount;
1326         val.freeswap <<= bitcount;
1327         val.totalhigh <<= bitcount;
1328         val.freehigh <<= bitcount;
1329
1330  out:
1331         if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1332                 return -EFAULT;
1333
1334         return 0;
1335 }
1336
1337 static void __devinit init_timers_cpu(int cpu)
1338 {
1339         int j;
1340         tvec_base_t *base;
1341        
1342         base = &per_cpu(tvec_bases, cpu);
1343         spin_lock_init(&base->lock);
1344         for (j = 0; j < TVN_SIZE; j++) {
1345                 INIT_LIST_HEAD(base->tv5.vec + j);
1346                 INIT_LIST_HEAD(base->tv4.vec + j);
1347                 INIT_LIST_HEAD(base->tv3.vec + j);
1348                 INIT_LIST_HEAD(base->tv2.vec + j);
1349         }
1350         for (j = 0; j < TVR_SIZE; j++)
1351                 INIT_LIST_HEAD(base->tv1.vec + j);
1352
1353         base->timer_jiffies = jiffies;
1354 }
1355
1356 #ifdef CONFIG_HOTPLUG_CPU
1357 static int migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
1358 {
1359         struct timer_list *timer;
1360
1361         while (!list_empty(head)) {
1362                 timer = list_entry(head->next, struct timer_list, entry);
1363                 /* We're locking backwards from __mod_timer order here,
1364                    beware deadlock. */
1365                 if (!spin_trylock(&timer->lock))
1366                         return 0;
1367                 list_del(&timer->entry);
1368                 internal_add_timer(new_base, timer);
1369                 timer->base = new_base;
1370                 spin_unlock(&timer->lock);
1371         }
1372         return 1;
1373 }
1374
1375 static void __devinit migrate_timers(int cpu)
1376 {
1377         tvec_base_t *old_base;
1378         tvec_base_t *new_base;
1379         int i;
1380
1381         BUG_ON(cpu_online(cpu));
1382         old_base = &per_cpu(tvec_bases, cpu);
1383         new_base = &get_cpu_var(tvec_bases);
1384
1385         local_irq_disable();
1386 again:
1387         /* Prevent deadlocks via ordering by old_base < new_base. */
1388         if (old_base < new_base) {
1389                 spin_lock(&new_base->lock);
1390                 spin_lock(&old_base->lock);
1391         } else {
1392                 spin_lock(&old_base->lock);
1393                 spin_lock(&new_base->lock);
1394         }
1395
1396         if (old_base->running_timer)
1397                 BUG();
1398         for (i = 0; i < TVR_SIZE; i++)
1399                 if (!migrate_timer_list(new_base, old_base->tv1.vec + i))
1400                         goto unlock_again;
1401         for (i = 0; i < TVN_SIZE; i++)
1402                 if (!migrate_timer_list(new_base, old_base->tv2.vec + i)
1403                     || !migrate_timer_list(new_base, old_base->tv3.vec + i)
1404                     || !migrate_timer_list(new_base, old_base->tv4.vec + i)
1405                     || !migrate_timer_list(new_base, old_base->tv5.vec + i))
1406                         goto unlock_again;
1407         spin_unlock(&old_base->lock);
1408         spin_unlock(&new_base->lock);
1409         local_irq_enable();
1410         put_cpu_var(tvec_bases);
1411         return;
1412
1413 unlock_again:
1414         /* Avoid deadlock with __mod_timer, by backing off. */
1415         spin_unlock(&old_base->lock);
1416         spin_unlock(&new_base->lock);
1417         cpu_relax();
1418         goto again;
1419 }
1420 #endif /* CONFIG_HOTPLUG_CPU */
1421
1422 static int __devinit timer_cpu_notify(struct notifier_block *self, 
1423                                 unsigned long action, void *hcpu)
1424 {
1425         long cpu = (long)hcpu;
1426         switch(action) {
1427         case CPU_UP_PREPARE:
1428                 init_timers_cpu(cpu);
1429                 break;
1430 #ifdef CONFIG_HOTPLUG_CPU
1431         case CPU_DEAD:
1432                 migrate_timers(cpu);
1433                 break;
1434 #endif
1435         default:
1436                 break;
1437         }
1438         return NOTIFY_OK;
1439 }
1440
1441 static struct notifier_block __devinitdata timers_nb = {
1442         .notifier_call  = timer_cpu_notify,
1443 };
1444
1445
1446 void __init init_timers(void)
1447 {
1448         timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1449                                 (void *)(long)smp_processor_id());
1450         register_cpu_notifier(&timers_nb);
1451         open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1452 }
1453
1454 #ifdef CONFIG_TIME_INTERPOLATION
1455
1456 struct time_interpolator *time_interpolator;
1457 static struct time_interpolator *time_interpolator_list;
1458 static spinlock_t time_interpolator_lock = SPIN_LOCK_UNLOCKED;
1459
1460 static inline u64 time_interpolator_get_cycles(unsigned int src)
1461 {
1462         unsigned long (*x)(void);
1463
1464         switch (src)
1465         {
1466                 case TIME_SOURCE_FUNCTION:
1467                         x = time_interpolator->addr;
1468                         return x();
1469
1470                 case TIME_SOURCE_MMIO64 :
1471                         return readq(time_interpolator->addr);
1472
1473                 case TIME_SOURCE_MMIO32 :
1474                         return readl(time_interpolator->addr);
1475
1476                 default: return get_cycles();
1477         }
1478 }
1479
1480 static inline u64 time_interpolator_get_counter(void)
1481 {
1482         unsigned int src = time_interpolator->source;
1483
1484         if (time_interpolator->jitter)
1485         {
1486                 u64 lcycle;
1487                 u64 now;
1488
1489                 do {
1490                         lcycle = time_interpolator->last_cycle;
1491                         now = time_interpolator_get_cycles(src);
1492                         if (lcycle && time_after(lcycle, now))
1493                                 return lcycle;
1494                         /* Keep track of the last timer value returned. The use of cmpxchg here
1495                          * will cause contention in an SMP environment.
1496                          */
1497                 } while (unlikely(cmpxchg(&time_interpolator->last_cycle, lcycle, now) != lcycle));
1498                 return now;
1499         }
1500         else
1501                 return time_interpolator_get_cycles(src);
1502 }
1503
1504 void time_interpolator_reset(void)
1505 {
1506         time_interpolator->offset = 0;
1507         time_interpolator->last_counter = time_interpolator_get_counter();
1508 }
1509
1510 #define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
1511
1512 unsigned long time_interpolator_get_offset(void)
1513 {
1514         /* If we do not have a time interpolator set up then just return zero */
1515         if (!time_interpolator)
1516                 return 0;
1517
1518         return time_interpolator->offset +
1519                 GET_TI_NSECS(time_interpolator_get_counter(), time_interpolator);
1520 }
1521
1522 #define INTERPOLATOR_ADJUST 65536
1523 #define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
1524
1525 static void time_interpolator_update(long delta_nsec)
1526 {
1527         u64 counter;
1528         unsigned long offset;
1529
1530         /* If there is no time interpolator set up then do nothing */
1531         if (!time_interpolator)
1532                 return;
1533
1534         /* The interpolator compensates for late ticks by accumulating
1535          * the late time in time_interpolator->offset. A tick earlier than
1536          * expected will lead to a reset of the offset and a corresponding
1537          * jump of the clock forward. Again this only works if the
1538          * interpolator clock is running slightly slower than the regular clock
1539          * and the tuning logic insures that.
1540          */
1541
1542         counter = time_interpolator_get_counter();
1543         offset = time_interpolator->offset + GET_TI_NSECS(counter, time_interpolator);
1544
1545         if (delta_nsec < 0 || (unsigned long) delta_nsec < offset)
1546                 time_interpolator->offset = offset - delta_nsec;
1547         else {
1548                 time_interpolator->skips++;
1549                 time_interpolator->ns_skipped += delta_nsec - offset;
1550                 time_interpolator->offset = 0;
1551         }
1552         time_interpolator->last_counter = counter;
1553
1554         /* Tuning logic for time interpolator invoked every minute or so.
1555          * Decrease interpolator clock speed if no skips occurred and an offset is carried.
1556          * Increase interpolator clock speed if we skip too much time.
1557          */
1558         if (jiffies % INTERPOLATOR_ADJUST == 0)
1559         {
1560                 if (time_interpolator->skips == 0 && time_interpolator->offset > TICK_NSEC)
1561                         time_interpolator->nsec_per_cyc--;
1562                 if (time_interpolator->ns_skipped > INTERPOLATOR_MAX_SKIP && time_interpolator->offset == 0)
1563                         time_interpolator->nsec_per_cyc++;
1564                 time_interpolator->skips = 0;
1565                 time_interpolator->ns_skipped = 0;
1566         }
1567 }
1568
1569 static inline int
1570 is_better_time_interpolator(struct time_interpolator *new)
1571 {
1572         if (!time_interpolator)
1573                 return 1;
1574         return new->frequency > 2*time_interpolator->frequency ||
1575             (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1576 }
1577
1578 void
1579 register_time_interpolator(struct time_interpolator *ti)
1580 {
1581         unsigned long flags;
1582
1583         /* Sanity check */
1584         if (ti->frequency == 0 || ti->mask == 0)
1585                 BUG();
1586
1587         ti->nsec_per_cyc = ((u64)NSEC_PER_SEC << ti->shift) / ti->frequency;
1588         spin_lock(&time_interpolator_lock);
1589         write_seqlock_irqsave(&xtime_lock, flags);
1590         if (is_better_time_interpolator(ti)) {
1591                 time_interpolator = ti;
1592                 time_interpolator_reset();
1593         }
1594         write_sequnlock_irqrestore(&xtime_lock, flags);
1595
1596         ti->next = time_interpolator_list;
1597         time_interpolator_list = ti;
1598         spin_unlock(&time_interpolator_lock);
1599 }
1600
1601 void
1602 unregister_time_interpolator(struct time_interpolator *ti)
1603 {
1604         struct time_interpolator *curr, **prev;
1605         unsigned long flags;
1606
1607         spin_lock(&time_interpolator_lock);
1608         prev = &time_interpolator_list;
1609         for (curr = *prev; curr; curr = curr->next) {
1610                 if (curr == ti) {
1611                         *prev = curr->next;
1612                         break;
1613                 }
1614                 prev = &curr->next;
1615         }
1616
1617         write_seqlock_irqsave(&xtime_lock, flags);
1618         if (ti == time_interpolator) {
1619                 /* we lost the best time-interpolator: */
1620                 time_interpolator = NULL;
1621                 /* find the next-best interpolator */
1622                 for (curr = time_interpolator_list; curr; curr = curr->next)
1623                         if (is_better_time_interpolator(curr))
1624                                 time_interpolator = curr;
1625                 time_interpolator_reset();
1626         }
1627         write_sequnlock_irqrestore(&xtime_lock, flags);
1628         spin_unlock(&time_interpolator_lock);
1629 }
1630 #endif /* CONFIG_TIME_INTERPOLATION */
1631
1632 /**
1633  * msleep - sleep safely even with waitqueue interruptions
1634  * @msecs: Time in milliseconds to sleep for
1635  */
1636 void msleep(unsigned int msecs)
1637 {
1638         unsigned long timeout = msecs_to_jiffies(msecs);
1639
1640         while (timeout) {
1641                 set_current_state(TASK_UNINTERRUPTIBLE);
1642                 timeout = schedule_timeout(timeout);
1643         }
1644 }
1645
1646 EXPORT_SYMBOL(msleep);
1647
1648 /**
1649  * msleep_interruptible - sleep waiting for waitqueue interruptions
1650  * @msecs: Time in milliseconds to sleep for
1651  */
1652 unsigned long msleep_interruptible(unsigned int msecs)
1653 {
1654         unsigned long timeout = msecs_to_jiffies(msecs);
1655
1656         while (timeout && !signal_pending(current)) {
1657                 set_current_state(TASK_INTERRUPTIBLE);
1658                 timeout = schedule_timeout(timeout);
1659         }
1660         return jiffies_to_msecs(timeout);
1661 }
1662
1663 EXPORT_SYMBOL(msleep_interruptible);