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