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