4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
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
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
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/proc_fs.h>
59 #include <linux/seq_file.h>
60 #include <linux/sysctl.h>
61 #include <linux/syscalls.h>
62 #include <linux/times.h>
63 #include <linux/tsacct_kern.h>
64 #include <linux/kprobes.h>
65 #include <linux/delayacct.h>
66 #include <linux/reciprocal_div.h>
67 #include <linux/unistd.h>
68 #include <linux/pagemap.h>
69 #include <linux/hrtimer.h>
70 #include <linux/tick.h>
71 #include <linux/bootmem.h>
72 #include <linux/debugfs.h>
73 #include <linux/ctype.h>
74 #include <linux/ftrace.h>
75 #include <trace/sched.h>
78 #include <asm/irq_regs.h>
80 #include "sched_cpupri.h"
83 * Convert user-nice values [ -20 ... 0 ... 19 ]
84 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
87 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
88 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
89 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
92 * 'User priority' is the nice value converted to something we
93 * can work with better when scaling various scheduler parameters,
94 * it's a [ 0 ... 39 ] range.
96 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
97 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
98 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
101 * Helpers for converting nanosecond timing to jiffy resolution
103 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
105 #define NICE_0_LOAD SCHED_LOAD_SCALE
106 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
109 * These are the 'tuning knobs' of the scheduler:
111 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
112 * Timeslices get refilled after they expire.
114 #define DEF_TIMESLICE (100 * HZ / 1000)
117 * single value that denotes runtime == period, ie unlimited time.
119 #define RUNTIME_INF ((u64)~0ULL)
121 DEFINE_TRACE(sched_wait_task);
122 DEFINE_TRACE(sched_wakeup);
123 DEFINE_TRACE(sched_wakeup_new);
124 DEFINE_TRACE(sched_switch);
125 DEFINE_TRACE(sched_migrate_task);
129 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
130 * Since cpu_power is a 'constant', we can use a reciprocal divide.
132 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
134 return reciprocal_divide(load, sg->reciprocal_cpu_power);
138 * Each time a sched group cpu_power is changed,
139 * we must compute its reciprocal value
141 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
143 sg->__cpu_power += val;
144 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
148 static inline int rt_policy(int policy)
150 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
155 static inline int task_has_rt_policy(struct task_struct *p)
157 return rt_policy(p->policy);
161 * This is the priority-queue data structure of the RT scheduling class:
163 struct rt_prio_array {
164 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
165 struct list_head queue[MAX_RT_PRIO];
168 struct rt_bandwidth {
169 /* nests inside the rq lock: */
170 spinlock_t rt_runtime_lock;
173 struct hrtimer rt_period_timer;
176 static struct rt_bandwidth def_rt_bandwidth;
178 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
180 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
182 struct rt_bandwidth *rt_b =
183 container_of(timer, struct rt_bandwidth, rt_period_timer);
189 now = hrtimer_cb_get_time(timer);
190 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
195 idle = do_sched_rt_period_timer(rt_b, overrun);
198 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
202 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
204 rt_b->rt_period = ns_to_ktime(period);
205 rt_b->rt_runtime = runtime;
207 spin_lock_init(&rt_b->rt_runtime_lock);
209 hrtimer_init(&rt_b->rt_period_timer,
210 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
211 rt_b->rt_period_timer.function = sched_rt_period_timer;
214 static inline int rt_bandwidth_enabled(void)
216 return sysctl_sched_rt_runtime >= 0;
219 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
223 if (rt_bandwidth_enabled() && rt_b->rt_runtime == RUNTIME_INF)
226 if (hrtimer_active(&rt_b->rt_period_timer))
229 spin_lock(&rt_b->rt_runtime_lock);
231 if (hrtimer_active(&rt_b->rt_period_timer))
234 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
235 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
236 hrtimer_start_expires(&rt_b->rt_period_timer,
239 spin_unlock(&rt_b->rt_runtime_lock);
242 #ifdef CONFIG_RT_GROUP_SCHED
243 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
245 hrtimer_cancel(&rt_b->rt_period_timer);
250 * sched_domains_mutex serializes calls to arch_init_sched_domains,
251 * detach_destroy_domains and partition_sched_domains.
253 static DEFINE_MUTEX(sched_domains_mutex);
255 #ifdef CONFIG_GROUP_SCHED
257 #include <linux/cgroup.h>
261 static LIST_HEAD(task_groups);
263 /* task group related information */
265 #ifdef CONFIG_CGROUP_SCHED
266 struct cgroup_subsys_state css;
269 #ifdef CONFIG_USER_SCHED
273 #ifdef CONFIG_FAIR_GROUP_SCHED
274 /* schedulable entities of this group on each cpu */
275 struct sched_entity **se;
276 /* runqueue "owned" by this group on each cpu */
277 struct cfs_rq **cfs_rq;
278 unsigned long shares;
281 #ifdef CONFIG_RT_GROUP_SCHED
282 struct sched_rt_entity **rt_se;
283 struct rt_rq **rt_rq;
285 struct rt_bandwidth rt_bandwidth;
289 struct list_head list;
291 struct task_group *parent;
292 struct list_head siblings;
293 struct list_head children;
296 #ifdef CONFIG_USER_SCHED
298 /* Helper function to pass uid information to create_sched_user() */
299 void set_tg_uid(struct user_struct *user)
301 user->tg->uid = user->uid;
306 * Every UID task group (including init_task_group aka UID-0) will
307 * be a child to this group.
309 struct task_group root_task_group;
311 #ifdef CONFIG_FAIR_GROUP_SCHED
312 /* Default task group's sched entity on each cpu */
313 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
314 /* Default task group's cfs_rq on each cpu */
315 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
316 #endif /* CONFIG_FAIR_GROUP_SCHED */
318 #ifdef CONFIG_RT_GROUP_SCHED
319 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
320 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
321 #endif /* CONFIG_RT_GROUP_SCHED */
322 #else /* !CONFIG_USER_SCHED */
323 #define root_task_group init_task_group
324 #endif /* CONFIG_USER_SCHED */
326 /* task_group_lock serializes add/remove of task groups and also changes to
327 * a task group's cpu shares.
329 static DEFINE_SPINLOCK(task_group_lock);
331 #ifdef CONFIG_FAIR_GROUP_SCHED
332 #ifdef CONFIG_USER_SCHED
333 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
334 #else /* !CONFIG_USER_SCHED */
335 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
336 #endif /* CONFIG_USER_SCHED */
339 * A weight of 0 or 1 can cause arithmetics problems.
340 * A weight of a cfs_rq is the sum of weights of which entities
341 * are queued on this cfs_rq, so a weight of a entity should not be
342 * too large, so as the shares value of a task group.
343 * (The default weight is 1024 - so there's no practical
344 * limitation from this.)
347 #define MAX_SHARES (1UL << 18)
349 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
352 /* Default task group.
353 * Every task in system belong to this group at bootup.
355 struct task_group init_task_group;
357 /* return group to which a task belongs */
358 static inline struct task_group *task_group(struct task_struct *p)
360 struct task_group *tg;
362 #ifdef CONFIG_USER_SCHED
364 tg = __task_cred(p)->user->tg;
366 #elif defined(CONFIG_CGROUP_SCHED)
367 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
368 struct task_group, css);
370 tg = &init_task_group;
375 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
376 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
378 #ifdef CONFIG_FAIR_GROUP_SCHED
379 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
380 p->se.parent = task_group(p)->se[cpu];
383 #ifdef CONFIG_RT_GROUP_SCHED
384 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
385 p->rt.parent = task_group(p)->rt_se[cpu];
391 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
392 static inline struct task_group *task_group(struct task_struct *p)
397 #endif /* CONFIG_GROUP_SCHED */
399 /* CFS-related fields in a runqueue */
401 struct load_weight load;
402 unsigned long nr_running;
407 struct rb_root tasks_timeline;
408 struct rb_node *rb_leftmost;
410 struct list_head tasks;
411 struct list_head *balance_iterator;
414 * 'curr' points to currently running entity on this cfs_rq.
415 * It is set to NULL otherwise (i.e when none are currently running).
417 struct sched_entity *curr, *next, *last;
419 unsigned int nr_spread_over;
421 #ifdef CONFIG_FAIR_GROUP_SCHED
422 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
425 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
426 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
427 * (like users, containers etc.)
429 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
430 * list is used during load balance.
432 struct list_head leaf_cfs_rq_list;
433 struct task_group *tg; /* group that "owns" this runqueue */
437 * the part of load.weight contributed by tasks
439 unsigned long task_weight;
442 * h_load = weight * f(tg)
444 * Where f(tg) is the recursive weight fraction assigned to
447 unsigned long h_load;
450 * this cpu's part of tg->shares
452 unsigned long shares;
455 * load.weight at the time we set shares
457 unsigned long rq_weight;
462 /* Real-Time classes' related field in a runqueue: */
464 struct rt_prio_array active;
465 unsigned long rt_nr_running;
466 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
468 int curr; /* highest queued rt task prio */
470 int next; /* next highest */
475 unsigned long rt_nr_migratory;
477 struct plist_head pushable_tasks;
482 /* Nests inside the rq lock: */
483 spinlock_t rt_runtime_lock;
485 #ifdef CONFIG_RT_GROUP_SCHED
486 unsigned long rt_nr_boosted;
489 struct list_head leaf_rt_rq_list;
490 struct task_group *tg;
491 struct sched_rt_entity *rt_se;
498 * We add the notion of a root-domain which will be used to define per-domain
499 * variables. Each exclusive cpuset essentially defines an island domain by
500 * fully partitioning the member cpus from any other cpuset. Whenever a new
501 * exclusive cpuset is created, we also create and attach a new root-domain
508 cpumask_var_t online;
511 * The "RT overload" flag: it gets set if a CPU has more than
512 * one runnable RT task.
514 cpumask_var_t rto_mask;
517 struct cpupri cpupri;
519 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
521 * Preferred wake up cpu nominated by sched_mc balance that will be
522 * used when most cpus are idle in the system indicating overall very
523 * low system utilisation. Triggered at POWERSAVINGS_BALANCE_WAKEUP(2)
525 unsigned int sched_mc_preferred_wakeup_cpu;
530 * By default the system creates a single root-domain with all cpus as
531 * members (mimicking the global state we have today).
533 static struct root_domain def_root_domain;
538 * This is the main, per-CPU runqueue data structure.
540 * Locking rule: those places that want to lock multiple runqueues
541 * (such as the load balancing or the thread migration code), lock
542 * acquire operations must be ordered by ascending &runqueue.
549 * nr_running and cpu_load should be in the same cacheline because
550 * remote CPUs use both these fields when doing load calculation.
552 unsigned long nr_running;
553 #define CPU_LOAD_IDX_MAX 5
554 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
555 unsigned char idle_at_tick;
557 unsigned long last_tick_seen;
558 unsigned char in_nohz_recently;
560 /* capture load from *all* tasks on this cpu: */
561 struct load_weight load;
562 unsigned long nr_load_updates;
568 #ifdef CONFIG_FAIR_GROUP_SCHED
569 /* list of leaf cfs_rq on this cpu: */
570 struct list_head leaf_cfs_rq_list;
572 #ifdef CONFIG_RT_GROUP_SCHED
573 struct list_head leaf_rt_rq_list;
577 * This is part of a global counter where only the total sum
578 * over all CPUs matters. A task can increase this counter on
579 * one CPU and if it got migrated afterwards it may decrease
580 * it on another CPU. Always updated under the runqueue lock:
582 unsigned long nr_uninterruptible;
584 struct task_struct *curr, *idle;
585 unsigned long next_balance;
586 struct mm_struct *prev_mm;
593 struct root_domain *rd;
594 struct sched_domain *sd;
596 /* For active balancing */
599 /* cpu of this runqueue: */
603 unsigned long avg_load_per_task;
605 struct task_struct *migration_thread;
606 struct list_head migration_queue;
609 #ifdef CONFIG_SCHED_HRTICK
611 int hrtick_csd_pending;
612 struct call_single_data hrtick_csd;
614 struct hrtimer hrtick_timer;
617 #ifdef CONFIG_SCHEDSTATS
619 struct sched_info rq_sched_info;
620 unsigned long long rq_cpu_time;
621 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
623 /* sys_sched_yield() stats */
624 unsigned int yld_exp_empty;
625 unsigned int yld_act_empty;
626 unsigned int yld_both_empty;
627 unsigned int yld_count;
629 /* schedule() stats */
630 unsigned int sched_switch;
631 unsigned int sched_count;
632 unsigned int sched_goidle;
634 /* try_to_wake_up() stats */
635 unsigned int ttwu_count;
636 unsigned int ttwu_local;
639 unsigned int bkl_count;
643 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
645 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p, int sync)
647 rq->curr->sched_class->check_preempt_curr(rq, p, sync);
650 static inline int cpu_of(struct rq *rq)
660 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
661 * See detach_destroy_domains: synchronize_sched for details.
663 * The domain tree of any CPU may only be accessed from within
664 * preempt-disabled sections.
666 #define for_each_domain(cpu, __sd) \
667 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
669 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
670 #define this_rq() (&__get_cpu_var(runqueues))
671 #define task_rq(p) cpu_rq(task_cpu(p))
672 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
674 static inline void update_rq_clock(struct rq *rq)
676 rq->clock = sched_clock_cpu(cpu_of(rq));
680 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
682 #ifdef CONFIG_SCHED_DEBUG
683 # define const_debug __read_mostly
685 # define const_debug static const
691 * Returns true if the current cpu runqueue is locked.
692 * This interface allows printk to be called with the runqueue lock
693 * held and know whether or not it is OK to wake up the klogd.
695 int runqueue_is_locked(void)
698 struct rq *rq = cpu_rq(cpu);
701 ret = spin_is_locked(&rq->lock);
707 * Debugging: various feature bits
710 #define SCHED_FEAT(name, enabled) \
711 __SCHED_FEAT_##name ,
714 #include "sched_features.h"
719 #define SCHED_FEAT(name, enabled) \
720 (1UL << __SCHED_FEAT_##name) * enabled |
722 const_debug unsigned int sysctl_sched_features =
723 #include "sched_features.h"
728 #ifdef CONFIG_SCHED_DEBUG
729 #define SCHED_FEAT(name, enabled) \
732 static __read_mostly char *sched_feat_names[] = {
733 #include "sched_features.h"
739 static int sched_feat_show(struct seq_file *m, void *v)
743 for (i = 0; sched_feat_names[i]; i++) {
744 if (!(sysctl_sched_features & (1UL << i)))
746 seq_printf(m, "%s ", sched_feat_names[i]);
754 sched_feat_write(struct file *filp, const char __user *ubuf,
755 size_t cnt, loff_t *ppos)
765 if (copy_from_user(&buf, ubuf, cnt))
770 if (strncmp(buf, "NO_", 3) == 0) {
775 for (i = 0; sched_feat_names[i]; i++) {
776 int len = strlen(sched_feat_names[i]);
778 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
780 sysctl_sched_features &= ~(1UL << i);
782 sysctl_sched_features |= (1UL << i);
787 if (!sched_feat_names[i])
795 static int sched_feat_open(struct inode *inode, struct file *filp)
797 return single_open(filp, sched_feat_show, NULL);
800 static struct file_operations sched_feat_fops = {
801 .open = sched_feat_open,
802 .write = sched_feat_write,
805 .release = single_release,
808 static __init int sched_init_debug(void)
810 debugfs_create_file("sched_features", 0644, NULL, NULL,
815 late_initcall(sched_init_debug);
819 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
822 * Number of tasks to iterate in a single balance run.
823 * Limited because this is done with IRQs disabled.
825 const_debug unsigned int sysctl_sched_nr_migrate = 32;
828 * ratelimit for updating the group shares.
831 unsigned int sysctl_sched_shares_ratelimit = 250000;
834 * Inject some fuzzyness into changing the per-cpu group shares
835 * this avoids remote rq-locks at the expense of fairness.
838 unsigned int sysctl_sched_shares_thresh = 4;
841 * period over which we measure -rt task cpu usage in us.
844 unsigned int sysctl_sched_rt_period = 1000000;
846 static __read_mostly int scheduler_running;
849 * part of the period that we allow rt tasks to run in us.
852 int sysctl_sched_rt_runtime = 950000;
854 static inline u64 global_rt_period(void)
856 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
859 static inline u64 global_rt_runtime(void)
861 if (sysctl_sched_rt_runtime < 0)
864 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
867 #ifndef prepare_arch_switch
868 # define prepare_arch_switch(next) do { } while (0)
870 #ifndef finish_arch_switch
871 # define finish_arch_switch(prev) do { } while (0)
874 static inline int task_current(struct rq *rq, struct task_struct *p)
876 return rq->curr == p;
879 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
880 static inline int task_running(struct rq *rq, struct task_struct *p)
882 return task_current(rq, p);
885 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
889 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
891 #ifdef CONFIG_DEBUG_SPINLOCK
892 /* this is a valid case when another task releases the spinlock */
893 rq->lock.owner = current;
896 * If we are tracking spinlock dependencies then we have to
897 * fix up the runqueue lock - which gets 'carried over' from
900 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
902 spin_unlock_irq(&rq->lock);
905 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
906 static inline int task_running(struct rq *rq, struct task_struct *p)
911 return task_current(rq, p);
915 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
919 * We can optimise this out completely for !SMP, because the
920 * SMP rebalancing from interrupt is the only thing that cares
925 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
926 spin_unlock_irq(&rq->lock);
928 spin_unlock(&rq->lock);
932 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
936 * After ->oncpu is cleared, the task can be moved to a different CPU.
937 * We must ensure this doesn't happen until the switch is completely
943 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
947 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
950 * __task_rq_lock - lock the runqueue a given task resides on.
951 * Must be called interrupts disabled.
953 static inline struct rq *__task_rq_lock(struct task_struct *p)
957 struct rq *rq = task_rq(p);
958 spin_lock(&rq->lock);
959 if (likely(rq == task_rq(p)))
961 spin_unlock(&rq->lock);
966 * task_rq_lock - lock the runqueue a given task resides on and disable
967 * interrupts. Note the ordering: we can safely lookup the task_rq without
968 * explicitly disabling preemption.
970 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
976 local_irq_save(*flags);
978 spin_lock(&rq->lock);
979 if (likely(rq == task_rq(p)))
981 spin_unlock_irqrestore(&rq->lock, *flags);
985 void task_rq_unlock_wait(struct task_struct *p)
987 struct rq *rq = task_rq(p);
989 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
990 spin_unlock_wait(&rq->lock);
993 static void __task_rq_unlock(struct rq *rq)
996 spin_unlock(&rq->lock);
999 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1000 __releases(rq->lock)
1002 spin_unlock_irqrestore(&rq->lock, *flags);
1006 * this_rq_lock - lock this runqueue and disable interrupts.
1008 static struct rq *this_rq_lock(void)
1009 __acquires(rq->lock)
1013 local_irq_disable();
1015 spin_lock(&rq->lock);
1020 #ifdef CONFIG_SCHED_HRTICK
1022 * Use HR-timers to deliver accurate preemption points.
1024 * Its all a bit involved since we cannot program an hrt while holding the
1025 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1028 * When we get rescheduled we reprogram the hrtick_timer outside of the
1034 * - enabled by features
1035 * - hrtimer is actually high res
1037 static inline int hrtick_enabled(struct rq *rq)
1039 if (!sched_feat(HRTICK))
1041 if (!cpu_active(cpu_of(rq)))
1043 return hrtimer_is_hres_active(&rq->hrtick_timer);
1046 static void hrtick_clear(struct rq *rq)
1048 if (hrtimer_active(&rq->hrtick_timer))
1049 hrtimer_cancel(&rq->hrtick_timer);
1053 * High-resolution timer tick.
1054 * Runs from hardirq context with interrupts disabled.
1056 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1058 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1060 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1062 spin_lock(&rq->lock);
1063 update_rq_clock(rq);
1064 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1065 spin_unlock(&rq->lock);
1067 return HRTIMER_NORESTART;
1072 * called from hardirq (IPI) context
1074 static void __hrtick_start(void *arg)
1076 struct rq *rq = arg;
1078 spin_lock(&rq->lock);
1079 hrtimer_restart(&rq->hrtick_timer);
1080 rq->hrtick_csd_pending = 0;
1081 spin_unlock(&rq->lock);
1085 * Called to set the hrtick timer state.
1087 * called with rq->lock held and irqs disabled
1089 static void hrtick_start(struct rq *rq, u64 delay)
1091 struct hrtimer *timer = &rq->hrtick_timer;
1092 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1094 hrtimer_set_expires(timer, time);
1096 if (rq == this_rq()) {
1097 hrtimer_restart(timer);
1098 } else if (!rq->hrtick_csd_pending) {
1099 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd);
1100 rq->hrtick_csd_pending = 1;
1105 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1107 int cpu = (int)(long)hcpu;
1110 case CPU_UP_CANCELED:
1111 case CPU_UP_CANCELED_FROZEN:
1112 case CPU_DOWN_PREPARE:
1113 case CPU_DOWN_PREPARE_FROZEN:
1115 case CPU_DEAD_FROZEN:
1116 hrtick_clear(cpu_rq(cpu));
1123 static __init void init_hrtick(void)
1125 hotcpu_notifier(hotplug_hrtick, 0);
1129 * Called to set the hrtick timer state.
1131 * called with rq->lock held and irqs disabled
1133 static void hrtick_start(struct rq *rq, u64 delay)
1135 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay), HRTIMER_MODE_REL);
1138 static inline void init_hrtick(void)
1141 #endif /* CONFIG_SMP */
1143 static void init_rq_hrtick(struct rq *rq)
1146 rq->hrtick_csd_pending = 0;
1148 rq->hrtick_csd.flags = 0;
1149 rq->hrtick_csd.func = __hrtick_start;
1150 rq->hrtick_csd.info = rq;
1153 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1154 rq->hrtick_timer.function = hrtick;
1156 #else /* CONFIG_SCHED_HRTICK */
1157 static inline void hrtick_clear(struct rq *rq)
1161 static inline void init_rq_hrtick(struct rq *rq)
1165 static inline void init_hrtick(void)
1168 #endif /* CONFIG_SCHED_HRTICK */
1171 * resched_task - mark a task 'to be rescheduled now'.
1173 * On UP this means the setting of the need_resched flag, on SMP it
1174 * might also involve a cross-CPU call to trigger the scheduler on
1179 #ifndef tsk_is_polling
1180 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1183 static void resched_task(struct task_struct *p)
1187 assert_spin_locked(&task_rq(p)->lock);
1189 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
1192 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
1195 if (cpu == smp_processor_id())
1198 /* NEED_RESCHED must be visible before we test polling */
1200 if (!tsk_is_polling(p))
1201 smp_send_reschedule(cpu);
1204 static void resched_cpu(int cpu)
1206 struct rq *rq = cpu_rq(cpu);
1207 unsigned long flags;
1209 if (!spin_trylock_irqsave(&rq->lock, flags))
1211 resched_task(cpu_curr(cpu));
1212 spin_unlock_irqrestore(&rq->lock, flags);
1217 * When add_timer_on() enqueues a timer into the timer wheel of an
1218 * idle CPU then this timer might expire before the next timer event
1219 * which is scheduled to wake up that CPU. In case of a completely
1220 * idle system the next event might even be infinite time into the
1221 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1222 * leaves the inner idle loop so the newly added timer is taken into
1223 * account when the CPU goes back to idle and evaluates the timer
1224 * wheel for the next timer event.
1226 void wake_up_idle_cpu(int cpu)
1228 struct rq *rq = cpu_rq(cpu);
1230 if (cpu == smp_processor_id())
1234 * This is safe, as this function is called with the timer
1235 * wheel base lock of (cpu) held. When the CPU is on the way
1236 * to idle and has not yet set rq->curr to idle then it will
1237 * be serialized on the timer wheel base lock and take the new
1238 * timer into account automatically.
1240 if (rq->curr != rq->idle)
1244 * We can set TIF_RESCHED on the idle task of the other CPU
1245 * lockless. The worst case is that the other CPU runs the
1246 * idle task through an additional NOOP schedule()
1248 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1250 /* NEED_RESCHED must be visible before we test polling */
1252 if (!tsk_is_polling(rq->idle))
1253 smp_send_reschedule(cpu);
1255 #endif /* CONFIG_NO_HZ */
1257 #else /* !CONFIG_SMP */
1258 static void resched_task(struct task_struct *p)
1260 assert_spin_locked(&task_rq(p)->lock);
1261 set_tsk_need_resched(p);
1263 #endif /* CONFIG_SMP */
1265 #if BITS_PER_LONG == 32
1266 # define WMULT_CONST (~0UL)
1268 # define WMULT_CONST (1UL << 32)
1271 #define WMULT_SHIFT 32
1274 * Shift right and round:
1276 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1279 * delta *= weight / lw
1281 static unsigned long
1282 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1283 struct load_weight *lw)
1287 if (!lw->inv_weight) {
1288 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1291 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1295 tmp = (u64)delta_exec * weight;
1297 * Check whether we'd overflow the 64-bit multiplication:
1299 if (unlikely(tmp > WMULT_CONST))
1300 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1303 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1305 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1308 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1314 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1321 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1322 * of tasks with abnormal "nice" values across CPUs the contribution that
1323 * each task makes to its run queue's load is weighted according to its
1324 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1325 * scaled version of the new time slice allocation that they receive on time
1329 #define WEIGHT_IDLEPRIO 2
1330 #define WMULT_IDLEPRIO (1 << 31)
1333 * Nice levels are multiplicative, with a gentle 10% change for every
1334 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1335 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1336 * that remained on nice 0.
1338 * The "10% effect" is relative and cumulative: from _any_ nice level,
1339 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1340 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1341 * If a task goes up by ~10% and another task goes down by ~10% then
1342 * the relative distance between them is ~25%.)
1344 static const int prio_to_weight[40] = {
1345 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1346 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1347 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1348 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1349 /* 0 */ 1024, 820, 655, 526, 423,
1350 /* 5 */ 335, 272, 215, 172, 137,
1351 /* 10 */ 110, 87, 70, 56, 45,
1352 /* 15 */ 36, 29, 23, 18, 15,
1356 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1358 * In cases where the weight does not change often, we can use the
1359 * precalculated inverse to speed up arithmetics by turning divisions
1360 * into multiplications:
1362 static const u32 prio_to_wmult[40] = {
1363 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1364 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1365 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1366 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1367 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1368 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1369 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1370 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1373 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1376 * runqueue iterator, to support SMP load-balancing between different
1377 * scheduling classes, without having to expose their internal data
1378 * structures to the load-balancing proper:
1380 struct rq_iterator {
1382 struct task_struct *(*start)(void *);
1383 struct task_struct *(*next)(void *);
1387 static unsigned long
1388 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1389 unsigned long max_load_move, struct sched_domain *sd,
1390 enum cpu_idle_type idle, int *all_pinned,
1391 int *this_best_prio, struct rq_iterator *iterator);
1394 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1395 struct sched_domain *sd, enum cpu_idle_type idle,
1396 struct rq_iterator *iterator);
1399 #ifdef CONFIG_CGROUP_CPUACCT
1400 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1402 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1405 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1407 update_load_add(&rq->load, load);
1410 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1412 update_load_sub(&rq->load, load);
1415 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1416 typedef int (*tg_visitor)(struct task_group *, void *);
1419 * Iterate the full tree, calling @down when first entering a node and @up when
1420 * leaving it for the final time.
1422 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1424 struct task_group *parent, *child;
1428 parent = &root_task_group;
1430 ret = (*down)(parent, data);
1433 list_for_each_entry_rcu(child, &parent->children, siblings) {
1440 ret = (*up)(parent, data);
1445 parent = parent->parent;
1454 static int tg_nop(struct task_group *tg, void *data)
1461 static unsigned long source_load(int cpu, int type);
1462 static unsigned long target_load(int cpu, int type);
1463 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1465 static unsigned long cpu_avg_load_per_task(int cpu)
1467 struct rq *rq = cpu_rq(cpu);
1468 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1471 rq->avg_load_per_task = rq->load.weight / nr_running;
1473 rq->avg_load_per_task = 0;
1475 return rq->avg_load_per_task;
1478 #ifdef CONFIG_FAIR_GROUP_SCHED
1480 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1483 * Calculate and set the cpu's group shares.
1486 update_group_shares_cpu(struct task_group *tg, int cpu,
1487 unsigned long sd_shares, unsigned long sd_rq_weight)
1489 unsigned long shares;
1490 unsigned long rq_weight;
1495 rq_weight = tg->cfs_rq[cpu]->rq_weight;
1498 * \Sum shares * rq_weight
1499 * shares = -----------------------
1503 shares = (sd_shares * rq_weight) / sd_rq_weight;
1504 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1506 if (abs(shares - tg->se[cpu]->load.weight) >
1507 sysctl_sched_shares_thresh) {
1508 struct rq *rq = cpu_rq(cpu);
1509 unsigned long flags;
1511 spin_lock_irqsave(&rq->lock, flags);
1512 tg->cfs_rq[cpu]->shares = shares;
1514 __set_se_shares(tg->se[cpu], shares);
1515 spin_unlock_irqrestore(&rq->lock, flags);
1520 * Re-compute the task group their per cpu shares over the given domain.
1521 * This needs to be done in a bottom-up fashion because the rq weight of a
1522 * parent group depends on the shares of its child groups.
1524 static int tg_shares_up(struct task_group *tg, void *data)
1526 unsigned long weight, rq_weight = 0;
1527 unsigned long shares = 0;
1528 struct sched_domain *sd = data;
1531 for_each_cpu(i, sched_domain_span(sd)) {
1533 * If there are currently no tasks on the cpu pretend there
1534 * is one of average load so that when a new task gets to
1535 * run here it will not get delayed by group starvation.
1537 weight = tg->cfs_rq[i]->load.weight;
1539 weight = NICE_0_LOAD;
1541 tg->cfs_rq[i]->rq_weight = weight;
1542 rq_weight += weight;
1543 shares += tg->cfs_rq[i]->shares;
1546 if ((!shares && rq_weight) || shares > tg->shares)
1547 shares = tg->shares;
1549 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1550 shares = tg->shares;
1552 for_each_cpu(i, sched_domain_span(sd))
1553 update_group_shares_cpu(tg, i, shares, rq_weight);
1559 * Compute the cpu's hierarchical load factor for each task group.
1560 * This needs to be done in a top-down fashion because the load of a child
1561 * group is a fraction of its parents load.
1563 static int tg_load_down(struct task_group *tg, void *data)
1566 long cpu = (long)data;
1569 load = cpu_rq(cpu)->load.weight;
1571 load = tg->parent->cfs_rq[cpu]->h_load;
1572 load *= tg->cfs_rq[cpu]->shares;
1573 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1576 tg->cfs_rq[cpu]->h_load = load;
1581 static void update_shares(struct sched_domain *sd)
1583 u64 now = cpu_clock(raw_smp_processor_id());
1584 s64 elapsed = now - sd->last_update;
1586 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1587 sd->last_update = now;
1588 walk_tg_tree(tg_nop, tg_shares_up, sd);
1592 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1594 spin_unlock(&rq->lock);
1596 spin_lock(&rq->lock);
1599 static void update_h_load(long cpu)
1601 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1606 static inline void update_shares(struct sched_domain *sd)
1610 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1616 #ifdef CONFIG_PREEMPT
1619 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1620 * way at the expense of forcing extra atomic operations in all
1621 * invocations. This assures that the double_lock is acquired using the
1622 * same underlying policy as the spinlock_t on this architecture, which
1623 * reduces latency compared to the unfair variant below. However, it
1624 * also adds more overhead and therefore may reduce throughput.
1626 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1627 __releases(this_rq->lock)
1628 __acquires(busiest->lock)
1629 __acquires(this_rq->lock)
1631 spin_unlock(&this_rq->lock);
1632 double_rq_lock(this_rq, busiest);
1639 * Unfair double_lock_balance: Optimizes throughput at the expense of
1640 * latency by eliminating extra atomic operations when the locks are
1641 * already in proper order on entry. This favors lower cpu-ids and will
1642 * grant the double lock to lower cpus over higher ids under contention,
1643 * regardless of entry order into the function.
1645 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1646 __releases(this_rq->lock)
1647 __acquires(busiest->lock)
1648 __acquires(this_rq->lock)
1652 if (unlikely(!spin_trylock(&busiest->lock))) {
1653 if (busiest < this_rq) {
1654 spin_unlock(&this_rq->lock);
1655 spin_lock(&busiest->lock);
1656 spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING);
1659 spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING);
1664 #endif /* CONFIG_PREEMPT */
1667 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1669 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1671 if (unlikely(!irqs_disabled())) {
1672 /* printk() doesn't work good under rq->lock */
1673 spin_unlock(&this_rq->lock);
1677 return _double_lock_balance(this_rq, busiest);
1680 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1681 __releases(busiest->lock)
1683 spin_unlock(&busiest->lock);
1684 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1688 #ifdef CONFIG_FAIR_GROUP_SCHED
1689 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1692 cfs_rq->shares = shares;
1697 #include "sched_stats.h"
1698 #include "sched_idletask.c"
1699 #include "sched_fair.c"
1700 #include "sched_rt.c"
1701 #ifdef CONFIG_SCHED_DEBUG
1702 # include "sched_debug.c"
1705 #define sched_class_highest (&rt_sched_class)
1706 #define for_each_class(class) \
1707 for (class = sched_class_highest; class; class = class->next)
1709 static void inc_nr_running(struct rq *rq)
1714 static void dec_nr_running(struct rq *rq)
1719 static void set_load_weight(struct task_struct *p)
1721 if (task_has_rt_policy(p)) {
1722 p->se.load.weight = prio_to_weight[0] * 2;
1723 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1728 * SCHED_IDLE tasks get minimal weight:
1730 if (p->policy == SCHED_IDLE) {
1731 p->se.load.weight = WEIGHT_IDLEPRIO;
1732 p->se.load.inv_weight = WMULT_IDLEPRIO;
1736 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1737 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1740 static void update_avg(u64 *avg, u64 sample)
1742 s64 diff = sample - *avg;
1746 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1748 sched_info_queued(p);
1749 p->sched_class->enqueue_task(rq, p, wakeup);
1753 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1755 if (sleep && p->se.last_wakeup) {
1756 update_avg(&p->se.avg_overlap,
1757 p->se.sum_exec_runtime - p->se.last_wakeup);
1758 p->se.last_wakeup = 0;
1761 sched_info_dequeued(p);
1762 p->sched_class->dequeue_task(rq, p, sleep);
1767 * __normal_prio - return the priority that is based on the static prio
1769 static inline int __normal_prio(struct task_struct *p)
1771 return p->static_prio;
1775 * Calculate the expected normal priority: i.e. priority
1776 * without taking RT-inheritance into account. Might be
1777 * boosted by interactivity modifiers. Changes upon fork,
1778 * setprio syscalls, and whenever the interactivity
1779 * estimator recalculates.
1781 static inline int normal_prio(struct task_struct *p)
1785 if (task_has_rt_policy(p))
1786 prio = MAX_RT_PRIO-1 - p->rt_priority;
1788 prio = __normal_prio(p);
1793 * Calculate the current priority, i.e. the priority
1794 * taken into account by the scheduler. This value might
1795 * be boosted by RT tasks, or might be boosted by
1796 * interactivity modifiers. Will be RT if the task got
1797 * RT-boosted. If not then it returns p->normal_prio.
1799 static int effective_prio(struct task_struct *p)
1801 p->normal_prio = normal_prio(p);
1803 * If we are RT tasks or we were boosted to RT priority,
1804 * keep the priority unchanged. Otherwise, update priority
1805 * to the normal priority:
1807 if (!rt_prio(p->prio))
1808 return p->normal_prio;
1813 * activate_task - move a task to the runqueue.
1815 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1817 if (task_contributes_to_load(p))
1818 rq->nr_uninterruptible--;
1820 enqueue_task(rq, p, wakeup);
1825 * deactivate_task - remove a task from the runqueue.
1827 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1829 if (task_contributes_to_load(p))
1830 rq->nr_uninterruptible++;
1832 dequeue_task(rq, p, sleep);
1837 * task_curr - is this task currently executing on a CPU?
1838 * @p: the task in question.
1840 inline int task_curr(const struct task_struct *p)
1842 return cpu_curr(task_cpu(p)) == p;
1845 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1847 set_task_rq(p, cpu);
1850 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1851 * successfuly executed on another CPU. We must ensure that updates of
1852 * per-task data have been completed by this moment.
1855 task_thread_info(p)->cpu = cpu;
1859 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1860 const struct sched_class *prev_class,
1861 int oldprio, int running)
1863 if (prev_class != p->sched_class) {
1864 if (prev_class->switched_from)
1865 prev_class->switched_from(rq, p, running);
1866 p->sched_class->switched_to(rq, p, running);
1868 p->sched_class->prio_changed(rq, p, oldprio, running);
1873 /* Used instead of source_load when we know the type == 0 */
1874 static unsigned long weighted_cpuload(const int cpu)
1876 return cpu_rq(cpu)->load.weight;
1880 * Is this task likely cache-hot:
1883 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1888 * Buddy candidates are cache hot:
1890 if (sched_feat(CACHE_HOT_BUDDY) &&
1891 (&p->se == cfs_rq_of(&p->se)->next ||
1892 &p->se == cfs_rq_of(&p->se)->last))
1895 if (p->sched_class != &fair_sched_class)
1898 if (sysctl_sched_migration_cost == -1)
1900 if (sysctl_sched_migration_cost == 0)
1903 delta = now - p->se.exec_start;
1905 return delta < (s64)sysctl_sched_migration_cost;
1909 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1911 int old_cpu = task_cpu(p);
1912 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1913 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1914 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1917 clock_offset = old_rq->clock - new_rq->clock;
1919 trace_sched_migrate_task(p, task_cpu(p), new_cpu);
1921 #ifdef CONFIG_SCHEDSTATS
1922 if (p->se.wait_start)
1923 p->se.wait_start -= clock_offset;
1924 if (p->se.sleep_start)
1925 p->se.sleep_start -= clock_offset;
1926 if (p->se.block_start)
1927 p->se.block_start -= clock_offset;
1928 if (old_cpu != new_cpu) {
1929 schedstat_inc(p, se.nr_migrations);
1930 if (task_hot(p, old_rq->clock, NULL))
1931 schedstat_inc(p, se.nr_forced2_migrations);
1934 p->se.vruntime -= old_cfsrq->min_vruntime -
1935 new_cfsrq->min_vruntime;
1937 __set_task_cpu(p, new_cpu);
1940 struct migration_req {
1941 struct list_head list;
1943 struct task_struct *task;
1946 struct completion done;
1950 * The task's runqueue lock must be held.
1951 * Returns true if you have to wait for migration thread.
1954 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1956 struct rq *rq = task_rq(p);
1959 * If the task is not on a runqueue (and not running), then
1960 * it is sufficient to simply update the task's cpu field.
1962 if (!p->se.on_rq && !task_running(rq, p)) {
1963 set_task_cpu(p, dest_cpu);
1967 init_completion(&req->done);
1969 req->dest_cpu = dest_cpu;
1970 list_add(&req->list, &rq->migration_queue);
1976 * wait_task_inactive - wait for a thread to unschedule.
1978 * If @match_state is nonzero, it's the @p->state value just checked and
1979 * not expected to change. If it changes, i.e. @p might have woken up,
1980 * then return zero. When we succeed in waiting for @p to be off its CPU,
1981 * we return a positive number (its total switch count). If a second call
1982 * a short while later returns the same number, the caller can be sure that
1983 * @p has remained unscheduled the whole time.
1985 * The caller must ensure that the task *will* unschedule sometime soon,
1986 * else this function might spin for a *long* time. This function can't
1987 * be called with interrupts off, or it may introduce deadlock with
1988 * smp_call_function() if an IPI is sent by the same process we are
1989 * waiting to become inactive.
1991 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1993 unsigned long flags;
2000 * We do the initial early heuristics without holding
2001 * any task-queue locks at all. We'll only try to get
2002 * the runqueue lock when things look like they will
2008 * If the task is actively running on another CPU
2009 * still, just relax and busy-wait without holding
2012 * NOTE! Since we don't hold any locks, it's not
2013 * even sure that "rq" stays as the right runqueue!
2014 * But we don't care, since "task_running()" will
2015 * return false if the runqueue has changed and p
2016 * is actually now running somewhere else!
2018 while (task_running(rq, p)) {
2019 if (match_state && unlikely(p->state != match_state))
2025 * Ok, time to look more closely! We need the rq
2026 * lock now, to be *sure*. If we're wrong, we'll
2027 * just go back and repeat.
2029 rq = task_rq_lock(p, &flags);
2030 trace_sched_wait_task(rq, p);
2031 running = task_running(rq, p);
2032 on_rq = p->se.on_rq;
2034 if (!match_state || p->state == match_state)
2035 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2036 task_rq_unlock(rq, &flags);
2039 * If it changed from the expected state, bail out now.
2041 if (unlikely(!ncsw))
2045 * Was it really running after all now that we
2046 * checked with the proper locks actually held?
2048 * Oops. Go back and try again..
2050 if (unlikely(running)) {
2056 * It's not enough that it's not actively running,
2057 * it must be off the runqueue _entirely_, and not
2060 * So if it wa still runnable (but just not actively
2061 * running right now), it's preempted, and we should
2062 * yield - it could be a while.
2064 if (unlikely(on_rq)) {
2065 schedule_timeout_uninterruptible(1);
2070 * Ahh, all good. It wasn't running, and it wasn't
2071 * runnable, which means that it will never become
2072 * running in the future either. We're all done!
2081 * kick_process - kick a running thread to enter/exit the kernel
2082 * @p: the to-be-kicked thread
2084 * Cause a process which is running on another CPU to enter
2085 * kernel-mode, without any delay. (to get signals handled.)
2087 * NOTE: this function doesnt have to take the runqueue lock,
2088 * because all it wants to ensure is that the remote task enters
2089 * the kernel. If the IPI races and the task has been migrated
2090 * to another CPU then no harm is done and the purpose has been
2093 void kick_process(struct task_struct *p)
2099 if ((cpu != smp_processor_id()) && task_curr(p))
2100 smp_send_reschedule(cpu);
2105 * Return a low guess at the load of a migration-source cpu weighted
2106 * according to the scheduling class and "nice" value.
2108 * We want to under-estimate the load of migration sources, to
2109 * balance conservatively.
2111 static unsigned long source_load(int cpu, int type)
2113 struct rq *rq = cpu_rq(cpu);
2114 unsigned long total = weighted_cpuload(cpu);
2116 if (type == 0 || !sched_feat(LB_BIAS))
2119 return min(rq->cpu_load[type-1], total);
2123 * Return a high guess at the load of a migration-target cpu weighted
2124 * according to the scheduling class and "nice" value.
2126 static unsigned long target_load(int cpu, int type)
2128 struct rq *rq = cpu_rq(cpu);
2129 unsigned long total = weighted_cpuload(cpu);
2131 if (type == 0 || !sched_feat(LB_BIAS))
2134 return max(rq->cpu_load[type-1], total);
2138 * find_idlest_group finds and returns the least busy CPU group within the
2141 static struct sched_group *
2142 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2144 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2145 unsigned long min_load = ULONG_MAX, this_load = 0;
2146 int load_idx = sd->forkexec_idx;
2147 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2150 unsigned long load, avg_load;
2154 /* Skip over this group if it has no CPUs allowed */
2155 if (!cpumask_intersects(sched_group_cpus(group),
2159 local_group = cpumask_test_cpu(this_cpu,
2160 sched_group_cpus(group));
2162 /* Tally up the load of all CPUs in the group */
2165 for_each_cpu(i, sched_group_cpus(group)) {
2166 /* Bias balancing toward cpus of our domain */
2168 load = source_load(i, load_idx);
2170 load = target_load(i, load_idx);
2175 /* Adjust by relative CPU power of the group */
2176 avg_load = sg_div_cpu_power(group,
2177 avg_load * SCHED_LOAD_SCALE);
2180 this_load = avg_load;
2182 } else if (avg_load < min_load) {
2183 min_load = avg_load;
2186 } while (group = group->next, group != sd->groups);
2188 if (!idlest || 100*this_load < imbalance*min_load)
2194 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2197 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2199 unsigned long load, min_load = ULONG_MAX;
2203 /* Traverse only the allowed CPUs */
2204 for_each_cpu_and(i, sched_group_cpus(group), &p->cpus_allowed) {
2205 load = weighted_cpuload(i);
2207 if (load < min_load || (load == min_load && i == this_cpu)) {
2217 * sched_balance_self: balance the current task (running on cpu) in domains
2218 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2221 * Balance, ie. select the least loaded group.
2223 * Returns the target CPU number, or the same CPU if no balancing is needed.
2225 * preempt must be disabled.
2227 static int sched_balance_self(int cpu, int flag)
2229 struct task_struct *t = current;
2230 struct sched_domain *tmp, *sd = NULL;
2232 for_each_domain(cpu, tmp) {
2234 * If power savings logic is enabled for a domain, stop there.
2236 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2238 if (tmp->flags & flag)
2246 struct sched_group *group;
2247 int new_cpu, weight;
2249 if (!(sd->flags & flag)) {
2254 group = find_idlest_group(sd, t, cpu);
2260 new_cpu = find_idlest_cpu(group, t, cpu);
2261 if (new_cpu == -1 || new_cpu == cpu) {
2262 /* Now try balancing at a lower domain level of cpu */
2267 /* Now try balancing at a lower domain level of new_cpu */
2269 weight = cpumask_weight(sched_domain_span(sd));
2271 for_each_domain(cpu, tmp) {
2272 if (weight <= cpumask_weight(sched_domain_span(tmp)))
2274 if (tmp->flags & flag)
2277 /* while loop will break here if sd == NULL */
2283 #endif /* CONFIG_SMP */
2286 * try_to_wake_up - wake up a thread
2287 * @p: the to-be-woken-up thread
2288 * @state: the mask of task states that can be woken
2289 * @sync: do a synchronous wakeup?
2291 * Put it on the run-queue if it's not already there. The "current"
2292 * thread is always on the run-queue (except when the actual
2293 * re-schedule is in progress), and as such you're allowed to do
2294 * the simpler "current->state = TASK_RUNNING" to mark yourself
2295 * runnable without the overhead of this.
2297 * returns failure only if the task is already active.
2299 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2301 int cpu, orig_cpu, this_cpu, success = 0;
2302 unsigned long flags;
2306 if (!sched_feat(SYNC_WAKEUPS))
2310 if (sched_feat(LB_WAKEUP_UPDATE)) {
2311 struct sched_domain *sd;
2313 this_cpu = raw_smp_processor_id();
2316 for_each_domain(this_cpu, sd) {
2317 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2326 rq = task_rq_lock(p, &flags);
2327 update_rq_clock(rq);
2328 old_state = p->state;
2329 if (!(old_state & state))
2337 this_cpu = smp_processor_id();
2340 if (unlikely(task_running(rq, p)))
2343 cpu = p->sched_class->select_task_rq(p, sync);
2344 if (cpu != orig_cpu) {
2345 set_task_cpu(p, cpu);
2346 task_rq_unlock(rq, &flags);
2347 /* might preempt at this point */
2348 rq = task_rq_lock(p, &flags);
2349 old_state = p->state;
2350 if (!(old_state & state))
2355 this_cpu = smp_processor_id();
2359 #ifdef CONFIG_SCHEDSTATS
2360 schedstat_inc(rq, ttwu_count);
2361 if (cpu == this_cpu)
2362 schedstat_inc(rq, ttwu_local);
2364 struct sched_domain *sd;
2365 for_each_domain(this_cpu, sd) {
2366 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2367 schedstat_inc(sd, ttwu_wake_remote);
2372 #endif /* CONFIG_SCHEDSTATS */
2375 #endif /* CONFIG_SMP */
2376 schedstat_inc(p, se.nr_wakeups);
2378 schedstat_inc(p, se.nr_wakeups_sync);
2379 if (orig_cpu != cpu)
2380 schedstat_inc(p, se.nr_wakeups_migrate);
2381 if (cpu == this_cpu)
2382 schedstat_inc(p, se.nr_wakeups_local);
2384 schedstat_inc(p, se.nr_wakeups_remote);
2385 activate_task(rq, p, 1);
2389 trace_sched_wakeup(rq, p, success);
2390 check_preempt_curr(rq, p, sync);
2392 p->state = TASK_RUNNING;
2394 if (p->sched_class->task_wake_up)
2395 p->sched_class->task_wake_up(rq, p);
2398 current->se.last_wakeup = current->se.sum_exec_runtime;
2400 task_rq_unlock(rq, &flags);
2405 int wake_up_process(struct task_struct *p)
2407 return try_to_wake_up(p, TASK_ALL, 0);
2409 EXPORT_SYMBOL(wake_up_process);
2411 int wake_up_state(struct task_struct *p, unsigned int state)
2413 return try_to_wake_up(p, state, 0);
2417 * Perform scheduler related setup for a newly forked process p.
2418 * p is forked by current.
2420 * __sched_fork() is basic setup used by init_idle() too:
2422 static void __sched_fork(struct task_struct *p)
2424 p->se.exec_start = 0;
2425 p->se.sum_exec_runtime = 0;
2426 p->se.prev_sum_exec_runtime = 0;
2427 p->se.last_wakeup = 0;
2428 p->se.avg_overlap = 0;
2430 #ifdef CONFIG_SCHEDSTATS
2431 p->se.wait_start = 0;
2432 p->se.sum_sleep_runtime = 0;
2433 p->se.sleep_start = 0;
2434 p->se.block_start = 0;
2435 p->se.sleep_max = 0;
2436 p->se.block_max = 0;
2438 p->se.slice_max = 0;
2442 INIT_LIST_HEAD(&p->rt.run_list);
2444 INIT_LIST_HEAD(&p->se.group_node);
2446 #ifdef CONFIG_PREEMPT_NOTIFIERS
2447 INIT_HLIST_HEAD(&p->preempt_notifiers);
2451 * We mark the process as running here, but have not actually
2452 * inserted it onto the runqueue yet. This guarantees that
2453 * nobody will actually run it, and a signal or other external
2454 * event cannot wake it up and insert it on the runqueue either.
2456 p->state = TASK_RUNNING;
2460 * fork()/clone()-time setup:
2462 void sched_fork(struct task_struct *p, int clone_flags)
2464 int cpu = get_cpu();
2469 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2471 set_task_cpu(p, cpu);
2474 * Make sure we do not leak PI boosting priority to the child:
2476 p->prio = current->normal_prio;
2477 if (!rt_prio(p->prio))
2478 p->sched_class = &fair_sched_class;
2480 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2481 if (likely(sched_info_on()))
2482 memset(&p->sched_info, 0, sizeof(p->sched_info));
2484 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2487 #ifdef CONFIG_PREEMPT
2488 /* Want to start with kernel preemption disabled. */
2489 task_thread_info(p)->preempt_count = 1;
2491 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2497 * wake_up_new_task - wake up a newly created task for the first time.
2499 * This function will do some initial scheduler statistics housekeeping
2500 * that must be done for every newly created context, then puts the task
2501 * on the runqueue and wakes it.
2503 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2505 unsigned long flags;
2508 rq = task_rq_lock(p, &flags);
2509 BUG_ON(p->state != TASK_RUNNING);
2510 update_rq_clock(rq);
2512 p->prio = effective_prio(p);
2514 if (!p->sched_class->task_new || !current->se.on_rq) {
2515 activate_task(rq, p, 0);
2518 * Let the scheduling class do new task startup
2519 * management (if any):
2521 p->sched_class->task_new(rq, p);
2524 trace_sched_wakeup_new(rq, p, 1);
2525 check_preempt_curr(rq, p, 0);
2527 if (p->sched_class->task_wake_up)
2528 p->sched_class->task_wake_up(rq, p);
2530 task_rq_unlock(rq, &flags);
2533 #ifdef CONFIG_PREEMPT_NOTIFIERS
2536 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2537 * @notifier: notifier struct to register
2539 void preempt_notifier_register(struct preempt_notifier *notifier)
2541 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2543 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2546 * preempt_notifier_unregister - no longer interested in preemption notifications
2547 * @notifier: notifier struct to unregister
2549 * This is safe to call from within a preemption notifier.
2551 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2553 hlist_del(¬ifier->link);
2555 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2557 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2559 struct preempt_notifier *notifier;
2560 struct hlist_node *node;
2562 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2563 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2567 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2568 struct task_struct *next)
2570 struct preempt_notifier *notifier;
2571 struct hlist_node *node;
2573 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2574 notifier->ops->sched_out(notifier, next);
2577 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2579 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2584 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2585 struct task_struct *next)
2589 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2592 * prepare_task_switch - prepare to switch tasks
2593 * @rq: the runqueue preparing to switch
2594 * @prev: the current task that is being switched out
2595 * @next: the task we are going to switch to.
2597 * This is called with the rq lock held and interrupts off. It must
2598 * be paired with a subsequent finish_task_switch after the context
2601 * prepare_task_switch sets up locking and calls architecture specific
2605 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2606 struct task_struct *next)
2608 fire_sched_out_preempt_notifiers(prev, next);
2609 prepare_lock_switch(rq, next);
2610 prepare_arch_switch(next);
2614 * finish_task_switch - clean up after a task-switch
2615 * @rq: runqueue associated with task-switch
2616 * @prev: the thread we just switched away from.
2618 * finish_task_switch must be called after the context switch, paired
2619 * with a prepare_task_switch call before the context switch.
2620 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2621 * and do any other architecture-specific cleanup actions.
2623 * Note that we may have delayed dropping an mm in context_switch(). If
2624 * so, we finish that here outside of the runqueue lock. (Doing it
2625 * with the lock held can cause deadlocks; see schedule() for
2628 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2629 __releases(rq->lock)
2631 struct mm_struct *mm = rq->prev_mm;
2634 int post_schedule = 0;
2636 if (current->sched_class->needs_post_schedule)
2637 post_schedule = current->sched_class->needs_post_schedule(rq);
2643 * A task struct has one reference for the use as "current".
2644 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2645 * schedule one last time. The schedule call will never return, and
2646 * the scheduled task must drop that reference.
2647 * The test for TASK_DEAD must occur while the runqueue locks are
2648 * still held, otherwise prev could be scheduled on another cpu, die
2649 * there before we look at prev->state, and then the reference would
2651 * Manfred Spraul <manfred@colorfullife.com>
2653 prev_state = prev->state;
2654 finish_arch_switch(prev);
2655 finish_lock_switch(rq, prev);
2658 current->sched_class->post_schedule(rq);
2661 fire_sched_in_preempt_notifiers(current);
2664 if (unlikely(prev_state == TASK_DEAD)) {
2666 * Remove function-return probe instances associated with this
2667 * task and put them back on the free list.
2669 kprobe_flush_task(prev);
2670 put_task_struct(prev);
2675 * schedule_tail - first thing a freshly forked thread must call.
2676 * @prev: the thread we just switched away from.
2678 asmlinkage void schedule_tail(struct task_struct *prev)
2679 __releases(rq->lock)
2681 struct rq *rq = this_rq();
2683 finish_task_switch(rq, prev);
2684 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2685 /* In this case, finish_task_switch does not reenable preemption */
2688 if (current->set_child_tid)
2689 put_user(task_pid_vnr(current), current->set_child_tid);
2693 * context_switch - switch to the new MM and the new
2694 * thread's register state.
2697 context_switch(struct rq *rq, struct task_struct *prev,
2698 struct task_struct *next)
2700 struct mm_struct *mm, *oldmm;
2702 prepare_task_switch(rq, prev, next);
2703 trace_sched_switch(rq, prev, next);
2705 oldmm = prev->active_mm;
2707 * For paravirt, this is coupled with an exit in switch_to to
2708 * combine the page table reload and the switch backend into
2711 arch_enter_lazy_cpu_mode();
2713 if (unlikely(!mm)) {
2714 next->active_mm = oldmm;
2715 atomic_inc(&oldmm->mm_count);
2716 enter_lazy_tlb(oldmm, next);
2718 switch_mm(oldmm, mm, next);
2720 if (unlikely(!prev->mm)) {
2721 prev->active_mm = NULL;
2722 rq->prev_mm = oldmm;
2725 * Since the runqueue lock will be released by the next
2726 * task (which is an invalid locking op but in the case
2727 * of the scheduler it's an obvious special-case), so we
2728 * do an early lockdep release here:
2730 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2731 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2734 /* Here we just switch the register state and the stack. */
2735 switch_to(prev, next, prev);
2739 * this_rq must be evaluated again because prev may have moved
2740 * CPUs since it called schedule(), thus the 'rq' on its stack
2741 * frame will be invalid.
2743 finish_task_switch(this_rq(), prev);
2747 * nr_running, nr_uninterruptible and nr_context_switches:
2749 * externally visible scheduler statistics: current number of runnable
2750 * threads, current number of uninterruptible-sleeping threads, total
2751 * number of context switches performed since bootup.
2753 unsigned long nr_running(void)
2755 unsigned long i, sum = 0;
2757 for_each_online_cpu(i)
2758 sum += cpu_rq(i)->nr_running;
2763 unsigned long nr_uninterruptible(void)
2765 unsigned long i, sum = 0;
2767 for_each_possible_cpu(i)
2768 sum += cpu_rq(i)->nr_uninterruptible;
2771 * Since we read the counters lockless, it might be slightly
2772 * inaccurate. Do not allow it to go below zero though:
2774 if (unlikely((long)sum < 0))
2780 unsigned long long nr_context_switches(void)
2783 unsigned long long sum = 0;
2785 for_each_possible_cpu(i)
2786 sum += cpu_rq(i)->nr_switches;
2791 unsigned long nr_iowait(void)
2793 unsigned long i, sum = 0;
2795 for_each_possible_cpu(i)
2796 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2801 unsigned long nr_active(void)
2803 unsigned long i, running = 0, uninterruptible = 0;
2805 for_each_online_cpu(i) {
2806 running += cpu_rq(i)->nr_running;
2807 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2810 if (unlikely((long)uninterruptible < 0))
2811 uninterruptible = 0;
2813 return running + uninterruptible;
2817 * Update rq->cpu_load[] statistics. This function is usually called every
2818 * scheduler tick (TICK_NSEC).
2820 static void update_cpu_load(struct rq *this_rq)
2822 unsigned long this_load = this_rq->load.weight;
2825 this_rq->nr_load_updates++;
2827 /* Update our load: */
2828 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2829 unsigned long old_load, new_load;
2831 /* scale is effectively 1 << i now, and >> i divides by scale */
2833 old_load = this_rq->cpu_load[i];
2834 new_load = this_load;
2836 * Round up the averaging division if load is increasing. This
2837 * prevents us from getting stuck on 9 if the load is 10, for
2840 if (new_load > old_load)
2841 new_load += scale-1;
2842 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2849 * double_rq_lock - safely lock two runqueues
2851 * Note this does not disable interrupts like task_rq_lock,
2852 * you need to do so manually before calling.
2854 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2855 __acquires(rq1->lock)
2856 __acquires(rq2->lock)
2858 BUG_ON(!irqs_disabled());
2860 spin_lock(&rq1->lock);
2861 __acquire(rq2->lock); /* Fake it out ;) */
2864 spin_lock(&rq1->lock);
2865 spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
2867 spin_lock(&rq2->lock);
2868 spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
2871 update_rq_clock(rq1);
2872 update_rq_clock(rq2);
2876 * double_rq_unlock - safely unlock two runqueues
2878 * Note this does not restore interrupts like task_rq_unlock,
2879 * you need to do so manually after calling.
2881 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2882 __releases(rq1->lock)
2883 __releases(rq2->lock)
2885 spin_unlock(&rq1->lock);
2887 spin_unlock(&rq2->lock);
2889 __release(rq2->lock);
2893 * If dest_cpu is allowed for this process, migrate the task to it.
2894 * This is accomplished by forcing the cpu_allowed mask to only
2895 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2896 * the cpu_allowed mask is restored.
2898 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2900 struct migration_req req;
2901 unsigned long flags;
2904 rq = task_rq_lock(p, &flags);
2905 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed)
2906 || unlikely(!cpu_active(dest_cpu)))
2909 /* force the process onto the specified CPU */
2910 if (migrate_task(p, dest_cpu, &req)) {
2911 /* Need to wait for migration thread (might exit: take ref). */
2912 struct task_struct *mt = rq->migration_thread;
2914 get_task_struct(mt);
2915 task_rq_unlock(rq, &flags);
2916 wake_up_process(mt);
2917 put_task_struct(mt);
2918 wait_for_completion(&req.done);
2923 task_rq_unlock(rq, &flags);
2927 * sched_exec - execve() is a valuable balancing opportunity, because at
2928 * this point the task has the smallest effective memory and cache footprint.
2930 void sched_exec(void)
2932 int new_cpu, this_cpu = get_cpu();
2933 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2935 if (new_cpu != this_cpu)
2936 sched_migrate_task(current, new_cpu);
2940 * pull_task - move a task from a remote runqueue to the local runqueue.
2941 * Both runqueues must be locked.
2943 static void pull_task(struct rq *src_rq, struct task_struct *p,
2944 struct rq *this_rq, int this_cpu)
2946 deactivate_task(src_rq, p, 0);
2947 set_task_cpu(p, this_cpu);
2948 activate_task(this_rq, p, 0);
2950 * Note that idle threads have a prio of MAX_PRIO, for this test
2951 * to be always true for them.
2953 check_preempt_curr(this_rq, p, 0);
2957 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2960 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2961 struct sched_domain *sd, enum cpu_idle_type idle,
2965 * We do not migrate tasks that are:
2966 * 1) running (obviously), or
2967 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2968 * 3) are cache-hot on their current CPU.
2970 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
2971 schedstat_inc(p, se.nr_failed_migrations_affine);
2976 if (task_running(rq, p)) {
2977 schedstat_inc(p, se.nr_failed_migrations_running);
2982 * Aggressive migration if:
2983 * 1) task is cache cold, or
2984 * 2) too many balance attempts have failed.
2987 if (!task_hot(p, rq->clock, sd) ||
2988 sd->nr_balance_failed > sd->cache_nice_tries) {
2989 #ifdef CONFIG_SCHEDSTATS
2990 if (task_hot(p, rq->clock, sd)) {
2991 schedstat_inc(sd, lb_hot_gained[idle]);
2992 schedstat_inc(p, se.nr_forced_migrations);
2998 if (task_hot(p, rq->clock, sd)) {
2999 schedstat_inc(p, se.nr_failed_migrations_hot);
3005 static unsigned long
3006 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3007 unsigned long max_load_move, struct sched_domain *sd,
3008 enum cpu_idle_type idle, int *all_pinned,
3009 int *this_best_prio, struct rq_iterator *iterator)
3011 int loops = 0, pulled = 0, pinned = 0;
3012 struct task_struct *p;
3013 long rem_load_move = max_load_move;
3015 if (max_load_move == 0)
3021 * Start the load-balancing iterator:
3023 p = iterator->start(iterator->arg);
3025 if (!p || loops++ > sysctl_sched_nr_migrate)
3028 if ((p->se.load.weight >> 1) > rem_load_move ||
3029 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3030 p = iterator->next(iterator->arg);
3034 pull_task(busiest, p, this_rq, this_cpu);
3036 rem_load_move -= p->se.load.weight;
3038 #ifdef CONFIG_PREEMPT
3040 * NEWIDLE balancing is a source of latency, so preemptible kernels
3041 * will stop after the first task is pulled to minimize the critical
3044 if (idle == CPU_NEWLY_IDLE)
3049 * We only want to steal up to the prescribed amount of weighted load.
3051 if (rem_load_move > 0) {
3052 if (p->prio < *this_best_prio)
3053 *this_best_prio = p->prio;
3054 p = iterator->next(iterator->arg);
3059 * Right now, this is one of only two places pull_task() is called,
3060 * so we can safely collect pull_task() stats here rather than
3061 * inside pull_task().
3063 schedstat_add(sd, lb_gained[idle], pulled);
3066 *all_pinned = pinned;
3068 return max_load_move - rem_load_move;
3072 * move_tasks tries to move up to max_load_move weighted load from busiest to
3073 * this_rq, as part of a balancing operation within domain "sd".
3074 * Returns 1 if successful and 0 otherwise.
3076 * Called with both runqueues locked.
3078 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3079 unsigned long max_load_move,
3080 struct sched_domain *sd, enum cpu_idle_type idle,
3083 const struct sched_class *class = sched_class_highest;
3084 unsigned long total_load_moved = 0;
3085 int this_best_prio = this_rq->curr->prio;
3089 class->load_balance(this_rq, this_cpu, busiest,
3090 max_load_move - total_load_moved,
3091 sd, idle, all_pinned, &this_best_prio);
3092 class = class->next;
3094 #ifdef CONFIG_PREEMPT
3096 * NEWIDLE balancing is a source of latency, so preemptible
3097 * kernels will stop after the first task is pulled to minimize
3098 * the critical section.
3100 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3103 } while (class && max_load_move > total_load_moved);
3105 return total_load_moved > 0;
3109 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3110 struct sched_domain *sd, enum cpu_idle_type idle,
3111 struct rq_iterator *iterator)
3113 struct task_struct *p = iterator->start(iterator->arg);
3117 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3118 pull_task(busiest, p, this_rq, this_cpu);
3120 * Right now, this is only the second place pull_task()
3121 * is called, so we can safely collect pull_task()
3122 * stats here rather than inside pull_task().
3124 schedstat_inc(sd, lb_gained[idle]);
3128 p = iterator->next(iterator->arg);
3135 * move_one_task tries to move exactly one task from busiest to this_rq, as
3136 * part of active balancing operations within "domain".
3137 * Returns 1 if successful and 0 otherwise.
3139 * Called with both runqueues locked.
3141 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3142 struct sched_domain *sd, enum cpu_idle_type idle)
3144 const struct sched_class *class;
3146 for (class = sched_class_highest; class; class = class->next)
3147 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3154 * find_busiest_group finds and returns the busiest CPU group within the
3155 * domain. It calculates and returns the amount of weighted load which
3156 * should be moved to restore balance via the imbalance parameter.
3158 static struct sched_group *
3159 find_busiest_group(struct sched_domain *sd, int this_cpu,
3160 unsigned long *imbalance, enum cpu_idle_type idle,
3161 int *sd_idle, const struct cpumask *cpus, int *balance)
3163 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3164 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3165 unsigned long max_pull;
3166 unsigned long busiest_load_per_task, busiest_nr_running;
3167 unsigned long this_load_per_task, this_nr_running;
3168 int load_idx, group_imb = 0;
3169 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3170 int power_savings_balance = 1;
3171 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3172 unsigned long min_nr_running = ULONG_MAX;
3173 struct sched_group *group_min = NULL, *group_leader = NULL;
3176 max_load = this_load = total_load = total_pwr = 0;
3177 busiest_load_per_task = busiest_nr_running = 0;
3178 this_load_per_task = this_nr_running = 0;
3180 if (idle == CPU_NOT_IDLE)
3181 load_idx = sd->busy_idx;
3182 else if (idle == CPU_NEWLY_IDLE)
3183 load_idx = sd->newidle_idx;
3185 load_idx = sd->idle_idx;
3188 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3191 int __group_imb = 0;
3192 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3193 unsigned long sum_nr_running, sum_weighted_load;
3194 unsigned long sum_avg_load_per_task;
3195 unsigned long avg_load_per_task;
3197 local_group = cpumask_test_cpu(this_cpu,
3198 sched_group_cpus(group));
3201 balance_cpu = cpumask_first(sched_group_cpus(group));
3203 /* Tally up the load of all CPUs in the group */
3204 sum_weighted_load = sum_nr_running = avg_load = 0;
3205 sum_avg_load_per_task = avg_load_per_task = 0;
3208 min_cpu_load = ~0UL;
3210 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
3211 struct rq *rq = cpu_rq(i);
3213 if (*sd_idle && rq->nr_running)
3216 /* Bias balancing toward cpus of our domain */
3218 if (idle_cpu(i) && !first_idle_cpu) {
3223 load = target_load(i, load_idx);
3225 load = source_load(i, load_idx);
3226 if (load > max_cpu_load)
3227 max_cpu_load = load;
3228 if (min_cpu_load > load)
3229 min_cpu_load = load;
3233 sum_nr_running += rq->nr_running;
3234 sum_weighted_load += weighted_cpuload(i);
3236 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3240 * First idle cpu or the first cpu(busiest) in this sched group
3241 * is eligible for doing load balancing at this and above
3242 * domains. In the newly idle case, we will allow all the cpu's
3243 * to do the newly idle load balance.
3245 if (idle != CPU_NEWLY_IDLE && local_group &&
3246 balance_cpu != this_cpu && balance) {
3251 total_load += avg_load;
3252 total_pwr += group->__cpu_power;
3254 /* Adjust by relative CPU power of the group */
3255 avg_load = sg_div_cpu_power(group,
3256 avg_load * SCHED_LOAD_SCALE);
3260 * Consider the group unbalanced when the imbalance is larger
3261 * than the average weight of two tasks.
3263 * APZ: with cgroup the avg task weight can vary wildly and
3264 * might not be a suitable number - should we keep a
3265 * normalized nr_running number somewhere that negates
3268 avg_load_per_task = sg_div_cpu_power(group,
3269 sum_avg_load_per_task * SCHED_LOAD_SCALE);
3271 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3274 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3277 this_load = avg_load;
3279 this_nr_running = sum_nr_running;
3280 this_load_per_task = sum_weighted_load;
3281 } else if (avg_load > max_load &&
3282 (sum_nr_running > group_capacity || __group_imb)) {
3283 max_load = avg_load;
3285 busiest_nr_running = sum_nr_running;
3286 busiest_load_per_task = sum_weighted_load;
3287 group_imb = __group_imb;
3290 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3292 * Busy processors will not participate in power savings
3295 if (idle == CPU_NOT_IDLE ||
3296 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3300 * If the local group is idle or completely loaded
3301 * no need to do power savings balance at this domain
3303 if (local_group && (this_nr_running >= group_capacity ||
3305 power_savings_balance = 0;
3308 * If a group is already running at full capacity or idle,
3309 * don't include that group in power savings calculations
3311 if (!power_savings_balance || sum_nr_running >= group_capacity
3316 * Calculate the group which has the least non-idle load.
3317 * This is the group from where we need to pick up the load
3320 if ((sum_nr_running < min_nr_running) ||
3321 (sum_nr_running == min_nr_running &&
3322 cpumask_first(sched_group_cpus(group)) >
3323 cpumask_first(sched_group_cpus(group_min)))) {
3325 min_nr_running = sum_nr_running;
3326 min_load_per_task = sum_weighted_load /
3331 * Calculate the group which is almost near its
3332 * capacity but still has some space to pick up some load
3333 * from other group and save more power
3335 if (sum_nr_running <= group_capacity - 1) {
3336 if (sum_nr_running > leader_nr_running ||
3337 (sum_nr_running == leader_nr_running &&
3338 cpumask_first(sched_group_cpus(group)) <
3339 cpumask_first(sched_group_cpus(group_leader)))) {
3340 group_leader = group;
3341 leader_nr_running = sum_nr_running;
3346 group = group->next;
3347 } while (group != sd->groups);
3349 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3352 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3354 if (this_load >= avg_load ||
3355 100*max_load <= sd->imbalance_pct*this_load)
3358 busiest_load_per_task /= busiest_nr_running;
3360 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3363 * We're trying to get all the cpus to the average_load, so we don't
3364 * want to push ourselves above the average load, nor do we wish to
3365 * reduce the max loaded cpu below the average load, as either of these
3366 * actions would just result in more rebalancing later, and ping-pong
3367 * tasks around. Thus we look for the minimum possible imbalance.
3368 * Negative imbalances (*we* are more loaded than anyone else) will
3369 * be counted as no imbalance for these purposes -- we can't fix that
3370 * by pulling tasks to us. Be careful of negative numbers as they'll
3371 * appear as very large values with unsigned longs.
3373 if (max_load <= busiest_load_per_task)
3377 * In the presence of smp nice balancing, certain scenarios can have
3378 * max load less than avg load(as we skip the groups at or below
3379 * its cpu_power, while calculating max_load..)
3381 if (max_load < avg_load) {
3383 goto small_imbalance;
3386 /* Don't want to pull so many tasks that a group would go idle */
3387 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3389 /* How much load to actually move to equalise the imbalance */
3390 *imbalance = min(max_pull * busiest->__cpu_power,
3391 (avg_load - this_load) * this->__cpu_power)
3395 * if *imbalance is less than the average load per runnable task
3396 * there is no gaurantee that any tasks will be moved so we'll have
3397 * a think about bumping its value to force at least one task to be
3400 if (*imbalance < busiest_load_per_task) {
3401 unsigned long tmp, pwr_now, pwr_move;
3405 pwr_move = pwr_now = 0;
3407 if (this_nr_running) {
3408 this_load_per_task /= this_nr_running;
3409 if (busiest_load_per_task > this_load_per_task)
3412 this_load_per_task = cpu_avg_load_per_task(this_cpu);
3414 if (max_load - this_load + busiest_load_per_task >=
3415 busiest_load_per_task * imbn) {
3416 *imbalance = busiest_load_per_task;
3421 * OK, we don't have enough imbalance to justify moving tasks,
3422 * however we may be able to increase total CPU power used by
3426 pwr_now += busiest->__cpu_power *
3427 min(busiest_load_per_task, max_load);
3428 pwr_now += this->__cpu_power *
3429 min(this_load_per_task, this_load);
3430 pwr_now /= SCHED_LOAD_SCALE;
3432 /* Amount of load we'd subtract */
3433 tmp = sg_div_cpu_power(busiest,
3434 busiest_load_per_task * SCHED_LOAD_SCALE);
3436 pwr_move += busiest->__cpu_power *
3437 min(busiest_load_per_task, max_load - tmp);
3439 /* Amount of load we'd add */
3440 if (max_load * busiest->__cpu_power <
3441 busiest_load_per_task * SCHED_LOAD_SCALE)
3442 tmp = sg_div_cpu_power(this,
3443 max_load * busiest->__cpu_power);
3445 tmp = sg_div_cpu_power(this,
3446 busiest_load_per_task * SCHED_LOAD_SCALE);
3447 pwr_move += this->__cpu_power *
3448 min(this_load_per_task, this_load + tmp);
3449 pwr_move /= SCHED_LOAD_SCALE;
3451 /* Move if we gain throughput */
3452 if (pwr_move > pwr_now)
3453 *imbalance = busiest_load_per_task;
3459 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3460 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3463 if (this == group_leader && group_leader != group_min) {
3464 *imbalance = min_load_per_task;
3465 if (sched_mc_power_savings >= POWERSAVINGS_BALANCE_WAKEUP) {
3466 cpu_rq(this_cpu)->rd->sched_mc_preferred_wakeup_cpu =
3467 cpumask_first(sched_group_cpus(group_leader));
3478 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3481 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3482 unsigned long imbalance, const struct cpumask *cpus)
3484 struct rq *busiest = NULL, *rq;
3485 unsigned long max_load = 0;
3488 for_each_cpu(i, sched_group_cpus(group)) {
3491 if (!cpumask_test_cpu(i, cpus))
3495 wl = weighted_cpuload(i);
3497 if (rq->nr_running == 1 && wl > imbalance)
3500 if (wl > max_load) {
3510 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3511 * so long as it is large enough.
3513 #define MAX_PINNED_INTERVAL 512
3516 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3517 * tasks if there is an imbalance.
3519 static int load_balance(int this_cpu, struct rq *this_rq,
3520 struct sched_domain *sd, enum cpu_idle_type idle,
3521 int *balance, struct cpumask *cpus)
3523 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3524 struct sched_group *group;
3525 unsigned long imbalance;
3527 unsigned long flags;
3529 cpumask_setall(cpus);
3532 * When power savings policy is enabled for the parent domain, idle
3533 * sibling can pick up load irrespective of busy siblings. In this case,
3534 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3535 * portraying it as CPU_NOT_IDLE.
3537 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3538 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3541 schedstat_inc(sd, lb_count[idle]);
3545 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3552 schedstat_inc(sd, lb_nobusyg[idle]);
3556 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3558 schedstat_inc(sd, lb_nobusyq[idle]);
3562 BUG_ON(busiest == this_rq);
3564 schedstat_add(sd, lb_imbalance[idle], imbalance);
3567 if (busiest->nr_running > 1) {
3569 * Attempt to move tasks. If find_busiest_group has found
3570 * an imbalance but busiest->nr_running <= 1, the group is
3571 * still unbalanced. ld_moved simply stays zero, so it is
3572 * correctly treated as an imbalance.
3574 local_irq_save(flags);
3575 double_rq_lock(this_rq, busiest);
3576 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3577 imbalance, sd, idle, &all_pinned);
3578 double_rq_unlock(this_rq, busiest);
3579 local_irq_restore(flags);
3582 * some other cpu did the load balance for us.
3584 if (ld_moved && this_cpu != smp_processor_id())
3585 resched_cpu(this_cpu);
3587 /* All tasks on this runqueue were pinned by CPU affinity */
3588 if (unlikely(all_pinned)) {
3589 cpumask_clear_cpu(cpu_of(busiest), cpus);
3590 if (!cpumask_empty(cpus))
3597 schedstat_inc(sd, lb_failed[idle]);
3598 sd->nr_balance_failed++;
3600 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3602 spin_lock_irqsave(&busiest->lock, flags);
3604 /* don't kick the migration_thread, if the curr
3605 * task on busiest cpu can't be moved to this_cpu
3607 if (!cpumask_test_cpu(this_cpu,
3608 &busiest->curr->cpus_allowed)) {
3609 spin_unlock_irqrestore(&busiest->lock, flags);
3611 goto out_one_pinned;
3614 if (!busiest->active_balance) {
3615 busiest->active_balance = 1;
3616 busiest->push_cpu = this_cpu;
3619 spin_unlock_irqrestore(&busiest->lock, flags);
3621 wake_up_process(busiest->migration_thread);
3624 * We've kicked active balancing, reset the failure
3627 sd->nr_balance_failed = sd->cache_nice_tries+1;
3630 sd->nr_balance_failed = 0;
3632 if (likely(!active_balance)) {
3633 /* We were unbalanced, so reset the balancing interval */
3634 sd->balance_interval = sd->min_interval;
3637 * If we've begun active balancing, start to back off. This
3638 * case may not be covered by the all_pinned logic if there
3639 * is only 1 task on the busy runqueue (because we don't call
3642 if (sd->balance_interval < sd->max_interval)
3643 sd->balance_interval *= 2;
3646 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3647 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3653 schedstat_inc(sd, lb_balanced[idle]);
3655 sd->nr_balance_failed = 0;
3658 /* tune up the balancing interval */
3659 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3660 (sd->balance_interval < sd->max_interval))
3661 sd->balance_interval *= 2;
3663 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3664 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3675 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3676 * tasks if there is an imbalance.
3678 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3679 * this_rq is locked.
3682 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3683 struct cpumask *cpus)
3685 struct sched_group *group;
3686 struct rq *busiest = NULL;
3687 unsigned long imbalance;
3692 cpumask_setall(cpus);
3695 * When power savings policy is enabled for the parent domain, idle
3696 * sibling can pick up load irrespective of busy siblings. In this case,
3697 * let the state of idle sibling percolate up as IDLE, instead of
3698 * portraying it as CPU_NOT_IDLE.
3700 if (sd->flags & SD_SHARE_CPUPOWER &&
3701 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3704 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3706 update_shares_locked(this_rq, sd);
3707 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3708 &sd_idle, cpus, NULL);
3710 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3714 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3716 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3720 BUG_ON(busiest == this_rq);
3722 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3725 if (busiest->nr_running > 1) {
3726 /* Attempt to move tasks */
3727 double_lock_balance(this_rq, busiest);
3728 /* this_rq->clock is already updated */
3729 update_rq_clock(busiest);
3730 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3731 imbalance, sd, CPU_NEWLY_IDLE,
3733 double_unlock_balance(this_rq, busiest);
3735 if (unlikely(all_pinned)) {
3736 cpumask_clear_cpu(cpu_of(busiest), cpus);
3737 if (!cpumask_empty(cpus))
3743 int active_balance = 0;
3745 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3746 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3747 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3750 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
3753 if (sd->nr_balance_failed++ < 2)
3757 * The only task running in a non-idle cpu can be moved to this
3758 * cpu in an attempt to completely freeup the other CPU
3759 * package. The same method used to move task in load_balance()
3760 * have been extended for load_balance_newidle() to speedup
3761 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
3763 * The package power saving logic comes from
3764 * find_busiest_group(). If there are no imbalance, then
3765 * f_b_g() will return NULL. However when sched_mc={1,2} then
3766 * f_b_g() will select a group from which a running task may be
3767 * pulled to this cpu in order to make the other package idle.
3768 * If there is no opportunity to make a package idle and if
3769 * there are no imbalance, then f_b_g() will return NULL and no
3770 * action will be taken in load_balance_newidle().
3772 * Under normal task pull operation due to imbalance, there
3773 * will be more than one task in the source run queue and
3774 * move_tasks() will succeed. ld_moved will be true and this
3775 * active balance code will not be triggered.
3778 /* Lock busiest in correct order while this_rq is held */
3779 double_lock_balance(this_rq, busiest);
3782 * don't kick the migration_thread, if the curr
3783 * task on busiest cpu can't be moved to this_cpu
3785 if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
3786 double_unlock_balance(this_rq, busiest);
3791 if (!busiest->active_balance) {
3792 busiest->active_balance = 1;
3793 busiest->push_cpu = this_cpu;
3797 double_unlock_balance(this_rq, busiest);
3799 * Should not call ttwu while holding a rq->lock
3801 spin_unlock(&this_rq->lock);
3803 wake_up_process(busiest->migration_thread);
3804 spin_lock(&this_rq->lock);
3807 sd->nr_balance_failed = 0;
3809 update_shares_locked(this_rq, sd);
3813 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3814 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3815 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3817 sd->nr_balance_failed = 0;
3823 * idle_balance is called by schedule() if this_cpu is about to become
3824 * idle. Attempts to pull tasks from other CPUs.
3826 static void idle_balance(int this_cpu, struct rq *this_rq)
3828 struct sched_domain *sd;
3829 int pulled_task = 0;
3830 unsigned long next_balance = jiffies + HZ;
3831 cpumask_var_t tmpmask;
3833 if (!alloc_cpumask_var(&tmpmask, GFP_ATOMIC))
3836 for_each_domain(this_cpu, sd) {
3837 unsigned long interval;
3839 if (!(sd->flags & SD_LOAD_BALANCE))
3842 if (sd->flags & SD_BALANCE_NEWIDLE)
3843 /* If we've pulled tasks over stop searching: */
3844 pulled_task = load_balance_newidle(this_cpu, this_rq,
3847 interval = msecs_to_jiffies(sd->balance_interval);
3848 if (time_after(next_balance, sd->last_balance + interval))
3849 next_balance = sd->last_balance + interval;
3853 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3855 * We are going idle. next_balance may be set based on
3856 * a busy processor. So reset next_balance.
3858 this_rq->next_balance = next_balance;
3860 free_cpumask_var(tmpmask);
3864 * active_load_balance is run by migration threads. It pushes running tasks
3865 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3866 * running on each physical CPU where possible, and avoids physical /
3867 * logical imbalances.
3869 * Called with busiest_rq locked.
3871 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3873 int target_cpu = busiest_rq->push_cpu;
3874 struct sched_domain *sd;
3875 struct rq *target_rq;
3877 /* Is there any task to move? */
3878 if (busiest_rq->nr_running <= 1)
3881 target_rq = cpu_rq(target_cpu);
3884 * This condition is "impossible", if it occurs
3885 * we need to fix it. Originally reported by
3886 * Bjorn Helgaas on a 128-cpu setup.
3888 BUG_ON(busiest_rq == target_rq);
3890 /* move a task from busiest_rq to target_rq */
3891 double_lock_balance(busiest_rq, target_rq);
3892 update_rq_clock(busiest_rq);
3893 update_rq_clock(target_rq);
3895 /* Search for an sd spanning us and the target CPU. */
3896 for_each_domain(target_cpu, sd) {
3897 if ((sd->flags & SD_LOAD_BALANCE) &&
3898 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
3903 schedstat_inc(sd, alb_count);
3905 if (move_one_task(target_rq, target_cpu, busiest_rq,
3907 schedstat_inc(sd, alb_pushed);
3909 schedstat_inc(sd, alb_failed);
3911 double_unlock_balance(busiest_rq, target_rq);
3916 atomic_t load_balancer;
3917 cpumask_var_t cpu_mask;
3918 } nohz ____cacheline_aligned = {
3919 .load_balancer = ATOMIC_INIT(-1),
3923 * This routine will try to nominate the ilb (idle load balancing)
3924 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3925 * load balancing on behalf of all those cpus. If all the cpus in the system
3926 * go into this tickless mode, then there will be no ilb owner (as there is
3927 * no need for one) and all the cpus will sleep till the next wakeup event
3930 * For the ilb owner, tick is not stopped. And this tick will be used
3931 * for idle load balancing. ilb owner will still be part of
3934 * While stopping the tick, this cpu will become the ilb owner if there
3935 * is no other owner. And will be the owner till that cpu becomes busy
3936 * or if all cpus in the system stop their ticks at which point
3937 * there is no need for ilb owner.
3939 * When the ilb owner becomes busy, it nominates another owner, during the
3940 * next busy scheduler_tick()
3942 int select_nohz_load_balancer(int stop_tick)
3944 int cpu = smp_processor_id();
3947 cpumask_set_cpu(cpu, nohz.cpu_mask);
3948 cpu_rq(cpu)->in_nohz_recently = 1;
3951 * If we are going offline and still the leader, give up!
3953 if (!cpu_active(cpu) &&
3954 atomic_read(&nohz.load_balancer) == cpu) {
3955 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3960 /* time for ilb owner also to sleep */
3961 if (cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
3962 if (atomic_read(&nohz.load_balancer) == cpu)
3963 atomic_set(&nohz.load_balancer, -1);
3967 if (atomic_read(&nohz.load_balancer) == -1) {
3968 /* make me the ilb owner */
3969 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3971 } else if (atomic_read(&nohz.load_balancer) == cpu)
3974 if (!cpumask_test_cpu(cpu, nohz.cpu_mask))
3977 cpumask_clear_cpu(cpu, nohz.cpu_mask);
3979 if (atomic_read(&nohz.load_balancer) == cpu)
3980 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3987 static DEFINE_SPINLOCK(balancing);
3990 * It checks each scheduling domain to see if it is due to be balanced,
3991 * and initiates a balancing operation if so.
3993 * Balancing parameters are set up in arch_init_sched_domains.
3995 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3998 struct rq *rq = cpu_rq(cpu);
3999 unsigned long interval;
4000 struct sched_domain *sd;
4001 /* Earliest time when we have to do rebalance again */
4002 unsigned long next_balance = jiffies + 60*HZ;
4003 int update_next_balance = 0;
4007 /* Fails alloc? Rebalancing probably not a priority right now. */
4008 if (!alloc_cpumask_var(&tmp, GFP_ATOMIC))
4011 for_each_domain(cpu, sd) {
4012 if (!(sd->flags & SD_LOAD_BALANCE))
4015 interval = sd->balance_interval;
4016 if (idle != CPU_IDLE)
4017 interval *= sd->busy_factor;
4019 /* scale ms to jiffies */
4020 interval = msecs_to_jiffies(interval);
4021 if (unlikely(!interval))
4023 if (interval > HZ*NR_CPUS/10)
4024 interval = HZ*NR_CPUS/10;
4026 need_serialize = sd->flags & SD_SERIALIZE;
4028 if (need_serialize) {
4029 if (!spin_trylock(&balancing))
4033 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4034 if (load_balance(cpu, rq, sd, idle, &balance, tmp)) {
4036 * We've pulled tasks over so either we're no
4037 * longer idle, or one of our SMT siblings is
4040 idle = CPU_NOT_IDLE;
4042 sd->last_balance = jiffies;
4045 spin_unlock(&balancing);
4047 if (time_after(next_balance, sd->last_balance + interval)) {
4048 next_balance = sd->last_balance + interval;
4049 update_next_balance = 1;
4053 * Stop the load balance at this level. There is another
4054 * CPU in our sched group which is doing load balancing more
4062 * next_balance will be updated only when there is a need.
4063 * When the cpu is attached to null domain for ex, it will not be
4066 if (likely(update_next_balance))
4067 rq->next_balance = next_balance;
4069 free_cpumask_var(tmp);
4073 * run_rebalance_domains is triggered when needed from the scheduler tick.
4074 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4075 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4077 static void run_rebalance_domains(struct softirq_action *h)
4079 int this_cpu = smp_processor_id();
4080 struct rq *this_rq = cpu_rq(this_cpu);
4081 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4082 CPU_IDLE : CPU_NOT_IDLE;
4084 rebalance_domains(this_cpu, idle);
4088 * If this cpu is the owner for idle load balancing, then do the
4089 * balancing on behalf of the other idle cpus whose ticks are
4092 if (this_rq->idle_at_tick &&
4093 atomic_read(&nohz.load_balancer) == this_cpu) {
4097 for_each_cpu(balance_cpu, nohz.cpu_mask) {
4098 if (balance_cpu == this_cpu)
4102 * If this cpu gets work to do, stop the load balancing
4103 * work being done for other cpus. Next load
4104 * balancing owner will pick it up.
4109 rebalance_domains(balance_cpu, CPU_IDLE);
4111 rq = cpu_rq(balance_cpu);
4112 if (time_after(this_rq->next_balance, rq->next_balance))
4113 this_rq->next_balance = rq->next_balance;
4120 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4122 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4123 * idle load balancing owner or decide to stop the periodic load balancing,
4124 * if the whole system is idle.
4126 static inline void trigger_load_balance(struct rq *rq, int cpu)
4130 * If we were in the nohz mode recently and busy at the current
4131 * scheduler tick, then check if we need to nominate new idle
4134 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4135 rq->in_nohz_recently = 0;
4137 if (atomic_read(&nohz.load_balancer) == cpu) {
4138 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4139 atomic_set(&nohz.load_balancer, -1);
4142 if (atomic_read(&nohz.load_balancer) == -1) {
4144 * simple selection for now: Nominate the
4145 * first cpu in the nohz list to be the next
4148 * TBD: Traverse the sched domains and nominate
4149 * the nearest cpu in the nohz.cpu_mask.
4151 int ilb = cpumask_first(nohz.cpu_mask);
4153 if (ilb < nr_cpu_ids)
4159 * If this cpu is idle and doing idle load balancing for all the
4160 * cpus with ticks stopped, is it time for that to stop?
4162 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4163 cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4169 * If this cpu is idle and the idle load balancing is done by
4170 * someone else, then no need raise the SCHED_SOFTIRQ
4172 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4173 cpumask_test_cpu(cpu, nohz.cpu_mask))
4176 if (time_after_eq(jiffies, rq->next_balance))
4177 raise_softirq(SCHED_SOFTIRQ);
4180 #else /* CONFIG_SMP */
4183 * on UP we do not need to balance between CPUs:
4185 static inline void idle_balance(int cpu, struct rq *rq)
4191 DEFINE_PER_CPU(struct kernel_stat, kstat);
4193 EXPORT_PER_CPU_SYMBOL(kstat);
4196 * Return any ns on the sched_clock that have not yet been banked in
4197 * @p in case that task is currently running.
4199 unsigned long long task_delta_exec(struct task_struct *p)
4201 unsigned long flags;
4205 rq = task_rq_lock(p, &flags);
4207 if (task_current(rq, p)) {
4210 update_rq_clock(rq);
4211 delta_exec = rq->clock - p->se.exec_start;
4212 if ((s64)delta_exec > 0)
4216 task_rq_unlock(rq, &flags);
4222 * Account user cpu time to a process.
4223 * @p: the process that the cpu time gets accounted to
4224 * @cputime: the cpu time spent in user space since the last update
4225 * @cputime_scaled: cputime scaled by cpu frequency
4227 void account_user_time(struct task_struct *p, cputime_t cputime,
4228 cputime_t cputime_scaled)
4230 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4233 /* Add user time to process. */
4234 p->utime = cputime_add(p->utime, cputime);
4235 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4236 account_group_user_time(p, cputime);
4238 /* Add user time to cpustat. */
4239 tmp = cputime_to_cputime64(cputime);
4240 if (TASK_NICE(p) > 0)
4241 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4243 cpustat->user = cputime64_add(cpustat->user, tmp);
4244 /* Account for user time used */
4245 acct_update_integrals(p);
4249 * Account guest cpu time to a process.
4250 * @p: the process that the cpu time gets accounted to
4251 * @cputime: the cpu time spent in virtual machine since the last update
4252 * @cputime_scaled: cputime scaled by cpu frequency
4254 static void account_guest_time(struct task_struct *p, cputime_t cputime,
4255 cputime_t cputime_scaled)
4258 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4260 tmp = cputime_to_cputime64(cputime);
4262 /* Add guest time to process. */
4263 p->utime = cputime_add(p->utime, cputime);
4264 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4265 account_group_user_time(p, cputime);
4266 p->gtime = cputime_add(p->gtime, cputime);
4268 /* Add guest time to cpustat. */
4269 cpustat->user = cputime64_add(cpustat->user, tmp);
4270 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4274 * Account system cpu time to a process.
4275 * @p: the process that the cpu time gets accounted to
4276 * @hardirq_offset: the offset to subtract from hardirq_count()
4277 * @cputime: the cpu time spent in kernel space since the last update
4278 * @cputime_scaled: cputime scaled by cpu frequency
4280 void account_system_time(struct task_struct *p, int hardirq_offset,
4281 cputime_t cputime, cputime_t cputime_scaled)
4283 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4286 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4287 account_guest_time(p, cputime, cputime_scaled);
4291 /* Add system time to process. */
4292 p->stime = cputime_add(p->stime, cputime);
4293 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
4294 account_group_system_time(p, cputime);
4296 /* Add system time to cpustat. */
4297 tmp = cputime_to_cputime64(cputime);
4298 if (hardirq_count() - hardirq_offset)
4299 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4300 else if (softirq_count())
4301 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4303 cpustat->system = cputime64_add(cpustat->system, tmp);
4305 /* Account for system time used */
4306 acct_update_integrals(p);
4310 * Account for involuntary wait time.
4311 * @steal: the cpu time spent in involuntary wait
4313 void account_steal_time(cputime_t cputime)
4315 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4316 cputime64_t cputime64 = cputime_to_cputime64(cputime);
4318 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
4322 * Account for idle time.
4323 * @cputime: the cpu time spent in idle wait
4325 void account_idle_time(cputime_t cputime)
4327 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4328 cputime64_t cputime64 = cputime_to_cputime64(cputime);
4329 struct rq *rq = this_rq();
4331 if (atomic_read(&rq->nr_iowait) > 0)
4332 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
4334 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
4337 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
4340 * Account a single tick of cpu time.
4341 * @p: the process that the cpu time gets accounted to
4342 * @user_tick: indicates if the tick is a user or a system tick
4344 void account_process_tick(struct task_struct *p, int user_tick)
4346 cputime_t one_jiffy = jiffies_to_cputime(1);
4347 cputime_t one_jiffy_scaled = cputime_to_scaled(one_jiffy);
4348 struct rq *rq = this_rq();
4351 account_user_time(p, one_jiffy, one_jiffy_scaled);
4352 else if (p != rq->idle)
4353 account_system_time(p, HARDIRQ_OFFSET, one_jiffy,
4356 account_idle_time(one_jiffy);
4360 * Account multiple ticks of steal time.
4361 * @p: the process from which the cpu time has been stolen
4362 * @ticks: number of stolen ticks
4364 void account_steal_ticks(unsigned long ticks)
4366 account_steal_time(jiffies_to_cputime(ticks));
4370 * Account multiple ticks of idle time.
4371 * @ticks: number of stolen ticks
4373 void account_idle_ticks(unsigned long ticks)
4375 account_idle_time(jiffies_to_cputime(ticks));
4381 * Use precise platform statistics if available:
4383 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
4384 cputime_t task_utime(struct task_struct *p)
4389 cputime_t task_stime(struct task_struct *p)
4394 cputime_t task_utime(struct task_struct *p)
4396 clock_t utime = cputime_to_clock_t(p->utime),
4397 total = utime + cputime_to_clock_t(p->stime);
4401 * Use CFS's precise accounting:
4403 temp = (u64)nsec_to_clock_t(p->se.sum_exec_runtime);
4407 do_div(temp, total);
4409 utime = (clock_t)temp;
4411 p->prev_utime = max(p->prev_utime, clock_t_to_cputime(utime));
4412 return p->prev_utime;
4415 cputime_t task_stime(struct task_struct *p)
4420 * Use CFS's precise accounting. (we subtract utime from
4421 * the total, to make sure the total observed by userspace
4422 * grows monotonically - apps rely on that):
4424 stime = nsec_to_clock_t(p->se.sum_exec_runtime) -
4425 cputime_to_clock_t(task_utime(p));
4428 p->prev_stime = max(p->prev_stime, clock_t_to_cputime(stime));
4430 return p->prev_stime;
4434 inline cputime_t task_gtime(struct task_struct *p)
4440 * This function gets called by the timer code, with HZ frequency.
4441 * We call it with interrupts disabled.
4443 * It also gets called by the fork code, when changing the parent's
4446 void scheduler_tick(void)
4448 int cpu = smp_processor_id();
4449 struct rq *rq = cpu_rq(cpu);
4450 struct task_struct *curr = rq->curr;
4454 spin_lock(&rq->lock);
4455 update_rq_clock(rq);
4456 update_cpu_load(rq);
4457 curr->sched_class->task_tick(rq, curr, 0);
4458 spin_unlock(&rq->lock);
4461 rq->idle_at_tick = idle_cpu(cpu);
4462 trigger_load_balance(rq, cpu);
4466 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4467 defined(CONFIG_PREEMPT_TRACER))
4469 static inline unsigned long get_parent_ip(unsigned long addr)
4471 if (in_lock_functions(addr)) {
4472 addr = CALLER_ADDR2;
4473 if (in_lock_functions(addr))
4474 addr = CALLER_ADDR3;
4479 void __kprobes add_preempt_count(int val)
4481 #ifdef CONFIG_DEBUG_PREEMPT
4485 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4488 preempt_count() += val;
4489 #ifdef CONFIG_DEBUG_PREEMPT
4491 * Spinlock count overflowing soon?
4493 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4496 if (preempt_count() == val)
4497 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4499 EXPORT_SYMBOL(add_preempt_count);
4501 void __kprobes sub_preempt_count(int val)
4503 #ifdef CONFIG_DEBUG_PREEMPT
4507 if (DEBUG_LOCKS_WARN_ON(val > preempt_count() - (!!kernel_locked())))
4510 * Is the spinlock portion underflowing?
4512 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4513 !(preempt_count() & PREEMPT_MASK)))
4517 if (preempt_count() == val)
4518 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4519 preempt_count() -= val;
4521 EXPORT_SYMBOL(sub_preempt_count);
4526 * Print scheduling while atomic bug:
4528 static noinline void __schedule_bug(struct task_struct *prev)
4530 struct pt_regs *regs = get_irq_regs();
4532 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4533 prev->comm, prev->pid, preempt_count());
4535 debug_show_held_locks(prev);
4537 if (irqs_disabled())
4538 print_irqtrace_events(prev);
4547 * Various schedule()-time debugging checks and statistics:
4549 static inline void schedule_debug(struct task_struct *prev)
4552 * Test if we are atomic. Since do_exit() needs to call into
4553 * schedule() atomically, we ignore that path for now.
4554 * Otherwise, whine if we are scheduling when we should not be.
4556 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
4557 __schedule_bug(prev);
4559 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4561 schedstat_inc(this_rq(), sched_count);
4562 #ifdef CONFIG_SCHEDSTATS
4563 if (unlikely(prev->lock_depth >= 0)) {
4564 schedstat_inc(this_rq(), bkl_count);
4565 schedstat_inc(prev, sched_info.bkl_count);
4571 * Pick up the highest-prio task:
4573 static inline struct task_struct *
4574 pick_next_task(struct rq *rq, struct task_struct *prev)
4576 const struct sched_class *class;
4577 struct task_struct *p;
4580 * Optimization: we know that if all tasks are in
4581 * the fair class we can call that function directly:
4583 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4584 p = fair_sched_class.pick_next_task(rq);
4589 class = sched_class_highest;
4591 p = class->pick_next_task(rq);
4595 * Will never be NULL as the idle class always
4596 * returns a non-NULL p:
4598 class = class->next;
4603 * schedule() is the main scheduler function.
4605 asmlinkage void __sched schedule(void)
4607 struct task_struct *prev, *next;
4608 unsigned long *switch_count;
4614 cpu = smp_processor_id();
4618 switch_count = &prev->nivcsw;
4620 release_kernel_lock(prev);
4621 need_resched_nonpreemptible:
4623 schedule_debug(prev);
4625 if (sched_feat(HRTICK))
4628 spin_lock_irq(&rq->lock);
4629 update_rq_clock(rq);
4630 clear_tsk_need_resched(prev);
4632 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4633 if (unlikely(signal_pending_state(prev->state, prev)))
4634 prev->state = TASK_RUNNING;
4636 deactivate_task(rq, prev, 1);
4637 switch_count = &prev->nvcsw;
4641 if (prev->sched_class->pre_schedule)
4642 prev->sched_class->pre_schedule(rq, prev);
4645 if (unlikely(!rq->nr_running))
4646 idle_balance(cpu, rq);
4648 prev->sched_class->put_prev_task(rq, prev);
4649 next = pick_next_task(rq, prev);
4651 if (likely(prev != next)) {
4652 sched_info_switch(prev, next);
4658 context_switch(rq, prev, next); /* unlocks the rq */
4660 * the context switch might have flipped the stack from under
4661 * us, hence refresh the local variables.
4663 cpu = smp_processor_id();
4666 spin_unlock_irq(&rq->lock);
4668 if (unlikely(reacquire_kernel_lock(current) < 0))
4669 goto need_resched_nonpreemptible;
4671 preempt_enable_no_resched();
4672 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4675 EXPORT_SYMBOL(schedule);
4677 #ifdef CONFIG_PREEMPT
4679 * this is the entry point to schedule() from in-kernel preemption
4680 * off of preempt_enable. Kernel preemptions off return from interrupt
4681 * occur there and call schedule directly.
4683 asmlinkage void __sched preempt_schedule(void)
4685 struct thread_info *ti = current_thread_info();
4688 * If there is a non-zero preempt_count or interrupts are disabled,
4689 * we do not want to preempt the current task. Just return..
4691 if (likely(ti->preempt_count || irqs_disabled()))
4695 add_preempt_count(PREEMPT_ACTIVE);
4697 sub_preempt_count(PREEMPT_ACTIVE);
4700 * Check again in case we missed a preemption opportunity
4701 * between schedule and now.
4704 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4706 EXPORT_SYMBOL(preempt_schedule);
4709 * this is the entry point to schedule() from kernel preemption
4710 * off of irq context.
4711 * Note, that this is called and return with irqs disabled. This will
4712 * protect us against recursive calling from irq.
4714 asmlinkage void __sched preempt_schedule_irq(void)
4716 struct thread_info *ti = current_thread_info();
4718 /* Catch callers which need to be fixed */
4719 BUG_ON(ti->preempt_count || !irqs_disabled());
4722 add_preempt_count(PREEMPT_ACTIVE);
4725 local_irq_disable();
4726 sub_preempt_count(PREEMPT_ACTIVE);
4729 * Check again in case we missed a preemption opportunity
4730 * between schedule and now.
4733 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4736 #endif /* CONFIG_PREEMPT */
4738 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4741 return try_to_wake_up(curr->private, mode, sync);
4743 EXPORT_SYMBOL(default_wake_function);
4746 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4747 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4748 * number) then we wake all the non-exclusive tasks and one exclusive task.
4750 * There are circumstances in which we can try to wake a task which has already
4751 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4752 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4754 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4755 int nr_exclusive, int sync, void *key)
4757 wait_queue_t *curr, *next;
4759 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4760 unsigned flags = curr->flags;
4762 if (curr->func(curr, mode, sync, key) &&
4763 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4769 * __wake_up - wake up threads blocked on a waitqueue.
4771 * @mode: which threads
4772 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4773 * @key: is directly passed to the wakeup function
4775 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4776 int nr_exclusive, void *key)
4778 unsigned long flags;
4780 spin_lock_irqsave(&q->lock, flags);
4781 __wake_up_common(q, mode, nr_exclusive, 0, key);
4782 spin_unlock_irqrestore(&q->lock, flags);
4784 EXPORT_SYMBOL(__wake_up);
4787 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4789 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4791 __wake_up_common(q, mode, 1, 0, NULL);
4795 * __wake_up_sync - wake up threads blocked on a waitqueue.
4797 * @mode: which threads
4798 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4800 * The sync wakeup differs that the waker knows that it will schedule
4801 * away soon, so while the target thread will be woken up, it will not
4802 * be migrated to another CPU - ie. the two threads are 'synchronized'
4803 * with each other. This can prevent needless bouncing between CPUs.
4805 * On UP it can prevent extra preemption.
4808 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4810 unsigned long flags;
4816 if (unlikely(!nr_exclusive))
4819 spin_lock_irqsave(&q->lock, flags);
4820 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4821 spin_unlock_irqrestore(&q->lock, flags);
4823 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4826 * complete: - signals a single thread waiting on this completion
4827 * @x: holds the state of this particular completion
4829 * This will wake up a single thread waiting on this completion. Threads will be
4830 * awakened in the same order in which they were queued.
4832 * See also complete_all(), wait_for_completion() and related routines.
4834 void complete(struct completion *x)
4836 unsigned long flags;
4838 spin_lock_irqsave(&x->wait.lock, flags);
4840 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4841 spin_unlock_irqrestore(&x->wait.lock, flags);
4843 EXPORT_SYMBOL(complete);
4846 * complete_all: - signals all threads waiting on this completion
4847 * @x: holds the state of this particular completion
4849 * This will wake up all threads waiting on this particular completion event.
4851 void complete_all(struct completion *x)
4853 unsigned long flags;
4855 spin_lock_irqsave(&x->wait.lock, flags);
4856 x->done += UINT_MAX/2;
4857 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4858 spin_unlock_irqrestore(&x->wait.lock, flags);
4860 EXPORT_SYMBOL(complete_all);
4862 static inline long __sched
4863 do_wait_for_common(struct completion *x, long timeout, int state)
4866 DECLARE_WAITQUEUE(wait, current);
4868 wait.flags |= WQ_FLAG_EXCLUSIVE;
4869 __add_wait_queue_tail(&x->wait, &wait);
4871 if (signal_pending_state(state, current)) {
4872 timeout = -ERESTARTSYS;
4875 __set_current_state(state);
4876 spin_unlock_irq(&x->wait.lock);
4877 timeout = schedule_timeout(timeout);
4878 spin_lock_irq(&x->wait.lock);
4879 } while (!x->done && timeout);
4880 __remove_wait_queue(&x->wait, &wait);
4885 return timeout ?: 1;
4889 wait_for_common(struct completion *x, long timeout, int state)
4893 spin_lock_irq(&x->wait.lock);
4894 timeout = do_wait_for_common(x, timeout, state);
4895 spin_unlock_irq(&x->wait.lock);
4900 * wait_for_completion: - waits for completion of a task
4901 * @x: holds the state of this particular completion
4903 * This waits to be signaled for completion of a specific task. It is NOT
4904 * interruptible and there is no timeout.
4906 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4907 * and interrupt capability. Also see complete().
4909 void __sched wait_for_completion(struct completion *x)
4911 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4913 EXPORT_SYMBOL(wait_for_completion);
4916 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4917 * @x: holds the state of this particular completion
4918 * @timeout: timeout value in jiffies
4920 * This waits for either a completion of a specific task to be signaled or for a
4921 * specified timeout to expire. The timeout is in jiffies. It is not
4924 unsigned long __sched
4925 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4927 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4929 EXPORT_SYMBOL(wait_for_completion_timeout);
4932 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4933 * @x: holds the state of this particular completion
4935 * This waits for completion of a specific task to be signaled. It is
4938 int __sched wait_for_completion_interruptible(struct completion *x)
4940 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4941 if (t == -ERESTARTSYS)
4945 EXPORT_SYMBOL(wait_for_completion_interruptible);
4948 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4949 * @x: holds the state of this particular completion
4950 * @timeout: timeout value in jiffies
4952 * This waits for either a completion of a specific task to be signaled or for a
4953 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4955 unsigned long __sched
4956 wait_for_completion_interruptible_timeout(struct completion *x,
4957 unsigned long timeout)
4959 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4961 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4964 * wait_for_completion_killable: - waits for completion of a task (killable)
4965 * @x: holds the state of this particular completion
4967 * This waits to be signaled for completion of a specific task. It can be
4968 * interrupted by a kill signal.
4970 int __sched wait_for_completion_killable(struct completion *x)
4972 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4973 if (t == -ERESTARTSYS)
4977 EXPORT_SYMBOL(wait_for_completion_killable);
4980 * try_wait_for_completion - try to decrement a completion without blocking
4981 * @x: completion structure
4983 * Returns: 0 if a decrement cannot be done without blocking
4984 * 1 if a decrement succeeded.
4986 * If a completion is being used as a counting completion,
4987 * attempt to decrement the counter without blocking. This
4988 * enables us to avoid waiting if the resource the completion
4989 * is protecting is not available.
4991 bool try_wait_for_completion(struct completion *x)
4995 spin_lock_irq(&x->wait.lock);
5000 spin_unlock_irq(&x->wait.lock);
5003 EXPORT_SYMBOL(try_wait_for_completion);
5006 * completion_done - Test to see if a completion has any waiters
5007 * @x: completion structure
5009 * Returns: 0 if there are waiters (wait_for_completion() in progress)
5010 * 1 if there are no waiters.
5013 bool completion_done(struct completion *x)
5017 spin_lock_irq(&x->wait.lock);
5020 spin_unlock_irq(&x->wait.lock);
5023 EXPORT_SYMBOL(completion_done);
5026 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
5028 unsigned long flags;
5031 init_waitqueue_entry(&wait, current);
5033 __set_current_state(state);
5035 spin_lock_irqsave(&q->lock, flags);
5036 __add_wait_queue(q, &wait);
5037 spin_unlock(&q->lock);
5038 timeout = schedule_timeout(timeout);
5039 spin_lock_irq(&q->lock);
5040 __remove_wait_queue(q, &wait);
5041 spin_unlock_irqrestore(&q->lock, flags);
5046 void __sched interruptible_sleep_on(wait_queue_head_t *q)
5048 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5050 EXPORT_SYMBOL(interruptible_sleep_on);
5053 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
5055 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
5057 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
5059 void __sched sleep_on(wait_queue_head_t *q)
5061 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5063 EXPORT_SYMBOL(sleep_on);
5065 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
5067 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5069 EXPORT_SYMBOL(sleep_on_timeout);
5071 #ifdef CONFIG_RT_MUTEXES
5074 * rt_mutex_setprio - set the current priority of a task
5076 * @prio: prio value (kernel-internal form)
5078 * This function changes the 'effective' priority of a task. It does
5079 * not touch ->normal_prio like __setscheduler().
5081 * Used by the rt_mutex code to implement priority inheritance logic.
5083 void rt_mutex_setprio(struct task_struct *p, int prio)
5085 unsigned long flags;
5086 int oldprio, on_rq, running;
5088 const struct sched_class *prev_class = p->sched_class;
5090 BUG_ON(prio < 0 || prio > MAX_PRIO);
5092 rq = task_rq_lock(p, &flags);
5093 update_rq_clock(rq);
5096 on_rq = p->se.on_rq;
5097 running = task_current(rq, p);
5099 dequeue_task(rq, p, 0);
5101 p->sched_class->put_prev_task(rq, p);
5104 p->sched_class = &rt_sched_class;
5106 p->sched_class = &fair_sched_class;
5111 p->sched_class->set_curr_task(rq);
5113 enqueue_task(rq, p, 0);
5115 check_class_changed(rq, p, prev_class, oldprio, running);
5117 task_rq_unlock(rq, &flags);
5122 void set_user_nice(struct task_struct *p, long nice)
5124 int old_prio, delta, on_rq;
5125 unsigned long flags;
5128 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
5131 * We have to be careful, if called from sys_setpriority(),
5132 * the task might be in the middle of scheduling on another CPU.
5134 rq = task_rq_lock(p, &flags);
5135 update_rq_clock(rq);
5137 * The RT priorities are set via sched_setscheduler(), but we still
5138 * allow the 'normal' nice value to be set - but as expected
5139 * it wont have any effect on scheduling until the task is
5140 * SCHED_FIFO/SCHED_RR:
5142 if (task_has_rt_policy(p)) {
5143 p->static_prio = NICE_TO_PRIO(nice);
5146 on_rq = p->se.on_rq;
5148 dequeue_task(rq, p, 0);
5150 p->static_prio = NICE_TO_PRIO(nice);
5153 p->prio = effective_prio(p);
5154 delta = p->prio - old_prio;
5157 enqueue_task(rq, p, 0);
5159 * If the task increased its priority or is running and
5160 * lowered its priority, then reschedule its CPU:
5162 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5163 resched_task(rq->curr);
5166 task_rq_unlock(rq, &flags);
5168 EXPORT_SYMBOL(set_user_nice);
5171 * can_nice - check if a task can reduce its nice value
5175 int can_nice(const struct task_struct *p, const int nice)
5177 /* convert nice value [19,-20] to rlimit style value [1,40] */
5178 int nice_rlim = 20 - nice;
5180 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5181 capable(CAP_SYS_NICE));
5184 #ifdef __ARCH_WANT_SYS_NICE
5187 * sys_nice - change the priority of the current process.
5188 * @increment: priority increment
5190 * sys_setpriority is a more generic, but much slower function that
5191 * does similar things.
5193 asmlinkage long sys_nice(int increment)
5198 * Setpriority might change our priority at the same moment.
5199 * We don't have to worry. Conceptually one call occurs first
5200 * and we have a single winner.
5202 if (increment < -40)
5207 nice = PRIO_TO_NICE(current->static_prio) + increment;
5213 if (increment < 0 && !can_nice(current, nice))
5216 retval = security_task_setnice(current, nice);
5220 set_user_nice(current, nice);
5227 * task_prio - return the priority value of a given task.
5228 * @p: the task in question.
5230 * This is the priority value as seen by users in /proc.
5231 * RT tasks are offset by -200. Normal tasks are centered
5232 * around 0, value goes from -16 to +15.
5234 int task_prio(const struct task_struct *p)
5236 return p->prio - MAX_RT_PRIO;
5240 * task_nice - return the nice value of a given task.
5241 * @p: the task in question.
5243 int task_nice(const struct task_struct *p)
5245 return TASK_NICE(p);
5247 EXPORT_SYMBOL(task_nice);
5250 * idle_cpu - is a given cpu idle currently?
5251 * @cpu: the processor in question.
5253 int idle_cpu(int cpu)
5255 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5259 * idle_task - return the idle task for a given cpu.
5260 * @cpu: the processor in question.
5262 struct task_struct *idle_task(int cpu)
5264 return cpu_rq(cpu)->idle;
5268 * find_process_by_pid - find a process with a matching PID value.
5269 * @pid: the pid in question.
5271 static struct task_struct *find_process_by_pid(pid_t pid)
5273 return pid ? find_task_by_vpid(pid) : current;
5276 /* Actually do priority change: must hold rq lock. */
5278 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5280 BUG_ON(p->se.on_rq);
5283 switch (p->policy) {
5287 p->sched_class = &fair_sched_class;
5291 p->sched_class = &rt_sched_class;
5295 p->rt_priority = prio;
5296 p->normal_prio = normal_prio(p);
5297 /* we are holding p->pi_lock already */
5298 p->prio = rt_mutex_getprio(p);
5303 * check the target process has a UID that matches the current process's
5305 static bool check_same_owner(struct task_struct *p)
5307 const struct cred *cred = current_cred(), *pcred;
5311 pcred = __task_cred(p);
5312 match = (cred->euid == pcred->euid ||
5313 cred->euid == pcred->uid);
5318 static int __sched_setscheduler(struct task_struct *p, int policy,
5319 struct sched_param *param, bool user)
5321 int retval, oldprio, oldpolicy = -1, on_rq, running;
5322 unsigned long flags;
5323 const struct sched_class *prev_class = p->sched_class;
5326 /* may grab non-irq protected spin_locks */
5327 BUG_ON(in_interrupt());
5329 /* double check policy once rq lock held */
5331 policy = oldpolicy = p->policy;
5332 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5333 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5334 policy != SCHED_IDLE)
5337 * Valid priorities for SCHED_FIFO and SCHED_RR are
5338 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5339 * SCHED_BATCH and SCHED_IDLE is 0.
5341 if (param->sched_priority < 0 ||
5342 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5343 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5345 if (rt_policy(policy) != (param->sched_priority != 0))
5349 * Allow unprivileged RT tasks to decrease priority:
5351 if (user && !capable(CAP_SYS_NICE)) {
5352 if (rt_policy(policy)) {
5353 unsigned long rlim_rtprio;
5355 if (!lock_task_sighand(p, &flags))
5357 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5358 unlock_task_sighand(p, &flags);
5360 /* can't set/change the rt policy */
5361 if (policy != p->policy && !rlim_rtprio)
5364 /* can't increase priority */
5365 if (param->sched_priority > p->rt_priority &&
5366 param->sched_priority > rlim_rtprio)
5370 * Like positive nice levels, dont allow tasks to
5371 * move out of SCHED_IDLE either:
5373 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5376 /* can't change other user's priorities */
5377 if (!check_same_owner(p))
5382 #ifdef CONFIG_RT_GROUP_SCHED
5384 * Do not allow realtime tasks into groups that have no runtime
5387 if (rt_bandwidth_enabled() && rt_policy(policy) &&
5388 task_group(p)->rt_bandwidth.rt_runtime == 0)
5392 retval = security_task_setscheduler(p, policy, param);
5398 * make sure no PI-waiters arrive (or leave) while we are
5399 * changing the priority of the task:
5401 spin_lock_irqsave(&p->pi_lock, flags);
5403 * To be able to change p->policy safely, the apropriate
5404 * runqueue lock must be held.
5406 rq = __task_rq_lock(p);
5407 /* recheck policy now with rq lock held */
5408 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5409 policy = oldpolicy = -1;
5410 __task_rq_unlock(rq);
5411 spin_unlock_irqrestore(&p->pi_lock, flags);
5414 update_rq_clock(rq);
5415 on_rq = p->se.on_rq;
5416 running = task_current(rq, p);
5418 deactivate_task(rq, p, 0);
5420 p->sched_class->put_prev_task(rq, p);
5423 __setscheduler(rq, p, policy, param->sched_priority);
5426 p->sched_class->set_curr_task(rq);
5428 activate_task(rq, p, 0);
5430 check_class_changed(rq, p, prev_class, oldprio, running);
5432 __task_rq_unlock(rq);
5433 spin_unlock_irqrestore(&p->pi_lock, flags);
5435 rt_mutex_adjust_pi(p);
5441 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5442 * @p: the task in question.
5443 * @policy: new policy.
5444 * @param: structure containing the new RT priority.
5446 * NOTE that the task may be already dead.
5448 int sched_setscheduler(struct task_struct *p, int policy,
5449 struct sched_param *param)
5451 return __sched_setscheduler(p, policy, param, true);
5453 EXPORT_SYMBOL_GPL(sched_setscheduler);
5456 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5457 * @p: the task in question.
5458 * @policy: new policy.
5459 * @param: structure containing the new RT priority.
5461 * Just like sched_setscheduler, only don't bother checking if the
5462 * current context has permission. For example, this is needed in
5463 * stop_machine(): we create temporary high priority worker threads,
5464 * but our caller might not have that capability.
5466 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5467 struct sched_param *param)
5469 return __sched_setscheduler(p, policy, param, false);
5473 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5475 struct sched_param lparam;
5476 struct task_struct *p;
5479 if (!param || pid < 0)
5481 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5486 p = find_process_by_pid(pid);
5488 retval = sched_setscheduler(p, policy, &lparam);
5495 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5496 * @pid: the pid in question.
5497 * @policy: new policy.
5498 * @param: structure containing the new RT priority.
5501 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5503 /* negative values for policy are not valid */
5507 return do_sched_setscheduler(pid, policy, param);
5511 * sys_sched_setparam - set/change the RT priority of a thread
5512 * @pid: the pid in question.
5513 * @param: structure containing the new RT priority.
5515 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5517 return do_sched_setscheduler(pid, -1, param);
5521 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5522 * @pid: the pid in question.
5524 asmlinkage long sys_sched_getscheduler(pid_t pid)
5526 struct task_struct *p;
5533 read_lock(&tasklist_lock);
5534 p = find_process_by_pid(pid);
5536 retval = security_task_getscheduler(p);
5540 read_unlock(&tasklist_lock);
5545 * sys_sched_getscheduler - get the RT priority of a thread
5546 * @pid: the pid in question.
5547 * @param: structure containing the RT priority.
5549 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5551 struct sched_param lp;
5552 struct task_struct *p;
5555 if (!param || pid < 0)
5558 read_lock(&tasklist_lock);
5559 p = find_process_by_pid(pid);
5564 retval = security_task_getscheduler(p);
5568 lp.sched_priority = p->rt_priority;
5569 read_unlock(&tasklist_lock);
5572 * This one might sleep, we cannot do it with a spinlock held ...
5574 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5579 read_unlock(&tasklist_lock);
5583 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
5585 cpumask_var_t cpus_allowed, new_mask;
5586 struct task_struct *p;
5590 read_lock(&tasklist_lock);
5592 p = find_process_by_pid(pid);
5594 read_unlock(&tasklist_lock);
5600 * It is not safe to call set_cpus_allowed with the
5601 * tasklist_lock held. We will bump the task_struct's
5602 * usage count and then drop tasklist_lock.
5605 read_unlock(&tasklist_lock);
5607 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
5611 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
5613 goto out_free_cpus_allowed;
5616 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
5619 retval = security_task_setscheduler(p, 0, NULL);
5623 cpuset_cpus_allowed(p, cpus_allowed);
5624 cpumask_and(new_mask, in_mask, cpus_allowed);
5626 retval = set_cpus_allowed_ptr(p, new_mask);
5629 cpuset_cpus_allowed(p, cpus_allowed);
5630 if (!cpumask_subset(new_mask, cpus_allowed)) {
5632 * We must have raced with a concurrent cpuset
5633 * update. Just reset the cpus_allowed to the
5634 * cpuset's cpus_allowed
5636 cpumask_copy(new_mask, cpus_allowed);
5641 free_cpumask_var(new_mask);
5642 out_free_cpus_allowed:
5643 free_cpumask_var(cpus_allowed);
5650 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5651 struct cpumask *new_mask)
5653 if (len < cpumask_size())
5654 cpumask_clear(new_mask);
5655 else if (len > cpumask_size())
5656 len = cpumask_size();
5658 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5662 * sys_sched_setaffinity - set the cpu affinity of a process
5663 * @pid: pid of the process
5664 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5665 * @user_mask_ptr: user-space pointer to the new cpu mask
5667 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5668 unsigned long __user *user_mask_ptr)
5670 cpumask_var_t new_mask;
5673 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
5676 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
5678 retval = sched_setaffinity(pid, new_mask);
5679 free_cpumask_var(new_mask);
5683 long sched_getaffinity(pid_t pid, struct cpumask *mask)
5685 struct task_struct *p;
5689 read_lock(&tasklist_lock);
5692 p = find_process_by_pid(pid);
5696 retval = security_task_getscheduler(p);
5700 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
5703 read_unlock(&tasklist_lock);
5710 * sys_sched_getaffinity - get the cpu affinity of a process
5711 * @pid: pid of the process
5712 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5713 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5715 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5716 unsigned long __user *user_mask_ptr)
5721 if (len < cpumask_size())
5724 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5727 ret = sched_getaffinity(pid, mask);
5729 if (copy_to_user(user_mask_ptr, mask, cpumask_size()))
5732 ret = cpumask_size();
5734 free_cpumask_var(mask);
5740 * sys_sched_yield - yield the current processor to other threads.
5742 * This function yields the current CPU to other tasks. If there are no
5743 * other threads running on this CPU then this function will return.
5745 asmlinkage long sys_sched_yield(void)
5747 struct rq *rq = this_rq_lock();
5749 schedstat_inc(rq, yld_count);
5750 current->sched_class->yield_task(rq);
5753 * Since we are going to call schedule() anyway, there's
5754 * no need to preempt or enable interrupts:
5756 __release(rq->lock);
5757 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5758 _raw_spin_unlock(&rq->lock);
5759 preempt_enable_no_resched();
5766 static void __cond_resched(void)
5768 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5769 __might_sleep(__FILE__, __LINE__);
5772 * The BKS might be reacquired before we have dropped
5773 * PREEMPT_ACTIVE, which could trigger a second
5774 * cond_resched() call.
5777 add_preempt_count(PREEMPT_ACTIVE);
5779 sub_preempt_count(PREEMPT_ACTIVE);
5780 } while (need_resched());
5783 int __sched _cond_resched(void)
5785 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5786 system_state == SYSTEM_RUNNING) {
5792 EXPORT_SYMBOL(_cond_resched);
5795 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5796 * call schedule, and on return reacquire the lock.
5798 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5799 * operations here to prevent schedule() from being called twice (once via
5800 * spin_unlock(), once by hand).
5802 int cond_resched_lock(spinlock_t *lock)
5804 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5807 if (spin_needbreak(lock) || resched) {
5809 if (resched && need_resched())
5818 EXPORT_SYMBOL(cond_resched_lock);
5820 int __sched cond_resched_softirq(void)
5822 BUG_ON(!in_softirq());
5824 if (need_resched() && system_state == SYSTEM_RUNNING) {
5832 EXPORT_SYMBOL(cond_resched_softirq);
5835 * yield - yield the current processor to other threads.
5837 * This is a shortcut for kernel-space yielding - it marks the
5838 * thread runnable and calls sys_sched_yield().
5840 void __sched yield(void)
5842 set_current_state(TASK_RUNNING);
5845 EXPORT_SYMBOL(yield);
5848 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5849 * that process accounting knows that this is a task in IO wait state.
5851 * But don't do that if it is a deliberate, throttling IO wait (this task
5852 * has set its backing_dev_info: the queue against which it should throttle)
5854 void __sched io_schedule(void)
5856 struct rq *rq = &__raw_get_cpu_var(runqueues);
5858 delayacct_blkio_start();
5859 atomic_inc(&rq->nr_iowait);
5861 atomic_dec(&rq->nr_iowait);
5862 delayacct_blkio_end();
5864 EXPORT_SYMBOL(io_schedule);
5866 long __sched io_schedule_timeout(long timeout)
5868 struct rq *rq = &__raw_get_cpu_var(runqueues);
5871 delayacct_blkio_start();
5872 atomic_inc(&rq->nr_iowait);
5873 ret = schedule_timeout(timeout);
5874 atomic_dec(&rq->nr_iowait);
5875 delayacct_blkio_end();
5880 * sys_sched_get_priority_max - return maximum RT priority.
5881 * @policy: scheduling class.
5883 * this syscall returns the maximum rt_priority that can be used
5884 * by a given scheduling class.
5886 asmlinkage long sys_sched_get_priority_max(int policy)
5893 ret = MAX_USER_RT_PRIO-1;
5905 * sys_sched_get_priority_min - return minimum RT priority.
5906 * @policy: scheduling class.
5908 * this syscall returns the minimum rt_priority that can be used
5909 * by a given scheduling class.
5911 asmlinkage long sys_sched_get_priority_min(int policy)
5929 * sys_sched_rr_get_interval - return the default timeslice of a process.
5930 * @pid: pid of the process.
5931 * @interval: userspace pointer to the timeslice value.
5933 * this syscall writes the default timeslice value of a given process
5934 * into the user-space timespec buffer. A value of '0' means infinity.
5937 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5939 struct task_struct *p;
5940 unsigned int time_slice;
5948 read_lock(&tasklist_lock);
5949 p = find_process_by_pid(pid);
5953 retval = security_task_getscheduler(p);
5958 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5959 * tasks that are on an otherwise idle runqueue:
5962 if (p->policy == SCHED_RR) {
5963 time_slice = DEF_TIMESLICE;
5964 } else if (p->policy != SCHED_FIFO) {
5965 struct sched_entity *se = &p->se;
5966 unsigned long flags;
5969 rq = task_rq_lock(p, &flags);
5970 if (rq->cfs.load.weight)
5971 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5972 task_rq_unlock(rq, &flags);
5974 read_unlock(&tasklist_lock);
5975 jiffies_to_timespec(time_slice, &t);
5976 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5980 read_unlock(&tasklist_lock);
5984 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5986 void sched_show_task(struct task_struct *p)
5988 unsigned long free = 0;
5991 state = p->state ? __ffs(p->state) + 1 : 0;
5992 printk(KERN_INFO "%-13.13s %c", p->comm,
5993 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5994 #if BITS_PER_LONG == 32
5995 if (state == TASK_RUNNING)
5996 printk(KERN_CONT " running ");
5998 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
6000 if (state == TASK_RUNNING)
6001 printk(KERN_CONT " running task ");
6003 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
6005 #ifdef CONFIG_DEBUG_STACK_USAGE
6007 unsigned long *n = end_of_stack(p);
6010 free = (unsigned long)n - (unsigned long)end_of_stack(p);
6013 printk(KERN_CONT "%5lu %5d %6d\n", free,
6014 task_pid_nr(p), task_pid_nr(p->real_parent));
6016 show_stack(p, NULL);
6019 void show_state_filter(unsigned long state_filter)
6021 struct task_struct *g, *p;
6023 #if BITS_PER_LONG == 32
6025 " task PC stack pid father\n");
6028 " task PC stack pid father\n");
6030 read_lock(&tasklist_lock);
6031 do_each_thread(g, p) {
6033 * reset the NMI-timeout, listing all files on a slow
6034 * console might take alot of time:
6036 touch_nmi_watchdog();
6037 if (!state_filter || (p->state & state_filter))
6039 } while_each_thread(g, p);
6041 touch_all_softlockup_watchdogs();
6043 #ifdef CONFIG_SCHED_DEBUG
6044 sysrq_sched_debug_show();
6046 read_unlock(&tasklist_lock);
6048 * Only show locks if all tasks are dumped:
6050 if (state_filter == -1)
6051 debug_show_all_locks();
6054 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
6056 idle->sched_class = &idle_sched_class;
6060 * init_idle - set up an idle thread for a given CPU
6061 * @idle: task in question
6062 * @cpu: cpu the idle task belongs to
6064 * NOTE: this function does not set the idle thread's NEED_RESCHED
6065 * flag, to make booting more robust.
6067 void __cpuinit init_idle(struct task_struct *idle, int cpu)
6069 struct rq *rq = cpu_rq(cpu);
6070 unsigned long flags;
6072 spin_lock_irqsave(&rq->lock, flags);
6075 idle->se.exec_start = sched_clock();
6077 idle->prio = idle->normal_prio = MAX_PRIO;
6078 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
6079 __set_task_cpu(idle, cpu);
6081 rq->curr = rq->idle = idle;
6082 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
6085 spin_unlock_irqrestore(&rq->lock, flags);
6087 /* Set the preempt count _outside_ the spinlocks! */
6088 #if defined(CONFIG_PREEMPT)
6089 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
6091 task_thread_info(idle)->preempt_count = 0;
6094 * The idle tasks have their own, simple scheduling class:
6096 idle->sched_class = &idle_sched_class;
6097 ftrace_graph_init_task(idle);
6101 * In a system that switches off the HZ timer nohz_cpu_mask
6102 * indicates which cpus entered this state. This is used
6103 * in the rcu update to wait only for active cpus. For system
6104 * which do not switch off the HZ timer nohz_cpu_mask should
6105 * always be CPU_BITS_NONE.
6107 cpumask_var_t nohz_cpu_mask;
6110 * Increase the granularity value when there are more CPUs,
6111 * because with more CPUs the 'effective latency' as visible
6112 * to users decreases. But the relationship is not linear,
6113 * so pick a second-best guess by going with the log2 of the
6116 * This idea comes from the SD scheduler of Con Kolivas:
6118 static inline void sched_init_granularity(void)
6120 unsigned int factor = 1 + ilog2(num_online_cpus());
6121 const unsigned long limit = 200000000;
6123 sysctl_sched_min_granularity *= factor;
6124 if (sysctl_sched_min_granularity > limit)
6125 sysctl_sched_min_granularity = limit;
6127 sysctl_sched_latency *= factor;
6128 if (sysctl_sched_latency > limit)
6129 sysctl_sched_latency = limit;
6131 sysctl_sched_wakeup_granularity *= factor;
6133 sysctl_sched_shares_ratelimit *= factor;
6138 * This is how migration works:
6140 * 1) we queue a struct migration_req structure in the source CPU's
6141 * runqueue and wake up that CPU's migration thread.
6142 * 2) we down() the locked semaphore => thread blocks.
6143 * 3) migration thread wakes up (implicitly it forces the migrated
6144 * thread off the CPU)
6145 * 4) it gets the migration request and checks whether the migrated
6146 * task is still in the wrong runqueue.
6147 * 5) if it's in the wrong runqueue then the migration thread removes
6148 * it and puts it into the right queue.
6149 * 6) migration thread up()s the semaphore.
6150 * 7) we wake up and the migration is done.
6154 * Change a given task's CPU affinity. Migrate the thread to a
6155 * proper CPU and schedule it away if the CPU it's executing on
6156 * is removed from the allowed bitmask.
6158 * NOTE: the caller must have a valid reference to the task, the
6159 * task must not exit() & deallocate itself prematurely. The
6160 * call is not atomic; no spinlocks may be held.
6162 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
6164 struct migration_req req;
6165 unsigned long flags;
6169 rq = task_rq_lock(p, &flags);
6170 if (!cpumask_intersects(new_mask, cpu_online_mask)) {
6175 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
6176 !cpumask_equal(&p->cpus_allowed, new_mask))) {
6181 if (p->sched_class->set_cpus_allowed)
6182 p->sched_class->set_cpus_allowed(p, new_mask);
6184 cpumask_copy(&p->cpus_allowed, new_mask);
6185 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
6188 /* Can the task run on the task's current CPU? If so, we're done */
6189 if (cpumask_test_cpu(task_cpu(p), new_mask))
6192 if (migrate_task(p, cpumask_any_and(cpu_online_mask, new_mask), &req)) {
6193 /* Need help from migration thread: drop lock and wait. */
6194 task_rq_unlock(rq, &flags);
6195 wake_up_process(rq->migration_thread);
6196 wait_for_completion(&req.done);
6197 tlb_migrate_finish(p->mm);
6201 task_rq_unlock(rq, &flags);
6205 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6208 * Move (not current) task off this cpu, onto dest cpu. We're doing
6209 * this because either it can't run here any more (set_cpus_allowed()
6210 * away from this CPU, or CPU going down), or because we're
6211 * attempting to rebalance this task on exec (sched_exec).
6213 * So we race with normal scheduler movements, but that's OK, as long
6214 * as the task is no longer on this CPU.
6216 * Returns non-zero if task was successfully migrated.
6218 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6220 struct rq *rq_dest, *rq_src;
6223 if (unlikely(!cpu_active(dest_cpu)))
6226 rq_src = cpu_rq(src_cpu);
6227 rq_dest = cpu_rq(dest_cpu);
6229 double_rq_lock(rq_src, rq_dest);
6230 /* Already moved. */
6231 if (task_cpu(p) != src_cpu)
6233 /* Affinity changed (again). */
6234 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6237 on_rq = p->se.on_rq;
6239 deactivate_task(rq_src, p, 0);
6241 set_task_cpu(p, dest_cpu);
6243 activate_task(rq_dest, p, 0);
6244 check_preempt_curr(rq_dest, p, 0);
6249 double_rq_unlock(rq_src, rq_dest);
6254 * migration_thread - this is a highprio system thread that performs
6255 * thread migration by bumping thread off CPU then 'pushing' onto
6258 static int migration_thread(void *data)
6260 int cpu = (long)data;
6264 BUG_ON(rq->migration_thread != current);
6266 set_current_state(TASK_INTERRUPTIBLE);
6267 while (!kthread_should_stop()) {
6268 struct migration_req *req;
6269 struct list_head *head;
6271 spin_lock_irq(&rq->lock);
6273 if (cpu_is_offline(cpu)) {
6274 spin_unlock_irq(&rq->lock);
6278 if (rq->active_balance) {
6279 active_load_balance(rq, cpu);
6280 rq->active_balance = 0;
6283 head = &rq->migration_queue;
6285 if (list_empty(head)) {
6286 spin_unlock_irq(&rq->lock);
6288 set_current_state(TASK_INTERRUPTIBLE);
6291 req = list_entry(head->next, struct migration_req, list);
6292 list_del_init(head->next);
6294 spin_unlock(&rq->lock);
6295 __migrate_task(req->task, cpu, req->dest_cpu);
6298 complete(&req->done);
6300 __set_current_state(TASK_RUNNING);
6304 /* Wait for kthread_stop */
6305 set_current_state(TASK_INTERRUPTIBLE);
6306 while (!kthread_should_stop()) {
6308 set_current_state(TASK_INTERRUPTIBLE);
6310 __set_current_state(TASK_RUNNING);
6314 #ifdef CONFIG_HOTPLUG_CPU
6316 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6320 local_irq_disable();
6321 ret = __migrate_task(p, src_cpu, dest_cpu);
6327 * Figure out where task on dead CPU should go, use force if necessary.
6329 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6332 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(dead_cpu));
6335 /* Look for allowed, online CPU in same node. */
6336 for_each_cpu_and(dest_cpu, nodemask, cpu_online_mask)
6337 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6340 /* Any allowed, online CPU? */
6341 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_online_mask);
6342 if (dest_cpu < nr_cpu_ids)
6345 /* No more Mr. Nice Guy. */
6346 if (dest_cpu >= nr_cpu_ids) {
6347 cpuset_cpus_allowed_locked(p, &p->cpus_allowed);
6348 dest_cpu = cpumask_any_and(cpu_online_mask, &p->cpus_allowed);
6351 * Don't tell them about moving exiting tasks or
6352 * kernel threads (both mm NULL), since they never
6355 if (p->mm && printk_ratelimit()) {
6356 printk(KERN_INFO "process %d (%s) no "
6357 "longer affine to cpu%d\n",
6358 task_pid_nr(p), p->comm, dead_cpu);
6363 /* It can have affinity changed while we were choosing. */
6364 if (unlikely(!__migrate_task_irq(p, dead_cpu, dest_cpu)))
6369 * While a dead CPU has no uninterruptible tasks queued at this point,
6370 * it might still have a nonzero ->nr_uninterruptible counter, because
6371 * for performance reasons the counter is not stricly tracking tasks to
6372 * their home CPUs. So we just add the counter to another CPU's counter,
6373 * to keep the global sum constant after CPU-down:
6375 static void migrate_nr_uninterruptible(struct rq *rq_src)
6377 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_online_mask));
6378 unsigned long flags;
6380 local_irq_save(flags);
6381 double_rq_lock(rq_src, rq_dest);
6382 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6383 rq_src->nr_uninterruptible = 0;
6384 double_rq_unlock(rq_src, rq_dest);
6385 local_irq_restore(flags);
6388 /* Run through task list and migrate tasks from the dead cpu. */
6389 static void migrate_live_tasks(int src_cpu)
6391 struct task_struct *p, *t;
6393 read_lock(&tasklist_lock);
6395 do_each_thread(t, p) {
6399 if (task_cpu(p) == src_cpu)
6400 move_task_off_dead_cpu(src_cpu, p);
6401 } while_each_thread(t, p);
6403 read_unlock(&tasklist_lock);
6407 * Schedules idle task to be the next runnable task on current CPU.
6408 * It does so by boosting its priority to highest possible.
6409 * Used by CPU offline code.
6411 void sched_idle_next(void)
6413 int this_cpu = smp_processor_id();
6414 struct rq *rq = cpu_rq(this_cpu);
6415 struct task_struct *p = rq->idle;
6416 unsigned long flags;
6418 /* cpu has to be offline */
6419 BUG_ON(cpu_online(this_cpu));
6422 * Strictly not necessary since rest of the CPUs are stopped by now
6423 * and interrupts disabled on the current cpu.
6425 spin_lock_irqsave(&rq->lock, flags);
6427 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6429 update_rq_clock(rq);
6430 activate_task(rq, p, 0);
6432 spin_unlock_irqrestore(&rq->lock, flags);
6436 * Ensures that the idle task is using init_mm right before its cpu goes
6439 void idle_task_exit(void)
6441 struct mm_struct *mm = current->active_mm;
6443 BUG_ON(cpu_online(smp_processor_id()));
6446 switch_mm(mm, &init_mm, current);
6450 /* called under rq->lock with disabled interrupts */
6451 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6453 struct rq *rq = cpu_rq(dead_cpu);
6455 /* Must be exiting, otherwise would be on tasklist. */
6456 BUG_ON(!p->exit_state);
6458 /* Cannot have done final schedule yet: would have vanished. */
6459 BUG_ON(p->state == TASK_DEAD);
6464 * Drop lock around migration; if someone else moves it,
6465 * that's OK. No task can be added to this CPU, so iteration is
6468 spin_unlock_irq(&rq->lock);
6469 move_task_off_dead_cpu(dead_cpu, p);
6470 spin_lock_irq(&rq->lock);
6475 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6476 static void migrate_dead_tasks(unsigned int dead_cpu)
6478 struct rq *rq = cpu_rq(dead_cpu);
6479 struct task_struct *next;
6482 if (!rq->nr_running)
6484 update_rq_clock(rq);
6485 next = pick_next_task(rq, rq->curr);
6488 next->sched_class->put_prev_task(rq, next);
6489 migrate_dead(dead_cpu, next);
6493 #endif /* CONFIG_HOTPLUG_CPU */
6495 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6497 static struct ctl_table sd_ctl_dir[] = {
6499 .procname = "sched_domain",
6505 static struct ctl_table sd_ctl_root[] = {
6507 .ctl_name = CTL_KERN,
6508 .procname = "kernel",
6510 .child = sd_ctl_dir,
6515 static struct ctl_table *sd_alloc_ctl_entry(int n)
6517 struct ctl_table *entry =
6518 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6523 static void sd_free_ctl_entry(struct ctl_table **tablep)
6525 struct ctl_table *entry;
6528 * In the intermediate directories, both the child directory and
6529 * procname are dynamically allocated and could fail but the mode
6530 * will always be set. In the lowest directory the names are
6531 * static strings and all have proc handlers.
6533 for (entry = *tablep; entry->mode; entry++) {
6535 sd_free_ctl_entry(&entry->child);
6536 if (entry->proc_handler == NULL)
6537 kfree(entry->procname);
6545 set_table_entry(struct ctl_table *entry,
6546 const char *procname, void *data, int maxlen,
6547 mode_t mode, proc_handler *proc_handler)
6549 entry->procname = procname;
6551 entry->maxlen = maxlen;
6553 entry->proc_handler = proc_handler;
6556 static struct ctl_table *
6557 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6559 struct ctl_table *table = sd_alloc_ctl_entry(13);
6564 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6565 sizeof(long), 0644, proc_doulongvec_minmax);
6566 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6567 sizeof(long), 0644, proc_doulongvec_minmax);
6568 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6569 sizeof(int), 0644, proc_dointvec_minmax);
6570 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6571 sizeof(int), 0644, proc_dointvec_minmax);
6572 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6573 sizeof(int), 0644, proc_dointvec_minmax);
6574 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6575 sizeof(int), 0644, proc_dointvec_minmax);
6576 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6577 sizeof(int), 0644, proc_dointvec_minmax);
6578 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6579 sizeof(int), 0644, proc_dointvec_minmax);
6580 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6581 sizeof(int), 0644, proc_dointvec_minmax);
6582 set_table_entry(&table[9], "cache_nice_tries",
6583 &sd->cache_nice_tries,
6584 sizeof(int), 0644, proc_dointvec_minmax);
6585 set_table_entry(&table[10], "flags", &sd->flags,
6586 sizeof(int), 0644, proc_dointvec_minmax);
6587 set_table_entry(&table[11], "name", sd->name,
6588 CORENAME_MAX_SIZE, 0444, proc_dostring);
6589 /* &table[12] is terminator */
6594 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6596 struct ctl_table *entry, *table;
6597 struct sched_domain *sd;
6598 int domain_num = 0, i;
6601 for_each_domain(cpu, sd)
6603 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6608 for_each_domain(cpu, sd) {
6609 snprintf(buf, 32, "domain%d", i);
6610 entry->procname = kstrdup(buf, GFP_KERNEL);
6612 entry->child = sd_alloc_ctl_domain_table(sd);
6619 static struct ctl_table_header *sd_sysctl_header;
6620 static void register_sched_domain_sysctl(void)
6622 int i, cpu_num = num_online_cpus();
6623 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6626 WARN_ON(sd_ctl_dir[0].child);
6627 sd_ctl_dir[0].child = entry;
6632 for_each_online_cpu(i) {
6633 snprintf(buf, 32, "cpu%d", i);
6634 entry->procname = kstrdup(buf, GFP_KERNEL);
6636 entry->child = sd_alloc_ctl_cpu_table(i);
6640 WARN_ON(sd_sysctl_header);
6641 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6644 /* may be called multiple times per register */
6645 static void unregister_sched_domain_sysctl(void)
6647 if (sd_sysctl_header)
6648 unregister_sysctl_table(sd_sysctl_header);
6649 sd_sysctl_header = NULL;
6650 if (sd_ctl_dir[0].child)
6651 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6654 static void register_sched_domain_sysctl(void)
6657 static void unregister_sched_domain_sysctl(void)
6662 static void set_rq_online(struct rq *rq)
6665 const struct sched_class *class;
6667 cpumask_set_cpu(rq->cpu, rq->rd->online);
6670 for_each_class(class) {
6671 if (class->rq_online)
6672 class->rq_online(rq);
6677 static void set_rq_offline(struct rq *rq)
6680 const struct sched_class *class;
6682 for_each_class(class) {
6683 if (class->rq_offline)
6684 class->rq_offline(rq);
6687 cpumask_clear_cpu(rq->cpu, rq->rd->online);
6693 * migration_call - callback that gets triggered when a CPU is added.
6694 * Here we can start up the necessary migration thread for the new CPU.
6696 static int __cpuinit
6697 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6699 struct task_struct *p;
6700 int cpu = (long)hcpu;
6701 unsigned long flags;
6706 case CPU_UP_PREPARE:
6707 case CPU_UP_PREPARE_FROZEN:
6708 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6711 kthread_bind(p, cpu);
6712 /* Must be high prio: stop_machine expects to yield to it. */
6713 rq = task_rq_lock(p, &flags);
6714 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6715 task_rq_unlock(rq, &flags);
6716 cpu_rq(cpu)->migration_thread = p;
6720 case CPU_ONLINE_FROZEN:
6721 /* Strictly unnecessary, as first user will wake it. */
6722 wake_up_process(cpu_rq(cpu)->migration_thread);
6724 /* Update our root-domain */
6726 spin_lock_irqsave(&rq->lock, flags);
6728 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6732 spin_unlock_irqrestore(&rq->lock, flags);
6735 #ifdef CONFIG_HOTPLUG_CPU
6736 case CPU_UP_CANCELED:
6737 case CPU_UP_CANCELED_FROZEN:
6738 if (!cpu_rq(cpu)->migration_thread)
6740 /* Unbind it from offline cpu so it can run. Fall thru. */
6741 kthread_bind(cpu_rq(cpu)->migration_thread,
6742 cpumask_any(cpu_online_mask));
6743 kthread_stop(cpu_rq(cpu)->migration_thread);
6744 cpu_rq(cpu)->migration_thread = NULL;
6748 case CPU_DEAD_FROZEN:
6749 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6750 migrate_live_tasks(cpu);
6752 kthread_stop(rq->migration_thread);
6753 rq->migration_thread = NULL;
6754 /* Idle task back to normal (off runqueue, low prio) */
6755 spin_lock_irq(&rq->lock);
6756 update_rq_clock(rq);
6757 deactivate_task(rq, rq->idle, 0);
6758 rq->idle->static_prio = MAX_PRIO;
6759 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6760 rq->idle->sched_class = &idle_sched_class;
6761 migrate_dead_tasks(cpu);
6762 spin_unlock_irq(&rq->lock);
6764 migrate_nr_uninterruptible(rq);
6765 BUG_ON(rq->nr_running != 0);
6768 * No need to migrate the tasks: it was best-effort if
6769 * they didn't take sched_hotcpu_mutex. Just wake up
6772 spin_lock_irq(&rq->lock);
6773 while (!list_empty(&rq->migration_queue)) {
6774 struct migration_req *req;
6776 req = list_entry(rq->migration_queue.next,
6777 struct migration_req, list);
6778 list_del_init(&req->list);
6779 spin_unlock_irq(&rq->lock);
6780 complete(&req->done);
6781 spin_lock_irq(&rq->lock);
6783 spin_unlock_irq(&rq->lock);
6787 case CPU_DYING_FROZEN:
6788 /* Update our root-domain */
6790 spin_lock_irqsave(&rq->lock, flags);
6792 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6795 spin_unlock_irqrestore(&rq->lock, flags);
6802 /* Register at highest priority so that task migration (migrate_all_tasks)
6803 * happens before everything else.
6805 static struct notifier_block __cpuinitdata migration_notifier = {
6806 .notifier_call = migration_call,
6810 static int __init migration_init(void)
6812 void *cpu = (void *)(long)smp_processor_id();
6815 /* Start one for the boot CPU: */
6816 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6817 BUG_ON(err == NOTIFY_BAD);
6818 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6819 register_cpu_notifier(&migration_notifier);
6823 early_initcall(migration_init);
6828 #ifdef CONFIG_SCHED_DEBUG
6830 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6831 struct cpumask *groupmask)
6833 struct sched_group *group = sd->groups;
6836 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
6837 cpumask_clear(groupmask);
6839 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6841 if (!(sd->flags & SD_LOAD_BALANCE)) {
6842 printk("does not load-balance\n");
6844 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6849 printk(KERN_CONT "span %s level %s\n", str, sd->name);
6851 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6852 printk(KERN_ERR "ERROR: domain->span does not contain "
6855 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6856 printk(KERN_ERR "ERROR: domain->groups does not contain"
6860 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6864 printk(KERN_ERR "ERROR: group is NULL\n");
6868 if (!group->__cpu_power) {
6869 printk(KERN_CONT "\n");
6870 printk(KERN_ERR "ERROR: domain->cpu_power not "
6875 if (!cpumask_weight(sched_group_cpus(group))) {
6876 printk(KERN_CONT "\n");
6877 printk(KERN_ERR "ERROR: empty group\n");
6881 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6882 printk(KERN_CONT "\n");
6883 printk(KERN_ERR "ERROR: repeated CPUs\n");
6887 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6889 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6890 printk(KERN_CONT " %s", str);
6892 group = group->next;
6893 } while (group != sd->groups);
6894 printk(KERN_CONT "\n");
6896 if (!cpumask_equal(sched_domain_span(sd), groupmask))
6897 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6900 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6901 printk(KERN_ERR "ERROR: parent span is not a superset "
6902 "of domain->span\n");
6906 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6908 cpumask_var_t groupmask;
6912 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6916 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6918 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
6919 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6924 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6931 free_cpumask_var(groupmask);
6933 #else /* !CONFIG_SCHED_DEBUG */
6934 # define sched_domain_debug(sd, cpu) do { } while (0)
6935 #endif /* CONFIG_SCHED_DEBUG */
6937 static int sd_degenerate(struct sched_domain *sd)
6939 if (cpumask_weight(sched_domain_span(sd)) == 1)
6942 /* Following flags need at least 2 groups */
6943 if (sd->flags & (SD_LOAD_BALANCE |
6944 SD_BALANCE_NEWIDLE |
6948 SD_SHARE_PKG_RESOURCES)) {
6949 if (sd->groups != sd->groups->next)
6953 /* Following flags don't use groups */
6954 if (sd->flags & (SD_WAKE_IDLE |
6963 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6965 unsigned long cflags = sd->flags, pflags = parent->flags;
6967 if (sd_degenerate(parent))
6970 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6973 /* Does parent contain flags not in child? */
6974 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6975 if (cflags & SD_WAKE_AFFINE)
6976 pflags &= ~SD_WAKE_BALANCE;
6977 /* Flags needing groups don't count if only 1 group in parent */
6978 if (parent->groups == parent->groups->next) {
6979 pflags &= ~(SD_LOAD_BALANCE |
6980 SD_BALANCE_NEWIDLE |
6984 SD_SHARE_PKG_RESOURCES);
6985 if (nr_node_ids == 1)
6986 pflags &= ~SD_SERIALIZE;
6988 if (~cflags & pflags)
6994 static void free_rootdomain(struct root_domain *rd)
6996 cpupri_cleanup(&rd->cpupri);
6998 free_cpumask_var(rd->rto_mask);
6999 free_cpumask_var(rd->online);
7000 free_cpumask_var(rd->span);
7004 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
7006 unsigned long flags;
7008 spin_lock_irqsave(&rq->lock, flags);
7011 struct root_domain *old_rd = rq->rd;
7013 if (cpumask_test_cpu(rq->cpu, old_rd->online))
7016 cpumask_clear_cpu(rq->cpu, old_rd->span);
7018 if (atomic_dec_and_test(&old_rd->refcount))
7019 free_rootdomain(old_rd);
7022 atomic_inc(&rd->refcount);
7025 cpumask_set_cpu(rq->cpu, rd->span);
7026 if (cpumask_test_cpu(rq->cpu, cpu_online_mask))
7029 spin_unlock_irqrestore(&rq->lock, flags);
7032 static int __init_refok init_rootdomain(struct root_domain *rd, bool bootmem)
7034 memset(rd, 0, sizeof(*rd));
7037 alloc_bootmem_cpumask_var(&def_root_domain.span);
7038 alloc_bootmem_cpumask_var(&def_root_domain.online);
7039 alloc_bootmem_cpumask_var(&def_root_domain.rto_mask);
7040 cpupri_init(&rd->cpupri, true);
7044 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
7046 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
7048 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
7051 if (cpupri_init(&rd->cpupri, false) != 0)
7056 free_cpumask_var(rd->rto_mask);
7058 free_cpumask_var(rd->online);
7060 free_cpumask_var(rd->span);
7065 static void init_defrootdomain(void)
7067 init_rootdomain(&def_root_domain, true);
7069 atomic_set(&def_root_domain.refcount, 1);
7072 static struct root_domain *alloc_rootdomain(void)
7074 struct root_domain *rd;
7076 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
7080 if (init_rootdomain(rd, false) != 0) {
7089 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
7090 * hold the hotplug lock.
7093 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
7095 struct rq *rq = cpu_rq(cpu);
7096 struct sched_domain *tmp;
7098 /* Remove the sched domains which do not contribute to scheduling. */
7099 for (tmp = sd; tmp; ) {
7100 struct sched_domain *parent = tmp->parent;
7104 if (sd_parent_degenerate(tmp, parent)) {
7105 tmp->parent = parent->parent;
7107 parent->parent->child = tmp;
7112 if (sd && sd_degenerate(sd)) {
7118 sched_domain_debug(sd, cpu);
7120 rq_attach_root(rq, rd);
7121 rcu_assign_pointer(rq->sd, sd);
7124 /* cpus with isolated domains */
7125 static cpumask_var_t cpu_isolated_map;
7127 /* Setup the mask of cpus configured for isolated domains */
7128 static int __init isolated_cpu_setup(char *str)
7130 cpulist_parse(str, cpu_isolated_map);
7134 __setup("isolcpus=", isolated_cpu_setup);
7137 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
7138 * to a function which identifies what group(along with sched group) a CPU
7139 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
7140 * (due to the fact that we keep track of groups covered with a struct cpumask).
7142 * init_sched_build_groups will build a circular linked list of the groups
7143 * covered by the given span, and will set each group's ->cpumask correctly,
7144 * and ->cpu_power to 0.
7147 init_sched_build_groups(const struct cpumask *span,
7148 const struct cpumask *cpu_map,
7149 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
7150 struct sched_group **sg,
7151 struct cpumask *tmpmask),
7152 struct cpumask *covered, struct cpumask *tmpmask)
7154 struct sched_group *first = NULL, *last = NULL;
7157 cpumask_clear(covered);
7159 for_each_cpu(i, span) {
7160 struct sched_group *sg;
7161 int group = group_fn(i, cpu_map, &sg, tmpmask);
7164 if (cpumask_test_cpu(i, covered))
7167 cpumask_clear(sched_group_cpus(sg));
7168 sg->__cpu_power = 0;
7170 for_each_cpu(j, span) {
7171 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
7174 cpumask_set_cpu(j, covered);
7175 cpumask_set_cpu(j, sched_group_cpus(sg));
7186 #define SD_NODES_PER_DOMAIN 16
7191 * find_next_best_node - find the next node to include in a sched_domain
7192 * @node: node whose sched_domain we're building
7193 * @used_nodes: nodes already in the sched_domain
7195 * Find the next node to include in a given scheduling domain. Simply
7196 * finds the closest node not already in the @used_nodes map.
7198 * Should use nodemask_t.
7200 static int find_next_best_node(int node, nodemask_t *used_nodes)
7202 int i, n, val, min_val, best_node = 0;
7206 for (i = 0; i < nr_node_ids; i++) {
7207 /* Start at @node */
7208 n = (node + i) % nr_node_ids;
7210 if (!nr_cpus_node(n))
7213 /* Skip already used nodes */
7214 if (node_isset(n, *used_nodes))
7217 /* Simple min distance search */
7218 val = node_distance(node, n);
7220 if (val < min_val) {
7226 node_set(best_node, *used_nodes);
7231 * sched_domain_node_span - get a cpumask for a node's sched_domain
7232 * @node: node whose cpumask we're constructing
7233 * @span: resulting cpumask
7235 * Given a node, construct a good cpumask for its sched_domain to span. It
7236 * should be one that prevents unnecessary balancing, but also spreads tasks
7239 static void sched_domain_node_span(int node, struct cpumask *span)
7241 nodemask_t used_nodes;
7244 cpumask_clear(span);
7245 nodes_clear(used_nodes);
7247 cpumask_or(span, span, cpumask_of_node(node));
7248 node_set(node, used_nodes);
7250 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7251 int next_node = find_next_best_node(node, &used_nodes);
7253 cpumask_or(span, span, cpumask_of_node(next_node));
7256 #endif /* CONFIG_NUMA */
7258 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7261 * The cpus mask in sched_group and sched_domain hangs off the end.
7262 * FIXME: use cpumask_var_t or dynamic percpu alloc to avoid wasting space
7263 * for nr_cpu_ids < CONFIG_NR_CPUS.
7265 struct static_sched_group {
7266 struct sched_group sg;
7267 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
7270 struct static_sched_domain {
7271 struct sched_domain sd;
7272 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
7276 * SMT sched-domains:
7278 #ifdef CONFIG_SCHED_SMT
7279 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
7280 static DEFINE_PER_CPU(struct static_sched_group, sched_group_cpus);
7283 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
7284 struct sched_group **sg, struct cpumask *unused)
7287 *sg = &per_cpu(sched_group_cpus, cpu).sg;
7290 #endif /* CONFIG_SCHED_SMT */
7293 * multi-core sched-domains:
7295 #ifdef CONFIG_SCHED_MC
7296 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
7297 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
7298 #endif /* CONFIG_SCHED_MC */
7300 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7302 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
7303 struct sched_group **sg, struct cpumask *mask)
7307 cpumask_and(mask, &per_cpu(cpu_sibling_map, cpu), cpu_map);
7308 group = cpumask_first(mask);
7310 *sg = &per_cpu(sched_group_core, group).sg;
7313 #elif defined(CONFIG_SCHED_MC)
7315 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
7316 struct sched_group **sg, struct cpumask *unused)
7319 *sg = &per_cpu(sched_group_core, cpu).sg;
7324 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
7325 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
7328 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
7329 struct sched_group **sg, struct cpumask *mask)
7332 #ifdef CONFIG_SCHED_MC
7333 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
7334 group = cpumask_first(mask);
7335 #elif defined(CONFIG_SCHED_SMT)
7336 cpumask_and(mask, &per_cpu(cpu_sibling_map, cpu), cpu_map);
7337 group = cpumask_first(mask);
7342 *sg = &per_cpu(sched_group_phys, group).sg;
7348 * The init_sched_build_groups can't handle what we want to do with node
7349 * groups, so roll our own. Now each node has its own list of groups which
7350 * gets dynamically allocated.
7352 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7353 static struct sched_group ***sched_group_nodes_bycpu;
7355 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7356 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
7358 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
7359 struct sched_group **sg,
7360 struct cpumask *nodemask)
7364 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
7365 group = cpumask_first(nodemask);
7368 *sg = &per_cpu(sched_group_allnodes, group).sg;
7372 static void init_numa_sched_groups_power(struct sched_group *group_head)
7374 struct sched_group *sg = group_head;
7380 for_each_cpu(j, sched_group_cpus(sg)) {
7381 struct sched_domain *sd;
7383 sd = &per_cpu(phys_domains, j).sd;
7384 if (j != cpumask_first(sched_group_cpus(sd->groups))) {
7386 * Only add "power" once for each
7392 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7395 } while (sg != group_head);
7397 #endif /* CONFIG_NUMA */
7400 /* Free memory allocated for various sched_group structures */
7401 static void free_sched_groups(const struct cpumask *cpu_map,
7402 struct cpumask *nodemask)
7406 for_each_cpu(cpu, cpu_map) {
7407 struct sched_group **sched_group_nodes
7408 = sched_group_nodes_bycpu[cpu];
7410 if (!sched_group_nodes)
7413 for (i = 0; i < nr_node_ids; i++) {
7414 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7416 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
7417 if (cpumask_empty(nodemask))
7427 if (oldsg != sched_group_nodes[i])
7430 kfree(sched_group_nodes);
7431 sched_group_nodes_bycpu[cpu] = NULL;
7434 #else /* !CONFIG_NUMA */
7435 static void free_sched_groups(const struct cpumask *cpu_map,
7436 struct cpumask *nodemask)
7439 #endif /* CONFIG_NUMA */
7442 * Initialize sched groups cpu_power.
7444 * cpu_power indicates the capacity of sched group, which is used while
7445 * distributing the load between different sched groups in a sched domain.
7446 * Typically cpu_power for all the groups in a sched domain will be same unless
7447 * there are asymmetries in the topology. If there are asymmetries, group
7448 * having more cpu_power will pickup more load compared to the group having
7451 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7452 * the maximum number of tasks a group can handle in the presence of other idle
7453 * or lightly loaded groups in the same sched domain.
7455 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7457 struct sched_domain *child;
7458 struct sched_group *group;
7460 WARN_ON(!sd || !sd->groups);
7462 if (cpu != cpumask_first(sched_group_cpus(sd->groups)))
7467 sd->groups->__cpu_power = 0;
7470 * For perf policy, if the groups in child domain share resources
7471 * (for example cores sharing some portions of the cache hierarchy
7472 * or SMT), then set this domain groups cpu_power such that each group
7473 * can handle only one task, when there are other idle groups in the
7474 * same sched domain.
7476 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7478 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7479 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7484 * add cpu_power of each child group to this groups cpu_power
7486 group = child->groups;
7488 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7489 group = group->next;
7490 } while (group != child->groups);
7494 * Initializers for schedule domains
7495 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7498 #ifdef CONFIG_SCHED_DEBUG
7499 # define SD_INIT_NAME(sd, type) sd->name = #type
7501 # define SD_INIT_NAME(sd, type) do { } while (0)
7504 #define SD_INIT(sd, type) sd_init_##type(sd)
7506 #define SD_INIT_FUNC(type) \
7507 static noinline void sd_init_##type(struct sched_domain *sd) \
7509 memset(sd, 0, sizeof(*sd)); \
7510 *sd = SD_##type##_INIT; \
7511 sd->level = SD_LV_##type; \
7512 SD_INIT_NAME(sd, type); \
7517 SD_INIT_FUNC(ALLNODES)
7520 #ifdef CONFIG_SCHED_SMT
7521 SD_INIT_FUNC(SIBLING)
7523 #ifdef CONFIG_SCHED_MC
7527 static int default_relax_domain_level = -1;
7529 static int __init setup_relax_domain_level(char *str)
7533 val = simple_strtoul(str, NULL, 0);
7534 if (val < SD_LV_MAX)
7535 default_relax_domain_level = val;
7539 __setup("relax_domain_level=", setup_relax_domain_level);
7541 static void set_domain_attribute(struct sched_domain *sd,
7542 struct sched_domain_attr *attr)
7546 if (!attr || attr->relax_domain_level < 0) {
7547 if (default_relax_domain_level < 0)
7550 request = default_relax_domain_level;
7552 request = attr->relax_domain_level;
7553 if (request < sd->level) {
7554 /* turn off idle balance on this domain */
7555 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7557 /* turn on idle balance on this domain */
7558 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7563 * Build sched domains for a given set of cpus and attach the sched domains
7564 * to the individual cpus
7566 static int __build_sched_domains(const struct cpumask *cpu_map,
7567 struct sched_domain_attr *attr)
7569 int i, err = -ENOMEM;
7570 struct root_domain *rd;
7571 cpumask_var_t nodemask, this_sibling_map, this_core_map, send_covered,
7574 cpumask_var_t domainspan, covered, notcovered;
7575 struct sched_group **sched_group_nodes = NULL;
7576 int sd_allnodes = 0;
7578 if (!alloc_cpumask_var(&domainspan, GFP_KERNEL))
7580 if (!alloc_cpumask_var(&covered, GFP_KERNEL))
7581 goto free_domainspan;
7582 if (!alloc_cpumask_var(¬covered, GFP_KERNEL))
7586 if (!alloc_cpumask_var(&nodemask, GFP_KERNEL))
7587 goto free_notcovered;
7588 if (!alloc_cpumask_var(&this_sibling_map, GFP_KERNEL))
7590 if (!alloc_cpumask_var(&this_core_map, GFP_KERNEL))
7591 goto free_this_sibling_map;
7592 if (!alloc_cpumask_var(&send_covered, GFP_KERNEL))
7593 goto free_this_core_map;
7594 if (!alloc_cpumask_var(&tmpmask, GFP_KERNEL))
7595 goto free_send_covered;
7599 * Allocate the per-node list of sched groups
7601 sched_group_nodes = kcalloc(nr_node_ids, sizeof(struct sched_group *),
7603 if (!sched_group_nodes) {
7604 printk(KERN_WARNING "Can not alloc sched group node list\n");
7609 rd = alloc_rootdomain();
7611 printk(KERN_WARNING "Cannot alloc root domain\n");
7612 goto free_sched_groups;
7616 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = sched_group_nodes;
7620 * Set up domains for cpus specified by the cpu_map.
7622 for_each_cpu(i, cpu_map) {
7623 struct sched_domain *sd = NULL, *p;
7625 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(i)), cpu_map);
7628 if (cpumask_weight(cpu_map) >
7629 SD_NODES_PER_DOMAIN*cpumask_weight(nodemask)) {
7630 sd = &per_cpu(allnodes_domains, i);
7631 SD_INIT(sd, ALLNODES);
7632 set_domain_attribute(sd, attr);
7633 cpumask_copy(sched_domain_span(sd), cpu_map);
7634 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7640 sd = &per_cpu(node_domains, i);
7642 set_domain_attribute(sd, attr);
7643 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
7647 cpumask_and(sched_domain_span(sd),
7648 sched_domain_span(sd), cpu_map);
7652 sd = &per_cpu(phys_domains, i).sd;
7654 set_domain_attribute(sd, attr);
7655 cpumask_copy(sched_domain_span(sd), nodemask);
7659 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7661 #ifdef CONFIG_SCHED_MC
7663 sd = &per_cpu(core_domains, i).sd;
7665 set_domain_attribute(sd, attr);
7666 cpumask_and(sched_domain_span(sd), cpu_map,
7667 cpu_coregroup_mask(i));
7670 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7673 #ifdef CONFIG_SCHED_SMT
7675 sd = &per_cpu(cpu_domains, i).sd;
7676 SD_INIT(sd, SIBLING);
7677 set_domain_attribute(sd, attr);
7678 cpumask_and(sched_domain_span(sd),
7679 &per_cpu(cpu_sibling_map, i), cpu_map);
7682 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7686 #ifdef CONFIG_SCHED_SMT
7687 /* Set up CPU (sibling) groups */
7688 for_each_cpu(i, cpu_map) {
7689 cpumask_and(this_sibling_map,
7690 &per_cpu(cpu_sibling_map, i), cpu_map);
7691 if (i != cpumask_first(this_sibling_map))
7694 init_sched_build_groups(this_sibling_map, cpu_map,
7696 send_covered, tmpmask);
7700 #ifdef CONFIG_SCHED_MC
7701 /* Set up multi-core groups */
7702 for_each_cpu(i, cpu_map) {
7703 cpumask_and(this_core_map, cpu_coregroup_mask(i), cpu_map);
7704 if (i != cpumask_first(this_core_map))
7707 init_sched_build_groups(this_core_map, cpu_map,
7709 send_covered, tmpmask);
7713 /* Set up physical groups */
7714 for (i = 0; i < nr_node_ids; i++) {
7715 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
7716 if (cpumask_empty(nodemask))
7719 init_sched_build_groups(nodemask, cpu_map,
7721 send_covered, tmpmask);
7725 /* Set up node groups */
7727 init_sched_build_groups(cpu_map, cpu_map,
7728 &cpu_to_allnodes_group,
7729 send_covered, tmpmask);
7732 for (i = 0; i < nr_node_ids; i++) {
7733 /* Set up node groups */
7734 struct sched_group *sg, *prev;
7737 cpumask_clear(covered);
7738 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
7739 if (cpumask_empty(nodemask)) {
7740 sched_group_nodes[i] = NULL;
7744 sched_domain_node_span(i, domainspan);
7745 cpumask_and(domainspan, domainspan, cpu_map);
7747 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
7750 printk(KERN_WARNING "Can not alloc domain group for "
7754 sched_group_nodes[i] = sg;
7755 for_each_cpu(j, nodemask) {
7756 struct sched_domain *sd;
7758 sd = &per_cpu(node_domains, j);
7761 sg->__cpu_power = 0;
7762 cpumask_copy(sched_group_cpus(sg), nodemask);
7764 cpumask_or(covered, covered, nodemask);
7767 for (j = 0; j < nr_node_ids; j++) {
7768 int n = (i + j) % nr_node_ids;
7770 cpumask_complement(notcovered, covered);
7771 cpumask_and(tmpmask, notcovered, cpu_map);
7772 cpumask_and(tmpmask, tmpmask, domainspan);
7773 if (cpumask_empty(tmpmask))
7776 cpumask_and(tmpmask, tmpmask, cpumask_of_node(n));
7777 if (cpumask_empty(tmpmask))
7780 sg = kmalloc_node(sizeof(struct sched_group) +
7785 "Can not alloc domain group for node %d\n", j);
7788 sg->__cpu_power = 0;
7789 cpumask_copy(sched_group_cpus(sg), tmpmask);
7790 sg->next = prev->next;
7791 cpumask_or(covered, covered, tmpmask);
7798 /* Calculate CPU power for physical packages and nodes */
7799 #ifdef CONFIG_SCHED_SMT
7800 for_each_cpu(i, cpu_map) {
7801 struct sched_domain *sd = &per_cpu(cpu_domains, i).sd;
7803 init_sched_groups_power(i, sd);
7806 #ifdef CONFIG_SCHED_MC
7807 for_each_cpu(i, cpu_map) {
7808 struct sched_domain *sd = &per_cpu(core_domains, i).sd;
7810 init_sched_groups_power(i, sd);
7814 for_each_cpu(i, cpu_map) {
7815 struct sched_domain *sd = &per_cpu(phys_domains, i).sd;
7817 init_sched_groups_power(i, sd);
7821 for (i = 0; i < nr_node_ids; i++)
7822 init_numa_sched_groups_power(sched_group_nodes[i]);
7825 struct sched_group *sg;
7827 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
7829 init_numa_sched_groups_power(sg);
7833 /* Attach the domains */
7834 for_each_cpu(i, cpu_map) {
7835 struct sched_domain *sd;
7836 #ifdef CONFIG_SCHED_SMT
7837 sd = &per_cpu(cpu_domains, i).sd;
7838 #elif defined(CONFIG_SCHED_MC)
7839 sd = &per_cpu(core_domains, i).sd;
7841 sd = &per_cpu(phys_domains, i).sd;
7843 cpu_attach_domain(sd, rd, i);
7849 free_cpumask_var(tmpmask);
7851 free_cpumask_var(send_covered);
7853 free_cpumask_var(this_core_map);
7854 free_this_sibling_map:
7855 free_cpumask_var(this_sibling_map);
7857 free_cpumask_var(nodemask);
7860 free_cpumask_var(notcovered);
7862 free_cpumask_var(covered);
7864 free_cpumask_var(domainspan);
7871 kfree(sched_group_nodes);
7877 free_sched_groups(cpu_map, tmpmask);
7878 free_rootdomain(rd);
7883 static int build_sched_domains(const struct cpumask *cpu_map)
7885 return __build_sched_domains(cpu_map, NULL);
7888 static struct cpumask *doms_cur; /* current sched domains */
7889 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7890 static struct sched_domain_attr *dattr_cur;
7891 /* attribues of custom domains in 'doms_cur' */
7894 * Special case: If a kmalloc of a doms_cur partition (array of
7895 * cpumask) fails, then fallback to a single sched domain,
7896 * as determined by the single cpumask fallback_doms.
7898 static cpumask_var_t fallback_doms;
7901 * arch_update_cpu_topology lets virtualized architectures update the
7902 * cpu core maps. It is supposed to return 1 if the topology changed
7903 * or 0 if it stayed the same.
7905 int __attribute__((weak)) arch_update_cpu_topology(void)
7911 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7912 * For now this just excludes isolated cpus, but could be used to
7913 * exclude other special cases in the future.
7915 static int arch_init_sched_domains(const struct cpumask *cpu_map)
7919 arch_update_cpu_topology();
7921 doms_cur = kmalloc(cpumask_size(), GFP_KERNEL);
7923 doms_cur = fallback_doms;
7924 cpumask_andnot(doms_cur, cpu_map, cpu_isolated_map);
7926 err = build_sched_domains(doms_cur);
7927 register_sched_domain_sysctl();
7932 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
7933 struct cpumask *tmpmask)
7935 free_sched_groups(cpu_map, tmpmask);
7939 * Detach sched domains from a group of cpus specified in cpu_map
7940 * These cpus will now be attached to the NULL domain
7942 static void detach_destroy_domains(const struct cpumask *cpu_map)
7944 /* Save because hotplug lock held. */
7945 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
7948 for_each_cpu(i, cpu_map)
7949 cpu_attach_domain(NULL, &def_root_domain, i);
7950 synchronize_sched();
7951 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
7954 /* handle null as "default" */
7955 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7956 struct sched_domain_attr *new, int idx_new)
7958 struct sched_domain_attr tmp;
7965 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7966 new ? (new + idx_new) : &tmp,
7967 sizeof(struct sched_domain_attr));
7971 * Partition sched domains as specified by the 'ndoms_new'
7972 * cpumasks in the array doms_new[] of cpumasks. This compares
7973 * doms_new[] to the current sched domain partitioning, doms_cur[].
7974 * It destroys each deleted domain and builds each new domain.
7976 * 'doms_new' is an array of cpumask's of length 'ndoms_new'.
7977 * The masks don't intersect (don't overlap.) We should setup one
7978 * sched domain for each mask. CPUs not in any of the cpumasks will
7979 * not be load balanced. If the same cpumask appears both in the
7980 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7983 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7984 * ownership of it and will kfree it when done with it. If the caller
7985 * failed the kmalloc call, then it can pass in doms_new == NULL &&
7986 * ndoms_new == 1, and partition_sched_domains() will fallback to
7987 * the single partition 'fallback_doms', it also forces the domains
7990 * If doms_new == NULL it will be replaced with cpu_online_mask.
7991 * ndoms_new == 0 is a special case for destroying existing domains,
7992 * and it will not create the default domain.
7994 * Call with hotplug lock held
7996 /* FIXME: Change to struct cpumask *doms_new[] */
7997 void partition_sched_domains(int ndoms_new, struct cpumask *doms_new,
7998 struct sched_domain_attr *dattr_new)
8003 mutex_lock(&sched_domains_mutex);
8005 /* always unregister in case we don't destroy any domains */
8006 unregister_sched_domain_sysctl();
8008 /* Let architecture update cpu core mappings. */
8009 new_topology = arch_update_cpu_topology();
8011 n = doms_new ? ndoms_new : 0;
8013 /* Destroy deleted domains */
8014 for (i = 0; i < ndoms_cur; i++) {
8015 for (j = 0; j < n && !new_topology; j++) {
8016 if (cpumask_equal(&doms_cur[i], &doms_new[j])
8017 && dattrs_equal(dattr_cur, i, dattr_new, j))
8020 /* no match - a current sched domain not in new doms_new[] */
8021 detach_destroy_domains(doms_cur + i);
8026 if (doms_new == NULL) {
8028 doms_new = fallback_doms;
8029 cpumask_andnot(&doms_new[0], cpu_online_mask, cpu_isolated_map);
8030 WARN_ON_ONCE(dattr_new);
8033 /* Build new domains */
8034 for (i = 0; i < ndoms_new; i++) {
8035 for (j = 0; j < ndoms_cur && !new_topology; j++) {
8036 if (cpumask_equal(&doms_new[i], &doms_cur[j])
8037 && dattrs_equal(dattr_new, i, dattr_cur, j))
8040 /* no match - add a new doms_new */
8041 __build_sched_domains(doms_new + i,
8042 dattr_new ? dattr_new + i : NULL);
8047 /* Remember the new sched domains */
8048 if (doms_cur != fallback_doms)
8050 kfree(dattr_cur); /* kfree(NULL) is safe */
8051 doms_cur = doms_new;
8052 dattr_cur = dattr_new;
8053 ndoms_cur = ndoms_new;
8055 register_sched_domain_sysctl();
8057 mutex_unlock(&sched_domains_mutex);
8060 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
8061 static void arch_reinit_sched_domains(void)
8065 /* Destroy domains first to force the rebuild */
8066 partition_sched_domains(0, NULL, NULL);
8068 rebuild_sched_domains();
8072 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
8074 unsigned int level = 0;
8076 if (sscanf(buf, "%u", &level) != 1)
8080 * level is always be positive so don't check for
8081 * level < POWERSAVINGS_BALANCE_NONE which is 0
8082 * What happens on 0 or 1 byte write,
8083 * need to check for count as well?
8086 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
8090 sched_smt_power_savings = level;
8092 sched_mc_power_savings = level;
8094 arch_reinit_sched_domains();
8099 #ifdef CONFIG_SCHED_MC
8100 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
8103 return sprintf(page, "%u\n", sched_mc_power_savings);
8105 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
8106 const char *buf, size_t count)
8108 return sched_power_savings_store(buf, count, 0);
8110 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
8111 sched_mc_power_savings_show,
8112 sched_mc_power_savings_store);
8115 #ifdef CONFIG_SCHED_SMT
8116 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
8119 return sprintf(page, "%u\n", sched_smt_power_savings);
8121 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
8122 const char *buf, size_t count)
8124 return sched_power_savings_store(buf, count, 1);
8126 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
8127 sched_smt_power_savings_show,
8128 sched_smt_power_savings_store);
8131 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
8135 #ifdef CONFIG_SCHED_SMT
8137 err = sysfs_create_file(&cls->kset.kobj,
8138 &attr_sched_smt_power_savings.attr);
8140 #ifdef CONFIG_SCHED_MC
8141 if (!err && mc_capable())
8142 err = sysfs_create_file(&cls->kset.kobj,
8143 &attr_sched_mc_power_savings.attr);
8147 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
8149 #ifndef CONFIG_CPUSETS
8151 * Add online and remove offline CPUs from the scheduler domains.
8152 * When cpusets are enabled they take over this function.
8154 static int update_sched_domains(struct notifier_block *nfb,
8155 unsigned long action, void *hcpu)
8159 case CPU_ONLINE_FROZEN:
8161 case CPU_DEAD_FROZEN:
8162 partition_sched_domains(1, NULL, NULL);
8171 static int update_runtime(struct notifier_block *nfb,
8172 unsigned long action, void *hcpu)
8174 int cpu = (int)(long)hcpu;
8177 case CPU_DOWN_PREPARE:
8178 case CPU_DOWN_PREPARE_FROZEN:
8179 disable_runtime(cpu_rq(cpu));
8182 case CPU_DOWN_FAILED:
8183 case CPU_DOWN_FAILED_FROZEN:
8185 case CPU_ONLINE_FROZEN:
8186 enable_runtime(cpu_rq(cpu));
8194 void __init sched_init_smp(void)
8196 cpumask_var_t non_isolated_cpus;
8198 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
8200 #if defined(CONFIG_NUMA)
8201 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
8203 BUG_ON(sched_group_nodes_bycpu == NULL);
8206 mutex_lock(&sched_domains_mutex);
8207 arch_init_sched_domains(cpu_online_mask);
8208 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
8209 if (cpumask_empty(non_isolated_cpus))
8210 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
8211 mutex_unlock(&sched_domains_mutex);
8214 #ifndef CONFIG_CPUSETS
8215 /* XXX: Theoretical race here - CPU may be hotplugged now */
8216 hotcpu_notifier(update_sched_domains, 0);
8219 /* RT runtime code needs to handle some hotplug events */
8220 hotcpu_notifier(update_runtime, 0);
8224 /* Move init over to a non-isolated CPU */
8225 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
8227 sched_init_granularity();
8228 free_cpumask_var(non_isolated_cpus);
8230 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
8231 init_sched_rt_class();
8234 void __init sched_init_smp(void)
8236 sched_init_granularity();
8238 #endif /* CONFIG_SMP */
8240 int in_sched_functions(unsigned long addr)
8242 return in_lock_functions(addr) ||
8243 (addr >= (unsigned long)__sched_text_start
8244 && addr < (unsigned long)__sched_text_end);
8247 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8249 cfs_rq->tasks_timeline = RB_ROOT;
8250 INIT_LIST_HEAD(&cfs_rq->tasks);
8251 #ifdef CONFIG_FAIR_GROUP_SCHED
8254 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8257 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8259 struct rt_prio_array *array;
8262 array = &rt_rq->active;
8263 for (i = 0; i < MAX_RT_PRIO; i++) {
8264 INIT_LIST_HEAD(array->queue + i);
8265 __clear_bit(i, array->bitmap);
8267 /* delimiter for bitsearch: */
8268 __set_bit(MAX_RT_PRIO, array->bitmap);
8270 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8271 rt_rq->highest_prio.curr = MAX_RT_PRIO;
8273 rt_rq->highest_prio.next = MAX_RT_PRIO;
8277 rt_rq->rt_nr_migratory = 0;
8278 rt_rq->overloaded = 0;
8279 plist_head_init(&rq->rt.pushable_tasks, &rq->lock);
8283 rt_rq->rt_throttled = 0;
8284 rt_rq->rt_runtime = 0;
8285 spin_lock_init(&rt_rq->rt_runtime_lock);
8287 #ifdef CONFIG_RT_GROUP_SCHED
8288 rt_rq->rt_nr_boosted = 0;
8293 #ifdef CONFIG_FAIR_GROUP_SCHED
8294 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8295 struct sched_entity *se, int cpu, int add,
8296 struct sched_entity *parent)
8298 struct rq *rq = cpu_rq(cpu);
8299 tg->cfs_rq[cpu] = cfs_rq;
8300 init_cfs_rq(cfs_rq, rq);
8303 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8306 /* se could be NULL for init_task_group */
8311 se->cfs_rq = &rq->cfs;
8313 se->cfs_rq = parent->my_q;
8316 se->load.weight = tg->shares;
8317 se->load.inv_weight = 0;
8318 se->parent = parent;
8322 #ifdef CONFIG_RT_GROUP_SCHED
8323 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8324 struct sched_rt_entity *rt_se, int cpu, int add,
8325 struct sched_rt_entity *parent)
8327 struct rq *rq = cpu_rq(cpu);
8329 tg->rt_rq[cpu] = rt_rq;
8330 init_rt_rq(rt_rq, rq);
8332 rt_rq->rt_se = rt_se;
8333 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8335 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8337 tg->rt_se[cpu] = rt_se;
8342 rt_se->rt_rq = &rq->rt;
8344 rt_se->rt_rq = parent->my_q;
8346 rt_se->my_q = rt_rq;
8347 rt_se->parent = parent;
8348 INIT_LIST_HEAD(&rt_se->run_list);
8352 void __init sched_init(void)
8355 unsigned long alloc_size = 0, ptr;
8357 #ifdef CONFIG_FAIR_GROUP_SCHED
8358 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8360 #ifdef CONFIG_RT_GROUP_SCHED
8361 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8363 #ifdef CONFIG_USER_SCHED
8367 * As sched_init() is called before page_alloc is setup,
8368 * we use alloc_bootmem().
8371 ptr = (unsigned long)alloc_bootmem(alloc_size);
8373 #ifdef CONFIG_FAIR_GROUP_SCHED
8374 init_task_group.se = (struct sched_entity **)ptr;
8375 ptr += nr_cpu_ids * sizeof(void **);
8377 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8378 ptr += nr_cpu_ids * sizeof(void **);
8380 #ifdef CONFIG_USER_SCHED
8381 root_task_group.se = (struct sched_entity **)ptr;
8382 ptr += nr_cpu_ids * sizeof(void **);
8384 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8385 ptr += nr_cpu_ids * sizeof(void **);
8386 #endif /* CONFIG_USER_SCHED */
8387 #endif /* CONFIG_FAIR_GROUP_SCHED */
8388 #ifdef CONFIG_RT_GROUP_SCHED
8389 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8390 ptr += nr_cpu_ids * sizeof(void **);
8392 init_task_group.rt_rq = (struct rt_rq **)ptr;
8393 ptr += nr_cpu_ids * sizeof(void **);
8395 #ifdef CONFIG_USER_SCHED
8396 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8397 ptr += nr_cpu_ids * sizeof(void **);
8399 root_task_group.rt_rq = (struct rt_rq **)ptr;
8400 ptr += nr_cpu_ids * sizeof(void **);
8401 #endif /* CONFIG_USER_SCHED */
8402 #endif /* CONFIG_RT_GROUP_SCHED */
8406 init_defrootdomain();
8409 init_rt_bandwidth(&def_rt_bandwidth,
8410 global_rt_period(), global_rt_runtime());
8412 #ifdef CONFIG_RT_GROUP_SCHED
8413 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8414 global_rt_period(), global_rt_runtime());
8415 #ifdef CONFIG_USER_SCHED
8416 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8417 global_rt_period(), RUNTIME_INF);
8418 #endif /* CONFIG_USER_SCHED */
8419 #endif /* CONFIG_RT_GROUP_SCHED */
8421 #ifdef CONFIG_GROUP_SCHED
8422 list_add(&init_task_group.list, &task_groups);
8423 INIT_LIST_HEAD(&init_task_group.children);
8425 #ifdef CONFIG_USER_SCHED
8426 INIT_LIST_HEAD(&root_task_group.children);
8427 init_task_group.parent = &root_task_group;
8428 list_add(&init_task_group.siblings, &root_task_group.children);
8429 #endif /* CONFIG_USER_SCHED */
8430 #endif /* CONFIG_GROUP_SCHED */
8432 for_each_possible_cpu(i) {
8436 spin_lock_init(&rq->lock);
8438 init_cfs_rq(&rq->cfs, rq);
8439 init_rt_rq(&rq->rt, rq);
8440 #ifdef CONFIG_FAIR_GROUP_SCHED
8441 init_task_group.shares = init_task_group_load;
8442 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8443 #ifdef CONFIG_CGROUP_SCHED
8445 * How much cpu bandwidth does init_task_group get?
8447 * In case of task-groups formed thr' the cgroup filesystem, it
8448 * gets 100% of the cpu resources in the system. This overall
8449 * system cpu resource is divided among the tasks of
8450 * init_task_group and its child task-groups in a fair manner,
8451 * based on each entity's (task or task-group's) weight
8452 * (se->load.weight).
8454 * In other words, if init_task_group has 10 tasks of weight
8455 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8456 * then A0's share of the cpu resource is:
8458 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8460 * We achieve this by letting init_task_group's tasks sit
8461 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8463 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8464 #elif defined CONFIG_USER_SCHED
8465 root_task_group.shares = NICE_0_LOAD;
8466 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8468 * In case of task-groups formed thr' the user id of tasks,
8469 * init_task_group represents tasks belonging to root user.
8470 * Hence it forms a sibling of all subsequent groups formed.
8471 * In this case, init_task_group gets only a fraction of overall
8472 * system cpu resource, based on the weight assigned to root
8473 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8474 * by letting tasks of init_task_group sit in a separate cfs_rq
8475 * (init_cfs_rq) and having one entity represent this group of
8476 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8478 init_tg_cfs_entry(&init_task_group,
8479 &per_cpu(init_cfs_rq, i),
8480 &per_cpu(init_sched_entity, i), i, 1,
8481 root_task_group.se[i]);
8484 #endif /* CONFIG_FAIR_GROUP_SCHED */
8486 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8487 #ifdef CONFIG_RT_GROUP_SCHED
8488 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8489 #ifdef CONFIG_CGROUP_SCHED
8490 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8491 #elif defined CONFIG_USER_SCHED
8492 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8493 init_tg_rt_entry(&init_task_group,
8494 &per_cpu(init_rt_rq, i),
8495 &per_cpu(init_sched_rt_entity, i), i, 1,
8496 root_task_group.rt_se[i]);
8500 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8501 rq->cpu_load[j] = 0;
8505 rq->active_balance = 0;
8506 rq->next_balance = jiffies;
8510 rq->migration_thread = NULL;
8511 INIT_LIST_HEAD(&rq->migration_queue);
8512 rq_attach_root(rq, &def_root_domain);
8515 atomic_set(&rq->nr_iowait, 0);
8518 set_load_weight(&init_task);
8520 #ifdef CONFIG_PREEMPT_NOTIFIERS
8521 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8525 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
8528 #ifdef CONFIG_RT_MUTEXES
8529 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8533 * The boot idle thread does lazy MMU switching as well:
8535 atomic_inc(&init_mm.mm_count);
8536 enter_lazy_tlb(&init_mm, current);
8539 * Make us the idle thread. Technically, schedule() should not be
8540 * called from this thread, however somewhere below it might be,
8541 * but because we are the idle thread, we just pick up running again
8542 * when this runqueue becomes "idle".
8544 init_idle(current, smp_processor_id());
8546 * During early bootup we pretend to be a normal task:
8548 current->sched_class = &fair_sched_class;
8550 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
8551 alloc_bootmem_cpumask_var(&nohz_cpu_mask);
8554 alloc_bootmem_cpumask_var(&nohz.cpu_mask);
8556 alloc_bootmem_cpumask_var(&cpu_isolated_map);
8559 scheduler_running = 1;
8562 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8563 void __might_sleep(char *file, int line)
8566 static unsigned long prev_jiffy; /* ratelimiting */
8568 if ((!in_atomic() && !irqs_disabled()) ||
8569 system_state != SYSTEM_RUNNING || oops_in_progress)
8571 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8573 prev_jiffy = jiffies;
8576 "BUG: sleeping function called from invalid context at %s:%d\n",
8579 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8580 in_atomic(), irqs_disabled(),
8581 current->pid, current->comm);
8583 debug_show_held_locks(current);
8584 if (irqs_disabled())
8585 print_irqtrace_events(current);
8589 EXPORT_SYMBOL(__might_sleep);
8592 #ifdef CONFIG_MAGIC_SYSRQ
8593 static void normalize_task(struct rq *rq, struct task_struct *p)
8597 update_rq_clock(rq);
8598 on_rq = p->se.on_rq;
8600 deactivate_task(rq, p, 0);
8601 __setscheduler(rq, p, SCHED_NORMAL, 0);
8603 activate_task(rq, p, 0);
8604 resched_task(rq->curr);
8608 void normalize_rt_tasks(void)
8610 struct task_struct *g, *p;
8611 unsigned long flags;
8614 read_lock_irqsave(&tasklist_lock, flags);
8615 do_each_thread(g, p) {
8617 * Only normalize user tasks:
8622 p->se.exec_start = 0;
8623 #ifdef CONFIG_SCHEDSTATS
8624 p->se.wait_start = 0;
8625 p->se.sleep_start = 0;
8626 p->se.block_start = 0;
8631 * Renice negative nice level userspace
8634 if (TASK_NICE(p) < 0 && p->mm)
8635 set_user_nice(p, 0);
8639 spin_lock(&p->pi_lock);
8640 rq = __task_rq_lock(p);
8642 normalize_task(rq, p);
8644 __task_rq_unlock(rq);
8645 spin_unlock(&p->pi_lock);
8646 } while_each_thread(g, p);
8648 read_unlock_irqrestore(&tasklist_lock, flags);
8651 #endif /* CONFIG_MAGIC_SYSRQ */
8655 * These functions are only useful for the IA64 MCA handling.
8657 * They can only be called when the whole system has been
8658 * stopped - every CPU needs to be quiescent, and no scheduling
8659 * activity can take place. Using them for anything else would
8660 * be a serious bug, and as a result, they aren't even visible
8661 * under any other configuration.
8665 * curr_task - return the current task for a given cpu.
8666 * @cpu: the processor in question.
8668 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8670 struct task_struct *curr_task(int cpu)
8672 return cpu_curr(cpu);
8676 * set_curr_task - set the current task for a given cpu.
8677 * @cpu: the processor in question.
8678 * @p: the task pointer to set.
8680 * Description: This function must only be used when non-maskable interrupts
8681 * are serviced on a separate stack. It allows the architecture to switch the
8682 * notion of the current task on a cpu in a non-blocking manner. This function
8683 * must be called with all CPU's synchronized, and interrupts disabled, the
8684 * and caller must save the original value of the current task (see
8685 * curr_task() above) and restore that value before reenabling interrupts and
8686 * re-starting the system.
8688 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8690 void set_curr_task(int cpu, struct task_struct *p)
8697 #ifdef CONFIG_FAIR_GROUP_SCHED
8698 static void free_fair_sched_group(struct task_group *tg)
8702 for_each_possible_cpu(i) {
8704 kfree(tg->cfs_rq[i]);
8714 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8716 struct cfs_rq *cfs_rq;
8717 struct sched_entity *se;
8721 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8724 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8728 tg->shares = NICE_0_LOAD;
8730 for_each_possible_cpu(i) {
8733 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8734 GFP_KERNEL, cpu_to_node(i));
8738 se = kzalloc_node(sizeof(struct sched_entity),
8739 GFP_KERNEL, cpu_to_node(i));
8743 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
8752 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8754 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8755 &cpu_rq(cpu)->leaf_cfs_rq_list);
8758 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8760 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8762 #else /* !CONFG_FAIR_GROUP_SCHED */
8763 static inline void free_fair_sched_group(struct task_group *tg)
8768 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8773 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8777 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8780 #endif /* CONFIG_FAIR_GROUP_SCHED */
8782 #ifdef CONFIG_RT_GROUP_SCHED
8783 static void free_rt_sched_group(struct task_group *tg)
8787 destroy_rt_bandwidth(&tg->rt_bandwidth);
8789 for_each_possible_cpu(i) {
8791 kfree(tg->rt_rq[i]);
8793 kfree(tg->rt_se[i]);
8801 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8803 struct rt_rq *rt_rq;
8804 struct sched_rt_entity *rt_se;
8808 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8811 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8815 init_rt_bandwidth(&tg->rt_bandwidth,
8816 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8818 for_each_possible_cpu(i) {
8821 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8822 GFP_KERNEL, cpu_to_node(i));
8826 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8827 GFP_KERNEL, cpu_to_node(i));
8831 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
8840 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8842 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8843 &cpu_rq(cpu)->leaf_rt_rq_list);
8846 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8848 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8850 #else /* !CONFIG_RT_GROUP_SCHED */
8851 static inline void free_rt_sched_group(struct task_group *tg)
8856 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8861 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8865 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8868 #endif /* CONFIG_RT_GROUP_SCHED */
8870 #ifdef CONFIG_GROUP_SCHED
8871 static void free_sched_group(struct task_group *tg)
8873 free_fair_sched_group(tg);
8874 free_rt_sched_group(tg);
8878 /* allocate runqueue etc for a new task group */
8879 struct task_group *sched_create_group(struct task_group *parent)
8881 struct task_group *tg;
8882 unsigned long flags;
8885 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8887 return ERR_PTR(-ENOMEM);
8889 if (!alloc_fair_sched_group(tg, parent))
8892 if (!alloc_rt_sched_group(tg, parent))
8895 spin_lock_irqsave(&task_group_lock, flags);
8896 for_each_possible_cpu(i) {
8897 register_fair_sched_group(tg, i);
8898 register_rt_sched_group(tg, i);
8900 list_add_rcu(&tg->list, &task_groups);
8902 WARN_ON(!parent); /* root should already exist */
8904 tg->parent = parent;
8905 INIT_LIST_HEAD(&tg->children);
8906 list_add_rcu(&tg->siblings, &parent->children);
8907 spin_unlock_irqrestore(&task_group_lock, flags);
8912 free_sched_group(tg);
8913 return ERR_PTR(-ENOMEM);
8916 /* rcu callback to free various structures associated with a task group */
8917 static void free_sched_group_rcu(struct rcu_head *rhp)
8919 /* now it should be safe to free those cfs_rqs */
8920 free_sched_group(container_of(rhp, struct task_group, rcu));
8923 /* Destroy runqueue etc associated with a task group */
8924 void sched_destroy_group(struct task_group *tg)
8926 unsigned long flags;
8929 spin_lock_irqsave(&task_group_lock, flags);
8930 for_each_possible_cpu(i) {
8931 unregister_fair_sched_group(tg, i);
8932 unregister_rt_sched_group(tg, i);
8934 list_del_rcu(&tg->list);
8935 list_del_rcu(&tg->siblings);
8936 spin_unlock_irqrestore(&task_group_lock, flags);
8938 /* wait for possible concurrent references to cfs_rqs complete */
8939 call_rcu(&tg->rcu, free_sched_group_rcu);
8942 /* change task's runqueue when it moves between groups.
8943 * The caller of this function should have put the task in its new group
8944 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8945 * reflect its new group.
8947 void sched_move_task(struct task_struct *tsk)
8950 unsigned long flags;
8953 rq = task_rq_lock(tsk, &flags);
8955 update_rq_clock(rq);
8957 running = task_current(rq, tsk);
8958 on_rq = tsk->se.on_rq;
8961 dequeue_task(rq, tsk, 0);
8962 if (unlikely(running))
8963 tsk->sched_class->put_prev_task(rq, tsk);
8965 set_task_rq(tsk, task_cpu(tsk));
8967 #ifdef CONFIG_FAIR_GROUP_SCHED
8968 if (tsk->sched_class->moved_group)
8969 tsk->sched_class->moved_group(tsk);
8972 if (unlikely(running))
8973 tsk->sched_class->set_curr_task(rq);
8975 enqueue_task(rq, tsk, 0);
8977 task_rq_unlock(rq, &flags);
8979 #endif /* CONFIG_GROUP_SCHED */
8981 #ifdef CONFIG_FAIR_GROUP_SCHED
8982 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8984 struct cfs_rq *cfs_rq = se->cfs_rq;
8989 dequeue_entity(cfs_rq, se, 0);
8991 se->load.weight = shares;
8992 se->load.inv_weight = 0;
8995 enqueue_entity(cfs_rq, se, 0);
8998 static void set_se_shares(struct sched_entity *se, unsigned long shares)
9000 struct cfs_rq *cfs_rq = se->cfs_rq;
9001 struct rq *rq = cfs_rq->rq;
9002 unsigned long flags;
9004 spin_lock_irqsave(&rq->lock, flags);
9005 __set_se_shares(se, shares);
9006 spin_unlock_irqrestore(&rq->lock, flags);
9009 static DEFINE_MUTEX(shares_mutex);
9011 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
9014 unsigned long flags;
9017 * We can't change the weight of the root cgroup.
9022 if (shares < MIN_SHARES)
9023 shares = MIN_SHARES;
9024 else if (shares > MAX_SHARES)
9025 shares = MAX_SHARES;
9027 mutex_lock(&shares_mutex);
9028 if (tg->shares == shares)
9031 spin_lock_irqsave(&task_group_lock, flags);
9032 for_each_possible_cpu(i)
9033 unregister_fair_sched_group(tg, i);
9034 list_del_rcu(&tg->siblings);
9035 spin_unlock_irqrestore(&task_group_lock, flags);
9037 /* wait for any ongoing reference to this group to finish */
9038 synchronize_sched();
9041 * Now we are free to modify the group's share on each cpu
9042 * w/o tripping rebalance_share or load_balance_fair.
9044 tg->shares = shares;
9045 for_each_possible_cpu(i) {
9049 cfs_rq_set_shares(tg->cfs_rq[i], 0);
9050 set_se_shares(tg->se[i], shares);
9054 * Enable load balance activity on this group, by inserting it back on
9055 * each cpu's rq->leaf_cfs_rq_list.
9057 spin_lock_irqsave(&task_group_lock, flags);
9058 for_each_possible_cpu(i)
9059 register_fair_sched_group(tg, i);
9060 list_add_rcu(&tg->siblings, &tg->parent->children);
9061 spin_unlock_irqrestore(&task_group_lock, flags);
9063 mutex_unlock(&shares_mutex);
9067 unsigned long sched_group_shares(struct task_group *tg)
9073 #ifdef CONFIG_RT_GROUP_SCHED
9075 * Ensure that the real time constraints are schedulable.
9077 static DEFINE_MUTEX(rt_constraints_mutex);
9079 static unsigned long to_ratio(u64 period, u64 runtime)
9081 if (runtime == RUNTIME_INF)
9084 return div64_u64(runtime << 20, period);
9087 /* Must be called with tasklist_lock held */
9088 static inline int tg_has_rt_tasks(struct task_group *tg)
9090 struct task_struct *g, *p;
9092 do_each_thread(g, p) {
9093 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
9095 } while_each_thread(g, p);
9100 struct rt_schedulable_data {
9101 struct task_group *tg;
9106 static int tg_schedulable(struct task_group *tg, void *data)
9108 struct rt_schedulable_data *d = data;
9109 struct task_group *child;
9110 unsigned long total, sum = 0;
9111 u64 period, runtime;
9113 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
9114 runtime = tg->rt_bandwidth.rt_runtime;
9117 period = d->rt_period;
9118 runtime = d->rt_runtime;
9122 * Cannot have more runtime than the period.
9124 if (runtime > period && runtime != RUNTIME_INF)
9128 * Ensure we don't starve existing RT tasks.
9130 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
9133 total = to_ratio(period, runtime);
9136 * Nobody can have more than the global setting allows.
9138 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
9142 * The sum of our children's runtime should not exceed our own.
9144 list_for_each_entry_rcu(child, &tg->children, siblings) {
9145 period = ktime_to_ns(child->rt_bandwidth.rt_period);
9146 runtime = child->rt_bandwidth.rt_runtime;
9148 if (child == d->tg) {
9149 period = d->rt_period;
9150 runtime = d->rt_runtime;
9153 sum += to_ratio(period, runtime);
9162 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
9164 struct rt_schedulable_data data = {
9166 .rt_period = period,
9167 .rt_runtime = runtime,
9170 return walk_tg_tree(tg_schedulable, tg_nop, &data);
9173 static int tg_set_bandwidth(struct task_group *tg,
9174 u64 rt_period, u64 rt_runtime)
9178 mutex_lock(&rt_constraints_mutex);
9179 read_lock(&tasklist_lock);
9180 err = __rt_schedulable(tg, rt_period, rt_runtime);
9184 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
9185 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
9186 tg->rt_bandwidth.rt_runtime = rt_runtime;
9188 for_each_possible_cpu(i) {
9189 struct rt_rq *rt_rq = tg->rt_rq[i];
9191 spin_lock(&rt_rq->rt_runtime_lock);
9192 rt_rq->rt_runtime = rt_runtime;
9193 spin_unlock(&rt_rq->rt_runtime_lock);
9195 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
9197 read_unlock(&tasklist_lock);
9198 mutex_unlock(&rt_constraints_mutex);
9203 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
9205 u64 rt_runtime, rt_period;
9207 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
9208 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
9209 if (rt_runtime_us < 0)
9210 rt_runtime = RUNTIME_INF;
9212 return tg_set_bandwidth(tg, rt_period, rt_runtime);
9215 long sched_group_rt_runtime(struct task_group *tg)
9219 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
9222 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
9223 do_div(rt_runtime_us, NSEC_PER_USEC);
9224 return rt_runtime_us;
9227 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
9229 u64 rt_runtime, rt_period;
9231 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
9232 rt_runtime = tg->rt_bandwidth.rt_runtime;
9237 return tg_set_bandwidth(tg, rt_period, rt_runtime);
9240 long sched_group_rt_period(struct task_group *tg)
9244 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
9245 do_div(rt_period_us, NSEC_PER_USEC);
9246 return rt_period_us;
9249 static int sched_rt_global_constraints(void)
9251 u64 runtime, period;
9254 if (sysctl_sched_rt_period <= 0)
9257 runtime = global_rt_runtime();
9258 period = global_rt_period();
9261 * Sanity check on the sysctl variables.
9263 if (runtime > period && runtime != RUNTIME_INF)
9266 mutex_lock(&rt_constraints_mutex);
9267 read_lock(&tasklist_lock);
9268 ret = __rt_schedulable(NULL, 0, 0);
9269 read_unlock(&tasklist_lock);
9270 mutex_unlock(&rt_constraints_mutex);
9274 #else /* !CONFIG_RT_GROUP_SCHED */
9275 static int sched_rt_global_constraints(void)
9277 unsigned long flags;
9280 if (sysctl_sched_rt_period <= 0)
9283 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9284 for_each_possible_cpu(i) {
9285 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9287 spin_lock(&rt_rq->rt_runtime_lock);
9288 rt_rq->rt_runtime = global_rt_runtime();
9289 spin_unlock(&rt_rq->rt_runtime_lock);
9291 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9295 #endif /* CONFIG_RT_GROUP_SCHED */
9297 int sched_rt_handler(struct ctl_table *table, int write,
9298 struct file *filp, void __user *buffer, size_t *lenp,
9302 int old_period, old_runtime;
9303 static DEFINE_MUTEX(mutex);
9306 old_period = sysctl_sched_rt_period;
9307 old_runtime = sysctl_sched_rt_runtime;
9309 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9311 if (!ret && write) {
9312 ret = sched_rt_global_constraints();
9314 sysctl_sched_rt_period = old_period;
9315 sysctl_sched_rt_runtime = old_runtime;
9317 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9318 def_rt_bandwidth.rt_period =
9319 ns_to_ktime(global_rt_period());
9322 mutex_unlock(&mutex);
9327 #ifdef CONFIG_CGROUP_SCHED
9329 /* return corresponding task_group object of a cgroup */
9330 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9332 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9333 struct task_group, css);
9336 static struct cgroup_subsys_state *
9337 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9339 struct task_group *tg, *parent;
9341 if (!cgrp->parent) {
9342 /* This is early initialization for the top cgroup */
9343 return &init_task_group.css;
9346 parent = cgroup_tg(cgrp->parent);
9347 tg = sched_create_group(parent);
9349 return ERR_PTR(-ENOMEM);
9355 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9357 struct task_group *tg = cgroup_tg(cgrp);
9359 sched_destroy_group(tg);
9363 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9364 struct task_struct *tsk)
9366 #ifdef CONFIG_RT_GROUP_SCHED
9367 /* Don't accept realtime tasks when there is no way for them to run */
9368 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9371 /* We don't support RT-tasks being in separate groups */
9372 if (tsk->sched_class != &fair_sched_class)
9380 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9381 struct cgroup *old_cont, struct task_struct *tsk)
9383 sched_move_task(tsk);
9386 #ifdef CONFIG_FAIR_GROUP_SCHED
9387 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9390 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9393 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9395 struct task_group *tg = cgroup_tg(cgrp);
9397 return (u64) tg->shares;
9399 #endif /* CONFIG_FAIR_GROUP_SCHED */
9401 #ifdef CONFIG_RT_GROUP_SCHED
9402 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9405 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9408 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9410 return sched_group_rt_runtime(cgroup_tg(cgrp));
9413 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9416 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9419 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9421 return sched_group_rt_period(cgroup_tg(cgrp));
9423 #endif /* CONFIG_RT_GROUP_SCHED */
9425 static struct cftype cpu_files[] = {
9426 #ifdef CONFIG_FAIR_GROUP_SCHED
9429 .read_u64 = cpu_shares_read_u64,
9430 .write_u64 = cpu_shares_write_u64,
9433 #ifdef CONFIG_RT_GROUP_SCHED
9435 .name = "rt_runtime_us",
9436 .read_s64 = cpu_rt_runtime_read,
9437 .write_s64 = cpu_rt_runtime_write,
9440 .name = "rt_period_us",
9441 .read_u64 = cpu_rt_period_read_uint,
9442 .write_u64 = cpu_rt_period_write_uint,
9447 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9449 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9452 struct cgroup_subsys cpu_cgroup_subsys = {
9454 .create = cpu_cgroup_create,
9455 .destroy = cpu_cgroup_destroy,
9456 .can_attach = cpu_cgroup_can_attach,
9457 .attach = cpu_cgroup_attach,
9458 .populate = cpu_cgroup_populate,
9459 .subsys_id = cpu_cgroup_subsys_id,
9463 #endif /* CONFIG_CGROUP_SCHED */
9465 #ifdef CONFIG_CGROUP_CPUACCT
9468 * CPU accounting code for task groups.
9470 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9471 * (balbir@in.ibm.com).
9474 /* track cpu usage of a group of tasks and its child groups */
9476 struct cgroup_subsys_state css;
9477 /* cpuusage holds pointer to a u64-type object on every cpu */
9479 struct cpuacct *parent;
9482 struct cgroup_subsys cpuacct_subsys;
9484 /* return cpu accounting group corresponding to this container */
9485 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9487 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9488 struct cpuacct, css);
9491 /* return cpu accounting group to which this task belongs */
9492 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9494 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9495 struct cpuacct, css);
9498 /* create a new cpu accounting group */
9499 static struct cgroup_subsys_state *cpuacct_create(
9500 struct cgroup_subsys *ss, struct cgroup *cgrp)
9502 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9505 return ERR_PTR(-ENOMEM);
9507 ca->cpuusage = alloc_percpu(u64);
9508 if (!ca->cpuusage) {
9510 return ERR_PTR(-ENOMEM);
9514 ca->parent = cgroup_ca(cgrp->parent);
9519 /* destroy an existing cpu accounting group */
9521 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9523 struct cpuacct *ca = cgroup_ca(cgrp);
9525 free_percpu(ca->cpuusage);
9529 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
9531 u64 *cpuusage = percpu_ptr(ca->cpuusage, cpu);
9534 #ifndef CONFIG_64BIT
9536 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
9538 spin_lock_irq(&cpu_rq(cpu)->lock);
9540 spin_unlock_irq(&cpu_rq(cpu)->lock);
9548 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
9550 u64 *cpuusage = percpu_ptr(ca->cpuusage, cpu);
9552 #ifndef CONFIG_64BIT
9554 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
9556 spin_lock_irq(&cpu_rq(cpu)->lock);
9558 spin_unlock_irq(&cpu_rq(cpu)->lock);
9564 /* return total cpu usage (in nanoseconds) of a group */
9565 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9567 struct cpuacct *ca = cgroup_ca(cgrp);
9568 u64 totalcpuusage = 0;
9571 for_each_present_cpu(i)
9572 totalcpuusage += cpuacct_cpuusage_read(ca, i);
9574 return totalcpuusage;
9577 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9580 struct cpuacct *ca = cgroup_ca(cgrp);
9589 for_each_present_cpu(i)
9590 cpuacct_cpuusage_write(ca, i, 0);
9596 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
9599 struct cpuacct *ca = cgroup_ca(cgroup);
9603 for_each_present_cpu(i) {
9604 percpu = cpuacct_cpuusage_read(ca, i);
9605 seq_printf(m, "%llu ", (unsigned long long) percpu);
9607 seq_printf(m, "\n");
9611 static struct cftype files[] = {
9614 .read_u64 = cpuusage_read,
9615 .write_u64 = cpuusage_write,
9618 .name = "usage_percpu",
9619 .read_seq_string = cpuacct_percpu_seq_read,
9624 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9626 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9630 * charge this task's execution time to its accounting group.
9632 * called with rq->lock held.
9634 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9639 if (!cpuacct_subsys.active)
9642 cpu = task_cpu(tsk);
9645 for (; ca; ca = ca->parent) {
9646 u64 *cpuusage = percpu_ptr(ca->cpuusage, cpu);
9647 *cpuusage += cputime;
9651 struct cgroup_subsys cpuacct_subsys = {
9653 .create = cpuacct_create,
9654 .destroy = cpuacct_destroy,
9655 .populate = cpuacct_populate,
9656 .subsys_id = cpuacct_subsys_id,
9658 #endif /* CONFIG_CGROUP_CPUACCT */