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>
35 #include <asm/uaccess.h>
36 #include <asm/div64.h>
37 #include <asm/timex.h>
40 * per-CPU timer vector definitions:
44 #define TVN_SIZE (1 << TVN_BITS)
45 #define TVR_SIZE (1 << TVR_BITS)
46 #define TVN_MASK (TVN_SIZE - 1)
47 #define TVR_MASK (TVR_SIZE - 1)
49 typedef struct tvec_s {
50 struct list_head vec[TVN_SIZE];
53 typedef struct tvec_root_s {
54 struct list_head vec[TVR_SIZE];
57 struct tvec_t_base_s {
59 unsigned long timer_jiffies;
60 struct timer_list *running_timer;
66 } ____cacheline_aligned_in_smp;
68 typedef struct tvec_t_base_s tvec_base_t;
70 static inline void set_running_timer(tvec_base_t *base,
71 struct timer_list *timer)
74 base->running_timer = timer;
78 /* Fake initialization */
79 static DEFINE_PER_CPU(tvec_base_t, tvec_bases) = { SPIN_LOCK_UNLOCKED };
81 static void check_timer_failed(struct timer_list *timer)
83 static int whine_count;
84 if (whine_count < 16) {
86 printk("Uninitialised timer!\n");
87 printk("This is just a warning. Your computer is OK\n");
88 printk("function=0x%p, data=0x%lx\n",
89 timer->function, timer->data);
95 spin_lock_init(&timer->lock);
96 timer->magic = TIMER_MAGIC;
99 static inline void check_timer(struct timer_list *timer)
101 if (timer->magic != TIMER_MAGIC)
102 check_timer_failed(timer);
106 static void internal_add_timer(tvec_base_t *base, struct timer_list *timer)
108 unsigned long expires = timer->expires;
109 unsigned long idx = expires - base->timer_jiffies;
110 struct list_head *vec;
112 if (idx < TVR_SIZE) {
113 int i = expires & TVR_MASK;
114 vec = base->tv1.vec + i;
115 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
116 int i = (expires >> TVR_BITS) & TVN_MASK;
117 vec = base->tv2.vec + i;
118 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
119 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
120 vec = base->tv3.vec + i;
121 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
122 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
123 vec = base->tv4.vec + i;
124 } else if ((signed long) idx < 0) {
126 * Can happen if you add a timer with expires == jiffies,
127 * or you set a timer to go off in the past
129 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
132 /* If the timeout is larger than 0xffffffff on 64-bit
133 * architectures then we use the maximum timeout:
135 if (idx > 0xffffffffUL) {
137 expires = idx + base->timer_jiffies;
139 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
140 vec = base->tv5.vec + i;
145 list_add_tail(&timer->entry, vec);
148 int __mod_timer(struct timer_list *timer, unsigned long expires)
150 tvec_base_t *old_base, *new_base;
154 BUG_ON(!timer->function);
158 spin_lock_irqsave(&timer->lock, flags);
159 new_base = &__get_cpu_var(tvec_bases);
161 old_base = timer->base;
164 * Prevent deadlocks via ordering by old_base < new_base.
166 if (old_base && (new_base != old_base)) {
167 if (old_base < new_base) {
168 spin_lock(&new_base->lock);
169 spin_lock(&old_base->lock);
171 spin_lock(&old_base->lock);
172 spin_lock(&new_base->lock);
175 * The timer base might have been cancelled while we were
176 * trying to take the lock(s):
178 if (timer->base != old_base) {
179 spin_unlock(&new_base->lock);
180 spin_unlock(&old_base->lock);
184 spin_lock(&new_base->lock);
185 if (timer->base != old_base) {
186 spin_unlock(&new_base->lock);
192 * Delete the previous timeout (if there was any), and install
196 list_del(&timer->entry);
199 timer->expires = expires;
200 internal_add_timer(new_base, timer);
201 timer->base = new_base;
203 if (old_base && (new_base != old_base))
204 spin_unlock(&old_base->lock);
205 spin_unlock(&new_base->lock);
206 spin_unlock_irqrestore(&timer->lock, flags);
211 EXPORT_SYMBOL(__mod_timer);
214 * add_timer_on - start a timer on a particular CPU
215 * @timer: the timer to be added
216 * @cpu: the CPU to start it on
218 * This is not very scalable on SMP. Double adds are not possible.
220 void add_timer_on(struct timer_list *timer, int cpu)
222 tvec_base_t *base = &per_cpu(tvec_bases, cpu);
225 BUG_ON(timer_pending(timer) || !timer->function);
229 spin_lock_irqsave(&base->lock, flags);
230 internal_add_timer(base, timer);
232 spin_unlock_irqrestore(&base->lock, flags);
236 * mod_timer - modify a timer's timeout
237 * @timer: the timer to be modified
239 * mod_timer is a more efficient way to update the expire field of an
240 * active timer (if the timer is inactive it will be activated)
242 * mod_timer(timer, expires) is equivalent to:
244 * del_timer(timer); timer->expires = expires; add_timer(timer);
246 * Note that if there are multiple unserialized concurrent users of the
247 * same timer, then mod_timer() is the only safe way to modify the timeout,
248 * since add_timer() cannot modify an already running timer.
250 * The function returns whether it has modified a pending timer or not.
251 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
252 * active timer returns 1.)
254 int mod_timer(struct timer_list *timer, unsigned long expires)
256 BUG_ON(!timer->function);
261 * This is a common optimization triggered by the
262 * networking code - if the timer is re-modified
263 * to be the same thing then just return:
265 if (timer->expires == expires && timer_pending(timer))
268 return __mod_timer(timer, expires);
271 EXPORT_SYMBOL(mod_timer);
274 * del_timer - deactive a timer.
275 * @timer: the timer to be deactivated
277 * del_timer() deactivates a timer - this works on both active and inactive
280 * The function returns whether it has deactivated a pending timer or not.
281 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
282 * active timer returns 1.)
284 int del_timer(struct timer_list *timer)
295 spin_lock_irqsave(&base->lock, flags);
296 if (base != timer->base) {
297 spin_unlock_irqrestore(&base->lock, flags);
300 list_del(&timer->entry);
302 spin_unlock_irqrestore(&base->lock, flags);
307 EXPORT_SYMBOL(del_timer);
311 * del_timer_sync - deactivate a timer and wait for the handler to finish.
312 * @timer: the timer to be deactivated
314 * This function only differs from del_timer() on SMP: besides deactivating
315 * the timer it also makes sure the handler has finished executing on other
318 * Synchronization rules: callers must prevent restarting of the timer,
319 * otherwise this function is meaningless. It must not be called from
320 * interrupt contexts. Upon exit the timer is not queued and the handler
321 * is not running on any CPU.
323 * The function returns whether it has deactivated a pending timer or not.
325 int del_timer_sync(struct timer_list *timer)
333 ret += del_timer(timer);
336 base = &per_cpu(tvec_bases, i);
337 if (base->running_timer == timer) {
338 while (base->running_timer == timer) {
340 preempt_check_resched();
346 if (timer_pending(timer))
352 EXPORT_SYMBOL(del_timer_sync);
355 static int cascade(tvec_base_t *base, tvec_t *tv, int index)
357 /* cascade all the timers from tv up one level */
358 struct list_head *head, *curr;
360 head = tv->vec + index;
363 * We are removing _all_ timers from the list, so we don't have to
364 * detach them individually, just clear the list afterwards.
366 while (curr != head) {
367 struct timer_list *tmp;
369 tmp = list_entry(curr, struct timer_list, entry);
370 BUG_ON(tmp->base != base);
372 internal_add_timer(base, tmp);
374 INIT_LIST_HEAD(head);
380 * __run_timers - run all expired timers (if any) on this CPU.
381 * @base: the timer vector to be processed.
383 * This function cascades all vectors and executes all expired timer
386 #define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) & TVN_MASK
388 static inline void __run_timers(tvec_base_t *base)
390 struct timer_list *timer;
392 spin_lock_irq(&base->lock);
393 while (time_after_eq(jiffies, base->timer_jiffies)) {
394 struct list_head work_list = LIST_HEAD_INIT(work_list);
395 struct list_head *head = &work_list;
396 int index = base->timer_jiffies & TVR_MASK;
402 (!cascade(base, &base->tv2, INDEX(0))) &&
403 (!cascade(base, &base->tv3, INDEX(1))) &&
404 !cascade(base, &base->tv4, INDEX(2)))
405 cascade(base, &base->tv5, INDEX(3));
406 ++base->timer_jiffies;
407 list_splice_init(base->tv1.vec + index, &work_list);
409 if (!list_empty(head)) {
410 void (*fn)(unsigned long);
413 timer = list_entry(head->next,struct timer_list,entry);
414 fn = timer->function;
417 list_del(&timer->entry);
418 set_running_timer(base, timer);
421 spin_unlock_irq(&base->lock);
423 spin_lock_irq(&base->lock);
427 set_running_timer(base, NULL);
428 spin_unlock_irq(&base->lock);
431 #ifdef CONFIG_NO_IDLE_HZ
433 * Find out when the next timer event is due to happen. This
434 * is used on S/390 to stop all activity when a cpus is idle.
435 * This functions needs to be called disabled.
437 unsigned long next_timer_interrupt(void)
440 struct list_head *list;
441 struct timer_list *nte;
442 unsigned long expires;
446 base = &__get_cpu_var(tvec_bases);
447 spin_lock(&base->lock);
448 expires = base->timer_jiffies + (LONG_MAX >> 1);
451 /* Look for timer events in tv1. */
452 j = base->timer_jiffies & TVR_MASK;
454 list_for_each_entry(nte, base->tv1.vec + j, entry) {
455 expires = nte->expires;
456 if (j < (base->timer_jiffies & TVR_MASK))
457 list = base->tv2.vec + (INDEX(0));
460 j = (j + 1) & TVR_MASK;
461 } while (j != (base->timer_jiffies & TVR_MASK));
464 varray[0] = &base->tv2;
465 varray[1] = &base->tv3;
466 varray[2] = &base->tv4;
467 varray[3] = &base->tv5;
468 for (i = 0; i < 4; i++) {
471 if (list_empty(varray[i]->vec + j)) {
472 j = (j + 1) & TVN_MASK;
475 list_for_each_entry(nte, varray[i]->vec + j, entry)
476 if (time_before(nte->expires, expires))
477 expires = nte->expires;
478 if (j < (INDEX(i)) && i < 3)
479 list = varray[i + 1]->vec + (INDEX(i + 1));
481 } while (j != (INDEX(i)));
486 * The search wrapped. We need to look at the next list
487 * from next tv element that would cascade into tv element
488 * where we found the timer element.
490 list_for_each_entry(nte, list, entry) {
491 if (time_before(nte->expires, expires))
492 expires = nte->expires;
495 spin_unlock(&base->lock);
500 /******************************************************************/
503 * Timekeeping variables
505 unsigned long tick_usec = TICK_USEC; /* USER_HZ period (usec) */
506 unsigned long tick_nsec = TICK_NSEC; /* ACTHZ period (nsec) */
510 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
511 * for sub jiffie times) to get to monotonic time. Monotonic is pegged at zero
512 * at zero at system boot time, so wall_to_monotonic will be negative,
513 * however, we will ALWAYS keep the tv_nsec part positive so we can use
514 * the usual normalization.
516 struct timespec xtime __attribute__ ((aligned (16)));
517 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
519 EXPORT_SYMBOL(xtime);
521 /* Don't completely fail for HZ > 500. */
522 int tickadj = 500/HZ ? : 1; /* microsecs */
526 * phase-lock loop variables
528 /* TIME_ERROR prevents overwriting the CMOS clock */
529 int time_state = TIME_OK; /* clock synchronization status */
530 int time_status = STA_UNSYNC; /* clock status bits */
531 long time_offset; /* time adjustment (us) */
532 long time_constant = 2; /* pll time constant */
533 long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
534 long time_precision = 1; /* clock precision (us) */
535 long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
536 long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
537 long time_phase; /* phase offset (scaled us) */
538 long time_freq = (((NSEC_PER_SEC + HZ/2) % HZ - HZ/2) << SHIFT_USEC) / NSEC_PER_USEC;
539 /* frequency offset (scaled ppm)*/
540 long time_adj; /* tick adjust (scaled 1 / HZ) */
541 long time_reftime; /* time at last adjustment (s) */
543 long time_next_adjust;
546 * this routine handles the overflow of the microsecond field
548 * The tricky bits of code to handle the accurate clock support
549 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
550 * They were originally developed for SUN and DEC kernels.
551 * All the kudos should go to Dave for this stuff.
554 static void second_overflow(void)
558 /* Bump the maxerror field */
559 time_maxerror += time_tolerance >> SHIFT_USEC;
560 if ( time_maxerror > NTP_PHASE_LIMIT ) {
561 time_maxerror = NTP_PHASE_LIMIT;
562 time_status |= STA_UNSYNC;
566 * Leap second processing. If in leap-insert state at
567 * the end of the day, the system clock is set back one
568 * second; if in leap-delete state, the system clock is
569 * set ahead one second. The microtime() routine or
570 * external clock driver will insure that reported time
571 * is always monotonic. The ugly divides should be
574 switch (time_state) {
577 if (time_status & STA_INS)
578 time_state = TIME_INS;
579 else if (time_status & STA_DEL)
580 time_state = TIME_DEL;
584 if (xtime.tv_sec % 86400 == 0) {
586 wall_to_monotonic.tv_sec++;
587 time_interpolator_update(-NSEC_PER_SEC);
588 time_state = TIME_OOP;
590 printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
595 if ((xtime.tv_sec + 1) % 86400 == 0) {
597 wall_to_monotonic.tv_sec--;
598 time_interpolator_update(NSEC_PER_SEC);
599 time_state = TIME_WAIT;
601 printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
606 time_state = TIME_WAIT;
610 if (!(time_status & (STA_INS | STA_DEL)))
611 time_state = TIME_OK;
615 * Compute the phase adjustment for the next second. In
616 * PLL mode, the offset is reduced by a fixed factor
617 * times the time constant. In FLL mode the offset is
618 * used directly. In either mode, the maximum phase
619 * adjustment for each second is clamped so as to spread
620 * the adjustment over not more than the number of
621 * seconds between updates.
623 if (time_offset < 0) {
624 ltemp = -time_offset;
625 if (!(time_status & STA_FLL))
626 ltemp >>= SHIFT_KG + time_constant;
627 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
628 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
629 time_offset += ltemp;
630 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
633 if (!(time_status & STA_FLL))
634 ltemp >>= SHIFT_KG + time_constant;
635 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
636 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
637 time_offset -= ltemp;
638 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
642 * Compute the frequency estimate and additional phase
643 * adjustment due to frequency error for the next
644 * second. When the PPS signal is engaged, gnaw on the
645 * watchdog counter and update the frequency computed by
646 * the pll and the PPS signal.
649 if (pps_valid == PPS_VALID) { /* PPS signal lost */
650 pps_jitter = MAXTIME;
651 pps_stabil = MAXFREQ;
652 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
653 STA_PPSWANDER | STA_PPSERROR);
655 ltemp = time_freq + pps_freq;
657 time_adj -= -ltemp >>
658 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
661 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
664 /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
665 * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
668 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
670 time_adj += (time_adj >> 2) + (time_adj >> 5);
673 /* Compensate for (HZ==1000) != (1 << SHIFT_HZ).
674 * Add 1.5625% and 0.78125% to get 1023.4375; => only 0.05% error (p. 14)
677 time_adj -= (-time_adj >> 6) + (-time_adj >> 7);
679 time_adj += (time_adj >> 6) + (time_adj >> 7);
683 /* in the NTP reference this is called "hardclock()" */
684 static void update_wall_time_one_tick(void)
686 long time_adjust_step, delta_nsec;
688 if ( (time_adjust_step = time_adjust) != 0 ) {
689 /* We are doing an adjtime thing.
691 * Prepare time_adjust_step to be within bounds.
692 * Note that a positive time_adjust means we want the clock
695 * Limit the amount of the step to be in the range
696 * -tickadj .. +tickadj
698 if (time_adjust > tickadj)
699 time_adjust_step = tickadj;
700 else if (time_adjust < -tickadj)
701 time_adjust_step = -tickadj;
703 /* Reduce by this step the amount of time left */
704 time_adjust -= time_adjust_step;
706 delta_nsec = tick_nsec + time_adjust_step * 1000;
708 * Advance the phase, once it gets to one microsecond, then
709 * advance the tick more.
711 time_phase += time_adj;
712 if (time_phase <= -FINENSEC) {
713 long ltemp = -time_phase >> (SHIFT_SCALE - 10);
714 time_phase += ltemp << (SHIFT_SCALE - 10);
717 else if (time_phase >= FINENSEC) {
718 long ltemp = time_phase >> (SHIFT_SCALE - 10);
719 time_phase -= ltemp << (SHIFT_SCALE - 10);
722 xtime.tv_nsec += delta_nsec;
723 time_interpolator_update(delta_nsec);
725 /* Changes by adjtime() do not take effect till next tick. */
726 if (time_next_adjust != 0) {
727 time_adjust = time_next_adjust;
728 time_next_adjust = 0;
733 * Using a loop looks inefficient, but "ticks" is
734 * usually just one (we shouldn't be losing ticks,
735 * we're doing this this way mainly for interrupt
736 * latency reasons, not because we think we'll
737 * have lots of lost timer ticks
739 static void update_wall_time(unsigned long ticks)
743 update_wall_time_one_tick();
746 if (xtime.tv_nsec >= 1000000000) {
747 xtime.tv_nsec -= 1000000000;
753 static inline void do_process_times(struct task_struct *p,
754 unsigned long user, unsigned long system)
758 psecs = (p->utime += user);
759 psecs += (p->stime += system);
760 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
761 /* Send SIGXCPU every second.. */
763 send_sig(SIGXCPU, p, 1);
764 /* and SIGKILL when we go over max.. */
765 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
766 send_sig(SIGKILL, p, 1);
770 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
772 unsigned long it_virt = p->it_virt_value;
777 it_virt = p->it_virt_incr;
778 send_sig(SIGVTALRM, p, 1);
780 p->it_virt_value = it_virt;
784 static inline void do_it_prof(struct task_struct *p)
786 unsigned long it_prof = p->it_prof_value;
789 if (--it_prof == 0) {
790 it_prof = p->it_prof_incr;
791 send_sig(SIGPROF, p, 1);
793 p->it_prof_value = it_prof;
797 void update_one_process(struct task_struct *p, unsigned long user,
798 unsigned long system, int cpu)
800 do_process_times(p, user, system);
806 * Called from the timer interrupt handler to charge one tick to the current
807 * process. user_tick is 1 if the tick is user time, 0 for system.
809 void update_process_times(int user_tick)
811 struct task_struct *p = current;
812 int cpu = smp_processor_id(), system = user_tick ^ 1;
814 update_one_process(p, user_tick, system, cpu);
816 scheduler_tick(user_tick, system);
820 * Nr of active tasks - counted in fixed-point numbers
822 static unsigned long count_active_tasks(void)
824 return (nr_running() + nr_uninterruptible()) * FIXED_1;
828 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
829 * imply that avenrun[] is the standard name for this kind of thing.
830 * Nothing else seems to be standardized: the fractional size etc
831 * all seem to differ on different machines.
833 * Requires xtime_lock to access.
835 unsigned long avenrun[3];
838 * calc_load - given tick count, update the avenrun load estimates.
839 * This is called while holding a write_lock on xtime_lock.
841 static inline void calc_load(unsigned long ticks)
843 unsigned long active_tasks; /* fixed-point */
844 static int count = LOAD_FREQ;
849 active_tasks = count_active_tasks();
850 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
851 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
852 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
856 /* jiffies at the most recent update of wall time */
857 unsigned long wall_jiffies = INITIAL_JIFFIES;
860 * This read-write spinlock protects us from races in SMP while
861 * playing with xtime and avenrun.
863 #ifndef ARCH_HAVE_XTIME_LOCK
864 seqlock_t xtime_lock __cacheline_aligned_in_smp = SEQLOCK_UNLOCKED;
866 EXPORT_SYMBOL(xtime_lock);
870 * This function runs timers and the timer-tq in bottom half context.
872 static void run_timer_softirq(struct softirq_action *h)
874 tvec_base_t *base = &__get_cpu_var(tvec_bases);
876 if (time_after_eq(jiffies, base->timer_jiffies))
881 * Called by the local, per-CPU timer interrupt on SMP.
883 void run_local_timers(void)
885 raise_softirq(TIMER_SOFTIRQ);
889 * Called by the timer interrupt. xtime_lock must already be taken
892 static inline void update_times(void)
896 ticks = jiffies - wall_jiffies;
898 wall_jiffies += ticks;
899 update_wall_time(ticks);
905 * The 64-bit jiffies value is not atomic - you MUST NOT read it
906 * without sampling the sequence number in xtime_lock.
907 * jiffies is defined in the linker script...
910 void do_timer(struct pt_regs *regs)
914 /* SMP process accounting uses the local APIC timer */
916 update_process_times(user_mode(regs));
921 #if !defined(__alpha__) && !defined(__ia64__)
924 * For backwards compatibility? This can be done in libc so Alpha
925 * and all newer ports shouldn't need it.
927 asmlinkage unsigned long sys_alarm(unsigned int seconds)
929 struct itimerval it_new, it_old;
930 unsigned int oldalarm;
932 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
933 it_new.it_value.tv_sec = seconds;
934 it_new.it_value.tv_usec = 0;
935 do_setitimer(ITIMER_REAL, &it_new, &it_old);
936 oldalarm = it_old.it_value.tv_sec;
937 /* ehhh.. We can't return 0 if we have an alarm pending.. */
938 /* And we'd better return too much than too little anyway */
939 if ((!oldalarm && it_old.it_value.tv_usec) || it_old.it_value.tv_usec >= 500000)
949 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
950 * should be moved into arch/i386 instead?
954 * sys_getpid - return the thread group id of the current process
956 * Note, despite the name, this returns the tgid not the pid. The tgid and
957 * the pid are identical unless CLONE_THREAD was specified on clone() in
958 * which case the tgid is the same in all threads of the same group.
960 * This is SMP safe as current->tgid does not change.
962 asmlinkage long sys_getpid(void)
964 return current->tgid;
968 * Accessing ->group_leader->real_parent is not SMP-safe, it could
969 * change from under us. However, rather than getting any lock
970 * we can use an optimistic algorithm: get the parent
971 * pid, and go back and check that the parent is still
972 * the same. If it has changed (which is extremely unlikely
973 * indeed), we just try again..
975 * NOTE! This depends on the fact that even if we _do_
976 * get an old value of "parent", we can happily dereference
977 * the pointer (it was and remains a dereferencable kernel pointer
978 * no matter what): we just can't necessarily trust the result
979 * until we know that the parent pointer is valid.
981 * NOTE2: ->group_leader never changes from under us.
983 asmlinkage long sys_getppid(void)
986 struct task_struct *me = current;
987 struct task_struct *parent;
989 parent = me->group_leader->real_parent;
994 struct task_struct *old = parent;
997 * Make sure we read the pid before re-reading the
1001 parent = me->group_leader->real_parent;
1011 asmlinkage long sys_getuid(void)
1013 /* Only we change this so SMP safe */
1014 return current->uid;
1017 asmlinkage long sys_geteuid(void)
1019 /* Only we change this so SMP safe */
1020 return current->euid;
1023 asmlinkage long sys_getgid(void)
1025 /* Only we change this so SMP safe */
1026 return current->gid;
1029 asmlinkage long sys_getegid(void)
1031 /* Only we change this so SMP safe */
1032 return current->egid;
1037 static void process_timeout(unsigned long __data)
1039 wake_up_process((task_t *)__data);
1043 * schedule_timeout - sleep until timeout
1044 * @timeout: timeout value in jiffies
1046 * Make the current task sleep until @timeout jiffies have
1047 * elapsed. The routine will return immediately unless
1048 * the current task state has been set (see set_current_state()).
1050 * You can set the task state as follows -
1052 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1053 * pass before the routine returns. The routine will return 0
1055 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1056 * delivered to the current task. In this case the remaining time
1057 * in jiffies will be returned, or 0 if the timer expired in time
1059 * The current task state is guaranteed to be TASK_RUNNING when this
1062 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1063 * the CPU away without a bound on the timeout. In this case the return
1064 * value will be %MAX_SCHEDULE_TIMEOUT.
1066 * In all cases the return value is guaranteed to be non-negative.
1068 fastcall signed long __sched schedule_timeout(signed long timeout)
1070 struct timer_list timer;
1071 unsigned long expire;
1075 case MAX_SCHEDULE_TIMEOUT:
1077 * These two special cases are useful to be comfortable
1078 * in the caller. Nothing more. We could take
1079 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1080 * but I' d like to return a valid offset (>=0) to allow
1081 * the caller to do everything it want with the retval.
1087 * Another bit of PARANOID. Note that the retval will be
1088 * 0 since no piece of kernel is supposed to do a check
1089 * for a negative retval of schedule_timeout() (since it
1090 * should never happens anyway). You just have the printk()
1091 * that will tell you if something is gone wrong and where.
1095 printk(KERN_ERR "schedule_timeout: wrong timeout "
1096 "value %lx from %p\n", timeout,
1097 __builtin_return_address(0));
1098 current->state = TASK_RUNNING;
1103 expire = timeout + jiffies;
1106 timer.expires = expire;
1107 timer.data = (unsigned long) current;
1108 timer.function = process_timeout;
1112 del_timer_sync(&timer);
1114 timeout = expire - jiffies;
1117 return timeout < 0 ? 0 : timeout;
1120 EXPORT_SYMBOL(schedule_timeout);
1122 /* Thread ID - the internal kernel "pid" */
1123 asmlinkage long sys_gettid(void)
1125 return current->pid;
1128 static long __sched nanosleep_restart(struct restart_block *restart)
1130 unsigned long expire = restart->arg0, now = jiffies;
1131 struct timespec __user *rmtp = (struct timespec __user *) restart->arg1;
1134 /* Did it expire while we handled signals? */
1135 if (!time_after(expire, now))
1138 current->state = TASK_INTERRUPTIBLE;
1139 expire = schedule_timeout(expire - now);
1144 jiffies_to_timespec(expire, &t);
1146 ret = -ERESTART_RESTARTBLOCK;
1147 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1149 /* The 'restart' block is already filled in */
1154 asmlinkage long sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1157 unsigned long expire;
1160 if (copy_from_user(&t, rqtp, sizeof(t)))
1163 if ((t.tv_nsec >= 1000000000L) || (t.tv_nsec < 0) || (t.tv_sec < 0))
1166 expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1167 current->state = TASK_INTERRUPTIBLE;
1168 expire = schedule_timeout(expire);
1172 struct restart_block *restart;
1173 jiffies_to_timespec(expire, &t);
1174 if (rmtp && copy_to_user(rmtp, &t, sizeof(t)))
1177 restart = ¤t_thread_info()->restart_block;
1178 restart->fn = nanosleep_restart;
1179 restart->arg0 = jiffies + expire;
1180 restart->arg1 = (unsigned long) rmtp;
1181 ret = -ERESTART_RESTARTBLOCK;
1187 * sys_sysinfo - fill in sysinfo struct
1189 asmlinkage long sys_sysinfo(struct sysinfo __user *info)
1192 unsigned long mem_total, sav_total;
1193 unsigned int mem_unit, bitcount;
1196 memset((char *)&val, 0, sizeof(struct sysinfo));
1200 seq = read_seqbegin(&xtime_lock);
1203 * This is annoying. The below is the same thing
1204 * posix_get_clock_monotonic() does, but it wants to
1205 * take the lock which we want to cover the loads stuff
1209 do_gettimeofday((struct timeval *)&tp);
1210 tp.tv_nsec *= NSEC_PER_USEC;
1211 tp.tv_sec += wall_to_monotonic.tv_sec;
1212 tp.tv_nsec += wall_to_monotonic.tv_nsec;
1213 if (tp.tv_nsec - NSEC_PER_SEC >= 0) {
1214 tp.tv_nsec = tp.tv_nsec - NSEC_PER_SEC;
1217 val.uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
1219 val.loads[0] = avenrun[0] << (SI_LOAD_SHIFT - FSHIFT);
1220 val.loads[1] = avenrun[1] << (SI_LOAD_SHIFT - FSHIFT);
1221 val.loads[2] = avenrun[2] << (SI_LOAD_SHIFT - FSHIFT);
1223 val.procs = nr_threads;
1224 } while (read_seqretry(&xtime_lock, seq));
1230 * If the sum of all the available memory (i.e. ram + swap)
1231 * is less than can be stored in a 32 bit unsigned long then
1232 * we can be binary compatible with 2.2.x kernels. If not,
1233 * well, in that case 2.2.x was broken anyways...
1235 * -Erik Andersen <andersee@debian.org>
1238 mem_total = val.totalram + val.totalswap;
1239 if (mem_total < val.totalram || mem_total < val.totalswap)
1242 mem_unit = val.mem_unit;
1243 while (mem_unit > 1) {
1246 sav_total = mem_total;
1248 if (mem_total < sav_total)
1253 * If mem_total did not overflow, multiply all memory values by
1254 * val.mem_unit and set it to 1. This leaves things compatible
1255 * with 2.2.x, and also retains compatibility with earlier 2.4.x
1260 val.totalram <<= bitcount;
1261 val.freeram <<= bitcount;
1262 val.sharedram <<= bitcount;
1263 val.bufferram <<= bitcount;
1264 val.totalswap <<= bitcount;
1265 val.freeswap <<= bitcount;
1266 val.totalhigh <<= bitcount;
1267 val.freehigh <<= bitcount;
1270 if (copy_to_user(info, &val, sizeof(struct sysinfo)))
1276 static void __devinit init_timers_cpu(int cpu)
1281 base = &per_cpu(tvec_bases, cpu);
1282 spin_lock_init(&base->lock);
1283 for (j = 0; j < TVN_SIZE; j++) {
1284 INIT_LIST_HEAD(base->tv5.vec + j);
1285 INIT_LIST_HEAD(base->tv4.vec + j);
1286 INIT_LIST_HEAD(base->tv3.vec + j);
1287 INIT_LIST_HEAD(base->tv2.vec + j);
1289 for (j = 0; j < TVR_SIZE; j++)
1290 INIT_LIST_HEAD(base->tv1.vec + j);
1292 base->timer_jiffies = jiffies;
1295 #ifdef CONFIG_HOTPLUG_CPU
1296 static int migrate_timer_list(tvec_base_t *new_base, struct list_head *head)
1298 struct timer_list *timer;
1300 while (!list_empty(head)) {
1301 timer = list_entry(head->next, struct timer_list, entry);
1302 /* We're locking backwards from __mod_timer order here,
1304 if (!spin_trylock(&timer->lock))
1306 list_del(&timer->entry);
1307 internal_add_timer(new_base, timer);
1308 timer->base = new_base;
1309 spin_unlock(&timer->lock);
1314 static void __devinit migrate_timers(int cpu)
1316 tvec_base_t *old_base;
1317 tvec_base_t *new_base;
1320 BUG_ON(cpu_online(cpu));
1321 old_base = &per_cpu(tvec_bases, cpu);
1322 new_base = &get_cpu_var(tvec_bases);
1324 local_irq_disable();
1326 /* Prevent deadlocks via ordering by old_base < new_base. */
1327 if (old_base < new_base) {
1328 spin_lock(&new_base->lock);
1329 spin_lock(&old_base->lock);
1331 spin_lock(&old_base->lock);
1332 spin_lock(&new_base->lock);
1335 if (old_base->running_timer)
1337 for (i = 0; i < TVR_SIZE; i++)
1338 if (!migrate_timer_list(new_base, old_base->tv1.vec + i))
1340 for (i = 0; i < TVN_SIZE; i++)
1341 if (!migrate_timer_list(new_base, old_base->tv2.vec + i)
1342 || !migrate_timer_list(new_base, old_base->tv3.vec + i)
1343 || !migrate_timer_list(new_base, old_base->tv4.vec + i)
1344 || !migrate_timer_list(new_base, old_base->tv5.vec + i))
1346 spin_unlock(&old_base->lock);
1347 spin_unlock(&new_base->lock);
1349 put_cpu_var(tvec_bases);
1353 /* Avoid deadlock with __mod_timer, by backing off. */
1354 spin_unlock(&old_base->lock);
1355 spin_unlock(&new_base->lock);
1359 #endif /* CONFIG_HOTPLUG_CPU */
1361 static int __devinit timer_cpu_notify(struct notifier_block *self,
1362 unsigned long action, void *hcpu)
1364 long cpu = (long)hcpu;
1366 case CPU_UP_PREPARE:
1367 init_timers_cpu(cpu);
1369 #ifdef CONFIG_HOTPLUG_CPU
1371 migrate_timers(cpu);
1380 static struct notifier_block __devinitdata timers_nb = {
1381 .notifier_call = timer_cpu_notify,
1385 void __init init_timers(void)
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);
1393 #ifdef CONFIG_TIME_INTERPOLATION
1394 volatile unsigned long last_nsec_offset;
1395 #ifndef __HAVE_ARCH_CMPXCHG
1396 spinlock_t last_nsec_offset_lock = SPIN_LOCK_UNLOCKED;
1399 struct time_interpolator *time_interpolator;
1400 static struct time_interpolator *time_interpolator_list;
1401 static spinlock_t time_interpolator_lock = SPIN_LOCK_UNLOCKED;
1404 is_better_time_interpolator(struct time_interpolator *new)
1406 if (!time_interpolator)
1408 return new->frequency > 2*time_interpolator->frequency ||
1409 (unsigned long)new->drift < (unsigned long)time_interpolator->drift;
1413 register_time_interpolator(struct time_interpolator *ti)
1415 spin_lock(&time_interpolator_lock);
1416 write_seqlock_irq(&xtime_lock);
1417 if (is_better_time_interpolator(ti))
1418 time_interpolator = ti;
1419 write_sequnlock_irq(&xtime_lock);
1421 ti->next = time_interpolator_list;
1422 time_interpolator_list = ti;
1423 spin_unlock(&time_interpolator_lock);
1427 unregister_time_interpolator(struct time_interpolator *ti)
1429 struct time_interpolator *curr, **prev;
1431 spin_lock(&time_interpolator_lock);
1432 prev = &time_interpolator_list;
1433 for (curr = *prev; curr; curr = curr->next) {
1441 write_seqlock_irq(&xtime_lock);
1442 if (ti == time_interpolator) {
1443 /* we lost the best time-interpolator: */
1444 time_interpolator = NULL;
1445 /* find the next-best interpolator */
1446 for (curr = time_interpolator_list; curr; curr = curr->next)
1447 if (is_better_time_interpolator(curr))
1448 time_interpolator = curr;
1450 write_sequnlock_irq(&xtime_lock);
1451 spin_unlock(&time_interpolator_lock);
1453 #endif /* CONFIG_TIME_INTERPOLATION */