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