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