4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/suspend.h>
35 #include <linux/blkdev.h>
36 #include <linux/delay.h>
37 #include <linux/smp.h>
38 #include <linux/timer.h>
39 #include <linux/rcupdate.h>
40 #include <linux/cpu.h>
41 #include <linux/percpu.h>
42 #include <linux/kthread.h>
44 #include <asm/unistd.h>
47 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
49 #define cpu_to_node_mask(cpu) (cpu_online_map)
53 * Convert user-nice values [ -20 ... 0 ... 19 ]
54 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
57 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
58 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
59 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
62 * 'User priority' is the nice value converted to something we
63 * can work with better when scaling various scheduler parameters,
64 * it's a [ 0 ... 39 ] range.
66 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
67 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
68 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
69 #define AVG_TIMESLICE (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) *\
70 (MAX_PRIO-1-NICE_TO_PRIO(0))/(MAX_USER_PRIO - 1)))
73 * Some helpers for converting nanosecond timing to jiffy resolution
75 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
76 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
79 * These are the 'tuning knobs' of the scheduler:
81 * Minimum timeslice is 10 msecs, default timeslice is 100 msecs,
82 * maximum timeslice is 200 msecs. Timeslices get refilled after
85 #define MIN_TIMESLICE ( 10 * HZ / 1000)
86 #define MAX_TIMESLICE (200 * HZ / 1000)
87 #define ON_RUNQUEUE_WEIGHT 30
88 #define CHILD_PENALTY 95
89 #define PARENT_PENALTY 100
91 #define PRIO_BONUS_RATIO 25
92 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
93 #define INTERACTIVE_DELTA 2
94 #define MAX_SLEEP_AVG (AVG_TIMESLICE * MAX_BONUS)
95 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
96 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
97 #define CREDIT_LIMIT 100
100 * If a task is 'interactive' then we reinsert it in the active
101 * array after it has expired its current timeslice. (it will not
102 * continue to run immediately, it will still roundrobin with
103 * other interactive tasks.)
105 * This part scales the interactivity limit depending on niceness.
107 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
108 * Here are a few examples of different nice levels:
110 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
111 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
112 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
113 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
114 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
116 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
117 * priority range a task can explore, a value of '1' means the
118 * task is rated interactive.)
120 * Ie. nice +19 tasks can never get 'interactive' enough to be
121 * reinserted into the active array. And only heavily CPU-hog nice -20
122 * tasks will be expired. Default nice 0 tasks are somewhere between,
123 * it takes some effort for them to get interactive, but it's not
127 #define CURRENT_BONUS(p) \
128 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
132 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
133 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
136 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
137 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
140 #define SCALE(v1,v1_max,v2_max) \
141 (v1) * (v2_max) / (v1_max)
144 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
146 #define TASK_INTERACTIVE(p) \
147 ((p)->prio <= (p)->static_prio - DELTA(p))
149 #define INTERACTIVE_SLEEP(p) \
150 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
151 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
153 #define HIGH_CREDIT(p) \
154 ((p)->interactive_credit > CREDIT_LIMIT)
156 #define LOW_CREDIT(p) \
157 ((p)->interactive_credit < -CREDIT_LIMIT)
159 #define TASK_PREEMPTS_CURR(p, rq) \
160 ((p)->prio < (rq)->curr->prio)
163 * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
164 * to time slice values.
166 * The higher a thread's priority, the bigger timeslices
167 * it gets during one round of execution. But even the lowest
168 * priority thread gets MIN_TIMESLICE worth of execution time.
170 * task_timeslice() is the interface that is used by the scheduler.
173 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
174 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
175 (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
177 static unsigned int task_timeslice(task_t *p)
179 return BASE_TIMESLICE(p);
182 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
185 * These are the runqueue data structures:
188 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
190 typedef struct runqueue runqueue_t;
193 unsigned int nr_active;
194 unsigned long bitmap[BITMAP_SIZE];
195 struct list_head queue[MAX_PRIO];
199 * This is the main, per-CPU runqueue data structure.
201 * Locking rule: those places that want to lock multiple runqueues
202 * (such as the load balancing or the thread migration code), lock
203 * acquire operations must be ordered by ascending &runqueue.
209 * nr_running and cpu_load should be in the same cacheline because
210 * remote CPUs use both these fields when doing load calculation.
212 unsigned long nr_running;
214 unsigned long cpu_load;
216 unsigned long long nr_switches;
217 unsigned long expired_timestamp, nr_uninterruptible;
218 unsigned long long timestamp_last_tick;
220 struct mm_struct *prev_mm;
221 prio_array_t *active, *expired, arrays[2];
222 int best_expired_prio;
226 struct sched_domain *sd;
228 /* For active balancing */
232 task_t *migration_thread;
233 struct list_head migration_queue;
237 static DEFINE_PER_CPU(struct runqueue, runqueues);
239 #define for_each_domain(cpu, domain) \
240 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
242 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
243 #define this_rq() (&__get_cpu_var(runqueues))
244 #define task_rq(p) cpu_rq(task_cpu(p))
245 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
248 * Default context-switch locking:
250 #ifndef prepare_arch_switch
251 # define prepare_arch_switch(rq, next) do { } while (0)
252 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
253 # define task_running(rq, p) ((rq)->curr == (p))
257 * task_rq_lock - lock the runqueue a given task resides on and disable
258 * interrupts. Note the ordering: we can safely lookup the task_rq without
259 * explicitly disabling preemption.
261 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
266 local_irq_save(*flags);
268 spin_lock(&rq->lock);
269 if (unlikely(rq != task_rq(p))) {
270 spin_unlock_irqrestore(&rq->lock, *flags);
271 goto repeat_lock_task;
276 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
278 spin_unlock_irqrestore(&rq->lock, *flags);
282 * rq_lock - lock a given runqueue and disable interrupts.
284 static runqueue_t *this_rq_lock(void)
290 spin_lock(&rq->lock);
295 static inline void rq_unlock(runqueue_t *rq)
297 spin_unlock_irq(&rq->lock);
301 * Adding/removing a task to/from a priority array:
303 static void dequeue_task(struct task_struct *p, prio_array_t *array)
306 list_del(&p->run_list);
307 if (list_empty(array->queue + p->prio))
308 __clear_bit(p->prio, array->bitmap);
311 static void enqueue_task(struct task_struct *p, prio_array_t *array)
313 list_add_tail(&p->run_list, array->queue + p->prio);
314 __set_bit(p->prio, array->bitmap);
320 * Used by the migration code - we pull tasks from the head of the
321 * remote queue so we want these tasks to show up at the head of the
324 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
326 list_add(&p->run_list, array->queue + p->prio);
327 __set_bit(p->prio, array->bitmap);
333 * effective_prio - return the priority that is based on the static
334 * priority but is modified by bonuses/penalties.
336 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
337 * into the -5 ... 0 ... +5 bonus/penalty range.
339 * We use 25% of the full 0...39 priority range so that:
341 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
342 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
344 * Both properties are important to certain workloads.
346 static int effective_prio(task_t *p)
353 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
355 prio = p->static_prio - bonus;
356 if (prio < MAX_RT_PRIO)
358 if (prio > MAX_PRIO-1)
364 * __activate_task - move a task to the runqueue.
366 static inline void __activate_task(task_t *p, runqueue_t *rq)
368 enqueue_task(p, rq->active);
373 * __activate_idle_task - move idle task to the _front_ of runqueue.
375 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
377 enqueue_task_head(p, rq->active);
381 static void recalc_task_prio(task_t *p, unsigned long long now)
383 unsigned long long __sleep_time = now - p->timestamp;
384 unsigned long sleep_time;
386 if (__sleep_time > NS_MAX_SLEEP_AVG)
387 sleep_time = NS_MAX_SLEEP_AVG;
389 sleep_time = (unsigned long)__sleep_time;
391 if (likely(sleep_time > 0)) {
393 * User tasks that sleep a long time are categorised as
394 * idle and will get just interactive status to stay active &
395 * prevent them suddenly becoming cpu hogs and starving
398 if (p->mm && p->activated != -1 &&
399 sleep_time > INTERACTIVE_SLEEP(p)) {
400 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
403 p->interactive_credit++;
406 * The lower the sleep avg a task has the more
407 * rapidly it will rise with sleep time.
409 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
412 * Tasks with low interactive_credit are limited to
413 * one timeslice worth of sleep avg bonus.
416 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
417 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
420 * Non high_credit tasks waking from uninterruptible
421 * sleep are limited in their sleep_avg rise as they
422 * are likely to be cpu hogs waiting on I/O
424 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
425 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
427 else if (p->sleep_avg + sleep_time >=
428 INTERACTIVE_SLEEP(p)) {
429 p->sleep_avg = INTERACTIVE_SLEEP(p);
435 * This code gives a bonus to interactive tasks.
437 * The boost works by updating the 'average sleep time'
438 * value here, based on ->timestamp. The more time a
439 * task spends sleeping, the higher the average gets -
440 * and the higher the priority boost gets as well.
442 p->sleep_avg += sleep_time;
444 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
445 p->sleep_avg = NS_MAX_SLEEP_AVG;
447 p->interactive_credit++;
452 p->prio = effective_prio(p);
456 * activate_task - move a task to the runqueue and do priority recalculation
458 * Update all the scheduling statistics stuff. (sleep average
459 * calculation, priority modifiers, etc.)
461 static void activate_task(task_t *p, runqueue_t *rq, int local)
463 unsigned long long now;
468 /* Compensate for drifting sched_clock */
469 runqueue_t *this_rq = this_rq();
470 now = (now - this_rq->timestamp_last_tick)
471 + rq->timestamp_last_tick;
475 recalc_task_prio(p, now);
478 * This checks to make sure it's not an uninterruptible task
479 * that is now waking up.
483 * Tasks which were woken up by interrupts (ie. hw events)
484 * are most likely of interactive nature. So we give them
485 * the credit of extending their sleep time to the period
486 * of time they spend on the runqueue, waiting for execution
487 * on a CPU, first time around:
493 * Normal first-time wakeups get a credit too for
494 * on-runqueue time, but it will be weighted down:
501 __activate_task(p, rq);
505 * deactivate_task - remove a task from the runqueue.
507 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
510 if (p->state == TASK_UNINTERRUPTIBLE)
511 rq->nr_uninterruptible++;
512 dequeue_task(p, p->array);
517 * resched_task - mark a task 'to be rescheduled now'.
519 * On UP this means the setting of the need_resched flag, on SMP it
520 * might also involve a cross-CPU call to trigger the scheduler on
524 static void resched_task(task_t *p)
526 int need_resched, nrpolling;
529 /* minimise the chance of sending an interrupt to poll_idle() */
530 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
531 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
532 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
534 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
535 smp_send_reschedule(task_cpu(p));
539 static inline void resched_task(task_t *p)
541 set_tsk_need_resched(p);
546 * task_curr - is this task currently executing on a CPU?
547 * @p: the task in question.
549 inline int task_curr(task_t *p)
551 return cpu_curr(task_cpu(p)) == p;
561 struct list_head list;
562 enum request_type type;
564 /* For REQ_MOVE_TASK */
568 /* For REQ_SET_DOMAIN */
569 struct sched_domain *sd;
571 struct completion done;
575 * The task's runqueue lock must be held.
576 * Returns true if you have to wait for migration thread.
578 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
580 runqueue_t *rq = task_rq(p);
583 * If the task is not on a runqueue (and not running), then
584 * it is sufficient to simply update the task's cpu field.
586 if (!p->array && !task_running(rq, p)) {
587 set_task_cpu(p, dest_cpu);
591 init_completion(&req->done);
592 req->type = REQ_MOVE_TASK;
594 req->dest_cpu = dest_cpu;
595 list_add(&req->list, &rq->migration_queue);
600 * wait_task_inactive - wait for a thread to unschedule.
602 * The caller must ensure that the task *will* unschedule sometime soon,
603 * else this function might spin for a *long* time. This function can't
604 * be called with interrupts off, or it may introduce deadlock with
605 * smp_call_function() if an IPI is sent by the same process we are
606 * waiting to become inactive.
608 void wait_task_inactive(task_t * p)
615 rq = task_rq_lock(p, &flags);
616 /* Must be off runqueue entirely, not preempted. */
617 if (unlikely(p->array)) {
618 /* If it's preempted, we yield. It could be a while. */
619 preempted = !task_running(rq, p);
620 task_rq_unlock(rq, &flags);
626 task_rq_unlock(rq, &flags);
630 * kick_process - kick a running thread to enter/exit the kernel
631 * @p: the to-be-kicked thread
633 * Cause a process which is running on another CPU to enter
634 * kernel-mode, without any delay. (to get signals handled.)
636 void kick_process(task_t *p)
642 if ((cpu != smp_processor_id()) && task_curr(p))
643 smp_send_reschedule(cpu);
647 EXPORT_SYMBOL_GPL(kick_process);
650 * Return a low guess at the load of a migration-source cpu.
652 * We want to under-estimate the load of migration sources, to
653 * balance conservatively.
655 static inline unsigned long source_load(int cpu)
657 runqueue_t *rq = cpu_rq(cpu);
658 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
660 return min(rq->cpu_load, load_now);
664 * Return a high guess at the load of a migration-target cpu
666 static inline unsigned long target_load(int cpu)
668 runqueue_t *rq = cpu_rq(cpu);
669 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
671 return max(rq->cpu_load, load_now);
677 * wake_idle() is useful especially on SMT architectures to wake a
678 * task onto an idle sibling if we would otherwise wake it onto a
681 * Returns the CPU we should wake onto.
683 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
684 static int wake_idle(int cpu, task_t *p)
687 runqueue_t *rq = cpu_rq(cpu);
688 struct sched_domain *sd;
695 if (!(sd->flags & SD_WAKE_IDLE))
698 cpus_and(tmp, sd->span, cpu_online_map);
699 for_each_cpu_mask(i, tmp) {
700 if (!cpu_isset(i, p->cpus_allowed))
710 static inline int wake_idle(int cpu, task_t *p)
717 * try_to_wake_up - wake up a thread
718 * @p: the to-be-woken-up thread
719 * @state: the mask of task states that can be woken
720 * @sync: do a synchronous wakeup?
722 * Put it on the run-queue if it's not already there. The "current"
723 * thread is always on the run-queue (except when the actual
724 * re-schedule is in progress), and as such you're allowed to do
725 * the simpler "current->state = TASK_RUNNING" to mark yourself
726 * runnable without the overhead of this.
728 * returns failure only if the task is already active.
730 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
732 int cpu, this_cpu, success = 0;
737 unsigned long load, this_load;
738 struct sched_domain *sd;
742 rq = task_rq_lock(p, &flags);
743 old_state = p->state;
744 if (!(old_state & state))
751 this_cpu = smp_processor_id();
754 if (unlikely(task_running(rq, p)))
759 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
762 load = source_load(cpu);
763 this_load = target_load(this_cpu);
766 * If sync wakeup then subtract the (maximum possible) effect of
767 * the currently running task from the load of the current CPU:
770 this_load -= SCHED_LOAD_SCALE;
772 /* Don't pull the task off an idle CPU to a busy one */
773 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
776 new_cpu = this_cpu; /* Wake to this CPU if we can */
779 * Scan domains for affine wakeup and passive balancing
782 for_each_domain(this_cpu, sd) {
783 unsigned int imbalance;
785 * Start passive balancing when half the imbalance_pct
788 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
790 if ( ((sd->flags & SD_WAKE_AFFINE) &&
791 !task_hot(p, rq->timestamp_last_tick, sd))
792 || ((sd->flags & SD_WAKE_BALANCE) &&
793 imbalance*this_load <= 100*load) ) {
795 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
796 * or sd has SD_WAKE_BALANCE and there is an imbalance
798 if (cpu_isset(cpu, sd->span))
803 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
805 new_cpu = wake_idle(new_cpu, p);
806 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
807 set_task_cpu(p, new_cpu);
808 task_rq_unlock(rq, &flags);
809 /* might preempt at this point */
810 rq = task_rq_lock(p, &flags);
811 old_state = p->state;
812 if (!(old_state & state))
817 this_cpu = smp_processor_id();
822 #endif /* CONFIG_SMP */
823 if (old_state == TASK_UNINTERRUPTIBLE) {
824 rq->nr_uninterruptible--;
826 * Tasks on involuntary sleep don't earn
827 * sleep_avg beyond just interactive state.
833 * Sync wakeups (i.e. those types of wakeups where the waker
834 * has indicated that it will leave the CPU in short order)
835 * don't trigger a preemption, if the woken up task will run on
836 * this cpu. (in this case the 'I will reschedule' promise of
837 * the waker guarantees that the freshly woken up task is going
838 * to be considered on this CPU.)
840 activate_task(p, rq, cpu == this_cpu);
841 if (!sync || cpu != this_cpu) {
842 if (TASK_PREEMPTS_CURR(p, rq))
843 resched_task(rq->curr);
848 p->state = TASK_RUNNING;
850 task_rq_unlock(rq, &flags);
855 int fastcall wake_up_process(task_t * p)
857 return try_to_wake_up(p, TASK_STOPPED |
858 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
861 EXPORT_SYMBOL(wake_up_process);
863 int fastcall wake_up_state(task_t *p, unsigned int state)
865 return try_to_wake_up(p, state, 0);
869 * Perform scheduler related setup for a newly forked process p.
870 * p is forked by current.
872 void fastcall sched_fork(task_t *p)
875 * We mark the process as running here, but have not actually
876 * inserted it onto the runqueue yet. This guarantees that
877 * nobody will actually run it, and a signal or other external
878 * event cannot wake it up and insert it on the runqueue either.
880 p->state = TASK_RUNNING;
881 INIT_LIST_HEAD(&p->run_list);
883 spin_lock_init(&p->switch_lock);
884 #ifdef CONFIG_PREEMPT
886 * During context-switch we hold precisely one spinlock, which
887 * schedule_tail drops. (in the common case it's this_rq()->lock,
888 * but it also can be p->switch_lock.) So we compensate with a count
889 * of 1. Also, we want to start with kernel preemption disabled.
891 p->thread_info->preempt_count = 1;
894 * Share the timeslice between parent and child, thus the
895 * total amount of pending timeslices in the system doesn't change,
896 * resulting in more scheduling fairness.
899 p->time_slice = (current->time_slice + 1) >> 1;
901 * The remainder of the first timeslice might be recovered by
902 * the parent if the child exits early enough.
904 p->first_time_slice = 1;
905 current->time_slice >>= 1;
906 p->timestamp = sched_clock();
907 if (!current->time_slice) {
909 * This case is rare, it happens when the parent has only
910 * a single jiffy left from its timeslice. Taking the
911 * runqueue lock is not a problem.
913 current->time_slice = 1;
915 scheduler_tick(0, 0);
923 * wake_up_forked_process - wake up a freshly forked process.
925 * This function will do some initial scheduler statistics housekeeping
926 * that must be done for every newly created process.
928 void fastcall wake_up_forked_process(task_t * p)
931 runqueue_t *rq = task_rq_lock(current, &flags);
933 BUG_ON(p->state != TASK_RUNNING);
936 * We decrease the sleep average of forking parents
937 * and children as well, to keep max-interactive tasks
938 * from forking tasks that are max-interactive.
940 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
941 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
943 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
944 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
946 p->interactive_credit = 0;
948 p->prio = effective_prio(p);
949 set_task_cpu(p, smp_processor_id());
951 if (unlikely(!current->array))
952 __activate_task(p, rq);
954 p->prio = current->prio;
955 list_add_tail(&p->run_list, ¤t->run_list);
956 p->array = current->array;
957 p->array->nr_active++;
960 task_rq_unlock(rq, &flags);
964 * Potentially available exiting-child timeslices are
965 * retrieved here - this way the parent does not get
966 * penalized for creating too many threads.
968 * (this cannot be used to 'generate' timeslices
969 * artificially, because any timeslice recovered here
970 * was given away by the parent in the first place.)
972 void fastcall sched_exit(task_t * p)
977 local_irq_save(flags);
978 if (p->first_time_slice) {
979 p->parent->time_slice += p->time_slice;
980 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
981 p->parent->time_slice = MAX_TIMESLICE;
983 local_irq_restore(flags);
985 * If the child was a (relative-) CPU hog then decrease
986 * the sleep_avg of the parent as well.
988 rq = task_rq_lock(p->parent, &flags);
989 if (p->sleep_avg < p->parent->sleep_avg)
990 p->parent->sleep_avg = p->parent->sleep_avg /
991 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
993 task_rq_unlock(rq, &flags);
997 * finish_task_switch - clean up after a task-switch
998 * @prev: the thread we just switched away from.
1000 * We enter this with the runqueue still locked, and finish_arch_switch()
1001 * will unlock it along with doing any other architecture-specific cleanup
1004 * Note that we may have delayed dropping an mm in context_switch(). If
1005 * so, we finish that here outside of the runqueue lock. (Doing it
1006 * with the lock held can cause deadlocks; see schedule() for
1009 static void finish_task_switch(task_t *prev)
1011 runqueue_t *rq = this_rq();
1012 struct mm_struct *mm = rq->prev_mm;
1013 unsigned long prev_task_flags;
1018 * A task struct has one reference for the use as "current".
1019 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1020 * schedule one last time. The schedule call will never return,
1021 * and the scheduled task must drop that reference.
1022 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1023 * still held, otherwise prev could be scheduled on another cpu, die
1024 * there before we look at prev->state, and then the reference would
1026 * Manfred Spraul <manfred@colorfullife.com>
1028 prev_task_flags = prev->flags;
1029 finish_arch_switch(rq, prev);
1032 if (unlikely(prev_task_flags & PF_DEAD))
1033 put_task_struct(prev);
1037 * schedule_tail - first thing a freshly forked thread must call.
1038 * @prev: the thread we just switched away from.
1040 asmlinkage void schedule_tail(task_t *prev)
1042 finish_task_switch(prev);
1044 if (current->set_child_tid)
1045 put_user(current->pid, current->set_child_tid);
1049 * context_switch - switch to the new MM and the new
1050 * thread's register state.
1053 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1055 struct mm_struct *mm = next->mm;
1056 struct mm_struct *oldmm = prev->active_mm;
1058 if (unlikely(!mm)) {
1059 next->active_mm = oldmm;
1060 atomic_inc(&oldmm->mm_count);
1061 enter_lazy_tlb(oldmm, next);
1063 switch_mm(oldmm, mm, next);
1065 if (unlikely(!prev->mm)) {
1066 prev->active_mm = NULL;
1067 WARN_ON(rq->prev_mm);
1068 rq->prev_mm = oldmm;
1071 /* Here we just switch the register state and the stack. */
1072 switch_to(prev, next, prev);
1078 * nr_running, nr_uninterruptible and nr_context_switches:
1080 * externally visible scheduler statistics: current number of runnable
1081 * threads, current number of uninterruptible-sleeping threads, total
1082 * number of context switches performed since bootup.
1084 unsigned long nr_running(void)
1086 unsigned long i, sum = 0;
1089 sum += cpu_rq(i)->nr_running;
1094 unsigned long nr_uninterruptible(void)
1096 unsigned long i, sum = 0;
1098 for_each_online_cpu(i)
1099 sum += cpu_rq(i)->nr_uninterruptible;
1104 unsigned long long nr_context_switches(void)
1106 unsigned long long i, sum = 0;
1108 for_each_online_cpu(i)
1109 sum += cpu_rq(i)->nr_switches;
1114 unsigned long nr_iowait(void)
1116 unsigned long i, sum = 0;
1118 for_each_online_cpu(i)
1119 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1125 * double_rq_lock - safely lock two runqueues
1127 * Note this does not disable interrupts like task_rq_lock,
1128 * you need to do so manually before calling.
1130 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1133 spin_lock(&rq1->lock);
1136 spin_lock(&rq1->lock);
1137 spin_lock(&rq2->lock);
1139 spin_lock(&rq2->lock);
1140 spin_lock(&rq1->lock);
1146 * double_rq_unlock - safely unlock two runqueues
1148 * Note this does not restore interrupts like task_rq_unlock,
1149 * you need to do so manually after calling.
1151 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1153 spin_unlock(&rq1->lock);
1155 spin_unlock(&rq2->lock);
1168 * find_idlest_cpu - find the least busy runqueue.
1170 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1171 struct sched_domain *sd)
1173 unsigned long load, min_load, this_load;
1178 min_load = ULONG_MAX;
1180 cpus_and(mask, sd->span, cpu_online_map);
1181 cpus_and(mask, mask, p->cpus_allowed);
1183 for_each_cpu_mask(i, mask) {
1184 load = target_load(i);
1186 if (load < min_load) {
1190 /* break out early on an idle CPU: */
1196 /* add +1 to account for the new task */
1197 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1200 * Would with the addition of the new task to the
1201 * current CPU there be an imbalance between this
1202 * CPU and the idlest CPU?
1204 * Use half of the balancing threshold - new-context is
1205 * a good opportunity to balance.
1207 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1214 * wake_up_forked_thread - wake up a freshly forked thread.
1216 * This function will do some initial scheduler statistics housekeeping
1217 * that must be done for every newly created context, and it also does
1218 * runqueue balancing.
1220 void fastcall wake_up_forked_thread(task_t * p)
1222 unsigned long flags;
1223 int this_cpu = get_cpu(), cpu;
1224 struct sched_domain *tmp, *sd = NULL;
1225 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1228 * Find the largest domain that this CPU is part of that
1229 * is willing to balance on clone:
1231 for_each_domain(this_cpu, tmp)
1232 if (tmp->flags & SD_BALANCE_CLONE)
1235 cpu = find_idlest_cpu(p, this_cpu, sd);
1239 local_irq_save(flags);
1242 double_rq_lock(this_rq, rq);
1244 BUG_ON(p->state != TASK_RUNNING);
1247 * We did find_idlest_cpu() unlocked, so in theory
1248 * the mask could have changed - just dont migrate
1251 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1253 double_rq_unlock(this_rq, rq);
1257 * We decrease the sleep average of forking parents
1258 * and children as well, to keep max-interactive tasks
1259 * from forking tasks that are max-interactive.
1261 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1262 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1264 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1265 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1267 p->interactive_credit = 0;
1269 p->prio = effective_prio(p);
1270 set_task_cpu(p, cpu);
1272 if (cpu == this_cpu) {
1273 if (unlikely(!current->array))
1274 __activate_task(p, rq);
1276 p->prio = current->prio;
1277 list_add_tail(&p->run_list, ¤t->run_list);
1278 p->array = current->array;
1279 p->array->nr_active++;
1283 /* Not the local CPU - must adjust timestamp */
1284 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1285 + rq->timestamp_last_tick;
1286 __activate_task(p, rq);
1287 if (TASK_PREEMPTS_CURR(p, rq))
1288 resched_task(rq->curr);
1291 double_rq_unlock(this_rq, rq);
1292 local_irq_restore(flags);
1297 * If dest_cpu is allowed for this process, migrate the task to it.
1298 * This is accomplished by forcing the cpu_allowed mask to only
1299 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1300 * the cpu_allowed mask is restored.
1302 static void sched_migrate_task(task_t *p, int dest_cpu)
1304 migration_req_t req;
1306 unsigned long flags;
1308 rq = task_rq_lock(p, &flags);
1309 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1310 || unlikely(cpu_is_offline(dest_cpu)))
1313 /* force the process onto the specified CPU */
1314 if (migrate_task(p, dest_cpu, &req)) {
1315 /* Need to wait for migration thread (might exit: take ref). */
1316 struct task_struct *mt = rq->migration_thread;
1317 get_task_struct(mt);
1318 task_rq_unlock(rq, &flags);
1319 wake_up_process(mt);
1320 put_task_struct(mt);
1321 wait_for_completion(&req.done);
1325 task_rq_unlock(rq, &flags);
1329 * sched_balance_exec(): find the highest-level, exec-balance-capable
1330 * domain and try to migrate the task to the least loaded CPU.
1332 * execve() is a valuable balancing opportunity, because at this point
1333 * the task has the smallest effective memory and cache footprint.
1335 void sched_balance_exec(void)
1337 struct sched_domain *tmp, *sd = NULL;
1338 int new_cpu, this_cpu = get_cpu();
1340 /* Prefer the current CPU if there's only this task running */
1341 if (this_rq()->nr_running <= 1)
1344 for_each_domain(this_cpu, tmp)
1345 if (tmp->flags & SD_BALANCE_EXEC)
1349 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1350 if (new_cpu != this_cpu) {
1352 sched_migrate_task(current, new_cpu);
1361 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1363 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1365 if (unlikely(!spin_trylock(&busiest->lock))) {
1366 if (busiest < this_rq) {
1367 spin_unlock(&this_rq->lock);
1368 spin_lock(&busiest->lock);
1369 spin_lock(&this_rq->lock);
1371 spin_lock(&busiest->lock);
1376 * pull_task - move a task from a remote runqueue to the local runqueue.
1377 * Both runqueues must be locked.
1380 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1381 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1383 dequeue_task(p, src_array);
1384 src_rq->nr_running--;
1385 set_task_cpu(p, this_cpu);
1386 this_rq->nr_running++;
1387 enqueue_task(p, this_array);
1388 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1389 + this_rq->timestamp_last_tick;
1391 * Note that idle threads have a prio of MAX_PRIO, for this test
1392 * to be always true for them.
1394 if (TASK_PREEMPTS_CURR(p, this_rq))
1395 resched_task(this_rq->curr);
1399 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1402 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1403 struct sched_domain *sd, enum idle_type idle)
1406 * We do not migrate tasks that are:
1407 * 1) running (obviously), or
1408 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1409 * 3) are cache-hot on their current CPU.
1411 if (task_running(rq, p))
1413 if (!cpu_isset(this_cpu, p->cpus_allowed))
1416 /* Aggressive migration if we've failed balancing */
1417 if (idle == NEWLY_IDLE ||
1418 sd->nr_balance_failed < sd->cache_nice_tries) {
1419 if (task_hot(p, rq->timestamp_last_tick, sd))
1427 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1428 * as part of a balancing operation within "domain". Returns the number of
1431 * Called with both runqueues locked.
1433 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1434 unsigned long max_nr_move, struct sched_domain *sd,
1435 enum idle_type idle)
1437 prio_array_t *array, *dst_array;
1438 struct list_head *head, *curr;
1439 int idx, pulled = 0;
1442 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1446 * We first consider expired tasks. Those will likely not be
1447 * executed in the near future, and they are most likely to
1448 * be cache-cold, thus switching CPUs has the least effect
1451 if (busiest->expired->nr_active) {
1452 array = busiest->expired;
1453 dst_array = this_rq->expired;
1455 array = busiest->active;
1456 dst_array = this_rq->active;
1460 /* Start searching at priority 0: */
1464 idx = sched_find_first_bit(array->bitmap);
1466 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1467 if (idx >= MAX_PRIO) {
1468 if (array == busiest->expired && busiest->active->nr_active) {
1469 array = busiest->active;
1470 dst_array = this_rq->active;
1476 head = array->queue + idx;
1479 tmp = list_entry(curr, task_t, run_list);
1483 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1489 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1492 /* We only want to steal up to the prescribed number of tasks. */
1493 if (pulled < max_nr_move) {
1504 * find_busiest_group finds and returns the busiest CPU group within the
1505 * domain. It calculates and returns the number of tasks which should be
1506 * moved to restore balance via the imbalance parameter.
1508 static struct sched_group *
1509 find_busiest_group(struct sched_domain *sd, int this_cpu,
1510 unsigned long *imbalance, enum idle_type idle)
1512 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1513 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1515 max_load = this_load = total_load = total_pwr = 0;
1523 local_group = cpu_isset(this_cpu, group->cpumask);
1525 /* Tally up the load of all CPUs in the group */
1527 cpus_and(tmp, group->cpumask, cpu_online_map);
1528 if (unlikely(cpus_empty(tmp)))
1531 for_each_cpu_mask(i, tmp) {
1532 /* Bias balancing toward cpus of our domain */
1534 load = target_load(i);
1536 load = source_load(i);
1545 total_load += avg_load;
1546 total_pwr += group->cpu_power;
1548 /* Adjust by relative CPU power of the group */
1549 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1552 this_load = avg_load;
1555 } else if (avg_load > max_load) {
1556 max_load = avg_load;
1560 group = group->next;
1561 } while (group != sd->groups);
1563 if (!busiest || this_load >= max_load)
1566 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1568 if (this_load >= avg_load ||
1569 100*max_load <= sd->imbalance_pct*this_load)
1573 * We're trying to get all the cpus to the average_load, so we don't
1574 * want to push ourselves above the average load, nor do we wish to
1575 * reduce the max loaded cpu below the average load, as either of these
1576 * actions would just result in more rebalancing later, and ping-pong
1577 * tasks around. Thus we look for the minimum possible imbalance.
1578 * Negative imbalances (*we* are more loaded than anyone else) will
1579 * be counted as no imbalance for these purposes -- we can't fix that
1580 * by pulling tasks to us. Be careful of negative numbers as they'll
1581 * appear as very large values with unsigned longs.
1583 *imbalance = min(max_load - avg_load, avg_load - this_load);
1585 /* How much load to actually move to equalise the imbalance */
1586 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1589 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1590 unsigned long pwr_now = 0, pwr_move = 0;
1593 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1599 * OK, we don't have enough imbalance to justify moving tasks,
1600 * however we may be able to increase total CPU power used by
1604 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1605 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1606 pwr_now /= SCHED_LOAD_SCALE;
1608 /* Amount of load we'd subtract */
1609 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1611 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1614 /* Amount of load we'd add */
1615 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1618 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1619 pwr_move /= SCHED_LOAD_SCALE;
1621 /* Move if we gain another 8th of a CPU worth of throughput */
1622 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1629 /* Get rid of the scaling factor, rounding down as we divide */
1630 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1635 if (busiest && (idle == NEWLY_IDLE ||
1636 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1646 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1648 static runqueue_t *find_busiest_queue(struct sched_group *group)
1651 unsigned long load, max_load = 0;
1652 runqueue_t *busiest = NULL;
1655 cpus_and(tmp, group->cpumask, cpu_online_map);
1656 for_each_cpu_mask(i, tmp) {
1657 load = source_load(i);
1659 if (load > max_load) {
1661 busiest = cpu_rq(i);
1669 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1670 * tasks if there is an imbalance.
1672 * Called with this_rq unlocked.
1674 static int load_balance(int this_cpu, runqueue_t *this_rq,
1675 struct sched_domain *sd, enum idle_type idle)
1677 struct sched_group *group;
1678 runqueue_t *busiest;
1679 unsigned long imbalance;
1682 spin_lock(&this_rq->lock);
1684 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1688 busiest = find_busiest_queue(group);
1692 * This should be "impossible", but since load
1693 * balancing is inherently racy and statistical,
1694 * it could happen in theory.
1696 if (unlikely(busiest == this_rq)) {
1702 if (busiest->nr_running > 1) {
1704 * Attempt to move tasks. If find_busiest_group has found
1705 * an imbalance but busiest->nr_running <= 1, the group is
1706 * still unbalanced. nr_moved simply stays zero, so it is
1707 * correctly treated as an imbalance.
1709 double_lock_balance(this_rq, busiest);
1710 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1711 imbalance, sd, idle);
1712 spin_unlock(&busiest->lock);
1714 spin_unlock(&this_rq->lock);
1717 sd->nr_balance_failed++;
1719 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1722 spin_lock(&busiest->lock);
1723 if (!busiest->active_balance) {
1724 busiest->active_balance = 1;
1725 busiest->push_cpu = this_cpu;
1728 spin_unlock(&busiest->lock);
1730 wake_up_process(busiest->migration_thread);
1733 * We've kicked active balancing, reset the failure
1736 sd->nr_balance_failed = sd->cache_nice_tries;
1739 sd->nr_balance_failed = 0;
1741 /* We were unbalanced, so reset the balancing interval */
1742 sd->balance_interval = sd->min_interval;
1747 spin_unlock(&this_rq->lock);
1749 /* tune up the balancing interval */
1750 if (sd->balance_interval < sd->max_interval)
1751 sd->balance_interval *= 2;
1757 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1758 * tasks if there is an imbalance.
1760 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
1761 * this_rq is locked.
1763 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
1764 struct sched_domain *sd)
1766 struct sched_group *group;
1767 runqueue_t *busiest = NULL;
1768 unsigned long imbalance;
1771 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
1775 busiest = find_busiest_queue(group);
1776 if (!busiest || busiest == this_rq)
1779 /* Attempt to move tasks */
1780 double_lock_balance(this_rq, busiest);
1782 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1783 imbalance, sd, NEWLY_IDLE);
1785 spin_unlock(&busiest->lock);
1792 * idle_balance is called by schedule() if this_cpu is about to become
1793 * idle. Attempts to pull tasks from other CPUs.
1795 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1797 struct sched_domain *sd;
1799 for_each_domain(this_cpu, sd) {
1800 if (sd->flags & SD_BALANCE_NEWIDLE) {
1801 if (load_balance_newidle(this_cpu, this_rq, sd)) {
1802 /* We've pulled tasks over so stop searching */
1810 * active_load_balance is run by migration threads. It pushes a running
1811 * task off the cpu. It can be required to correctly have at least 1 task
1812 * running on each physical CPU where possible, and not have a physical /
1813 * logical imbalance.
1815 * Called with busiest locked.
1817 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
1819 struct sched_domain *sd;
1820 struct sched_group *group, *busy_group;
1823 if (busiest->nr_running <= 1)
1826 for_each_domain(busiest_cpu, sd)
1827 if (cpu_isset(busiest->push_cpu, sd->span))
1835 while (!cpu_isset(busiest_cpu, group->cpumask))
1836 group = group->next;
1845 if (group == busy_group)
1848 cpus_and(tmp, group->cpumask, cpu_online_map);
1849 if (!cpus_weight(tmp))
1852 for_each_cpu_mask(i, tmp) {
1858 rq = cpu_rq(push_cpu);
1861 * This condition is "impossible", but since load
1862 * balancing is inherently a bit racy and statistical,
1863 * it can trigger.. Reported by Bjorn Helgaas on a
1866 if (unlikely(busiest == rq))
1868 double_lock_balance(busiest, rq);
1869 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
1870 spin_unlock(&rq->lock);
1872 group = group->next;
1873 } while (group != sd->groups);
1877 * rebalance_tick will get called every timer tick, on every CPU.
1879 * It checks each scheduling domain to see if it is due to be balanced,
1880 * and initiates a balancing operation if so.
1882 * Balancing parameters are set up in arch_init_sched_domains.
1885 /* Don't have all balancing operations going off at once */
1886 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
1888 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
1889 enum idle_type idle)
1891 unsigned long old_load, this_load;
1892 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
1893 struct sched_domain *sd;
1895 /* Update our load */
1896 old_load = this_rq->cpu_load;
1897 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
1899 * Round up the averaging division if load is increasing. This
1900 * prevents us from getting stuck on 9 if the load is 10, for
1903 if (this_load > old_load)
1905 this_rq->cpu_load = (old_load + this_load) / 2;
1907 for_each_domain(this_cpu, sd) {
1908 unsigned long interval = sd->balance_interval;
1911 interval *= sd->busy_factor;
1913 /* scale ms to jiffies */
1914 interval = msecs_to_jiffies(interval);
1915 if (unlikely(!interval))
1918 if (j - sd->last_balance >= interval) {
1919 if (load_balance(this_cpu, this_rq, sd, idle)) {
1920 /* We've pulled tasks over so no longer idle */
1923 sd->last_balance += interval;
1929 * on UP we do not need to balance between CPUs:
1931 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
1934 static inline void idle_balance(int cpu, runqueue_t *rq)
1939 static inline int wake_priority_sleeper(runqueue_t *rq)
1941 #ifdef CONFIG_SCHED_SMT
1943 * If an SMT sibling task has been put to sleep for priority
1944 * reasons reschedule the idle task to see if it can now run.
1946 if (rq->nr_running) {
1947 resched_task(rq->idle);
1954 DEFINE_PER_CPU(struct kernel_stat, kstat);
1956 EXPORT_PER_CPU_SYMBOL(kstat);
1959 * We place interactive tasks back into the active array, if possible.
1961 * To guarantee that this does not starve expired tasks we ignore the
1962 * interactivity of a task if the first expired task had to wait more
1963 * than a 'reasonable' amount of time. This deadline timeout is
1964 * load-dependent, as the frequency of array switched decreases with
1965 * increasing number of running tasks. We also ignore the interactivity
1966 * if a better static_prio task has expired:
1968 #define EXPIRED_STARVING(rq) \
1969 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
1970 (jiffies - (rq)->expired_timestamp >= \
1971 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
1972 ((rq)->curr->static_prio > (rq)->best_expired_prio))
1975 * This function gets called by the timer code, with HZ frequency.
1976 * We call it with interrupts disabled.
1978 * It also gets called by the fork code, when changing the parent's
1981 void scheduler_tick(int user_ticks, int sys_ticks)
1983 int cpu = smp_processor_id();
1984 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
1985 runqueue_t *rq = this_rq();
1986 task_t *p = current;
1988 rq->timestamp_last_tick = sched_clock();
1990 if (rcu_pending(cpu))
1991 rcu_check_callbacks(cpu, user_ticks);
1993 /* note: this timer irq context must be accounted for as well */
1994 if (hardirq_count() - HARDIRQ_OFFSET) {
1995 cpustat->irq += sys_ticks;
1997 } else if (softirq_count()) {
1998 cpustat->softirq += sys_ticks;
2002 if (p == rq->idle) {
2003 if (atomic_read(&rq->nr_iowait) > 0)
2004 cpustat->iowait += sys_ticks;
2006 cpustat->idle += sys_ticks;
2007 if (wake_priority_sleeper(rq))
2009 rebalance_tick(cpu, rq, IDLE);
2012 if (TASK_NICE(p) > 0)
2013 cpustat->nice += user_ticks;
2015 cpustat->user += user_ticks;
2016 cpustat->system += sys_ticks;
2018 /* Task might have expired already, but not scheduled off yet */
2019 if (p->array != rq->active) {
2020 set_tsk_need_resched(p);
2023 spin_lock(&rq->lock);
2025 * The task was running during this tick - update the
2026 * time slice counter. Note: we do not update a thread's
2027 * priority until it either goes to sleep or uses up its
2028 * timeslice. This makes it possible for interactive tasks
2029 * to use up their timeslices at their highest priority levels.
2031 if (unlikely(rt_task(p))) {
2033 * RR tasks need a special form of timeslice management.
2034 * FIFO tasks have no timeslices.
2036 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2037 p->time_slice = task_timeslice(p);
2038 p->first_time_slice = 0;
2039 set_tsk_need_resched(p);
2041 /* put it at the end of the queue: */
2042 dequeue_task(p, rq->active);
2043 enqueue_task(p, rq->active);
2047 if (!--p->time_slice) {
2048 dequeue_task(p, rq->active);
2049 set_tsk_need_resched(p);
2050 p->prio = effective_prio(p);
2051 p->time_slice = task_timeslice(p);
2052 p->first_time_slice = 0;
2054 if (!rq->expired_timestamp)
2055 rq->expired_timestamp = jiffies;
2056 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2057 enqueue_task(p, rq->expired);
2058 if (p->static_prio < rq->best_expired_prio)
2059 rq->best_expired_prio = p->static_prio;
2061 enqueue_task(p, rq->active);
2064 * Prevent a too long timeslice allowing a task to monopolize
2065 * the CPU. We do this by splitting up the timeslice into
2068 * Note: this does not mean the task's timeslices expire or
2069 * get lost in any way, they just might be preempted by
2070 * another task of equal priority. (one with higher
2071 * priority would have preempted this task already.) We
2072 * requeue this task to the end of the list on this priority
2073 * level, which is in essence a round-robin of tasks with
2076 * This only applies to tasks in the interactive
2077 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2079 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2080 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2081 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2082 (p->array == rq->active)) {
2084 dequeue_task(p, rq->active);
2085 set_tsk_need_resched(p);
2086 p->prio = effective_prio(p);
2087 enqueue_task(p, rq->active);
2091 spin_unlock(&rq->lock);
2093 rebalance_tick(cpu, rq, NOT_IDLE);
2096 #ifdef CONFIG_SCHED_SMT
2097 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2100 struct sched_domain *sd = rq->sd;
2101 cpumask_t sibling_map;
2103 if (!(sd->flags & SD_SHARE_CPUPOWER))
2106 cpus_and(sibling_map, sd->span, cpu_online_map);
2107 for_each_cpu_mask(i, sibling_map) {
2116 * If an SMT sibling task is sleeping due to priority
2117 * reasons wake it up now.
2119 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2120 resched_task(smt_rq->idle);
2124 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2126 struct sched_domain *sd = rq->sd;
2127 cpumask_t sibling_map;
2130 if (!(sd->flags & SD_SHARE_CPUPOWER))
2133 cpus_and(sibling_map, sd->span, cpu_online_map);
2134 for_each_cpu_mask(i, sibling_map) {
2142 smt_curr = smt_rq->curr;
2145 * If a user task with lower static priority than the
2146 * running task on the SMT sibling is trying to schedule,
2147 * delay it till there is proportionately less timeslice
2148 * left of the sibling task to prevent a lower priority
2149 * task from using an unfair proportion of the
2150 * physical cpu's resources. -ck
2152 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2153 task_timeslice(p) || rt_task(smt_curr)) &&
2154 p->mm && smt_curr->mm && !rt_task(p))
2158 * Reschedule a lower priority task on the SMT sibling,
2159 * or wake it up if it has been put to sleep for priority
2162 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2163 task_timeslice(smt_curr) || rt_task(p)) &&
2164 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2165 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2166 resched_task(smt_curr);
2171 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2175 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2182 * schedule() is the main scheduler function.
2184 asmlinkage void __sched schedule(void)
2187 task_t *prev, *next;
2189 prio_array_t *array;
2190 struct list_head *queue;
2191 unsigned long long now;
2192 unsigned long run_time;
2196 * Test if we are atomic. Since do_exit() needs to call into
2197 * schedule() atomically, we ignore that path for now.
2198 * Otherwise, whine if we are scheduling when we should not be.
2200 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2201 if (unlikely(in_atomic())) {
2202 printk(KERN_ERR "bad: scheduling while atomic!\n");
2212 release_kernel_lock(prev);
2213 now = sched_clock();
2214 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2215 run_time = now - prev->timestamp;
2217 run_time = NS_MAX_SLEEP_AVG;
2220 * Tasks with interactive credits get charged less run_time
2221 * at high sleep_avg to delay them losing their interactive
2224 if (HIGH_CREDIT(prev))
2225 run_time /= (CURRENT_BONUS(prev) ? : 1);
2227 spin_lock_irq(&rq->lock);
2230 * if entering off of a kernel preemption go straight
2231 * to picking the next task.
2233 switch_count = &prev->nivcsw;
2234 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2235 switch_count = &prev->nvcsw;
2236 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2237 unlikely(signal_pending(prev))))
2238 prev->state = TASK_RUNNING;
2240 deactivate_task(prev, rq);
2243 cpu = smp_processor_id();
2244 if (unlikely(!rq->nr_running)) {
2245 idle_balance(cpu, rq);
2246 if (!rq->nr_running) {
2248 rq->expired_timestamp = 0;
2249 wake_sleeping_dependent(cpu, rq);
2255 if (unlikely(!array->nr_active)) {
2257 * Switch the active and expired arrays.
2259 rq->active = rq->expired;
2260 rq->expired = array;
2262 rq->expired_timestamp = 0;
2263 rq->best_expired_prio = MAX_PRIO;
2266 idx = sched_find_first_bit(array->bitmap);
2267 queue = array->queue + idx;
2268 next = list_entry(queue->next, task_t, run_list);
2270 if (dependent_sleeper(cpu, rq, next)) {
2275 if (!rt_task(next) && next->activated > 0) {
2276 unsigned long long delta = now - next->timestamp;
2278 if (next->activated == 1)
2279 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2281 array = next->array;
2282 dequeue_task(next, array);
2283 recalc_task_prio(next, next->timestamp + delta);
2284 enqueue_task(next, array);
2286 next->activated = 0;
2289 clear_tsk_need_resched(prev);
2290 RCU_qsctr(task_cpu(prev))++;
2292 prev->sleep_avg -= run_time;
2293 if ((long)prev->sleep_avg <= 0) {
2294 prev->sleep_avg = 0;
2295 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2296 prev->interactive_credit--;
2298 prev->timestamp = now;
2300 if (likely(prev != next)) {
2301 next->timestamp = now;
2306 prepare_arch_switch(rq, next);
2307 prev = context_switch(rq, prev, next);
2310 finish_task_switch(prev);
2312 spin_unlock_irq(&rq->lock);
2314 reacquire_kernel_lock(current);
2315 preempt_enable_no_resched();
2316 if (test_thread_flag(TIF_NEED_RESCHED))
2320 EXPORT_SYMBOL(schedule);
2322 #ifdef CONFIG_PREEMPT
2324 * this is is the entry point to schedule() from in-kernel preemption
2325 * off of preempt_enable. Kernel preemptions off return from interrupt
2326 * occur there and call schedule directly.
2328 asmlinkage void __sched preempt_schedule(void)
2330 struct thread_info *ti = current_thread_info();
2333 * If there is a non-zero preempt_count or interrupts are disabled,
2334 * we do not want to preempt the current task. Just return..
2336 if (unlikely(ti->preempt_count || irqs_disabled()))
2340 ti->preempt_count = PREEMPT_ACTIVE;
2342 ti->preempt_count = 0;
2344 /* we could miss a preemption opportunity between schedule and now */
2346 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2350 EXPORT_SYMBOL(preempt_schedule);
2351 #endif /* CONFIG_PREEMPT */
2353 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2355 task_t *p = curr->task;
2356 return try_to_wake_up(p, mode, sync);
2359 EXPORT_SYMBOL(default_wake_function);
2362 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2363 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2364 * number) then we wake all the non-exclusive tasks and one exclusive task.
2366 * There are circumstances in which we can try to wake a task which has already
2367 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2368 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2370 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2371 int nr_exclusive, int sync, void *key)
2373 struct list_head *tmp, *next;
2375 list_for_each_safe(tmp, next, &q->task_list) {
2378 curr = list_entry(tmp, wait_queue_t, task_list);
2379 flags = curr->flags;
2380 if (curr->func(curr, mode, sync, key) &&
2381 (flags & WQ_FLAG_EXCLUSIVE) &&
2388 * __wake_up - wake up threads blocked on a waitqueue.
2390 * @mode: which threads
2391 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2393 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2394 int nr_exclusive, void *key)
2396 unsigned long flags;
2398 spin_lock_irqsave(&q->lock, flags);
2399 __wake_up_common(q, mode, nr_exclusive, 0, key);
2400 spin_unlock_irqrestore(&q->lock, flags);
2403 EXPORT_SYMBOL(__wake_up);
2406 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2408 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2410 __wake_up_common(q, mode, 1, 0, NULL);
2414 * __wake_up - sync- wake up threads blocked on a waitqueue.
2416 * @mode: which threads
2417 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2419 * The sync wakeup differs that the waker knows that it will schedule
2420 * away soon, so while the target thread will be woken up, it will not
2421 * be migrated to another CPU - ie. the two threads are 'synchronized'
2422 * with each other. This can prevent needless bouncing between CPUs.
2424 * On UP it can prevent extra preemption.
2426 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2428 unsigned long flags;
2434 if (unlikely(!nr_exclusive))
2437 spin_lock_irqsave(&q->lock, flags);
2438 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2439 spin_unlock_irqrestore(&q->lock, flags);
2441 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2443 void fastcall complete(struct completion *x)
2445 unsigned long flags;
2447 spin_lock_irqsave(&x->wait.lock, flags);
2449 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2451 spin_unlock_irqrestore(&x->wait.lock, flags);
2453 EXPORT_SYMBOL(complete);
2455 void fastcall complete_all(struct completion *x)
2457 unsigned long flags;
2459 spin_lock_irqsave(&x->wait.lock, flags);
2460 x->done += UINT_MAX/2;
2461 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2463 spin_unlock_irqrestore(&x->wait.lock, flags);
2465 EXPORT_SYMBOL(complete_all);
2467 void fastcall __sched wait_for_completion(struct completion *x)
2470 spin_lock_irq(&x->wait.lock);
2472 DECLARE_WAITQUEUE(wait, current);
2474 wait.flags |= WQ_FLAG_EXCLUSIVE;
2475 __add_wait_queue_tail(&x->wait, &wait);
2477 __set_current_state(TASK_UNINTERRUPTIBLE);
2478 spin_unlock_irq(&x->wait.lock);
2480 spin_lock_irq(&x->wait.lock);
2482 __remove_wait_queue(&x->wait, &wait);
2485 spin_unlock_irq(&x->wait.lock);
2487 EXPORT_SYMBOL(wait_for_completion);
2489 #define SLEEP_ON_VAR \
2490 unsigned long flags; \
2491 wait_queue_t wait; \
2492 init_waitqueue_entry(&wait, current);
2494 #define SLEEP_ON_HEAD \
2495 spin_lock_irqsave(&q->lock,flags); \
2496 __add_wait_queue(q, &wait); \
2497 spin_unlock(&q->lock);
2499 #define SLEEP_ON_TAIL \
2500 spin_lock_irq(&q->lock); \
2501 __remove_wait_queue(q, &wait); \
2502 spin_unlock_irqrestore(&q->lock, flags);
2504 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2508 current->state = TASK_INTERRUPTIBLE;
2515 EXPORT_SYMBOL(interruptible_sleep_on);
2517 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2521 current->state = TASK_INTERRUPTIBLE;
2524 timeout = schedule_timeout(timeout);
2530 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2532 void fastcall __sched sleep_on(wait_queue_head_t *q)
2536 current->state = TASK_UNINTERRUPTIBLE;
2543 EXPORT_SYMBOL(sleep_on);
2545 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2549 current->state = TASK_UNINTERRUPTIBLE;
2552 timeout = schedule_timeout(timeout);
2558 EXPORT_SYMBOL(sleep_on_timeout);
2560 void set_user_nice(task_t *p, long nice)
2562 unsigned long flags;
2563 prio_array_t *array;
2565 int old_prio, new_prio, delta;
2567 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2570 * We have to be careful, if called from sys_setpriority(),
2571 * the task might be in the middle of scheduling on another CPU.
2573 rq = task_rq_lock(p, &flags);
2575 * The RT priorities are set via setscheduler(), but we still
2576 * allow the 'normal' nice value to be set - but as expected
2577 * it wont have any effect on scheduling until the task is
2581 p->static_prio = NICE_TO_PRIO(nice);
2586 dequeue_task(p, array);
2589 new_prio = NICE_TO_PRIO(nice);
2590 delta = new_prio - old_prio;
2591 p->static_prio = NICE_TO_PRIO(nice);
2595 enqueue_task(p, array);
2597 * If the task increased its priority or is running and
2598 * lowered its priority, then reschedule its CPU:
2600 if (delta < 0 || (delta > 0 && task_running(rq, p)))
2601 resched_task(rq->curr);
2604 task_rq_unlock(rq, &flags);
2607 EXPORT_SYMBOL(set_user_nice);
2609 #ifdef __ARCH_WANT_SYS_NICE
2612 * sys_nice - change the priority of the current process.
2613 * @increment: priority increment
2615 * sys_setpriority is a more generic, but much slower function that
2616 * does similar things.
2618 asmlinkage long sys_nice(int increment)
2624 * Setpriority might change our priority at the same moment.
2625 * We don't have to worry. Conceptually one call occurs first
2626 * and we have a single winner.
2628 if (increment < 0) {
2629 if (!capable(CAP_SYS_NICE))
2631 if (increment < -40)
2637 nice = PRIO_TO_NICE(current->static_prio) + increment;
2643 retval = security_task_setnice(current, nice);
2647 set_user_nice(current, nice);
2654 * task_prio - return the priority value of a given task.
2655 * @p: the task in question.
2657 * This is the priority value as seen by users in /proc.
2658 * RT tasks are offset by -200. Normal tasks are centered
2659 * around 0, value goes from -16 to +15.
2661 int task_prio(task_t *p)
2663 return p->prio - MAX_RT_PRIO;
2667 * task_nice - return the nice value of a given task.
2668 * @p: the task in question.
2670 int task_nice(task_t *p)
2672 return TASK_NICE(p);
2675 EXPORT_SYMBOL(task_nice);
2678 * idle_cpu - is a given cpu idle currently?
2679 * @cpu: the processor in question.
2681 int idle_cpu(int cpu)
2683 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
2686 EXPORT_SYMBOL_GPL(idle_cpu);
2689 * find_process_by_pid - find a process with a matching PID value.
2690 * @pid: the pid in question.
2692 static inline task_t *find_process_by_pid(pid_t pid)
2694 return pid ? find_task_by_pid(pid) : current;
2697 /* Actually do priority change: must hold rq lock. */
2698 static void __setscheduler(struct task_struct *p, int policy, int prio)
2702 p->rt_priority = prio;
2703 if (policy != SCHED_NORMAL)
2704 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
2706 p->prio = p->static_prio;
2710 * setscheduler - change the scheduling policy and/or RT priority of a thread.
2712 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
2714 struct sched_param lp;
2715 int retval = -EINVAL;
2717 prio_array_t *array;
2718 unsigned long flags;
2722 if (!param || pid < 0)
2726 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
2730 * We play safe to avoid deadlocks.
2732 read_lock_irq(&tasklist_lock);
2734 p = find_process_by_pid(pid);
2738 goto out_unlock_tasklist;
2741 * To be able to change p->policy safely, the apropriate
2742 * runqueue lock must be held.
2744 rq = task_rq_lock(p, &flags);
2750 if (policy != SCHED_FIFO && policy != SCHED_RR &&
2751 policy != SCHED_NORMAL)
2756 * Valid priorities for SCHED_FIFO and SCHED_RR are
2757 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
2760 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
2762 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
2766 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
2767 !capable(CAP_SYS_NICE))
2769 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2770 !capable(CAP_SYS_NICE))
2773 retval = security_task_setscheduler(p, policy, &lp);
2779 deactivate_task(p, task_rq(p));
2782 __setscheduler(p, policy, lp.sched_priority);
2784 __activate_task(p, task_rq(p));
2786 * Reschedule if we are currently running on this runqueue and
2787 * our priority decreased, or if we are not currently running on
2788 * this runqueue and our priority is higher than the current's
2790 if (task_running(rq, p)) {
2791 if (p->prio > oldprio)
2792 resched_task(rq->curr);
2793 } else if (TASK_PREEMPTS_CURR(p, rq))
2794 resched_task(rq->curr);
2798 task_rq_unlock(rq, &flags);
2799 out_unlock_tasklist:
2800 read_unlock_irq(&tasklist_lock);
2807 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
2808 * @pid: the pid in question.
2809 * @policy: new policy
2810 * @param: structure containing the new RT priority.
2812 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
2813 struct sched_param __user *param)
2815 return setscheduler(pid, policy, param);
2819 * sys_sched_setparam - set/change the RT priority of a thread
2820 * @pid: the pid in question.
2821 * @param: structure containing the new RT priority.
2823 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
2825 return setscheduler(pid, -1, param);
2829 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
2830 * @pid: the pid in question.
2832 asmlinkage long sys_sched_getscheduler(pid_t pid)
2834 int retval = -EINVAL;
2841 read_lock(&tasklist_lock);
2842 p = find_process_by_pid(pid);
2844 retval = security_task_getscheduler(p);
2848 read_unlock(&tasklist_lock);
2855 * sys_sched_getscheduler - get the RT priority of a thread
2856 * @pid: the pid in question.
2857 * @param: structure containing the RT priority.
2859 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
2861 struct sched_param lp;
2862 int retval = -EINVAL;
2865 if (!param || pid < 0)
2868 read_lock(&tasklist_lock);
2869 p = find_process_by_pid(pid);
2874 retval = security_task_getscheduler(p);
2878 lp.sched_priority = p->rt_priority;
2879 read_unlock(&tasklist_lock);
2882 * This one might sleep, we cannot do it with a spinlock held ...
2884 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
2890 read_unlock(&tasklist_lock);
2895 * sys_sched_setaffinity - set the cpu affinity of a process
2896 * @pid: pid of the process
2897 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2898 * @user_mask_ptr: user-space pointer to the new cpu mask
2900 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
2901 unsigned long __user *user_mask_ptr)
2907 if (len < sizeof(new_mask))
2910 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
2914 read_lock(&tasklist_lock);
2916 p = find_process_by_pid(pid);
2918 read_unlock(&tasklist_lock);
2919 unlock_cpu_hotplug();
2924 * It is not safe to call set_cpus_allowed with the
2925 * tasklist_lock held. We will bump the task_struct's
2926 * usage count and then drop tasklist_lock.
2929 read_unlock(&tasklist_lock);
2932 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2933 !capable(CAP_SYS_NICE))
2936 retval = set_cpus_allowed(p, new_mask);
2940 unlock_cpu_hotplug();
2945 * sys_sched_getaffinity - get the cpu affinity of a process
2946 * @pid: pid of the process
2947 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2948 * @user_mask_ptr: user-space pointer to hold the current cpu mask
2950 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
2951 unsigned long __user *user_mask_ptr)
2953 unsigned int real_len;
2958 real_len = sizeof(mask);
2963 read_lock(&tasklist_lock);
2966 p = find_process_by_pid(pid);
2971 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
2974 read_unlock(&tasklist_lock);
2975 unlock_cpu_hotplug();
2978 if (copy_to_user(user_mask_ptr, &mask, real_len))
2984 * sys_sched_yield - yield the current processor to other threads.
2986 * this function yields the current CPU by moving the calling thread
2987 * to the expired array. If there are no other threads running on this
2988 * CPU then this function will return.
2990 asmlinkage long sys_sched_yield(void)
2992 runqueue_t *rq = this_rq_lock();
2993 prio_array_t *array = current->array;
2994 prio_array_t *target = rq->expired;
2997 * We implement yielding by moving the task into the expired
3000 * (special rule: RT tasks will just roundrobin in the active
3003 if (unlikely(rt_task(current)))
3004 target = rq->active;
3006 dequeue_task(current, array);
3007 enqueue_task(current, target);
3010 * Since we are going to call schedule() anyway, there's
3011 * no need to preempt or enable interrupts:
3013 _raw_spin_unlock(&rq->lock);
3014 preempt_enable_no_resched();
3021 void __sched __cond_resched(void)
3023 set_current_state(TASK_RUNNING);
3027 EXPORT_SYMBOL(__cond_resched);
3030 * yield - yield the current processor to other threads.
3032 * this is a shortcut for kernel-space yielding - it marks the
3033 * thread runnable and calls sys_sched_yield().
3035 void __sched yield(void)
3037 set_current_state(TASK_RUNNING);
3041 EXPORT_SYMBOL(yield);
3044 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3045 * that process accounting knows that this is a task in IO wait state.
3047 * But don't do that if it is a deliberate, throttling IO wait (this task
3048 * has set its backing_dev_info: the queue against which it should throttle)
3050 void __sched io_schedule(void)
3052 struct runqueue *rq = this_rq();
3054 atomic_inc(&rq->nr_iowait);
3056 atomic_dec(&rq->nr_iowait);
3059 EXPORT_SYMBOL(io_schedule);
3061 long __sched io_schedule_timeout(long timeout)
3063 struct runqueue *rq = this_rq();
3066 atomic_inc(&rq->nr_iowait);
3067 ret = schedule_timeout(timeout);
3068 atomic_dec(&rq->nr_iowait);
3073 * sys_sched_get_priority_max - return maximum RT priority.
3074 * @policy: scheduling class.
3076 * this syscall returns the maximum rt_priority that can be used
3077 * by a given scheduling class.
3079 asmlinkage long sys_sched_get_priority_max(int policy)
3086 ret = MAX_USER_RT_PRIO-1;
3096 * sys_sched_get_priority_min - return minimum RT priority.
3097 * @policy: scheduling class.
3099 * this syscall returns the minimum rt_priority that can be used
3100 * by a given scheduling class.
3102 asmlinkage long sys_sched_get_priority_min(int policy)
3118 * sys_sched_rr_get_interval - return the default timeslice of a process.
3119 * @pid: pid of the process.
3120 * @interval: userspace pointer to the timeslice value.
3122 * this syscall writes the default timeslice value of a given process
3123 * into the user-space timespec buffer. A value of '0' means infinity.
3126 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3128 int retval = -EINVAL;
3136 read_lock(&tasklist_lock);
3137 p = find_process_by_pid(pid);
3141 retval = security_task_getscheduler(p);
3145 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3146 0 : task_timeslice(p), &t);
3147 read_unlock(&tasklist_lock);
3148 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3152 read_unlock(&tasklist_lock);
3156 static inline struct task_struct *eldest_child(struct task_struct *p)
3158 if (list_empty(&p->children)) return NULL;
3159 return list_entry(p->children.next,struct task_struct,sibling);
3162 static inline struct task_struct *older_sibling(struct task_struct *p)
3164 if (p->sibling.prev==&p->parent->children) return NULL;
3165 return list_entry(p->sibling.prev,struct task_struct,sibling);
3168 static inline struct task_struct *younger_sibling(struct task_struct *p)
3170 if (p->sibling.next==&p->parent->children) return NULL;
3171 return list_entry(p->sibling.next,struct task_struct,sibling);
3174 static void show_task(task_t * p)
3178 unsigned long free = 0;
3179 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3181 printk("%-13.13s ", p->comm);
3182 state = p->state ? __ffs(p->state) + 1 : 0;
3183 if (state < ARRAY_SIZE(stat_nam))
3184 printk(stat_nam[state]);
3187 #if (BITS_PER_LONG == 32)
3188 if (state == TASK_RUNNING)
3189 printk(" running ");
3191 printk(" %08lX ", thread_saved_pc(p));
3193 if (state == TASK_RUNNING)
3194 printk(" running task ");
3196 printk(" %016lx ", thread_saved_pc(p));
3198 #ifdef CONFIG_DEBUG_STACK_USAGE
3200 unsigned long * n = (unsigned long *) (p->thread_info+1);
3203 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3206 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3207 if ((relative = eldest_child(p)))
3208 printk("%5d ", relative->pid);
3211 if ((relative = younger_sibling(p)))
3212 printk("%7d", relative->pid);
3215 if ((relative = older_sibling(p)))
3216 printk(" %5d", relative->pid);
3220 printk(" (L-TLB)\n");
3222 printk(" (NOTLB)\n");
3224 if (state != TASK_RUNNING)
3225 show_stack(p, NULL);
3228 void show_state(void)
3232 #if (BITS_PER_LONG == 32)
3235 printk(" task PC pid father child younger older\n");
3239 printk(" task PC pid father child younger older\n");
3241 read_lock(&tasklist_lock);
3242 do_each_thread(g, p) {
3244 * reset the NMI-timeout, listing all files on a slow
3245 * console might take alot of time:
3247 touch_nmi_watchdog();
3249 } while_each_thread(g, p);
3251 read_unlock(&tasklist_lock);
3254 void __devinit init_idle(task_t *idle, int cpu)
3256 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3257 unsigned long flags;
3259 local_irq_save(flags);
3260 double_rq_lock(idle_rq, rq);
3262 idle_rq->curr = idle_rq->idle = idle;
3263 deactivate_task(idle, rq);
3265 idle->prio = MAX_PRIO;
3266 idle->state = TASK_RUNNING;
3267 set_task_cpu(idle, cpu);
3268 double_rq_unlock(idle_rq, rq);
3269 set_tsk_need_resched(idle);
3270 local_irq_restore(flags);
3272 /* Set the preempt count _outside_ the spinlocks! */
3273 #ifdef CONFIG_PREEMPT
3274 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3276 idle->thread_info->preempt_count = 0;
3281 * In a system that switches off the HZ timer nohz_cpu_mask
3282 * indicates which cpus entered this state. This is used
3283 * in the rcu update to wait only for active cpus. For system
3284 * which do not switch off the HZ timer nohz_cpu_mask should
3285 * always be CPU_MASK_NONE.
3287 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3291 * This is how migration works:
3293 * 1) we queue a migration_req_t structure in the source CPU's
3294 * runqueue and wake up that CPU's migration thread.
3295 * 2) we down() the locked semaphore => thread blocks.
3296 * 3) migration thread wakes up (implicitly it forces the migrated
3297 * thread off the CPU)
3298 * 4) it gets the migration request and checks whether the migrated
3299 * task is still in the wrong runqueue.
3300 * 5) if it's in the wrong runqueue then the migration thread removes
3301 * it and puts it into the right queue.
3302 * 6) migration thread up()s the semaphore.
3303 * 7) we wake up and the migration is done.
3307 * Change a given task's CPU affinity. Migrate the thread to a
3308 * proper CPU and schedule it away if the CPU it's executing on
3309 * is removed from the allowed bitmask.
3311 * NOTE: the caller must have a valid reference to the task, the
3312 * task must not exit() & deallocate itself prematurely. The
3313 * call is not atomic; no spinlocks may be held.
3315 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3317 unsigned long flags;
3319 migration_req_t req;
3322 rq = task_rq_lock(p, &flags);
3323 if (any_online_cpu(new_mask) == NR_CPUS) {
3328 p->cpus_allowed = new_mask;
3329 /* Can the task run on the task's current CPU? If so, we're done */
3330 if (cpu_isset(task_cpu(p), new_mask))
3333 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3334 /* Need help from migration thread: drop lock and wait. */
3335 task_rq_unlock(rq, &flags);
3336 wake_up_process(rq->migration_thread);
3337 wait_for_completion(&req.done);
3341 task_rq_unlock(rq, &flags);
3345 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3348 * Move (not current) task off this cpu, onto dest cpu. We're doing
3349 * this because either it can't run here any more (set_cpus_allowed()
3350 * away from this CPU, or CPU going down), or because we're
3351 * attempting to rebalance this task on exec (sched_balance_exec).
3353 * So we race with normal scheduler movements, but that's OK, as long
3354 * as the task is no longer on this CPU.
3356 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3358 runqueue_t *rq_dest, *rq_src;
3360 if (unlikely(cpu_is_offline(dest_cpu)))
3363 rq_src = cpu_rq(src_cpu);
3364 rq_dest = cpu_rq(dest_cpu);
3366 double_rq_lock(rq_src, rq_dest);
3367 /* Already moved. */
3368 if (task_cpu(p) != src_cpu)
3370 /* Affinity changed (again). */
3371 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3374 set_task_cpu(p, dest_cpu);
3377 * Sync timestamp with rq_dest's before activating.
3378 * The same thing could be achieved by doing this step
3379 * afterwards, and pretending it was a local activate.
3380 * This way is cleaner and logically correct.
3382 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3383 + rq_dest->timestamp_last_tick;
3384 deactivate_task(p, rq_src);
3385 activate_task(p, rq_dest, 0);
3386 if (TASK_PREEMPTS_CURR(p, rq_dest))
3387 resched_task(rq_dest->curr);
3391 double_rq_unlock(rq_src, rq_dest);
3395 * migration_thread - this is a highprio system thread that performs
3396 * thread migration by bumping thread off CPU then 'pushing' onto
3399 static int migration_thread(void * data)
3402 int cpu = (long)data;
3405 BUG_ON(rq->migration_thread != current);
3407 set_current_state(TASK_INTERRUPTIBLE);
3408 while (!kthread_should_stop()) {
3409 struct list_head *head;
3410 migration_req_t *req;
3412 if (current->flags & PF_FREEZE)
3413 refrigerator(PF_FREEZE);
3415 spin_lock_irq(&rq->lock);
3417 if (cpu_is_offline(cpu)) {
3418 spin_unlock_irq(&rq->lock);
3422 if (rq->active_balance) {
3423 active_load_balance(rq, cpu);
3424 rq->active_balance = 0;
3427 head = &rq->migration_queue;
3429 if (list_empty(head)) {
3430 spin_unlock_irq(&rq->lock);
3432 set_current_state(TASK_INTERRUPTIBLE);
3435 req = list_entry(head->next, migration_req_t, list);
3436 list_del_init(head->next);
3438 if (req->type == REQ_MOVE_TASK) {
3439 spin_unlock(&rq->lock);
3440 __migrate_task(req->task, smp_processor_id(),
3443 } else if (req->type == REQ_SET_DOMAIN) {
3445 spin_unlock_irq(&rq->lock);
3447 spin_unlock_irq(&rq->lock);
3451 complete(&req->done);
3453 __set_current_state(TASK_RUNNING);
3457 /* Wait for kthread_stop */
3458 set_current_state(TASK_INTERRUPTIBLE);
3459 while (!kthread_should_stop()) {
3461 set_current_state(TASK_INTERRUPTIBLE);
3463 __set_current_state(TASK_RUNNING);
3467 #ifdef CONFIG_HOTPLUG_CPU
3468 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
3469 static void migrate_all_tasks(int src_cpu)
3471 struct task_struct *tsk, *t;
3475 write_lock_irq(&tasklist_lock);
3477 /* watch out for per node tasks, let's stay on this node */
3478 node = cpu_to_node(src_cpu);
3480 do_each_thread(t, tsk) {
3485 if (task_cpu(tsk) != src_cpu)
3488 /* Figure out where this task should go (attempting to
3489 * keep it on-node), and check if it can be migrated
3490 * as-is. NOTE that kernel threads bound to more than
3491 * one online cpu will be migrated. */
3492 mask = node_to_cpumask(node);
3493 cpus_and(mask, mask, tsk->cpus_allowed);
3494 dest_cpu = any_online_cpu(mask);
3495 if (dest_cpu == NR_CPUS)
3496 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3497 if (dest_cpu == NR_CPUS) {
3498 cpus_clear(tsk->cpus_allowed);
3499 cpus_complement(tsk->cpus_allowed);
3500 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3502 /* Don't tell them about moving exiting tasks
3503 or kernel threads (both mm NULL), since
3504 they never leave kernel. */
3505 if (tsk->mm && printk_ratelimit())
3506 printk(KERN_INFO "process %d (%s) no "
3507 "longer affine to cpu%d\n",
3508 tsk->pid, tsk->comm, src_cpu);
3511 __migrate_task(tsk, src_cpu, dest_cpu);
3512 } while_each_thread(t, tsk);
3514 write_unlock_irq(&tasklist_lock);
3517 /* Schedules idle task to be the next runnable task on current CPU.
3518 * It does so by boosting its priority to highest possible and adding it to
3519 * the _front_ of runqueue. Used by CPU offline code.
3521 void sched_idle_next(void)
3523 int cpu = smp_processor_id();
3524 runqueue_t *rq = this_rq();
3525 struct task_struct *p = rq->idle;
3526 unsigned long flags;
3528 /* cpu has to be offline */
3529 BUG_ON(cpu_online(cpu));
3531 /* Strictly not necessary since rest of the CPUs are stopped by now
3532 * and interrupts disabled on current cpu.
3534 spin_lock_irqsave(&rq->lock, flags);
3536 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3537 /* Add idle task to _front_ of it's priority queue */
3538 __activate_idle_task(p, rq);
3540 spin_unlock_irqrestore(&rq->lock, flags);
3542 #endif /* CONFIG_HOTPLUG_CPU */
3545 * migration_call - callback that gets triggered when a CPU is added.
3546 * Here we can start up the necessary migration thread for the new CPU.
3548 static int migration_call(struct notifier_block *nfb, unsigned long action,
3551 int cpu = (long)hcpu;
3552 struct task_struct *p;
3553 struct runqueue *rq;
3554 unsigned long flags;
3557 case CPU_UP_PREPARE:
3558 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
3561 kthread_bind(p, cpu);
3562 /* Must be high prio: stop_machine expects to yield to it. */
3563 rq = task_rq_lock(p, &flags);
3564 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3565 task_rq_unlock(rq, &flags);
3566 cpu_rq(cpu)->migration_thread = p;
3569 /* Strictly unneccessary, as first user will wake it. */
3570 wake_up_process(cpu_rq(cpu)->migration_thread);
3572 #ifdef CONFIG_HOTPLUG_CPU
3573 case CPU_UP_CANCELED:
3574 /* Unbind it from offline cpu so it can run. Fall thru. */
3575 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
3576 kthread_stop(cpu_rq(cpu)->migration_thread);
3577 cpu_rq(cpu)->migration_thread = NULL;
3580 migrate_all_tasks(cpu);
3582 kthread_stop(rq->migration_thread);
3583 rq->migration_thread = NULL;
3584 /* Idle task back to normal (off runqueue, low prio) */
3585 rq = task_rq_lock(rq->idle, &flags);
3586 deactivate_task(rq->idle, rq);
3587 rq->idle->static_prio = MAX_PRIO;
3588 __setscheduler(rq->idle, SCHED_NORMAL, 0);
3589 task_rq_unlock(rq, &flags);
3590 BUG_ON(rq->nr_running != 0);
3592 /* No need to migrate the tasks: it was best-effort if
3593 * they didn't do lock_cpu_hotplug(). Just wake up
3594 * the requestors. */
3595 spin_lock_irq(&rq->lock);
3596 while (!list_empty(&rq->migration_queue)) {
3597 migration_req_t *req;
3598 req = list_entry(rq->migration_queue.next,
3599 migration_req_t, list);
3600 BUG_ON(req->type != REQ_MOVE_TASK);
3601 list_del_init(&req->list);
3602 complete(&req->done);
3604 spin_unlock_irq(&rq->lock);
3611 /* Register at highest priority so that task migration (migrate_all_tasks)
3612 * happens before everything else.
3614 static struct notifier_block __devinitdata migration_notifier = {
3615 .notifier_call = migration_call,
3619 int __init migration_init(void)
3621 void *cpu = (void *)(long)smp_processor_id();
3622 /* Start one for boot CPU. */
3623 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
3624 migration_call(&migration_notifier, CPU_ONLINE, cpu);
3625 register_cpu_notifier(&migration_notifier);
3631 * The 'big kernel lock'
3633 * This spinlock is taken and released recursively by lock_kernel()
3634 * and unlock_kernel(). It is transparently dropped and reaquired
3635 * over schedule(). It is used to protect legacy code that hasn't
3636 * been migrated to a proper locking design yet.
3638 * Don't use in new code.
3640 * Note: spinlock debugging needs this even on !CONFIG_SMP.
3642 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
3643 EXPORT_SYMBOL(kernel_flag);
3646 /* Attach the domain 'sd' to 'cpu' as its base domain */
3647 void cpu_attach_domain(struct sched_domain *sd, int cpu)
3649 migration_req_t req;
3650 unsigned long flags;
3651 runqueue_t *rq = cpu_rq(cpu);
3656 spin_lock_irqsave(&rq->lock, flags);
3658 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
3661 init_completion(&req.done);
3662 req.type = REQ_SET_DOMAIN;
3664 list_add(&req.list, &rq->migration_queue);
3668 spin_unlock_irqrestore(&rq->lock, flags);
3671 wake_up_process(rq->migration_thread);
3672 wait_for_completion(&req.done);
3675 unlock_cpu_hotplug();
3678 #ifdef ARCH_HAS_SCHED_DOMAIN
3679 extern void __init arch_init_sched_domains(void);
3681 static struct sched_group sched_group_cpus[NR_CPUS];
3682 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
3684 static struct sched_group sched_group_nodes[MAX_NUMNODES];
3685 static DEFINE_PER_CPU(struct sched_domain, node_domains);
3686 static void __init arch_init_sched_domains(void)
3689 struct sched_group *first_node = NULL, *last_node = NULL;
3691 /* Set up domains */
3693 int node = cpu_to_node(i);
3694 cpumask_t nodemask = node_to_cpumask(node);
3695 struct sched_domain *node_sd = &per_cpu(node_domains, i);
3696 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3698 *node_sd = SD_NODE_INIT;
3699 node_sd->span = cpu_possible_map;
3700 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
3702 *cpu_sd = SD_CPU_INIT;
3703 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
3704 cpu_sd->groups = &sched_group_cpus[i];
3705 cpu_sd->parent = node_sd;
3709 for (i = 0; i < MAX_NUMNODES; i++) {
3710 cpumask_t tmp = node_to_cpumask(i);
3712 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3713 struct sched_group *node = &sched_group_nodes[i];
3716 cpus_and(nodemask, tmp, cpu_possible_map);
3718 if (cpus_empty(nodemask))
3721 node->cpumask = nodemask;
3722 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
3724 for_each_cpu_mask(j, node->cpumask) {
3725 struct sched_group *cpu = &sched_group_cpus[j];
3727 cpus_clear(cpu->cpumask);
3728 cpu_set(j, cpu->cpumask);
3729 cpu->cpu_power = SCHED_LOAD_SCALE;
3734 last_cpu->next = cpu;
3737 last_cpu->next = first_cpu;
3742 last_node->next = node;
3745 last_node->next = first_node;
3749 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3750 cpu_attach_domain(cpu_sd, i);
3754 #else /* !CONFIG_NUMA */
3755 static void __init arch_init_sched_domains(void)
3758 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3760 /* Set up domains */
3762 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3764 *cpu_sd = SD_CPU_INIT;
3765 cpu_sd->span = cpu_possible_map;
3766 cpu_sd->groups = &sched_group_cpus[i];
3769 /* Set up CPU groups */
3770 for_each_cpu_mask(i, cpu_possible_map) {
3771 struct sched_group *cpu = &sched_group_cpus[i];
3773 cpus_clear(cpu->cpumask);
3774 cpu_set(i, cpu->cpumask);
3775 cpu->cpu_power = SCHED_LOAD_SCALE;
3780 last_cpu->next = cpu;
3783 last_cpu->next = first_cpu;
3785 mb(); /* domains were modified outside the lock */
3787 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3788 cpu_attach_domain(cpu_sd, i);
3792 #endif /* CONFIG_NUMA */
3793 #endif /* ARCH_HAS_SCHED_DOMAIN */
3795 #define SCHED_DOMAIN_DEBUG
3796 #ifdef SCHED_DOMAIN_DEBUG
3797 void sched_domain_debug(void)
3802 runqueue_t *rq = cpu_rq(i);
3803 struct sched_domain *sd;
3808 printk(KERN_DEBUG "CPU%d: %s\n",
3809 i, (cpu_online(i) ? " online" : "offline"));
3814 struct sched_group *group = sd->groups;
3815 cpumask_t groupmask, tmp;
3817 cpumask_scnprintf(str, NR_CPUS, sd->span);
3818 cpus_clear(groupmask);
3821 for (j = 0; j < level + 1; j++)
3823 printk("domain %d: span %s\n", level, str);
3825 if (!cpu_isset(i, sd->span))
3826 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
3827 if (!cpu_isset(i, group->cpumask))
3828 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
3829 if (!group->cpu_power)
3830 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
3833 for (j = 0; j < level + 2; j++)
3838 printk(" ERROR: NULL");
3842 if (!cpus_weight(group->cpumask))
3843 printk(" ERROR empty group:");
3845 cpus_and(tmp, groupmask, group->cpumask);
3846 if (cpus_weight(tmp) > 0)
3847 printk(" ERROR repeated CPUs:");
3849 cpus_or(groupmask, groupmask, group->cpumask);
3851 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
3854 group = group->next;
3855 } while (group != sd->groups);
3858 if (!cpus_equal(sd->span, groupmask))
3859 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
3865 cpus_and(tmp, groupmask, sd->span);
3866 if (!cpus_equal(tmp, groupmask))
3867 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
3874 #define sched_domain_debug() {}
3877 void __init sched_init_smp(void)
3879 arch_init_sched_domains();
3880 sched_domain_debug();
3883 void __init sched_init_smp(void)
3886 #endif /* CONFIG_SMP */
3888 int in_sched_functions(unsigned long addr)
3890 /* Linker adds these: start and end of __sched functions */
3891 extern char __sched_text_start[], __sched_text_end[];
3892 return addr >= (unsigned long)__sched_text_start
3893 && addr < (unsigned long)__sched_text_end;
3896 void __init sched_init(void)
3902 /* Set up an initial dummy domain for early boot */
3903 static struct sched_domain sched_domain_init;
3904 static struct sched_group sched_group_init;
3905 cpumask_t cpu_mask_all = CPU_MASK_ALL;
3907 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
3908 sched_domain_init.span = cpu_mask_all;
3909 sched_domain_init.groups = &sched_group_init;
3910 sched_domain_init.last_balance = jiffies;
3911 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
3913 memset(&sched_group_init, 0, sizeof(struct sched_group));
3914 sched_group_init.cpumask = cpu_mask_all;
3915 sched_group_init.next = &sched_group_init;
3916 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
3919 for (i = 0; i < NR_CPUS; i++) {
3920 prio_array_t *array;
3923 spin_lock_init(&rq->lock);
3924 rq->active = rq->arrays;
3925 rq->expired = rq->arrays + 1;
3926 rq->best_expired_prio = MAX_PRIO;
3929 rq->sd = &sched_domain_init;
3931 rq->active_balance = 0;
3933 rq->migration_thread = NULL;
3934 INIT_LIST_HEAD(&rq->migration_queue);
3936 atomic_set(&rq->nr_iowait, 0);
3938 for (j = 0; j < 2; j++) {
3939 array = rq->arrays + j;
3940 for (k = 0; k < MAX_PRIO; k++) {
3941 INIT_LIST_HEAD(array->queue + k);
3942 __clear_bit(k, array->bitmap);
3944 // delimiter for bitsearch
3945 __set_bit(MAX_PRIO, array->bitmap);
3949 * We have to do a little magic to get the first
3950 * thread right in SMP mode.
3955 set_task_cpu(current, smp_processor_id());
3956 wake_up_forked_process(current);
3959 * The boot idle thread does lazy MMU switching as well:
3961 atomic_inc(&init_mm.mm_count);
3962 enter_lazy_tlb(&init_mm, current);
3965 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
3966 void __might_sleep(char *file, int line)
3968 #if defined(in_atomic)
3969 static unsigned long prev_jiffy; /* ratelimiting */
3971 if ((in_atomic() || irqs_disabled()) &&
3972 system_state == SYSTEM_RUNNING) {
3973 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
3975 prev_jiffy = jiffies;
3976 printk(KERN_ERR "Debug: sleeping function called from invalid"
3977 " context at %s:%d\n", file, line);
3978 printk("in_atomic():%d, irqs_disabled():%d\n",
3979 in_atomic(), irqs_disabled());
3984 EXPORT_SYMBOL(__might_sleep);
3988 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
3990 * This could be a long-held lock. If another CPU holds it for a long time,
3991 * and that CPU is not asked to reschedule then *this* CPU will spin on the
3992 * lock for a long time, even if *this* CPU is asked to reschedule.
3994 * So what we do here, in the slow (contended) path is to spin on the lock by
3995 * hand while permitting preemption.
3997 * Called inside preempt_disable().
3999 void __sched __preempt_spin_lock(spinlock_t *lock)
4001 if (preempt_count() > 1) {
4002 _raw_spin_lock(lock);
4007 while (spin_is_locked(lock))
4010 } while (!_raw_spin_trylock(lock));
4013 EXPORT_SYMBOL(__preempt_spin_lock);
4015 void __sched __preempt_write_lock(rwlock_t *lock)
4017 if (preempt_count() > 1) {
4018 _raw_write_lock(lock);
4024 while (rwlock_is_locked(lock))
4027 } while (!_raw_write_trylock(lock));
4030 EXPORT_SYMBOL(__preempt_write_lock);
4031 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */