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/debug_locks.h>
34 #include <linux/security.h>
35 #include <linux/notifier.h>
36 #include <linux/profile.h>
37 #include <linux/suspend.h>
38 #include <linux/vmalloc.h>
39 #include <linux/blkdev.h>
40 #include <linux/delay.h>
41 #include <linux/smp.h>
42 #include <linux/threads.h>
43 #include <linux/timer.h>
44 #include <linux/rcupdate.h>
45 #include <linux/cpu.h>
46 #include <linux/cpuset.h>
47 #include <linux/percpu.h>
48 #include <linux/kthread.h>
49 #include <linux/seq_file.h>
50 #include <linux/syscalls.h>
51 #include <linux/times.h>
52 #include <linux/acct.h>
53 #include <linux/kprobes.h>
54 #include <linux/delayacct.h>
57 #include <asm/unistd.h>
60 * Convert user-nice values [ -20 ... 0 ... 19 ]
61 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
64 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
65 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
66 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
69 * 'User priority' is the nice value converted to something we
70 * can work with better when scaling various scheduler parameters,
71 * it's a [ 0 ... 39 ] range.
73 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
74 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
75 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
78 * Some helpers for converting nanosecond timing to jiffy resolution
80 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
81 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
84 * These are the 'tuning knobs' of the scheduler:
86 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
87 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
88 * Timeslices get refilled after they expire.
90 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
91 #define DEF_TIMESLICE (100 * HZ / 1000)
92 #define ON_RUNQUEUE_WEIGHT 30
93 #define CHILD_PENALTY 95
94 #define PARENT_PENALTY 100
96 #define PRIO_BONUS_RATIO 25
97 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
98 #define INTERACTIVE_DELTA 2
99 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
100 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
101 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
104 * If a task is 'interactive' then we reinsert it in the active
105 * array after it has expired its current timeslice. (it will not
106 * continue to run immediately, it will still roundrobin with
107 * other interactive tasks.)
109 * This part scales the interactivity limit depending on niceness.
111 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
112 * Here are a few examples of different nice levels:
114 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
115 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
116 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
117 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
118 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
120 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
121 * priority range a task can explore, a value of '1' means the
122 * task is rated interactive.)
124 * Ie. nice +19 tasks can never get 'interactive' enough to be
125 * reinserted into the active array. And only heavily CPU-hog nice -20
126 * tasks will be expired. Default nice 0 tasks are somewhere between,
127 * it takes some effort for them to get interactive, but it's not
131 #define CURRENT_BONUS(p) \
132 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
135 #define GRANULARITY (10 * HZ / 1000 ? : 1)
138 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
139 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
142 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
143 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
146 #define SCALE(v1,v1_max,v2_max) \
147 (v1) * (v2_max) / (v1_max)
150 (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
153 #define TASK_INTERACTIVE(p) \
154 ((p)->prio <= (p)->static_prio - DELTA(p))
156 #define INTERACTIVE_SLEEP(p) \
157 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
158 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
160 #define TASK_PREEMPTS_CURR(p, rq) \
161 ((p)->prio < (rq)->curr->prio)
164 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
165 * to time slice values: [800ms ... 100ms ... 5ms]
167 * The higher a thread's priority, the bigger timeslices
168 * it gets during one round of execution. But even the lowest
169 * priority thread gets MIN_TIMESLICE worth of execution time.
172 #define SCALE_PRIO(x, prio) \
173 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
175 static unsigned int static_prio_timeslice(int static_prio)
177 if (static_prio < NICE_TO_PRIO(0))
178 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
180 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
183 static inline unsigned int task_timeslice(struct task_struct *p)
185 return static_prio_timeslice(p->static_prio);
189 * These are the runqueue data structures:
193 unsigned int nr_active;
194 DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
195 struct list_head queue[MAX_PRIO];
199 * This is the main, per-CPU runqueue data structure.
201 * Locking rule: those places that want to lock multiple runqueues
202 * (such as the load balancing or the thread migration code), lock
203 * acquire operations must be ordered by ascending &runqueue.
209 * nr_running and cpu_load should be in the same cacheline because
210 * remote CPUs use both these fields when doing load calculation.
212 unsigned long nr_running;
213 unsigned long raw_weighted_load;
215 unsigned long cpu_load[3];
217 unsigned long long nr_switches;
220 * This is part of a global counter where only the total sum
221 * over all CPUs matters. A task can increase this counter on
222 * one CPU and if it got migrated afterwards it may decrease
223 * it on another CPU. Always updated under the runqueue lock:
225 unsigned long nr_uninterruptible;
227 unsigned long expired_timestamp;
228 unsigned long long timestamp_last_tick;
229 struct task_struct *curr, *idle;
230 struct mm_struct *prev_mm;
231 struct prio_array *active, *expired, arrays[2];
232 int best_expired_prio;
236 struct sched_domain *sd;
238 /* For active balancing */
242 struct task_struct *migration_thread;
243 struct list_head migration_queue;
246 #ifdef CONFIG_SCHEDSTATS
248 struct sched_info rq_sched_info;
250 /* sys_sched_yield() stats */
251 unsigned long yld_exp_empty;
252 unsigned long yld_act_empty;
253 unsigned long yld_both_empty;
254 unsigned long yld_cnt;
256 /* schedule() stats */
257 unsigned long sched_switch;
258 unsigned long sched_cnt;
259 unsigned long sched_goidle;
261 /* try_to_wake_up() stats */
262 unsigned long ttwu_cnt;
263 unsigned long ttwu_local;
265 struct lock_class_key rq_lock_key;
268 static DEFINE_PER_CPU(struct rq, runqueues);
271 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
272 * See detach_destroy_domains: synchronize_sched for details.
274 * The domain tree of any CPU may only be accessed from within
275 * preempt-disabled sections.
277 #define for_each_domain(cpu, __sd) \
278 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
280 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
281 #define this_rq() (&__get_cpu_var(runqueues))
282 #define task_rq(p) cpu_rq(task_cpu(p))
283 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
285 #ifndef prepare_arch_switch
286 # define prepare_arch_switch(next) do { } while (0)
288 #ifndef finish_arch_switch
289 # define finish_arch_switch(prev) do { } while (0)
292 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
293 static inline int task_running(struct rq *rq, struct task_struct *p)
295 return rq->curr == p;
298 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
302 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
304 #ifdef CONFIG_DEBUG_SPINLOCK
305 /* this is a valid case when another task releases the spinlock */
306 rq->lock.owner = current;
309 * If we are tracking spinlock dependencies then we have to
310 * fix up the runqueue lock - which gets 'carried over' from
313 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
315 spin_unlock_irq(&rq->lock);
318 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
319 static inline int task_running(struct rq *rq, struct task_struct *p)
324 return rq->curr == p;
328 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
332 * We can optimise this out completely for !SMP, because the
333 * SMP rebalancing from interrupt is the only thing that cares
338 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
339 spin_unlock_irq(&rq->lock);
341 spin_unlock(&rq->lock);
345 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
349 * After ->oncpu is cleared, the task can be moved to a different CPU.
350 * We must ensure this doesn't happen until the switch is completely
356 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
360 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
363 * __task_rq_lock - lock the runqueue a given task resides on.
364 * Must be called interrupts disabled.
366 static inline struct rq *__task_rq_lock(struct task_struct *p)
373 spin_lock(&rq->lock);
374 if (unlikely(rq != task_rq(p))) {
375 spin_unlock(&rq->lock);
376 goto repeat_lock_task;
382 * task_rq_lock - lock the runqueue a given task resides on and disable
383 * interrupts. Note the ordering: we can safely lookup the task_rq without
384 * explicitly disabling preemption.
386 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
392 local_irq_save(*flags);
394 spin_lock(&rq->lock);
395 if (unlikely(rq != task_rq(p))) {
396 spin_unlock_irqrestore(&rq->lock, *flags);
397 goto repeat_lock_task;
402 static inline void __task_rq_unlock(struct rq *rq)
405 spin_unlock(&rq->lock);
408 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
411 spin_unlock_irqrestore(&rq->lock, *flags);
414 #ifdef CONFIG_SCHEDSTATS
416 * bump this up when changing the output format or the meaning of an existing
417 * format, so that tools can adapt (or abort)
419 #define SCHEDSTAT_VERSION 12
421 static int show_schedstat(struct seq_file *seq, void *v)
425 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
426 seq_printf(seq, "timestamp %lu\n", jiffies);
427 for_each_online_cpu(cpu) {
428 struct rq *rq = cpu_rq(cpu);
430 struct sched_domain *sd;
434 /* runqueue-specific stats */
436 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
437 cpu, rq->yld_both_empty,
438 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
439 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
440 rq->ttwu_cnt, rq->ttwu_local,
441 rq->rq_sched_info.cpu_time,
442 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
444 seq_printf(seq, "\n");
447 /* domain-specific stats */
449 for_each_domain(cpu, sd) {
450 enum idle_type itype;
451 char mask_str[NR_CPUS];
453 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
454 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
455 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
457 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
459 sd->lb_balanced[itype],
460 sd->lb_failed[itype],
461 sd->lb_imbalance[itype],
462 sd->lb_gained[itype],
463 sd->lb_hot_gained[itype],
464 sd->lb_nobusyq[itype],
465 sd->lb_nobusyg[itype]);
467 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
468 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
469 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
470 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
471 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
479 static int schedstat_open(struct inode *inode, struct file *file)
481 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
482 char *buf = kmalloc(size, GFP_KERNEL);
488 res = single_open(file, show_schedstat, NULL);
490 m = file->private_data;
498 struct file_operations proc_schedstat_operations = {
499 .open = schedstat_open,
502 .release = single_release,
505 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
506 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
507 #else /* !CONFIG_SCHEDSTATS */
508 # define schedstat_inc(rq, field) do { } while (0)
509 # define schedstat_add(rq, field, amt) do { } while (0)
513 * rq_lock - lock a given runqueue and disable interrupts.
515 static inline struct rq *this_rq_lock(void)
522 spin_lock(&rq->lock);
527 #ifdef CONFIG_SCHEDSTATS
529 * Called when a process is dequeued from the active array and given
530 * the cpu. We should note that with the exception of interactive
531 * tasks, the expired queue will become the active queue after the active
532 * queue is empty, without explicitly dequeuing and requeuing tasks in the
533 * expired queue. (Interactive tasks may be requeued directly to the
534 * active queue, thus delaying tasks in the expired queue from running;
535 * see scheduler_tick()).
537 * This function is only called from sched_info_arrive(), rather than
538 * dequeue_task(). Even though a task may be queued and dequeued multiple
539 * times as it is shuffled about, we're really interested in knowing how
540 * long it was from the *first* time it was queued to the time that it
543 static inline void sched_info_dequeued(struct task_struct *t)
545 t->sched_info.last_queued = 0;
549 * Called when a task finally hits the cpu. We can now calculate how
550 * long it was waiting to run. We also note when it began so that we
551 * can keep stats on how long its timeslice is.
553 static void sched_info_arrive(struct task_struct *t)
555 unsigned long now = jiffies, diff = 0;
556 struct rq *rq = task_rq(t);
558 if (t->sched_info.last_queued)
559 diff = now - t->sched_info.last_queued;
560 sched_info_dequeued(t);
561 t->sched_info.run_delay += diff;
562 t->sched_info.last_arrival = now;
563 t->sched_info.pcnt++;
568 rq->rq_sched_info.run_delay += diff;
569 rq->rq_sched_info.pcnt++;
573 * Called when a process is queued into either the active or expired
574 * array. The time is noted and later used to determine how long we
575 * had to wait for us to reach the cpu. Since the expired queue will
576 * become the active queue after active queue is empty, without dequeuing
577 * and requeuing any tasks, we are interested in queuing to either. It
578 * is unusual but not impossible for tasks to be dequeued and immediately
579 * requeued in the same or another array: this can happen in sched_yield(),
580 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
583 * This function is only called from enqueue_task(), but also only updates
584 * the timestamp if it is already not set. It's assumed that
585 * sched_info_dequeued() will clear that stamp when appropriate.
587 static inline void sched_info_queued(struct task_struct *t)
589 if (!t->sched_info.last_queued)
590 t->sched_info.last_queued = jiffies;
594 * Called when a process ceases being the active-running process, either
595 * voluntarily or involuntarily. Now we can calculate how long we ran.
597 static inline void sched_info_depart(struct task_struct *t)
599 struct rq *rq = task_rq(t);
600 unsigned long diff = jiffies - t->sched_info.last_arrival;
602 t->sched_info.cpu_time += diff;
605 rq->rq_sched_info.cpu_time += diff;
609 * Called when tasks are switched involuntarily due, typically, to expiring
610 * their time slice. (This may also be called when switching to or from
611 * the idle task.) We are only called when prev != next.
614 sched_info_switch(struct task_struct *prev, struct task_struct *next)
616 struct rq *rq = task_rq(prev);
619 * prev now departs the cpu. It's not interesting to record
620 * stats about how efficient we were at scheduling the idle
623 if (prev != rq->idle)
624 sched_info_depart(prev);
626 if (next != rq->idle)
627 sched_info_arrive(next);
630 #define sched_info_queued(t) do { } while (0)
631 #define sched_info_switch(t, next) do { } while (0)
632 #endif /* CONFIG_SCHEDSTATS */
635 * Adding/removing a task to/from a priority array:
637 static void dequeue_task(struct task_struct *p, struct prio_array *array)
640 list_del(&p->run_list);
641 if (list_empty(array->queue + p->prio))
642 __clear_bit(p->prio, array->bitmap);
645 static void enqueue_task(struct task_struct *p, struct prio_array *array)
647 sched_info_queued(p);
648 list_add_tail(&p->run_list, array->queue + p->prio);
649 __set_bit(p->prio, array->bitmap);
655 * Put task to the end of the run list without the overhead of dequeue
656 * followed by enqueue.
658 static void requeue_task(struct task_struct *p, struct prio_array *array)
660 list_move_tail(&p->run_list, array->queue + p->prio);
664 enqueue_task_head(struct task_struct *p, struct prio_array *array)
666 list_add(&p->run_list, array->queue + p->prio);
667 __set_bit(p->prio, array->bitmap);
673 * __normal_prio - return the priority that is based on the static
674 * priority but is modified by bonuses/penalties.
676 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
677 * into the -5 ... 0 ... +5 bonus/penalty range.
679 * We use 25% of the full 0...39 priority range so that:
681 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
682 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
684 * Both properties are important to certain workloads.
687 static inline int __normal_prio(struct task_struct *p)
691 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
693 prio = p->static_prio - bonus;
694 if (prio < MAX_RT_PRIO)
696 if (prio > MAX_PRIO-1)
702 * To aid in avoiding the subversion of "niceness" due to uneven distribution
703 * of tasks with abnormal "nice" values across CPUs the contribution that
704 * each task makes to its run queue's load is weighted according to its
705 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
706 * scaled version of the new time slice allocation that they receive on time
711 * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
712 * If static_prio_timeslice() is ever changed to break this assumption then
713 * this code will need modification
715 #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
716 #define LOAD_WEIGHT(lp) \
717 (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
718 #define PRIO_TO_LOAD_WEIGHT(prio) \
719 LOAD_WEIGHT(static_prio_timeslice(prio))
720 #define RTPRIO_TO_LOAD_WEIGHT(rp) \
721 (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
723 static void set_load_weight(struct task_struct *p)
725 if (has_rt_policy(p)) {
727 if (p == task_rq(p)->migration_thread)
729 * The migration thread does the actual balancing.
730 * Giving its load any weight will skew balancing
736 p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
738 p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
742 inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
744 rq->raw_weighted_load += p->load_weight;
748 dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
750 rq->raw_weighted_load -= p->load_weight;
753 static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
756 inc_raw_weighted_load(rq, p);
759 static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
762 dec_raw_weighted_load(rq, p);
766 * Calculate the expected normal priority: i.e. priority
767 * without taking RT-inheritance into account. Might be
768 * boosted by interactivity modifiers. Changes upon fork,
769 * setprio syscalls, and whenever the interactivity
770 * estimator recalculates.
772 static inline int normal_prio(struct task_struct *p)
776 if (has_rt_policy(p))
777 prio = MAX_RT_PRIO-1 - p->rt_priority;
779 prio = __normal_prio(p);
784 * Calculate the current priority, i.e. the priority
785 * taken into account by the scheduler. This value might
786 * be boosted by RT tasks, or might be boosted by
787 * interactivity modifiers. Will be RT if the task got
788 * RT-boosted. If not then it returns p->normal_prio.
790 static int effective_prio(struct task_struct *p)
792 p->normal_prio = normal_prio(p);
794 * If we are RT tasks or we were boosted to RT priority,
795 * keep the priority unchanged. Otherwise, update priority
796 * to the normal priority:
798 if (!rt_prio(p->prio))
799 return p->normal_prio;
804 * __activate_task - move a task to the runqueue.
806 static void __activate_task(struct task_struct *p, struct rq *rq)
808 struct prio_array *target = rq->active;
811 target = rq->expired;
812 enqueue_task(p, target);
813 inc_nr_running(p, rq);
817 * __activate_idle_task - move idle task to the _front_ of runqueue.
819 static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
821 enqueue_task_head(p, rq->active);
822 inc_nr_running(p, rq);
826 * Recalculate p->normal_prio and p->prio after having slept,
827 * updating the sleep-average too:
829 static int recalc_task_prio(struct task_struct *p, unsigned long long now)
831 /* Caller must always ensure 'now >= p->timestamp' */
832 unsigned long sleep_time = now - p->timestamp;
837 if (likely(sleep_time > 0)) {
839 * This ceiling is set to the lowest priority that would allow
840 * a task to be reinserted into the active array on timeslice
843 unsigned long ceiling = INTERACTIVE_SLEEP(p);
845 if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
847 * Prevents user tasks from achieving best priority
848 * with one single large enough sleep.
850 p->sleep_avg = ceiling;
852 * Using INTERACTIVE_SLEEP() as a ceiling places a
853 * nice(0) task 1ms sleep away from promotion, and
854 * gives it 700ms to round-robin with no chance of
855 * being demoted. This is more than generous, so
856 * mark this sleep as non-interactive to prevent the
857 * on-runqueue bonus logic from intervening should
858 * this task not receive cpu immediately.
860 p->sleep_type = SLEEP_NONINTERACTIVE;
863 * Tasks waking from uninterruptible sleep are
864 * limited in their sleep_avg rise as they
865 * are likely to be waiting on I/O
867 if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
868 if (p->sleep_avg >= ceiling)
870 else if (p->sleep_avg + sleep_time >=
872 p->sleep_avg = ceiling;
878 * This code gives a bonus to interactive tasks.
880 * The boost works by updating the 'average sleep time'
881 * value here, based on ->timestamp. The more time a
882 * task spends sleeping, the higher the average gets -
883 * and the higher the priority boost gets as well.
885 p->sleep_avg += sleep_time;
888 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
889 p->sleep_avg = NS_MAX_SLEEP_AVG;
892 return effective_prio(p);
896 * activate_task - move a task to the runqueue and do priority recalculation
898 * Update all the scheduling statistics stuff. (sleep average
899 * calculation, priority modifiers, etc.)
901 static void activate_task(struct task_struct *p, struct rq *rq, int local)
903 unsigned long long now;
908 /* Compensate for drifting sched_clock */
909 struct rq *this_rq = this_rq();
910 now = (now - this_rq->timestamp_last_tick)
911 + rq->timestamp_last_tick;
916 p->prio = recalc_task_prio(p, now);
919 * This checks to make sure it's not an uninterruptible task
920 * that is now waking up.
922 if (p->sleep_type == SLEEP_NORMAL) {
924 * Tasks which were woken up by interrupts (ie. hw events)
925 * are most likely of interactive nature. So we give them
926 * the credit of extending their sleep time to the period
927 * of time they spend on the runqueue, waiting for execution
928 * on a CPU, first time around:
931 p->sleep_type = SLEEP_INTERRUPTED;
934 * Normal first-time wakeups get a credit too for
935 * on-runqueue time, but it will be weighted down:
937 p->sleep_type = SLEEP_INTERACTIVE;
942 __activate_task(p, rq);
946 * deactivate_task - remove a task from the runqueue.
948 static void deactivate_task(struct task_struct *p, struct rq *rq)
950 dec_nr_running(p, rq);
951 dequeue_task(p, p->array);
956 * resched_task - mark a task 'to be rescheduled now'.
958 * On UP this means the setting of the need_resched flag, on SMP it
959 * might also involve a cross-CPU call to trigger the scheduler on
964 #ifndef tsk_is_polling
965 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
968 static void resched_task(struct task_struct *p)
972 assert_spin_locked(&task_rq(p)->lock);
974 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
977 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
980 if (cpu == smp_processor_id())
983 /* NEED_RESCHED must be visible before we test polling */
985 if (!tsk_is_polling(p))
986 smp_send_reschedule(cpu);
989 static inline void resched_task(struct task_struct *p)
991 assert_spin_locked(&task_rq(p)->lock);
992 set_tsk_need_resched(p);
997 * task_curr - is this task currently executing on a CPU?
998 * @p: the task in question.
1000 inline int task_curr(const struct task_struct *p)
1002 return cpu_curr(task_cpu(p)) == p;
1005 /* Used instead of source_load when we know the type == 0 */
1006 unsigned long weighted_cpuload(const int cpu)
1008 return cpu_rq(cpu)->raw_weighted_load;
1012 struct migration_req {
1013 struct list_head list;
1015 struct task_struct *task;
1018 struct completion done;
1022 * The task's runqueue lock must be held.
1023 * Returns true if you have to wait for migration thread.
1026 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1028 struct rq *rq = task_rq(p);
1031 * If the task is not on a runqueue (and not running), then
1032 * it is sufficient to simply update the task's cpu field.
1034 if (!p->array && !task_running(rq, p)) {
1035 set_task_cpu(p, dest_cpu);
1039 init_completion(&req->done);
1041 req->dest_cpu = dest_cpu;
1042 list_add(&req->list, &rq->migration_queue);
1048 * wait_task_inactive - wait for a thread to unschedule.
1050 * The caller must ensure that the task *will* unschedule sometime soon,
1051 * else this function might spin for a *long* time. This function can't
1052 * be called with interrupts off, or it may introduce deadlock with
1053 * smp_call_function() if an IPI is sent by the same process we are
1054 * waiting to become inactive.
1056 void wait_task_inactive(struct task_struct *p)
1058 unsigned long flags;
1063 rq = task_rq_lock(p, &flags);
1064 /* Must be off runqueue entirely, not preempted. */
1065 if (unlikely(p->array || task_running(rq, p))) {
1066 /* If it's preempted, we yield. It could be a while. */
1067 preempted = !task_running(rq, p);
1068 task_rq_unlock(rq, &flags);
1074 task_rq_unlock(rq, &flags);
1078 * kick_process - kick a running thread to enter/exit the kernel
1079 * @p: the to-be-kicked thread
1081 * Cause a process which is running on another CPU to enter
1082 * kernel-mode, without any delay. (to get signals handled.)
1084 * NOTE: this function doesnt have to take the runqueue lock,
1085 * because all it wants to ensure is that the remote task enters
1086 * the kernel. If the IPI races and the task has been migrated
1087 * to another CPU then no harm is done and the purpose has been
1090 void kick_process(struct task_struct *p)
1096 if ((cpu != smp_processor_id()) && task_curr(p))
1097 smp_send_reschedule(cpu);
1102 * Return a low guess at the load of a migration-source cpu weighted
1103 * according to the scheduling class and "nice" value.
1105 * We want to under-estimate the load of migration sources, to
1106 * balance conservatively.
1108 static inline unsigned long source_load(int cpu, int type)
1110 struct rq *rq = cpu_rq(cpu);
1113 return rq->raw_weighted_load;
1115 return min(rq->cpu_load[type-1], rq->raw_weighted_load);
1119 * Return a high guess at the load of a migration-target cpu weighted
1120 * according to the scheduling class and "nice" value.
1122 static inline unsigned long target_load(int cpu, int type)
1124 struct rq *rq = cpu_rq(cpu);
1127 return rq->raw_weighted_load;
1129 return max(rq->cpu_load[type-1], rq->raw_weighted_load);
1133 * Return the average load per task on the cpu's run queue
1135 static inline unsigned long cpu_avg_load_per_task(int cpu)
1137 struct rq *rq = cpu_rq(cpu);
1138 unsigned long n = rq->nr_running;
1140 return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
1144 * find_idlest_group finds and returns the least busy CPU group within the
1147 static struct sched_group *
1148 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1150 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1151 unsigned long min_load = ULONG_MAX, this_load = 0;
1152 int load_idx = sd->forkexec_idx;
1153 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1156 unsigned long load, avg_load;
1160 /* Skip over this group if it has no CPUs allowed */
1161 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1164 local_group = cpu_isset(this_cpu, group->cpumask);
1166 /* Tally up the load of all CPUs in the group */
1169 for_each_cpu_mask(i, group->cpumask) {
1170 /* Bias balancing toward cpus of our domain */
1172 load = source_load(i, load_idx);
1174 load = target_load(i, load_idx);
1179 /* Adjust by relative CPU power of the group */
1180 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1183 this_load = avg_load;
1185 } else if (avg_load < min_load) {
1186 min_load = avg_load;
1190 group = group->next;
1191 } while (group != sd->groups);
1193 if (!idlest || 100*this_load < imbalance*min_load)
1199 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1202 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1205 unsigned long load, min_load = ULONG_MAX;
1209 /* Traverse only the allowed CPUs */
1210 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1212 for_each_cpu_mask(i, tmp) {
1213 load = weighted_cpuload(i);
1215 if (load < min_load || (load == min_load && i == this_cpu)) {
1225 * sched_balance_self: balance the current task (running on cpu) in domains
1226 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1229 * Balance, ie. select the least loaded group.
1231 * Returns the target CPU number, or the same CPU if no balancing is needed.
1233 * preempt must be disabled.
1235 static int sched_balance_self(int cpu, int flag)
1237 struct task_struct *t = current;
1238 struct sched_domain *tmp, *sd = NULL;
1240 for_each_domain(cpu, tmp) {
1242 * If power savings logic is enabled for a domain, stop there.
1244 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1246 if (tmp->flags & flag)
1252 struct sched_group *group;
1257 group = find_idlest_group(sd, t, cpu);
1261 new_cpu = find_idlest_cpu(group, t, cpu);
1262 if (new_cpu == -1 || new_cpu == cpu)
1265 /* Now try balancing at a lower domain level */
1269 weight = cpus_weight(span);
1270 for_each_domain(cpu, tmp) {
1271 if (weight <= cpus_weight(tmp->span))
1273 if (tmp->flags & flag)
1276 /* while loop will break here if sd == NULL */
1282 #endif /* CONFIG_SMP */
1285 * wake_idle() will wake a task on an idle cpu if task->cpu is
1286 * not idle and an idle cpu is available. The span of cpus to
1287 * search starts with cpus closest then further out as needed,
1288 * so we always favor a closer, idle cpu.
1290 * Returns the CPU we should wake onto.
1292 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1293 static int wake_idle(int cpu, struct task_struct *p)
1296 struct sched_domain *sd;
1302 for_each_domain(cpu, sd) {
1303 if (sd->flags & SD_WAKE_IDLE) {
1304 cpus_and(tmp, sd->span, p->cpus_allowed);
1305 for_each_cpu_mask(i, tmp) {
1316 static inline int wake_idle(int cpu, struct task_struct *p)
1323 * try_to_wake_up - wake up a thread
1324 * @p: the to-be-woken-up thread
1325 * @state: the mask of task states that can be woken
1326 * @sync: do a synchronous wakeup?
1328 * Put it on the run-queue if it's not already there. The "current"
1329 * thread is always on the run-queue (except when the actual
1330 * re-schedule is in progress), and as such you're allowed to do
1331 * the simpler "current->state = TASK_RUNNING" to mark yourself
1332 * runnable without the overhead of this.
1334 * returns failure only if the task is already active.
1336 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1338 int cpu, this_cpu, success = 0;
1339 unsigned long flags;
1343 struct sched_domain *sd, *this_sd = NULL;
1344 unsigned long load, this_load;
1348 rq = task_rq_lock(p, &flags);
1349 old_state = p->state;
1350 if (!(old_state & state))
1357 this_cpu = smp_processor_id();
1360 if (unlikely(task_running(rq, p)))
1365 schedstat_inc(rq, ttwu_cnt);
1366 if (cpu == this_cpu) {
1367 schedstat_inc(rq, ttwu_local);
1371 for_each_domain(this_cpu, sd) {
1372 if (cpu_isset(cpu, sd->span)) {
1373 schedstat_inc(sd, ttwu_wake_remote);
1379 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1383 * Check for affine wakeup and passive balancing possibilities.
1386 int idx = this_sd->wake_idx;
1387 unsigned int imbalance;
1389 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1391 load = source_load(cpu, idx);
1392 this_load = target_load(this_cpu, idx);
1394 new_cpu = this_cpu; /* Wake to this CPU if we can */
1396 if (this_sd->flags & SD_WAKE_AFFINE) {
1397 unsigned long tl = this_load;
1398 unsigned long tl_per_task = cpu_avg_load_per_task(this_cpu);
1401 * If sync wakeup then subtract the (maximum possible)
1402 * effect of the currently running task from the load
1403 * of the current CPU:
1406 tl -= current->load_weight;
1409 tl + target_load(cpu, idx) <= tl_per_task) ||
1410 100*(tl + p->load_weight) <= imbalance*load) {
1412 * This domain has SD_WAKE_AFFINE and
1413 * p is cache cold in this domain, and
1414 * there is no bad imbalance.
1416 schedstat_inc(this_sd, ttwu_move_affine);
1422 * Start passive balancing when half the imbalance_pct
1425 if (this_sd->flags & SD_WAKE_BALANCE) {
1426 if (imbalance*this_load <= 100*load) {
1427 schedstat_inc(this_sd, ttwu_move_balance);
1433 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1435 new_cpu = wake_idle(new_cpu, p);
1436 if (new_cpu != cpu) {
1437 set_task_cpu(p, new_cpu);
1438 task_rq_unlock(rq, &flags);
1439 /* might preempt at this point */
1440 rq = task_rq_lock(p, &flags);
1441 old_state = p->state;
1442 if (!(old_state & state))
1447 this_cpu = smp_processor_id();
1452 #endif /* CONFIG_SMP */
1453 if (old_state == TASK_UNINTERRUPTIBLE) {
1454 rq->nr_uninterruptible--;
1456 * Tasks on involuntary sleep don't earn
1457 * sleep_avg beyond just interactive state.
1459 p->sleep_type = SLEEP_NONINTERACTIVE;
1463 * Tasks that have marked their sleep as noninteractive get
1464 * woken up with their sleep average not weighted in an
1467 if (old_state & TASK_NONINTERACTIVE)
1468 p->sleep_type = SLEEP_NONINTERACTIVE;
1471 activate_task(p, rq, cpu == this_cpu);
1473 * Sync wakeups (i.e. those types of wakeups where the waker
1474 * has indicated that it will leave the CPU in short order)
1475 * don't trigger a preemption, if the woken up task will run on
1476 * this cpu. (in this case the 'I will reschedule' promise of
1477 * the waker guarantees that the freshly woken up task is going
1478 * to be considered on this CPU.)
1480 if (!sync || cpu != this_cpu) {
1481 if (TASK_PREEMPTS_CURR(p, rq))
1482 resched_task(rq->curr);
1487 p->state = TASK_RUNNING;
1489 task_rq_unlock(rq, &flags);
1494 int fastcall wake_up_process(struct task_struct *p)
1496 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1497 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1499 EXPORT_SYMBOL(wake_up_process);
1501 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1503 return try_to_wake_up(p, state, 0);
1507 * Perform scheduler related setup for a newly forked process p.
1508 * p is forked by current.
1510 void fastcall sched_fork(struct task_struct *p, int clone_flags)
1512 int cpu = get_cpu();
1515 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1517 set_task_cpu(p, cpu);
1520 * We mark the process as running here, but have not actually
1521 * inserted it onto the runqueue yet. This guarantees that
1522 * nobody will actually run it, and a signal or other external
1523 * event cannot wake it up and insert it on the runqueue either.
1525 p->state = TASK_RUNNING;
1528 * Make sure we do not leak PI boosting priority to the child:
1530 p->prio = current->normal_prio;
1532 INIT_LIST_HEAD(&p->run_list);
1534 #ifdef CONFIG_SCHEDSTATS
1535 memset(&p->sched_info, 0, sizeof(p->sched_info));
1537 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1540 #ifdef CONFIG_PREEMPT
1541 /* Want to start with kernel preemption disabled. */
1542 task_thread_info(p)->preempt_count = 1;
1545 * Share the timeslice between parent and child, thus the
1546 * total amount of pending timeslices in the system doesn't change,
1547 * resulting in more scheduling fairness.
1549 local_irq_disable();
1550 p->time_slice = (current->time_slice + 1) >> 1;
1552 * The remainder of the first timeslice might be recovered by
1553 * the parent if the child exits early enough.
1555 p->first_time_slice = 1;
1556 current->time_slice >>= 1;
1557 p->timestamp = sched_clock();
1558 if (unlikely(!current->time_slice)) {
1560 * This case is rare, it happens when the parent has only
1561 * a single jiffy left from its timeslice. Taking the
1562 * runqueue lock is not a problem.
1564 current->time_slice = 1;
1572 * wake_up_new_task - wake up a newly created task for the first time.
1574 * This function will do some initial scheduler statistics housekeeping
1575 * that must be done for every newly created context, then puts the task
1576 * on the runqueue and wakes it.
1578 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1580 struct rq *rq, *this_rq;
1581 unsigned long flags;
1584 rq = task_rq_lock(p, &flags);
1585 BUG_ON(p->state != TASK_RUNNING);
1586 this_cpu = smp_processor_id();
1590 * We decrease the sleep average of forking parents
1591 * and children as well, to keep max-interactive tasks
1592 * from forking tasks that are max-interactive. The parent
1593 * (current) is done further down, under its lock.
1595 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1596 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1598 p->prio = effective_prio(p);
1600 if (likely(cpu == this_cpu)) {
1601 if (!(clone_flags & CLONE_VM)) {
1603 * The VM isn't cloned, so we're in a good position to
1604 * do child-runs-first in anticipation of an exec. This
1605 * usually avoids a lot of COW overhead.
1607 if (unlikely(!current->array))
1608 __activate_task(p, rq);
1610 p->prio = current->prio;
1611 p->normal_prio = current->normal_prio;
1612 list_add_tail(&p->run_list, ¤t->run_list);
1613 p->array = current->array;
1614 p->array->nr_active++;
1615 inc_nr_running(p, rq);
1619 /* Run child last */
1620 __activate_task(p, rq);
1622 * We skip the following code due to cpu == this_cpu
1624 * task_rq_unlock(rq, &flags);
1625 * this_rq = task_rq_lock(current, &flags);
1629 this_rq = cpu_rq(this_cpu);
1632 * Not the local CPU - must adjust timestamp. This should
1633 * get optimised away in the !CONFIG_SMP case.
1635 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1636 + rq->timestamp_last_tick;
1637 __activate_task(p, rq);
1638 if (TASK_PREEMPTS_CURR(p, rq))
1639 resched_task(rq->curr);
1642 * Parent and child are on different CPUs, now get the
1643 * parent runqueue to update the parent's ->sleep_avg:
1645 task_rq_unlock(rq, &flags);
1646 this_rq = task_rq_lock(current, &flags);
1648 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1649 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1650 task_rq_unlock(this_rq, &flags);
1654 * Potentially available exiting-child timeslices are
1655 * retrieved here - this way the parent does not get
1656 * penalized for creating too many threads.
1658 * (this cannot be used to 'generate' timeslices
1659 * artificially, because any timeslice recovered here
1660 * was given away by the parent in the first place.)
1662 void fastcall sched_exit(struct task_struct *p)
1664 unsigned long flags;
1668 * If the child was a (relative-) CPU hog then decrease
1669 * the sleep_avg of the parent as well.
1671 rq = task_rq_lock(p->parent, &flags);
1672 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1673 p->parent->time_slice += p->time_slice;
1674 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1675 p->parent->time_slice = task_timeslice(p);
1677 if (p->sleep_avg < p->parent->sleep_avg)
1678 p->parent->sleep_avg = p->parent->sleep_avg /
1679 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1681 task_rq_unlock(rq, &flags);
1685 * prepare_task_switch - prepare to switch tasks
1686 * @rq: the runqueue preparing to switch
1687 * @next: the task we are going to switch to.
1689 * This is called with the rq lock held and interrupts off. It must
1690 * be paired with a subsequent finish_task_switch after the context
1693 * prepare_task_switch sets up locking and calls architecture specific
1696 static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
1698 prepare_lock_switch(rq, next);
1699 prepare_arch_switch(next);
1703 * finish_task_switch - clean up after a task-switch
1704 * @rq: runqueue associated with task-switch
1705 * @prev: the thread we just switched away from.
1707 * finish_task_switch must be called after the context switch, paired
1708 * with a prepare_task_switch call before the context switch.
1709 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1710 * and do any other architecture-specific cleanup actions.
1712 * Note that we may have delayed dropping an mm in context_switch(). If
1713 * so, we finish that here outside of the runqueue lock. (Doing it
1714 * with the lock held can cause deadlocks; see schedule() for
1717 static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1718 __releases(rq->lock)
1720 struct mm_struct *mm = rq->prev_mm;
1721 unsigned long prev_task_flags;
1726 * A task struct has one reference for the use as "current".
1727 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1728 * calls schedule one last time. The schedule call will never return,
1729 * and the scheduled task must drop that reference.
1730 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1731 * still held, otherwise prev could be scheduled on another cpu, die
1732 * there before we look at prev->state, and then the reference would
1734 * Manfred Spraul <manfred@colorfullife.com>
1736 prev_task_flags = prev->flags;
1737 finish_arch_switch(prev);
1738 finish_lock_switch(rq, prev);
1741 if (unlikely(prev_task_flags & PF_DEAD)) {
1743 * Remove function-return probe instances associated with this
1744 * task and put them back on the free list.
1746 kprobe_flush_task(prev);
1747 put_task_struct(prev);
1752 * schedule_tail - first thing a freshly forked thread must call.
1753 * @prev: the thread we just switched away from.
1755 asmlinkage void schedule_tail(struct task_struct *prev)
1756 __releases(rq->lock)
1758 struct rq *rq = this_rq();
1760 finish_task_switch(rq, prev);
1761 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1762 /* In this case, finish_task_switch does not reenable preemption */
1765 if (current->set_child_tid)
1766 put_user(current->pid, current->set_child_tid);
1770 * context_switch - switch to the new MM and the new
1771 * thread's register state.
1773 static inline struct task_struct *
1774 context_switch(struct rq *rq, struct task_struct *prev,
1775 struct task_struct *next)
1777 struct mm_struct *mm = next->mm;
1778 struct mm_struct *oldmm = prev->active_mm;
1780 if (unlikely(!mm)) {
1781 next->active_mm = oldmm;
1782 atomic_inc(&oldmm->mm_count);
1783 enter_lazy_tlb(oldmm, next);
1785 switch_mm(oldmm, mm, next);
1787 if (unlikely(!prev->mm)) {
1788 prev->active_mm = NULL;
1789 WARN_ON(rq->prev_mm);
1790 rq->prev_mm = oldmm;
1793 * Since the runqueue lock will be released by the next
1794 * task (which is an invalid locking op but in the case
1795 * of the scheduler it's an obvious special-case), so we
1796 * do an early lockdep release here:
1798 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1799 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1802 /* Here we just switch the register state and the stack. */
1803 switch_to(prev, next, prev);
1809 * nr_running, nr_uninterruptible and nr_context_switches:
1811 * externally visible scheduler statistics: current number of runnable
1812 * threads, current number of uninterruptible-sleeping threads, total
1813 * number of context switches performed since bootup.
1815 unsigned long nr_running(void)
1817 unsigned long i, sum = 0;
1819 for_each_online_cpu(i)
1820 sum += cpu_rq(i)->nr_running;
1825 unsigned long nr_uninterruptible(void)
1827 unsigned long i, sum = 0;
1829 for_each_possible_cpu(i)
1830 sum += cpu_rq(i)->nr_uninterruptible;
1833 * Since we read the counters lockless, it might be slightly
1834 * inaccurate. Do not allow it to go below zero though:
1836 if (unlikely((long)sum < 0))
1842 unsigned long long nr_context_switches(void)
1845 unsigned long long sum = 0;
1847 for_each_possible_cpu(i)
1848 sum += cpu_rq(i)->nr_switches;
1853 unsigned long nr_iowait(void)
1855 unsigned long i, sum = 0;
1857 for_each_possible_cpu(i)
1858 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1863 unsigned long nr_active(void)
1865 unsigned long i, running = 0, uninterruptible = 0;
1867 for_each_online_cpu(i) {
1868 running += cpu_rq(i)->nr_running;
1869 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1872 if (unlikely((long)uninterruptible < 0))
1873 uninterruptible = 0;
1875 return running + uninterruptible;
1881 * Is this task likely cache-hot:
1884 task_hot(struct task_struct *p, unsigned long long now, struct sched_domain *sd)
1886 return (long long)(now - p->last_ran) < (long long)sd->cache_hot_time;
1890 * double_rq_lock - safely lock two runqueues
1892 * Note this does not disable interrupts like task_rq_lock,
1893 * you need to do so manually before calling.
1895 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1896 __acquires(rq1->lock)
1897 __acquires(rq2->lock)
1900 spin_lock(&rq1->lock);
1901 __acquire(rq2->lock); /* Fake it out ;) */
1904 spin_lock(&rq1->lock);
1905 spin_lock(&rq2->lock);
1907 spin_lock(&rq2->lock);
1908 spin_lock(&rq1->lock);
1914 * double_rq_unlock - safely unlock two runqueues
1916 * Note this does not restore interrupts like task_rq_unlock,
1917 * you need to do so manually after calling.
1919 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1920 __releases(rq1->lock)
1921 __releases(rq2->lock)
1923 spin_unlock(&rq1->lock);
1925 spin_unlock(&rq2->lock);
1927 __release(rq2->lock);
1931 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1933 static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
1934 __releases(this_rq->lock)
1935 __acquires(busiest->lock)
1936 __acquires(this_rq->lock)
1938 if (unlikely(!spin_trylock(&busiest->lock))) {
1939 if (busiest < this_rq) {
1940 spin_unlock(&this_rq->lock);
1941 spin_lock(&busiest->lock);
1942 spin_lock(&this_rq->lock);
1944 spin_lock(&busiest->lock);
1949 * If dest_cpu is allowed for this process, migrate the task to it.
1950 * This is accomplished by forcing the cpu_allowed mask to only
1951 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1952 * the cpu_allowed mask is restored.
1954 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
1956 struct migration_req req;
1957 unsigned long flags;
1960 rq = task_rq_lock(p, &flags);
1961 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1962 || unlikely(cpu_is_offline(dest_cpu)))
1965 /* force the process onto the specified CPU */
1966 if (migrate_task(p, dest_cpu, &req)) {
1967 /* Need to wait for migration thread (might exit: take ref). */
1968 struct task_struct *mt = rq->migration_thread;
1970 get_task_struct(mt);
1971 task_rq_unlock(rq, &flags);
1972 wake_up_process(mt);
1973 put_task_struct(mt);
1974 wait_for_completion(&req.done);
1979 task_rq_unlock(rq, &flags);
1983 * sched_exec - execve() is a valuable balancing opportunity, because at
1984 * this point the task has the smallest effective memory and cache footprint.
1986 void sched_exec(void)
1988 int new_cpu, this_cpu = get_cpu();
1989 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1991 if (new_cpu != this_cpu)
1992 sched_migrate_task(current, new_cpu);
1996 * pull_task - move a task from a remote runqueue to the local runqueue.
1997 * Both runqueues must be locked.
1999 static void pull_task(struct rq *src_rq, struct prio_array *src_array,
2000 struct task_struct *p, struct rq *this_rq,
2001 struct prio_array *this_array, int this_cpu)
2003 dequeue_task(p, src_array);
2004 dec_nr_running(p, src_rq);
2005 set_task_cpu(p, this_cpu);
2006 inc_nr_running(p, this_rq);
2007 enqueue_task(p, this_array);
2008 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
2009 + this_rq->timestamp_last_tick;
2011 * Note that idle threads have a prio of MAX_PRIO, for this test
2012 * to be always true for them.
2014 if (TASK_PREEMPTS_CURR(p, this_rq))
2015 resched_task(this_rq->curr);
2019 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2022 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2023 struct sched_domain *sd, enum idle_type idle,
2027 * We do not migrate tasks that are:
2028 * 1) running (obviously), or
2029 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2030 * 3) are cache-hot on their current CPU.
2032 if (!cpu_isset(this_cpu, p->cpus_allowed))
2036 if (task_running(rq, p))
2040 * Aggressive migration if:
2041 * 1) task is cache cold, or
2042 * 2) too many balance attempts have failed.
2045 if (sd->nr_balance_failed > sd->cache_nice_tries)
2048 if (task_hot(p, rq->timestamp_last_tick, sd))
2053 #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
2056 * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
2057 * load from busiest to this_rq, as part of a balancing operation within
2058 * "domain". Returns the number of tasks moved.
2060 * Called with both runqueues locked.
2062 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2063 unsigned long max_nr_move, unsigned long max_load_move,
2064 struct sched_domain *sd, enum idle_type idle,
2067 int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
2068 best_prio_seen, skip_for_load;
2069 struct prio_array *array, *dst_array;
2070 struct list_head *head, *curr;
2071 struct task_struct *tmp;
2074 if (max_nr_move == 0 || max_load_move == 0)
2077 rem_load_move = max_load_move;
2079 this_best_prio = rq_best_prio(this_rq);
2080 best_prio = rq_best_prio(busiest);
2082 * Enable handling of the case where there is more than one task
2083 * with the best priority. If the current running task is one
2084 * of those with prio==best_prio we know it won't be moved
2085 * and therefore it's safe to override the skip (based on load) of
2086 * any task we find with that prio.
2088 best_prio_seen = best_prio == busiest->curr->prio;
2091 * We first consider expired tasks. Those will likely not be
2092 * executed in the near future, and they are most likely to
2093 * be cache-cold, thus switching CPUs has the least effect
2096 if (busiest->expired->nr_active) {
2097 array = busiest->expired;
2098 dst_array = this_rq->expired;
2100 array = busiest->active;
2101 dst_array = this_rq->active;
2105 /* Start searching at priority 0: */
2109 idx = sched_find_first_bit(array->bitmap);
2111 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2112 if (idx >= MAX_PRIO) {
2113 if (array == busiest->expired && busiest->active->nr_active) {
2114 array = busiest->active;
2115 dst_array = this_rq->active;
2121 head = array->queue + idx;
2124 tmp = list_entry(curr, struct task_struct, run_list);
2129 * To help distribute high priority tasks accross CPUs we don't
2130 * skip a task if it will be the highest priority task (i.e. smallest
2131 * prio value) on its new queue regardless of its load weight
2133 skip_for_load = tmp->load_weight > rem_load_move;
2134 if (skip_for_load && idx < this_best_prio)
2135 skip_for_load = !best_prio_seen && idx == best_prio;
2136 if (skip_for_load ||
2137 !can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
2139 best_prio_seen |= idx == best_prio;
2146 #ifdef CONFIG_SCHEDSTATS
2147 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
2148 schedstat_inc(sd, lb_hot_gained[idle]);
2151 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2153 rem_load_move -= tmp->load_weight;
2156 * We only want to steal up to the prescribed number of tasks
2157 * and the prescribed amount of weighted load.
2159 if (pulled < max_nr_move && rem_load_move > 0) {
2160 if (idx < this_best_prio)
2161 this_best_prio = idx;
2169 * Right now, this is the only place pull_task() is called,
2170 * so we can safely collect pull_task() stats here rather than
2171 * inside pull_task().
2173 schedstat_add(sd, lb_gained[idle], pulled);
2176 *all_pinned = pinned;
2181 * find_busiest_group finds and returns the busiest CPU group within the
2182 * domain. It calculates and returns the amount of weighted load which
2183 * should be moved to restore balance via the imbalance parameter.
2185 static struct sched_group *
2186 find_busiest_group(struct sched_domain *sd, int this_cpu,
2187 unsigned long *imbalance, enum idle_type idle, int *sd_idle)
2189 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2190 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2191 unsigned long max_pull;
2192 unsigned long busiest_load_per_task, busiest_nr_running;
2193 unsigned long this_load_per_task, this_nr_running;
2195 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2196 int power_savings_balance = 1;
2197 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2198 unsigned long min_nr_running = ULONG_MAX;
2199 struct sched_group *group_min = NULL, *group_leader = NULL;
2202 max_load = this_load = total_load = total_pwr = 0;
2203 busiest_load_per_task = busiest_nr_running = 0;
2204 this_load_per_task = this_nr_running = 0;
2205 if (idle == NOT_IDLE)
2206 load_idx = sd->busy_idx;
2207 else if (idle == NEWLY_IDLE)
2208 load_idx = sd->newidle_idx;
2210 load_idx = sd->idle_idx;
2213 unsigned long load, group_capacity;
2216 unsigned long sum_nr_running, sum_weighted_load;
2218 local_group = cpu_isset(this_cpu, group->cpumask);
2220 /* Tally up the load of all CPUs in the group */
2221 sum_weighted_load = sum_nr_running = avg_load = 0;
2223 for_each_cpu_mask(i, group->cpumask) {
2224 struct rq *rq = cpu_rq(i);
2226 if (*sd_idle && !idle_cpu(i))
2229 /* Bias balancing toward cpus of our domain */
2231 load = target_load(i, load_idx);
2233 load = source_load(i, load_idx);
2236 sum_nr_running += rq->nr_running;
2237 sum_weighted_load += rq->raw_weighted_load;
2240 total_load += avg_load;
2241 total_pwr += group->cpu_power;
2243 /* Adjust by relative CPU power of the group */
2244 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2246 group_capacity = group->cpu_power / SCHED_LOAD_SCALE;
2249 this_load = avg_load;
2251 this_nr_running = sum_nr_running;
2252 this_load_per_task = sum_weighted_load;
2253 } else if (avg_load > max_load &&
2254 sum_nr_running > group_capacity) {
2255 max_load = avg_load;
2257 busiest_nr_running = sum_nr_running;
2258 busiest_load_per_task = sum_weighted_load;
2261 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2263 * Busy processors will not participate in power savings
2266 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2270 * If the local group is idle or completely loaded
2271 * no need to do power savings balance at this domain
2273 if (local_group && (this_nr_running >= group_capacity ||
2275 power_savings_balance = 0;
2278 * If a group is already running at full capacity or idle,
2279 * don't include that group in power savings calculations
2281 if (!power_savings_balance || sum_nr_running >= group_capacity
2286 * Calculate the group which has the least non-idle load.
2287 * This is the group from where we need to pick up the load
2290 if ((sum_nr_running < min_nr_running) ||
2291 (sum_nr_running == min_nr_running &&
2292 first_cpu(group->cpumask) <
2293 first_cpu(group_min->cpumask))) {
2295 min_nr_running = sum_nr_running;
2296 min_load_per_task = sum_weighted_load /
2301 * Calculate the group which is almost near its
2302 * capacity but still has some space to pick up some load
2303 * from other group and save more power
2305 if (sum_nr_running <= group_capacity - 1) {
2306 if (sum_nr_running > leader_nr_running ||
2307 (sum_nr_running == leader_nr_running &&
2308 first_cpu(group->cpumask) >
2309 first_cpu(group_leader->cpumask))) {
2310 group_leader = group;
2311 leader_nr_running = sum_nr_running;
2316 group = group->next;
2317 } while (group != sd->groups);
2319 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2322 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2324 if (this_load >= avg_load ||
2325 100*max_load <= sd->imbalance_pct*this_load)
2328 busiest_load_per_task /= busiest_nr_running;
2330 * We're trying to get all the cpus to the average_load, so we don't
2331 * want to push ourselves above the average load, nor do we wish to
2332 * reduce the max loaded cpu below the average load, as either of these
2333 * actions would just result in more rebalancing later, and ping-pong
2334 * tasks around. Thus we look for the minimum possible imbalance.
2335 * Negative imbalances (*we* are more loaded than anyone else) will
2336 * be counted as no imbalance for these purposes -- we can't fix that
2337 * by pulling tasks to us. Be careful of negative numbers as they'll
2338 * appear as very large values with unsigned longs.
2340 if (max_load <= busiest_load_per_task)
2344 * In the presence of smp nice balancing, certain scenarios can have
2345 * max load less than avg load(as we skip the groups at or below
2346 * its cpu_power, while calculating max_load..)
2348 if (max_load < avg_load) {
2350 goto small_imbalance;
2353 /* Don't want to pull so many tasks that a group would go idle */
2354 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2356 /* How much load to actually move to equalise the imbalance */
2357 *imbalance = min(max_pull * busiest->cpu_power,
2358 (avg_load - this_load) * this->cpu_power)
2362 * if *imbalance is less than the average load per runnable task
2363 * there is no gaurantee that any tasks will be moved so we'll have
2364 * a think about bumping its value to force at least one task to be
2367 if (*imbalance < busiest_load_per_task) {
2368 unsigned long tmp, pwr_now, pwr_move;
2372 pwr_move = pwr_now = 0;
2374 if (this_nr_running) {
2375 this_load_per_task /= this_nr_running;
2376 if (busiest_load_per_task > this_load_per_task)
2379 this_load_per_task = SCHED_LOAD_SCALE;
2381 if (max_load - this_load >= busiest_load_per_task * imbn) {
2382 *imbalance = busiest_load_per_task;
2387 * OK, we don't have enough imbalance to justify moving tasks,
2388 * however we may be able to increase total CPU power used by
2392 pwr_now += busiest->cpu_power *
2393 min(busiest_load_per_task, max_load);
2394 pwr_now += this->cpu_power *
2395 min(this_load_per_task, this_load);
2396 pwr_now /= SCHED_LOAD_SCALE;
2398 /* Amount of load we'd subtract */
2399 tmp = busiest_load_per_task*SCHED_LOAD_SCALE/busiest->cpu_power;
2401 pwr_move += busiest->cpu_power *
2402 min(busiest_load_per_task, max_load - tmp);
2404 /* Amount of load we'd add */
2405 if (max_load*busiest->cpu_power <
2406 busiest_load_per_task*SCHED_LOAD_SCALE)
2407 tmp = max_load*busiest->cpu_power/this->cpu_power;
2409 tmp = busiest_load_per_task*SCHED_LOAD_SCALE/this->cpu_power;
2410 pwr_move += this->cpu_power*min(this_load_per_task, this_load + tmp);
2411 pwr_move /= SCHED_LOAD_SCALE;
2413 /* Move if we gain throughput */
2414 if (pwr_move <= pwr_now)
2417 *imbalance = busiest_load_per_task;
2423 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2424 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2427 if (this == group_leader && group_leader != group_min) {
2428 *imbalance = min_load_per_task;
2438 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2441 find_busiest_queue(struct sched_group *group, enum idle_type idle,
2442 unsigned long imbalance)
2444 struct rq *busiest = NULL, *rq;
2445 unsigned long max_load = 0;
2448 for_each_cpu_mask(i, group->cpumask) {
2451 if (rq->nr_running == 1 && rq->raw_weighted_load > imbalance)
2454 if (rq->raw_weighted_load > max_load) {
2455 max_load = rq->raw_weighted_load;
2464 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2465 * so long as it is large enough.
2467 #define MAX_PINNED_INTERVAL 512
2469 static inline unsigned long minus_1_or_zero(unsigned long n)
2471 return n > 0 ? n - 1 : 0;
2475 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2476 * tasks if there is an imbalance.
2478 * Called with this_rq unlocked.
2480 static int load_balance(int this_cpu, struct rq *this_rq,
2481 struct sched_domain *sd, enum idle_type idle)
2483 int nr_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2484 struct sched_group *group;
2485 unsigned long imbalance;
2488 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2489 !sched_smt_power_savings)
2492 schedstat_inc(sd, lb_cnt[idle]);
2494 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
2496 schedstat_inc(sd, lb_nobusyg[idle]);
2500 busiest = find_busiest_queue(group, idle, imbalance);
2502 schedstat_inc(sd, lb_nobusyq[idle]);
2506 BUG_ON(busiest == this_rq);
2508 schedstat_add(sd, lb_imbalance[idle], imbalance);
2511 if (busiest->nr_running > 1) {
2513 * Attempt to move tasks. If find_busiest_group has found
2514 * an imbalance but busiest->nr_running <= 1, the group is
2515 * still unbalanced. nr_moved simply stays zero, so it is
2516 * correctly treated as an imbalance.
2518 double_rq_lock(this_rq, busiest);
2519 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2520 minus_1_or_zero(busiest->nr_running),
2521 imbalance, sd, idle, &all_pinned);
2522 double_rq_unlock(this_rq, busiest);
2524 /* All tasks on this runqueue were pinned by CPU affinity */
2525 if (unlikely(all_pinned))
2530 schedstat_inc(sd, lb_failed[idle]);
2531 sd->nr_balance_failed++;
2533 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2535 spin_lock(&busiest->lock);
2537 /* don't kick the migration_thread, if the curr
2538 * task on busiest cpu can't be moved to this_cpu
2540 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2541 spin_unlock(&busiest->lock);
2543 goto out_one_pinned;
2546 if (!busiest->active_balance) {
2547 busiest->active_balance = 1;
2548 busiest->push_cpu = this_cpu;
2551 spin_unlock(&busiest->lock);
2553 wake_up_process(busiest->migration_thread);
2556 * We've kicked active balancing, reset the failure
2559 sd->nr_balance_failed = sd->cache_nice_tries+1;
2562 sd->nr_balance_failed = 0;
2564 if (likely(!active_balance)) {
2565 /* We were unbalanced, so reset the balancing interval */
2566 sd->balance_interval = sd->min_interval;
2569 * If we've begun active balancing, start to back off. This
2570 * case may not be covered by the all_pinned logic if there
2571 * is only 1 task on the busy runqueue (because we don't call
2574 if (sd->balance_interval < sd->max_interval)
2575 sd->balance_interval *= 2;
2578 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2579 !sched_smt_power_savings)
2584 schedstat_inc(sd, lb_balanced[idle]);
2586 sd->nr_balance_failed = 0;
2589 /* tune up the balancing interval */
2590 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2591 (sd->balance_interval < sd->max_interval))
2592 sd->balance_interval *= 2;
2594 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2595 !sched_smt_power_savings)
2601 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2602 * tasks if there is an imbalance.
2604 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2605 * this_rq is locked.
2608 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2610 struct sched_group *group;
2611 struct rq *busiest = NULL;
2612 unsigned long imbalance;
2616 if (sd->flags & SD_SHARE_CPUPOWER && !sched_smt_power_savings)
2619 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2620 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
2622 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2626 busiest = find_busiest_queue(group, NEWLY_IDLE, imbalance);
2628 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2632 BUG_ON(busiest == this_rq);
2634 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2637 if (busiest->nr_running > 1) {
2638 /* Attempt to move tasks */
2639 double_lock_balance(this_rq, busiest);
2640 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2641 minus_1_or_zero(busiest->nr_running),
2642 imbalance, sd, NEWLY_IDLE, NULL);
2643 spin_unlock(&busiest->lock);
2647 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2648 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2651 sd->nr_balance_failed = 0;
2656 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2657 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2658 !sched_smt_power_savings)
2660 sd->nr_balance_failed = 0;
2666 * idle_balance is called by schedule() if this_cpu is about to become
2667 * idle. Attempts to pull tasks from other CPUs.
2669 static void idle_balance(int this_cpu, struct rq *this_rq)
2671 struct sched_domain *sd;
2673 for_each_domain(this_cpu, sd) {
2674 if (sd->flags & SD_BALANCE_NEWIDLE) {
2675 /* If we've pulled tasks over stop searching: */
2676 if (load_balance_newidle(this_cpu, this_rq, sd))
2683 * active_load_balance is run by migration threads. It pushes running tasks
2684 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2685 * running on each physical CPU where possible, and avoids physical /
2686 * logical imbalances.
2688 * Called with busiest_rq locked.
2690 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
2692 int target_cpu = busiest_rq->push_cpu;
2693 struct sched_domain *sd;
2694 struct rq *target_rq;
2696 /* Is there any task to move? */
2697 if (busiest_rq->nr_running <= 1)
2700 target_rq = cpu_rq(target_cpu);
2703 * This condition is "impossible", if it occurs
2704 * we need to fix it. Originally reported by
2705 * Bjorn Helgaas on a 128-cpu setup.
2707 BUG_ON(busiest_rq == target_rq);
2709 /* move a task from busiest_rq to target_rq */
2710 double_lock_balance(busiest_rq, target_rq);
2712 /* Search for an sd spanning us and the target CPU. */
2713 for_each_domain(target_cpu, sd) {
2714 if ((sd->flags & SD_LOAD_BALANCE) &&
2715 cpu_isset(busiest_cpu, sd->span))
2720 schedstat_inc(sd, alb_cnt);
2722 if (move_tasks(target_rq, target_cpu, busiest_rq, 1,
2723 RTPRIO_TO_LOAD_WEIGHT(100), sd, SCHED_IDLE,
2725 schedstat_inc(sd, alb_pushed);
2727 schedstat_inc(sd, alb_failed);
2729 spin_unlock(&target_rq->lock);
2733 * rebalance_tick will get called every timer tick, on every CPU.
2735 * It checks each scheduling domain to see if it is due to be balanced,
2736 * and initiates a balancing operation if so.
2738 * Balancing parameters are set up in arch_init_sched_domains.
2741 /* Don't have all balancing operations going off at once: */
2742 static inline unsigned long cpu_offset(int cpu)
2744 return jiffies + cpu * HZ / NR_CPUS;
2748 rebalance_tick(int this_cpu, struct rq *this_rq, enum idle_type idle)
2750 unsigned long this_load, interval, j = cpu_offset(this_cpu);
2751 struct sched_domain *sd;
2754 this_load = this_rq->raw_weighted_load;
2756 /* Update our load: */
2757 for (i = 0, scale = 1; i < 3; i++, scale <<= 1) {
2758 unsigned long old_load, new_load;
2760 old_load = this_rq->cpu_load[i];
2761 new_load = this_load;
2763 * Round up the averaging division if load is increasing. This
2764 * prevents us from getting stuck on 9 if the load is 10, for
2767 if (new_load > old_load)
2768 new_load += scale-1;
2769 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2772 for_each_domain(this_cpu, sd) {
2773 if (!(sd->flags & SD_LOAD_BALANCE))
2776 interval = sd->balance_interval;
2777 if (idle != SCHED_IDLE)
2778 interval *= sd->busy_factor;
2780 /* scale ms to jiffies */
2781 interval = msecs_to_jiffies(interval);
2782 if (unlikely(!interval))
2785 if (j - sd->last_balance >= interval) {
2786 if (load_balance(this_cpu, this_rq, sd, idle)) {
2788 * We've pulled tasks over so either we're no
2789 * longer idle, or one of our SMT siblings is
2794 sd->last_balance += interval;
2800 * on UP we do not need to balance between CPUs:
2802 static inline void rebalance_tick(int cpu, struct rq *rq, enum idle_type idle)
2805 static inline void idle_balance(int cpu, struct rq *rq)
2810 static inline int wake_priority_sleeper(struct rq *rq)
2814 #ifdef CONFIG_SCHED_SMT
2815 spin_lock(&rq->lock);
2817 * If an SMT sibling task has been put to sleep for priority
2818 * reasons reschedule the idle task to see if it can now run.
2820 if (rq->nr_running) {
2821 resched_task(rq->idle);
2824 spin_unlock(&rq->lock);
2829 DEFINE_PER_CPU(struct kernel_stat, kstat);
2831 EXPORT_PER_CPU_SYMBOL(kstat);
2834 * This is called on clock ticks and on context switches.
2835 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2838 update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
2840 p->sched_time += now - max(p->timestamp, rq->timestamp_last_tick);
2844 * Return current->sched_time plus any more ns on the sched_clock
2845 * that have not yet been banked.
2847 unsigned long long current_sched_time(const struct task_struct *p)
2849 unsigned long long ns;
2850 unsigned long flags;
2852 local_irq_save(flags);
2853 ns = max(p->timestamp, task_rq(p)->timestamp_last_tick);
2854 ns = p->sched_time + sched_clock() - ns;
2855 local_irq_restore(flags);
2861 * We place interactive tasks back into the active array, if possible.
2863 * To guarantee that this does not starve expired tasks we ignore the
2864 * interactivity of a task if the first expired task had to wait more
2865 * than a 'reasonable' amount of time. This deadline timeout is
2866 * load-dependent, as the frequency of array switched decreases with
2867 * increasing number of running tasks. We also ignore the interactivity
2868 * if a better static_prio task has expired:
2870 static inline int expired_starving(struct rq *rq)
2872 if (rq->curr->static_prio > rq->best_expired_prio)
2874 if (!STARVATION_LIMIT || !rq->expired_timestamp)
2876 if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
2882 * Account user cpu time to a process.
2883 * @p: the process that the cpu time gets accounted to
2884 * @hardirq_offset: the offset to subtract from hardirq_count()
2885 * @cputime: the cpu time spent in user space since the last update
2887 void account_user_time(struct task_struct *p, cputime_t cputime)
2889 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2892 p->utime = cputime_add(p->utime, cputime);
2894 /* Add user time to cpustat. */
2895 tmp = cputime_to_cputime64(cputime);
2896 if (TASK_NICE(p) > 0)
2897 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2899 cpustat->user = cputime64_add(cpustat->user, tmp);
2903 * Account system cpu time to a process.
2904 * @p: the process that the cpu time gets accounted to
2905 * @hardirq_offset: the offset to subtract from hardirq_count()
2906 * @cputime: the cpu time spent in kernel space since the last update
2908 void account_system_time(struct task_struct *p, int hardirq_offset,
2911 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2912 struct rq *rq = this_rq();
2915 p->stime = cputime_add(p->stime, cputime);
2917 /* Add system time to cpustat. */
2918 tmp = cputime_to_cputime64(cputime);
2919 if (hardirq_count() - hardirq_offset)
2920 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2921 else if (softirq_count())
2922 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2923 else if (p != rq->idle)
2924 cpustat->system = cputime64_add(cpustat->system, tmp);
2925 else if (atomic_read(&rq->nr_iowait) > 0)
2926 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2928 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2929 /* Account for system time used */
2930 acct_update_integrals(p);
2934 * Account for involuntary wait time.
2935 * @p: the process from which the cpu time has been stolen
2936 * @steal: the cpu time spent in involuntary wait
2938 void account_steal_time(struct task_struct *p, cputime_t steal)
2940 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2941 cputime64_t tmp = cputime_to_cputime64(steal);
2942 struct rq *rq = this_rq();
2944 if (p == rq->idle) {
2945 p->stime = cputime_add(p->stime, steal);
2946 if (atomic_read(&rq->nr_iowait) > 0)
2947 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2949 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2951 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2955 * This function gets called by the timer code, with HZ frequency.
2956 * We call it with interrupts disabled.
2958 * It also gets called by the fork code, when changing the parent's
2961 void scheduler_tick(void)
2963 unsigned long long now = sched_clock();
2964 struct task_struct *p = current;
2965 int cpu = smp_processor_id();
2966 struct rq *rq = cpu_rq(cpu);
2968 update_cpu_clock(p, rq, now);
2970 rq->timestamp_last_tick = now;
2972 if (p == rq->idle) {
2973 if (wake_priority_sleeper(rq))
2975 rebalance_tick(cpu, rq, SCHED_IDLE);
2979 /* Task might have expired already, but not scheduled off yet */
2980 if (p->array != rq->active) {
2981 set_tsk_need_resched(p);
2984 spin_lock(&rq->lock);
2986 * The task was running during this tick - update the
2987 * time slice counter. Note: we do not update a thread's
2988 * priority until it either goes to sleep or uses up its
2989 * timeslice. This makes it possible for interactive tasks
2990 * to use up their timeslices at their highest priority levels.
2994 * RR tasks need a special form of timeslice management.
2995 * FIFO tasks have no timeslices.
2997 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2998 p->time_slice = task_timeslice(p);
2999 p->first_time_slice = 0;
3000 set_tsk_need_resched(p);
3002 /* put it at the end of the queue: */
3003 requeue_task(p, rq->active);
3007 if (!--p->time_slice) {
3008 dequeue_task(p, rq->active);
3009 set_tsk_need_resched(p);
3010 p->prio = effective_prio(p);
3011 p->time_slice = task_timeslice(p);
3012 p->first_time_slice = 0;
3014 if (!rq->expired_timestamp)
3015 rq->expired_timestamp = jiffies;
3016 if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
3017 enqueue_task(p, rq->expired);
3018 if (p->static_prio < rq->best_expired_prio)
3019 rq->best_expired_prio = p->static_prio;
3021 enqueue_task(p, rq->active);
3024 * Prevent a too long timeslice allowing a task to monopolize
3025 * the CPU. We do this by splitting up the timeslice into
3028 * Note: this does not mean the task's timeslices expire or
3029 * get lost in any way, they just might be preempted by
3030 * another task of equal priority. (one with higher
3031 * priority would have preempted this task already.) We
3032 * requeue this task to the end of the list on this priority
3033 * level, which is in essence a round-robin of tasks with
3036 * This only applies to tasks in the interactive
3037 * delta range with at least TIMESLICE_GRANULARITY to requeue.
3039 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
3040 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
3041 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
3042 (p->array == rq->active)) {
3044 requeue_task(p, rq->active);
3045 set_tsk_need_resched(p);
3049 spin_unlock(&rq->lock);
3051 rebalance_tick(cpu, rq, NOT_IDLE);
3054 #ifdef CONFIG_SCHED_SMT
3055 static inline void wakeup_busy_runqueue(struct rq *rq)
3057 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
3058 if (rq->curr == rq->idle && rq->nr_running)
3059 resched_task(rq->idle);
3063 * Called with interrupt disabled and this_rq's runqueue locked.
3065 static void wake_sleeping_dependent(int this_cpu)
3067 struct sched_domain *tmp, *sd = NULL;
3070 for_each_domain(this_cpu, tmp) {
3071 if (tmp->flags & SD_SHARE_CPUPOWER) {
3080 for_each_cpu_mask(i, sd->span) {
3081 struct rq *smt_rq = cpu_rq(i);
3085 if (unlikely(!spin_trylock(&smt_rq->lock)))
3088 wakeup_busy_runqueue(smt_rq);
3089 spin_unlock(&smt_rq->lock);
3094 * number of 'lost' timeslices this task wont be able to fully
3095 * utilize, if another task runs on a sibling. This models the
3096 * slowdown effect of other tasks running on siblings:
3098 static inline unsigned long
3099 smt_slice(struct task_struct *p, struct sched_domain *sd)
3101 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
3105 * To minimise lock contention and not have to drop this_rq's runlock we only
3106 * trylock the sibling runqueues and bypass those runqueues if we fail to
3107 * acquire their lock. As we only trylock the normal locking order does not
3108 * need to be obeyed.
3111 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3113 struct sched_domain *tmp, *sd = NULL;
3116 /* kernel/rt threads do not participate in dependent sleeping */
3117 if (!p->mm || rt_task(p))
3120 for_each_domain(this_cpu, tmp) {
3121 if (tmp->flags & SD_SHARE_CPUPOWER) {
3130 for_each_cpu_mask(i, sd->span) {
3131 struct task_struct *smt_curr;
3138 if (unlikely(!spin_trylock(&smt_rq->lock)))
3141 smt_curr = smt_rq->curr;
3147 * If a user task with lower static priority than the
3148 * running task on the SMT sibling is trying to schedule,
3149 * delay it till there is proportionately less timeslice
3150 * left of the sibling task to prevent a lower priority
3151 * task from using an unfair proportion of the
3152 * physical cpu's resources. -ck
3154 if (rt_task(smt_curr)) {
3156 * With real time tasks we run non-rt tasks only
3157 * per_cpu_gain% of the time.
3159 if ((jiffies % DEF_TIMESLICE) >
3160 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
3163 if (smt_curr->static_prio < p->static_prio &&
3164 !TASK_PREEMPTS_CURR(p, smt_rq) &&
3165 smt_slice(smt_curr, sd) > task_timeslice(p))
3169 spin_unlock(&smt_rq->lock);
3174 static inline void wake_sleeping_dependent(int this_cpu)
3178 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3184 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3186 void fastcall add_preempt_count(int val)
3191 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3193 preempt_count() += val;
3195 * Spinlock count overflowing soon?
3197 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
3199 EXPORT_SYMBOL(add_preempt_count);
3201 void fastcall sub_preempt_count(int val)
3206 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3209 * Is the spinlock portion underflowing?
3211 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3212 !(preempt_count() & PREEMPT_MASK)))
3215 preempt_count() -= val;
3217 EXPORT_SYMBOL(sub_preempt_count);
3221 static inline int interactive_sleep(enum sleep_type sleep_type)
3223 return (sleep_type == SLEEP_INTERACTIVE ||
3224 sleep_type == SLEEP_INTERRUPTED);
3228 * schedule() is the main scheduler function.
3230 asmlinkage void __sched schedule(void)
3232 struct task_struct *prev, *next;
3233 struct prio_array *array;
3234 struct list_head *queue;
3235 unsigned long long now;
3236 unsigned long run_time;
3237 int cpu, idx, new_prio;
3242 * Test if we are atomic. Since do_exit() needs to call into
3243 * schedule() atomically, we ignore that path for now.
3244 * Otherwise, whine if we are scheduling when we should not be.
3246 if (unlikely(in_atomic() && !current->exit_state)) {
3247 printk(KERN_ERR "BUG: scheduling while atomic: "
3249 current->comm, preempt_count(), current->pid);
3252 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3257 release_kernel_lock(prev);
3258 need_resched_nonpreemptible:
3262 * The idle thread is not allowed to schedule!
3263 * Remove this check after it has been exercised a bit.
3265 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
3266 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3270 schedstat_inc(rq, sched_cnt);
3271 now = sched_clock();
3272 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
3273 run_time = now - prev->timestamp;
3274 if (unlikely((long long)(now - prev->timestamp) < 0))
3277 run_time = NS_MAX_SLEEP_AVG;
3280 * Tasks charged proportionately less run_time at high sleep_avg to
3281 * delay them losing their interactive status
3283 run_time /= (CURRENT_BONUS(prev) ? : 1);
3285 spin_lock_irq(&rq->lock);
3287 if (unlikely(prev->flags & PF_DEAD))
3288 prev->state = EXIT_DEAD;
3290 switch_count = &prev->nivcsw;
3291 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3292 switch_count = &prev->nvcsw;
3293 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3294 unlikely(signal_pending(prev))))
3295 prev->state = TASK_RUNNING;
3297 if (prev->state == TASK_UNINTERRUPTIBLE)
3298 rq->nr_uninterruptible++;
3299 deactivate_task(prev, rq);
3303 cpu = smp_processor_id();
3304 if (unlikely(!rq->nr_running)) {
3305 idle_balance(cpu, rq);
3306 if (!rq->nr_running) {
3308 rq->expired_timestamp = 0;
3309 wake_sleeping_dependent(cpu);
3315 if (unlikely(!array->nr_active)) {
3317 * Switch the active and expired arrays.
3319 schedstat_inc(rq, sched_switch);
3320 rq->active = rq->expired;
3321 rq->expired = array;
3323 rq->expired_timestamp = 0;
3324 rq->best_expired_prio = MAX_PRIO;
3327 idx = sched_find_first_bit(array->bitmap);
3328 queue = array->queue + idx;
3329 next = list_entry(queue->next, struct task_struct, run_list);
3331 if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3332 unsigned long long delta = now - next->timestamp;
3333 if (unlikely((long long)(now - next->timestamp) < 0))
3336 if (next->sleep_type == SLEEP_INTERACTIVE)
3337 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3339 array = next->array;
3340 new_prio = recalc_task_prio(next, next->timestamp + delta);
3342 if (unlikely(next->prio != new_prio)) {
3343 dequeue_task(next, array);
3344 next->prio = new_prio;
3345 enqueue_task(next, array);
3348 next->sleep_type = SLEEP_NORMAL;
3349 if (dependent_sleeper(cpu, rq, next))
3352 if (next == rq->idle)
3353 schedstat_inc(rq, sched_goidle);
3355 prefetch_stack(next);
3356 clear_tsk_need_resched(prev);
3357 rcu_qsctr_inc(task_cpu(prev));
3359 update_cpu_clock(prev, rq, now);
3361 prev->sleep_avg -= run_time;
3362 if ((long)prev->sleep_avg <= 0)
3363 prev->sleep_avg = 0;
3364 prev->timestamp = prev->last_ran = now;
3366 sched_info_switch(prev, next);
3367 if (likely(prev != next)) {
3368 next->timestamp = now;
3373 prepare_task_switch(rq, next);
3374 prev = context_switch(rq, prev, next);
3377 * this_rq must be evaluated again because prev may have moved
3378 * CPUs since it called schedule(), thus the 'rq' on its stack
3379 * frame will be invalid.
3381 finish_task_switch(this_rq(), prev);
3383 spin_unlock_irq(&rq->lock);
3386 if (unlikely(reacquire_kernel_lock(prev) < 0))
3387 goto need_resched_nonpreemptible;
3388 preempt_enable_no_resched();
3389 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3392 EXPORT_SYMBOL(schedule);
3394 #ifdef CONFIG_PREEMPT
3396 * this is the entry point to schedule() from in-kernel preemption
3397 * off of preempt_enable. Kernel preemptions off return from interrupt
3398 * occur there and call schedule directly.
3400 asmlinkage void __sched preempt_schedule(void)
3402 struct thread_info *ti = current_thread_info();
3403 #ifdef CONFIG_PREEMPT_BKL
3404 struct task_struct *task = current;
3405 int saved_lock_depth;
3408 * If there is a non-zero preempt_count or interrupts are disabled,
3409 * we do not want to preempt the current task. Just return..
3411 if (unlikely(ti->preempt_count || irqs_disabled()))
3415 add_preempt_count(PREEMPT_ACTIVE);
3417 * We keep the big kernel semaphore locked, but we
3418 * clear ->lock_depth so that schedule() doesnt
3419 * auto-release the semaphore:
3421 #ifdef CONFIG_PREEMPT_BKL
3422 saved_lock_depth = task->lock_depth;
3423 task->lock_depth = -1;
3426 #ifdef CONFIG_PREEMPT_BKL
3427 task->lock_depth = saved_lock_depth;
3429 sub_preempt_count(PREEMPT_ACTIVE);
3431 /* we could miss a preemption opportunity between schedule and now */
3433 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3436 EXPORT_SYMBOL(preempt_schedule);
3439 * this is the entry point to schedule() from kernel preemption
3440 * off of irq context.
3441 * Note, that this is called and return with irqs disabled. This will
3442 * protect us against recursive calling from irq.
3444 asmlinkage void __sched preempt_schedule_irq(void)
3446 struct thread_info *ti = current_thread_info();
3447 #ifdef CONFIG_PREEMPT_BKL
3448 struct task_struct *task = current;
3449 int saved_lock_depth;
3451 /* Catch callers which need to be fixed */
3452 BUG_ON(ti->preempt_count || !irqs_disabled());
3455 add_preempt_count(PREEMPT_ACTIVE);
3457 * We keep the big kernel semaphore locked, but we
3458 * clear ->lock_depth so that schedule() doesnt
3459 * auto-release the semaphore:
3461 #ifdef CONFIG_PREEMPT_BKL
3462 saved_lock_depth = task->lock_depth;
3463 task->lock_depth = -1;
3467 local_irq_disable();
3468 #ifdef CONFIG_PREEMPT_BKL
3469 task->lock_depth = saved_lock_depth;
3471 sub_preempt_count(PREEMPT_ACTIVE);
3473 /* we could miss a preemption opportunity between schedule and now */
3475 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3479 #endif /* CONFIG_PREEMPT */
3481 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3484 return try_to_wake_up(curr->private, mode, sync);
3486 EXPORT_SYMBOL(default_wake_function);
3489 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3490 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3491 * number) then we wake all the non-exclusive tasks and one exclusive task.
3493 * There are circumstances in which we can try to wake a task which has already
3494 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3495 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3497 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3498 int nr_exclusive, int sync, void *key)
3500 struct list_head *tmp, *next;
3502 list_for_each_safe(tmp, next, &q->task_list) {
3503 wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
3504 unsigned flags = curr->flags;
3506 if (curr->func(curr, mode, sync, key) &&
3507 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3513 * __wake_up - wake up threads blocked on a waitqueue.
3515 * @mode: which threads
3516 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3517 * @key: is directly passed to the wakeup function
3519 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3520 int nr_exclusive, void *key)
3522 unsigned long flags;
3524 spin_lock_irqsave(&q->lock, flags);
3525 __wake_up_common(q, mode, nr_exclusive, 0, key);
3526 spin_unlock_irqrestore(&q->lock, flags);
3528 EXPORT_SYMBOL(__wake_up);
3531 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3533 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3535 __wake_up_common(q, mode, 1, 0, NULL);
3539 * __wake_up_sync - wake up threads blocked on a waitqueue.
3541 * @mode: which threads
3542 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3544 * The sync wakeup differs that the waker knows that it will schedule
3545 * away soon, so while the target thread will be woken up, it will not
3546 * be migrated to another CPU - ie. the two threads are 'synchronized'
3547 * with each other. This can prevent needless bouncing between CPUs.
3549 * On UP it can prevent extra preemption.
3552 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3554 unsigned long flags;
3560 if (unlikely(!nr_exclusive))
3563 spin_lock_irqsave(&q->lock, flags);
3564 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3565 spin_unlock_irqrestore(&q->lock, flags);
3567 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3569 void fastcall complete(struct completion *x)
3571 unsigned long flags;
3573 spin_lock_irqsave(&x->wait.lock, flags);
3575 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3577 spin_unlock_irqrestore(&x->wait.lock, flags);
3579 EXPORT_SYMBOL(complete);
3581 void fastcall complete_all(struct completion *x)
3583 unsigned long flags;
3585 spin_lock_irqsave(&x->wait.lock, flags);
3586 x->done += UINT_MAX/2;
3587 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3589 spin_unlock_irqrestore(&x->wait.lock, flags);
3591 EXPORT_SYMBOL(complete_all);
3593 void fastcall __sched wait_for_completion(struct completion *x)
3597 spin_lock_irq(&x->wait.lock);
3599 DECLARE_WAITQUEUE(wait, current);
3601 wait.flags |= WQ_FLAG_EXCLUSIVE;
3602 __add_wait_queue_tail(&x->wait, &wait);
3604 __set_current_state(TASK_UNINTERRUPTIBLE);
3605 spin_unlock_irq(&x->wait.lock);
3607 spin_lock_irq(&x->wait.lock);
3609 __remove_wait_queue(&x->wait, &wait);
3612 spin_unlock_irq(&x->wait.lock);
3614 EXPORT_SYMBOL(wait_for_completion);
3616 unsigned long fastcall __sched
3617 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3621 spin_lock_irq(&x->wait.lock);
3623 DECLARE_WAITQUEUE(wait, current);
3625 wait.flags |= WQ_FLAG_EXCLUSIVE;
3626 __add_wait_queue_tail(&x->wait, &wait);
3628 __set_current_state(TASK_UNINTERRUPTIBLE);
3629 spin_unlock_irq(&x->wait.lock);
3630 timeout = schedule_timeout(timeout);
3631 spin_lock_irq(&x->wait.lock);
3633 __remove_wait_queue(&x->wait, &wait);
3637 __remove_wait_queue(&x->wait, &wait);
3641 spin_unlock_irq(&x->wait.lock);
3644 EXPORT_SYMBOL(wait_for_completion_timeout);
3646 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3652 spin_lock_irq(&x->wait.lock);
3654 DECLARE_WAITQUEUE(wait, current);
3656 wait.flags |= WQ_FLAG_EXCLUSIVE;
3657 __add_wait_queue_tail(&x->wait, &wait);
3659 if (signal_pending(current)) {
3661 __remove_wait_queue(&x->wait, &wait);
3664 __set_current_state(TASK_INTERRUPTIBLE);
3665 spin_unlock_irq(&x->wait.lock);
3667 spin_lock_irq(&x->wait.lock);
3669 __remove_wait_queue(&x->wait, &wait);
3673 spin_unlock_irq(&x->wait.lock);
3677 EXPORT_SYMBOL(wait_for_completion_interruptible);
3679 unsigned long fastcall __sched
3680 wait_for_completion_interruptible_timeout(struct completion *x,
3681 unsigned long timeout)
3685 spin_lock_irq(&x->wait.lock);
3687 DECLARE_WAITQUEUE(wait, current);
3689 wait.flags |= WQ_FLAG_EXCLUSIVE;
3690 __add_wait_queue_tail(&x->wait, &wait);
3692 if (signal_pending(current)) {
3693 timeout = -ERESTARTSYS;
3694 __remove_wait_queue(&x->wait, &wait);
3697 __set_current_state(TASK_INTERRUPTIBLE);
3698 spin_unlock_irq(&x->wait.lock);
3699 timeout = schedule_timeout(timeout);
3700 spin_lock_irq(&x->wait.lock);
3702 __remove_wait_queue(&x->wait, &wait);
3706 __remove_wait_queue(&x->wait, &wait);
3710 spin_unlock_irq(&x->wait.lock);
3713 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3716 #define SLEEP_ON_VAR \
3717 unsigned long flags; \
3718 wait_queue_t wait; \
3719 init_waitqueue_entry(&wait, current);
3721 #define SLEEP_ON_HEAD \
3722 spin_lock_irqsave(&q->lock,flags); \
3723 __add_wait_queue(q, &wait); \
3724 spin_unlock(&q->lock);
3726 #define SLEEP_ON_TAIL \
3727 spin_lock_irq(&q->lock); \
3728 __remove_wait_queue(q, &wait); \
3729 spin_unlock_irqrestore(&q->lock, flags);
3731 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3735 current->state = TASK_INTERRUPTIBLE;
3741 EXPORT_SYMBOL(interruptible_sleep_on);
3743 long fastcall __sched
3744 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3748 current->state = TASK_INTERRUPTIBLE;
3751 timeout = schedule_timeout(timeout);
3756 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3758 void fastcall __sched sleep_on(wait_queue_head_t *q)
3762 current->state = TASK_UNINTERRUPTIBLE;
3768 EXPORT_SYMBOL(sleep_on);
3770 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3774 current->state = TASK_UNINTERRUPTIBLE;
3777 timeout = schedule_timeout(timeout);
3783 EXPORT_SYMBOL(sleep_on_timeout);
3785 #ifdef CONFIG_RT_MUTEXES
3788 * rt_mutex_setprio - set the current priority of a task
3790 * @prio: prio value (kernel-internal form)
3792 * This function changes the 'effective' priority of a task. It does
3793 * not touch ->normal_prio like __setscheduler().
3795 * Used by the rt_mutex code to implement priority inheritance logic.
3797 void rt_mutex_setprio(struct task_struct *p, int prio)
3799 struct prio_array *array;
3800 unsigned long flags;
3804 BUG_ON(prio < 0 || prio > MAX_PRIO);
3806 rq = task_rq_lock(p, &flags);
3811 dequeue_task(p, array);
3816 * If changing to an RT priority then queue it
3817 * in the active array!
3821 enqueue_task(p, array);
3823 * Reschedule if we are currently running on this runqueue and
3824 * our priority decreased, or if we are not currently running on
3825 * this runqueue and our priority is higher than the current's
3827 if (task_running(rq, p)) {
3828 if (p->prio > oldprio)
3829 resched_task(rq->curr);
3830 } else if (TASK_PREEMPTS_CURR(p, rq))
3831 resched_task(rq->curr);
3833 task_rq_unlock(rq, &flags);
3838 void set_user_nice(struct task_struct *p, long nice)
3840 struct prio_array *array;
3841 int old_prio, delta;
3842 unsigned long flags;
3845 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3848 * We have to be careful, if called from sys_setpriority(),
3849 * the task might be in the middle of scheduling on another CPU.
3851 rq = task_rq_lock(p, &flags);
3853 * The RT priorities are set via sched_setscheduler(), but we still
3854 * allow the 'normal' nice value to be set - but as expected
3855 * it wont have any effect on scheduling until the task is
3856 * not SCHED_NORMAL/SCHED_BATCH:
3858 if (has_rt_policy(p)) {
3859 p->static_prio = NICE_TO_PRIO(nice);
3864 dequeue_task(p, array);
3865 dec_raw_weighted_load(rq, p);
3868 p->static_prio = NICE_TO_PRIO(nice);
3871 p->prio = effective_prio(p);
3872 delta = p->prio - old_prio;
3875 enqueue_task(p, array);
3876 inc_raw_weighted_load(rq, p);
3878 * If the task increased its priority or is running and
3879 * lowered its priority, then reschedule its CPU:
3881 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3882 resched_task(rq->curr);
3885 task_rq_unlock(rq, &flags);
3887 EXPORT_SYMBOL(set_user_nice);
3890 * can_nice - check if a task can reduce its nice value
3894 int can_nice(const struct task_struct *p, const int nice)
3896 /* convert nice value [19,-20] to rlimit style value [1,40] */
3897 int nice_rlim = 20 - nice;
3899 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3900 capable(CAP_SYS_NICE));
3903 #ifdef __ARCH_WANT_SYS_NICE
3906 * sys_nice - change the priority of the current process.
3907 * @increment: priority increment
3909 * sys_setpriority is a more generic, but much slower function that
3910 * does similar things.
3912 asmlinkage long sys_nice(int increment)
3917 * Setpriority might change our priority at the same moment.
3918 * We don't have to worry. Conceptually one call occurs first
3919 * and we have a single winner.
3921 if (increment < -40)
3926 nice = PRIO_TO_NICE(current->static_prio) + increment;
3932 if (increment < 0 && !can_nice(current, nice))
3935 retval = security_task_setnice(current, nice);
3939 set_user_nice(current, nice);
3946 * task_prio - return the priority value of a given task.
3947 * @p: the task in question.
3949 * This is the priority value as seen by users in /proc.
3950 * RT tasks are offset by -200. Normal tasks are centered
3951 * around 0, value goes from -16 to +15.
3953 int task_prio(const struct task_struct *p)
3955 return p->prio - MAX_RT_PRIO;
3959 * task_nice - return the nice value of a given task.
3960 * @p: the task in question.
3962 int task_nice(const struct task_struct *p)
3964 return TASK_NICE(p);
3966 EXPORT_SYMBOL_GPL(task_nice);
3969 * idle_cpu - is a given cpu idle currently?
3970 * @cpu: the processor in question.
3972 int idle_cpu(int cpu)
3974 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3978 * idle_task - return the idle task for a given cpu.
3979 * @cpu: the processor in question.
3981 struct task_struct *idle_task(int cpu)
3983 return cpu_rq(cpu)->idle;
3987 * find_process_by_pid - find a process with a matching PID value.
3988 * @pid: the pid in question.
3990 static inline struct task_struct *find_process_by_pid(pid_t pid)
3992 return pid ? find_task_by_pid(pid) : current;
3995 /* Actually do priority change: must hold rq lock. */
3996 static void __setscheduler(struct task_struct *p, int policy, int prio)
4001 p->rt_priority = prio;
4002 p->normal_prio = normal_prio(p);
4003 /* we are holding p->pi_lock already */
4004 p->prio = rt_mutex_getprio(p);
4006 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
4008 if (policy == SCHED_BATCH)
4014 * sched_setscheduler - change the scheduling policy and/or RT priority of
4016 * @p: the task in question.
4017 * @policy: new policy.
4018 * @param: structure containing the new RT priority.
4020 int sched_setscheduler(struct task_struct *p, int policy,
4021 struct sched_param *param)
4023 int retval, oldprio, oldpolicy = -1;
4024 struct prio_array *array;
4025 unsigned long flags;
4028 /* may grab non-irq protected spin_locks */
4029 BUG_ON(in_interrupt());
4031 /* double check policy once rq lock held */
4033 policy = oldpolicy = p->policy;
4034 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4035 policy != SCHED_NORMAL && policy != SCHED_BATCH)
4038 * Valid priorities for SCHED_FIFO and SCHED_RR are
4039 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
4042 if (param->sched_priority < 0 ||
4043 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4044 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4046 if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
4047 != (param->sched_priority == 0))
4051 * Allow unprivileged RT tasks to decrease priority:
4053 if (!capable(CAP_SYS_NICE)) {
4055 * can't change policy, except between SCHED_NORMAL
4058 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
4059 (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
4060 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4062 /* can't increase priority */
4063 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
4064 param->sched_priority > p->rt_priority &&
4065 param->sched_priority >
4066 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4068 /* can't change other user's priorities */
4069 if ((current->euid != p->euid) &&
4070 (current->euid != p->uid))
4074 retval = security_task_setscheduler(p, policy, param);
4078 * make sure no PI-waiters arrive (or leave) while we are
4079 * changing the priority of the task:
4081 spin_lock_irqsave(&p->pi_lock, flags);
4083 * To be able to change p->policy safely, the apropriate
4084 * runqueue lock must be held.
4086 rq = __task_rq_lock(p);
4087 /* recheck policy now with rq lock held */
4088 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4089 policy = oldpolicy = -1;
4090 __task_rq_unlock(rq);
4091 spin_unlock_irqrestore(&p->pi_lock, flags);
4096 deactivate_task(p, rq);
4098 __setscheduler(p, policy, param->sched_priority);
4100 __activate_task(p, rq);
4102 * Reschedule if we are currently running on this runqueue and
4103 * our priority decreased, or if we are not currently running on
4104 * this runqueue and our priority is higher than the current's
4106 if (task_running(rq, p)) {
4107 if (p->prio > oldprio)
4108 resched_task(rq->curr);
4109 } else if (TASK_PREEMPTS_CURR(p, rq))
4110 resched_task(rq->curr);
4112 __task_rq_unlock(rq);
4113 spin_unlock_irqrestore(&p->pi_lock, flags);
4115 rt_mutex_adjust_pi(p);
4119 EXPORT_SYMBOL_GPL(sched_setscheduler);
4122 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4124 struct sched_param lparam;
4125 struct task_struct *p;
4128 if (!param || pid < 0)
4130 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4132 read_lock_irq(&tasklist_lock);
4133 p = find_process_by_pid(pid);
4135 read_unlock_irq(&tasklist_lock);
4139 read_unlock_irq(&tasklist_lock);
4140 retval = sched_setscheduler(p, policy, &lparam);
4147 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4148 * @pid: the pid in question.
4149 * @policy: new policy.
4150 * @param: structure containing the new RT priority.
4152 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4153 struct sched_param __user *param)
4155 /* negative values for policy are not valid */
4159 return do_sched_setscheduler(pid, policy, param);
4163 * sys_sched_setparam - set/change the RT priority of a thread
4164 * @pid: the pid in question.
4165 * @param: structure containing the new RT priority.
4167 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4169 return do_sched_setscheduler(pid, -1, param);
4173 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4174 * @pid: the pid in question.
4176 asmlinkage long sys_sched_getscheduler(pid_t pid)
4178 struct task_struct *p;
4179 int retval = -EINVAL;
4185 read_lock(&tasklist_lock);
4186 p = find_process_by_pid(pid);
4188 retval = security_task_getscheduler(p);
4192 read_unlock(&tasklist_lock);
4199 * sys_sched_getscheduler - get the RT priority of a thread
4200 * @pid: the pid in question.
4201 * @param: structure containing the RT priority.
4203 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4205 struct sched_param lp;
4206 struct task_struct *p;
4207 int retval = -EINVAL;
4209 if (!param || pid < 0)
4212 read_lock(&tasklist_lock);
4213 p = find_process_by_pid(pid);
4218 retval = security_task_getscheduler(p);
4222 lp.sched_priority = p->rt_priority;
4223 read_unlock(&tasklist_lock);
4226 * This one might sleep, we cannot do it with a spinlock held ...
4228 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4234 read_unlock(&tasklist_lock);
4238 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4240 cpumask_t cpus_allowed;
4241 struct task_struct *p;
4245 read_lock(&tasklist_lock);
4247 p = find_process_by_pid(pid);
4249 read_unlock(&tasklist_lock);
4250 unlock_cpu_hotplug();
4255 * It is not safe to call set_cpus_allowed with the
4256 * tasklist_lock held. We will bump the task_struct's
4257 * usage count and then drop tasklist_lock.
4260 read_unlock(&tasklist_lock);
4263 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4264 !capable(CAP_SYS_NICE))
4267 retval = security_task_setscheduler(p, 0, NULL);
4271 cpus_allowed = cpuset_cpus_allowed(p);
4272 cpus_and(new_mask, new_mask, cpus_allowed);
4273 retval = set_cpus_allowed(p, new_mask);
4277 unlock_cpu_hotplug();
4281 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4282 cpumask_t *new_mask)
4284 if (len < sizeof(cpumask_t)) {
4285 memset(new_mask, 0, sizeof(cpumask_t));
4286 } else if (len > sizeof(cpumask_t)) {
4287 len = sizeof(cpumask_t);
4289 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4293 * sys_sched_setaffinity - set the cpu affinity of a process
4294 * @pid: pid of the process
4295 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4296 * @user_mask_ptr: user-space pointer to the new cpu mask
4298 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4299 unsigned long __user *user_mask_ptr)
4304 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4308 return sched_setaffinity(pid, new_mask);
4312 * Represents all cpu's present in the system
4313 * In systems capable of hotplug, this map could dynamically grow
4314 * as new cpu's are detected in the system via any platform specific
4315 * method, such as ACPI for e.g.
4318 cpumask_t cpu_present_map __read_mostly;
4319 EXPORT_SYMBOL(cpu_present_map);
4322 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4323 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4326 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4328 struct task_struct *p;
4332 read_lock(&tasklist_lock);
4335 p = find_process_by_pid(pid);
4339 retval = security_task_getscheduler(p);
4343 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4346 read_unlock(&tasklist_lock);
4347 unlock_cpu_hotplug();
4355 * sys_sched_getaffinity - get the cpu affinity of a process
4356 * @pid: pid of the process
4357 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4358 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4360 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4361 unsigned long __user *user_mask_ptr)
4366 if (len < sizeof(cpumask_t))
4369 ret = sched_getaffinity(pid, &mask);
4373 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4376 return sizeof(cpumask_t);
4380 * sys_sched_yield - yield the current processor to other threads.
4382 * this function yields the current CPU by moving the calling thread
4383 * to the expired array. If there are no other threads running on this
4384 * CPU then this function will return.
4386 asmlinkage long sys_sched_yield(void)
4388 struct rq *rq = this_rq_lock();
4389 struct prio_array *array = current->array, *target = rq->expired;
4391 schedstat_inc(rq, yld_cnt);
4393 * We implement yielding by moving the task into the expired
4396 * (special rule: RT tasks will just roundrobin in the active
4399 if (rt_task(current))
4400 target = rq->active;
4402 if (array->nr_active == 1) {
4403 schedstat_inc(rq, yld_act_empty);
4404 if (!rq->expired->nr_active)
4405 schedstat_inc(rq, yld_both_empty);
4406 } else if (!rq->expired->nr_active)
4407 schedstat_inc(rq, yld_exp_empty);
4409 if (array != target) {
4410 dequeue_task(current, array);
4411 enqueue_task(current, target);
4414 * requeue_task is cheaper so perform that if possible.
4416 requeue_task(current, array);
4419 * Since we are going to call schedule() anyway, there's
4420 * no need to preempt or enable interrupts:
4422 __release(rq->lock);
4423 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4424 _raw_spin_unlock(&rq->lock);
4425 preempt_enable_no_resched();
4432 static inline int __resched_legal(void)
4434 if (unlikely(preempt_count()))
4436 if (unlikely(system_state != SYSTEM_RUNNING))
4441 static void __cond_resched(void)
4443 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4444 __might_sleep(__FILE__, __LINE__);
4447 * The BKS might be reacquired before we have dropped
4448 * PREEMPT_ACTIVE, which could trigger a second
4449 * cond_resched() call.
4452 add_preempt_count(PREEMPT_ACTIVE);
4454 sub_preempt_count(PREEMPT_ACTIVE);
4455 } while (need_resched());
4458 int __sched cond_resched(void)
4460 if (need_resched() && __resched_legal()) {
4466 EXPORT_SYMBOL(cond_resched);
4469 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4470 * call schedule, and on return reacquire the lock.
4472 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4473 * operations here to prevent schedule() from being called twice (once via
4474 * spin_unlock(), once by hand).
4476 int cond_resched_lock(spinlock_t *lock)
4480 if (need_lockbreak(lock)) {
4486 if (need_resched() && __resched_legal()) {
4487 spin_release(&lock->dep_map, 1, _THIS_IP_);
4488 _raw_spin_unlock(lock);
4489 preempt_enable_no_resched();
4496 EXPORT_SYMBOL(cond_resched_lock);
4498 int __sched cond_resched_softirq(void)
4500 BUG_ON(!in_softirq());
4502 if (need_resched() && __resched_legal()) {
4503 raw_local_irq_disable();
4505 raw_local_irq_enable();
4512 EXPORT_SYMBOL(cond_resched_softirq);
4515 * yield - yield the current processor to other threads.
4517 * this is a shortcut for kernel-space yielding - it marks the
4518 * thread runnable and calls sys_sched_yield().
4520 void __sched yield(void)
4522 set_current_state(TASK_RUNNING);
4525 EXPORT_SYMBOL(yield);
4528 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4529 * that process accounting knows that this is a task in IO wait state.
4531 * But don't do that if it is a deliberate, throttling IO wait (this task
4532 * has set its backing_dev_info: the queue against which it should throttle)
4534 void __sched io_schedule(void)
4536 struct rq *rq = &__raw_get_cpu_var(runqueues);
4538 delayacct_blkio_start();
4539 atomic_inc(&rq->nr_iowait);
4541 atomic_dec(&rq->nr_iowait);
4542 delayacct_blkio_end();
4544 EXPORT_SYMBOL(io_schedule);
4546 long __sched io_schedule_timeout(long timeout)
4548 struct rq *rq = &__raw_get_cpu_var(runqueues);
4551 delayacct_blkio_start();
4552 atomic_inc(&rq->nr_iowait);
4553 ret = schedule_timeout(timeout);
4554 atomic_dec(&rq->nr_iowait);
4555 delayacct_blkio_end();
4560 * sys_sched_get_priority_max - return maximum RT priority.
4561 * @policy: scheduling class.
4563 * this syscall returns the maximum rt_priority that can be used
4564 * by a given scheduling class.
4566 asmlinkage long sys_sched_get_priority_max(int policy)
4573 ret = MAX_USER_RT_PRIO-1;
4584 * sys_sched_get_priority_min - return minimum RT priority.
4585 * @policy: scheduling class.
4587 * this syscall returns the minimum rt_priority that can be used
4588 * by a given scheduling class.
4590 asmlinkage long sys_sched_get_priority_min(int policy)
4607 * sys_sched_rr_get_interval - return the default timeslice of a process.
4608 * @pid: pid of the process.
4609 * @interval: userspace pointer to the timeslice value.
4611 * this syscall writes the default timeslice value of a given process
4612 * into the user-space timespec buffer. A value of '0' means infinity.
4615 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4617 struct task_struct *p;
4618 int retval = -EINVAL;
4625 read_lock(&tasklist_lock);
4626 p = find_process_by_pid(pid);
4630 retval = security_task_getscheduler(p);
4634 jiffies_to_timespec(p->policy == SCHED_FIFO ?
4635 0 : task_timeslice(p), &t);
4636 read_unlock(&tasklist_lock);
4637 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4641 read_unlock(&tasklist_lock);
4645 static inline struct task_struct *eldest_child(struct task_struct *p)
4647 if (list_empty(&p->children))
4649 return list_entry(p->children.next,struct task_struct,sibling);
4652 static inline struct task_struct *older_sibling(struct task_struct *p)
4654 if (p->sibling.prev==&p->parent->children)
4656 return list_entry(p->sibling.prev,struct task_struct,sibling);
4659 static inline struct task_struct *younger_sibling(struct task_struct *p)
4661 if (p->sibling.next==&p->parent->children)
4663 return list_entry(p->sibling.next,struct task_struct,sibling);
4666 static const char stat_nam[] = "RSDTtZX";
4668 static void show_task(struct task_struct *p)
4670 struct task_struct *relative;
4671 unsigned long free = 0;
4674 state = p->state ? __ffs(p->state) + 1 : 0;
4675 printk("%-13.13s %c", p->comm,
4676 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4677 #if (BITS_PER_LONG == 32)
4678 if (state == TASK_RUNNING)
4679 printk(" running ");
4681 printk(" %08lX ", thread_saved_pc(p));
4683 if (state == TASK_RUNNING)
4684 printk(" running task ");
4686 printk(" %016lx ", thread_saved_pc(p));
4688 #ifdef CONFIG_DEBUG_STACK_USAGE
4690 unsigned long *n = end_of_stack(p);
4693 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4696 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4697 if ((relative = eldest_child(p)))
4698 printk("%5d ", relative->pid);
4701 if ((relative = younger_sibling(p)))
4702 printk("%7d", relative->pid);
4705 if ((relative = older_sibling(p)))
4706 printk(" %5d", relative->pid);
4710 printk(" (L-TLB)\n");
4712 printk(" (NOTLB)\n");
4714 if (state != TASK_RUNNING)
4715 show_stack(p, NULL);
4718 void show_state(void)
4720 struct task_struct *g, *p;
4722 #if (BITS_PER_LONG == 32)
4725 printk(" task PC pid father child younger older\n");
4729 printk(" task PC pid father child younger older\n");
4731 read_lock(&tasklist_lock);
4732 do_each_thread(g, p) {
4734 * reset the NMI-timeout, listing all files on a slow
4735 * console might take alot of time:
4737 touch_nmi_watchdog();
4739 } while_each_thread(g, p);
4741 read_unlock(&tasklist_lock);
4742 debug_show_all_locks();
4746 * init_idle - set up an idle thread for a given CPU
4747 * @idle: task in question
4748 * @cpu: cpu the idle task belongs to
4750 * NOTE: this function does not set the idle thread's NEED_RESCHED
4751 * flag, to make booting more robust.
4753 void __devinit init_idle(struct task_struct *idle, int cpu)
4755 struct rq *rq = cpu_rq(cpu);
4756 unsigned long flags;
4758 idle->timestamp = sched_clock();
4759 idle->sleep_avg = 0;
4761 idle->prio = idle->normal_prio = MAX_PRIO;
4762 idle->state = TASK_RUNNING;
4763 idle->cpus_allowed = cpumask_of_cpu(cpu);
4764 set_task_cpu(idle, cpu);
4766 spin_lock_irqsave(&rq->lock, flags);
4767 rq->curr = rq->idle = idle;
4768 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4771 spin_unlock_irqrestore(&rq->lock, flags);
4773 /* Set the preempt count _outside_ the spinlocks! */
4774 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4775 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4777 task_thread_info(idle)->preempt_count = 0;
4782 * In a system that switches off the HZ timer nohz_cpu_mask
4783 * indicates which cpus entered this state. This is used
4784 * in the rcu update to wait only for active cpus. For system
4785 * which do not switch off the HZ timer nohz_cpu_mask should
4786 * always be CPU_MASK_NONE.
4788 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4792 * This is how migration works:
4794 * 1) we queue a struct migration_req structure in the source CPU's
4795 * runqueue and wake up that CPU's migration thread.
4796 * 2) we down() the locked semaphore => thread blocks.
4797 * 3) migration thread wakes up (implicitly it forces the migrated
4798 * thread off the CPU)
4799 * 4) it gets the migration request and checks whether the migrated
4800 * task is still in the wrong runqueue.
4801 * 5) if it's in the wrong runqueue then the migration thread removes
4802 * it and puts it into the right queue.
4803 * 6) migration thread up()s the semaphore.
4804 * 7) we wake up and the migration is done.
4808 * Change a given task's CPU affinity. Migrate the thread to a
4809 * proper CPU and schedule it away if the CPU it's executing on
4810 * is removed from the allowed bitmask.
4812 * NOTE: the caller must have a valid reference to the task, the
4813 * task must not exit() & deallocate itself prematurely. The
4814 * call is not atomic; no spinlocks may be held.
4816 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
4818 struct migration_req req;
4819 unsigned long flags;
4823 rq = task_rq_lock(p, &flags);
4824 if (!cpus_intersects(new_mask, cpu_online_map)) {
4829 p->cpus_allowed = new_mask;
4830 /* Can the task run on the task's current CPU? If so, we're done */
4831 if (cpu_isset(task_cpu(p), new_mask))
4834 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4835 /* Need help from migration thread: drop lock and wait. */
4836 task_rq_unlock(rq, &flags);
4837 wake_up_process(rq->migration_thread);
4838 wait_for_completion(&req.done);
4839 tlb_migrate_finish(p->mm);
4843 task_rq_unlock(rq, &flags);
4847 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4850 * Move (not current) task off this cpu, onto dest cpu. We're doing
4851 * this because either it can't run here any more (set_cpus_allowed()
4852 * away from this CPU, or CPU going down), or because we're
4853 * attempting to rebalance this task on exec (sched_exec).
4855 * So we race with normal scheduler movements, but that's OK, as long
4856 * as the task is no longer on this CPU.
4858 * Returns non-zero if task was successfully migrated.
4860 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4862 struct rq *rq_dest, *rq_src;
4865 if (unlikely(cpu_is_offline(dest_cpu)))
4868 rq_src = cpu_rq(src_cpu);
4869 rq_dest = cpu_rq(dest_cpu);
4871 double_rq_lock(rq_src, rq_dest);
4872 /* Already moved. */
4873 if (task_cpu(p) != src_cpu)
4875 /* Affinity changed (again). */
4876 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4879 set_task_cpu(p, dest_cpu);
4882 * Sync timestamp with rq_dest's before activating.
4883 * The same thing could be achieved by doing this step
4884 * afterwards, and pretending it was a local activate.
4885 * This way is cleaner and logically correct.
4887 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4888 + rq_dest->timestamp_last_tick;
4889 deactivate_task(p, rq_src);
4890 __activate_task(p, rq_dest);
4891 if (TASK_PREEMPTS_CURR(p, rq_dest))
4892 resched_task(rq_dest->curr);
4896 double_rq_unlock(rq_src, rq_dest);
4901 * migration_thread - this is a highprio system thread that performs
4902 * thread migration by bumping thread off CPU then 'pushing' onto
4905 static int migration_thread(void *data)
4907 int cpu = (long)data;
4911 BUG_ON(rq->migration_thread != current);
4913 set_current_state(TASK_INTERRUPTIBLE);
4914 while (!kthread_should_stop()) {
4915 struct migration_req *req;
4916 struct list_head *head;
4920 spin_lock_irq(&rq->lock);
4922 if (cpu_is_offline(cpu)) {
4923 spin_unlock_irq(&rq->lock);
4927 if (rq->active_balance) {
4928 active_load_balance(rq, cpu);
4929 rq->active_balance = 0;
4932 head = &rq->migration_queue;
4934 if (list_empty(head)) {
4935 spin_unlock_irq(&rq->lock);
4937 set_current_state(TASK_INTERRUPTIBLE);
4940 req = list_entry(head->next, struct migration_req, list);
4941 list_del_init(head->next);
4943 spin_unlock(&rq->lock);
4944 __migrate_task(req->task, cpu, req->dest_cpu);
4947 complete(&req->done);
4949 __set_current_state(TASK_RUNNING);
4953 /* Wait for kthread_stop */
4954 set_current_state(TASK_INTERRUPTIBLE);
4955 while (!kthread_should_stop()) {
4957 set_current_state(TASK_INTERRUPTIBLE);
4959 __set_current_state(TASK_RUNNING);
4963 #ifdef CONFIG_HOTPLUG_CPU
4964 /* Figure out where task on dead CPU should go, use force if neccessary. */
4965 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
4967 unsigned long flags;
4974 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4975 cpus_and(mask, mask, p->cpus_allowed);
4976 dest_cpu = any_online_cpu(mask);
4978 /* On any allowed CPU? */
4979 if (dest_cpu == NR_CPUS)
4980 dest_cpu = any_online_cpu(p->cpus_allowed);
4982 /* No more Mr. Nice Guy. */
4983 if (dest_cpu == NR_CPUS) {
4984 rq = task_rq_lock(p, &flags);
4985 cpus_setall(p->cpus_allowed);
4986 dest_cpu = any_online_cpu(p->cpus_allowed);
4987 task_rq_unlock(rq, &flags);
4990 * Don't tell them about moving exiting tasks or
4991 * kernel threads (both mm NULL), since they never
4994 if (p->mm && printk_ratelimit())
4995 printk(KERN_INFO "process %d (%s) no "
4996 "longer affine to cpu%d\n",
4997 p->pid, p->comm, dead_cpu);
4999 if (!__migrate_task(p, dead_cpu, dest_cpu))
5004 * While a dead CPU has no uninterruptible tasks queued at this point,
5005 * it might still have a nonzero ->nr_uninterruptible counter, because
5006 * for performance reasons the counter is not stricly tracking tasks to
5007 * their home CPUs. So we just add the counter to another CPU's counter,
5008 * to keep the global sum constant after CPU-down:
5010 static void migrate_nr_uninterruptible(struct rq *rq_src)
5012 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5013 unsigned long flags;
5015 local_irq_save(flags);
5016 double_rq_lock(rq_src, rq_dest);
5017 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5018 rq_src->nr_uninterruptible = 0;
5019 double_rq_unlock(rq_src, rq_dest);
5020 local_irq_restore(flags);
5023 /* Run through task list and migrate tasks from the dead cpu. */
5024 static void migrate_live_tasks(int src_cpu)
5026 struct task_struct *p, *t;
5028 write_lock_irq(&tasklist_lock);
5030 do_each_thread(t, p) {
5034 if (task_cpu(p) == src_cpu)
5035 move_task_off_dead_cpu(src_cpu, p);
5036 } while_each_thread(t, p);
5038 write_unlock_irq(&tasklist_lock);
5041 /* Schedules idle task to be the next runnable task on current CPU.
5042 * It does so by boosting its priority to highest possible and adding it to
5043 * the _front_ of the runqueue. Used by CPU offline code.
5045 void sched_idle_next(void)
5047 int this_cpu = smp_processor_id();
5048 struct rq *rq = cpu_rq(this_cpu);
5049 struct task_struct *p = rq->idle;
5050 unsigned long flags;
5052 /* cpu has to be offline */
5053 BUG_ON(cpu_online(this_cpu));
5056 * Strictly not necessary since rest of the CPUs are stopped by now
5057 * and interrupts disabled on the current cpu.
5059 spin_lock_irqsave(&rq->lock, flags);
5061 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5063 /* Add idle task to the _front_ of its priority queue: */
5064 __activate_idle_task(p, rq);
5066 spin_unlock_irqrestore(&rq->lock, flags);
5070 * Ensures that the idle task is using init_mm right before its cpu goes
5073 void idle_task_exit(void)
5075 struct mm_struct *mm = current->active_mm;
5077 BUG_ON(cpu_online(smp_processor_id()));
5080 switch_mm(mm, &init_mm, current);
5084 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5086 struct rq *rq = cpu_rq(dead_cpu);
5088 /* Must be exiting, otherwise would be on tasklist. */
5089 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
5091 /* Cannot have done final schedule yet: would have vanished. */
5092 BUG_ON(p->flags & PF_DEAD);
5097 * Drop lock around migration; if someone else moves it,
5098 * that's OK. No task can be added to this CPU, so iteration is
5101 spin_unlock_irq(&rq->lock);
5102 move_task_off_dead_cpu(dead_cpu, p);
5103 spin_lock_irq(&rq->lock);
5108 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5109 static void migrate_dead_tasks(unsigned int dead_cpu)
5111 struct rq *rq = cpu_rq(dead_cpu);
5112 unsigned int arr, i;
5114 for (arr = 0; arr < 2; arr++) {
5115 for (i = 0; i < MAX_PRIO; i++) {
5116 struct list_head *list = &rq->arrays[arr].queue[i];
5118 while (!list_empty(list))
5119 migrate_dead(dead_cpu, list_entry(list->next,
5120 struct task_struct, run_list));
5124 #endif /* CONFIG_HOTPLUG_CPU */
5127 * migration_call - callback that gets triggered when a CPU is added.
5128 * Here we can start up the necessary migration thread for the new CPU.
5130 static int __cpuinit
5131 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5133 struct task_struct *p;
5134 int cpu = (long)hcpu;
5135 unsigned long flags;
5139 case CPU_UP_PREPARE:
5140 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
5143 p->flags |= PF_NOFREEZE;
5144 kthread_bind(p, cpu);
5145 /* Must be high prio: stop_machine expects to yield to it. */
5146 rq = task_rq_lock(p, &flags);
5147 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5148 task_rq_unlock(rq, &flags);
5149 cpu_rq(cpu)->migration_thread = p;
5153 /* Strictly unneccessary, as first user will wake it. */
5154 wake_up_process(cpu_rq(cpu)->migration_thread);
5157 #ifdef CONFIG_HOTPLUG_CPU
5158 case CPU_UP_CANCELED:
5159 if (!cpu_rq(cpu)->migration_thread)
5161 /* Unbind it from offline cpu so it can run. Fall thru. */
5162 kthread_bind(cpu_rq(cpu)->migration_thread,
5163 any_online_cpu(cpu_online_map));
5164 kthread_stop(cpu_rq(cpu)->migration_thread);
5165 cpu_rq(cpu)->migration_thread = NULL;
5169 migrate_live_tasks(cpu);
5171 kthread_stop(rq->migration_thread);
5172 rq->migration_thread = NULL;
5173 /* Idle task back to normal (off runqueue, low prio) */
5174 rq = task_rq_lock(rq->idle, &flags);
5175 deactivate_task(rq->idle, rq);
5176 rq->idle->static_prio = MAX_PRIO;
5177 __setscheduler(rq->idle, SCHED_NORMAL, 0);
5178 migrate_dead_tasks(cpu);
5179 task_rq_unlock(rq, &flags);
5180 migrate_nr_uninterruptible(rq);
5181 BUG_ON(rq->nr_running != 0);
5183 /* No need to migrate the tasks: it was best-effort if
5184 * they didn't do lock_cpu_hotplug(). Just wake up
5185 * the requestors. */
5186 spin_lock_irq(&rq->lock);
5187 while (!list_empty(&rq->migration_queue)) {
5188 struct migration_req *req;
5190 req = list_entry(rq->migration_queue.next,
5191 struct migration_req, list);
5192 list_del_init(&req->list);
5193 complete(&req->done);
5195 spin_unlock_irq(&rq->lock);
5202 /* Register at highest priority so that task migration (migrate_all_tasks)
5203 * happens before everything else.
5205 static struct notifier_block __cpuinitdata migration_notifier = {
5206 .notifier_call = migration_call,
5210 int __init migration_init(void)
5212 void *cpu = (void *)(long)smp_processor_id();
5214 /* Start one for the boot CPU: */
5215 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5216 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5217 register_cpu_notifier(&migration_notifier);
5224 #undef SCHED_DOMAIN_DEBUG
5225 #ifdef SCHED_DOMAIN_DEBUG
5226 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5231 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5235 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5240 struct sched_group *group = sd->groups;
5241 cpumask_t groupmask;
5243 cpumask_scnprintf(str, NR_CPUS, sd->span);
5244 cpus_clear(groupmask);
5247 for (i = 0; i < level + 1; i++)
5249 printk("domain %d: ", level);
5251 if (!(sd->flags & SD_LOAD_BALANCE)) {
5252 printk("does not load-balance\n");
5254 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
5258 printk("span %s\n", str);
5260 if (!cpu_isset(cpu, sd->span))
5261 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
5262 if (!cpu_isset(cpu, group->cpumask))
5263 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
5266 for (i = 0; i < level + 2; i++)
5272 printk(KERN_ERR "ERROR: group is NULL\n");
5276 if (!group->cpu_power) {
5278 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
5281 if (!cpus_weight(group->cpumask)) {
5283 printk(KERN_ERR "ERROR: empty group\n");
5286 if (cpus_intersects(groupmask, group->cpumask)) {
5288 printk(KERN_ERR "ERROR: repeated CPUs\n");
5291 cpus_or(groupmask, groupmask, group->cpumask);
5293 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5296 group = group->next;
5297 } while (group != sd->groups);
5300 if (!cpus_equal(sd->span, groupmask))
5301 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5307 if (!cpus_subset(groupmask, sd->span))
5308 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
5314 # define sched_domain_debug(sd, cpu) do { } while (0)
5317 static int sd_degenerate(struct sched_domain *sd)
5319 if (cpus_weight(sd->span) == 1)
5322 /* Following flags need at least 2 groups */
5323 if (sd->flags & (SD_LOAD_BALANCE |
5324 SD_BALANCE_NEWIDLE |
5327 if (sd->groups != sd->groups->next)
5331 /* Following flags don't use groups */
5332 if (sd->flags & (SD_WAKE_IDLE |
5341 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5343 unsigned long cflags = sd->flags, pflags = parent->flags;
5345 if (sd_degenerate(parent))
5348 if (!cpus_equal(sd->span, parent->span))
5351 /* Does parent contain flags not in child? */
5352 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5353 if (cflags & SD_WAKE_AFFINE)
5354 pflags &= ~SD_WAKE_BALANCE;
5355 /* Flags needing groups don't count if only 1 group in parent */
5356 if (parent->groups == parent->groups->next) {
5357 pflags &= ~(SD_LOAD_BALANCE |
5358 SD_BALANCE_NEWIDLE |
5362 if (~cflags & pflags)
5369 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5370 * hold the hotplug lock.
5372 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5374 struct rq *rq = cpu_rq(cpu);
5375 struct sched_domain *tmp;
5377 /* Remove the sched domains which do not contribute to scheduling. */
5378 for (tmp = sd; tmp; tmp = tmp->parent) {
5379 struct sched_domain *parent = tmp->parent;
5382 if (sd_parent_degenerate(tmp, parent))
5383 tmp->parent = parent->parent;
5386 if (sd && sd_degenerate(sd))
5389 sched_domain_debug(sd, cpu);
5391 rcu_assign_pointer(rq->sd, sd);
5394 /* cpus with isolated domains */
5395 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5397 /* Setup the mask of cpus configured for isolated domains */
5398 static int __init isolated_cpu_setup(char *str)
5400 int ints[NR_CPUS], i;
5402 str = get_options(str, ARRAY_SIZE(ints), ints);
5403 cpus_clear(cpu_isolated_map);
5404 for (i = 1; i <= ints[0]; i++)
5405 if (ints[i] < NR_CPUS)
5406 cpu_set(ints[i], cpu_isolated_map);
5410 __setup ("isolcpus=", isolated_cpu_setup);
5413 * init_sched_build_groups takes an array of groups, the cpumask we wish
5414 * to span, and a pointer to a function which identifies what group a CPU
5415 * belongs to. The return value of group_fn must be a valid index into the
5416 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5417 * keep track of groups covered with a cpumask_t).
5419 * init_sched_build_groups will build a circular linked list of the groups
5420 * covered by the given span, and will set each group's ->cpumask correctly,
5421 * and ->cpu_power to 0.
5423 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5424 int (*group_fn)(int cpu))
5426 struct sched_group *first = NULL, *last = NULL;
5427 cpumask_t covered = CPU_MASK_NONE;
5430 for_each_cpu_mask(i, span) {
5431 int group = group_fn(i);
5432 struct sched_group *sg = &groups[group];
5435 if (cpu_isset(i, covered))
5438 sg->cpumask = CPU_MASK_NONE;
5441 for_each_cpu_mask(j, span) {
5442 if (group_fn(j) != group)
5445 cpu_set(j, covered);
5446 cpu_set(j, sg->cpumask);
5457 #define SD_NODES_PER_DOMAIN 16
5460 * Self-tuning task migration cost measurement between source and target CPUs.
5462 * This is done by measuring the cost of manipulating buffers of varying
5463 * sizes. For a given buffer-size here are the steps that are taken:
5465 * 1) the source CPU reads+dirties a shared buffer
5466 * 2) the target CPU reads+dirties the same shared buffer
5468 * We measure how long they take, in the following 4 scenarios:
5470 * - source: CPU1, target: CPU2 | cost1
5471 * - source: CPU2, target: CPU1 | cost2
5472 * - source: CPU1, target: CPU1 | cost3
5473 * - source: CPU2, target: CPU2 | cost4
5475 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5476 * the cost of migration.
5478 * We then start off from a small buffer-size and iterate up to larger
5479 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5480 * doing a maximum search for the cost. (The maximum cost for a migration
5481 * normally occurs when the working set size is around the effective cache
5484 #define SEARCH_SCOPE 2
5485 #define MIN_CACHE_SIZE (64*1024U)
5486 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5487 #define ITERATIONS 1
5488 #define SIZE_THRESH 130
5489 #define COST_THRESH 130
5492 * The migration cost is a function of 'domain distance'. Domain
5493 * distance is the number of steps a CPU has to iterate down its
5494 * domain tree to share a domain with the other CPU. The farther
5495 * two CPUs are from each other, the larger the distance gets.
5497 * Note that we use the distance only to cache measurement results,
5498 * the distance value is not used numerically otherwise. When two
5499 * CPUs have the same distance it is assumed that the migration
5500 * cost is the same. (this is a simplification but quite practical)
5502 #define MAX_DOMAIN_DISTANCE 32
5504 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5505 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5507 * Architectures may override the migration cost and thus avoid
5508 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5509 * virtualized hardware:
5511 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5512 CONFIG_DEFAULT_MIGRATION_COST
5519 * Allow override of migration cost - in units of microseconds.
5520 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5521 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5523 static int __init migration_cost_setup(char *str)
5525 int ints[MAX_DOMAIN_DISTANCE+1], i;
5527 str = get_options(str, ARRAY_SIZE(ints), ints);
5529 printk("#ints: %d\n", ints[0]);
5530 for (i = 1; i <= ints[0]; i++) {
5531 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5532 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5537 __setup ("migration_cost=", migration_cost_setup);
5540 * Global multiplier (divisor) for migration-cutoff values,
5541 * in percentiles. E.g. use a value of 150 to get 1.5 times
5542 * longer cache-hot cutoff times.
5544 * (We scale it from 100 to 128 to long long handling easier.)
5547 #define MIGRATION_FACTOR_SCALE 128
5549 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5551 static int __init setup_migration_factor(char *str)
5553 get_option(&str, &migration_factor);
5554 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5558 __setup("migration_factor=", setup_migration_factor);
5561 * Estimated distance of two CPUs, measured via the number of domains
5562 * we have to pass for the two CPUs to be in the same span:
5564 static unsigned long domain_distance(int cpu1, int cpu2)
5566 unsigned long distance = 0;
5567 struct sched_domain *sd;
5569 for_each_domain(cpu1, sd) {
5570 WARN_ON(!cpu_isset(cpu1, sd->span));
5571 if (cpu_isset(cpu2, sd->span))
5575 if (distance >= MAX_DOMAIN_DISTANCE) {
5577 distance = MAX_DOMAIN_DISTANCE-1;
5583 static unsigned int migration_debug;
5585 static int __init setup_migration_debug(char *str)
5587 get_option(&str, &migration_debug);
5591 __setup("migration_debug=", setup_migration_debug);
5594 * Maximum cache-size that the scheduler should try to measure.
5595 * Architectures with larger caches should tune this up during
5596 * bootup. Gets used in the domain-setup code (i.e. during SMP
5599 unsigned int max_cache_size;
5601 static int __init setup_max_cache_size(char *str)
5603 get_option(&str, &max_cache_size);
5607 __setup("max_cache_size=", setup_max_cache_size);
5610 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5611 * is the operation that is timed, so we try to generate unpredictable
5612 * cachemisses that still end up filling the L2 cache:
5614 static void touch_cache(void *__cache, unsigned long __size)
5616 unsigned long size = __size/sizeof(long), chunk1 = size/3,
5618 unsigned long *cache = __cache;
5621 for (i = 0; i < size/6; i += 8) {
5624 case 1: cache[size-1-i]++;
5625 case 2: cache[chunk1-i]++;
5626 case 3: cache[chunk1+i]++;
5627 case 4: cache[chunk2-i]++;
5628 case 5: cache[chunk2+i]++;
5634 * Measure the cache-cost of one task migration. Returns in units of nsec.
5636 static unsigned long long
5637 measure_one(void *cache, unsigned long size, int source, int target)
5639 cpumask_t mask, saved_mask;
5640 unsigned long long t0, t1, t2, t3, cost;
5642 saved_mask = current->cpus_allowed;
5645 * Flush source caches to RAM and invalidate them:
5650 * Migrate to the source CPU:
5652 mask = cpumask_of_cpu(source);
5653 set_cpus_allowed(current, mask);
5654 WARN_ON(smp_processor_id() != source);
5657 * Dirty the working set:
5660 touch_cache(cache, size);
5664 * Migrate to the target CPU, dirty the L2 cache and access
5665 * the shared buffer. (which represents the working set
5666 * of a migrated task.)
5668 mask = cpumask_of_cpu(target);
5669 set_cpus_allowed(current, mask);
5670 WARN_ON(smp_processor_id() != target);
5673 touch_cache(cache, size);
5676 cost = t1-t0 + t3-t2;
5678 if (migration_debug >= 2)
5679 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5680 source, target, t1-t0, t1-t0, t3-t2, cost);
5682 * Flush target caches to RAM and invalidate them:
5686 set_cpus_allowed(current, saved_mask);
5692 * Measure a series of task migrations and return the average
5693 * result. Since this code runs early during bootup the system
5694 * is 'undisturbed' and the average latency makes sense.
5696 * The algorithm in essence auto-detects the relevant cache-size,
5697 * so it will properly detect different cachesizes for different
5698 * cache-hierarchies, depending on how the CPUs are connected.
5700 * Architectures can prime the upper limit of the search range via
5701 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5703 static unsigned long long
5704 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5706 unsigned long long cost1, cost2;
5710 * Measure the migration cost of 'size' bytes, over an
5711 * average of 10 runs:
5713 * (We perturb the cache size by a small (0..4k)
5714 * value to compensate size/alignment related artifacts.
5715 * We also subtract the cost of the operation done on
5721 * dry run, to make sure we start off cache-cold on cpu1,
5722 * and to get any vmalloc pagefaults in advance:
5724 measure_one(cache, size, cpu1, cpu2);
5725 for (i = 0; i < ITERATIONS; i++)
5726 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5728 measure_one(cache, size, cpu2, cpu1);
5729 for (i = 0; i < ITERATIONS; i++)
5730 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5733 * (We measure the non-migrating [cached] cost on both
5734 * cpu1 and cpu2, to handle CPUs with different speeds)
5738 measure_one(cache, size, cpu1, cpu1);
5739 for (i = 0; i < ITERATIONS; i++)
5740 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5742 measure_one(cache, size, cpu2, cpu2);
5743 for (i = 0; i < ITERATIONS; i++)
5744 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5747 * Get the per-iteration migration cost:
5749 do_div(cost1, 2*ITERATIONS);
5750 do_div(cost2, 2*ITERATIONS);
5752 return cost1 - cost2;
5755 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5757 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5758 unsigned int max_size, size, size_found = 0;
5759 long long cost = 0, prev_cost;
5763 * Search from max_cache_size*5 down to 64K - the real relevant
5764 * cachesize has to lie somewhere inbetween.
5766 if (max_cache_size) {
5767 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5768 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5771 * Since we have no estimation about the relevant
5774 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5775 size = MIN_CACHE_SIZE;
5778 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5779 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5784 * Allocate the working set:
5786 cache = vmalloc(max_size);
5788 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5789 return 1000000; /* return 1 msec on very small boxen */
5792 while (size <= max_size) {
5794 cost = measure_cost(cpu1, cpu2, cache, size);
5800 if (max_cost < cost) {
5806 * Calculate average fluctuation, we use this to prevent
5807 * noise from triggering an early break out of the loop:
5809 fluct = abs(cost - prev_cost);
5810 avg_fluct = (avg_fluct + fluct)/2;
5812 if (migration_debug)
5813 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5815 (long)cost / 1000000,
5816 ((long)cost / 100000) % 10,
5817 (long)max_cost / 1000000,
5818 ((long)max_cost / 100000) % 10,
5819 domain_distance(cpu1, cpu2),
5823 * If we iterated at least 20% past the previous maximum,
5824 * and the cost has dropped by more than 20% already,
5825 * (taking fluctuations into account) then we assume to
5826 * have found the maximum and break out of the loop early:
5828 if (size_found && (size*100 > size_found*SIZE_THRESH))
5829 if (cost+avg_fluct <= 0 ||
5830 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5832 if (migration_debug)
5833 printk("-> found max.\n");
5837 * Increase the cachesize in 10% steps:
5839 size = size * 10 / 9;
5842 if (migration_debug)
5843 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5844 cpu1, cpu2, size_found, max_cost);
5849 * A task is considered 'cache cold' if at least 2 times
5850 * the worst-case cost of migration has passed.
5852 * (this limit is only listened to if the load-balancing
5853 * situation is 'nice' - if there is a large imbalance we
5854 * ignore it for the sake of CPU utilization and
5855 * processing fairness.)
5857 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5860 static void calibrate_migration_costs(const cpumask_t *cpu_map)
5862 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5863 unsigned long j0, j1, distance, max_distance = 0;
5864 struct sched_domain *sd;
5869 * First pass - calculate the cacheflush times:
5871 for_each_cpu_mask(cpu1, *cpu_map) {
5872 for_each_cpu_mask(cpu2, *cpu_map) {
5875 distance = domain_distance(cpu1, cpu2);
5876 max_distance = max(max_distance, distance);
5878 * No result cached yet?
5880 if (migration_cost[distance] == -1LL)
5881 migration_cost[distance] =
5882 measure_migration_cost(cpu1, cpu2);
5886 * Second pass - update the sched domain hierarchy with
5887 * the new cache-hot-time estimations:
5889 for_each_cpu_mask(cpu, *cpu_map) {
5891 for_each_domain(cpu, sd) {
5892 sd->cache_hot_time = migration_cost[distance];
5899 if (migration_debug)
5900 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5908 if (system_state == SYSTEM_BOOTING) {
5909 printk("migration_cost=");
5910 for (distance = 0; distance <= max_distance; distance++) {
5913 printk("%ld", (long)migration_cost[distance] / 1000);
5918 if (migration_debug)
5919 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5922 * Move back to the original CPU. NUMA-Q gets confused
5923 * if we migrate to another quad during bootup.
5925 if (raw_smp_processor_id() != orig_cpu) {
5926 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5927 saved_mask = current->cpus_allowed;
5929 set_cpus_allowed(current, mask);
5930 set_cpus_allowed(current, saved_mask);
5937 * find_next_best_node - find the next node to include in a sched_domain
5938 * @node: node whose sched_domain we're building
5939 * @used_nodes: nodes already in the sched_domain
5941 * Find the next node to include in a given scheduling domain. Simply
5942 * finds the closest node not already in the @used_nodes map.
5944 * Should use nodemask_t.
5946 static int find_next_best_node(int node, unsigned long *used_nodes)
5948 int i, n, val, min_val, best_node = 0;
5952 for (i = 0; i < MAX_NUMNODES; i++) {
5953 /* Start at @node */
5954 n = (node + i) % MAX_NUMNODES;
5956 if (!nr_cpus_node(n))
5959 /* Skip already used nodes */
5960 if (test_bit(n, used_nodes))
5963 /* Simple min distance search */
5964 val = node_distance(node, n);
5966 if (val < min_val) {
5972 set_bit(best_node, used_nodes);
5977 * sched_domain_node_span - get a cpumask for a node's sched_domain
5978 * @node: node whose cpumask we're constructing
5979 * @size: number of nodes to include in this span
5981 * Given a node, construct a good cpumask for its sched_domain to span. It
5982 * should be one that prevents unnecessary balancing, but also spreads tasks
5985 static cpumask_t sched_domain_node_span(int node)
5987 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5988 cpumask_t span, nodemask;
5992 bitmap_zero(used_nodes, MAX_NUMNODES);
5994 nodemask = node_to_cpumask(node);
5995 cpus_or(span, span, nodemask);
5996 set_bit(node, used_nodes);
5998 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5999 int next_node = find_next_best_node(node, used_nodes);
6001 nodemask = node_to_cpumask(next_node);
6002 cpus_or(span, span, nodemask);
6009 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6012 * SMT sched-domains:
6014 #ifdef CONFIG_SCHED_SMT
6015 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6016 static struct sched_group sched_group_cpus[NR_CPUS];
6018 static int cpu_to_cpu_group(int cpu)
6025 * multi-core sched-domains:
6027 #ifdef CONFIG_SCHED_MC
6028 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6029 static struct sched_group *sched_group_core_bycpu[NR_CPUS];
6032 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6033 static int cpu_to_core_group(int cpu)
6035 return first_cpu(cpu_sibling_map[cpu]);
6037 #elif defined(CONFIG_SCHED_MC)
6038 static int cpu_to_core_group(int cpu)
6044 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6045 static struct sched_group *sched_group_phys_bycpu[NR_CPUS];
6047 static int cpu_to_phys_group(int cpu)
6049 #ifdef CONFIG_SCHED_MC
6050 cpumask_t mask = cpu_coregroup_map(cpu);
6051 return first_cpu(mask);
6052 #elif defined(CONFIG_SCHED_SMT)
6053 return first_cpu(cpu_sibling_map[cpu]);
6061 * The init_sched_build_groups can't handle what we want to do with node
6062 * groups, so roll our own. Now each node has its own list of groups which
6063 * gets dynamically allocated.
6065 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6066 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6068 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6069 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
6071 static int cpu_to_allnodes_group(int cpu)
6073 return cpu_to_node(cpu);
6075 static void init_numa_sched_groups_power(struct sched_group *group_head)
6077 struct sched_group *sg = group_head;
6083 for_each_cpu_mask(j, sg->cpumask) {
6084 struct sched_domain *sd;
6086 sd = &per_cpu(phys_domains, j);
6087 if (j != first_cpu(sd->groups->cpumask)) {
6089 * Only add "power" once for each
6095 sg->cpu_power += sd->groups->cpu_power;
6098 if (sg != group_head)
6103 /* Free memory allocated for various sched_group structures */
6104 static void free_sched_groups(const cpumask_t *cpu_map)
6110 for_each_cpu_mask(cpu, *cpu_map) {
6111 struct sched_group *sched_group_allnodes
6112 = sched_group_allnodes_bycpu[cpu];
6113 struct sched_group **sched_group_nodes
6114 = sched_group_nodes_bycpu[cpu];
6116 if (sched_group_allnodes) {
6117 kfree(sched_group_allnodes);
6118 sched_group_allnodes_bycpu[cpu] = NULL;
6121 if (!sched_group_nodes)
6124 for (i = 0; i < MAX_NUMNODES; i++) {
6125 cpumask_t nodemask = node_to_cpumask(i);
6126 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6128 cpus_and(nodemask, nodemask, *cpu_map);
6129 if (cpus_empty(nodemask))
6139 if (oldsg != sched_group_nodes[i])
6142 kfree(sched_group_nodes);
6143 sched_group_nodes_bycpu[cpu] = NULL;
6146 for_each_cpu_mask(cpu, *cpu_map) {
6147 if (sched_group_phys_bycpu[cpu]) {
6148 kfree(sched_group_phys_bycpu[cpu]);
6149 sched_group_phys_bycpu[cpu] = NULL;
6151 #ifdef CONFIG_SCHED_MC
6152 if (sched_group_core_bycpu[cpu]) {
6153 kfree(sched_group_core_bycpu[cpu]);
6154 sched_group_core_bycpu[cpu] = NULL;
6161 * Build sched domains for a given set of cpus and attach the sched domains
6162 * to the individual cpus
6164 static int build_sched_domains(const cpumask_t *cpu_map)
6167 struct sched_group *sched_group_phys = NULL;
6168 #ifdef CONFIG_SCHED_MC
6169 struct sched_group *sched_group_core = NULL;
6172 struct sched_group **sched_group_nodes = NULL;
6173 struct sched_group *sched_group_allnodes = NULL;
6176 * Allocate the per-node list of sched groups
6178 sched_group_nodes = kzalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
6180 if (!sched_group_nodes) {
6181 printk(KERN_WARNING "Can not alloc sched group node list\n");
6184 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6188 * Set up domains for cpus specified by the cpu_map.
6190 for_each_cpu_mask(i, *cpu_map) {
6192 struct sched_domain *sd = NULL, *p;
6193 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6195 cpus_and(nodemask, nodemask, *cpu_map);
6198 if (cpus_weight(*cpu_map)
6199 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6200 if (!sched_group_allnodes) {
6201 sched_group_allnodes
6202 = kmalloc(sizeof(struct sched_group)
6205 if (!sched_group_allnodes) {
6207 "Can not alloc allnodes sched group\n");
6210 sched_group_allnodes_bycpu[i]
6211 = sched_group_allnodes;
6213 sd = &per_cpu(allnodes_domains, i);
6214 *sd = SD_ALLNODES_INIT;
6215 sd->span = *cpu_map;
6216 group = cpu_to_allnodes_group(i);
6217 sd->groups = &sched_group_allnodes[group];
6222 sd = &per_cpu(node_domains, i);
6224 sd->span = sched_domain_node_span(cpu_to_node(i));
6226 cpus_and(sd->span, sd->span, *cpu_map);
6229 if (!sched_group_phys) {
6231 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6233 if (!sched_group_phys) {
6234 printk (KERN_WARNING "Can not alloc phys sched"
6238 sched_group_phys_bycpu[i] = sched_group_phys;
6242 sd = &per_cpu(phys_domains, i);
6243 group = cpu_to_phys_group(i);
6245 sd->span = nodemask;
6247 sd->groups = &sched_group_phys[group];
6249 #ifdef CONFIG_SCHED_MC
6250 if (!sched_group_core) {
6252 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6254 if (!sched_group_core) {
6255 printk (KERN_WARNING "Can not alloc core sched"
6259 sched_group_core_bycpu[i] = sched_group_core;
6263 sd = &per_cpu(core_domains, i);
6264 group = cpu_to_core_group(i);
6266 sd->span = cpu_coregroup_map(i);
6267 cpus_and(sd->span, sd->span, *cpu_map);
6269 sd->groups = &sched_group_core[group];
6272 #ifdef CONFIG_SCHED_SMT
6274 sd = &per_cpu(cpu_domains, i);
6275 group = cpu_to_cpu_group(i);
6276 *sd = SD_SIBLING_INIT;
6277 sd->span = cpu_sibling_map[i];
6278 cpus_and(sd->span, sd->span, *cpu_map);
6280 sd->groups = &sched_group_cpus[group];
6284 #ifdef CONFIG_SCHED_SMT
6285 /* Set up CPU (sibling) groups */
6286 for_each_cpu_mask(i, *cpu_map) {
6287 cpumask_t this_sibling_map = cpu_sibling_map[i];
6288 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6289 if (i != first_cpu(this_sibling_map))
6292 init_sched_build_groups(sched_group_cpus, this_sibling_map,
6297 #ifdef CONFIG_SCHED_MC
6298 /* Set up multi-core groups */
6299 for_each_cpu_mask(i, *cpu_map) {
6300 cpumask_t this_core_map = cpu_coregroup_map(i);
6301 cpus_and(this_core_map, this_core_map, *cpu_map);
6302 if (i != first_cpu(this_core_map))
6304 init_sched_build_groups(sched_group_core, this_core_map,
6305 &cpu_to_core_group);
6310 /* Set up physical groups */
6311 for (i = 0; i < MAX_NUMNODES; i++) {
6312 cpumask_t nodemask = node_to_cpumask(i);
6314 cpus_and(nodemask, nodemask, *cpu_map);
6315 if (cpus_empty(nodemask))
6318 init_sched_build_groups(sched_group_phys, nodemask,
6319 &cpu_to_phys_group);
6323 /* Set up node groups */
6324 if (sched_group_allnodes)
6325 init_sched_build_groups(sched_group_allnodes, *cpu_map,
6326 &cpu_to_allnodes_group);
6328 for (i = 0; i < MAX_NUMNODES; i++) {
6329 /* Set up node groups */
6330 struct sched_group *sg, *prev;
6331 cpumask_t nodemask = node_to_cpumask(i);
6332 cpumask_t domainspan;
6333 cpumask_t covered = CPU_MASK_NONE;
6336 cpus_and(nodemask, nodemask, *cpu_map);
6337 if (cpus_empty(nodemask)) {
6338 sched_group_nodes[i] = NULL;
6342 domainspan = sched_domain_node_span(i);
6343 cpus_and(domainspan, domainspan, *cpu_map);
6345 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6347 printk(KERN_WARNING "Can not alloc domain group for "
6351 sched_group_nodes[i] = sg;
6352 for_each_cpu_mask(j, nodemask) {
6353 struct sched_domain *sd;
6354 sd = &per_cpu(node_domains, j);
6358 sg->cpumask = nodemask;
6360 cpus_or(covered, covered, nodemask);
6363 for (j = 0; j < MAX_NUMNODES; j++) {
6364 cpumask_t tmp, notcovered;
6365 int n = (i + j) % MAX_NUMNODES;
6367 cpus_complement(notcovered, covered);
6368 cpus_and(tmp, notcovered, *cpu_map);
6369 cpus_and(tmp, tmp, domainspan);
6370 if (cpus_empty(tmp))
6373 nodemask = node_to_cpumask(n);
6374 cpus_and(tmp, tmp, nodemask);
6375 if (cpus_empty(tmp))
6378 sg = kmalloc_node(sizeof(struct sched_group),
6382 "Can not alloc domain group for node %d\n", j);
6387 sg->next = prev->next;
6388 cpus_or(covered, covered, tmp);
6395 /* Calculate CPU power for physical packages and nodes */
6396 #ifdef CONFIG_SCHED_SMT
6397 for_each_cpu_mask(i, *cpu_map) {
6398 struct sched_domain *sd;
6399 sd = &per_cpu(cpu_domains, i);
6400 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6403 #ifdef CONFIG_SCHED_MC
6404 for_each_cpu_mask(i, *cpu_map) {
6406 struct sched_domain *sd;
6407 sd = &per_cpu(core_domains, i);
6408 if (sched_smt_power_savings)
6409 power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6411 power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
6412 * SCHED_LOAD_SCALE / 10;
6413 sd->groups->cpu_power = power;
6417 for_each_cpu_mask(i, *cpu_map) {
6418 struct sched_domain *sd;
6419 #ifdef CONFIG_SCHED_MC
6420 sd = &per_cpu(phys_domains, i);
6421 if (i != first_cpu(sd->groups->cpumask))
6424 sd->groups->cpu_power = 0;
6425 if (sched_mc_power_savings || sched_smt_power_savings) {
6428 for_each_cpu_mask(j, sd->groups->cpumask) {
6429 struct sched_domain *sd1;
6430 sd1 = &per_cpu(core_domains, j);
6432 * for each core we will add once
6433 * to the group in physical domain
6435 if (j != first_cpu(sd1->groups->cpumask))
6438 if (sched_smt_power_savings)
6439 sd->groups->cpu_power += sd1->groups->cpu_power;
6441 sd->groups->cpu_power += SCHED_LOAD_SCALE;
6445 * This has to be < 2 * SCHED_LOAD_SCALE
6446 * Lets keep it SCHED_LOAD_SCALE, so that
6447 * while calculating NUMA group's cpu_power
6449 * numa_group->cpu_power += phys_group->cpu_power;
6451 * See "only add power once for each physical pkg"
6454 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6457 sd = &per_cpu(phys_domains, i);
6458 if (sched_smt_power_savings)
6459 power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6461 power = SCHED_LOAD_SCALE;
6462 sd->groups->cpu_power = power;
6467 for (i = 0; i < MAX_NUMNODES; i++)
6468 init_numa_sched_groups_power(sched_group_nodes[i]);
6470 init_numa_sched_groups_power(sched_group_allnodes);
6473 /* Attach the domains */
6474 for_each_cpu_mask(i, *cpu_map) {
6475 struct sched_domain *sd;
6476 #ifdef CONFIG_SCHED_SMT
6477 sd = &per_cpu(cpu_domains, i);
6478 #elif defined(CONFIG_SCHED_MC)
6479 sd = &per_cpu(core_domains, i);
6481 sd = &per_cpu(phys_domains, i);
6483 cpu_attach_domain(sd, i);
6486 * Tune cache-hot values:
6488 calibrate_migration_costs(cpu_map);
6493 free_sched_groups(cpu_map);
6497 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6499 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6501 cpumask_t cpu_default_map;
6505 * Setup mask for cpus without special case scheduling requirements.
6506 * For now this just excludes isolated cpus, but could be used to
6507 * exclude other special cases in the future.
6509 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6511 err = build_sched_domains(&cpu_default_map);
6516 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6518 free_sched_groups(cpu_map);
6522 * Detach sched domains from a group of cpus specified in cpu_map
6523 * These cpus will now be attached to the NULL domain
6525 static void detach_destroy_domains(const cpumask_t *cpu_map)
6529 for_each_cpu_mask(i, *cpu_map)
6530 cpu_attach_domain(NULL, i);
6531 synchronize_sched();
6532 arch_destroy_sched_domains(cpu_map);
6536 * Partition sched domains as specified by the cpumasks below.
6537 * This attaches all cpus from the cpumasks to the NULL domain,
6538 * waits for a RCU quiescent period, recalculates sched
6539 * domain information and then attaches them back to the
6540 * correct sched domains
6541 * Call with hotplug lock held
6543 int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6545 cpumask_t change_map;
6548 cpus_and(*partition1, *partition1, cpu_online_map);
6549 cpus_and(*partition2, *partition2, cpu_online_map);
6550 cpus_or(change_map, *partition1, *partition2);
6552 /* Detach sched domains from all of the affected cpus */
6553 detach_destroy_domains(&change_map);
6554 if (!cpus_empty(*partition1))
6555 err = build_sched_domains(partition1);
6556 if (!err && !cpus_empty(*partition2))
6557 err = build_sched_domains(partition2);
6562 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6563 int arch_reinit_sched_domains(void)
6568 detach_destroy_domains(&cpu_online_map);
6569 err = arch_init_sched_domains(&cpu_online_map);
6570 unlock_cpu_hotplug();
6575 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6579 if (buf[0] != '0' && buf[0] != '1')
6583 sched_smt_power_savings = (buf[0] == '1');
6585 sched_mc_power_savings = (buf[0] == '1');
6587 ret = arch_reinit_sched_domains();
6589 return ret ? ret : count;
6592 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6596 #ifdef CONFIG_SCHED_SMT
6598 err = sysfs_create_file(&cls->kset.kobj,
6599 &attr_sched_smt_power_savings.attr);
6601 #ifdef CONFIG_SCHED_MC
6602 if (!err && mc_capable())
6603 err = sysfs_create_file(&cls->kset.kobj,
6604 &attr_sched_mc_power_savings.attr);
6610 #ifdef CONFIG_SCHED_MC
6611 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6613 return sprintf(page, "%u\n", sched_mc_power_savings);
6615 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6616 const char *buf, size_t count)
6618 return sched_power_savings_store(buf, count, 0);
6620 SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6621 sched_mc_power_savings_store);
6624 #ifdef CONFIG_SCHED_SMT
6625 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6627 return sprintf(page, "%u\n", sched_smt_power_savings);
6629 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6630 const char *buf, size_t count)
6632 return sched_power_savings_store(buf, count, 1);
6634 SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6635 sched_smt_power_savings_store);
6639 #ifdef CONFIG_HOTPLUG_CPU
6641 * Force a reinitialization of the sched domains hierarchy. The domains
6642 * and groups cannot be updated in place without racing with the balancing
6643 * code, so we temporarily attach all running cpus to the NULL domain
6644 * which will prevent rebalancing while the sched domains are recalculated.
6646 static int update_sched_domains(struct notifier_block *nfb,
6647 unsigned long action, void *hcpu)
6650 case CPU_UP_PREPARE:
6651 case CPU_DOWN_PREPARE:
6652 detach_destroy_domains(&cpu_online_map);
6655 case CPU_UP_CANCELED:
6656 case CPU_DOWN_FAILED:
6660 * Fall through and re-initialise the domains.
6667 /* The hotplug lock is already held by cpu_up/cpu_down */
6668 arch_init_sched_domains(&cpu_online_map);
6674 void __init sched_init_smp(void)
6677 arch_init_sched_domains(&cpu_online_map);
6678 unlock_cpu_hotplug();
6679 /* XXX: Theoretical race here - CPU may be hotplugged now */
6680 hotcpu_notifier(update_sched_domains, 0);
6683 void __init sched_init_smp(void)
6686 #endif /* CONFIG_SMP */
6688 int in_sched_functions(unsigned long addr)
6690 /* Linker adds these: start and end of __sched functions */
6691 extern char __sched_text_start[], __sched_text_end[];
6693 return in_lock_functions(addr) ||
6694 (addr >= (unsigned long)__sched_text_start
6695 && addr < (unsigned long)__sched_text_end);
6698 void __init sched_init(void)
6702 for_each_possible_cpu(i) {
6703 struct prio_array *array;
6707 spin_lock_init(&rq->lock);
6708 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6710 rq->active = rq->arrays;
6711 rq->expired = rq->arrays + 1;
6712 rq->best_expired_prio = MAX_PRIO;
6716 for (j = 1; j < 3; j++)
6717 rq->cpu_load[j] = 0;
6718 rq->active_balance = 0;
6720 rq->migration_thread = NULL;
6721 INIT_LIST_HEAD(&rq->migration_queue);
6723 atomic_set(&rq->nr_iowait, 0);
6725 for (j = 0; j < 2; j++) {
6726 array = rq->arrays + j;
6727 for (k = 0; k < MAX_PRIO; k++) {
6728 INIT_LIST_HEAD(array->queue + k);
6729 __clear_bit(k, array->bitmap);
6731 // delimiter for bitsearch
6732 __set_bit(MAX_PRIO, array->bitmap);
6736 set_load_weight(&init_task);
6738 * The boot idle thread does lazy MMU switching as well:
6740 atomic_inc(&init_mm.mm_count);
6741 enter_lazy_tlb(&init_mm, current);
6744 * Make us the idle thread. Technically, schedule() should not be
6745 * called from this thread, however somewhere below it might be,
6746 * but because we are the idle thread, we just pick up running again
6747 * when this runqueue becomes "idle".
6749 init_idle(current, smp_processor_id());
6752 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6753 void __might_sleep(char *file, int line)
6756 static unsigned long prev_jiffy; /* ratelimiting */
6758 if ((in_atomic() || irqs_disabled()) &&
6759 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6760 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6762 prev_jiffy = jiffies;
6763 printk(KERN_ERR "BUG: sleeping function called from invalid"
6764 " context at %s:%d\n", file, line);
6765 printk("in_atomic():%d, irqs_disabled():%d\n",
6766 in_atomic(), irqs_disabled());
6771 EXPORT_SYMBOL(__might_sleep);
6774 #ifdef CONFIG_MAGIC_SYSRQ
6775 void normalize_rt_tasks(void)
6777 struct prio_array *array;
6778 struct task_struct *p;
6779 unsigned long flags;
6782 read_lock_irq(&tasklist_lock);
6783 for_each_process(p) {
6787 spin_lock_irqsave(&p->pi_lock, flags);
6788 rq = __task_rq_lock(p);
6792 deactivate_task(p, task_rq(p));
6793 __setscheduler(p, SCHED_NORMAL, 0);
6795 __activate_task(p, task_rq(p));
6796 resched_task(rq->curr);
6799 __task_rq_unlock(rq);
6800 spin_unlock_irqrestore(&p->pi_lock, flags);
6802 read_unlock_irq(&tasklist_lock);
6805 #endif /* CONFIG_MAGIC_SYSRQ */
6809 * These functions are only useful for the IA64 MCA handling.
6811 * They can only be called when the whole system has been
6812 * stopped - every CPU needs to be quiescent, and no scheduling
6813 * activity can take place. Using them for anything else would
6814 * be a serious bug, and as a result, they aren't even visible
6815 * under any other configuration.
6819 * curr_task - return the current task for a given cpu.
6820 * @cpu: the processor in question.
6822 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6824 struct task_struct *curr_task(int cpu)
6826 return cpu_curr(cpu);
6830 * set_curr_task - set the current task for a given cpu.
6831 * @cpu: the processor in question.
6832 * @p: the task pointer to set.
6834 * Description: This function must only be used when non-maskable interrupts
6835 * are serviced on a separate stack. It allows the architecture to switch the
6836 * notion of the current task on a cpu in a non-blocking manner. This function
6837 * must be called with all CPU's synchronized, and interrupts disabled, the
6838 * and caller must save the original value of the current task (see
6839 * curr_task() above) and restore that value before reenabling interrupts and
6840 * re-starting the system.
6842 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6844 void set_curr_task(int cpu, struct task_struct *p)