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/perf_event.h>
43 #include <linux/security.h>
44 #include <linux/notifier.h>
45 #include <linux/profile.h>
46 #include <linux/freezer.h>
47 #include <linux/vmalloc.h>
48 #include <linux/blkdev.h>
49 #include <linux/delay.h>
50 #include <linux/pid_namespace.h>
51 #include <linux/smp.h>
52 #include <linux/threads.h>
53 #include <linux/timer.h>
54 #include <linux/rcupdate.h>
55 #include <linux/cpu.h>
56 #include <linux/cpuset.h>
57 #include <linux/percpu.h>
58 #include <linux/kthread.h>
59 #include <linux/proc_fs.h>
60 #include <linux/seq_file.h>
61 #include <linux/sysctl.h>
62 #include <linux/syscalls.h>
63 #include <linux/times.h>
64 #include <linux/tsacct_kern.h>
65 #include <linux/kprobes.h>
66 #include <linux/delayacct.h>
67 #include <linux/unistd.h>
68 #include <linux/pagemap.h>
69 #include <linux/hrtimer.h>
70 #include <linux/tick.h>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
73 #include <linux/ftrace.h>
76 #include <asm/irq_regs.h>
78 #include "sched_cpupri.h"
80 #define CREATE_TRACE_POINTS
81 #include <trace/events/sched.h>
84 * Convert user-nice values [ -20 ... 0 ... 19 ]
85 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
88 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
89 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
90 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
93 * 'User priority' is the nice value converted to something we
94 * can work with better when scaling various scheduler parameters,
95 * it's a [ 0 ... 39 ] range.
97 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
98 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
99 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
102 * Helpers for converting nanosecond timing to jiffy resolution
104 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
106 #define NICE_0_LOAD SCHED_LOAD_SCALE
107 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
110 * These are the 'tuning knobs' of the scheduler:
112 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
113 * Timeslices get refilled after they expire.
115 #define DEF_TIMESLICE (100 * HZ / 1000)
118 * single value that denotes runtime == period, ie unlimited time.
120 #define RUNTIME_INF ((u64)~0ULL)
122 static inline int rt_policy(int policy)
124 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
129 static inline int task_has_rt_policy(struct task_struct *p)
131 return rt_policy(p->policy);
135 * This is the priority-queue data structure of the RT scheduling class:
137 struct rt_prio_array {
138 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
139 struct list_head queue[MAX_RT_PRIO];
142 struct rt_bandwidth {
143 /* nests inside the rq lock: */
144 raw_spinlock_t rt_runtime_lock;
147 struct hrtimer rt_period_timer;
150 static struct rt_bandwidth def_rt_bandwidth;
152 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
154 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
156 struct rt_bandwidth *rt_b =
157 container_of(timer, struct rt_bandwidth, rt_period_timer);
163 now = hrtimer_cb_get_time(timer);
164 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
169 idle = do_sched_rt_period_timer(rt_b, overrun);
172 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
176 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
178 rt_b->rt_period = ns_to_ktime(period);
179 rt_b->rt_runtime = runtime;
181 raw_spin_lock_init(&rt_b->rt_runtime_lock);
183 hrtimer_init(&rt_b->rt_period_timer,
184 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
185 rt_b->rt_period_timer.function = sched_rt_period_timer;
188 static inline int rt_bandwidth_enabled(void)
190 return sysctl_sched_rt_runtime >= 0;
193 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
197 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
200 if (hrtimer_active(&rt_b->rt_period_timer))
203 raw_spin_lock(&rt_b->rt_runtime_lock);
208 if (hrtimer_active(&rt_b->rt_period_timer))
211 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
212 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
214 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
215 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
216 delta = ktime_to_ns(ktime_sub(hard, soft));
217 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
218 HRTIMER_MODE_ABS_PINNED, 0);
220 raw_spin_unlock(&rt_b->rt_runtime_lock);
223 #ifdef CONFIG_RT_GROUP_SCHED
224 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
226 hrtimer_cancel(&rt_b->rt_period_timer);
231 * sched_domains_mutex serializes calls to arch_init_sched_domains,
232 * detach_destroy_domains and partition_sched_domains.
234 static DEFINE_MUTEX(sched_domains_mutex);
236 #ifdef CONFIG_GROUP_SCHED
238 #include <linux/cgroup.h>
242 static LIST_HEAD(task_groups);
244 /* task group related information */
246 #ifdef CONFIG_CGROUP_SCHED
247 struct cgroup_subsys_state css;
250 #ifdef CONFIG_USER_SCHED
254 #ifdef CONFIG_FAIR_GROUP_SCHED
255 /* schedulable entities of this group on each cpu */
256 struct sched_entity **se;
257 /* runqueue "owned" by this group on each cpu */
258 struct cfs_rq **cfs_rq;
259 unsigned long shares;
262 #ifdef CONFIG_RT_GROUP_SCHED
263 struct sched_rt_entity **rt_se;
264 struct rt_rq **rt_rq;
266 struct rt_bandwidth rt_bandwidth;
270 struct list_head list;
272 struct task_group *parent;
273 struct list_head siblings;
274 struct list_head children;
277 #ifdef CONFIG_USER_SCHED
279 /* Helper function to pass uid information to create_sched_user() */
280 void set_tg_uid(struct user_struct *user)
282 user->tg->uid = user->uid;
287 * Every UID task group (including init_task_group aka UID-0) will
288 * be a child to this group.
290 struct task_group root_task_group;
292 #ifdef CONFIG_FAIR_GROUP_SCHED
293 /* Default task group's sched entity on each cpu */
294 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
295 /* Default task group's cfs_rq on each cpu */
296 static DEFINE_PER_CPU_SHARED_ALIGNED(struct cfs_rq, init_tg_cfs_rq);
297 #endif /* CONFIG_FAIR_GROUP_SCHED */
299 #ifdef CONFIG_RT_GROUP_SCHED
300 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
301 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rt_rq, init_rt_rq_var);
302 #endif /* CONFIG_RT_GROUP_SCHED */
303 #else /* !CONFIG_USER_SCHED */
304 #define root_task_group init_task_group
305 #endif /* CONFIG_USER_SCHED */
307 /* task_group_lock serializes add/remove of task groups and also changes to
308 * a task group's cpu shares.
310 static DEFINE_SPINLOCK(task_group_lock);
312 #ifdef CONFIG_FAIR_GROUP_SCHED
315 static int root_task_group_empty(void)
317 return list_empty(&root_task_group.children);
321 #ifdef CONFIG_USER_SCHED
322 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
323 #else /* !CONFIG_USER_SCHED */
324 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
325 #endif /* CONFIG_USER_SCHED */
328 * A weight of 0 or 1 can cause arithmetics problems.
329 * A weight of a cfs_rq is the sum of weights of which entities
330 * are queued on this cfs_rq, so a weight of a entity should not be
331 * too large, so as the shares value of a task group.
332 * (The default weight is 1024 - so there's no practical
333 * limitation from this.)
336 #define MAX_SHARES (1UL << 18)
338 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
341 /* Default task group.
342 * Every task in system belong to this group at bootup.
344 struct task_group init_task_group;
346 /* return group to which a task belongs */
347 static inline struct task_group *task_group(struct task_struct *p)
349 struct task_group *tg;
351 #ifdef CONFIG_USER_SCHED
353 tg = __task_cred(p)->user->tg;
355 #elif defined(CONFIG_CGROUP_SCHED)
356 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
357 struct task_group, css);
359 tg = &init_task_group;
364 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
365 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
367 #ifdef CONFIG_FAIR_GROUP_SCHED
368 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
369 p->se.parent = task_group(p)->se[cpu];
372 #ifdef CONFIG_RT_GROUP_SCHED
373 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
374 p->rt.parent = task_group(p)->rt_se[cpu];
380 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
381 static inline struct task_group *task_group(struct task_struct *p)
386 #endif /* CONFIG_GROUP_SCHED */
388 /* CFS-related fields in a runqueue */
390 struct load_weight load;
391 unsigned long nr_running;
396 struct rb_root tasks_timeline;
397 struct rb_node *rb_leftmost;
399 struct list_head tasks;
400 struct list_head *balance_iterator;
403 * 'curr' points to currently running entity on this cfs_rq.
404 * It is set to NULL otherwise (i.e when none are currently running).
406 struct sched_entity *curr, *next, *last;
408 unsigned int nr_spread_over;
410 #ifdef CONFIG_FAIR_GROUP_SCHED
411 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
414 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
415 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
416 * (like users, containers etc.)
418 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
419 * list is used during load balance.
421 struct list_head leaf_cfs_rq_list;
422 struct task_group *tg; /* group that "owns" this runqueue */
426 * the part of load.weight contributed by tasks
428 unsigned long task_weight;
431 * h_load = weight * f(tg)
433 * Where f(tg) is the recursive weight fraction assigned to
436 unsigned long h_load;
439 * this cpu's part of tg->shares
441 unsigned long shares;
444 * load.weight at the time we set shares
446 unsigned long rq_weight;
451 /* Real-Time classes' related field in a runqueue: */
453 struct rt_prio_array active;
454 unsigned long rt_nr_running;
455 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
457 int curr; /* highest queued rt task prio */
459 int next; /* next highest */
464 unsigned long rt_nr_migratory;
465 unsigned long rt_nr_total;
467 struct plist_head pushable_tasks;
472 /* Nests inside the rq lock: */
473 raw_spinlock_t rt_runtime_lock;
475 #ifdef CONFIG_RT_GROUP_SCHED
476 unsigned long rt_nr_boosted;
479 struct list_head leaf_rt_rq_list;
480 struct task_group *tg;
481 struct sched_rt_entity *rt_se;
488 * We add the notion of a root-domain which will be used to define per-domain
489 * variables. Each exclusive cpuset essentially defines an island domain by
490 * fully partitioning the member cpus from any other cpuset. Whenever a new
491 * exclusive cpuset is created, we also create and attach a new root-domain
498 cpumask_var_t online;
501 * The "RT overload" flag: it gets set if a CPU has more than
502 * one runnable RT task.
504 cpumask_var_t rto_mask;
507 struct cpupri cpupri;
512 * By default the system creates a single root-domain with all cpus as
513 * members (mimicking the global state we have today).
515 static struct root_domain def_root_domain;
520 * This is the main, per-CPU runqueue data structure.
522 * Locking rule: those places that want to lock multiple runqueues
523 * (such as the load balancing or the thread migration code), lock
524 * acquire operations must be ordered by ascending &runqueue.
531 * nr_running and cpu_load should be in the same cacheline because
532 * remote CPUs use both these fields when doing load calculation.
534 unsigned long nr_running;
535 #define CPU_LOAD_IDX_MAX 5
536 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
538 unsigned char in_nohz_recently;
540 /* capture load from *all* tasks on this cpu: */
541 struct load_weight load;
542 unsigned long nr_load_updates;
548 #ifdef CONFIG_FAIR_GROUP_SCHED
549 /* list of leaf cfs_rq on this cpu: */
550 struct list_head leaf_cfs_rq_list;
552 #ifdef CONFIG_RT_GROUP_SCHED
553 struct list_head leaf_rt_rq_list;
557 * This is part of a global counter where only the total sum
558 * over all CPUs matters. A task can increase this counter on
559 * one CPU and if it got migrated afterwards it may decrease
560 * it on another CPU. Always updated under the runqueue lock:
562 unsigned long nr_uninterruptible;
564 struct task_struct *curr, *idle;
565 unsigned long next_balance;
566 struct mm_struct *prev_mm;
573 struct root_domain *rd;
574 struct sched_domain *sd;
576 unsigned char idle_at_tick;
577 /* For active balancing */
581 /* cpu of this runqueue: */
585 unsigned long avg_load_per_task;
587 struct task_struct *migration_thread;
588 struct list_head migration_queue;
596 /* calc_load related fields */
597 unsigned long calc_load_update;
598 long calc_load_active;
600 #ifdef CONFIG_SCHED_HRTICK
602 int hrtick_csd_pending;
603 struct call_single_data hrtick_csd;
605 struct hrtimer hrtick_timer;
608 #ifdef CONFIG_SCHEDSTATS
610 struct sched_info rq_sched_info;
611 unsigned long long rq_cpu_time;
612 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
614 /* sys_sched_yield() stats */
615 unsigned int yld_count;
617 /* schedule() stats */
618 unsigned int sched_switch;
619 unsigned int sched_count;
620 unsigned int sched_goidle;
622 /* try_to_wake_up() stats */
623 unsigned int ttwu_count;
624 unsigned int ttwu_local;
627 unsigned int bkl_count;
631 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
634 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
636 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
639 static inline int cpu_of(struct rq *rq)
649 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
650 * See detach_destroy_domains: synchronize_sched for details.
652 * The domain tree of any CPU may only be accessed from within
653 * preempt-disabled sections.
655 #define for_each_domain(cpu, __sd) \
656 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
658 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
659 #define this_rq() (&__get_cpu_var(runqueues))
660 #define task_rq(p) cpu_rq(task_cpu(p))
661 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
662 #define raw_rq() (&__raw_get_cpu_var(runqueues))
664 inline void update_rq_clock(struct rq *rq)
666 rq->clock = sched_clock_cpu(cpu_of(rq));
670 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
672 #ifdef CONFIG_SCHED_DEBUG
673 # define const_debug __read_mostly
675 # define const_debug static const
680 * @cpu: the processor in question.
682 * Returns true if the current cpu runqueue is locked.
683 * This interface allows printk to be called with the runqueue lock
684 * held and know whether or not it is OK to wake up the klogd.
686 int runqueue_is_locked(int cpu)
688 return raw_spin_is_locked(&cpu_rq(cpu)->lock);
692 * Debugging: various feature bits
695 #define SCHED_FEAT(name, enabled) \
696 __SCHED_FEAT_##name ,
699 #include "sched_features.h"
704 #define SCHED_FEAT(name, enabled) \
705 (1UL << __SCHED_FEAT_##name) * enabled |
707 const_debug unsigned int sysctl_sched_features =
708 #include "sched_features.h"
713 #ifdef CONFIG_SCHED_DEBUG
714 #define SCHED_FEAT(name, enabled) \
717 static __read_mostly char *sched_feat_names[] = {
718 #include "sched_features.h"
724 static int sched_feat_show(struct seq_file *m, void *v)
728 for (i = 0; sched_feat_names[i]; i++) {
729 if (!(sysctl_sched_features & (1UL << i)))
731 seq_printf(m, "%s ", sched_feat_names[i]);
739 sched_feat_write(struct file *filp, const char __user *ubuf,
740 size_t cnt, loff_t *ppos)
750 if (copy_from_user(&buf, ubuf, cnt))
755 if (strncmp(buf, "NO_", 3) == 0) {
760 for (i = 0; sched_feat_names[i]; i++) {
761 int len = strlen(sched_feat_names[i]);
763 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
765 sysctl_sched_features &= ~(1UL << i);
767 sysctl_sched_features |= (1UL << i);
772 if (!sched_feat_names[i])
780 static int sched_feat_open(struct inode *inode, struct file *filp)
782 return single_open(filp, sched_feat_show, NULL);
785 static const struct file_operations sched_feat_fops = {
786 .open = sched_feat_open,
787 .write = sched_feat_write,
790 .release = single_release,
793 static __init int sched_init_debug(void)
795 debugfs_create_file("sched_features", 0644, NULL, NULL,
800 late_initcall(sched_init_debug);
804 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
807 * Number of tasks to iterate in a single balance run.
808 * Limited because this is done with IRQs disabled.
810 const_debug unsigned int sysctl_sched_nr_migrate = 32;
813 * ratelimit for updating the group shares.
816 unsigned int sysctl_sched_shares_ratelimit = 250000;
817 unsigned int normalized_sysctl_sched_shares_ratelimit = 250000;
820 * Inject some fuzzyness into changing the per-cpu group shares
821 * this avoids remote rq-locks at the expense of fairness.
824 unsigned int sysctl_sched_shares_thresh = 4;
827 * period over which we average the RT time consumption, measured
832 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
835 * period over which we measure -rt task cpu usage in us.
838 unsigned int sysctl_sched_rt_period = 1000000;
840 static __read_mostly int scheduler_running;
843 * part of the period that we allow rt tasks to run in us.
846 int sysctl_sched_rt_runtime = 950000;
848 static inline u64 global_rt_period(void)
850 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
853 static inline u64 global_rt_runtime(void)
855 if (sysctl_sched_rt_runtime < 0)
858 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
861 #ifndef prepare_arch_switch
862 # define prepare_arch_switch(next) do { } while (0)
864 #ifndef finish_arch_switch
865 # define finish_arch_switch(prev) do { } while (0)
868 static inline int task_current(struct rq *rq, struct task_struct *p)
870 return rq->curr == p;
873 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
874 static inline int task_running(struct rq *rq, struct task_struct *p)
876 return task_current(rq, p);
879 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
883 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
885 #ifdef CONFIG_DEBUG_SPINLOCK
886 /* this is a valid case when another task releases the spinlock */
887 rq->lock.owner = current;
890 * If we are tracking spinlock dependencies then we have to
891 * fix up the runqueue lock - which gets 'carried over' from
894 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
896 raw_spin_unlock_irq(&rq->lock);
899 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
900 static inline int task_running(struct rq *rq, struct task_struct *p)
905 return task_current(rq, p);
909 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
913 * We can optimise this out completely for !SMP, because the
914 * SMP rebalancing from interrupt is the only thing that cares
919 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
920 raw_spin_unlock_irq(&rq->lock);
922 raw_spin_unlock(&rq->lock);
926 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
930 * After ->oncpu is cleared, the task can be moved to a different CPU.
931 * We must ensure this doesn't happen until the switch is completely
937 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
941 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
944 * __task_rq_lock - lock the runqueue a given task resides on.
945 * Must be called interrupts disabled.
947 static inline struct rq *__task_rq_lock(struct task_struct *p)
951 struct rq *rq = task_rq(p);
952 raw_spin_lock(&rq->lock);
953 if (likely(rq == task_rq(p)))
955 raw_spin_unlock(&rq->lock);
960 * task_rq_lock - lock the runqueue a given task resides on and disable
961 * interrupts. Note the ordering: we can safely lookup the task_rq without
962 * explicitly disabling preemption.
964 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
970 local_irq_save(*flags);
972 raw_spin_lock(&rq->lock);
973 if (likely(rq == task_rq(p)))
975 raw_spin_unlock_irqrestore(&rq->lock, *flags);
979 void task_rq_unlock_wait(struct task_struct *p)
981 struct rq *rq = task_rq(p);
983 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
984 raw_spin_unlock_wait(&rq->lock);
987 static void __task_rq_unlock(struct rq *rq)
990 raw_spin_unlock(&rq->lock);
993 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
996 raw_spin_unlock_irqrestore(&rq->lock, *flags);
1000 * this_rq_lock - lock this runqueue and disable interrupts.
1002 static struct rq *this_rq_lock(void)
1003 __acquires(rq->lock)
1007 local_irq_disable();
1009 raw_spin_lock(&rq->lock);
1014 #ifdef CONFIG_SCHED_HRTICK
1016 * Use HR-timers to deliver accurate preemption points.
1018 * Its all a bit involved since we cannot program an hrt while holding the
1019 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1022 * When we get rescheduled we reprogram the hrtick_timer outside of the
1028 * - enabled by features
1029 * - hrtimer is actually high res
1031 static inline int hrtick_enabled(struct rq *rq)
1033 if (!sched_feat(HRTICK))
1035 if (!cpu_active(cpu_of(rq)))
1037 return hrtimer_is_hres_active(&rq->hrtick_timer);
1040 static void hrtick_clear(struct rq *rq)
1042 if (hrtimer_active(&rq->hrtick_timer))
1043 hrtimer_cancel(&rq->hrtick_timer);
1047 * High-resolution timer tick.
1048 * Runs from hardirq context with interrupts disabled.
1050 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1052 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1054 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1056 raw_spin_lock(&rq->lock);
1057 update_rq_clock(rq);
1058 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1059 raw_spin_unlock(&rq->lock);
1061 return HRTIMER_NORESTART;
1066 * called from hardirq (IPI) context
1068 static void __hrtick_start(void *arg)
1070 struct rq *rq = arg;
1072 raw_spin_lock(&rq->lock);
1073 hrtimer_restart(&rq->hrtick_timer);
1074 rq->hrtick_csd_pending = 0;
1075 raw_spin_unlock(&rq->lock);
1079 * Called to set the hrtick timer state.
1081 * called with rq->lock held and irqs disabled
1083 static void hrtick_start(struct rq *rq, u64 delay)
1085 struct hrtimer *timer = &rq->hrtick_timer;
1086 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1088 hrtimer_set_expires(timer, time);
1090 if (rq == this_rq()) {
1091 hrtimer_restart(timer);
1092 } else if (!rq->hrtick_csd_pending) {
1093 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1094 rq->hrtick_csd_pending = 1;
1099 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1101 int cpu = (int)(long)hcpu;
1104 case CPU_UP_CANCELED:
1105 case CPU_UP_CANCELED_FROZEN:
1106 case CPU_DOWN_PREPARE:
1107 case CPU_DOWN_PREPARE_FROZEN:
1109 case CPU_DEAD_FROZEN:
1110 hrtick_clear(cpu_rq(cpu));
1117 static __init void init_hrtick(void)
1119 hotcpu_notifier(hotplug_hrtick, 0);
1123 * Called to set the hrtick timer state.
1125 * called with rq->lock held and irqs disabled
1127 static void hrtick_start(struct rq *rq, u64 delay)
1129 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1130 HRTIMER_MODE_REL_PINNED, 0);
1133 static inline void init_hrtick(void)
1136 #endif /* CONFIG_SMP */
1138 static void init_rq_hrtick(struct rq *rq)
1141 rq->hrtick_csd_pending = 0;
1143 rq->hrtick_csd.flags = 0;
1144 rq->hrtick_csd.func = __hrtick_start;
1145 rq->hrtick_csd.info = rq;
1148 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1149 rq->hrtick_timer.function = hrtick;
1151 #else /* CONFIG_SCHED_HRTICK */
1152 static inline void hrtick_clear(struct rq *rq)
1156 static inline void init_rq_hrtick(struct rq *rq)
1160 static inline void init_hrtick(void)
1163 #endif /* CONFIG_SCHED_HRTICK */
1166 * resched_task - mark a task 'to be rescheduled now'.
1168 * On UP this means the setting of the need_resched flag, on SMP it
1169 * might also involve a cross-CPU call to trigger the scheduler on
1174 #ifndef tsk_is_polling
1175 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1178 static void resched_task(struct task_struct *p)
1182 assert_raw_spin_locked(&task_rq(p)->lock);
1184 if (test_tsk_need_resched(p))
1187 set_tsk_need_resched(p);
1190 if (cpu == smp_processor_id())
1193 /* NEED_RESCHED must be visible before we test polling */
1195 if (!tsk_is_polling(p))
1196 smp_send_reschedule(cpu);
1199 static void resched_cpu(int cpu)
1201 struct rq *rq = cpu_rq(cpu);
1202 unsigned long flags;
1204 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1206 resched_task(cpu_curr(cpu));
1207 raw_spin_unlock_irqrestore(&rq->lock, flags);
1212 * When add_timer_on() enqueues a timer into the timer wheel of an
1213 * idle CPU then this timer might expire before the next timer event
1214 * which is scheduled to wake up that CPU. In case of a completely
1215 * idle system the next event might even be infinite time into the
1216 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1217 * leaves the inner idle loop so the newly added timer is taken into
1218 * account when the CPU goes back to idle and evaluates the timer
1219 * wheel for the next timer event.
1221 void wake_up_idle_cpu(int cpu)
1223 struct rq *rq = cpu_rq(cpu);
1225 if (cpu == smp_processor_id())
1229 * This is safe, as this function is called with the timer
1230 * wheel base lock of (cpu) held. When the CPU is on the way
1231 * to idle and has not yet set rq->curr to idle then it will
1232 * be serialized on the timer wheel base lock and take the new
1233 * timer into account automatically.
1235 if (rq->curr != rq->idle)
1239 * We can set TIF_RESCHED on the idle task of the other CPU
1240 * lockless. The worst case is that the other CPU runs the
1241 * idle task through an additional NOOP schedule()
1243 set_tsk_need_resched(rq->idle);
1245 /* NEED_RESCHED must be visible before we test polling */
1247 if (!tsk_is_polling(rq->idle))
1248 smp_send_reschedule(cpu);
1250 #endif /* CONFIG_NO_HZ */
1252 static u64 sched_avg_period(void)
1254 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1257 static void sched_avg_update(struct rq *rq)
1259 s64 period = sched_avg_period();
1261 while ((s64)(rq->clock - rq->age_stamp) > period) {
1262 rq->age_stamp += period;
1267 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1269 rq->rt_avg += rt_delta;
1270 sched_avg_update(rq);
1273 #else /* !CONFIG_SMP */
1274 static void resched_task(struct task_struct *p)
1276 assert_raw_spin_locked(&task_rq(p)->lock);
1277 set_tsk_need_resched(p);
1280 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1283 #endif /* CONFIG_SMP */
1285 #if BITS_PER_LONG == 32
1286 # define WMULT_CONST (~0UL)
1288 # define WMULT_CONST (1UL << 32)
1291 #define WMULT_SHIFT 32
1294 * Shift right and round:
1296 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1299 * delta *= weight / lw
1301 static unsigned long
1302 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1303 struct load_weight *lw)
1307 if (!lw->inv_weight) {
1308 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1311 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1315 tmp = (u64)delta_exec * weight;
1317 * Check whether we'd overflow the 64-bit multiplication:
1319 if (unlikely(tmp > WMULT_CONST))
1320 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1323 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1325 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1328 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1334 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1341 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1342 * of tasks with abnormal "nice" values across CPUs the contribution that
1343 * each task makes to its run queue's load is weighted according to its
1344 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1345 * scaled version of the new time slice allocation that they receive on time
1349 #define WEIGHT_IDLEPRIO 3
1350 #define WMULT_IDLEPRIO 1431655765
1353 * Nice levels are multiplicative, with a gentle 10% change for every
1354 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1355 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1356 * that remained on nice 0.
1358 * The "10% effect" is relative and cumulative: from _any_ nice level,
1359 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1360 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1361 * If a task goes up by ~10% and another task goes down by ~10% then
1362 * the relative distance between them is ~25%.)
1364 static const int prio_to_weight[40] = {
1365 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1366 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1367 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1368 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1369 /* 0 */ 1024, 820, 655, 526, 423,
1370 /* 5 */ 335, 272, 215, 172, 137,
1371 /* 10 */ 110, 87, 70, 56, 45,
1372 /* 15 */ 36, 29, 23, 18, 15,
1376 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1378 * In cases where the weight does not change often, we can use the
1379 * precalculated inverse to speed up arithmetics by turning divisions
1380 * into multiplications:
1382 static const u32 prio_to_wmult[40] = {
1383 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1384 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1385 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1386 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1387 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1388 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1389 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1390 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1393 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1396 * runqueue iterator, to support SMP load-balancing between different
1397 * scheduling classes, without having to expose their internal data
1398 * structures to the load-balancing proper:
1400 struct rq_iterator {
1402 struct task_struct *(*start)(void *);
1403 struct task_struct *(*next)(void *);
1407 static unsigned long
1408 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1409 unsigned long max_load_move, struct sched_domain *sd,
1410 enum cpu_idle_type idle, int *all_pinned,
1411 int *this_best_prio, struct rq_iterator *iterator);
1414 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1415 struct sched_domain *sd, enum cpu_idle_type idle,
1416 struct rq_iterator *iterator);
1419 /* Time spent by the tasks of the cpu accounting group executing in ... */
1420 enum cpuacct_stat_index {
1421 CPUACCT_STAT_USER, /* ... user mode */
1422 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1424 CPUACCT_STAT_NSTATS,
1427 #ifdef CONFIG_CGROUP_CPUACCT
1428 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1429 static void cpuacct_update_stats(struct task_struct *tsk,
1430 enum cpuacct_stat_index idx, cputime_t val);
1432 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1433 static inline void cpuacct_update_stats(struct task_struct *tsk,
1434 enum cpuacct_stat_index idx, cputime_t val) {}
1437 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1439 update_load_add(&rq->load, load);
1442 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1444 update_load_sub(&rq->load, load);
1447 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1448 typedef int (*tg_visitor)(struct task_group *, void *);
1451 * Iterate the full tree, calling @down when first entering a node and @up when
1452 * leaving it for the final time.
1454 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1456 struct task_group *parent, *child;
1460 parent = &root_task_group;
1462 ret = (*down)(parent, data);
1465 list_for_each_entry_rcu(child, &parent->children, siblings) {
1472 ret = (*up)(parent, data);
1477 parent = parent->parent;
1486 static int tg_nop(struct task_group *tg, void *data)
1493 /* Used instead of source_load when we know the type == 0 */
1494 static unsigned long weighted_cpuload(const int cpu)
1496 return cpu_rq(cpu)->load.weight;
1500 * Return a low guess at the load of a migration-source cpu weighted
1501 * according to the scheduling class and "nice" value.
1503 * We want to under-estimate the load of migration sources, to
1504 * balance conservatively.
1506 static unsigned long source_load(int cpu, int type)
1508 struct rq *rq = cpu_rq(cpu);
1509 unsigned long total = weighted_cpuload(cpu);
1511 if (type == 0 || !sched_feat(LB_BIAS))
1514 return min(rq->cpu_load[type-1], total);
1518 * Return a high guess at the load of a migration-target cpu weighted
1519 * according to the scheduling class and "nice" value.
1521 static unsigned long target_load(int cpu, int type)
1523 struct rq *rq = cpu_rq(cpu);
1524 unsigned long total = weighted_cpuload(cpu);
1526 if (type == 0 || !sched_feat(LB_BIAS))
1529 return max(rq->cpu_load[type-1], total);
1532 static struct sched_group *group_of(int cpu)
1534 struct sched_domain *sd = rcu_dereference(cpu_rq(cpu)->sd);
1542 static unsigned long power_of(int cpu)
1544 struct sched_group *group = group_of(cpu);
1547 return SCHED_LOAD_SCALE;
1549 return group->cpu_power;
1552 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1554 static unsigned long cpu_avg_load_per_task(int cpu)
1556 struct rq *rq = cpu_rq(cpu);
1557 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1560 rq->avg_load_per_task = rq->load.weight / nr_running;
1562 rq->avg_load_per_task = 0;
1564 return rq->avg_load_per_task;
1567 #ifdef CONFIG_FAIR_GROUP_SCHED
1569 static __read_mostly unsigned long *update_shares_data;
1571 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1574 * Calculate and set the cpu's group shares.
1576 static void update_group_shares_cpu(struct task_group *tg, int cpu,
1577 unsigned long sd_shares,
1578 unsigned long sd_rq_weight,
1579 unsigned long *usd_rq_weight)
1581 unsigned long shares, rq_weight;
1584 rq_weight = usd_rq_weight[cpu];
1587 rq_weight = NICE_0_LOAD;
1591 * \Sum_j shares_j * rq_weight_i
1592 * shares_i = -----------------------------
1593 * \Sum_j rq_weight_j
1595 shares = (sd_shares * rq_weight) / sd_rq_weight;
1596 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1598 if (abs(shares - tg->se[cpu]->load.weight) >
1599 sysctl_sched_shares_thresh) {
1600 struct rq *rq = cpu_rq(cpu);
1601 unsigned long flags;
1603 raw_spin_lock_irqsave(&rq->lock, flags);
1604 tg->cfs_rq[cpu]->rq_weight = boost ? 0 : rq_weight;
1605 tg->cfs_rq[cpu]->shares = boost ? 0 : shares;
1606 __set_se_shares(tg->se[cpu], shares);
1607 raw_spin_unlock_irqrestore(&rq->lock, flags);
1612 * Re-compute the task group their per cpu shares over the given domain.
1613 * This needs to be done in a bottom-up fashion because the rq weight of a
1614 * parent group depends on the shares of its child groups.
1616 static int tg_shares_up(struct task_group *tg, void *data)
1618 unsigned long weight, rq_weight = 0, sum_weight = 0, shares = 0;
1619 unsigned long *usd_rq_weight;
1620 struct sched_domain *sd = data;
1621 unsigned long flags;
1627 local_irq_save(flags);
1628 usd_rq_weight = per_cpu_ptr(update_shares_data, smp_processor_id());
1630 for_each_cpu(i, sched_domain_span(sd)) {
1631 weight = tg->cfs_rq[i]->load.weight;
1632 usd_rq_weight[i] = weight;
1634 rq_weight += weight;
1636 * If there are currently no tasks on the cpu pretend there
1637 * is one of average load so that when a new task gets to
1638 * run here it will not get delayed by group starvation.
1641 weight = NICE_0_LOAD;
1643 sum_weight += weight;
1644 shares += tg->cfs_rq[i]->shares;
1648 rq_weight = sum_weight;
1650 if ((!shares && rq_weight) || shares > tg->shares)
1651 shares = tg->shares;
1653 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1654 shares = tg->shares;
1656 for_each_cpu(i, sched_domain_span(sd))
1657 update_group_shares_cpu(tg, i, shares, rq_weight, usd_rq_weight);
1659 local_irq_restore(flags);
1665 * Compute the cpu's hierarchical load factor for each task group.
1666 * This needs to be done in a top-down fashion because the load of a child
1667 * group is a fraction of its parents load.
1669 static int tg_load_down(struct task_group *tg, void *data)
1672 long cpu = (long)data;
1675 load = cpu_rq(cpu)->load.weight;
1677 load = tg->parent->cfs_rq[cpu]->h_load;
1678 load *= tg->cfs_rq[cpu]->shares;
1679 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1682 tg->cfs_rq[cpu]->h_load = load;
1687 static void update_shares(struct sched_domain *sd)
1692 if (root_task_group_empty())
1695 now = cpu_clock(raw_smp_processor_id());
1696 elapsed = now - sd->last_update;
1698 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1699 sd->last_update = now;
1700 walk_tg_tree(tg_nop, tg_shares_up, sd);
1704 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1706 if (root_task_group_empty())
1709 raw_spin_unlock(&rq->lock);
1711 raw_spin_lock(&rq->lock);
1714 static void update_h_load(long cpu)
1716 if (root_task_group_empty())
1719 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1724 static inline void update_shares(struct sched_domain *sd)
1728 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1734 #ifdef CONFIG_PREEMPT
1736 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1739 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1740 * way at the expense of forcing extra atomic operations in all
1741 * invocations. This assures that the double_lock is acquired using the
1742 * same underlying policy as the spinlock_t on this architecture, which
1743 * reduces latency compared to the unfair variant below. However, it
1744 * also adds more overhead and therefore may reduce throughput.
1746 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1747 __releases(this_rq->lock)
1748 __acquires(busiest->lock)
1749 __acquires(this_rq->lock)
1751 raw_spin_unlock(&this_rq->lock);
1752 double_rq_lock(this_rq, busiest);
1759 * Unfair double_lock_balance: Optimizes throughput at the expense of
1760 * latency by eliminating extra atomic operations when the locks are
1761 * already in proper order on entry. This favors lower cpu-ids and will
1762 * grant the double lock to lower cpus over higher ids under contention,
1763 * regardless of entry order into the function.
1765 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1766 __releases(this_rq->lock)
1767 __acquires(busiest->lock)
1768 __acquires(this_rq->lock)
1772 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1773 if (busiest < this_rq) {
1774 raw_spin_unlock(&this_rq->lock);
1775 raw_spin_lock(&busiest->lock);
1776 raw_spin_lock_nested(&this_rq->lock,
1777 SINGLE_DEPTH_NESTING);
1780 raw_spin_lock_nested(&busiest->lock,
1781 SINGLE_DEPTH_NESTING);
1786 #endif /* CONFIG_PREEMPT */
1789 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1791 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1793 if (unlikely(!irqs_disabled())) {
1794 /* printk() doesn't work good under rq->lock */
1795 raw_spin_unlock(&this_rq->lock);
1799 return _double_lock_balance(this_rq, busiest);
1802 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1803 __releases(busiest->lock)
1805 raw_spin_unlock(&busiest->lock);
1806 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1810 #ifdef CONFIG_FAIR_GROUP_SCHED
1811 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1814 cfs_rq->shares = shares;
1819 static void calc_load_account_active(struct rq *this_rq);
1820 static void update_sysctl(void);
1821 static int get_update_sysctl_factor(void);
1823 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1825 set_task_rq(p, cpu);
1828 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1829 * successfuly executed on another CPU. We must ensure that updates of
1830 * per-task data have been completed by this moment.
1833 task_thread_info(p)->cpu = cpu;
1837 #include "sched_stats.h"
1838 #include "sched_idletask.c"
1839 #include "sched_fair.c"
1840 #include "sched_rt.c"
1841 #ifdef CONFIG_SCHED_DEBUG
1842 # include "sched_debug.c"
1845 #define sched_class_highest (&rt_sched_class)
1846 #define for_each_class(class) \
1847 for (class = sched_class_highest; class; class = class->next)
1849 static void inc_nr_running(struct rq *rq)
1854 static void dec_nr_running(struct rq *rq)
1859 static void set_load_weight(struct task_struct *p)
1861 if (task_has_rt_policy(p)) {
1862 p->se.load.weight = prio_to_weight[0] * 2;
1863 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1868 * SCHED_IDLE tasks get minimal weight:
1870 if (p->policy == SCHED_IDLE) {
1871 p->se.load.weight = WEIGHT_IDLEPRIO;
1872 p->se.load.inv_weight = WMULT_IDLEPRIO;
1876 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1877 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1880 static void update_avg(u64 *avg, u64 sample)
1882 s64 diff = sample - *avg;
1886 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1889 p->se.start_runtime = p->se.sum_exec_runtime;
1891 sched_info_queued(p);
1892 p->sched_class->enqueue_task(rq, p, wakeup);
1896 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1899 if (p->se.last_wakeup) {
1900 update_avg(&p->se.avg_overlap,
1901 p->se.sum_exec_runtime - p->se.last_wakeup);
1902 p->se.last_wakeup = 0;
1904 update_avg(&p->se.avg_wakeup,
1905 sysctl_sched_wakeup_granularity);
1909 sched_info_dequeued(p);
1910 p->sched_class->dequeue_task(rq, p, sleep);
1915 * __normal_prio - return the priority that is based on the static prio
1917 static inline int __normal_prio(struct task_struct *p)
1919 return p->static_prio;
1923 * Calculate the expected normal priority: i.e. priority
1924 * without taking RT-inheritance into account. Might be
1925 * boosted by interactivity modifiers. Changes upon fork,
1926 * setprio syscalls, and whenever the interactivity
1927 * estimator recalculates.
1929 static inline int normal_prio(struct task_struct *p)
1933 if (task_has_rt_policy(p))
1934 prio = MAX_RT_PRIO-1 - p->rt_priority;
1936 prio = __normal_prio(p);
1941 * Calculate the current priority, i.e. the priority
1942 * taken into account by the scheduler. This value might
1943 * be boosted by RT tasks, or might be boosted by
1944 * interactivity modifiers. Will be RT if the task got
1945 * RT-boosted. If not then it returns p->normal_prio.
1947 static int effective_prio(struct task_struct *p)
1949 p->normal_prio = normal_prio(p);
1951 * If we are RT tasks or we were boosted to RT priority,
1952 * keep the priority unchanged. Otherwise, update priority
1953 * to the normal priority:
1955 if (!rt_prio(p->prio))
1956 return p->normal_prio;
1961 * activate_task - move a task to the runqueue.
1963 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1965 if (task_contributes_to_load(p))
1966 rq->nr_uninterruptible--;
1968 enqueue_task(rq, p, wakeup);
1973 * deactivate_task - remove a task from the runqueue.
1975 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1977 if (task_contributes_to_load(p))
1978 rq->nr_uninterruptible++;
1980 dequeue_task(rq, p, sleep);
1985 * task_curr - is this task currently executing on a CPU?
1986 * @p: the task in question.
1988 inline int task_curr(const struct task_struct *p)
1990 return cpu_curr(task_cpu(p)) == p;
1993 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1994 const struct sched_class *prev_class,
1995 int oldprio, int running)
1997 if (prev_class != p->sched_class) {
1998 if (prev_class->switched_from)
1999 prev_class->switched_from(rq, p, running);
2000 p->sched_class->switched_to(rq, p, running);
2002 p->sched_class->prio_changed(rq, p, oldprio, running);
2007 * Is this task likely cache-hot:
2010 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2014 if (p->sched_class != &fair_sched_class)
2018 * Buddy candidates are cache hot:
2020 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2021 (&p->se == cfs_rq_of(&p->se)->next ||
2022 &p->se == cfs_rq_of(&p->se)->last))
2025 if (sysctl_sched_migration_cost == -1)
2027 if (sysctl_sched_migration_cost == 0)
2030 delta = now - p->se.exec_start;
2032 return delta < (s64)sysctl_sched_migration_cost;
2035 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2037 #ifdef CONFIG_SCHED_DEBUG
2039 * We should never call set_task_cpu() on a blocked task,
2040 * ttwu() will sort out the placement.
2042 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2043 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2046 trace_sched_migrate_task(p, new_cpu);
2048 if (task_cpu(p) != new_cpu) {
2049 p->se.nr_migrations++;
2050 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0);
2053 __set_task_cpu(p, new_cpu);
2056 struct migration_req {
2057 struct list_head list;
2059 struct task_struct *task;
2062 struct completion done;
2066 * The task's runqueue lock must be held.
2067 * Returns true if you have to wait for migration thread.
2070 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2072 struct rq *rq = task_rq(p);
2075 * If the task is not on a runqueue (and not running), then
2076 * the next wake-up will properly place the task.
2078 if (!p->se.on_rq && !task_running(rq, p))
2081 init_completion(&req->done);
2083 req->dest_cpu = dest_cpu;
2084 list_add(&req->list, &rq->migration_queue);
2090 * wait_task_context_switch - wait for a thread to complete at least one
2093 * @p must not be current.
2095 void wait_task_context_switch(struct task_struct *p)
2097 unsigned long nvcsw, nivcsw, flags;
2105 * The runqueue is assigned before the actual context
2106 * switch. We need to take the runqueue lock.
2108 * We could check initially without the lock but it is
2109 * very likely that we need to take the lock in every
2112 rq = task_rq_lock(p, &flags);
2113 running = task_running(rq, p);
2114 task_rq_unlock(rq, &flags);
2116 if (likely(!running))
2119 * The switch count is incremented before the actual
2120 * context switch. We thus wait for two switches to be
2121 * sure at least one completed.
2123 if ((p->nvcsw - nvcsw) > 1)
2125 if ((p->nivcsw - nivcsw) > 1)
2133 * wait_task_inactive - wait for a thread to unschedule.
2135 * If @match_state is nonzero, it's the @p->state value just checked and
2136 * not expected to change. If it changes, i.e. @p might have woken up,
2137 * then return zero. When we succeed in waiting for @p to be off its CPU,
2138 * we return a positive number (its total switch count). If a second call
2139 * a short while later returns the same number, the caller can be sure that
2140 * @p has remained unscheduled the whole time.
2142 * The caller must ensure that the task *will* unschedule sometime soon,
2143 * else this function might spin for a *long* time. This function can't
2144 * be called with interrupts off, or it may introduce deadlock with
2145 * smp_call_function() if an IPI is sent by the same process we are
2146 * waiting to become inactive.
2148 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2150 unsigned long flags;
2157 * We do the initial early heuristics without holding
2158 * any task-queue locks at all. We'll only try to get
2159 * the runqueue lock when things look like they will
2165 * If the task is actively running on another CPU
2166 * still, just relax and busy-wait without holding
2169 * NOTE! Since we don't hold any locks, it's not
2170 * even sure that "rq" stays as the right runqueue!
2171 * But we don't care, since "task_running()" will
2172 * return false if the runqueue has changed and p
2173 * is actually now running somewhere else!
2175 while (task_running(rq, p)) {
2176 if (match_state && unlikely(p->state != match_state))
2182 * Ok, time to look more closely! We need the rq
2183 * lock now, to be *sure*. If we're wrong, we'll
2184 * just go back and repeat.
2186 rq = task_rq_lock(p, &flags);
2187 trace_sched_wait_task(rq, p);
2188 running = task_running(rq, p);
2189 on_rq = p->se.on_rq;
2191 if (!match_state || p->state == match_state)
2192 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2193 task_rq_unlock(rq, &flags);
2196 * If it changed from the expected state, bail out now.
2198 if (unlikely(!ncsw))
2202 * Was it really running after all now that we
2203 * checked with the proper locks actually held?
2205 * Oops. Go back and try again..
2207 if (unlikely(running)) {
2213 * It's not enough that it's not actively running,
2214 * it must be off the runqueue _entirely_, and not
2217 * So if it was still runnable (but just not actively
2218 * running right now), it's preempted, and we should
2219 * yield - it could be a while.
2221 if (unlikely(on_rq)) {
2222 schedule_timeout_uninterruptible(1);
2227 * Ahh, all good. It wasn't running, and it wasn't
2228 * runnable, which means that it will never become
2229 * running in the future either. We're all done!
2238 * kick_process - kick a running thread to enter/exit the kernel
2239 * @p: the to-be-kicked thread
2241 * Cause a process which is running on another CPU to enter
2242 * kernel-mode, without any delay. (to get signals handled.)
2244 * NOTE: this function doesnt have to take the runqueue lock,
2245 * because all it wants to ensure is that the remote task enters
2246 * the kernel. If the IPI races and the task has been migrated
2247 * to another CPU then no harm is done and the purpose has been
2250 void kick_process(struct task_struct *p)
2256 if ((cpu != smp_processor_id()) && task_curr(p))
2257 smp_send_reschedule(cpu);
2260 EXPORT_SYMBOL_GPL(kick_process);
2261 #endif /* CONFIG_SMP */
2264 * task_oncpu_function_call - call a function on the cpu on which a task runs
2265 * @p: the task to evaluate
2266 * @func: the function to be called
2267 * @info: the function call argument
2269 * Calls the function @func when the task is currently running. This might
2270 * be on the current CPU, which just calls the function directly
2272 void task_oncpu_function_call(struct task_struct *p,
2273 void (*func) (void *info), void *info)
2280 smp_call_function_single(cpu, func, info, 1);
2285 static int select_fallback_rq(int cpu, struct task_struct *p)
2288 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2290 /* Look for allowed, online CPU in same node. */
2291 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2292 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2295 /* Any allowed, online CPU? */
2296 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2297 if (dest_cpu < nr_cpu_ids)
2300 /* No more Mr. Nice Guy. */
2301 if (dest_cpu >= nr_cpu_ids) {
2303 cpuset_cpus_allowed_locked(p, &p->cpus_allowed);
2305 dest_cpu = cpumask_any_and(cpu_active_mask, &p->cpus_allowed);
2308 * Don't tell them about moving exiting tasks or
2309 * kernel threads (both mm NULL), since they never
2312 if (p->mm && printk_ratelimit()) {
2313 printk(KERN_INFO "process %d (%s) no "
2314 "longer affine to cpu%d\n",
2315 task_pid_nr(p), p->comm, cpu);
2323 * Gets called from 3 sites (exec, fork, wakeup), since it is called without
2324 * holding rq->lock we need to ensure ->cpus_allowed is stable, this is done
2327 * exec: is unstable, retry loop
2328 * fork & wake-up: serialize ->cpus_allowed against TASK_WAKING
2331 int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
2333 int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
2336 * In order not to call set_task_cpu() on a blocking task we need
2337 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2340 * Since this is common to all placement strategies, this lives here.
2342 * [ this allows ->select_task() to simply return task_cpu(p) and
2343 * not worry about this generic constraint ]
2345 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2347 cpu = select_fallback_rq(task_cpu(p), p);
2354 * try_to_wake_up - wake up a thread
2355 * @p: the to-be-woken-up thread
2356 * @state: the mask of task states that can be woken
2357 * @sync: do a synchronous wakeup?
2359 * Put it on the run-queue if it's not already there. The "current"
2360 * thread is always on the run-queue (except when the actual
2361 * re-schedule is in progress), and as such you're allowed to do
2362 * the simpler "current->state = TASK_RUNNING" to mark yourself
2363 * runnable without the overhead of this.
2365 * returns failure only if the task is already active.
2367 static int try_to_wake_up(struct task_struct *p, unsigned int state,
2370 int cpu, orig_cpu, this_cpu, success = 0;
2371 unsigned long flags;
2372 struct rq *rq, *orig_rq;
2374 if (!sched_feat(SYNC_WAKEUPS))
2375 wake_flags &= ~WF_SYNC;
2377 this_cpu = get_cpu();
2380 rq = orig_rq = task_rq_lock(p, &flags);
2381 update_rq_clock(rq);
2382 if (!(p->state & state))
2392 if (unlikely(task_running(rq, p)))
2396 * In order to handle concurrent wakeups and release the rq->lock
2397 * we put the task in TASK_WAKING state.
2399 * First fix up the nr_uninterruptible count:
2401 if (task_contributes_to_load(p))
2402 rq->nr_uninterruptible--;
2403 p->state = TASK_WAKING;
2405 if (p->sched_class->task_waking)
2406 p->sched_class->task_waking(rq, p);
2408 __task_rq_unlock(rq);
2410 cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
2411 if (cpu != orig_cpu)
2412 set_task_cpu(p, cpu);
2414 rq = __task_rq_lock(p);
2415 update_rq_clock(rq);
2417 WARN_ON(p->state != TASK_WAKING);
2420 #ifdef CONFIG_SCHEDSTATS
2421 schedstat_inc(rq, ttwu_count);
2422 if (cpu == this_cpu)
2423 schedstat_inc(rq, ttwu_local);
2425 struct sched_domain *sd;
2426 for_each_domain(this_cpu, sd) {
2427 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2428 schedstat_inc(sd, ttwu_wake_remote);
2433 #endif /* CONFIG_SCHEDSTATS */
2436 #endif /* CONFIG_SMP */
2437 schedstat_inc(p, se.nr_wakeups);
2438 if (wake_flags & WF_SYNC)
2439 schedstat_inc(p, se.nr_wakeups_sync);
2440 if (orig_cpu != cpu)
2441 schedstat_inc(p, se.nr_wakeups_migrate);
2442 if (cpu == this_cpu)
2443 schedstat_inc(p, se.nr_wakeups_local);
2445 schedstat_inc(p, se.nr_wakeups_remote);
2446 activate_task(rq, p, 1);
2450 * Only attribute actual wakeups done by this task.
2452 if (!in_interrupt()) {
2453 struct sched_entity *se = ¤t->se;
2454 u64 sample = se->sum_exec_runtime;
2456 if (se->last_wakeup)
2457 sample -= se->last_wakeup;
2459 sample -= se->start_runtime;
2460 update_avg(&se->avg_wakeup, sample);
2462 se->last_wakeup = se->sum_exec_runtime;
2466 trace_sched_wakeup(rq, p, success);
2467 check_preempt_curr(rq, p, wake_flags);
2469 p->state = TASK_RUNNING;
2471 if (p->sched_class->task_woken)
2472 p->sched_class->task_woken(rq, p);
2474 if (unlikely(rq->idle_stamp)) {
2475 u64 delta = rq->clock - rq->idle_stamp;
2476 u64 max = 2*sysctl_sched_migration_cost;
2481 update_avg(&rq->avg_idle, delta);
2486 task_rq_unlock(rq, &flags);
2493 * wake_up_process - Wake up a specific process
2494 * @p: The process to be woken up.
2496 * Attempt to wake up the nominated process and move it to the set of runnable
2497 * processes. Returns 1 if the process was woken up, 0 if it was already
2500 * It may be assumed that this function implies a write memory barrier before
2501 * changing the task state if and only if any tasks are woken up.
2503 int wake_up_process(struct task_struct *p)
2505 return try_to_wake_up(p, TASK_ALL, 0);
2507 EXPORT_SYMBOL(wake_up_process);
2509 int wake_up_state(struct task_struct *p, unsigned int state)
2511 return try_to_wake_up(p, state, 0);
2515 * Perform scheduler related setup for a newly forked process p.
2516 * p is forked by current.
2518 * __sched_fork() is basic setup used by init_idle() too:
2520 static void __sched_fork(struct task_struct *p)
2522 p->se.exec_start = 0;
2523 p->se.sum_exec_runtime = 0;
2524 p->se.prev_sum_exec_runtime = 0;
2525 p->se.nr_migrations = 0;
2526 p->se.last_wakeup = 0;
2527 p->se.avg_overlap = 0;
2528 p->se.start_runtime = 0;
2529 p->se.avg_wakeup = sysctl_sched_wakeup_granularity;
2531 #ifdef CONFIG_SCHEDSTATS
2532 p->se.wait_start = 0;
2534 p->se.wait_count = 0;
2537 p->se.sleep_start = 0;
2538 p->se.sleep_max = 0;
2539 p->se.sum_sleep_runtime = 0;
2541 p->se.block_start = 0;
2542 p->se.block_max = 0;
2544 p->se.slice_max = 0;
2546 p->se.nr_migrations_cold = 0;
2547 p->se.nr_failed_migrations_affine = 0;
2548 p->se.nr_failed_migrations_running = 0;
2549 p->se.nr_failed_migrations_hot = 0;
2550 p->se.nr_forced_migrations = 0;
2552 p->se.nr_wakeups = 0;
2553 p->se.nr_wakeups_sync = 0;
2554 p->se.nr_wakeups_migrate = 0;
2555 p->se.nr_wakeups_local = 0;
2556 p->se.nr_wakeups_remote = 0;
2557 p->se.nr_wakeups_affine = 0;
2558 p->se.nr_wakeups_affine_attempts = 0;
2559 p->se.nr_wakeups_passive = 0;
2560 p->se.nr_wakeups_idle = 0;
2564 INIT_LIST_HEAD(&p->rt.run_list);
2566 INIT_LIST_HEAD(&p->se.group_node);
2568 #ifdef CONFIG_PREEMPT_NOTIFIERS
2569 INIT_HLIST_HEAD(&p->preempt_notifiers);
2574 * fork()/clone()-time setup:
2576 void sched_fork(struct task_struct *p, int clone_flags)
2578 int cpu = get_cpu();
2582 * We mark the process as waking here. This guarantees that
2583 * nobody will actually run it, and a signal or other external
2584 * event cannot wake it up and insert it on the runqueue either.
2586 p->state = TASK_WAKING;
2589 * Revert to default priority/policy on fork if requested.
2591 if (unlikely(p->sched_reset_on_fork)) {
2592 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2593 p->policy = SCHED_NORMAL;
2594 p->normal_prio = p->static_prio;
2597 if (PRIO_TO_NICE(p->static_prio) < 0) {
2598 p->static_prio = NICE_TO_PRIO(0);
2599 p->normal_prio = p->static_prio;
2604 * We don't need the reset flag anymore after the fork. It has
2605 * fulfilled its duty:
2607 p->sched_reset_on_fork = 0;
2611 * Make sure we do not leak PI boosting priority to the child.
2613 p->prio = current->normal_prio;
2615 if (!rt_prio(p->prio))
2616 p->sched_class = &fair_sched_class;
2618 if (p->sched_class->task_fork)
2619 p->sched_class->task_fork(p);
2621 set_task_cpu(p, cpu);
2623 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2624 if (likely(sched_info_on()))
2625 memset(&p->sched_info, 0, sizeof(p->sched_info));
2627 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2630 #ifdef CONFIG_PREEMPT
2631 /* Want to start with kernel preemption disabled. */
2632 task_thread_info(p)->preempt_count = 1;
2634 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2640 * wake_up_new_task - wake up a newly created task for the first time.
2642 * This function will do some initial scheduler statistics housekeeping
2643 * that must be done for every newly created context, then puts the task
2644 * on the runqueue and wakes it.
2646 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2648 unsigned long flags;
2650 int cpu = get_cpu();
2654 * Fork balancing, do it here and not earlier because:
2655 * - cpus_allowed can change in the fork path
2656 * - any previously selected cpu might disappear through hotplug
2658 * We still have TASK_WAKING but PF_STARTING is gone now, meaning
2659 * ->cpus_allowed is stable, we have preemption disabled, meaning
2660 * cpu_online_mask is stable.
2662 cpu = select_task_rq(p, SD_BALANCE_FORK, 0);
2663 set_task_cpu(p, cpu);
2666 rq = task_rq_lock(p, &flags);
2667 BUG_ON(p->state != TASK_WAKING);
2668 p->state = TASK_RUNNING;
2669 update_rq_clock(rq);
2670 activate_task(rq, p, 0);
2671 trace_sched_wakeup_new(rq, p, 1);
2672 check_preempt_curr(rq, p, WF_FORK);
2674 if (p->sched_class->task_woken)
2675 p->sched_class->task_woken(rq, p);
2677 task_rq_unlock(rq, &flags);
2681 #ifdef CONFIG_PREEMPT_NOTIFIERS
2684 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2685 * @notifier: notifier struct to register
2687 void preempt_notifier_register(struct preempt_notifier *notifier)
2689 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2691 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2694 * preempt_notifier_unregister - no longer interested in preemption notifications
2695 * @notifier: notifier struct to unregister
2697 * This is safe to call from within a preemption notifier.
2699 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2701 hlist_del(¬ifier->link);
2703 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2705 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2707 struct preempt_notifier *notifier;
2708 struct hlist_node *node;
2710 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2711 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2715 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2716 struct task_struct *next)
2718 struct preempt_notifier *notifier;
2719 struct hlist_node *node;
2721 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2722 notifier->ops->sched_out(notifier, next);
2725 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2727 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2732 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2733 struct task_struct *next)
2737 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2740 * prepare_task_switch - prepare to switch tasks
2741 * @rq: the runqueue preparing to switch
2742 * @prev: the current task that is being switched out
2743 * @next: the task we are going to switch to.
2745 * This is called with the rq lock held and interrupts off. It must
2746 * be paired with a subsequent finish_task_switch after the context
2749 * prepare_task_switch sets up locking and calls architecture specific
2753 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2754 struct task_struct *next)
2756 fire_sched_out_preempt_notifiers(prev, next);
2757 prepare_lock_switch(rq, next);
2758 prepare_arch_switch(next);
2762 * finish_task_switch - clean up after a task-switch
2763 * @rq: runqueue associated with task-switch
2764 * @prev: the thread we just switched away from.
2766 * finish_task_switch must be called after the context switch, paired
2767 * with a prepare_task_switch call before the context switch.
2768 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2769 * and do any other architecture-specific cleanup actions.
2771 * Note that we may have delayed dropping an mm in context_switch(). If
2772 * so, we finish that here outside of the runqueue lock. (Doing it
2773 * with the lock held can cause deadlocks; see schedule() for
2776 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2777 __releases(rq->lock)
2779 struct mm_struct *mm = rq->prev_mm;
2785 * A task struct has one reference for the use as "current".
2786 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2787 * schedule one last time. The schedule call will never return, and
2788 * the scheduled task must drop that reference.
2789 * The test for TASK_DEAD must occur while the runqueue locks are
2790 * still held, otherwise prev could be scheduled on another cpu, die
2791 * there before we look at prev->state, and then the reference would
2793 * Manfred Spraul <manfred@colorfullife.com>
2795 prev_state = prev->state;
2796 finish_arch_switch(prev);
2797 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2798 local_irq_disable();
2799 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2800 perf_event_task_sched_in(current);
2801 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2803 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2804 finish_lock_switch(rq, prev);
2806 fire_sched_in_preempt_notifiers(current);
2809 if (unlikely(prev_state == TASK_DEAD)) {
2811 * Remove function-return probe instances associated with this
2812 * task and put them back on the free list.
2814 kprobe_flush_task(prev);
2815 put_task_struct(prev);
2821 /* assumes rq->lock is held */
2822 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2824 if (prev->sched_class->pre_schedule)
2825 prev->sched_class->pre_schedule(rq, prev);
2828 /* rq->lock is NOT held, but preemption is disabled */
2829 static inline void post_schedule(struct rq *rq)
2831 if (rq->post_schedule) {
2832 unsigned long flags;
2834 raw_spin_lock_irqsave(&rq->lock, flags);
2835 if (rq->curr->sched_class->post_schedule)
2836 rq->curr->sched_class->post_schedule(rq);
2837 raw_spin_unlock_irqrestore(&rq->lock, flags);
2839 rq->post_schedule = 0;
2845 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2849 static inline void post_schedule(struct rq *rq)
2856 * schedule_tail - first thing a freshly forked thread must call.
2857 * @prev: the thread we just switched away from.
2859 asmlinkage void schedule_tail(struct task_struct *prev)
2860 __releases(rq->lock)
2862 struct rq *rq = this_rq();
2864 finish_task_switch(rq, prev);
2867 * FIXME: do we need to worry about rq being invalidated by the
2872 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2873 /* In this case, finish_task_switch does not reenable preemption */
2876 if (current->set_child_tid)
2877 put_user(task_pid_vnr(current), current->set_child_tid);
2881 * context_switch - switch to the new MM and the new
2882 * thread's register state.
2885 context_switch(struct rq *rq, struct task_struct *prev,
2886 struct task_struct *next)
2888 struct mm_struct *mm, *oldmm;
2890 prepare_task_switch(rq, prev, next);
2891 trace_sched_switch(rq, prev, next);
2893 oldmm = prev->active_mm;
2895 * For paravirt, this is coupled with an exit in switch_to to
2896 * combine the page table reload and the switch backend into
2899 arch_start_context_switch(prev);
2902 next->active_mm = oldmm;
2903 atomic_inc(&oldmm->mm_count);
2904 enter_lazy_tlb(oldmm, next);
2906 switch_mm(oldmm, mm, next);
2908 if (likely(!prev->mm)) {
2909 prev->active_mm = NULL;
2910 rq->prev_mm = oldmm;
2913 * Since the runqueue lock will be released by the next
2914 * task (which is an invalid locking op but in the case
2915 * of the scheduler it's an obvious special-case), so we
2916 * do an early lockdep release here:
2918 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2919 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2922 /* Here we just switch the register state and the stack. */
2923 switch_to(prev, next, prev);
2927 * this_rq must be evaluated again because prev may have moved
2928 * CPUs since it called schedule(), thus the 'rq' on its stack
2929 * frame will be invalid.
2931 finish_task_switch(this_rq(), prev);
2935 * nr_running, nr_uninterruptible and nr_context_switches:
2937 * externally visible scheduler statistics: current number of runnable
2938 * threads, current number of uninterruptible-sleeping threads, total
2939 * number of context switches performed since bootup.
2941 unsigned long nr_running(void)
2943 unsigned long i, sum = 0;
2945 for_each_online_cpu(i)
2946 sum += cpu_rq(i)->nr_running;
2951 unsigned long nr_uninterruptible(void)
2953 unsigned long i, sum = 0;
2955 for_each_possible_cpu(i)
2956 sum += cpu_rq(i)->nr_uninterruptible;
2959 * Since we read the counters lockless, it might be slightly
2960 * inaccurate. Do not allow it to go below zero though:
2962 if (unlikely((long)sum < 0))
2968 unsigned long long nr_context_switches(void)
2971 unsigned long long sum = 0;
2973 for_each_possible_cpu(i)
2974 sum += cpu_rq(i)->nr_switches;
2979 unsigned long nr_iowait(void)
2981 unsigned long i, sum = 0;
2983 for_each_possible_cpu(i)
2984 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2989 unsigned long nr_iowait_cpu(void)
2991 struct rq *this = this_rq();
2992 return atomic_read(&this->nr_iowait);
2995 unsigned long this_cpu_load(void)
2997 struct rq *this = this_rq();
2998 return this->cpu_load[0];
3002 /* Variables and functions for calc_load */
3003 static atomic_long_t calc_load_tasks;
3004 static unsigned long calc_load_update;
3005 unsigned long avenrun[3];
3006 EXPORT_SYMBOL(avenrun);
3009 * get_avenrun - get the load average array
3010 * @loads: pointer to dest load array
3011 * @offset: offset to add
3012 * @shift: shift count to shift the result left
3014 * These values are estimates at best, so no need for locking.
3016 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3018 loads[0] = (avenrun[0] + offset) << shift;
3019 loads[1] = (avenrun[1] + offset) << shift;
3020 loads[2] = (avenrun[2] + offset) << shift;
3023 static unsigned long
3024 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3027 load += active * (FIXED_1 - exp);
3028 return load >> FSHIFT;
3032 * calc_load - update the avenrun load estimates 10 ticks after the
3033 * CPUs have updated calc_load_tasks.
3035 void calc_global_load(void)
3037 unsigned long upd = calc_load_update + 10;
3040 if (time_before(jiffies, upd))
3043 active = atomic_long_read(&calc_load_tasks);
3044 active = active > 0 ? active * FIXED_1 : 0;
3046 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3047 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3048 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3050 calc_load_update += LOAD_FREQ;
3054 * Either called from update_cpu_load() or from a cpu going idle
3056 static void calc_load_account_active(struct rq *this_rq)
3058 long nr_active, delta;
3060 nr_active = this_rq->nr_running;
3061 nr_active += (long) this_rq->nr_uninterruptible;
3063 if (nr_active != this_rq->calc_load_active) {
3064 delta = nr_active - this_rq->calc_load_active;
3065 this_rq->calc_load_active = nr_active;
3066 atomic_long_add(delta, &calc_load_tasks);
3071 * Update rq->cpu_load[] statistics. This function is usually called every
3072 * scheduler tick (TICK_NSEC).
3074 static void update_cpu_load(struct rq *this_rq)
3076 unsigned long this_load = this_rq->load.weight;
3079 this_rq->nr_load_updates++;
3081 /* Update our load: */
3082 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3083 unsigned long old_load, new_load;
3085 /* scale is effectively 1 << i now, and >> i divides by scale */
3087 old_load = this_rq->cpu_load[i];
3088 new_load = this_load;
3090 * Round up the averaging division if load is increasing. This
3091 * prevents us from getting stuck on 9 if the load is 10, for
3094 if (new_load > old_load)
3095 new_load += scale-1;
3096 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3099 if (time_after_eq(jiffies, this_rq->calc_load_update)) {
3100 this_rq->calc_load_update += LOAD_FREQ;
3101 calc_load_account_active(this_rq);
3108 * double_rq_lock - safely lock two runqueues
3110 * Note this does not disable interrupts like task_rq_lock,
3111 * you need to do so manually before calling.
3113 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3114 __acquires(rq1->lock)
3115 __acquires(rq2->lock)
3117 BUG_ON(!irqs_disabled());
3119 raw_spin_lock(&rq1->lock);
3120 __acquire(rq2->lock); /* Fake it out ;) */
3123 raw_spin_lock(&rq1->lock);
3124 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
3126 raw_spin_lock(&rq2->lock);
3127 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
3130 update_rq_clock(rq1);
3131 update_rq_clock(rq2);
3135 * double_rq_unlock - safely unlock two runqueues
3137 * Note this does not restore interrupts like task_rq_unlock,
3138 * you need to do so manually after calling.
3140 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3141 __releases(rq1->lock)
3142 __releases(rq2->lock)
3144 raw_spin_unlock(&rq1->lock);
3146 raw_spin_unlock(&rq2->lock);
3148 __release(rq2->lock);
3152 * sched_exec - execve() is a valuable balancing opportunity, because at
3153 * this point the task has the smallest effective memory and cache footprint.
3155 void sched_exec(void)
3157 struct task_struct *p = current;
3158 struct migration_req req;
3159 int dest_cpu, this_cpu;
3160 unsigned long flags;
3164 this_cpu = get_cpu();
3165 dest_cpu = select_task_rq(p, SD_BALANCE_EXEC, 0);
3166 if (dest_cpu == this_cpu) {
3171 rq = task_rq_lock(p, &flags);
3175 * select_task_rq() can race against ->cpus_allowed
3177 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed)
3178 || unlikely(!cpu_active(dest_cpu))) {
3179 task_rq_unlock(rq, &flags);
3183 /* force the process onto the specified CPU */
3184 if (migrate_task(p, dest_cpu, &req)) {
3185 /* Need to wait for migration thread (might exit: take ref). */
3186 struct task_struct *mt = rq->migration_thread;
3188 get_task_struct(mt);
3189 task_rq_unlock(rq, &flags);
3190 wake_up_process(mt);
3191 put_task_struct(mt);
3192 wait_for_completion(&req.done);
3196 task_rq_unlock(rq, &flags);
3200 * pull_task - move a task from a remote runqueue to the local runqueue.
3201 * Both runqueues must be locked.
3203 static void pull_task(struct rq *src_rq, struct task_struct *p,
3204 struct rq *this_rq, int this_cpu)
3206 deactivate_task(src_rq, p, 0);
3207 set_task_cpu(p, this_cpu);
3208 activate_task(this_rq, p, 0);
3209 check_preempt_curr(this_rq, p, 0);
3213 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3216 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3217 struct sched_domain *sd, enum cpu_idle_type idle,
3220 int tsk_cache_hot = 0;
3222 * We do not migrate tasks that are:
3223 * 1) running (obviously), or
3224 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3225 * 3) are cache-hot on their current CPU.
3227 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
3228 schedstat_inc(p, se.nr_failed_migrations_affine);
3233 if (task_running(rq, p)) {
3234 schedstat_inc(p, se.nr_failed_migrations_running);
3239 * Aggressive migration if:
3240 * 1) task is cache cold, or
3241 * 2) too many balance attempts have failed.
3244 tsk_cache_hot = task_hot(p, rq->clock, sd);
3245 if (!tsk_cache_hot ||
3246 sd->nr_balance_failed > sd->cache_nice_tries) {
3247 #ifdef CONFIG_SCHEDSTATS
3248 if (tsk_cache_hot) {
3249 schedstat_inc(sd, lb_hot_gained[idle]);
3250 schedstat_inc(p, se.nr_forced_migrations);
3256 if (tsk_cache_hot) {
3257 schedstat_inc(p, se.nr_failed_migrations_hot);
3263 static unsigned long
3264 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3265 unsigned long max_load_move, struct sched_domain *sd,
3266 enum cpu_idle_type idle, int *all_pinned,
3267 int *this_best_prio, struct rq_iterator *iterator)
3269 int loops = 0, pulled = 0, pinned = 0;
3270 struct task_struct *p;
3271 long rem_load_move = max_load_move;
3273 if (max_load_move == 0)
3279 * Start the load-balancing iterator:
3281 p = iterator->start(iterator->arg);
3283 if (!p || loops++ > sysctl_sched_nr_migrate)
3286 if ((p->se.load.weight >> 1) > rem_load_move ||
3287 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3288 p = iterator->next(iterator->arg);
3292 pull_task(busiest, p, this_rq, this_cpu);
3294 rem_load_move -= p->se.load.weight;
3296 #ifdef CONFIG_PREEMPT
3298 * NEWIDLE balancing is a source of latency, so preemptible kernels
3299 * will stop after the first task is pulled to minimize the critical
3302 if (idle == CPU_NEWLY_IDLE)
3307 * We only want to steal up to the prescribed amount of weighted load.
3309 if (rem_load_move > 0) {
3310 if (p->prio < *this_best_prio)
3311 *this_best_prio = p->prio;
3312 p = iterator->next(iterator->arg);
3317 * Right now, this is one of only two places pull_task() is called,
3318 * so we can safely collect pull_task() stats here rather than
3319 * inside pull_task().
3321 schedstat_add(sd, lb_gained[idle], pulled);
3324 *all_pinned = pinned;
3326 return max_load_move - rem_load_move;
3330 * move_tasks tries to move up to max_load_move weighted load from busiest to
3331 * this_rq, as part of a balancing operation within domain "sd".
3332 * Returns 1 if successful and 0 otherwise.
3334 * Called with both runqueues locked.
3336 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3337 unsigned long max_load_move,
3338 struct sched_domain *sd, enum cpu_idle_type idle,
3341 const struct sched_class *class = sched_class_highest;
3342 unsigned long total_load_moved = 0;
3343 int this_best_prio = this_rq->curr->prio;
3347 class->load_balance(this_rq, this_cpu, busiest,
3348 max_load_move - total_load_moved,
3349 sd, idle, all_pinned, &this_best_prio);
3350 class = class->next;
3352 #ifdef CONFIG_PREEMPT
3354 * NEWIDLE balancing is a source of latency, so preemptible
3355 * kernels will stop after the first task is pulled to minimize
3356 * the critical section.
3358 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3361 } while (class && max_load_move > total_load_moved);
3363 return total_load_moved > 0;
3367 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3368 struct sched_domain *sd, enum cpu_idle_type idle,
3369 struct rq_iterator *iterator)
3371 struct task_struct *p = iterator->start(iterator->arg);
3375 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3376 pull_task(busiest, p, this_rq, this_cpu);
3378 * Right now, this is only the second place pull_task()
3379 * is called, so we can safely collect pull_task()
3380 * stats here rather than inside pull_task().
3382 schedstat_inc(sd, lb_gained[idle]);
3386 p = iterator->next(iterator->arg);
3393 * move_one_task tries to move exactly one task from busiest to this_rq, as
3394 * part of active balancing operations within "domain".
3395 * Returns 1 if successful and 0 otherwise.
3397 * Called with both runqueues locked.
3399 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3400 struct sched_domain *sd, enum cpu_idle_type idle)
3402 const struct sched_class *class;
3404 for_each_class(class) {
3405 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3411 /********** Helpers for find_busiest_group ************************/
3413 * sd_lb_stats - Structure to store the statistics of a sched_domain
3414 * during load balancing.
3416 struct sd_lb_stats {
3417 struct sched_group *busiest; /* Busiest group in this sd */
3418 struct sched_group *this; /* Local group in this sd */
3419 unsigned long total_load; /* Total load of all groups in sd */
3420 unsigned long total_pwr; /* Total power of all groups in sd */
3421 unsigned long avg_load; /* Average load across all groups in sd */
3423 /** Statistics of this group */
3424 unsigned long this_load;
3425 unsigned long this_load_per_task;
3426 unsigned long this_nr_running;
3428 /* Statistics of the busiest group */
3429 unsigned long max_load;
3430 unsigned long busiest_load_per_task;
3431 unsigned long busiest_nr_running;
3433 int group_imb; /* Is there imbalance in this sd */
3434 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3435 int power_savings_balance; /* Is powersave balance needed for this sd */
3436 struct sched_group *group_min; /* Least loaded group in sd */
3437 struct sched_group *group_leader; /* Group which relieves group_min */
3438 unsigned long min_load_per_task; /* load_per_task in group_min */
3439 unsigned long leader_nr_running; /* Nr running of group_leader */
3440 unsigned long min_nr_running; /* Nr running of group_min */
3445 * sg_lb_stats - stats of a sched_group required for load_balancing
3447 struct sg_lb_stats {
3448 unsigned long avg_load; /*Avg load across the CPUs of the group */
3449 unsigned long group_load; /* Total load over the CPUs of the group */
3450 unsigned long sum_nr_running; /* Nr tasks running in the group */
3451 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3452 unsigned long group_capacity;
3453 int group_imb; /* Is there an imbalance in the group ? */
3457 * group_first_cpu - Returns the first cpu in the cpumask of a sched_group.
3458 * @group: The group whose first cpu is to be returned.
3460 static inline unsigned int group_first_cpu(struct sched_group *group)
3462 return cpumask_first(sched_group_cpus(group));
3466 * get_sd_load_idx - Obtain the load index for a given sched domain.
3467 * @sd: The sched_domain whose load_idx is to be obtained.
3468 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3470 static inline int get_sd_load_idx(struct sched_domain *sd,
3471 enum cpu_idle_type idle)
3477 load_idx = sd->busy_idx;
3480 case CPU_NEWLY_IDLE:
3481 load_idx = sd->newidle_idx;
3484 load_idx = sd->idle_idx;
3492 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3494 * init_sd_power_savings_stats - Initialize power savings statistics for
3495 * the given sched_domain, during load balancing.
3497 * @sd: Sched domain whose power-savings statistics are to be initialized.
3498 * @sds: Variable containing the statistics for sd.
3499 * @idle: Idle status of the CPU at which we're performing load-balancing.
3501 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3502 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3505 * Busy processors will not participate in power savings
3508 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3509 sds->power_savings_balance = 0;
3511 sds->power_savings_balance = 1;
3512 sds->min_nr_running = ULONG_MAX;
3513 sds->leader_nr_running = 0;
3518 * update_sd_power_savings_stats - Update the power saving stats for a
3519 * sched_domain while performing load balancing.
3521 * @group: sched_group belonging to the sched_domain under consideration.
3522 * @sds: Variable containing the statistics of the sched_domain
3523 * @local_group: Does group contain the CPU for which we're performing
3525 * @sgs: Variable containing the statistics of the group.
3527 static inline void update_sd_power_savings_stats(struct sched_group *group,
3528 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3531 if (!sds->power_savings_balance)
3535 * If the local group is idle or completely loaded
3536 * no need to do power savings balance at this domain
3538 if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
3539 !sds->this_nr_running))
3540 sds->power_savings_balance = 0;
3543 * If a group is already running at full capacity or idle,
3544 * don't include that group in power savings calculations
3546 if (!sds->power_savings_balance ||
3547 sgs->sum_nr_running >= sgs->group_capacity ||
3548 !sgs->sum_nr_running)
3552 * Calculate the group which has the least non-idle load.
3553 * This is the group from where we need to pick up the load
3556 if ((sgs->sum_nr_running < sds->min_nr_running) ||
3557 (sgs->sum_nr_running == sds->min_nr_running &&
3558 group_first_cpu(group) > group_first_cpu(sds->group_min))) {
3559 sds->group_min = group;
3560 sds->min_nr_running = sgs->sum_nr_running;
3561 sds->min_load_per_task = sgs->sum_weighted_load /
3562 sgs->sum_nr_running;
3566 * Calculate the group which is almost near its
3567 * capacity but still has some space to pick up some load
3568 * from other group and save more power
3570 if (sgs->sum_nr_running + 1 > sgs->group_capacity)
3573 if (sgs->sum_nr_running > sds->leader_nr_running ||
3574 (sgs->sum_nr_running == sds->leader_nr_running &&
3575 group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
3576 sds->group_leader = group;
3577 sds->leader_nr_running = sgs->sum_nr_running;
3582 * check_power_save_busiest_group - see if there is potential for some power-savings balance
3583 * @sds: Variable containing the statistics of the sched_domain
3584 * under consideration.
3585 * @this_cpu: Cpu at which we're currently performing load-balancing.
3586 * @imbalance: Variable to store the imbalance.
3589 * Check if we have potential to perform some power-savings balance.
3590 * If yes, set the busiest group to be the least loaded group in the
3591 * sched_domain, so that it's CPUs can be put to idle.
3593 * Returns 1 if there is potential to perform power-savings balance.
3596 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3597 int this_cpu, unsigned long *imbalance)
3599 if (!sds->power_savings_balance)
3602 if (sds->this != sds->group_leader ||
3603 sds->group_leader == sds->group_min)
3606 *imbalance = sds->min_load_per_task;
3607 sds->busiest = sds->group_min;
3612 #else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3613 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3614 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3619 static inline void update_sd_power_savings_stats(struct sched_group *group,
3620 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3625 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3626 int this_cpu, unsigned long *imbalance)
3630 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3633 unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
3635 return SCHED_LOAD_SCALE;
3638 unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
3640 return default_scale_freq_power(sd, cpu);
3643 unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
3645 unsigned long weight = cpumask_weight(sched_domain_span(sd));
3646 unsigned long smt_gain = sd->smt_gain;
3653 unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
3655 return default_scale_smt_power(sd, cpu);
3658 unsigned long scale_rt_power(int cpu)
3660 struct rq *rq = cpu_rq(cpu);
3661 u64 total, available;
3663 sched_avg_update(rq);
3665 total = sched_avg_period() + (rq->clock - rq->age_stamp);
3666 available = total - rq->rt_avg;
3668 if (unlikely((s64)total < SCHED_LOAD_SCALE))
3669 total = SCHED_LOAD_SCALE;
3671 total >>= SCHED_LOAD_SHIFT;
3673 return div_u64(available, total);
3676 static void update_cpu_power(struct sched_domain *sd, int cpu)
3678 unsigned long weight = cpumask_weight(sched_domain_span(sd));
3679 unsigned long power = SCHED_LOAD_SCALE;
3680 struct sched_group *sdg = sd->groups;
3682 if (sched_feat(ARCH_POWER))
3683 power *= arch_scale_freq_power(sd, cpu);
3685 power *= default_scale_freq_power(sd, cpu);
3687 power >>= SCHED_LOAD_SHIFT;
3689 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
3690 if (sched_feat(ARCH_POWER))
3691 power *= arch_scale_smt_power(sd, cpu);
3693 power *= default_scale_smt_power(sd, cpu);
3695 power >>= SCHED_LOAD_SHIFT;
3698 power *= scale_rt_power(cpu);
3699 power >>= SCHED_LOAD_SHIFT;
3704 sdg->cpu_power = power;
3707 static void update_group_power(struct sched_domain *sd, int cpu)
3709 struct sched_domain *child = sd->child;
3710 struct sched_group *group, *sdg = sd->groups;
3711 unsigned long power;
3714 update_cpu_power(sd, cpu);
3720 group = child->groups;
3722 power += group->cpu_power;
3723 group = group->next;
3724 } while (group != child->groups);
3726 sdg->cpu_power = power;
3730 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
3731 * @sd: The sched_domain whose statistics are to be updated.
3732 * @group: sched_group whose statistics are to be updated.
3733 * @this_cpu: Cpu for which load balance is currently performed.
3734 * @idle: Idle status of this_cpu
3735 * @load_idx: Load index of sched_domain of this_cpu for load calc.
3736 * @sd_idle: Idle status of the sched_domain containing group.
3737 * @local_group: Does group contain this_cpu.
3738 * @cpus: Set of cpus considered for load balancing.
3739 * @balance: Should we balance.
3740 * @sgs: variable to hold the statistics for this group.
3742 static inline void update_sg_lb_stats(struct sched_domain *sd,
3743 struct sched_group *group, int this_cpu,
3744 enum cpu_idle_type idle, int load_idx, int *sd_idle,
3745 int local_group, const struct cpumask *cpus,
3746 int *balance, struct sg_lb_stats *sgs)
3748 unsigned long load, max_cpu_load, min_cpu_load;
3750 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3751 unsigned long sum_avg_load_per_task;
3752 unsigned long avg_load_per_task;
3755 balance_cpu = group_first_cpu(group);
3756 if (balance_cpu == this_cpu)
3757 update_group_power(sd, this_cpu);
3760 /* Tally up the load of all CPUs in the group */
3761 sum_avg_load_per_task = avg_load_per_task = 0;
3763 min_cpu_load = ~0UL;
3765 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
3766 struct rq *rq = cpu_rq(i);
3768 if (*sd_idle && rq->nr_running)
3771 /* Bias balancing toward cpus of our domain */
3773 if (idle_cpu(i) && !first_idle_cpu) {
3778 load = target_load(i, load_idx);
3780 load = source_load(i, load_idx);
3781 if (load > max_cpu_load)
3782 max_cpu_load = load;
3783 if (min_cpu_load > load)
3784 min_cpu_load = load;
3787 sgs->group_load += load;
3788 sgs->sum_nr_running += rq->nr_running;
3789 sgs->sum_weighted_load += weighted_cpuload(i);
3791 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3795 * First idle cpu or the first cpu(busiest) in this sched group
3796 * is eligible for doing load balancing at this and above
3797 * domains. In the newly idle case, we will allow all the cpu's
3798 * to do the newly idle load balance.
3800 if (idle != CPU_NEWLY_IDLE && local_group &&
3801 balance_cpu != this_cpu && balance) {
3806 /* Adjust by relative CPU power of the group */
3807 sgs->avg_load = (sgs->group_load * SCHED_LOAD_SCALE) / group->cpu_power;
3811 * Consider the group unbalanced when the imbalance is larger
3812 * than the average weight of two tasks.
3814 * APZ: with cgroup the avg task weight can vary wildly and
3815 * might not be a suitable number - should we keep a
3816 * normalized nr_running number somewhere that negates
3819 avg_load_per_task = (sum_avg_load_per_task * SCHED_LOAD_SCALE) /
3822 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3825 sgs->group_capacity =
3826 DIV_ROUND_CLOSEST(group->cpu_power, SCHED_LOAD_SCALE);
3830 * update_sd_lb_stats - Update sched_group's statistics for load balancing.
3831 * @sd: sched_domain whose statistics are to be updated.
3832 * @this_cpu: Cpu for which load balance is currently performed.
3833 * @idle: Idle status of this_cpu
3834 * @sd_idle: Idle status of the sched_domain containing group.
3835 * @cpus: Set of cpus considered for load balancing.
3836 * @balance: Should we balance.
3837 * @sds: variable to hold the statistics for this sched_domain.
3839 static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
3840 enum cpu_idle_type idle, int *sd_idle,
3841 const struct cpumask *cpus, int *balance,
3842 struct sd_lb_stats *sds)
3844 struct sched_domain *child = sd->child;
3845 struct sched_group *group = sd->groups;
3846 struct sg_lb_stats sgs;
3847 int load_idx, prefer_sibling = 0;
3849 if (child && child->flags & SD_PREFER_SIBLING)
3852 init_sd_power_savings_stats(sd, sds, idle);
3853 load_idx = get_sd_load_idx(sd, idle);
3858 local_group = cpumask_test_cpu(this_cpu,
3859 sched_group_cpus(group));
3860 memset(&sgs, 0, sizeof(sgs));
3861 update_sg_lb_stats(sd, group, this_cpu, idle, load_idx, sd_idle,
3862 local_group, cpus, balance, &sgs);
3864 if (local_group && balance && !(*balance))
3867 sds->total_load += sgs.group_load;
3868 sds->total_pwr += group->cpu_power;
3871 * In case the child domain prefers tasks go to siblings
3872 * first, lower the group capacity to one so that we'll try
3873 * and move all the excess tasks away.
3876 sgs.group_capacity = min(sgs.group_capacity, 1UL);
3879 sds->this_load = sgs.avg_load;
3881 sds->this_nr_running = sgs.sum_nr_running;
3882 sds->this_load_per_task = sgs.sum_weighted_load;
3883 } else if (sgs.avg_load > sds->max_load &&
3884 (sgs.sum_nr_running > sgs.group_capacity ||
3886 sds->max_load = sgs.avg_load;
3887 sds->busiest = group;
3888 sds->busiest_nr_running = sgs.sum_nr_running;
3889 sds->busiest_load_per_task = sgs.sum_weighted_load;
3890 sds->group_imb = sgs.group_imb;
3893 update_sd_power_savings_stats(group, sds, local_group, &sgs);
3894 group = group->next;
3895 } while (group != sd->groups);
3899 * fix_small_imbalance - Calculate the minor imbalance that exists
3900 * amongst the groups of a sched_domain, during
3902 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
3903 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
3904 * @imbalance: Variable to store the imbalance.
3906 static inline void fix_small_imbalance(struct sd_lb_stats *sds,
3907 int this_cpu, unsigned long *imbalance)
3909 unsigned long tmp, pwr_now = 0, pwr_move = 0;
3910 unsigned int imbn = 2;
3912 if (sds->this_nr_running) {
3913 sds->this_load_per_task /= sds->this_nr_running;
3914 if (sds->busiest_load_per_task >
3915 sds->this_load_per_task)
3918 sds->this_load_per_task =
3919 cpu_avg_load_per_task(this_cpu);
3921 if (sds->max_load - sds->this_load + sds->busiest_load_per_task >=
3922 sds->busiest_load_per_task * imbn) {
3923 *imbalance = sds->busiest_load_per_task;
3928 * OK, we don't have enough imbalance to justify moving tasks,
3929 * however we may be able to increase total CPU power used by
3933 pwr_now += sds->busiest->cpu_power *
3934 min(sds->busiest_load_per_task, sds->max_load);
3935 pwr_now += sds->this->cpu_power *
3936 min(sds->this_load_per_task, sds->this_load);
3937 pwr_now /= SCHED_LOAD_SCALE;
3939 /* Amount of load we'd subtract */
3940 tmp = (sds->busiest_load_per_task * SCHED_LOAD_SCALE) /
3941 sds->busiest->cpu_power;
3942 if (sds->max_load > tmp)
3943 pwr_move += sds->busiest->cpu_power *
3944 min(sds->busiest_load_per_task, sds->max_load - tmp);
3946 /* Amount of load we'd add */
3947 if (sds->max_load * sds->busiest->cpu_power <
3948 sds->busiest_load_per_task * SCHED_LOAD_SCALE)
3949 tmp = (sds->max_load * sds->busiest->cpu_power) /
3950 sds->this->cpu_power;
3952 tmp = (sds->busiest_load_per_task * SCHED_LOAD_SCALE) /
3953 sds->this->cpu_power;
3954 pwr_move += sds->this->cpu_power *
3955 min(sds->this_load_per_task, sds->this_load + tmp);
3956 pwr_move /= SCHED_LOAD_SCALE;
3958 /* Move if we gain throughput */
3959 if (pwr_move > pwr_now)
3960 *imbalance = sds->busiest_load_per_task;
3964 * calculate_imbalance - Calculate the amount of imbalance present within the
3965 * groups of a given sched_domain during load balance.
3966 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
3967 * @this_cpu: Cpu for which currently load balance is being performed.
3968 * @imbalance: The variable to store the imbalance.
3970 static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
3971 unsigned long *imbalance)
3973 unsigned long max_pull;
3975 * In the presence of smp nice balancing, certain scenarios can have
3976 * max load less than avg load(as we skip the groups at or below
3977 * its cpu_power, while calculating max_load..)
3979 if (sds->max_load < sds->avg_load) {
3981 return fix_small_imbalance(sds, this_cpu, imbalance);
3984 /* Don't want to pull so many tasks that a group would go idle */
3985 max_pull = min(sds->max_load - sds->avg_load,
3986 sds->max_load - sds->busiest_load_per_task);
3988 /* How much load to actually move to equalise the imbalance */
3989 *imbalance = min(max_pull * sds->busiest->cpu_power,
3990 (sds->avg_load - sds->this_load) * sds->this->cpu_power)
3994 * if *imbalance is less than the average load per runnable task
3995 * there is no gaurantee that any tasks will be moved so we'll have
3996 * a think about bumping its value to force at least one task to be
3999 if (*imbalance < sds->busiest_load_per_task)
4000 return fix_small_imbalance(sds, this_cpu, imbalance);
4003 /******* find_busiest_group() helpers end here *********************/
4006 * find_busiest_group - Returns the busiest group within the sched_domain
4007 * if there is an imbalance. If there isn't an imbalance, and
4008 * the user has opted for power-savings, it returns a group whose
4009 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
4010 * such a group exists.
4012 * Also calculates the amount of weighted load which should be moved
4013 * to restore balance.
4015 * @sd: The sched_domain whose busiest group is to be returned.
4016 * @this_cpu: The cpu for which load balancing is currently being performed.
4017 * @imbalance: Variable which stores amount of weighted load which should
4018 * be moved to restore balance/put a group to idle.
4019 * @idle: The idle status of this_cpu.
4020 * @sd_idle: The idleness of sd
4021 * @cpus: The set of CPUs under consideration for load-balancing.
4022 * @balance: Pointer to a variable indicating if this_cpu
4023 * is the appropriate cpu to perform load balancing at this_level.
4025 * Returns: - the busiest group if imbalance exists.
4026 * - If no imbalance and user has opted for power-savings balance,
4027 * return the least loaded group whose CPUs can be
4028 * put to idle by rebalancing its tasks onto our group.
4030 static struct sched_group *
4031 find_busiest_group(struct sched_domain *sd, int this_cpu,
4032 unsigned long *imbalance, enum cpu_idle_type idle,
4033 int *sd_idle, const struct cpumask *cpus, int *balance)
4035 struct sd_lb_stats sds;
4037 memset(&sds, 0, sizeof(sds));
4040 * Compute the various statistics relavent for load balancing at
4043 update_sd_lb_stats(sd, this_cpu, idle, sd_idle, cpus,
4046 /* Cases where imbalance does not exist from POV of this_cpu */
4047 /* 1) this_cpu is not the appropriate cpu to perform load balancing
4049 * 2) There is no busy sibling group to pull from.
4050 * 3) This group is the busiest group.
4051 * 4) This group is more busy than the avg busieness at this
4053 * 5) The imbalance is within the specified limit.
4054 * 6) Any rebalance would lead to ping-pong
4056 if (balance && !(*balance))
4059 if (!sds.busiest || sds.busiest_nr_running == 0)
4062 if (sds.this_load >= sds.max_load)
4065 sds.avg_load = (SCHED_LOAD_SCALE * sds.total_load) / sds.total_pwr;
4067 if (sds.this_load >= sds.avg_load)
4070 if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
4073 sds.busiest_load_per_task /= sds.busiest_nr_running;
4075 sds.busiest_load_per_task =
4076 min(sds.busiest_load_per_task, sds.avg_load);
4079 * We're trying to get all the cpus to the average_load, so we don't
4080 * want to push ourselves above the average load, nor do we wish to
4081 * reduce the max loaded cpu below the average load, as either of these
4082 * actions would just result in more rebalancing later, and ping-pong
4083 * tasks around. Thus we look for the minimum possible imbalance.
4084 * Negative imbalances (*we* are more loaded than anyone else) will
4085 * be counted as no imbalance for these purposes -- we can't fix that
4086 * by pulling tasks to us. Be careful of negative numbers as they'll
4087 * appear as very large values with unsigned longs.
4089 if (sds.max_load <= sds.busiest_load_per_task)
4092 /* Looks like there is an imbalance. Compute it */
4093 calculate_imbalance(&sds, this_cpu, imbalance);
4098 * There is no obvious imbalance. But check if we can do some balancing
4101 if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
4109 * find_busiest_queue - find the busiest runqueue among the cpus in group.
4112 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
4113 unsigned long imbalance, const struct cpumask *cpus)
4115 struct rq *busiest = NULL, *rq;
4116 unsigned long max_load = 0;
4119 for_each_cpu(i, sched_group_cpus(group)) {
4120 unsigned long power = power_of(i);
4121 unsigned long capacity = DIV_ROUND_CLOSEST(power, SCHED_LOAD_SCALE);
4124 if (!cpumask_test_cpu(i, cpus))
4128 wl = weighted_cpuload(i) * SCHED_LOAD_SCALE;
4131 if (capacity && rq->nr_running == 1 && wl > imbalance)
4134 if (wl > max_load) {
4144 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4145 * so long as it is large enough.
4147 #define MAX_PINNED_INTERVAL 512
4149 /* Working cpumask for load_balance and load_balance_newidle. */
4150 static DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
4153 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4154 * tasks if there is an imbalance.
4156 static int load_balance(int this_cpu, struct rq *this_rq,
4157 struct sched_domain *sd, enum cpu_idle_type idle,
4160 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
4161 struct sched_group *group;
4162 unsigned long imbalance;
4164 unsigned long flags;
4165 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4167 cpumask_copy(cpus, cpu_active_mask);
4170 * When power savings policy is enabled for the parent domain, idle
4171 * sibling can pick up load irrespective of busy siblings. In this case,
4172 * let the state of idle sibling percolate up as CPU_IDLE, instead of
4173 * portraying it as CPU_NOT_IDLE.
4175 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
4176 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4179 schedstat_inc(sd, lb_count[idle]);
4183 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
4190 schedstat_inc(sd, lb_nobusyg[idle]);
4194 busiest = find_busiest_queue(group, idle, imbalance, cpus);
4196 schedstat_inc(sd, lb_nobusyq[idle]);
4200 BUG_ON(busiest == this_rq);
4202 schedstat_add(sd, lb_imbalance[idle], imbalance);
4205 if (busiest->nr_running > 1) {
4207 * Attempt to move tasks. If find_busiest_group has found
4208 * an imbalance but busiest->nr_running <= 1, the group is
4209 * still unbalanced. ld_moved simply stays zero, so it is
4210 * correctly treated as an imbalance.
4212 local_irq_save(flags);
4213 double_rq_lock(this_rq, busiest);
4214 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4215 imbalance, sd, idle, &all_pinned);
4216 double_rq_unlock(this_rq, busiest);
4217 local_irq_restore(flags);
4220 * some other cpu did the load balance for us.
4222 if (ld_moved && this_cpu != smp_processor_id())
4223 resched_cpu(this_cpu);
4225 /* All tasks on this runqueue were pinned by CPU affinity */
4226 if (unlikely(all_pinned)) {
4227 cpumask_clear_cpu(cpu_of(busiest), cpus);
4228 if (!cpumask_empty(cpus))
4235 schedstat_inc(sd, lb_failed[idle]);
4236 sd->nr_balance_failed++;
4238 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
4240 raw_spin_lock_irqsave(&busiest->lock, flags);
4242 /* don't kick the migration_thread, if the curr
4243 * task on busiest cpu can't be moved to this_cpu
4245 if (!cpumask_test_cpu(this_cpu,
4246 &busiest->curr->cpus_allowed)) {
4247 raw_spin_unlock_irqrestore(&busiest->lock,
4250 goto out_one_pinned;
4253 if (!busiest->active_balance) {
4254 busiest->active_balance = 1;
4255 busiest->push_cpu = this_cpu;
4258 raw_spin_unlock_irqrestore(&busiest->lock, flags);
4260 wake_up_process(busiest->migration_thread);
4263 * We've kicked active balancing, reset the failure
4266 sd->nr_balance_failed = sd->cache_nice_tries+1;
4269 sd->nr_balance_failed = 0;
4271 if (likely(!active_balance)) {
4272 /* We were unbalanced, so reset the balancing interval */
4273 sd->balance_interval = sd->min_interval;
4276 * If we've begun active balancing, start to back off. This
4277 * case may not be covered by the all_pinned logic if there
4278 * is only 1 task on the busy runqueue (because we don't call
4281 if (sd->balance_interval < sd->max_interval)
4282 sd->balance_interval *= 2;
4285 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4286 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4292 schedstat_inc(sd, lb_balanced[idle]);
4294 sd->nr_balance_failed = 0;
4297 /* tune up the balancing interval */
4298 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
4299 (sd->balance_interval < sd->max_interval))
4300 sd->balance_interval *= 2;
4302 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4303 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4314 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4315 * tasks if there is an imbalance.
4317 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
4318 * this_rq is locked.
4321 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
4323 struct sched_group *group;
4324 struct rq *busiest = NULL;
4325 unsigned long imbalance;
4329 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4331 cpumask_copy(cpus, cpu_active_mask);
4334 * When power savings policy is enabled for the parent domain, idle
4335 * sibling can pick up load irrespective of busy siblings. In this case,
4336 * let the state of idle sibling percolate up as IDLE, instead of
4337 * portraying it as CPU_NOT_IDLE.
4339 if (sd->flags & SD_SHARE_CPUPOWER &&
4340 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4343 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
4345 update_shares_locked(this_rq, sd);
4346 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
4347 &sd_idle, cpus, NULL);
4349 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
4353 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
4355 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
4359 BUG_ON(busiest == this_rq);
4361 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
4364 if (busiest->nr_running > 1) {
4365 /* Attempt to move tasks */
4366 double_lock_balance(this_rq, busiest);
4367 /* this_rq->clock is already updated */
4368 update_rq_clock(busiest);
4369 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4370 imbalance, sd, CPU_NEWLY_IDLE,
4372 double_unlock_balance(this_rq, busiest);
4374 if (unlikely(all_pinned)) {
4375 cpumask_clear_cpu(cpu_of(busiest), cpus);
4376 if (!cpumask_empty(cpus))
4382 int active_balance = 0;
4384 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
4385 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4386 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4389 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
4392 if (sd->nr_balance_failed++ < 2)
4396 * The only task running in a non-idle cpu can be moved to this
4397 * cpu in an attempt to completely freeup the other CPU
4398 * package. The same method used to move task in load_balance()
4399 * have been extended for load_balance_newidle() to speedup
4400 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
4402 * The package power saving logic comes from
4403 * find_busiest_group(). If there are no imbalance, then
4404 * f_b_g() will return NULL. However when sched_mc={1,2} then
4405 * f_b_g() will select a group from which a running task may be
4406 * pulled to this cpu in order to make the other package idle.
4407 * If there is no opportunity to make a package idle and if
4408 * there are no imbalance, then f_b_g() will return NULL and no
4409 * action will be taken in load_balance_newidle().
4411 * Under normal task pull operation due to imbalance, there
4412 * will be more than one task in the source run queue and
4413 * move_tasks() will succeed. ld_moved will be true and this
4414 * active balance code will not be triggered.
4417 /* Lock busiest in correct order while this_rq is held */
4418 double_lock_balance(this_rq, busiest);
4421 * don't kick the migration_thread, if the curr
4422 * task on busiest cpu can't be moved to this_cpu
4424 if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
4425 double_unlock_balance(this_rq, busiest);
4430 if (!busiest->active_balance) {
4431 busiest->active_balance = 1;
4432 busiest->push_cpu = this_cpu;
4436 double_unlock_balance(this_rq, busiest);
4438 * Should not call ttwu while holding a rq->lock
4440 raw_spin_unlock(&this_rq->lock);
4442 wake_up_process(busiest->migration_thread);
4443 raw_spin_lock(&this_rq->lock);
4446 sd->nr_balance_failed = 0;
4448 update_shares_locked(this_rq, sd);
4452 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
4453 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4454 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4456 sd->nr_balance_failed = 0;
4462 * idle_balance is called by schedule() if this_cpu is about to become
4463 * idle. Attempts to pull tasks from other CPUs.
4465 static void idle_balance(int this_cpu, struct rq *this_rq)
4467 struct sched_domain *sd;
4468 int pulled_task = 0;
4469 unsigned long next_balance = jiffies + HZ;
4471 this_rq->idle_stamp = this_rq->clock;
4473 if (this_rq->avg_idle < sysctl_sched_migration_cost)
4476 for_each_domain(this_cpu, sd) {
4477 unsigned long interval;
4479 if (!(sd->flags & SD_LOAD_BALANCE))
4482 if (sd->flags & SD_BALANCE_NEWIDLE)
4483 /* If we've pulled tasks over stop searching: */
4484 pulled_task = load_balance_newidle(this_cpu, this_rq,
4487 interval = msecs_to_jiffies(sd->balance_interval);
4488 if (time_after(next_balance, sd->last_balance + interval))
4489 next_balance = sd->last_balance + interval;
4491 this_rq->idle_stamp = 0;
4495 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4497 * We are going idle. next_balance may be set based on
4498 * a busy processor. So reset next_balance.
4500 this_rq->next_balance = next_balance;
4505 * active_load_balance is run by migration threads. It pushes running tasks
4506 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4507 * running on each physical CPU where possible, and avoids physical /
4508 * logical imbalances.
4510 * Called with busiest_rq locked.
4512 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4514 int target_cpu = busiest_rq->push_cpu;
4515 struct sched_domain *sd;
4516 struct rq *target_rq;
4518 /* Is there any task to move? */
4519 if (busiest_rq->nr_running <= 1)
4522 target_rq = cpu_rq(target_cpu);
4525 * This condition is "impossible", if it occurs
4526 * we need to fix it. Originally reported by
4527 * Bjorn Helgaas on a 128-cpu setup.
4529 BUG_ON(busiest_rq == target_rq);
4531 /* move a task from busiest_rq to target_rq */
4532 double_lock_balance(busiest_rq, target_rq);
4533 update_rq_clock(busiest_rq);
4534 update_rq_clock(target_rq);
4536 /* Search for an sd spanning us and the target CPU. */
4537 for_each_domain(target_cpu, sd) {
4538 if ((sd->flags & SD_LOAD_BALANCE) &&
4539 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4544 schedstat_inc(sd, alb_count);
4546 if (move_one_task(target_rq, target_cpu, busiest_rq,
4548 schedstat_inc(sd, alb_pushed);
4550 schedstat_inc(sd, alb_failed);
4552 double_unlock_balance(busiest_rq, target_rq);
4557 atomic_t load_balancer;
4558 cpumask_var_t cpu_mask;
4559 cpumask_var_t ilb_grp_nohz_mask;
4560 } nohz ____cacheline_aligned = {
4561 .load_balancer = ATOMIC_INIT(-1),
4564 int get_nohz_load_balancer(void)
4566 return atomic_read(&nohz.load_balancer);
4569 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
4571 * lowest_flag_domain - Return lowest sched_domain containing flag.
4572 * @cpu: The cpu whose lowest level of sched domain is to
4574 * @flag: The flag to check for the lowest sched_domain
4575 * for the given cpu.
4577 * Returns the lowest sched_domain of a cpu which contains the given flag.
4579 static inline struct sched_domain *lowest_flag_domain(int cpu, int flag)
4581 struct sched_domain *sd;
4583 for_each_domain(cpu, sd)
4584 if (sd && (sd->flags & flag))
4591 * for_each_flag_domain - Iterates over sched_domains containing the flag.
4592 * @cpu: The cpu whose domains we're iterating over.
4593 * @sd: variable holding the value of the power_savings_sd
4595 * @flag: The flag to filter the sched_domains to be iterated.
4597 * Iterates over all the scheduler domains for a given cpu that has the 'flag'
4598 * set, starting from the lowest sched_domain to the highest.
4600 #define for_each_flag_domain(cpu, sd, flag) \
4601 for (sd = lowest_flag_domain(cpu, flag); \
4602 (sd && (sd->flags & flag)); sd = sd->parent)
4605 * is_semi_idle_group - Checks if the given sched_group is semi-idle.
4606 * @ilb_group: group to be checked for semi-idleness
4608 * Returns: 1 if the group is semi-idle. 0 otherwise.
4610 * We define a sched_group to be semi idle if it has atleast one idle-CPU
4611 * and atleast one non-idle CPU. This helper function checks if the given
4612 * sched_group is semi-idle or not.
4614 static inline int is_semi_idle_group(struct sched_group *ilb_group)
4616 cpumask_and(nohz.ilb_grp_nohz_mask, nohz.cpu_mask,
4617 sched_group_cpus(ilb_group));
4620 * A sched_group is semi-idle when it has atleast one busy cpu
4621 * and atleast one idle cpu.
4623 if (cpumask_empty(nohz.ilb_grp_nohz_mask))
4626 if (cpumask_equal(nohz.ilb_grp_nohz_mask, sched_group_cpus(ilb_group)))
4632 * find_new_ilb - Finds the optimum idle load balancer for nomination.
4633 * @cpu: The cpu which is nominating a new idle_load_balancer.
4635 * Returns: Returns the id of the idle load balancer if it exists,
4636 * Else, returns >= nr_cpu_ids.
4638 * This algorithm picks the idle load balancer such that it belongs to a
4639 * semi-idle powersavings sched_domain. The idea is to try and avoid
4640 * completely idle packages/cores just for the purpose of idle load balancing
4641 * when there are other idle cpu's which are better suited for that job.
4643 static int find_new_ilb(int cpu)
4645 struct sched_domain *sd;
4646 struct sched_group *ilb_group;
4649 * Have idle load balancer selection from semi-idle packages only
4650 * when power-aware load balancing is enabled
4652 if (!(sched_smt_power_savings || sched_mc_power_savings))
4656 * Optimize for the case when we have no idle CPUs or only one
4657 * idle CPU. Don't walk the sched_domain hierarchy in such cases
4659 if (cpumask_weight(nohz.cpu_mask) < 2)
4662 for_each_flag_domain(cpu, sd, SD_POWERSAVINGS_BALANCE) {
4663 ilb_group = sd->groups;
4666 if (is_semi_idle_group(ilb_group))
4667 return cpumask_first(nohz.ilb_grp_nohz_mask);
4669 ilb_group = ilb_group->next;
4671 } while (ilb_group != sd->groups);
4675 return cpumask_first(nohz.cpu_mask);
4677 #else /* (CONFIG_SCHED_MC || CONFIG_SCHED_SMT) */
4678 static inline int find_new_ilb(int call_cpu)
4680 return cpumask_first(nohz.cpu_mask);
4685 * This routine will try to nominate the ilb (idle load balancing)
4686 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4687 * load balancing on behalf of all those cpus. If all the cpus in the system
4688 * go into this tickless mode, then there will be no ilb owner (as there is
4689 * no need for one) and all the cpus will sleep till the next wakeup event
4692 * For the ilb owner, tick is not stopped. And this tick will be used
4693 * for idle load balancing. ilb owner will still be part of
4696 * While stopping the tick, this cpu will become the ilb owner if there
4697 * is no other owner. And will be the owner till that cpu becomes busy
4698 * or if all cpus in the system stop their ticks at which point
4699 * there is no need for ilb owner.
4701 * When the ilb owner becomes busy, it nominates another owner, during the
4702 * next busy scheduler_tick()
4704 int select_nohz_load_balancer(int stop_tick)
4706 int cpu = smp_processor_id();
4709 cpu_rq(cpu)->in_nohz_recently = 1;
4711 if (!cpu_active(cpu)) {
4712 if (atomic_read(&nohz.load_balancer) != cpu)
4716 * If we are going offline and still the leader,
4719 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4725 cpumask_set_cpu(cpu, nohz.cpu_mask);
4727 /* time for ilb owner also to sleep */
4728 if (cpumask_weight(nohz.cpu_mask) == num_active_cpus()) {
4729 if (atomic_read(&nohz.load_balancer) == cpu)
4730 atomic_set(&nohz.load_balancer, -1);
4734 if (atomic_read(&nohz.load_balancer) == -1) {
4735 /* make me the ilb owner */
4736 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4738 } else if (atomic_read(&nohz.load_balancer) == cpu) {
4741 if (!(sched_smt_power_savings ||
4742 sched_mc_power_savings))
4745 * Check to see if there is a more power-efficient
4748 new_ilb = find_new_ilb(cpu);
4749 if (new_ilb < nr_cpu_ids && new_ilb != cpu) {
4750 atomic_set(&nohz.load_balancer, -1);
4751 resched_cpu(new_ilb);
4757 if (!cpumask_test_cpu(cpu, nohz.cpu_mask))
4760 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4762 if (atomic_read(&nohz.load_balancer) == cpu)
4763 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4770 static DEFINE_SPINLOCK(balancing);
4773 * It checks each scheduling domain to see if it is due to be balanced,
4774 * and initiates a balancing operation if so.
4776 * Balancing parameters are set up in arch_init_sched_domains.
4778 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4781 struct rq *rq = cpu_rq(cpu);
4782 unsigned long interval;
4783 struct sched_domain *sd;
4784 /* Earliest time when we have to do rebalance again */
4785 unsigned long next_balance = jiffies + 60*HZ;
4786 int update_next_balance = 0;
4789 for_each_domain(cpu, sd) {
4790 if (!(sd->flags & SD_LOAD_BALANCE))
4793 interval = sd->balance_interval;
4794 if (idle != CPU_IDLE)
4795 interval *= sd->busy_factor;
4797 /* scale ms to jiffies */
4798 interval = msecs_to_jiffies(interval);
4799 if (unlikely(!interval))
4801 if (interval > HZ*NR_CPUS/10)
4802 interval = HZ*NR_CPUS/10;
4804 need_serialize = sd->flags & SD_SERIALIZE;
4806 if (need_serialize) {
4807 if (!spin_trylock(&balancing))
4811 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4812 if (load_balance(cpu, rq, sd, idle, &balance)) {
4814 * We've pulled tasks over so either we're no
4815 * longer idle, or one of our SMT siblings is
4818 idle = CPU_NOT_IDLE;
4820 sd->last_balance = jiffies;
4823 spin_unlock(&balancing);
4825 if (time_after(next_balance, sd->last_balance + interval)) {
4826 next_balance = sd->last_balance + interval;
4827 update_next_balance = 1;
4831 * Stop the load balance at this level. There is another
4832 * CPU in our sched group which is doing load balancing more
4840 * next_balance will be updated only when there is a need.
4841 * When the cpu is attached to null domain for ex, it will not be
4844 if (likely(update_next_balance))
4845 rq->next_balance = next_balance;
4849 * run_rebalance_domains is triggered when needed from the scheduler tick.
4850 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4851 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4853 static void run_rebalance_domains(struct softirq_action *h)
4855 int this_cpu = smp_processor_id();
4856 struct rq *this_rq = cpu_rq(this_cpu);
4857 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4858 CPU_IDLE : CPU_NOT_IDLE;
4860 rebalance_domains(this_cpu, idle);
4864 * If this cpu is the owner for idle load balancing, then do the
4865 * balancing on behalf of the other idle cpus whose ticks are
4868 if (this_rq->idle_at_tick &&
4869 atomic_read(&nohz.load_balancer) == this_cpu) {
4873 for_each_cpu(balance_cpu, nohz.cpu_mask) {
4874 if (balance_cpu == this_cpu)
4878 * If this cpu gets work to do, stop the load balancing
4879 * work being done for other cpus. Next load
4880 * balancing owner will pick it up.
4885 rebalance_domains(balance_cpu, CPU_IDLE);
4887 rq = cpu_rq(balance_cpu);
4888 if (time_after(this_rq->next_balance, rq->next_balance))
4889 this_rq->next_balance = rq->next_balance;
4895 static inline int on_null_domain(int cpu)
4897 return !rcu_dereference(cpu_rq(cpu)->sd);
4901 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4903 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4904 * idle load balancing owner or decide to stop the periodic load balancing,
4905 * if the whole system is idle.
4907 static inline void trigger_load_balance(struct rq *rq, int cpu)
4911 * If we were in the nohz mode recently and busy at the current
4912 * scheduler tick, then check if we need to nominate new idle
4915 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4916 rq->in_nohz_recently = 0;
4918 if (atomic_read(&nohz.load_balancer) == cpu) {
4919 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4920 atomic_set(&nohz.load_balancer, -1);
4923 if (atomic_read(&nohz.load_balancer) == -1) {
4924 int ilb = find_new_ilb(cpu);
4926 if (ilb < nr_cpu_ids)
4932 * If this cpu is idle and doing idle load balancing for all the
4933 * cpus with ticks stopped, is it time for that to stop?
4935 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4936 cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4942 * If this cpu is idle and the idle load balancing is done by
4943 * someone else, then no need raise the SCHED_SOFTIRQ
4945 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4946 cpumask_test_cpu(cpu, nohz.cpu_mask))
4949 /* Don't need to rebalance while attached to NULL domain */
4950 if (time_after_eq(jiffies, rq->next_balance) &&
4951 likely(!on_null_domain(cpu)))
4952 raise_softirq(SCHED_SOFTIRQ);
4955 #else /* CONFIG_SMP */
4958 * on UP we do not need to balance between CPUs:
4960 static inline void idle_balance(int cpu, struct rq *rq)
4966 DEFINE_PER_CPU(struct kernel_stat, kstat);
4968 EXPORT_PER_CPU_SYMBOL(kstat);
4971 * Return any ns on the sched_clock that have not yet been accounted in
4972 * @p in case that task is currently running.
4974 * Called with task_rq_lock() held on @rq.
4976 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
4980 if (task_current(rq, p)) {
4981 update_rq_clock(rq);
4982 ns = rq->clock - p->se.exec_start;
4990 unsigned long long task_delta_exec(struct task_struct *p)
4992 unsigned long flags;
4996 rq = task_rq_lock(p, &flags);
4997 ns = do_task_delta_exec(p, rq);
4998 task_rq_unlock(rq, &flags);
5004 * Return accounted runtime for the task.
5005 * In case the task is currently running, return the runtime plus current's
5006 * pending runtime that have not been accounted yet.
5008 unsigned long long task_sched_runtime(struct task_struct *p)
5010 unsigned long flags;
5014 rq = task_rq_lock(p, &flags);
5015 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
5016 task_rq_unlock(rq, &flags);
5022 * Return sum_exec_runtime for the thread group.
5023 * In case the task is currently running, return the sum plus current's
5024 * pending runtime that have not been accounted yet.
5026 * Note that the thread group might have other running tasks as well,
5027 * so the return value not includes other pending runtime that other
5028 * running tasks might have.
5030 unsigned long long thread_group_sched_runtime(struct task_struct *p)
5032 struct task_cputime totals;
5033 unsigned long flags;
5037 rq = task_rq_lock(p, &flags);
5038 thread_group_cputime(p, &totals);
5039 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
5040 task_rq_unlock(rq, &flags);
5046 * Account user cpu time to a process.
5047 * @p: the process that the cpu time gets accounted to
5048 * @cputime: the cpu time spent in user space since the last update
5049 * @cputime_scaled: cputime scaled by cpu frequency
5051 void account_user_time(struct task_struct *p, cputime_t cputime,
5052 cputime_t cputime_scaled)
5054 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5057 /* Add user time to process. */
5058 p->utime = cputime_add(p->utime, cputime);
5059 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
5060 account_group_user_time(p, cputime);
5062 /* Add user time to cpustat. */
5063 tmp = cputime_to_cputime64(cputime);
5064 if (TASK_NICE(p) > 0)
5065 cpustat->nice = cputime64_add(cpustat->nice, tmp);
5067 cpustat->user = cputime64_add(cpustat->user, tmp);
5069 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
5070 /* Account for user time used */
5071 acct_update_integrals(p);
5075 * Account guest cpu time to a process.
5076 * @p: the process that the cpu time gets accounted to
5077 * @cputime: the cpu time spent in virtual machine since the last update
5078 * @cputime_scaled: cputime scaled by cpu frequency
5080 static void account_guest_time(struct task_struct *p, cputime_t cputime,
5081 cputime_t cputime_scaled)
5084 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5086 tmp = cputime_to_cputime64(cputime);
5088 /* Add guest time to process. */
5089 p->utime = cputime_add(p->utime, cputime);
5090 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
5091 account_group_user_time(p, cputime);
5092 p->gtime = cputime_add(p->gtime, cputime);
5094 /* Add guest time to cpustat. */
5095 if (TASK_NICE(p) > 0) {
5096 cpustat->nice = cputime64_add(cpustat->nice, tmp);
5097 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
5099 cpustat->user = cputime64_add(cpustat->user, tmp);
5100 cpustat->guest = cputime64_add(cpustat->guest, tmp);
5105 * Account system cpu time to a process.
5106 * @p: the process that the cpu time gets accounted to
5107 * @hardirq_offset: the offset to subtract from hardirq_count()
5108 * @cputime: the cpu time spent in kernel space since the last update
5109 * @cputime_scaled: cputime scaled by cpu frequency
5111 void account_system_time(struct task_struct *p, int hardirq_offset,
5112 cputime_t cputime, cputime_t cputime_scaled)
5114 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5117 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
5118 account_guest_time(p, cputime, cputime_scaled);
5122 /* Add system time to process. */
5123 p->stime = cputime_add(p->stime, cputime);
5124 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
5125 account_group_system_time(p, cputime);
5127 /* Add system time to cpustat. */
5128 tmp = cputime_to_cputime64(cputime);
5129 if (hardirq_count() - hardirq_offset)
5130 cpustat->irq = cputime64_add(cpustat->irq, tmp);
5131 else if (softirq_count())
5132 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
5134 cpustat->system = cputime64_add(cpustat->system, tmp);
5136 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
5138 /* Account for system time used */
5139 acct_update_integrals(p);
5143 * Account for involuntary wait time.
5144 * @steal: the cpu time spent in involuntary wait
5146 void account_steal_time(cputime_t cputime)
5148 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5149 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5151 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
5155 * Account for idle time.
5156 * @cputime: the cpu time spent in idle wait
5158 void account_idle_time(cputime_t cputime)
5160 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5161 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5162 struct rq *rq = this_rq();
5164 if (atomic_read(&rq->nr_iowait) > 0)
5165 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
5167 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
5170 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
5173 * Account a single tick of cpu time.
5174 * @p: the process that the cpu time gets accounted to
5175 * @user_tick: indicates if the tick is a user or a system tick
5177 void account_process_tick(struct task_struct *p, int user_tick)
5179 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
5180 struct rq *rq = this_rq();
5183 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
5184 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
5185 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
5188 account_idle_time(cputime_one_jiffy);
5192 * Account multiple ticks of steal time.
5193 * @p: the process from which the cpu time has been stolen
5194 * @ticks: number of stolen ticks
5196 void account_steal_ticks(unsigned long ticks)
5198 account_steal_time(jiffies_to_cputime(ticks));
5202 * Account multiple ticks of idle time.
5203 * @ticks: number of stolen ticks
5205 void account_idle_ticks(unsigned long ticks)
5207 account_idle_time(jiffies_to_cputime(ticks));
5213 * Use precise platform statistics if available:
5215 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
5216 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5222 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5224 struct task_cputime cputime;
5226 thread_group_cputime(p, &cputime);
5228 *ut = cputime.utime;
5229 *st = cputime.stime;
5233 #ifndef nsecs_to_cputime
5234 # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
5237 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5239 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
5242 * Use CFS's precise accounting:
5244 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
5249 temp = (u64)(rtime * utime);
5250 do_div(temp, total);
5251 utime = (cputime_t)temp;
5256 * Compare with previous values, to keep monotonicity:
5258 p->prev_utime = max(p->prev_utime, utime);
5259 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
5261 *ut = p->prev_utime;
5262 *st = p->prev_stime;
5266 * Must be called with siglock held.
5268 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5270 struct signal_struct *sig = p->signal;
5271 struct task_cputime cputime;
5272 cputime_t rtime, utime, total;
5274 thread_group_cputime(p, &cputime);
5276 total = cputime_add(cputime.utime, cputime.stime);
5277 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
5282 temp = (u64)(rtime * cputime.utime);
5283 do_div(temp, total);
5284 utime = (cputime_t)temp;
5288 sig->prev_utime = max(sig->prev_utime, utime);
5289 sig->prev_stime = max(sig->prev_stime,
5290 cputime_sub(rtime, sig->prev_utime));
5292 *ut = sig->prev_utime;
5293 *st = sig->prev_stime;
5298 * This function gets called by the timer code, with HZ frequency.
5299 * We call it with interrupts disabled.
5301 * It also gets called by the fork code, when changing the parent's
5304 void scheduler_tick(void)
5306 int cpu = smp_processor_id();
5307 struct rq *rq = cpu_rq(cpu);
5308 struct task_struct *curr = rq->curr;
5312 raw_spin_lock(&rq->lock);
5313 update_rq_clock(rq);
5314 update_cpu_load(rq);
5315 curr->sched_class->task_tick(rq, curr, 0);
5316 raw_spin_unlock(&rq->lock);
5318 perf_event_task_tick(curr);
5321 rq->idle_at_tick = idle_cpu(cpu);
5322 trigger_load_balance(rq, cpu);
5326 notrace unsigned long get_parent_ip(unsigned long addr)
5328 if (in_lock_functions(addr)) {
5329 addr = CALLER_ADDR2;
5330 if (in_lock_functions(addr))
5331 addr = CALLER_ADDR3;
5336 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
5337 defined(CONFIG_PREEMPT_TRACER))
5339 void __kprobes add_preempt_count(int val)
5341 #ifdef CONFIG_DEBUG_PREEMPT
5345 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5348 preempt_count() += val;
5349 #ifdef CONFIG_DEBUG_PREEMPT
5351 * Spinlock count overflowing soon?
5353 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5356 if (preempt_count() == val)
5357 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5359 EXPORT_SYMBOL(add_preempt_count);
5361 void __kprobes sub_preempt_count(int val)
5363 #ifdef CONFIG_DEBUG_PREEMPT
5367 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
5370 * Is the spinlock portion underflowing?
5372 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5373 !(preempt_count() & PREEMPT_MASK)))
5377 if (preempt_count() == val)
5378 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5379 preempt_count() -= val;
5381 EXPORT_SYMBOL(sub_preempt_count);
5386 * Print scheduling while atomic bug:
5388 static noinline void __schedule_bug(struct task_struct *prev)
5390 struct pt_regs *regs = get_irq_regs();
5392 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
5393 prev->comm, prev->pid, preempt_count());
5395 debug_show_held_locks(prev);
5397 if (irqs_disabled())
5398 print_irqtrace_events(prev);
5407 * Various schedule()-time debugging checks and statistics:
5409 static inline void schedule_debug(struct task_struct *prev)
5412 * Test if we are atomic. Since do_exit() needs to call into
5413 * schedule() atomically, we ignore that path for now.
5414 * Otherwise, whine if we are scheduling when we should not be.
5416 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
5417 __schedule_bug(prev);
5419 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5421 schedstat_inc(this_rq(), sched_count);
5422 #ifdef CONFIG_SCHEDSTATS
5423 if (unlikely(prev->lock_depth >= 0)) {
5424 schedstat_inc(this_rq(), bkl_count);
5425 schedstat_inc(prev, sched_info.bkl_count);
5430 static void put_prev_task(struct rq *rq, struct task_struct *prev)
5432 if (prev->state == TASK_RUNNING) {
5433 u64 runtime = prev->se.sum_exec_runtime;
5435 runtime -= prev->se.prev_sum_exec_runtime;
5436 runtime = min_t(u64, runtime, 2*sysctl_sched_migration_cost);
5439 * In order to avoid avg_overlap growing stale when we are
5440 * indeed overlapping and hence not getting put to sleep, grow
5441 * the avg_overlap on preemption.
5443 * We use the average preemption runtime because that
5444 * correlates to the amount of cache footprint a task can
5447 update_avg(&prev->se.avg_overlap, runtime);
5449 prev->sched_class->put_prev_task(rq, prev);
5453 * Pick up the highest-prio task:
5455 static inline struct task_struct *
5456 pick_next_task(struct rq *rq)
5458 const struct sched_class *class;
5459 struct task_struct *p;
5462 * Optimization: we know that if all tasks are in
5463 * the fair class we can call that function directly:
5465 if (likely(rq->nr_running == rq->cfs.nr_running)) {
5466 p = fair_sched_class.pick_next_task(rq);
5471 class = sched_class_highest;
5473 p = class->pick_next_task(rq);
5477 * Will never be NULL as the idle class always
5478 * returns a non-NULL p:
5480 class = class->next;
5485 * schedule() is the main scheduler function.
5487 asmlinkage void __sched schedule(void)
5489 struct task_struct *prev, *next;
5490 unsigned long *switch_count;
5496 cpu = smp_processor_id();
5500 switch_count = &prev->nivcsw;
5502 release_kernel_lock(prev);
5503 need_resched_nonpreemptible:
5505 schedule_debug(prev);
5507 if (sched_feat(HRTICK))
5510 raw_spin_lock_irq(&rq->lock);
5511 update_rq_clock(rq);
5512 clear_tsk_need_resched(prev);
5514 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
5515 if (unlikely(signal_pending_state(prev->state, prev)))
5516 prev->state = TASK_RUNNING;
5518 deactivate_task(rq, prev, 1);
5519 switch_count = &prev->nvcsw;
5522 pre_schedule(rq, prev);
5524 if (unlikely(!rq->nr_running))
5525 idle_balance(cpu, rq);
5527 put_prev_task(rq, prev);
5528 next = pick_next_task(rq);
5530 if (likely(prev != next)) {
5531 sched_info_switch(prev, next);
5532 perf_event_task_sched_out(prev, next);
5538 context_switch(rq, prev, next); /* unlocks the rq */
5540 * the context switch might have flipped the stack from under
5541 * us, hence refresh the local variables.
5543 cpu = smp_processor_id();
5546 raw_spin_unlock_irq(&rq->lock);
5550 if (unlikely(reacquire_kernel_lock(current) < 0)) {
5552 switch_count = &prev->nivcsw;
5553 goto need_resched_nonpreemptible;
5556 preempt_enable_no_resched();
5560 EXPORT_SYMBOL(schedule);
5562 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
5564 * Look out! "owner" is an entirely speculative pointer
5565 * access and not reliable.
5567 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
5572 if (!sched_feat(OWNER_SPIN))
5575 #ifdef CONFIG_DEBUG_PAGEALLOC
5577 * Need to access the cpu field knowing that
5578 * DEBUG_PAGEALLOC could have unmapped it if
5579 * the mutex owner just released it and exited.
5581 if (probe_kernel_address(&owner->cpu, cpu))
5588 * Even if the access succeeded (likely case),
5589 * the cpu field may no longer be valid.
5591 if (cpu >= nr_cpumask_bits)
5595 * We need to validate that we can do a
5596 * get_cpu() and that we have the percpu area.
5598 if (!cpu_online(cpu))
5605 * Owner changed, break to re-assess state.
5607 if (lock->owner != owner)
5611 * Is that owner really running on that cpu?
5613 if (task_thread_info(rq->curr) != owner || need_resched())
5623 #ifdef CONFIG_PREEMPT
5625 * this is the entry point to schedule() from in-kernel preemption
5626 * off of preempt_enable. Kernel preemptions off return from interrupt
5627 * occur there and call schedule directly.
5629 asmlinkage void __sched preempt_schedule(void)
5631 struct thread_info *ti = current_thread_info();
5634 * If there is a non-zero preempt_count or interrupts are disabled,
5635 * we do not want to preempt the current task. Just return..
5637 if (likely(ti->preempt_count || irqs_disabled()))
5641 add_preempt_count(PREEMPT_ACTIVE);
5643 sub_preempt_count(PREEMPT_ACTIVE);
5646 * Check again in case we missed a preemption opportunity
5647 * between schedule and now.
5650 } while (need_resched());
5652 EXPORT_SYMBOL(preempt_schedule);
5655 * this is the entry point to schedule() from kernel preemption
5656 * off of irq context.
5657 * Note, that this is called and return with irqs disabled. This will
5658 * protect us against recursive calling from irq.
5660 asmlinkage void __sched preempt_schedule_irq(void)
5662 struct thread_info *ti = current_thread_info();
5664 /* Catch callers which need to be fixed */
5665 BUG_ON(ti->preempt_count || !irqs_disabled());
5668 add_preempt_count(PREEMPT_ACTIVE);
5671 local_irq_disable();
5672 sub_preempt_count(PREEMPT_ACTIVE);
5675 * Check again in case we missed a preemption opportunity
5676 * between schedule and now.
5679 } while (need_resched());
5682 #endif /* CONFIG_PREEMPT */
5684 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
5687 return try_to_wake_up(curr->private, mode, wake_flags);
5689 EXPORT_SYMBOL(default_wake_function);
5692 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
5693 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
5694 * number) then we wake all the non-exclusive tasks and one exclusive task.
5696 * There are circumstances in which we can try to wake a task which has already
5697 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
5698 * zero in this (rare) case, and we handle it by continuing to scan the queue.
5700 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
5701 int nr_exclusive, int wake_flags, void *key)
5703 wait_queue_t *curr, *next;
5705 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
5706 unsigned flags = curr->flags;
5708 if (curr->func(curr, mode, wake_flags, key) &&
5709 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
5715 * __wake_up - wake up threads blocked on a waitqueue.
5717 * @mode: which threads
5718 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5719 * @key: is directly passed to the wakeup function
5721 * It may be assumed that this function implies a write memory barrier before
5722 * changing the task state if and only if any tasks are woken up.
5724 void __wake_up(wait_queue_head_t *q, unsigned int mode,
5725 int nr_exclusive, void *key)
5727 unsigned long flags;
5729 spin_lock_irqsave(&q->lock, flags);
5730 __wake_up_common(q, mode, nr_exclusive, 0, key);
5731 spin_unlock_irqrestore(&q->lock, flags);
5733 EXPORT_SYMBOL(__wake_up);
5736 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
5738 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
5740 __wake_up_common(q, mode, 1, 0, NULL);
5743 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
5745 __wake_up_common(q, mode, 1, 0, key);
5749 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
5751 * @mode: which threads
5752 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5753 * @key: opaque value to be passed to wakeup targets
5755 * The sync wakeup differs that the waker knows that it will schedule
5756 * away soon, so while the target thread will be woken up, it will not
5757 * be migrated to another CPU - ie. the two threads are 'synchronized'
5758 * with each other. This can prevent needless bouncing between CPUs.
5760 * On UP it can prevent extra preemption.
5762 * It may be assumed that this function implies a write memory barrier before
5763 * changing the task state if and only if any tasks are woken up.
5765 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
5766 int nr_exclusive, void *key)
5768 unsigned long flags;
5769 int wake_flags = WF_SYNC;
5774 if (unlikely(!nr_exclusive))
5777 spin_lock_irqsave(&q->lock, flags);
5778 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
5779 spin_unlock_irqrestore(&q->lock, flags);
5781 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
5784 * __wake_up_sync - see __wake_up_sync_key()
5786 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
5788 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
5790 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
5793 * complete: - signals a single thread waiting on this completion
5794 * @x: holds the state of this particular completion
5796 * This will wake up a single thread waiting on this completion. Threads will be
5797 * awakened in the same order in which they were queued.
5799 * See also complete_all(), wait_for_completion() and related routines.
5801 * It may be assumed that this function implies a write memory barrier before
5802 * changing the task state if and only if any tasks are woken up.
5804 void complete(struct completion *x)
5806 unsigned long flags;
5808 spin_lock_irqsave(&x->wait.lock, flags);
5810 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
5811 spin_unlock_irqrestore(&x->wait.lock, flags);
5813 EXPORT_SYMBOL(complete);
5816 * complete_all: - signals all threads waiting on this completion
5817 * @x: holds the state of this particular completion
5819 * This will wake up all threads waiting on this particular completion event.
5821 * It may be assumed that this function implies a write memory barrier before
5822 * changing the task state if and only if any tasks are woken up.
5824 void complete_all(struct completion *x)
5826 unsigned long flags;
5828 spin_lock_irqsave(&x->wait.lock, flags);
5829 x->done += UINT_MAX/2;
5830 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
5831 spin_unlock_irqrestore(&x->wait.lock, flags);
5833 EXPORT_SYMBOL(complete_all);
5835 static inline long __sched
5836 do_wait_for_common(struct completion *x, long timeout, int state)
5839 DECLARE_WAITQUEUE(wait, current);
5841 wait.flags |= WQ_FLAG_EXCLUSIVE;
5842 __add_wait_queue_tail(&x->wait, &wait);
5844 if (signal_pending_state(state, current)) {
5845 timeout = -ERESTARTSYS;
5848 __set_current_state(state);
5849 spin_unlock_irq(&x->wait.lock);
5850 timeout = schedule_timeout(timeout);
5851 spin_lock_irq(&x->wait.lock);
5852 } while (!x->done && timeout);
5853 __remove_wait_queue(&x->wait, &wait);
5858 return timeout ?: 1;
5862 wait_for_common(struct completion *x, long timeout, int state)
5866 spin_lock_irq(&x->wait.lock);
5867 timeout = do_wait_for_common(x, timeout, state);
5868 spin_unlock_irq(&x->wait.lock);
5873 * wait_for_completion: - waits for completion of a task
5874 * @x: holds the state of this particular completion
5876 * This waits to be signaled for completion of a specific task. It is NOT
5877 * interruptible and there is no timeout.
5879 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
5880 * and interrupt capability. Also see complete().
5882 void __sched wait_for_completion(struct completion *x)
5884 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
5886 EXPORT_SYMBOL(wait_for_completion);
5889 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
5890 * @x: holds the state of this particular completion
5891 * @timeout: timeout value in jiffies
5893 * This waits for either a completion of a specific task to be signaled or for a
5894 * specified timeout to expire. The timeout is in jiffies. It is not
5897 unsigned long __sched
5898 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
5900 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
5902 EXPORT_SYMBOL(wait_for_completion_timeout);
5905 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
5906 * @x: holds the state of this particular completion
5908 * This waits for completion of a specific task to be signaled. It is
5911 int __sched wait_for_completion_interruptible(struct completion *x)
5913 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
5914 if (t == -ERESTARTSYS)
5918 EXPORT_SYMBOL(wait_for_completion_interruptible);
5921 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
5922 * @x: holds the state of this particular completion
5923 * @timeout: timeout value in jiffies
5925 * This waits for either a completion of a specific task to be signaled or for a
5926 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
5928 unsigned long __sched
5929 wait_for_completion_interruptible_timeout(struct completion *x,
5930 unsigned long timeout)
5932 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
5934 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
5937 * wait_for_completion_killable: - waits for completion of a task (killable)
5938 * @x: holds the state of this particular completion
5940 * This waits to be signaled for completion of a specific task. It can be
5941 * interrupted by a kill signal.
5943 int __sched wait_for_completion_killable(struct completion *x)
5945 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
5946 if (t == -ERESTARTSYS)
5950 EXPORT_SYMBOL(wait_for_completion_killable);
5953 * try_wait_for_completion - try to decrement a completion without blocking
5954 * @x: completion structure
5956 * Returns: 0 if a decrement cannot be done without blocking
5957 * 1 if a decrement succeeded.
5959 * If a completion is being used as a counting completion,
5960 * attempt to decrement the counter without blocking. This
5961 * enables us to avoid waiting if the resource the completion
5962 * is protecting is not available.
5964 bool try_wait_for_completion(struct completion *x)
5966 unsigned long flags;
5969 spin_lock_irqsave(&x->wait.lock, flags);
5974 spin_unlock_irqrestore(&x->wait.lock, flags);
5977 EXPORT_SYMBOL(try_wait_for_completion);
5980 * completion_done - Test to see if a completion has any waiters
5981 * @x: completion structure
5983 * Returns: 0 if there are waiters (wait_for_completion() in progress)
5984 * 1 if there are no waiters.
5987 bool completion_done(struct completion *x)
5989 unsigned long flags;
5992 spin_lock_irqsave(&x->wait.lock, flags);
5995 spin_unlock_irqrestore(&x->wait.lock, flags);
5998 EXPORT_SYMBOL(completion_done);
6001 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
6003 unsigned long flags;
6006 init_waitqueue_entry(&wait, current);
6008 __set_current_state(state);
6010 spin_lock_irqsave(&q->lock, flags);
6011 __add_wait_queue(q, &wait);
6012 spin_unlock(&q->lock);
6013 timeout = schedule_timeout(timeout);
6014 spin_lock_irq(&q->lock);
6015 __remove_wait_queue(q, &wait);
6016 spin_unlock_irqrestore(&q->lock, flags);
6021 void __sched interruptible_sleep_on(wait_queue_head_t *q)
6023 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
6025 EXPORT_SYMBOL(interruptible_sleep_on);
6028 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
6030 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
6032 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
6034 void __sched sleep_on(wait_queue_head_t *q)
6036 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
6038 EXPORT_SYMBOL(sleep_on);
6040 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
6042 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
6044 EXPORT_SYMBOL(sleep_on_timeout);
6046 #ifdef CONFIG_RT_MUTEXES
6049 * rt_mutex_setprio - set the current priority of a task
6051 * @prio: prio value (kernel-internal form)
6053 * This function changes the 'effective' priority of a task. It does
6054 * not touch ->normal_prio like __setscheduler().
6056 * Used by the rt_mutex code to implement priority inheritance logic.
6058 void rt_mutex_setprio(struct task_struct *p, int prio)
6060 unsigned long flags;
6061 int oldprio, on_rq, running;
6063 const struct sched_class *prev_class = p->sched_class;
6065 BUG_ON(prio < 0 || prio > MAX_PRIO);
6067 rq = task_rq_lock(p, &flags);
6068 update_rq_clock(rq);
6071 on_rq = p->se.on_rq;
6072 running = task_current(rq, p);
6074 dequeue_task(rq, p, 0);
6076 p->sched_class->put_prev_task(rq, p);
6079 p->sched_class = &rt_sched_class;
6081 p->sched_class = &fair_sched_class;
6086 p->sched_class->set_curr_task(rq);
6088 enqueue_task(rq, p, 0);
6090 check_class_changed(rq, p, prev_class, oldprio, running);
6092 task_rq_unlock(rq, &flags);
6097 void set_user_nice(struct task_struct *p, long nice)
6099 int old_prio, delta, on_rq;
6100 unsigned long flags;
6103 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
6106 * We have to be careful, if called from sys_setpriority(),
6107 * the task might be in the middle of scheduling on another CPU.
6109 rq = task_rq_lock(p, &flags);
6110 update_rq_clock(rq);
6112 * The RT priorities are set via sched_setscheduler(), but we still
6113 * allow the 'normal' nice value to be set - but as expected
6114 * it wont have any effect on scheduling until the task is
6115 * SCHED_FIFO/SCHED_RR:
6117 if (task_has_rt_policy(p)) {
6118 p->static_prio = NICE_TO_PRIO(nice);
6121 on_rq = p->se.on_rq;
6123 dequeue_task(rq, p, 0);
6125 p->static_prio = NICE_TO_PRIO(nice);
6128 p->prio = effective_prio(p);
6129 delta = p->prio - old_prio;
6132 enqueue_task(rq, p, 0);
6134 * If the task increased its priority or is running and
6135 * lowered its priority, then reschedule its CPU:
6137 if (delta < 0 || (delta > 0 && task_running(rq, p)))
6138 resched_task(rq->curr);
6141 task_rq_unlock(rq, &flags);
6143 EXPORT_SYMBOL(set_user_nice);
6146 * can_nice - check if a task can reduce its nice value
6150 int can_nice(const struct task_struct *p, const int nice)
6152 /* convert nice value [19,-20] to rlimit style value [1,40] */
6153 int nice_rlim = 20 - nice;
6155 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
6156 capable(CAP_SYS_NICE));
6159 #ifdef __ARCH_WANT_SYS_NICE
6162 * sys_nice - change the priority of the current process.
6163 * @increment: priority increment
6165 * sys_setpriority is a more generic, but much slower function that
6166 * does similar things.
6168 SYSCALL_DEFINE1(nice, int, increment)
6173 * Setpriority might change our priority at the same moment.
6174 * We don't have to worry. Conceptually one call occurs first
6175 * and we have a single winner.
6177 if (increment < -40)
6182 nice = TASK_NICE(current) + increment;
6188 if (increment < 0 && !can_nice(current, nice))
6191 retval = security_task_setnice(current, nice);
6195 set_user_nice(current, nice);
6202 * task_prio - return the priority value of a given task.
6203 * @p: the task in question.
6205 * This is the priority value as seen by users in /proc.
6206 * RT tasks are offset by -200. Normal tasks are centered
6207 * around 0, value goes from -16 to +15.
6209 int task_prio(const struct task_struct *p)
6211 return p->prio - MAX_RT_PRIO;
6215 * task_nice - return the nice value of a given task.
6216 * @p: the task in question.
6218 int task_nice(const struct task_struct *p)
6220 return TASK_NICE(p);
6222 EXPORT_SYMBOL(task_nice);
6225 * idle_cpu - is a given cpu idle currently?
6226 * @cpu: the processor in question.
6228 int idle_cpu(int cpu)
6230 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
6234 * idle_task - return the idle task for a given cpu.
6235 * @cpu: the processor in question.
6237 struct task_struct *idle_task(int cpu)
6239 return cpu_rq(cpu)->idle;
6243 * find_process_by_pid - find a process with a matching PID value.
6244 * @pid: the pid in question.
6246 static struct task_struct *find_process_by_pid(pid_t pid)
6248 return pid ? find_task_by_vpid(pid) : current;
6251 /* Actually do priority change: must hold rq lock. */
6253 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
6255 BUG_ON(p->se.on_rq);
6258 p->rt_priority = prio;
6259 p->normal_prio = normal_prio(p);
6260 /* we are holding p->pi_lock already */
6261 p->prio = rt_mutex_getprio(p);
6262 if (rt_prio(p->prio))
6263 p->sched_class = &rt_sched_class;
6265 p->sched_class = &fair_sched_class;
6270 * check the target process has a UID that matches the current process's
6272 static bool check_same_owner(struct task_struct *p)
6274 const struct cred *cred = current_cred(), *pcred;
6278 pcred = __task_cred(p);
6279 match = (cred->euid == pcred->euid ||
6280 cred->euid == pcred->uid);
6285 static int __sched_setscheduler(struct task_struct *p, int policy,
6286 struct sched_param *param, bool user)
6288 int retval, oldprio, oldpolicy = -1, on_rq, running;
6289 unsigned long flags;
6290 const struct sched_class *prev_class = p->sched_class;
6294 /* may grab non-irq protected spin_locks */
6295 BUG_ON(in_interrupt());
6297 /* double check policy once rq lock held */
6299 reset_on_fork = p->sched_reset_on_fork;
6300 policy = oldpolicy = p->policy;
6302 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
6303 policy &= ~SCHED_RESET_ON_FORK;
6305 if (policy != SCHED_FIFO && policy != SCHED_RR &&
6306 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
6307 policy != SCHED_IDLE)
6312 * Valid priorities for SCHED_FIFO and SCHED_RR are
6313 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
6314 * SCHED_BATCH and SCHED_IDLE is 0.
6316 if (param->sched_priority < 0 ||
6317 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
6318 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
6320 if (rt_policy(policy) != (param->sched_priority != 0))
6324 * Allow unprivileged RT tasks to decrease priority:
6326 if (user && !capable(CAP_SYS_NICE)) {
6327 if (rt_policy(policy)) {
6328 unsigned long rlim_rtprio;
6330 if (!lock_task_sighand(p, &flags))
6332 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
6333 unlock_task_sighand(p, &flags);
6335 /* can't set/change the rt policy */
6336 if (policy != p->policy && !rlim_rtprio)
6339 /* can't increase priority */
6340 if (param->sched_priority > p->rt_priority &&
6341 param->sched_priority > rlim_rtprio)
6345 * Like positive nice levels, dont allow tasks to
6346 * move out of SCHED_IDLE either:
6348 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
6351 /* can't change other user's priorities */
6352 if (!check_same_owner(p))
6355 /* Normal users shall not reset the sched_reset_on_fork flag */
6356 if (p->sched_reset_on_fork && !reset_on_fork)
6361 #ifdef CONFIG_RT_GROUP_SCHED
6363 * Do not allow realtime tasks into groups that have no runtime
6366 if (rt_bandwidth_enabled() && rt_policy(policy) &&
6367 task_group(p)->rt_bandwidth.rt_runtime == 0)
6371 retval = security_task_setscheduler(p, policy, param);
6377 * make sure no PI-waiters arrive (or leave) while we are
6378 * changing the priority of the task:
6380 raw_spin_lock_irqsave(&p->pi_lock, flags);
6382 * To be able to change p->policy safely, the apropriate
6383 * runqueue lock must be held.
6385 rq = __task_rq_lock(p);
6386 /* recheck policy now with rq lock held */
6387 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
6388 policy = oldpolicy = -1;
6389 __task_rq_unlock(rq);
6390 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
6393 update_rq_clock(rq);
6394 on_rq = p->se.on_rq;
6395 running = task_current(rq, p);
6397 deactivate_task(rq, p, 0);
6399 p->sched_class->put_prev_task(rq, p);
6401 p->sched_reset_on_fork = reset_on_fork;
6404 __setscheduler(rq, p, policy, param->sched_priority);
6407 p->sched_class->set_curr_task(rq);
6409 activate_task(rq, p, 0);
6411 check_class_changed(rq, p, prev_class, oldprio, running);
6413 __task_rq_unlock(rq);
6414 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
6416 rt_mutex_adjust_pi(p);
6422 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
6423 * @p: the task in question.
6424 * @policy: new policy.
6425 * @param: structure containing the new RT priority.
6427 * NOTE that the task may be already dead.
6429 int sched_setscheduler(struct task_struct *p, int policy,
6430 struct sched_param *param)
6432 return __sched_setscheduler(p, policy, param, true);
6434 EXPORT_SYMBOL_GPL(sched_setscheduler);
6437 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
6438 * @p: the task in question.
6439 * @policy: new policy.
6440 * @param: structure containing the new RT priority.
6442 * Just like sched_setscheduler, only don't bother checking if the
6443 * current context has permission. For example, this is needed in
6444 * stop_machine(): we create temporary high priority worker threads,
6445 * but our caller might not have that capability.
6447 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
6448 struct sched_param *param)
6450 return __sched_setscheduler(p, policy, param, false);
6454 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
6456 struct sched_param lparam;
6457 struct task_struct *p;
6460 if (!param || pid < 0)
6462 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
6467 p = find_process_by_pid(pid);
6469 retval = sched_setscheduler(p, policy, &lparam);
6476 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
6477 * @pid: the pid in question.
6478 * @policy: new policy.
6479 * @param: structure containing the new RT priority.
6481 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
6482 struct sched_param __user *, param)
6484 /* negative values for policy are not valid */
6488 return do_sched_setscheduler(pid, policy, param);
6492 * sys_sched_setparam - set/change the RT priority of a thread
6493 * @pid: the pid in question.
6494 * @param: structure containing the new RT priority.
6496 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
6498 return do_sched_setscheduler(pid, -1, param);
6502 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
6503 * @pid: the pid in question.
6505 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
6507 struct task_struct *p;
6515 p = find_process_by_pid(pid);
6517 retval = security_task_getscheduler(p);
6520 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
6527 * sys_sched_getparam - get the RT priority of a thread
6528 * @pid: the pid in question.
6529 * @param: structure containing the RT priority.
6531 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
6533 struct sched_param lp;
6534 struct task_struct *p;
6537 if (!param || pid < 0)
6541 p = find_process_by_pid(pid);
6546 retval = security_task_getscheduler(p);
6550 lp.sched_priority = p->rt_priority;
6554 * This one might sleep, we cannot do it with a spinlock held ...
6556 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
6565 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
6567 cpumask_var_t cpus_allowed, new_mask;
6568 struct task_struct *p;
6574 p = find_process_by_pid(pid);
6581 /* Prevent p going away */
6585 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
6589 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
6591 goto out_free_cpus_allowed;
6594 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
6597 retval = security_task_setscheduler(p, 0, NULL);
6601 cpuset_cpus_allowed(p, cpus_allowed);
6602 cpumask_and(new_mask, in_mask, cpus_allowed);
6604 retval = set_cpus_allowed_ptr(p, new_mask);
6607 cpuset_cpus_allowed(p, cpus_allowed);
6608 if (!cpumask_subset(new_mask, cpus_allowed)) {
6610 * We must have raced with a concurrent cpuset
6611 * update. Just reset the cpus_allowed to the
6612 * cpuset's cpus_allowed
6614 cpumask_copy(new_mask, cpus_allowed);
6619 free_cpumask_var(new_mask);
6620 out_free_cpus_allowed:
6621 free_cpumask_var(cpus_allowed);
6628 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
6629 struct cpumask *new_mask)
6631 if (len < cpumask_size())
6632 cpumask_clear(new_mask);
6633 else if (len > cpumask_size())
6634 len = cpumask_size();
6636 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6640 * sys_sched_setaffinity - set the cpu affinity of a process
6641 * @pid: pid of the process
6642 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6643 * @user_mask_ptr: user-space pointer to the new cpu mask
6645 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6646 unsigned long __user *, user_mask_ptr)
6648 cpumask_var_t new_mask;
6651 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6654 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6656 retval = sched_setaffinity(pid, new_mask);
6657 free_cpumask_var(new_mask);
6661 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6663 struct task_struct *p;
6664 unsigned long flags;
6672 p = find_process_by_pid(pid);
6676 retval = security_task_getscheduler(p);
6680 rq = task_rq_lock(p, &flags);
6681 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
6682 task_rq_unlock(rq, &flags);
6692 * sys_sched_getaffinity - get the cpu affinity of a process
6693 * @pid: pid of the process
6694 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6695 * @user_mask_ptr: user-space pointer to hold the current cpu mask
6697 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6698 unsigned long __user *, user_mask_ptr)
6703 if (len < cpumask_size())
6706 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
6709 ret = sched_getaffinity(pid, mask);
6711 if (copy_to_user(user_mask_ptr, mask, cpumask_size()))
6714 ret = cpumask_size();
6716 free_cpumask_var(mask);
6722 * sys_sched_yield - yield the current processor to other threads.
6724 * This function yields the current CPU to other tasks. If there are no
6725 * other threads running on this CPU then this function will return.
6727 SYSCALL_DEFINE0(sched_yield)
6729 struct rq *rq = this_rq_lock();
6731 schedstat_inc(rq, yld_count);
6732 current->sched_class->yield_task(rq);
6735 * Since we are going to call schedule() anyway, there's
6736 * no need to preempt or enable interrupts:
6738 __release(rq->lock);
6739 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
6740 do_raw_spin_unlock(&rq->lock);
6741 preempt_enable_no_resched();
6748 static inline int should_resched(void)
6750 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
6753 static void __cond_resched(void)
6755 add_preempt_count(PREEMPT_ACTIVE);
6757 sub_preempt_count(PREEMPT_ACTIVE);
6760 int __sched _cond_resched(void)
6762 if (should_resched()) {
6768 EXPORT_SYMBOL(_cond_resched);
6771 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
6772 * call schedule, and on return reacquire the lock.
6774 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
6775 * operations here to prevent schedule() from being called twice (once via
6776 * spin_unlock(), once by hand).
6778 int __cond_resched_lock(spinlock_t *lock)
6780 int resched = should_resched();
6783 lockdep_assert_held(lock);
6785 if (spin_needbreak(lock) || resched) {
6796 EXPORT_SYMBOL(__cond_resched_lock);
6798 int __sched __cond_resched_softirq(void)
6800 BUG_ON(!in_softirq());
6802 if (should_resched()) {
6810 EXPORT_SYMBOL(__cond_resched_softirq);
6813 * yield - yield the current processor to other threads.
6815 * This is a shortcut for kernel-space yielding - it marks the
6816 * thread runnable and calls sys_sched_yield().
6818 void __sched yield(void)
6820 set_current_state(TASK_RUNNING);
6823 EXPORT_SYMBOL(yield);
6826 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6827 * that process accounting knows that this is a task in IO wait state.
6829 void __sched io_schedule(void)
6831 struct rq *rq = raw_rq();
6833 delayacct_blkio_start();
6834 atomic_inc(&rq->nr_iowait);
6835 current->in_iowait = 1;
6837 current->in_iowait = 0;
6838 atomic_dec(&rq->nr_iowait);
6839 delayacct_blkio_end();
6841 EXPORT_SYMBOL(io_schedule);
6843 long __sched io_schedule_timeout(long timeout)
6845 struct rq *rq = raw_rq();
6848 delayacct_blkio_start();
6849 atomic_inc(&rq->nr_iowait);
6850 current->in_iowait = 1;
6851 ret = schedule_timeout(timeout);
6852 current->in_iowait = 0;
6853 atomic_dec(&rq->nr_iowait);
6854 delayacct_blkio_end();
6859 * sys_sched_get_priority_max - return maximum RT priority.
6860 * @policy: scheduling class.
6862 * this syscall returns the maximum rt_priority that can be used
6863 * by a given scheduling class.
6865 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6872 ret = MAX_USER_RT_PRIO-1;
6884 * sys_sched_get_priority_min - return minimum RT priority.
6885 * @policy: scheduling class.
6887 * this syscall returns the minimum rt_priority that can be used
6888 * by a given scheduling class.
6890 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6908 * sys_sched_rr_get_interval - return the default timeslice of a process.
6909 * @pid: pid of the process.
6910 * @interval: userspace pointer to the timeslice value.
6912 * this syscall writes the default timeslice value of a given process
6913 * into the user-space timespec buffer. A value of '0' means infinity.
6915 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
6916 struct timespec __user *, interval)
6918 struct task_struct *p;
6919 unsigned int time_slice;
6920 unsigned long flags;
6930 p = find_process_by_pid(pid);
6934 retval = security_task_getscheduler(p);
6938 rq = task_rq_lock(p, &flags);
6939 time_slice = p->sched_class->get_rr_interval(rq, p);
6940 task_rq_unlock(rq, &flags);
6943 jiffies_to_timespec(time_slice, &t);
6944 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
6952 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
6954 void sched_show_task(struct task_struct *p)
6956 unsigned long free = 0;
6959 state = p->state ? __ffs(p->state) + 1 : 0;
6960 printk(KERN_INFO "%-13.13s %c", p->comm,
6961 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
6962 #if BITS_PER_LONG == 32
6963 if (state == TASK_RUNNING)
6964 printk(KERN_CONT " running ");
6966 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
6968 if (state == TASK_RUNNING)
6969 printk(KERN_CONT " running task ");
6971 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
6973 #ifdef CONFIG_DEBUG_STACK_USAGE
6974 free = stack_not_used(p);
6976 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
6977 task_pid_nr(p), task_pid_nr(p->real_parent),
6978 (unsigned long)task_thread_info(p)->flags);
6980 show_stack(p, NULL);
6983 void show_state_filter(unsigned long state_filter)
6985 struct task_struct *g, *p;
6987 #if BITS_PER_LONG == 32
6989 " task PC stack pid father\n");
6992 " task PC stack pid father\n");
6994 read_lock(&tasklist_lock);
6995 do_each_thread(g, p) {
6997 * reset the NMI-timeout, listing all files on a slow
6998 * console might take alot of time:
7000 touch_nmi_watchdog();
7001 if (!state_filter || (p->state & state_filter))
7003 } while_each_thread(g, p);
7005 touch_all_softlockup_watchdogs();
7007 #ifdef CONFIG_SCHED_DEBUG
7008 sysrq_sched_debug_show();
7010 read_unlock(&tasklist_lock);
7012 * Only show locks if all tasks are dumped:
7015 debug_show_all_locks();
7018 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
7020 idle->sched_class = &idle_sched_class;
7024 * init_idle - set up an idle thread for a given CPU
7025 * @idle: task in question
7026 * @cpu: cpu the idle task belongs to
7028 * NOTE: this function does not set the idle thread's NEED_RESCHED
7029 * flag, to make booting more robust.
7031 void __cpuinit init_idle(struct task_struct *idle, int cpu)
7033 struct rq *rq = cpu_rq(cpu);
7034 unsigned long flags;
7036 raw_spin_lock_irqsave(&rq->lock, flags);
7039 idle->state = TASK_RUNNING;
7040 idle->se.exec_start = sched_clock();
7042 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
7043 __set_task_cpu(idle, cpu);
7045 rq->curr = rq->idle = idle;
7046 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
7049 raw_spin_unlock_irqrestore(&rq->lock, flags);
7051 /* Set the preempt count _outside_ the spinlocks! */
7052 #if defined(CONFIG_PREEMPT)
7053 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
7055 task_thread_info(idle)->preempt_count = 0;
7058 * The idle tasks have their own, simple scheduling class:
7060 idle->sched_class = &idle_sched_class;
7061 ftrace_graph_init_task(idle);
7065 * In a system that switches off the HZ timer nohz_cpu_mask
7066 * indicates which cpus entered this state. This is used
7067 * in the rcu update to wait only for active cpus. For system
7068 * which do not switch off the HZ timer nohz_cpu_mask should
7069 * always be CPU_BITS_NONE.
7071 cpumask_var_t nohz_cpu_mask;
7074 * Increase the granularity value when there are more CPUs,
7075 * because with more CPUs the 'effective latency' as visible
7076 * to users decreases. But the relationship is not linear,
7077 * so pick a second-best guess by going with the log2 of the
7080 * This idea comes from the SD scheduler of Con Kolivas:
7082 static int get_update_sysctl_factor(void)
7084 unsigned int cpus = min_t(int, num_online_cpus(), 8);
7085 unsigned int factor;
7087 switch (sysctl_sched_tunable_scaling) {
7088 case SCHED_TUNABLESCALING_NONE:
7091 case SCHED_TUNABLESCALING_LINEAR:
7094 case SCHED_TUNABLESCALING_LOG:
7096 factor = 1 + ilog2(cpus);
7103 static void update_sysctl(void)
7105 unsigned int factor = get_update_sysctl_factor();
7107 #define SET_SYSCTL(name) \
7108 (sysctl_##name = (factor) * normalized_sysctl_##name)
7109 SET_SYSCTL(sched_min_granularity);
7110 SET_SYSCTL(sched_latency);
7111 SET_SYSCTL(sched_wakeup_granularity);
7112 SET_SYSCTL(sched_shares_ratelimit);
7116 static inline void sched_init_granularity(void)
7123 * This is how migration works:
7125 * 1) we queue a struct migration_req structure in the source CPU's
7126 * runqueue and wake up that CPU's migration thread.
7127 * 2) we down() the locked semaphore => thread blocks.
7128 * 3) migration thread wakes up (implicitly it forces the migrated
7129 * thread off the CPU)
7130 * 4) it gets the migration request and checks whether the migrated
7131 * task is still in the wrong runqueue.
7132 * 5) if it's in the wrong runqueue then the migration thread removes
7133 * it and puts it into the right queue.
7134 * 6) migration thread up()s the semaphore.
7135 * 7) we wake up and the migration is done.
7139 * Change a given task's CPU affinity. Migrate the thread to a
7140 * proper CPU and schedule it away if the CPU it's executing on
7141 * is removed from the allowed bitmask.
7143 * NOTE: the caller must have a valid reference to the task, the
7144 * task must not exit() & deallocate itself prematurely. The
7145 * call is not atomic; no spinlocks may be held.
7147 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
7149 struct migration_req req;
7150 unsigned long flags;
7155 * Since we rely on wake-ups to migrate sleeping tasks, don't change
7156 * the ->cpus_allowed mask from under waking tasks, which would be
7157 * possible when we change rq->lock in ttwu(), so synchronize against
7158 * TASK_WAKING to avoid that.
7160 * Make an exception for freshly cloned tasks, since cpuset namespaces
7161 * might move the task about, we have to validate the target in
7162 * wake_up_new_task() anyway since the cpu might have gone away.
7165 while (p->state == TASK_WAKING && !(p->flags & PF_STARTING))
7168 rq = task_rq_lock(p, &flags);
7170 if (p->state == TASK_WAKING && !(p->flags & PF_STARTING)) {
7171 task_rq_unlock(rq, &flags);
7175 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
7180 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
7181 !cpumask_equal(&p->cpus_allowed, new_mask))) {
7186 if (p->sched_class->set_cpus_allowed)
7187 p->sched_class->set_cpus_allowed(p, new_mask);
7189 cpumask_copy(&p->cpus_allowed, new_mask);
7190 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
7193 /* Can the task run on the task's current CPU? If so, we're done */
7194 if (cpumask_test_cpu(task_cpu(p), new_mask))
7197 if (migrate_task(p, cpumask_any_and(cpu_active_mask, new_mask), &req)) {
7198 /* Need help from migration thread: drop lock and wait. */
7199 struct task_struct *mt = rq->migration_thread;
7201 get_task_struct(mt);
7202 task_rq_unlock(rq, &flags);
7203 wake_up_process(rq->migration_thread);
7204 put_task_struct(mt);
7205 wait_for_completion(&req.done);
7206 tlb_migrate_finish(p->mm);
7210 task_rq_unlock(rq, &flags);
7214 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
7217 * Move (not current) task off this cpu, onto dest cpu. We're doing
7218 * this because either it can't run here any more (set_cpus_allowed()
7219 * away from this CPU, or CPU going down), or because we're
7220 * attempting to rebalance this task on exec (sched_exec).
7222 * So we race with normal scheduler movements, but that's OK, as long
7223 * as the task is no longer on this CPU.
7225 * Returns non-zero if task was successfully migrated.
7227 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
7229 struct rq *rq_dest, *rq_src;
7232 if (unlikely(!cpu_active(dest_cpu)))
7235 rq_src = cpu_rq(src_cpu);
7236 rq_dest = cpu_rq(dest_cpu);
7238 double_rq_lock(rq_src, rq_dest);
7239 /* Already moved. */
7240 if (task_cpu(p) != src_cpu)
7242 /* Affinity changed (again). */
7243 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
7247 * If we're not on a rq, the next wake-up will ensure we're
7251 deactivate_task(rq_src, p, 0);
7252 set_task_cpu(p, dest_cpu);
7253 activate_task(rq_dest, p, 0);
7254 check_preempt_curr(rq_dest, p, 0);
7259 double_rq_unlock(rq_src, rq_dest);
7263 #define RCU_MIGRATION_IDLE 0
7264 #define RCU_MIGRATION_NEED_QS 1
7265 #define RCU_MIGRATION_GOT_QS 2
7266 #define RCU_MIGRATION_MUST_SYNC 3
7269 * migration_thread - this is a highprio system thread that performs
7270 * thread migration by bumping thread off CPU then 'pushing' onto
7273 static int migration_thread(void *data)
7276 int cpu = (long)data;
7280 BUG_ON(rq->migration_thread != current);
7282 set_current_state(TASK_INTERRUPTIBLE);
7283 while (!kthread_should_stop()) {
7284 struct migration_req *req;
7285 struct list_head *head;
7287 raw_spin_lock_irq(&rq->lock);
7289 if (cpu_is_offline(cpu)) {
7290 raw_spin_unlock_irq(&rq->lock);
7294 if (rq->active_balance) {
7295 active_load_balance(rq, cpu);
7296 rq->active_balance = 0;
7299 head = &rq->migration_queue;
7301 if (list_empty(head)) {
7302 raw_spin_unlock_irq(&rq->lock);
7304 set_current_state(TASK_INTERRUPTIBLE);
7307 req = list_entry(head->next, struct migration_req, list);
7308 list_del_init(head->next);
7310 if (req->task != NULL) {
7311 raw_spin_unlock(&rq->lock);
7312 __migrate_task(req->task, cpu, req->dest_cpu);
7313 } else if (likely(cpu == (badcpu = smp_processor_id()))) {
7314 req->dest_cpu = RCU_MIGRATION_GOT_QS;
7315 raw_spin_unlock(&rq->lock);
7317 req->dest_cpu = RCU_MIGRATION_MUST_SYNC;
7318 raw_spin_unlock(&rq->lock);
7319 WARN_ONCE(1, "migration_thread() on CPU %d, expected %d\n", badcpu, cpu);
7323 complete(&req->done);
7325 __set_current_state(TASK_RUNNING);
7330 #ifdef CONFIG_HOTPLUG_CPU
7332 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
7336 local_irq_disable();
7337 ret = __migrate_task(p, src_cpu, dest_cpu);
7343 * Figure out where task on dead CPU should go, use force if necessary.
7345 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
7350 dest_cpu = select_fallback_rq(dead_cpu, p);
7352 /* It can have affinity changed while we were choosing. */
7353 if (unlikely(!__migrate_task_irq(p, dead_cpu, dest_cpu)))
7358 * While a dead CPU has no uninterruptible tasks queued at this point,
7359 * it might still have a nonzero ->nr_uninterruptible counter, because
7360 * for performance reasons the counter is not stricly tracking tasks to
7361 * their home CPUs. So we just add the counter to another CPU's counter,
7362 * to keep the global sum constant after CPU-down:
7364 static void migrate_nr_uninterruptible(struct rq *rq_src)
7366 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
7367 unsigned long flags;
7369 local_irq_save(flags);
7370 double_rq_lock(rq_src, rq_dest);
7371 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
7372 rq_src->nr_uninterruptible = 0;
7373 double_rq_unlock(rq_src, rq_dest);
7374 local_irq_restore(flags);
7377 /* Run through task list and migrate tasks from the dead cpu. */
7378 static void migrate_live_tasks(int src_cpu)
7380 struct task_struct *p, *t;
7382 read_lock(&tasklist_lock);
7384 do_each_thread(t, p) {
7388 if (task_cpu(p) == src_cpu)
7389 move_task_off_dead_cpu(src_cpu, p);
7390 } while_each_thread(t, p);
7392 read_unlock(&tasklist_lock);
7396 * Schedules idle task to be the next runnable task on current CPU.
7397 * It does so by boosting its priority to highest possible.
7398 * Used by CPU offline code.
7400 void sched_idle_next(void)
7402 int this_cpu = smp_processor_id();
7403 struct rq *rq = cpu_rq(this_cpu);
7404 struct task_struct *p = rq->idle;
7405 unsigned long flags;
7407 /* cpu has to be offline */
7408 BUG_ON(cpu_online(this_cpu));
7411 * Strictly not necessary since rest of the CPUs are stopped by now
7412 * and interrupts disabled on the current cpu.
7414 raw_spin_lock_irqsave(&rq->lock, flags);
7416 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7418 update_rq_clock(rq);
7419 activate_task(rq, p, 0);
7421 raw_spin_unlock_irqrestore(&rq->lock, flags);
7425 * Ensures that the idle task is using init_mm right before its cpu goes
7428 void idle_task_exit(void)
7430 struct mm_struct *mm = current->active_mm;
7432 BUG_ON(cpu_online(smp_processor_id()));
7435 switch_mm(mm, &init_mm, current);
7439 /* called under rq->lock with disabled interrupts */
7440 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
7442 struct rq *rq = cpu_rq(dead_cpu);
7444 /* Must be exiting, otherwise would be on tasklist. */
7445 BUG_ON(!p->exit_state);
7447 /* Cannot have done final schedule yet: would have vanished. */
7448 BUG_ON(p->state == TASK_DEAD);
7453 * Drop lock around migration; if someone else moves it,
7454 * that's OK. No task can be added to this CPU, so iteration is
7457 raw_spin_unlock_irq(&rq->lock);
7458 move_task_off_dead_cpu(dead_cpu, p);
7459 raw_spin_lock_irq(&rq->lock);
7464 /* release_task() removes task from tasklist, so we won't find dead tasks. */
7465 static void migrate_dead_tasks(unsigned int dead_cpu)
7467 struct rq *rq = cpu_rq(dead_cpu);
7468 struct task_struct *next;
7471 if (!rq->nr_running)
7473 update_rq_clock(rq);
7474 next = pick_next_task(rq);
7477 next->sched_class->put_prev_task(rq, next);
7478 migrate_dead(dead_cpu, next);
7484 * remove the tasks which were accounted by rq from calc_load_tasks.
7486 static void calc_global_load_remove(struct rq *rq)
7488 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
7489 rq->calc_load_active = 0;
7491 #endif /* CONFIG_HOTPLUG_CPU */
7493 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
7495 static struct ctl_table sd_ctl_dir[] = {
7497 .procname = "sched_domain",
7503 static struct ctl_table sd_ctl_root[] = {
7505 .procname = "kernel",
7507 .child = sd_ctl_dir,
7512 static struct ctl_table *sd_alloc_ctl_entry(int n)
7514 struct ctl_table *entry =
7515 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
7520 static void sd_free_ctl_entry(struct ctl_table **tablep)
7522 struct ctl_table *entry;
7525 * In the intermediate directories, both the child directory and
7526 * procname are dynamically allocated and could fail but the mode
7527 * will always be set. In the lowest directory the names are
7528 * static strings and all have proc handlers.
7530 for (entry = *tablep; entry->mode; entry++) {
7532 sd_free_ctl_entry(&entry->child);
7533 if (entry->proc_handler == NULL)
7534 kfree(entry->procname);
7542 set_table_entry(struct ctl_table *entry,
7543 const char *procname, void *data, int maxlen,
7544 mode_t mode, proc_handler *proc_handler)
7546 entry->procname = procname;
7548 entry->maxlen = maxlen;
7550 entry->proc_handler = proc_handler;
7553 static struct ctl_table *
7554 sd_alloc_ctl_domain_table(struct sched_domain *sd)
7556 struct ctl_table *table = sd_alloc_ctl_entry(13);
7561 set_table_entry(&table[0], "min_interval", &sd->min_interval,
7562 sizeof(long), 0644, proc_doulongvec_minmax);
7563 set_table_entry(&table[1], "max_interval", &sd->max_interval,
7564 sizeof(long), 0644, proc_doulongvec_minmax);
7565 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
7566 sizeof(int), 0644, proc_dointvec_minmax);
7567 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
7568 sizeof(int), 0644, proc_dointvec_minmax);
7569 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
7570 sizeof(int), 0644, proc_dointvec_minmax);
7571 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
7572 sizeof(int), 0644, proc_dointvec_minmax);
7573 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
7574 sizeof(int), 0644, proc_dointvec_minmax);
7575 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
7576 sizeof(int), 0644, proc_dointvec_minmax);
7577 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
7578 sizeof(int), 0644, proc_dointvec_minmax);
7579 set_table_entry(&table[9], "cache_nice_tries",
7580 &sd->cache_nice_tries,
7581 sizeof(int), 0644, proc_dointvec_minmax);
7582 set_table_entry(&table[10], "flags", &sd->flags,
7583 sizeof(int), 0644, proc_dointvec_minmax);
7584 set_table_entry(&table[11], "name", sd->name,
7585 CORENAME_MAX_SIZE, 0444, proc_dostring);
7586 /* &table[12] is terminator */
7591 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
7593 struct ctl_table *entry, *table;
7594 struct sched_domain *sd;
7595 int domain_num = 0, i;
7598 for_each_domain(cpu, sd)
7600 entry = table = sd_alloc_ctl_entry(domain_num + 1);
7605 for_each_domain(cpu, sd) {
7606 snprintf(buf, 32, "domain%d", i);
7607 entry->procname = kstrdup(buf, GFP_KERNEL);
7609 entry->child = sd_alloc_ctl_domain_table(sd);
7616 static struct ctl_table_header *sd_sysctl_header;
7617 static void register_sched_domain_sysctl(void)
7619 int i, cpu_num = num_possible_cpus();
7620 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
7623 WARN_ON(sd_ctl_dir[0].child);
7624 sd_ctl_dir[0].child = entry;
7629 for_each_possible_cpu(i) {
7630 snprintf(buf, 32, "cpu%d", i);
7631 entry->procname = kstrdup(buf, GFP_KERNEL);
7633 entry->child = sd_alloc_ctl_cpu_table(i);
7637 WARN_ON(sd_sysctl_header);
7638 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
7641 /* may be called multiple times per register */
7642 static void unregister_sched_domain_sysctl(void)
7644 if (sd_sysctl_header)
7645 unregister_sysctl_table(sd_sysctl_header);
7646 sd_sysctl_header = NULL;
7647 if (sd_ctl_dir[0].child)
7648 sd_free_ctl_entry(&sd_ctl_dir[0].child);
7651 static void register_sched_domain_sysctl(void)
7654 static void unregister_sched_domain_sysctl(void)
7659 static void set_rq_online(struct rq *rq)
7662 const struct sched_class *class;
7664 cpumask_set_cpu(rq->cpu, rq->rd->online);
7667 for_each_class(class) {
7668 if (class->rq_online)
7669 class->rq_online(rq);
7674 static void set_rq_offline(struct rq *rq)
7677 const struct sched_class *class;
7679 for_each_class(class) {
7680 if (class->rq_offline)
7681 class->rq_offline(rq);
7684 cpumask_clear_cpu(rq->cpu, rq->rd->online);
7690 * migration_call - callback that gets triggered when a CPU is added.
7691 * Here we can start up the necessary migration thread for the new CPU.
7693 static int __cpuinit
7694 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
7696 struct task_struct *p;
7697 int cpu = (long)hcpu;
7698 unsigned long flags;
7703 case CPU_UP_PREPARE:
7704 case CPU_UP_PREPARE_FROZEN:
7705 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
7708 kthread_bind(p, cpu);
7709 /* Must be high prio: stop_machine expects to yield to it. */
7710 rq = task_rq_lock(p, &flags);
7711 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7712 task_rq_unlock(rq, &flags);
7714 cpu_rq(cpu)->migration_thread = p;
7715 rq->calc_load_update = calc_load_update;
7719 case CPU_ONLINE_FROZEN:
7720 /* Strictly unnecessary, as first user will wake it. */
7721 wake_up_process(cpu_rq(cpu)->migration_thread);
7723 /* Update our root-domain */
7725 raw_spin_lock_irqsave(&rq->lock, flags);
7727 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7731 raw_spin_unlock_irqrestore(&rq->lock, flags);
7734 #ifdef CONFIG_HOTPLUG_CPU
7735 case CPU_UP_CANCELED:
7736 case CPU_UP_CANCELED_FROZEN:
7737 if (!cpu_rq(cpu)->migration_thread)
7739 /* Unbind it from offline cpu so it can run. Fall thru. */
7740 kthread_bind(cpu_rq(cpu)->migration_thread,
7741 cpumask_any(cpu_online_mask));
7742 kthread_stop(cpu_rq(cpu)->migration_thread);
7743 put_task_struct(cpu_rq(cpu)->migration_thread);
7744 cpu_rq(cpu)->migration_thread = NULL;
7748 case CPU_DEAD_FROZEN:
7749 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
7750 migrate_live_tasks(cpu);
7752 kthread_stop(rq->migration_thread);
7753 put_task_struct(rq->migration_thread);
7754 rq->migration_thread = NULL;
7755 /* Idle task back to normal (off runqueue, low prio) */
7756 raw_spin_lock_irq(&rq->lock);
7757 update_rq_clock(rq);
7758 deactivate_task(rq, rq->idle, 0);
7759 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
7760 rq->idle->sched_class = &idle_sched_class;
7761 migrate_dead_tasks(cpu);
7762 raw_spin_unlock_irq(&rq->lock);
7764 migrate_nr_uninterruptible(rq);
7765 BUG_ON(rq->nr_running != 0);
7766 calc_global_load_remove(rq);
7768 * No need to migrate the tasks: it was best-effort if
7769 * they didn't take sched_hotcpu_mutex. Just wake up
7772 raw_spin_lock_irq(&rq->lock);
7773 while (!list_empty(&rq->migration_queue)) {
7774 struct migration_req *req;
7776 req = list_entry(rq->migration_queue.next,
7777 struct migration_req, list);
7778 list_del_init(&req->list);
7779 raw_spin_unlock_irq(&rq->lock);
7780 complete(&req->done);
7781 raw_spin_lock_irq(&rq->lock);
7783 raw_spin_unlock_irq(&rq->lock);
7787 case CPU_DYING_FROZEN:
7788 /* Update our root-domain */
7790 raw_spin_lock_irqsave(&rq->lock, flags);
7792 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7795 raw_spin_unlock_irqrestore(&rq->lock, flags);
7803 * Register at high priority so that task migration (migrate_all_tasks)
7804 * happens before everything else. This has to be lower priority than
7805 * the notifier in the perf_event subsystem, though.
7807 static struct notifier_block __cpuinitdata migration_notifier = {
7808 .notifier_call = migration_call,
7812 static int __init migration_init(void)
7814 void *cpu = (void *)(long)smp_processor_id();
7817 /* Start one for the boot CPU: */
7818 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
7819 BUG_ON(err == NOTIFY_BAD);
7820 migration_call(&migration_notifier, CPU_ONLINE, cpu);
7821 register_cpu_notifier(&migration_notifier);
7825 early_initcall(migration_init);
7830 #ifdef CONFIG_SCHED_DEBUG
7832 static __read_mostly int sched_domain_debug_enabled;
7834 static int __init sched_domain_debug_setup(char *str)
7836 sched_domain_debug_enabled = 1;
7840 early_param("sched_debug", sched_domain_debug_setup);
7842 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
7843 struct cpumask *groupmask)
7845 struct sched_group *group = sd->groups;
7848 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
7849 cpumask_clear(groupmask);
7851 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
7853 if (!(sd->flags & SD_LOAD_BALANCE)) {
7854 printk("does not load-balance\n");
7856 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
7861 printk(KERN_CONT "span %s level %s\n", str, sd->name);
7863 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
7864 printk(KERN_ERR "ERROR: domain->span does not contain "
7867 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
7868 printk(KERN_ERR "ERROR: domain->groups does not contain"
7872 printk(KERN_DEBUG "%*s groups:", level + 1, "");
7876 printk(KERN_ERR "ERROR: group is NULL\n");
7880 if (!group->cpu_power) {
7881 printk(KERN_CONT "\n");
7882 printk(KERN_ERR "ERROR: domain->cpu_power not "
7887 if (!cpumask_weight(sched_group_cpus(group))) {
7888 printk(KERN_CONT "\n");
7889 printk(KERN_ERR "ERROR: empty group\n");
7893 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
7894 printk(KERN_CONT "\n");
7895 printk(KERN_ERR "ERROR: repeated CPUs\n");
7899 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
7901 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
7903 printk(KERN_CONT " %s", str);
7904 if (group->cpu_power != SCHED_LOAD_SCALE) {
7905 printk(KERN_CONT " (cpu_power = %d)",
7909 group = group->next;
7910 } while (group != sd->groups);
7911 printk(KERN_CONT "\n");
7913 if (!cpumask_equal(sched_domain_span(sd), groupmask))
7914 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
7917 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
7918 printk(KERN_ERR "ERROR: parent span is not a superset "
7919 "of domain->span\n");
7923 static void sched_domain_debug(struct sched_domain *sd, int cpu)
7925 cpumask_var_t groupmask;
7928 if (!sched_domain_debug_enabled)
7932 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
7936 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
7938 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
7939 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
7944 if (sched_domain_debug_one(sd, cpu, level, groupmask))
7951 free_cpumask_var(groupmask);
7953 #else /* !CONFIG_SCHED_DEBUG */
7954 # define sched_domain_debug(sd, cpu) do { } while (0)
7955 #endif /* CONFIG_SCHED_DEBUG */
7957 static int sd_degenerate(struct sched_domain *sd)
7959 if (cpumask_weight(sched_domain_span(sd)) == 1)
7962 /* Following flags need at least 2 groups */
7963 if (sd->flags & (SD_LOAD_BALANCE |
7964 SD_BALANCE_NEWIDLE |
7968 SD_SHARE_PKG_RESOURCES)) {
7969 if (sd->groups != sd->groups->next)
7973 /* Following flags don't use groups */
7974 if (sd->flags & (SD_WAKE_AFFINE))
7981 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
7983 unsigned long cflags = sd->flags, pflags = parent->flags;
7985 if (sd_degenerate(parent))
7988 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
7991 /* Flags needing groups don't count if only 1 group in parent */
7992 if (parent->groups == parent->groups->next) {
7993 pflags &= ~(SD_LOAD_BALANCE |
7994 SD_BALANCE_NEWIDLE |
7998 SD_SHARE_PKG_RESOURCES);
7999 if (nr_node_ids == 1)
8000 pflags &= ~SD_SERIALIZE;
8002 if (~cflags & pflags)
8008 static void free_rootdomain(struct root_domain *rd)
8010 synchronize_sched();
8012 cpupri_cleanup(&rd->cpupri);
8014 free_cpumask_var(rd->rto_mask);
8015 free_cpumask_var(rd->online);
8016 free_cpumask_var(rd->span);
8020 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
8022 struct root_domain *old_rd = NULL;
8023 unsigned long flags;
8025 raw_spin_lock_irqsave(&rq->lock, flags);
8030 if (cpumask_test_cpu(rq->cpu, old_rd->online))
8033 cpumask_clear_cpu(rq->cpu, old_rd->span);
8036 * If we dont want to free the old_rt yet then
8037 * set old_rd to NULL to skip the freeing later
8040 if (!atomic_dec_and_test(&old_rd->refcount))
8044 atomic_inc(&rd->refcount);
8047 cpumask_set_cpu(rq->cpu, rd->span);
8048 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
8051 raw_spin_unlock_irqrestore(&rq->lock, flags);
8054 free_rootdomain(old_rd);
8057 static int init_rootdomain(struct root_domain *rd, bool bootmem)
8059 gfp_t gfp = GFP_KERNEL;
8061 memset(rd, 0, sizeof(*rd));
8066 if (!alloc_cpumask_var(&rd->span, gfp))
8068 if (!alloc_cpumask_var(&rd->online, gfp))
8070 if (!alloc_cpumask_var(&rd->rto_mask, gfp))
8073 if (cpupri_init(&rd->cpupri, bootmem) != 0)
8078 free_cpumask_var(rd->rto_mask);
8080 free_cpumask_var(rd->online);
8082 free_cpumask_var(rd->span);
8087 static void init_defrootdomain(void)
8089 init_rootdomain(&def_root_domain, true);
8091 atomic_set(&def_root_domain.refcount, 1);
8094 static struct root_domain *alloc_rootdomain(void)
8096 struct root_domain *rd;
8098 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
8102 if (init_rootdomain(rd, false) != 0) {
8111 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
8112 * hold the hotplug lock.
8115 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
8117 struct rq *rq = cpu_rq(cpu);
8118 struct sched_domain *tmp;
8120 /* Remove the sched domains which do not contribute to scheduling. */
8121 for (tmp = sd; tmp; ) {
8122 struct sched_domain *parent = tmp->parent;
8126 if (sd_parent_degenerate(tmp, parent)) {
8127 tmp->parent = parent->parent;
8129 parent->parent->child = tmp;
8134 if (sd && sd_degenerate(sd)) {
8140 sched_domain_debug(sd, cpu);
8142 rq_attach_root(rq, rd);
8143 rcu_assign_pointer(rq->sd, sd);
8146 /* cpus with isolated domains */
8147 static cpumask_var_t cpu_isolated_map;
8149 /* Setup the mask of cpus configured for isolated domains */
8150 static int __init isolated_cpu_setup(char *str)
8152 alloc_bootmem_cpumask_var(&cpu_isolated_map);
8153 cpulist_parse(str, cpu_isolated_map);
8157 __setup("isolcpus=", isolated_cpu_setup);
8160 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
8161 * to a function which identifies what group(along with sched group) a CPU
8162 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
8163 * (due to the fact that we keep track of groups covered with a struct cpumask).
8165 * init_sched_build_groups will build a circular linked list of the groups
8166 * covered by the given span, and will set each group's ->cpumask correctly,
8167 * and ->cpu_power to 0.
8170 init_sched_build_groups(const struct cpumask *span,
8171 const struct cpumask *cpu_map,
8172 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
8173 struct sched_group **sg,
8174 struct cpumask *tmpmask),
8175 struct cpumask *covered, struct cpumask *tmpmask)
8177 struct sched_group *first = NULL, *last = NULL;
8180 cpumask_clear(covered);
8182 for_each_cpu(i, span) {
8183 struct sched_group *sg;
8184 int group = group_fn(i, cpu_map, &sg, tmpmask);
8187 if (cpumask_test_cpu(i, covered))
8190 cpumask_clear(sched_group_cpus(sg));
8193 for_each_cpu(j, span) {
8194 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
8197 cpumask_set_cpu(j, covered);
8198 cpumask_set_cpu(j, sched_group_cpus(sg));
8209 #define SD_NODES_PER_DOMAIN 16
8214 * find_next_best_node - find the next node to include in a sched_domain
8215 * @node: node whose sched_domain we're building
8216 * @used_nodes: nodes already in the sched_domain
8218 * Find the next node to include in a given scheduling domain. Simply
8219 * finds the closest node not already in the @used_nodes map.
8221 * Should use nodemask_t.
8223 static int find_next_best_node(int node, nodemask_t *used_nodes)
8225 int i, n, val, min_val, best_node = 0;
8229 for (i = 0; i < nr_node_ids; i++) {
8230 /* Start at @node */
8231 n = (node + i) % nr_node_ids;
8233 if (!nr_cpus_node(n))
8236 /* Skip already used nodes */
8237 if (node_isset(n, *used_nodes))
8240 /* Simple min distance search */
8241 val = node_distance(node, n);
8243 if (val < min_val) {
8249 node_set(best_node, *used_nodes);
8254 * sched_domain_node_span - get a cpumask for a node's sched_domain
8255 * @node: node whose cpumask we're constructing
8256 * @span: resulting cpumask
8258 * Given a node, construct a good cpumask for its sched_domain to span. It
8259 * should be one that prevents unnecessary balancing, but also spreads tasks
8262 static void sched_domain_node_span(int node, struct cpumask *span)
8264 nodemask_t used_nodes;
8267 cpumask_clear(span);
8268 nodes_clear(used_nodes);
8270 cpumask_or(span, span, cpumask_of_node(node));
8271 node_set(node, used_nodes);
8273 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
8274 int next_node = find_next_best_node(node, &used_nodes);
8276 cpumask_or(span, span, cpumask_of_node(next_node));
8279 #endif /* CONFIG_NUMA */
8281 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
8284 * The cpus mask in sched_group and sched_domain hangs off the end.
8286 * ( See the the comments in include/linux/sched.h:struct sched_group
8287 * and struct sched_domain. )
8289 struct static_sched_group {
8290 struct sched_group sg;
8291 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
8294 struct static_sched_domain {
8295 struct sched_domain sd;
8296 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
8302 cpumask_var_t domainspan;
8303 cpumask_var_t covered;
8304 cpumask_var_t notcovered;
8306 cpumask_var_t nodemask;
8307 cpumask_var_t this_sibling_map;
8308 cpumask_var_t this_core_map;
8309 cpumask_var_t send_covered;
8310 cpumask_var_t tmpmask;
8311 struct sched_group **sched_group_nodes;
8312 struct root_domain *rd;
8316 sa_sched_groups = 0,
8321 sa_this_sibling_map,
8323 sa_sched_group_nodes,
8333 * SMT sched-domains:
8335 #ifdef CONFIG_SCHED_SMT
8336 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
8337 static DEFINE_PER_CPU(struct static_sched_group, sched_groups);
8340 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
8341 struct sched_group **sg, struct cpumask *unused)
8344 *sg = &per_cpu(sched_groups, cpu).sg;
8347 #endif /* CONFIG_SCHED_SMT */
8350 * multi-core sched-domains:
8352 #ifdef CONFIG_SCHED_MC
8353 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
8354 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
8355 #endif /* CONFIG_SCHED_MC */
8357 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
8359 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8360 struct sched_group **sg, struct cpumask *mask)
8364 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8365 group = cpumask_first(mask);
8367 *sg = &per_cpu(sched_group_core, group).sg;
8370 #elif defined(CONFIG_SCHED_MC)
8372 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8373 struct sched_group **sg, struct cpumask *unused)
8376 *sg = &per_cpu(sched_group_core, cpu).sg;
8381 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
8382 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
8385 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
8386 struct sched_group **sg, struct cpumask *mask)
8389 #ifdef CONFIG_SCHED_MC
8390 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
8391 group = cpumask_first(mask);
8392 #elif defined(CONFIG_SCHED_SMT)
8393 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8394 group = cpumask_first(mask);
8399 *sg = &per_cpu(sched_group_phys, group).sg;
8405 * The init_sched_build_groups can't handle what we want to do with node
8406 * groups, so roll our own. Now each node has its own list of groups which
8407 * gets dynamically allocated.
8409 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
8410 static struct sched_group ***sched_group_nodes_bycpu;
8412 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
8413 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
8415 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
8416 struct sched_group **sg,
8417 struct cpumask *nodemask)
8421 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
8422 group = cpumask_first(nodemask);
8425 *sg = &per_cpu(sched_group_allnodes, group).sg;
8429 static void init_numa_sched_groups_power(struct sched_group *group_head)
8431 struct sched_group *sg = group_head;
8437 for_each_cpu(j, sched_group_cpus(sg)) {
8438 struct sched_domain *sd;
8440 sd = &per_cpu(phys_domains, j).sd;
8441 if (j != group_first_cpu(sd->groups)) {
8443 * Only add "power" once for each
8449 sg->cpu_power += sd->groups->cpu_power;
8452 } while (sg != group_head);
8455 static int build_numa_sched_groups(struct s_data *d,
8456 const struct cpumask *cpu_map, int num)
8458 struct sched_domain *sd;
8459 struct sched_group *sg, *prev;
8462 cpumask_clear(d->covered);
8463 cpumask_and(d->nodemask, cpumask_of_node(num), cpu_map);
8464 if (cpumask_empty(d->nodemask)) {
8465 d->sched_group_nodes[num] = NULL;
8469 sched_domain_node_span(num, d->domainspan);
8470 cpumask_and(d->domainspan, d->domainspan, cpu_map);
8472 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8475 printk(KERN_WARNING "Can not alloc domain group for node %d\n",
8479 d->sched_group_nodes[num] = sg;
8481 for_each_cpu(j, d->nodemask) {
8482 sd = &per_cpu(node_domains, j).sd;
8487 cpumask_copy(sched_group_cpus(sg), d->nodemask);
8489 cpumask_or(d->covered, d->covered, d->nodemask);
8492 for (j = 0; j < nr_node_ids; j++) {
8493 n = (num + j) % nr_node_ids;
8494 cpumask_complement(d->notcovered, d->covered);
8495 cpumask_and(d->tmpmask, d->notcovered, cpu_map);
8496 cpumask_and(d->tmpmask, d->tmpmask, d->domainspan);
8497 if (cpumask_empty(d->tmpmask))
8499 cpumask_and(d->tmpmask, d->tmpmask, cpumask_of_node(n));
8500 if (cpumask_empty(d->tmpmask))
8502 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8506 "Can not alloc domain group for node %d\n", j);
8510 cpumask_copy(sched_group_cpus(sg), d->tmpmask);
8511 sg->next = prev->next;
8512 cpumask_or(d->covered, d->covered, d->tmpmask);
8519 #endif /* CONFIG_NUMA */
8522 /* Free memory allocated for various sched_group structures */
8523 static void free_sched_groups(const struct cpumask *cpu_map,
8524 struct cpumask *nodemask)
8528 for_each_cpu(cpu, cpu_map) {
8529 struct sched_group **sched_group_nodes
8530 = sched_group_nodes_bycpu[cpu];
8532 if (!sched_group_nodes)
8535 for (i = 0; i < nr_node_ids; i++) {
8536 struct sched_group *oldsg, *sg = sched_group_nodes[i];
8538 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8539 if (cpumask_empty(nodemask))
8549 if (oldsg != sched_group_nodes[i])
8552 kfree(sched_group_nodes);
8553 sched_group_nodes_bycpu[cpu] = NULL;
8556 #else /* !CONFIG_NUMA */
8557 static void free_sched_groups(const struct cpumask *cpu_map,
8558 struct cpumask *nodemask)
8561 #endif /* CONFIG_NUMA */
8564 * Initialize sched groups cpu_power.
8566 * cpu_power indicates the capacity of sched group, which is used while
8567 * distributing the load between different sched groups in a sched domain.
8568 * Typically cpu_power for all the groups in a sched domain will be same unless
8569 * there are asymmetries in the topology. If there are asymmetries, group
8570 * having more cpu_power will pickup more load compared to the group having
8573 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
8575 struct sched_domain *child;
8576 struct sched_group *group;
8580 WARN_ON(!sd || !sd->groups);
8582 if (cpu != group_first_cpu(sd->groups))
8587 sd->groups->cpu_power = 0;
8590 power = SCHED_LOAD_SCALE;
8591 weight = cpumask_weight(sched_domain_span(sd));
8593 * SMT siblings share the power of a single core.
8594 * Usually multiple threads get a better yield out of
8595 * that one core than a single thread would have,
8596 * reflect that in sd->smt_gain.
8598 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
8599 power *= sd->smt_gain;
8601 power >>= SCHED_LOAD_SHIFT;
8603 sd->groups->cpu_power += power;
8608 * Add cpu_power of each child group to this groups cpu_power.
8610 group = child->groups;
8612 sd->groups->cpu_power += group->cpu_power;
8613 group = group->next;
8614 } while (group != child->groups);
8618 * Initializers for schedule domains
8619 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
8622 #ifdef CONFIG_SCHED_DEBUG
8623 # define SD_INIT_NAME(sd, type) sd->name = #type
8625 # define SD_INIT_NAME(sd, type) do { } while (0)
8628 #define SD_INIT(sd, type) sd_init_##type(sd)
8630 #define SD_INIT_FUNC(type) \
8631 static noinline void sd_init_##type(struct sched_domain *sd) \
8633 memset(sd, 0, sizeof(*sd)); \
8634 *sd = SD_##type##_INIT; \
8635 sd->level = SD_LV_##type; \
8636 SD_INIT_NAME(sd, type); \
8641 SD_INIT_FUNC(ALLNODES)
8644 #ifdef CONFIG_SCHED_SMT
8645 SD_INIT_FUNC(SIBLING)
8647 #ifdef CONFIG_SCHED_MC
8651 static int default_relax_domain_level = -1;
8653 static int __init setup_relax_domain_level(char *str)
8657 val = simple_strtoul(str, NULL, 0);
8658 if (val < SD_LV_MAX)
8659 default_relax_domain_level = val;
8663 __setup("relax_domain_level=", setup_relax_domain_level);
8665 static void set_domain_attribute(struct sched_domain *sd,
8666 struct sched_domain_attr *attr)
8670 if (!attr || attr->relax_domain_level < 0) {
8671 if (default_relax_domain_level < 0)
8674 request = default_relax_domain_level;
8676 request = attr->relax_domain_level;
8677 if (request < sd->level) {
8678 /* turn off idle balance on this domain */
8679 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
8681 /* turn on idle balance on this domain */
8682 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
8686 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
8687 const struct cpumask *cpu_map)
8690 case sa_sched_groups:
8691 free_sched_groups(cpu_map, d->tmpmask); /* fall through */
8692 d->sched_group_nodes = NULL;
8694 free_rootdomain(d->rd); /* fall through */
8696 free_cpumask_var(d->tmpmask); /* fall through */
8697 case sa_send_covered:
8698 free_cpumask_var(d->send_covered); /* fall through */
8699 case sa_this_core_map:
8700 free_cpumask_var(d->this_core_map); /* fall through */
8701 case sa_this_sibling_map:
8702 free_cpumask_var(d->this_sibling_map); /* fall through */
8704 free_cpumask_var(d->nodemask); /* fall through */
8705 case sa_sched_group_nodes:
8707 kfree(d->sched_group_nodes); /* fall through */
8709 free_cpumask_var(d->notcovered); /* fall through */
8711 free_cpumask_var(d->covered); /* fall through */
8713 free_cpumask_var(d->domainspan); /* fall through */
8720 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
8721 const struct cpumask *cpu_map)
8724 if (!alloc_cpumask_var(&d->domainspan, GFP_KERNEL))
8726 if (!alloc_cpumask_var(&d->covered, GFP_KERNEL))
8727 return sa_domainspan;
8728 if (!alloc_cpumask_var(&d->notcovered, GFP_KERNEL))
8730 /* Allocate the per-node list of sched groups */
8731 d->sched_group_nodes = kcalloc(nr_node_ids,
8732 sizeof(struct sched_group *), GFP_KERNEL);
8733 if (!d->sched_group_nodes) {
8734 printk(KERN_WARNING "Can not alloc sched group node list\n");
8735 return sa_notcovered;
8737 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = d->sched_group_nodes;
8739 if (!alloc_cpumask_var(&d->nodemask, GFP_KERNEL))
8740 return sa_sched_group_nodes;
8741 if (!alloc_cpumask_var(&d->this_sibling_map, GFP_KERNEL))
8743 if (!alloc_cpumask_var(&d->this_core_map, GFP_KERNEL))
8744 return sa_this_sibling_map;
8745 if (!alloc_cpumask_var(&d->send_covered, GFP_KERNEL))
8746 return sa_this_core_map;
8747 if (!alloc_cpumask_var(&d->tmpmask, GFP_KERNEL))
8748 return sa_send_covered;
8749 d->rd = alloc_rootdomain();
8751 printk(KERN_WARNING "Cannot alloc root domain\n");
8754 return sa_rootdomain;
8757 static struct sched_domain *__build_numa_sched_domains(struct s_data *d,
8758 const struct cpumask *cpu_map, struct sched_domain_attr *attr, int i)
8760 struct sched_domain *sd = NULL;
8762 struct sched_domain *parent;
8765 if (cpumask_weight(cpu_map) >
8766 SD_NODES_PER_DOMAIN * cpumask_weight(d->nodemask)) {
8767 sd = &per_cpu(allnodes_domains, i).sd;
8768 SD_INIT(sd, ALLNODES);
8769 set_domain_attribute(sd, attr);
8770 cpumask_copy(sched_domain_span(sd), cpu_map);
8771 cpu_to_allnodes_group(i, cpu_map, &sd->groups, d->tmpmask);
8776 sd = &per_cpu(node_domains, i).sd;
8778 set_domain_attribute(sd, attr);
8779 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
8780 sd->parent = parent;
8783 cpumask_and(sched_domain_span(sd), sched_domain_span(sd), cpu_map);
8788 static struct sched_domain *__build_cpu_sched_domain(struct s_data *d,
8789 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
8790 struct sched_domain *parent, int i)
8792 struct sched_domain *sd;
8793 sd = &per_cpu(phys_domains, i).sd;
8795 set_domain_attribute(sd, attr);
8796 cpumask_copy(sched_domain_span(sd), d->nodemask);
8797 sd->parent = parent;
8800 cpu_to_phys_group(i, cpu_map, &sd->groups, d->tmpmask);
8804 static struct sched_domain *__build_mc_sched_domain(struct s_data *d,
8805 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
8806 struct sched_domain *parent, int i)
8808 struct sched_domain *sd = parent;
8809 #ifdef CONFIG_SCHED_MC
8810 sd = &per_cpu(core_domains, i).sd;
8812 set_domain_attribute(sd, attr);
8813 cpumask_and(sched_domain_span(sd), cpu_map, cpu_coregroup_mask(i));
8814 sd->parent = parent;
8816 cpu_to_core_group(i, cpu_map, &sd->groups, d->tmpmask);
8821 static struct sched_domain *__build_smt_sched_domain(struct s_data *d,
8822 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
8823 struct sched_domain *parent, int i)
8825 struct sched_domain *sd = parent;
8826 #ifdef CONFIG_SCHED_SMT
8827 sd = &per_cpu(cpu_domains, i).sd;
8828 SD_INIT(sd, SIBLING);
8829 set_domain_attribute(sd, attr);
8830 cpumask_and(sched_domain_span(sd), cpu_map, topology_thread_cpumask(i));
8831 sd->parent = parent;
8833 cpu_to_cpu_group(i, cpu_map, &sd->groups, d->tmpmask);
8838 static void build_sched_groups(struct s_data *d, enum sched_domain_level l,
8839 const struct cpumask *cpu_map, int cpu)
8842 #ifdef CONFIG_SCHED_SMT
8843 case SD_LV_SIBLING: /* set up CPU (sibling) groups */
8844 cpumask_and(d->this_sibling_map, cpu_map,
8845 topology_thread_cpumask(cpu));
8846 if (cpu == cpumask_first(d->this_sibling_map))
8847 init_sched_build_groups(d->this_sibling_map, cpu_map,
8849 d->send_covered, d->tmpmask);
8852 #ifdef CONFIG_SCHED_MC
8853 case SD_LV_MC: /* set up multi-core groups */
8854 cpumask_and(d->this_core_map, cpu_map, cpu_coregroup_mask(cpu));
8855 if (cpu == cpumask_first(d->this_core_map))
8856 init_sched_build_groups(d->this_core_map, cpu_map,
8858 d->send_covered, d->tmpmask);
8861 case SD_LV_CPU: /* set up physical groups */
8862 cpumask_and(d->nodemask, cpumask_of_node(cpu), cpu_map);
8863 if (!cpumask_empty(d->nodemask))
8864 init_sched_build_groups(d->nodemask, cpu_map,
8866 d->send_covered, d->tmpmask);
8869 case SD_LV_ALLNODES:
8870 init_sched_build_groups(cpu_map, cpu_map, &cpu_to_allnodes_group,
8871 d->send_covered, d->tmpmask);
8880 * Build sched domains for a given set of cpus and attach the sched domains
8881 * to the individual cpus
8883 static int __build_sched_domains(const struct cpumask *cpu_map,
8884 struct sched_domain_attr *attr)
8886 enum s_alloc alloc_state = sa_none;
8888 struct sched_domain *sd;
8894 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
8895 if (alloc_state != sa_rootdomain)
8897 alloc_state = sa_sched_groups;
8900 * Set up domains for cpus specified by the cpu_map.
8902 for_each_cpu(i, cpu_map) {
8903 cpumask_and(d.nodemask, cpumask_of_node(cpu_to_node(i)),
8906 sd = __build_numa_sched_domains(&d, cpu_map, attr, i);
8907 sd = __build_cpu_sched_domain(&d, cpu_map, attr, sd, i);
8908 sd = __build_mc_sched_domain(&d, cpu_map, attr, sd, i);
8909 sd = __build_smt_sched_domain(&d, cpu_map, attr, sd, i);
8912 for_each_cpu(i, cpu_map) {
8913 build_sched_groups(&d, SD_LV_SIBLING, cpu_map, i);
8914 build_sched_groups(&d, SD_LV_MC, cpu_map, i);
8917 /* Set up physical groups */
8918 for (i = 0; i < nr_node_ids; i++)
8919 build_sched_groups(&d, SD_LV_CPU, cpu_map, i);
8922 /* Set up node groups */
8924 build_sched_groups(&d, SD_LV_ALLNODES, cpu_map, 0);
8926 for (i = 0; i < nr_node_ids; i++)
8927 if (build_numa_sched_groups(&d, cpu_map, i))
8931 /* Calculate CPU power for physical packages and nodes */
8932 #ifdef CONFIG_SCHED_SMT
8933 for_each_cpu(i, cpu_map) {
8934 sd = &per_cpu(cpu_domains, i).sd;
8935 init_sched_groups_power(i, sd);
8938 #ifdef CONFIG_SCHED_MC
8939 for_each_cpu(i, cpu_map) {
8940 sd = &per_cpu(core_domains, i).sd;
8941 init_sched_groups_power(i, sd);
8945 for_each_cpu(i, cpu_map) {
8946 sd = &per_cpu(phys_domains, i).sd;
8947 init_sched_groups_power(i, sd);
8951 for (i = 0; i < nr_node_ids; i++)
8952 init_numa_sched_groups_power(d.sched_group_nodes[i]);
8954 if (d.sd_allnodes) {
8955 struct sched_group *sg;
8957 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
8959 init_numa_sched_groups_power(sg);
8963 /* Attach the domains */
8964 for_each_cpu(i, cpu_map) {
8965 #ifdef CONFIG_SCHED_SMT
8966 sd = &per_cpu(cpu_domains, i).sd;
8967 #elif defined(CONFIG_SCHED_MC)
8968 sd = &per_cpu(core_domains, i).sd;
8970 sd = &per_cpu(phys_domains, i).sd;
8972 cpu_attach_domain(sd, d.rd, i);
8975 d.sched_group_nodes = NULL; /* don't free this we still need it */
8976 __free_domain_allocs(&d, sa_tmpmask, cpu_map);
8980 __free_domain_allocs(&d, alloc_state, cpu_map);
8984 static int build_sched_domains(const struct cpumask *cpu_map)
8986 return __build_sched_domains(cpu_map, NULL);
8989 static cpumask_var_t *doms_cur; /* current sched domains */
8990 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
8991 static struct sched_domain_attr *dattr_cur;
8992 /* attribues of custom domains in 'doms_cur' */
8995 * Special case: If a kmalloc of a doms_cur partition (array of
8996 * cpumask) fails, then fallback to a single sched domain,
8997 * as determined by the single cpumask fallback_doms.
8999 static cpumask_var_t fallback_doms;
9002 * arch_update_cpu_topology lets virtualized architectures update the
9003 * cpu core maps. It is supposed to return 1 if the topology changed
9004 * or 0 if it stayed the same.
9006 int __attribute__((weak)) arch_update_cpu_topology(void)
9011 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
9014 cpumask_var_t *doms;
9016 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
9019 for (i = 0; i < ndoms; i++) {
9020 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
9021 free_sched_domains(doms, i);
9028 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
9031 for (i = 0; i < ndoms; i++)
9032 free_cpumask_var(doms[i]);
9037 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
9038 * For now this just excludes isolated cpus, but could be used to
9039 * exclude other special cases in the future.
9041 static int arch_init_sched_domains(const struct cpumask *cpu_map)
9045 arch_update_cpu_topology();
9047 doms_cur = alloc_sched_domains(ndoms_cur);
9049 doms_cur = &fallback_doms;
9050 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
9052 err = build_sched_domains(doms_cur[0]);
9053 register_sched_domain_sysctl();
9058 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
9059 struct cpumask *tmpmask)
9061 free_sched_groups(cpu_map, tmpmask);
9065 * Detach sched domains from a group of cpus specified in cpu_map
9066 * These cpus will now be attached to the NULL domain
9068 static void detach_destroy_domains(const struct cpumask *cpu_map)
9070 /* Save because hotplug lock held. */
9071 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
9074 for_each_cpu(i, cpu_map)
9075 cpu_attach_domain(NULL, &def_root_domain, i);
9076 synchronize_sched();
9077 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
9080 /* handle null as "default" */
9081 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
9082 struct sched_domain_attr *new, int idx_new)
9084 struct sched_domain_attr tmp;
9091 return !memcmp(cur ? (cur + idx_cur) : &tmp,
9092 new ? (new + idx_new) : &tmp,
9093 sizeof(struct sched_domain_attr));
9097 * Partition sched domains as specified by the 'ndoms_new'
9098 * cpumasks in the array doms_new[] of cpumasks. This compares
9099 * doms_new[] to the current sched domain partitioning, doms_cur[].
9100 * It destroys each deleted domain and builds each new domain.
9102 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
9103 * The masks don't intersect (don't overlap.) We should setup one
9104 * sched domain for each mask. CPUs not in any of the cpumasks will
9105 * not be load balanced. If the same cpumask appears both in the
9106 * current 'doms_cur' domains and in the new 'doms_new', we can leave
9109 * The passed in 'doms_new' should be allocated using
9110 * alloc_sched_domains. This routine takes ownership of it and will
9111 * free_sched_domains it when done with it. If the caller failed the
9112 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
9113 * and partition_sched_domains() will fallback to the single partition
9114 * 'fallback_doms', it also forces the domains to be rebuilt.
9116 * If doms_new == NULL it will be replaced with cpu_online_mask.
9117 * ndoms_new == 0 is a special case for destroying existing domains,
9118 * and it will not create the default domain.
9120 * Call with hotplug lock held
9122 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
9123 struct sched_domain_attr *dattr_new)
9128 mutex_lock(&sched_domains_mutex);
9130 /* always unregister in case we don't destroy any domains */
9131 unregister_sched_domain_sysctl();
9133 /* Let architecture update cpu core mappings. */
9134 new_topology = arch_update_cpu_topology();
9136 n = doms_new ? ndoms_new : 0;
9138 /* Destroy deleted domains */
9139 for (i = 0; i < ndoms_cur; i++) {
9140 for (j = 0; j < n && !new_topology; j++) {
9141 if (cpumask_equal(doms_cur[i], doms_new[j])
9142 && dattrs_equal(dattr_cur, i, dattr_new, j))
9145 /* no match - a current sched domain not in new doms_new[] */
9146 detach_destroy_domains(doms_cur[i]);
9151 if (doms_new == NULL) {
9153 doms_new = &fallback_doms;
9154 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
9155 WARN_ON_ONCE(dattr_new);
9158 /* Build new domains */
9159 for (i = 0; i < ndoms_new; i++) {
9160 for (j = 0; j < ndoms_cur && !new_topology; j++) {
9161 if (cpumask_equal(doms_new[i], doms_cur[j])
9162 && dattrs_equal(dattr_new, i, dattr_cur, j))
9165 /* no match - add a new doms_new */
9166 __build_sched_domains(doms_new[i],
9167 dattr_new ? dattr_new + i : NULL);
9172 /* Remember the new sched domains */
9173 if (doms_cur != &fallback_doms)
9174 free_sched_domains(doms_cur, ndoms_cur);
9175 kfree(dattr_cur); /* kfree(NULL) is safe */
9176 doms_cur = doms_new;
9177 dattr_cur = dattr_new;
9178 ndoms_cur = ndoms_new;
9180 register_sched_domain_sysctl();
9182 mutex_unlock(&sched_domains_mutex);
9185 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
9186 static void arch_reinit_sched_domains(void)
9190 /* Destroy domains first to force the rebuild */
9191 partition_sched_domains(0, NULL, NULL);
9193 rebuild_sched_domains();
9197 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
9199 unsigned int level = 0;
9201 if (sscanf(buf, "%u", &level) != 1)
9205 * level is always be positive so don't check for
9206 * level < POWERSAVINGS_BALANCE_NONE which is 0
9207 * What happens on 0 or 1 byte write,
9208 * need to check for count as well?
9211 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
9215 sched_smt_power_savings = level;
9217 sched_mc_power_savings = level;
9219 arch_reinit_sched_domains();
9224 #ifdef CONFIG_SCHED_MC
9225 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
9228 return sprintf(page, "%u\n", sched_mc_power_savings);
9230 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
9231 const char *buf, size_t count)
9233 return sched_power_savings_store(buf, count, 0);
9235 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
9236 sched_mc_power_savings_show,
9237 sched_mc_power_savings_store);
9240 #ifdef CONFIG_SCHED_SMT
9241 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
9244 return sprintf(page, "%u\n", sched_smt_power_savings);
9246 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
9247 const char *buf, size_t count)
9249 return sched_power_savings_store(buf, count, 1);
9251 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
9252 sched_smt_power_savings_show,
9253 sched_smt_power_savings_store);
9256 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
9260 #ifdef CONFIG_SCHED_SMT
9262 err = sysfs_create_file(&cls->kset.kobj,
9263 &attr_sched_smt_power_savings.attr);
9265 #ifdef CONFIG_SCHED_MC
9266 if (!err && mc_capable())
9267 err = sysfs_create_file(&cls->kset.kobj,
9268 &attr_sched_mc_power_savings.attr);
9272 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
9274 #ifndef CONFIG_CPUSETS
9276 * Add online and remove offline CPUs from the scheduler domains.
9277 * When cpusets are enabled they take over this function.
9279 static int update_sched_domains(struct notifier_block *nfb,
9280 unsigned long action, void *hcpu)
9284 case CPU_ONLINE_FROZEN:
9285 case CPU_DOWN_PREPARE:
9286 case CPU_DOWN_PREPARE_FROZEN:
9287 case CPU_DOWN_FAILED:
9288 case CPU_DOWN_FAILED_FROZEN:
9289 partition_sched_domains(1, NULL, NULL);
9298 static int update_runtime(struct notifier_block *nfb,
9299 unsigned long action, void *hcpu)
9301 int cpu = (int)(long)hcpu;
9304 case CPU_DOWN_PREPARE:
9305 case CPU_DOWN_PREPARE_FROZEN:
9306 disable_runtime(cpu_rq(cpu));
9309 case CPU_DOWN_FAILED:
9310 case CPU_DOWN_FAILED_FROZEN:
9312 case CPU_ONLINE_FROZEN:
9313 enable_runtime(cpu_rq(cpu));
9321 void __init sched_init_smp(void)
9323 cpumask_var_t non_isolated_cpus;
9325 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
9326 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
9328 #if defined(CONFIG_NUMA)
9329 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
9331 BUG_ON(sched_group_nodes_bycpu == NULL);
9334 mutex_lock(&sched_domains_mutex);
9335 arch_init_sched_domains(cpu_active_mask);
9336 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
9337 if (cpumask_empty(non_isolated_cpus))
9338 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
9339 mutex_unlock(&sched_domains_mutex);
9342 #ifndef CONFIG_CPUSETS
9343 /* XXX: Theoretical race here - CPU may be hotplugged now */
9344 hotcpu_notifier(update_sched_domains, 0);
9347 /* RT runtime code needs to handle some hotplug events */
9348 hotcpu_notifier(update_runtime, 0);
9352 /* Move init over to a non-isolated CPU */
9353 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
9355 sched_init_granularity();
9356 free_cpumask_var(non_isolated_cpus);
9358 init_sched_rt_class();
9361 void __init sched_init_smp(void)
9363 sched_init_granularity();
9365 #endif /* CONFIG_SMP */
9367 const_debug unsigned int sysctl_timer_migration = 1;
9369 int in_sched_functions(unsigned long addr)
9371 return in_lock_functions(addr) ||
9372 (addr >= (unsigned long)__sched_text_start
9373 && addr < (unsigned long)__sched_text_end);
9376 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
9378 cfs_rq->tasks_timeline = RB_ROOT;
9379 INIT_LIST_HEAD(&cfs_rq->tasks);
9380 #ifdef CONFIG_FAIR_GROUP_SCHED
9383 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
9386 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
9388 struct rt_prio_array *array;
9391 array = &rt_rq->active;
9392 for (i = 0; i < MAX_RT_PRIO; i++) {
9393 INIT_LIST_HEAD(array->queue + i);
9394 __clear_bit(i, array->bitmap);
9396 /* delimiter for bitsearch: */
9397 __set_bit(MAX_RT_PRIO, array->bitmap);
9399 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
9400 rt_rq->highest_prio.curr = MAX_RT_PRIO;
9402 rt_rq->highest_prio.next = MAX_RT_PRIO;
9406 rt_rq->rt_nr_migratory = 0;
9407 rt_rq->overloaded = 0;
9408 plist_head_init_raw(&rt_rq->pushable_tasks, &rq->lock);
9412 rt_rq->rt_throttled = 0;
9413 rt_rq->rt_runtime = 0;
9414 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
9416 #ifdef CONFIG_RT_GROUP_SCHED
9417 rt_rq->rt_nr_boosted = 0;
9422 #ifdef CONFIG_FAIR_GROUP_SCHED
9423 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
9424 struct sched_entity *se, int cpu, int add,
9425 struct sched_entity *parent)
9427 struct rq *rq = cpu_rq(cpu);
9428 tg->cfs_rq[cpu] = cfs_rq;
9429 init_cfs_rq(cfs_rq, rq);
9432 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
9435 /* se could be NULL for init_task_group */
9440 se->cfs_rq = &rq->cfs;
9442 se->cfs_rq = parent->my_q;
9445 se->load.weight = tg->shares;
9446 se->load.inv_weight = 0;
9447 se->parent = parent;
9451 #ifdef CONFIG_RT_GROUP_SCHED
9452 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
9453 struct sched_rt_entity *rt_se, int cpu, int add,
9454 struct sched_rt_entity *parent)
9456 struct rq *rq = cpu_rq(cpu);
9458 tg->rt_rq[cpu] = rt_rq;
9459 init_rt_rq(rt_rq, rq);
9461 rt_rq->rt_se = rt_se;
9462 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
9464 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
9466 tg->rt_se[cpu] = rt_se;
9471 rt_se->rt_rq = &rq->rt;
9473 rt_se->rt_rq = parent->my_q;
9475 rt_se->my_q = rt_rq;
9476 rt_se->parent = parent;
9477 INIT_LIST_HEAD(&rt_se->run_list);
9481 void __init sched_init(void)
9484 unsigned long alloc_size = 0, ptr;
9486 #ifdef CONFIG_FAIR_GROUP_SCHED
9487 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9489 #ifdef CONFIG_RT_GROUP_SCHED
9490 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9492 #ifdef CONFIG_USER_SCHED
9495 #ifdef CONFIG_CPUMASK_OFFSTACK
9496 alloc_size += num_possible_cpus() * cpumask_size();
9499 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
9501 #ifdef CONFIG_FAIR_GROUP_SCHED
9502 init_task_group.se = (struct sched_entity **)ptr;
9503 ptr += nr_cpu_ids * sizeof(void **);
9505 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
9506 ptr += nr_cpu_ids * sizeof(void **);
9508 #ifdef CONFIG_USER_SCHED
9509 root_task_group.se = (struct sched_entity **)ptr;
9510 ptr += nr_cpu_ids * sizeof(void **);
9512 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
9513 ptr += nr_cpu_ids * sizeof(void **);
9514 #endif /* CONFIG_USER_SCHED */
9515 #endif /* CONFIG_FAIR_GROUP_SCHED */
9516 #ifdef CONFIG_RT_GROUP_SCHED
9517 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
9518 ptr += nr_cpu_ids * sizeof(void **);
9520 init_task_group.rt_rq = (struct rt_rq **)ptr;
9521 ptr += nr_cpu_ids * sizeof(void **);
9523 #ifdef CONFIG_USER_SCHED
9524 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
9525 ptr += nr_cpu_ids * sizeof(void **);
9527 root_task_group.rt_rq = (struct rt_rq **)ptr;
9528 ptr += nr_cpu_ids * sizeof(void **);
9529 #endif /* CONFIG_USER_SCHED */
9530 #endif /* CONFIG_RT_GROUP_SCHED */
9531 #ifdef CONFIG_CPUMASK_OFFSTACK
9532 for_each_possible_cpu(i) {
9533 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
9534 ptr += cpumask_size();
9536 #endif /* CONFIG_CPUMASK_OFFSTACK */
9540 init_defrootdomain();
9543 init_rt_bandwidth(&def_rt_bandwidth,
9544 global_rt_period(), global_rt_runtime());
9546 #ifdef CONFIG_RT_GROUP_SCHED
9547 init_rt_bandwidth(&init_task_group.rt_bandwidth,
9548 global_rt_period(), global_rt_runtime());
9549 #ifdef CONFIG_USER_SCHED
9550 init_rt_bandwidth(&root_task_group.rt_bandwidth,
9551 global_rt_period(), RUNTIME_INF);
9552 #endif /* CONFIG_USER_SCHED */
9553 #endif /* CONFIG_RT_GROUP_SCHED */
9555 #ifdef CONFIG_GROUP_SCHED
9556 list_add(&init_task_group.list, &task_groups);
9557 INIT_LIST_HEAD(&init_task_group.children);
9559 #ifdef CONFIG_USER_SCHED
9560 INIT_LIST_HEAD(&root_task_group.children);
9561 init_task_group.parent = &root_task_group;
9562 list_add(&init_task_group.siblings, &root_task_group.children);
9563 #endif /* CONFIG_USER_SCHED */
9564 #endif /* CONFIG_GROUP_SCHED */
9566 #if defined CONFIG_FAIR_GROUP_SCHED && defined CONFIG_SMP
9567 update_shares_data = __alloc_percpu(nr_cpu_ids * sizeof(unsigned long),
9568 __alignof__(unsigned long));
9570 for_each_possible_cpu(i) {
9574 raw_spin_lock_init(&rq->lock);
9576 rq->calc_load_active = 0;
9577 rq->calc_load_update = jiffies + LOAD_FREQ;
9578 init_cfs_rq(&rq->cfs, rq);
9579 init_rt_rq(&rq->rt, rq);
9580 #ifdef CONFIG_FAIR_GROUP_SCHED
9581 init_task_group.shares = init_task_group_load;
9582 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9583 #ifdef CONFIG_CGROUP_SCHED
9585 * How much cpu bandwidth does init_task_group get?
9587 * In case of task-groups formed thr' the cgroup filesystem, it
9588 * gets 100% of the cpu resources in the system. This overall
9589 * system cpu resource is divided among the tasks of
9590 * init_task_group and its child task-groups in a fair manner,
9591 * based on each entity's (task or task-group's) weight
9592 * (se->load.weight).
9594 * In other words, if init_task_group has 10 tasks of weight
9595 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9596 * then A0's share of the cpu resource is:
9598 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9600 * We achieve this by letting init_task_group's tasks sit
9601 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
9603 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
9604 #elif defined CONFIG_USER_SCHED
9605 root_task_group.shares = NICE_0_LOAD;
9606 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
9608 * In case of task-groups formed thr' the user id of tasks,
9609 * init_task_group represents tasks belonging to root user.
9610 * Hence it forms a sibling of all subsequent groups formed.
9611 * In this case, init_task_group gets only a fraction of overall
9612 * system cpu resource, based on the weight assigned to root
9613 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
9614 * by letting tasks of init_task_group sit in a separate cfs_rq
9615 * (init_tg_cfs_rq) and having one entity represent this group of
9616 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
9618 init_tg_cfs_entry(&init_task_group,
9619 &per_cpu(init_tg_cfs_rq, i),
9620 &per_cpu(init_sched_entity, i), i, 1,
9621 root_task_group.se[i]);
9624 #endif /* CONFIG_FAIR_GROUP_SCHED */
9626 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
9627 #ifdef CONFIG_RT_GROUP_SCHED
9628 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
9629 #ifdef CONFIG_CGROUP_SCHED
9630 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
9631 #elif defined CONFIG_USER_SCHED
9632 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
9633 init_tg_rt_entry(&init_task_group,
9634 &per_cpu(init_rt_rq_var, i),
9635 &per_cpu(init_sched_rt_entity, i), i, 1,
9636 root_task_group.rt_se[i]);
9640 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
9641 rq->cpu_load[j] = 0;
9645 rq->post_schedule = 0;
9646 rq->active_balance = 0;
9647 rq->next_balance = jiffies;
9651 rq->migration_thread = NULL;
9653 rq->avg_idle = 2*sysctl_sched_migration_cost;
9654 INIT_LIST_HEAD(&rq->migration_queue);
9655 rq_attach_root(rq, &def_root_domain);
9658 atomic_set(&rq->nr_iowait, 0);
9661 set_load_weight(&init_task);
9663 #ifdef CONFIG_PREEMPT_NOTIFIERS
9664 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
9668 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9671 #ifdef CONFIG_RT_MUTEXES
9672 plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock);
9676 * The boot idle thread does lazy MMU switching as well:
9678 atomic_inc(&init_mm.mm_count);
9679 enter_lazy_tlb(&init_mm, current);
9682 * Make us the idle thread. Technically, schedule() should not be
9683 * called from this thread, however somewhere below it might be,
9684 * but because we are the idle thread, we just pick up running again
9685 * when this runqueue becomes "idle".
9687 init_idle(current, smp_processor_id());
9689 calc_load_update = jiffies + LOAD_FREQ;
9692 * During early bootup we pretend to be a normal task:
9694 current->sched_class = &fair_sched_class;
9696 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
9697 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
9700 zalloc_cpumask_var(&nohz.cpu_mask, GFP_NOWAIT);
9701 alloc_cpumask_var(&nohz.ilb_grp_nohz_mask, GFP_NOWAIT);
9703 /* May be allocated at isolcpus cmdline parse time */
9704 if (cpu_isolated_map == NULL)
9705 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
9710 scheduler_running = 1;
9713 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
9714 static inline int preempt_count_equals(int preempt_offset)
9716 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
9718 return (nested == PREEMPT_INATOMIC_BASE + preempt_offset);
9721 void __might_sleep(char *file, int line, int preempt_offset)
9724 static unsigned long prev_jiffy; /* ratelimiting */
9726 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
9727 system_state != SYSTEM_RUNNING || oops_in_progress)
9729 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9731 prev_jiffy = jiffies;
9734 "BUG: sleeping function called from invalid context at %s:%d\n",
9737 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9738 in_atomic(), irqs_disabled(),
9739 current->pid, current->comm);
9741 debug_show_held_locks(current);
9742 if (irqs_disabled())
9743 print_irqtrace_events(current);
9747 EXPORT_SYMBOL(__might_sleep);
9750 #ifdef CONFIG_MAGIC_SYSRQ
9751 static void normalize_task(struct rq *rq, struct task_struct *p)
9755 update_rq_clock(rq);
9756 on_rq = p->se.on_rq;
9758 deactivate_task(rq, p, 0);
9759 __setscheduler(rq, p, SCHED_NORMAL, 0);
9761 activate_task(rq, p, 0);
9762 resched_task(rq->curr);
9766 void normalize_rt_tasks(void)
9768 struct task_struct *g, *p;
9769 unsigned long flags;
9772 read_lock_irqsave(&tasklist_lock, flags);
9773 do_each_thread(g, p) {
9775 * Only normalize user tasks:
9780 p->se.exec_start = 0;
9781 #ifdef CONFIG_SCHEDSTATS
9782 p->se.wait_start = 0;
9783 p->se.sleep_start = 0;
9784 p->se.block_start = 0;
9789 * Renice negative nice level userspace
9792 if (TASK_NICE(p) < 0 && p->mm)
9793 set_user_nice(p, 0);
9797 raw_spin_lock(&p->pi_lock);
9798 rq = __task_rq_lock(p);
9800 normalize_task(rq, p);
9802 __task_rq_unlock(rq);
9803 raw_spin_unlock(&p->pi_lock);
9804 } while_each_thread(g, p);
9806 read_unlock_irqrestore(&tasklist_lock, flags);
9809 #endif /* CONFIG_MAGIC_SYSRQ */
9813 * These functions are only useful for the IA64 MCA handling.
9815 * They can only be called when the whole system has been
9816 * stopped - every CPU needs to be quiescent, and no scheduling
9817 * activity can take place. Using them for anything else would
9818 * be a serious bug, and as a result, they aren't even visible
9819 * under any other configuration.
9823 * curr_task - return the current task for a given cpu.
9824 * @cpu: the processor in question.
9826 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9828 struct task_struct *curr_task(int cpu)
9830 return cpu_curr(cpu);
9834 * set_curr_task - set the current task for a given cpu.
9835 * @cpu: the processor in question.
9836 * @p: the task pointer to set.
9838 * Description: This function must only be used when non-maskable interrupts
9839 * are serviced on a separate stack. It allows the architecture to switch the
9840 * notion of the current task on a cpu in a non-blocking manner. This function
9841 * must be called with all CPU's synchronized, and interrupts disabled, the
9842 * and caller must save the original value of the current task (see
9843 * curr_task() above) and restore that value before reenabling interrupts and
9844 * re-starting the system.
9846 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9848 void set_curr_task(int cpu, struct task_struct *p)
9855 #ifdef CONFIG_FAIR_GROUP_SCHED
9856 static void free_fair_sched_group(struct task_group *tg)
9860 for_each_possible_cpu(i) {
9862 kfree(tg->cfs_rq[i]);
9872 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9874 struct cfs_rq *cfs_rq;
9875 struct sched_entity *se;
9879 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
9882 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
9886 tg->shares = NICE_0_LOAD;
9888 for_each_possible_cpu(i) {
9891 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
9892 GFP_KERNEL, cpu_to_node(i));
9896 se = kzalloc_node(sizeof(struct sched_entity),
9897 GFP_KERNEL, cpu_to_node(i));
9901 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
9912 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9914 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
9915 &cpu_rq(cpu)->leaf_cfs_rq_list);
9918 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9920 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
9922 #else /* !CONFG_FAIR_GROUP_SCHED */
9923 static inline void free_fair_sched_group(struct task_group *tg)
9928 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9933 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9937 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9940 #endif /* CONFIG_FAIR_GROUP_SCHED */
9942 #ifdef CONFIG_RT_GROUP_SCHED
9943 static void free_rt_sched_group(struct task_group *tg)
9947 destroy_rt_bandwidth(&tg->rt_bandwidth);
9949 for_each_possible_cpu(i) {
9951 kfree(tg->rt_rq[i]);
9953 kfree(tg->rt_se[i]);
9961 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9963 struct rt_rq *rt_rq;
9964 struct sched_rt_entity *rt_se;
9968 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
9971 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
9975 init_rt_bandwidth(&tg->rt_bandwidth,
9976 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
9978 for_each_possible_cpu(i) {
9981 rt_rq = kzalloc_node(sizeof(struct rt_rq),
9982 GFP_KERNEL, cpu_to_node(i));
9986 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
9987 GFP_KERNEL, cpu_to_node(i));
9991 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
10002 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
10004 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
10005 &cpu_rq(cpu)->leaf_rt_rq_list);
10008 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
10010 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
10012 #else /* !CONFIG_RT_GROUP_SCHED */
10013 static inline void free_rt_sched_group(struct task_group *tg)
10018 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
10023 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
10027 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
10030 #endif /* CONFIG_RT_GROUP_SCHED */
10032 #ifdef CONFIG_GROUP_SCHED
10033 static void free_sched_group(struct task_group *tg)
10035 free_fair_sched_group(tg);
10036 free_rt_sched_group(tg);
10040 /* allocate runqueue etc for a new task group */
10041 struct task_group *sched_create_group(struct task_group *parent)
10043 struct task_group *tg;
10044 unsigned long flags;
10047 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
10049 return ERR_PTR(-ENOMEM);
10051 if (!alloc_fair_sched_group(tg, parent))
10054 if (!alloc_rt_sched_group(tg, parent))
10057 spin_lock_irqsave(&task_group_lock, flags);
10058 for_each_possible_cpu(i) {
10059 register_fair_sched_group(tg, i);
10060 register_rt_sched_group(tg, i);
10062 list_add_rcu(&tg->list, &task_groups);
10064 WARN_ON(!parent); /* root should already exist */
10066 tg->parent = parent;
10067 INIT_LIST_HEAD(&tg->children);
10068 list_add_rcu(&tg->siblings, &parent->children);
10069 spin_unlock_irqrestore(&task_group_lock, flags);
10074 free_sched_group(tg);
10075 return ERR_PTR(-ENOMEM);
10078 /* rcu callback to free various structures associated with a task group */
10079 static void free_sched_group_rcu(struct rcu_head *rhp)
10081 /* now it should be safe to free those cfs_rqs */
10082 free_sched_group(container_of(rhp, struct task_group, rcu));
10085 /* Destroy runqueue etc associated with a task group */
10086 void sched_destroy_group(struct task_group *tg)
10088 unsigned long flags;
10091 spin_lock_irqsave(&task_group_lock, flags);
10092 for_each_possible_cpu(i) {
10093 unregister_fair_sched_group(tg, i);
10094 unregister_rt_sched_group(tg, i);
10096 list_del_rcu(&tg->list);
10097 list_del_rcu(&tg->siblings);
10098 spin_unlock_irqrestore(&task_group_lock, flags);
10100 /* wait for possible concurrent references to cfs_rqs complete */
10101 call_rcu(&tg->rcu, free_sched_group_rcu);
10104 /* change task's runqueue when it moves between groups.
10105 * The caller of this function should have put the task in its new group
10106 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
10107 * reflect its new group.
10109 void sched_move_task(struct task_struct *tsk)
10111 int on_rq, running;
10112 unsigned long flags;
10115 rq = task_rq_lock(tsk, &flags);
10117 update_rq_clock(rq);
10119 running = task_current(rq, tsk);
10120 on_rq = tsk->se.on_rq;
10123 dequeue_task(rq, tsk, 0);
10124 if (unlikely(running))
10125 tsk->sched_class->put_prev_task(rq, tsk);
10127 set_task_rq(tsk, task_cpu(tsk));
10129 #ifdef CONFIG_FAIR_GROUP_SCHED
10130 if (tsk->sched_class->moved_group)
10131 tsk->sched_class->moved_group(tsk, on_rq);
10134 if (unlikely(running))
10135 tsk->sched_class->set_curr_task(rq);
10137 enqueue_task(rq, tsk, 0);
10139 task_rq_unlock(rq, &flags);
10141 #endif /* CONFIG_GROUP_SCHED */
10143 #ifdef CONFIG_FAIR_GROUP_SCHED
10144 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
10146 struct cfs_rq *cfs_rq = se->cfs_rq;
10151 dequeue_entity(cfs_rq, se, 0);
10153 se->load.weight = shares;
10154 se->load.inv_weight = 0;
10157 enqueue_entity(cfs_rq, se, 0);
10160 static void set_se_shares(struct sched_entity *se, unsigned long shares)
10162 struct cfs_rq *cfs_rq = se->cfs_rq;
10163 struct rq *rq = cfs_rq->rq;
10164 unsigned long flags;
10166 raw_spin_lock_irqsave(&rq->lock, flags);
10167 __set_se_shares(se, shares);
10168 raw_spin_unlock_irqrestore(&rq->lock, flags);
10171 static DEFINE_MUTEX(shares_mutex);
10173 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
10176 unsigned long flags;
10179 * We can't change the weight of the root cgroup.
10184 if (shares < MIN_SHARES)
10185 shares = MIN_SHARES;
10186 else if (shares > MAX_SHARES)
10187 shares = MAX_SHARES;
10189 mutex_lock(&shares_mutex);
10190 if (tg->shares == shares)
10193 spin_lock_irqsave(&task_group_lock, flags);
10194 for_each_possible_cpu(i)
10195 unregister_fair_sched_group(tg, i);
10196 list_del_rcu(&tg->siblings);
10197 spin_unlock_irqrestore(&task_group_lock, flags);
10199 /* wait for any ongoing reference to this group to finish */
10200 synchronize_sched();
10203 * Now we are free to modify the group's share on each cpu
10204 * w/o tripping rebalance_share or load_balance_fair.
10206 tg->shares = shares;
10207 for_each_possible_cpu(i) {
10209 * force a rebalance
10211 cfs_rq_set_shares(tg->cfs_rq[i], 0);
10212 set_se_shares(tg->se[i], shares);
10216 * Enable load balance activity on this group, by inserting it back on
10217 * each cpu's rq->leaf_cfs_rq_list.
10219 spin_lock_irqsave(&task_group_lock, flags);
10220 for_each_possible_cpu(i)
10221 register_fair_sched_group(tg, i);
10222 list_add_rcu(&tg->siblings, &tg->parent->children);
10223 spin_unlock_irqrestore(&task_group_lock, flags);
10225 mutex_unlock(&shares_mutex);
10229 unsigned long sched_group_shares(struct task_group *tg)
10235 #ifdef CONFIG_RT_GROUP_SCHED
10237 * Ensure that the real time constraints are schedulable.
10239 static DEFINE_MUTEX(rt_constraints_mutex);
10241 static unsigned long to_ratio(u64 period, u64 runtime)
10243 if (runtime == RUNTIME_INF)
10246 return div64_u64(runtime << 20, period);
10249 /* Must be called with tasklist_lock held */
10250 static inline int tg_has_rt_tasks(struct task_group *tg)
10252 struct task_struct *g, *p;
10254 do_each_thread(g, p) {
10255 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
10257 } while_each_thread(g, p);
10262 struct rt_schedulable_data {
10263 struct task_group *tg;
10268 static int tg_schedulable(struct task_group *tg, void *data)
10270 struct rt_schedulable_data *d = data;
10271 struct task_group *child;
10272 unsigned long total, sum = 0;
10273 u64 period, runtime;
10275 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10276 runtime = tg->rt_bandwidth.rt_runtime;
10279 period = d->rt_period;
10280 runtime = d->rt_runtime;
10283 #ifdef CONFIG_USER_SCHED
10284 if (tg == &root_task_group) {
10285 period = global_rt_period();
10286 runtime = global_rt_runtime();
10291 * Cannot have more runtime than the period.
10293 if (runtime > period && runtime != RUNTIME_INF)
10297 * Ensure we don't starve existing RT tasks.
10299 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
10302 total = to_ratio(period, runtime);
10305 * Nobody can have more than the global setting allows.
10307 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
10311 * The sum of our children's runtime should not exceed our own.
10313 list_for_each_entry_rcu(child, &tg->children, siblings) {
10314 period = ktime_to_ns(child->rt_bandwidth.rt_period);
10315 runtime = child->rt_bandwidth.rt_runtime;
10317 if (child == d->tg) {
10318 period = d->rt_period;
10319 runtime = d->rt_runtime;
10322 sum += to_ratio(period, runtime);
10331 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
10333 struct rt_schedulable_data data = {
10335 .rt_period = period,
10336 .rt_runtime = runtime,
10339 return walk_tg_tree(tg_schedulable, tg_nop, &data);
10342 static int tg_set_bandwidth(struct task_group *tg,
10343 u64 rt_period, u64 rt_runtime)
10347 mutex_lock(&rt_constraints_mutex);
10348 read_lock(&tasklist_lock);
10349 err = __rt_schedulable(tg, rt_period, rt_runtime);
10353 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10354 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
10355 tg->rt_bandwidth.rt_runtime = rt_runtime;
10357 for_each_possible_cpu(i) {
10358 struct rt_rq *rt_rq = tg->rt_rq[i];
10360 raw_spin_lock(&rt_rq->rt_runtime_lock);
10361 rt_rq->rt_runtime = rt_runtime;
10362 raw_spin_unlock(&rt_rq->rt_runtime_lock);
10364 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10366 read_unlock(&tasklist_lock);
10367 mutex_unlock(&rt_constraints_mutex);
10372 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
10374 u64 rt_runtime, rt_period;
10376 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10377 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
10378 if (rt_runtime_us < 0)
10379 rt_runtime = RUNTIME_INF;
10381 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10384 long sched_group_rt_runtime(struct task_group *tg)
10388 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
10391 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
10392 do_div(rt_runtime_us, NSEC_PER_USEC);
10393 return rt_runtime_us;
10396 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
10398 u64 rt_runtime, rt_period;
10400 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
10401 rt_runtime = tg->rt_bandwidth.rt_runtime;
10403 if (rt_period == 0)
10406 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10409 long sched_group_rt_period(struct task_group *tg)
10413 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
10414 do_div(rt_period_us, NSEC_PER_USEC);
10415 return rt_period_us;
10418 static int sched_rt_global_constraints(void)
10420 u64 runtime, period;
10423 if (sysctl_sched_rt_period <= 0)
10426 runtime = global_rt_runtime();
10427 period = global_rt_period();
10430 * Sanity check on the sysctl variables.
10432 if (runtime > period && runtime != RUNTIME_INF)
10435 mutex_lock(&rt_constraints_mutex);
10436 read_lock(&tasklist_lock);
10437 ret = __rt_schedulable(NULL, 0, 0);
10438 read_unlock(&tasklist_lock);
10439 mutex_unlock(&rt_constraints_mutex);
10444 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
10446 /* Don't accept realtime tasks when there is no way for them to run */
10447 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
10453 #else /* !CONFIG_RT_GROUP_SCHED */
10454 static int sched_rt_global_constraints(void)
10456 unsigned long flags;
10459 if (sysctl_sched_rt_period <= 0)
10463 * There's always some RT tasks in the root group
10464 * -- migration, kstopmachine etc..
10466 if (sysctl_sched_rt_runtime == 0)
10469 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
10470 for_each_possible_cpu(i) {
10471 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
10473 raw_spin_lock(&rt_rq->rt_runtime_lock);
10474 rt_rq->rt_runtime = global_rt_runtime();
10475 raw_spin_unlock(&rt_rq->rt_runtime_lock);
10477 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
10481 #endif /* CONFIG_RT_GROUP_SCHED */
10483 int sched_rt_handler(struct ctl_table *table, int write,
10484 void __user *buffer, size_t *lenp,
10488 int old_period, old_runtime;
10489 static DEFINE_MUTEX(mutex);
10491 mutex_lock(&mutex);
10492 old_period = sysctl_sched_rt_period;
10493 old_runtime = sysctl_sched_rt_runtime;
10495 ret = proc_dointvec(table, write, buffer, lenp, ppos);
10497 if (!ret && write) {
10498 ret = sched_rt_global_constraints();
10500 sysctl_sched_rt_period = old_period;
10501 sysctl_sched_rt_runtime = old_runtime;
10503 def_rt_bandwidth.rt_runtime = global_rt_runtime();
10504 def_rt_bandwidth.rt_period =
10505 ns_to_ktime(global_rt_period());
10508 mutex_unlock(&mutex);
10513 #ifdef CONFIG_CGROUP_SCHED
10515 /* return corresponding task_group object of a cgroup */
10516 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
10518 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
10519 struct task_group, css);
10522 static struct cgroup_subsys_state *
10523 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
10525 struct task_group *tg, *parent;
10527 if (!cgrp->parent) {
10528 /* This is early initialization for the top cgroup */
10529 return &init_task_group.css;
10532 parent = cgroup_tg(cgrp->parent);
10533 tg = sched_create_group(parent);
10535 return ERR_PTR(-ENOMEM);
10541 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10543 struct task_group *tg = cgroup_tg(cgrp);
10545 sched_destroy_group(tg);
10549 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
10551 #ifdef CONFIG_RT_GROUP_SCHED
10552 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
10555 /* We don't support RT-tasks being in separate groups */
10556 if (tsk->sched_class != &fair_sched_class)
10563 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10564 struct task_struct *tsk, bool threadgroup)
10566 int retval = cpu_cgroup_can_attach_task(cgrp, tsk);
10570 struct task_struct *c;
10572 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
10573 retval = cpu_cgroup_can_attach_task(cgrp, c);
10585 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10586 struct cgroup *old_cont, struct task_struct *tsk,
10589 sched_move_task(tsk);
10591 struct task_struct *c;
10593 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
10594 sched_move_task(c);
10600 #ifdef CONFIG_FAIR_GROUP_SCHED
10601 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
10604 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
10607 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
10609 struct task_group *tg = cgroup_tg(cgrp);
10611 return (u64) tg->shares;
10613 #endif /* CONFIG_FAIR_GROUP_SCHED */
10615 #ifdef CONFIG_RT_GROUP_SCHED
10616 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
10619 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
10622 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
10624 return sched_group_rt_runtime(cgroup_tg(cgrp));
10627 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
10630 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
10633 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
10635 return sched_group_rt_period(cgroup_tg(cgrp));
10637 #endif /* CONFIG_RT_GROUP_SCHED */
10639 static struct cftype cpu_files[] = {
10640 #ifdef CONFIG_FAIR_GROUP_SCHED
10643 .read_u64 = cpu_shares_read_u64,
10644 .write_u64 = cpu_shares_write_u64,
10647 #ifdef CONFIG_RT_GROUP_SCHED
10649 .name = "rt_runtime_us",
10650 .read_s64 = cpu_rt_runtime_read,
10651 .write_s64 = cpu_rt_runtime_write,
10654 .name = "rt_period_us",
10655 .read_u64 = cpu_rt_period_read_uint,
10656 .write_u64 = cpu_rt_period_write_uint,
10661 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
10663 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
10666 struct cgroup_subsys cpu_cgroup_subsys = {
10668 .create = cpu_cgroup_create,
10669 .destroy = cpu_cgroup_destroy,
10670 .can_attach = cpu_cgroup_can_attach,
10671 .attach = cpu_cgroup_attach,
10672 .populate = cpu_cgroup_populate,
10673 .subsys_id = cpu_cgroup_subsys_id,
10677 #endif /* CONFIG_CGROUP_SCHED */
10679 #ifdef CONFIG_CGROUP_CPUACCT
10682 * CPU accounting code for task groups.
10684 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
10685 * (balbir@in.ibm.com).
10688 /* track cpu usage of a group of tasks and its child groups */
10690 struct cgroup_subsys_state css;
10691 /* cpuusage holds pointer to a u64-type object on every cpu */
10693 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
10694 struct cpuacct *parent;
10697 struct cgroup_subsys cpuacct_subsys;
10699 /* return cpu accounting group corresponding to this container */
10700 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
10702 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
10703 struct cpuacct, css);
10706 /* return cpu accounting group to which this task belongs */
10707 static inline struct cpuacct *task_ca(struct task_struct *tsk)
10709 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
10710 struct cpuacct, css);
10713 /* create a new cpu accounting group */
10714 static struct cgroup_subsys_state *cpuacct_create(
10715 struct cgroup_subsys *ss, struct cgroup *cgrp)
10717 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
10723 ca->cpuusage = alloc_percpu(u64);
10727 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
10728 if (percpu_counter_init(&ca->cpustat[i], 0))
10729 goto out_free_counters;
10732 ca->parent = cgroup_ca(cgrp->parent);
10738 percpu_counter_destroy(&ca->cpustat[i]);
10739 free_percpu(ca->cpuusage);
10743 return ERR_PTR(-ENOMEM);
10746 /* destroy an existing cpu accounting group */
10748 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10750 struct cpuacct *ca = cgroup_ca(cgrp);
10753 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
10754 percpu_counter_destroy(&ca->cpustat[i]);
10755 free_percpu(ca->cpuusage);
10759 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
10761 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10764 #ifndef CONFIG_64BIT
10766 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
10768 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
10770 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
10778 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
10780 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10782 #ifndef CONFIG_64BIT
10784 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
10786 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
10788 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
10794 /* return total cpu usage (in nanoseconds) of a group */
10795 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
10797 struct cpuacct *ca = cgroup_ca(cgrp);
10798 u64 totalcpuusage = 0;
10801 for_each_present_cpu(i)
10802 totalcpuusage += cpuacct_cpuusage_read(ca, i);
10804 return totalcpuusage;
10807 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
10810 struct cpuacct *ca = cgroup_ca(cgrp);
10819 for_each_present_cpu(i)
10820 cpuacct_cpuusage_write(ca, i, 0);
10826 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
10827 struct seq_file *m)
10829 struct cpuacct *ca = cgroup_ca(cgroup);
10833 for_each_present_cpu(i) {
10834 percpu = cpuacct_cpuusage_read(ca, i);
10835 seq_printf(m, "%llu ", (unsigned long long) percpu);
10837 seq_printf(m, "\n");
10841 static const char *cpuacct_stat_desc[] = {
10842 [CPUACCT_STAT_USER] = "user",
10843 [CPUACCT_STAT_SYSTEM] = "system",
10846 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
10847 struct cgroup_map_cb *cb)
10849 struct cpuacct *ca = cgroup_ca(cgrp);
10852 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
10853 s64 val = percpu_counter_read(&ca->cpustat[i]);
10854 val = cputime64_to_clock_t(val);
10855 cb->fill(cb, cpuacct_stat_desc[i], val);
10860 static struct cftype files[] = {
10863 .read_u64 = cpuusage_read,
10864 .write_u64 = cpuusage_write,
10867 .name = "usage_percpu",
10868 .read_seq_string = cpuacct_percpu_seq_read,
10872 .read_map = cpuacct_stats_show,
10876 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
10878 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
10882 * charge this task's execution time to its accounting group.
10884 * called with rq->lock held.
10886 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
10888 struct cpuacct *ca;
10891 if (unlikely(!cpuacct_subsys.active))
10894 cpu = task_cpu(tsk);
10900 for (; ca; ca = ca->parent) {
10901 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10902 *cpuusage += cputime;
10909 * Charge the system/user time to the task's accounting group.
10911 static void cpuacct_update_stats(struct task_struct *tsk,
10912 enum cpuacct_stat_index idx, cputime_t val)
10914 struct cpuacct *ca;
10916 if (unlikely(!cpuacct_subsys.active))
10923 percpu_counter_add(&ca->cpustat[idx], val);
10929 struct cgroup_subsys cpuacct_subsys = {
10931 .create = cpuacct_create,
10932 .destroy = cpuacct_destroy,
10933 .populate = cpuacct_populate,
10934 .subsys_id = cpuacct_subsys_id,
10936 #endif /* CONFIG_CGROUP_CPUACCT */
10940 int rcu_expedited_torture_stats(char *page)
10944 EXPORT_SYMBOL_GPL(rcu_expedited_torture_stats);
10946 void synchronize_sched_expedited(void)
10949 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
10951 #else /* #ifndef CONFIG_SMP */
10953 static DEFINE_PER_CPU(struct migration_req, rcu_migration_req);
10954 static DEFINE_MUTEX(rcu_sched_expedited_mutex);
10956 #define RCU_EXPEDITED_STATE_POST -2
10957 #define RCU_EXPEDITED_STATE_IDLE -1
10959 static int rcu_expedited_state = RCU_EXPEDITED_STATE_IDLE;
10961 int rcu_expedited_torture_stats(char *page)
10966 cnt += sprintf(&page[cnt], "state: %d /", rcu_expedited_state);
10967 for_each_online_cpu(cpu) {
10968 cnt += sprintf(&page[cnt], " %d:%d",
10969 cpu, per_cpu(rcu_migration_req, cpu).dest_cpu);
10971 cnt += sprintf(&page[cnt], "\n");
10974 EXPORT_SYMBOL_GPL(rcu_expedited_torture_stats);
10976 static long synchronize_sched_expedited_count;
10979 * Wait for an rcu-sched grace period to elapse, but use "big hammer"
10980 * approach to force grace period to end quickly. This consumes
10981 * significant time on all CPUs, and is thus not recommended for
10982 * any sort of common-case code.
10984 * Note that it is illegal to call this function while holding any
10985 * lock that is acquired by a CPU-hotplug notifier. Failing to
10986 * observe this restriction will result in deadlock.
10988 void synchronize_sched_expedited(void)
10991 unsigned long flags;
10992 bool need_full_sync = 0;
10994 struct migration_req *req;
10998 smp_mb(); /* ensure prior mod happens before capturing snap. */
10999 snap = ACCESS_ONCE(synchronize_sched_expedited_count) + 1;
11001 while (!mutex_trylock(&rcu_sched_expedited_mutex)) {
11003 if (trycount++ < 10)
11004 udelay(trycount * num_online_cpus());
11006 synchronize_sched();
11009 if (ACCESS_ONCE(synchronize_sched_expedited_count) - snap > 0) {
11010 smp_mb(); /* ensure test happens before caller kfree */
11015 rcu_expedited_state = RCU_EXPEDITED_STATE_POST;
11016 for_each_online_cpu(cpu) {
11018 req = &per_cpu(rcu_migration_req, cpu);
11019 init_completion(&req->done);
11021 req->dest_cpu = RCU_MIGRATION_NEED_QS;
11022 raw_spin_lock_irqsave(&rq->lock, flags);
11023 list_add(&req->list, &rq->migration_queue);
11024 raw_spin_unlock_irqrestore(&rq->lock, flags);
11025 wake_up_process(rq->migration_thread);
11027 for_each_online_cpu(cpu) {
11028 rcu_expedited_state = cpu;
11029 req = &per_cpu(rcu_migration_req, cpu);
11031 wait_for_completion(&req->done);
11032 raw_spin_lock_irqsave(&rq->lock, flags);
11033 if (unlikely(req->dest_cpu == RCU_MIGRATION_MUST_SYNC))
11034 need_full_sync = 1;
11035 req->dest_cpu = RCU_MIGRATION_IDLE;
11036 raw_spin_unlock_irqrestore(&rq->lock, flags);
11038 rcu_expedited_state = RCU_EXPEDITED_STATE_IDLE;
11039 synchronize_sched_expedited_count++;
11040 mutex_unlock(&rcu_sched_expedited_mutex);
11042 if (need_full_sync)
11043 synchronize_sched();
11045 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
11047 #endif /* #else #ifndef CONFIG_SMP */