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