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