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