4 * Kernel internal timers, kernel timekeeping, basic process system calls
6 * Copyright (C) 1991, 1992 Linus Torvalds
8 * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better.
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
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>
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/cpu.h>
34 #include <linux/vserver/sched.h>
35 #include <linux/vserver/cvirt.h>
37 #include <asm/uaccess.h>
38 #include <asm/unistd.h>
39 #include <asm/div64.h>
40 #include <asm/timex.h>
43 * per-CPU timer vector definitions:
47 #define TVN_SIZE (1 << TVN_BITS)
48 #define TVR_SIZE (1 << TVR_BITS)
49 #define TVN_MASK (TVN_SIZE - 1)
50 #define TVR_MASK (TVR_SIZE - 1)
52 typedef struct tvec_s {
53 struct list_head vec[TVN_SIZE];
56 typedef struct tvec_root_s {
57 struct list_head vec[TVR_SIZE];
60 struct tvec_t_base_s {
62 unsigned long timer_jiffies;
63 struct timer_list *running_timer;
69 } ____cacheline_aligned_in_smp;
71 typedef struct tvec_t_base_s tvec_base_t;
73 static inline void set_running_timer(tvec_base_t *base,
74 struct timer_list *timer)
77 base->running_timer = timer;
81 /* Fake initialization */
82 static DEFINE_PER_CPU(tvec_base_t, tvec_bases) = { SPIN_LOCK_UNLOCKED };
84 static void check_timer_failed(struct timer_list *timer)
86 static int whine_count;
87 if (whine_count < 16) {
89 printk("Uninitialised timer!\n");
90 printk("This is just a warning. Your computer is OK\n");
91 printk("function=0x%p, data=0x%lx\n",
92 timer->function, timer->data);
98 spin_lock_init(&timer->lock);
99 timer->magic = TIMER_MAGIC;
102 static inline void check_timer(struct timer_list *timer)
104 if (timer->magic != TIMER_MAGIC)
105 check_timer_failed(timer);
109 static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
111 unsigned long expires = timer->expires;
112 unsigned long idx = expires - base->timer_jiffies;
113 struct list_head *vec;
115 if (idx < TVR_SIZE) {
116 int i = expires & TVR_MASK;
117 vec = base->tv1.vec + i;
118 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
119 int i = (expires >> TVR_BITS) & TVN_MASK;
120 vec = base->tv2.vec + i;
121 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
122 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
123 vec = base->tv3.vec + i;
124 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
125 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
126 vec = base->tv4.vec + i;
127 } else if ((signed long) idx < 0) {
129 * Can happen if you add a timer with expires == jiffies,
130 * or you set a timer to go off in the past
132 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
135 /* If the timeout is larger than 0xffffffff on 64-bit
136 * architectures then we use the maximum timeout:
138 if (idx > 0xffffffffUL) {
140 expires = idx + base->timer_jiffies;
142 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
143 vec = base->tv5.vec + i;
148 list_add_tail(&timer->entry, vec);
151 int __mod_timer(struct timer_list *timer, unsigned long expires)
153 tvec_base_t *old_base, *new_base;
157 BUG_ON(!timer->function);
161 spin_lock_irqsave(&timer->lock, flags);
162 new_base = &__get_cpu_var(tvec_bases);
164 old_base = timer->base;
167 * Prevent deadlocks via ordering by old_base < new_base.
169 if (old_base && (new_base != old_base)) {
170 if (old_base < new_base) {
171 spin_lock(&new_base->lock);
172 spin_lock(&old_base->lock);
174 spin_lock(&old_base->lock);
175 spin_lock(&new_base->lock);
178 * The timer base might have been cancelled while we were
179 * trying to take the lock(s):
181 if (timer->base != old_base) {
182 spin_unlock(&new_base->lock);
183 spin_unlock(&old_base->lock);
187 spin_lock(&new_base->lock);
188 if (timer->base != old_base) {
189 spin_unlock(&new_base->lock);
195 * Delete the previous timeout (if there was any), and install
199 list_del(&timer->entry);
202 timer->expires = expires;
203 internal_add_timer(new_base, timer);
204 timer->base = new_base;
206 if (old_base && (new_base != old_base))
207 spin_unlock(&old_base->lock);
208 spin_unlock(&new_base->lock);
209 spin_unlock_irqrestore(&timer->lock, flags);
214 EXPORT_SYMBOL(__mod_timer);
217 * add_timer_on - start a timer on a particular CPU
218 * @timer: the timer to be added
219 * @cpu: the CPU to start it on
221 * This is not very scalable on SMP. Double adds are not possible.
223 void add_timer_on(struct timer_list *timer, int cpu)
225 tvec_base_t *base = &per_cpu(tvec_bases, cpu);
228 BUG_ON(timer_pending(timer) || !timer->function);
232 spin_lock_irqsave(&base->lock, flags);
233 internal_add_timer(base, timer);
235 spin_unlock_irqrestore(&base->lock, flags);
239 * mod_timer - modify a timer's timeout
240 * @timer: the timer to be modified
242 * mod_timer is a more efficient way to update the expire field of an
243 * active timer (if the timer is inactive it will be activated)
245 * mod_timer(timer, expires) is equivalent to:
247 * del_timer(timer); timer->expires = expires; add_timer(timer);
249 * Note that if there are multiple unserialized concurrent users of the
250 * same timer, then mod_timer() is the only safe way to modify the timeout,
251 * since add_timer() cannot modify an already running timer.
253 * The function returns whether it has modified a pending timer or not.
254 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
255 * active timer returns 1.)
257 int mod_timer(struct timer_list *timer, unsigned long expires)
259 BUG_ON(!timer->function);
264 * This is a common optimization triggered by the
265 * networking code - if the timer is re-modified
266 * to be the same thing then just return:
268 if (timer->expires == expires && timer_pending(timer))
271 return __mod_timer(timer, expires);
274 EXPORT_SYMBOL(mod_timer);
277 * del_timer - deactive a timer.
278 * @timer: the timer to be deactivated
280 * del_timer() deactivates a timer - this works on both active and inactive
283 * The function returns whether it has deactivated a pending timer or not.
284 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
285 * active timer returns 1.)
287 int del_timer(struct timer_list *timer)
298 spin_lock_irqsave(&base->lock, flags);
299 if (base != timer->base) {
300 spin_unlock_irqrestore(&base->lock, flags);
303 list_del(&timer->entry);
305 spin_unlock_irqrestore(&base->lock, flags);
310 EXPORT_SYMBOL(del_timer);
314 * del_timer_sync - deactivate a timer and wait for the handler to finish.
315 * @timer: the timer to be deactivated
317 * This function only differs from del_timer() on SMP: besides deactivating
318 * the timer it also makes sure the handler has finished executing on other
321 * Synchronization rules: callers must prevent restarting of the timer,
322 * otherwise this function is meaningless. It must not be called from
323 * interrupt contexts. The caller must not hold locks which would prevent
324 * completion of the timer's handler. Upon exit the timer is not queued and
325 * the handler is not running on any CPU.
327 * The function returns whether it has deactivated a pending timer or not.
329 * del_timer_sync() is slow and complicated because it copes with timer
330 * handlers which re-arm the timer (periodic timers). If the timer handler
331 * is known to not do this (a single shot timer) then use
332 * del_singleshot_timer_sync() instead.
334 int del_timer_sync(struct timer_list *timer)
342 ret += del_timer(timer);
344 for_each_online_cpu(i) {
345 base = &per_cpu(tvec_bases, i);
346 if (base->running_timer == timer) {
347 while (base->running_timer == timer) {
349 preempt_check_resched();
355 if (timer_pending(timer))
360 EXPORT_SYMBOL(del_timer_sync);
363 * del_singleshot_timer_sync - deactivate a non-recursive timer
364 * @timer: the timer to be deactivated
366 * This function is an optimization of del_timer_sync for the case where the
367 * caller can guarantee the timer does not reschedule itself in its timer
370 * Synchronization rules: callers must prevent restarting of the timer,
371 * otherwise this function is meaningless. It must not be called from
372 * interrupt contexts. The caller must not hold locks which wold prevent
373 * completion of the timer's handler. Upon exit the timer is not queued and
374 * the handler is not running on any CPU.
376 * The function returns whether it has deactivated a pending timer or not.
378 int del_singleshot_timer_sync(struct timer_list *timer)
380 int ret = del_timer(timer);
383 ret = del_timer_sync(timer);
389 EXPORT_SYMBOL(del_singleshot_timer_sync);
392 static int cascade(tvec_base_t *base, tvec_t *tv, int index)
394 /* cascade all the timers from tv up one level */
395 struct list_head *head, *curr;
397 head = tv->vec + index;
400 * We are removing _all_ timers from the list, so we don't have to
401 * detach them individually, just clear the list afterwards.
403 while (curr != head) {
404 struct timer_list *tmp;
406 tmp = list_entry(curr, struct timer_list, entry);
407 BUG_ON(tmp->base != base);
409 internal_add_timer(base, tmp);
411 INIT_LIST_HEAD(head);
417 * __run_timers - run all expired timers (if any) on this CPU.
418 * @base: the timer vector to be processed.
420 * This function cascades all vectors and executes all expired timer
423 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
425 static inline void __run_timers(tvec_base_t *base)
427 struct timer_list *timer;
429 spin_lock_irq(&base->lock);
430 while (time_after_eq(jiffies, base->timer_jiffies)) {
431 struct list_head work_list = LIST_HEAD_INIT(work_list);
432 struct list_head *head = &work_list;
433 int index = base->timer_jiffies & TVR_MASK;
439 (!cascade(base, &base->tv2, INDEX(0))) &&
440 (!cascade(base, &base->tv3, INDEX(1))) &&
441 !cascade(base, &base->tv4, INDEX(2)))
442 cascade(base, &base->tv5, INDEX(3));
443 ++base->timer_jiffies;
444 list_splice_init(base->tv1.vec + index, &work_list);
446 if (!list_empty(head)) {
447 void (*fn)(unsigned long);
450 timer = list_entry(head->next,struct timer_list,entry);
451 fn = timer->function;
454 list_del(&timer->entry);
455 set_running_timer(base, timer);
458 spin_unlock_irq(&base->lock);
460 spin_lock_irq(&base->lock);
464 set_running_timer(base, NULL);
465 spin_unlock_irq(&base->lock);
468 #ifdef CONFIG_NO_IDLE_HZ
470 * Find out when the next timer event is due to happen. This
471 * is used on S/390 to stop all activity when a cpus is idle.
472 * This functions needs to be called disabled.
474 unsigned long next_timer_interrupt(void)
477 struct list_head *list;
478 struct timer_list *nte;
479 unsigned long expires;
483 base = &__get_cpu_var(tvec_bases);
484 spin_lock(&base->lock);
485 expires = base->timer_jiffies + (LONG_MAX >> 1);
488 /* Look for timer events in tv1. */
489 j = base->timer_jiffies & TVR_MASK;
491 list_for_each_entry(nte, base->tv1.vec + j, entry) {
492 expires = nte->expires;
493 if (j < (base->timer_jiffies & TVR_MASK))
494 list = base->tv2.vec + (INDEX(0));
497 j = (j + 1) & TVR_MASK;
498 } while (j != (base->timer_jiffies & TVR_MASK));
501 varray[0] = &base->tv2;
502 varray[1] = &base->tv3;
503 varray[2] = &base->tv4;
504 varray[3] = &base->tv5;
505 for (i = 0; i < 4; i++) {
508 if (list_empty(varray[i]->vec + j)) {
509 j = (j + 1) & TVN_MASK;
512 list_for_each_entry(nte, varray[i]->vec + j, entry)
513 if (time_before(nte->expires, expires))
514 expires = nte->expires;
515 if (j < (INDEX(i)) && i < 3)
516 list = varray[i + 1]->vec + (INDEX(i + 1));
518 } while (j != (INDEX(i)));
523 * The search wrapped. We need to look at the next list
524 * from next tv element that would cascade into tv element
525 * where we found the timer element.
527 list_for_each_entry(nte, list, entry) {
528 if (time_before(nte->expires, expires))
529 expires = nte->expires;
532 spin_unlock(&base->lock);
537 /******************************************************************/
540 * Timekeeping variables
542 unsigned long tick_usec = TICK_USEC; /* USER_HZ period (usec) */
543 unsigned long tick_nsec = TICK_NSEC; /* ACTHZ period (nsec) */
547 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
548 * for sub jiffie times) to get to monotonic time. Monotonic is pegged at zero
549 * at zero at system boot time, so wall_to_monotonic will be negative,
550 * however, we will ALWAYS keep the tv_nsec part positive so we can use
551 * the usual normalization.
553 struct timespec xtime __attribute__ ((aligned (16)));
554 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
556 EXPORT_SYMBOL(xtime);
558 /* Don't completely fail for HZ > 500. */
559 int tickadj = 500/HZ ? : 1; /* microsecs */
563 * phase-lock loop variables
565 /* TIME_ERROR prevents overwriting the CMOS clock */
566 int time_state = TIME_OK; /* clock synchronization status */
567 int time_status = STA_UNSYNC; /* clock status bits */
568 long time_offset; /* time adjustment (us) */
569 long time_constant = 2; /* pll time constant */
570 long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
571 long time_precision = 1; /* clock precision (us) */
572 long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
573 long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
574 long time_phase; /* phase offset (scaled us) */
575 long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
576 /* frequency offset (scaled ppm)*/
577 long time_adj; /* tick adjust (scaled 1 / HZ) */
578 long time_reftime; /* time at last adjustment (s) */
580 long time_next_adjust;
583 * this routine handles the overflow of the microsecond field
585 * The tricky bits of code to handle the accurate clock support
586 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
587 * They were originally developed for SUN and DEC kernels.
588 * All the kudos should go to Dave for this stuff.
591 static void second_overflow(void)
595 /* Bump the maxerror field */
596 time_maxerror += time_tolerance >> SHIFT_USEC;
597 if ( time_maxerror > NTP_PHASE_LIMIT ) {
598 time_maxerror = NTP_PHASE_LIMIT;
599 time_status |= STA_UNSYNC;
603 * Leap second processing. If in leap-insert state at
604 * the end of the day, the system clock is set back one
605 * second; if in leap-delete state, the system clock is
606 * set ahead one second. The microtime() routine or
607 * external clock driver will insure that reported time
608 * is always monotonic. The ugly divides should be
611 switch (time_state) {
614 if (time_status & STA_INS)
615 time_state = TIME_INS;
616 else if (time_status & STA_DEL)
617 time_state = TIME_DEL;
621 if (xtime.tv_sec % 86400 == 0) {
623 wall_to_monotonic.tv_sec++;
624 time_interpolator_update(-NSEC_PER_SEC);
625 time_state = TIME_OOP;
627 printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
632 if ((xtime.tv_sec + 1) % 86400 == 0) {
634 wall_to_monotonic.tv_sec--;
635 time_interpolator_update(NSEC_PER_SEC);
636 time_state = TIME_WAIT;
638 printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
643 time_state = TIME_WAIT;
647 if (!(time_status & (STA_INS | STA_DEL)))
648 time_state = TIME_OK;
652 * Compute the phase adjustment for the next second. In
653 * PLL mode, the offset is reduced by a fixed factor
654 * times the time constant. In FLL mode the offset is
655 * used directly. In either mode, the maximum phase
656 * adjustment for each second is clamped so as to spread
657 * the adjustment over not more than the number of
658 * seconds between updates.
660 if (time_offset < 0) {
661 ltemp = -time_offset;
662 if (!(time_status & STA_FLL))
663 ltemp >>= SHIFT_KG + time_constant;
664 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
665 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
666 time_offset += ltemp;
667 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
670 if (!(time_status & STA_FLL))
671 ltemp >>= SHIFT_KG + time_constant;
672 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
673 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
674 time_offset -= ltemp;
675 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
679 * Compute the frequency estimate and additional phase
680 * adjustment due to frequency error for the next
681 * second. When the PPS signal is engaged, gnaw on the
682 * watchdog counter and update the frequency computed by
683 * the pll and the PPS signal.
686 if (pps_valid == PPS_VALID) { /* PPS signal lost */
687 pps_jitter = MAXTIME;
688 pps_stabil = MAXFREQ;
689 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
690 STA_PPSWANDER | STA_PPSERROR);
692 ltemp = time_freq + pps_freq;
694 time_adj -= -ltemp >>
695 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
698 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
701 /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
702 * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
705 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
707 time_adj += (time_adj >> 2) + (time_adj >> 5);
710 /* Compensate for (HZ==1000) != (1 << SHIFT_HZ).
711 * Add 1.5625% and 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
714 time_adj -= (-time_adj >> 6) + (-time_adj >> 7);
716 time_adj += (time_adj >> 6) + (time_adj >> 7);
720 /* in the NTP reference this is called "hardclock()" */
721 static void update_wall_time_one_tick(void)
723 long time_adjust_step, delta_nsec;
725 if ( (time_adjust_step = time_adjust) != 0 ) {
726 /* We are doing an adjtime thing.
728 * Prepare time_adjust_step to be within bounds.
729 * Note that a positive time_adjust means we want the clock
732 * Limit the amount of the step to be in the range
733 * -tickadj .. +tickadj
735 if (time_adjust > tickadj)
736 time_adjust_step = tickadj;
737 else if (time_adjust < -tickadj)
738 time_adjust_step = -tickadj;
740 /* Reduce by this step the amount of time left */
741 time_adjust -= time_adjust_step;
743 delta_nsec = tick_nsec + time_adjust_step * 1000;
745 * Advance the phase, once it gets to one microsecond, then
746 * advance the tick more.
748 time_phase += time_adj;
749 if (time_phase <= -FINENSEC) {
750 long ltemp = -time_phase >> (SHIFT_SCALE - 10);
751 time_phase += ltemp << (SHIFT_SCALE - 10);
754 else if (time_phase >= FINENSEC) {
755 long ltemp = time_phase >> (SHIFT_SCALE - 10);
756 time_phase -= ltemp << (SHIFT_SCALE - 10);
759 xtime.tv_nsec += delta_nsec;
760 time_interpolator_update(delta_nsec);
762 /* Changes by adjtime() do not take effect till next tick. */
763 if (time_next_adjust != 0) {
764 time_adjust = time_next_adjust;
765 time_next_adjust = 0;
770 * Using a loop looks inefficient, but "ticks" is
771 * usually just one (we shouldn't be losing ticks,
772 * we're doing this this way mainly for interrupt
773 * latency reasons, not because we think we'll
774 * have lots of lost timer ticks
776 static void update_wall_time(unsigned long ticks)
780 update_wall_time_one_tick();
783 if (xtime.tv_nsec >= 1000000000) {
784 xtime.tv_nsec -= 1000000000;
790 static inline void do_process_times(struct task_struct *p,
791 unsigned long user, unsigned long system)
795 psecs = (p->utime += user);
796 psecs += (p->stime += system);
797 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
798 /* Send SIGXCPU every second.. */
800 send_sig(SIGXCPU, p, 1);
801 /* and SIGKILL when we go over max.. */
802 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
803 send_sig(SIGKILL, p, 1);
807 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
809 unsigned long it_virt = p->it_virt_value;
814 it_virt = p->it_virt_incr;
815 send_sig(SIGVTALRM, p, 1);
817 p->it_virt_value = it_virt;
821 static inline void do_it_prof(struct task_struct *p)
823 unsigned long it_prof = p->it_prof_value;
826 if (--it_prof == 0) {
827 it_prof = p->it_prof_incr;
828 send_sig(SIGPROF, p, 1);
830 p->it_prof_value = it_prof;
834 void update_one_process(struct task_struct *p, unsigned long user,
835 unsigned long system, int cpu)
837 do_process_times(p, user, system);
843 * Called from the timer interrupt handler to charge one tick to the current
844 * process. user_tick is 1 if the tick is user time, 0 for system.
846 void update_process_times(int user_tick)
848 struct task_struct *p = current;
849 int cpu = smp_processor_id(), system = user_tick ^ 1;
851 update_one_process(p, user_tick, system, cpu);
853 scheduler_tick(user_tick, system);
857 * Nr of active tasks - counted in fixed-point numbers
859 static unsigned long count_active_tasks(void)
861 return (nr_running() + nr_uninterruptible()) * FIXED_1;
865 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
866 * imply that avenrun[] is the standard name for this kind of thing.
867 * Nothing else seems to be standardized: the fractional size etc
868 * all seem to differ on different machines.
870 * Requires xtime_lock to access.
872 unsigned long avenrun[3];
875 * calc_load - given tick count, update the avenrun load estimates.
876 * This is called while holding a write_lock on xtime_lock.
878 static inline void calc_load(unsigned long ticks)
880 unsigned long active_tasks; /* fixed-point */
881 static int count = LOAD_FREQ;
886 active_tasks = count_active_tasks();
887 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
888 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
889 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
893 /* jiffies at the most recent update of wall time */
894 unsigned long wall_jiffies = INITIAL_JIFFIES;
897 * This read-write spinlock protects us from races in SMP while
898 * playing with xtime and avenrun.
900 #ifndef ARCH_HAVE_XTIME_LOCK
901 seqlock_t xtime_lock __cacheline_aligned_in_smp = SEQLOCK_UNLOCKED;
903 EXPORT_SYMBOL(xtime_lock);
907 * This function runs timers and the timer-tq in bottom half context.
909 static void run_timer_softirq(struct softirq_action *h)
911 tvec_base_t *base = &__get_cpu_var(tvec_bases);
913 if (time_after_eq(jiffies, base->timer_jiffies))
918 * Called by the local, per-CPU timer interrupt on SMP.
920 void run_local_timers(void)
922 raise_softirq(TIMER_SOFTIRQ);
926 * Called by the timer interrupt. xtime_lock must already be taken
929 static inline void update_times(void)
933 ticks = jiffies - wall_jiffies;
935 wall_jiffies += ticks;
936 update_wall_time(ticks);
942 * The 64-bit jiffies value is not atomic - you MUST NOT read it
943 * without sampling the sequence number in xtime_lock.
944 * jiffies is defined in the linker script...
947 void do_timer(struct pt_regs *regs)
951 /* SMP process accounting uses the local APIC timer */
953 update_process_times(user_mode(regs));
958 #ifdef __ARCH_WANT_SYS_ALARM
961 * For backwards compatibility? This can be done in libc so Alpha
962 * and all newer ports shouldn't need it.
964 asmlinkage unsigned long sys_alarm(unsigned int seconds)
966 struct itimerval it_new, it_old;
967 unsigned int oldalarm;
969 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
970 it_new.it_value.tv_sec = seconds;
971 it_new.it_value.tv_usec = 0;
972 do_setitimer(ITIMER_REAL, &it_new, &it_old);
973 oldalarm = it_old.it_value.tv_sec;
974 /* ehhh.. We can't return 0 if we have an alarm pending.. */
975 /* And we'd better return too much than too little anyway */
976 if ((!oldalarm && it_old.it_value.tv_usec) || it_old.it_value.tv_usec >= 500000)
986 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
987 * should be moved into arch/i386 instead?
991 * sys_getpid - return the thread group id of the current process
993 * Note, despite the name, this returns the tgid not the pid. The tgid and
994 * the pid are identical unless CLONE_THREAD was specified on clone() in
995 * which case the tgid is the same in all threads of the same group.
997 * This is SMP safe as current->tgid does not change.
999 asmlinkage long sys_getpid(void)
1001 return vx_map_tgid(current->vx_info, current->tgid);
1005 * Accessing ->group_leader->real_parent is not SMP-safe, it could
1006 * change from under us. However, rather than getting any lock
1007 * we can use an optimistic algorithm: get the parent
1008 * pid, and go back and check that the parent is still
1009 * the same. If it has changed (which is extremely unlikely
1010 * indeed), we just try again..
1012 * NOTE! This depends on the fact that even if we _do_
1013 * get an old value of "parent", we can happily dereference
1014 * the pointer (it was and remains a dereferencable kernel pointer
1015 * no matter what): we just can't necessarily trust the result
1016 * until we know that the parent pointer is valid.
1018 * NOTE2: ->group_leader never changes from under us.
1020 asmlinkage long sys_getppid(void)
1023 struct task_struct *me = current;
1024 struct task_struct *parent;
1026 parent = me->group_leader->real_parent;
1031 struct task_struct *old = parent;
1034 * Make sure we read the pid before re-reading the
1038 parent = me->group_leader->real_parent;
1045 return vx_map_tgid(current->vx_info, pid);
1048 asmlinkage long sys_getuid(void)
1050 /* Only we change this so SMP safe */
1051 return current->uid;
1054 asmlinkage long sys_geteuid(void)
1056 /* Only we change this so SMP safe */
1057 return current->euid;
1060 asmlinkage long sys_getgid(void)
1062 /* Only we change this so SMP safe */
1063 return current->gid;
1066 asmlinkage long sys_getegid(void)
1068 /* Only we change this so SMP safe */
1069 return current->egid;
1074 static void process_timeout(unsigned long __data)
1076 wake_up_process((task_t *)__data);
1080 * schedule_timeout - sleep until timeout
1081 * @timeout: timeout value in jiffies
1083 * Make the current task sleep until @timeout jiffies have
1084 * elapsed. The routine will return immediately unless
1085 * the current task state has been set (see set_current_state()).
1087 * You can set the task state as follows -
1089 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1090 * pass before the routine returns. The routine will return 0
1092 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1093 * delivered to the current task. In this case the remaining time
1094 * in jiffies will be returned, or 0 if the timer expired in time
1096 * The current task state is guaranteed to be TASK_RUNNING when this
1099 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1100 * the CPU away without a bound on the timeout. In this case the return
1101 * value will be %MAX_SCHEDULE_TIMEOUT.
1103 * In all cases the return value is guaranteed to be non-negative.
1105 fastcall signed long __sched schedule_timeout(signed long timeout)
1107 struct timer_list timer;
1108 unsigned long expire;
1112 case MAX_SCHEDULE_TIMEOUT:
1114 * These two special cases are useful to be comfortable
1115 * in the caller. Nothing more. We could take
1116 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1117 * but I' d like to return a valid offset (>=0) to allow
1118 * the caller to do everything it want with the retval.
1124 * Another bit of PARANOID. Note that the retval will be
1125 * 0 since no piece of kernel is supposed to do a check
1126 * for a negative retval of schedule_timeout() (since it
1127 * should never happens anyway). You just have the printk()
1128 * that will tell you if something is gone wrong and where.
1132 printk(KERN_ERR "schedule_timeout: wrong timeout "
1133 "value %lx from %p\n", timeout,
1134 __builtin_return_address(0));
1135 current->state = TASK_RUNNING;
1140 expire = timeout + jiffies;
1143 timer.expires = expire;
1144 timer.data = (unsigned long) current;
1145 timer.function = process_timeout;
1149 del_singleshot_timer_sync(&timer);
1151 timeout = expire - jiffies;
1154 return timeout < 0 ? 0 : timeout;
1157 EXPORT_SYMBOL(schedule_timeout);
1159 /* Thread ID - the internal kernel "pid" */
1160 asmlinkage long sys_gettid(void)
1162 return current->pid;
1165 static long __sched nanosleep_restart(struct restart_block *restart)
1167 unsigned long expire = restart->arg0, now = jiffies;
1168 struct timespec __user *rmtp = (struct timespec __user *) restart->arg1;
1171 /* Did it expire while we handled signals? */
1172 if (!time_after(expire, now))
1175 current->state = TASK_INTERRUPTIBLE;
1176 expire = schedule_timeout(expire - now);
1181 jiffies_to_timespec(expire, &t);
1183 ret = -ERESTART_RESTARTBLOCK;
1184 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1186 /* The 'restart' block is already filled in */
1191 asmlinkage long sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1194 unsigned long expire;
1197 if (copy_from_user(&t, rqtp, sizeof(t)))
1200 if ((t.tv_nsec >= 1000000000L) || (t.tv_nsec < 0) || (t.tv_sec < 0))
1203 expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1204 current->state = TASK_INTERRUPTIBLE;
1205 expire = schedule_timeout(expire);
1209 struct restart_block *restart;
1210 jiffies_to_timespec(expire, &t);
1211 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1214 restart = ¤t_thread_info()->restart_block;
1215 restart->fn = nanosleep_restart;
1216 restart->arg0 = jiffies + expire;
1217 restart->arg1 = (unsigned long) rmtp;
1218 ret = -ERESTART_RESTARTBLOCK;
1224 * sys_sysinfo - fill in sysinfo struct
1226 asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1229 unsigned long mem_total, sav_total;
1230 unsigned int mem_unit, bitcount;
1233 memset((char *)&val, 0, sizeof(struct sysinfo));
1237 seq = read_seqbegin(&xtime_lock);
1240 * This is annoying. The below is the same thing
1241 * posix_get_clock_monotonic() does, but it wants to
1242 * take the lock which we want to cover the loads stuff
1246 do_gettimeofday((struct timeval *)&tp);
1247 tp.tv_nsec *= NSEC_PER_USEC;
1248 tp.tv_sec += wall_to_monotonic.tv_sec;
1249 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1250 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1251 tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1254 if (vx_flags(VXF_VIRT_UPTIME, 0))
1255 vx_vsi_uptime(&tp, NULL);
1256 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1258 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1259 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1260 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1262 val.procs = nr_threads;
1263 } while (read_seqretry(&xtime_lock, seq));
1265 /* if (vx_flags(VXF_VIRT_CPU, 0))
1272 * If the sum of all the available memory (i.e. ram + swap)
1273 * is less than can be stored in a 32 bit unsigned long then
1274 * we can be binary compatible with 2.2.x kernels. If not,
1275 * well, in that case 2.2.x was broken anyways...
1277 * -Erik Andersen <andersee@debian.org>
1280 mem_total = val.totalram + val.totalswap;
1281 if (mem_total < val.totalram || mem_total < val.totalswap)
1284 mem_unit = val.mem_unit;
1285 while (mem_unit > 1) {
1288 sav_total = mem_total;
1290 if (mem_total < sav_total)
1295 * If mem_total did not overflow, multiply all memory values by
1296 * val.mem_unit and set it to 1. This leaves things compatible
1297 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1302 val.totalram <<= bitcount;
1303 val.freeram <<= bitcount;
1304 val.sharedram <<= bitcount;
1305 val.bufferram <<= bitcount;
1306 val.totalswap <<= bitcount;
1307 val.freeswap <<= bitcount;
1308 val.totalhigh <<= bitcount;
1309 val.freehigh <<= bitcount;
1312 if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1318 static void __devinit init_timers_cpu(int cpu)
1323 base = &per_cpu(tvec_bases, cpu);
1324 spin_lock_init(&base->lock);
1325 for (j = 0; j < TVN_SIZE; j++) {
1326 INIT_LIST_HEAD(base->tv5.vec + j);
1327 INIT_LIST_HEAD(base->tv4.vec + j);
1328 INIT_LIST_HEAD(base->tv3.vec + j);
1329 INIT_LIST_HEAD(base->tv2.vec + j);
1331 for (j = 0; j < TVR_SIZE; j++)
1332 INIT_LIST_HEAD(base->tv1.vec + j);
1334 base->timer_jiffies = jiffies;
1337 #ifdef CONFIG_HOTPLUG_CPU
1338 static int migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
1340 struct timer_list *timer;
1342 while (!list_empty(head)) {
1343 timer = list_entry(head->next, struct timer_list, entry);
1344 /* We're locking backwards from __mod_timer order here,
1346 if (!spin_trylock(&timer->lock))
1348 list_del(&timer->entry);
1349 internal_add_timer(new_base, timer);
1350 timer->base = new_base;
1351 spin_unlock(&timer->lock);
1356 static void __devinit migrate_timers(int cpu)
1358 tvec_base_t *old_base;
1359 tvec_base_t *new_base;
1362 BUG_ON(cpu_online(cpu));
1363 old_base = &per_cpu(tvec_bases, cpu);
1364 new_base = &get_cpu_var(tvec_bases);
1366 local_irq_disable();
1368 /* Prevent deadlocks via ordering by old_base < new_base. */
1369 if (old_base < new_base) {
1370 spin_lock(&new_base->lock);
1371 spin_lock(&old_base->lock);
1373 spin_lock(&old_base->lock);
1374 spin_lock(&new_base->lock);
1377 if (old_base->running_timer)
1379 for (i = 0; i < TVR_SIZE; i++)
1380 if (!migrate_timer_list(new_base, old_base->tv1.vec + i))
1382 for (i = 0; i < TVN_SIZE; i++)
1383 if (!migrate_timer_list(new_base, old_base->tv2.vec + i)
1384 || !migrate_timer_list(new_base, old_base->tv3.vec + i)
1385 || !migrate_timer_list(new_base, old_base->tv4.vec + i)
1386 || !migrate_timer_list(new_base, old_base->tv5.vec + i))
1388 spin_unlock(&old_base->lock);
1389 spin_unlock(&new_base->lock);
1391 put_cpu_var(tvec_bases);
1395 /* Avoid deadlock with __mod_timer, by backing off. */
1396 spin_unlock(&old_base->lock);
1397 spin_unlock(&new_base->lock);
1401 #endif /* CONFIG_HOTPLUG_CPU */
1403 static int __devinit timer_cpu_notify(struct notifier_block *self,
1404 unsigned long action, void *hcpu)
1406 long cpu = (long)hcpu;
1408 case CPU_UP_PREPARE:
1409 init_timers_cpu(cpu);
1411 #ifdef CONFIG_HOTPLUG_CPU
1413 migrate_timers(cpu);
1422 static struct notifier_block __devinitdata timers_nb = {
1423 .notifier_call = timer_cpu_notify,
1427 void __init init_timers(void)
1429 timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1430 (void *)(long)smp_processor_id());
1431 register_cpu_notifier(&timers_nb);
1432 open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1435 #ifdef CONFIG_TIME_INTERPOLATION
1436 volatile unsigned long last_nsec_offset;
1437 #ifndef __HAVE_ARCH_CMPXCHG
1438 spinlock_t last_nsec_offset_lock = SPIN_LOCK_UNLOCKED;
1441 struct time_interpolator *time_interpolator;
1442 static struct time_interpolator *time_interpolator_list;
1443 static spinlock_t time_interpolator_lock = SPIN_LOCK_UNLOCKED;
1446 is_better_time_interpolator(struct time_interpolator *new)
1448 if (!time_interpolator)
1450 return new->frequency > 2*time_interpolator->frequency ||
1451 (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1455 register_time_interpolator(struct time_interpolator *ti)
1457 spin_lock(&time_interpolator_lock);
1458 write_seqlock_irq(&xtime_lock);
1459 if (is_better_time_interpolator(ti))
1460 time_interpolator = ti;
1461 write_sequnlock_irq(&xtime_lock);
1463 ti->next = time_interpolator_list;
1464 time_interpolator_list = ti;
1465 spin_unlock(&time_interpolator_lock);
1469 unregister_time_interpolator(struct time_interpolator *ti)
1471 struct time_interpolator *curr, **prev;
1473 spin_lock(&time_interpolator_lock);
1474 prev = &time_interpolator_list;
1475 for (curr = *prev; curr; curr = curr->next) {
1483 write_seqlock_irq(&xtime_lock);
1484 if (ti == time_interpolator) {
1485 /* we lost the best time-interpolator: */
1486 time_interpolator = NULL;
1487 /* find the next-best interpolator */
1488 for (curr = time_interpolator_list; curr; curr = curr->next)
1489 if (is_better_time_interpolator(curr))
1490 time_interpolator = curr;
1492 write_sequnlock_irq(&xtime_lock);
1493 spin_unlock(&time_interpolator_lock);
1495 #endif /* CONFIG_TIME_INTERPOLATION */
1498 * msleep - sleep safely even with waitqueue interruptions
1499 * @msecs: Time in milliseconds to sleep for
1501 void msleep(unsigned int msecs)
1503 unsigned long timeout = msecs_to_jiffies(msecs);
1506 set_current_state(TASK_UNINTERRUPTIBLE);
1507 timeout = schedule_timeout(timeout);
1511 EXPORT_SYMBOL(msleep);