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/vinline.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(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);
773 /* Don't pull the task off an idle CPU to a busy one */
774 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
777 new_cpu = this_cpu; /* Wake to this CPU if we can */
780 * Scan domains for affine wakeup and passive balancing
783 for_each_domain(this_cpu, sd) {
784 unsigned int imbalance;
786 * Start passive balancing when half the imbalance_pct
789 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
791 if ( ((sd->flags & SD_WAKE_AFFINE) &&
792 !task_hot(p, rq->timestamp_last_tick, sd))
793 || ((sd->flags & SD_WAKE_BALANCE) &&
794 imbalance*this_load <= 100*load) ) {
796 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
797 * or sd has SD_WAKE_BALANCE and there is an imbalance
799 if (cpu_isset(cpu, sd->span))
804 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
806 new_cpu = wake_idle(new_cpu, p);
807 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
808 set_task_cpu(p, new_cpu);
809 task_rq_unlock(rq, &flags);
810 /* might preempt at this point */
811 rq = task_rq_lock(p, &flags);
812 old_state = p->state;
813 if (!(old_state & state))
818 this_cpu = smp_processor_id();
823 #endif /* CONFIG_SMP */
824 if (old_state == TASK_UNINTERRUPTIBLE) {
825 rq->nr_uninterruptible--;
827 * Tasks on involuntary sleep don't earn
828 * sleep_avg beyond just interactive state.
834 * Sync wakeups (i.e. those types of wakeups where the waker
835 * has indicated that it will leave the CPU in short order)
836 * don't trigger a preemption, if the woken up task will run on
837 * this cpu. (in this case the 'I will reschedule' promise of
838 * the waker guarantees that the freshly woken up task is going
839 * to be considered on this CPU.)
841 activate_task(p, rq, cpu == this_cpu);
842 if (!sync || cpu != this_cpu) {
843 if (TASK_PREEMPTS_CURR(p, rq))
844 resched_task(rq->curr);
849 p->state = TASK_RUNNING;
851 task_rq_unlock(rq, &flags);
856 int fastcall wake_up_process(task_t * p)
858 return try_to_wake_up(p, TASK_STOPPED |
859 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
862 EXPORT_SYMBOL(wake_up_process);
864 int fastcall wake_up_state(task_t *p, unsigned int state)
866 return try_to_wake_up(p, state, 0);
870 * Perform scheduler related setup for a newly forked process p.
871 * p is forked by current.
873 void fastcall sched_fork(task_t *p)
876 * We mark the process as running here, but have not actually
877 * inserted it onto the runqueue yet. This guarantees that
878 * nobody will actually run it, and a signal or other external
879 * event cannot wake it up and insert it on the runqueue either.
881 p->state = TASK_RUNNING;
882 INIT_LIST_HEAD(&p->run_list);
884 spin_lock_init(&p->switch_lock);
885 #ifdef CONFIG_PREEMPT
887 * During context-switch we hold precisely one spinlock, which
888 * schedule_tail drops. (in the common case it's this_rq()->lock,
889 * but it also can be p->switch_lock.) So we compensate with a count
890 * of 1. Also, we want to start with kernel preemption disabled.
892 p->thread_info->preempt_count = 1;
895 * Share the timeslice between parent and child, thus the
896 * total amount of pending timeslices in the system doesn't change,
897 * resulting in more scheduling fairness.
900 p->time_slice = (current->time_slice + 1) >> 1;
902 * The remainder of the first timeslice might be recovered by
903 * the parent if the child exits early enough.
905 p->first_time_slice = 1;
906 current->time_slice >>= 1;
907 p->timestamp = sched_clock();
908 if (!current->time_slice) {
910 * This case is rare, it happens when the parent has only
911 * a single jiffy left from its timeslice. Taking the
912 * runqueue lock is not a problem.
914 current->time_slice = 1;
916 scheduler_tick(0, 0);
924 * wake_up_forked_process - wake up a freshly forked process.
926 * This function will do some initial scheduler statistics housekeeping
927 * that must be done for every newly created process.
929 void fastcall wake_up_forked_process(task_t * p)
932 runqueue_t *rq = task_rq_lock(current, &flags);
934 BUG_ON(p->state != TASK_RUNNING);
937 * We decrease the sleep average of forking parents
938 * and children as well, to keep max-interactive tasks
939 * from forking tasks that are max-interactive.
941 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
942 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
944 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
945 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
947 p->interactive_credit = 0;
949 p->prio = effective_prio(p);
950 set_task_cpu(p, smp_processor_id());
952 if (unlikely(!current->array))
953 __activate_task(p, rq);
955 p->prio = current->prio;
956 list_add_tail(&p->run_list, ¤t->run_list);
957 p->array = current->array;
958 p->array->nr_active++;
961 task_rq_unlock(rq, &flags);
965 * Potentially available exiting-child timeslices are
966 * retrieved here - this way the parent does not get
967 * penalized for creating too many threads.
969 * (this cannot be used to 'generate' timeslices
970 * artificially, because any timeslice recovered here
971 * was given away by the parent in the first place.)
973 void fastcall sched_exit(task_t * p)
978 local_irq_save(flags);
979 if (p->first_time_slice) {
980 p->parent->time_slice += p->time_slice;
981 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
982 p->parent->time_slice = MAX_TIMESLICE;
984 local_irq_restore(flags);
986 * If the child was a (relative-) CPU hog then decrease
987 * the sleep_avg of the parent as well.
989 rq = task_rq_lock(p->parent, &flags);
990 if (p->sleep_avg < p->parent->sleep_avg)
991 p->parent->sleep_avg = p->parent->sleep_avg /
992 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
994 task_rq_unlock(rq, &flags);
998 * finish_task_switch - clean up after a task-switch
999 * @prev: the thread we just switched away from.
1001 * We enter this with the runqueue still locked, and finish_arch_switch()
1002 * will unlock it along with doing any other architecture-specific cleanup
1005 * Note that we may have delayed dropping an mm in context_switch(). If
1006 * so, we finish that here outside of the runqueue lock. (Doing it
1007 * with the lock held can cause deadlocks; see schedule() for
1010 static void finish_task_switch(task_t *prev)
1012 runqueue_t *rq = this_rq();
1013 struct mm_struct *mm = rq->prev_mm;
1014 unsigned long prev_task_flags;
1019 * A task struct has one reference for the use as "current".
1020 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1021 * schedule one last time. The schedule call will never return,
1022 * and the scheduled task must drop that reference.
1023 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1024 * still held, otherwise prev could be scheduled on another cpu, die
1025 * there before we look at prev->state, and then the reference would
1027 * Manfred Spraul <manfred@colorfullife.com>
1029 prev_task_flags = prev->flags;
1030 finish_arch_switch(rq, prev);
1033 if (unlikely(prev_task_flags & PF_DEAD))
1034 put_task_struct(prev);
1038 * schedule_tail - first thing a freshly forked thread must call.
1039 * @prev: the thread we just switched away from.
1041 asmlinkage void schedule_tail(task_t *prev)
1043 finish_task_switch(prev);
1045 if (current->set_child_tid)
1046 put_user(current->pid, current->set_child_tid);
1050 * context_switch - switch to the new MM and the new
1051 * thread's register state.
1054 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1056 struct mm_struct *mm = next->mm;
1057 struct mm_struct *oldmm = prev->active_mm;
1059 if (unlikely(!mm)) {
1060 next->active_mm = oldmm;
1061 atomic_inc(&oldmm->mm_count);
1062 enter_lazy_tlb(oldmm, next);
1064 switch_mm(oldmm, mm, next);
1066 if (unlikely(!prev->mm)) {
1067 prev->active_mm = NULL;
1068 WARN_ON(rq->prev_mm);
1069 rq->prev_mm = oldmm;
1072 /* Here we just switch the register state and the stack. */
1073 switch_to(prev, next, prev);
1079 * nr_running, nr_uninterruptible and nr_context_switches:
1081 * externally visible scheduler statistics: current number of runnable
1082 * threads, current number of uninterruptible-sleeping threads, total
1083 * number of context switches performed since bootup.
1085 unsigned long nr_running(void)
1087 unsigned long i, sum = 0;
1090 sum += cpu_rq(i)->nr_running;
1095 unsigned long nr_uninterruptible(void)
1097 unsigned long i, sum = 0;
1099 for_each_online_cpu(i)
1100 sum += cpu_rq(i)->nr_uninterruptible;
1105 unsigned long long nr_context_switches(void)
1107 unsigned long long i, sum = 0;
1109 for_each_online_cpu(i)
1110 sum += cpu_rq(i)->nr_switches;
1115 unsigned long nr_iowait(void)
1117 unsigned long i, sum = 0;
1119 for_each_online_cpu(i)
1120 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1126 * double_rq_lock - safely lock two runqueues
1128 * Note this does not disable interrupts like task_rq_lock,
1129 * you need to do so manually before calling.
1131 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1134 spin_lock(&rq1->lock);
1137 spin_lock(&rq1->lock);
1138 spin_lock(&rq2->lock);
1140 spin_lock(&rq2->lock);
1141 spin_lock(&rq1->lock);
1147 * double_rq_unlock - safely unlock two runqueues
1149 * Note this does not restore interrupts like task_rq_unlock,
1150 * you need to do so manually after calling.
1152 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1154 spin_unlock(&rq1->lock);
1156 spin_unlock(&rq2->lock);
1169 * find_idlest_cpu - find the least busy runqueue.
1171 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1172 struct sched_domain *sd)
1174 unsigned long load, min_load, this_load;
1179 min_load = ULONG_MAX;
1181 cpus_and(mask, sd->span, cpu_online_map);
1182 cpus_and(mask, mask, p->cpus_allowed);
1184 for_each_cpu_mask(i, mask) {
1185 load = target_load(i);
1187 if (load < min_load) {
1191 /* break out early on an idle CPU: */
1197 /* add +1 to account for the new task */
1198 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1201 * Would with the addition of the new task to the
1202 * current CPU there be an imbalance between this
1203 * CPU and the idlest CPU?
1205 * Use half of the balancing threshold - new-context is
1206 * a good opportunity to balance.
1208 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1215 * wake_up_forked_thread - wake up a freshly forked thread.
1217 * This function will do some initial scheduler statistics housekeeping
1218 * that must be done for every newly created context, and it also does
1219 * runqueue balancing.
1221 void fastcall wake_up_forked_thread(task_t * p)
1223 unsigned long flags;
1224 int this_cpu = get_cpu(), cpu;
1225 struct sched_domain *tmp, *sd = NULL;
1226 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1229 * Find the largest domain that this CPU is part of that
1230 * is willing to balance on clone:
1232 for_each_domain(this_cpu, tmp)
1233 if (tmp->flags & SD_BALANCE_CLONE)
1236 cpu = find_idlest_cpu(p, this_cpu, sd);
1240 local_irq_save(flags);
1243 double_rq_lock(this_rq, rq);
1245 BUG_ON(p->state != TASK_RUNNING);
1248 * We did find_idlest_cpu() unlocked, so in theory
1249 * the mask could have changed - just dont migrate
1252 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1254 double_rq_unlock(this_rq, rq);
1258 * We decrease the sleep average of forking parents
1259 * and children as well, to keep max-interactive tasks
1260 * from forking tasks that are max-interactive.
1262 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1263 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1265 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1266 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1268 p->interactive_credit = 0;
1270 p->prio = effective_prio(p);
1271 set_task_cpu(p, cpu);
1273 if (cpu == this_cpu) {
1274 if (unlikely(!current->array))
1275 __activate_task(p, rq);
1277 p->prio = current->prio;
1278 list_add_tail(&p->run_list, ¤t->run_list);
1279 p->array = current->array;
1280 p->array->nr_active++;
1284 /* Not the local CPU - must adjust timestamp */
1285 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1286 + rq->timestamp_last_tick;
1287 __activate_task(p, rq);
1288 if (TASK_PREEMPTS_CURR(p, rq))
1289 resched_task(rq->curr);
1292 double_rq_unlock(this_rq, rq);
1293 local_irq_restore(flags);
1298 * If dest_cpu is allowed for this process, migrate the task to it.
1299 * This is accomplished by forcing the cpu_allowed mask to only
1300 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1301 * the cpu_allowed mask is restored.
1303 static void sched_migrate_task(task_t *p, int dest_cpu)
1305 migration_req_t req;
1307 unsigned long flags;
1309 rq = task_rq_lock(p, &flags);
1310 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1311 || unlikely(cpu_is_offline(dest_cpu)))
1314 /* force the process onto the specified CPU */
1315 if (migrate_task(p, dest_cpu, &req)) {
1316 /* Need to wait for migration thread (might exit: take ref). */
1317 struct task_struct *mt = rq->migration_thread;
1318 get_task_struct(mt);
1319 task_rq_unlock(rq, &flags);
1320 wake_up_process(mt);
1321 put_task_struct(mt);
1322 wait_for_completion(&req.done);
1326 task_rq_unlock(rq, &flags);
1330 * sched_balance_exec(): find the highest-level, exec-balance-capable
1331 * domain and try to migrate the task to the least loaded CPU.
1333 * execve() is a valuable balancing opportunity, because at this point
1334 * the task has the smallest effective memory and cache footprint.
1336 void sched_balance_exec(void)
1338 struct sched_domain *tmp, *sd = NULL;
1339 int new_cpu, this_cpu = get_cpu();
1341 /* Prefer the current CPU if there's only this task running */
1342 if (this_rq()->nr_running <= 1)
1345 for_each_domain(this_cpu, tmp)
1346 if (tmp->flags & SD_BALANCE_EXEC)
1350 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1351 if (new_cpu != this_cpu) {
1353 sched_migrate_task(current, new_cpu);
1362 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1364 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1366 if (unlikely(!spin_trylock(&busiest->lock))) {
1367 if (busiest < this_rq) {
1368 spin_unlock(&this_rq->lock);
1369 spin_lock(&busiest->lock);
1370 spin_lock(&this_rq->lock);
1372 spin_lock(&busiest->lock);
1377 * pull_task - move a task from a remote runqueue to the local runqueue.
1378 * Both runqueues must be locked.
1381 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1382 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1384 dequeue_task(p, src_array);
1385 src_rq->nr_running--;
1386 set_task_cpu(p, this_cpu);
1387 this_rq->nr_running++;
1388 enqueue_task(p, this_array);
1389 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1390 + this_rq->timestamp_last_tick;
1392 * Note that idle threads have a prio of MAX_PRIO, for this test
1393 * to be always true for them.
1395 if (TASK_PREEMPTS_CURR(p, this_rq))
1396 resched_task(this_rq->curr);
1400 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1403 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1404 struct sched_domain *sd, enum idle_type idle)
1407 * We do not migrate tasks that are:
1408 * 1) running (obviously), or
1409 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1410 * 3) are cache-hot on their current CPU.
1412 if (task_running(rq, p))
1414 if (!cpu_isset(this_cpu, p->cpus_allowed))
1417 /* Aggressive migration if we've failed balancing */
1418 if (idle == NEWLY_IDLE ||
1419 sd->nr_balance_failed < sd->cache_nice_tries) {
1420 if (task_hot(p, rq->timestamp_last_tick, sd))
1428 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1429 * as part of a balancing operation within "domain". Returns the number of
1432 * Called with both runqueues locked.
1434 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1435 unsigned long max_nr_move, struct sched_domain *sd,
1436 enum idle_type idle)
1438 prio_array_t *array, *dst_array;
1439 struct list_head *head, *curr;
1440 int idx, pulled = 0;
1443 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1447 * We first consider expired tasks. Those will likely not be
1448 * executed in the near future, and they are most likely to
1449 * be cache-cold, thus switching CPUs has the least effect
1452 if (busiest->expired->nr_active) {
1453 array = busiest->expired;
1454 dst_array = this_rq->expired;
1456 array = busiest->active;
1457 dst_array = this_rq->active;
1461 /* Start searching at priority 0: */
1465 idx = sched_find_first_bit(array->bitmap);
1467 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1468 if (idx >= MAX_PRIO) {
1469 if (array == busiest->expired && busiest->active->nr_active) {
1470 array = busiest->active;
1471 dst_array = this_rq->active;
1477 head = array->queue + idx;
1480 tmp = list_entry(curr, task_t, run_list);
1484 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1490 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1493 /* We only want to steal up to the prescribed number of tasks. */
1494 if (pulled < max_nr_move) {
1505 * find_busiest_group finds and returns the busiest CPU group within the
1506 * domain. It calculates and returns the number of tasks which should be
1507 * moved to restore balance via the imbalance parameter.
1509 static struct sched_group *
1510 find_busiest_group(struct sched_domain *sd, int this_cpu,
1511 unsigned long *imbalance, enum idle_type idle)
1513 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1514 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1516 max_load = this_load = total_load = total_pwr = 0;
1524 local_group = cpu_isset(this_cpu, group->cpumask);
1526 /* Tally up the load of all CPUs in the group */
1528 cpus_and(tmp, group->cpumask, cpu_online_map);
1529 if (unlikely(cpus_empty(tmp)))
1532 for_each_cpu_mask(i, tmp) {
1533 /* Bias balancing toward cpus of our domain */
1535 load = target_load(i);
1537 load = source_load(i);
1546 total_load += avg_load;
1547 total_pwr += group->cpu_power;
1549 /* Adjust by relative CPU power of the group */
1550 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1553 this_load = avg_load;
1556 } else if (avg_load > max_load) {
1557 max_load = avg_load;
1561 group = group->next;
1562 } while (group != sd->groups);
1564 if (!busiest || this_load >= max_load)
1567 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1569 if (this_load >= avg_load ||
1570 100*max_load <= sd->imbalance_pct*this_load)
1574 * We're trying to get all the cpus to the average_load, so we don't
1575 * want to push ourselves above the average load, nor do we wish to
1576 * reduce the max loaded cpu below the average load, as either of these
1577 * actions would just result in more rebalancing later, and ping-pong
1578 * tasks around. Thus we look for the minimum possible imbalance.
1579 * Negative imbalances (*we* are more loaded than anyone else) will
1580 * be counted as no imbalance for these purposes -- we can't fix that
1581 * by pulling tasks to us. Be careful of negative numbers as they'll
1582 * appear as very large values with unsigned longs.
1584 *imbalance = min(max_load - avg_load, avg_load - this_load);
1586 /* How much load to actually move to equalise the imbalance */
1587 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1590 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1591 unsigned long pwr_now = 0, pwr_move = 0;
1594 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1600 * OK, we don't have enough imbalance to justify moving tasks,
1601 * however we may be able to increase total CPU power used by
1605 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1606 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1607 pwr_now /= SCHED_LOAD_SCALE;
1609 /* Amount of load we'd subtract */
1610 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1612 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1615 /* Amount of load we'd add */
1616 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1619 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1620 pwr_move /= SCHED_LOAD_SCALE;
1622 /* Move if we gain another 8th of a CPU worth of throughput */
1623 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1630 /* Get rid of the scaling factor, rounding down as we divide */
1631 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1636 if (busiest && (idle == NEWLY_IDLE ||
1637 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1647 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1649 static runqueue_t *find_busiest_queue(struct sched_group *group)
1652 unsigned long load, max_load = 0;
1653 runqueue_t *busiest = NULL;
1656 cpus_and(tmp, group->cpumask, cpu_online_map);
1657 for_each_cpu_mask(i, tmp) {
1658 load = source_load(i);
1660 if (load > max_load) {
1662 busiest = cpu_rq(i);
1670 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1671 * tasks if there is an imbalance.
1673 * Called with this_rq unlocked.
1675 static int load_balance(int this_cpu, runqueue_t *this_rq,
1676 struct sched_domain *sd, enum idle_type idle)
1678 struct sched_group *group;
1679 runqueue_t *busiest;
1680 unsigned long imbalance;
1683 spin_lock(&this_rq->lock);
1685 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1689 busiest = find_busiest_queue(group);
1693 * This should be "impossible", but since load
1694 * balancing is inherently racy and statistical,
1695 * it could happen in theory.
1697 if (unlikely(busiest == this_rq)) {
1703 if (busiest->nr_running > 1) {
1705 * Attempt to move tasks. If find_busiest_group has found
1706 * an imbalance but busiest->nr_running <= 1, the group is
1707 * still unbalanced. nr_moved simply stays zero, so it is
1708 * correctly treated as an imbalance.
1710 double_lock_balance(this_rq, busiest);
1711 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1712 imbalance, sd, idle);
1713 spin_unlock(&busiest->lock);
1715 spin_unlock(&this_rq->lock);
1718 sd->nr_balance_failed++;
1720 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1723 spin_lock(&busiest->lock);
1724 if (!busiest->active_balance) {
1725 busiest->active_balance = 1;
1726 busiest->push_cpu = this_cpu;
1729 spin_unlock(&busiest->lock);
1731 wake_up_process(busiest->migration_thread);
1734 * We've kicked active balancing, reset the failure
1737 sd->nr_balance_failed = sd->cache_nice_tries;
1740 sd->nr_balance_failed = 0;
1742 /* We were unbalanced, so reset the balancing interval */
1743 sd->balance_interval = sd->min_interval;
1748 spin_unlock(&this_rq->lock);
1750 /* tune up the balancing interval */
1751 if (sd->balance_interval < sd->max_interval)
1752 sd->balance_interval *= 2;
1758 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1759 * tasks if there is an imbalance.
1761 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
1762 * this_rq is locked.
1764 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
1765 struct sched_domain *sd)
1767 struct sched_group *group;
1768 runqueue_t *busiest = NULL;
1769 unsigned long imbalance;
1772 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
1776 busiest = find_busiest_queue(group);
1777 if (!busiest || busiest == this_rq)
1780 /* Attempt to move tasks */
1781 double_lock_balance(this_rq, busiest);
1783 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1784 imbalance, sd, NEWLY_IDLE);
1786 spin_unlock(&busiest->lock);
1793 * idle_balance is called by schedule() if this_cpu is about to become
1794 * idle. Attempts to pull tasks from other CPUs.
1796 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1798 struct sched_domain *sd;
1800 for_each_domain(this_cpu, sd) {
1801 if (sd->flags & SD_BALANCE_NEWIDLE) {
1802 if (load_balance_newidle(this_cpu, this_rq, sd)) {
1803 /* We've pulled tasks over so stop searching */
1811 * active_load_balance is run by migration threads. It pushes a running
1812 * task off the cpu. It can be required to correctly have at least 1 task
1813 * running on each physical CPU where possible, and not have a physical /
1814 * logical imbalance.
1816 * Called with busiest locked.
1818 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
1820 struct sched_domain *sd;
1821 struct sched_group *group, *busy_group;
1824 if (busiest->nr_running <= 1)
1827 for_each_domain(busiest_cpu, sd)
1828 if (cpu_isset(busiest->push_cpu, sd->span))
1836 while (!cpu_isset(busiest_cpu, group->cpumask))
1837 group = group->next;
1846 if (group == busy_group)
1849 cpus_and(tmp, group->cpumask, cpu_online_map);
1850 if (!cpus_weight(tmp))
1853 for_each_cpu_mask(i, tmp) {
1859 rq = cpu_rq(push_cpu);
1862 * This condition is "impossible", but since load
1863 * balancing is inherently a bit racy and statistical,
1864 * it can trigger.. Reported by Bjorn Helgaas on a
1867 if (unlikely(busiest == rq))
1869 double_lock_balance(busiest, rq);
1870 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
1871 spin_unlock(&rq->lock);
1873 group = group->next;
1874 } while (group != sd->groups);
1878 * rebalance_tick will get called every timer tick, on every CPU.
1880 * It checks each scheduling domain to see if it is due to be balanced,
1881 * and initiates a balancing operation if so.
1883 * Balancing parameters are set up in arch_init_sched_domains.
1886 /* Don't have all balancing operations going off at once */
1887 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
1889 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
1890 enum idle_type idle)
1892 unsigned long old_load, this_load;
1893 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
1894 struct sched_domain *sd;
1896 /* Update our load */
1897 old_load = this_rq->cpu_load;
1898 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
1900 * Round up the averaging division if load is increasing. This
1901 * prevents us from getting stuck on 9 if the load is 10, for
1904 if (this_load > old_load)
1906 this_rq->cpu_load = (old_load + this_load) / 2;
1908 for_each_domain(this_cpu, sd) {
1909 unsigned long interval = sd->balance_interval;
1912 interval *= sd->busy_factor;
1914 /* scale ms to jiffies */
1915 interval = msecs_to_jiffies(interval);
1916 if (unlikely(!interval))
1919 if (j - sd->last_balance >= interval) {
1920 if (load_balance(this_cpu, this_rq, sd, idle)) {
1921 /* We've pulled tasks over so no longer idle */
1924 sd->last_balance += interval;
1930 * on UP we do not need to balance between CPUs:
1932 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
1935 static inline void idle_balance(int cpu, runqueue_t *rq)
1940 static inline int wake_priority_sleeper(runqueue_t *rq)
1942 #ifdef CONFIG_SCHED_SMT
1944 * If an SMT sibling task has been put to sleep for priority
1945 * reasons reschedule the idle task to see if it can now run.
1947 if (rq->nr_running) {
1948 resched_task(rq->idle);
1955 DEFINE_PER_CPU(struct kernel_stat, kstat);
1957 EXPORT_PER_CPU_SYMBOL(kstat);
1960 * We place interactive tasks back into the active array, if possible.
1962 * To guarantee that this does not starve expired tasks we ignore the
1963 * interactivity of a task if the first expired task had to wait more
1964 * than a 'reasonable' amount of time. This deadline timeout is
1965 * load-dependent, as the frequency of array switched decreases with
1966 * increasing number of running tasks. We also ignore the interactivity
1967 * if a better static_prio task has expired:
1969 #define EXPIRED_STARVING(rq) \
1970 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
1971 (jiffies - (rq)->expired_timestamp >= \
1972 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
1973 ((rq)->curr->static_prio > (rq)->best_expired_prio))
1976 * This function gets called by the timer code, with HZ frequency.
1977 * We call it with interrupts disabled.
1979 * It also gets called by the fork code, when changing the parent's
1982 void scheduler_tick(int user_ticks, int sys_ticks)
1984 int cpu = smp_processor_id();
1985 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
1986 runqueue_t *rq = this_rq();
1987 task_t *p = current;
1989 rq->timestamp_last_tick = sched_clock();
1991 if (rcu_pending(cpu))
1992 rcu_check_callbacks(cpu, user_ticks);
1994 /* note: this timer irq context must be accounted for as well */
1995 if (hardirq_count() - HARDIRQ_OFFSET) {
1996 cpustat->irq += sys_ticks;
1998 } else if (softirq_count()) {
1999 cpustat->softirq += sys_ticks;
2003 if (p == rq->idle) {
2004 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2007 if (atomic_read(&rq->nr_iowait) > 0)
2008 cpustat->iowait += sys_ticks;
2010 cpustat->idle += sys_ticks;
2011 if (wake_priority_sleeper(rq))
2013 rebalance_tick(cpu, rq, IDLE);
2016 if (TASK_NICE(p) > 0)
2017 cpustat->nice += user_ticks;
2019 cpustat->user += user_ticks;
2020 cpustat->system += sys_ticks;
2022 /* Task might have expired already, but not scheduled off yet */
2023 if (p->array != rq->active) {
2024 set_tsk_need_resched(p);
2027 spin_lock(&rq->lock);
2029 * The task was running during this tick - update the
2030 * time slice counter. Note: we do not update a thread's
2031 * priority until it either goes to sleep or uses up its
2032 * timeslice. This makes it possible for interactive tasks
2033 * to use up their timeslices at their highest priority levels.
2035 if (unlikely(rt_task(p))) {
2037 * RR tasks need a special form of timeslice management.
2038 * FIFO tasks have no timeslices.
2040 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2041 p->time_slice = task_timeslice(p);
2042 p->first_time_slice = 0;
2043 set_tsk_need_resched(p);
2045 /* put it at the end of the queue: */
2046 dequeue_task(p, rq->active);
2047 enqueue_task(p, rq->active);
2051 if (vx_need_resched(p)) {
2052 dequeue_task(p, rq->active);
2053 set_tsk_need_resched(p);
2054 p->prio = effective_prio(p);
2055 p->time_slice = task_timeslice(p);
2056 p->first_time_slice = 0;
2058 if (!rq->expired_timestamp)
2059 rq->expired_timestamp = jiffies;
2060 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2061 enqueue_task(p, rq->expired);
2062 if (p->static_prio < rq->best_expired_prio)
2063 rq->best_expired_prio = p->static_prio;
2065 enqueue_task(p, rq->active);
2068 * Prevent a too long timeslice allowing a task to monopolize
2069 * the CPU. We do this by splitting up the timeslice into
2072 * Note: this does not mean the task's timeslices expire or
2073 * get lost in any way, they just might be preempted by
2074 * another task of equal priority. (one with higher
2075 * priority would have preempted this task already.) We
2076 * requeue this task to the end of the list on this priority
2077 * level, which is in essence a round-robin of tasks with
2080 * This only applies to tasks in the interactive
2081 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2083 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2084 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2085 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2086 (p->array == rq->active)) {
2088 dequeue_task(p, rq->active);
2089 set_tsk_need_resched(p);
2090 p->prio = effective_prio(p);
2091 enqueue_task(p, rq->active);
2095 spin_unlock(&rq->lock);
2097 rebalance_tick(cpu, rq, NOT_IDLE);
2100 #ifdef CONFIG_SCHED_SMT
2101 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2104 struct sched_domain *sd = rq->sd;
2105 cpumask_t sibling_map;
2107 if (!(sd->flags & SD_SHARE_CPUPOWER))
2110 cpus_and(sibling_map, sd->span, cpu_online_map);
2111 for_each_cpu_mask(i, sibling_map) {
2120 * If an SMT sibling task is sleeping due to priority
2121 * reasons wake it up now.
2123 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2124 resched_task(smt_rq->idle);
2128 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2130 struct sched_domain *sd = rq->sd;
2131 cpumask_t sibling_map;
2134 if (!(sd->flags & SD_SHARE_CPUPOWER))
2137 cpus_and(sibling_map, sd->span, cpu_online_map);
2138 for_each_cpu_mask(i, sibling_map) {
2146 smt_curr = smt_rq->curr;
2149 * If a user task with lower static priority than the
2150 * running task on the SMT sibling is trying to schedule,
2151 * delay it till there is proportionately less timeslice
2152 * left of the sibling task to prevent a lower priority
2153 * task from using an unfair proportion of the
2154 * physical cpu's resources. -ck
2156 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2157 task_timeslice(p) || rt_task(smt_curr)) &&
2158 p->mm && smt_curr->mm && !rt_task(p))
2162 * Reschedule a lower priority task on the SMT sibling,
2163 * or wake it up if it has been put to sleep for priority
2166 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2167 task_timeslice(smt_curr) || rt_task(p)) &&
2168 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2169 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2170 resched_task(smt_curr);
2175 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2179 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2186 * schedule() is the main scheduler function.
2188 asmlinkage void __sched schedule(void)
2191 task_t *prev, *next;
2193 prio_array_t *array;
2194 struct list_head *queue;
2195 unsigned long long now;
2196 unsigned long run_time;
2198 #ifdef CONFIG_VSERVER_HARDCPU
2199 struct vx_info *vxi;
2204 * Test if we are atomic. Since do_exit() needs to call into
2205 * schedule() atomically, we ignore that path for now.
2206 * Otherwise, whine if we are scheduling when we should not be.
2208 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2209 if (unlikely(in_atomic())) {
2210 printk(KERN_ERR "bad: scheduling while atomic!\n");
2220 release_kernel_lock(prev);
2221 now = sched_clock();
2222 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2223 run_time = now - prev->timestamp;
2225 run_time = NS_MAX_SLEEP_AVG;
2228 * Tasks with interactive credits get charged less run_time
2229 * at high sleep_avg to delay them losing their interactive
2232 if (HIGH_CREDIT(prev))
2233 run_time /= (CURRENT_BONUS(prev) ? : 1);
2235 spin_lock_irq(&rq->lock);
2238 * if entering off of a kernel preemption go straight
2239 * to picking the next task.
2241 switch_count = &prev->nivcsw;
2242 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2243 switch_count = &prev->nvcsw;
2244 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2245 unlikely(signal_pending(prev))))
2246 prev->state = TASK_RUNNING;
2248 deactivate_task(prev, rq);
2251 cpu = smp_processor_id();
2252 #ifdef CONFIG_VSERVER_HARDCPU
2253 if (!list_empty(&rq->hold_queue)) {
2254 struct list_head *l, *n;
2258 list_for_each_safe(l, n, &rq->hold_queue) {
2259 next = list_entry(l, task_t, run_list);
2260 if (vxi == next->vx_info)
2263 vxi = next->vx_info;
2264 ret = vx_tokens_recalc(vxi);
2265 // tokens = vx_tokens_avail(next);
2268 list_del(&next->run_list);
2269 next->state &= ~TASK_ONHOLD;
2270 recalc_task_prio(next, now);
2271 __activate_task(next, rq);
2272 // printk("··· unhold %p\n", next);
2275 if ((ret < 0) && (maxidle < ret))
2279 rq->idle_tokens = -maxidle;
2283 if (unlikely(!rq->nr_running)) {
2284 idle_balance(cpu, rq);
2285 if (!rq->nr_running) {
2287 rq->expired_timestamp = 0;
2288 wake_sleeping_dependent(cpu, rq);
2294 if (unlikely(!array->nr_active)) {
2296 * Switch the active and expired arrays.
2298 rq->active = rq->expired;
2299 rq->expired = array;
2301 rq->expired_timestamp = 0;
2302 rq->best_expired_prio = MAX_PRIO;
2305 idx = sched_find_first_bit(array->bitmap);
2306 queue = array->queue + idx;
2307 next = list_entry(queue->next, task_t, run_list);
2309 if (dependent_sleeper(cpu, rq, next)) {
2314 #ifdef CONFIG_VSERVER_HARDCPU
2315 vxi = next->vx_info;
2316 if (vxi && __vx_flags(vxi->vx_flags,
2317 VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2318 int ret = vx_tokens_recalc(vxi);
2320 if (unlikely(ret <= 0)) {
2321 if (ret && (rq->idle_tokens > -ret))
2322 rq->idle_tokens = -ret;
2323 deactivate_task(next, rq);
2324 list_add_tail(&next->run_list, &rq->hold_queue);
2325 next->state |= TASK_ONHOLD;
2331 if (!rt_task(next) && next->activated > 0) {
2332 unsigned long long delta = now - next->timestamp;
2334 if (next->activated == 1)
2335 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2337 array = next->array;
2338 dequeue_task(next, array);
2339 recalc_task_prio(next, next->timestamp + delta);
2340 enqueue_task(next, array);
2342 next->activated = 0;
2345 clear_tsk_need_resched(prev);
2346 RCU_qsctr(task_cpu(prev))++;
2348 prev->sleep_avg -= run_time;
2349 if ((long)prev->sleep_avg <= 0) {
2350 prev->sleep_avg = 0;
2351 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2352 prev->interactive_credit--;
2354 prev->timestamp = now;
2356 if (likely(prev != next)) {
2357 next->timestamp = now;
2362 prepare_arch_switch(rq, next);
2363 prev = context_switch(rq, prev, next);
2366 finish_task_switch(prev);
2368 spin_unlock_irq(&rq->lock);
2370 reacquire_kernel_lock(current);
2371 preempt_enable_no_resched();
2372 if (test_thread_flag(TIF_NEED_RESCHED))
2376 EXPORT_SYMBOL(schedule);
2378 #ifdef CONFIG_PREEMPT
2380 * this is is the entry point to schedule() from in-kernel preemption
2381 * off of preempt_enable. Kernel preemptions off return from interrupt
2382 * occur there and call schedule directly.
2384 asmlinkage void __sched preempt_schedule(void)
2386 struct thread_info *ti = current_thread_info();
2389 * If there is a non-zero preempt_count or interrupts are disabled,
2390 * we do not want to preempt the current task. Just return..
2392 if (unlikely(ti->preempt_count || irqs_disabled()))
2396 ti->preempt_count = PREEMPT_ACTIVE;
2398 ti->preempt_count = 0;
2400 /* we could miss a preemption opportunity between schedule and now */
2402 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2406 EXPORT_SYMBOL(preempt_schedule);
2407 #endif /* CONFIG_PREEMPT */
2409 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2411 task_t *p = curr->task;
2412 return try_to_wake_up(p, mode, sync);
2415 EXPORT_SYMBOL(default_wake_function);
2418 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2419 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2420 * number) then we wake all the non-exclusive tasks and one exclusive task.
2422 * There are circumstances in which we can try to wake a task which has already
2423 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2424 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2426 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2427 int nr_exclusive, int sync, void *key)
2429 struct list_head *tmp, *next;
2431 list_for_each_safe(tmp, next, &q->task_list) {
2434 curr = list_entry(tmp, wait_queue_t, task_list);
2435 flags = curr->flags;
2436 if (curr->func(curr, mode, sync, key) &&
2437 (flags & WQ_FLAG_EXCLUSIVE) &&
2444 * __wake_up - wake up threads blocked on a waitqueue.
2446 * @mode: which threads
2447 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2449 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2450 int nr_exclusive, void *key)
2452 unsigned long flags;
2454 spin_lock_irqsave(&q->lock, flags);
2455 __wake_up_common(q, mode, nr_exclusive, 0, key);
2456 spin_unlock_irqrestore(&q->lock, flags);
2459 EXPORT_SYMBOL(__wake_up);
2462 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2464 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2466 __wake_up_common(q, mode, 1, 0, NULL);
2470 * __wake_up - sync- wake up threads blocked on a waitqueue.
2472 * @mode: which threads
2473 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2475 * The sync wakeup differs that the waker knows that it will schedule
2476 * away soon, so while the target thread will be woken up, it will not
2477 * be migrated to another CPU - ie. the two threads are 'synchronized'
2478 * with each other. This can prevent needless bouncing between CPUs.
2480 * On UP it can prevent extra preemption.
2482 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2484 unsigned long flags;
2490 if (unlikely(!nr_exclusive))
2493 spin_lock_irqsave(&q->lock, flags);
2494 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2495 spin_unlock_irqrestore(&q->lock, flags);
2497 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2499 void fastcall complete(struct completion *x)
2501 unsigned long flags;
2503 spin_lock_irqsave(&x->wait.lock, flags);
2505 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2507 spin_unlock_irqrestore(&x->wait.lock, flags);
2509 EXPORT_SYMBOL(complete);
2511 void fastcall complete_all(struct completion *x)
2513 unsigned long flags;
2515 spin_lock_irqsave(&x->wait.lock, flags);
2516 x->done += UINT_MAX/2;
2517 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2519 spin_unlock_irqrestore(&x->wait.lock, flags);
2521 EXPORT_SYMBOL(complete_all);
2523 void fastcall __sched wait_for_completion(struct completion *x)
2526 spin_lock_irq(&x->wait.lock);
2528 DECLARE_WAITQUEUE(wait, current);
2530 wait.flags |= WQ_FLAG_EXCLUSIVE;
2531 __add_wait_queue_tail(&x->wait, &wait);
2533 __set_current_state(TASK_UNINTERRUPTIBLE);
2534 spin_unlock_irq(&x->wait.lock);
2536 spin_lock_irq(&x->wait.lock);
2538 __remove_wait_queue(&x->wait, &wait);
2541 spin_unlock_irq(&x->wait.lock);
2543 EXPORT_SYMBOL(wait_for_completion);
2545 #define SLEEP_ON_VAR \
2546 unsigned long flags; \
2547 wait_queue_t wait; \
2548 init_waitqueue_entry(&wait, current);
2550 #define SLEEP_ON_HEAD \
2551 spin_lock_irqsave(&q->lock,flags); \
2552 __add_wait_queue(q, &wait); \
2553 spin_unlock(&q->lock);
2555 #define SLEEP_ON_TAIL \
2556 spin_lock_irq(&q->lock); \
2557 __remove_wait_queue(q, &wait); \
2558 spin_unlock_irqrestore(&q->lock, flags);
2560 #define SLEEP_ON_BKLCHECK \
2561 if (unlikely(!kernel_locked()) && \
2562 sleep_on_bkl_warnings < 10) { \
2563 sleep_on_bkl_warnings++; \
2567 static int sleep_on_bkl_warnings;
2569 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2575 current->state = TASK_INTERRUPTIBLE;
2582 EXPORT_SYMBOL(interruptible_sleep_on);
2584 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2590 current->state = TASK_INTERRUPTIBLE;
2593 timeout = schedule_timeout(timeout);
2599 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2601 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2607 current->state = TASK_UNINTERRUPTIBLE;
2610 timeout = schedule_timeout(timeout);
2616 EXPORT_SYMBOL(sleep_on_timeout);
2618 void set_user_nice(task_t *p, long nice)
2620 unsigned long flags;
2621 prio_array_t *array;
2623 int old_prio, new_prio, delta;
2625 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2628 * We have to be careful, if called from sys_setpriority(),
2629 * the task might be in the middle of scheduling on another CPU.
2631 rq = task_rq_lock(p, &flags);
2633 * The RT priorities are set via setscheduler(), but we still
2634 * allow the 'normal' nice value to be set - but as expected
2635 * it wont have any effect on scheduling until the task is
2639 p->static_prio = NICE_TO_PRIO(nice);
2644 dequeue_task(p, array);
2647 new_prio = NICE_TO_PRIO(nice);
2648 delta = new_prio - old_prio;
2649 p->static_prio = NICE_TO_PRIO(nice);
2653 enqueue_task(p, array);
2655 * If the task increased its priority or is running and
2656 * lowered its priority, then reschedule its CPU:
2658 if (delta < 0 || (delta > 0 && task_running(rq, p)))
2659 resched_task(rq->curr);
2662 task_rq_unlock(rq, &flags);
2665 EXPORT_SYMBOL(set_user_nice);
2667 #ifdef __ARCH_WANT_SYS_NICE
2670 * sys_nice - change the priority of the current process.
2671 * @increment: priority increment
2673 * sys_setpriority is a more generic, but much slower function that
2674 * does similar things.
2676 asmlinkage long sys_nice(int increment)
2682 * Setpriority might change our priority at the same moment.
2683 * We don't have to worry. Conceptually one call occurs first
2684 * and we have a single winner.
2686 if (increment < 0) {
2687 if (!capable(CAP_SYS_NICE))
2689 if (increment < -40)
2695 nice = PRIO_TO_NICE(current->static_prio) + increment;
2701 retval = security_task_setnice(current, nice);
2705 set_user_nice(current, nice);
2712 * task_prio - return the priority value of a given task.
2713 * @p: the task in question.
2715 * This is the priority value as seen by users in /proc.
2716 * RT tasks are offset by -200. Normal tasks are centered
2717 * around 0, value goes from -16 to +15.
2719 int task_prio(task_t *p)
2721 return p->prio - MAX_RT_PRIO;
2725 * task_nice - return the nice value of a given task.
2726 * @p: the task in question.
2728 int task_nice(task_t *p)
2730 return TASK_NICE(p);
2733 EXPORT_SYMBOL(task_nice);
2736 * idle_cpu - is a given cpu idle currently?
2737 * @cpu: the processor in question.
2739 int idle_cpu(int cpu)
2741 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
2744 EXPORT_SYMBOL_GPL(idle_cpu);
2747 * find_process_by_pid - find a process with a matching PID value.
2748 * @pid: the pid in question.
2750 static inline task_t *find_process_by_pid(pid_t pid)
2752 return pid ? find_task_by_pid(pid) : current;
2755 /* Actually do priority change: must hold rq lock. */
2756 static void __setscheduler(struct task_struct *p, int policy, int prio)
2760 p->rt_priority = prio;
2761 if (policy != SCHED_NORMAL)
2762 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
2764 p->prio = p->static_prio;
2768 * setscheduler - change the scheduling policy and/or RT priority of a thread.
2770 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
2772 struct sched_param lp;
2773 int retval = -EINVAL;
2775 prio_array_t *array;
2776 unsigned long flags;
2780 if (!param || pid < 0)
2784 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
2788 * We play safe to avoid deadlocks.
2790 read_lock_irq(&tasklist_lock);
2792 p = find_process_by_pid(pid);
2796 goto out_unlock_tasklist;
2799 * To be able to change p->policy safely, the apropriate
2800 * runqueue lock must be held.
2802 rq = task_rq_lock(p, &flags);
2808 if (policy != SCHED_FIFO && policy != SCHED_RR &&
2809 policy != SCHED_NORMAL)
2814 * Valid priorities for SCHED_FIFO and SCHED_RR are
2815 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
2818 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
2820 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
2824 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
2825 !capable(CAP_SYS_NICE))
2827 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2828 !capable(CAP_SYS_NICE))
2831 retval = security_task_setscheduler(p, policy, &lp);
2837 deactivate_task(p, task_rq(p));
2840 __setscheduler(p, policy, lp.sched_priority);
2842 __activate_task(p, task_rq(p));
2844 * Reschedule if we are currently running on this runqueue and
2845 * our priority decreased, or if we are not currently running on
2846 * this runqueue and our priority is higher than the current's
2848 if (task_running(rq, p)) {
2849 if (p->prio > oldprio)
2850 resched_task(rq->curr);
2851 } else if (TASK_PREEMPTS_CURR(p, rq))
2852 resched_task(rq->curr);
2856 task_rq_unlock(rq, &flags);
2857 out_unlock_tasklist:
2858 read_unlock_irq(&tasklist_lock);
2865 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
2866 * @pid: the pid in question.
2867 * @policy: new policy
2868 * @param: structure containing the new RT priority.
2870 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
2871 struct sched_param __user *param)
2873 return setscheduler(pid, policy, param);
2877 * sys_sched_setparam - set/change the RT priority of a thread
2878 * @pid: the pid in question.
2879 * @param: structure containing the new RT priority.
2881 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
2883 return setscheduler(pid, -1, param);
2887 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
2888 * @pid: the pid in question.
2890 asmlinkage long sys_sched_getscheduler(pid_t pid)
2892 int retval = -EINVAL;
2899 read_lock(&tasklist_lock);
2900 p = find_process_by_pid(pid);
2902 retval = security_task_getscheduler(p);
2906 read_unlock(&tasklist_lock);
2913 * sys_sched_getscheduler - get the RT priority of a thread
2914 * @pid: the pid in question.
2915 * @param: structure containing the RT priority.
2917 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
2919 struct sched_param lp;
2920 int retval = -EINVAL;
2923 if (!param || pid < 0)
2926 read_lock(&tasklist_lock);
2927 p = find_process_by_pid(pid);
2932 retval = security_task_getscheduler(p);
2936 lp.sched_priority = p->rt_priority;
2937 read_unlock(&tasklist_lock);
2940 * This one might sleep, we cannot do it with a spinlock held ...
2942 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
2948 read_unlock(&tasklist_lock);
2953 * sys_sched_setaffinity - set the cpu affinity of a process
2954 * @pid: pid of the process
2955 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2956 * @user_mask_ptr: user-space pointer to the new cpu mask
2958 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
2959 unsigned long __user *user_mask_ptr)
2965 if (len < sizeof(new_mask))
2968 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
2972 read_lock(&tasklist_lock);
2974 p = find_process_by_pid(pid);
2976 read_unlock(&tasklist_lock);
2977 unlock_cpu_hotplug();
2982 * It is not safe to call set_cpus_allowed with the
2983 * tasklist_lock held. We will bump the task_struct's
2984 * usage count and then drop tasklist_lock.
2987 read_unlock(&tasklist_lock);
2990 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2991 !capable(CAP_SYS_NICE))
2994 retval = set_cpus_allowed(p, new_mask);
2998 unlock_cpu_hotplug();
3003 * sys_sched_getaffinity - get the cpu affinity of a process
3004 * @pid: pid of the process
3005 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3006 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3008 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3009 unsigned long __user *user_mask_ptr)
3011 unsigned int real_len;
3016 real_len = sizeof(mask);
3021 read_lock(&tasklist_lock);
3024 p = find_process_by_pid(pid);
3029 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
3032 read_unlock(&tasklist_lock);
3033 unlock_cpu_hotplug();
3036 if (copy_to_user(user_mask_ptr, &mask, real_len))
3042 * sys_sched_yield - yield the current processor to other threads.
3044 * this function yields the current CPU by moving the calling thread
3045 * to the expired array. If there are no other threads running on this
3046 * CPU then this function will return.
3048 asmlinkage long sys_sched_yield(void)
3050 runqueue_t *rq = this_rq_lock();
3051 prio_array_t *array = current->array;
3052 prio_array_t *target = rq->expired;
3055 * We implement yielding by moving the task into the expired
3058 * (special rule: RT tasks will just roundrobin in the active
3061 if (unlikely(rt_task(current)))
3062 target = rq->active;
3064 dequeue_task(current, array);
3065 enqueue_task(current, target);
3068 * Since we are going to call schedule() anyway, there's
3069 * no need to preempt or enable interrupts:
3071 _raw_spin_unlock(&rq->lock);
3072 preempt_enable_no_resched();
3079 void __sched __cond_resched(void)
3081 set_current_state(TASK_RUNNING);
3085 EXPORT_SYMBOL(__cond_resched);
3088 * yield - yield the current processor to other threads.
3090 * this is a shortcut for kernel-space yielding - it marks the
3091 * thread runnable and calls sys_sched_yield().
3093 void __sched yield(void)
3095 set_current_state(TASK_RUNNING);
3099 EXPORT_SYMBOL(yield);
3102 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3103 * that process accounting knows that this is a task in IO wait state.
3105 * But don't do that if it is a deliberate, throttling IO wait (this task
3106 * has set its backing_dev_info: the queue against which it should throttle)
3108 void __sched io_schedule(void)
3110 struct runqueue *rq = this_rq();
3112 atomic_inc(&rq->nr_iowait);
3114 atomic_dec(&rq->nr_iowait);
3117 EXPORT_SYMBOL(io_schedule);
3119 long __sched io_schedule_timeout(long timeout)
3121 struct runqueue *rq = this_rq();
3124 atomic_inc(&rq->nr_iowait);
3125 ret = schedule_timeout(timeout);
3126 atomic_dec(&rq->nr_iowait);
3131 * sys_sched_get_priority_max - return maximum RT priority.
3132 * @policy: scheduling class.
3134 * this syscall returns the maximum rt_priority that can be used
3135 * by a given scheduling class.
3137 asmlinkage long sys_sched_get_priority_max(int policy)
3144 ret = MAX_USER_RT_PRIO-1;
3154 * sys_sched_get_priority_min - return minimum RT priority.
3155 * @policy: scheduling class.
3157 * this syscall returns the minimum rt_priority that can be used
3158 * by a given scheduling class.
3160 asmlinkage long sys_sched_get_priority_min(int policy)
3176 * sys_sched_rr_get_interval - return the default timeslice of a process.
3177 * @pid: pid of the process.
3178 * @interval: userspace pointer to the timeslice value.
3180 * this syscall writes the default timeslice value of a given process
3181 * into the user-space timespec buffer. A value of '0' means infinity.
3184 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3186 int retval = -EINVAL;
3194 read_lock(&tasklist_lock);
3195 p = find_process_by_pid(pid);
3199 retval = security_task_getscheduler(p);
3203 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3204 0 : task_timeslice(p), &t);
3205 read_unlock(&tasklist_lock);
3206 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3210 read_unlock(&tasklist_lock);
3214 static inline struct task_struct *eldest_child(struct task_struct *p)
3216 if (list_empty(&p->children)) return NULL;
3217 return list_entry(p->children.next,struct task_struct,sibling);
3220 static inline struct task_struct *older_sibling(struct task_struct *p)
3222 if (p->sibling.prev==&p->parent->children) return NULL;
3223 return list_entry(p->sibling.prev,struct task_struct,sibling);
3226 static inline struct task_struct *younger_sibling(struct task_struct *p)
3228 if (p->sibling.next==&p->parent->children) return NULL;
3229 return list_entry(p->sibling.next,struct task_struct,sibling);
3232 static void show_task(task_t * p)
3236 unsigned long free = 0;
3237 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3239 printk("%-13.13s ", p->comm);
3240 state = p->state ? __ffs(p->state) + 1 : 0;
3241 if (state < ARRAY_SIZE(stat_nam))
3242 printk(stat_nam[state]);
3245 #if (BITS_PER_LONG == 32)
3246 if (state == TASK_RUNNING)
3247 printk(" running ");
3249 printk(" %08lX ", thread_saved_pc(p));
3251 if (state == TASK_RUNNING)
3252 printk(" running task ");
3254 printk(" %016lx ", thread_saved_pc(p));
3256 #ifdef CONFIG_DEBUG_STACK_USAGE
3258 unsigned long * n = (unsigned long *) (p->thread_info+1);
3261 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3264 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3265 if ((relative = eldest_child(p)))
3266 printk("%5d ", relative->pid);
3269 if ((relative = younger_sibling(p)))
3270 printk("%7d", relative->pid);
3273 if ((relative = older_sibling(p)))
3274 printk(" %5d", relative->pid);
3278 printk(" (L-TLB)\n");
3280 printk(" (NOTLB)\n");
3282 if (state != TASK_RUNNING)
3283 show_stack(p, NULL);
3286 void show_state(void)
3290 #if (BITS_PER_LONG == 32)
3293 printk(" task PC pid father child younger older\n");
3297 printk(" task PC pid father child younger older\n");
3299 read_lock(&tasklist_lock);
3300 do_each_thread(g, p) {
3302 * reset the NMI-timeout, listing all files on a slow
3303 * console might take alot of time:
3305 touch_nmi_watchdog();
3307 } while_each_thread(g, p);
3309 read_unlock(&tasklist_lock);
3312 void __devinit init_idle(task_t *idle, int cpu)
3314 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3315 unsigned long flags;
3317 local_irq_save(flags);
3318 double_rq_lock(idle_rq, rq);
3320 idle_rq->curr = idle_rq->idle = idle;
3321 deactivate_task(idle, rq);
3323 idle->prio = MAX_PRIO;
3324 idle->state = TASK_RUNNING;
3325 set_task_cpu(idle, cpu);
3326 double_rq_unlock(idle_rq, rq);
3327 set_tsk_need_resched(idle);
3328 local_irq_restore(flags);
3330 /* Set the preempt count _outside_ the spinlocks! */
3331 #ifdef CONFIG_PREEMPT
3332 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3334 idle->thread_info->preempt_count = 0;
3339 * In a system that switches off the HZ timer nohz_cpu_mask
3340 * indicates which cpus entered this state. This is used
3341 * in the rcu update to wait only for active cpus. For system
3342 * which do not switch off the HZ timer nohz_cpu_mask should
3343 * always be CPU_MASK_NONE.
3345 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3349 * This is how migration works:
3351 * 1) we queue a migration_req_t structure in the source CPU's
3352 * runqueue and wake up that CPU's migration thread.
3353 * 2) we down() the locked semaphore => thread blocks.
3354 * 3) migration thread wakes up (implicitly it forces the migrated
3355 * thread off the CPU)
3356 * 4) it gets the migration request and checks whether the migrated
3357 * task is still in the wrong runqueue.
3358 * 5) if it's in the wrong runqueue then the migration thread removes
3359 * it and puts it into the right queue.
3360 * 6) migration thread up()s the semaphore.
3361 * 7) we wake up and the migration is done.
3365 * Change a given task's CPU affinity. Migrate the thread to a
3366 * proper CPU and schedule it away if the CPU it's executing on
3367 * is removed from the allowed bitmask.
3369 * NOTE: the caller must have a valid reference to the task, the
3370 * task must not exit() & deallocate itself prematurely. The
3371 * call is not atomic; no spinlocks may be held.
3373 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3375 unsigned long flags;
3377 migration_req_t req;
3380 rq = task_rq_lock(p, &flags);
3381 if (any_online_cpu(new_mask) == NR_CPUS) {
3386 p->cpus_allowed = new_mask;
3387 /* Can the task run on the task's current CPU? If so, we're done */
3388 if (cpu_isset(task_cpu(p), new_mask))
3391 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3392 /* Need help from migration thread: drop lock and wait. */
3393 task_rq_unlock(rq, &flags);
3394 wake_up_process(rq->migration_thread);
3395 wait_for_completion(&req.done);
3399 task_rq_unlock(rq, &flags);
3403 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3406 * Move (not current) task off this cpu, onto dest cpu. We're doing
3407 * this because either it can't run here any more (set_cpus_allowed()
3408 * away from this CPU, or CPU going down), or because we're
3409 * attempting to rebalance this task on exec (sched_balance_exec).
3411 * So we race with normal scheduler movements, but that's OK, as long
3412 * as the task is no longer on this CPU.
3414 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3416 runqueue_t *rq_dest, *rq_src;
3418 if (unlikely(cpu_is_offline(dest_cpu)))
3421 rq_src = cpu_rq(src_cpu);
3422 rq_dest = cpu_rq(dest_cpu);
3424 double_rq_lock(rq_src, rq_dest);
3425 /* Already moved. */
3426 if (task_cpu(p) != src_cpu)
3428 /* Affinity changed (again). */
3429 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3432 set_task_cpu(p, dest_cpu);
3435 * Sync timestamp with rq_dest's before activating.
3436 * The same thing could be achieved by doing this step
3437 * afterwards, and pretending it was a local activate.
3438 * This way is cleaner and logically correct.
3440 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3441 + rq_dest->timestamp_last_tick;
3442 deactivate_task(p, rq_src);
3443 activate_task(p, rq_dest, 0);
3444 if (TASK_PREEMPTS_CURR(p, rq_dest))
3445 resched_task(rq_dest->curr);
3449 double_rq_unlock(rq_src, rq_dest);
3453 * migration_thread - this is a highprio system thread that performs
3454 * thread migration by bumping thread off CPU then 'pushing' onto
3457 static int migration_thread(void * data)
3460 int cpu = (long)data;
3463 BUG_ON(rq->migration_thread != current);
3465 set_current_state(TASK_INTERRUPTIBLE);
3466 while (!kthread_should_stop()) {
3467 struct list_head *head;
3468 migration_req_t *req;
3470 if (current->flags & PF_FREEZE)
3471 refrigerator(PF_FREEZE);
3473 spin_lock_irq(&rq->lock);
3475 if (cpu_is_offline(cpu)) {
3476 spin_unlock_irq(&rq->lock);
3480 if (rq->active_balance) {
3481 active_load_balance(rq, cpu);
3482 rq->active_balance = 0;
3485 head = &rq->migration_queue;
3487 if (list_empty(head)) {
3488 spin_unlock_irq(&rq->lock);
3490 set_current_state(TASK_INTERRUPTIBLE);
3493 req = list_entry(head->next, migration_req_t, list);
3494 list_del_init(head->next);
3496 if (req->type == REQ_MOVE_TASK) {
3497 spin_unlock(&rq->lock);
3498 __migrate_task(req->task, smp_processor_id(),
3501 } else if (req->type == REQ_SET_DOMAIN) {
3503 spin_unlock_irq(&rq->lock);
3505 spin_unlock_irq(&rq->lock);
3509 complete(&req->done);
3511 __set_current_state(TASK_RUNNING);
3515 /* Wait for kthread_stop */
3516 set_current_state(TASK_INTERRUPTIBLE);
3517 while (!kthread_should_stop()) {
3519 set_current_state(TASK_INTERRUPTIBLE);
3521 __set_current_state(TASK_RUNNING);
3525 #ifdef CONFIG_HOTPLUG_CPU
3526 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
3527 static void migrate_all_tasks(int src_cpu)
3529 struct task_struct *tsk, *t;
3533 write_lock_irq(&tasklist_lock);
3535 /* watch out for per node tasks, let's stay on this node */
3536 node = cpu_to_node(src_cpu);
3538 do_each_thread(t, tsk) {
3543 if (task_cpu(tsk) != src_cpu)
3546 /* Figure out where this task should go (attempting to
3547 * keep it on-node), and check if it can be migrated
3548 * as-is. NOTE that kernel threads bound to more than
3549 * one online cpu will be migrated. */
3550 mask = node_to_cpumask(node);
3551 cpus_and(mask, mask, tsk->cpus_allowed);
3552 dest_cpu = any_online_cpu(mask);
3553 if (dest_cpu == NR_CPUS)
3554 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3555 if (dest_cpu == NR_CPUS) {
3556 cpus_clear(tsk->cpus_allowed);
3557 cpus_complement(tsk->cpus_allowed);
3558 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3560 /* Don't tell them about moving exiting tasks
3561 or kernel threads (both mm NULL), since
3562 they never leave kernel. */
3563 if (tsk->mm && printk_ratelimit())
3564 printk(KERN_INFO "process %d (%s) no "
3565 "longer affine to cpu%d\n",
3566 tsk->pid, tsk->comm, src_cpu);
3569 __migrate_task(tsk, src_cpu, dest_cpu);
3570 } while_each_thread(t, tsk);
3572 write_unlock_irq(&tasklist_lock);
3575 /* Schedules idle task to be the next runnable task on current CPU.
3576 * It does so by boosting its priority to highest possible and adding it to
3577 * the _front_ of runqueue. Used by CPU offline code.
3579 void sched_idle_next(void)
3581 int cpu = smp_processor_id();
3582 runqueue_t *rq = this_rq();
3583 struct task_struct *p = rq->idle;
3584 unsigned long flags;
3586 /* cpu has to be offline */
3587 BUG_ON(cpu_online(cpu));
3589 /* Strictly not necessary since rest of the CPUs are stopped by now
3590 * and interrupts disabled on current cpu.
3592 spin_lock_irqsave(&rq->lock, flags);
3594 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3595 /* Add idle task to _front_ of it's priority queue */
3596 __activate_idle_task(p, rq);
3598 spin_unlock_irqrestore(&rq->lock, flags);
3600 #endif /* CONFIG_HOTPLUG_CPU */
3603 * migration_call - callback that gets triggered when a CPU is added.
3604 * Here we can start up the necessary migration thread for the new CPU.
3606 static int migration_call(struct notifier_block *nfb, unsigned long action,
3609 int cpu = (long)hcpu;
3610 struct task_struct *p;
3611 struct runqueue *rq;
3612 unsigned long flags;
3615 case CPU_UP_PREPARE:
3616 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
3619 kthread_bind(p, cpu);
3620 /* Must be high prio: stop_machine expects to yield to it. */
3621 rq = task_rq_lock(p, &flags);
3622 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3623 task_rq_unlock(rq, &flags);
3624 cpu_rq(cpu)->migration_thread = p;
3627 /* Strictly unneccessary, as first user will wake it. */
3628 wake_up_process(cpu_rq(cpu)->migration_thread);
3630 #ifdef CONFIG_HOTPLUG_CPU
3631 case CPU_UP_CANCELED:
3632 /* Unbind it from offline cpu so it can run. Fall thru. */
3633 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
3634 kthread_stop(cpu_rq(cpu)->migration_thread);
3635 cpu_rq(cpu)->migration_thread = NULL;
3638 migrate_all_tasks(cpu);
3640 kthread_stop(rq->migration_thread);
3641 rq->migration_thread = NULL;
3642 /* Idle task back to normal (off runqueue, low prio) */
3643 rq = task_rq_lock(rq->idle, &flags);
3644 deactivate_task(rq->idle, rq);
3645 rq->idle->static_prio = MAX_PRIO;
3646 __setscheduler(rq->idle, SCHED_NORMAL, 0);
3647 task_rq_unlock(rq, &flags);
3648 BUG_ON(rq->nr_running != 0);
3650 /* No need to migrate the tasks: it was best-effort if
3651 * they didn't do lock_cpu_hotplug(). Just wake up
3652 * the requestors. */
3653 spin_lock_irq(&rq->lock);
3654 while (!list_empty(&rq->migration_queue)) {
3655 migration_req_t *req;
3656 req = list_entry(rq->migration_queue.next,
3657 migration_req_t, list);
3658 BUG_ON(req->type != REQ_MOVE_TASK);
3659 list_del_init(&req->list);
3660 complete(&req->done);
3662 spin_unlock_irq(&rq->lock);
3669 /* Register at highest priority so that task migration (migrate_all_tasks)
3670 * happens before everything else.
3672 static struct notifier_block __devinitdata migration_notifier = {
3673 .notifier_call = migration_call,
3677 int __init migration_init(void)
3679 void *cpu = (void *)(long)smp_processor_id();
3680 /* Start one for boot CPU. */
3681 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
3682 migration_call(&migration_notifier, CPU_ONLINE, cpu);
3683 register_cpu_notifier(&migration_notifier);
3689 * The 'big kernel lock'
3691 * This spinlock is taken and released recursively by lock_kernel()
3692 * and unlock_kernel(). It is transparently dropped and reaquired
3693 * over schedule(). It is used to protect legacy code that hasn't
3694 * been migrated to a proper locking design yet.
3696 * Don't use in new code.
3698 * Note: spinlock debugging needs this even on !CONFIG_SMP.
3700 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
3701 EXPORT_SYMBOL(kernel_flag);
3704 /* Attach the domain 'sd' to 'cpu' as its base domain */
3705 void cpu_attach_domain(struct sched_domain *sd, int cpu)
3707 migration_req_t req;
3708 unsigned long flags;
3709 runqueue_t *rq = cpu_rq(cpu);
3714 spin_lock_irqsave(&rq->lock, flags);
3716 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
3719 init_completion(&req.done);
3720 req.type = REQ_SET_DOMAIN;
3722 list_add(&req.list, &rq->migration_queue);
3726 spin_unlock_irqrestore(&rq->lock, flags);
3729 wake_up_process(rq->migration_thread);
3730 wait_for_completion(&req.done);
3733 unlock_cpu_hotplug();
3736 #ifdef ARCH_HAS_SCHED_DOMAIN
3737 extern void __init arch_init_sched_domains(void);
3739 static struct sched_group sched_group_cpus[NR_CPUS];
3740 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
3742 static struct sched_group sched_group_nodes[MAX_NUMNODES];
3743 static DEFINE_PER_CPU(struct sched_domain, node_domains);
3744 static void __init arch_init_sched_domains(void)
3747 struct sched_group *first_node = NULL, *last_node = NULL;
3749 /* Set up domains */
3751 int node = cpu_to_node(i);
3752 cpumask_t nodemask = node_to_cpumask(node);
3753 struct sched_domain *node_sd = &per_cpu(node_domains, i);
3754 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3756 *node_sd = SD_NODE_INIT;
3757 node_sd->span = cpu_possible_map;
3758 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
3760 *cpu_sd = SD_CPU_INIT;
3761 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
3762 cpu_sd->groups = &sched_group_cpus[i];
3763 cpu_sd->parent = node_sd;
3767 for (i = 0; i < MAX_NUMNODES; i++) {
3768 cpumask_t tmp = node_to_cpumask(i);
3770 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3771 struct sched_group *node = &sched_group_nodes[i];
3774 cpus_and(nodemask, tmp, cpu_possible_map);
3776 if (cpus_empty(nodemask))
3779 node->cpumask = nodemask;
3780 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
3782 for_each_cpu_mask(j, node->cpumask) {
3783 struct sched_group *cpu = &sched_group_cpus[j];
3785 cpus_clear(cpu->cpumask);
3786 cpu_set(j, cpu->cpumask);
3787 cpu->cpu_power = SCHED_LOAD_SCALE;
3792 last_cpu->next = cpu;
3795 last_cpu->next = first_cpu;
3800 last_node->next = node;
3803 last_node->next = first_node;
3807 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3808 cpu_attach_domain(cpu_sd, i);
3812 #else /* !CONFIG_NUMA */
3813 static void __init arch_init_sched_domains(void)
3816 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3818 /* Set up domains */
3820 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3822 *cpu_sd = SD_CPU_INIT;
3823 cpu_sd->span = cpu_possible_map;
3824 cpu_sd->groups = &sched_group_cpus[i];
3827 /* Set up CPU groups */
3828 for_each_cpu_mask(i, cpu_possible_map) {
3829 struct sched_group *cpu = &sched_group_cpus[i];
3831 cpus_clear(cpu->cpumask);
3832 cpu_set(i, cpu->cpumask);
3833 cpu->cpu_power = SCHED_LOAD_SCALE;
3838 last_cpu->next = cpu;
3841 last_cpu->next = first_cpu;
3843 mb(); /* domains were modified outside the lock */
3845 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3846 cpu_attach_domain(cpu_sd, i);
3850 #endif /* CONFIG_NUMA */
3851 #endif /* ARCH_HAS_SCHED_DOMAIN */
3853 #define SCHED_DOMAIN_DEBUG
3854 #ifdef SCHED_DOMAIN_DEBUG
3855 void sched_domain_debug(void)
3860 runqueue_t *rq = cpu_rq(i);
3861 struct sched_domain *sd;
3866 printk(KERN_DEBUG "CPU%d: %s\n",
3867 i, (cpu_online(i) ? " online" : "offline"));
3872 struct sched_group *group = sd->groups;
3873 cpumask_t groupmask, tmp;
3875 cpumask_scnprintf(str, NR_CPUS, sd->span);
3876 cpus_clear(groupmask);
3879 for (j = 0; j < level + 1; j++)
3881 printk("domain %d: span %s\n", level, str);
3883 if (!cpu_isset(i, sd->span))
3884 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
3885 if (!cpu_isset(i, group->cpumask))
3886 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
3887 if (!group->cpu_power)
3888 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
3891 for (j = 0; j < level + 2; j++)
3896 printk(" ERROR: NULL");
3900 if (!cpus_weight(group->cpumask))
3901 printk(" ERROR empty group:");
3903 cpus_and(tmp, groupmask, group->cpumask);
3904 if (cpus_weight(tmp) > 0)
3905 printk(" ERROR repeated CPUs:");
3907 cpus_or(groupmask, groupmask, group->cpumask);
3909 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
3912 group = group->next;
3913 } while (group != sd->groups);
3916 if (!cpus_equal(sd->span, groupmask))
3917 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
3923 cpus_and(tmp, groupmask, sd->span);
3924 if (!cpus_equal(tmp, groupmask))
3925 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
3932 #define sched_domain_debug() {}
3935 void __init sched_init_smp(void)
3937 arch_init_sched_domains();
3938 sched_domain_debug();
3941 void __init sched_init_smp(void)
3944 #endif /* CONFIG_SMP */
3946 int in_sched_functions(unsigned long addr)
3948 /* Linker adds these: start and end of __sched functions */
3949 extern char __sched_text_start[], __sched_text_end[];
3950 return addr >= (unsigned long)__sched_text_start
3951 && addr < (unsigned long)__sched_text_end;
3954 void __init sched_init(void)
3960 /* Set up an initial dummy domain for early boot */
3961 static struct sched_domain sched_domain_init;
3962 static struct sched_group sched_group_init;
3963 cpumask_t cpu_mask_all = CPU_MASK_ALL;
3965 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
3966 sched_domain_init.span = cpu_mask_all;
3967 sched_domain_init.groups = &sched_group_init;
3968 sched_domain_init.last_balance = jiffies;
3969 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
3971 memset(&sched_group_init, 0, sizeof(struct sched_group));
3972 sched_group_init.cpumask = cpu_mask_all;
3973 sched_group_init.next = &sched_group_init;
3974 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
3977 for (i = 0; i < NR_CPUS; i++) {
3978 prio_array_t *array;
3981 spin_lock_init(&rq->lock);
3982 rq->active = rq->arrays;
3983 rq->expired = rq->arrays + 1;
3984 rq->best_expired_prio = MAX_PRIO;
3987 rq->sd = &sched_domain_init;
3989 rq->active_balance = 0;
3991 rq->migration_thread = NULL;
3992 INIT_LIST_HEAD(&rq->migration_queue);
3994 INIT_LIST_HEAD(&rq->hold_queue);
3995 atomic_set(&rq->nr_iowait, 0);
3997 for (j = 0; j < 2; j++) {
3998 array = rq->arrays + j;
3999 for (k = 0; k < MAX_PRIO; k++) {
4000 INIT_LIST_HEAD(array->queue + k);
4001 __clear_bit(k, array->bitmap);
4003 // delimiter for bitsearch
4004 __set_bit(MAX_PRIO, array->bitmap);
4008 * We have to do a little magic to get the first
4009 * thread right in SMP mode.
4014 set_task_cpu(current, smp_processor_id());
4015 wake_up_forked_process(current);
4018 * The boot idle thread does lazy MMU switching as well:
4020 atomic_inc(&init_mm.mm_count);
4021 enter_lazy_tlb(&init_mm, current);
4024 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4025 void __might_sleep(char *file, int line)
4027 #if defined(in_atomic)
4028 static unsigned long prev_jiffy; /* ratelimiting */
4030 if ((in_atomic() || irqs_disabled()) &&
4031 system_state == SYSTEM_RUNNING) {
4032 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4034 prev_jiffy = jiffies;
4035 printk(KERN_ERR "Debug: sleeping function called from invalid"
4036 " context at %s:%d\n", file, line);
4037 printk("in_atomic():%d, irqs_disabled():%d\n",
4038 in_atomic(), irqs_disabled());
4043 EXPORT_SYMBOL(__might_sleep);
4047 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
4049 * This could be a long-held lock. If another CPU holds it for a long time,
4050 * and that CPU is not asked to reschedule then *this* CPU will spin on the
4051 * lock for a long time, even if *this* CPU is asked to reschedule.
4053 * So what we do here, in the slow (contended) path is to spin on the lock by
4054 * hand while permitting preemption.
4056 * Called inside preempt_disable().
4058 void __sched __preempt_spin_lock(spinlock_t *lock)
4060 if (preempt_count() > 1) {
4061 _raw_spin_lock(lock);
4066 while (spin_is_locked(lock))
4069 } while (!_raw_spin_trylock(lock));
4072 EXPORT_SYMBOL(__preempt_spin_lock);
4074 void __sched __preempt_write_lock(rwlock_t *lock)
4076 if (preempt_count() > 1) {
4077 _raw_write_lock(lock);
4083 while (rwlock_is_locked(lock))
4086 } while (!_raw_write_trylock(lock));
4089 EXPORT_SYMBOL(__preempt_write_lock);
4090 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */