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 <linux/pagemap.h>
29 #include <asm/mmu_context.h>
30 #include <linux/interrupt.h>
31 #include <linux/completion.h>
32 #include <linux/kernel_stat.h>
33 #include <linux/security.h>
34 #include <linux/notifier.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/timer.h>
40 #include <linux/rcupdate.h>
41 #include <linux/cpu.h>
42 #include <linux/percpu.h>
43 #include <linux/kthread.h>
45 #include <asm/unistd.h>
48 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
50 #define cpu_to_node_mask(cpu) (cpu_online_map)
54 * Convert user-nice values [ -20 ... 0 ... 19 ]
55 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
58 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
59 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
60 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
63 * 'User priority' is the nice value converted to something we
64 * can work with better when scaling various scheduler parameters,
65 * it's a [ 0 ... 39 ] range.
67 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
68 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
69 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
70 #define AVG_TIMESLICE (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) *\
71 (MAX_PRIO-1-NICE_TO_PRIO(0))/(MAX_USER_PRIO - 1)))
74 * Some helpers for converting nanosecond timing to jiffy resolution
76 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
77 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
80 * These are the 'tuning knobs' of the scheduler:
82 * Minimum timeslice is 10 msecs, default timeslice is 100 msecs,
83 * maximum timeslice is 200 msecs. Timeslices get refilled after
86 #define MIN_TIMESLICE ( 10 * HZ / 1000)
87 #define MAX_TIMESLICE (200 * HZ / 1000)
88 #define ON_RUNQUEUE_WEIGHT 30
89 #define CHILD_PENALTY 95
90 #define PARENT_PENALTY 100
92 #define PRIO_BONUS_RATIO 25
93 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
94 #define INTERACTIVE_DELTA 2
95 #define MAX_SLEEP_AVG (AVG_TIMESLICE * MAX_BONUS)
96 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
97 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
98 #define CREDIT_LIMIT 100
101 * If a task is 'interactive' then we reinsert it in the active
102 * array after it has expired its current timeslice. (it will not
103 * continue to run immediately, it will still roundrobin with
104 * other interactive tasks.)
106 * This part scales the interactivity limit depending on niceness.
108 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
109 * Here are a few examples of different nice levels:
111 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
112 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
113 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
114 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
115 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
117 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
118 * priority range a task can explore, a value of '1' means the
119 * task is rated interactive.)
121 * Ie. nice +19 tasks can never get 'interactive' enough to be
122 * reinserted into the active array. And only heavily CPU-hog nice -20
123 * tasks will be expired. Default nice 0 tasks are somewhere between,
124 * it takes some effort for them to get interactive, but it's not
128 #define CURRENT_BONUS(p) \
129 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
133 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
134 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
137 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
138 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
141 #define SCALE(v1,v1_max,v2_max) \
142 (v1) * (v2_max) / (v1_max)
145 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
147 #define TASK_INTERACTIVE(p) \
148 ((p)->prio <= (p)->static_prio - DELTA(p))
150 #define INTERACTIVE_SLEEP(p) \
151 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
152 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
154 #define HIGH_CREDIT(p) \
155 ((p)->interactive_credit > CREDIT_LIMIT)
157 #define LOW_CREDIT(p) \
158 ((p)->interactive_credit < -CREDIT_LIMIT)
160 #define TASK_PREEMPTS_CURR(p, rq) \
161 ((p)->prio < (rq)->curr->prio)
164 * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
165 * to time slice values.
167 * The higher a thread's priority, the bigger timeslices
168 * it gets during one round of execution. But even the lowest
169 * priority thread gets MIN_TIMESLICE worth of execution time.
171 * task_timeslice() is the interface that is used by the scheduler.
174 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
175 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
176 (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
178 static unsigned int task_timeslice(task_t *p)
180 return BASE_TIMESLICE(p);
183 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
186 * These are the runqueue data structures:
189 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
191 typedef struct runqueue runqueue_t;
194 unsigned int nr_active;
195 unsigned long bitmap[BITMAP_SIZE];
196 struct list_head queue[MAX_PRIO];
200 * This is the main, per-CPU runqueue data structure.
202 * Locking rule: those places that want to lock multiple runqueues
203 * (such as the load balancing or the thread migration code), lock
204 * acquire operations must be ordered by ascending &runqueue.
210 * nr_running and cpu_load should be in the same cacheline because
211 * remote CPUs use both these fields when doing load calculation.
213 unsigned long nr_running;
215 unsigned long cpu_load;
217 unsigned long long nr_switches;
218 unsigned long expired_timestamp, nr_uninterruptible;
219 unsigned long long timestamp_last_tick;
221 struct mm_struct *prev_mm;
222 prio_array_t *active, *expired, arrays[2];
223 int best_expired_prio;
227 struct sched_domain *sd;
229 /* For active balancing */
233 task_t *migration_thread;
234 struct list_head migration_queue;
238 static DEFINE_PER_CPU(struct runqueue, runqueues);
240 #define for_each_domain(cpu, domain) \
241 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
243 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
244 #define this_rq() (&__get_cpu_var(runqueues))
245 #define task_rq(p) cpu_rq(task_cpu(p))
246 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
249 * Default context-switch locking:
251 #ifndef prepare_arch_switch
252 # define prepare_arch_switch(rq, next) do { } while (0)
253 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
254 # define task_running(rq, p) ((rq)->curr == (p))
258 * task_rq_lock - lock the runqueue a given task resides on and disable
259 * interrupts. Note the ordering: we can safely lookup the task_rq without
260 * explicitly disabling preemption.
262 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
267 local_irq_save(*flags);
269 spin_lock(&rq->lock);
270 if (unlikely(rq != task_rq(p))) {
271 spin_unlock_irqrestore(&rq->lock, *flags);
272 goto repeat_lock_task;
277 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
279 spin_unlock_irqrestore(&rq->lock, *flags);
283 * rq_lock - lock a given runqueue and disable interrupts.
285 static runqueue_t *this_rq_lock(void)
291 spin_lock(&rq->lock);
296 static inline void rq_unlock(runqueue_t *rq)
298 spin_unlock_irq(&rq->lock);
302 * Adding/removing a task to/from a priority array:
304 static void dequeue_task(struct task_struct *p, prio_array_t *array)
307 list_del(&p->run_list);
308 if (list_empty(array->queue + p->prio))
309 __clear_bit(p->prio, array->bitmap);
312 static void enqueue_task(struct task_struct *p, prio_array_t *array)
314 list_add_tail(&p->run_list, array->queue + p->prio);
315 __set_bit(p->prio, array->bitmap);
321 * Used by the migration code - we pull tasks from the head of the
322 * remote queue so we want these tasks to show up at the head of the
325 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
327 list_add(&p->run_list, array->queue + p->prio);
328 __set_bit(p->prio, array->bitmap);
334 * effective_prio - return the priority that is based on the static
335 * priority but is modified by bonuses/penalties.
337 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
338 * into the -5 ... 0 ... +5 bonus/penalty range.
340 * We use 25% of the full 0...39 priority range so that:
342 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
343 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
345 * Both properties are important to certain workloads.
347 static int effective_prio(task_t *p)
354 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
356 prio = p->static_prio - bonus;
357 if (prio < MAX_RT_PRIO)
359 if (prio > MAX_PRIO-1)
365 * __activate_task - move a task to the runqueue.
367 static inline void __activate_task(task_t *p, runqueue_t *rq)
369 enqueue_task(p, rq->active);
374 * __activate_idle_task - move idle task to the _front_ of runqueue.
376 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
378 enqueue_task_head(p, rq->active);
382 static void recalc_task_prio(task_t *p, unsigned long long now)
384 unsigned long long __sleep_time = now - p->timestamp;
385 unsigned long sleep_time;
387 if (__sleep_time > NS_MAX_SLEEP_AVG)
388 sleep_time = NS_MAX_SLEEP_AVG;
390 sleep_time = (unsigned long)__sleep_time;
392 if (likely(sleep_time > 0)) {
394 * User tasks that sleep a long time are categorised as
395 * idle and will get just interactive status to stay active &
396 * prevent them suddenly becoming cpu hogs and starving
399 if (p->mm && p->activated != -1 &&
400 sleep_time > INTERACTIVE_SLEEP(p)) {
401 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
404 p->interactive_credit++;
407 * The lower the sleep avg a task has the more
408 * rapidly it will rise with sleep time.
410 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
413 * Tasks with low interactive_credit are limited to
414 * one timeslice worth of sleep avg bonus.
417 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
418 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
421 * Non high_credit tasks waking from uninterruptible
422 * sleep are limited in their sleep_avg rise as they
423 * are likely to be cpu hogs waiting on I/O
425 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
426 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
428 else if (p->sleep_avg + sleep_time >=
429 INTERACTIVE_SLEEP(p)) {
430 p->sleep_avg = INTERACTIVE_SLEEP(p);
436 * This code gives a bonus to interactive tasks.
438 * The boost works by updating the 'average sleep time'
439 * value here, based on ->timestamp. The more time a
440 * task spends sleeping, the higher the average gets -
441 * and the higher the priority boost gets as well.
443 p->sleep_avg += sleep_time;
445 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
446 p->sleep_avg = NS_MAX_SLEEP_AVG;
448 p->interactive_credit++;
453 p->prio = effective_prio(p);
457 * activate_task - move a task to the runqueue and do priority recalculation
459 * Update all the scheduling statistics stuff. (sleep average
460 * calculation, priority modifiers, etc.)
462 static void activate_task(task_t *p, runqueue_t *rq, int local)
464 unsigned long long now;
469 /* Compensate for drifting sched_clock */
470 runqueue_t *this_rq = this_rq();
471 now = (now - this_rq->timestamp_last_tick)
472 + rq->timestamp_last_tick;
476 recalc_task_prio(p, now);
479 * This checks to make sure it's not an uninterruptible task
480 * that is now waking up.
484 * Tasks which were woken up by interrupts (ie. hw events)
485 * are most likely of interactive nature. So we give them
486 * the credit of extending their sleep time to the period
487 * of time they spend on the runqueue, waiting for execution
488 * on a CPU, first time around:
494 * Normal first-time wakeups get a credit too for
495 * on-runqueue time, but it will be weighted down:
502 __activate_task(p, rq);
506 * deactivate_task - remove a task from the runqueue.
508 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
511 if (p->state == TASK_UNINTERRUPTIBLE)
512 rq->nr_uninterruptible++;
513 dequeue_task(p, p->array);
518 * resched_task - mark a task 'to be rescheduled now'.
520 * On UP this means the setting of the need_resched flag, on SMP it
521 * might also involve a cross-CPU call to trigger the scheduler on
525 static void resched_task(task_t *p)
527 int need_resched, nrpolling;
530 /* minimise the chance of sending an interrupt to poll_idle() */
531 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
532 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
533 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
535 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
536 smp_send_reschedule(task_cpu(p));
540 static inline void resched_task(task_t *p)
542 set_tsk_need_resched(p);
547 * task_curr - is this task currently executing on a CPU?
548 * @p: the task in question.
550 inline int task_curr(task_t *p)
552 return cpu_curr(task_cpu(p)) == p;
562 struct list_head list;
563 enum request_type type;
565 /* For REQ_MOVE_TASK */
569 /* For REQ_SET_DOMAIN */
570 struct sched_domain *sd;
572 struct completion done;
576 * The task's runqueue lock must be held.
577 * Returns true if you have to wait for migration thread.
579 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
581 runqueue_t *rq = task_rq(p);
584 * If the task is not on a runqueue (and not running), then
585 * it is sufficient to simply update the task's cpu field.
587 if (!p->array && !task_running(rq, p)) {
588 set_task_cpu(p, dest_cpu);
592 init_completion(&req->done);
593 req->type = REQ_MOVE_TASK;
595 req->dest_cpu = dest_cpu;
596 list_add(&req->list, &rq->migration_queue);
601 * wait_task_inactive - wait for a thread to unschedule.
603 * The caller must ensure that the task *will* unschedule sometime soon,
604 * else this function might spin for a *long* time. This function can't
605 * be called with interrupts off, or it may introduce deadlock with
606 * smp_call_function() if an IPI is sent by the same process we are
607 * waiting to become inactive.
609 void wait_task_inactive(task_t * p)
616 rq = task_rq_lock(p, &flags);
617 /* Must be off runqueue entirely, not preempted. */
618 if (unlikely(p->array)) {
619 /* If it's preempted, we yield. It could be a while. */
620 preempted = !task_running(rq, p);
621 task_rq_unlock(rq, &flags);
627 task_rq_unlock(rq, &flags);
631 * kick_process - kick a running thread to enter/exit the kernel
632 * @p: the to-be-kicked thread
634 * Cause a process which is running on another CPU to enter
635 * kernel-mode, without any delay. (to get signals handled.)
637 void kick_process(task_t *p)
643 if ((cpu != smp_processor_id()) && task_curr(p))
644 smp_send_reschedule(cpu);
648 EXPORT_SYMBOL_GPL(kick_process);
651 * Return a low guess at the load of a migration-source cpu.
653 * We want to under-estimate the load of migration sources, to
654 * balance conservatively.
656 static inline unsigned long source_load(int cpu)
658 runqueue_t *rq = cpu_rq(cpu);
659 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
661 return min(rq->cpu_load, load_now);
665 * Return a high guess at the load of a migration-target cpu
667 static inline unsigned long target_load(int cpu)
669 runqueue_t *rq = cpu_rq(cpu);
670 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
672 return max(rq->cpu_load, load_now);
678 * wake_idle() is useful especially on SMT architectures to wake a
679 * task onto an idle sibling if we would otherwise wake it onto a
682 * Returns the CPU we should wake onto.
684 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
685 static int wake_idle(int cpu, task_t *p)
688 runqueue_t *rq = cpu_rq(cpu);
689 struct sched_domain *sd;
696 if (!(sd->flags & SD_WAKE_IDLE))
699 cpus_and(tmp, sd->span, cpu_online_map);
700 for_each_cpu_mask(i, tmp) {
701 if (!cpu_isset(i, p->cpus_allowed))
711 static inline int wake_idle(int cpu, task_t *p)
718 * try_to_wake_up - wake up a thread
719 * @p: the to-be-woken-up thread
720 * @state: the mask of task states that can be woken
721 * @sync: do a synchronous wakeup?
723 * Put it on the run-queue if it's not already there. The "current"
724 * thread is always on the run-queue (except when the actual
725 * re-schedule is in progress), and as such you're allowed to do
726 * the simpler "current->state = TASK_RUNNING" to mark yourself
727 * runnable without the overhead of this.
729 * returns failure only if the task is already active.
731 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
733 int cpu, this_cpu, success = 0;
738 unsigned long load, this_load;
739 struct sched_domain *sd;
743 rq = task_rq_lock(p, &flags);
744 old_state = p->state;
745 if (!(old_state & state))
752 this_cpu = smp_processor_id();
755 if (unlikely(task_running(rq, p)))
760 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
763 load = source_load(cpu);
764 this_load = target_load(this_cpu);
766 /* Don't pull the task off an idle CPU to a busy one */
767 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
770 new_cpu = this_cpu; /* Wake to this CPU if we can */
773 * Scan domains for affine wakeup and passive balancing
776 for_each_domain(this_cpu, sd) {
777 unsigned int imbalance;
779 * Start passive balancing when half the imbalance_pct
782 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
784 if ( ((sd->flags & SD_WAKE_AFFINE) &&
785 !task_hot(p, rq->timestamp_last_tick, sd))
786 || ((sd->flags & SD_WAKE_BALANCE) &&
787 imbalance*this_load <= 100*load) ) {
789 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
790 * or sd has SD_WAKE_BALANCE and there is an imbalance
792 if (cpu_isset(cpu, sd->span))
797 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
799 new_cpu = wake_idle(new_cpu, p);
800 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
801 set_task_cpu(p, new_cpu);
802 task_rq_unlock(rq, &flags);
803 /* might preempt at this point */
804 rq = task_rq_lock(p, &flags);
805 old_state = p->state;
806 if (!(old_state & state))
811 this_cpu = smp_processor_id();
816 #endif /* CONFIG_SMP */
817 if (old_state == TASK_UNINTERRUPTIBLE) {
818 rq->nr_uninterruptible--;
820 * Tasks on involuntary sleep don't earn
821 * sleep_avg beyond just interactive state.
827 * Sync wakeups (i.e. those types of wakeups where the waker
828 * has indicated that it will leave the CPU in short order)
829 * don't trigger a preemption, if the woken up task will run on
830 * this cpu. (in this case the 'I will reschedule' promise of
831 * the waker guarantees that the freshly woken up task is going
832 * to be considered on this CPU.)
834 activate_task(p, rq, cpu == this_cpu);
835 if (!sync || cpu != this_cpu) {
836 if (TASK_PREEMPTS_CURR(p, rq))
837 resched_task(rq->curr);
842 p->state = TASK_RUNNING;
844 task_rq_unlock(rq, &flags);
849 int fastcall wake_up_process(task_t * p)
851 return try_to_wake_up(p, TASK_STOPPED |
852 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
855 EXPORT_SYMBOL(wake_up_process);
857 int fastcall wake_up_state(task_t *p, unsigned int state)
859 return try_to_wake_up(p, state, 0);
863 * Perform scheduler related setup for a newly forked process p.
864 * p is forked by current.
866 void fastcall sched_fork(task_t *p)
869 * We mark the process as running here, but have not actually
870 * inserted it onto the runqueue yet. This guarantees that
871 * nobody will actually run it, and a signal or other external
872 * event cannot wake it up and insert it on the runqueue either.
874 p->state = TASK_RUNNING;
875 INIT_LIST_HEAD(&p->run_list);
877 spin_lock_init(&p->switch_lock);
878 #ifdef CONFIG_PREEMPT
880 * During context-switch we hold precisely one spinlock, which
881 * schedule_tail drops. (in the common case it's this_rq()->lock,
882 * but it also can be p->switch_lock.) So we compensate with a count
883 * of 1. Also, we want to start with kernel preemption disabled.
885 p->thread_info->preempt_count = 1;
888 * Share the timeslice between parent and child, thus the
889 * total amount of pending timeslices in the system doesn't change,
890 * resulting in more scheduling fairness.
893 p->time_slice = (current->time_slice + 1) >> 1;
895 * The remainder of the first timeslice might be recovered by
896 * the parent if the child exits early enough.
898 p->first_time_slice = 1;
899 current->time_slice >>= 1;
900 p->timestamp = sched_clock();
901 if (!current->time_slice) {
903 * This case is rare, it happens when the parent has only
904 * a single jiffy left from its timeslice. Taking the
905 * runqueue lock is not a problem.
907 current->time_slice = 1;
909 scheduler_tick(0, 0);
917 * wake_up_forked_process - wake up a freshly forked process.
919 * This function will do some initial scheduler statistics housekeeping
920 * that must be done for every newly created process.
922 void fastcall wake_up_forked_process(task_t * p)
925 runqueue_t *rq = task_rq_lock(current, &flags);
927 BUG_ON(p->state != TASK_RUNNING);
930 * We decrease the sleep average of forking parents
931 * and children as well, to keep max-interactive tasks
932 * from forking tasks that are max-interactive.
934 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
935 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
937 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
938 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
940 p->interactive_credit = 0;
942 p->prio = effective_prio(p);
943 set_task_cpu(p, smp_processor_id());
945 if (unlikely(!current->array))
946 __activate_task(p, rq);
948 p->prio = current->prio;
949 list_add_tail(&p->run_list, ¤t->run_list);
950 p->array = current->array;
951 p->array->nr_active++;
954 task_rq_unlock(rq, &flags);
958 * Potentially available exiting-child timeslices are
959 * retrieved here - this way the parent does not get
960 * penalized for creating too many threads.
962 * (this cannot be used to 'generate' timeslices
963 * artificially, because any timeslice recovered here
964 * was given away by the parent in the first place.)
966 void fastcall sched_exit(task_t * p)
971 local_irq_save(flags);
972 if (p->first_time_slice) {
973 p->parent->time_slice += p->time_slice;
974 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
975 p->parent->time_slice = MAX_TIMESLICE;
977 local_irq_restore(flags);
979 * If the child was a (relative-) CPU hog then decrease
980 * the sleep_avg of the parent as well.
982 rq = task_rq_lock(p->parent, &flags);
983 if (p->sleep_avg < p->parent->sleep_avg)
984 p->parent->sleep_avg = p->parent->sleep_avg /
985 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
987 task_rq_unlock(rq, &flags);
991 * finish_task_switch - clean up after a task-switch
992 * @prev: the thread we just switched away from.
994 * We enter this with the runqueue still locked, and finish_arch_switch()
995 * will unlock it along with doing any other architecture-specific cleanup
998 * Note that we may have delayed dropping an mm in context_switch(). If
999 * so, we finish that here outside of the runqueue lock. (Doing it
1000 * with the lock held can cause deadlocks; see schedule() for
1003 static void finish_task_switch(task_t *prev)
1005 runqueue_t *rq = this_rq();
1006 struct mm_struct *mm = rq->prev_mm;
1007 unsigned long prev_task_flags;
1012 * A task struct has one reference for the use as "current".
1013 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1014 * schedule one last time. The schedule call will never return,
1015 * and the scheduled task must drop that reference.
1016 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1017 * still held, otherwise prev could be scheduled on another cpu, die
1018 * there before we look at prev->state, and then the reference would
1020 * Manfred Spraul <manfred@colorfullife.com>
1022 prev_task_flags = prev->flags;
1023 finish_arch_switch(rq, prev);
1026 if (unlikely(prev_task_flags & PF_DEAD))
1027 put_task_struct(prev);
1031 * schedule_tail - first thing a freshly forked thread must call.
1032 * @prev: the thread we just switched away from.
1034 asmlinkage void schedule_tail(task_t *prev)
1036 finish_task_switch(prev);
1038 if (current->set_child_tid)
1039 put_user(current->pid, current->set_child_tid);
1043 * context_switch - switch to the new MM and the new
1044 * thread's register state.
1047 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1049 struct mm_struct *mm = next->mm;
1050 struct mm_struct *oldmm = prev->active_mm;
1052 if (unlikely(!mm)) {
1053 next->active_mm = oldmm;
1054 atomic_inc(&oldmm->mm_count);
1055 enter_lazy_tlb(oldmm, next);
1057 switch_mm(oldmm, mm, next);
1059 if (unlikely(!prev->mm)) {
1060 prev->active_mm = NULL;
1061 WARN_ON(rq->prev_mm);
1062 rq->prev_mm = oldmm;
1065 /* Here we just switch the register state and the stack. */
1066 switch_to(prev, next, prev);
1072 * nr_running, nr_uninterruptible and nr_context_switches:
1074 * externally visible scheduler statistics: current number of runnable
1075 * threads, current number of uninterruptible-sleeping threads, total
1076 * number of context switches performed since bootup.
1078 unsigned long nr_running(void)
1080 unsigned long i, sum = 0;
1083 sum += cpu_rq(i)->nr_running;
1088 unsigned long nr_uninterruptible(void)
1090 unsigned long i, sum = 0;
1092 for_each_online_cpu(i)
1093 sum += cpu_rq(i)->nr_uninterruptible;
1098 unsigned long long nr_context_switches(void)
1100 unsigned long long i, sum = 0;
1102 for_each_online_cpu(i)
1103 sum += cpu_rq(i)->nr_switches;
1108 unsigned long nr_iowait(void)
1110 unsigned long i, sum = 0;
1112 for_each_online_cpu(i)
1113 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1119 * double_rq_lock - safely lock two runqueues
1121 * Note this does not disable interrupts like task_rq_lock,
1122 * you need to do so manually before calling.
1124 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1127 spin_lock(&rq1->lock);
1130 spin_lock(&rq1->lock);
1131 spin_lock(&rq2->lock);
1133 spin_lock(&rq2->lock);
1134 spin_lock(&rq1->lock);
1140 * double_rq_unlock - safely unlock two runqueues
1142 * Note this does not restore interrupts like task_rq_unlock,
1143 * you need to do so manually after calling.
1145 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1147 spin_unlock(&rq1->lock);
1149 spin_unlock(&rq2->lock);
1162 * find_idlest_cpu - find the least busy runqueue.
1164 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1165 struct sched_domain *sd)
1167 unsigned long load, min_load, this_load;
1172 min_load = ULONG_MAX;
1174 cpus_and(mask, sd->span, cpu_online_map);
1175 cpus_and(mask, mask, p->cpus_allowed);
1177 for_each_cpu_mask(i, mask) {
1178 load = target_load(i);
1180 if (load < min_load) {
1184 /* break out early on an idle CPU: */
1190 /* add +1 to account for the new task */
1191 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1194 * Would with the addition of the new task to the
1195 * current CPU there be an imbalance between this
1196 * CPU and the idlest CPU?
1198 * Use half of the balancing threshold - new-context is
1199 * a good opportunity to balance.
1201 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1208 * wake_up_forked_thread - wake up a freshly forked thread.
1210 * This function will do some initial scheduler statistics housekeeping
1211 * that must be done for every newly created context, and it also does
1212 * runqueue balancing.
1214 void fastcall wake_up_forked_thread(task_t * p)
1216 unsigned long flags;
1217 int this_cpu = get_cpu(), cpu;
1218 struct sched_domain *tmp, *sd = NULL;
1219 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1222 * Find the largest domain that this CPU is part of that
1223 * is willing to balance on clone:
1225 for_each_domain(this_cpu, tmp)
1226 if (tmp->flags & SD_BALANCE_CLONE)
1229 cpu = find_idlest_cpu(p, this_cpu, sd);
1233 local_irq_save(flags);
1236 double_rq_lock(this_rq, rq);
1238 BUG_ON(p->state != TASK_RUNNING);
1241 * We did find_idlest_cpu() unlocked, so in theory
1242 * the mask could have changed - just dont migrate
1245 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1247 double_rq_unlock(this_rq, rq);
1251 * We decrease the sleep average of forking parents
1252 * and children as well, to keep max-interactive tasks
1253 * from forking tasks that are max-interactive.
1255 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1256 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1258 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1259 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1261 p->interactive_credit = 0;
1263 p->prio = effective_prio(p);
1264 set_task_cpu(p, cpu);
1266 if (cpu == this_cpu) {
1267 if (unlikely(!current->array))
1268 __activate_task(p, rq);
1270 p->prio = current->prio;
1271 list_add_tail(&p->run_list, ¤t->run_list);
1272 p->array = current->array;
1273 p->array->nr_active++;
1277 /* Not the local CPU - must adjust timestamp */
1278 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1279 + rq->timestamp_last_tick;
1280 __activate_task(p, rq);
1281 if (TASK_PREEMPTS_CURR(p, rq))
1282 resched_task(rq->curr);
1285 double_rq_unlock(this_rq, rq);
1286 local_irq_restore(flags);
1291 * If dest_cpu is allowed for this process, migrate the task to it.
1292 * This is accomplished by forcing the cpu_allowed mask to only
1293 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1294 * the cpu_allowed mask is restored.
1296 static void sched_migrate_task(task_t *p, int dest_cpu)
1298 migration_req_t req;
1300 unsigned long flags;
1302 rq = task_rq_lock(p, &flags);
1303 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1304 || unlikely(cpu_is_offline(dest_cpu)))
1307 /* force the process onto the specified CPU */
1308 if (migrate_task(p, dest_cpu, &req)) {
1309 /* Need to wait for migration thread (might exit: take ref). */
1310 struct task_struct *mt = rq->migration_thread;
1311 get_task_struct(mt);
1312 task_rq_unlock(rq, &flags);
1313 wake_up_process(mt);
1314 put_task_struct(mt);
1315 wait_for_completion(&req.done);
1319 task_rq_unlock(rq, &flags);
1323 * sched_balance_exec(): find the highest-level, exec-balance-capable
1324 * domain and try to migrate the task to the least loaded CPU.
1326 * execve() is a valuable balancing opportunity, because at this point
1327 * the task has the smallest effective memory and cache footprint.
1329 void sched_balance_exec(void)
1331 struct sched_domain *tmp, *sd = NULL;
1332 int new_cpu, this_cpu = get_cpu();
1334 /* Prefer the current CPU if there's only this task running */
1335 if (this_rq()->nr_running <= 1)
1338 for_each_domain(this_cpu, tmp)
1339 if (tmp->flags & SD_BALANCE_EXEC)
1343 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1344 if (new_cpu != this_cpu) {
1346 sched_migrate_task(current, new_cpu);
1355 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1357 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1359 if (unlikely(!spin_trylock(&busiest->lock))) {
1360 if (busiest < this_rq) {
1361 spin_unlock(&this_rq->lock);
1362 spin_lock(&busiest->lock);
1363 spin_lock(&this_rq->lock);
1365 spin_lock(&busiest->lock);
1370 * pull_task - move a task from a remote runqueue to the local runqueue.
1371 * Both runqueues must be locked.
1374 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1375 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1377 dequeue_task(p, src_array);
1378 src_rq->nr_running--;
1379 set_task_cpu(p, this_cpu);
1380 this_rq->nr_running++;
1381 enqueue_task(p, this_array);
1382 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1383 + this_rq->timestamp_last_tick;
1385 * Note that idle threads have a prio of MAX_PRIO, for this test
1386 * to be always true for them.
1388 if (TASK_PREEMPTS_CURR(p, this_rq))
1389 resched_task(this_rq->curr);
1393 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1396 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1397 struct sched_domain *sd, enum idle_type idle)
1400 * We do not migrate tasks that are:
1401 * 1) running (obviously), or
1402 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1403 * 3) are cache-hot on their current CPU.
1405 if (task_running(rq, p))
1407 if (!cpu_isset(this_cpu, p->cpus_allowed))
1410 /* Aggressive migration if we've failed balancing */
1411 if (idle == NEWLY_IDLE ||
1412 sd->nr_balance_failed < sd->cache_nice_tries) {
1413 if (task_hot(p, rq->timestamp_last_tick, sd))
1421 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1422 * as part of a balancing operation within "domain". Returns the number of
1425 * Called with both runqueues locked.
1427 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1428 unsigned long max_nr_move, struct sched_domain *sd,
1429 enum idle_type idle)
1431 prio_array_t *array, *dst_array;
1432 struct list_head *head, *curr;
1433 int idx, pulled = 0;
1436 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1440 * We first consider expired tasks. Those will likely not be
1441 * executed in the near future, and they are most likely to
1442 * be cache-cold, thus switching CPUs has the least effect
1445 if (busiest->expired->nr_active) {
1446 array = busiest->expired;
1447 dst_array = this_rq->expired;
1449 array = busiest->active;
1450 dst_array = this_rq->active;
1454 /* Start searching at priority 0: */
1458 idx = sched_find_first_bit(array->bitmap);
1460 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1461 if (idx >= MAX_PRIO) {
1462 if (array == busiest->expired && busiest->active->nr_active) {
1463 array = busiest->active;
1464 dst_array = this_rq->active;
1470 head = array->queue + idx;
1473 tmp = list_entry(curr, task_t, run_list);
1477 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1483 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1486 /* We only want to steal up to the prescribed number of tasks. */
1487 if (pulled < max_nr_move) {
1498 * find_busiest_group finds and returns the busiest CPU group within the
1499 * domain. It calculates and returns the number of tasks which should be
1500 * moved to restore balance via the imbalance parameter.
1502 static struct sched_group *
1503 find_busiest_group(struct sched_domain *sd, int this_cpu,
1504 unsigned long *imbalance, enum idle_type idle)
1506 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1507 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1509 max_load = this_load = total_load = total_pwr = 0;
1517 local_group = cpu_isset(this_cpu, group->cpumask);
1519 /* Tally up the load of all CPUs in the group */
1521 cpus_and(tmp, group->cpumask, cpu_online_map);
1522 if (unlikely(cpus_empty(tmp)))
1525 for_each_cpu_mask(i, tmp) {
1526 /* Bias balancing toward cpus of our domain */
1528 load = target_load(i);
1530 load = source_load(i);
1539 total_load += avg_load;
1540 total_pwr += group->cpu_power;
1542 /* Adjust by relative CPU power of the group */
1543 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1546 this_load = avg_load;
1549 } else if (avg_load > max_load) {
1550 max_load = avg_load;
1554 group = group->next;
1555 } while (group != sd->groups);
1557 if (!busiest || this_load >= max_load)
1560 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1562 if (this_load >= avg_load ||
1563 100*max_load <= sd->imbalance_pct*this_load)
1567 * We're trying to get all the cpus to the average_load, so we don't
1568 * want to push ourselves above the average load, nor do we wish to
1569 * reduce the max loaded cpu below the average load, as either of these
1570 * actions would just result in more rebalancing later, and ping-pong
1571 * tasks around. Thus we look for the minimum possible imbalance.
1572 * Negative imbalances (*we* are more loaded than anyone else) will
1573 * be counted as no imbalance for these purposes -- we can't fix that
1574 * by pulling tasks to us. Be careful of negative numbers as they'll
1575 * appear as very large values with unsigned longs.
1577 *imbalance = min(max_load - avg_load, avg_load - this_load);
1579 /* How much load to actually move to equalise the imbalance */
1580 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1583 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1584 unsigned long pwr_now = 0, pwr_move = 0;
1587 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1593 * OK, we don't have enough imbalance to justify moving tasks,
1594 * however we may be able to increase total CPU power used by
1598 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1599 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1600 pwr_now /= SCHED_LOAD_SCALE;
1602 /* Amount of load we'd subtract */
1603 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1605 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1608 /* Amount of load we'd add */
1609 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1612 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1613 pwr_move /= SCHED_LOAD_SCALE;
1615 /* Move if we gain another 8th of a CPU worth of throughput */
1616 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1623 /* Get rid of the scaling factor, rounding down as we divide */
1624 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1629 if (busiest && (idle == NEWLY_IDLE ||
1630 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1640 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1642 static runqueue_t *find_busiest_queue(struct sched_group *group)
1645 unsigned long load, max_load = 0;
1646 runqueue_t *busiest = NULL;
1649 cpus_and(tmp, group->cpumask, cpu_online_map);
1650 for_each_cpu_mask(i, tmp) {
1651 load = source_load(i);
1653 if (load > max_load) {
1655 busiest = cpu_rq(i);
1663 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1664 * tasks if there is an imbalance.
1666 * Called with this_rq unlocked.
1668 * This function is marked noinline to work around a compiler
1669 * bug with gcc 3.3.3-hammer on x86-64.
1671 static int noinline load_balance(int this_cpu, runqueue_t *this_rq,
1672 struct sched_domain *sd, enum idle_type idle)
1674 struct sched_group *group;
1675 runqueue_t *busiest;
1676 unsigned long imbalance;
1679 spin_lock(&this_rq->lock);
1681 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1685 busiest = find_busiest_queue(group);
1688 if (unlikely(busiest == this_rq)) {
1694 if (busiest->nr_running > 1) {
1696 * Attempt to move tasks. If find_busiest_group has found
1697 * an imbalance but busiest->nr_running <= 1, the group is
1698 * still unbalanced. nr_moved simply stays zero, so it is
1699 * correctly treated as an imbalance.
1701 double_lock_balance(this_rq, busiest);
1702 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1703 imbalance, sd, idle);
1704 spin_unlock(&busiest->lock);
1706 spin_unlock(&this_rq->lock);
1709 sd->nr_balance_failed++;
1711 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1714 spin_lock(&busiest->lock);
1715 if (!busiest->active_balance) {
1716 busiest->active_balance = 1;
1717 busiest->push_cpu = this_cpu;
1720 spin_unlock(&busiest->lock);
1722 wake_up_process(busiest->migration_thread);
1725 * We've kicked active balancing, reset the failure
1728 sd->nr_balance_failed = sd->cache_nice_tries;
1731 sd->nr_balance_failed = 0;
1733 /* We were unbalanced, so reset the balancing interval */
1734 sd->balance_interval = sd->min_interval;
1739 spin_unlock(&this_rq->lock);
1741 /* tune up the balancing interval */
1742 if (sd->balance_interval < sd->max_interval)
1743 sd->balance_interval *= 2;
1749 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1750 * tasks if there is an imbalance.
1752 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
1753 * this_rq is locked.
1755 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
1756 struct sched_domain *sd)
1758 struct sched_group *group;
1759 runqueue_t *busiest = NULL;
1760 unsigned long imbalance;
1763 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
1767 busiest = find_busiest_queue(group);
1768 if (!busiest || busiest == this_rq)
1771 /* Attempt to move tasks */
1772 double_lock_balance(this_rq, busiest);
1774 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1775 imbalance, sd, NEWLY_IDLE);
1777 spin_unlock(&busiest->lock);
1784 * idle_balance is called by schedule() if this_cpu is about to become
1785 * idle. Attempts to pull tasks from other CPUs.
1787 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1789 struct sched_domain *sd;
1791 for_each_domain(this_cpu, sd) {
1792 if (sd->flags & SD_BALANCE_NEWIDLE) {
1793 if (load_balance_newidle(this_cpu, this_rq, sd)) {
1794 /* We've pulled tasks over so stop searching */
1802 * active_load_balance is run by migration threads. It pushes a running
1803 * task off the cpu. It can be required to correctly have at least 1 task
1804 * running on each physical CPU where possible, and not have a physical /
1805 * logical imbalance.
1807 * Called with busiest locked.
1809 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
1811 struct sched_domain *sd;
1812 struct sched_group *group, *busy_group;
1815 if (busiest->nr_running <= 1)
1818 for_each_domain(busiest_cpu, sd)
1819 if (cpu_isset(busiest->push_cpu, sd->span))
1827 while (!cpu_isset(busiest_cpu, group->cpumask))
1828 group = group->next;
1837 if (group == busy_group)
1840 cpus_and(tmp, group->cpumask, cpu_online_map);
1841 if (!cpus_weight(tmp))
1844 for_each_cpu_mask(i, tmp) {
1850 rq = cpu_rq(push_cpu);
1851 double_lock_balance(busiest, rq);
1852 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
1853 spin_unlock(&rq->lock);
1855 group = group->next;
1856 } while (group != sd->groups);
1860 * rebalance_tick will get called every timer tick, on every CPU.
1862 * It checks each scheduling domain to see if it is due to be balanced,
1863 * and initiates a balancing operation if so.
1865 * Balancing parameters are set up in arch_init_sched_domains.
1868 /* Don't have all balancing operations going off at once */
1869 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
1871 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
1872 enum idle_type idle)
1874 unsigned long old_load, this_load;
1875 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
1876 struct sched_domain *sd;
1878 /* Update our load */
1879 old_load = this_rq->cpu_load;
1880 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
1882 * Round up the averaging division if load is increasing. This
1883 * prevents us from getting stuck on 9 if the load is 10, for
1886 if (this_load > old_load)
1888 this_rq->cpu_load = (old_load + this_load) / 2;
1890 for_each_domain(this_cpu, sd) {
1891 unsigned long interval = sd->balance_interval;
1894 interval *= sd->busy_factor;
1896 /* scale ms to jiffies */
1897 interval = msecs_to_jiffies(interval);
1898 if (unlikely(!interval))
1901 if (j - sd->last_balance >= interval) {
1902 if (load_balance(this_cpu, this_rq, sd, idle)) {
1903 /* We've pulled tasks over so no longer idle */
1906 sd->last_balance += interval;
1912 * on UP we do not need to balance between CPUs:
1914 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
1917 static inline void idle_balance(int cpu, runqueue_t *rq)
1922 static inline int wake_priority_sleeper(runqueue_t *rq)
1924 #ifdef CONFIG_SCHED_SMT
1926 * If an SMT sibling task has been put to sleep for priority
1927 * reasons reschedule the idle task to see if it can now run.
1929 if (rq->nr_running) {
1930 resched_task(rq->idle);
1937 DEFINE_PER_CPU(struct kernel_stat, kstat);
1939 EXPORT_PER_CPU_SYMBOL(kstat);
1942 * We place interactive tasks back into the active array, if possible.
1944 * To guarantee that this does not starve expired tasks we ignore the
1945 * interactivity of a task if the first expired task had to wait more
1946 * than a 'reasonable' amount of time. This deadline timeout is
1947 * load-dependent, as the frequency of array switched decreases with
1948 * increasing number of running tasks. We also ignore the interactivity
1949 * if a better static_prio task has expired:
1951 #define EXPIRED_STARVING(rq) \
1952 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
1953 (jiffies - (rq)->expired_timestamp >= \
1954 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
1955 ((rq)->curr->static_prio > (rq)->best_expired_prio))
1958 * This function gets called by the timer code, with HZ frequency.
1959 * We call it with interrupts disabled.
1961 * It also gets called by the fork code, when changing the parent's
1964 void scheduler_tick(int user_ticks, int sys_ticks)
1966 int cpu = smp_processor_id();
1967 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
1968 runqueue_t *rq = this_rq();
1969 task_t *p = current;
1971 rq->timestamp_last_tick = sched_clock();
1973 if (rcu_pending(cpu))
1974 rcu_check_callbacks(cpu, user_ticks);
1976 /* note: this timer irq context must be accounted for as well */
1977 if (hardirq_count() - HARDIRQ_OFFSET) {
1978 cpustat->irq += sys_ticks;
1980 } else if (softirq_count()) {
1981 cpustat->softirq += sys_ticks;
1985 if (p == rq->idle) {
1986 if (atomic_read(&rq->nr_iowait) > 0)
1987 cpustat->iowait += sys_ticks;
1989 cpustat->idle += sys_ticks;
1990 if (wake_priority_sleeper(rq))
1992 rebalance_tick(cpu, rq, IDLE);
1995 if (TASK_NICE(p) > 0)
1996 cpustat->nice += user_ticks;
1998 cpustat->user += user_ticks;
1999 cpustat->system += sys_ticks;
2001 /* Task might have expired already, but not scheduled off yet */
2002 if (p->array != rq->active) {
2003 set_tsk_need_resched(p);
2006 spin_lock(&rq->lock);
2008 * The task was running during this tick - update the
2009 * time slice counter. Note: we do not update a thread's
2010 * priority until it either goes to sleep or uses up its
2011 * timeslice. This makes it possible for interactive tasks
2012 * to use up their timeslices at their highest priority levels.
2014 if (unlikely(rt_task(p))) {
2016 * RR tasks need a special form of timeslice management.
2017 * FIFO tasks have no timeslices.
2019 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2020 p->time_slice = task_timeslice(p);
2021 p->first_time_slice = 0;
2022 set_tsk_need_resched(p);
2024 /* put it at the end of the queue: */
2025 dequeue_task(p, rq->active);
2026 enqueue_task(p, rq->active);
2030 if (!--p->time_slice) {
2031 dequeue_task(p, rq->active);
2032 set_tsk_need_resched(p);
2033 p->prio = effective_prio(p);
2034 p->time_slice = task_timeslice(p);
2035 p->first_time_slice = 0;
2037 if (!rq->expired_timestamp)
2038 rq->expired_timestamp = jiffies;
2039 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2040 enqueue_task(p, rq->expired);
2041 if (p->static_prio < rq->best_expired_prio)
2042 rq->best_expired_prio = p->static_prio;
2044 enqueue_task(p, rq->active);
2047 * Prevent a too long timeslice allowing a task to monopolize
2048 * the CPU. We do this by splitting up the timeslice into
2051 * Note: this does not mean the task's timeslices expire or
2052 * get lost in any way, they just might be preempted by
2053 * another task of equal priority. (one with higher
2054 * priority would have preempted this task already.) We
2055 * requeue this task to the end of the list on this priority
2056 * level, which is in essence a round-robin of tasks with
2059 * This only applies to tasks in the interactive
2060 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2062 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2063 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2064 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2065 (p->array == rq->active)) {
2067 dequeue_task(p, rq->active);
2068 set_tsk_need_resched(p);
2069 p->prio = effective_prio(p);
2070 enqueue_task(p, rq->active);
2074 spin_unlock(&rq->lock);
2076 rebalance_tick(cpu, rq, NOT_IDLE);
2079 #ifdef CONFIG_SCHED_SMT
2080 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2083 struct sched_domain *sd = rq->sd;
2084 cpumask_t sibling_map;
2086 if (!(sd->flags & SD_SHARE_CPUPOWER))
2089 cpus_and(sibling_map, sd->span, cpu_online_map);
2090 for_each_cpu_mask(i, sibling_map) {
2099 * If an SMT sibling task is sleeping due to priority
2100 * reasons wake it up now.
2102 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2103 resched_task(smt_rq->idle);
2107 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2109 struct sched_domain *sd = rq->sd;
2110 cpumask_t sibling_map;
2113 if (!(sd->flags & SD_SHARE_CPUPOWER))
2116 cpus_and(sibling_map, sd->span, cpu_online_map);
2117 for_each_cpu_mask(i, sibling_map) {
2125 smt_curr = smt_rq->curr;
2128 * If a user task with lower static priority than the
2129 * running task on the SMT sibling is trying to schedule,
2130 * delay it till there is proportionately less timeslice
2131 * left of the sibling task to prevent a lower priority
2132 * task from using an unfair proportion of the
2133 * physical cpu's resources. -ck
2135 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2136 task_timeslice(p) || rt_task(smt_curr)) &&
2137 p->mm && smt_curr->mm && !rt_task(p))
2141 * Reschedule a lower priority task on the SMT sibling,
2142 * or wake it up if it has been put to sleep for priority
2145 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2146 task_timeslice(smt_curr) || rt_task(p)) &&
2147 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2148 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2149 resched_task(smt_curr);
2154 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2158 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2165 * schedule() is the main scheduler function.
2167 asmlinkage void __sched schedule(void)
2170 task_t *prev, *next;
2172 prio_array_t *array;
2173 struct list_head *queue;
2174 unsigned long long now;
2175 unsigned long run_time;
2179 * Test if we are atomic. Since do_exit() needs to call into
2180 * schedule() atomically, we ignore that path for now.
2181 * Otherwise, whine if we are scheduling when we should not be.
2183 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2184 if (unlikely(in_atomic())) {
2185 printk(KERN_ERR "bad: scheduling while atomic!\n");
2195 release_kernel_lock(prev);
2196 now = sched_clock();
2197 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2198 run_time = now - prev->timestamp;
2200 run_time = NS_MAX_SLEEP_AVG;
2203 * Tasks with interactive credits get charged less run_time
2204 * at high sleep_avg to delay them losing their interactive
2207 if (HIGH_CREDIT(prev))
2208 run_time /= (CURRENT_BONUS(prev) ? : 1);
2210 spin_lock_irq(&rq->lock);
2213 * if entering off of a kernel preemption go straight
2214 * to picking the next task.
2216 switch_count = &prev->nivcsw;
2217 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2218 switch_count = &prev->nvcsw;
2219 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2220 unlikely(signal_pending(prev))))
2221 prev->state = TASK_RUNNING;
2223 deactivate_task(prev, rq);
2226 cpu = smp_processor_id();
2227 if (unlikely(!rq->nr_running)) {
2228 idle_balance(cpu, rq);
2229 if (!rq->nr_running) {
2231 rq->expired_timestamp = 0;
2232 wake_sleeping_dependent(cpu, rq);
2238 if (unlikely(!array->nr_active)) {
2240 * Switch the active and expired arrays.
2242 rq->active = rq->expired;
2243 rq->expired = array;
2245 rq->expired_timestamp = 0;
2246 rq->best_expired_prio = MAX_PRIO;
2249 idx = sched_find_first_bit(array->bitmap);
2250 queue = array->queue + idx;
2251 next = list_entry(queue->next, task_t, run_list);
2253 if (dependent_sleeper(cpu, rq, next)) {
2258 if (!rt_task(next) && next->activated > 0) {
2259 unsigned long long delta = now - next->timestamp;
2261 if (next->activated == 1)
2262 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2264 array = next->array;
2265 dequeue_task(next, array);
2266 recalc_task_prio(next, next->timestamp + delta);
2267 enqueue_task(next, array);
2269 next->activated = 0;
2272 clear_tsk_need_resched(prev);
2273 RCU_qsctr(task_cpu(prev))++;
2275 prev->sleep_avg -= run_time;
2276 if ((long)prev->sleep_avg <= 0) {
2277 prev->sleep_avg = 0;
2278 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2279 prev->interactive_credit--;
2281 prev->timestamp = now;
2283 if (likely(prev != next)) {
2284 next->timestamp = now;
2289 prepare_arch_switch(rq, next);
2290 prev = context_switch(rq, prev, next);
2293 finish_task_switch(prev);
2295 spin_unlock_irq(&rq->lock);
2297 reacquire_kernel_lock(current);
2298 preempt_enable_no_resched();
2299 if (test_thread_flag(TIF_NEED_RESCHED))
2303 EXPORT_SYMBOL(schedule);
2305 #ifdef CONFIG_PREEMPT
2307 * this is is the entry point to schedule() from in-kernel preemption
2308 * off of preempt_enable. Kernel preemptions off return from interrupt
2309 * occur there and call schedule directly.
2311 asmlinkage void __sched preempt_schedule(void)
2313 struct thread_info *ti = current_thread_info();
2316 * If there is a non-zero preempt_count or interrupts are disabled,
2317 * we do not want to preempt the current task. Just return..
2319 if (unlikely(ti->preempt_count || irqs_disabled()))
2323 ti->preempt_count = PREEMPT_ACTIVE;
2325 ti->preempt_count = 0;
2327 /* we could miss a preemption opportunity between schedule and now */
2329 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2333 EXPORT_SYMBOL(preempt_schedule);
2334 #endif /* CONFIG_PREEMPT */
2336 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2338 task_t *p = curr->task;
2339 return try_to_wake_up(p, mode, sync);
2342 EXPORT_SYMBOL(default_wake_function);
2345 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2346 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2347 * number) then we wake all the non-exclusive tasks and one exclusive task.
2349 * There are circumstances in which we can try to wake a task which has already
2350 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2351 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2353 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2354 int nr_exclusive, int sync, void *key)
2356 struct list_head *tmp, *next;
2358 list_for_each_safe(tmp, next, &q->task_list) {
2361 curr = list_entry(tmp, wait_queue_t, task_list);
2362 flags = curr->flags;
2363 if (curr->func(curr, mode, sync, key) &&
2364 (flags & WQ_FLAG_EXCLUSIVE) &&
2371 * __wake_up - wake up threads blocked on a waitqueue.
2373 * @mode: which threads
2374 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2376 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2377 int nr_exclusive, void *key)
2379 unsigned long flags;
2381 spin_lock_irqsave(&q->lock, flags);
2382 __wake_up_common(q, mode, nr_exclusive, 0, key);
2383 spin_unlock_irqrestore(&q->lock, flags);
2386 EXPORT_SYMBOL(__wake_up);
2389 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2391 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2393 __wake_up_common(q, mode, 1, 0, NULL);
2397 * __wake_up - sync- wake up threads blocked on a waitqueue.
2399 * @mode: which threads
2400 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2402 * The sync wakeup differs that the waker knows that it will schedule
2403 * away soon, so while the target thread will be woken up, it will not
2404 * be migrated to another CPU - ie. the two threads are 'synchronized'
2405 * with each other. This can prevent needless bouncing between CPUs.
2407 * On UP it can prevent extra preemption.
2409 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2411 unsigned long flags;
2417 if (unlikely(!nr_exclusive))
2420 spin_lock_irqsave(&q->lock, flags);
2421 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2422 spin_unlock_irqrestore(&q->lock, flags);
2424 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2426 void fastcall complete(struct completion *x)
2428 unsigned long flags;
2430 spin_lock_irqsave(&x->wait.lock, flags);
2432 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2434 spin_unlock_irqrestore(&x->wait.lock, flags);
2436 EXPORT_SYMBOL(complete);
2438 void fastcall complete_all(struct completion *x)
2440 unsigned long flags;
2442 spin_lock_irqsave(&x->wait.lock, flags);
2443 x->done += UINT_MAX/2;
2444 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2446 spin_unlock_irqrestore(&x->wait.lock, flags);
2448 EXPORT_SYMBOL(complete_all);
2450 void fastcall __sched wait_for_completion(struct completion *x)
2453 spin_lock_irq(&x->wait.lock);
2455 DECLARE_WAITQUEUE(wait, current);
2457 wait.flags |= WQ_FLAG_EXCLUSIVE;
2458 __add_wait_queue_tail(&x->wait, &wait);
2460 __set_current_state(TASK_UNINTERRUPTIBLE);
2461 spin_unlock_irq(&x->wait.lock);
2463 spin_lock_irq(&x->wait.lock);
2465 __remove_wait_queue(&x->wait, &wait);
2468 spin_unlock_irq(&x->wait.lock);
2470 EXPORT_SYMBOL(wait_for_completion);
2472 #define SLEEP_ON_VAR \
2473 unsigned long flags; \
2474 wait_queue_t wait; \
2475 init_waitqueue_entry(&wait, current);
2477 #define SLEEP_ON_HEAD \
2478 spin_lock_irqsave(&q->lock,flags); \
2479 __add_wait_queue(q, &wait); \
2480 spin_unlock(&q->lock);
2482 #define SLEEP_ON_TAIL \
2483 spin_lock_irq(&q->lock); \
2484 __remove_wait_queue(q, &wait); \
2485 spin_unlock_irqrestore(&q->lock, flags);
2487 #define SLEEP_ON_BKLCHECK \
2488 if (unlikely(!kernel_locked()) && \
2489 sleep_on_bkl_warnings < 10) { \
2490 sleep_on_bkl_warnings++; \
2494 static int sleep_on_bkl_warnings;
2496 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2502 current->state = TASK_INTERRUPTIBLE;
2509 EXPORT_SYMBOL(interruptible_sleep_on);
2511 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2517 current->state = TASK_INTERRUPTIBLE;
2520 timeout = schedule_timeout(timeout);
2526 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2528 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2534 current->state = TASK_UNINTERRUPTIBLE;
2537 timeout = schedule_timeout(timeout);
2543 EXPORT_SYMBOL(sleep_on_timeout);
2545 void set_user_nice(task_t *p, long nice)
2547 unsigned long flags;
2548 prio_array_t *array;
2550 int old_prio, new_prio, delta;
2552 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2555 * We have to be careful, if called from sys_setpriority(),
2556 * the task might be in the middle of scheduling on another CPU.
2558 rq = task_rq_lock(p, &flags);
2560 * The RT priorities are set via setscheduler(), but we still
2561 * allow the 'normal' nice value to be set - but as expected
2562 * it wont have any effect on scheduling until the task is
2566 p->static_prio = NICE_TO_PRIO(nice);
2571 dequeue_task(p, array);
2574 new_prio = NICE_TO_PRIO(nice);
2575 delta = new_prio - old_prio;
2576 p->static_prio = NICE_TO_PRIO(nice);
2580 enqueue_task(p, array);
2582 * If the task increased its priority or is running and
2583 * lowered its priority, then reschedule its CPU:
2585 if (delta < 0 || (delta > 0 && task_running(rq, p)))
2586 resched_task(rq->curr);
2589 task_rq_unlock(rq, &flags);
2592 EXPORT_SYMBOL(set_user_nice);
2594 #ifdef __ARCH_WANT_SYS_NICE
2597 * sys_nice - change the priority of the current process.
2598 * @increment: priority increment
2600 * sys_setpriority is a more generic, but much slower function that
2601 * does similar things.
2603 asmlinkage long sys_nice(int increment)
2609 * Setpriority might change our priority at the same moment.
2610 * We don't have to worry. Conceptually one call occurs first
2611 * and we have a single winner.
2613 if (increment < 0) {
2614 if (!capable(CAP_SYS_NICE))
2616 if (increment < -40)
2622 nice = PRIO_TO_NICE(current->static_prio) + increment;
2628 retval = security_task_setnice(current, nice);
2632 set_user_nice(current, nice);
2639 * task_prio - return the priority value of a given task.
2640 * @p: the task in question.
2642 * This is the priority value as seen by users in /proc.
2643 * RT tasks are offset by -200. Normal tasks are centered
2644 * around 0, value goes from -16 to +15.
2646 int task_prio(task_t *p)
2648 return p->prio - MAX_RT_PRIO;
2652 * task_nice - return the nice value of a given task.
2653 * @p: the task in question.
2655 int task_nice(task_t *p)
2657 return TASK_NICE(p);
2660 EXPORT_SYMBOL(task_nice);
2663 * idle_cpu - is a given cpu idle currently?
2664 * @cpu: the processor in question.
2666 int idle_cpu(int cpu)
2668 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
2671 EXPORT_SYMBOL_GPL(idle_cpu);
2674 * find_process_by_pid - find a process with a matching PID value.
2675 * @pid: the pid in question.
2677 static inline task_t *find_process_by_pid(pid_t pid)
2679 return pid ? find_task_by_pid(pid) : current;
2682 /* Actually do priority change: must hold rq lock. */
2683 static void __setscheduler(struct task_struct *p, int policy, int prio)
2687 p->rt_priority = prio;
2688 if (policy != SCHED_NORMAL)
2689 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
2691 p->prio = p->static_prio;
2695 * setscheduler - change the scheduling policy and/or RT priority of a thread.
2697 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
2699 struct sched_param lp;
2700 int retval = -EINVAL;
2702 prio_array_t *array;
2703 unsigned long flags;
2707 if (!param || pid < 0)
2711 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
2715 * We play safe to avoid deadlocks.
2717 read_lock_irq(&tasklist_lock);
2719 p = find_process_by_pid(pid);
2723 goto out_unlock_tasklist;
2726 * To be able to change p->policy safely, the apropriate
2727 * runqueue lock must be held.
2729 rq = task_rq_lock(p, &flags);
2735 if (policy != SCHED_FIFO && policy != SCHED_RR &&
2736 policy != SCHED_NORMAL)
2741 * Valid priorities for SCHED_FIFO and SCHED_RR are
2742 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
2745 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
2747 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
2751 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
2752 !capable(CAP_SYS_NICE))
2754 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2755 !capable(CAP_SYS_NICE))
2758 retval = security_task_setscheduler(p, policy, &lp);
2764 deactivate_task(p, task_rq(p));
2767 __setscheduler(p, policy, lp.sched_priority);
2769 __activate_task(p, task_rq(p));
2771 * Reschedule if we are currently running on this runqueue and
2772 * our priority decreased, or if we are not currently running on
2773 * this runqueue and our priority is higher than the current's
2775 if (task_running(rq, p)) {
2776 if (p->prio > oldprio)
2777 resched_task(rq->curr);
2778 } else if (TASK_PREEMPTS_CURR(p, rq))
2779 resched_task(rq->curr);
2783 task_rq_unlock(rq, &flags);
2784 out_unlock_tasklist:
2785 read_unlock_irq(&tasklist_lock);
2792 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
2793 * @pid: the pid in question.
2794 * @policy: new policy
2795 * @param: structure containing the new RT priority.
2797 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
2798 struct sched_param __user *param)
2800 return setscheduler(pid, policy, param);
2804 * sys_sched_setparam - set/change the RT priority of a thread
2805 * @pid: the pid in question.
2806 * @param: structure containing the new RT priority.
2808 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
2810 return setscheduler(pid, -1, param);
2814 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
2815 * @pid: the pid in question.
2817 asmlinkage long sys_sched_getscheduler(pid_t pid)
2819 int retval = -EINVAL;
2826 read_lock(&tasklist_lock);
2827 p = find_process_by_pid(pid);
2829 retval = security_task_getscheduler(p);
2833 read_unlock(&tasklist_lock);
2840 * sys_sched_getscheduler - get the RT priority of a thread
2841 * @pid: the pid in question.
2842 * @param: structure containing the RT priority.
2844 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
2846 struct sched_param lp;
2847 int retval = -EINVAL;
2850 if (!param || pid < 0)
2853 read_lock(&tasklist_lock);
2854 p = find_process_by_pid(pid);
2859 retval = security_task_getscheduler(p);
2863 lp.sched_priority = p->rt_priority;
2864 read_unlock(&tasklist_lock);
2867 * This one might sleep, we cannot do it with a spinlock held ...
2869 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
2875 read_unlock(&tasklist_lock);
2880 * sys_sched_setaffinity - set the cpu affinity of a process
2881 * @pid: pid of the process
2882 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2883 * @user_mask_ptr: user-space pointer to the new cpu mask
2885 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
2886 unsigned long __user *user_mask_ptr)
2892 if (len < sizeof(new_mask))
2895 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
2899 read_lock(&tasklist_lock);
2901 p = find_process_by_pid(pid);
2903 read_unlock(&tasklist_lock);
2904 unlock_cpu_hotplug();
2909 * It is not safe to call set_cpus_allowed with the
2910 * tasklist_lock held. We will bump the task_struct's
2911 * usage count and then drop tasklist_lock.
2914 read_unlock(&tasklist_lock);
2917 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2918 !capable(CAP_SYS_NICE))
2921 retval = set_cpus_allowed(p, new_mask);
2925 unlock_cpu_hotplug();
2930 * sys_sched_getaffinity - get the cpu affinity of a process
2931 * @pid: pid of the process
2932 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2933 * @user_mask_ptr: user-space pointer to hold the current cpu mask
2935 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
2936 unsigned long __user *user_mask_ptr)
2938 unsigned int real_len;
2943 real_len = sizeof(mask);
2948 read_lock(&tasklist_lock);
2951 p = find_process_by_pid(pid);
2956 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
2959 read_unlock(&tasklist_lock);
2960 unlock_cpu_hotplug();
2963 if (copy_to_user(user_mask_ptr, &mask, real_len))
2969 * sys_sched_yield - yield the current processor to other threads.
2971 * this function yields the current CPU by moving the calling thread
2972 * to the expired array. If there are no other threads running on this
2973 * CPU then this function will return.
2975 asmlinkage long sys_sched_yield(void)
2977 runqueue_t *rq = this_rq_lock();
2978 prio_array_t *array = current->array;
2979 prio_array_t *target = rq->expired;
2982 * We implement yielding by moving the task into the expired
2985 * (special rule: RT tasks will just roundrobin in the active
2988 if (unlikely(rt_task(current)))
2989 target = rq->active;
2991 dequeue_task(current, array);
2992 enqueue_task(current, target);
2995 * Since we are going to call schedule() anyway, there's
2996 * no need to preempt or enable interrupts:
2998 _raw_spin_unlock(&rq->lock);
2999 preempt_enable_no_resched();
3006 void __sched __cond_resched(void)
3008 set_current_state(TASK_RUNNING);
3012 EXPORT_SYMBOL(__cond_resched);
3015 * yield - yield the current processor to other threads.
3017 * this is a shortcut for kernel-space yielding - it marks the
3018 * thread runnable and calls sys_sched_yield().
3020 void __sched yield(void)
3022 set_current_state(TASK_RUNNING);
3026 EXPORT_SYMBOL(yield);
3029 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3030 * that process accounting knows that this is a task in IO wait state.
3032 * But don't do that if it is a deliberate, throttling IO wait (this task
3033 * has set its backing_dev_info: the queue against which it should throttle)
3035 void __sched io_schedule(void)
3037 struct runqueue *rq = this_rq();
3039 atomic_inc(&rq->nr_iowait);
3041 atomic_dec(&rq->nr_iowait);
3044 EXPORT_SYMBOL(io_schedule);
3046 long __sched io_schedule_timeout(long timeout)
3048 struct runqueue *rq = this_rq();
3051 atomic_inc(&rq->nr_iowait);
3052 ret = schedule_timeout(timeout);
3053 atomic_dec(&rq->nr_iowait);
3058 * sys_sched_get_priority_max - return maximum RT priority.
3059 * @policy: scheduling class.
3061 * this syscall returns the maximum rt_priority that can be used
3062 * by a given scheduling class.
3064 asmlinkage long sys_sched_get_priority_max(int policy)
3071 ret = MAX_USER_RT_PRIO-1;
3081 * sys_sched_get_priority_min - return minimum RT priority.
3082 * @policy: scheduling class.
3084 * this syscall returns the minimum rt_priority that can be used
3085 * by a given scheduling class.
3087 asmlinkage long sys_sched_get_priority_min(int policy)
3103 * sys_sched_rr_get_interval - return the default timeslice of a process.
3104 * @pid: pid of the process.
3105 * @interval: userspace pointer to the timeslice value.
3107 * this syscall writes the default timeslice value of a given process
3108 * into the user-space timespec buffer. A value of '0' means infinity.
3111 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3113 int retval = -EINVAL;
3121 read_lock(&tasklist_lock);
3122 p = find_process_by_pid(pid);
3126 retval = security_task_getscheduler(p);
3130 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3131 0 : task_timeslice(p), &t);
3132 read_unlock(&tasklist_lock);
3133 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3137 read_unlock(&tasklist_lock);
3141 static inline struct task_struct *eldest_child(struct task_struct *p)
3143 if (list_empty(&p->children)) return NULL;
3144 return list_entry(p->children.next,struct task_struct,sibling);
3147 static inline struct task_struct *older_sibling(struct task_struct *p)
3149 if (p->sibling.prev==&p->parent->children) return NULL;
3150 return list_entry(p->sibling.prev,struct task_struct,sibling);
3153 static inline struct task_struct *younger_sibling(struct task_struct *p)
3155 if (p->sibling.next==&p->parent->children) return NULL;
3156 return list_entry(p->sibling.next,struct task_struct,sibling);
3159 static void show_task(task_t * p)
3163 unsigned long free = 0;
3164 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3166 printk("%-13.13s ", p->comm);
3167 state = p->state ? __ffs(p->state) + 1 : 0;
3168 if (state < ARRAY_SIZE(stat_nam))
3169 printk(stat_nam[state]);
3172 #if (BITS_PER_LONG == 32)
3173 if (state == TASK_RUNNING)
3174 printk(" running ");
3176 printk(" %08lX ", thread_saved_pc(p));
3178 if (state == TASK_RUNNING)
3179 printk(" running task ");
3181 printk(" %016lx ", thread_saved_pc(p));
3183 #ifdef CONFIG_DEBUG_STACK_USAGE
3185 unsigned long * n = (unsigned long *) (p->thread_info+1);
3188 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3191 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3192 if ((relative = eldest_child(p)))
3193 printk("%5d ", relative->pid);
3196 if ((relative = younger_sibling(p)))
3197 printk("%7d", relative->pid);
3200 if ((relative = older_sibling(p)))
3201 printk(" %5d", relative->pid);
3205 printk(" (L-TLB)\n");
3207 printk(" (NOTLB)\n");
3209 if (state != TASK_RUNNING)
3210 show_stack(p, NULL);
3213 void show_state(void)
3217 #if (BITS_PER_LONG == 32)
3220 printk(" task PC pid father child younger older\n");
3224 printk(" task PC pid father child younger older\n");
3226 read_lock(&tasklist_lock);
3227 do_each_thread(g, p) {
3229 * reset the NMI-timeout, listing all files on a slow
3230 * console might take alot of time:
3232 touch_nmi_watchdog();
3234 } while_each_thread(g, p);
3236 read_unlock(&tasklist_lock);
3239 void __devinit init_idle(task_t *idle, int cpu)
3241 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3242 unsigned long flags;
3244 local_irq_save(flags);
3245 double_rq_lock(idle_rq, rq);
3247 idle_rq->curr = idle_rq->idle = idle;
3248 deactivate_task(idle, rq);
3250 idle->prio = MAX_PRIO;
3251 idle->state = TASK_RUNNING;
3252 set_task_cpu(idle, cpu);
3253 double_rq_unlock(idle_rq, rq);
3254 set_tsk_need_resched(idle);
3255 local_irq_restore(flags);
3257 /* Set the preempt count _outside_ the spinlocks! */
3258 #ifdef CONFIG_PREEMPT
3259 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3261 idle->thread_info->preempt_count = 0;
3266 * In a system that switches off the HZ timer nohz_cpu_mask
3267 * indicates which cpus entered this state. This is used
3268 * in the rcu update to wait only for active cpus. For system
3269 * which do not switch off the HZ timer nohz_cpu_mask should
3270 * always be CPU_MASK_NONE.
3272 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3276 * This is how migration works:
3278 * 1) we queue a migration_req_t structure in the source CPU's
3279 * runqueue and wake up that CPU's migration thread.
3280 * 2) we down() the locked semaphore => thread blocks.
3281 * 3) migration thread wakes up (implicitly it forces the migrated
3282 * thread off the CPU)
3283 * 4) it gets the migration request and checks whether the migrated
3284 * task is still in the wrong runqueue.
3285 * 5) if it's in the wrong runqueue then the migration thread removes
3286 * it and puts it into the right queue.
3287 * 6) migration thread up()s the semaphore.
3288 * 7) we wake up and the migration is done.
3292 * Change a given task's CPU affinity. Migrate the thread to a
3293 * proper CPU and schedule it away if the CPU it's executing on
3294 * is removed from the allowed bitmask.
3296 * NOTE: the caller must have a valid reference to the task, the
3297 * task must not exit() & deallocate itself prematurely. The
3298 * call is not atomic; no spinlocks may be held.
3300 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3302 unsigned long flags;
3304 migration_req_t req;
3307 rq = task_rq_lock(p, &flags);
3308 if (any_online_cpu(new_mask) == NR_CPUS) {
3313 p->cpus_allowed = new_mask;
3314 /* Can the task run on the task's current CPU? If so, we're done */
3315 if (cpu_isset(task_cpu(p), new_mask))
3318 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3319 /* Need help from migration thread: drop lock and wait. */
3320 task_rq_unlock(rq, &flags);
3321 wake_up_process(rq->migration_thread);
3322 wait_for_completion(&req.done);
3326 task_rq_unlock(rq, &flags);
3330 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3333 * Move (not current) task off this cpu, onto dest cpu. We're doing
3334 * this because either it can't run here any more (set_cpus_allowed()
3335 * away from this CPU, or CPU going down), or because we're
3336 * attempting to rebalance this task on exec (sched_balance_exec).
3338 * So we race with normal scheduler movements, but that's OK, as long
3339 * as the task is no longer on this CPU.
3341 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3343 runqueue_t *rq_dest, *rq_src;
3345 if (unlikely(cpu_is_offline(dest_cpu)))
3348 rq_src = cpu_rq(src_cpu);
3349 rq_dest = cpu_rq(dest_cpu);
3351 double_rq_lock(rq_src, rq_dest);
3352 /* Already moved. */
3353 if (task_cpu(p) != src_cpu)
3355 /* Affinity changed (again). */
3356 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3359 set_task_cpu(p, dest_cpu);
3362 * Sync timestamp with rq_dest's before activating.
3363 * The same thing could be achieved by doing this step
3364 * afterwards, and pretending it was a local activate.
3365 * This way is cleaner and logically correct.
3367 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3368 + rq_dest->timestamp_last_tick;
3369 deactivate_task(p, rq_src);
3370 activate_task(p, rq_dest, 0);
3371 if (TASK_PREEMPTS_CURR(p, rq_dest))
3372 resched_task(rq_dest->curr);
3376 double_rq_unlock(rq_src, rq_dest);
3380 * migration_thread - this is a highprio system thread that performs
3381 * thread migration by bumping thread off CPU then 'pushing' onto
3384 static int migration_thread(void * data)
3387 int cpu = (long)data;
3390 BUG_ON(rq->migration_thread != current);
3392 set_current_state(TASK_INTERRUPTIBLE);
3393 while (!kthread_should_stop()) {
3394 struct list_head *head;
3395 migration_req_t *req;
3397 if (current->flags & PF_FREEZE)
3398 refrigerator(PF_FREEZE);
3400 spin_lock_irq(&rq->lock);
3402 if (cpu_is_offline(cpu)) {
3403 spin_unlock_irq(&rq->lock);
3407 if (rq->active_balance) {
3408 active_load_balance(rq, cpu);
3409 rq->active_balance = 0;
3412 head = &rq->migration_queue;
3414 if (list_empty(head)) {
3415 spin_unlock_irq(&rq->lock);
3417 set_current_state(TASK_INTERRUPTIBLE);
3420 req = list_entry(head->next, migration_req_t, list);
3421 list_del_init(head->next);
3423 if (req->type == REQ_MOVE_TASK) {
3424 spin_unlock(&rq->lock);
3425 __migrate_task(req->task, smp_processor_id(),
3428 } else if (req->type == REQ_SET_DOMAIN) {
3430 spin_unlock_irq(&rq->lock);
3432 spin_unlock_irq(&rq->lock);
3436 complete(&req->done);
3438 __set_current_state(TASK_RUNNING);
3442 /* Wait for kthread_stop */
3443 set_current_state(TASK_INTERRUPTIBLE);
3444 while (!kthread_should_stop()) {
3446 set_current_state(TASK_INTERRUPTIBLE);
3448 __set_current_state(TASK_RUNNING);
3452 #ifdef CONFIG_HOTPLUG_CPU
3453 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
3454 static void migrate_all_tasks(int src_cpu)
3456 struct task_struct *tsk, *t;
3460 write_lock_irq(&tasklist_lock);
3462 /* watch out for per node tasks, let's stay on this node */
3463 node = cpu_to_node(src_cpu);
3465 do_each_thread(t, tsk) {
3470 if (task_cpu(tsk) != src_cpu)
3473 /* Figure out where this task should go (attempting to
3474 * keep it on-node), and check if it can be migrated
3475 * as-is. NOTE that kernel threads bound to more than
3476 * one online cpu will be migrated. */
3477 mask = node_to_cpumask(node);
3478 cpus_and(mask, mask, tsk->cpus_allowed);
3479 dest_cpu = any_online_cpu(mask);
3480 if (dest_cpu == NR_CPUS)
3481 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3482 if (dest_cpu == NR_CPUS) {
3483 cpus_clear(tsk->cpus_allowed);
3484 cpus_complement(tsk->cpus_allowed);
3485 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3487 /* Don't tell them about moving exiting tasks
3488 or kernel threads (both mm NULL), since
3489 they never leave kernel. */
3490 if (tsk->mm && printk_ratelimit())
3491 printk(KERN_INFO "process %d (%s) no "
3492 "longer affine to cpu%d\n",
3493 tsk->pid, tsk->comm, src_cpu);
3496 __migrate_task(tsk, src_cpu, dest_cpu);
3497 } while_each_thread(t, tsk);
3499 write_unlock_irq(&tasklist_lock);
3502 /* Schedules idle task to be the next runnable task on current CPU.
3503 * It does so by boosting its priority to highest possible and adding it to
3504 * the _front_ of runqueue. Used by CPU offline code.
3506 void sched_idle_next(void)
3508 int cpu = smp_processor_id();
3509 runqueue_t *rq = this_rq();
3510 struct task_struct *p = rq->idle;
3511 unsigned long flags;
3513 /* cpu has to be offline */
3514 BUG_ON(cpu_online(cpu));
3516 /* Strictly not necessary since rest of the CPUs are stopped by now
3517 * and interrupts disabled on current cpu.
3519 spin_lock_irqsave(&rq->lock, flags);
3521 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3522 /* Add idle task to _front_ of it's priority queue */
3523 __activate_idle_task(p, rq);
3525 spin_unlock_irqrestore(&rq->lock, flags);
3527 #endif /* CONFIG_HOTPLUG_CPU */
3530 * migration_call - callback that gets triggered when a CPU is added.
3531 * Here we can start up the necessary migration thread for the new CPU.
3533 static int migration_call(struct notifier_block *nfb, unsigned long action,
3536 int cpu = (long)hcpu;
3537 struct task_struct *p;
3538 struct runqueue *rq;
3539 unsigned long flags;
3542 case CPU_UP_PREPARE:
3543 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
3546 kthread_bind(p, cpu);
3547 /* Must be high prio: stop_machine expects to yield to it. */
3548 rq = task_rq_lock(p, &flags);
3549 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3550 task_rq_unlock(rq, &flags);
3551 cpu_rq(cpu)->migration_thread = p;
3554 /* Strictly unneccessary, as first user will wake it. */
3555 wake_up_process(cpu_rq(cpu)->migration_thread);
3557 #ifdef CONFIG_HOTPLUG_CPU
3558 case CPU_UP_CANCELED:
3559 /* Unbind it from offline cpu so it can run. Fall thru. */
3560 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
3561 kthread_stop(cpu_rq(cpu)->migration_thread);
3562 cpu_rq(cpu)->migration_thread = NULL;
3565 migrate_all_tasks(cpu);
3567 kthread_stop(rq->migration_thread);
3568 rq->migration_thread = NULL;
3569 /* Idle task back to normal (off runqueue, low prio) */
3570 rq = task_rq_lock(rq->idle, &flags);
3571 deactivate_task(rq->idle, rq);
3572 rq->idle->static_prio = MAX_PRIO;
3573 __setscheduler(rq->idle, SCHED_NORMAL, 0);
3574 task_rq_unlock(rq, &flags);
3575 BUG_ON(rq->nr_running != 0);
3577 /* No need to migrate the tasks: it was best-effort if
3578 * they didn't do lock_cpu_hotplug(). Just wake up
3579 * the requestors. */
3580 spin_lock_irq(&rq->lock);
3581 while (!list_empty(&rq->migration_queue)) {
3582 migration_req_t *req;
3583 req = list_entry(rq->migration_queue.next,
3584 migration_req_t, list);
3585 BUG_ON(req->type != REQ_MOVE_TASK);
3586 list_del_init(&req->list);
3587 complete(&req->done);
3589 spin_unlock_irq(&rq->lock);
3596 /* Register at highest priority so that task migration (migrate_all_tasks)
3597 * happens before everything else.
3599 static struct notifier_block __devinitdata migration_notifier = {
3600 .notifier_call = migration_call,
3604 int __init migration_init(void)
3606 void *cpu = (void *)(long)smp_processor_id();
3607 /* Start one for boot CPU. */
3608 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
3609 migration_call(&migration_notifier, CPU_ONLINE, cpu);
3610 register_cpu_notifier(&migration_notifier);
3616 * The 'big kernel lock'
3618 * This spinlock is taken and released recursively by lock_kernel()
3619 * and unlock_kernel(). It is transparently dropped and reaquired
3620 * over schedule(). It is used to protect legacy code that hasn't
3621 * been migrated to a proper locking design yet.
3623 * Don't use in new code.
3625 * Note: spinlock debugging needs this even on !CONFIG_SMP.
3627 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
3628 EXPORT_SYMBOL(kernel_flag);
3631 /* Attach the domain 'sd' to 'cpu' as its base domain */
3632 void cpu_attach_domain(struct sched_domain *sd, int cpu)
3634 migration_req_t req;
3635 unsigned long flags;
3636 runqueue_t *rq = cpu_rq(cpu);
3641 spin_lock_irqsave(&rq->lock, flags);
3643 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
3646 init_completion(&req.done);
3647 req.type = REQ_SET_DOMAIN;
3649 list_add(&req.list, &rq->migration_queue);
3653 spin_unlock_irqrestore(&rq->lock, flags);
3656 wake_up_process(rq->migration_thread);
3657 wait_for_completion(&req.done);
3660 unlock_cpu_hotplug();
3663 #ifdef ARCH_HAS_SCHED_DOMAIN
3664 extern void __init arch_init_sched_domains(void);
3666 static struct sched_group sched_group_cpus[NR_CPUS];
3667 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
3669 static struct sched_group sched_group_nodes[MAX_NUMNODES];
3670 static DEFINE_PER_CPU(struct sched_domain, node_domains);
3671 static void __init arch_init_sched_domains(void)
3674 struct sched_group *first_node = NULL, *last_node = NULL;
3676 /* Set up domains */
3678 int node = cpu_to_node(i);
3679 cpumask_t nodemask = node_to_cpumask(node);
3680 struct sched_domain *node_sd = &per_cpu(node_domains, i);
3681 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3683 *node_sd = SD_NODE_INIT;
3684 node_sd->span = cpu_possible_map;
3685 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
3687 *cpu_sd = SD_CPU_INIT;
3688 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
3689 cpu_sd->groups = &sched_group_cpus[i];
3690 cpu_sd->parent = node_sd;
3694 for (i = 0; i < MAX_NUMNODES; i++) {
3695 cpumask_t tmp = node_to_cpumask(i);
3697 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3698 struct sched_group *node = &sched_group_nodes[i];
3701 cpus_and(nodemask, tmp, cpu_possible_map);
3703 if (cpus_empty(nodemask))
3706 node->cpumask = nodemask;
3707 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
3709 for_each_cpu_mask(j, node->cpumask) {
3710 struct sched_group *cpu = &sched_group_cpus[j];
3712 cpus_clear(cpu->cpumask);
3713 cpu_set(j, cpu->cpumask);
3714 cpu->cpu_power = SCHED_LOAD_SCALE;
3719 last_cpu->next = cpu;
3722 last_cpu->next = first_cpu;
3727 last_node->next = node;
3730 last_node->next = first_node;
3734 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3735 cpu_attach_domain(cpu_sd, i);
3739 #else /* !CONFIG_NUMA */
3740 static void __init arch_init_sched_domains(void)
3743 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3745 /* Set up domains */
3747 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3749 *cpu_sd = SD_CPU_INIT;
3750 cpu_sd->span = cpu_possible_map;
3751 cpu_sd->groups = &sched_group_cpus[i];
3754 /* Set up CPU groups */
3755 for_each_cpu_mask(i, cpu_possible_map) {
3756 struct sched_group *cpu = &sched_group_cpus[i];
3758 cpus_clear(cpu->cpumask);
3759 cpu_set(i, cpu->cpumask);
3760 cpu->cpu_power = SCHED_LOAD_SCALE;
3765 last_cpu->next = cpu;
3768 last_cpu->next = first_cpu;
3770 mb(); /* domains were modified outside the lock */
3772 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3773 cpu_attach_domain(cpu_sd, i);
3777 #endif /* CONFIG_NUMA */
3778 #endif /* ARCH_HAS_SCHED_DOMAIN */
3780 #define SCHED_DOMAIN_DEBUG
3781 #ifdef SCHED_DOMAIN_DEBUG
3782 void sched_domain_debug(void)
3787 runqueue_t *rq = cpu_rq(i);
3788 struct sched_domain *sd;
3793 printk(KERN_DEBUG "CPU%d: %s\n",
3794 i, (cpu_online(i) ? " online" : "offline"));
3799 struct sched_group *group = sd->groups;
3800 cpumask_t groupmask, tmp;
3802 cpumask_scnprintf(str, NR_CPUS, sd->span);
3803 cpus_clear(groupmask);
3806 for (j = 0; j < level + 1; j++)
3808 printk("domain %d: span %s\n", level, str);
3810 if (!cpu_isset(i, sd->span))
3811 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
3812 if (!cpu_isset(i, group->cpumask))
3813 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
3814 if (!group->cpu_power)
3815 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
3818 for (j = 0; j < level + 2; j++)
3823 printk(" ERROR: NULL");
3827 if (!cpus_weight(group->cpumask))
3828 printk(" ERROR empty group:");
3830 cpus_and(tmp, groupmask, group->cpumask);
3831 if (cpus_weight(tmp) > 0)
3832 printk(" ERROR repeated CPUs:");
3834 cpus_or(groupmask, groupmask, group->cpumask);
3836 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
3839 group = group->next;
3840 } while (group != sd->groups);
3843 if (!cpus_equal(sd->span, groupmask))
3844 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
3850 cpus_and(tmp, groupmask, sd->span);
3851 if (!cpus_equal(tmp, groupmask))
3852 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
3859 #define sched_domain_debug() {}
3862 void __init sched_init_smp(void)
3864 arch_init_sched_domains();
3865 sched_domain_debug();
3868 void __init sched_init_smp(void)
3871 #endif /* CONFIG_SMP */
3873 int in_sched_functions(unsigned long addr)
3875 /* Linker adds these: start and end of __sched functions */
3876 extern char __sched_text_start[], __sched_text_end[];
3877 return addr >= (unsigned long)__sched_text_start
3878 && addr < (unsigned long)__sched_text_end;
3881 void __init sched_init(void)
3887 /* Set up an initial dummy domain for early boot */
3888 static struct sched_domain sched_domain_init;
3889 static struct sched_group sched_group_init;
3890 cpumask_t cpu_mask_all = CPU_MASK_ALL;
3892 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
3893 sched_domain_init.span = cpu_mask_all;
3894 sched_domain_init.groups = &sched_group_init;
3895 sched_domain_init.last_balance = jiffies;
3896 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
3898 memset(&sched_group_init, 0, sizeof(struct sched_group));
3899 sched_group_init.cpumask = cpu_mask_all;
3900 sched_group_init.next = &sched_group_init;
3901 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
3904 for (i = 0; i < NR_CPUS; i++) {
3905 prio_array_t *array;
3908 spin_lock_init(&rq->lock);
3909 rq->active = rq->arrays;
3910 rq->expired = rq->arrays + 1;
3911 rq->best_expired_prio = MAX_PRIO;
3914 rq->sd = &sched_domain_init;
3916 rq->active_balance = 0;
3918 rq->migration_thread = NULL;
3919 INIT_LIST_HEAD(&rq->migration_queue);
3921 atomic_set(&rq->nr_iowait, 0);
3923 for (j = 0; j < 2; j++) {
3924 array = rq->arrays + j;
3925 for (k = 0; k < MAX_PRIO; k++) {
3926 INIT_LIST_HEAD(array->queue + k);
3927 __clear_bit(k, array->bitmap);
3929 // delimiter for bitsearch
3930 __set_bit(MAX_PRIO, array->bitmap);
3934 * We have to do a little magic to get the first
3935 * thread right in SMP mode.
3940 set_task_cpu(current, smp_processor_id());
3941 wake_up_forked_process(current);
3944 * The boot idle thread does lazy MMU switching as well:
3946 atomic_inc(&init_mm.mm_count);
3947 enter_lazy_tlb(&init_mm, current);
3950 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
3951 void __might_sleep(char *file, int line)
3953 #if defined(in_atomic)
3954 static unsigned long prev_jiffy; /* ratelimiting */
3956 if ((in_atomic() || irqs_disabled()) &&
3957 system_state == SYSTEM_RUNNING) {
3958 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
3960 prev_jiffy = jiffies;
3961 printk(KERN_ERR "Debug: sleeping function called from invalid"
3962 " context at %s:%d\n", file, line);
3963 printk("in_atomic():%d, irqs_disabled():%d\n",
3964 in_atomic(), irqs_disabled());
3969 EXPORT_SYMBOL(__might_sleep);
3973 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
3975 * This could be a long-held lock. If another CPU holds it for a long time,
3976 * and that CPU is not asked to reschedule then *this* CPU will spin on the
3977 * lock for a long time, even if *this* CPU is asked to reschedule.
3979 * So what we do here, in the slow (contended) path is to spin on the lock by
3980 * hand while permitting preemption.
3982 * Called inside preempt_disable().
3984 void __sched __preempt_spin_lock(spinlock_t *lock)
3986 if (preempt_count() > 1) {
3987 _raw_spin_lock(lock);
3992 while (spin_is_locked(lock))
3995 } while (!_raw_spin_trylock(lock));
3998 EXPORT_SYMBOL(__preempt_spin_lock);
4000 void __sched __preempt_write_lock(rwlock_t *lock)
4002 if (preempt_count() > 1) {
4003 _raw_write_lock(lock);
4009 while (rwlock_is_locked(lock))
4012 } while (!_raw_write_trylock(lock));
4015 EXPORT_SYMBOL(__preempt_write_lock);
4016 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */