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