pre-2.1.109-2..
[davej-history.git] / kernel / sched.c
blob63d95efe4c31cdd9ce9c4d3b6d618ec0ac541dde
1 /*
2 * linux/kernel/sched.c
4 * Copyright (C) 1991, 1992 Linus Torvalds
6 * 1996-04-21 Modified by Ulrich Windl to make NTP work
7 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
8 * make semaphores SMP safe
9 * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better.
13 * 'sched.c' is the main kernel file. It contains scheduling primitives
14 * (sleep_on, wakeup, schedule etc) as well as a number of simple system
15 * call functions (type getpid()), which just extract a field from
16 * current-task
19 #include <linux/signal.h>
20 #include <linux/sched.h>
21 #include <linux/timer.h>
22 #include <linux/kernel.h>
23 #include <linux/kernel_stat.h>
24 #include <linux/fdreg.h>
25 #include <linux/errno.h>
26 #include <linux/time.h>
27 #include <linux/ptrace.h>
28 #include <linux/delay.h>
29 #include <linux/interrupt.h>
30 #include <linux/tqueue.h>
31 #include <linux/resource.h>
32 #include <linux/mm.h>
33 #include <linux/smp.h>
34 #include <linux/smp_lock.h>
35 #include <linux/init.h>
37 #include <asm/system.h>
38 #include <asm/io.h>
39 #include <asm/uaccess.h>
40 #include <asm/pgtable.h>
41 #include <asm/mmu_context.h>
42 #include <asm/spinlock.h>
44 #include <linux/timex.h>
47 * kernel variables
50 unsigned securebits = SECUREBITS_DEFAULT; /* systemwide security settings */
52 long tick = (1000000 + HZ/2) / HZ; /* timer interrupt period */
54 /* The current time */
55 volatile struct timeval xtime __attribute__ ((aligned (16)));
57 /* Don't completely fail for HZ > 500. */
58 int tickadj = 500/HZ ? : 1; /* microsecs */
60 DECLARE_TASK_QUEUE(tq_timer);
61 DECLARE_TASK_QUEUE(tq_immediate);
62 DECLARE_TASK_QUEUE(tq_scheduler);
65 * phase-lock loop variables
67 /* TIME_ERROR prevents overwriting the CMOS clock */
68 int time_state = TIME_ERROR; /* clock synchronization status */
69 int time_status = STA_UNSYNC; /* clock status bits */
70 long time_offset = 0; /* time adjustment (us) */
71 long time_constant = 2; /* pll time constant */
72 long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
73 long time_precision = 1; /* clock precision (us) */
74 long time_maxerror = MAXPHASE; /* maximum error (us) */
75 long time_esterror = MAXPHASE; /* estimated error (us) */
76 long time_phase = 0; /* phase offset (scaled us) */
77 long time_freq = ((1000000 + HZ/2) % HZ - HZ/2) << SHIFT_USEC; /* frequency offset (scaled ppm) */
78 long time_adj = 0; /* tick adjust (scaled 1 / HZ) */
79 long time_reftime = 0; /* time at last adjustment (s) */
81 long time_adjust = 0;
82 long time_adjust_step = 0;
84 int need_resched = 0;
85 unsigned long event = 0;
87 extern int do_setitimer(int, struct itimerval *, struct itimerval *);
88 unsigned int * prof_buffer = NULL;
89 unsigned long prof_len = 0;
90 unsigned long prof_shift = 0;
92 extern void mem_use(void);
94 unsigned long volatile jiffies=0;
97 * Init task must be ok at boot for the ix86 as we will check its signals
98 * via the SMP irq return path.
101 struct task_struct * task[NR_TASKS] = {&init_task, };
103 struct kernel_stat kstat = { 0 };
105 void scheduling_functions_start_here(void) { }
107 static inline void add_to_runqueue(struct task_struct * p)
109 if (p->policy != SCHED_OTHER || p->counter > current->counter + 3)
110 need_resched = 1;
111 nr_running++;
112 (p->prev_run = init_task.prev_run)->next_run = p;
113 p->next_run = &init_task;
114 init_task.prev_run = p;
117 static inline void del_from_runqueue(struct task_struct * p)
119 struct task_struct *next = p->next_run;
120 struct task_struct *prev = p->prev_run;
122 nr_running--;
123 next->prev_run = prev;
124 prev->next_run = next;
125 p->next_run = NULL;
126 p->prev_run = NULL;
129 static inline void move_last_runqueue(struct task_struct * p)
131 struct task_struct *next = p->next_run;
132 struct task_struct *prev = p->prev_run;
134 /* remove from list */
135 next->prev_run = prev;
136 prev->next_run = next;
137 /* add back to list */
138 p->next_run = &init_task;
139 prev = init_task.prev_run;
140 init_task.prev_run = p;
141 p->prev_run = prev;
142 prev->next_run = p;
145 static inline void move_first_runqueue(struct task_struct * p)
147 struct task_struct *next = p->next_run;
148 struct task_struct *prev = p->prev_run;
150 /* remove from list */
151 next->prev_run = prev;
152 prev->next_run = next;
153 /* add back to list */
154 p->prev_run = &init_task;
155 next = init_task.next_run;
156 init_task.next_run = p;
157 p->next_run = next;
158 next->prev_run = p;
162 * The tasklist_lock protects the linked list of processes.
164 * The scheduler lock is protecting against multiple entry
165 * into the scheduling code, and doesn't need to worry
166 * about interrupts (because interrupts cannot call the
167 * scheduler).
169 * The run-queue lock locks the parts that actually access
170 * and change the run-queues, and have to be interrupt-safe.
172 spinlock_t scheduler_lock = SPIN_LOCK_UNLOCKED; /* should be acquired first */
173 spinlock_t runqueue_lock = SPIN_LOCK_UNLOCKED; /* second */
174 rwlock_t tasklist_lock = RW_LOCK_UNLOCKED; /* third */
177 * Wake up a process. Put it on the run-queue if it's not
178 * already there. The "current" process is always on the
179 * run-queue (except when the actual re-schedule is in
180 * progress), and as such you're allowed to do the simpler
181 * "current->state = TASK_RUNNING" to mark yourself runnable
182 * without the overhead of this.
184 inline void wake_up_process(struct task_struct * p)
186 unsigned long flags;
188 spin_lock_irqsave(&runqueue_lock, flags);
189 p->state = TASK_RUNNING;
190 if (!p->next_run)
191 add_to_runqueue(p);
192 spin_unlock_irqrestore(&runqueue_lock, flags);
195 static void process_timeout(unsigned long __data)
197 struct task_struct * p = (struct task_struct *) __data;
199 p->timeout = 0;
200 wake_up_process(p);
204 * This is the function that decides how desirable a process is..
205 * You can weigh different processes against each other depending
206 * on what CPU they've run on lately etc to try to handle cache
207 * and TLB miss penalties.
209 * Return values:
210 * -1000: never select this
211 * 0: out of time, recalculate counters (but it might still be
212 * selected)
213 * +ve: "goodness" value (the larger, the better)
214 * +1000: realtime process, select this.
216 static inline int goodness(struct task_struct * p, struct task_struct * prev, int this_cpu)
218 int policy = p->policy;
219 int weight;
221 if (policy & SCHED_YIELD) {
222 p->policy = policy & ~SCHED_YIELD;
223 return 0;
227 * Realtime process, select the first one on the
228 * runqueue (taking priorities within processes
229 * into account).
231 if (policy != SCHED_OTHER)
232 return 1000 + p->rt_priority;
235 * Give the process a first-approximation goodness value
236 * according to the number of clock-ticks it has left.
238 * Don't do any other calculations if the time slice is
239 * over..
241 weight = p->counter;
242 if (weight) {
244 #ifdef __SMP__
245 /* Give a largish advantage to the same processor... */
246 /* (this is equivalent to penalizing other processors) */
247 if (p->processor == this_cpu)
248 weight += PROC_CHANGE_PENALTY;
249 #endif
251 /* .. and a slight advantage to the current thread */
252 if (p->mm == prev->mm)
253 weight += 1;
254 weight += p->priority;
257 return weight;
261 * Event timer code
263 #define TVN_BITS 6
264 #define TVR_BITS 8
265 #define TVN_SIZE (1 << TVN_BITS)
266 #define TVR_SIZE (1 << TVR_BITS)
267 #define TVN_MASK (TVN_SIZE - 1)
268 #define TVR_MASK (TVR_SIZE - 1)
270 struct timer_vec {
271 int index;
272 struct timer_list *vec[TVN_SIZE];
275 struct timer_vec_root {
276 int index;
277 struct timer_list *vec[TVR_SIZE];
280 static struct timer_vec tv5 = { 0 };
281 static struct timer_vec tv4 = { 0 };
282 static struct timer_vec tv3 = { 0 };
283 static struct timer_vec tv2 = { 0 };
284 static struct timer_vec_root tv1 = { 0 };
286 static struct timer_vec * const tvecs[] = {
287 (struct timer_vec *)&tv1, &tv2, &tv3, &tv4, &tv5
290 #define NOOF_TVECS (sizeof(tvecs) / sizeof(tvecs[0]))
292 static unsigned long timer_jiffies = 0;
294 static inline void insert_timer(struct timer_list *timer,
295 struct timer_list **vec, int idx)
297 if ((timer->next = vec[idx]))
298 vec[idx]->prev = timer;
299 vec[idx] = timer;
300 timer->prev = (struct timer_list *)&vec[idx];
303 static inline void internal_add_timer(struct timer_list *timer)
306 * must be cli-ed when calling this
308 unsigned long expires = timer->expires;
309 unsigned long idx = expires - timer_jiffies;
311 if (idx < TVR_SIZE) {
312 int i = expires & TVR_MASK;
313 insert_timer(timer, tv1.vec, i);
314 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
315 int i = (expires >> TVR_BITS) & TVN_MASK;
316 insert_timer(timer, tv2.vec, i);
317 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
318 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
319 insert_timer(timer, tv3.vec, i);
320 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
321 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
322 insert_timer(timer, tv4.vec, i);
323 } else if (expires < timer_jiffies) {
324 /* can happen if you add a timer with expires == jiffies,
325 * or you set a timer to go off in the past
327 insert_timer(timer, tv1.vec, tv1.index);
328 } else if (idx < 0xffffffffUL) {
329 int i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
330 insert_timer(timer, tv5.vec, i);
331 } else {
332 /* Can only get here on architectures with 64-bit jiffies */
333 timer->next = timer->prev = timer;
337 spinlock_t timerlist_lock = SPIN_LOCK_UNLOCKED;
339 void add_timer(struct timer_list *timer)
341 unsigned long flags;
343 spin_lock_irqsave(&timerlist_lock, flags);
344 internal_add_timer(timer);
345 spin_unlock_irqrestore(&timerlist_lock, flags);
348 static inline int detach_timer(struct timer_list *timer)
350 struct timer_list *prev = timer->prev;
351 if (prev) {
352 struct timer_list *next = timer->next;
353 prev->next = next;
354 if (next)
355 next->prev = prev;
356 return 1;
358 return 0;
361 void mod_timer(struct timer_list *timer, unsigned long expires)
363 unsigned long flags;
365 spin_lock_irqsave(&timerlist_lock, flags);
366 timer->expires = expires;
367 detach_timer(timer);
368 internal_add_timer(timer);
369 spin_unlock_irqrestore(&timerlist_lock, flags);
372 int del_timer(struct timer_list * timer)
374 int ret;
375 unsigned long flags;
377 spin_lock_irqsave(&timerlist_lock, flags);
378 ret = detach_timer(timer);
379 timer->next = timer->prev = 0;
380 spin_unlock_irqrestore(&timerlist_lock, flags);
381 return ret;
384 #ifdef __SMP__
386 #define idle_task (task[cpu_number_map[this_cpu]])
387 #define can_schedule(p) (!(p)->has_cpu)
389 #else
391 #define idle_task (&init_task)
392 #define can_schedule(p) (1)
394 #endif
397 * 'schedule()' is the scheduler function. It's a very simple and nice
398 * scheduler: it's not perfect, but certainly works for most things.
400 * The goto is "interesting".
402 * NOTE!! Task 0 is the 'idle' task, which gets called when no other
403 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
404 * information in task[0] is never used.
406 asmlinkage void schedule(void)
408 int lock_depth;
409 struct task_struct * prev, * next;
410 unsigned long timeout;
411 int this_cpu;
413 need_resched = 0;
414 prev = current;
415 this_cpu = smp_processor_id();
416 if (in_interrupt())
417 goto scheduling_in_interrupt;
418 release_kernel_lock(prev, this_cpu, lock_depth);
419 if (bh_active & bh_mask)
420 do_bottom_half();
422 spin_lock(&scheduler_lock);
423 spin_lock_irq(&runqueue_lock);
425 /* move an exhausted RR process to be last.. */
426 if (!prev->counter && prev->policy == SCHED_RR) {
427 prev->counter = prev->priority;
428 move_last_runqueue(prev);
430 timeout = 0;
431 switch (prev->state) {
432 case TASK_INTERRUPTIBLE:
433 if (signal_pending(prev))
434 goto makerunnable;
435 timeout = prev->timeout;
436 if (timeout && (timeout <= jiffies)) {
437 prev->timeout = 0;
438 timeout = 0;
439 makerunnable:
440 prev->state = TASK_RUNNING;
441 break;
443 default:
444 del_from_runqueue(prev);
445 case TASK_RUNNING:
448 struct task_struct * p = init_task.next_run;
450 * This is subtle.
451 * Note how we can enable interrupts here, even
452 * though interrupts can add processes to the run-
453 * queue. This is because any new processes will
454 * be added to the front of the queue, so "p" above
455 * is a safe starting point.
456 * run-queue deletion and re-ordering is protected by
457 * the scheduler lock
459 spin_unlock_irq(&runqueue_lock);
460 #ifdef __SMP__
461 prev->has_cpu = 0;
462 #endif
465 * Note! there may appear new tasks on the run-queue during this, as
466 * interrupts are enabled. However, they will be put on front of the
467 * list, so our list starting at "p" is essentially fixed.
469 /* this is the scheduler proper: */
471 int c = -1000;
472 next = idle_task;
473 while (p != &init_task) {
474 if (can_schedule(p)) {
475 int weight = goodness(p, prev, this_cpu);
476 if (weight > c)
477 c = weight, next = p;
479 p = p->next_run;
482 /* Do we need to re-calculate counters? */
483 if (!c) {
484 struct task_struct *p;
485 read_lock(&tasklist_lock);
486 for_each_task(p)
487 p->counter = (p->counter >> 1) + p->priority;
488 read_unlock(&tasklist_lock);
493 #ifdef __SMP__
494 next->has_cpu = 1;
495 next->processor = this_cpu;
496 #endif
498 if (prev != next) {
499 struct timer_list timer;
501 kstat.context_swtch++;
502 if (timeout) {
503 init_timer(&timer);
504 timer.expires = timeout;
505 timer.data = (unsigned long) prev;
506 timer.function = process_timeout;
507 add_timer(&timer);
509 get_mmu_context(next);
510 switch_to(prev,next);
512 if (timeout)
513 del_timer(&timer);
515 spin_unlock(&scheduler_lock);
517 reacquire_kernel_lock(prev, smp_processor_id(), lock_depth);
518 return;
520 scheduling_in_interrupt:
521 printk("Scheduling in interrupt\n");
522 *(int *)0 = 0;
526 rwlock_t waitqueue_lock = RW_LOCK_UNLOCKED;
529 * wake_up doesn't wake up stopped processes - they have to be awakened
530 * with signals or similar.
532 * Note that we only need a read lock for the wait queue (and thus do not
533 * have to protect against interrupts), as the actual removal from the
534 * queue is handled by the process itself.
536 void __wake_up(struct wait_queue **q, unsigned int mode)
538 struct wait_queue *next;
540 read_lock(&waitqueue_lock);
541 if (q && (next = *q)) {
542 struct wait_queue *head;
544 head = WAIT_QUEUE_HEAD(q);
545 while (next != head) {
546 struct task_struct *p = next->task;
547 next = next->next;
548 if (p->state & mode)
549 wake_up_process(p);
552 read_unlock(&waitqueue_lock);
556 * Semaphores are implemented using a two-way counter:
557 * The "count" variable is decremented for each process
558 * that tries to sleep, while the "waking" variable is
559 * incremented when the "up()" code goes to wake up waiting
560 * processes.
562 * Notably, the inline "up()" and "down()" functions can
563 * efficiently test if they need to do any extra work (up
564 * needs to do something only if count was negative before
565 * the increment operation.
567 * waking_non_zero() (from asm/semaphore.h) must execute
568 * atomically.
570 * When __up() is called, the count was negative before
571 * incrementing it, and we need to wake up somebody.
573 * This routine adds one to the count of processes that need to
574 * wake up and exit. ALL waiting processes actually wake up but
575 * only the one that gets to the "waking" field first will gate
576 * through and acquire the semaphore. The others will go back
577 * to sleep.
579 * Note that these functions are only called when there is
580 * contention on the lock, and as such all this is the
581 * "non-critical" part of the whole semaphore business. The
582 * critical part is the inline stuff in <asm/semaphore.h>
583 * where we want to avoid any extra jumps and calls.
585 void __up(struct semaphore *sem)
587 wake_one_more(sem);
588 wake_up(&sem->wait);
592 * Perform the "down" function. Return zero for semaphore acquired,
593 * return negative for signalled out of the function.
595 * If called from __down, the return is ignored and the wait loop is
596 * not interruptible. This means that a task waiting on a semaphore
597 * using "down()" cannot be killed until someone does an "up()" on
598 * the semaphore.
600 * If called from __down_interruptible, the return value gets checked
601 * upon return. If the return value is negative then the task continues
602 * with the negative value in the return register (it can be tested by
603 * the caller).
605 * Either form may be used in conjunction with "up()".
608 static inline int __do_down(struct semaphore * sem, int task_state)
610 struct task_struct *tsk = current;
611 struct wait_queue wait = { tsk, NULL };
612 int ret = 0;
614 tsk->state = task_state;
615 add_wait_queue(&sem->wait, &wait);
618 * Ok, we're set up. sem->count is known to be less than zero
619 * so we must wait.
621 * We can let go the lock for purposes of waiting.
622 * We re-acquire it after awaking so as to protect
623 * all semaphore operations.
625 * If "up()" is called before we call waking_non_zero() then
626 * we will catch it right away. If it is called later then
627 * we will have to go through a wakeup cycle to catch it.
629 * Multiple waiters contend for the semaphore lock to see
630 * who gets to gate through and who has to wait some more.
632 for (;;) {
633 if (waking_non_zero(sem)) /* are we waking up? */
634 break; /* yes, exit loop */
636 if (task_state == TASK_INTERRUPTIBLE && signal_pending(tsk)) {
637 ret = -EINTR; /* interrupted */
638 atomic_inc(&sem->count); /* give up on down operation */
639 break;
642 schedule();
643 tsk->state = task_state;
646 tsk->state = TASK_RUNNING;
647 remove_wait_queue(&sem->wait, &wait);
648 return ret;
651 void __down(struct semaphore * sem)
653 __do_down(sem,TASK_UNINTERRUPTIBLE);
656 int __down_interruptible(struct semaphore * sem)
658 return __do_down(sem,TASK_INTERRUPTIBLE);
662 static void FASTCALL(__sleep_on(struct wait_queue **p, int state));
663 static void __sleep_on(struct wait_queue **p, int state)
665 unsigned long flags;
666 struct wait_queue wait;
668 current->state = state;
669 wait.task = current;
670 write_lock_irqsave(&waitqueue_lock, flags);
671 __add_wait_queue(p, &wait);
672 write_unlock(&waitqueue_lock);
673 schedule();
674 write_lock_irq(&waitqueue_lock);
675 __remove_wait_queue(p, &wait);
676 write_unlock_irqrestore(&waitqueue_lock, flags);
679 void interruptible_sleep_on(struct wait_queue **p)
681 __sleep_on(p,TASK_INTERRUPTIBLE);
684 void sleep_on(struct wait_queue **p)
686 __sleep_on(p,TASK_UNINTERRUPTIBLE);
689 void scheduling_functions_end_here(void) { }
691 static inline void cascade_timers(struct timer_vec *tv)
693 /* cascade all the timers from tv up one level */
694 struct timer_list *timer;
695 timer = tv->vec[tv->index];
697 * We are removing _all_ timers from the list, so we don't have to
698 * detach them individually, just clear the list afterwards.
700 while (timer) {
701 struct timer_list *tmp = timer;
702 timer = timer->next;
703 internal_add_timer(tmp);
705 tv->vec[tv->index] = NULL;
706 tv->index = (tv->index + 1) & TVN_MASK;
709 static inline void run_timer_list(void)
711 spin_lock_irq(&timerlist_lock);
712 while ((long)(jiffies - timer_jiffies) >= 0) {
713 struct timer_list *timer;
714 if (!tv1.index) {
715 int n = 1;
716 do {
717 cascade_timers(tvecs[n]);
718 } while (tvecs[n]->index == 1 && ++n < NOOF_TVECS);
720 while ((timer = tv1.vec[tv1.index])) {
721 void (*fn)(unsigned long) = timer->function;
722 unsigned long data = timer->data;
723 detach_timer(timer);
724 timer->next = timer->prev = NULL;
725 spin_unlock_irq(&timerlist_lock);
726 fn(data);
727 spin_lock_irq(&timerlist_lock);
729 ++timer_jiffies;
730 tv1.index = (tv1.index + 1) & TVR_MASK;
732 spin_unlock_irq(&timerlist_lock);
736 static inline void run_old_timers(void)
738 struct timer_struct *tp;
739 unsigned long mask;
741 for (mask = 1, tp = timer_table+0 ; mask ; tp++,mask += mask) {
742 if (mask > timer_active)
743 break;
744 if (!(mask & timer_active))
745 continue;
746 if (tp->expires > jiffies)
747 continue;
748 timer_active &= ~mask;
749 tp->fn();
750 sti();
754 spinlock_t tqueue_lock;
756 void tqueue_bh(void)
758 run_task_queue(&tq_timer);
761 void immediate_bh(void)
763 run_task_queue(&tq_immediate);
766 unsigned long timer_active = 0;
767 struct timer_struct timer_table[32];
770 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
771 * imply that avenrun[] is the standard name for this kind of thing.
772 * Nothing else seems to be standardized: the fractional size etc
773 * all seem to differ on different machines.
775 unsigned long avenrun[3] = { 0,0,0 };
778 * Nr of active tasks - counted in fixed-point numbers
780 static unsigned long count_active_tasks(void)
782 struct task_struct *p;
783 unsigned long nr = 0;
785 read_lock(&tasklist_lock);
786 for_each_task(p) {
787 if (p->pid &&
788 (p->state == TASK_RUNNING ||
789 p->state == TASK_UNINTERRUPTIBLE ||
790 p->state == TASK_SWAPPING))
791 nr += FIXED_1;
793 read_unlock(&tasklist_lock);
794 return nr;
797 static inline void calc_load(unsigned long ticks)
799 unsigned long active_tasks; /* fixed-point */
800 static int count = LOAD_FREQ;
802 count -= ticks;
803 if (count < 0) {
804 count += LOAD_FREQ;
805 active_tasks = count_active_tasks();
806 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
807 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
808 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
813 * this routine handles the overflow of the microsecond field
815 * The tricky bits of code to handle the accurate clock support
816 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
817 * They were originally developed for SUN and DEC kernels.
818 * All the kudos should go to Dave for this stuff.
821 static void second_overflow(void)
823 long ltemp;
825 /* Bump the maxerror field */
826 time_maxerror += time_tolerance >> SHIFT_USEC;
827 if ( time_maxerror > MAXPHASE )
828 time_maxerror = MAXPHASE;
831 * Leap second processing. If in leap-insert state at
832 * the end of the day, the system clock is set back one
833 * second; if in leap-delete state, the system clock is
834 * set ahead one second. The microtime() routine or
835 * external clock driver will insure that reported time
836 * is always monotonic. The ugly divides should be
837 * replaced.
839 switch (time_state) {
841 case TIME_OK:
842 if (time_status & STA_INS)
843 time_state = TIME_INS;
844 else if (time_status & STA_DEL)
845 time_state = TIME_DEL;
846 break;
848 case TIME_INS:
849 if (xtime.tv_sec % 86400 == 0) {
850 xtime.tv_sec--;
851 time_state = TIME_OOP;
852 printk("Clock: inserting leap second 23:59:60 UTC\n");
854 break;
856 case TIME_DEL:
857 if ((xtime.tv_sec + 1) % 86400 == 0) {
858 xtime.tv_sec++;
859 time_state = TIME_WAIT;
860 printk("Clock: deleting leap second 23:59:59 UTC\n");
862 break;
864 case TIME_OOP:
865 time_state = TIME_WAIT;
866 break;
868 case TIME_WAIT:
869 if (!(time_status & (STA_INS | STA_DEL)))
870 time_state = TIME_OK;
874 * Compute the phase adjustment for the next second. In
875 * PLL mode, the offset is reduced by a fixed factor
876 * times the time constant. In FLL mode the offset is
877 * used directly. In either mode, the maximum phase
878 * adjustment for each second is clamped so as to spread
879 * the adjustment over not more than the number of
880 * seconds between updates.
882 if (time_offset < 0) {
883 ltemp = -time_offset;
884 if (!(time_status & STA_FLL))
885 ltemp >>= SHIFT_KG + time_constant;
886 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
887 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
888 time_offset += ltemp;
889 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
890 } else {
891 ltemp = time_offset;
892 if (!(time_status & STA_FLL))
893 ltemp >>= SHIFT_KG + time_constant;
894 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
895 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
896 time_offset -= ltemp;
897 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
901 * Compute the frequency estimate and additional phase
902 * adjustment due to frequency error for the next
903 * second. When the PPS signal is engaged, gnaw on the
904 * watchdog counter and update the frequency computed by
905 * the pll and the PPS signal.
907 pps_valid++;
908 if (pps_valid == PPS_VALID) {
909 pps_jitter = MAXTIME;
910 pps_stabil = MAXFREQ;
911 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
912 STA_PPSWANDER | STA_PPSERROR);
914 ltemp = time_freq + pps_freq;
915 if (ltemp < 0)
916 time_adj -= -ltemp >>
917 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
918 else
919 time_adj += ltemp >>
920 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
922 #if HZ == 100
923 /* compensate for (HZ==100) != 128. Add 25% to get 125; => only 3% error */
924 if (time_adj < 0)
925 time_adj -= -time_adj >> 2;
926 else
927 time_adj += time_adj >> 2;
928 #endif
931 /* in the NTP reference this is called "hardclock()" */
932 static void update_wall_time_one_tick(void)
935 * Advance the phase, once it gets to one microsecond, then
936 * advance the tick more.
938 time_phase += time_adj;
939 if (time_phase <= -FINEUSEC) {
940 long ltemp = -time_phase >> SHIFT_SCALE;
941 time_phase += ltemp << SHIFT_SCALE;
942 xtime.tv_usec += tick + time_adjust_step - ltemp;
944 else if (time_phase >= FINEUSEC) {
945 long ltemp = time_phase >> SHIFT_SCALE;
946 time_phase -= ltemp << SHIFT_SCALE;
947 xtime.tv_usec += tick + time_adjust_step + ltemp;
948 } else
949 xtime.tv_usec += tick + time_adjust_step;
951 if (time_adjust) {
952 /* We are doing an adjtime thing.
954 * Modify the value of the tick for next time.
955 * Note that a positive delta means we want the clock
956 * to run fast. This means that the tick should be bigger
958 * Limit the amount of the step for *next* tick to be
959 * in the range -tickadj .. +tickadj
961 if (time_adjust > tickadj)
962 time_adjust_step = tickadj;
963 else if (time_adjust < -tickadj)
964 time_adjust_step = -tickadj;
965 else
966 time_adjust_step = time_adjust;
968 /* Reduce by this step the amount of time left */
969 time_adjust -= time_adjust_step;
971 else
972 time_adjust_step = 0;
976 * Using a loop looks inefficient, but "ticks" is
977 * usually just one (we shouldn't be losing ticks,
978 * we're doing this this way mainly for interrupt
979 * latency reasons, not because we think we'll
980 * have lots of lost timer ticks
982 static void update_wall_time(unsigned long ticks)
984 do {
985 ticks--;
986 update_wall_time_one_tick();
987 } while (ticks);
989 if (xtime.tv_usec >= 1000000) {
990 xtime.tv_usec -= 1000000;
991 xtime.tv_sec++;
992 second_overflow();
996 static inline void do_process_times(struct task_struct *p,
997 unsigned long user, unsigned long system)
999 long psecs;
1001 psecs = (p->times.tms_utime += user);
1002 psecs += (p->times.tms_stime += system);
1003 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
1004 /* Send SIGXCPU every second.. */
1005 if (!(psecs % HZ))
1006 send_sig(SIGXCPU, p, 1);
1007 /* and SIGKILL when we go over max.. */
1008 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
1009 send_sig(SIGKILL, p, 1);
1013 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
1015 unsigned long it_virt = p->it_virt_value;
1017 if (it_virt) {
1018 if (it_virt <= ticks) {
1019 it_virt = ticks + p->it_virt_incr;
1020 send_sig(SIGVTALRM, p, 1);
1022 p->it_virt_value = it_virt - ticks;
1026 static inline void do_it_prof(struct task_struct * p, unsigned long ticks)
1028 unsigned long it_prof = p->it_prof_value;
1030 if (it_prof) {
1031 if (it_prof <= ticks) {
1032 it_prof = ticks + p->it_prof_incr;
1033 send_sig(SIGPROF, p, 1);
1035 p->it_prof_value = it_prof - ticks;
1039 void update_one_process(struct task_struct *p,
1040 unsigned long ticks, unsigned long user, unsigned long system, int cpu)
1042 p->per_cpu_utime[cpu] += user;
1043 p->per_cpu_stime[cpu] += system;
1044 do_process_times(p, user, system);
1045 do_it_virt(p, user);
1046 do_it_prof(p, ticks);
1049 static void update_process_times(unsigned long ticks, unsigned long system)
1052 * SMP does this on a per-CPU basis elsewhere
1054 #ifndef __SMP__
1055 struct task_struct * p = current;
1056 unsigned long user = ticks - system;
1057 if (p->pid) {
1058 p->counter -= ticks;
1059 if (p->counter < 0) {
1060 p->counter = 0;
1061 need_resched = 1;
1063 if (p->priority < DEF_PRIORITY)
1064 kstat.cpu_nice += user;
1065 else
1066 kstat.cpu_user += user;
1067 kstat.cpu_system += system;
1069 update_one_process(p, ticks, user, system, 0);
1070 #endif
1073 volatile unsigned long lost_ticks = 0;
1074 static unsigned long lost_ticks_system = 0;
1076 static inline void update_times(void)
1078 unsigned long ticks;
1079 unsigned long flags;
1081 save_flags(flags);
1082 cli();
1084 ticks = lost_ticks;
1085 lost_ticks = 0;
1087 if (ticks) {
1088 unsigned long system;
1089 system = xchg(&lost_ticks_system, 0);
1091 calc_load(ticks);
1092 update_wall_time(ticks);
1093 restore_flags(flags);
1095 update_process_times(ticks, system);
1097 } else
1098 restore_flags(flags);
1101 static void timer_bh(void)
1103 update_times();
1104 run_old_timers();
1105 run_timer_list();
1108 void do_timer(struct pt_regs * regs)
1110 (*(unsigned long *)&jiffies)++;
1111 lost_ticks++;
1112 mark_bh(TIMER_BH);
1113 if (!user_mode(regs))
1114 lost_ticks_system++;
1115 if (tq_timer)
1116 mark_bh(TQUEUE_BH);
1119 #ifndef __alpha__
1122 * For backwards compatibility? This can be done in libc so Alpha
1123 * and all newer ports shouldn't need it.
1125 asmlinkage unsigned int sys_alarm(unsigned int seconds)
1127 struct itimerval it_new, it_old;
1128 unsigned int oldalarm;
1130 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
1131 it_new.it_value.tv_sec = seconds;
1132 it_new.it_value.tv_usec = 0;
1133 do_setitimer(ITIMER_REAL, &it_new, &it_old);
1134 oldalarm = it_old.it_value.tv_sec;
1135 /* ehhh.. We can't return 0 if we have an alarm pending.. */
1136 /* And we'd better return too much than too little anyway */
1137 if (it_old.it_value.tv_usec)
1138 oldalarm++;
1139 return oldalarm;
1143 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
1144 * should be moved into arch/i386 instead?
1147 asmlinkage int sys_getpid(void)
1149 /* This is SMP safe - current->pid doesn't change */
1150 return current->pid;
1154 * This is not strictly SMP safe: p_opptr could change
1155 * from under us. However, rather than getting any lock
1156 * we can use an optimistic algorithm: get the parent
1157 * pid, and go back and check that the parent is still
1158 * the same. If it has changed (which is extremely unlikely
1159 * indeed), we just try again..
1161 * NOTE! This depends on the fact that even if we _do_
1162 * get an old value of "parent", we can happily dereference
1163 * the pointer: we just can't necessarily trust the result
1164 * until we know that the parent pointer is valid.
1166 * The "mb()" macro is a memory barrier - a synchronizing
1167 * event. It also makes sure that gcc doesn't optimize
1168 * away the necessary memory references.. The barrier doesn't
1169 * have to have all that strong semantics: on x86 we don't
1170 * really require a synchronizing instruction, for example.
1171 * The barrier is more important for code generation than
1172 * for any real memory ordering semantics (even if there is
1173 * a small window for a race, using the old pointer is
1174 * harmless for a while).
1176 asmlinkage int sys_getppid(void)
1178 int pid;
1179 struct task_struct * me = current;
1180 struct task_struct * parent;
1182 parent = me->p_opptr;
1183 for (;;) {
1184 pid = parent->pid;
1185 #if __SMP__
1187 struct task_struct *old = parent;
1188 mb();
1189 parent = me->p_opptr;
1190 if (old != parent)
1191 continue;
1193 #endif
1194 break;
1196 return pid;
1199 asmlinkage int sys_getuid(void)
1201 /* Only we change this so SMP safe */
1202 return current->uid;
1205 asmlinkage int sys_geteuid(void)
1207 /* Only we change this so SMP safe */
1208 return current->euid;
1211 asmlinkage int sys_getgid(void)
1213 /* Only we change this so SMP safe */
1214 return current->gid;
1217 asmlinkage int sys_getegid(void)
1219 /* Only we change this so SMP safe */
1220 return current->egid;
1224 * This has been replaced by sys_setpriority. Maybe it should be
1225 * moved into the arch dependent tree for those ports that require
1226 * it for backward compatibility?
1229 asmlinkage int sys_nice(int increment)
1231 unsigned long newprio;
1232 int increase = 0;
1235 * Setpriority might change our priority at the same moment.
1236 * We don't have to worry. Conceptually one call occurs first
1237 * and we have a single winner.
1240 newprio = increment;
1241 if (increment < 0) {
1242 if (!capable(CAP_SYS_NICE))
1243 return -EPERM;
1244 newprio = -increment;
1245 increase = 1;
1248 if (newprio > 40)
1249 newprio = 40;
1251 * do a "normalization" of the priority (traditionally
1252 * Unix nice values are -20 to 20; Linux doesn't really
1253 * use that kind of thing, but uses the length of the
1254 * timeslice instead (default 150 ms). The rounding is
1255 * why we want to avoid negative values.
1257 newprio = (newprio * DEF_PRIORITY + 10) / 20;
1258 increment = newprio;
1259 if (increase)
1260 increment = -increment;
1262 * Current->priority can change between this point
1263 * and the assignment. We are assigning not doing add/subs
1264 * so thats ok. Conceptually a process might just instantaneously
1265 * read the value we stomp over. I don't think that is an issue
1266 * unless posix makes it one. If so we can loop on changes
1267 * to current->priority.
1269 newprio = current->priority - increment;
1270 if ((signed) newprio < 1)
1271 newprio = 1;
1272 if (newprio > DEF_PRIORITY*2)
1273 newprio = DEF_PRIORITY*2;
1274 current->priority = newprio;
1275 return 0;
1278 #endif
1280 static inline struct task_struct *find_process_by_pid(pid_t pid)
1282 struct task_struct *tsk = current;
1284 if (pid)
1285 tsk = find_task_by_pid(pid);
1286 return tsk;
1289 static int setscheduler(pid_t pid, int policy,
1290 struct sched_param *param)
1292 struct sched_param lp;
1293 struct task_struct *p;
1294 int retval;
1296 retval = -EINVAL;
1297 if (!param || pid < 0)
1298 goto out_nounlock;
1300 retval = -EFAULT;
1301 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
1302 goto out_nounlock;
1305 * We play safe to avoid deadlocks.
1307 spin_lock_irq(&scheduler_lock);
1308 spin_lock(&runqueue_lock);
1309 read_lock(&tasklist_lock);
1311 p = find_process_by_pid(pid);
1313 retval = -ESRCH;
1314 if (!p)
1315 goto out_unlock;
1317 if (policy < 0)
1318 policy = p->policy;
1319 else {
1320 retval = -EINVAL;
1321 if (policy != SCHED_FIFO && policy != SCHED_RR &&
1322 policy != SCHED_OTHER)
1323 goto out_unlock;
1327 * Valid priorities for SCHED_FIFO and SCHED_RR are 1..99, valid
1328 * priority for SCHED_OTHER is 0.
1330 retval = -EINVAL;
1331 if (lp.sched_priority < 0 || lp.sched_priority > 99)
1332 goto out_unlock;
1333 if ((policy == SCHED_OTHER) != (lp.sched_priority == 0))
1334 goto out_unlock;
1336 retval = -EPERM;
1337 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
1338 !capable(CAP_SYS_NICE))
1339 goto out_unlock;
1340 if ((current->euid != p->euid) && (current->euid != p->uid) &&
1341 !capable(CAP_SYS_NICE))
1342 goto out_unlock;
1344 retval = 0;
1345 p->policy = policy;
1346 p->rt_priority = lp.sched_priority;
1347 if (p->next_run)
1348 move_first_runqueue(p);
1350 need_resched = 1;
1352 out_unlock:
1353 read_unlock(&tasklist_lock);
1354 spin_unlock(&runqueue_lock);
1355 spin_unlock_irq(&scheduler_lock);
1357 out_nounlock:
1358 return retval;
1361 asmlinkage int sys_sched_setscheduler(pid_t pid, int policy,
1362 struct sched_param *param)
1364 return setscheduler(pid, policy, param);
1367 asmlinkage int sys_sched_setparam(pid_t pid, struct sched_param *param)
1369 return setscheduler(pid, -1, param);
1372 asmlinkage int sys_sched_getscheduler(pid_t pid)
1374 struct task_struct *p;
1375 int retval;
1377 retval = -EINVAL;
1378 if (pid < 0)
1379 goto out_nounlock;
1381 read_lock(&tasklist_lock);
1383 retval = -ESRCH;
1384 p = find_process_by_pid(pid);
1385 if (!p)
1386 goto out_unlock;
1388 retval = p->policy;
1390 out_unlock:
1391 read_unlock(&tasklist_lock);
1393 out_nounlock:
1394 return retval;
1397 asmlinkage int sys_sched_getparam(pid_t pid, struct sched_param *param)
1399 struct task_struct *p;
1400 struct sched_param lp;
1401 int retval;
1403 retval = -EINVAL;
1404 if (!param || pid < 0)
1405 goto out_nounlock;
1407 read_lock(&tasklist_lock);
1408 p = find_process_by_pid(pid);
1409 retval = -ESRCH;
1410 if (!p)
1411 goto out_unlock;
1412 lp.sched_priority = p->rt_priority;
1413 read_unlock(&tasklist_lock);
1416 * This one might sleep, we cannot do it with a spinlock held ...
1418 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
1420 out_nounlock:
1421 return retval;
1423 out_unlock:
1424 read_unlock(&tasklist_lock);
1425 return retval;
1428 asmlinkage int sys_sched_yield(void)
1430 spin_lock(&scheduler_lock);
1431 spin_lock_irq(&runqueue_lock);
1432 current->policy |= SCHED_YIELD;
1433 move_last_runqueue(current);
1434 spin_unlock_irq(&runqueue_lock);
1435 spin_unlock(&scheduler_lock);
1436 need_resched = 1;
1437 return 0;
1440 asmlinkage int sys_sched_get_priority_max(int policy)
1442 int ret = -EINVAL;
1444 switch (policy) {
1445 case SCHED_FIFO:
1446 case SCHED_RR:
1447 ret = 99;
1448 break;
1449 case SCHED_OTHER:
1450 ret = 0;
1451 break;
1453 return ret;
1456 asmlinkage int sys_sched_get_priority_min(int policy)
1458 int ret = -EINVAL;
1460 switch (policy) {
1461 case SCHED_FIFO:
1462 case SCHED_RR:
1463 ret = 1;
1464 break;
1465 case SCHED_OTHER:
1466 ret = 0;
1468 return ret;
1471 asmlinkage int sys_sched_rr_get_interval(pid_t pid, struct timespec *interval)
1473 struct timespec t;
1475 t.tv_sec = 0;
1476 t.tv_nsec = 150000;
1477 if (copy_to_user(interval, &t, sizeof(struct timespec)))
1478 return -EFAULT;
1479 return 0;
1482 asmlinkage int sys_nanosleep(struct timespec *rqtp, struct timespec *rmtp)
1484 struct timespec t;
1485 unsigned long expire;
1487 if(copy_from_user(&t, rqtp, sizeof(struct timespec)))
1488 return -EFAULT;
1490 if (t.tv_nsec >= 1000000000L || t.tv_nsec < 0 || t.tv_sec < 0)
1491 return -EINVAL;
1494 if (t.tv_sec == 0 && t.tv_nsec <= 2000000L &&
1495 current->policy != SCHED_OTHER)
1498 * Short delay requests up to 2 ms will be handled with
1499 * high precision by a busy wait for all real-time processes.
1501 * Its important on SMP not to do this holding locks.
1503 udelay((t.tv_nsec + 999) / 1000);
1504 return 0;
1507 expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec) + jiffies;
1509 current->timeout = expire;
1510 current->state = TASK_INTERRUPTIBLE;
1511 schedule();
1513 if (expire > jiffies) {
1514 if (rmtp) {
1515 jiffies_to_timespec(expire - jiffies -
1516 (expire > jiffies + 1), &t);
1517 if (copy_to_user(rmtp, &t, sizeof(struct timespec)))
1518 return -EFAULT;
1520 return -EINTR;
1522 return 0;
1525 static void show_task(int nr,struct task_struct * p)
1527 unsigned long free = 0;
1528 static const char * stat_nam[] = { "R", "S", "D", "Z", "T", "W" };
1530 printk("%-8s %3d ", p->comm, (p == current) ? -nr : nr);
1531 if (((unsigned) p->state) < sizeof(stat_nam)/sizeof(char *))
1532 printk(stat_nam[p->state]);
1533 else
1534 printk(" ");
1535 #if (BITS_PER_LONG == 32)
1536 if (p == current)
1537 printk(" current ");
1538 else
1539 printk(" %08lX ", thread_saved_pc(&p->tss));
1540 #else
1541 if (p == current)
1542 printk(" current task ");
1543 else
1544 printk(" %016lx ", thread_saved_pc(&p->tss));
1545 #endif
1546 #if 0
1547 for (free = 1; free < PAGE_SIZE/sizeof(long) ; free++) {
1548 if (((unsigned long *)p->kernel_stack_page)[free])
1549 break;
1551 #endif
1552 printk("%5lu %5d %6d ", free*sizeof(long), p->pid, p->p_pptr->pid);
1553 if (p->p_cptr)
1554 printk("%5d ", p->p_cptr->pid);
1555 else
1556 printk(" ");
1557 if (p->p_ysptr)
1558 printk("%7d", p->p_ysptr->pid);
1559 else
1560 printk(" ");
1561 if (p->p_osptr)
1562 printk(" %5d\n", p->p_osptr->pid);
1563 else
1564 printk("\n");
1567 struct signal_queue *q;
1568 char s[sizeof(sigset_t)*2+1], b[sizeof(sigset_t)*2+1];
1570 render_sigset_t(&p->signal, s);
1571 render_sigset_t(&p->blocked, b);
1572 printk(" sig: %d %s %s :", signal_pending(p), s, b);
1573 for (q = p->sigqueue; q ; q = q->next)
1574 printk(" %d", q->info.si_signo);
1575 printk(" X\n");
1579 char * render_sigset_t(sigset_t *set, char *buffer)
1581 int i = _NSIG, x;
1582 do {
1583 i -= 4, x = 0;
1584 if (sigismember(set, i+1)) x |= 1;
1585 if (sigismember(set, i+2)) x |= 2;
1586 if (sigismember(set, i+3)) x |= 4;
1587 if (sigismember(set, i+4)) x |= 8;
1588 *buffer++ = (x < 10 ? '0' : 'a' - 10) + x;
1589 } while (i >= 4);
1590 *buffer = 0;
1591 return buffer;
1594 void show_state(void)
1596 struct task_struct *p;
1598 #if (BITS_PER_LONG == 32)
1599 printk("\n"
1600 " free sibling\n");
1601 printk(" task PC stack pid father child younger older\n");
1602 #else
1603 printk("\n"
1604 " free sibling\n");
1605 printk(" task PC stack pid father child younger older\n");
1606 #endif
1607 read_lock(&tasklist_lock);
1608 for_each_task(p)
1609 show_task((p->tarray_ptr - &task[0]),p);
1610 read_unlock(&tasklist_lock);
1613 __initfunc(void sched_init(void))
1616 * We have to do a little magic to get the first
1617 * process right in SMP mode.
1619 int cpu=hard_smp_processor_id();
1620 int nr = NR_TASKS;
1622 init_task.processor=cpu;
1624 /* Init task array free list and pidhash table. */
1625 while(--nr > 0)
1626 add_free_taskslot(&task[nr]);
1628 for(nr = 0; nr < PIDHASH_SZ; nr++)
1629 pidhash[nr] = NULL;
1631 init_bh(TIMER_BH, timer_bh);
1632 init_bh(TQUEUE_BH, tqueue_bh);
1633 init_bh(IMMEDIATE_BH, immediate_bh);