Committer: Michael Beasley <mike@snafu.setup>
[mikesnafu-overlay.git] / kernel / sched.c
blob1e4596c68dd0bef405c2f42a0dbf19d241fc6c8d
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
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/kthread.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
70 #include <asm/tlb.h>
71 #include <asm/irq_regs.h>
74 * Scheduler clock - returns current time in nanosec units.
75 * This is default implementation.
76 * Architectures and sub-architectures can override this.
78 unsigned long long __attribute__((weak)) sched_clock(void)
80 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
84 * Convert user-nice values [ -20 ... 0 ... 19 ]
85 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
86 * and back.
88 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
89 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
90 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
93 * 'User priority' is the nice value converted to something we
94 * can work with better when scaling various scheduler parameters,
95 * it's a [ 0 ... 39 ] range.
97 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
98 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
99 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
102 * Helpers for converting nanosecond timing to jiffy resolution
104 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
106 #define NICE_0_LOAD SCHED_LOAD_SCALE
107 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
110 * These are the 'tuning knobs' of the scheduler:
112 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
113 * Timeslices get refilled after they expire.
115 #define DEF_TIMESLICE (100 * HZ / 1000)
117 #ifdef CONFIG_SMP
119 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
120 * Since cpu_power is a 'constant', we can use a reciprocal divide.
122 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
124 return reciprocal_divide(load, sg->reciprocal_cpu_power);
128 * Each time a sched group cpu_power is changed,
129 * we must compute its reciprocal value
131 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
133 sg->__cpu_power += val;
134 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
136 #endif
138 static inline int rt_policy(int policy)
140 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
141 return 1;
142 return 0;
145 static inline int task_has_rt_policy(struct task_struct *p)
147 return rt_policy(p->policy);
151 * This is the priority-queue data structure of the RT scheduling class:
153 struct rt_prio_array {
154 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
155 struct list_head queue[MAX_RT_PRIO];
158 #ifdef CONFIG_GROUP_SCHED
160 #include <linux/cgroup.h>
162 struct cfs_rq;
164 static LIST_HEAD(task_groups);
166 /* task group related information */
167 struct task_group {
168 #ifdef CONFIG_CGROUP_SCHED
169 struct cgroup_subsys_state css;
170 #endif
172 #ifdef CONFIG_FAIR_GROUP_SCHED
173 /* schedulable entities of this group on each cpu */
174 struct sched_entity **se;
175 /* runqueue "owned" by this group on each cpu */
176 struct cfs_rq **cfs_rq;
177 unsigned long shares;
178 #endif
180 #ifdef CONFIG_RT_GROUP_SCHED
181 struct sched_rt_entity **rt_se;
182 struct rt_rq **rt_rq;
184 u64 rt_runtime;
185 #endif
187 struct rcu_head rcu;
188 struct list_head list;
191 #ifdef CONFIG_FAIR_GROUP_SCHED
192 /* Default task group's sched entity on each cpu */
193 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
194 /* Default task group's cfs_rq on each cpu */
195 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
197 static struct sched_entity *init_sched_entity_p[NR_CPUS];
198 static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
199 #endif
201 #ifdef CONFIG_RT_GROUP_SCHED
202 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
203 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
205 static struct sched_rt_entity *init_sched_rt_entity_p[NR_CPUS];
206 static struct rt_rq *init_rt_rq_p[NR_CPUS];
207 #endif
209 /* task_group_lock serializes add/remove of task groups and also changes to
210 * a task group's cpu shares.
212 static DEFINE_SPINLOCK(task_group_lock);
214 /* doms_cur_mutex serializes access to doms_cur[] array */
215 static DEFINE_MUTEX(doms_cur_mutex);
217 #ifdef CONFIG_FAIR_GROUP_SCHED
218 #ifdef CONFIG_USER_SCHED
219 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
220 #else
221 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
222 #endif
224 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
225 #endif
227 /* Default task group.
228 * Every task in system belong to this group at bootup.
230 struct task_group init_task_group = {
231 #ifdef CONFIG_FAIR_GROUP_SCHED
232 .se = init_sched_entity_p,
233 .cfs_rq = init_cfs_rq_p,
234 #endif
236 #ifdef CONFIG_RT_GROUP_SCHED
237 .rt_se = init_sched_rt_entity_p,
238 .rt_rq = init_rt_rq_p,
239 #endif
242 /* return group to which a task belongs */
243 static inline struct task_group *task_group(struct task_struct *p)
245 struct task_group *tg;
247 #ifdef CONFIG_USER_SCHED
248 tg = p->user->tg;
249 #elif defined(CONFIG_CGROUP_SCHED)
250 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
251 struct task_group, css);
252 #else
253 tg = &init_task_group;
254 #endif
255 return tg;
258 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
259 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
261 #ifdef CONFIG_FAIR_GROUP_SCHED
262 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
263 p->se.parent = task_group(p)->se[cpu];
264 #endif
266 #ifdef CONFIG_RT_GROUP_SCHED
267 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
268 p->rt.parent = task_group(p)->rt_se[cpu];
269 #endif
272 static inline void lock_doms_cur(void)
274 mutex_lock(&doms_cur_mutex);
277 static inline void unlock_doms_cur(void)
279 mutex_unlock(&doms_cur_mutex);
282 #else
284 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
285 static inline void lock_doms_cur(void) { }
286 static inline void unlock_doms_cur(void) { }
288 #endif /* CONFIG_GROUP_SCHED */
290 /* CFS-related fields in a runqueue */
291 struct cfs_rq {
292 struct load_weight load;
293 unsigned long nr_running;
295 u64 exec_clock;
296 u64 min_vruntime;
298 struct rb_root tasks_timeline;
299 struct rb_node *rb_leftmost;
300 struct rb_node *rb_load_balance_curr;
301 /* 'curr' points to currently running entity on this cfs_rq.
302 * It is set to NULL otherwise (i.e when none are currently running).
304 struct sched_entity *curr, *next;
306 unsigned long nr_spread_over;
308 #ifdef CONFIG_FAIR_GROUP_SCHED
309 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
312 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
313 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
314 * (like users, containers etc.)
316 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
317 * list is used during load balance.
319 struct list_head leaf_cfs_rq_list;
320 struct task_group *tg; /* group that "owns" this runqueue */
321 #endif
324 /* Real-Time classes' related field in a runqueue: */
325 struct rt_rq {
326 struct rt_prio_array active;
327 unsigned long rt_nr_running;
328 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
329 int highest_prio; /* highest queued rt task prio */
330 #endif
331 #ifdef CONFIG_SMP
332 unsigned long rt_nr_migratory;
333 int overloaded;
334 #endif
335 int rt_throttled;
336 u64 rt_time;
338 #ifdef CONFIG_RT_GROUP_SCHED
339 unsigned long rt_nr_boosted;
341 struct rq *rq;
342 struct list_head leaf_rt_rq_list;
343 struct task_group *tg;
344 struct sched_rt_entity *rt_se;
345 #endif
348 #ifdef CONFIG_SMP
351 * We add the notion of a root-domain which will be used to define per-domain
352 * variables. Each exclusive cpuset essentially defines an island domain by
353 * fully partitioning the member cpus from any other cpuset. Whenever a new
354 * exclusive cpuset is created, we also create and attach a new root-domain
355 * object.
358 struct root_domain {
359 atomic_t refcount;
360 cpumask_t span;
361 cpumask_t online;
364 * The "RT overload" flag: it gets set if a CPU has more than
365 * one runnable RT task.
367 cpumask_t rto_mask;
368 atomic_t rto_count;
372 * By default the system creates a single root-domain with all cpus as
373 * members (mimicking the global state we have today).
375 static struct root_domain def_root_domain;
377 #endif
380 * This is the main, per-CPU runqueue data structure.
382 * Locking rule: those places that want to lock multiple runqueues
383 * (such as the load balancing or the thread migration code), lock
384 * acquire operations must be ordered by ascending &runqueue.
386 struct rq {
387 /* runqueue lock: */
388 spinlock_t lock;
391 * nr_running and cpu_load should be in the same cacheline because
392 * remote CPUs use both these fields when doing load calculation.
394 unsigned long nr_running;
395 #define CPU_LOAD_IDX_MAX 5
396 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
397 unsigned char idle_at_tick;
398 #ifdef CONFIG_NO_HZ
399 unsigned char in_nohz_recently;
400 #endif
401 /* capture load from *all* tasks on this cpu: */
402 struct load_weight load;
403 unsigned long nr_load_updates;
404 u64 nr_switches;
406 struct cfs_rq cfs;
407 struct rt_rq rt;
408 u64 rt_period_expire;
409 int rt_throttled;
411 #ifdef CONFIG_FAIR_GROUP_SCHED
412 /* list of leaf cfs_rq on this cpu: */
413 struct list_head leaf_cfs_rq_list;
414 #endif
415 #ifdef CONFIG_RT_GROUP_SCHED
416 struct list_head leaf_rt_rq_list;
417 #endif
420 * This is part of a global counter where only the total sum
421 * over all CPUs matters. A task can increase this counter on
422 * one CPU and if it got migrated afterwards it may decrease
423 * it on another CPU. Always updated under the runqueue lock:
425 unsigned long nr_uninterruptible;
427 struct task_struct *curr, *idle;
428 unsigned long next_balance;
429 struct mm_struct *prev_mm;
431 u64 clock, prev_clock_raw;
432 s64 clock_max_delta;
434 unsigned int clock_warps, clock_overflows, clock_underflows;
435 u64 idle_clock;
436 unsigned int clock_deep_idle_events;
437 u64 tick_timestamp;
439 atomic_t nr_iowait;
441 #ifdef CONFIG_SMP
442 struct root_domain *rd;
443 struct sched_domain *sd;
445 /* For active balancing */
446 int active_balance;
447 int push_cpu;
448 /* cpu of this runqueue: */
449 int cpu;
451 struct task_struct *migration_thread;
452 struct list_head migration_queue;
453 #endif
455 #ifdef CONFIG_SCHED_HRTICK
456 unsigned long hrtick_flags;
457 ktime_t hrtick_expire;
458 struct hrtimer hrtick_timer;
459 #endif
461 #ifdef CONFIG_SCHEDSTATS
462 /* latency stats */
463 struct sched_info rq_sched_info;
465 /* sys_sched_yield() stats */
466 unsigned int yld_exp_empty;
467 unsigned int yld_act_empty;
468 unsigned int yld_both_empty;
469 unsigned int yld_count;
471 /* schedule() stats */
472 unsigned int sched_switch;
473 unsigned int sched_count;
474 unsigned int sched_goidle;
476 /* try_to_wake_up() stats */
477 unsigned int ttwu_count;
478 unsigned int ttwu_local;
480 /* BKL stats */
481 unsigned int bkl_count;
482 #endif
483 struct lock_class_key rq_lock_key;
486 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
488 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
490 rq->curr->sched_class->check_preempt_curr(rq, p);
493 static inline int cpu_of(struct rq *rq)
495 #ifdef CONFIG_SMP
496 return rq->cpu;
497 #else
498 return 0;
499 #endif
503 * Update the per-runqueue clock, as finegrained as the platform can give
504 * us, but without assuming monotonicity, etc.:
506 static void __update_rq_clock(struct rq *rq)
508 u64 prev_raw = rq->prev_clock_raw;
509 u64 now = sched_clock();
510 s64 delta = now - prev_raw;
511 u64 clock = rq->clock;
513 #ifdef CONFIG_SCHED_DEBUG
514 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
515 #endif
517 * Protect against sched_clock() occasionally going backwards:
519 if (unlikely(delta < 0)) {
520 clock++;
521 rq->clock_warps++;
522 } else {
524 * Catch too large forward jumps too:
526 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
527 if (clock < rq->tick_timestamp + TICK_NSEC)
528 clock = rq->tick_timestamp + TICK_NSEC;
529 else
530 clock++;
531 rq->clock_overflows++;
532 } else {
533 if (unlikely(delta > rq->clock_max_delta))
534 rq->clock_max_delta = delta;
535 clock += delta;
539 rq->prev_clock_raw = now;
540 rq->clock = clock;
543 static void update_rq_clock(struct rq *rq)
545 if (likely(smp_processor_id() == cpu_of(rq)))
546 __update_rq_clock(rq);
550 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
551 * See detach_destroy_domains: synchronize_sched for details.
553 * The domain tree of any CPU may only be accessed from within
554 * preempt-disabled sections.
556 #define for_each_domain(cpu, __sd) \
557 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
559 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
560 #define this_rq() (&__get_cpu_var(runqueues))
561 #define task_rq(p) cpu_rq(task_cpu(p))
562 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
564 unsigned long rt_needs_cpu(int cpu)
566 struct rq *rq = cpu_rq(cpu);
567 u64 delta;
569 if (!rq->rt_throttled)
570 return 0;
572 if (rq->clock > rq->rt_period_expire)
573 return 1;
575 delta = rq->rt_period_expire - rq->clock;
576 do_div(delta, NSEC_PER_SEC / HZ);
578 return (unsigned long)delta;
582 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
584 #ifdef CONFIG_SCHED_DEBUG
585 # define const_debug __read_mostly
586 #else
587 # define const_debug static const
588 #endif
591 * Debugging: various feature bits
593 enum {
594 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
595 SCHED_FEAT_WAKEUP_PREEMPT = 2,
596 SCHED_FEAT_START_DEBIT = 4,
597 SCHED_FEAT_HRTICK = 8,
598 SCHED_FEAT_DOUBLE_TICK = 16,
601 const_debug unsigned int sysctl_sched_features =
602 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
603 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
604 SCHED_FEAT_START_DEBIT * 1 |
605 SCHED_FEAT_HRTICK * 1 |
606 SCHED_FEAT_DOUBLE_TICK * 0;
608 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
611 * Number of tasks to iterate in a single balance run.
612 * Limited because this is done with IRQs disabled.
614 const_debug unsigned int sysctl_sched_nr_migrate = 32;
617 * period over which we measure -rt task cpu usage in us.
618 * default: 1s
620 unsigned int sysctl_sched_rt_period = 1000000;
622 static __read_mostly int scheduler_running;
625 * part of the period that we allow rt tasks to run in us.
626 * default: 0.95s
628 int sysctl_sched_rt_runtime = 950000;
631 * single value that denotes runtime == period, ie unlimited time.
633 #define RUNTIME_INF ((u64)~0ULL)
636 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
637 * clock constructed from sched_clock():
639 unsigned long long cpu_clock(int cpu)
641 unsigned long long now;
642 unsigned long flags;
643 struct rq *rq;
646 * Only call sched_clock() if the scheduler has already been
647 * initialized (some code might call cpu_clock() very early):
649 if (unlikely(!scheduler_running))
650 return 0;
652 local_irq_save(flags);
653 rq = cpu_rq(cpu);
654 update_rq_clock(rq);
655 now = rq->clock;
656 local_irq_restore(flags);
658 return now;
660 EXPORT_SYMBOL_GPL(cpu_clock);
662 #ifndef prepare_arch_switch
663 # define prepare_arch_switch(next) do { } while (0)
664 #endif
665 #ifndef finish_arch_switch
666 # define finish_arch_switch(prev) do { } while (0)
667 #endif
669 static inline int task_current(struct rq *rq, struct task_struct *p)
671 return rq->curr == p;
674 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
675 static inline int task_running(struct rq *rq, struct task_struct *p)
677 return task_current(rq, p);
680 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
684 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
686 #ifdef CONFIG_DEBUG_SPINLOCK
687 /* this is a valid case when another task releases the spinlock */
688 rq->lock.owner = current;
689 #endif
691 * If we are tracking spinlock dependencies then we have to
692 * fix up the runqueue lock - which gets 'carried over' from
693 * prev into current:
695 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
697 spin_unlock_irq(&rq->lock);
700 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
701 static inline int task_running(struct rq *rq, struct task_struct *p)
703 #ifdef CONFIG_SMP
704 return p->oncpu;
705 #else
706 return task_current(rq, p);
707 #endif
710 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
712 #ifdef CONFIG_SMP
714 * We can optimise this out completely for !SMP, because the
715 * SMP rebalancing from interrupt is the only thing that cares
716 * here.
718 next->oncpu = 1;
719 #endif
720 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
721 spin_unlock_irq(&rq->lock);
722 #else
723 spin_unlock(&rq->lock);
724 #endif
727 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
729 #ifdef CONFIG_SMP
731 * After ->oncpu is cleared, the task can be moved to a different CPU.
732 * We must ensure this doesn't happen until the switch is completely
733 * finished.
735 smp_wmb();
736 prev->oncpu = 0;
737 #endif
738 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
739 local_irq_enable();
740 #endif
742 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
745 * __task_rq_lock - lock the runqueue a given task resides on.
746 * Must be called interrupts disabled.
748 static inline struct rq *__task_rq_lock(struct task_struct *p)
749 __acquires(rq->lock)
751 for (;;) {
752 struct rq *rq = task_rq(p);
753 spin_lock(&rq->lock);
754 if (likely(rq == task_rq(p)))
755 return rq;
756 spin_unlock(&rq->lock);
761 * task_rq_lock - lock the runqueue a given task resides on and disable
762 * interrupts. Note the ordering: we can safely lookup the task_rq without
763 * explicitly disabling preemption.
765 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
766 __acquires(rq->lock)
768 struct rq *rq;
770 for (;;) {
771 local_irq_save(*flags);
772 rq = task_rq(p);
773 spin_lock(&rq->lock);
774 if (likely(rq == task_rq(p)))
775 return rq;
776 spin_unlock_irqrestore(&rq->lock, *flags);
780 static void __task_rq_unlock(struct rq *rq)
781 __releases(rq->lock)
783 spin_unlock(&rq->lock);
786 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
787 __releases(rq->lock)
789 spin_unlock_irqrestore(&rq->lock, *flags);
793 * this_rq_lock - lock this runqueue and disable interrupts.
795 static struct rq *this_rq_lock(void)
796 __acquires(rq->lock)
798 struct rq *rq;
800 local_irq_disable();
801 rq = this_rq();
802 spin_lock(&rq->lock);
804 return rq;
808 * We are going deep-idle (irqs are disabled):
810 void sched_clock_idle_sleep_event(void)
812 struct rq *rq = cpu_rq(smp_processor_id());
814 spin_lock(&rq->lock);
815 __update_rq_clock(rq);
816 spin_unlock(&rq->lock);
817 rq->clock_deep_idle_events++;
819 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
822 * We just idled delta nanoseconds (called with irqs disabled):
824 void sched_clock_idle_wakeup_event(u64 delta_ns)
826 struct rq *rq = cpu_rq(smp_processor_id());
827 u64 now = sched_clock();
829 rq->idle_clock += delta_ns;
831 * Override the previous timestamp and ignore all
832 * sched_clock() deltas that occured while we idled,
833 * and use the PM-provided delta_ns to advance the
834 * rq clock:
836 spin_lock(&rq->lock);
837 rq->prev_clock_raw = now;
838 rq->clock += delta_ns;
839 spin_unlock(&rq->lock);
840 touch_softlockup_watchdog();
842 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
844 static void __resched_task(struct task_struct *p, int tif_bit);
846 static inline void resched_task(struct task_struct *p)
848 __resched_task(p, TIF_NEED_RESCHED);
851 #ifdef CONFIG_SCHED_HRTICK
853 * Use HR-timers to deliver accurate preemption points.
855 * Its all a bit involved since we cannot program an hrt while holding the
856 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
857 * reschedule event.
859 * When we get rescheduled we reprogram the hrtick_timer outside of the
860 * rq->lock.
862 static inline void resched_hrt(struct task_struct *p)
864 __resched_task(p, TIF_HRTICK_RESCHED);
867 static inline void resched_rq(struct rq *rq)
869 unsigned long flags;
871 spin_lock_irqsave(&rq->lock, flags);
872 resched_task(rq->curr);
873 spin_unlock_irqrestore(&rq->lock, flags);
876 enum {
877 HRTICK_SET, /* re-programm hrtick_timer */
878 HRTICK_RESET, /* not a new slice */
879 HRTICK_BLOCK, /* stop hrtick operations */
883 * Use hrtick when:
884 * - enabled by features
885 * - hrtimer is actually high res
887 static inline int hrtick_enabled(struct rq *rq)
889 if (!sched_feat(HRTICK))
890 return 0;
891 if (unlikely(test_bit(HRTICK_BLOCK, &rq->hrtick_flags)))
892 return 0;
893 return hrtimer_is_hres_active(&rq->hrtick_timer);
897 * Called to set the hrtick timer state.
899 * called with rq->lock held and irqs disabled
901 static void hrtick_start(struct rq *rq, u64 delay, int reset)
903 assert_spin_locked(&rq->lock);
906 * preempt at: now + delay
908 rq->hrtick_expire =
909 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
911 * indicate we need to program the timer
913 __set_bit(HRTICK_SET, &rq->hrtick_flags);
914 if (reset)
915 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
918 * New slices are called from the schedule path and don't need a
919 * forced reschedule.
921 if (reset)
922 resched_hrt(rq->curr);
925 static void hrtick_clear(struct rq *rq)
927 if (hrtimer_active(&rq->hrtick_timer))
928 hrtimer_cancel(&rq->hrtick_timer);
932 * Update the timer from the possible pending state.
934 static void hrtick_set(struct rq *rq)
936 ktime_t time;
937 int set, reset;
938 unsigned long flags;
940 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
942 spin_lock_irqsave(&rq->lock, flags);
943 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
944 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
945 time = rq->hrtick_expire;
946 clear_thread_flag(TIF_HRTICK_RESCHED);
947 spin_unlock_irqrestore(&rq->lock, flags);
949 if (set) {
950 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
951 if (reset && !hrtimer_active(&rq->hrtick_timer))
952 resched_rq(rq);
953 } else
954 hrtick_clear(rq);
958 * High-resolution timer tick.
959 * Runs from hardirq context with interrupts disabled.
961 static enum hrtimer_restart hrtick(struct hrtimer *timer)
963 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
965 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
967 spin_lock(&rq->lock);
968 __update_rq_clock(rq);
969 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
970 spin_unlock(&rq->lock);
972 return HRTIMER_NORESTART;
975 static void hotplug_hrtick_disable(int cpu)
977 struct rq *rq = cpu_rq(cpu);
978 unsigned long flags;
980 spin_lock_irqsave(&rq->lock, flags);
981 rq->hrtick_flags = 0;
982 __set_bit(HRTICK_BLOCK, &rq->hrtick_flags);
983 spin_unlock_irqrestore(&rq->lock, flags);
985 hrtick_clear(rq);
988 static void hotplug_hrtick_enable(int cpu)
990 struct rq *rq = cpu_rq(cpu);
991 unsigned long flags;
993 spin_lock_irqsave(&rq->lock, flags);
994 __clear_bit(HRTICK_BLOCK, &rq->hrtick_flags);
995 spin_unlock_irqrestore(&rq->lock, flags);
998 static int
999 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1001 int cpu = (int)(long)hcpu;
1003 switch (action) {
1004 case CPU_UP_CANCELED:
1005 case CPU_UP_CANCELED_FROZEN:
1006 case CPU_DOWN_PREPARE:
1007 case CPU_DOWN_PREPARE_FROZEN:
1008 case CPU_DEAD:
1009 case CPU_DEAD_FROZEN:
1010 hotplug_hrtick_disable(cpu);
1011 return NOTIFY_OK;
1013 case CPU_UP_PREPARE:
1014 case CPU_UP_PREPARE_FROZEN:
1015 case CPU_DOWN_FAILED:
1016 case CPU_DOWN_FAILED_FROZEN:
1017 case CPU_ONLINE:
1018 case CPU_ONLINE_FROZEN:
1019 hotplug_hrtick_enable(cpu);
1020 return NOTIFY_OK;
1023 return NOTIFY_DONE;
1026 static void init_hrtick(void)
1028 hotcpu_notifier(hotplug_hrtick, 0);
1031 static void init_rq_hrtick(struct rq *rq)
1033 rq->hrtick_flags = 0;
1034 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1035 rq->hrtick_timer.function = hrtick;
1036 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1039 void hrtick_resched(void)
1041 struct rq *rq;
1042 unsigned long flags;
1044 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1045 return;
1047 local_irq_save(flags);
1048 rq = cpu_rq(smp_processor_id());
1049 hrtick_set(rq);
1050 local_irq_restore(flags);
1052 #else
1053 static inline void hrtick_clear(struct rq *rq)
1057 static inline void hrtick_set(struct rq *rq)
1061 static inline void init_rq_hrtick(struct rq *rq)
1065 void hrtick_resched(void)
1069 static inline void init_hrtick(void)
1072 #endif
1075 * resched_task - mark a task 'to be rescheduled now'.
1077 * On UP this means the setting of the need_resched flag, on SMP it
1078 * might also involve a cross-CPU call to trigger the scheduler on
1079 * the target CPU.
1081 #ifdef CONFIG_SMP
1083 #ifndef tsk_is_polling
1084 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1085 #endif
1087 static void __resched_task(struct task_struct *p, int tif_bit)
1089 int cpu;
1091 assert_spin_locked(&task_rq(p)->lock);
1093 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1094 return;
1096 set_tsk_thread_flag(p, tif_bit);
1098 cpu = task_cpu(p);
1099 if (cpu == smp_processor_id())
1100 return;
1102 /* NEED_RESCHED must be visible before we test polling */
1103 smp_mb();
1104 if (!tsk_is_polling(p))
1105 smp_send_reschedule(cpu);
1108 static void resched_cpu(int cpu)
1110 struct rq *rq = cpu_rq(cpu);
1111 unsigned long flags;
1113 if (!spin_trylock_irqsave(&rq->lock, flags))
1114 return;
1115 resched_task(cpu_curr(cpu));
1116 spin_unlock_irqrestore(&rq->lock, flags);
1119 #ifdef CONFIG_NO_HZ
1121 * When add_timer_on() enqueues a timer into the timer wheel of an
1122 * idle CPU then this timer might expire before the next timer event
1123 * which is scheduled to wake up that CPU. In case of a completely
1124 * idle system the next event might even be infinite time into the
1125 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1126 * leaves the inner idle loop so the newly added timer is taken into
1127 * account when the CPU goes back to idle and evaluates the timer
1128 * wheel for the next timer event.
1130 void wake_up_idle_cpu(int cpu)
1132 struct rq *rq = cpu_rq(cpu);
1134 if (cpu == smp_processor_id())
1135 return;
1138 * This is safe, as this function is called with the timer
1139 * wheel base lock of (cpu) held. When the CPU is on the way
1140 * to idle and has not yet set rq->curr to idle then it will
1141 * be serialized on the timer wheel base lock and take the new
1142 * timer into account automatically.
1144 if (rq->curr != rq->idle)
1145 return;
1148 * We can set TIF_RESCHED on the idle task of the other CPU
1149 * lockless. The worst case is that the other CPU runs the
1150 * idle task through an additional NOOP schedule()
1152 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1154 /* NEED_RESCHED must be visible before we test polling */
1155 smp_mb();
1156 if (!tsk_is_polling(rq->idle))
1157 smp_send_reschedule(cpu);
1159 #endif
1161 #else
1162 static void __resched_task(struct task_struct *p, int tif_bit)
1164 assert_spin_locked(&task_rq(p)->lock);
1165 set_tsk_thread_flag(p, tif_bit);
1167 #endif
1169 #if BITS_PER_LONG == 32
1170 # define WMULT_CONST (~0UL)
1171 #else
1172 # define WMULT_CONST (1UL << 32)
1173 #endif
1175 #define WMULT_SHIFT 32
1178 * Shift right and round:
1180 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1182 static unsigned long
1183 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1184 struct load_weight *lw)
1186 u64 tmp;
1188 if (unlikely(!lw->inv_weight))
1189 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1191 tmp = (u64)delta_exec * weight;
1193 * Check whether we'd overflow the 64-bit multiplication:
1195 if (unlikely(tmp > WMULT_CONST))
1196 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1197 WMULT_SHIFT/2);
1198 else
1199 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1201 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1204 static inline unsigned long
1205 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
1207 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
1210 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1212 lw->weight += inc;
1213 lw->inv_weight = 0;
1216 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1218 lw->weight -= dec;
1219 lw->inv_weight = 0;
1223 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1224 * of tasks with abnormal "nice" values across CPUs the contribution that
1225 * each task makes to its run queue's load is weighted according to its
1226 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1227 * scaled version of the new time slice allocation that they receive on time
1228 * slice expiry etc.
1231 #define WEIGHT_IDLEPRIO 2
1232 #define WMULT_IDLEPRIO (1 << 31)
1235 * Nice levels are multiplicative, with a gentle 10% change for every
1236 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1237 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1238 * that remained on nice 0.
1240 * The "10% effect" is relative and cumulative: from _any_ nice level,
1241 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1242 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1243 * If a task goes up by ~10% and another task goes down by ~10% then
1244 * the relative distance between them is ~25%.)
1246 static const int prio_to_weight[40] = {
1247 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1248 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1249 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1250 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1251 /* 0 */ 1024, 820, 655, 526, 423,
1252 /* 5 */ 335, 272, 215, 172, 137,
1253 /* 10 */ 110, 87, 70, 56, 45,
1254 /* 15 */ 36, 29, 23, 18, 15,
1258 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1260 * In cases where the weight does not change often, we can use the
1261 * precalculated inverse to speed up arithmetics by turning divisions
1262 * into multiplications:
1264 static const u32 prio_to_wmult[40] = {
1265 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1266 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1267 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1268 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1269 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1270 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1271 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1272 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1275 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1278 * runqueue iterator, to support SMP load-balancing between different
1279 * scheduling classes, without having to expose their internal data
1280 * structures to the load-balancing proper:
1282 struct rq_iterator {
1283 void *arg;
1284 struct task_struct *(*start)(void *);
1285 struct task_struct *(*next)(void *);
1288 #ifdef CONFIG_SMP
1289 static unsigned long
1290 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1291 unsigned long max_load_move, struct sched_domain *sd,
1292 enum cpu_idle_type idle, int *all_pinned,
1293 int *this_best_prio, struct rq_iterator *iterator);
1295 static int
1296 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1297 struct sched_domain *sd, enum cpu_idle_type idle,
1298 struct rq_iterator *iterator);
1299 #endif
1301 #ifdef CONFIG_CGROUP_CPUACCT
1302 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1303 #else
1304 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1305 #endif
1307 #ifdef CONFIG_SMP
1308 static unsigned long source_load(int cpu, int type);
1309 static unsigned long target_load(int cpu, int type);
1310 static unsigned long cpu_avg_load_per_task(int cpu);
1311 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1312 #endif /* CONFIG_SMP */
1314 #include "sched_stats.h"
1315 #include "sched_idletask.c"
1316 #include "sched_fair.c"
1317 #include "sched_rt.c"
1318 #ifdef CONFIG_SCHED_DEBUG
1319 # include "sched_debug.c"
1320 #endif
1322 #define sched_class_highest (&rt_sched_class)
1324 static inline void inc_load(struct rq *rq, const struct task_struct *p)
1326 update_load_add(&rq->load, p->se.load.weight);
1329 static inline void dec_load(struct rq *rq, const struct task_struct *p)
1331 update_load_sub(&rq->load, p->se.load.weight);
1334 static void inc_nr_running(struct task_struct *p, struct rq *rq)
1336 rq->nr_running++;
1337 inc_load(rq, p);
1340 static void dec_nr_running(struct task_struct *p, struct rq *rq)
1342 rq->nr_running--;
1343 dec_load(rq, p);
1346 static void set_load_weight(struct task_struct *p)
1348 if (task_has_rt_policy(p)) {
1349 p->se.load.weight = prio_to_weight[0] * 2;
1350 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1351 return;
1355 * SCHED_IDLE tasks get minimal weight:
1357 if (p->policy == SCHED_IDLE) {
1358 p->se.load.weight = WEIGHT_IDLEPRIO;
1359 p->se.load.inv_weight = WMULT_IDLEPRIO;
1360 return;
1363 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1364 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1367 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1369 sched_info_queued(p);
1370 p->sched_class->enqueue_task(rq, p, wakeup);
1371 p->se.on_rq = 1;
1374 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1376 p->sched_class->dequeue_task(rq, p, sleep);
1377 p->se.on_rq = 0;
1381 * __normal_prio - return the priority that is based on the static prio
1383 static inline int __normal_prio(struct task_struct *p)
1385 return p->static_prio;
1389 * Calculate the expected normal priority: i.e. priority
1390 * without taking RT-inheritance into account. Might be
1391 * boosted by interactivity modifiers. Changes upon fork,
1392 * setprio syscalls, and whenever the interactivity
1393 * estimator recalculates.
1395 static inline int normal_prio(struct task_struct *p)
1397 int prio;
1399 if (task_has_rt_policy(p))
1400 prio = MAX_RT_PRIO-1 - p->rt_priority;
1401 else
1402 prio = __normal_prio(p);
1403 return prio;
1407 * Calculate the current priority, i.e. the priority
1408 * taken into account by the scheduler. This value might
1409 * be boosted by RT tasks, or might be boosted by
1410 * interactivity modifiers. Will be RT if the task got
1411 * RT-boosted. If not then it returns p->normal_prio.
1413 static int effective_prio(struct task_struct *p)
1415 p->normal_prio = normal_prio(p);
1417 * If we are RT tasks or we were boosted to RT priority,
1418 * keep the priority unchanged. Otherwise, update priority
1419 * to the normal priority:
1421 if (!rt_prio(p->prio))
1422 return p->normal_prio;
1423 return p->prio;
1427 * activate_task - move a task to the runqueue.
1429 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1431 if (task_contributes_to_load(p))
1432 rq->nr_uninterruptible--;
1434 enqueue_task(rq, p, wakeup);
1435 inc_nr_running(p, rq);
1439 * deactivate_task - remove a task from the runqueue.
1441 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1443 if (task_contributes_to_load(p))
1444 rq->nr_uninterruptible++;
1446 dequeue_task(rq, p, sleep);
1447 dec_nr_running(p, rq);
1451 * task_curr - is this task currently executing on a CPU?
1452 * @p: the task in question.
1454 inline int task_curr(const struct task_struct *p)
1456 return cpu_curr(task_cpu(p)) == p;
1459 /* Used instead of source_load when we know the type == 0 */
1460 unsigned long weighted_cpuload(const int cpu)
1462 return cpu_rq(cpu)->load.weight;
1465 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1467 set_task_rq(p, cpu);
1468 #ifdef CONFIG_SMP
1470 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1471 * successfuly executed on another CPU. We must ensure that updates of
1472 * per-task data have been completed by this moment.
1474 smp_wmb();
1475 task_thread_info(p)->cpu = cpu;
1476 #endif
1479 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1480 const struct sched_class *prev_class,
1481 int oldprio, int running)
1483 if (prev_class != p->sched_class) {
1484 if (prev_class->switched_from)
1485 prev_class->switched_from(rq, p, running);
1486 p->sched_class->switched_to(rq, p, running);
1487 } else
1488 p->sched_class->prio_changed(rq, p, oldprio, running);
1491 #ifdef CONFIG_SMP
1494 * Is this task likely cache-hot:
1496 static int
1497 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1499 s64 delta;
1502 * Buddy candidates are cache hot:
1504 if (&p->se == cfs_rq_of(&p->se)->next)
1505 return 1;
1507 if (p->sched_class != &fair_sched_class)
1508 return 0;
1510 if (sysctl_sched_migration_cost == -1)
1511 return 1;
1512 if (sysctl_sched_migration_cost == 0)
1513 return 0;
1515 delta = now - p->se.exec_start;
1517 return delta < (s64)sysctl_sched_migration_cost;
1521 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1523 int old_cpu = task_cpu(p);
1524 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1525 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1526 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1527 u64 clock_offset;
1529 clock_offset = old_rq->clock - new_rq->clock;
1531 #ifdef CONFIG_SCHEDSTATS
1532 if (p->se.wait_start)
1533 p->se.wait_start -= clock_offset;
1534 if (p->se.sleep_start)
1535 p->se.sleep_start -= clock_offset;
1536 if (p->se.block_start)
1537 p->se.block_start -= clock_offset;
1538 if (old_cpu != new_cpu) {
1539 schedstat_inc(p, se.nr_migrations);
1540 if (task_hot(p, old_rq->clock, NULL))
1541 schedstat_inc(p, se.nr_forced2_migrations);
1543 #endif
1544 p->se.vruntime -= old_cfsrq->min_vruntime -
1545 new_cfsrq->min_vruntime;
1547 __set_task_cpu(p, new_cpu);
1550 struct migration_req {
1551 struct list_head list;
1553 struct task_struct *task;
1554 int dest_cpu;
1556 struct completion done;
1560 * The task's runqueue lock must be held.
1561 * Returns true if you have to wait for migration thread.
1563 static int
1564 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1566 struct rq *rq = task_rq(p);
1569 * If the task is not on a runqueue (and not running), then
1570 * it is sufficient to simply update the task's cpu field.
1572 if (!p->se.on_rq && !task_running(rq, p)) {
1573 set_task_cpu(p, dest_cpu);
1574 return 0;
1577 init_completion(&req->done);
1578 req->task = p;
1579 req->dest_cpu = dest_cpu;
1580 list_add(&req->list, &rq->migration_queue);
1582 return 1;
1586 * wait_task_inactive - wait for a thread to unschedule.
1588 * The caller must ensure that the task *will* unschedule sometime soon,
1589 * else this function might spin for a *long* time. This function can't
1590 * be called with interrupts off, or it may introduce deadlock with
1591 * smp_call_function() if an IPI is sent by the same process we are
1592 * waiting to become inactive.
1594 void wait_task_inactive(struct task_struct *p)
1596 unsigned long flags;
1597 int running, on_rq;
1598 struct rq *rq;
1600 for (;;) {
1602 * We do the initial early heuristics without holding
1603 * any task-queue locks at all. We'll only try to get
1604 * the runqueue lock when things look like they will
1605 * work out!
1607 rq = task_rq(p);
1610 * If the task is actively running on another CPU
1611 * still, just relax and busy-wait without holding
1612 * any locks.
1614 * NOTE! Since we don't hold any locks, it's not
1615 * even sure that "rq" stays as the right runqueue!
1616 * But we don't care, since "task_running()" will
1617 * return false if the runqueue has changed and p
1618 * is actually now running somewhere else!
1620 while (task_running(rq, p))
1621 cpu_relax();
1624 * Ok, time to look more closely! We need the rq
1625 * lock now, to be *sure*. If we're wrong, we'll
1626 * just go back and repeat.
1628 rq = task_rq_lock(p, &flags);
1629 running = task_running(rq, p);
1630 on_rq = p->se.on_rq;
1631 task_rq_unlock(rq, &flags);
1634 * Was it really running after all now that we
1635 * checked with the proper locks actually held?
1637 * Oops. Go back and try again..
1639 if (unlikely(running)) {
1640 cpu_relax();
1641 continue;
1645 * It's not enough that it's not actively running,
1646 * it must be off the runqueue _entirely_, and not
1647 * preempted!
1649 * So if it wa still runnable (but just not actively
1650 * running right now), it's preempted, and we should
1651 * yield - it could be a while.
1653 if (unlikely(on_rq)) {
1654 schedule_timeout_uninterruptible(1);
1655 continue;
1659 * Ahh, all good. It wasn't running, and it wasn't
1660 * runnable, which means that it will never become
1661 * running in the future either. We're all done!
1663 break;
1667 /***
1668 * kick_process - kick a running thread to enter/exit the kernel
1669 * @p: the to-be-kicked thread
1671 * Cause a process which is running on another CPU to enter
1672 * kernel-mode, without any delay. (to get signals handled.)
1674 * NOTE: this function doesnt have to take the runqueue lock,
1675 * because all it wants to ensure is that the remote task enters
1676 * the kernel. If the IPI races and the task has been migrated
1677 * to another CPU then no harm is done and the purpose has been
1678 * achieved as well.
1680 void kick_process(struct task_struct *p)
1682 int cpu;
1684 preempt_disable();
1685 cpu = task_cpu(p);
1686 if ((cpu != smp_processor_id()) && task_curr(p))
1687 smp_send_reschedule(cpu);
1688 preempt_enable();
1692 * Return a low guess at the load of a migration-source cpu weighted
1693 * according to the scheduling class and "nice" value.
1695 * We want to under-estimate the load of migration sources, to
1696 * balance conservatively.
1698 static unsigned long source_load(int cpu, int type)
1700 struct rq *rq = cpu_rq(cpu);
1701 unsigned long total = weighted_cpuload(cpu);
1703 if (type == 0)
1704 return total;
1706 return min(rq->cpu_load[type-1], total);
1710 * Return a high guess at the load of a migration-target cpu weighted
1711 * according to the scheduling class and "nice" value.
1713 static unsigned long target_load(int cpu, int type)
1715 struct rq *rq = cpu_rq(cpu);
1716 unsigned long total = weighted_cpuload(cpu);
1718 if (type == 0)
1719 return total;
1721 return max(rq->cpu_load[type-1], total);
1725 * Return the average load per task on the cpu's run queue
1727 static unsigned long cpu_avg_load_per_task(int cpu)
1729 struct rq *rq = cpu_rq(cpu);
1730 unsigned long total = weighted_cpuload(cpu);
1731 unsigned long n = rq->nr_running;
1733 return n ? total / n : SCHED_LOAD_SCALE;
1737 * find_idlest_group finds and returns the least busy CPU group within the
1738 * domain.
1740 static struct sched_group *
1741 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1743 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1744 unsigned long min_load = ULONG_MAX, this_load = 0;
1745 int load_idx = sd->forkexec_idx;
1746 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1748 do {
1749 unsigned long load, avg_load;
1750 int local_group;
1751 int i;
1753 /* Skip over this group if it has no CPUs allowed */
1754 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1755 continue;
1757 local_group = cpu_isset(this_cpu, group->cpumask);
1759 /* Tally up the load of all CPUs in the group */
1760 avg_load = 0;
1762 for_each_cpu_mask(i, group->cpumask) {
1763 /* Bias balancing toward cpus of our domain */
1764 if (local_group)
1765 load = source_load(i, load_idx);
1766 else
1767 load = target_load(i, load_idx);
1769 avg_load += load;
1772 /* Adjust by relative CPU power of the group */
1773 avg_load = sg_div_cpu_power(group,
1774 avg_load * SCHED_LOAD_SCALE);
1776 if (local_group) {
1777 this_load = avg_load;
1778 this = group;
1779 } else if (avg_load < min_load) {
1780 min_load = avg_load;
1781 idlest = group;
1783 } while (group = group->next, group != sd->groups);
1785 if (!idlest || 100*this_load < imbalance*min_load)
1786 return NULL;
1787 return idlest;
1791 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1793 static int
1794 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1796 cpumask_t tmp;
1797 unsigned long load, min_load = ULONG_MAX;
1798 int idlest = -1;
1799 int i;
1801 /* Traverse only the allowed CPUs */
1802 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1804 for_each_cpu_mask(i, tmp) {
1805 load = weighted_cpuload(i);
1807 if (load < min_load || (load == min_load && i == this_cpu)) {
1808 min_load = load;
1809 idlest = i;
1813 return idlest;
1817 * sched_balance_self: balance the current task (running on cpu) in domains
1818 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1819 * SD_BALANCE_EXEC.
1821 * Balance, ie. select the least loaded group.
1823 * Returns the target CPU number, or the same CPU if no balancing is needed.
1825 * preempt must be disabled.
1827 static int sched_balance_self(int cpu, int flag)
1829 struct task_struct *t = current;
1830 struct sched_domain *tmp, *sd = NULL;
1832 for_each_domain(cpu, tmp) {
1834 * If power savings logic is enabled for a domain, stop there.
1836 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1837 break;
1838 if (tmp->flags & flag)
1839 sd = tmp;
1842 while (sd) {
1843 cpumask_t span;
1844 struct sched_group *group;
1845 int new_cpu, weight;
1847 if (!(sd->flags & flag)) {
1848 sd = sd->child;
1849 continue;
1852 span = sd->span;
1853 group = find_idlest_group(sd, t, cpu);
1854 if (!group) {
1855 sd = sd->child;
1856 continue;
1859 new_cpu = find_idlest_cpu(group, t, cpu);
1860 if (new_cpu == -1 || new_cpu == cpu) {
1861 /* Now try balancing at a lower domain level of cpu */
1862 sd = sd->child;
1863 continue;
1866 /* Now try balancing at a lower domain level of new_cpu */
1867 cpu = new_cpu;
1868 sd = NULL;
1869 weight = cpus_weight(span);
1870 for_each_domain(cpu, tmp) {
1871 if (weight <= cpus_weight(tmp->span))
1872 break;
1873 if (tmp->flags & flag)
1874 sd = tmp;
1876 /* while loop will break here if sd == NULL */
1879 return cpu;
1882 #endif /* CONFIG_SMP */
1884 /***
1885 * try_to_wake_up - wake up a thread
1886 * @p: the to-be-woken-up thread
1887 * @state: the mask of task states that can be woken
1888 * @sync: do a synchronous wakeup?
1890 * Put it on the run-queue if it's not already there. The "current"
1891 * thread is always on the run-queue (except when the actual
1892 * re-schedule is in progress), and as such you're allowed to do
1893 * the simpler "current->state = TASK_RUNNING" to mark yourself
1894 * runnable without the overhead of this.
1896 * returns failure only if the task is already active.
1898 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1900 int cpu, orig_cpu, this_cpu, success = 0;
1901 unsigned long flags;
1902 long old_state;
1903 struct rq *rq;
1905 smp_wmb();
1906 rq = task_rq_lock(p, &flags);
1907 old_state = p->state;
1908 if (!(old_state & state))
1909 goto out;
1911 if (p->se.on_rq)
1912 goto out_running;
1914 cpu = task_cpu(p);
1915 orig_cpu = cpu;
1916 this_cpu = smp_processor_id();
1918 #ifdef CONFIG_SMP
1919 if (unlikely(task_running(rq, p)))
1920 goto out_activate;
1922 cpu = p->sched_class->select_task_rq(p, sync);
1923 if (cpu != orig_cpu) {
1924 set_task_cpu(p, cpu);
1925 task_rq_unlock(rq, &flags);
1926 /* might preempt at this point */
1927 rq = task_rq_lock(p, &flags);
1928 old_state = p->state;
1929 if (!(old_state & state))
1930 goto out;
1931 if (p->se.on_rq)
1932 goto out_running;
1934 this_cpu = smp_processor_id();
1935 cpu = task_cpu(p);
1938 #ifdef CONFIG_SCHEDSTATS
1939 schedstat_inc(rq, ttwu_count);
1940 if (cpu == this_cpu)
1941 schedstat_inc(rq, ttwu_local);
1942 else {
1943 struct sched_domain *sd;
1944 for_each_domain(this_cpu, sd) {
1945 if (cpu_isset(cpu, sd->span)) {
1946 schedstat_inc(sd, ttwu_wake_remote);
1947 break;
1951 #endif
1953 out_activate:
1954 #endif /* CONFIG_SMP */
1955 schedstat_inc(p, se.nr_wakeups);
1956 if (sync)
1957 schedstat_inc(p, se.nr_wakeups_sync);
1958 if (orig_cpu != cpu)
1959 schedstat_inc(p, se.nr_wakeups_migrate);
1960 if (cpu == this_cpu)
1961 schedstat_inc(p, se.nr_wakeups_local);
1962 else
1963 schedstat_inc(p, se.nr_wakeups_remote);
1964 update_rq_clock(rq);
1965 activate_task(rq, p, 1);
1966 success = 1;
1968 out_running:
1969 check_preempt_curr(rq, p);
1971 p->state = TASK_RUNNING;
1972 #ifdef CONFIG_SMP
1973 if (p->sched_class->task_wake_up)
1974 p->sched_class->task_wake_up(rq, p);
1975 #endif
1976 out:
1977 task_rq_unlock(rq, &flags);
1979 return success;
1982 int wake_up_process(struct task_struct *p)
1984 return try_to_wake_up(p, TASK_ALL, 0);
1986 EXPORT_SYMBOL(wake_up_process);
1988 int wake_up_state(struct task_struct *p, unsigned int state)
1990 return try_to_wake_up(p, state, 0);
1994 * Perform scheduler related setup for a newly forked process p.
1995 * p is forked by current.
1997 * __sched_fork() is basic setup used by init_idle() too:
1999 static void __sched_fork(struct task_struct *p)
2001 p->se.exec_start = 0;
2002 p->se.sum_exec_runtime = 0;
2003 p->se.prev_sum_exec_runtime = 0;
2004 p->se.last_wakeup = 0;
2005 p->se.avg_overlap = 0;
2007 #ifdef CONFIG_SCHEDSTATS
2008 p->se.wait_start = 0;
2009 p->se.sum_sleep_runtime = 0;
2010 p->se.sleep_start = 0;
2011 p->se.block_start = 0;
2012 p->se.sleep_max = 0;
2013 p->se.block_max = 0;
2014 p->se.exec_max = 0;
2015 p->se.slice_max = 0;
2016 p->se.wait_max = 0;
2017 #endif
2019 INIT_LIST_HEAD(&p->rt.run_list);
2020 p->se.on_rq = 0;
2022 #ifdef CONFIG_PREEMPT_NOTIFIERS
2023 INIT_HLIST_HEAD(&p->preempt_notifiers);
2024 #endif
2027 * We mark the process as running here, but have not actually
2028 * inserted it onto the runqueue yet. This guarantees that
2029 * nobody will actually run it, and a signal or other external
2030 * event cannot wake it up and insert it on the runqueue either.
2032 p->state = TASK_RUNNING;
2036 * fork()/clone()-time setup:
2038 void sched_fork(struct task_struct *p, int clone_flags)
2040 int cpu = get_cpu();
2042 __sched_fork(p);
2044 #ifdef CONFIG_SMP
2045 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2046 #endif
2047 set_task_cpu(p, cpu);
2050 * Make sure we do not leak PI boosting priority to the child:
2052 p->prio = current->normal_prio;
2053 if (!rt_prio(p->prio))
2054 p->sched_class = &fair_sched_class;
2056 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2057 if (likely(sched_info_on()))
2058 memset(&p->sched_info, 0, sizeof(p->sched_info));
2059 #endif
2060 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2061 p->oncpu = 0;
2062 #endif
2063 #ifdef CONFIG_PREEMPT
2064 /* Want to start with kernel preemption disabled. */
2065 task_thread_info(p)->preempt_count = 1;
2066 #endif
2067 put_cpu();
2071 * wake_up_new_task - wake up a newly created task for the first time.
2073 * This function will do some initial scheduler statistics housekeeping
2074 * that must be done for every newly created context, then puts the task
2075 * on the runqueue and wakes it.
2077 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2079 unsigned long flags;
2080 struct rq *rq;
2082 rq = task_rq_lock(p, &flags);
2083 BUG_ON(p->state != TASK_RUNNING);
2084 update_rq_clock(rq);
2086 p->prio = effective_prio(p);
2088 if (!p->sched_class->task_new || !current->se.on_rq) {
2089 activate_task(rq, p, 0);
2090 } else {
2092 * Let the scheduling class do new task startup
2093 * management (if any):
2095 p->sched_class->task_new(rq, p);
2096 inc_nr_running(p, rq);
2098 check_preempt_curr(rq, p);
2099 #ifdef CONFIG_SMP
2100 if (p->sched_class->task_wake_up)
2101 p->sched_class->task_wake_up(rq, p);
2102 #endif
2103 task_rq_unlock(rq, &flags);
2106 #ifdef CONFIG_PREEMPT_NOTIFIERS
2109 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2110 * @notifier: notifier struct to register
2112 void preempt_notifier_register(struct preempt_notifier *notifier)
2114 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2116 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2119 * preempt_notifier_unregister - no longer interested in preemption notifications
2120 * @notifier: notifier struct to unregister
2122 * This is safe to call from within a preemption notifier.
2124 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2126 hlist_del(&notifier->link);
2128 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2130 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2132 struct preempt_notifier *notifier;
2133 struct hlist_node *node;
2135 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2136 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2139 static void
2140 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2141 struct task_struct *next)
2143 struct preempt_notifier *notifier;
2144 struct hlist_node *node;
2146 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2147 notifier->ops->sched_out(notifier, next);
2150 #else
2152 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2156 static void
2157 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2158 struct task_struct *next)
2162 #endif
2165 * prepare_task_switch - prepare to switch tasks
2166 * @rq: the runqueue preparing to switch
2167 * @prev: the current task that is being switched out
2168 * @next: the task we are going to switch to.
2170 * This is called with the rq lock held and interrupts off. It must
2171 * be paired with a subsequent finish_task_switch after the context
2172 * switch.
2174 * prepare_task_switch sets up locking and calls architecture specific
2175 * hooks.
2177 static inline void
2178 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2179 struct task_struct *next)
2181 fire_sched_out_preempt_notifiers(prev, next);
2182 prepare_lock_switch(rq, next);
2183 prepare_arch_switch(next);
2187 * finish_task_switch - clean up after a task-switch
2188 * @rq: runqueue associated with task-switch
2189 * @prev: the thread we just switched away from.
2191 * finish_task_switch must be called after the context switch, paired
2192 * with a prepare_task_switch call before the context switch.
2193 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2194 * and do any other architecture-specific cleanup actions.
2196 * Note that we may have delayed dropping an mm in context_switch(). If
2197 * so, we finish that here outside of the runqueue lock. (Doing it
2198 * with the lock held can cause deadlocks; see schedule() for
2199 * details.)
2201 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2202 __releases(rq->lock)
2204 struct mm_struct *mm = rq->prev_mm;
2205 long prev_state;
2207 rq->prev_mm = NULL;
2210 * A task struct has one reference for the use as "current".
2211 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2212 * schedule one last time. The schedule call will never return, and
2213 * the scheduled task must drop that reference.
2214 * The test for TASK_DEAD must occur while the runqueue locks are
2215 * still held, otherwise prev could be scheduled on another cpu, die
2216 * there before we look at prev->state, and then the reference would
2217 * be dropped twice.
2218 * Manfred Spraul <manfred@colorfullife.com>
2220 prev_state = prev->state;
2221 finish_arch_switch(prev);
2222 finish_lock_switch(rq, prev);
2223 #ifdef CONFIG_SMP
2224 if (current->sched_class->post_schedule)
2225 current->sched_class->post_schedule(rq);
2226 #endif
2228 fire_sched_in_preempt_notifiers(current);
2229 if (mm)
2230 mmdrop(mm);
2231 if (unlikely(prev_state == TASK_DEAD)) {
2233 * Remove function-return probe instances associated with this
2234 * task and put them back on the free list.
2236 kprobe_flush_task(prev);
2237 put_task_struct(prev);
2242 * schedule_tail - first thing a freshly forked thread must call.
2243 * @prev: the thread we just switched away from.
2245 asmlinkage void schedule_tail(struct task_struct *prev)
2246 __releases(rq->lock)
2248 struct rq *rq = this_rq();
2250 finish_task_switch(rq, prev);
2251 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2252 /* In this case, finish_task_switch does not reenable preemption */
2253 preempt_enable();
2254 #endif
2255 if (current->set_child_tid)
2256 put_user(task_pid_vnr(current), current->set_child_tid);
2260 * context_switch - switch to the new MM and the new
2261 * thread's register state.
2263 static inline void
2264 context_switch(struct rq *rq, struct task_struct *prev,
2265 struct task_struct *next)
2267 struct mm_struct *mm, *oldmm;
2269 prepare_task_switch(rq, prev, next);
2270 mm = next->mm;
2271 oldmm = prev->active_mm;
2273 * For paravirt, this is coupled with an exit in switch_to to
2274 * combine the page table reload and the switch backend into
2275 * one hypercall.
2277 arch_enter_lazy_cpu_mode();
2279 if (unlikely(!mm)) {
2280 next->active_mm = oldmm;
2281 atomic_inc(&oldmm->mm_count);
2282 enter_lazy_tlb(oldmm, next);
2283 } else
2284 switch_mm(oldmm, mm, next);
2286 if (unlikely(!prev->mm)) {
2287 prev->active_mm = NULL;
2288 rq->prev_mm = oldmm;
2291 * Since the runqueue lock will be released by the next
2292 * task (which is an invalid locking op but in the case
2293 * of the scheduler it's an obvious special-case), so we
2294 * do an early lockdep release here:
2296 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2297 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2298 #endif
2300 /* Here we just switch the register state and the stack. */
2301 switch_to(prev, next, prev);
2303 barrier();
2305 * this_rq must be evaluated again because prev may have moved
2306 * CPUs since it called schedule(), thus the 'rq' on its stack
2307 * frame will be invalid.
2309 finish_task_switch(this_rq(), prev);
2313 * nr_running, nr_uninterruptible and nr_context_switches:
2315 * externally visible scheduler statistics: current number of runnable
2316 * threads, current number of uninterruptible-sleeping threads, total
2317 * number of context switches performed since bootup.
2319 unsigned long nr_running(void)
2321 unsigned long i, sum = 0;
2323 for_each_online_cpu(i)
2324 sum += cpu_rq(i)->nr_running;
2326 return sum;
2329 unsigned long nr_uninterruptible(void)
2331 unsigned long i, sum = 0;
2333 for_each_possible_cpu(i)
2334 sum += cpu_rq(i)->nr_uninterruptible;
2337 * Since we read the counters lockless, it might be slightly
2338 * inaccurate. Do not allow it to go below zero though:
2340 if (unlikely((long)sum < 0))
2341 sum = 0;
2343 return sum;
2346 unsigned long long nr_context_switches(void)
2348 int i;
2349 unsigned long long sum = 0;
2351 for_each_possible_cpu(i)
2352 sum += cpu_rq(i)->nr_switches;
2354 return sum;
2357 unsigned long nr_iowait(void)
2359 unsigned long i, sum = 0;
2361 for_each_possible_cpu(i)
2362 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2364 return sum;
2367 unsigned long nr_active(void)
2369 unsigned long i, running = 0, uninterruptible = 0;
2371 for_each_online_cpu(i) {
2372 running += cpu_rq(i)->nr_running;
2373 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2376 if (unlikely((long)uninterruptible < 0))
2377 uninterruptible = 0;
2379 return running + uninterruptible;
2383 * Update rq->cpu_load[] statistics. This function is usually called every
2384 * scheduler tick (TICK_NSEC).
2386 static void update_cpu_load(struct rq *this_rq)
2388 unsigned long this_load = this_rq->load.weight;
2389 int i, scale;
2391 this_rq->nr_load_updates++;
2393 /* Update our load: */
2394 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2395 unsigned long old_load, new_load;
2397 /* scale is effectively 1 << i now, and >> i divides by scale */
2399 old_load = this_rq->cpu_load[i];
2400 new_load = this_load;
2402 * Round up the averaging division if load is increasing. This
2403 * prevents us from getting stuck on 9 if the load is 10, for
2404 * example.
2406 if (new_load > old_load)
2407 new_load += scale-1;
2408 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2412 #ifdef CONFIG_SMP
2415 * double_rq_lock - safely lock two runqueues
2417 * Note this does not disable interrupts like task_rq_lock,
2418 * you need to do so manually before calling.
2420 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2421 __acquires(rq1->lock)
2422 __acquires(rq2->lock)
2424 BUG_ON(!irqs_disabled());
2425 if (rq1 == rq2) {
2426 spin_lock(&rq1->lock);
2427 __acquire(rq2->lock); /* Fake it out ;) */
2428 } else {
2429 if (rq1 < rq2) {
2430 spin_lock(&rq1->lock);
2431 spin_lock(&rq2->lock);
2432 } else {
2433 spin_lock(&rq2->lock);
2434 spin_lock(&rq1->lock);
2437 update_rq_clock(rq1);
2438 update_rq_clock(rq2);
2442 * double_rq_unlock - safely unlock two runqueues
2444 * Note this does not restore interrupts like task_rq_unlock,
2445 * you need to do so manually after calling.
2447 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2448 __releases(rq1->lock)
2449 __releases(rq2->lock)
2451 spin_unlock(&rq1->lock);
2452 if (rq1 != rq2)
2453 spin_unlock(&rq2->lock);
2454 else
2455 __release(rq2->lock);
2459 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2461 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2462 __releases(this_rq->lock)
2463 __acquires(busiest->lock)
2464 __acquires(this_rq->lock)
2466 int ret = 0;
2468 if (unlikely(!irqs_disabled())) {
2469 /* printk() doesn't work good under rq->lock */
2470 spin_unlock(&this_rq->lock);
2471 BUG_ON(1);
2473 if (unlikely(!spin_trylock(&busiest->lock))) {
2474 if (busiest < this_rq) {
2475 spin_unlock(&this_rq->lock);
2476 spin_lock(&busiest->lock);
2477 spin_lock(&this_rq->lock);
2478 ret = 1;
2479 } else
2480 spin_lock(&busiest->lock);
2482 return ret;
2486 * If dest_cpu is allowed for this process, migrate the task to it.
2487 * This is accomplished by forcing the cpu_allowed mask to only
2488 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2489 * the cpu_allowed mask is restored.
2491 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2493 struct migration_req req;
2494 unsigned long flags;
2495 struct rq *rq;
2497 rq = task_rq_lock(p, &flags);
2498 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2499 || unlikely(cpu_is_offline(dest_cpu)))
2500 goto out;
2502 /* force the process onto the specified CPU */
2503 if (migrate_task(p, dest_cpu, &req)) {
2504 /* Need to wait for migration thread (might exit: take ref). */
2505 struct task_struct *mt = rq->migration_thread;
2507 get_task_struct(mt);
2508 task_rq_unlock(rq, &flags);
2509 wake_up_process(mt);
2510 put_task_struct(mt);
2511 wait_for_completion(&req.done);
2513 return;
2515 out:
2516 task_rq_unlock(rq, &flags);
2520 * sched_exec - execve() is a valuable balancing opportunity, because at
2521 * this point the task has the smallest effective memory and cache footprint.
2523 void sched_exec(void)
2525 int new_cpu, this_cpu = get_cpu();
2526 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2527 put_cpu();
2528 if (new_cpu != this_cpu)
2529 sched_migrate_task(current, new_cpu);
2533 * pull_task - move a task from a remote runqueue to the local runqueue.
2534 * Both runqueues must be locked.
2536 static void pull_task(struct rq *src_rq, struct task_struct *p,
2537 struct rq *this_rq, int this_cpu)
2539 deactivate_task(src_rq, p, 0);
2540 set_task_cpu(p, this_cpu);
2541 activate_task(this_rq, p, 0);
2543 * Note that idle threads have a prio of MAX_PRIO, for this test
2544 * to be always true for them.
2546 check_preempt_curr(this_rq, p);
2550 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2552 static
2553 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2554 struct sched_domain *sd, enum cpu_idle_type idle,
2555 int *all_pinned)
2558 * We do not migrate tasks that are:
2559 * 1) running (obviously), or
2560 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2561 * 3) are cache-hot on their current CPU.
2563 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2564 schedstat_inc(p, se.nr_failed_migrations_affine);
2565 return 0;
2567 *all_pinned = 0;
2569 if (task_running(rq, p)) {
2570 schedstat_inc(p, se.nr_failed_migrations_running);
2571 return 0;
2575 * Aggressive migration if:
2576 * 1) task is cache cold, or
2577 * 2) too many balance attempts have failed.
2580 if (!task_hot(p, rq->clock, sd) ||
2581 sd->nr_balance_failed > sd->cache_nice_tries) {
2582 #ifdef CONFIG_SCHEDSTATS
2583 if (task_hot(p, rq->clock, sd)) {
2584 schedstat_inc(sd, lb_hot_gained[idle]);
2585 schedstat_inc(p, se.nr_forced_migrations);
2587 #endif
2588 return 1;
2591 if (task_hot(p, rq->clock, sd)) {
2592 schedstat_inc(p, se.nr_failed_migrations_hot);
2593 return 0;
2595 return 1;
2598 static unsigned long
2599 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2600 unsigned long max_load_move, struct sched_domain *sd,
2601 enum cpu_idle_type idle, int *all_pinned,
2602 int *this_best_prio, struct rq_iterator *iterator)
2604 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
2605 struct task_struct *p;
2606 long rem_load_move = max_load_move;
2608 if (max_load_move == 0)
2609 goto out;
2611 pinned = 1;
2614 * Start the load-balancing iterator:
2616 p = iterator->start(iterator->arg);
2617 next:
2618 if (!p || loops++ > sysctl_sched_nr_migrate)
2619 goto out;
2621 * To help distribute high priority tasks across CPUs we don't
2622 * skip a task if it will be the highest priority task (i.e. smallest
2623 * prio value) on its new queue regardless of its load weight
2625 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2626 SCHED_LOAD_SCALE_FUZZ;
2627 if ((skip_for_load && p->prio >= *this_best_prio) ||
2628 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2629 p = iterator->next(iterator->arg);
2630 goto next;
2633 pull_task(busiest, p, this_rq, this_cpu);
2634 pulled++;
2635 rem_load_move -= p->se.load.weight;
2638 * We only want to steal up to the prescribed amount of weighted load.
2640 if (rem_load_move > 0) {
2641 if (p->prio < *this_best_prio)
2642 *this_best_prio = p->prio;
2643 p = iterator->next(iterator->arg);
2644 goto next;
2646 out:
2648 * Right now, this is one of only two places pull_task() is called,
2649 * so we can safely collect pull_task() stats here rather than
2650 * inside pull_task().
2652 schedstat_add(sd, lb_gained[idle], pulled);
2654 if (all_pinned)
2655 *all_pinned = pinned;
2657 return max_load_move - rem_load_move;
2661 * move_tasks tries to move up to max_load_move weighted load from busiest to
2662 * this_rq, as part of a balancing operation within domain "sd".
2663 * Returns 1 if successful and 0 otherwise.
2665 * Called with both runqueues locked.
2667 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2668 unsigned long max_load_move,
2669 struct sched_domain *sd, enum cpu_idle_type idle,
2670 int *all_pinned)
2672 const struct sched_class *class = sched_class_highest;
2673 unsigned long total_load_moved = 0;
2674 int this_best_prio = this_rq->curr->prio;
2676 do {
2677 total_load_moved +=
2678 class->load_balance(this_rq, this_cpu, busiest,
2679 max_load_move - total_load_moved,
2680 sd, idle, all_pinned, &this_best_prio);
2681 class = class->next;
2682 } while (class && max_load_move > total_load_moved);
2684 return total_load_moved > 0;
2687 static int
2688 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2689 struct sched_domain *sd, enum cpu_idle_type idle,
2690 struct rq_iterator *iterator)
2692 struct task_struct *p = iterator->start(iterator->arg);
2693 int pinned = 0;
2695 while (p) {
2696 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2697 pull_task(busiest, p, this_rq, this_cpu);
2699 * Right now, this is only the second place pull_task()
2700 * is called, so we can safely collect pull_task()
2701 * stats here rather than inside pull_task().
2703 schedstat_inc(sd, lb_gained[idle]);
2705 return 1;
2707 p = iterator->next(iterator->arg);
2710 return 0;
2714 * move_one_task tries to move exactly one task from busiest to this_rq, as
2715 * part of active balancing operations within "domain".
2716 * Returns 1 if successful and 0 otherwise.
2718 * Called with both runqueues locked.
2720 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2721 struct sched_domain *sd, enum cpu_idle_type idle)
2723 const struct sched_class *class;
2725 for (class = sched_class_highest; class; class = class->next)
2726 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
2727 return 1;
2729 return 0;
2733 * find_busiest_group finds and returns the busiest CPU group within the
2734 * domain. It calculates and returns the amount of weighted load which
2735 * should be moved to restore balance via the imbalance parameter.
2737 static struct sched_group *
2738 find_busiest_group(struct sched_domain *sd, int this_cpu,
2739 unsigned long *imbalance, enum cpu_idle_type idle,
2740 int *sd_idle, cpumask_t *cpus, int *balance)
2742 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2743 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2744 unsigned long max_pull;
2745 unsigned long busiest_load_per_task, busiest_nr_running;
2746 unsigned long this_load_per_task, this_nr_running;
2747 int load_idx, group_imb = 0;
2748 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2749 int power_savings_balance = 1;
2750 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2751 unsigned long min_nr_running = ULONG_MAX;
2752 struct sched_group *group_min = NULL, *group_leader = NULL;
2753 #endif
2755 max_load = this_load = total_load = total_pwr = 0;
2756 busiest_load_per_task = busiest_nr_running = 0;
2757 this_load_per_task = this_nr_running = 0;
2758 if (idle == CPU_NOT_IDLE)
2759 load_idx = sd->busy_idx;
2760 else if (idle == CPU_NEWLY_IDLE)
2761 load_idx = sd->newidle_idx;
2762 else
2763 load_idx = sd->idle_idx;
2765 do {
2766 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
2767 int local_group;
2768 int i;
2769 int __group_imb = 0;
2770 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2771 unsigned long sum_nr_running, sum_weighted_load;
2773 local_group = cpu_isset(this_cpu, group->cpumask);
2775 if (local_group)
2776 balance_cpu = first_cpu(group->cpumask);
2778 /* Tally up the load of all CPUs in the group */
2779 sum_weighted_load = sum_nr_running = avg_load = 0;
2780 max_cpu_load = 0;
2781 min_cpu_load = ~0UL;
2783 for_each_cpu_mask(i, group->cpumask) {
2784 struct rq *rq;
2786 if (!cpu_isset(i, *cpus))
2787 continue;
2789 rq = cpu_rq(i);
2791 if (*sd_idle && rq->nr_running)
2792 *sd_idle = 0;
2794 /* Bias balancing toward cpus of our domain */
2795 if (local_group) {
2796 if (idle_cpu(i) && !first_idle_cpu) {
2797 first_idle_cpu = 1;
2798 balance_cpu = i;
2801 load = target_load(i, load_idx);
2802 } else {
2803 load = source_load(i, load_idx);
2804 if (load > max_cpu_load)
2805 max_cpu_load = load;
2806 if (min_cpu_load > load)
2807 min_cpu_load = load;
2810 avg_load += load;
2811 sum_nr_running += rq->nr_running;
2812 sum_weighted_load += weighted_cpuload(i);
2816 * First idle cpu or the first cpu(busiest) in this sched group
2817 * is eligible for doing load balancing at this and above
2818 * domains. In the newly idle case, we will allow all the cpu's
2819 * to do the newly idle load balance.
2821 if (idle != CPU_NEWLY_IDLE && local_group &&
2822 balance_cpu != this_cpu && balance) {
2823 *balance = 0;
2824 goto ret;
2827 total_load += avg_load;
2828 total_pwr += group->__cpu_power;
2830 /* Adjust by relative CPU power of the group */
2831 avg_load = sg_div_cpu_power(group,
2832 avg_load * SCHED_LOAD_SCALE);
2834 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2835 __group_imb = 1;
2837 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2839 if (local_group) {
2840 this_load = avg_load;
2841 this = group;
2842 this_nr_running = sum_nr_running;
2843 this_load_per_task = sum_weighted_load;
2844 } else if (avg_load > max_load &&
2845 (sum_nr_running > group_capacity || __group_imb)) {
2846 max_load = avg_load;
2847 busiest = group;
2848 busiest_nr_running = sum_nr_running;
2849 busiest_load_per_task = sum_weighted_load;
2850 group_imb = __group_imb;
2853 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2855 * Busy processors will not participate in power savings
2856 * balance.
2858 if (idle == CPU_NOT_IDLE ||
2859 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2860 goto group_next;
2863 * If the local group is idle or completely loaded
2864 * no need to do power savings balance at this domain
2866 if (local_group && (this_nr_running >= group_capacity ||
2867 !this_nr_running))
2868 power_savings_balance = 0;
2871 * If a group is already running at full capacity or idle,
2872 * don't include that group in power savings calculations
2874 if (!power_savings_balance || sum_nr_running >= group_capacity
2875 || !sum_nr_running)
2876 goto group_next;
2879 * Calculate the group which has the least non-idle load.
2880 * This is the group from where we need to pick up the load
2881 * for saving power
2883 if ((sum_nr_running < min_nr_running) ||
2884 (sum_nr_running == min_nr_running &&
2885 first_cpu(group->cpumask) <
2886 first_cpu(group_min->cpumask))) {
2887 group_min = group;
2888 min_nr_running = sum_nr_running;
2889 min_load_per_task = sum_weighted_load /
2890 sum_nr_running;
2894 * Calculate the group which is almost near its
2895 * capacity but still has some space to pick up some load
2896 * from other group and save more power
2898 if (sum_nr_running <= group_capacity - 1) {
2899 if (sum_nr_running > leader_nr_running ||
2900 (sum_nr_running == leader_nr_running &&
2901 first_cpu(group->cpumask) >
2902 first_cpu(group_leader->cpumask))) {
2903 group_leader = group;
2904 leader_nr_running = sum_nr_running;
2907 group_next:
2908 #endif
2909 group = group->next;
2910 } while (group != sd->groups);
2912 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2913 goto out_balanced;
2915 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2917 if (this_load >= avg_load ||
2918 100*max_load <= sd->imbalance_pct*this_load)
2919 goto out_balanced;
2921 busiest_load_per_task /= busiest_nr_running;
2922 if (group_imb)
2923 busiest_load_per_task = min(busiest_load_per_task, avg_load);
2926 * We're trying to get all the cpus to the average_load, so we don't
2927 * want to push ourselves above the average load, nor do we wish to
2928 * reduce the max loaded cpu below the average load, as either of these
2929 * actions would just result in more rebalancing later, and ping-pong
2930 * tasks around. Thus we look for the minimum possible imbalance.
2931 * Negative imbalances (*we* are more loaded than anyone else) will
2932 * be counted as no imbalance for these purposes -- we can't fix that
2933 * by pulling tasks to us. Be careful of negative numbers as they'll
2934 * appear as very large values with unsigned longs.
2936 if (max_load <= busiest_load_per_task)
2937 goto out_balanced;
2940 * In the presence of smp nice balancing, certain scenarios can have
2941 * max load less than avg load(as we skip the groups at or below
2942 * its cpu_power, while calculating max_load..)
2944 if (max_load < avg_load) {
2945 *imbalance = 0;
2946 goto small_imbalance;
2949 /* Don't want to pull so many tasks that a group would go idle */
2950 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2952 /* How much load to actually move to equalise the imbalance */
2953 *imbalance = min(max_pull * busiest->__cpu_power,
2954 (avg_load - this_load) * this->__cpu_power)
2955 / SCHED_LOAD_SCALE;
2958 * if *imbalance is less than the average load per runnable task
2959 * there is no gaurantee that any tasks will be moved so we'll have
2960 * a think about bumping its value to force at least one task to be
2961 * moved
2963 if (*imbalance < busiest_load_per_task) {
2964 unsigned long tmp, pwr_now, pwr_move;
2965 unsigned int imbn;
2967 small_imbalance:
2968 pwr_move = pwr_now = 0;
2969 imbn = 2;
2970 if (this_nr_running) {
2971 this_load_per_task /= this_nr_running;
2972 if (busiest_load_per_task > this_load_per_task)
2973 imbn = 1;
2974 } else
2975 this_load_per_task = SCHED_LOAD_SCALE;
2977 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2978 busiest_load_per_task * imbn) {
2979 *imbalance = busiest_load_per_task;
2980 return busiest;
2984 * OK, we don't have enough imbalance to justify moving tasks,
2985 * however we may be able to increase total CPU power used by
2986 * moving them.
2989 pwr_now += busiest->__cpu_power *
2990 min(busiest_load_per_task, max_load);
2991 pwr_now += this->__cpu_power *
2992 min(this_load_per_task, this_load);
2993 pwr_now /= SCHED_LOAD_SCALE;
2995 /* Amount of load we'd subtract */
2996 tmp = sg_div_cpu_power(busiest,
2997 busiest_load_per_task * SCHED_LOAD_SCALE);
2998 if (max_load > tmp)
2999 pwr_move += busiest->__cpu_power *
3000 min(busiest_load_per_task, max_load - tmp);
3002 /* Amount of load we'd add */
3003 if (max_load * busiest->__cpu_power <
3004 busiest_load_per_task * SCHED_LOAD_SCALE)
3005 tmp = sg_div_cpu_power(this,
3006 max_load * busiest->__cpu_power);
3007 else
3008 tmp = sg_div_cpu_power(this,
3009 busiest_load_per_task * SCHED_LOAD_SCALE);
3010 pwr_move += this->__cpu_power *
3011 min(this_load_per_task, this_load + tmp);
3012 pwr_move /= SCHED_LOAD_SCALE;
3014 /* Move if we gain throughput */
3015 if (pwr_move > pwr_now)
3016 *imbalance = busiest_load_per_task;
3019 return busiest;
3021 out_balanced:
3022 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3023 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3024 goto ret;
3026 if (this == group_leader && group_leader != group_min) {
3027 *imbalance = min_load_per_task;
3028 return group_min;
3030 #endif
3031 ret:
3032 *imbalance = 0;
3033 return NULL;
3037 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3039 static struct rq *
3040 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3041 unsigned long imbalance, cpumask_t *cpus)
3043 struct rq *busiest = NULL, *rq;
3044 unsigned long max_load = 0;
3045 int i;
3047 for_each_cpu_mask(i, group->cpumask) {
3048 unsigned long wl;
3050 if (!cpu_isset(i, *cpus))
3051 continue;
3053 rq = cpu_rq(i);
3054 wl = weighted_cpuload(i);
3056 if (rq->nr_running == 1 && wl > imbalance)
3057 continue;
3059 if (wl > max_load) {
3060 max_load = wl;
3061 busiest = rq;
3065 return busiest;
3069 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3070 * so long as it is large enough.
3072 #define MAX_PINNED_INTERVAL 512
3075 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3076 * tasks if there is an imbalance.
3078 static int load_balance(int this_cpu, struct rq *this_rq,
3079 struct sched_domain *sd, enum cpu_idle_type idle,
3080 int *balance)
3082 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3083 struct sched_group *group;
3084 unsigned long imbalance;
3085 struct rq *busiest;
3086 cpumask_t cpus = CPU_MASK_ALL;
3087 unsigned long flags;
3090 * When power savings policy is enabled for the parent domain, idle
3091 * sibling can pick up load irrespective of busy siblings. In this case,
3092 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3093 * portraying it as CPU_NOT_IDLE.
3095 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3096 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3097 sd_idle = 1;
3099 schedstat_inc(sd, lb_count[idle]);
3101 redo:
3102 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3103 &cpus, balance);
3105 if (*balance == 0)
3106 goto out_balanced;
3108 if (!group) {
3109 schedstat_inc(sd, lb_nobusyg[idle]);
3110 goto out_balanced;
3113 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
3114 if (!busiest) {
3115 schedstat_inc(sd, lb_nobusyq[idle]);
3116 goto out_balanced;
3119 BUG_ON(busiest == this_rq);
3121 schedstat_add(sd, lb_imbalance[idle], imbalance);
3123 ld_moved = 0;
3124 if (busiest->nr_running > 1) {
3126 * Attempt to move tasks. If find_busiest_group has found
3127 * an imbalance but busiest->nr_running <= 1, the group is
3128 * still unbalanced. ld_moved simply stays zero, so it is
3129 * correctly treated as an imbalance.
3131 local_irq_save(flags);
3132 double_rq_lock(this_rq, busiest);
3133 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3134 imbalance, sd, idle, &all_pinned);
3135 double_rq_unlock(this_rq, busiest);
3136 local_irq_restore(flags);
3139 * some other cpu did the load balance for us.
3141 if (ld_moved && this_cpu != smp_processor_id())
3142 resched_cpu(this_cpu);
3144 /* All tasks on this runqueue were pinned by CPU affinity */
3145 if (unlikely(all_pinned)) {
3146 cpu_clear(cpu_of(busiest), cpus);
3147 if (!cpus_empty(cpus))
3148 goto redo;
3149 goto out_balanced;
3153 if (!ld_moved) {
3154 schedstat_inc(sd, lb_failed[idle]);
3155 sd->nr_balance_failed++;
3157 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3159 spin_lock_irqsave(&busiest->lock, flags);
3161 /* don't kick the migration_thread, if the curr
3162 * task on busiest cpu can't be moved to this_cpu
3164 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3165 spin_unlock_irqrestore(&busiest->lock, flags);
3166 all_pinned = 1;
3167 goto out_one_pinned;
3170 if (!busiest->active_balance) {
3171 busiest->active_balance = 1;
3172 busiest->push_cpu = this_cpu;
3173 active_balance = 1;
3175 spin_unlock_irqrestore(&busiest->lock, flags);
3176 if (active_balance)
3177 wake_up_process(busiest->migration_thread);
3180 * We've kicked active balancing, reset the failure
3181 * counter.
3183 sd->nr_balance_failed = sd->cache_nice_tries+1;
3185 } else
3186 sd->nr_balance_failed = 0;
3188 if (likely(!active_balance)) {
3189 /* We were unbalanced, so reset the balancing interval */
3190 sd->balance_interval = sd->min_interval;
3191 } else {
3193 * If we've begun active balancing, start to back off. This
3194 * case may not be covered by the all_pinned logic if there
3195 * is only 1 task on the busy runqueue (because we don't call
3196 * move_tasks).
3198 if (sd->balance_interval < sd->max_interval)
3199 sd->balance_interval *= 2;
3202 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3203 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3204 return -1;
3205 return ld_moved;
3207 out_balanced:
3208 schedstat_inc(sd, lb_balanced[idle]);
3210 sd->nr_balance_failed = 0;
3212 out_one_pinned:
3213 /* tune up the balancing interval */
3214 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3215 (sd->balance_interval < sd->max_interval))
3216 sd->balance_interval *= 2;
3218 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3219 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3220 return -1;
3221 return 0;
3225 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3226 * tasks if there is an imbalance.
3228 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3229 * this_rq is locked.
3231 static int
3232 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
3234 struct sched_group *group;
3235 struct rq *busiest = NULL;
3236 unsigned long imbalance;
3237 int ld_moved = 0;
3238 int sd_idle = 0;
3239 int all_pinned = 0;
3240 cpumask_t cpus = CPU_MASK_ALL;
3243 * When power savings policy is enabled for the parent domain, idle
3244 * sibling can pick up load irrespective of busy siblings. In this case,
3245 * let the state of idle sibling percolate up as IDLE, instead of
3246 * portraying it as CPU_NOT_IDLE.
3248 if (sd->flags & SD_SHARE_CPUPOWER &&
3249 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3250 sd_idle = 1;
3252 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3253 redo:
3254 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3255 &sd_idle, &cpus, NULL);
3256 if (!group) {
3257 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3258 goto out_balanced;
3261 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
3262 &cpus);
3263 if (!busiest) {
3264 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3265 goto out_balanced;
3268 BUG_ON(busiest == this_rq);
3270 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3272 ld_moved = 0;
3273 if (busiest->nr_running > 1) {
3274 /* Attempt to move tasks */
3275 double_lock_balance(this_rq, busiest);
3276 /* this_rq->clock is already updated */
3277 update_rq_clock(busiest);
3278 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3279 imbalance, sd, CPU_NEWLY_IDLE,
3280 &all_pinned);
3281 spin_unlock(&busiest->lock);
3283 if (unlikely(all_pinned)) {
3284 cpu_clear(cpu_of(busiest), cpus);
3285 if (!cpus_empty(cpus))
3286 goto redo;
3290 if (!ld_moved) {
3291 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3292 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3293 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3294 return -1;
3295 } else
3296 sd->nr_balance_failed = 0;
3298 return ld_moved;
3300 out_balanced:
3301 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3302 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3303 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3304 return -1;
3305 sd->nr_balance_failed = 0;
3307 return 0;
3311 * idle_balance is called by schedule() if this_cpu is about to become
3312 * idle. Attempts to pull tasks from other CPUs.
3314 static void idle_balance(int this_cpu, struct rq *this_rq)
3316 struct sched_domain *sd;
3317 int pulled_task = -1;
3318 unsigned long next_balance = jiffies + HZ;
3320 for_each_domain(this_cpu, sd) {
3321 unsigned long interval;
3323 if (!(sd->flags & SD_LOAD_BALANCE))
3324 continue;
3326 if (sd->flags & SD_BALANCE_NEWIDLE)
3327 /* If we've pulled tasks over stop searching: */
3328 pulled_task = load_balance_newidle(this_cpu,
3329 this_rq, sd);
3331 interval = msecs_to_jiffies(sd->balance_interval);
3332 if (time_after(next_balance, sd->last_balance + interval))
3333 next_balance = sd->last_balance + interval;
3334 if (pulled_task)
3335 break;
3337 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3339 * We are going idle. next_balance may be set based on
3340 * a busy processor. So reset next_balance.
3342 this_rq->next_balance = next_balance;
3347 * active_load_balance is run by migration threads. It pushes running tasks
3348 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3349 * running on each physical CPU where possible, and avoids physical /
3350 * logical imbalances.
3352 * Called with busiest_rq locked.
3354 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3356 int target_cpu = busiest_rq->push_cpu;
3357 struct sched_domain *sd;
3358 struct rq *target_rq;
3360 /* Is there any task to move? */
3361 if (busiest_rq->nr_running <= 1)
3362 return;
3364 target_rq = cpu_rq(target_cpu);
3367 * This condition is "impossible", if it occurs
3368 * we need to fix it. Originally reported by
3369 * Bjorn Helgaas on a 128-cpu setup.
3371 BUG_ON(busiest_rq == target_rq);
3373 /* move a task from busiest_rq to target_rq */
3374 double_lock_balance(busiest_rq, target_rq);
3375 update_rq_clock(busiest_rq);
3376 update_rq_clock(target_rq);
3378 /* Search for an sd spanning us and the target CPU. */
3379 for_each_domain(target_cpu, sd) {
3380 if ((sd->flags & SD_LOAD_BALANCE) &&
3381 cpu_isset(busiest_cpu, sd->span))
3382 break;
3385 if (likely(sd)) {
3386 schedstat_inc(sd, alb_count);
3388 if (move_one_task(target_rq, target_cpu, busiest_rq,
3389 sd, CPU_IDLE))
3390 schedstat_inc(sd, alb_pushed);
3391 else
3392 schedstat_inc(sd, alb_failed);
3394 spin_unlock(&target_rq->lock);
3397 #ifdef CONFIG_NO_HZ
3398 static struct {
3399 atomic_t load_balancer;
3400 cpumask_t cpu_mask;
3401 } nohz ____cacheline_aligned = {
3402 .load_balancer = ATOMIC_INIT(-1),
3403 .cpu_mask = CPU_MASK_NONE,
3407 * This routine will try to nominate the ilb (idle load balancing)
3408 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3409 * load balancing on behalf of all those cpus. If all the cpus in the system
3410 * go into this tickless mode, then there will be no ilb owner (as there is
3411 * no need for one) and all the cpus will sleep till the next wakeup event
3412 * arrives...
3414 * For the ilb owner, tick is not stopped. And this tick will be used
3415 * for idle load balancing. ilb owner will still be part of
3416 * nohz.cpu_mask..
3418 * While stopping the tick, this cpu will become the ilb owner if there
3419 * is no other owner. And will be the owner till that cpu becomes busy
3420 * or if all cpus in the system stop their ticks at which point
3421 * there is no need for ilb owner.
3423 * When the ilb owner becomes busy, it nominates another owner, during the
3424 * next busy scheduler_tick()
3426 int select_nohz_load_balancer(int stop_tick)
3428 int cpu = smp_processor_id();
3430 if (stop_tick) {
3431 cpu_set(cpu, nohz.cpu_mask);
3432 cpu_rq(cpu)->in_nohz_recently = 1;
3435 * If we are going offline and still the leader, give up!
3437 if (cpu_is_offline(cpu) &&
3438 atomic_read(&nohz.load_balancer) == cpu) {
3439 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3440 BUG();
3441 return 0;
3444 /* time for ilb owner also to sleep */
3445 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3446 if (atomic_read(&nohz.load_balancer) == cpu)
3447 atomic_set(&nohz.load_balancer, -1);
3448 return 0;
3451 if (atomic_read(&nohz.load_balancer) == -1) {
3452 /* make me the ilb owner */
3453 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3454 return 1;
3455 } else if (atomic_read(&nohz.load_balancer) == cpu)
3456 return 1;
3457 } else {
3458 if (!cpu_isset(cpu, nohz.cpu_mask))
3459 return 0;
3461 cpu_clear(cpu, nohz.cpu_mask);
3463 if (atomic_read(&nohz.load_balancer) == cpu)
3464 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3465 BUG();
3467 return 0;
3469 #endif
3471 static DEFINE_SPINLOCK(balancing);
3474 * It checks each scheduling domain to see if it is due to be balanced,
3475 * and initiates a balancing operation if so.
3477 * Balancing parameters are set up in arch_init_sched_domains.
3479 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3481 int balance = 1;
3482 struct rq *rq = cpu_rq(cpu);
3483 unsigned long interval;
3484 struct sched_domain *sd;
3485 /* Earliest time when we have to do rebalance again */
3486 unsigned long next_balance = jiffies + 60*HZ;
3487 int update_next_balance = 0;
3489 for_each_domain(cpu, sd) {
3490 if (!(sd->flags & SD_LOAD_BALANCE))
3491 continue;
3493 interval = sd->balance_interval;
3494 if (idle != CPU_IDLE)
3495 interval *= sd->busy_factor;
3497 /* scale ms to jiffies */
3498 interval = msecs_to_jiffies(interval);
3499 if (unlikely(!interval))
3500 interval = 1;
3501 if (interval > HZ*NR_CPUS/10)
3502 interval = HZ*NR_CPUS/10;
3505 if (sd->flags & SD_SERIALIZE) {
3506 if (!spin_trylock(&balancing))
3507 goto out;
3510 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3511 if (load_balance(cpu, rq, sd, idle, &balance)) {
3513 * We've pulled tasks over so either we're no
3514 * longer idle, or one of our SMT siblings is
3515 * not idle.
3517 idle = CPU_NOT_IDLE;
3519 sd->last_balance = jiffies;
3521 if (sd->flags & SD_SERIALIZE)
3522 spin_unlock(&balancing);
3523 out:
3524 if (time_after(next_balance, sd->last_balance + interval)) {
3525 next_balance = sd->last_balance + interval;
3526 update_next_balance = 1;
3530 * Stop the load balance at this level. There is another
3531 * CPU in our sched group which is doing load balancing more
3532 * actively.
3534 if (!balance)
3535 break;
3539 * next_balance will be updated only when there is a need.
3540 * When the cpu is attached to null domain for ex, it will not be
3541 * updated.
3543 if (likely(update_next_balance))
3544 rq->next_balance = next_balance;
3548 * run_rebalance_domains is triggered when needed from the scheduler tick.
3549 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3550 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3552 static void run_rebalance_domains(struct softirq_action *h)
3554 int this_cpu = smp_processor_id();
3555 struct rq *this_rq = cpu_rq(this_cpu);
3556 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3557 CPU_IDLE : CPU_NOT_IDLE;
3559 rebalance_domains(this_cpu, idle);
3561 #ifdef CONFIG_NO_HZ
3563 * If this cpu is the owner for idle load balancing, then do the
3564 * balancing on behalf of the other idle cpus whose ticks are
3565 * stopped.
3567 if (this_rq->idle_at_tick &&
3568 atomic_read(&nohz.load_balancer) == this_cpu) {
3569 cpumask_t cpus = nohz.cpu_mask;
3570 struct rq *rq;
3571 int balance_cpu;
3573 cpu_clear(this_cpu, cpus);
3574 for_each_cpu_mask(balance_cpu, cpus) {
3576 * If this cpu gets work to do, stop the load balancing
3577 * work being done for other cpus. Next load
3578 * balancing owner will pick it up.
3580 if (need_resched())
3581 break;
3583 rebalance_domains(balance_cpu, CPU_IDLE);
3585 rq = cpu_rq(balance_cpu);
3586 if (time_after(this_rq->next_balance, rq->next_balance))
3587 this_rq->next_balance = rq->next_balance;
3590 #endif
3594 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3596 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3597 * idle load balancing owner or decide to stop the periodic load balancing,
3598 * if the whole system is idle.
3600 static inline void trigger_load_balance(struct rq *rq, int cpu)
3602 #ifdef CONFIG_NO_HZ
3604 * If we were in the nohz mode recently and busy at the current
3605 * scheduler tick, then check if we need to nominate new idle
3606 * load balancer.
3608 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3609 rq->in_nohz_recently = 0;
3611 if (atomic_read(&nohz.load_balancer) == cpu) {
3612 cpu_clear(cpu, nohz.cpu_mask);
3613 atomic_set(&nohz.load_balancer, -1);
3616 if (atomic_read(&nohz.load_balancer) == -1) {
3618 * simple selection for now: Nominate the
3619 * first cpu in the nohz list to be the next
3620 * ilb owner.
3622 * TBD: Traverse the sched domains and nominate
3623 * the nearest cpu in the nohz.cpu_mask.
3625 int ilb = first_cpu(nohz.cpu_mask);
3627 if (ilb != NR_CPUS)
3628 resched_cpu(ilb);
3633 * If this cpu is idle and doing idle load balancing for all the
3634 * cpus with ticks stopped, is it time for that to stop?
3636 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3637 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3638 resched_cpu(cpu);
3639 return;
3643 * If this cpu is idle and the idle load balancing is done by
3644 * someone else, then no need raise the SCHED_SOFTIRQ
3646 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3647 cpu_isset(cpu, nohz.cpu_mask))
3648 return;
3649 #endif
3650 if (time_after_eq(jiffies, rq->next_balance))
3651 raise_softirq(SCHED_SOFTIRQ);
3654 #else /* CONFIG_SMP */
3657 * on UP we do not need to balance between CPUs:
3659 static inline void idle_balance(int cpu, struct rq *rq)
3663 #endif
3665 DEFINE_PER_CPU(struct kernel_stat, kstat);
3667 EXPORT_PER_CPU_SYMBOL(kstat);
3670 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3671 * that have not yet been banked in case the task is currently running.
3673 unsigned long long task_sched_runtime(struct task_struct *p)
3675 unsigned long flags;
3676 u64 ns, delta_exec;
3677 struct rq *rq;
3679 rq = task_rq_lock(p, &flags);
3680 ns = p->se.sum_exec_runtime;
3681 if (task_current(rq, p)) {
3682 update_rq_clock(rq);
3683 delta_exec = rq->clock - p->se.exec_start;
3684 if ((s64)delta_exec > 0)
3685 ns += delta_exec;
3687 task_rq_unlock(rq, &flags);
3689 return ns;
3693 * Account user cpu time to a process.
3694 * @p: the process that the cpu time gets accounted to
3695 * @cputime: the cpu time spent in user space since the last update
3697 void account_user_time(struct task_struct *p, cputime_t cputime)
3699 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3700 cputime64_t tmp;
3702 p->utime = cputime_add(p->utime, cputime);
3704 /* Add user time to cpustat. */
3705 tmp = cputime_to_cputime64(cputime);
3706 if (TASK_NICE(p) > 0)
3707 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3708 else
3709 cpustat->user = cputime64_add(cpustat->user, tmp);
3713 * Account guest cpu time to a process.
3714 * @p: the process that the cpu time gets accounted to
3715 * @cputime: the cpu time spent in virtual machine since the last update
3717 static void account_guest_time(struct task_struct *p, cputime_t cputime)
3719 cputime64_t tmp;
3720 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3722 tmp = cputime_to_cputime64(cputime);
3724 p->utime = cputime_add(p->utime, cputime);
3725 p->gtime = cputime_add(p->gtime, cputime);
3727 cpustat->user = cputime64_add(cpustat->user, tmp);
3728 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3732 * Account scaled user cpu time to a process.
3733 * @p: the process that the cpu time gets accounted to
3734 * @cputime: the cpu time spent in user space since the last update
3736 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3738 p->utimescaled = cputime_add(p->utimescaled, cputime);
3742 * Account system cpu time to a process.
3743 * @p: the process that the cpu time gets accounted to
3744 * @hardirq_offset: the offset to subtract from hardirq_count()
3745 * @cputime: the cpu time spent in kernel space since the last update
3747 void account_system_time(struct task_struct *p, int hardirq_offset,
3748 cputime_t cputime)
3750 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3751 struct rq *rq = this_rq();
3752 cputime64_t tmp;
3754 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3755 return account_guest_time(p, cputime);
3757 p->stime = cputime_add(p->stime, cputime);
3759 /* Add system time to cpustat. */
3760 tmp = cputime_to_cputime64(cputime);
3761 if (hardirq_count() - hardirq_offset)
3762 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3763 else if (softirq_count())
3764 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3765 else if (p != rq->idle)
3766 cpustat->system = cputime64_add(cpustat->system, tmp);
3767 else if (atomic_read(&rq->nr_iowait) > 0)
3768 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3769 else
3770 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3771 /* Account for system time used */
3772 acct_update_integrals(p);
3776 * Account scaled system cpu time to a process.
3777 * @p: the process that the cpu time gets accounted to
3778 * @hardirq_offset: the offset to subtract from hardirq_count()
3779 * @cputime: the cpu time spent in kernel space since the last update
3781 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3783 p->stimescaled = cputime_add(p->stimescaled, cputime);
3787 * Account for involuntary wait time.
3788 * @p: the process from which the cpu time has been stolen
3789 * @steal: the cpu time spent in involuntary wait
3791 void account_steal_time(struct task_struct *p, cputime_t steal)
3793 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3794 cputime64_t tmp = cputime_to_cputime64(steal);
3795 struct rq *rq = this_rq();
3797 if (p == rq->idle) {
3798 p->stime = cputime_add(p->stime, steal);
3799 if (atomic_read(&rq->nr_iowait) > 0)
3800 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3801 else
3802 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3803 } else
3804 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3808 * This function gets called by the timer code, with HZ frequency.
3809 * We call it with interrupts disabled.
3811 * It also gets called by the fork code, when changing the parent's
3812 * timeslices.
3814 void scheduler_tick(void)
3816 int cpu = smp_processor_id();
3817 struct rq *rq = cpu_rq(cpu);
3818 struct task_struct *curr = rq->curr;
3819 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3821 spin_lock(&rq->lock);
3822 __update_rq_clock(rq);
3824 * Let rq->clock advance by at least TICK_NSEC:
3826 if (unlikely(rq->clock < next_tick)) {
3827 rq->clock = next_tick;
3828 rq->clock_underflows++;
3830 rq->tick_timestamp = rq->clock;
3831 update_cpu_load(rq);
3832 curr->sched_class->task_tick(rq, curr, 0);
3833 update_sched_rt_period(rq);
3834 spin_unlock(&rq->lock);
3836 #ifdef CONFIG_SMP
3837 rq->idle_at_tick = idle_cpu(cpu);
3838 trigger_load_balance(rq, cpu);
3839 #endif
3842 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3844 void __kprobes add_preempt_count(int val)
3847 * Underflow?
3849 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3850 return;
3851 preempt_count() += val;
3853 * Spinlock count overflowing soon?
3855 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3856 PREEMPT_MASK - 10);
3858 EXPORT_SYMBOL(add_preempt_count);
3860 void __kprobes sub_preempt_count(int val)
3863 * Underflow?
3865 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3866 return;
3868 * Is the spinlock portion underflowing?
3870 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3871 !(preempt_count() & PREEMPT_MASK)))
3872 return;
3874 preempt_count() -= val;
3876 EXPORT_SYMBOL(sub_preempt_count);
3878 #endif
3881 * Print scheduling while atomic bug:
3883 static noinline void __schedule_bug(struct task_struct *prev)
3885 struct pt_regs *regs = get_irq_regs();
3887 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3888 prev->comm, prev->pid, preempt_count());
3890 debug_show_held_locks(prev);
3891 if (irqs_disabled())
3892 print_irqtrace_events(prev);
3894 if (regs)
3895 show_regs(regs);
3896 else
3897 dump_stack();
3901 * Various schedule()-time debugging checks and statistics:
3903 static inline void schedule_debug(struct task_struct *prev)
3906 * Test if we are atomic. Since do_exit() needs to call into
3907 * schedule() atomically, we ignore that path for now.
3908 * Otherwise, whine if we are scheduling when we should not be.
3910 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3911 __schedule_bug(prev);
3913 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3915 schedstat_inc(this_rq(), sched_count);
3916 #ifdef CONFIG_SCHEDSTATS
3917 if (unlikely(prev->lock_depth >= 0)) {
3918 schedstat_inc(this_rq(), bkl_count);
3919 schedstat_inc(prev, sched_info.bkl_count);
3921 #endif
3925 * Pick up the highest-prio task:
3927 static inline struct task_struct *
3928 pick_next_task(struct rq *rq, struct task_struct *prev)
3930 const struct sched_class *class;
3931 struct task_struct *p;
3934 * Optimization: we know that if all tasks are in
3935 * the fair class we can call that function directly:
3937 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3938 p = fair_sched_class.pick_next_task(rq);
3939 if (likely(p))
3940 return p;
3943 class = sched_class_highest;
3944 for ( ; ; ) {
3945 p = class->pick_next_task(rq);
3946 if (p)
3947 return p;
3949 * Will never be NULL as the idle class always
3950 * returns a non-NULL p:
3952 class = class->next;
3957 * schedule() is the main scheduler function.
3959 asmlinkage void __sched schedule(void)
3961 struct task_struct *prev, *next;
3962 unsigned long *switch_count;
3963 struct rq *rq;
3964 int cpu;
3966 need_resched:
3967 preempt_disable();
3968 cpu = smp_processor_id();
3969 rq = cpu_rq(cpu);
3970 rcu_qsctr_inc(cpu);
3971 prev = rq->curr;
3972 switch_count = &prev->nivcsw;
3974 release_kernel_lock(prev);
3975 need_resched_nonpreemptible:
3977 schedule_debug(prev);
3979 hrtick_clear(rq);
3982 * Do the rq-clock update outside the rq lock:
3984 local_irq_disable();
3985 __update_rq_clock(rq);
3986 spin_lock(&rq->lock);
3987 clear_tsk_need_resched(prev);
3989 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3990 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3991 signal_pending(prev))) {
3992 prev->state = TASK_RUNNING;
3993 } else {
3994 deactivate_task(rq, prev, 1);
3996 switch_count = &prev->nvcsw;
3999 #ifdef CONFIG_SMP
4000 if (prev->sched_class->pre_schedule)
4001 prev->sched_class->pre_schedule(rq, prev);
4002 #endif
4004 if (unlikely(!rq->nr_running))
4005 idle_balance(cpu, rq);
4007 prev->sched_class->put_prev_task(rq, prev);
4008 next = pick_next_task(rq, prev);
4010 sched_info_switch(prev, next);
4012 if (likely(prev != next)) {
4013 rq->nr_switches++;
4014 rq->curr = next;
4015 ++*switch_count;
4017 context_switch(rq, prev, next); /* unlocks the rq */
4019 * the context switch might have flipped the stack from under
4020 * us, hence refresh the local variables.
4022 cpu = smp_processor_id();
4023 rq = cpu_rq(cpu);
4024 } else
4025 spin_unlock_irq(&rq->lock);
4027 hrtick_set(rq);
4029 if (unlikely(reacquire_kernel_lock(current) < 0))
4030 goto need_resched_nonpreemptible;
4032 preempt_enable_no_resched();
4033 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4034 goto need_resched;
4036 EXPORT_SYMBOL(schedule);
4038 #ifdef CONFIG_PREEMPT
4040 * this is the entry point to schedule() from in-kernel preemption
4041 * off of preempt_enable. Kernel preemptions off return from interrupt
4042 * occur there and call schedule directly.
4044 asmlinkage void __sched preempt_schedule(void)
4046 struct thread_info *ti = current_thread_info();
4047 struct task_struct *task = current;
4048 int saved_lock_depth;
4051 * If there is a non-zero preempt_count or interrupts are disabled,
4052 * we do not want to preempt the current task. Just return..
4054 if (likely(ti->preempt_count || irqs_disabled()))
4055 return;
4057 do {
4058 add_preempt_count(PREEMPT_ACTIVE);
4061 * We keep the big kernel semaphore locked, but we
4062 * clear ->lock_depth so that schedule() doesnt
4063 * auto-release the semaphore:
4065 saved_lock_depth = task->lock_depth;
4066 task->lock_depth = -1;
4067 schedule();
4068 task->lock_depth = saved_lock_depth;
4069 sub_preempt_count(PREEMPT_ACTIVE);
4072 * Check again in case we missed a preemption opportunity
4073 * between schedule and now.
4075 barrier();
4076 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4078 EXPORT_SYMBOL(preempt_schedule);
4081 * this is the entry point to schedule() from kernel preemption
4082 * off of irq context.
4083 * Note, that this is called and return with irqs disabled. This will
4084 * protect us against recursive calling from irq.
4086 asmlinkage void __sched preempt_schedule_irq(void)
4088 struct thread_info *ti = current_thread_info();
4089 struct task_struct *task = current;
4090 int saved_lock_depth;
4092 /* Catch callers which need to be fixed */
4093 BUG_ON(ti->preempt_count || !irqs_disabled());
4095 do {
4096 add_preempt_count(PREEMPT_ACTIVE);
4099 * We keep the big kernel semaphore locked, but we
4100 * clear ->lock_depth so that schedule() doesnt
4101 * auto-release the semaphore:
4103 saved_lock_depth = task->lock_depth;
4104 task->lock_depth = -1;
4105 local_irq_enable();
4106 schedule();
4107 local_irq_disable();
4108 task->lock_depth = saved_lock_depth;
4109 sub_preempt_count(PREEMPT_ACTIVE);
4112 * Check again in case we missed a preemption opportunity
4113 * between schedule and now.
4115 barrier();
4116 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4119 #endif /* CONFIG_PREEMPT */
4121 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4122 void *key)
4124 return try_to_wake_up(curr->private, mode, sync);
4126 EXPORT_SYMBOL(default_wake_function);
4129 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4130 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4131 * number) then we wake all the non-exclusive tasks and one exclusive task.
4133 * There are circumstances in which we can try to wake a task which has already
4134 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4135 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4137 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4138 int nr_exclusive, int sync, void *key)
4140 wait_queue_t *curr, *next;
4142 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4143 unsigned flags = curr->flags;
4145 if (curr->func(curr, mode, sync, key) &&
4146 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4147 break;
4152 * __wake_up - wake up threads blocked on a waitqueue.
4153 * @q: the waitqueue
4154 * @mode: which threads
4155 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4156 * @key: is directly passed to the wakeup function
4158 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4159 int nr_exclusive, void *key)
4161 unsigned long flags;
4163 spin_lock_irqsave(&q->lock, flags);
4164 __wake_up_common(q, mode, nr_exclusive, 0, key);
4165 spin_unlock_irqrestore(&q->lock, flags);
4167 EXPORT_SYMBOL(__wake_up);
4170 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4172 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4174 __wake_up_common(q, mode, 1, 0, NULL);
4178 * __wake_up_sync - wake up threads blocked on a waitqueue.
4179 * @q: the waitqueue
4180 * @mode: which threads
4181 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4183 * The sync wakeup differs that the waker knows that it will schedule
4184 * away soon, so while the target thread will be woken up, it will not
4185 * be migrated to another CPU - ie. the two threads are 'synchronized'
4186 * with each other. This can prevent needless bouncing between CPUs.
4188 * On UP it can prevent extra preemption.
4190 void
4191 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4193 unsigned long flags;
4194 int sync = 1;
4196 if (unlikely(!q))
4197 return;
4199 if (unlikely(!nr_exclusive))
4200 sync = 0;
4202 spin_lock_irqsave(&q->lock, flags);
4203 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4204 spin_unlock_irqrestore(&q->lock, flags);
4206 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4208 void complete(struct completion *x)
4210 unsigned long flags;
4212 spin_lock_irqsave(&x->wait.lock, flags);
4213 x->done++;
4214 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4215 spin_unlock_irqrestore(&x->wait.lock, flags);
4217 EXPORT_SYMBOL(complete);
4219 void complete_all(struct completion *x)
4221 unsigned long flags;
4223 spin_lock_irqsave(&x->wait.lock, flags);
4224 x->done += UINT_MAX/2;
4225 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4226 spin_unlock_irqrestore(&x->wait.lock, flags);
4228 EXPORT_SYMBOL(complete_all);
4230 static inline long __sched
4231 do_wait_for_common(struct completion *x, long timeout, int state)
4233 if (!x->done) {
4234 DECLARE_WAITQUEUE(wait, current);
4236 wait.flags |= WQ_FLAG_EXCLUSIVE;
4237 __add_wait_queue_tail(&x->wait, &wait);
4238 do {
4239 if ((state == TASK_INTERRUPTIBLE &&
4240 signal_pending(current)) ||
4241 (state == TASK_KILLABLE &&
4242 fatal_signal_pending(current))) {
4243 __remove_wait_queue(&x->wait, &wait);
4244 return -ERESTARTSYS;
4246 __set_current_state(state);
4247 spin_unlock_irq(&x->wait.lock);
4248 timeout = schedule_timeout(timeout);
4249 spin_lock_irq(&x->wait.lock);
4250 if (!timeout) {
4251 __remove_wait_queue(&x->wait, &wait);
4252 return timeout;
4254 } while (!x->done);
4255 __remove_wait_queue(&x->wait, &wait);
4257 x->done--;
4258 return timeout;
4261 static long __sched
4262 wait_for_common(struct completion *x, long timeout, int state)
4264 might_sleep();
4266 spin_lock_irq(&x->wait.lock);
4267 timeout = do_wait_for_common(x, timeout, state);
4268 spin_unlock_irq(&x->wait.lock);
4269 return timeout;
4272 void __sched wait_for_completion(struct completion *x)
4274 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4276 EXPORT_SYMBOL(wait_for_completion);
4278 unsigned long __sched
4279 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4281 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4283 EXPORT_SYMBOL(wait_for_completion_timeout);
4285 int __sched wait_for_completion_interruptible(struct completion *x)
4287 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4288 if (t == -ERESTARTSYS)
4289 return t;
4290 return 0;
4292 EXPORT_SYMBOL(wait_for_completion_interruptible);
4294 unsigned long __sched
4295 wait_for_completion_interruptible_timeout(struct completion *x,
4296 unsigned long timeout)
4298 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4300 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4302 int __sched wait_for_completion_killable(struct completion *x)
4304 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4305 if (t == -ERESTARTSYS)
4306 return t;
4307 return 0;
4309 EXPORT_SYMBOL(wait_for_completion_killable);
4311 static long __sched
4312 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4314 unsigned long flags;
4315 wait_queue_t wait;
4317 init_waitqueue_entry(&wait, current);
4319 __set_current_state(state);
4321 spin_lock_irqsave(&q->lock, flags);
4322 __add_wait_queue(q, &wait);
4323 spin_unlock(&q->lock);
4324 timeout = schedule_timeout(timeout);
4325 spin_lock_irq(&q->lock);
4326 __remove_wait_queue(q, &wait);
4327 spin_unlock_irqrestore(&q->lock, flags);
4329 return timeout;
4332 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4334 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4336 EXPORT_SYMBOL(interruptible_sleep_on);
4338 long __sched
4339 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4341 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4343 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4345 void __sched sleep_on(wait_queue_head_t *q)
4347 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4349 EXPORT_SYMBOL(sleep_on);
4351 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4353 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4355 EXPORT_SYMBOL(sleep_on_timeout);
4357 #ifdef CONFIG_RT_MUTEXES
4360 * rt_mutex_setprio - set the current priority of a task
4361 * @p: task
4362 * @prio: prio value (kernel-internal form)
4364 * This function changes the 'effective' priority of a task. It does
4365 * not touch ->normal_prio like __setscheduler().
4367 * Used by the rt_mutex code to implement priority inheritance logic.
4369 void rt_mutex_setprio(struct task_struct *p, int prio)
4371 unsigned long flags;
4372 int oldprio, on_rq, running;
4373 struct rq *rq;
4374 const struct sched_class *prev_class = p->sched_class;
4376 BUG_ON(prio < 0 || prio > MAX_PRIO);
4378 rq = task_rq_lock(p, &flags);
4379 update_rq_clock(rq);
4381 oldprio = p->prio;
4382 on_rq = p->se.on_rq;
4383 running = task_current(rq, p);
4384 if (on_rq)
4385 dequeue_task(rq, p, 0);
4386 if (running)
4387 p->sched_class->put_prev_task(rq, p);
4389 if (rt_prio(prio))
4390 p->sched_class = &rt_sched_class;
4391 else
4392 p->sched_class = &fair_sched_class;
4394 p->prio = prio;
4396 if (running)
4397 p->sched_class->set_curr_task(rq);
4398 if (on_rq) {
4399 enqueue_task(rq, p, 0);
4401 check_class_changed(rq, p, prev_class, oldprio, running);
4403 task_rq_unlock(rq, &flags);
4406 #endif
4408 void set_user_nice(struct task_struct *p, long nice)
4410 int old_prio, delta, on_rq;
4411 unsigned long flags;
4412 struct rq *rq;
4414 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4415 return;
4417 * We have to be careful, if called from sys_setpriority(),
4418 * the task might be in the middle of scheduling on another CPU.
4420 rq = task_rq_lock(p, &flags);
4421 update_rq_clock(rq);
4423 * The RT priorities are set via sched_setscheduler(), but we still
4424 * allow the 'normal' nice value to be set - but as expected
4425 * it wont have any effect on scheduling until the task is
4426 * SCHED_FIFO/SCHED_RR:
4428 if (task_has_rt_policy(p)) {
4429 p->static_prio = NICE_TO_PRIO(nice);
4430 goto out_unlock;
4432 on_rq = p->se.on_rq;
4433 if (on_rq) {
4434 dequeue_task(rq, p, 0);
4435 dec_load(rq, p);
4438 p->static_prio = NICE_TO_PRIO(nice);
4439 set_load_weight(p);
4440 old_prio = p->prio;
4441 p->prio = effective_prio(p);
4442 delta = p->prio - old_prio;
4444 if (on_rq) {
4445 enqueue_task(rq, p, 0);
4446 inc_load(rq, p);
4448 * If the task increased its priority or is running and
4449 * lowered its priority, then reschedule its CPU:
4451 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4452 resched_task(rq->curr);
4454 out_unlock:
4455 task_rq_unlock(rq, &flags);
4457 EXPORT_SYMBOL(set_user_nice);
4460 * can_nice - check if a task can reduce its nice value
4461 * @p: task
4462 * @nice: nice value
4464 int can_nice(const struct task_struct *p, const int nice)
4466 /* convert nice value [19,-20] to rlimit style value [1,40] */
4467 int nice_rlim = 20 - nice;
4469 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4470 capable(CAP_SYS_NICE));
4473 #ifdef __ARCH_WANT_SYS_NICE
4476 * sys_nice - change the priority of the current process.
4477 * @increment: priority increment
4479 * sys_setpriority is a more generic, but much slower function that
4480 * does similar things.
4482 asmlinkage long sys_nice(int increment)
4484 long nice, retval;
4487 * Setpriority might change our priority at the same moment.
4488 * We don't have to worry. Conceptually one call occurs first
4489 * and we have a single winner.
4491 if (increment < -40)
4492 increment = -40;
4493 if (increment > 40)
4494 increment = 40;
4496 nice = PRIO_TO_NICE(current->static_prio) + increment;
4497 if (nice < -20)
4498 nice = -20;
4499 if (nice > 19)
4500 nice = 19;
4502 if (increment < 0 && !can_nice(current, nice))
4503 return -EPERM;
4505 retval = security_task_setnice(current, nice);
4506 if (retval)
4507 return retval;
4509 set_user_nice(current, nice);
4510 return 0;
4513 #endif
4516 * task_prio - return the priority value of a given task.
4517 * @p: the task in question.
4519 * This is the priority value as seen by users in /proc.
4520 * RT tasks are offset by -200. Normal tasks are centered
4521 * around 0, value goes from -16 to +15.
4523 int task_prio(const struct task_struct *p)
4525 return p->prio - MAX_RT_PRIO;
4529 * task_nice - return the nice value of a given task.
4530 * @p: the task in question.
4532 int task_nice(const struct task_struct *p)
4534 return TASK_NICE(p);
4536 EXPORT_SYMBOL(task_nice);
4539 * idle_cpu - is a given cpu idle currently?
4540 * @cpu: the processor in question.
4542 int idle_cpu(int cpu)
4544 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4548 * idle_task - return the idle task for a given cpu.
4549 * @cpu: the processor in question.
4551 struct task_struct *idle_task(int cpu)
4553 return cpu_rq(cpu)->idle;
4557 * find_process_by_pid - find a process with a matching PID value.
4558 * @pid: the pid in question.
4560 static struct task_struct *find_process_by_pid(pid_t pid)
4562 return pid ? find_task_by_vpid(pid) : current;
4565 /* Actually do priority change: must hold rq lock. */
4566 static void
4567 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4569 BUG_ON(p->se.on_rq);
4571 p->policy = policy;
4572 switch (p->policy) {
4573 case SCHED_NORMAL:
4574 case SCHED_BATCH:
4575 case SCHED_IDLE:
4576 p->sched_class = &fair_sched_class;
4577 break;
4578 case SCHED_FIFO:
4579 case SCHED_RR:
4580 p->sched_class = &rt_sched_class;
4581 break;
4584 p->rt_priority = prio;
4585 p->normal_prio = normal_prio(p);
4586 /* we are holding p->pi_lock already */
4587 p->prio = rt_mutex_getprio(p);
4588 set_load_weight(p);
4592 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4593 * @p: the task in question.
4594 * @policy: new policy.
4595 * @param: structure containing the new RT priority.
4597 * NOTE that the task may be already dead.
4599 int sched_setscheduler(struct task_struct *p, int policy,
4600 struct sched_param *param)
4602 int retval, oldprio, oldpolicy = -1, on_rq, running;
4603 unsigned long flags;
4604 const struct sched_class *prev_class = p->sched_class;
4605 struct rq *rq;
4607 /* may grab non-irq protected spin_locks */
4608 BUG_ON(in_interrupt());
4609 recheck:
4610 /* double check policy once rq lock held */
4611 if (policy < 0)
4612 policy = oldpolicy = p->policy;
4613 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4614 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4615 policy != SCHED_IDLE)
4616 return -EINVAL;
4618 * Valid priorities for SCHED_FIFO and SCHED_RR are
4619 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4620 * SCHED_BATCH and SCHED_IDLE is 0.
4622 if (param->sched_priority < 0 ||
4623 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4624 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4625 return -EINVAL;
4626 if (rt_policy(policy) != (param->sched_priority != 0))
4627 return -EINVAL;
4630 * Allow unprivileged RT tasks to decrease priority:
4632 if (!capable(CAP_SYS_NICE)) {
4633 if (rt_policy(policy)) {
4634 unsigned long rlim_rtprio;
4636 if (!lock_task_sighand(p, &flags))
4637 return -ESRCH;
4638 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4639 unlock_task_sighand(p, &flags);
4641 /* can't set/change the rt policy */
4642 if (policy != p->policy && !rlim_rtprio)
4643 return -EPERM;
4645 /* can't increase priority */
4646 if (param->sched_priority > p->rt_priority &&
4647 param->sched_priority > rlim_rtprio)
4648 return -EPERM;
4651 * Like positive nice levels, dont allow tasks to
4652 * move out of SCHED_IDLE either:
4654 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4655 return -EPERM;
4657 /* can't change other user's priorities */
4658 if ((current->euid != p->euid) &&
4659 (current->euid != p->uid))
4660 return -EPERM;
4663 #ifdef CONFIG_RT_GROUP_SCHED
4665 * Do not allow realtime tasks into groups that have no runtime
4666 * assigned.
4668 if (rt_policy(policy) && task_group(p)->rt_runtime == 0)
4669 return -EPERM;
4670 #endif
4672 retval = security_task_setscheduler(p, policy, param);
4673 if (retval)
4674 return retval;
4676 * make sure no PI-waiters arrive (or leave) while we are
4677 * changing the priority of the task:
4679 spin_lock_irqsave(&p->pi_lock, flags);
4681 * To be able to change p->policy safely, the apropriate
4682 * runqueue lock must be held.
4684 rq = __task_rq_lock(p);
4685 /* recheck policy now with rq lock held */
4686 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4687 policy = oldpolicy = -1;
4688 __task_rq_unlock(rq);
4689 spin_unlock_irqrestore(&p->pi_lock, flags);
4690 goto recheck;
4692 update_rq_clock(rq);
4693 on_rq = p->se.on_rq;
4694 running = task_current(rq, p);
4695 if (on_rq)
4696 deactivate_task(rq, p, 0);
4697 if (running)
4698 p->sched_class->put_prev_task(rq, p);
4700 oldprio = p->prio;
4701 __setscheduler(rq, p, policy, param->sched_priority);
4703 if (running)
4704 p->sched_class->set_curr_task(rq);
4705 if (on_rq) {
4706 activate_task(rq, p, 0);
4708 check_class_changed(rq, p, prev_class, oldprio, running);
4710 __task_rq_unlock(rq);
4711 spin_unlock_irqrestore(&p->pi_lock, flags);
4713 rt_mutex_adjust_pi(p);
4715 return 0;
4717 EXPORT_SYMBOL_GPL(sched_setscheduler);
4719 static int
4720 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4722 struct sched_param lparam;
4723 struct task_struct *p;
4724 int retval;
4726 if (!param || pid < 0)
4727 return -EINVAL;
4728 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4729 return -EFAULT;
4731 rcu_read_lock();
4732 retval = -ESRCH;
4733 p = find_process_by_pid(pid);
4734 if (p != NULL)
4735 retval = sched_setscheduler(p, policy, &lparam);
4736 rcu_read_unlock();
4738 return retval;
4742 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4743 * @pid: the pid in question.
4744 * @policy: new policy.
4745 * @param: structure containing the new RT priority.
4747 asmlinkage long
4748 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4750 /* negative values for policy are not valid */
4751 if (policy < 0)
4752 return -EINVAL;
4754 return do_sched_setscheduler(pid, policy, param);
4758 * sys_sched_setparam - set/change the RT priority of a thread
4759 * @pid: the pid in question.
4760 * @param: structure containing the new RT priority.
4762 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4764 return do_sched_setscheduler(pid, -1, param);
4768 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4769 * @pid: the pid in question.
4771 asmlinkage long sys_sched_getscheduler(pid_t pid)
4773 struct task_struct *p;
4774 int retval;
4776 if (pid < 0)
4777 return -EINVAL;
4779 retval = -ESRCH;
4780 read_lock(&tasklist_lock);
4781 p = find_process_by_pid(pid);
4782 if (p) {
4783 retval = security_task_getscheduler(p);
4784 if (!retval)
4785 retval = p->policy;
4787 read_unlock(&tasklist_lock);
4788 return retval;
4792 * sys_sched_getscheduler - get the RT priority of a thread
4793 * @pid: the pid in question.
4794 * @param: structure containing the RT priority.
4796 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4798 struct sched_param lp;
4799 struct task_struct *p;
4800 int retval;
4802 if (!param || pid < 0)
4803 return -EINVAL;
4805 read_lock(&tasklist_lock);
4806 p = find_process_by_pid(pid);
4807 retval = -ESRCH;
4808 if (!p)
4809 goto out_unlock;
4811 retval = security_task_getscheduler(p);
4812 if (retval)
4813 goto out_unlock;
4815 lp.sched_priority = p->rt_priority;
4816 read_unlock(&tasklist_lock);
4819 * This one might sleep, we cannot do it with a spinlock held ...
4821 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4823 return retval;
4825 out_unlock:
4826 read_unlock(&tasklist_lock);
4827 return retval;
4830 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4832 cpumask_t cpus_allowed;
4833 struct task_struct *p;
4834 int retval;
4836 get_online_cpus();
4837 read_lock(&tasklist_lock);
4839 p = find_process_by_pid(pid);
4840 if (!p) {
4841 read_unlock(&tasklist_lock);
4842 put_online_cpus();
4843 return -ESRCH;
4847 * It is not safe to call set_cpus_allowed with the
4848 * tasklist_lock held. We will bump the task_struct's
4849 * usage count and then drop tasklist_lock.
4851 get_task_struct(p);
4852 read_unlock(&tasklist_lock);
4854 retval = -EPERM;
4855 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4856 !capable(CAP_SYS_NICE))
4857 goto out_unlock;
4859 retval = security_task_setscheduler(p, 0, NULL);
4860 if (retval)
4861 goto out_unlock;
4863 cpus_allowed = cpuset_cpus_allowed(p);
4864 cpus_and(new_mask, new_mask, cpus_allowed);
4865 again:
4866 retval = set_cpus_allowed(p, new_mask);
4868 if (!retval) {
4869 cpus_allowed = cpuset_cpus_allowed(p);
4870 if (!cpus_subset(new_mask, cpus_allowed)) {
4872 * We must have raced with a concurrent cpuset
4873 * update. Just reset the cpus_allowed to the
4874 * cpuset's cpus_allowed
4876 new_mask = cpus_allowed;
4877 goto again;
4880 out_unlock:
4881 put_task_struct(p);
4882 put_online_cpus();
4883 return retval;
4886 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4887 cpumask_t *new_mask)
4889 if (len < sizeof(cpumask_t)) {
4890 memset(new_mask, 0, sizeof(cpumask_t));
4891 } else if (len > sizeof(cpumask_t)) {
4892 len = sizeof(cpumask_t);
4894 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4898 * sys_sched_setaffinity - set the cpu affinity of a process
4899 * @pid: pid of the process
4900 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4901 * @user_mask_ptr: user-space pointer to the new cpu mask
4903 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4904 unsigned long __user *user_mask_ptr)
4906 cpumask_t new_mask;
4907 int retval;
4909 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4910 if (retval)
4911 return retval;
4913 return sched_setaffinity(pid, new_mask);
4917 * Represents all cpu's present in the system
4918 * In systems capable of hotplug, this map could dynamically grow
4919 * as new cpu's are detected in the system via any platform specific
4920 * method, such as ACPI for e.g.
4923 cpumask_t cpu_present_map __read_mostly;
4924 EXPORT_SYMBOL(cpu_present_map);
4926 #ifndef CONFIG_SMP
4927 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4928 EXPORT_SYMBOL(cpu_online_map);
4930 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4931 EXPORT_SYMBOL(cpu_possible_map);
4932 #endif
4934 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4936 struct task_struct *p;
4937 int retval;
4939 get_online_cpus();
4940 read_lock(&tasklist_lock);
4942 retval = -ESRCH;
4943 p = find_process_by_pid(pid);
4944 if (!p)
4945 goto out_unlock;
4947 retval = security_task_getscheduler(p);
4948 if (retval)
4949 goto out_unlock;
4951 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4953 out_unlock:
4954 read_unlock(&tasklist_lock);
4955 put_online_cpus();
4957 return retval;
4961 * sys_sched_getaffinity - get the cpu affinity of a process
4962 * @pid: pid of the process
4963 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4964 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4966 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4967 unsigned long __user *user_mask_ptr)
4969 int ret;
4970 cpumask_t mask;
4972 if (len < sizeof(cpumask_t))
4973 return -EINVAL;
4975 ret = sched_getaffinity(pid, &mask);
4976 if (ret < 0)
4977 return ret;
4979 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4980 return -EFAULT;
4982 return sizeof(cpumask_t);
4986 * sys_sched_yield - yield the current processor to other threads.
4988 * This function yields the current CPU to other tasks. If there are no
4989 * other threads running on this CPU then this function will return.
4991 asmlinkage long sys_sched_yield(void)
4993 struct rq *rq = this_rq_lock();
4995 schedstat_inc(rq, yld_count);
4996 current->sched_class->yield_task(rq);
4999 * Since we are going to call schedule() anyway, there's
5000 * no need to preempt or enable interrupts:
5002 __release(rq->lock);
5003 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5004 _raw_spin_unlock(&rq->lock);
5005 preempt_enable_no_resched();
5007 schedule();
5009 return 0;
5012 static void __cond_resched(void)
5014 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5015 __might_sleep(__FILE__, __LINE__);
5016 #endif
5018 * The BKS might be reacquired before we have dropped
5019 * PREEMPT_ACTIVE, which could trigger a second
5020 * cond_resched() call.
5022 do {
5023 add_preempt_count(PREEMPT_ACTIVE);
5024 schedule();
5025 sub_preempt_count(PREEMPT_ACTIVE);
5026 } while (need_resched());
5029 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5030 int __sched _cond_resched(void)
5032 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5033 system_state == SYSTEM_RUNNING) {
5034 __cond_resched();
5035 return 1;
5037 return 0;
5039 EXPORT_SYMBOL(_cond_resched);
5040 #endif
5043 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5044 * call schedule, and on return reacquire the lock.
5046 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5047 * operations here to prevent schedule() from being called twice (once via
5048 * spin_unlock(), once by hand).
5050 int cond_resched_lock(spinlock_t *lock)
5052 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5053 int ret = 0;
5055 if (spin_needbreak(lock) || resched) {
5056 spin_unlock(lock);
5057 if (resched && need_resched())
5058 __cond_resched();
5059 else
5060 cpu_relax();
5061 ret = 1;
5062 spin_lock(lock);
5064 return ret;
5066 EXPORT_SYMBOL(cond_resched_lock);
5068 int __sched cond_resched_softirq(void)
5070 BUG_ON(!in_softirq());
5072 if (need_resched() && system_state == SYSTEM_RUNNING) {
5073 local_bh_enable();
5074 __cond_resched();
5075 local_bh_disable();
5076 return 1;
5078 return 0;
5080 EXPORT_SYMBOL(cond_resched_softirq);
5083 * yield - yield the current processor to other threads.
5085 * This is a shortcut for kernel-space yielding - it marks the
5086 * thread runnable and calls sys_sched_yield().
5088 void __sched yield(void)
5090 set_current_state(TASK_RUNNING);
5091 sys_sched_yield();
5093 EXPORT_SYMBOL(yield);
5096 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5097 * that process accounting knows that this is a task in IO wait state.
5099 * But don't do that if it is a deliberate, throttling IO wait (this task
5100 * has set its backing_dev_info: the queue against which it should throttle)
5102 void __sched io_schedule(void)
5104 struct rq *rq = &__raw_get_cpu_var(runqueues);
5106 delayacct_blkio_start();
5107 atomic_inc(&rq->nr_iowait);
5108 schedule();
5109 atomic_dec(&rq->nr_iowait);
5110 delayacct_blkio_end();
5112 EXPORT_SYMBOL(io_schedule);
5114 long __sched io_schedule_timeout(long timeout)
5116 struct rq *rq = &__raw_get_cpu_var(runqueues);
5117 long ret;
5119 delayacct_blkio_start();
5120 atomic_inc(&rq->nr_iowait);
5121 ret = schedule_timeout(timeout);
5122 atomic_dec(&rq->nr_iowait);
5123 delayacct_blkio_end();
5124 return ret;
5128 * sys_sched_get_priority_max - return maximum RT priority.
5129 * @policy: scheduling class.
5131 * this syscall returns the maximum rt_priority that can be used
5132 * by a given scheduling class.
5134 asmlinkage long sys_sched_get_priority_max(int policy)
5136 int ret = -EINVAL;
5138 switch (policy) {
5139 case SCHED_FIFO:
5140 case SCHED_RR:
5141 ret = MAX_USER_RT_PRIO-1;
5142 break;
5143 case SCHED_NORMAL:
5144 case SCHED_BATCH:
5145 case SCHED_IDLE:
5146 ret = 0;
5147 break;
5149 return ret;
5153 * sys_sched_get_priority_min - return minimum RT priority.
5154 * @policy: scheduling class.
5156 * this syscall returns the minimum rt_priority that can be used
5157 * by a given scheduling class.
5159 asmlinkage long sys_sched_get_priority_min(int policy)
5161 int ret = -EINVAL;
5163 switch (policy) {
5164 case SCHED_FIFO:
5165 case SCHED_RR:
5166 ret = 1;
5167 break;
5168 case SCHED_NORMAL:
5169 case SCHED_BATCH:
5170 case SCHED_IDLE:
5171 ret = 0;
5173 return ret;
5177 * sys_sched_rr_get_interval - return the default timeslice of a process.
5178 * @pid: pid of the process.
5179 * @interval: userspace pointer to the timeslice value.
5181 * this syscall writes the default timeslice value of a given process
5182 * into the user-space timespec buffer. A value of '0' means infinity.
5184 asmlinkage
5185 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5187 struct task_struct *p;
5188 unsigned int time_slice;
5189 int retval;
5190 struct timespec t;
5192 if (pid < 0)
5193 return -EINVAL;
5195 retval = -ESRCH;
5196 read_lock(&tasklist_lock);
5197 p = find_process_by_pid(pid);
5198 if (!p)
5199 goto out_unlock;
5201 retval = security_task_getscheduler(p);
5202 if (retval)
5203 goto out_unlock;
5206 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5207 * tasks that are on an otherwise idle runqueue:
5209 time_slice = 0;
5210 if (p->policy == SCHED_RR) {
5211 time_slice = DEF_TIMESLICE;
5212 } else if (p->policy != SCHED_FIFO) {
5213 struct sched_entity *se = &p->se;
5214 unsigned long flags;
5215 struct rq *rq;
5217 rq = task_rq_lock(p, &flags);
5218 if (rq->cfs.load.weight)
5219 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5220 task_rq_unlock(rq, &flags);
5222 read_unlock(&tasklist_lock);
5223 jiffies_to_timespec(time_slice, &t);
5224 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5225 return retval;
5227 out_unlock:
5228 read_unlock(&tasklist_lock);
5229 return retval;
5232 static const char stat_nam[] = "RSDTtZX";
5234 void sched_show_task(struct task_struct *p)
5236 unsigned long free = 0;
5237 unsigned state;
5239 state = p->state ? __ffs(p->state) + 1 : 0;
5240 printk(KERN_INFO "%-13.13s %c", p->comm,
5241 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5242 #if BITS_PER_LONG == 32
5243 if (state == TASK_RUNNING)
5244 printk(KERN_CONT " running ");
5245 else
5246 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5247 #else
5248 if (state == TASK_RUNNING)
5249 printk(KERN_CONT " running task ");
5250 else
5251 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5252 #endif
5253 #ifdef CONFIG_DEBUG_STACK_USAGE
5255 unsigned long *n = end_of_stack(p);
5256 while (!*n)
5257 n++;
5258 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5260 #endif
5261 printk(KERN_CONT "%5lu %5d %6d\n", free,
5262 task_pid_nr(p), task_pid_nr(p->real_parent));
5264 show_stack(p, NULL);
5267 void show_state_filter(unsigned long state_filter)
5269 struct task_struct *g, *p;
5271 #if BITS_PER_LONG == 32
5272 printk(KERN_INFO
5273 " task PC stack pid father\n");
5274 #else
5275 printk(KERN_INFO
5276 " task PC stack pid father\n");
5277 #endif
5278 read_lock(&tasklist_lock);
5279 do_each_thread(g, p) {
5281 * reset the NMI-timeout, listing all files on a slow
5282 * console might take alot of time:
5284 touch_nmi_watchdog();
5285 if (!state_filter || (p->state & state_filter))
5286 sched_show_task(p);
5287 } while_each_thread(g, p);
5289 touch_all_softlockup_watchdogs();
5291 #ifdef CONFIG_SCHED_DEBUG
5292 sysrq_sched_debug_show();
5293 #endif
5294 read_unlock(&tasklist_lock);
5296 * Only show locks if all tasks are dumped:
5298 if (state_filter == -1)
5299 debug_show_all_locks();
5302 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5304 idle->sched_class = &idle_sched_class;
5308 * init_idle - set up an idle thread for a given CPU
5309 * @idle: task in question
5310 * @cpu: cpu the idle task belongs to
5312 * NOTE: this function does not set the idle thread's NEED_RESCHED
5313 * flag, to make booting more robust.
5315 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5317 struct rq *rq = cpu_rq(cpu);
5318 unsigned long flags;
5320 __sched_fork(idle);
5321 idle->se.exec_start = sched_clock();
5323 idle->prio = idle->normal_prio = MAX_PRIO;
5324 idle->cpus_allowed = cpumask_of_cpu(cpu);
5325 __set_task_cpu(idle, cpu);
5327 spin_lock_irqsave(&rq->lock, flags);
5328 rq->curr = rq->idle = idle;
5329 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5330 idle->oncpu = 1;
5331 #endif
5332 spin_unlock_irqrestore(&rq->lock, flags);
5334 /* Set the preempt count _outside_ the spinlocks! */
5335 task_thread_info(idle)->preempt_count = 0;
5338 * The idle tasks have their own, simple scheduling class:
5340 idle->sched_class = &idle_sched_class;
5344 * In a system that switches off the HZ timer nohz_cpu_mask
5345 * indicates which cpus entered this state. This is used
5346 * in the rcu update to wait only for active cpus. For system
5347 * which do not switch off the HZ timer nohz_cpu_mask should
5348 * always be CPU_MASK_NONE.
5350 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5353 * Increase the granularity value when there are more CPUs,
5354 * because with more CPUs the 'effective latency' as visible
5355 * to users decreases. But the relationship is not linear,
5356 * so pick a second-best guess by going with the log2 of the
5357 * number of CPUs.
5359 * This idea comes from the SD scheduler of Con Kolivas:
5361 static inline void sched_init_granularity(void)
5363 unsigned int factor = 1 + ilog2(num_online_cpus());
5364 const unsigned long limit = 200000000;
5366 sysctl_sched_min_granularity *= factor;
5367 if (sysctl_sched_min_granularity > limit)
5368 sysctl_sched_min_granularity = limit;
5370 sysctl_sched_latency *= factor;
5371 if (sysctl_sched_latency > limit)
5372 sysctl_sched_latency = limit;
5374 sysctl_sched_wakeup_granularity *= factor;
5375 sysctl_sched_batch_wakeup_granularity *= factor;
5378 #ifdef CONFIG_SMP
5380 * This is how migration works:
5382 * 1) we queue a struct migration_req structure in the source CPU's
5383 * runqueue and wake up that CPU's migration thread.
5384 * 2) we down() the locked semaphore => thread blocks.
5385 * 3) migration thread wakes up (implicitly it forces the migrated
5386 * thread off the CPU)
5387 * 4) it gets the migration request and checks whether the migrated
5388 * task is still in the wrong runqueue.
5389 * 5) if it's in the wrong runqueue then the migration thread removes
5390 * it and puts it into the right queue.
5391 * 6) migration thread up()s the semaphore.
5392 * 7) we wake up and the migration is done.
5396 * Change a given task's CPU affinity. Migrate the thread to a
5397 * proper CPU and schedule it away if the CPU it's executing on
5398 * is removed from the allowed bitmask.
5400 * NOTE: the caller must have a valid reference to the task, the
5401 * task must not exit() & deallocate itself prematurely. The
5402 * call is not atomic; no spinlocks may be held.
5404 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5406 struct migration_req req;
5407 unsigned long flags;
5408 struct rq *rq;
5409 int ret = 0;
5411 rq = task_rq_lock(p, &flags);
5412 if (!cpus_intersects(new_mask, cpu_online_map)) {
5413 ret = -EINVAL;
5414 goto out;
5417 if (p->sched_class->set_cpus_allowed)
5418 p->sched_class->set_cpus_allowed(p, &new_mask);
5419 else {
5420 p->cpus_allowed = new_mask;
5421 p->rt.nr_cpus_allowed = cpus_weight(new_mask);
5424 /* Can the task run on the task's current CPU? If so, we're done */
5425 if (cpu_isset(task_cpu(p), new_mask))
5426 goto out;
5428 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5429 /* Need help from migration thread: drop lock and wait. */
5430 task_rq_unlock(rq, &flags);
5431 wake_up_process(rq->migration_thread);
5432 wait_for_completion(&req.done);
5433 tlb_migrate_finish(p->mm);
5434 return 0;
5436 out:
5437 task_rq_unlock(rq, &flags);
5439 return ret;
5441 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5444 * Move (not current) task off this cpu, onto dest cpu. We're doing
5445 * this because either it can't run here any more (set_cpus_allowed()
5446 * away from this CPU, or CPU going down), or because we're
5447 * attempting to rebalance this task on exec (sched_exec).
5449 * So we race with normal scheduler movements, but that's OK, as long
5450 * as the task is no longer on this CPU.
5452 * Returns non-zero if task was successfully migrated.
5454 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5456 struct rq *rq_dest, *rq_src;
5457 int ret = 0, on_rq;
5459 if (unlikely(cpu_is_offline(dest_cpu)))
5460 return ret;
5462 rq_src = cpu_rq(src_cpu);
5463 rq_dest = cpu_rq(dest_cpu);
5465 double_rq_lock(rq_src, rq_dest);
5466 /* Already moved. */
5467 if (task_cpu(p) != src_cpu)
5468 goto out;
5469 /* Affinity changed (again). */
5470 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5471 goto out;
5473 on_rq = p->se.on_rq;
5474 if (on_rq)
5475 deactivate_task(rq_src, p, 0);
5477 set_task_cpu(p, dest_cpu);
5478 if (on_rq) {
5479 activate_task(rq_dest, p, 0);
5480 check_preempt_curr(rq_dest, p);
5482 ret = 1;
5483 out:
5484 double_rq_unlock(rq_src, rq_dest);
5485 return ret;
5489 * migration_thread - this is a highprio system thread that performs
5490 * thread migration by bumping thread off CPU then 'pushing' onto
5491 * another runqueue.
5493 static int migration_thread(void *data)
5495 int cpu = (long)data;
5496 struct rq *rq;
5498 rq = cpu_rq(cpu);
5499 BUG_ON(rq->migration_thread != current);
5501 set_current_state(TASK_INTERRUPTIBLE);
5502 while (!kthread_should_stop()) {
5503 struct migration_req *req;
5504 struct list_head *head;
5506 spin_lock_irq(&rq->lock);
5508 if (cpu_is_offline(cpu)) {
5509 spin_unlock_irq(&rq->lock);
5510 goto wait_to_die;
5513 if (rq->active_balance) {
5514 active_load_balance(rq, cpu);
5515 rq->active_balance = 0;
5518 head = &rq->migration_queue;
5520 if (list_empty(head)) {
5521 spin_unlock_irq(&rq->lock);
5522 schedule();
5523 set_current_state(TASK_INTERRUPTIBLE);
5524 continue;
5526 req = list_entry(head->next, struct migration_req, list);
5527 list_del_init(head->next);
5529 spin_unlock(&rq->lock);
5530 __migrate_task(req->task, cpu, req->dest_cpu);
5531 local_irq_enable();
5533 complete(&req->done);
5535 __set_current_state(TASK_RUNNING);
5536 return 0;
5538 wait_to_die:
5539 /* Wait for kthread_stop */
5540 set_current_state(TASK_INTERRUPTIBLE);
5541 while (!kthread_should_stop()) {
5542 schedule();
5543 set_current_state(TASK_INTERRUPTIBLE);
5545 __set_current_state(TASK_RUNNING);
5546 return 0;
5549 #ifdef CONFIG_HOTPLUG_CPU
5551 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5553 int ret;
5555 local_irq_disable();
5556 ret = __migrate_task(p, src_cpu, dest_cpu);
5557 local_irq_enable();
5558 return ret;
5562 * Figure out where task on dead CPU should go, use force if necessary.
5563 * NOTE: interrupts should be disabled by the caller
5565 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5567 unsigned long flags;
5568 cpumask_t mask;
5569 struct rq *rq;
5570 int dest_cpu;
5572 do {
5573 /* On same node? */
5574 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5575 cpus_and(mask, mask, p->cpus_allowed);
5576 dest_cpu = any_online_cpu(mask);
5578 /* On any allowed CPU? */
5579 if (dest_cpu == NR_CPUS)
5580 dest_cpu = any_online_cpu(p->cpus_allowed);
5582 /* No more Mr. Nice Guy. */
5583 if (dest_cpu == NR_CPUS) {
5584 cpumask_t cpus_allowed = cpuset_cpus_allowed_locked(p);
5586 * Try to stay on the same cpuset, where the
5587 * current cpuset may be a subset of all cpus.
5588 * The cpuset_cpus_allowed_locked() variant of
5589 * cpuset_cpus_allowed() will not block. It must be
5590 * called within calls to cpuset_lock/cpuset_unlock.
5592 rq = task_rq_lock(p, &flags);
5593 p->cpus_allowed = cpus_allowed;
5594 dest_cpu = any_online_cpu(p->cpus_allowed);
5595 task_rq_unlock(rq, &flags);
5598 * Don't tell them about moving exiting tasks or
5599 * kernel threads (both mm NULL), since they never
5600 * leave kernel.
5602 if (p->mm && printk_ratelimit()) {
5603 printk(KERN_INFO "process %d (%s) no "
5604 "longer affine to cpu%d\n",
5605 task_pid_nr(p), p->comm, dead_cpu);
5608 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5612 * While a dead CPU has no uninterruptible tasks queued at this point,
5613 * it might still have a nonzero ->nr_uninterruptible counter, because
5614 * for performance reasons the counter is not stricly tracking tasks to
5615 * their home CPUs. So we just add the counter to another CPU's counter,
5616 * to keep the global sum constant after CPU-down:
5618 static void migrate_nr_uninterruptible(struct rq *rq_src)
5620 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5621 unsigned long flags;
5623 local_irq_save(flags);
5624 double_rq_lock(rq_src, rq_dest);
5625 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5626 rq_src->nr_uninterruptible = 0;
5627 double_rq_unlock(rq_src, rq_dest);
5628 local_irq_restore(flags);
5631 /* Run through task list and migrate tasks from the dead cpu. */
5632 static void migrate_live_tasks(int src_cpu)
5634 struct task_struct *p, *t;
5636 read_lock(&tasklist_lock);
5638 do_each_thread(t, p) {
5639 if (p == current)
5640 continue;
5642 if (task_cpu(p) == src_cpu)
5643 move_task_off_dead_cpu(src_cpu, p);
5644 } while_each_thread(t, p);
5646 read_unlock(&tasklist_lock);
5650 * Schedules idle task to be the next runnable task on current CPU.
5651 * It does so by boosting its priority to highest possible.
5652 * Used by CPU offline code.
5654 void sched_idle_next(void)
5656 int this_cpu = smp_processor_id();
5657 struct rq *rq = cpu_rq(this_cpu);
5658 struct task_struct *p = rq->idle;
5659 unsigned long flags;
5661 /* cpu has to be offline */
5662 BUG_ON(cpu_online(this_cpu));
5665 * Strictly not necessary since rest of the CPUs are stopped by now
5666 * and interrupts disabled on the current cpu.
5668 spin_lock_irqsave(&rq->lock, flags);
5670 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5672 update_rq_clock(rq);
5673 activate_task(rq, p, 0);
5675 spin_unlock_irqrestore(&rq->lock, flags);
5679 * Ensures that the idle task is using init_mm right before its cpu goes
5680 * offline.
5682 void idle_task_exit(void)
5684 struct mm_struct *mm = current->active_mm;
5686 BUG_ON(cpu_online(smp_processor_id()));
5688 if (mm != &init_mm)
5689 switch_mm(mm, &init_mm, current);
5690 mmdrop(mm);
5693 /* called under rq->lock with disabled interrupts */
5694 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5696 struct rq *rq = cpu_rq(dead_cpu);
5698 /* Must be exiting, otherwise would be on tasklist. */
5699 BUG_ON(!p->exit_state);
5701 /* Cannot have done final schedule yet: would have vanished. */
5702 BUG_ON(p->state == TASK_DEAD);
5704 get_task_struct(p);
5707 * Drop lock around migration; if someone else moves it,
5708 * that's OK. No task can be added to this CPU, so iteration is
5709 * fine.
5711 spin_unlock_irq(&rq->lock);
5712 move_task_off_dead_cpu(dead_cpu, p);
5713 spin_lock_irq(&rq->lock);
5715 put_task_struct(p);
5718 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5719 static void migrate_dead_tasks(unsigned int dead_cpu)
5721 struct rq *rq = cpu_rq(dead_cpu);
5722 struct task_struct *next;
5724 for ( ; ; ) {
5725 if (!rq->nr_running)
5726 break;
5727 update_rq_clock(rq);
5728 next = pick_next_task(rq, rq->curr);
5729 if (!next)
5730 break;
5731 migrate_dead(dead_cpu, next);
5735 #endif /* CONFIG_HOTPLUG_CPU */
5737 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5739 static struct ctl_table sd_ctl_dir[] = {
5741 .procname = "sched_domain",
5742 .mode = 0555,
5744 {0, },
5747 static struct ctl_table sd_ctl_root[] = {
5749 .ctl_name = CTL_KERN,
5750 .procname = "kernel",
5751 .mode = 0555,
5752 .child = sd_ctl_dir,
5754 {0, },
5757 static struct ctl_table *sd_alloc_ctl_entry(int n)
5759 struct ctl_table *entry =
5760 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5762 return entry;
5765 static void sd_free_ctl_entry(struct ctl_table **tablep)
5767 struct ctl_table *entry;
5770 * In the intermediate directories, both the child directory and
5771 * procname are dynamically allocated and could fail but the mode
5772 * will always be set. In the lowest directory the names are
5773 * static strings and all have proc handlers.
5775 for (entry = *tablep; entry->mode; entry++) {
5776 if (entry->child)
5777 sd_free_ctl_entry(&entry->child);
5778 if (entry->proc_handler == NULL)
5779 kfree(entry->procname);
5782 kfree(*tablep);
5783 *tablep = NULL;
5786 static void
5787 set_table_entry(struct ctl_table *entry,
5788 const char *procname, void *data, int maxlen,
5789 mode_t mode, proc_handler *proc_handler)
5791 entry->procname = procname;
5792 entry->data = data;
5793 entry->maxlen = maxlen;
5794 entry->mode = mode;
5795 entry->proc_handler = proc_handler;
5798 static struct ctl_table *
5799 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5801 struct ctl_table *table = sd_alloc_ctl_entry(12);
5803 if (table == NULL)
5804 return NULL;
5806 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5807 sizeof(long), 0644, proc_doulongvec_minmax);
5808 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5809 sizeof(long), 0644, proc_doulongvec_minmax);
5810 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5811 sizeof(int), 0644, proc_dointvec_minmax);
5812 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5813 sizeof(int), 0644, proc_dointvec_minmax);
5814 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5815 sizeof(int), 0644, proc_dointvec_minmax);
5816 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5817 sizeof(int), 0644, proc_dointvec_minmax);
5818 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5819 sizeof(int), 0644, proc_dointvec_minmax);
5820 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5821 sizeof(int), 0644, proc_dointvec_minmax);
5822 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5823 sizeof(int), 0644, proc_dointvec_minmax);
5824 set_table_entry(&table[9], "cache_nice_tries",
5825 &sd->cache_nice_tries,
5826 sizeof(int), 0644, proc_dointvec_minmax);
5827 set_table_entry(&table[10], "flags", &sd->flags,
5828 sizeof(int), 0644, proc_dointvec_minmax);
5829 /* &table[11] is terminator */
5831 return table;
5834 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5836 struct ctl_table *entry, *table;
5837 struct sched_domain *sd;
5838 int domain_num = 0, i;
5839 char buf[32];
5841 for_each_domain(cpu, sd)
5842 domain_num++;
5843 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5844 if (table == NULL)
5845 return NULL;
5847 i = 0;
5848 for_each_domain(cpu, sd) {
5849 snprintf(buf, 32, "domain%d", i);
5850 entry->procname = kstrdup(buf, GFP_KERNEL);
5851 entry->mode = 0555;
5852 entry->child = sd_alloc_ctl_domain_table(sd);
5853 entry++;
5854 i++;
5856 return table;
5859 static struct ctl_table_header *sd_sysctl_header;
5860 static void register_sched_domain_sysctl(void)
5862 int i, cpu_num = num_online_cpus();
5863 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5864 char buf[32];
5866 WARN_ON(sd_ctl_dir[0].child);
5867 sd_ctl_dir[0].child = entry;
5869 if (entry == NULL)
5870 return;
5872 for_each_online_cpu(i) {
5873 snprintf(buf, 32, "cpu%d", i);
5874 entry->procname = kstrdup(buf, GFP_KERNEL);
5875 entry->mode = 0555;
5876 entry->child = sd_alloc_ctl_cpu_table(i);
5877 entry++;
5880 WARN_ON(sd_sysctl_header);
5881 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5884 /* may be called multiple times per register */
5885 static void unregister_sched_domain_sysctl(void)
5887 if (sd_sysctl_header)
5888 unregister_sysctl_table(sd_sysctl_header);
5889 sd_sysctl_header = NULL;
5890 if (sd_ctl_dir[0].child)
5891 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5893 #else
5894 static void register_sched_domain_sysctl(void)
5897 static void unregister_sched_domain_sysctl(void)
5900 #endif
5903 * migration_call - callback that gets triggered when a CPU is added.
5904 * Here we can start up the necessary migration thread for the new CPU.
5906 static int __cpuinit
5907 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5909 struct task_struct *p;
5910 int cpu = (long)hcpu;
5911 unsigned long flags;
5912 struct rq *rq;
5914 switch (action) {
5916 case CPU_UP_PREPARE:
5917 case CPU_UP_PREPARE_FROZEN:
5918 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
5919 if (IS_ERR(p))
5920 return NOTIFY_BAD;
5921 kthread_bind(p, cpu);
5922 /* Must be high prio: stop_machine expects to yield to it. */
5923 rq = task_rq_lock(p, &flags);
5924 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5925 task_rq_unlock(rq, &flags);
5926 cpu_rq(cpu)->migration_thread = p;
5927 break;
5929 case CPU_ONLINE:
5930 case CPU_ONLINE_FROZEN:
5931 /* Strictly unnecessary, as first user will wake it. */
5932 wake_up_process(cpu_rq(cpu)->migration_thread);
5934 /* Update our root-domain */
5935 rq = cpu_rq(cpu);
5936 spin_lock_irqsave(&rq->lock, flags);
5937 if (rq->rd) {
5938 BUG_ON(!cpu_isset(cpu, rq->rd->span));
5939 cpu_set(cpu, rq->rd->online);
5941 spin_unlock_irqrestore(&rq->lock, flags);
5942 break;
5944 #ifdef CONFIG_HOTPLUG_CPU
5945 case CPU_UP_CANCELED:
5946 case CPU_UP_CANCELED_FROZEN:
5947 if (!cpu_rq(cpu)->migration_thread)
5948 break;
5949 /* Unbind it from offline cpu so it can run. Fall thru. */
5950 kthread_bind(cpu_rq(cpu)->migration_thread,
5951 any_online_cpu(cpu_online_map));
5952 kthread_stop(cpu_rq(cpu)->migration_thread);
5953 cpu_rq(cpu)->migration_thread = NULL;
5954 break;
5956 case CPU_DEAD:
5957 case CPU_DEAD_FROZEN:
5958 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5959 migrate_live_tasks(cpu);
5960 rq = cpu_rq(cpu);
5961 kthread_stop(rq->migration_thread);
5962 rq->migration_thread = NULL;
5963 /* Idle task back to normal (off runqueue, low prio) */
5964 spin_lock_irq(&rq->lock);
5965 update_rq_clock(rq);
5966 deactivate_task(rq, rq->idle, 0);
5967 rq->idle->static_prio = MAX_PRIO;
5968 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5969 rq->idle->sched_class = &idle_sched_class;
5970 migrate_dead_tasks(cpu);
5971 spin_unlock_irq(&rq->lock);
5972 cpuset_unlock();
5973 migrate_nr_uninterruptible(rq);
5974 BUG_ON(rq->nr_running != 0);
5977 * No need to migrate the tasks: it was best-effort if
5978 * they didn't take sched_hotcpu_mutex. Just wake up
5979 * the requestors.
5981 spin_lock_irq(&rq->lock);
5982 while (!list_empty(&rq->migration_queue)) {
5983 struct migration_req *req;
5985 req = list_entry(rq->migration_queue.next,
5986 struct migration_req, list);
5987 list_del_init(&req->list);
5988 complete(&req->done);
5990 spin_unlock_irq(&rq->lock);
5991 break;
5993 case CPU_DYING:
5994 case CPU_DYING_FROZEN:
5995 /* Update our root-domain */
5996 rq = cpu_rq(cpu);
5997 spin_lock_irqsave(&rq->lock, flags);
5998 if (rq->rd) {
5999 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6000 cpu_clear(cpu, rq->rd->online);
6002 spin_unlock_irqrestore(&rq->lock, flags);
6003 break;
6004 #endif
6006 return NOTIFY_OK;
6009 /* Register at highest priority so that task migration (migrate_all_tasks)
6010 * happens before everything else.
6012 static struct notifier_block __cpuinitdata migration_notifier = {
6013 .notifier_call = migration_call,
6014 .priority = 10
6017 void __init migration_init(void)
6019 void *cpu = (void *)(long)smp_processor_id();
6020 int err;
6022 /* Start one for the boot CPU: */
6023 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6024 BUG_ON(err == NOTIFY_BAD);
6025 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6026 register_cpu_notifier(&migration_notifier);
6028 #endif
6030 #ifdef CONFIG_SMP
6032 /* Number of possible processor ids */
6033 int nr_cpu_ids __read_mostly = NR_CPUS;
6034 EXPORT_SYMBOL(nr_cpu_ids);
6036 #ifdef CONFIG_SCHED_DEBUG
6038 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level)
6040 struct sched_group *group = sd->groups;
6041 cpumask_t groupmask;
6042 char str[NR_CPUS];
6044 cpumask_scnprintf(str, NR_CPUS, sd->span);
6045 cpus_clear(groupmask);
6047 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6049 if (!(sd->flags & SD_LOAD_BALANCE)) {
6050 printk("does not load-balance\n");
6051 if (sd->parent)
6052 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6053 " has parent");
6054 return -1;
6057 printk(KERN_CONT "span %s\n", str);
6059 if (!cpu_isset(cpu, sd->span)) {
6060 printk(KERN_ERR "ERROR: domain->span does not contain "
6061 "CPU%d\n", cpu);
6063 if (!cpu_isset(cpu, group->cpumask)) {
6064 printk(KERN_ERR "ERROR: domain->groups does not contain"
6065 " CPU%d\n", cpu);
6068 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6069 do {
6070 if (!group) {
6071 printk("\n");
6072 printk(KERN_ERR "ERROR: group is NULL\n");
6073 break;
6076 if (!group->__cpu_power) {
6077 printk(KERN_CONT "\n");
6078 printk(KERN_ERR "ERROR: domain->cpu_power not "
6079 "set\n");
6080 break;
6083 if (!cpus_weight(group->cpumask)) {
6084 printk(KERN_CONT "\n");
6085 printk(KERN_ERR "ERROR: empty group\n");
6086 break;
6089 if (cpus_intersects(groupmask, group->cpumask)) {
6090 printk(KERN_CONT "\n");
6091 printk(KERN_ERR "ERROR: repeated CPUs\n");
6092 break;
6095 cpus_or(groupmask, groupmask, group->cpumask);
6097 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
6098 printk(KERN_CONT " %s", str);
6100 group = group->next;
6101 } while (group != sd->groups);
6102 printk(KERN_CONT "\n");
6104 if (!cpus_equal(sd->span, groupmask))
6105 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6107 if (sd->parent && !cpus_subset(groupmask, sd->parent->span))
6108 printk(KERN_ERR "ERROR: parent span is not a superset "
6109 "of domain->span\n");
6110 return 0;
6113 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6115 int level = 0;
6117 if (!sd) {
6118 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6119 return;
6122 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6124 for (;;) {
6125 if (sched_domain_debug_one(sd, cpu, level))
6126 break;
6127 level++;
6128 sd = sd->parent;
6129 if (!sd)
6130 break;
6133 #else
6134 # define sched_domain_debug(sd, cpu) do { } while (0)
6135 #endif
6137 static int sd_degenerate(struct sched_domain *sd)
6139 if (cpus_weight(sd->span) == 1)
6140 return 1;
6142 /* Following flags need at least 2 groups */
6143 if (sd->flags & (SD_LOAD_BALANCE |
6144 SD_BALANCE_NEWIDLE |
6145 SD_BALANCE_FORK |
6146 SD_BALANCE_EXEC |
6147 SD_SHARE_CPUPOWER |
6148 SD_SHARE_PKG_RESOURCES)) {
6149 if (sd->groups != sd->groups->next)
6150 return 0;
6153 /* Following flags don't use groups */
6154 if (sd->flags & (SD_WAKE_IDLE |
6155 SD_WAKE_AFFINE |
6156 SD_WAKE_BALANCE))
6157 return 0;
6159 return 1;
6162 static int
6163 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6165 unsigned long cflags = sd->flags, pflags = parent->flags;
6167 if (sd_degenerate(parent))
6168 return 1;
6170 if (!cpus_equal(sd->span, parent->span))
6171 return 0;
6173 /* Does parent contain flags not in child? */
6174 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6175 if (cflags & SD_WAKE_AFFINE)
6176 pflags &= ~SD_WAKE_BALANCE;
6177 /* Flags needing groups don't count if only 1 group in parent */
6178 if (parent->groups == parent->groups->next) {
6179 pflags &= ~(SD_LOAD_BALANCE |
6180 SD_BALANCE_NEWIDLE |
6181 SD_BALANCE_FORK |
6182 SD_BALANCE_EXEC |
6183 SD_SHARE_CPUPOWER |
6184 SD_SHARE_PKG_RESOURCES);
6186 if (~cflags & pflags)
6187 return 0;
6189 return 1;
6192 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6194 unsigned long flags;
6195 const struct sched_class *class;
6197 spin_lock_irqsave(&rq->lock, flags);
6199 if (rq->rd) {
6200 struct root_domain *old_rd = rq->rd;
6202 for (class = sched_class_highest; class; class = class->next) {
6203 if (class->leave_domain)
6204 class->leave_domain(rq);
6207 cpu_clear(rq->cpu, old_rd->span);
6208 cpu_clear(rq->cpu, old_rd->online);
6210 if (atomic_dec_and_test(&old_rd->refcount))
6211 kfree(old_rd);
6214 atomic_inc(&rd->refcount);
6215 rq->rd = rd;
6217 cpu_set(rq->cpu, rd->span);
6218 if (cpu_isset(rq->cpu, cpu_online_map))
6219 cpu_set(rq->cpu, rd->online);
6221 for (class = sched_class_highest; class; class = class->next) {
6222 if (class->join_domain)
6223 class->join_domain(rq);
6226 spin_unlock_irqrestore(&rq->lock, flags);
6229 static void init_rootdomain(struct root_domain *rd)
6231 memset(rd, 0, sizeof(*rd));
6233 cpus_clear(rd->span);
6234 cpus_clear(rd->online);
6237 static void init_defrootdomain(void)
6239 init_rootdomain(&def_root_domain);
6240 atomic_set(&def_root_domain.refcount, 1);
6243 static struct root_domain *alloc_rootdomain(void)
6245 struct root_domain *rd;
6247 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6248 if (!rd)
6249 return NULL;
6251 init_rootdomain(rd);
6253 return rd;
6257 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6258 * hold the hotplug lock.
6260 static void
6261 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6263 struct rq *rq = cpu_rq(cpu);
6264 struct sched_domain *tmp;
6266 /* Remove the sched domains which do not contribute to scheduling. */
6267 for (tmp = sd; tmp; tmp = tmp->parent) {
6268 struct sched_domain *parent = tmp->parent;
6269 if (!parent)
6270 break;
6271 if (sd_parent_degenerate(tmp, parent)) {
6272 tmp->parent = parent->parent;
6273 if (parent->parent)
6274 parent->parent->child = tmp;
6278 if (sd && sd_degenerate(sd)) {
6279 sd = sd->parent;
6280 if (sd)
6281 sd->child = NULL;
6284 sched_domain_debug(sd, cpu);
6286 rq_attach_root(rq, rd);
6287 rcu_assign_pointer(rq->sd, sd);
6290 /* cpus with isolated domains */
6291 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6293 /* Setup the mask of cpus configured for isolated domains */
6294 static int __init isolated_cpu_setup(char *str)
6296 int ints[NR_CPUS], i;
6298 str = get_options(str, ARRAY_SIZE(ints), ints);
6299 cpus_clear(cpu_isolated_map);
6300 for (i = 1; i <= ints[0]; i++)
6301 if (ints[i] < NR_CPUS)
6302 cpu_set(ints[i], cpu_isolated_map);
6303 return 1;
6306 __setup("isolcpus=", isolated_cpu_setup);
6309 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6310 * to a function which identifies what group(along with sched group) a CPU
6311 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6312 * (due to the fact that we keep track of groups covered with a cpumask_t).
6314 * init_sched_build_groups will build a circular linked list of the groups
6315 * covered by the given span, and will set each group's ->cpumask correctly,
6316 * and ->cpu_power to 0.
6318 static void
6319 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
6320 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6321 struct sched_group **sg))
6323 struct sched_group *first = NULL, *last = NULL;
6324 cpumask_t covered = CPU_MASK_NONE;
6325 int i;
6327 for_each_cpu_mask(i, span) {
6328 struct sched_group *sg;
6329 int group = group_fn(i, cpu_map, &sg);
6330 int j;
6332 if (cpu_isset(i, covered))
6333 continue;
6335 sg->cpumask = CPU_MASK_NONE;
6336 sg->__cpu_power = 0;
6338 for_each_cpu_mask(j, span) {
6339 if (group_fn(j, cpu_map, NULL) != group)
6340 continue;
6342 cpu_set(j, covered);
6343 cpu_set(j, sg->cpumask);
6345 if (!first)
6346 first = sg;
6347 if (last)
6348 last->next = sg;
6349 last = sg;
6351 last->next = first;
6354 #define SD_NODES_PER_DOMAIN 16
6356 #ifdef CONFIG_NUMA
6359 * find_next_best_node - find the next node to include in a sched_domain
6360 * @node: node whose sched_domain we're building
6361 * @used_nodes: nodes already in the sched_domain
6363 * Find the next node to include in a given scheduling domain. Simply
6364 * finds the closest node not already in the @used_nodes map.
6366 * Should use nodemask_t.
6368 static int find_next_best_node(int node, unsigned long *used_nodes)
6370 int i, n, val, min_val, best_node = 0;
6372 min_val = INT_MAX;
6374 for (i = 0; i < MAX_NUMNODES; i++) {
6375 /* Start at @node */
6376 n = (node + i) % MAX_NUMNODES;
6378 if (!nr_cpus_node(n))
6379 continue;
6381 /* Skip already used nodes */
6382 if (test_bit(n, used_nodes))
6383 continue;
6385 /* Simple min distance search */
6386 val = node_distance(node, n);
6388 if (val < min_val) {
6389 min_val = val;
6390 best_node = n;
6394 set_bit(best_node, used_nodes);
6395 return best_node;
6399 * sched_domain_node_span - get a cpumask for a node's sched_domain
6400 * @node: node whose cpumask we're constructing
6401 * @size: number of nodes to include in this span
6403 * Given a node, construct a good cpumask for its sched_domain to span. It
6404 * should be one that prevents unnecessary balancing, but also spreads tasks
6405 * out optimally.
6407 static cpumask_t sched_domain_node_span(int node)
6409 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6410 cpumask_t span, nodemask;
6411 int i;
6413 cpus_clear(span);
6414 bitmap_zero(used_nodes, MAX_NUMNODES);
6416 nodemask = node_to_cpumask(node);
6417 cpus_or(span, span, nodemask);
6418 set_bit(node, used_nodes);
6420 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6421 int next_node = find_next_best_node(node, used_nodes);
6423 nodemask = node_to_cpumask(next_node);
6424 cpus_or(span, span, nodemask);
6427 return span;
6429 #endif
6431 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6434 * SMT sched-domains:
6436 #ifdef CONFIG_SCHED_SMT
6437 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6438 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6440 static int
6441 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6443 if (sg)
6444 *sg = &per_cpu(sched_group_cpus, cpu);
6445 return cpu;
6447 #endif
6450 * multi-core sched-domains:
6452 #ifdef CONFIG_SCHED_MC
6453 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6454 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6455 #endif
6457 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6458 static int
6459 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6461 int group;
6462 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6463 cpus_and(mask, mask, *cpu_map);
6464 group = first_cpu(mask);
6465 if (sg)
6466 *sg = &per_cpu(sched_group_core, group);
6467 return group;
6469 #elif defined(CONFIG_SCHED_MC)
6470 static int
6471 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6473 if (sg)
6474 *sg = &per_cpu(sched_group_core, cpu);
6475 return cpu;
6477 #endif
6479 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6480 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6482 static int
6483 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6485 int group;
6486 #ifdef CONFIG_SCHED_MC
6487 cpumask_t mask = cpu_coregroup_map(cpu);
6488 cpus_and(mask, mask, *cpu_map);
6489 group = first_cpu(mask);
6490 #elif defined(CONFIG_SCHED_SMT)
6491 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6492 cpus_and(mask, mask, *cpu_map);
6493 group = first_cpu(mask);
6494 #else
6495 group = cpu;
6496 #endif
6497 if (sg)
6498 *sg = &per_cpu(sched_group_phys, group);
6499 return group;
6502 #ifdef CONFIG_NUMA
6504 * The init_sched_build_groups can't handle what we want to do with node
6505 * groups, so roll our own. Now each node has its own list of groups which
6506 * gets dynamically allocated.
6508 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6509 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6511 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6512 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6514 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6515 struct sched_group **sg)
6517 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6518 int group;
6520 cpus_and(nodemask, nodemask, *cpu_map);
6521 group = first_cpu(nodemask);
6523 if (sg)
6524 *sg = &per_cpu(sched_group_allnodes, group);
6525 return group;
6528 static void init_numa_sched_groups_power(struct sched_group *group_head)
6530 struct sched_group *sg = group_head;
6531 int j;
6533 if (!sg)
6534 return;
6535 do {
6536 for_each_cpu_mask(j, sg->cpumask) {
6537 struct sched_domain *sd;
6539 sd = &per_cpu(phys_domains, j);
6540 if (j != first_cpu(sd->groups->cpumask)) {
6542 * Only add "power" once for each
6543 * physical package.
6545 continue;
6548 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6550 sg = sg->next;
6551 } while (sg != group_head);
6553 #endif
6555 #ifdef CONFIG_NUMA
6556 /* Free memory allocated for various sched_group structures */
6557 static void free_sched_groups(const cpumask_t *cpu_map)
6559 int cpu, i;
6561 for_each_cpu_mask(cpu, *cpu_map) {
6562 struct sched_group **sched_group_nodes
6563 = sched_group_nodes_bycpu[cpu];
6565 if (!sched_group_nodes)
6566 continue;
6568 for (i = 0; i < MAX_NUMNODES; i++) {
6569 cpumask_t nodemask = node_to_cpumask(i);
6570 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6572 cpus_and(nodemask, nodemask, *cpu_map);
6573 if (cpus_empty(nodemask))
6574 continue;
6576 if (sg == NULL)
6577 continue;
6578 sg = sg->next;
6579 next_sg:
6580 oldsg = sg;
6581 sg = sg->next;
6582 kfree(oldsg);
6583 if (oldsg != sched_group_nodes[i])
6584 goto next_sg;
6586 kfree(sched_group_nodes);
6587 sched_group_nodes_bycpu[cpu] = NULL;
6590 #else
6591 static void free_sched_groups(const cpumask_t *cpu_map)
6594 #endif
6597 * Initialize sched groups cpu_power.
6599 * cpu_power indicates the capacity of sched group, which is used while
6600 * distributing the load between different sched groups in a sched domain.
6601 * Typically cpu_power for all the groups in a sched domain will be same unless
6602 * there are asymmetries in the topology. If there are asymmetries, group
6603 * having more cpu_power will pickup more load compared to the group having
6604 * less cpu_power.
6606 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6607 * the maximum number of tasks a group can handle in the presence of other idle
6608 * or lightly loaded groups in the same sched domain.
6610 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6612 struct sched_domain *child;
6613 struct sched_group *group;
6615 WARN_ON(!sd || !sd->groups);
6617 if (cpu != first_cpu(sd->groups->cpumask))
6618 return;
6620 child = sd->child;
6622 sd->groups->__cpu_power = 0;
6625 * For perf policy, if the groups in child domain share resources
6626 * (for example cores sharing some portions of the cache hierarchy
6627 * or SMT), then set this domain groups cpu_power such that each group
6628 * can handle only one task, when there are other idle groups in the
6629 * same sched domain.
6631 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6632 (child->flags &
6633 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6634 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6635 return;
6639 * add cpu_power of each child group to this groups cpu_power
6641 group = child->groups;
6642 do {
6643 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6644 group = group->next;
6645 } while (group != child->groups);
6649 * Build sched domains for a given set of cpus and attach the sched domains
6650 * to the individual cpus
6652 static int build_sched_domains(const cpumask_t *cpu_map)
6654 int i;
6655 struct root_domain *rd;
6656 #ifdef CONFIG_NUMA
6657 struct sched_group **sched_group_nodes = NULL;
6658 int sd_allnodes = 0;
6661 * Allocate the per-node list of sched groups
6663 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6664 GFP_KERNEL);
6665 if (!sched_group_nodes) {
6666 printk(KERN_WARNING "Can not alloc sched group node list\n");
6667 return -ENOMEM;
6669 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6670 #endif
6672 rd = alloc_rootdomain();
6673 if (!rd) {
6674 printk(KERN_WARNING "Cannot alloc root domain\n");
6675 return -ENOMEM;
6679 * Set up domains for cpus specified by the cpu_map.
6681 for_each_cpu_mask(i, *cpu_map) {
6682 struct sched_domain *sd = NULL, *p;
6683 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6685 cpus_and(nodemask, nodemask, *cpu_map);
6687 #ifdef CONFIG_NUMA
6688 if (cpus_weight(*cpu_map) >
6689 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6690 sd = &per_cpu(allnodes_domains, i);
6691 *sd = SD_ALLNODES_INIT;
6692 sd->span = *cpu_map;
6693 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6694 p = sd;
6695 sd_allnodes = 1;
6696 } else
6697 p = NULL;
6699 sd = &per_cpu(node_domains, i);
6700 *sd = SD_NODE_INIT;
6701 sd->span = sched_domain_node_span(cpu_to_node(i));
6702 sd->parent = p;
6703 if (p)
6704 p->child = sd;
6705 cpus_and(sd->span, sd->span, *cpu_map);
6706 #endif
6708 p = sd;
6709 sd = &per_cpu(phys_domains, i);
6710 *sd = SD_CPU_INIT;
6711 sd->span = nodemask;
6712 sd->parent = p;
6713 if (p)
6714 p->child = sd;
6715 cpu_to_phys_group(i, cpu_map, &sd->groups);
6717 #ifdef CONFIG_SCHED_MC
6718 p = sd;
6719 sd = &per_cpu(core_domains, i);
6720 *sd = SD_MC_INIT;
6721 sd->span = cpu_coregroup_map(i);
6722 cpus_and(sd->span, sd->span, *cpu_map);
6723 sd->parent = p;
6724 p->child = sd;
6725 cpu_to_core_group(i, cpu_map, &sd->groups);
6726 #endif
6728 #ifdef CONFIG_SCHED_SMT
6729 p = sd;
6730 sd = &per_cpu(cpu_domains, i);
6731 *sd = SD_SIBLING_INIT;
6732 sd->span = per_cpu(cpu_sibling_map, i);
6733 cpus_and(sd->span, sd->span, *cpu_map);
6734 sd->parent = p;
6735 p->child = sd;
6736 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6737 #endif
6740 #ifdef CONFIG_SCHED_SMT
6741 /* Set up CPU (sibling) groups */
6742 for_each_cpu_mask(i, *cpu_map) {
6743 cpumask_t this_sibling_map = per_cpu(cpu_sibling_map, i);
6744 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6745 if (i != first_cpu(this_sibling_map))
6746 continue;
6748 init_sched_build_groups(this_sibling_map, cpu_map,
6749 &cpu_to_cpu_group);
6751 #endif
6753 #ifdef CONFIG_SCHED_MC
6754 /* Set up multi-core groups */
6755 for_each_cpu_mask(i, *cpu_map) {
6756 cpumask_t this_core_map = cpu_coregroup_map(i);
6757 cpus_and(this_core_map, this_core_map, *cpu_map);
6758 if (i != first_cpu(this_core_map))
6759 continue;
6760 init_sched_build_groups(this_core_map, cpu_map,
6761 &cpu_to_core_group);
6763 #endif
6765 /* Set up physical groups */
6766 for (i = 0; i < MAX_NUMNODES; i++) {
6767 cpumask_t nodemask = node_to_cpumask(i);
6769 cpus_and(nodemask, nodemask, *cpu_map);
6770 if (cpus_empty(nodemask))
6771 continue;
6773 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6776 #ifdef CONFIG_NUMA
6777 /* Set up node groups */
6778 if (sd_allnodes)
6779 init_sched_build_groups(*cpu_map, cpu_map,
6780 &cpu_to_allnodes_group);
6782 for (i = 0; i < MAX_NUMNODES; i++) {
6783 /* Set up node groups */
6784 struct sched_group *sg, *prev;
6785 cpumask_t nodemask = node_to_cpumask(i);
6786 cpumask_t domainspan;
6787 cpumask_t covered = CPU_MASK_NONE;
6788 int j;
6790 cpus_and(nodemask, nodemask, *cpu_map);
6791 if (cpus_empty(nodemask)) {
6792 sched_group_nodes[i] = NULL;
6793 continue;
6796 domainspan = sched_domain_node_span(i);
6797 cpus_and(domainspan, domainspan, *cpu_map);
6799 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6800 if (!sg) {
6801 printk(KERN_WARNING "Can not alloc domain group for "
6802 "node %d\n", i);
6803 goto error;
6805 sched_group_nodes[i] = sg;
6806 for_each_cpu_mask(j, nodemask) {
6807 struct sched_domain *sd;
6809 sd = &per_cpu(node_domains, j);
6810 sd->groups = sg;
6812 sg->__cpu_power = 0;
6813 sg->cpumask = nodemask;
6814 sg->next = sg;
6815 cpus_or(covered, covered, nodemask);
6816 prev = sg;
6818 for (j = 0; j < MAX_NUMNODES; j++) {
6819 cpumask_t tmp, notcovered;
6820 int n = (i + j) % MAX_NUMNODES;
6822 cpus_complement(notcovered, covered);
6823 cpus_and(tmp, notcovered, *cpu_map);
6824 cpus_and(tmp, tmp, domainspan);
6825 if (cpus_empty(tmp))
6826 break;
6828 nodemask = node_to_cpumask(n);
6829 cpus_and(tmp, tmp, nodemask);
6830 if (cpus_empty(tmp))
6831 continue;
6833 sg = kmalloc_node(sizeof(struct sched_group),
6834 GFP_KERNEL, i);
6835 if (!sg) {
6836 printk(KERN_WARNING
6837 "Can not alloc domain group for node %d\n", j);
6838 goto error;
6840 sg->__cpu_power = 0;
6841 sg->cpumask = tmp;
6842 sg->next = prev->next;
6843 cpus_or(covered, covered, tmp);
6844 prev->next = sg;
6845 prev = sg;
6848 #endif
6850 /* Calculate CPU power for physical packages and nodes */
6851 #ifdef CONFIG_SCHED_SMT
6852 for_each_cpu_mask(i, *cpu_map) {
6853 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6855 init_sched_groups_power(i, sd);
6857 #endif
6858 #ifdef CONFIG_SCHED_MC
6859 for_each_cpu_mask(i, *cpu_map) {
6860 struct sched_domain *sd = &per_cpu(core_domains, i);
6862 init_sched_groups_power(i, sd);
6864 #endif
6866 for_each_cpu_mask(i, *cpu_map) {
6867 struct sched_domain *sd = &per_cpu(phys_domains, i);
6869 init_sched_groups_power(i, sd);
6872 #ifdef CONFIG_NUMA
6873 for (i = 0; i < MAX_NUMNODES; i++)
6874 init_numa_sched_groups_power(sched_group_nodes[i]);
6876 if (sd_allnodes) {
6877 struct sched_group *sg;
6879 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6880 init_numa_sched_groups_power(sg);
6882 #endif
6884 /* Attach the domains */
6885 for_each_cpu_mask(i, *cpu_map) {
6886 struct sched_domain *sd;
6887 #ifdef CONFIG_SCHED_SMT
6888 sd = &per_cpu(cpu_domains, i);
6889 #elif defined(CONFIG_SCHED_MC)
6890 sd = &per_cpu(core_domains, i);
6891 #else
6892 sd = &per_cpu(phys_domains, i);
6893 #endif
6894 cpu_attach_domain(sd, rd, i);
6897 return 0;
6899 #ifdef CONFIG_NUMA
6900 error:
6901 free_sched_groups(cpu_map);
6902 return -ENOMEM;
6903 #endif
6906 static cpumask_t *doms_cur; /* current sched domains */
6907 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
6910 * Special case: If a kmalloc of a doms_cur partition (array of
6911 * cpumask_t) fails, then fallback to a single sched domain,
6912 * as determined by the single cpumask_t fallback_doms.
6914 static cpumask_t fallback_doms;
6916 void __attribute__((weak)) arch_update_cpu_topology(void)
6921 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6922 * For now this just excludes isolated cpus, but could be used to
6923 * exclude other special cases in the future.
6925 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6927 int err;
6929 arch_update_cpu_topology();
6930 ndoms_cur = 1;
6931 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6932 if (!doms_cur)
6933 doms_cur = &fallback_doms;
6934 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
6935 err = build_sched_domains(doms_cur);
6936 register_sched_domain_sysctl();
6938 return err;
6941 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6943 free_sched_groups(cpu_map);
6947 * Detach sched domains from a group of cpus specified in cpu_map
6948 * These cpus will now be attached to the NULL domain
6950 static void detach_destroy_domains(const cpumask_t *cpu_map)
6952 int i;
6954 unregister_sched_domain_sysctl();
6956 for_each_cpu_mask(i, *cpu_map)
6957 cpu_attach_domain(NULL, &def_root_domain, i);
6958 synchronize_sched();
6959 arch_destroy_sched_domains(cpu_map);
6963 * Partition sched domains as specified by the 'ndoms_new'
6964 * cpumasks in the array doms_new[] of cpumasks. This compares
6965 * doms_new[] to the current sched domain partitioning, doms_cur[].
6966 * It destroys each deleted domain and builds each new domain.
6968 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6969 * The masks don't intersect (don't overlap.) We should setup one
6970 * sched domain for each mask. CPUs not in any of the cpumasks will
6971 * not be load balanced. If the same cpumask appears both in the
6972 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6973 * it as it is.
6975 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6976 * ownership of it and will kfree it when done with it. If the caller
6977 * failed the kmalloc call, then it can pass in doms_new == NULL,
6978 * and partition_sched_domains() will fallback to the single partition
6979 * 'fallback_doms'.
6981 * Call with hotplug lock held
6983 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
6985 int i, j;
6987 lock_doms_cur();
6989 /* always unregister in case we don't destroy any domains */
6990 unregister_sched_domain_sysctl();
6992 if (doms_new == NULL) {
6993 ndoms_new = 1;
6994 doms_new = &fallback_doms;
6995 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
6998 /* Destroy deleted domains */
6999 for (i = 0; i < ndoms_cur; i++) {
7000 for (j = 0; j < ndoms_new; j++) {
7001 if (cpus_equal(doms_cur[i], doms_new[j]))
7002 goto match1;
7004 /* no match - a current sched domain not in new doms_new[] */
7005 detach_destroy_domains(doms_cur + i);
7006 match1:
7010 /* Build new domains */
7011 for (i = 0; i < ndoms_new; i++) {
7012 for (j = 0; j < ndoms_cur; j++) {
7013 if (cpus_equal(doms_new[i], doms_cur[j]))
7014 goto match2;
7016 /* no match - add a new doms_new */
7017 build_sched_domains(doms_new + i);
7018 match2:
7022 /* Remember the new sched domains */
7023 if (doms_cur != &fallback_doms)
7024 kfree(doms_cur);
7025 doms_cur = doms_new;
7026 ndoms_cur = ndoms_new;
7028 register_sched_domain_sysctl();
7030 unlock_doms_cur();
7033 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7034 int arch_reinit_sched_domains(void)
7036 int err;
7038 get_online_cpus();
7039 detach_destroy_domains(&cpu_online_map);
7040 err = arch_init_sched_domains(&cpu_online_map);
7041 put_online_cpus();
7043 return err;
7046 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7048 int ret;
7050 if (buf[0] != '0' && buf[0] != '1')
7051 return -EINVAL;
7053 if (smt)
7054 sched_smt_power_savings = (buf[0] == '1');
7055 else
7056 sched_mc_power_savings = (buf[0] == '1');
7058 ret = arch_reinit_sched_domains();
7060 return ret ? ret : count;
7063 #ifdef CONFIG_SCHED_MC
7064 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7066 return sprintf(page, "%u\n", sched_mc_power_savings);
7068 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7069 const char *buf, size_t count)
7071 return sched_power_savings_store(buf, count, 0);
7073 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7074 sched_mc_power_savings_store);
7075 #endif
7077 #ifdef CONFIG_SCHED_SMT
7078 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7080 return sprintf(page, "%u\n", sched_smt_power_savings);
7082 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7083 const char *buf, size_t count)
7085 return sched_power_savings_store(buf, count, 1);
7087 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7088 sched_smt_power_savings_store);
7089 #endif
7091 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7093 int err = 0;
7095 #ifdef CONFIG_SCHED_SMT
7096 if (smt_capable())
7097 err = sysfs_create_file(&cls->kset.kobj,
7098 &attr_sched_smt_power_savings.attr);
7099 #endif
7100 #ifdef CONFIG_SCHED_MC
7101 if (!err && mc_capable())
7102 err = sysfs_create_file(&cls->kset.kobj,
7103 &attr_sched_mc_power_savings.attr);
7104 #endif
7105 return err;
7107 #endif
7110 * Force a reinitialization of the sched domains hierarchy. The domains
7111 * and groups cannot be updated in place without racing with the balancing
7112 * code, so we temporarily attach all running cpus to the NULL domain
7113 * which will prevent rebalancing while the sched domains are recalculated.
7115 static int update_sched_domains(struct notifier_block *nfb,
7116 unsigned long action, void *hcpu)
7118 switch (action) {
7119 case CPU_UP_PREPARE:
7120 case CPU_UP_PREPARE_FROZEN:
7121 case CPU_DOWN_PREPARE:
7122 case CPU_DOWN_PREPARE_FROZEN:
7123 detach_destroy_domains(&cpu_online_map);
7124 return NOTIFY_OK;
7126 case CPU_UP_CANCELED:
7127 case CPU_UP_CANCELED_FROZEN:
7128 case CPU_DOWN_FAILED:
7129 case CPU_DOWN_FAILED_FROZEN:
7130 case CPU_ONLINE:
7131 case CPU_ONLINE_FROZEN:
7132 case CPU_DEAD:
7133 case CPU_DEAD_FROZEN:
7135 * Fall through and re-initialise the domains.
7137 break;
7138 default:
7139 return NOTIFY_DONE;
7142 /* The hotplug lock is already held by cpu_up/cpu_down */
7143 arch_init_sched_domains(&cpu_online_map);
7145 return NOTIFY_OK;
7148 void __init sched_init_smp(void)
7150 cpumask_t non_isolated_cpus;
7152 get_online_cpus();
7153 arch_init_sched_domains(&cpu_online_map);
7154 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7155 if (cpus_empty(non_isolated_cpus))
7156 cpu_set(smp_processor_id(), non_isolated_cpus);
7157 put_online_cpus();
7158 /* XXX: Theoretical race here - CPU may be hotplugged now */
7159 hotcpu_notifier(update_sched_domains, 0);
7160 init_hrtick();
7162 /* Move init over to a non-isolated CPU */
7163 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
7164 BUG();
7165 sched_init_granularity();
7167 #else
7168 void __init sched_init_smp(void)
7170 sched_init_granularity();
7172 #endif /* CONFIG_SMP */
7174 int in_sched_functions(unsigned long addr)
7176 return in_lock_functions(addr) ||
7177 (addr >= (unsigned long)__sched_text_start
7178 && addr < (unsigned long)__sched_text_end);
7181 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7183 cfs_rq->tasks_timeline = RB_ROOT;
7184 #ifdef CONFIG_FAIR_GROUP_SCHED
7185 cfs_rq->rq = rq;
7186 #endif
7187 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7190 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7192 struct rt_prio_array *array;
7193 int i;
7195 array = &rt_rq->active;
7196 for (i = 0; i < MAX_RT_PRIO; i++) {
7197 INIT_LIST_HEAD(array->queue + i);
7198 __clear_bit(i, array->bitmap);
7200 /* delimiter for bitsearch: */
7201 __set_bit(MAX_RT_PRIO, array->bitmap);
7203 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7204 rt_rq->highest_prio = MAX_RT_PRIO;
7205 #endif
7206 #ifdef CONFIG_SMP
7207 rt_rq->rt_nr_migratory = 0;
7208 rt_rq->overloaded = 0;
7209 #endif
7211 rt_rq->rt_time = 0;
7212 rt_rq->rt_throttled = 0;
7214 #ifdef CONFIG_RT_GROUP_SCHED
7215 rt_rq->rt_nr_boosted = 0;
7216 rt_rq->rq = rq;
7217 #endif
7220 #ifdef CONFIG_FAIR_GROUP_SCHED
7221 static void init_tg_cfs_entry(struct rq *rq, struct task_group *tg,
7222 struct cfs_rq *cfs_rq, struct sched_entity *se,
7223 int cpu, int add)
7225 tg->cfs_rq[cpu] = cfs_rq;
7226 init_cfs_rq(cfs_rq, rq);
7227 cfs_rq->tg = tg;
7228 if (add)
7229 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7231 tg->se[cpu] = se;
7232 se->cfs_rq = &rq->cfs;
7233 se->my_q = cfs_rq;
7234 se->load.weight = tg->shares;
7235 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
7236 se->parent = NULL;
7238 #endif
7240 #ifdef CONFIG_RT_GROUP_SCHED
7241 static void init_tg_rt_entry(struct rq *rq, struct task_group *tg,
7242 struct rt_rq *rt_rq, struct sched_rt_entity *rt_se,
7243 int cpu, int add)
7245 tg->rt_rq[cpu] = rt_rq;
7246 init_rt_rq(rt_rq, rq);
7247 rt_rq->tg = tg;
7248 rt_rq->rt_se = rt_se;
7249 if (add)
7250 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7252 tg->rt_se[cpu] = rt_se;
7253 rt_se->rt_rq = &rq->rt;
7254 rt_se->my_q = rt_rq;
7255 rt_se->parent = NULL;
7256 INIT_LIST_HEAD(&rt_se->run_list);
7258 #endif
7260 void __init sched_init(void)
7262 int highest_cpu = 0;
7263 int i, j;
7265 #ifdef CONFIG_SMP
7266 init_defrootdomain();
7267 #endif
7269 #ifdef CONFIG_GROUP_SCHED
7270 list_add(&init_task_group.list, &task_groups);
7271 #endif
7273 for_each_possible_cpu(i) {
7274 struct rq *rq;
7276 rq = cpu_rq(i);
7277 spin_lock_init(&rq->lock);
7278 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7279 rq->nr_running = 0;
7280 rq->clock = 1;
7281 init_cfs_rq(&rq->cfs, rq);
7282 init_rt_rq(&rq->rt, rq);
7283 #ifdef CONFIG_FAIR_GROUP_SCHED
7284 init_task_group.shares = init_task_group_load;
7285 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7286 init_tg_cfs_entry(rq, &init_task_group,
7287 &per_cpu(init_cfs_rq, i),
7288 &per_cpu(init_sched_entity, i), i, 1);
7290 #endif
7291 #ifdef CONFIG_RT_GROUP_SCHED
7292 init_task_group.rt_runtime =
7293 sysctl_sched_rt_runtime * NSEC_PER_USEC;
7294 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7295 init_tg_rt_entry(rq, &init_task_group,
7296 &per_cpu(init_rt_rq, i),
7297 &per_cpu(init_sched_rt_entity, i), i, 1);
7298 #endif
7299 rq->rt_period_expire = 0;
7300 rq->rt_throttled = 0;
7302 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7303 rq->cpu_load[j] = 0;
7304 #ifdef CONFIG_SMP
7305 rq->sd = NULL;
7306 rq->rd = NULL;
7307 rq->active_balance = 0;
7308 rq->next_balance = jiffies;
7309 rq->push_cpu = 0;
7310 rq->cpu = i;
7311 rq->migration_thread = NULL;
7312 INIT_LIST_HEAD(&rq->migration_queue);
7313 rq_attach_root(rq, &def_root_domain);
7314 #endif
7315 init_rq_hrtick(rq);
7316 atomic_set(&rq->nr_iowait, 0);
7317 highest_cpu = i;
7320 set_load_weight(&init_task);
7322 #ifdef CONFIG_PREEMPT_NOTIFIERS
7323 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7324 #endif
7326 #ifdef CONFIG_SMP
7327 nr_cpu_ids = highest_cpu + 1;
7328 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7329 #endif
7331 #ifdef CONFIG_RT_MUTEXES
7332 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7333 #endif
7336 * The boot idle thread does lazy MMU switching as well:
7338 atomic_inc(&init_mm.mm_count);
7339 enter_lazy_tlb(&init_mm, current);
7342 * Make us the idle thread. Technically, schedule() should not be
7343 * called from this thread, however somewhere below it might be,
7344 * but because we are the idle thread, we just pick up running again
7345 * when this runqueue becomes "idle".
7347 init_idle(current, smp_processor_id());
7349 * During early bootup we pretend to be a normal task:
7351 current->sched_class = &fair_sched_class;
7353 scheduler_running = 1;
7356 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7357 void __might_sleep(char *file, int line)
7359 #ifdef in_atomic
7360 static unsigned long prev_jiffy; /* ratelimiting */
7362 if ((in_atomic() || irqs_disabled()) &&
7363 system_state == SYSTEM_RUNNING && !oops_in_progress) {
7364 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7365 return;
7366 prev_jiffy = jiffies;
7367 printk(KERN_ERR "BUG: sleeping function called from invalid"
7368 " context at %s:%d\n", file, line);
7369 printk("in_atomic():%d, irqs_disabled():%d\n",
7370 in_atomic(), irqs_disabled());
7371 debug_show_held_locks(current);
7372 if (irqs_disabled())
7373 print_irqtrace_events(current);
7374 dump_stack();
7376 #endif
7378 EXPORT_SYMBOL(__might_sleep);
7379 #endif
7381 #ifdef CONFIG_MAGIC_SYSRQ
7382 static void normalize_task(struct rq *rq, struct task_struct *p)
7384 int on_rq;
7385 update_rq_clock(rq);
7386 on_rq = p->se.on_rq;
7387 if (on_rq)
7388 deactivate_task(rq, p, 0);
7389 __setscheduler(rq, p, SCHED_NORMAL, 0);
7390 if (on_rq) {
7391 activate_task(rq, p, 0);
7392 resched_task(rq->curr);
7396 void normalize_rt_tasks(void)
7398 struct task_struct *g, *p;
7399 unsigned long flags;
7400 struct rq *rq;
7402 read_lock_irqsave(&tasklist_lock, flags);
7403 do_each_thread(g, p) {
7405 * Only normalize user tasks:
7407 if (!p->mm)
7408 continue;
7410 p->se.exec_start = 0;
7411 #ifdef CONFIG_SCHEDSTATS
7412 p->se.wait_start = 0;
7413 p->se.sleep_start = 0;
7414 p->se.block_start = 0;
7415 #endif
7416 task_rq(p)->clock = 0;
7418 if (!rt_task(p)) {
7420 * Renice negative nice level userspace
7421 * tasks back to 0:
7423 if (TASK_NICE(p) < 0 && p->mm)
7424 set_user_nice(p, 0);
7425 continue;
7428 spin_lock(&p->pi_lock);
7429 rq = __task_rq_lock(p);
7431 normalize_task(rq, p);
7433 __task_rq_unlock(rq);
7434 spin_unlock(&p->pi_lock);
7435 } while_each_thread(g, p);
7437 read_unlock_irqrestore(&tasklist_lock, flags);
7440 #endif /* CONFIG_MAGIC_SYSRQ */
7442 #ifdef CONFIG_IA64
7444 * These functions are only useful for the IA64 MCA handling.
7446 * They can only be called when the whole system has been
7447 * stopped - every CPU needs to be quiescent, and no scheduling
7448 * activity can take place. Using them for anything else would
7449 * be a serious bug, and as a result, they aren't even visible
7450 * under any other configuration.
7454 * curr_task - return the current task for a given cpu.
7455 * @cpu: the processor in question.
7457 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7459 struct task_struct *curr_task(int cpu)
7461 return cpu_curr(cpu);
7465 * set_curr_task - set the current task for a given cpu.
7466 * @cpu: the processor in question.
7467 * @p: the task pointer to set.
7469 * Description: This function must only be used when non-maskable interrupts
7470 * are serviced on a separate stack. It allows the architecture to switch the
7471 * notion of the current task on a cpu in a non-blocking manner. This function
7472 * must be called with all CPU's synchronized, and interrupts disabled, the
7473 * and caller must save the original value of the current task (see
7474 * curr_task() above) and restore that value before reenabling interrupts and
7475 * re-starting the system.
7477 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7479 void set_curr_task(int cpu, struct task_struct *p)
7481 cpu_curr(cpu) = p;
7484 #endif
7486 #ifdef CONFIG_GROUP_SCHED
7488 #ifdef CONFIG_FAIR_GROUP_SCHED
7489 static void free_fair_sched_group(struct task_group *tg)
7491 int i;
7493 for_each_possible_cpu(i) {
7494 if (tg->cfs_rq)
7495 kfree(tg->cfs_rq[i]);
7496 if (tg->se)
7497 kfree(tg->se[i]);
7500 kfree(tg->cfs_rq);
7501 kfree(tg->se);
7504 static int alloc_fair_sched_group(struct task_group *tg)
7506 struct cfs_rq *cfs_rq;
7507 struct sched_entity *se;
7508 struct rq *rq;
7509 int i;
7511 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
7512 if (!tg->cfs_rq)
7513 goto err;
7514 tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
7515 if (!tg->se)
7516 goto err;
7518 tg->shares = NICE_0_LOAD;
7520 for_each_possible_cpu(i) {
7521 rq = cpu_rq(i);
7523 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
7524 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7525 if (!cfs_rq)
7526 goto err;
7528 se = kmalloc_node(sizeof(struct sched_entity),
7529 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7530 if (!se)
7531 goto err;
7533 init_tg_cfs_entry(rq, tg, cfs_rq, se, i, 0);
7536 return 1;
7538 err:
7539 return 0;
7542 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7544 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
7545 &cpu_rq(cpu)->leaf_cfs_rq_list);
7548 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7550 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
7552 #else
7553 static inline void free_fair_sched_group(struct task_group *tg)
7557 static inline int alloc_fair_sched_group(struct task_group *tg)
7559 return 1;
7562 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7566 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7569 #endif
7571 #ifdef CONFIG_RT_GROUP_SCHED
7572 static void free_rt_sched_group(struct task_group *tg)
7574 int i;
7576 for_each_possible_cpu(i) {
7577 if (tg->rt_rq)
7578 kfree(tg->rt_rq[i]);
7579 if (tg->rt_se)
7580 kfree(tg->rt_se[i]);
7583 kfree(tg->rt_rq);
7584 kfree(tg->rt_se);
7587 static int alloc_rt_sched_group(struct task_group *tg)
7589 struct rt_rq *rt_rq;
7590 struct sched_rt_entity *rt_se;
7591 struct rq *rq;
7592 int i;
7594 tg->rt_rq = kzalloc(sizeof(rt_rq) * NR_CPUS, GFP_KERNEL);
7595 if (!tg->rt_rq)
7596 goto err;
7597 tg->rt_se = kzalloc(sizeof(rt_se) * NR_CPUS, GFP_KERNEL);
7598 if (!tg->rt_se)
7599 goto err;
7601 tg->rt_runtime = 0;
7603 for_each_possible_cpu(i) {
7604 rq = cpu_rq(i);
7606 rt_rq = kmalloc_node(sizeof(struct rt_rq),
7607 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7608 if (!rt_rq)
7609 goto err;
7611 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
7612 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7613 if (!rt_se)
7614 goto err;
7616 init_tg_rt_entry(rq, tg, rt_rq, rt_se, i, 0);
7619 return 1;
7621 err:
7622 return 0;
7625 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7627 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
7628 &cpu_rq(cpu)->leaf_rt_rq_list);
7631 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7633 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
7635 #else
7636 static inline void free_rt_sched_group(struct task_group *tg)
7640 static inline int alloc_rt_sched_group(struct task_group *tg)
7642 return 1;
7645 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7649 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7652 #endif
7654 static void free_sched_group(struct task_group *tg)
7656 free_fair_sched_group(tg);
7657 free_rt_sched_group(tg);
7658 kfree(tg);
7661 /* allocate runqueue etc for a new task group */
7662 struct task_group *sched_create_group(void)
7664 struct task_group *tg;
7665 unsigned long flags;
7666 int i;
7668 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7669 if (!tg)
7670 return ERR_PTR(-ENOMEM);
7672 if (!alloc_fair_sched_group(tg))
7673 goto err;
7675 if (!alloc_rt_sched_group(tg))
7676 goto err;
7678 spin_lock_irqsave(&task_group_lock, flags);
7679 for_each_possible_cpu(i) {
7680 register_fair_sched_group(tg, i);
7681 register_rt_sched_group(tg, i);
7683 list_add_rcu(&tg->list, &task_groups);
7684 spin_unlock_irqrestore(&task_group_lock, flags);
7686 return tg;
7688 err:
7689 free_sched_group(tg);
7690 return ERR_PTR(-ENOMEM);
7693 /* rcu callback to free various structures associated with a task group */
7694 static void free_sched_group_rcu(struct rcu_head *rhp)
7696 /* now it should be safe to free those cfs_rqs */
7697 free_sched_group(container_of(rhp, struct task_group, rcu));
7700 /* Destroy runqueue etc associated with a task group */
7701 void sched_destroy_group(struct task_group *tg)
7703 unsigned long flags;
7704 int i;
7706 spin_lock_irqsave(&task_group_lock, flags);
7707 for_each_possible_cpu(i) {
7708 unregister_fair_sched_group(tg, i);
7709 unregister_rt_sched_group(tg, i);
7711 list_del_rcu(&tg->list);
7712 spin_unlock_irqrestore(&task_group_lock, flags);
7714 /* wait for possible concurrent references to cfs_rqs complete */
7715 call_rcu(&tg->rcu, free_sched_group_rcu);
7718 /* change task's runqueue when it moves between groups.
7719 * The caller of this function should have put the task in its new group
7720 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7721 * reflect its new group.
7723 void sched_move_task(struct task_struct *tsk)
7725 int on_rq, running;
7726 unsigned long flags;
7727 struct rq *rq;
7729 rq = task_rq_lock(tsk, &flags);
7731 update_rq_clock(rq);
7733 running = task_current(rq, tsk);
7734 on_rq = tsk->se.on_rq;
7736 if (on_rq)
7737 dequeue_task(rq, tsk, 0);
7738 if (unlikely(running))
7739 tsk->sched_class->put_prev_task(rq, tsk);
7741 set_task_rq(tsk, task_cpu(tsk));
7743 #ifdef CONFIG_FAIR_GROUP_SCHED
7744 if (tsk->sched_class->moved_group)
7745 tsk->sched_class->moved_group(tsk);
7746 #endif
7748 if (unlikely(running))
7749 tsk->sched_class->set_curr_task(rq);
7750 if (on_rq)
7751 enqueue_task(rq, tsk, 0);
7753 task_rq_unlock(rq, &flags);
7756 #ifdef CONFIG_FAIR_GROUP_SCHED
7757 static void set_se_shares(struct sched_entity *se, unsigned long shares)
7759 struct cfs_rq *cfs_rq = se->cfs_rq;
7760 struct rq *rq = cfs_rq->rq;
7761 int on_rq;
7763 spin_lock_irq(&rq->lock);
7765 on_rq = se->on_rq;
7766 if (on_rq)
7767 dequeue_entity(cfs_rq, se, 0);
7769 se->load.weight = shares;
7770 se->load.inv_weight = div64_64((1ULL<<32), shares);
7772 if (on_rq)
7773 enqueue_entity(cfs_rq, se, 0);
7775 spin_unlock_irq(&rq->lock);
7778 static DEFINE_MUTEX(shares_mutex);
7780 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7782 int i;
7783 unsigned long flags;
7786 * A weight of 0 or 1 can cause arithmetics problems.
7787 * (The default weight is 1024 - so there's no practical
7788 * limitation from this.)
7790 if (shares < 2)
7791 shares = 2;
7793 mutex_lock(&shares_mutex);
7794 if (tg->shares == shares)
7795 goto done;
7797 spin_lock_irqsave(&task_group_lock, flags);
7798 for_each_possible_cpu(i)
7799 unregister_fair_sched_group(tg, i);
7800 spin_unlock_irqrestore(&task_group_lock, flags);
7802 /* wait for any ongoing reference to this group to finish */
7803 synchronize_sched();
7806 * Now we are free to modify the group's share on each cpu
7807 * w/o tripping rebalance_share or load_balance_fair.
7809 tg->shares = shares;
7810 for_each_possible_cpu(i)
7811 set_se_shares(tg->se[i], shares);
7814 * Enable load balance activity on this group, by inserting it back on
7815 * each cpu's rq->leaf_cfs_rq_list.
7817 spin_lock_irqsave(&task_group_lock, flags);
7818 for_each_possible_cpu(i)
7819 register_fair_sched_group(tg, i);
7820 spin_unlock_irqrestore(&task_group_lock, flags);
7821 done:
7822 mutex_unlock(&shares_mutex);
7823 return 0;
7826 unsigned long sched_group_shares(struct task_group *tg)
7828 return tg->shares;
7830 #endif
7832 #ifdef CONFIG_RT_GROUP_SCHED
7834 * Ensure that the real time constraints are schedulable.
7836 static DEFINE_MUTEX(rt_constraints_mutex);
7838 static unsigned long to_ratio(u64 period, u64 runtime)
7840 if (runtime == RUNTIME_INF)
7841 return 1ULL << 16;
7843 return div64_64(runtime << 16, period);
7846 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7848 struct task_group *tgi;
7849 unsigned long total = 0;
7850 unsigned long global_ratio =
7851 to_ratio(sysctl_sched_rt_period,
7852 sysctl_sched_rt_runtime < 0 ?
7853 RUNTIME_INF : sysctl_sched_rt_runtime);
7855 rcu_read_lock();
7856 list_for_each_entry_rcu(tgi, &task_groups, list) {
7857 if (tgi == tg)
7858 continue;
7860 total += to_ratio(period, tgi->rt_runtime);
7862 rcu_read_unlock();
7864 return total + to_ratio(period, runtime) < global_ratio;
7867 /* Must be called with tasklist_lock held */
7868 static inline int tg_has_rt_tasks(struct task_group *tg)
7870 struct task_struct *g, *p;
7871 do_each_thread(g, p) {
7872 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
7873 return 1;
7874 } while_each_thread(g, p);
7875 return 0;
7878 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
7880 u64 rt_runtime, rt_period;
7881 int err = 0;
7883 rt_period = (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
7884 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7885 if (rt_runtime_us == -1)
7886 rt_runtime = RUNTIME_INF;
7888 mutex_lock(&rt_constraints_mutex);
7889 read_lock(&tasklist_lock);
7890 if (rt_runtime_us == 0 && tg_has_rt_tasks(tg)) {
7891 err = -EBUSY;
7892 goto unlock;
7894 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
7895 err = -EINVAL;
7896 goto unlock;
7898 tg->rt_runtime = rt_runtime;
7899 unlock:
7900 read_unlock(&tasklist_lock);
7901 mutex_unlock(&rt_constraints_mutex);
7903 return err;
7906 long sched_group_rt_runtime(struct task_group *tg)
7908 u64 rt_runtime_us;
7910 if (tg->rt_runtime == RUNTIME_INF)
7911 return -1;
7913 rt_runtime_us = tg->rt_runtime;
7914 do_div(rt_runtime_us, NSEC_PER_USEC);
7915 return rt_runtime_us;
7917 #endif
7918 #endif /* CONFIG_GROUP_SCHED */
7920 #ifdef CONFIG_CGROUP_SCHED
7922 /* return corresponding task_group object of a cgroup */
7923 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
7925 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7926 struct task_group, css);
7929 static struct cgroup_subsys_state *
7930 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
7932 struct task_group *tg;
7934 if (!cgrp->parent) {
7935 /* This is early initialization for the top cgroup */
7936 init_task_group.css.cgroup = cgrp;
7937 return &init_task_group.css;
7940 /* we support only 1-level deep hierarchical scheduler atm */
7941 if (cgrp->parent->parent)
7942 return ERR_PTR(-EINVAL);
7944 tg = sched_create_group();
7945 if (IS_ERR(tg))
7946 return ERR_PTR(-ENOMEM);
7948 /* Bind the cgroup to task_group object we just created */
7949 tg->css.cgroup = cgrp;
7951 return &tg->css;
7954 static void
7955 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
7957 struct task_group *tg = cgroup_tg(cgrp);
7959 sched_destroy_group(tg);
7962 static int
7963 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7964 struct task_struct *tsk)
7966 #ifdef CONFIG_RT_GROUP_SCHED
7967 /* Don't accept realtime tasks when there is no way for them to run */
7968 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_runtime == 0)
7969 return -EINVAL;
7970 #else
7971 /* We don't support RT-tasks being in separate groups */
7972 if (tsk->sched_class != &fair_sched_class)
7973 return -EINVAL;
7974 #endif
7976 return 0;
7979 static void
7980 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7981 struct cgroup *old_cont, struct task_struct *tsk)
7983 sched_move_task(tsk);
7986 #ifdef CONFIG_FAIR_GROUP_SCHED
7987 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
7988 u64 shareval)
7990 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
7993 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
7995 struct task_group *tg = cgroup_tg(cgrp);
7997 return (u64) tg->shares;
7999 #endif
8001 #ifdef CONFIG_RT_GROUP_SCHED
8002 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8003 struct file *file,
8004 const char __user *userbuf,
8005 size_t nbytes, loff_t *unused_ppos)
8007 char buffer[64];
8008 int retval = 0;
8009 s64 val;
8010 char *end;
8012 if (!nbytes)
8013 return -EINVAL;
8014 if (nbytes >= sizeof(buffer))
8015 return -E2BIG;
8016 if (copy_from_user(buffer, userbuf, nbytes))
8017 return -EFAULT;
8019 buffer[nbytes] = 0; /* nul-terminate */
8021 /* strip newline if necessary */
8022 if (nbytes && (buffer[nbytes-1] == '\n'))
8023 buffer[nbytes-1] = 0;
8024 val = simple_strtoll(buffer, &end, 0);
8025 if (*end)
8026 return -EINVAL;
8028 /* Pass to subsystem */
8029 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8030 if (!retval)
8031 retval = nbytes;
8032 return retval;
8035 static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
8036 struct file *file,
8037 char __user *buf, size_t nbytes,
8038 loff_t *ppos)
8040 char tmp[64];
8041 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
8042 int len = sprintf(tmp, "%ld\n", val);
8044 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
8046 #endif
8048 static struct cftype cpu_files[] = {
8049 #ifdef CONFIG_FAIR_GROUP_SCHED
8051 .name = "shares",
8052 .read_uint = cpu_shares_read_uint,
8053 .write_uint = cpu_shares_write_uint,
8055 #endif
8056 #ifdef CONFIG_RT_GROUP_SCHED
8058 .name = "rt_runtime_us",
8059 .read = cpu_rt_runtime_read,
8060 .write = cpu_rt_runtime_write,
8062 #endif
8065 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8067 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8070 struct cgroup_subsys cpu_cgroup_subsys = {
8071 .name = "cpu",
8072 .create = cpu_cgroup_create,
8073 .destroy = cpu_cgroup_destroy,
8074 .can_attach = cpu_cgroup_can_attach,
8075 .attach = cpu_cgroup_attach,
8076 .populate = cpu_cgroup_populate,
8077 .subsys_id = cpu_cgroup_subsys_id,
8078 .early_init = 1,
8081 #endif /* CONFIG_CGROUP_SCHED */
8083 #ifdef CONFIG_CGROUP_CPUACCT
8086 * CPU accounting code for task groups.
8088 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8089 * (balbir@in.ibm.com).
8092 /* track cpu usage of a group of tasks */
8093 struct cpuacct {
8094 struct cgroup_subsys_state css;
8095 /* cpuusage holds pointer to a u64-type object on every cpu */
8096 u64 *cpuusage;
8099 struct cgroup_subsys cpuacct_subsys;
8101 /* return cpu accounting group corresponding to this container */
8102 static inline struct cpuacct *cgroup_ca(struct cgroup *cont)
8104 return container_of(cgroup_subsys_state(cont, cpuacct_subsys_id),
8105 struct cpuacct, css);
8108 /* return cpu accounting group to which this task belongs */
8109 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8111 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8112 struct cpuacct, css);
8115 /* create a new cpu accounting group */
8116 static struct cgroup_subsys_state *cpuacct_create(
8117 struct cgroup_subsys *ss, struct cgroup *cont)
8119 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8121 if (!ca)
8122 return ERR_PTR(-ENOMEM);
8124 ca->cpuusage = alloc_percpu(u64);
8125 if (!ca->cpuusage) {
8126 kfree(ca);
8127 return ERR_PTR(-ENOMEM);
8130 return &ca->css;
8133 /* destroy an existing cpu accounting group */
8134 static void
8135 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
8137 struct cpuacct *ca = cgroup_ca(cont);
8139 free_percpu(ca->cpuusage);
8140 kfree(ca);
8143 /* return total cpu usage (in nanoseconds) of a group */
8144 static u64 cpuusage_read(struct cgroup *cont, struct cftype *cft)
8146 struct cpuacct *ca = cgroup_ca(cont);
8147 u64 totalcpuusage = 0;
8148 int i;
8150 for_each_possible_cpu(i) {
8151 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8154 * Take rq->lock to make 64-bit addition safe on 32-bit
8155 * platforms.
8157 spin_lock_irq(&cpu_rq(i)->lock);
8158 totalcpuusage += *cpuusage;
8159 spin_unlock_irq(&cpu_rq(i)->lock);
8162 return totalcpuusage;
8165 static struct cftype files[] = {
8167 .name = "usage",
8168 .read_uint = cpuusage_read,
8172 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8174 return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
8178 * charge this task's execution time to its accounting group.
8180 * called with rq->lock held.
8182 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8184 struct cpuacct *ca;
8186 if (!cpuacct_subsys.active)
8187 return;
8189 ca = task_ca(tsk);
8190 if (ca) {
8191 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
8193 *cpuusage += cputime;
8197 struct cgroup_subsys cpuacct_subsys = {
8198 .name = "cpuacct",
8199 .create = cpuacct_create,
8200 .destroy = cpuacct_destroy,
8201 .populate = cpuacct_populate,
8202 .subsys_id = cpuacct_subsys_id,
8204 #endif /* CONFIG_CGROUP_CPUACCT */