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