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 task_rq_unlock_wait(struct task_struct *p)
1002 struct rq *rq = task_rq(p);
1004 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
1005 spin_unlock_wait(&rq->lock);
1008 static void __task_rq_unlock(struct rq *rq)
1009 __releases(rq->lock)
1011 spin_unlock(&rq->lock);
1014 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1015 __releases(rq->lock)
1017 spin_unlock_irqrestore(&rq->lock, *flags);
1021 * this_rq_lock - lock this runqueue and disable interrupts.
1023 static struct rq *this_rq_lock(void)
1024 __acquires(rq->lock)
1028 local_irq_disable();
1030 spin_lock(&rq->lock);
1035 #ifdef CONFIG_SCHED_HRTICK
1037 * Use HR-timers to deliver accurate preemption points.
1039 * Its all a bit involved since we cannot program an hrt while holding the
1040 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1043 * When we get rescheduled we reprogram the hrtick_timer outside of the
1049 * - enabled by features
1050 * - hrtimer is actually high res
1052 static inline int hrtick_enabled(struct rq *rq)
1054 if (!sched_feat(HRTICK))
1056 if (!cpu_active(cpu_of(rq)))
1058 return hrtimer_is_hres_active(&rq->hrtick_timer);
1061 static void hrtick_clear(struct rq *rq)
1063 if (hrtimer_active(&rq->hrtick_timer))
1064 hrtimer_cancel(&rq->hrtick_timer);
1068 * High-resolution timer tick.
1069 * Runs from hardirq context with interrupts disabled.
1071 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1073 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1075 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1077 spin_lock(&rq->lock);
1078 update_rq_clock(rq);
1079 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1080 spin_unlock(&rq->lock);
1082 return HRTIMER_NORESTART;
1087 * called from hardirq (IPI) context
1089 static void __hrtick_start(void *arg)
1091 struct rq *rq = arg;
1093 spin_lock(&rq->lock);
1094 hrtimer_restart(&rq->hrtick_timer);
1095 rq->hrtick_csd_pending = 0;
1096 spin_unlock(&rq->lock);
1100 * Called to set the hrtick timer state.
1102 * called with rq->lock held and irqs disabled
1104 static void hrtick_start(struct rq *rq, u64 delay)
1106 struct hrtimer *timer = &rq->hrtick_timer;
1107 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1109 hrtimer_set_expires(timer, time);
1111 if (rq == this_rq()) {
1112 hrtimer_restart(timer);
1113 } else if (!rq->hrtick_csd_pending) {
1114 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1115 rq->hrtick_csd_pending = 1;
1120 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1122 int cpu = (int)(long)hcpu;
1125 case CPU_UP_CANCELED:
1126 case CPU_UP_CANCELED_FROZEN:
1127 case CPU_DOWN_PREPARE:
1128 case CPU_DOWN_PREPARE_FROZEN:
1130 case CPU_DEAD_FROZEN:
1131 hrtick_clear(cpu_rq(cpu));
1138 static __init void init_hrtick(void)
1140 hotcpu_notifier(hotplug_hrtick, 0);
1144 * Called to set the hrtick timer state.
1146 * called with rq->lock held and irqs disabled
1148 static void hrtick_start(struct rq *rq, u64 delay)
1150 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay), HRTIMER_MODE_REL);
1153 static inline void init_hrtick(void)
1156 #endif /* CONFIG_SMP */
1158 static void init_rq_hrtick(struct rq *rq)
1161 rq->hrtick_csd_pending = 0;
1163 rq->hrtick_csd.flags = 0;
1164 rq->hrtick_csd.func = __hrtick_start;
1165 rq->hrtick_csd.info = rq;
1168 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1169 rq->hrtick_timer.function = hrtick;
1171 #else /* CONFIG_SCHED_HRTICK */
1172 static inline void hrtick_clear(struct rq *rq)
1176 static inline void init_rq_hrtick(struct rq *rq)
1180 static inline void init_hrtick(void)
1183 #endif /* CONFIG_SCHED_HRTICK */
1186 * resched_task - mark a task 'to be rescheduled now'.
1188 * On UP this means the setting of the need_resched flag, on SMP it
1189 * might also involve a cross-CPU call to trigger the scheduler on
1194 #ifndef tsk_is_polling
1195 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1198 static void resched_task(struct task_struct *p)
1202 assert_spin_locked(&task_rq(p)->lock);
1204 if (test_tsk_need_resched(p))
1207 set_tsk_need_resched(p);
1210 if (cpu == smp_processor_id())
1213 /* NEED_RESCHED must be visible before we test polling */
1215 if (!tsk_is_polling(p))
1216 smp_send_reschedule(cpu);
1219 static void resched_cpu(int cpu)
1221 struct rq *rq = cpu_rq(cpu);
1222 unsigned long flags;
1224 if (!spin_trylock_irqsave(&rq->lock, flags))
1226 resched_task(cpu_curr(cpu));
1227 spin_unlock_irqrestore(&rq->lock, flags);
1232 * When add_timer_on() enqueues a timer into the timer wheel of an
1233 * idle CPU then this timer might expire before the next timer event
1234 * which is scheduled to wake up that CPU. In case of a completely
1235 * idle system the next event might even be infinite time into the
1236 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1237 * leaves the inner idle loop so the newly added timer is taken into
1238 * account when the CPU goes back to idle and evaluates the timer
1239 * wheel for the next timer event.
1241 void wake_up_idle_cpu(int cpu)
1243 struct rq *rq = cpu_rq(cpu);
1245 if (cpu == smp_processor_id())
1249 * This is safe, as this function is called with the timer
1250 * wheel base lock of (cpu) held. When the CPU is on the way
1251 * to idle and has not yet set rq->curr to idle then it will
1252 * be serialized on the timer wheel base lock and take the new
1253 * timer into account automatically.
1255 if (rq->curr != rq->idle)
1259 * We can set TIF_RESCHED on the idle task of the other CPU
1260 * lockless. The worst case is that the other CPU runs the
1261 * idle task through an additional NOOP schedule()
1263 set_tsk_need_resched(rq->idle);
1265 /* NEED_RESCHED must be visible before we test polling */
1267 if (!tsk_is_polling(rq->idle))
1268 smp_send_reschedule(cpu);
1270 #endif /* CONFIG_NO_HZ */
1272 #else /* !CONFIG_SMP */
1273 static void resched_task(struct task_struct *p)
1275 assert_spin_locked(&task_rq(p)->lock);
1276 set_tsk_need_resched(p);
1278 #endif /* CONFIG_SMP */
1280 #if BITS_PER_LONG == 32
1281 # define WMULT_CONST (~0UL)
1283 # define WMULT_CONST (1UL << 32)
1286 #define WMULT_SHIFT 32
1289 * Shift right and round:
1291 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1294 * delta *= weight / lw
1296 static unsigned long
1297 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1298 struct load_weight *lw)
1302 if (!lw->inv_weight) {
1303 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1306 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1310 tmp = (u64)delta_exec * weight;
1312 * Check whether we'd overflow the 64-bit multiplication:
1314 if (unlikely(tmp > WMULT_CONST))
1315 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1318 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1320 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1323 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1329 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1336 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1337 * of tasks with abnormal "nice" values across CPUs the contribution that
1338 * each task makes to its run queue's load is weighted according to its
1339 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1340 * scaled version of the new time slice allocation that they receive on time
1344 #define WEIGHT_IDLEPRIO 3
1345 #define WMULT_IDLEPRIO 1431655765
1348 * Nice levels are multiplicative, with a gentle 10% change for every
1349 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1350 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1351 * that remained on nice 0.
1353 * The "10% effect" is relative and cumulative: from _any_ nice level,
1354 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1355 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1356 * If a task goes up by ~10% and another task goes down by ~10% then
1357 * the relative distance between them is ~25%.)
1359 static const int prio_to_weight[40] = {
1360 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1361 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1362 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1363 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1364 /* 0 */ 1024, 820, 655, 526, 423,
1365 /* 5 */ 335, 272, 215, 172, 137,
1366 /* 10 */ 110, 87, 70, 56, 45,
1367 /* 15 */ 36, 29, 23, 18, 15,
1371 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1373 * In cases where the weight does not change often, we can use the
1374 * precalculated inverse to speed up arithmetics by turning divisions
1375 * into multiplications:
1377 static const u32 prio_to_wmult[40] = {
1378 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1379 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1380 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1381 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1382 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1383 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1384 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1385 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1388 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1391 * runqueue iterator, to support SMP load-balancing between different
1392 * scheduling classes, without having to expose their internal data
1393 * structures to the load-balancing proper:
1395 struct rq_iterator {
1397 struct task_struct *(*start)(void *);
1398 struct task_struct *(*next)(void *);
1402 static unsigned long
1403 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1404 unsigned long max_load_move, struct sched_domain *sd,
1405 enum cpu_idle_type idle, int *all_pinned,
1406 int *this_best_prio, struct rq_iterator *iterator);
1409 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1410 struct sched_domain *sd, enum cpu_idle_type idle,
1411 struct rq_iterator *iterator);
1414 #ifdef CONFIG_CGROUP_CPUACCT
1415 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1417 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1420 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1422 update_load_add(&rq->load, load);
1425 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1427 update_load_sub(&rq->load, load);
1430 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1431 typedef int (*tg_visitor)(struct task_group *, void *);
1434 * Iterate the full tree, calling @down when first entering a node and @up when
1435 * leaving it for the final time.
1437 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1439 struct task_group *parent, *child;
1443 parent = &root_task_group;
1445 ret = (*down)(parent, data);
1448 list_for_each_entry_rcu(child, &parent->children, siblings) {
1455 ret = (*up)(parent, data);
1460 parent = parent->parent;
1469 static int tg_nop(struct task_group *tg, void *data)
1476 static unsigned long source_load(int cpu, int type);
1477 static unsigned long target_load(int cpu, int type);
1478 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1480 static unsigned long cpu_avg_load_per_task(int cpu)
1482 struct rq *rq = cpu_rq(cpu);
1483 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1486 rq->avg_load_per_task = rq->load.weight / nr_running;
1488 rq->avg_load_per_task = 0;
1490 return rq->avg_load_per_task;
1493 #ifdef CONFIG_FAIR_GROUP_SCHED
1495 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1498 * Calculate and set the cpu's group shares.
1501 update_group_shares_cpu(struct task_group *tg, int cpu,
1502 unsigned long sd_shares, unsigned long sd_rq_weight)
1504 unsigned long shares;
1505 unsigned long rq_weight;
1510 rq_weight = tg->cfs_rq[cpu]->rq_weight;
1513 * \Sum shares * rq_weight
1514 * shares = -----------------------
1518 shares = (sd_shares * rq_weight) / sd_rq_weight;
1519 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1521 if (abs(shares - tg->se[cpu]->load.weight) >
1522 sysctl_sched_shares_thresh) {
1523 struct rq *rq = cpu_rq(cpu);
1524 unsigned long flags;
1526 spin_lock_irqsave(&rq->lock, flags);
1527 tg->cfs_rq[cpu]->shares = shares;
1529 __set_se_shares(tg->se[cpu], shares);
1530 spin_unlock_irqrestore(&rq->lock, flags);
1535 * Re-compute the task group their per cpu shares over the given domain.
1536 * This needs to be done in a bottom-up fashion because the rq weight of a
1537 * parent group depends on the shares of its child groups.
1539 static int tg_shares_up(struct task_group *tg, void *data)
1541 unsigned long weight, rq_weight = 0;
1542 unsigned long shares = 0;
1543 struct sched_domain *sd = data;
1546 for_each_cpu(i, sched_domain_span(sd)) {
1548 * If there are currently no tasks on the cpu pretend there
1549 * is one of average load so that when a new task gets to
1550 * run here it will not get delayed by group starvation.
1552 weight = tg->cfs_rq[i]->load.weight;
1554 weight = NICE_0_LOAD;
1556 tg->cfs_rq[i]->rq_weight = weight;
1557 rq_weight += weight;
1558 shares += tg->cfs_rq[i]->shares;
1561 if ((!shares && rq_weight) || shares > tg->shares)
1562 shares = tg->shares;
1564 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1565 shares = tg->shares;
1567 for_each_cpu(i, sched_domain_span(sd))
1568 update_group_shares_cpu(tg, i, shares, rq_weight);
1574 * Compute the cpu's hierarchical load factor for each task group.
1575 * This needs to be done in a top-down fashion because the load of a child
1576 * group is a fraction of its parents load.
1578 static int tg_load_down(struct task_group *tg, void *data)
1581 long cpu = (long)data;
1584 load = cpu_rq(cpu)->load.weight;
1586 load = tg->parent->cfs_rq[cpu]->h_load;
1587 load *= tg->cfs_rq[cpu]->shares;
1588 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1591 tg->cfs_rq[cpu]->h_load = load;
1596 static void update_shares(struct sched_domain *sd)
1598 u64 now = cpu_clock(raw_smp_processor_id());
1599 s64 elapsed = now - sd->last_update;
1601 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1602 sd->last_update = now;
1603 walk_tg_tree(tg_nop, tg_shares_up, sd);
1607 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1609 spin_unlock(&rq->lock);
1611 spin_lock(&rq->lock);
1614 static void update_h_load(long cpu)
1616 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1621 static inline void update_shares(struct sched_domain *sd)
1625 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1631 #ifdef CONFIG_PREEMPT
1634 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1635 * way at the expense of forcing extra atomic operations in all
1636 * invocations. This assures that the double_lock is acquired using the
1637 * same underlying policy as the spinlock_t on this architecture, which
1638 * reduces latency compared to the unfair variant below. However, it
1639 * also adds more overhead and therefore may reduce throughput.
1641 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1642 __releases(this_rq->lock)
1643 __acquires(busiest->lock)
1644 __acquires(this_rq->lock)
1646 spin_unlock(&this_rq->lock);
1647 double_rq_lock(this_rq, busiest);
1654 * Unfair double_lock_balance: Optimizes throughput at the expense of
1655 * latency by eliminating extra atomic operations when the locks are
1656 * already in proper order on entry. This favors lower cpu-ids and will
1657 * grant the double lock to lower cpus over higher ids under contention,
1658 * regardless of entry order into the function.
1660 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1661 __releases(this_rq->lock)
1662 __acquires(busiest->lock)
1663 __acquires(this_rq->lock)
1667 if (unlikely(!spin_trylock(&busiest->lock))) {
1668 if (busiest < this_rq) {
1669 spin_unlock(&this_rq->lock);
1670 spin_lock(&busiest->lock);
1671 spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING);
1674 spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING);
1679 #endif /* CONFIG_PREEMPT */
1682 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1684 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1686 if (unlikely(!irqs_disabled())) {
1687 /* printk() doesn't work good under rq->lock */
1688 spin_unlock(&this_rq->lock);
1692 return _double_lock_balance(this_rq, busiest);
1695 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1696 __releases(busiest->lock)
1698 spin_unlock(&busiest->lock);
1699 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1703 #ifdef CONFIG_FAIR_GROUP_SCHED
1704 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1707 cfs_rq->shares = shares;
1712 #include "sched_stats.h"
1713 #include "sched_idletask.c"
1714 #include "sched_fair.c"
1715 #include "sched_rt.c"
1716 #ifdef CONFIG_SCHED_DEBUG
1717 # include "sched_debug.c"
1720 #define sched_class_highest (&rt_sched_class)
1721 #define for_each_class(class) \
1722 for (class = sched_class_highest; class; class = class->next)
1724 static void inc_nr_running(struct rq *rq)
1729 static void dec_nr_running(struct rq *rq)
1734 static void set_load_weight(struct task_struct *p)
1736 if (task_has_rt_policy(p)) {
1737 p->se.load.weight = prio_to_weight[0] * 2;
1738 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1743 * SCHED_IDLE tasks get minimal weight:
1745 if (p->policy == SCHED_IDLE) {
1746 p->se.load.weight = WEIGHT_IDLEPRIO;
1747 p->se.load.inv_weight = WMULT_IDLEPRIO;
1751 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1752 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1755 static void update_avg(u64 *avg, u64 sample)
1757 s64 diff = sample - *avg;
1761 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1764 p->se.start_runtime = p->se.sum_exec_runtime;
1766 sched_info_queued(p);
1767 p->sched_class->enqueue_task(rq, p, wakeup);
1771 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1774 if (p->se.last_wakeup) {
1775 update_avg(&p->se.avg_overlap,
1776 p->se.sum_exec_runtime - p->se.last_wakeup);
1777 p->se.last_wakeup = 0;
1779 update_avg(&p->se.avg_wakeup,
1780 sysctl_sched_wakeup_granularity);
1784 sched_info_dequeued(p);
1785 p->sched_class->dequeue_task(rq, p, sleep);
1790 * __normal_prio - return the priority that is based on the static prio
1792 static inline int __normal_prio(struct task_struct *p)
1794 return p->static_prio;
1798 * Calculate the expected normal priority: i.e. priority
1799 * without taking RT-inheritance into account. Might be
1800 * boosted by interactivity modifiers. Changes upon fork,
1801 * setprio syscalls, and whenever the interactivity
1802 * estimator recalculates.
1804 static inline int normal_prio(struct task_struct *p)
1808 if (task_has_rt_policy(p))
1809 prio = MAX_RT_PRIO-1 - p->rt_priority;
1811 prio = __normal_prio(p);
1816 * Calculate the current priority, i.e. the priority
1817 * taken into account by the scheduler. This value might
1818 * be boosted by RT tasks, or might be boosted by
1819 * interactivity modifiers. Will be RT if the task got
1820 * RT-boosted. If not then it returns p->normal_prio.
1822 static int effective_prio(struct task_struct *p)
1824 p->normal_prio = normal_prio(p);
1826 * If we are RT tasks or we were boosted to RT priority,
1827 * keep the priority unchanged. Otherwise, update priority
1828 * to the normal priority:
1830 if (!rt_prio(p->prio))
1831 return p->normal_prio;
1836 * activate_task - move a task to the runqueue.
1838 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1840 if (task_contributes_to_load(p))
1841 rq->nr_uninterruptible--;
1843 enqueue_task(rq, p, wakeup);
1848 * deactivate_task - remove a task from the runqueue.
1850 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1852 if (task_contributes_to_load(p))
1853 rq->nr_uninterruptible++;
1855 dequeue_task(rq, p, sleep);
1860 * task_curr - is this task currently executing on a CPU?
1861 * @p: the task in question.
1863 inline int task_curr(const struct task_struct *p)
1865 return cpu_curr(task_cpu(p)) == p;
1868 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1870 set_task_rq(p, cpu);
1873 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1874 * successfuly executed on another CPU. We must ensure that updates of
1875 * per-task data have been completed by this moment.
1878 task_thread_info(p)->cpu = cpu;
1882 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1883 const struct sched_class *prev_class,
1884 int oldprio, int running)
1886 if (prev_class != p->sched_class) {
1887 if (prev_class->switched_from)
1888 prev_class->switched_from(rq, p, running);
1889 p->sched_class->switched_to(rq, p, running);
1891 p->sched_class->prio_changed(rq, p, oldprio, running);
1896 /* Used instead of source_load when we know the type == 0 */
1897 static unsigned long weighted_cpuload(const int cpu)
1899 return cpu_rq(cpu)->load.weight;
1903 * Is this task likely cache-hot:
1906 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1911 * Buddy candidates are cache hot:
1913 if (sched_feat(CACHE_HOT_BUDDY) &&
1914 (&p->se == cfs_rq_of(&p->se)->next ||
1915 &p->se == cfs_rq_of(&p->se)->last))
1918 if (p->sched_class != &fair_sched_class)
1921 if (sysctl_sched_migration_cost == -1)
1923 if (sysctl_sched_migration_cost == 0)
1926 delta = now - p->se.exec_start;
1928 return delta < (s64)sysctl_sched_migration_cost;
1932 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1934 int old_cpu = task_cpu(p);
1935 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1936 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1937 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1940 clock_offset = old_rq->clock - new_rq->clock;
1942 trace_sched_migrate_task(p, task_cpu(p), new_cpu);
1944 #ifdef CONFIG_SCHEDSTATS
1945 if (p->se.wait_start)
1946 p->se.wait_start -= clock_offset;
1947 if (p->se.sleep_start)
1948 p->se.sleep_start -= clock_offset;
1949 if (p->se.block_start)
1950 p->se.block_start -= clock_offset;
1952 if (old_cpu != new_cpu) {
1953 p->se.nr_migrations++;
1954 new_rq->nr_migrations_in++;
1955 #ifdef CONFIG_SCHEDSTATS
1956 if (task_hot(p, old_rq->clock, NULL))
1957 schedstat_inc(p, se.nr_forced2_migrations);
1960 p->se.vruntime -= old_cfsrq->min_vruntime -
1961 new_cfsrq->min_vruntime;
1963 __set_task_cpu(p, new_cpu);
1966 struct migration_req {
1967 struct list_head list;
1969 struct task_struct *task;
1972 struct completion done;
1976 * The task's runqueue lock must be held.
1977 * Returns true if you have to wait for migration thread.
1980 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1982 struct rq *rq = task_rq(p);
1985 * If the task is not on a runqueue (and not running), then
1986 * it is sufficient to simply update the task's cpu field.
1988 if (!p->se.on_rq && !task_running(rq, p)) {
1989 set_task_cpu(p, dest_cpu);
1993 init_completion(&req->done);
1995 req->dest_cpu = dest_cpu;
1996 list_add(&req->list, &rq->migration_queue);
2002 * wait_task_inactive - wait for a thread to unschedule.
2004 * If @match_state is nonzero, it's the @p->state value just checked and
2005 * not expected to change. If it changes, i.e. @p might have woken up,
2006 * then return zero. When we succeed in waiting for @p to be off its CPU,
2007 * we return a positive number (its total switch count). If a second call
2008 * a short while later returns the same number, the caller can be sure that
2009 * @p has remained unscheduled the whole time.
2011 * The caller must ensure that the task *will* unschedule sometime soon,
2012 * else this function might spin for a *long* time. This function can't
2013 * be called with interrupts off, or it may introduce deadlock with
2014 * smp_call_function() if an IPI is sent by the same process we are
2015 * waiting to become inactive.
2017 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2019 unsigned long flags;
2026 * We do the initial early heuristics without holding
2027 * any task-queue locks at all. We'll only try to get
2028 * the runqueue lock when things look like they will
2034 * If the task is actively running on another CPU
2035 * still, just relax and busy-wait without holding
2038 * NOTE! Since we don't hold any locks, it's not
2039 * even sure that "rq" stays as the right runqueue!
2040 * But we don't care, since "task_running()" will
2041 * return false if the runqueue has changed and p
2042 * is actually now running somewhere else!
2044 while (task_running(rq, p)) {
2045 if (match_state && unlikely(p->state != match_state))
2051 * Ok, time to look more closely! We need the rq
2052 * lock now, to be *sure*. If we're wrong, we'll
2053 * just go back and repeat.
2055 rq = task_rq_lock(p, &flags);
2056 trace_sched_wait_task(rq, p);
2057 running = task_running(rq, p);
2058 on_rq = p->se.on_rq;
2060 if (!match_state || p->state == match_state)
2061 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2062 task_rq_unlock(rq, &flags);
2065 * If it changed from the expected state, bail out now.
2067 if (unlikely(!ncsw))
2071 * Was it really running after all now that we
2072 * checked with the proper locks actually held?
2074 * Oops. Go back and try again..
2076 if (unlikely(running)) {
2082 * It's not enough that it's not actively running,
2083 * it must be off the runqueue _entirely_, and not
2086 * So if it was still runnable (but just not actively
2087 * running right now), it's preempted, and we should
2088 * yield - it could be a while.
2090 if (unlikely(on_rq)) {
2091 schedule_timeout_uninterruptible(1);
2096 * Ahh, all good. It wasn't running, and it wasn't
2097 * runnable, which means that it will never become
2098 * running in the future either. We're all done!
2107 * kick_process - kick a running thread to enter/exit the kernel
2108 * @p: the to-be-kicked thread
2110 * Cause a process which is running on another CPU to enter
2111 * kernel-mode, without any delay. (to get signals handled.)
2113 * NOTE: this function doesnt have to take the runqueue lock,
2114 * because all it wants to ensure is that the remote task enters
2115 * the kernel. If the IPI races and the task has been migrated
2116 * to another CPU then no harm is done and the purpose has been
2119 void kick_process(struct task_struct *p)
2125 if ((cpu != smp_processor_id()) && task_curr(p))
2126 smp_send_reschedule(cpu);
2131 * Return a low guess at the load of a migration-source cpu weighted
2132 * according to the scheduling class and "nice" value.
2134 * We want to under-estimate the load of migration sources, to
2135 * balance conservatively.
2137 static unsigned long source_load(int cpu, int type)
2139 struct rq *rq = cpu_rq(cpu);
2140 unsigned long total = weighted_cpuload(cpu);
2142 if (type == 0 || !sched_feat(LB_BIAS))
2145 return min(rq->cpu_load[type-1], total);
2149 * Return a high guess at the load of a migration-target cpu weighted
2150 * according to the scheduling class and "nice" value.
2152 static unsigned long target_load(int cpu, int type)
2154 struct rq *rq = cpu_rq(cpu);
2155 unsigned long total = weighted_cpuload(cpu);
2157 if (type == 0 || !sched_feat(LB_BIAS))
2160 return max(rq->cpu_load[type-1], total);
2164 * find_idlest_group finds and returns the least busy CPU group within the
2167 static struct sched_group *
2168 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2170 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2171 unsigned long min_load = ULONG_MAX, this_load = 0;
2172 int load_idx = sd->forkexec_idx;
2173 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2176 unsigned long load, avg_load;
2180 /* Skip over this group if it has no CPUs allowed */
2181 if (!cpumask_intersects(sched_group_cpus(group),
2185 local_group = cpumask_test_cpu(this_cpu,
2186 sched_group_cpus(group));
2188 /* Tally up the load of all CPUs in the group */
2191 for_each_cpu(i, sched_group_cpus(group)) {
2192 /* Bias balancing toward cpus of our domain */
2194 load = source_load(i, load_idx);
2196 load = target_load(i, load_idx);
2201 /* Adjust by relative CPU power of the group */
2202 avg_load = sg_div_cpu_power(group,
2203 avg_load * SCHED_LOAD_SCALE);
2206 this_load = avg_load;
2208 } else if (avg_load < min_load) {
2209 min_load = avg_load;
2212 } while (group = group->next, group != sd->groups);
2214 if (!idlest || 100*this_load < imbalance*min_load)
2220 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2223 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
2225 unsigned long load, min_load = ULONG_MAX;
2229 /* Traverse only the allowed CPUs */
2230 for_each_cpu_and(i, sched_group_cpus(group), &p->cpus_allowed) {
2231 load = weighted_cpuload(i);
2233 if (load < min_load || (load == min_load && i == this_cpu)) {
2243 * sched_balance_self: balance the current task (running on cpu) in domains
2244 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2247 * Balance, ie. select the least loaded group.
2249 * Returns the target CPU number, or the same CPU if no balancing is needed.
2251 * preempt must be disabled.
2253 static int sched_balance_self(int cpu, int flag)
2255 struct task_struct *t = current;
2256 struct sched_domain *tmp, *sd = NULL;
2258 for_each_domain(cpu, tmp) {
2260 * If power savings logic is enabled for a domain, stop there.
2262 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2264 if (tmp->flags & flag)
2272 struct sched_group *group;
2273 int new_cpu, weight;
2275 if (!(sd->flags & flag)) {
2280 group = find_idlest_group(sd, t, cpu);
2286 new_cpu = find_idlest_cpu(group, t, cpu);
2287 if (new_cpu == -1 || new_cpu == cpu) {
2288 /* Now try balancing at a lower domain level of cpu */
2293 /* Now try balancing at a lower domain level of new_cpu */
2295 weight = cpumask_weight(sched_domain_span(sd));
2297 for_each_domain(cpu, tmp) {
2298 if (weight <= cpumask_weight(sched_domain_span(tmp)))
2300 if (tmp->flags & flag)
2303 /* while loop will break here if sd == NULL */
2309 #endif /* CONFIG_SMP */
2312 * task_oncpu_function_call - call a function on the cpu on which a task runs
2313 * @p: the task to evaluate
2314 * @func: the function to be called
2315 * @info: the function call argument
2317 * Calls the function @func when the task is currently running. This might
2318 * be on the current CPU, which just calls the function directly
2320 void task_oncpu_function_call(struct task_struct *p,
2321 void (*func) (void *info), void *info)
2328 smp_call_function_single(cpu, func, info, 1);
2333 * try_to_wake_up - wake up a thread
2334 * @p: the to-be-woken-up thread
2335 * @state: the mask of task states that can be woken
2336 * @sync: do a synchronous wakeup?
2338 * Put it on the run-queue if it's not already there. The "current"
2339 * thread is always on the run-queue (except when the actual
2340 * re-schedule is in progress), and as such you're allowed to do
2341 * the simpler "current->state = TASK_RUNNING" to mark yourself
2342 * runnable without the overhead of this.
2344 * returns failure only if the task is already active.
2346 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2348 int cpu, orig_cpu, this_cpu, success = 0;
2349 unsigned long flags;
2353 if (!sched_feat(SYNC_WAKEUPS))
2357 if (sched_feat(LB_WAKEUP_UPDATE) && !root_task_group_empty()) {
2358 struct sched_domain *sd;
2360 this_cpu = raw_smp_processor_id();
2363 for_each_domain(this_cpu, sd) {
2364 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2373 rq = task_rq_lock(p, &flags);
2374 update_rq_clock(rq);
2375 old_state = p->state;
2376 if (!(old_state & state))
2384 this_cpu = smp_processor_id();
2387 if (unlikely(task_running(rq, p)))
2390 cpu = p->sched_class->select_task_rq(p, sync);
2391 if (cpu != orig_cpu) {
2392 set_task_cpu(p, cpu);
2393 task_rq_unlock(rq, &flags);
2394 /* might preempt at this point */
2395 rq = task_rq_lock(p, &flags);
2396 old_state = p->state;
2397 if (!(old_state & state))
2402 this_cpu = smp_processor_id();
2406 #ifdef CONFIG_SCHEDSTATS
2407 schedstat_inc(rq, ttwu_count);
2408 if (cpu == this_cpu)
2409 schedstat_inc(rq, ttwu_local);
2411 struct sched_domain *sd;
2412 for_each_domain(this_cpu, sd) {
2413 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2414 schedstat_inc(sd, ttwu_wake_remote);
2419 #endif /* CONFIG_SCHEDSTATS */
2422 #endif /* CONFIG_SMP */
2423 schedstat_inc(p, se.nr_wakeups);
2425 schedstat_inc(p, se.nr_wakeups_sync);
2426 if (orig_cpu != cpu)
2427 schedstat_inc(p, se.nr_wakeups_migrate);
2428 if (cpu == this_cpu)
2429 schedstat_inc(p, se.nr_wakeups_local);
2431 schedstat_inc(p, se.nr_wakeups_remote);
2432 activate_task(rq, p, 1);
2436 * Only attribute actual wakeups done by this task.
2438 if (!in_interrupt()) {
2439 struct sched_entity *se = ¤t->se;
2440 u64 sample = se->sum_exec_runtime;
2442 if (se->last_wakeup)
2443 sample -= se->last_wakeup;
2445 sample -= se->start_runtime;
2446 update_avg(&se->avg_wakeup, sample);
2448 se->last_wakeup = se->sum_exec_runtime;
2452 trace_sched_wakeup(rq, p, success);
2453 check_preempt_curr(rq, p, sync);
2455 p->state = TASK_RUNNING;
2457 if (p->sched_class->task_wake_up)
2458 p->sched_class->task_wake_up(rq, p);
2461 task_rq_unlock(rq, &flags);
2466 int wake_up_process(struct task_struct *p)
2468 return try_to_wake_up(p, TASK_ALL, 0);
2470 EXPORT_SYMBOL(wake_up_process);
2472 int wake_up_state(struct task_struct *p, unsigned int state)
2474 return try_to_wake_up(p, state, 0);
2478 * Perform scheduler related setup for a newly forked process p.
2479 * p is forked by current.
2481 * __sched_fork() is basic setup used by init_idle() too:
2483 static void __sched_fork(struct task_struct *p)
2485 p->se.exec_start = 0;
2486 p->se.sum_exec_runtime = 0;
2487 p->se.prev_sum_exec_runtime = 0;
2488 p->se.nr_migrations = 0;
2489 p->se.last_wakeup = 0;
2490 p->se.avg_overlap = 0;
2491 p->se.start_runtime = 0;
2492 p->se.avg_wakeup = sysctl_sched_wakeup_granularity;
2494 #ifdef CONFIG_SCHEDSTATS
2495 p->se.wait_start = 0;
2496 p->se.sum_sleep_runtime = 0;
2497 p->se.sleep_start = 0;
2498 p->se.block_start = 0;
2499 p->se.sleep_max = 0;
2500 p->se.block_max = 0;
2502 p->se.slice_max = 0;
2506 INIT_LIST_HEAD(&p->rt.run_list);
2508 INIT_LIST_HEAD(&p->se.group_node);
2510 #ifdef CONFIG_PREEMPT_NOTIFIERS
2511 INIT_HLIST_HEAD(&p->preempt_notifiers);
2515 * We mark the process as running here, but have not actually
2516 * inserted it onto the runqueue yet. This guarantees that
2517 * nobody will actually run it, and a signal or other external
2518 * event cannot wake it up and insert it on the runqueue either.
2520 p->state = TASK_RUNNING;
2524 * fork()/clone()-time setup:
2526 void sched_fork(struct task_struct *p, int clone_flags)
2528 int cpu = get_cpu();
2533 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2535 set_task_cpu(p, cpu);
2538 * Make sure we do not leak PI boosting priority to the child:
2540 p->prio = current->normal_prio;
2541 if (!rt_prio(p->prio))
2542 p->sched_class = &fair_sched_class;
2544 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2545 if (likely(sched_info_on()))
2546 memset(&p->sched_info, 0, sizeof(p->sched_info));
2548 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2551 #ifdef CONFIG_PREEMPT
2552 /* Want to start with kernel preemption disabled. */
2553 task_thread_info(p)->preempt_count = 1;
2555 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2561 * wake_up_new_task - wake up a newly created task for the first time.
2563 * This function will do some initial scheduler statistics housekeeping
2564 * that must be done for every newly created context, then puts the task
2565 * on the runqueue and wakes it.
2567 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2569 unsigned long flags;
2572 rq = task_rq_lock(p, &flags);
2573 BUG_ON(p->state != TASK_RUNNING);
2574 update_rq_clock(rq);
2576 p->prio = effective_prio(p);
2578 if (!p->sched_class->task_new || !current->se.on_rq) {
2579 activate_task(rq, p, 0);
2582 * Let the scheduling class do new task startup
2583 * management (if any):
2585 p->sched_class->task_new(rq, p);
2588 trace_sched_wakeup_new(rq, p, 1);
2589 check_preempt_curr(rq, p, 0);
2591 if (p->sched_class->task_wake_up)
2592 p->sched_class->task_wake_up(rq, p);
2594 task_rq_unlock(rq, &flags);
2597 #ifdef CONFIG_PREEMPT_NOTIFIERS
2600 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2601 * @notifier: notifier struct to register
2603 void preempt_notifier_register(struct preempt_notifier *notifier)
2605 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2607 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2610 * preempt_notifier_unregister - no longer interested in preemption notifications
2611 * @notifier: notifier struct to unregister
2613 * This is safe to call from within a preemption notifier.
2615 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2617 hlist_del(¬ifier->link);
2619 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2621 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2623 struct preempt_notifier *notifier;
2624 struct hlist_node *node;
2626 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2627 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2631 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2632 struct task_struct *next)
2634 struct preempt_notifier *notifier;
2635 struct hlist_node *node;
2637 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2638 notifier->ops->sched_out(notifier, next);
2641 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2643 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2648 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2649 struct task_struct *next)
2653 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2656 * prepare_task_switch - prepare to switch tasks
2657 * @rq: the runqueue preparing to switch
2658 * @prev: the current task that is being switched out
2659 * @next: the task we are going to switch to.
2661 * This is called with the rq lock held and interrupts off. It must
2662 * be paired with a subsequent finish_task_switch after the context
2665 * prepare_task_switch sets up locking and calls architecture specific
2669 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2670 struct task_struct *next)
2672 fire_sched_out_preempt_notifiers(prev, next);
2673 prepare_lock_switch(rq, next);
2674 prepare_arch_switch(next);
2678 * finish_task_switch - clean up after a task-switch
2679 * @rq: runqueue associated with task-switch
2680 * @prev: the thread we just switched away from.
2682 * finish_task_switch must be called after the context switch, paired
2683 * with a prepare_task_switch call before the context switch.
2684 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2685 * and do any other architecture-specific cleanup actions.
2687 * Note that we may have delayed dropping an mm in context_switch(). If
2688 * so, we finish that here outside of the runqueue lock. (Doing it
2689 * with the lock held can cause deadlocks; see schedule() for
2692 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2693 __releases(rq->lock)
2695 struct mm_struct *mm = rq->prev_mm;
2698 int post_schedule = 0;
2700 if (current->sched_class->needs_post_schedule)
2701 post_schedule = current->sched_class->needs_post_schedule(rq);
2707 * A task struct has one reference for the use as "current".
2708 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2709 * schedule one last time. The schedule call will never return, and
2710 * the scheduled task must drop that reference.
2711 * The test for TASK_DEAD must occur while the runqueue locks are
2712 * still held, otherwise prev could be scheduled on another cpu, die
2713 * there before we look at prev->state, and then the reference would
2715 * Manfred Spraul <manfred@colorfullife.com>
2717 prev_state = prev->state;
2718 finish_arch_switch(prev);
2719 perf_counter_task_sched_in(current, cpu_of(rq));
2720 finish_lock_switch(rq, prev);
2723 current->sched_class->post_schedule(rq);
2726 fire_sched_in_preempt_notifiers(current);
2729 if (unlikely(prev_state == TASK_DEAD)) {
2731 * Remove function-return probe instances associated with this
2732 * task and put them back on the free list.
2734 kprobe_flush_task(prev);
2735 put_task_struct(prev);
2740 * schedule_tail - first thing a freshly forked thread must call.
2741 * @prev: the thread we just switched away from.
2743 asmlinkage void schedule_tail(struct task_struct *prev)
2744 __releases(rq->lock)
2746 struct rq *rq = this_rq();
2748 finish_task_switch(rq, prev);
2749 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2750 /* In this case, finish_task_switch does not reenable preemption */
2753 if (current->set_child_tid)
2754 put_user(task_pid_vnr(current), current->set_child_tid);
2758 * context_switch - switch to the new MM and the new
2759 * thread's register state.
2762 context_switch(struct rq *rq, struct task_struct *prev,
2763 struct task_struct *next)
2765 struct mm_struct *mm, *oldmm;
2767 prepare_task_switch(rq, prev, next);
2768 trace_sched_switch(rq, prev, next);
2770 oldmm = prev->active_mm;
2772 * For paravirt, this is coupled with an exit in switch_to to
2773 * combine the page table reload and the switch backend into
2776 arch_enter_lazy_cpu_mode();
2778 if (unlikely(!mm)) {
2779 next->active_mm = oldmm;
2780 atomic_inc(&oldmm->mm_count);
2781 enter_lazy_tlb(oldmm, next);
2783 switch_mm(oldmm, mm, next);
2785 if (unlikely(!prev->mm)) {
2786 prev->active_mm = NULL;
2787 rq->prev_mm = oldmm;
2790 * Since the runqueue lock will be released by the next
2791 * task (which is an invalid locking op but in the case
2792 * of the scheduler it's an obvious special-case), so we
2793 * do an early lockdep release here:
2795 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2796 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2799 /* Here we just switch the register state and the stack. */
2800 switch_to(prev, next, prev);
2804 * this_rq must be evaluated again because prev may have moved
2805 * CPUs since it called schedule(), thus the 'rq' on its stack
2806 * frame will be invalid.
2808 finish_task_switch(this_rq(), prev);
2812 * nr_running, nr_uninterruptible and nr_context_switches:
2814 * externally visible scheduler statistics: current number of runnable
2815 * threads, current number of uninterruptible-sleeping threads, total
2816 * number of context switches performed since bootup.
2818 unsigned long nr_running(void)
2820 unsigned long i, sum = 0;
2822 for_each_online_cpu(i)
2823 sum += cpu_rq(i)->nr_running;
2828 unsigned long nr_uninterruptible(void)
2830 unsigned long i, sum = 0;
2832 for_each_possible_cpu(i)
2833 sum += cpu_rq(i)->nr_uninterruptible;
2836 * Since we read the counters lockless, it might be slightly
2837 * inaccurate. Do not allow it to go below zero though:
2839 if (unlikely((long)sum < 0))
2845 unsigned long long nr_context_switches(void)
2848 unsigned long long sum = 0;
2850 for_each_possible_cpu(i)
2851 sum += cpu_rq(i)->nr_switches;
2856 unsigned long nr_iowait(void)
2858 unsigned long i, sum = 0;
2860 for_each_possible_cpu(i)
2861 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2866 unsigned long nr_active(void)
2868 unsigned long i, running = 0, uninterruptible = 0;
2870 for_each_online_cpu(i) {
2871 running += cpu_rq(i)->nr_running;
2872 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2875 if (unlikely((long)uninterruptible < 0))
2876 uninterruptible = 0;
2878 return running + uninterruptible;
2882 * Externally visible per-cpu scheduler statistics:
2883 * cpu_nr_migrations(cpu) - number of migrations into that cpu
2885 u64 cpu_nr_migrations(int cpu)
2887 return cpu_rq(cpu)->nr_migrations_in;
2891 * Update rq->cpu_load[] statistics. This function is usually called every
2892 * scheduler tick (TICK_NSEC).
2894 static void update_cpu_load(struct rq *this_rq)
2896 unsigned long this_load = this_rq->load.weight;
2899 this_rq->nr_load_updates++;
2901 /* Update our load: */
2902 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2903 unsigned long old_load, new_load;
2905 /* scale is effectively 1 << i now, and >> i divides by scale */
2907 old_load = this_rq->cpu_load[i];
2908 new_load = this_load;
2910 * Round up the averaging division if load is increasing. This
2911 * prevents us from getting stuck on 9 if the load is 10, for
2914 if (new_load > old_load)
2915 new_load += scale-1;
2916 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2923 * double_rq_lock - safely lock two runqueues
2925 * Note this does not disable interrupts like task_rq_lock,
2926 * you need to do so manually before calling.
2928 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2929 __acquires(rq1->lock)
2930 __acquires(rq2->lock)
2932 BUG_ON(!irqs_disabled());
2934 spin_lock(&rq1->lock);
2935 __acquire(rq2->lock); /* Fake it out ;) */
2938 spin_lock(&rq1->lock);
2939 spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
2941 spin_lock(&rq2->lock);
2942 spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
2945 update_rq_clock(rq1);
2946 update_rq_clock(rq2);
2950 * double_rq_unlock - safely unlock two runqueues
2952 * Note this does not restore interrupts like task_rq_unlock,
2953 * you need to do so manually after calling.
2955 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2956 __releases(rq1->lock)
2957 __releases(rq2->lock)
2959 spin_unlock(&rq1->lock);
2961 spin_unlock(&rq2->lock);
2963 __release(rq2->lock);
2967 * If dest_cpu is allowed for this process, migrate the task to it.
2968 * This is accomplished by forcing the cpu_allowed mask to only
2969 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2970 * the cpu_allowed mask is restored.
2972 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2974 struct migration_req req;
2975 unsigned long flags;
2978 rq = task_rq_lock(p, &flags);
2979 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed)
2980 || unlikely(!cpu_active(dest_cpu)))
2983 /* force the process onto the specified CPU */
2984 if (migrate_task(p, dest_cpu, &req)) {
2985 /* Need to wait for migration thread (might exit: take ref). */
2986 struct task_struct *mt = rq->migration_thread;
2988 get_task_struct(mt);
2989 task_rq_unlock(rq, &flags);
2990 wake_up_process(mt);
2991 put_task_struct(mt);
2992 wait_for_completion(&req.done);
2997 task_rq_unlock(rq, &flags);
3001 * sched_exec - execve() is a valuable balancing opportunity, because at
3002 * this point the task has the smallest effective memory and cache footprint.
3004 void sched_exec(void)
3006 int new_cpu, this_cpu = get_cpu();
3007 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3009 if (new_cpu != this_cpu)
3010 sched_migrate_task(current, new_cpu);
3014 * pull_task - move a task from a remote runqueue to the local runqueue.
3015 * Both runqueues must be locked.
3017 static void pull_task(struct rq *src_rq, struct task_struct *p,
3018 struct rq *this_rq, int this_cpu)
3020 deactivate_task(src_rq, p, 0);
3021 set_task_cpu(p, this_cpu);
3022 activate_task(this_rq, p, 0);
3024 * Note that idle threads have a prio of MAX_PRIO, for this test
3025 * to be always true for them.
3027 check_preempt_curr(this_rq, p, 0);
3031 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3034 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3035 struct sched_domain *sd, enum cpu_idle_type idle,
3038 int tsk_cache_hot = 0;
3040 * We do not migrate tasks that are:
3041 * 1) running (obviously), or
3042 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3043 * 3) are cache-hot on their current CPU.
3045 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
3046 schedstat_inc(p, se.nr_failed_migrations_affine);
3051 if (task_running(rq, p)) {
3052 schedstat_inc(p, se.nr_failed_migrations_running);
3057 * Aggressive migration if:
3058 * 1) task is cache cold, or
3059 * 2) too many balance attempts have failed.
3062 tsk_cache_hot = task_hot(p, rq->clock, sd);
3063 if (!tsk_cache_hot ||
3064 sd->nr_balance_failed > sd->cache_nice_tries) {
3065 #ifdef CONFIG_SCHEDSTATS
3066 if (tsk_cache_hot) {
3067 schedstat_inc(sd, lb_hot_gained[idle]);
3068 schedstat_inc(p, se.nr_forced_migrations);
3074 if (tsk_cache_hot) {
3075 schedstat_inc(p, se.nr_failed_migrations_hot);
3081 static unsigned long
3082 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3083 unsigned long max_load_move, struct sched_domain *sd,
3084 enum cpu_idle_type idle, int *all_pinned,
3085 int *this_best_prio, struct rq_iterator *iterator)
3087 int loops = 0, pulled = 0, pinned = 0;
3088 struct task_struct *p;
3089 long rem_load_move = max_load_move;
3091 if (max_load_move == 0)
3097 * Start the load-balancing iterator:
3099 p = iterator->start(iterator->arg);
3101 if (!p || loops++ > sysctl_sched_nr_migrate)
3104 if ((p->se.load.weight >> 1) > rem_load_move ||
3105 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3106 p = iterator->next(iterator->arg);
3110 pull_task(busiest, p, this_rq, this_cpu);
3112 rem_load_move -= p->se.load.weight;
3114 #ifdef CONFIG_PREEMPT
3116 * NEWIDLE balancing is a source of latency, so preemptible kernels
3117 * will stop after the first task is pulled to minimize the critical
3120 if (idle == CPU_NEWLY_IDLE)
3125 * We only want to steal up to the prescribed amount of weighted load.
3127 if (rem_load_move > 0) {
3128 if (p->prio < *this_best_prio)
3129 *this_best_prio = p->prio;
3130 p = iterator->next(iterator->arg);
3135 * Right now, this is one of only two places pull_task() is called,
3136 * so we can safely collect pull_task() stats here rather than
3137 * inside pull_task().
3139 schedstat_add(sd, lb_gained[idle], pulled);
3142 *all_pinned = pinned;
3144 return max_load_move - rem_load_move;
3148 * move_tasks tries to move up to max_load_move weighted load from busiest to
3149 * this_rq, as part of a balancing operation within domain "sd".
3150 * Returns 1 if successful and 0 otherwise.
3152 * Called with both runqueues locked.
3154 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3155 unsigned long max_load_move,
3156 struct sched_domain *sd, enum cpu_idle_type idle,
3159 const struct sched_class *class = sched_class_highest;
3160 unsigned long total_load_moved = 0;
3161 int this_best_prio = this_rq->curr->prio;
3165 class->load_balance(this_rq, this_cpu, busiest,
3166 max_load_move - total_load_moved,
3167 sd, idle, all_pinned, &this_best_prio);
3168 class = class->next;
3170 #ifdef CONFIG_PREEMPT
3172 * NEWIDLE balancing is a source of latency, so preemptible
3173 * kernels will stop after the first task is pulled to minimize
3174 * the critical section.
3176 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3179 } while (class && max_load_move > total_load_moved);
3181 return total_load_moved > 0;
3185 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3186 struct sched_domain *sd, enum cpu_idle_type idle,
3187 struct rq_iterator *iterator)
3189 struct task_struct *p = iterator->start(iterator->arg);
3193 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3194 pull_task(busiest, p, this_rq, this_cpu);
3196 * Right now, this is only the second place pull_task()
3197 * is called, so we can safely collect pull_task()
3198 * stats here rather than inside pull_task().
3200 schedstat_inc(sd, lb_gained[idle]);
3204 p = iterator->next(iterator->arg);
3211 * move_one_task tries to move exactly one task from busiest to this_rq, as
3212 * part of active balancing operations within "domain".
3213 * Returns 1 if successful and 0 otherwise.
3215 * Called with both runqueues locked.
3217 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3218 struct sched_domain *sd, enum cpu_idle_type idle)
3220 const struct sched_class *class;
3222 for (class = sched_class_highest; class; class = class->next)
3223 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3228 /********** Helpers for find_busiest_group ************************/
3230 * sd_lb_stats - Structure to store the statistics of a sched_domain
3231 * during load balancing.
3233 struct sd_lb_stats {
3234 struct sched_group *busiest; /* Busiest group in this sd */
3235 struct sched_group *this; /* Local group in this sd */
3236 unsigned long total_load; /* Total load of all groups in sd */
3237 unsigned long total_pwr; /* Total power of all groups in sd */
3238 unsigned long avg_load; /* Average load across all groups in sd */
3240 /** Statistics of this group */
3241 unsigned long this_load;
3242 unsigned long this_load_per_task;
3243 unsigned long this_nr_running;
3245 /* Statistics of the busiest group */
3246 unsigned long max_load;
3247 unsigned long busiest_load_per_task;
3248 unsigned long busiest_nr_running;
3250 int group_imb; /* Is there imbalance in this sd */
3251 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3252 int power_savings_balance; /* Is powersave balance needed for this sd */
3253 struct sched_group *group_min; /* Least loaded group in sd */
3254 struct sched_group *group_leader; /* Group which relieves group_min */
3255 unsigned long min_load_per_task; /* load_per_task in group_min */
3256 unsigned long leader_nr_running; /* Nr running of group_leader */
3257 unsigned long min_nr_running; /* Nr running of group_min */
3262 * sg_lb_stats - stats of a sched_group required for load_balancing
3264 struct sg_lb_stats {
3265 unsigned long avg_load; /*Avg load across the CPUs of the group */
3266 unsigned long group_load; /* Total load over the CPUs of the group */
3267 unsigned long sum_nr_running; /* Nr tasks running in the group */
3268 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3269 unsigned long group_capacity;
3270 int group_imb; /* Is there an imbalance in the group ? */
3274 * group_first_cpu - Returns the first cpu in the cpumask of a sched_group.
3275 * @group: The group whose first cpu is to be returned.
3277 static inline unsigned int group_first_cpu(struct sched_group *group)
3279 return cpumask_first(sched_group_cpus(group));
3283 * get_sd_load_idx - Obtain the load index for a given sched domain.
3284 * @sd: The sched_domain whose load_idx is to be obtained.
3285 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3287 static inline int get_sd_load_idx(struct sched_domain *sd,
3288 enum cpu_idle_type idle)
3294 load_idx = sd->busy_idx;
3297 case CPU_NEWLY_IDLE:
3298 load_idx = sd->newidle_idx;
3301 load_idx = sd->idle_idx;
3309 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3311 * init_sd_power_savings_stats - Initialize power savings statistics for
3312 * the given sched_domain, during load balancing.
3314 * @sd: Sched domain whose power-savings statistics are to be initialized.
3315 * @sds: Variable containing the statistics for sd.
3316 * @idle: Idle status of the CPU at which we're performing load-balancing.
3318 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3319 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3322 * Busy processors will not participate in power savings
3325 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3326 sds->power_savings_balance = 0;
3328 sds->power_savings_balance = 1;
3329 sds->min_nr_running = ULONG_MAX;
3330 sds->leader_nr_running = 0;
3335 * update_sd_power_savings_stats - Update the power saving stats for a
3336 * sched_domain while performing load balancing.
3338 * @group: sched_group belonging to the sched_domain under consideration.
3339 * @sds: Variable containing the statistics of the sched_domain
3340 * @local_group: Does group contain the CPU for which we're performing
3342 * @sgs: Variable containing the statistics of the group.
3344 static inline void update_sd_power_savings_stats(struct sched_group *group,
3345 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3348 if (!sds->power_savings_balance)
3352 * If the local group is idle or completely loaded
3353 * no need to do power savings balance at this domain
3355 if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
3356 !sds->this_nr_running))
3357 sds->power_savings_balance = 0;
3360 * If a group is already running at full capacity or idle,
3361 * don't include that group in power savings calculations
3363 if (!sds->power_savings_balance ||
3364 sgs->sum_nr_running >= sgs->group_capacity ||
3365 !sgs->sum_nr_running)
3369 * Calculate the group which has the least non-idle load.
3370 * This is the group from where we need to pick up the load
3373 if ((sgs->sum_nr_running < sds->min_nr_running) ||
3374 (sgs->sum_nr_running == sds->min_nr_running &&
3375 group_first_cpu(group) > group_first_cpu(sds->group_min))) {
3376 sds->group_min = group;
3377 sds->min_nr_running = sgs->sum_nr_running;
3378 sds->min_load_per_task = sgs->sum_weighted_load /
3379 sgs->sum_nr_running;
3383 * Calculate the group which is almost near its
3384 * capacity but still has some space to pick up some load
3385 * from other group and save more power
3387 if (sgs->sum_nr_running > sgs->group_capacity - 1)
3390 if (sgs->sum_nr_running > sds->leader_nr_running ||
3391 (sgs->sum_nr_running == sds->leader_nr_running &&
3392 group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
3393 sds->group_leader = group;
3394 sds->leader_nr_running = sgs->sum_nr_running;
3399 * check_power_save_busiest_group - see if there is potential for some power-savings balance
3400 * @sds: Variable containing the statistics of the sched_domain
3401 * under consideration.
3402 * @this_cpu: Cpu at which we're currently performing load-balancing.
3403 * @imbalance: Variable to store the imbalance.
3406 * Check if we have potential to perform some power-savings balance.
3407 * If yes, set the busiest group to be the least loaded group in the
3408 * sched_domain, so that it's CPUs can be put to idle.
3410 * Returns 1 if there is potential to perform power-savings balance.
3413 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3414 int this_cpu, unsigned long *imbalance)
3416 if (!sds->power_savings_balance)
3419 if (sds->this != sds->group_leader ||
3420 sds->group_leader == sds->group_min)
3423 *imbalance = sds->min_load_per_task;
3424 sds->busiest = sds->group_min;
3426 if (sched_mc_power_savings >= POWERSAVINGS_BALANCE_WAKEUP) {
3427 cpu_rq(this_cpu)->rd->sched_mc_preferred_wakeup_cpu =
3428 group_first_cpu(sds->group_leader);
3434 #else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3435 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3436 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3441 static inline void update_sd_power_savings_stats(struct sched_group *group,
3442 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3447 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3448 int this_cpu, unsigned long *imbalance)
3452 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3456 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
3457 * @group: sched_group whose statistics are to be updated.
3458 * @this_cpu: Cpu for which load balance is currently performed.
3459 * @idle: Idle status of this_cpu
3460 * @load_idx: Load index of sched_domain of this_cpu for load calc.
3461 * @sd_idle: Idle status of the sched_domain containing group.
3462 * @local_group: Does group contain this_cpu.
3463 * @cpus: Set of cpus considered for load balancing.
3464 * @balance: Should we balance.
3465 * @sgs: variable to hold the statistics for this group.
3467 static inline void update_sg_lb_stats(struct sched_group *group, int this_cpu,
3468 enum cpu_idle_type idle, int load_idx, int *sd_idle,
3469 int local_group, const struct cpumask *cpus,
3470 int *balance, struct sg_lb_stats *sgs)
3472 unsigned long load, max_cpu_load, min_cpu_load;
3474 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3475 unsigned long sum_avg_load_per_task;
3476 unsigned long avg_load_per_task;
3479 balance_cpu = group_first_cpu(group);
3481 /* Tally up the load of all CPUs in the group */
3482 sum_avg_load_per_task = avg_load_per_task = 0;
3484 min_cpu_load = ~0UL;
3486 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
3487 struct rq *rq = cpu_rq(i);
3489 if (*sd_idle && rq->nr_running)
3492 /* Bias balancing toward cpus of our domain */
3494 if (idle_cpu(i) && !first_idle_cpu) {
3499 load = target_load(i, load_idx);
3501 load = source_load(i, load_idx);
3502 if (load > max_cpu_load)
3503 max_cpu_load = load;
3504 if (min_cpu_load > load)
3505 min_cpu_load = load;
3508 sgs->group_load += load;
3509 sgs->sum_nr_running += rq->nr_running;
3510 sgs->sum_weighted_load += weighted_cpuload(i);
3512 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3516 * First idle cpu or the first cpu(busiest) in this sched group
3517 * is eligible for doing load balancing at this and above
3518 * domains. In the newly idle case, we will allow all the cpu's
3519 * to do the newly idle load balance.
3521 if (idle != CPU_NEWLY_IDLE && local_group &&
3522 balance_cpu != this_cpu && balance) {
3527 /* Adjust by relative CPU power of the group */
3528 sgs->avg_load = sg_div_cpu_power(group,
3529 sgs->group_load * SCHED_LOAD_SCALE);
3533 * Consider the group unbalanced when the imbalance is larger
3534 * than the average weight of two tasks.
3536 * APZ: with cgroup the avg task weight can vary wildly and
3537 * might not be a suitable number - should we keep a
3538 * normalized nr_running number somewhere that negates
3541 avg_load_per_task = sg_div_cpu_power(group,
3542 sum_avg_load_per_task * SCHED_LOAD_SCALE);
3544 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3547 sgs->group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3552 * update_sd_lb_stats - Update sched_group's statistics for load balancing.
3553 * @sd: sched_domain whose statistics are to be updated.
3554 * @this_cpu: Cpu for which load balance is currently performed.
3555 * @idle: Idle status of this_cpu
3556 * @sd_idle: Idle status of the sched_domain containing group.
3557 * @cpus: Set of cpus considered for load balancing.
3558 * @balance: Should we balance.
3559 * @sds: variable to hold the statistics for this sched_domain.
3561 static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
3562 enum cpu_idle_type idle, int *sd_idle,
3563 const struct cpumask *cpus, int *balance,
3564 struct sd_lb_stats *sds)
3566 struct sched_group *group = sd->groups;
3567 struct sg_lb_stats sgs;
3570 init_sd_power_savings_stats(sd, sds, idle);
3571 load_idx = get_sd_load_idx(sd, idle);
3576 local_group = cpumask_test_cpu(this_cpu,
3577 sched_group_cpus(group));
3578 memset(&sgs, 0, sizeof(sgs));
3579 update_sg_lb_stats(group, this_cpu, idle, load_idx, sd_idle,
3580 local_group, cpus, balance, &sgs);
3582 if (local_group && balance && !(*balance))
3585 sds->total_load += sgs.group_load;
3586 sds->total_pwr += group->__cpu_power;
3589 sds->this_load = sgs.avg_load;
3591 sds->this_nr_running = sgs.sum_nr_running;
3592 sds->this_load_per_task = sgs.sum_weighted_load;
3593 } else if (sgs.avg_load > sds->max_load &&
3594 (sgs.sum_nr_running > sgs.group_capacity ||
3596 sds->max_load = sgs.avg_load;
3597 sds->busiest = group;
3598 sds->busiest_nr_running = sgs.sum_nr_running;
3599 sds->busiest_load_per_task = sgs.sum_weighted_load;
3600 sds->group_imb = sgs.group_imb;
3603 update_sd_power_savings_stats(group, sds, local_group, &sgs);
3604 group = group->next;
3605 } while (group != sd->groups);
3610 * fix_small_imbalance - Calculate the minor imbalance that exists
3611 * amongst the groups of a sched_domain, during
3613 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
3614 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
3615 * @imbalance: Variable to store the imbalance.
3617 static inline void fix_small_imbalance(struct sd_lb_stats *sds,
3618 int this_cpu, unsigned long *imbalance)
3620 unsigned long tmp, pwr_now = 0, pwr_move = 0;
3621 unsigned int imbn = 2;
3623 if (sds->this_nr_running) {
3624 sds->this_load_per_task /= sds->this_nr_running;
3625 if (sds->busiest_load_per_task >
3626 sds->this_load_per_task)
3629 sds->this_load_per_task =
3630 cpu_avg_load_per_task(this_cpu);
3632 if (sds->max_load - sds->this_load + sds->busiest_load_per_task >=
3633 sds->busiest_load_per_task * imbn) {
3634 *imbalance = sds->busiest_load_per_task;
3639 * OK, we don't have enough imbalance to justify moving tasks,
3640 * however we may be able to increase total CPU power used by
3644 pwr_now += sds->busiest->__cpu_power *
3645 min(sds->busiest_load_per_task, sds->max_load);
3646 pwr_now += sds->this->__cpu_power *
3647 min(sds->this_load_per_task, sds->this_load);
3648 pwr_now /= SCHED_LOAD_SCALE;
3650 /* Amount of load we'd subtract */
3651 tmp = sg_div_cpu_power(sds->busiest,
3652 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3653 if (sds->max_load > tmp)
3654 pwr_move += sds->busiest->__cpu_power *
3655 min(sds->busiest_load_per_task, sds->max_load - tmp);
3657 /* Amount of load we'd add */
3658 if (sds->max_load * sds->busiest->__cpu_power <
3659 sds->busiest_load_per_task * SCHED_LOAD_SCALE)
3660 tmp = sg_div_cpu_power(sds->this,
3661 sds->max_load * sds->busiest->__cpu_power);
3663 tmp = sg_div_cpu_power(sds->this,
3664 sds->busiest_load_per_task * SCHED_LOAD_SCALE);
3665 pwr_move += sds->this->__cpu_power *
3666 min(sds->this_load_per_task, sds->this_load + tmp);
3667 pwr_move /= SCHED_LOAD_SCALE;
3669 /* Move if we gain throughput */
3670 if (pwr_move > pwr_now)
3671 *imbalance = sds->busiest_load_per_task;
3675 * calculate_imbalance - Calculate the amount of imbalance present within the
3676 * groups of a given sched_domain during load balance.
3677 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
3678 * @this_cpu: Cpu for which currently load balance is being performed.
3679 * @imbalance: The variable to store the imbalance.
3681 static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
3682 unsigned long *imbalance)
3684 unsigned long max_pull;
3686 * In the presence of smp nice balancing, certain scenarios can have
3687 * max load less than avg load(as we skip the groups at or below
3688 * its cpu_power, while calculating max_load..)
3690 if (sds->max_load < sds->avg_load) {
3692 return fix_small_imbalance(sds, this_cpu, imbalance);
3695 /* Don't want to pull so many tasks that a group would go idle */
3696 max_pull = min(sds->max_load - sds->avg_load,
3697 sds->max_load - sds->busiest_load_per_task);
3699 /* How much load to actually move to equalise the imbalance */
3700 *imbalance = min(max_pull * sds->busiest->__cpu_power,
3701 (sds->avg_load - sds->this_load) * sds->this->__cpu_power)
3705 * if *imbalance is less than the average load per runnable task
3706 * there is no gaurantee that any tasks will be moved so we'll have
3707 * a think about bumping its value to force at least one task to be
3710 if (*imbalance < sds->busiest_load_per_task)
3711 return fix_small_imbalance(sds, this_cpu, imbalance);
3714 /******* find_busiest_group() helpers end here *********************/
3717 * find_busiest_group - Returns the busiest group within the sched_domain
3718 * if there is an imbalance. If there isn't an imbalance, and
3719 * the user has opted for power-savings, it returns a group whose
3720 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
3721 * such a group exists.
3723 * Also calculates the amount of weighted load which should be moved
3724 * to restore balance.
3726 * @sd: The sched_domain whose busiest group is to be returned.
3727 * @this_cpu: The cpu for which load balancing is currently being performed.
3728 * @imbalance: Variable which stores amount of weighted load which should
3729 * be moved to restore balance/put a group to idle.
3730 * @idle: The idle status of this_cpu.
3731 * @sd_idle: The idleness of sd
3732 * @cpus: The set of CPUs under consideration for load-balancing.
3733 * @balance: Pointer to a variable indicating if this_cpu
3734 * is the appropriate cpu to perform load balancing at this_level.
3736 * Returns: - the busiest group if imbalance exists.
3737 * - If no imbalance and user has opted for power-savings balance,
3738 * return the least loaded group whose CPUs can be
3739 * put to idle by rebalancing its tasks onto our group.
3741 static struct sched_group *
3742 find_busiest_group(struct sched_domain *sd, int this_cpu,
3743 unsigned long *imbalance, enum cpu_idle_type idle,
3744 int *sd_idle, const struct cpumask *cpus, int *balance)
3746 struct sd_lb_stats sds;
3748 memset(&sds, 0, sizeof(sds));
3751 * Compute the various statistics relavent for load balancing at
3754 update_sd_lb_stats(sd, this_cpu, idle, sd_idle, cpus,
3757 /* Cases where imbalance does not exist from POV of this_cpu */
3758 /* 1) this_cpu is not the appropriate cpu to perform load balancing
3760 * 2) There is no busy sibling group to pull from.
3761 * 3) This group is the busiest group.
3762 * 4) This group is more busy than the avg busieness at this
3764 * 5) The imbalance is within the specified limit.
3765 * 6) Any rebalance would lead to ping-pong
3767 if (balance && !(*balance))
3770 if (!sds.busiest || sds.busiest_nr_running == 0)
3773 if (sds.this_load >= sds.max_load)
3776 sds.avg_load = (SCHED_LOAD_SCALE * sds.total_load) / sds.total_pwr;
3778 if (sds.this_load >= sds.avg_load)
3781 if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
3784 sds.busiest_load_per_task /= sds.busiest_nr_running;
3786 sds.busiest_load_per_task =
3787 min(sds.busiest_load_per_task, sds.avg_load);
3790 * We're trying to get all the cpus to the average_load, so we don't
3791 * want to push ourselves above the average load, nor do we wish to
3792 * reduce the max loaded cpu below the average load, as either of these
3793 * actions would just result in more rebalancing later, and ping-pong
3794 * tasks around. Thus we look for the minimum possible imbalance.
3795 * Negative imbalances (*we* are more loaded than anyone else) will
3796 * be counted as no imbalance for these purposes -- we can't fix that
3797 * by pulling tasks to us. Be careful of negative numbers as they'll
3798 * appear as very large values with unsigned longs.
3800 if (sds.max_load <= sds.busiest_load_per_task)
3803 /* Looks like there is an imbalance. Compute it */
3804 calculate_imbalance(&sds, this_cpu, imbalance);
3809 * There is no obvious imbalance. But check if we can do some balancing
3812 if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
3820 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3823 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3824 unsigned long imbalance, const struct cpumask *cpus)
3826 struct rq *busiest = NULL, *rq;
3827 unsigned long max_load = 0;
3830 for_each_cpu(i, sched_group_cpus(group)) {
3833 if (!cpumask_test_cpu(i, cpus))
3837 wl = weighted_cpuload(i);
3839 if (rq->nr_running == 1 && wl > imbalance)
3842 if (wl > max_load) {
3852 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3853 * so long as it is large enough.
3855 #define MAX_PINNED_INTERVAL 512
3857 /* Working cpumask for load_balance and load_balance_newidle. */
3858 static DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
3861 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3862 * tasks if there is an imbalance.
3864 static int load_balance(int this_cpu, struct rq *this_rq,
3865 struct sched_domain *sd, enum cpu_idle_type idle,
3868 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3869 struct sched_group *group;
3870 unsigned long imbalance;
3872 unsigned long flags;
3873 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
3875 cpumask_setall(cpus);
3878 * When power savings policy is enabled for the parent domain, idle
3879 * sibling can pick up load irrespective of busy siblings. In this case,
3880 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3881 * portraying it as CPU_NOT_IDLE.
3883 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3884 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3887 schedstat_inc(sd, lb_count[idle]);
3891 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3898 schedstat_inc(sd, lb_nobusyg[idle]);
3902 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3904 schedstat_inc(sd, lb_nobusyq[idle]);
3908 BUG_ON(busiest == this_rq);
3910 schedstat_add(sd, lb_imbalance[idle], imbalance);
3913 if (busiest->nr_running > 1) {
3915 * Attempt to move tasks. If find_busiest_group has found
3916 * an imbalance but busiest->nr_running <= 1, the group is
3917 * still unbalanced. ld_moved simply stays zero, so it is
3918 * correctly treated as an imbalance.
3920 local_irq_save(flags);
3921 double_rq_lock(this_rq, busiest);
3922 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3923 imbalance, sd, idle, &all_pinned);
3924 double_rq_unlock(this_rq, busiest);
3925 local_irq_restore(flags);
3928 * some other cpu did the load balance for us.
3930 if (ld_moved && this_cpu != smp_processor_id())
3931 resched_cpu(this_cpu);
3933 /* All tasks on this runqueue were pinned by CPU affinity */
3934 if (unlikely(all_pinned)) {
3935 cpumask_clear_cpu(cpu_of(busiest), cpus);
3936 if (!cpumask_empty(cpus))
3943 schedstat_inc(sd, lb_failed[idle]);
3944 sd->nr_balance_failed++;
3946 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3948 spin_lock_irqsave(&busiest->lock, flags);
3950 /* don't kick the migration_thread, if the curr
3951 * task on busiest cpu can't be moved to this_cpu
3953 if (!cpumask_test_cpu(this_cpu,
3954 &busiest->curr->cpus_allowed)) {
3955 spin_unlock_irqrestore(&busiest->lock, flags);
3957 goto out_one_pinned;
3960 if (!busiest->active_balance) {
3961 busiest->active_balance = 1;
3962 busiest->push_cpu = this_cpu;
3965 spin_unlock_irqrestore(&busiest->lock, flags);
3967 wake_up_process(busiest->migration_thread);
3970 * We've kicked active balancing, reset the failure
3973 sd->nr_balance_failed = sd->cache_nice_tries+1;
3976 sd->nr_balance_failed = 0;
3978 if (likely(!active_balance)) {
3979 /* We were unbalanced, so reset the balancing interval */
3980 sd->balance_interval = sd->min_interval;
3983 * If we've begun active balancing, start to back off. This
3984 * case may not be covered by the all_pinned logic if there
3985 * is only 1 task on the busy runqueue (because we don't call
3988 if (sd->balance_interval < sd->max_interval)
3989 sd->balance_interval *= 2;
3992 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3993 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3999 schedstat_inc(sd, lb_balanced[idle]);
4001 sd->nr_balance_failed = 0;
4004 /* tune up the balancing interval */
4005 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
4006 (sd->balance_interval < sd->max_interval))
4007 sd->balance_interval *= 2;
4009 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4010 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4021 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4022 * tasks if there is an imbalance.
4024 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
4025 * this_rq is locked.
4028 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
4030 struct sched_group *group;
4031 struct rq *busiest = NULL;
4032 unsigned long imbalance;
4036 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4038 cpumask_setall(cpus);
4041 * When power savings policy is enabled for the parent domain, idle
4042 * sibling can pick up load irrespective of busy siblings. In this case,
4043 * let the state of idle sibling percolate up as IDLE, instead of
4044 * portraying it as CPU_NOT_IDLE.
4046 if (sd->flags & SD_SHARE_CPUPOWER &&
4047 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4050 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
4052 update_shares_locked(this_rq, sd);
4053 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
4054 &sd_idle, cpus, NULL);
4056 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
4060 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
4062 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
4066 BUG_ON(busiest == this_rq);
4068 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
4071 if (busiest->nr_running > 1) {
4072 /* Attempt to move tasks */
4073 double_lock_balance(this_rq, busiest);
4074 /* this_rq->clock is already updated */
4075 update_rq_clock(busiest);
4076 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4077 imbalance, sd, CPU_NEWLY_IDLE,
4079 double_unlock_balance(this_rq, busiest);
4081 if (unlikely(all_pinned)) {
4082 cpumask_clear_cpu(cpu_of(busiest), cpus);
4083 if (!cpumask_empty(cpus))
4089 int active_balance = 0;
4091 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
4092 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4093 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4096 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
4099 if (sd->nr_balance_failed++ < 2)
4103 * The only task running in a non-idle cpu can be moved to this
4104 * cpu in an attempt to completely freeup the other CPU
4105 * package. The same method used to move task in load_balance()
4106 * have been extended for load_balance_newidle() to speedup
4107 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
4109 * The package power saving logic comes from
4110 * find_busiest_group(). If there are no imbalance, then
4111 * f_b_g() will return NULL. However when sched_mc={1,2} then
4112 * f_b_g() will select a group from which a running task may be
4113 * pulled to this cpu in order to make the other package idle.
4114 * If there is no opportunity to make a package idle and if
4115 * there are no imbalance, then f_b_g() will return NULL and no
4116 * action will be taken in load_balance_newidle().
4118 * Under normal task pull operation due to imbalance, there
4119 * will be more than one task in the source run queue and
4120 * move_tasks() will succeed. ld_moved will be true and this
4121 * active balance code will not be triggered.
4124 /* Lock busiest in correct order while this_rq is held */
4125 double_lock_balance(this_rq, busiest);
4128 * don't kick the migration_thread, if the curr
4129 * task on busiest cpu can't be moved to this_cpu
4131 if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
4132 double_unlock_balance(this_rq, busiest);
4137 if (!busiest->active_balance) {
4138 busiest->active_balance = 1;
4139 busiest->push_cpu = this_cpu;
4143 double_unlock_balance(this_rq, busiest);
4145 * Should not call ttwu while holding a rq->lock
4147 spin_unlock(&this_rq->lock);
4149 wake_up_process(busiest->migration_thread);
4150 spin_lock(&this_rq->lock);
4153 sd->nr_balance_failed = 0;
4155 update_shares_locked(this_rq, sd);
4159 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
4160 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4161 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4163 sd->nr_balance_failed = 0;
4169 * idle_balance is called by schedule() if this_cpu is about to become
4170 * idle. Attempts to pull tasks from other CPUs.
4172 static void idle_balance(int this_cpu, struct rq *this_rq)
4174 struct sched_domain *sd;
4175 int pulled_task = 0;
4176 unsigned long next_balance = jiffies + HZ;
4178 for_each_domain(this_cpu, sd) {
4179 unsigned long interval;
4181 if (!(sd->flags & SD_LOAD_BALANCE))
4184 if (sd->flags & SD_BALANCE_NEWIDLE)
4185 /* If we've pulled tasks over stop searching: */
4186 pulled_task = load_balance_newidle(this_cpu, this_rq,
4189 interval = msecs_to_jiffies(sd->balance_interval);
4190 if (time_after(next_balance, sd->last_balance + interval))
4191 next_balance = sd->last_balance + interval;
4195 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4197 * We are going idle. next_balance may be set based on
4198 * a busy processor. So reset next_balance.
4200 this_rq->next_balance = next_balance;
4205 * active_load_balance is run by migration threads. It pushes running tasks
4206 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4207 * running on each physical CPU where possible, and avoids physical /
4208 * logical imbalances.
4210 * Called with busiest_rq locked.
4212 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4214 int target_cpu = busiest_rq->push_cpu;
4215 struct sched_domain *sd;
4216 struct rq *target_rq;
4218 /* Is there any task to move? */
4219 if (busiest_rq->nr_running <= 1)
4222 target_rq = cpu_rq(target_cpu);
4225 * This condition is "impossible", if it occurs
4226 * we need to fix it. Originally reported by
4227 * Bjorn Helgaas on a 128-cpu setup.
4229 BUG_ON(busiest_rq == target_rq);
4231 /* move a task from busiest_rq to target_rq */
4232 double_lock_balance(busiest_rq, target_rq);
4233 update_rq_clock(busiest_rq);
4234 update_rq_clock(target_rq);
4236 /* Search for an sd spanning us and the target CPU. */
4237 for_each_domain(target_cpu, sd) {
4238 if ((sd->flags & SD_LOAD_BALANCE) &&
4239 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4244 schedstat_inc(sd, alb_count);
4246 if (move_one_task(target_rq, target_cpu, busiest_rq,
4248 schedstat_inc(sd, alb_pushed);
4250 schedstat_inc(sd, alb_failed);
4252 double_unlock_balance(busiest_rq, target_rq);
4257 atomic_t load_balancer;
4258 cpumask_var_t cpu_mask;
4259 } nohz ____cacheline_aligned = {
4260 .load_balancer = ATOMIC_INIT(-1),
4264 * This routine will try to nominate the ilb (idle load balancing)
4265 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4266 * load balancing on behalf of all those cpus. If all the cpus in the system
4267 * go into this tickless mode, then there will be no ilb owner (as there is
4268 * no need for one) and all the cpus will sleep till the next wakeup event
4271 * For the ilb owner, tick is not stopped. And this tick will be used
4272 * for idle load balancing. ilb owner will still be part of
4275 * While stopping the tick, this cpu will become the ilb owner if there
4276 * is no other owner. And will be the owner till that cpu becomes busy
4277 * or if all cpus in the system stop their ticks at which point
4278 * there is no need for ilb owner.
4280 * When the ilb owner becomes busy, it nominates another owner, during the
4281 * next busy scheduler_tick()
4283 int select_nohz_load_balancer(int stop_tick)
4285 int cpu = smp_processor_id();
4288 cpu_rq(cpu)->in_nohz_recently = 1;
4290 if (!cpu_active(cpu)) {
4291 if (atomic_read(&nohz.load_balancer) != cpu)
4295 * If we are going offline and still the leader,
4298 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4304 cpumask_set_cpu(cpu, nohz.cpu_mask);
4306 /* time for ilb owner also to sleep */
4307 if (cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4308 if (atomic_read(&nohz.load_balancer) == cpu)
4309 atomic_set(&nohz.load_balancer, -1);
4313 if (atomic_read(&nohz.load_balancer) == -1) {
4314 /* make me the ilb owner */
4315 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4317 } else if (atomic_read(&nohz.load_balancer) == cpu)
4320 if (!cpumask_test_cpu(cpu, nohz.cpu_mask))
4323 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4325 if (atomic_read(&nohz.load_balancer) == cpu)
4326 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4333 static DEFINE_SPINLOCK(balancing);
4336 * It checks each scheduling domain to see if it is due to be balanced,
4337 * and initiates a balancing operation if so.
4339 * Balancing parameters are set up in arch_init_sched_domains.
4341 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4344 struct rq *rq = cpu_rq(cpu);
4345 unsigned long interval;
4346 struct sched_domain *sd;
4347 /* Earliest time when we have to do rebalance again */
4348 unsigned long next_balance = jiffies + 60*HZ;
4349 int update_next_balance = 0;
4352 for_each_domain(cpu, sd) {
4353 if (!(sd->flags & SD_LOAD_BALANCE))
4356 interval = sd->balance_interval;
4357 if (idle != CPU_IDLE)
4358 interval *= sd->busy_factor;
4360 /* scale ms to jiffies */
4361 interval = msecs_to_jiffies(interval);
4362 if (unlikely(!interval))
4364 if (interval > HZ*NR_CPUS/10)
4365 interval = HZ*NR_CPUS/10;
4367 need_serialize = sd->flags & SD_SERIALIZE;
4369 if (need_serialize) {
4370 if (!spin_trylock(&balancing))
4374 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4375 if (load_balance(cpu, rq, sd, idle, &balance)) {
4377 * We've pulled tasks over so either we're no
4378 * longer idle, or one of our SMT siblings is
4381 idle = CPU_NOT_IDLE;
4383 sd->last_balance = jiffies;
4386 spin_unlock(&balancing);
4388 if (time_after(next_balance, sd->last_balance + interval)) {
4389 next_balance = sd->last_balance + interval;
4390 update_next_balance = 1;
4394 * Stop the load balance at this level. There is another
4395 * CPU in our sched group which is doing load balancing more
4403 * next_balance will be updated only when there is a need.
4404 * When the cpu is attached to null domain for ex, it will not be
4407 if (likely(update_next_balance))
4408 rq->next_balance = next_balance;
4412 * run_rebalance_domains is triggered when needed from the scheduler tick.
4413 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4414 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4416 static void run_rebalance_domains(struct softirq_action *h)
4418 int this_cpu = smp_processor_id();
4419 struct rq *this_rq = cpu_rq(this_cpu);
4420 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4421 CPU_IDLE : CPU_NOT_IDLE;
4423 rebalance_domains(this_cpu, idle);
4427 * If this cpu is the owner for idle load balancing, then do the
4428 * balancing on behalf of the other idle cpus whose ticks are
4431 if (this_rq->idle_at_tick &&
4432 atomic_read(&nohz.load_balancer) == this_cpu) {
4436 for_each_cpu(balance_cpu, nohz.cpu_mask) {
4437 if (balance_cpu == this_cpu)
4441 * If this cpu gets work to do, stop the load balancing
4442 * work being done for other cpus. Next load
4443 * balancing owner will pick it up.
4448 rebalance_domains(balance_cpu, CPU_IDLE);
4450 rq = cpu_rq(balance_cpu);
4451 if (time_after(this_rq->next_balance, rq->next_balance))
4452 this_rq->next_balance = rq->next_balance;
4458 static inline int on_null_domain(int cpu)
4460 return !rcu_dereference(cpu_rq(cpu)->sd);
4464 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4466 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4467 * idle load balancing owner or decide to stop the periodic load balancing,
4468 * if the whole system is idle.
4470 static inline void trigger_load_balance(struct rq *rq, int cpu)
4474 * If we were in the nohz mode recently and busy at the current
4475 * scheduler tick, then check if we need to nominate new idle
4478 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4479 rq->in_nohz_recently = 0;
4481 if (atomic_read(&nohz.load_balancer) == cpu) {
4482 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4483 atomic_set(&nohz.load_balancer, -1);
4486 if (atomic_read(&nohz.load_balancer) == -1) {
4488 * simple selection for now: Nominate the
4489 * first cpu in the nohz list to be the next
4492 * TBD: Traverse the sched domains and nominate
4493 * the nearest cpu in the nohz.cpu_mask.
4495 int ilb = cpumask_first(nohz.cpu_mask);
4497 if (ilb < nr_cpu_ids)
4503 * If this cpu is idle and doing idle load balancing for all the
4504 * cpus with ticks stopped, is it time for that to stop?
4506 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4507 cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4513 * If this cpu is idle and the idle load balancing is done by
4514 * someone else, then no need raise the SCHED_SOFTIRQ
4516 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4517 cpumask_test_cpu(cpu, nohz.cpu_mask))
4520 /* Don't need to rebalance while attached to NULL domain */
4521 if (time_after_eq(jiffies, rq->next_balance) &&
4522 likely(!on_null_domain(cpu)))
4523 raise_softirq(SCHED_SOFTIRQ);
4526 #else /* CONFIG_SMP */
4529 * on UP we do not need to balance between CPUs:
4531 static inline void idle_balance(int cpu, struct rq *rq)
4537 DEFINE_PER_CPU(struct kernel_stat, kstat);
4539 EXPORT_PER_CPU_SYMBOL(kstat);
4542 * Return any ns on the sched_clock that have not yet been banked in
4543 * @p in case that task is currently running.
4545 unsigned long long __task_delta_exec(struct task_struct *p, int update)
4551 WARN_ON_ONCE(!runqueue_is_locked());
4552 WARN_ON_ONCE(!task_current(rq, p));
4555 update_rq_clock(rq);
4557 delta_exec = rq->clock - p->se.exec_start;
4559 WARN_ON_ONCE(delta_exec < 0);
4565 * Return any ns on the sched_clock that have not yet been banked in
4566 * @p in case that task is currently running.
4568 unsigned long long task_delta_exec(struct task_struct *p)
4570 unsigned long flags;
4574 rq = task_rq_lock(p, &flags);
4576 if (task_current(rq, p)) {
4579 update_rq_clock(rq);
4580 delta_exec = rq->clock - p->se.exec_start;
4581 if ((s64)delta_exec > 0)
4585 task_rq_unlock(rq, &flags);
4591 * Account user cpu time to a process.
4592 * @p: the process that the cpu time gets accounted to
4593 * @cputime: the cpu time spent in user space since the last update
4594 * @cputime_scaled: cputime scaled by cpu frequency
4596 void account_user_time(struct task_struct *p, cputime_t cputime,
4597 cputime_t cputime_scaled)
4599 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4602 /* Add user time to process. */
4603 p->utime = cputime_add(p->utime, cputime);
4604 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4605 account_group_user_time(p, cputime);
4607 /* Add user time to cpustat. */
4608 tmp = cputime_to_cputime64(cputime);
4609 if (TASK_NICE(p) > 0)
4610 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4612 cpustat->user = cputime64_add(cpustat->user, tmp);
4613 /* Account for user time used */
4614 acct_update_integrals(p);
4618 * Account guest cpu time to a process.
4619 * @p: the process that the cpu time gets accounted to
4620 * @cputime: the cpu time spent in virtual machine since the last update
4621 * @cputime_scaled: cputime scaled by cpu frequency
4623 static void account_guest_time(struct task_struct *p, cputime_t cputime,
4624 cputime_t cputime_scaled)
4627 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4629 tmp = cputime_to_cputime64(cputime);
4631 /* Add guest time to process. */
4632 p->utime = cputime_add(p->utime, cputime);
4633 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
4634 account_group_user_time(p, cputime);
4635 p->gtime = cputime_add(p->gtime, cputime);
4637 /* Add guest time to cpustat. */
4638 cpustat->user = cputime64_add(cpustat->user, tmp);
4639 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4643 * Account system cpu time to a process.
4644 * @p: the process that the cpu time gets accounted to
4645 * @hardirq_offset: the offset to subtract from hardirq_count()
4646 * @cputime: the cpu time spent in kernel space since the last update
4647 * @cputime_scaled: cputime scaled by cpu frequency
4649 void account_system_time(struct task_struct *p, int hardirq_offset,
4650 cputime_t cputime, cputime_t cputime_scaled)
4652 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4655 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4656 account_guest_time(p, cputime, cputime_scaled);
4660 /* Add system time to process. */
4661 p->stime = cputime_add(p->stime, cputime);
4662 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
4663 account_group_system_time(p, cputime);
4665 /* Add system time to cpustat. */
4666 tmp = cputime_to_cputime64(cputime);
4667 if (hardirq_count() - hardirq_offset)
4668 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4669 else if (softirq_count())
4670 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4672 cpustat->system = cputime64_add(cpustat->system, tmp);
4674 /* Account for system time used */
4675 acct_update_integrals(p);
4679 * Account for involuntary wait time.
4680 * @steal: the cpu time spent in involuntary wait
4682 void account_steal_time(cputime_t cputime)
4684 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4685 cputime64_t cputime64 = cputime_to_cputime64(cputime);
4687 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
4691 * Account for idle time.
4692 * @cputime: the cpu time spent in idle wait
4694 void account_idle_time(cputime_t cputime)
4696 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4697 cputime64_t cputime64 = cputime_to_cputime64(cputime);
4698 struct rq *rq = this_rq();
4700 if (atomic_read(&rq->nr_iowait) > 0)
4701 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
4703 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
4706 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
4709 * Account a single tick of cpu time.
4710 * @p: the process that the cpu time gets accounted to
4711 * @user_tick: indicates if the tick is a user or a system tick
4713 void account_process_tick(struct task_struct *p, int user_tick)
4715 cputime_t one_jiffy = jiffies_to_cputime(1);
4716 cputime_t one_jiffy_scaled = cputime_to_scaled(one_jiffy);
4717 struct rq *rq = this_rq();
4720 account_user_time(p, one_jiffy, one_jiffy_scaled);
4721 else if (p != rq->idle)
4722 account_system_time(p, HARDIRQ_OFFSET, one_jiffy,
4725 account_idle_time(one_jiffy);
4729 * Account multiple ticks of steal time.
4730 * @p: the process from which the cpu time has been stolen
4731 * @ticks: number of stolen ticks
4733 void account_steal_ticks(unsigned long ticks)
4735 account_steal_time(jiffies_to_cputime(ticks));
4739 * Account multiple ticks of idle time.
4740 * @ticks: number of stolen ticks
4742 void account_idle_ticks(unsigned long ticks)
4744 account_idle_time(jiffies_to_cputime(ticks));
4750 * Use precise platform statistics if available:
4752 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
4753 cputime_t task_utime(struct task_struct *p)
4758 cputime_t task_stime(struct task_struct *p)
4763 cputime_t task_utime(struct task_struct *p)
4765 clock_t utime = cputime_to_clock_t(p->utime),
4766 total = utime + cputime_to_clock_t(p->stime);
4770 * Use CFS's precise accounting:
4772 temp = (u64)nsec_to_clock_t(p->se.sum_exec_runtime);
4776 do_div(temp, total);
4778 utime = (clock_t)temp;
4780 p->prev_utime = max(p->prev_utime, clock_t_to_cputime(utime));
4781 return p->prev_utime;
4784 cputime_t task_stime(struct task_struct *p)
4789 * Use CFS's precise accounting. (we subtract utime from
4790 * the total, to make sure the total observed by userspace
4791 * grows monotonically - apps rely on that):
4793 stime = nsec_to_clock_t(p->se.sum_exec_runtime) -
4794 cputime_to_clock_t(task_utime(p));
4797 p->prev_stime = max(p->prev_stime, clock_t_to_cputime(stime));
4799 return p->prev_stime;
4803 inline cputime_t task_gtime(struct task_struct *p)
4809 * This function gets called by the timer code, with HZ frequency.
4810 * We call it with interrupts disabled.
4812 * It also gets called by the fork code, when changing the parent's
4815 void scheduler_tick(void)
4817 int cpu = smp_processor_id();
4818 struct rq *rq = cpu_rq(cpu);
4819 struct task_struct *curr = rq->curr;
4823 spin_lock(&rq->lock);
4824 update_rq_clock(rq);
4825 update_cpu_load(rq);
4826 curr->sched_class->task_tick(rq, curr, 0);
4827 perf_counter_task_tick(curr, cpu);
4828 spin_unlock(&rq->lock);
4831 rq->idle_at_tick = idle_cpu(cpu);
4832 trigger_load_balance(rq, cpu);
4836 unsigned long get_parent_ip(unsigned long addr)
4838 if (in_lock_functions(addr)) {
4839 addr = CALLER_ADDR2;
4840 if (in_lock_functions(addr))
4841 addr = CALLER_ADDR3;
4846 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4847 defined(CONFIG_PREEMPT_TRACER))
4849 void __kprobes add_preempt_count(int val)
4851 #ifdef CONFIG_DEBUG_PREEMPT
4855 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4858 preempt_count() += val;
4859 #ifdef CONFIG_DEBUG_PREEMPT
4861 * Spinlock count overflowing soon?
4863 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4866 if (preempt_count() == val)
4867 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4869 EXPORT_SYMBOL(add_preempt_count);
4871 void __kprobes sub_preempt_count(int val)
4873 #ifdef CONFIG_DEBUG_PREEMPT
4877 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4880 * Is the spinlock portion underflowing?
4882 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4883 !(preempt_count() & PREEMPT_MASK)))
4887 if (preempt_count() == val)
4888 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4889 preempt_count() -= val;
4891 EXPORT_SYMBOL(sub_preempt_count);
4896 * Print scheduling while atomic bug:
4898 static noinline void __schedule_bug(struct task_struct *prev)
4900 struct pt_regs *regs = get_irq_regs();
4902 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4903 prev->comm, prev->pid, preempt_count());
4905 debug_show_held_locks(prev);
4907 if (irqs_disabled())
4908 print_irqtrace_events(prev);
4917 * Various schedule()-time debugging checks and statistics:
4919 static inline void schedule_debug(struct task_struct *prev)
4922 * Test if we are atomic. Since do_exit() needs to call into
4923 * schedule() atomically, we ignore that path for now.
4924 * Otherwise, whine if we are scheduling when we should not be.
4926 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
4927 __schedule_bug(prev);
4929 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4931 schedstat_inc(this_rq(), sched_count);
4932 #ifdef CONFIG_SCHEDSTATS
4933 if (unlikely(prev->lock_depth >= 0)) {
4934 schedstat_inc(this_rq(), bkl_count);
4935 schedstat_inc(prev, sched_info.bkl_count);
4940 static void put_prev_task(struct rq *rq, struct task_struct *prev)
4942 if (prev->state == TASK_RUNNING) {
4943 u64 runtime = prev->se.sum_exec_runtime;
4945 runtime -= prev->se.prev_sum_exec_runtime;
4946 runtime = min_t(u64, runtime, 2*sysctl_sched_migration_cost);
4949 * In order to avoid avg_overlap growing stale when we are
4950 * indeed overlapping and hence not getting put to sleep, grow
4951 * the avg_overlap on preemption.
4953 * We use the average preemption runtime because that
4954 * correlates to the amount of cache footprint a task can
4957 update_avg(&prev->se.avg_overlap, runtime);
4959 prev->sched_class->put_prev_task(rq, prev);
4963 * Pick up the highest-prio task:
4965 static inline struct task_struct *
4966 pick_next_task(struct rq *rq)
4968 const struct sched_class *class;
4969 struct task_struct *p;
4972 * Optimization: we know that if all tasks are in
4973 * the fair class we can call that function directly:
4975 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4976 p = fair_sched_class.pick_next_task(rq);
4981 class = sched_class_highest;
4983 p = class->pick_next_task(rq);
4987 * Will never be NULL as the idle class always
4988 * returns a non-NULL p:
4990 class = class->next;
4995 * schedule() is the main scheduler function.
4997 asmlinkage void __sched __schedule(void)
4999 struct task_struct *prev, *next;
5000 unsigned long *switch_count;
5004 cpu = smp_processor_id();
5008 switch_count = &prev->nivcsw;
5010 release_kernel_lock(prev);
5011 need_resched_nonpreemptible:
5013 schedule_debug(prev);
5015 if (sched_feat(HRTICK))
5018 spin_lock_irq(&rq->lock);
5019 update_rq_clock(rq);
5020 clear_tsk_need_resched(prev);
5022 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
5023 if (unlikely(signal_pending_state(prev->state, prev)))
5024 prev->state = TASK_RUNNING;
5026 deactivate_task(rq, prev, 1);
5027 switch_count = &prev->nvcsw;
5031 if (prev->sched_class->pre_schedule)
5032 prev->sched_class->pre_schedule(rq, prev);
5035 if (unlikely(!rq->nr_running))
5036 idle_balance(cpu, rq);
5038 put_prev_task(rq, prev);
5039 next = pick_next_task(rq);
5041 if (likely(prev != next)) {
5042 sched_info_switch(prev, next);
5043 perf_counter_task_sched_out(prev, cpu);
5049 context_switch(rq, prev, next); /* unlocks the rq */
5051 * the context switch might have flipped the stack from under
5052 * us, hence refresh the local variables.
5054 cpu = smp_processor_id();
5057 spin_unlock_irq(&rq->lock);
5059 if (unlikely(reacquire_kernel_lock(current) < 0))
5060 goto need_resched_nonpreemptible;
5063 asmlinkage void __sched schedule(void)
5068 preempt_enable_no_resched();
5069 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
5072 EXPORT_SYMBOL(schedule);
5076 * Look out! "owner" is an entirely speculative pointer
5077 * access and not reliable.
5079 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
5084 if (!sched_feat(OWNER_SPIN))
5087 #ifdef CONFIG_DEBUG_PAGEALLOC
5089 * Need to access the cpu field knowing that
5090 * DEBUG_PAGEALLOC could have unmapped it if
5091 * the mutex owner just released it and exited.
5093 if (probe_kernel_address(&owner->cpu, cpu))
5100 * Even if the access succeeded (likely case),
5101 * the cpu field may no longer be valid.
5103 if (cpu >= nr_cpumask_bits)
5107 * We need to validate that we can do a
5108 * get_cpu() and that we have the percpu area.
5110 if (!cpu_online(cpu))
5117 * Owner changed, break to re-assess state.
5119 if (lock->owner != owner)
5123 * Is that owner really running on that cpu?
5125 if (task_thread_info(rq->curr) != owner || need_resched())
5135 #ifdef CONFIG_PREEMPT
5137 * this is the entry point to schedule() from in-kernel preemption
5138 * off of preempt_enable. Kernel preemptions off return from interrupt
5139 * occur there and call schedule directly.
5141 asmlinkage void __sched preempt_schedule(void)
5143 struct thread_info *ti = current_thread_info();
5146 * If there is a non-zero preempt_count or interrupts are disabled,
5147 * we do not want to preempt the current task. Just return..
5149 if (likely(ti->preempt_count || irqs_disabled()))
5153 add_preempt_count(PREEMPT_ACTIVE);
5155 sub_preempt_count(PREEMPT_ACTIVE);
5158 * Check again in case we missed a preemption opportunity
5159 * between schedule and now.
5162 } while (need_resched());
5164 EXPORT_SYMBOL(preempt_schedule);
5167 * this is the entry point to schedule() from kernel preemption
5168 * off of irq context.
5169 * Note, that this is called and return with irqs disabled. This will
5170 * protect us against recursive calling from irq.
5172 asmlinkage void __sched preempt_schedule_irq(void)
5174 struct thread_info *ti = current_thread_info();
5176 /* Catch callers which need to be fixed */
5177 BUG_ON(ti->preempt_count || !irqs_disabled());
5180 add_preempt_count(PREEMPT_ACTIVE);
5183 local_irq_disable();
5184 sub_preempt_count(PREEMPT_ACTIVE);
5187 * Check again in case we missed a preemption opportunity
5188 * between schedule and now.
5191 } while (need_resched());
5194 #endif /* CONFIG_PREEMPT */
5196 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
5199 return try_to_wake_up(curr->private, mode, sync);
5201 EXPORT_SYMBOL(default_wake_function);
5204 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
5205 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
5206 * number) then we wake all the non-exclusive tasks and one exclusive task.
5208 * There are circumstances in which we can try to wake a task which has already
5209 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
5210 * zero in this (rare) case, and we handle it by continuing to scan the queue.
5212 void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
5213 int nr_exclusive, int sync, void *key)
5215 wait_queue_t *curr, *next;
5217 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
5218 unsigned flags = curr->flags;
5220 if (curr->func(curr, mode, sync, key) &&
5221 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
5227 * __wake_up - wake up threads blocked on a waitqueue.
5229 * @mode: which threads
5230 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5231 * @key: is directly passed to the wakeup function
5233 void __wake_up(wait_queue_head_t *q, unsigned int mode,
5234 int nr_exclusive, void *key)
5236 unsigned long flags;
5238 spin_lock_irqsave(&q->lock, flags);
5239 __wake_up_common(q, mode, nr_exclusive, 0, key);
5240 spin_unlock_irqrestore(&q->lock, flags);
5242 EXPORT_SYMBOL(__wake_up);
5245 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
5247 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
5249 __wake_up_common(q, mode, 1, 0, NULL);
5252 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
5254 __wake_up_common(q, mode, 1, 0, key);
5258 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
5260 * @mode: which threads
5261 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5262 * @key: opaque value to be passed to wakeup targets
5264 * The sync wakeup differs that the waker knows that it will schedule
5265 * away soon, so while the target thread will be woken up, it will not
5266 * be migrated to another CPU - ie. the two threads are 'synchronized'
5267 * with each other. This can prevent needless bouncing between CPUs.
5269 * On UP it can prevent extra preemption.
5271 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
5272 int nr_exclusive, void *key)
5274 unsigned long flags;
5280 if (unlikely(!nr_exclusive))
5283 spin_lock_irqsave(&q->lock, flags);
5284 __wake_up_common(q, mode, nr_exclusive, sync, key);
5285 spin_unlock_irqrestore(&q->lock, flags);
5287 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
5290 * __wake_up_sync - see __wake_up_sync_key()
5292 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
5294 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
5296 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
5299 * complete: - signals a single thread waiting on this completion
5300 * @x: holds the state of this particular completion
5302 * This will wake up a single thread waiting on this completion. Threads will be
5303 * awakened in the same order in which they were queued.
5305 * See also complete_all(), wait_for_completion() and related routines.
5307 void complete(struct completion *x)
5309 unsigned long flags;
5311 spin_lock_irqsave(&x->wait.lock, flags);
5313 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
5314 spin_unlock_irqrestore(&x->wait.lock, flags);
5316 EXPORT_SYMBOL(complete);
5319 * complete_all: - signals all threads waiting on this completion
5320 * @x: holds the state of this particular completion
5322 * This will wake up all threads waiting on this particular completion event.
5324 void complete_all(struct completion *x)
5326 unsigned long flags;
5328 spin_lock_irqsave(&x->wait.lock, flags);
5329 x->done += UINT_MAX/2;
5330 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
5331 spin_unlock_irqrestore(&x->wait.lock, flags);
5333 EXPORT_SYMBOL(complete_all);
5335 static inline long __sched
5336 do_wait_for_common(struct completion *x, long timeout, int state)
5339 DECLARE_WAITQUEUE(wait, current);
5341 wait.flags |= WQ_FLAG_EXCLUSIVE;
5342 __add_wait_queue_tail(&x->wait, &wait);
5344 if (signal_pending_state(state, current)) {
5345 timeout = -ERESTARTSYS;
5348 __set_current_state(state);
5349 spin_unlock_irq(&x->wait.lock);
5350 timeout = schedule_timeout(timeout);
5351 spin_lock_irq(&x->wait.lock);
5352 } while (!x->done && timeout);
5353 __remove_wait_queue(&x->wait, &wait);
5358 return timeout ?: 1;
5362 wait_for_common(struct completion *x, long timeout, int state)
5366 spin_lock_irq(&x->wait.lock);
5367 timeout = do_wait_for_common(x, timeout, state);
5368 spin_unlock_irq(&x->wait.lock);
5373 * wait_for_completion: - waits for completion of a task
5374 * @x: holds the state of this particular completion
5376 * This waits to be signaled for completion of a specific task. It is NOT
5377 * interruptible and there is no timeout.
5379 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
5380 * and interrupt capability. Also see complete().
5382 void __sched wait_for_completion(struct completion *x)
5384 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
5386 EXPORT_SYMBOL(wait_for_completion);
5389 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
5390 * @x: holds the state of this particular completion
5391 * @timeout: timeout value in jiffies
5393 * This waits for either a completion of a specific task to be signaled or for a
5394 * specified timeout to expire. The timeout is in jiffies. It is not
5397 unsigned long __sched
5398 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
5400 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
5402 EXPORT_SYMBOL(wait_for_completion_timeout);
5405 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
5406 * @x: holds the state of this particular completion
5408 * This waits for completion of a specific task to be signaled. It is
5411 int __sched wait_for_completion_interruptible(struct completion *x)
5413 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
5414 if (t == -ERESTARTSYS)
5418 EXPORT_SYMBOL(wait_for_completion_interruptible);
5421 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
5422 * @x: holds the state of this particular completion
5423 * @timeout: timeout value in jiffies
5425 * This waits for either a completion of a specific task to be signaled or for a
5426 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
5428 unsigned long __sched
5429 wait_for_completion_interruptible_timeout(struct completion *x,
5430 unsigned long timeout)
5432 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
5434 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
5437 * wait_for_completion_killable: - waits for completion of a task (killable)
5438 * @x: holds the state of this particular completion
5440 * This waits to be signaled for completion of a specific task. It can be
5441 * interrupted by a kill signal.
5443 int __sched wait_for_completion_killable(struct completion *x)
5445 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
5446 if (t == -ERESTARTSYS)
5450 EXPORT_SYMBOL(wait_for_completion_killable);
5453 * try_wait_for_completion - try to decrement a completion without blocking
5454 * @x: completion structure
5456 * Returns: 0 if a decrement cannot be done without blocking
5457 * 1 if a decrement succeeded.
5459 * If a completion is being used as a counting completion,
5460 * attempt to decrement the counter without blocking. This
5461 * enables us to avoid waiting if the resource the completion
5462 * is protecting is not available.
5464 bool try_wait_for_completion(struct completion *x)
5468 spin_lock_irq(&x->wait.lock);
5473 spin_unlock_irq(&x->wait.lock);
5476 EXPORT_SYMBOL(try_wait_for_completion);
5479 * completion_done - Test to see if a completion has any waiters
5480 * @x: completion structure
5482 * Returns: 0 if there are waiters (wait_for_completion() in progress)
5483 * 1 if there are no waiters.
5486 bool completion_done(struct completion *x)
5490 spin_lock_irq(&x->wait.lock);
5493 spin_unlock_irq(&x->wait.lock);
5496 EXPORT_SYMBOL(completion_done);
5499 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
5501 unsigned long flags;
5504 init_waitqueue_entry(&wait, current);
5506 __set_current_state(state);
5508 spin_lock_irqsave(&q->lock, flags);
5509 __add_wait_queue(q, &wait);
5510 spin_unlock(&q->lock);
5511 timeout = schedule_timeout(timeout);
5512 spin_lock_irq(&q->lock);
5513 __remove_wait_queue(q, &wait);
5514 spin_unlock_irqrestore(&q->lock, flags);
5519 void __sched interruptible_sleep_on(wait_queue_head_t *q)
5521 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5523 EXPORT_SYMBOL(interruptible_sleep_on);
5526 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
5528 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
5530 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
5532 void __sched sleep_on(wait_queue_head_t *q)
5534 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
5536 EXPORT_SYMBOL(sleep_on);
5538 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
5540 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
5542 EXPORT_SYMBOL(sleep_on_timeout);
5544 #ifdef CONFIG_RT_MUTEXES
5547 * rt_mutex_setprio - set the current priority of a task
5549 * @prio: prio value (kernel-internal form)
5551 * This function changes the 'effective' priority of a task. It does
5552 * not touch ->normal_prio like __setscheduler().
5554 * Used by the rt_mutex code to implement priority inheritance logic.
5556 void rt_mutex_setprio(struct task_struct *p, int prio)
5558 unsigned long flags;
5559 int oldprio, on_rq, running;
5561 const struct sched_class *prev_class = p->sched_class;
5563 BUG_ON(prio < 0 || prio > MAX_PRIO);
5565 rq = task_rq_lock(p, &flags);
5566 update_rq_clock(rq);
5569 on_rq = p->se.on_rq;
5570 running = task_current(rq, p);
5572 dequeue_task(rq, p, 0);
5574 p->sched_class->put_prev_task(rq, p);
5577 p->sched_class = &rt_sched_class;
5579 p->sched_class = &fair_sched_class;
5584 p->sched_class->set_curr_task(rq);
5586 enqueue_task(rq, p, 0);
5588 check_class_changed(rq, p, prev_class, oldprio, running);
5590 task_rq_unlock(rq, &flags);
5595 void set_user_nice(struct task_struct *p, long nice)
5597 int old_prio, delta, on_rq;
5598 unsigned long flags;
5601 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
5604 * We have to be careful, if called from sys_setpriority(),
5605 * the task might be in the middle of scheduling on another CPU.
5607 rq = task_rq_lock(p, &flags);
5608 update_rq_clock(rq);
5610 * The RT priorities are set via sched_setscheduler(), but we still
5611 * allow the 'normal' nice value to be set - but as expected
5612 * it wont have any effect on scheduling until the task is
5613 * SCHED_FIFO/SCHED_RR:
5615 if (task_has_rt_policy(p)) {
5616 p->static_prio = NICE_TO_PRIO(nice);
5619 on_rq = p->se.on_rq;
5621 dequeue_task(rq, p, 0);
5623 p->static_prio = NICE_TO_PRIO(nice);
5626 p->prio = effective_prio(p);
5627 delta = p->prio - old_prio;
5630 enqueue_task(rq, p, 0);
5632 * If the task increased its priority or is running and
5633 * lowered its priority, then reschedule its CPU:
5635 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5636 resched_task(rq->curr);
5639 task_rq_unlock(rq, &flags);
5641 EXPORT_SYMBOL(set_user_nice);
5644 * can_nice - check if a task can reduce its nice value
5648 int can_nice(const struct task_struct *p, const int nice)
5650 /* convert nice value [19,-20] to rlimit style value [1,40] */
5651 int nice_rlim = 20 - nice;
5653 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5654 capable(CAP_SYS_NICE));
5657 #ifdef __ARCH_WANT_SYS_NICE
5660 * sys_nice - change the priority of the current process.
5661 * @increment: priority increment
5663 * sys_setpriority is a more generic, but much slower function that
5664 * does similar things.
5666 SYSCALL_DEFINE1(nice, int, increment)
5671 * Setpriority might change our priority at the same moment.
5672 * We don't have to worry. Conceptually one call occurs first
5673 * and we have a single winner.
5675 if (increment < -40)
5680 nice = TASK_NICE(current) + increment;
5686 if (increment < 0 && !can_nice(current, nice))
5689 retval = security_task_setnice(current, nice);
5693 set_user_nice(current, nice);
5700 * task_prio - return the priority value of a given task.
5701 * @p: the task in question.
5703 * This is the priority value as seen by users in /proc.
5704 * RT tasks are offset by -200. Normal tasks are centered
5705 * around 0, value goes from -16 to +15.
5707 int task_prio(const struct task_struct *p)
5709 return p->prio - MAX_RT_PRIO;
5713 * task_nice - return the nice value of a given task.
5714 * @p: the task in question.
5716 int task_nice(const struct task_struct *p)
5718 return TASK_NICE(p);
5720 EXPORT_SYMBOL(task_nice);
5723 * idle_cpu - is a given cpu idle currently?
5724 * @cpu: the processor in question.
5726 int idle_cpu(int cpu)
5728 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5732 * idle_task - return the idle task for a given cpu.
5733 * @cpu: the processor in question.
5735 struct task_struct *idle_task(int cpu)
5737 return cpu_rq(cpu)->idle;
5741 * find_process_by_pid - find a process with a matching PID value.
5742 * @pid: the pid in question.
5744 static struct task_struct *find_process_by_pid(pid_t pid)
5746 return pid ? find_task_by_vpid(pid) : current;
5749 /* Actually do priority change: must hold rq lock. */
5751 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5753 BUG_ON(p->se.on_rq);
5756 switch (p->policy) {
5760 p->sched_class = &fair_sched_class;
5764 p->sched_class = &rt_sched_class;
5768 p->rt_priority = prio;
5769 p->normal_prio = normal_prio(p);
5770 /* we are holding p->pi_lock already */
5771 p->prio = rt_mutex_getprio(p);
5776 * check the target process has a UID that matches the current process's
5778 static bool check_same_owner(struct task_struct *p)
5780 const struct cred *cred = current_cred(), *pcred;
5784 pcred = __task_cred(p);
5785 match = (cred->euid == pcred->euid ||
5786 cred->euid == pcred->uid);
5791 static int __sched_setscheduler(struct task_struct *p, int policy,
5792 struct sched_param *param, bool user)
5794 int retval, oldprio, oldpolicy = -1, on_rq, running;
5795 unsigned long flags;
5796 const struct sched_class *prev_class = p->sched_class;
5799 /* may grab non-irq protected spin_locks */
5800 BUG_ON(in_interrupt());
5802 /* double check policy once rq lock held */
5804 policy = oldpolicy = p->policy;
5805 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5806 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5807 policy != SCHED_IDLE)
5810 * Valid priorities for SCHED_FIFO and SCHED_RR are
5811 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5812 * SCHED_BATCH and SCHED_IDLE is 0.
5814 if (param->sched_priority < 0 ||
5815 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5816 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5818 if (rt_policy(policy) != (param->sched_priority != 0))
5822 * Allow unprivileged RT tasks to decrease priority:
5824 if (user && !capable(CAP_SYS_NICE)) {
5825 if (rt_policy(policy)) {
5826 unsigned long rlim_rtprio;
5828 if (!lock_task_sighand(p, &flags))
5830 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5831 unlock_task_sighand(p, &flags);
5833 /* can't set/change the rt policy */
5834 if (policy != p->policy && !rlim_rtprio)
5837 /* can't increase priority */
5838 if (param->sched_priority > p->rt_priority &&
5839 param->sched_priority > rlim_rtprio)
5843 * Like positive nice levels, dont allow tasks to
5844 * move out of SCHED_IDLE either:
5846 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5849 /* can't change other user's priorities */
5850 if (!check_same_owner(p))
5855 #ifdef CONFIG_RT_GROUP_SCHED
5857 * Do not allow realtime tasks into groups that have no runtime
5860 if (rt_bandwidth_enabled() && rt_policy(policy) &&
5861 task_group(p)->rt_bandwidth.rt_runtime == 0)
5865 retval = security_task_setscheduler(p, policy, param);
5871 * make sure no PI-waiters arrive (or leave) while we are
5872 * changing the priority of the task:
5874 spin_lock_irqsave(&p->pi_lock, flags);
5876 * To be able to change p->policy safely, the apropriate
5877 * runqueue lock must be held.
5879 rq = __task_rq_lock(p);
5880 /* recheck policy now with rq lock held */
5881 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5882 policy = oldpolicy = -1;
5883 __task_rq_unlock(rq);
5884 spin_unlock_irqrestore(&p->pi_lock, flags);
5887 update_rq_clock(rq);
5888 on_rq = p->se.on_rq;
5889 running = task_current(rq, p);
5891 deactivate_task(rq, p, 0);
5893 p->sched_class->put_prev_task(rq, p);
5896 __setscheduler(rq, p, policy, param->sched_priority);
5899 p->sched_class->set_curr_task(rq);
5901 activate_task(rq, p, 0);
5903 check_class_changed(rq, p, prev_class, oldprio, running);
5905 __task_rq_unlock(rq);
5906 spin_unlock_irqrestore(&p->pi_lock, flags);
5908 rt_mutex_adjust_pi(p);
5914 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5915 * @p: the task in question.
5916 * @policy: new policy.
5917 * @param: structure containing the new RT priority.
5919 * NOTE that the task may be already dead.
5921 int sched_setscheduler(struct task_struct *p, int policy,
5922 struct sched_param *param)
5924 return __sched_setscheduler(p, policy, param, true);
5926 EXPORT_SYMBOL_GPL(sched_setscheduler);
5929 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5930 * @p: the task in question.
5931 * @policy: new policy.
5932 * @param: structure containing the new RT priority.
5934 * Just like sched_setscheduler, only don't bother checking if the
5935 * current context has permission. For example, this is needed in
5936 * stop_machine(): we create temporary high priority worker threads,
5937 * but our caller might not have that capability.
5939 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5940 struct sched_param *param)
5942 return __sched_setscheduler(p, policy, param, false);
5946 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5948 struct sched_param lparam;
5949 struct task_struct *p;
5952 if (!param || pid < 0)
5954 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5959 p = find_process_by_pid(pid);
5961 retval = sched_setscheduler(p, policy, &lparam);
5968 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5969 * @pid: the pid in question.
5970 * @policy: new policy.
5971 * @param: structure containing the new RT priority.
5973 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
5974 struct sched_param __user *, param)
5976 /* negative values for policy are not valid */
5980 return do_sched_setscheduler(pid, policy, param);
5984 * sys_sched_setparam - set/change the RT priority of a thread
5985 * @pid: the pid in question.
5986 * @param: structure containing the new RT priority.
5988 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
5990 return do_sched_setscheduler(pid, -1, param);
5994 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5995 * @pid: the pid in question.
5997 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
5999 struct task_struct *p;
6006 read_lock(&tasklist_lock);
6007 p = find_process_by_pid(pid);
6009 retval = security_task_getscheduler(p);
6013 read_unlock(&tasklist_lock);
6018 * sys_sched_getscheduler - get the RT priority of a thread
6019 * @pid: the pid in question.
6020 * @param: structure containing the RT priority.
6022 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
6024 struct sched_param lp;
6025 struct task_struct *p;
6028 if (!param || pid < 0)
6031 read_lock(&tasklist_lock);
6032 p = find_process_by_pid(pid);
6037 retval = security_task_getscheduler(p);
6041 lp.sched_priority = p->rt_priority;
6042 read_unlock(&tasklist_lock);
6045 * This one might sleep, we cannot do it with a spinlock held ...
6047 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
6052 read_unlock(&tasklist_lock);
6056 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
6058 cpumask_var_t cpus_allowed, new_mask;
6059 struct task_struct *p;
6063 read_lock(&tasklist_lock);
6065 p = find_process_by_pid(pid);
6067 read_unlock(&tasklist_lock);
6073 * It is not safe to call set_cpus_allowed with the
6074 * tasklist_lock held. We will bump the task_struct's
6075 * usage count and then drop tasklist_lock.
6078 read_unlock(&tasklist_lock);
6080 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
6084 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
6086 goto out_free_cpus_allowed;
6089 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
6092 retval = security_task_setscheduler(p, 0, NULL);
6096 cpuset_cpus_allowed(p, cpus_allowed);
6097 cpumask_and(new_mask, in_mask, cpus_allowed);
6099 retval = set_cpus_allowed_ptr(p, new_mask);
6102 cpuset_cpus_allowed(p, cpus_allowed);
6103 if (!cpumask_subset(new_mask, cpus_allowed)) {
6105 * We must have raced with a concurrent cpuset
6106 * update. Just reset the cpus_allowed to the
6107 * cpuset's cpus_allowed
6109 cpumask_copy(new_mask, cpus_allowed);
6114 free_cpumask_var(new_mask);
6115 out_free_cpus_allowed:
6116 free_cpumask_var(cpus_allowed);
6123 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
6124 struct cpumask *new_mask)
6126 if (len < cpumask_size())
6127 cpumask_clear(new_mask);
6128 else if (len > cpumask_size())
6129 len = cpumask_size();
6131 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6135 * sys_sched_setaffinity - set the cpu affinity of a process
6136 * @pid: pid of the process
6137 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6138 * @user_mask_ptr: user-space pointer to the new cpu mask
6140 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6141 unsigned long __user *, user_mask_ptr)
6143 cpumask_var_t new_mask;
6146 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6149 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6151 retval = sched_setaffinity(pid, new_mask);
6152 free_cpumask_var(new_mask);
6156 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6158 struct task_struct *p;
6162 read_lock(&tasklist_lock);
6165 p = find_process_by_pid(pid);
6169 retval = security_task_getscheduler(p);
6173 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
6176 read_unlock(&tasklist_lock);
6183 * sys_sched_getaffinity - get the cpu affinity of a process
6184 * @pid: pid of the process
6185 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6186 * @user_mask_ptr: user-space pointer to hold the current cpu mask
6188 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6189 unsigned long __user *, user_mask_ptr)
6194 if (len < cpumask_size())
6197 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
6200 ret = sched_getaffinity(pid, mask);
6202 if (copy_to_user(user_mask_ptr, mask, cpumask_size()))
6205 ret = cpumask_size();
6207 free_cpumask_var(mask);
6213 * sys_sched_yield - yield the current processor to other threads.
6215 * This function yields the current CPU to other tasks. If there are no
6216 * other threads running on this CPU then this function will return.
6218 SYSCALL_DEFINE0(sched_yield)
6220 struct rq *rq = this_rq_lock();
6222 schedstat_inc(rq, yld_count);
6223 current->sched_class->yield_task(rq);
6226 * Since we are going to call schedule() anyway, there's
6227 * no need to preempt or enable interrupts:
6229 __release(rq->lock);
6230 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
6231 _raw_spin_unlock(&rq->lock);
6232 preempt_enable_no_resched();
6239 static void __cond_resched(void)
6241 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6242 __might_sleep(__FILE__, __LINE__);
6245 * The BKS might be reacquired before we have dropped
6246 * PREEMPT_ACTIVE, which could trigger a second
6247 * cond_resched() call.
6250 add_preempt_count(PREEMPT_ACTIVE);
6252 sub_preempt_count(PREEMPT_ACTIVE);
6253 } while (need_resched());
6256 int __sched _cond_resched(void)
6258 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
6259 system_state == SYSTEM_RUNNING) {
6265 EXPORT_SYMBOL(_cond_resched);
6268 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
6269 * call schedule, and on return reacquire the lock.
6271 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
6272 * operations here to prevent schedule() from being called twice (once via
6273 * spin_unlock(), once by hand).
6275 int cond_resched_lock(spinlock_t *lock)
6277 int resched = need_resched() && system_state == SYSTEM_RUNNING;
6280 if (spin_needbreak(lock) || resched) {
6282 if (resched && need_resched())
6291 EXPORT_SYMBOL(cond_resched_lock);
6293 int __sched cond_resched_softirq(void)
6295 BUG_ON(!in_softirq());
6297 if (need_resched() && system_state == SYSTEM_RUNNING) {
6305 EXPORT_SYMBOL(cond_resched_softirq);
6308 * yield - yield the current processor to other threads.
6310 * This is a shortcut for kernel-space yielding - it marks the
6311 * thread runnable and calls sys_sched_yield().
6313 void __sched yield(void)
6315 set_current_state(TASK_RUNNING);
6318 EXPORT_SYMBOL(yield);
6321 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6322 * that process accounting knows that this is a task in IO wait state.
6324 * But don't do that if it is a deliberate, throttling IO wait (this task
6325 * has set its backing_dev_info: the queue against which it should throttle)
6327 void __sched io_schedule(void)
6329 struct rq *rq = &__raw_get_cpu_var(runqueues);
6331 delayacct_blkio_start();
6332 atomic_inc(&rq->nr_iowait);
6334 atomic_dec(&rq->nr_iowait);
6335 delayacct_blkio_end();
6337 EXPORT_SYMBOL(io_schedule);
6339 long __sched io_schedule_timeout(long timeout)
6341 struct rq *rq = &__raw_get_cpu_var(runqueues);
6344 delayacct_blkio_start();
6345 atomic_inc(&rq->nr_iowait);
6346 ret = schedule_timeout(timeout);
6347 atomic_dec(&rq->nr_iowait);
6348 delayacct_blkio_end();
6353 * sys_sched_get_priority_max - return maximum RT priority.
6354 * @policy: scheduling class.
6356 * this syscall returns the maximum rt_priority that can be used
6357 * by a given scheduling class.
6359 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6366 ret = MAX_USER_RT_PRIO-1;
6378 * sys_sched_get_priority_min - return minimum RT priority.
6379 * @policy: scheduling class.
6381 * this syscall returns the minimum rt_priority that can be used
6382 * by a given scheduling class.
6384 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6402 * sys_sched_rr_get_interval - return the default timeslice of a process.
6403 * @pid: pid of the process.
6404 * @interval: userspace pointer to the timeslice value.
6406 * this syscall writes the default timeslice value of a given process
6407 * into the user-space timespec buffer. A value of '0' means infinity.
6409 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
6410 struct timespec __user *, interval)
6412 struct task_struct *p;
6413 unsigned int time_slice;
6421 read_lock(&tasklist_lock);
6422 p = find_process_by_pid(pid);
6426 retval = security_task_getscheduler(p);
6431 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
6432 * tasks that are on an otherwise idle runqueue:
6435 if (p->policy == SCHED_RR) {
6436 time_slice = DEF_TIMESLICE;
6437 } else if (p->policy != SCHED_FIFO) {
6438 struct sched_entity *se = &p->se;
6439 unsigned long flags;
6442 rq = task_rq_lock(p, &flags);
6443 if (rq->cfs.load.weight)
6444 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
6445 task_rq_unlock(rq, &flags);
6447 read_unlock(&tasklist_lock);
6448 jiffies_to_timespec(time_slice, &t);
6449 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
6453 read_unlock(&tasklist_lock);
6457 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
6459 void sched_show_task(struct task_struct *p)
6461 unsigned long free = 0;
6464 state = p->state ? __ffs(p->state) + 1 : 0;
6465 printk(KERN_INFO "%-13.13s %c", p->comm,
6466 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
6467 #if BITS_PER_LONG == 32
6468 if (state == TASK_RUNNING)
6469 printk(KERN_CONT " running ");
6471 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
6473 if (state == TASK_RUNNING)
6474 printk(KERN_CONT " running task ");
6476 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
6478 #ifdef CONFIG_DEBUG_STACK_USAGE
6479 free = stack_not_used(p);
6481 printk(KERN_CONT "%5lu %5d %6d\n", free,
6482 task_pid_nr(p), task_pid_nr(p->real_parent));
6484 show_stack(p, NULL);
6487 void show_state_filter(unsigned long state_filter)
6489 struct task_struct *g, *p;
6491 #if BITS_PER_LONG == 32
6493 " task PC stack pid father\n");
6496 " task PC stack pid father\n");
6498 read_lock(&tasklist_lock);
6499 do_each_thread(g, p) {
6501 * reset the NMI-timeout, listing all files on a slow
6502 * console might take alot of time:
6504 touch_nmi_watchdog();
6505 if (!state_filter || (p->state & state_filter))
6507 } while_each_thread(g, p);
6509 touch_all_softlockup_watchdogs();
6511 #ifdef CONFIG_SCHED_DEBUG
6512 sysrq_sched_debug_show();
6514 read_unlock(&tasklist_lock);
6516 * Only show locks if all tasks are dumped:
6518 if (state_filter == -1)
6519 debug_show_all_locks();
6522 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
6524 idle->sched_class = &idle_sched_class;
6528 * init_idle - set up an idle thread for a given CPU
6529 * @idle: task in question
6530 * @cpu: cpu the idle task belongs to
6532 * NOTE: this function does not set the idle thread's NEED_RESCHED
6533 * flag, to make booting more robust.
6535 void __cpuinit init_idle(struct task_struct *idle, int cpu)
6537 struct rq *rq = cpu_rq(cpu);
6538 unsigned long flags;
6540 spin_lock_irqsave(&rq->lock, flags);
6543 idle->se.exec_start = sched_clock();
6545 idle->prio = idle->normal_prio = MAX_PRIO;
6546 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
6547 __set_task_cpu(idle, cpu);
6549 rq->curr = rq->idle = idle;
6550 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
6553 spin_unlock_irqrestore(&rq->lock, flags);
6555 /* Set the preempt count _outside_ the spinlocks! */
6556 #if defined(CONFIG_PREEMPT)
6557 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
6559 task_thread_info(idle)->preempt_count = 0;
6562 * The idle tasks have their own, simple scheduling class:
6564 idle->sched_class = &idle_sched_class;
6565 ftrace_graph_init_task(idle);
6569 * In a system that switches off the HZ timer nohz_cpu_mask
6570 * indicates which cpus entered this state. This is used
6571 * in the rcu update to wait only for active cpus. For system
6572 * which do not switch off the HZ timer nohz_cpu_mask should
6573 * always be CPU_BITS_NONE.
6575 cpumask_var_t nohz_cpu_mask;
6578 * Increase the granularity value when there are more CPUs,
6579 * because with more CPUs the 'effective latency' as visible
6580 * to users decreases. But the relationship is not linear,
6581 * so pick a second-best guess by going with the log2 of the
6584 * This idea comes from the SD scheduler of Con Kolivas:
6586 static inline void sched_init_granularity(void)
6588 unsigned int factor = 1 + ilog2(num_online_cpus());
6589 const unsigned long limit = 200000000;
6591 sysctl_sched_min_granularity *= factor;
6592 if (sysctl_sched_min_granularity > limit)
6593 sysctl_sched_min_granularity = limit;
6595 sysctl_sched_latency *= factor;
6596 if (sysctl_sched_latency > limit)
6597 sysctl_sched_latency = limit;
6599 sysctl_sched_wakeup_granularity *= factor;
6601 sysctl_sched_shares_ratelimit *= factor;
6606 * This is how migration works:
6608 * 1) we queue a struct migration_req structure in the source CPU's
6609 * runqueue and wake up that CPU's migration thread.
6610 * 2) we down() the locked semaphore => thread blocks.
6611 * 3) migration thread wakes up (implicitly it forces the migrated
6612 * thread off the CPU)
6613 * 4) it gets the migration request and checks whether the migrated
6614 * task is still in the wrong runqueue.
6615 * 5) if it's in the wrong runqueue then the migration thread removes
6616 * it and puts it into the right queue.
6617 * 6) migration thread up()s the semaphore.
6618 * 7) we wake up and the migration is done.
6622 * Change a given task's CPU affinity. Migrate the thread to a
6623 * proper CPU and schedule it away if the CPU it's executing on
6624 * is removed from the allowed bitmask.
6626 * NOTE: the caller must have a valid reference to the task, the
6627 * task must not exit() & deallocate itself prematurely. The
6628 * call is not atomic; no spinlocks may be held.
6630 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
6632 struct migration_req req;
6633 unsigned long flags;
6637 rq = task_rq_lock(p, &flags);
6638 if (!cpumask_intersects(new_mask, cpu_online_mask)) {
6643 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
6644 !cpumask_equal(&p->cpus_allowed, new_mask))) {
6649 if (p->sched_class->set_cpus_allowed)
6650 p->sched_class->set_cpus_allowed(p, new_mask);
6652 cpumask_copy(&p->cpus_allowed, new_mask);
6653 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
6656 /* Can the task run on the task's current CPU? If so, we're done */
6657 if (cpumask_test_cpu(task_cpu(p), new_mask))
6660 if (migrate_task(p, cpumask_any_and(cpu_online_mask, new_mask), &req)) {
6661 /* Need help from migration thread: drop lock and wait. */
6662 task_rq_unlock(rq, &flags);
6663 wake_up_process(rq->migration_thread);
6664 wait_for_completion(&req.done);
6665 tlb_migrate_finish(p->mm);
6669 task_rq_unlock(rq, &flags);
6673 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6676 * Move (not current) task off this cpu, onto dest cpu. We're doing
6677 * this because either it can't run here any more (set_cpus_allowed()
6678 * away from this CPU, or CPU going down), or because we're
6679 * attempting to rebalance this task on exec (sched_exec).
6681 * So we race with normal scheduler movements, but that's OK, as long
6682 * as the task is no longer on this CPU.
6684 * Returns non-zero if task was successfully migrated.
6686 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6688 struct rq *rq_dest, *rq_src;
6691 if (unlikely(!cpu_active(dest_cpu)))
6694 rq_src = cpu_rq(src_cpu);
6695 rq_dest = cpu_rq(dest_cpu);
6697 double_rq_lock(rq_src, rq_dest);
6698 /* Already moved. */
6699 if (task_cpu(p) != src_cpu)
6701 /* Affinity changed (again). */
6702 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6705 on_rq = p->se.on_rq;
6707 deactivate_task(rq_src, p, 0);
6709 set_task_cpu(p, dest_cpu);
6711 activate_task(rq_dest, p, 0);
6712 check_preempt_curr(rq_dest, p, 0);
6717 double_rq_unlock(rq_src, rq_dest);
6722 * migration_thread - this is a highprio system thread that performs
6723 * thread migration by bumping thread off CPU then 'pushing' onto
6726 static int migration_thread(void *data)
6728 int cpu = (long)data;
6732 BUG_ON(rq->migration_thread != current);
6734 set_current_state(TASK_INTERRUPTIBLE);
6735 while (!kthread_should_stop()) {
6736 struct migration_req *req;
6737 struct list_head *head;
6739 spin_lock_irq(&rq->lock);
6741 if (cpu_is_offline(cpu)) {
6742 spin_unlock_irq(&rq->lock);
6746 if (rq->active_balance) {
6747 active_load_balance(rq, cpu);
6748 rq->active_balance = 0;
6751 head = &rq->migration_queue;
6753 if (list_empty(head)) {
6754 spin_unlock_irq(&rq->lock);
6756 set_current_state(TASK_INTERRUPTIBLE);
6759 req = list_entry(head->next, struct migration_req, list);
6760 list_del_init(head->next);
6762 spin_unlock(&rq->lock);
6763 __migrate_task(req->task, cpu, req->dest_cpu);
6766 complete(&req->done);
6768 __set_current_state(TASK_RUNNING);
6772 /* Wait for kthread_stop */
6773 set_current_state(TASK_INTERRUPTIBLE);
6774 while (!kthread_should_stop()) {
6776 set_current_state(TASK_INTERRUPTIBLE);
6778 __set_current_state(TASK_RUNNING);
6782 #ifdef CONFIG_HOTPLUG_CPU
6784 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6788 local_irq_disable();
6789 ret = __migrate_task(p, src_cpu, dest_cpu);
6795 * Figure out where task on dead CPU should go, use force if necessary.
6797 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6800 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(dead_cpu));
6803 /* Look for allowed, online CPU in same node. */
6804 for_each_cpu_and(dest_cpu, nodemask, cpu_online_mask)
6805 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6808 /* Any allowed, online CPU? */
6809 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_online_mask);
6810 if (dest_cpu < nr_cpu_ids)
6813 /* No more Mr. Nice Guy. */
6814 if (dest_cpu >= nr_cpu_ids) {
6815 cpuset_cpus_allowed_locked(p, &p->cpus_allowed);
6816 dest_cpu = cpumask_any_and(cpu_online_mask, &p->cpus_allowed);
6819 * Don't tell them about moving exiting tasks or
6820 * kernel threads (both mm NULL), since they never
6823 if (p->mm && printk_ratelimit()) {
6824 printk(KERN_INFO "process %d (%s) no "
6825 "longer affine to cpu%d\n",
6826 task_pid_nr(p), p->comm, dead_cpu);
6831 /* It can have affinity changed while we were choosing. */
6832 if (unlikely(!__migrate_task_irq(p, dead_cpu, dest_cpu)))
6837 * While a dead CPU has no uninterruptible tasks queued at this point,
6838 * it might still have a nonzero ->nr_uninterruptible counter, because
6839 * for performance reasons the counter is not stricly tracking tasks to
6840 * their home CPUs. So we just add the counter to another CPU's counter,
6841 * to keep the global sum constant after CPU-down:
6843 static void migrate_nr_uninterruptible(struct rq *rq_src)
6845 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_online_mask));
6846 unsigned long flags;
6848 local_irq_save(flags);
6849 double_rq_lock(rq_src, rq_dest);
6850 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6851 rq_src->nr_uninterruptible = 0;
6852 double_rq_unlock(rq_src, rq_dest);
6853 local_irq_restore(flags);
6856 /* Run through task list and migrate tasks from the dead cpu. */
6857 static void migrate_live_tasks(int src_cpu)
6859 struct task_struct *p, *t;
6861 read_lock(&tasklist_lock);
6863 do_each_thread(t, p) {
6867 if (task_cpu(p) == src_cpu)
6868 move_task_off_dead_cpu(src_cpu, p);
6869 } while_each_thread(t, p);
6871 read_unlock(&tasklist_lock);
6875 * Schedules idle task to be the next runnable task on current CPU.
6876 * It does so by boosting its priority to highest possible.
6877 * Used by CPU offline code.
6879 void sched_idle_next(void)
6881 int this_cpu = smp_processor_id();
6882 struct rq *rq = cpu_rq(this_cpu);
6883 struct task_struct *p = rq->idle;
6884 unsigned long flags;
6886 /* cpu has to be offline */
6887 BUG_ON(cpu_online(this_cpu));
6890 * Strictly not necessary since rest of the CPUs are stopped by now
6891 * and interrupts disabled on the current cpu.
6893 spin_lock_irqsave(&rq->lock, flags);
6895 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6897 update_rq_clock(rq);
6898 activate_task(rq, p, 0);
6900 spin_unlock_irqrestore(&rq->lock, flags);
6904 * Ensures that the idle task is using init_mm right before its cpu goes
6907 void idle_task_exit(void)
6909 struct mm_struct *mm = current->active_mm;
6911 BUG_ON(cpu_online(smp_processor_id()));
6914 switch_mm(mm, &init_mm, current);
6918 /* called under rq->lock with disabled interrupts */
6919 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6921 struct rq *rq = cpu_rq(dead_cpu);
6923 /* Must be exiting, otherwise would be on tasklist. */
6924 BUG_ON(!p->exit_state);
6926 /* Cannot have done final schedule yet: would have vanished. */
6927 BUG_ON(p->state == TASK_DEAD);
6932 * Drop lock around migration; if someone else moves it,
6933 * that's OK. No task can be added to this CPU, so iteration is
6936 spin_unlock_irq(&rq->lock);
6937 move_task_off_dead_cpu(dead_cpu, p);
6938 spin_lock_irq(&rq->lock);
6943 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6944 static void migrate_dead_tasks(unsigned int dead_cpu)
6946 struct rq *rq = cpu_rq(dead_cpu);
6947 struct task_struct *next;
6950 if (!rq->nr_running)
6952 update_rq_clock(rq);
6953 next = pick_next_task(rq);
6956 next->sched_class->put_prev_task(rq, next);
6957 migrate_dead(dead_cpu, next);
6961 #endif /* CONFIG_HOTPLUG_CPU */
6963 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6965 static struct ctl_table sd_ctl_dir[] = {
6967 .procname = "sched_domain",
6973 static struct ctl_table sd_ctl_root[] = {
6975 .ctl_name = CTL_KERN,
6976 .procname = "kernel",
6978 .child = sd_ctl_dir,
6983 static struct ctl_table *sd_alloc_ctl_entry(int n)
6985 struct ctl_table *entry =
6986 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6991 static void sd_free_ctl_entry(struct ctl_table **tablep)
6993 struct ctl_table *entry;
6996 * In the intermediate directories, both the child directory and
6997 * procname are dynamically allocated and could fail but the mode
6998 * will always be set. In the lowest directory the names are
6999 * static strings and all have proc handlers.
7001 for (entry = *tablep; entry->mode; entry++) {
7003 sd_free_ctl_entry(&entry->child);
7004 if (entry->proc_handler == NULL)
7005 kfree(entry->procname);
7013 set_table_entry(struct ctl_table *entry,
7014 const char *procname, void *data, int maxlen,
7015 mode_t mode, proc_handler *proc_handler)
7017 entry->procname = procname;
7019 entry->maxlen = maxlen;
7021 entry->proc_handler = proc_handler;
7024 static struct ctl_table *
7025 sd_alloc_ctl_domain_table(struct sched_domain *sd)
7027 struct ctl_table *table = sd_alloc_ctl_entry(13);
7032 set_table_entry(&table[0], "min_interval", &sd->min_interval,
7033 sizeof(long), 0644, proc_doulongvec_minmax);
7034 set_table_entry(&table[1], "max_interval", &sd->max_interval,
7035 sizeof(long), 0644, proc_doulongvec_minmax);
7036 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
7037 sizeof(int), 0644, proc_dointvec_minmax);
7038 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
7039 sizeof(int), 0644, proc_dointvec_minmax);
7040 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
7041 sizeof(int), 0644, proc_dointvec_minmax);
7042 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
7043 sizeof(int), 0644, proc_dointvec_minmax);
7044 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
7045 sizeof(int), 0644, proc_dointvec_minmax);
7046 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
7047 sizeof(int), 0644, proc_dointvec_minmax);
7048 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
7049 sizeof(int), 0644, proc_dointvec_minmax);
7050 set_table_entry(&table[9], "cache_nice_tries",
7051 &sd->cache_nice_tries,
7052 sizeof(int), 0644, proc_dointvec_minmax);
7053 set_table_entry(&table[10], "flags", &sd->flags,
7054 sizeof(int), 0644, proc_dointvec_minmax);
7055 set_table_entry(&table[11], "name", sd->name,
7056 CORENAME_MAX_SIZE, 0444, proc_dostring);
7057 /* &table[12] is terminator */
7062 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
7064 struct ctl_table *entry, *table;
7065 struct sched_domain *sd;
7066 int domain_num = 0, i;
7069 for_each_domain(cpu, sd)
7071 entry = table = sd_alloc_ctl_entry(domain_num + 1);
7076 for_each_domain(cpu, sd) {
7077 snprintf(buf, 32, "domain%d", i);
7078 entry->procname = kstrdup(buf, GFP_KERNEL);
7080 entry->child = sd_alloc_ctl_domain_table(sd);
7087 static struct ctl_table_header *sd_sysctl_header;
7088 static void register_sched_domain_sysctl(void)
7090 int i, cpu_num = num_online_cpus();
7091 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
7094 WARN_ON(sd_ctl_dir[0].child);
7095 sd_ctl_dir[0].child = entry;
7100 for_each_online_cpu(i) {
7101 snprintf(buf, 32, "cpu%d", i);
7102 entry->procname = kstrdup(buf, GFP_KERNEL);
7104 entry->child = sd_alloc_ctl_cpu_table(i);
7108 WARN_ON(sd_sysctl_header);
7109 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
7112 /* may be called multiple times per register */
7113 static void unregister_sched_domain_sysctl(void)
7115 if (sd_sysctl_header)
7116 unregister_sysctl_table(sd_sysctl_header);
7117 sd_sysctl_header = NULL;
7118 if (sd_ctl_dir[0].child)
7119 sd_free_ctl_entry(&sd_ctl_dir[0].child);
7122 static void register_sched_domain_sysctl(void)
7125 static void unregister_sched_domain_sysctl(void)
7130 static void set_rq_online(struct rq *rq)
7133 const struct sched_class *class;
7135 cpumask_set_cpu(rq->cpu, rq->rd->online);
7138 for_each_class(class) {
7139 if (class->rq_online)
7140 class->rq_online(rq);
7145 static void set_rq_offline(struct rq *rq)
7148 const struct sched_class *class;
7150 for_each_class(class) {
7151 if (class->rq_offline)
7152 class->rq_offline(rq);
7155 cpumask_clear_cpu(rq->cpu, rq->rd->online);
7161 * migration_call - callback that gets triggered when a CPU is added.
7162 * Here we can start up the necessary migration thread for the new CPU.
7164 static int __cpuinit
7165 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
7167 struct task_struct *p;
7168 int cpu = (long)hcpu;
7169 unsigned long flags;
7174 case CPU_UP_PREPARE:
7175 case CPU_UP_PREPARE_FROZEN:
7176 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
7179 kthread_bind(p, cpu);
7180 /* Must be high prio: stop_machine expects to yield to it. */
7181 rq = task_rq_lock(p, &flags);
7182 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7183 task_rq_unlock(rq, &flags);
7184 cpu_rq(cpu)->migration_thread = p;
7188 case CPU_ONLINE_FROZEN:
7189 /* Strictly unnecessary, as first user will wake it. */
7190 wake_up_process(cpu_rq(cpu)->migration_thread);
7192 /* Update our root-domain */
7194 spin_lock_irqsave(&rq->lock, flags);
7196 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7200 spin_unlock_irqrestore(&rq->lock, flags);
7203 #ifdef CONFIG_HOTPLUG_CPU
7204 case CPU_UP_CANCELED:
7205 case CPU_UP_CANCELED_FROZEN:
7206 if (!cpu_rq(cpu)->migration_thread)
7208 /* Unbind it from offline cpu so it can run. Fall thru. */
7209 kthread_bind(cpu_rq(cpu)->migration_thread,
7210 cpumask_any(cpu_online_mask));
7211 kthread_stop(cpu_rq(cpu)->migration_thread);
7212 cpu_rq(cpu)->migration_thread = NULL;
7216 case CPU_DEAD_FROZEN:
7217 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
7218 migrate_live_tasks(cpu);
7220 kthread_stop(rq->migration_thread);
7221 rq->migration_thread = NULL;
7222 /* Idle task back to normal (off runqueue, low prio) */
7223 spin_lock_irq(&rq->lock);
7224 update_rq_clock(rq);
7225 deactivate_task(rq, rq->idle, 0);
7226 rq->idle->static_prio = MAX_PRIO;
7227 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
7228 rq->idle->sched_class = &idle_sched_class;
7229 migrate_dead_tasks(cpu);
7230 spin_unlock_irq(&rq->lock);
7232 migrate_nr_uninterruptible(rq);
7233 BUG_ON(rq->nr_running != 0);
7236 * No need to migrate the tasks: it was best-effort if
7237 * they didn't take sched_hotcpu_mutex. Just wake up
7240 spin_lock_irq(&rq->lock);
7241 while (!list_empty(&rq->migration_queue)) {
7242 struct migration_req *req;
7244 req = list_entry(rq->migration_queue.next,
7245 struct migration_req, list);
7246 list_del_init(&req->list);
7247 spin_unlock_irq(&rq->lock);
7248 complete(&req->done);
7249 spin_lock_irq(&rq->lock);
7251 spin_unlock_irq(&rq->lock);
7255 case CPU_DYING_FROZEN:
7256 /* Update our root-domain */
7258 spin_lock_irqsave(&rq->lock, flags);
7260 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7263 spin_unlock_irqrestore(&rq->lock, flags);
7270 /* Register at highest priority so that task migration (migrate_all_tasks)
7271 * happens before everything else.
7273 static struct notifier_block __cpuinitdata migration_notifier = {
7274 .notifier_call = migration_call,
7278 static int __init migration_init(void)
7280 void *cpu = (void *)(long)smp_processor_id();
7283 /* Start one for the boot CPU: */
7284 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
7285 BUG_ON(err == NOTIFY_BAD);
7286 migration_call(&migration_notifier, CPU_ONLINE, cpu);
7287 register_cpu_notifier(&migration_notifier);
7291 early_initcall(migration_init);
7296 #ifdef CONFIG_SCHED_DEBUG
7298 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
7299 struct cpumask *groupmask)
7301 struct sched_group *group = sd->groups;
7304 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
7305 cpumask_clear(groupmask);
7307 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
7309 if (!(sd->flags & SD_LOAD_BALANCE)) {
7310 printk("does not load-balance\n");
7312 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
7317 printk(KERN_CONT "span %s level %s\n", str, sd->name);
7319 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
7320 printk(KERN_ERR "ERROR: domain->span does not contain "
7323 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
7324 printk(KERN_ERR "ERROR: domain->groups does not contain"
7328 printk(KERN_DEBUG "%*s groups:", level + 1, "");
7332 printk(KERN_ERR "ERROR: group is NULL\n");
7336 if (!group->__cpu_power) {
7337 printk(KERN_CONT "\n");
7338 printk(KERN_ERR "ERROR: domain->cpu_power not "
7343 if (!cpumask_weight(sched_group_cpus(group))) {
7344 printk(KERN_CONT "\n");
7345 printk(KERN_ERR "ERROR: empty group\n");
7349 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
7350 printk(KERN_CONT "\n");
7351 printk(KERN_ERR "ERROR: repeated CPUs\n");
7355 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
7357 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
7358 printk(KERN_CONT " %s", str);
7360 group = group->next;
7361 } while (group != sd->groups);
7362 printk(KERN_CONT "\n");
7364 if (!cpumask_equal(sched_domain_span(sd), groupmask))
7365 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
7368 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
7369 printk(KERN_ERR "ERROR: parent span is not a superset "
7370 "of domain->span\n");
7374 static void sched_domain_debug(struct sched_domain *sd, int cpu)
7376 cpumask_var_t groupmask;
7380 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
7384 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
7386 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
7387 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
7392 if (sched_domain_debug_one(sd, cpu, level, groupmask))
7399 free_cpumask_var(groupmask);
7401 #else /* !CONFIG_SCHED_DEBUG */
7402 # define sched_domain_debug(sd, cpu) do { } while (0)
7403 #endif /* CONFIG_SCHED_DEBUG */
7405 static int sd_degenerate(struct sched_domain *sd)
7407 if (cpumask_weight(sched_domain_span(sd)) == 1)
7410 /* Following flags need at least 2 groups */
7411 if (sd->flags & (SD_LOAD_BALANCE |
7412 SD_BALANCE_NEWIDLE |
7416 SD_SHARE_PKG_RESOURCES)) {
7417 if (sd->groups != sd->groups->next)
7421 /* Following flags don't use groups */
7422 if (sd->flags & (SD_WAKE_IDLE |
7431 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
7433 unsigned long cflags = sd->flags, pflags = parent->flags;
7435 if (sd_degenerate(parent))
7438 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
7441 /* Does parent contain flags not in child? */
7442 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
7443 if (cflags & SD_WAKE_AFFINE)
7444 pflags &= ~SD_WAKE_BALANCE;
7445 /* Flags needing groups don't count if only 1 group in parent */
7446 if (parent->groups == parent->groups->next) {
7447 pflags &= ~(SD_LOAD_BALANCE |
7448 SD_BALANCE_NEWIDLE |
7452 SD_SHARE_PKG_RESOURCES);
7453 if (nr_node_ids == 1)
7454 pflags &= ~SD_SERIALIZE;
7456 if (~cflags & pflags)
7462 static void free_rootdomain(struct root_domain *rd)
7464 cpupri_cleanup(&rd->cpupri);
7466 free_cpumask_var(rd->rto_mask);
7467 free_cpumask_var(rd->online);
7468 free_cpumask_var(rd->span);
7472 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
7474 struct root_domain *old_rd = NULL;
7475 unsigned long flags;
7477 spin_lock_irqsave(&rq->lock, flags);
7482 if (cpumask_test_cpu(rq->cpu, old_rd->online))
7485 cpumask_clear_cpu(rq->cpu, old_rd->span);
7488 * If we dont want to free the old_rt yet then
7489 * set old_rd to NULL to skip the freeing later
7492 if (!atomic_dec_and_test(&old_rd->refcount))
7496 atomic_inc(&rd->refcount);
7499 cpumask_set_cpu(rq->cpu, rd->span);
7500 if (cpumask_test_cpu(rq->cpu, cpu_online_mask))
7503 spin_unlock_irqrestore(&rq->lock, flags);
7506 free_rootdomain(old_rd);
7509 static int __init_refok init_rootdomain(struct root_domain *rd, bool bootmem)
7511 memset(rd, 0, sizeof(*rd));
7514 alloc_bootmem_cpumask_var(&def_root_domain.span);
7515 alloc_bootmem_cpumask_var(&def_root_domain.online);
7516 alloc_bootmem_cpumask_var(&def_root_domain.rto_mask);
7517 cpupri_init(&rd->cpupri, true);
7521 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
7523 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
7525 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
7528 if (cpupri_init(&rd->cpupri, false) != 0)
7533 free_cpumask_var(rd->rto_mask);
7535 free_cpumask_var(rd->online);
7537 free_cpumask_var(rd->span);
7542 static void init_defrootdomain(void)
7544 init_rootdomain(&def_root_domain, true);
7546 atomic_set(&def_root_domain.refcount, 1);
7549 static struct root_domain *alloc_rootdomain(void)
7551 struct root_domain *rd;
7553 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
7557 if (init_rootdomain(rd, false) != 0) {
7566 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
7567 * hold the hotplug lock.
7570 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
7572 struct rq *rq = cpu_rq(cpu);
7573 struct sched_domain *tmp;
7575 /* Remove the sched domains which do not contribute to scheduling. */
7576 for (tmp = sd; tmp; ) {
7577 struct sched_domain *parent = tmp->parent;
7581 if (sd_parent_degenerate(tmp, parent)) {
7582 tmp->parent = parent->parent;
7584 parent->parent->child = tmp;
7589 if (sd && sd_degenerate(sd)) {
7595 sched_domain_debug(sd, cpu);
7597 rq_attach_root(rq, rd);
7598 rcu_assign_pointer(rq->sd, sd);
7601 /* cpus with isolated domains */
7602 static cpumask_var_t cpu_isolated_map;
7604 /* Setup the mask of cpus configured for isolated domains */
7605 static int __init isolated_cpu_setup(char *str)
7607 cpulist_parse(str, cpu_isolated_map);
7611 __setup("isolcpus=", isolated_cpu_setup);
7614 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
7615 * to a function which identifies what group(along with sched group) a CPU
7616 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
7617 * (due to the fact that we keep track of groups covered with a struct cpumask).
7619 * init_sched_build_groups will build a circular linked list of the groups
7620 * covered by the given span, and will set each group's ->cpumask correctly,
7621 * and ->cpu_power to 0.
7624 init_sched_build_groups(const struct cpumask *span,
7625 const struct cpumask *cpu_map,
7626 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
7627 struct sched_group **sg,
7628 struct cpumask *tmpmask),
7629 struct cpumask *covered, struct cpumask *tmpmask)
7631 struct sched_group *first = NULL, *last = NULL;
7634 cpumask_clear(covered);
7636 for_each_cpu(i, span) {
7637 struct sched_group *sg;
7638 int group = group_fn(i, cpu_map, &sg, tmpmask);
7641 if (cpumask_test_cpu(i, covered))
7644 cpumask_clear(sched_group_cpus(sg));
7645 sg->__cpu_power = 0;
7647 for_each_cpu(j, span) {
7648 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
7651 cpumask_set_cpu(j, covered);
7652 cpumask_set_cpu(j, sched_group_cpus(sg));
7663 #define SD_NODES_PER_DOMAIN 16
7668 * find_next_best_node - find the next node to include in a sched_domain
7669 * @node: node whose sched_domain we're building
7670 * @used_nodes: nodes already in the sched_domain
7672 * Find the next node to include in a given scheduling domain. Simply
7673 * finds the closest node not already in the @used_nodes map.
7675 * Should use nodemask_t.
7677 static int find_next_best_node(int node, nodemask_t *used_nodes)
7679 int i, n, val, min_val, best_node = 0;
7683 for (i = 0; i < nr_node_ids; i++) {
7684 /* Start at @node */
7685 n = (node + i) % nr_node_ids;
7687 if (!nr_cpus_node(n))
7690 /* Skip already used nodes */
7691 if (node_isset(n, *used_nodes))
7694 /* Simple min distance search */
7695 val = node_distance(node, n);
7697 if (val < min_val) {
7703 node_set(best_node, *used_nodes);
7708 * sched_domain_node_span - get a cpumask for a node's sched_domain
7709 * @node: node whose cpumask we're constructing
7710 * @span: resulting cpumask
7712 * Given a node, construct a good cpumask for its sched_domain to span. It
7713 * should be one that prevents unnecessary balancing, but also spreads tasks
7716 static void sched_domain_node_span(int node, struct cpumask *span)
7718 nodemask_t used_nodes;
7721 cpumask_clear(span);
7722 nodes_clear(used_nodes);
7724 cpumask_or(span, span, cpumask_of_node(node));
7725 node_set(node, used_nodes);
7727 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7728 int next_node = find_next_best_node(node, &used_nodes);
7730 cpumask_or(span, span, cpumask_of_node(next_node));
7733 #endif /* CONFIG_NUMA */
7735 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7738 * The cpus mask in sched_group and sched_domain hangs off the end.
7739 * FIXME: use cpumask_var_t or dynamic percpu alloc to avoid wasting space
7740 * for nr_cpu_ids < CONFIG_NR_CPUS.
7742 struct static_sched_group {
7743 struct sched_group sg;
7744 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
7747 struct static_sched_domain {
7748 struct sched_domain sd;
7749 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
7753 * SMT sched-domains:
7755 #ifdef CONFIG_SCHED_SMT
7756 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
7757 static DEFINE_PER_CPU(struct static_sched_group, sched_group_cpus);
7760 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
7761 struct sched_group **sg, struct cpumask *unused)
7764 *sg = &per_cpu(sched_group_cpus, cpu).sg;
7767 #endif /* CONFIG_SCHED_SMT */
7770 * multi-core sched-domains:
7772 #ifdef CONFIG_SCHED_MC
7773 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
7774 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
7775 #endif /* CONFIG_SCHED_MC */
7777 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7779 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
7780 struct sched_group **sg, struct cpumask *mask)
7784 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
7785 group = cpumask_first(mask);
7787 *sg = &per_cpu(sched_group_core, group).sg;
7790 #elif defined(CONFIG_SCHED_MC)
7792 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
7793 struct sched_group **sg, struct cpumask *unused)
7796 *sg = &per_cpu(sched_group_core, cpu).sg;
7801 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
7802 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
7805 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
7806 struct sched_group **sg, struct cpumask *mask)
7809 #ifdef CONFIG_SCHED_MC
7810 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
7811 group = cpumask_first(mask);
7812 #elif defined(CONFIG_SCHED_SMT)
7813 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
7814 group = cpumask_first(mask);
7819 *sg = &per_cpu(sched_group_phys, group).sg;
7825 * The init_sched_build_groups can't handle what we want to do with node
7826 * groups, so roll our own. Now each node has its own list of groups which
7827 * gets dynamically allocated.
7829 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
7830 static struct sched_group ***sched_group_nodes_bycpu;
7832 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
7833 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
7835 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
7836 struct sched_group **sg,
7837 struct cpumask *nodemask)
7841 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
7842 group = cpumask_first(nodemask);
7845 *sg = &per_cpu(sched_group_allnodes, group).sg;
7849 static void init_numa_sched_groups_power(struct sched_group *group_head)
7851 struct sched_group *sg = group_head;
7857 for_each_cpu(j, sched_group_cpus(sg)) {
7858 struct sched_domain *sd;
7860 sd = &per_cpu(phys_domains, j).sd;
7861 if (j != cpumask_first(sched_group_cpus(sd->groups))) {
7863 * Only add "power" once for each
7869 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7872 } while (sg != group_head);
7874 #endif /* CONFIG_NUMA */
7877 /* Free memory allocated for various sched_group structures */
7878 static void free_sched_groups(const struct cpumask *cpu_map,
7879 struct cpumask *nodemask)
7883 for_each_cpu(cpu, cpu_map) {
7884 struct sched_group **sched_group_nodes
7885 = sched_group_nodes_bycpu[cpu];
7887 if (!sched_group_nodes)
7890 for (i = 0; i < nr_node_ids; i++) {
7891 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7893 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
7894 if (cpumask_empty(nodemask))
7904 if (oldsg != sched_group_nodes[i])
7907 kfree(sched_group_nodes);
7908 sched_group_nodes_bycpu[cpu] = NULL;
7911 #else /* !CONFIG_NUMA */
7912 static void free_sched_groups(const struct cpumask *cpu_map,
7913 struct cpumask *nodemask)
7916 #endif /* CONFIG_NUMA */
7919 * Initialize sched groups cpu_power.
7921 * cpu_power indicates the capacity of sched group, which is used while
7922 * distributing the load between different sched groups in a sched domain.
7923 * Typically cpu_power for all the groups in a sched domain will be same unless
7924 * there are asymmetries in the topology. If there are asymmetries, group
7925 * having more cpu_power will pickup more load compared to the group having
7928 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7929 * the maximum number of tasks a group can handle in the presence of other idle
7930 * or lightly loaded groups in the same sched domain.
7932 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7934 struct sched_domain *child;
7935 struct sched_group *group;
7937 WARN_ON(!sd || !sd->groups);
7939 if (cpu != cpumask_first(sched_group_cpus(sd->groups)))
7944 sd->groups->__cpu_power = 0;
7947 * For perf policy, if the groups in child domain share resources
7948 * (for example cores sharing some portions of the cache hierarchy
7949 * or SMT), then set this domain groups cpu_power such that each group
7950 * can handle only one task, when there are other idle groups in the
7951 * same sched domain.
7953 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7955 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7956 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7961 * add cpu_power of each child group to this groups cpu_power
7963 group = child->groups;
7965 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7966 group = group->next;
7967 } while (group != child->groups);
7971 * Initializers for schedule domains
7972 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7975 #ifdef CONFIG_SCHED_DEBUG
7976 # define SD_INIT_NAME(sd, type) sd->name = #type
7978 # define SD_INIT_NAME(sd, type) do { } while (0)
7981 #define SD_INIT(sd, type) sd_init_##type(sd)
7983 #define SD_INIT_FUNC(type) \
7984 static noinline void sd_init_##type(struct sched_domain *sd) \
7986 memset(sd, 0, sizeof(*sd)); \
7987 *sd = SD_##type##_INIT; \
7988 sd->level = SD_LV_##type; \
7989 SD_INIT_NAME(sd, type); \
7994 SD_INIT_FUNC(ALLNODES)
7997 #ifdef CONFIG_SCHED_SMT
7998 SD_INIT_FUNC(SIBLING)
8000 #ifdef CONFIG_SCHED_MC
8004 static int default_relax_domain_level = -1;
8006 static int __init setup_relax_domain_level(char *str)
8010 val = simple_strtoul(str, NULL, 0);
8011 if (val < SD_LV_MAX)
8012 default_relax_domain_level = val;
8016 __setup("relax_domain_level=", setup_relax_domain_level);
8018 static void set_domain_attribute(struct sched_domain *sd,
8019 struct sched_domain_attr *attr)
8023 if (!attr || attr->relax_domain_level < 0) {
8024 if (default_relax_domain_level < 0)
8027 request = default_relax_domain_level;
8029 request = attr->relax_domain_level;
8030 if (request < sd->level) {
8031 /* turn off idle balance on this domain */
8032 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
8034 /* turn on idle balance on this domain */
8035 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
8040 * Build sched domains for a given set of cpus and attach the sched domains
8041 * to the individual cpus
8043 static int __build_sched_domains(const struct cpumask *cpu_map,
8044 struct sched_domain_attr *attr)
8046 int i, err = -ENOMEM;
8047 struct root_domain *rd;
8048 cpumask_var_t nodemask, this_sibling_map, this_core_map, send_covered,
8051 cpumask_var_t domainspan, covered, notcovered;
8052 struct sched_group **sched_group_nodes = NULL;
8053 int sd_allnodes = 0;
8055 if (!alloc_cpumask_var(&domainspan, GFP_KERNEL))
8057 if (!alloc_cpumask_var(&covered, GFP_KERNEL))
8058 goto free_domainspan;
8059 if (!alloc_cpumask_var(¬covered, GFP_KERNEL))
8063 if (!alloc_cpumask_var(&nodemask, GFP_KERNEL))
8064 goto free_notcovered;
8065 if (!alloc_cpumask_var(&this_sibling_map, GFP_KERNEL))
8067 if (!alloc_cpumask_var(&this_core_map, GFP_KERNEL))
8068 goto free_this_sibling_map;
8069 if (!alloc_cpumask_var(&send_covered, GFP_KERNEL))
8070 goto free_this_core_map;
8071 if (!alloc_cpumask_var(&tmpmask, GFP_KERNEL))
8072 goto free_send_covered;
8076 * Allocate the per-node list of sched groups
8078 sched_group_nodes = kcalloc(nr_node_ids, sizeof(struct sched_group *),
8080 if (!sched_group_nodes) {
8081 printk(KERN_WARNING "Can not alloc sched group node list\n");
8086 rd = alloc_rootdomain();
8088 printk(KERN_WARNING "Cannot alloc root domain\n");
8089 goto free_sched_groups;
8093 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = sched_group_nodes;
8097 * Set up domains for cpus specified by the cpu_map.
8099 for_each_cpu(i, cpu_map) {
8100 struct sched_domain *sd = NULL, *p;
8102 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(i)), cpu_map);
8105 if (cpumask_weight(cpu_map) >
8106 SD_NODES_PER_DOMAIN*cpumask_weight(nodemask)) {
8107 sd = &per_cpu(allnodes_domains, i).sd;
8108 SD_INIT(sd, ALLNODES);
8109 set_domain_attribute(sd, attr);
8110 cpumask_copy(sched_domain_span(sd), cpu_map);
8111 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
8117 sd = &per_cpu(node_domains, i).sd;
8119 set_domain_attribute(sd, attr);
8120 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
8124 cpumask_and(sched_domain_span(sd),
8125 sched_domain_span(sd), cpu_map);
8129 sd = &per_cpu(phys_domains, i).sd;
8131 set_domain_attribute(sd, attr);
8132 cpumask_copy(sched_domain_span(sd), nodemask);
8136 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
8138 #ifdef CONFIG_SCHED_MC
8140 sd = &per_cpu(core_domains, i).sd;
8142 set_domain_attribute(sd, attr);
8143 cpumask_and(sched_domain_span(sd), cpu_map,
8144 cpu_coregroup_mask(i));
8147 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
8150 #ifdef CONFIG_SCHED_SMT
8152 sd = &per_cpu(cpu_domains, i).sd;
8153 SD_INIT(sd, SIBLING);
8154 set_domain_attribute(sd, attr);
8155 cpumask_and(sched_domain_span(sd),
8156 topology_thread_cpumask(i), cpu_map);
8159 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
8163 #ifdef CONFIG_SCHED_SMT
8164 /* Set up CPU (sibling) groups */
8165 for_each_cpu(i, cpu_map) {
8166 cpumask_and(this_sibling_map,
8167 topology_thread_cpumask(i), cpu_map);
8168 if (i != cpumask_first(this_sibling_map))
8171 init_sched_build_groups(this_sibling_map, cpu_map,
8173 send_covered, tmpmask);
8177 #ifdef CONFIG_SCHED_MC
8178 /* Set up multi-core groups */
8179 for_each_cpu(i, cpu_map) {
8180 cpumask_and(this_core_map, cpu_coregroup_mask(i), cpu_map);
8181 if (i != cpumask_first(this_core_map))
8184 init_sched_build_groups(this_core_map, cpu_map,
8186 send_covered, tmpmask);
8190 /* Set up physical groups */
8191 for (i = 0; i < nr_node_ids; i++) {
8192 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8193 if (cpumask_empty(nodemask))
8196 init_sched_build_groups(nodemask, cpu_map,
8198 send_covered, tmpmask);
8202 /* Set up node groups */
8204 init_sched_build_groups(cpu_map, cpu_map,
8205 &cpu_to_allnodes_group,
8206 send_covered, tmpmask);
8209 for (i = 0; i < nr_node_ids; i++) {
8210 /* Set up node groups */
8211 struct sched_group *sg, *prev;
8214 cpumask_clear(covered);
8215 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8216 if (cpumask_empty(nodemask)) {
8217 sched_group_nodes[i] = NULL;
8221 sched_domain_node_span(i, domainspan);
8222 cpumask_and(domainspan, domainspan, cpu_map);
8224 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8227 printk(KERN_WARNING "Can not alloc domain group for "
8231 sched_group_nodes[i] = sg;
8232 for_each_cpu(j, nodemask) {
8233 struct sched_domain *sd;
8235 sd = &per_cpu(node_domains, j).sd;
8238 sg->__cpu_power = 0;
8239 cpumask_copy(sched_group_cpus(sg), nodemask);
8241 cpumask_or(covered, covered, nodemask);
8244 for (j = 0; j < nr_node_ids; j++) {
8245 int n = (i + j) % nr_node_ids;
8247 cpumask_complement(notcovered, covered);
8248 cpumask_and(tmpmask, notcovered, cpu_map);
8249 cpumask_and(tmpmask, tmpmask, domainspan);
8250 if (cpumask_empty(tmpmask))
8253 cpumask_and(tmpmask, tmpmask, cpumask_of_node(n));
8254 if (cpumask_empty(tmpmask))
8257 sg = kmalloc_node(sizeof(struct sched_group) +
8262 "Can not alloc domain group for node %d\n", j);
8265 sg->__cpu_power = 0;
8266 cpumask_copy(sched_group_cpus(sg), tmpmask);
8267 sg->next = prev->next;
8268 cpumask_or(covered, covered, tmpmask);
8275 /* Calculate CPU power for physical packages and nodes */
8276 #ifdef CONFIG_SCHED_SMT
8277 for_each_cpu(i, cpu_map) {
8278 struct sched_domain *sd = &per_cpu(cpu_domains, i).sd;
8280 init_sched_groups_power(i, sd);
8283 #ifdef CONFIG_SCHED_MC
8284 for_each_cpu(i, cpu_map) {
8285 struct sched_domain *sd = &per_cpu(core_domains, i).sd;
8287 init_sched_groups_power(i, sd);
8291 for_each_cpu(i, cpu_map) {
8292 struct sched_domain *sd = &per_cpu(phys_domains, i).sd;
8294 init_sched_groups_power(i, sd);
8298 for (i = 0; i < nr_node_ids; i++)
8299 init_numa_sched_groups_power(sched_group_nodes[i]);
8302 struct sched_group *sg;
8304 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
8306 init_numa_sched_groups_power(sg);
8310 /* Attach the domains */
8311 for_each_cpu(i, cpu_map) {
8312 struct sched_domain *sd;
8313 #ifdef CONFIG_SCHED_SMT
8314 sd = &per_cpu(cpu_domains, i).sd;
8315 #elif defined(CONFIG_SCHED_MC)
8316 sd = &per_cpu(core_domains, i).sd;
8318 sd = &per_cpu(phys_domains, i).sd;
8320 cpu_attach_domain(sd, rd, i);
8326 free_cpumask_var(tmpmask);
8328 free_cpumask_var(send_covered);
8330 free_cpumask_var(this_core_map);
8331 free_this_sibling_map:
8332 free_cpumask_var(this_sibling_map);
8334 free_cpumask_var(nodemask);
8337 free_cpumask_var(notcovered);
8339 free_cpumask_var(covered);
8341 free_cpumask_var(domainspan);
8348 kfree(sched_group_nodes);
8354 free_sched_groups(cpu_map, tmpmask);
8355 free_rootdomain(rd);
8360 static int build_sched_domains(const struct cpumask *cpu_map)
8362 return __build_sched_domains(cpu_map, NULL);
8365 static struct cpumask *doms_cur; /* current sched domains */
8366 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
8367 static struct sched_domain_attr *dattr_cur;
8368 /* attribues of custom domains in 'doms_cur' */
8371 * Special case: If a kmalloc of a doms_cur partition (array of
8372 * cpumask) fails, then fallback to a single sched domain,
8373 * as determined by the single cpumask fallback_doms.
8375 static cpumask_var_t fallback_doms;
8378 * arch_update_cpu_topology lets virtualized architectures update the
8379 * cpu core maps. It is supposed to return 1 if the topology changed
8380 * or 0 if it stayed the same.
8382 int __attribute__((weak)) arch_update_cpu_topology(void)
8388 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
8389 * For now this just excludes isolated cpus, but could be used to
8390 * exclude other special cases in the future.
8392 static int arch_init_sched_domains(const struct cpumask *cpu_map)
8396 arch_update_cpu_topology();
8398 doms_cur = kmalloc(cpumask_size(), GFP_KERNEL);
8400 doms_cur = fallback_doms;
8401 cpumask_andnot(doms_cur, cpu_map, cpu_isolated_map);
8403 err = build_sched_domains(doms_cur);
8404 register_sched_domain_sysctl();
8409 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
8410 struct cpumask *tmpmask)
8412 free_sched_groups(cpu_map, tmpmask);
8416 * Detach sched domains from a group of cpus specified in cpu_map
8417 * These cpus will now be attached to the NULL domain
8419 static void detach_destroy_domains(const struct cpumask *cpu_map)
8421 /* Save because hotplug lock held. */
8422 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
8425 for_each_cpu(i, cpu_map)
8426 cpu_attach_domain(NULL, &def_root_domain, i);
8427 synchronize_sched();
8428 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
8431 /* handle null as "default" */
8432 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
8433 struct sched_domain_attr *new, int idx_new)
8435 struct sched_domain_attr tmp;
8442 return !memcmp(cur ? (cur + idx_cur) : &tmp,
8443 new ? (new + idx_new) : &tmp,
8444 sizeof(struct sched_domain_attr));
8448 * Partition sched domains as specified by the 'ndoms_new'
8449 * cpumasks in the array doms_new[] of cpumasks. This compares
8450 * doms_new[] to the current sched domain partitioning, doms_cur[].
8451 * It destroys each deleted domain and builds each new domain.
8453 * 'doms_new' is an array of cpumask's of length 'ndoms_new'.
8454 * The masks don't intersect (don't overlap.) We should setup one
8455 * sched domain for each mask. CPUs not in any of the cpumasks will
8456 * not be load balanced. If the same cpumask appears both in the
8457 * current 'doms_cur' domains and in the new 'doms_new', we can leave
8460 * The passed in 'doms_new' should be kmalloc'd. This routine takes
8461 * ownership of it and will kfree it when done with it. If the caller
8462 * failed the kmalloc call, then it can pass in doms_new == NULL &&
8463 * ndoms_new == 1, and partition_sched_domains() will fallback to
8464 * the single partition 'fallback_doms', it also forces the domains
8467 * If doms_new == NULL it will be replaced with cpu_online_mask.
8468 * ndoms_new == 0 is a special case for destroying existing domains,
8469 * and it will not create the default domain.
8471 * Call with hotplug lock held
8473 /* FIXME: Change to struct cpumask *doms_new[] */
8474 void partition_sched_domains(int ndoms_new, struct cpumask *doms_new,
8475 struct sched_domain_attr *dattr_new)
8480 mutex_lock(&sched_domains_mutex);
8482 /* always unregister in case we don't destroy any domains */
8483 unregister_sched_domain_sysctl();
8485 /* Let architecture update cpu core mappings. */
8486 new_topology = arch_update_cpu_topology();
8488 n = doms_new ? ndoms_new : 0;
8490 /* Destroy deleted domains */
8491 for (i = 0; i < ndoms_cur; i++) {
8492 for (j = 0; j < n && !new_topology; j++) {
8493 if (cpumask_equal(&doms_cur[i], &doms_new[j])
8494 && dattrs_equal(dattr_cur, i, dattr_new, j))
8497 /* no match - a current sched domain not in new doms_new[] */
8498 detach_destroy_domains(doms_cur + i);
8503 if (doms_new == NULL) {
8505 doms_new = fallback_doms;
8506 cpumask_andnot(&doms_new[0], cpu_online_mask, cpu_isolated_map);
8507 WARN_ON_ONCE(dattr_new);
8510 /* Build new domains */
8511 for (i = 0; i < ndoms_new; i++) {
8512 for (j = 0; j < ndoms_cur && !new_topology; j++) {
8513 if (cpumask_equal(&doms_new[i], &doms_cur[j])
8514 && dattrs_equal(dattr_new, i, dattr_cur, j))
8517 /* no match - add a new doms_new */
8518 __build_sched_domains(doms_new + i,
8519 dattr_new ? dattr_new + i : NULL);
8524 /* Remember the new sched domains */
8525 if (doms_cur != fallback_doms)
8527 kfree(dattr_cur); /* kfree(NULL) is safe */
8528 doms_cur = doms_new;
8529 dattr_cur = dattr_new;
8530 ndoms_cur = ndoms_new;
8532 register_sched_domain_sysctl();
8534 mutex_unlock(&sched_domains_mutex);
8537 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
8538 static void arch_reinit_sched_domains(void)
8542 /* Destroy domains first to force the rebuild */
8543 partition_sched_domains(0, NULL, NULL);
8545 rebuild_sched_domains();
8549 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
8551 unsigned int level = 0;
8553 if (sscanf(buf, "%u", &level) != 1)
8557 * level is always be positive so don't check for
8558 * level < POWERSAVINGS_BALANCE_NONE which is 0
8559 * What happens on 0 or 1 byte write,
8560 * need to check for count as well?
8563 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
8567 sched_smt_power_savings = level;
8569 sched_mc_power_savings = level;
8571 arch_reinit_sched_domains();
8576 #ifdef CONFIG_SCHED_MC
8577 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
8580 return sprintf(page, "%u\n", sched_mc_power_savings);
8582 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
8583 const char *buf, size_t count)
8585 return sched_power_savings_store(buf, count, 0);
8587 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
8588 sched_mc_power_savings_show,
8589 sched_mc_power_savings_store);
8592 #ifdef CONFIG_SCHED_SMT
8593 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
8596 return sprintf(page, "%u\n", sched_smt_power_savings);
8598 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
8599 const char *buf, size_t count)
8601 return sched_power_savings_store(buf, count, 1);
8603 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
8604 sched_smt_power_savings_show,
8605 sched_smt_power_savings_store);
8608 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
8612 #ifdef CONFIG_SCHED_SMT
8614 err = sysfs_create_file(&cls->kset.kobj,
8615 &attr_sched_smt_power_savings.attr);
8617 #ifdef CONFIG_SCHED_MC
8618 if (!err && mc_capable())
8619 err = sysfs_create_file(&cls->kset.kobj,
8620 &attr_sched_mc_power_savings.attr);
8624 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
8626 #ifndef CONFIG_CPUSETS
8628 * Add online and remove offline CPUs from the scheduler domains.
8629 * When cpusets are enabled they take over this function.
8631 static int update_sched_domains(struct notifier_block *nfb,
8632 unsigned long action, void *hcpu)
8636 case CPU_ONLINE_FROZEN:
8638 case CPU_DEAD_FROZEN:
8639 partition_sched_domains(1, NULL, NULL);
8648 static int update_runtime(struct notifier_block *nfb,
8649 unsigned long action, void *hcpu)
8651 int cpu = (int)(long)hcpu;
8654 case CPU_DOWN_PREPARE:
8655 case CPU_DOWN_PREPARE_FROZEN:
8656 disable_runtime(cpu_rq(cpu));
8659 case CPU_DOWN_FAILED:
8660 case CPU_DOWN_FAILED_FROZEN:
8662 case CPU_ONLINE_FROZEN:
8663 enable_runtime(cpu_rq(cpu));
8671 void __init sched_init_smp(void)
8673 cpumask_var_t non_isolated_cpus;
8675 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
8677 #if defined(CONFIG_NUMA)
8678 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
8680 BUG_ON(sched_group_nodes_bycpu == NULL);
8683 mutex_lock(&sched_domains_mutex);
8684 arch_init_sched_domains(cpu_online_mask);
8685 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
8686 if (cpumask_empty(non_isolated_cpus))
8687 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
8688 mutex_unlock(&sched_domains_mutex);
8691 #ifndef CONFIG_CPUSETS
8692 /* XXX: Theoretical race here - CPU may be hotplugged now */
8693 hotcpu_notifier(update_sched_domains, 0);
8696 /* RT runtime code needs to handle some hotplug events */
8697 hotcpu_notifier(update_runtime, 0);
8701 /* Move init over to a non-isolated CPU */
8702 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
8704 sched_init_granularity();
8705 free_cpumask_var(non_isolated_cpus);
8707 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
8708 init_sched_rt_class();
8711 void __init sched_init_smp(void)
8713 sched_init_granularity();
8715 #endif /* CONFIG_SMP */
8717 int in_sched_functions(unsigned long addr)
8719 return in_lock_functions(addr) ||
8720 (addr >= (unsigned long)__sched_text_start
8721 && addr < (unsigned long)__sched_text_end);
8724 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8726 cfs_rq->tasks_timeline = RB_ROOT;
8727 INIT_LIST_HEAD(&cfs_rq->tasks);
8728 #ifdef CONFIG_FAIR_GROUP_SCHED
8731 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8734 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8736 struct rt_prio_array *array;
8739 array = &rt_rq->active;
8740 for (i = 0; i < MAX_RT_PRIO; i++) {
8741 INIT_LIST_HEAD(array->queue + i);
8742 __clear_bit(i, array->bitmap);
8744 /* delimiter for bitsearch: */
8745 __set_bit(MAX_RT_PRIO, array->bitmap);
8747 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8748 rt_rq->highest_prio.curr = MAX_RT_PRIO;
8750 rt_rq->highest_prio.next = MAX_RT_PRIO;
8754 rt_rq->rt_nr_migratory = 0;
8755 rt_rq->overloaded = 0;
8756 plist_head_init(&rq->rt.pushable_tasks, &rq->lock);
8760 rt_rq->rt_throttled = 0;
8761 rt_rq->rt_runtime = 0;
8762 spin_lock_init(&rt_rq->rt_runtime_lock);
8764 #ifdef CONFIG_RT_GROUP_SCHED
8765 rt_rq->rt_nr_boosted = 0;
8770 #ifdef CONFIG_FAIR_GROUP_SCHED
8771 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8772 struct sched_entity *se, int cpu, int add,
8773 struct sched_entity *parent)
8775 struct rq *rq = cpu_rq(cpu);
8776 tg->cfs_rq[cpu] = cfs_rq;
8777 init_cfs_rq(cfs_rq, rq);
8780 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8783 /* se could be NULL for init_task_group */
8788 se->cfs_rq = &rq->cfs;
8790 se->cfs_rq = parent->my_q;
8793 se->load.weight = tg->shares;
8794 se->load.inv_weight = 0;
8795 se->parent = parent;
8799 #ifdef CONFIG_RT_GROUP_SCHED
8800 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8801 struct sched_rt_entity *rt_se, int cpu, int add,
8802 struct sched_rt_entity *parent)
8804 struct rq *rq = cpu_rq(cpu);
8806 tg->rt_rq[cpu] = rt_rq;
8807 init_rt_rq(rt_rq, rq);
8809 rt_rq->rt_se = rt_se;
8810 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8812 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8814 tg->rt_se[cpu] = rt_se;
8819 rt_se->rt_rq = &rq->rt;
8821 rt_se->rt_rq = parent->my_q;
8823 rt_se->my_q = rt_rq;
8824 rt_se->parent = parent;
8825 INIT_LIST_HEAD(&rt_se->run_list);
8829 void __init sched_init(void)
8832 unsigned long alloc_size = 0, ptr;
8834 #ifdef CONFIG_FAIR_GROUP_SCHED
8835 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8837 #ifdef CONFIG_RT_GROUP_SCHED
8838 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8840 #ifdef CONFIG_USER_SCHED
8843 #ifdef CONFIG_CPUMASK_OFFSTACK
8844 alloc_size += num_possible_cpus() * cpumask_size();
8847 * As sched_init() is called before page_alloc is setup,
8848 * we use alloc_bootmem().
8851 ptr = (unsigned long)alloc_bootmem(alloc_size);
8853 #ifdef CONFIG_FAIR_GROUP_SCHED
8854 init_task_group.se = (struct sched_entity **)ptr;
8855 ptr += nr_cpu_ids * sizeof(void **);
8857 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8858 ptr += nr_cpu_ids * sizeof(void **);
8860 #ifdef CONFIG_USER_SCHED
8861 root_task_group.se = (struct sched_entity **)ptr;
8862 ptr += nr_cpu_ids * sizeof(void **);
8864 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8865 ptr += nr_cpu_ids * sizeof(void **);
8866 #endif /* CONFIG_USER_SCHED */
8867 #endif /* CONFIG_FAIR_GROUP_SCHED */
8868 #ifdef CONFIG_RT_GROUP_SCHED
8869 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8870 ptr += nr_cpu_ids * sizeof(void **);
8872 init_task_group.rt_rq = (struct rt_rq **)ptr;
8873 ptr += nr_cpu_ids * sizeof(void **);
8875 #ifdef CONFIG_USER_SCHED
8876 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8877 ptr += nr_cpu_ids * sizeof(void **);
8879 root_task_group.rt_rq = (struct rt_rq **)ptr;
8880 ptr += nr_cpu_ids * sizeof(void **);
8881 #endif /* CONFIG_USER_SCHED */
8882 #endif /* CONFIG_RT_GROUP_SCHED */
8883 #ifdef CONFIG_CPUMASK_OFFSTACK
8884 for_each_possible_cpu(i) {
8885 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
8886 ptr += cpumask_size();
8888 #endif /* CONFIG_CPUMASK_OFFSTACK */
8892 init_defrootdomain();
8895 init_rt_bandwidth(&def_rt_bandwidth,
8896 global_rt_period(), global_rt_runtime());
8898 #ifdef CONFIG_RT_GROUP_SCHED
8899 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8900 global_rt_period(), global_rt_runtime());
8901 #ifdef CONFIG_USER_SCHED
8902 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8903 global_rt_period(), RUNTIME_INF);
8904 #endif /* CONFIG_USER_SCHED */
8905 #endif /* CONFIG_RT_GROUP_SCHED */
8907 #ifdef CONFIG_GROUP_SCHED
8908 list_add(&init_task_group.list, &task_groups);
8909 INIT_LIST_HEAD(&init_task_group.children);
8911 #ifdef CONFIG_USER_SCHED
8912 INIT_LIST_HEAD(&root_task_group.children);
8913 init_task_group.parent = &root_task_group;
8914 list_add(&init_task_group.siblings, &root_task_group.children);
8915 #endif /* CONFIG_USER_SCHED */
8916 #endif /* CONFIG_GROUP_SCHED */
8918 for_each_possible_cpu(i) {
8922 spin_lock_init(&rq->lock);
8924 init_cfs_rq(&rq->cfs, rq);
8925 init_rt_rq(&rq->rt, rq);
8926 #ifdef CONFIG_FAIR_GROUP_SCHED
8927 init_task_group.shares = init_task_group_load;
8928 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8929 #ifdef CONFIG_CGROUP_SCHED
8931 * How much cpu bandwidth does init_task_group get?
8933 * In case of task-groups formed thr' the cgroup filesystem, it
8934 * gets 100% of the cpu resources in the system. This overall
8935 * system cpu resource is divided among the tasks of
8936 * init_task_group and its child task-groups in a fair manner,
8937 * based on each entity's (task or task-group's) weight
8938 * (se->load.weight).
8940 * In other words, if init_task_group has 10 tasks of weight
8941 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8942 * then A0's share of the cpu resource is:
8944 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8946 * We achieve this by letting init_task_group's tasks sit
8947 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8949 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8950 #elif defined CONFIG_USER_SCHED
8951 root_task_group.shares = NICE_0_LOAD;
8952 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8954 * In case of task-groups formed thr' the user id of tasks,
8955 * init_task_group represents tasks belonging to root user.
8956 * Hence it forms a sibling of all subsequent groups formed.
8957 * In this case, init_task_group gets only a fraction of overall
8958 * system cpu resource, based on the weight assigned to root
8959 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8960 * by letting tasks of init_task_group sit in a separate cfs_rq
8961 * (init_cfs_rq) and having one entity represent this group of
8962 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8964 init_tg_cfs_entry(&init_task_group,
8965 &per_cpu(init_cfs_rq, i),
8966 &per_cpu(init_sched_entity, i), i, 1,
8967 root_task_group.se[i]);
8970 #endif /* CONFIG_FAIR_GROUP_SCHED */
8972 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8973 #ifdef CONFIG_RT_GROUP_SCHED
8974 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8975 #ifdef CONFIG_CGROUP_SCHED
8976 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8977 #elif defined CONFIG_USER_SCHED
8978 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8979 init_tg_rt_entry(&init_task_group,
8980 &per_cpu(init_rt_rq, i),
8981 &per_cpu(init_sched_rt_entity, i), i, 1,
8982 root_task_group.rt_se[i]);
8986 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8987 rq->cpu_load[j] = 0;
8991 rq->active_balance = 0;
8992 rq->next_balance = jiffies;
8996 rq->migration_thread = NULL;
8997 INIT_LIST_HEAD(&rq->migration_queue);
8998 rq_attach_root(rq, &def_root_domain);
9001 atomic_set(&rq->nr_iowait, 0);
9004 set_load_weight(&init_task);
9006 #ifdef CONFIG_PREEMPT_NOTIFIERS
9007 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
9011 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9014 #ifdef CONFIG_RT_MUTEXES
9015 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
9019 * The boot idle thread does lazy MMU switching as well:
9021 atomic_inc(&init_mm.mm_count);
9022 enter_lazy_tlb(&init_mm, current);
9025 * Make us the idle thread. Technically, schedule() should not be
9026 * called from this thread, however somewhere below it might be,
9027 * but because we are the idle thread, we just pick up running again
9028 * when this runqueue becomes "idle".
9030 init_idle(current, smp_processor_id());
9032 * During early bootup we pretend to be a normal task:
9034 current->sched_class = &fair_sched_class;
9036 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
9037 alloc_bootmem_cpumask_var(&nohz_cpu_mask);
9040 alloc_bootmem_cpumask_var(&nohz.cpu_mask);
9042 alloc_bootmem_cpumask_var(&cpu_isolated_map);
9045 scheduler_running = 1;
9048 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
9049 void __might_sleep(char *file, int line)
9052 static unsigned long prev_jiffy; /* ratelimiting */
9054 if ((!in_atomic() && !irqs_disabled()) ||
9055 system_state != SYSTEM_RUNNING || oops_in_progress)
9057 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9059 prev_jiffy = jiffies;
9062 "BUG: sleeping function called from invalid context at %s:%d\n",
9065 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9066 in_atomic(), irqs_disabled(),
9067 current->pid, current->comm);
9069 debug_show_held_locks(current);
9070 if (irqs_disabled())
9071 print_irqtrace_events(current);
9075 EXPORT_SYMBOL(__might_sleep);
9078 #ifdef CONFIG_MAGIC_SYSRQ
9079 static void normalize_task(struct rq *rq, struct task_struct *p)
9083 update_rq_clock(rq);
9084 on_rq = p->se.on_rq;
9086 deactivate_task(rq, p, 0);
9087 __setscheduler(rq, p, SCHED_NORMAL, 0);
9089 activate_task(rq, p, 0);
9090 resched_task(rq->curr);
9094 void normalize_rt_tasks(void)
9096 struct task_struct *g, *p;
9097 unsigned long flags;
9100 read_lock_irqsave(&tasklist_lock, flags);
9101 do_each_thread(g, p) {
9103 * Only normalize user tasks:
9108 p->se.exec_start = 0;
9109 #ifdef CONFIG_SCHEDSTATS
9110 p->se.wait_start = 0;
9111 p->se.sleep_start = 0;
9112 p->se.block_start = 0;
9117 * Renice negative nice level userspace
9120 if (TASK_NICE(p) < 0 && p->mm)
9121 set_user_nice(p, 0);
9125 spin_lock(&p->pi_lock);
9126 rq = __task_rq_lock(p);
9128 normalize_task(rq, p);
9130 __task_rq_unlock(rq);
9131 spin_unlock(&p->pi_lock);
9132 } while_each_thread(g, p);
9134 read_unlock_irqrestore(&tasklist_lock, flags);
9137 #endif /* CONFIG_MAGIC_SYSRQ */
9141 * These functions are only useful for the IA64 MCA handling.
9143 * They can only be called when the whole system has been
9144 * stopped - every CPU needs to be quiescent, and no scheduling
9145 * activity can take place. Using them for anything else would
9146 * be a serious bug, and as a result, they aren't even visible
9147 * under any other configuration.
9151 * curr_task - return the current task for a given cpu.
9152 * @cpu: the processor in question.
9154 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9156 struct task_struct *curr_task(int cpu)
9158 return cpu_curr(cpu);
9162 * set_curr_task - set the current task for a given cpu.
9163 * @cpu: the processor in question.
9164 * @p: the task pointer to set.
9166 * Description: This function must only be used when non-maskable interrupts
9167 * are serviced on a separate stack. It allows the architecture to switch the
9168 * notion of the current task on a cpu in a non-blocking manner. This function
9169 * must be called with all CPU's synchronized, and interrupts disabled, the
9170 * and caller must save the original value of the current task (see
9171 * curr_task() above) and restore that value before reenabling interrupts and
9172 * re-starting the system.
9174 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9176 void set_curr_task(int cpu, struct task_struct *p)
9183 #ifdef CONFIG_FAIR_GROUP_SCHED
9184 static void free_fair_sched_group(struct task_group *tg)
9188 for_each_possible_cpu(i) {
9190 kfree(tg->cfs_rq[i]);
9200 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9202 struct cfs_rq *cfs_rq;
9203 struct sched_entity *se;
9207 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
9210 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
9214 tg->shares = NICE_0_LOAD;
9216 for_each_possible_cpu(i) {
9219 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
9220 GFP_KERNEL, cpu_to_node(i));
9224 se = kzalloc_node(sizeof(struct sched_entity),
9225 GFP_KERNEL, cpu_to_node(i));
9229 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
9238 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9240 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
9241 &cpu_rq(cpu)->leaf_cfs_rq_list);
9244 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9246 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
9248 #else /* !CONFG_FAIR_GROUP_SCHED */
9249 static inline void free_fair_sched_group(struct task_group *tg)
9254 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9259 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9263 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9266 #endif /* CONFIG_FAIR_GROUP_SCHED */
9268 #ifdef CONFIG_RT_GROUP_SCHED
9269 static void free_rt_sched_group(struct task_group *tg)
9273 destroy_rt_bandwidth(&tg->rt_bandwidth);
9275 for_each_possible_cpu(i) {
9277 kfree(tg->rt_rq[i]);
9279 kfree(tg->rt_se[i]);
9287 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9289 struct rt_rq *rt_rq;
9290 struct sched_rt_entity *rt_se;
9294 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
9297 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
9301 init_rt_bandwidth(&tg->rt_bandwidth,
9302 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
9304 for_each_possible_cpu(i) {
9307 rt_rq = kzalloc_node(sizeof(struct rt_rq),
9308 GFP_KERNEL, cpu_to_node(i));
9312 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
9313 GFP_KERNEL, cpu_to_node(i));
9317 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
9326 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9328 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
9329 &cpu_rq(cpu)->leaf_rt_rq_list);
9332 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9334 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
9336 #else /* !CONFIG_RT_GROUP_SCHED */
9337 static inline void free_rt_sched_group(struct task_group *tg)
9342 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9347 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
9351 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
9354 #endif /* CONFIG_RT_GROUP_SCHED */
9356 #ifdef CONFIG_GROUP_SCHED
9357 static void free_sched_group(struct task_group *tg)
9359 free_fair_sched_group(tg);
9360 free_rt_sched_group(tg);
9364 /* allocate runqueue etc for a new task group */
9365 struct task_group *sched_create_group(struct task_group *parent)
9367 struct task_group *tg;
9368 unsigned long flags;
9371 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
9373 return ERR_PTR(-ENOMEM);
9375 if (!alloc_fair_sched_group(tg, parent))
9378 if (!alloc_rt_sched_group(tg, parent))
9381 spin_lock_irqsave(&task_group_lock, flags);
9382 for_each_possible_cpu(i) {
9383 register_fair_sched_group(tg, i);
9384 register_rt_sched_group(tg, i);
9386 list_add_rcu(&tg->list, &task_groups);
9388 WARN_ON(!parent); /* root should already exist */
9390 tg->parent = parent;
9391 INIT_LIST_HEAD(&tg->children);
9392 list_add_rcu(&tg->siblings, &parent->children);
9393 spin_unlock_irqrestore(&task_group_lock, flags);
9398 free_sched_group(tg);
9399 return ERR_PTR(-ENOMEM);
9402 /* rcu callback to free various structures associated with a task group */
9403 static void free_sched_group_rcu(struct rcu_head *rhp)
9405 /* now it should be safe to free those cfs_rqs */
9406 free_sched_group(container_of(rhp, struct task_group, rcu));
9409 /* Destroy runqueue etc associated with a task group */
9410 void sched_destroy_group(struct task_group *tg)
9412 unsigned long flags;
9415 spin_lock_irqsave(&task_group_lock, flags);
9416 for_each_possible_cpu(i) {
9417 unregister_fair_sched_group(tg, i);
9418 unregister_rt_sched_group(tg, i);
9420 list_del_rcu(&tg->list);
9421 list_del_rcu(&tg->siblings);
9422 spin_unlock_irqrestore(&task_group_lock, flags);
9424 /* wait for possible concurrent references to cfs_rqs complete */
9425 call_rcu(&tg->rcu, free_sched_group_rcu);
9428 /* change task's runqueue when it moves between groups.
9429 * The caller of this function should have put the task in its new group
9430 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
9431 * reflect its new group.
9433 void sched_move_task(struct task_struct *tsk)
9436 unsigned long flags;
9439 rq = task_rq_lock(tsk, &flags);
9441 update_rq_clock(rq);
9443 running = task_current(rq, tsk);
9444 on_rq = tsk->se.on_rq;
9447 dequeue_task(rq, tsk, 0);
9448 if (unlikely(running))
9449 tsk->sched_class->put_prev_task(rq, tsk);
9451 set_task_rq(tsk, task_cpu(tsk));
9453 #ifdef CONFIG_FAIR_GROUP_SCHED
9454 if (tsk->sched_class->moved_group)
9455 tsk->sched_class->moved_group(tsk);
9458 if (unlikely(running))
9459 tsk->sched_class->set_curr_task(rq);
9461 enqueue_task(rq, tsk, 0);
9463 task_rq_unlock(rq, &flags);
9465 #endif /* CONFIG_GROUP_SCHED */
9467 #ifdef CONFIG_FAIR_GROUP_SCHED
9468 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
9470 struct cfs_rq *cfs_rq = se->cfs_rq;
9475 dequeue_entity(cfs_rq, se, 0);
9477 se->load.weight = shares;
9478 se->load.inv_weight = 0;
9481 enqueue_entity(cfs_rq, se, 0);
9484 static void set_se_shares(struct sched_entity *se, unsigned long shares)
9486 struct cfs_rq *cfs_rq = se->cfs_rq;
9487 struct rq *rq = cfs_rq->rq;
9488 unsigned long flags;
9490 spin_lock_irqsave(&rq->lock, flags);
9491 __set_se_shares(se, shares);
9492 spin_unlock_irqrestore(&rq->lock, flags);
9495 static DEFINE_MUTEX(shares_mutex);
9497 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
9500 unsigned long flags;
9503 * We can't change the weight of the root cgroup.
9508 if (shares < MIN_SHARES)
9509 shares = MIN_SHARES;
9510 else if (shares > MAX_SHARES)
9511 shares = MAX_SHARES;
9513 mutex_lock(&shares_mutex);
9514 if (tg->shares == shares)
9517 spin_lock_irqsave(&task_group_lock, flags);
9518 for_each_possible_cpu(i)
9519 unregister_fair_sched_group(tg, i);
9520 list_del_rcu(&tg->siblings);
9521 spin_unlock_irqrestore(&task_group_lock, flags);
9523 /* wait for any ongoing reference to this group to finish */
9524 synchronize_sched();
9527 * Now we are free to modify the group's share on each cpu
9528 * w/o tripping rebalance_share or load_balance_fair.
9530 tg->shares = shares;
9531 for_each_possible_cpu(i) {
9535 cfs_rq_set_shares(tg->cfs_rq[i], 0);
9536 set_se_shares(tg->se[i], shares);
9540 * Enable load balance activity on this group, by inserting it back on
9541 * each cpu's rq->leaf_cfs_rq_list.
9543 spin_lock_irqsave(&task_group_lock, flags);
9544 for_each_possible_cpu(i)
9545 register_fair_sched_group(tg, i);
9546 list_add_rcu(&tg->siblings, &tg->parent->children);
9547 spin_unlock_irqrestore(&task_group_lock, flags);
9549 mutex_unlock(&shares_mutex);
9553 unsigned long sched_group_shares(struct task_group *tg)
9559 #ifdef CONFIG_RT_GROUP_SCHED
9561 * Ensure that the real time constraints are schedulable.
9563 static DEFINE_MUTEX(rt_constraints_mutex);
9565 static unsigned long to_ratio(u64 period, u64 runtime)
9567 if (runtime == RUNTIME_INF)
9570 return div64_u64(runtime << 20, period);
9573 /* Must be called with tasklist_lock held */
9574 static inline int tg_has_rt_tasks(struct task_group *tg)
9576 struct task_struct *g, *p;
9578 do_each_thread(g, p) {
9579 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
9581 } while_each_thread(g, p);
9586 struct rt_schedulable_data {
9587 struct task_group *tg;
9592 static int tg_schedulable(struct task_group *tg, void *data)
9594 struct rt_schedulable_data *d = data;
9595 struct task_group *child;
9596 unsigned long total, sum = 0;
9597 u64 period, runtime;
9599 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
9600 runtime = tg->rt_bandwidth.rt_runtime;
9603 period = d->rt_period;
9604 runtime = d->rt_runtime;
9607 #ifdef CONFIG_USER_SCHED
9608 if (tg == &root_task_group) {
9609 period = global_rt_period();
9610 runtime = global_rt_runtime();
9615 * Cannot have more runtime than the period.
9617 if (runtime > period && runtime != RUNTIME_INF)
9621 * Ensure we don't starve existing RT tasks.
9623 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
9626 total = to_ratio(period, runtime);
9629 * Nobody can have more than the global setting allows.
9631 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
9635 * The sum of our children's runtime should not exceed our own.
9637 list_for_each_entry_rcu(child, &tg->children, siblings) {
9638 period = ktime_to_ns(child->rt_bandwidth.rt_period);
9639 runtime = child->rt_bandwidth.rt_runtime;
9641 if (child == d->tg) {
9642 period = d->rt_period;
9643 runtime = d->rt_runtime;
9646 sum += to_ratio(period, runtime);
9655 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
9657 struct rt_schedulable_data data = {
9659 .rt_period = period,
9660 .rt_runtime = runtime,
9663 return walk_tg_tree(tg_schedulable, tg_nop, &data);
9666 static int tg_set_bandwidth(struct task_group *tg,
9667 u64 rt_period, u64 rt_runtime)
9671 mutex_lock(&rt_constraints_mutex);
9672 read_lock(&tasklist_lock);
9673 err = __rt_schedulable(tg, rt_period, rt_runtime);
9677 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
9678 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
9679 tg->rt_bandwidth.rt_runtime = rt_runtime;
9681 for_each_possible_cpu(i) {
9682 struct rt_rq *rt_rq = tg->rt_rq[i];
9684 spin_lock(&rt_rq->rt_runtime_lock);
9685 rt_rq->rt_runtime = rt_runtime;
9686 spin_unlock(&rt_rq->rt_runtime_lock);
9688 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
9690 read_unlock(&tasklist_lock);
9691 mutex_unlock(&rt_constraints_mutex);
9696 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
9698 u64 rt_runtime, rt_period;
9700 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
9701 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
9702 if (rt_runtime_us < 0)
9703 rt_runtime = RUNTIME_INF;
9705 return tg_set_bandwidth(tg, rt_period, rt_runtime);
9708 long sched_group_rt_runtime(struct task_group *tg)
9712 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
9715 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
9716 do_div(rt_runtime_us, NSEC_PER_USEC);
9717 return rt_runtime_us;
9720 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
9722 u64 rt_runtime, rt_period;
9724 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
9725 rt_runtime = tg->rt_bandwidth.rt_runtime;
9730 return tg_set_bandwidth(tg, rt_period, rt_runtime);
9733 long sched_group_rt_period(struct task_group *tg)
9737 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
9738 do_div(rt_period_us, NSEC_PER_USEC);
9739 return rt_period_us;
9742 static int sched_rt_global_constraints(void)
9744 u64 runtime, period;
9747 if (sysctl_sched_rt_period <= 0)
9750 runtime = global_rt_runtime();
9751 period = global_rt_period();
9754 * Sanity check on the sysctl variables.
9756 if (runtime > period && runtime != RUNTIME_INF)
9759 mutex_lock(&rt_constraints_mutex);
9760 read_lock(&tasklist_lock);
9761 ret = __rt_schedulable(NULL, 0, 0);
9762 read_unlock(&tasklist_lock);
9763 mutex_unlock(&rt_constraints_mutex);
9768 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
9770 /* Don't accept realtime tasks when there is no way for them to run */
9771 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
9777 #else /* !CONFIG_RT_GROUP_SCHED */
9778 static int sched_rt_global_constraints(void)
9780 unsigned long flags;
9783 if (sysctl_sched_rt_period <= 0)
9786 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9787 for_each_possible_cpu(i) {
9788 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9790 spin_lock(&rt_rq->rt_runtime_lock);
9791 rt_rq->rt_runtime = global_rt_runtime();
9792 spin_unlock(&rt_rq->rt_runtime_lock);
9794 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9798 #endif /* CONFIG_RT_GROUP_SCHED */
9800 int sched_rt_handler(struct ctl_table *table, int write,
9801 struct file *filp, void __user *buffer, size_t *lenp,
9805 int old_period, old_runtime;
9806 static DEFINE_MUTEX(mutex);
9809 old_period = sysctl_sched_rt_period;
9810 old_runtime = sysctl_sched_rt_runtime;
9812 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9814 if (!ret && write) {
9815 ret = sched_rt_global_constraints();
9817 sysctl_sched_rt_period = old_period;
9818 sysctl_sched_rt_runtime = old_runtime;
9820 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9821 def_rt_bandwidth.rt_period =
9822 ns_to_ktime(global_rt_period());
9825 mutex_unlock(&mutex);
9830 #ifdef CONFIG_CGROUP_SCHED
9832 /* return corresponding task_group object of a cgroup */
9833 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9835 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9836 struct task_group, css);
9839 static struct cgroup_subsys_state *
9840 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9842 struct task_group *tg, *parent;
9844 if (!cgrp->parent) {
9845 /* This is early initialization for the top cgroup */
9846 return &init_task_group.css;
9849 parent = cgroup_tg(cgrp->parent);
9850 tg = sched_create_group(parent);
9852 return ERR_PTR(-ENOMEM);
9858 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9860 struct task_group *tg = cgroup_tg(cgrp);
9862 sched_destroy_group(tg);
9866 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9867 struct task_struct *tsk)
9869 #ifdef CONFIG_RT_GROUP_SCHED
9870 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
9873 /* We don't support RT-tasks being in separate groups */
9874 if (tsk->sched_class != &fair_sched_class)
9882 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9883 struct cgroup *old_cont, struct task_struct *tsk)
9885 sched_move_task(tsk);
9888 #ifdef CONFIG_FAIR_GROUP_SCHED
9889 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9892 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9895 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9897 struct task_group *tg = cgroup_tg(cgrp);
9899 return (u64) tg->shares;
9901 #endif /* CONFIG_FAIR_GROUP_SCHED */
9903 #ifdef CONFIG_RT_GROUP_SCHED
9904 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9907 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9910 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9912 return sched_group_rt_runtime(cgroup_tg(cgrp));
9915 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9918 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9921 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9923 return sched_group_rt_period(cgroup_tg(cgrp));
9925 #endif /* CONFIG_RT_GROUP_SCHED */
9927 static struct cftype cpu_files[] = {
9928 #ifdef CONFIG_FAIR_GROUP_SCHED
9931 .read_u64 = cpu_shares_read_u64,
9932 .write_u64 = cpu_shares_write_u64,
9935 #ifdef CONFIG_RT_GROUP_SCHED
9937 .name = "rt_runtime_us",
9938 .read_s64 = cpu_rt_runtime_read,
9939 .write_s64 = cpu_rt_runtime_write,
9942 .name = "rt_period_us",
9943 .read_u64 = cpu_rt_period_read_uint,
9944 .write_u64 = cpu_rt_period_write_uint,
9949 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9951 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9954 struct cgroup_subsys cpu_cgroup_subsys = {
9956 .create = cpu_cgroup_create,
9957 .destroy = cpu_cgroup_destroy,
9958 .can_attach = cpu_cgroup_can_attach,
9959 .attach = cpu_cgroup_attach,
9960 .populate = cpu_cgroup_populate,
9961 .subsys_id = cpu_cgroup_subsys_id,
9965 #endif /* CONFIG_CGROUP_SCHED */
9967 #ifdef CONFIG_CGROUP_CPUACCT
9970 * CPU accounting code for task groups.
9972 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9973 * (balbir@in.ibm.com).
9976 /* track cpu usage of a group of tasks and its child groups */
9978 struct cgroup_subsys_state css;
9979 /* cpuusage holds pointer to a u64-type object on every cpu */
9981 struct cpuacct *parent;
9984 struct cgroup_subsys cpuacct_subsys;
9986 /* return cpu accounting group corresponding to this container */
9987 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9989 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9990 struct cpuacct, css);
9993 /* return cpu accounting group to which this task belongs */
9994 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9996 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9997 struct cpuacct, css);
10000 /* create a new cpu accounting group */
10001 static struct cgroup_subsys_state *cpuacct_create(
10002 struct cgroup_subsys *ss, struct cgroup *cgrp)
10004 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
10007 return ERR_PTR(-ENOMEM);
10009 ca->cpuusage = alloc_percpu(u64);
10010 if (!ca->cpuusage) {
10012 return ERR_PTR(-ENOMEM);
10016 ca->parent = cgroup_ca(cgrp->parent);
10021 /* destroy an existing cpu accounting group */
10023 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10025 struct cpuacct *ca = cgroup_ca(cgrp);
10027 free_percpu(ca->cpuusage);
10031 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
10033 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10036 #ifndef CONFIG_64BIT
10038 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
10040 spin_lock_irq(&cpu_rq(cpu)->lock);
10042 spin_unlock_irq(&cpu_rq(cpu)->lock);
10050 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
10052 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10054 #ifndef CONFIG_64BIT
10056 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
10058 spin_lock_irq(&cpu_rq(cpu)->lock);
10060 spin_unlock_irq(&cpu_rq(cpu)->lock);
10066 /* return total cpu usage (in nanoseconds) of a group */
10067 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
10069 struct cpuacct *ca = cgroup_ca(cgrp);
10070 u64 totalcpuusage = 0;
10073 for_each_present_cpu(i)
10074 totalcpuusage += cpuacct_cpuusage_read(ca, i);
10076 return totalcpuusage;
10079 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
10082 struct cpuacct *ca = cgroup_ca(cgrp);
10091 for_each_present_cpu(i)
10092 cpuacct_cpuusage_write(ca, i, 0);
10098 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
10099 struct seq_file *m)
10101 struct cpuacct *ca = cgroup_ca(cgroup);
10105 for_each_present_cpu(i) {
10106 percpu = cpuacct_cpuusage_read(ca, i);
10107 seq_printf(m, "%llu ", (unsigned long long) percpu);
10109 seq_printf(m, "\n");
10113 static struct cftype files[] = {
10116 .read_u64 = cpuusage_read,
10117 .write_u64 = cpuusage_write,
10120 .name = "usage_percpu",
10121 .read_seq_string = cpuacct_percpu_seq_read,
10126 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
10128 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
10132 * charge this task's execution time to its accounting group.
10134 * called with rq->lock held.
10136 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
10138 struct cpuacct *ca;
10141 if (unlikely(!cpuacct_subsys.active))
10144 cpu = task_cpu(tsk);
10147 for (; ca; ca = ca->parent) {
10148 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10149 *cpuusage += cputime;
10153 struct cgroup_subsys cpuacct_subsys = {
10155 .create = cpuacct_create,
10156 .destroy = cpuacct_destroy,
10157 .populate = cpuacct_populate,
10158 .subsys_id = cpuacct_subsys_id,
10160 #endif /* CONFIG_CGROUP_CPUACCT */