4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/capability.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/profile.h>
36 #include <linux/suspend.h>
37 #include <linux/vmalloc.h>
38 #include <linux/blkdev.h>
39 #include <linux/delay.h>
40 #include <linux/smp.h>
41 #include <linux/threads.h>
42 #include <linux/timer.h>
43 #include <linux/rcupdate.h>
44 #include <linux/cpu.h>
45 #include <linux/cpuset.h>
46 #include <linux/percpu.h>
47 #include <linux/kthread.h>
48 #include <linux/seq_file.h>
49 #include <linux/syscalls.h>
50 #include <linux/times.h>
51 #include <linux/acct.h>
54 #include <asm/unistd.h>
57 * Convert user-nice values [ -20 ... 0 ... 19 ]
58 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
61 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
62 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
63 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
66 * 'User priority' is the nice value converted to something we
67 * can work with better when scaling various scheduler parameters,
68 * it's a [ 0 ... 39 ] range.
70 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
71 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
72 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
75 * Some helpers for converting nanosecond timing to jiffy resolution
77 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
78 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
81 * These are the 'tuning knobs' of the scheduler:
83 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
84 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
85 * Timeslices get refilled after they expire.
87 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
88 #define DEF_TIMESLICE (100 * HZ / 1000)
89 #define ON_RUNQUEUE_WEIGHT 30
90 #define CHILD_PENALTY 95
91 #define PARENT_PENALTY 100
93 #define PRIO_BONUS_RATIO 25
94 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
95 #define INTERACTIVE_DELTA 2
96 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
97 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
98 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
101 * If a task is 'interactive' then we reinsert it in the active
102 * array after it has expired its current timeslice. (it will not
103 * continue to run immediately, it will still roundrobin with
104 * other interactive tasks.)
106 * This part scales the interactivity limit depending on niceness.
108 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
109 * Here are a few examples of different nice levels:
111 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
112 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
113 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
114 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
115 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
117 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
118 * priority range a task can explore, a value of '1' means the
119 * task is rated interactive.)
121 * Ie. nice +19 tasks can never get 'interactive' enough to be
122 * reinserted into the active array. And only heavily CPU-hog nice -20
123 * tasks will be expired. Default nice 0 tasks are somewhere between,
124 * it takes some effort for them to get interactive, but it's not
128 #define CURRENT_BONUS(p) \
129 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
132 #define GRANULARITY (10 * HZ / 1000 ? : 1)
135 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
136 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
139 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
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 TASK_PREEMPTS_CURR(p, rq) \
157 ((p)->prio < (rq)->curr->prio)
160 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
161 * to time slice values: [800ms ... 100ms ... 5ms]
163 * The higher a thread's priority, the bigger timeslices
164 * it gets during one round of execution. But even the lowest
165 * priority thread gets MIN_TIMESLICE worth of execution time.
168 #define SCALE_PRIO(x, prio) \
169 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
171 static unsigned int task_timeslice(task_t *p)
173 if (p->static_prio < NICE_TO_PRIO(0))
174 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
176 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
178 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
179 < (long long) (sd)->cache_hot_time)
181 void __put_task_struct_cb(struct rcu_head *rhp)
183 __put_task_struct(container_of(rhp, struct task_struct, rcu));
186 EXPORT_SYMBOL_GPL(__put_task_struct_cb);
189 * These are the runqueue data structures:
192 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
194 typedef struct runqueue runqueue_t;
197 unsigned int nr_active;
198 unsigned long bitmap[BITMAP_SIZE];
199 struct list_head queue[MAX_PRIO];
203 * This is the main, per-CPU runqueue data structure.
205 * Locking rule: those places that want to lock multiple runqueues
206 * (such as the load balancing or the thread migration code), lock
207 * acquire operations must be ordered by ascending &runqueue.
213 * nr_running and cpu_load should be in the same cacheline because
214 * remote CPUs use both these fields when doing load calculation.
216 unsigned long nr_running;
218 unsigned long prio_bias;
219 unsigned long cpu_load[3];
221 unsigned long long nr_switches;
224 * This is part of a global counter where only the total sum
225 * over all CPUs matters. A task can increase this counter on
226 * one CPU and if it got migrated afterwards it may decrease
227 * it on another CPU. Always updated under the runqueue lock:
229 unsigned long nr_uninterruptible;
231 unsigned long expired_timestamp;
232 unsigned long long timestamp_last_tick;
234 struct mm_struct *prev_mm;
235 prio_array_t *active, *expired, arrays[2];
236 int best_expired_prio;
240 struct sched_domain *sd;
242 /* For active balancing */
246 task_t *migration_thread;
247 struct list_head migration_queue;
250 #ifdef CONFIG_SCHEDSTATS
252 struct sched_info rq_sched_info;
254 /* sys_sched_yield() stats */
255 unsigned long yld_exp_empty;
256 unsigned long yld_act_empty;
257 unsigned long yld_both_empty;
258 unsigned long yld_cnt;
260 /* schedule() stats */
261 unsigned long sched_switch;
262 unsigned long sched_cnt;
263 unsigned long sched_goidle;
265 /* try_to_wake_up() stats */
266 unsigned long ttwu_cnt;
267 unsigned long ttwu_local;
271 static DEFINE_PER_CPU(struct runqueue, runqueues);
274 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
275 * See detach_destroy_domains: synchronize_sched for details.
277 * The domain tree of any CPU may only be accessed from within
278 * preempt-disabled sections.
280 #define for_each_domain(cpu, domain) \
281 for (domain = rcu_dereference(cpu_rq(cpu)->sd); domain; domain = domain->parent)
283 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
284 #define this_rq() (&__get_cpu_var(runqueues))
285 #define task_rq(p) cpu_rq(task_cpu(p))
286 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
288 #ifndef prepare_arch_switch
289 # define prepare_arch_switch(next) do { } while (0)
291 #ifndef finish_arch_switch
292 # define finish_arch_switch(prev) do { } while (0)
295 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
296 static inline int task_running(runqueue_t *rq, task_t *p)
298 return rq->curr == p;
301 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
305 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
307 #ifdef CONFIG_DEBUG_SPINLOCK
308 /* this is a valid case when another task releases the spinlock */
309 rq->lock.owner = current;
311 spin_unlock_irq(&rq->lock);
314 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
315 static inline int task_running(runqueue_t *rq, task_t *p)
320 return rq->curr == p;
324 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
328 * We can optimise this out completely for !SMP, because the
329 * SMP rebalancing from interrupt is the only thing that cares
334 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
335 spin_unlock_irq(&rq->lock);
337 spin_unlock(&rq->lock);
341 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
345 * After ->oncpu is cleared, the task can be moved to a different CPU.
346 * We must ensure this doesn't happen until the switch is completely
352 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
356 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
359 * task_rq_lock - lock the runqueue a given task resides on and disable
360 * interrupts. Note the ordering: we can safely lookup the task_rq without
361 * explicitly disabling preemption.
363 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
369 local_irq_save(*flags);
371 spin_lock(&rq->lock);
372 if (unlikely(rq != task_rq(p))) {
373 spin_unlock_irqrestore(&rq->lock, *flags);
374 goto repeat_lock_task;
379 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
382 spin_unlock_irqrestore(&rq->lock, *flags);
385 #ifdef CONFIG_SCHEDSTATS
387 * bump this up when changing the output format or the meaning of an existing
388 * format, so that tools can adapt (or abort)
390 #define SCHEDSTAT_VERSION 12
392 static int show_schedstat(struct seq_file *seq, void *v)
396 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
397 seq_printf(seq, "timestamp %lu\n", jiffies);
398 for_each_online_cpu(cpu) {
399 runqueue_t *rq = cpu_rq(cpu);
401 struct sched_domain *sd;
405 /* runqueue-specific stats */
407 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
408 cpu, rq->yld_both_empty,
409 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
410 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
411 rq->ttwu_cnt, rq->ttwu_local,
412 rq->rq_sched_info.cpu_time,
413 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
415 seq_printf(seq, "\n");
418 /* domain-specific stats */
420 for_each_domain(cpu, sd) {
421 enum idle_type itype;
422 char mask_str[NR_CPUS];
424 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
425 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
426 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
428 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
430 sd->lb_balanced[itype],
431 sd->lb_failed[itype],
432 sd->lb_imbalance[itype],
433 sd->lb_gained[itype],
434 sd->lb_hot_gained[itype],
435 sd->lb_nobusyq[itype],
436 sd->lb_nobusyg[itype]);
438 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
439 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
440 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
441 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
442 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
450 static int schedstat_open(struct inode *inode, struct file *file)
452 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
453 char *buf = kmalloc(size, GFP_KERNEL);
459 res = single_open(file, show_schedstat, NULL);
461 m = file->private_data;
469 struct file_operations proc_schedstat_operations = {
470 .open = schedstat_open,
473 .release = single_release,
476 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
477 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
478 #else /* !CONFIG_SCHEDSTATS */
479 # define schedstat_inc(rq, field) do { } while (0)
480 # define schedstat_add(rq, field, amt) do { } while (0)
484 * rq_lock - lock a given runqueue and disable interrupts.
486 static inline runqueue_t *this_rq_lock(void)
493 spin_lock(&rq->lock);
498 #ifdef CONFIG_SCHEDSTATS
500 * Called when a process is dequeued from the active array and given
501 * the cpu. We should note that with the exception of interactive
502 * tasks, the expired queue will become the active queue after the active
503 * queue is empty, without explicitly dequeuing and requeuing tasks in the
504 * expired queue. (Interactive tasks may be requeued directly to the
505 * active queue, thus delaying tasks in the expired queue from running;
506 * see scheduler_tick()).
508 * This function is only called from sched_info_arrive(), rather than
509 * dequeue_task(). Even though a task may be queued and dequeued multiple
510 * times as it is shuffled about, we're really interested in knowing how
511 * long it was from the *first* time it was queued to the time that it
514 static inline void sched_info_dequeued(task_t *t)
516 t->sched_info.last_queued = 0;
520 * Called when a task finally hits the cpu. We can now calculate how
521 * long it was waiting to run. We also note when it began so that we
522 * can keep stats on how long its timeslice is.
524 static inline void sched_info_arrive(task_t *t)
526 unsigned long now = jiffies, diff = 0;
527 struct runqueue *rq = task_rq(t);
529 if (t->sched_info.last_queued)
530 diff = now - t->sched_info.last_queued;
531 sched_info_dequeued(t);
532 t->sched_info.run_delay += diff;
533 t->sched_info.last_arrival = now;
534 t->sched_info.pcnt++;
539 rq->rq_sched_info.run_delay += diff;
540 rq->rq_sched_info.pcnt++;
544 * Called when a process is queued into either the active or expired
545 * array. The time is noted and later used to determine how long we
546 * had to wait for us to reach the cpu. Since the expired queue will
547 * become the active queue after active queue is empty, without dequeuing
548 * and requeuing any tasks, we are interested in queuing to either. It
549 * is unusual but not impossible for tasks to be dequeued and immediately
550 * requeued in the same or another array: this can happen in sched_yield(),
551 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
554 * This function is only called from enqueue_task(), but also only updates
555 * the timestamp if it is already not set. It's assumed that
556 * sched_info_dequeued() will clear that stamp when appropriate.
558 static inline void sched_info_queued(task_t *t)
560 if (!t->sched_info.last_queued)
561 t->sched_info.last_queued = jiffies;
565 * Called when a process ceases being the active-running process, either
566 * voluntarily or involuntarily. Now we can calculate how long we ran.
568 static inline void sched_info_depart(task_t *t)
570 struct runqueue *rq = task_rq(t);
571 unsigned long diff = jiffies - t->sched_info.last_arrival;
573 t->sched_info.cpu_time += diff;
576 rq->rq_sched_info.cpu_time += diff;
580 * Called when tasks are switched involuntarily due, typically, to expiring
581 * their time slice. (This may also be called when switching to or from
582 * the idle task.) We are only called when prev != next.
584 static inline void sched_info_switch(task_t *prev, task_t *next)
586 struct runqueue *rq = task_rq(prev);
589 * prev now departs the cpu. It's not interesting to record
590 * stats about how efficient we were at scheduling the idle
593 if (prev != rq->idle)
594 sched_info_depart(prev);
596 if (next != rq->idle)
597 sched_info_arrive(next);
600 #define sched_info_queued(t) do { } while (0)
601 #define sched_info_switch(t, next) do { } while (0)
602 #endif /* CONFIG_SCHEDSTATS */
605 * Adding/removing a task to/from a priority array:
607 static void dequeue_task(struct task_struct *p, prio_array_t *array)
610 list_del(&p->run_list);
611 if (list_empty(array->queue + p->prio))
612 __clear_bit(p->prio, array->bitmap);
615 static void enqueue_task(struct task_struct *p, prio_array_t *array)
617 sched_info_queued(p);
618 list_add_tail(&p->run_list, array->queue + p->prio);
619 __set_bit(p->prio, array->bitmap);
625 * Put task to the end of the run list without the overhead of dequeue
626 * followed by enqueue.
628 static void requeue_task(struct task_struct *p, prio_array_t *array)
630 list_move_tail(&p->run_list, array->queue + p->prio);
633 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
635 list_add(&p->run_list, array->queue + p->prio);
636 __set_bit(p->prio, array->bitmap);
642 * effective_prio - return the priority that is based on the static
643 * priority but is modified by bonuses/penalties.
645 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
646 * into the -5 ... 0 ... +5 bonus/penalty range.
648 * We use 25% of the full 0...39 priority range so that:
650 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
651 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
653 * Both properties are important to certain workloads.
655 static int effective_prio(task_t *p)
662 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
664 prio = p->static_prio - bonus;
665 if (prio < MAX_RT_PRIO)
667 if (prio > MAX_PRIO-1)
673 static inline void inc_prio_bias(runqueue_t *rq, int prio)
675 rq->prio_bias += MAX_PRIO - prio;
678 static inline void dec_prio_bias(runqueue_t *rq, int prio)
680 rq->prio_bias -= MAX_PRIO - prio;
683 static inline void inc_nr_running(task_t *p, runqueue_t *rq)
687 if (p != rq->migration_thread)
689 * The migration thread does the actual balancing. Do
690 * not bias by its priority as the ultra high priority
691 * will skew balancing adversely.
693 inc_prio_bias(rq, p->prio);
695 inc_prio_bias(rq, p->static_prio);
698 static inline void dec_nr_running(task_t *p, runqueue_t *rq)
702 if (p != rq->migration_thread)
703 dec_prio_bias(rq, p->prio);
705 dec_prio_bias(rq, p->static_prio);
708 static inline void inc_prio_bias(runqueue_t *rq, int prio)
712 static inline void dec_prio_bias(runqueue_t *rq, int prio)
716 static inline void inc_nr_running(task_t *p, runqueue_t *rq)
721 static inline void dec_nr_running(task_t *p, runqueue_t *rq)
728 * __activate_task - move a task to the runqueue.
730 static inline void __activate_task(task_t *p, runqueue_t *rq)
732 enqueue_task(p, rq->active);
733 inc_nr_running(p, rq);
737 * __activate_idle_task - move idle task to the _front_ of runqueue.
739 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
741 enqueue_task_head(p, rq->active);
742 inc_nr_running(p, rq);
745 static int recalc_task_prio(task_t *p, unsigned long long now)
747 /* Caller must always ensure 'now >= p->timestamp' */
748 unsigned long long __sleep_time = now - p->timestamp;
749 unsigned long sleep_time;
751 if (__sleep_time > NS_MAX_SLEEP_AVG)
752 sleep_time = NS_MAX_SLEEP_AVG;
754 sleep_time = (unsigned long)__sleep_time;
756 if (likely(sleep_time > 0)) {
758 * User tasks that sleep a long time are categorised as
759 * idle and will get just interactive status to stay active &
760 * prevent them suddenly becoming cpu hogs and starving
763 if (p->mm && p->activated != -1 &&
764 sleep_time > INTERACTIVE_SLEEP(p)) {
765 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
769 * The lower the sleep avg a task has the more
770 * rapidly it will rise with sleep time.
772 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
775 * Tasks waking from uninterruptible sleep are
776 * limited in their sleep_avg rise as they
777 * are likely to be waiting on I/O
779 if (p->activated == -1 && p->mm) {
780 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
782 else if (p->sleep_avg + sleep_time >=
783 INTERACTIVE_SLEEP(p)) {
784 p->sleep_avg = INTERACTIVE_SLEEP(p);
790 * This code gives a bonus to interactive tasks.
792 * The boost works by updating the 'average sleep time'
793 * value here, based on ->timestamp. The more time a
794 * task spends sleeping, the higher the average gets -
795 * and the higher the priority boost gets as well.
797 p->sleep_avg += sleep_time;
799 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
800 p->sleep_avg = NS_MAX_SLEEP_AVG;
804 return effective_prio(p);
808 * activate_task - move a task to the runqueue and do priority recalculation
810 * Update all the scheduling statistics stuff. (sleep average
811 * calculation, priority modifiers, etc.)
813 static void activate_task(task_t *p, runqueue_t *rq, int local)
815 unsigned long long now;
820 /* Compensate for drifting sched_clock */
821 runqueue_t *this_rq = this_rq();
822 now = (now - this_rq->timestamp_last_tick)
823 + rq->timestamp_last_tick;
828 p->prio = recalc_task_prio(p, now);
831 * This checks to make sure it's not an uninterruptible task
832 * that is now waking up.
836 * Tasks which were woken up by interrupts (ie. hw events)
837 * are most likely of interactive nature. So we give them
838 * the credit of extending their sleep time to the period
839 * of time they spend on the runqueue, waiting for execution
840 * on a CPU, first time around:
846 * Normal first-time wakeups get a credit too for
847 * on-runqueue time, but it will be weighted down:
854 __activate_task(p, rq);
858 * deactivate_task - remove a task from the runqueue.
860 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
862 dec_nr_running(p, rq);
863 dequeue_task(p, p->array);
868 * resched_task - mark a task 'to be rescheduled now'.
870 * On UP this means the setting of the need_resched flag, on SMP it
871 * might also involve a cross-CPU call to trigger the scheduler on
875 static void resched_task(task_t *p)
879 assert_spin_locked(&task_rq(p)->lock);
881 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
884 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
887 if (cpu == smp_processor_id())
890 /* NEED_RESCHED must be visible before we test POLLING_NRFLAG */
892 if (!test_tsk_thread_flag(p, TIF_POLLING_NRFLAG))
893 smp_send_reschedule(cpu);
896 static inline void resched_task(task_t *p)
898 assert_spin_locked(&task_rq(p)->lock);
899 set_tsk_need_resched(p);
904 * task_curr - is this task currently executing on a CPU?
905 * @p: the task in question.
907 inline int task_curr(const task_t *p)
909 return cpu_curr(task_cpu(p)) == p;
914 struct list_head list;
919 struct completion done;
923 * The task's runqueue lock must be held.
924 * Returns true if you have to wait for migration thread.
926 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
928 runqueue_t *rq = task_rq(p);
931 * If the task is not on a runqueue (and not running), then
932 * it is sufficient to simply update the task's cpu field.
934 if (!p->array && !task_running(rq, p)) {
935 set_task_cpu(p, dest_cpu);
939 init_completion(&req->done);
941 req->dest_cpu = dest_cpu;
942 list_add(&req->list, &rq->migration_queue);
947 * wait_task_inactive - wait for a thread to unschedule.
949 * The caller must ensure that the task *will* unschedule sometime soon,
950 * else this function might spin for a *long* time. This function can't
951 * be called with interrupts off, or it may introduce deadlock with
952 * smp_call_function() if an IPI is sent by the same process we are
953 * waiting to become inactive.
955 void wait_task_inactive(task_t *p)
962 rq = task_rq_lock(p, &flags);
963 /* Must be off runqueue entirely, not preempted. */
964 if (unlikely(p->array || task_running(rq, p))) {
965 /* If it's preempted, we yield. It could be a while. */
966 preempted = !task_running(rq, p);
967 task_rq_unlock(rq, &flags);
973 task_rq_unlock(rq, &flags);
977 * kick_process - kick a running thread to enter/exit the kernel
978 * @p: the to-be-kicked thread
980 * Cause a process which is running on another CPU to enter
981 * kernel-mode, without any delay. (to get signals handled.)
983 * NOTE: this function doesnt have to take the runqueue lock,
984 * because all it wants to ensure is that the remote task enters
985 * the kernel. If the IPI races and the task has been migrated
986 * to another CPU then no harm is done and the purpose has been
989 void kick_process(task_t *p)
995 if ((cpu != smp_processor_id()) && task_curr(p))
996 smp_send_reschedule(cpu);
1001 * Return a low guess at the load of a migration-source cpu.
1003 * We want to under-estimate the load of migration sources, to
1004 * balance conservatively.
1006 static inline unsigned long __source_load(int cpu, int type, enum idle_type idle)
1008 runqueue_t *rq = cpu_rq(cpu);
1009 unsigned long running = rq->nr_running;
1010 unsigned long source_load, cpu_load = rq->cpu_load[type-1],
1011 load_now = running * SCHED_LOAD_SCALE;
1014 source_load = load_now;
1016 source_load = min(cpu_load, load_now);
1018 if (running > 1 || (idle == NOT_IDLE && running))
1020 * If we are busy rebalancing the load is biased by
1021 * priority to create 'nice' support across cpus. When
1022 * idle rebalancing we should only bias the source_load if
1023 * there is more than one task running on that queue to
1024 * prevent idle rebalance from trying to pull tasks from a
1025 * queue with only one running task.
1027 source_load = source_load * rq->prio_bias / running;
1032 static inline unsigned long source_load(int cpu, int type)
1034 return __source_load(cpu, type, NOT_IDLE);
1038 * Return a high guess at the load of a migration-target cpu
1040 static inline unsigned long __target_load(int cpu, int type, enum idle_type idle)
1042 runqueue_t *rq = cpu_rq(cpu);
1043 unsigned long running = rq->nr_running;
1044 unsigned long target_load, cpu_load = rq->cpu_load[type-1],
1045 load_now = running * SCHED_LOAD_SCALE;
1048 target_load = load_now;
1050 target_load = max(cpu_load, load_now);
1052 if (running > 1 || (idle == NOT_IDLE && running))
1053 target_load = target_load * rq->prio_bias / running;
1058 static inline unsigned long target_load(int cpu, int type)
1060 return __target_load(cpu, type, NOT_IDLE);
1064 * find_idlest_group finds and returns the least busy CPU group within the
1067 static struct sched_group *
1068 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1070 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1071 unsigned long min_load = ULONG_MAX, this_load = 0;
1072 int load_idx = sd->forkexec_idx;
1073 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1076 unsigned long load, avg_load;
1080 /* Skip over this group if it has no CPUs allowed */
1081 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1084 local_group = cpu_isset(this_cpu, group->cpumask);
1086 /* Tally up the load of all CPUs in the group */
1089 for_each_cpu_mask(i, group->cpumask) {
1090 /* Bias balancing toward cpus of our domain */
1092 load = source_load(i, load_idx);
1094 load = target_load(i, load_idx);
1099 /* Adjust by relative CPU power of the group */
1100 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1103 this_load = avg_load;
1105 } else if (avg_load < min_load) {
1106 min_load = avg_load;
1110 group = group->next;
1111 } while (group != sd->groups);
1113 if (!idlest || 100*this_load < imbalance*min_load)
1119 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1122 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1125 unsigned long load, min_load = ULONG_MAX;
1129 /* Traverse only the allowed CPUs */
1130 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1132 for_each_cpu_mask(i, tmp) {
1133 load = source_load(i, 0);
1135 if (load < min_load || (load == min_load && i == this_cpu)) {
1145 * sched_balance_self: balance the current task (running on cpu) in domains
1146 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1149 * Balance, ie. select the least loaded group.
1151 * Returns the target CPU number, or the same CPU if no balancing is needed.
1153 * preempt must be disabled.
1155 static int sched_balance_self(int cpu, int flag)
1157 struct task_struct *t = current;
1158 struct sched_domain *tmp, *sd = NULL;
1160 for_each_domain(cpu, tmp)
1161 if (tmp->flags & flag)
1166 struct sched_group *group;
1171 group = find_idlest_group(sd, t, cpu);
1175 new_cpu = find_idlest_cpu(group, t, cpu);
1176 if (new_cpu == -1 || new_cpu == cpu)
1179 /* Now try balancing at a lower domain level */
1183 weight = cpus_weight(span);
1184 for_each_domain(cpu, tmp) {
1185 if (weight <= cpus_weight(tmp->span))
1187 if (tmp->flags & flag)
1190 /* while loop will break here if sd == NULL */
1196 #endif /* CONFIG_SMP */
1199 * wake_idle() will wake a task on an idle cpu if task->cpu is
1200 * not idle and an idle cpu is available. The span of cpus to
1201 * search starts with cpus closest then further out as needed,
1202 * so we always favor a closer, idle cpu.
1204 * Returns the CPU we should wake onto.
1206 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1207 static int wake_idle(int cpu, task_t *p)
1210 struct sched_domain *sd;
1216 for_each_domain(cpu, sd) {
1217 if (sd->flags & SD_WAKE_IDLE) {
1218 cpus_and(tmp, sd->span, p->cpus_allowed);
1219 for_each_cpu_mask(i, tmp) {
1230 static inline int wake_idle(int cpu, task_t *p)
1237 * try_to_wake_up - wake up a thread
1238 * @p: the to-be-woken-up thread
1239 * @state: the mask of task states that can be woken
1240 * @sync: do a synchronous wakeup?
1242 * Put it on the run-queue if it's not already there. The "current"
1243 * thread is always on the run-queue (except when the actual
1244 * re-schedule is in progress), and as such you're allowed to do
1245 * the simpler "current->state = TASK_RUNNING" to mark yourself
1246 * runnable without the overhead of this.
1248 * returns failure only if the task is already active.
1250 static int try_to_wake_up(task_t *p, unsigned int state, int sync)
1252 int cpu, this_cpu, success = 0;
1253 unsigned long flags;
1257 unsigned long load, this_load;
1258 struct sched_domain *sd, *this_sd = NULL;
1262 rq = task_rq_lock(p, &flags);
1263 old_state = p->state;
1264 if (!(old_state & state))
1271 this_cpu = smp_processor_id();
1274 if (unlikely(task_running(rq, p)))
1279 schedstat_inc(rq, ttwu_cnt);
1280 if (cpu == this_cpu) {
1281 schedstat_inc(rq, ttwu_local);
1285 for_each_domain(this_cpu, sd) {
1286 if (cpu_isset(cpu, sd->span)) {
1287 schedstat_inc(sd, ttwu_wake_remote);
1293 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1297 * Check for affine wakeup and passive balancing possibilities.
1300 int idx = this_sd->wake_idx;
1301 unsigned int imbalance;
1303 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1305 load = source_load(cpu, idx);
1306 this_load = target_load(this_cpu, idx);
1308 new_cpu = this_cpu; /* Wake to this CPU if we can */
1310 if (this_sd->flags & SD_WAKE_AFFINE) {
1311 unsigned long tl = this_load;
1313 * If sync wakeup then subtract the (maximum possible)
1314 * effect of the currently running task from the load
1315 * of the current CPU:
1318 tl -= SCHED_LOAD_SCALE;
1321 tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
1322 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
1324 * This domain has SD_WAKE_AFFINE and
1325 * p is cache cold in this domain, and
1326 * there is no bad imbalance.
1328 schedstat_inc(this_sd, ttwu_move_affine);
1334 * Start passive balancing when half the imbalance_pct
1337 if (this_sd->flags & SD_WAKE_BALANCE) {
1338 if (imbalance*this_load <= 100*load) {
1339 schedstat_inc(this_sd, ttwu_move_balance);
1345 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1347 new_cpu = wake_idle(new_cpu, p);
1348 if (new_cpu != cpu) {
1349 set_task_cpu(p, new_cpu);
1350 task_rq_unlock(rq, &flags);
1351 /* might preempt at this point */
1352 rq = task_rq_lock(p, &flags);
1353 old_state = p->state;
1354 if (!(old_state & state))
1359 this_cpu = smp_processor_id();
1364 #endif /* CONFIG_SMP */
1365 if (old_state == TASK_UNINTERRUPTIBLE) {
1366 rq->nr_uninterruptible--;
1368 * Tasks on involuntary sleep don't earn
1369 * sleep_avg beyond just interactive state.
1375 * Tasks that have marked their sleep as noninteractive get
1376 * woken up without updating their sleep average. (i.e. their
1377 * sleep is handled in a priority-neutral manner, no priority
1378 * boost and no penalty.)
1380 if (old_state & TASK_NONINTERACTIVE)
1381 __activate_task(p, rq);
1383 activate_task(p, rq, cpu == this_cpu);
1385 * Sync wakeups (i.e. those types of wakeups where the waker
1386 * has indicated that it will leave the CPU in short order)
1387 * don't trigger a preemption, if the woken up task will run on
1388 * this cpu. (in this case the 'I will reschedule' promise of
1389 * the waker guarantees that the freshly woken up task is going
1390 * to be considered on this CPU.)
1392 if (!sync || cpu != this_cpu) {
1393 if (TASK_PREEMPTS_CURR(p, rq))
1394 resched_task(rq->curr);
1399 p->state = TASK_RUNNING;
1401 task_rq_unlock(rq, &flags);
1406 int fastcall wake_up_process(task_t *p)
1408 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1409 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1412 EXPORT_SYMBOL(wake_up_process);
1414 int fastcall wake_up_state(task_t *p, unsigned int state)
1416 return try_to_wake_up(p, state, 0);
1420 * Perform scheduler related setup for a newly forked process p.
1421 * p is forked by current.
1423 void fastcall sched_fork(task_t *p, int clone_flags)
1425 int cpu = get_cpu();
1428 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1430 set_task_cpu(p, cpu);
1433 * We mark the process as running here, but have not actually
1434 * inserted it onto the runqueue yet. This guarantees that
1435 * nobody will actually run it, and a signal or other external
1436 * event cannot wake it up and insert it on the runqueue either.
1438 p->state = TASK_RUNNING;
1439 INIT_LIST_HEAD(&p->run_list);
1441 #ifdef CONFIG_SCHEDSTATS
1442 memset(&p->sched_info, 0, sizeof(p->sched_info));
1444 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1447 #ifdef CONFIG_PREEMPT
1448 /* Want to start with kernel preemption disabled. */
1449 task_thread_info(p)->preempt_count = 1;
1452 * Share the timeslice between parent and child, thus the
1453 * total amount of pending timeslices in the system doesn't change,
1454 * resulting in more scheduling fairness.
1456 local_irq_disable();
1457 p->time_slice = (current->time_slice + 1) >> 1;
1459 * The remainder of the first timeslice might be recovered by
1460 * the parent if the child exits early enough.
1462 p->first_time_slice = 1;
1463 current->time_slice >>= 1;
1464 p->timestamp = sched_clock();
1465 if (unlikely(!current->time_slice)) {
1467 * This case is rare, it happens when the parent has only
1468 * a single jiffy left from its timeslice. Taking the
1469 * runqueue lock is not a problem.
1471 current->time_slice = 1;
1479 * wake_up_new_task - wake up a newly created task for the first time.
1481 * This function will do some initial scheduler statistics housekeeping
1482 * that must be done for every newly created context, then puts the task
1483 * on the runqueue and wakes it.
1485 void fastcall wake_up_new_task(task_t *p, unsigned long clone_flags)
1487 unsigned long flags;
1489 runqueue_t *rq, *this_rq;
1491 rq = task_rq_lock(p, &flags);
1492 BUG_ON(p->state != TASK_RUNNING);
1493 this_cpu = smp_processor_id();
1497 * We decrease the sleep average of forking parents
1498 * and children as well, to keep max-interactive tasks
1499 * from forking tasks that are max-interactive. The parent
1500 * (current) is done further down, under its lock.
1502 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1503 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1505 p->prio = effective_prio(p);
1507 if (likely(cpu == this_cpu)) {
1508 if (!(clone_flags & CLONE_VM)) {
1510 * The VM isn't cloned, so we're in a good position to
1511 * do child-runs-first in anticipation of an exec. This
1512 * usually avoids a lot of COW overhead.
1514 if (unlikely(!current->array))
1515 __activate_task(p, rq);
1517 p->prio = current->prio;
1518 list_add_tail(&p->run_list, ¤t->run_list);
1519 p->array = current->array;
1520 p->array->nr_active++;
1521 inc_nr_running(p, rq);
1525 /* Run child last */
1526 __activate_task(p, rq);
1528 * We skip the following code due to cpu == this_cpu
1530 * task_rq_unlock(rq, &flags);
1531 * this_rq = task_rq_lock(current, &flags);
1535 this_rq = cpu_rq(this_cpu);
1538 * Not the local CPU - must adjust timestamp. This should
1539 * get optimised away in the !CONFIG_SMP case.
1541 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1542 + rq->timestamp_last_tick;
1543 __activate_task(p, rq);
1544 if (TASK_PREEMPTS_CURR(p, rq))
1545 resched_task(rq->curr);
1548 * Parent and child are on different CPUs, now get the
1549 * parent runqueue to update the parent's ->sleep_avg:
1551 task_rq_unlock(rq, &flags);
1552 this_rq = task_rq_lock(current, &flags);
1554 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1555 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1556 task_rq_unlock(this_rq, &flags);
1560 * Potentially available exiting-child timeslices are
1561 * retrieved here - this way the parent does not get
1562 * penalized for creating too many threads.
1564 * (this cannot be used to 'generate' timeslices
1565 * artificially, because any timeslice recovered here
1566 * was given away by the parent in the first place.)
1568 void fastcall sched_exit(task_t *p)
1570 unsigned long flags;
1574 * If the child was a (relative-) CPU hog then decrease
1575 * the sleep_avg of the parent as well.
1577 rq = task_rq_lock(p->parent, &flags);
1578 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1579 p->parent->time_slice += p->time_slice;
1580 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1581 p->parent->time_slice = task_timeslice(p);
1583 if (p->sleep_avg < p->parent->sleep_avg)
1584 p->parent->sleep_avg = p->parent->sleep_avg /
1585 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1587 task_rq_unlock(rq, &flags);
1591 * prepare_task_switch - prepare to switch tasks
1592 * @rq: the runqueue preparing to switch
1593 * @next: the task we are going to switch to.
1595 * This is called with the rq lock held and interrupts off. It must
1596 * be paired with a subsequent finish_task_switch after the context
1599 * prepare_task_switch sets up locking and calls architecture specific
1602 static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
1604 prepare_lock_switch(rq, next);
1605 prepare_arch_switch(next);
1609 * finish_task_switch - clean up after a task-switch
1610 * @rq: runqueue associated with task-switch
1611 * @prev: the thread we just switched away from.
1613 * finish_task_switch must be called after the context switch, paired
1614 * with a prepare_task_switch call before the context switch.
1615 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1616 * and do any other architecture-specific cleanup actions.
1618 * Note that we may have delayed dropping an mm in context_switch(). If
1619 * so, we finish that here outside of the runqueue lock. (Doing it
1620 * with the lock held can cause deadlocks; see schedule() for
1623 static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
1624 __releases(rq->lock)
1626 struct mm_struct *mm = rq->prev_mm;
1627 unsigned long prev_task_flags;
1632 * A task struct has one reference for the use as "current".
1633 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1634 * calls schedule one last time. The schedule call will never return,
1635 * and the scheduled task must drop that reference.
1636 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1637 * still held, otherwise prev could be scheduled on another cpu, die
1638 * there before we look at prev->state, and then the reference would
1640 * Manfred Spraul <manfred@colorfullife.com>
1642 prev_task_flags = prev->flags;
1643 finish_arch_switch(prev);
1644 finish_lock_switch(rq, prev);
1647 if (unlikely(prev_task_flags & PF_DEAD))
1648 put_task_struct(prev);
1652 * schedule_tail - first thing a freshly forked thread must call.
1653 * @prev: the thread we just switched away from.
1655 asmlinkage void schedule_tail(task_t *prev)
1656 __releases(rq->lock)
1658 runqueue_t *rq = this_rq();
1659 finish_task_switch(rq, prev);
1660 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1661 /* In this case, finish_task_switch does not reenable preemption */
1664 if (current->set_child_tid)
1665 put_user(current->pid, current->set_child_tid);
1669 * context_switch - switch to the new MM and the new
1670 * thread's register state.
1673 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1675 struct mm_struct *mm = next->mm;
1676 struct mm_struct *oldmm = prev->active_mm;
1678 if (unlikely(!mm)) {
1679 next->active_mm = oldmm;
1680 atomic_inc(&oldmm->mm_count);
1681 enter_lazy_tlb(oldmm, next);
1683 switch_mm(oldmm, mm, next);
1685 if (unlikely(!prev->mm)) {
1686 prev->active_mm = NULL;
1687 WARN_ON(rq->prev_mm);
1688 rq->prev_mm = oldmm;
1691 /* Here we just switch the register state and the stack. */
1692 switch_to(prev, next, prev);
1698 * nr_running, nr_uninterruptible and nr_context_switches:
1700 * externally visible scheduler statistics: current number of runnable
1701 * threads, current number of uninterruptible-sleeping threads, total
1702 * number of context switches performed since bootup.
1704 unsigned long nr_running(void)
1706 unsigned long i, sum = 0;
1708 for_each_online_cpu(i)
1709 sum += cpu_rq(i)->nr_running;
1714 unsigned long nr_uninterruptible(void)
1716 unsigned long i, sum = 0;
1719 sum += cpu_rq(i)->nr_uninterruptible;
1722 * Since we read the counters lockless, it might be slightly
1723 * inaccurate. Do not allow it to go below zero though:
1725 if (unlikely((long)sum < 0))
1731 unsigned long long nr_context_switches(void)
1733 unsigned long long i, sum = 0;
1736 sum += cpu_rq(i)->nr_switches;
1741 unsigned long nr_iowait(void)
1743 unsigned long i, sum = 0;
1746 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1754 * double_rq_lock - safely lock two runqueues
1756 * Note this does not disable interrupts like task_rq_lock,
1757 * you need to do so manually before calling.
1759 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1760 __acquires(rq1->lock)
1761 __acquires(rq2->lock)
1764 spin_lock(&rq1->lock);
1765 __acquire(rq2->lock); /* Fake it out ;) */
1768 spin_lock(&rq1->lock);
1769 spin_lock(&rq2->lock);
1771 spin_lock(&rq2->lock);
1772 spin_lock(&rq1->lock);
1778 * double_rq_unlock - safely unlock two runqueues
1780 * Note this does not restore interrupts like task_rq_unlock,
1781 * you need to do so manually after calling.
1783 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1784 __releases(rq1->lock)
1785 __releases(rq2->lock)
1787 spin_unlock(&rq1->lock);
1789 spin_unlock(&rq2->lock);
1791 __release(rq2->lock);
1795 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1797 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1798 __releases(this_rq->lock)
1799 __acquires(busiest->lock)
1800 __acquires(this_rq->lock)
1802 if (unlikely(!spin_trylock(&busiest->lock))) {
1803 if (busiest < this_rq) {
1804 spin_unlock(&this_rq->lock);
1805 spin_lock(&busiest->lock);
1806 spin_lock(&this_rq->lock);
1808 spin_lock(&busiest->lock);
1813 * If dest_cpu is allowed for this process, migrate the task to it.
1814 * This is accomplished by forcing the cpu_allowed mask to only
1815 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1816 * the cpu_allowed mask is restored.
1818 static void sched_migrate_task(task_t *p, int dest_cpu)
1820 migration_req_t req;
1822 unsigned long flags;
1824 rq = task_rq_lock(p, &flags);
1825 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1826 || unlikely(cpu_is_offline(dest_cpu)))
1829 /* force the process onto the specified CPU */
1830 if (migrate_task(p, dest_cpu, &req)) {
1831 /* Need to wait for migration thread (might exit: take ref). */
1832 struct task_struct *mt = rq->migration_thread;
1833 get_task_struct(mt);
1834 task_rq_unlock(rq, &flags);
1835 wake_up_process(mt);
1836 put_task_struct(mt);
1837 wait_for_completion(&req.done);
1841 task_rq_unlock(rq, &flags);
1845 * sched_exec - execve() is a valuable balancing opportunity, because at
1846 * this point the task has the smallest effective memory and cache footprint.
1848 void sched_exec(void)
1850 int new_cpu, this_cpu = get_cpu();
1851 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1853 if (new_cpu != this_cpu)
1854 sched_migrate_task(current, new_cpu);
1858 * pull_task - move a task from a remote runqueue to the local runqueue.
1859 * Both runqueues must be locked.
1862 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1863 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1865 dequeue_task(p, src_array);
1866 dec_nr_running(p, src_rq);
1867 set_task_cpu(p, this_cpu);
1868 inc_nr_running(p, this_rq);
1869 enqueue_task(p, this_array);
1870 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1871 + this_rq->timestamp_last_tick;
1873 * Note that idle threads have a prio of MAX_PRIO, for this test
1874 * to be always true for them.
1876 if (TASK_PREEMPTS_CURR(p, this_rq))
1877 resched_task(this_rq->curr);
1881 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1884 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1885 struct sched_domain *sd, enum idle_type idle,
1889 * We do not migrate tasks that are:
1890 * 1) running (obviously), or
1891 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1892 * 3) are cache-hot on their current CPU.
1894 if (!cpu_isset(this_cpu, p->cpus_allowed))
1898 if (task_running(rq, p))
1902 * Aggressive migration if:
1903 * 1) task is cache cold, or
1904 * 2) too many balance attempts have failed.
1907 if (sd->nr_balance_failed > sd->cache_nice_tries)
1910 if (task_hot(p, rq->timestamp_last_tick, sd))
1916 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1917 * as part of a balancing operation within "domain". Returns the number of
1920 * Called with both runqueues locked.
1922 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1923 unsigned long max_nr_move, struct sched_domain *sd,
1924 enum idle_type idle, int *all_pinned)
1926 prio_array_t *array, *dst_array;
1927 struct list_head *head, *curr;
1928 int idx, pulled = 0, pinned = 0;
1931 if (max_nr_move == 0)
1937 * We first consider expired tasks. Those will likely not be
1938 * executed in the near future, and they are most likely to
1939 * be cache-cold, thus switching CPUs has the least effect
1942 if (busiest->expired->nr_active) {
1943 array = busiest->expired;
1944 dst_array = this_rq->expired;
1946 array = busiest->active;
1947 dst_array = this_rq->active;
1951 /* Start searching at priority 0: */
1955 idx = sched_find_first_bit(array->bitmap);
1957 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1958 if (idx >= MAX_PRIO) {
1959 if (array == busiest->expired && busiest->active->nr_active) {
1960 array = busiest->active;
1961 dst_array = this_rq->active;
1967 head = array->queue + idx;
1970 tmp = list_entry(curr, task_t, run_list);
1974 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
1981 #ifdef CONFIG_SCHEDSTATS
1982 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1983 schedstat_inc(sd, lb_hot_gained[idle]);
1986 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1989 /* We only want to steal up to the prescribed number of tasks. */
1990 if (pulled < max_nr_move) {
1998 * Right now, this is the only place pull_task() is called,
1999 * so we can safely collect pull_task() stats here rather than
2000 * inside pull_task().
2002 schedstat_add(sd, lb_gained[idle], pulled);
2005 *all_pinned = pinned;
2010 * find_busiest_group finds and returns the busiest CPU group within the
2011 * domain. It calculates and returns the number of tasks which should be
2012 * moved to restore balance via the imbalance parameter.
2014 static struct sched_group *
2015 find_busiest_group(struct sched_domain *sd, int this_cpu,
2016 unsigned long *imbalance, enum idle_type idle, int *sd_idle)
2018 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2019 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2020 unsigned long max_pull;
2023 max_load = this_load = total_load = total_pwr = 0;
2024 if (idle == NOT_IDLE)
2025 load_idx = sd->busy_idx;
2026 else if (idle == NEWLY_IDLE)
2027 load_idx = sd->newidle_idx;
2029 load_idx = sd->idle_idx;
2036 local_group = cpu_isset(this_cpu, group->cpumask);
2038 /* Tally up the load of all CPUs in the group */
2041 for_each_cpu_mask(i, group->cpumask) {
2042 if (*sd_idle && !idle_cpu(i))
2045 /* Bias balancing toward cpus of our domain */
2047 load = __target_load(i, load_idx, idle);
2049 load = __source_load(i, load_idx, idle);
2054 total_load += avg_load;
2055 total_pwr += group->cpu_power;
2057 /* Adjust by relative CPU power of the group */
2058 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2061 this_load = avg_load;
2063 } else if (avg_load > max_load) {
2064 max_load = avg_load;
2067 group = group->next;
2068 } while (group != sd->groups);
2070 if (!busiest || this_load >= max_load || max_load <= SCHED_LOAD_SCALE)
2073 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2075 if (this_load >= avg_load ||
2076 100*max_load <= sd->imbalance_pct*this_load)
2080 * We're trying to get all the cpus to the average_load, so we don't
2081 * want to push ourselves above the average load, nor do we wish to
2082 * reduce the max loaded cpu below the average load, as either of these
2083 * actions would just result in more rebalancing later, and ping-pong
2084 * tasks around. Thus we look for the minimum possible imbalance.
2085 * Negative imbalances (*we* are more loaded than anyone else) will
2086 * be counted as no imbalance for these purposes -- we can't fix that
2087 * by pulling tasks to us. Be careful of negative numbers as they'll
2088 * appear as very large values with unsigned longs.
2091 /* Don't want to pull so many tasks that a group would go idle */
2092 max_pull = min(max_load - avg_load, max_load - SCHED_LOAD_SCALE);
2094 /* How much load to actually move to equalise the imbalance */
2095 *imbalance = min(max_pull * busiest->cpu_power,
2096 (avg_load - this_load) * this->cpu_power)
2099 if (*imbalance < SCHED_LOAD_SCALE) {
2100 unsigned long pwr_now = 0, pwr_move = 0;
2103 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2109 * OK, we don't have enough imbalance to justify moving tasks,
2110 * however we may be able to increase total CPU power used by
2114 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2115 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2116 pwr_now /= SCHED_LOAD_SCALE;
2118 /* Amount of load we'd subtract */
2119 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2121 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2124 /* Amount of load we'd add */
2125 if (max_load*busiest->cpu_power <
2126 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
2127 tmp = max_load*busiest->cpu_power/this->cpu_power;
2129 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2130 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2131 pwr_move /= SCHED_LOAD_SCALE;
2133 /* Move if we gain throughput */
2134 if (pwr_move <= pwr_now)
2141 /* Get rid of the scaling factor, rounding down as we divide */
2142 *imbalance = *imbalance / SCHED_LOAD_SCALE;
2152 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2154 static runqueue_t *find_busiest_queue(struct sched_group *group,
2155 enum idle_type idle)
2157 unsigned long load, max_load = 0;
2158 runqueue_t *busiest = NULL;
2161 for_each_cpu_mask(i, group->cpumask) {
2162 load = __source_load(i, 0, idle);
2164 if (load > max_load) {
2166 busiest = cpu_rq(i);
2174 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2175 * so long as it is large enough.
2177 #define MAX_PINNED_INTERVAL 512
2180 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2181 * tasks if there is an imbalance.
2183 * Called with this_rq unlocked.
2185 static int load_balance(int this_cpu, runqueue_t *this_rq,
2186 struct sched_domain *sd, enum idle_type idle)
2188 struct sched_group *group;
2189 runqueue_t *busiest;
2190 unsigned long imbalance;
2191 int nr_moved, all_pinned = 0;
2192 int active_balance = 0;
2195 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER)
2198 schedstat_inc(sd, lb_cnt[idle]);
2200 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
2202 schedstat_inc(sd, lb_nobusyg[idle]);
2206 busiest = find_busiest_queue(group, idle);
2208 schedstat_inc(sd, lb_nobusyq[idle]);
2212 BUG_ON(busiest == this_rq);
2214 schedstat_add(sd, lb_imbalance[idle], imbalance);
2217 if (busiest->nr_running > 1) {
2219 * Attempt to move tasks. If find_busiest_group has found
2220 * an imbalance but busiest->nr_running <= 1, the group is
2221 * still unbalanced. nr_moved simply stays zero, so it is
2222 * correctly treated as an imbalance.
2224 double_rq_lock(this_rq, busiest);
2225 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2226 imbalance, sd, idle, &all_pinned);
2227 double_rq_unlock(this_rq, busiest);
2229 /* All tasks on this runqueue were pinned by CPU affinity */
2230 if (unlikely(all_pinned))
2235 schedstat_inc(sd, lb_failed[idle]);
2236 sd->nr_balance_failed++;
2238 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2240 spin_lock(&busiest->lock);
2242 /* don't kick the migration_thread, if the curr
2243 * task on busiest cpu can't be moved to this_cpu
2245 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2246 spin_unlock(&busiest->lock);
2248 goto out_one_pinned;
2251 if (!busiest->active_balance) {
2252 busiest->active_balance = 1;
2253 busiest->push_cpu = this_cpu;
2256 spin_unlock(&busiest->lock);
2258 wake_up_process(busiest->migration_thread);
2261 * We've kicked active balancing, reset the failure
2264 sd->nr_balance_failed = sd->cache_nice_tries+1;
2267 sd->nr_balance_failed = 0;
2269 if (likely(!active_balance)) {
2270 /* We were unbalanced, so reset the balancing interval */
2271 sd->balance_interval = sd->min_interval;
2274 * If we've begun active balancing, start to back off. This
2275 * case may not be covered by the all_pinned logic if there
2276 * is only 1 task on the busy runqueue (because we don't call
2279 if (sd->balance_interval < sd->max_interval)
2280 sd->balance_interval *= 2;
2283 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2288 schedstat_inc(sd, lb_balanced[idle]);
2290 sd->nr_balance_failed = 0;
2293 /* tune up the balancing interval */
2294 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2295 (sd->balance_interval < sd->max_interval))
2296 sd->balance_interval *= 2;
2298 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2304 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2305 * tasks if there is an imbalance.
2307 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2308 * this_rq is locked.
2310 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2311 struct sched_domain *sd)
2313 struct sched_group *group;
2314 runqueue_t *busiest = NULL;
2315 unsigned long imbalance;
2319 if (sd->flags & SD_SHARE_CPUPOWER)
2322 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2323 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
2325 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2329 busiest = find_busiest_queue(group, NEWLY_IDLE);
2331 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2335 BUG_ON(busiest == this_rq);
2337 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2340 if (busiest->nr_running > 1) {
2341 /* Attempt to move tasks */
2342 double_lock_balance(this_rq, busiest);
2343 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2344 imbalance, sd, NEWLY_IDLE, NULL);
2345 spin_unlock(&busiest->lock);
2349 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2350 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2353 sd->nr_balance_failed = 0;
2358 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2359 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2361 sd->nr_balance_failed = 0;
2366 * idle_balance is called by schedule() if this_cpu is about to become
2367 * idle. Attempts to pull tasks from other CPUs.
2369 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2371 struct sched_domain *sd;
2373 for_each_domain(this_cpu, sd) {
2374 if (sd->flags & SD_BALANCE_NEWIDLE) {
2375 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2376 /* We've pulled tasks over so stop searching */
2384 * active_load_balance is run by migration threads. It pushes running tasks
2385 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2386 * running on each physical CPU where possible, and avoids physical /
2387 * logical imbalances.
2389 * Called with busiest_rq locked.
2391 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2393 struct sched_domain *sd;
2394 runqueue_t *target_rq;
2395 int target_cpu = busiest_rq->push_cpu;
2397 if (busiest_rq->nr_running <= 1)
2398 /* no task to move */
2401 target_rq = cpu_rq(target_cpu);
2404 * This condition is "impossible", if it occurs
2405 * we need to fix it. Originally reported by
2406 * Bjorn Helgaas on a 128-cpu setup.
2408 BUG_ON(busiest_rq == target_rq);
2410 /* move a task from busiest_rq to target_rq */
2411 double_lock_balance(busiest_rq, target_rq);
2413 /* Search for an sd spanning us and the target CPU. */
2414 for_each_domain(target_cpu, sd)
2415 if ((sd->flags & SD_LOAD_BALANCE) &&
2416 cpu_isset(busiest_cpu, sd->span))
2419 if (unlikely(sd == NULL))
2422 schedstat_inc(sd, alb_cnt);
2424 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
2425 schedstat_inc(sd, alb_pushed);
2427 schedstat_inc(sd, alb_failed);
2429 spin_unlock(&target_rq->lock);
2433 * rebalance_tick will get called every timer tick, on every CPU.
2435 * It checks each scheduling domain to see if it is due to be balanced,
2436 * and initiates a balancing operation if so.
2438 * Balancing parameters are set up in arch_init_sched_domains.
2441 /* Don't have all balancing operations going off at once */
2442 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2444 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2445 enum idle_type idle)
2447 unsigned long old_load, this_load;
2448 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2449 struct sched_domain *sd;
2452 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2453 /* Update our load */
2454 for (i = 0; i < 3; i++) {
2455 unsigned long new_load = this_load;
2457 old_load = this_rq->cpu_load[i];
2459 * Round up the averaging division if load is increasing. This
2460 * prevents us from getting stuck on 9 if the load is 10, for
2463 if (new_load > old_load)
2464 new_load += scale-1;
2465 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2468 for_each_domain(this_cpu, sd) {
2469 unsigned long interval;
2471 if (!(sd->flags & SD_LOAD_BALANCE))
2474 interval = sd->balance_interval;
2475 if (idle != SCHED_IDLE)
2476 interval *= sd->busy_factor;
2478 /* scale ms to jiffies */
2479 interval = msecs_to_jiffies(interval);
2480 if (unlikely(!interval))
2483 if (j - sd->last_balance >= interval) {
2484 if (load_balance(this_cpu, this_rq, sd, idle)) {
2486 * We've pulled tasks over so either we're no
2487 * longer idle, or one of our SMT siblings is
2492 sd->last_balance += interval;
2498 * on UP we do not need to balance between CPUs:
2500 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2503 static inline void idle_balance(int cpu, runqueue_t *rq)
2508 static inline int wake_priority_sleeper(runqueue_t *rq)
2511 #ifdef CONFIG_SCHED_SMT
2512 spin_lock(&rq->lock);
2514 * If an SMT sibling task has been put to sleep for priority
2515 * reasons reschedule the idle task to see if it can now run.
2517 if (rq->nr_running) {
2518 resched_task(rq->idle);
2521 spin_unlock(&rq->lock);
2526 DEFINE_PER_CPU(struct kernel_stat, kstat);
2528 EXPORT_PER_CPU_SYMBOL(kstat);
2531 * This is called on clock ticks and on context switches.
2532 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2534 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2535 unsigned long long now)
2537 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2538 p->sched_time += now - last;
2542 * Return current->sched_time plus any more ns on the sched_clock
2543 * that have not yet been banked.
2545 unsigned long long current_sched_time(const task_t *tsk)
2547 unsigned long long ns;
2548 unsigned long flags;
2549 local_irq_save(flags);
2550 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2551 ns = tsk->sched_time + (sched_clock() - ns);
2552 local_irq_restore(flags);
2557 * We place interactive tasks back into the active array, if possible.
2559 * To guarantee that this does not starve expired tasks we ignore the
2560 * interactivity of a task if the first expired task had to wait more
2561 * than a 'reasonable' amount of time. This deadline timeout is
2562 * load-dependent, as the frequency of array switched decreases with
2563 * increasing number of running tasks. We also ignore the interactivity
2564 * if a better static_prio task has expired:
2566 #define EXPIRED_STARVING(rq) \
2567 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2568 (jiffies - (rq)->expired_timestamp >= \
2569 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2570 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2573 * Account user cpu time to a process.
2574 * @p: the process that the cpu time gets accounted to
2575 * @hardirq_offset: the offset to subtract from hardirq_count()
2576 * @cputime: the cpu time spent in user space since the last update
2578 void account_user_time(struct task_struct *p, cputime_t cputime)
2580 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2583 p->utime = cputime_add(p->utime, cputime);
2585 /* Add user time to cpustat. */
2586 tmp = cputime_to_cputime64(cputime);
2587 if (TASK_NICE(p) > 0)
2588 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2590 cpustat->user = cputime64_add(cpustat->user, tmp);
2594 * Account system cpu time to a process.
2595 * @p: the process that the cpu time gets accounted to
2596 * @hardirq_offset: the offset to subtract from hardirq_count()
2597 * @cputime: the cpu time spent in kernel space since the last update
2599 void account_system_time(struct task_struct *p, int hardirq_offset,
2602 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2603 runqueue_t *rq = this_rq();
2606 p->stime = cputime_add(p->stime, cputime);
2608 /* Add system time to cpustat. */
2609 tmp = cputime_to_cputime64(cputime);
2610 if (hardirq_count() - hardirq_offset)
2611 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2612 else if (softirq_count())
2613 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2614 else if (p != rq->idle)
2615 cpustat->system = cputime64_add(cpustat->system, tmp);
2616 else if (atomic_read(&rq->nr_iowait) > 0)
2617 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2619 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2620 /* Account for system time used */
2621 acct_update_integrals(p);
2625 * Account for involuntary wait time.
2626 * @p: the process from which the cpu time has been stolen
2627 * @steal: the cpu time spent in involuntary wait
2629 void account_steal_time(struct task_struct *p, cputime_t steal)
2631 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2632 cputime64_t tmp = cputime_to_cputime64(steal);
2633 runqueue_t *rq = this_rq();
2635 if (p == rq->idle) {
2636 p->stime = cputime_add(p->stime, steal);
2637 if (atomic_read(&rq->nr_iowait) > 0)
2638 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2640 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2642 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2646 * This function gets called by the timer code, with HZ frequency.
2647 * We call it with interrupts disabled.
2649 * It also gets called by the fork code, when changing the parent's
2652 void scheduler_tick(void)
2654 int cpu = smp_processor_id();
2655 runqueue_t *rq = this_rq();
2656 task_t *p = current;
2657 unsigned long long now = sched_clock();
2659 update_cpu_clock(p, rq, now);
2661 rq->timestamp_last_tick = now;
2663 if (p == rq->idle) {
2664 if (wake_priority_sleeper(rq))
2666 rebalance_tick(cpu, rq, SCHED_IDLE);
2670 /* Task might have expired already, but not scheduled off yet */
2671 if (p->array != rq->active) {
2672 set_tsk_need_resched(p);
2675 spin_lock(&rq->lock);
2677 * The task was running during this tick - update the
2678 * time slice counter. Note: we do not update a thread's
2679 * priority until it either goes to sleep or uses up its
2680 * timeslice. This makes it possible for interactive tasks
2681 * to use up their timeslices at their highest priority levels.
2685 * RR tasks need a special form of timeslice management.
2686 * FIFO tasks have no timeslices.
2688 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2689 p->time_slice = task_timeslice(p);
2690 p->first_time_slice = 0;
2691 set_tsk_need_resched(p);
2693 /* put it at the end of the queue: */
2694 requeue_task(p, rq->active);
2698 if (!--p->time_slice) {
2699 dequeue_task(p, rq->active);
2700 set_tsk_need_resched(p);
2701 p->prio = effective_prio(p);
2702 p->time_slice = task_timeslice(p);
2703 p->first_time_slice = 0;
2705 if (!rq->expired_timestamp)
2706 rq->expired_timestamp = jiffies;
2707 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2708 enqueue_task(p, rq->expired);
2709 if (p->static_prio < rq->best_expired_prio)
2710 rq->best_expired_prio = p->static_prio;
2712 enqueue_task(p, rq->active);
2715 * Prevent a too long timeslice allowing a task to monopolize
2716 * the CPU. We do this by splitting up the timeslice into
2719 * Note: this does not mean the task's timeslices expire or
2720 * get lost in any way, they just might be preempted by
2721 * another task of equal priority. (one with higher
2722 * priority would have preempted this task already.) We
2723 * requeue this task to the end of the list on this priority
2724 * level, which is in essence a round-robin of tasks with
2727 * This only applies to tasks in the interactive
2728 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2730 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2731 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2732 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2733 (p->array == rq->active)) {
2735 requeue_task(p, rq->active);
2736 set_tsk_need_resched(p);
2740 spin_unlock(&rq->lock);
2742 rebalance_tick(cpu, rq, NOT_IDLE);
2745 #ifdef CONFIG_SCHED_SMT
2746 static inline void wakeup_busy_runqueue(runqueue_t *rq)
2748 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
2749 if (rq->curr == rq->idle && rq->nr_running)
2750 resched_task(rq->idle);
2753 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2755 struct sched_domain *tmp, *sd = NULL;
2756 cpumask_t sibling_map;
2759 for_each_domain(this_cpu, tmp)
2760 if (tmp->flags & SD_SHARE_CPUPOWER)
2767 * Unlock the current runqueue because we have to lock in
2768 * CPU order to avoid deadlocks. Caller knows that we might
2769 * unlock. We keep IRQs disabled.
2771 spin_unlock(&this_rq->lock);
2773 sibling_map = sd->span;
2775 for_each_cpu_mask(i, sibling_map)
2776 spin_lock(&cpu_rq(i)->lock);
2778 * We clear this CPU from the mask. This both simplifies the
2779 * inner loop and keps this_rq locked when we exit:
2781 cpu_clear(this_cpu, sibling_map);
2783 for_each_cpu_mask(i, sibling_map) {
2784 runqueue_t *smt_rq = cpu_rq(i);
2786 wakeup_busy_runqueue(smt_rq);
2789 for_each_cpu_mask(i, sibling_map)
2790 spin_unlock(&cpu_rq(i)->lock);
2792 * We exit with this_cpu's rq still held and IRQs
2798 * number of 'lost' timeslices this task wont be able to fully
2799 * utilize, if another task runs on a sibling. This models the
2800 * slowdown effect of other tasks running on siblings:
2802 static inline unsigned long smt_slice(task_t *p, struct sched_domain *sd)
2804 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
2807 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2809 struct sched_domain *tmp, *sd = NULL;
2810 cpumask_t sibling_map;
2811 prio_array_t *array;
2815 for_each_domain(this_cpu, tmp)
2816 if (tmp->flags & SD_SHARE_CPUPOWER)
2823 * The same locking rules and details apply as for
2824 * wake_sleeping_dependent():
2826 spin_unlock(&this_rq->lock);
2827 sibling_map = sd->span;
2828 for_each_cpu_mask(i, sibling_map)
2829 spin_lock(&cpu_rq(i)->lock);
2830 cpu_clear(this_cpu, sibling_map);
2833 * Establish next task to be run - it might have gone away because
2834 * we released the runqueue lock above:
2836 if (!this_rq->nr_running)
2838 array = this_rq->active;
2839 if (!array->nr_active)
2840 array = this_rq->expired;
2841 BUG_ON(!array->nr_active);
2843 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2846 for_each_cpu_mask(i, sibling_map) {
2847 runqueue_t *smt_rq = cpu_rq(i);
2848 task_t *smt_curr = smt_rq->curr;
2850 /* Kernel threads do not participate in dependent sleeping */
2851 if (!p->mm || !smt_curr->mm || rt_task(p))
2852 goto check_smt_task;
2855 * If a user task with lower static priority than the
2856 * running task on the SMT sibling is trying to schedule,
2857 * delay it till there is proportionately less timeslice
2858 * left of the sibling task to prevent a lower priority
2859 * task from using an unfair proportion of the
2860 * physical cpu's resources. -ck
2862 if (rt_task(smt_curr)) {
2864 * With real time tasks we run non-rt tasks only
2865 * per_cpu_gain% of the time.
2867 if ((jiffies % DEF_TIMESLICE) >
2868 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2871 if (smt_curr->static_prio < p->static_prio &&
2872 !TASK_PREEMPTS_CURR(p, smt_rq) &&
2873 smt_slice(smt_curr, sd) > task_timeslice(p))
2877 if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
2881 wakeup_busy_runqueue(smt_rq);
2886 * Reschedule a lower priority task on the SMT sibling for
2887 * it to be put to sleep, or wake it up if it has been put to
2888 * sleep for priority reasons to see if it should run now.
2891 if ((jiffies % DEF_TIMESLICE) >
2892 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2893 resched_task(smt_curr);
2895 if (TASK_PREEMPTS_CURR(p, smt_rq) &&
2896 smt_slice(p, sd) > task_timeslice(smt_curr))
2897 resched_task(smt_curr);
2899 wakeup_busy_runqueue(smt_rq);
2903 for_each_cpu_mask(i, sibling_map)
2904 spin_unlock(&cpu_rq(i)->lock);
2908 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2912 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2918 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2920 void fastcall add_preempt_count(int val)
2925 BUG_ON((preempt_count() < 0));
2926 preempt_count() += val;
2928 * Spinlock count overflowing soon?
2930 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2932 EXPORT_SYMBOL(add_preempt_count);
2934 void fastcall sub_preempt_count(int val)
2939 BUG_ON(val > preempt_count());
2941 * Is the spinlock portion underflowing?
2943 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2944 preempt_count() -= val;
2946 EXPORT_SYMBOL(sub_preempt_count);
2951 * schedule() is the main scheduler function.
2953 asmlinkage void __sched schedule(void)
2956 task_t *prev, *next;
2958 prio_array_t *array;
2959 struct list_head *queue;
2960 unsigned long long now;
2961 unsigned long run_time;
2962 int cpu, idx, new_prio;
2965 * Test if we are atomic. Since do_exit() needs to call into
2966 * schedule() atomically, we ignore that path for now.
2967 * Otherwise, whine if we are scheduling when we should not be.
2969 if (likely(!current->exit_state)) {
2970 if (unlikely(in_atomic())) {
2971 printk(KERN_ERR "scheduling while atomic: "
2973 current->comm, preempt_count(), current->pid);
2977 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2982 release_kernel_lock(prev);
2983 need_resched_nonpreemptible:
2987 * The idle thread is not allowed to schedule!
2988 * Remove this check after it has been exercised a bit.
2990 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2991 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2995 schedstat_inc(rq, sched_cnt);
2996 now = sched_clock();
2997 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
2998 run_time = now - prev->timestamp;
2999 if (unlikely((long long)(now - prev->timestamp) < 0))
3002 run_time = NS_MAX_SLEEP_AVG;
3005 * Tasks charged proportionately less run_time at high sleep_avg to
3006 * delay them losing their interactive status
3008 run_time /= (CURRENT_BONUS(prev) ? : 1);
3010 spin_lock_irq(&rq->lock);
3012 if (unlikely(prev->flags & PF_DEAD))
3013 prev->state = EXIT_DEAD;
3015 switch_count = &prev->nivcsw;
3016 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3017 switch_count = &prev->nvcsw;
3018 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3019 unlikely(signal_pending(prev))))
3020 prev->state = TASK_RUNNING;
3022 if (prev->state == TASK_UNINTERRUPTIBLE)
3023 rq->nr_uninterruptible++;
3024 deactivate_task(prev, rq);
3028 cpu = smp_processor_id();
3029 if (unlikely(!rq->nr_running)) {
3031 idle_balance(cpu, rq);
3032 if (!rq->nr_running) {
3034 rq->expired_timestamp = 0;
3035 wake_sleeping_dependent(cpu, rq);
3037 * wake_sleeping_dependent() might have released
3038 * the runqueue, so break out if we got new
3041 if (!rq->nr_running)
3045 if (dependent_sleeper(cpu, rq)) {
3050 * dependent_sleeper() releases and reacquires the runqueue
3051 * lock, hence go into the idle loop if the rq went
3054 if (unlikely(!rq->nr_running))
3059 if (unlikely(!array->nr_active)) {
3061 * Switch the active and expired arrays.
3063 schedstat_inc(rq, sched_switch);
3064 rq->active = rq->expired;
3065 rq->expired = array;
3067 rq->expired_timestamp = 0;
3068 rq->best_expired_prio = MAX_PRIO;
3071 idx = sched_find_first_bit(array->bitmap);
3072 queue = array->queue + idx;
3073 next = list_entry(queue->next, task_t, run_list);
3075 if (!rt_task(next) && next->activated > 0) {
3076 unsigned long long delta = now - next->timestamp;
3077 if (unlikely((long long)(now - next->timestamp) < 0))
3080 if (next->activated == 1)
3081 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3083 array = next->array;
3084 new_prio = recalc_task_prio(next, next->timestamp + delta);
3086 if (unlikely(next->prio != new_prio)) {
3087 dequeue_task(next, array);
3088 next->prio = new_prio;
3089 enqueue_task(next, array);
3091 requeue_task(next, array);
3093 next->activated = 0;
3095 if (next == rq->idle)
3096 schedstat_inc(rq, sched_goidle);
3098 prefetch_stack(next);
3099 clear_tsk_need_resched(prev);
3100 rcu_qsctr_inc(task_cpu(prev));
3102 update_cpu_clock(prev, rq, now);
3104 prev->sleep_avg -= run_time;
3105 if ((long)prev->sleep_avg <= 0)
3106 prev->sleep_avg = 0;
3107 prev->timestamp = prev->last_ran = now;
3109 sched_info_switch(prev, next);
3110 if (likely(prev != next)) {
3111 next->timestamp = now;
3116 prepare_task_switch(rq, next);
3117 prev = context_switch(rq, prev, next);
3120 * this_rq must be evaluated again because prev may have moved
3121 * CPUs since it called schedule(), thus the 'rq' on its stack
3122 * frame will be invalid.
3124 finish_task_switch(this_rq(), prev);
3126 spin_unlock_irq(&rq->lock);
3129 if (unlikely(reacquire_kernel_lock(prev) < 0))
3130 goto need_resched_nonpreemptible;
3131 preempt_enable_no_resched();
3132 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3136 EXPORT_SYMBOL(schedule);
3138 #ifdef CONFIG_PREEMPT
3140 * this is is the entry point to schedule() from in-kernel preemption
3141 * off of preempt_enable. Kernel preemptions off return from interrupt
3142 * occur there and call schedule directly.
3144 asmlinkage void __sched preempt_schedule(void)
3146 struct thread_info *ti = current_thread_info();
3147 #ifdef CONFIG_PREEMPT_BKL
3148 struct task_struct *task = current;
3149 int saved_lock_depth;
3152 * If there is a non-zero preempt_count or interrupts are disabled,
3153 * we do not want to preempt the current task. Just return..
3155 if (unlikely(ti->preempt_count || irqs_disabled()))
3159 add_preempt_count(PREEMPT_ACTIVE);
3161 * We keep the big kernel semaphore locked, but we
3162 * clear ->lock_depth so that schedule() doesnt
3163 * auto-release the semaphore:
3165 #ifdef CONFIG_PREEMPT_BKL
3166 saved_lock_depth = task->lock_depth;
3167 task->lock_depth = -1;
3170 #ifdef CONFIG_PREEMPT_BKL
3171 task->lock_depth = saved_lock_depth;
3173 sub_preempt_count(PREEMPT_ACTIVE);
3175 /* we could miss a preemption opportunity between schedule and now */
3177 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3181 EXPORT_SYMBOL(preempt_schedule);
3184 * this is is the entry point to schedule() from kernel preemption
3185 * off of irq context.
3186 * Note, that this is called and return with irqs disabled. This will
3187 * protect us against recursive calling from irq.
3189 asmlinkage void __sched preempt_schedule_irq(void)
3191 struct thread_info *ti = current_thread_info();
3192 #ifdef CONFIG_PREEMPT_BKL
3193 struct task_struct *task = current;
3194 int saved_lock_depth;
3196 /* Catch callers which need to be fixed*/
3197 BUG_ON(ti->preempt_count || !irqs_disabled());
3200 add_preempt_count(PREEMPT_ACTIVE);
3202 * We keep the big kernel semaphore locked, but we
3203 * clear ->lock_depth so that schedule() doesnt
3204 * auto-release the semaphore:
3206 #ifdef CONFIG_PREEMPT_BKL
3207 saved_lock_depth = task->lock_depth;
3208 task->lock_depth = -1;
3212 local_irq_disable();
3213 #ifdef CONFIG_PREEMPT_BKL
3214 task->lock_depth = saved_lock_depth;
3216 sub_preempt_count(PREEMPT_ACTIVE);
3218 /* we could miss a preemption opportunity between schedule and now */
3220 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3224 #endif /* CONFIG_PREEMPT */
3226 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3229 task_t *p = curr->private;
3230 return try_to_wake_up(p, mode, sync);
3233 EXPORT_SYMBOL(default_wake_function);
3236 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3237 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3238 * number) then we wake all the non-exclusive tasks and one exclusive task.
3240 * There are circumstances in which we can try to wake a task which has already
3241 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3242 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3244 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3245 int nr_exclusive, int sync, void *key)
3247 struct list_head *tmp, *next;
3249 list_for_each_safe(tmp, next, &q->task_list) {
3252 curr = list_entry(tmp, wait_queue_t, task_list);
3253 flags = curr->flags;
3254 if (curr->func(curr, mode, sync, key) &&
3255 (flags & WQ_FLAG_EXCLUSIVE) &&
3262 * __wake_up - wake up threads blocked on a waitqueue.
3264 * @mode: which threads
3265 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3266 * @key: is directly passed to the wakeup function
3268 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3269 int nr_exclusive, void *key)
3271 unsigned long flags;
3273 spin_lock_irqsave(&q->lock, flags);
3274 __wake_up_common(q, mode, nr_exclusive, 0, key);
3275 spin_unlock_irqrestore(&q->lock, flags);
3278 EXPORT_SYMBOL(__wake_up);
3281 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3283 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3285 __wake_up_common(q, mode, 1, 0, NULL);
3289 * __wake_up_sync - wake up threads blocked on a waitqueue.
3291 * @mode: which threads
3292 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3294 * The sync wakeup differs that the waker knows that it will schedule
3295 * away soon, so while the target thread will be woken up, it will not
3296 * be migrated to another CPU - ie. the two threads are 'synchronized'
3297 * with each other. This can prevent needless bouncing between CPUs.
3299 * On UP it can prevent extra preemption.
3302 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3304 unsigned long flags;
3310 if (unlikely(!nr_exclusive))
3313 spin_lock_irqsave(&q->lock, flags);
3314 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3315 spin_unlock_irqrestore(&q->lock, flags);
3317 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3319 void fastcall complete(struct completion *x)
3321 unsigned long flags;
3323 spin_lock_irqsave(&x->wait.lock, flags);
3325 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3327 spin_unlock_irqrestore(&x->wait.lock, flags);
3329 EXPORT_SYMBOL(complete);
3331 void fastcall complete_all(struct completion *x)
3333 unsigned long flags;
3335 spin_lock_irqsave(&x->wait.lock, flags);
3336 x->done += UINT_MAX/2;
3337 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3339 spin_unlock_irqrestore(&x->wait.lock, flags);
3341 EXPORT_SYMBOL(complete_all);
3343 void fastcall __sched wait_for_completion(struct completion *x)
3346 spin_lock_irq(&x->wait.lock);
3348 DECLARE_WAITQUEUE(wait, current);
3350 wait.flags |= WQ_FLAG_EXCLUSIVE;
3351 __add_wait_queue_tail(&x->wait, &wait);
3353 __set_current_state(TASK_UNINTERRUPTIBLE);
3354 spin_unlock_irq(&x->wait.lock);
3356 spin_lock_irq(&x->wait.lock);
3358 __remove_wait_queue(&x->wait, &wait);
3361 spin_unlock_irq(&x->wait.lock);
3363 EXPORT_SYMBOL(wait_for_completion);
3365 unsigned long fastcall __sched
3366 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3370 spin_lock_irq(&x->wait.lock);
3372 DECLARE_WAITQUEUE(wait, current);
3374 wait.flags |= WQ_FLAG_EXCLUSIVE;
3375 __add_wait_queue_tail(&x->wait, &wait);
3377 __set_current_state(TASK_UNINTERRUPTIBLE);
3378 spin_unlock_irq(&x->wait.lock);
3379 timeout = schedule_timeout(timeout);
3380 spin_lock_irq(&x->wait.lock);
3382 __remove_wait_queue(&x->wait, &wait);
3386 __remove_wait_queue(&x->wait, &wait);
3390 spin_unlock_irq(&x->wait.lock);
3393 EXPORT_SYMBOL(wait_for_completion_timeout);
3395 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3401 spin_lock_irq(&x->wait.lock);
3403 DECLARE_WAITQUEUE(wait, current);
3405 wait.flags |= WQ_FLAG_EXCLUSIVE;
3406 __add_wait_queue_tail(&x->wait, &wait);
3408 if (signal_pending(current)) {
3410 __remove_wait_queue(&x->wait, &wait);
3413 __set_current_state(TASK_INTERRUPTIBLE);
3414 spin_unlock_irq(&x->wait.lock);
3416 spin_lock_irq(&x->wait.lock);
3418 __remove_wait_queue(&x->wait, &wait);
3422 spin_unlock_irq(&x->wait.lock);
3426 EXPORT_SYMBOL(wait_for_completion_interruptible);
3428 unsigned long fastcall __sched
3429 wait_for_completion_interruptible_timeout(struct completion *x,
3430 unsigned long timeout)
3434 spin_lock_irq(&x->wait.lock);
3436 DECLARE_WAITQUEUE(wait, current);
3438 wait.flags |= WQ_FLAG_EXCLUSIVE;
3439 __add_wait_queue_tail(&x->wait, &wait);
3441 if (signal_pending(current)) {
3442 timeout = -ERESTARTSYS;
3443 __remove_wait_queue(&x->wait, &wait);
3446 __set_current_state(TASK_INTERRUPTIBLE);
3447 spin_unlock_irq(&x->wait.lock);
3448 timeout = schedule_timeout(timeout);
3449 spin_lock_irq(&x->wait.lock);
3451 __remove_wait_queue(&x->wait, &wait);
3455 __remove_wait_queue(&x->wait, &wait);
3459 spin_unlock_irq(&x->wait.lock);
3462 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3465 #define SLEEP_ON_VAR \
3466 unsigned long flags; \
3467 wait_queue_t wait; \
3468 init_waitqueue_entry(&wait, current);
3470 #define SLEEP_ON_HEAD \
3471 spin_lock_irqsave(&q->lock,flags); \
3472 __add_wait_queue(q, &wait); \
3473 spin_unlock(&q->lock);
3475 #define SLEEP_ON_TAIL \
3476 spin_lock_irq(&q->lock); \
3477 __remove_wait_queue(q, &wait); \
3478 spin_unlock_irqrestore(&q->lock, flags);
3480 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3484 current->state = TASK_INTERRUPTIBLE;
3491 EXPORT_SYMBOL(interruptible_sleep_on);
3493 long fastcall __sched
3494 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3498 current->state = TASK_INTERRUPTIBLE;
3501 timeout = schedule_timeout(timeout);
3507 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3509 void fastcall __sched sleep_on(wait_queue_head_t *q)
3513 current->state = TASK_UNINTERRUPTIBLE;
3520 EXPORT_SYMBOL(sleep_on);
3522 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3526 current->state = TASK_UNINTERRUPTIBLE;
3529 timeout = schedule_timeout(timeout);
3535 EXPORT_SYMBOL(sleep_on_timeout);
3537 void set_user_nice(task_t *p, long nice)
3539 unsigned long flags;
3540 prio_array_t *array;
3542 int old_prio, new_prio, delta;
3544 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3547 * We have to be careful, if called from sys_setpriority(),
3548 * the task might be in the middle of scheduling on another CPU.
3550 rq = task_rq_lock(p, &flags);
3552 * The RT priorities are set via sched_setscheduler(), but we still
3553 * allow the 'normal' nice value to be set - but as expected
3554 * it wont have any effect on scheduling until the task is
3558 p->static_prio = NICE_TO_PRIO(nice);
3563 dequeue_task(p, array);
3564 dec_prio_bias(rq, p->static_prio);
3568 new_prio = NICE_TO_PRIO(nice);
3569 delta = new_prio - old_prio;
3570 p->static_prio = NICE_TO_PRIO(nice);
3574 enqueue_task(p, array);
3575 inc_prio_bias(rq, p->static_prio);
3577 * If the task increased its priority or is running and
3578 * lowered its priority, then reschedule its CPU:
3580 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3581 resched_task(rq->curr);
3584 task_rq_unlock(rq, &flags);
3587 EXPORT_SYMBOL(set_user_nice);
3590 * can_nice - check if a task can reduce its nice value
3594 int can_nice(const task_t *p, const int nice)
3596 /* convert nice value [19,-20] to rlimit style value [1,40] */
3597 int nice_rlim = 20 - nice;
3598 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3599 capable(CAP_SYS_NICE));
3602 #ifdef __ARCH_WANT_SYS_NICE
3605 * sys_nice - change the priority of the current process.
3606 * @increment: priority increment
3608 * sys_setpriority is a more generic, but much slower function that
3609 * does similar things.
3611 asmlinkage long sys_nice(int increment)
3617 * Setpriority might change our priority at the same moment.
3618 * We don't have to worry. Conceptually one call occurs first
3619 * and we have a single winner.
3621 if (increment < -40)
3626 nice = PRIO_TO_NICE(current->static_prio) + increment;
3632 if (increment < 0 && !can_nice(current, nice))
3635 retval = security_task_setnice(current, nice);
3639 set_user_nice(current, nice);
3646 * task_prio - return the priority value of a given task.
3647 * @p: the task in question.
3649 * This is the priority value as seen by users in /proc.
3650 * RT tasks are offset by -200. Normal tasks are centered
3651 * around 0, value goes from -16 to +15.
3653 int task_prio(const task_t *p)
3655 return p->prio - MAX_RT_PRIO;
3659 * task_nice - return the nice value of a given task.
3660 * @p: the task in question.
3662 int task_nice(const task_t *p)
3664 return TASK_NICE(p);
3666 EXPORT_SYMBOL_GPL(task_nice);
3669 * idle_cpu - is a given cpu idle currently?
3670 * @cpu: the processor in question.
3672 int idle_cpu(int cpu)
3674 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3678 * idle_task - return the idle task for a given cpu.
3679 * @cpu: the processor in question.
3681 task_t *idle_task(int cpu)
3683 return cpu_rq(cpu)->idle;
3687 * find_process_by_pid - find a process with a matching PID value.
3688 * @pid: the pid in question.
3690 static inline task_t *find_process_by_pid(pid_t pid)
3692 return pid ? find_task_by_pid(pid) : current;
3695 /* Actually do priority change: must hold rq lock. */
3696 static void __setscheduler(struct task_struct *p, int policy, int prio)
3700 p->rt_priority = prio;
3701 if (policy != SCHED_NORMAL)
3702 p->prio = MAX_RT_PRIO-1 - p->rt_priority;
3704 p->prio = p->static_prio;
3708 * sched_setscheduler - change the scheduling policy and/or RT priority of
3710 * @p: the task in question.
3711 * @policy: new policy.
3712 * @param: structure containing the new RT priority.
3714 int sched_setscheduler(struct task_struct *p, int policy,
3715 struct sched_param *param)
3718 int oldprio, oldpolicy = -1;
3719 prio_array_t *array;
3720 unsigned long flags;
3724 /* double check policy once rq lock held */
3726 policy = oldpolicy = p->policy;
3727 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3728 policy != SCHED_NORMAL)
3731 * Valid priorities for SCHED_FIFO and SCHED_RR are
3732 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3734 if (param->sched_priority < 0 ||
3735 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
3736 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
3738 if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3742 * Allow unprivileged RT tasks to decrease priority:
3744 if (!capable(CAP_SYS_NICE)) {
3745 /* can't change policy */
3746 if (policy != p->policy &&
3747 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3749 /* can't increase priority */
3750 if (policy != SCHED_NORMAL &&
3751 param->sched_priority > p->rt_priority &&
3752 param->sched_priority >
3753 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3755 /* can't change other user's priorities */
3756 if ((current->euid != p->euid) &&
3757 (current->euid != p->uid))
3761 retval = security_task_setscheduler(p, policy, param);
3765 * To be able to change p->policy safely, the apropriate
3766 * runqueue lock must be held.
3768 rq = task_rq_lock(p, &flags);
3769 /* recheck policy now with rq lock held */
3770 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3771 policy = oldpolicy = -1;
3772 task_rq_unlock(rq, &flags);
3777 deactivate_task(p, rq);
3779 __setscheduler(p, policy, param->sched_priority);
3781 __activate_task(p, rq);
3783 * Reschedule if we are currently running on this runqueue and
3784 * our priority decreased, or if we are not currently running on
3785 * this runqueue and our priority is higher than the current's
3787 if (task_running(rq, p)) {
3788 if (p->prio > oldprio)
3789 resched_task(rq->curr);
3790 } else if (TASK_PREEMPTS_CURR(p, rq))
3791 resched_task(rq->curr);
3793 task_rq_unlock(rq, &flags);
3796 EXPORT_SYMBOL_GPL(sched_setscheduler);
3799 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3802 struct sched_param lparam;
3803 struct task_struct *p;
3805 if (!param || pid < 0)
3807 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3809 read_lock_irq(&tasklist_lock);
3810 p = find_process_by_pid(pid);
3812 read_unlock_irq(&tasklist_lock);
3815 retval = sched_setscheduler(p, policy, &lparam);
3816 read_unlock_irq(&tasklist_lock);
3821 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3822 * @pid: the pid in question.
3823 * @policy: new policy.
3824 * @param: structure containing the new RT priority.
3826 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3827 struct sched_param __user *param)
3829 return do_sched_setscheduler(pid, policy, param);
3833 * sys_sched_setparam - set/change the RT priority of a thread
3834 * @pid: the pid in question.
3835 * @param: structure containing the new RT priority.
3837 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3839 return do_sched_setscheduler(pid, -1, param);
3843 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3844 * @pid: the pid in question.
3846 asmlinkage long sys_sched_getscheduler(pid_t pid)
3848 int retval = -EINVAL;
3855 read_lock(&tasklist_lock);
3856 p = find_process_by_pid(pid);
3858 retval = security_task_getscheduler(p);
3862 read_unlock(&tasklist_lock);
3869 * sys_sched_getscheduler - get the RT priority of a thread
3870 * @pid: the pid in question.
3871 * @param: structure containing the RT priority.
3873 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3875 struct sched_param lp;
3876 int retval = -EINVAL;
3879 if (!param || pid < 0)
3882 read_lock(&tasklist_lock);
3883 p = find_process_by_pid(pid);
3888 retval = security_task_getscheduler(p);
3892 lp.sched_priority = p->rt_priority;
3893 read_unlock(&tasklist_lock);
3896 * This one might sleep, we cannot do it with a spinlock held ...
3898 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3904 read_unlock(&tasklist_lock);
3908 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3912 cpumask_t cpus_allowed;
3915 read_lock(&tasklist_lock);
3917 p = find_process_by_pid(pid);
3919 read_unlock(&tasklist_lock);
3920 unlock_cpu_hotplug();
3925 * It is not safe to call set_cpus_allowed with the
3926 * tasklist_lock held. We will bump the task_struct's
3927 * usage count and then drop tasklist_lock.
3930 read_unlock(&tasklist_lock);
3933 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3934 !capable(CAP_SYS_NICE))
3937 cpus_allowed = cpuset_cpus_allowed(p);
3938 cpus_and(new_mask, new_mask, cpus_allowed);
3939 retval = set_cpus_allowed(p, new_mask);
3943 unlock_cpu_hotplug();
3947 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3948 cpumask_t *new_mask)
3950 if (len < sizeof(cpumask_t)) {
3951 memset(new_mask, 0, sizeof(cpumask_t));
3952 } else if (len > sizeof(cpumask_t)) {
3953 len = sizeof(cpumask_t);
3955 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3959 * sys_sched_setaffinity - set the cpu affinity of a process
3960 * @pid: pid of the process
3961 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3962 * @user_mask_ptr: user-space pointer to the new cpu mask
3964 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3965 unsigned long __user *user_mask_ptr)
3970 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3974 return sched_setaffinity(pid, new_mask);
3978 * Represents all cpu's present in the system
3979 * In systems capable of hotplug, this map could dynamically grow
3980 * as new cpu's are detected in the system via any platform specific
3981 * method, such as ACPI for e.g.
3984 cpumask_t cpu_present_map __read_mostly;
3985 EXPORT_SYMBOL(cpu_present_map);
3988 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
3989 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
3992 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3998 read_lock(&tasklist_lock);
4001 p = find_process_by_pid(pid);
4006 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
4009 read_unlock(&tasklist_lock);
4010 unlock_cpu_hotplug();
4018 * sys_sched_getaffinity - get the cpu affinity of a process
4019 * @pid: pid of the process
4020 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4021 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4023 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4024 unsigned long __user *user_mask_ptr)
4029 if (len < sizeof(cpumask_t))
4032 ret = sched_getaffinity(pid, &mask);
4036 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4039 return sizeof(cpumask_t);
4043 * sys_sched_yield - yield the current processor to other threads.
4045 * this function yields the current CPU by moving the calling thread
4046 * to the expired array. If there are no other threads running on this
4047 * CPU then this function will return.
4049 asmlinkage long sys_sched_yield(void)
4051 runqueue_t *rq = this_rq_lock();
4052 prio_array_t *array = current->array;
4053 prio_array_t *target = rq->expired;
4055 schedstat_inc(rq, yld_cnt);
4057 * We implement yielding by moving the task into the expired
4060 * (special rule: RT tasks will just roundrobin in the active
4063 if (rt_task(current))
4064 target = rq->active;
4066 if (array->nr_active == 1) {
4067 schedstat_inc(rq, yld_act_empty);
4068 if (!rq->expired->nr_active)
4069 schedstat_inc(rq, yld_both_empty);
4070 } else if (!rq->expired->nr_active)
4071 schedstat_inc(rq, yld_exp_empty);
4073 if (array != target) {
4074 dequeue_task(current, array);
4075 enqueue_task(current, target);
4078 * requeue_task is cheaper so perform that if possible.
4080 requeue_task(current, array);
4083 * Since we are going to call schedule() anyway, there's
4084 * no need to preempt or enable interrupts:
4086 __release(rq->lock);
4087 _raw_spin_unlock(&rq->lock);
4088 preempt_enable_no_resched();
4095 static inline void __cond_resched(void)
4098 * The BKS might be reacquired before we have dropped
4099 * PREEMPT_ACTIVE, which could trigger a second
4100 * cond_resched() call.
4102 if (unlikely(preempt_count()))
4105 add_preempt_count(PREEMPT_ACTIVE);
4107 sub_preempt_count(PREEMPT_ACTIVE);
4108 } while (need_resched());
4111 int __sched cond_resched(void)
4113 if (need_resched()) {
4120 EXPORT_SYMBOL(cond_resched);
4123 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4124 * call schedule, and on return reacquire the lock.
4126 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4127 * operations here to prevent schedule() from being called twice (once via
4128 * spin_unlock(), once by hand).
4130 int cond_resched_lock(spinlock_t *lock)
4134 if (need_lockbreak(lock)) {
4140 if (need_resched()) {
4141 _raw_spin_unlock(lock);
4142 preempt_enable_no_resched();
4150 EXPORT_SYMBOL(cond_resched_lock);
4152 int __sched cond_resched_softirq(void)
4154 BUG_ON(!in_softirq());
4156 if (need_resched()) {
4157 __local_bh_enable();
4165 EXPORT_SYMBOL(cond_resched_softirq);
4169 * yield - yield the current processor to other threads.
4171 * this is a shortcut for kernel-space yielding - it marks the
4172 * thread runnable and calls sys_sched_yield().
4174 void __sched yield(void)
4176 set_current_state(TASK_RUNNING);
4180 EXPORT_SYMBOL(yield);
4183 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4184 * that process accounting knows that this is a task in IO wait state.
4186 * But don't do that if it is a deliberate, throttling IO wait (this task
4187 * has set its backing_dev_info: the queue against which it should throttle)
4189 void __sched io_schedule(void)
4191 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4193 atomic_inc(&rq->nr_iowait);
4195 atomic_dec(&rq->nr_iowait);
4198 EXPORT_SYMBOL(io_schedule);
4200 long __sched io_schedule_timeout(long timeout)
4202 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4205 atomic_inc(&rq->nr_iowait);
4206 ret = schedule_timeout(timeout);
4207 atomic_dec(&rq->nr_iowait);
4212 * sys_sched_get_priority_max - return maximum RT priority.
4213 * @policy: scheduling class.
4215 * this syscall returns the maximum rt_priority that can be used
4216 * by a given scheduling class.
4218 asmlinkage long sys_sched_get_priority_max(int policy)
4225 ret = MAX_USER_RT_PRIO-1;
4235 * sys_sched_get_priority_min - return minimum RT priority.
4236 * @policy: scheduling class.
4238 * this syscall returns the minimum rt_priority that can be used
4239 * by a given scheduling class.
4241 asmlinkage long sys_sched_get_priority_min(int policy)
4257 * sys_sched_rr_get_interval - return the default timeslice of a process.
4258 * @pid: pid of the process.
4259 * @interval: userspace pointer to the timeslice value.
4261 * this syscall writes the default timeslice value of a given process
4262 * into the user-space timespec buffer. A value of '0' means infinity.
4265 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4267 int retval = -EINVAL;
4275 read_lock(&tasklist_lock);
4276 p = find_process_by_pid(pid);
4280 retval = security_task_getscheduler(p);
4284 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4285 0 : task_timeslice(p), &t);
4286 read_unlock(&tasklist_lock);
4287 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4291 read_unlock(&tasklist_lock);
4295 static inline struct task_struct *eldest_child(struct task_struct *p)
4297 if (list_empty(&p->children)) return NULL;
4298 return list_entry(p->children.next,struct task_struct,sibling);
4301 static inline struct task_struct *older_sibling(struct task_struct *p)
4303 if (p->sibling.prev==&p->parent->children) return NULL;
4304 return list_entry(p->sibling.prev,struct task_struct,sibling);
4307 static inline struct task_struct *younger_sibling(struct task_struct *p)
4309 if (p->sibling.next==&p->parent->children) return NULL;
4310 return list_entry(p->sibling.next,struct task_struct,sibling);
4313 static void show_task(task_t *p)
4317 unsigned long free = 0;
4318 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4320 printk("%-13.13s ", p->comm);
4321 state = p->state ? __ffs(p->state) + 1 : 0;
4322 if (state < ARRAY_SIZE(stat_nam))
4323 printk(stat_nam[state]);
4326 #if (BITS_PER_LONG == 32)
4327 if (state == TASK_RUNNING)
4328 printk(" running ");
4330 printk(" %08lX ", thread_saved_pc(p));
4332 if (state == TASK_RUNNING)
4333 printk(" running task ");
4335 printk(" %016lx ", thread_saved_pc(p));
4337 #ifdef CONFIG_DEBUG_STACK_USAGE
4339 unsigned long *n = end_of_stack(p);
4342 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4345 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4346 if ((relative = eldest_child(p)))
4347 printk("%5d ", relative->pid);
4350 if ((relative = younger_sibling(p)))
4351 printk("%7d", relative->pid);
4354 if ((relative = older_sibling(p)))
4355 printk(" %5d", relative->pid);
4359 printk(" (L-TLB)\n");
4361 printk(" (NOTLB)\n");
4363 if (state != TASK_RUNNING)
4364 show_stack(p, NULL);
4367 void show_state(void)
4371 #if (BITS_PER_LONG == 32)
4374 printk(" task PC pid father child younger older\n");
4378 printk(" task PC pid father child younger older\n");
4380 read_lock(&tasklist_lock);
4381 do_each_thread(g, p) {
4383 * reset the NMI-timeout, listing all files on a slow
4384 * console might take alot of time:
4386 touch_nmi_watchdog();
4388 } while_each_thread(g, p);
4390 read_unlock(&tasklist_lock);
4391 mutex_debug_show_all_locks();
4395 * init_idle - set up an idle thread for a given CPU
4396 * @idle: task in question
4397 * @cpu: cpu the idle task belongs to
4399 * NOTE: this function does not set the idle thread's NEED_RESCHED
4400 * flag, to make booting more robust.
4402 void __devinit init_idle(task_t *idle, int cpu)
4404 runqueue_t *rq = cpu_rq(cpu);
4405 unsigned long flags;
4407 idle->sleep_avg = 0;
4409 idle->prio = MAX_PRIO;
4410 idle->state = TASK_RUNNING;
4411 idle->cpus_allowed = cpumask_of_cpu(cpu);
4412 set_task_cpu(idle, cpu);
4414 spin_lock_irqsave(&rq->lock, flags);
4415 rq->curr = rq->idle = idle;
4416 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4419 spin_unlock_irqrestore(&rq->lock, flags);
4421 /* Set the preempt count _outside_ the spinlocks! */
4422 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4423 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4425 task_thread_info(idle)->preempt_count = 0;
4430 * In a system that switches off the HZ timer nohz_cpu_mask
4431 * indicates which cpus entered this state. This is used
4432 * in the rcu update to wait only for active cpus. For system
4433 * which do not switch off the HZ timer nohz_cpu_mask should
4434 * always be CPU_MASK_NONE.
4436 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4440 * This is how migration works:
4442 * 1) we queue a migration_req_t structure in the source CPU's
4443 * runqueue and wake up that CPU's migration thread.
4444 * 2) we down() the locked semaphore => thread blocks.
4445 * 3) migration thread wakes up (implicitly it forces the migrated
4446 * thread off the CPU)
4447 * 4) it gets the migration request and checks whether the migrated
4448 * task is still in the wrong runqueue.
4449 * 5) if it's in the wrong runqueue then the migration thread removes
4450 * it and puts it into the right queue.
4451 * 6) migration thread up()s the semaphore.
4452 * 7) we wake up and the migration is done.
4456 * Change a given task's CPU affinity. Migrate the thread to a
4457 * proper CPU and schedule it away if the CPU it's executing on
4458 * is removed from the allowed bitmask.
4460 * NOTE: the caller must have a valid reference to the task, the
4461 * task must not exit() & deallocate itself prematurely. The
4462 * call is not atomic; no spinlocks may be held.
4464 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4466 unsigned long flags;
4468 migration_req_t req;
4471 rq = task_rq_lock(p, &flags);
4472 if (!cpus_intersects(new_mask, cpu_online_map)) {
4477 p->cpus_allowed = new_mask;
4478 /* Can the task run on the task's current CPU? If so, we're done */
4479 if (cpu_isset(task_cpu(p), new_mask))
4482 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4483 /* Need help from migration thread: drop lock and wait. */
4484 task_rq_unlock(rq, &flags);
4485 wake_up_process(rq->migration_thread);
4486 wait_for_completion(&req.done);
4487 tlb_migrate_finish(p->mm);
4491 task_rq_unlock(rq, &flags);
4495 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4498 * Move (not current) task off this cpu, onto dest cpu. We're doing
4499 * this because either it can't run here any more (set_cpus_allowed()
4500 * away from this CPU, or CPU going down), or because we're
4501 * attempting to rebalance this task on exec (sched_exec).
4503 * So we race with normal scheduler movements, but that's OK, as long
4504 * as the task is no longer on this CPU.
4506 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4508 runqueue_t *rq_dest, *rq_src;
4510 if (unlikely(cpu_is_offline(dest_cpu)))
4513 rq_src = cpu_rq(src_cpu);
4514 rq_dest = cpu_rq(dest_cpu);
4516 double_rq_lock(rq_src, rq_dest);
4517 /* Already moved. */
4518 if (task_cpu(p) != src_cpu)
4520 /* Affinity changed (again). */
4521 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4524 set_task_cpu(p, dest_cpu);
4527 * Sync timestamp with rq_dest's before activating.
4528 * The same thing could be achieved by doing this step
4529 * afterwards, and pretending it was a local activate.
4530 * This way is cleaner and logically correct.
4532 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4533 + rq_dest->timestamp_last_tick;
4534 deactivate_task(p, rq_src);
4535 activate_task(p, rq_dest, 0);
4536 if (TASK_PREEMPTS_CURR(p, rq_dest))
4537 resched_task(rq_dest->curr);
4541 double_rq_unlock(rq_src, rq_dest);
4545 * migration_thread - this is a highprio system thread that performs
4546 * thread migration by bumping thread off CPU then 'pushing' onto
4549 static int migration_thread(void *data)
4552 int cpu = (long)data;
4555 BUG_ON(rq->migration_thread != current);
4557 set_current_state(TASK_INTERRUPTIBLE);
4558 while (!kthread_should_stop()) {
4559 struct list_head *head;
4560 migration_req_t *req;
4564 spin_lock_irq(&rq->lock);
4566 if (cpu_is_offline(cpu)) {
4567 spin_unlock_irq(&rq->lock);
4571 if (rq->active_balance) {
4572 active_load_balance(rq, cpu);
4573 rq->active_balance = 0;
4576 head = &rq->migration_queue;
4578 if (list_empty(head)) {
4579 spin_unlock_irq(&rq->lock);
4581 set_current_state(TASK_INTERRUPTIBLE);
4584 req = list_entry(head->next, migration_req_t, list);
4585 list_del_init(head->next);
4587 spin_unlock(&rq->lock);
4588 __migrate_task(req->task, cpu, req->dest_cpu);
4591 complete(&req->done);
4593 __set_current_state(TASK_RUNNING);
4597 /* Wait for kthread_stop */
4598 set_current_state(TASK_INTERRUPTIBLE);
4599 while (!kthread_should_stop()) {
4601 set_current_state(TASK_INTERRUPTIBLE);
4603 __set_current_state(TASK_RUNNING);
4607 #ifdef CONFIG_HOTPLUG_CPU
4608 /* Figure out where task on dead CPU should go, use force if neccessary. */
4609 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4615 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4616 cpus_and(mask, mask, tsk->cpus_allowed);
4617 dest_cpu = any_online_cpu(mask);
4619 /* On any allowed CPU? */
4620 if (dest_cpu == NR_CPUS)
4621 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4623 /* No more Mr. Nice Guy. */
4624 if (dest_cpu == NR_CPUS) {
4625 cpus_setall(tsk->cpus_allowed);
4626 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4629 * Don't tell them about moving exiting tasks or
4630 * kernel threads (both mm NULL), since they never
4633 if (tsk->mm && printk_ratelimit())
4634 printk(KERN_INFO "process %d (%s) no "
4635 "longer affine to cpu%d\n",
4636 tsk->pid, tsk->comm, dead_cpu);
4638 __migrate_task(tsk, dead_cpu, dest_cpu);
4642 * While a dead CPU has no uninterruptible tasks queued at this point,
4643 * it might still have a nonzero ->nr_uninterruptible counter, because
4644 * for performance reasons the counter is not stricly tracking tasks to
4645 * their home CPUs. So we just add the counter to another CPU's counter,
4646 * to keep the global sum constant after CPU-down:
4648 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4650 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4651 unsigned long flags;
4653 local_irq_save(flags);
4654 double_rq_lock(rq_src, rq_dest);
4655 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4656 rq_src->nr_uninterruptible = 0;
4657 double_rq_unlock(rq_src, rq_dest);
4658 local_irq_restore(flags);
4661 /* Run through task list and migrate tasks from the dead cpu. */
4662 static void migrate_live_tasks(int src_cpu)
4664 struct task_struct *tsk, *t;
4666 write_lock_irq(&tasklist_lock);
4668 do_each_thread(t, tsk) {
4672 if (task_cpu(tsk) == src_cpu)
4673 move_task_off_dead_cpu(src_cpu, tsk);
4674 } while_each_thread(t, tsk);
4676 write_unlock_irq(&tasklist_lock);
4679 /* Schedules idle task to be the next runnable task on current CPU.
4680 * It does so by boosting its priority to highest possible and adding it to
4681 * the _front_ of runqueue. Used by CPU offline code.
4683 void sched_idle_next(void)
4685 int cpu = smp_processor_id();
4686 runqueue_t *rq = this_rq();
4687 struct task_struct *p = rq->idle;
4688 unsigned long flags;
4690 /* cpu has to be offline */
4691 BUG_ON(cpu_online(cpu));
4693 /* Strictly not necessary since rest of the CPUs are stopped by now
4694 * and interrupts disabled on current cpu.
4696 spin_lock_irqsave(&rq->lock, flags);
4698 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4699 /* Add idle task to _front_ of it's priority queue */
4700 __activate_idle_task(p, rq);
4702 spin_unlock_irqrestore(&rq->lock, flags);
4705 /* Ensures that the idle task is using init_mm right before its cpu goes
4708 void idle_task_exit(void)
4710 struct mm_struct *mm = current->active_mm;
4712 BUG_ON(cpu_online(smp_processor_id()));
4715 switch_mm(mm, &init_mm, current);
4719 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4721 struct runqueue *rq = cpu_rq(dead_cpu);
4723 /* Must be exiting, otherwise would be on tasklist. */
4724 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4726 /* Cannot have done final schedule yet: would have vanished. */
4727 BUG_ON(tsk->flags & PF_DEAD);
4729 get_task_struct(tsk);
4732 * Drop lock around migration; if someone else moves it,
4733 * that's OK. No task can be added to this CPU, so iteration is
4736 spin_unlock_irq(&rq->lock);
4737 move_task_off_dead_cpu(dead_cpu, tsk);
4738 spin_lock_irq(&rq->lock);
4740 put_task_struct(tsk);
4743 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4744 static void migrate_dead_tasks(unsigned int dead_cpu)
4747 struct runqueue *rq = cpu_rq(dead_cpu);
4749 for (arr = 0; arr < 2; arr++) {
4750 for (i = 0; i < MAX_PRIO; i++) {
4751 struct list_head *list = &rq->arrays[arr].queue[i];
4752 while (!list_empty(list))
4753 migrate_dead(dead_cpu,
4754 list_entry(list->next, task_t,
4759 #endif /* CONFIG_HOTPLUG_CPU */
4762 * migration_call - callback that gets triggered when a CPU is added.
4763 * Here we can start up the necessary migration thread for the new CPU.
4765 static int migration_call(struct notifier_block *nfb, unsigned long action,
4768 int cpu = (long)hcpu;
4769 struct task_struct *p;
4770 struct runqueue *rq;
4771 unsigned long flags;
4774 case CPU_UP_PREPARE:
4775 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4778 p->flags |= PF_NOFREEZE;
4779 kthread_bind(p, cpu);
4780 /* Must be high prio: stop_machine expects to yield to it. */
4781 rq = task_rq_lock(p, &flags);
4782 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4783 task_rq_unlock(rq, &flags);
4784 cpu_rq(cpu)->migration_thread = p;
4787 /* Strictly unneccessary, as first user will wake it. */
4788 wake_up_process(cpu_rq(cpu)->migration_thread);
4790 #ifdef CONFIG_HOTPLUG_CPU
4791 case CPU_UP_CANCELED:
4792 /* Unbind it from offline cpu so it can run. Fall thru. */
4793 kthread_bind(cpu_rq(cpu)->migration_thread,
4794 any_online_cpu(cpu_online_map));
4795 kthread_stop(cpu_rq(cpu)->migration_thread);
4796 cpu_rq(cpu)->migration_thread = NULL;
4799 migrate_live_tasks(cpu);
4801 kthread_stop(rq->migration_thread);
4802 rq->migration_thread = NULL;
4803 /* Idle task back to normal (off runqueue, low prio) */
4804 rq = task_rq_lock(rq->idle, &flags);
4805 deactivate_task(rq->idle, rq);
4806 rq->idle->static_prio = MAX_PRIO;
4807 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4808 migrate_dead_tasks(cpu);
4809 task_rq_unlock(rq, &flags);
4810 migrate_nr_uninterruptible(rq);
4811 BUG_ON(rq->nr_running != 0);
4813 /* No need to migrate the tasks: it was best-effort if
4814 * they didn't do lock_cpu_hotplug(). Just wake up
4815 * the requestors. */
4816 spin_lock_irq(&rq->lock);
4817 while (!list_empty(&rq->migration_queue)) {
4818 migration_req_t *req;
4819 req = list_entry(rq->migration_queue.next,
4820 migration_req_t, list);
4821 list_del_init(&req->list);
4822 complete(&req->done);
4824 spin_unlock_irq(&rq->lock);
4831 /* Register at highest priority so that task migration (migrate_all_tasks)
4832 * happens before everything else.
4834 static struct notifier_block __devinitdata migration_notifier = {
4835 .notifier_call = migration_call,
4839 int __init migration_init(void)
4841 void *cpu = (void *)(long)smp_processor_id();
4842 /* Start one for boot CPU. */
4843 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4844 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4845 register_cpu_notifier(&migration_notifier);
4851 #undef SCHED_DOMAIN_DEBUG
4852 #ifdef SCHED_DOMAIN_DEBUG
4853 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4858 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
4862 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4867 struct sched_group *group = sd->groups;
4868 cpumask_t groupmask;
4870 cpumask_scnprintf(str, NR_CPUS, sd->span);
4871 cpus_clear(groupmask);
4874 for (i = 0; i < level + 1; i++)
4876 printk("domain %d: ", level);
4878 if (!(sd->flags & SD_LOAD_BALANCE)) {
4879 printk("does not load-balance\n");
4881 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4885 printk("span %s\n", str);
4887 if (!cpu_isset(cpu, sd->span))
4888 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4889 if (!cpu_isset(cpu, group->cpumask))
4890 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4893 for (i = 0; i < level + 2; i++)
4899 printk(KERN_ERR "ERROR: group is NULL\n");
4903 if (!group->cpu_power) {
4905 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4908 if (!cpus_weight(group->cpumask)) {
4910 printk(KERN_ERR "ERROR: empty group\n");
4913 if (cpus_intersects(groupmask, group->cpumask)) {
4915 printk(KERN_ERR "ERROR: repeated CPUs\n");
4918 cpus_or(groupmask, groupmask, group->cpumask);
4920 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4923 group = group->next;
4924 } while (group != sd->groups);
4927 if (!cpus_equal(sd->span, groupmask))
4928 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4934 if (!cpus_subset(groupmask, sd->span))
4935 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4941 #define sched_domain_debug(sd, cpu) {}
4944 static int sd_degenerate(struct sched_domain *sd)
4946 if (cpus_weight(sd->span) == 1)
4949 /* Following flags need at least 2 groups */
4950 if (sd->flags & (SD_LOAD_BALANCE |
4951 SD_BALANCE_NEWIDLE |
4954 if (sd->groups != sd->groups->next)
4958 /* Following flags don't use groups */
4959 if (sd->flags & (SD_WAKE_IDLE |
4967 static int sd_parent_degenerate(struct sched_domain *sd,
4968 struct sched_domain *parent)
4970 unsigned long cflags = sd->flags, pflags = parent->flags;
4972 if (sd_degenerate(parent))
4975 if (!cpus_equal(sd->span, parent->span))
4978 /* Does parent contain flags not in child? */
4979 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
4980 if (cflags & SD_WAKE_AFFINE)
4981 pflags &= ~SD_WAKE_BALANCE;
4982 /* Flags needing groups don't count if only 1 group in parent */
4983 if (parent->groups == parent->groups->next) {
4984 pflags &= ~(SD_LOAD_BALANCE |
4985 SD_BALANCE_NEWIDLE |
4989 if (~cflags & pflags)
4996 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4997 * hold the hotplug lock.
4999 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5001 runqueue_t *rq = cpu_rq(cpu);
5002 struct sched_domain *tmp;
5004 /* Remove the sched domains which do not contribute to scheduling. */
5005 for (tmp = sd; tmp; tmp = tmp->parent) {
5006 struct sched_domain *parent = tmp->parent;
5009 if (sd_parent_degenerate(tmp, parent))
5010 tmp->parent = parent->parent;
5013 if (sd && sd_degenerate(sd))
5016 sched_domain_debug(sd, cpu);
5018 rcu_assign_pointer(rq->sd, sd);
5021 /* cpus with isolated domains */
5022 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5024 /* Setup the mask of cpus configured for isolated domains */
5025 static int __init isolated_cpu_setup(char *str)
5027 int ints[NR_CPUS], i;
5029 str = get_options(str, ARRAY_SIZE(ints), ints);
5030 cpus_clear(cpu_isolated_map);
5031 for (i = 1; i <= ints[0]; i++)
5032 if (ints[i] < NR_CPUS)
5033 cpu_set(ints[i], cpu_isolated_map);
5037 __setup ("isolcpus=", isolated_cpu_setup);
5040 * init_sched_build_groups takes an array of groups, the cpumask we wish
5041 * to span, and a pointer to a function which identifies what group a CPU
5042 * belongs to. The return value of group_fn must be a valid index into the
5043 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5044 * keep track of groups covered with a cpumask_t).
5046 * init_sched_build_groups will build a circular linked list of the groups
5047 * covered by the given span, and will set each group's ->cpumask correctly,
5048 * and ->cpu_power to 0.
5050 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5051 int (*group_fn)(int cpu))
5053 struct sched_group *first = NULL, *last = NULL;
5054 cpumask_t covered = CPU_MASK_NONE;
5057 for_each_cpu_mask(i, span) {
5058 int group = group_fn(i);
5059 struct sched_group *sg = &groups[group];
5062 if (cpu_isset(i, covered))
5065 sg->cpumask = CPU_MASK_NONE;
5068 for_each_cpu_mask(j, span) {
5069 if (group_fn(j) != group)
5072 cpu_set(j, covered);
5073 cpu_set(j, sg->cpumask);
5084 #define SD_NODES_PER_DOMAIN 16
5087 * Self-tuning task migration cost measurement between source and target CPUs.
5089 * This is done by measuring the cost of manipulating buffers of varying
5090 * sizes. For a given buffer-size here are the steps that are taken:
5092 * 1) the source CPU reads+dirties a shared buffer
5093 * 2) the target CPU reads+dirties the same shared buffer
5095 * We measure how long they take, in the following 4 scenarios:
5097 * - source: CPU1, target: CPU2 | cost1
5098 * - source: CPU2, target: CPU1 | cost2
5099 * - source: CPU1, target: CPU1 | cost3
5100 * - source: CPU2, target: CPU2 | cost4
5102 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5103 * the cost of migration.
5105 * We then start off from a small buffer-size and iterate up to larger
5106 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5107 * doing a maximum search for the cost. (The maximum cost for a migration
5108 * normally occurs when the working set size is around the effective cache
5111 #define SEARCH_SCOPE 2
5112 #define MIN_CACHE_SIZE (64*1024U)
5113 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5114 #define ITERATIONS 2
5115 #define SIZE_THRESH 130
5116 #define COST_THRESH 130
5119 * The migration cost is a function of 'domain distance'. Domain
5120 * distance is the number of steps a CPU has to iterate down its
5121 * domain tree to share a domain with the other CPU. The farther
5122 * two CPUs are from each other, the larger the distance gets.
5124 * Note that we use the distance only to cache measurement results,
5125 * the distance value is not used numerically otherwise. When two
5126 * CPUs have the same distance it is assumed that the migration
5127 * cost is the same. (this is a simplification but quite practical)
5129 #define MAX_DOMAIN_DISTANCE 32
5131 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5132 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] = -1LL };
5135 * Allow override of migration cost - in units of microseconds.
5136 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5137 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5139 static int __init migration_cost_setup(char *str)
5141 int ints[MAX_DOMAIN_DISTANCE+1], i;
5143 str = get_options(str, ARRAY_SIZE(ints), ints);
5145 printk("#ints: %d\n", ints[0]);
5146 for (i = 1; i <= ints[0]; i++) {
5147 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5148 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5153 __setup ("migration_cost=", migration_cost_setup);
5156 * Global multiplier (divisor) for migration-cutoff values,
5157 * in percentiles. E.g. use a value of 150 to get 1.5 times
5158 * longer cache-hot cutoff times.
5160 * (We scale it from 100 to 128 to long long handling easier.)
5163 #define MIGRATION_FACTOR_SCALE 128
5165 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5167 static int __init setup_migration_factor(char *str)
5169 get_option(&str, &migration_factor);
5170 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5174 __setup("migration_factor=", setup_migration_factor);
5177 * Estimated distance of two CPUs, measured via the number of domains
5178 * we have to pass for the two CPUs to be in the same span:
5180 static unsigned long domain_distance(int cpu1, int cpu2)
5182 unsigned long distance = 0;
5183 struct sched_domain *sd;
5185 for_each_domain(cpu1, sd) {
5186 WARN_ON(!cpu_isset(cpu1, sd->span));
5187 if (cpu_isset(cpu2, sd->span))
5191 if (distance >= MAX_DOMAIN_DISTANCE) {
5193 distance = MAX_DOMAIN_DISTANCE-1;
5199 static unsigned int migration_debug;
5201 static int __init setup_migration_debug(char *str)
5203 get_option(&str, &migration_debug);
5207 __setup("migration_debug=", setup_migration_debug);
5210 * Maximum cache-size that the scheduler should try to measure.
5211 * Architectures with larger caches should tune this up during
5212 * bootup. Gets used in the domain-setup code (i.e. during SMP
5215 unsigned int max_cache_size;
5217 static int __init setup_max_cache_size(char *str)
5219 get_option(&str, &max_cache_size);
5223 __setup("max_cache_size=", setup_max_cache_size);
5226 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5227 * is the operation that is timed, so we try to generate unpredictable
5228 * cachemisses that still end up filling the L2 cache:
5230 static void touch_cache(void *__cache, unsigned long __size)
5232 unsigned long size = __size/sizeof(long), chunk1 = size/3,
5234 unsigned long *cache = __cache;
5237 for (i = 0; i < size/6; i += 8) {
5240 case 1: cache[size-1-i]++;
5241 case 2: cache[chunk1-i]++;
5242 case 3: cache[chunk1+i]++;
5243 case 4: cache[chunk2-i]++;
5244 case 5: cache[chunk2+i]++;
5250 * Measure the cache-cost of one task migration. Returns in units of nsec.
5252 static unsigned long long measure_one(void *cache, unsigned long size,
5253 int source, int target)
5255 cpumask_t mask, saved_mask;
5256 unsigned long long t0, t1, t2, t3, cost;
5258 saved_mask = current->cpus_allowed;
5261 * Flush source caches to RAM and invalidate them:
5266 * Migrate to the source CPU:
5268 mask = cpumask_of_cpu(source);
5269 set_cpus_allowed(current, mask);
5270 WARN_ON(smp_processor_id() != source);
5273 * Dirty the working set:
5276 touch_cache(cache, size);
5280 * Migrate to the target CPU, dirty the L2 cache and access
5281 * the shared buffer. (which represents the working set
5282 * of a migrated task.)
5284 mask = cpumask_of_cpu(target);
5285 set_cpus_allowed(current, mask);
5286 WARN_ON(smp_processor_id() != target);
5289 touch_cache(cache, size);
5292 cost = t1-t0 + t3-t2;
5294 if (migration_debug >= 2)
5295 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5296 source, target, t1-t0, t1-t0, t3-t2, cost);
5298 * Flush target caches to RAM and invalidate them:
5302 set_cpus_allowed(current, saved_mask);
5308 * Measure a series of task migrations and return the average
5309 * result. Since this code runs early during bootup the system
5310 * is 'undisturbed' and the average latency makes sense.
5312 * The algorithm in essence auto-detects the relevant cache-size,
5313 * so it will properly detect different cachesizes for different
5314 * cache-hierarchies, depending on how the CPUs are connected.
5316 * Architectures can prime the upper limit of the search range via
5317 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5319 static unsigned long long
5320 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5322 unsigned long long cost1, cost2;
5326 * Measure the migration cost of 'size' bytes, over an
5327 * average of 10 runs:
5329 * (We perturb the cache size by a small (0..4k)
5330 * value to compensate size/alignment related artifacts.
5331 * We also subtract the cost of the operation done on
5337 * dry run, to make sure we start off cache-cold on cpu1,
5338 * and to get any vmalloc pagefaults in advance:
5340 measure_one(cache, size, cpu1, cpu2);
5341 for (i = 0; i < ITERATIONS; i++)
5342 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5344 measure_one(cache, size, cpu2, cpu1);
5345 for (i = 0; i < ITERATIONS; i++)
5346 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5349 * (We measure the non-migrating [cached] cost on both
5350 * cpu1 and cpu2, to handle CPUs with different speeds)
5354 measure_one(cache, size, cpu1, cpu1);
5355 for (i = 0; i < ITERATIONS; i++)
5356 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5358 measure_one(cache, size, cpu2, cpu2);
5359 for (i = 0; i < ITERATIONS; i++)
5360 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5363 * Get the per-iteration migration cost:
5365 do_div(cost1, 2*ITERATIONS);
5366 do_div(cost2, 2*ITERATIONS);
5368 return cost1 - cost2;
5371 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5373 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5374 unsigned int max_size, size, size_found = 0;
5375 long long cost = 0, prev_cost;
5379 * Search from max_cache_size*5 down to 64K - the real relevant
5380 * cachesize has to lie somewhere inbetween.
5382 if (max_cache_size) {
5383 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5384 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5387 * Since we have no estimation about the relevant
5390 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5391 size = MIN_CACHE_SIZE;
5394 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5395 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5400 * Allocate the working set:
5402 cache = vmalloc(max_size);
5404 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5405 return 1000000; // return 1 msec on very small boxen
5408 while (size <= max_size) {
5410 cost = measure_cost(cpu1, cpu2, cache, size);
5416 if (max_cost < cost) {
5422 * Calculate average fluctuation, we use this to prevent
5423 * noise from triggering an early break out of the loop:
5425 fluct = abs(cost - prev_cost);
5426 avg_fluct = (avg_fluct + fluct)/2;
5428 if (migration_debug)
5429 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5431 (long)cost / 1000000,
5432 ((long)cost / 100000) % 10,
5433 (long)max_cost / 1000000,
5434 ((long)max_cost / 100000) % 10,
5435 domain_distance(cpu1, cpu2),
5439 * If we iterated at least 20% past the previous maximum,
5440 * and the cost has dropped by more than 20% already,
5441 * (taking fluctuations into account) then we assume to
5442 * have found the maximum and break out of the loop early:
5444 if (size_found && (size*100 > size_found*SIZE_THRESH))
5445 if (cost+avg_fluct <= 0 ||
5446 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5448 if (migration_debug)
5449 printk("-> found max.\n");
5453 * Increase the cachesize in 5% steps:
5455 size = size * 20 / 19;
5458 if (migration_debug)
5459 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5460 cpu1, cpu2, size_found, max_cost);
5465 * A task is considered 'cache cold' if at least 2 times
5466 * the worst-case cost of migration has passed.
5468 * (this limit is only listened to if the load-balancing
5469 * situation is 'nice' - if there is a large imbalance we
5470 * ignore it for the sake of CPU utilization and
5471 * processing fairness.)
5473 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5476 static void calibrate_migration_costs(const cpumask_t *cpu_map)
5478 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5479 unsigned long j0, j1, distance, max_distance = 0;
5480 struct sched_domain *sd;
5485 * First pass - calculate the cacheflush times:
5487 for_each_cpu_mask(cpu1, *cpu_map) {
5488 for_each_cpu_mask(cpu2, *cpu_map) {
5491 distance = domain_distance(cpu1, cpu2);
5492 max_distance = max(max_distance, distance);
5494 * No result cached yet?
5496 if (migration_cost[distance] == -1LL)
5497 migration_cost[distance] =
5498 measure_migration_cost(cpu1, cpu2);
5502 * Second pass - update the sched domain hierarchy with
5503 * the new cache-hot-time estimations:
5505 for_each_cpu_mask(cpu, *cpu_map) {
5507 for_each_domain(cpu, sd) {
5508 sd->cache_hot_time = migration_cost[distance];
5515 if (migration_debug)
5516 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5524 printk("migration_cost=");
5525 for (distance = 0; distance <= max_distance; distance++) {
5528 printk("%ld", (long)migration_cost[distance] / 1000);
5532 if (migration_debug)
5533 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5536 * Move back to the original CPU. NUMA-Q gets confused
5537 * if we migrate to another quad during bootup.
5539 if (raw_smp_processor_id() != orig_cpu) {
5540 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5541 saved_mask = current->cpus_allowed;
5543 set_cpus_allowed(current, mask);
5544 set_cpus_allowed(current, saved_mask);
5551 * find_next_best_node - find the next node to include in a sched_domain
5552 * @node: node whose sched_domain we're building
5553 * @used_nodes: nodes already in the sched_domain
5555 * Find the next node to include in a given scheduling domain. Simply
5556 * finds the closest node not already in the @used_nodes map.
5558 * Should use nodemask_t.
5560 static int find_next_best_node(int node, unsigned long *used_nodes)
5562 int i, n, val, min_val, best_node = 0;
5566 for (i = 0; i < MAX_NUMNODES; i++) {
5567 /* Start at @node */
5568 n = (node + i) % MAX_NUMNODES;
5570 if (!nr_cpus_node(n))
5573 /* Skip already used nodes */
5574 if (test_bit(n, used_nodes))
5577 /* Simple min distance search */
5578 val = node_distance(node, n);
5580 if (val < min_val) {
5586 set_bit(best_node, used_nodes);
5591 * sched_domain_node_span - get a cpumask for a node's sched_domain
5592 * @node: node whose cpumask we're constructing
5593 * @size: number of nodes to include in this span
5595 * Given a node, construct a good cpumask for its sched_domain to span. It
5596 * should be one that prevents unnecessary balancing, but also spreads tasks
5599 static cpumask_t sched_domain_node_span(int node)
5602 cpumask_t span, nodemask;
5603 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5606 bitmap_zero(used_nodes, MAX_NUMNODES);
5608 nodemask = node_to_cpumask(node);
5609 cpus_or(span, span, nodemask);
5610 set_bit(node, used_nodes);
5612 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5613 int next_node = find_next_best_node(node, used_nodes);
5614 nodemask = node_to_cpumask(next_node);
5615 cpus_or(span, span, nodemask);
5623 * At the moment, CONFIG_SCHED_SMT is never defined, but leave it in so we
5624 * can switch it on easily if needed.
5626 #ifdef CONFIG_SCHED_SMT
5627 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
5628 static struct sched_group sched_group_cpus[NR_CPUS];
5629 static int cpu_to_cpu_group(int cpu)
5635 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
5636 static struct sched_group sched_group_phys[NR_CPUS];
5637 static int cpu_to_phys_group(int cpu)
5639 #ifdef CONFIG_SCHED_SMT
5640 return first_cpu(cpu_sibling_map[cpu]);
5648 * The init_sched_build_groups can't handle what we want to do with node
5649 * groups, so roll our own. Now each node has its own list of groups which
5650 * gets dynamically allocated.
5652 static DEFINE_PER_CPU(struct sched_domain, node_domains);
5653 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
5655 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
5656 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
5658 static int cpu_to_allnodes_group(int cpu)
5660 return cpu_to_node(cpu);
5665 * Build sched domains for a given set of cpus and attach the sched domains
5666 * to the individual cpus
5668 void build_sched_domains(const cpumask_t *cpu_map)
5672 struct sched_group **sched_group_nodes = NULL;
5673 struct sched_group *sched_group_allnodes = NULL;
5676 * Allocate the per-node list of sched groups
5678 sched_group_nodes = kmalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
5680 if (!sched_group_nodes) {
5681 printk(KERN_WARNING "Can not alloc sched group node list\n");
5684 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
5688 * Set up domains for cpus specified by the cpu_map.
5690 for_each_cpu_mask(i, *cpu_map) {
5692 struct sched_domain *sd = NULL, *p;
5693 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5695 cpus_and(nodemask, nodemask, *cpu_map);
5698 if (cpus_weight(*cpu_map)
5699 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
5700 if (!sched_group_allnodes) {
5701 sched_group_allnodes
5702 = kmalloc(sizeof(struct sched_group)
5705 if (!sched_group_allnodes) {
5707 "Can not alloc allnodes sched group\n");
5710 sched_group_allnodes_bycpu[i]
5711 = sched_group_allnodes;
5713 sd = &per_cpu(allnodes_domains, i);
5714 *sd = SD_ALLNODES_INIT;
5715 sd->span = *cpu_map;
5716 group = cpu_to_allnodes_group(i);
5717 sd->groups = &sched_group_allnodes[group];
5722 sd = &per_cpu(node_domains, i);
5724 sd->span = sched_domain_node_span(cpu_to_node(i));
5726 cpus_and(sd->span, sd->span, *cpu_map);
5730 sd = &per_cpu(phys_domains, i);
5731 group = cpu_to_phys_group(i);
5733 sd->span = nodemask;
5735 sd->groups = &sched_group_phys[group];
5737 #ifdef CONFIG_SCHED_SMT
5739 sd = &per_cpu(cpu_domains, i);
5740 group = cpu_to_cpu_group(i);
5741 *sd = SD_SIBLING_INIT;
5742 sd->span = cpu_sibling_map[i];
5743 cpus_and(sd->span, sd->span, *cpu_map);
5745 sd->groups = &sched_group_cpus[group];
5749 #ifdef CONFIG_SCHED_SMT
5750 /* Set up CPU (sibling) groups */
5751 for_each_cpu_mask(i, *cpu_map) {
5752 cpumask_t this_sibling_map = cpu_sibling_map[i];
5753 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
5754 if (i != first_cpu(this_sibling_map))
5757 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5762 /* Set up physical groups */
5763 for (i = 0; i < MAX_NUMNODES; i++) {
5764 cpumask_t nodemask = node_to_cpumask(i);
5766 cpus_and(nodemask, nodemask, *cpu_map);
5767 if (cpus_empty(nodemask))
5770 init_sched_build_groups(sched_group_phys, nodemask,
5771 &cpu_to_phys_group);
5775 /* Set up node groups */
5776 if (sched_group_allnodes)
5777 init_sched_build_groups(sched_group_allnodes, *cpu_map,
5778 &cpu_to_allnodes_group);
5780 for (i = 0; i < MAX_NUMNODES; i++) {
5781 /* Set up node groups */
5782 struct sched_group *sg, *prev;
5783 cpumask_t nodemask = node_to_cpumask(i);
5784 cpumask_t domainspan;
5785 cpumask_t covered = CPU_MASK_NONE;
5788 cpus_and(nodemask, nodemask, *cpu_map);
5789 if (cpus_empty(nodemask)) {
5790 sched_group_nodes[i] = NULL;
5794 domainspan = sched_domain_node_span(i);
5795 cpus_and(domainspan, domainspan, *cpu_map);
5797 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
5798 sched_group_nodes[i] = sg;
5799 for_each_cpu_mask(j, nodemask) {
5800 struct sched_domain *sd;
5801 sd = &per_cpu(node_domains, j);
5803 if (sd->groups == NULL) {
5804 /* Turn off balancing if we have no groups */
5810 "Can not alloc domain group for node %d\n", i);
5814 sg->cpumask = nodemask;
5815 cpus_or(covered, covered, nodemask);
5818 for (j = 0; j < MAX_NUMNODES; j++) {
5819 cpumask_t tmp, notcovered;
5820 int n = (i + j) % MAX_NUMNODES;
5822 cpus_complement(notcovered, covered);
5823 cpus_and(tmp, notcovered, *cpu_map);
5824 cpus_and(tmp, tmp, domainspan);
5825 if (cpus_empty(tmp))
5828 nodemask = node_to_cpumask(n);
5829 cpus_and(tmp, tmp, nodemask);
5830 if (cpus_empty(tmp))
5833 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
5836 "Can not alloc domain group for node %d\n", j);
5841 cpus_or(covered, covered, tmp);
5845 prev->next = sched_group_nodes[i];
5849 /* Calculate CPU power for physical packages and nodes */
5850 for_each_cpu_mask(i, *cpu_map) {
5852 struct sched_domain *sd;
5853 #ifdef CONFIG_SCHED_SMT
5854 sd = &per_cpu(cpu_domains, i);
5855 power = SCHED_LOAD_SCALE;
5856 sd->groups->cpu_power = power;
5859 sd = &per_cpu(phys_domains, i);
5860 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5861 (cpus_weight(sd->groups->cpumask)-1) / 10;
5862 sd->groups->cpu_power = power;
5865 sd = &per_cpu(allnodes_domains, i);
5867 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5868 (cpus_weight(sd->groups->cpumask)-1) / 10;
5869 sd->groups->cpu_power = power;
5875 for (i = 0; i < MAX_NUMNODES; i++) {
5876 struct sched_group *sg = sched_group_nodes[i];
5882 for_each_cpu_mask(j, sg->cpumask) {
5883 struct sched_domain *sd;
5886 sd = &per_cpu(phys_domains, j);
5887 if (j != first_cpu(sd->groups->cpumask)) {
5889 * Only add "power" once for each
5894 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5895 (cpus_weight(sd->groups->cpumask)-1) / 10;
5897 sg->cpu_power += power;
5900 if (sg != sched_group_nodes[i])
5905 /* Attach the domains */
5906 for_each_cpu_mask(i, *cpu_map) {
5907 struct sched_domain *sd;
5908 #ifdef CONFIG_SCHED_SMT
5909 sd = &per_cpu(cpu_domains, i);
5911 sd = &per_cpu(phys_domains, i);
5913 cpu_attach_domain(sd, i);
5916 * Tune cache-hot values:
5918 calibrate_migration_costs(cpu_map);
5921 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
5923 static void arch_init_sched_domains(const cpumask_t *cpu_map)
5925 cpumask_t cpu_default_map;
5928 * Setup mask for cpus without special case scheduling requirements.
5929 * For now this just excludes isolated cpus, but could be used to
5930 * exclude other special cases in the future.
5932 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
5934 build_sched_domains(&cpu_default_map);
5937 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
5943 for_each_cpu_mask(cpu, *cpu_map) {
5944 struct sched_group *sched_group_allnodes
5945 = sched_group_allnodes_bycpu[cpu];
5946 struct sched_group **sched_group_nodes
5947 = sched_group_nodes_bycpu[cpu];
5949 if (sched_group_allnodes) {
5950 kfree(sched_group_allnodes);
5951 sched_group_allnodes_bycpu[cpu] = NULL;
5954 if (!sched_group_nodes)
5957 for (i = 0; i < MAX_NUMNODES; i++) {
5958 cpumask_t nodemask = node_to_cpumask(i);
5959 struct sched_group *oldsg, *sg = sched_group_nodes[i];
5961 cpus_and(nodemask, nodemask, *cpu_map);
5962 if (cpus_empty(nodemask))
5972 if (oldsg != sched_group_nodes[i])
5975 kfree(sched_group_nodes);
5976 sched_group_nodes_bycpu[cpu] = NULL;
5982 * Detach sched domains from a group of cpus specified in cpu_map
5983 * These cpus will now be attached to the NULL domain
5985 static inline void detach_destroy_domains(const cpumask_t *cpu_map)
5989 for_each_cpu_mask(i, *cpu_map)
5990 cpu_attach_domain(NULL, i);
5991 synchronize_sched();
5992 arch_destroy_sched_domains(cpu_map);
5996 * Partition sched domains as specified by the cpumasks below.
5997 * This attaches all cpus from the cpumasks to the NULL domain,
5998 * waits for a RCU quiescent period, recalculates sched
5999 * domain information and then attaches them back to the
6000 * correct sched domains
6001 * Call with hotplug lock held
6003 void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6005 cpumask_t change_map;
6007 cpus_and(*partition1, *partition1, cpu_online_map);
6008 cpus_and(*partition2, *partition2, cpu_online_map);
6009 cpus_or(change_map, *partition1, *partition2);
6011 /* Detach sched domains from all of the affected cpus */
6012 detach_destroy_domains(&change_map);
6013 if (!cpus_empty(*partition1))
6014 build_sched_domains(partition1);
6015 if (!cpus_empty(*partition2))
6016 build_sched_domains(partition2);
6019 #ifdef CONFIG_HOTPLUG_CPU
6021 * Force a reinitialization of the sched domains hierarchy. The domains
6022 * and groups cannot be updated in place without racing with the balancing
6023 * code, so we temporarily attach all running cpus to the NULL domain
6024 * which will prevent rebalancing while the sched domains are recalculated.
6026 static int update_sched_domains(struct notifier_block *nfb,
6027 unsigned long action, void *hcpu)
6030 case CPU_UP_PREPARE:
6031 case CPU_DOWN_PREPARE:
6032 detach_destroy_domains(&cpu_online_map);
6035 case CPU_UP_CANCELED:
6036 case CPU_DOWN_FAILED:
6040 * Fall through and re-initialise the domains.
6047 /* The hotplug lock is already held by cpu_up/cpu_down */
6048 arch_init_sched_domains(&cpu_online_map);
6054 void __init sched_init_smp(void)
6057 arch_init_sched_domains(&cpu_online_map);
6058 unlock_cpu_hotplug();
6059 /* XXX: Theoretical race here - CPU may be hotplugged now */
6060 hotcpu_notifier(update_sched_domains, 0);
6063 void __init sched_init_smp(void)
6066 #endif /* CONFIG_SMP */
6068 int in_sched_functions(unsigned long addr)
6070 /* Linker adds these: start and end of __sched functions */
6071 extern char __sched_text_start[], __sched_text_end[];
6072 return in_lock_functions(addr) ||
6073 (addr >= (unsigned long)__sched_text_start
6074 && addr < (unsigned long)__sched_text_end);
6077 void __init sched_init(void)
6082 for (i = 0; i < NR_CPUS; i++) {
6083 prio_array_t *array;
6086 spin_lock_init(&rq->lock);
6088 rq->active = rq->arrays;
6089 rq->expired = rq->arrays + 1;
6090 rq->best_expired_prio = MAX_PRIO;
6094 for (j = 1; j < 3; j++)
6095 rq->cpu_load[j] = 0;
6096 rq->active_balance = 0;
6098 rq->migration_thread = NULL;
6099 INIT_LIST_HEAD(&rq->migration_queue);
6101 atomic_set(&rq->nr_iowait, 0);
6103 for (j = 0; j < 2; j++) {
6104 array = rq->arrays + j;
6105 for (k = 0; k < MAX_PRIO; k++) {
6106 INIT_LIST_HEAD(array->queue + k);
6107 __clear_bit(k, array->bitmap);
6109 // delimiter for bitsearch
6110 __set_bit(MAX_PRIO, array->bitmap);
6115 * The boot idle thread does lazy MMU switching as well:
6117 atomic_inc(&init_mm.mm_count);
6118 enter_lazy_tlb(&init_mm, current);
6121 * Make us the idle thread. Technically, schedule() should not be
6122 * called from this thread, however somewhere below it might be,
6123 * but because we are the idle thread, we just pick up running again
6124 * when this runqueue becomes "idle".
6126 init_idle(current, smp_processor_id());
6129 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6130 void __might_sleep(char *file, int line)
6132 #if defined(in_atomic)
6133 static unsigned long prev_jiffy; /* ratelimiting */
6135 if ((in_atomic() || irqs_disabled()) &&
6136 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6137 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6139 prev_jiffy = jiffies;
6140 printk(KERN_ERR "Debug: sleeping function called from invalid"
6141 " context at %s:%d\n", file, line);
6142 printk("in_atomic():%d, irqs_disabled():%d\n",
6143 in_atomic(), irqs_disabled());
6148 EXPORT_SYMBOL(__might_sleep);
6151 #ifdef CONFIG_MAGIC_SYSRQ
6152 void normalize_rt_tasks(void)
6154 struct task_struct *p;
6155 prio_array_t *array;
6156 unsigned long flags;
6159 read_lock_irq(&tasklist_lock);
6160 for_each_process (p) {
6164 rq = task_rq_lock(p, &flags);
6168 deactivate_task(p, task_rq(p));
6169 __setscheduler(p, SCHED_NORMAL, 0);
6171 __activate_task(p, task_rq(p));
6172 resched_task(rq->curr);
6175 task_rq_unlock(rq, &flags);
6177 read_unlock_irq(&tasklist_lock);
6180 #endif /* CONFIG_MAGIC_SYSRQ */
6184 * These functions are only useful for the IA64 MCA handling.
6186 * They can only be called when the whole system has been
6187 * stopped - every CPU needs to be quiescent, and no scheduling
6188 * activity can take place. Using them for anything else would
6189 * be a serious bug, and as a result, they aren't even visible
6190 * under any other configuration.
6194 * curr_task - return the current task for a given cpu.
6195 * @cpu: the processor in question.
6197 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6199 task_t *curr_task(int cpu)
6201 return cpu_curr(cpu);
6205 * set_curr_task - set the current task for a given cpu.
6206 * @cpu: the processor in question.
6207 * @p: the task pointer to set.
6209 * Description: This function must only be used when non-maskable interrupts
6210 * are serviced on a separate stack. It allows the architecture to switch the
6211 * notion of the current task on a cpu in a non-blocking manner. This function
6212 * must be called with all CPU's synchronized, and interrupts disabled, the
6213 * and caller must save the original value of the current task (see
6214 * curr_task() above) and restore that value before reenabling interrupts and
6215 * re-starting the system.
6217 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6219 void set_curr_task(int cpu, task_t *p)