blob: acfa557e685b9291b09a8e72fa3492d4d16c6912 [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);
Andrew Mortonba6edfc2006-04-10 22:53:58 -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)
178{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800179 tvec_base_t *base;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700180
181 for (;;) {
182 base = timer->base;
183 if (likely(base != NULL)) {
184 spin_lock_irqsave(&base->lock, *flags);
185 if (likely(base == timer->base))
186 return base;
187 /* The timer has migrated to another CPU */
188 spin_unlock_irqrestore(&base->lock, *flags);
189 }
190 cpu_relax();
191 }
192}
193
Linus Torvalds1da177e2005-04-16 15:20:36 -0700194int __mod_timer(struct timer_list *timer, unsigned long expires)
195{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800196 tvec_base_t *base, *new_base;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700197 unsigned long flags;
198 int ret = 0;
199
200 BUG_ON(!timer->function);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700201
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700202 base = lock_timer_base(timer, &flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700203
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700204 if (timer_pending(timer)) {
205 detach_timer(timer, 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700206 ret = 1;
207 }
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700208
Jan Beulicha4a61982006-03-24 03:15:54 -0800209 new_base = __get_cpu_var(tvec_bases);
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700210
Oleg Nesterov3691c512006-03-31 02:30:30 -0800211 if (base != new_base) {
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700212 /*
213 * We are trying to schedule the timer on the local CPU.
214 * However we can't change timer's base while it is running,
215 * otherwise del_timer_sync() can't detect that the timer's
216 * handler yet has not finished. This also guarantees that
217 * the timer is serialized wrt itself.
218 */
Oleg Nesterova2c348f2006-03-31 02:30:31 -0800219 if (likely(base->running_timer != timer)) {
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700220 /* See the comment in lock_timer_base() */
221 timer->base = NULL;
222 spin_unlock(&base->lock);
Oleg Nesterova2c348f2006-03-31 02:30:31 -0800223 base = new_base;
224 spin_lock(&base->lock);
225 timer->base = base;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700226 }
227 }
228
Linus Torvalds1da177e2005-04-16 15:20:36 -0700229 timer->expires = expires;
Oleg Nesterova2c348f2006-03-31 02:30:31 -0800230 internal_add_timer(base, timer);
231 spin_unlock_irqrestore(&base->lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700232
233 return ret;
234}
235
236EXPORT_SYMBOL(__mod_timer);
237
238/***
239 * add_timer_on - start a timer on a particular CPU
240 * @timer: the timer to be added
241 * @cpu: the CPU to start it on
242 *
243 * This is not very scalable on SMP. Double adds are not possible.
244 */
245void add_timer_on(struct timer_list *timer, int cpu)
246{
Jan Beulicha4a61982006-03-24 03:15:54 -0800247 tvec_base_t *base = per_cpu(tvec_bases, cpu);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700248 unsigned long flags;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700249
Linus Torvalds1da177e2005-04-16 15:20:36 -0700250 BUG_ON(timer_pending(timer) || !timer->function);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800251 spin_lock_irqsave(&base->lock, flags);
252 timer->base = base;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700253 internal_add_timer(base, timer);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800254 spin_unlock_irqrestore(&base->lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700255}
256
257
258/***
259 * mod_timer - modify a timer's timeout
260 * @timer: the timer to be modified
261 *
262 * mod_timer is a more efficient way to update the expire field of an
263 * active timer (if the timer is inactive it will be activated)
264 *
265 * mod_timer(timer, expires) is equivalent to:
266 *
267 * del_timer(timer); timer->expires = expires; add_timer(timer);
268 *
269 * Note that if there are multiple unserialized concurrent users of the
270 * same timer, then mod_timer() is the only safe way to modify the timeout,
271 * since add_timer() cannot modify an already running timer.
272 *
273 * The function returns whether it has modified a pending timer or not.
274 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
275 * active timer returns 1.)
276 */
277int mod_timer(struct timer_list *timer, unsigned long expires)
278{
279 BUG_ON(!timer->function);
280
Linus Torvalds1da177e2005-04-16 15:20:36 -0700281 /*
282 * This is a common optimization triggered by the
283 * networking code - if the timer is re-modified
284 * to be the same thing then just return:
285 */
286 if (timer->expires == expires && timer_pending(timer))
287 return 1;
288
289 return __mod_timer(timer, expires);
290}
291
292EXPORT_SYMBOL(mod_timer);
293
294/***
295 * del_timer - deactive a timer.
296 * @timer: the timer to be deactivated
297 *
298 * del_timer() deactivates a timer - this works on both active and inactive
299 * timers.
300 *
301 * The function returns whether it has deactivated a pending timer or not.
302 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
303 * active timer returns 1.)
304 */
305int del_timer(struct timer_list *timer)
306{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800307 tvec_base_t *base;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700308 unsigned long flags;
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700309 int ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700310
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700311 if (timer_pending(timer)) {
312 base = lock_timer_base(timer, &flags);
313 if (timer_pending(timer)) {
314 detach_timer(timer, 1);
315 ret = 1;
316 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700317 spin_unlock_irqrestore(&base->lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700318 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700319
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700320 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700321}
322
323EXPORT_SYMBOL(del_timer);
324
325#ifdef CONFIG_SMP
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700326/*
327 * This function tries to deactivate a timer. Upon successful (ret >= 0)
328 * exit the timer is not queued and the handler is not running on any CPU.
329 *
330 * It must not be called from interrupt contexts.
331 */
332int try_to_del_timer_sync(struct timer_list *timer)
333{
Oleg Nesterov3691c512006-03-31 02:30:30 -0800334 tvec_base_t *base;
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700335 unsigned long flags;
336 int ret = -1;
337
338 base = lock_timer_base(timer, &flags);
339
340 if (base->running_timer == timer)
341 goto out;
342
343 ret = 0;
344 if (timer_pending(timer)) {
345 detach_timer(timer, 1);
346 ret = 1;
347 }
348out:
349 spin_unlock_irqrestore(&base->lock, flags);
350
351 return ret;
352}
353
Linus Torvalds1da177e2005-04-16 15:20:36 -0700354/***
355 * del_timer_sync - deactivate a timer and wait for the handler to finish.
356 * @timer: the timer to be deactivated
357 *
358 * This function only differs from del_timer() on SMP: besides deactivating
359 * the timer it also makes sure the handler has finished executing on other
360 * CPUs.
361 *
362 * Synchronization rules: callers must prevent restarting of the timer,
363 * otherwise this function is meaningless. It must not be called from
364 * interrupt contexts. The caller must not hold locks which would prevent
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700365 * completion of the timer's handler. The timer's handler must not call
366 * add_timer_on(). Upon exit the timer is not queued and the handler is
367 * not running on any CPU.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700368 *
369 * The function returns whether it has deactivated a pending timer or not.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700370 */
371int del_timer_sync(struct timer_list *timer)
372{
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700373 for (;;) {
374 int ret = try_to_del_timer_sync(timer);
375 if (ret >= 0)
376 return ret;
Andrew Mortona0009652006-07-14 00:24:06 -0700377 cpu_relax();
Oleg Nesterovfd450b72005-06-23 00:08:59 -0700378 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700379}
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700380
Linus Torvalds1da177e2005-04-16 15:20:36 -0700381EXPORT_SYMBOL(del_timer_sync);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700382#endif
383
384static int cascade(tvec_base_t *base, tvec_t *tv, int index)
385{
386 /* cascade all the timers from tv up one level */
Porpoise3439dd82006-06-23 02:05:56 -0700387 struct timer_list *timer, *tmp;
388 struct list_head tv_list;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700389
Porpoise3439dd82006-06-23 02:05:56 -0700390 list_replace_init(tv->vec + index, &tv_list);
391
Linus Torvalds1da177e2005-04-16 15:20:36 -0700392 /*
Porpoise3439dd82006-06-23 02:05:56 -0700393 * We are removing _all_ timers from the list, so we
394 * don't have to detach them individually.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700395 */
Porpoise3439dd82006-06-23 02:05:56 -0700396 list_for_each_entry_safe(timer, tmp, &tv_list, entry) {
397 BUG_ON(timer->base != base);
398 internal_add_timer(base, timer);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700399 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700400
401 return index;
402}
403
404/***
405 * __run_timers - run all expired timers (if any) on this CPU.
406 * @base: the timer vector to be processed.
407 *
408 * This function cascades all vectors and executes all expired timer
409 * vectors.
410 */
411#define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
412
413static inline void __run_timers(tvec_base_t *base)
414{
415 struct timer_list *timer;
416
Oleg Nesterov3691c512006-03-31 02:30:30 -0800417 spin_lock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700418 while (time_after_eq(jiffies, base->timer_jiffies)) {
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700419 struct list_head work_list;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700420 struct list_head *head = &work_list;
421 int index = base->timer_jiffies & TVR_MASK;
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700422
Linus Torvalds1da177e2005-04-16 15:20:36 -0700423 /*
424 * Cascade timers:
425 */
426 if (!index &&
427 (!cascade(base, &base->tv2, INDEX(0))) &&
428 (!cascade(base, &base->tv3, INDEX(1))) &&
429 !cascade(base, &base->tv4, INDEX(2)))
430 cascade(base, &base->tv5, INDEX(3));
Oleg Nesterov626ab0e2006-06-23 02:05:55 -0700431 ++base->timer_jiffies;
432 list_replace_init(base->tv1.vec + index, &work_list);
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700433 while (!list_empty(head)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700434 void (*fn)(unsigned long);
435 unsigned long data;
436
437 timer = list_entry(head->next,struct timer_list,entry);
438 fn = timer->function;
439 data = timer->data;
440
Linus Torvalds1da177e2005-04-16 15:20:36 -0700441 set_running_timer(base, timer);
Oleg Nesterov55c888d2005-06-23 00:08:56 -0700442 detach_timer(timer, 1);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800443 spin_unlock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700444 {
Jesper Juhlbe5b4fb2005-06-23 00:09:09 -0700445 int preempt_count = preempt_count();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700446 fn(data);
447 if (preempt_count != preempt_count()) {
Jesper Juhlbe5b4fb2005-06-23 00:09:09 -0700448 printk(KERN_WARNING "huh, entered %p "
449 "with preempt_count %08x, exited"
450 " with %08x?\n",
451 fn, preempt_count,
452 preempt_count());
Linus Torvalds1da177e2005-04-16 15:20:36 -0700453 BUG();
454 }
455 }
Oleg Nesterov3691c512006-03-31 02:30:30 -0800456 spin_lock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700457 }
458 }
459 set_running_timer(base, NULL);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800460 spin_unlock_irq(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700461}
462
463#ifdef CONFIG_NO_IDLE_HZ
464/*
465 * Find out when the next timer event is due to happen. This
466 * is used on S/390 to stop all activity when a cpus is idle.
467 * This functions needs to be called disabled.
468 */
469unsigned long next_timer_interrupt(void)
470{
471 tvec_base_t *base;
472 struct list_head *list;
473 struct timer_list *nte;
474 unsigned long expires;
Tony Lindgren69239742006-03-06 15:42:45 -0800475 unsigned long hr_expires = MAX_JIFFY_OFFSET;
476 ktime_t hr_delta;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700477 tvec_t *varray[4];
478 int i, j;
479
Tony Lindgren69239742006-03-06 15:42:45 -0800480 hr_delta = hrtimer_get_next_event();
481 if (hr_delta.tv64 != KTIME_MAX) {
482 struct timespec tsdelta;
483 tsdelta = ktime_to_timespec(hr_delta);
484 hr_expires = timespec_to_jiffies(&tsdelta);
485 if (hr_expires < 3)
486 return hr_expires + jiffies;
487 }
488 hr_expires += jiffies;
489
Jan Beulicha4a61982006-03-24 03:15:54 -0800490 base = __get_cpu_var(tvec_bases);
Oleg Nesterov3691c512006-03-31 02:30:30 -0800491 spin_lock(&base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700492 expires = base->timer_jiffies + (LONG_MAX >> 1);
Al Viro53f087f2006-02-01 05:56:41 -0500493 list = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700494
495 /* Look for timer events in tv1. */
496 j = base->timer_jiffies & TVR_MASK;
497 do {
498 list_for_each_entry(nte, base->tv1.vec + j, entry) {
499 expires = nte->expires;
500 if (j < (base->timer_jiffies & TVR_MASK))
501 list = base->tv2.vec + (INDEX(0));
502 goto found;
503 }
504 j = (j + 1) & TVR_MASK;
505 } while (j != (base->timer_jiffies & TVR_MASK));
506
507 /* Check tv2-tv5. */
508 varray[0] = &base->tv2;
509 varray[1] = &base->tv3;
510 varray[2] = &base->tv4;
511 varray[3] = &base->tv5;
512 for (i = 0; i < 4; i++) {
513 j = INDEX(i);
514 do {
515 if (list_empty(varray[i]->vec + j)) {
516 j = (j + 1) & TVN_MASK;
517 continue;
518 }
519 list_for_each_entry(nte, varray[i]->vec + j, entry)
520 if (time_before(nte->expires, expires))
521 expires = nte->expires;
522 if (j < (INDEX(i)) && i < 3)
523 list = varray[i + 1]->vec + (INDEX(i + 1));
524 goto found;
525 } while (j != (INDEX(i)));
526 }
527found:
528 if (list) {
529 /*
530 * The search wrapped. We need to look at the next list
531 * from next tv element that would cascade into tv element
532 * where we found the timer element.
533 */
534 list_for_each_entry(nte, list, entry) {
535 if (time_before(nte->expires, expires))
536 expires = nte->expires;
537 }
538 }
Oleg Nesterov3691c512006-03-31 02:30:30 -0800539 spin_unlock(&base->lock);
Tony Lindgren69239742006-03-06 15:42:45 -0800540
Zachary Amsden0662b712006-05-20 15:00:24 -0700541 /*
542 * It can happen that other CPUs service timer IRQs and increment
543 * jiffies, but we have not yet got a local timer tick to process
544 * the timer wheels. In that case, the expiry time can be before
545 * jiffies, but since the high-resolution timer here is relative to
546 * jiffies, the default expression when high-resolution timers are
547 * not active,
548 *
549 * time_before(MAX_JIFFY_OFFSET + jiffies, expires)
550 *
551 * would falsely evaluate to true. If that is the case, just
552 * return jiffies so that we can immediately fire the local timer
553 */
554 if (time_before(expires, jiffies))
555 return jiffies;
556
Tony Lindgren69239742006-03-06 15:42:45 -0800557 if (time_before(hr_expires, expires))
558 return hr_expires;
559
Linus Torvalds1da177e2005-04-16 15:20:36 -0700560 return expires;
561}
562#endif
563
564/******************************************************************/
565
566/*
567 * Timekeeping variables
568 */
569unsigned long tick_usec = TICK_USEC; /* USER_HZ period (usec) */
570unsigned long tick_nsec = TICK_NSEC; /* ACTHZ period (nsec) */
571
572/*
573 * The current time
574 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
575 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
576 * at zero at system boot time, so wall_to_monotonic will be negative,
577 * however, we will ALWAYS keep the tv_nsec part positive so we can use
578 * the usual normalization.
579 */
580struct timespec xtime __attribute__ ((aligned (16)));
581struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
582
583EXPORT_SYMBOL(xtime);
584
585/* Don't completely fail for HZ > 500. */
586int tickadj = 500/HZ ? : 1; /* microsecs */
587
588
589/*
590 * phase-lock loop variables
591 */
592/* TIME_ERROR prevents overwriting the CMOS clock */
593int time_state = TIME_OK; /* clock synchronization status */
594int time_status = STA_UNSYNC; /* clock status bits */
595long time_offset; /* time adjustment (us) */
596long time_constant = 2; /* pll time constant */
597long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
598long time_precision = 1; /* clock precision (us) */
599long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
600long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700601long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
602 /* frequency offset (scaled ppm)*/
603static long time_adj; /* tick adjust (scaled 1 / HZ) */
604long time_reftime; /* time at last adjustment (s) */
605long time_adjust;
606long time_next_adjust;
607
608/*
609 * this routine handles the overflow of the microsecond field
610 *
611 * The tricky bits of code to handle the accurate clock support
612 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
613 * They were originally developed for SUN and DEC kernels.
614 * All the kudos should go to Dave for this stuff.
615 *
616 */
617static void second_overflow(void)
618{
Andrew Mortona5a0d522005-10-30 15:01:42 -0800619 long ltemp;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700620
Andrew Mortona5a0d522005-10-30 15:01:42 -0800621 /* Bump the maxerror field */
622 time_maxerror += time_tolerance >> SHIFT_USEC;
623 if (time_maxerror > NTP_PHASE_LIMIT) {
624 time_maxerror = NTP_PHASE_LIMIT;
625 time_status |= STA_UNSYNC;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627
Andrew Mortona5a0d522005-10-30 15:01:42 -0800628 /*
629 * Leap second processing. If in leap-insert state at the end of the
630 * day, the system clock is set back one second; if in leap-delete
631 * state, the system clock is set ahead one second. The microtime()
632 * routine or external clock driver will insure that reported time is
633 * always monotonic. The ugly divides should be replaced.
634 */
635 switch (time_state) {
636 case TIME_OK:
637 if (time_status & STA_INS)
638 time_state = TIME_INS;
639 else if (time_status & STA_DEL)
640 time_state = TIME_DEL;
641 break;
642 case TIME_INS:
643 if (xtime.tv_sec % 86400 == 0) {
644 xtime.tv_sec--;
645 wall_to_monotonic.tv_sec++;
646 /*
647 * The timer interpolator will make time change
648 * gradually instead of an immediate jump by one second
649 */
650 time_interpolator_update(-NSEC_PER_SEC);
651 time_state = TIME_OOP;
652 clock_was_set();
653 printk(KERN_NOTICE "Clock: inserting leap second "
654 "23:59:60 UTC\n");
655 }
656 break;
657 case TIME_DEL:
658 if ((xtime.tv_sec + 1) % 86400 == 0) {
659 xtime.tv_sec++;
660 wall_to_monotonic.tv_sec--;
661 /*
662 * Use of time interpolator for a gradual change of
663 * time
664 */
665 time_interpolator_update(NSEC_PER_SEC);
666 time_state = TIME_WAIT;
667 clock_was_set();
668 printk(KERN_NOTICE "Clock: deleting leap second "
669 "23:59:59 UTC\n");
670 }
671 break;
672 case TIME_OOP:
673 time_state = TIME_WAIT;
674 break;
675 case TIME_WAIT:
676 if (!(time_status & (STA_INS | STA_DEL)))
677 time_state = TIME_OK;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700678 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700679
Andrew Mortona5a0d522005-10-30 15:01:42 -0800680 /*
681 * Compute the phase adjustment for the next second. In PLL mode, the
682 * offset is reduced by a fixed factor times the time constant. In FLL
683 * mode the offset is used directly. In either mode, the maximum phase
684 * adjustment for each second is clamped so as to spread the adjustment
685 * over not more than the number of seconds between updates.
686 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700687 ltemp = time_offset;
688 if (!(time_status & STA_FLL))
john stultz1bb34a42005-10-30 15:01:42 -0800689 ltemp = shift_right(ltemp, SHIFT_KG + time_constant);
690 ltemp = min(ltemp, (MAXPHASE / MINSEC) << SHIFT_UPDATE);
691 ltemp = max(ltemp, -(MAXPHASE / MINSEC) << SHIFT_UPDATE);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692 time_offset -= ltemp;
693 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694
Andrew Mortona5a0d522005-10-30 15:01:42 -0800695 /*
696 * Compute the frequency estimate and additional phase adjustment due
Roman Zippel5ddcfa82006-03-25 03:08:28 -0800697 * to frequency error for the next second.
Andrew Mortona5a0d522005-10-30 15:01:42 -0800698 */
Roman Zippel5ddcfa82006-03-25 03:08:28 -0800699 ltemp = time_freq;
Andrew Mortona5a0d522005-10-30 15:01:42 -0800700 time_adj += shift_right(ltemp,(SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE));
Linus Torvalds1da177e2005-04-16 15:20:36 -0700701
702#if HZ == 100
Andrew Mortona5a0d522005-10-30 15:01:42 -0800703 /*
704 * Compensate for (HZ==100) != (1 << SHIFT_HZ). Add 25% and 3.125% to
705 * get 128.125; => only 0.125% error (p. 14)
706 */
707 time_adj += shift_right(time_adj, 2) + shift_right(time_adj, 5);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700708#endif
YOSHIFUJI Hideaki4b8f5732005-10-29 18:15:42 -0700709#if HZ == 250
Andrew Mortona5a0d522005-10-30 15:01:42 -0800710 /*
711 * Compensate for (HZ==250) != (1 << SHIFT_HZ). Add 1.5625% and
712 * 0.78125% to get 255.85938; => only 0.05% error (p. 14)
713 */
714 time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
YOSHIFUJI Hideaki4b8f5732005-10-29 18:15:42 -0700715#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -0700716#if HZ == 1000
Andrew Mortona5a0d522005-10-30 15:01:42 -0800717 /*
718 * Compensate for (HZ==1000) != (1 << SHIFT_HZ). Add 1.5625% and
719 * 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
720 */
721 time_adj += shift_right(time_adj, 6) + shift_right(time_adj, 7);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700722#endif
723}
724
Paul Mackerras726c14b2006-02-17 10:30:23 +1100725/*
726 * Returns how many microseconds we need to add to xtime this tick
727 * in doing an adjustment requested with adjtime.
728 */
729static long adjtime_adjustment(void)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700730{
Paul Mackerras726c14b2006-02-17 10:30:23 +1100731 long time_adjust_step;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700732
Paul Mackerras726c14b2006-02-17 10:30:23 +1100733 time_adjust_step = time_adjust;
734 if (time_adjust_step) {
Andrew Mortona5a0d522005-10-30 15:01:42 -0800735 /*
736 * We are doing an adjtime thing. Prepare time_adjust_step to
737 * be within bounds. Note that a positive time_adjust means we
738 * want the clock to run faster.
739 *
740 * Limit the amount of the step to be in the range
741 * -tickadj .. +tickadj
742 */
743 time_adjust_step = min(time_adjust_step, (long)tickadj);
744 time_adjust_step = max(time_adjust_step, (long)-tickadj);
Paul Mackerras726c14b2006-02-17 10:30:23 +1100745 }
746 return time_adjust_step;
747}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700748
Paul Mackerras726c14b2006-02-17 10:30:23 +1100749/* in the NTP reference this is called "hardclock()" */
john stultz5eb6d202006-06-26 00:25:07 -0700750static void update_ntp_one_tick(void)
Paul Mackerras726c14b2006-02-17 10:30:23 +1100751{
john stultz5eb6d202006-06-26 00:25:07 -0700752 long time_adjust_step;
Paul Mackerras726c14b2006-02-17 10:30:23 +1100753
754 time_adjust_step = adjtime_adjustment();
755 if (time_adjust_step)
Andrew Mortona5a0d522005-10-30 15:01:42 -0800756 /* Reduce by this step the amount of time left */
757 time_adjust -= time_adjust_step;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700758
759 /* Changes by adjtime() do not take effect till next tick. */
760 if (time_next_adjust != 0) {
761 time_adjust = time_next_adjust;
762 time_next_adjust = 0;
763 }
764}
765
766/*
Paul Mackerras726c14b2006-02-17 10:30:23 +1100767 * Return how long ticks are at the moment, that is, how much time
768 * update_wall_time_one_tick will add to xtime next time we call it
769 * (assuming no calls to do_adjtimex in the meantime).
john stultz260a4232006-06-26 00:25:07 -0700770 * The return value is in fixed-point nanoseconds shifted by the
771 * specified number of bits to the right of the binary point.
Paul Mackerras726c14b2006-02-17 10:30:23 +1100772 * This function has no side-effects.
773 */
Roman Zippel19923c12006-06-26 00:25:18 -0700774u64 current_tick_length(void)
Paul Mackerras726c14b2006-02-17 10:30:23 +1100775{
776 long delta_nsec;
john stultz260a4232006-06-26 00:25:07 -0700777 u64 ret;
Paul Mackerras726c14b2006-02-17 10:30:23 +1100778
john stultz260a4232006-06-26 00:25:07 -0700779 /* calculate the finest interval NTP will allow.
780 * ie: nanosecond value shifted by (SHIFT_SCALE - 10)
781 */
Paul Mackerras726c14b2006-02-17 10:30:23 +1100782 delta_nsec = tick_nsec + adjtime_adjustment() * 1000;
Roman Zippel19923c12006-06-26 00:25:18 -0700783 ret = (u64)delta_nsec << TICK_LENGTH_SHIFT;
784 ret += (s64)time_adj << (TICK_LENGTH_SHIFT - (SHIFT_SCALE - 10));
john stultz260a4232006-06-26 00:25:07 -0700785
786 return ret;
Paul Mackerras726c14b2006-02-17 10:30:23 +1100787}
788
john stultzad596172006-06-26 00:25:06 -0700789/* XXX - all of this timekeeping code should be later moved to time.c */
790#include <linux/clocksource.h>
791static struct clocksource *clock; /* pointer to current clocksource */
john stultzcf3c7692006-06-26 00:25:08 -0700792
793#ifdef CONFIG_GENERIC_TIME
794/**
795 * __get_nsec_offset - Returns nanoseconds since last call to periodic_hook
796 *
797 * private function, must hold xtime_lock lock when being
798 * called. Returns the number of nanoseconds since the
799 * last call to update_wall_time() (adjusted by NTP scaling)
800 */
801static inline s64 __get_nsec_offset(void)
802{
803 cycle_t cycle_now, cycle_delta;
804 s64 ns_offset;
805
806 /* read clocksource: */
john stultza2752542006-06-26 00:25:14 -0700807 cycle_now = clocksource_read(clock);
john stultzcf3c7692006-06-26 00:25:08 -0700808
809 /* calculate the delta since the last update_wall_time: */
Roman Zippel19923c12006-06-26 00:25:18 -0700810 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
john stultzcf3c7692006-06-26 00:25:08 -0700811
812 /* convert to nanoseconds: */
813 ns_offset = cyc2ns(clock, cycle_delta);
814
815 return ns_offset;
816}
817
818/**
819 * __get_realtime_clock_ts - Returns the time of day in a timespec
820 * @ts: pointer to the timespec to be set
821 *
822 * Returns the time of day in a timespec. Used by
823 * do_gettimeofday() and get_realtime_clock_ts().
824 */
825static inline void __get_realtime_clock_ts(struct timespec *ts)
826{
827 unsigned long seq;
828 s64 nsecs;
829
830 do {
831 seq = read_seqbegin(&xtime_lock);
832
833 *ts = xtime;
834 nsecs = __get_nsec_offset();
835
836 } while (read_seqretry(&xtime_lock, seq));
837
838 timespec_add_ns(ts, nsecs);
839}
840
841/**
john stultza2752542006-06-26 00:25:14 -0700842 * getnstimeofday - Returns the time of day in a timespec
john stultzcf3c7692006-06-26 00:25:08 -0700843 * @ts: pointer to the timespec to be set
844 *
845 * Returns the time of day in a timespec.
846 */
847void getnstimeofday(struct timespec *ts)
848{
849 __get_realtime_clock_ts(ts);
850}
851
852EXPORT_SYMBOL(getnstimeofday);
853
854/**
855 * do_gettimeofday - Returns the time of day in a timeval
856 * @tv: pointer to the timeval to be set
857 *
858 * NOTE: Users should be converted to using get_realtime_clock_ts()
859 */
860void do_gettimeofday(struct timeval *tv)
861{
862 struct timespec now;
863
864 __get_realtime_clock_ts(&now);
865 tv->tv_sec = now.tv_sec;
866 tv->tv_usec = now.tv_nsec/1000;
867}
868
869EXPORT_SYMBOL(do_gettimeofday);
870/**
871 * do_settimeofday - Sets the time of day
872 * @tv: pointer to the timespec variable containing the new time
873 *
874 * Sets the time of day to the new time and update NTP and notify hrtimers
875 */
876int do_settimeofday(struct timespec *tv)
877{
878 unsigned long flags;
879 time_t wtm_sec, sec = tv->tv_sec;
880 long wtm_nsec, nsec = tv->tv_nsec;
881
882 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
883 return -EINVAL;
884
885 write_seqlock_irqsave(&xtime_lock, flags);
886
887 nsec -= __get_nsec_offset();
888
889 wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
890 wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
891
892 set_normalized_timespec(&xtime, sec, nsec);
893 set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
894
Roman Zippele154ff32006-07-10 04:44:32 -0700895 clock->error = 0;
john stultzcf3c7692006-06-26 00:25:08 -0700896 ntp_clear();
897
898 write_sequnlock_irqrestore(&xtime_lock, flags);
899
900 /* signal hrtimers about time change */
901 clock_was_set();
902
903 return 0;
904}
905
906EXPORT_SYMBOL(do_settimeofday);
907
908/**
909 * change_clocksource - Swaps clocksources if a new one is available
910 *
911 * Accumulates current time interval and initializes new clocksource
912 */
913static int change_clocksource(void)
914{
915 struct clocksource *new;
916 cycle_t now;
917 u64 nsec;
john stultza2752542006-06-26 00:25:14 -0700918 new = clocksource_get_next();
john stultzcf3c7692006-06-26 00:25:08 -0700919 if (clock != new) {
john stultza2752542006-06-26 00:25:14 -0700920 now = clocksource_read(new);
john stultzcf3c7692006-06-26 00:25:08 -0700921 nsec = __get_nsec_offset();
922 timespec_add_ns(&xtime, nsec);
923
924 clock = new;
Roman Zippel19923c12006-06-26 00:25:18 -0700925 clock->cycle_last = now;
john stultzcf3c7692006-06-26 00:25:08 -0700926 printk(KERN_INFO "Time: %s clocksource has been installed.\n",
927 clock->name);
928 return 1;
929 } else if (clock->update_callback) {
930 return clock->update_callback();
931 }
932 return 0;
933}
934#else
935#define change_clocksource() (0)
936#endif
937
938/**
939 * timeofday_is_continuous - check to see if timekeeping is free running
940 */
941int timekeeping_is_continuous(void)
942{
943 unsigned long seq;
944 int ret;
945
946 do {
947 seq = read_seqbegin(&xtime_lock);
948
949 ret = clock->is_continuous;
950
951 } while (read_seqretry(&xtime_lock, seq));
952
953 return ret;
954}
955
Paul Mackerras726c14b2006-02-17 10:30:23 +1100956/*
john stultzad596172006-06-26 00:25:06 -0700957 * timekeeping_init - Initializes the clocksource and common timekeeping values
Linus Torvalds1da177e2005-04-16 15:20:36 -0700958 */
john stultzad596172006-06-26 00:25:06 -0700959void __init timekeeping_init(void)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700960{
john stultzad596172006-06-26 00:25:06 -0700961 unsigned long flags;
962
963 write_seqlock_irqsave(&xtime_lock, flags);
john stultza2752542006-06-26 00:25:14 -0700964 clock = clocksource_get_next();
965 clocksource_calculate_interval(clock, tick_nsec);
Roman Zippel19923c12006-06-26 00:25:18 -0700966 clock->cycle_last = clocksource_read(clock);
john stultzad596172006-06-26 00:25:06 -0700967 ntp_clear();
968 write_sequnlock_irqrestore(&xtime_lock, flags);
969}
970
971
972/*
973 * timekeeping_resume - Resumes the generic timekeeping subsystem.
974 * @dev: unused
975 *
976 * This is for the generic clocksource timekeeping.
977 * xtime/wall_to_monotonic/jiffies/wall_jiffies/etc are
978 * still managed by arch specific suspend/resume code.
979 */
980static int timekeeping_resume(struct sys_device *dev)
981{
982 unsigned long flags;
983
984 write_seqlock_irqsave(&xtime_lock, flags);
985 /* restart the last cycle value */
Roman Zippel19923c12006-06-26 00:25:18 -0700986 clock->cycle_last = clocksource_read(clock);
john stultzad596172006-06-26 00:25:06 -0700987 write_sequnlock_irqrestore(&xtime_lock, flags);
988 return 0;
989}
990
991/* sysfs resume/suspend bits for timekeeping */
992static struct sysdev_class timekeeping_sysclass = {
993 .resume = timekeeping_resume,
994 set_kset_name("timekeeping"),
995};
996
997static struct sys_device device_timer = {
998 .id = 0,
999 .cls = &timekeeping_sysclass,
1000};
1001
1002static int __init timekeeping_init_device(void)
1003{
1004 int error = sysdev_class_register(&timekeeping_sysclass);
1005 if (!error)
1006 error = sysdev_register(&device_timer);
1007 return error;
1008}
1009
1010device_initcall(timekeeping_init_device);
1011
1012/*
Roman Zippele154ff32006-07-10 04:44:32 -07001013 * If the error is already larger, we look ahead even further
Roman Zippel19923c12006-06-26 00:25:18 -07001014 * to compensate for late or lost adjustments.
1015 */
Roman Zippele154ff32006-07-10 04:44:32 -07001016static __always_inline int clocksource_bigadjust(s64 error, s64 *interval, s64 *offset)
Roman Zippel19923c12006-06-26 00:25:18 -07001017{
Roman Zippele154ff32006-07-10 04:44:32 -07001018 s64 tick_error, i;
1019 u32 look_ahead, adj;
1020 s32 error2, mult;
Roman Zippel19923c12006-06-26 00:25:18 -07001021
1022 /*
Roman Zippele154ff32006-07-10 04:44:32 -07001023 * Use the current error value to determine how much to look ahead.
1024 * The larger the error the slower we adjust for it to avoid problems
1025 * with losing too many ticks, otherwise we would overadjust and
1026 * produce an even larger error. The smaller the adjustment the
1027 * faster we try to adjust for it, as lost ticks can do less harm
1028 * here. This is tuned so that an error of about 1 msec is adusted
1029 * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
Roman Zippel19923c12006-06-26 00:25:18 -07001030 */
Roman Zippele154ff32006-07-10 04:44:32 -07001031 error2 = clock->error >> (TICK_LENGTH_SHIFT + 22 - 2 * SHIFT_HZ);
1032 error2 = abs(error2);
1033 for (look_ahead = 0; error2 > 0; look_ahead++)
1034 error2 >>= 2;
Roman Zippel19923c12006-06-26 00:25:18 -07001035
1036 /*
Roman Zippele154ff32006-07-10 04:44:32 -07001037 * Now calculate the error in (1 << look_ahead) ticks, but first
1038 * remove the single look ahead already included in the error.
Roman Zippel19923c12006-06-26 00:25:18 -07001039 */
Roman Zippele154ff32006-07-10 04:44:32 -07001040 tick_error = current_tick_length() >> (TICK_LENGTH_SHIFT - clock->shift + 1);
1041 tick_error -= clock->xtime_interval >> 1;
1042 error = ((error - tick_error) >> look_ahead) + tick_error;
Roman Zippel19923c12006-06-26 00:25:18 -07001043
Roman Zippele154ff32006-07-10 04:44:32 -07001044 /* Finally calculate the adjustment shift value. */
1045 i = *interval;
1046 mult = 1;
1047 if (error < 0) {
1048 error = -error;
1049 *interval = -*interval;
1050 *offset = -*offset;
1051 mult = -1;
Roman Zippel19923c12006-06-26 00:25:18 -07001052 }
Roman Zippele154ff32006-07-10 04:44:32 -07001053 for (adj = 0; error > i; adj++)
1054 error >>= 1;
Roman Zippel19923c12006-06-26 00:25:18 -07001055
1056 *interval <<= adj;
1057 *offset <<= adj;
Roman Zippele154ff32006-07-10 04:44:32 -07001058 return mult << adj;
Roman Zippel19923c12006-06-26 00:25:18 -07001059}
1060
1061/*
1062 * Adjust the multiplier to reduce the error value,
1063 * this is optimized for the most common adjustments of -1,0,1,
1064 * for other values we can do a bit more work.
1065 */
1066static void clocksource_adjust(struct clocksource *clock, s64 offset)
1067{
1068 s64 error, interval = clock->cycle_interval;
1069 int adj;
1070
1071 error = clock->error >> (TICK_LENGTH_SHIFT - clock->shift - 1);
1072 if (error > interval) {
Roman Zippele154ff32006-07-10 04:44:32 -07001073 error >>= 2;
1074 if (likely(error <= interval))
1075 adj = 1;
1076 else
1077 adj = clocksource_bigadjust(error, &interval, &offset);
Roman Zippel19923c12006-06-26 00:25:18 -07001078 } else if (error < -interval) {
Roman Zippele154ff32006-07-10 04:44:32 -07001079 error >>= 2;
1080 if (likely(error >= -interval)) {
1081 adj = -1;
1082 interval = -interval;
1083 offset = -offset;
1084 } else
1085 adj = clocksource_bigadjust(error, &interval, &offset);
Roman Zippel19923c12006-06-26 00:25:18 -07001086 } else
1087 return;
1088
1089 clock->mult += adj;
1090 clock->xtime_interval += interval;
1091 clock->xtime_nsec -= offset;
1092 clock->error -= (interval - offset) << (TICK_LENGTH_SHIFT - clock->shift);
1093}
1094
1095/*
john stultzad596172006-06-26 00:25:06 -07001096 * update_wall_time - Uses the current clocksource to increment the wall time
1097 *
1098 * Called from the timer interrupt, must hold a write on xtime_lock.
1099 */
1100static void update_wall_time(void)
1101{
Roman Zippel19923c12006-06-26 00:25:18 -07001102 cycle_t offset;
john stultzad596172006-06-26 00:25:06 -07001103
Roman Zippel19923c12006-06-26 00:25:18 -07001104 clock->xtime_nsec += (s64)xtime.tv_nsec << clock->shift;
john stultz5eb6d202006-06-26 00:25:07 -07001105
Roman Zippel19923c12006-06-26 00:25:18 -07001106#ifdef CONFIG_GENERIC_TIME
1107 offset = (clocksource_read(clock) - clock->cycle_last) & clock->mask;
1108#else
1109 offset = clock->cycle_interval;
1110#endif
john stultzad596172006-06-26 00:25:06 -07001111
1112 /* normally this loop will run just once, however in the
1113 * case of lost or late ticks, it will accumulate correctly.
1114 */
Roman Zippel19923c12006-06-26 00:25:18 -07001115 while (offset >= clock->cycle_interval) {
john stultzad596172006-06-26 00:25:06 -07001116 /* accumulate one interval */
Roman Zippel19923c12006-06-26 00:25:18 -07001117 clock->xtime_nsec += clock->xtime_interval;
1118 clock->cycle_last += clock->cycle_interval;
1119 offset -= clock->cycle_interval;
1120
1121 if (clock->xtime_nsec >= (u64)NSEC_PER_SEC << clock->shift) {
1122 clock->xtime_nsec -= (u64)NSEC_PER_SEC << clock->shift;
1123 xtime.tv_sec++;
1124 second_overflow();
1125 }
john stultzad596172006-06-26 00:25:06 -07001126
john stultz5eb6d202006-06-26 00:25:07 -07001127 /* interpolator bits */
Roman Zippel19923c12006-06-26 00:25:18 -07001128 time_interpolator_update(clock->xtime_interval
john stultz5eb6d202006-06-26 00:25:07 -07001129 >> clock->shift);
1130 /* increment the NTP state machine */
1131 update_ntp_one_tick();
1132
1133 /* accumulate error between NTP and clock interval */
Roman Zippel19923c12006-06-26 00:25:18 -07001134 clock->error += current_tick_length();
1135 clock->error -= clock->xtime_interval << (TICK_LENGTH_SHIFT - clock->shift);
john stultzad596172006-06-26 00:25:06 -07001136 }
Roman Zippel19923c12006-06-26 00:25:18 -07001137
1138 /* correct the clock when NTP error is too big */
1139 clocksource_adjust(clock, offset);
1140
john stultz5eb6d202006-06-26 00:25:07 -07001141 /* store full nanoseconds into xtime */
Roman Zippele154ff32006-07-10 04:44:32 -07001142 xtime.tv_nsec = (s64)clock->xtime_nsec >> clock->shift;
Roman Zippel19923c12006-06-26 00:25:18 -07001143 clock->xtime_nsec -= (s64)xtime.tv_nsec << clock->shift;
john stultzcf3c7692006-06-26 00:25:08 -07001144
1145 /* check to see if there is a new clocksource to use */
1146 if (change_clocksource()) {
Roman Zippel19923c12006-06-26 00:25:18 -07001147 clock->error = 0;
1148 clock->xtime_nsec = 0;
john stultza2752542006-06-26 00:25:14 -07001149 clocksource_calculate_interval(clock, tick_nsec);
john stultzcf3c7692006-06-26 00:25:08 -07001150 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001151}
1152
1153/*
1154 * Called from the timer interrupt handler to charge one tick to the current
1155 * process. user_tick is 1 if the tick is user time, 0 for system.
1156 */
1157void update_process_times(int user_tick)
1158{
1159 struct task_struct *p = current;
1160 int cpu = smp_processor_id();
1161
1162 /* Note: this timer irq context must be accounted for as well. */
1163 if (user_tick)
1164 account_user_time(p, jiffies_to_cputime(1));
1165 else
1166 account_system_time(p, HARDIRQ_OFFSET, jiffies_to_cputime(1));
1167 run_local_timers();
1168 if (rcu_pending(cpu))
1169 rcu_check_callbacks(cpu, user_tick);
1170 scheduler_tick();
1171 run_posix_cpu_timers(p);
1172}
1173
1174/*
1175 * Nr of active tasks - counted in fixed-point numbers
1176 */
1177static unsigned long count_active_tasks(void)
1178{
Jack Steinerdb1b1fe2006-03-31 02:31:21 -08001179 return nr_active() * FIXED_1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001180}
1181
1182/*
1183 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
1184 * imply that avenrun[] is the standard name for this kind of thing.
1185 * Nothing else seems to be standardized: the fractional size etc
1186 * all seem to differ on different machines.
1187 *
1188 * Requires xtime_lock to access.
1189 */
1190unsigned long avenrun[3];
1191
1192EXPORT_SYMBOL(avenrun);
1193
1194/*
1195 * calc_load - given tick count, update the avenrun load estimates.
1196 * This is called while holding a write_lock on xtime_lock.
1197 */
1198static inline void calc_load(unsigned long ticks)
1199{
1200 unsigned long active_tasks; /* fixed-point */
1201 static int count = LOAD_FREQ;
1202
1203 count -= ticks;
1204 if (count < 0) {
1205 count += LOAD_FREQ;
1206 active_tasks = count_active_tasks();
1207 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
1208 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
1209 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
1210 }
1211}
1212
1213/* jiffies at the most recent update of wall time */
1214unsigned long wall_jiffies = INITIAL_JIFFIES;
1215
1216/*
1217 * This read-write spinlock protects us from races in SMP while
1218 * playing with xtime and avenrun.
1219 */
1220#ifndef ARCH_HAVE_XTIME_LOCK
Ingo Molnare4d91912006-07-03 00:24:34 -07001221__cacheline_aligned_in_smp DEFINE_SEQLOCK(xtime_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001222
1223EXPORT_SYMBOL(xtime_lock);
1224#endif
1225
1226/*
1227 * This function runs timers and the timer-tq in bottom half context.
1228 */
1229static void run_timer_softirq(struct softirq_action *h)
1230{
Jan Beulicha4a61982006-03-24 03:15:54 -08001231 tvec_base_t *base = __get_cpu_var(tvec_bases);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001232
Thomas Gleixnerc0a31322006-01-09 20:52:32 -08001233 hrtimer_run_queues();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001234 if (time_after_eq(jiffies, base->timer_jiffies))
1235 __run_timers(base);
1236}
1237
1238/*
1239 * Called by the local, per-CPU timer interrupt on SMP.
1240 */
1241void run_local_timers(void)
1242{
1243 raise_softirq(TIMER_SOFTIRQ);
Ingo Molnar6687a972006-03-24 03:18:41 -08001244 softlockup_tick();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001245}
1246
1247/*
1248 * Called by the timer interrupt. xtime_lock must already be taken
1249 * by the timer IRQ!
1250 */
1251static inline void update_times(void)
1252{
1253 unsigned long ticks;
1254
1255 ticks = jiffies - wall_jiffies;
john stultzad596172006-06-26 00:25:06 -07001256 wall_jiffies += ticks;
1257 update_wall_time();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001258 calc_load(ticks);
1259}
1260
1261/*
1262 * The 64-bit jiffies value is not atomic - you MUST NOT read it
1263 * without sampling the sequence number in xtime_lock.
1264 * jiffies is defined in the linker script...
1265 */
1266
1267void do_timer(struct pt_regs *regs)
1268{
1269 jiffies_64++;
Atsushi Nemoto5aee4052006-03-06 15:42:51 -08001270 /* prevent loading jiffies before storing new jiffies_64 value. */
1271 barrier();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001272 update_times();
1273}
1274
1275#ifdef __ARCH_WANT_SYS_ALARM
1276
1277/*
1278 * For backwards compatibility? This can be done in libc so Alpha
1279 * and all newer ports shouldn't need it.
1280 */
1281asmlinkage unsigned long sys_alarm(unsigned int seconds)
1282{
Thomas Gleixnerc08b8a42006-03-25 03:06:33 -08001283 return alarm_setitimer(seconds);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001284}
1285
1286#endif
1287
1288#ifndef __alpha__
1289
1290/*
1291 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
1292 * should be moved into arch/i386 instead?
1293 */
1294
1295/**
1296 * sys_getpid - return the thread group id of the current process
1297 *
1298 * Note, despite the name, this returns the tgid not the pid. The tgid and
1299 * the pid are identical unless CLONE_THREAD was specified on clone() in
1300 * which case the tgid is the same in all threads of the same group.
1301 *
1302 * This is SMP safe as current->tgid does not change.
1303 */
1304asmlinkage long sys_getpid(void)
1305{
1306 return current->tgid;
1307}
1308
1309/*
1310 * Accessing ->group_leader->real_parent is not SMP-safe, it could
1311 * change from under us. However, rather than getting any lock
1312 * we can use an optimistic algorithm: get the parent
1313 * pid, and go back and check that the parent is still
1314 * the same. If it has changed (which is extremely unlikely
1315 * indeed), we just try again..
1316 *
1317 * NOTE! This depends on the fact that even if we _do_
1318 * get an old value of "parent", we can happily dereference
1319 * the pointer (it was and remains a dereferencable kernel pointer
1320 * no matter what): we just can't necessarily trust the result
1321 * until we know that the parent pointer is valid.
1322 *
1323 * NOTE2: ->group_leader never changes from under us.
1324 */
1325asmlinkage long sys_getppid(void)
1326{
1327 int pid;
1328 struct task_struct *me = current;
1329 struct task_struct *parent;
1330
1331 parent = me->group_leader->real_parent;
1332 for (;;) {
1333 pid = parent->tgid;
David Meybohm4c5640c2005-08-22 13:11:08 -07001334#if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001335{
1336 struct task_struct *old = parent;
1337
1338 /*
1339 * Make sure we read the pid before re-reading the
1340 * parent pointer:
1341 */
akpm@osdl.orgd59dd462005-05-01 08:58:47 -07001342 smp_rmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001343 parent = me->group_leader->real_parent;
1344 if (old != parent)
1345 continue;
1346}
1347#endif
1348 break;
1349 }
1350 return pid;
1351}
1352
1353asmlinkage long sys_getuid(void)
1354{
1355 /* Only we change this so SMP safe */
1356 return current->uid;
1357}
1358
1359asmlinkage long sys_geteuid(void)
1360{
1361 /* Only we change this so SMP safe */
1362 return current->euid;
1363}
1364
1365asmlinkage long sys_getgid(void)
1366{
1367 /* Only we change this so SMP safe */
1368 return current->gid;
1369}
1370
1371asmlinkage long sys_getegid(void)
1372{
1373 /* Only we change this so SMP safe */
1374 return current->egid;
1375}
1376
1377#endif
1378
1379static void process_timeout(unsigned long __data)
1380{
Ingo Molnar36c8b582006-07-03 00:25:41 -07001381 wake_up_process((struct task_struct *)__data);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001382}
1383
1384/**
1385 * schedule_timeout - sleep until timeout
1386 * @timeout: timeout value in jiffies
1387 *
1388 * Make the current task sleep until @timeout jiffies have
1389 * elapsed. The routine will return immediately unless
1390 * the current task state has been set (see set_current_state()).
1391 *
1392 * You can set the task state as follows -
1393 *
1394 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1395 * pass before the routine returns. The routine will return 0
1396 *
1397 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1398 * delivered to the current task. In this case the remaining time
1399 * in jiffies will be returned, or 0 if the timer expired in time
1400 *
1401 * The current task state is guaranteed to be TASK_RUNNING when this
1402 * routine returns.
1403 *
1404 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1405 * the CPU away without a bound on the timeout. In this case the return
1406 * value will be %MAX_SCHEDULE_TIMEOUT.
1407 *
1408 * In all cases the return value is guaranteed to be non-negative.
1409 */
1410fastcall signed long __sched schedule_timeout(signed long timeout)
1411{
1412 struct timer_list timer;
1413 unsigned long expire;
1414
1415 switch (timeout)
1416 {
1417 case MAX_SCHEDULE_TIMEOUT:
1418 /*
1419 * These two special cases are useful to be comfortable
1420 * in the caller. Nothing more. We could take
1421 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1422 * but I' d like to return a valid offset (>=0) to allow
1423 * the caller to do everything it want with the retval.
1424 */
1425 schedule();
1426 goto out;
1427 default:
1428 /*
1429 * Another bit of PARANOID. Note that the retval will be
1430 * 0 since no piece of kernel is supposed to do a check
1431 * for a negative retval of schedule_timeout() (since it
1432 * should never happens anyway). You just have the printk()
1433 * that will tell you if something is gone wrong and where.
1434 */
1435 if (timeout < 0)
1436 {
1437 printk(KERN_ERR "schedule_timeout: wrong timeout "
Andrew Mortona5a0d522005-10-30 15:01:42 -08001438 "value %lx from %p\n", timeout,
1439 __builtin_return_address(0));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001440 current->state = TASK_RUNNING;
1441 goto out;
1442 }
1443 }
1444
1445 expire = timeout + jiffies;
1446
Oleg Nesterova8db2db2005-10-30 15:01:38 -08001447 setup_timer(&timer, process_timeout, (unsigned long)current);
1448 __mod_timer(&timer, expire);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001449 schedule();
1450 del_singleshot_timer_sync(&timer);
1451
1452 timeout = expire - jiffies;
1453
1454 out:
1455 return timeout < 0 ? 0 : timeout;
1456}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001457EXPORT_SYMBOL(schedule_timeout);
1458
Andrew Morton8a1c1752005-09-13 01:25:15 -07001459/*
1460 * We can use __set_current_state() here because schedule_timeout() calls
1461 * schedule() unconditionally.
1462 */
Nishanth Aravamudan64ed93a2005-09-10 00:27:21 -07001463signed long __sched schedule_timeout_interruptible(signed long timeout)
1464{
Andrew Mortona5a0d522005-10-30 15:01:42 -08001465 __set_current_state(TASK_INTERRUPTIBLE);
1466 return schedule_timeout(timeout);
Nishanth Aravamudan64ed93a2005-09-10 00:27:21 -07001467}
1468EXPORT_SYMBOL(schedule_timeout_interruptible);
1469
1470signed long __sched schedule_timeout_uninterruptible(signed long timeout)
1471{
Andrew Mortona5a0d522005-10-30 15:01:42 -08001472 __set_current_state(TASK_UNINTERRUPTIBLE);
1473 return schedule_timeout(timeout);
Nishanth Aravamudan64ed93a2005-09-10 00:27:21 -07001474}
1475EXPORT_SYMBOL(schedule_timeout_uninterruptible);
1476
Linus Torvalds1da177e2005-04-16 15:20:36 -07001477/* Thread ID - the internal kernel "pid" */
1478asmlinkage long sys_gettid(void)
1479{
1480 return current->pid;
1481}
1482
Linus Torvalds1da177e2005-04-16 15:20:36 -07001483/*
1484 * sys_sysinfo - fill in sysinfo struct
1485 */
1486asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1487{
1488 struct sysinfo val;
1489 unsigned long mem_total, sav_total;
1490 unsigned int mem_unit, bitcount;
1491 unsigned long seq;
1492
1493 memset((char *)&val, 0, sizeof(struct sysinfo));
1494
1495 do {
1496 struct timespec tp;
1497 seq = read_seqbegin(&xtime_lock);
1498
1499 /*
1500 * This is annoying. The below is the same thing
1501 * posix_get_clock_monotonic() does, but it wants to
1502 * take the lock which we want to cover the loads stuff
1503 * too.
1504 */
1505
1506 getnstimeofday(&tp);
1507 tp.tv_sec += wall_to_monotonic.tv_sec;
1508 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1509 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1510 tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1511 tp.tv_sec++;
1512 }
1513 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1514
1515 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1516 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1517 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1518
1519 val.procs = nr_threads;
1520 } while (read_seqretry(&xtime_lock, seq));
1521
1522 si_meminfo(&val);
1523 si_swapinfo(&val);
1524
1525 /*
1526 * If the sum of all the available memory (i.e. ram + swap)
1527 * is less than can be stored in a 32 bit unsigned long then
1528 * we can be binary compatible with 2.2.x kernels. If not,
1529 * well, in that case 2.2.x was broken anyways...
1530 *
1531 * -Erik Andersen <andersee@debian.org>
1532 */
1533
1534 mem_total = val.totalram + val.totalswap;
1535 if (mem_total < val.totalram || mem_total < val.totalswap)
1536 goto out;
1537 bitcount = 0;
1538 mem_unit = val.mem_unit;
1539 while (mem_unit > 1) {
1540 bitcount++;
1541 mem_unit >>= 1;
1542 sav_total = mem_total;
1543 mem_total <<= 1;
1544 if (mem_total < sav_total)
1545 goto out;
1546 }
1547
1548 /*
1549 * If mem_total did not overflow, multiply all memory values by
1550 * val.mem_unit and set it to 1. This leaves things compatible
1551 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1552 * kernels...
1553 */
1554
1555 val.mem_unit = 1;
1556 val.totalram <<= bitcount;
1557 val.freeram <<= bitcount;
1558 val.sharedram <<= bitcount;
1559 val.bufferram <<= bitcount;
1560 val.totalswap <<= bitcount;
1561 val.freeswap <<= bitcount;
1562 val.totalhigh <<= bitcount;
1563 val.freehigh <<= bitcount;
1564
1565 out:
1566 if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1567 return -EFAULT;
1568
1569 return 0;
1570}
1571
Ingo Molnard730e882006-07-03 00:25:10 -07001572/*
1573 * lockdep: we want to track each per-CPU base as a separate lock-class,
1574 * but timer-bases are kmalloc()-ed, so we need to attach separate
1575 * keys to them:
1576 */
1577static struct lock_class_key base_lock_keys[NR_CPUS];
1578
Jan Beulicha4a61982006-03-24 03:15:54 -08001579static int __devinit init_timers_cpu(int cpu)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001580{
1581 int j;
1582 tvec_base_t *base;
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001583 static char __devinitdata tvec_base_done[NR_CPUS];
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001584
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001585 if (!tvec_base_done[cpu]) {
Jan Beulicha4a61982006-03-24 03:15:54 -08001586 static char boot_done;
1587
Jan Beulicha4a61982006-03-24 03:15:54 -08001588 if (boot_done) {
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001589 /*
1590 * The APs use this path later in boot
1591 */
Jan Beulicha4a61982006-03-24 03:15:54 -08001592 base = kmalloc_node(sizeof(*base), GFP_KERNEL,
1593 cpu_to_node(cpu));
1594 if (!base)
1595 return -ENOMEM;
1596 memset(base, 0, sizeof(*base));
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001597 per_cpu(tvec_bases, cpu) = base;
Jan Beulicha4a61982006-03-24 03:15:54 -08001598 } else {
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001599 /*
1600 * This is for the boot CPU - we use compile-time
1601 * static initialisation because per-cpu memory isn't
1602 * ready yet and because the memory allocators are not
1603 * initialised either.
1604 */
Jan Beulicha4a61982006-03-24 03:15:54 -08001605 boot_done = 1;
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001606 base = &boot_tvec_bases;
Jan Beulicha4a61982006-03-24 03:15:54 -08001607 }
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001608 tvec_base_done[cpu] = 1;
1609 } else {
1610 base = per_cpu(tvec_bases, cpu);
Jan Beulicha4a61982006-03-24 03:15:54 -08001611 }
Andrew Mortonba6edfc2006-04-10 22:53:58 -07001612
Oleg Nesterov3691c512006-03-31 02:30:30 -08001613 spin_lock_init(&base->lock);
Ingo Molnard730e882006-07-03 00:25:10 -07001614 lockdep_set_class(&base->lock, base_lock_keys + cpu);
1615
Linus Torvalds1da177e2005-04-16 15:20:36 -07001616 for (j = 0; j < TVN_SIZE; j++) {
1617 INIT_LIST_HEAD(base->tv5.vec + j);
1618 INIT_LIST_HEAD(base->tv4.vec + j);
1619 INIT_LIST_HEAD(base->tv3.vec + j);
1620 INIT_LIST_HEAD(base->tv2.vec + j);
1621 }
1622 for (j = 0; j < TVR_SIZE; j++)
1623 INIT_LIST_HEAD(base->tv1.vec + j);
1624
1625 base->timer_jiffies = jiffies;
Jan Beulicha4a61982006-03-24 03:15:54 -08001626 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001627}
1628
1629#ifdef CONFIG_HOTPLUG_CPU
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001630static void migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001631{
1632 struct timer_list *timer;
1633
1634 while (!list_empty(head)) {
1635 timer = list_entry(head->next, struct timer_list, entry);
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001636 detach_timer(timer, 0);
Oleg Nesterov3691c512006-03-31 02:30:30 -08001637 timer->base = new_base;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001638 internal_add_timer(new_base, timer);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001639 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001640}
1641
1642static void __devinit migrate_timers(int cpu)
1643{
1644 tvec_base_t *old_base;
1645 tvec_base_t *new_base;
1646 int i;
1647
1648 BUG_ON(cpu_online(cpu));
Jan Beulicha4a61982006-03-24 03:15:54 -08001649 old_base = per_cpu(tvec_bases, cpu);
1650 new_base = get_cpu_var(tvec_bases);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001651
1652 local_irq_disable();
Oleg Nesterov3691c512006-03-31 02:30:30 -08001653 spin_lock(&new_base->lock);
1654 spin_lock(&old_base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001655
Oleg Nesterov3691c512006-03-31 02:30:30 -08001656 BUG_ON(old_base->running_timer);
1657
Linus Torvalds1da177e2005-04-16 15:20:36 -07001658 for (i = 0; i < TVR_SIZE; i++)
Oleg Nesterov55c888d2005-06-23 00:08:56 -07001659 migrate_timer_list(new_base, old_base->tv1.vec + i);
1660 for (i = 0; i < TVN_SIZE; i++) {
1661 migrate_timer_list(new_base, old_base->tv2.vec + i);
1662 migrate_timer_list(new_base, old_base->tv3.vec + i);
1663 migrate_timer_list(new_base, old_base->tv4.vec + i);
1664 migrate_timer_list(new_base, old_base->tv5.vec + i);
1665 }
1666
Oleg Nesterov3691c512006-03-31 02:30:30 -08001667 spin_unlock(&old_base->lock);
1668 spin_unlock(&new_base->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001669 local_irq_enable();
1670 put_cpu_var(tvec_bases);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001671}
1672#endif /* CONFIG_HOTPLUG_CPU */
1673
Chandra Seetharaman9c7b2162006-06-27 02:54:07 -07001674static int __devinit timer_cpu_notify(struct notifier_block *self,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001675 unsigned long action, void *hcpu)
1676{
1677 long cpu = (long)hcpu;
1678 switch(action) {
1679 case CPU_UP_PREPARE:
Jan Beulicha4a61982006-03-24 03:15:54 -08001680 if (init_timers_cpu(cpu) < 0)
1681 return NOTIFY_BAD;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001682 break;
1683#ifdef CONFIG_HOTPLUG_CPU
1684 case CPU_DEAD:
1685 migrate_timers(cpu);
1686 break;
1687#endif
1688 default:
1689 break;
1690 }
1691 return NOTIFY_OK;
1692}
1693
Chandra Seetharaman054cc8a2006-06-27 02:54:07 -07001694static struct notifier_block __devinitdata timers_nb = {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 .notifier_call = timer_cpu_notify,
1696};
1697
1698
1699void __init init_timers(void)
1700{
1701 timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1702 (void *)(long)smp_processor_id());
1703 register_cpu_notifier(&timers_nb);
1704 open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1705}
1706
1707#ifdef CONFIG_TIME_INTERPOLATION
1708
Christoph Lameter67890d72006-03-16 23:04:00 -08001709struct time_interpolator *time_interpolator __read_mostly;
1710static struct time_interpolator *time_interpolator_list __read_mostly;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001711static DEFINE_SPINLOCK(time_interpolator_lock);
1712
1713static inline u64 time_interpolator_get_cycles(unsigned int src)
1714{
1715 unsigned long (*x)(void);
1716
1717 switch (src)
1718 {
1719 case TIME_SOURCE_FUNCTION:
1720 x = time_interpolator->addr;
1721 return x();
1722
1723 case TIME_SOURCE_MMIO64 :
Christoph Lameter685db652006-03-02 02:54:35 -08001724 return readq_relaxed((void __iomem *)time_interpolator->addr);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001725
1726 case TIME_SOURCE_MMIO32 :
Christoph Lameter685db652006-03-02 02:54:35 -08001727 return readl_relaxed((void __iomem *)time_interpolator->addr);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001728
1729 default: return get_cycles();
1730 }
1731}
1732
Alex Williamson486d46a2005-09-06 15:17:04 -07001733static inline u64 time_interpolator_get_counter(int writelock)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001734{
1735 unsigned int src = time_interpolator->source;
1736
1737 if (time_interpolator->jitter)
1738 {
1739 u64 lcycle;
1740 u64 now;
1741
1742 do {
1743 lcycle = time_interpolator->last_cycle;
1744 now = time_interpolator_get_cycles(src);
1745 if (lcycle && time_after(lcycle, now))
1746 return lcycle;
Alex Williamson486d46a2005-09-06 15:17:04 -07001747
1748 /* When holding the xtime write lock, there's no need
1749 * to add the overhead of the cmpxchg. Readers are
1750 * force to retry until the write lock is released.
1751 */
1752 if (writelock) {
1753 time_interpolator->last_cycle = now;
1754 return now;
1755 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001756 /* Keep track of the last timer value returned. The use of cmpxchg here
1757 * will cause contention in an SMP environment.
1758 */
1759 } while (unlikely(cmpxchg(&time_interpolator->last_cycle, lcycle, now) != lcycle));
1760 return now;
1761 }
1762 else
1763 return time_interpolator_get_cycles(src);
1764}
1765
1766void time_interpolator_reset(void)
1767{
1768 time_interpolator->offset = 0;
Alex Williamson486d46a2005-09-06 15:17:04 -07001769 time_interpolator->last_counter = time_interpolator_get_counter(1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001770}
1771
1772#define GET_TI_NSECS(count,i) (((((count) - i->last_counter) & (i)->mask) * (i)->nsec_per_cyc) >> (i)->shift)
1773
1774unsigned long time_interpolator_get_offset(void)
1775{
1776 /* If we do not have a time interpolator set up then just return zero */
1777 if (!time_interpolator)
1778 return 0;
1779
1780 return time_interpolator->offset +
Alex Williamson486d46a2005-09-06 15:17:04 -07001781 GET_TI_NSECS(time_interpolator_get_counter(0), time_interpolator);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001782}
1783
1784#define INTERPOLATOR_ADJUST 65536
1785#define INTERPOLATOR_MAX_SKIP 10*INTERPOLATOR_ADJUST
1786
1787static void time_interpolator_update(long delta_nsec)
1788{
1789 u64 counter;
1790 unsigned long offset;
1791
1792 /* If there is no time interpolator set up then do nothing */
1793 if (!time_interpolator)
1794 return;
1795
Andrew Mortona5a0d522005-10-30 15:01:42 -08001796 /*
1797 * The interpolator compensates for late ticks by accumulating the late
1798 * time in time_interpolator->offset. A tick earlier than expected will
1799 * lead to a reset of the offset and a corresponding jump of the clock
1800 * forward. Again this only works if the interpolator clock is running
1801 * slightly slower than the regular clock and the tuning logic insures
1802 * that.
1803 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001804
Alex Williamson486d46a2005-09-06 15:17:04 -07001805 counter = time_interpolator_get_counter(1);
Andrew Mortona5a0d522005-10-30 15:01:42 -08001806 offset = time_interpolator->offset +
1807 GET_TI_NSECS(counter, time_interpolator);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001808
1809 if (delta_nsec < 0 || (unsigned long) delta_nsec < offset)
1810 time_interpolator->offset = offset - delta_nsec;
1811 else {
1812 time_interpolator->skips++;
1813 time_interpolator->ns_skipped += delta_nsec - offset;
1814 time_interpolator->offset = 0;
1815 }
1816 time_interpolator->last_counter = counter;
1817
1818 /* Tuning logic for time interpolator invoked every minute or so.
1819 * Decrease interpolator clock speed if no skips occurred and an offset is carried.
1820 * Increase interpolator clock speed if we skip too much time.
1821 */
1822 if (jiffies % INTERPOLATOR_ADJUST == 0)
1823 {
Jordan Hargraveb20367a2006-04-07 19:50:18 +02001824 if (time_interpolator->skips == 0 && time_interpolator->offset > tick_nsec)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001825 time_interpolator->nsec_per_cyc--;
1826 if (time_interpolator->ns_skipped > INTERPOLATOR_MAX_SKIP && time_interpolator->offset == 0)
1827 time_interpolator->nsec_per_cyc++;
1828 time_interpolator->skips = 0;
1829 time_interpolator->ns_skipped = 0;
1830 }
1831}
1832
1833static inline int
1834is_better_time_interpolator(struct time_interpolator *new)
1835{
1836 if (!time_interpolator)
1837 return 1;
1838 return new->frequency > 2*time_interpolator->frequency ||
1839 (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1840}
1841
1842void
1843register_time_interpolator(struct time_interpolator *ti)
1844{
1845 unsigned long flags;
1846
1847 /* Sanity check */
Eric Sesterhenn9f312522006-04-02 13:45:55 +02001848 BUG_ON(ti->frequency == 0 || ti->mask == 0);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001849
1850 ti->nsec_per_cyc = ((u64)NSEC_PER_SEC << ti->shift) / ti->frequency;
1851 spin_lock(&time_interpolator_lock);
1852 write_seqlock_irqsave(&xtime_lock, flags);
1853 if (is_better_time_interpolator(ti)) {
1854 time_interpolator = ti;
1855 time_interpolator_reset();
1856 }
1857 write_sequnlock_irqrestore(&xtime_lock, flags);
1858
1859 ti->next = time_interpolator_list;
1860 time_interpolator_list = ti;
1861 spin_unlock(&time_interpolator_lock);
1862}
1863
1864void
1865unregister_time_interpolator(struct time_interpolator *ti)
1866{
1867 struct time_interpolator *curr, **prev;
1868 unsigned long flags;
1869
1870 spin_lock(&time_interpolator_lock);
1871 prev = &time_interpolator_list;
1872 for (curr = *prev; curr; curr = curr->next) {
1873 if (curr == ti) {
1874 *prev = curr->next;
1875 break;
1876 }
1877 prev = &curr->next;
1878 }
1879
1880 write_seqlock_irqsave(&xtime_lock, flags);
1881 if (ti == time_interpolator) {
1882 /* we lost the best time-interpolator: */
1883 time_interpolator = NULL;
1884 /* find the next-best interpolator */
1885 for (curr = time_interpolator_list; curr; curr = curr->next)
1886 if (is_better_time_interpolator(curr))
1887 time_interpolator = curr;
1888 time_interpolator_reset();
1889 }
1890 write_sequnlock_irqrestore(&xtime_lock, flags);
1891 spin_unlock(&time_interpolator_lock);
1892}
1893#endif /* CONFIG_TIME_INTERPOLATION */
1894
1895/**
1896 * msleep - sleep safely even with waitqueue interruptions
1897 * @msecs: Time in milliseconds to sleep for
1898 */
1899void msleep(unsigned int msecs)
1900{
1901 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1902
Nishanth Aravamudan75bcc8c2005-09-10 00:27:24 -07001903 while (timeout)
1904 timeout = schedule_timeout_uninterruptible(timeout);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001905}
1906
1907EXPORT_SYMBOL(msleep);
1908
1909/**
Domen Puncer96ec3ef2005-06-25 14:58:43 -07001910 * msleep_interruptible - sleep waiting for signals
Linus Torvalds1da177e2005-04-16 15:20:36 -07001911 * @msecs: Time in milliseconds to sleep for
1912 */
1913unsigned long msleep_interruptible(unsigned int msecs)
1914{
1915 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1916
Nishanth Aravamudan75bcc8c2005-09-10 00:27:24 -07001917 while (timeout && !signal_pending(current))
1918 timeout = schedule_timeout_interruptible(timeout);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001919 return jiffies_to_msecs(timeout);
1920}
1921
1922EXPORT_SYMBOL(msleep_interruptible);