Import 2.3.1pre2
[davej-history.git] / kernel / sched.c
blob942c5a570384491fb4abd2fef71fe2fe3ae58f92
1 /*
2 * linux/kernel/sched.c
4 * Copyright (C) 1991, 1992 Linus Torvalds
6 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
7 * make semaphores SMP safe
8 * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better.
9 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
10 * "A Kernel Model for Precision Timekeeping" by Dave Mills
11 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * by Andrea Arcangeli
13 * 1998-12-24 Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
14 * serialize accesses to xtime/lost_ticks).
15 * Copyright (C) 1998 Andrea Arcangeli
16 * 1998-12-28 Implemented better SMP scheduling by Ingo Molnar
17 * 1999-03-10 Improved NTP compatibility by Ulrich Windl
21 * 'sched.c' is the main kernel file. It contains scheduling primitives
22 * (sleep_on, wakeup, schedule etc) as well as a number of simple system
23 * call functions (type getpid()), which just extract a field from
24 * current-task
27 #include <linux/mm.h>
28 #include <linux/kernel_stat.h>
29 #include <linux/fdreg.h>
30 #include <linux/delay.h>
31 #include <linux/interrupt.h>
32 #include <linux/smp_lock.h>
33 #include <linux/init.h>
35 #include <asm/io.h>
36 #include <asm/uaccess.h>
37 #include <asm/pgtable.h>
38 #include <asm/mmu_context.h>
39 #include <asm/semaphore-helper.h>
41 #include <linux/timex.h>
44 * kernel variables
47 unsigned securebits = SECUREBITS_DEFAULT; /* systemwide security settings */
49 long tick = (1000000 + HZ/2) / HZ; /* timer interrupt period */
51 /* The current time */
52 volatile struct timeval xtime __attribute__ ((aligned (16)));
54 /* Don't completely fail for HZ > 500. */
55 int tickadj = 500/HZ ? : 1; /* microsecs */
57 DECLARE_TASK_QUEUE(tq_timer);
58 DECLARE_TASK_QUEUE(tq_immediate);
59 DECLARE_TASK_QUEUE(tq_scheduler);
62 * phase-lock loop variables
64 /* TIME_ERROR prevents overwriting the CMOS clock */
65 int time_state = TIME_OK; /* clock synchronization status */
66 int time_status = STA_UNSYNC; /* clock status bits */
67 long time_offset = 0; /* time adjustment (us) */
68 long time_constant = 2; /* pll time constant */
69 long time_tolerance = MAXFREQ; /* frequency tolerance (ppm) */
70 long time_precision = 1; /* clock precision (us) */
71 long time_maxerror = NTP_PHASE_LIMIT; /* maximum error (us) */
72 long time_esterror = NTP_PHASE_LIMIT; /* estimated error (us) */
73 long time_phase = 0; /* phase offset (scaled us) */
74 long time_freq = ((1000000 + HZ/2) % HZ - HZ/2) << SHIFT_USEC; /* frequency offset (scaled ppm) */
75 long time_adj = 0; /* tick adjust (scaled 1 / HZ) */
76 long time_reftime = 0; /* time at last adjustment (s) */
78 long time_adjust = 0;
79 long time_adjust_step = 0;
81 unsigned long event = 0;
83 extern int do_setitimer(int, struct itimerval *, struct itimerval *);
84 unsigned int * prof_buffer = NULL;
85 unsigned long prof_len = 0;
86 unsigned long prof_shift = 0;
88 extern void mem_use(void);
90 unsigned long volatile jiffies=0;
93 * Init task must be ok at boot for the ix86 as we will check its signals
94 * via the SMP irq return path.
97 struct task_struct * task[NR_TASKS] = {&init_task, };
100 * We align per-CPU scheduling data on cacheline boundaries,
101 * to prevent cacheline ping-pong.
103 static union {
104 struct schedule_data {
105 struct task_struct * curr;
106 cycles_t last_schedule;
107 } schedule_data;
108 char __pad [SMP_CACHE_BYTES];
109 } aligned_data [NR_CPUS] __cacheline_aligned = { {{&init_task,0}}};
111 #define cpu_curr(cpu) aligned_data[(cpu)].schedule_data.curr
113 struct kernel_stat kstat = { 0 };
115 #ifdef __SMP__
117 #define idle_task(cpu) (task[cpu_number_map[(cpu)]])
118 #define can_schedule(p) (!(p)->has_cpu)
120 #else
122 #define idle_task(cpu) (&init_task)
123 #define can_schedule(p) (1)
125 #endif
127 void scheduling_functions_start_here(void) { }
130 * This is the function that decides how desirable a process is..
131 * You can weigh different processes against each other depending
132 * on what CPU they've run on lately etc to try to handle cache
133 * and TLB miss penalties.
135 * Return values:
136 * -1000: never select this
137 * 0: out of time, recalculate counters (but it might still be
138 * selected)
139 * +ve: "goodness" value (the larger, the better)
140 * +1000: realtime process, select this.
143 static inline int goodness (struct task_struct * prev,
144 struct task_struct * p, int this_cpu)
146 int weight;
149 * Realtime process, select the first one on the
150 * runqueue (taking priorities within processes
151 * into account).
153 if (p->policy != SCHED_OTHER) {
154 weight = 1000 + p->rt_priority;
155 goto out;
159 * Give the process a first-approximation goodness value
160 * according to the number of clock-ticks it has left.
162 * Don't do any other calculations if the time slice is
163 * over..
165 weight = p->counter;
166 if (!weight)
167 goto out;
169 #ifdef __SMP__
170 /* Give a largish advantage to the same processor... */
171 /* (this is equivalent to penalizing other processors) */
172 if (p->processor == this_cpu)
173 weight += PROC_CHANGE_PENALTY;
174 #endif
176 /* .. and a slight advantage to the current MM */
177 if (p->mm == prev->mm)
178 weight += 1;
179 weight += p->priority;
181 out:
182 return weight;
186 * subtle. We want to discard a yielded process only if it's being
187 * considered for a reschedule. Wakeup-time 'queries' of the scheduling
188 * state do not count. Another optimization we do: sched_yield()-ed
189 * processes are runnable (and thus will be considered for scheduling)
190 * right when they are calling schedule(). So the only place we need
191 * to care about SCHED_YIELD is when we calculate the previous process'
192 * goodness ...
194 static inline int prev_goodness (struct task_struct * prev,
195 struct task_struct * p, int this_cpu)
197 if (p->policy & SCHED_YIELD) {
198 p->policy &= ~SCHED_YIELD;
199 return 0;
201 return goodness(prev, p, this_cpu);
205 * the 'goodness value' of replacing a process on a given CPU.
206 * positive value means 'replace', zero or negative means 'dont'.
208 static inline int preemption_goodness (struct task_struct * prev,
209 struct task_struct * p, int cpu)
211 return goodness(prev, p, cpu) - goodness(prev, prev, cpu);
215 * If there is a dependency between p1 and p2,
216 * don't be too eager to go into the slow schedule.
217 * In particular, if p1 and p2 both want the kernel
218 * lock, there is no point in trying to make them
219 * extremely parallel..
221 * (No lock - lock_depth < 0)
223 * There are two additional metrics here:
225 * first, a 'cutoff' interval, currently 0-200 usecs on
226 * x86 CPUs, depending on the size of the 'SMP-local cache'.
227 * If the current process has longer average timeslices than
228 * this, then we utilize the idle CPU.
230 * second, if the wakeup comes from a process context,
231 * then the two processes are 'related'. (they form a
232 * 'gang')
234 * An idle CPU is almost always a bad thing, thus we skip
235 * the idle-CPU utilization only if both these conditions
236 * are true. (ie. a 'process-gang' rescheduling with rather
237 * high frequency should stay on the same CPU).
239 * [We can switch to something more finegrained in 2.3.]
241 * do not 'guess' if the to-be-scheduled task is RT.
243 #define related(p1,p2) (((p1)->lock_depth >= 0) && (p2)->lock_depth >= 0) && \
244 (((p2)->policy == SCHED_OTHER) && ((p1)->avg_slice < cacheflush_time))
246 static inline void reschedule_idle_slow(struct task_struct * p)
248 #ifdef __SMP__
250 * (see reschedule_idle() for an explanation first ...)
252 * Pass #2
254 * We try to find another (idle) CPU for this woken-up process.
256 * On SMP, we mostly try to see if the CPU the task used
257 * to run on is idle.. but we will use another idle CPU too,
258 * at this point we already know that this CPU is not
259 * willing to reschedule in the near future.
261 * An idle CPU is definitely wasted, especially if this CPU is
262 * running long-timeslice processes. The following algorithm is
263 * pretty good at finding the best idle CPU to send this process
264 * to.
266 * [We can try to preempt low-priority processes on other CPUs in
267 * 2.3. Also we can try to use the avg_slice value to predict
268 * 'likely reschedule' events even on other CPUs.]
270 int this_cpu = smp_processor_id(), target_cpu;
271 struct task_struct *tsk, *target_tsk;
272 int cpu, best_cpu, weight, best_weight, i;
273 unsigned long flags;
275 best_weight = 0; /* prevents negative weight */
277 spin_lock_irqsave(&runqueue_lock, flags);
280 * shortcut if the woken up task's last CPU is
281 * idle now.
283 best_cpu = p->processor;
284 target_tsk = idle_task(best_cpu);
285 if (cpu_curr(best_cpu) == target_tsk)
286 goto send_now;
288 target_tsk = NULL;
289 for (i = 0; i < smp_num_cpus; i++) {
290 cpu = cpu_logical_map(i);
291 tsk = cpu_curr(cpu);
292 if (related(tsk, p))
293 goto out_no_target;
294 weight = preemption_goodness(tsk, p, cpu);
295 if (weight > best_weight) {
296 best_weight = weight;
297 target_tsk = tsk;
302 * found any suitable CPU?
304 if (!target_tsk)
305 goto out_no_target;
307 send_now:
308 target_cpu = target_tsk->processor;
309 target_tsk->need_resched = 1;
310 spin_unlock_irqrestore(&runqueue_lock, flags);
312 * the APIC stuff can go outside of the lock because
313 * it uses no task information, only CPU#.
315 if (target_cpu != this_cpu)
316 smp_send_reschedule(target_cpu);
317 return;
318 out_no_target:
319 spin_unlock_irqrestore(&runqueue_lock, flags);
320 return;
321 #else /* UP */
322 int this_cpu = smp_processor_id();
323 struct task_struct *tsk;
325 tsk = cpu_curr(this_cpu);
326 if (preemption_goodness(tsk, p, this_cpu) > 0)
327 tsk->need_resched = 1;
328 #endif
331 static void reschedule_idle(struct task_struct * p)
333 #ifdef __SMP__
334 int cpu = smp_processor_id();
336 * ("wakeup()" should not be called before we've initialized
337 * SMP completely.
338 * Basically a not-yet initialized SMP subsystem can be
339 * considered as a not-yet working scheduler, simply dont use
340 * it before it's up and running ...)
342 * SMP rescheduling is done in 2 passes:
343 * - pass #1: faster: 'quick decisions'
344 * - pass #2: slower: 'lets try and find a suitable CPU'
348 * Pass #1. (subtle. We might be in the middle of __switch_to, so
349 * to preserve scheduling atomicity we have to use cpu_curr)
351 if ((p->processor == cpu) && related(cpu_curr(cpu), p))
352 return;
353 #endif /* __SMP__ */
355 * Pass #2
357 reschedule_idle_slow(p);
361 * Careful!
363 * This has to add the process to the _beginning_ of the
364 * run-queue, not the end. See the comment about "This is
365 * subtle" in the scheduler proper..
367 static inline void add_to_runqueue(struct task_struct * p)
369 struct task_struct *next = init_task.next_run;
371 p->prev_run = &init_task;
372 init_task.next_run = p;
373 p->next_run = next;
374 next->prev_run = p;
375 nr_running++;
378 static inline void del_from_runqueue(struct task_struct * p)
380 struct task_struct *next = p->next_run;
381 struct task_struct *prev = p->prev_run;
383 nr_running--;
384 next->prev_run = prev;
385 prev->next_run = next;
386 p->next_run = NULL;
387 p->prev_run = NULL;
390 static inline void move_last_runqueue(struct task_struct * p)
392 struct task_struct *next = p->next_run;
393 struct task_struct *prev = p->prev_run;
395 /* remove from list */
396 next->prev_run = prev;
397 prev->next_run = next;
398 /* add back to list */
399 p->next_run = &init_task;
400 prev = init_task.prev_run;
401 init_task.prev_run = p;
402 p->prev_run = prev;
403 prev->next_run = p;
406 static inline void move_first_runqueue(struct task_struct * p)
408 struct task_struct *next = p->next_run;
409 struct task_struct *prev = p->prev_run;
411 /* remove from list */
412 next->prev_run = prev;
413 prev->next_run = next;
414 /* add back to list */
415 p->prev_run = &init_task;
416 next = init_task.next_run;
417 init_task.next_run = p;
418 p->next_run = next;
419 next->prev_run = p;
423 * The tasklist_lock protects the linked list of processes.
425 * The scheduler lock is protecting against multiple entry
426 * into the scheduling code, and doesn't need to worry
427 * about interrupts (because interrupts cannot call the
428 * scheduler).
430 * The run-queue lock locks the parts that actually access
431 * and change the run-queues, and have to be interrupt-safe.
433 spinlock_t runqueue_lock = SPIN_LOCK_UNLOCKED; /* second */
434 rwlock_t tasklist_lock = RW_LOCK_UNLOCKED; /* third */
437 * Wake up a process. Put it on the run-queue if it's not
438 * already there. The "current" process is always on the
439 * run-queue (except when the actual re-schedule is in
440 * progress), and as such you're allowed to do the simpler
441 * "current->state = TASK_RUNNING" to mark yourself runnable
442 * without the overhead of this.
444 void wake_up_process(struct task_struct * p)
446 unsigned long flags;
449 * We want the common case fall through straight, thus the goto.
451 spin_lock_irqsave(&runqueue_lock, flags);
452 p->state = TASK_RUNNING;
453 if (p->next_run)
454 goto out;
455 add_to_runqueue(p);
456 spin_unlock_irqrestore(&runqueue_lock, flags);
458 reschedule_idle(p);
459 return;
460 out:
461 spin_unlock_irqrestore(&runqueue_lock, flags);
464 static void process_timeout(unsigned long __data)
466 struct task_struct * p = (struct task_struct *) __data;
468 wake_up_process(p);
472 * Event timer code
474 #define TVN_BITS 6
475 #define TVR_BITS 8
476 #define TVN_SIZE (1 << TVN_BITS)
477 #define TVR_SIZE (1 << TVR_BITS)
478 #define TVN_MASK (TVN_SIZE - 1)
479 #define TVR_MASK (TVR_SIZE - 1)
481 struct timer_vec {
482 int index;
483 struct timer_list *vec[TVN_SIZE];
486 struct timer_vec_root {
487 int index;
488 struct timer_list *vec[TVR_SIZE];
491 static struct timer_vec tv5 = { 0 };
492 static struct timer_vec tv4 = { 0 };
493 static struct timer_vec tv3 = { 0 };
494 static struct timer_vec tv2 = { 0 };
495 static struct timer_vec_root tv1 = { 0 };
497 static struct timer_vec * const tvecs[] = {
498 (struct timer_vec *)&tv1, &tv2, &tv3, &tv4, &tv5
501 #define NOOF_TVECS (sizeof(tvecs) / sizeof(tvecs[0]))
503 static unsigned long timer_jiffies = 0;
505 static inline void insert_timer(struct timer_list *timer,
506 struct timer_list **vec, int idx)
508 if ((timer->next = vec[idx]))
509 vec[idx]->prev = timer;
510 vec[idx] = timer;
511 timer->prev = (struct timer_list *)&vec[idx];
514 static inline void internal_add_timer(struct timer_list *timer)
517 * must be cli-ed when calling this
519 unsigned long expires = timer->expires;
520 unsigned long idx = expires - timer_jiffies;
522 if (idx < TVR_SIZE) {
523 int i = expires & TVR_MASK;
524 insert_timer(timer, tv1.vec, i);
525 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
526 int i = (expires >> TVR_BITS) & TVN_MASK;
527 insert_timer(timer, tv2.vec, i);
528 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
529 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
530 insert_timer(timer, tv3.vec, i);
531 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
532 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
533 insert_timer(timer, tv4.vec, i);
534 } else if ((signed long) idx < 0) {
535 /* can happen if you add a timer with expires == jiffies,
536 * or you set a timer to go off in the past
538 insert_timer(timer, tv1.vec, tv1.index);
539 } else if (idx <= 0xffffffffUL) {
540 int i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
541 insert_timer(timer, tv5.vec, i);
542 } else {
543 /* Can only get here on architectures with 64-bit jiffies */
544 timer->next = timer->prev = timer;
548 spinlock_t timerlist_lock = SPIN_LOCK_UNLOCKED;
550 void add_timer(struct timer_list *timer)
552 unsigned long flags;
554 spin_lock_irqsave(&timerlist_lock, flags);
555 if (timer->prev)
556 goto bug;
557 internal_add_timer(timer);
558 out:
559 spin_unlock_irqrestore(&timerlist_lock, flags);
560 return;
562 bug:
563 printk("bug: kernel timer added twice at %p.\n",
564 __builtin_return_address(0));
565 goto out;
568 static inline int detach_timer(struct timer_list *timer)
570 struct timer_list *prev = timer->prev;
571 if (prev) {
572 struct timer_list *next = timer->next;
573 prev->next = next;
574 if (next)
575 next->prev = prev;
576 return 1;
578 return 0;
581 void mod_timer(struct timer_list *timer, unsigned long expires)
583 unsigned long flags;
585 spin_lock_irqsave(&timerlist_lock, flags);
586 timer->expires = expires;
587 detach_timer(timer);
588 internal_add_timer(timer);
589 spin_unlock_irqrestore(&timerlist_lock, flags);
592 int del_timer(struct timer_list * timer)
594 int ret;
595 unsigned long flags;
597 spin_lock_irqsave(&timerlist_lock, flags);
598 ret = detach_timer(timer);
599 timer->next = timer->prev = 0;
600 spin_unlock_irqrestore(&timerlist_lock, flags);
601 return ret;
604 signed long schedule_timeout(signed long timeout)
606 struct timer_list timer;
607 unsigned long expire;
609 switch (timeout)
611 case MAX_SCHEDULE_TIMEOUT:
613 * These two special cases are useful to be comfortable
614 * in the caller. Nothing more. We could take
615 * MAX_SCHEDULE_TIMEOUT from one of the negative value
616 * but I' d like to return a valid offset (>=0) to allow
617 * the caller to do everything it want with the retval.
619 schedule();
620 goto out;
621 default:
623 * Another bit of PARANOID. Note that the retval will be
624 * 0 since no piece of kernel is supposed to do a check
625 * for a negative retval of schedule_timeout() (since it
626 * should never happens anyway). You just have the printk()
627 * that will tell you if something is gone wrong and where.
629 if (timeout < 0)
631 printk(KERN_ERR "schedule_timeout: wrong timeout "
632 "value %lx from %p\n", timeout,
633 __builtin_return_address(0));
634 goto out;
638 expire = timeout + jiffies;
640 init_timer(&timer);
641 timer.expires = expire;
642 timer.data = (unsigned long) current;
643 timer.function = process_timeout;
645 add_timer(&timer);
646 schedule();
647 del_timer(&timer);
649 timeout = expire - jiffies;
651 out:
652 return timeout < 0 ? 0 : timeout;
656 * schedule_tail() is getting called from the fork return path. This
657 * cleans up all remaining scheduler things, without impacting the
658 * common case.
660 static inline void __schedule_tail (struct task_struct *prev)
662 #ifdef __SMP__
663 if ((prev->state == TASK_RUNNING) &&
664 (prev != idle_task(smp_processor_id())))
665 reschedule_idle(prev);
666 wmb();
667 prev->has_cpu = 0;
668 #endif /* __SMP__ */
671 void schedule_tail (struct task_struct *prev)
673 __schedule_tail(prev);
677 * 'schedule()' is the scheduler function. It's a very simple and nice
678 * scheduler: it's not perfect, but certainly works for most things.
680 * The goto is "interesting".
682 * NOTE!! Task 0 is the 'idle' task, which gets called when no other
683 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
684 * information in task[0] is never used.
686 asmlinkage void schedule(void)
688 struct schedule_data * sched_data;
689 struct task_struct *prev, *next, *p;
690 int this_cpu, c;
692 if (tq_scheduler)
693 goto handle_tq_scheduler;
694 tq_scheduler_back:
696 prev = current;
697 this_cpu = prev->processor;
699 if (in_interrupt())
700 goto scheduling_in_interrupt;
702 release_kernel_lock(prev, this_cpu);
704 /* Do "administrative" work here while we don't hold any locks */
705 if (bh_mask & bh_active)
706 goto handle_bh;
707 handle_bh_back:
710 * 'sched_data' is protected by the fact that we can run
711 * only one process per CPU.
713 sched_data = & aligned_data[this_cpu].schedule_data;
715 spin_lock_irq(&runqueue_lock);
717 /* move an exhausted RR process to be last.. */
718 if (prev->policy == SCHED_RR)
719 goto move_rr_last;
720 move_rr_back:
722 switch (prev->state) {
723 case TASK_INTERRUPTIBLE:
724 if (signal_pending(prev)) {
725 prev->state = TASK_RUNNING;
726 break;
728 default:
729 del_from_runqueue(prev);
730 case TASK_RUNNING:
732 prev->need_resched = 0;
734 repeat_schedule:
737 * this is the scheduler proper:
740 p = init_task.next_run;
741 /* Default process to select.. */
742 next = idle_task(this_cpu);
743 c = -1000;
744 if (prev->state == TASK_RUNNING)
745 goto still_running;
746 still_running_back:
749 * This is subtle.
750 * Note how we can enable interrupts here, even
751 * though interrupts can add processes to the run-
752 * queue. This is because any new processes will
753 * be added to the front of the queue, so "p" above
754 * is a safe starting point.
755 * run-queue deletion and re-ordering is protected by
756 * the scheduler lock
759 * Note! there may appear new tasks on the run-queue during this, as
760 * interrupts are enabled. However, they will be put on front of the
761 * list, so our list starting at "p" is essentially fixed.
763 while (p != &init_task) {
764 if (can_schedule(p)) {
765 int weight = goodness(prev, p, this_cpu);
766 if (weight > c)
767 c = weight, next = p;
769 p = p->next_run;
772 /* Do we need to re-calculate counters? */
773 if (!c)
774 goto recalculate;
776 * from this point on nothing can prevent us from
777 * switching to the next task, save this fact in
778 * sched_data.
780 sched_data->curr = next;
781 #ifdef __SMP__
782 next->has_cpu = 1;
783 next->processor = this_cpu;
784 #endif
785 spin_unlock_irq(&runqueue_lock);
787 if (prev == next)
788 goto same_process;
790 #ifdef __SMP__
792 * maintain the per-process 'average timeslice' value.
793 * (this has to be recalculated even if we reschedule to
794 * the same process) Currently this is only used on SMP,
795 * and it's approximate, so we do not have to maintain
796 * it while holding the runqueue spinlock.
799 cycles_t t, this_slice;
801 t = get_cycles();
802 this_slice = t - sched_data->last_schedule;
803 sched_data->last_schedule = t;
806 * Exponentially fading average calculation, with
807 * some weight so it doesnt get fooled easily by
808 * smaller irregularities.
810 prev->avg_slice = (this_slice*1 + prev->avg_slice*1)/2;
814 * We drop the scheduler lock early (it's a global spinlock),
815 * thus we have to lock the previous process from getting
816 * rescheduled during switch_to().
819 #endif /* __SMP__ */
821 kstat.context_swtch++;
822 get_mmu_context(next);
823 switch_to(prev, next, prev);
824 __schedule_tail(prev);
826 same_process:
828 reacquire_kernel_lock(current);
829 return;
831 recalculate:
833 struct task_struct *p;
834 spin_unlock_irq(&runqueue_lock);
835 read_lock(&tasklist_lock);
836 for_each_task(p)
837 p->counter = (p->counter >> 1) + p->priority;
838 read_unlock(&tasklist_lock);
839 spin_lock_irq(&runqueue_lock);
840 goto repeat_schedule;
843 still_running:
844 c = prev_goodness(prev, prev, this_cpu);
845 next = prev;
846 goto still_running_back;
848 handle_bh:
849 do_bottom_half();
850 goto handle_bh_back;
852 handle_tq_scheduler:
853 run_task_queue(&tq_scheduler);
854 goto tq_scheduler_back;
856 move_rr_last:
857 if (!prev->counter) {
858 prev->counter = prev->priority;
859 move_last_runqueue(prev);
861 goto move_rr_back;
863 scheduling_in_interrupt:
864 printk("Scheduling in interrupt\n");
865 *(int *)0 = 0;
866 return;
869 void __wake_up(wait_queue_head_t *q, unsigned int mode)
871 struct list_head *tmp, *head;
872 struct task_struct *p;
873 unsigned long flags;
875 if (!q)
876 goto out;
878 wq_write_lock_irqsave(&q->lock, flags);
880 #if WAITQUEUE_DEBUG
881 CHECK_MAGIC_WQHEAD(q);
882 #endif
884 head = &q->task_list;
885 #if WAITQUEUE_DEBUG
886 if (!head->next || !head->prev)
887 WQ_BUG();
888 #endif
889 tmp = head->next;
890 while (tmp != head) {
891 wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
893 tmp = tmp->next;
895 #if WAITQUEUE_DEBUG
896 CHECK_MAGIC(curr->__magic);
897 #endif
898 p = curr->task;
899 if (p->state & mode) {
900 if (p->state & TASK_EXCLUSIVE) {
901 __remove_wait_queue(q, curr);
902 wq_write_unlock_irqrestore(&q->lock, flags);
904 curr->task_list.next = NULL;
905 curr->__waker = 0;
906 wake_up_process(p);
907 goto out;
909 #if WAITQUEUE_DEBUG
910 curr->__waker = (int)__builtin_return_address(0);
911 #endif
912 wake_up_process(p);
914 if (p->state & TASK_EXCLUSIVE)
915 break;
917 wq_write_unlock_irqrestore(&q->lock, flags);
918 out:
919 return;
923 * Semaphores are implemented using a two-way counter:
924 * The "count" variable is decremented for each process
925 * that tries to sleep, while the "waking" variable is
926 * incremented when the "up()" code goes to wake up waiting
927 * processes.
929 * Notably, the inline "up()" and "down()" functions can
930 * efficiently test if they need to do any extra work (up
931 * needs to do something only if count was negative before
932 * the increment operation.
934 * waking_non_zero() (from asm/semaphore.h) must execute
935 * atomically.
937 * When __up() is called, the count was negative before
938 * incrementing it, and we need to wake up somebody.
940 * This routine adds one to the count of processes that need to
941 * wake up and exit. ALL waiting processes actually wake up but
942 * only the one that gets to the "waking" field first will gate
943 * through and acquire the semaphore. The others will go back
944 * to sleep.
946 * Note that these functions are only called when there is
947 * contention on the lock, and as such all this is the
948 * "non-critical" part of the whole semaphore business. The
949 * critical part is the inline stuff in <asm/semaphore.h>
950 * where we want to avoid any extra jumps and calls.
952 void __up(struct semaphore *sem)
954 wake_one_more(sem);
955 wake_up(&sem->wait);
959 * Perform the "down" function. Return zero for semaphore acquired,
960 * return negative for signalled out of the function.
962 * If called from __down, the return is ignored and the wait loop is
963 * not interruptible. This means that a task waiting on a semaphore
964 * using "down()" cannot be killed until someone does an "up()" on
965 * the semaphore.
967 * If called from __down_interruptible, the return value gets checked
968 * upon return. If the return value is negative then the task continues
969 * with the negative value in the return register (it can be tested by
970 * the caller).
972 * Either form may be used in conjunction with "up()".
976 #define DOWN_VAR \
977 struct task_struct *tsk = current; \
978 wait_queue_t wait; \
979 init_waitqueue_entry(&wait, tsk);
981 #define DOWN_HEAD(task_state) \
984 tsk->state = (task_state); \
985 add_wait_queue(&sem->wait, &wait); \
987 /* \
988 * Ok, we're set up. sem->count is known to be less than zero \
989 * so we must wait. \
991 * We can let go the lock for purposes of waiting. \
992 * We re-acquire it after awaking so as to protect \
993 * all semaphore operations. \
995 * If "up()" is called before we call waking_non_zero() then \
996 * we will catch it right away. If it is called later then \
997 * we will have to go through a wakeup cycle to catch it. \
999 * Multiple waiters contend for the semaphore lock to see \
1000 * who gets to gate through and who has to wait some more. \
1001 */ \
1002 for (;;) {
1004 #define DOWN_TAIL(task_state) \
1005 tsk->state = (task_state); \
1007 tsk->state = TASK_RUNNING; \
1008 remove_wait_queue(&sem->wait, &wait);
1010 void __down(struct semaphore * sem)
1012 DOWN_VAR
1013 DOWN_HEAD(TASK_UNINTERRUPTIBLE)
1014 if (waking_non_zero(sem))
1015 break;
1016 schedule();
1017 DOWN_TAIL(TASK_UNINTERRUPTIBLE)
1020 int __down_interruptible(struct semaphore * sem)
1022 int ret = 0;
1023 DOWN_VAR
1024 DOWN_HEAD(TASK_INTERRUPTIBLE)
1026 ret = waking_non_zero_interruptible(sem, tsk);
1027 if (ret)
1029 if (ret == 1)
1030 /* ret != 0 only if we get interrupted -arca */
1031 ret = 0;
1032 break;
1034 schedule();
1035 DOWN_TAIL(TASK_INTERRUPTIBLE)
1036 return ret;
1039 int __down_trylock(struct semaphore * sem)
1041 return waking_non_zero_trylock(sem);
1044 #define SLEEP_ON_VAR \
1045 unsigned long flags; \
1046 wait_queue_t wait; \
1047 init_waitqueue_entry(&wait, current);
1049 #define SLEEP_ON_HEAD \
1050 wq_write_lock_irqsave(&q->lock,flags); \
1051 __add_wait_queue(q, &wait); \
1052 wq_write_unlock(&q->lock);
1054 #define SLEEP_ON_TAIL \
1055 wq_write_lock_irq(&q->lock); \
1056 __remove_wait_queue(q, &wait); \
1057 wq_write_unlock_irqrestore(&q->lock,flags);
1059 void interruptible_sleep_on(wait_queue_head_t *q)
1061 SLEEP_ON_VAR
1063 current->state = TASK_INTERRUPTIBLE;
1065 SLEEP_ON_HEAD
1066 schedule();
1067 SLEEP_ON_TAIL
1070 long interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
1072 SLEEP_ON_VAR
1074 current->state = TASK_INTERRUPTIBLE;
1076 SLEEP_ON_HEAD
1077 timeout = schedule_timeout(timeout);
1078 SLEEP_ON_TAIL
1080 return timeout;
1083 void sleep_on(wait_queue_head_t *q)
1085 SLEEP_ON_VAR
1087 current->state = TASK_UNINTERRUPTIBLE;
1089 SLEEP_ON_HEAD
1090 schedule();
1091 SLEEP_ON_TAIL
1094 long sleep_on_timeout(wait_queue_head_t *q, long timeout)
1096 SLEEP_ON_VAR
1098 current->state = TASK_UNINTERRUPTIBLE;
1100 SLEEP_ON_HEAD
1101 timeout = schedule_timeout(timeout);
1102 SLEEP_ON_TAIL
1104 return timeout;
1107 void scheduling_functions_end_here(void) { }
1109 static inline void cascade_timers(struct timer_vec *tv)
1111 /* cascade all the timers from tv up one level */
1112 struct timer_list *timer;
1113 timer = tv->vec[tv->index];
1115 * We are removing _all_ timers from the list, so we don't have to
1116 * detach them individually, just clear the list afterwards.
1118 while (timer) {
1119 struct timer_list *tmp = timer;
1120 timer = timer->next;
1121 internal_add_timer(tmp);
1123 tv->vec[tv->index] = NULL;
1124 tv->index = (tv->index + 1) & TVN_MASK;
1127 static inline void run_timer_list(void)
1129 spin_lock_irq(&timerlist_lock);
1130 while ((long)(jiffies - timer_jiffies) >= 0) {
1131 struct timer_list *timer;
1132 if (!tv1.index) {
1133 int n = 1;
1134 do {
1135 cascade_timers(tvecs[n]);
1136 } while (tvecs[n]->index == 1 && ++n < NOOF_TVECS);
1138 while ((timer = tv1.vec[tv1.index])) {
1139 void (*fn)(unsigned long) = timer->function;
1140 unsigned long data = timer->data;
1141 detach_timer(timer);
1142 timer->next = timer->prev = NULL;
1143 spin_unlock_irq(&timerlist_lock);
1144 fn(data);
1145 spin_lock_irq(&timerlist_lock);
1147 ++timer_jiffies;
1148 tv1.index = (tv1.index + 1) & TVR_MASK;
1150 spin_unlock_irq(&timerlist_lock);
1154 static inline void run_old_timers(void)
1156 struct timer_struct *tp;
1157 unsigned long mask;
1159 for (mask = 1, tp = timer_table+0 ; mask ; tp++,mask += mask) {
1160 if (mask > timer_active)
1161 break;
1162 if (!(mask & timer_active))
1163 continue;
1164 if (time_after(tp->expires, jiffies))
1165 continue;
1166 timer_active &= ~mask;
1167 tp->fn();
1168 sti();
1172 spinlock_t tqueue_lock;
1174 void tqueue_bh(void)
1176 run_task_queue(&tq_timer);
1179 void immediate_bh(void)
1181 run_task_queue(&tq_immediate);
1184 unsigned long timer_active = 0;
1185 struct timer_struct timer_table[32];
1188 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
1189 * imply that avenrun[] is the standard name for this kind of thing.
1190 * Nothing else seems to be standardized: the fractional size etc
1191 * all seem to differ on different machines.
1193 unsigned long avenrun[3] = { 0,0,0 };
1196 * Nr of active tasks - counted in fixed-point numbers
1198 static unsigned long count_active_tasks(void)
1200 struct task_struct *p;
1201 unsigned long nr = 0;
1203 read_lock(&tasklist_lock);
1204 for_each_task(p) {
1205 if ((p->state == TASK_RUNNING ||
1206 (p->state & TASK_UNINTERRUPTIBLE) ||
1207 (p->state & TASK_SWAPPING)))
1208 nr += FIXED_1;
1210 read_unlock(&tasklist_lock);
1211 return nr;
1214 static inline void calc_load(unsigned long ticks)
1216 unsigned long active_tasks; /* fixed-point */
1217 static int count = LOAD_FREQ;
1219 count -= ticks;
1220 if (count < 0) {
1221 count += LOAD_FREQ;
1222 active_tasks = count_active_tasks();
1223 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
1224 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
1225 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
1230 * this routine handles the overflow of the microsecond field
1232 * The tricky bits of code to handle the accurate clock support
1233 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
1234 * They were originally developed for SUN and DEC kernels.
1235 * All the kudos should go to Dave for this stuff.
1238 static void second_overflow(void)
1240 long ltemp;
1242 /* Bump the maxerror field */
1243 time_maxerror += time_tolerance >> SHIFT_USEC;
1244 if ( time_maxerror > NTP_PHASE_LIMIT ) {
1245 time_maxerror = NTP_PHASE_LIMIT;
1246 time_status |= STA_UNSYNC;
1250 * Leap second processing. If in leap-insert state at
1251 * the end of the day, the system clock is set back one
1252 * second; if in leap-delete state, the system clock is
1253 * set ahead one second. The microtime() routine or
1254 * external clock driver will insure that reported time
1255 * is always monotonic. The ugly divides should be
1256 * replaced.
1258 switch (time_state) {
1260 case TIME_OK:
1261 if (time_status & STA_INS)
1262 time_state = TIME_INS;
1263 else if (time_status & STA_DEL)
1264 time_state = TIME_DEL;
1265 break;
1267 case TIME_INS:
1268 if (xtime.tv_sec % 86400 == 0) {
1269 xtime.tv_sec--;
1270 time_state = TIME_OOP;
1271 printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
1273 break;
1275 case TIME_DEL:
1276 if ((xtime.tv_sec + 1) % 86400 == 0) {
1277 xtime.tv_sec++;
1278 time_state = TIME_WAIT;
1279 printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
1281 break;
1283 case TIME_OOP:
1284 time_state = TIME_WAIT;
1285 break;
1287 case TIME_WAIT:
1288 if (!(time_status & (STA_INS | STA_DEL)))
1289 time_state = TIME_OK;
1293 * Compute the phase adjustment for the next second. In
1294 * PLL mode, the offset is reduced by a fixed factor
1295 * times the time constant. In FLL mode the offset is
1296 * used directly. In either mode, the maximum phase
1297 * adjustment for each second is clamped so as to spread
1298 * the adjustment over not more than the number of
1299 * seconds between updates.
1301 if (time_offset < 0) {
1302 ltemp = -time_offset;
1303 if (!(time_status & STA_FLL))
1304 ltemp >>= SHIFT_KG + time_constant;
1305 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
1306 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
1307 time_offset += ltemp;
1308 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
1309 } else {
1310 ltemp = time_offset;
1311 if (!(time_status & STA_FLL))
1312 ltemp >>= SHIFT_KG + time_constant;
1313 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
1314 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
1315 time_offset -= ltemp;
1316 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
1320 * Compute the frequency estimate and additional phase
1321 * adjustment due to frequency error for the next
1322 * second. When the PPS signal is engaged, gnaw on the
1323 * watchdog counter and update the frequency computed by
1324 * the pll and the PPS signal.
1326 pps_valid++;
1327 if (pps_valid == PPS_VALID) { /* PPS signal lost */
1328 pps_jitter = MAXTIME;
1329 pps_stabil = MAXFREQ;
1330 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
1331 STA_PPSWANDER | STA_PPSERROR);
1333 ltemp = time_freq + pps_freq;
1334 if (ltemp < 0)
1335 time_adj -= -ltemp >>
1336 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
1337 else
1338 time_adj += ltemp >>
1339 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
1341 #if HZ == 100
1342 /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
1343 * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
1345 if (time_adj < 0)
1346 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
1347 else
1348 time_adj += (time_adj >> 2) + (time_adj >> 5);
1349 #endif
1352 /* in the NTP reference this is called "hardclock()" */
1353 static void update_wall_time_one_tick(void)
1355 if ( (time_adjust_step = time_adjust) != 0 ) {
1356 /* We are doing an adjtime thing.
1358 * Prepare time_adjust_step to be within bounds.
1359 * Note that a positive time_adjust means we want the clock
1360 * to run faster.
1362 * Limit the amount of the step to be in the range
1363 * -tickadj .. +tickadj
1365 if (time_adjust > tickadj)
1366 time_adjust_step = tickadj;
1367 else if (time_adjust < -tickadj)
1368 time_adjust_step = -tickadj;
1370 /* Reduce by this step the amount of time left */
1371 time_adjust -= time_adjust_step;
1373 xtime.tv_usec += tick + time_adjust_step;
1375 * Advance the phase, once it gets to one microsecond, then
1376 * advance the tick more.
1378 time_phase += time_adj;
1379 if (time_phase <= -FINEUSEC) {
1380 long ltemp = -time_phase >> SHIFT_SCALE;
1381 time_phase += ltemp << SHIFT_SCALE;
1382 xtime.tv_usec -= ltemp;
1384 else if (time_phase >= FINEUSEC) {
1385 long ltemp = time_phase >> SHIFT_SCALE;
1386 time_phase -= ltemp << SHIFT_SCALE;
1387 xtime.tv_usec += ltemp;
1392 * Using a loop looks inefficient, but "ticks" is
1393 * usually just one (we shouldn't be losing ticks,
1394 * we're doing this this way mainly for interrupt
1395 * latency reasons, not because we think we'll
1396 * have lots of lost timer ticks
1398 static void update_wall_time(unsigned long ticks)
1400 do {
1401 ticks--;
1402 update_wall_time_one_tick();
1403 } while (ticks);
1405 if (xtime.tv_usec >= 1000000) {
1406 xtime.tv_usec -= 1000000;
1407 xtime.tv_sec++;
1408 second_overflow();
1412 static inline void do_process_times(struct task_struct *p,
1413 unsigned long user, unsigned long system)
1415 long psecs;
1417 psecs = (p->times.tms_utime += user);
1418 psecs += (p->times.tms_stime += system);
1419 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
1420 /* Send SIGXCPU every second.. */
1421 if (!(psecs % HZ))
1422 send_sig(SIGXCPU, p, 1);
1423 /* and SIGKILL when we go over max.. */
1424 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
1425 send_sig(SIGKILL, p, 1);
1429 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
1431 unsigned long it_virt = p->it_virt_value;
1433 if (it_virt) {
1434 if (it_virt <= ticks) {
1435 it_virt = ticks + p->it_virt_incr;
1436 send_sig(SIGVTALRM, p, 1);
1438 p->it_virt_value = it_virt - ticks;
1442 static inline void do_it_prof(struct task_struct * p, unsigned long ticks)
1444 unsigned long it_prof = p->it_prof_value;
1446 if (it_prof) {
1447 if (it_prof <= ticks) {
1448 it_prof = ticks + p->it_prof_incr;
1449 send_sig(SIGPROF, p, 1);
1451 p->it_prof_value = it_prof - ticks;
1455 void update_one_process(struct task_struct *p,
1456 unsigned long ticks, unsigned long user, unsigned long system, int cpu)
1458 p->per_cpu_utime[cpu] += user;
1459 p->per_cpu_stime[cpu] += system;
1460 do_process_times(p, user, system);
1461 do_it_virt(p, user);
1462 do_it_prof(p, ticks);
1465 static void update_process_times(unsigned long ticks, unsigned long system)
1468 * SMP does this on a per-CPU basis elsewhere
1470 #ifndef __SMP__
1471 struct task_struct * p = current;
1472 unsigned long user = ticks - system;
1473 if (p->pid) {
1474 p->counter -= ticks;
1475 if (p->counter < 0) {
1476 p->counter = 0;
1477 p->need_resched = 1;
1479 if (p->priority < DEF_PRIORITY)
1480 kstat.cpu_nice += user;
1481 else
1482 kstat.cpu_user += user;
1483 kstat.cpu_system += system;
1485 update_one_process(p, ticks, user, system, 0);
1486 #endif
1489 volatile unsigned long lost_ticks = 0;
1490 static unsigned long lost_ticks_system = 0;
1493 * This spinlock protect us from races in SMP while playing with xtime. -arca
1495 rwlock_t xtime_lock = RW_LOCK_UNLOCKED;
1497 static inline void update_times(void)
1499 unsigned long ticks;
1502 * update_times() is run from the raw timer_bh handler so we
1503 * just know that the irqs are locally enabled and so we don't
1504 * need to save/restore the flags of the local CPU here. -arca
1506 write_lock_irq(&xtime_lock);
1508 ticks = lost_ticks;
1509 lost_ticks = 0;
1511 if (ticks) {
1512 unsigned long system;
1513 system = xchg(&lost_ticks_system, 0);
1515 calc_load(ticks);
1516 update_wall_time(ticks);
1517 write_unlock_irq(&xtime_lock);
1519 update_process_times(ticks, system);
1521 } else
1522 write_unlock_irq(&xtime_lock);
1525 static void timer_bh(void)
1527 update_times();
1528 run_old_timers();
1529 run_timer_list();
1532 void do_timer(struct pt_regs * regs)
1534 (*(unsigned long *)&jiffies)++;
1535 lost_ticks++;
1536 mark_bh(TIMER_BH);
1537 if (!user_mode(regs))
1538 lost_ticks_system++;
1539 if (tq_timer)
1540 mark_bh(TQUEUE_BH);
1543 #ifndef __alpha__
1546 * For backwards compatibility? This can be done in libc so Alpha
1547 * and all newer ports shouldn't need it.
1549 asmlinkage unsigned int sys_alarm(unsigned int seconds)
1551 struct itimerval it_new, it_old;
1552 unsigned int oldalarm;
1554 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
1555 it_new.it_value.tv_sec = seconds;
1556 it_new.it_value.tv_usec = 0;
1557 do_setitimer(ITIMER_REAL, &it_new, &it_old);
1558 oldalarm = it_old.it_value.tv_sec;
1559 /* ehhh.. We can't return 0 if we have an alarm pending.. */
1560 /* And we'd better return too much than too little anyway */
1561 if (it_old.it_value.tv_usec)
1562 oldalarm++;
1563 return oldalarm;
1567 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
1568 * should be moved into arch/i386 instead?
1571 asmlinkage int sys_getpid(void)
1573 /* This is SMP safe - current->pid doesn't change */
1574 return current->pid;
1578 * This is not strictly SMP safe: p_opptr could change
1579 * from under us. However, rather than getting any lock
1580 * we can use an optimistic algorithm: get the parent
1581 * pid, and go back and check that the parent is still
1582 * the same. If it has changed (which is extremely unlikely
1583 * indeed), we just try again..
1585 * NOTE! This depends on the fact that even if we _do_
1586 * get an old value of "parent", we can happily dereference
1587 * the pointer: we just can't necessarily trust the result
1588 * until we know that the parent pointer is valid.
1590 * The "mb()" macro is a memory barrier - a synchronizing
1591 * event. It also makes sure that gcc doesn't optimize
1592 * away the necessary memory references.. The barrier doesn't
1593 * have to have all that strong semantics: on x86 we don't
1594 * really require a synchronizing instruction, for example.
1595 * The barrier is more important for code generation than
1596 * for any real memory ordering semantics (even if there is
1597 * a small window for a race, using the old pointer is
1598 * harmless for a while).
1600 asmlinkage int sys_getppid(void)
1602 int pid;
1603 struct task_struct * me = current;
1604 struct task_struct * parent;
1606 parent = me->p_opptr;
1607 for (;;) {
1608 pid = parent->pid;
1609 #if __SMP__
1611 struct task_struct *old = parent;
1612 mb();
1613 parent = me->p_opptr;
1614 if (old != parent)
1615 continue;
1617 #endif
1618 break;
1620 return pid;
1623 asmlinkage int sys_getuid(void)
1625 /* Only we change this so SMP safe */
1626 return current->uid;
1629 asmlinkage int sys_geteuid(void)
1631 /* Only we change this so SMP safe */
1632 return current->euid;
1635 asmlinkage int sys_getgid(void)
1637 /* Only we change this so SMP safe */
1638 return current->gid;
1641 asmlinkage int sys_getegid(void)
1643 /* Only we change this so SMP safe */
1644 return current->egid;
1648 * This has been replaced by sys_setpriority. Maybe it should be
1649 * moved into the arch dependent tree for those ports that require
1650 * it for backward compatibility?
1653 asmlinkage int sys_nice(int increment)
1655 unsigned long newprio;
1656 int increase = 0;
1659 * Setpriority might change our priority at the same moment.
1660 * We don't have to worry. Conceptually one call occurs first
1661 * and we have a single winner.
1664 newprio = increment;
1665 if (increment < 0) {
1666 if (!capable(CAP_SYS_NICE))
1667 return -EPERM;
1668 newprio = -increment;
1669 increase = 1;
1672 if (newprio > 40)
1673 newprio = 40;
1675 * do a "normalization" of the priority (traditionally
1676 * Unix nice values are -20 to 20; Linux doesn't really
1677 * use that kind of thing, but uses the length of the
1678 * timeslice instead (default 210 ms). The rounding is
1679 * why we want to avoid negative values.
1681 newprio = (newprio * DEF_PRIORITY + 10) / 20;
1682 increment = newprio;
1683 if (increase)
1684 increment = -increment;
1686 * Current->priority can change between this point
1687 * and the assignment. We are assigning not doing add/subs
1688 * so thats ok. Conceptually a process might just instantaneously
1689 * read the value we stomp over. I don't think that is an issue
1690 * unless posix makes it one. If so we can loop on changes
1691 * to current->priority.
1693 newprio = current->priority - increment;
1694 if ((signed) newprio < 1)
1695 newprio = 1;
1696 if (newprio > DEF_PRIORITY*2)
1697 newprio = DEF_PRIORITY*2;
1698 current->priority = newprio;
1699 return 0;
1702 #endif
1704 static inline struct task_struct *find_process_by_pid(pid_t pid)
1706 struct task_struct *tsk = current;
1708 if (pid)
1709 tsk = find_task_by_pid(pid);
1710 return tsk;
1713 static int setscheduler(pid_t pid, int policy,
1714 struct sched_param *param)
1716 struct sched_param lp;
1717 struct task_struct *p;
1718 int retval;
1720 retval = -EINVAL;
1721 if (!param || pid < 0)
1722 goto out_nounlock;
1724 retval = -EFAULT;
1725 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
1726 goto out_nounlock;
1729 * We play safe to avoid deadlocks.
1731 spin_lock_irq(&runqueue_lock);
1732 read_lock(&tasklist_lock);
1734 p = find_process_by_pid(pid);
1736 retval = -ESRCH;
1737 if (!p)
1738 goto out_unlock;
1740 if (policy < 0)
1741 policy = p->policy;
1742 else {
1743 retval = -EINVAL;
1744 if (policy != SCHED_FIFO && policy != SCHED_RR &&
1745 policy != SCHED_OTHER)
1746 goto out_unlock;
1750 * Valid priorities for SCHED_FIFO and SCHED_RR are 1..99, valid
1751 * priority for SCHED_OTHER is 0.
1753 retval = -EINVAL;
1754 if (lp.sched_priority < 0 || lp.sched_priority > 99)
1755 goto out_unlock;
1756 if ((policy == SCHED_OTHER) != (lp.sched_priority == 0))
1757 goto out_unlock;
1759 retval = -EPERM;
1760 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
1761 !capable(CAP_SYS_NICE))
1762 goto out_unlock;
1763 if ((current->euid != p->euid) && (current->euid != p->uid) &&
1764 !capable(CAP_SYS_NICE))
1765 goto out_unlock;
1767 retval = 0;
1768 p->policy = policy;
1769 p->rt_priority = lp.sched_priority;
1770 if (p->next_run)
1771 move_first_runqueue(p);
1773 current->need_resched = 1;
1775 out_unlock:
1776 read_unlock(&tasklist_lock);
1777 spin_unlock_irq(&runqueue_lock);
1779 out_nounlock:
1780 return retval;
1783 asmlinkage int sys_sched_setscheduler(pid_t pid, int policy,
1784 struct sched_param *param)
1786 return setscheduler(pid, policy, param);
1789 asmlinkage int sys_sched_setparam(pid_t pid, struct sched_param *param)
1791 return setscheduler(pid, -1, param);
1794 asmlinkage int sys_sched_getscheduler(pid_t pid)
1796 struct task_struct *p;
1797 int retval;
1799 retval = -EINVAL;
1800 if (pid < 0)
1801 goto out_nounlock;
1803 read_lock(&tasklist_lock);
1805 retval = -ESRCH;
1806 p = find_process_by_pid(pid);
1807 if (!p)
1808 goto out_unlock;
1810 retval = p->policy;
1812 out_unlock:
1813 read_unlock(&tasklist_lock);
1815 out_nounlock:
1816 return retval;
1819 asmlinkage int sys_sched_getparam(pid_t pid, struct sched_param *param)
1821 struct task_struct *p;
1822 struct sched_param lp;
1823 int retval;
1825 retval = -EINVAL;
1826 if (!param || pid < 0)
1827 goto out_nounlock;
1829 read_lock(&tasklist_lock);
1830 p = find_process_by_pid(pid);
1831 retval = -ESRCH;
1832 if (!p)
1833 goto out_unlock;
1834 lp.sched_priority = p->rt_priority;
1835 read_unlock(&tasklist_lock);
1838 * This one might sleep, we cannot do it with a spinlock held ...
1840 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
1842 out_nounlock:
1843 return retval;
1845 out_unlock:
1846 read_unlock(&tasklist_lock);
1847 return retval;
1850 asmlinkage int sys_sched_yield(void)
1852 spin_lock_irq(&runqueue_lock);
1853 if (current->policy == SCHED_OTHER)
1854 current->policy |= SCHED_YIELD;
1855 current->need_resched = 1;
1856 move_last_runqueue(current);
1857 spin_unlock_irq(&runqueue_lock);
1858 return 0;
1861 asmlinkage int sys_sched_get_priority_max(int policy)
1863 int ret = -EINVAL;
1865 switch (policy) {
1866 case SCHED_FIFO:
1867 case SCHED_RR:
1868 ret = 99;
1869 break;
1870 case SCHED_OTHER:
1871 ret = 0;
1872 break;
1874 return ret;
1877 asmlinkage int sys_sched_get_priority_min(int policy)
1879 int ret = -EINVAL;
1881 switch (policy) {
1882 case SCHED_FIFO:
1883 case SCHED_RR:
1884 ret = 1;
1885 break;
1886 case SCHED_OTHER:
1887 ret = 0;
1889 return ret;
1892 asmlinkage int sys_sched_rr_get_interval(pid_t pid, struct timespec *interval)
1894 struct timespec t;
1896 t.tv_sec = 0;
1897 t.tv_nsec = 150000;
1898 if (copy_to_user(interval, &t, sizeof(struct timespec)))
1899 return -EFAULT;
1900 return 0;
1903 asmlinkage int sys_nanosleep(struct timespec *rqtp, struct timespec *rmtp)
1905 struct timespec t;
1906 unsigned long expire;
1908 if(copy_from_user(&t, rqtp, sizeof(struct timespec)))
1909 return -EFAULT;
1911 if (t.tv_nsec >= 1000000000L || t.tv_nsec < 0 || t.tv_sec < 0)
1912 return -EINVAL;
1915 if (t.tv_sec == 0 && t.tv_nsec <= 2000000L &&
1916 current->policy != SCHED_OTHER)
1919 * Short delay requests up to 2 ms will be handled with
1920 * high precision by a busy wait for all real-time processes.
1922 * Its important on SMP not to do this holding locks.
1924 udelay((t.tv_nsec + 999) / 1000);
1925 return 0;
1928 expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1930 current->state = TASK_INTERRUPTIBLE;
1931 expire = schedule_timeout(expire);
1933 if (expire) {
1934 if (rmtp) {
1935 jiffies_to_timespec(expire, &t);
1936 if (copy_to_user(rmtp, &t, sizeof(struct timespec)))
1937 return -EFAULT;
1939 return -EINTR;
1941 return 0;
1944 static void show_task(int nr,struct task_struct * p)
1946 unsigned long free = 0;
1947 int state;
1948 static const char * stat_nam[] = { "R", "S", "D", "Z", "T", "W" };
1950 printk("%-8s %3d ", p->comm, (p == current) ? -nr : nr);
1951 state = p->state ? ffz(~p->state) + 1 : 0;
1952 if (((unsigned) state) < sizeof(stat_nam)/sizeof(char *))
1953 printk(stat_nam[state]);
1954 else
1955 printk(" ");
1956 #if (BITS_PER_LONG == 32)
1957 if (p == current)
1958 printk(" current ");
1959 else
1960 printk(" %08lX ", thread_saved_pc(&p->tss));
1961 #else
1962 if (p == current)
1963 printk(" current task ");
1964 else
1965 printk(" %016lx ", thread_saved_pc(&p->tss));
1966 #endif
1968 unsigned long * n = (unsigned long *) (p+1);
1969 while (!*n)
1970 n++;
1971 free = (unsigned long) n - (unsigned long)(p+1);
1973 printk("%5lu %5d %6d ", free, p->pid, p->p_pptr->pid);
1974 if (p->p_cptr)
1975 printk("%5d ", p->p_cptr->pid);
1976 else
1977 printk(" ");
1978 if (p->p_ysptr)
1979 printk("%7d", p->p_ysptr->pid);
1980 else
1981 printk(" ");
1982 if (p->p_osptr)
1983 printk(" %5d\n", p->p_osptr->pid);
1984 else
1985 printk("\n");
1988 struct signal_queue *q;
1989 char s[sizeof(sigset_t)*2+1], b[sizeof(sigset_t)*2+1];
1991 render_sigset_t(&p->signal, s);
1992 render_sigset_t(&p->blocked, b);
1993 printk(" sig: %d %s %s :", signal_pending(p), s, b);
1994 for (q = p->sigqueue; q ; q = q->next)
1995 printk(" %d", q->info.si_signo);
1996 printk(" X\n");
2000 char * render_sigset_t(sigset_t *set, char *buffer)
2002 int i = _NSIG, x;
2003 do {
2004 i -= 4, x = 0;
2005 if (sigismember(set, i+1)) x |= 1;
2006 if (sigismember(set, i+2)) x |= 2;
2007 if (sigismember(set, i+3)) x |= 4;
2008 if (sigismember(set, i+4)) x |= 8;
2009 *buffer++ = (x < 10 ? '0' : 'a' - 10) + x;
2010 } while (i >= 4);
2011 *buffer = 0;
2012 return buffer;
2015 void show_state(void)
2017 struct task_struct *p;
2019 #if (BITS_PER_LONG == 32)
2020 printk("\n"
2021 " free sibling\n");
2022 printk(" task PC stack pid father child younger older\n");
2023 #else
2024 printk("\n"
2025 " free sibling\n");
2026 printk(" task PC stack pid father child younger older\n");
2027 #endif
2028 read_lock(&tasklist_lock);
2029 for_each_task(p)
2030 show_task((p->tarray_ptr - &task[0]),p);
2031 read_unlock(&tasklist_lock);
2034 void __init init_idle(void)
2036 cycles_t t;
2037 struct schedule_data * sched_data;
2038 sched_data = &aligned_data[smp_processor_id()].schedule_data;
2040 t = get_cycles();
2041 sched_data->curr = current;
2042 sched_data->last_schedule = t;
2045 void __init sched_init(void)
2048 * We have to do a little magic to get the first
2049 * process right in SMP mode.
2051 int cpu=hard_smp_processor_id();
2052 int nr = NR_TASKS;
2054 init_task.processor=cpu;
2056 /* Init task array free list and pidhash table. */
2057 while(--nr > 0)
2058 add_free_taskslot(&task[nr]);
2060 for(nr = 0; nr < PIDHASH_SZ; nr++)
2061 pidhash[nr] = NULL;
2063 init_bh(TIMER_BH, timer_bh);
2064 init_bh(TQUEUE_BH, tqueue_bh);
2065 init_bh(IMMEDIATE_BH, immediate_bh);