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