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>
44 #include <linux/vserver/sched.h>
45 #include <linux/vs_base.h>
47 #include <asm/unistd.h>
50 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
52 #define cpu_to_node_mask(cpu) (cpu_online_map)
56 * Convert user-nice values [ -20 ... 0 ... 19 ]
57 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
60 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
61 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
62 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
65 * 'User priority' is the nice value converted to something we
66 * can work with better when scaling various scheduler parameters,
67 * it's a [ 0 ... 39 ] range.
69 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
70 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
71 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
72 #define AVG_TIMESLICE (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) *\
73 (MAX_PRIO-1-NICE_TO_PRIO(0))/(MAX_USER_PRIO - 1)))
76 * Some helpers for converting nanosecond timing to jiffy resolution
78 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
79 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
82 * These are the 'tuning knobs' of the scheduler:
84 * Minimum timeslice is 10 msecs, default timeslice is 100 msecs,
85 * maximum timeslice is 200 msecs. Timeslices get refilled after
88 #define MIN_TIMESLICE ( 10 * HZ / 1000)
89 #define MAX_TIMESLICE (200 * HZ / 1000)
90 #define ON_RUNQUEUE_WEIGHT 30
91 #define CHILD_PENALTY 95
92 #define PARENT_PENALTY 100
94 #define PRIO_BONUS_RATIO 25
95 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
96 #define INTERACTIVE_DELTA 2
97 #define MAX_SLEEP_AVG (AVG_TIMESLICE * MAX_BONUS)
98 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
99 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
100 #define CREDIT_LIMIT 100
103 * If a task is 'interactive' then we reinsert it in the active
104 * array after it has expired its current timeslice. (it will not
105 * continue to run immediately, it will still roundrobin with
106 * other interactive tasks.)
108 * This part scales the interactivity limit depending on niceness.
110 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
111 * Here are a few examples of different nice levels:
113 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
114 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
115 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
116 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
117 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
119 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
120 * priority range a task can explore, a value of '1' means the
121 * task is rated interactive.)
123 * Ie. nice +19 tasks can never get 'interactive' enough to be
124 * reinserted into the active array. And only heavily CPU-hog nice -20
125 * tasks will be expired. Default nice 0 tasks are somewhere between,
126 * it takes some effort for them to get interactive, but it's not
130 #define CURRENT_BONUS(p) \
131 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
135 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
136 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
139 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
140 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
143 #define SCALE(v1,v1_max,v2_max) \
144 (v1) * (v2_max) / (v1_max)
147 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
149 #define TASK_INTERACTIVE(p) \
150 ((p)->prio <= (p)->static_prio - DELTA(p))
152 #define INTERACTIVE_SLEEP(p) \
153 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
154 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
156 #define HIGH_CREDIT(p) \
157 ((p)->interactive_credit > CREDIT_LIMIT)
159 #define LOW_CREDIT(p) \
160 ((p)->interactive_credit < -CREDIT_LIMIT)
162 #define TASK_PREEMPTS_CURR(p, rq) \
163 ((p)->prio < (rq)->curr->prio)
166 * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
167 * to time slice values.
169 * The higher a thread's priority, the bigger timeslices
170 * it gets during one round of execution. But even the lowest
171 * priority thread gets MIN_TIMESLICE worth of execution time.
173 * task_timeslice() is the interface that is used by the scheduler.
176 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
177 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
178 (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
180 static unsigned int task_timeslice(task_t *p)
182 return BASE_TIMESLICE(p);
185 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
188 * These are the runqueue data structures:
191 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
193 typedef struct runqueue runqueue_t;
196 unsigned int nr_active;
197 unsigned long bitmap[BITMAP_SIZE];
198 struct list_head queue[MAX_PRIO];
202 * This is the main, per-CPU runqueue data structure.
204 * Locking rule: those places that want to lock multiple runqueues
205 * (such as the load balancing or the thread migration code), lock
206 * acquire operations must be ordered by ascending &runqueue.
212 * nr_running and cpu_load should be in the same cacheline because
213 * remote CPUs use both these fields when doing load calculation.
215 unsigned long nr_running;
217 unsigned long cpu_load;
219 unsigned long long nr_switches;
220 unsigned long expired_timestamp, nr_uninterruptible;
221 unsigned long long timestamp_last_tick;
223 struct mm_struct *prev_mm;
224 prio_array_t *active, *expired, arrays[2];
225 int best_expired_prio;
229 struct sched_domain *sd;
231 /* For active balancing */
235 task_t *migration_thread;
236 struct list_head migration_queue;
238 struct list_head hold_queue;
242 static DEFINE_PER_CPU(struct runqueue, runqueues);
244 #define for_each_domain(cpu, domain) \
245 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
247 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
248 #define this_rq() (&__get_cpu_var(runqueues))
249 #define task_rq(p) cpu_rq(task_cpu(p))
250 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
253 * Default context-switch locking:
255 #ifndef prepare_arch_switch
256 # define prepare_arch_switch(rq, next) do { } while (0)
257 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
258 # define task_running(rq, p) ((rq)->curr == (p))
262 * task_rq_lock - lock the runqueue a given task resides on and disable
263 * interrupts. Note the ordering: we can safely lookup the task_rq without
264 * explicitly disabling preemption.
266 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
271 local_irq_save(*flags);
273 spin_lock(&rq->lock);
274 if (unlikely(rq != task_rq(p))) {
275 spin_unlock_irqrestore(&rq->lock, *flags);
276 goto repeat_lock_task;
281 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
283 spin_unlock_irqrestore(&rq->lock, *flags);
287 * rq_lock - lock a given runqueue and disable interrupts.
289 static runqueue_t *this_rq_lock(void)
295 spin_lock(&rq->lock);
300 static inline void rq_unlock(runqueue_t *rq)
302 spin_unlock_irq(&rq->lock);
306 * Adding/removing a task to/from a priority array:
308 static void dequeue_task(struct task_struct *p, prio_array_t *array)
311 list_del(&p->run_list);
312 if (list_empty(array->queue + p->prio))
313 __clear_bit(p->prio, array->bitmap);
316 static void enqueue_task(struct task_struct *p, prio_array_t *array)
318 list_add_tail(&p->run_list, array->queue + p->prio);
319 __set_bit(p->prio, array->bitmap);
325 * Used by the migration code - we pull tasks from the head of the
326 * remote queue so we want these tasks to show up at the head of the
329 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
331 list_add(&p->run_list, array->queue + p->prio);
332 __set_bit(p->prio, array->bitmap);
338 * effective_prio - return the priority that is based on the static
339 * priority but is modified by bonuses/penalties.
341 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
342 * into the -5 ... 0 ... +5 bonus/penalty range.
344 * We use 25% of the full 0...39 priority range so that:
346 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
347 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
349 * Both properties are important to certain workloads.
351 static int effective_prio(task_t *p)
358 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
360 prio = p->static_prio - bonus;
361 if (__vx_task_flags(p, VXF_SCHED_PRIO, 0))
362 prio += effective_vavavoom(p, MAX_USER_PRIO);
364 if (prio < MAX_RT_PRIO)
366 if (prio > MAX_PRIO-1)
372 * __activate_task - move a task to the runqueue.
374 static inline void __activate_task(task_t *p, runqueue_t *rq)
376 enqueue_task(p, rq->active);
381 * __activate_idle_task - move idle task to the _front_ of runqueue.
383 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
385 enqueue_task_head(p, rq->active);
389 static void recalc_task_prio(task_t *p, unsigned long long now)
391 unsigned long long __sleep_time = now - p->timestamp;
392 unsigned long sleep_time;
394 if (__sleep_time > NS_MAX_SLEEP_AVG)
395 sleep_time = NS_MAX_SLEEP_AVG;
397 sleep_time = (unsigned long)__sleep_time;
399 if (likely(sleep_time > 0)) {
401 * User tasks that sleep a long time are categorised as
402 * idle and will get just interactive status to stay active &
403 * prevent them suddenly becoming cpu hogs and starving
406 if (p->mm && p->activated != -1 &&
407 sleep_time > INTERACTIVE_SLEEP(p)) {
408 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
411 p->interactive_credit++;
414 * The lower the sleep avg a task has the more
415 * rapidly it will rise with sleep time.
417 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
420 * Tasks with low interactive_credit are limited to
421 * one timeslice worth of sleep avg bonus.
424 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
425 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
428 * Non high_credit tasks waking from uninterruptible
429 * sleep are limited in their sleep_avg rise as they
430 * are likely to be cpu hogs waiting on I/O
432 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
433 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
435 else if (p->sleep_avg + sleep_time >=
436 INTERACTIVE_SLEEP(p)) {
437 p->sleep_avg = INTERACTIVE_SLEEP(p);
443 * This code gives a bonus to interactive tasks.
445 * The boost works by updating the 'average sleep time'
446 * value here, based on ->timestamp. The more time a
447 * task spends sleeping, the higher the average gets -
448 * and the higher the priority boost gets as well.
450 p->sleep_avg += sleep_time;
452 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
453 p->sleep_avg = NS_MAX_SLEEP_AVG;
455 p->interactive_credit++;
460 p->prio = effective_prio(p);
464 * activate_task - move a task to the runqueue and do priority recalculation
466 * Update all the scheduling statistics stuff. (sleep average
467 * calculation, priority modifiers, etc.)
469 static void activate_task(task_t *p, runqueue_t *rq, int local)
471 unsigned long long now;
476 /* Compensate for drifting sched_clock */
477 runqueue_t *this_rq = this_rq();
478 now = (now - this_rq->timestamp_last_tick)
479 + rq->timestamp_last_tick;
483 recalc_task_prio(p, now);
486 * This checks to make sure it's not an uninterruptible task
487 * that is now waking up.
491 * Tasks which were woken up by interrupts (ie. hw events)
492 * are most likely of interactive nature. So we give them
493 * the credit of extending their sleep time to the period
494 * of time they spend on the runqueue, waiting for execution
495 * on a CPU, first time around:
501 * Normal first-time wakeups get a credit too for
502 * on-runqueue time, but it will be weighted down:
509 __activate_task(p, rq);
513 * deactivate_task - remove a task from the runqueue.
515 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
518 if (p->state == TASK_UNINTERRUPTIBLE)
519 rq->nr_uninterruptible++;
520 dequeue_task(p, p->array);
525 * resched_task - mark a task 'to be rescheduled now'.
527 * On UP this means the setting of the need_resched flag, on SMP it
528 * might also involve a cross-CPU call to trigger the scheduler on
532 static void resched_task(task_t *p)
534 int need_resched, nrpolling;
537 /* minimise the chance of sending an interrupt to poll_idle() */
538 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
539 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
540 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
542 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
543 smp_send_reschedule(task_cpu(p));
547 static inline void resched_task(task_t *p)
549 set_tsk_need_resched(p);
554 * task_curr - is this task currently executing on a CPU?
555 * @p: the task in question.
557 inline int task_curr(const task_t *p)
559 return cpu_curr(task_cpu(p)) == p;
569 struct list_head list;
570 enum request_type type;
572 /* For REQ_MOVE_TASK */
576 /* For REQ_SET_DOMAIN */
577 struct sched_domain *sd;
579 struct completion done;
583 * The task's runqueue lock must be held.
584 * Returns true if you have to wait for migration thread.
586 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
588 runqueue_t *rq = task_rq(p);
591 * If the task is not on a runqueue (and not running), then
592 * it is sufficient to simply update the task's cpu field.
594 if (!p->array && !task_running(rq, p)) {
595 set_task_cpu(p, dest_cpu);
599 init_completion(&req->done);
600 req->type = REQ_MOVE_TASK;
602 req->dest_cpu = dest_cpu;
603 list_add(&req->list, &rq->migration_queue);
608 * wait_task_inactive - wait for a thread to unschedule.
610 * The caller must ensure that the task *will* unschedule sometime soon,
611 * else this function might spin for a *long* time. This function can't
612 * be called with interrupts off, or it may introduce deadlock with
613 * smp_call_function() if an IPI is sent by the same process we are
614 * waiting to become inactive.
616 void wait_task_inactive(task_t * p)
623 rq = task_rq_lock(p, &flags);
624 /* Must be off runqueue entirely, not preempted. */
625 if (unlikely(p->array)) {
626 /* If it's preempted, we yield. It could be a while. */
627 preempted = !task_running(rq, p);
628 task_rq_unlock(rq, &flags);
634 task_rq_unlock(rq, &flags);
638 * kick_process - kick a running thread to enter/exit the kernel
639 * @p: the to-be-kicked thread
641 * Cause a process which is running on another CPU to enter
642 * kernel-mode, without any delay. (to get signals handled.)
644 void kick_process(task_t *p)
650 if ((cpu != smp_processor_id()) && task_curr(p))
651 smp_send_reschedule(cpu);
655 EXPORT_SYMBOL_GPL(kick_process);
658 * Return a low guess at the load of a migration-source cpu.
660 * We want to under-estimate the load of migration sources, to
661 * balance conservatively.
663 static inline unsigned long source_load(int cpu)
665 runqueue_t *rq = cpu_rq(cpu);
666 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
668 return min(rq->cpu_load, load_now);
672 * Return a high guess at the load of a migration-target cpu
674 static inline unsigned long target_load(int cpu)
676 runqueue_t *rq = cpu_rq(cpu);
677 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
679 return max(rq->cpu_load, load_now);
685 * wake_idle() is useful especially on SMT architectures to wake a
686 * task onto an idle sibling if we would otherwise wake it onto a
689 * Returns the CPU we should wake onto.
691 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
692 static int wake_idle(int cpu, task_t *p)
695 runqueue_t *rq = cpu_rq(cpu);
696 struct sched_domain *sd;
703 if (!(sd->flags & SD_WAKE_IDLE))
706 cpus_and(tmp, sd->span, cpu_online_map);
707 for_each_cpu_mask(i, tmp) {
708 if (!cpu_isset(i, p->cpus_allowed))
718 static inline int wake_idle(int cpu, task_t *p)
725 * try_to_wake_up - wake up a thread
726 * @p: the to-be-woken-up thread
727 * @state: the mask of task states that can be woken
728 * @sync: do a synchronous wakeup?
730 * Put it on the run-queue if it's not already there. The "current"
731 * thread is always on the run-queue (except when the actual
732 * re-schedule is in progress), and as such you're allowed to do
733 * the simpler "current->state = TASK_RUNNING" to mark yourself
734 * runnable without the overhead of this.
736 * returns failure only if the task is already active.
738 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
740 int cpu, this_cpu, success = 0;
745 unsigned long load, this_load;
746 struct sched_domain *sd;
750 rq = task_rq_lock(p, &flags);
751 old_state = p->state;
752 if (!(old_state & state))
759 this_cpu = smp_processor_id();
762 if (unlikely(task_running(rq, p)))
767 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
770 load = source_load(cpu);
771 this_load = target_load(this_cpu);
774 * If sync wakeup then subtract the (maximum possible) effect of
775 * the currently running task from the load of the current CPU:
778 this_load -= SCHED_LOAD_SCALE;
780 /* Don't pull the task off an idle CPU to a busy one */
781 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
784 new_cpu = this_cpu; /* Wake to this CPU if we can */
787 * Scan domains for affine wakeup and passive balancing
790 for_each_domain(this_cpu, sd) {
791 unsigned int imbalance;
793 * Start passive balancing when half the imbalance_pct
796 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
798 if ( ((sd->flags & SD_WAKE_AFFINE) &&
799 !task_hot(p, rq->timestamp_last_tick, sd))
800 || ((sd->flags & SD_WAKE_BALANCE) &&
801 imbalance*this_load <= 100*load) ) {
803 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
804 * or sd has SD_WAKE_BALANCE and there is an imbalance
806 if (cpu_isset(cpu, sd->span))
811 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
813 new_cpu = wake_idle(new_cpu, p);
814 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
815 set_task_cpu(p, new_cpu);
816 task_rq_unlock(rq, &flags);
817 /* might preempt at this point */
818 rq = task_rq_lock(p, &flags);
819 old_state = p->state;
820 if (!(old_state & state))
825 this_cpu = smp_processor_id();
830 #endif /* CONFIG_SMP */
831 if (old_state == TASK_UNINTERRUPTIBLE) {
832 rq->nr_uninterruptible--;
834 * Tasks on involuntary sleep don't earn
835 * sleep_avg beyond just interactive state.
841 * Sync wakeups (i.e. those types of wakeups where the waker
842 * has indicated that it will leave the CPU in short order)
843 * don't trigger a preemption, if the woken up task will run on
844 * this cpu. (in this case the 'I will reschedule' promise of
845 * the waker guarantees that the freshly woken up task is going
846 * to be considered on this CPU.)
848 activate_task(p, rq, cpu == this_cpu);
849 if (!sync || cpu != this_cpu) {
850 if (TASK_PREEMPTS_CURR(p, rq))
851 resched_task(rq->curr);
856 p->state = TASK_RUNNING;
858 task_rq_unlock(rq, &flags);
863 int fastcall wake_up_process(task_t * p)
865 return try_to_wake_up(p, TASK_STOPPED |
866 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
869 EXPORT_SYMBOL(wake_up_process);
871 int fastcall wake_up_state(task_t *p, unsigned int state)
873 return try_to_wake_up(p, state, 0);
877 * Perform scheduler related setup for a newly forked process p.
878 * p is forked by current.
880 void fastcall sched_fork(task_t *p)
883 * We mark the process as running here, but have not actually
884 * inserted it onto the runqueue yet. This guarantees that
885 * nobody will actually run it, and a signal or other external
886 * event cannot wake it up and insert it on the runqueue either.
888 p->state = TASK_RUNNING;
889 INIT_LIST_HEAD(&p->run_list);
891 spin_lock_init(&p->switch_lock);
892 #ifdef CONFIG_PREEMPT
894 * During context-switch we hold precisely one spinlock, which
895 * schedule_tail drops. (in the common case it's this_rq()->lock,
896 * but it also can be p->switch_lock.) So we compensate with a count
897 * of 1. Also, we want to start with kernel preemption disabled.
899 p->thread_info->preempt_count = 1;
902 * Share the timeslice between parent and child, thus the
903 * total amount of pending timeslices in the system doesn't change,
904 * resulting in more scheduling fairness.
907 p->time_slice = (current->time_slice + 1) >> 1;
909 * The remainder of the first timeslice might be recovered by
910 * the parent if the child exits early enough.
912 p->first_time_slice = 1;
913 current->time_slice >>= 1;
914 p->timestamp = sched_clock();
915 if (!current->time_slice) {
917 * This case is rare, it happens when the parent has only
918 * a single jiffy left from its timeslice. Taking the
919 * runqueue lock is not a problem.
921 current->time_slice = 1;
923 scheduler_tick(0, 0);
931 * wake_up_forked_process - wake up a freshly forked process.
933 * This function will do some initial scheduler statistics housekeeping
934 * that must be done for every newly created process.
936 void fastcall wake_up_forked_process(task_t * p)
939 runqueue_t *rq = task_rq_lock(current, &flags);
941 BUG_ON(p->state != TASK_RUNNING);
944 * We decrease the sleep average of forking parents
945 * and children as well, to keep max-interactive tasks
946 * from forking tasks that are max-interactive.
948 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
949 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
951 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
952 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
954 p->interactive_credit = 0;
956 p->prio = effective_prio(p);
957 set_task_cpu(p, smp_processor_id());
959 if (unlikely(!current->array))
960 __activate_task(p, rq);
962 p->prio = current->prio;
963 list_add_tail(&p->run_list, ¤t->run_list);
964 p->array = current->array;
965 p->array->nr_active++;
968 task_rq_unlock(rq, &flags);
972 * Potentially available exiting-child timeslices are
973 * retrieved here - this way the parent does not get
974 * penalized for creating too many threads.
976 * (this cannot be used to 'generate' timeslices
977 * artificially, because any timeslice recovered here
978 * was given away by the parent in the first place.)
980 void fastcall sched_exit(task_t * p)
985 local_irq_save(flags);
986 if (p->first_time_slice) {
987 p->parent->time_slice += p->time_slice;
988 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
989 p->parent->time_slice = MAX_TIMESLICE;
991 local_irq_restore(flags);
993 * If the child was a (relative-) CPU hog then decrease
994 * the sleep_avg of the parent as well.
996 rq = task_rq_lock(p->parent, &flags);
997 if (p->sleep_avg < p->parent->sleep_avg)
998 p->parent->sleep_avg = p->parent->sleep_avg /
999 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1001 task_rq_unlock(rq, &flags);
1005 * finish_task_switch - clean up after a task-switch
1006 * @prev: the thread we just switched away from.
1008 * We enter this with the runqueue still locked, and finish_arch_switch()
1009 * will unlock it along with doing any other architecture-specific cleanup
1012 * Note that we may have delayed dropping an mm in context_switch(). If
1013 * so, we finish that here outside of the runqueue lock. (Doing it
1014 * with the lock held can cause deadlocks; see schedule() for
1017 static void finish_task_switch(task_t *prev)
1019 runqueue_t *rq = this_rq();
1020 struct mm_struct *mm = rq->prev_mm;
1021 unsigned long prev_task_flags;
1026 * A task struct has one reference for the use as "current".
1027 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1028 * schedule one last time. The schedule call will never return,
1029 * and the scheduled task must drop that reference.
1030 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1031 * still held, otherwise prev could be scheduled on another cpu, die
1032 * there before we look at prev->state, and then the reference would
1034 * Manfred Spraul <manfred@colorfullife.com>
1036 prev_task_flags = prev->flags;
1037 finish_arch_switch(rq, prev);
1040 if (unlikely(prev_task_flags & PF_DEAD))
1041 put_task_struct(prev);
1045 * schedule_tail - first thing a freshly forked thread must call.
1046 * @prev: the thread we just switched away from.
1048 asmlinkage void schedule_tail(task_t *prev)
1050 finish_task_switch(prev);
1052 if (current->set_child_tid)
1053 put_user(current->pid, current->set_child_tid);
1057 * context_switch - switch to the new MM and the new
1058 * thread's register state.
1061 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1063 struct mm_struct *mm = next->mm;
1064 struct mm_struct *oldmm = prev->active_mm;
1066 if (unlikely(!mm)) {
1067 next->active_mm = oldmm;
1068 atomic_inc(&oldmm->mm_count);
1069 enter_lazy_tlb(oldmm, next);
1071 switch_mm(oldmm, mm, next);
1073 if (unlikely(!prev->mm)) {
1074 prev->active_mm = NULL;
1075 WARN_ON(rq->prev_mm);
1076 rq->prev_mm = oldmm;
1079 /* Here we just switch the register state and the stack. */
1080 switch_to(prev, next, prev);
1086 * nr_running, nr_uninterruptible and nr_context_switches:
1088 * externally visible scheduler statistics: current number of runnable
1089 * threads, current number of uninterruptible-sleeping threads, total
1090 * number of context switches performed since bootup.
1092 unsigned long nr_running(void)
1094 unsigned long i, sum = 0;
1097 sum += cpu_rq(i)->nr_running;
1102 unsigned long nr_uninterruptible(void)
1104 unsigned long i, sum = 0;
1106 for_each_online_cpu(i)
1107 sum += cpu_rq(i)->nr_uninterruptible;
1112 unsigned long long nr_context_switches(void)
1114 unsigned long long i, sum = 0;
1116 for_each_online_cpu(i)
1117 sum += cpu_rq(i)->nr_switches;
1122 unsigned long nr_iowait(void)
1124 unsigned long i, sum = 0;
1126 for_each_online_cpu(i)
1127 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1133 * double_rq_lock - safely lock two runqueues
1135 * Note this does not disable interrupts like task_rq_lock,
1136 * you need to do so manually before calling.
1138 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1141 spin_lock(&rq1->lock);
1144 spin_lock(&rq1->lock);
1145 spin_lock(&rq2->lock);
1147 spin_lock(&rq2->lock);
1148 spin_lock(&rq1->lock);
1154 * double_rq_unlock - safely unlock two runqueues
1156 * Note this does not restore interrupts like task_rq_unlock,
1157 * you need to do so manually after calling.
1159 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1161 spin_unlock(&rq1->lock);
1163 spin_unlock(&rq2->lock);
1176 * find_idlest_cpu - find the least busy runqueue.
1178 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1179 struct sched_domain *sd)
1181 unsigned long load, min_load, this_load;
1186 min_load = ULONG_MAX;
1188 cpus_and(mask, sd->span, cpu_online_map);
1189 cpus_and(mask, mask, p->cpus_allowed);
1191 for_each_cpu_mask(i, mask) {
1192 load = target_load(i);
1194 if (load < min_load) {
1198 /* break out early on an idle CPU: */
1204 /* add +1 to account for the new task */
1205 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1208 * Would with the addition of the new task to the
1209 * current CPU there be an imbalance between this
1210 * CPU and the idlest CPU?
1212 * Use half of the balancing threshold - new-context is
1213 * a good opportunity to balance.
1215 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1222 * wake_up_forked_thread - wake up a freshly forked thread.
1224 * This function will do some initial scheduler statistics housekeeping
1225 * that must be done for every newly created context, and it also does
1226 * runqueue balancing.
1228 void fastcall wake_up_forked_thread(task_t * p)
1230 unsigned long flags;
1231 int this_cpu = get_cpu(), cpu;
1232 struct sched_domain *tmp, *sd = NULL;
1233 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1236 * Find the largest domain that this CPU is part of that
1237 * is willing to balance on clone:
1239 for_each_domain(this_cpu, tmp)
1240 if (tmp->flags & SD_BALANCE_CLONE)
1243 cpu = find_idlest_cpu(p, this_cpu, sd);
1247 local_irq_save(flags);
1250 double_rq_lock(this_rq, rq);
1252 BUG_ON(p->state != TASK_RUNNING);
1255 * We did find_idlest_cpu() unlocked, so in theory
1256 * the mask could have changed - just dont migrate
1259 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1261 double_rq_unlock(this_rq, rq);
1265 * We decrease the sleep average of forking parents
1266 * and children as well, to keep max-interactive tasks
1267 * from forking tasks that are max-interactive.
1269 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1270 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1272 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1273 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1275 p->interactive_credit = 0;
1277 p->prio = effective_prio(p);
1278 set_task_cpu(p, cpu);
1280 if (cpu == this_cpu) {
1281 if (unlikely(!current->array))
1282 __activate_task(p, rq);
1284 p->prio = current->prio;
1285 list_add_tail(&p->run_list, ¤t->run_list);
1286 p->array = current->array;
1287 p->array->nr_active++;
1291 /* Not the local CPU - must adjust timestamp */
1292 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1293 + rq->timestamp_last_tick;
1294 __activate_task(p, rq);
1295 if (TASK_PREEMPTS_CURR(p, rq))
1296 resched_task(rq->curr);
1299 double_rq_unlock(this_rq, rq);
1300 local_irq_restore(flags);
1305 * If dest_cpu is allowed for this process, migrate the task to it.
1306 * This is accomplished by forcing the cpu_allowed mask to only
1307 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1308 * the cpu_allowed mask is restored.
1310 static void sched_migrate_task(task_t *p, int dest_cpu)
1312 migration_req_t req;
1314 unsigned long flags;
1316 rq = task_rq_lock(p, &flags);
1317 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1318 || unlikely(cpu_is_offline(dest_cpu)))
1321 /* force the process onto the specified CPU */
1322 if (migrate_task(p, dest_cpu, &req)) {
1323 /* Need to wait for migration thread (might exit: take ref). */
1324 struct task_struct *mt = rq->migration_thread;
1325 get_task_struct(mt);
1326 task_rq_unlock(rq, &flags);
1327 wake_up_process(mt);
1328 put_task_struct(mt);
1329 wait_for_completion(&req.done);
1333 task_rq_unlock(rq, &flags);
1337 * sched_balance_exec(): find the highest-level, exec-balance-capable
1338 * domain and try to migrate the task to the least loaded CPU.
1340 * execve() is a valuable balancing opportunity, because at this point
1341 * the task has the smallest effective memory and cache footprint.
1343 void sched_balance_exec(void)
1345 struct sched_domain *tmp, *sd = NULL;
1346 int new_cpu, this_cpu = get_cpu();
1348 /* Prefer the current CPU if there's only this task running */
1349 if (this_rq()->nr_running <= 1)
1352 for_each_domain(this_cpu, tmp)
1353 if (tmp->flags & SD_BALANCE_EXEC)
1357 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1358 if (new_cpu != this_cpu) {
1360 sched_migrate_task(current, new_cpu);
1369 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1371 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1373 if (unlikely(!spin_trylock(&busiest->lock))) {
1374 if (busiest < this_rq) {
1375 spin_unlock(&this_rq->lock);
1376 spin_lock(&busiest->lock);
1377 spin_lock(&this_rq->lock);
1379 spin_lock(&busiest->lock);
1384 * pull_task - move a task from a remote runqueue to the local runqueue.
1385 * Both runqueues must be locked.
1388 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1389 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1391 dequeue_task(p, src_array);
1392 src_rq->nr_running--;
1393 set_task_cpu(p, this_cpu);
1394 this_rq->nr_running++;
1395 enqueue_task(p, this_array);
1396 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1397 + this_rq->timestamp_last_tick;
1399 * Note that idle threads have a prio of MAX_PRIO, for this test
1400 * to be always true for them.
1402 if (TASK_PREEMPTS_CURR(p, this_rq))
1403 resched_task(this_rq->curr);
1407 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1410 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1411 struct sched_domain *sd, enum idle_type idle)
1414 * We do not migrate tasks that are:
1415 * 1) running (obviously), or
1416 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1417 * 3) are cache-hot on their current CPU.
1419 if (task_running(rq, p))
1421 if (!cpu_isset(this_cpu, p->cpus_allowed))
1424 /* Aggressive migration if we've failed balancing */
1425 if (idle == NEWLY_IDLE ||
1426 sd->nr_balance_failed < sd->cache_nice_tries) {
1427 if (task_hot(p, rq->timestamp_last_tick, sd))
1435 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1436 * as part of a balancing operation within "domain". Returns the number of
1439 * Called with both runqueues locked.
1441 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1442 unsigned long max_nr_move, struct sched_domain *sd,
1443 enum idle_type idle)
1445 prio_array_t *array, *dst_array;
1446 struct list_head *head, *curr;
1447 int idx, pulled = 0;
1450 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1454 * We first consider expired tasks. Those will likely not be
1455 * executed in the near future, and they are most likely to
1456 * be cache-cold, thus switching CPUs has the least effect
1459 if (busiest->expired->nr_active) {
1460 array = busiest->expired;
1461 dst_array = this_rq->expired;
1463 array = busiest->active;
1464 dst_array = this_rq->active;
1468 /* Start searching at priority 0: */
1472 idx = sched_find_first_bit(array->bitmap);
1474 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1475 if (idx >= MAX_PRIO) {
1476 if (array == busiest->expired && busiest->active->nr_active) {
1477 array = busiest->active;
1478 dst_array = this_rq->active;
1484 head = array->queue + idx;
1487 tmp = list_entry(curr, task_t, run_list);
1491 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1497 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1500 /* We only want to steal up to the prescribed number of tasks. */
1501 if (pulled < max_nr_move) {
1512 * find_busiest_group finds and returns the busiest CPU group within the
1513 * domain. It calculates and returns the number of tasks which should be
1514 * moved to restore balance via the imbalance parameter.
1516 static struct sched_group *
1517 find_busiest_group(struct sched_domain *sd, int this_cpu,
1518 unsigned long *imbalance, enum idle_type idle)
1520 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1521 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1523 max_load = this_load = total_load = total_pwr = 0;
1531 local_group = cpu_isset(this_cpu, group->cpumask);
1533 /* Tally up the load of all CPUs in the group */
1535 cpus_and(tmp, group->cpumask, cpu_online_map);
1536 if (unlikely(cpus_empty(tmp)))
1539 for_each_cpu_mask(i, tmp) {
1540 /* Bias balancing toward cpus of our domain */
1542 load = target_load(i);
1544 load = source_load(i);
1553 total_load += avg_load;
1554 total_pwr += group->cpu_power;
1556 /* Adjust by relative CPU power of the group */
1557 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1560 this_load = avg_load;
1563 } else if (avg_load > max_load) {
1564 max_load = avg_load;
1568 group = group->next;
1569 } while (group != sd->groups);
1571 if (!busiest || this_load >= max_load)
1574 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1576 if (this_load >= avg_load ||
1577 100*max_load <= sd->imbalance_pct*this_load)
1581 * We're trying to get all the cpus to the average_load, so we don't
1582 * want to push ourselves above the average load, nor do we wish to
1583 * reduce the max loaded cpu below the average load, as either of these
1584 * actions would just result in more rebalancing later, and ping-pong
1585 * tasks around. Thus we look for the minimum possible imbalance.
1586 * Negative imbalances (*we* are more loaded than anyone else) will
1587 * be counted as no imbalance for these purposes -- we can't fix that
1588 * by pulling tasks to us. Be careful of negative numbers as they'll
1589 * appear as very large values with unsigned longs.
1591 *imbalance = min(max_load - avg_load, avg_load - this_load);
1593 /* How much load to actually move to equalise the imbalance */
1594 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1597 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1598 unsigned long pwr_now = 0, pwr_move = 0;
1601 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1607 * OK, we don't have enough imbalance to justify moving tasks,
1608 * however we may be able to increase total CPU power used by
1612 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1613 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1614 pwr_now /= SCHED_LOAD_SCALE;
1616 /* Amount of load we'd subtract */
1617 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1619 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1622 /* Amount of load we'd add */
1623 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1626 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1627 pwr_move /= SCHED_LOAD_SCALE;
1629 /* Move if we gain another 8th of a CPU worth of throughput */
1630 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1637 /* Get rid of the scaling factor, rounding down as we divide */
1638 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1643 if (busiest && (idle == NEWLY_IDLE ||
1644 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1654 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1656 static runqueue_t *find_busiest_queue(struct sched_group *group)
1659 unsigned long load, max_load = 0;
1660 runqueue_t *busiest = NULL;
1663 cpus_and(tmp, group->cpumask, cpu_online_map);
1664 for_each_cpu_mask(i, tmp) {
1665 load = source_load(i);
1667 if (load > max_load) {
1669 busiest = cpu_rq(i);
1677 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1678 * tasks if there is an imbalance.
1680 * Called with this_rq unlocked.
1682 static int load_balance(int this_cpu, runqueue_t *this_rq,
1683 struct sched_domain *sd, enum idle_type idle)
1685 struct sched_group *group;
1686 runqueue_t *busiest;
1687 unsigned long imbalance;
1690 spin_lock(&this_rq->lock);
1692 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1696 busiest = find_busiest_queue(group);
1700 * This should be "impossible", but since load
1701 * balancing is inherently racy and statistical,
1702 * it could happen in theory.
1704 if (unlikely(busiest == this_rq)) {
1710 if (busiest->nr_running > 1) {
1712 * Attempt to move tasks. If find_busiest_group has found
1713 * an imbalance but busiest->nr_running <= 1, the group is
1714 * still unbalanced. nr_moved simply stays zero, so it is
1715 * correctly treated as an imbalance.
1717 double_lock_balance(this_rq, busiest);
1718 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1719 imbalance, sd, idle);
1720 spin_unlock(&busiest->lock);
1722 spin_unlock(&this_rq->lock);
1725 sd->nr_balance_failed++;
1727 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1730 spin_lock(&busiest->lock);
1731 if (!busiest->active_balance) {
1732 busiest->active_balance = 1;
1733 busiest->push_cpu = this_cpu;
1736 spin_unlock(&busiest->lock);
1738 wake_up_process(busiest->migration_thread);
1741 * We've kicked active balancing, reset the failure
1744 sd->nr_balance_failed = sd->cache_nice_tries;
1747 sd->nr_balance_failed = 0;
1749 /* We were unbalanced, so reset the balancing interval */
1750 sd->balance_interval = sd->min_interval;
1755 spin_unlock(&this_rq->lock);
1757 /* tune up the balancing interval */
1758 if (sd->balance_interval < sd->max_interval)
1759 sd->balance_interval *= 2;
1765 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1766 * tasks if there is an imbalance.
1768 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
1769 * this_rq is locked.
1771 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
1772 struct sched_domain *sd)
1774 struct sched_group *group;
1775 runqueue_t *busiest = NULL;
1776 unsigned long imbalance;
1779 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
1783 busiest = find_busiest_queue(group);
1784 if (!busiest || busiest == this_rq)
1787 /* Attempt to move tasks */
1788 double_lock_balance(this_rq, busiest);
1790 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1791 imbalance, sd, NEWLY_IDLE);
1793 spin_unlock(&busiest->lock);
1800 * idle_balance is called by schedule() if this_cpu is about to become
1801 * idle. Attempts to pull tasks from other CPUs.
1803 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1805 struct sched_domain *sd;
1807 for_each_domain(this_cpu, sd) {
1808 if (sd->flags & SD_BALANCE_NEWIDLE) {
1809 if (load_balance_newidle(this_cpu, this_rq, sd)) {
1810 /* We've pulled tasks over so stop searching */
1818 * active_load_balance is run by migration threads. It pushes a running
1819 * task off the cpu. It can be required to correctly have at least 1 task
1820 * running on each physical CPU where possible, and not have a physical /
1821 * logical imbalance.
1823 * Called with busiest locked.
1825 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
1827 struct sched_domain *sd;
1828 struct sched_group *group, *busy_group;
1831 if (busiest->nr_running <= 1)
1834 for_each_domain(busiest_cpu, sd)
1835 if (cpu_isset(busiest->push_cpu, sd->span))
1843 while (!cpu_isset(busiest_cpu, group->cpumask))
1844 group = group->next;
1853 if (group == busy_group)
1856 cpus_and(tmp, group->cpumask, cpu_online_map);
1857 if (!cpus_weight(tmp))
1860 for_each_cpu_mask(i, tmp) {
1866 rq = cpu_rq(push_cpu);
1869 * This condition is "impossible", but since load
1870 * balancing is inherently a bit racy and statistical,
1871 * it can trigger.. Reported by Bjorn Helgaas on a
1874 if (unlikely(busiest == rq))
1876 double_lock_balance(busiest, rq);
1877 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
1878 spin_unlock(&rq->lock);
1880 group = group->next;
1881 } while (group != sd->groups);
1885 * rebalance_tick will get called every timer tick, on every CPU.
1887 * It checks each scheduling domain to see if it is due to be balanced,
1888 * and initiates a balancing operation if so.
1890 * Balancing parameters are set up in arch_init_sched_domains.
1893 /* Don't have all balancing operations going off at once */
1894 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
1896 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
1897 enum idle_type idle)
1899 unsigned long old_load, this_load;
1900 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
1901 struct sched_domain *sd;
1903 /* Update our load */
1904 old_load = this_rq->cpu_load;
1905 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
1907 * Round up the averaging division if load is increasing. This
1908 * prevents us from getting stuck on 9 if the load is 10, for
1911 if (this_load > old_load)
1913 this_rq->cpu_load = (old_load + this_load) / 2;
1915 for_each_domain(this_cpu, sd) {
1916 unsigned long interval = sd->balance_interval;
1919 interval *= sd->busy_factor;
1921 /* scale ms to jiffies */
1922 interval = msecs_to_jiffies(interval);
1923 if (unlikely(!interval))
1926 if (j - sd->last_balance >= interval) {
1927 if (load_balance(this_cpu, this_rq, sd, idle)) {
1928 /* We've pulled tasks over so no longer idle */
1931 sd->last_balance += interval;
1937 * on UP we do not need to balance between CPUs:
1939 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
1942 static inline void idle_balance(int cpu, runqueue_t *rq)
1947 static inline int wake_priority_sleeper(runqueue_t *rq)
1949 #ifdef CONFIG_SCHED_SMT
1951 * If an SMT sibling task has been put to sleep for priority
1952 * reasons reschedule the idle task to see if it can now run.
1954 if (rq->nr_running) {
1955 resched_task(rq->idle);
1962 DEFINE_PER_CPU(struct kernel_stat, kstat);
1964 EXPORT_PER_CPU_SYMBOL(kstat);
1967 * We place interactive tasks back into the active array, if possible.
1969 * To guarantee that this does not starve expired tasks we ignore the
1970 * interactivity of a task if the first expired task had to wait more
1971 * than a 'reasonable' amount of time. This deadline timeout is
1972 * load-dependent, as the frequency of array switched decreases with
1973 * increasing number of running tasks. We also ignore the interactivity
1974 * if a better static_prio task has expired:
1976 #define EXPIRED_STARVING(rq) \
1977 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
1978 (jiffies - (rq)->expired_timestamp >= \
1979 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
1980 ((rq)->curr->static_prio > (rq)->best_expired_prio))
1983 * This function gets called by the timer code, with HZ frequency.
1984 * We call it with interrupts disabled.
1986 * It also gets called by the fork code, when changing the parent's
1989 void scheduler_tick(int user_ticks, int sys_ticks)
1991 int cpu = smp_processor_id();
1992 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
1993 runqueue_t *rq = this_rq();
1994 task_t *p = current;
1996 rq->timestamp_last_tick = sched_clock();
1998 if (rcu_pending(cpu))
1999 rcu_check_callbacks(cpu, user_ticks);
2001 /* note: this timer irq context must be accounted for as well */
2002 if (hardirq_count() - HARDIRQ_OFFSET) {
2003 cpustat->irq += sys_ticks;
2005 } else if (softirq_count()) {
2006 cpustat->softirq += sys_ticks;
2010 if (p == rq->idle) {
2011 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2014 if (atomic_read(&rq->nr_iowait) > 0)
2015 cpustat->iowait += sys_ticks;
2017 cpustat->idle += sys_ticks;
2018 if (wake_priority_sleeper(rq))
2020 rebalance_tick(cpu, rq, IDLE);
2023 if (TASK_NICE(p) > 0)
2024 cpustat->nice += user_ticks;
2026 cpustat->user += user_ticks;
2027 cpustat->system += sys_ticks;
2029 /* Task might have expired already, but not scheduled off yet */
2030 if (p->array != rq->active) {
2031 set_tsk_need_resched(p);
2034 spin_lock(&rq->lock);
2036 * The task was running during this tick - update the
2037 * time slice counter. Note: we do not update a thread's
2038 * priority until it either goes to sleep or uses up its
2039 * timeslice. This makes it possible for interactive tasks
2040 * to use up their timeslices at their highest priority levels.
2042 if (unlikely(rt_task(p))) {
2044 * RR tasks need a special form of timeslice management.
2045 * FIFO tasks have no timeslices.
2047 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2048 p->time_slice = task_timeslice(p);
2049 p->first_time_slice = 0;
2050 set_tsk_need_resched(p);
2052 /* put it at the end of the queue: */
2053 dequeue_task(p, rq->active);
2054 enqueue_task(p, rq->active);
2058 if (vx_need_resched(p)) {
2059 dequeue_task(p, rq->active);
2060 set_tsk_need_resched(p);
2061 p->prio = effective_prio(p);
2062 p->time_slice = task_timeslice(p);
2063 p->first_time_slice = 0;
2065 if (!rq->expired_timestamp)
2066 rq->expired_timestamp = jiffies;
2067 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2068 enqueue_task(p, rq->expired);
2069 if (p->static_prio < rq->best_expired_prio)
2070 rq->best_expired_prio = p->static_prio;
2072 enqueue_task(p, rq->active);
2075 * Prevent a too long timeslice allowing a task to monopolize
2076 * the CPU. We do this by splitting up the timeslice into
2079 * Note: this does not mean the task's timeslices expire or
2080 * get lost in any way, they just might be preempted by
2081 * another task of equal priority. (one with higher
2082 * priority would have preempted this task already.) We
2083 * requeue this task to the end of the list on this priority
2084 * level, which is in essence a round-robin of tasks with
2087 * This only applies to tasks in the interactive
2088 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2090 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2091 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2092 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2093 (p->array == rq->active)) {
2095 dequeue_task(p, rq->active);
2096 set_tsk_need_resched(p);
2097 p->prio = effective_prio(p);
2098 enqueue_task(p, rq->active);
2102 spin_unlock(&rq->lock);
2104 rebalance_tick(cpu, rq, NOT_IDLE);
2107 #ifdef CONFIG_SCHED_SMT
2108 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2111 struct sched_domain *sd = rq->sd;
2112 cpumask_t sibling_map;
2114 if (!(sd->flags & SD_SHARE_CPUPOWER))
2117 cpus_and(sibling_map, sd->span, cpu_online_map);
2118 for_each_cpu_mask(i, sibling_map) {
2127 * If an SMT sibling task is sleeping due to priority
2128 * reasons wake it up now.
2130 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2131 resched_task(smt_rq->idle);
2135 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2137 struct sched_domain *sd = rq->sd;
2138 cpumask_t sibling_map;
2141 if (!(sd->flags & SD_SHARE_CPUPOWER))
2144 cpus_and(sibling_map, sd->span, cpu_online_map);
2145 for_each_cpu_mask(i, sibling_map) {
2153 smt_curr = smt_rq->curr;
2156 * If a user task with lower static priority than the
2157 * running task on the SMT sibling is trying to schedule,
2158 * delay it till there is proportionately less timeslice
2159 * left of the sibling task to prevent a lower priority
2160 * task from using an unfair proportion of the
2161 * physical cpu's resources. -ck
2163 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2164 task_timeslice(p) || rt_task(smt_curr)) &&
2165 p->mm && smt_curr->mm && !rt_task(p))
2169 * Reschedule a lower priority task on the SMT sibling,
2170 * or wake it up if it has been put to sleep for priority
2173 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2174 task_timeslice(smt_curr) || rt_task(p)) &&
2175 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2176 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2177 resched_task(smt_curr);
2182 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2186 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2193 * schedule() is the main scheduler function.
2195 asmlinkage void __sched schedule(void)
2198 task_t *prev, *next;
2200 prio_array_t *array;
2201 struct list_head *queue;
2202 unsigned long long now;
2203 unsigned long run_time;
2205 #ifdef CONFIG_VSERVER_HARDCPU
2206 struct vx_info *vxi;
2211 * Test if we are atomic. Since do_exit() needs to call into
2212 * schedule() atomically, we ignore that path for now.
2213 * Otherwise, whine if we are scheduling when we should not be.
2215 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2216 if (unlikely(in_atomic())) {
2217 printk(KERN_ERR "bad: scheduling while atomic!\n");
2227 release_kernel_lock(prev);
2228 now = sched_clock();
2229 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2230 run_time = now - prev->timestamp;
2232 run_time = NS_MAX_SLEEP_AVG;
2235 * Tasks with interactive credits get charged less run_time
2236 * at high sleep_avg to delay them losing their interactive
2239 if (HIGH_CREDIT(prev))
2240 run_time /= (CURRENT_BONUS(prev) ? : 1);
2242 spin_lock_irq(&rq->lock);
2245 * if entering off of a kernel preemption go straight
2246 * to picking the next task.
2248 switch_count = &prev->nivcsw;
2249 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2250 switch_count = &prev->nvcsw;
2251 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2252 unlikely(signal_pending(prev))))
2253 prev->state = TASK_RUNNING;
2255 deactivate_task(prev, rq);
2258 cpu = smp_processor_id();
2259 #ifdef CONFIG_VSERVER_HARDCPU
2260 if (!list_empty(&rq->hold_queue)) {
2261 struct list_head *l, *n;
2265 list_for_each_safe(l, n, &rq->hold_queue) {
2266 next = list_entry(l, task_t, run_list);
2267 if (vxi == next->vx_info)
2270 vxi = next->vx_info;
2271 ret = vx_tokens_recalc(vxi);
2272 // tokens = vx_tokens_avail(next);
2275 list_del(&next->run_list);
2276 next->state &= ~TASK_ONHOLD;
2277 recalc_task_prio(next, now);
2278 __activate_task(next, rq);
2279 // printk("··· unhold %p\n", next);
2282 if ((ret < 0) && (maxidle < ret))
2286 rq->idle_tokens = -maxidle;
2290 if (unlikely(!rq->nr_running)) {
2291 idle_balance(cpu, rq);
2292 if (!rq->nr_running) {
2294 rq->expired_timestamp = 0;
2295 wake_sleeping_dependent(cpu, rq);
2301 if (unlikely(!array->nr_active)) {
2303 * Switch the active and expired arrays.
2305 rq->active = rq->expired;
2306 rq->expired = array;
2308 rq->expired_timestamp = 0;
2309 rq->best_expired_prio = MAX_PRIO;
2312 idx = sched_find_first_bit(array->bitmap);
2313 queue = array->queue + idx;
2314 next = list_entry(queue->next, task_t, run_list);
2316 if (dependent_sleeper(cpu, rq, next)) {
2321 #ifdef CONFIG_VSERVER_HARDCPU
2322 vxi = next->vx_info;
2323 if (vxi && __vx_flags(vxi->vx_flags,
2324 VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2325 int ret = vx_tokens_recalc(vxi);
2327 if (unlikely(ret <= 0)) {
2328 if (ret && (rq->idle_tokens > -ret))
2329 rq->idle_tokens = -ret;
2330 deactivate_task(next, rq);
2331 list_add_tail(&next->run_list, &rq->hold_queue);
2332 next->state |= TASK_ONHOLD;
2338 if (!rt_task(next) && next->activated > 0) {
2339 unsigned long long delta = now - next->timestamp;
2341 if (next->activated == 1)
2342 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2344 array = next->array;
2345 dequeue_task(next, array);
2346 recalc_task_prio(next, next->timestamp + delta);
2347 enqueue_task(next, array);
2349 next->activated = 0;
2352 clear_tsk_need_resched(prev);
2353 RCU_qsctr(task_cpu(prev))++;
2355 prev->sleep_avg -= run_time;
2356 if ((long)prev->sleep_avg <= 0) {
2357 prev->sleep_avg = 0;
2358 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2359 prev->interactive_credit--;
2361 add_delay_ts(prev,runcpu_total,prev->timestamp,now);
2362 prev->timestamp = now;
2364 if (likely(prev != next)) {
2365 add_delay_ts(next,waitcpu_total,next->timestamp,now);
2366 inc_delay(next,runs);
2367 next->timestamp = now;
2372 prepare_arch_switch(rq, next);
2373 prev = context_switch(rq, prev, next);
2376 finish_task_switch(prev);
2378 spin_unlock_irq(&rq->lock);
2380 reacquire_kernel_lock(current);
2381 preempt_enable_no_resched();
2382 if (test_thread_flag(TIF_NEED_RESCHED))
2386 EXPORT_SYMBOL(schedule);
2388 #ifdef CONFIG_PREEMPT
2390 * this is is the entry point to schedule() from in-kernel preemption
2391 * off of preempt_enable. Kernel preemptions off return from interrupt
2392 * occur there and call schedule directly.
2394 asmlinkage void __sched preempt_schedule(void)
2396 struct thread_info *ti = current_thread_info();
2399 * If there is a non-zero preempt_count or interrupts are disabled,
2400 * we do not want to preempt the current task. Just return..
2402 if (unlikely(ti->preempt_count || irqs_disabled()))
2406 ti->preempt_count = PREEMPT_ACTIVE;
2408 ti->preempt_count = 0;
2410 /* we could miss a preemption opportunity between schedule and now */
2412 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2416 EXPORT_SYMBOL(preempt_schedule);
2417 #endif /* CONFIG_PREEMPT */
2419 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2421 task_t *p = curr->task;
2422 return try_to_wake_up(p, mode, sync);
2425 EXPORT_SYMBOL(default_wake_function);
2428 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2429 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2430 * number) then we wake all the non-exclusive tasks and one exclusive task.
2432 * There are circumstances in which we can try to wake a task which has already
2433 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2434 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2436 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2437 int nr_exclusive, int sync, void *key)
2439 struct list_head *tmp, *next;
2441 list_for_each_safe(tmp, next, &q->task_list) {
2444 curr = list_entry(tmp, wait_queue_t, task_list);
2445 flags = curr->flags;
2446 if (curr->func(curr, mode, sync, key) &&
2447 (flags & WQ_FLAG_EXCLUSIVE) &&
2454 * __wake_up - wake up threads blocked on a waitqueue.
2456 * @mode: which threads
2457 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2459 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2460 int nr_exclusive, void *key)
2462 unsigned long flags;
2464 spin_lock_irqsave(&q->lock, flags);
2465 __wake_up_common(q, mode, nr_exclusive, 0, key);
2466 spin_unlock_irqrestore(&q->lock, flags);
2469 EXPORT_SYMBOL(__wake_up);
2472 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2474 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2476 __wake_up_common(q, mode, 1, 0, NULL);
2480 * __wake_up - sync- wake up threads blocked on a waitqueue.
2482 * @mode: which threads
2483 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2485 * The sync wakeup differs that the waker knows that it will schedule
2486 * away soon, so while the target thread will be woken up, it will not
2487 * be migrated to another CPU - ie. the two threads are 'synchronized'
2488 * with each other. This can prevent needless bouncing between CPUs.
2490 * On UP it can prevent extra preemption.
2492 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2494 unsigned long flags;
2500 if (unlikely(!nr_exclusive))
2503 spin_lock_irqsave(&q->lock, flags);
2504 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2505 spin_unlock_irqrestore(&q->lock, flags);
2507 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2509 void fastcall complete(struct completion *x)
2511 unsigned long flags;
2513 spin_lock_irqsave(&x->wait.lock, flags);
2515 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2517 spin_unlock_irqrestore(&x->wait.lock, flags);
2519 EXPORT_SYMBOL(complete);
2521 void fastcall complete_all(struct completion *x)
2523 unsigned long flags;
2525 spin_lock_irqsave(&x->wait.lock, flags);
2526 x->done += UINT_MAX/2;
2527 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2529 spin_unlock_irqrestore(&x->wait.lock, flags);
2531 EXPORT_SYMBOL(complete_all);
2533 void fastcall __sched wait_for_completion(struct completion *x)
2536 spin_lock_irq(&x->wait.lock);
2538 DECLARE_WAITQUEUE(wait, current);
2540 wait.flags |= WQ_FLAG_EXCLUSIVE;
2541 __add_wait_queue_tail(&x->wait, &wait);
2543 __set_current_state(TASK_UNINTERRUPTIBLE);
2544 spin_unlock_irq(&x->wait.lock);
2546 spin_lock_irq(&x->wait.lock);
2548 __remove_wait_queue(&x->wait, &wait);
2551 spin_unlock_irq(&x->wait.lock);
2553 EXPORT_SYMBOL(wait_for_completion);
2555 #define SLEEP_ON_VAR \
2556 unsigned long flags; \
2557 wait_queue_t wait; \
2558 init_waitqueue_entry(&wait, current);
2560 #define SLEEP_ON_HEAD \
2561 spin_lock_irqsave(&q->lock,flags); \
2562 __add_wait_queue(q, &wait); \
2563 spin_unlock(&q->lock);
2565 #define SLEEP_ON_TAIL \
2566 spin_lock_irq(&q->lock); \
2567 __remove_wait_queue(q, &wait); \
2568 spin_unlock_irqrestore(&q->lock, flags);
2570 #define SLEEP_ON_BKLCHECK \
2571 if (unlikely(!kernel_locked()) && \
2572 sleep_on_bkl_warnings < 10) { \
2573 sleep_on_bkl_warnings++; \
2577 static int sleep_on_bkl_warnings;
2579 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2585 current->state = TASK_INTERRUPTIBLE;
2592 EXPORT_SYMBOL(interruptible_sleep_on);
2594 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2600 current->state = TASK_INTERRUPTIBLE;
2603 timeout = schedule_timeout(timeout);
2609 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2611 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2617 current->state = TASK_UNINTERRUPTIBLE;
2620 timeout = schedule_timeout(timeout);
2626 EXPORT_SYMBOL(sleep_on_timeout);
2628 void set_user_nice(task_t *p, long nice)
2630 unsigned long flags;
2631 prio_array_t *array;
2633 int old_prio, new_prio, delta;
2635 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2638 * We have to be careful, if called from sys_setpriority(),
2639 * the task might be in the middle of scheduling on another CPU.
2641 rq = task_rq_lock(p, &flags);
2643 * The RT priorities are set via setscheduler(), but we still
2644 * allow the 'normal' nice value to be set - but as expected
2645 * it wont have any effect on scheduling until the task is
2649 p->static_prio = NICE_TO_PRIO(nice);
2654 dequeue_task(p, array);
2657 new_prio = NICE_TO_PRIO(nice);
2658 delta = new_prio - old_prio;
2659 p->static_prio = NICE_TO_PRIO(nice);
2663 enqueue_task(p, array);
2665 * If the task increased its priority or is running and
2666 * lowered its priority, then reschedule its CPU:
2668 if (delta < 0 || (delta > 0 && task_running(rq, p)))
2669 resched_task(rq->curr);
2672 task_rq_unlock(rq, &flags);
2675 EXPORT_SYMBOL(set_user_nice);
2677 #ifdef __ARCH_WANT_SYS_NICE
2680 * sys_nice - change the priority of the current process.
2681 * @increment: priority increment
2683 * sys_setpriority is a more generic, but much slower function that
2684 * does similar things.
2686 asmlinkage long sys_nice(int increment)
2692 * Setpriority might change our priority at the same moment.
2693 * We don't have to worry. Conceptually one call occurs first
2694 * and we have a single winner.
2696 if (increment < 0) {
2697 if (!capable(CAP_SYS_NICE))
2699 if (increment < -40)
2705 nice = PRIO_TO_NICE(current->static_prio) + increment;
2711 retval = security_task_setnice(current, nice);
2715 set_user_nice(current, nice);
2722 * task_prio - return the priority value of a given task.
2723 * @p: the task in question.
2725 * This is the priority value as seen by users in /proc.
2726 * RT tasks are offset by -200. Normal tasks are centered
2727 * around 0, value goes from -16 to +15.
2729 int task_prio(const task_t *p)
2731 return p->prio - MAX_RT_PRIO;
2735 * task_nice - return the nice value of a given task.
2736 * @p: the task in question.
2738 int task_nice(const task_t *p)
2740 return TASK_NICE(p);
2743 EXPORT_SYMBOL(task_nice);
2746 * idle_cpu - is a given cpu idle currently?
2747 * @cpu: the processor in question.
2749 int idle_cpu(int cpu)
2751 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
2754 EXPORT_SYMBOL_GPL(idle_cpu);
2757 * find_process_by_pid - find a process with a matching PID value.
2758 * @pid: the pid in question.
2760 static inline task_t *find_process_by_pid(pid_t pid)
2762 return pid ? find_task_by_pid(pid) : current;
2765 /* Actually do priority change: must hold rq lock. */
2766 static void __setscheduler(struct task_struct *p, int policy, int prio)
2770 p->rt_priority = prio;
2771 if (policy != SCHED_NORMAL)
2772 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
2774 p->prio = p->static_prio;
2778 * setscheduler - change the scheduling policy and/or RT priority of a thread.
2780 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
2782 struct sched_param lp;
2783 int retval = -EINVAL;
2785 prio_array_t *array;
2786 unsigned long flags;
2790 if (!param || pid < 0)
2794 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
2798 * We play safe to avoid deadlocks.
2800 read_lock_irq(&tasklist_lock);
2802 p = find_process_by_pid(pid);
2806 goto out_unlock_tasklist;
2809 * To be able to change p->policy safely, the apropriate
2810 * runqueue lock must be held.
2812 rq = task_rq_lock(p, &flags);
2818 if (policy != SCHED_FIFO && policy != SCHED_RR &&
2819 policy != SCHED_NORMAL)
2824 * Valid priorities for SCHED_FIFO and SCHED_RR are
2825 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
2828 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
2830 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
2834 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
2835 !capable(CAP_SYS_NICE))
2837 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2838 !capable(CAP_SYS_NICE))
2841 retval = security_task_setscheduler(p, policy, &lp);
2847 deactivate_task(p, task_rq(p));
2850 __setscheduler(p, policy, lp.sched_priority);
2852 __activate_task(p, task_rq(p));
2854 * Reschedule if we are currently running on this runqueue and
2855 * our priority decreased, or if we are not currently running on
2856 * this runqueue and our priority is higher than the current's
2858 if (task_running(rq, p)) {
2859 if (p->prio > oldprio)
2860 resched_task(rq->curr);
2861 } else if (TASK_PREEMPTS_CURR(p, rq))
2862 resched_task(rq->curr);
2866 task_rq_unlock(rq, &flags);
2867 out_unlock_tasklist:
2868 read_unlock_irq(&tasklist_lock);
2875 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
2876 * @pid: the pid in question.
2877 * @policy: new policy
2878 * @param: structure containing the new RT priority.
2880 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
2881 struct sched_param __user *param)
2883 return setscheduler(pid, policy, param);
2887 * sys_sched_setparam - set/change the RT priority of a thread
2888 * @pid: the pid in question.
2889 * @param: structure containing the new RT priority.
2891 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
2893 return setscheduler(pid, -1, param);
2897 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
2898 * @pid: the pid in question.
2900 asmlinkage long sys_sched_getscheduler(pid_t pid)
2902 int retval = -EINVAL;
2909 read_lock(&tasklist_lock);
2910 p = find_process_by_pid(pid);
2912 retval = security_task_getscheduler(p);
2916 read_unlock(&tasklist_lock);
2923 * sys_sched_getscheduler - get the RT priority of a thread
2924 * @pid: the pid in question.
2925 * @param: structure containing the RT priority.
2927 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
2929 struct sched_param lp;
2930 int retval = -EINVAL;
2933 if (!param || pid < 0)
2936 read_lock(&tasklist_lock);
2937 p = find_process_by_pid(pid);
2942 retval = security_task_getscheduler(p);
2946 lp.sched_priority = p->rt_priority;
2947 read_unlock(&tasklist_lock);
2950 * This one might sleep, we cannot do it with a spinlock held ...
2952 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
2958 read_unlock(&tasklist_lock);
2963 * sys_sched_setaffinity - set the cpu affinity of a process
2964 * @pid: pid of the process
2965 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2966 * @user_mask_ptr: user-space pointer to the new cpu mask
2968 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
2969 unsigned long __user *user_mask_ptr)
2975 if (len < sizeof(new_mask))
2978 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
2982 read_lock(&tasklist_lock);
2984 p = find_process_by_pid(pid);
2986 read_unlock(&tasklist_lock);
2987 unlock_cpu_hotplug();
2992 * It is not safe to call set_cpus_allowed with the
2993 * tasklist_lock held. We will bump the task_struct's
2994 * usage count and then drop tasklist_lock.
2997 read_unlock(&tasklist_lock);
3000 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3001 !capable(CAP_SYS_NICE))
3004 retval = set_cpus_allowed(p, new_mask);
3008 unlock_cpu_hotplug();
3013 * sys_sched_getaffinity - get the cpu affinity of a process
3014 * @pid: pid of the process
3015 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3016 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3018 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3019 unsigned long __user *user_mask_ptr)
3021 unsigned int real_len;
3026 real_len = sizeof(mask);
3031 read_lock(&tasklist_lock);
3034 p = find_process_by_pid(pid);
3039 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
3042 read_unlock(&tasklist_lock);
3043 unlock_cpu_hotplug();
3046 if (copy_to_user(user_mask_ptr, &mask, real_len))
3052 * sys_sched_yield - yield the current processor to other threads.
3054 * this function yields the current CPU by moving the calling thread
3055 * to the expired array. If there are no other threads running on this
3056 * CPU then this function will return.
3058 asmlinkage long sys_sched_yield(void)
3060 runqueue_t *rq = this_rq_lock();
3061 prio_array_t *array = current->array;
3062 prio_array_t *target = rq->expired;
3065 * We implement yielding by moving the task into the expired
3068 * (special rule: RT tasks will just roundrobin in the active
3071 if (unlikely(rt_task(current)))
3072 target = rq->active;
3074 dequeue_task(current, array);
3075 enqueue_task(current, target);
3078 * Since we are going to call schedule() anyway, there's
3079 * no need to preempt or enable interrupts:
3081 _raw_spin_unlock(&rq->lock);
3082 preempt_enable_no_resched();
3089 void __sched __cond_resched(void)
3091 set_current_state(TASK_RUNNING);
3095 EXPORT_SYMBOL(__cond_resched);
3098 * yield - yield the current processor to other threads.
3100 * this is a shortcut for kernel-space yielding - it marks the
3101 * thread runnable and calls sys_sched_yield().
3103 void __sched yield(void)
3105 set_current_state(TASK_RUNNING);
3109 EXPORT_SYMBOL(yield);
3112 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3113 * that process accounting knows that this is a task in IO wait state.
3115 * But don't do that if it is a deliberate, throttling IO wait (this task
3116 * has set its backing_dev_info: the queue against which it should throttle)
3118 void __sched io_schedule(void)
3120 struct runqueue *rq = this_rq();
3121 def_delay_var(dstart);
3123 start_delay_set(dstart,PF_IOWAIT);
3124 atomic_inc(&rq->nr_iowait);
3126 atomic_dec(&rq->nr_iowait);
3127 add_io_delay(dstart);
3130 EXPORT_SYMBOL(io_schedule);
3132 long __sched io_schedule_timeout(long timeout)
3134 struct runqueue *rq = this_rq();
3136 def_delay_var(dstart);
3138 start_delay_set(dstart,PF_IOWAIT);
3139 atomic_inc(&rq->nr_iowait);
3140 ret = schedule_timeout(timeout);
3141 atomic_dec(&rq->nr_iowait);
3142 add_io_delay(dstart);
3147 * sys_sched_get_priority_max - return maximum RT priority.
3148 * @policy: scheduling class.
3150 * this syscall returns the maximum rt_priority that can be used
3151 * by a given scheduling class.
3153 asmlinkage long sys_sched_get_priority_max(int policy)
3160 ret = MAX_USER_RT_PRIO-1;
3170 * sys_sched_get_priority_min - return minimum RT priority.
3171 * @policy: scheduling class.
3173 * this syscall returns the minimum rt_priority that can be used
3174 * by a given scheduling class.
3176 asmlinkage long sys_sched_get_priority_min(int policy)
3192 * sys_sched_rr_get_interval - return the default timeslice of a process.
3193 * @pid: pid of the process.
3194 * @interval: userspace pointer to the timeslice value.
3196 * this syscall writes the default timeslice value of a given process
3197 * into the user-space timespec buffer. A value of '0' means infinity.
3200 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3202 int retval = -EINVAL;
3210 read_lock(&tasklist_lock);
3211 p = find_process_by_pid(pid);
3215 retval = security_task_getscheduler(p);
3219 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3220 0 : task_timeslice(p), &t);
3221 read_unlock(&tasklist_lock);
3222 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3226 read_unlock(&tasklist_lock);
3230 static inline struct task_struct *eldest_child(struct task_struct *p)
3232 if (list_empty(&p->children)) return NULL;
3233 return list_entry(p->children.next,struct task_struct,sibling);
3236 static inline struct task_struct *older_sibling(struct task_struct *p)
3238 if (p->sibling.prev==&p->parent->children) return NULL;
3239 return list_entry(p->sibling.prev,struct task_struct,sibling);
3242 static inline struct task_struct *younger_sibling(struct task_struct *p)
3244 if (p->sibling.next==&p->parent->children) return NULL;
3245 return list_entry(p->sibling.next,struct task_struct,sibling);
3248 static void show_task(task_t * p)
3252 unsigned long free = 0;
3253 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3255 printk("%-13.13s ", p->comm);
3256 state = p->state ? __ffs(p->state) + 1 : 0;
3257 if (state < ARRAY_SIZE(stat_nam))
3258 printk(stat_nam[state]);
3261 #if (BITS_PER_LONG == 32)
3262 if (state == TASK_RUNNING)
3263 printk(" running ");
3265 printk(" %08lX ", thread_saved_pc(p));
3267 if (state == TASK_RUNNING)
3268 printk(" running task ");
3270 printk(" %016lx ", thread_saved_pc(p));
3272 #ifdef CONFIG_DEBUG_STACK_USAGE
3274 unsigned long * n = (unsigned long *) (p->thread_info+1);
3277 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3280 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3281 if ((relative = eldest_child(p)))
3282 printk("%5d ", relative->pid);
3285 if ((relative = younger_sibling(p)))
3286 printk("%7d", relative->pid);
3289 if ((relative = older_sibling(p)))
3290 printk(" %5d", relative->pid);
3294 printk(" (L-TLB)\n");
3296 printk(" (NOTLB)\n");
3298 if (state != TASK_RUNNING)
3299 show_stack(p, NULL);
3302 void show_state(void)
3306 #if (BITS_PER_LONG == 32)
3309 printk(" task PC pid father child younger older\n");
3313 printk(" task PC pid father child younger older\n");
3315 read_lock(&tasklist_lock);
3316 do_each_thread(g, p) {
3318 * reset the NMI-timeout, listing all files on a slow
3319 * console might take alot of time:
3321 touch_nmi_watchdog();
3323 } while_each_thread(g, p);
3325 read_unlock(&tasklist_lock);
3328 void __devinit init_idle(task_t *idle, int cpu)
3330 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3331 unsigned long flags;
3333 local_irq_save(flags);
3334 double_rq_lock(idle_rq, rq);
3336 idle_rq->curr = idle_rq->idle = idle;
3337 deactivate_task(idle, rq);
3339 idle->prio = MAX_PRIO;
3340 idle->state = TASK_RUNNING;
3341 set_task_cpu(idle, cpu);
3342 double_rq_unlock(idle_rq, rq);
3343 set_tsk_need_resched(idle);
3344 local_irq_restore(flags);
3346 /* Set the preempt count _outside_ the spinlocks! */
3347 #ifdef CONFIG_PREEMPT
3348 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3350 idle->thread_info->preempt_count = 0;
3355 * In a system that switches off the HZ timer nohz_cpu_mask
3356 * indicates which cpus entered this state. This is used
3357 * in the rcu update to wait only for active cpus. For system
3358 * which do not switch off the HZ timer nohz_cpu_mask should
3359 * always be CPU_MASK_NONE.
3361 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3365 * This is how migration works:
3367 * 1) we queue a migration_req_t structure in the source CPU's
3368 * runqueue and wake up that CPU's migration thread.
3369 * 2) we down() the locked semaphore => thread blocks.
3370 * 3) migration thread wakes up (implicitly it forces the migrated
3371 * thread off the CPU)
3372 * 4) it gets the migration request and checks whether the migrated
3373 * task is still in the wrong runqueue.
3374 * 5) if it's in the wrong runqueue then the migration thread removes
3375 * it and puts it into the right queue.
3376 * 6) migration thread up()s the semaphore.
3377 * 7) we wake up and the migration is done.
3381 * Change a given task's CPU affinity. Migrate the thread to a
3382 * proper CPU and schedule it away if the CPU it's executing on
3383 * is removed from the allowed bitmask.
3385 * NOTE: the caller must have a valid reference to the task, the
3386 * task must not exit() & deallocate itself prematurely. The
3387 * call is not atomic; no spinlocks may be held.
3389 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3391 unsigned long flags;
3393 migration_req_t req;
3396 rq = task_rq_lock(p, &flags);
3397 if (any_online_cpu(new_mask) == NR_CPUS) {
3402 p->cpus_allowed = new_mask;
3403 /* Can the task run on the task's current CPU? If so, we're done */
3404 if (cpu_isset(task_cpu(p), new_mask))
3407 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3408 /* Need help from migration thread: drop lock and wait. */
3409 task_rq_unlock(rq, &flags);
3410 wake_up_process(rq->migration_thread);
3411 wait_for_completion(&req.done);
3415 task_rq_unlock(rq, &flags);
3419 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3422 * Move (not current) task off this cpu, onto dest cpu. We're doing
3423 * this because either it can't run here any more (set_cpus_allowed()
3424 * away from this CPU, or CPU going down), or because we're
3425 * attempting to rebalance this task on exec (sched_balance_exec).
3427 * So we race with normal scheduler movements, but that's OK, as long
3428 * as the task is no longer on this CPU.
3430 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3432 runqueue_t *rq_dest, *rq_src;
3434 if (unlikely(cpu_is_offline(dest_cpu)))
3437 rq_src = cpu_rq(src_cpu);
3438 rq_dest = cpu_rq(dest_cpu);
3440 double_rq_lock(rq_src, rq_dest);
3441 /* Already moved. */
3442 if (task_cpu(p) != src_cpu)
3444 /* Affinity changed (again). */
3445 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3448 set_task_cpu(p, dest_cpu);
3451 * Sync timestamp with rq_dest's before activating.
3452 * The same thing could be achieved by doing this step
3453 * afterwards, and pretending it was a local activate.
3454 * This way is cleaner and logically correct.
3456 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3457 + rq_dest->timestamp_last_tick;
3458 deactivate_task(p, rq_src);
3459 activate_task(p, rq_dest, 0);
3460 if (TASK_PREEMPTS_CURR(p, rq_dest))
3461 resched_task(rq_dest->curr);
3465 double_rq_unlock(rq_src, rq_dest);
3469 * migration_thread - this is a highprio system thread that performs
3470 * thread migration by bumping thread off CPU then 'pushing' onto
3473 static int migration_thread(void * data)
3476 int cpu = (long)data;
3479 BUG_ON(rq->migration_thread != current);
3481 set_current_state(TASK_INTERRUPTIBLE);
3482 while (!kthread_should_stop()) {
3483 struct list_head *head;
3484 migration_req_t *req;
3486 if (current->flags & PF_FREEZE)
3487 refrigerator(PF_FREEZE);
3489 spin_lock_irq(&rq->lock);
3491 if (cpu_is_offline(cpu)) {
3492 spin_unlock_irq(&rq->lock);
3496 if (rq->active_balance) {
3497 active_load_balance(rq, cpu);
3498 rq->active_balance = 0;
3501 head = &rq->migration_queue;
3503 if (list_empty(head)) {
3504 spin_unlock_irq(&rq->lock);
3506 set_current_state(TASK_INTERRUPTIBLE);
3509 req = list_entry(head->next, migration_req_t, list);
3510 list_del_init(head->next);
3512 if (req->type == REQ_MOVE_TASK) {
3513 spin_unlock(&rq->lock);
3514 __migrate_task(req->task, smp_processor_id(),
3517 } else if (req->type == REQ_SET_DOMAIN) {
3519 spin_unlock_irq(&rq->lock);
3521 spin_unlock_irq(&rq->lock);
3525 complete(&req->done);
3527 __set_current_state(TASK_RUNNING);
3531 /* Wait for kthread_stop */
3532 set_current_state(TASK_INTERRUPTIBLE);
3533 while (!kthread_should_stop()) {
3535 set_current_state(TASK_INTERRUPTIBLE);
3537 __set_current_state(TASK_RUNNING);
3541 #ifdef CONFIG_HOTPLUG_CPU
3542 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
3543 static void migrate_all_tasks(int src_cpu)
3545 struct task_struct *tsk, *t;
3549 write_lock_irq(&tasklist_lock);
3551 /* watch out for per node tasks, let's stay on this node */
3552 node = cpu_to_node(src_cpu);
3554 do_each_thread(t, tsk) {
3559 if (task_cpu(tsk) != src_cpu)
3562 /* Figure out where this task should go (attempting to
3563 * keep it on-node), and check if it can be migrated
3564 * as-is. NOTE that kernel threads bound to more than
3565 * one online cpu will be migrated. */
3566 mask = node_to_cpumask(node);
3567 cpus_and(mask, mask, tsk->cpus_allowed);
3568 dest_cpu = any_online_cpu(mask);
3569 if (dest_cpu == NR_CPUS)
3570 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3571 if (dest_cpu == NR_CPUS) {
3572 cpus_clear(tsk->cpus_allowed);
3573 cpus_complement(tsk->cpus_allowed);
3574 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3576 /* Don't tell them about moving exiting tasks
3577 or kernel threads (both mm NULL), since
3578 they never leave kernel. */
3579 if (tsk->mm && printk_ratelimit())
3580 printk(KERN_INFO "process %d (%s) no "
3581 "longer affine to cpu%d\n",
3582 tsk->pid, tsk->comm, src_cpu);
3585 __migrate_task(tsk, src_cpu, dest_cpu);
3586 } while_each_thread(t, tsk);
3588 write_unlock_irq(&tasklist_lock);
3591 /* Schedules idle task to be the next runnable task on current CPU.
3592 * It does so by boosting its priority to highest possible and adding it to
3593 * the _front_ of runqueue. Used by CPU offline code.
3595 void sched_idle_next(void)
3597 int cpu = smp_processor_id();
3598 runqueue_t *rq = this_rq();
3599 struct task_struct *p = rq->idle;
3600 unsigned long flags;
3602 /* cpu has to be offline */
3603 BUG_ON(cpu_online(cpu));
3605 /* Strictly not necessary since rest of the CPUs are stopped by now
3606 * and interrupts disabled on current cpu.
3608 spin_lock_irqsave(&rq->lock, flags);
3610 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3611 /* Add idle task to _front_ of it's priority queue */
3612 __activate_idle_task(p, rq);
3614 spin_unlock_irqrestore(&rq->lock, flags);
3616 #endif /* CONFIG_HOTPLUG_CPU */
3619 * migration_call - callback that gets triggered when a CPU is added.
3620 * Here we can start up the necessary migration thread for the new CPU.
3622 static int migration_call(struct notifier_block *nfb, unsigned long action,
3625 int cpu = (long)hcpu;
3626 struct task_struct *p;
3627 struct runqueue *rq;
3628 unsigned long flags;
3631 case CPU_UP_PREPARE:
3632 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
3635 kthread_bind(p, cpu);
3636 /* Must be high prio: stop_machine expects to yield to it. */
3637 rq = task_rq_lock(p, &flags);
3638 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3639 task_rq_unlock(rq, &flags);
3640 cpu_rq(cpu)->migration_thread = p;
3643 /* Strictly unneccessary, as first user will wake it. */
3644 wake_up_process(cpu_rq(cpu)->migration_thread);
3646 #ifdef CONFIG_HOTPLUG_CPU
3647 case CPU_UP_CANCELED:
3648 /* Unbind it from offline cpu so it can run. Fall thru. */
3649 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
3650 kthread_stop(cpu_rq(cpu)->migration_thread);
3651 cpu_rq(cpu)->migration_thread = NULL;
3654 migrate_all_tasks(cpu);
3656 kthread_stop(rq->migration_thread);
3657 rq->migration_thread = NULL;
3658 /* Idle task back to normal (off runqueue, low prio) */
3659 rq = task_rq_lock(rq->idle, &flags);
3660 deactivate_task(rq->idle, rq);
3661 rq->idle->static_prio = MAX_PRIO;
3662 __setscheduler(rq->idle, SCHED_NORMAL, 0);
3663 task_rq_unlock(rq, &flags);
3664 BUG_ON(rq->nr_running != 0);
3666 /* No need to migrate the tasks: it was best-effort if
3667 * they didn't do lock_cpu_hotplug(). Just wake up
3668 * the requestors. */
3669 spin_lock_irq(&rq->lock);
3670 while (!list_empty(&rq->migration_queue)) {
3671 migration_req_t *req;
3672 req = list_entry(rq->migration_queue.next,
3673 migration_req_t, list);
3674 BUG_ON(req->type != REQ_MOVE_TASK);
3675 list_del_init(&req->list);
3676 complete(&req->done);
3678 spin_unlock_irq(&rq->lock);
3685 /* Register at highest priority so that task migration (migrate_all_tasks)
3686 * happens before everything else.
3688 static struct notifier_block __devinitdata migration_notifier = {
3689 .notifier_call = migration_call,
3693 int __init migration_init(void)
3695 void *cpu = (void *)(long)smp_processor_id();
3696 /* Start one for boot CPU. */
3697 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
3698 migration_call(&migration_notifier, CPU_ONLINE, cpu);
3699 register_cpu_notifier(&migration_notifier);
3705 * The 'big kernel lock'
3707 * This spinlock is taken and released recursively by lock_kernel()
3708 * and unlock_kernel(). It is transparently dropped and reaquired
3709 * over schedule(). It is used to protect legacy code that hasn't
3710 * been migrated to a proper locking design yet.
3712 * Don't use in new code.
3714 * Note: spinlock debugging needs this even on !CONFIG_SMP.
3716 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
3717 EXPORT_SYMBOL(kernel_flag);
3720 /* Attach the domain 'sd' to 'cpu' as its base domain */
3721 void cpu_attach_domain(struct sched_domain *sd, int cpu)
3723 migration_req_t req;
3724 unsigned long flags;
3725 runqueue_t *rq = cpu_rq(cpu);
3730 spin_lock_irqsave(&rq->lock, flags);
3732 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
3735 init_completion(&req.done);
3736 req.type = REQ_SET_DOMAIN;
3738 list_add(&req.list, &rq->migration_queue);
3742 spin_unlock_irqrestore(&rq->lock, flags);
3745 wake_up_process(rq->migration_thread);
3746 wait_for_completion(&req.done);
3749 unlock_cpu_hotplug();
3752 #ifdef ARCH_HAS_SCHED_DOMAIN
3753 extern void __init arch_init_sched_domains(void);
3755 static struct sched_group sched_group_cpus[NR_CPUS];
3756 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
3758 static struct sched_group sched_group_nodes[MAX_NUMNODES];
3759 static DEFINE_PER_CPU(struct sched_domain, node_domains);
3760 static void __init arch_init_sched_domains(void)
3763 struct sched_group *first_node = NULL, *last_node = NULL;
3765 /* Set up domains */
3767 int node = cpu_to_node(i);
3768 cpumask_t nodemask = node_to_cpumask(node);
3769 struct sched_domain *node_sd = &per_cpu(node_domains, i);
3770 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3772 *node_sd = SD_NODE_INIT;
3773 node_sd->span = cpu_possible_map;
3774 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
3776 *cpu_sd = SD_CPU_INIT;
3777 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
3778 cpu_sd->groups = &sched_group_cpus[i];
3779 cpu_sd->parent = node_sd;
3783 for (i = 0; i < MAX_NUMNODES; i++) {
3784 cpumask_t tmp = node_to_cpumask(i);
3786 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3787 struct sched_group *node = &sched_group_nodes[i];
3790 cpus_and(nodemask, tmp, cpu_possible_map);
3792 if (cpus_empty(nodemask))
3795 node->cpumask = nodemask;
3796 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
3798 for_each_cpu_mask(j, node->cpumask) {
3799 struct sched_group *cpu = &sched_group_cpus[j];
3801 cpus_clear(cpu->cpumask);
3802 cpu_set(j, cpu->cpumask);
3803 cpu->cpu_power = SCHED_LOAD_SCALE;
3808 last_cpu->next = cpu;
3811 last_cpu->next = first_cpu;
3816 last_node->next = node;
3819 last_node->next = first_node;
3823 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3824 cpu_attach_domain(cpu_sd, i);
3828 #else /* !CONFIG_NUMA */
3829 static void __init arch_init_sched_domains(void)
3832 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3834 /* Set up domains */
3836 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3838 *cpu_sd = SD_CPU_INIT;
3839 cpu_sd->span = cpu_possible_map;
3840 cpu_sd->groups = &sched_group_cpus[i];
3843 /* Set up CPU groups */
3844 for_each_cpu_mask(i, cpu_possible_map) {
3845 struct sched_group *cpu = &sched_group_cpus[i];
3847 cpus_clear(cpu->cpumask);
3848 cpu_set(i, cpu->cpumask);
3849 cpu->cpu_power = SCHED_LOAD_SCALE;
3854 last_cpu->next = cpu;
3857 last_cpu->next = first_cpu;
3859 mb(); /* domains were modified outside the lock */
3861 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3862 cpu_attach_domain(cpu_sd, i);
3866 #endif /* CONFIG_NUMA */
3867 #endif /* ARCH_HAS_SCHED_DOMAIN */
3869 #define SCHED_DOMAIN_DEBUG
3870 #ifdef SCHED_DOMAIN_DEBUG
3871 void sched_domain_debug(void)
3876 runqueue_t *rq = cpu_rq(i);
3877 struct sched_domain *sd;
3882 printk(KERN_WARNING "CPU%d: %s\n",
3883 i, (cpu_online(i) ? " online" : "offline"));
3888 struct sched_group *group = sd->groups;
3889 cpumask_t groupmask, tmp;
3891 cpumask_scnprintf(str, NR_CPUS, sd->span);
3892 cpus_clear(groupmask);
3895 for (j = 0; j < level + 1; j++)
3897 printk("domain %d: span %s\n", level, str);
3899 if (!cpu_isset(i, sd->span))
3900 printk(KERN_WARNING "ERROR domain->span does not contain CPU%d\n", i);
3901 if (!cpu_isset(i, group->cpumask))
3902 printk(KERN_WARNING "ERROR domain->groups does not contain CPU%d\n", i);
3903 if (!group->cpu_power)
3904 printk(KERN_WARNING "ERROR domain->cpu_power not set\n");
3906 printk(KERN_WARNING);
3907 for (j = 0; j < level + 2; j++)
3912 printk(" ERROR: NULL");
3916 if (!cpus_weight(group->cpumask))
3917 printk(" ERROR empty group:");
3919 cpus_and(tmp, groupmask, group->cpumask);
3920 if (cpus_weight(tmp) > 0)
3921 printk(" ERROR repeated CPUs:");
3923 cpus_or(groupmask, groupmask, group->cpumask);
3925 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
3928 group = group->next;
3929 } while (group != sd->groups);
3932 if (!cpus_equal(sd->span, groupmask))
3933 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
3939 cpus_and(tmp, groupmask, sd->span);
3940 if (!cpus_equal(tmp, groupmask))
3941 printk(KERN_WARNING "ERROR parent span is not a superset of domain->span\n");
3948 #define sched_domain_debug() {}
3951 void __init sched_init_smp(void)
3953 arch_init_sched_domains();
3954 sched_domain_debug();
3957 void __init sched_init_smp(void)
3960 #endif /* CONFIG_SMP */
3962 int in_sched_functions(unsigned long addr)
3964 /* Linker adds these: start and end of __sched functions */
3965 extern char __sched_text_start[], __sched_text_end[];
3966 return addr >= (unsigned long)__sched_text_start
3967 && addr < (unsigned long)__sched_text_end;
3970 void __init sched_init(void)
3976 /* Set up an initial dummy domain for early boot */
3977 static struct sched_domain sched_domain_init;
3978 static struct sched_group sched_group_init;
3979 cpumask_t cpu_mask_all = CPU_MASK_ALL;
3981 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
3982 sched_domain_init.span = cpu_mask_all;
3983 sched_domain_init.groups = &sched_group_init;
3984 sched_domain_init.last_balance = jiffies;
3985 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
3987 memset(&sched_group_init, 0, sizeof(struct sched_group));
3988 sched_group_init.cpumask = cpu_mask_all;
3989 sched_group_init.next = &sched_group_init;
3990 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
3993 for (i = 0; i < NR_CPUS; i++) {
3994 prio_array_t *array;
3997 spin_lock_init(&rq->lock);
3998 rq->active = rq->arrays;
3999 rq->expired = rq->arrays + 1;
4000 rq->best_expired_prio = MAX_PRIO;
4003 rq->sd = &sched_domain_init;
4005 rq->active_balance = 0;
4007 rq->migration_thread = NULL;
4008 INIT_LIST_HEAD(&rq->migration_queue);
4010 INIT_LIST_HEAD(&rq->hold_queue);
4011 atomic_set(&rq->nr_iowait, 0);
4013 for (j = 0; j < 2; j++) {
4014 array = rq->arrays + j;
4015 for (k = 0; k < MAX_PRIO; k++) {
4016 INIT_LIST_HEAD(array->queue + k);
4017 __clear_bit(k, array->bitmap);
4019 // delimiter for bitsearch
4020 __set_bit(MAX_PRIO, array->bitmap);
4024 * We have to do a little magic to get the first
4025 * thread right in SMP mode.
4030 set_task_cpu(current, smp_processor_id());
4031 wake_up_forked_process(current);
4034 * The boot idle thread does lazy MMU switching as well:
4036 atomic_inc(&init_mm.mm_count);
4037 enter_lazy_tlb(&init_mm, current);
4040 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4041 void __might_sleep(char *file, int line)
4043 #if defined(in_atomic)
4044 static unsigned long prev_jiffy; /* ratelimiting */
4046 if ((in_atomic() || irqs_disabled()) &&
4047 system_state == SYSTEM_RUNNING) {
4048 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4050 prev_jiffy = jiffies;
4051 printk(KERN_ERR "Debug: sleeping function called from invalid"
4052 " context at %s:%d\n", file, line);
4053 printk("in_atomic():%d, irqs_disabled():%d\n",
4054 in_atomic(), irqs_disabled());
4059 EXPORT_SYMBOL(__might_sleep);
4063 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
4065 * This could be a long-held lock. If another CPU holds it for a long time,
4066 * and that CPU is not asked to reschedule then *this* CPU will spin on the
4067 * lock for a long time, even if *this* CPU is asked to reschedule.
4069 * So what we do here, in the slow (contended) path is to spin on the lock by
4070 * hand while permitting preemption.
4072 * Called inside preempt_disable().
4074 void __sched __preempt_spin_lock(spinlock_t *lock)
4076 if (preempt_count() > 1) {
4077 _raw_spin_lock(lock);
4082 while (spin_is_locked(lock))
4085 } while (!_raw_spin_trylock(lock));
4088 EXPORT_SYMBOL(__preempt_spin_lock);
4090 void __sched __preempt_write_lock(rwlock_t *lock)
4092 if (preempt_count() > 1) {
4093 _raw_write_lock(lock);
4099 while (rwlock_is_locked(lock))
4102 } while (!_raw_write_trylock(lock));
4105 EXPORT_SYMBOL(__preempt_write_lock);
4106 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */
4108 #ifdef CONFIG_DELAY_ACCT
4109 int task_running_sys(struct task_struct *p)
4111 return task_running(task_rq(p),p);
4113 EXPORT_SYMBOL(task_running_sys);