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/vs_base.h>
35 #include <linux/vs_cvirt.h>
36 #include <linux/vserver/sched.h>
38 #include <asm/uaccess.h>
39 #include <asm/unistd.h>
40 #include <asm/div64.h>
41 #include <asm/timex.h>
44 * per-CPU timer vector definitions:
48 #define TVN_SIZE (1 << TVN_BITS)
49 #define TVR_SIZE (1 << TVR_BITS)
50 #define TVN_MASK (TVN_SIZE - 1)
51 #define TVR_MASK (TVR_SIZE - 1)
53 typedef struct tvec_s {
54 struct list_head vec[TVN_SIZE];
57 typedef struct tvec_root_s {
58 struct list_head vec[TVR_SIZE];
61 struct tvec_t_base_s {
63 unsigned long timer_jiffies;
64 struct timer_list *running_timer;
70 } ____cacheline_aligned_in_smp;
72 typedef struct tvec_t_base_s tvec_base_t;
74 static inline void set_running_timer(tvec_base_t *base,
75 struct timer_list *timer)
78 base->running_timer = timer;
82 /* Fake initialization */
83 static DEFINE_PER_CPU(tvec_base_t, tvec_bases) = { SPIN_LOCK_UNLOCKED };
85 static void check_timer_failed(struct timer_list *timer)
87 static int whine_count;
88 if (whine_count < 16) {
90 printk("Uninitialised timer!\n");
91 printk("This is just a warning. Your computer is OK\n");
92 printk("function=0x%p, data=0x%lx\n",
93 timer->function, timer->data);
99 spin_lock_init(&timer->lock);
100 timer->magic = TIMER_MAGIC;
103 static inline void check_timer(struct timer_list *timer)
105 if (timer->magic != TIMER_MAGIC)
106 check_timer_failed(timer);
110 static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
112 unsigned long expires = timer->expires;
113 unsigned long idx = expires - base->timer_jiffies;
114 struct list_head *vec;
116 if (idx < TVR_SIZE) {
117 int i = expires & TVR_MASK;
118 vec = base->tv1.vec + i;
119 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
120 int i = (expires >> TVR_BITS) & TVN_MASK;
121 vec = base->tv2.vec + i;
122 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
123 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
124 vec = base->tv3.vec + i;
125 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
126 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
127 vec = base->tv4.vec + i;
128 } else if ((signed long) idx < 0) {
130 * Can happen if you add a timer with expires == jiffies,
131 * or you set a timer to go off in the past
133 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
136 /* If the timeout is larger than 0xffffffff on 64-bit
137 * architectures then we use the maximum timeout:
139 if (idx > 0xffffffffUL) {
141 expires = idx + base->timer_jiffies;
143 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
144 vec = base->tv5.vec + i;
149 list_add_tail(&timer->entry, vec);
152 int __mod_timer(struct timer_list *timer, unsigned long expires)
154 tvec_base_t *old_base, *new_base;
158 BUG_ON(!timer->function);
162 spin_lock_irqsave(&timer->lock, flags);
163 new_base = &__get_cpu_var(tvec_bases);
165 old_base = timer->base;
168 * Prevent deadlocks via ordering by old_base < new_base.
170 if (old_base && (new_base != old_base)) {
171 if (old_base < new_base) {
172 spin_lock(&new_base->lock);
173 spin_lock(&old_base->lock);
175 spin_lock(&old_base->lock);
176 spin_lock(&new_base->lock);
179 * The timer base might have been cancelled while we were
180 * trying to take the lock(s):
182 if (timer->base != old_base) {
183 spin_unlock(&new_base->lock);
184 spin_unlock(&old_base->lock);
188 spin_lock(&new_base->lock);
189 if (timer->base != old_base) {
190 spin_unlock(&new_base->lock);
196 * Delete the previous timeout (if there was any), and install
200 list_del(&timer->entry);
203 timer->expires = expires;
204 internal_add_timer(new_base, timer);
205 timer->base = new_base;
207 if (old_base && (new_base != old_base))
208 spin_unlock(&old_base->lock);
209 spin_unlock(&new_base->lock);
210 spin_unlock_irqrestore(&timer->lock, flags);
215 EXPORT_SYMBOL(__mod_timer);
218 * add_timer_on - start a timer on a particular CPU
219 * @timer: the timer to be added
220 * @cpu: the CPU to start it on
222 * This is not very scalable on SMP. Double adds are not possible.
224 void add_timer_on(struct timer_list *timer, int cpu)
226 tvec_base_t *base = &per_cpu(tvec_bases, cpu);
229 BUG_ON(timer_pending(timer) || !timer->function);
233 spin_lock_irqsave(&base->lock, flags);
234 internal_add_timer(base, timer);
236 spin_unlock_irqrestore(&base->lock, flags);
240 * mod_timer - modify a timer's timeout
241 * @timer: the timer to be modified
243 * mod_timer is a more efficient way to update the expire field of an
244 * active timer (if the timer is inactive it will be activated)
246 * mod_timer(timer, expires) is equivalent to:
248 * del_timer(timer); timer->expires = expires; add_timer(timer);
250 * Note that if there are multiple unserialized concurrent users of the
251 * same timer, then mod_timer() is the only safe way to modify the timeout,
252 * since add_timer() cannot modify an already running timer.
254 * The function returns whether it has modified a pending timer or not.
255 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
256 * active timer returns 1.)
258 int mod_timer(struct timer_list *timer, unsigned long expires)
260 BUG_ON(!timer->function);
265 * This is a common optimization triggered by the
266 * networking code - if the timer is re-modified
267 * to be the same thing then just return:
269 if (timer->expires == expires && timer_pending(timer))
272 return __mod_timer(timer, expires);
275 EXPORT_SYMBOL(mod_timer);
278 * del_timer - deactive a timer.
279 * @timer: the timer to be deactivated
281 * del_timer() deactivates a timer - this works on both active and inactive
284 * The function returns whether it has deactivated a pending timer or not.
285 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
286 * active timer returns 1.)
288 int del_timer(struct timer_list *timer)
299 spin_lock_irqsave(&base->lock, flags);
300 if (base != timer->base) {
301 spin_unlock_irqrestore(&base->lock, flags);
304 list_del(&timer->entry);
306 spin_unlock_irqrestore(&base->lock, flags);
311 EXPORT_SYMBOL(del_timer);
315 * del_timer_sync - deactivate a timer and wait for the handler to finish.
316 * @timer: the timer to be deactivated
318 * This function only differs from del_timer() on SMP: besides deactivating
319 * the timer it also makes sure the handler has finished executing on other
322 * Synchronization rules: callers must prevent restarting of the timer,
323 * otherwise this function is meaningless. It must not be called from
324 * interrupt contexts. The caller must not hold locks which would prevent
325 * completion of the timer's handler. Upon exit the timer is not queued and
326 * the handler is not running on any CPU.
328 * The function returns whether it has deactivated a pending timer or not.
330 * del_timer_sync() is slow and complicated because it copes with timer
331 * handlers which re-arm the timer (periodic timers). If the timer handler
332 * is known to not do this (a single shot timer) then use
333 * del_singleshot_timer_sync() instead.
335 int del_timer_sync(struct timer_list *timer)
343 ret += del_timer(timer);
345 for_each_online_cpu(i) {
346 base = &per_cpu(tvec_bases, i);
347 if (base->running_timer == timer) {
348 while (base->running_timer == timer) {
350 preempt_check_resched();
356 if (timer_pending(timer))
361 EXPORT_SYMBOL(del_timer_sync);
364 * del_singleshot_timer_sync - deactivate a non-recursive timer
365 * @timer: the timer to be deactivated
367 * This function is an optimization of del_timer_sync for the case where the
368 * caller can guarantee the timer does not reschedule itself in its timer
371 * Synchronization rules: callers must prevent restarting of the timer,
372 * otherwise this function is meaningless. It must not be called from
373 * interrupt contexts. The caller must not hold locks which wold prevent
374 * completion of the timer's handler. Upon exit the timer is not queued and
375 * the handler is not running on any CPU.
377 * The function returns whether it has deactivated a pending timer or not.
379 int del_singleshot_timer_sync(struct timer_list *timer)
381 int ret = del_timer(timer);
384 ret = del_timer_sync(timer);
390 EXPORT_SYMBOL(del_singleshot_timer_sync);
393 static int cascade(tvec_base_t *base, tvec_t *tv, int index)
395 /* cascade all the timers from tv up one level */
396 struct list_head *head, *curr;
398 head = tv->vec + index;
401 * We are removing _all_ timers from the list, so we don't have to
402 * detach them individually, just clear the list afterwards.
404 while (curr != head) {
405 struct timer_list *tmp;
407 tmp = list_entry(curr, struct timer_list, entry);
408 BUG_ON(tmp->base != base);
410 internal_add_timer(base, tmp);
412 INIT_LIST_HEAD(head);
418 * __run_timers - run all expired timers (if any) on this CPU.
419 * @base: the timer vector to be processed.
421 * This function cascades all vectors and executes all expired timer
424 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
426 static inline void __run_timers(tvec_base_t *base)
428 struct timer_list *timer;
430 spin_lock_irq(&base->lock);
431 while (time_after_eq(jiffies, base->timer_jiffies)) {
432 struct list_head work_list = LIST_HEAD_INIT(work_list);
433 struct list_head *head = &work_list;
434 int index = base->timer_jiffies & TVR_MASK;
440 (!cascade(base, &base->tv2, INDEX(0))) &&
441 (!cascade(base, &base->tv3, INDEX(1))) &&
442 !cascade(base, &base->tv4, INDEX(2)))
443 cascade(base, &base->tv5, INDEX(3));
444 ++base->timer_jiffies;
445 list_splice_init(base->tv1.vec + index, &work_list);
447 if (!list_empty(head)) {
448 void (*fn)(unsigned long);
451 timer = list_entry(head->next,struct timer_list,entry);
452 fn = timer->function;
455 list_del(&timer->entry);
456 set_running_timer(base, timer);
459 spin_unlock_irq(&base->lock);
461 spin_lock_irq(&base->lock);
465 set_running_timer(base, NULL);
466 spin_unlock_irq(&base->lock);
469 #ifdef CONFIG_NO_IDLE_HZ
471 * Find out when the next timer event is due to happen. This
472 * is used on S/390 to stop all activity when a cpus is idle.
473 * This functions needs to be called disabled.
475 unsigned long next_timer_interrupt(void)
478 struct list_head *list;
479 struct timer_list *nte;
480 unsigned long expires;
484 base = &__get_cpu_var(tvec_bases);
485 spin_lock(&base->lock);
486 expires = base->timer_jiffies + (LONG_MAX >> 1);
489 /* Look for timer events in tv1. */
490 j = base->timer_jiffies & TVR_MASK;
492 list_for_each_entry(nte, base->tv1.vec + j, entry) {
493 expires = nte->expires;
494 if (j < (base->timer_jiffies & TVR_MASK))
495 list = base->tv2.vec + (INDEX(0));
498 j = (j + 1) & TVR_MASK;
499 } while (j != (base->timer_jiffies & TVR_MASK));
502 varray[0] = &base->tv2;
503 varray[1] = &base->tv3;
504 varray[2] = &base->tv4;
505 varray[3] = &base->tv5;
506 for (i = 0; i < 4; i++) {
509 if (list_empty(varray[i]->vec + j)) {
510 j = (j + 1) & TVN_MASK;
513 list_for_each_entry(nte, varray[i]->vec + j, entry)
514 if (time_before(nte->expires, expires))
515 expires = nte->expires;
516 if (j < (INDEX(i)) && i < 3)
517 list = varray[i + 1]->vec + (INDEX(i + 1));
519 } while (j != (INDEX(i)));
524 * The search wrapped. We need to look at the next list
525 * from next tv element that would cascade into tv element
526 * where we found the timer element.
528 list_for_each_entry(nte, list, entry) {
529 if (time_before(nte->expires, expires))
530 expires = nte->expires;
533 spin_unlock(&base->lock);
538 /******************************************************************/
541 * Timekeeping variables
543 unsigned long tick_usec = TICK_USEC; /* USER_HZ period (usec) */
544 unsigned long tick_nsec = TICK_NSEC; /* ACTHZ period (nsec) */
548 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
549 * for sub jiffie times) to get to monotonic time. Monotonic is pegged at zero
550 * at zero at system boot time, so wall_to_monotonic will be negative,
551 * however, we will ALWAYS keep the tv_nsec part positive so we can use
552 * the usual normalization.
554 struct timespec xtime __attribute__ ((aligned (16)));
555 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
557 EXPORT_SYMBOL(xtime);
559 /* Don't completely fail for HZ > 500. */
560 int tickadj = 500/HZ ? : 1; /* microsecs */
564 * phase-lock loop variables
566 /* TIME_ERROR prevents overwriting the CMOS clock */
567 int time_state = TIME_OK; /* clock synchronization status */
568 int time_status = STA_UNSYNC; /* clock status bits */
569 long time_offset; /* time adjustment (us) */
570 long time_constant = 2; /* pll time constant */
571 long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
572 long time_precision = 1; /* clock precision (us) */
573 long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
574 long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
575 long time_phase; /* phase offset (scaled us) */
576 long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
577 /* frequency offset (scaled ppm)*/
578 long time_adj; /* tick adjust (scaled 1 / HZ) */
579 long time_reftime; /* time at last adjustment (s) */
581 long time_next_adjust;
584 * this routine handles the overflow of the microsecond field
586 * The tricky bits of code to handle the accurate clock support
587 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
588 * They were originally developed for SUN and DEC kernels.
589 * All the kudos should go to Dave for this stuff.
592 static void second_overflow(void)
596 /* Bump the maxerror field */
597 time_maxerror += time_tolerance >> SHIFT_USEC;
598 if ( time_maxerror > NTP_PHASE_LIMIT ) {
599 time_maxerror = NTP_PHASE_LIMIT;
600 time_status |= STA_UNSYNC;
604 * Leap second processing. If in leap-insert state at
605 * the end of the day, the system clock is set back one
606 * second; if in leap-delete state, the system clock is
607 * set ahead one second. The microtime() routine or
608 * external clock driver will insure that reported time
609 * is always monotonic. The ugly divides should be
612 switch (time_state) {
615 if (time_status & STA_INS)
616 time_state = TIME_INS;
617 else if (time_status & STA_DEL)
618 time_state = TIME_DEL;
622 if (xtime.tv_sec % 86400 == 0) {
624 wall_to_monotonic.tv_sec++;
625 time_interpolator_update(-NSEC_PER_SEC);
626 time_state = TIME_OOP;
628 printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
633 if ((xtime.tv_sec + 1) % 86400 == 0) {
635 wall_to_monotonic.tv_sec--;
636 time_interpolator_update(NSEC_PER_SEC);
637 time_state = TIME_WAIT;
639 printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
644 time_state = TIME_WAIT;
648 if (!(time_status & (STA_INS | STA_DEL)))
649 time_state = TIME_OK;
653 * Compute the phase adjustment for the next second. In
654 * PLL mode, the offset is reduced by a fixed factor
655 * times the time constant. In FLL mode the offset is
656 * used directly. In either mode, the maximum phase
657 * adjustment for each second is clamped so as to spread
658 * the adjustment over not more than the number of
659 * seconds between updates.
661 if (time_offset < 0) {
662 ltemp = -time_offset;
663 if (!(time_status & STA_FLL))
664 ltemp >>= SHIFT_KG + time_constant;
665 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
666 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
667 time_offset += ltemp;
668 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
671 if (!(time_status & STA_FLL))
672 ltemp >>= SHIFT_KG + time_constant;
673 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
674 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
675 time_offset -= ltemp;
676 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
680 * Compute the frequency estimate and additional phase
681 * adjustment due to frequency error for the next
682 * second. When the PPS signal is engaged, gnaw on the
683 * watchdog counter and update the frequency computed by
684 * the pll and the PPS signal.
687 if (pps_valid == PPS_VALID) { /* PPS signal lost */
688 pps_jitter = MAXTIME;
689 pps_stabil = MAXFREQ;
690 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
691 STA_PPSWANDER | STA_PPSERROR);
693 ltemp = time_freq + pps_freq;
695 time_adj -= -ltemp >>
696 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
699 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
702 /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
703 * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
706 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
708 time_adj += (time_adj >> 2) + (time_adj >> 5);
711 /* Compensate for (HZ==1000) != (1 << SHIFT_HZ).
712 * Add 1.5625% and 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
715 time_adj -= (-time_adj >> 6) + (-time_adj >> 7);
717 time_adj += (time_adj >> 6) + (time_adj >> 7);
721 /* in the NTP reference this is called "hardclock()" */
722 static void update_wall_time_one_tick(void)
724 long time_adjust_step, delta_nsec;
726 if ( (time_adjust_step = time_adjust) != 0 ) {
727 /* We are doing an adjtime thing.
729 * Prepare time_adjust_step to be within bounds.
730 * Note that a positive time_adjust means we want the clock
733 * Limit the amount of the step to be in the range
734 * -tickadj .. +tickadj
736 if (time_adjust > tickadj)
737 time_adjust_step = tickadj;
738 else if (time_adjust < -tickadj)
739 time_adjust_step = -tickadj;
741 /* Reduce by this step the amount of time left */
742 time_adjust -= time_adjust_step;
744 delta_nsec = tick_nsec + time_adjust_step * 1000;
746 * Advance the phase, once it gets to one microsecond, then
747 * advance the tick more.
749 time_phase += time_adj;
750 if (time_phase <= -FINENSEC) {
751 long ltemp = -time_phase >> (SHIFT_SCALE - 10);
752 time_phase += ltemp << (SHIFT_SCALE - 10);
755 else if (time_phase >= FINENSEC) {
756 long ltemp = time_phase >> (SHIFT_SCALE - 10);
757 time_phase -= ltemp << (SHIFT_SCALE - 10);
760 xtime.tv_nsec += delta_nsec;
761 time_interpolator_update(delta_nsec);
763 /* Changes by adjtime() do not take effect till next tick. */
764 if (time_next_adjust != 0) {
765 time_adjust = time_next_adjust;
766 time_next_adjust = 0;
771 * Using a loop looks inefficient, but "ticks" is
772 * usually just one (we shouldn't be losing ticks,
773 * we're doing this this way mainly for interrupt
774 * latency reasons, not because we think we'll
775 * have lots of lost timer ticks
777 static void update_wall_time(unsigned long ticks)
781 update_wall_time_one_tick();
784 if (xtime.tv_nsec >= 1000000000) {
785 xtime.tv_nsec -= 1000000000;
791 static inline void do_process_times(struct task_struct *p,
792 unsigned long user, unsigned long system)
796 psecs = (p->utime += user);
797 psecs += (p->stime += system);
798 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
799 /* Send SIGXCPU every second.. */
801 send_sig(SIGXCPU, p, 1);
802 /* and SIGKILL when we go over max.. */
803 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
804 send_sig(SIGKILL, p, 1);
808 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
810 unsigned long it_virt = p->it_virt_value;
815 it_virt = p->it_virt_incr;
816 send_sig(SIGVTALRM, p, 1);
818 p->it_virt_value = it_virt;
822 static inline void do_it_prof(struct task_struct *p)
824 unsigned long it_prof = p->it_prof_value;
827 if (--it_prof == 0) {
828 it_prof = p->it_prof_incr;
829 send_sig(SIGPROF, p, 1);
831 p->it_prof_value = it_prof;
835 static void update_one_process(struct task_struct *p, unsigned long user,
836 unsigned long system, int cpu)
838 do_process_times(p, user, system);
844 * Called from the timer interrupt handler to charge one tick to the current
845 * process. user_tick is 1 if the tick is user time, 0 for system.
847 void update_process_times(int user_tick)
849 struct task_struct *p = current;
850 int cpu = smp_processor_id(), system = user_tick ^ 1;
852 update_one_process(p, user_tick, system, cpu);
854 scheduler_tick(user_tick, system);
858 * Nr of active tasks - counted in fixed-point numbers
860 static unsigned long count_active_tasks(void)
862 return (nr_running() + nr_uninterruptible()) * FIXED_1;
866 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
867 * imply that avenrun[] is the standard name for this kind of thing.
868 * Nothing else seems to be standardized: the fractional size etc
869 * all seem to differ on different machines.
871 * Requires xtime_lock to access.
873 unsigned long avenrun[3];
876 * calc_load - given tick count, update the avenrun load estimates.
877 * This is called while holding a write_lock on xtime_lock.
879 static inline void calc_load(unsigned long ticks)
881 unsigned long active_tasks; /* fixed-point */
882 static int count = LOAD_FREQ;
887 active_tasks = count_active_tasks();
888 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
889 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
890 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
894 /* jiffies at the most recent update of wall time */
895 unsigned long wall_jiffies = INITIAL_JIFFIES;
898 * This read-write spinlock protects us from races in SMP while
899 * playing with xtime and avenrun.
901 #ifndef ARCH_HAVE_XTIME_LOCK
902 seqlock_t xtime_lock __cacheline_aligned_in_smp = SEQLOCK_UNLOCKED;
904 EXPORT_SYMBOL(xtime_lock);
908 * This function runs timers and the timer-tq in bottom half context.
910 static void run_timer_softirq(struct softirq_action *h)
912 tvec_base_t *base = &__get_cpu_var(tvec_bases);
914 if (time_after_eq(jiffies, base->timer_jiffies))
919 * Called by the local, per-CPU timer interrupt on SMP.
921 void run_local_timers(void)
923 raise_softirq(TIMER_SOFTIRQ);
927 * Called by the timer interrupt. xtime_lock must already be taken
930 static inline void update_times(void)
934 ticks = jiffies - wall_jiffies;
936 wall_jiffies += ticks;
937 update_wall_time(ticks);
943 * The 64-bit jiffies value is not atomic - you MUST NOT read it
944 * without sampling the sequence number in xtime_lock.
945 * jiffies is defined in the linker script...
948 void do_timer(struct pt_regs *regs)
952 /* SMP process accounting uses the local APIC timer */
954 update_process_times(user_mode(regs));
959 #ifdef __ARCH_WANT_SYS_ALARM
962 * For backwards compatibility? This can be done in libc so Alpha
963 * and all newer ports shouldn't need it.
965 asmlinkage unsigned long sys_alarm(unsigned int seconds)
967 struct itimerval it_new, it_old;
968 unsigned int oldalarm;
970 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
971 it_new.it_value.tv_sec = seconds;
972 it_new.it_value.tv_usec = 0;
973 do_setitimer(ITIMER_REAL, &it_new, &it_old);
974 oldalarm = it_old.it_value.tv_sec;
975 /* ehhh.. We can't return 0 if we have an alarm pending.. */
976 /* And we'd better return too much than too little anyway */
977 if ((!oldalarm && it_old.it_value.tv_usec) || it_old.it_value.tv_usec >= 500000)
987 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
988 * should be moved into arch/i386 instead?
992 * sys_getpid - return the thread group id of the current process
994 * Note, despite the name, this returns the tgid not the pid. The tgid and
995 * the pid are identical unless CLONE_THREAD was specified on clone() in
996 * which case the tgid is the same in all threads of the same group.
998 * This is SMP safe as current->tgid does not change.
1000 asmlinkage long sys_getpid(void)
1002 return vx_map_tgid(current->vx_info, current->tgid);
1006 * Accessing ->group_leader->real_parent is not SMP-safe, it could
1007 * change from under us. However, rather than getting any lock
1008 * we can use an optimistic algorithm: get the parent
1009 * pid, and go back and check that the parent is still
1010 * the same. If it has changed (which is extremely unlikely
1011 * indeed), we just try again..
1013 * NOTE! This depends on the fact that even if we _do_
1014 * get an old value of "parent", we can happily dereference
1015 * the pointer (it was and remains a dereferencable kernel pointer
1016 * no matter what): we just can't necessarily trust the result
1017 * until we know that the parent pointer is valid.
1019 * NOTE2: ->group_leader never changes from under us.
1021 asmlinkage long sys_getppid(void)
1024 struct task_struct *me = current;
1025 struct task_struct *parent;
1027 parent = me->group_leader->real_parent;
1032 struct task_struct *old = parent;
1035 * Make sure we read the pid before re-reading the
1039 parent = me->group_leader->real_parent;
1046 return vx_map_tgid(current->vx_info, pid);
1049 asmlinkage long sys_getuid(void)
1051 /* Only we change this so SMP safe */
1052 return current->uid;
1055 asmlinkage long sys_geteuid(void)
1057 /* Only we change this so SMP safe */
1058 return current->euid;
1061 asmlinkage long sys_getgid(void)
1063 /* Only we change this so SMP safe */
1064 return current->gid;
1067 asmlinkage long sys_getegid(void)
1069 /* Only we change this so SMP safe */
1070 return current->egid;
1075 static void process_timeout(unsigned long __data)
1077 wake_up_process((task_t *)__data);
1081 * schedule_timeout - sleep until timeout
1082 * @timeout: timeout value in jiffies
1084 * Make the current task sleep until @timeout jiffies have
1085 * elapsed. The routine will return immediately unless
1086 * the current task state has been set (see set_current_state()).
1088 * You can set the task state as follows -
1090 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1091 * pass before the routine returns. The routine will return 0
1093 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1094 * delivered to the current task. In this case the remaining time
1095 * in jiffies will be returned, or 0 if the timer expired in time
1097 * The current task state is guaranteed to be TASK_RUNNING when this
1100 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1101 * the CPU away without a bound on the timeout. In this case the return
1102 * value will be %MAX_SCHEDULE_TIMEOUT.
1104 * In all cases the return value is guaranteed to be non-negative.
1106 fastcall signed long __sched schedule_timeout(signed long timeout)
1108 struct timer_list timer;
1109 unsigned long expire;
1113 case MAX_SCHEDULE_TIMEOUT:
1115 * These two special cases are useful to be comfortable
1116 * in the caller. Nothing more. We could take
1117 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1118 * but I' d like to return a valid offset (>=0) to allow
1119 * the caller to do everything it want with the retval.
1125 * Another bit of PARANOID. Note that the retval will be
1126 * 0 since no piece of kernel is supposed to do a check
1127 * for a negative retval of schedule_timeout() (since it
1128 * should never happens anyway). You just have the printk()
1129 * that will tell you if something is gone wrong and where.
1133 printk(KERN_ERR "schedule_timeout: wrong timeout "
1134 "value %lx from %p\n", timeout,
1135 __builtin_return_address(0));
1136 current->state = TASK_RUNNING;
1141 expire = timeout + jiffies;
1144 timer.expires = expire;
1145 timer.data = (unsigned long) current;
1146 timer.function = process_timeout;
1150 del_singleshot_timer_sync(&timer);
1152 timeout = expire - jiffies;
1155 return timeout < 0 ? 0 : timeout;
1158 EXPORT_SYMBOL(schedule_timeout);
1160 /* Thread ID - the internal kernel "pid" */
1161 asmlinkage long sys_gettid(void)
1163 return current->pid;
1166 static long __sched nanosleep_restart(struct restart_block *restart)
1168 unsigned long expire = restart->arg0, now = jiffies;
1169 struct timespec __user *rmtp = (struct timespec __user *) restart->arg1;
1172 /* Did it expire while we handled signals? */
1173 if (!time_after(expire, now))
1176 current->state = TASK_INTERRUPTIBLE;
1177 expire = schedule_timeout(expire - now);
1182 jiffies_to_timespec(expire, &t);
1184 ret = -ERESTART_RESTARTBLOCK;
1185 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1187 /* The 'restart' block is already filled in */
1192 asmlinkage long sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1195 unsigned long expire;
1198 if (copy_from_user(&t, rqtp, sizeof(t)))
1201 if ((t.tv_nsec >= 1000000000L) || (t.tv_nsec < 0) || (t.tv_sec < 0))
1204 expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1205 current->state = TASK_INTERRUPTIBLE;
1206 expire = schedule_timeout(expire);
1210 struct restart_block *restart;
1211 jiffies_to_timespec(expire, &t);
1212 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1215 restart = ¤t_thread_info()->restart_block;
1216 restart->fn = nanosleep_restart;
1217 restart->arg0 = jiffies + expire;
1218 restart->arg1 = (unsigned long) rmtp;
1219 ret = -ERESTART_RESTARTBLOCK;
1225 * sys_sysinfo - fill in sysinfo struct
1227 asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1230 unsigned long mem_total, sav_total;
1231 unsigned int mem_unit, bitcount;
1234 memset((char *)&val, 0, sizeof(struct sysinfo));
1238 seq = read_seqbegin(&xtime_lock);
1241 * This is annoying. The below is the same thing
1242 * posix_get_clock_monotonic() does, but it wants to
1243 * take the lock which we want to cover the loads stuff
1247 do_gettimeofday((struct timeval *)&tp);
1248 tp.tv_nsec *= NSEC_PER_USEC;
1249 tp.tv_sec += wall_to_monotonic.tv_sec;
1250 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1251 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1252 tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1255 if (vx_flags(VXF_VIRT_UPTIME, 0))
1256 vx_vsi_uptime(&tp, NULL);
1257 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1259 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1260 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1261 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1263 val.procs = nr_threads;
1264 } while (read_seqretry(&xtime_lock, seq));
1266 /* if (vx_flags(VXF_VIRT_CPU, 0))
1273 * If the sum of all the available memory (i.e. ram + swap)
1274 * is less than can be stored in a 32 bit unsigned long then
1275 * we can be binary compatible with 2.2.x kernels. If not,
1276 * well, in that case 2.2.x was broken anyways...
1278 * -Erik Andersen <andersee@debian.org>
1281 mem_total = val.totalram + val.totalswap;
1282 if (mem_total < val.totalram || mem_total < val.totalswap)
1285 mem_unit = val.mem_unit;
1286 while (mem_unit > 1) {
1289 sav_total = mem_total;
1291 if (mem_total < sav_total)
1296 * If mem_total did not overflow, multiply all memory values by
1297 * val.mem_unit and set it to 1. This leaves things compatible
1298 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1303 val.totalram <<= bitcount;
1304 val.freeram <<= bitcount;
1305 val.sharedram <<= bitcount;
1306 val.bufferram <<= bitcount;
1307 val.totalswap <<= bitcount;
1308 val.freeswap <<= bitcount;
1309 val.totalhigh <<= bitcount;
1310 val.freehigh <<= bitcount;
1313 if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1319 static void __devinit init_timers_cpu(int cpu)
1324 base = &per_cpu(tvec_bases, cpu);
1325 spin_lock_init(&base->lock);
1326 for (j = 0; j < TVN_SIZE; j++) {
1327 INIT_LIST_HEAD(base->tv5.vec + j);
1328 INIT_LIST_HEAD(base->tv4.vec + j);
1329 INIT_LIST_HEAD(base->tv3.vec + j);
1330 INIT_LIST_HEAD(base->tv2.vec + j);
1332 for (j = 0; j < TVR_SIZE; j++)
1333 INIT_LIST_HEAD(base->tv1.vec + j);
1335 base->timer_jiffies = jiffies;
1338 #ifdef CONFIG_HOTPLUG_CPU
1339 static int migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
1341 struct timer_list *timer;
1343 while (!list_empty(head)) {
1344 timer = list_entry(head->next, struct timer_list, entry);
1345 /* We're locking backwards from __mod_timer order here,
1347 if (!spin_trylock(&timer->lock))
1349 list_del(&timer->entry);
1350 internal_add_timer(new_base, timer);
1351 timer->base = new_base;
1352 spin_unlock(&timer->lock);
1357 static void __devinit migrate_timers(int cpu)
1359 tvec_base_t *old_base;
1360 tvec_base_t *new_base;
1363 BUG_ON(cpu_online(cpu));
1364 old_base = &per_cpu(tvec_bases, cpu);
1365 new_base = &get_cpu_var(tvec_bases);
1367 local_irq_disable();
1369 /* Prevent deadlocks via ordering by old_base < new_base. */
1370 if (old_base < new_base) {
1371 spin_lock(&new_base->lock);
1372 spin_lock(&old_base->lock);
1374 spin_lock(&old_base->lock);
1375 spin_lock(&new_base->lock);
1378 if (old_base->running_timer)
1380 for (i = 0; i < TVR_SIZE; i++)
1381 if (!migrate_timer_list(new_base, old_base->tv1.vec + i))
1383 for (i = 0; i < TVN_SIZE; i++)
1384 if (!migrate_timer_list(new_base, old_base->tv2.vec + i)
1385 || !migrate_timer_list(new_base, old_base->tv3.vec + i)
1386 || !migrate_timer_list(new_base, old_base->tv4.vec + i)
1387 || !migrate_timer_list(new_base, old_base->tv5.vec + i))
1389 spin_unlock(&old_base->lock);
1390 spin_unlock(&new_base->lock);
1392 put_cpu_var(tvec_bases);
1396 /* Avoid deadlock with __mod_timer, by backing off. */
1397 spin_unlock(&old_base->lock);
1398 spin_unlock(&new_base->lock);
1402 #endif /* CONFIG_HOTPLUG_CPU */
1404 static int __devinit timer_cpu_notify(struct notifier_block *self,
1405 unsigned long action, void *hcpu)
1407 long cpu = (long)hcpu;
1409 case CPU_UP_PREPARE:
1410 init_timers_cpu(cpu);
1412 #ifdef CONFIG_HOTPLUG_CPU
1414 migrate_timers(cpu);
1423 static struct notifier_block __devinitdata timers_nb = {
1424 .notifier_call = timer_cpu_notify,
1428 void __init init_timers(void)
1430 timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1431 (void *)(long)smp_processor_id());
1432 register_cpu_notifier(&timers_nb);
1433 open_softirq(TIMER_SOFTIRQ, run_timer_softirq, NULL);
1436 #ifdef CONFIG_TIME_INTERPOLATION
1437 volatile unsigned long last_nsec_offset;
1438 #ifndef __HAVE_ARCH_CMPXCHG
1439 spinlock_t last_nsec_offset_lock = SPIN_LOCK_UNLOCKED;
1442 struct time_interpolator *time_interpolator;
1443 static struct time_interpolator *time_interpolator_list;
1444 static spinlock_t time_interpolator_lock = SPIN_LOCK_UNLOCKED;
1447 is_better_time_interpolator(struct time_interpolator *new)
1449 if (!time_interpolator)
1451 return new->frequency > 2*time_interpolator->frequency ||
1452 (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1456 register_time_interpolator(struct time_interpolator *ti)
1458 spin_lock(&time_interpolator_lock);
1459 write_seqlock_irq(&xtime_lock);
1460 if (is_better_time_interpolator(ti))
1461 time_interpolator = ti;
1462 write_sequnlock_irq(&xtime_lock);
1464 ti->next = time_interpolator_list;
1465 time_interpolator_list = ti;
1466 spin_unlock(&time_interpolator_lock);
1470 unregister_time_interpolator(struct time_interpolator *ti)
1472 struct time_interpolator *curr, **prev;
1474 spin_lock(&time_interpolator_lock);
1475 prev = &time_interpolator_list;
1476 for (curr = *prev; curr; curr = curr->next) {
1484 write_seqlock_irq(&xtime_lock);
1485 if (ti == time_interpolator) {
1486 /* we lost the best time-interpolator: */
1487 time_interpolator = NULL;
1488 /* find the next-best interpolator */
1489 for (curr = time_interpolator_list; curr; curr = curr->next)
1490 if (is_better_time_interpolator(curr))
1491 time_interpolator = curr;
1493 write_sequnlock_irq(&xtime_lock);
1494 spin_unlock(&time_interpolator_lock);
1496 #endif /* CONFIG_TIME_INTERPOLATION */
1499 * msleep - sleep safely even with waitqueue interruptions
1500 * @msecs: Time in milliseconds to sleep for
1502 void msleep(unsigned int msecs)
1504 unsigned long timeout = msecs_to_jiffies(msecs);
1507 set_current_state(TASK_UNINTERRUPTIBLE);
1508 timeout = schedule_timeout(timeout);
1512 EXPORT_SYMBOL(msleep);