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