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