sched: fix SMP migration latencies
[linux-2.6/kvm.git] / kernel / sched.c
blob4ad789d268fe4959d7a24789f06a0c711af516a1
1 /*
2 * kernel/sched.c
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
11 * by Andrea Arcangeli
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
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
27 #include <linux/mm.h>
28 #include <linux/module.h>
29 #include <linux/nmi.h>
30 #include <linux/init.h>
31 #include <linux/uaccess.h>
32 #include <linux/highmem.h>
33 #include <linux/smp_lock.h>
34 #include <asm/mmu_context.h>
35 #include <linux/interrupt.h>
36 #include <linux/capability.h>
37 #include <linux/completion.h>
38 #include <linux/kernel_stat.h>
39 #include <linux/debug_locks.h>
40 #include <linux/security.h>
41 #include <linux/notifier.h>
42 #include <linux/profile.h>
43 #include <linux/freezer.h>
44 #include <linux/vmalloc.h>
45 #include <linux/blkdev.h>
46 #include <linux/delay.h>
47 #include <linux/smp.h>
48 #include <linux/threads.h>
49 #include <linux/timer.h>
50 #include <linux/rcupdate.h>
51 #include <linux/cpu.h>
52 #include <linux/cpuset.h>
53 #include <linux/percpu.h>
54 #include <linux/kthread.h>
55 #include <linux/seq_file.h>
56 #include <linux/sysctl.h>
57 #include <linux/syscalls.h>
58 #include <linux/times.h>
59 #include <linux/tsacct_kern.h>
60 #include <linux/kprobes.h>
61 #include <linux/delayacct.h>
62 #include <linux/reciprocal_div.h>
63 #include <linux/unistd.h>
64 #include <linux/pagemap.h>
66 #include <asm/tlb.h>
69 * Scheduler clock - returns current time in nanosec units.
70 * This is default implementation.
71 * Architectures and sub-architectures can override this.
73 unsigned long long __attribute__((weak)) sched_clock(void)
75 return (unsigned long long)jiffies * (1000000000 / HZ);
79 * Convert user-nice values [ -20 ... 0 ... 19 ]
80 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
81 * and back.
83 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
84 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
85 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
88 * 'User priority' is the nice value converted to something we
89 * can work with better when scaling various scheduler parameters,
90 * it's a [ 0 ... 39 ] range.
92 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
93 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
94 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
97 * Some helpers for converting nanosecond timing to jiffy resolution
99 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
100 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
102 #define NICE_0_LOAD SCHED_LOAD_SCALE
103 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
106 * These are the 'tuning knobs' of the scheduler:
108 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
109 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
110 * Timeslices get refilled after they expire.
112 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
113 #define DEF_TIMESLICE (100 * HZ / 1000)
115 #ifdef CONFIG_SMP
117 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
118 * Since cpu_power is a 'constant', we can use a reciprocal divide.
120 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
122 return reciprocal_divide(load, sg->reciprocal_cpu_power);
126 * Each time a sched group cpu_power is changed,
127 * we must compute its reciprocal value
129 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
131 sg->__cpu_power += val;
132 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
134 #endif
136 #define SCALE_PRIO(x, prio) \
137 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
140 * static_prio_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
141 * to time slice values: [800ms ... 100ms ... 5ms]
143 static unsigned int static_prio_timeslice(int static_prio)
145 if (static_prio == NICE_TO_PRIO(19))
146 return 1;
148 if (static_prio < NICE_TO_PRIO(0))
149 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
150 else
151 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
154 static inline int rt_policy(int policy)
156 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
157 return 1;
158 return 0;
161 static inline int task_has_rt_policy(struct task_struct *p)
163 return rt_policy(p->policy);
167 * This is the priority-queue data structure of the RT scheduling class:
169 struct rt_prio_array {
170 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
171 struct list_head queue[MAX_RT_PRIO];
174 /* CFS-related fields in a runqueue */
175 struct cfs_rq {
176 struct load_weight load;
177 unsigned long nr_running;
179 u64 exec_clock;
180 u64 min_vruntime;
182 struct rb_root tasks_timeline;
183 struct rb_node *rb_leftmost;
184 struct rb_node *rb_load_balance_curr;
185 /* 'curr' points to currently running entity on this cfs_rq.
186 * It is set to NULL otherwise (i.e when none are currently running).
188 struct sched_entity *curr;
189 #ifdef CONFIG_FAIR_GROUP_SCHED
190 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
192 /* leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
193 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
194 * (like users, containers etc.)
196 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
197 * list is used during load balance.
199 struct list_head leaf_cfs_rq_list; /* Better name : task_cfs_rq_list? */
200 #endif
203 /* Real-Time classes' related field in a runqueue: */
204 struct rt_rq {
205 struct rt_prio_array active;
206 int rt_load_balance_idx;
207 struct list_head *rt_load_balance_head, *rt_load_balance_curr;
211 * This is the main, per-CPU runqueue data structure.
213 * Locking rule: those places that want to lock multiple runqueues
214 * (such as the load balancing or the thread migration code), lock
215 * acquire operations must be ordered by ascending &runqueue.
217 struct rq {
218 spinlock_t lock; /* runqueue lock */
221 * nr_running and cpu_load should be in the same cacheline because
222 * remote CPUs use both these fields when doing load calculation.
224 unsigned long nr_running;
225 #define CPU_LOAD_IDX_MAX 5
226 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
227 unsigned char idle_at_tick;
228 #ifdef CONFIG_NO_HZ
229 unsigned char in_nohz_recently;
230 #endif
231 struct load_weight load; /* capture load from *all* tasks on this cpu */
232 unsigned long nr_load_updates;
233 u64 nr_switches;
235 struct cfs_rq cfs;
236 #ifdef CONFIG_FAIR_GROUP_SCHED
237 struct list_head leaf_cfs_rq_list; /* list of leaf cfs_rq on this cpu */
238 #endif
239 struct rt_rq rt;
242 * This is part of a global counter where only the total sum
243 * over all CPUs matters. A task can increase this counter on
244 * one CPU and if it got migrated afterwards it may decrease
245 * it on another CPU. Always updated under the runqueue lock:
247 unsigned long nr_uninterruptible;
249 struct task_struct *curr, *idle;
250 unsigned long next_balance;
251 struct mm_struct *prev_mm;
253 u64 clock, prev_clock_raw;
254 s64 clock_max_delta;
256 unsigned int clock_warps, clock_overflows;
257 u64 idle_clock;
258 unsigned int clock_deep_idle_events;
259 u64 tick_timestamp;
261 atomic_t nr_iowait;
263 #ifdef CONFIG_SMP
264 struct sched_domain *sd;
266 /* For active balancing */
267 int active_balance;
268 int push_cpu;
269 int cpu; /* cpu of this runqueue */
271 struct task_struct *migration_thread;
272 struct list_head migration_queue;
273 #endif
275 #ifdef CONFIG_SCHEDSTATS
276 /* latency stats */
277 struct sched_info rq_sched_info;
279 /* sys_sched_yield() stats */
280 unsigned long yld_exp_empty;
281 unsigned long yld_act_empty;
282 unsigned long yld_both_empty;
283 unsigned long yld_cnt;
285 /* schedule() stats */
286 unsigned long sched_switch;
287 unsigned long sched_cnt;
288 unsigned long sched_goidle;
290 /* try_to_wake_up() stats */
291 unsigned long ttwu_cnt;
292 unsigned long ttwu_local;
293 #endif
294 struct lock_class_key rq_lock_key;
297 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
298 static DEFINE_MUTEX(sched_hotcpu_mutex);
300 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
302 rq->curr->sched_class->check_preempt_curr(rq, p);
305 static inline int cpu_of(struct rq *rq)
307 #ifdef CONFIG_SMP
308 return rq->cpu;
309 #else
310 return 0;
311 #endif
315 * Update the per-runqueue clock, as finegrained as the platform can give
316 * us, but without assuming monotonicity, etc.:
318 static void __update_rq_clock(struct rq *rq)
320 u64 prev_raw = rq->prev_clock_raw;
321 u64 now = sched_clock();
322 s64 delta = now - prev_raw;
323 u64 clock = rq->clock;
325 #ifdef CONFIG_SCHED_DEBUG
326 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
327 #endif
329 * Protect against sched_clock() occasionally going backwards:
331 if (unlikely(delta < 0)) {
332 clock++;
333 rq->clock_warps++;
334 } else {
336 * Catch too large forward jumps too:
338 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
339 if (clock < rq->tick_timestamp + TICK_NSEC)
340 clock = rq->tick_timestamp + TICK_NSEC;
341 else
342 clock++;
343 rq->clock_overflows++;
344 } else {
345 if (unlikely(delta > rq->clock_max_delta))
346 rq->clock_max_delta = delta;
347 clock += delta;
351 rq->prev_clock_raw = now;
352 rq->clock = clock;
355 static void update_rq_clock(struct rq *rq)
357 if (likely(smp_processor_id() == cpu_of(rq)))
358 __update_rq_clock(rq);
362 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
363 * See detach_destroy_domains: synchronize_sched for details.
365 * The domain tree of any CPU may only be accessed from within
366 * preempt-disabled sections.
368 #define for_each_domain(cpu, __sd) \
369 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
371 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
372 #define this_rq() (&__get_cpu_var(runqueues))
373 #define task_rq(p) cpu_rq(task_cpu(p))
374 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
377 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
379 #ifdef CONFIG_SCHED_DEBUG
380 # define const_debug __read_mostly
381 #else
382 # define const_debug static const
383 #endif
386 * Debugging: various feature bits
388 enum {
389 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
390 SCHED_FEAT_START_DEBIT = 2,
391 SCHED_FEAT_USE_TREE_AVG = 4,
392 SCHED_FEAT_APPROX_AVG = 8,
395 const_debug unsigned int sysctl_sched_features =
396 SCHED_FEAT_NEW_FAIR_SLEEPERS *1 |
397 SCHED_FEAT_START_DEBIT *1 |
398 SCHED_FEAT_USE_TREE_AVG *0 |
399 SCHED_FEAT_APPROX_AVG *0;
401 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
404 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
405 * clock constructed from sched_clock():
407 unsigned long long cpu_clock(int cpu)
409 unsigned long long now;
410 unsigned long flags;
411 struct rq *rq;
413 local_irq_save(flags);
414 rq = cpu_rq(cpu);
415 update_rq_clock(rq);
416 now = rq->clock;
417 local_irq_restore(flags);
419 return now;
422 #ifdef CONFIG_FAIR_GROUP_SCHED
423 /* Change a task's ->cfs_rq if it moves across CPUs */
424 static inline void set_task_cfs_rq(struct task_struct *p)
426 p->se.cfs_rq = &task_rq(p)->cfs;
428 #else
429 static inline void set_task_cfs_rq(struct task_struct *p)
432 #endif
434 #ifndef prepare_arch_switch
435 # define prepare_arch_switch(next) do { } while (0)
436 #endif
437 #ifndef finish_arch_switch
438 # define finish_arch_switch(prev) do { } while (0)
439 #endif
441 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
442 static inline int task_running(struct rq *rq, struct task_struct *p)
444 return rq->curr == p;
447 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
451 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
453 #ifdef CONFIG_DEBUG_SPINLOCK
454 /* this is a valid case when another task releases the spinlock */
455 rq->lock.owner = current;
456 #endif
458 * If we are tracking spinlock dependencies then we have to
459 * fix up the runqueue lock - which gets 'carried over' from
460 * prev into current:
462 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
464 spin_unlock_irq(&rq->lock);
467 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
468 static inline int task_running(struct rq *rq, struct task_struct *p)
470 #ifdef CONFIG_SMP
471 return p->oncpu;
472 #else
473 return rq->curr == p;
474 #endif
477 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
479 #ifdef CONFIG_SMP
481 * We can optimise this out completely for !SMP, because the
482 * SMP rebalancing from interrupt is the only thing that cares
483 * here.
485 next->oncpu = 1;
486 #endif
487 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
488 spin_unlock_irq(&rq->lock);
489 #else
490 spin_unlock(&rq->lock);
491 #endif
494 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
496 #ifdef CONFIG_SMP
498 * After ->oncpu is cleared, the task can be moved to a different CPU.
499 * We must ensure this doesn't happen until the switch is completely
500 * finished.
502 smp_wmb();
503 prev->oncpu = 0;
504 #endif
505 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
506 local_irq_enable();
507 #endif
509 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
512 * __task_rq_lock - lock the runqueue a given task resides on.
513 * Must be called interrupts disabled.
515 static inline struct rq *__task_rq_lock(struct task_struct *p)
516 __acquires(rq->lock)
518 struct rq *rq;
520 repeat_lock_task:
521 rq = task_rq(p);
522 spin_lock(&rq->lock);
523 if (unlikely(rq != task_rq(p))) {
524 spin_unlock(&rq->lock);
525 goto repeat_lock_task;
527 return rq;
531 * task_rq_lock - lock the runqueue a given task resides on and disable
532 * interrupts. Note the ordering: we can safely lookup the task_rq without
533 * explicitly disabling preemption.
535 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
536 __acquires(rq->lock)
538 struct rq *rq;
540 repeat_lock_task:
541 local_irq_save(*flags);
542 rq = task_rq(p);
543 spin_lock(&rq->lock);
544 if (unlikely(rq != task_rq(p))) {
545 spin_unlock_irqrestore(&rq->lock, *flags);
546 goto repeat_lock_task;
548 return rq;
551 static inline void __task_rq_unlock(struct rq *rq)
552 __releases(rq->lock)
554 spin_unlock(&rq->lock);
557 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
558 __releases(rq->lock)
560 spin_unlock_irqrestore(&rq->lock, *flags);
564 * this_rq_lock - lock this runqueue and disable interrupts.
566 static inline struct rq *this_rq_lock(void)
567 __acquires(rq->lock)
569 struct rq *rq;
571 local_irq_disable();
572 rq = this_rq();
573 spin_lock(&rq->lock);
575 return rq;
579 * We are going deep-idle (irqs are disabled):
581 void sched_clock_idle_sleep_event(void)
583 struct rq *rq = cpu_rq(smp_processor_id());
585 spin_lock(&rq->lock);
586 __update_rq_clock(rq);
587 spin_unlock(&rq->lock);
588 rq->clock_deep_idle_events++;
590 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
593 * We just idled delta nanoseconds (called with irqs disabled):
595 void sched_clock_idle_wakeup_event(u64 delta_ns)
597 struct rq *rq = cpu_rq(smp_processor_id());
598 u64 now = sched_clock();
600 rq->idle_clock += delta_ns;
602 * Override the previous timestamp and ignore all
603 * sched_clock() deltas that occured while we idled,
604 * and use the PM-provided delta_ns to advance the
605 * rq clock:
607 spin_lock(&rq->lock);
608 rq->prev_clock_raw = now;
609 rq->clock += delta_ns;
610 spin_unlock(&rq->lock);
612 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
615 * resched_task - mark a task 'to be rescheduled now'.
617 * On UP this means the setting of the need_resched flag, on SMP it
618 * might also involve a cross-CPU call to trigger the scheduler on
619 * the target CPU.
621 #ifdef CONFIG_SMP
623 #ifndef tsk_is_polling
624 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
625 #endif
627 static void resched_task(struct task_struct *p)
629 int cpu;
631 assert_spin_locked(&task_rq(p)->lock);
633 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
634 return;
636 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
638 cpu = task_cpu(p);
639 if (cpu == smp_processor_id())
640 return;
642 /* NEED_RESCHED must be visible before we test polling */
643 smp_mb();
644 if (!tsk_is_polling(p))
645 smp_send_reschedule(cpu);
648 static void resched_cpu(int cpu)
650 struct rq *rq = cpu_rq(cpu);
651 unsigned long flags;
653 if (!spin_trylock_irqsave(&rq->lock, flags))
654 return;
655 resched_task(cpu_curr(cpu));
656 spin_unlock_irqrestore(&rq->lock, flags);
658 #else
659 static inline void resched_task(struct task_struct *p)
661 assert_spin_locked(&task_rq(p)->lock);
662 set_tsk_need_resched(p);
664 #endif
666 #if BITS_PER_LONG == 32
667 # define WMULT_CONST (~0UL)
668 #else
669 # define WMULT_CONST (1UL << 32)
670 #endif
672 #define WMULT_SHIFT 32
675 * Shift right and round:
677 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
679 static unsigned long
680 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
681 struct load_weight *lw)
683 u64 tmp;
685 if (unlikely(!lw->inv_weight))
686 lw->inv_weight = (WMULT_CONST - lw->weight/2) / lw->weight + 1;
688 tmp = (u64)delta_exec * weight;
690 * Check whether we'd overflow the 64-bit multiplication:
692 if (unlikely(tmp > WMULT_CONST))
693 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
694 WMULT_SHIFT/2);
695 else
696 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
698 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
701 static inline unsigned long
702 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
704 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
707 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
709 lw->weight += inc;
712 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
714 lw->weight -= dec;
718 * To aid in avoiding the subversion of "niceness" due to uneven distribution
719 * of tasks with abnormal "nice" values across CPUs the contribution that
720 * each task makes to its run queue's load is weighted according to its
721 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
722 * scaled version of the new time slice allocation that they receive on time
723 * slice expiry etc.
726 #define WEIGHT_IDLEPRIO 2
727 #define WMULT_IDLEPRIO (1 << 31)
730 * Nice levels are multiplicative, with a gentle 10% change for every
731 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
732 * nice 1, it will get ~10% less CPU time than another CPU-bound task
733 * that remained on nice 0.
735 * The "10% effect" is relative and cumulative: from _any_ nice level,
736 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
737 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
738 * If a task goes up by ~10% and another task goes down by ~10% then
739 * the relative distance between them is ~25%.)
741 static const int prio_to_weight[40] = {
742 /* -20 */ 88761, 71755, 56483, 46273, 36291,
743 /* -15 */ 29154, 23254, 18705, 14949, 11916,
744 /* -10 */ 9548, 7620, 6100, 4904, 3906,
745 /* -5 */ 3121, 2501, 1991, 1586, 1277,
746 /* 0 */ 1024, 820, 655, 526, 423,
747 /* 5 */ 335, 272, 215, 172, 137,
748 /* 10 */ 110, 87, 70, 56, 45,
749 /* 15 */ 36, 29, 23, 18, 15,
753 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
755 * In cases where the weight does not change often, we can use the
756 * precalculated inverse to speed up arithmetics by turning divisions
757 * into multiplications:
759 static const u32 prio_to_wmult[40] = {
760 /* -20 */ 48388, 59856, 76040, 92818, 118348,
761 /* -15 */ 147320, 184698, 229616, 287308, 360437,
762 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
763 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
764 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
765 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
766 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
767 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
770 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
773 * runqueue iterator, to support SMP load-balancing between different
774 * scheduling classes, without having to expose their internal data
775 * structures to the load-balancing proper:
777 struct rq_iterator {
778 void *arg;
779 struct task_struct *(*start)(void *);
780 struct task_struct *(*next)(void *);
783 static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
784 unsigned long max_nr_move, unsigned long max_load_move,
785 struct sched_domain *sd, enum cpu_idle_type idle,
786 int *all_pinned, unsigned long *load_moved,
787 int *this_best_prio, struct rq_iterator *iterator);
789 #include "sched_stats.h"
790 #include "sched_rt.c"
791 #include "sched_fair.c"
792 #include "sched_idletask.c"
793 #ifdef CONFIG_SCHED_DEBUG
794 # include "sched_debug.c"
795 #endif
797 #define sched_class_highest (&rt_sched_class)
800 * Update delta_exec, delta_fair fields for rq.
802 * delta_fair clock advances at a rate inversely proportional to
803 * total load (rq->load.weight) on the runqueue, while
804 * delta_exec advances at the same rate as wall-clock (provided
805 * cpu is not idle).
807 * delta_exec / delta_fair is a measure of the (smoothened) load on this
808 * runqueue over any given interval. This (smoothened) load is used
809 * during load balance.
811 * This function is called /before/ updating rq->load
812 * and when switching tasks.
814 static inline void inc_load(struct rq *rq, const struct task_struct *p)
816 update_load_add(&rq->load, p->se.load.weight);
819 static inline void dec_load(struct rq *rq, const struct task_struct *p)
821 update_load_sub(&rq->load, p->se.load.weight);
824 static void inc_nr_running(struct task_struct *p, struct rq *rq)
826 rq->nr_running++;
827 inc_load(rq, p);
830 static void dec_nr_running(struct task_struct *p, struct rq *rq)
832 rq->nr_running--;
833 dec_load(rq, p);
836 static void set_load_weight(struct task_struct *p)
838 if (task_has_rt_policy(p)) {
839 p->se.load.weight = prio_to_weight[0] * 2;
840 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
841 return;
845 * SCHED_IDLE tasks get minimal weight:
847 if (p->policy == SCHED_IDLE) {
848 p->se.load.weight = WEIGHT_IDLEPRIO;
849 p->se.load.inv_weight = WMULT_IDLEPRIO;
850 return;
853 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
854 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
857 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
859 sched_info_queued(p);
860 p->sched_class->enqueue_task(rq, p, wakeup);
861 p->se.on_rq = 1;
864 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
866 p->sched_class->dequeue_task(rq, p, sleep);
867 p->se.on_rq = 0;
871 * __normal_prio - return the priority that is based on the static prio
873 static inline int __normal_prio(struct task_struct *p)
875 return p->static_prio;
879 * Calculate the expected normal priority: i.e. priority
880 * without taking RT-inheritance into account. Might be
881 * boosted by interactivity modifiers. Changes upon fork,
882 * setprio syscalls, and whenever the interactivity
883 * estimator recalculates.
885 static inline int normal_prio(struct task_struct *p)
887 int prio;
889 if (task_has_rt_policy(p))
890 prio = MAX_RT_PRIO-1 - p->rt_priority;
891 else
892 prio = __normal_prio(p);
893 return prio;
897 * Calculate the current priority, i.e. the priority
898 * taken into account by the scheduler. This value might
899 * be boosted by RT tasks, or might be boosted by
900 * interactivity modifiers. Will be RT if the task got
901 * RT-boosted. If not then it returns p->normal_prio.
903 static int effective_prio(struct task_struct *p)
905 p->normal_prio = normal_prio(p);
907 * If we are RT tasks or we were boosted to RT priority,
908 * keep the priority unchanged. Otherwise, update priority
909 * to the normal priority:
911 if (!rt_prio(p->prio))
912 return p->normal_prio;
913 return p->prio;
917 * activate_task - move a task to the runqueue.
919 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
921 if (p->state == TASK_UNINTERRUPTIBLE)
922 rq->nr_uninterruptible--;
924 enqueue_task(rq, p, wakeup);
925 inc_nr_running(p, rq);
929 * activate_idle_task - move idle task to the _front_ of runqueue.
931 static inline void activate_idle_task(struct task_struct *p, struct rq *rq)
933 update_rq_clock(rq);
935 if (p->state == TASK_UNINTERRUPTIBLE)
936 rq->nr_uninterruptible--;
938 enqueue_task(rq, p, 0);
939 inc_nr_running(p, rq);
943 * deactivate_task - remove a task from the runqueue.
945 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
947 if (p->state == TASK_UNINTERRUPTIBLE)
948 rq->nr_uninterruptible++;
950 dequeue_task(rq, p, sleep);
951 dec_nr_running(p, rq);
955 * task_curr - is this task currently executing on a CPU?
956 * @p: the task in question.
958 inline int task_curr(const struct task_struct *p)
960 return cpu_curr(task_cpu(p)) == p;
963 /* Used instead of source_load when we know the type == 0 */
964 unsigned long weighted_cpuload(const int cpu)
966 return cpu_rq(cpu)->load.weight;
969 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
971 #ifdef CONFIG_SMP
972 task_thread_info(p)->cpu = cpu;
973 set_task_cfs_rq(p);
974 #endif
977 #ifdef CONFIG_SMP
979 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
981 int old_cpu = task_cpu(p);
982 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
983 u64 clock_offset;
985 clock_offset = old_rq->clock - new_rq->clock;
987 #ifdef CONFIG_SCHEDSTATS
988 if (p->se.wait_start)
989 p->se.wait_start -= clock_offset;
990 if (p->se.sleep_start)
991 p->se.sleep_start -= clock_offset;
992 if (p->se.block_start)
993 p->se.block_start -= clock_offset;
994 #endif
995 if (likely(new_rq->cfs.min_vruntime))
996 p->se.vruntime -= old_rq->cfs.min_vruntime -
997 new_rq->cfs.min_vruntime;
999 __set_task_cpu(p, new_cpu);
1002 struct migration_req {
1003 struct list_head list;
1005 struct task_struct *task;
1006 int dest_cpu;
1008 struct completion done;
1012 * The task's runqueue lock must be held.
1013 * Returns true if you have to wait for migration thread.
1015 static int
1016 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1018 struct rq *rq = task_rq(p);
1021 * If the task is not on a runqueue (and not running), then
1022 * it is sufficient to simply update the task's cpu field.
1024 if (!p->se.on_rq && !task_running(rq, p)) {
1025 set_task_cpu(p, dest_cpu);
1026 return 0;
1029 init_completion(&req->done);
1030 req->task = p;
1031 req->dest_cpu = dest_cpu;
1032 list_add(&req->list, &rq->migration_queue);
1034 return 1;
1038 * wait_task_inactive - wait for a thread to unschedule.
1040 * The caller must ensure that the task *will* unschedule sometime soon,
1041 * else this function might spin for a *long* time. This function can't
1042 * be called with interrupts off, or it may introduce deadlock with
1043 * smp_call_function() if an IPI is sent by the same process we are
1044 * waiting to become inactive.
1046 void wait_task_inactive(struct task_struct *p)
1048 unsigned long flags;
1049 int running, on_rq;
1050 struct rq *rq;
1052 repeat:
1054 * We do the initial early heuristics without holding
1055 * any task-queue locks at all. We'll only try to get
1056 * the runqueue lock when things look like they will
1057 * work out!
1059 rq = task_rq(p);
1062 * If the task is actively running on another CPU
1063 * still, just relax and busy-wait without holding
1064 * any locks.
1066 * NOTE! Since we don't hold any locks, it's not
1067 * even sure that "rq" stays as the right runqueue!
1068 * But we don't care, since "task_running()" will
1069 * return false if the runqueue has changed and p
1070 * is actually now running somewhere else!
1072 while (task_running(rq, p))
1073 cpu_relax();
1076 * Ok, time to look more closely! We need the rq
1077 * lock now, to be *sure*. If we're wrong, we'll
1078 * just go back and repeat.
1080 rq = task_rq_lock(p, &flags);
1081 running = task_running(rq, p);
1082 on_rq = p->se.on_rq;
1083 task_rq_unlock(rq, &flags);
1086 * Was it really running after all now that we
1087 * checked with the proper locks actually held?
1089 * Oops. Go back and try again..
1091 if (unlikely(running)) {
1092 cpu_relax();
1093 goto repeat;
1097 * It's not enough that it's not actively running,
1098 * it must be off the runqueue _entirely_, and not
1099 * preempted!
1101 * So if it wa still runnable (but just not actively
1102 * running right now), it's preempted, and we should
1103 * yield - it could be a while.
1105 if (unlikely(on_rq)) {
1106 yield();
1107 goto repeat;
1111 * Ahh, all good. It wasn't running, and it wasn't
1112 * runnable, which means that it will never become
1113 * running in the future either. We're all done!
1117 /***
1118 * kick_process - kick a running thread to enter/exit the kernel
1119 * @p: the to-be-kicked thread
1121 * Cause a process which is running on another CPU to enter
1122 * kernel-mode, without any delay. (to get signals handled.)
1124 * NOTE: this function doesnt have to take the runqueue lock,
1125 * because all it wants to ensure is that the remote task enters
1126 * the kernel. If the IPI races and the task has been migrated
1127 * to another CPU then no harm is done and the purpose has been
1128 * achieved as well.
1130 void kick_process(struct task_struct *p)
1132 int cpu;
1134 preempt_disable();
1135 cpu = task_cpu(p);
1136 if ((cpu != smp_processor_id()) && task_curr(p))
1137 smp_send_reschedule(cpu);
1138 preempt_enable();
1142 * Return a low guess at the load of a migration-source cpu weighted
1143 * according to the scheduling class and "nice" value.
1145 * We want to under-estimate the load of migration sources, to
1146 * balance conservatively.
1148 static inline unsigned long source_load(int cpu, int type)
1150 struct rq *rq = cpu_rq(cpu);
1151 unsigned long total = weighted_cpuload(cpu);
1153 if (type == 0)
1154 return total;
1156 return min(rq->cpu_load[type-1], total);
1160 * Return a high guess at the load of a migration-target cpu weighted
1161 * according to the scheduling class and "nice" value.
1163 static inline unsigned long target_load(int cpu, int type)
1165 struct rq *rq = cpu_rq(cpu);
1166 unsigned long total = weighted_cpuload(cpu);
1168 if (type == 0)
1169 return total;
1171 return max(rq->cpu_load[type-1], total);
1175 * Return the average load per task on the cpu's run queue
1177 static inline unsigned long cpu_avg_load_per_task(int cpu)
1179 struct rq *rq = cpu_rq(cpu);
1180 unsigned long total = weighted_cpuload(cpu);
1181 unsigned long n = rq->nr_running;
1183 return n ? total / n : SCHED_LOAD_SCALE;
1187 * find_idlest_group finds and returns the least busy CPU group within the
1188 * domain.
1190 static struct sched_group *
1191 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1193 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1194 unsigned long min_load = ULONG_MAX, this_load = 0;
1195 int load_idx = sd->forkexec_idx;
1196 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1198 do {
1199 unsigned long load, avg_load;
1200 int local_group;
1201 int i;
1203 /* Skip over this group if it has no CPUs allowed */
1204 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1205 goto nextgroup;
1207 local_group = cpu_isset(this_cpu, group->cpumask);
1209 /* Tally up the load of all CPUs in the group */
1210 avg_load = 0;
1212 for_each_cpu_mask(i, group->cpumask) {
1213 /* Bias balancing toward cpus of our domain */
1214 if (local_group)
1215 load = source_load(i, load_idx);
1216 else
1217 load = target_load(i, load_idx);
1219 avg_load += load;
1222 /* Adjust by relative CPU power of the group */
1223 avg_load = sg_div_cpu_power(group,
1224 avg_load * SCHED_LOAD_SCALE);
1226 if (local_group) {
1227 this_load = avg_load;
1228 this = group;
1229 } else if (avg_load < min_load) {
1230 min_load = avg_load;
1231 idlest = group;
1233 nextgroup:
1234 group = group->next;
1235 } while (group != sd->groups);
1237 if (!idlest || 100*this_load < imbalance*min_load)
1238 return NULL;
1239 return idlest;
1243 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1245 static int
1246 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1248 cpumask_t tmp;
1249 unsigned long load, min_load = ULONG_MAX;
1250 int idlest = -1;
1251 int i;
1253 /* Traverse only the allowed CPUs */
1254 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1256 for_each_cpu_mask(i, tmp) {
1257 load = weighted_cpuload(i);
1259 if (load < min_load || (load == min_load && i == this_cpu)) {
1260 min_load = load;
1261 idlest = i;
1265 return idlest;
1269 * sched_balance_self: balance the current task (running on cpu) in domains
1270 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1271 * SD_BALANCE_EXEC.
1273 * Balance, ie. select the least loaded group.
1275 * Returns the target CPU number, or the same CPU if no balancing is needed.
1277 * preempt must be disabled.
1279 static int sched_balance_self(int cpu, int flag)
1281 struct task_struct *t = current;
1282 struct sched_domain *tmp, *sd = NULL;
1284 for_each_domain(cpu, tmp) {
1286 * If power savings logic is enabled for a domain, stop there.
1288 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1289 break;
1290 if (tmp->flags & flag)
1291 sd = tmp;
1294 while (sd) {
1295 cpumask_t span;
1296 struct sched_group *group;
1297 int new_cpu, weight;
1299 if (!(sd->flags & flag)) {
1300 sd = sd->child;
1301 continue;
1304 span = sd->span;
1305 group = find_idlest_group(sd, t, cpu);
1306 if (!group) {
1307 sd = sd->child;
1308 continue;
1311 new_cpu = find_idlest_cpu(group, t, cpu);
1312 if (new_cpu == -1 || new_cpu == cpu) {
1313 /* Now try balancing at a lower domain level of cpu */
1314 sd = sd->child;
1315 continue;
1318 /* Now try balancing at a lower domain level of new_cpu */
1319 cpu = new_cpu;
1320 sd = NULL;
1321 weight = cpus_weight(span);
1322 for_each_domain(cpu, tmp) {
1323 if (weight <= cpus_weight(tmp->span))
1324 break;
1325 if (tmp->flags & flag)
1326 sd = tmp;
1328 /* while loop will break here if sd == NULL */
1331 return cpu;
1334 #endif /* CONFIG_SMP */
1337 * wake_idle() will wake a task on an idle cpu if task->cpu is
1338 * not idle and an idle cpu is available. The span of cpus to
1339 * search starts with cpus closest then further out as needed,
1340 * so we always favor a closer, idle cpu.
1342 * Returns the CPU we should wake onto.
1344 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1345 static int wake_idle(int cpu, struct task_struct *p)
1347 cpumask_t tmp;
1348 struct sched_domain *sd;
1349 int i;
1352 * If it is idle, then it is the best cpu to run this task.
1354 * This cpu is also the best, if it has more than one task already.
1355 * Siblings must be also busy(in most cases) as they didn't already
1356 * pickup the extra load from this cpu and hence we need not check
1357 * sibling runqueue info. This will avoid the checks and cache miss
1358 * penalities associated with that.
1360 if (idle_cpu(cpu) || cpu_rq(cpu)->nr_running > 1)
1361 return cpu;
1363 for_each_domain(cpu, sd) {
1364 if (sd->flags & SD_WAKE_IDLE) {
1365 cpus_and(tmp, sd->span, p->cpus_allowed);
1366 for_each_cpu_mask(i, tmp) {
1367 if (idle_cpu(i))
1368 return i;
1370 } else {
1371 break;
1374 return cpu;
1376 #else
1377 static inline int wake_idle(int cpu, struct task_struct *p)
1379 return cpu;
1381 #endif
1383 /***
1384 * try_to_wake_up - wake up a thread
1385 * @p: the to-be-woken-up thread
1386 * @state: the mask of task states that can be woken
1387 * @sync: do a synchronous wakeup?
1389 * Put it on the run-queue if it's not already there. The "current"
1390 * thread is always on the run-queue (except when the actual
1391 * re-schedule is in progress), and as such you're allowed to do
1392 * the simpler "current->state = TASK_RUNNING" to mark yourself
1393 * runnable without the overhead of this.
1395 * returns failure only if the task is already active.
1397 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1399 int cpu, this_cpu, success = 0;
1400 unsigned long flags;
1401 long old_state;
1402 struct rq *rq;
1403 #ifdef CONFIG_SMP
1404 struct sched_domain *sd, *this_sd = NULL;
1405 unsigned long load, this_load;
1406 int new_cpu;
1407 #endif
1409 rq = task_rq_lock(p, &flags);
1410 old_state = p->state;
1411 if (!(old_state & state))
1412 goto out;
1414 if (p->se.on_rq)
1415 goto out_running;
1417 cpu = task_cpu(p);
1418 this_cpu = smp_processor_id();
1420 #ifdef CONFIG_SMP
1421 if (unlikely(task_running(rq, p)))
1422 goto out_activate;
1424 new_cpu = cpu;
1426 schedstat_inc(rq, ttwu_cnt);
1427 if (cpu == this_cpu) {
1428 schedstat_inc(rq, ttwu_local);
1429 goto out_set_cpu;
1432 for_each_domain(this_cpu, sd) {
1433 if (cpu_isset(cpu, sd->span)) {
1434 schedstat_inc(sd, ttwu_wake_remote);
1435 this_sd = sd;
1436 break;
1440 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1441 goto out_set_cpu;
1444 * Check for affine wakeup and passive balancing possibilities.
1446 if (this_sd) {
1447 int idx = this_sd->wake_idx;
1448 unsigned int imbalance;
1450 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1452 load = source_load(cpu, idx);
1453 this_load = target_load(this_cpu, idx);
1455 new_cpu = this_cpu; /* Wake to this CPU if we can */
1457 if (this_sd->flags & SD_WAKE_AFFINE) {
1458 unsigned long tl = this_load;
1459 unsigned long tl_per_task;
1461 tl_per_task = cpu_avg_load_per_task(this_cpu);
1464 * If sync wakeup then subtract the (maximum possible)
1465 * effect of the currently running task from the load
1466 * of the current CPU:
1468 if (sync)
1469 tl -= current->se.load.weight;
1471 if ((tl <= load &&
1472 tl + target_load(cpu, idx) <= tl_per_task) ||
1473 100*(tl + p->se.load.weight) <= imbalance*load) {
1475 * This domain has SD_WAKE_AFFINE and
1476 * p is cache cold in this domain, and
1477 * there is no bad imbalance.
1479 schedstat_inc(this_sd, ttwu_move_affine);
1480 goto out_set_cpu;
1485 * Start passive balancing when half the imbalance_pct
1486 * limit is reached.
1488 if (this_sd->flags & SD_WAKE_BALANCE) {
1489 if (imbalance*this_load <= 100*load) {
1490 schedstat_inc(this_sd, ttwu_move_balance);
1491 goto out_set_cpu;
1496 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1497 out_set_cpu:
1498 new_cpu = wake_idle(new_cpu, p);
1499 if (new_cpu != cpu) {
1500 set_task_cpu(p, new_cpu);
1501 task_rq_unlock(rq, &flags);
1502 /* might preempt at this point */
1503 rq = task_rq_lock(p, &flags);
1504 old_state = p->state;
1505 if (!(old_state & state))
1506 goto out;
1507 if (p->se.on_rq)
1508 goto out_running;
1510 this_cpu = smp_processor_id();
1511 cpu = task_cpu(p);
1514 out_activate:
1515 #endif /* CONFIG_SMP */
1516 update_rq_clock(rq);
1517 activate_task(rq, p, 1);
1519 * Sync wakeups (i.e. those types of wakeups where the waker
1520 * has indicated that it will leave the CPU in short order)
1521 * don't trigger a preemption, if the woken up task will run on
1522 * this cpu. (in this case the 'I will reschedule' promise of
1523 * the waker guarantees that the freshly woken up task is going
1524 * to be considered on this CPU.)
1526 if (!sync || cpu != this_cpu)
1527 check_preempt_curr(rq, p);
1528 success = 1;
1530 out_running:
1531 p->state = TASK_RUNNING;
1532 out:
1533 task_rq_unlock(rq, &flags);
1535 return success;
1538 int fastcall wake_up_process(struct task_struct *p)
1540 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1541 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1543 EXPORT_SYMBOL(wake_up_process);
1545 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1547 return try_to_wake_up(p, state, 0);
1551 * Perform scheduler related setup for a newly forked process p.
1552 * p is forked by current.
1554 * __sched_fork() is basic setup used by init_idle() too:
1556 static void __sched_fork(struct task_struct *p)
1558 p->se.exec_start = 0;
1559 p->se.sum_exec_runtime = 0;
1560 p->se.prev_sum_exec_runtime = 0;
1562 #ifdef CONFIG_SCHEDSTATS
1563 p->se.wait_start = 0;
1564 p->se.sum_sleep_runtime = 0;
1565 p->se.sleep_start = 0;
1566 p->se.block_start = 0;
1567 p->se.sleep_max = 0;
1568 p->se.block_max = 0;
1569 p->se.exec_max = 0;
1570 p->se.slice_max = 0;
1571 p->se.wait_max = 0;
1572 #endif
1574 INIT_LIST_HEAD(&p->run_list);
1575 p->se.on_rq = 0;
1577 #ifdef CONFIG_PREEMPT_NOTIFIERS
1578 INIT_HLIST_HEAD(&p->preempt_notifiers);
1579 #endif
1582 * We mark the process as running here, but have not actually
1583 * inserted it onto the runqueue yet. This guarantees that
1584 * nobody will actually run it, and a signal or other external
1585 * event cannot wake it up and insert it on the runqueue either.
1587 p->state = TASK_RUNNING;
1591 * fork()/clone()-time setup:
1593 void sched_fork(struct task_struct *p, int clone_flags)
1595 int cpu = get_cpu();
1597 __sched_fork(p);
1599 #ifdef CONFIG_SMP
1600 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1601 #endif
1602 __set_task_cpu(p, cpu);
1605 * Make sure we do not leak PI boosting priority to the child:
1607 p->prio = current->normal_prio;
1609 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1610 if (likely(sched_info_on()))
1611 memset(&p->sched_info, 0, sizeof(p->sched_info));
1612 #endif
1613 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1614 p->oncpu = 0;
1615 #endif
1616 #ifdef CONFIG_PREEMPT
1617 /* Want to start with kernel preemption disabled. */
1618 task_thread_info(p)->preempt_count = 1;
1619 #endif
1620 put_cpu();
1624 * wake_up_new_task - wake up a newly created task for the first time.
1626 * This function will do some initial scheduler statistics housekeeping
1627 * that must be done for every newly created context, then puts the task
1628 * on the runqueue and wakes it.
1630 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1632 unsigned long flags;
1633 struct rq *rq;
1634 int this_cpu;
1636 rq = task_rq_lock(p, &flags);
1637 BUG_ON(p->state != TASK_RUNNING);
1638 this_cpu = smp_processor_id(); /* parent's CPU */
1639 update_rq_clock(rq);
1641 p->prio = effective_prio(p);
1643 if (rt_prio(p->prio))
1644 p->sched_class = &rt_sched_class;
1645 else
1646 p->sched_class = &fair_sched_class;
1648 if (task_cpu(p) != this_cpu || !p->sched_class->task_new ||
1649 !current->se.on_rq) {
1650 activate_task(rq, p, 0);
1651 } else {
1653 * Let the scheduling class do new task startup
1654 * management (if any):
1656 p->sched_class->task_new(rq, p);
1657 inc_nr_running(p, rq);
1659 check_preempt_curr(rq, p);
1660 task_rq_unlock(rq, &flags);
1663 #ifdef CONFIG_PREEMPT_NOTIFIERS
1666 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
1667 * @notifier: notifier struct to register
1669 void preempt_notifier_register(struct preempt_notifier *notifier)
1671 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1673 EXPORT_SYMBOL_GPL(preempt_notifier_register);
1676 * preempt_notifier_unregister - no longer interested in preemption notifications
1677 * @notifier: notifier struct to unregister
1679 * This is safe to call from within a preemption notifier.
1681 void preempt_notifier_unregister(struct preempt_notifier *notifier)
1683 hlist_del(&notifier->link);
1685 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1687 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1689 struct preempt_notifier *notifier;
1690 struct hlist_node *node;
1692 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1693 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1696 static void
1697 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1698 struct task_struct *next)
1700 struct preempt_notifier *notifier;
1701 struct hlist_node *node;
1703 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1704 notifier->ops->sched_out(notifier, next);
1707 #else
1709 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1713 static void
1714 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1715 struct task_struct *next)
1719 #endif
1722 * prepare_task_switch - prepare to switch tasks
1723 * @rq: the runqueue preparing to switch
1724 * @prev: the current task that is being switched out
1725 * @next: the task we are going to switch to.
1727 * This is called with the rq lock held and interrupts off. It must
1728 * be paired with a subsequent finish_task_switch after the context
1729 * switch.
1731 * prepare_task_switch sets up locking and calls architecture specific
1732 * hooks.
1734 static inline void
1735 prepare_task_switch(struct rq *rq, struct task_struct *prev,
1736 struct task_struct *next)
1738 fire_sched_out_preempt_notifiers(prev, next);
1739 prepare_lock_switch(rq, next);
1740 prepare_arch_switch(next);
1744 * finish_task_switch - clean up after a task-switch
1745 * @rq: runqueue associated with task-switch
1746 * @prev: the thread we just switched away from.
1748 * finish_task_switch must be called after the context switch, paired
1749 * with a prepare_task_switch call before the context switch.
1750 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1751 * and do any other architecture-specific cleanup actions.
1753 * Note that we may have delayed dropping an mm in context_switch(). If
1754 * so, we finish that here outside of the runqueue lock. (Doing it
1755 * with the lock held can cause deadlocks; see schedule() for
1756 * details.)
1758 static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1759 __releases(rq->lock)
1761 struct mm_struct *mm = rq->prev_mm;
1762 long prev_state;
1764 rq->prev_mm = NULL;
1767 * A task struct has one reference for the use as "current".
1768 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
1769 * schedule one last time. The schedule call will never return, and
1770 * the scheduled task must drop that reference.
1771 * The test for TASK_DEAD must occur while the runqueue locks are
1772 * still held, otherwise prev could be scheduled on another cpu, die
1773 * there before we look at prev->state, and then the reference would
1774 * be dropped twice.
1775 * Manfred Spraul <manfred@colorfullife.com>
1777 prev_state = prev->state;
1778 finish_arch_switch(prev);
1779 finish_lock_switch(rq, prev);
1780 fire_sched_in_preempt_notifiers(current);
1781 if (mm)
1782 mmdrop(mm);
1783 if (unlikely(prev_state == TASK_DEAD)) {
1785 * Remove function-return probe instances associated with this
1786 * task and put them back on the free list.
1788 kprobe_flush_task(prev);
1789 put_task_struct(prev);
1794 * schedule_tail - first thing a freshly forked thread must call.
1795 * @prev: the thread we just switched away from.
1797 asmlinkage void schedule_tail(struct task_struct *prev)
1798 __releases(rq->lock)
1800 struct rq *rq = this_rq();
1802 finish_task_switch(rq, prev);
1803 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1804 /* In this case, finish_task_switch does not reenable preemption */
1805 preempt_enable();
1806 #endif
1807 if (current->set_child_tid)
1808 put_user(current->pid, current->set_child_tid);
1812 * context_switch - switch to the new MM and the new
1813 * thread's register state.
1815 static inline void
1816 context_switch(struct rq *rq, struct task_struct *prev,
1817 struct task_struct *next)
1819 struct mm_struct *mm, *oldmm;
1821 prepare_task_switch(rq, prev, next);
1822 mm = next->mm;
1823 oldmm = prev->active_mm;
1825 * For paravirt, this is coupled with an exit in switch_to to
1826 * combine the page table reload and the switch backend into
1827 * one hypercall.
1829 arch_enter_lazy_cpu_mode();
1831 if (unlikely(!mm)) {
1832 next->active_mm = oldmm;
1833 atomic_inc(&oldmm->mm_count);
1834 enter_lazy_tlb(oldmm, next);
1835 } else
1836 switch_mm(oldmm, mm, next);
1838 if (unlikely(!prev->mm)) {
1839 prev->active_mm = NULL;
1840 rq->prev_mm = oldmm;
1843 * Since the runqueue lock will be released by the next
1844 * task (which is an invalid locking op but in the case
1845 * of the scheduler it's an obvious special-case), so we
1846 * do an early lockdep release here:
1848 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1849 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1850 #endif
1852 /* Here we just switch the register state and the stack. */
1853 switch_to(prev, next, prev);
1855 barrier();
1857 * this_rq must be evaluated again because prev may have moved
1858 * CPUs since it called schedule(), thus the 'rq' on its stack
1859 * frame will be invalid.
1861 finish_task_switch(this_rq(), prev);
1865 * nr_running, nr_uninterruptible and nr_context_switches:
1867 * externally visible scheduler statistics: current number of runnable
1868 * threads, current number of uninterruptible-sleeping threads, total
1869 * number of context switches performed since bootup.
1871 unsigned long nr_running(void)
1873 unsigned long i, sum = 0;
1875 for_each_online_cpu(i)
1876 sum += cpu_rq(i)->nr_running;
1878 return sum;
1881 unsigned long nr_uninterruptible(void)
1883 unsigned long i, sum = 0;
1885 for_each_possible_cpu(i)
1886 sum += cpu_rq(i)->nr_uninterruptible;
1889 * Since we read the counters lockless, it might be slightly
1890 * inaccurate. Do not allow it to go below zero though:
1892 if (unlikely((long)sum < 0))
1893 sum = 0;
1895 return sum;
1898 unsigned long long nr_context_switches(void)
1900 int i;
1901 unsigned long long sum = 0;
1903 for_each_possible_cpu(i)
1904 sum += cpu_rq(i)->nr_switches;
1906 return sum;
1909 unsigned long nr_iowait(void)
1911 unsigned long i, sum = 0;
1913 for_each_possible_cpu(i)
1914 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1916 return sum;
1919 unsigned long nr_active(void)
1921 unsigned long i, running = 0, uninterruptible = 0;
1923 for_each_online_cpu(i) {
1924 running += cpu_rq(i)->nr_running;
1925 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1928 if (unlikely((long)uninterruptible < 0))
1929 uninterruptible = 0;
1931 return running + uninterruptible;
1935 * Update rq->cpu_load[] statistics. This function is usually called every
1936 * scheduler tick (TICK_NSEC).
1938 static void update_cpu_load(struct rq *this_rq)
1940 unsigned long this_load = this_rq->load.weight;
1941 int i, scale;
1943 this_rq->nr_load_updates++;
1945 /* Update our load: */
1946 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
1947 unsigned long old_load, new_load;
1949 /* scale is effectively 1 << i now, and >> i divides by scale */
1951 old_load = this_rq->cpu_load[i];
1952 new_load = this_load;
1954 * Round up the averaging division if load is increasing. This
1955 * prevents us from getting stuck on 9 if the load is 10, for
1956 * example.
1958 if (new_load > old_load)
1959 new_load += scale-1;
1960 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
1964 #ifdef CONFIG_SMP
1967 * double_rq_lock - safely lock two runqueues
1969 * Note this does not disable interrupts like task_rq_lock,
1970 * you need to do so manually before calling.
1972 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1973 __acquires(rq1->lock)
1974 __acquires(rq2->lock)
1976 BUG_ON(!irqs_disabled());
1977 if (rq1 == rq2) {
1978 spin_lock(&rq1->lock);
1979 __acquire(rq2->lock); /* Fake it out ;) */
1980 } else {
1981 if (rq1 < rq2) {
1982 spin_lock(&rq1->lock);
1983 spin_lock(&rq2->lock);
1984 } else {
1985 spin_lock(&rq2->lock);
1986 spin_lock(&rq1->lock);
1989 update_rq_clock(rq1);
1990 update_rq_clock(rq2);
1994 * double_rq_unlock - safely unlock two runqueues
1996 * Note this does not restore interrupts like task_rq_unlock,
1997 * you need to do so manually after calling.
1999 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2000 __releases(rq1->lock)
2001 __releases(rq2->lock)
2003 spin_unlock(&rq1->lock);
2004 if (rq1 != rq2)
2005 spin_unlock(&rq2->lock);
2006 else
2007 __release(rq2->lock);
2011 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2013 static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
2014 __releases(this_rq->lock)
2015 __acquires(busiest->lock)
2016 __acquires(this_rq->lock)
2018 if (unlikely(!irqs_disabled())) {
2019 /* printk() doesn't work good under rq->lock */
2020 spin_unlock(&this_rq->lock);
2021 BUG_ON(1);
2023 if (unlikely(!spin_trylock(&busiest->lock))) {
2024 if (busiest < this_rq) {
2025 spin_unlock(&this_rq->lock);
2026 spin_lock(&busiest->lock);
2027 spin_lock(&this_rq->lock);
2028 } else
2029 spin_lock(&busiest->lock);
2034 * If dest_cpu is allowed for this process, migrate the task to it.
2035 * This is accomplished by forcing the cpu_allowed mask to only
2036 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2037 * the cpu_allowed mask is restored.
2039 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2041 struct migration_req req;
2042 unsigned long flags;
2043 struct rq *rq;
2045 rq = task_rq_lock(p, &flags);
2046 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2047 || unlikely(cpu_is_offline(dest_cpu)))
2048 goto out;
2050 /* force the process onto the specified CPU */
2051 if (migrate_task(p, dest_cpu, &req)) {
2052 /* Need to wait for migration thread (might exit: take ref). */
2053 struct task_struct *mt = rq->migration_thread;
2055 get_task_struct(mt);
2056 task_rq_unlock(rq, &flags);
2057 wake_up_process(mt);
2058 put_task_struct(mt);
2059 wait_for_completion(&req.done);
2061 return;
2063 out:
2064 task_rq_unlock(rq, &flags);
2068 * sched_exec - execve() is a valuable balancing opportunity, because at
2069 * this point the task has the smallest effective memory and cache footprint.
2071 void sched_exec(void)
2073 int new_cpu, this_cpu = get_cpu();
2074 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2075 put_cpu();
2076 if (new_cpu != this_cpu)
2077 sched_migrate_task(current, new_cpu);
2081 * pull_task - move a task from a remote runqueue to the local runqueue.
2082 * Both runqueues must be locked.
2084 static void pull_task(struct rq *src_rq, struct task_struct *p,
2085 struct rq *this_rq, int this_cpu)
2087 deactivate_task(src_rq, p, 0);
2088 set_task_cpu(p, this_cpu);
2089 activate_task(this_rq, p, 0);
2091 * Note that idle threads have a prio of MAX_PRIO, for this test
2092 * to be always true for them.
2094 check_preempt_curr(this_rq, p);
2098 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2100 static
2101 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2102 struct sched_domain *sd, enum cpu_idle_type idle,
2103 int *all_pinned)
2106 * We do not migrate tasks that are:
2107 * 1) running (obviously), or
2108 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2109 * 3) are cache-hot on their current CPU.
2111 if (!cpu_isset(this_cpu, p->cpus_allowed))
2112 return 0;
2113 *all_pinned = 0;
2115 if (task_running(rq, p))
2116 return 0;
2118 return 1;
2121 static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2122 unsigned long max_nr_move, unsigned long max_load_move,
2123 struct sched_domain *sd, enum cpu_idle_type idle,
2124 int *all_pinned, unsigned long *load_moved,
2125 int *this_best_prio, struct rq_iterator *iterator)
2127 int pulled = 0, pinned = 0, skip_for_load;
2128 struct task_struct *p;
2129 long rem_load_move = max_load_move;
2131 if (max_nr_move == 0 || max_load_move == 0)
2132 goto out;
2134 pinned = 1;
2137 * Start the load-balancing iterator:
2139 p = iterator->start(iterator->arg);
2140 next:
2141 if (!p)
2142 goto out;
2144 * To help distribute high priority tasks accross CPUs we don't
2145 * skip a task if it will be the highest priority task (i.e. smallest
2146 * prio value) on its new queue regardless of its load weight
2148 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2149 SCHED_LOAD_SCALE_FUZZ;
2150 if ((skip_for_load && p->prio >= *this_best_prio) ||
2151 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2152 p = iterator->next(iterator->arg);
2153 goto next;
2156 pull_task(busiest, p, this_rq, this_cpu);
2157 pulled++;
2158 rem_load_move -= p->se.load.weight;
2161 * We only want to steal up to the prescribed number of tasks
2162 * and the prescribed amount of weighted load.
2164 if (pulled < max_nr_move && rem_load_move > 0) {
2165 if (p->prio < *this_best_prio)
2166 *this_best_prio = p->prio;
2167 p = iterator->next(iterator->arg);
2168 goto next;
2170 out:
2172 * Right now, this is the only place pull_task() is called,
2173 * so we can safely collect pull_task() stats here rather than
2174 * inside pull_task().
2176 schedstat_add(sd, lb_gained[idle], pulled);
2178 if (all_pinned)
2179 *all_pinned = pinned;
2180 *load_moved = max_load_move - rem_load_move;
2181 return pulled;
2185 * move_tasks tries to move up to max_load_move weighted load from busiest to
2186 * this_rq, as part of a balancing operation within domain "sd".
2187 * Returns 1 if successful and 0 otherwise.
2189 * Called with both runqueues locked.
2191 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2192 unsigned long max_load_move,
2193 struct sched_domain *sd, enum cpu_idle_type idle,
2194 int *all_pinned)
2196 struct sched_class *class = sched_class_highest;
2197 unsigned long total_load_moved = 0;
2198 int this_best_prio = this_rq->curr->prio;
2200 do {
2201 total_load_moved +=
2202 class->load_balance(this_rq, this_cpu, busiest,
2203 ULONG_MAX, max_load_move - total_load_moved,
2204 sd, idle, all_pinned, &this_best_prio);
2205 class = class->next;
2206 } while (class && max_load_move > total_load_moved);
2208 return total_load_moved > 0;
2212 * move_one_task tries to move exactly one task from busiest to this_rq, as
2213 * part of active balancing operations within "domain".
2214 * Returns 1 if successful and 0 otherwise.
2216 * Called with both runqueues locked.
2218 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2219 struct sched_domain *sd, enum cpu_idle_type idle)
2221 struct sched_class *class;
2222 int this_best_prio = MAX_PRIO;
2224 for (class = sched_class_highest; class; class = class->next)
2225 if (class->load_balance(this_rq, this_cpu, busiest,
2226 1, ULONG_MAX, sd, idle, NULL,
2227 &this_best_prio))
2228 return 1;
2230 return 0;
2234 * find_busiest_group finds and returns the busiest CPU group within the
2235 * domain. It calculates and returns the amount of weighted load which
2236 * should be moved to restore balance via the imbalance parameter.
2238 static struct sched_group *
2239 find_busiest_group(struct sched_domain *sd, int this_cpu,
2240 unsigned long *imbalance, enum cpu_idle_type idle,
2241 int *sd_idle, cpumask_t *cpus, int *balance)
2243 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2244 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2245 unsigned long max_pull;
2246 unsigned long busiest_load_per_task, busiest_nr_running;
2247 unsigned long this_load_per_task, this_nr_running;
2248 int load_idx;
2249 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2250 int power_savings_balance = 1;
2251 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2252 unsigned long min_nr_running = ULONG_MAX;
2253 struct sched_group *group_min = NULL, *group_leader = NULL;
2254 #endif
2256 max_load = this_load = total_load = total_pwr = 0;
2257 busiest_load_per_task = busiest_nr_running = 0;
2258 this_load_per_task = this_nr_running = 0;
2259 if (idle == CPU_NOT_IDLE)
2260 load_idx = sd->busy_idx;
2261 else if (idle == CPU_NEWLY_IDLE)
2262 load_idx = sd->newidle_idx;
2263 else
2264 load_idx = sd->idle_idx;
2266 do {
2267 unsigned long load, group_capacity;
2268 int local_group;
2269 int i;
2270 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2271 unsigned long sum_nr_running, sum_weighted_load;
2273 local_group = cpu_isset(this_cpu, group->cpumask);
2275 if (local_group)
2276 balance_cpu = first_cpu(group->cpumask);
2278 /* Tally up the load of all CPUs in the group */
2279 sum_weighted_load = sum_nr_running = avg_load = 0;
2281 for_each_cpu_mask(i, group->cpumask) {
2282 struct rq *rq;
2284 if (!cpu_isset(i, *cpus))
2285 continue;
2287 rq = cpu_rq(i);
2289 if (*sd_idle && rq->nr_running)
2290 *sd_idle = 0;
2292 /* Bias balancing toward cpus of our domain */
2293 if (local_group) {
2294 if (idle_cpu(i) && !first_idle_cpu) {
2295 first_idle_cpu = 1;
2296 balance_cpu = i;
2299 load = target_load(i, load_idx);
2300 } else
2301 load = source_load(i, load_idx);
2303 avg_load += load;
2304 sum_nr_running += rq->nr_running;
2305 sum_weighted_load += weighted_cpuload(i);
2309 * First idle cpu or the first cpu(busiest) in this sched group
2310 * is eligible for doing load balancing at this and above
2311 * domains. In the newly idle case, we will allow all the cpu's
2312 * to do the newly idle load balance.
2314 if (idle != CPU_NEWLY_IDLE && local_group &&
2315 balance_cpu != this_cpu && balance) {
2316 *balance = 0;
2317 goto ret;
2320 total_load += avg_load;
2321 total_pwr += group->__cpu_power;
2323 /* Adjust by relative CPU power of the group */
2324 avg_load = sg_div_cpu_power(group,
2325 avg_load * SCHED_LOAD_SCALE);
2327 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2329 if (local_group) {
2330 this_load = avg_load;
2331 this = group;
2332 this_nr_running = sum_nr_running;
2333 this_load_per_task = sum_weighted_load;
2334 } else if (avg_load > max_load &&
2335 sum_nr_running > group_capacity) {
2336 max_load = avg_load;
2337 busiest = group;
2338 busiest_nr_running = sum_nr_running;
2339 busiest_load_per_task = sum_weighted_load;
2342 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2344 * Busy processors will not participate in power savings
2345 * balance.
2347 if (idle == CPU_NOT_IDLE ||
2348 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2349 goto group_next;
2352 * If the local group is idle or completely loaded
2353 * no need to do power savings balance at this domain
2355 if (local_group && (this_nr_running >= group_capacity ||
2356 !this_nr_running))
2357 power_savings_balance = 0;
2360 * If a group is already running at full capacity or idle,
2361 * don't include that group in power savings calculations
2363 if (!power_savings_balance || sum_nr_running >= group_capacity
2364 || !sum_nr_running)
2365 goto group_next;
2368 * Calculate the group which has the least non-idle load.
2369 * This is the group from where we need to pick up the load
2370 * for saving power
2372 if ((sum_nr_running < min_nr_running) ||
2373 (sum_nr_running == min_nr_running &&
2374 first_cpu(group->cpumask) <
2375 first_cpu(group_min->cpumask))) {
2376 group_min = group;
2377 min_nr_running = sum_nr_running;
2378 min_load_per_task = sum_weighted_load /
2379 sum_nr_running;
2383 * Calculate the group which is almost near its
2384 * capacity but still has some space to pick up some load
2385 * from other group and save more power
2387 if (sum_nr_running <= group_capacity - 1) {
2388 if (sum_nr_running > leader_nr_running ||
2389 (sum_nr_running == leader_nr_running &&
2390 first_cpu(group->cpumask) >
2391 first_cpu(group_leader->cpumask))) {
2392 group_leader = group;
2393 leader_nr_running = sum_nr_running;
2396 group_next:
2397 #endif
2398 group = group->next;
2399 } while (group != sd->groups);
2401 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2402 goto out_balanced;
2404 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2406 if (this_load >= avg_load ||
2407 100*max_load <= sd->imbalance_pct*this_load)
2408 goto out_balanced;
2410 busiest_load_per_task /= busiest_nr_running;
2412 * We're trying to get all the cpus to the average_load, so we don't
2413 * want to push ourselves above the average load, nor do we wish to
2414 * reduce the max loaded cpu below the average load, as either of these
2415 * actions would just result in more rebalancing later, and ping-pong
2416 * tasks around. Thus we look for the minimum possible imbalance.
2417 * Negative imbalances (*we* are more loaded than anyone else) will
2418 * be counted as no imbalance for these purposes -- we can't fix that
2419 * by pulling tasks to us. Be careful of negative numbers as they'll
2420 * appear as very large values with unsigned longs.
2422 if (max_load <= busiest_load_per_task)
2423 goto out_balanced;
2426 * In the presence of smp nice balancing, certain scenarios can have
2427 * max load less than avg load(as we skip the groups at or below
2428 * its cpu_power, while calculating max_load..)
2430 if (max_load < avg_load) {
2431 *imbalance = 0;
2432 goto small_imbalance;
2435 /* Don't want to pull so many tasks that a group would go idle */
2436 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2438 /* How much load to actually move to equalise the imbalance */
2439 *imbalance = min(max_pull * busiest->__cpu_power,
2440 (avg_load - this_load) * this->__cpu_power)
2441 / SCHED_LOAD_SCALE;
2444 * if *imbalance is less than the average load per runnable task
2445 * there is no gaurantee that any tasks will be moved so we'll have
2446 * a think about bumping its value to force at least one task to be
2447 * moved
2449 if (*imbalance < busiest_load_per_task) {
2450 unsigned long tmp, pwr_now, pwr_move;
2451 unsigned int imbn;
2453 small_imbalance:
2454 pwr_move = pwr_now = 0;
2455 imbn = 2;
2456 if (this_nr_running) {
2457 this_load_per_task /= this_nr_running;
2458 if (busiest_load_per_task > this_load_per_task)
2459 imbn = 1;
2460 } else
2461 this_load_per_task = SCHED_LOAD_SCALE;
2463 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2464 busiest_load_per_task * imbn) {
2465 *imbalance = busiest_load_per_task;
2466 return busiest;
2470 * OK, we don't have enough imbalance to justify moving tasks,
2471 * however we may be able to increase total CPU power used by
2472 * moving them.
2475 pwr_now += busiest->__cpu_power *
2476 min(busiest_load_per_task, max_load);
2477 pwr_now += this->__cpu_power *
2478 min(this_load_per_task, this_load);
2479 pwr_now /= SCHED_LOAD_SCALE;
2481 /* Amount of load we'd subtract */
2482 tmp = sg_div_cpu_power(busiest,
2483 busiest_load_per_task * SCHED_LOAD_SCALE);
2484 if (max_load > tmp)
2485 pwr_move += busiest->__cpu_power *
2486 min(busiest_load_per_task, max_load - tmp);
2488 /* Amount of load we'd add */
2489 if (max_load * busiest->__cpu_power <
2490 busiest_load_per_task * SCHED_LOAD_SCALE)
2491 tmp = sg_div_cpu_power(this,
2492 max_load * busiest->__cpu_power);
2493 else
2494 tmp = sg_div_cpu_power(this,
2495 busiest_load_per_task * SCHED_LOAD_SCALE);
2496 pwr_move += this->__cpu_power *
2497 min(this_load_per_task, this_load + tmp);
2498 pwr_move /= SCHED_LOAD_SCALE;
2500 /* Move if we gain throughput */
2501 if (pwr_move > pwr_now)
2502 *imbalance = busiest_load_per_task;
2505 return busiest;
2507 out_balanced:
2508 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2509 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2510 goto ret;
2512 if (this == group_leader && group_leader != group_min) {
2513 *imbalance = min_load_per_task;
2514 return group_min;
2516 #endif
2517 ret:
2518 *imbalance = 0;
2519 return NULL;
2523 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2525 static struct rq *
2526 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
2527 unsigned long imbalance, cpumask_t *cpus)
2529 struct rq *busiest = NULL, *rq;
2530 unsigned long max_load = 0;
2531 int i;
2533 for_each_cpu_mask(i, group->cpumask) {
2534 unsigned long wl;
2536 if (!cpu_isset(i, *cpus))
2537 continue;
2539 rq = cpu_rq(i);
2540 wl = weighted_cpuload(i);
2542 if (rq->nr_running == 1 && wl > imbalance)
2543 continue;
2545 if (wl > max_load) {
2546 max_load = wl;
2547 busiest = rq;
2551 return busiest;
2555 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2556 * so long as it is large enough.
2558 #define MAX_PINNED_INTERVAL 512
2561 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2562 * tasks if there is an imbalance.
2564 static int load_balance(int this_cpu, struct rq *this_rq,
2565 struct sched_domain *sd, enum cpu_idle_type idle,
2566 int *balance)
2568 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2569 struct sched_group *group;
2570 unsigned long imbalance;
2571 struct rq *busiest;
2572 cpumask_t cpus = CPU_MASK_ALL;
2573 unsigned long flags;
2576 * When power savings policy is enabled for the parent domain, idle
2577 * sibling can pick up load irrespective of busy siblings. In this case,
2578 * let the state of idle sibling percolate up as CPU_IDLE, instead of
2579 * portraying it as CPU_NOT_IDLE.
2581 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2582 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2583 sd_idle = 1;
2585 schedstat_inc(sd, lb_cnt[idle]);
2587 redo:
2588 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
2589 &cpus, balance);
2591 if (*balance == 0)
2592 goto out_balanced;
2594 if (!group) {
2595 schedstat_inc(sd, lb_nobusyg[idle]);
2596 goto out_balanced;
2599 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
2600 if (!busiest) {
2601 schedstat_inc(sd, lb_nobusyq[idle]);
2602 goto out_balanced;
2605 BUG_ON(busiest == this_rq);
2607 schedstat_add(sd, lb_imbalance[idle], imbalance);
2609 ld_moved = 0;
2610 if (busiest->nr_running > 1) {
2612 * Attempt to move tasks. If find_busiest_group has found
2613 * an imbalance but busiest->nr_running <= 1, the group is
2614 * still unbalanced. ld_moved simply stays zero, so it is
2615 * correctly treated as an imbalance.
2617 local_irq_save(flags);
2618 double_rq_lock(this_rq, busiest);
2619 ld_moved = move_tasks(this_rq, this_cpu, busiest,
2620 imbalance, sd, idle, &all_pinned);
2621 double_rq_unlock(this_rq, busiest);
2622 local_irq_restore(flags);
2625 * some other cpu did the load balance for us.
2627 if (ld_moved && this_cpu != smp_processor_id())
2628 resched_cpu(this_cpu);
2630 /* All tasks on this runqueue were pinned by CPU affinity */
2631 if (unlikely(all_pinned)) {
2632 cpu_clear(cpu_of(busiest), cpus);
2633 if (!cpus_empty(cpus))
2634 goto redo;
2635 goto out_balanced;
2639 if (!ld_moved) {
2640 schedstat_inc(sd, lb_failed[idle]);
2641 sd->nr_balance_failed++;
2643 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2645 spin_lock_irqsave(&busiest->lock, flags);
2647 /* don't kick the migration_thread, if the curr
2648 * task on busiest cpu can't be moved to this_cpu
2650 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2651 spin_unlock_irqrestore(&busiest->lock, flags);
2652 all_pinned = 1;
2653 goto out_one_pinned;
2656 if (!busiest->active_balance) {
2657 busiest->active_balance = 1;
2658 busiest->push_cpu = this_cpu;
2659 active_balance = 1;
2661 spin_unlock_irqrestore(&busiest->lock, flags);
2662 if (active_balance)
2663 wake_up_process(busiest->migration_thread);
2666 * We've kicked active balancing, reset the failure
2667 * counter.
2669 sd->nr_balance_failed = sd->cache_nice_tries+1;
2671 } else
2672 sd->nr_balance_failed = 0;
2674 if (likely(!active_balance)) {
2675 /* We were unbalanced, so reset the balancing interval */
2676 sd->balance_interval = sd->min_interval;
2677 } else {
2679 * If we've begun active balancing, start to back off. This
2680 * case may not be covered by the all_pinned logic if there
2681 * is only 1 task on the busy runqueue (because we don't call
2682 * move_tasks).
2684 if (sd->balance_interval < sd->max_interval)
2685 sd->balance_interval *= 2;
2688 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2689 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2690 return -1;
2691 return ld_moved;
2693 out_balanced:
2694 schedstat_inc(sd, lb_balanced[idle]);
2696 sd->nr_balance_failed = 0;
2698 out_one_pinned:
2699 /* tune up the balancing interval */
2700 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2701 (sd->balance_interval < sd->max_interval))
2702 sd->balance_interval *= 2;
2704 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2705 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2706 return -1;
2707 return 0;
2711 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2712 * tasks if there is an imbalance.
2714 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
2715 * this_rq is locked.
2717 static int
2718 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2720 struct sched_group *group;
2721 struct rq *busiest = NULL;
2722 unsigned long imbalance;
2723 int ld_moved = 0;
2724 int sd_idle = 0;
2725 int all_pinned = 0;
2726 cpumask_t cpus = CPU_MASK_ALL;
2729 * When power savings policy is enabled for the parent domain, idle
2730 * sibling can pick up load irrespective of busy siblings. In this case,
2731 * let the state of idle sibling percolate up as IDLE, instead of
2732 * portraying it as CPU_NOT_IDLE.
2734 if (sd->flags & SD_SHARE_CPUPOWER &&
2735 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2736 sd_idle = 1;
2738 schedstat_inc(sd, lb_cnt[CPU_NEWLY_IDLE]);
2739 redo:
2740 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
2741 &sd_idle, &cpus, NULL);
2742 if (!group) {
2743 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
2744 goto out_balanced;
2747 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
2748 &cpus);
2749 if (!busiest) {
2750 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
2751 goto out_balanced;
2754 BUG_ON(busiest == this_rq);
2756 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
2758 ld_moved = 0;
2759 if (busiest->nr_running > 1) {
2760 /* Attempt to move tasks */
2761 double_lock_balance(this_rq, busiest);
2762 /* this_rq->clock is already updated */
2763 update_rq_clock(busiest);
2764 ld_moved = move_tasks(this_rq, this_cpu, busiest,
2765 imbalance, sd, CPU_NEWLY_IDLE,
2766 &all_pinned);
2767 spin_unlock(&busiest->lock);
2769 if (unlikely(all_pinned)) {
2770 cpu_clear(cpu_of(busiest), cpus);
2771 if (!cpus_empty(cpus))
2772 goto redo;
2776 if (!ld_moved) {
2777 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
2778 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2779 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2780 return -1;
2781 } else
2782 sd->nr_balance_failed = 0;
2784 return ld_moved;
2786 out_balanced:
2787 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
2788 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2789 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2790 return -1;
2791 sd->nr_balance_failed = 0;
2793 return 0;
2797 * idle_balance is called by schedule() if this_cpu is about to become
2798 * idle. Attempts to pull tasks from other CPUs.
2800 static void idle_balance(int this_cpu, struct rq *this_rq)
2802 struct sched_domain *sd;
2803 int pulled_task = -1;
2804 unsigned long next_balance = jiffies + HZ;
2806 for_each_domain(this_cpu, sd) {
2807 unsigned long interval;
2809 if (!(sd->flags & SD_LOAD_BALANCE))
2810 continue;
2812 if (sd->flags & SD_BALANCE_NEWIDLE)
2813 /* If we've pulled tasks over stop searching: */
2814 pulled_task = load_balance_newidle(this_cpu,
2815 this_rq, sd);
2817 interval = msecs_to_jiffies(sd->balance_interval);
2818 if (time_after(next_balance, sd->last_balance + interval))
2819 next_balance = sd->last_balance + interval;
2820 if (pulled_task)
2821 break;
2823 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
2825 * We are going idle. next_balance may be set based on
2826 * a busy processor. So reset next_balance.
2828 this_rq->next_balance = next_balance;
2833 * active_load_balance is run by migration threads. It pushes running tasks
2834 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2835 * running on each physical CPU where possible, and avoids physical /
2836 * logical imbalances.
2838 * Called with busiest_rq locked.
2840 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
2842 int target_cpu = busiest_rq->push_cpu;
2843 struct sched_domain *sd;
2844 struct rq *target_rq;
2846 /* Is there any task to move? */
2847 if (busiest_rq->nr_running <= 1)
2848 return;
2850 target_rq = cpu_rq(target_cpu);
2853 * This condition is "impossible", if it occurs
2854 * we need to fix it. Originally reported by
2855 * Bjorn Helgaas on a 128-cpu setup.
2857 BUG_ON(busiest_rq == target_rq);
2859 /* move a task from busiest_rq to target_rq */
2860 double_lock_balance(busiest_rq, target_rq);
2861 update_rq_clock(busiest_rq);
2862 update_rq_clock(target_rq);
2864 /* Search for an sd spanning us and the target CPU. */
2865 for_each_domain(target_cpu, sd) {
2866 if ((sd->flags & SD_LOAD_BALANCE) &&
2867 cpu_isset(busiest_cpu, sd->span))
2868 break;
2871 if (likely(sd)) {
2872 schedstat_inc(sd, alb_cnt);
2874 if (move_one_task(target_rq, target_cpu, busiest_rq,
2875 sd, CPU_IDLE))
2876 schedstat_inc(sd, alb_pushed);
2877 else
2878 schedstat_inc(sd, alb_failed);
2880 spin_unlock(&target_rq->lock);
2883 #ifdef CONFIG_NO_HZ
2884 static struct {
2885 atomic_t load_balancer;
2886 cpumask_t cpu_mask;
2887 } nohz ____cacheline_aligned = {
2888 .load_balancer = ATOMIC_INIT(-1),
2889 .cpu_mask = CPU_MASK_NONE,
2893 * This routine will try to nominate the ilb (idle load balancing)
2894 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
2895 * load balancing on behalf of all those cpus. If all the cpus in the system
2896 * go into this tickless mode, then there will be no ilb owner (as there is
2897 * no need for one) and all the cpus will sleep till the next wakeup event
2898 * arrives...
2900 * For the ilb owner, tick is not stopped. And this tick will be used
2901 * for idle load balancing. ilb owner will still be part of
2902 * nohz.cpu_mask..
2904 * While stopping the tick, this cpu will become the ilb owner if there
2905 * is no other owner. And will be the owner till that cpu becomes busy
2906 * or if all cpus in the system stop their ticks at which point
2907 * there is no need for ilb owner.
2909 * When the ilb owner becomes busy, it nominates another owner, during the
2910 * next busy scheduler_tick()
2912 int select_nohz_load_balancer(int stop_tick)
2914 int cpu = smp_processor_id();
2916 if (stop_tick) {
2917 cpu_set(cpu, nohz.cpu_mask);
2918 cpu_rq(cpu)->in_nohz_recently = 1;
2921 * If we are going offline and still the leader, give up!
2923 if (cpu_is_offline(cpu) &&
2924 atomic_read(&nohz.load_balancer) == cpu) {
2925 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
2926 BUG();
2927 return 0;
2930 /* time for ilb owner also to sleep */
2931 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
2932 if (atomic_read(&nohz.load_balancer) == cpu)
2933 atomic_set(&nohz.load_balancer, -1);
2934 return 0;
2937 if (atomic_read(&nohz.load_balancer) == -1) {
2938 /* make me the ilb owner */
2939 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
2940 return 1;
2941 } else if (atomic_read(&nohz.load_balancer) == cpu)
2942 return 1;
2943 } else {
2944 if (!cpu_isset(cpu, nohz.cpu_mask))
2945 return 0;
2947 cpu_clear(cpu, nohz.cpu_mask);
2949 if (atomic_read(&nohz.load_balancer) == cpu)
2950 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
2951 BUG();
2953 return 0;
2955 #endif
2957 static DEFINE_SPINLOCK(balancing);
2960 * It checks each scheduling domain to see if it is due to be balanced,
2961 * and initiates a balancing operation if so.
2963 * Balancing parameters are set up in arch_init_sched_domains.
2965 static inline void rebalance_domains(int cpu, enum cpu_idle_type idle)
2967 int balance = 1;
2968 struct rq *rq = cpu_rq(cpu);
2969 unsigned long interval;
2970 struct sched_domain *sd;
2971 /* Earliest time when we have to do rebalance again */
2972 unsigned long next_balance = jiffies + 60*HZ;
2973 int update_next_balance = 0;
2975 for_each_domain(cpu, sd) {
2976 if (!(sd->flags & SD_LOAD_BALANCE))
2977 continue;
2979 interval = sd->balance_interval;
2980 if (idle != CPU_IDLE)
2981 interval *= sd->busy_factor;
2983 /* scale ms to jiffies */
2984 interval = msecs_to_jiffies(interval);
2985 if (unlikely(!interval))
2986 interval = 1;
2987 if (interval > HZ*NR_CPUS/10)
2988 interval = HZ*NR_CPUS/10;
2991 if (sd->flags & SD_SERIALIZE) {
2992 if (!spin_trylock(&balancing))
2993 goto out;
2996 if (time_after_eq(jiffies, sd->last_balance + interval)) {
2997 if (load_balance(cpu, rq, sd, idle, &balance)) {
2999 * We've pulled tasks over so either we're no
3000 * longer idle, or one of our SMT siblings is
3001 * not idle.
3003 idle = CPU_NOT_IDLE;
3005 sd->last_balance = jiffies;
3007 if (sd->flags & SD_SERIALIZE)
3008 spin_unlock(&balancing);
3009 out:
3010 if (time_after(next_balance, sd->last_balance + interval)) {
3011 next_balance = sd->last_balance + interval;
3012 update_next_balance = 1;
3016 * Stop the load balance at this level. There is another
3017 * CPU in our sched group which is doing load balancing more
3018 * actively.
3020 if (!balance)
3021 break;
3025 * next_balance will be updated only when there is a need.
3026 * When the cpu is attached to null domain for ex, it will not be
3027 * updated.
3029 if (likely(update_next_balance))
3030 rq->next_balance = next_balance;
3034 * run_rebalance_domains is triggered when needed from the scheduler tick.
3035 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3036 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3038 static void run_rebalance_domains(struct softirq_action *h)
3040 int this_cpu = smp_processor_id();
3041 struct rq *this_rq = cpu_rq(this_cpu);
3042 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3043 CPU_IDLE : CPU_NOT_IDLE;
3045 rebalance_domains(this_cpu, idle);
3047 #ifdef CONFIG_NO_HZ
3049 * If this cpu is the owner for idle load balancing, then do the
3050 * balancing on behalf of the other idle cpus whose ticks are
3051 * stopped.
3053 if (this_rq->idle_at_tick &&
3054 atomic_read(&nohz.load_balancer) == this_cpu) {
3055 cpumask_t cpus = nohz.cpu_mask;
3056 struct rq *rq;
3057 int balance_cpu;
3059 cpu_clear(this_cpu, cpus);
3060 for_each_cpu_mask(balance_cpu, cpus) {
3062 * If this cpu gets work to do, stop the load balancing
3063 * work being done for other cpus. Next load
3064 * balancing owner will pick it up.
3066 if (need_resched())
3067 break;
3069 rebalance_domains(balance_cpu, CPU_IDLE);
3071 rq = cpu_rq(balance_cpu);
3072 if (time_after(this_rq->next_balance, rq->next_balance))
3073 this_rq->next_balance = rq->next_balance;
3076 #endif
3080 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3082 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3083 * idle load balancing owner or decide to stop the periodic load balancing,
3084 * if the whole system is idle.
3086 static inline void trigger_load_balance(struct rq *rq, int cpu)
3088 #ifdef CONFIG_NO_HZ
3090 * If we were in the nohz mode recently and busy at the current
3091 * scheduler tick, then check if we need to nominate new idle
3092 * load balancer.
3094 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3095 rq->in_nohz_recently = 0;
3097 if (atomic_read(&nohz.load_balancer) == cpu) {
3098 cpu_clear(cpu, nohz.cpu_mask);
3099 atomic_set(&nohz.load_balancer, -1);
3102 if (atomic_read(&nohz.load_balancer) == -1) {
3104 * simple selection for now: Nominate the
3105 * first cpu in the nohz list to be the next
3106 * ilb owner.
3108 * TBD: Traverse the sched domains and nominate
3109 * the nearest cpu in the nohz.cpu_mask.
3111 int ilb = first_cpu(nohz.cpu_mask);
3113 if (ilb != NR_CPUS)
3114 resched_cpu(ilb);
3119 * If this cpu is idle and doing idle load balancing for all the
3120 * cpus with ticks stopped, is it time for that to stop?
3122 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3123 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3124 resched_cpu(cpu);
3125 return;
3129 * If this cpu is idle and the idle load balancing is done by
3130 * someone else, then no need raise the SCHED_SOFTIRQ
3132 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3133 cpu_isset(cpu, nohz.cpu_mask))
3134 return;
3135 #endif
3136 if (time_after_eq(jiffies, rq->next_balance))
3137 raise_softirq(SCHED_SOFTIRQ);
3140 #else /* CONFIG_SMP */
3143 * on UP we do not need to balance between CPUs:
3145 static inline void idle_balance(int cpu, struct rq *rq)
3149 /* Avoid "used but not defined" warning on UP */
3150 static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3151 unsigned long max_nr_move, unsigned long max_load_move,
3152 struct sched_domain *sd, enum cpu_idle_type idle,
3153 int *all_pinned, unsigned long *load_moved,
3154 int *this_best_prio, struct rq_iterator *iterator)
3156 *load_moved = 0;
3158 return 0;
3161 #endif
3163 DEFINE_PER_CPU(struct kernel_stat, kstat);
3165 EXPORT_PER_CPU_SYMBOL(kstat);
3168 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3169 * that have not yet been banked in case the task is currently running.
3171 unsigned long long task_sched_runtime(struct task_struct *p)
3173 unsigned long flags;
3174 u64 ns, delta_exec;
3175 struct rq *rq;
3177 rq = task_rq_lock(p, &flags);
3178 ns = p->se.sum_exec_runtime;
3179 if (rq->curr == p) {
3180 update_rq_clock(rq);
3181 delta_exec = rq->clock - p->se.exec_start;
3182 if ((s64)delta_exec > 0)
3183 ns += delta_exec;
3185 task_rq_unlock(rq, &flags);
3187 return ns;
3191 * Account user cpu time to a process.
3192 * @p: the process that the cpu time gets accounted to
3193 * @hardirq_offset: the offset to subtract from hardirq_count()
3194 * @cputime: the cpu time spent in user space since the last update
3196 void account_user_time(struct task_struct *p, cputime_t cputime)
3198 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3199 cputime64_t tmp;
3201 p->utime = cputime_add(p->utime, cputime);
3203 /* Add user time to cpustat. */
3204 tmp = cputime_to_cputime64(cputime);
3205 if (TASK_NICE(p) > 0)
3206 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3207 else
3208 cpustat->user = cputime64_add(cpustat->user, tmp);
3212 * Account system cpu time to a process.
3213 * @p: the process that the cpu time gets accounted to
3214 * @hardirq_offset: the offset to subtract from hardirq_count()
3215 * @cputime: the cpu time spent in kernel space since the last update
3217 void account_system_time(struct task_struct *p, int hardirq_offset,
3218 cputime_t cputime)
3220 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3221 struct rq *rq = this_rq();
3222 cputime64_t tmp;
3224 p->stime = cputime_add(p->stime, cputime);
3226 /* Add system time to cpustat. */
3227 tmp = cputime_to_cputime64(cputime);
3228 if (hardirq_count() - hardirq_offset)
3229 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3230 else if (softirq_count())
3231 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3232 else if (p != rq->idle)
3233 cpustat->system = cputime64_add(cpustat->system, tmp);
3234 else if (atomic_read(&rq->nr_iowait) > 0)
3235 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3236 else
3237 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3238 /* Account for system time used */
3239 acct_update_integrals(p);
3243 * Account for involuntary wait time.
3244 * @p: the process from which the cpu time has been stolen
3245 * @steal: the cpu time spent in involuntary wait
3247 void account_steal_time(struct task_struct *p, cputime_t steal)
3249 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3250 cputime64_t tmp = cputime_to_cputime64(steal);
3251 struct rq *rq = this_rq();
3253 if (p == rq->idle) {
3254 p->stime = cputime_add(p->stime, steal);
3255 if (atomic_read(&rq->nr_iowait) > 0)
3256 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3257 else
3258 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3259 } else
3260 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3264 * This function gets called by the timer code, with HZ frequency.
3265 * We call it with interrupts disabled.
3267 * It also gets called by the fork code, when changing the parent's
3268 * timeslices.
3270 void scheduler_tick(void)
3272 int cpu = smp_processor_id();
3273 struct rq *rq = cpu_rq(cpu);
3274 struct task_struct *curr = rq->curr;
3275 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3277 spin_lock(&rq->lock);
3278 __update_rq_clock(rq);
3280 * Let rq->clock advance by at least TICK_NSEC:
3282 if (unlikely(rq->clock < next_tick))
3283 rq->clock = next_tick;
3284 rq->tick_timestamp = rq->clock;
3285 update_cpu_load(rq);
3286 if (curr != rq->idle) /* FIXME: needed? */
3287 curr->sched_class->task_tick(rq, curr);
3288 spin_unlock(&rq->lock);
3290 #ifdef CONFIG_SMP
3291 rq->idle_at_tick = idle_cpu(cpu);
3292 trigger_load_balance(rq, cpu);
3293 #endif
3296 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3298 void fastcall add_preempt_count(int val)
3301 * Underflow?
3303 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3304 return;
3305 preempt_count() += val;
3307 * Spinlock count overflowing soon?
3309 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3310 PREEMPT_MASK - 10);
3312 EXPORT_SYMBOL(add_preempt_count);
3314 void fastcall sub_preempt_count(int val)
3317 * Underflow?
3319 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3320 return;
3322 * Is the spinlock portion underflowing?
3324 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3325 !(preempt_count() & PREEMPT_MASK)))
3326 return;
3328 preempt_count() -= val;
3330 EXPORT_SYMBOL(sub_preempt_count);
3332 #endif
3335 * Print scheduling while atomic bug:
3337 static noinline void __schedule_bug(struct task_struct *prev)
3339 printk(KERN_ERR "BUG: scheduling while atomic: %s/0x%08x/%d\n",
3340 prev->comm, preempt_count(), prev->pid);
3341 debug_show_held_locks(prev);
3342 if (irqs_disabled())
3343 print_irqtrace_events(prev);
3344 dump_stack();
3348 * Various schedule()-time debugging checks and statistics:
3350 static inline void schedule_debug(struct task_struct *prev)
3353 * Test if we are atomic. Since do_exit() needs to call into
3354 * schedule() atomically, we ignore that path for now.
3355 * Otherwise, whine if we are scheduling when we should not be.
3357 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3358 __schedule_bug(prev);
3360 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3362 schedstat_inc(this_rq(), sched_cnt);
3366 * Pick up the highest-prio task:
3368 static inline struct task_struct *
3369 pick_next_task(struct rq *rq, struct task_struct *prev)
3371 struct sched_class *class;
3372 struct task_struct *p;
3375 * Optimization: we know that if all tasks are in
3376 * the fair class we can call that function directly:
3378 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3379 p = fair_sched_class.pick_next_task(rq);
3380 if (likely(p))
3381 return p;
3384 class = sched_class_highest;
3385 for ( ; ; ) {
3386 p = class->pick_next_task(rq);
3387 if (p)
3388 return p;
3390 * Will never be NULL as the idle class always
3391 * returns a non-NULL p:
3393 class = class->next;
3398 * schedule() is the main scheduler function.
3400 asmlinkage void __sched schedule(void)
3402 struct task_struct *prev, *next;
3403 long *switch_count;
3404 struct rq *rq;
3405 int cpu;
3407 need_resched:
3408 preempt_disable();
3409 cpu = smp_processor_id();
3410 rq = cpu_rq(cpu);
3411 rcu_qsctr_inc(cpu);
3412 prev = rq->curr;
3413 switch_count = &prev->nivcsw;
3415 release_kernel_lock(prev);
3416 need_resched_nonpreemptible:
3418 schedule_debug(prev);
3420 spin_lock_irq(&rq->lock);
3421 clear_tsk_need_resched(prev);
3422 __update_rq_clock(rq);
3424 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3425 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3426 unlikely(signal_pending(prev)))) {
3427 prev->state = TASK_RUNNING;
3428 } else {
3429 deactivate_task(rq, prev, 1);
3431 switch_count = &prev->nvcsw;
3434 if (unlikely(!rq->nr_running))
3435 idle_balance(cpu, rq);
3437 prev->sched_class->put_prev_task(rq, prev);
3438 next = pick_next_task(rq, prev);
3440 sched_info_switch(prev, next);
3442 if (likely(prev != next)) {
3443 rq->nr_switches++;
3444 rq->curr = next;
3445 ++*switch_count;
3447 context_switch(rq, prev, next); /* unlocks the rq */
3448 } else
3449 spin_unlock_irq(&rq->lock);
3451 if (unlikely(reacquire_kernel_lock(current) < 0)) {
3452 cpu = smp_processor_id();
3453 rq = cpu_rq(cpu);
3454 goto need_resched_nonpreemptible;
3456 preempt_enable_no_resched();
3457 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3458 goto need_resched;
3460 EXPORT_SYMBOL(schedule);
3462 #ifdef CONFIG_PREEMPT
3464 * this is the entry point to schedule() from in-kernel preemption
3465 * off of preempt_enable. Kernel preemptions off return from interrupt
3466 * occur there and call schedule directly.
3468 asmlinkage void __sched preempt_schedule(void)
3470 struct thread_info *ti = current_thread_info();
3471 #ifdef CONFIG_PREEMPT_BKL
3472 struct task_struct *task = current;
3473 int saved_lock_depth;
3474 #endif
3476 * If there is a non-zero preempt_count or interrupts are disabled,
3477 * we do not want to preempt the current task. Just return..
3479 if (likely(ti->preempt_count || irqs_disabled()))
3480 return;
3482 need_resched:
3483 add_preempt_count(PREEMPT_ACTIVE);
3485 * We keep the big kernel semaphore locked, but we
3486 * clear ->lock_depth so that schedule() doesnt
3487 * auto-release the semaphore:
3489 #ifdef CONFIG_PREEMPT_BKL
3490 saved_lock_depth = task->lock_depth;
3491 task->lock_depth = -1;
3492 #endif
3493 schedule();
3494 #ifdef CONFIG_PREEMPT_BKL
3495 task->lock_depth = saved_lock_depth;
3496 #endif
3497 sub_preempt_count(PREEMPT_ACTIVE);
3499 /* we could miss a preemption opportunity between schedule and now */
3500 barrier();
3501 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3502 goto need_resched;
3504 EXPORT_SYMBOL(preempt_schedule);
3507 * this is the entry point to schedule() from kernel preemption
3508 * off of irq context.
3509 * Note, that this is called and return with irqs disabled. This will
3510 * protect us against recursive calling from irq.
3512 asmlinkage void __sched preempt_schedule_irq(void)
3514 struct thread_info *ti = current_thread_info();
3515 #ifdef CONFIG_PREEMPT_BKL
3516 struct task_struct *task = current;
3517 int saved_lock_depth;
3518 #endif
3519 /* Catch callers which need to be fixed */
3520 BUG_ON(ti->preempt_count || !irqs_disabled());
3522 need_resched:
3523 add_preempt_count(PREEMPT_ACTIVE);
3525 * We keep the big kernel semaphore locked, but we
3526 * clear ->lock_depth so that schedule() doesnt
3527 * auto-release the semaphore:
3529 #ifdef CONFIG_PREEMPT_BKL
3530 saved_lock_depth = task->lock_depth;
3531 task->lock_depth = -1;
3532 #endif
3533 local_irq_enable();
3534 schedule();
3535 local_irq_disable();
3536 #ifdef CONFIG_PREEMPT_BKL
3537 task->lock_depth = saved_lock_depth;
3538 #endif
3539 sub_preempt_count(PREEMPT_ACTIVE);
3541 /* we could miss a preemption opportunity between schedule and now */
3542 barrier();
3543 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3544 goto need_resched;
3547 #endif /* CONFIG_PREEMPT */
3549 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3550 void *key)
3552 return try_to_wake_up(curr->private, mode, sync);
3554 EXPORT_SYMBOL(default_wake_function);
3557 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3558 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3559 * number) then we wake all the non-exclusive tasks and one exclusive task.
3561 * There are circumstances in which we can try to wake a task which has already
3562 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3563 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3565 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3566 int nr_exclusive, int sync, void *key)
3568 wait_queue_t *curr, *next;
3570 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3571 unsigned flags = curr->flags;
3573 if (curr->func(curr, mode, sync, key) &&
3574 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3575 break;
3580 * __wake_up - wake up threads blocked on a waitqueue.
3581 * @q: the waitqueue
3582 * @mode: which threads
3583 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3584 * @key: is directly passed to the wakeup function
3586 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3587 int nr_exclusive, void *key)
3589 unsigned long flags;
3591 spin_lock_irqsave(&q->lock, flags);
3592 __wake_up_common(q, mode, nr_exclusive, 0, key);
3593 spin_unlock_irqrestore(&q->lock, flags);
3595 EXPORT_SYMBOL(__wake_up);
3598 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3600 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3602 __wake_up_common(q, mode, 1, 0, NULL);
3606 * __wake_up_sync - wake up threads blocked on a waitqueue.
3607 * @q: the waitqueue
3608 * @mode: which threads
3609 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3611 * The sync wakeup differs that the waker knows that it will schedule
3612 * away soon, so while the target thread will be woken up, it will not
3613 * be migrated to another CPU - ie. the two threads are 'synchronized'
3614 * with each other. This can prevent needless bouncing between CPUs.
3616 * On UP it can prevent extra preemption.
3618 void fastcall
3619 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3621 unsigned long flags;
3622 int sync = 1;
3624 if (unlikely(!q))
3625 return;
3627 if (unlikely(!nr_exclusive))
3628 sync = 0;
3630 spin_lock_irqsave(&q->lock, flags);
3631 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3632 spin_unlock_irqrestore(&q->lock, flags);
3634 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3636 void fastcall complete(struct completion *x)
3638 unsigned long flags;
3640 spin_lock_irqsave(&x->wait.lock, flags);
3641 x->done++;
3642 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3643 1, 0, NULL);
3644 spin_unlock_irqrestore(&x->wait.lock, flags);
3646 EXPORT_SYMBOL(complete);
3648 void fastcall complete_all(struct completion *x)
3650 unsigned long flags;
3652 spin_lock_irqsave(&x->wait.lock, flags);
3653 x->done += UINT_MAX/2;
3654 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3655 0, 0, NULL);
3656 spin_unlock_irqrestore(&x->wait.lock, flags);
3658 EXPORT_SYMBOL(complete_all);
3660 void fastcall __sched wait_for_completion(struct completion *x)
3662 might_sleep();
3664 spin_lock_irq(&x->wait.lock);
3665 if (!x->done) {
3666 DECLARE_WAITQUEUE(wait, current);
3668 wait.flags |= WQ_FLAG_EXCLUSIVE;
3669 __add_wait_queue_tail(&x->wait, &wait);
3670 do {
3671 __set_current_state(TASK_UNINTERRUPTIBLE);
3672 spin_unlock_irq(&x->wait.lock);
3673 schedule();
3674 spin_lock_irq(&x->wait.lock);
3675 } while (!x->done);
3676 __remove_wait_queue(&x->wait, &wait);
3678 x->done--;
3679 spin_unlock_irq(&x->wait.lock);
3681 EXPORT_SYMBOL(wait_for_completion);
3683 unsigned long fastcall __sched
3684 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3686 might_sleep();
3688 spin_lock_irq(&x->wait.lock);
3689 if (!x->done) {
3690 DECLARE_WAITQUEUE(wait, current);
3692 wait.flags |= WQ_FLAG_EXCLUSIVE;
3693 __add_wait_queue_tail(&x->wait, &wait);
3694 do {
3695 __set_current_state(TASK_UNINTERRUPTIBLE);
3696 spin_unlock_irq(&x->wait.lock);
3697 timeout = schedule_timeout(timeout);
3698 spin_lock_irq(&x->wait.lock);
3699 if (!timeout) {
3700 __remove_wait_queue(&x->wait, &wait);
3701 goto out;
3703 } while (!x->done);
3704 __remove_wait_queue(&x->wait, &wait);
3706 x->done--;
3707 out:
3708 spin_unlock_irq(&x->wait.lock);
3709 return timeout;
3711 EXPORT_SYMBOL(wait_for_completion_timeout);
3713 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3715 int ret = 0;
3717 might_sleep();
3719 spin_lock_irq(&x->wait.lock);
3720 if (!x->done) {
3721 DECLARE_WAITQUEUE(wait, current);
3723 wait.flags |= WQ_FLAG_EXCLUSIVE;
3724 __add_wait_queue_tail(&x->wait, &wait);
3725 do {
3726 if (signal_pending(current)) {
3727 ret = -ERESTARTSYS;
3728 __remove_wait_queue(&x->wait, &wait);
3729 goto out;
3731 __set_current_state(TASK_INTERRUPTIBLE);
3732 spin_unlock_irq(&x->wait.lock);
3733 schedule();
3734 spin_lock_irq(&x->wait.lock);
3735 } while (!x->done);
3736 __remove_wait_queue(&x->wait, &wait);
3738 x->done--;
3739 out:
3740 spin_unlock_irq(&x->wait.lock);
3742 return ret;
3744 EXPORT_SYMBOL(wait_for_completion_interruptible);
3746 unsigned long fastcall __sched
3747 wait_for_completion_interruptible_timeout(struct completion *x,
3748 unsigned long timeout)
3750 might_sleep();
3752 spin_lock_irq(&x->wait.lock);
3753 if (!x->done) {
3754 DECLARE_WAITQUEUE(wait, current);
3756 wait.flags |= WQ_FLAG_EXCLUSIVE;
3757 __add_wait_queue_tail(&x->wait, &wait);
3758 do {
3759 if (signal_pending(current)) {
3760 timeout = -ERESTARTSYS;
3761 __remove_wait_queue(&x->wait, &wait);
3762 goto out;
3764 __set_current_state(TASK_INTERRUPTIBLE);
3765 spin_unlock_irq(&x->wait.lock);
3766 timeout = schedule_timeout(timeout);
3767 spin_lock_irq(&x->wait.lock);
3768 if (!timeout) {
3769 __remove_wait_queue(&x->wait, &wait);
3770 goto out;
3772 } while (!x->done);
3773 __remove_wait_queue(&x->wait, &wait);
3775 x->done--;
3776 out:
3777 spin_unlock_irq(&x->wait.lock);
3778 return timeout;
3780 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3782 static inline void
3783 sleep_on_head(wait_queue_head_t *q, wait_queue_t *wait, unsigned long *flags)
3785 spin_lock_irqsave(&q->lock, *flags);
3786 __add_wait_queue(q, wait);
3787 spin_unlock(&q->lock);
3790 static inline void
3791 sleep_on_tail(wait_queue_head_t *q, wait_queue_t *wait, unsigned long *flags)
3793 spin_lock_irq(&q->lock);
3794 __remove_wait_queue(q, wait);
3795 spin_unlock_irqrestore(&q->lock, *flags);
3798 void __sched interruptible_sleep_on(wait_queue_head_t *q)
3800 unsigned long flags;
3801 wait_queue_t wait;
3803 init_waitqueue_entry(&wait, current);
3805 current->state = TASK_INTERRUPTIBLE;
3807 sleep_on_head(q, &wait, &flags);
3808 schedule();
3809 sleep_on_tail(q, &wait, &flags);
3811 EXPORT_SYMBOL(interruptible_sleep_on);
3813 long __sched
3814 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3816 unsigned long flags;
3817 wait_queue_t wait;
3819 init_waitqueue_entry(&wait, current);
3821 current->state = TASK_INTERRUPTIBLE;
3823 sleep_on_head(q, &wait, &flags);
3824 timeout = schedule_timeout(timeout);
3825 sleep_on_tail(q, &wait, &flags);
3827 return timeout;
3829 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3831 void __sched sleep_on(wait_queue_head_t *q)
3833 unsigned long flags;
3834 wait_queue_t wait;
3836 init_waitqueue_entry(&wait, current);
3838 current->state = TASK_UNINTERRUPTIBLE;
3840 sleep_on_head(q, &wait, &flags);
3841 schedule();
3842 sleep_on_tail(q, &wait, &flags);
3844 EXPORT_SYMBOL(sleep_on);
3846 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3848 unsigned long flags;
3849 wait_queue_t wait;
3851 init_waitqueue_entry(&wait, current);
3853 current->state = TASK_UNINTERRUPTIBLE;
3855 sleep_on_head(q, &wait, &flags);
3856 timeout = schedule_timeout(timeout);
3857 sleep_on_tail(q, &wait, &flags);
3859 return timeout;
3861 EXPORT_SYMBOL(sleep_on_timeout);
3863 #ifdef CONFIG_RT_MUTEXES
3866 * rt_mutex_setprio - set the current priority of a task
3867 * @p: task
3868 * @prio: prio value (kernel-internal form)
3870 * This function changes the 'effective' priority of a task. It does
3871 * not touch ->normal_prio like __setscheduler().
3873 * Used by the rt_mutex code to implement priority inheritance logic.
3875 void rt_mutex_setprio(struct task_struct *p, int prio)
3877 unsigned long flags;
3878 int oldprio, on_rq;
3879 struct rq *rq;
3881 BUG_ON(prio < 0 || prio > MAX_PRIO);
3883 rq = task_rq_lock(p, &flags);
3884 update_rq_clock(rq);
3886 oldprio = p->prio;
3887 on_rq = p->se.on_rq;
3888 if (on_rq)
3889 dequeue_task(rq, p, 0);
3891 if (rt_prio(prio))
3892 p->sched_class = &rt_sched_class;
3893 else
3894 p->sched_class = &fair_sched_class;
3896 p->prio = prio;
3898 if (on_rq) {
3899 enqueue_task(rq, p, 0);
3901 * Reschedule if we are currently running on this runqueue and
3902 * our priority decreased, or if we are not currently running on
3903 * this runqueue and our priority is higher than the current's
3905 if (task_running(rq, p)) {
3906 if (p->prio > oldprio)
3907 resched_task(rq->curr);
3908 } else {
3909 check_preempt_curr(rq, p);
3912 task_rq_unlock(rq, &flags);
3915 #endif
3917 void set_user_nice(struct task_struct *p, long nice)
3919 int old_prio, delta, on_rq;
3920 unsigned long flags;
3921 struct rq *rq;
3923 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3924 return;
3926 * We have to be careful, if called from sys_setpriority(),
3927 * the task might be in the middle of scheduling on another CPU.
3929 rq = task_rq_lock(p, &flags);
3930 update_rq_clock(rq);
3932 * The RT priorities are set via sched_setscheduler(), but we still
3933 * allow the 'normal' nice value to be set - but as expected
3934 * it wont have any effect on scheduling until the task is
3935 * SCHED_FIFO/SCHED_RR:
3937 if (task_has_rt_policy(p)) {
3938 p->static_prio = NICE_TO_PRIO(nice);
3939 goto out_unlock;
3941 on_rq = p->se.on_rq;
3942 if (on_rq) {
3943 dequeue_task(rq, p, 0);
3944 dec_load(rq, p);
3947 p->static_prio = NICE_TO_PRIO(nice);
3948 set_load_weight(p);
3949 old_prio = p->prio;
3950 p->prio = effective_prio(p);
3951 delta = p->prio - old_prio;
3953 if (on_rq) {
3954 enqueue_task(rq, p, 0);
3955 inc_load(rq, p);
3957 * If the task increased its priority or is running and
3958 * lowered its priority, then reschedule its CPU:
3960 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3961 resched_task(rq->curr);
3963 out_unlock:
3964 task_rq_unlock(rq, &flags);
3966 EXPORT_SYMBOL(set_user_nice);
3969 * can_nice - check if a task can reduce its nice value
3970 * @p: task
3971 * @nice: nice value
3973 int can_nice(const struct task_struct *p, const int nice)
3975 /* convert nice value [19,-20] to rlimit style value [1,40] */
3976 int nice_rlim = 20 - nice;
3978 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3979 capable(CAP_SYS_NICE));
3982 #ifdef __ARCH_WANT_SYS_NICE
3985 * sys_nice - change the priority of the current process.
3986 * @increment: priority increment
3988 * sys_setpriority is a more generic, but much slower function that
3989 * does similar things.
3991 asmlinkage long sys_nice(int increment)
3993 long nice, retval;
3996 * Setpriority might change our priority at the same moment.
3997 * We don't have to worry. Conceptually one call occurs first
3998 * and we have a single winner.
4000 if (increment < -40)
4001 increment = -40;
4002 if (increment > 40)
4003 increment = 40;
4005 nice = PRIO_TO_NICE(current->static_prio) + increment;
4006 if (nice < -20)
4007 nice = -20;
4008 if (nice > 19)
4009 nice = 19;
4011 if (increment < 0 && !can_nice(current, nice))
4012 return -EPERM;
4014 retval = security_task_setnice(current, nice);
4015 if (retval)
4016 return retval;
4018 set_user_nice(current, nice);
4019 return 0;
4022 #endif
4025 * task_prio - return the priority value of a given task.
4026 * @p: the task in question.
4028 * This is the priority value as seen by users in /proc.
4029 * RT tasks are offset by -200. Normal tasks are centered
4030 * around 0, value goes from -16 to +15.
4032 int task_prio(const struct task_struct *p)
4034 return p->prio - MAX_RT_PRIO;
4038 * task_nice - return the nice value of a given task.
4039 * @p: the task in question.
4041 int task_nice(const struct task_struct *p)
4043 return TASK_NICE(p);
4045 EXPORT_SYMBOL_GPL(task_nice);
4048 * idle_cpu - is a given cpu idle currently?
4049 * @cpu: the processor in question.
4051 int idle_cpu(int cpu)
4053 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4057 * idle_task - return the idle task for a given cpu.
4058 * @cpu: the processor in question.
4060 struct task_struct *idle_task(int cpu)
4062 return cpu_rq(cpu)->idle;
4066 * find_process_by_pid - find a process with a matching PID value.
4067 * @pid: the pid in question.
4069 static inline struct task_struct *find_process_by_pid(pid_t pid)
4071 return pid ? find_task_by_pid(pid) : current;
4074 /* Actually do priority change: must hold rq lock. */
4075 static void
4076 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4078 BUG_ON(p->se.on_rq);
4080 p->policy = policy;
4081 switch (p->policy) {
4082 case SCHED_NORMAL:
4083 case SCHED_BATCH:
4084 case SCHED_IDLE:
4085 p->sched_class = &fair_sched_class;
4086 break;
4087 case SCHED_FIFO:
4088 case SCHED_RR:
4089 p->sched_class = &rt_sched_class;
4090 break;
4093 p->rt_priority = prio;
4094 p->normal_prio = normal_prio(p);
4095 /* we are holding p->pi_lock already */
4096 p->prio = rt_mutex_getprio(p);
4097 set_load_weight(p);
4101 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4102 * @p: the task in question.
4103 * @policy: new policy.
4104 * @param: structure containing the new RT priority.
4106 * NOTE that the task may be already dead.
4108 int sched_setscheduler(struct task_struct *p, int policy,
4109 struct sched_param *param)
4111 int retval, oldprio, oldpolicy = -1, on_rq;
4112 unsigned long flags;
4113 struct rq *rq;
4115 /* may grab non-irq protected spin_locks */
4116 BUG_ON(in_interrupt());
4117 recheck:
4118 /* double check policy once rq lock held */
4119 if (policy < 0)
4120 policy = oldpolicy = p->policy;
4121 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4122 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4123 policy != SCHED_IDLE)
4124 return -EINVAL;
4126 * Valid priorities for SCHED_FIFO and SCHED_RR are
4127 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4128 * SCHED_BATCH and SCHED_IDLE is 0.
4130 if (param->sched_priority < 0 ||
4131 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4132 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4133 return -EINVAL;
4134 if (rt_policy(policy) != (param->sched_priority != 0))
4135 return -EINVAL;
4138 * Allow unprivileged RT tasks to decrease priority:
4140 if (!capable(CAP_SYS_NICE)) {
4141 if (rt_policy(policy)) {
4142 unsigned long rlim_rtprio;
4144 if (!lock_task_sighand(p, &flags))
4145 return -ESRCH;
4146 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4147 unlock_task_sighand(p, &flags);
4149 /* can't set/change the rt policy */
4150 if (policy != p->policy && !rlim_rtprio)
4151 return -EPERM;
4153 /* can't increase priority */
4154 if (param->sched_priority > p->rt_priority &&
4155 param->sched_priority > rlim_rtprio)
4156 return -EPERM;
4159 * Like positive nice levels, dont allow tasks to
4160 * move out of SCHED_IDLE either:
4162 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4163 return -EPERM;
4165 /* can't change other user's priorities */
4166 if ((current->euid != p->euid) &&
4167 (current->euid != p->uid))
4168 return -EPERM;
4171 retval = security_task_setscheduler(p, policy, param);
4172 if (retval)
4173 return retval;
4175 * make sure no PI-waiters arrive (or leave) while we are
4176 * changing the priority of the task:
4178 spin_lock_irqsave(&p->pi_lock, flags);
4180 * To be able to change p->policy safely, the apropriate
4181 * runqueue lock must be held.
4183 rq = __task_rq_lock(p);
4184 /* recheck policy now with rq lock held */
4185 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4186 policy = oldpolicy = -1;
4187 __task_rq_unlock(rq);
4188 spin_unlock_irqrestore(&p->pi_lock, flags);
4189 goto recheck;
4191 update_rq_clock(rq);
4192 on_rq = p->se.on_rq;
4193 if (on_rq)
4194 deactivate_task(rq, p, 0);
4195 oldprio = p->prio;
4196 __setscheduler(rq, p, policy, param->sched_priority);
4197 if (on_rq) {
4198 activate_task(rq, p, 0);
4200 * Reschedule if we are currently running on this runqueue and
4201 * our priority decreased, or if we are not currently running on
4202 * this runqueue and our priority is higher than the current's
4204 if (task_running(rq, p)) {
4205 if (p->prio > oldprio)
4206 resched_task(rq->curr);
4207 } else {
4208 check_preempt_curr(rq, p);
4211 __task_rq_unlock(rq);
4212 spin_unlock_irqrestore(&p->pi_lock, flags);
4214 rt_mutex_adjust_pi(p);
4216 return 0;
4218 EXPORT_SYMBOL_GPL(sched_setscheduler);
4220 static int
4221 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4223 struct sched_param lparam;
4224 struct task_struct *p;
4225 int retval;
4227 if (!param || pid < 0)
4228 return -EINVAL;
4229 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4230 return -EFAULT;
4232 rcu_read_lock();
4233 retval = -ESRCH;
4234 p = find_process_by_pid(pid);
4235 if (p != NULL)
4236 retval = sched_setscheduler(p, policy, &lparam);
4237 rcu_read_unlock();
4239 return retval;
4243 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4244 * @pid: the pid in question.
4245 * @policy: new policy.
4246 * @param: structure containing the new RT priority.
4248 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4249 struct sched_param __user *param)
4251 /* negative values for policy are not valid */
4252 if (policy < 0)
4253 return -EINVAL;
4255 return do_sched_setscheduler(pid, policy, param);
4259 * sys_sched_setparam - set/change the RT priority of a thread
4260 * @pid: the pid in question.
4261 * @param: structure containing the new RT priority.
4263 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4265 return do_sched_setscheduler(pid, -1, param);
4269 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4270 * @pid: the pid in question.
4272 asmlinkage long sys_sched_getscheduler(pid_t pid)
4274 struct task_struct *p;
4275 int retval = -EINVAL;
4277 if (pid < 0)
4278 goto out_nounlock;
4280 retval = -ESRCH;
4281 read_lock(&tasklist_lock);
4282 p = find_process_by_pid(pid);
4283 if (p) {
4284 retval = security_task_getscheduler(p);
4285 if (!retval)
4286 retval = p->policy;
4288 read_unlock(&tasklist_lock);
4290 out_nounlock:
4291 return retval;
4295 * sys_sched_getscheduler - get the RT priority of a thread
4296 * @pid: the pid in question.
4297 * @param: structure containing the RT priority.
4299 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4301 struct sched_param lp;
4302 struct task_struct *p;
4303 int retval = -EINVAL;
4305 if (!param || pid < 0)
4306 goto out_nounlock;
4308 read_lock(&tasklist_lock);
4309 p = find_process_by_pid(pid);
4310 retval = -ESRCH;
4311 if (!p)
4312 goto out_unlock;
4314 retval = security_task_getscheduler(p);
4315 if (retval)
4316 goto out_unlock;
4318 lp.sched_priority = p->rt_priority;
4319 read_unlock(&tasklist_lock);
4322 * This one might sleep, we cannot do it with a spinlock held ...
4324 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4326 out_nounlock:
4327 return retval;
4329 out_unlock:
4330 read_unlock(&tasklist_lock);
4331 return retval;
4334 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4336 cpumask_t cpus_allowed;
4337 struct task_struct *p;
4338 int retval;
4340 mutex_lock(&sched_hotcpu_mutex);
4341 read_lock(&tasklist_lock);
4343 p = find_process_by_pid(pid);
4344 if (!p) {
4345 read_unlock(&tasklist_lock);
4346 mutex_unlock(&sched_hotcpu_mutex);
4347 return -ESRCH;
4351 * It is not safe to call set_cpus_allowed with the
4352 * tasklist_lock held. We will bump the task_struct's
4353 * usage count and then drop tasklist_lock.
4355 get_task_struct(p);
4356 read_unlock(&tasklist_lock);
4358 retval = -EPERM;
4359 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4360 !capable(CAP_SYS_NICE))
4361 goto out_unlock;
4363 retval = security_task_setscheduler(p, 0, NULL);
4364 if (retval)
4365 goto out_unlock;
4367 cpus_allowed = cpuset_cpus_allowed(p);
4368 cpus_and(new_mask, new_mask, cpus_allowed);
4369 retval = set_cpus_allowed(p, new_mask);
4371 out_unlock:
4372 put_task_struct(p);
4373 mutex_unlock(&sched_hotcpu_mutex);
4374 return retval;
4377 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4378 cpumask_t *new_mask)
4380 if (len < sizeof(cpumask_t)) {
4381 memset(new_mask, 0, sizeof(cpumask_t));
4382 } else if (len > sizeof(cpumask_t)) {
4383 len = sizeof(cpumask_t);
4385 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4389 * sys_sched_setaffinity - set the cpu affinity of a process
4390 * @pid: pid of the process
4391 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4392 * @user_mask_ptr: user-space pointer to the new cpu mask
4394 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4395 unsigned long __user *user_mask_ptr)
4397 cpumask_t new_mask;
4398 int retval;
4400 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4401 if (retval)
4402 return retval;
4404 return sched_setaffinity(pid, new_mask);
4408 * Represents all cpu's present in the system
4409 * In systems capable of hotplug, this map could dynamically grow
4410 * as new cpu's are detected in the system via any platform specific
4411 * method, such as ACPI for e.g.
4414 cpumask_t cpu_present_map __read_mostly;
4415 EXPORT_SYMBOL(cpu_present_map);
4417 #ifndef CONFIG_SMP
4418 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4419 EXPORT_SYMBOL(cpu_online_map);
4421 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4422 EXPORT_SYMBOL(cpu_possible_map);
4423 #endif
4425 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4427 struct task_struct *p;
4428 int retval;
4430 mutex_lock(&sched_hotcpu_mutex);
4431 read_lock(&tasklist_lock);
4433 retval = -ESRCH;
4434 p = find_process_by_pid(pid);
4435 if (!p)
4436 goto out_unlock;
4438 retval = security_task_getscheduler(p);
4439 if (retval)
4440 goto out_unlock;
4442 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4444 out_unlock:
4445 read_unlock(&tasklist_lock);
4446 mutex_unlock(&sched_hotcpu_mutex);
4448 return retval;
4452 * sys_sched_getaffinity - get the cpu affinity of a process
4453 * @pid: pid of the process
4454 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4455 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4457 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4458 unsigned long __user *user_mask_ptr)
4460 int ret;
4461 cpumask_t mask;
4463 if (len < sizeof(cpumask_t))
4464 return -EINVAL;
4466 ret = sched_getaffinity(pid, &mask);
4467 if (ret < 0)
4468 return ret;
4470 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4471 return -EFAULT;
4473 return sizeof(cpumask_t);
4477 * sys_sched_yield - yield the current processor to other threads.
4479 * This function yields the current CPU to other tasks. If there are no
4480 * other threads running on this CPU then this function will return.
4482 asmlinkage long sys_sched_yield(void)
4484 struct rq *rq = this_rq_lock();
4486 schedstat_inc(rq, yld_cnt);
4487 current->sched_class->yield_task(rq, current);
4490 * Since we are going to call schedule() anyway, there's
4491 * no need to preempt or enable interrupts:
4493 __release(rq->lock);
4494 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4495 _raw_spin_unlock(&rq->lock);
4496 preempt_enable_no_resched();
4498 schedule();
4500 return 0;
4503 static void __cond_resched(void)
4505 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4506 __might_sleep(__FILE__, __LINE__);
4507 #endif
4509 * The BKS might be reacquired before we have dropped
4510 * PREEMPT_ACTIVE, which could trigger a second
4511 * cond_resched() call.
4513 do {
4514 add_preempt_count(PREEMPT_ACTIVE);
4515 schedule();
4516 sub_preempt_count(PREEMPT_ACTIVE);
4517 } while (need_resched());
4520 int __sched cond_resched(void)
4522 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
4523 system_state == SYSTEM_RUNNING) {
4524 __cond_resched();
4525 return 1;
4527 return 0;
4529 EXPORT_SYMBOL(cond_resched);
4532 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4533 * call schedule, and on return reacquire the lock.
4535 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4536 * operations here to prevent schedule() from being called twice (once via
4537 * spin_unlock(), once by hand).
4539 int cond_resched_lock(spinlock_t *lock)
4541 int ret = 0;
4543 if (need_lockbreak(lock)) {
4544 spin_unlock(lock);
4545 cpu_relax();
4546 ret = 1;
4547 spin_lock(lock);
4549 if (need_resched() && system_state == SYSTEM_RUNNING) {
4550 spin_release(&lock->dep_map, 1, _THIS_IP_);
4551 _raw_spin_unlock(lock);
4552 preempt_enable_no_resched();
4553 __cond_resched();
4554 ret = 1;
4555 spin_lock(lock);
4557 return ret;
4559 EXPORT_SYMBOL(cond_resched_lock);
4561 int __sched cond_resched_softirq(void)
4563 BUG_ON(!in_softirq());
4565 if (need_resched() && system_state == SYSTEM_RUNNING) {
4566 local_bh_enable();
4567 __cond_resched();
4568 local_bh_disable();
4569 return 1;
4571 return 0;
4573 EXPORT_SYMBOL(cond_resched_softirq);
4576 * yield - yield the current processor to other threads.
4578 * This is a shortcut for kernel-space yielding - it marks the
4579 * thread runnable and calls sys_sched_yield().
4581 void __sched yield(void)
4583 set_current_state(TASK_RUNNING);
4584 sys_sched_yield();
4586 EXPORT_SYMBOL(yield);
4589 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4590 * that process accounting knows that this is a task in IO wait state.
4592 * But don't do that if it is a deliberate, throttling IO wait (this task
4593 * has set its backing_dev_info: the queue against which it should throttle)
4595 void __sched io_schedule(void)
4597 struct rq *rq = &__raw_get_cpu_var(runqueues);
4599 delayacct_blkio_start();
4600 atomic_inc(&rq->nr_iowait);
4601 schedule();
4602 atomic_dec(&rq->nr_iowait);
4603 delayacct_blkio_end();
4605 EXPORT_SYMBOL(io_schedule);
4607 long __sched io_schedule_timeout(long timeout)
4609 struct rq *rq = &__raw_get_cpu_var(runqueues);
4610 long ret;
4612 delayacct_blkio_start();
4613 atomic_inc(&rq->nr_iowait);
4614 ret = schedule_timeout(timeout);
4615 atomic_dec(&rq->nr_iowait);
4616 delayacct_blkio_end();
4617 return ret;
4621 * sys_sched_get_priority_max - return maximum RT priority.
4622 * @policy: scheduling class.
4624 * this syscall returns the maximum rt_priority that can be used
4625 * by a given scheduling class.
4627 asmlinkage long sys_sched_get_priority_max(int policy)
4629 int ret = -EINVAL;
4631 switch (policy) {
4632 case SCHED_FIFO:
4633 case SCHED_RR:
4634 ret = MAX_USER_RT_PRIO-1;
4635 break;
4636 case SCHED_NORMAL:
4637 case SCHED_BATCH:
4638 case SCHED_IDLE:
4639 ret = 0;
4640 break;
4642 return ret;
4646 * sys_sched_get_priority_min - return minimum RT priority.
4647 * @policy: scheduling class.
4649 * this syscall returns the minimum rt_priority that can be used
4650 * by a given scheduling class.
4652 asmlinkage long sys_sched_get_priority_min(int policy)
4654 int ret = -EINVAL;
4656 switch (policy) {
4657 case SCHED_FIFO:
4658 case SCHED_RR:
4659 ret = 1;
4660 break;
4661 case SCHED_NORMAL:
4662 case SCHED_BATCH:
4663 case SCHED_IDLE:
4664 ret = 0;
4666 return ret;
4670 * sys_sched_rr_get_interval - return the default timeslice of a process.
4671 * @pid: pid of the process.
4672 * @interval: userspace pointer to the timeslice value.
4674 * this syscall writes the default timeslice value of a given process
4675 * into the user-space timespec buffer. A value of '0' means infinity.
4677 asmlinkage
4678 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4680 struct task_struct *p;
4681 int retval = -EINVAL;
4682 struct timespec t;
4684 if (pid < 0)
4685 goto out_nounlock;
4687 retval = -ESRCH;
4688 read_lock(&tasklist_lock);
4689 p = find_process_by_pid(pid);
4690 if (!p)
4691 goto out_unlock;
4693 retval = security_task_getscheduler(p);
4694 if (retval)
4695 goto out_unlock;
4697 jiffies_to_timespec(p->policy == SCHED_FIFO ?
4698 0 : static_prio_timeslice(p->static_prio), &t);
4699 read_unlock(&tasklist_lock);
4700 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4701 out_nounlock:
4702 return retval;
4703 out_unlock:
4704 read_unlock(&tasklist_lock);
4705 return retval;
4708 static const char stat_nam[] = "RSDTtZX";
4710 static void show_task(struct task_struct *p)
4712 unsigned long free = 0;
4713 unsigned state;
4715 state = p->state ? __ffs(p->state) + 1 : 0;
4716 printk("%-13.13s %c", p->comm,
4717 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4718 #if BITS_PER_LONG == 32
4719 if (state == TASK_RUNNING)
4720 printk(" running ");
4721 else
4722 printk(" %08lx ", thread_saved_pc(p));
4723 #else
4724 if (state == TASK_RUNNING)
4725 printk(" running task ");
4726 else
4727 printk(" %016lx ", thread_saved_pc(p));
4728 #endif
4729 #ifdef CONFIG_DEBUG_STACK_USAGE
4731 unsigned long *n = end_of_stack(p);
4732 while (!*n)
4733 n++;
4734 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4736 #endif
4737 printk("%5lu %5d %6d\n", free, p->pid, p->parent->pid);
4739 if (state != TASK_RUNNING)
4740 show_stack(p, NULL);
4743 void show_state_filter(unsigned long state_filter)
4745 struct task_struct *g, *p;
4747 #if BITS_PER_LONG == 32
4748 printk(KERN_INFO
4749 " task PC stack pid father\n");
4750 #else
4751 printk(KERN_INFO
4752 " task PC stack pid father\n");
4753 #endif
4754 read_lock(&tasklist_lock);
4755 do_each_thread(g, p) {
4757 * reset the NMI-timeout, listing all files on a slow
4758 * console might take alot of time:
4760 touch_nmi_watchdog();
4761 if (!state_filter || (p->state & state_filter))
4762 show_task(p);
4763 } while_each_thread(g, p);
4765 touch_all_softlockup_watchdogs();
4767 #ifdef CONFIG_SCHED_DEBUG
4768 sysrq_sched_debug_show();
4769 #endif
4770 read_unlock(&tasklist_lock);
4772 * Only show locks if all tasks are dumped:
4774 if (state_filter == -1)
4775 debug_show_all_locks();
4778 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4780 idle->sched_class = &idle_sched_class;
4784 * init_idle - set up an idle thread for a given CPU
4785 * @idle: task in question
4786 * @cpu: cpu the idle task belongs to
4788 * NOTE: this function does not set the idle thread's NEED_RESCHED
4789 * flag, to make booting more robust.
4791 void __cpuinit init_idle(struct task_struct *idle, int cpu)
4793 struct rq *rq = cpu_rq(cpu);
4794 unsigned long flags;
4796 __sched_fork(idle);
4797 idle->se.exec_start = sched_clock();
4799 idle->prio = idle->normal_prio = MAX_PRIO;
4800 idle->cpus_allowed = cpumask_of_cpu(cpu);
4801 __set_task_cpu(idle, cpu);
4803 spin_lock_irqsave(&rq->lock, flags);
4804 rq->curr = rq->idle = idle;
4805 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4806 idle->oncpu = 1;
4807 #endif
4808 spin_unlock_irqrestore(&rq->lock, flags);
4810 /* Set the preempt count _outside_ the spinlocks! */
4811 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4812 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4813 #else
4814 task_thread_info(idle)->preempt_count = 0;
4815 #endif
4817 * The idle tasks have their own, simple scheduling class:
4819 idle->sched_class = &idle_sched_class;
4823 * In a system that switches off the HZ timer nohz_cpu_mask
4824 * indicates which cpus entered this state. This is used
4825 * in the rcu update to wait only for active cpus. For system
4826 * which do not switch off the HZ timer nohz_cpu_mask should
4827 * always be CPU_MASK_NONE.
4829 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4831 #ifdef CONFIG_SMP
4833 * This is how migration works:
4835 * 1) we queue a struct migration_req structure in the source CPU's
4836 * runqueue and wake up that CPU's migration thread.
4837 * 2) we down() the locked semaphore => thread blocks.
4838 * 3) migration thread wakes up (implicitly it forces the migrated
4839 * thread off the CPU)
4840 * 4) it gets the migration request and checks whether the migrated
4841 * task is still in the wrong runqueue.
4842 * 5) if it's in the wrong runqueue then the migration thread removes
4843 * it and puts it into the right queue.
4844 * 6) migration thread up()s the semaphore.
4845 * 7) we wake up and the migration is done.
4849 * Change a given task's CPU affinity. Migrate the thread to a
4850 * proper CPU and schedule it away if the CPU it's executing on
4851 * is removed from the allowed bitmask.
4853 * NOTE: the caller must have a valid reference to the task, the
4854 * task must not exit() & deallocate itself prematurely. The
4855 * call is not atomic; no spinlocks may be held.
4857 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
4859 struct migration_req req;
4860 unsigned long flags;
4861 struct rq *rq;
4862 int ret = 0;
4864 rq = task_rq_lock(p, &flags);
4865 if (!cpus_intersects(new_mask, cpu_online_map)) {
4866 ret = -EINVAL;
4867 goto out;
4870 p->cpus_allowed = new_mask;
4871 /* Can the task run on the task's current CPU? If so, we're done */
4872 if (cpu_isset(task_cpu(p), new_mask))
4873 goto out;
4875 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4876 /* Need help from migration thread: drop lock and wait. */
4877 task_rq_unlock(rq, &flags);
4878 wake_up_process(rq->migration_thread);
4879 wait_for_completion(&req.done);
4880 tlb_migrate_finish(p->mm);
4881 return 0;
4883 out:
4884 task_rq_unlock(rq, &flags);
4886 return ret;
4888 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4891 * Move (not current) task off this cpu, onto dest cpu. We're doing
4892 * this because either it can't run here any more (set_cpus_allowed()
4893 * away from this CPU, or CPU going down), or because we're
4894 * attempting to rebalance this task on exec (sched_exec).
4896 * So we race with normal scheduler movements, but that's OK, as long
4897 * as the task is no longer on this CPU.
4899 * Returns non-zero if task was successfully migrated.
4901 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4903 struct rq *rq_dest, *rq_src;
4904 int ret = 0, on_rq;
4906 if (unlikely(cpu_is_offline(dest_cpu)))
4907 return ret;
4909 rq_src = cpu_rq(src_cpu);
4910 rq_dest = cpu_rq(dest_cpu);
4912 double_rq_lock(rq_src, rq_dest);
4913 /* Already moved. */
4914 if (task_cpu(p) != src_cpu)
4915 goto out;
4916 /* Affinity changed (again). */
4917 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4918 goto out;
4920 on_rq = p->se.on_rq;
4921 if (on_rq)
4922 deactivate_task(rq_src, p, 0);
4924 set_task_cpu(p, dest_cpu);
4925 if (on_rq) {
4926 activate_task(rq_dest, p, 0);
4927 check_preempt_curr(rq_dest, p);
4929 ret = 1;
4930 out:
4931 double_rq_unlock(rq_src, rq_dest);
4932 return ret;
4936 * migration_thread - this is a highprio system thread that performs
4937 * thread migration by bumping thread off CPU then 'pushing' onto
4938 * another runqueue.
4940 static int migration_thread(void *data)
4942 int cpu = (long)data;
4943 struct rq *rq;
4945 rq = cpu_rq(cpu);
4946 BUG_ON(rq->migration_thread != current);
4948 set_current_state(TASK_INTERRUPTIBLE);
4949 while (!kthread_should_stop()) {
4950 struct migration_req *req;
4951 struct list_head *head;
4953 spin_lock_irq(&rq->lock);
4955 if (cpu_is_offline(cpu)) {
4956 spin_unlock_irq(&rq->lock);
4957 goto wait_to_die;
4960 if (rq->active_balance) {
4961 active_load_balance(rq, cpu);
4962 rq->active_balance = 0;
4965 head = &rq->migration_queue;
4967 if (list_empty(head)) {
4968 spin_unlock_irq(&rq->lock);
4969 schedule();
4970 set_current_state(TASK_INTERRUPTIBLE);
4971 continue;
4973 req = list_entry(head->next, struct migration_req, list);
4974 list_del_init(head->next);
4976 spin_unlock(&rq->lock);
4977 __migrate_task(req->task, cpu, req->dest_cpu);
4978 local_irq_enable();
4980 complete(&req->done);
4982 __set_current_state(TASK_RUNNING);
4983 return 0;
4985 wait_to_die:
4986 /* Wait for kthread_stop */
4987 set_current_state(TASK_INTERRUPTIBLE);
4988 while (!kthread_should_stop()) {
4989 schedule();
4990 set_current_state(TASK_INTERRUPTIBLE);
4992 __set_current_state(TASK_RUNNING);
4993 return 0;
4996 #ifdef CONFIG_HOTPLUG_CPU
4998 * Figure out where task on dead CPU should go, use force if neccessary.
4999 * NOTE: interrupts should be disabled by the caller
5001 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5003 unsigned long flags;
5004 cpumask_t mask;
5005 struct rq *rq;
5006 int dest_cpu;
5008 restart:
5009 /* On same node? */
5010 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5011 cpus_and(mask, mask, p->cpus_allowed);
5012 dest_cpu = any_online_cpu(mask);
5014 /* On any allowed CPU? */
5015 if (dest_cpu == NR_CPUS)
5016 dest_cpu = any_online_cpu(p->cpus_allowed);
5018 /* No more Mr. Nice Guy. */
5019 if (dest_cpu == NR_CPUS) {
5020 rq = task_rq_lock(p, &flags);
5021 cpus_setall(p->cpus_allowed);
5022 dest_cpu = any_online_cpu(p->cpus_allowed);
5023 task_rq_unlock(rq, &flags);
5026 * Don't tell them about moving exiting tasks or
5027 * kernel threads (both mm NULL), since they never
5028 * leave kernel.
5030 if (p->mm && printk_ratelimit())
5031 printk(KERN_INFO "process %d (%s) no "
5032 "longer affine to cpu%d\n",
5033 p->pid, p->comm, dead_cpu);
5035 if (!__migrate_task(p, dead_cpu, dest_cpu))
5036 goto restart;
5040 * While a dead CPU has no uninterruptible tasks queued at this point,
5041 * it might still have a nonzero ->nr_uninterruptible counter, because
5042 * for performance reasons the counter is not stricly tracking tasks to
5043 * their home CPUs. So we just add the counter to another CPU's counter,
5044 * to keep the global sum constant after CPU-down:
5046 static void migrate_nr_uninterruptible(struct rq *rq_src)
5048 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5049 unsigned long flags;
5051 local_irq_save(flags);
5052 double_rq_lock(rq_src, rq_dest);
5053 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5054 rq_src->nr_uninterruptible = 0;
5055 double_rq_unlock(rq_src, rq_dest);
5056 local_irq_restore(flags);
5059 /* Run through task list and migrate tasks from the dead cpu. */
5060 static void migrate_live_tasks(int src_cpu)
5062 struct task_struct *p, *t;
5064 write_lock_irq(&tasklist_lock);
5066 do_each_thread(t, p) {
5067 if (p == current)
5068 continue;
5070 if (task_cpu(p) == src_cpu)
5071 move_task_off_dead_cpu(src_cpu, p);
5072 } while_each_thread(t, p);
5074 write_unlock_irq(&tasklist_lock);
5078 * Schedules idle task to be the next runnable task on current CPU.
5079 * It does so by boosting its priority to highest possible and adding it to
5080 * the _front_ of the runqueue. Used by CPU offline code.
5082 void sched_idle_next(void)
5084 int this_cpu = smp_processor_id();
5085 struct rq *rq = cpu_rq(this_cpu);
5086 struct task_struct *p = rq->idle;
5087 unsigned long flags;
5089 /* cpu has to be offline */
5090 BUG_ON(cpu_online(this_cpu));
5093 * Strictly not necessary since rest of the CPUs are stopped by now
5094 * and interrupts disabled on the current cpu.
5096 spin_lock_irqsave(&rq->lock, flags);
5098 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5100 /* Add idle task to the _front_ of its priority queue: */
5101 activate_idle_task(p, rq);
5103 spin_unlock_irqrestore(&rq->lock, flags);
5107 * Ensures that the idle task is using init_mm right before its cpu goes
5108 * offline.
5110 void idle_task_exit(void)
5112 struct mm_struct *mm = current->active_mm;
5114 BUG_ON(cpu_online(smp_processor_id()));
5116 if (mm != &init_mm)
5117 switch_mm(mm, &init_mm, current);
5118 mmdrop(mm);
5121 /* called under rq->lock with disabled interrupts */
5122 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5124 struct rq *rq = cpu_rq(dead_cpu);
5126 /* Must be exiting, otherwise would be on tasklist. */
5127 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
5129 /* Cannot have done final schedule yet: would have vanished. */
5130 BUG_ON(p->state == TASK_DEAD);
5132 get_task_struct(p);
5135 * Drop lock around migration; if someone else moves it,
5136 * that's OK. No task can be added to this CPU, so iteration is
5137 * fine.
5138 * NOTE: interrupts should be left disabled --dev@
5140 spin_unlock(&rq->lock);
5141 move_task_off_dead_cpu(dead_cpu, p);
5142 spin_lock(&rq->lock);
5144 put_task_struct(p);
5147 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5148 static void migrate_dead_tasks(unsigned int dead_cpu)
5150 struct rq *rq = cpu_rq(dead_cpu);
5151 struct task_struct *next;
5153 for ( ; ; ) {
5154 if (!rq->nr_running)
5155 break;
5156 update_rq_clock(rq);
5157 next = pick_next_task(rq, rq->curr);
5158 if (!next)
5159 break;
5160 migrate_dead(dead_cpu, next);
5164 #endif /* CONFIG_HOTPLUG_CPU */
5166 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5168 static struct ctl_table sd_ctl_dir[] = {
5170 .procname = "sched_domain",
5171 .mode = 0555,
5173 {0,},
5176 static struct ctl_table sd_ctl_root[] = {
5178 .ctl_name = CTL_KERN,
5179 .procname = "kernel",
5180 .mode = 0555,
5181 .child = sd_ctl_dir,
5183 {0,},
5186 static struct ctl_table *sd_alloc_ctl_entry(int n)
5188 struct ctl_table *entry =
5189 kmalloc(n * sizeof(struct ctl_table), GFP_KERNEL);
5191 BUG_ON(!entry);
5192 memset(entry, 0, n * sizeof(struct ctl_table));
5194 return entry;
5197 static void
5198 set_table_entry(struct ctl_table *entry,
5199 const char *procname, void *data, int maxlen,
5200 mode_t mode, proc_handler *proc_handler)
5202 entry->procname = procname;
5203 entry->data = data;
5204 entry->maxlen = maxlen;
5205 entry->mode = mode;
5206 entry->proc_handler = proc_handler;
5209 static struct ctl_table *
5210 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5212 struct ctl_table *table = sd_alloc_ctl_entry(14);
5214 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5215 sizeof(long), 0644, proc_doulongvec_minmax);
5216 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5217 sizeof(long), 0644, proc_doulongvec_minmax);
5218 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5219 sizeof(int), 0644, proc_dointvec_minmax);
5220 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5221 sizeof(int), 0644, proc_dointvec_minmax);
5222 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5223 sizeof(int), 0644, proc_dointvec_minmax);
5224 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5225 sizeof(int), 0644, proc_dointvec_minmax);
5226 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5227 sizeof(int), 0644, proc_dointvec_minmax);
5228 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5229 sizeof(int), 0644, proc_dointvec_minmax);
5230 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5231 sizeof(int), 0644, proc_dointvec_minmax);
5232 set_table_entry(&table[10], "cache_nice_tries",
5233 &sd->cache_nice_tries,
5234 sizeof(int), 0644, proc_dointvec_minmax);
5235 set_table_entry(&table[12], "flags", &sd->flags,
5236 sizeof(int), 0644, proc_dointvec_minmax);
5238 return table;
5241 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5243 struct ctl_table *entry, *table;
5244 struct sched_domain *sd;
5245 int domain_num = 0, i;
5246 char buf[32];
5248 for_each_domain(cpu, sd)
5249 domain_num++;
5250 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5252 i = 0;
5253 for_each_domain(cpu, sd) {
5254 snprintf(buf, 32, "domain%d", i);
5255 entry->procname = kstrdup(buf, GFP_KERNEL);
5256 entry->mode = 0555;
5257 entry->child = sd_alloc_ctl_domain_table(sd);
5258 entry++;
5259 i++;
5261 return table;
5264 static struct ctl_table_header *sd_sysctl_header;
5265 static void init_sched_domain_sysctl(void)
5267 int i, cpu_num = num_online_cpus();
5268 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5269 char buf[32];
5271 sd_ctl_dir[0].child = entry;
5273 for (i = 0; i < cpu_num; i++, entry++) {
5274 snprintf(buf, 32, "cpu%d", i);
5275 entry->procname = kstrdup(buf, GFP_KERNEL);
5276 entry->mode = 0555;
5277 entry->child = sd_alloc_ctl_cpu_table(i);
5279 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5281 #else
5282 static void init_sched_domain_sysctl(void)
5285 #endif
5288 * migration_call - callback that gets triggered when a CPU is added.
5289 * Here we can start up the necessary migration thread for the new CPU.
5291 static int __cpuinit
5292 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5294 struct task_struct *p;
5295 int cpu = (long)hcpu;
5296 unsigned long flags;
5297 struct rq *rq;
5299 switch (action) {
5300 case CPU_LOCK_ACQUIRE:
5301 mutex_lock(&sched_hotcpu_mutex);
5302 break;
5304 case CPU_UP_PREPARE:
5305 case CPU_UP_PREPARE_FROZEN:
5306 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
5307 if (IS_ERR(p))
5308 return NOTIFY_BAD;
5309 kthread_bind(p, cpu);
5310 /* Must be high prio: stop_machine expects to yield to it. */
5311 rq = task_rq_lock(p, &flags);
5312 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5313 task_rq_unlock(rq, &flags);
5314 cpu_rq(cpu)->migration_thread = p;
5315 break;
5317 case CPU_ONLINE:
5318 case CPU_ONLINE_FROZEN:
5319 /* Strictly unneccessary, as first user will wake it. */
5320 wake_up_process(cpu_rq(cpu)->migration_thread);
5321 break;
5323 #ifdef CONFIG_HOTPLUG_CPU
5324 case CPU_UP_CANCELED:
5325 case CPU_UP_CANCELED_FROZEN:
5326 if (!cpu_rq(cpu)->migration_thread)
5327 break;
5328 /* Unbind it from offline cpu so it can run. Fall thru. */
5329 kthread_bind(cpu_rq(cpu)->migration_thread,
5330 any_online_cpu(cpu_online_map));
5331 kthread_stop(cpu_rq(cpu)->migration_thread);
5332 cpu_rq(cpu)->migration_thread = NULL;
5333 break;
5335 case CPU_DEAD:
5336 case CPU_DEAD_FROZEN:
5337 migrate_live_tasks(cpu);
5338 rq = cpu_rq(cpu);
5339 kthread_stop(rq->migration_thread);
5340 rq->migration_thread = NULL;
5341 /* Idle task back to normal (off runqueue, low prio) */
5342 rq = task_rq_lock(rq->idle, &flags);
5343 update_rq_clock(rq);
5344 deactivate_task(rq, rq->idle, 0);
5345 rq->idle->static_prio = MAX_PRIO;
5346 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5347 rq->idle->sched_class = &idle_sched_class;
5348 migrate_dead_tasks(cpu);
5349 task_rq_unlock(rq, &flags);
5350 migrate_nr_uninterruptible(rq);
5351 BUG_ON(rq->nr_running != 0);
5353 /* No need to migrate the tasks: it was best-effort if
5354 * they didn't take sched_hotcpu_mutex. Just wake up
5355 * the requestors. */
5356 spin_lock_irq(&rq->lock);
5357 while (!list_empty(&rq->migration_queue)) {
5358 struct migration_req *req;
5360 req = list_entry(rq->migration_queue.next,
5361 struct migration_req, list);
5362 list_del_init(&req->list);
5363 complete(&req->done);
5365 spin_unlock_irq(&rq->lock);
5366 break;
5367 #endif
5368 case CPU_LOCK_RELEASE:
5369 mutex_unlock(&sched_hotcpu_mutex);
5370 break;
5372 return NOTIFY_OK;
5375 /* Register at highest priority so that task migration (migrate_all_tasks)
5376 * happens before everything else.
5378 static struct notifier_block __cpuinitdata migration_notifier = {
5379 .notifier_call = migration_call,
5380 .priority = 10
5383 int __init migration_init(void)
5385 void *cpu = (void *)(long)smp_processor_id();
5386 int err;
5388 /* Start one for the boot CPU: */
5389 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5390 BUG_ON(err == NOTIFY_BAD);
5391 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5392 register_cpu_notifier(&migration_notifier);
5394 return 0;
5396 #endif
5398 #ifdef CONFIG_SMP
5400 /* Number of possible processor ids */
5401 int nr_cpu_ids __read_mostly = NR_CPUS;
5402 EXPORT_SYMBOL(nr_cpu_ids);
5404 #undef SCHED_DOMAIN_DEBUG
5405 #ifdef SCHED_DOMAIN_DEBUG
5406 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5408 int level = 0;
5410 if (!sd) {
5411 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5412 return;
5415 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5417 do {
5418 int i;
5419 char str[NR_CPUS];
5420 struct sched_group *group = sd->groups;
5421 cpumask_t groupmask;
5423 cpumask_scnprintf(str, NR_CPUS, sd->span);
5424 cpus_clear(groupmask);
5426 printk(KERN_DEBUG);
5427 for (i = 0; i < level + 1; i++)
5428 printk(" ");
5429 printk("domain %d: ", level);
5431 if (!(sd->flags & SD_LOAD_BALANCE)) {
5432 printk("does not load-balance\n");
5433 if (sd->parent)
5434 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5435 " has parent");
5436 break;
5439 printk("span %s\n", str);
5441 if (!cpu_isset(cpu, sd->span))
5442 printk(KERN_ERR "ERROR: domain->span does not contain "
5443 "CPU%d\n", cpu);
5444 if (!cpu_isset(cpu, group->cpumask))
5445 printk(KERN_ERR "ERROR: domain->groups does not contain"
5446 " CPU%d\n", cpu);
5448 printk(KERN_DEBUG);
5449 for (i = 0; i < level + 2; i++)
5450 printk(" ");
5451 printk("groups:");
5452 do {
5453 if (!group) {
5454 printk("\n");
5455 printk(KERN_ERR "ERROR: group is NULL\n");
5456 break;
5459 if (!group->__cpu_power) {
5460 printk("\n");
5461 printk(KERN_ERR "ERROR: domain->cpu_power not "
5462 "set\n");
5465 if (!cpus_weight(group->cpumask)) {
5466 printk("\n");
5467 printk(KERN_ERR "ERROR: empty group\n");
5470 if (cpus_intersects(groupmask, group->cpumask)) {
5471 printk("\n");
5472 printk(KERN_ERR "ERROR: repeated CPUs\n");
5475 cpus_or(groupmask, groupmask, group->cpumask);
5477 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5478 printk(" %s", str);
5480 group = group->next;
5481 } while (group != sd->groups);
5482 printk("\n");
5484 if (!cpus_equal(sd->span, groupmask))
5485 printk(KERN_ERR "ERROR: groups don't span "
5486 "domain->span\n");
5488 level++;
5489 sd = sd->parent;
5490 if (!sd)
5491 continue;
5493 if (!cpus_subset(groupmask, sd->span))
5494 printk(KERN_ERR "ERROR: parent span is not a superset "
5495 "of domain->span\n");
5497 } while (sd);
5499 #else
5500 # define sched_domain_debug(sd, cpu) do { } while (0)
5501 #endif
5503 static int sd_degenerate(struct sched_domain *sd)
5505 if (cpus_weight(sd->span) == 1)
5506 return 1;
5508 /* Following flags need at least 2 groups */
5509 if (sd->flags & (SD_LOAD_BALANCE |
5510 SD_BALANCE_NEWIDLE |
5511 SD_BALANCE_FORK |
5512 SD_BALANCE_EXEC |
5513 SD_SHARE_CPUPOWER |
5514 SD_SHARE_PKG_RESOURCES)) {
5515 if (sd->groups != sd->groups->next)
5516 return 0;
5519 /* Following flags don't use groups */
5520 if (sd->flags & (SD_WAKE_IDLE |
5521 SD_WAKE_AFFINE |
5522 SD_WAKE_BALANCE))
5523 return 0;
5525 return 1;
5528 static int
5529 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5531 unsigned long cflags = sd->flags, pflags = parent->flags;
5533 if (sd_degenerate(parent))
5534 return 1;
5536 if (!cpus_equal(sd->span, parent->span))
5537 return 0;
5539 /* Does parent contain flags not in child? */
5540 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5541 if (cflags & SD_WAKE_AFFINE)
5542 pflags &= ~SD_WAKE_BALANCE;
5543 /* Flags needing groups don't count if only 1 group in parent */
5544 if (parent->groups == parent->groups->next) {
5545 pflags &= ~(SD_LOAD_BALANCE |
5546 SD_BALANCE_NEWIDLE |
5547 SD_BALANCE_FORK |
5548 SD_BALANCE_EXEC |
5549 SD_SHARE_CPUPOWER |
5550 SD_SHARE_PKG_RESOURCES);
5552 if (~cflags & pflags)
5553 return 0;
5555 return 1;
5559 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5560 * hold the hotplug lock.
5562 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5564 struct rq *rq = cpu_rq(cpu);
5565 struct sched_domain *tmp;
5567 /* Remove the sched domains which do not contribute to scheduling. */
5568 for (tmp = sd; tmp; tmp = tmp->parent) {
5569 struct sched_domain *parent = tmp->parent;
5570 if (!parent)
5571 break;
5572 if (sd_parent_degenerate(tmp, parent)) {
5573 tmp->parent = parent->parent;
5574 if (parent->parent)
5575 parent->parent->child = tmp;
5579 if (sd && sd_degenerate(sd)) {
5580 sd = sd->parent;
5581 if (sd)
5582 sd->child = NULL;
5585 sched_domain_debug(sd, cpu);
5587 rcu_assign_pointer(rq->sd, sd);
5590 /* cpus with isolated domains */
5591 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
5593 /* Setup the mask of cpus configured for isolated domains */
5594 static int __init isolated_cpu_setup(char *str)
5596 int ints[NR_CPUS], i;
5598 str = get_options(str, ARRAY_SIZE(ints), ints);
5599 cpus_clear(cpu_isolated_map);
5600 for (i = 1; i <= ints[0]; i++)
5601 if (ints[i] < NR_CPUS)
5602 cpu_set(ints[i], cpu_isolated_map);
5603 return 1;
5606 __setup ("isolcpus=", isolated_cpu_setup);
5609 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
5610 * to a function which identifies what group(along with sched group) a CPU
5611 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
5612 * (due to the fact that we keep track of groups covered with a cpumask_t).
5614 * init_sched_build_groups will build a circular linked list of the groups
5615 * covered by the given span, and will set each group's ->cpumask correctly,
5616 * and ->cpu_power to 0.
5618 static void
5619 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
5620 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
5621 struct sched_group **sg))
5623 struct sched_group *first = NULL, *last = NULL;
5624 cpumask_t covered = CPU_MASK_NONE;
5625 int i;
5627 for_each_cpu_mask(i, span) {
5628 struct sched_group *sg;
5629 int group = group_fn(i, cpu_map, &sg);
5630 int j;
5632 if (cpu_isset(i, covered))
5633 continue;
5635 sg->cpumask = CPU_MASK_NONE;
5636 sg->__cpu_power = 0;
5638 for_each_cpu_mask(j, span) {
5639 if (group_fn(j, cpu_map, NULL) != group)
5640 continue;
5642 cpu_set(j, covered);
5643 cpu_set(j, sg->cpumask);
5645 if (!first)
5646 first = sg;
5647 if (last)
5648 last->next = sg;
5649 last = sg;
5651 last->next = first;
5654 #define SD_NODES_PER_DOMAIN 16
5656 #ifdef CONFIG_NUMA
5659 * find_next_best_node - find the next node to include in a sched_domain
5660 * @node: node whose sched_domain we're building
5661 * @used_nodes: nodes already in the sched_domain
5663 * Find the next node to include in a given scheduling domain. Simply
5664 * finds the closest node not already in the @used_nodes map.
5666 * Should use nodemask_t.
5668 static int find_next_best_node(int node, unsigned long *used_nodes)
5670 int i, n, val, min_val, best_node = 0;
5672 min_val = INT_MAX;
5674 for (i = 0; i < MAX_NUMNODES; i++) {
5675 /* Start at @node */
5676 n = (node + i) % MAX_NUMNODES;
5678 if (!nr_cpus_node(n))
5679 continue;
5681 /* Skip already used nodes */
5682 if (test_bit(n, used_nodes))
5683 continue;
5685 /* Simple min distance search */
5686 val = node_distance(node, n);
5688 if (val < min_val) {
5689 min_val = val;
5690 best_node = n;
5694 set_bit(best_node, used_nodes);
5695 return best_node;
5699 * sched_domain_node_span - get a cpumask for a node's sched_domain
5700 * @node: node whose cpumask we're constructing
5701 * @size: number of nodes to include in this span
5703 * Given a node, construct a good cpumask for its sched_domain to span. It
5704 * should be one that prevents unnecessary balancing, but also spreads tasks
5705 * out optimally.
5707 static cpumask_t sched_domain_node_span(int node)
5709 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5710 cpumask_t span, nodemask;
5711 int i;
5713 cpus_clear(span);
5714 bitmap_zero(used_nodes, MAX_NUMNODES);
5716 nodemask = node_to_cpumask(node);
5717 cpus_or(span, span, nodemask);
5718 set_bit(node, used_nodes);
5720 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5721 int next_node = find_next_best_node(node, used_nodes);
5723 nodemask = node_to_cpumask(next_node);
5724 cpus_or(span, span, nodemask);
5727 return span;
5729 #endif
5731 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
5734 * SMT sched-domains:
5736 #ifdef CONFIG_SCHED_SMT
5737 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
5738 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
5740 static int cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map,
5741 struct sched_group **sg)
5743 if (sg)
5744 *sg = &per_cpu(sched_group_cpus, cpu);
5745 return cpu;
5747 #endif
5750 * multi-core sched-domains:
5752 #ifdef CONFIG_SCHED_MC
5753 static DEFINE_PER_CPU(struct sched_domain, core_domains);
5754 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
5755 #endif
5757 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
5758 static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
5759 struct sched_group **sg)
5761 int group;
5762 cpumask_t mask = cpu_sibling_map[cpu];
5763 cpus_and(mask, mask, *cpu_map);
5764 group = first_cpu(mask);
5765 if (sg)
5766 *sg = &per_cpu(sched_group_core, group);
5767 return group;
5769 #elif defined(CONFIG_SCHED_MC)
5770 static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
5771 struct sched_group **sg)
5773 if (sg)
5774 *sg = &per_cpu(sched_group_core, cpu);
5775 return cpu;
5777 #endif
5779 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
5780 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
5782 static int cpu_to_phys_group(int cpu, const cpumask_t *cpu_map,
5783 struct sched_group **sg)
5785 int group;
5786 #ifdef CONFIG_SCHED_MC
5787 cpumask_t mask = cpu_coregroup_map(cpu);
5788 cpus_and(mask, mask, *cpu_map);
5789 group = first_cpu(mask);
5790 #elif defined(CONFIG_SCHED_SMT)
5791 cpumask_t mask = cpu_sibling_map[cpu];
5792 cpus_and(mask, mask, *cpu_map);
5793 group = first_cpu(mask);
5794 #else
5795 group = cpu;
5796 #endif
5797 if (sg)
5798 *sg = &per_cpu(sched_group_phys, group);
5799 return group;
5802 #ifdef CONFIG_NUMA
5804 * The init_sched_build_groups can't handle what we want to do with node
5805 * groups, so roll our own. Now each node has its own list of groups which
5806 * gets dynamically allocated.
5808 static DEFINE_PER_CPU(struct sched_domain, node_domains);
5809 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
5811 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
5812 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
5814 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
5815 struct sched_group **sg)
5817 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
5818 int group;
5820 cpus_and(nodemask, nodemask, *cpu_map);
5821 group = first_cpu(nodemask);
5823 if (sg)
5824 *sg = &per_cpu(sched_group_allnodes, group);
5825 return group;
5828 static void init_numa_sched_groups_power(struct sched_group *group_head)
5830 struct sched_group *sg = group_head;
5831 int j;
5833 if (!sg)
5834 return;
5835 next_sg:
5836 for_each_cpu_mask(j, sg->cpumask) {
5837 struct sched_domain *sd;
5839 sd = &per_cpu(phys_domains, j);
5840 if (j != first_cpu(sd->groups->cpumask)) {
5842 * Only add "power" once for each
5843 * physical package.
5845 continue;
5848 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
5850 sg = sg->next;
5851 if (sg != group_head)
5852 goto next_sg;
5854 #endif
5856 #ifdef CONFIG_NUMA
5857 /* Free memory allocated for various sched_group structures */
5858 static void free_sched_groups(const cpumask_t *cpu_map)
5860 int cpu, i;
5862 for_each_cpu_mask(cpu, *cpu_map) {
5863 struct sched_group **sched_group_nodes
5864 = sched_group_nodes_bycpu[cpu];
5866 if (!sched_group_nodes)
5867 continue;
5869 for (i = 0; i < MAX_NUMNODES; i++) {
5870 cpumask_t nodemask = node_to_cpumask(i);
5871 struct sched_group *oldsg, *sg = sched_group_nodes[i];
5873 cpus_and(nodemask, nodemask, *cpu_map);
5874 if (cpus_empty(nodemask))
5875 continue;
5877 if (sg == NULL)
5878 continue;
5879 sg = sg->next;
5880 next_sg:
5881 oldsg = sg;
5882 sg = sg->next;
5883 kfree(oldsg);
5884 if (oldsg != sched_group_nodes[i])
5885 goto next_sg;
5887 kfree(sched_group_nodes);
5888 sched_group_nodes_bycpu[cpu] = NULL;
5891 #else
5892 static void free_sched_groups(const cpumask_t *cpu_map)
5895 #endif
5898 * Initialize sched groups cpu_power.
5900 * cpu_power indicates the capacity of sched group, which is used while
5901 * distributing the load between different sched groups in a sched domain.
5902 * Typically cpu_power for all the groups in a sched domain will be same unless
5903 * there are asymmetries in the topology. If there are asymmetries, group
5904 * having more cpu_power will pickup more load compared to the group having
5905 * less cpu_power.
5907 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
5908 * the maximum number of tasks a group can handle in the presence of other idle
5909 * or lightly loaded groups in the same sched domain.
5911 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
5913 struct sched_domain *child;
5914 struct sched_group *group;
5916 WARN_ON(!sd || !sd->groups);
5918 if (cpu != first_cpu(sd->groups->cpumask))
5919 return;
5921 child = sd->child;
5923 sd->groups->__cpu_power = 0;
5926 * For perf policy, if the groups in child domain share resources
5927 * (for example cores sharing some portions of the cache hierarchy
5928 * or SMT), then set this domain groups cpu_power such that each group
5929 * can handle only one task, when there are other idle groups in the
5930 * same sched domain.
5932 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
5933 (child->flags &
5934 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
5935 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
5936 return;
5940 * add cpu_power of each child group to this groups cpu_power
5942 group = child->groups;
5943 do {
5944 sg_inc_cpu_power(sd->groups, group->__cpu_power);
5945 group = group->next;
5946 } while (group != child->groups);
5950 * Build sched domains for a given set of cpus and attach the sched domains
5951 * to the individual cpus
5953 static int build_sched_domains(const cpumask_t *cpu_map)
5955 int i;
5956 #ifdef CONFIG_NUMA
5957 struct sched_group **sched_group_nodes = NULL;
5958 int sd_allnodes = 0;
5961 * Allocate the per-node list of sched groups
5963 sched_group_nodes = kzalloc(sizeof(struct sched_group *)*MAX_NUMNODES,
5964 GFP_KERNEL);
5965 if (!sched_group_nodes) {
5966 printk(KERN_WARNING "Can not alloc sched group node list\n");
5967 return -ENOMEM;
5969 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
5970 #endif
5973 * Set up domains for cpus specified by the cpu_map.
5975 for_each_cpu_mask(i, *cpu_map) {
5976 struct sched_domain *sd = NULL, *p;
5977 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5979 cpus_and(nodemask, nodemask, *cpu_map);
5981 #ifdef CONFIG_NUMA
5982 if (cpus_weight(*cpu_map) >
5983 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
5984 sd = &per_cpu(allnodes_domains, i);
5985 *sd = SD_ALLNODES_INIT;
5986 sd->span = *cpu_map;
5987 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
5988 p = sd;
5989 sd_allnodes = 1;
5990 } else
5991 p = NULL;
5993 sd = &per_cpu(node_domains, i);
5994 *sd = SD_NODE_INIT;
5995 sd->span = sched_domain_node_span(cpu_to_node(i));
5996 sd->parent = p;
5997 if (p)
5998 p->child = sd;
5999 cpus_and(sd->span, sd->span, *cpu_map);
6000 #endif
6002 p = sd;
6003 sd = &per_cpu(phys_domains, i);
6004 *sd = SD_CPU_INIT;
6005 sd->span = nodemask;
6006 sd->parent = p;
6007 if (p)
6008 p->child = sd;
6009 cpu_to_phys_group(i, cpu_map, &sd->groups);
6011 #ifdef CONFIG_SCHED_MC
6012 p = sd;
6013 sd = &per_cpu(core_domains, i);
6014 *sd = SD_MC_INIT;
6015 sd->span = cpu_coregroup_map(i);
6016 cpus_and(sd->span, sd->span, *cpu_map);
6017 sd->parent = p;
6018 p->child = sd;
6019 cpu_to_core_group(i, cpu_map, &sd->groups);
6020 #endif
6022 #ifdef CONFIG_SCHED_SMT
6023 p = sd;
6024 sd = &per_cpu(cpu_domains, i);
6025 *sd = SD_SIBLING_INIT;
6026 sd->span = cpu_sibling_map[i];
6027 cpus_and(sd->span, sd->span, *cpu_map);
6028 sd->parent = p;
6029 p->child = sd;
6030 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6031 #endif
6034 #ifdef CONFIG_SCHED_SMT
6035 /* Set up CPU (sibling) groups */
6036 for_each_cpu_mask(i, *cpu_map) {
6037 cpumask_t this_sibling_map = cpu_sibling_map[i];
6038 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6039 if (i != first_cpu(this_sibling_map))
6040 continue;
6042 init_sched_build_groups(this_sibling_map, cpu_map,
6043 &cpu_to_cpu_group);
6045 #endif
6047 #ifdef CONFIG_SCHED_MC
6048 /* Set up multi-core groups */
6049 for_each_cpu_mask(i, *cpu_map) {
6050 cpumask_t this_core_map = cpu_coregroup_map(i);
6051 cpus_and(this_core_map, this_core_map, *cpu_map);
6052 if (i != first_cpu(this_core_map))
6053 continue;
6054 init_sched_build_groups(this_core_map, cpu_map,
6055 &cpu_to_core_group);
6057 #endif
6059 /* Set up physical groups */
6060 for (i = 0; i < MAX_NUMNODES; i++) {
6061 cpumask_t nodemask = node_to_cpumask(i);
6063 cpus_and(nodemask, nodemask, *cpu_map);
6064 if (cpus_empty(nodemask))
6065 continue;
6067 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6070 #ifdef CONFIG_NUMA
6071 /* Set up node groups */
6072 if (sd_allnodes)
6073 init_sched_build_groups(*cpu_map, cpu_map,
6074 &cpu_to_allnodes_group);
6076 for (i = 0; i < MAX_NUMNODES; i++) {
6077 /* Set up node groups */
6078 struct sched_group *sg, *prev;
6079 cpumask_t nodemask = node_to_cpumask(i);
6080 cpumask_t domainspan;
6081 cpumask_t covered = CPU_MASK_NONE;
6082 int j;
6084 cpus_and(nodemask, nodemask, *cpu_map);
6085 if (cpus_empty(nodemask)) {
6086 sched_group_nodes[i] = NULL;
6087 continue;
6090 domainspan = sched_domain_node_span(i);
6091 cpus_and(domainspan, domainspan, *cpu_map);
6093 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6094 if (!sg) {
6095 printk(KERN_WARNING "Can not alloc domain group for "
6096 "node %d\n", i);
6097 goto error;
6099 sched_group_nodes[i] = sg;
6100 for_each_cpu_mask(j, nodemask) {
6101 struct sched_domain *sd;
6103 sd = &per_cpu(node_domains, j);
6104 sd->groups = sg;
6106 sg->__cpu_power = 0;
6107 sg->cpumask = nodemask;
6108 sg->next = sg;
6109 cpus_or(covered, covered, nodemask);
6110 prev = sg;
6112 for (j = 0; j < MAX_NUMNODES; j++) {
6113 cpumask_t tmp, notcovered;
6114 int n = (i + j) % MAX_NUMNODES;
6116 cpus_complement(notcovered, covered);
6117 cpus_and(tmp, notcovered, *cpu_map);
6118 cpus_and(tmp, tmp, domainspan);
6119 if (cpus_empty(tmp))
6120 break;
6122 nodemask = node_to_cpumask(n);
6123 cpus_and(tmp, tmp, nodemask);
6124 if (cpus_empty(tmp))
6125 continue;
6127 sg = kmalloc_node(sizeof(struct sched_group),
6128 GFP_KERNEL, i);
6129 if (!sg) {
6130 printk(KERN_WARNING
6131 "Can not alloc domain group for node %d\n", j);
6132 goto error;
6134 sg->__cpu_power = 0;
6135 sg->cpumask = tmp;
6136 sg->next = prev->next;
6137 cpus_or(covered, covered, tmp);
6138 prev->next = sg;
6139 prev = sg;
6142 #endif
6144 /* Calculate CPU power for physical packages and nodes */
6145 #ifdef CONFIG_SCHED_SMT
6146 for_each_cpu_mask(i, *cpu_map) {
6147 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6149 init_sched_groups_power(i, sd);
6151 #endif
6152 #ifdef CONFIG_SCHED_MC
6153 for_each_cpu_mask(i, *cpu_map) {
6154 struct sched_domain *sd = &per_cpu(core_domains, i);
6156 init_sched_groups_power(i, sd);
6158 #endif
6160 for_each_cpu_mask(i, *cpu_map) {
6161 struct sched_domain *sd = &per_cpu(phys_domains, i);
6163 init_sched_groups_power(i, sd);
6166 #ifdef CONFIG_NUMA
6167 for (i = 0; i < MAX_NUMNODES; i++)
6168 init_numa_sched_groups_power(sched_group_nodes[i]);
6170 if (sd_allnodes) {
6171 struct sched_group *sg;
6173 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6174 init_numa_sched_groups_power(sg);
6176 #endif
6178 /* Attach the domains */
6179 for_each_cpu_mask(i, *cpu_map) {
6180 struct sched_domain *sd;
6181 #ifdef CONFIG_SCHED_SMT
6182 sd = &per_cpu(cpu_domains, i);
6183 #elif defined(CONFIG_SCHED_MC)
6184 sd = &per_cpu(core_domains, i);
6185 #else
6186 sd = &per_cpu(phys_domains, i);
6187 #endif
6188 cpu_attach_domain(sd, i);
6191 return 0;
6193 #ifdef CONFIG_NUMA
6194 error:
6195 free_sched_groups(cpu_map);
6196 return -ENOMEM;
6197 #endif
6200 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6202 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6204 cpumask_t cpu_default_map;
6205 int err;
6208 * Setup mask for cpus without special case scheduling requirements.
6209 * For now this just excludes isolated cpus, but could be used to
6210 * exclude other special cases in the future.
6212 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6214 err = build_sched_domains(&cpu_default_map);
6216 return err;
6219 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6221 free_sched_groups(cpu_map);
6225 * Detach sched domains from a group of cpus specified in cpu_map
6226 * These cpus will now be attached to the NULL domain
6228 static void detach_destroy_domains(const cpumask_t *cpu_map)
6230 int i;
6232 for_each_cpu_mask(i, *cpu_map)
6233 cpu_attach_domain(NULL, i);
6234 synchronize_sched();
6235 arch_destroy_sched_domains(cpu_map);
6239 * Partition sched domains as specified by the cpumasks below.
6240 * This attaches all cpus from the cpumasks to the NULL domain,
6241 * waits for a RCU quiescent period, recalculates sched
6242 * domain information and then attaches them back to the
6243 * correct sched domains
6244 * Call with hotplug lock held
6246 int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6248 cpumask_t change_map;
6249 int err = 0;
6251 cpus_and(*partition1, *partition1, cpu_online_map);
6252 cpus_and(*partition2, *partition2, cpu_online_map);
6253 cpus_or(change_map, *partition1, *partition2);
6255 /* Detach sched domains from all of the affected cpus */
6256 detach_destroy_domains(&change_map);
6257 if (!cpus_empty(*partition1))
6258 err = build_sched_domains(partition1);
6259 if (!err && !cpus_empty(*partition2))
6260 err = build_sched_domains(partition2);
6262 return err;
6265 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6266 static int arch_reinit_sched_domains(void)
6268 int err;
6270 mutex_lock(&sched_hotcpu_mutex);
6271 detach_destroy_domains(&cpu_online_map);
6272 err = arch_init_sched_domains(&cpu_online_map);
6273 mutex_unlock(&sched_hotcpu_mutex);
6275 return err;
6278 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6280 int ret;
6282 if (buf[0] != '0' && buf[0] != '1')
6283 return -EINVAL;
6285 if (smt)
6286 sched_smt_power_savings = (buf[0] == '1');
6287 else
6288 sched_mc_power_savings = (buf[0] == '1');
6290 ret = arch_reinit_sched_domains();
6292 return ret ? ret : count;
6295 #ifdef CONFIG_SCHED_MC
6296 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6298 return sprintf(page, "%u\n", sched_mc_power_savings);
6300 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6301 const char *buf, size_t count)
6303 return sched_power_savings_store(buf, count, 0);
6305 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6306 sched_mc_power_savings_store);
6307 #endif
6309 #ifdef CONFIG_SCHED_SMT
6310 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6312 return sprintf(page, "%u\n", sched_smt_power_savings);
6314 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6315 const char *buf, size_t count)
6317 return sched_power_savings_store(buf, count, 1);
6319 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6320 sched_smt_power_savings_store);
6321 #endif
6323 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6325 int err = 0;
6327 #ifdef CONFIG_SCHED_SMT
6328 if (smt_capable())
6329 err = sysfs_create_file(&cls->kset.kobj,
6330 &attr_sched_smt_power_savings.attr);
6331 #endif
6332 #ifdef CONFIG_SCHED_MC
6333 if (!err && mc_capable())
6334 err = sysfs_create_file(&cls->kset.kobj,
6335 &attr_sched_mc_power_savings.attr);
6336 #endif
6337 return err;
6339 #endif
6342 * Force a reinitialization of the sched domains hierarchy. The domains
6343 * and groups cannot be updated in place without racing with the balancing
6344 * code, so we temporarily attach all running cpus to the NULL domain
6345 * which will prevent rebalancing while the sched domains are recalculated.
6347 static int update_sched_domains(struct notifier_block *nfb,
6348 unsigned long action, void *hcpu)
6350 switch (action) {
6351 case CPU_UP_PREPARE:
6352 case CPU_UP_PREPARE_FROZEN:
6353 case CPU_DOWN_PREPARE:
6354 case CPU_DOWN_PREPARE_FROZEN:
6355 detach_destroy_domains(&cpu_online_map);
6356 return NOTIFY_OK;
6358 case CPU_UP_CANCELED:
6359 case CPU_UP_CANCELED_FROZEN:
6360 case CPU_DOWN_FAILED:
6361 case CPU_DOWN_FAILED_FROZEN:
6362 case CPU_ONLINE:
6363 case CPU_ONLINE_FROZEN:
6364 case CPU_DEAD:
6365 case CPU_DEAD_FROZEN:
6367 * Fall through and re-initialise the domains.
6369 break;
6370 default:
6371 return NOTIFY_DONE;
6374 /* The hotplug lock is already held by cpu_up/cpu_down */
6375 arch_init_sched_domains(&cpu_online_map);
6377 return NOTIFY_OK;
6380 void __init sched_init_smp(void)
6382 cpumask_t non_isolated_cpus;
6384 mutex_lock(&sched_hotcpu_mutex);
6385 arch_init_sched_domains(&cpu_online_map);
6386 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
6387 if (cpus_empty(non_isolated_cpus))
6388 cpu_set(smp_processor_id(), non_isolated_cpus);
6389 mutex_unlock(&sched_hotcpu_mutex);
6390 /* XXX: Theoretical race here - CPU may be hotplugged now */
6391 hotcpu_notifier(update_sched_domains, 0);
6393 init_sched_domain_sysctl();
6395 /* Move init over to a non-isolated CPU */
6396 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
6397 BUG();
6399 #else
6400 void __init sched_init_smp(void)
6403 #endif /* CONFIG_SMP */
6405 int in_sched_functions(unsigned long addr)
6407 /* Linker adds these: start and end of __sched functions */
6408 extern char __sched_text_start[], __sched_text_end[];
6410 return in_lock_functions(addr) ||
6411 (addr >= (unsigned long)__sched_text_start
6412 && addr < (unsigned long)__sched_text_end);
6415 static inline void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
6417 cfs_rq->tasks_timeline = RB_ROOT;
6418 #ifdef CONFIG_FAIR_GROUP_SCHED
6419 cfs_rq->rq = rq;
6420 #endif
6423 void __init sched_init(void)
6425 int highest_cpu = 0;
6426 int i, j;
6429 * Link up the scheduling class hierarchy:
6431 rt_sched_class.next = &fair_sched_class;
6432 fair_sched_class.next = &idle_sched_class;
6433 idle_sched_class.next = NULL;
6435 for_each_possible_cpu(i) {
6436 struct rt_prio_array *array;
6437 struct rq *rq;
6439 rq = cpu_rq(i);
6440 spin_lock_init(&rq->lock);
6441 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6442 rq->nr_running = 0;
6443 rq->clock = 1;
6444 init_cfs_rq(&rq->cfs, rq);
6445 #ifdef CONFIG_FAIR_GROUP_SCHED
6446 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6447 list_add(&rq->cfs.leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
6448 #endif
6450 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6451 rq->cpu_load[j] = 0;
6452 #ifdef CONFIG_SMP
6453 rq->sd = NULL;
6454 rq->active_balance = 0;
6455 rq->next_balance = jiffies;
6456 rq->push_cpu = 0;
6457 rq->cpu = i;
6458 rq->migration_thread = NULL;
6459 INIT_LIST_HEAD(&rq->migration_queue);
6460 #endif
6461 atomic_set(&rq->nr_iowait, 0);
6463 array = &rq->rt.active;
6464 for (j = 0; j < MAX_RT_PRIO; j++) {
6465 INIT_LIST_HEAD(array->queue + j);
6466 __clear_bit(j, array->bitmap);
6468 highest_cpu = i;
6469 /* delimiter for bitsearch: */
6470 __set_bit(MAX_RT_PRIO, array->bitmap);
6473 set_load_weight(&init_task);
6475 #ifdef CONFIG_PREEMPT_NOTIFIERS
6476 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
6477 #endif
6479 #ifdef CONFIG_SMP
6480 nr_cpu_ids = highest_cpu + 1;
6481 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
6482 #endif
6484 #ifdef CONFIG_RT_MUTEXES
6485 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
6486 #endif
6489 * The boot idle thread does lazy MMU switching as well:
6491 atomic_inc(&init_mm.mm_count);
6492 enter_lazy_tlb(&init_mm, current);
6495 * Make us the idle thread. Technically, schedule() should not be
6496 * called from this thread, however somewhere below it might be,
6497 * but because we are the idle thread, we just pick up running again
6498 * when this runqueue becomes "idle".
6500 init_idle(current, smp_processor_id());
6502 * During early bootup we pretend to be a normal task:
6504 current->sched_class = &fair_sched_class;
6507 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6508 void __might_sleep(char *file, int line)
6510 #ifdef in_atomic
6511 static unsigned long prev_jiffy; /* ratelimiting */
6513 if ((in_atomic() || irqs_disabled()) &&
6514 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6515 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6516 return;
6517 prev_jiffy = jiffies;
6518 printk(KERN_ERR "BUG: sleeping function called from invalid"
6519 " context at %s:%d\n", file, line);
6520 printk("in_atomic():%d, irqs_disabled():%d\n",
6521 in_atomic(), irqs_disabled());
6522 debug_show_held_locks(current);
6523 if (irqs_disabled())
6524 print_irqtrace_events(current);
6525 dump_stack();
6527 #endif
6529 EXPORT_SYMBOL(__might_sleep);
6530 #endif
6532 #ifdef CONFIG_MAGIC_SYSRQ
6533 void normalize_rt_tasks(void)
6535 struct task_struct *g, *p;
6536 unsigned long flags;
6537 struct rq *rq;
6538 int on_rq;
6540 read_lock_irq(&tasklist_lock);
6541 do_each_thread(g, p) {
6542 p->se.fair_key = 0;
6543 p->se.exec_start = 0;
6544 #ifdef CONFIG_SCHEDSTATS
6545 p->se.wait_start = 0;
6546 p->se.sleep_start = 0;
6547 p->se.block_start = 0;
6548 #endif
6549 task_rq(p)->clock = 0;
6551 if (!rt_task(p)) {
6553 * Renice negative nice level userspace
6554 * tasks back to 0:
6556 if (TASK_NICE(p) < 0 && p->mm)
6557 set_user_nice(p, 0);
6558 continue;
6561 spin_lock_irqsave(&p->pi_lock, flags);
6562 rq = __task_rq_lock(p);
6563 #ifdef CONFIG_SMP
6565 * Do not touch the migration thread:
6567 if (p == rq->migration_thread)
6568 goto out_unlock;
6569 #endif
6571 update_rq_clock(rq);
6572 on_rq = p->se.on_rq;
6573 if (on_rq)
6574 deactivate_task(rq, p, 0);
6575 __setscheduler(rq, p, SCHED_NORMAL, 0);
6576 if (on_rq) {
6577 activate_task(rq, p, 0);
6578 resched_task(rq->curr);
6580 #ifdef CONFIG_SMP
6581 out_unlock:
6582 #endif
6583 __task_rq_unlock(rq);
6584 spin_unlock_irqrestore(&p->pi_lock, flags);
6585 } while_each_thread(g, p);
6587 read_unlock_irq(&tasklist_lock);
6590 #endif /* CONFIG_MAGIC_SYSRQ */
6592 #ifdef CONFIG_IA64
6594 * These functions are only useful for the IA64 MCA handling.
6596 * They can only be called when the whole system has been
6597 * stopped - every CPU needs to be quiescent, and no scheduling
6598 * activity can take place. Using them for anything else would
6599 * be a serious bug, and as a result, they aren't even visible
6600 * under any other configuration.
6604 * curr_task - return the current task for a given cpu.
6605 * @cpu: the processor in question.
6607 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6609 struct task_struct *curr_task(int cpu)
6611 return cpu_curr(cpu);
6615 * set_curr_task - set the current task for a given cpu.
6616 * @cpu: the processor in question.
6617 * @p: the task pointer to set.
6619 * Description: This function must only be used when non-maskable interrupts
6620 * are serviced on a separate stack. It allows the architecture to switch the
6621 * notion of the current task on a cpu in a non-blocking manner. This function
6622 * must be called with all CPU's synchronized, and interrupts disabled, the
6623 * and caller must save the original value of the current task (see
6624 * curr_task() above) and restore that value before reenabling interrupts and
6625 * re-starting the system.
6627 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6629 void set_curr_task(int cpu, struct task_struct *p)
6631 cpu_curr(cpu) = p;
6634 #endif