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