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