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