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