blob: 6c9fa80088eda58a3203c2a5616738894bfcb9f3 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
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>
Adrian Bunk97a41e22006-01-08 01:02:17 -080036#include <linux/delay.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070037
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
Thomas Gleixnerecea8d12005-10-30 15:03:00 -080050u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
51
52EXPORT_SYMBOL(jiffies_64);
53
Linus Torvalds1da177e2005-04-16 15:20:36 -070054/*
55 * per-CPU timer vector definitions:
56 */
Linus Torvalds1da177e2005-04-16 15:20:36 -070057#define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
58#define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
59#define TVN_SIZE (1 << TVN_BITS)
60#define TVR_SIZE (1 << TVR_BITS)
61#define TVN_MASK (TVN_SIZE - 1)
62#define TVR_MASK (TVR_SIZE - 1)
63
64typedef struct tvec_s {
65 struct list_head vec[TVN_SIZE];
66} tvec_t;
67
68typedef struct tvec_root_s {
69 struct list_head vec[TVR_SIZE];
70} tvec_root_t;
71
72struct tvec_t_base_s {
Oleg Nesterov3691c512006-03-31 02:30:30 -080073 spinlock_t lock;
74 struct timer_list *running_timer;
Linus Torvalds1da177e2005-04-16 15:20:36 -070075 unsigned long timer_jiffies;
Linus Torvalds1da177e2005-04-16 15:20:36 -070076 tvec_root_t tv1;
77 tvec_t tv2;
78 tvec_t tv3;
79 tvec_t tv4;
80 tvec_t tv5;
81} ____cacheline_aligned_in_smp;
82
83typedef struct tvec_t_base_s tvec_base_t;
Andrew Mortonba6edfc2006-04-10 22:53:58 -070084
Oleg Nesterov3691c512006-03-31 02:30:30 -080085tvec_base_t boot_tvec_bases;
86EXPORT_SYMBOL(boot_tvec_bases);
Josh Triplett51d8c5e2006-07-30 03:04:14 -070087static DEFINE_PER_CPU(tvec_base_t *, tvec_bases) = &boot_tvec_bases;
Linus Torvalds1da177e2005-04-16 15:20:36 -070088
89static inline void set_running_timer(tvec_base_t *base,
90 struct timer_list *timer)
91{
92#ifdef CONFIG_SMP
Oleg Nesterov3691c512006-03-31 02:30:30 -080093 base->running_timer = timer;
Linus Torvalds1da177e2005-04-16 15:20:36 -070094#endif
95}
96
Linus Torvalds1da177e2005-04-16 15:20:36 -070097static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
98{
99 unsigned long expires = timer->expires;
100 unsigned long idx = expires - base->timer_jiffies;
101 struct list_head *vec;
102
103 if (idx < TVR_SIZE) {
104 int i = expires & TVR_MASK;
105 vec = base->tv1.vec + i;
106 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
107 int i = (expires >> TVR_BITS) & TVN_MASK;
108 vec = base->tv2.vec + i;
109 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
110 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
111 vec = base->tv3.vec + i;
112 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
113 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
114 vec = base->tv4.vec + i;
115 } else if ((signed long) idx < 0) {
116 /*
117 * Can happen if you add a timer with expires == jiffies,
118 * or you set a timer to go off in the past
119 */
120 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
121 } else {
122 int i;
123 /* If the timeout is larger than 0xffffffff on 64-bit
124 * architectures then we use the maximum timeout:
125 */
126 if (idx > 0xffffffffUL) {
127 idx = 0xffffffffUL;
128 expires = idx + base->timer_jiffies;
129 }
130 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
131 vec = base->tv5.vec + i;
132 }
133 /*
134 * Timers are FIFO:
135 */
136 list_add_tail(&timer->entry, vec);
137}
138
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700139/***
140 * init_timer - initialize a timer.
141 * @timer: the timer to be initialized
142 *
143 * init_timer() must be done to a timer prior calling *any* of the
144 * other timer functions.
145 */
146void fastcall init_timer(struct timer_list *timer)
147{
148 timer->entry.next = NULL;
Paul Mackerrasbfe5d832006-06-25 05:47:14 -0700149 timer->base = __raw_get_cpu_var(tvec_bases);
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700150}
151EXPORT_SYMBOL(init_timer);
152
153static inline void detach_timer(struct timer_list *timer,
154 int clear_pending)
155{
156 struct list_head *entry = &timer->entry;
157
158 __list_del(entry->prev, entry->next);
159 if (clear_pending)
160 entry->next = NULL;
161 entry->prev = LIST_POISON2;
162}
163
164/*
Oleg Nesterov3691c512006-03-31 02:30:30 -0800165 * We are using hashed locking: holding per_cpu(tvec_bases).lock
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700166 * means that all timers which are tied to this base via timer->base are
167 * locked, and the base itself is locked too.
168 *
169 * So __run_timers/migrate_timers can safely modify all timers which could
170 * be found on ->tvX lists.
171 *
172 * When the timer's base is locked, and the timer removed from list, it is
173 * possible to set timer->base = NULL and drop the lock: the timer remains
174 * locked.
175 */
Oleg Nesterov3691c512006-03-31 02:30:30 -0800176static tvec_base_t *lock_timer_base(struct timer_list *timer,
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700177 unsigned long *flags)
Josh Triplett89e7e3742006-09-29 01:59:36 -0700178 __acquires(timer->base->lock)
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700179{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800180 tvec_base_t *base;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700181
182 for (;;) {
183 base = timer->base;
184 if (likely(base != NULL)) {
185 spin_lock_irqsave(&base->lock, *flags);
186 if (likely(base == timer->base))
187 return base;
188 /* The timer has migrated to another CPU */
189 spin_unlock_irqrestore(&base->lock, *flags);
190 }
191 cpu_relax();
192 }
193}
194
Linus Torvalds1da177e2005-04-16 15:20:36 -0700195int __mod_timer(struct timer_list *timer, unsigned long expires)
196{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800197 tvec_base_t *base, *new_base;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700198 unsigned long flags;
199 int ret = 0;
200
201 BUG_ON(!timer->function);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700202
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700203 base = lock_timer_base(timer, &flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700204
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700205 if (timer_pending(timer)) {
206 detach_timer(timer, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700207 ret = 1;
208 }
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700209
Jan Beulicha4a61982006-03-24 03:15:54 -0800210 new_base = __get_cpu_var(tvec_bases);
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700211
Oleg Nesterov3691c512006-03-31 02:30:30 -0800212 if (base != new_base) {
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700213 /*
214 * We are trying to schedule the timer on the local CPU.
215 * However we can't change timer's base while it is running,
216 * otherwise del_timer_sync() can't detect that the timer's
217 * handler yet has not finished. This also guarantees that
218 * the timer is serialized wrt itself.
219 */
Oleg Nesterova2c348f2006-03-31 02:30:31 -0800220 if (likely(base->running_timer != timer)) {
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700221 /* See the comment in lock_timer_base() */
222 timer->base = NULL;
223 spin_unlock(&base->lock);
Oleg Nesterova2c348f2006-03-31 02:30:31 -0800224 base = new_base;
225 spin_lock(&base->lock);
226 timer->base = base;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700227 }
228 }
229
Linus Torvalds1da177e2005-04-16 15:20:36 -0700230 timer->expires = expires;
Oleg Nesterova2c348f2006-03-31 02:30:31 -0800231 internal_add_timer(base, timer);
232 spin_unlock_irqrestore(&base->lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700233
234 return ret;
235}
236
237EXPORT_SYMBOL(__mod_timer);
238
239/***
240 * add_timer_on - start a timer on a particular CPU
241 * @timer: the timer to be added
242 * @cpu: the CPU to start it on
243 *
244 * This is not very scalable on SMP. Double adds are not possible.
245 */
246void add_timer_on(struct timer_list *timer, int cpu)
247{
Jan Beulicha4a61982006-03-24 03:15:54 -0800248 tvec_base_t *base = per_cpu(tvec_bases, cpu);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700249 unsigned long flags;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700250
Linus Torvalds1da177e2005-04-16 15:20:36 -0700251 BUG_ON(timer_pending(timer) || !timer->function);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800252 spin_lock_irqsave(&base->lock, flags);
253 timer->base = base;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700254 internal_add_timer(base, timer);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800255 spin_unlock_irqrestore(&base->lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700256}
257
258
259/***
260 * mod_timer - modify a timer's timeout
261 * @timer: the timer to be modified
262 *
263 * mod_timer is a more efficient way to update the expire field of an
264 * active timer (if the timer is inactive it will be activated)
265 *
266 * mod_timer(timer, expires) is equivalent to:
267 *
268 * del_timer(timer); timer->expires = expires; add_timer(timer);
269 *
270 * Note that if there are multiple unserialized concurrent users of the
271 * same timer, then mod_timer() is the only safe way to modify the timeout,
272 * since add_timer() cannot modify an already running timer.
273 *
274 * The function returns whether it has modified a pending timer or not.
275 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
276 * active timer returns 1.)
277 */
278int mod_timer(struct timer_list *timer, unsigned long expires)
279{
280 BUG_ON(!timer->function);
281
Linus Torvalds1da177e2005-04-16 15:20:36 -0700282 /*
283 * This is a common optimization triggered by the
284 * networking code - if the timer is re-modified
285 * to be the same thing then just return:
286 */
287 if (timer->expires == expires && timer_pending(timer))
288 return 1;
289
290 return __mod_timer(timer, expires);
291}
292
293EXPORT_SYMBOL(mod_timer);
294
295/***
296 * del_timer - deactive a timer.
297 * @timer: the timer to be deactivated
298 *
299 * del_timer() deactivates a timer - this works on both active and inactive
300 * timers.
301 *
302 * The function returns whether it has deactivated a pending timer or not.
303 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
304 * active timer returns 1.)
305 */
306int del_timer(struct timer_list *timer)
307{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800308 tvec_base_t *base;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700309 unsigned long flags;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700310 int ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700311
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700312 if (timer_pending(timer)) {
313 base = lock_timer_base(timer, &flags);
314 if (timer_pending(timer)) {
315 detach_timer(timer, 1);
316 ret = 1;
317 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700318 spin_unlock_irqrestore(&base->lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700319 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700320
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700321 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700322}
323
324EXPORT_SYMBOL(del_timer);
325
326#ifdef CONFIG_SMP
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700327/*
328 * This function tries to deactivate a timer. Upon successful (ret >= 0)
329 * exit the timer is not queued and the handler is not running on any CPU.
330 *
331 * It must not be called from interrupt contexts.
332 */
333int try_to_del_timer_sync(struct timer_list *timer)
334{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800335 tvec_base_t *base;
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700336 unsigned long flags;
337 int ret = -1;
338
339 base = lock_timer_base(timer, &flags);
340
341 if (base->running_timer == timer)
342 goto out;
343
344 ret = 0;
345 if (timer_pending(timer)) {
346 detach_timer(timer, 1);
347 ret = 1;
348 }
349out:
350 spin_unlock_irqrestore(&base->lock, flags);
351
352 return ret;
353}
354
Linus Torvalds1da177e2005-04-16 15:20:36 -0700355/***
356 * del_timer_sync - deactivate a timer and wait for the handler to finish.
357 * @timer: the timer to be deactivated
358 *
359 * This function only differs from del_timer() on SMP: besides deactivating
360 * the timer it also makes sure the handler has finished executing on other
361 * CPUs.
362 *
363 * Synchronization rules: callers must prevent restarting of the timer,
364 * otherwise this function is meaningless. It must not be called from
365 * interrupt contexts. The caller must not hold locks which would prevent
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700366 * completion of the timer's handler. The timer's handler must not call
367 * add_timer_on(). Upon exit the timer is not queued and the handler is
368 * not running on any CPU.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700369 *
370 * The function returns whether it has deactivated a pending timer or not.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700371 */
372int del_timer_sync(struct timer_list *timer)
373{
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700374 for (;;) {
375 int ret = try_to_del_timer_sync(timer);
376 if (ret >= 0)
377 return ret;
Andrew Mortona0009652006-07-14 00:24:06 -0700378 cpu_relax();
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700379 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700380}
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700381
Linus Torvalds1da177e2005-04-16 15:20:36 -0700382EXPORT_SYMBOL(del_timer_sync);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700383#endif
384
385static int cascade(tvec_base_t *base, tvec_t *tv, int index)
386{
387 /* cascade all the timers from tv up one level */
Porpoise3439dd82006-06-23 02:05:56 -0700388 struct timer_list *timer, *tmp;
389 struct list_head tv_list;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700390
Porpoise3439dd82006-06-23 02:05:56 -0700391 list_replace_init(tv->vec + index, &tv_list);
392
Linus Torvalds1da177e2005-04-16 15:20:36 -0700393 /*
Porpoise3439dd82006-06-23 02:05:56 -0700394 * We are removing _all_ timers from the list, so we
395 * don't have to detach them individually.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700396 */
Porpoise3439dd82006-06-23 02:05:56 -0700397 list_for_each_entry_safe(timer, tmp, &tv_list, entry) {
398 BUG_ON(timer->base != base);
399 internal_add_timer(base, timer);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700400 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700401
402 return index;
403}
404
405/***
406 * __run_timers - run all expired timers (if any) on this CPU.
407 * @base: the timer vector to be processed.
408 *
409 * This function cascades all vectors and executes all expired timer
410 * vectors.
411 */
Steven Rostedt6ea24f92006-07-30 03:03:38 -0700412#define INDEX(N) ((base->timer_jiffies >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700413
414static inline void __run_timers(tvec_base_t *base)
415{
416 struct timer_list *timer;
417
Oleg Nesterov3691c512006-03-31 02:30:30 -0800418 spin_lock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700419 while (time_after_eq(jiffies, base->timer_jiffies)) {
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700420 struct list_head work_list;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700421 struct list_head *head = &work_list;
422 int index = base->timer_jiffies & TVR_MASK;
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700423
Linus Torvalds1da177e2005-04-16 15:20:36 -0700424 /*
425 * Cascade timers:
426 */
427 if (!index &&
428 (!cascade(base, &base->tv2, INDEX(0))) &&
429 (!cascade(base, &base->tv3, INDEX(1))) &&
430 !cascade(base, &base->tv4, INDEX(2)))
431 cascade(base, &base->tv5, INDEX(3));
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700432 ++base->timer_jiffies;
433 list_replace_init(base->tv1.vec + index, &work_list);
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700434 while (!list_empty(head)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700435 void (*fn)(unsigned long);
436 unsigned long data;
437
438 timer = list_entry(head->next,struct timer_list,entry);
439 fn = timer->function;
440 data = timer->data;
441
Linus Torvalds1da177e2005-04-16 15:20:36 -0700442 set_running_timer(base, timer);
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700443 detach_timer(timer, 1);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800444 spin_unlock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700445 {
Jesper Juhlbe5b4fb2005-06-23 00:09:09 -0700446 int preempt_count = preempt_count();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700447 fn(data);
448 if (preempt_count != preempt_count()) {
Jesper Juhlbe5b4fb2005-06-23 00:09:09 -0700449 printk(KERN_WARNING "huh, entered %p "
450 "with preempt_count %08x, exited"
451 " with %08x?\n",
452 fn, preempt_count,
453 preempt_count());
Linus Torvalds1da177e2005-04-16 15:20:36 -0700454 BUG();
455 }
456 }
Oleg Nesterov3691c512006-03-31 02:30:30 -0800457 spin_lock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700458 }
459 }
460 set_running_timer(base, NULL);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800461 spin_unlock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700462}
463
464#ifdef CONFIG_NO_IDLE_HZ
465/*
466 * Find out when the next timer event is due to happen. This
467 * is used on S/390 to stop all activity when a cpus is idle.
468 * This functions needs to be called disabled.
469 */
470unsigned long next_timer_interrupt(void)
471{
472 tvec_base_t *base;
473 struct list_head *list;
474 struct timer_list *nte;
475 unsigned long expires;
Tony Lindgren69239742006-03-06 15:42:45 -0800476 unsigned long hr_expires = MAX_JIFFY_OFFSET;
477 ktime_t hr_delta;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700478 tvec_t *varray[4];
479 int i, j;
480
Tony Lindgren69239742006-03-06 15:42:45 -0800481 hr_delta = hrtimer_get_next_event();
482 if (hr_delta.tv64 != KTIME_MAX) {
483 struct timespec tsdelta;
484 tsdelta = ktime_to_timespec(hr_delta);
485 hr_expires = timespec_to_jiffies(&tsdelta);
486 if (hr_expires < 3)
487 return hr_expires + jiffies;
488 }
489 hr_expires += jiffies;
490
Jan Beulicha4a61982006-03-24 03:15:54 -0800491 base = __get_cpu_var(tvec_bases);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800492 spin_lock(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700493 expires = base->timer_jiffies + (LONG_MAX >> 1);
Al Viro53f087f2006-02-01 05:56:41 -0500494 list = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700495
496 /* Look for timer events in tv1. */
497 j = base->timer_jiffies & TVR_MASK;
498 do {
499 list_for_each_entry(nte, base->tv1.vec + j, entry) {
500 expires = nte->expires;
501 if (j < (base->timer_jiffies & TVR_MASK))
502 list = base->tv2.vec + (INDEX(0));
503 goto found;
504 }
505 j = (j + 1) & TVR_MASK;
506 } while (j != (base->timer_jiffies & TVR_MASK));
507
508 /* Check tv2-tv5. */
509 varray[0] = &base->tv2;
510 varray[1] = &base->tv3;
511 varray[2] = &base->tv4;
512 varray[3] = &base->tv5;
513 for (i = 0; i < 4; i++) {
514 j = INDEX(i);
515 do {
516 if (list_empty(varray[i]->vec + j)) {
517 j = (j + 1) & TVN_MASK;
518 continue;
519 }
520 list_for_each_entry(nte, varray[i]->vec + j, entry)
521 if (time_before(nte->expires, expires))
522 expires = nte->expires;
523 if (j < (INDEX(i)) && i < 3)
524 list = varray[i + 1]->vec + (INDEX(i + 1));
525 goto found;
526 } while (j != (INDEX(i)));
527 }
528found:
529 if (list) {
530 /*
531 * The search wrapped. We need to look at the next list
532 * from next tv element that would cascade into tv element
533 * where we found the timer element.
534 */
535 list_for_each_entry(nte, list, entry) {
536 if (time_before(nte->expires, expires))
537 expires = nte->expires;
538 }
539 }
Oleg Nesterov3691c512006-03-31 02:30:30 -0800540 spin_unlock(&base->lock);
Tony Lindgren69239742006-03-06 15:42:45 -0800541
Zachary Amsden0662b712006-05-20 15:00:24 -0700542 /*
543 * It can happen that other CPUs service timer IRQs and increment
544 * jiffies, but we have not yet got a local timer tick to process
545 * the timer wheels. In that case, the expiry time can be before
546 * jiffies, but since the high-resolution timer here is relative to
547 * jiffies, the default expression when high-resolution timers are
548 * not active,
549 *
550 * time_before(MAX_JIFFY_OFFSET + jiffies, expires)
551 *
552 * would falsely evaluate to true. If that is the case, just
553 * return jiffies so that we can immediately fire the local timer
554 */
555 if (time_before(expires, jiffies))
556 return jiffies;
557
Tony Lindgren69239742006-03-06 15:42:45 -0800558 if (time_before(hr_expires, expires))
559 return hr_expires;
560
Linus Torvalds1da177e2005-04-16 15:20:36 -0700561 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) */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700602long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
603 /* frequency offset (scaled ppm)*/
604static long time_adj; /* tick adjust (scaled 1 / HZ) */
605long time_reftime; /* time at last adjustment (s) */
606long time_adjust;
607long time_next_adjust;
608
609/*
610 * this routine handles the overflow of the microsecond field
611 *
612 * The tricky bits of code to handle the accurate clock support
613 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
614 * They were originally developed for SUN and DEC kernels.
615 * All the kudos should go to Dave for this stuff.
616 *
617 */
618static void second_overflow(void)
619{
Andrew Mortona5a0d522005-10-30 15:01:42 -0800620 long ltemp;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700621
Andrew Mortona5a0d522005-10-30 15:01:42 -0800622 /* Bump the maxerror field */
623 time_maxerror += time_tolerance >> SHIFT_USEC;
624 if (time_maxerror > NTP_PHASE_LIMIT) {
625 time_maxerror = NTP_PHASE_LIMIT;
626 time_status |= STA_UNSYNC;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700628
Andrew Mortona5a0d522005-10-30 15:01:42 -0800629 /*
630 * Leap second processing. If in leap-insert state at the end of the
631 * day, the system clock is set back one second; if in leap-delete
632 * state, the system clock is set ahead one second. The microtime()
633 * routine or external clock driver will insure that reported time is
634 * always monotonic. The ugly divides should be replaced.
635 */
636 switch (time_state) {
637 case TIME_OK:
638 if (time_status & STA_INS)
639 time_state = TIME_INS;
640 else if (time_status & STA_DEL)
641 time_state = TIME_DEL;
642 break;
643 case TIME_INS:
644 if (xtime.tv_sec % 86400 == 0) {
645 xtime.tv_sec--;
646 wall_to_monotonic.tv_sec++;
647 /*
648 * The timer interpolator will make time change
649 * gradually instead of an immediate jump by one second
650 */
651 time_interpolator_update(-NSEC_PER_SEC);
652 time_state = TIME_OOP;
653 clock_was_set();
654 printk(KERN_NOTICE "Clock: inserting leap second "
655 "23:59:60 UTC\n");
656 }
657 break;
658 case TIME_DEL:
659 if ((xtime.tv_sec + 1) % 86400 == 0) {
660 xtime.tv_sec++;
661 wall_to_monotonic.tv_sec--;
662 /*
663 * Use of time interpolator for a gradual change of
664 * time
665 */
666 time_interpolator_update(NSEC_PER_SEC);
667 time_state = TIME_WAIT;
668 clock_was_set();
669 printk(KERN_NOTICE "Clock: deleting leap second "
670 "23:59:59 UTC\n");
671 }
672 break;
673 case TIME_OOP:
674 time_state = TIME_WAIT;
675 break;
676 case TIME_WAIT:
677 if (!(time_status & (STA_INS | STA_DEL)))
678 time_state = TIME_OK;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700679 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680
Andrew Mortona5a0d522005-10-30 15:01:42 -0800681 /*
682 * Compute the phase adjustment for the next second. In PLL mode, the
683 * offset is reduced by a fixed factor times the time constant. In FLL
684 * mode the offset is used directly. In either mode, the maximum phase
685 * adjustment for each second is clamped so as to spread the adjustment
686 * over not more than the number of seconds between updates.
687 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688 ltemp = time_offset;
689 if (!(time_status & STA_FLL))
john stultz1bb34a42005-10-30 15:01:42 -0800690 ltemp = shift_right(ltemp, SHIFT_KG + time_constant);
691 ltemp = min(ltemp, (MAXPHASE / MINSEC) << SHIFT_UPDATE);
692 ltemp = max(ltemp, -(MAXPHASE / MINSEC) << SHIFT_UPDATE);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700693 time_offset -= ltemp;
694 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700695
Andrew Mortona5a0d522005-10-30 15:01:42 -0800696 /*
697 * Compute the frequency estimate and additional phase adjustment due
Roman Zippel5ddcfa82006-03-25 03:08:28 -0800698 * to frequency error for the next second.
Andrew Mortona5a0d522005-10-30 15:01:42 -0800699 */
Roman Zippel5ddcfa82006-03-25 03:08:28 -0800700 ltemp = time_freq;
Andrew Mortona5a0d522005-10-30 15:01:42 -0800701 time_adj += shift_right(ltemp,(SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE));
Linus Torvalds1da177e2005-04-16 15:20:36 -0700702
703#if HZ == 100
Andrew Mortona5a0d522005-10-30 15:01:42 -0800704 /*
705 * Compensate for (HZ==100) != (1 << SHIFT_HZ). Add 25% and 3.125% to
706 * get 128.125; => only 0.125% error (p. 14)
707 */
708 time_adj += shift_right(time_adj, 2) + shift_right(time_adj, 5);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700709#endif
YOSHIFUJI Hideaki4b8f5732005-10-29 18:15:42 -0700710#if HZ == 250
Andrew Mortona5a0d522005-10-30 15:01:42 -0800711 /*
712 * Compensate for (HZ==250) != (1 << SHIFT_HZ). Add 1.5625% and
713 * 0.78125% to get 255.85938; => only 0.05% error (p. 14)
714 */
715 time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
YOSHIFUJI Hideaki4b8f5732005-10-29 18:15:42 -0700716#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -0700717#if HZ == 1000
Andrew Mortona5a0d522005-10-30 15:01:42 -0800718 /*
719 * Compensate for (HZ==1000) != (1 << SHIFT_HZ). Add 1.5625% and
720 * 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
721 */
722 time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700723#endif
724}
725
Paul Mackerras726c14b2006-02-17 10:30:23 +1100726/*
727 * Returns how many microseconds we need to add to xtime this tick
728 * in doing an adjustment requested with adjtime.
729 */
730static long adjtime_adjustment(void)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700731{
Paul Mackerras726c14b2006-02-17 10:30:23 +1100732 long time_adjust_step;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700733
Paul Mackerras726c14b2006-02-17 10:30:23 +1100734 time_adjust_step = time_adjust;
735 if (time_adjust_step) {
Andrew Mortona5a0d522005-10-30 15:01:42 -0800736 /*
737 * We are doing an adjtime thing. Prepare time_adjust_step to
738 * be within bounds. Note that a positive time_adjust means we
739 * want the clock to run faster.
740 *
741 * Limit the amount of the step to be in the range
742 * -tickadj .. +tickadj
743 */
744 time_adjust_step = min(time_adjust_step, (long)tickadj);
745 time_adjust_step = max(time_adjust_step, (long)-tickadj);
Paul Mackerras726c14b2006-02-17 10:30:23 +1100746 }
747 return time_adjust_step;
748}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700749
Paul Mackerras726c14b2006-02-17 10:30:23 +1100750/* in the NTP reference this is called "hardclock()" */
john stultz5eb6d202006-06-26 00:25:07 -0700751static void update_ntp_one_tick(void)
Paul Mackerras726c14b2006-02-17 10:30:23 +1100752{
john stultz5eb6d202006-06-26 00:25:07 -0700753 long time_adjust_step;
Paul Mackerras726c14b2006-02-17 10:30:23 +1100754
755 time_adjust_step = adjtime_adjustment();
756 if (time_adjust_step)
Andrew Mortona5a0d522005-10-30 15:01:42 -0800757 /* Reduce by this step the amount of time left */
758 time_adjust -= time_adjust_step;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700759
760 /* Changes by adjtime() do not take effect till next tick. */
761 if (time_next_adjust != 0) {
762 time_adjust = time_next_adjust;
763 time_next_adjust = 0;
764 }
765}
766
767/*
Paul Mackerras726c14b2006-02-17 10:30:23 +1100768 * Return how long ticks are at the moment, that is, how much time
769 * update_wall_time_one_tick will add to xtime next time we call it
770 * (assuming no calls to do_adjtimex in the meantime).
john stultz260a4232006-06-26 00:25:07 -0700771 * The return value is in fixed-point nanoseconds shifted by the
772 * specified number of bits to the right of the binary point.
Paul Mackerras726c14b2006-02-17 10:30:23 +1100773 * This function has no side-effects.
774 */
Roman Zippel19923c12006-06-26 00:25:18 -0700775u64 current_tick_length(void)
Paul Mackerras726c14b2006-02-17 10:30:23 +1100776{
777 long delta_nsec;
john stultz260a4232006-06-26 00:25:07 -0700778 u64 ret;
Paul Mackerras726c14b2006-02-17 10:30:23 +1100779
john stultz260a4232006-06-26 00:25:07 -0700780 /* calculate the finest interval NTP will allow.
781 * ie: nanosecond value shifted by (SHIFT_SCALE - 10)
782 */
Paul Mackerras726c14b2006-02-17 10:30:23 +1100783 delta_nsec = tick_nsec + adjtime_adjustment() * 1000;
Roman Zippel19923c12006-06-26 00:25:18 -0700784 ret = (u64)delta_nsec << TICK_LENGTH_SHIFT;
785 ret += (s64)time_adj << (TICK_LENGTH_SHIFT - (SHIFT_SCALE - 10));
john stultz260a4232006-06-26 00:25:07 -0700786
787 return ret;
Paul Mackerras726c14b2006-02-17 10:30:23 +1100788}
789
john stultzad596172006-06-26 00:25:06 -0700790/* XXX - all of this timekeeping code should be later moved to time.c */
791#include <linux/clocksource.h>
792static struct clocksource *clock; /* pointer to current clocksource */
john stultzcf3c7692006-06-26 00:25:08 -0700793
794#ifdef CONFIG_GENERIC_TIME
795/**
796 * __get_nsec_offset - Returns nanoseconds since last call to periodic_hook
797 *
798 * private function, must hold xtime_lock lock when being
799 * called. Returns the number of nanoseconds since the
800 * last call to update_wall_time() (adjusted by NTP scaling)
801 */
802static inline s64 __get_nsec_offset(void)
803{
804 cycle_t cycle_now, cycle_delta;
805 s64 ns_offset;
806
807 /* read clocksource: */
john stultza2752542006-06-26 00:25:14 -0700808 cycle_now = clocksource_read(clock);
john stultzcf3c7692006-06-26 00:25:08 -0700809
810 /* calculate the delta since the last update_wall_time: */
Roman Zippel19923c12006-06-26 00:25:18 -0700811 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
john stultzcf3c7692006-06-26 00:25:08 -0700812
813 /* convert to nanoseconds: */
814 ns_offset = cyc2ns(clock, cycle_delta);
815
816 return ns_offset;
817}
818
819/**
820 * __get_realtime_clock_ts - Returns the time of day in a timespec
821 * @ts: pointer to the timespec to be set
822 *
823 * Returns the time of day in a timespec. Used by
824 * do_gettimeofday() and get_realtime_clock_ts().
825 */
826static inline void __get_realtime_clock_ts(struct timespec *ts)
827{
828 unsigned long seq;
829 s64 nsecs;
830
831 do {
832 seq = read_seqbegin(&xtime_lock);
833
834 *ts = xtime;
835 nsecs = __get_nsec_offset();
836
837 } while (read_seqretry(&xtime_lock, seq));
838
839 timespec_add_ns(ts, nsecs);
840}
841
842/**
john stultza2752542006-06-26 00:25:14 -0700843 * getnstimeofday - Returns the time of day in a timespec
john stultzcf3c7692006-06-26 00:25:08 -0700844 * @ts: pointer to the timespec to be set
845 *
846 * Returns the time of day in a timespec.
847 */
848void getnstimeofday(struct timespec *ts)
849{
850 __get_realtime_clock_ts(ts);
851}
852
853EXPORT_SYMBOL(getnstimeofday);
854
855/**
856 * do_gettimeofday - Returns the time of day in a timeval
857 * @tv: pointer to the timeval to be set
858 *
859 * NOTE: Users should be converted to using get_realtime_clock_ts()
860 */
861void do_gettimeofday(struct timeval *tv)
862{
863 struct timespec now;
864
865 __get_realtime_clock_ts(&now);
866 tv->tv_sec = now.tv_sec;
867 tv->tv_usec = now.tv_nsec/1000;
868}
869
870EXPORT_SYMBOL(do_gettimeofday);
871/**
872 * do_settimeofday - Sets the time of day
873 * @tv: pointer to the timespec variable containing the new time
874 *
875 * Sets the time of day to the new time and update NTP and notify hrtimers
876 */
877int do_settimeofday(struct timespec *tv)
878{
879 unsigned long flags;
880 time_t wtm_sec, sec = tv->tv_sec;
881 long wtm_nsec, nsec = tv->tv_nsec;
882
883 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
884 return -EINVAL;
885
886 write_seqlock_irqsave(&xtime_lock, flags);
887
888 nsec -= __get_nsec_offset();
889
890 wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
891 wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
892
893 set_normalized_timespec(&xtime, sec, nsec);
894 set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
895
Roman Zippele154ff32006-07-10 04:44:32 -0700896 clock->error = 0;
john stultzcf3c7692006-06-26 00:25:08 -0700897 ntp_clear();
898
899 write_sequnlock_irqrestore(&xtime_lock, flags);
900
901 /* signal hrtimers about time change */
902 clock_was_set();
903
904 return 0;
905}
906
907EXPORT_SYMBOL(do_settimeofday);
908
909/**
910 * change_clocksource - Swaps clocksources if a new one is available
911 *
912 * Accumulates current time interval and initializes new clocksource
913 */
914static int change_clocksource(void)
915{
916 struct clocksource *new;
917 cycle_t now;
918 u64 nsec;
john stultza2752542006-06-26 00:25:14 -0700919 new = clocksource_get_next();
john stultzcf3c7692006-06-26 00:25:08 -0700920 if (clock != new) {
john stultza2752542006-06-26 00:25:14 -0700921 now = clocksource_read(new);
john stultzcf3c7692006-06-26 00:25:08 -0700922 nsec = __get_nsec_offset();
923 timespec_add_ns(&xtime, nsec);
924
925 clock = new;
Roman Zippel19923c12006-06-26 00:25:18 -0700926 clock->cycle_last = now;
john stultzcf3c7692006-06-26 00:25:08 -0700927 printk(KERN_INFO "Time: %s clocksource has been installed.\n",
928 clock->name);
929 return 1;
930 } else if (clock->update_callback) {
931 return clock->update_callback();
932 }
933 return 0;
934}
935#else
936#define change_clocksource() (0)
937#endif
938
939/**
940 * timeofday_is_continuous - check to see if timekeeping is free running
941 */
942int timekeeping_is_continuous(void)
943{
944 unsigned long seq;
945 int ret;
946
947 do {
948 seq = read_seqbegin(&xtime_lock);
949
950 ret = clock->is_continuous;
951
952 } while (read_seqretry(&xtime_lock, seq));
953
954 return ret;
955}
956
Paul Mackerras726c14b2006-02-17 10:30:23 +1100957/*
john stultzad596172006-06-26 00:25:06 -0700958 * timekeeping_init - Initializes the clocksource and common timekeeping values
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959 */
john stultzad596172006-06-26 00:25:06 -0700960void __init timekeeping_init(void)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700961{
john stultzad596172006-06-26 00:25:06 -0700962 unsigned long flags;
963
964 write_seqlock_irqsave(&xtime_lock, flags);
john stultza2752542006-06-26 00:25:14 -0700965 clock = clocksource_get_next();
966 clocksource_calculate_interval(clock, tick_nsec);
Roman Zippel19923c12006-06-26 00:25:18 -0700967 clock->cycle_last = clocksource_read(clock);
john stultzad596172006-06-26 00:25:06 -0700968 ntp_clear();
969 write_sequnlock_irqrestore(&xtime_lock, flags);
970}
971
972
john stultz3e143472006-07-14 00:24:17 -0700973static int timekeeping_suspended;
john stultzad596172006-06-26 00:25:06 -0700974/*
975 * timekeeping_resume - Resumes the generic timekeeping subsystem.
976 * @dev: unused
977 *
978 * This is for the generic clocksource timekeeping.
979 * xtime/wall_to_monotonic/jiffies/wall_jiffies/etc are
980 * still managed by arch specific suspend/resume code.
981 */
982static int timekeeping_resume(struct sys_device *dev)
983{
984 unsigned long flags;
985
986 write_seqlock_irqsave(&xtime_lock, flags);
987 /* restart the last cycle value */
Roman Zippel19923c12006-06-26 00:25:18 -0700988 clock->cycle_last = clocksource_read(clock);
john stultz3e143472006-07-14 00:24:17 -0700989 clock->error = 0;
990 timekeeping_suspended = 0;
991 write_sequnlock_irqrestore(&xtime_lock, flags);
992 return 0;
993}
994
995static int timekeeping_suspend(struct sys_device *dev, pm_message_t state)
996{
997 unsigned long flags;
998
999 write_seqlock_irqsave(&xtime_lock, flags);
1000 timekeeping_suspended = 1;
john stultzad596172006-06-26 00:25:06 -07001001 write_sequnlock_irqrestore(&xtime_lock, flags);
1002 return 0;
1003}
1004
1005/* sysfs resume/suspend bits for timekeeping */
1006static struct sysdev_class timekeeping_sysclass = {
1007 .resume = timekeeping_resume,
john stultz3e143472006-07-14 00:24:17 -07001008 .suspend = timekeeping_suspend,
john stultzad596172006-06-26 00:25:06 -07001009 set_kset_name("timekeeping"),
1010};
1011
1012static struct sys_device device_timer = {
1013 .id = 0,
1014 .cls = &timekeeping_sysclass,
1015};
1016
1017static int __init timekeeping_init_device(void)
1018{
1019 int error = sysdev_class_register(&timekeeping_sysclass);
1020 if (!error)
1021 error = sysdev_register(&device_timer);
1022 return error;
1023}
1024
1025device_initcall(timekeeping_init_device);
1026
1027/*
Roman Zippele154ff32006-07-10 04:44:32 -07001028 * If the error is already larger, we look ahead even further
Roman Zippel19923c12006-06-26 00:25:18 -07001029 * to compensate for late or lost adjustments.
1030 */
Roman Zippele154ff32006-07-10 04:44:32 -07001031static __always_inline int clocksource_bigadjust(s64 error, s64 *interval, s64 *offset)
Roman Zippel19923c12006-06-26 00:25:18 -07001032{
Roman Zippele154ff32006-07-10 04:44:32 -07001033 s64 tick_error, i;
1034 u32 look_ahead, adj;
1035 s32 error2, mult;
Roman Zippel19923c12006-06-26 00:25:18 -07001036
1037 /*
Roman Zippele154ff32006-07-10 04:44:32 -07001038 * Use the current error value to determine how much to look ahead.
1039 * The larger the error the slower we adjust for it to avoid problems
1040 * with losing too many ticks, otherwise we would overadjust and
1041 * produce an even larger error. The smaller the adjustment the
1042 * faster we try to adjust for it, as lost ticks can do less harm
1043 * here. This is tuned so that an error of about 1 msec is adusted
1044 * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
Roman Zippel19923c12006-06-26 00:25:18 -07001045 */
Roman Zippele154ff32006-07-10 04:44:32 -07001046 error2 = clock->error >> (TICK_LENGTH_SHIFT + 22 - 2 * SHIFT_HZ);
1047 error2 = abs(error2);
1048 for (look_ahead = 0; error2 > 0; look_ahead++)
1049 error2 >>= 2;
Roman Zippel19923c12006-06-26 00:25:18 -07001050
1051 /*
Roman Zippele154ff32006-07-10 04:44:32 -07001052 * Now calculate the error in (1 << look_ahead) ticks, but first
1053 * remove the single look ahead already included in the error.
Roman Zippel19923c12006-06-26 00:25:18 -07001054 */
Roman Zippele154ff32006-07-10 04:44:32 -07001055 tick_error = current_tick_length() >> (TICK_LENGTH_SHIFT - clock->shift + 1);
1056 tick_error -= clock->xtime_interval >> 1;
1057 error = ((error - tick_error) >> look_ahead) + tick_error;
Roman Zippel19923c12006-06-26 00:25:18 -07001058
Roman Zippele154ff32006-07-10 04:44:32 -07001059 /* Finally calculate the adjustment shift value. */
1060 i = *interval;
1061 mult = 1;
1062 if (error < 0) {
1063 error = -error;
1064 *interval = -*interval;
1065 *offset = -*offset;
1066 mult = -1;
Roman Zippel19923c12006-06-26 00:25:18 -07001067 }
Roman Zippele154ff32006-07-10 04:44:32 -07001068 for (adj = 0; error > i; adj++)
1069 error >>= 1;
Roman Zippel19923c12006-06-26 00:25:18 -07001070
1071 *interval <<= adj;
1072 *offset <<= adj;
Roman Zippele154ff32006-07-10 04:44:32 -07001073 return mult << adj;
Roman Zippel19923c12006-06-26 00:25:18 -07001074}
1075
1076/*
1077 * Adjust the multiplier to reduce the error value,
1078 * this is optimized for the most common adjustments of -1,0,1,
1079 * for other values we can do a bit more work.
1080 */
1081static void clocksource_adjust(struct clocksource *clock, s64 offset)
1082{
1083 s64 error, interval = clock->cycle_interval;
1084 int adj;
1085
1086 error = clock->error >> (TICK_LENGTH_SHIFT - clock->shift - 1);
1087 if (error > interval) {
Roman Zippele154ff32006-07-10 04:44:32 -07001088 error >>= 2;
1089 if (likely(error <= interval))
1090 adj = 1;
1091 else
1092 adj = clocksource_bigadjust(error, &interval, &offset);
Roman Zippel19923c12006-06-26 00:25:18 -07001093 } else if (error < -interval) {
Roman Zippele154ff32006-07-10 04:44:32 -07001094 error >>= 2;
1095 if (likely(error >= -interval)) {
1096 adj = -1;
1097 interval = -interval;
1098 offset = -offset;
1099 } else
1100 adj = clocksource_bigadjust(error, &interval, &offset);
Roman Zippel19923c12006-06-26 00:25:18 -07001101 } else
1102 return;
1103
1104 clock->mult += adj;
1105 clock->xtime_interval += interval;
1106 clock->xtime_nsec -= offset;
1107 clock->error -= (interval - offset) << (TICK_LENGTH_SHIFT - clock->shift);
1108}
1109
1110/*
john stultzad596172006-06-26 00:25:06 -07001111 * update_wall_time - Uses the current clocksource to increment the wall time
1112 *
1113 * Called from the timer interrupt, must hold a write on xtime_lock.
1114 */
1115static void update_wall_time(void)
1116{
Roman Zippel19923c12006-06-26 00:25:18 -07001117 cycle_t offset;
john stultzad596172006-06-26 00:25:06 -07001118
john stultz3e143472006-07-14 00:24:17 -07001119 /* Make sure we're fully resumed: */
1120 if (unlikely(timekeeping_suspended))
1121 return;
john stultz5eb6d202006-06-26 00:25:07 -07001122
Roman Zippel19923c12006-06-26 00:25:18 -07001123#ifdef CONFIG_GENERIC_TIME
1124 offset = (clocksource_read(clock) - clock->cycle_last) & clock->mask;
1125#else
1126 offset = clock->cycle_interval;
1127#endif
john stultz3e143472006-07-14 00:24:17 -07001128 clock->xtime_nsec += (s64)xtime.tv_nsec << clock->shift;
john stultzad596172006-06-26 00:25:06 -07001129
1130 /* normally this loop will run just once, however in the
1131 * case of lost or late ticks, it will accumulate correctly.
1132 */
Roman Zippel19923c12006-06-26 00:25:18 -07001133 while (offset >= clock->cycle_interval) {
john stultzad596172006-06-26 00:25:06 -07001134 /* accumulate one interval */
Roman Zippel19923c12006-06-26 00:25:18 -07001135 clock->xtime_nsec += clock->xtime_interval;
1136 clock->cycle_last += clock->cycle_interval;
1137 offset -= clock->cycle_interval;
1138
1139 if (clock->xtime_nsec >= (u64)NSEC_PER_SEC << clock->shift) {
1140 clock->xtime_nsec -= (u64)NSEC_PER_SEC << clock->shift;
1141 xtime.tv_sec++;
1142 second_overflow();
1143 }
john stultzad596172006-06-26 00:25:06 -07001144
john stultz5eb6d202006-06-26 00:25:07 -07001145 /* interpolator bits */
Roman Zippel19923c12006-06-26 00:25:18 -07001146 time_interpolator_update(clock->xtime_interval
john stultz5eb6d202006-06-26 00:25:07 -07001147 >> clock->shift);
1148 /* increment the NTP state machine */
1149 update_ntp_one_tick();
1150
1151 /* accumulate error between NTP and clock interval */
Roman Zippel19923c12006-06-26 00:25:18 -07001152 clock->error += current_tick_length();
1153 clock->error -= clock->xtime_interval << (TICK_LENGTH_SHIFT - clock->shift);
john stultzad596172006-06-26 00:25:06 -07001154 }
Roman Zippel19923c12006-06-26 00:25:18 -07001155
1156 /* correct the clock when NTP error is too big */
1157 clocksource_adjust(clock, offset);
1158
john stultz5eb6d202006-06-26 00:25:07 -07001159 /* store full nanoseconds into xtime */
Roman Zippele154ff32006-07-10 04:44:32 -07001160 xtime.tv_nsec = (s64)clock->xtime_nsec >> clock->shift;
Roman Zippel19923c12006-06-26 00:25:18 -07001161 clock->xtime_nsec -= (s64)xtime.tv_nsec << clock->shift;
john stultzcf3c7692006-06-26 00:25:08 -07001162
1163 /* check to see if there is a new clocksource to use */
1164 if (change_clocksource()) {
Roman Zippel19923c12006-06-26 00:25:18 -07001165 clock->error = 0;
1166 clock->xtime_nsec = 0;
john stultza2752542006-06-26 00:25:14 -07001167 clocksource_calculate_interval(clock, tick_nsec);
john stultzcf3c7692006-06-26 00:25:08 -07001168 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001169}
1170
1171/*
1172 * Called from the timer interrupt handler to charge one tick to the current
1173 * process. user_tick is 1 if the tick is user time, 0 for system.
1174 */
1175void update_process_times(int user_tick)
1176{
1177 struct task_struct *p = current;
1178 int cpu = smp_processor_id();
1179
1180 /* Note: this timer irq context must be accounted for as well. */
1181 if (user_tick)
1182 account_user_time(p, jiffies_to_cputime(1));
1183 else
1184 account_system_time(p, HARDIRQ_OFFSET, jiffies_to_cputime(1));
1185 run_local_timers();
1186 if (rcu_pending(cpu))
1187 rcu_check_callbacks(cpu, user_tick);
1188 scheduler_tick();
1189 run_posix_cpu_timers(p);
1190}
1191
1192/*
1193 * Nr of active tasks - counted in fixed-point numbers
1194 */
1195static unsigned long count_active_tasks(void)
1196{
Jack Steinerdb1b1fe2006-03-31 02:31:21 -08001197 return nr_active() * FIXED_1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001198}
1199
1200/*
1201 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
1202 * imply that avenrun[] is the standard name for this kind of thing.
1203 * Nothing else seems to be standardized: the fractional size etc
1204 * all seem to differ on different machines.
1205 *
1206 * Requires xtime_lock to access.
1207 */
1208unsigned long avenrun[3];
1209
1210EXPORT_SYMBOL(avenrun);
1211
1212/*
1213 * calc_load - given tick count, update the avenrun load estimates.
1214 * This is called while holding a write_lock on xtime_lock.
1215 */
1216static inline void calc_load(unsigned long ticks)
1217{
1218 unsigned long active_tasks; /* fixed-point */
1219 static int count = LOAD_FREQ;
1220
1221 count -= ticks;
1222 if (count < 0) {
1223 count += LOAD_FREQ;
1224 active_tasks = count_active_tasks();
1225 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
1226 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
1227 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
1228 }
1229}
1230
1231/* jiffies at the most recent update of wall time */
1232unsigned long wall_jiffies = INITIAL_JIFFIES;
1233
1234/*
1235 * This read-write spinlock protects us from races in SMP while
1236 * playing with xtime and avenrun.
1237 */
1238#ifndef ARCH_HAVE_XTIME_LOCK
Ingo Molnare4d91912006-07-03 00:24:34 -07001239__cacheline_aligned_in_smp DEFINE_SEQLOCK(xtime_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001240
1241EXPORT_SYMBOL(xtime_lock);
1242#endif
1243
1244/*
1245 * This function runs timers and the timer-tq in bottom half context.
1246 */
1247static void run_timer_softirq(struct softirq_action *h)
1248{
Jan Beulicha4a61982006-03-24 03:15:54 -08001249 tvec_base_t *base = __get_cpu_var(tvec_bases);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001250
Thomas Gleixnerc0a31322006-01-09 20:52:32 -08001251 hrtimer_run_queues();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001252 if (time_after_eq(jiffies, base->timer_jiffies))
1253 __run_timers(base);
1254}
1255
1256/*
1257 * Called by the local, per-CPU timer interrupt on SMP.
1258 */
1259void run_local_timers(void)
1260{
1261 raise_softirq(TIMER_SOFTIRQ);
Ingo Molnar6687a972006-03-24 03:18:41 -08001262 softlockup_tick();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001263}
1264
1265/*
1266 * Called by the timer interrupt. xtime_lock must already be taken
1267 * by the timer IRQ!
1268 */
1269static inline void update_times(void)
1270{
1271 unsigned long ticks;
1272
1273 ticks = jiffies - wall_jiffies;
john stultzad596172006-06-26 00:25:06 -07001274 wall_jiffies += ticks;
1275 update_wall_time();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001276 calc_load(ticks);
1277}
1278
1279/*
1280 * The 64-bit jiffies value is not atomic - you MUST NOT read it
1281 * without sampling the sequence number in xtime_lock.
1282 * jiffies is defined in the linker script...
1283 */
1284
1285void do_timer(struct pt_regs *regs)
1286{
1287 jiffies_64++;
Atsushi Nemoto5aee4052006-03-06 15:42:51 -08001288 /* prevent loading jiffies before storing new jiffies_64 value. */
1289 barrier();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001290 update_times();
1291}
1292
1293#ifdef __ARCH_WANT_SYS_ALARM
1294
1295/*
1296 * For backwards compatibility? This can be done in libc so Alpha
1297 * and all newer ports shouldn't need it.
1298 */
1299asmlinkage unsigned long sys_alarm(unsigned int seconds)
1300{
Thomas Gleixnerc08b8a42006-03-25 03:06:33 -08001301 return alarm_setitimer(seconds);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001302}
1303
1304#endif
1305
1306#ifndef __alpha__
1307
1308/*
1309 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
1310 * should be moved into arch/i386 instead?
1311 */
1312
1313/**
1314 * sys_getpid - return the thread group id of the current process
1315 *
1316 * Note, despite the name, this returns the tgid not the pid. The tgid and
1317 * the pid are identical unless CLONE_THREAD was specified on clone() in
1318 * which case the tgid is the same in all threads of the same group.
1319 *
1320 * This is SMP safe as current->tgid does not change.
1321 */
1322asmlinkage long sys_getpid(void)
1323{
1324 return current->tgid;
1325}
1326
1327/*
Kirill Korotaev6997a6f2006-08-13 23:24:23 -07001328 * Accessing ->real_parent is not SMP-safe, it could
1329 * change from under us. However, we can use a stale
1330 * value of ->real_parent under rcu_read_lock(), see
1331 * release_task()->call_rcu(delayed_put_task_struct).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001332 */
1333asmlinkage long sys_getppid(void)
1334{
1335 int pid;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001336
Kirill Korotaev6997a6f2006-08-13 23:24:23 -07001337 rcu_read_lock();
1338 pid = rcu_dereference(current->real_parent)->tgid;
1339 rcu_read_unlock();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001340
Linus Torvalds1da177e2005-04-16 15:20:36 -07001341 return pid;
1342}
1343
1344asmlinkage long sys_getuid(void)
1345{
1346 /* Only we change this so SMP safe */
1347 return current->uid;
1348}
1349
1350asmlinkage long sys_geteuid(void)
1351{
1352 /* Only we change this so SMP safe */
1353 return current->euid;
1354}
1355
1356asmlinkage long sys_getgid(void)
1357{
1358 /* Only we change this so SMP safe */
1359 return current->gid;
1360}
1361
1362asmlinkage long sys_getegid(void)
1363{
1364 /* Only we change this so SMP safe */
1365 return current->egid;
1366}
1367
1368#endif
1369
1370static void process_timeout(unsigned long __data)
1371{
Ingo Molnar36c8b582006-07-03 00:25:41 -07001372 wake_up_process((struct task_struct *)__data);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001373}
1374
1375/**
1376 * schedule_timeout - sleep until timeout
1377 * @timeout: timeout value in jiffies
1378 *
1379 * Make the current task sleep until @timeout jiffies have
1380 * elapsed. The routine will return immediately unless
1381 * the current task state has been set (see set_current_state()).
1382 *
1383 * You can set the task state as follows -
1384 *
1385 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1386 * pass before the routine returns. The routine will return 0
1387 *
1388 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1389 * delivered to the current task. In this case the remaining time
1390 * in jiffies will be returned, or 0 if the timer expired in time
1391 *
1392 * The current task state is guaranteed to be TASK_RUNNING when this
1393 * routine returns.
1394 *
1395 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1396 * the CPU away without a bound on the timeout. In this case the return
1397 * value will be %MAX_SCHEDULE_TIMEOUT.
1398 *
1399 * In all cases the return value is guaranteed to be non-negative.
1400 */
1401fastcall signed long __sched schedule_timeout(signed long timeout)
1402{
1403 struct timer_list timer;
1404 unsigned long expire;
1405
1406 switch (timeout)
1407 {
1408 case MAX_SCHEDULE_TIMEOUT:
1409 /*
1410 * These two special cases are useful to be comfortable
1411 * in the caller. Nothing more. We could take
1412 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1413 * but I' d like to return a valid offset (>=0) to allow
1414 * the caller to do everything it want with the retval.
1415 */
1416 schedule();
1417 goto out;
1418 default:
1419 /*
1420 * Another bit of PARANOID. Note that the retval will be
1421 * 0 since no piece of kernel is supposed to do a check
1422 * for a negative retval of schedule_timeout() (since it
1423 * should never happens anyway). You just have the printk()
1424 * that will tell you if something is gone wrong and where.
1425 */
1426 if (timeout < 0)
1427 {
1428 printk(KERN_ERR "schedule_timeout: wrong timeout "
Andrew Mortona5a0d522005-10-30 15:01:42 -08001429 "value %lx from %p\n", timeout,
1430 __builtin_return_address(0));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001431 current->state = TASK_RUNNING;
1432 goto out;
1433 }
1434 }
1435
1436 expire = timeout + jiffies;
1437
Oleg Nesterova8db2db2005-10-30 15:01:38 -08001438 setup_timer(&timer, process_timeout, (unsigned long)current);
1439 __mod_timer(&timer, expire);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001440 schedule();
1441 del_singleshot_timer_sync(&timer);
1442
1443 timeout = expire - jiffies;
1444
1445 out:
1446 return timeout < 0 ? 0 : timeout;
1447}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001448EXPORT_SYMBOL(schedule_timeout);
1449
Andrew Morton8a1c1752005-09-13 01:25:15 -07001450/*
1451 * We can use __set_current_state() here because schedule_timeout() calls
1452 * schedule() unconditionally.
1453 */
Nishanth Aravamudan64ed93a2005-09-10 00:27:21 -07001454signed long __sched schedule_timeout_interruptible(signed long timeout)
1455{
Andrew Mortona5a0d522005-10-30 15:01:42 -08001456 __set_current_state(TASK_INTERRUPTIBLE);
1457 return schedule_timeout(timeout);
Nishanth Aravamudan64ed93a2005-09-10 00:27:21 -07001458}
1459EXPORT_SYMBOL(schedule_timeout_interruptible);
1460
1461signed long __sched schedule_timeout_uninterruptible(signed long timeout)
1462{
Andrew Mortona5a0d522005-10-30 15:01:42 -08001463 __set_current_state(TASK_UNINTERRUPTIBLE);
1464 return schedule_timeout(timeout);
Nishanth Aravamudan64ed93a2005-09-10 00:27:21 -07001465}
1466EXPORT_SYMBOL(schedule_timeout_uninterruptible);
1467
Linus Torvalds1da177e2005-04-16 15:20:36 -07001468/* Thread ID - the internal kernel "pid" */
1469asmlinkage long sys_gettid(void)
1470{
1471 return current->pid;
1472}
1473
Linus Torvalds1da177e2005-04-16 15:20:36 -07001474/*
1475 * sys_sysinfo - fill in sysinfo struct
1476 */
1477asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1478{
1479 struct sysinfo val;
1480 unsigned long mem_total, sav_total;
1481 unsigned int mem_unit, bitcount;
1482 unsigned long seq;
1483
1484 memset((char *)&val, 0, sizeof(struct sysinfo));
1485
1486 do {
1487 struct timespec tp;
1488 seq = read_seqbegin(&xtime_lock);
1489
1490 /*
1491 * This is annoying. The below is the same thing
1492 * posix_get_clock_monotonic() does, but it wants to
1493 * take the lock which we want to cover the loads stuff
1494 * too.
1495 */
1496
1497 getnstimeofday(&tp);
1498 tp.tv_sec += wall_to_monotonic.tv_sec;
1499 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1500 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1501 tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1502 tp.tv_sec++;
1503 }
1504 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1505
1506 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1507 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1508 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1509
1510 val.procs = nr_threads;
1511 } while (read_seqretry(&xtime_lock, seq));
1512
1513 si_meminfo(&val);
1514 si_swapinfo(&val);
1515
1516 /*
1517 * If the sum of all the available memory (i.e. ram + swap)
1518 * is less than can be stored in a 32 bit unsigned long then
1519 * we can be binary compatible with 2.2.x kernels. If not,
1520 * well, in that case 2.2.x was broken anyways...
1521 *
1522 * -Erik Andersen <andersee@debian.org>
1523 */
1524
1525 mem_total = val.totalram + val.totalswap;
1526 if (mem_total < val.totalram || mem_total < val.totalswap)
1527 goto out;
1528 bitcount = 0;
1529 mem_unit = val.mem_unit;
1530 while (mem_unit > 1) {
1531 bitcount++;
1532 mem_unit >>= 1;
1533 sav_total = mem_total;
1534 mem_total <<= 1;
1535 if (mem_total < sav_total)
1536 goto out;
1537 }
1538
1539 /*
1540 * If mem_total did not overflow, multiply all memory values by
1541 * val.mem_unit and set it to 1. This leaves things compatible
1542 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1543 * kernels...
1544 */
1545
1546 val.mem_unit = 1;
1547 val.totalram <<= bitcount;
1548 val.freeram <<= bitcount;
1549 val.sharedram <<= bitcount;
1550 val.bufferram <<= bitcount;
1551 val.totalswap <<= bitcount;
1552 val.freeswap <<= bitcount;
1553 val.totalhigh <<= bitcount;
1554 val.freehigh <<= bitcount;
1555
1556 out:
1557 if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1558 return -EFAULT;
1559
1560 return 0;
1561}
1562
Ingo Molnard730e882006-07-03 00:25:10 -07001563/*
1564 * lockdep: we want to track each per-CPU base as a separate lock-class,
1565 * but timer-bases are kmalloc()-ed, so we need to attach separate
1566 * keys to them:
1567 */
1568static struct lock_class_key base_lock_keys[NR_CPUS];
1569
Jan Beulicha4a61982006-03-24 03:15:54 -08001570static int __devinit init_timers_cpu(int cpu)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001571{
1572 int j;
1573 tvec_base_t *base;
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001574 static char __devinitdata tvec_base_done[NR_CPUS];
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001575
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001576 if (!tvec_base_done[cpu]) {
Jan Beulicha4a61982006-03-24 03:15:54 -08001577 static char boot_done;
1578
Jan Beulicha4a61982006-03-24 03:15:54 -08001579 if (boot_done) {
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001580 /*
1581 * The APs use this path later in boot
1582 */
Jan Beulicha4a61982006-03-24 03:15:54 -08001583 base = kmalloc_node(sizeof(*base), GFP_KERNEL,
1584 cpu_to_node(cpu));
1585 if (!base)
1586 return -ENOMEM;
1587 memset(base, 0, sizeof(*base));
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001588 per_cpu(tvec_bases, cpu) = base;
Jan Beulicha4a61982006-03-24 03:15:54 -08001589 } else {
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001590 /*
1591 * This is for the boot CPU - we use compile-time
1592 * static initialisation because per-cpu memory isn't
1593 * ready yet and because the memory allocators are not
1594 * initialised either.
1595 */
Jan Beulicha4a61982006-03-24 03:15:54 -08001596 boot_done = 1;
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001597 base = &boot_tvec_bases;
Jan Beulicha4a61982006-03-24 03:15:54 -08001598 }
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001599 tvec_base_done[cpu] = 1;
1600 } else {
1601 base = per_cpu(tvec_bases, cpu);
Jan Beulicha4a61982006-03-24 03:15:54 -08001602 }
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001603
Oleg Nesterov3691c512006-03-31 02:30:30 -08001604 spin_lock_init(&base->lock);
Ingo Molnard730e882006-07-03 00:25:10 -07001605 lockdep_set_class(&base->lock, base_lock_keys + cpu);
1606
Linus Torvalds1da177e2005-04-16 15:20:36 -07001607 for (j = 0; j < TVN_SIZE; j++) {
1608 INIT_LIST_HEAD(base->tv5.vec + j);
1609 INIT_LIST_HEAD(base->tv4.vec + j);
1610 INIT_LIST_HEAD(base->tv3.vec + j);
1611 INIT_LIST_HEAD(base->tv2.vec + j);
1612 }
1613 for (j = 0; j < TVR_SIZE; j++)
1614 INIT_LIST_HEAD(base->tv1.vec + j);
1615
1616 base->timer_jiffies = jiffies;
Jan Beulicha4a61982006-03-24 03:15:54 -08001617 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001618}
1619
1620#ifdef CONFIG_HOTPLUG_CPU
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001621static void migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001622{
1623 struct timer_list *timer;
1624
1625 while (!list_empty(head)) {
1626 timer = list_entry(head->next, struct timer_list, entry);
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001627 detach_timer(timer, 0);
Oleg Nesterov3691c512006-03-31 02:30:30 -08001628 timer->base = new_base;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001629 internal_add_timer(new_base, timer);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001630 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001631}
1632
1633static void __devinit migrate_timers(int cpu)
1634{
1635 tvec_base_t *old_base;
1636 tvec_base_t *new_base;
1637 int i;
1638
1639 BUG_ON(cpu_online(cpu));
Jan Beulicha4a61982006-03-24 03:15:54 -08001640 old_base = per_cpu(tvec_bases, cpu);
1641 new_base = get_cpu_var(tvec_bases);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001642
1643 local_irq_disable();
Oleg Nesterov3691c512006-03-31 02:30:30 -08001644 spin_lock(&new_base->lock);
1645 spin_lock(&old_base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001646
Oleg Nesterov3691c512006-03-31 02:30:30 -08001647 BUG_ON(old_base->running_timer);
1648
Linus Torvalds1da177e2005-04-16 15:20:36 -07001649 for (i = 0; i < TVR_SIZE; i++)
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001650 migrate_timer_list(new_base, old_base->tv1.vec + i);
1651 for (i = 0; i < TVN_SIZE; i++) {
1652 migrate_timer_list(new_base, old_base->tv2.vec + i);
1653 migrate_timer_list(new_base, old_base->tv3.vec + i);
1654 migrate_timer_list(new_base, old_base->tv4.vec + i);
1655 migrate_timer_list(new_base, old_base->tv5.vec + i);
1656 }
1657
Oleg Nesterov3691c512006-03-31 02:30:30 -08001658 spin_unlock(&old_base->lock);
1659 spin_unlock(&new_base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001660 local_irq_enable();
1661 put_cpu_var(tvec_bases);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001662}
1663#endif /* CONFIG_HOTPLUG_CPU */
1664
Chandra Seetharaman8c78f302006-07-30 03:03:35 -07001665static int __cpuinit timer_cpu_notify(struct notifier_block *self,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001666 unsigned long action, void *hcpu)
1667{
1668 long cpu = (long)hcpu;
1669 switch(action) {
1670 case CPU_UP_PREPARE:
Jan Beulicha4a61982006-03-24 03:15:54 -08001671 if (init_timers_cpu(cpu) < 0)
1672 return NOTIFY_BAD;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001673 break;
1674#ifdef CONFIG_HOTPLUG_CPU
1675 case CPU_DEAD:
1676 migrate_timers(cpu);
1677 break;
1678#endif
1679 default:
1680 break;
1681 }
1682 return NOTIFY_OK;
1683}
1684
Chandra Seetharaman8c78f302006-07-30 03:03:35 -07001685static struct notifier_block __cpuinitdata timers_nb = {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001686 .notifier_call = timer_cpu_notify,
1687};
1688
1689
1690void __init init_timers(void)
1691{
1692 timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1693 (void *)(long)smp_processor_id());
1694 register_cpu_notifier(&timers_nb);
1695 open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1696}
1697
1698#ifdef CONFIG_TIME_INTERPOLATION
1699
Christoph Lameter67890d72006-03-16 23:04:00 -08001700struct time_interpolator *time_interpolator __read_mostly;
1701static struct time_interpolator *time_interpolator_list __read_mostly;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001702static DEFINE_SPINLOCK(time_interpolator_lock);
1703
1704static inline u64 time_interpolator_get_cycles(unsigned int src)
1705{
1706 unsigned long (*x)(void);
1707
1708 switch (src)
1709 {
1710 case TIME_SOURCE_FUNCTION:
1711 x = time_interpolator->addr;
1712 return x();
1713
1714 case TIME_SOURCE_MMIO64 :
Christoph Lameter685db652006-03-02 02:54:35 -08001715 return readq_relaxed((void __iomem *)time_interpolator->addr);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001716
1717 case TIME_SOURCE_MMIO32 :
Christoph Lameter685db652006-03-02 02:54:35 -08001718 return readl_relaxed((void __iomem *)time_interpolator->addr);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001719
1720 default: return get_cycles();
1721 }
1722}
1723
Alex Williamson486d46ae2005-09-06 15:17:04 -07001724static inline u64 time_interpolator_get_counter(int writelock)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001725{
1726 unsigned int src = time_interpolator->source;
1727
1728 if (time_interpolator->jitter)
1729 {
1730 u64 lcycle;
1731 u64 now;
1732
1733 do {
1734 lcycle = time_interpolator->last_cycle;
1735 now = time_interpolator_get_cycles(src);
1736 if (lcycle && time_after(lcycle, now))
1737 return lcycle;
Alex Williamson486d46ae2005-09-06 15:17:04 -07001738
1739 /* When holding the xtime write lock, there's no need
1740 * to add the overhead of the cmpxchg. Readers are
1741 * force to retry until the write lock is released.
1742 */
1743 if (writelock) {
1744 time_interpolator->last_cycle = now;
1745 return now;
1746 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001747 /* Keep track of the last timer value returned. The use of cmpxchg here
1748 * will cause contention in an SMP environment.
1749 */
1750 } while (unlikely(cmpxchg(&time_interpolator->last_cycle, lcycle, now) != lcycle));
1751 return now;
1752 }
1753 else
1754 return time_interpolator_get_cycles(src);
1755}
1756
1757void time_interpolator_reset(void)
1758{
1759 time_interpolator->offset = 0;
Alex Williamson486d46ae2005-09-06 15:17:04 -07001760 time_interpolator->last_counter = time_interpolator_get_counter(1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001761}
1762
1763#define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
1764
1765unsigned long time_interpolator_get_offset(void)
1766{
1767 /* If we do not have a time interpolator set up then just return zero */
1768 if (!time_interpolator)
1769 return 0;
1770
1771 return time_interpolator->offset +
Alex Williamson486d46ae2005-09-06 15:17:04 -07001772 GET_TI_NSECS(time_interpolator_get_counter(0), time_interpolator);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001773}
1774
1775#define INTERPOLATOR_ADJUST 65536
1776#define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
1777
1778static void time_interpolator_update(long delta_nsec)
1779{
1780 u64 counter;
1781 unsigned long offset;
1782
1783 /* If there is no time interpolator set up then do nothing */
1784 if (!time_interpolator)
1785 return;
1786
Andrew Mortona5a0d522005-10-30 15:01:42 -08001787 /*
1788 * The interpolator compensates for late ticks by accumulating the late
1789 * time in time_interpolator->offset. A tick earlier than expected will
1790 * lead to a reset of the offset and a corresponding jump of the clock
1791 * forward. Again this only works if the interpolator clock is running
1792 * slightly slower than the regular clock and the tuning logic insures
1793 * that.
1794 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001795
Alex Williamson486d46ae2005-09-06 15:17:04 -07001796 counter = time_interpolator_get_counter(1);
Andrew Mortona5a0d522005-10-30 15:01:42 -08001797 offset = time_interpolator->offset +
1798 GET_TI_NSECS(counter, time_interpolator);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001799
1800 if (delta_nsec < 0 || (unsigned long) delta_nsec < offset)
1801 time_interpolator->offset = offset - delta_nsec;
1802 else {
1803 time_interpolator->skips++;
1804 time_interpolator->ns_skipped += delta_nsec - offset;
1805 time_interpolator->offset = 0;
1806 }
1807 time_interpolator->last_counter = counter;
1808
1809 /* Tuning logic for time interpolator invoked every minute or so.
1810 * Decrease interpolator clock speed if no skips occurred and an offset is carried.
1811 * Increase interpolator clock speed if we skip too much time.
1812 */
1813 if (jiffies % INTERPOLATOR_ADJUST == 0)
1814 {
Jordan Hargraveb20367a2006-04-07 19:50:18 +02001815 if (time_interpolator->skips == 0 && time_interpolator->offset > tick_nsec)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001816 time_interpolator->nsec_per_cyc--;
1817 if (time_interpolator->ns_skipped > INTERPOLATOR_MAX_SKIP && time_interpolator->offset == 0)
1818 time_interpolator->nsec_per_cyc++;
1819 time_interpolator->skips = 0;
1820 time_interpolator->ns_skipped = 0;
1821 }
1822}
1823
1824static inline int
1825is_better_time_interpolator(struct time_interpolator *new)
1826{
1827 if (!time_interpolator)
1828 return 1;
1829 return new->frequency > 2*time_interpolator->frequency ||
1830 (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1831}
1832
1833void
1834register_time_interpolator(struct time_interpolator *ti)
1835{
1836 unsigned long flags;
1837
1838 /* Sanity check */
Eric Sesterhenn9f312522006-04-02 13:45:55 +02001839 BUG_ON(ti->frequency == 0 || ti->mask == 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001840
1841 ti->nsec_per_cyc = ((u64)NSEC_PER_SEC << ti->shift) / ti->frequency;
1842 spin_lock(&time_interpolator_lock);
1843 write_seqlock_irqsave(&xtime_lock, flags);
1844 if (is_better_time_interpolator(ti)) {
1845 time_interpolator = ti;
1846 time_interpolator_reset();
1847 }
1848 write_sequnlock_irqrestore(&xtime_lock, flags);
1849
1850 ti->next = time_interpolator_list;
1851 time_interpolator_list = ti;
1852 spin_unlock(&time_interpolator_lock);
1853}
1854
1855void
1856unregister_time_interpolator(struct time_interpolator *ti)
1857{
1858 struct time_interpolator *curr, **prev;
1859 unsigned long flags;
1860
1861 spin_lock(&time_interpolator_lock);
1862 prev = &time_interpolator_list;
1863 for (curr = *prev; curr; curr = curr->next) {
1864 if (curr == ti) {
1865 *prev = curr->next;
1866 break;
1867 }
1868 prev = &curr->next;
1869 }
1870
1871 write_seqlock_irqsave(&xtime_lock, flags);
1872 if (ti == time_interpolator) {
1873 /* we lost the best time-interpolator: */
1874 time_interpolator = NULL;
1875 /* find the next-best interpolator */
1876 for (curr = time_interpolator_list; curr; curr = curr->next)
1877 if (is_better_time_interpolator(curr))
1878 time_interpolator = curr;
1879 time_interpolator_reset();
1880 }
1881 write_sequnlock_irqrestore(&xtime_lock, flags);
1882 spin_unlock(&time_interpolator_lock);
1883}
1884#endif /* CONFIG_TIME_INTERPOLATION */
1885
1886/**
1887 * msleep - sleep safely even with waitqueue interruptions
1888 * @msecs: Time in milliseconds to sleep for
1889 */
1890void msleep(unsigned int msecs)
1891{
1892 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1893
Nishanth Aravamudan75bcc8c2005-09-10 00:27:24 -07001894 while (timeout)
1895 timeout = schedule_timeout_uninterruptible(timeout);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001896}
1897
1898EXPORT_SYMBOL(msleep);
1899
1900/**
Domen Puncer96ec3ef2005-06-25 14:58:43 -07001901 * msleep_interruptible - sleep waiting for signals
Linus Torvalds1da177e2005-04-16 15:20:36 -07001902 * @msecs: Time in milliseconds to sleep for
1903 */
1904unsigned long msleep_interruptible(unsigned int msecs)
1905{
1906 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1907
Nishanth Aravamudan75bcc8c2005-09-10 00:27:24 -07001908 while (timeout && !signal_pending(current))
1909 timeout = schedule_timeout_interruptible(timeout);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001910 return jiffies_to_msecs(timeout);
1911}
1912
1913EXPORT_SYMBOL(msleep_interruptible);