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 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
132 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
133 * Since cpu_power is a 'constant', we can use a reciprocal divide.
135 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
137 return reciprocal_divide(load, sg->reciprocal_cpu_power);
141 * Each time a sched group cpu_power is changed,
142 * we must compute its reciprocal value
144 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
146 sg->__cpu_power += val;
147 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
151 static inline int rt_policy(int policy)
153 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
158 static inline int task_has_rt_policy(struct task_struct *p)
160 return rt_policy(p->policy);
164 * This is the priority-queue data structure of the RT scheduling class:
166 struct rt_prio_array {
167 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
168 struct list_head queue[MAX_RT_PRIO];
171 struct rt_bandwidth {
172 /* nests inside the rq lock: */
173 spinlock_t rt_runtime_lock;
176 struct hrtimer rt_period_timer;
179 static struct rt_bandwidth def_rt_bandwidth;
181 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
183 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
185 struct rt_bandwidth *rt_b =
186 container_of(timer, struct rt_bandwidth, rt_period_timer);
192 now = hrtimer_cb_get_time(timer);
193 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
198 idle = do_sched_rt_period_timer(rt_b, overrun);
201 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
205 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
207 rt_b->rt_period = ns_to_ktime(period);
208 rt_b->rt_runtime = runtime;
210 spin_lock_init(&rt_b->rt_runtime_lock);
212 hrtimer_init(&rt_b->rt_period_timer,
213 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
214 rt_b->rt_period_timer.function = sched_rt_period_timer;
217 static inline int rt_bandwidth_enabled(void)
219 return sysctl_sched_rt_runtime >= 0;
222 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
226 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
229 if (hrtimer_active(&rt_b->rt_period_timer))
232 spin_lock(&rt_b->rt_runtime_lock);
234 if (hrtimer_active(&rt_b->rt_period_timer))
237 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
238 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
239 hrtimer_start_expires(&rt_b->rt_period_timer,
242 spin_unlock(&rt_b->rt_runtime_lock);
245 #ifdef CONFIG_RT_GROUP_SCHED
246 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
248 hrtimer_cancel(&rt_b->rt_period_timer);
253 * sched_domains_mutex serializes calls to arch_init_sched_domains,
254 * detach_destroy_domains and partition_sched_domains.
256 static DEFINE_MUTEX(sched_domains_mutex);
258 #ifdef CONFIG_GROUP_SCHED
260 #include <linux/cgroup.h>
264 static LIST_HEAD(task_groups);
266 /* task group related information */
268 #ifdef CONFIG_CGROUP_SCHED
269 struct cgroup_subsys_state css;
272 #ifdef CONFIG_USER_SCHED
276 #ifdef CONFIG_FAIR_GROUP_SCHED
277 /* schedulable entities of this group on each cpu */
278 struct sched_entity **se;
279 /* runqueue "owned" by this group on each cpu */
280 struct cfs_rq **cfs_rq;
281 unsigned long shares;
284 #ifdef CONFIG_RT_GROUP_SCHED
285 struct sched_rt_entity **rt_se;
286 struct rt_rq **rt_rq;
288 struct rt_bandwidth rt_bandwidth;
292 struct list_head list;
294 struct task_group *parent;
295 struct list_head siblings;
296 struct list_head children;
299 #ifdef CONFIG_USER_SCHED
301 /* Helper function to pass uid information to create_sched_user() */
302 void set_tg_uid(struct user_struct *user)
304 user->tg->uid = user->uid;
309 * Every UID task group (including init_task_group aka UID-0) will
310 * be a child to this group.
312 struct task_group root_task_group;
314 #ifdef CONFIG_FAIR_GROUP_SCHED
315 /* Default task group's sched entity on each cpu */
316 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
317 /* Default task group's cfs_rq on each cpu */
318 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
319 #endif /* CONFIG_FAIR_GROUP_SCHED */
321 #ifdef CONFIG_RT_GROUP_SCHED
322 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
323 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
324 #endif /* CONFIG_RT_GROUP_SCHED */
325 #else /* !CONFIG_USER_SCHED */
326 #define root_task_group init_task_group
327 #endif /* CONFIG_USER_SCHED */
329 /* task_group_lock serializes add/remove of task groups and also changes to
330 * a task group's cpu shares.
332 static DEFINE_SPINLOCK(task_group_lock);
335 static int root_task_group_empty(void)
337 return list_empty(&root_task_group.children);
341 #ifdef CONFIG_FAIR_GROUP_SCHED
342 #ifdef CONFIG_USER_SCHED
343 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
344 #else /* !CONFIG_USER_SCHED */
345 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
346 #endif /* CONFIG_USER_SCHED */
349 * A weight of 0 or 1 can cause arithmetics problems.
350 * A weight of a cfs_rq is the sum of weights of which entities
351 * are queued on this cfs_rq, so a weight of a entity should not be
352 * too large, so as the shares value of a task group.
353 * (The default weight is 1024 - so there's no practical
354 * limitation from this.)
357 #define MAX_SHARES (1UL << 18)
359 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
362 /* Default task group.
363 * Every task in system belong to this group at bootup.
365 struct task_group init_task_group;
367 /* return group to which a task belongs */
368 static inline struct task_group *task_group(struct task_struct *p)
370 struct task_group *tg;
372 #ifdef CONFIG_USER_SCHED
374 tg = __task_cred(p)->user->tg;
376 #elif defined(CONFIG_CGROUP_SCHED)
377 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
378 struct task_group, css);
380 tg = &init_task_group;
385 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
386 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
388 #ifdef CONFIG_FAIR_GROUP_SCHED
389 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
390 p->se.parent = task_group(p)->se[cpu];
393 #ifdef CONFIG_RT_GROUP_SCHED
394 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
395 p->rt.parent = task_group(p)->rt_se[cpu];
402 static int root_task_group_empty(void)
408 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
409 static inline struct task_group *task_group(struct task_struct *p)
414 #endif /* CONFIG_GROUP_SCHED */
416 /* CFS-related fields in a runqueue */
418 struct load_weight load;
419 unsigned long nr_running;
424 struct rb_root tasks_timeline;
425 struct rb_node *rb_leftmost;
427 struct list_head tasks;
428 struct list_head *balance_iterator;
431 * 'curr' points to currently running entity on this cfs_rq.
432 * It is set to NULL otherwise (i.e when none are currently running).
434 struct sched_entity *curr, *next, *last;
436 unsigned int nr_spread_over;
438 #ifdef CONFIG_FAIR_GROUP_SCHED
439 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
442 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
443 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
444 * (like users, containers etc.)
446 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
447 * list is used during load balance.
449 struct list_head leaf_cfs_rq_list;
450 struct task_group *tg; /* group that "owns" this runqueue */
454 * the part of load.weight contributed by tasks
456 unsigned long task_weight;
459 * h_load = weight * f(tg)
461 * Where f(tg) is the recursive weight fraction assigned to
464 unsigned long h_load;
467 * this cpu's part of tg->shares
469 unsigned long shares;
472 * load.weight at the time we set shares
474 unsigned long rq_weight;
479 /* Real-Time classes' related field in a runqueue: */
481 struct rt_prio_array active;
482 unsigned long rt_nr_running;
483 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
485 int curr; /* highest queued rt task prio */
487 int next; /* next highest */
492 unsigned long rt_nr_migratory;
494 struct plist_head pushable_tasks;
499 /* Nests inside the rq lock: */
500 spinlock_t rt_runtime_lock;
502 #ifdef CONFIG_RT_GROUP_SCHED
503 unsigned long rt_nr_boosted;
506 struct list_head leaf_rt_rq_list;
507 struct task_group *tg;
508 struct sched_rt_entity *rt_se;
515 * We add the notion of a root-domain which will be used to define per-domain
516 * variables. Each exclusive cpuset essentially defines an island domain by
517 * fully partitioning the member cpus from any other cpuset. Whenever a new
518 * exclusive cpuset is created, we also create and attach a new root-domain
525 cpumask_var_t online;
528 * The "RT overload" flag: it gets set if a CPU has more than
529 * one runnable RT task.
531 cpumask_var_t rto_mask;
534 struct cpupri cpupri;
536 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
538 * Preferred wake up cpu nominated by sched_mc balance that will be
539 * used when most cpus are idle in the system indicating overall very
540 * low system utilisation. Triggered at POWERSAVINGS_BALANCE_WAKEUP(2)
542 unsigned int sched_mc_preferred_wakeup_cpu;
547 * By default the system creates a single root-domain with all cpus as
548 * members (mimicking the global state we have today).
550 static struct root_domain def_root_domain;
555 * This is the main, per-CPU runqueue data structure.
557 * Locking rule: those places that want to lock multiple runqueues
558 * (such as the load balancing or the thread migration code), lock
559 * acquire operations must be ordered by ascending &runqueue.
566 * nr_running and cpu_load should be in the same cacheline because
567 * remote CPUs use both these fields when doing load calculation.
569 unsigned long nr_running;
570 #define CPU_LOAD_IDX_MAX 5
571 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
573 unsigned long last_tick_seen;
574 unsigned char in_nohz_recently;
576 /* capture load from *all* tasks on this cpu: */
577 struct load_weight load;
578 unsigned long nr_load_updates;
580 u64 nr_migrations_in;
585 #ifdef CONFIG_FAIR_GROUP_SCHED
586 /* list of leaf cfs_rq on this cpu: */
587 struct list_head leaf_cfs_rq_list;
589 #ifdef CONFIG_RT_GROUP_SCHED
590 struct list_head leaf_rt_rq_list;
594 * This is part of a global counter where only the total sum
595 * over all CPUs matters. A task can increase this counter on
596 * one CPU and if it got migrated afterwards it may decrease
597 * it on another CPU. Always updated under the runqueue lock:
599 unsigned long nr_uninterruptible;
601 struct task_struct *curr, *idle;
602 unsigned long next_balance;
603 struct mm_struct *prev_mm;
610 struct root_domain *rd;
611 struct sched_domain *sd;
613 unsigned char idle_at_tick;
614 /* For active balancing */
617 /* cpu of this runqueue: */
621 unsigned long avg_load_per_task;
623 struct task_struct *migration_thread;
624 struct list_head migration_queue;
627 #ifdef CONFIG_SCHED_HRTICK
629 int hrtick_csd_pending;
630 struct call_single_data hrtick_csd;
632 struct hrtimer hrtick_timer;
635 #ifdef CONFIG_SCHEDSTATS
637 struct sched_info rq_sched_info;
638 unsigned long long rq_cpu_time;
639 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
641 /* sys_sched_yield() stats */
642 unsigned int yld_count;
644 /* schedule() stats */
645 unsigned int sched_switch;
646 unsigned int sched_count;
647 unsigned int sched_goidle;
649 /* try_to_wake_up() stats */
650 unsigned int ttwu_count;
651 unsigned int ttwu_local;
654 unsigned int bkl_count;
658 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
660 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p, int sync)
662 rq->curr->sched_class->check_preempt_curr(rq, p, sync);
665 static inline int cpu_of(struct rq *rq)
675 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
676 * See detach_destroy_domains: synchronize_sched for details.
678 * The domain tree of any CPU may only be accessed from within
679 * preempt-disabled sections.
681 #define for_each_domain(cpu, __sd) \
682 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
684 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
685 #define this_rq() (&__get_cpu_var(runqueues))
686 #define task_rq(p) cpu_rq(task_cpu(p))
687 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
689 inline void update_rq_clock(struct rq *rq)
691 rq->clock = sched_clock_cpu(cpu_of(rq));
695 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
697 #ifdef CONFIG_SCHED_DEBUG
698 # define const_debug __read_mostly
700 # define const_debug static const
706 * Returns true if the current cpu runqueue is locked.
707 * This interface allows printk to be called with the runqueue lock
708 * held and know whether or not it is OK to wake up the klogd.
710 int runqueue_is_locked(void)
713 struct rq *rq = cpu_rq(cpu);
716 ret = spin_is_locked(&rq->lock);
722 * Debugging: various feature bits
725 #define SCHED_FEAT(name, enabled) \
726 __SCHED_FEAT_##name ,
729 #include "sched_features.h"
734 #define SCHED_FEAT(name, enabled) \
735 (1UL << __SCHED_FEAT_##name) * enabled |
737 const_debug unsigned int sysctl_sched_features =
738 #include "sched_features.h"
743 #ifdef CONFIG_SCHED_DEBUG
744 #define SCHED_FEAT(name, enabled) \
747 static __read_mostly char *sched_feat_names[] = {
748 #include "sched_features.h"
754 static int sched_feat_show(struct seq_file *m, void *v)
758 for (i = 0; sched_feat_names[i]; i++) {
759 if (!(sysctl_sched_features & (1UL << i)))
761 seq_printf(m, "%s ", sched_feat_names[i]);
769 sched_feat_write(struct file *filp, const char __user *ubuf,
770 size_t cnt, loff_t *ppos)
780 if (copy_from_user(&buf, ubuf, cnt))
785 if (strncmp(buf, "NO_", 3) == 0) {
790 for (i = 0; sched_feat_names[i]; i++) {
791 int len = strlen(sched_feat_names[i]);
793 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
795 sysctl_sched_features &= ~(1UL << i);
797 sysctl_sched_features |= (1UL << i);
802 if (!sched_feat_names[i])
810 static int sched_feat_open(struct inode *inode, struct file *filp)
812 return single_open(filp, sched_feat_show, NULL);
815 static struct file_operations sched_feat_fops = {
816 .open = sched_feat_open,
817 .write = sched_feat_write,
820 .release = single_release,
823 static __init int sched_init_debug(void)
825 debugfs_create_file("sched_features", 0644, NULL, NULL,
830 late_initcall(sched_init_debug);
834 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
837 * Number of tasks to iterate in a single balance run.
838 * Limited because this is done with IRQs disabled.
840 const_debug unsigned int sysctl_sched_nr_migrate = 32;
843 * ratelimit for updating the group shares.
846 unsigned int sysctl_sched_shares_ratelimit = 250000;
849 * Inject some fuzzyness into changing the per-cpu group shares
850 * this avoids remote rq-locks at the expense of fairness.
853 unsigned int sysctl_sched_shares_thresh = 4;
856 * period over which we measure -rt task cpu usage in us.
859 unsigned int sysctl_sched_rt_period = 1000000;
861 static __read_mostly int scheduler_running;
864 * part of the period that we allow rt tasks to run in us.
867 int sysctl_sched_rt_runtime = 950000;
869 static inline u64 global_rt_period(void)
871 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
874 static inline u64 global_rt_runtime(void)
876 if (sysctl_sched_rt_runtime < 0)
879 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
882 #ifndef prepare_arch_switch
883 # define prepare_arch_switch(next) do { } while (0)
885 #ifndef finish_arch_switch
886 # define finish_arch_switch(prev) do { } while (0)
889 static inline int task_current(struct rq *rq, struct task_struct *p)
891 return rq->curr == p;
894 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
895 static inline int task_running(struct rq *rq, struct task_struct *p)
897 return task_current(rq, p);
900 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
904 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
906 #ifdef CONFIG_DEBUG_SPINLOCK
907 /* this is a valid case when another task releases the spinlock */
908 rq->lock.owner = current;
911 * If we are tracking spinlock dependencies then we have to
912 * fix up the runqueue lock - which gets 'carried over' from
915 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
917 spin_unlock_irq(&rq->lock);
920 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
921 static inline int task_running(struct rq *rq, struct task_struct *p)
926 return task_current(rq, p);
930 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
934 * We can optimise this out completely for !SMP, because the
935 * SMP rebalancing from interrupt is the only thing that cares
940 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
941 spin_unlock_irq(&rq->lock);
943 spin_unlock(&rq->lock);
947 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
951 * After ->oncpu is cleared, the task can be moved to a different CPU.
952 * We must ensure this doesn't happen until the switch is completely
958 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
962 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
965 * __task_rq_lock - lock the runqueue a given task resides on.
966 * Must be called interrupts disabled.
968 static inline struct rq *__task_rq_lock(struct task_struct *p)
972 struct rq *rq = task_rq(p);
973 spin_lock(&rq->lock);
974 if (likely(rq == task_rq(p)))
976 spin_unlock(&rq->lock);
981 * task_rq_lock - lock the runqueue a given task resides on and disable
982 * interrupts. Note the ordering: we can safely lookup the task_rq without
983 * explicitly disabling preemption.
985 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
991 local_irq_save(*flags);
993 spin_lock(&rq->lock);
994 if (likely(rq == task_rq(p)))
996 spin_unlock_irqrestore(&rq->lock, *flags);
1000 void curr_rq_lock_irq_save(unsigned long *flags)
1001 __acquires(rq->lock)
1005 local_irq_save(*flags);
1006 rq = cpu_rq(smp_processor_id());
1007 spin_lock(&rq->lock);
1010 void curr_rq_unlock_irq_restore(unsigned long *flags)
1011 __releases(rq->lock)
1015 rq = cpu_rq(smp_processor_id());
1016 spin_unlock(&rq->lock);
1017 local_irq_restore(*flags);
1020 void task_rq_unlock_wait(struct task_struct *p)
1022 struct rq *rq = task_rq(p);
1024 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
1025 spin_unlock_wait(&rq->lock);
1028 static void __task_rq_unlock(struct rq *rq)
1029 __releases(rq->lock)
1031 spin_unlock(&rq->lock);
1034 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1035 __releases(rq->lock)
1037 spin_unlock_irqrestore(&rq->lock, *flags);
1041 * this_rq_lock - lock this runqueue and disable interrupts.
1043 static struct rq *this_rq_lock(void)
1044 __acquires(rq->lock)
1048 local_irq_disable();
1050 spin_lock(&rq->lock);
1055 #ifdef CONFIG_SCHED_HRTICK
1057 * Use HR-timers to deliver accurate preemption points.
1059 * Its all a bit involved since we cannot program an hrt while holding the
1060 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1063 * When we get rescheduled we reprogram the hrtick_timer outside of the
1069 * - enabled by features
1070 * - hrtimer is actually high res
1072 static inline int hrtick_enabled(struct rq *rq)
1074 if (!sched_feat(HRTICK))
1076 if (!cpu_active(cpu_of(rq)))
1078 return hrtimer_is_hres_active(&rq->hrtick_timer);
1081 static void hrtick_clear(struct rq *rq)
1083 if (hrtimer_active(&rq->hrtick_timer))
1084 hrtimer_cancel(&rq->hrtick_timer);
1088 * High-resolution timer tick.
1089 * Runs from hardirq context with interrupts disabled.
1091 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1093 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1095 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1097 spin_lock(&rq->lock);
1098 update_rq_clock(rq);
1099 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1100 spin_unlock(&rq->lock);
1102 return HRTIMER_NORESTART;
1107 * called from hardirq (IPI) context
1109 static void __hrtick_start(void *arg)
1111 struct rq *rq = arg;
1113 spin_lock(&rq->lock);
1114 hrtimer_restart(&rq->hrtick_timer);
1115 rq->hrtick_csd_pending = 0;
1116 spin_unlock(&rq->lock);
1120 * Called to set the hrtick timer state.
1122 * called with rq->lock held and irqs disabled
1124 static void hrtick_start(struct rq *rq, u64 delay)
1126 struct hrtimer *timer = &rq->hrtick_timer;
1127 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1129 hrtimer_set_expires(timer, time);
1131 if (rq == this_rq()) {
1132 hrtimer_restart(timer);
1133 } else if (!rq->hrtick_csd_pending) {
1134 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1135 rq->hrtick_csd_pending = 1;
1140 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1142 int cpu = (int)(long)hcpu;
1145 case CPU_UP_CANCELED:
1146 case CPU_UP_CANCELED_FROZEN:
1147 case CPU_DOWN_PREPARE:
1148 case CPU_DOWN_PREPARE_FROZEN:
1150 case CPU_DEAD_FROZEN:
1151 hrtick_clear(cpu_rq(cpu));
1158 static __init void init_hrtick(void)
1160 hotcpu_notifier(hotplug_hrtick, 0);
1164 * Called to set the hrtick timer state.
1166 * called with rq->lock held and irqs disabled
1168 static void hrtick_start(struct rq *rq, u64 delay)
1170 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay), HRTIMER_MODE_REL);
1173 static inline void init_hrtick(void)
1176 #endif /* CONFIG_SMP */
1178 static void init_rq_hrtick(struct rq *rq)
1181 rq->hrtick_csd_pending = 0;
1183 rq->hrtick_csd.flags = 0;
1184 rq->hrtick_csd.func = __hrtick_start;
1185 rq->hrtick_csd.info = rq;
1188 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1189 rq->hrtick_timer.function = hrtick;
1191 #else /* CONFIG_SCHED_HRTICK */
1192 static inline void hrtick_clear(struct rq *rq)
1196 static inline void init_rq_hrtick(struct rq *rq)
1200 static inline void init_hrtick(void)
1203 #endif /* CONFIG_SCHED_HRTICK */
1206 * resched_task - mark a task 'to be rescheduled now'.
1208 * On UP this means the setting of the need_resched flag, on SMP it
1209 * might also involve a cross-CPU call to trigger the scheduler on
1214 #ifndef tsk_is_polling
1215 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1218 static void resched_task(struct task_struct *p)
1222 assert_spin_locked(&task_rq(p)->lock);
1224 if (test_tsk_need_resched(p))
1227 set_tsk_need_resched(p);
1230 if (cpu == smp_processor_id())
1233 /* NEED_RESCHED must be visible before we test polling */
1235 if (!tsk_is_polling(p))
1236 smp_send_reschedule(cpu);
1239 static void resched_cpu(int cpu)
1241 struct rq *rq = cpu_rq(cpu);
1242 unsigned long flags;
1244 if (!spin_trylock_irqsave(&rq->lock, flags))
1246 resched_task(cpu_curr(cpu));
1247 spin_unlock_irqrestore(&rq->lock, flags);
1252 * When add_timer_on() enqueues a timer into the timer wheel of an
1253 * idle CPU then this timer might expire before the next timer event
1254 * which is scheduled to wake up that CPU. In case of a completely
1255 * idle system the next event might even be infinite time into the
1256 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1257 * leaves the inner idle loop so the newly added timer is taken into
1258 * account when the CPU goes back to idle and evaluates the timer
1259 * wheel for the next timer event.
1261 void wake_up_idle_cpu(int cpu)
1263 struct rq *rq = cpu_rq(cpu);
1265 if (cpu == smp_processor_id())
1269 * This is safe, as this function is called with the timer
1270 * wheel base lock of (cpu) held. When the CPU is on the way
1271 * to idle and has not yet set rq->curr to idle then it will
1272 * be serialized on the timer wheel base lock and take the new
1273 * timer into account automatically.
1275 if (rq->curr != rq->idle)
1279 * We can set TIF_RESCHED on the idle task of the other CPU
1280 * lockless. The worst case is that the other CPU runs the
1281 * idle task through an additional NOOP schedule()
1283 set_tsk_need_resched(rq->idle);
1285 /* NEED_RESCHED must be visible before we test polling */
1287 if (!tsk_is_polling(rq->idle))
1288 smp_send_reschedule(cpu);
1290 #endif /* CONFIG_NO_HZ */
1292 #else /* !CONFIG_SMP */
1293 static void resched_task(struct task_struct *p)
1295 assert_spin_locked(&task_rq(p)->lock);
1296 set_tsk_need_resched(p);
1298 #endif /* CONFIG_SMP */
1300 #if BITS_PER_LONG == 32
1301 # define WMULT_CONST (~0UL)
1303 # define WMULT_CONST (1UL << 32)
1306 #define WMULT_SHIFT 32
1309 * Shift right and round:
1311 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1314 * delta *= weight / lw
1316 static unsigned long
1317 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1318 struct load_weight *lw)
1322 if (!lw->inv_weight) {
1323 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1326 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1330 tmp = (u64)delta_exec * weight;
1332 * Check whether we'd overflow the 64-bit multiplication:
1334 if (unlikely(tmp > WMULT_CONST))
1335 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1338 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1340 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1343 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1349 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1356 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1357 * of tasks with abnormal "nice" values across CPUs the contribution that
1358 * each task makes to its run queue's load is weighted according to its
1359 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1360 * scaled version of the new time slice allocation that they receive on time
1364 #define WEIGHT_IDLEPRIO 3
1365 #define WMULT_IDLEPRIO 1431655765
1368 * Nice levels are multiplicative, with a gentle 10% change for every
1369 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1370 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1371 * that remained on nice 0.
1373 * The "10% effect" is relative and cumulative: from _any_ nice level,
1374 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1375 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1376 * If a task goes up by ~10% and another task goes down by ~10% then
1377 * the relative distance between them is ~25%.)
1379 static const int prio_to_weight[40] = {
1380 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1381 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1382 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1383 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1384 /* 0 */ 1024, 820, 655, 526, 423,
1385 /* 5 */ 335, 272, 215, 172, 137,
1386 /* 10 */ 110, 87, 70, 56, 45,
1387 /* 15 */ 36, 29, 23, 18, 15,
1391 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1393 * In cases where the weight does not change often, we can use the
1394 * precalculated inverse to speed up arithmetics by turning divisions
1395 * into multiplications:
1397 static const u32 prio_to_wmult[40] = {
1398 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1399 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1400 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1401 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1402 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1403 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1404 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1405 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1408 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1411 * runqueue iterator, to support SMP load-balancing between different
1412 * scheduling classes, without having to expose their internal data
1413 * structures to the load-balancing proper:
1415 struct rq_iterator {
1417 struct task_struct *(*start)(void *);
1418 struct task_struct *(*next)(void *);
1422 static unsigned long
1423 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1424 unsigned long max_load_move, struct sched_domain *sd,
1425 enum cpu_idle_type idle, int *all_pinned,
1426 int *this_best_prio, struct rq_iterator *iterator);
1429 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1430 struct sched_domain *sd, enum cpu_idle_type idle,
1431 struct rq_iterator *iterator);
1434 #ifdef CONFIG_CGROUP_CPUACCT
1435 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1437 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1440 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1442 update_load_add(&rq->load, load);
1445 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1447 update_load_sub(&rq->load, load);
1450 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1451 typedef int (*tg_visitor)(struct task_group *, void *);
1454 * Iterate the full tree, calling @down when first entering a node and @up when
1455 * leaving it for the final time.
1457 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1459 struct task_group *parent, *child;
1463 parent = &root_task_group;
1465 ret = (*down)(parent, data);
1468 list_for_each_entry_rcu(child, &parent->children, siblings) {
1475 ret = (*up)(parent, data);
1480 parent = parent->parent;
1489 static int tg_nop(struct task_group *tg, void *data)
1496 static unsigned long source_load(int cpu, int type);
1497 static unsigned long target_load(int cpu, int type);
1498 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1500 static unsigned long cpu_avg_load_per_task(int cpu)
1502 struct rq *rq = cpu_rq(cpu);
1503 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1506 rq->avg_load_per_task = rq->load.weight / nr_running;
1508 rq->avg_load_per_task = 0;
1510 return rq->avg_load_per_task;
1513 #ifdef CONFIG_FAIR_GROUP_SCHED
1515 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1518 * Calculate and set the cpu's group shares.
1521 update_group_shares_cpu(struct task_group *tg, int cpu,
1522 unsigned long sd_shares, unsigned long sd_rq_weight)
1524 unsigned long shares;
1525 unsigned long rq_weight;
1530 rq_weight = tg->cfs_rq[cpu]->rq_weight;
1533 * \Sum shares * rq_weight
1534 * shares = -----------------------
1538 shares = (sd_shares * rq_weight) / sd_rq_weight;
1539 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1541 if (abs(shares - tg->se[cpu]->load.weight) >
1542 sysctl_sched_shares_thresh) {
1543 struct rq *rq = cpu_rq(cpu);
1544 unsigned long flags;
1546 spin_lock_irqsave(&rq->lock, flags);
1547 tg->cfs_rq[cpu]->shares = shares;
1549 __set_se_shares(tg->se[cpu], shares);
1550 spin_unlock_irqrestore(&rq->lock, flags);
1555 * Re-compute the task group their per cpu shares over the given domain.
1556 * This needs to be done in a bottom-up fashion because the rq weight of a
1557 * parent group depends on the shares of its child groups.
1559 static int tg_shares_up(struct task_group *tg, void *data)
1561 unsigned long weight, rq_weight = 0;
1562 unsigned long shares = 0;
1563 struct sched_domain *sd = data;
1566 for_each_cpu(i, sched_domain_span(sd)) {
1568 * If there are currently no tasks on the cpu pretend there
1569 * is one of average load so that when a new task gets to
1570 * run here it will not get delayed by group starvation.
1572 weight = tg->cfs_rq[i]->load.weight;
1574 weight = NICE_0_LOAD;
1576 tg->cfs_rq[i]->rq_weight = weight;
1577 rq_weight += weight;
1578 shares += tg->cfs_rq[i]->shares;
1581 if ((!shares && rq_weight) || shares > tg->shares)
1582 shares = tg->shares;
1584 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1585 shares = tg->shares;
1587 for_each_cpu(i, sched_domain_span(sd))
1588 update_group_shares_cpu(tg, i, shares, rq_weight);
1594 * Compute the cpu's hierarchical load factor for each task group.
1595 * This needs to be done in a top-down fashion because the load of a child
1596 * group is a fraction of its parents load.
1598 static int tg_load_down(struct task_group *tg, void *data)
1601 long cpu = (long)data;
1604 load = cpu_rq(cpu)->load.weight;
1606 load = tg->parent->cfs_rq[cpu]->h_load;
1607 load *= tg->cfs_rq[cpu]->shares;
1608 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1611 tg->cfs_rq[cpu]->h_load = load;
1616 static void update_shares(struct sched_domain *sd)
1618 u64 now = cpu_clock(raw_smp_processor_id());
1619 s64 elapsed = now - sd->last_update;
1621 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1622 sd->last_update = now;
1623 walk_tg_tree(tg_nop, tg_shares_up, sd);
1627 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1629 spin_unlock(&rq->lock);
1631 spin_lock(&rq->lock);
1634 static void update_h_load(long cpu)
1636 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1641 static inline void update_shares(struct sched_domain *sd)
1645 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1651 #ifdef CONFIG_PREEMPT
1654 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1655 * way at the expense of forcing extra atomic operations in all
1656 * invocations. This assures that the double_lock is acquired using the
1657 * same underlying policy as the spinlock_t on this architecture, which
1658 * reduces latency compared to the unfair variant below. However, it
1659 * also adds more overhead and therefore may reduce throughput.
1661 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1662 __releases(this_rq->lock)
1663 __acquires(busiest->lock)
1664 __acquires(this_rq->lock)
1666 spin_unlock(&this_rq->lock);
1667 double_rq_lock(this_rq, busiest);
1674 * Unfair double_lock_balance: Optimizes throughput at the expense of
1675 * latency by eliminating extra atomic operations when the locks are
1676 * already in proper order on entry. This favors lower cpu-ids and will
1677 * grant the double lock to lower cpus over higher ids under contention,
1678 * regardless of entry order into the function.
1680 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1681 __releases(this_rq->lock)
1682 __acquires(busiest->lock)
1683 __acquires(this_rq->lock)
1687 if (unlikely(!spin_trylock(&busiest->lock))) {
1688 if (busiest < this_rq) {
1689 spin_unlock(&this_rq->lock);
1690 spin_lock(&busiest->lock);
1691 spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING);
1694 spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING);
1699 #endif /* CONFIG_PREEMPT */
1702 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1704 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1706 if (unlikely(!irqs_disabled())) {
1707 /* printk() doesn't work good under rq->lock */
1708 spin_unlock(&this_rq->lock);
1712 return _double_lock_balance(this_rq, busiest);
1715 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1716 __releases(busiest->lock)
1718 spin_unlock(&busiest->lock);
1719 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1723 #ifdef CONFIG_FAIR_GROUP_SCHED
1724 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1727 cfs_rq->shares = shares;
1732 #include "sched_stats.h"
1733 #include "sched_idletask.c"
1734 #include "sched_fair.c"
1735 #include "sched_rt.c"
1736 #ifdef CONFIG_SCHED_DEBUG
1737 # include "sched_debug.c"
1740 #define sched_class_highest (&rt_sched_class)
1741 #define for_each_class(class) \
1742 for (class = sched_class_highest; class; class = class->next)
1744 static void inc_nr_running(struct rq *rq)
1749 static void dec_nr_running(struct rq *rq)
1754 static void set_load_weight(struct task_struct *p)
1756 if (task_has_rt_policy(p)) {
1757 p->se.load.weight = prio_to_weight[0] * 2;
1758 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1763 * SCHED_IDLE tasks get minimal weight:
1765 if (p->policy == SCHED_IDLE) {
1766 p->se.load.weight = WEIGHT_IDLEPRIO;
1767 p->se.load.inv_weight = WMULT_IDLEPRIO;
1771 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1772 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1775 static void update_avg(u64 *avg, u64 sample)
1777 s64 diff = sample - *avg;
1781 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1784 p->se.start_runtime = p->se.sum_exec_runtime;
1786 sched_info_queued(p);
1787 p->sched_class->enqueue_task(rq, p, wakeup);
1791 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1794 if (p->se.last_wakeup) {
1795 update_avg(&p->se.avg_overlap,
1796 p->se.sum_exec_runtime - p->se.last_wakeup);
1797 p->se.last_wakeup = 0;
1799 update_avg(&p->se.avg_wakeup,
1800 sysctl_sched_wakeup_granularity);
1804 sched_info_dequeued(p);
1805 p->sched_class->dequeue_task(rq, p, sleep);
1810 * __normal_prio - return the priority that is based on the static prio
1812 static inline int __normal_prio(struct task_struct *p)
1814 return p->static_prio;
1818 * Calculate the expected normal priority: i.e. priority
1819 * without taking RT-inheritance into account. Might be
1820 * boosted by interactivity modifiers. Changes upon fork,
1821 * setprio syscalls, and whenever the interactivity
1822 * estimator recalculates.
1824 static inline int normal_prio(struct task_struct *p)
1828 if (task_has_rt_policy(p))
1829 prio = MAX_RT_PRIO-1 - p->rt_priority;
1831 prio = __normal_prio(p);
1836 * Calculate the current priority, i.e. the priority
1837 * taken into account by the scheduler. This value might
1838 * be boosted by RT tasks, or might be boosted by
1839 * interactivity modifiers. Will be RT if the task got
1840 * RT-boosted. If not then it returns p->normal_prio.
1842 static int effective_prio(struct task_struct *p)
1844 p->normal_prio = normal_prio(p);
1846 * If we are RT tasks or we were boosted to RT priority,
1847 * keep the priority unchanged. Otherwise, update priority
1848 * to the normal priority:
1850 if (!rt_prio(p->prio))
1851 return p->normal_prio;
1856 * activate_task - move a task to the runqueue.
1858 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1860 if (task_contributes_to_load(p))
1861 rq->nr_uninterruptible--;
1863 enqueue_task(rq, p, wakeup);
1868 * deactivate_task - remove a task from the runqueue.
1870 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1872 if (task_contributes_to_load(p))
1873 rq->nr_uninterruptible++;
1875 dequeue_task(rq, p, sleep);
1880 * task_curr - is this task currently executing on a CPU?
1881 * @p: the task in question.
1883 inline int task_curr(const struct task_struct *p)
1885 return cpu_curr(task_cpu(p)) == p;
1888 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1890 set_task_rq(p, cpu);
1893 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1894 * successfuly executed on another CPU. We must ensure that updates of
1895 * per-task data have been completed by this moment.
1898 task_thread_info(p)->cpu = cpu;
1902 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1903 const struct sched_class *prev_class,
1904 int oldprio, int running)
1906 if (prev_class != p->sched_class) {
1907 if (prev_class->switched_from)
1908 prev_class->switched_from(rq, p, running);
1909 p->sched_class->switched_to(rq, p, running);
1911 p->sched_class->prio_changed(rq, p, oldprio, running);
1916 /* Used instead of source_load when we know the type == 0 */
1917 static unsigned long weighted_cpuload(const int cpu)
1919 return cpu_rq(cpu)->load.weight;
1923 * Is this task likely cache-hot:
1926 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1931 * Buddy candidates are cache hot:
1933 if (sched_feat(CACHE_HOT_BUDDY) &&
1934 (&p->se == cfs_rq_of(&p->se)->next ||
1935 &p->se == cfs_rq_of(&p->se)->last))
1938 if (p->sched_class != &fair_sched_class)
1941 if (sysctl_sched_migration_cost == -1)
1943 if (sysctl_sched_migration_cost == 0)
1946 delta = now - p->se.exec_start;
1948 return delta < (s64)sysctl_sched_migration_cost;
1952 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1954 int old_cpu = task_cpu(p);
1955 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1956 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1957 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1960 clock_offset = old_rq->clock - new_rq->clock;
1962 trace_sched_migrate_task(p, task_cpu(p), new_cpu);
1964 #ifdef CONFIG_SCHEDSTATS
1965 if (p->se.wait_start)
1966 p->se.wait_start -= clock_offset;
1967 if (p->se.sleep_start)
1968 p->se.sleep_start -= clock_offset;
1969 if (p->se.block_start)
1970 p->se.block_start -= clock_offset;
1972 if (old_cpu != new_cpu) {
1973 p->se.nr_migrations++;
1974 new_rq->nr_migrations_in++;
1975 #ifdef CONFIG_SCHEDSTATS
1976 if (task_hot(p, old_rq->clock, NULL))
1977 schedstat_inc(p, se.nr_forced2_migrations);
1980 p->se.vruntime -= old_cfsrq->min_vruntime -
1981 new_cfsrq->min_vruntime;
1983 __set_task_cpu(p, new_cpu);
1986 struct migration_req {
1987 struct list_head list;
1989 struct task_struct *task;
1992 struct completion done;
1996 * The task's runqueue lock must be held.
1997 * Returns true if you have to wait for migration thread.
2000 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2002 struct rq *rq = task_rq(p);
2005 * If the task is not on a runqueue (and not running), then
2006 * it is sufficient to simply update the task's cpu field.
2008 if (!p->se.on_rq && !task_running(rq, p)) {
2009 set_task_cpu(p, dest_cpu);
2013 init_completion(&req->done);
2015 req->dest_cpu = dest_cpu;
2016 list_add(&req->list, &rq->migration_queue);
2022 * wait_task_inactive - wait for a thread to unschedule.
2024 * If @match_state is nonzero, it's the @p->state value just checked and
2025 * not expected to change. If it changes, i.e. @p might have woken up,
2026 * then return zero. When we succeed in waiting for @p to be off its CPU,
2027 * we return a positive number (its total switch count). If a second call
2028 * a short while later returns the same number, the caller can be sure that
2029 * @p has remained unscheduled the whole time.
2031 * The caller must ensure that the task *will* unschedule sometime soon,
2032 * else this function might spin for a *long* time. This function can't
2033 * be called with interrupts off, or it may introduce deadlock with
2034 * smp_call_function() if an IPI is sent by the same process we are
2035 * waiting to become inactive.
2037 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2039 unsigned long flags;
2046 * We do the initial early heuristics without holding
2047 * any task-queue locks at all. We'll only try to get
2048 * the runqueue lock when things look like they will
2054 * If the task is actively running on another CPU
2055 * still, just relax and busy-wait without holding
2058 * NOTE! Since we don't hold any locks, it's not
2059 * even sure that "rq" stays as the right runqueue!
2060 * But we don't care, since "task_running()" will
2061 * return false if the runqueue has changed and p
2062 * is actually now running somewhere else!
2064 while (task_running(rq, p)) {
2065 if (match_state && unlikely(p->state != match_state))
2071 * Ok, time to look more closely! We need the rq
2072 * lock now, to be *sure*. If we're wrong, we'll
2073 * just go back and repeat.
2075 rq = task_rq_lock(p, &flags);
2076 trace_sched_wait_task(rq, p);
2077 running = task_running(rq, p);
2078 on_rq = p->se.on_rq;
2080 if (!match_state || p->state == match_state)
2081 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2082 task_rq_unlock(rq, &flags);
2085 * If it changed from the expected state, bail out now.
2087 if (unlikely(!ncsw))
2091 * Was it really running after all now that we
2092 * checked with the proper locks actually held?
2094 * Oops. Go back and try again..
2096 if (unlikely(running)) {
2102 * It's not enough that it's not actively running,
2103 * it must be off the runqueue _entirely_, and not
2106 * So if it was still runnable (but just not actively
2107 * running right now), it's preempted, and we should
2108 * yield - it could be a while.
2110 if (unlikely(on_rq)) {
2111 schedule_timeout_uninterruptible(1);
2116 * Ahh, all good. It wasn't running, and it wasn't
2117 * runnable, which means that it will never become
2118 * running in the future either. We're all done!
2127 * kick_process - kick a running thread to enter/exit the kernel
2128 * @p: the to-be-kicked thread
2130 * Cause a process which is running on another CPU to enter
2131 * kernel-mode, without any delay. (to get signals handled.)
2133 * NOTE: this function doesnt have to take the runqueue lock,
2134 * because all it wants to ensure is that the remote task enters
2135 * the kernel. If the IPI races and the task has been migrated
2136 * to another CPU then no harm is done and the purpose has been
2139 void kick_process(struct task_struct *p)
2145 if ((cpu != smp_processor_id()) && task_curr(p))
2146 smp_send_reschedule(cpu);
2151 * Return a low guess at the load of a migration-source cpu weighted
2152 * according to the scheduling class and "nice" value.
2154 * We want to under-estimate the load of migration sources, to
2155 * balance conservatively.
2157 static unsigned long source_load(int cpu, int type)
2159 struct rq *rq = cpu_rq(cpu);
2160 unsigned long total = weighted_cpuload(cpu);
2162 if (type == 0 || !sched_feat(LB_BIAS))
2165 return min(rq->cpu_load[type-1], total);
2169 * Return a high guess at the load of a migration-target cpu weighted
2170 * according to the scheduling class and "nice" value.
2172 static unsigned long target_load(int cpu, int type)
2174 struct rq *rq = cpu_rq(cpu);
2175 unsigned long total = weighted_cpuload(cpu);
2177 if (type == 0 || !sched_feat(LB_BIAS))
2180 return max(rq->cpu_load[type-1], total);
2184 * find_idlest_group finds and returns the least busy CPU group within the
2187 static struct sched_group *
2188 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2190 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2191 unsigned long min_load = ULONG_MAX, this_load = 0;
2192 int load_idx = sd->forkexec_idx;
2193 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2196 unsigned long load, avg_load;
2200 /* Skip over this group if it has no CPUs allowed */
2201 if (!cpumask_intersects(sched_group_cpus(group),
2205 local_group = cpumask_test_cpu(this_cpu,
2206 sched_group_cpus(group));
2208 /* Tally up the load of all CPUs in the group */
2211 for_each_cpu(i, sched_group_cpus(group)) {
2212 /* Bias balancing toward cpus of our domain */
2214 load = source_load(i, load_idx);
2216 load = target_load(i, load_idx);
2221 /* Adjust by relative CPU power of the group */
2222 avg_load = sg_div_cpu_power(group,
2223 avg_load * SCHED_LOAD_SCALE);
2226 this_load = avg_load;
2228 } else if (avg_load < min_load) {
2229 min_load = avg_load;
2232 } while (group = group->next, group != sd->groups);
2234 if (!idlest || 100*this_load < imbalance*min_load)
2240 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2243 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2245 unsigned long load, min_load = ULONG_MAX;
2249 /* Traverse only the allowed CPUs */
2250 for_each_cpu_and(i, sched_group_cpus(group), &p->cpus_allowed) {
2251 load = weighted_cpuload(i);
2253 if (load < min_load || (load == min_load && i == this_cpu)) {
2263 * sched_balance_self: balance the current task (running on cpu) in domains
2264 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2267 * Balance, ie. select the least loaded group.
2269 * Returns the target CPU number, or the same CPU if no balancing is needed.
2271 * preempt must be disabled.
2273 static int sched_balance_self(int cpu, int flag)
2275 struct task_struct *t = current;
2276 struct sched_domain *tmp, *sd = NULL;
2278 for_each_domain(cpu, tmp) {
2280 * If power savings logic is enabled for a domain, stop there.
2282 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2284 if (tmp->flags & flag)
2292 struct sched_group *group;
2293 int new_cpu, weight;
2295 if (!(sd->flags & flag)) {
2300 group = find_idlest_group(sd, t, cpu);
2306 new_cpu = find_idlest_cpu(group, t, cpu);
2307 if (new_cpu == -1 || new_cpu == cpu) {
2308 /* Now try balancing at a lower domain level of cpu */
2313 /* Now try balancing at a lower domain level of new_cpu */
2315 weight = cpumask_weight(sched_domain_span(sd));
2317 for_each_domain(cpu, tmp) {
2318 if (weight <= cpumask_weight(sched_domain_span(tmp)))
2320 if (tmp->flags & flag)
2323 /* while loop will break here if sd == NULL */
2329 #endif /* CONFIG_SMP */
2332 * task_oncpu_function_call - call a function on the cpu on which a task runs
2333 * @p: the task to evaluate
2334 * @func: the function to be called
2335 * @info: the function call argument
2337 * Calls the function @func when the task is currently running. This might
2338 * be on the current CPU, which just calls the function directly
2340 void task_oncpu_function_call(struct task_struct *p,
2341 void (*func) (void *info), void *info)
2348 smp_call_function_single(cpu, func, info, 1);
2353 * try_to_wake_up - wake up a thread
2354 * @p: the to-be-woken-up thread
2355 * @state: the mask of task states that can be woken
2356 * @sync: do a synchronous wakeup?
2358 * Put it on the run-queue if it's not already there. The "current"
2359 * thread is always on the run-queue (except when the actual
2360 * re-schedule is in progress), and as such you're allowed to do
2361 * the simpler "current->state = TASK_RUNNING" to mark yourself
2362 * runnable without the overhead of this.
2364 * returns failure only if the task is already active.
2366 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2368 int cpu, orig_cpu, this_cpu, success = 0;
2369 unsigned long flags;
2373 if (!sched_feat(SYNC_WAKEUPS))
2377 if (sched_feat(LB_WAKEUP_UPDATE) && !root_task_group_empty()) {
2378 struct sched_domain *sd;
2380 this_cpu = raw_smp_processor_id();
2383 for_each_domain(this_cpu, sd) {
2384 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2393 rq = task_rq_lock(p, &flags);
2394 update_rq_clock(rq);
2395 old_state = p->state;
2396 if (!(old_state & state))
2404 this_cpu = smp_processor_id();
2407 if (unlikely(task_running(rq, p)))
2410 cpu = p->sched_class->select_task_rq(p, sync);
2411 if (cpu != orig_cpu) {
2412 set_task_cpu(p, cpu);
2413 task_rq_unlock(rq, &flags);
2414 /* might preempt at this point */
2415 rq = task_rq_lock(p, &flags);
2416 old_state = p->state;
2417 if (!(old_state & state))
2422 this_cpu = smp_processor_id();
2426 #ifdef CONFIG_SCHEDSTATS
2427 schedstat_inc(rq, ttwu_count);
2428 if (cpu == this_cpu)
2429 schedstat_inc(rq, ttwu_local);
2431 struct sched_domain *sd;
2432 for_each_domain(this_cpu, sd) {
2433 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2434 schedstat_inc(sd, ttwu_wake_remote);
2439 #endif /* CONFIG_SCHEDSTATS */
2442 #endif /* CONFIG_SMP */
2443 schedstat_inc(p, se.nr_wakeups);
2445 schedstat_inc(p, se.nr_wakeups_sync);
2446 if (orig_cpu != cpu)
2447 schedstat_inc(p, se.nr_wakeups_migrate);
2448 if (cpu == this_cpu)
2449 schedstat_inc(p, se.nr_wakeups_local);
2451 schedstat_inc(p, se.nr_wakeups_remote);
2452 activate_task(rq, p, 1);
2456 * Only attribute actual wakeups done by this task.
2458 if (!in_interrupt()) {
2459 struct sched_entity *se = ¤t->se;
2460 u64 sample = se->sum_exec_runtime;
2462 if (se->last_wakeup)
2463 sample -= se->last_wakeup;
2465 sample -= se->start_runtime;
2466 update_avg(&se->avg_wakeup, sample);
2468 se->last_wakeup = se->sum_exec_runtime;
2472 trace_sched_wakeup(rq, p, success);
2473 check_preempt_curr(rq, p, sync);
2475 p->state = TASK_RUNNING;
2477 if (p->sched_class->task_wake_up)
2478 p->sched_class->task_wake_up(rq, p);
2481 task_rq_unlock(rq, &flags);
2486 int wake_up_process(struct task_struct *p)
2488 return try_to_wake_up(p, TASK_ALL, 0);
2490 EXPORT_SYMBOL(wake_up_process);
2492 int wake_up_state(struct task_struct *p, unsigned int state)
2494 return try_to_wake_up(p, state, 0);
2498 * Perform scheduler related setup for a newly forked process p.
2499 * p is forked by current.
2501 * __sched_fork() is basic setup used by init_idle() too:
2503 static void __sched_fork(struct task_struct *p)
2505 p->se.exec_start = 0;
2506 p->se.sum_exec_runtime = 0;
2507 p->se.prev_sum_exec_runtime = 0;
2508 p->se.nr_migrations = 0;
2509 p->se.last_wakeup = 0;
2510 p->se.avg_overlap = 0;
2511 p->se.start_runtime = 0;
2512 p->se.avg_wakeup = sysctl_sched_wakeup_granularity;
2514 #ifdef CONFIG_SCHEDSTATS
2515 p->se.wait_start = 0;
2516 p->se.sum_sleep_runtime = 0;
2517 p->se.sleep_start = 0;
2518 p->se.block_start = 0;
2519 p->se.sleep_max = 0;
2520 p->se.block_max = 0;
2522 p->se.slice_max = 0;
2526 INIT_LIST_HEAD(&p->rt.run_list);
2528 INIT_LIST_HEAD(&p->se.group_node);
2530 #ifdef CONFIG_PREEMPT_NOTIFIERS
2531 INIT_HLIST_HEAD(&p->preempt_notifiers);
2535 * We mark the process as running here, but have not actually
2536 * inserted it onto the runqueue yet. This guarantees that
2537 * nobody will actually run it, and a signal or other external
2538 * event cannot wake it up and insert it on the runqueue either.
2540 p->state = TASK_RUNNING;
2544 * fork()/clone()-time setup:
2546 void sched_fork(struct task_struct *p, int clone_flags)
2548 int cpu = get_cpu();
2553 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2555 set_task_cpu(p, cpu);
2558 * Make sure we do not leak PI boosting priority to the child:
2560 p->prio = current->normal_prio;
2561 if (!rt_prio(p->prio))
2562 p->sched_class = &fair_sched_class;
2564 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2565 if (likely(sched_info_on()))
2566 memset(&p->sched_info, 0, sizeof(p->sched_info));
2568 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2571 #ifdef CONFIG_PREEMPT
2572 /* Want to start with kernel preemption disabled. */
2573 task_thread_info(p)->preempt_count = 1;
2575 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2581 * wake_up_new_task - wake up a newly created task for the first time.
2583 * This function will do some initial scheduler statistics housekeeping
2584 * that must be done for every newly created context, then puts the task
2585 * on the runqueue and wakes it.
2587 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2589 unsigned long flags;
2592 rq = task_rq_lock(p, &flags);
2593 BUG_ON(p->state != TASK_RUNNING);
2594 update_rq_clock(rq);
2596 p->prio = effective_prio(p);
2598 if (!p->sched_class->task_new || !current->se.on_rq) {
2599 activate_task(rq, p, 0);
2602 * Let the scheduling class do new task startup
2603 * management (if any):
2605 p->sched_class->task_new(rq, p);
2608 trace_sched_wakeup_new(rq, p, 1);
2609 check_preempt_curr(rq, p, 0);
2611 if (p->sched_class->task_wake_up)
2612 p->sched_class->task_wake_up(rq, p);
2614 task_rq_unlock(rq, &flags);
2617 #ifdef CONFIG_PREEMPT_NOTIFIERS
2620 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2621 * @notifier: notifier struct to register
2623 void preempt_notifier_register(struct preempt_notifier *notifier)
2625 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2627 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2630 * preempt_notifier_unregister - no longer interested in preemption notifications
2631 * @notifier: notifier struct to unregister
2633 * This is safe to call from within a preemption notifier.
2635 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2637 hlist_del(¬ifier->link);
2639 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2641 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2643 struct preempt_notifier *notifier;
2644 struct hlist_node *node;
2646 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2647 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2651 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2652 struct task_struct *next)
2654 struct preempt_notifier *notifier;
2655 struct hlist_node *node;
2657 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2658 notifier->ops->sched_out(notifier, next);
2661 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2663 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2668 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2669 struct task_struct *next)
2673 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2676 * prepare_task_switch - prepare to switch tasks
2677 * @rq: the runqueue preparing to switch
2678 * @prev: the current task that is being switched out
2679 * @next: the task we are going to switch to.
2681 * This is called with the rq lock held and interrupts off. It must
2682 * be paired with a subsequent finish_task_switch after the context
2685 * prepare_task_switch sets up locking and calls architecture specific
2689 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2690 struct task_struct *next)
2692 fire_sched_out_preempt_notifiers(prev, next);
2693 prepare_lock_switch(rq, next);
2694 prepare_arch_switch(next);
2698 * finish_task_switch - clean up after a task-switch
2699 * @rq: runqueue associated with task-switch
2700 * @prev: the thread we just switched away from.
2702 * finish_task_switch must be called after the context switch, paired
2703 * with a prepare_task_switch call before the context switch.
2704 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2705 * and do any other architecture-specific cleanup actions.
2707 * Note that we may have delayed dropping an mm in context_switch(). If
2708 * so, we finish that here outside of the runqueue lock. (Doing it
2709 * with the lock held can cause deadlocks; see schedule() for
2712 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2713 __releases(rq->lock)
2715 struct mm_struct *mm = rq->prev_mm;
2718 int post_schedule = 0;
2720 if (current->sched_class->needs_post_schedule)
2721 post_schedule = current->sched_class->needs_post_schedule(rq);
2727 * A task struct has one reference for the use as "current".
2728 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2729 * schedule one last time. The schedule call will never return, and
2730 * the scheduled task must drop that reference.
2731 * The test for TASK_DEAD must occur while the runqueue locks are
2732 * still held, otherwise prev could be scheduled on another cpu, die
2733 * there before we look at prev->state, and then the reference would
2735 * Manfred Spraul <manfred@colorfullife.com>
2737 prev_state = prev->state;
2738 finish_arch_switch(prev);
2739 perf_counter_task_sched_in(current, cpu_of(rq));
2740 finish_lock_switch(rq, prev);
2743 current->sched_class->post_schedule(rq);
2746 fire_sched_in_preempt_notifiers(current);
2749 if (unlikely(prev_state == TASK_DEAD)) {
2751 * Remove function-return probe instances associated with this
2752 * task and put them back on the free list.
2754 kprobe_flush_task(prev);
2755 put_task_struct(prev);
2760 * schedule_tail - first thing a freshly forked thread must call.
2761 * @prev: the thread we just switched away from.
2763 asmlinkage void schedule_tail(struct task_struct *prev)
2764 __releases(rq->lock)
2766 struct rq *rq = this_rq();
2768 finish_task_switch(rq, prev);
2769 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2770 /* In this case, finish_task_switch does not reenable preemption */
2773 if (current->set_child_tid)
2774 put_user(task_pid_vnr(current), current->set_child_tid);
2778 * context_switch - switch to the new MM and the new
2779 * thread's register state.
2782 context_switch(struct rq *rq, struct task_struct *prev,
2783 struct task_struct *next)
2785 struct mm_struct *mm, *oldmm;
2787 prepare_task_switch(rq, prev, next);
2788 trace_sched_switch(rq, prev, next);
2790 oldmm = prev->active_mm;
2792 * For paravirt, this is coupled with an exit in switch_to to
2793 * combine the page table reload and the switch backend into
2796 arch_enter_lazy_cpu_mode();
2798 if (unlikely(!mm)) {
2799 next->active_mm = oldmm;
2800 atomic_inc(&oldmm->mm_count);
2801 enter_lazy_tlb(oldmm, next);
2803 switch_mm(oldmm, mm, next);
2805 if (unlikely(!prev->mm)) {
2806 prev->active_mm = NULL;
2807 rq->prev_mm = oldmm;
2810 * Since the runqueue lock will be released by the next
2811 * task (which is an invalid locking op but in the case
2812 * of the scheduler it's an obvious special-case), so we
2813 * do an early lockdep release here:
2815 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2816 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2819 /* Here we just switch the register state and the stack. */
2820 switch_to(prev, next, prev);
2824 * this_rq must be evaluated again because prev may have moved
2825 * CPUs since it called schedule(), thus the 'rq' on its stack
2826 * frame will be invalid.
2828 finish_task_switch(this_rq(), prev);
2832 * nr_running, nr_uninterruptible and nr_context_switches:
2834 * externally visible scheduler statistics: current number of runnable
2835 * threads, current number of uninterruptible-sleeping threads, total
2836 * number of context switches performed since bootup.
2838 unsigned long nr_running(void)
2840 unsigned long i, sum = 0;
2842 for_each_online_cpu(i)
2843 sum += cpu_rq(i)->nr_running;
2848 unsigned long nr_uninterruptible(void)
2850 unsigned long i, sum = 0;
2852 for_each_possible_cpu(i)
2853 sum += cpu_rq(i)->nr_uninterruptible;
2856 * Since we read the counters lockless, it might be slightly
2857 * inaccurate. Do not allow it to go below zero though:
2859 if (unlikely((long)sum < 0))
2865 unsigned long long nr_context_switches(void)
2868 unsigned long long sum = 0;
2870 for_each_possible_cpu(i)
2871 sum += cpu_rq(i)->nr_switches;
2876 unsigned long nr_iowait(void)
2878 unsigned long i, sum = 0;
2880 for_each_possible_cpu(i)
2881 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2886 unsigned long nr_active(void)
2888 unsigned long i, running = 0, uninterruptible = 0;
2890 for_each_online_cpu(i) {
2891 running += cpu_rq(i)->nr_running;
2892 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2895 if (unlikely((long)uninterruptible < 0))
2896 uninterruptible = 0;
2898 return running + uninterruptible;
2902 * Externally visible per-cpu scheduler statistics:
2903 * cpu_nr_switches(cpu) - number of context switches on that cpu
2904 * cpu_nr_migrations(cpu) - number of migrations into that cpu
2906 u64 cpu_nr_switches(int cpu)
2908 return cpu_rq(cpu)->nr_switches;
2911 u64 cpu_nr_migrations(int cpu)
2913 return cpu_rq(cpu)->nr_migrations_in;
2917 * Update rq->cpu_load[] statistics. This function is usually called every
2918 * scheduler tick (TICK_NSEC).
2920 static void update_cpu_load(struct rq *this_rq)
2922 unsigned long this_load = this_rq->load.weight;
2925 this_rq->nr_load_updates++;
2927 /* Update our load: */
2928 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2929 unsigned long old_load, new_load;
2931 /* scale is effectively 1 << i now, and >> i divides by scale */
2933 old_load = this_rq->cpu_load[i];
2934 new_load = this_load;
2936 * Round up the averaging division if load is increasing. This
2937 * prevents us from getting stuck on 9 if the load is 10, for
2940 if (new_load > old_load)
2941 new_load += scale-1;
2942 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2949 * double_rq_lock - safely lock two runqueues
2951 * Note this does not disable interrupts like task_rq_lock,
2952 * you need to do so manually before calling.
2954 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2955 __acquires(rq1->lock)
2956 __acquires(rq2->lock)
2958 BUG_ON(!irqs_disabled());
2960 spin_lock(&rq1->lock);
2961 __acquire(rq2->lock); /* Fake it out ;) */
2964 spin_lock(&rq1->lock);
2965 spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
2967 spin_lock(&rq2->lock);
2968 spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
2971 update_rq_clock(rq1);
2972 update_rq_clock(rq2);
2976 * double_rq_unlock - safely unlock two runqueues
2978 * Note this does not restore interrupts like task_rq_unlock,
2979 * you need to do so manually after calling.
2981 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2982 __releases(rq1->lock)
2983 __releases(rq2->lock)
2985 spin_unlock(&rq1->lock);
2987 spin_unlock(&rq2->lock);
2989 __release(rq2->lock);
2993 * If dest_cpu is allowed for this process, migrate the task to it.
2994 * This is accomplished by forcing the cpu_allowed mask to only
2995 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2996 * the cpu_allowed mask is restored.
2998 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3000 struct migration_req req;
3001 unsigned long flags;
3004 rq = task_rq_lock(p, &flags);
3005 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed)
3006 || unlikely(!cpu_active(dest_cpu)))
3009 /* force the process onto the specified CPU */
3010 if (migrate_task(p, dest_cpu, &req)) {
3011 /* Need to wait for migration thread (might exit: take ref). */
3012 struct task_struct *mt = rq->migration_thread;
3014 get_task_struct(mt);
3015 task_rq_unlock(rq, &flags);
3016 wake_up_process(mt);
3017 put_task_struct(mt);
3018 wait_for_completion(&req.done);
3023 task_rq_unlock(rq, &flags);
3027 * sched_exec - execve() is a valuable balancing opportunity, because at
3028 * this point the task has the smallest effective memory and cache footprint.
3030 void sched_exec(void)
3032 int new_cpu, this_cpu = get_cpu();
3033 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3035 if (new_cpu != this_cpu)
3036 sched_migrate_task(current, new_cpu);
3040 * pull_task - move a task from a remote runqueue to the local runqueue.
3041 * Both runqueues must be locked.
3043 static void pull_task(struct rq *src_rq, struct task_struct *p,
3044 struct rq *this_rq, int this_cpu)
3046 deactivate_task(src_rq, p, 0);
3047 set_task_cpu(p, this_cpu);
3048 activate_task(this_rq, p, 0);
3050 * Note that idle threads have a prio of MAX_PRIO, for this test
3051 * to be always true for them.
3053 check_preempt_curr(this_rq, p, 0);
3057 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3060 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3061 struct sched_domain *sd, enum cpu_idle_type idle,
3064 int tsk_cache_hot = 0;
3066 * We do not migrate tasks that are:
3067 * 1) running (obviously), or
3068 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3069 * 3) are cache-hot on their current CPU.
3071 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
3072 schedstat_inc(p, se.nr_failed_migrations_affine);
3077 if (task_running(rq, p)) {
3078 schedstat_inc(p, se.nr_failed_migrations_running);
3083 * Aggressive migration if:
3084 * 1) task is cache cold, or
3085 * 2) too many balance attempts have failed.
3088 tsk_cache_hot = task_hot(p, rq->clock, sd);
3089 if (!tsk_cache_hot ||
3090 sd->nr_balance_failed > sd->cache_nice_tries) {
3091 #ifdef CONFIG_SCHEDSTATS
3092 if (tsk_cache_hot) {
3093 schedstat_inc(sd, lb_hot_gained[idle]);
3094 schedstat_inc(p, se.nr_forced_migrations);
3100 if (tsk_cache_hot) {
3101 schedstat_inc(p, se.nr_failed_migrations_hot);
3107 static unsigned long
3108 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3109 unsigned long max_load_move, struct sched_domain *sd,
3110 enum cpu_idle_type idle, int *all_pinned,
3111 int *this_best_prio, struct rq_iterator *iterator)
3113 int loops = 0, pulled = 0, pinned = 0;
3114 struct task_struct *p;
3115 long rem_load_move = max_load_move;
3117 if (max_load_move == 0)
3123 * Start the load-balancing iterator:
3125 p = iterator->start(iterator->arg);
3127 if (!p || loops++ > sysctl_sched_nr_migrate)
3130 if ((p->se.load.weight >> 1) > rem_load_move ||
3131 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3132 p = iterator->next(iterator->arg);
3136 pull_task(busiest, p, this_rq, this_cpu);
3138 rem_load_move -= p->se.load.weight;
3140 #ifdef CONFIG_PREEMPT
3142 * NEWIDLE balancing is a source of latency, so preemptible kernels
3143 * will stop after the first task is pulled to minimize the critical
3146 if (idle == CPU_NEWLY_IDLE)
3151 * We only want to steal up to the prescribed amount of weighted load.
3153 if (rem_load_move > 0) {
3154 if (p->prio < *this_best_prio)
3155 *this_best_prio = p->prio;
3156 p = iterator->next(iterator->arg);
3161 * Right now, this is one of only two places pull_task() is called,
3162 * so we can safely collect pull_task() stats here rather than
3163 * inside pull_task().
3165 schedstat_add(sd, lb_gained[idle], pulled);
3168 *all_pinned = pinned;
3170 return max_load_move - rem_load_move;
3174 * move_tasks tries to move up to max_load_move weighted load from busiest to
3175 * this_rq, as part of a balancing operation within domain "sd".
3176 * Returns 1 if successful and 0 otherwise.
3178 * Called with both runqueues locked.
3180 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3181 unsigned long max_load_move,
3182 struct sched_domain *sd, enum cpu_idle_type idle,
3185 const struct sched_class *class = sched_class_highest;
3186 unsigned long total_load_moved = 0;
3187 int this_best_prio = this_rq->curr->prio;
3191 class->load_balance(this_rq, this_cpu, busiest,
3192 max_load_move - total_load_moved,
3193 sd, idle, all_pinned, &this_best_prio);
3194 class = class->next;
3196 #ifdef CONFIG_PREEMPT
3198 * NEWIDLE balancing is a source of latency, so preemptible
3199 * kernels will stop after the first task is pulled to minimize
3200 * the critical section.
3202 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3205 } while (class && max_load_move > total_load_moved);
3207 return total_load_moved > 0;
3211 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3212 struct sched_domain *sd, enum cpu_idle_type idle,
3213 struct rq_iterator *iterator)
3215 struct task_struct *p = iterator->start(iterator->arg);
3219 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3220 pull_task(busiest, p, this_rq, this_cpu);
3222 * Right now, this is only the second place pull_task()
3223 * is called, so we can safely collect pull_task()
3224 * stats here rather than inside pull_task().
3226 schedstat_inc(sd, lb_gained[idle]);
3230 p = iterator->next(iterator->arg);
3237 * move_one_task tries to move exactly one task from busiest to this_rq, as
3238 * part of active balancing operations within "domain".
3239 * Returns 1 if successful and 0 otherwise.
3241 * Called with both runqueues locked.
3243 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3244 struct sched_domain *sd, enum cpu_idle_type idle)
3246 const struct sched_class *class;
3248 for (class = sched_class_highest; class; class = class->next)
3249 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3254 /********** Helpers for find_busiest_group ************************/
3256 * sd_lb_stats - Structure to store the statistics of a sched_domain
3257 * during load balancing.
3259 struct sd_lb_stats {
3260 struct sched_group *busiest; /* Busiest group in this sd */
3261 struct sched_group *this; /* Local group in this sd */
3262 unsigned long total_load; /* Total load of all groups in sd */
3263 unsigned long total_pwr; /* Total power of all groups in sd */
3264 unsigned long avg_load; /* Average load across all groups in sd */
3266 /** Statistics of this group */
3267 unsigned long this_load;
3268 unsigned long this_load_per_task;
3269 unsigned long this_nr_running;
3271 /* Statistics of the busiest group */
3272 unsigned long max_load;
3273 unsigned long busiest_load_per_task;
3274 unsigned long busiest_nr_running;
3276 int group_imb; /* Is there imbalance in this sd */
3277 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3278 int power_savings_balance; /* Is powersave balance needed for this sd */
3279 struct sched_group *group_min; /* Least loaded group in sd */
3280 struct sched_group *group_leader; /* Group which relieves group_min */
3281 unsigned long min_load_per_task; /* load_per_task in group_min */
3282 unsigned long leader_nr_running; /* Nr running of group_leader */
3283 unsigned long min_nr_running; /* Nr running of group_min */
3288 * sg_lb_stats - stats of a sched_group required for load_balancing
3290 struct sg_lb_stats {
3291 unsigned long avg_load; /*Avg load across the CPUs of the group */
3292 unsigned long group_load; /* Total load over the CPUs of the group */
3293 unsigned long sum_nr_running; /* Nr tasks running in the group */
3294 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3295 unsigned long group_capacity;
3296 int group_imb; /* Is there an imbalance in the group ? */
3300 * group_first_cpu - Returns the first cpu in the cpumask of a sched_group.
3301 * @group: The group whose first cpu is to be returned.
3303 static inline unsigned int group_first_cpu(struct sched_group *group)
3305 return cpumask_first(sched_group_cpus(group));
3309 * get_sd_load_idx - Obtain the load index for a given sched domain.
3310 * @sd: The sched_domain whose load_idx is to be obtained.
3311 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3313 static inline int get_sd_load_idx(struct sched_domain *sd,
3314 enum cpu_idle_type idle)
3320 load_idx = sd->busy_idx;
3323 case CPU_NEWLY_IDLE:
3324 load_idx = sd->newidle_idx;
3327 load_idx = sd->idle_idx;
3335 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3337 * init_sd_power_savings_stats - Initialize power savings statistics for
3338 * the given sched_domain, during load balancing.
3340 * @sd: Sched domain whose power-savings statistics are to be initialized.
3341 * @sds: Variable containing the statistics for sd.
3342 * @idle: Idle status of the CPU at which we're performing load-balancing.
3344 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3345 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3348 * Busy processors will not participate in power savings
3351 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3352 sds->power_savings_balance = 0;
3354 sds->power_savings_balance = 1;
3355 sds->min_nr_running = ULONG_MAX;
3356 sds->leader_nr_running = 0;
3361 * update_sd_power_savings_stats - Update the power saving stats for a
3362 * sched_domain while performing load balancing.
3364 * @group: sched_group belonging to the sched_domain under consideration.
3365 * @sds: Variable containing the statistics of the sched_domain
3366 * @local_group: Does group contain the CPU for which we're performing
3368 * @sgs: Variable containing the statistics of the group.
3370 static inline void update_sd_power_savings_stats(struct sched_group *group,
3371 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3374 if (!sds->power_savings_balance)
3378 * If the local group is idle or completely loaded
3379 * no need to do power savings balance at this domain
3381 if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
3382 !sds->this_nr_running))
3383 sds->power_savings_balance = 0;
3386 * If a group is already running at full capacity or idle,
3387 * don't include that group in power savings calculations
3389 if (!sds->power_savings_balance ||
3390 sgs->sum_nr_running >= sgs->group_capacity ||
3391 !sgs->sum_nr_running)
3395 * Calculate the group which has the least non-idle load.
3396 * This is the group from where we need to pick up the load
3399 if ((sgs->sum_nr_running < sds->min_nr_running) ||
3400 (sgs->sum_nr_running == sds->min_nr_running &&
3401 group_first_cpu(group) > group_first_cpu(sds->group_min))) {
3402 sds->group_min = group;
3403 sds->min_nr_running = sgs->sum_nr_running;
3404 sds->min_load_per_task = sgs->sum_weighted_load /
3405 sgs->sum_nr_running;
3409 * Calculate the group which is almost near its
3410 * capacity but still has some space to pick up some load
3411 * from other group and save more power
3413 if (sgs->sum_nr_running > sgs->group_capacity - 1)
3416 if (sgs->sum_nr_running > sds->leader_nr_running ||
3417 (sgs->sum_nr_running == sds->leader_nr_running &&
3418 group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
3419 sds->group_leader = group;
3420 sds->leader_nr_running = sgs->sum_nr_running;
3425 * check_power_save_busiest_group - see if there is potential for some power-savings balance
3426 * @sds: Variable containing the statistics of the sched_domain
3427 * under consideration.
3428 * @this_cpu: Cpu at which we're currently performing load-balancing.
3429 * @imbalance: Variable to store the imbalance.
3432 * Check if we have potential to perform some power-savings balance.
3433 * If yes, set the busiest group to be the least loaded group in the
3434 * sched_domain, so that it's CPUs can be put to idle.
3436 * Returns 1 if there is potential to perform power-savings balance.
3439 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3440 int this_cpu, unsigned long *imbalance)
3442 if (!sds->power_savings_balance)
3445 if (sds->this != sds->group_leader ||
3446 sds->group_leader == sds->group_min)
3449 *imbalance = sds->min_load_per_task;
3450 sds->busiest = sds->group_min;
3452 if (sched_mc_power_savings >= POWERSAVINGS_BALANCE_WAKEUP) {
3453 cpu_rq(this_cpu)->rd->sched_mc_preferred_wakeup_cpu =
3454 group_first_cpu(sds->group_leader);
3460 #else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3461 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3462 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3467 static inline void update_sd_power_savings_stats(struct sched_group *group,
3468 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3473 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3474 int this_cpu, unsigned long *imbalance)
3478 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3482 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
3483 * @group: sched_group whose statistics are to be updated.
3484 * @this_cpu: Cpu for which load balance is currently performed.
3485 * @idle: Idle status of this_cpu
3486 * @load_idx: Load index of sched_domain of this_cpu for load calc.
3487 * @sd_idle: Idle status of the sched_domain containing group.
3488 * @local_group: Does group contain this_cpu.
3489 * @cpus: Set of cpus considered for load balancing.
3490 * @balance: Should we balance.
3491 * @sgs: variable to hold the statistics for this group.
3493 static inline void update_sg_lb_stats(struct sched_group *group, int this_cpu,
3494 enum cpu_idle_type idle, int load_idx, int *sd_idle,
3495 int local_group, const struct cpumask *cpus,
3496 int *balance, struct sg_lb_stats *sgs)
3498 unsigned long load, max_cpu_load, min_cpu_load;
3500 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3501 unsigned long sum_avg_load_per_task;
3502 unsigned long avg_load_per_task;
3505 balance_cpu = group_first_cpu(group);
3507 /* Tally up the load of all CPUs in the group */
3508 sum_avg_load_per_task = avg_load_per_task = 0;
3510 min_cpu_load = ~0UL;
3512 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
3513 struct rq *rq = cpu_rq(i);
3515 if (*sd_idle && rq->nr_running)
3518 /* Bias balancing toward cpus of our domain */
3520 if (idle_cpu(i) && !first_idle_cpu) {
3525 load = target_load(i, load_idx);
3527 load = source_load(i, load_idx);
3528 if (load > max_cpu_load)
3529 max_cpu_load = load;
3530 if (min_cpu_load > load)
3531 min_cpu_load = load;
3534 sgs->group_load += load;
3535 sgs->sum_nr_running += rq->nr_running;
3536 sgs->sum_weighted_load += weighted_cpuload(i);
3538 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3542 * First idle cpu or the first cpu(busiest) in this sched group
3543 * is eligible for doing load balancing at this and above
3544 * domains. In the newly idle case, we will allow all the cpu's
3545 * to do the newly idle load balance.
3547 if (idle != CPU_NEWLY_IDLE && local_group &&
3548 balance_cpu != this_cpu && balance) {
3553 /* Adjust by relative CPU power of the group */
3554 sgs->avg_load = sg_div_cpu_power(group,
3555 sgs->group_load * SCHED_LOAD_SCALE);
3559 * Consider the group unbalanced when the imbalance is larger
3560 * than the average weight of two tasks.
3562 * APZ: with cgroup the avg task weight can vary wildly and
3563 * might not be a suitable number - should we keep a
3564 * normalized nr_running number somewhere that negates
3567 avg_load_per_task = sg_div_cpu_power(group,
3568 sum_avg_load_per_task * SCHED_LOAD_SCALE);
3570 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3573 sgs->group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3578 * update_sd_lb_stats - Update sched_group's statistics for load balancing.
3579 * @sd: sched_domain whose statistics are to be updated.
3580 * @this_cpu: Cpu for which load balance is currently performed.
3581 * @idle: Idle status of this_cpu
3582 * @sd_idle: Idle status of the sched_domain containing group.
3583 * @cpus: Set of cpus considered for load balancing.
3584 * @balance: Should we balance.
3585 * @sds: variable to hold the statistics for this sched_domain.
3587 static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
3588 enum cpu_idle_type idle, int *sd_idle,
3589 const struct cpumask *cpus, int *balance,
3590 struct sd_lb_stats *sds)
3592 struct sched_group *group = sd->groups;
3593 struct sg_lb_stats sgs;
3596 init_sd_power_savings_stats(sd, sds, idle);
3597 load_idx = get_sd_load_idx(sd, idle);
3602 local_group = cpumask_test_cpu(this_cpu,
3603 sched_group_cpus(group));
3604 memset(&sgs, 0, sizeof(sgs));
3605 update_sg_lb_stats(group, this_cpu, idle, load_idx, sd_idle,
3606 local_group, cpus, balance, &sgs);
3608 if (local_group && balance && !(*balance))
3611 sds->total_load += sgs.group_load;
3612 sds->total_pwr += group->__cpu_power;
3615 sds->this_load = sgs.avg_load;
3617 sds->this_nr_running = sgs.sum_nr_running;
3618 sds->this_load_per_task = sgs.sum_weighted_load;
3619 } else if (sgs.avg_load > sds->max_load &&
3620 (sgs.sum_nr_running > sgs.group_capacity ||
3622 sds->max_load = sgs.avg_load;
3623 sds->busiest = group;
3624 sds->busiest_nr_running = sgs.sum_nr_running;
3625 sds->busiest_load_per_task = sgs.sum_weighted_load;
3626 sds->group_imb = sgs.group_imb;
3629 update_sd_power_savings_stats(group, sds, local_group, &sgs);
3630 group = group->next;
3631 } while (group != sd->groups);
3636 * fix_small_imbalance - Calculate the minor imbalance that exists
3637 * amongst the groups of a sched_domain, during
3639 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
3640 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
3641 * @imbalance: Variable to store the imbalance.
3643 static inline void fix_small_imbalance(struct sd_lb_stats *sds,
3644 int this_cpu, unsigned long *imbalance)
3646 unsigned long tmp, pwr_now = 0, pwr_move = 0;
3647 unsigned int imbn = 2;
3649 if (sds->this_nr_running) {
3650 sds->this_load_per_task /= sds->this_nr_running;
3651 if (sds->busiest_load_per_task >
3652 sds->this_load_per_task)
3655 sds->this_load_per_task =
3656 cpu_avg_load_per_task(this_cpu);
3658 if (sds->max_load - sds->this_load + sds->busiest_load_per_task >=
3659 sds->busiest_load_per_task * imbn) {
3660 *imbalance = sds->busiest_load_per_task;
3665 * OK, we don't have enough imbalance to justify moving tasks,
3666 * however we may be able to increase total CPU power used by
3670 pwr_now += sds->busiest->__cpu_power *
3671 min(sds->busiest_load_per_task, sds->max_load);
3672 pwr_now += sds->this->__cpu_power *
3673 min(sds->this_load_per_task, sds->this_load);
3674 pwr_now /= SCHED_LOAD_SCALE;
3676 /* Amount of load we'd subtract */
3677 tmp = sg_div_cpu_power(sds->busiest,
3678 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3679 if (sds->max_load > tmp)
3680 pwr_move += sds->busiest->__cpu_power *
3681 min(sds->busiest_load_per_task, sds->max_load - tmp);
3683 /* Amount of load we'd add */
3684 if (sds->max_load * sds->busiest->__cpu_power <
3685 sds->busiest_load_per_task * SCHED_LOAD_SCALE)
3686 tmp = sg_div_cpu_power(sds->this,
3687 sds->max_load * sds->busiest->__cpu_power);
3689 tmp = sg_div_cpu_power(sds->this,
3690 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3691 pwr_move += sds->this->__cpu_power *
3692 min(sds->this_load_per_task, sds->this_load + tmp);
3693 pwr_move /= SCHED_LOAD_SCALE;
3695 /* Move if we gain throughput */
3696 if (pwr_move > pwr_now)
3697 *imbalance = sds->busiest_load_per_task;
3701 * calculate_imbalance - Calculate the amount of imbalance present within the
3702 * groups of a given sched_domain during load balance.
3703 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
3704 * @this_cpu: Cpu for which currently load balance is being performed.
3705 * @imbalance: The variable to store the imbalance.
3707 static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
3708 unsigned long *imbalance)
3710 unsigned long max_pull;
3712 * In the presence of smp nice balancing, certain scenarios can have
3713 * max load less than avg load(as we skip the groups at or below
3714 * its cpu_power, while calculating max_load..)
3716 if (sds->max_load < sds->avg_load) {
3718 return fix_small_imbalance(sds, this_cpu, imbalance);
3721 /* Don't want to pull so many tasks that a group would go idle */
3722 max_pull = min(sds->max_load - sds->avg_load,
3723 sds->max_load - sds->busiest_load_per_task);
3725 /* How much load to actually move to equalise the imbalance */
3726 *imbalance = min(max_pull * sds->busiest->__cpu_power,
3727 (sds->avg_load - sds->this_load) * sds->this->__cpu_power)
3731 * if *imbalance is less than the average load per runnable task
3732 * there is no gaurantee that any tasks will be moved so we'll have
3733 * a think about bumping its value to force at least one task to be
3736 if (*imbalance < sds->busiest_load_per_task)
3737 return fix_small_imbalance(sds, this_cpu, imbalance);
3740 /******* find_busiest_group() helpers end here *********************/
3743 * find_busiest_group - Returns the busiest group within the sched_domain
3744 * if there is an imbalance. If there isn't an imbalance, and
3745 * the user has opted for power-savings, it returns a group whose
3746 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
3747 * such a group exists.
3749 * Also calculates the amount of weighted load which should be moved
3750 * to restore balance.
3752 * @sd: The sched_domain whose busiest group is to be returned.
3753 * @this_cpu: The cpu for which load balancing is currently being performed.
3754 * @imbalance: Variable which stores amount of weighted load which should
3755 * be moved to restore balance/put a group to idle.
3756 * @idle: The idle status of this_cpu.
3757 * @sd_idle: The idleness of sd
3758 * @cpus: The set of CPUs under consideration for load-balancing.
3759 * @balance: Pointer to a variable indicating if this_cpu
3760 * is the appropriate cpu to perform load balancing at this_level.
3762 * Returns: - the busiest group if imbalance exists.
3763 * - If no imbalance and user has opted for power-savings balance,
3764 * return the least loaded group whose CPUs can be
3765 * put to idle by rebalancing its tasks onto our group.
3767 static struct sched_group *
3768 find_busiest_group(struct sched_domain *sd, int this_cpu,
3769 unsigned long *imbalance, enum cpu_idle_type idle,
3770 int *sd_idle, const struct cpumask *cpus, int *balance)
3772 struct sd_lb_stats sds;
3774 memset(&sds, 0, sizeof(sds));
3777 * Compute the various statistics relavent for load balancing at
3780 update_sd_lb_stats(sd, this_cpu, idle, sd_idle, cpus,
3783 /* Cases where imbalance does not exist from POV of this_cpu */
3784 /* 1) this_cpu is not the appropriate cpu to perform load balancing
3786 * 2) There is no busy sibling group to pull from.
3787 * 3) This group is the busiest group.
3788 * 4) This group is more busy than the avg busieness at this
3790 * 5) The imbalance is within the specified limit.
3791 * 6) Any rebalance would lead to ping-pong
3793 if (balance && !(*balance))
3796 if (!sds.busiest || sds.busiest_nr_running == 0)
3799 if (sds.this_load >= sds.max_load)
3802 sds.avg_load = (SCHED_LOAD_SCALE * sds.total_load) / sds.total_pwr;
3804 if (sds.this_load >= sds.avg_load)
3807 if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
3810 sds.busiest_load_per_task /= sds.busiest_nr_running;
3812 sds.busiest_load_per_task =
3813 min(sds.busiest_load_per_task, sds.avg_load);
3816 * We're trying to get all the cpus to the average_load, so we don't
3817 * want to push ourselves above the average load, nor do we wish to
3818 * reduce the max loaded cpu below the average load, as either of these
3819 * actions would just result in more rebalancing later, and ping-pong
3820 * tasks around. Thus we look for the minimum possible imbalance.
3821 * Negative imbalances (*we* are more loaded than anyone else) will
3822 * be counted as no imbalance for these purposes -- we can't fix that
3823 * by pulling tasks to us. Be careful of negative numbers as they'll
3824 * appear as very large values with unsigned longs.
3826 if (sds.max_load <= sds.busiest_load_per_task)
3829 /* Looks like there is an imbalance. Compute it */
3830 calculate_imbalance(&sds, this_cpu, imbalance);
3835 * There is no obvious imbalance. But check if we can do some balancing
3838 if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
3846 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3849 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3850 unsigned long imbalance, const struct cpumask *cpus)
3852 struct rq *busiest = NULL, *rq;
3853 unsigned long max_load = 0;
3856 for_each_cpu(i, sched_group_cpus(group)) {
3859 if (!cpumask_test_cpu(i, cpus))
3863 wl = weighted_cpuload(i);
3865 if (rq->nr_running == 1 && wl > imbalance)
3868 if (wl > max_load) {
3878 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3879 * so long as it is large enough.
3881 #define MAX_PINNED_INTERVAL 512
3883 /* Working cpumask for load_balance and load_balance_newidle. */
3884 static DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
3887 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3888 * tasks if there is an imbalance.
3890 static int load_balance(int this_cpu, struct rq *this_rq,
3891 struct sched_domain *sd, enum cpu_idle_type idle,
3894 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3895 struct sched_group *group;
3896 unsigned long imbalance;
3898 unsigned long flags;
3899 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
3901 cpumask_setall(cpus);
3904 * When power savings policy is enabled for the parent domain, idle
3905 * sibling can pick up load irrespective of busy siblings. In this case,
3906 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3907 * portraying it as CPU_NOT_IDLE.
3909 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3910 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3913 schedstat_inc(sd, lb_count[idle]);
3917 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3924 schedstat_inc(sd, lb_nobusyg[idle]);
3928 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3930 schedstat_inc(sd, lb_nobusyq[idle]);
3934 BUG_ON(busiest == this_rq);
3936 schedstat_add(sd, lb_imbalance[idle], imbalance);
3939 if (busiest->nr_running > 1) {
3941 * Attempt to move tasks. If find_busiest_group has found
3942 * an imbalance but busiest->nr_running <= 1, the group is
3943 * still unbalanced. ld_moved simply stays zero, so it is
3944 * correctly treated as an imbalance.
3946 local_irq_save(flags);
3947 double_rq_lock(this_rq, busiest);
3948 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3949 imbalance, sd, idle, &all_pinned);
3950 double_rq_unlock(this_rq, busiest);
3951 local_irq_restore(flags);
3954 * some other cpu did the load balance for us.
3956 if (ld_moved && this_cpu != smp_processor_id())
3957 resched_cpu(this_cpu);
3959 /* All tasks on this runqueue were pinned by CPU affinity */
3960 if (unlikely(all_pinned)) {
3961 cpumask_clear_cpu(cpu_of(busiest), cpus);
3962 if (!cpumask_empty(cpus))
3969 schedstat_inc(sd, lb_failed[idle]);
3970 sd->nr_balance_failed++;
3972 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3974 spin_lock_irqsave(&busiest->lock, flags);
3976 /* don't kick the migration_thread, if the curr
3977 * task on busiest cpu can't be moved to this_cpu
3979 if (!cpumask_test_cpu(this_cpu,
3980 &busiest->curr->cpus_allowed)) {
3981 spin_unlock_irqrestore(&busiest->lock, flags);
3983 goto out_one_pinned;
3986 if (!busiest->active_balance) {
3987 busiest->active_balance = 1;
3988 busiest->push_cpu = this_cpu;
3991 spin_unlock_irqrestore(&busiest->lock, flags);
3993 wake_up_process(busiest->migration_thread);
3996 * We've kicked active balancing, reset the failure
3999 sd->nr_balance_failed = sd->cache_nice_tries+1;
4002 sd->nr_balance_failed = 0;
4004 if (likely(!active_balance)) {
4005 /* We were unbalanced, so reset the balancing interval */
4006 sd->balance_interval = sd->min_interval;
4009 * If we've begun active balancing, start to back off. This
4010 * case may not be covered by the all_pinned logic if there
4011 * is only 1 task on the busy runqueue (because we don't call
4014 if (sd->balance_interval < sd->max_interval)
4015 sd->balance_interval *= 2;
4018 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4019 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4025 schedstat_inc(sd, lb_balanced[idle]);
4027 sd->nr_balance_failed = 0;
4030 /* tune up the balancing interval */
4031 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
4032 (sd->balance_interval < sd->max_interval))
4033 sd->balance_interval *= 2;
4035 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4036 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4047 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4048 * tasks if there is an imbalance.
4050 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
4051 * this_rq is locked.
4054 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
4056 struct sched_group *group;
4057 struct rq *busiest = NULL;
4058 unsigned long imbalance;
4062 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4064 cpumask_setall(cpus);
4067 * When power savings policy is enabled for the parent domain, idle
4068 * sibling can pick up load irrespective of busy siblings. In this case,
4069 * let the state of idle sibling percolate up as IDLE, instead of
4070 * portraying it as CPU_NOT_IDLE.
4072 if (sd->flags & SD_SHARE_CPUPOWER &&
4073 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4076 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
4078 update_shares_locked(this_rq, sd);
4079 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
4080 &sd_idle, cpus, NULL);
4082 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
4086 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
4088 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
4092 BUG_ON(busiest == this_rq);
4094 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
4097 if (busiest->nr_running > 1) {
4098 /* Attempt to move tasks */
4099 double_lock_balance(this_rq, busiest);
4100 /* this_rq->clock is already updated */
4101 update_rq_clock(busiest);
4102 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4103 imbalance, sd, CPU_NEWLY_IDLE,
4105 double_unlock_balance(this_rq, busiest);
4107 if (unlikely(all_pinned)) {
4108 cpumask_clear_cpu(cpu_of(busiest), cpus);
4109 if (!cpumask_empty(cpus))
4115 int active_balance = 0;
4117 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
4118 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4119 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4122 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
4125 if (sd->nr_balance_failed++ < 2)
4129 * The only task running in a non-idle cpu can be moved to this
4130 * cpu in an attempt to completely freeup the other CPU
4131 * package. The same method used to move task in load_balance()
4132 * have been extended for load_balance_newidle() to speedup
4133 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
4135 * The package power saving logic comes from
4136 * find_busiest_group(). If there are no imbalance, then
4137 * f_b_g() will return NULL. However when sched_mc={1,2} then
4138 * f_b_g() will select a group from which a running task may be
4139 * pulled to this cpu in order to make the other package idle.
4140 * If there is no opportunity to make a package idle and if
4141 * there are no imbalance, then f_b_g() will return NULL and no
4142 * action will be taken in load_balance_newidle().
4144 * Under normal task pull operation due to imbalance, there
4145 * will be more than one task in the source run queue and
4146 * move_tasks() will succeed. ld_moved will be true and this
4147 * active balance code will not be triggered.
4150 /* Lock busiest in correct order while this_rq is held */
4151 double_lock_balance(this_rq, busiest);
4154 * don't kick the migration_thread, if the curr
4155 * task on busiest cpu can't be moved to this_cpu
4157 if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
4158 double_unlock_balance(this_rq, busiest);
4163 if (!busiest->active_balance) {
4164 busiest->active_balance = 1;
4165 busiest->push_cpu = this_cpu;
4169 double_unlock_balance(this_rq, busiest);
4171 * Should not call ttwu while holding a rq->lock
4173 spin_unlock(&this_rq->lock);
4175 wake_up_process(busiest->migration_thread);
4176 spin_lock(&this_rq->lock);
4179 sd->nr_balance_failed = 0;
4181 update_shares_locked(this_rq, sd);
4185 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
4186 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4187 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4189 sd->nr_balance_failed = 0;
4195 * idle_balance is called by schedule() if this_cpu is about to become
4196 * idle. Attempts to pull tasks from other CPUs.
4198 static void idle_balance(int this_cpu, struct rq *this_rq)
4200 struct sched_domain *sd;
4201 int pulled_task = 0;
4202 unsigned long next_balance = jiffies + HZ;
4204 for_each_domain(this_cpu, sd) {
4205 unsigned long interval;
4207 if (!(sd->flags & SD_LOAD_BALANCE))
4210 if (sd->flags & SD_BALANCE_NEWIDLE)
4211 /* If we've pulled tasks over stop searching: */
4212 pulled_task = load_balance_newidle(this_cpu, this_rq,
4215 interval = msecs_to_jiffies(sd->balance_interval);
4216 if (time_after(next_balance, sd->last_balance + interval))
4217 next_balance = sd->last_balance + interval;
4221 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4223 * We are going idle. next_balance may be set based on
4224 * a busy processor. So reset next_balance.
4226 this_rq->next_balance = next_balance;
4231 * active_load_balance is run by migration threads. It pushes running tasks
4232 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4233 * running on each physical CPU where possible, and avoids physical /
4234 * logical imbalances.
4236 * Called with busiest_rq locked.
4238 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4240 int target_cpu = busiest_rq->push_cpu;
4241 struct sched_domain *sd;
4242 struct rq *target_rq;
4244 /* Is there any task to move? */
4245 if (busiest_rq->nr_running <= 1)
4248 target_rq = cpu_rq(target_cpu);
4251 * This condition is "impossible", if it occurs
4252 * we need to fix it. Originally reported by
4253 * Bjorn Helgaas on a 128-cpu setup.
4255 BUG_ON(busiest_rq == target_rq);
4257 /* move a task from busiest_rq to target_rq */
4258 double_lock_balance(busiest_rq, target_rq);
4259 update_rq_clock(busiest_rq);
4260 update_rq_clock(target_rq);
4262 /* Search for an sd spanning us and the target CPU. */
4263 for_each_domain(target_cpu, sd) {
4264 if ((sd->flags & SD_LOAD_BALANCE) &&
4265 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4270 schedstat_inc(sd, alb_count);
4272 if (move_one_task(target_rq, target_cpu, busiest_rq,
4274 schedstat_inc(sd, alb_pushed);
4276 schedstat_inc(sd, alb_failed);
4278 double_unlock_balance(busiest_rq, target_rq);
4283 atomic_t load_balancer;
4284 cpumask_var_t cpu_mask;
4285 } nohz ____cacheline_aligned = {
4286 .load_balancer = ATOMIC_INIT(-1),
4290 * This routine will try to nominate the ilb (idle load balancing)
4291 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4292 * load balancing on behalf of all those cpus. If all the cpus in the system
4293 * go into this tickless mode, then there will be no ilb owner (as there is
4294 * no need for one) and all the cpus will sleep till the next wakeup event
4297 * For the ilb owner, tick is not stopped. And this tick will be used
4298 * for idle load balancing. ilb owner will still be part of
4301 * While stopping the tick, this cpu will become the ilb owner if there
4302 * is no other owner. And will be the owner till that cpu becomes busy
4303 * or if all cpus in the system stop their ticks at which point
4304 * there is no need for ilb owner.
4306 * When the ilb owner becomes busy, it nominates another owner, during the
4307 * next busy scheduler_tick()
4309 int select_nohz_load_balancer(int stop_tick)
4311 int cpu = smp_processor_id();
4314 cpu_rq(cpu)->in_nohz_recently = 1;
4316 if (!cpu_active(cpu)) {
4317 if (atomic_read(&nohz.load_balancer) != cpu)
4321 * If we are going offline and still the leader,
4324 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4330 cpumask_set_cpu(cpu, nohz.cpu_mask);
4332 /* time for ilb owner also to sleep */
4333 if (cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4334 if (atomic_read(&nohz.load_balancer) == cpu)
4335 atomic_set(&nohz.load_balancer, -1);
4339 if (atomic_read(&nohz.load_balancer) == -1) {
4340 /* make me the ilb owner */
4341 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4343 } else if (atomic_read(&nohz.load_balancer) == cpu)
4346 if (!cpumask_test_cpu(cpu, nohz.cpu_mask))
4349 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4351 if (atomic_read(&nohz.load_balancer) == cpu)
4352 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4359 static DEFINE_SPINLOCK(balancing);
4362 * It checks each scheduling domain to see if it is due to be balanced,
4363 * and initiates a balancing operation if so.
4365 * Balancing parameters are set up in arch_init_sched_domains.
4367 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4370 struct rq *rq = cpu_rq(cpu);
4371 unsigned long interval;
4372 struct sched_domain *sd;
4373 /* Earliest time when we have to do rebalance again */
4374 unsigned long next_balance = jiffies + 60*HZ;
4375 int update_next_balance = 0;
4378 for_each_domain(cpu, sd) {
4379 if (!(sd->flags & SD_LOAD_BALANCE))
4382 interval = sd->balance_interval;
4383 if (idle != CPU_IDLE)
4384 interval *= sd->busy_factor;
4386 /* scale ms to jiffies */
4387 interval = msecs_to_jiffies(interval);
4388 if (unlikely(!interval))
4390 if (interval > HZ*NR_CPUS/10)
4391 interval = HZ*NR_CPUS/10;
4393 need_serialize = sd->flags & SD_SERIALIZE;
4395 if (need_serialize) {
4396 if (!spin_trylock(&balancing))
4400 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4401 if (load_balance(cpu, rq, sd, idle, &balance)) {
4403 * We've pulled tasks over so either we're no
4404 * longer idle, or one of our SMT siblings is
4407 idle = CPU_NOT_IDLE;
4409 sd->last_balance = jiffies;
4412 spin_unlock(&balancing);
4414 if (time_after(next_balance, sd->last_balance + interval)) {
4415 next_balance = sd->last_balance + interval;
4416 update_next_balance = 1;
4420 * Stop the load balance at this level. There is another
4421 * CPU in our sched group which is doing load balancing more
4429 * next_balance will be updated only when there is a need.
4430 * When the cpu is attached to null domain for ex, it will not be
4433 if (likely(update_next_balance))
4434 rq->next_balance = next_balance;
4438 * run_rebalance_domains is triggered when needed from the scheduler tick.
4439 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4440 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4442 static void run_rebalance_domains(struct softirq_action *h)
4444 int this_cpu = smp_processor_id();
4445 struct rq *this_rq = cpu_rq(this_cpu);
4446 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4447 CPU_IDLE : CPU_NOT_IDLE;
4449 rebalance_domains(this_cpu, idle);
4453 * If this cpu is the owner for idle load balancing, then do the
4454 * balancing on behalf of the other idle cpus whose ticks are
4457 if (this_rq->idle_at_tick &&
4458 atomic_read(&nohz.load_balancer) == this_cpu) {
4462 for_each_cpu(balance_cpu, nohz.cpu_mask) {
4463 if (balance_cpu == this_cpu)
4467 * If this cpu gets work to do, stop the load balancing
4468 * work being done for other cpus. Next load
4469 * balancing owner will pick it up.
4474 rebalance_domains(balance_cpu, CPU_IDLE);
4476 rq = cpu_rq(balance_cpu);
4477 if (time_after(this_rq->next_balance, rq->next_balance))
4478 this_rq->next_balance = rq->next_balance;
4484 static inline int on_null_domain(int cpu)
4486 return !rcu_dereference(cpu_rq(cpu)->sd);
4490 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4492 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4493 * idle load balancing owner or decide to stop the periodic load balancing,
4494 * if the whole system is idle.
4496 static inline void trigger_load_balance(struct rq *rq, int cpu)
4500 * If we were in the nohz mode recently and busy at the current
4501 * scheduler tick, then check if we need to nominate new idle
4504 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4505 rq->in_nohz_recently = 0;
4507 if (atomic_read(&nohz.load_balancer) == cpu) {
4508 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4509 atomic_set(&nohz.load_balancer, -1);
4512 if (atomic_read(&nohz.load_balancer) == -1) {
4514 * simple selection for now: Nominate the
4515 * first cpu in the nohz list to be the next
4518 * TBD: Traverse the sched domains and nominate
4519 * the nearest cpu in the nohz.cpu_mask.
4521 int ilb = cpumask_first(nohz.cpu_mask);
4523 if (ilb < nr_cpu_ids)
4529 * If this cpu is idle and doing idle load balancing for all the
4530 * cpus with ticks stopped, is it time for that to stop?
4532 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4533 cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4539 * If this cpu is idle and the idle load balancing is done by
4540 * someone else, then no need raise the SCHED_SOFTIRQ
4542 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4543 cpumask_test_cpu(cpu, nohz.cpu_mask))
4546 /* Don't need to rebalance while attached to NULL domain */
4547 if (time_after_eq(jiffies, rq->next_balance) &&
4548 likely(!on_null_domain(cpu)))
4549 raise_softirq(SCHED_SOFTIRQ);
4552 #else /* CONFIG_SMP */
4555 * on UP we do not need to balance between CPUs:
4557 static inline void idle_balance(int cpu, struct rq *rq)
4563 DEFINE_PER_CPU(struct kernel_stat, kstat);
4565 EXPORT_PER_CPU_SYMBOL(kstat);
4568 * Return any ns on the sched_clock that have not yet been banked in
4569 * @p in case that task is currently running.
4571 unsigned long long __task_delta_exec(struct task_struct *p, int update)
4577 WARN_ON_ONCE(!runqueue_is_locked());
4578 WARN_ON_ONCE(!task_current(rq, p));
4581 update_rq_clock(rq);
4583 delta_exec = rq->clock - p->se.exec_start;
4585 WARN_ON_ONCE(delta_exec < 0);
4591 * Return any ns on the sched_clock that have not yet been banked in
4592 * @p in case that task is currently running.
4594 unsigned long long task_delta_exec(struct task_struct *p)
4596 unsigned long flags;
4600 rq = task_rq_lock(p, &flags);
4602 if (task_current(rq, p)) {
4605 update_rq_clock(rq);
4606 delta_exec = rq->clock - p->se.exec_start;
4607 if ((s64)delta_exec > 0)
4611 task_rq_unlock(rq, &flags);
4617 * Account user cpu time to a process.
4618 * @p: the process that the cpu time gets accounted to
4619 * @cputime: the cpu time spent in user space since the last update
4620 * @cputime_scaled: cputime scaled by cpu frequency
4622 void account_user_time(struct task_struct *p, cputime_t cputime,
4623 cputime_t cputime_scaled)
4625 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4628 /* Add user time to process. */
4629 p->utime = cputime_add(p->utime, cputime);
4630 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4631 account_group_user_time(p, cputime);
4633 /* Add user time to cpustat. */
4634 tmp = cputime_to_cputime64(cputime);
4635 if (TASK_NICE(p) > 0)
4636 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4638 cpustat->user = cputime64_add(cpustat->user, tmp);
4639 /* Account for user time used */
4640 acct_update_integrals(p);
4644 * Account guest cpu time to a process.
4645 * @p: the process that the cpu time gets accounted to
4646 * @cputime: the cpu time spent in virtual machine since the last update
4647 * @cputime_scaled: cputime scaled by cpu frequency
4649 static void account_guest_time(struct task_struct *p, cputime_t cputime,
4650 cputime_t cputime_scaled)
4653 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4655 tmp = cputime_to_cputime64(cputime);
4657 /* Add guest time to process. */
4658 p->utime = cputime_add(p->utime, cputime);
4659 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4660 account_group_user_time(p, cputime);
4661 p->gtime = cputime_add(p->gtime, cputime);
4663 /* Add guest time to cpustat. */
4664 cpustat->user = cputime64_add(cpustat->user, tmp);
4665 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4669 * Account system cpu time to a process.
4670 * @p: the process that the cpu time gets accounted to
4671 * @hardirq_offset: the offset to subtract from hardirq_count()
4672 * @cputime: the cpu time spent in kernel space since the last update
4673 * @cputime_scaled: cputime scaled by cpu frequency
4675 void account_system_time(struct task_struct *p, int hardirq_offset,
4676 cputime_t cputime, cputime_t cputime_scaled)
4678 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4681 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4682 account_guest_time(p, cputime, cputime_scaled);
4686 /* Add system time to process. */
4687 p->stime = cputime_add(p->stime, cputime);
4688 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
4689 account_group_system_time(p, cputime);
4691 /* Add system time to cpustat. */
4692 tmp = cputime_to_cputime64(cputime);
4693 if (hardirq_count() - hardirq_offset)
4694 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4695 else if (softirq_count())
4696 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4698 cpustat->system = cputime64_add(cpustat->system, tmp);
4700 /* Account for system time used */
4701 acct_update_integrals(p);
4705 * Account for involuntary wait time.
4706 * @steal: the cpu time spent in involuntary wait
4708 void account_steal_time(cputime_t cputime)
4710 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4711 cputime64_t cputime64 = cputime_to_cputime64(cputime);
4713 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
4717 * Account for idle time.
4718 * @cputime: the cpu time spent in idle wait
4720 void account_idle_time(cputime_t cputime)
4722 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4723 cputime64_t cputime64 = cputime_to_cputime64(cputime);
4724 struct rq *rq = this_rq();
4726 if (atomic_read(&rq->nr_iowait) > 0)
4727 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
4729 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
4732 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
4735 * Account a single tick of cpu time.
4736 * @p: the process that the cpu time gets accounted to
4737 * @user_tick: indicates if the tick is a user or a system tick
4739 void account_process_tick(struct task_struct *p, int user_tick)
4741 cputime_t one_jiffy = jiffies_to_cputime(1);
4742 cputime_t one_jiffy_scaled = cputime_to_scaled(one_jiffy);
4743 struct rq *rq = this_rq();
4746 account_user_time(p, one_jiffy, one_jiffy_scaled);
4747 else if (p != rq->idle)
4748 account_system_time(p, HARDIRQ_OFFSET, one_jiffy,
4751 account_idle_time(one_jiffy);
4755 * Account multiple ticks of steal time.
4756 * @p: the process from which the cpu time has been stolen
4757 * @ticks: number of stolen ticks
4759 void account_steal_ticks(unsigned long ticks)
4761 account_steal_time(jiffies_to_cputime(ticks));
4765 * Account multiple ticks of idle time.
4766 * @ticks: number of stolen ticks
4768 void account_idle_ticks(unsigned long ticks)
4770 account_idle_time(jiffies_to_cputime(ticks));
4776 * Use precise platform statistics if available:
4778 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
4779 cputime_t task_utime(struct task_struct *p)
4784 cputime_t task_stime(struct task_struct *p)
4789 cputime_t task_utime(struct task_struct *p)
4791 clock_t utime = cputime_to_clock_t(p->utime),
4792 total = utime + cputime_to_clock_t(p->stime);
4796 * Use CFS's precise accounting:
4798 temp = (u64)nsec_to_clock_t(p->se.sum_exec_runtime);
4802 do_div(temp, total);
4804 utime = (clock_t)temp;
4806 p->prev_utime = max(p->prev_utime, clock_t_to_cputime(utime));
4807 return p->prev_utime;
4810 cputime_t task_stime(struct task_struct *p)
4815 * Use CFS's precise accounting. (we subtract utime from
4816 * the total, to make sure the total observed by userspace
4817 * grows monotonically - apps rely on that):
4819 stime = nsec_to_clock_t(p->se.sum_exec_runtime) -
4820 cputime_to_clock_t(task_utime(p));
4823 p->prev_stime = max(p->prev_stime, clock_t_to_cputime(stime));
4825 return p->prev_stime;
4829 inline cputime_t task_gtime(struct task_struct *p)
4835 * This function gets called by the timer code, with HZ frequency.
4836 * We call it with interrupts disabled.
4838 * It also gets called by the fork code, when changing the parent's
4841 void scheduler_tick(void)
4843 int cpu = smp_processor_id();
4844 struct rq *rq = cpu_rq(cpu);
4845 struct task_struct *curr = rq->curr;
4849 spin_lock(&rq->lock);
4850 update_rq_clock(rq);
4851 update_cpu_load(rq);
4852 curr->sched_class->task_tick(rq, curr, 0);
4853 perf_counter_task_tick(curr, cpu);
4854 spin_unlock(&rq->lock);
4857 rq->idle_at_tick = idle_cpu(cpu);
4858 trigger_load_balance(rq, cpu);
4862 unsigned long get_parent_ip(unsigned long addr)
4864 if (in_lock_functions(addr)) {
4865 addr = CALLER_ADDR2;
4866 if (in_lock_functions(addr))
4867 addr = CALLER_ADDR3;
4872 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4873 defined(CONFIG_PREEMPT_TRACER))
4875 void __kprobes add_preempt_count(int val)
4877 #ifdef CONFIG_DEBUG_PREEMPT
4881 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4884 preempt_count() += val;
4885 #ifdef CONFIG_DEBUG_PREEMPT
4887 * Spinlock count overflowing soon?
4889 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4892 if (preempt_count() == val)
4893 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4895 EXPORT_SYMBOL(add_preempt_count);
4897 void __kprobes sub_preempt_count(int val)
4899 #ifdef CONFIG_DEBUG_PREEMPT
4903 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4906 * Is the spinlock portion underflowing?
4908 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4909 !(preempt_count() & PREEMPT_MASK)))
4913 if (preempt_count() == val)
4914 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4915 preempt_count() -= val;
4917 EXPORT_SYMBOL(sub_preempt_count);
4922 * Print scheduling while atomic bug:
4924 static noinline void __schedule_bug(struct task_struct *prev)
4926 struct pt_regs *regs = get_irq_regs();
4928 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4929 prev->comm, prev->pid, preempt_count());
4931 debug_show_held_locks(prev);
4933 if (irqs_disabled())
4934 print_irqtrace_events(prev);
4943 * Various schedule()-time debugging checks and statistics:
4945 static inline void schedule_debug(struct task_struct *prev)
4948 * Test if we are atomic. Since do_exit() needs to call into
4949 * schedule() atomically, we ignore that path for now.
4950 * Otherwise, whine if we are scheduling when we should not be.
4952 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
4953 __schedule_bug(prev);
4955 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4957 schedstat_inc(this_rq(), sched_count);
4958 #ifdef CONFIG_SCHEDSTATS
4959 if (unlikely(prev->lock_depth >= 0)) {
4960 schedstat_inc(this_rq(), bkl_count);
4961 schedstat_inc(prev, sched_info.bkl_count);
4966 static void put_prev_task(struct rq *rq, struct task_struct *prev)
4968 if (prev->state == TASK_RUNNING) {
4969 u64 runtime = prev->se.sum_exec_runtime;
4971 runtime -= prev->se.prev_sum_exec_runtime;
4972 runtime = min_t(u64, runtime, 2*sysctl_sched_migration_cost);
4975 * In order to avoid avg_overlap growing stale when we are
4976 * indeed overlapping and hence not getting put to sleep, grow
4977 * the avg_overlap on preemption.
4979 * We use the average preemption runtime because that
4980 * correlates to the amount of cache footprint a task can
4983 update_avg(&prev->se.avg_overlap, runtime);
4985 prev->sched_class->put_prev_task(rq, prev);
4989 * Pick up the highest-prio task:
4991 static inline struct task_struct *
4992 pick_next_task(struct rq *rq)
4994 const struct sched_class *class;
4995 struct task_struct *p;
4998 * Optimization: we know that if all tasks are in
4999 * the fair class we can call that function directly:
5001 if (likely(rq->nr_running == rq->cfs.nr_running)) {
5002 p = fair_sched_class.pick_next_task(rq);
5007 class = sched_class_highest;
5009 p = class->pick_next_task(rq);
5013 * Will never be NULL as the idle class always
5014 * returns a non-NULL p:
5016 class = class->next;
5021 * schedule() is the main scheduler function.
5023 asmlinkage void __sched __schedule(void)
5025 struct task_struct *prev, *next;
5026 unsigned long *switch_count;
5030 cpu = smp_processor_id();
5034 switch_count = &prev->nivcsw;
5036 release_kernel_lock(prev);
5037 need_resched_nonpreemptible:
5039 schedule_debug(prev);
5041 if (sched_feat(HRTICK))
5044 spin_lock_irq(&rq->lock);
5045 update_rq_clock(rq);
5046 clear_tsk_need_resched(prev);
5048 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
5049 if (unlikely(signal_pending_state(prev->state, prev)))
5050 prev->state = TASK_RUNNING;
5052 deactivate_task(rq, prev, 1);
5053 switch_count = &prev->nvcsw;
5057 if (prev->sched_class->pre_schedule)
5058 prev->sched_class->pre_schedule(rq, prev);
5061 if (unlikely(!rq->nr_running))
5062 idle_balance(cpu, rq);
5064 put_prev_task(rq, prev);
5065 next = pick_next_task(rq);
5067 if (likely(prev != next)) {
5068 sched_info_switch(prev, next);
5069 perf_counter_task_sched_out(prev, cpu);
5075 context_switch(rq, prev, next); /* unlocks the rq */
5077 * the context switch might have flipped the stack from under
5078 * us, hence refresh the local variables.
5080 cpu = smp_processor_id();
5083 spin_unlock_irq(&rq->lock);
5085 if (unlikely(reacquire_kernel_lock(current) < 0))
5086 goto need_resched_nonpreemptible;
5089 asmlinkage void __sched schedule(void)
5094 preempt_enable_no_resched();
5095 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
5098 EXPORT_SYMBOL(schedule);
5102 * Look out! "owner" is an entirely speculative pointer
5103 * access and not reliable.
5105 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
5110 if (!sched_feat(OWNER_SPIN))
5113 #ifdef CONFIG_DEBUG_PAGEALLOC
5115 * Need to access the cpu field knowing that
5116 * DEBUG_PAGEALLOC could have unmapped it if
5117 * the mutex owner just released it and exited.
5119 if (probe_kernel_address(&owner->cpu, cpu))
5126 * Even if the access succeeded (likely case),
5127 * the cpu field may no longer be valid.
5129 if (cpu >= nr_cpumask_bits)
5133 * We need to validate that we can do a
5134 * get_cpu() and that we have the percpu area.
5136 if (!cpu_online(cpu))
5143 * Owner changed, break to re-assess state.
5145 if (lock->owner != owner)
5149 * Is that owner really running on that cpu?
5151 if (task_thread_info(rq->curr) != owner || need_resched())
5161 #ifdef CONFIG_PREEMPT
5163 * this is the entry point to schedule() from in-kernel preemption
5164 * off of preempt_enable. Kernel preemptions off return from interrupt
5165 * occur there and call schedule directly.
5167 asmlinkage void __sched preempt_schedule(void)
5169 struct thread_info *ti = current_thread_info();
5172 * If there is a non-zero preempt_count or interrupts are disabled,
5173 * we do not want to preempt the current task. Just return..
5175 if (likely(ti->preempt_count || irqs_disabled()))
5179 add_preempt_count(PREEMPT_ACTIVE);
5181 sub_preempt_count(PREEMPT_ACTIVE);
5184 * Check again in case we missed a preemption opportunity
5185 * between schedule and now.
5188 } while (need_resched());
5190 EXPORT_SYMBOL(preempt_schedule);
5193 * this is the entry point to schedule() from kernel preemption
5194 * off of irq context.
5195 * Note, that this is called and return with irqs disabled. This will
5196 * protect us against recursive calling from irq.
5198 asmlinkage void __sched preempt_schedule_irq(void)
5200 struct thread_info *ti = current_thread_info();
5202 /* Catch callers which need to be fixed */
5203 BUG_ON(ti->preempt_count || !irqs_disabled());
5206 add_preempt_count(PREEMPT_ACTIVE);
5209 local_irq_disable();
5210 sub_preempt_count(PREEMPT_ACTIVE);
5213 * Check again in case we missed a preemption opportunity
5214 * between schedule and now.
5217 } while (need_resched());
5220 #endif /* CONFIG_PREEMPT */
5222 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
5225 return try_to_wake_up(curr->private, mode, sync);
5227 EXPORT_SYMBOL(default_wake_function);
5230 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
5231 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
5232 * number) then we wake all the non-exclusive tasks and one exclusive task.
5234 * There are circumstances in which we can try to wake a task which has already
5235 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
5236 * zero in this (rare) case, and we handle it by continuing to scan the queue.
5238 void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
5239 int nr_exclusive, int sync, void *key)
5241 wait_queue_t *curr, *next;
5243 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
5244 unsigned flags = curr->flags;
5246 if (curr->func(curr, mode, sync, key) &&
5247 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
5253 * __wake_up - wake up threads blocked on a waitqueue.
5255 * @mode: which threads
5256 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5257 * @key: is directly passed to the wakeup function
5259 void __wake_up(wait_queue_head_t *q, unsigned int mode,
5260 int nr_exclusive, void *key)
5262 unsigned long flags;
5264 spin_lock_irqsave(&q->lock, flags);
5265 __wake_up_common(q, mode, nr_exclusive, 0, key);
5266 spin_unlock_irqrestore(&q->lock, flags);
5268 EXPORT_SYMBOL(__wake_up);
5271 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
5273 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
5275 __wake_up_common(q, mode, 1, 0, NULL);
5278 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
5280 __wake_up_common(q, mode, 1, 0, key);
5284 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
5286 * @mode: which threads
5287 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5288 * @key: opaque value to be passed to wakeup targets
5290 * The sync wakeup differs that the waker knows that it will schedule
5291 * away soon, so while the target thread will be woken up, it will not
5292 * be migrated to another CPU - ie. the two threads are 'synchronized'
5293 * with each other. This can prevent needless bouncing between CPUs.
5295 * On UP it can prevent extra preemption.
5297 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
5298 int nr_exclusive, void *key)
5300 unsigned long flags;
5306 if (unlikely(!nr_exclusive))
5309 spin_lock_irqsave(&q->lock, flags);
5310 __wake_up_common(q, mode, nr_exclusive, sync, key);
5311 spin_unlock_irqrestore(&q->lock, flags);
5313 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
5316 * __wake_up_sync - see __wake_up_sync_key()
5318 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
5320 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
5322 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
5325 * complete: - signals a single thread waiting on this completion
5326 * @x: holds the state of this particular completion
5328 * This will wake up a single thread waiting on this completion. Threads will be
5329 * awakened in the same order in which they were queued.
5331 * See also complete_all(), wait_for_completion() and related routines.
5333 void complete(struct completion *x)
5335 unsigned long flags;
5337 spin_lock_irqsave(&x->wait.lock, flags);
5339 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
5340 spin_unlock_irqrestore(&x->wait.lock, flags);
5342 EXPORT_SYMBOL(complete);
5345 * complete_all: - signals all threads waiting on this completion
5346 * @x: holds the state of this particular completion
5348 * This will wake up all threads waiting on this particular completion event.
5350 void complete_all(struct completion *x)
5352 unsigned long flags;
5354 spin_lock_irqsave(&x->wait.lock, flags);
5355 x->done += UINT_MAX/2;
5356 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
5357 spin_unlock_irqrestore(&x->wait.lock, flags);
5359 EXPORT_SYMBOL(complete_all);
5361 static inline long __sched
5362 do_wait_for_common(struct completion *x, long timeout, int state)
5365 DECLARE_WAITQUEUE(wait, current);
5367 wait.flags |= WQ_FLAG_EXCLUSIVE;
5368 __add_wait_queue_tail(&x->wait, &wait);
5370 if (signal_pending_state(state, current)) {
5371 timeout = -ERESTARTSYS;
5374 __set_current_state(state);
5375 spin_unlock_irq(&x->wait.lock);
5376 timeout = schedule_timeout(timeout);
5377 spin_lock_irq(&x->wait.lock);
5378 } while (!x->done && timeout);
5379 __remove_wait_queue(&x->wait, &wait);
5384 return timeout ?: 1;
5388 wait_for_common(struct completion *x, long timeout, int state)
5392 spin_lock_irq(&x->wait.lock);
5393 timeout = do_wait_for_common(x, timeout, state);
5394 spin_unlock_irq(&x->wait.lock);
5399 * wait_for_completion: - waits for completion of a task
5400 * @x: holds the state of this particular completion
5402 * This waits to be signaled for completion of a specific task. It is NOT
5403 * interruptible and there is no timeout.
5405 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
5406 * and interrupt capability. Also see complete().
5408 void __sched wait_for_completion(struct completion *x)
5410 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
5412 EXPORT_SYMBOL(wait_for_completion);
5415 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
5416 * @x: holds the state of this particular completion
5417 * @timeout: timeout value in jiffies
5419 * This waits for either a completion of a specific task to be signaled or for a
5420 * specified timeout to expire. The timeout is in jiffies. It is not
5423 unsigned long __sched
5424 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
5426 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
5428 EXPORT_SYMBOL(wait_for_completion_timeout);
5431 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
5432 * @x: holds the state of this particular completion
5434 * This waits for completion of a specific task to be signaled. It is
5437 int __sched wait_for_completion_interruptible(struct completion *x)
5439 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
5440 if (t == -ERESTARTSYS)
5444 EXPORT_SYMBOL(wait_for_completion_interruptible);
5447 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
5448 * @x: holds the state of this particular completion
5449 * @timeout: timeout value in jiffies
5451 * This waits for either a completion of a specific task to be signaled or for a
5452 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
5454 unsigned long __sched
5455 wait_for_completion_interruptible_timeout(struct completion *x,
5456 unsigned long timeout)
5458 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
5460 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
5463 * wait_for_completion_killable: - waits for completion of a task (killable)
5464 * @x: holds the state of this particular completion
5466 * This waits to be signaled for completion of a specific task. It can be
5467 * interrupted by a kill signal.
5469 int __sched wait_for_completion_killable(struct completion *x)
5471 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
5472 if (t == -ERESTARTSYS)
5476 EXPORT_SYMBOL(wait_for_completion_killable);
5479 * try_wait_for_completion - try to decrement a completion without blocking
5480 * @x: completion structure
5482 * Returns: 0 if a decrement cannot be done without blocking
5483 * 1 if a decrement succeeded.
5485 * If a completion is being used as a counting completion,
5486 * attempt to decrement the counter without blocking. This
5487 * enables us to avoid waiting if the resource the completion
5488 * is protecting is not available.
5490 bool try_wait_for_completion(struct completion *x)
5494 spin_lock_irq(&x->wait.lock);
5499 spin_unlock_irq(&x->wait.lock);
5502 EXPORT_SYMBOL(try_wait_for_completion);
5505 * completion_done - Test to see if a completion has any waiters
5506 * @x: completion structure
5508 * Returns: 0 if there are waiters (wait_for_completion() in progress)
5509 * 1 if there are no waiters.
5512 bool completion_done(struct completion *x)
5516 spin_lock_irq(&x->wait.lock);
5519 spin_unlock_irq(&x->wait.lock);
5522 EXPORT_SYMBOL(completion_done);
5525 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
5527 unsigned long flags;
5530 init_waitqueue_entry(&wait, current);
5532 __set_current_state(state);
5534 spin_lock_irqsave(&q->lock, flags);
5535 __add_wait_queue(q, &wait);
5536 spin_unlock(&q->lock);
5537 timeout = schedule_timeout(timeout);
5538 spin_lock_irq(&q->lock);
5539 __remove_wait_queue(q, &wait);
5540 spin_unlock_irqrestore(&q->lock, flags);
5545 void __sched interruptible_sleep_on(wait_queue_head_t *q)
5547 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5549 EXPORT_SYMBOL(interruptible_sleep_on);
5552 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
5554 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
5556 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
5558 void __sched sleep_on(wait_queue_head_t *q)
5560 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5562 EXPORT_SYMBOL(sleep_on);
5564 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
5566 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5568 EXPORT_SYMBOL(sleep_on_timeout);
5570 #ifdef CONFIG_RT_MUTEXES
5573 * rt_mutex_setprio - set the current priority of a task
5575 * @prio: prio value (kernel-internal form)
5577 * This function changes the 'effective' priority of a task. It does
5578 * not touch ->normal_prio like __setscheduler().
5580 * Used by the rt_mutex code to implement priority inheritance logic.
5582 void rt_mutex_setprio(struct task_struct *p, int prio)
5584 unsigned long flags;
5585 int oldprio, on_rq, running;
5587 const struct sched_class *prev_class = p->sched_class;
5589 BUG_ON(prio < 0 || prio > MAX_PRIO);
5591 rq = task_rq_lock(p, &flags);
5592 update_rq_clock(rq);
5595 on_rq = p->se.on_rq;
5596 running = task_current(rq, p);
5598 dequeue_task(rq, p, 0);
5600 p->sched_class->put_prev_task(rq, p);
5603 p->sched_class = &rt_sched_class;
5605 p->sched_class = &fair_sched_class;
5610 p->sched_class->set_curr_task(rq);
5612 enqueue_task(rq, p, 0);
5614 check_class_changed(rq, p, prev_class, oldprio, running);
5616 task_rq_unlock(rq, &flags);
5621 void set_user_nice(struct task_struct *p, long nice)
5623 int old_prio, delta, on_rq;
5624 unsigned long flags;
5627 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
5630 * We have to be careful, if called from sys_setpriority(),
5631 * the task might be in the middle of scheduling on another CPU.
5633 rq = task_rq_lock(p, &flags);
5634 update_rq_clock(rq);
5636 * The RT priorities are set via sched_setscheduler(), but we still
5637 * allow the 'normal' nice value to be set - but as expected
5638 * it wont have any effect on scheduling until the task is
5639 * SCHED_FIFO/SCHED_RR:
5641 if (task_has_rt_policy(p)) {
5642 p->static_prio = NICE_TO_PRIO(nice);
5645 on_rq = p->se.on_rq;
5647 dequeue_task(rq, p, 0);
5649 p->static_prio = NICE_TO_PRIO(nice);
5652 p->prio = effective_prio(p);
5653 delta = p->prio - old_prio;
5656 enqueue_task(rq, p, 0);
5658 * If the task increased its priority or is running and
5659 * lowered its priority, then reschedule its CPU:
5661 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5662 resched_task(rq->curr);
5665 task_rq_unlock(rq, &flags);
5667 EXPORT_SYMBOL(set_user_nice);
5670 * can_nice - check if a task can reduce its nice value
5674 int can_nice(const struct task_struct *p, const int nice)
5676 /* convert nice value [19,-20] to rlimit style value [1,40] */
5677 int nice_rlim = 20 - nice;
5679 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5680 capable(CAP_SYS_NICE));
5683 #ifdef __ARCH_WANT_SYS_NICE
5686 * sys_nice - change the priority of the current process.
5687 * @increment: priority increment
5689 * sys_setpriority is a more generic, but much slower function that
5690 * does similar things.
5692 SYSCALL_DEFINE1(nice, int, increment)
5697 * Setpriority might change our priority at the same moment.
5698 * We don't have to worry. Conceptually one call occurs first
5699 * and we have a single winner.
5701 if (increment < -40)
5706 nice = TASK_NICE(current) + increment;
5712 if (increment < 0 && !can_nice(current, nice))
5715 retval = security_task_setnice(current, nice);
5719 set_user_nice(current, nice);
5726 * task_prio - return the priority value of a given task.
5727 * @p: the task in question.
5729 * This is the priority value as seen by users in /proc.
5730 * RT tasks are offset by -200. Normal tasks are centered
5731 * around 0, value goes from -16 to +15.
5733 int task_prio(const struct task_struct *p)
5735 return p->prio - MAX_RT_PRIO;
5739 * task_nice - return the nice value of a given task.
5740 * @p: the task in question.
5742 int task_nice(const struct task_struct *p)
5744 return TASK_NICE(p);
5746 EXPORT_SYMBOL(task_nice);
5749 * idle_cpu - is a given cpu idle currently?
5750 * @cpu: the processor in question.
5752 int idle_cpu(int cpu)
5754 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5758 * idle_task - return the idle task for a given cpu.
5759 * @cpu: the processor in question.
5761 struct task_struct *idle_task(int cpu)
5763 return cpu_rq(cpu)->idle;
5767 * find_process_by_pid - find a process with a matching PID value.
5768 * @pid: the pid in question.
5770 static struct task_struct *find_process_by_pid(pid_t pid)
5772 return pid ? find_task_by_vpid(pid) : current;
5775 /* Actually do priority change: must hold rq lock. */
5777 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5779 BUG_ON(p->se.on_rq);
5782 switch (p->policy) {
5786 p->sched_class = &fair_sched_class;
5790 p->sched_class = &rt_sched_class;
5794 p->rt_priority = prio;
5795 p->normal_prio = normal_prio(p);
5796 /* we are holding p->pi_lock already */
5797 p->prio = rt_mutex_getprio(p);
5802 * check the target process has a UID that matches the current process's
5804 static bool check_same_owner(struct task_struct *p)
5806 const struct cred *cred = current_cred(), *pcred;
5810 pcred = __task_cred(p);
5811 match = (cred->euid == pcred->euid ||
5812 cred->euid == pcred->uid);
5817 static int __sched_setscheduler(struct task_struct *p, int policy,
5818 struct sched_param *param, bool user)
5820 int retval, oldprio, oldpolicy = -1, on_rq, running;
5821 unsigned long flags;
5822 const struct sched_class *prev_class = p->sched_class;
5825 /* may grab non-irq protected spin_locks */
5826 BUG_ON(in_interrupt());
5828 /* double check policy once rq lock held */
5830 policy = oldpolicy = p->policy;
5831 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5832 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5833 policy != SCHED_IDLE)
5836 * Valid priorities for SCHED_FIFO and SCHED_RR are
5837 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5838 * SCHED_BATCH and SCHED_IDLE is 0.
5840 if (param->sched_priority < 0 ||
5841 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5842 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5844 if (rt_policy(policy) != (param->sched_priority != 0))
5848 * Allow unprivileged RT tasks to decrease priority:
5850 if (user && !capable(CAP_SYS_NICE)) {
5851 if (rt_policy(policy)) {
5852 unsigned long rlim_rtprio;
5854 if (!lock_task_sighand(p, &flags))
5856 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5857 unlock_task_sighand(p, &flags);
5859 /* can't set/change the rt policy */
5860 if (policy != p->policy && !rlim_rtprio)
5863 /* can't increase priority */
5864 if (param->sched_priority > p->rt_priority &&
5865 param->sched_priority > rlim_rtprio)
5869 * Like positive nice levels, dont allow tasks to
5870 * move out of SCHED_IDLE either:
5872 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5875 /* can't change other user's priorities */
5876 if (!check_same_owner(p))
5881 #ifdef CONFIG_RT_GROUP_SCHED
5883 * Do not allow realtime tasks into groups that have no runtime
5886 if (rt_bandwidth_enabled() && rt_policy(policy) &&
5887 task_group(p)->rt_bandwidth.rt_runtime == 0)
5891 retval = security_task_setscheduler(p, policy, param);
5897 * make sure no PI-waiters arrive (or leave) while we are
5898 * changing the priority of the task:
5900 spin_lock_irqsave(&p->pi_lock, flags);
5902 * To be able to change p->policy safely, the apropriate
5903 * runqueue lock must be held.
5905 rq = __task_rq_lock(p);
5906 /* recheck policy now with rq lock held */
5907 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5908 policy = oldpolicy = -1;
5909 __task_rq_unlock(rq);
5910 spin_unlock_irqrestore(&p->pi_lock, flags);
5913 update_rq_clock(rq);
5914 on_rq = p->se.on_rq;
5915 running = task_current(rq, p);
5917 deactivate_task(rq, p, 0);
5919 p->sched_class->put_prev_task(rq, p);
5922 __setscheduler(rq, p, policy, param->sched_priority);
5925 p->sched_class->set_curr_task(rq);
5927 activate_task(rq, p, 0);
5929 check_class_changed(rq, p, prev_class, oldprio, running);
5931 __task_rq_unlock(rq);
5932 spin_unlock_irqrestore(&p->pi_lock, flags);
5934 rt_mutex_adjust_pi(p);
5940 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5941 * @p: the task in question.
5942 * @policy: new policy.
5943 * @param: structure containing the new RT priority.
5945 * NOTE that the task may be already dead.
5947 int sched_setscheduler(struct task_struct *p, int policy,
5948 struct sched_param *param)
5950 return __sched_setscheduler(p, policy, param, true);
5952 EXPORT_SYMBOL_GPL(sched_setscheduler);
5955 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5956 * @p: the task in question.
5957 * @policy: new policy.
5958 * @param: structure containing the new RT priority.
5960 * Just like sched_setscheduler, only don't bother checking if the
5961 * current context has permission. For example, this is needed in
5962 * stop_machine(): we create temporary high priority worker threads,
5963 * but our caller might not have that capability.
5965 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5966 struct sched_param *param)
5968 return __sched_setscheduler(p, policy, param, false);
5972 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5974 struct sched_param lparam;
5975 struct task_struct *p;
5978 if (!param || pid < 0)
5980 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5985 p = find_process_by_pid(pid);
5987 retval = sched_setscheduler(p, policy, &lparam);
5994 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5995 * @pid: the pid in question.
5996 * @policy: new policy.
5997 * @param: structure containing the new RT priority.
5999 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
6000 struct sched_param __user *, param)
6002 /* negative values for policy are not valid */
6006 return do_sched_setscheduler(pid, policy, param);
6010 * sys_sched_setparam - set/change the RT priority of a thread
6011 * @pid: the pid in question.
6012 * @param: structure containing the new RT priority.
6014 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
6016 return do_sched_setscheduler(pid, -1, param);
6020 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
6021 * @pid: the pid in question.
6023 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
6025 struct task_struct *p;
6032 read_lock(&tasklist_lock);
6033 p = find_process_by_pid(pid);
6035 retval = security_task_getscheduler(p);
6039 read_unlock(&tasklist_lock);
6044 * sys_sched_getscheduler - get the RT priority of a thread
6045 * @pid: the pid in question.
6046 * @param: structure containing the RT priority.
6048 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
6050 struct sched_param lp;
6051 struct task_struct *p;
6054 if (!param || pid < 0)
6057 read_lock(&tasklist_lock);
6058 p = find_process_by_pid(pid);
6063 retval = security_task_getscheduler(p);
6067 lp.sched_priority = p->rt_priority;
6068 read_unlock(&tasklist_lock);
6071 * This one might sleep, we cannot do it with a spinlock held ...
6073 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
6078 read_unlock(&tasklist_lock);
6082 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
6084 cpumask_var_t cpus_allowed, new_mask;
6085 struct task_struct *p;
6089 read_lock(&tasklist_lock);
6091 p = find_process_by_pid(pid);
6093 read_unlock(&tasklist_lock);
6099 * It is not safe to call set_cpus_allowed with the
6100 * tasklist_lock held. We will bump the task_struct's
6101 * usage count and then drop tasklist_lock.
6104 read_unlock(&tasklist_lock);
6106 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
6110 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
6112 goto out_free_cpus_allowed;
6115 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
6118 retval = security_task_setscheduler(p, 0, NULL);
6122 cpuset_cpus_allowed(p, cpus_allowed);
6123 cpumask_and(new_mask, in_mask, cpus_allowed);
6125 retval = set_cpus_allowed_ptr(p, new_mask);
6128 cpuset_cpus_allowed(p, cpus_allowed);
6129 if (!cpumask_subset(new_mask, cpus_allowed)) {
6131 * We must have raced with a concurrent cpuset
6132 * update. Just reset the cpus_allowed to the
6133 * cpuset's cpus_allowed
6135 cpumask_copy(new_mask, cpus_allowed);
6140 free_cpumask_var(new_mask);
6141 out_free_cpus_allowed:
6142 free_cpumask_var(cpus_allowed);
6149 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
6150 struct cpumask *new_mask)
6152 if (len < cpumask_size())
6153 cpumask_clear(new_mask);
6154 else if (len > cpumask_size())
6155 len = cpumask_size();
6157 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6161 * sys_sched_setaffinity - set the cpu affinity of a process
6162 * @pid: pid of the process
6163 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6164 * @user_mask_ptr: user-space pointer to the new cpu mask
6166 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6167 unsigned long __user *, user_mask_ptr)
6169 cpumask_var_t new_mask;
6172 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6175 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6177 retval = sched_setaffinity(pid, new_mask);
6178 free_cpumask_var(new_mask);
6182 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6184 struct task_struct *p;
6188 read_lock(&tasklist_lock);
6191 p = find_process_by_pid(pid);
6195 retval = security_task_getscheduler(p);
6199 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
6202 read_unlock(&tasklist_lock);
6209 * sys_sched_getaffinity - get the cpu affinity of a process
6210 * @pid: pid of the process
6211 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6212 * @user_mask_ptr: user-space pointer to hold the current cpu mask
6214 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6215 unsigned long __user *, user_mask_ptr)
6220 if (len < cpumask_size())
6223 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
6226 ret = sched_getaffinity(pid, mask);
6228 if (copy_to_user(user_mask_ptr, mask, cpumask_size()))
6231 ret = cpumask_size();
6233 free_cpumask_var(mask);
6239 * sys_sched_yield - yield the current processor to other threads.
6241 * This function yields the current CPU to other tasks. If there are no
6242 * other threads running on this CPU then this function will return.
6244 SYSCALL_DEFINE0(sched_yield)
6246 struct rq *rq = this_rq_lock();
6248 schedstat_inc(rq, yld_count);
6249 current->sched_class->yield_task(rq);
6252 * Since we are going to call schedule() anyway, there's
6253 * no need to preempt or enable interrupts:
6255 __release(rq->lock);
6256 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
6257 _raw_spin_unlock(&rq->lock);
6258 preempt_enable_no_resched();
6265 static void __cond_resched(void)
6267 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6268 __might_sleep(__FILE__, __LINE__);
6271 * The BKS might be reacquired before we have dropped
6272 * PREEMPT_ACTIVE, which could trigger a second
6273 * cond_resched() call.
6276 add_preempt_count(PREEMPT_ACTIVE);
6278 sub_preempt_count(PREEMPT_ACTIVE);
6279 } while (need_resched());
6282 int __sched _cond_resched(void)
6284 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
6285 system_state == SYSTEM_RUNNING) {
6291 EXPORT_SYMBOL(_cond_resched);
6294 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
6295 * call schedule, and on return reacquire the lock.
6297 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
6298 * operations here to prevent schedule() from being called twice (once via
6299 * spin_unlock(), once by hand).
6301 int cond_resched_lock(spinlock_t *lock)
6303 int resched = need_resched() && system_state == SYSTEM_RUNNING;
6306 if (spin_needbreak(lock) || resched) {
6308 if (resched && need_resched())
6317 EXPORT_SYMBOL(cond_resched_lock);
6319 int __sched cond_resched_softirq(void)
6321 BUG_ON(!in_softirq());
6323 if (need_resched() && system_state == SYSTEM_RUNNING) {
6331 EXPORT_SYMBOL(cond_resched_softirq);
6334 * yield - yield the current processor to other threads.
6336 * This is a shortcut for kernel-space yielding - it marks the
6337 * thread runnable and calls sys_sched_yield().
6339 void __sched yield(void)
6341 set_current_state(TASK_RUNNING);
6344 EXPORT_SYMBOL(yield);
6347 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6348 * that process accounting knows that this is a task in IO wait state.
6350 * But don't do that if it is a deliberate, throttling IO wait (this task
6351 * has set its backing_dev_info: the queue against which it should throttle)
6353 void __sched io_schedule(void)
6355 struct rq *rq = &__raw_get_cpu_var(runqueues);
6357 delayacct_blkio_start();
6358 atomic_inc(&rq->nr_iowait);
6360 atomic_dec(&rq->nr_iowait);
6361 delayacct_blkio_end();
6363 EXPORT_SYMBOL(io_schedule);
6365 long __sched io_schedule_timeout(long timeout)
6367 struct rq *rq = &__raw_get_cpu_var(runqueues);
6370 delayacct_blkio_start();
6371 atomic_inc(&rq->nr_iowait);
6372 ret = schedule_timeout(timeout);
6373 atomic_dec(&rq->nr_iowait);
6374 delayacct_blkio_end();
6379 * sys_sched_get_priority_max - return maximum RT priority.
6380 * @policy: scheduling class.
6382 * this syscall returns the maximum rt_priority that can be used
6383 * by a given scheduling class.
6385 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6392 ret = MAX_USER_RT_PRIO-1;
6404 * sys_sched_get_priority_min - return minimum RT priority.
6405 * @policy: scheduling class.
6407 * this syscall returns the minimum rt_priority that can be used
6408 * by a given scheduling class.
6410 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6428 * sys_sched_rr_get_interval - return the default timeslice of a process.
6429 * @pid: pid of the process.
6430 * @interval: userspace pointer to the timeslice value.
6432 * this syscall writes the default timeslice value of a given process
6433 * into the user-space timespec buffer. A value of '0' means infinity.
6435 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
6436 struct timespec __user *, interval)
6438 struct task_struct *p;
6439 unsigned int time_slice;
6447 read_lock(&tasklist_lock);
6448 p = find_process_by_pid(pid);
6452 retval = security_task_getscheduler(p);
6457 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
6458 * tasks that are on an otherwise idle runqueue:
6461 if (p->policy == SCHED_RR) {
6462 time_slice = DEF_TIMESLICE;
6463 } else if (p->policy != SCHED_FIFO) {
6464 struct sched_entity *se = &p->se;
6465 unsigned long flags;
6468 rq = task_rq_lock(p, &flags);
6469 if (rq->cfs.load.weight)
6470 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
6471 task_rq_unlock(rq, &flags);
6473 read_unlock(&tasklist_lock);
6474 jiffies_to_timespec(time_slice, &t);
6475 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
6479 read_unlock(&tasklist_lock);
6483 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
6485 void sched_show_task(struct task_struct *p)
6487 unsigned long free = 0;
6490 state = p->state ? __ffs(p->state) + 1 : 0;
6491 printk(KERN_INFO "%-13.13s %c", p->comm,
6492 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
6493 #if BITS_PER_LONG == 32
6494 if (state == TASK_RUNNING)
6495 printk(KERN_CONT " running ");
6497 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
6499 if (state == TASK_RUNNING)
6500 printk(KERN_CONT " running task ");
6502 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
6504 #ifdef CONFIG_DEBUG_STACK_USAGE
6505 free = stack_not_used(p);
6507 printk(KERN_CONT "%5lu %5d %6d\n", free,
6508 task_pid_nr(p), task_pid_nr(p->real_parent));
6510 show_stack(p, NULL);
6513 void show_state_filter(unsigned long state_filter)
6515 struct task_struct *g, *p;
6517 #if BITS_PER_LONG == 32
6519 " task PC stack pid father\n");
6522 " task PC stack pid father\n");
6524 read_lock(&tasklist_lock);
6525 do_each_thread(g, p) {
6527 * reset the NMI-timeout, listing all files on a slow
6528 * console might take alot of time:
6530 touch_nmi_watchdog();
6531 if (!state_filter || (p->state & state_filter))
6533 } while_each_thread(g, p);
6535 touch_all_softlockup_watchdogs();
6537 #ifdef CONFIG_SCHED_DEBUG
6538 sysrq_sched_debug_show();
6540 read_unlock(&tasklist_lock);
6542 * Only show locks if all tasks are dumped:
6544 if (state_filter == -1)
6545 debug_show_all_locks();
6548 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
6550 idle->sched_class = &idle_sched_class;
6554 * init_idle - set up an idle thread for a given CPU
6555 * @idle: task in question
6556 * @cpu: cpu the idle task belongs to
6558 * NOTE: this function does not set the idle thread's NEED_RESCHED
6559 * flag, to make booting more robust.
6561 void __cpuinit init_idle(struct task_struct *idle, int cpu)
6563 struct rq *rq = cpu_rq(cpu);
6564 unsigned long flags;
6566 spin_lock_irqsave(&rq->lock, flags);
6569 idle->se.exec_start = sched_clock();
6571 idle->prio = idle->normal_prio = MAX_PRIO;
6572 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
6573 __set_task_cpu(idle, cpu);
6575 rq->curr = rq->idle = idle;
6576 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
6579 spin_unlock_irqrestore(&rq->lock, flags);
6581 /* Set the preempt count _outside_ the spinlocks! */
6582 #if defined(CONFIG_PREEMPT)
6583 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
6585 task_thread_info(idle)->preempt_count = 0;
6588 * The idle tasks have their own, simple scheduling class:
6590 idle->sched_class = &idle_sched_class;
6591 ftrace_graph_init_task(idle);
6595 * In a system that switches off the HZ timer nohz_cpu_mask
6596 * indicates which cpus entered this state. This is used
6597 * in the rcu update to wait only for active cpus. For system
6598 * which do not switch off the HZ timer nohz_cpu_mask should
6599 * always be CPU_BITS_NONE.
6601 cpumask_var_t nohz_cpu_mask;
6604 * Increase the granularity value when there are more CPUs,
6605 * because with more CPUs the 'effective latency' as visible
6606 * to users decreases. But the relationship is not linear,
6607 * so pick a second-best guess by going with the log2 of the
6610 * This idea comes from the SD scheduler of Con Kolivas:
6612 static inline void sched_init_granularity(void)
6614 unsigned int factor = 1 + ilog2(num_online_cpus());
6615 const unsigned long limit = 200000000;
6617 sysctl_sched_min_granularity *= factor;
6618 if (sysctl_sched_min_granularity > limit)
6619 sysctl_sched_min_granularity = limit;
6621 sysctl_sched_latency *= factor;
6622 if (sysctl_sched_latency > limit)
6623 sysctl_sched_latency = limit;
6625 sysctl_sched_wakeup_granularity *= factor;
6627 sysctl_sched_shares_ratelimit *= factor;
6632 * This is how migration works:
6634 * 1) we queue a struct migration_req structure in the source CPU's
6635 * runqueue and wake up that CPU's migration thread.
6636 * 2) we down() the locked semaphore => thread blocks.
6637 * 3) migration thread wakes up (implicitly it forces the migrated
6638 * thread off the CPU)
6639 * 4) it gets the migration request and checks whether the migrated
6640 * task is still in the wrong runqueue.
6641 * 5) if it's in the wrong runqueue then the migration thread removes
6642 * it and puts it into the right queue.
6643 * 6) migration thread up()s the semaphore.
6644 * 7) we wake up and the migration is done.
6648 * Change a given task's CPU affinity. Migrate the thread to a
6649 * proper CPU and schedule it away if the CPU it's executing on
6650 * is removed from the allowed bitmask.
6652 * NOTE: the caller must have a valid reference to the task, the
6653 * task must not exit() & deallocate itself prematurely. The
6654 * call is not atomic; no spinlocks may be held.
6656 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
6658 struct migration_req req;
6659 unsigned long flags;
6663 rq = task_rq_lock(p, &flags);
6664 if (!cpumask_intersects(new_mask, cpu_online_mask)) {
6669 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
6670 !cpumask_equal(&p->cpus_allowed, new_mask))) {
6675 if (p->sched_class->set_cpus_allowed)
6676 p->sched_class->set_cpus_allowed(p, new_mask);
6678 cpumask_copy(&p->cpus_allowed, new_mask);
6679 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
6682 /* Can the task run on the task's current CPU? If so, we're done */
6683 if (cpumask_test_cpu(task_cpu(p), new_mask))
6686 if (migrate_task(p, cpumask_any_and(cpu_online_mask, new_mask), &req)) {
6687 /* Need help from migration thread: drop lock and wait. */
6688 task_rq_unlock(rq, &flags);
6689 wake_up_process(rq->migration_thread);
6690 wait_for_completion(&req.done);
6691 tlb_migrate_finish(p->mm);
6695 task_rq_unlock(rq, &flags);
6699 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6702 * Move (not current) task off this cpu, onto dest cpu. We're doing
6703 * this because either it can't run here any more (set_cpus_allowed()
6704 * away from this CPU, or CPU going down), or because we're
6705 * attempting to rebalance this task on exec (sched_exec).
6707 * So we race with normal scheduler movements, but that's OK, as long
6708 * as the task is no longer on this CPU.
6710 * Returns non-zero if task was successfully migrated.
6712 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6714 struct rq *rq_dest, *rq_src;
6717 if (unlikely(!cpu_active(dest_cpu)))
6720 rq_src = cpu_rq(src_cpu);
6721 rq_dest = cpu_rq(dest_cpu);
6723 double_rq_lock(rq_src, rq_dest);
6724 /* Already moved. */
6725 if (task_cpu(p) != src_cpu)
6727 /* Affinity changed (again). */
6728 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6731 on_rq = p->se.on_rq;
6733 deactivate_task(rq_src, p, 0);
6735 set_task_cpu(p, dest_cpu);
6737 activate_task(rq_dest, p, 0);
6738 check_preempt_curr(rq_dest, p, 0);
6743 double_rq_unlock(rq_src, rq_dest);
6748 * migration_thread - this is a highprio system thread that performs
6749 * thread migration by bumping thread off CPU then 'pushing' onto
6752 static int migration_thread(void *data)
6754 int cpu = (long)data;
6758 BUG_ON(rq->migration_thread != current);
6760 set_current_state(TASK_INTERRUPTIBLE);
6761 while (!kthread_should_stop()) {
6762 struct migration_req *req;
6763 struct list_head *head;
6765 spin_lock_irq(&rq->lock);
6767 if (cpu_is_offline(cpu)) {
6768 spin_unlock_irq(&rq->lock);
6772 if (rq->active_balance) {
6773 active_load_balance(rq, cpu);
6774 rq->active_balance = 0;
6777 head = &rq->migration_queue;
6779 if (list_empty(head)) {
6780 spin_unlock_irq(&rq->lock);
6782 set_current_state(TASK_INTERRUPTIBLE);
6785 req = list_entry(head->next, struct migration_req, list);
6786 list_del_init(head->next);
6788 spin_unlock(&rq->lock);
6789 __migrate_task(req->task, cpu, req->dest_cpu);
6792 complete(&req->done);
6794 __set_current_state(TASK_RUNNING);
6798 /* Wait for kthread_stop */
6799 set_current_state(TASK_INTERRUPTIBLE);
6800 while (!kthread_should_stop()) {
6802 set_current_state(TASK_INTERRUPTIBLE);
6804 __set_current_state(TASK_RUNNING);
6808 #ifdef CONFIG_HOTPLUG_CPU
6810 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6814 local_irq_disable();
6815 ret = __migrate_task(p, src_cpu, dest_cpu);
6821 * Figure out where task on dead CPU should go, use force if necessary.
6823 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6826 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(dead_cpu));
6829 /* Look for allowed, online CPU in same node. */
6830 for_each_cpu_and(dest_cpu, nodemask, cpu_online_mask)
6831 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6834 /* Any allowed, online CPU? */
6835 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_online_mask);
6836 if (dest_cpu < nr_cpu_ids)
6839 /* No more Mr. Nice Guy. */
6840 if (dest_cpu >= nr_cpu_ids) {
6841 cpuset_cpus_allowed_locked(p, &p->cpus_allowed);
6842 dest_cpu = cpumask_any_and(cpu_online_mask, &p->cpus_allowed);
6845 * Don't tell them about moving exiting tasks or
6846 * kernel threads (both mm NULL), since they never
6849 if (p->mm && printk_ratelimit()) {
6850 printk(KERN_INFO "process %d (%s) no "
6851 "longer affine to cpu%d\n",
6852 task_pid_nr(p), p->comm, dead_cpu);
6857 /* It can have affinity changed while we were choosing. */
6858 if (unlikely(!__migrate_task_irq(p, dead_cpu, dest_cpu)))
6863 * While a dead CPU has no uninterruptible tasks queued at this point,
6864 * it might still have a nonzero ->nr_uninterruptible counter, because
6865 * for performance reasons the counter is not stricly tracking tasks to
6866 * their home CPUs. So we just add the counter to another CPU's counter,
6867 * to keep the global sum constant after CPU-down:
6869 static void migrate_nr_uninterruptible(struct rq *rq_src)
6871 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_online_mask));
6872 unsigned long flags;
6874 local_irq_save(flags);
6875 double_rq_lock(rq_src, rq_dest);
6876 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6877 rq_src->nr_uninterruptible = 0;
6878 double_rq_unlock(rq_src, rq_dest);
6879 local_irq_restore(flags);
6882 /* Run through task list and migrate tasks from the dead cpu. */
6883 static void migrate_live_tasks(int src_cpu)
6885 struct task_struct *p, *t;
6887 read_lock(&tasklist_lock);
6889 do_each_thread(t, p) {
6893 if (task_cpu(p) == src_cpu)
6894 move_task_off_dead_cpu(src_cpu, p);
6895 } while_each_thread(t, p);
6897 read_unlock(&tasklist_lock);
6901 * Schedules idle task to be the next runnable task on current CPU.
6902 * It does so by boosting its priority to highest possible.
6903 * Used by CPU offline code.
6905 void sched_idle_next(void)
6907 int this_cpu = smp_processor_id();
6908 struct rq *rq = cpu_rq(this_cpu);
6909 struct task_struct *p = rq->idle;
6910 unsigned long flags;
6912 /* cpu has to be offline */
6913 BUG_ON(cpu_online(this_cpu));
6916 * Strictly not necessary since rest of the CPUs are stopped by now
6917 * and interrupts disabled on the current cpu.
6919 spin_lock_irqsave(&rq->lock, flags);
6921 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6923 update_rq_clock(rq);
6924 activate_task(rq, p, 0);
6926 spin_unlock_irqrestore(&rq->lock, flags);
6930 * Ensures that the idle task is using init_mm right before its cpu goes
6933 void idle_task_exit(void)
6935 struct mm_struct *mm = current->active_mm;
6937 BUG_ON(cpu_online(smp_processor_id()));
6940 switch_mm(mm, &init_mm, current);
6944 /* called under rq->lock with disabled interrupts */
6945 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6947 struct rq *rq = cpu_rq(dead_cpu);
6949 /* Must be exiting, otherwise would be on tasklist. */
6950 BUG_ON(!p->exit_state);
6952 /* Cannot have done final schedule yet: would have vanished. */
6953 BUG_ON(p->state == TASK_DEAD);
6958 * Drop lock around migration; if someone else moves it,
6959 * that's OK. No task can be added to this CPU, so iteration is
6962 spin_unlock_irq(&rq->lock);
6963 move_task_off_dead_cpu(dead_cpu, p);
6964 spin_lock_irq(&rq->lock);
6969 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6970 static void migrate_dead_tasks(unsigned int dead_cpu)
6972 struct rq *rq = cpu_rq(dead_cpu);
6973 struct task_struct *next;
6976 if (!rq->nr_running)
6978 update_rq_clock(rq);
6979 next = pick_next_task(rq);
6982 next->sched_class->put_prev_task(rq, next);
6983 migrate_dead(dead_cpu, next);
6987 #endif /* CONFIG_HOTPLUG_CPU */
6989 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6991 static struct ctl_table sd_ctl_dir[] = {
6993 .procname = "sched_domain",
6999 static struct ctl_table sd_ctl_root[] = {
7001 .ctl_name = CTL_KERN,
7002 .procname = "kernel",
7004 .child = sd_ctl_dir,
7009 static struct ctl_table *sd_alloc_ctl_entry(int n)
7011 struct ctl_table *entry =
7012 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
7017 static void sd_free_ctl_entry(struct ctl_table **tablep)
7019 struct ctl_table *entry;
7022 * In the intermediate directories, both the child directory and
7023 * procname are dynamically allocated and could fail but the mode
7024 * will always be set. In the lowest directory the names are
7025 * static strings and all have proc handlers.
7027 for (entry = *tablep; entry->mode; entry++) {
7029 sd_free_ctl_entry(&entry->child);
7030 if (entry->proc_handler == NULL)
7031 kfree(entry->procname);
7039 set_table_entry(struct ctl_table *entry,
7040 const char *procname, void *data, int maxlen,
7041 mode_t mode, proc_handler *proc_handler)
7043 entry->procname = procname;
7045 entry->maxlen = maxlen;
7047 entry->proc_handler = proc_handler;
7050 static struct ctl_table *
7051 sd_alloc_ctl_domain_table(struct sched_domain *sd)
7053 struct ctl_table *table = sd_alloc_ctl_entry(13);
7058 set_table_entry(&table[0], "min_interval", &sd->min_interval,
7059 sizeof(long), 0644, proc_doulongvec_minmax);
7060 set_table_entry(&table[1], "max_interval", &sd->max_interval,
7061 sizeof(long), 0644, proc_doulongvec_minmax);
7062 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
7063 sizeof(int), 0644, proc_dointvec_minmax);
7064 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
7065 sizeof(int), 0644, proc_dointvec_minmax);
7066 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
7067 sizeof(int), 0644, proc_dointvec_minmax);
7068 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
7069 sizeof(int), 0644, proc_dointvec_minmax);
7070 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
7071 sizeof(int), 0644, proc_dointvec_minmax);
7072 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
7073 sizeof(int), 0644, proc_dointvec_minmax);
7074 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
7075 sizeof(int), 0644, proc_dointvec_minmax);
7076 set_table_entry(&table[9], "cache_nice_tries",
7077 &sd->cache_nice_tries,
7078 sizeof(int), 0644, proc_dointvec_minmax);
7079 set_table_entry(&table[10], "flags", &sd->flags,
7080 sizeof(int), 0644, proc_dointvec_minmax);
7081 set_table_entry(&table[11], "name", sd->name,
7082 CORENAME_MAX_SIZE, 0444, proc_dostring);
7083 /* &table[12] is terminator */
7088 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
7090 struct ctl_table *entry, *table;
7091 struct sched_domain *sd;
7092 int domain_num = 0, i;
7095 for_each_domain(cpu, sd)
7097 entry = table = sd_alloc_ctl_entry(domain_num + 1);
7102 for_each_domain(cpu, sd) {
7103 snprintf(buf, 32, "domain%d", i);
7104 entry->procname = kstrdup(buf, GFP_KERNEL);
7106 entry->child = sd_alloc_ctl_domain_table(sd);
7113 static struct ctl_table_header *sd_sysctl_header;
7114 static void register_sched_domain_sysctl(void)
7116 int i, cpu_num = num_online_cpus();
7117 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
7120 WARN_ON(sd_ctl_dir[0].child);
7121 sd_ctl_dir[0].child = entry;
7126 for_each_online_cpu(i) {
7127 snprintf(buf, 32, "cpu%d", i);
7128 entry->procname = kstrdup(buf, GFP_KERNEL);
7130 entry->child = sd_alloc_ctl_cpu_table(i);
7134 WARN_ON(sd_sysctl_header);
7135 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
7138 /* may be called multiple times per register */
7139 static void unregister_sched_domain_sysctl(void)
7141 if (sd_sysctl_header)
7142 unregister_sysctl_table(sd_sysctl_header);
7143 sd_sysctl_header = NULL;
7144 if (sd_ctl_dir[0].child)
7145 sd_free_ctl_entry(&sd_ctl_dir[0].child);
7148 static void register_sched_domain_sysctl(void)
7151 static void unregister_sched_domain_sysctl(void)
7156 static void set_rq_online(struct rq *rq)
7159 const struct sched_class *class;
7161 cpumask_set_cpu(rq->cpu, rq->rd->online);
7164 for_each_class(class) {
7165 if (class->rq_online)
7166 class->rq_online(rq);
7171 static void set_rq_offline(struct rq *rq)
7174 const struct sched_class *class;
7176 for_each_class(class) {
7177 if (class->rq_offline)
7178 class->rq_offline(rq);
7181 cpumask_clear_cpu(rq->cpu, rq->rd->online);
7187 * migration_call - callback that gets triggered when a CPU is added.
7188 * Here we can start up the necessary migration thread for the new CPU.
7190 static int __cpuinit
7191 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
7193 struct task_struct *p;
7194 int cpu = (long)hcpu;
7195 unsigned long flags;
7200 case CPU_UP_PREPARE:
7201 case CPU_UP_PREPARE_FROZEN:
7202 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
7205 kthread_bind(p, cpu);
7206 /* Must be high prio: stop_machine expects to yield to it. */
7207 rq = task_rq_lock(p, &flags);
7208 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7209 task_rq_unlock(rq, &flags);
7210 cpu_rq(cpu)->migration_thread = p;
7214 case CPU_ONLINE_FROZEN:
7215 /* Strictly unnecessary, as first user will wake it. */
7216 wake_up_process(cpu_rq(cpu)->migration_thread);
7218 /* Update our root-domain */
7220 spin_lock_irqsave(&rq->lock, flags);
7222 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7226 spin_unlock_irqrestore(&rq->lock, flags);
7229 #ifdef CONFIG_HOTPLUG_CPU
7230 case CPU_UP_CANCELED:
7231 case CPU_UP_CANCELED_FROZEN:
7232 if (!cpu_rq(cpu)->migration_thread)
7234 /* Unbind it from offline cpu so it can run. Fall thru. */
7235 kthread_bind(cpu_rq(cpu)->migration_thread,
7236 cpumask_any(cpu_online_mask));
7237 kthread_stop(cpu_rq(cpu)->migration_thread);
7238 cpu_rq(cpu)->migration_thread = NULL;
7242 case CPU_DEAD_FROZEN:
7243 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
7244 migrate_live_tasks(cpu);
7246 kthread_stop(rq->migration_thread);
7247 rq->migration_thread = NULL;
7248 /* Idle task back to normal (off runqueue, low prio) */
7249 spin_lock_irq(&rq->lock);
7250 update_rq_clock(rq);
7251 deactivate_task(rq, rq->idle, 0);
7252 rq->idle->static_prio = MAX_PRIO;
7253 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
7254 rq->idle->sched_class = &idle_sched_class;
7255 migrate_dead_tasks(cpu);
7256 spin_unlock_irq(&rq->lock);
7258 migrate_nr_uninterruptible(rq);
7259 BUG_ON(rq->nr_running != 0);
7262 * No need to migrate the tasks: it was best-effort if
7263 * they didn't take sched_hotcpu_mutex. Just wake up
7266 spin_lock_irq(&rq->lock);
7267 while (!list_empty(&rq->migration_queue)) {
7268 struct migration_req *req;
7270 req = list_entry(rq->migration_queue.next,
7271 struct migration_req, list);
7272 list_del_init(&req->list);
7273 spin_unlock_irq(&rq->lock);
7274 complete(&req->done);
7275 spin_lock_irq(&rq->lock);
7277 spin_unlock_irq(&rq->lock);
7281 case CPU_DYING_FROZEN:
7282 /* Update our root-domain */
7284 spin_lock_irqsave(&rq->lock, flags);
7286 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7289 spin_unlock_irqrestore(&rq->lock, flags);
7296 /* Register at highest priority so that task migration (migrate_all_tasks)
7297 * happens before everything else.
7299 static struct notifier_block __cpuinitdata migration_notifier = {
7300 .notifier_call = migration_call,
7304 static int __init migration_init(void)
7306 void *cpu = (void *)(long)smp_processor_id();
7309 /* Start one for the boot CPU: */
7310 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
7311 BUG_ON(err == NOTIFY_BAD);
7312 migration_call(&migration_notifier, CPU_ONLINE, cpu);
7313 register_cpu_notifier(&migration_notifier);
7317 early_initcall(migration_init);
7322 #ifdef CONFIG_SCHED_DEBUG
7324 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
7325 struct cpumask *groupmask)
7327 struct sched_group *group = sd->groups;
7330 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
7331 cpumask_clear(groupmask);
7333 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
7335 if (!(sd->flags & SD_LOAD_BALANCE)) {
7336 printk("does not load-balance\n");
7338 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
7343 printk(KERN_CONT "span %s level %s\n", str, sd->name);
7345 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
7346 printk(KERN_ERR "ERROR: domain->span does not contain "
7349 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
7350 printk(KERN_ERR "ERROR: domain->groups does not contain"
7354 printk(KERN_DEBUG "%*s groups:", level + 1, "");
7358 printk(KERN_ERR "ERROR: group is NULL\n");
7362 if (!group->__cpu_power) {
7363 printk(KERN_CONT "\n");
7364 printk(KERN_ERR "ERROR: domain->cpu_power not "
7369 if (!cpumask_weight(sched_group_cpus(group))) {
7370 printk(KERN_CONT "\n");
7371 printk(KERN_ERR "ERROR: empty group\n");
7375 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
7376 printk(KERN_CONT "\n");
7377 printk(KERN_ERR "ERROR: repeated CPUs\n");
7381 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
7383 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
7384 printk(KERN_CONT " %s", str);
7386 group = group->next;
7387 } while (group != sd->groups);
7388 printk(KERN_CONT "\n");
7390 if (!cpumask_equal(sched_domain_span(sd), groupmask))
7391 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
7394 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
7395 printk(KERN_ERR "ERROR: parent span is not a superset "
7396 "of domain->span\n");
7400 static void sched_domain_debug(struct sched_domain *sd, int cpu)
7402 cpumask_var_t groupmask;
7406 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
7410 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
7412 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
7413 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
7418 if (sched_domain_debug_one(sd, cpu, level, groupmask))
7425 free_cpumask_var(groupmask);
7427 #else /* !CONFIG_SCHED_DEBUG */
7428 # define sched_domain_debug(sd, cpu) do { } while (0)
7429 #endif /* CONFIG_SCHED_DEBUG */
7431 static int sd_degenerate(struct sched_domain *sd)
7433 if (cpumask_weight(sched_domain_span(sd)) == 1)
7436 /* Following flags need at least 2 groups */
7437 if (sd->flags & (SD_LOAD_BALANCE |
7438 SD_BALANCE_NEWIDLE |
7442 SD_SHARE_PKG_RESOURCES)) {
7443 if (sd->groups != sd->groups->next)
7447 /* Following flags don't use groups */
7448 if (sd->flags & (SD_WAKE_IDLE |
7457 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
7459 unsigned long cflags = sd->flags, pflags = parent->flags;
7461 if (sd_degenerate(parent))
7464 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
7467 /* Does parent contain flags not in child? */
7468 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
7469 if (cflags & SD_WAKE_AFFINE)
7470 pflags &= ~SD_WAKE_BALANCE;
7471 /* Flags needing groups don't count if only 1 group in parent */
7472 if (parent->groups == parent->groups->next) {
7473 pflags &= ~(SD_LOAD_BALANCE |
7474 SD_BALANCE_NEWIDLE |
7478 SD_SHARE_PKG_RESOURCES);
7479 if (nr_node_ids == 1)
7480 pflags &= ~SD_SERIALIZE;
7482 if (~cflags & pflags)
7488 static void free_rootdomain(struct root_domain *rd)
7490 cpupri_cleanup(&rd->cpupri);
7492 free_cpumask_var(rd->rto_mask);
7493 free_cpumask_var(rd->online);
7494 free_cpumask_var(rd->span);
7498 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
7500 struct root_domain *old_rd = NULL;
7501 unsigned long flags;
7503 spin_lock_irqsave(&rq->lock, flags);
7508 if (cpumask_test_cpu(rq->cpu, old_rd->online))
7511 cpumask_clear_cpu(rq->cpu, old_rd->span);
7514 * If we dont want to free the old_rt yet then
7515 * set old_rd to NULL to skip the freeing later
7518 if (!atomic_dec_and_test(&old_rd->refcount))
7522 atomic_inc(&rd->refcount);
7525 cpumask_set_cpu(rq->cpu, rd->span);
7526 if (cpumask_test_cpu(rq->cpu, cpu_online_mask))
7529 spin_unlock_irqrestore(&rq->lock, flags);
7532 free_rootdomain(old_rd);
7535 static int __init_refok init_rootdomain(struct root_domain *rd, bool bootmem)
7537 memset(rd, 0, sizeof(*rd));
7540 alloc_bootmem_cpumask_var(&def_root_domain.span);
7541 alloc_bootmem_cpumask_var(&def_root_domain.online);
7542 alloc_bootmem_cpumask_var(&def_root_domain.rto_mask);
7543 cpupri_init(&rd->cpupri, true);
7547 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
7549 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
7551 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
7554 if (cpupri_init(&rd->cpupri, false) != 0)
7559 free_cpumask_var(rd->rto_mask);
7561 free_cpumask_var(rd->online);
7563 free_cpumask_var(rd->span);
7568 static void init_defrootdomain(void)
7570 init_rootdomain(&def_root_domain, true);
7572 atomic_set(&def_root_domain.refcount, 1);
7575 static struct root_domain *alloc_rootdomain(void)
7577 struct root_domain *rd;
7579 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
7583 if (init_rootdomain(rd, false) != 0) {
7592 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
7593 * hold the hotplug lock.
7596 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
7598 struct rq *rq = cpu_rq(cpu);
7599 struct sched_domain *tmp;
7601 /* Remove the sched domains which do not contribute to scheduling. */
7602 for (tmp = sd; tmp; ) {
7603 struct sched_domain *parent = tmp->parent;
7607 if (sd_parent_degenerate(tmp, parent)) {
7608 tmp->parent = parent->parent;
7610 parent->parent->child = tmp;
7615 if (sd && sd_degenerate(sd)) {
7621 sched_domain_debug(sd, cpu);
7623 rq_attach_root(rq, rd);
7624 rcu_assign_pointer(rq->sd, sd);
7627 /* cpus with isolated domains */
7628 static cpumask_var_t cpu_isolated_map;
7630 /* Setup the mask of cpus configured for isolated domains */
7631 static int __init isolated_cpu_setup(char *str)
7633 cpulist_parse(str, cpu_isolated_map);
7637 __setup("isolcpus=", isolated_cpu_setup);
7640 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
7641 * to a function which identifies what group(along with sched group) a CPU
7642 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
7643 * (due to the fact that we keep track of groups covered with a struct cpumask).
7645 * init_sched_build_groups will build a circular linked list of the groups
7646 * covered by the given span, and will set each group's ->cpumask correctly,
7647 * and ->cpu_power to 0.
7650 init_sched_build_groups(const struct cpumask *span,
7651 const struct cpumask *cpu_map,
7652 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
7653 struct sched_group **sg,
7654 struct cpumask *tmpmask),
7655 struct cpumask *covered, struct cpumask *tmpmask)
7657 struct sched_group *first = NULL, *last = NULL;
7660 cpumask_clear(covered);
7662 for_each_cpu(i, span) {
7663 struct sched_group *sg;
7664 int group = group_fn(i, cpu_map, &sg, tmpmask);
7667 if (cpumask_test_cpu(i, covered))
7670 cpumask_clear(sched_group_cpus(sg));
7671 sg->__cpu_power = 0;
7673 for_each_cpu(j, span) {
7674 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
7677 cpumask_set_cpu(j, covered);
7678 cpumask_set_cpu(j, sched_group_cpus(sg));
7689 #define SD_NODES_PER_DOMAIN 16
7694 * find_next_best_node - find the next node to include in a sched_domain
7695 * @node: node whose sched_domain we're building
7696 * @used_nodes: nodes already in the sched_domain
7698 * Find the next node to include in a given scheduling domain. Simply
7699 * finds the closest node not already in the @used_nodes map.
7701 * Should use nodemask_t.
7703 static int find_next_best_node(int node, nodemask_t *used_nodes)
7705 int i, n, val, min_val, best_node = 0;
7709 for (i = 0; i < nr_node_ids; i++) {
7710 /* Start at @node */
7711 n = (node + i) % nr_node_ids;
7713 if (!nr_cpus_node(n))
7716 /* Skip already used nodes */
7717 if (node_isset(n, *used_nodes))
7720 /* Simple min distance search */
7721 val = node_distance(node, n);
7723 if (val < min_val) {
7729 node_set(best_node, *used_nodes);
7734 * sched_domain_node_span - get a cpumask for a node's sched_domain
7735 * @node: node whose cpumask we're constructing
7736 * @span: resulting cpumask
7738 * Given a node, construct a good cpumask for its sched_domain to span. It
7739 * should be one that prevents unnecessary balancing, but also spreads tasks
7742 static void sched_domain_node_span(int node, struct cpumask *span)
7744 nodemask_t used_nodes;
7747 cpumask_clear(span);
7748 nodes_clear(used_nodes);
7750 cpumask_or(span, span, cpumask_of_node(node));
7751 node_set(node, used_nodes);
7753 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7754 int next_node = find_next_best_node(node, &used_nodes);
7756 cpumask_or(span, span, cpumask_of_node(next_node));
7759 #endif /* CONFIG_NUMA */
7761 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7764 * The cpus mask in sched_group and sched_domain hangs off the end.
7765 * FIXME: use cpumask_var_t or dynamic percpu alloc to avoid wasting space
7766 * for nr_cpu_ids < CONFIG_NR_CPUS.
7768 struct static_sched_group {
7769 struct sched_group sg;
7770 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
7773 struct static_sched_domain {
7774 struct sched_domain sd;
7775 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
7779 * SMT sched-domains:
7781 #ifdef CONFIG_SCHED_SMT
7782 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
7783 static DEFINE_PER_CPU(struct static_sched_group, sched_group_cpus);
7786 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
7787 struct sched_group **sg, struct cpumask *unused)
7790 *sg = &per_cpu(sched_group_cpus, cpu).sg;
7793 #endif /* CONFIG_SCHED_SMT */
7796 * multi-core sched-domains:
7798 #ifdef CONFIG_SCHED_MC
7799 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
7800 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
7801 #endif /* CONFIG_SCHED_MC */
7803 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7805 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
7806 struct sched_group **sg, struct cpumask *mask)
7810 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
7811 group = cpumask_first(mask);
7813 *sg = &per_cpu(sched_group_core, group).sg;
7816 #elif defined(CONFIG_SCHED_MC)
7818 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
7819 struct sched_group **sg, struct cpumask *unused)
7822 *sg = &per_cpu(sched_group_core, cpu).sg;
7827 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
7828 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
7831 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
7832 struct sched_group **sg, struct cpumask *mask)
7835 #ifdef CONFIG_SCHED_MC
7836 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
7837 group = cpumask_first(mask);
7838 #elif defined(CONFIG_SCHED_SMT)
7839 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
7840 group = cpumask_first(mask);
7845 *sg = &per_cpu(sched_group_phys, group).sg;
7851 * The init_sched_build_groups can't handle what we want to do with node
7852 * groups, so roll our own. Now each node has its own list of groups which
7853 * gets dynamically allocated.
7855 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
7856 static struct sched_group ***sched_group_nodes_bycpu;
7858 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
7859 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
7861 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
7862 struct sched_group **sg,
7863 struct cpumask *nodemask)
7867 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
7868 group = cpumask_first(nodemask);
7871 *sg = &per_cpu(sched_group_allnodes, group).sg;
7875 static void init_numa_sched_groups_power(struct sched_group *group_head)
7877 struct sched_group *sg = group_head;
7883 for_each_cpu(j, sched_group_cpus(sg)) {
7884 struct sched_domain *sd;
7886 sd = &per_cpu(phys_domains, j).sd;
7887 if (j != cpumask_first(sched_group_cpus(sd->groups))) {
7889 * Only add "power" once for each
7895 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7898 } while (sg != group_head);
7900 #endif /* CONFIG_NUMA */
7903 /* Free memory allocated for various sched_group structures */
7904 static void free_sched_groups(const struct cpumask *cpu_map,
7905 struct cpumask *nodemask)
7909 for_each_cpu(cpu, cpu_map) {
7910 struct sched_group **sched_group_nodes
7911 = sched_group_nodes_bycpu[cpu];
7913 if (!sched_group_nodes)
7916 for (i = 0; i < nr_node_ids; i++) {
7917 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7919 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
7920 if (cpumask_empty(nodemask))
7930 if (oldsg != sched_group_nodes[i])
7933 kfree(sched_group_nodes);
7934 sched_group_nodes_bycpu[cpu] = NULL;
7937 #else /* !CONFIG_NUMA */
7938 static void free_sched_groups(const struct cpumask *cpu_map,
7939 struct cpumask *nodemask)
7942 #endif /* CONFIG_NUMA */
7945 * Initialize sched groups cpu_power.
7947 * cpu_power indicates the capacity of sched group, which is used while
7948 * distributing the load between different sched groups in a sched domain.
7949 * Typically cpu_power for all the groups in a sched domain will be same unless
7950 * there are asymmetries in the topology. If there are asymmetries, group
7951 * having more cpu_power will pickup more load compared to the group having
7954 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7955 * the maximum number of tasks a group can handle in the presence of other idle
7956 * or lightly loaded groups in the same sched domain.
7958 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7960 struct sched_domain *child;
7961 struct sched_group *group;
7963 WARN_ON(!sd || !sd->groups);
7965 if (cpu != cpumask_first(sched_group_cpus(sd->groups)))
7970 sd->groups->__cpu_power = 0;
7973 * For perf policy, if the groups in child domain share resources
7974 * (for example cores sharing some portions of the cache hierarchy
7975 * or SMT), then set this domain groups cpu_power such that each group
7976 * can handle only one task, when there are other idle groups in the
7977 * same sched domain.
7979 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7981 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7982 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7987 * add cpu_power of each child group to this groups cpu_power
7989 group = child->groups;
7991 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7992 group = group->next;
7993 } while (group != child->groups);
7997 * Initializers for schedule domains
7998 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
8001 #ifdef CONFIG_SCHED_DEBUG
8002 # define SD_INIT_NAME(sd, type) sd->name = #type
8004 # define SD_INIT_NAME(sd, type) do { } while (0)
8007 #define SD_INIT(sd, type) sd_init_##type(sd)
8009 #define SD_INIT_FUNC(type) \
8010 static noinline void sd_init_##type(struct sched_domain *sd) \
8012 memset(sd, 0, sizeof(*sd)); \
8013 *sd = SD_##type##_INIT; \
8014 sd->level = SD_LV_##type; \
8015 SD_INIT_NAME(sd, type); \
8020 SD_INIT_FUNC(ALLNODES)
8023 #ifdef CONFIG_SCHED_SMT
8024 SD_INIT_FUNC(SIBLING)
8026 #ifdef CONFIG_SCHED_MC
8030 static int default_relax_domain_level = -1;
8032 static int __init setup_relax_domain_level(char *str)
8036 val = simple_strtoul(str, NULL, 0);
8037 if (val < SD_LV_MAX)
8038 default_relax_domain_level = val;
8042 __setup("relax_domain_level=", setup_relax_domain_level);
8044 static void set_domain_attribute(struct sched_domain *sd,
8045 struct sched_domain_attr *attr)
8049 if (!attr || attr->relax_domain_level < 0) {
8050 if (default_relax_domain_level < 0)
8053 request = default_relax_domain_level;
8055 request = attr->relax_domain_level;
8056 if (request < sd->level) {
8057 /* turn off idle balance on this domain */
8058 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
8060 /* turn on idle balance on this domain */
8061 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
8066 * Build sched domains for a given set of cpus and attach the sched domains
8067 * to the individual cpus
8069 static int __build_sched_domains(const struct cpumask *cpu_map,
8070 struct sched_domain_attr *attr)
8072 int i, err = -ENOMEM;
8073 struct root_domain *rd;
8074 cpumask_var_t nodemask, this_sibling_map, this_core_map, send_covered,
8077 cpumask_var_t domainspan, covered, notcovered;
8078 struct sched_group **sched_group_nodes = NULL;
8079 int sd_allnodes = 0;
8081 if (!alloc_cpumask_var(&domainspan, GFP_KERNEL))
8083 if (!alloc_cpumask_var(&covered, GFP_KERNEL))
8084 goto free_domainspan;
8085 if (!alloc_cpumask_var(¬covered, GFP_KERNEL))
8089 if (!alloc_cpumask_var(&nodemask, GFP_KERNEL))
8090 goto free_notcovered;
8091 if (!alloc_cpumask_var(&this_sibling_map, GFP_KERNEL))
8093 if (!alloc_cpumask_var(&this_core_map, GFP_KERNEL))
8094 goto free_this_sibling_map;
8095 if (!alloc_cpumask_var(&send_covered, GFP_KERNEL))
8096 goto free_this_core_map;
8097 if (!alloc_cpumask_var(&tmpmask, GFP_KERNEL))
8098 goto free_send_covered;
8102 * Allocate the per-node list of sched groups
8104 sched_group_nodes = kcalloc(nr_node_ids, sizeof(struct sched_group *),
8106 if (!sched_group_nodes) {
8107 printk(KERN_WARNING "Can not alloc sched group node list\n");
8112 rd = alloc_rootdomain();
8114 printk(KERN_WARNING "Cannot alloc root domain\n");
8115 goto free_sched_groups;
8119 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = sched_group_nodes;
8123 * Set up domains for cpus specified by the cpu_map.
8125 for_each_cpu(i, cpu_map) {
8126 struct sched_domain *sd = NULL, *p;
8128 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(i)), cpu_map);
8131 if (cpumask_weight(cpu_map) >
8132 SD_NODES_PER_DOMAIN*cpumask_weight(nodemask)) {
8133 sd = &per_cpu(allnodes_domains, i).sd;
8134 SD_INIT(sd, ALLNODES);
8135 set_domain_attribute(sd, attr);
8136 cpumask_copy(sched_domain_span(sd), cpu_map);
8137 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
8143 sd = &per_cpu(node_domains, i).sd;
8145 set_domain_attribute(sd, attr);
8146 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
8150 cpumask_and(sched_domain_span(sd),
8151 sched_domain_span(sd), cpu_map);
8155 sd = &per_cpu(phys_domains, i).sd;
8157 set_domain_attribute(sd, attr);
8158 cpumask_copy(sched_domain_span(sd), nodemask);
8162 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
8164 #ifdef CONFIG_SCHED_MC
8166 sd = &per_cpu(core_domains, i).sd;
8168 set_domain_attribute(sd, attr);
8169 cpumask_and(sched_domain_span(sd), cpu_map,
8170 cpu_coregroup_mask(i));
8173 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
8176 #ifdef CONFIG_SCHED_SMT
8178 sd = &per_cpu(cpu_domains, i).sd;
8179 SD_INIT(sd, SIBLING);
8180 set_domain_attribute(sd, attr);
8181 cpumask_and(sched_domain_span(sd),
8182 topology_thread_cpumask(i), cpu_map);
8185 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
8189 #ifdef CONFIG_SCHED_SMT
8190 /* Set up CPU (sibling) groups */
8191 for_each_cpu(i, cpu_map) {
8192 cpumask_and(this_sibling_map,
8193 topology_thread_cpumask(i), cpu_map);
8194 if (i != cpumask_first(this_sibling_map))
8197 init_sched_build_groups(this_sibling_map, cpu_map,
8199 send_covered, tmpmask);
8203 #ifdef CONFIG_SCHED_MC
8204 /* Set up multi-core groups */
8205 for_each_cpu(i, cpu_map) {
8206 cpumask_and(this_core_map, cpu_coregroup_mask(i), cpu_map);
8207 if (i != cpumask_first(this_core_map))
8210 init_sched_build_groups(this_core_map, cpu_map,
8212 send_covered, tmpmask);
8216 /* Set up physical groups */
8217 for (i = 0; i < nr_node_ids; i++) {
8218 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8219 if (cpumask_empty(nodemask))
8222 init_sched_build_groups(nodemask, cpu_map,
8224 send_covered, tmpmask);
8228 /* Set up node groups */
8230 init_sched_build_groups(cpu_map, cpu_map,
8231 &cpu_to_allnodes_group,
8232 send_covered, tmpmask);
8235 for (i = 0; i < nr_node_ids; i++) {
8236 /* Set up node groups */
8237 struct sched_group *sg, *prev;
8240 cpumask_clear(covered);
8241 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8242 if (cpumask_empty(nodemask)) {
8243 sched_group_nodes[i] = NULL;
8247 sched_domain_node_span(i, domainspan);
8248 cpumask_and(domainspan, domainspan, cpu_map);
8250 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8253 printk(KERN_WARNING "Can not alloc domain group for "
8257 sched_group_nodes[i] = sg;
8258 for_each_cpu(j, nodemask) {
8259 struct sched_domain *sd;
8261 sd = &per_cpu(node_domains, j).sd;
8264 sg->__cpu_power = 0;
8265 cpumask_copy(sched_group_cpus(sg), nodemask);
8267 cpumask_or(covered, covered, nodemask);
8270 for (j = 0; j < nr_node_ids; j++) {
8271 int n = (i + j) % nr_node_ids;
8273 cpumask_complement(notcovered, covered);
8274 cpumask_and(tmpmask, notcovered, cpu_map);
8275 cpumask_and(tmpmask, tmpmask, domainspan);
8276 if (cpumask_empty(tmpmask))
8279 cpumask_and(tmpmask, tmpmask, cpumask_of_node(n));
8280 if (cpumask_empty(tmpmask))
8283 sg = kmalloc_node(sizeof(struct sched_group) +
8288 "Can not alloc domain group for node %d\n", j);
8291 sg->__cpu_power = 0;
8292 cpumask_copy(sched_group_cpus(sg), tmpmask);
8293 sg->next = prev->next;
8294 cpumask_or(covered, covered, tmpmask);
8301 /* Calculate CPU power for physical packages and nodes */
8302 #ifdef CONFIG_SCHED_SMT
8303 for_each_cpu(i, cpu_map) {
8304 struct sched_domain *sd = &per_cpu(cpu_domains, i).sd;
8306 init_sched_groups_power(i, sd);
8309 #ifdef CONFIG_SCHED_MC
8310 for_each_cpu(i, cpu_map) {
8311 struct sched_domain *sd = &per_cpu(core_domains, i).sd;
8313 init_sched_groups_power(i, sd);
8317 for_each_cpu(i, cpu_map) {
8318 struct sched_domain *sd = &per_cpu(phys_domains, i).sd;
8320 init_sched_groups_power(i, sd);
8324 for (i = 0; i < nr_node_ids; i++)
8325 init_numa_sched_groups_power(sched_group_nodes[i]);
8328 struct sched_group *sg;
8330 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
8332 init_numa_sched_groups_power(sg);
8336 /* Attach the domains */
8337 for_each_cpu(i, cpu_map) {
8338 struct sched_domain *sd;
8339 #ifdef CONFIG_SCHED_SMT
8340 sd = &per_cpu(cpu_domains, i).sd;
8341 #elif defined(CONFIG_SCHED_MC)
8342 sd = &per_cpu(core_domains, i).sd;
8344 sd = &per_cpu(phys_domains, i).sd;
8346 cpu_attach_domain(sd, rd, i);
8352 free_cpumask_var(tmpmask);
8354 free_cpumask_var(send_covered);
8356 free_cpumask_var(this_core_map);
8357 free_this_sibling_map:
8358 free_cpumask_var(this_sibling_map);
8360 free_cpumask_var(nodemask);
8363 free_cpumask_var(notcovered);
8365 free_cpumask_var(covered);
8367 free_cpumask_var(domainspan);
8374 kfree(sched_group_nodes);
8380 free_sched_groups(cpu_map, tmpmask);
8381 free_rootdomain(rd);
8386 static int build_sched_domains(const struct cpumask *cpu_map)
8388 return __build_sched_domains(cpu_map, NULL);
8391 static struct cpumask *doms_cur; /* current sched domains */
8392 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
8393 static struct sched_domain_attr *dattr_cur;
8394 /* attribues of custom domains in 'doms_cur' */
8397 * Special case: If a kmalloc of a doms_cur partition (array of
8398 * cpumask) fails, then fallback to a single sched domain,
8399 * as determined by the single cpumask fallback_doms.
8401 static cpumask_var_t fallback_doms;
8404 * arch_update_cpu_topology lets virtualized architectures update the
8405 * cpu core maps. It is supposed to return 1 if the topology changed
8406 * or 0 if it stayed the same.
8408 int __attribute__((weak)) arch_update_cpu_topology(void)
8414 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
8415 * For now this just excludes isolated cpus, but could be used to
8416 * exclude other special cases in the future.
8418 static int arch_init_sched_domains(const struct cpumask *cpu_map)
8422 arch_update_cpu_topology();
8424 doms_cur = kmalloc(cpumask_size(), GFP_KERNEL);
8426 doms_cur = fallback_doms;
8427 cpumask_andnot(doms_cur, cpu_map, cpu_isolated_map);
8429 err = build_sched_domains(doms_cur);
8430 register_sched_domain_sysctl();
8435 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
8436 struct cpumask *tmpmask)
8438 free_sched_groups(cpu_map, tmpmask);
8442 * Detach sched domains from a group of cpus specified in cpu_map
8443 * These cpus will now be attached to the NULL domain
8445 static void detach_destroy_domains(const struct cpumask *cpu_map)
8447 /* Save because hotplug lock held. */
8448 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
8451 for_each_cpu(i, cpu_map)
8452 cpu_attach_domain(NULL, &def_root_domain, i);
8453 synchronize_sched();
8454 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
8457 /* handle null as "default" */
8458 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
8459 struct sched_domain_attr *new, int idx_new)
8461 struct sched_domain_attr tmp;
8468 return !memcmp(cur ? (cur + idx_cur) : &tmp,
8469 new ? (new + idx_new) : &tmp,
8470 sizeof(struct sched_domain_attr));
8474 * Partition sched domains as specified by the 'ndoms_new'
8475 * cpumasks in the array doms_new[] of cpumasks. This compares
8476 * doms_new[] to the current sched domain partitioning, doms_cur[].
8477 * It destroys each deleted domain and builds each new domain.
8479 * 'doms_new' is an array of cpumask's of length 'ndoms_new'.
8480 * The masks don't intersect (don't overlap.) We should setup one
8481 * sched domain for each mask. CPUs not in any of the cpumasks will
8482 * not be load balanced. If the same cpumask appears both in the
8483 * current 'doms_cur' domains and in the new 'doms_new', we can leave
8486 * The passed in 'doms_new' should be kmalloc'd. This routine takes
8487 * ownership of it and will kfree it when done with it. If the caller
8488 * failed the kmalloc call, then it can pass in doms_new == NULL &&
8489 * ndoms_new == 1, and partition_sched_domains() will fallback to
8490 * the single partition 'fallback_doms', it also forces the domains
8493 * If doms_new == NULL it will be replaced with cpu_online_mask.
8494 * ndoms_new == 0 is a special case for destroying existing domains,
8495 * and it will not create the default domain.
8497 * Call with hotplug lock held
8499 /* FIXME: Change to struct cpumask *doms_new[] */
8500 void partition_sched_domains(int ndoms_new, struct cpumask *doms_new,
8501 struct sched_domain_attr *dattr_new)
8506 mutex_lock(&sched_domains_mutex);
8508 /* always unregister in case we don't destroy any domains */
8509 unregister_sched_domain_sysctl();
8511 /* Let architecture update cpu core mappings. */
8512 new_topology = arch_update_cpu_topology();
8514 n = doms_new ? ndoms_new : 0;
8516 /* Destroy deleted domains */
8517 for (i = 0; i < ndoms_cur; i++) {
8518 for (j = 0; j < n && !new_topology; j++) {
8519 if (cpumask_equal(&doms_cur[i], &doms_new[j])
8520 && dattrs_equal(dattr_cur, i, dattr_new, j))
8523 /* no match - a current sched domain not in new doms_new[] */
8524 detach_destroy_domains(doms_cur + i);
8529 if (doms_new == NULL) {
8531 doms_new = fallback_doms;
8532 cpumask_andnot(&doms_new[0], cpu_online_mask, cpu_isolated_map);
8533 WARN_ON_ONCE(dattr_new);
8536 /* Build new domains */
8537 for (i = 0; i < ndoms_new; i++) {
8538 for (j = 0; j < ndoms_cur && !new_topology; j++) {
8539 if (cpumask_equal(&doms_new[i], &doms_cur[j])
8540 && dattrs_equal(dattr_new, i, dattr_cur, j))
8543 /* no match - add a new doms_new */
8544 __build_sched_domains(doms_new + i,
8545 dattr_new ? dattr_new + i : NULL);
8550 /* Remember the new sched domains */
8551 if (doms_cur != fallback_doms)
8553 kfree(dattr_cur); /* kfree(NULL) is safe */
8554 doms_cur = doms_new;
8555 dattr_cur = dattr_new;
8556 ndoms_cur = ndoms_new;
8558 register_sched_domain_sysctl();
8560 mutex_unlock(&sched_domains_mutex);
8563 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
8564 static void arch_reinit_sched_domains(void)
8568 /* Destroy domains first to force the rebuild */
8569 partition_sched_domains(0, NULL, NULL);
8571 rebuild_sched_domains();
8575 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
8577 unsigned int level = 0;
8579 if (sscanf(buf, "%u", &level) != 1)
8583 * level is always be positive so don't check for
8584 * level < POWERSAVINGS_BALANCE_NONE which is 0
8585 * What happens on 0 or 1 byte write,
8586 * need to check for count as well?
8589 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
8593 sched_smt_power_savings = level;
8595 sched_mc_power_savings = level;
8597 arch_reinit_sched_domains();
8602 #ifdef CONFIG_SCHED_MC
8603 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
8606 return sprintf(page, "%u\n", sched_mc_power_savings);
8608 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
8609 const char *buf, size_t count)
8611 return sched_power_savings_store(buf, count, 0);
8613 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
8614 sched_mc_power_savings_show,
8615 sched_mc_power_savings_store);
8618 #ifdef CONFIG_SCHED_SMT
8619 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
8622 return sprintf(page, "%u\n", sched_smt_power_savings);
8624 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
8625 const char *buf, size_t count)
8627 return sched_power_savings_store(buf, count, 1);
8629 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
8630 sched_smt_power_savings_show,
8631 sched_smt_power_savings_store);
8634 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
8638 #ifdef CONFIG_SCHED_SMT
8640 err = sysfs_create_file(&cls->kset.kobj,
8641 &attr_sched_smt_power_savings.attr);
8643 #ifdef CONFIG_SCHED_MC
8644 if (!err && mc_capable())
8645 err = sysfs_create_file(&cls->kset.kobj,
8646 &attr_sched_mc_power_savings.attr);
8650 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
8652 #ifndef CONFIG_CPUSETS
8654 * Add online and remove offline CPUs from the scheduler domains.
8655 * When cpusets are enabled they take over this function.
8657 static int update_sched_domains(struct notifier_block *nfb,
8658 unsigned long action, void *hcpu)
8662 case CPU_ONLINE_FROZEN:
8664 case CPU_DEAD_FROZEN:
8665 partition_sched_domains(1, NULL, NULL);
8674 static int update_runtime(struct notifier_block *nfb,
8675 unsigned long action, void *hcpu)
8677 int cpu = (int)(long)hcpu;
8680 case CPU_DOWN_PREPARE:
8681 case CPU_DOWN_PREPARE_FROZEN:
8682 disable_runtime(cpu_rq(cpu));
8685 case CPU_DOWN_FAILED:
8686 case CPU_DOWN_FAILED_FROZEN:
8688 case CPU_ONLINE_FROZEN:
8689 enable_runtime(cpu_rq(cpu));
8697 void __init sched_init_smp(void)
8699 cpumask_var_t non_isolated_cpus;
8701 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
8703 #if defined(CONFIG_NUMA)
8704 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
8706 BUG_ON(sched_group_nodes_bycpu == NULL);
8709 mutex_lock(&sched_domains_mutex);
8710 arch_init_sched_domains(cpu_online_mask);
8711 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
8712 if (cpumask_empty(non_isolated_cpus))
8713 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
8714 mutex_unlock(&sched_domains_mutex);
8717 #ifndef CONFIG_CPUSETS
8718 /* XXX: Theoretical race here - CPU may be hotplugged now */
8719 hotcpu_notifier(update_sched_domains, 0);
8722 /* RT runtime code needs to handle some hotplug events */
8723 hotcpu_notifier(update_runtime, 0);
8727 /* Move init over to a non-isolated CPU */
8728 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
8730 sched_init_granularity();
8731 free_cpumask_var(non_isolated_cpus);
8733 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
8734 init_sched_rt_class();
8737 void __init sched_init_smp(void)
8739 sched_init_granularity();
8741 #endif /* CONFIG_SMP */
8743 int in_sched_functions(unsigned long addr)
8745 return in_lock_functions(addr) ||
8746 (addr >= (unsigned long)__sched_text_start
8747 && addr < (unsigned long)__sched_text_end);
8750 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8752 cfs_rq->tasks_timeline = RB_ROOT;
8753 INIT_LIST_HEAD(&cfs_rq->tasks);
8754 #ifdef CONFIG_FAIR_GROUP_SCHED
8757 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8760 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8762 struct rt_prio_array *array;
8765 array = &rt_rq->active;
8766 for (i = 0; i < MAX_RT_PRIO; i++) {
8767 INIT_LIST_HEAD(array->queue + i);
8768 __clear_bit(i, array->bitmap);
8770 /* delimiter for bitsearch: */
8771 __set_bit(MAX_RT_PRIO, array->bitmap);
8773 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8774 rt_rq->highest_prio.curr = MAX_RT_PRIO;
8776 rt_rq->highest_prio.next = MAX_RT_PRIO;
8780 rt_rq->rt_nr_migratory = 0;
8781 rt_rq->overloaded = 0;
8782 plist_head_init(&rq->rt.pushable_tasks, &rq->lock);
8786 rt_rq->rt_throttled = 0;
8787 rt_rq->rt_runtime = 0;
8788 spin_lock_init(&rt_rq->rt_runtime_lock);
8790 #ifdef CONFIG_RT_GROUP_SCHED
8791 rt_rq->rt_nr_boosted = 0;
8796 #ifdef CONFIG_FAIR_GROUP_SCHED
8797 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8798 struct sched_entity *se, int cpu, int add,
8799 struct sched_entity *parent)
8801 struct rq *rq = cpu_rq(cpu);
8802 tg->cfs_rq[cpu] = cfs_rq;
8803 init_cfs_rq(cfs_rq, rq);
8806 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8809 /* se could be NULL for init_task_group */
8814 se->cfs_rq = &rq->cfs;
8816 se->cfs_rq = parent->my_q;
8819 se->load.weight = tg->shares;
8820 se->load.inv_weight = 0;
8821 se->parent = parent;
8825 #ifdef CONFIG_RT_GROUP_SCHED
8826 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8827 struct sched_rt_entity *rt_se, int cpu, int add,
8828 struct sched_rt_entity *parent)
8830 struct rq *rq = cpu_rq(cpu);
8832 tg->rt_rq[cpu] = rt_rq;
8833 init_rt_rq(rt_rq, rq);
8835 rt_rq->rt_se = rt_se;
8836 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8838 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8840 tg->rt_se[cpu] = rt_se;
8845 rt_se->rt_rq = &rq->rt;
8847 rt_se->rt_rq = parent->my_q;
8849 rt_se->my_q = rt_rq;
8850 rt_se->parent = parent;
8851 INIT_LIST_HEAD(&rt_se->run_list);
8855 void __init sched_init(void)
8858 unsigned long alloc_size = 0, ptr;
8860 #ifdef CONFIG_FAIR_GROUP_SCHED
8861 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8863 #ifdef CONFIG_RT_GROUP_SCHED
8864 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8866 #ifdef CONFIG_USER_SCHED
8869 #ifdef CONFIG_CPUMASK_OFFSTACK
8870 alloc_size += num_possible_cpus() * cpumask_size();
8873 * As sched_init() is called before page_alloc is setup,
8874 * we use alloc_bootmem().
8877 ptr = (unsigned long)alloc_bootmem(alloc_size);
8879 #ifdef CONFIG_FAIR_GROUP_SCHED
8880 init_task_group.se = (struct sched_entity **)ptr;
8881 ptr += nr_cpu_ids * sizeof(void **);
8883 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8884 ptr += nr_cpu_ids * sizeof(void **);
8886 #ifdef CONFIG_USER_SCHED
8887 root_task_group.se = (struct sched_entity **)ptr;
8888 ptr += nr_cpu_ids * sizeof(void **);
8890 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8891 ptr += nr_cpu_ids * sizeof(void **);
8892 #endif /* CONFIG_USER_SCHED */
8893 #endif /* CONFIG_FAIR_GROUP_SCHED */
8894 #ifdef CONFIG_RT_GROUP_SCHED
8895 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8896 ptr += nr_cpu_ids * sizeof(void **);
8898 init_task_group.rt_rq = (struct rt_rq **)ptr;
8899 ptr += nr_cpu_ids * sizeof(void **);
8901 #ifdef CONFIG_USER_SCHED
8902 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8903 ptr += nr_cpu_ids * sizeof(void **);
8905 root_task_group.rt_rq = (struct rt_rq **)ptr;
8906 ptr += nr_cpu_ids * sizeof(void **);
8907 #endif /* CONFIG_USER_SCHED */
8908 #endif /* CONFIG_RT_GROUP_SCHED */
8909 #ifdef CONFIG_CPUMASK_OFFSTACK
8910 for_each_possible_cpu(i) {
8911 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
8912 ptr += cpumask_size();
8914 #endif /* CONFIG_CPUMASK_OFFSTACK */
8918 init_defrootdomain();
8921 init_rt_bandwidth(&def_rt_bandwidth,
8922 global_rt_period(), global_rt_runtime());
8924 #ifdef CONFIG_RT_GROUP_SCHED
8925 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8926 global_rt_period(), global_rt_runtime());
8927 #ifdef CONFIG_USER_SCHED
8928 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8929 global_rt_period(), RUNTIME_INF);
8930 #endif /* CONFIG_USER_SCHED */
8931 #endif /* CONFIG_RT_GROUP_SCHED */
8933 #ifdef CONFIG_GROUP_SCHED
8934 list_add(&init_task_group.list, &task_groups);
8935 INIT_LIST_HEAD(&init_task_group.children);
8937 #ifdef CONFIG_USER_SCHED
8938 INIT_LIST_HEAD(&root_task_group.children);
8939 init_task_group.parent = &root_task_group;
8940 list_add(&init_task_group.siblings, &root_task_group.children);
8941 #endif /* CONFIG_USER_SCHED */
8942 #endif /* CONFIG_GROUP_SCHED */
8944 for_each_possible_cpu(i) {
8948 spin_lock_init(&rq->lock);
8950 init_cfs_rq(&rq->cfs, rq);
8951 init_rt_rq(&rq->rt, rq);
8952 #ifdef CONFIG_FAIR_GROUP_SCHED
8953 init_task_group.shares = init_task_group_load;
8954 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8955 #ifdef CONFIG_CGROUP_SCHED
8957 * How much cpu bandwidth does init_task_group get?
8959 * In case of task-groups formed thr' the cgroup filesystem, it
8960 * gets 100% of the cpu resources in the system. This overall
8961 * system cpu resource is divided among the tasks of
8962 * init_task_group and its child task-groups in a fair manner,
8963 * based on each entity's (task or task-group's) weight
8964 * (se->load.weight).
8966 * In other words, if init_task_group has 10 tasks of weight
8967 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8968 * then A0's share of the cpu resource is:
8970 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8972 * We achieve this by letting init_task_group's tasks sit
8973 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8975 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8976 #elif defined CONFIG_USER_SCHED
8977 root_task_group.shares = NICE_0_LOAD;
8978 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8980 * In case of task-groups formed thr' the user id of tasks,
8981 * init_task_group represents tasks belonging to root user.
8982 * Hence it forms a sibling of all subsequent groups formed.
8983 * In this case, init_task_group gets only a fraction of overall
8984 * system cpu resource, based on the weight assigned to root
8985 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8986 * by letting tasks of init_task_group sit in a separate cfs_rq
8987 * (init_cfs_rq) and having one entity represent this group of
8988 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8990 init_tg_cfs_entry(&init_task_group,
8991 &per_cpu(init_cfs_rq, i),
8992 &per_cpu(init_sched_entity, i), i, 1,
8993 root_task_group.se[i]);
8996 #endif /* CONFIG_FAIR_GROUP_SCHED */
8998 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8999 #ifdef CONFIG_RT_GROUP_SCHED
9000 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
9001 #ifdef CONFIG_CGROUP_SCHED
9002 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
9003 #elif defined CONFIG_USER_SCHED
9004 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
9005 init_tg_rt_entry(&init_task_group,
9006 &per_cpu(init_rt_rq, i),
9007 &per_cpu(init_sched_rt_entity, i), i, 1,
9008 root_task_group.rt_se[i]);
9012 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
9013 rq->cpu_load[j] = 0;
9017 rq->active_balance = 0;
9018 rq->next_balance = jiffies;
9022 rq->migration_thread = NULL;
9023 INIT_LIST_HEAD(&rq->migration_queue);
9024 rq_attach_root(rq, &def_root_domain);
9027 atomic_set(&rq->nr_iowait, 0);
9030 set_load_weight(&init_task);
9032 #ifdef CONFIG_PREEMPT_NOTIFIERS
9033 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
9037 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9040 #ifdef CONFIG_RT_MUTEXES
9041 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
9045 * The boot idle thread does lazy MMU switching as well:
9047 atomic_inc(&init_mm.mm_count);
9048 enter_lazy_tlb(&init_mm, current);
9051 * Make us the idle thread. Technically, schedule() should not be
9052 * called from this thread, however somewhere below it might be,
9053 * but because we are the idle thread, we just pick up running again
9054 * when this runqueue becomes "idle".
9056 init_idle(current, smp_processor_id());
9058 * During early bootup we pretend to be a normal task:
9060 current->sched_class = &fair_sched_class;
9062 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
9063 alloc_bootmem_cpumask_var(&nohz_cpu_mask);
9066 alloc_bootmem_cpumask_var(&nohz.cpu_mask);
9068 alloc_bootmem_cpumask_var(&cpu_isolated_map);
9071 scheduler_running = 1;
9074 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
9075 void __might_sleep(char *file, int line)
9078 static unsigned long prev_jiffy; /* ratelimiting */
9080 if ((!in_atomic() && !irqs_disabled()) ||
9081 system_state != SYSTEM_RUNNING || oops_in_progress)
9083 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9085 prev_jiffy = jiffies;
9088 "BUG: sleeping function called from invalid context at %s:%d\n",
9091 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9092 in_atomic(), irqs_disabled(),
9093 current->pid, current->comm);
9095 debug_show_held_locks(current);
9096 if (irqs_disabled())
9097 print_irqtrace_events(current);
9101 EXPORT_SYMBOL(__might_sleep);
9104 #ifdef CONFIG_MAGIC_SYSRQ
9105 static void normalize_task(struct rq *rq, struct task_struct *p)
9109 update_rq_clock(rq);
9110 on_rq = p->se.on_rq;
9112 deactivate_task(rq, p, 0);
9113 __setscheduler(rq, p, SCHED_NORMAL, 0);
9115 activate_task(rq, p, 0);
9116 resched_task(rq->curr);
9120 void normalize_rt_tasks(void)
9122 struct task_struct *g, *p;
9123 unsigned long flags;
9126 read_lock_irqsave(&tasklist_lock, flags);
9127 do_each_thread(g, p) {
9129 * Only normalize user tasks:
9134 p->se.exec_start = 0;
9135 #ifdef CONFIG_SCHEDSTATS
9136 p->se.wait_start = 0;
9137 p->se.sleep_start = 0;
9138 p->se.block_start = 0;
9143 * Renice negative nice level userspace
9146 if (TASK_NICE(p) < 0 && p->mm)
9147 set_user_nice(p, 0);
9151 spin_lock(&p->pi_lock);
9152 rq = __task_rq_lock(p);
9154 normalize_task(rq, p);
9156 __task_rq_unlock(rq);
9157 spin_unlock(&p->pi_lock);
9158 } while_each_thread(g, p);
9160 read_unlock_irqrestore(&tasklist_lock, flags);
9163 #endif /* CONFIG_MAGIC_SYSRQ */
9167 * These functions are only useful for the IA64 MCA handling.
9169 * They can only be called when the whole system has been
9170 * stopped - every CPU needs to be quiescent, and no scheduling
9171 * activity can take place. Using them for anything else would
9172 * be a serious bug, and as a result, they aren't even visible
9173 * under any other configuration.
9177 * curr_task - return the current task for a given cpu.
9178 * @cpu: the processor in question.
9180 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9182 struct task_struct *curr_task(int cpu)
9184 return cpu_curr(cpu);
9188 * set_curr_task - set the current task for a given cpu.
9189 * @cpu: the processor in question.
9190 * @p: the task pointer to set.
9192 * Description: This function must only be used when non-maskable interrupts
9193 * are serviced on a separate stack. It allows the architecture to switch the
9194 * notion of the current task on a cpu in a non-blocking manner. This function
9195 * must be called with all CPU's synchronized, and interrupts disabled, the
9196 * and caller must save the original value of the current task (see
9197 * curr_task() above) and restore that value before reenabling interrupts and
9198 * re-starting the system.
9200 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9202 void set_curr_task(int cpu, struct task_struct *p)
9209 #ifdef CONFIG_FAIR_GROUP_SCHED
9210 static void free_fair_sched_group(struct task_group *tg)
9214 for_each_possible_cpu(i) {
9216 kfree(tg->cfs_rq[i]);
9226 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9228 struct cfs_rq *cfs_rq;
9229 struct sched_entity *se;
9233 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
9236 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
9240 tg->shares = NICE_0_LOAD;
9242 for_each_possible_cpu(i) {
9245 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
9246 GFP_KERNEL, cpu_to_node(i));
9250 se = kzalloc_node(sizeof(struct sched_entity),
9251 GFP_KERNEL, cpu_to_node(i));
9255 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
9264 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9266 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
9267 &cpu_rq(cpu)->leaf_cfs_rq_list);
9270 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9272 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
9274 #else /* !CONFG_FAIR_GROUP_SCHED */
9275 static inline void free_fair_sched_group(struct task_group *tg)
9280 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9285 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9289 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9292 #endif /* CONFIG_FAIR_GROUP_SCHED */
9294 #ifdef CONFIG_RT_GROUP_SCHED
9295 static void free_rt_sched_group(struct task_group *tg)
9299 destroy_rt_bandwidth(&tg->rt_bandwidth);
9301 for_each_possible_cpu(i) {
9303 kfree(tg->rt_rq[i]);
9305 kfree(tg->rt_se[i]);
9313 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9315 struct rt_rq *rt_rq;
9316 struct sched_rt_entity *rt_se;
9320 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
9323 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
9327 init_rt_bandwidth(&tg->rt_bandwidth,
9328 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
9330 for_each_possible_cpu(i) {
9333 rt_rq = kzalloc_node(sizeof(struct rt_rq),
9334 GFP_KERNEL, cpu_to_node(i));
9338 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
9339 GFP_KERNEL, cpu_to_node(i));
9343 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
9352 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9354 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
9355 &cpu_rq(cpu)->leaf_rt_rq_list);
9358 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9360 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
9362 #else /* !CONFIG_RT_GROUP_SCHED */
9363 static inline void free_rt_sched_group(struct task_group *tg)
9368 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9373 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9377 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9380 #endif /* CONFIG_RT_GROUP_SCHED */
9382 #ifdef CONFIG_GROUP_SCHED
9383 static void free_sched_group(struct task_group *tg)
9385 free_fair_sched_group(tg);
9386 free_rt_sched_group(tg);
9390 /* allocate runqueue etc for a new task group */
9391 struct task_group *sched_create_group(struct task_group *parent)
9393 struct task_group *tg;
9394 unsigned long flags;
9397 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
9399 return ERR_PTR(-ENOMEM);
9401 if (!alloc_fair_sched_group(tg, parent))
9404 if (!alloc_rt_sched_group(tg, parent))
9407 spin_lock_irqsave(&task_group_lock, flags);
9408 for_each_possible_cpu(i) {
9409 register_fair_sched_group(tg, i);
9410 register_rt_sched_group(tg, i);
9412 list_add_rcu(&tg->list, &task_groups);
9414 WARN_ON(!parent); /* root should already exist */
9416 tg->parent = parent;
9417 INIT_LIST_HEAD(&tg->children);
9418 list_add_rcu(&tg->siblings, &parent->children);
9419 spin_unlock_irqrestore(&task_group_lock, flags);
9424 free_sched_group(tg);
9425 return ERR_PTR(-ENOMEM);
9428 /* rcu callback to free various structures associated with a task group */
9429 static void free_sched_group_rcu(struct rcu_head *rhp)
9431 /* now it should be safe to free those cfs_rqs */
9432 free_sched_group(container_of(rhp, struct task_group, rcu));
9435 /* Destroy runqueue etc associated with a task group */
9436 void sched_destroy_group(struct task_group *tg)
9438 unsigned long flags;
9441 spin_lock_irqsave(&task_group_lock, flags);
9442 for_each_possible_cpu(i) {
9443 unregister_fair_sched_group(tg, i);
9444 unregister_rt_sched_group(tg, i);
9446 list_del_rcu(&tg->list);
9447 list_del_rcu(&tg->siblings);
9448 spin_unlock_irqrestore(&task_group_lock, flags);
9450 /* wait for possible concurrent references to cfs_rqs complete */
9451 call_rcu(&tg->rcu, free_sched_group_rcu);
9454 /* change task's runqueue when it moves between groups.
9455 * The caller of this function should have put the task in its new group
9456 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
9457 * reflect its new group.
9459 void sched_move_task(struct task_struct *tsk)
9462 unsigned long flags;
9465 rq = task_rq_lock(tsk, &flags);
9467 update_rq_clock(rq);
9469 running = task_current(rq, tsk);
9470 on_rq = tsk->se.on_rq;
9473 dequeue_task(rq, tsk, 0);
9474 if (unlikely(running))
9475 tsk->sched_class->put_prev_task(rq, tsk);
9477 set_task_rq(tsk, task_cpu(tsk));
9479 #ifdef CONFIG_FAIR_GROUP_SCHED
9480 if (tsk->sched_class->moved_group)
9481 tsk->sched_class->moved_group(tsk);
9484 if (unlikely(running))
9485 tsk->sched_class->set_curr_task(rq);
9487 enqueue_task(rq, tsk, 0);
9489 task_rq_unlock(rq, &flags);
9491 #endif /* CONFIG_GROUP_SCHED */
9493 #ifdef CONFIG_FAIR_GROUP_SCHED
9494 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
9496 struct cfs_rq *cfs_rq = se->cfs_rq;
9501 dequeue_entity(cfs_rq, se, 0);
9503 se->load.weight = shares;
9504 se->load.inv_weight = 0;
9507 enqueue_entity(cfs_rq, se, 0);
9510 static void set_se_shares(struct sched_entity *se, unsigned long shares)
9512 struct cfs_rq *cfs_rq = se->cfs_rq;
9513 struct rq *rq = cfs_rq->rq;
9514 unsigned long flags;
9516 spin_lock_irqsave(&rq->lock, flags);
9517 __set_se_shares(se, shares);
9518 spin_unlock_irqrestore(&rq->lock, flags);
9521 static DEFINE_MUTEX(shares_mutex);
9523 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
9526 unsigned long flags;
9529 * We can't change the weight of the root cgroup.
9534 if (shares < MIN_SHARES)
9535 shares = MIN_SHARES;
9536 else if (shares > MAX_SHARES)
9537 shares = MAX_SHARES;
9539 mutex_lock(&shares_mutex);
9540 if (tg->shares == shares)
9543 spin_lock_irqsave(&task_group_lock, flags);
9544 for_each_possible_cpu(i)
9545 unregister_fair_sched_group(tg, i);
9546 list_del_rcu(&tg->siblings);
9547 spin_unlock_irqrestore(&task_group_lock, flags);
9549 /* wait for any ongoing reference to this group to finish */
9550 synchronize_sched();
9553 * Now we are free to modify the group's share on each cpu
9554 * w/o tripping rebalance_share or load_balance_fair.
9556 tg->shares = shares;
9557 for_each_possible_cpu(i) {
9561 cfs_rq_set_shares(tg->cfs_rq[i], 0);
9562 set_se_shares(tg->se[i], shares);
9566 * Enable load balance activity on this group, by inserting it back on
9567 * each cpu's rq->leaf_cfs_rq_list.
9569 spin_lock_irqsave(&task_group_lock, flags);
9570 for_each_possible_cpu(i)
9571 register_fair_sched_group(tg, i);
9572 list_add_rcu(&tg->siblings, &tg->parent->children);
9573 spin_unlock_irqrestore(&task_group_lock, flags);
9575 mutex_unlock(&shares_mutex);
9579 unsigned long sched_group_shares(struct task_group *tg)
9585 #ifdef CONFIG_RT_GROUP_SCHED
9587 * Ensure that the real time constraints are schedulable.
9589 static DEFINE_MUTEX(rt_constraints_mutex);
9591 static unsigned long to_ratio(u64 period, u64 runtime)
9593 if (runtime == RUNTIME_INF)
9596 return div64_u64(runtime << 20, period);
9599 /* Must be called with tasklist_lock held */
9600 static inline int tg_has_rt_tasks(struct task_group *tg)
9602 struct task_struct *g, *p;
9604 do_each_thread(g, p) {
9605 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
9607 } while_each_thread(g, p);
9612 struct rt_schedulable_data {
9613 struct task_group *tg;
9618 static int tg_schedulable(struct task_group *tg, void *data)
9620 struct rt_schedulable_data *d = data;
9621 struct task_group *child;
9622 unsigned long total, sum = 0;
9623 u64 period, runtime;
9625 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
9626 runtime = tg->rt_bandwidth.rt_runtime;
9629 period = d->rt_period;
9630 runtime = d->rt_runtime;
9633 #ifdef CONFIG_USER_SCHED
9634 if (tg == &root_task_group) {
9635 period = global_rt_period();
9636 runtime = global_rt_runtime();
9641 * Cannot have more runtime than the period.
9643 if (runtime > period && runtime != RUNTIME_INF)
9647 * Ensure we don't starve existing RT tasks.
9649 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
9652 total = to_ratio(period, runtime);
9655 * Nobody can have more than the global setting allows.
9657 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
9661 * The sum of our children's runtime should not exceed our own.
9663 list_for_each_entry_rcu(child, &tg->children, siblings) {
9664 period = ktime_to_ns(child->rt_bandwidth.rt_period);
9665 runtime = child->rt_bandwidth.rt_runtime;
9667 if (child == d->tg) {
9668 period = d->rt_period;
9669 runtime = d->rt_runtime;
9672 sum += to_ratio(period, runtime);
9681 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
9683 struct rt_schedulable_data data = {
9685 .rt_period = period,
9686 .rt_runtime = runtime,
9689 return walk_tg_tree(tg_schedulable, tg_nop, &data);
9692 static int tg_set_bandwidth(struct task_group *tg,
9693 u64 rt_period, u64 rt_runtime)
9697 mutex_lock(&rt_constraints_mutex);
9698 read_lock(&tasklist_lock);
9699 err = __rt_schedulable(tg, rt_period, rt_runtime);
9703 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
9704 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
9705 tg->rt_bandwidth.rt_runtime = rt_runtime;
9707 for_each_possible_cpu(i) {
9708 struct rt_rq *rt_rq = tg->rt_rq[i];
9710 spin_lock(&rt_rq->rt_runtime_lock);
9711 rt_rq->rt_runtime = rt_runtime;
9712 spin_unlock(&rt_rq->rt_runtime_lock);
9714 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
9716 read_unlock(&tasklist_lock);
9717 mutex_unlock(&rt_constraints_mutex);
9722 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
9724 u64 rt_runtime, rt_period;
9726 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
9727 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
9728 if (rt_runtime_us < 0)
9729 rt_runtime = RUNTIME_INF;
9731 return tg_set_bandwidth(tg, rt_period, rt_runtime);
9734 long sched_group_rt_runtime(struct task_group *tg)
9738 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
9741 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
9742 do_div(rt_runtime_us, NSEC_PER_USEC);
9743 return rt_runtime_us;
9746 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
9748 u64 rt_runtime, rt_period;
9750 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
9751 rt_runtime = tg->rt_bandwidth.rt_runtime;
9756 return tg_set_bandwidth(tg, rt_period, rt_runtime);
9759 long sched_group_rt_period(struct task_group *tg)
9763 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
9764 do_div(rt_period_us, NSEC_PER_USEC);
9765 return rt_period_us;
9768 static int sched_rt_global_constraints(void)
9770 u64 runtime, period;
9773 if (sysctl_sched_rt_period <= 0)
9776 runtime = global_rt_runtime();
9777 period = global_rt_period();
9780 * Sanity check on the sysctl variables.
9782 if (runtime > period && runtime != RUNTIME_INF)
9785 mutex_lock(&rt_constraints_mutex);
9786 read_lock(&tasklist_lock);
9787 ret = __rt_schedulable(NULL, 0, 0);
9788 read_unlock(&tasklist_lock);
9789 mutex_unlock(&rt_constraints_mutex);
9794 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
9796 /* Don't accept realtime tasks when there is no way for them to run */
9797 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
9803 #else /* !CONFIG_RT_GROUP_SCHED */
9804 static int sched_rt_global_constraints(void)
9806 unsigned long flags;
9809 if (sysctl_sched_rt_period <= 0)
9812 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9813 for_each_possible_cpu(i) {
9814 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9816 spin_lock(&rt_rq->rt_runtime_lock);
9817 rt_rq->rt_runtime = global_rt_runtime();
9818 spin_unlock(&rt_rq->rt_runtime_lock);
9820 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9824 #endif /* CONFIG_RT_GROUP_SCHED */
9826 int sched_rt_handler(struct ctl_table *table, int write,
9827 struct file *filp, void __user *buffer, size_t *lenp,
9831 int old_period, old_runtime;
9832 static DEFINE_MUTEX(mutex);
9835 old_period = sysctl_sched_rt_period;
9836 old_runtime = sysctl_sched_rt_runtime;
9838 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9840 if (!ret && write) {
9841 ret = sched_rt_global_constraints();
9843 sysctl_sched_rt_period = old_period;
9844 sysctl_sched_rt_runtime = old_runtime;
9846 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9847 def_rt_bandwidth.rt_period =
9848 ns_to_ktime(global_rt_period());
9851 mutex_unlock(&mutex);
9856 #ifdef CONFIG_CGROUP_SCHED
9858 /* return corresponding task_group object of a cgroup */
9859 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9861 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9862 struct task_group, css);
9865 static struct cgroup_subsys_state *
9866 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9868 struct task_group *tg, *parent;
9870 if (!cgrp->parent) {
9871 /* This is early initialization for the top cgroup */
9872 return &init_task_group.css;
9875 parent = cgroup_tg(cgrp->parent);
9876 tg = sched_create_group(parent);
9878 return ERR_PTR(-ENOMEM);
9884 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9886 struct task_group *tg = cgroup_tg(cgrp);
9888 sched_destroy_group(tg);
9892 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9893 struct task_struct *tsk)
9895 #ifdef CONFIG_RT_GROUP_SCHED
9896 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
9899 /* We don't support RT-tasks being in separate groups */
9900 if (tsk->sched_class != &fair_sched_class)
9908 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9909 struct cgroup *old_cont, struct task_struct *tsk)
9911 sched_move_task(tsk);
9914 #ifdef CONFIG_FAIR_GROUP_SCHED
9915 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9918 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9921 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9923 struct task_group *tg = cgroup_tg(cgrp);
9925 return (u64) tg->shares;
9927 #endif /* CONFIG_FAIR_GROUP_SCHED */
9929 #ifdef CONFIG_RT_GROUP_SCHED
9930 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9933 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9936 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9938 return sched_group_rt_runtime(cgroup_tg(cgrp));
9941 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9944 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9947 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9949 return sched_group_rt_period(cgroup_tg(cgrp));
9951 #endif /* CONFIG_RT_GROUP_SCHED */
9953 static struct cftype cpu_files[] = {
9954 #ifdef CONFIG_FAIR_GROUP_SCHED
9957 .read_u64 = cpu_shares_read_u64,
9958 .write_u64 = cpu_shares_write_u64,
9961 #ifdef CONFIG_RT_GROUP_SCHED
9963 .name = "rt_runtime_us",
9964 .read_s64 = cpu_rt_runtime_read,
9965 .write_s64 = cpu_rt_runtime_write,
9968 .name = "rt_period_us",
9969 .read_u64 = cpu_rt_period_read_uint,
9970 .write_u64 = cpu_rt_period_write_uint,
9975 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9977 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9980 struct cgroup_subsys cpu_cgroup_subsys = {
9982 .create = cpu_cgroup_create,
9983 .destroy = cpu_cgroup_destroy,
9984 .can_attach = cpu_cgroup_can_attach,
9985 .attach = cpu_cgroup_attach,
9986 .populate = cpu_cgroup_populate,
9987 .subsys_id = cpu_cgroup_subsys_id,
9991 #endif /* CONFIG_CGROUP_SCHED */
9993 #ifdef CONFIG_CGROUP_CPUACCT
9996 * CPU accounting code for task groups.
9998 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9999 * (balbir@in.ibm.com).
10002 /* track cpu usage of a group of tasks and its child groups */
10004 struct cgroup_subsys_state css;
10005 /* cpuusage holds pointer to a u64-type object on every cpu */
10007 struct cpuacct *parent;
10010 struct cgroup_subsys cpuacct_subsys;
10012 /* return cpu accounting group corresponding to this container */
10013 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
10015 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
10016 struct cpuacct, css);
10019 /* return cpu accounting group to which this task belongs */
10020 static inline struct cpuacct *task_ca(struct task_struct *tsk)
10022 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
10023 struct cpuacct, css);
10026 /* create a new cpu accounting group */
10027 static struct cgroup_subsys_state *cpuacct_create(
10028 struct cgroup_subsys *ss, struct cgroup *cgrp)
10030 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
10033 return ERR_PTR(-ENOMEM);
10035 ca->cpuusage = alloc_percpu(u64);
10036 if (!ca->cpuusage) {
10038 return ERR_PTR(-ENOMEM);
10042 ca->parent = cgroup_ca(cgrp->parent);
10047 /* destroy an existing cpu accounting group */
10049 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10051 struct cpuacct *ca = cgroup_ca(cgrp);
10053 free_percpu(ca->cpuusage);
10057 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
10059 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10062 #ifndef CONFIG_64BIT
10064 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
10066 spin_lock_irq(&cpu_rq(cpu)->lock);
10068 spin_unlock_irq(&cpu_rq(cpu)->lock);
10076 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
10078 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10080 #ifndef CONFIG_64BIT
10082 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
10084 spin_lock_irq(&cpu_rq(cpu)->lock);
10086 spin_unlock_irq(&cpu_rq(cpu)->lock);
10092 /* return total cpu usage (in nanoseconds) of a group */
10093 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
10095 struct cpuacct *ca = cgroup_ca(cgrp);
10096 u64 totalcpuusage = 0;
10099 for_each_present_cpu(i)
10100 totalcpuusage += cpuacct_cpuusage_read(ca, i);
10102 return totalcpuusage;
10105 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
10108 struct cpuacct *ca = cgroup_ca(cgrp);
10117 for_each_present_cpu(i)
10118 cpuacct_cpuusage_write(ca, i, 0);
10124 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
10125 struct seq_file *m)
10127 struct cpuacct *ca = cgroup_ca(cgroup);
10131 for_each_present_cpu(i) {
10132 percpu = cpuacct_cpuusage_read(ca, i);
10133 seq_printf(m, "%llu ", (unsigned long long) percpu);
10135 seq_printf(m, "\n");
10139 static struct cftype files[] = {
10142 .read_u64 = cpuusage_read,
10143 .write_u64 = cpuusage_write,
10146 .name = "usage_percpu",
10147 .read_seq_string = cpuacct_percpu_seq_read,
10152 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
10154 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
10158 * charge this task's execution time to its accounting group.
10160 * called with rq->lock held.
10162 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
10164 struct cpuacct *ca;
10167 if (unlikely(!cpuacct_subsys.active))
10170 cpu = task_cpu(tsk);
10173 for (; ca; ca = ca->parent) {
10174 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10175 *cpuusage += cputime;
10179 struct cgroup_subsys cpuacct_subsys = {
10181 .create = cpuacct_create,
10182 .destroy = cpuacct_destroy,
10183 .populate = cpuacct_populate,
10184 .subsys_id = cpuacct_subsys_id,
10186 #endif /* CONFIG_CGROUP_CPUACCT */