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