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