sched: style cleanup, #2
[linux-2.6/linux-loongson.git] / kernel / sched.c
blob23b9925a1dfb3971ff8b30637b1ee0b763b4a764
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/pid_namespace.h>
48 #include <linux/smp.h>
49 #include <linux/threads.h>
50 #include <linux/timer.h>
51 #include <linux/rcupdate.h>
52 #include <linux/cpu.h>
53 #include <linux/cpuset.h>
54 #include <linux/percpu.h>
55 #include <linux/kthread.h>
56 #include <linux/seq_file.h>
57 #include <linux/sysctl.h>
58 #include <linux/syscalls.h>
59 #include <linux/times.h>
60 #include <linux/tsacct_kern.h>
61 #include <linux/kprobes.h>
62 #include <linux/delayacct.h>
63 #include <linux/reciprocal_div.h>
64 #include <linux/unistd.h>
65 #include <linux/pagemap.h>
67 #include <asm/tlb.h>
68 #include <asm/irq_regs.h>
71 * Scheduler clock - returns current time in nanosec units.
72 * This is default implementation.
73 * Architectures and sub-architectures can override this.
75 unsigned long long __attribute__((weak)) sched_clock(void)
77 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
81 * Convert user-nice values [ -20 ... 0 ... 19 ]
82 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
83 * and back.
85 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
86 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
87 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
90 * 'User priority' is the nice value converted to something we
91 * can work with better when scaling various scheduler parameters,
92 * it's a [ 0 ... 39 ] range.
94 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
95 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
96 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
99 * Helpers for converting nanosecond timing to jiffy resolution
101 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
103 #define NICE_0_LOAD SCHED_LOAD_SCALE
104 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
107 * These are the 'tuning knobs' of the scheduler:
109 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
110 * Timeslices get refilled after they expire.
112 #define DEF_TIMESLICE (100 * HZ / 1000)
114 #ifdef CONFIG_SMP
116 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
117 * Since cpu_power is a 'constant', we can use a reciprocal divide.
119 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
121 return reciprocal_divide(load, sg->reciprocal_cpu_power);
125 * Each time a sched group cpu_power is changed,
126 * we must compute its reciprocal value
128 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
130 sg->__cpu_power += val;
131 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
133 #endif
135 static inline int rt_policy(int policy)
137 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
138 return 1;
139 return 0;
142 static inline int task_has_rt_policy(struct task_struct *p)
144 return rt_policy(p->policy);
148 * This is the priority-queue data structure of the RT scheduling class:
150 struct rt_prio_array {
151 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
152 struct list_head queue[MAX_RT_PRIO];
155 #ifdef CONFIG_FAIR_GROUP_SCHED
157 #include <linux/cgroup.h>
159 struct cfs_rq;
161 /* task group related information */
162 struct task_group {
163 #ifdef CONFIG_FAIR_CGROUP_SCHED
164 struct cgroup_subsys_state css;
165 #endif
166 /* schedulable entities of this group on each cpu */
167 struct sched_entity **se;
168 /* runqueue "owned" by this group on each cpu */
169 struct cfs_rq **cfs_rq;
172 * shares assigned to a task group governs how much of cpu bandwidth
173 * is allocated to the group. The more shares a group has, the more is
174 * the cpu bandwidth allocated to it.
176 * For ex, lets say that there are three task groups, A, B and C which
177 * have been assigned shares 1000, 2000 and 3000 respectively. Then,
178 * cpu bandwidth allocated by the scheduler to task groups A, B and C
179 * should be:
181 * Bw(A) = 1000/(1000+2000+3000) * 100 = 16.66%
182 * Bw(B) = 2000/(1000+2000+3000) * 100 = 33.33%
183 * Bw(C) = 3000/(1000+2000+3000) * 100 = 50%
185 * The weight assigned to a task group's schedulable entities on every
186 * cpu (task_group.se[a_cpu]->load.weight) is derived from the task
187 * group's shares. For ex: lets say that task group A has been
188 * assigned shares of 1000 and there are two CPUs in a system. Then,
190 * tg_A->se[0]->load.weight = tg_A->se[1]->load.weight = 1000;
192 * Note: It's not necessary that each of a task's group schedulable
193 * entity have the same weight on all CPUs. If the group
194 * has 2 of its tasks on CPU0 and 1 task on CPU1, then a
195 * better distribution of weight could be:
197 * tg_A->se[0]->load.weight = 2/3 * 2000 = 1333
198 * tg_A->se[1]->load.weight = 1/2 * 2000 = 667
200 * rebalance_shares() is responsible for distributing the shares of a
201 * task groups like this among the group's schedulable entities across
202 * cpus.
205 unsigned long shares;
207 struct rcu_head rcu;
210 /* Default task group's sched entity on each cpu */
211 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
212 /* Default task group's cfs_rq on each cpu */
213 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
215 static struct sched_entity *init_sched_entity_p[NR_CPUS];
216 static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
218 /* task_group_mutex serializes add/remove of task groups and also changes to
219 * a task group's cpu shares.
221 static DEFINE_MUTEX(task_group_mutex);
223 /* doms_cur_mutex serializes access to doms_cur[] array */
224 static DEFINE_MUTEX(doms_cur_mutex);
226 #ifdef CONFIG_SMP
227 /* kernel thread that runs rebalance_shares() periodically */
228 static struct task_struct *lb_monitor_task;
229 static int load_balance_monitor(void *unused);
230 #endif
232 static void set_se_shares(struct sched_entity *se, unsigned long shares);
234 /* Default task group.
235 * Every task in system belong to this group at bootup.
237 struct task_group init_task_group = {
238 .se = init_sched_entity_p,
239 .cfs_rq = init_cfs_rq_p,
242 #ifdef CONFIG_FAIR_USER_SCHED
243 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
244 #else
245 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
246 #endif
248 #define MIN_GROUP_SHARES 2
250 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
252 /* return group to which a task belongs */
253 static inline struct task_group *task_group(struct task_struct *p)
255 struct task_group *tg;
257 #ifdef CONFIG_FAIR_USER_SCHED
258 tg = p->user->tg;
259 #elif defined(CONFIG_FAIR_CGROUP_SCHED)
260 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
261 struct task_group, css);
262 #else
263 tg = &init_task_group;
264 #endif
265 return tg;
268 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
269 static inline void set_task_cfs_rq(struct task_struct *p, unsigned int cpu)
271 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
272 p->se.parent = task_group(p)->se[cpu];
275 static inline void lock_task_group_list(void)
277 mutex_lock(&task_group_mutex);
280 static inline void unlock_task_group_list(void)
282 mutex_unlock(&task_group_mutex);
285 static inline void lock_doms_cur(void)
287 mutex_lock(&doms_cur_mutex);
290 static inline void unlock_doms_cur(void)
292 mutex_unlock(&doms_cur_mutex);
295 #else
297 static inline void set_task_cfs_rq(struct task_struct *p, unsigned int cpu) { }
298 static inline void lock_task_group_list(void) { }
299 static inline void unlock_task_group_list(void) { }
300 static inline void lock_doms_cur(void) { }
301 static inline void unlock_doms_cur(void) { }
303 #endif /* CONFIG_FAIR_GROUP_SCHED */
305 /* CFS-related fields in a runqueue */
306 struct cfs_rq {
307 struct load_weight load;
308 unsigned long nr_running;
310 u64 exec_clock;
311 u64 min_vruntime;
313 struct rb_root tasks_timeline;
314 struct rb_node *rb_leftmost;
315 struct rb_node *rb_load_balance_curr;
316 /* 'curr' points to currently running entity on this cfs_rq.
317 * It is set to NULL otherwise (i.e when none are currently running).
319 struct sched_entity *curr;
321 unsigned long nr_spread_over;
323 #ifdef CONFIG_FAIR_GROUP_SCHED
324 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
327 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
328 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
329 * (like users, containers etc.)
331 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
332 * list is used during load balance.
334 struct list_head leaf_cfs_rq_list;
335 struct task_group *tg; /* group that "owns" this runqueue */
336 #endif
339 /* Real-Time classes' related field in a runqueue: */
340 struct rt_rq {
341 struct rt_prio_array active;
342 int rt_load_balance_idx;
343 struct list_head *rt_load_balance_head, *rt_load_balance_curr;
344 unsigned long rt_nr_running;
345 unsigned long rt_nr_migratory;
346 /* highest queued rt task prio */
347 int highest_prio;
348 int overloaded;
351 #ifdef CONFIG_SMP
354 * We add the notion of a root-domain which will be used to define per-domain
355 * variables. Each exclusive cpuset essentially defines an island domain by
356 * fully partitioning the member cpus from any other cpuset. Whenever a new
357 * exclusive cpuset is created, we also create and attach a new root-domain
358 * object.
360 * By default the system creates a single root-domain with all cpus as
361 * members (mimicking the global state we have today).
363 struct root_domain {
364 atomic_t refcount;
365 cpumask_t span;
366 cpumask_t online;
369 * The "RT overload" flag: it gets set if a CPU has more than
370 * one runnable RT task.
372 cpumask_t rto_mask;
373 atomic_t rto_count;
376 static struct root_domain def_root_domain;
378 #endif
381 * This is the main, per-CPU runqueue data structure.
383 * Locking rule: those places that want to lock multiple runqueues
384 * (such as the load balancing or the thread migration code), lock
385 * acquire operations must be ordered by ascending &runqueue.
387 struct rq {
388 /* runqueue lock: */
389 spinlock_t lock;
392 * nr_running and cpu_load should be in the same cacheline because
393 * remote CPUs use both these fields when doing load calculation.
395 unsigned long nr_running;
396 #define CPU_LOAD_IDX_MAX 5
397 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
398 unsigned char idle_at_tick;
399 #ifdef CONFIG_NO_HZ
400 unsigned char in_nohz_recently;
401 #endif
402 /* capture load from *all* tasks on this cpu: */
403 struct load_weight load;
404 unsigned long nr_load_updates;
405 u64 nr_switches;
407 struct cfs_rq cfs;
408 #ifdef CONFIG_FAIR_GROUP_SCHED
409 /* list of leaf cfs_rq on this cpu: */
410 struct list_head leaf_cfs_rq_list;
411 #endif
412 struct rt_rq rt;
415 * This is part of a global counter where only the total sum
416 * over all CPUs matters. A task can increase this counter on
417 * one CPU and if it got migrated afterwards it may decrease
418 * it on another CPU. Always updated under the runqueue lock:
420 unsigned long nr_uninterruptible;
422 struct task_struct *curr, *idle;
423 unsigned long next_balance;
424 struct mm_struct *prev_mm;
426 u64 clock, prev_clock_raw;
427 s64 clock_max_delta;
429 unsigned int clock_warps, clock_overflows;
430 u64 idle_clock;
431 unsigned int clock_deep_idle_events;
432 u64 tick_timestamp;
434 atomic_t nr_iowait;
436 #ifdef CONFIG_SMP
437 struct root_domain *rd;
438 struct sched_domain *sd;
440 /* For active balancing */
441 int active_balance;
442 int push_cpu;
443 /* cpu of this runqueue: */
444 int cpu;
446 struct task_struct *migration_thread;
447 struct list_head migration_queue;
448 #endif
450 #ifdef CONFIG_SCHEDSTATS
451 /* latency stats */
452 struct sched_info rq_sched_info;
454 /* sys_sched_yield() stats */
455 unsigned int yld_exp_empty;
456 unsigned int yld_act_empty;
457 unsigned int yld_both_empty;
458 unsigned int yld_count;
460 /* schedule() stats */
461 unsigned int sched_switch;
462 unsigned int sched_count;
463 unsigned int sched_goidle;
465 /* try_to_wake_up() stats */
466 unsigned int ttwu_count;
467 unsigned int ttwu_local;
469 /* BKL stats */
470 unsigned int bkl_count;
471 #endif
472 struct lock_class_key rq_lock_key;
475 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
477 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
479 rq->curr->sched_class->check_preempt_curr(rq, p);
482 static inline int cpu_of(struct rq *rq)
484 #ifdef CONFIG_SMP
485 return rq->cpu;
486 #else
487 return 0;
488 #endif
492 * Update the per-runqueue clock, as finegrained as the platform can give
493 * us, but without assuming monotonicity, etc.:
495 static void __update_rq_clock(struct rq *rq)
497 u64 prev_raw = rq->prev_clock_raw;
498 u64 now = sched_clock();
499 s64 delta = now - prev_raw;
500 u64 clock = rq->clock;
502 #ifdef CONFIG_SCHED_DEBUG
503 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
504 #endif
506 * Protect against sched_clock() occasionally going backwards:
508 if (unlikely(delta < 0)) {
509 clock++;
510 rq->clock_warps++;
511 } else {
513 * Catch too large forward jumps too:
515 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
516 if (clock < rq->tick_timestamp + TICK_NSEC)
517 clock = rq->tick_timestamp + TICK_NSEC;
518 else
519 clock++;
520 rq->clock_overflows++;
521 } else {
522 if (unlikely(delta > rq->clock_max_delta))
523 rq->clock_max_delta = delta;
524 clock += delta;
528 rq->prev_clock_raw = now;
529 rq->clock = clock;
532 static void update_rq_clock(struct rq *rq)
534 if (likely(smp_processor_id() == cpu_of(rq)))
535 __update_rq_clock(rq);
539 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
540 * See detach_destroy_domains: synchronize_sched for details.
542 * The domain tree of any CPU may only be accessed from within
543 * preempt-disabled sections.
545 #define for_each_domain(cpu, __sd) \
546 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
548 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
549 #define this_rq() (&__get_cpu_var(runqueues))
550 #define task_rq(p) cpu_rq(task_cpu(p))
551 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
554 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
556 #ifdef CONFIG_SCHED_DEBUG
557 # define const_debug __read_mostly
558 #else
559 # define const_debug static const
560 #endif
563 * Debugging: various feature bits
565 enum {
566 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
567 SCHED_FEAT_WAKEUP_PREEMPT = 2,
568 SCHED_FEAT_START_DEBIT = 4,
569 SCHED_FEAT_TREE_AVG = 8,
570 SCHED_FEAT_APPROX_AVG = 16,
573 const_debug unsigned int sysctl_sched_features =
574 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
575 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
576 SCHED_FEAT_START_DEBIT * 1 |
577 SCHED_FEAT_TREE_AVG * 0 |
578 SCHED_FEAT_APPROX_AVG * 0;
580 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
583 * Number of tasks to iterate in a single balance run.
584 * Limited because this is done with IRQs disabled.
586 const_debug unsigned int sysctl_sched_nr_migrate = 32;
589 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
590 * clock constructed from sched_clock():
592 unsigned long long cpu_clock(int cpu)
594 unsigned long long now;
595 unsigned long flags;
596 struct rq *rq;
598 local_irq_save(flags);
599 rq = cpu_rq(cpu);
601 * Only call sched_clock() if the scheduler has already been
602 * initialized (some code might call cpu_clock() very early):
604 if (rq->idle)
605 update_rq_clock(rq);
606 now = rq->clock;
607 local_irq_restore(flags);
609 return now;
611 EXPORT_SYMBOL_GPL(cpu_clock);
613 #ifndef prepare_arch_switch
614 # define prepare_arch_switch(next) do { } while (0)
615 #endif
616 #ifndef finish_arch_switch
617 # define finish_arch_switch(prev) do { } while (0)
618 #endif
620 static inline int task_current(struct rq *rq, struct task_struct *p)
622 return rq->curr == p;
625 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
626 static inline int task_running(struct rq *rq, struct task_struct *p)
628 return task_current(rq, p);
631 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
635 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
637 #ifdef CONFIG_DEBUG_SPINLOCK
638 /* this is a valid case when another task releases the spinlock */
639 rq->lock.owner = current;
640 #endif
642 * If we are tracking spinlock dependencies then we have to
643 * fix up the runqueue lock - which gets 'carried over' from
644 * prev into current:
646 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
648 spin_unlock_irq(&rq->lock);
651 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
652 static inline int task_running(struct rq *rq, struct task_struct *p)
654 #ifdef CONFIG_SMP
655 return p->oncpu;
656 #else
657 return task_current(rq, p);
658 #endif
661 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
663 #ifdef CONFIG_SMP
665 * We can optimise this out completely for !SMP, because the
666 * SMP rebalancing from interrupt is the only thing that cares
667 * here.
669 next->oncpu = 1;
670 #endif
671 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
672 spin_unlock_irq(&rq->lock);
673 #else
674 spin_unlock(&rq->lock);
675 #endif
678 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
680 #ifdef CONFIG_SMP
682 * After ->oncpu is cleared, the task can be moved to a different CPU.
683 * We must ensure this doesn't happen until the switch is completely
684 * finished.
686 smp_wmb();
687 prev->oncpu = 0;
688 #endif
689 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
690 local_irq_enable();
691 #endif
693 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
696 * __task_rq_lock - lock the runqueue a given task resides on.
697 * Must be called interrupts disabled.
699 static inline struct rq *__task_rq_lock(struct task_struct *p)
700 __acquires(rq->lock)
702 for (;;) {
703 struct rq *rq = task_rq(p);
704 spin_lock(&rq->lock);
705 if (likely(rq == task_rq(p)))
706 return rq;
707 spin_unlock(&rq->lock);
712 * task_rq_lock - lock the runqueue a given task resides on and disable
713 * interrupts. Note the ordering: we can safely lookup the task_rq without
714 * explicitly disabling preemption.
716 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
717 __acquires(rq->lock)
719 struct rq *rq;
721 for (;;) {
722 local_irq_save(*flags);
723 rq = task_rq(p);
724 spin_lock(&rq->lock);
725 if (likely(rq == task_rq(p)))
726 return rq;
727 spin_unlock_irqrestore(&rq->lock, *flags);
731 static void __task_rq_unlock(struct rq *rq)
732 __releases(rq->lock)
734 spin_unlock(&rq->lock);
737 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
738 __releases(rq->lock)
740 spin_unlock_irqrestore(&rq->lock, *flags);
744 * this_rq_lock - lock this runqueue and disable interrupts.
746 static struct rq *this_rq_lock(void)
747 __acquires(rq->lock)
749 struct rq *rq;
751 local_irq_disable();
752 rq = this_rq();
753 spin_lock(&rq->lock);
755 return rq;
759 * We are going deep-idle (irqs are disabled):
761 void sched_clock_idle_sleep_event(void)
763 struct rq *rq = cpu_rq(smp_processor_id());
765 spin_lock(&rq->lock);
766 __update_rq_clock(rq);
767 spin_unlock(&rq->lock);
768 rq->clock_deep_idle_events++;
770 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
773 * We just idled delta nanoseconds (called with irqs disabled):
775 void sched_clock_idle_wakeup_event(u64 delta_ns)
777 struct rq *rq = cpu_rq(smp_processor_id());
778 u64 now = sched_clock();
780 touch_softlockup_watchdog();
781 rq->idle_clock += delta_ns;
783 * Override the previous timestamp and ignore all
784 * sched_clock() deltas that occured while we idled,
785 * and use the PM-provided delta_ns to advance the
786 * rq clock:
788 spin_lock(&rq->lock);
789 rq->prev_clock_raw = now;
790 rq->clock += delta_ns;
791 spin_unlock(&rq->lock);
793 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
796 * resched_task - mark a task 'to be rescheduled now'.
798 * On UP this means the setting of the need_resched flag, on SMP it
799 * might also involve a cross-CPU call to trigger the scheduler on
800 * the target CPU.
802 #ifdef CONFIG_SMP
804 #ifndef tsk_is_polling
805 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
806 #endif
808 static void resched_task(struct task_struct *p)
810 int cpu;
812 assert_spin_locked(&task_rq(p)->lock);
814 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
815 return;
817 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
819 cpu = task_cpu(p);
820 if (cpu == smp_processor_id())
821 return;
823 /* NEED_RESCHED must be visible before we test polling */
824 smp_mb();
825 if (!tsk_is_polling(p))
826 smp_send_reschedule(cpu);
829 static void resched_cpu(int cpu)
831 struct rq *rq = cpu_rq(cpu);
832 unsigned long flags;
834 if (!spin_trylock_irqsave(&rq->lock, flags))
835 return;
836 resched_task(cpu_curr(cpu));
837 spin_unlock_irqrestore(&rq->lock, flags);
839 #else
840 static inline void resched_task(struct task_struct *p)
842 assert_spin_locked(&task_rq(p)->lock);
843 set_tsk_need_resched(p);
845 #endif
847 #if BITS_PER_LONG == 32
848 # define WMULT_CONST (~0UL)
849 #else
850 # define WMULT_CONST (1UL << 32)
851 #endif
853 #define WMULT_SHIFT 32
856 * Shift right and round:
858 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
860 static unsigned long
861 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
862 struct load_weight *lw)
864 u64 tmp;
866 if (unlikely(!lw->inv_weight))
867 lw->inv_weight = (WMULT_CONST - lw->weight/2) / lw->weight + 1;
869 tmp = (u64)delta_exec * weight;
871 * Check whether we'd overflow the 64-bit multiplication:
873 if (unlikely(tmp > WMULT_CONST))
874 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
875 WMULT_SHIFT/2);
876 else
877 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
879 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
882 static inline unsigned long
883 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
885 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
888 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
890 lw->weight += inc;
893 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
895 lw->weight -= dec;
899 * To aid in avoiding the subversion of "niceness" due to uneven distribution
900 * of tasks with abnormal "nice" values across CPUs the contribution that
901 * each task makes to its run queue's load is weighted according to its
902 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
903 * scaled version of the new time slice allocation that they receive on time
904 * slice expiry etc.
907 #define WEIGHT_IDLEPRIO 2
908 #define WMULT_IDLEPRIO (1 << 31)
911 * Nice levels are multiplicative, with a gentle 10% change for every
912 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
913 * nice 1, it will get ~10% less CPU time than another CPU-bound task
914 * that remained on nice 0.
916 * The "10% effect" is relative and cumulative: from _any_ nice level,
917 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
918 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
919 * If a task goes up by ~10% and another task goes down by ~10% then
920 * the relative distance between them is ~25%.)
922 static const int prio_to_weight[40] = {
923 /* -20 */ 88761, 71755, 56483, 46273, 36291,
924 /* -15 */ 29154, 23254, 18705, 14949, 11916,
925 /* -10 */ 9548, 7620, 6100, 4904, 3906,
926 /* -5 */ 3121, 2501, 1991, 1586, 1277,
927 /* 0 */ 1024, 820, 655, 526, 423,
928 /* 5 */ 335, 272, 215, 172, 137,
929 /* 10 */ 110, 87, 70, 56, 45,
930 /* 15 */ 36, 29, 23, 18, 15,
934 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
936 * In cases where the weight does not change often, we can use the
937 * precalculated inverse to speed up arithmetics by turning divisions
938 * into multiplications:
940 static const u32 prio_to_wmult[40] = {
941 /* -20 */ 48388, 59856, 76040, 92818, 118348,
942 /* -15 */ 147320, 184698, 229616, 287308, 360437,
943 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
944 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
945 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
946 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
947 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
948 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
951 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
954 * runqueue iterator, to support SMP load-balancing between different
955 * scheduling classes, without having to expose their internal data
956 * structures to the load-balancing proper:
958 struct rq_iterator {
959 void *arg;
960 struct task_struct *(*start)(void *);
961 struct task_struct *(*next)(void *);
964 #ifdef CONFIG_SMP
965 static unsigned long
966 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
967 unsigned long max_load_move, struct sched_domain *sd,
968 enum cpu_idle_type idle, int *all_pinned,
969 int *this_best_prio, struct rq_iterator *iterator);
971 static int
972 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
973 struct sched_domain *sd, enum cpu_idle_type idle,
974 struct rq_iterator *iterator);
975 #endif
977 #ifdef CONFIG_CGROUP_CPUACCT
978 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
979 #else
980 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
981 #endif
983 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
985 update_load_add(&rq->load, load);
988 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
990 update_load_sub(&rq->load, load);
993 #ifdef CONFIG_SMP
994 static unsigned long source_load(int cpu, int type);
995 static unsigned long target_load(int cpu, int type);
996 static unsigned long cpu_avg_load_per_task(int cpu);
997 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
998 #endif /* CONFIG_SMP */
1000 #include "sched_stats.h"
1001 #include "sched_idletask.c"
1002 #include "sched_fair.c"
1003 #include "sched_rt.c"
1004 #ifdef CONFIG_SCHED_DEBUG
1005 # include "sched_debug.c"
1006 #endif
1008 #define sched_class_highest (&rt_sched_class)
1010 static void inc_nr_running(struct task_struct *p, struct rq *rq)
1012 rq->nr_running++;
1015 static void dec_nr_running(struct task_struct *p, struct rq *rq)
1017 rq->nr_running--;
1020 static void set_load_weight(struct task_struct *p)
1022 if (task_has_rt_policy(p)) {
1023 p->se.load.weight = prio_to_weight[0] * 2;
1024 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1025 return;
1029 * SCHED_IDLE tasks get minimal weight:
1031 if (p->policy == SCHED_IDLE) {
1032 p->se.load.weight = WEIGHT_IDLEPRIO;
1033 p->se.load.inv_weight = WMULT_IDLEPRIO;
1034 return;
1037 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1038 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1041 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1043 sched_info_queued(p);
1044 p->sched_class->enqueue_task(rq, p, wakeup);
1045 p->se.on_rq = 1;
1048 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1050 p->sched_class->dequeue_task(rq, p, sleep);
1051 p->se.on_rq = 0;
1055 * __normal_prio - return the priority that is based on the static prio
1057 static inline int __normal_prio(struct task_struct *p)
1059 return p->static_prio;
1063 * Calculate the expected normal priority: i.e. priority
1064 * without taking RT-inheritance into account. Might be
1065 * boosted by interactivity modifiers. Changes upon fork,
1066 * setprio syscalls, and whenever the interactivity
1067 * estimator recalculates.
1069 static inline int normal_prio(struct task_struct *p)
1071 int prio;
1073 if (task_has_rt_policy(p))
1074 prio = MAX_RT_PRIO-1 - p->rt_priority;
1075 else
1076 prio = __normal_prio(p);
1077 return prio;
1081 * Calculate the current priority, i.e. the priority
1082 * taken into account by the scheduler. This value might
1083 * be boosted by RT tasks, or might be boosted by
1084 * interactivity modifiers. Will be RT if the task got
1085 * RT-boosted. If not then it returns p->normal_prio.
1087 static int effective_prio(struct task_struct *p)
1089 p->normal_prio = normal_prio(p);
1091 * If we are RT tasks or we were boosted to RT priority,
1092 * keep the priority unchanged. Otherwise, update priority
1093 * to the normal priority:
1095 if (!rt_prio(p->prio))
1096 return p->normal_prio;
1097 return p->prio;
1101 * activate_task - move a task to the runqueue.
1103 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1105 if (p->state == TASK_UNINTERRUPTIBLE)
1106 rq->nr_uninterruptible--;
1108 enqueue_task(rq, p, wakeup);
1109 inc_nr_running(p, rq);
1113 * deactivate_task - remove a task from the runqueue.
1115 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1117 if (p->state == TASK_UNINTERRUPTIBLE)
1118 rq->nr_uninterruptible++;
1120 dequeue_task(rq, p, sleep);
1121 dec_nr_running(p, rq);
1125 * task_curr - is this task currently executing on a CPU?
1126 * @p: the task in question.
1128 inline int task_curr(const struct task_struct *p)
1130 return cpu_curr(task_cpu(p)) == p;
1133 /* Used instead of source_load when we know the type == 0 */
1134 unsigned long weighted_cpuload(const int cpu)
1136 return cpu_rq(cpu)->load.weight;
1139 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1141 set_task_cfs_rq(p, cpu);
1142 #ifdef CONFIG_SMP
1144 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1145 * successfuly executed on another CPU. We must ensure that updates of
1146 * per-task data have been completed by this moment.
1148 smp_wmb();
1149 task_thread_info(p)->cpu = cpu;
1150 #endif
1153 #ifdef CONFIG_SMP
1156 * Is this task likely cache-hot:
1158 static int
1159 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1161 s64 delta;
1163 if (p->sched_class != &fair_sched_class)
1164 return 0;
1166 if (sysctl_sched_migration_cost == -1)
1167 return 1;
1168 if (sysctl_sched_migration_cost == 0)
1169 return 0;
1171 delta = now - p->se.exec_start;
1173 return delta < (s64)sysctl_sched_migration_cost;
1177 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1179 int old_cpu = task_cpu(p);
1180 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1181 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1182 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1183 u64 clock_offset;
1185 clock_offset = old_rq->clock - new_rq->clock;
1187 #ifdef CONFIG_SCHEDSTATS
1188 if (p->se.wait_start)
1189 p->se.wait_start -= clock_offset;
1190 if (p->se.sleep_start)
1191 p->se.sleep_start -= clock_offset;
1192 if (p->se.block_start)
1193 p->se.block_start -= clock_offset;
1194 if (old_cpu != new_cpu) {
1195 schedstat_inc(p, se.nr_migrations);
1196 if (task_hot(p, old_rq->clock, NULL))
1197 schedstat_inc(p, se.nr_forced2_migrations);
1199 #endif
1200 p->se.vruntime -= old_cfsrq->min_vruntime -
1201 new_cfsrq->min_vruntime;
1203 __set_task_cpu(p, new_cpu);
1206 struct migration_req {
1207 struct list_head list;
1209 struct task_struct *task;
1210 int dest_cpu;
1212 struct completion done;
1216 * The task's runqueue lock must be held.
1217 * Returns true if you have to wait for migration thread.
1219 static int
1220 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1222 struct rq *rq = task_rq(p);
1225 * If the task is not on a runqueue (and not running), then
1226 * it is sufficient to simply update the task's cpu field.
1228 if (!p->se.on_rq && !task_running(rq, p)) {
1229 set_task_cpu(p, dest_cpu);
1230 return 0;
1233 init_completion(&req->done);
1234 req->task = p;
1235 req->dest_cpu = dest_cpu;
1236 list_add(&req->list, &rq->migration_queue);
1238 return 1;
1242 * wait_task_inactive - wait for a thread to unschedule.
1244 * The caller must ensure that the task *will* unschedule sometime soon,
1245 * else this function might spin for a *long* time. This function can't
1246 * be called with interrupts off, or it may introduce deadlock with
1247 * smp_call_function() if an IPI is sent by the same process we are
1248 * waiting to become inactive.
1250 void wait_task_inactive(struct task_struct *p)
1252 unsigned long flags;
1253 int running, on_rq;
1254 struct rq *rq;
1256 for (;;) {
1258 * We do the initial early heuristics without holding
1259 * any task-queue locks at all. We'll only try to get
1260 * the runqueue lock when things look like they will
1261 * work out!
1263 rq = task_rq(p);
1266 * If the task is actively running on another CPU
1267 * still, just relax and busy-wait without holding
1268 * any locks.
1270 * NOTE! Since we don't hold any locks, it's not
1271 * even sure that "rq" stays as the right runqueue!
1272 * But we don't care, since "task_running()" will
1273 * return false if the runqueue has changed and p
1274 * is actually now running somewhere else!
1276 while (task_running(rq, p))
1277 cpu_relax();
1280 * Ok, time to look more closely! We need the rq
1281 * lock now, to be *sure*. If we're wrong, we'll
1282 * just go back and repeat.
1284 rq = task_rq_lock(p, &flags);
1285 running = task_running(rq, p);
1286 on_rq = p->se.on_rq;
1287 task_rq_unlock(rq, &flags);
1290 * Was it really running after all now that we
1291 * checked with the proper locks actually held?
1293 * Oops. Go back and try again..
1295 if (unlikely(running)) {
1296 cpu_relax();
1297 continue;
1301 * It's not enough that it's not actively running,
1302 * it must be off the runqueue _entirely_, and not
1303 * preempted!
1305 * So if it wa still runnable (but just not actively
1306 * running right now), it's preempted, and we should
1307 * yield - it could be a while.
1309 if (unlikely(on_rq)) {
1310 schedule_timeout_uninterruptible(1);
1311 continue;
1315 * Ahh, all good. It wasn't running, and it wasn't
1316 * runnable, which means that it will never become
1317 * running in the future either. We're all done!
1319 break;
1323 /***
1324 * kick_process - kick a running thread to enter/exit the kernel
1325 * @p: the to-be-kicked thread
1327 * Cause a process which is running on another CPU to enter
1328 * kernel-mode, without any delay. (to get signals handled.)
1330 * NOTE: this function doesnt have to take the runqueue lock,
1331 * because all it wants to ensure is that the remote task enters
1332 * the kernel. If the IPI races and the task has been migrated
1333 * to another CPU then no harm is done and the purpose has been
1334 * achieved as well.
1336 void kick_process(struct task_struct *p)
1338 int cpu;
1340 preempt_disable();
1341 cpu = task_cpu(p);
1342 if ((cpu != smp_processor_id()) && task_curr(p))
1343 smp_send_reschedule(cpu);
1344 preempt_enable();
1348 * Return a low guess at the load of a migration-source cpu weighted
1349 * according to the scheduling class and "nice" value.
1351 * We want to under-estimate the load of migration sources, to
1352 * balance conservatively.
1354 static unsigned long source_load(int cpu, int type)
1356 struct rq *rq = cpu_rq(cpu);
1357 unsigned long total = weighted_cpuload(cpu);
1359 if (type == 0)
1360 return total;
1362 return min(rq->cpu_load[type-1], total);
1366 * Return a high guess at the load of a migration-target cpu weighted
1367 * according to the scheduling class and "nice" value.
1369 static unsigned long target_load(int cpu, int type)
1371 struct rq *rq = cpu_rq(cpu);
1372 unsigned long total = weighted_cpuload(cpu);
1374 if (type == 0)
1375 return total;
1377 return max(rq->cpu_load[type-1], total);
1381 * Return the average load per task on the cpu's run queue
1383 static unsigned long cpu_avg_load_per_task(int cpu)
1385 struct rq *rq = cpu_rq(cpu);
1386 unsigned long total = weighted_cpuload(cpu);
1387 unsigned long n = rq->nr_running;
1389 return n ? total / n : SCHED_LOAD_SCALE;
1393 * find_idlest_group finds and returns the least busy CPU group within the
1394 * domain.
1396 static struct sched_group *
1397 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1399 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1400 unsigned long min_load = ULONG_MAX, this_load = 0;
1401 int load_idx = sd->forkexec_idx;
1402 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1404 do {
1405 unsigned long load, avg_load;
1406 int local_group;
1407 int i;
1409 /* Skip over this group if it has no CPUs allowed */
1410 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1411 continue;
1413 local_group = cpu_isset(this_cpu, group->cpumask);
1415 /* Tally up the load of all CPUs in the group */
1416 avg_load = 0;
1418 for_each_cpu_mask(i, group->cpumask) {
1419 /* Bias balancing toward cpus of our domain */
1420 if (local_group)
1421 load = source_load(i, load_idx);
1422 else
1423 load = target_load(i, load_idx);
1425 avg_load += load;
1428 /* Adjust by relative CPU power of the group */
1429 avg_load = sg_div_cpu_power(group,
1430 avg_load * SCHED_LOAD_SCALE);
1432 if (local_group) {
1433 this_load = avg_load;
1434 this = group;
1435 } else if (avg_load < min_load) {
1436 min_load = avg_load;
1437 idlest = group;
1439 } while (group = group->next, group != sd->groups);
1441 if (!idlest || 100*this_load < imbalance*min_load)
1442 return NULL;
1443 return idlest;
1447 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1449 static int
1450 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1452 cpumask_t tmp;
1453 unsigned long load, min_load = ULONG_MAX;
1454 int idlest = -1;
1455 int i;
1457 /* Traverse only the allowed CPUs */
1458 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1460 for_each_cpu_mask(i, tmp) {
1461 load = weighted_cpuload(i);
1463 if (load < min_load || (load == min_load && i == this_cpu)) {
1464 min_load = load;
1465 idlest = i;
1469 return idlest;
1473 * sched_balance_self: balance the current task (running on cpu) in domains
1474 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1475 * SD_BALANCE_EXEC.
1477 * Balance, ie. select the least loaded group.
1479 * Returns the target CPU number, or the same CPU if no balancing is needed.
1481 * preempt must be disabled.
1483 static int sched_balance_self(int cpu, int flag)
1485 struct task_struct *t = current;
1486 struct sched_domain *tmp, *sd = NULL;
1488 for_each_domain(cpu, tmp) {
1490 * If power savings logic is enabled for a domain, stop there.
1492 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1493 break;
1494 if (tmp->flags & flag)
1495 sd = tmp;
1498 while (sd) {
1499 cpumask_t span;
1500 struct sched_group *group;
1501 int new_cpu, weight;
1503 if (!(sd->flags & flag)) {
1504 sd = sd->child;
1505 continue;
1508 span = sd->span;
1509 group = find_idlest_group(sd, t, cpu);
1510 if (!group) {
1511 sd = sd->child;
1512 continue;
1515 new_cpu = find_idlest_cpu(group, t, cpu);
1516 if (new_cpu == -1 || new_cpu == cpu) {
1517 /* Now try balancing at a lower domain level of cpu */
1518 sd = sd->child;
1519 continue;
1522 /* Now try balancing at a lower domain level of new_cpu */
1523 cpu = new_cpu;
1524 sd = NULL;
1525 weight = cpus_weight(span);
1526 for_each_domain(cpu, tmp) {
1527 if (weight <= cpus_weight(tmp->span))
1528 break;
1529 if (tmp->flags & flag)
1530 sd = tmp;
1532 /* while loop will break here if sd == NULL */
1535 return cpu;
1538 #endif /* CONFIG_SMP */
1540 /***
1541 * try_to_wake_up - wake up a thread
1542 * @p: the to-be-woken-up thread
1543 * @state: the mask of task states that can be woken
1544 * @sync: do a synchronous wakeup?
1546 * Put it on the run-queue if it's not already there. The "current"
1547 * thread is always on the run-queue (except when the actual
1548 * re-schedule is in progress), and as such you're allowed to do
1549 * the simpler "current->state = TASK_RUNNING" to mark yourself
1550 * runnable without the overhead of this.
1552 * returns failure only if the task is already active.
1554 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1556 int cpu, orig_cpu, this_cpu, success = 0;
1557 unsigned long flags;
1558 long old_state;
1559 struct rq *rq;
1560 #ifdef CONFIG_SMP
1561 int new_cpu;
1562 #endif
1564 rq = task_rq_lock(p, &flags);
1565 old_state = p->state;
1566 if (!(old_state & state))
1567 goto out;
1569 if (p->se.on_rq)
1570 goto out_running;
1572 cpu = task_cpu(p);
1573 orig_cpu = cpu;
1574 this_cpu = smp_processor_id();
1576 #ifdef CONFIG_SMP
1577 if (unlikely(task_running(rq, p)))
1578 goto out_activate;
1580 new_cpu = p->sched_class->select_task_rq(p, sync);
1581 if (new_cpu != cpu) {
1582 set_task_cpu(p, new_cpu);
1583 task_rq_unlock(rq, &flags);
1584 /* might preempt at this point */
1585 rq = task_rq_lock(p, &flags);
1586 old_state = p->state;
1587 if (!(old_state & state))
1588 goto out;
1589 if (p->se.on_rq)
1590 goto out_running;
1592 this_cpu = smp_processor_id();
1593 cpu = task_cpu(p);
1596 #ifdef CONFIG_SCHEDSTATS
1597 schedstat_inc(rq, ttwu_count);
1598 if (cpu == this_cpu)
1599 schedstat_inc(rq, ttwu_local);
1600 else {
1601 struct sched_domain *sd;
1602 for_each_domain(this_cpu, sd) {
1603 if (cpu_isset(cpu, sd->span)) {
1604 schedstat_inc(sd, ttwu_wake_remote);
1605 break;
1610 #endif
1613 out_activate:
1614 #endif /* CONFIG_SMP */
1615 schedstat_inc(p, se.nr_wakeups);
1616 if (sync)
1617 schedstat_inc(p, se.nr_wakeups_sync);
1618 if (orig_cpu != cpu)
1619 schedstat_inc(p, se.nr_wakeups_migrate);
1620 if (cpu == this_cpu)
1621 schedstat_inc(p, se.nr_wakeups_local);
1622 else
1623 schedstat_inc(p, se.nr_wakeups_remote);
1624 update_rq_clock(rq);
1625 activate_task(rq, p, 1);
1626 check_preempt_curr(rq, p);
1627 success = 1;
1629 out_running:
1630 p->state = TASK_RUNNING;
1631 wakeup_balance_rt(rq, p);
1632 out:
1633 task_rq_unlock(rq, &flags);
1635 return success;
1638 int fastcall wake_up_process(struct task_struct *p)
1640 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1641 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1643 EXPORT_SYMBOL(wake_up_process);
1645 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1647 return try_to_wake_up(p, state, 0);
1651 * Perform scheduler related setup for a newly forked process p.
1652 * p is forked by current.
1654 * __sched_fork() is basic setup used by init_idle() too:
1656 static void __sched_fork(struct task_struct *p)
1658 p->se.exec_start = 0;
1659 p->se.sum_exec_runtime = 0;
1660 p->se.prev_sum_exec_runtime = 0;
1662 #ifdef CONFIG_SCHEDSTATS
1663 p->se.wait_start = 0;
1664 p->se.sum_sleep_runtime = 0;
1665 p->se.sleep_start = 0;
1666 p->se.block_start = 0;
1667 p->se.sleep_max = 0;
1668 p->se.block_max = 0;
1669 p->se.exec_max = 0;
1670 p->se.slice_max = 0;
1671 p->se.wait_max = 0;
1672 #endif
1674 INIT_LIST_HEAD(&p->run_list);
1675 p->se.on_rq = 0;
1677 #ifdef CONFIG_PREEMPT_NOTIFIERS
1678 INIT_HLIST_HEAD(&p->preempt_notifiers);
1679 #endif
1682 * We mark the process as running here, but have not actually
1683 * inserted it onto the runqueue yet. This guarantees that
1684 * nobody will actually run it, and a signal or other external
1685 * event cannot wake it up and insert it on the runqueue either.
1687 p->state = TASK_RUNNING;
1691 * fork()/clone()-time setup:
1693 void sched_fork(struct task_struct *p, int clone_flags)
1695 int cpu = get_cpu();
1697 __sched_fork(p);
1699 #ifdef CONFIG_SMP
1700 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1701 #endif
1702 set_task_cpu(p, cpu);
1705 * Make sure we do not leak PI boosting priority to the child:
1707 p->prio = current->normal_prio;
1708 if (!rt_prio(p->prio))
1709 p->sched_class = &fair_sched_class;
1711 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1712 if (likely(sched_info_on()))
1713 memset(&p->sched_info, 0, sizeof(p->sched_info));
1714 #endif
1715 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1716 p->oncpu = 0;
1717 #endif
1718 #ifdef CONFIG_PREEMPT
1719 /* Want to start with kernel preemption disabled. */
1720 task_thread_info(p)->preempt_count = 1;
1721 #endif
1722 put_cpu();
1726 * wake_up_new_task - wake up a newly created task for the first time.
1728 * This function will do some initial scheduler statistics housekeeping
1729 * that must be done for every newly created context, then puts the task
1730 * on the runqueue and wakes it.
1732 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1734 unsigned long flags;
1735 struct rq *rq;
1737 rq = task_rq_lock(p, &flags);
1738 BUG_ON(p->state != TASK_RUNNING);
1739 update_rq_clock(rq);
1741 p->prio = effective_prio(p);
1743 if (!p->sched_class->task_new || !current->se.on_rq) {
1744 activate_task(rq, p, 0);
1745 } else {
1747 * Let the scheduling class do new task startup
1748 * management (if any):
1750 p->sched_class->task_new(rq, p);
1751 inc_nr_running(p, rq);
1753 check_preempt_curr(rq, p);
1754 wakeup_balance_rt(rq, p);
1755 task_rq_unlock(rq, &flags);
1758 #ifdef CONFIG_PREEMPT_NOTIFIERS
1761 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
1762 * @notifier: notifier struct to register
1764 void preempt_notifier_register(struct preempt_notifier *notifier)
1766 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1768 EXPORT_SYMBOL_GPL(preempt_notifier_register);
1771 * preempt_notifier_unregister - no longer interested in preemption notifications
1772 * @notifier: notifier struct to unregister
1774 * This is safe to call from within a preemption notifier.
1776 void preempt_notifier_unregister(struct preempt_notifier *notifier)
1778 hlist_del(&notifier->link);
1780 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1782 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1784 struct preempt_notifier *notifier;
1785 struct hlist_node *node;
1787 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1788 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1791 static void
1792 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1793 struct task_struct *next)
1795 struct preempt_notifier *notifier;
1796 struct hlist_node *node;
1798 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1799 notifier->ops->sched_out(notifier, next);
1802 #else
1804 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1808 static void
1809 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1810 struct task_struct *next)
1814 #endif
1817 * prepare_task_switch - prepare to switch tasks
1818 * @rq: the runqueue preparing to switch
1819 * @prev: the current task that is being switched out
1820 * @next: the task we are going to switch to.
1822 * This is called with the rq lock held and interrupts off. It must
1823 * be paired with a subsequent finish_task_switch after the context
1824 * switch.
1826 * prepare_task_switch sets up locking and calls architecture specific
1827 * hooks.
1829 static inline void
1830 prepare_task_switch(struct rq *rq, struct task_struct *prev,
1831 struct task_struct *next)
1833 fire_sched_out_preempt_notifiers(prev, next);
1834 prepare_lock_switch(rq, next);
1835 prepare_arch_switch(next);
1839 * finish_task_switch - clean up after a task-switch
1840 * @rq: runqueue associated with task-switch
1841 * @prev: the thread we just switched away from.
1843 * finish_task_switch must be called after the context switch, paired
1844 * with a prepare_task_switch call before the context switch.
1845 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1846 * and do any other architecture-specific cleanup actions.
1848 * Note that we may have delayed dropping an mm in context_switch(). If
1849 * so, we finish that here outside of the runqueue lock. (Doing it
1850 * with the lock held can cause deadlocks; see schedule() for
1851 * details.)
1853 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
1854 __releases(rq->lock)
1856 struct mm_struct *mm = rq->prev_mm;
1857 long prev_state;
1859 rq->prev_mm = NULL;
1862 * A task struct has one reference for the use as "current".
1863 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
1864 * schedule one last time. The schedule call will never return, and
1865 * the scheduled task must drop that reference.
1866 * The test for TASK_DEAD must occur while the runqueue locks are
1867 * still held, otherwise prev could be scheduled on another cpu, die
1868 * there before we look at prev->state, and then the reference would
1869 * be dropped twice.
1870 * Manfred Spraul <manfred@colorfullife.com>
1872 prev_state = prev->state;
1873 finish_arch_switch(prev);
1874 finish_lock_switch(rq, prev);
1875 schedule_tail_balance_rt(rq);
1877 fire_sched_in_preempt_notifiers(current);
1878 if (mm)
1879 mmdrop(mm);
1880 if (unlikely(prev_state == TASK_DEAD)) {
1882 * Remove function-return probe instances associated with this
1883 * task and put them back on the free list.
1885 kprobe_flush_task(prev);
1886 put_task_struct(prev);
1891 * schedule_tail - first thing a freshly forked thread must call.
1892 * @prev: the thread we just switched away from.
1894 asmlinkage void schedule_tail(struct task_struct *prev)
1895 __releases(rq->lock)
1897 struct rq *rq = this_rq();
1899 finish_task_switch(rq, prev);
1900 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1901 /* In this case, finish_task_switch does not reenable preemption */
1902 preempt_enable();
1903 #endif
1904 if (current->set_child_tid)
1905 put_user(task_pid_vnr(current), current->set_child_tid);
1909 * context_switch - switch to the new MM and the new
1910 * thread's register state.
1912 static inline void
1913 context_switch(struct rq *rq, struct task_struct *prev,
1914 struct task_struct *next)
1916 struct mm_struct *mm, *oldmm;
1918 prepare_task_switch(rq, prev, next);
1919 mm = next->mm;
1920 oldmm = prev->active_mm;
1922 * For paravirt, this is coupled with an exit in switch_to to
1923 * combine the page table reload and the switch backend into
1924 * one hypercall.
1926 arch_enter_lazy_cpu_mode();
1928 if (unlikely(!mm)) {
1929 next->active_mm = oldmm;
1930 atomic_inc(&oldmm->mm_count);
1931 enter_lazy_tlb(oldmm, next);
1932 } else
1933 switch_mm(oldmm, mm, next);
1935 if (unlikely(!prev->mm)) {
1936 prev->active_mm = NULL;
1937 rq->prev_mm = oldmm;
1940 * Since the runqueue lock will be released by the next
1941 * task (which is an invalid locking op but in the case
1942 * of the scheduler it's an obvious special-case), so we
1943 * do an early lockdep release here:
1945 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1946 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1947 #endif
1949 /* Here we just switch the register state and the stack. */
1950 switch_to(prev, next, prev);
1952 barrier();
1954 * this_rq must be evaluated again because prev may have moved
1955 * CPUs since it called schedule(), thus the 'rq' on its stack
1956 * frame will be invalid.
1958 finish_task_switch(this_rq(), prev);
1962 * nr_running, nr_uninterruptible and nr_context_switches:
1964 * externally visible scheduler statistics: current number of runnable
1965 * threads, current number of uninterruptible-sleeping threads, total
1966 * number of context switches performed since bootup.
1968 unsigned long nr_running(void)
1970 unsigned long i, sum = 0;
1972 for_each_online_cpu(i)
1973 sum += cpu_rq(i)->nr_running;
1975 return sum;
1978 unsigned long nr_uninterruptible(void)
1980 unsigned long i, sum = 0;
1982 for_each_possible_cpu(i)
1983 sum += cpu_rq(i)->nr_uninterruptible;
1986 * Since we read the counters lockless, it might be slightly
1987 * inaccurate. Do not allow it to go below zero though:
1989 if (unlikely((long)sum < 0))
1990 sum = 0;
1992 return sum;
1995 unsigned long long nr_context_switches(void)
1997 int i;
1998 unsigned long long sum = 0;
2000 for_each_possible_cpu(i)
2001 sum += cpu_rq(i)->nr_switches;
2003 return sum;
2006 unsigned long nr_iowait(void)
2008 unsigned long i, sum = 0;
2010 for_each_possible_cpu(i)
2011 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2013 return sum;
2016 unsigned long nr_active(void)
2018 unsigned long i, running = 0, uninterruptible = 0;
2020 for_each_online_cpu(i) {
2021 running += cpu_rq(i)->nr_running;
2022 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2025 if (unlikely((long)uninterruptible < 0))
2026 uninterruptible = 0;
2028 return running + uninterruptible;
2032 * Update rq->cpu_load[] statistics. This function is usually called every
2033 * scheduler tick (TICK_NSEC).
2035 static void update_cpu_load(struct rq *this_rq)
2037 unsigned long this_load = this_rq->load.weight;
2038 int i, scale;
2040 this_rq->nr_load_updates++;
2042 /* Update our load: */
2043 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2044 unsigned long old_load, new_load;
2046 /* scale is effectively 1 << i now, and >> i divides by scale */
2048 old_load = this_rq->cpu_load[i];
2049 new_load = this_load;
2051 * Round up the averaging division if load is increasing. This
2052 * prevents us from getting stuck on 9 if the load is 10, for
2053 * example.
2055 if (new_load > old_load)
2056 new_load += scale-1;
2057 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2061 #ifdef CONFIG_SMP
2064 * double_rq_lock - safely lock two runqueues
2066 * Note this does not disable interrupts like task_rq_lock,
2067 * you need to do so manually before calling.
2069 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2070 __acquires(rq1->lock)
2071 __acquires(rq2->lock)
2073 BUG_ON(!irqs_disabled());
2074 if (rq1 == rq2) {
2075 spin_lock(&rq1->lock);
2076 __acquire(rq2->lock); /* Fake it out ;) */
2077 } else {
2078 if (rq1 < rq2) {
2079 spin_lock(&rq1->lock);
2080 spin_lock(&rq2->lock);
2081 } else {
2082 spin_lock(&rq2->lock);
2083 spin_lock(&rq1->lock);
2086 update_rq_clock(rq1);
2087 update_rq_clock(rq2);
2091 * double_rq_unlock - safely unlock two runqueues
2093 * Note this does not restore interrupts like task_rq_unlock,
2094 * you need to do so manually after calling.
2096 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2097 __releases(rq1->lock)
2098 __releases(rq2->lock)
2100 spin_unlock(&rq1->lock);
2101 if (rq1 != rq2)
2102 spin_unlock(&rq2->lock);
2103 else
2104 __release(rq2->lock);
2108 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2110 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2111 __releases(this_rq->lock)
2112 __acquires(busiest->lock)
2113 __acquires(this_rq->lock)
2115 int ret = 0;
2117 if (unlikely(!irqs_disabled())) {
2118 /* printk() doesn't work good under rq->lock */
2119 spin_unlock(&this_rq->lock);
2120 BUG_ON(1);
2122 if (unlikely(!spin_trylock(&busiest->lock))) {
2123 if (busiest < this_rq) {
2124 spin_unlock(&this_rq->lock);
2125 spin_lock(&busiest->lock);
2126 spin_lock(&this_rq->lock);
2127 ret = 1;
2128 } else
2129 spin_lock(&busiest->lock);
2131 return ret;
2135 * If dest_cpu is allowed for this process, migrate the task to it.
2136 * This is accomplished by forcing the cpu_allowed mask to only
2137 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2138 * the cpu_allowed mask is restored.
2140 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2142 struct migration_req req;
2143 unsigned long flags;
2144 struct rq *rq;
2146 rq = task_rq_lock(p, &flags);
2147 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2148 || unlikely(cpu_is_offline(dest_cpu)))
2149 goto out;
2151 /* force the process onto the specified CPU */
2152 if (migrate_task(p, dest_cpu, &req)) {
2153 /* Need to wait for migration thread (might exit: take ref). */
2154 struct task_struct *mt = rq->migration_thread;
2156 get_task_struct(mt);
2157 task_rq_unlock(rq, &flags);
2158 wake_up_process(mt);
2159 put_task_struct(mt);
2160 wait_for_completion(&req.done);
2162 return;
2164 out:
2165 task_rq_unlock(rq, &flags);
2169 * sched_exec - execve() is a valuable balancing opportunity, because at
2170 * this point the task has the smallest effective memory and cache footprint.
2172 void sched_exec(void)
2174 int new_cpu, this_cpu = get_cpu();
2175 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2176 put_cpu();
2177 if (new_cpu != this_cpu)
2178 sched_migrate_task(current, new_cpu);
2182 * pull_task - move a task from a remote runqueue to the local runqueue.
2183 * Both runqueues must be locked.
2185 static void pull_task(struct rq *src_rq, struct task_struct *p,
2186 struct rq *this_rq, int this_cpu)
2188 deactivate_task(src_rq, p, 0);
2189 set_task_cpu(p, this_cpu);
2190 activate_task(this_rq, p, 0);
2192 * Note that idle threads have a prio of MAX_PRIO, for this test
2193 * to be always true for them.
2195 check_preempt_curr(this_rq, p);
2199 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2201 static
2202 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2203 struct sched_domain *sd, enum cpu_idle_type idle,
2204 int *all_pinned)
2207 * We do not migrate tasks that are:
2208 * 1) running (obviously), or
2209 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2210 * 3) are cache-hot on their current CPU.
2212 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2213 schedstat_inc(p, se.nr_failed_migrations_affine);
2214 return 0;
2216 *all_pinned = 0;
2218 if (task_running(rq, p)) {
2219 schedstat_inc(p, se.nr_failed_migrations_running);
2220 return 0;
2224 * Aggressive migration if:
2225 * 1) task is cache cold, or
2226 * 2) too many balance attempts have failed.
2229 if (!task_hot(p, rq->clock, sd) ||
2230 sd->nr_balance_failed > sd->cache_nice_tries) {
2231 #ifdef CONFIG_SCHEDSTATS
2232 if (task_hot(p, rq->clock, sd)) {
2233 schedstat_inc(sd, lb_hot_gained[idle]);
2234 schedstat_inc(p, se.nr_forced_migrations);
2236 #endif
2237 return 1;
2240 if (task_hot(p, rq->clock, sd)) {
2241 schedstat_inc(p, se.nr_failed_migrations_hot);
2242 return 0;
2244 return 1;
2247 static unsigned long
2248 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2249 unsigned long max_load_move, struct sched_domain *sd,
2250 enum cpu_idle_type idle, int *all_pinned,
2251 int *this_best_prio, struct rq_iterator *iterator)
2253 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
2254 struct task_struct *p;
2255 long rem_load_move = max_load_move;
2257 if (max_load_move == 0)
2258 goto out;
2260 pinned = 1;
2263 * Start the load-balancing iterator:
2265 p = iterator->start(iterator->arg);
2266 next:
2267 if (!p || loops++ > sysctl_sched_nr_migrate)
2268 goto out;
2270 * To help distribute high priority tasks across CPUs we don't
2271 * skip a task if it will be the highest priority task (i.e. smallest
2272 * prio value) on its new queue regardless of its load weight
2274 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2275 SCHED_LOAD_SCALE_FUZZ;
2276 if ((skip_for_load && p->prio >= *this_best_prio) ||
2277 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2278 p = iterator->next(iterator->arg);
2279 goto next;
2282 pull_task(busiest, p, this_rq, this_cpu);
2283 pulled++;
2284 rem_load_move -= p->se.load.weight;
2287 * We only want to steal up to the prescribed amount of weighted load.
2289 if (rem_load_move > 0) {
2290 if (p->prio < *this_best_prio)
2291 *this_best_prio = p->prio;
2292 p = iterator->next(iterator->arg);
2293 goto next;
2295 out:
2297 * Right now, this is one of only two places pull_task() is called,
2298 * so we can safely collect pull_task() stats here rather than
2299 * inside pull_task().
2301 schedstat_add(sd, lb_gained[idle], pulled);
2303 if (all_pinned)
2304 *all_pinned = pinned;
2306 return max_load_move - rem_load_move;
2310 * move_tasks tries to move up to max_load_move weighted load from busiest to
2311 * this_rq, as part of a balancing operation within domain "sd".
2312 * Returns 1 if successful and 0 otherwise.
2314 * Called with both runqueues locked.
2316 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2317 unsigned long max_load_move,
2318 struct sched_domain *sd, enum cpu_idle_type idle,
2319 int *all_pinned)
2321 const struct sched_class *class = sched_class_highest;
2322 unsigned long total_load_moved = 0;
2323 int this_best_prio = this_rq->curr->prio;
2325 do {
2326 total_load_moved +=
2327 class->load_balance(this_rq, this_cpu, busiest,
2328 max_load_move - total_load_moved,
2329 sd, idle, all_pinned, &this_best_prio);
2330 class = class->next;
2331 } while (class && max_load_move > total_load_moved);
2333 return total_load_moved > 0;
2336 static int
2337 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2338 struct sched_domain *sd, enum cpu_idle_type idle,
2339 struct rq_iterator *iterator)
2341 struct task_struct *p = iterator->start(iterator->arg);
2342 int pinned = 0;
2344 while (p) {
2345 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2346 pull_task(busiest, p, this_rq, this_cpu);
2348 * Right now, this is only the second place pull_task()
2349 * is called, so we can safely collect pull_task()
2350 * stats here rather than inside pull_task().
2352 schedstat_inc(sd, lb_gained[idle]);
2354 return 1;
2356 p = iterator->next(iterator->arg);
2359 return 0;
2363 * move_one_task tries to move exactly one task from busiest to this_rq, as
2364 * part of active balancing operations within "domain".
2365 * Returns 1 if successful and 0 otherwise.
2367 * Called with both runqueues locked.
2369 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2370 struct sched_domain *sd, enum cpu_idle_type idle)
2372 const struct sched_class *class;
2374 for (class = sched_class_highest; class; class = class->next)
2375 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
2376 return 1;
2378 return 0;
2382 * find_busiest_group finds and returns the busiest CPU group within the
2383 * domain. It calculates and returns the amount of weighted load which
2384 * should be moved to restore balance via the imbalance parameter.
2386 static struct sched_group *
2387 find_busiest_group(struct sched_domain *sd, int this_cpu,
2388 unsigned long *imbalance, enum cpu_idle_type idle,
2389 int *sd_idle, cpumask_t *cpus, int *balance)
2391 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2392 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2393 unsigned long max_pull;
2394 unsigned long busiest_load_per_task, busiest_nr_running;
2395 unsigned long this_load_per_task, this_nr_running;
2396 int load_idx, group_imb = 0;
2397 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2398 int power_savings_balance = 1;
2399 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2400 unsigned long min_nr_running = ULONG_MAX;
2401 struct sched_group *group_min = NULL, *group_leader = NULL;
2402 #endif
2404 max_load = this_load = total_load = total_pwr = 0;
2405 busiest_load_per_task = busiest_nr_running = 0;
2406 this_load_per_task = this_nr_running = 0;
2407 if (idle == CPU_NOT_IDLE)
2408 load_idx = sd->busy_idx;
2409 else if (idle == CPU_NEWLY_IDLE)
2410 load_idx = sd->newidle_idx;
2411 else
2412 load_idx = sd->idle_idx;
2414 do {
2415 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
2416 int local_group;
2417 int i;
2418 int __group_imb = 0;
2419 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2420 unsigned long sum_nr_running, sum_weighted_load;
2422 local_group = cpu_isset(this_cpu, group->cpumask);
2424 if (local_group)
2425 balance_cpu = first_cpu(group->cpumask);
2427 /* Tally up the load of all CPUs in the group */
2428 sum_weighted_load = sum_nr_running = avg_load = 0;
2429 max_cpu_load = 0;
2430 min_cpu_load = ~0UL;
2432 for_each_cpu_mask(i, group->cpumask) {
2433 struct rq *rq;
2435 if (!cpu_isset(i, *cpus))
2436 continue;
2438 rq = cpu_rq(i);
2440 if (*sd_idle && rq->nr_running)
2441 *sd_idle = 0;
2443 /* Bias balancing toward cpus of our domain */
2444 if (local_group) {
2445 if (idle_cpu(i) && !first_idle_cpu) {
2446 first_idle_cpu = 1;
2447 balance_cpu = i;
2450 load = target_load(i, load_idx);
2451 } else {
2452 load = source_load(i, load_idx);
2453 if (load > max_cpu_load)
2454 max_cpu_load = load;
2455 if (min_cpu_load > load)
2456 min_cpu_load = load;
2459 avg_load += load;
2460 sum_nr_running += rq->nr_running;
2461 sum_weighted_load += weighted_cpuload(i);
2465 * First idle cpu or the first cpu(busiest) in this sched group
2466 * is eligible for doing load balancing at this and above
2467 * domains. In the newly idle case, we will allow all the cpu's
2468 * to do the newly idle load balance.
2470 if (idle != CPU_NEWLY_IDLE && local_group &&
2471 balance_cpu != this_cpu && balance) {
2472 *balance = 0;
2473 goto ret;
2476 total_load += avg_load;
2477 total_pwr += group->__cpu_power;
2479 /* Adjust by relative CPU power of the group */
2480 avg_load = sg_div_cpu_power(group,
2481 avg_load * SCHED_LOAD_SCALE);
2483 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2484 __group_imb = 1;
2486 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2488 if (local_group) {
2489 this_load = avg_load;
2490 this = group;
2491 this_nr_running = sum_nr_running;
2492 this_load_per_task = sum_weighted_load;
2493 } else if (avg_load > max_load &&
2494 (sum_nr_running > group_capacity || __group_imb)) {
2495 max_load = avg_load;
2496 busiest = group;
2497 busiest_nr_running = sum_nr_running;
2498 busiest_load_per_task = sum_weighted_load;
2499 group_imb = __group_imb;
2502 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2504 * Busy processors will not participate in power savings
2505 * balance.
2507 if (idle == CPU_NOT_IDLE ||
2508 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2509 goto group_next;
2512 * If the local group is idle or completely loaded
2513 * no need to do power savings balance at this domain
2515 if (local_group && (this_nr_running >= group_capacity ||
2516 !this_nr_running))
2517 power_savings_balance = 0;
2520 * If a group is already running at full capacity or idle,
2521 * don't include that group in power savings calculations
2523 if (!power_savings_balance || sum_nr_running >= group_capacity
2524 || !sum_nr_running)
2525 goto group_next;
2528 * Calculate the group which has the least non-idle load.
2529 * This is the group from where we need to pick up the load
2530 * for saving power
2532 if ((sum_nr_running < min_nr_running) ||
2533 (sum_nr_running == min_nr_running &&
2534 first_cpu(group->cpumask) <
2535 first_cpu(group_min->cpumask))) {
2536 group_min = group;
2537 min_nr_running = sum_nr_running;
2538 min_load_per_task = sum_weighted_load /
2539 sum_nr_running;
2543 * Calculate the group which is almost near its
2544 * capacity but still has some space to pick up some load
2545 * from other group and save more power
2547 if (sum_nr_running <= group_capacity - 1) {
2548 if (sum_nr_running > leader_nr_running ||
2549 (sum_nr_running == leader_nr_running &&
2550 first_cpu(group->cpumask) >
2551 first_cpu(group_leader->cpumask))) {
2552 group_leader = group;
2553 leader_nr_running = sum_nr_running;
2556 group_next:
2557 #endif
2558 group = group->next;
2559 } while (group != sd->groups);
2561 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2562 goto out_balanced;
2564 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2566 if (this_load >= avg_load ||
2567 100*max_load <= sd->imbalance_pct*this_load)
2568 goto out_balanced;
2570 busiest_load_per_task /= busiest_nr_running;
2571 if (group_imb)
2572 busiest_load_per_task = min(busiest_load_per_task, avg_load);
2575 * We're trying to get all the cpus to the average_load, so we don't
2576 * want to push ourselves above the average load, nor do we wish to
2577 * reduce the max loaded cpu below the average load, as either of these
2578 * actions would just result in more rebalancing later, and ping-pong
2579 * tasks around. Thus we look for the minimum possible imbalance.
2580 * Negative imbalances (*we* are more loaded than anyone else) will
2581 * be counted as no imbalance for these purposes -- we can't fix that
2582 * by pulling tasks to us. Be careful of negative numbers as they'll
2583 * appear as very large values with unsigned longs.
2585 if (max_load <= busiest_load_per_task)
2586 goto out_balanced;
2589 * In the presence of smp nice balancing, certain scenarios can have
2590 * max load less than avg load(as we skip the groups at or below
2591 * its cpu_power, while calculating max_load..)
2593 if (max_load < avg_load) {
2594 *imbalance = 0;
2595 goto small_imbalance;
2598 /* Don't want to pull so many tasks that a group would go idle */
2599 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2601 /* How much load to actually move to equalise the imbalance */
2602 *imbalance = min(max_pull * busiest->__cpu_power,
2603 (avg_load - this_load) * this->__cpu_power)
2604 / SCHED_LOAD_SCALE;
2607 * if *imbalance is less than the average load per runnable task
2608 * there is no gaurantee that any tasks will be moved so we'll have
2609 * a think about bumping its value to force at least one task to be
2610 * moved
2612 if (*imbalance < busiest_load_per_task) {
2613 unsigned long tmp, pwr_now, pwr_move;
2614 unsigned int imbn;
2616 small_imbalance:
2617 pwr_move = pwr_now = 0;
2618 imbn = 2;
2619 if (this_nr_running) {
2620 this_load_per_task /= this_nr_running;
2621 if (busiest_load_per_task > this_load_per_task)
2622 imbn = 1;
2623 } else
2624 this_load_per_task = SCHED_LOAD_SCALE;
2626 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2627 busiest_load_per_task * imbn) {
2628 *imbalance = busiest_load_per_task;
2629 return busiest;
2633 * OK, we don't have enough imbalance to justify moving tasks,
2634 * however we may be able to increase total CPU power used by
2635 * moving them.
2638 pwr_now += busiest->__cpu_power *
2639 min(busiest_load_per_task, max_load);
2640 pwr_now += this->__cpu_power *
2641 min(this_load_per_task, this_load);
2642 pwr_now /= SCHED_LOAD_SCALE;
2644 /* Amount of load we'd subtract */
2645 tmp = sg_div_cpu_power(busiest,
2646 busiest_load_per_task * SCHED_LOAD_SCALE);
2647 if (max_load > tmp)
2648 pwr_move += busiest->__cpu_power *
2649 min(busiest_load_per_task, max_load - tmp);
2651 /* Amount of load we'd add */
2652 if (max_load * busiest->__cpu_power <
2653 busiest_load_per_task * SCHED_LOAD_SCALE)
2654 tmp = sg_div_cpu_power(this,
2655 max_load * busiest->__cpu_power);
2656 else
2657 tmp = sg_div_cpu_power(this,
2658 busiest_load_per_task * SCHED_LOAD_SCALE);
2659 pwr_move += this->__cpu_power *
2660 min(this_load_per_task, this_load + tmp);
2661 pwr_move /= SCHED_LOAD_SCALE;
2663 /* Move if we gain throughput */
2664 if (pwr_move > pwr_now)
2665 *imbalance = busiest_load_per_task;
2668 return busiest;
2670 out_balanced:
2671 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2672 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2673 goto ret;
2675 if (this == group_leader && group_leader != group_min) {
2676 *imbalance = min_load_per_task;
2677 return group_min;
2679 #endif
2680 ret:
2681 *imbalance = 0;
2682 return NULL;
2686 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2688 static struct rq *
2689 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
2690 unsigned long imbalance, cpumask_t *cpus)
2692 struct rq *busiest = NULL, *rq;
2693 unsigned long max_load = 0;
2694 int i;
2696 for_each_cpu_mask(i, group->cpumask) {
2697 unsigned long wl;
2699 if (!cpu_isset(i, *cpus))
2700 continue;
2702 rq = cpu_rq(i);
2703 wl = weighted_cpuload(i);
2705 if (rq->nr_running == 1 && wl > imbalance)
2706 continue;
2708 if (wl > max_load) {
2709 max_load = wl;
2710 busiest = rq;
2714 return busiest;
2718 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2719 * so long as it is large enough.
2721 #define MAX_PINNED_INTERVAL 512
2724 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2725 * tasks if there is an imbalance.
2727 static int load_balance(int this_cpu, struct rq *this_rq,
2728 struct sched_domain *sd, enum cpu_idle_type idle,
2729 int *balance)
2731 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2732 struct sched_group *group;
2733 unsigned long imbalance;
2734 struct rq *busiest;
2735 cpumask_t cpus = CPU_MASK_ALL;
2736 unsigned long flags;
2739 * When power savings policy is enabled for the parent domain, idle
2740 * sibling can pick up load irrespective of busy siblings. In this case,
2741 * let the state of idle sibling percolate up as CPU_IDLE, instead of
2742 * portraying it as CPU_NOT_IDLE.
2744 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2745 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2746 sd_idle = 1;
2748 schedstat_inc(sd, lb_count[idle]);
2750 redo:
2751 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
2752 &cpus, balance);
2754 if (*balance == 0)
2755 goto out_balanced;
2757 if (!group) {
2758 schedstat_inc(sd, lb_nobusyg[idle]);
2759 goto out_balanced;
2762 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
2763 if (!busiest) {
2764 schedstat_inc(sd, lb_nobusyq[idle]);
2765 goto out_balanced;
2768 BUG_ON(busiest == this_rq);
2770 schedstat_add(sd, lb_imbalance[idle], imbalance);
2772 ld_moved = 0;
2773 if (busiest->nr_running > 1) {
2775 * Attempt to move tasks. If find_busiest_group has found
2776 * an imbalance but busiest->nr_running <= 1, the group is
2777 * still unbalanced. ld_moved simply stays zero, so it is
2778 * correctly treated as an imbalance.
2780 local_irq_save(flags);
2781 double_rq_lock(this_rq, busiest);
2782 ld_moved = move_tasks(this_rq, this_cpu, busiest,
2783 imbalance, sd, idle, &all_pinned);
2784 double_rq_unlock(this_rq, busiest);
2785 local_irq_restore(flags);
2788 * some other cpu did the load balance for us.
2790 if (ld_moved && this_cpu != smp_processor_id())
2791 resched_cpu(this_cpu);
2793 /* All tasks on this runqueue were pinned by CPU affinity */
2794 if (unlikely(all_pinned)) {
2795 cpu_clear(cpu_of(busiest), cpus);
2796 if (!cpus_empty(cpus))
2797 goto redo;
2798 goto out_balanced;
2802 if (!ld_moved) {
2803 schedstat_inc(sd, lb_failed[idle]);
2804 sd->nr_balance_failed++;
2806 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2808 spin_lock_irqsave(&busiest->lock, flags);
2810 /* don't kick the migration_thread, if the curr
2811 * task on busiest cpu can't be moved to this_cpu
2813 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2814 spin_unlock_irqrestore(&busiest->lock, flags);
2815 all_pinned = 1;
2816 goto out_one_pinned;
2819 if (!busiest->active_balance) {
2820 busiest->active_balance = 1;
2821 busiest->push_cpu = this_cpu;
2822 active_balance = 1;
2824 spin_unlock_irqrestore(&busiest->lock, flags);
2825 if (active_balance)
2826 wake_up_process(busiest->migration_thread);
2829 * We've kicked active balancing, reset the failure
2830 * counter.
2832 sd->nr_balance_failed = sd->cache_nice_tries+1;
2834 } else
2835 sd->nr_balance_failed = 0;
2837 if (likely(!active_balance)) {
2838 /* We were unbalanced, so reset the balancing interval */
2839 sd->balance_interval = sd->min_interval;
2840 } else {
2842 * If we've begun active balancing, start to back off. This
2843 * case may not be covered by the all_pinned logic if there
2844 * is only 1 task on the busy runqueue (because we don't call
2845 * move_tasks).
2847 if (sd->balance_interval < sd->max_interval)
2848 sd->balance_interval *= 2;
2851 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2852 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2853 return -1;
2854 return ld_moved;
2856 out_balanced:
2857 schedstat_inc(sd, lb_balanced[idle]);
2859 sd->nr_balance_failed = 0;
2861 out_one_pinned:
2862 /* tune up the balancing interval */
2863 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2864 (sd->balance_interval < sd->max_interval))
2865 sd->balance_interval *= 2;
2867 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2868 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2869 return -1;
2870 return 0;
2874 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2875 * tasks if there is an imbalance.
2877 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
2878 * this_rq is locked.
2880 static int
2881 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2883 struct sched_group *group;
2884 struct rq *busiest = NULL;
2885 unsigned long imbalance;
2886 int ld_moved = 0;
2887 int sd_idle = 0;
2888 int all_pinned = 0;
2889 cpumask_t cpus = CPU_MASK_ALL;
2892 * When power savings policy is enabled for the parent domain, idle
2893 * sibling can pick up load irrespective of busy siblings. In this case,
2894 * let the state of idle sibling percolate up as IDLE, instead of
2895 * portraying it as CPU_NOT_IDLE.
2897 if (sd->flags & SD_SHARE_CPUPOWER &&
2898 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2899 sd_idle = 1;
2901 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
2902 redo:
2903 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
2904 &sd_idle, &cpus, NULL);
2905 if (!group) {
2906 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
2907 goto out_balanced;
2910 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
2911 &cpus);
2912 if (!busiest) {
2913 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
2914 goto out_balanced;
2917 BUG_ON(busiest == this_rq);
2919 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
2921 ld_moved = 0;
2922 if (busiest->nr_running > 1) {
2923 /* Attempt to move tasks */
2924 double_lock_balance(this_rq, busiest);
2925 /* this_rq->clock is already updated */
2926 update_rq_clock(busiest);
2927 ld_moved = move_tasks(this_rq, this_cpu, busiest,
2928 imbalance, sd, CPU_NEWLY_IDLE,
2929 &all_pinned);
2930 spin_unlock(&busiest->lock);
2932 if (unlikely(all_pinned)) {
2933 cpu_clear(cpu_of(busiest), cpus);
2934 if (!cpus_empty(cpus))
2935 goto redo;
2939 if (!ld_moved) {
2940 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
2941 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2942 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2943 return -1;
2944 } else
2945 sd->nr_balance_failed = 0;
2947 return ld_moved;
2949 out_balanced:
2950 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
2951 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2952 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2953 return -1;
2954 sd->nr_balance_failed = 0;
2956 return 0;
2960 * idle_balance is called by schedule() if this_cpu is about to become
2961 * idle. Attempts to pull tasks from other CPUs.
2963 static void idle_balance(int this_cpu, struct rq *this_rq)
2965 struct sched_domain *sd;
2966 int pulled_task = -1;
2967 unsigned long next_balance = jiffies + HZ;
2969 for_each_domain(this_cpu, sd) {
2970 unsigned long interval;
2972 if (!(sd->flags & SD_LOAD_BALANCE))
2973 continue;
2975 if (sd->flags & SD_BALANCE_NEWIDLE)
2976 /* If we've pulled tasks over stop searching: */
2977 pulled_task = load_balance_newidle(this_cpu,
2978 this_rq, sd);
2980 interval = msecs_to_jiffies(sd->balance_interval);
2981 if (time_after(next_balance, sd->last_balance + interval))
2982 next_balance = sd->last_balance + interval;
2983 if (pulled_task)
2984 break;
2986 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
2988 * We are going idle. next_balance may be set based on
2989 * a busy processor. So reset next_balance.
2991 this_rq->next_balance = next_balance;
2996 * active_load_balance is run by migration threads. It pushes running tasks
2997 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2998 * running on each physical CPU where possible, and avoids physical /
2999 * logical imbalances.
3001 * Called with busiest_rq locked.
3003 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3005 int target_cpu = busiest_rq->push_cpu;
3006 struct sched_domain *sd;
3007 struct rq *target_rq;
3009 /* Is there any task to move? */
3010 if (busiest_rq->nr_running <= 1)
3011 return;
3013 target_rq = cpu_rq(target_cpu);
3016 * This condition is "impossible", if it occurs
3017 * we need to fix it. Originally reported by
3018 * Bjorn Helgaas on a 128-cpu setup.
3020 BUG_ON(busiest_rq == target_rq);
3022 /* move a task from busiest_rq to target_rq */
3023 double_lock_balance(busiest_rq, target_rq);
3024 update_rq_clock(busiest_rq);
3025 update_rq_clock(target_rq);
3027 /* Search for an sd spanning us and the target CPU. */
3028 for_each_domain(target_cpu, sd) {
3029 if ((sd->flags & SD_LOAD_BALANCE) &&
3030 cpu_isset(busiest_cpu, sd->span))
3031 break;
3034 if (likely(sd)) {
3035 schedstat_inc(sd, alb_count);
3037 if (move_one_task(target_rq, target_cpu, busiest_rq,
3038 sd, CPU_IDLE))
3039 schedstat_inc(sd, alb_pushed);
3040 else
3041 schedstat_inc(sd, alb_failed);
3043 spin_unlock(&target_rq->lock);
3046 #ifdef CONFIG_NO_HZ
3047 static struct {
3048 atomic_t load_balancer;
3049 cpumask_t cpu_mask;
3050 } nohz ____cacheline_aligned = {
3051 .load_balancer = ATOMIC_INIT(-1),
3052 .cpu_mask = CPU_MASK_NONE,
3056 * This routine will try to nominate the ilb (idle load balancing)
3057 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3058 * load balancing on behalf of all those cpus. If all the cpus in the system
3059 * go into this tickless mode, then there will be no ilb owner (as there is
3060 * no need for one) and all the cpus will sleep till the next wakeup event
3061 * arrives...
3063 * For the ilb owner, tick is not stopped. And this tick will be used
3064 * for idle load balancing. ilb owner will still be part of
3065 * nohz.cpu_mask..
3067 * While stopping the tick, this cpu will become the ilb owner if there
3068 * is no other owner. And will be the owner till that cpu becomes busy
3069 * or if all cpus in the system stop their ticks at which point
3070 * there is no need for ilb owner.
3072 * When the ilb owner becomes busy, it nominates another owner, during the
3073 * next busy scheduler_tick()
3075 int select_nohz_load_balancer(int stop_tick)
3077 int cpu = smp_processor_id();
3079 if (stop_tick) {
3080 cpu_set(cpu, nohz.cpu_mask);
3081 cpu_rq(cpu)->in_nohz_recently = 1;
3084 * If we are going offline and still the leader, give up!
3086 if (cpu_is_offline(cpu) &&
3087 atomic_read(&nohz.load_balancer) == cpu) {
3088 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3089 BUG();
3090 return 0;
3093 /* time for ilb owner also to sleep */
3094 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3095 if (atomic_read(&nohz.load_balancer) == cpu)
3096 atomic_set(&nohz.load_balancer, -1);
3097 return 0;
3100 if (atomic_read(&nohz.load_balancer) == -1) {
3101 /* make me the ilb owner */
3102 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3103 return 1;
3104 } else if (atomic_read(&nohz.load_balancer) == cpu)
3105 return 1;
3106 } else {
3107 if (!cpu_isset(cpu, nohz.cpu_mask))
3108 return 0;
3110 cpu_clear(cpu, nohz.cpu_mask);
3112 if (atomic_read(&nohz.load_balancer) == cpu)
3113 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3114 BUG();
3116 return 0;
3118 #endif
3120 static DEFINE_SPINLOCK(balancing);
3123 * It checks each scheduling domain to see if it is due to be balanced,
3124 * and initiates a balancing operation if so.
3126 * Balancing parameters are set up in arch_init_sched_domains.
3128 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3130 int balance = 1;
3131 struct rq *rq = cpu_rq(cpu);
3132 unsigned long interval;
3133 struct sched_domain *sd;
3134 /* Earliest time when we have to do rebalance again */
3135 unsigned long next_balance = jiffies + 60*HZ;
3136 int update_next_balance = 0;
3138 for_each_domain(cpu, sd) {
3139 if (!(sd->flags & SD_LOAD_BALANCE))
3140 continue;
3142 interval = sd->balance_interval;
3143 if (idle != CPU_IDLE)
3144 interval *= sd->busy_factor;
3146 /* scale ms to jiffies */
3147 interval = msecs_to_jiffies(interval);
3148 if (unlikely(!interval))
3149 interval = 1;
3150 if (interval > HZ*NR_CPUS/10)
3151 interval = HZ*NR_CPUS/10;
3154 if (sd->flags & SD_SERIALIZE) {
3155 if (!spin_trylock(&balancing))
3156 goto out;
3159 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3160 if (load_balance(cpu, rq, sd, idle, &balance)) {
3162 * We've pulled tasks over so either we're no
3163 * longer idle, or one of our SMT siblings is
3164 * not idle.
3166 idle = CPU_NOT_IDLE;
3168 sd->last_balance = jiffies;
3170 if (sd->flags & SD_SERIALIZE)
3171 spin_unlock(&balancing);
3172 out:
3173 if (time_after(next_balance, sd->last_balance + interval)) {
3174 next_balance = sd->last_balance + interval;
3175 update_next_balance = 1;
3179 * Stop the load balance at this level. There is another
3180 * CPU in our sched group which is doing load balancing more
3181 * actively.
3183 if (!balance)
3184 break;
3188 * next_balance will be updated only when there is a need.
3189 * When the cpu is attached to null domain for ex, it will not be
3190 * updated.
3192 if (likely(update_next_balance))
3193 rq->next_balance = next_balance;
3197 * run_rebalance_domains is triggered when needed from the scheduler tick.
3198 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3199 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3201 static void run_rebalance_domains(struct softirq_action *h)
3203 int this_cpu = smp_processor_id();
3204 struct rq *this_rq = cpu_rq(this_cpu);
3205 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3206 CPU_IDLE : CPU_NOT_IDLE;
3208 rebalance_domains(this_cpu, idle);
3210 #ifdef CONFIG_NO_HZ
3212 * If this cpu is the owner for idle load balancing, then do the
3213 * balancing on behalf of the other idle cpus whose ticks are
3214 * stopped.
3216 if (this_rq->idle_at_tick &&
3217 atomic_read(&nohz.load_balancer) == this_cpu) {
3218 cpumask_t cpus = nohz.cpu_mask;
3219 struct rq *rq;
3220 int balance_cpu;
3222 cpu_clear(this_cpu, cpus);
3223 for_each_cpu_mask(balance_cpu, cpus) {
3225 * If this cpu gets work to do, stop the load balancing
3226 * work being done for other cpus. Next load
3227 * balancing owner will pick it up.
3229 if (need_resched())
3230 break;
3232 rebalance_domains(balance_cpu, CPU_IDLE);
3234 rq = cpu_rq(balance_cpu);
3235 if (time_after(this_rq->next_balance, rq->next_balance))
3236 this_rq->next_balance = rq->next_balance;
3239 #endif
3243 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3245 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3246 * idle load balancing owner or decide to stop the periodic load balancing,
3247 * if the whole system is idle.
3249 static inline void trigger_load_balance(struct rq *rq, int cpu)
3251 #ifdef CONFIG_NO_HZ
3253 * If we were in the nohz mode recently and busy at the current
3254 * scheduler tick, then check if we need to nominate new idle
3255 * load balancer.
3257 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3258 rq->in_nohz_recently = 0;
3260 if (atomic_read(&nohz.load_balancer) == cpu) {
3261 cpu_clear(cpu, nohz.cpu_mask);
3262 atomic_set(&nohz.load_balancer, -1);
3265 if (atomic_read(&nohz.load_balancer) == -1) {
3267 * simple selection for now: Nominate the
3268 * first cpu in the nohz list to be the next
3269 * ilb owner.
3271 * TBD: Traverse the sched domains and nominate
3272 * the nearest cpu in the nohz.cpu_mask.
3274 int ilb = first_cpu(nohz.cpu_mask);
3276 if (ilb != NR_CPUS)
3277 resched_cpu(ilb);
3282 * If this cpu is idle and doing idle load balancing for all the
3283 * cpus with ticks stopped, is it time for that to stop?
3285 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3286 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3287 resched_cpu(cpu);
3288 return;
3292 * If this cpu is idle and the idle load balancing is done by
3293 * someone else, then no need raise the SCHED_SOFTIRQ
3295 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3296 cpu_isset(cpu, nohz.cpu_mask))
3297 return;
3298 #endif
3299 if (time_after_eq(jiffies, rq->next_balance))
3300 raise_softirq(SCHED_SOFTIRQ);
3303 #else /* CONFIG_SMP */
3306 * on UP we do not need to balance between CPUs:
3308 static inline void idle_balance(int cpu, struct rq *rq)
3312 #endif
3314 DEFINE_PER_CPU(struct kernel_stat, kstat);
3316 EXPORT_PER_CPU_SYMBOL(kstat);
3319 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3320 * that have not yet been banked in case the task is currently running.
3322 unsigned long long task_sched_runtime(struct task_struct *p)
3324 unsigned long flags;
3325 u64 ns, delta_exec;
3326 struct rq *rq;
3328 rq = task_rq_lock(p, &flags);
3329 ns = p->se.sum_exec_runtime;
3330 if (task_current(rq, p)) {
3331 update_rq_clock(rq);
3332 delta_exec = rq->clock - p->se.exec_start;
3333 if ((s64)delta_exec > 0)
3334 ns += delta_exec;
3336 task_rq_unlock(rq, &flags);
3338 return ns;
3342 * Account user cpu time to a process.
3343 * @p: the process that the cpu time gets accounted to
3344 * @cputime: the cpu time spent in user space since the last update
3346 void account_user_time(struct task_struct *p, cputime_t cputime)
3348 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3349 cputime64_t tmp;
3351 p->utime = cputime_add(p->utime, cputime);
3353 /* Add user time to cpustat. */
3354 tmp = cputime_to_cputime64(cputime);
3355 if (TASK_NICE(p) > 0)
3356 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3357 else
3358 cpustat->user = cputime64_add(cpustat->user, tmp);
3362 * Account guest cpu time to a process.
3363 * @p: the process that the cpu time gets accounted to
3364 * @cputime: the cpu time spent in virtual machine since the last update
3366 static void account_guest_time(struct task_struct *p, cputime_t cputime)
3368 cputime64_t tmp;
3369 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3371 tmp = cputime_to_cputime64(cputime);
3373 p->utime = cputime_add(p->utime, cputime);
3374 p->gtime = cputime_add(p->gtime, cputime);
3376 cpustat->user = cputime64_add(cpustat->user, tmp);
3377 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3381 * Account scaled user cpu time to a process.
3382 * @p: the process that the cpu time gets accounted to
3383 * @cputime: the cpu time spent in user space since the last update
3385 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3387 p->utimescaled = cputime_add(p->utimescaled, cputime);
3391 * Account system cpu time to a process.
3392 * @p: the process that the cpu time gets accounted to
3393 * @hardirq_offset: the offset to subtract from hardirq_count()
3394 * @cputime: the cpu time spent in kernel space since the last update
3396 void account_system_time(struct task_struct *p, int hardirq_offset,
3397 cputime_t cputime)
3399 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3400 struct rq *rq = this_rq();
3401 cputime64_t tmp;
3403 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3404 return account_guest_time(p, cputime);
3406 p->stime = cputime_add(p->stime, cputime);
3408 /* Add system time to cpustat. */
3409 tmp = cputime_to_cputime64(cputime);
3410 if (hardirq_count() - hardirq_offset)
3411 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3412 else if (softirq_count())
3413 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3414 else if (p != rq->idle)
3415 cpustat->system = cputime64_add(cpustat->system, tmp);
3416 else if (atomic_read(&rq->nr_iowait) > 0)
3417 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3418 else
3419 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3420 /* Account for system time used */
3421 acct_update_integrals(p);
3425 * Account scaled system cpu time to a process.
3426 * @p: the process that the cpu time gets accounted to
3427 * @hardirq_offset: the offset to subtract from hardirq_count()
3428 * @cputime: the cpu time spent in kernel space since the last update
3430 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3432 p->stimescaled = cputime_add(p->stimescaled, cputime);
3436 * Account for involuntary wait time.
3437 * @p: the process from which the cpu time has been stolen
3438 * @steal: the cpu time spent in involuntary wait
3440 void account_steal_time(struct task_struct *p, cputime_t steal)
3442 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3443 cputime64_t tmp = cputime_to_cputime64(steal);
3444 struct rq *rq = this_rq();
3446 if (p == rq->idle) {
3447 p->stime = cputime_add(p->stime, steal);
3448 if (atomic_read(&rq->nr_iowait) > 0)
3449 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3450 else
3451 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3452 } else
3453 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3457 * This function gets called by the timer code, with HZ frequency.
3458 * We call it with interrupts disabled.
3460 * It also gets called by the fork code, when changing the parent's
3461 * timeslices.
3463 void scheduler_tick(void)
3465 int cpu = smp_processor_id();
3466 struct rq *rq = cpu_rq(cpu);
3467 struct task_struct *curr = rq->curr;
3468 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3470 spin_lock(&rq->lock);
3471 __update_rq_clock(rq);
3473 * Let rq->clock advance by at least TICK_NSEC:
3475 if (unlikely(rq->clock < next_tick))
3476 rq->clock = next_tick;
3477 rq->tick_timestamp = rq->clock;
3478 update_cpu_load(rq);
3479 if (curr != rq->idle) /* FIXME: needed? */
3480 curr->sched_class->task_tick(rq, curr);
3481 spin_unlock(&rq->lock);
3483 #ifdef CONFIG_SMP
3484 rq->idle_at_tick = idle_cpu(cpu);
3485 trigger_load_balance(rq, cpu);
3486 #endif
3489 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3491 void fastcall add_preempt_count(int val)
3494 * Underflow?
3496 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3497 return;
3498 preempt_count() += val;
3500 * Spinlock count overflowing soon?
3502 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3503 PREEMPT_MASK - 10);
3505 EXPORT_SYMBOL(add_preempt_count);
3507 void fastcall sub_preempt_count(int val)
3510 * Underflow?
3512 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3513 return;
3515 * Is the spinlock portion underflowing?
3517 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3518 !(preempt_count() & PREEMPT_MASK)))
3519 return;
3521 preempt_count() -= val;
3523 EXPORT_SYMBOL(sub_preempt_count);
3525 #endif
3528 * Print scheduling while atomic bug:
3530 static noinline void __schedule_bug(struct task_struct *prev)
3532 struct pt_regs *regs = get_irq_regs();
3534 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3535 prev->comm, prev->pid, preempt_count());
3537 debug_show_held_locks(prev);
3538 if (irqs_disabled())
3539 print_irqtrace_events(prev);
3541 if (regs)
3542 show_regs(regs);
3543 else
3544 dump_stack();
3548 * Various schedule()-time debugging checks and statistics:
3550 static inline void schedule_debug(struct task_struct *prev)
3553 * Test if we are atomic. Since do_exit() needs to call into
3554 * schedule() atomically, we ignore that path for now.
3555 * Otherwise, whine if we are scheduling when we should not be.
3557 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3558 __schedule_bug(prev);
3560 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3562 schedstat_inc(this_rq(), sched_count);
3563 #ifdef CONFIG_SCHEDSTATS
3564 if (unlikely(prev->lock_depth >= 0)) {
3565 schedstat_inc(this_rq(), bkl_count);
3566 schedstat_inc(prev, sched_info.bkl_count);
3568 #endif
3572 * Pick up the highest-prio task:
3574 static inline struct task_struct *
3575 pick_next_task(struct rq *rq, struct task_struct *prev)
3577 const struct sched_class *class;
3578 struct task_struct *p;
3581 * Optimization: we know that if all tasks are in
3582 * the fair class we can call that function directly:
3584 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3585 p = fair_sched_class.pick_next_task(rq);
3586 if (likely(p))
3587 return p;
3590 class = sched_class_highest;
3591 for ( ; ; ) {
3592 p = class->pick_next_task(rq);
3593 if (p)
3594 return p;
3596 * Will never be NULL as the idle class always
3597 * returns a non-NULL p:
3599 class = class->next;
3604 * schedule() is the main scheduler function.
3606 asmlinkage void __sched schedule(void)
3608 struct task_struct *prev, *next;
3609 long *switch_count;
3610 struct rq *rq;
3611 int cpu;
3613 need_resched:
3614 preempt_disable();
3615 cpu = smp_processor_id();
3616 rq = cpu_rq(cpu);
3617 rcu_qsctr_inc(cpu);
3618 prev = rq->curr;
3619 switch_count = &prev->nivcsw;
3621 release_kernel_lock(prev);
3622 need_resched_nonpreemptible:
3624 schedule_debug(prev);
3627 * Do the rq-clock update outside the rq lock:
3629 local_irq_disable();
3630 __update_rq_clock(rq);
3631 spin_lock(&rq->lock);
3632 clear_tsk_need_resched(prev);
3634 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3635 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3636 unlikely(signal_pending(prev)))) {
3637 prev->state = TASK_RUNNING;
3638 } else {
3639 deactivate_task(rq, prev, 1);
3641 switch_count = &prev->nvcsw;
3644 schedule_balance_rt(rq, prev);
3646 if (unlikely(!rq->nr_running))
3647 idle_balance(cpu, rq);
3649 prev->sched_class->put_prev_task(rq, prev);
3650 next = pick_next_task(rq, prev);
3652 sched_info_switch(prev, next);
3654 if (likely(prev != next)) {
3655 rq->nr_switches++;
3656 rq->curr = next;
3657 ++*switch_count;
3659 context_switch(rq, prev, next); /* unlocks the rq */
3660 } else
3661 spin_unlock_irq(&rq->lock);
3663 if (unlikely(reacquire_kernel_lock(current) < 0)) {
3664 cpu = smp_processor_id();
3665 rq = cpu_rq(cpu);
3666 goto need_resched_nonpreemptible;
3668 preempt_enable_no_resched();
3669 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3670 goto need_resched;
3672 EXPORT_SYMBOL(schedule);
3674 #ifdef CONFIG_PREEMPT
3676 * this is the entry point to schedule() from in-kernel preemption
3677 * off of preempt_enable. Kernel preemptions off return from interrupt
3678 * occur there and call schedule directly.
3680 asmlinkage void __sched preempt_schedule(void)
3682 struct thread_info *ti = current_thread_info();
3683 #ifdef CONFIG_PREEMPT_BKL
3684 struct task_struct *task = current;
3685 int saved_lock_depth;
3686 #endif
3688 * If there is a non-zero preempt_count or interrupts are disabled,
3689 * we do not want to preempt the current task. Just return..
3691 if (likely(ti->preempt_count || irqs_disabled()))
3692 return;
3694 do {
3695 add_preempt_count(PREEMPT_ACTIVE);
3698 * We keep the big kernel semaphore locked, but we
3699 * clear ->lock_depth so that schedule() doesnt
3700 * auto-release the semaphore:
3702 #ifdef CONFIG_PREEMPT_BKL
3703 saved_lock_depth = task->lock_depth;
3704 task->lock_depth = -1;
3705 #endif
3706 schedule();
3707 #ifdef CONFIG_PREEMPT_BKL
3708 task->lock_depth = saved_lock_depth;
3709 #endif
3710 sub_preempt_count(PREEMPT_ACTIVE);
3713 * Check again in case we missed a preemption opportunity
3714 * between schedule and now.
3716 barrier();
3717 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
3719 EXPORT_SYMBOL(preempt_schedule);
3722 * this is the entry point to schedule() from kernel preemption
3723 * off of irq context.
3724 * Note, that this is called and return with irqs disabled. This will
3725 * protect us against recursive calling from irq.
3727 asmlinkage void __sched preempt_schedule_irq(void)
3729 struct thread_info *ti = current_thread_info();
3730 #ifdef CONFIG_PREEMPT_BKL
3731 struct task_struct *task = current;
3732 int saved_lock_depth;
3733 #endif
3734 /* Catch callers which need to be fixed */
3735 BUG_ON(ti->preempt_count || !irqs_disabled());
3737 do {
3738 add_preempt_count(PREEMPT_ACTIVE);
3741 * We keep the big kernel semaphore locked, but we
3742 * clear ->lock_depth so that schedule() doesnt
3743 * auto-release the semaphore:
3745 #ifdef CONFIG_PREEMPT_BKL
3746 saved_lock_depth = task->lock_depth;
3747 task->lock_depth = -1;
3748 #endif
3749 local_irq_enable();
3750 schedule();
3751 local_irq_disable();
3752 #ifdef CONFIG_PREEMPT_BKL
3753 task->lock_depth = saved_lock_depth;
3754 #endif
3755 sub_preempt_count(PREEMPT_ACTIVE);
3758 * Check again in case we missed a preemption opportunity
3759 * between schedule and now.
3761 barrier();
3762 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
3765 #endif /* CONFIG_PREEMPT */
3767 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3768 void *key)
3770 return try_to_wake_up(curr->private, mode, sync);
3772 EXPORT_SYMBOL(default_wake_function);
3775 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3776 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3777 * number) then we wake all the non-exclusive tasks and one exclusive task.
3779 * There are circumstances in which we can try to wake a task which has already
3780 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3781 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3783 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3784 int nr_exclusive, int sync, void *key)
3786 wait_queue_t *curr, *next;
3788 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3789 unsigned flags = curr->flags;
3791 if (curr->func(curr, mode, sync, key) &&
3792 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3793 break;
3798 * __wake_up - wake up threads blocked on a waitqueue.
3799 * @q: the waitqueue
3800 * @mode: which threads
3801 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3802 * @key: is directly passed to the wakeup function
3804 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3805 int nr_exclusive, void *key)
3807 unsigned long flags;
3809 spin_lock_irqsave(&q->lock, flags);
3810 __wake_up_common(q, mode, nr_exclusive, 0, key);
3811 spin_unlock_irqrestore(&q->lock, flags);
3813 EXPORT_SYMBOL(__wake_up);
3816 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3818 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3820 __wake_up_common(q, mode, 1, 0, NULL);
3824 * __wake_up_sync - wake up threads blocked on a waitqueue.
3825 * @q: the waitqueue
3826 * @mode: which threads
3827 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3829 * The sync wakeup differs that the waker knows that it will schedule
3830 * away soon, so while the target thread will be woken up, it will not
3831 * be migrated to another CPU - ie. the two threads are 'synchronized'
3832 * with each other. This can prevent needless bouncing between CPUs.
3834 * On UP it can prevent extra preemption.
3836 void fastcall
3837 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3839 unsigned long flags;
3840 int sync = 1;
3842 if (unlikely(!q))
3843 return;
3845 if (unlikely(!nr_exclusive))
3846 sync = 0;
3848 spin_lock_irqsave(&q->lock, flags);
3849 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3850 spin_unlock_irqrestore(&q->lock, flags);
3852 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3854 void complete(struct completion *x)
3856 unsigned long flags;
3858 spin_lock_irqsave(&x->wait.lock, flags);
3859 x->done++;
3860 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3861 1, 0, NULL);
3862 spin_unlock_irqrestore(&x->wait.lock, flags);
3864 EXPORT_SYMBOL(complete);
3866 void complete_all(struct completion *x)
3868 unsigned long flags;
3870 spin_lock_irqsave(&x->wait.lock, flags);
3871 x->done += UINT_MAX/2;
3872 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3873 0, 0, NULL);
3874 spin_unlock_irqrestore(&x->wait.lock, flags);
3876 EXPORT_SYMBOL(complete_all);
3878 static inline long __sched
3879 do_wait_for_common(struct completion *x, long timeout, int state)
3881 if (!x->done) {
3882 DECLARE_WAITQUEUE(wait, current);
3884 wait.flags |= WQ_FLAG_EXCLUSIVE;
3885 __add_wait_queue_tail(&x->wait, &wait);
3886 do {
3887 if (state == TASK_INTERRUPTIBLE &&
3888 signal_pending(current)) {
3889 __remove_wait_queue(&x->wait, &wait);
3890 return -ERESTARTSYS;
3892 __set_current_state(state);
3893 spin_unlock_irq(&x->wait.lock);
3894 timeout = schedule_timeout(timeout);
3895 spin_lock_irq(&x->wait.lock);
3896 if (!timeout) {
3897 __remove_wait_queue(&x->wait, &wait);
3898 return timeout;
3900 } while (!x->done);
3901 __remove_wait_queue(&x->wait, &wait);
3903 x->done--;
3904 return timeout;
3907 static long __sched
3908 wait_for_common(struct completion *x, long timeout, int state)
3910 might_sleep();
3912 spin_lock_irq(&x->wait.lock);
3913 timeout = do_wait_for_common(x, timeout, state);
3914 spin_unlock_irq(&x->wait.lock);
3915 return timeout;
3918 void __sched wait_for_completion(struct completion *x)
3920 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
3922 EXPORT_SYMBOL(wait_for_completion);
3924 unsigned long __sched
3925 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3927 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
3929 EXPORT_SYMBOL(wait_for_completion_timeout);
3931 int __sched wait_for_completion_interruptible(struct completion *x)
3933 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
3934 if (t == -ERESTARTSYS)
3935 return t;
3936 return 0;
3938 EXPORT_SYMBOL(wait_for_completion_interruptible);
3940 unsigned long __sched
3941 wait_for_completion_interruptible_timeout(struct completion *x,
3942 unsigned long timeout)
3944 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
3946 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3948 static long __sched
3949 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
3951 unsigned long flags;
3952 wait_queue_t wait;
3954 init_waitqueue_entry(&wait, current);
3956 __set_current_state(state);
3958 spin_lock_irqsave(&q->lock, flags);
3959 __add_wait_queue(q, &wait);
3960 spin_unlock(&q->lock);
3961 timeout = schedule_timeout(timeout);
3962 spin_lock_irq(&q->lock);
3963 __remove_wait_queue(q, &wait);
3964 spin_unlock_irqrestore(&q->lock, flags);
3966 return timeout;
3969 void __sched interruptible_sleep_on(wait_queue_head_t *q)
3971 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
3973 EXPORT_SYMBOL(interruptible_sleep_on);
3975 long __sched
3976 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3978 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
3980 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3982 void __sched sleep_on(wait_queue_head_t *q)
3984 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
3986 EXPORT_SYMBOL(sleep_on);
3988 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3990 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
3992 EXPORT_SYMBOL(sleep_on_timeout);
3994 #ifdef CONFIG_RT_MUTEXES
3997 * rt_mutex_setprio - set the current priority of a task
3998 * @p: task
3999 * @prio: prio value (kernel-internal form)
4001 * This function changes the 'effective' priority of a task. It does
4002 * not touch ->normal_prio like __setscheduler().
4004 * Used by the rt_mutex code to implement priority inheritance logic.
4006 void rt_mutex_setprio(struct task_struct *p, int prio)
4008 unsigned long flags;
4009 int oldprio, on_rq, running;
4010 struct rq *rq;
4012 BUG_ON(prio < 0 || prio > MAX_PRIO);
4014 rq = task_rq_lock(p, &flags);
4015 update_rq_clock(rq);
4017 oldprio = p->prio;
4018 on_rq = p->se.on_rq;
4019 running = task_current(rq, p);
4020 if (on_rq) {
4021 dequeue_task(rq, p, 0);
4022 if (running)
4023 p->sched_class->put_prev_task(rq, p);
4026 if (rt_prio(prio))
4027 p->sched_class = &rt_sched_class;
4028 else
4029 p->sched_class = &fair_sched_class;
4031 p->prio = prio;
4033 if (on_rq) {
4034 if (running)
4035 p->sched_class->set_curr_task(rq);
4036 enqueue_task(rq, p, 0);
4038 * Reschedule if we are currently running on this runqueue and
4039 * our priority decreased, or if we are not currently running on
4040 * this runqueue and our priority is higher than the current's
4042 if (running) {
4043 if (p->prio > oldprio)
4044 resched_task(rq->curr);
4045 } else {
4046 check_preempt_curr(rq, p);
4049 task_rq_unlock(rq, &flags);
4052 #endif
4054 void set_user_nice(struct task_struct *p, long nice)
4056 int old_prio, delta, on_rq;
4057 unsigned long flags;
4058 struct rq *rq;
4060 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4061 return;
4063 * We have to be careful, if called from sys_setpriority(),
4064 * the task might be in the middle of scheduling on another CPU.
4066 rq = task_rq_lock(p, &flags);
4067 update_rq_clock(rq);
4069 * The RT priorities are set via sched_setscheduler(), but we still
4070 * allow the 'normal' nice value to be set - but as expected
4071 * it wont have any effect on scheduling until the task is
4072 * SCHED_FIFO/SCHED_RR:
4074 if (task_has_rt_policy(p)) {
4075 p->static_prio = NICE_TO_PRIO(nice);
4076 goto out_unlock;
4078 on_rq = p->se.on_rq;
4079 if (on_rq)
4080 dequeue_task(rq, p, 0);
4082 p->static_prio = NICE_TO_PRIO(nice);
4083 set_load_weight(p);
4084 old_prio = p->prio;
4085 p->prio = effective_prio(p);
4086 delta = p->prio - old_prio;
4088 if (on_rq) {
4089 enqueue_task(rq, p, 0);
4091 * If the task increased its priority or is running and
4092 * lowered its priority, then reschedule its CPU:
4094 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4095 resched_task(rq->curr);
4097 out_unlock:
4098 task_rq_unlock(rq, &flags);
4100 EXPORT_SYMBOL(set_user_nice);
4103 * can_nice - check if a task can reduce its nice value
4104 * @p: task
4105 * @nice: nice value
4107 int can_nice(const struct task_struct *p, const int nice)
4109 /* convert nice value [19,-20] to rlimit style value [1,40] */
4110 int nice_rlim = 20 - nice;
4112 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4113 capable(CAP_SYS_NICE));
4116 #ifdef __ARCH_WANT_SYS_NICE
4119 * sys_nice - change the priority of the current process.
4120 * @increment: priority increment
4122 * sys_setpriority is a more generic, but much slower function that
4123 * does similar things.
4125 asmlinkage long sys_nice(int increment)
4127 long nice, retval;
4130 * Setpriority might change our priority at the same moment.
4131 * We don't have to worry. Conceptually one call occurs first
4132 * and we have a single winner.
4134 if (increment < -40)
4135 increment = -40;
4136 if (increment > 40)
4137 increment = 40;
4139 nice = PRIO_TO_NICE(current->static_prio) + increment;
4140 if (nice < -20)
4141 nice = -20;
4142 if (nice > 19)
4143 nice = 19;
4145 if (increment < 0 && !can_nice(current, nice))
4146 return -EPERM;
4148 retval = security_task_setnice(current, nice);
4149 if (retval)
4150 return retval;
4152 set_user_nice(current, nice);
4153 return 0;
4156 #endif
4159 * task_prio - return the priority value of a given task.
4160 * @p: the task in question.
4162 * This is the priority value as seen by users in /proc.
4163 * RT tasks are offset by -200. Normal tasks are centered
4164 * around 0, value goes from -16 to +15.
4166 int task_prio(const struct task_struct *p)
4168 return p->prio - MAX_RT_PRIO;
4172 * task_nice - return the nice value of a given task.
4173 * @p: the task in question.
4175 int task_nice(const struct task_struct *p)
4177 return TASK_NICE(p);
4179 EXPORT_SYMBOL_GPL(task_nice);
4182 * idle_cpu - is a given cpu idle currently?
4183 * @cpu: the processor in question.
4185 int idle_cpu(int cpu)
4187 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4191 * idle_task - return the idle task for a given cpu.
4192 * @cpu: the processor in question.
4194 struct task_struct *idle_task(int cpu)
4196 return cpu_rq(cpu)->idle;
4200 * find_process_by_pid - find a process with a matching PID value.
4201 * @pid: the pid in question.
4203 static struct task_struct *find_process_by_pid(pid_t pid)
4205 return pid ? find_task_by_vpid(pid) : current;
4208 /* Actually do priority change: must hold rq lock. */
4209 static void
4210 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4212 BUG_ON(p->se.on_rq);
4214 p->policy = policy;
4215 switch (p->policy) {
4216 case SCHED_NORMAL:
4217 case SCHED_BATCH:
4218 case SCHED_IDLE:
4219 p->sched_class = &fair_sched_class;
4220 break;
4221 case SCHED_FIFO:
4222 case SCHED_RR:
4223 p->sched_class = &rt_sched_class;
4224 break;
4227 p->rt_priority = prio;
4228 p->normal_prio = normal_prio(p);
4229 /* we are holding p->pi_lock already */
4230 p->prio = rt_mutex_getprio(p);
4231 set_load_weight(p);
4235 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4236 * @p: the task in question.
4237 * @policy: new policy.
4238 * @param: structure containing the new RT priority.
4240 * NOTE that the task may be already dead.
4242 int sched_setscheduler(struct task_struct *p, int policy,
4243 struct sched_param *param)
4245 int retval, oldprio, oldpolicy = -1, on_rq, running;
4246 unsigned long flags;
4247 struct rq *rq;
4249 /* may grab non-irq protected spin_locks */
4250 BUG_ON(in_interrupt());
4251 recheck:
4252 /* double check policy once rq lock held */
4253 if (policy < 0)
4254 policy = oldpolicy = p->policy;
4255 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4256 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4257 policy != SCHED_IDLE)
4258 return -EINVAL;
4260 * Valid priorities for SCHED_FIFO and SCHED_RR are
4261 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4262 * SCHED_BATCH and SCHED_IDLE is 0.
4264 if (param->sched_priority < 0 ||
4265 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4266 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4267 return -EINVAL;
4268 if (rt_policy(policy) != (param->sched_priority != 0))
4269 return -EINVAL;
4272 * Allow unprivileged RT tasks to decrease priority:
4274 if (!capable(CAP_SYS_NICE)) {
4275 if (rt_policy(policy)) {
4276 unsigned long rlim_rtprio;
4278 if (!lock_task_sighand(p, &flags))
4279 return -ESRCH;
4280 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4281 unlock_task_sighand(p, &flags);
4283 /* can't set/change the rt policy */
4284 if (policy != p->policy && !rlim_rtprio)
4285 return -EPERM;
4287 /* can't increase priority */
4288 if (param->sched_priority > p->rt_priority &&
4289 param->sched_priority > rlim_rtprio)
4290 return -EPERM;
4293 * Like positive nice levels, dont allow tasks to
4294 * move out of SCHED_IDLE either:
4296 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4297 return -EPERM;
4299 /* can't change other user's priorities */
4300 if ((current->euid != p->euid) &&
4301 (current->euid != p->uid))
4302 return -EPERM;
4305 retval = security_task_setscheduler(p, policy, param);
4306 if (retval)
4307 return retval;
4309 * make sure no PI-waiters arrive (or leave) while we are
4310 * changing the priority of the task:
4312 spin_lock_irqsave(&p->pi_lock, flags);
4314 * To be able to change p->policy safely, the apropriate
4315 * runqueue lock must be held.
4317 rq = __task_rq_lock(p);
4318 /* recheck policy now with rq lock held */
4319 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4320 policy = oldpolicy = -1;
4321 __task_rq_unlock(rq);
4322 spin_unlock_irqrestore(&p->pi_lock, flags);
4323 goto recheck;
4325 update_rq_clock(rq);
4326 on_rq = p->se.on_rq;
4327 running = task_current(rq, p);
4328 if (on_rq) {
4329 deactivate_task(rq, p, 0);
4330 if (running)
4331 p->sched_class->put_prev_task(rq, p);
4334 oldprio = p->prio;
4335 __setscheduler(rq, p, policy, param->sched_priority);
4337 if (on_rq) {
4338 if (running)
4339 p->sched_class->set_curr_task(rq);
4340 activate_task(rq, p, 0);
4342 * Reschedule if we are currently running on this runqueue and
4343 * our priority decreased, or if we are not currently running on
4344 * this runqueue and our priority is higher than the current's
4346 if (running) {
4347 if (p->prio > oldprio)
4348 resched_task(rq->curr);
4349 } else {
4350 check_preempt_curr(rq, p);
4353 __task_rq_unlock(rq);
4354 spin_unlock_irqrestore(&p->pi_lock, flags);
4356 rt_mutex_adjust_pi(p);
4358 return 0;
4360 EXPORT_SYMBOL_GPL(sched_setscheduler);
4362 static int
4363 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4365 struct sched_param lparam;
4366 struct task_struct *p;
4367 int retval;
4369 if (!param || pid < 0)
4370 return -EINVAL;
4371 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4372 return -EFAULT;
4374 rcu_read_lock();
4375 retval = -ESRCH;
4376 p = find_process_by_pid(pid);
4377 if (p != NULL)
4378 retval = sched_setscheduler(p, policy, &lparam);
4379 rcu_read_unlock();
4381 return retval;
4385 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4386 * @pid: the pid in question.
4387 * @policy: new policy.
4388 * @param: structure containing the new RT priority.
4390 asmlinkage long
4391 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4393 /* negative values for policy are not valid */
4394 if (policy < 0)
4395 return -EINVAL;
4397 return do_sched_setscheduler(pid, policy, param);
4401 * sys_sched_setparam - set/change the RT priority of a thread
4402 * @pid: the pid in question.
4403 * @param: structure containing the new RT priority.
4405 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4407 return do_sched_setscheduler(pid, -1, param);
4411 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4412 * @pid: the pid in question.
4414 asmlinkage long sys_sched_getscheduler(pid_t pid)
4416 struct task_struct *p;
4417 int retval;
4419 if (pid < 0)
4420 return -EINVAL;
4422 retval = -ESRCH;
4423 read_lock(&tasklist_lock);
4424 p = find_process_by_pid(pid);
4425 if (p) {
4426 retval = security_task_getscheduler(p);
4427 if (!retval)
4428 retval = p->policy;
4430 read_unlock(&tasklist_lock);
4431 return retval;
4435 * sys_sched_getscheduler - get the RT priority of a thread
4436 * @pid: the pid in question.
4437 * @param: structure containing the RT priority.
4439 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4441 struct sched_param lp;
4442 struct task_struct *p;
4443 int retval;
4445 if (!param || pid < 0)
4446 return -EINVAL;
4448 read_lock(&tasklist_lock);
4449 p = find_process_by_pid(pid);
4450 retval = -ESRCH;
4451 if (!p)
4452 goto out_unlock;
4454 retval = security_task_getscheduler(p);
4455 if (retval)
4456 goto out_unlock;
4458 lp.sched_priority = p->rt_priority;
4459 read_unlock(&tasklist_lock);
4462 * This one might sleep, we cannot do it with a spinlock held ...
4464 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4466 return retval;
4468 out_unlock:
4469 read_unlock(&tasklist_lock);
4470 return retval;
4473 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4475 cpumask_t cpus_allowed;
4476 struct task_struct *p;
4477 int retval;
4479 get_online_cpus();
4480 read_lock(&tasklist_lock);
4482 p = find_process_by_pid(pid);
4483 if (!p) {
4484 read_unlock(&tasklist_lock);
4485 put_online_cpus();
4486 return -ESRCH;
4490 * It is not safe to call set_cpus_allowed with the
4491 * tasklist_lock held. We will bump the task_struct's
4492 * usage count and then drop tasklist_lock.
4494 get_task_struct(p);
4495 read_unlock(&tasklist_lock);
4497 retval = -EPERM;
4498 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4499 !capable(CAP_SYS_NICE))
4500 goto out_unlock;
4502 retval = security_task_setscheduler(p, 0, NULL);
4503 if (retval)
4504 goto out_unlock;
4506 cpus_allowed = cpuset_cpus_allowed(p);
4507 cpus_and(new_mask, new_mask, cpus_allowed);
4508 again:
4509 retval = set_cpus_allowed(p, new_mask);
4511 if (!retval) {
4512 cpus_allowed = cpuset_cpus_allowed(p);
4513 if (!cpus_subset(new_mask, cpus_allowed)) {
4515 * We must have raced with a concurrent cpuset
4516 * update. Just reset the cpus_allowed to the
4517 * cpuset's cpus_allowed
4519 new_mask = cpus_allowed;
4520 goto again;
4523 out_unlock:
4524 put_task_struct(p);
4525 put_online_cpus();
4526 return retval;
4529 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4530 cpumask_t *new_mask)
4532 if (len < sizeof(cpumask_t)) {
4533 memset(new_mask, 0, sizeof(cpumask_t));
4534 } else if (len > sizeof(cpumask_t)) {
4535 len = sizeof(cpumask_t);
4537 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4541 * sys_sched_setaffinity - set the cpu affinity of a process
4542 * @pid: pid of the process
4543 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4544 * @user_mask_ptr: user-space pointer to the new cpu mask
4546 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4547 unsigned long __user *user_mask_ptr)
4549 cpumask_t new_mask;
4550 int retval;
4552 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4553 if (retval)
4554 return retval;
4556 return sched_setaffinity(pid, new_mask);
4560 * Represents all cpu's present in the system
4561 * In systems capable of hotplug, this map could dynamically grow
4562 * as new cpu's are detected in the system via any platform specific
4563 * method, such as ACPI for e.g.
4566 cpumask_t cpu_present_map __read_mostly;
4567 EXPORT_SYMBOL(cpu_present_map);
4569 #ifndef CONFIG_SMP
4570 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4571 EXPORT_SYMBOL(cpu_online_map);
4573 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4574 EXPORT_SYMBOL(cpu_possible_map);
4575 #endif
4577 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4579 struct task_struct *p;
4580 int retval;
4582 get_online_cpus();
4583 read_lock(&tasklist_lock);
4585 retval = -ESRCH;
4586 p = find_process_by_pid(pid);
4587 if (!p)
4588 goto out_unlock;
4590 retval = security_task_getscheduler(p);
4591 if (retval)
4592 goto out_unlock;
4594 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4596 out_unlock:
4597 read_unlock(&tasklist_lock);
4598 put_online_cpus();
4600 return retval;
4604 * sys_sched_getaffinity - get the cpu affinity of a process
4605 * @pid: pid of the process
4606 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4607 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4609 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4610 unsigned long __user *user_mask_ptr)
4612 int ret;
4613 cpumask_t mask;
4615 if (len < sizeof(cpumask_t))
4616 return -EINVAL;
4618 ret = sched_getaffinity(pid, &mask);
4619 if (ret < 0)
4620 return ret;
4622 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4623 return -EFAULT;
4625 return sizeof(cpumask_t);
4629 * sys_sched_yield - yield the current processor to other threads.
4631 * This function yields the current CPU to other tasks. If there are no
4632 * other threads running on this CPU then this function will return.
4634 asmlinkage long sys_sched_yield(void)
4636 struct rq *rq = this_rq_lock();
4638 schedstat_inc(rq, yld_count);
4639 current->sched_class->yield_task(rq);
4642 * Since we are going to call schedule() anyway, there's
4643 * no need to preempt or enable interrupts:
4645 __release(rq->lock);
4646 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4647 _raw_spin_unlock(&rq->lock);
4648 preempt_enable_no_resched();
4650 schedule();
4652 return 0;
4655 static void __cond_resched(void)
4657 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4658 __might_sleep(__FILE__, __LINE__);
4659 #endif
4661 * The BKS might be reacquired before we have dropped
4662 * PREEMPT_ACTIVE, which could trigger a second
4663 * cond_resched() call.
4665 do {
4666 add_preempt_count(PREEMPT_ACTIVE);
4667 schedule();
4668 sub_preempt_count(PREEMPT_ACTIVE);
4669 } while (need_resched());
4672 int __sched cond_resched(void)
4674 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
4675 system_state == SYSTEM_RUNNING) {
4676 __cond_resched();
4677 return 1;
4679 return 0;
4681 EXPORT_SYMBOL(cond_resched);
4684 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4685 * call schedule, and on return reacquire the lock.
4687 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4688 * operations here to prevent schedule() from being called twice (once via
4689 * spin_unlock(), once by hand).
4691 int cond_resched_lock(spinlock_t *lock)
4693 int ret = 0;
4695 if (need_lockbreak(lock)) {
4696 spin_unlock(lock);
4697 cpu_relax();
4698 ret = 1;
4699 spin_lock(lock);
4701 if (need_resched() && system_state == SYSTEM_RUNNING) {
4702 spin_release(&lock->dep_map, 1, _THIS_IP_);
4703 _raw_spin_unlock(lock);
4704 preempt_enable_no_resched();
4705 __cond_resched();
4706 ret = 1;
4707 spin_lock(lock);
4709 return ret;
4711 EXPORT_SYMBOL(cond_resched_lock);
4713 int __sched cond_resched_softirq(void)
4715 BUG_ON(!in_softirq());
4717 if (need_resched() && system_state == SYSTEM_RUNNING) {
4718 local_bh_enable();
4719 __cond_resched();
4720 local_bh_disable();
4721 return 1;
4723 return 0;
4725 EXPORT_SYMBOL(cond_resched_softirq);
4728 * yield - yield the current processor to other threads.
4730 * This is a shortcut for kernel-space yielding - it marks the
4731 * thread runnable and calls sys_sched_yield().
4733 void __sched yield(void)
4735 set_current_state(TASK_RUNNING);
4736 sys_sched_yield();
4738 EXPORT_SYMBOL(yield);
4741 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4742 * that process accounting knows that this is a task in IO wait state.
4744 * But don't do that if it is a deliberate, throttling IO wait (this task
4745 * has set its backing_dev_info: the queue against which it should throttle)
4747 void __sched io_schedule(void)
4749 struct rq *rq = &__raw_get_cpu_var(runqueues);
4751 delayacct_blkio_start();
4752 atomic_inc(&rq->nr_iowait);
4753 schedule();
4754 atomic_dec(&rq->nr_iowait);
4755 delayacct_blkio_end();
4757 EXPORT_SYMBOL(io_schedule);
4759 long __sched io_schedule_timeout(long timeout)
4761 struct rq *rq = &__raw_get_cpu_var(runqueues);
4762 long ret;
4764 delayacct_blkio_start();
4765 atomic_inc(&rq->nr_iowait);
4766 ret = schedule_timeout(timeout);
4767 atomic_dec(&rq->nr_iowait);
4768 delayacct_blkio_end();
4769 return ret;
4773 * sys_sched_get_priority_max - return maximum RT priority.
4774 * @policy: scheduling class.
4776 * this syscall returns the maximum rt_priority that can be used
4777 * by a given scheduling class.
4779 asmlinkage long sys_sched_get_priority_max(int policy)
4781 int ret = -EINVAL;
4783 switch (policy) {
4784 case SCHED_FIFO:
4785 case SCHED_RR:
4786 ret = MAX_USER_RT_PRIO-1;
4787 break;
4788 case SCHED_NORMAL:
4789 case SCHED_BATCH:
4790 case SCHED_IDLE:
4791 ret = 0;
4792 break;
4794 return ret;
4798 * sys_sched_get_priority_min - return minimum RT priority.
4799 * @policy: scheduling class.
4801 * this syscall returns the minimum rt_priority that can be used
4802 * by a given scheduling class.
4804 asmlinkage long sys_sched_get_priority_min(int policy)
4806 int ret = -EINVAL;
4808 switch (policy) {
4809 case SCHED_FIFO:
4810 case SCHED_RR:
4811 ret = 1;
4812 break;
4813 case SCHED_NORMAL:
4814 case SCHED_BATCH:
4815 case SCHED_IDLE:
4816 ret = 0;
4818 return ret;
4822 * sys_sched_rr_get_interval - return the default timeslice of a process.
4823 * @pid: pid of the process.
4824 * @interval: userspace pointer to the timeslice value.
4826 * this syscall writes the default timeslice value of a given process
4827 * into the user-space timespec buffer. A value of '0' means infinity.
4829 asmlinkage
4830 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4832 struct task_struct *p;
4833 unsigned int time_slice;
4834 int retval;
4835 struct timespec t;
4837 if (pid < 0)
4838 return -EINVAL;
4840 retval = -ESRCH;
4841 read_lock(&tasklist_lock);
4842 p = find_process_by_pid(pid);
4843 if (!p)
4844 goto out_unlock;
4846 retval = security_task_getscheduler(p);
4847 if (retval)
4848 goto out_unlock;
4851 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
4852 * tasks that are on an otherwise idle runqueue:
4854 time_slice = 0;
4855 if (p->policy == SCHED_RR) {
4856 time_slice = DEF_TIMESLICE;
4857 } else {
4858 struct sched_entity *se = &p->se;
4859 unsigned long flags;
4860 struct rq *rq;
4862 rq = task_rq_lock(p, &flags);
4863 if (rq->cfs.load.weight)
4864 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
4865 task_rq_unlock(rq, &flags);
4867 read_unlock(&tasklist_lock);
4868 jiffies_to_timespec(time_slice, &t);
4869 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4870 return retval;
4872 out_unlock:
4873 read_unlock(&tasklist_lock);
4874 return retval;
4877 static const char stat_nam[] = "RSDTtZX";
4879 void sched_show_task(struct task_struct *p)
4881 unsigned long free = 0;
4882 unsigned state;
4884 state = p->state ? __ffs(p->state) + 1 : 0;
4885 printk(KERN_INFO "%-13.13s %c", p->comm,
4886 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4887 #if BITS_PER_LONG == 32
4888 if (state == TASK_RUNNING)
4889 printk(KERN_CONT " running ");
4890 else
4891 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
4892 #else
4893 if (state == TASK_RUNNING)
4894 printk(KERN_CONT " running task ");
4895 else
4896 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
4897 #endif
4898 #ifdef CONFIG_DEBUG_STACK_USAGE
4900 unsigned long *n = end_of_stack(p);
4901 while (!*n)
4902 n++;
4903 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4905 #endif
4906 printk(KERN_CONT "%5lu %5d %6d\n", free,
4907 task_pid_nr(p), task_pid_nr(p->real_parent));
4909 if (state != TASK_RUNNING)
4910 show_stack(p, NULL);
4913 void show_state_filter(unsigned long state_filter)
4915 struct task_struct *g, *p;
4917 #if BITS_PER_LONG == 32
4918 printk(KERN_INFO
4919 " task PC stack pid father\n");
4920 #else
4921 printk(KERN_INFO
4922 " task PC stack pid father\n");
4923 #endif
4924 read_lock(&tasklist_lock);
4925 do_each_thread(g, p) {
4927 * reset the NMI-timeout, listing all files on a slow
4928 * console might take alot of time:
4930 touch_nmi_watchdog();
4931 if (!state_filter || (p->state & state_filter))
4932 sched_show_task(p);
4933 } while_each_thread(g, p);
4935 touch_all_softlockup_watchdogs();
4937 #ifdef CONFIG_SCHED_DEBUG
4938 sysrq_sched_debug_show();
4939 #endif
4940 read_unlock(&tasklist_lock);
4942 * Only show locks if all tasks are dumped:
4944 if (state_filter == -1)
4945 debug_show_all_locks();
4948 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4950 idle->sched_class = &idle_sched_class;
4954 * init_idle - set up an idle thread for a given CPU
4955 * @idle: task in question
4956 * @cpu: cpu the idle task belongs to
4958 * NOTE: this function does not set the idle thread's NEED_RESCHED
4959 * flag, to make booting more robust.
4961 void __cpuinit init_idle(struct task_struct *idle, int cpu)
4963 struct rq *rq = cpu_rq(cpu);
4964 unsigned long flags;
4966 __sched_fork(idle);
4967 idle->se.exec_start = sched_clock();
4969 idle->prio = idle->normal_prio = MAX_PRIO;
4970 idle->cpus_allowed = cpumask_of_cpu(cpu);
4971 __set_task_cpu(idle, cpu);
4973 spin_lock_irqsave(&rq->lock, flags);
4974 rq->curr = rq->idle = idle;
4975 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4976 idle->oncpu = 1;
4977 #endif
4978 spin_unlock_irqrestore(&rq->lock, flags);
4980 /* Set the preempt count _outside_ the spinlocks! */
4981 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4982 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4983 #else
4984 task_thread_info(idle)->preempt_count = 0;
4985 #endif
4987 * The idle tasks have their own, simple scheduling class:
4989 idle->sched_class = &idle_sched_class;
4993 * In a system that switches off the HZ timer nohz_cpu_mask
4994 * indicates which cpus entered this state. This is used
4995 * in the rcu update to wait only for active cpus. For system
4996 * which do not switch off the HZ timer nohz_cpu_mask should
4997 * always be CPU_MASK_NONE.
4999 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5002 * Increase the granularity value when there are more CPUs,
5003 * because with more CPUs the 'effective latency' as visible
5004 * to users decreases. But the relationship is not linear,
5005 * so pick a second-best guess by going with the log2 of the
5006 * number of CPUs.
5008 * This idea comes from the SD scheduler of Con Kolivas:
5010 static inline void sched_init_granularity(void)
5012 unsigned int factor = 1 + ilog2(num_online_cpus());
5013 const unsigned long limit = 200000000;
5015 sysctl_sched_min_granularity *= factor;
5016 if (sysctl_sched_min_granularity > limit)
5017 sysctl_sched_min_granularity = limit;
5019 sysctl_sched_latency *= factor;
5020 if (sysctl_sched_latency > limit)
5021 sysctl_sched_latency = limit;
5023 sysctl_sched_wakeup_granularity *= factor;
5024 sysctl_sched_batch_wakeup_granularity *= factor;
5027 #ifdef CONFIG_SMP
5029 * This is how migration works:
5031 * 1) we queue a struct migration_req structure in the source CPU's
5032 * runqueue and wake up that CPU's migration thread.
5033 * 2) we down() the locked semaphore => thread blocks.
5034 * 3) migration thread wakes up (implicitly it forces the migrated
5035 * thread off the CPU)
5036 * 4) it gets the migration request and checks whether the migrated
5037 * task is still in the wrong runqueue.
5038 * 5) if it's in the wrong runqueue then the migration thread removes
5039 * it and puts it into the right queue.
5040 * 6) migration thread up()s the semaphore.
5041 * 7) we wake up and the migration is done.
5045 * Change a given task's CPU affinity. Migrate the thread to a
5046 * proper CPU and schedule it away if the CPU it's executing on
5047 * is removed from the allowed bitmask.
5049 * NOTE: the caller must have a valid reference to the task, the
5050 * task must not exit() & deallocate itself prematurely. The
5051 * call is not atomic; no spinlocks may be held.
5053 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5055 struct migration_req req;
5056 unsigned long flags;
5057 struct rq *rq;
5058 int ret = 0;
5060 rq = task_rq_lock(p, &flags);
5061 if (!cpus_intersects(new_mask, cpu_online_map)) {
5062 ret = -EINVAL;
5063 goto out;
5066 if (p->sched_class->set_cpus_allowed)
5067 p->sched_class->set_cpus_allowed(p, &new_mask);
5068 else {
5069 p->cpus_allowed = new_mask;
5070 p->nr_cpus_allowed = cpus_weight(new_mask);
5073 /* Can the task run on the task's current CPU? If so, we're done */
5074 if (cpu_isset(task_cpu(p), new_mask))
5075 goto out;
5077 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5078 /* Need help from migration thread: drop lock and wait. */
5079 task_rq_unlock(rq, &flags);
5080 wake_up_process(rq->migration_thread);
5081 wait_for_completion(&req.done);
5082 tlb_migrate_finish(p->mm);
5083 return 0;
5085 out:
5086 task_rq_unlock(rq, &flags);
5088 return ret;
5090 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5093 * Move (not current) task off this cpu, onto dest cpu. We're doing
5094 * this because either it can't run here any more (set_cpus_allowed()
5095 * away from this CPU, or CPU going down), or because we're
5096 * attempting to rebalance this task on exec (sched_exec).
5098 * So we race with normal scheduler movements, but that's OK, as long
5099 * as the task is no longer on this CPU.
5101 * Returns non-zero if task was successfully migrated.
5103 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5105 struct rq *rq_dest, *rq_src;
5106 int ret = 0, on_rq;
5108 if (unlikely(cpu_is_offline(dest_cpu)))
5109 return ret;
5111 rq_src = cpu_rq(src_cpu);
5112 rq_dest = cpu_rq(dest_cpu);
5114 double_rq_lock(rq_src, rq_dest);
5115 /* Already moved. */
5116 if (task_cpu(p) != src_cpu)
5117 goto out;
5118 /* Affinity changed (again). */
5119 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5120 goto out;
5122 on_rq = p->se.on_rq;
5123 if (on_rq)
5124 deactivate_task(rq_src, p, 0);
5126 set_task_cpu(p, dest_cpu);
5127 if (on_rq) {
5128 activate_task(rq_dest, p, 0);
5129 check_preempt_curr(rq_dest, p);
5131 ret = 1;
5132 out:
5133 double_rq_unlock(rq_src, rq_dest);
5134 return ret;
5138 * migration_thread - this is a highprio system thread that performs
5139 * thread migration by bumping thread off CPU then 'pushing' onto
5140 * another runqueue.
5142 static int migration_thread(void *data)
5144 int cpu = (long)data;
5145 struct rq *rq;
5147 rq = cpu_rq(cpu);
5148 BUG_ON(rq->migration_thread != current);
5150 set_current_state(TASK_INTERRUPTIBLE);
5151 while (!kthread_should_stop()) {
5152 struct migration_req *req;
5153 struct list_head *head;
5155 spin_lock_irq(&rq->lock);
5157 if (cpu_is_offline(cpu)) {
5158 spin_unlock_irq(&rq->lock);
5159 goto wait_to_die;
5162 if (rq->active_balance) {
5163 active_load_balance(rq, cpu);
5164 rq->active_balance = 0;
5167 head = &rq->migration_queue;
5169 if (list_empty(head)) {
5170 spin_unlock_irq(&rq->lock);
5171 schedule();
5172 set_current_state(TASK_INTERRUPTIBLE);
5173 continue;
5175 req = list_entry(head->next, struct migration_req, list);
5176 list_del_init(head->next);
5178 spin_unlock(&rq->lock);
5179 __migrate_task(req->task, cpu, req->dest_cpu);
5180 local_irq_enable();
5182 complete(&req->done);
5184 __set_current_state(TASK_RUNNING);
5185 return 0;
5187 wait_to_die:
5188 /* Wait for kthread_stop */
5189 set_current_state(TASK_INTERRUPTIBLE);
5190 while (!kthread_should_stop()) {
5191 schedule();
5192 set_current_state(TASK_INTERRUPTIBLE);
5194 __set_current_state(TASK_RUNNING);
5195 return 0;
5198 #ifdef CONFIG_HOTPLUG_CPU
5200 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5202 int ret;
5204 local_irq_disable();
5205 ret = __migrate_task(p, src_cpu, dest_cpu);
5206 local_irq_enable();
5207 return ret;
5211 * Figure out where task on dead CPU should go, use force if necessary.
5212 * NOTE: interrupts should be disabled by the caller
5214 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5216 unsigned long flags;
5217 cpumask_t mask;
5218 struct rq *rq;
5219 int dest_cpu;
5221 do {
5222 /* On same node? */
5223 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5224 cpus_and(mask, mask, p->cpus_allowed);
5225 dest_cpu = any_online_cpu(mask);
5227 /* On any allowed CPU? */
5228 if (dest_cpu == NR_CPUS)
5229 dest_cpu = any_online_cpu(p->cpus_allowed);
5231 /* No more Mr. Nice Guy. */
5232 if (dest_cpu == NR_CPUS) {
5233 cpumask_t cpus_allowed = cpuset_cpus_allowed_locked(p);
5235 * Try to stay on the same cpuset, where the
5236 * current cpuset may be a subset of all cpus.
5237 * The cpuset_cpus_allowed_locked() variant of
5238 * cpuset_cpus_allowed() will not block. It must be
5239 * called within calls to cpuset_lock/cpuset_unlock.
5241 rq = task_rq_lock(p, &flags);
5242 p->cpus_allowed = cpus_allowed;
5243 dest_cpu = any_online_cpu(p->cpus_allowed);
5244 task_rq_unlock(rq, &flags);
5247 * Don't tell them about moving exiting tasks or
5248 * kernel threads (both mm NULL), since they never
5249 * leave kernel.
5251 if (p->mm && printk_ratelimit()) {
5252 printk(KERN_INFO "process %d (%s) no "
5253 "longer affine to cpu%d\n",
5254 task_pid_nr(p), p->comm, dead_cpu);
5257 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5261 * While a dead CPU has no uninterruptible tasks queued at this point,
5262 * it might still have a nonzero ->nr_uninterruptible counter, because
5263 * for performance reasons the counter is not stricly tracking tasks to
5264 * their home CPUs. So we just add the counter to another CPU's counter,
5265 * to keep the global sum constant after CPU-down:
5267 static void migrate_nr_uninterruptible(struct rq *rq_src)
5269 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5270 unsigned long flags;
5272 local_irq_save(flags);
5273 double_rq_lock(rq_src, rq_dest);
5274 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5275 rq_src->nr_uninterruptible = 0;
5276 double_rq_unlock(rq_src, rq_dest);
5277 local_irq_restore(flags);
5280 /* Run through task list and migrate tasks from the dead cpu. */
5281 static void migrate_live_tasks(int src_cpu)
5283 struct task_struct *p, *t;
5285 read_lock(&tasklist_lock);
5287 do_each_thread(t, p) {
5288 if (p == current)
5289 continue;
5291 if (task_cpu(p) == src_cpu)
5292 move_task_off_dead_cpu(src_cpu, p);
5293 } while_each_thread(t, p);
5295 read_unlock(&tasklist_lock);
5299 * Schedules idle task to be the next runnable task on current CPU.
5300 * It does so by boosting its priority to highest possible.
5301 * Used by CPU offline code.
5303 void sched_idle_next(void)
5305 int this_cpu = smp_processor_id();
5306 struct rq *rq = cpu_rq(this_cpu);
5307 struct task_struct *p = rq->idle;
5308 unsigned long flags;
5310 /* cpu has to be offline */
5311 BUG_ON(cpu_online(this_cpu));
5314 * Strictly not necessary since rest of the CPUs are stopped by now
5315 * and interrupts disabled on the current cpu.
5317 spin_lock_irqsave(&rq->lock, flags);
5319 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5321 update_rq_clock(rq);
5322 activate_task(rq, p, 0);
5324 spin_unlock_irqrestore(&rq->lock, flags);
5328 * Ensures that the idle task is using init_mm right before its cpu goes
5329 * offline.
5331 void idle_task_exit(void)
5333 struct mm_struct *mm = current->active_mm;
5335 BUG_ON(cpu_online(smp_processor_id()));
5337 if (mm != &init_mm)
5338 switch_mm(mm, &init_mm, current);
5339 mmdrop(mm);
5342 /* called under rq->lock with disabled interrupts */
5343 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5345 struct rq *rq = cpu_rq(dead_cpu);
5347 /* Must be exiting, otherwise would be on tasklist. */
5348 BUG_ON(!p->exit_state);
5350 /* Cannot have done final schedule yet: would have vanished. */
5351 BUG_ON(p->state == TASK_DEAD);
5353 get_task_struct(p);
5356 * Drop lock around migration; if someone else moves it,
5357 * that's OK. No task can be added to this CPU, so iteration is
5358 * fine.
5360 spin_unlock_irq(&rq->lock);
5361 move_task_off_dead_cpu(dead_cpu, p);
5362 spin_lock_irq(&rq->lock);
5364 put_task_struct(p);
5367 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5368 static void migrate_dead_tasks(unsigned int dead_cpu)
5370 struct rq *rq = cpu_rq(dead_cpu);
5371 struct task_struct *next;
5373 for ( ; ; ) {
5374 if (!rq->nr_running)
5375 break;
5376 update_rq_clock(rq);
5377 next = pick_next_task(rq, rq->curr);
5378 if (!next)
5379 break;
5380 migrate_dead(dead_cpu, next);
5384 #endif /* CONFIG_HOTPLUG_CPU */
5386 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5388 static struct ctl_table sd_ctl_dir[] = {
5390 .procname = "sched_domain",
5391 .mode = 0555,
5393 {0, },
5396 static struct ctl_table sd_ctl_root[] = {
5398 .ctl_name = CTL_KERN,
5399 .procname = "kernel",
5400 .mode = 0555,
5401 .child = sd_ctl_dir,
5403 {0, },
5406 static struct ctl_table *sd_alloc_ctl_entry(int n)
5408 struct ctl_table *entry =
5409 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5411 return entry;
5414 static void sd_free_ctl_entry(struct ctl_table **tablep)
5416 struct ctl_table *entry;
5419 * In the intermediate directories, both the child directory and
5420 * procname are dynamically allocated and could fail but the mode
5421 * will always be set. In the lowest directory the names are
5422 * static strings and all have proc handlers.
5424 for (entry = *tablep; entry->mode; entry++) {
5425 if (entry->child)
5426 sd_free_ctl_entry(&entry->child);
5427 if (entry->proc_handler == NULL)
5428 kfree(entry->procname);
5431 kfree(*tablep);
5432 *tablep = NULL;
5435 static void
5436 set_table_entry(struct ctl_table *entry,
5437 const char *procname, void *data, int maxlen,
5438 mode_t mode, proc_handler *proc_handler)
5440 entry->procname = procname;
5441 entry->data = data;
5442 entry->maxlen = maxlen;
5443 entry->mode = mode;
5444 entry->proc_handler = proc_handler;
5447 static struct ctl_table *
5448 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5450 struct ctl_table *table = sd_alloc_ctl_entry(12);
5452 if (table == NULL)
5453 return NULL;
5455 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5456 sizeof(long), 0644, proc_doulongvec_minmax);
5457 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5458 sizeof(long), 0644, proc_doulongvec_minmax);
5459 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5460 sizeof(int), 0644, proc_dointvec_minmax);
5461 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5462 sizeof(int), 0644, proc_dointvec_minmax);
5463 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5464 sizeof(int), 0644, proc_dointvec_minmax);
5465 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5466 sizeof(int), 0644, proc_dointvec_minmax);
5467 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5468 sizeof(int), 0644, proc_dointvec_minmax);
5469 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5470 sizeof(int), 0644, proc_dointvec_minmax);
5471 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5472 sizeof(int), 0644, proc_dointvec_minmax);
5473 set_table_entry(&table[9], "cache_nice_tries",
5474 &sd->cache_nice_tries,
5475 sizeof(int), 0644, proc_dointvec_minmax);
5476 set_table_entry(&table[10], "flags", &sd->flags,
5477 sizeof(int), 0644, proc_dointvec_minmax);
5478 /* &table[11] is terminator */
5480 return table;
5483 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5485 struct ctl_table *entry, *table;
5486 struct sched_domain *sd;
5487 int domain_num = 0, i;
5488 char buf[32];
5490 for_each_domain(cpu, sd)
5491 domain_num++;
5492 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5493 if (table == NULL)
5494 return NULL;
5496 i = 0;
5497 for_each_domain(cpu, sd) {
5498 snprintf(buf, 32, "domain%d", i);
5499 entry->procname = kstrdup(buf, GFP_KERNEL);
5500 entry->mode = 0555;
5501 entry->child = sd_alloc_ctl_domain_table(sd);
5502 entry++;
5503 i++;
5505 return table;
5508 static struct ctl_table_header *sd_sysctl_header;
5509 static void register_sched_domain_sysctl(void)
5511 int i, cpu_num = num_online_cpus();
5512 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5513 char buf[32];
5515 WARN_ON(sd_ctl_dir[0].child);
5516 sd_ctl_dir[0].child = entry;
5518 if (entry == NULL)
5519 return;
5521 for_each_online_cpu(i) {
5522 snprintf(buf, 32, "cpu%d", i);
5523 entry->procname = kstrdup(buf, GFP_KERNEL);
5524 entry->mode = 0555;
5525 entry->child = sd_alloc_ctl_cpu_table(i);
5526 entry++;
5529 WARN_ON(sd_sysctl_header);
5530 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5533 /* may be called multiple times per register */
5534 static void unregister_sched_domain_sysctl(void)
5536 if (sd_sysctl_header)
5537 unregister_sysctl_table(sd_sysctl_header);
5538 sd_sysctl_header = NULL;
5539 if (sd_ctl_dir[0].child)
5540 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5542 #else
5543 static void register_sched_domain_sysctl(void)
5546 static void unregister_sched_domain_sysctl(void)
5549 #endif
5552 * migration_call - callback that gets triggered when a CPU is added.
5553 * Here we can start up the necessary migration thread for the new CPU.
5555 static int __cpuinit
5556 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5558 struct task_struct *p;
5559 int cpu = (long)hcpu;
5560 unsigned long flags;
5561 struct rq *rq;
5563 switch (action) {
5565 case CPU_UP_PREPARE:
5566 case CPU_UP_PREPARE_FROZEN:
5567 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
5568 if (IS_ERR(p))
5569 return NOTIFY_BAD;
5570 kthread_bind(p, cpu);
5571 /* Must be high prio: stop_machine expects to yield to it. */
5572 rq = task_rq_lock(p, &flags);
5573 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5574 task_rq_unlock(rq, &flags);
5575 cpu_rq(cpu)->migration_thread = p;
5576 break;
5578 case CPU_ONLINE:
5579 case CPU_ONLINE_FROZEN:
5580 /* Strictly unnecessary, as first user will wake it. */
5581 wake_up_process(cpu_rq(cpu)->migration_thread);
5583 /* Update our root-domain */
5584 rq = cpu_rq(cpu);
5585 spin_lock_irqsave(&rq->lock, flags);
5586 if (rq->rd) {
5587 BUG_ON(!cpu_isset(cpu, rq->rd->span));
5588 cpu_set(cpu, rq->rd->online);
5590 spin_unlock_irqrestore(&rq->lock, flags);
5591 break;
5593 #ifdef CONFIG_HOTPLUG_CPU
5594 case CPU_UP_CANCELED:
5595 case CPU_UP_CANCELED_FROZEN:
5596 if (!cpu_rq(cpu)->migration_thread)
5597 break;
5598 /* Unbind it from offline cpu so it can run. Fall thru. */
5599 kthread_bind(cpu_rq(cpu)->migration_thread,
5600 any_online_cpu(cpu_online_map));
5601 kthread_stop(cpu_rq(cpu)->migration_thread);
5602 cpu_rq(cpu)->migration_thread = NULL;
5603 break;
5605 case CPU_DEAD:
5606 case CPU_DEAD_FROZEN:
5607 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5608 migrate_live_tasks(cpu);
5609 rq = cpu_rq(cpu);
5610 kthread_stop(rq->migration_thread);
5611 rq->migration_thread = NULL;
5612 /* Idle task back to normal (off runqueue, low prio) */
5613 spin_lock_irq(&rq->lock);
5614 update_rq_clock(rq);
5615 deactivate_task(rq, rq->idle, 0);
5616 rq->idle->static_prio = MAX_PRIO;
5617 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5618 rq->idle->sched_class = &idle_sched_class;
5619 migrate_dead_tasks(cpu);
5620 spin_unlock_irq(&rq->lock);
5621 cpuset_unlock();
5622 migrate_nr_uninterruptible(rq);
5623 BUG_ON(rq->nr_running != 0);
5626 * No need to migrate the tasks: it was best-effort if
5627 * they didn't take sched_hotcpu_mutex. Just wake up
5628 * the requestors.
5630 spin_lock_irq(&rq->lock);
5631 while (!list_empty(&rq->migration_queue)) {
5632 struct migration_req *req;
5634 req = list_entry(rq->migration_queue.next,
5635 struct migration_req, list);
5636 list_del_init(&req->list);
5637 complete(&req->done);
5639 spin_unlock_irq(&rq->lock);
5640 break;
5642 case CPU_DOWN_PREPARE:
5643 /* Update our root-domain */
5644 rq = cpu_rq(cpu);
5645 spin_lock_irqsave(&rq->lock, flags);
5646 if (rq->rd) {
5647 BUG_ON(!cpu_isset(cpu, rq->rd->span));
5648 cpu_clear(cpu, rq->rd->online);
5650 spin_unlock_irqrestore(&rq->lock, flags);
5651 break;
5652 #endif
5654 return NOTIFY_OK;
5657 /* Register at highest priority so that task migration (migrate_all_tasks)
5658 * happens before everything else.
5660 static struct notifier_block __cpuinitdata migration_notifier = {
5661 .notifier_call = migration_call,
5662 .priority = 10
5665 void __init migration_init(void)
5667 void *cpu = (void *)(long)smp_processor_id();
5668 int err;
5670 /* Start one for the boot CPU: */
5671 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5672 BUG_ON(err == NOTIFY_BAD);
5673 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5674 register_cpu_notifier(&migration_notifier);
5676 #endif
5678 #ifdef CONFIG_SMP
5680 /* Number of possible processor ids */
5681 int nr_cpu_ids __read_mostly = NR_CPUS;
5682 EXPORT_SYMBOL(nr_cpu_ids);
5684 #ifdef CONFIG_SCHED_DEBUG
5686 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level)
5688 struct sched_group *group = sd->groups;
5689 cpumask_t groupmask;
5690 char str[NR_CPUS];
5692 cpumask_scnprintf(str, NR_CPUS, sd->span);
5693 cpus_clear(groupmask);
5695 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5697 if (!(sd->flags & SD_LOAD_BALANCE)) {
5698 printk("does not load-balance\n");
5699 if (sd->parent)
5700 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5701 " has parent");
5702 return -1;
5705 printk(KERN_CONT "span %s\n", str);
5707 if (!cpu_isset(cpu, sd->span)) {
5708 printk(KERN_ERR "ERROR: domain->span does not contain "
5709 "CPU%d\n", cpu);
5711 if (!cpu_isset(cpu, group->cpumask)) {
5712 printk(KERN_ERR "ERROR: domain->groups does not contain"
5713 " CPU%d\n", cpu);
5716 printk(KERN_DEBUG "%*s groups:", level + 1, "");
5717 do {
5718 if (!group) {
5719 printk("\n");
5720 printk(KERN_ERR "ERROR: group is NULL\n");
5721 break;
5724 if (!group->__cpu_power) {
5725 printk(KERN_CONT "\n");
5726 printk(KERN_ERR "ERROR: domain->cpu_power not "
5727 "set\n");
5728 break;
5731 if (!cpus_weight(group->cpumask)) {
5732 printk(KERN_CONT "\n");
5733 printk(KERN_ERR "ERROR: empty group\n");
5734 break;
5737 if (cpus_intersects(groupmask, group->cpumask)) {
5738 printk(KERN_CONT "\n");
5739 printk(KERN_ERR "ERROR: repeated CPUs\n");
5740 break;
5743 cpus_or(groupmask, groupmask, group->cpumask);
5745 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5746 printk(KERN_CONT " %s", str);
5748 group = group->next;
5749 } while (group != sd->groups);
5750 printk(KERN_CONT "\n");
5752 if (!cpus_equal(sd->span, groupmask))
5753 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5755 if (sd->parent && !cpus_subset(groupmask, sd->parent->span))
5756 printk(KERN_ERR "ERROR: parent span is not a superset "
5757 "of domain->span\n");
5758 return 0;
5761 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5763 int level = 0;
5765 if (!sd) {
5766 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5767 return;
5770 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5772 for (;;) {
5773 if (sched_domain_debug_one(sd, cpu, level))
5774 break;
5775 level++;
5776 sd = sd->parent;
5777 if (!sd)
5778 break;
5781 #else
5782 # define sched_domain_debug(sd, cpu) do { } while (0)
5783 #endif
5785 static int sd_degenerate(struct sched_domain *sd)
5787 if (cpus_weight(sd->span) == 1)
5788 return 1;
5790 /* Following flags need at least 2 groups */
5791 if (sd->flags & (SD_LOAD_BALANCE |
5792 SD_BALANCE_NEWIDLE |
5793 SD_BALANCE_FORK |
5794 SD_BALANCE_EXEC |
5795 SD_SHARE_CPUPOWER |
5796 SD_SHARE_PKG_RESOURCES)) {
5797 if (sd->groups != sd->groups->next)
5798 return 0;
5801 /* Following flags don't use groups */
5802 if (sd->flags & (SD_WAKE_IDLE |
5803 SD_WAKE_AFFINE |
5804 SD_WAKE_BALANCE))
5805 return 0;
5807 return 1;
5810 static int
5811 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5813 unsigned long cflags = sd->flags, pflags = parent->flags;
5815 if (sd_degenerate(parent))
5816 return 1;
5818 if (!cpus_equal(sd->span, parent->span))
5819 return 0;
5821 /* Does parent contain flags not in child? */
5822 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5823 if (cflags & SD_WAKE_AFFINE)
5824 pflags &= ~SD_WAKE_BALANCE;
5825 /* Flags needing groups don't count if only 1 group in parent */
5826 if (parent->groups == parent->groups->next) {
5827 pflags &= ~(SD_LOAD_BALANCE |
5828 SD_BALANCE_NEWIDLE |
5829 SD_BALANCE_FORK |
5830 SD_BALANCE_EXEC |
5831 SD_SHARE_CPUPOWER |
5832 SD_SHARE_PKG_RESOURCES);
5834 if (~cflags & pflags)
5835 return 0;
5837 return 1;
5840 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5842 unsigned long flags;
5843 const struct sched_class *class;
5845 spin_lock_irqsave(&rq->lock, flags);
5847 if (rq->rd) {
5848 struct root_domain *old_rd = rq->rd;
5850 for (class = sched_class_highest; class; class = class->next) {
5851 if (class->leave_domain)
5852 class->leave_domain(rq);
5855 if (atomic_dec_and_test(&old_rd->refcount))
5856 kfree(old_rd);
5859 atomic_inc(&rd->refcount);
5860 rq->rd = rd;
5862 for (class = sched_class_highest; class; class = class->next) {
5863 if (class->join_domain)
5864 class->join_domain(rq);
5867 spin_unlock_irqrestore(&rq->lock, flags);
5870 static void init_rootdomain(struct root_domain *rd, const cpumask_t *map)
5872 memset(rd, 0, sizeof(*rd));
5874 rd->span = *map;
5875 cpus_and(rd->online, rd->span, cpu_online_map);
5878 static void init_defrootdomain(void)
5880 cpumask_t cpus = CPU_MASK_ALL;
5882 init_rootdomain(&def_root_domain, &cpus);
5883 atomic_set(&def_root_domain.refcount, 1);
5886 static struct root_domain *alloc_rootdomain(const cpumask_t *map)
5888 struct root_domain *rd;
5890 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5891 if (!rd)
5892 return NULL;
5894 init_rootdomain(rd, map);
5896 return rd;
5900 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5901 * hold the hotplug lock.
5903 static void
5904 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
5906 struct rq *rq = cpu_rq(cpu);
5907 struct sched_domain *tmp;
5909 /* Remove the sched domains which do not contribute to scheduling. */
5910 for (tmp = sd; tmp; tmp = tmp->parent) {
5911 struct sched_domain *parent = tmp->parent;
5912 if (!parent)
5913 break;
5914 if (sd_parent_degenerate(tmp, parent)) {
5915 tmp->parent = parent->parent;
5916 if (parent->parent)
5917 parent->parent->child = tmp;
5921 if (sd && sd_degenerate(sd)) {
5922 sd = sd->parent;
5923 if (sd)
5924 sd->child = NULL;
5927 sched_domain_debug(sd, cpu);
5929 rq_attach_root(rq, rd);
5930 rcu_assign_pointer(rq->sd, sd);
5933 /* cpus with isolated domains */
5934 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
5936 /* Setup the mask of cpus configured for isolated domains */
5937 static int __init isolated_cpu_setup(char *str)
5939 int ints[NR_CPUS], i;
5941 str = get_options(str, ARRAY_SIZE(ints), ints);
5942 cpus_clear(cpu_isolated_map);
5943 for (i = 1; i <= ints[0]; i++)
5944 if (ints[i] < NR_CPUS)
5945 cpu_set(ints[i], cpu_isolated_map);
5946 return 1;
5949 __setup("isolcpus=", isolated_cpu_setup);
5952 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
5953 * to a function which identifies what group(along with sched group) a CPU
5954 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
5955 * (due to the fact that we keep track of groups covered with a cpumask_t).
5957 * init_sched_build_groups will build a circular linked list of the groups
5958 * covered by the given span, and will set each group's ->cpumask correctly,
5959 * and ->cpu_power to 0.
5961 static void
5962 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
5963 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
5964 struct sched_group **sg))
5966 struct sched_group *first = NULL, *last = NULL;
5967 cpumask_t covered = CPU_MASK_NONE;
5968 int i;
5970 for_each_cpu_mask(i, span) {
5971 struct sched_group *sg;
5972 int group = group_fn(i, cpu_map, &sg);
5973 int j;
5975 if (cpu_isset(i, covered))
5976 continue;
5978 sg->cpumask = CPU_MASK_NONE;
5979 sg->__cpu_power = 0;
5981 for_each_cpu_mask(j, span) {
5982 if (group_fn(j, cpu_map, NULL) != group)
5983 continue;
5985 cpu_set(j, covered);
5986 cpu_set(j, sg->cpumask);
5988 if (!first)
5989 first = sg;
5990 if (last)
5991 last->next = sg;
5992 last = sg;
5994 last->next = first;
5997 #define SD_NODES_PER_DOMAIN 16
5999 #ifdef CONFIG_NUMA
6002 * find_next_best_node - find the next node to include in a sched_domain
6003 * @node: node whose sched_domain we're building
6004 * @used_nodes: nodes already in the sched_domain
6006 * Find the next node to include in a given scheduling domain. Simply
6007 * finds the closest node not already in the @used_nodes map.
6009 * Should use nodemask_t.
6011 static int find_next_best_node(int node, unsigned long *used_nodes)
6013 int i, n, val, min_val, best_node = 0;
6015 min_val = INT_MAX;
6017 for (i = 0; i < MAX_NUMNODES; i++) {
6018 /* Start at @node */
6019 n = (node + i) % MAX_NUMNODES;
6021 if (!nr_cpus_node(n))
6022 continue;
6024 /* Skip already used nodes */
6025 if (test_bit(n, used_nodes))
6026 continue;
6028 /* Simple min distance search */
6029 val = node_distance(node, n);
6031 if (val < min_val) {
6032 min_val = val;
6033 best_node = n;
6037 set_bit(best_node, used_nodes);
6038 return best_node;
6042 * sched_domain_node_span - get a cpumask for a node's sched_domain
6043 * @node: node whose cpumask we're constructing
6044 * @size: number of nodes to include in this span
6046 * Given a node, construct a good cpumask for its sched_domain to span. It
6047 * should be one that prevents unnecessary balancing, but also spreads tasks
6048 * out optimally.
6050 static cpumask_t sched_domain_node_span(int node)
6052 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6053 cpumask_t span, nodemask;
6054 int i;
6056 cpus_clear(span);
6057 bitmap_zero(used_nodes, MAX_NUMNODES);
6059 nodemask = node_to_cpumask(node);
6060 cpus_or(span, span, nodemask);
6061 set_bit(node, used_nodes);
6063 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6064 int next_node = find_next_best_node(node, used_nodes);
6066 nodemask = node_to_cpumask(next_node);
6067 cpus_or(span, span, nodemask);
6070 return span;
6072 #endif
6074 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6077 * SMT sched-domains:
6079 #ifdef CONFIG_SCHED_SMT
6080 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6081 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6083 static int
6084 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6086 if (sg)
6087 *sg = &per_cpu(sched_group_cpus, cpu);
6088 return cpu;
6090 #endif
6093 * multi-core sched-domains:
6095 #ifdef CONFIG_SCHED_MC
6096 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6097 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6098 #endif
6100 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6101 static int
6102 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6104 int group;
6105 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6106 cpus_and(mask, mask, *cpu_map);
6107 group = first_cpu(mask);
6108 if (sg)
6109 *sg = &per_cpu(sched_group_core, group);
6110 return group;
6112 #elif defined(CONFIG_SCHED_MC)
6113 static int
6114 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6116 if (sg)
6117 *sg = &per_cpu(sched_group_core, cpu);
6118 return cpu;
6120 #endif
6122 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6123 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6125 static int
6126 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6128 int group;
6129 #ifdef CONFIG_SCHED_MC
6130 cpumask_t mask = cpu_coregroup_map(cpu);
6131 cpus_and(mask, mask, *cpu_map);
6132 group = first_cpu(mask);
6133 #elif defined(CONFIG_SCHED_SMT)
6134 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6135 cpus_and(mask, mask, *cpu_map);
6136 group = first_cpu(mask);
6137 #else
6138 group = cpu;
6139 #endif
6140 if (sg)
6141 *sg = &per_cpu(sched_group_phys, group);
6142 return group;
6145 #ifdef CONFIG_NUMA
6147 * The init_sched_build_groups can't handle what we want to do with node
6148 * groups, so roll our own. Now each node has its own list of groups which
6149 * gets dynamically allocated.
6151 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6152 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6154 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6155 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6157 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6158 struct sched_group **sg)
6160 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6161 int group;
6163 cpus_and(nodemask, nodemask, *cpu_map);
6164 group = first_cpu(nodemask);
6166 if (sg)
6167 *sg = &per_cpu(sched_group_allnodes, group);
6168 return group;
6171 static void init_numa_sched_groups_power(struct sched_group *group_head)
6173 struct sched_group *sg = group_head;
6174 int j;
6176 if (!sg)
6177 return;
6178 do {
6179 for_each_cpu_mask(j, sg->cpumask) {
6180 struct sched_domain *sd;
6182 sd = &per_cpu(phys_domains, j);
6183 if (j != first_cpu(sd->groups->cpumask)) {
6185 * Only add "power" once for each
6186 * physical package.
6188 continue;
6191 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6193 sg = sg->next;
6194 } while (sg != group_head);
6196 #endif
6198 #ifdef CONFIG_NUMA
6199 /* Free memory allocated for various sched_group structures */
6200 static void free_sched_groups(const cpumask_t *cpu_map)
6202 int cpu, i;
6204 for_each_cpu_mask(cpu, *cpu_map) {
6205 struct sched_group **sched_group_nodes
6206 = sched_group_nodes_bycpu[cpu];
6208 if (!sched_group_nodes)
6209 continue;
6211 for (i = 0; i < MAX_NUMNODES; i++) {
6212 cpumask_t nodemask = node_to_cpumask(i);
6213 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6215 cpus_and(nodemask, nodemask, *cpu_map);
6216 if (cpus_empty(nodemask))
6217 continue;
6219 if (sg == NULL)
6220 continue;
6221 sg = sg->next;
6222 next_sg:
6223 oldsg = sg;
6224 sg = sg->next;
6225 kfree(oldsg);
6226 if (oldsg != sched_group_nodes[i])
6227 goto next_sg;
6229 kfree(sched_group_nodes);
6230 sched_group_nodes_bycpu[cpu] = NULL;
6233 #else
6234 static void free_sched_groups(const cpumask_t *cpu_map)
6237 #endif
6240 * Initialize sched groups cpu_power.
6242 * cpu_power indicates the capacity of sched group, which is used while
6243 * distributing the load between different sched groups in a sched domain.
6244 * Typically cpu_power for all the groups in a sched domain will be same unless
6245 * there are asymmetries in the topology. If there are asymmetries, group
6246 * having more cpu_power will pickup more load compared to the group having
6247 * less cpu_power.
6249 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6250 * the maximum number of tasks a group can handle in the presence of other idle
6251 * or lightly loaded groups in the same sched domain.
6253 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6255 struct sched_domain *child;
6256 struct sched_group *group;
6258 WARN_ON(!sd || !sd->groups);
6260 if (cpu != first_cpu(sd->groups->cpumask))
6261 return;
6263 child = sd->child;
6265 sd->groups->__cpu_power = 0;
6268 * For perf policy, if the groups in child domain share resources
6269 * (for example cores sharing some portions of the cache hierarchy
6270 * or SMT), then set this domain groups cpu_power such that each group
6271 * can handle only one task, when there are other idle groups in the
6272 * same sched domain.
6274 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6275 (child->flags &
6276 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6277 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6278 return;
6282 * add cpu_power of each child group to this groups cpu_power
6284 group = child->groups;
6285 do {
6286 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6287 group = group->next;
6288 } while (group != child->groups);
6292 * Build sched domains for a given set of cpus and attach the sched domains
6293 * to the individual cpus
6295 static int build_sched_domains(const cpumask_t *cpu_map)
6297 int i;
6298 struct root_domain *rd;
6299 #ifdef CONFIG_NUMA
6300 struct sched_group **sched_group_nodes = NULL;
6301 int sd_allnodes = 0;
6304 * Allocate the per-node list of sched groups
6306 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6307 GFP_KERNEL);
6308 if (!sched_group_nodes) {
6309 printk(KERN_WARNING "Can not alloc sched group node list\n");
6310 return -ENOMEM;
6312 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6313 #endif
6315 rd = alloc_rootdomain(cpu_map);
6316 if (!rd) {
6317 printk(KERN_WARNING "Cannot alloc root domain\n");
6318 return -ENOMEM;
6322 * Set up domains for cpus specified by the cpu_map.
6324 for_each_cpu_mask(i, *cpu_map) {
6325 struct sched_domain *sd = NULL, *p;
6326 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6328 cpus_and(nodemask, nodemask, *cpu_map);
6330 #ifdef CONFIG_NUMA
6331 if (cpus_weight(*cpu_map) >
6332 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6333 sd = &per_cpu(allnodes_domains, i);
6334 *sd = SD_ALLNODES_INIT;
6335 sd->span = *cpu_map;
6336 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6337 p = sd;
6338 sd_allnodes = 1;
6339 } else
6340 p = NULL;
6342 sd = &per_cpu(node_domains, i);
6343 *sd = SD_NODE_INIT;
6344 sd->span = sched_domain_node_span(cpu_to_node(i));
6345 sd->parent = p;
6346 if (p)
6347 p->child = sd;
6348 cpus_and(sd->span, sd->span, *cpu_map);
6349 #endif
6351 p = sd;
6352 sd = &per_cpu(phys_domains, i);
6353 *sd = SD_CPU_INIT;
6354 sd->span = nodemask;
6355 sd->parent = p;
6356 if (p)
6357 p->child = sd;
6358 cpu_to_phys_group(i, cpu_map, &sd->groups);
6360 #ifdef CONFIG_SCHED_MC
6361 p = sd;
6362 sd = &per_cpu(core_domains, i);
6363 *sd = SD_MC_INIT;
6364 sd->span = cpu_coregroup_map(i);
6365 cpus_and(sd->span, sd->span, *cpu_map);
6366 sd->parent = p;
6367 p->child = sd;
6368 cpu_to_core_group(i, cpu_map, &sd->groups);
6369 #endif
6371 #ifdef CONFIG_SCHED_SMT
6372 p = sd;
6373 sd = &per_cpu(cpu_domains, i);
6374 *sd = SD_SIBLING_INIT;
6375 sd->span = per_cpu(cpu_sibling_map, i);
6376 cpus_and(sd->span, sd->span, *cpu_map);
6377 sd->parent = p;
6378 p->child = sd;
6379 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6380 #endif
6383 #ifdef CONFIG_SCHED_SMT
6384 /* Set up CPU (sibling) groups */
6385 for_each_cpu_mask(i, *cpu_map) {
6386 cpumask_t this_sibling_map = per_cpu(cpu_sibling_map, i);
6387 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6388 if (i != first_cpu(this_sibling_map))
6389 continue;
6391 init_sched_build_groups(this_sibling_map, cpu_map,
6392 &cpu_to_cpu_group);
6394 #endif
6396 #ifdef CONFIG_SCHED_MC
6397 /* Set up multi-core groups */
6398 for_each_cpu_mask(i, *cpu_map) {
6399 cpumask_t this_core_map = cpu_coregroup_map(i);
6400 cpus_and(this_core_map, this_core_map, *cpu_map);
6401 if (i != first_cpu(this_core_map))
6402 continue;
6403 init_sched_build_groups(this_core_map, cpu_map,
6404 &cpu_to_core_group);
6406 #endif
6408 /* Set up physical groups */
6409 for (i = 0; i < MAX_NUMNODES; i++) {
6410 cpumask_t nodemask = node_to_cpumask(i);
6412 cpus_and(nodemask, nodemask, *cpu_map);
6413 if (cpus_empty(nodemask))
6414 continue;
6416 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6419 #ifdef CONFIG_NUMA
6420 /* Set up node groups */
6421 if (sd_allnodes)
6422 init_sched_build_groups(*cpu_map, cpu_map,
6423 &cpu_to_allnodes_group);
6425 for (i = 0; i < MAX_NUMNODES; i++) {
6426 /* Set up node groups */
6427 struct sched_group *sg, *prev;
6428 cpumask_t nodemask = node_to_cpumask(i);
6429 cpumask_t domainspan;
6430 cpumask_t covered = CPU_MASK_NONE;
6431 int j;
6433 cpus_and(nodemask, nodemask, *cpu_map);
6434 if (cpus_empty(nodemask)) {
6435 sched_group_nodes[i] = NULL;
6436 continue;
6439 domainspan = sched_domain_node_span(i);
6440 cpus_and(domainspan, domainspan, *cpu_map);
6442 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6443 if (!sg) {
6444 printk(KERN_WARNING "Can not alloc domain group for "
6445 "node %d\n", i);
6446 goto error;
6448 sched_group_nodes[i] = sg;
6449 for_each_cpu_mask(j, nodemask) {
6450 struct sched_domain *sd;
6452 sd = &per_cpu(node_domains, j);
6453 sd->groups = sg;
6455 sg->__cpu_power = 0;
6456 sg->cpumask = nodemask;
6457 sg->next = sg;
6458 cpus_or(covered, covered, nodemask);
6459 prev = sg;
6461 for (j = 0; j < MAX_NUMNODES; j++) {
6462 cpumask_t tmp, notcovered;
6463 int n = (i + j) % MAX_NUMNODES;
6465 cpus_complement(notcovered, covered);
6466 cpus_and(tmp, notcovered, *cpu_map);
6467 cpus_and(tmp, tmp, domainspan);
6468 if (cpus_empty(tmp))
6469 break;
6471 nodemask = node_to_cpumask(n);
6472 cpus_and(tmp, tmp, nodemask);
6473 if (cpus_empty(tmp))
6474 continue;
6476 sg = kmalloc_node(sizeof(struct sched_group),
6477 GFP_KERNEL, i);
6478 if (!sg) {
6479 printk(KERN_WARNING
6480 "Can not alloc domain group for node %d\n", j);
6481 goto error;
6483 sg->__cpu_power = 0;
6484 sg->cpumask = tmp;
6485 sg->next = prev->next;
6486 cpus_or(covered, covered, tmp);
6487 prev->next = sg;
6488 prev = sg;
6491 #endif
6493 /* Calculate CPU power for physical packages and nodes */
6494 #ifdef CONFIG_SCHED_SMT
6495 for_each_cpu_mask(i, *cpu_map) {
6496 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6498 init_sched_groups_power(i, sd);
6500 #endif
6501 #ifdef CONFIG_SCHED_MC
6502 for_each_cpu_mask(i, *cpu_map) {
6503 struct sched_domain *sd = &per_cpu(core_domains, i);
6505 init_sched_groups_power(i, sd);
6507 #endif
6509 for_each_cpu_mask(i, *cpu_map) {
6510 struct sched_domain *sd = &per_cpu(phys_domains, i);
6512 init_sched_groups_power(i, sd);
6515 #ifdef CONFIG_NUMA
6516 for (i = 0; i < MAX_NUMNODES; i++)
6517 init_numa_sched_groups_power(sched_group_nodes[i]);
6519 if (sd_allnodes) {
6520 struct sched_group *sg;
6522 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6523 init_numa_sched_groups_power(sg);
6525 #endif
6527 /* Attach the domains */
6528 for_each_cpu_mask(i, *cpu_map) {
6529 struct sched_domain *sd;
6530 #ifdef CONFIG_SCHED_SMT
6531 sd = &per_cpu(cpu_domains, i);
6532 #elif defined(CONFIG_SCHED_MC)
6533 sd = &per_cpu(core_domains, i);
6534 #else
6535 sd = &per_cpu(phys_domains, i);
6536 #endif
6537 cpu_attach_domain(sd, rd, i);
6540 return 0;
6542 #ifdef CONFIG_NUMA
6543 error:
6544 free_sched_groups(cpu_map);
6545 return -ENOMEM;
6546 #endif
6549 static cpumask_t *doms_cur; /* current sched domains */
6550 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
6553 * Special case: If a kmalloc of a doms_cur partition (array of
6554 * cpumask_t) fails, then fallback to a single sched domain,
6555 * as determined by the single cpumask_t fallback_doms.
6557 static cpumask_t fallback_doms;
6560 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6561 * For now this just excludes isolated cpus, but could be used to
6562 * exclude other special cases in the future.
6564 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6566 int err;
6568 ndoms_cur = 1;
6569 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6570 if (!doms_cur)
6571 doms_cur = &fallback_doms;
6572 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
6573 err = build_sched_domains(doms_cur);
6574 register_sched_domain_sysctl();
6576 return err;
6579 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6581 free_sched_groups(cpu_map);
6585 * Detach sched domains from a group of cpus specified in cpu_map
6586 * These cpus will now be attached to the NULL domain
6588 static void detach_destroy_domains(const cpumask_t *cpu_map)
6590 int i;
6592 unregister_sched_domain_sysctl();
6594 for_each_cpu_mask(i, *cpu_map)
6595 cpu_attach_domain(NULL, &def_root_domain, i);
6596 synchronize_sched();
6597 arch_destroy_sched_domains(cpu_map);
6601 * Partition sched domains as specified by the 'ndoms_new'
6602 * cpumasks in the array doms_new[] of cpumasks. This compares
6603 * doms_new[] to the current sched domain partitioning, doms_cur[].
6604 * It destroys each deleted domain and builds each new domain.
6606 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6607 * The masks don't intersect (don't overlap.) We should setup one
6608 * sched domain for each mask. CPUs not in any of the cpumasks will
6609 * not be load balanced. If the same cpumask appears both in the
6610 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6611 * it as it is.
6613 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6614 * ownership of it and will kfree it when done with it. If the caller
6615 * failed the kmalloc call, then it can pass in doms_new == NULL,
6616 * and partition_sched_domains() will fallback to the single partition
6617 * 'fallback_doms'.
6619 * Call with hotplug lock held
6621 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
6623 int i, j;
6625 lock_doms_cur();
6627 /* always unregister in case we don't destroy any domains */
6628 unregister_sched_domain_sysctl();
6630 if (doms_new == NULL) {
6631 ndoms_new = 1;
6632 doms_new = &fallback_doms;
6633 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
6636 /* Destroy deleted domains */
6637 for (i = 0; i < ndoms_cur; i++) {
6638 for (j = 0; j < ndoms_new; j++) {
6639 if (cpus_equal(doms_cur[i], doms_new[j]))
6640 goto match1;
6642 /* no match - a current sched domain not in new doms_new[] */
6643 detach_destroy_domains(doms_cur + i);
6644 match1:
6648 /* Build new domains */
6649 for (i = 0; i < ndoms_new; i++) {
6650 for (j = 0; j < ndoms_cur; j++) {
6651 if (cpus_equal(doms_new[i], doms_cur[j]))
6652 goto match2;
6654 /* no match - add a new doms_new */
6655 build_sched_domains(doms_new + i);
6656 match2:
6660 /* Remember the new sched domains */
6661 if (doms_cur != &fallback_doms)
6662 kfree(doms_cur);
6663 doms_cur = doms_new;
6664 ndoms_cur = ndoms_new;
6666 register_sched_domain_sysctl();
6668 unlock_doms_cur();
6671 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6672 static int arch_reinit_sched_domains(void)
6674 int err;
6676 get_online_cpus();
6677 detach_destroy_domains(&cpu_online_map);
6678 err = arch_init_sched_domains(&cpu_online_map);
6679 put_online_cpus();
6681 return err;
6684 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6686 int ret;
6688 if (buf[0] != '0' && buf[0] != '1')
6689 return -EINVAL;
6691 if (smt)
6692 sched_smt_power_savings = (buf[0] == '1');
6693 else
6694 sched_mc_power_savings = (buf[0] == '1');
6696 ret = arch_reinit_sched_domains();
6698 return ret ? ret : count;
6701 #ifdef CONFIG_SCHED_MC
6702 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6704 return sprintf(page, "%u\n", sched_mc_power_savings);
6706 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6707 const char *buf, size_t count)
6709 return sched_power_savings_store(buf, count, 0);
6711 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6712 sched_mc_power_savings_store);
6713 #endif
6715 #ifdef CONFIG_SCHED_SMT
6716 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6718 return sprintf(page, "%u\n", sched_smt_power_savings);
6720 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6721 const char *buf, size_t count)
6723 return sched_power_savings_store(buf, count, 1);
6725 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6726 sched_smt_power_savings_store);
6727 #endif
6729 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6731 int err = 0;
6733 #ifdef CONFIG_SCHED_SMT
6734 if (smt_capable())
6735 err = sysfs_create_file(&cls->kset.kobj,
6736 &attr_sched_smt_power_savings.attr);
6737 #endif
6738 #ifdef CONFIG_SCHED_MC
6739 if (!err && mc_capable())
6740 err = sysfs_create_file(&cls->kset.kobj,
6741 &attr_sched_mc_power_savings.attr);
6742 #endif
6743 return err;
6745 #endif
6748 * Force a reinitialization of the sched domains hierarchy. The domains
6749 * and groups cannot be updated in place without racing with the balancing
6750 * code, so we temporarily attach all running cpus to the NULL domain
6751 * which will prevent rebalancing while the sched domains are recalculated.
6753 static int update_sched_domains(struct notifier_block *nfb,
6754 unsigned long action, void *hcpu)
6756 switch (action) {
6757 case CPU_UP_PREPARE:
6758 case CPU_UP_PREPARE_FROZEN:
6759 case CPU_DOWN_PREPARE:
6760 case CPU_DOWN_PREPARE_FROZEN:
6761 detach_destroy_domains(&cpu_online_map);
6762 return NOTIFY_OK;
6764 case CPU_UP_CANCELED:
6765 case CPU_UP_CANCELED_FROZEN:
6766 case CPU_DOWN_FAILED:
6767 case CPU_DOWN_FAILED_FROZEN:
6768 case CPU_ONLINE:
6769 case CPU_ONLINE_FROZEN:
6770 case CPU_DEAD:
6771 case CPU_DEAD_FROZEN:
6773 * Fall through and re-initialise the domains.
6775 break;
6776 default:
6777 return NOTIFY_DONE;
6780 /* The hotplug lock is already held by cpu_up/cpu_down */
6781 arch_init_sched_domains(&cpu_online_map);
6783 return NOTIFY_OK;
6786 void __init sched_init_smp(void)
6788 cpumask_t non_isolated_cpus;
6790 get_online_cpus();
6791 arch_init_sched_domains(&cpu_online_map);
6792 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
6793 if (cpus_empty(non_isolated_cpus))
6794 cpu_set(smp_processor_id(), non_isolated_cpus);
6795 put_online_cpus();
6796 /* XXX: Theoretical race here - CPU may be hotplugged now */
6797 hotcpu_notifier(update_sched_domains, 0);
6799 /* Move init over to a non-isolated CPU */
6800 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
6801 BUG();
6802 sched_init_granularity();
6804 #ifdef CONFIG_FAIR_GROUP_SCHED
6805 if (nr_cpu_ids == 1)
6806 return;
6808 lb_monitor_task = kthread_create(load_balance_monitor, NULL,
6809 "group_balance");
6810 if (!IS_ERR(lb_monitor_task)) {
6811 lb_monitor_task->flags |= PF_NOFREEZE;
6812 wake_up_process(lb_monitor_task);
6813 } else {
6814 printk(KERN_ERR "Could not create load balance monitor thread"
6815 "(error = %ld) \n", PTR_ERR(lb_monitor_task));
6817 #endif
6819 #else
6820 void __init sched_init_smp(void)
6822 sched_init_granularity();
6824 #endif /* CONFIG_SMP */
6826 int in_sched_functions(unsigned long addr)
6828 return in_lock_functions(addr) ||
6829 (addr >= (unsigned long)__sched_text_start
6830 && addr < (unsigned long)__sched_text_end);
6833 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
6835 cfs_rq->tasks_timeline = RB_ROOT;
6836 #ifdef CONFIG_FAIR_GROUP_SCHED
6837 cfs_rq->rq = rq;
6838 #endif
6839 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
6842 void __init sched_init(void)
6844 int highest_cpu = 0;
6845 int i, j;
6847 #ifdef CONFIG_SMP
6848 init_defrootdomain();
6849 #endif
6851 for_each_possible_cpu(i) {
6852 struct rt_prio_array *array;
6853 struct rq *rq;
6855 rq = cpu_rq(i);
6856 spin_lock_init(&rq->lock);
6857 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6858 rq->nr_running = 0;
6859 rq->clock = 1;
6860 init_cfs_rq(&rq->cfs, rq);
6861 #ifdef CONFIG_FAIR_GROUP_SCHED
6862 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6864 struct cfs_rq *cfs_rq = &per_cpu(init_cfs_rq, i);
6865 struct sched_entity *se =
6866 &per_cpu(init_sched_entity, i);
6868 init_cfs_rq_p[i] = cfs_rq;
6869 init_cfs_rq(cfs_rq, rq);
6870 cfs_rq->tg = &init_task_group;
6871 list_add(&cfs_rq->leaf_cfs_rq_list,
6872 &rq->leaf_cfs_rq_list);
6874 init_sched_entity_p[i] = se;
6875 se->cfs_rq = &rq->cfs;
6876 se->my_q = cfs_rq;
6877 se->load.weight = init_task_group_load;
6878 se->load.inv_weight =
6879 div64_64(1ULL<<32, init_task_group_load);
6880 se->parent = NULL;
6882 init_task_group.shares = init_task_group_load;
6883 #endif
6885 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6886 rq->cpu_load[j] = 0;
6887 #ifdef CONFIG_SMP
6888 rq->sd = NULL;
6889 rq->rd = NULL;
6890 rq_attach_root(rq, &def_root_domain);
6891 rq->active_balance = 0;
6892 rq->next_balance = jiffies;
6893 rq->push_cpu = 0;
6894 rq->cpu = i;
6895 rq->migration_thread = NULL;
6896 INIT_LIST_HEAD(&rq->migration_queue);
6897 rq->rt.highest_prio = MAX_RT_PRIO;
6898 rq->rt.overloaded = 0;
6899 #endif
6900 atomic_set(&rq->nr_iowait, 0);
6902 array = &rq->rt.active;
6903 for (j = 0; j < MAX_RT_PRIO; j++) {
6904 INIT_LIST_HEAD(array->queue + j);
6905 __clear_bit(j, array->bitmap);
6907 highest_cpu = i;
6908 /* delimiter for bitsearch: */
6909 __set_bit(MAX_RT_PRIO, array->bitmap);
6912 set_load_weight(&init_task);
6914 #ifdef CONFIG_PREEMPT_NOTIFIERS
6915 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
6916 #endif
6918 #ifdef CONFIG_SMP
6919 nr_cpu_ids = highest_cpu + 1;
6920 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
6921 #endif
6923 #ifdef CONFIG_RT_MUTEXES
6924 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
6925 #endif
6928 * The boot idle thread does lazy MMU switching as well:
6930 atomic_inc(&init_mm.mm_count);
6931 enter_lazy_tlb(&init_mm, current);
6934 * Make us the idle thread. Technically, schedule() should not be
6935 * called from this thread, however somewhere below it might be,
6936 * but because we are the idle thread, we just pick up running again
6937 * when this runqueue becomes "idle".
6939 init_idle(current, smp_processor_id());
6941 * During early bootup we pretend to be a normal task:
6943 current->sched_class = &fair_sched_class;
6946 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6947 void __might_sleep(char *file, int line)
6949 #ifdef in_atomic
6950 static unsigned long prev_jiffy; /* ratelimiting */
6952 if ((in_atomic() || irqs_disabled()) &&
6953 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6954 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6955 return;
6956 prev_jiffy = jiffies;
6957 printk(KERN_ERR "BUG: sleeping function called from invalid"
6958 " context at %s:%d\n", file, line);
6959 printk("in_atomic():%d, irqs_disabled():%d\n",
6960 in_atomic(), irqs_disabled());
6961 debug_show_held_locks(current);
6962 if (irqs_disabled())
6963 print_irqtrace_events(current);
6964 dump_stack();
6966 #endif
6968 EXPORT_SYMBOL(__might_sleep);
6969 #endif
6971 #ifdef CONFIG_MAGIC_SYSRQ
6972 static void normalize_task(struct rq *rq, struct task_struct *p)
6974 int on_rq;
6975 update_rq_clock(rq);
6976 on_rq = p->se.on_rq;
6977 if (on_rq)
6978 deactivate_task(rq, p, 0);
6979 __setscheduler(rq, p, SCHED_NORMAL, 0);
6980 if (on_rq) {
6981 activate_task(rq, p, 0);
6982 resched_task(rq->curr);
6986 void normalize_rt_tasks(void)
6988 struct task_struct *g, *p;
6989 unsigned long flags;
6990 struct rq *rq;
6992 read_lock_irq(&tasklist_lock);
6993 do_each_thread(g, p) {
6995 * Only normalize user tasks:
6997 if (!p->mm)
6998 continue;
7000 p->se.exec_start = 0;
7001 #ifdef CONFIG_SCHEDSTATS
7002 p->se.wait_start = 0;
7003 p->se.sleep_start = 0;
7004 p->se.block_start = 0;
7005 #endif
7006 task_rq(p)->clock = 0;
7008 if (!rt_task(p)) {
7010 * Renice negative nice level userspace
7011 * tasks back to 0:
7013 if (TASK_NICE(p) < 0 && p->mm)
7014 set_user_nice(p, 0);
7015 continue;
7018 spin_lock_irqsave(&p->pi_lock, flags);
7019 rq = __task_rq_lock(p);
7021 normalize_task(rq, p);
7023 __task_rq_unlock(rq);
7024 spin_unlock_irqrestore(&p->pi_lock, flags);
7025 } while_each_thread(g, p);
7027 read_unlock_irq(&tasklist_lock);
7030 #endif /* CONFIG_MAGIC_SYSRQ */
7032 #ifdef CONFIG_IA64
7034 * These functions are only useful for the IA64 MCA handling.
7036 * They can only be called when the whole system has been
7037 * stopped - every CPU needs to be quiescent, and no scheduling
7038 * activity can take place. Using them for anything else would
7039 * be a serious bug, and as a result, they aren't even visible
7040 * under any other configuration.
7044 * curr_task - return the current task for a given cpu.
7045 * @cpu: the processor in question.
7047 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7049 struct task_struct *curr_task(int cpu)
7051 return cpu_curr(cpu);
7055 * set_curr_task - set the current task for a given cpu.
7056 * @cpu: the processor in question.
7057 * @p: the task pointer to set.
7059 * Description: This function must only be used when non-maskable interrupts
7060 * are serviced on a separate stack. It allows the architecture to switch the
7061 * notion of the current task on a cpu in a non-blocking manner. This function
7062 * must be called with all CPU's synchronized, and interrupts disabled, the
7063 * and caller must save the original value of the current task (see
7064 * curr_task() above) and restore that value before reenabling interrupts and
7065 * re-starting the system.
7067 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7069 void set_curr_task(int cpu, struct task_struct *p)
7071 cpu_curr(cpu) = p;
7074 #endif
7076 #ifdef CONFIG_FAIR_GROUP_SCHED
7078 #ifdef CONFIG_SMP
7080 * distribute shares of all task groups among their schedulable entities,
7081 * to reflect load distrbution across cpus.
7083 static int rebalance_shares(struct sched_domain *sd, int this_cpu)
7085 struct cfs_rq *cfs_rq;
7086 struct rq *rq = cpu_rq(this_cpu);
7087 cpumask_t sdspan = sd->span;
7088 int balanced = 1;
7090 /* Walk thr' all the task groups that we have */
7091 for_each_leaf_cfs_rq(rq, cfs_rq) {
7092 int i;
7093 unsigned long total_load = 0, total_shares;
7094 struct task_group *tg = cfs_rq->tg;
7096 /* Gather total task load of this group across cpus */
7097 for_each_cpu_mask(i, sdspan)
7098 total_load += tg->cfs_rq[i]->load.weight;
7100 /* Nothing to do if this group has no load */
7101 if (!total_load)
7102 continue;
7105 * tg->shares represents the number of cpu shares the task group
7106 * is eligible to hold on a single cpu. On N cpus, it is
7107 * eligible to hold (N * tg->shares) number of cpu shares.
7109 total_shares = tg->shares * cpus_weight(sdspan);
7112 * redistribute total_shares across cpus as per the task load
7113 * distribution.
7115 for_each_cpu_mask(i, sdspan) {
7116 unsigned long local_load, local_shares;
7118 local_load = tg->cfs_rq[i]->load.weight;
7119 local_shares = (local_load * total_shares) / total_load;
7120 if (!local_shares)
7121 local_shares = MIN_GROUP_SHARES;
7122 if (local_shares == tg->se[i]->load.weight)
7123 continue;
7125 spin_lock_irq(&cpu_rq(i)->lock);
7126 set_se_shares(tg->se[i], local_shares);
7127 spin_unlock_irq(&cpu_rq(i)->lock);
7128 balanced = 0;
7132 return balanced;
7136 * How frequently should we rebalance_shares() across cpus?
7138 * The more frequently we rebalance shares, the more accurate is the fairness
7139 * of cpu bandwidth distribution between task groups. However higher frequency
7140 * also implies increased scheduling overhead.
7142 * sysctl_sched_min_bal_int_shares represents the minimum interval between
7143 * consecutive calls to rebalance_shares() in the same sched domain.
7145 * sysctl_sched_max_bal_int_shares represents the maximum interval between
7146 * consecutive calls to rebalance_shares() in the same sched domain.
7148 * These settings allows for the appropriate tradeoff between accuracy of
7149 * fairness and the associated overhead.
7153 /* default: 8ms, units: milliseconds */
7154 const_debug unsigned int sysctl_sched_min_bal_int_shares = 8;
7156 /* default: 128ms, units: milliseconds */
7157 const_debug unsigned int sysctl_sched_max_bal_int_shares = 128;
7159 /* kernel thread that runs rebalance_shares() periodically */
7160 static int load_balance_monitor(void *unused)
7162 unsigned int timeout = sysctl_sched_min_bal_int_shares;
7163 struct sched_param schedparm;
7164 int ret;
7167 * We don't want this thread's execution to be limited by the shares
7168 * assigned to default group (init_task_group). Hence make it run
7169 * as a SCHED_RR RT task at the lowest priority.
7171 schedparm.sched_priority = 1;
7172 ret = sched_setscheduler(current, SCHED_RR, &schedparm);
7173 if (ret)
7174 printk(KERN_ERR "Couldn't set SCHED_RR policy for load balance"
7175 " monitor thread (error = %d) \n", ret);
7177 while (!kthread_should_stop()) {
7178 int i, cpu, balanced = 1;
7180 /* Prevent cpus going down or coming up */
7181 get_online_cpus();
7182 /* lockout changes to doms_cur[] array */
7183 lock_doms_cur();
7185 * Enter a rcu read-side critical section to safely walk rq->sd
7186 * chain on various cpus and to walk task group list
7187 * (rq->leaf_cfs_rq_list) in rebalance_shares().
7189 rcu_read_lock();
7191 for (i = 0; i < ndoms_cur; i++) {
7192 cpumask_t cpumap = doms_cur[i];
7193 struct sched_domain *sd = NULL, *sd_prev = NULL;
7195 cpu = first_cpu(cpumap);
7197 /* Find the highest domain at which to balance shares */
7198 for_each_domain(cpu, sd) {
7199 if (!(sd->flags & SD_LOAD_BALANCE))
7200 continue;
7201 sd_prev = sd;
7204 sd = sd_prev;
7205 /* sd == NULL? No load balance reqd in this domain */
7206 if (!sd)
7207 continue;
7209 balanced &= rebalance_shares(sd, cpu);
7212 rcu_read_unlock();
7214 unlock_doms_cur();
7215 put_online_cpus();
7217 if (!balanced)
7218 timeout = sysctl_sched_min_bal_int_shares;
7219 else if (timeout < sysctl_sched_max_bal_int_shares)
7220 timeout *= 2;
7222 msleep_interruptible(timeout);
7225 return 0;
7227 #endif /* CONFIG_SMP */
7229 /* allocate runqueue etc for a new task group */
7230 struct task_group *sched_create_group(void)
7232 struct task_group *tg;
7233 struct cfs_rq *cfs_rq;
7234 struct sched_entity *se;
7235 struct rq *rq;
7236 int i;
7238 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7239 if (!tg)
7240 return ERR_PTR(-ENOMEM);
7242 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
7243 if (!tg->cfs_rq)
7244 goto err;
7245 tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
7246 if (!tg->se)
7247 goto err;
7249 for_each_possible_cpu(i) {
7250 rq = cpu_rq(i);
7252 cfs_rq = kmalloc_node(sizeof(struct cfs_rq), GFP_KERNEL,
7253 cpu_to_node(i));
7254 if (!cfs_rq)
7255 goto err;
7257 se = kmalloc_node(sizeof(struct sched_entity), GFP_KERNEL,
7258 cpu_to_node(i));
7259 if (!se)
7260 goto err;
7262 memset(cfs_rq, 0, sizeof(struct cfs_rq));
7263 memset(se, 0, sizeof(struct sched_entity));
7265 tg->cfs_rq[i] = cfs_rq;
7266 init_cfs_rq(cfs_rq, rq);
7267 cfs_rq->tg = tg;
7269 tg->se[i] = se;
7270 se->cfs_rq = &rq->cfs;
7271 se->my_q = cfs_rq;
7272 se->load.weight = NICE_0_LOAD;
7273 se->load.inv_weight = div64_64(1ULL<<32, NICE_0_LOAD);
7274 se->parent = NULL;
7277 tg->shares = NICE_0_LOAD;
7279 lock_task_group_list();
7280 for_each_possible_cpu(i) {
7281 rq = cpu_rq(i);
7282 cfs_rq = tg->cfs_rq[i];
7283 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7285 unlock_task_group_list();
7287 return tg;
7289 err:
7290 for_each_possible_cpu(i) {
7291 if (tg->cfs_rq)
7292 kfree(tg->cfs_rq[i]);
7293 if (tg->se)
7294 kfree(tg->se[i]);
7296 kfree(tg->cfs_rq);
7297 kfree(tg->se);
7298 kfree(tg);
7300 return ERR_PTR(-ENOMEM);
7303 /* rcu callback to free various structures associated with a task group */
7304 static void free_sched_group(struct rcu_head *rhp)
7306 struct task_group *tg = container_of(rhp, struct task_group, rcu);
7307 struct cfs_rq *cfs_rq;
7308 struct sched_entity *se;
7309 int i;
7311 /* now it should be safe to free those cfs_rqs */
7312 for_each_possible_cpu(i) {
7313 cfs_rq = tg->cfs_rq[i];
7314 kfree(cfs_rq);
7316 se = tg->se[i];
7317 kfree(se);
7320 kfree(tg->cfs_rq);
7321 kfree(tg->se);
7322 kfree(tg);
7325 /* Destroy runqueue etc associated with a task group */
7326 void sched_destroy_group(struct task_group *tg)
7328 struct cfs_rq *cfs_rq = NULL;
7329 int i;
7331 lock_task_group_list();
7332 for_each_possible_cpu(i) {
7333 cfs_rq = tg->cfs_rq[i];
7334 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
7336 unlock_task_group_list();
7338 BUG_ON(!cfs_rq);
7340 /* wait for possible concurrent references to cfs_rqs complete */
7341 call_rcu(&tg->rcu, free_sched_group);
7344 /* change task's runqueue when it moves between groups.
7345 * The caller of this function should have put the task in its new group
7346 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7347 * reflect its new group.
7349 void sched_move_task(struct task_struct *tsk)
7351 int on_rq, running;
7352 unsigned long flags;
7353 struct rq *rq;
7355 rq = task_rq_lock(tsk, &flags);
7357 if (tsk->sched_class != &fair_sched_class) {
7358 set_task_cfs_rq(tsk, task_cpu(tsk));
7359 goto done;
7362 update_rq_clock(rq);
7364 running = task_current(rq, tsk);
7365 on_rq = tsk->se.on_rq;
7367 if (on_rq) {
7368 dequeue_task(rq, tsk, 0);
7369 if (unlikely(running))
7370 tsk->sched_class->put_prev_task(rq, tsk);
7373 set_task_cfs_rq(tsk, task_cpu(tsk));
7375 if (on_rq) {
7376 if (unlikely(running))
7377 tsk->sched_class->set_curr_task(rq);
7378 enqueue_task(rq, tsk, 0);
7381 done:
7382 task_rq_unlock(rq, &flags);
7385 /* rq->lock to be locked by caller */
7386 static void set_se_shares(struct sched_entity *se, unsigned long shares)
7388 struct cfs_rq *cfs_rq = se->cfs_rq;
7389 struct rq *rq = cfs_rq->rq;
7390 int on_rq;
7392 if (!shares)
7393 shares = MIN_GROUP_SHARES;
7395 on_rq = se->on_rq;
7396 if (on_rq) {
7397 dequeue_entity(cfs_rq, se, 0);
7398 dec_cpu_load(rq, se->load.weight);
7401 se->load.weight = shares;
7402 se->load.inv_weight = div64_64((1ULL<<32), shares);
7404 if (on_rq) {
7405 enqueue_entity(cfs_rq, se, 0);
7406 inc_cpu_load(rq, se->load.weight);
7410 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7412 int i;
7413 struct cfs_rq *cfs_rq;
7414 struct rq *rq;
7416 lock_task_group_list();
7417 if (tg->shares == shares)
7418 goto done;
7420 if (shares < MIN_GROUP_SHARES)
7421 shares = MIN_GROUP_SHARES;
7424 * Prevent any load balance activity (rebalance_shares,
7425 * load_balance_fair) from referring to this group first,
7426 * by taking it off the rq->leaf_cfs_rq_list on each cpu.
7428 for_each_possible_cpu(i) {
7429 cfs_rq = tg->cfs_rq[i];
7430 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
7433 /* wait for any ongoing reference to this group to finish */
7434 synchronize_sched();
7437 * Now we are free to modify the group's share on each cpu
7438 * w/o tripping rebalance_share or load_balance_fair.
7440 tg->shares = shares;
7441 for_each_possible_cpu(i) {
7442 spin_lock_irq(&cpu_rq(i)->lock);
7443 set_se_shares(tg->se[i], shares);
7444 spin_unlock_irq(&cpu_rq(i)->lock);
7448 * Enable load balance activity on this group, by inserting it back on
7449 * each cpu's rq->leaf_cfs_rq_list.
7451 for_each_possible_cpu(i) {
7452 rq = cpu_rq(i);
7453 cfs_rq = tg->cfs_rq[i];
7454 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7456 done:
7457 unlock_task_group_list();
7458 return 0;
7461 unsigned long sched_group_shares(struct task_group *tg)
7463 return tg->shares;
7466 #endif /* CONFIG_FAIR_GROUP_SCHED */
7468 #ifdef CONFIG_FAIR_CGROUP_SCHED
7470 /* return corresponding task_group object of a cgroup */
7471 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
7473 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7474 struct task_group, css);
7477 static struct cgroup_subsys_state *
7478 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
7480 struct task_group *tg;
7482 if (!cgrp->parent) {
7483 /* This is early initialization for the top cgroup */
7484 init_task_group.css.cgroup = cgrp;
7485 return &init_task_group.css;
7488 /* we support only 1-level deep hierarchical scheduler atm */
7489 if (cgrp->parent->parent)
7490 return ERR_PTR(-EINVAL);
7492 tg = sched_create_group();
7493 if (IS_ERR(tg))
7494 return ERR_PTR(-ENOMEM);
7496 /* Bind the cgroup to task_group object we just created */
7497 tg->css.cgroup = cgrp;
7499 return &tg->css;
7502 static void
7503 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
7505 struct task_group *tg = cgroup_tg(cgrp);
7507 sched_destroy_group(tg);
7510 static int
7511 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7512 struct task_struct *tsk)
7514 /* We don't support RT-tasks being in separate groups */
7515 if (tsk->sched_class != &fair_sched_class)
7516 return -EINVAL;
7518 return 0;
7521 static void
7522 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7523 struct cgroup *old_cont, struct task_struct *tsk)
7525 sched_move_task(tsk);
7528 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
7529 u64 shareval)
7531 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
7534 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
7536 struct task_group *tg = cgroup_tg(cgrp);
7538 return (u64) tg->shares;
7541 static struct cftype cpu_files[] = {
7543 .name = "shares",
7544 .read_uint = cpu_shares_read_uint,
7545 .write_uint = cpu_shares_write_uint,
7549 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
7551 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
7554 struct cgroup_subsys cpu_cgroup_subsys = {
7555 .name = "cpu",
7556 .create = cpu_cgroup_create,
7557 .destroy = cpu_cgroup_destroy,
7558 .can_attach = cpu_cgroup_can_attach,
7559 .attach = cpu_cgroup_attach,
7560 .populate = cpu_cgroup_populate,
7561 .subsys_id = cpu_cgroup_subsys_id,
7562 .early_init = 1,
7565 #endif /* CONFIG_FAIR_CGROUP_SCHED */
7567 #ifdef CONFIG_CGROUP_CPUACCT
7570 * CPU accounting code for task groups.
7572 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
7573 * (balbir@in.ibm.com).
7576 /* track cpu usage of a group of tasks */
7577 struct cpuacct {
7578 struct cgroup_subsys_state css;
7579 /* cpuusage holds pointer to a u64-type object on every cpu */
7580 u64 *cpuusage;
7583 struct cgroup_subsys cpuacct_subsys;
7585 /* return cpu accounting group corresponding to this container */
7586 static inline struct cpuacct *cgroup_ca(struct cgroup *cont)
7588 return container_of(cgroup_subsys_state(cont, cpuacct_subsys_id),
7589 struct cpuacct, css);
7592 /* return cpu accounting group to which this task belongs */
7593 static inline struct cpuacct *task_ca(struct task_struct *tsk)
7595 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
7596 struct cpuacct, css);
7599 /* create a new cpu accounting group */
7600 static struct cgroup_subsys_state *cpuacct_create(
7601 struct cgroup_subsys *ss, struct cgroup *cont)
7603 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
7605 if (!ca)
7606 return ERR_PTR(-ENOMEM);
7608 ca->cpuusage = alloc_percpu(u64);
7609 if (!ca->cpuusage) {
7610 kfree(ca);
7611 return ERR_PTR(-ENOMEM);
7614 return &ca->css;
7617 /* destroy an existing cpu accounting group */
7618 static void
7619 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
7621 struct cpuacct *ca = cgroup_ca(cont);
7623 free_percpu(ca->cpuusage);
7624 kfree(ca);
7627 /* return total cpu usage (in nanoseconds) of a group */
7628 static u64 cpuusage_read(struct cgroup *cont, struct cftype *cft)
7630 struct cpuacct *ca = cgroup_ca(cont);
7631 u64 totalcpuusage = 0;
7632 int i;
7634 for_each_possible_cpu(i) {
7635 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
7638 * Take rq->lock to make 64-bit addition safe on 32-bit
7639 * platforms.
7641 spin_lock_irq(&cpu_rq(i)->lock);
7642 totalcpuusage += *cpuusage;
7643 spin_unlock_irq(&cpu_rq(i)->lock);
7646 return totalcpuusage;
7649 static struct cftype files[] = {
7651 .name = "usage",
7652 .read_uint = cpuusage_read,
7656 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cont)
7658 return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
7662 * charge this task's execution time to its accounting group.
7664 * called with rq->lock held.
7666 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
7668 struct cpuacct *ca;
7670 if (!cpuacct_subsys.active)
7671 return;
7673 ca = task_ca(tsk);
7674 if (ca) {
7675 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
7677 *cpuusage += cputime;
7681 struct cgroup_subsys cpuacct_subsys = {
7682 .name = "cpuacct",
7683 .create = cpuacct_create,
7684 .destroy = cpuacct_destroy,
7685 .populate = cpuacct_populate,
7686 .subsys_id = cpuacct_subsys_id,
7688 #endif /* CONFIG_CGROUP_CPUACCT */