Import 2.3.12pre2
[davej-history.git] / kernel / sched.c
blobaed41e981afc1ecfb740570c119cdaa096ee79e8
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 * init_tasks[NR_CPUS] = {&init_task, };
100 * The tasklist_lock protects the linked list of processes.
102 * The scheduler lock is protecting against multiple entry
103 * into the scheduling code, and doesn't need to worry
104 * about interrupts (because interrupts cannot call the
105 * scheduler).
107 * The run-queue lock locks the parts that actually access
108 * and change the run-queues, and have to be interrupt-safe.
110 spinlock_t runqueue_lock = SPIN_LOCK_UNLOCKED; /* second */
111 rwlock_t tasklist_lock = RW_LOCK_UNLOCKED; /* third */
113 static LIST_HEAD(runqueue_head);
116 * We align per-CPU scheduling data on cacheline boundaries,
117 * to prevent cacheline ping-pong.
119 static union {
120 struct schedule_data {
121 struct task_struct * curr;
122 cycles_t last_schedule;
123 } schedule_data;
124 char __pad [SMP_CACHE_BYTES];
125 } aligned_data [NR_CPUS] __cacheline_aligned = { {{&init_task,0}}};
127 #define cpu_curr(cpu) aligned_data[(cpu)].schedule_data.curr
129 struct kernel_stat kstat = { 0 };
131 #ifdef __SMP__
133 #define idle_task(cpu) (init_tasks[cpu_number_map[(cpu)]])
134 #define can_schedule(p) (!(p)->has_cpu)
136 #else
138 #define idle_task(cpu) (&init_task)
139 #define can_schedule(p) (1)
141 #endif
143 void scheduling_functions_start_here(void) { }
146 * This is the function that decides how desirable a process is..
147 * You can weigh different processes against each other depending
148 * on what CPU they've run on lately etc to try to handle cache
149 * and TLB miss penalties.
151 * Return values:
152 * -1000: never select this
153 * 0: out of time, recalculate counters (but it might still be
154 * selected)
155 * +ve: "goodness" value (the larger, the better)
156 * +1000: realtime process, select this.
159 static inline int goodness(struct task_struct * p, int this_cpu, struct mm_struct *this_mm)
161 int weight;
164 * Realtime process, select the first one on the
165 * runqueue (taking priorities within processes
166 * into account).
168 if (p->policy != SCHED_OTHER) {
169 weight = 1000 + p->rt_priority;
170 goto out;
174 * Give the process a first-approximation goodness value
175 * according to the number of clock-ticks it has left.
177 * Don't do any other calculations if the time slice is
178 * over..
180 weight = p->counter;
181 if (!weight)
182 goto out;
184 #ifdef __SMP__
185 /* Give a largish advantage to the same processor... */
186 /* (this is equivalent to penalizing other processors) */
187 if (p->processor == this_cpu)
188 weight += PROC_CHANGE_PENALTY;
189 #endif
191 /* .. and a slight advantage to the current MM */
192 if (p->mm == this_mm)
193 weight += 1;
194 weight += p->priority;
196 out:
197 return weight;
201 * subtle. We want to discard a yielded process only if it's being
202 * considered for a reschedule. Wakeup-time 'queries' of the scheduling
203 * state do not count. Another optimization we do: sched_yield()-ed
204 * processes are runnable (and thus will be considered for scheduling)
205 * right when they are calling schedule(). So the only place we need
206 * to care about SCHED_YIELD is when we calculate the previous process'
207 * goodness ...
209 static inline int prev_goodness(struct task_struct * p, int this_cpu, struct mm_struct *this_mm)
211 if (p->policy & SCHED_YIELD) {
212 p->policy &= ~SCHED_YIELD;
213 return 0;
215 return goodness(p, this_cpu, this_mm);
219 * the 'goodness value' of replacing a process on a given CPU.
220 * positive value means 'replace', zero or negative means 'dont'.
222 static inline int preemption_goodness(struct task_struct * prev, struct task_struct * p, int cpu)
224 return goodness(p, cpu, prev->mm) - goodness(prev, cpu, prev->mm);
228 * If there is a dependency between p1 and p2,
229 * don't be too eager to go into the slow schedule.
230 * In particular, if p1 and p2 both want the kernel
231 * lock, there is no point in trying to make them
232 * extremely parallel..
234 * (No lock - lock_depth < 0)
236 * There are two additional metrics here:
238 * first, a 'cutoff' interval, currently 0-200 usecs on
239 * x86 CPUs, depending on the size of the 'SMP-local cache'.
240 * If the current process has longer average timeslices than
241 * this, then we utilize the idle CPU.
243 * second, if the wakeup comes from a process context,
244 * then the two processes are 'related'. (they form a
245 * 'gang')
247 * An idle CPU is almost always a bad thing, thus we skip
248 * the idle-CPU utilization only if both these conditions
249 * are true. (ie. a 'process-gang' rescheduling with rather
250 * high frequency should stay on the same CPU).
252 * [We can switch to something more finegrained in 2.3.]
254 * do not 'guess' if the to-be-scheduled task is RT.
256 #define related(p1,p2) (((p1)->lock_depth >= 0) && (p2)->lock_depth >= 0) && \
257 (((p2)->policy == SCHED_OTHER) && ((p1)->avg_slice < cacheflush_time))
259 static inline void reschedule_idle_slow(struct task_struct * p)
261 #ifdef __SMP__
263 * (see reschedule_idle() for an explanation first ...)
265 * Pass #2
267 * We try to find another (idle) CPU for this woken-up process.
269 * On SMP, we mostly try to see if the CPU the task used
270 * to run on is idle.. but we will use another idle CPU too,
271 * at this point we already know that this CPU is not
272 * willing to reschedule in the near future.
274 * An idle CPU is definitely wasted, especially if this CPU is
275 * running long-timeslice processes. The following algorithm is
276 * pretty good at finding the best idle CPU to send this process
277 * to.
279 * [We can try to preempt low-priority processes on other CPUs in
280 * 2.3. Also we can try to use the avg_slice value to predict
281 * 'likely reschedule' events even on other CPUs.]
283 int this_cpu = smp_processor_id(), target_cpu;
284 struct task_struct *tsk, *target_tsk;
285 int cpu, best_cpu, weight, best_weight, i;
286 unsigned long flags;
288 best_weight = 0; /* prevents negative weight */
290 spin_lock_irqsave(&runqueue_lock, flags);
293 * shortcut if the woken up task's last CPU is
294 * idle now.
296 best_cpu = p->processor;
297 target_tsk = idle_task(best_cpu);
298 if (cpu_curr(best_cpu) == target_tsk)
299 goto send_now;
301 target_tsk = NULL;
302 for (i = 0; i < smp_num_cpus; i++) {
303 cpu = cpu_logical_map(i);
304 tsk = cpu_curr(cpu);
305 if (related(tsk, p))
306 goto out_no_target;
307 weight = preemption_goodness(tsk, p, cpu);
308 if (weight > best_weight) {
309 best_weight = weight;
310 target_tsk = tsk;
315 * found any suitable CPU?
317 if (!target_tsk)
318 goto out_no_target;
320 send_now:
321 target_cpu = target_tsk->processor;
322 target_tsk->need_resched = 1;
323 spin_unlock_irqrestore(&runqueue_lock, flags);
325 * the APIC stuff can go outside of the lock because
326 * it uses no task information, only CPU#.
328 if (target_cpu != this_cpu)
329 smp_send_reschedule(target_cpu);
330 return;
331 out_no_target:
332 spin_unlock_irqrestore(&runqueue_lock, flags);
333 return;
334 #else /* UP */
335 int this_cpu = smp_processor_id();
336 struct task_struct *tsk;
338 tsk = cpu_curr(this_cpu);
339 if (preemption_goodness(tsk, p, this_cpu) > 0)
340 tsk->need_resched = 1;
341 #endif
344 static void reschedule_idle(struct task_struct * p)
346 #ifdef __SMP__
347 int cpu = smp_processor_id();
349 * ("wakeup()" should not be called before we've initialized
350 * SMP completely.
351 * Basically a not-yet initialized SMP subsystem can be
352 * considered as a not-yet working scheduler, simply dont use
353 * it before it's up and running ...)
355 * SMP rescheduling is done in 2 passes:
356 * - pass #1: faster: 'quick decisions'
357 * - pass #2: slower: 'lets try and find a suitable CPU'
361 * Pass #1. (subtle. We might be in the middle of __switch_to, so
362 * to preserve scheduling atomicity we have to use cpu_curr)
364 if ((p->processor == cpu) && related(cpu_curr(cpu), p))
365 return;
366 #endif /* __SMP__ */
368 * Pass #2
370 reschedule_idle_slow(p);
374 * Careful!
376 * This has to add the process to the _beginning_ of the
377 * run-queue, not the end. See the comment about "This is
378 * subtle" in the scheduler proper..
380 static inline void add_to_runqueue(struct task_struct * p)
382 list_add(&p->run_list, &runqueue_head);
383 nr_running++;
386 static inline void move_last_runqueue(struct task_struct * p)
388 list_del(&p->run_list);
389 list_add_tail(&p->run_list, &runqueue_head);
392 static inline void move_first_runqueue(struct task_struct * p)
394 list_del(&p->run_list);
395 list_add(&p->run_list, &runqueue_head);
399 * Wake up a process. Put it on the run-queue if it's not
400 * already there. The "current" process is always on the
401 * run-queue (except when the actual re-schedule is in
402 * progress), and as such you're allowed to do the simpler
403 * "current->state = TASK_RUNNING" to mark yourself runnable
404 * without the overhead of this.
406 void wake_up_process(struct task_struct * p)
408 unsigned long flags;
411 * We want the common case fall through straight, thus the goto.
413 spin_lock_irqsave(&runqueue_lock, flags);
414 p->state = TASK_RUNNING;
415 if (task_on_runqueue(p))
416 goto out;
417 add_to_runqueue(p);
418 spin_unlock_irqrestore(&runqueue_lock, flags);
420 reschedule_idle(p);
421 return;
422 out:
423 spin_unlock_irqrestore(&runqueue_lock, flags);
426 static void process_timeout(unsigned long __data)
428 struct task_struct * p = (struct task_struct *) __data;
430 wake_up_process(p);
434 * Event timer code
436 #define TVN_BITS 6
437 #define TVR_BITS 8
438 #define TVN_SIZE (1 << TVN_BITS)
439 #define TVR_SIZE (1 << TVR_BITS)
440 #define TVN_MASK (TVN_SIZE - 1)
441 #define TVR_MASK (TVR_SIZE - 1)
443 struct timer_vec {
444 int index;
445 struct timer_list *vec[TVN_SIZE];
448 struct timer_vec_root {
449 int index;
450 struct timer_list *vec[TVR_SIZE];
453 static struct timer_vec tv5 = { 0 };
454 static struct timer_vec tv4 = { 0 };
455 static struct timer_vec tv3 = { 0 };
456 static struct timer_vec tv2 = { 0 };
457 static struct timer_vec_root tv1 = { 0 };
459 static struct timer_vec * const tvecs[] = {
460 (struct timer_vec *)&tv1, &tv2, &tv3, &tv4, &tv5
463 #define NOOF_TVECS (sizeof(tvecs) / sizeof(tvecs[0]))
465 static unsigned long timer_jiffies = 0;
467 static inline void insert_timer(struct timer_list *timer,
468 struct timer_list **vec, int idx)
470 if ((timer->next = vec[idx]))
471 vec[idx]->prev = timer;
472 vec[idx] = timer;
473 timer->prev = (struct timer_list *)&vec[idx];
476 static inline void internal_add_timer(struct timer_list *timer)
479 * must be cli-ed when calling this
481 unsigned long expires = timer->expires;
482 unsigned long idx = expires - timer_jiffies;
484 if (idx < TVR_SIZE) {
485 int i = expires & TVR_MASK;
486 insert_timer(timer, tv1.vec, i);
487 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
488 int i = (expires >> TVR_BITS) & TVN_MASK;
489 insert_timer(timer, tv2.vec, i);
490 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
491 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
492 insert_timer(timer, tv3.vec, i);
493 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
494 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
495 insert_timer(timer, tv4.vec, i);
496 } else if ((signed long) idx < 0) {
497 /* can happen if you add a timer with expires == jiffies,
498 * or you set a timer to go off in the past
500 insert_timer(timer, tv1.vec, tv1.index);
501 } else if (idx <= 0xffffffffUL) {
502 int i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
503 insert_timer(timer, tv5.vec, i);
504 } else {
505 /* Can only get here on architectures with 64-bit jiffies */
506 timer->next = timer->prev = timer;
510 spinlock_t timerlist_lock = SPIN_LOCK_UNLOCKED;
512 void add_timer(struct timer_list *timer)
514 unsigned long flags;
516 spin_lock_irqsave(&timerlist_lock, flags);
517 if (timer->prev)
518 goto bug;
519 internal_add_timer(timer);
520 out:
521 spin_unlock_irqrestore(&timerlist_lock, flags);
522 return;
524 bug:
525 printk("bug: kernel timer added twice at %p.\n",
526 __builtin_return_address(0));
527 goto out;
530 static inline int detach_timer(struct timer_list *timer)
532 struct timer_list *prev = timer->prev;
533 if (prev) {
534 struct timer_list *next = timer->next;
535 prev->next = next;
536 if (next)
537 next->prev = prev;
538 return 1;
540 return 0;
543 void mod_timer(struct timer_list *timer, unsigned long expires)
545 unsigned long flags;
547 spin_lock_irqsave(&timerlist_lock, flags);
548 timer->expires = expires;
549 detach_timer(timer);
550 internal_add_timer(timer);
551 spin_unlock_irqrestore(&timerlist_lock, flags);
554 int del_timer(struct timer_list * timer)
556 int ret;
557 unsigned long flags;
559 spin_lock_irqsave(&timerlist_lock, flags);
560 ret = detach_timer(timer);
561 timer->next = timer->prev = 0;
562 spin_unlock_irqrestore(&timerlist_lock, flags);
563 return ret;
566 signed long schedule_timeout(signed long timeout)
568 struct timer_list timer;
569 unsigned long expire;
571 switch (timeout)
573 case MAX_SCHEDULE_TIMEOUT:
575 * These two special cases are useful to be comfortable
576 * in the caller. Nothing more. We could take
577 * MAX_SCHEDULE_TIMEOUT from one of the negative value
578 * but I' d like to return a valid offset (>=0) to allow
579 * the caller to do everything it want with the retval.
581 schedule();
582 goto out;
583 default:
585 * Another bit of PARANOID. Note that the retval will be
586 * 0 since no piece of kernel is supposed to do a check
587 * for a negative retval of schedule_timeout() (since it
588 * should never happens anyway). You just have the printk()
589 * that will tell you if something is gone wrong and where.
591 if (timeout < 0)
593 printk(KERN_ERR "schedule_timeout: wrong timeout "
594 "value %lx from %p\n", timeout,
595 __builtin_return_address(0));
596 goto out;
600 expire = timeout + jiffies;
602 init_timer(&timer);
603 timer.expires = expire;
604 timer.data = (unsigned long) current;
605 timer.function = process_timeout;
607 add_timer(&timer);
608 schedule();
609 del_timer(&timer);
611 timeout = expire - jiffies;
613 out:
614 return timeout < 0 ? 0 : timeout;
618 * schedule_tail() is getting called from the fork return path. This
619 * cleans up all remaining scheduler things, without impacting the
620 * common case.
622 static inline void __schedule_tail(struct task_struct *prev)
624 if (!current->active_mm) BUG();
626 if (!prev->mm) {
627 struct mm_struct *mm = prev->active_mm;
628 if (mm) {
629 prev->active_mm = NULL;
630 mmdrop(mm);
633 #ifdef __SMP__
634 if ((prev->state == TASK_RUNNING) &&
635 (prev != idle_task(smp_processor_id())))
636 reschedule_idle(prev);
637 wmb();
638 prev->has_cpu = 0;
639 #endif /* __SMP__ */
642 void schedule_tail(struct task_struct *prev)
644 __schedule_tail(prev);
648 * 'schedule()' is the scheduler function. It's a very simple and nice
649 * scheduler: it's not perfect, but certainly works for most things.
651 * The goto is "interesting".
653 * NOTE!! Task 0 is the 'idle' task, which gets called when no other
654 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
655 * information in task[0] is never used.
657 asmlinkage void schedule(void)
659 struct schedule_data * sched_data;
660 struct task_struct *prev, *next, *p;
661 struct list_head *tmp;
662 int this_cpu, c;
664 if (!current->active_mm) BUG();
665 if (tq_scheduler)
666 goto handle_tq_scheduler;
667 tq_scheduler_back:
669 prev = current;
670 this_cpu = prev->processor;
672 if (in_interrupt())
673 goto scheduling_in_interrupt;
675 release_kernel_lock(prev, this_cpu);
677 /* Do "administrative" work here while we don't hold any locks */
678 if (bh_mask & bh_active)
679 goto handle_bh;
680 handle_bh_back:
683 * 'sched_data' is protected by the fact that we can run
684 * only one process per CPU.
686 sched_data = & aligned_data[this_cpu].schedule_data;
688 spin_lock_irq(&runqueue_lock);
690 /* move an exhausted RR process to be last.. */
691 if (prev->policy == SCHED_RR)
692 goto move_rr_last;
693 move_rr_back:
695 switch (prev->state) {
696 case TASK_INTERRUPTIBLE:
697 if (signal_pending(prev)) {
698 prev->state = TASK_RUNNING;
699 break;
701 default:
702 del_from_runqueue(prev);
703 case TASK_RUNNING:
705 prev->need_resched = 0;
708 * this is the scheduler proper:
711 repeat_schedule:
713 * Default process to select..
715 next = idle_task(this_cpu);
716 c = -1000;
717 if (prev->state == TASK_RUNNING)
718 goto still_running;
719 still_running_back:
721 tmp = runqueue_head.next;
722 while (tmp != &runqueue_head) {
723 p = list_entry(tmp, struct task_struct, run_list);
724 if (can_schedule(p)) {
725 int weight = goodness(p, this_cpu, prev->active_mm);
726 if (weight > c)
727 c = weight, next = p;
729 tmp = tmp->next;
732 /* Do we need to re-calculate counters? */
733 if (!c)
734 goto recalculate;
736 * from this point on nothing can prevent us from
737 * switching to the next task, save this fact in
738 * sched_data.
740 sched_data->curr = next;
741 #ifdef __SMP__
742 next->has_cpu = 1;
743 next->processor = this_cpu;
744 #endif
745 spin_unlock_irq(&runqueue_lock);
747 if (prev == next)
748 goto same_process;
750 #ifdef __SMP__
752 * maintain the per-process 'average timeslice' value.
753 * (this has to be recalculated even if we reschedule to
754 * the same process) Currently this is only used on SMP,
755 * and it's approximate, so we do not have to maintain
756 * it while holding the runqueue spinlock.
759 cycles_t t, this_slice;
761 t = get_cycles();
762 this_slice = t - sched_data->last_schedule;
763 sched_data->last_schedule = t;
766 * Exponentially fading average calculation, with
767 * some weight so it doesnt get fooled easily by
768 * smaller irregularities.
770 prev->avg_slice = (this_slice*1 + prev->avg_slice*1)/2;
774 * We drop the scheduler lock early (it's a global spinlock),
775 * thus we have to lock the previous process from getting
776 * rescheduled during switch_to().
779 #endif /* __SMP__ */
781 kstat.context_swtch++;
783 * there are 3 processes which are affected by a context switch:
785 * prev == .... ==> (last => next)
787 * It's the 'much more previous' 'prev' that is on next's stack,
788 * but prev is set to (the just run) 'last' process by switch_to().
789 * This might sound slightly confusing but makes tons of sense.
792 struct mm_struct *mm = next->mm;
793 if (!mm) {
794 mm = prev->active_mm;
795 set_mmu_context(prev,next);
796 if (next->active_mm) BUG();
797 next->active_mm = mm;
798 atomic_inc(&mm->mm_count);
802 get_mmu_context(next);
803 switch_to(prev, next, prev);
804 __schedule_tail(prev);
806 same_process:
807 reacquire_kernel_lock(current);
808 return;
810 recalculate:
812 struct task_struct *p;
813 spin_unlock_irq(&runqueue_lock);
814 read_lock(&tasklist_lock);
815 for_each_task(p)
816 p->counter = (p->counter >> 1) + p->priority;
817 read_unlock(&tasklist_lock);
818 spin_lock_irq(&runqueue_lock);
820 goto repeat_schedule;
822 still_running:
823 c = prev_goodness(prev, this_cpu, prev->active_mm);
824 next = prev;
825 goto still_running_back;
827 handle_bh:
828 do_bottom_half();
829 goto handle_bh_back;
831 handle_tq_scheduler:
832 run_task_queue(&tq_scheduler);
833 goto tq_scheduler_back;
835 move_rr_last:
836 if (!prev->counter) {
837 prev->counter = prev->priority;
838 move_last_runqueue(prev);
840 goto move_rr_back;
842 scheduling_in_interrupt:
843 printk("Scheduling in interrupt\n");
844 *(int *)0 = 0;
845 return;
848 void __wake_up(wait_queue_head_t *q, unsigned int mode)
850 struct list_head *tmp, *head;
851 struct task_struct *p;
852 unsigned long flags;
854 if (!q)
855 goto out;
857 wq_write_lock_irqsave(&q->lock, flags);
859 #if WAITQUEUE_DEBUG
860 CHECK_MAGIC_WQHEAD(q);
861 #endif
863 head = &q->task_list;
864 #if WAITQUEUE_DEBUG
865 if (!head->next || !head->prev)
866 WQ_BUG();
867 #endif
868 tmp = head->next;
869 while (tmp != head) {
870 unsigned int state;
871 wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
873 tmp = tmp->next;
875 #if WAITQUEUE_DEBUG
876 CHECK_MAGIC(curr->__magic);
877 #endif
878 p = curr->task;
879 state = p->state;
880 if (state & mode) {
881 #if WAITQUEUE_DEBUG
882 curr->__waker = (long)__builtin_return_address(0);
883 #endif
884 wake_up_process(p);
885 if (state & TASK_EXCLUSIVE)
886 break;
889 wq_write_unlock_irqrestore(&q->lock, flags);
890 out:
891 return;
895 * Semaphores are implemented using a two-way counter:
896 * The "count" variable is decremented for each process
897 * that tries to sleep, while the "waking" variable is
898 * incremented when the "up()" code goes to wake up waiting
899 * processes.
901 * Notably, the inline "up()" and "down()" functions can
902 * efficiently test if they need to do any extra work (up
903 * needs to do something only if count was negative before
904 * the increment operation.
906 * waking_non_zero() (from asm/semaphore.h) must execute
907 * atomically.
909 * When __up() is called, the count was negative before
910 * incrementing it, and we need to wake up somebody.
912 * This routine adds one to the count of processes that need to
913 * wake up and exit. ALL waiting processes actually wake up but
914 * only the one that gets to the "waking" field first will gate
915 * through and acquire the semaphore. The others will go back
916 * to sleep.
918 * Note that these functions are only called when there is
919 * contention on the lock, and as such all this is the
920 * "non-critical" part of the whole semaphore business. The
921 * critical part is the inline stuff in <asm/semaphore.h>
922 * where we want to avoid any extra jumps and calls.
924 void __up(struct semaphore *sem)
926 wake_one_more(sem);
927 wake_up(&sem->wait);
931 * Perform the "down" function. Return zero for semaphore acquired,
932 * return negative for signalled out of the function.
934 * If called from __down, the return is ignored and the wait loop is
935 * not interruptible. This means that a task waiting on a semaphore
936 * using "down()" cannot be killed until someone does an "up()" on
937 * the semaphore.
939 * If called from __down_interruptible, the return value gets checked
940 * upon return. If the return value is negative then the task continues
941 * with the negative value in the return register (it can be tested by
942 * the caller).
944 * Either form may be used in conjunction with "up()".
948 #define DOWN_VAR \
949 struct task_struct *tsk = current; \
950 wait_queue_t wait; \
951 init_waitqueue_entry(&wait, tsk);
953 #define DOWN_HEAD(task_state) \
956 tsk->state = (task_state); \
957 add_wait_queue(&sem->wait, &wait); \
959 /* \
960 * Ok, we're set up. sem->count is known to be less than zero \
961 * so we must wait. \
963 * We can let go the lock for purposes of waiting. \
964 * We re-acquire it after awaking so as to protect \
965 * all semaphore operations. \
967 * If "up()" is called before we call waking_non_zero() then \
968 * we will catch it right away. If it is called later then \
969 * we will have to go through a wakeup cycle to catch it. \
971 * Multiple waiters contend for the semaphore lock to see \
972 * who gets to gate through and who has to wait some more. \
973 */ \
974 for (;;) {
976 #define DOWN_TAIL(task_state) \
977 tsk->state = (task_state); \
979 tsk->state = TASK_RUNNING; \
980 remove_wait_queue(&sem->wait, &wait);
982 void __down(struct semaphore * sem)
984 DOWN_VAR
985 DOWN_HEAD(TASK_UNINTERRUPTIBLE)
986 if (waking_non_zero(sem))
987 break;
988 schedule();
989 DOWN_TAIL(TASK_UNINTERRUPTIBLE)
992 int __down_interruptible(struct semaphore * sem)
994 int ret = 0;
995 DOWN_VAR
996 DOWN_HEAD(TASK_INTERRUPTIBLE)
998 ret = waking_non_zero_interruptible(sem, tsk);
999 if (ret)
1001 if (ret == 1)
1002 /* ret != 0 only if we get interrupted -arca */
1003 ret = 0;
1004 break;
1006 schedule();
1007 DOWN_TAIL(TASK_INTERRUPTIBLE)
1008 return ret;
1011 int __down_trylock(struct semaphore * sem)
1013 return waking_non_zero_trylock(sem);
1016 #define SLEEP_ON_VAR \
1017 unsigned long flags; \
1018 wait_queue_t wait; \
1019 init_waitqueue_entry(&wait, current);
1021 #define SLEEP_ON_HEAD \
1022 wq_write_lock_irqsave(&q->lock,flags); \
1023 __add_wait_queue(q, &wait); \
1024 wq_write_unlock(&q->lock);
1026 #define SLEEP_ON_TAIL \
1027 wq_write_lock_irq(&q->lock); \
1028 __remove_wait_queue(q, &wait); \
1029 wq_write_unlock_irqrestore(&q->lock,flags);
1031 void interruptible_sleep_on(wait_queue_head_t *q)
1033 SLEEP_ON_VAR
1035 current->state = TASK_INTERRUPTIBLE;
1037 SLEEP_ON_HEAD
1038 schedule();
1039 SLEEP_ON_TAIL
1042 long interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
1044 SLEEP_ON_VAR
1046 current->state = TASK_INTERRUPTIBLE;
1048 SLEEP_ON_HEAD
1049 timeout = schedule_timeout(timeout);
1050 SLEEP_ON_TAIL
1052 return timeout;
1055 void sleep_on(wait_queue_head_t *q)
1057 SLEEP_ON_VAR
1059 current->state = TASK_UNINTERRUPTIBLE;
1061 SLEEP_ON_HEAD
1062 schedule();
1063 SLEEP_ON_TAIL
1066 long sleep_on_timeout(wait_queue_head_t *q, long timeout)
1068 SLEEP_ON_VAR
1070 current->state = TASK_UNINTERRUPTIBLE;
1072 SLEEP_ON_HEAD
1073 timeout = schedule_timeout(timeout);
1074 SLEEP_ON_TAIL
1076 return timeout;
1079 void scheduling_functions_end_here(void) { }
1081 static inline void cascade_timers(struct timer_vec *tv)
1083 /* cascade all the timers from tv up one level */
1084 struct timer_list *timer;
1085 timer = tv->vec[tv->index];
1087 * We are removing _all_ timers from the list, so we don't have to
1088 * detach them individually, just clear the list afterwards.
1090 while (timer) {
1091 struct timer_list *tmp = timer;
1092 timer = timer->next;
1093 internal_add_timer(tmp);
1095 tv->vec[tv->index] = NULL;
1096 tv->index = (tv->index + 1) & TVN_MASK;
1099 static inline void run_timer_list(void)
1101 spin_lock_irq(&timerlist_lock);
1102 while ((long)(jiffies - timer_jiffies) >= 0) {
1103 struct timer_list *timer;
1104 if (!tv1.index) {
1105 int n = 1;
1106 do {
1107 cascade_timers(tvecs[n]);
1108 } while (tvecs[n]->index == 1 && ++n < NOOF_TVECS);
1110 while ((timer = tv1.vec[tv1.index])) {
1111 void (*fn)(unsigned long) = timer->function;
1112 unsigned long data = timer->data;
1113 detach_timer(timer);
1114 timer->next = timer->prev = NULL;
1115 spin_unlock_irq(&timerlist_lock);
1116 fn(data);
1117 spin_lock_irq(&timerlist_lock);
1119 ++timer_jiffies;
1120 tv1.index = (tv1.index + 1) & TVR_MASK;
1122 spin_unlock_irq(&timerlist_lock);
1126 static inline void run_old_timers(void)
1128 struct timer_struct *tp;
1129 unsigned long mask;
1131 for (mask = 1, tp = timer_table+0 ; mask ; tp++,mask += mask) {
1132 if (mask > timer_active)
1133 break;
1134 if (!(mask & timer_active))
1135 continue;
1136 if (time_after(tp->expires, jiffies))
1137 continue;
1138 timer_active &= ~mask;
1139 tp->fn();
1140 sti();
1144 spinlock_t tqueue_lock;
1146 void tqueue_bh(void)
1148 run_task_queue(&tq_timer);
1151 void immediate_bh(void)
1153 run_task_queue(&tq_immediate);
1156 unsigned long timer_active = 0;
1157 struct timer_struct timer_table[32];
1160 * Hmm.. Changed this, as the GNU make sources (load.c) seems to
1161 * imply that avenrun[] is the standard name for this kind of thing.
1162 * Nothing else seems to be standardized: the fractional size etc
1163 * all seem to differ on different machines.
1165 unsigned long avenrun[3] = { 0,0,0 };
1168 * Nr of active tasks - counted in fixed-point numbers
1170 static unsigned long count_active_tasks(void)
1172 struct task_struct *p;
1173 unsigned long nr = 0;
1175 read_lock(&tasklist_lock);
1176 for_each_task(p) {
1177 if ((p->state == TASK_RUNNING ||
1178 (p->state & TASK_UNINTERRUPTIBLE) ||
1179 (p->state & TASK_SWAPPING)))
1180 nr += FIXED_1;
1182 read_unlock(&tasklist_lock);
1183 return nr;
1186 static inline void calc_load(unsigned long ticks)
1188 unsigned long active_tasks; /* fixed-point */
1189 static int count = LOAD_FREQ;
1191 count -= ticks;
1192 if (count < 0) {
1193 count += LOAD_FREQ;
1194 active_tasks = count_active_tasks();
1195 CALC_LOAD(avenrun[0], EXP_1, active_tasks);
1196 CALC_LOAD(avenrun[1], EXP_5, active_tasks);
1197 CALC_LOAD(avenrun[2], EXP_15, active_tasks);
1202 * this routine handles the overflow of the microsecond field
1204 * The tricky bits of code to handle the accurate clock support
1205 * were provided by Dave Mills (Mills@UDEL.EDU) of NTP fame.
1206 * They were originally developed for SUN and DEC kernels.
1207 * All the kudos should go to Dave for this stuff.
1210 static void second_overflow(void)
1212 long ltemp;
1214 /* Bump the maxerror field */
1215 time_maxerror += time_tolerance >> SHIFT_USEC;
1216 if ( time_maxerror > NTP_PHASE_LIMIT ) {
1217 time_maxerror = NTP_PHASE_LIMIT;
1218 time_status |= STA_UNSYNC;
1222 * Leap second processing. If in leap-insert state at
1223 * the end of the day, the system clock is set back one
1224 * second; if in leap-delete state, the system clock is
1225 * set ahead one second. The microtime() routine or
1226 * external clock driver will insure that reported time
1227 * is always monotonic. The ugly divides should be
1228 * replaced.
1230 switch (time_state) {
1232 case TIME_OK:
1233 if (time_status & STA_INS)
1234 time_state = TIME_INS;
1235 else if (time_status & STA_DEL)
1236 time_state = TIME_DEL;
1237 break;
1239 case TIME_INS:
1240 if (xtime.tv_sec % 86400 == 0) {
1241 xtime.tv_sec--;
1242 time_state = TIME_OOP;
1243 printk(KERN_NOTICE "Clock: inserting leap second 23:59:60 UTC\n");
1245 break;
1247 case TIME_DEL:
1248 if ((xtime.tv_sec + 1) % 86400 == 0) {
1249 xtime.tv_sec++;
1250 time_state = TIME_WAIT;
1251 printk(KERN_NOTICE "Clock: deleting leap second 23:59:59 UTC\n");
1253 break;
1255 case TIME_OOP:
1256 time_state = TIME_WAIT;
1257 break;
1259 case TIME_WAIT:
1260 if (!(time_status & (STA_INS | STA_DEL)))
1261 time_state = TIME_OK;
1265 * Compute the phase adjustment for the next second. In
1266 * PLL mode, the offset is reduced by a fixed factor
1267 * times the time constant. In FLL mode the offset is
1268 * used directly. In either mode, the maximum phase
1269 * adjustment for each second is clamped so as to spread
1270 * the adjustment over not more than the number of
1271 * seconds between updates.
1273 if (time_offset < 0) {
1274 ltemp = -time_offset;
1275 if (!(time_status & STA_FLL))
1276 ltemp >>= SHIFT_KG + time_constant;
1277 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
1278 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
1279 time_offset += ltemp;
1280 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
1281 } else {
1282 ltemp = time_offset;
1283 if (!(time_status & STA_FLL))
1284 ltemp >>= SHIFT_KG + time_constant;
1285 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
1286 ltemp = (MAXPHASE / MINSEC) << SHIFT_UPDATE;
1287 time_offset -= ltemp;
1288 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
1292 * Compute the frequency estimate and additional phase
1293 * adjustment due to frequency error for the next
1294 * second. When the PPS signal is engaged, gnaw on the
1295 * watchdog counter and update the frequency computed by
1296 * the pll and the PPS signal.
1298 pps_valid++;
1299 if (pps_valid == PPS_VALID) { /* PPS signal lost */
1300 pps_jitter = MAXTIME;
1301 pps_stabil = MAXFREQ;
1302 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
1303 STA_PPSWANDER | STA_PPSERROR);
1305 ltemp = time_freq + pps_freq;
1306 if (ltemp < 0)
1307 time_adj -= -ltemp >>
1308 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
1309 else
1310 time_adj += ltemp >>
1311 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
1313 #if HZ == 100
1314 /* Compensate for (HZ==100) != (1 << SHIFT_HZ).
1315 * Add 25% and 3.125% to get 128.125; => only 0.125% error (p. 14)
1317 if (time_adj < 0)
1318 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
1319 else
1320 time_adj += (time_adj >> 2) + (time_adj >> 5);
1321 #endif
1324 /* in the NTP reference this is called "hardclock()" */
1325 static void update_wall_time_one_tick(void)
1327 if ( (time_adjust_step = time_adjust) != 0 ) {
1328 /* We are doing an adjtime thing.
1330 * Prepare time_adjust_step to be within bounds.
1331 * Note that a positive time_adjust means we want the clock
1332 * to run faster.
1334 * Limit the amount of the step to be in the range
1335 * -tickadj .. +tickadj
1337 if (time_adjust > tickadj)
1338 time_adjust_step = tickadj;
1339 else if (time_adjust < -tickadj)
1340 time_adjust_step = -tickadj;
1342 /* Reduce by this step the amount of time left */
1343 time_adjust -= time_adjust_step;
1345 xtime.tv_usec += tick + time_adjust_step;
1347 * Advance the phase, once it gets to one microsecond, then
1348 * advance the tick more.
1350 time_phase += time_adj;
1351 if (time_phase <= -FINEUSEC) {
1352 long ltemp = -time_phase >> SHIFT_SCALE;
1353 time_phase += ltemp << SHIFT_SCALE;
1354 xtime.tv_usec -= ltemp;
1356 else if (time_phase >= FINEUSEC) {
1357 long ltemp = time_phase >> SHIFT_SCALE;
1358 time_phase -= ltemp << SHIFT_SCALE;
1359 xtime.tv_usec += ltemp;
1364 * Using a loop looks inefficient, but "ticks" is
1365 * usually just one (we shouldn't be losing ticks,
1366 * we're doing this this way mainly for interrupt
1367 * latency reasons, not because we think we'll
1368 * have lots of lost timer ticks
1370 static void update_wall_time(unsigned long ticks)
1372 do {
1373 ticks--;
1374 update_wall_time_one_tick();
1375 } while (ticks);
1377 if (xtime.tv_usec >= 1000000) {
1378 xtime.tv_usec -= 1000000;
1379 xtime.tv_sec++;
1380 second_overflow();
1384 static inline void do_process_times(struct task_struct *p,
1385 unsigned long user, unsigned long system)
1387 long psecs;
1389 psecs = (p->times.tms_utime += user);
1390 psecs += (p->times.tms_stime += system);
1391 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_cur) {
1392 /* Send SIGXCPU every second.. */
1393 if (!(psecs % HZ))
1394 send_sig(SIGXCPU, p, 1);
1395 /* and SIGKILL when we go over max.. */
1396 if (psecs / HZ > p->rlim[RLIMIT_CPU].rlim_max)
1397 send_sig(SIGKILL, p, 1);
1401 static inline void do_it_virt(struct task_struct * p, unsigned long ticks)
1403 unsigned long it_virt = p->it_virt_value;
1405 if (it_virt) {
1406 if (it_virt <= ticks) {
1407 it_virt = ticks + p->it_virt_incr;
1408 send_sig(SIGVTALRM, p, 1);
1410 p->it_virt_value = it_virt - ticks;
1414 static inline void do_it_prof(struct task_struct * p, unsigned long ticks)
1416 unsigned long it_prof = p->it_prof_value;
1418 if (it_prof) {
1419 if (it_prof <= ticks) {
1420 it_prof = ticks + p->it_prof_incr;
1421 send_sig(SIGPROF, p, 1);
1423 p->it_prof_value = it_prof - ticks;
1427 void update_one_process(struct task_struct *p,
1428 unsigned long ticks, unsigned long user, unsigned long system, int cpu)
1430 p->per_cpu_utime[cpu] += user;
1431 p->per_cpu_stime[cpu] += system;
1432 do_process_times(p, user, system);
1433 do_it_virt(p, user);
1434 do_it_prof(p, ticks);
1437 static void update_process_times(unsigned long ticks, unsigned long system)
1440 * SMP does this on a per-CPU basis elsewhere
1442 #ifndef __SMP__
1443 struct task_struct * p = current;
1444 unsigned long user = ticks - system;
1445 if (p->pid) {
1446 p->counter -= ticks;
1447 if (p->counter <= 0) {
1448 p->counter = 0;
1449 p->need_resched = 1;
1451 if (p->priority < DEF_PRIORITY)
1452 kstat.cpu_nice += user;
1453 else
1454 kstat.cpu_user += user;
1455 kstat.cpu_system += system;
1457 update_one_process(p, ticks, user, system, 0);
1458 #endif
1461 volatile unsigned long lost_ticks = 0;
1462 static unsigned long lost_ticks_system = 0;
1465 * This spinlock protect us from races in SMP while playing with xtime. -arca
1467 rwlock_t xtime_lock = RW_LOCK_UNLOCKED;
1469 static inline void update_times(void)
1471 unsigned long ticks;
1474 * update_times() is run from the raw timer_bh handler so we
1475 * just know that the irqs are locally enabled and so we don't
1476 * need to save/restore the flags of the local CPU here. -arca
1478 write_lock_irq(&xtime_lock);
1480 ticks = lost_ticks;
1481 lost_ticks = 0;
1483 if (ticks) {
1484 unsigned long system;
1485 system = xchg(&lost_ticks_system, 0);
1487 calc_load(ticks);
1488 update_wall_time(ticks);
1489 write_unlock_irq(&xtime_lock);
1491 update_process_times(ticks, system);
1493 } else
1494 write_unlock_irq(&xtime_lock);
1497 static void timer_bh(void)
1499 update_times();
1500 run_old_timers();
1501 run_timer_list();
1504 void do_timer(struct pt_regs * regs)
1506 (*(unsigned long *)&jiffies)++;
1507 lost_ticks++;
1508 mark_bh(TIMER_BH);
1509 if (!user_mode(regs))
1510 lost_ticks_system++;
1511 if (tq_timer)
1512 mark_bh(TQUEUE_BH);
1515 #ifndef __alpha__
1518 * For backwards compatibility? This can be done in libc so Alpha
1519 * and all newer ports shouldn't need it.
1521 asmlinkage unsigned int sys_alarm(unsigned int seconds)
1523 struct itimerval it_new, it_old;
1524 unsigned int oldalarm;
1526 it_new.it_interval.tv_sec = it_new.it_interval.tv_usec = 0;
1527 it_new.it_value.tv_sec = seconds;
1528 it_new.it_value.tv_usec = 0;
1529 do_setitimer(ITIMER_REAL, &it_new, &it_old);
1530 oldalarm = it_old.it_value.tv_sec;
1531 /* ehhh.. We can't return 0 if we have an alarm pending.. */
1532 /* And we'd better return too much than too little anyway */
1533 if (it_old.it_value.tv_usec)
1534 oldalarm++;
1535 return oldalarm;
1539 * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
1540 * should be moved into arch/i386 instead?
1543 asmlinkage int sys_getpid(void)
1545 /* This is SMP safe - current->pid doesn't change */
1546 return current->pid;
1550 * This is not strictly SMP safe: p_opptr could change
1551 * from under us. However, rather than getting any lock
1552 * we can use an optimistic algorithm: get the parent
1553 * pid, and go back and check that the parent is still
1554 * the same. If it has changed (which is extremely unlikely
1555 * indeed), we just try again..
1557 * NOTE! This depends on the fact that even if we _do_
1558 * get an old value of "parent", we can happily dereference
1559 * the pointer: we just can't necessarily trust the result
1560 * until we know that the parent pointer is valid.
1562 * The "mb()" macro is a memory barrier - a synchronizing
1563 * event. It also makes sure that gcc doesn't optimize
1564 * away the necessary memory references.. The barrier doesn't
1565 * have to have all that strong semantics: on x86 we don't
1566 * really require a synchronizing instruction, for example.
1567 * The barrier is more important for code generation than
1568 * for any real memory ordering semantics (even if there is
1569 * a small window for a race, using the old pointer is
1570 * harmless for a while).
1572 asmlinkage int sys_getppid(void)
1574 int pid;
1575 struct task_struct * me = current;
1576 struct task_struct * parent;
1578 parent = me->p_opptr;
1579 for (;;) {
1580 pid = parent->pid;
1581 #if __SMP__
1583 struct task_struct *old = parent;
1584 mb();
1585 parent = me->p_opptr;
1586 if (old != parent)
1587 continue;
1589 #endif
1590 break;
1592 return pid;
1595 asmlinkage int sys_getuid(void)
1597 /* Only we change this so SMP safe */
1598 return current->uid;
1601 asmlinkage int sys_geteuid(void)
1603 /* Only we change this so SMP safe */
1604 return current->euid;
1607 asmlinkage int sys_getgid(void)
1609 /* Only we change this so SMP safe */
1610 return current->gid;
1613 asmlinkage int sys_getegid(void)
1615 /* Only we change this so SMP safe */
1616 return current->egid;
1620 * This has been replaced by sys_setpriority. Maybe it should be
1621 * moved into the arch dependent tree for those ports that require
1622 * it for backward compatibility?
1625 asmlinkage int sys_nice(int increment)
1627 unsigned long newprio;
1628 int increase = 0;
1631 * Setpriority might change our priority at the same moment.
1632 * We don't have to worry. Conceptually one call occurs first
1633 * and we have a single winner.
1636 newprio = increment;
1637 if (increment < 0) {
1638 if (!capable(CAP_SYS_NICE))
1639 return -EPERM;
1640 newprio = -increment;
1641 increase = 1;
1644 if (newprio > 40)
1645 newprio = 40;
1647 * do a "normalization" of the priority (traditionally
1648 * Unix nice values are -20 to 20; Linux doesn't really
1649 * use that kind of thing, but uses the length of the
1650 * timeslice instead (default 200 ms). The rounding is
1651 * why we want to avoid negative values.
1653 newprio = (newprio * DEF_PRIORITY + 10) / 20;
1654 increment = newprio;
1655 if (increase)
1656 increment = -increment;
1658 * Current->priority can change between this point
1659 * and the assignment. We are assigning not doing add/subs
1660 * so thats ok. Conceptually a process might just instantaneously
1661 * read the value we stomp over. I don't think that is an issue
1662 * unless posix makes it one. If so we can loop on changes
1663 * to current->priority.
1665 newprio = current->priority - increment;
1666 if ((signed) newprio < 1)
1667 newprio = 1;
1668 if (newprio > DEF_PRIORITY*2)
1669 newprio = DEF_PRIORITY*2;
1670 current->priority = newprio;
1671 return 0;
1674 #endif
1676 static inline struct task_struct *find_process_by_pid(pid_t pid)
1678 struct task_struct *tsk = current;
1680 if (pid)
1681 tsk = find_task_by_pid(pid);
1682 return tsk;
1685 static int setscheduler(pid_t pid, int policy,
1686 struct sched_param *param)
1688 struct sched_param lp;
1689 struct task_struct *p;
1690 int retval;
1692 retval = -EINVAL;
1693 if (!param || pid < 0)
1694 goto out_nounlock;
1696 retval = -EFAULT;
1697 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
1698 goto out_nounlock;
1701 * We play safe to avoid deadlocks.
1703 spin_lock_irq(&runqueue_lock);
1704 read_lock(&tasklist_lock);
1706 p = find_process_by_pid(pid);
1708 retval = -ESRCH;
1709 if (!p)
1710 goto out_unlock;
1712 if (policy < 0)
1713 policy = p->policy;
1714 else {
1715 retval = -EINVAL;
1716 if (policy != SCHED_FIFO && policy != SCHED_RR &&
1717 policy != SCHED_OTHER)
1718 goto out_unlock;
1722 * Valid priorities for SCHED_FIFO and SCHED_RR are 1..99, valid
1723 * priority for SCHED_OTHER is 0.
1725 retval = -EINVAL;
1726 if (lp.sched_priority < 0 || lp.sched_priority > 99)
1727 goto out_unlock;
1728 if ((policy == SCHED_OTHER) != (lp.sched_priority == 0))
1729 goto out_unlock;
1731 retval = -EPERM;
1732 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
1733 !capable(CAP_SYS_NICE))
1734 goto out_unlock;
1735 if ((current->euid != p->euid) && (current->euid != p->uid) &&
1736 !capable(CAP_SYS_NICE))
1737 goto out_unlock;
1739 retval = 0;
1740 p->policy = policy;
1741 p->rt_priority = lp.sched_priority;
1742 if (task_on_runqueue(p))
1743 move_first_runqueue(p);
1745 current->need_resched = 1;
1747 out_unlock:
1748 read_unlock(&tasklist_lock);
1749 spin_unlock_irq(&runqueue_lock);
1751 out_nounlock:
1752 return retval;
1755 asmlinkage int sys_sched_setscheduler(pid_t pid, int policy,
1756 struct sched_param *param)
1758 return setscheduler(pid, policy, param);
1761 asmlinkage int sys_sched_setparam(pid_t pid, struct sched_param *param)
1763 return setscheduler(pid, -1, param);
1766 asmlinkage int sys_sched_getscheduler(pid_t pid)
1768 struct task_struct *p;
1769 int retval;
1771 retval = -EINVAL;
1772 if (pid < 0)
1773 goto out_nounlock;
1775 read_lock(&tasklist_lock);
1777 retval = -ESRCH;
1778 p = find_process_by_pid(pid);
1779 if (!p)
1780 goto out_unlock;
1782 retval = p->policy;
1784 out_unlock:
1785 read_unlock(&tasklist_lock);
1787 out_nounlock:
1788 return retval;
1791 asmlinkage int sys_sched_getparam(pid_t pid, struct sched_param *param)
1793 struct task_struct *p;
1794 struct sched_param lp;
1795 int retval;
1797 retval = -EINVAL;
1798 if (!param || pid < 0)
1799 goto out_nounlock;
1801 read_lock(&tasklist_lock);
1802 p = find_process_by_pid(pid);
1803 retval = -ESRCH;
1804 if (!p)
1805 goto out_unlock;
1806 lp.sched_priority = p->rt_priority;
1807 read_unlock(&tasklist_lock);
1810 * This one might sleep, we cannot do it with a spinlock held ...
1812 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
1814 out_nounlock:
1815 return retval;
1817 out_unlock:
1818 read_unlock(&tasklist_lock);
1819 return retval;
1822 asmlinkage int sys_sched_yield(void)
1824 spin_lock_irq(&runqueue_lock);
1825 if (current->policy == SCHED_OTHER)
1826 current->policy |= SCHED_YIELD;
1827 current->need_resched = 1;
1828 move_last_runqueue(current);
1829 spin_unlock_irq(&runqueue_lock);
1830 return 0;
1833 asmlinkage int sys_sched_get_priority_max(int policy)
1835 int ret = -EINVAL;
1837 switch (policy) {
1838 case SCHED_FIFO:
1839 case SCHED_RR:
1840 ret = 99;
1841 break;
1842 case SCHED_OTHER:
1843 ret = 0;
1844 break;
1846 return ret;
1849 asmlinkage int sys_sched_get_priority_min(int policy)
1851 int ret = -EINVAL;
1853 switch (policy) {
1854 case SCHED_FIFO:
1855 case SCHED_RR:
1856 ret = 1;
1857 break;
1858 case SCHED_OTHER:
1859 ret = 0;
1861 return ret;
1864 asmlinkage int sys_sched_rr_get_interval(pid_t pid, struct timespec *interval)
1866 struct timespec t;
1868 t.tv_sec = 0;
1869 t.tv_nsec = 150000;
1870 if (copy_to_user(interval, &t, sizeof(struct timespec)))
1871 return -EFAULT;
1872 return 0;
1875 asmlinkage int sys_nanosleep(struct timespec *rqtp, struct timespec *rmtp)
1877 struct timespec t;
1878 unsigned long expire;
1880 if(copy_from_user(&t, rqtp, sizeof(struct timespec)))
1881 return -EFAULT;
1883 if (t.tv_nsec >= 1000000000L || t.tv_nsec < 0 || t.tv_sec < 0)
1884 return -EINVAL;
1887 if (t.tv_sec == 0 && t.tv_nsec <= 2000000L &&
1888 current->policy != SCHED_OTHER)
1891 * Short delay requests up to 2 ms will be handled with
1892 * high precision by a busy wait for all real-time processes.
1894 * Its important on SMP not to do this holding locks.
1896 udelay((t.tv_nsec + 999) / 1000);
1897 return 0;
1900 expire = timespec_to_jiffies(&t) + (t.tv_sec || t.tv_nsec);
1902 current->state = TASK_INTERRUPTIBLE;
1903 expire = schedule_timeout(expire);
1905 if (expire) {
1906 if (rmtp) {
1907 jiffies_to_timespec(expire, &t);
1908 if (copy_to_user(rmtp, &t, sizeof(struct timespec)))
1909 return -EFAULT;
1911 return -EINTR;
1913 return 0;
1916 static void show_task(struct task_struct * p)
1918 unsigned long free = 0;
1919 int state;
1920 static const char * stat_nam[] = { "R", "S", "D", "Z", "T", "W" };
1922 printk("%-8s ", p->comm);
1923 state = p->state ? ffz(~p->state) + 1 : 0;
1924 if (((unsigned) state) < sizeof(stat_nam)/sizeof(char *))
1925 printk(stat_nam[state]);
1926 else
1927 printk(" ");
1928 #if (BITS_PER_LONG == 32)
1929 if (p == current)
1930 printk(" current ");
1931 else
1932 printk(" %08lX ", thread_saved_pc(&p->thread));
1933 #else
1934 if (p == current)
1935 printk(" current task ");
1936 else
1937 printk(" %016lx ", thread_saved_pc(&p->thread));
1938 #endif
1940 unsigned long * n = (unsigned long *) (p+1);
1941 while (!*n)
1942 n++;
1943 free = (unsigned long) n - (unsigned long)(p+1);
1945 printk("%5lu %5d %6d ", free, p->pid, p->p_pptr->pid);
1946 if (p->p_cptr)
1947 printk("%5d ", p->p_cptr->pid);
1948 else
1949 printk(" ");
1950 if (!p->mm)
1951 printk(" (L-TLB) ");
1952 else
1953 printk(" (NOTLB) ");
1954 if (p->p_ysptr)
1955 printk("%7d", p->p_ysptr->pid);
1956 else
1957 printk(" ");
1958 if (p->p_osptr)
1959 printk(" %5d\n", p->p_osptr->pid);
1960 else
1961 printk("\n");
1964 struct signal_queue *q;
1965 char s[sizeof(sigset_t)*2+1], b[sizeof(sigset_t)*2+1];
1967 render_sigset_t(&p->signal, s);
1968 render_sigset_t(&p->blocked, b);
1969 printk(" sig: %d %s %s :", signal_pending(p), s, b);
1970 for (q = p->sigqueue; q ; q = q->next)
1971 printk(" %d", q->info.si_signo);
1972 printk(" X\n");
1976 char * render_sigset_t(sigset_t *set, char *buffer)
1978 int i = _NSIG, x;
1979 do {
1980 i -= 4, x = 0;
1981 if (sigismember(set, i+1)) x |= 1;
1982 if (sigismember(set, i+2)) x |= 2;
1983 if (sigismember(set, i+3)) x |= 4;
1984 if (sigismember(set, i+4)) x |= 8;
1985 *buffer++ = (x < 10 ? '0' : 'a' - 10) + x;
1986 } while (i >= 4);
1987 *buffer = 0;
1988 return buffer;
1991 void show_state(void)
1993 struct task_struct *p;
1995 #if (BITS_PER_LONG == 32)
1996 printk("\n"
1997 " free sibling\n");
1998 printk(" task PC stack pid father child younger older\n");
1999 #else
2000 printk("\n"
2001 " free sibling\n");
2002 printk(" task PC stack pid father child younger older\n");
2003 #endif
2004 read_lock(&tasklist_lock);
2005 for_each_task(p)
2006 show_task(p);
2007 read_unlock(&tasklist_lock);
2010 void __init init_idle(void)
2012 cycles_t t;
2013 struct schedule_data * sched_data;
2014 sched_data = &aligned_data[smp_processor_id()].schedule_data;
2016 if (current != &init_task && task_on_runqueue(current)) {
2017 printk("UGH! (%d:%d) was on the runqueue, removing.\n",
2018 smp_processor_id(), current->pid);
2019 del_from_runqueue(current);
2021 t = get_cycles();
2022 sched_data->curr = current;
2023 sched_data->last_schedule = t;
2026 void __init sched_init(void)
2029 * We have to do a little magic to get the first
2030 * process right in SMP mode.
2032 int cpu=hard_smp_processor_id();
2033 int nr;
2035 init_task.processor=cpu;
2037 for(nr = 0; nr < PIDHASH_SZ; nr++)
2038 pidhash[nr] = NULL;
2040 init_bh(TIMER_BH, timer_bh);
2041 init_bh(TQUEUE_BH, tqueue_bh);
2042 init_bh(IMMEDIATE_BH, immediate_bh);
2045 * The boot idle thread does lazy MMU switching as well:
2047 atomic_inc(&init_mm.mm_count);