mmc: sdhci: Check mrq->cmd in sdhci_tasklet_finish
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / sched.c
blobbee1242d92d0daeb15287b2a25cee467726ca8e3
1 /*
2 * kernel/sched.c
4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/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>
75 #include <asm/tlb.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 ],
86 * and back.
88 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
89 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
90 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
93 * 'User priority' is the nice value converted to something we
94 * can work with better when scaling various scheduler parameters,
95 * it's a [ 0 ... 39 ] range.
97 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
98 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
99 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
102 * Helpers for converting nanosecond timing to jiffy resolution
104 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
106 #define NICE_0_LOAD SCHED_LOAD_SCALE
107 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
110 * These are the 'tuning knobs' of the scheduler:
112 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
113 * Timeslices get refilled after they expire.
115 #define DEF_TIMESLICE (100 * HZ / 1000)
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))
125 return 1;
126 return 0;
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;
145 ktime_t rt_period;
146 u64 rt_runtime;
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);
158 ktime_t now;
159 int overrun;
160 int idle = 0;
162 for (;;) {
163 now = hrtimer_cb_get_time(timer);
164 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
166 if (!overrun)
167 break;
169 idle = do_sched_rt_period_timer(rt_b, overrun);
172 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
175 static
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)
195 ktime_t now;
197 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
198 return;
200 if (hrtimer_active(&rt_b->rt_period_timer))
201 return;
203 raw_spin_lock(&rt_b->rt_runtime_lock);
204 for (;;) {
205 unsigned long delta;
206 ktime_t soft, hard;
208 if (hrtimer_active(&rt_b->rt_period_timer))
209 break;
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);
228 #endif
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>
240 struct cfs_rq;
242 static LIST_HEAD(task_groups);
244 /* task group related information */
245 struct task_group {
246 #ifdef CONFIG_CGROUP_SCHED
247 struct cgroup_subsys_state css;
248 #endif
250 #ifdef CONFIG_USER_SCHED
251 uid_t uid;
252 #endif
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;
260 #endif
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;
267 #endif
269 struct rcu_head rcu;
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;
286 * Root task group.
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
314 #ifdef CONFIG_SMP
315 static int root_task_group_empty(void)
317 return list_empty(&root_task_group.children);
319 #endif
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.)
335 #define MIN_SHARES 2
336 #define MAX_SHARES (1UL << 18)
338 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
339 #endif
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
352 rcu_read_lock();
353 tg = __task_cred(p)->user->tg;
354 rcu_read_unlock();
355 #elif defined(CONFIG_CGROUP_SCHED)
356 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
357 struct task_group, css);
358 #else
359 tg = &init_task_group;
360 #endif
361 return tg;
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];
370 #endif
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];
375 #endif
378 #else
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)
383 return NULL;
386 #endif /* CONFIG_GROUP_SCHED */
388 /* CFS-related fields in a runqueue */
389 struct cfs_rq {
390 struct load_weight load;
391 unsigned long nr_running;
393 u64 exec_clock;
394 u64 min_vruntime;
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 */
424 #ifdef CONFIG_SMP
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
434 * this group.
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;
447 #endif
448 #endif
451 /* Real-Time classes' related field in a runqueue: */
452 struct rt_rq {
453 struct rt_prio_array active;
454 unsigned long rt_nr_running;
455 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
456 struct {
457 int curr; /* highest queued rt task prio */
458 #ifdef CONFIG_SMP
459 int next; /* next highest */
460 #endif
461 } highest_prio;
462 #endif
463 #ifdef CONFIG_SMP
464 unsigned long rt_nr_migratory;
465 unsigned long rt_nr_total;
466 int overloaded;
467 struct plist_head pushable_tasks;
468 #endif
469 int rt_throttled;
470 u64 rt_time;
471 u64 rt_runtime;
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;
478 struct rq *rq;
479 struct list_head leaf_rt_rq_list;
480 struct task_group *tg;
481 struct sched_rt_entity *rt_se;
482 #endif
485 #ifdef CONFIG_SMP
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
492 * object.
495 struct root_domain {
496 atomic_t refcount;
497 cpumask_var_t span;
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;
505 atomic_t rto_count;
506 #ifdef CONFIG_SMP
507 struct cpupri cpupri;
508 #endif
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;
517 #endif
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.
526 struct rq {
527 /* runqueue lock: */
528 raw_spinlock_t lock;
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];
537 #ifdef CONFIG_NO_HZ
538 unsigned char in_nohz_recently;
539 #endif
540 /* capture load from *all* tasks on this cpu: */
541 struct load_weight load;
542 unsigned long nr_load_updates;
543 u64 nr_switches;
545 struct cfs_rq cfs;
546 struct rt_rq rt;
548 #ifdef CONFIG_FAIR_GROUP_SCHED
549 /* list of leaf cfs_rq on this cpu: */
550 struct list_head leaf_cfs_rq_list;
551 #endif
552 #ifdef CONFIG_RT_GROUP_SCHED
553 struct list_head leaf_rt_rq_list;
554 #endif
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;
568 u64 clock;
570 atomic_t nr_iowait;
572 #ifdef CONFIG_SMP
573 struct root_domain *rd;
574 struct sched_domain *sd;
576 unsigned char idle_at_tick;
577 /* For active balancing */
578 int post_schedule;
579 int active_balance;
580 int push_cpu;
581 /* cpu of this runqueue: */
582 int cpu;
583 int online;
585 unsigned long avg_load_per_task;
587 struct task_struct *migration_thread;
588 struct list_head migration_queue;
590 u64 rt_avg;
591 u64 age_stamp;
592 u64 idle_stamp;
593 u64 avg_idle;
594 #endif
596 /* calc_load related fields */
597 unsigned long calc_load_update;
598 long calc_load_active;
600 #ifdef CONFIG_SCHED_HRTICK
601 #ifdef CONFIG_SMP
602 int hrtick_csd_pending;
603 struct call_single_data hrtick_csd;
604 #endif
605 struct hrtimer hrtick_timer;
606 #endif
608 #ifdef CONFIG_SCHEDSTATS
609 /* latency stats */
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;
626 /* BKL stats */
627 unsigned int bkl_count;
628 #endif
631 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
633 static inline
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)
641 #ifdef CONFIG_SMP
642 return rq->cpu;
643 #else
644 return 0;
645 #endif
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
674 #else
675 # define const_debug static const
676 #endif
679 * runqueue_is_locked
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 ,
698 enum {
699 #include "sched_features.h"
702 #undef SCHED_FEAT
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"
711 #undef SCHED_FEAT
713 #ifdef CONFIG_SCHED_DEBUG
714 #define SCHED_FEAT(name, enabled) \
715 #name ,
717 static __read_mostly char *sched_feat_names[] = {
718 #include "sched_features.h"
719 NULL
722 #undef SCHED_FEAT
724 static int sched_feat_show(struct seq_file *m, void *v)
726 int i;
728 for (i = 0; sched_feat_names[i]; i++) {
729 if (!(sysctl_sched_features & (1UL << i)))
730 seq_puts(m, "NO_");
731 seq_printf(m, "%s ", sched_feat_names[i]);
733 seq_puts(m, "\n");
735 return 0;
738 static ssize_t
739 sched_feat_write(struct file *filp, const char __user *ubuf,
740 size_t cnt, loff_t *ppos)
742 char buf[64];
743 char *cmp;
744 int neg = 0;
745 int i;
747 if (cnt > 63)
748 cnt = 63;
750 if (copy_from_user(&buf, ubuf, cnt))
751 return -EFAULT;
753 buf[cnt] = 0;
754 cmp = strstrip(buf);
756 if (strncmp(buf, "NO_", 3) == 0) {
757 neg = 1;
758 cmp += 3;
761 for (i = 0; sched_feat_names[i]; i++) {
762 if (strcmp(cmp, sched_feat_names[i]) == 0) {
763 if (neg)
764 sysctl_sched_features &= ~(1UL << i);
765 else
766 sysctl_sched_features |= (1UL << i);
767 break;
771 if (!sched_feat_names[i])
772 return -EINVAL;
774 *ppos += cnt;
776 return cnt;
779 static int sched_feat_open(struct inode *inode, struct file *filp)
781 return single_open(filp, sched_feat_show, NULL);
784 static const struct file_operations sched_feat_fops = {
785 .open = sched_feat_open,
786 .write = sched_feat_write,
787 .read = seq_read,
788 .llseek = seq_lseek,
789 .release = single_release,
792 static __init int sched_init_debug(void)
794 debugfs_create_file("sched_features", 0644, NULL, NULL,
795 &sched_feat_fops);
797 return 0;
799 late_initcall(sched_init_debug);
801 #endif
803 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
806 * Number of tasks to iterate in a single balance run.
807 * Limited because this is done with IRQs disabled.
809 const_debug unsigned int sysctl_sched_nr_migrate = 32;
812 * ratelimit for updating the group shares.
813 * default: 0.25ms
815 unsigned int sysctl_sched_shares_ratelimit = 250000;
816 unsigned int normalized_sysctl_sched_shares_ratelimit = 250000;
819 * Inject some fuzzyness into changing the per-cpu group shares
820 * this avoids remote rq-locks at the expense of fairness.
821 * default: 4
823 unsigned int sysctl_sched_shares_thresh = 4;
826 * period over which we average the RT time consumption, measured
827 * in ms.
829 * default: 1s
831 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
834 * period over which we measure -rt task cpu usage in us.
835 * default: 1s
837 unsigned int sysctl_sched_rt_period = 1000000;
839 static __read_mostly int scheduler_running;
842 * part of the period that we allow rt tasks to run in us.
843 * default: 0.95s
845 int sysctl_sched_rt_runtime = 950000;
847 static inline u64 global_rt_period(void)
849 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
852 static inline u64 global_rt_runtime(void)
854 if (sysctl_sched_rt_runtime < 0)
855 return RUNTIME_INF;
857 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
860 #ifndef prepare_arch_switch
861 # define prepare_arch_switch(next) do { } while (0)
862 #endif
863 #ifndef finish_arch_switch
864 # define finish_arch_switch(prev) do { } while (0)
865 #endif
867 static inline int task_current(struct rq *rq, struct task_struct *p)
869 return rq->curr == p;
872 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
873 static inline int task_running(struct rq *rq, struct task_struct *p)
875 return task_current(rq, p);
878 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
882 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
884 #ifdef CONFIG_DEBUG_SPINLOCK
885 /* this is a valid case when another task releases the spinlock */
886 rq->lock.owner = current;
887 #endif
889 * If we are tracking spinlock dependencies then we have to
890 * fix up the runqueue lock - which gets 'carried over' from
891 * prev into current:
893 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
895 raw_spin_unlock_irq(&rq->lock);
898 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
899 static inline int task_running(struct rq *rq, struct task_struct *p)
901 #ifdef CONFIG_SMP
902 return p->oncpu;
903 #else
904 return task_current(rq, p);
905 #endif
908 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
910 #ifdef CONFIG_SMP
912 * We can optimise this out completely for !SMP, because the
913 * SMP rebalancing from interrupt is the only thing that cares
914 * here.
916 next->oncpu = 1;
917 #endif
918 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
919 raw_spin_unlock_irq(&rq->lock);
920 #else
921 raw_spin_unlock(&rq->lock);
922 #endif
925 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
927 #ifdef CONFIG_SMP
929 * After ->oncpu is cleared, the task can be moved to a different CPU.
930 * We must ensure this doesn't happen until the switch is completely
931 * finished.
933 smp_wmb();
934 prev->oncpu = 0;
935 #endif
936 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
937 local_irq_enable();
938 #endif
940 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
943 * __task_rq_lock - lock the runqueue a given task resides on.
944 * Must be called interrupts disabled.
946 static inline struct rq *__task_rq_lock(struct task_struct *p)
947 __acquires(rq->lock)
949 for (;;) {
950 struct rq *rq = task_rq(p);
951 raw_spin_lock(&rq->lock);
952 if (likely(rq == task_rq(p)))
953 return rq;
954 raw_spin_unlock(&rq->lock);
959 * task_rq_lock - lock the runqueue a given task resides on and disable
960 * interrupts. Note the ordering: we can safely lookup the task_rq without
961 * explicitly disabling preemption.
963 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
964 __acquires(rq->lock)
966 struct rq *rq;
968 for (;;) {
969 local_irq_save(*flags);
970 rq = task_rq(p);
971 raw_spin_lock(&rq->lock);
972 if (likely(rq == task_rq(p)))
973 return rq;
974 raw_spin_unlock_irqrestore(&rq->lock, *flags);
978 void task_rq_unlock_wait(struct task_struct *p)
980 struct rq *rq = task_rq(p);
982 smp_mb(); /* spin-unlock-wait is not a full memory barrier */
983 raw_spin_unlock_wait(&rq->lock);
986 static void __task_rq_unlock(struct rq *rq)
987 __releases(rq->lock)
989 raw_spin_unlock(&rq->lock);
992 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
993 __releases(rq->lock)
995 raw_spin_unlock_irqrestore(&rq->lock, *flags);
999 * this_rq_lock - lock this runqueue and disable interrupts.
1001 static struct rq *this_rq_lock(void)
1002 __acquires(rq->lock)
1004 struct rq *rq;
1006 local_irq_disable();
1007 rq = this_rq();
1008 raw_spin_lock(&rq->lock);
1010 return rq;
1013 #ifdef CONFIG_SCHED_HRTICK
1015 * Use HR-timers to deliver accurate preemption points.
1017 * Its all a bit involved since we cannot program an hrt while holding the
1018 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1019 * reschedule event.
1021 * When we get rescheduled we reprogram the hrtick_timer outside of the
1022 * rq->lock.
1026 * Use hrtick when:
1027 * - enabled by features
1028 * - hrtimer is actually high res
1030 static inline int hrtick_enabled(struct rq *rq)
1032 if (!sched_feat(HRTICK))
1033 return 0;
1034 if (!cpu_active(cpu_of(rq)))
1035 return 0;
1036 return hrtimer_is_hres_active(&rq->hrtick_timer);
1039 static void hrtick_clear(struct rq *rq)
1041 if (hrtimer_active(&rq->hrtick_timer))
1042 hrtimer_cancel(&rq->hrtick_timer);
1046 * High-resolution timer tick.
1047 * Runs from hardirq context with interrupts disabled.
1049 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1051 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1053 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1055 raw_spin_lock(&rq->lock);
1056 update_rq_clock(rq);
1057 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1058 raw_spin_unlock(&rq->lock);
1060 return HRTIMER_NORESTART;
1063 #ifdef CONFIG_SMP
1065 * called from hardirq (IPI) context
1067 static void __hrtick_start(void *arg)
1069 struct rq *rq = arg;
1071 raw_spin_lock(&rq->lock);
1072 hrtimer_restart(&rq->hrtick_timer);
1073 rq->hrtick_csd_pending = 0;
1074 raw_spin_unlock(&rq->lock);
1078 * Called to set the hrtick timer state.
1080 * called with rq->lock held and irqs disabled
1082 static void hrtick_start(struct rq *rq, u64 delay)
1084 struct hrtimer *timer = &rq->hrtick_timer;
1085 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1087 hrtimer_set_expires(timer, time);
1089 if (rq == this_rq()) {
1090 hrtimer_restart(timer);
1091 } else if (!rq->hrtick_csd_pending) {
1092 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1093 rq->hrtick_csd_pending = 1;
1097 static int
1098 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1100 int cpu = (int)(long)hcpu;
1102 switch (action) {
1103 case CPU_UP_CANCELED:
1104 case CPU_UP_CANCELED_FROZEN:
1105 case CPU_DOWN_PREPARE:
1106 case CPU_DOWN_PREPARE_FROZEN:
1107 case CPU_DEAD:
1108 case CPU_DEAD_FROZEN:
1109 hrtick_clear(cpu_rq(cpu));
1110 return NOTIFY_OK;
1113 return NOTIFY_DONE;
1116 static __init void init_hrtick(void)
1118 hotcpu_notifier(hotplug_hrtick, 0);
1120 #else
1122 * Called to set the hrtick timer state.
1124 * called with rq->lock held and irqs disabled
1126 static void hrtick_start(struct rq *rq, u64 delay)
1128 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1129 HRTIMER_MODE_REL_PINNED, 0);
1132 static inline void init_hrtick(void)
1135 #endif /* CONFIG_SMP */
1137 static void init_rq_hrtick(struct rq *rq)
1139 #ifdef CONFIG_SMP
1140 rq->hrtick_csd_pending = 0;
1142 rq->hrtick_csd.flags = 0;
1143 rq->hrtick_csd.func = __hrtick_start;
1144 rq->hrtick_csd.info = rq;
1145 #endif
1147 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1148 rq->hrtick_timer.function = hrtick;
1150 #else /* CONFIG_SCHED_HRTICK */
1151 static inline void hrtick_clear(struct rq *rq)
1155 static inline void init_rq_hrtick(struct rq *rq)
1159 static inline void init_hrtick(void)
1162 #endif /* CONFIG_SCHED_HRTICK */
1165 * resched_task - mark a task 'to be rescheduled now'.
1167 * On UP this means the setting of the need_resched flag, on SMP it
1168 * might also involve a cross-CPU call to trigger the scheduler on
1169 * the target CPU.
1171 #ifdef CONFIG_SMP
1173 #ifndef tsk_is_polling
1174 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1175 #endif
1177 static void resched_task(struct task_struct *p)
1179 int cpu;
1181 assert_raw_spin_locked(&task_rq(p)->lock);
1183 if (test_tsk_need_resched(p))
1184 return;
1186 set_tsk_need_resched(p);
1188 cpu = task_cpu(p);
1189 if (cpu == smp_processor_id())
1190 return;
1192 /* NEED_RESCHED must be visible before we test polling */
1193 smp_mb();
1194 if (!tsk_is_polling(p))
1195 smp_send_reschedule(cpu);
1198 static void resched_cpu(int cpu)
1200 struct rq *rq = cpu_rq(cpu);
1201 unsigned long flags;
1203 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1204 return;
1205 resched_task(cpu_curr(cpu));
1206 raw_spin_unlock_irqrestore(&rq->lock, flags);
1209 #ifdef CONFIG_NO_HZ
1211 * When add_timer_on() enqueues a timer into the timer wheel of an
1212 * idle CPU then this timer might expire before the next timer event
1213 * which is scheduled to wake up that CPU. In case of a completely
1214 * idle system the next event might even be infinite time into the
1215 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1216 * leaves the inner idle loop so the newly added timer is taken into
1217 * account when the CPU goes back to idle and evaluates the timer
1218 * wheel for the next timer event.
1220 void wake_up_idle_cpu(int cpu)
1222 struct rq *rq = cpu_rq(cpu);
1224 if (cpu == smp_processor_id())
1225 return;
1228 * This is safe, as this function is called with the timer
1229 * wheel base lock of (cpu) held. When the CPU is on the way
1230 * to idle and has not yet set rq->curr to idle then it will
1231 * be serialized on the timer wheel base lock and take the new
1232 * timer into account automatically.
1234 if (rq->curr != rq->idle)
1235 return;
1238 * We can set TIF_RESCHED on the idle task of the other CPU
1239 * lockless. The worst case is that the other CPU runs the
1240 * idle task through an additional NOOP schedule()
1242 set_tsk_need_resched(rq->idle);
1244 /* NEED_RESCHED must be visible before we test polling */
1245 smp_mb();
1246 if (!tsk_is_polling(rq->idle))
1247 smp_send_reschedule(cpu);
1249 #endif /* CONFIG_NO_HZ */
1251 static u64 sched_avg_period(void)
1253 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1256 static void sched_avg_update(struct rq *rq)
1258 s64 period = sched_avg_period();
1260 while ((s64)(rq->clock - rq->age_stamp) > period) {
1262 * Inline assembly required to prevent the compiler
1263 * optimising this loop into a divmod call.
1264 * See __iter_div_u64_rem() for another example of this.
1266 asm("" : "+rm" (rq->age_stamp));
1267 rq->age_stamp += period;
1268 rq->rt_avg /= 2;
1272 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1274 rq->rt_avg += rt_delta;
1275 sched_avg_update(rq);
1278 #else /* !CONFIG_SMP */
1279 static void resched_task(struct task_struct *p)
1281 assert_raw_spin_locked(&task_rq(p)->lock);
1282 set_tsk_need_resched(p);
1285 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1288 #endif /* CONFIG_SMP */
1290 #if BITS_PER_LONG == 32
1291 # define WMULT_CONST (~0UL)
1292 #else
1293 # define WMULT_CONST (1UL << 32)
1294 #endif
1296 #define WMULT_SHIFT 32
1299 * Shift right and round:
1301 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1304 * delta *= weight / lw
1306 static unsigned long
1307 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1308 struct load_weight *lw)
1310 u64 tmp;
1312 if (!lw->inv_weight) {
1313 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1314 lw->inv_weight = 1;
1315 else
1316 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1317 / (lw->weight+1);
1320 tmp = (u64)delta_exec * weight;
1322 * Check whether we'd overflow the 64-bit multiplication:
1324 if (unlikely(tmp > WMULT_CONST))
1325 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1326 WMULT_SHIFT/2);
1327 else
1328 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1330 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1333 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1335 lw->weight += inc;
1336 lw->inv_weight = 0;
1339 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1341 lw->weight -= dec;
1342 lw->inv_weight = 0;
1346 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1347 * of tasks with abnormal "nice" values across CPUs the contribution that
1348 * each task makes to its run queue's load is weighted according to its
1349 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1350 * scaled version of the new time slice allocation that they receive on time
1351 * slice expiry etc.
1354 #define WEIGHT_IDLEPRIO 3
1355 #define WMULT_IDLEPRIO 1431655765
1358 * Nice levels are multiplicative, with a gentle 10% change for every
1359 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1360 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1361 * that remained on nice 0.
1363 * The "10% effect" is relative and cumulative: from _any_ nice level,
1364 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1365 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1366 * If a task goes up by ~10% and another task goes down by ~10% then
1367 * the relative distance between them is ~25%.)
1369 static const int prio_to_weight[40] = {
1370 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1371 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1372 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1373 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1374 /* 0 */ 1024, 820, 655, 526, 423,
1375 /* 5 */ 335, 272, 215, 172, 137,
1376 /* 10 */ 110, 87, 70, 56, 45,
1377 /* 15 */ 36, 29, 23, 18, 15,
1381 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1383 * In cases where the weight does not change often, we can use the
1384 * precalculated inverse to speed up arithmetics by turning divisions
1385 * into multiplications:
1387 static const u32 prio_to_wmult[40] = {
1388 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1389 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1390 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1391 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1392 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1393 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1394 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1395 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1398 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1401 * runqueue iterator, to support SMP load-balancing between different
1402 * scheduling classes, without having to expose their internal data
1403 * structures to the load-balancing proper:
1405 struct rq_iterator {
1406 void *arg;
1407 struct task_struct *(*start)(void *);
1408 struct task_struct *(*next)(void *);
1411 #ifdef CONFIG_SMP
1412 static unsigned long
1413 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1414 unsigned long max_load_move, struct sched_domain *sd,
1415 enum cpu_idle_type idle, int *all_pinned,
1416 int *this_best_prio, struct rq_iterator *iterator);
1418 static int
1419 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1420 struct sched_domain *sd, enum cpu_idle_type idle,
1421 struct rq_iterator *iterator);
1422 #endif
1424 /* Time spent by the tasks of the cpu accounting group executing in ... */
1425 enum cpuacct_stat_index {
1426 CPUACCT_STAT_USER, /* ... user mode */
1427 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1429 CPUACCT_STAT_NSTATS,
1432 #ifdef CONFIG_CGROUP_CPUACCT
1433 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1434 static void cpuacct_update_stats(struct task_struct *tsk,
1435 enum cpuacct_stat_index idx, cputime_t val);
1436 #else
1437 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1438 static inline void cpuacct_update_stats(struct task_struct *tsk,
1439 enum cpuacct_stat_index idx, cputime_t val) {}
1440 #endif
1442 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1444 update_load_add(&rq->load, load);
1447 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1449 update_load_sub(&rq->load, load);
1452 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1453 typedef int (*tg_visitor)(struct task_group *, void *);
1456 * Iterate the full tree, calling @down when first entering a node and @up when
1457 * leaving it for the final time.
1459 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1461 struct task_group *parent, *child;
1462 int ret;
1464 rcu_read_lock();
1465 parent = &root_task_group;
1466 down:
1467 ret = (*down)(parent, data);
1468 if (ret)
1469 goto out_unlock;
1470 list_for_each_entry_rcu(child, &parent->children, siblings) {
1471 parent = child;
1472 goto down;
1475 continue;
1477 ret = (*up)(parent, data);
1478 if (ret)
1479 goto out_unlock;
1481 child = parent;
1482 parent = parent->parent;
1483 if (parent)
1484 goto up;
1485 out_unlock:
1486 rcu_read_unlock();
1488 return ret;
1491 static int tg_nop(struct task_group *tg, void *data)
1493 return 0;
1495 #endif
1497 #ifdef CONFIG_SMP
1498 /* Used instead of source_load when we know the type == 0 */
1499 static unsigned long weighted_cpuload(const int cpu)
1501 return cpu_rq(cpu)->load.weight;
1505 * Return a low guess at the load of a migration-source cpu weighted
1506 * according to the scheduling class and "nice" value.
1508 * We want to under-estimate the load of migration sources, to
1509 * balance conservatively.
1511 static unsigned long source_load(int cpu, int type)
1513 struct rq *rq = cpu_rq(cpu);
1514 unsigned long total = weighted_cpuload(cpu);
1516 if (type == 0 || !sched_feat(LB_BIAS))
1517 return total;
1519 return min(rq->cpu_load[type-1], total);
1523 * Return a high guess at the load of a migration-target cpu weighted
1524 * according to the scheduling class and "nice" value.
1526 static unsigned long target_load(int cpu, int type)
1528 struct rq *rq = cpu_rq(cpu);
1529 unsigned long total = weighted_cpuload(cpu);
1531 if (type == 0 || !sched_feat(LB_BIAS))
1532 return total;
1534 return max(rq->cpu_load[type-1], total);
1537 static struct sched_group *group_of(int cpu)
1539 struct sched_domain *sd = rcu_dereference(cpu_rq(cpu)->sd);
1541 if (!sd)
1542 return NULL;
1544 return sd->groups;
1547 static unsigned long power_of(int cpu)
1549 struct sched_group *group = group_of(cpu);
1551 if (!group)
1552 return SCHED_LOAD_SCALE;
1554 return group->cpu_power;
1557 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1559 static unsigned long cpu_avg_load_per_task(int cpu)
1561 struct rq *rq = cpu_rq(cpu);
1562 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1564 if (nr_running)
1565 rq->avg_load_per_task = rq->load.weight / nr_running;
1566 else
1567 rq->avg_load_per_task = 0;
1569 return rq->avg_load_per_task;
1572 #ifdef CONFIG_FAIR_GROUP_SCHED
1574 static __read_mostly unsigned long *update_shares_data;
1576 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1579 * Calculate and set the cpu's group shares.
1581 static void update_group_shares_cpu(struct task_group *tg, int cpu,
1582 unsigned long sd_shares,
1583 unsigned long sd_rq_weight,
1584 unsigned long *usd_rq_weight)
1586 unsigned long shares, rq_weight;
1587 int boost = 0;
1589 rq_weight = usd_rq_weight[cpu];
1590 if (!rq_weight) {
1591 boost = 1;
1592 rq_weight = NICE_0_LOAD;
1596 * \Sum_j shares_j * rq_weight_i
1597 * shares_i = -----------------------------
1598 * \Sum_j rq_weight_j
1600 shares = (sd_shares * rq_weight) / sd_rq_weight;
1601 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1603 if (abs(shares - tg->se[cpu]->load.weight) >
1604 sysctl_sched_shares_thresh) {
1605 struct rq *rq = cpu_rq(cpu);
1606 unsigned long flags;
1608 raw_spin_lock_irqsave(&rq->lock, flags);
1609 tg->cfs_rq[cpu]->rq_weight = boost ? 0 : rq_weight;
1610 tg->cfs_rq[cpu]->shares = boost ? 0 : shares;
1611 __set_se_shares(tg->se[cpu], shares);
1612 raw_spin_unlock_irqrestore(&rq->lock, flags);
1617 * Re-compute the task group their per cpu shares over the given domain.
1618 * This needs to be done in a bottom-up fashion because the rq weight of a
1619 * parent group depends on the shares of its child groups.
1621 static int tg_shares_up(struct task_group *tg, void *data)
1623 unsigned long weight, rq_weight = 0, sum_weight = 0, shares = 0;
1624 unsigned long *usd_rq_weight;
1625 struct sched_domain *sd = data;
1626 unsigned long flags;
1627 int i;
1629 if (!tg->se[0])
1630 return 0;
1632 local_irq_save(flags);
1633 usd_rq_weight = per_cpu_ptr(update_shares_data, smp_processor_id());
1635 for_each_cpu(i, sched_domain_span(sd)) {
1636 weight = tg->cfs_rq[i]->load.weight;
1637 usd_rq_weight[i] = weight;
1639 rq_weight += weight;
1641 * If there are currently no tasks on the cpu pretend there
1642 * is one of average load so that when a new task gets to
1643 * run here it will not get delayed by group starvation.
1645 if (!weight)
1646 weight = NICE_0_LOAD;
1648 sum_weight += weight;
1649 shares += tg->cfs_rq[i]->shares;
1652 if (!rq_weight)
1653 rq_weight = sum_weight;
1655 if ((!shares && rq_weight) || shares > tg->shares)
1656 shares = tg->shares;
1658 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1659 shares = tg->shares;
1661 for_each_cpu(i, sched_domain_span(sd))
1662 update_group_shares_cpu(tg, i, shares, rq_weight, usd_rq_weight);
1664 local_irq_restore(flags);
1666 return 0;
1670 * Compute the cpu's hierarchical load factor for each task group.
1671 * This needs to be done in a top-down fashion because the load of a child
1672 * group is a fraction of its parents load.
1674 static int tg_load_down(struct task_group *tg, void *data)
1676 unsigned long load;
1677 long cpu = (long)data;
1679 if (!tg->parent) {
1680 load = cpu_rq(cpu)->load.weight;
1681 } else {
1682 load = tg->parent->cfs_rq[cpu]->h_load;
1683 load *= tg->cfs_rq[cpu]->shares;
1684 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1687 tg->cfs_rq[cpu]->h_load = load;
1689 return 0;
1692 static void update_shares(struct sched_domain *sd)
1694 s64 elapsed;
1695 u64 now;
1697 if (root_task_group_empty())
1698 return;
1700 now = cpu_clock(raw_smp_processor_id());
1701 elapsed = now - sd->last_update;
1703 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1704 sd->last_update = now;
1705 walk_tg_tree(tg_nop, tg_shares_up, sd);
1709 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1711 if (root_task_group_empty())
1712 return;
1714 raw_spin_unlock(&rq->lock);
1715 update_shares(sd);
1716 raw_spin_lock(&rq->lock);
1719 static void update_h_load(long cpu)
1721 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1724 #else
1726 static inline void update_shares(struct sched_domain *sd)
1730 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1734 #endif
1736 #ifdef CONFIG_PREEMPT
1738 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1741 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1742 * way at the expense of forcing extra atomic operations in all
1743 * invocations. This assures that the double_lock is acquired using the
1744 * same underlying policy as the spinlock_t on this architecture, which
1745 * reduces latency compared to the unfair variant below. However, it
1746 * also adds more overhead and therefore may reduce throughput.
1748 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1749 __releases(this_rq->lock)
1750 __acquires(busiest->lock)
1751 __acquires(this_rq->lock)
1753 raw_spin_unlock(&this_rq->lock);
1754 double_rq_lock(this_rq, busiest);
1756 return 1;
1759 #else
1761 * Unfair double_lock_balance: Optimizes throughput at the expense of
1762 * latency by eliminating extra atomic operations when the locks are
1763 * already in proper order on entry. This favors lower cpu-ids and will
1764 * grant the double lock to lower cpus over higher ids under contention,
1765 * regardless of entry order into the function.
1767 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1768 __releases(this_rq->lock)
1769 __acquires(busiest->lock)
1770 __acquires(this_rq->lock)
1772 int ret = 0;
1774 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1775 if (busiest < this_rq) {
1776 raw_spin_unlock(&this_rq->lock);
1777 raw_spin_lock(&busiest->lock);
1778 raw_spin_lock_nested(&this_rq->lock,
1779 SINGLE_DEPTH_NESTING);
1780 ret = 1;
1781 } else
1782 raw_spin_lock_nested(&busiest->lock,
1783 SINGLE_DEPTH_NESTING);
1785 return ret;
1788 #endif /* CONFIG_PREEMPT */
1791 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1793 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1795 if (unlikely(!irqs_disabled())) {
1796 /* printk() doesn't work good under rq->lock */
1797 raw_spin_unlock(&this_rq->lock);
1798 BUG_ON(1);
1801 return _double_lock_balance(this_rq, busiest);
1804 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1805 __releases(busiest->lock)
1807 raw_spin_unlock(&busiest->lock);
1808 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1810 #endif
1812 #ifdef CONFIG_FAIR_GROUP_SCHED
1813 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1815 #ifdef CONFIG_SMP
1816 cfs_rq->shares = shares;
1817 #endif
1819 #endif
1821 static void calc_load_account_active(struct rq *this_rq);
1822 static void update_sysctl(void);
1823 static int get_update_sysctl_factor(void);
1825 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1827 set_task_rq(p, cpu);
1828 #ifdef CONFIG_SMP
1830 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1831 * successfuly executed on another CPU. We must ensure that updates of
1832 * per-task data have been completed by this moment.
1834 smp_wmb();
1835 task_thread_info(p)->cpu = cpu;
1836 #endif
1839 #include "sched_stats.h"
1840 #include "sched_idletask.c"
1841 #include "sched_fair.c"
1842 #include "sched_rt.c"
1843 #ifdef CONFIG_SCHED_DEBUG
1844 # include "sched_debug.c"
1845 #endif
1847 #define sched_class_highest (&rt_sched_class)
1848 #define for_each_class(class) \
1849 for (class = sched_class_highest; class; class = class->next)
1851 static void inc_nr_running(struct rq *rq)
1853 rq->nr_running++;
1856 static void dec_nr_running(struct rq *rq)
1858 rq->nr_running--;
1861 static void set_load_weight(struct task_struct *p)
1863 if (task_has_rt_policy(p)) {
1864 p->se.load.weight = prio_to_weight[0] * 2;
1865 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1866 return;
1870 * SCHED_IDLE tasks get minimal weight:
1872 if (p->policy == SCHED_IDLE) {
1873 p->se.load.weight = WEIGHT_IDLEPRIO;
1874 p->se.load.inv_weight = WMULT_IDLEPRIO;
1875 return;
1878 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1879 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1882 static void update_avg(u64 *avg, u64 sample)
1884 s64 diff = sample - *avg;
1885 *avg += diff >> 3;
1888 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1890 if (wakeup)
1891 p->se.start_runtime = p->se.sum_exec_runtime;
1893 sched_info_queued(p);
1894 p->sched_class->enqueue_task(rq, p, wakeup);
1895 p->se.on_rq = 1;
1898 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1900 if (sleep) {
1901 if (p->se.last_wakeup) {
1902 update_avg(&p->se.avg_overlap,
1903 p->se.sum_exec_runtime - p->se.last_wakeup);
1904 p->se.last_wakeup = 0;
1905 } else {
1906 update_avg(&p->se.avg_wakeup,
1907 sysctl_sched_wakeup_granularity);
1911 sched_info_dequeued(p);
1912 p->sched_class->dequeue_task(rq, p, sleep);
1913 p->se.on_rq = 0;
1917 * __normal_prio - return the priority that is based on the static prio
1919 static inline int __normal_prio(struct task_struct *p)
1921 return p->static_prio;
1925 * Calculate the expected normal priority: i.e. priority
1926 * without taking RT-inheritance into account. Might be
1927 * boosted by interactivity modifiers. Changes upon fork,
1928 * setprio syscalls, and whenever the interactivity
1929 * estimator recalculates.
1931 static inline int normal_prio(struct task_struct *p)
1933 int prio;
1935 if (task_has_rt_policy(p))
1936 prio = MAX_RT_PRIO-1 - p->rt_priority;
1937 else
1938 prio = __normal_prio(p);
1939 return prio;
1943 * Calculate the current priority, i.e. the priority
1944 * taken into account by the scheduler. This value might
1945 * be boosted by RT tasks, or might be boosted by
1946 * interactivity modifiers. Will be RT if the task got
1947 * RT-boosted. If not then it returns p->normal_prio.
1949 static int effective_prio(struct task_struct *p)
1951 p->normal_prio = normal_prio(p);
1953 * If we are RT tasks or we were boosted to RT priority,
1954 * keep the priority unchanged. Otherwise, update priority
1955 * to the normal priority:
1957 if (!rt_prio(p->prio))
1958 return p->normal_prio;
1959 return p->prio;
1963 * activate_task - move a task to the runqueue.
1965 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1967 if (task_contributes_to_load(p))
1968 rq->nr_uninterruptible--;
1970 enqueue_task(rq, p, wakeup);
1971 inc_nr_running(rq);
1975 * deactivate_task - remove a task from the runqueue.
1977 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1979 if (task_contributes_to_load(p))
1980 rq->nr_uninterruptible++;
1982 dequeue_task(rq, p, sleep);
1983 dec_nr_running(rq);
1987 * task_curr - is this task currently executing on a CPU?
1988 * @p: the task in question.
1990 inline int task_curr(const struct task_struct *p)
1992 return cpu_curr(task_cpu(p)) == p;
1995 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1996 const struct sched_class *prev_class,
1997 int oldprio, int running)
1999 if (prev_class != p->sched_class) {
2000 if (prev_class->switched_from)
2001 prev_class->switched_from(rq, p, running);
2002 p->sched_class->switched_to(rq, p, running);
2003 } else
2004 p->sched_class->prio_changed(rq, p, oldprio, running);
2007 #ifdef CONFIG_SMP
2009 * Is this task likely cache-hot:
2011 static int
2012 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2014 s64 delta;
2016 if (p->sched_class != &fair_sched_class)
2017 return 0;
2020 * Buddy candidates are cache hot:
2022 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2023 (&p->se == cfs_rq_of(&p->se)->next ||
2024 &p->se == cfs_rq_of(&p->se)->last))
2025 return 1;
2027 if (sysctl_sched_migration_cost == -1)
2028 return 1;
2029 if (sysctl_sched_migration_cost == 0)
2030 return 0;
2032 delta = now - p->se.exec_start;
2034 return delta < (s64)sysctl_sched_migration_cost;
2037 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2039 #ifdef CONFIG_SCHED_DEBUG
2041 * We should never call set_task_cpu() on a blocked task,
2042 * ttwu() will sort out the placement.
2044 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2045 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2046 #endif
2048 trace_sched_migrate_task(p, new_cpu);
2050 if (task_cpu(p) != new_cpu) {
2051 p->se.nr_migrations++;
2052 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0);
2055 __set_task_cpu(p, new_cpu);
2058 struct migration_req {
2059 struct list_head list;
2061 struct task_struct *task;
2062 int dest_cpu;
2064 struct completion done;
2068 * The task's runqueue lock must be held.
2069 * Returns true if you have to wait for migration thread.
2071 static int
2072 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2074 struct rq *rq = task_rq(p);
2077 * If the task is not on a runqueue (and not running), then
2078 * the next wake-up will properly place the task.
2080 if (!p->se.on_rq && !task_running(rq, p))
2081 return 0;
2083 init_completion(&req->done);
2084 req->task = p;
2085 req->dest_cpu = dest_cpu;
2086 list_add(&req->list, &rq->migration_queue);
2088 return 1;
2092 * wait_task_context_switch - wait for a thread to complete at least one
2093 * context switch.
2095 * @p must not be current.
2097 void wait_task_context_switch(struct task_struct *p)
2099 unsigned long nvcsw, nivcsw, flags;
2100 int running;
2101 struct rq *rq;
2103 nvcsw = p->nvcsw;
2104 nivcsw = p->nivcsw;
2105 for (;;) {
2107 * The runqueue is assigned before the actual context
2108 * switch. We need to take the runqueue lock.
2110 * We could check initially without the lock but it is
2111 * very likely that we need to take the lock in every
2112 * iteration.
2114 rq = task_rq_lock(p, &flags);
2115 running = task_running(rq, p);
2116 task_rq_unlock(rq, &flags);
2118 if (likely(!running))
2119 break;
2121 * The switch count is incremented before the actual
2122 * context switch. We thus wait for two switches to be
2123 * sure at least one completed.
2125 if ((p->nvcsw - nvcsw) > 1)
2126 break;
2127 if ((p->nivcsw - nivcsw) > 1)
2128 break;
2130 cpu_relax();
2135 * wait_task_inactive - wait for a thread to unschedule.
2137 * If @match_state is nonzero, it's the @p->state value just checked and
2138 * not expected to change. If it changes, i.e. @p might have woken up,
2139 * then return zero. When we succeed in waiting for @p to be off its CPU,
2140 * we return a positive number (its total switch count). If a second call
2141 * a short while later returns the same number, the caller can be sure that
2142 * @p has remained unscheduled the whole time.
2144 * The caller must ensure that the task *will* unschedule sometime soon,
2145 * else this function might spin for a *long* time. This function can't
2146 * be called with interrupts off, or it may introduce deadlock with
2147 * smp_call_function() if an IPI is sent by the same process we are
2148 * waiting to become inactive.
2150 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2152 unsigned long flags;
2153 int running, on_rq;
2154 unsigned long ncsw;
2155 struct rq *rq;
2157 for (;;) {
2159 * We do the initial early heuristics without holding
2160 * any task-queue locks at all. We'll only try to get
2161 * the runqueue lock when things look like they will
2162 * work out!
2164 rq = task_rq(p);
2167 * If the task is actively running on another CPU
2168 * still, just relax and busy-wait without holding
2169 * any locks.
2171 * NOTE! Since we don't hold any locks, it's not
2172 * even sure that "rq" stays as the right runqueue!
2173 * But we don't care, since "task_running()" will
2174 * return false if the runqueue has changed and p
2175 * is actually now running somewhere else!
2177 while (task_running(rq, p)) {
2178 if (match_state && unlikely(p->state != match_state))
2179 return 0;
2180 cpu_relax();
2184 * Ok, time to look more closely! We need the rq
2185 * lock now, to be *sure*. If we're wrong, we'll
2186 * just go back and repeat.
2188 rq = task_rq_lock(p, &flags);
2189 trace_sched_wait_task(rq, p);
2190 running = task_running(rq, p);
2191 on_rq = p->se.on_rq;
2192 ncsw = 0;
2193 if (!match_state || p->state == match_state)
2194 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2195 task_rq_unlock(rq, &flags);
2198 * If it changed from the expected state, bail out now.
2200 if (unlikely(!ncsw))
2201 break;
2204 * Was it really running after all now that we
2205 * checked with the proper locks actually held?
2207 * Oops. Go back and try again..
2209 if (unlikely(running)) {
2210 cpu_relax();
2211 continue;
2215 * It's not enough that it's not actively running,
2216 * it must be off the runqueue _entirely_, and not
2217 * preempted!
2219 * So if it was still runnable (but just not actively
2220 * running right now), it's preempted, and we should
2221 * yield - it could be a while.
2223 if (unlikely(on_rq)) {
2224 schedule_timeout_uninterruptible(1);
2225 continue;
2229 * Ahh, all good. It wasn't running, and it wasn't
2230 * runnable, which means that it will never become
2231 * running in the future either. We're all done!
2233 break;
2236 return ncsw;
2239 /***
2240 * kick_process - kick a running thread to enter/exit the kernel
2241 * @p: the to-be-kicked thread
2243 * Cause a process which is running on another CPU to enter
2244 * kernel-mode, without any delay. (to get signals handled.)
2246 * NOTE: this function doesnt have to take the runqueue lock,
2247 * because all it wants to ensure is that the remote task enters
2248 * the kernel. If the IPI races and the task has been migrated
2249 * to another CPU then no harm is done and the purpose has been
2250 * achieved as well.
2252 void kick_process(struct task_struct *p)
2254 int cpu;
2256 preempt_disable();
2257 cpu = task_cpu(p);
2258 if ((cpu != smp_processor_id()) && task_curr(p))
2259 smp_send_reschedule(cpu);
2260 preempt_enable();
2262 EXPORT_SYMBOL_GPL(kick_process);
2263 #endif /* CONFIG_SMP */
2266 * task_oncpu_function_call - call a function on the cpu on which a task runs
2267 * @p: the task to evaluate
2268 * @func: the function to be called
2269 * @info: the function call argument
2271 * Calls the function @func when the task is currently running. This might
2272 * be on the current CPU, which just calls the function directly
2274 void task_oncpu_function_call(struct task_struct *p,
2275 void (*func) (void *info), void *info)
2277 int cpu;
2279 preempt_disable();
2280 cpu = task_cpu(p);
2281 if (task_curr(p))
2282 smp_call_function_single(cpu, func, info, 1);
2283 preempt_enable();
2286 #ifdef CONFIG_SMP
2287 static int select_fallback_rq(int cpu, struct task_struct *p)
2289 int dest_cpu;
2290 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2292 /* Look for allowed, online CPU in same node. */
2293 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2294 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2295 return dest_cpu;
2297 /* Any allowed, online CPU? */
2298 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2299 if (dest_cpu < nr_cpu_ids)
2300 return dest_cpu;
2302 /* No more Mr. Nice Guy. */
2303 if (dest_cpu >= nr_cpu_ids) {
2304 rcu_read_lock();
2305 cpuset_cpus_allowed_locked(p, &p->cpus_allowed);
2306 rcu_read_unlock();
2307 dest_cpu = cpumask_any_and(cpu_active_mask, &p->cpus_allowed);
2310 * Don't tell them about moving exiting tasks or
2311 * kernel threads (both mm NULL), since they never
2312 * leave kernel.
2314 if (p->mm && printk_ratelimit()) {
2315 printk(KERN_INFO "process %d (%s) no "
2316 "longer affine to cpu%d\n",
2317 task_pid_nr(p), p->comm, cpu);
2321 return dest_cpu;
2325 * Gets called from 3 sites (exec, fork, wakeup), since it is called without
2326 * holding rq->lock we need to ensure ->cpus_allowed is stable, this is done
2327 * by:
2329 * exec: is unstable, retry loop
2330 * fork & wake-up: serialize ->cpus_allowed against TASK_WAKING
2332 static inline
2333 int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
2335 int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
2338 * In order not to call set_task_cpu() on a blocking task we need
2339 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2340 * cpu.
2342 * Since this is common to all placement strategies, this lives here.
2344 * [ this allows ->select_task() to simply return task_cpu(p) and
2345 * not worry about this generic constraint ]
2347 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2348 !cpu_online(cpu)))
2349 cpu = select_fallback_rq(task_cpu(p), p);
2351 return cpu;
2353 #endif
2355 /***
2356 * try_to_wake_up - wake up a thread
2357 * @p: the to-be-woken-up thread
2358 * @state: the mask of task states that can be woken
2359 * @sync: do a synchronous wakeup?
2361 * Put it on the run-queue if it's not already there. The "current"
2362 * thread is always on the run-queue (except when the actual
2363 * re-schedule is in progress), and as such you're allowed to do
2364 * the simpler "current->state = TASK_RUNNING" to mark yourself
2365 * runnable without the overhead of this.
2367 * returns failure only if the task is already active.
2369 static int try_to_wake_up(struct task_struct *p, unsigned int state,
2370 int wake_flags)
2372 int cpu, orig_cpu, this_cpu, success = 0;
2373 unsigned long flags;
2374 struct rq *rq, *orig_rq;
2376 if (!sched_feat(SYNC_WAKEUPS))
2377 wake_flags &= ~WF_SYNC;
2379 this_cpu = get_cpu();
2381 smp_wmb();
2382 rq = orig_rq = task_rq_lock(p, &flags);
2383 update_rq_clock(rq);
2384 if (!(p->state & state))
2385 goto out;
2387 if (p->se.on_rq)
2388 goto out_running;
2390 cpu = task_cpu(p);
2391 orig_cpu = cpu;
2393 #ifdef CONFIG_SMP
2394 if (unlikely(task_running(rq, p)))
2395 goto out_activate;
2398 * In order to handle concurrent wakeups and release the rq->lock
2399 * we put the task in TASK_WAKING state.
2401 * First fix up the nr_uninterruptible count:
2403 if (task_contributes_to_load(p))
2404 rq->nr_uninterruptible--;
2405 p->state = TASK_WAKING;
2407 if (p->sched_class->task_waking)
2408 p->sched_class->task_waking(rq, p);
2410 __task_rq_unlock(rq);
2412 cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
2413 if (cpu != orig_cpu)
2414 set_task_cpu(p, cpu);
2416 rq = __task_rq_lock(p);
2417 update_rq_clock(rq);
2419 WARN_ON(p->state != TASK_WAKING);
2420 cpu = task_cpu(p);
2422 #ifdef CONFIG_SCHEDSTATS
2423 schedstat_inc(rq, ttwu_count);
2424 if (cpu == this_cpu)
2425 schedstat_inc(rq, ttwu_local);
2426 else {
2427 struct sched_domain *sd;
2428 for_each_domain(this_cpu, sd) {
2429 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2430 schedstat_inc(sd, ttwu_wake_remote);
2431 break;
2435 #endif /* CONFIG_SCHEDSTATS */
2437 out_activate:
2438 #endif /* CONFIG_SMP */
2439 schedstat_inc(p, se.nr_wakeups);
2440 if (wake_flags & WF_SYNC)
2441 schedstat_inc(p, se.nr_wakeups_sync);
2442 if (orig_cpu != cpu)
2443 schedstat_inc(p, se.nr_wakeups_migrate);
2444 if (cpu == this_cpu)
2445 schedstat_inc(p, se.nr_wakeups_local);
2446 else
2447 schedstat_inc(p, se.nr_wakeups_remote);
2448 activate_task(rq, p, 1);
2449 success = 1;
2452 * Only attribute actual wakeups done by this task.
2454 if (!in_interrupt()) {
2455 struct sched_entity *se = &current->se;
2456 u64 sample = se->sum_exec_runtime;
2458 if (se->last_wakeup)
2459 sample -= se->last_wakeup;
2460 else
2461 sample -= se->start_runtime;
2462 update_avg(&se->avg_wakeup, sample);
2464 se->last_wakeup = se->sum_exec_runtime;
2467 out_running:
2468 trace_sched_wakeup(rq, p, success);
2469 check_preempt_curr(rq, p, wake_flags);
2471 p->state = TASK_RUNNING;
2472 #ifdef CONFIG_SMP
2473 if (p->sched_class->task_woken)
2474 p->sched_class->task_woken(rq, p);
2476 if (unlikely(rq->idle_stamp)) {
2477 u64 delta = rq->clock - rq->idle_stamp;
2478 u64 max = 2*sysctl_sched_migration_cost;
2480 if (delta > max)
2481 rq->avg_idle = max;
2482 else
2483 update_avg(&rq->avg_idle, delta);
2484 rq->idle_stamp = 0;
2486 #endif
2487 out:
2488 task_rq_unlock(rq, &flags);
2489 put_cpu();
2491 return success;
2495 * wake_up_process - Wake up a specific process
2496 * @p: The process to be woken up.
2498 * Attempt to wake up the nominated process and move it to the set of runnable
2499 * processes. Returns 1 if the process was woken up, 0 if it was already
2500 * running.
2502 * It may be assumed that this function implies a write memory barrier before
2503 * changing the task state if and only if any tasks are woken up.
2505 int wake_up_process(struct task_struct *p)
2507 return try_to_wake_up(p, TASK_ALL, 0);
2509 EXPORT_SYMBOL(wake_up_process);
2511 int wake_up_state(struct task_struct *p, unsigned int state)
2513 return try_to_wake_up(p, state, 0);
2517 * Perform scheduler related setup for a newly forked process p.
2518 * p is forked by current.
2520 * __sched_fork() is basic setup used by init_idle() too:
2522 static void __sched_fork(struct task_struct *p)
2524 p->se.exec_start = 0;
2525 p->se.sum_exec_runtime = 0;
2526 p->se.prev_sum_exec_runtime = 0;
2527 p->se.nr_migrations = 0;
2528 p->se.last_wakeup = 0;
2529 p->se.avg_overlap = 0;
2530 p->se.start_runtime = 0;
2531 p->se.avg_wakeup = sysctl_sched_wakeup_granularity;
2533 #ifdef CONFIG_SCHEDSTATS
2534 p->se.wait_start = 0;
2535 p->se.wait_max = 0;
2536 p->se.wait_count = 0;
2537 p->se.wait_sum = 0;
2539 p->se.sleep_start = 0;
2540 p->se.sleep_max = 0;
2541 p->se.sum_sleep_runtime = 0;
2543 p->se.block_start = 0;
2544 p->se.block_max = 0;
2545 p->se.exec_max = 0;
2546 p->se.slice_max = 0;
2548 p->se.nr_migrations_cold = 0;
2549 p->se.nr_failed_migrations_affine = 0;
2550 p->se.nr_failed_migrations_running = 0;
2551 p->se.nr_failed_migrations_hot = 0;
2552 p->se.nr_forced_migrations = 0;
2554 p->se.nr_wakeups = 0;
2555 p->se.nr_wakeups_sync = 0;
2556 p->se.nr_wakeups_migrate = 0;
2557 p->se.nr_wakeups_local = 0;
2558 p->se.nr_wakeups_remote = 0;
2559 p->se.nr_wakeups_affine = 0;
2560 p->se.nr_wakeups_affine_attempts = 0;
2561 p->se.nr_wakeups_passive = 0;
2562 p->se.nr_wakeups_idle = 0;
2564 #endif
2566 INIT_LIST_HEAD(&p->rt.run_list);
2567 p->se.on_rq = 0;
2568 INIT_LIST_HEAD(&p->se.group_node);
2570 #ifdef CONFIG_PREEMPT_NOTIFIERS
2571 INIT_HLIST_HEAD(&p->preempt_notifiers);
2572 #endif
2576 * fork()/clone()-time setup:
2578 void sched_fork(struct task_struct *p, int clone_flags)
2580 int cpu = get_cpu();
2582 __sched_fork(p);
2584 * We mark the process as waking here. This guarantees that
2585 * nobody will actually run it, and a signal or other external
2586 * event cannot wake it up and insert it on the runqueue either.
2588 p->state = TASK_WAKING;
2591 * Revert to default priority/policy on fork if requested.
2593 if (unlikely(p->sched_reset_on_fork)) {
2594 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2595 p->policy = SCHED_NORMAL;
2596 p->normal_prio = p->static_prio;
2599 if (PRIO_TO_NICE(p->static_prio) < 0) {
2600 p->static_prio = NICE_TO_PRIO(0);
2601 p->normal_prio = p->static_prio;
2602 set_load_weight(p);
2606 * We don't need the reset flag anymore after the fork. It has
2607 * fulfilled its duty:
2609 p->sched_reset_on_fork = 0;
2613 * Make sure we do not leak PI boosting priority to the child.
2615 p->prio = current->normal_prio;
2617 if (!rt_prio(p->prio))
2618 p->sched_class = &fair_sched_class;
2620 if (p->sched_class->task_fork)
2621 p->sched_class->task_fork(p);
2623 set_task_cpu(p, cpu);
2625 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2626 if (likely(sched_info_on()))
2627 memset(&p->sched_info, 0, sizeof(p->sched_info));
2628 #endif
2629 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2630 p->oncpu = 0;
2631 #endif
2632 #ifdef CONFIG_PREEMPT
2633 /* Want to start with kernel preemption disabled. */
2634 task_thread_info(p)->preempt_count = 1;
2635 #endif
2636 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2638 put_cpu();
2642 * wake_up_new_task - wake up a newly created task for the first time.
2644 * This function will do some initial scheduler statistics housekeeping
2645 * that must be done for every newly created context, then puts the task
2646 * on the runqueue and wakes it.
2648 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2650 unsigned long flags;
2651 struct rq *rq;
2652 int cpu = get_cpu();
2654 #ifdef CONFIG_SMP
2656 * Fork balancing, do it here and not earlier because:
2657 * - cpus_allowed can change in the fork path
2658 * - any previously selected cpu might disappear through hotplug
2660 * We still have TASK_WAKING but PF_STARTING is gone now, meaning
2661 * ->cpus_allowed is stable, we have preemption disabled, meaning
2662 * cpu_online_mask is stable.
2664 cpu = select_task_rq(p, SD_BALANCE_FORK, 0);
2665 set_task_cpu(p, cpu);
2666 #endif
2668 rq = task_rq_lock(p, &flags);
2669 BUG_ON(p->state != TASK_WAKING);
2670 p->state = TASK_RUNNING;
2671 update_rq_clock(rq);
2672 activate_task(rq, p, 0);
2673 trace_sched_wakeup_new(rq, p, 1);
2674 check_preempt_curr(rq, p, WF_FORK);
2675 #ifdef CONFIG_SMP
2676 if (p->sched_class->task_woken)
2677 p->sched_class->task_woken(rq, p);
2678 #endif
2679 task_rq_unlock(rq, &flags);
2680 put_cpu();
2683 #ifdef CONFIG_PREEMPT_NOTIFIERS
2686 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2687 * @notifier: notifier struct to register
2689 void preempt_notifier_register(struct preempt_notifier *notifier)
2691 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2693 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2696 * preempt_notifier_unregister - no longer interested in preemption notifications
2697 * @notifier: notifier struct to unregister
2699 * This is safe to call from within a preemption notifier.
2701 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2703 hlist_del(&notifier->link);
2705 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2707 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2709 struct preempt_notifier *notifier;
2710 struct hlist_node *node;
2712 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2713 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2716 static void
2717 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2718 struct task_struct *next)
2720 struct preempt_notifier *notifier;
2721 struct hlist_node *node;
2723 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2724 notifier->ops->sched_out(notifier, next);
2727 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2729 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2733 static void
2734 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2735 struct task_struct *next)
2739 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2742 * prepare_task_switch - prepare to switch tasks
2743 * @rq: the runqueue preparing to switch
2744 * @prev: the current task that is being switched out
2745 * @next: the task we are going to switch to.
2747 * This is called with the rq lock held and interrupts off. It must
2748 * be paired with a subsequent finish_task_switch after the context
2749 * switch.
2751 * prepare_task_switch sets up locking and calls architecture specific
2752 * hooks.
2754 static inline void
2755 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2756 struct task_struct *next)
2758 fire_sched_out_preempt_notifiers(prev, next);
2759 prepare_lock_switch(rq, next);
2760 prepare_arch_switch(next);
2764 * finish_task_switch - clean up after a task-switch
2765 * @rq: runqueue associated with task-switch
2766 * @prev: the thread we just switched away from.
2768 * finish_task_switch must be called after the context switch, paired
2769 * with a prepare_task_switch call before the context switch.
2770 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2771 * and do any other architecture-specific cleanup actions.
2773 * Note that we may have delayed dropping an mm in context_switch(). If
2774 * so, we finish that here outside of the runqueue lock. (Doing it
2775 * with the lock held can cause deadlocks; see schedule() for
2776 * details.)
2778 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2779 __releases(rq->lock)
2781 struct mm_struct *mm = rq->prev_mm;
2782 long prev_state;
2784 rq->prev_mm = NULL;
2787 * A task struct has one reference for the use as "current".
2788 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2789 * schedule one last time. The schedule call will never return, and
2790 * the scheduled task must drop that reference.
2791 * The test for TASK_DEAD must occur while the runqueue locks are
2792 * still held, otherwise prev could be scheduled on another cpu, die
2793 * there before we look at prev->state, and then the reference would
2794 * be dropped twice.
2795 * Manfred Spraul <manfred@colorfullife.com>
2797 prev_state = prev->state;
2798 finish_arch_switch(prev);
2799 perf_event_task_sched_in(current, cpu_of(rq));
2800 finish_lock_switch(rq, prev);
2802 fire_sched_in_preempt_notifiers(current);
2803 if (mm)
2804 mmdrop(mm);
2805 if (unlikely(prev_state == TASK_DEAD)) {
2807 * Remove function-return probe instances associated with this
2808 * task and put them back on the free list.
2810 kprobe_flush_task(prev);
2811 put_task_struct(prev);
2815 #ifdef CONFIG_SMP
2817 /* assumes rq->lock is held */
2818 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2820 if (prev->sched_class->pre_schedule)
2821 prev->sched_class->pre_schedule(rq, prev);
2824 /* rq->lock is NOT held, but preemption is disabled */
2825 static inline void post_schedule(struct rq *rq)
2827 if (rq->post_schedule) {
2828 unsigned long flags;
2830 raw_spin_lock_irqsave(&rq->lock, flags);
2831 if (rq->curr->sched_class->post_schedule)
2832 rq->curr->sched_class->post_schedule(rq);
2833 raw_spin_unlock_irqrestore(&rq->lock, flags);
2835 rq->post_schedule = 0;
2839 #else
2841 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2845 static inline void post_schedule(struct rq *rq)
2849 #endif
2852 * schedule_tail - first thing a freshly forked thread must call.
2853 * @prev: the thread we just switched away from.
2855 asmlinkage void schedule_tail(struct task_struct *prev)
2856 __releases(rq->lock)
2858 struct rq *rq = this_rq();
2860 finish_task_switch(rq, prev);
2863 * FIXME: do we need to worry about rq being invalidated by the
2864 * task_switch?
2866 post_schedule(rq);
2868 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2869 /* In this case, finish_task_switch does not reenable preemption */
2870 preempt_enable();
2871 #endif
2872 if (current->set_child_tid)
2873 put_user(task_pid_vnr(current), current->set_child_tid);
2877 * context_switch - switch to the new MM and the new
2878 * thread's register state.
2880 static inline void
2881 context_switch(struct rq *rq, struct task_struct *prev,
2882 struct task_struct *next)
2884 struct mm_struct *mm, *oldmm;
2886 prepare_task_switch(rq, prev, next);
2887 trace_sched_switch(rq, prev, next);
2888 mm = next->mm;
2889 oldmm = prev->active_mm;
2891 * For paravirt, this is coupled with an exit in switch_to to
2892 * combine the page table reload and the switch backend into
2893 * one hypercall.
2895 arch_start_context_switch(prev);
2897 if (likely(!mm)) {
2898 next->active_mm = oldmm;
2899 atomic_inc(&oldmm->mm_count);
2900 enter_lazy_tlb(oldmm, next);
2901 } else
2902 switch_mm(oldmm, mm, next);
2904 if (likely(!prev->mm)) {
2905 prev->active_mm = NULL;
2906 rq->prev_mm = oldmm;
2909 * Since the runqueue lock will be released by the next
2910 * task (which is an invalid locking op but in the case
2911 * of the scheduler it's an obvious special-case), so we
2912 * do an early lockdep release here:
2914 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2915 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2916 #endif
2918 /* Here we just switch the register state and the stack. */
2919 switch_to(prev, next, prev);
2921 barrier();
2923 * this_rq must be evaluated again because prev may have moved
2924 * CPUs since it called schedule(), thus the 'rq' on its stack
2925 * frame will be invalid.
2927 finish_task_switch(this_rq(), prev);
2931 * nr_running, nr_uninterruptible and nr_context_switches:
2933 * externally visible scheduler statistics: current number of runnable
2934 * threads, current number of uninterruptible-sleeping threads, total
2935 * number of context switches performed since bootup.
2937 unsigned long nr_running(void)
2939 unsigned long i, sum = 0;
2941 for_each_online_cpu(i)
2942 sum += cpu_rq(i)->nr_running;
2944 return sum;
2947 unsigned long nr_uninterruptible(void)
2949 unsigned long i, sum = 0;
2951 for_each_possible_cpu(i)
2952 sum += cpu_rq(i)->nr_uninterruptible;
2955 * Since we read the counters lockless, it might be slightly
2956 * inaccurate. Do not allow it to go below zero though:
2958 if (unlikely((long)sum < 0))
2959 sum = 0;
2961 return sum;
2964 unsigned long long nr_context_switches(void)
2966 int i;
2967 unsigned long long sum = 0;
2969 for_each_possible_cpu(i)
2970 sum += cpu_rq(i)->nr_switches;
2972 return sum;
2975 unsigned long nr_iowait(void)
2977 unsigned long i, sum = 0;
2979 for_each_possible_cpu(i)
2980 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2982 return sum;
2985 unsigned long nr_iowait_cpu(void)
2987 struct rq *this = this_rq();
2988 return atomic_read(&this->nr_iowait);
2991 unsigned long this_cpu_load(void)
2993 struct rq *this = this_rq();
2994 return this->cpu_load[0];
2998 /* Variables and functions for calc_load */
2999 static atomic_long_t calc_load_tasks;
3000 static unsigned long calc_load_update;
3001 unsigned long avenrun[3];
3002 EXPORT_SYMBOL(avenrun);
3005 * get_avenrun - get the load average array
3006 * @loads: pointer to dest load array
3007 * @offset: offset to add
3008 * @shift: shift count to shift the result left
3010 * These values are estimates at best, so no need for locking.
3012 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3014 loads[0] = (avenrun[0] + offset) << shift;
3015 loads[1] = (avenrun[1] + offset) << shift;
3016 loads[2] = (avenrun[2] + offset) << shift;
3019 static unsigned long
3020 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3022 load *= exp;
3023 load += active * (FIXED_1 - exp);
3024 return load >> FSHIFT;
3028 * calc_load - update the avenrun load estimates 10 ticks after the
3029 * CPUs have updated calc_load_tasks.
3031 void calc_global_load(void)
3033 unsigned long upd = calc_load_update + 10;
3034 long active;
3036 if (time_before(jiffies, upd))
3037 return;
3039 active = atomic_long_read(&calc_load_tasks);
3040 active = active > 0 ? active * FIXED_1 : 0;
3042 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3043 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3044 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3046 calc_load_update += LOAD_FREQ;
3050 * Either called from update_cpu_load() or from a cpu going idle
3052 static void calc_load_account_active(struct rq *this_rq)
3054 long nr_active, delta;
3056 nr_active = this_rq->nr_running;
3057 nr_active += (long) this_rq->nr_uninterruptible;
3059 if (nr_active != this_rq->calc_load_active) {
3060 delta = nr_active - this_rq->calc_load_active;
3061 this_rq->calc_load_active = nr_active;
3062 atomic_long_add(delta, &calc_load_tasks);
3067 * Update rq->cpu_load[] statistics. This function is usually called every
3068 * scheduler tick (TICK_NSEC).
3070 static void update_cpu_load(struct rq *this_rq)
3072 unsigned long this_load = this_rq->load.weight;
3073 int i, scale;
3075 this_rq->nr_load_updates++;
3077 /* Update our load: */
3078 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3079 unsigned long old_load, new_load;
3081 /* scale is effectively 1 << i now, and >> i divides by scale */
3083 old_load = this_rq->cpu_load[i];
3084 new_load = this_load;
3086 * Round up the averaging division if load is increasing. This
3087 * prevents us from getting stuck on 9 if the load is 10, for
3088 * example.
3090 if (new_load > old_load)
3091 new_load += scale-1;
3092 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
3095 if (time_after_eq(jiffies, this_rq->calc_load_update)) {
3096 this_rq->calc_load_update += LOAD_FREQ;
3097 calc_load_account_active(this_rq);
3101 #ifdef CONFIG_SMP
3104 * double_rq_lock - safely lock two runqueues
3106 * Note this does not disable interrupts like task_rq_lock,
3107 * you need to do so manually before calling.
3109 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
3110 __acquires(rq1->lock)
3111 __acquires(rq2->lock)
3113 BUG_ON(!irqs_disabled());
3114 if (rq1 == rq2) {
3115 raw_spin_lock(&rq1->lock);
3116 __acquire(rq2->lock); /* Fake it out ;) */
3117 } else {
3118 if (rq1 < rq2) {
3119 raw_spin_lock(&rq1->lock);
3120 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
3121 } else {
3122 raw_spin_lock(&rq2->lock);
3123 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
3126 update_rq_clock(rq1);
3127 update_rq_clock(rq2);
3131 * double_rq_unlock - safely unlock two runqueues
3133 * Note this does not restore interrupts like task_rq_unlock,
3134 * you need to do so manually after calling.
3136 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
3137 __releases(rq1->lock)
3138 __releases(rq2->lock)
3140 raw_spin_unlock(&rq1->lock);
3141 if (rq1 != rq2)
3142 raw_spin_unlock(&rq2->lock);
3143 else
3144 __release(rq2->lock);
3148 * sched_exec - execve() is a valuable balancing opportunity, because at
3149 * this point the task has the smallest effective memory and cache footprint.
3151 void sched_exec(void)
3153 struct task_struct *p = current;
3154 struct migration_req req;
3155 int dest_cpu, this_cpu;
3156 unsigned long flags;
3157 struct rq *rq;
3159 again:
3160 this_cpu = get_cpu();
3161 dest_cpu = select_task_rq(p, SD_BALANCE_EXEC, 0);
3162 if (dest_cpu == this_cpu) {
3163 put_cpu();
3164 return;
3167 rq = task_rq_lock(p, &flags);
3168 put_cpu();
3171 * select_task_rq() can race against ->cpus_allowed
3173 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed)
3174 || unlikely(!cpu_active(dest_cpu))) {
3175 task_rq_unlock(rq, &flags);
3176 goto again;
3179 /* force the process onto the specified CPU */
3180 if (migrate_task(p, dest_cpu, &req)) {
3181 /* Need to wait for migration thread (might exit: take ref). */
3182 struct task_struct *mt = rq->migration_thread;
3184 get_task_struct(mt);
3185 task_rq_unlock(rq, &flags);
3186 wake_up_process(mt);
3187 put_task_struct(mt);
3188 wait_for_completion(&req.done);
3190 return;
3192 task_rq_unlock(rq, &flags);
3196 * pull_task - move a task from a remote runqueue to the local runqueue.
3197 * Both runqueues must be locked.
3199 static void pull_task(struct rq *src_rq, struct task_struct *p,
3200 struct rq *this_rq, int this_cpu)
3202 deactivate_task(src_rq, p, 0);
3203 set_task_cpu(p, this_cpu);
3204 activate_task(this_rq, p, 0);
3205 check_preempt_curr(this_rq, p, 0);
3209 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3211 static
3212 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3213 struct sched_domain *sd, enum cpu_idle_type idle,
3214 int *all_pinned)
3216 int tsk_cache_hot = 0;
3218 * We do not migrate tasks that are:
3219 * 1) running (obviously), or
3220 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3221 * 3) are cache-hot on their current CPU.
3223 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
3224 schedstat_inc(p, se.nr_failed_migrations_affine);
3225 return 0;
3227 *all_pinned = 0;
3229 if (task_running(rq, p)) {
3230 schedstat_inc(p, se.nr_failed_migrations_running);
3231 return 0;
3235 * Aggressive migration if:
3236 * 1) task is cache cold, or
3237 * 2) too many balance attempts have failed.
3240 tsk_cache_hot = task_hot(p, rq->clock, sd);
3241 if (!tsk_cache_hot ||
3242 sd->nr_balance_failed > sd->cache_nice_tries) {
3243 #ifdef CONFIG_SCHEDSTATS
3244 if (tsk_cache_hot) {
3245 schedstat_inc(sd, lb_hot_gained[idle]);
3246 schedstat_inc(p, se.nr_forced_migrations);
3248 #endif
3249 return 1;
3252 if (tsk_cache_hot) {
3253 schedstat_inc(p, se.nr_failed_migrations_hot);
3254 return 0;
3256 return 1;
3259 static unsigned long
3260 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3261 unsigned long max_load_move, struct sched_domain *sd,
3262 enum cpu_idle_type idle, int *all_pinned,
3263 int *this_best_prio, struct rq_iterator *iterator)
3265 int loops = 0, pulled = 0, pinned = 0;
3266 struct task_struct *p;
3267 long rem_load_move = max_load_move;
3269 if (max_load_move == 0)
3270 goto out;
3272 pinned = 1;
3275 * Start the load-balancing iterator:
3277 p = iterator->start(iterator->arg);
3278 next:
3279 if (!p || loops++ > sysctl_sched_nr_migrate)
3280 goto out;
3282 if ((p->se.load.weight >> 1) > rem_load_move ||
3283 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3284 p = iterator->next(iterator->arg);
3285 goto next;
3288 pull_task(busiest, p, this_rq, this_cpu);
3289 pulled++;
3290 rem_load_move -= p->se.load.weight;
3292 #ifdef CONFIG_PREEMPT
3294 * NEWIDLE balancing is a source of latency, so preemptible kernels
3295 * will stop after the first task is pulled to minimize the critical
3296 * section.
3298 if (idle == CPU_NEWLY_IDLE)
3299 goto out;
3300 #endif
3303 * We only want to steal up to the prescribed amount of weighted load.
3305 if (rem_load_move > 0) {
3306 if (p->prio < *this_best_prio)
3307 *this_best_prio = p->prio;
3308 p = iterator->next(iterator->arg);
3309 goto next;
3311 out:
3313 * Right now, this is one of only two places pull_task() is called,
3314 * so we can safely collect pull_task() stats here rather than
3315 * inside pull_task().
3317 schedstat_add(sd, lb_gained[idle], pulled);
3319 if (all_pinned)
3320 *all_pinned = pinned;
3322 return max_load_move - rem_load_move;
3326 * move_tasks tries to move up to max_load_move weighted load from busiest to
3327 * this_rq, as part of a balancing operation within domain "sd".
3328 * Returns 1 if successful and 0 otherwise.
3330 * Called with both runqueues locked.
3332 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3333 unsigned long max_load_move,
3334 struct sched_domain *sd, enum cpu_idle_type idle,
3335 int *all_pinned)
3337 const struct sched_class *class = sched_class_highest;
3338 unsigned long total_load_moved = 0;
3339 int this_best_prio = this_rq->curr->prio;
3341 do {
3342 total_load_moved +=
3343 class->load_balance(this_rq, this_cpu, busiest,
3344 max_load_move - total_load_moved,
3345 sd, idle, all_pinned, &this_best_prio);
3346 class = class->next;
3348 #ifdef CONFIG_PREEMPT
3350 * NEWIDLE balancing is a source of latency, so preemptible
3351 * kernels will stop after the first task is pulled to minimize
3352 * the critical section.
3354 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3355 break;
3356 #endif
3357 } while (class && max_load_move > total_load_moved);
3359 return total_load_moved > 0;
3362 static int
3363 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3364 struct sched_domain *sd, enum cpu_idle_type idle,
3365 struct rq_iterator *iterator)
3367 struct task_struct *p = iterator->start(iterator->arg);
3368 int pinned = 0;
3370 while (p) {
3371 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3372 pull_task(busiest, p, this_rq, this_cpu);
3374 * Right now, this is only the second place pull_task()
3375 * is called, so we can safely collect pull_task()
3376 * stats here rather than inside pull_task().
3378 schedstat_inc(sd, lb_gained[idle]);
3380 return 1;
3382 p = iterator->next(iterator->arg);
3385 return 0;
3389 * move_one_task tries to move exactly one task from busiest to this_rq, as
3390 * part of active balancing operations within "domain".
3391 * Returns 1 if successful and 0 otherwise.
3393 * Called with both runqueues locked.
3395 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3396 struct sched_domain *sd, enum cpu_idle_type idle)
3398 const struct sched_class *class;
3400 for_each_class(class) {
3401 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3402 return 1;
3405 return 0;
3407 /********** Helpers for find_busiest_group ************************/
3409 * sd_lb_stats - Structure to store the statistics of a sched_domain
3410 * during load balancing.
3412 struct sd_lb_stats {
3413 struct sched_group *busiest; /* Busiest group in this sd */
3414 struct sched_group *this; /* Local group in this sd */
3415 unsigned long total_load; /* Total load of all groups in sd */
3416 unsigned long total_pwr; /* Total power of all groups in sd */
3417 unsigned long avg_load; /* Average load across all groups in sd */
3419 /** Statistics of this group */
3420 unsigned long this_load;
3421 unsigned long this_load_per_task;
3422 unsigned long this_nr_running;
3424 /* Statistics of the busiest group */
3425 unsigned long max_load;
3426 unsigned long busiest_load_per_task;
3427 unsigned long busiest_nr_running;
3428 unsigned long busiest_group_capacity;
3430 int group_imb; /* Is there imbalance in this sd */
3431 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3432 int power_savings_balance; /* Is powersave balance needed for this sd */
3433 struct sched_group *group_min; /* Least loaded group in sd */
3434 struct sched_group *group_leader; /* Group which relieves group_min */
3435 unsigned long min_load_per_task; /* load_per_task in group_min */
3436 unsigned long leader_nr_running; /* Nr running of group_leader */
3437 unsigned long min_nr_running; /* Nr running of group_min */
3438 #endif
3442 * sg_lb_stats - stats of a sched_group required for load_balancing
3444 struct sg_lb_stats {
3445 unsigned long avg_load; /*Avg load across the CPUs of the group */
3446 unsigned long group_load; /* Total load over the CPUs of the group */
3447 unsigned long sum_nr_running; /* Nr tasks running in the group */
3448 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
3449 unsigned long group_capacity;
3450 int group_imb; /* Is there an imbalance in the group ? */
3454 * group_first_cpu - Returns the first cpu in the cpumask of a sched_group.
3455 * @group: The group whose first cpu is to be returned.
3457 static inline unsigned int group_first_cpu(struct sched_group *group)
3459 return cpumask_first(sched_group_cpus(group));
3463 * get_sd_load_idx - Obtain the load index for a given sched domain.
3464 * @sd: The sched_domain whose load_idx is to be obtained.
3465 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
3467 static inline int get_sd_load_idx(struct sched_domain *sd,
3468 enum cpu_idle_type idle)
3470 int load_idx;
3472 switch (idle) {
3473 case CPU_NOT_IDLE:
3474 load_idx = sd->busy_idx;
3475 break;
3477 case CPU_NEWLY_IDLE:
3478 load_idx = sd->newidle_idx;
3479 break;
3480 default:
3481 load_idx = sd->idle_idx;
3482 break;
3485 return load_idx;
3489 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3491 * init_sd_power_savings_stats - Initialize power savings statistics for
3492 * the given sched_domain, during load balancing.
3494 * @sd: Sched domain whose power-savings statistics are to be initialized.
3495 * @sds: Variable containing the statistics for sd.
3496 * @idle: Idle status of the CPU at which we're performing load-balancing.
3498 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3499 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3502 * Busy processors will not participate in power savings
3503 * balance.
3505 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3506 sds->power_savings_balance = 0;
3507 else {
3508 sds->power_savings_balance = 1;
3509 sds->min_nr_running = ULONG_MAX;
3510 sds->leader_nr_running = 0;
3515 * update_sd_power_savings_stats - Update the power saving stats for a
3516 * sched_domain while performing load balancing.
3518 * @group: sched_group belonging to the sched_domain under consideration.
3519 * @sds: Variable containing the statistics of the sched_domain
3520 * @local_group: Does group contain the CPU for which we're performing
3521 * load balancing ?
3522 * @sgs: Variable containing the statistics of the group.
3524 static inline void update_sd_power_savings_stats(struct sched_group *group,
3525 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3528 if (!sds->power_savings_balance)
3529 return;
3532 * If the local group is idle or completely loaded
3533 * no need to do power savings balance at this domain
3535 if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
3536 !sds->this_nr_running))
3537 sds->power_savings_balance = 0;
3540 * If a group is already running at full capacity or idle,
3541 * don't include that group in power savings calculations
3543 if (!sds->power_savings_balance ||
3544 sgs->sum_nr_running >= sgs->group_capacity ||
3545 !sgs->sum_nr_running)
3546 return;
3549 * Calculate the group which has the least non-idle load.
3550 * This is the group from where we need to pick up the load
3551 * for saving power
3553 if ((sgs->sum_nr_running < sds->min_nr_running) ||
3554 (sgs->sum_nr_running == sds->min_nr_running &&
3555 group_first_cpu(group) > group_first_cpu(sds->group_min))) {
3556 sds->group_min = group;
3557 sds->min_nr_running = sgs->sum_nr_running;
3558 sds->min_load_per_task = sgs->sum_weighted_load /
3559 sgs->sum_nr_running;
3563 * Calculate the group which is almost near its
3564 * capacity but still has some space to pick up some load
3565 * from other group and save more power
3567 if (sgs->sum_nr_running + 1 > sgs->group_capacity)
3568 return;
3570 if (sgs->sum_nr_running > sds->leader_nr_running ||
3571 (sgs->sum_nr_running == sds->leader_nr_running &&
3572 group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
3573 sds->group_leader = group;
3574 sds->leader_nr_running = sgs->sum_nr_running;
3579 * check_power_save_busiest_group - see if there is potential for some power-savings balance
3580 * @sds: Variable containing the statistics of the sched_domain
3581 * under consideration.
3582 * @this_cpu: Cpu at which we're currently performing load-balancing.
3583 * @imbalance: Variable to store the imbalance.
3585 * Description:
3586 * Check if we have potential to perform some power-savings balance.
3587 * If yes, set the busiest group to be the least loaded group in the
3588 * sched_domain, so that it's CPUs can be put to idle.
3590 * Returns 1 if there is potential to perform power-savings balance.
3591 * Else returns 0.
3593 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3594 int this_cpu, unsigned long *imbalance)
3596 if (!sds->power_savings_balance)
3597 return 0;
3599 if (sds->this != sds->group_leader ||
3600 sds->group_leader == sds->group_min)
3601 return 0;
3603 *imbalance = sds->min_load_per_task;
3604 sds->busiest = sds->group_min;
3606 return 1;
3609 #else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3610 static inline void init_sd_power_savings_stats(struct sched_domain *sd,
3611 struct sd_lb_stats *sds, enum cpu_idle_type idle)
3613 return;
3616 static inline void update_sd_power_savings_stats(struct sched_group *group,
3617 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
3619 return;
3622 static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
3623 int this_cpu, unsigned long *imbalance)
3625 return 0;
3627 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
3630 unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
3632 return SCHED_LOAD_SCALE;
3635 unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
3637 return default_scale_freq_power(sd, cpu);
3640 unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
3642 unsigned long weight = cpumask_weight(sched_domain_span(sd));
3643 unsigned long smt_gain = sd->smt_gain;
3645 smt_gain /= weight;
3647 return smt_gain;
3650 unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
3652 return default_scale_smt_power(sd, cpu);
3655 unsigned long scale_rt_power(int cpu)
3657 struct rq *rq = cpu_rq(cpu);
3658 u64 total, available;
3660 sched_avg_update(rq);
3662 total = sched_avg_period() + (rq->clock - rq->age_stamp);
3663 available = total - rq->rt_avg;
3665 if (unlikely((s64)total < SCHED_LOAD_SCALE))
3666 total = SCHED_LOAD_SCALE;
3668 total >>= SCHED_LOAD_SHIFT;
3670 return div_u64(available, total);
3673 static void update_cpu_power(struct sched_domain *sd, int cpu)
3675 unsigned long weight = cpumask_weight(sched_domain_span(sd));
3676 unsigned long power = SCHED_LOAD_SCALE;
3677 struct sched_group *sdg = sd->groups;
3679 if (sched_feat(ARCH_POWER))
3680 power *= arch_scale_freq_power(sd, cpu);
3681 else
3682 power *= default_scale_freq_power(sd, cpu);
3684 power >>= SCHED_LOAD_SHIFT;
3686 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
3687 if (sched_feat(ARCH_POWER))
3688 power *= arch_scale_smt_power(sd, cpu);
3689 else
3690 power *= default_scale_smt_power(sd, cpu);
3692 power >>= SCHED_LOAD_SHIFT;
3695 power *= scale_rt_power(cpu);
3696 power >>= SCHED_LOAD_SHIFT;
3698 if (!power)
3699 power = 1;
3701 sdg->cpu_power = power;
3704 static void update_group_power(struct sched_domain *sd, int cpu)
3706 struct sched_domain *child = sd->child;
3707 struct sched_group *group, *sdg = sd->groups;
3708 unsigned long power;
3710 if (!child) {
3711 update_cpu_power(sd, cpu);
3712 return;
3715 power = 0;
3717 group = child->groups;
3718 do {
3719 power += group->cpu_power;
3720 group = group->next;
3721 } while (group != child->groups);
3723 sdg->cpu_power = power;
3727 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
3728 * @sd: The sched_domain whose statistics are to be updated.
3729 * @group: sched_group whose statistics are to be updated.
3730 * @this_cpu: Cpu for which load balance is currently performed.
3731 * @idle: Idle status of this_cpu
3732 * @load_idx: Load index of sched_domain of this_cpu for load calc.
3733 * @sd_idle: Idle status of the sched_domain containing group.
3734 * @local_group: Does group contain this_cpu.
3735 * @cpus: Set of cpus considered for load balancing.
3736 * @balance: Should we balance.
3737 * @sgs: variable to hold the statistics for this group.
3739 static inline void update_sg_lb_stats(struct sched_domain *sd,
3740 struct sched_group *group, int this_cpu,
3741 enum cpu_idle_type idle, int load_idx, int *sd_idle,
3742 int local_group, const struct cpumask *cpus,
3743 int *balance, struct sg_lb_stats *sgs)
3745 unsigned long load, max_cpu_load, min_cpu_load;
3746 int i;
3747 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3748 unsigned long avg_load_per_task = 0;
3750 if (local_group) {
3751 balance_cpu = group_first_cpu(group);
3752 if (balance_cpu == this_cpu)
3753 update_group_power(sd, this_cpu);
3756 /* Tally up the load of all CPUs in the group */
3757 max_cpu_load = 0;
3758 min_cpu_load = ~0UL;
3760 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
3761 struct rq *rq = cpu_rq(i);
3763 if (*sd_idle && rq->nr_running)
3764 *sd_idle = 0;
3766 /* Bias balancing toward cpus of our domain */
3767 if (local_group) {
3768 if (idle_cpu(i) && !first_idle_cpu) {
3769 first_idle_cpu = 1;
3770 balance_cpu = i;
3773 load = target_load(i, load_idx);
3774 } else {
3775 load = source_load(i, load_idx);
3776 if (load > max_cpu_load)
3777 max_cpu_load = load;
3778 if (min_cpu_load > load)
3779 min_cpu_load = load;
3782 sgs->group_load += load;
3783 sgs->sum_nr_running += rq->nr_running;
3784 sgs->sum_weighted_load += weighted_cpuload(i);
3789 * First idle cpu or the first cpu(busiest) in this sched group
3790 * is eligible for doing load balancing at this and above
3791 * domains. In the newly idle case, we will allow all the cpu's
3792 * to do the newly idle load balance.
3794 if (idle != CPU_NEWLY_IDLE && local_group &&
3795 balance_cpu != this_cpu && balance) {
3796 *balance = 0;
3797 return;
3800 /* Adjust by relative CPU power of the group */
3801 sgs->avg_load = (sgs->group_load * SCHED_LOAD_SCALE) / group->cpu_power;
3804 * Consider the group unbalanced when the imbalance is larger
3805 * than the average weight of two tasks.
3807 * APZ: with cgroup the avg task weight can vary wildly and
3808 * might not be a suitable number - should we keep a
3809 * normalized nr_running number somewhere that negates
3810 * the hierarchy?
3812 if (sgs->sum_nr_running)
3813 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
3815 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3816 sgs->group_imb = 1;
3818 sgs->group_capacity =
3819 DIV_ROUND_CLOSEST(group->cpu_power, SCHED_LOAD_SCALE);
3823 * update_sd_lb_stats - Update sched_group's statistics for load balancing.
3824 * @sd: sched_domain whose statistics are to be updated.
3825 * @this_cpu: Cpu for which load balance is currently performed.
3826 * @idle: Idle status of this_cpu
3827 * @sd_idle: Idle status of the sched_domain containing group.
3828 * @cpus: Set of cpus considered for load balancing.
3829 * @balance: Should we balance.
3830 * @sds: variable to hold the statistics for this sched_domain.
3832 static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
3833 enum cpu_idle_type idle, int *sd_idle,
3834 const struct cpumask *cpus, int *balance,
3835 struct sd_lb_stats *sds)
3837 struct sched_domain *child = sd->child;
3838 struct sched_group *group = sd->groups;
3839 struct sg_lb_stats sgs;
3840 int load_idx, prefer_sibling = 0;
3842 if (child && child->flags & SD_PREFER_SIBLING)
3843 prefer_sibling = 1;
3845 init_sd_power_savings_stats(sd, sds, idle);
3846 load_idx = get_sd_load_idx(sd, idle);
3848 do {
3849 int local_group;
3851 local_group = cpumask_test_cpu(this_cpu,
3852 sched_group_cpus(group));
3853 memset(&sgs, 0, sizeof(sgs));
3854 update_sg_lb_stats(sd, group, this_cpu, idle, load_idx, sd_idle,
3855 local_group, cpus, balance, &sgs);
3857 if (local_group && balance && !(*balance))
3858 return;
3860 sds->total_load += sgs.group_load;
3861 sds->total_pwr += group->cpu_power;
3864 * In case the child domain prefers tasks go to siblings
3865 * first, lower the group capacity to one so that we'll try
3866 * and move all the excess tasks away.
3868 if (prefer_sibling)
3869 sgs.group_capacity = min(sgs.group_capacity, 1UL);
3871 if (local_group) {
3872 sds->this_load = sgs.avg_load;
3873 sds->this = group;
3874 sds->this_nr_running = sgs.sum_nr_running;
3875 sds->this_load_per_task = sgs.sum_weighted_load;
3876 } else if (sgs.avg_load > sds->max_load &&
3877 (sgs.sum_nr_running > sgs.group_capacity ||
3878 sgs.group_imb)) {
3879 sds->max_load = sgs.avg_load;
3880 sds->busiest = group;
3881 sds->busiest_nr_running = sgs.sum_nr_running;
3882 sds->busiest_group_capacity = sgs.group_capacity;
3883 sds->busiest_load_per_task = sgs.sum_weighted_load;
3884 sds->group_imb = sgs.group_imb;
3887 update_sd_power_savings_stats(group, sds, local_group, &sgs);
3888 group = group->next;
3889 } while (group != sd->groups);
3893 * fix_small_imbalance - Calculate the minor imbalance that exists
3894 * amongst the groups of a sched_domain, during
3895 * load balancing.
3896 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
3897 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
3898 * @imbalance: Variable to store the imbalance.
3900 static inline void fix_small_imbalance(struct sd_lb_stats *sds,
3901 int this_cpu, unsigned long *imbalance)
3903 unsigned long tmp, pwr_now = 0, pwr_move = 0;
3904 unsigned int imbn = 2;
3905 unsigned long scaled_busy_load_per_task;
3907 if (sds->this_nr_running) {
3908 sds->this_load_per_task /= sds->this_nr_running;
3909 if (sds->busiest_load_per_task >
3910 sds->this_load_per_task)
3911 imbn = 1;
3912 } else
3913 sds->this_load_per_task =
3914 cpu_avg_load_per_task(this_cpu);
3916 scaled_busy_load_per_task = sds->busiest_load_per_task
3917 * SCHED_LOAD_SCALE;
3918 scaled_busy_load_per_task /= sds->busiest->cpu_power;
3920 if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
3921 (scaled_busy_load_per_task * imbn)) {
3922 *imbalance = sds->busiest_load_per_task;
3923 return;
3927 * OK, we don't have enough imbalance to justify moving tasks,
3928 * however we may be able to increase total CPU power used by
3929 * moving them.
3932 pwr_now += sds->busiest->cpu_power *
3933 min(sds->busiest_load_per_task, sds->max_load);
3934 pwr_now += sds->this->cpu_power *
3935 min(sds->this_load_per_task, sds->this_load);
3936 pwr_now /= SCHED_LOAD_SCALE;
3938 /* Amount of load we'd subtract */
3939 tmp = (sds->busiest_load_per_task * SCHED_LOAD_SCALE) /
3940 sds->busiest->cpu_power;
3941 if (sds->max_load > tmp)
3942 pwr_move += sds->busiest->cpu_power *
3943 min(sds->busiest_load_per_task, sds->max_load - tmp);
3945 /* Amount of load we'd add */
3946 if (sds->max_load * sds->busiest->cpu_power <
3947 sds->busiest_load_per_task * SCHED_LOAD_SCALE)
3948 tmp = (sds->max_load * sds->busiest->cpu_power) /
3949 sds->this->cpu_power;
3950 else
3951 tmp = (sds->busiest_load_per_task * SCHED_LOAD_SCALE) /
3952 sds->this->cpu_power;
3953 pwr_move += sds->this->cpu_power *
3954 min(sds->this_load_per_task, sds->this_load + tmp);
3955 pwr_move /= SCHED_LOAD_SCALE;
3957 /* Move if we gain throughput */
3958 if (pwr_move > pwr_now)
3959 *imbalance = sds->busiest_load_per_task;
3963 * calculate_imbalance - Calculate the amount of imbalance present within the
3964 * groups of a given sched_domain during load balance.
3965 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
3966 * @this_cpu: Cpu for which currently load balance is being performed.
3967 * @imbalance: The variable to store the imbalance.
3969 static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
3970 unsigned long *imbalance)
3972 unsigned long max_pull, load_above_capacity = ~0UL;
3974 sds->busiest_load_per_task /= sds->busiest_nr_running;
3975 if (sds->group_imb) {
3976 sds->busiest_load_per_task =
3977 min(sds->busiest_load_per_task, sds->avg_load);
3981 * In the presence of smp nice balancing, certain scenarios can have
3982 * max load less than avg load(as we skip the groups at or below
3983 * its cpu_power, while calculating max_load..)
3985 if (sds->max_load < sds->avg_load) {
3986 *imbalance = 0;
3987 return fix_small_imbalance(sds, this_cpu, imbalance);
3990 if (!sds->group_imb) {
3992 * Don't want to pull so many tasks that a group would go idle.
3994 load_above_capacity = (sds->busiest_nr_running -
3995 sds->busiest_group_capacity);
3997 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_LOAD_SCALE);
3999 load_above_capacity /= sds->busiest->cpu_power;
4003 * We're trying to get all the cpus to the average_load, so we don't
4004 * want to push ourselves above the average load, nor do we wish to
4005 * reduce the max loaded cpu below the average load. At the same time,
4006 * we also don't want to reduce the group load below the group capacity
4007 * (so that we can implement power-savings policies etc). Thus we look
4008 * for the minimum possible imbalance.
4009 * Be careful of negative numbers as they'll appear as very large values
4010 * with unsigned longs.
4012 max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
4014 /* How much load to actually move to equalise the imbalance */
4015 *imbalance = min(max_pull * sds->busiest->cpu_power,
4016 (sds->avg_load - sds->this_load) * sds->this->cpu_power)
4017 / SCHED_LOAD_SCALE;
4020 * if *imbalance is less than the average load per runnable task
4021 * there is no gaurantee that any tasks will be moved so we'll have
4022 * a think about bumping its value to force at least one task to be
4023 * moved
4025 if (*imbalance < sds->busiest_load_per_task)
4026 return fix_small_imbalance(sds, this_cpu, imbalance);
4029 /******* find_busiest_group() helpers end here *********************/
4032 * find_busiest_group - Returns the busiest group within the sched_domain
4033 * if there is an imbalance. If there isn't an imbalance, and
4034 * the user has opted for power-savings, it returns a group whose
4035 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
4036 * such a group exists.
4038 * Also calculates the amount of weighted load which should be moved
4039 * to restore balance.
4041 * @sd: The sched_domain whose busiest group is to be returned.
4042 * @this_cpu: The cpu for which load balancing is currently being performed.
4043 * @imbalance: Variable which stores amount of weighted load which should
4044 * be moved to restore balance/put a group to idle.
4045 * @idle: The idle status of this_cpu.
4046 * @sd_idle: The idleness of sd
4047 * @cpus: The set of CPUs under consideration for load-balancing.
4048 * @balance: Pointer to a variable indicating if this_cpu
4049 * is the appropriate cpu to perform load balancing at this_level.
4051 * Returns: - the busiest group if imbalance exists.
4052 * - If no imbalance and user has opted for power-savings balance,
4053 * return the least loaded group whose CPUs can be
4054 * put to idle by rebalancing its tasks onto our group.
4056 static struct sched_group *
4057 find_busiest_group(struct sched_domain *sd, int this_cpu,
4058 unsigned long *imbalance, enum cpu_idle_type idle,
4059 int *sd_idle, const struct cpumask *cpus, int *balance)
4061 struct sd_lb_stats sds;
4063 memset(&sds, 0, sizeof(sds));
4066 * Compute the various statistics relavent for load balancing at
4067 * this level.
4069 update_sd_lb_stats(sd, this_cpu, idle, sd_idle, cpus,
4070 balance, &sds);
4072 /* Cases where imbalance does not exist from POV of this_cpu */
4073 /* 1) this_cpu is not the appropriate cpu to perform load balancing
4074 * at this level.
4075 * 2) There is no busy sibling group to pull from.
4076 * 3) This group is the busiest group.
4077 * 4) This group is more busy than the avg busieness at this
4078 * sched_domain.
4079 * 5) The imbalance is within the specified limit.
4081 if (balance && !(*balance))
4082 goto ret;
4084 if (!sds.busiest || sds.busiest_nr_running == 0)
4085 goto out_balanced;
4087 if (sds.this_load >= sds.max_load)
4088 goto out_balanced;
4090 sds.avg_load = (SCHED_LOAD_SCALE * sds.total_load) / sds.total_pwr;
4092 if (sds.this_load >= sds.avg_load)
4093 goto out_balanced;
4095 if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
4096 goto out_balanced;
4098 /* Looks like there is an imbalance. Compute it */
4099 calculate_imbalance(&sds, this_cpu, imbalance);
4100 return sds.busiest;
4102 out_balanced:
4104 * There is no obvious imbalance. But check if we can do some balancing
4105 * to save power.
4107 if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
4108 return sds.busiest;
4109 ret:
4110 *imbalance = 0;
4111 return NULL;
4115 * find_busiest_queue - find the busiest runqueue among the cpus in group.
4117 static struct rq *
4118 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
4119 unsigned long imbalance, const struct cpumask *cpus)
4121 struct rq *busiest = NULL, *rq;
4122 unsigned long max_load = 0;
4123 int i;
4125 for_each_cpu(i, sched_group_cpus(group)) {
4126 unsigned long power = power_of(i);
4127 unsigned long capacity = DIV_ROUND_CLOSEST(power, SCHED_LOAD_SCALE);
4128 unsigned long wl;
4130 if (!cpumask_test_cpu(i, cpus))
4131 continue;
4133 rq = cpu_rq(i);
4134 wl = weighted_cpuload(i);
4137 * When comparing with imbalance, use weighted_cpuload()
4138 * which is not scaled with the cpu power.
4140 if (capacity && rq->nr_running == 1 && wl > imbalance)
4141 continue;
4144 * For the load comparisons with the other cpu's, consider
4145 * the weighted_cpuload() scaled with the cpu power, so that
4146 * the load can be moved away from the cpu that is potentially
4147 * running at a lower capacity.
4149 wl = (wl * SCHED_LOAD_SCALE) / power;
4151 if (wl > max_load) {
4152 max_load = wl;
4153 busiest = rq;
4157 return busiest;
4161 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
4162 * so long as it is large enough.
4164 #define MAX_PINNED_INTERVAL 512
4166 /* Working cpumask for load_balance and load_balance_newidle. */
4167 static DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
4170 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4171 * tasks if there is an imbalance.
4173 static int load_balance(int this_cpu, struct rq *this_rq,
4174 struct sched_domain *sd, enum cpu_idle_type idle,
4175 int *balance)
4177 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
4178 struct sched_group *group;
4179 unsigned long imbalance;
4180 struct rq *busiest;
4181 unsigned long flags;
4182 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4184 cpumask_copy(cpus, cpu_active_mask);
4187 * When power savings policy is enabled for the parent domain, idle
4188 * sibling can pick up load irrespective of busy siblings. In this case,
4189 * let the state of idle sibling percolate up as CPU_IDLE, instead of
4190 * portraying it as CPU_NOT_IDLE.
4192 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
4193 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4194 sd_idle = 1;
4196 schedstat_inc(sd, lb_count[idle]);
4198 redo:
4199 update_shares(sd);
4200 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
4201 cpus, balance);
4203 if (*balance == 0)
4204 goto out_balanced;
4206 if (!group) {
4207 schedstat_inc(sd, lb_nobusyg[idle]);
4208 goto out_balanced;
4211 busiest = find_busiest_queue(group, idle, imbalance, cpus);
4212 if (!busiest) {
4213 schedstat_inc(sd, lb_nobusyq[idle]);
4214 goto out_balanced;
4217 BUG_ON(busiest == this_rq);
4219 schedstat_add(sd, lb_imbalance[idle], imbalance);
4221 ld_moved = 0;
4222 if (busiest->nr_running > 1) {
4224 * Attempt to move tasks. If find_busiest_group has found
4225 * an imbalance but busiest->nr_running <= 1, the group is
4226 * still unbalanced. ld_moved simply stays zero, so it is
4227 * correctly treated as an imbalance.
4229 local_irq_save(flags);
4230 double_rq_lock(this_rq, busiest);
4231 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4232 imbalance, sd, idle, &all_pinned);
4233 double_rq_unlock(this_rq, busiest);
4234 local_irq_restore(flags);
4237 * some other cpu did the load balance for us.
4239 if (ld_moved && this_cpu != smp_processor_id())
4240 resched_cpu(this_cpu);
4242 /* All tasks on this runqueue were pinned by CPU affinity */
4243 if (unlikely(all_pinned)) {
4244 cpumask_clear_cpu(cpu_of(busiest), cpus);
4245 if (!cpumask_empty(cpus))
4246 goto redo;
4247 goto out_balanced;
4251 if (!ld_moved) {
4252 schedstat_inc(sd, lb_failed[idle]);
4253 sd->nr_balance_failed++;
4255 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
4257 raw_spin_lock_irqsave(&busiest->lock, flags);
4259 /* don't kick the migration_thread, if the curr
4260 * task on busiest cpu can't be moved to this_cpu
4262 if (!cpumask_test_cpu(this_cpu,
4263 &busiest->curr->cpus_allowed)) {
4264 raw_spin_unlock_irqrestore(&busiest->lock,
4265 flags);
4266 all_pinned = 1;
4267 goto out_one_pinned;
4270 if (!busiest->active_balance) {
4271 busiest->active_balance = 1;
4272 busiest->push_cpu = this_cpu;
4273 active_balance = 1;
4275 raw_spin_unlock_irqrestore(&busiest->lock, flags);
4276 if (active_balance)
4277 wake_up_process(busiest->migration_thread);
4280 * We've kicked active balancing, reset the failure
4281 * counter.
4283 sd->nr_balance_failed = sd->cache_nice_tries+1;
4285 } else
4286 sd->nr_balance_failed = 0;
4288 if (likely(!active_balance)) {
4289 /* We were unbalanced, so reset the balancing interval */
4290 sd->balance_interval = sd->min_interval;
4291 } else {
4293 * If we've begun active balancing, start to back off. This
4294 * case may not be covered by the all_pinned logic if there
4295 * is only 1 task on the busy runqueue (because we don't call
4296 * move_tasks).
4298 if (sd->balance_interval < sd->max_interval)
4299 sd->balance_interval *= 2;
4302 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4303 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4304 ld_moved = -1;
4306 goto out;
4308 out_balanced:
4309 schedstat_inc(sd, lb_balanced[idle]);
4311 sd->nr_balance_failed = 0;
4313 out_one_pinned:
4314 /* tune up the balancing interval */
4315 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
4316 (sd->balance_interval < sd->max_interval))
4317 sd->balance_interval *= 2;
4319 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4320 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4321 ld_moved = -1;
4322 else
4323 ld_moved = 0;
4324 out:
4325 if (ld_moved)
4326 update_shares(sd);
4327 return ld_moved;
4331 * Check this_cpu to ensure it is balanced within domain. Attempt to move
4332 * tasks if there is an imbalance.
4334 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
4335 * this_rq is locked.
4337 static int
4338 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
4340 struct sched_group *group;
4341 struct rq *busiest = NULL;
4342 unsigned long imbalance;
4343 int ld_moved = 0;
4344 int sd_idle = 0;
4345 int all_pinned = 0;
4346 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
4348 cpumask_copy(cpus, cpu_active_mask);
4351 * When power savings policy is enabled for the parent domain, idle
4352 * sibling can pick up load irrespective of busy siblings. In this case,
4353 * let the state of idle sibling percolate up as IDLE, instead of
4354 * portraying it as CPU_NOT_IDLE.
4356 if (sd->flags & SD_SHARE_CPUPOWER &&
4357 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4358 sd_idle = 1;
4360 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
4361 redo:
4362 update_shares_locked(this_rq, sd);
4363 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
4364 &sd_idle, cpus, NULL);
4365 if (!group) {
4366 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
4367 goto out_balanced;
4370 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
4371 if (!busiest) {
4372 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
4373 goto out_balanced;
4376 BUG_ON(busiest == this_rq);
4378 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
4380 ld_moved = 0;
4381 if (busiest->nr_running > 1) {
4382 /* Attempt to move tasks */
4383 double_lock_balance(this_rq, busiest);
4384 /* this_rq->clock is already updated */
4385 update_rq_clock(busiest);
4386 ld_moved = move_tasks(this_rq, this_cpu, busiest,
4387 imbalance, sd, CPU_NEWLY_IDLE,
4388 &all_pinned);
4389 double_unlock_balance(this_rq, busiest);
4391 if (unlikely(all_pinned)) {
4392 cpumask_clear_cpu(cpu_of(busiest), cpus);
4393 if (!cpumask_empty(cpus))
4394 goto redo;
4398 if (!ld_moved) {
4399 int active_balance = 0;
4401 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
4402 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4403 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4404 return -1;
4406 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
4407 return -1;
4409 if (sd->nr_balance_failed++ < 2)
4410 return -1;
4413 * The only task running in a non-idle cpu can be moved to this
4414 * cpu in an attempt to completely freeup the other CPU
4415 * package. The same method used to move task in load_balance()
4416 * have been extended for load_balance_newidle() to speedup
4417 * consolidation at sched_mc=POWERSAVINGS_BALANCE_WAKEUP (2)
4419 * The package power saving logic comes from
4420 * find_busiest_group(). If there are no imbalance, then
4421 * f_b_g() will return NULL. However when sched_mc={1,2} then
4422 * f_b_g() will select a group from which a running task may be
4423 * pulled to this cpu in order to make the other package idle.
4424 * If there is no opportunity to make a package idle and if
4425 * there are no imbalance, then f_b_g() will return NULL and no
4426 * action will be taken in load_balance_newidle().
4428 * Under normal task pull operation due to imbalance, there
4429 * will be more than one task in the source run queue and
4430 * move_tasks() will succeed. ld_moved will be true and this
4431 * active balance code will not be triggered.
4434 /* Lock busiest in correct order while this_rq is held */
4435 double_lock_balance(this_rq, busiest);
4438 * don't kick the migration_thread, if the curr
4439 * task on busiest cpu can't be moved to this_cpu
4441 if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) {
4442 double_unlock_balance(this_rq, busiest);
4443 all_pinned = 1;
4444 return ld_moved;
4447 if (!busiest->active_balance) {
4448 busiest->active_balance = 1;
4449 busiest->push_cpu = this_cpu;
4450 active_balance = 1;
4453 double_unlock_balance(this_rq, busiest);
4455 * Should not call ttwu while holding a rq->lock
4457 raw_spin_unlock(&this_rq->lock);
4458 if (active_balance)
4459 wake_up_process(busiest->migration_thread);
4460 raw_spin_lock(&this_rq->lock);
4462 } else
4463 sd->nr_balance_failed = 0;
4465 update_shares_locked(this_rq, sd);
4466 return ld_moved;
4468 out_balanced:
4469 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
4470 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
4471 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
4472 return -1;
4473 sd->nr_balance_failed = 0;
4475 return 0;
4479 * idle_balance is called by schedule() if this_cpu is about to become
4480 * idle. Attempts to pull tasks from other CPUs.
4482 static void idle_balance(int this_cpu, struct rq *this_rq)
4484 struct sched_domain *sd;
4485 int pulled_task = 0;
4486 unsigned long next_balance = jiffies + HZ;
4488 this_rq->idle_stamp = this_rq->clock;
4490 if (this_rq->avg_idle < sysctl_sched_migration_cost)
4491 return;
4493 for_each_domain(this_cpu, sd) {
4494 unsigned long interval;
4496 if (!(sd->flags & SD_LOAD_BALANCE))
4497 continue;
4499 if (sd->flags & SD_BALANCE_NEWIDLE)
4500 /* If we've pulled tasks over stop searching: */
4501 pulled_task = load_balance_newidle(this_cpu, this_rq,
4502 sd);
4504 interval = msecs_to_jiffies(sd->balance_interval);
4505 if (time_after(next_balance, sd->last_balance + interval))
4506 next_balance = sd->last_balance + interval;
4507 if (pulled_task) {
4508 this_rq->idle_stamp = 0;
4509 break;
4512 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
4514 * We are going idle. next_balance may be set based on
4515 * a busy processor. So reset next_balance.
4517 this_rq->next_balance = next_balance;
4522 * active_load_balance is run by migration threads. It pushes running tasks
4523 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
4524 * running on each physical CPU where possible, and avoids physical /
4525 * logical imbalances.
4527 * Called with busiest_rq locked.
4529 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
4531 int target_cpu = busiest_rq->push_cpu;
4532 struct sched_domain *sd;
4533 struct rq *target_rq;
4535 /* Is there any task to move? */
4536 if (busiest_rq->nr_running <= 1)
4537 return;
4539 target_rq = cpu_rq(target_cpu);
4542 * This condition is "impossible", if it occurs
4543 * we need to fix it. Originally reported by
4544 * Bjorn Helgaas on a 128-cpu setup.
4546 BUG_ON(busiest_rq == target_rq);
4548 /* move a task from busiest_rq to target_rq */
4549 double_lock_balance(busiest_rq, target_rq);
4550 update_rq_clock(busiest_rq);
4551 update_rq_clock(target_rq);
4553 /* Search for an sd spanning us and the target CPU. */
4554 for_each_domain(target_cpu, sd) {
4555 if ((sd->flags & SD_LOAD_BALANCE) &&
4556 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
4557 break;
4560 if (likely(sd)) {
4561 schedstat_inc(sd, alb_count);
4563 if (move_one_task(target_rq, target_cpu, busiest_rq,
4564 sd, CPU_IDLE))
4565 schedstat_inc(sd, alb_pushed);
4566 else
4567 schedstat_inc(sd, alb_failed);
4569 double_unlock_balance(busiest_rq, target_rq);
4572 #ifdef CONFIG_NO_HZ
4573 static struct {
4574 atomic_t load_balancer;
4575 cpumask_var_t cpu_mask;
4576 cpumask_var_t ilb_grp_nohz_mask;
4577 } nohz ____cacheline_aligned = {
4578 .load_balancer = ATOMIC_INIT(-1),
4581 int get_nohz_load_balancer(void)
4583 return atomic_read(&nohz.load_balancer);
4586 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
4588 * lowest_flag_domain - Return lowest sched_domain containing flag.
4589 * @cpu: The cpu whose lowest level of sched domain is to
4590 * be returned.
4591 * @flag: The flag to check for the lowest sched_domain
4592 * for the given cpu.
4594 * Returns the lowest sched_domain of a cpu which contains the given flag.
4596 static inline struct sched_domain *lowest_flag_domain(int cpu, int flag)
4598 struct sched_domain *sd;
4600 for_each_domain(cpu, sd)
4601 if (sd && (sd->flags & flag))
4602 break;
4604 return sd;
4608 * for_each_flag_domain - Iterates over sched_domains containing the flag.
4609 * @cpu: The cpu whose domains we're iterating over.
4610 * @sd: variable holding the value of the power_savings_sd
4611 * for cpu.
4612 * @flag: The flag to filter the sched_domains to be iterated.
4614 * Iterates over all the scheduler domains for a given cpu that has the 'flag'
4615 * set, starting from the lowest sched_domain to the highest.
4617 #define for_each_flag_domain(cpu, sd, flag) \
4618 for (sd = lowest_flag_domain(cpu, flag); \
4619 (sd && (sd->flags & flag)); sd = sd->parent)
4622 * is_semi_idle_group - Checks if the given sched_group is semi-idle.
4623 * @ilb_group: group to be checked for semi-idleness
4625 * Returns: 1 if the group is semi-idle. 0 otherwise.
4627 * We define a sched_group to be semi idle if it has atleast one idle-CPU
4628 * and atleast one non-idle CPU. This helper function checks if the given
4629 * sched_group is semi-idle or not.
4631 static inline int is_semi_idle_group(struct sched_group *ilb_group)
4633 cpumask_and(nohz.ilb_grp_nohz_mask, nohz.cpu_mask,
4634 sched_group_cpus(ilb_group));
4637 * A sched_group is semi-idle when it has atleast one busy cpu
4638 * and atleast one idle cpu.
4640 if (cpumask_empty(nohz.ilb_grp_nohz_mask))
4641 return 0;
4643 if (cpumask_equal(nohz.ilb_grp_nohz_mask, sched_group_cpus(ilb_group)))
4644 return 0;
4646 return 1;
4649 * find_new_ilb - Finds the optimum idle load balancer for nomination.
4650 * @cpu: The cpu which is nominating a new idle_load_balancer.
4652 * Returns: Returns the id of the idle load balancer if it exists,
4653 * Else, returns >= nr_cpu_ids.
4655 * This algorithm picks the idle load balancer such that it belongs to a
4656 * semi-idle powersavings sched_domain. The idea is to try and avoid
4657 * completely idle packages/cores just for the purpose of idle load balancing
4658 * when there are other idle cpu's which are better suited for that job.
4660 static int find_new_ilb(int cpu)
4662 struct sched_domain *sd;
4663 struct sched_group *ilb_group;
4666 * Have idle load balancer selection from semi-idle packages only
4667 * when power-aware load balancing is enabled
4669 if (!(sched_smt_power_savings || sched_mc_power_savings))
4670 goto out_done;
4673 * Optimize for the case when we have no idle CPUs or only one
4674 * idle CPU. Don't walk the sched_domain hierarchy in such cases
4676 if (cpumask_weight(nohz.cpu_mask) < 2)
4677 goto out_done;
4679 for_each_flag_domain(cpu, sd, SD_POWERSAVINGS_BALANCE) {
4680 ilb_group = sd->groups;
4682 do {
4683 if (is_semi_idle_group(ilb_group))
4684 return cpumask_first(nohz.ilb_grp_nohz_mask);
4686 ilb_group = ilb_group->next;
4688 } while (ilb_group != sd->groups);
4691 out_done:
4692 return cpumask_first(nohz.cpu_mask);
4694 #else /* (CONFIG_SCHED_MC || CONFIG_SCHED_SMT) */
4695 static inline int find_new_ilb(int call_cpu)
4697 return cpumask_first(nohz.cpu_mask);
4699 #endif
4702 * This routine will try to nominate the ilb (idle load balancing)
4703 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
4704 * load balancing on behalf of all those cpus. If all the cpus in the system
4705 * go into this tickless mode, then there will be no ilb owner (as there is
4706 * no need for one) and all the cpus will sleep till the next wakeup event
4707 * arrives...
4709 * For the ilb owner, tick is not stopped. And this tick will be used
4710 * for idle load balancing. ilb owner will still be part of
4711 * nohz.cpu_mask..
4713 * While stopping the tick, this cpu will become the ilb owner if there
4714 * is no other owner. And will be the owner till that cpu becomes busy
4715 * or if all cpus in the system stop their ticks at which point
4716 * there is no need for ilb owner.
4718 * When the ilb owner becomes busy, it nominates another owner, during the
4719 * next busy scheduler_tick()
4721 int select_nohz_load_balancer(int stop_tick)
4723 int cpu = smp_processor_id();
4725 if (stop_tick) {
4726 cpu_rq(cpu)->in_nohz_recently = 1;
4728 if (!cpu_active(cpu)) {
4729 if (atomic_read(&nohz.load_balancer) != cpu)
4730 return 0;
4733 * If we are going offline and still the leader,
4734 * give up!
4736 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4737 BUG();
4739 return 0;
4742 cpumask_set_cpu(cpu, nohz.cpu_mask);
4744 /* time for ilb owner also to sleep */
4745 if (cpumask_weight(nohz.cpu_mask) == num_active_cpus()) {
4746 if (atomic_read(&nohz.load_balancer) == cpu)
4747 atomic_set(&nohz.load_balancer, -1);
4748 return 0;
4751 if (atomic_read(&nohz.load_balancer) == -1) {
4752 /* make me the ilb owner */
4753 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
4754 return 1;
4755 } else if (atomic_read(&nohz.load_balancer) == cpu) {
4756 int new_ilb;
4758 if (!(sched_smt_power_savings ||
4759 sched_mc_power_savings))
4760 return 1;
4762 * Check to see if there is a more power-efficient
4763 * ilb.
4765 new_ilb = find_new_ilb(cpu);
4766 if (new_ilb < nr_cpu_ids && new_ilb != cpu) {
4767 atomic_set(&nohz.load_balancer, -1);
4768 resched_cpu(new_ilb);
4769 return 0;
4771 return 1;
4773 } else {
4774 if (!cpumask_test_cpu(cpu, nohz.cpu_mask))
4775 return 0;
4777 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4779 if (atomic_read(&nohz.load_balancer) == cpu)
4780 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
4781 BUG();
4783 return 0;
4785 #endif
4787 static DEFINE_SPINLOCK(balancing);
4790 * It checks each scheduling domain to see if it is due to be balanced,
4791 * and initiates a balancing operation if so.
4793 * Balancing parameters are set up in arch_init_sched_domains.
4795 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4797 int balance = 1;
4798 struct rq *rq = cpu_rq(cpu);
4799 unsigned long interval;
4800 struct sched_domain *sd;
4801 /* Earliest time when we have to do rebalance again */
4802 unsigned long next_balance = jiffies + 60*HZ;
4803 int update_next_balance = 0;
4804 int need_serialize;
4806 for_each_domain(cpu, sd) {
4807 if (!(sd->flags & SD_LOAD_BALANCE))
4808 continue;
4810 interval = sd->balance_interval;
4811 if (idle != CPU_IDLE)
4812 interval *= sd->busy_factor;
4814 /* scale ms to jiffies */
4815 interval = msecs_to_jiffies(interval);
4816 if (unlikely(!interval))
4817 interval = 1;
4818 if (interval > HZ*NR_CPUS/10)
4819 interval = HZ*NR_CPUS/10;
4821 need_serialize = sd->flags & SD_SERIALIZE;
4823 if (need_serialize) {
4824 if (!spin_trylock(&balancing))
4825 goto out;
4828 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4829 if (load_balance(cpu, rq, sd, idle, &balance)) {
4831 * We've pulled tasks over so either we're no
4832 * longer idle, or one of our SMT siblings is
4833 * not idle.
4835 idle = CPU_NOT_IDLE;
4837 sd->last_balance = jiffies;
4839 if (need_serialize)
4840 spin_unlock(&balancing);
4841 out:
4842 if (time_after(next_balance, sd->last_balance + interval)) {
4843 next_balance = sd->last_balance + interval;
4844 update_next_balance = 1;
4848 * Stop the load balance at this level. There is another
4849 * CPU in our sched group which is doing load balancing more
4850 * actively.
4852 if (!balance)
4853 break;
4857 * next_balance will be updated only when there is a need.
4858 * When the cpu is attached to null domain for ex, it will not be
4859 * updated.
4861 if (likely(update_next_balance))
4862 rq->next_balance = next_balance;
4866 * run_rebalance_domains is triggered when needed from the scheduler tick.
4867 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4868 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4870 static void run_rebalance_domains(struct softirq_action *h)
4872 int this_cpu = smp_processor_id();
4873 struct rq *this_rq = cpu_rq(this_cpu);
4874 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4875 CPU_IDLE : CPU_NOT_IDLE;
4877 rebalance_domains(this_cpu, idle);
4879 #ifdef CONFIG_NO_HZ
4881 * If this cpu is the owner for idle load balancing, then do the
4882 * balancing on behalf of the other idle cpus whose ticks are
4883 * stopped.
4885 if (this_rq->idle_at_tick &&
4886 atomic_read(&nohz.load_balancer) == this_cpu) {
4887 struct rq *rq;
4888 int balance_cpu;
4890 for_each_cpu(balance_cpu, nohz.cpu_mask) {
4891 if (balance_cpu == this_cpu)
4892 continue;
4895 * If this cpu gets work to do, stop the load balancing
4896 * work being done for other cpus. Next load
4897 * balancing owner will pick it up.
4899 if (need_resched())
4900 break;
4902 rebalance_domains(balance_cpu, CPU_IDLE);
4904 rq = cpu_rq(balance_cpu);
4905 if (time_after(this_rq->next_balance, rq->next_balance))
4906 this_rq->next_balance = rq->next_balance;
4909 #endif
4912 static inline int on_null_domain(int cpu)
4914 return !rcu_dereference(cpu_rq(cpu)->sd);
4918 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4920 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4921 * idle load balancing owner or decide to stop the periodic load balancing,
4922 * if the whole system is idle.
4924 static inline void trigger_load_balance(struct rq *rq, int cpu)
4926 #ifdef CONFIG_NO_HZ
4928 * If we were in the nohz mode recently and busy at the current
4929 * scheduler tick, then check if we need to nominate new idle
4930 * load balancer.
4932 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4933 rq->in_nohz_recently = 0;
4935 if (atomic_read(&nohz.load_balancer) == cpu) {
4936 cpumask_clear_cpu(cpu, nohz.cpu_mask);
4937 atomic_set(&nohz.load_balancer, -1);
4940 if (atomic_read(&nohz.load_balancer) == -1) {
4941 int ilb = find_new_ilb(cpu);
4943 if (ilb < nr_cpu_ids)
4944 resched_cpu(ilb);
4949 * If this cpu is idle and doing idle load balancing for all the
4950 * cpus with ticks stopped, is it time for that to stop?
4952 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4953 cpumask_weight(nohz.cpu_mask) == num_online_cpus()) {
4954 resched_cpu(cpu);
4955 return;
4959 * If this cpu is idle and the idle load balancing is done by
4960 * someone else, then no need raise the SCHED_SOFTIRQ
4962 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4963 cpumask_test_cpu(cpu, nohz.cpu_mask))
4964 return;
4965 #endif
4966 /* Don't need to rebalance while attached to NULL domain */
4967 if (time_after_eq(jiffies, rq->next_balance) &&
4968 likely(!on_null_domain(cpu)))
4969 raise_softirq(SCHED_SOFTIRQ);
4972 #else /* CONFIG_SMP */
4975 * on UP we do not need to balance between CPUs:
4977 static inline void idle_balance(int cpu, struct rq *rq)
4981 #endif
4983 DEFINE_PER_CPU(struct kernel_stat, kstat);
4985 EXPORT_PER_CPU_SYMBOL(kstat);
4988 * Return any ns on the sched_clock that have not yet been accounted in
4989 * @p in case that task is currently running.
4991 * Called with task_rq_lock() held on @rq.
4993 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
4995 u64 ns = 0;
4997 if (task_current(rq, p)) {
4998 update_rq_clock(rq);
4999 ns = rq->clock - p->se.exec_start;
5000 if ((s64)ns < 0)
5001 ns = 0;
5004 return ns;
5007 unsigned long long task_delta_exec(struct task_struct *p)
5009 unsigned long flags;
5010 struct rq *rq;
5011 u64 ns = 0;
5013 rq = task_rq_lock(p, &flags);
5014 ns = do_task_delta_exec(p, rq);
5015 task_rq_unlock(rq, &flags);
5017 return ns;
5021 * Return accounted runtime for the task.
5022 * In case the task is currently running, return the runtime plus current's
5023 * pending runtime that have not been accounted yet.
5025 unsigned long long task_sched_runtime(struct task_struct *p)
5027 unsigned long flags;
5028 struct rq *rq;
5029 u64 ns = 0;
5031 rq = task_rq_lock(p, &flags);
5032 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
5033 task_rq_unlock(rq, &flags);
5035 return ns;
5039 * Return sum_exec_runtime for the thread group.
5040 * In case the task is currently running, return the sum plus current's
5041 * pending runtime that have not been accounted yet.
5043 * Note that the thread group might have other running tasks as well,
5044 * so the return value not includes other pending runtime that other
5045 * running tasks might have.
5047 unsigned long long thread_group_sched_runtime(struct task_struct *p)
5049 struct task_cputime totals;
5050 unsigned long flags;
5051 struct rq *rq;
5052 u64 ns;
5054 rq = task_rq_lock(p, &flags);
5055 thread_group_cputime(p, &totals);
5056 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
5057 task_rq_unlock(rq, &flags);
5059 return ns;
5063 * Account user cpu time to a process.
5064 * @p: the process that the cpu time gets accounted to
5065 * @cputime: the cpu time spent in user space since the last update
5066 * @cputime_scaled: cputime scaled by cpu frequency
5068 void account_user_time(struct task_struct *p, cputime_t cputime,
5069 cputime_t cputime_scaled)
5071 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5072 cputime64_t tmp;
5074 /* Add user time to process. */
5075 p->utime = cputime_add(p->utime, cputime);
5076 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
5077 account_group_user_time(p, cputime);
5079 /* Add user time to cpustat. */
5080 tmp = cputime_to_cputime64(cputime);
5081 if (TASK_NICE(p) > 0)
5082 cpustat->nice = cputime64_add(cpustat->nice, tmp);
5083 else
5084 cpustat->user = cputime64_add(cpustat->user, tmp);
5086 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
5087 /* Account for user time used */
5088 acct_update_integrals(p);
5092 * Account guest cpu time to a process.
5093 * @p: the process that the cpu time gets accounted to
5094 * @cputime: the cpu time spent in virtual machine since the last update
5095 * @cputime_scaled: cputime scaled by cpu frequency
5097 static void account_guest_time(struct task_struct *p, cputime_t cputime,
5098 cputime_t cputime_scaled)
5100 cputime64_t tmp;
5101 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5103 tmp = cputime_to_cputime64(cputime);
5105 /* Add guest time to process. */
5106 p->utime = cputime_add(p->utime, cputime);
5107 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
5108 account_group_user_time(p, cputime);
5109 p->gtime = cputime_add(p->gtime, cputime);
5111 /* Add guest time to cpustat. */
5112 if (TASK_NICE(p) > 0) {
5113 cpustat->nice = cputime64_add(cpustat->nice, tmp);
5114 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
5115 } else {
5116 cpustat->user = cputime64_add(cpustat->user, tmp);
5117 cpustat->guest = cputime64_add(cpustat->guest, tmp);
5122 * Account system cpu time to a process.
5123 * @p: the process that the cpu time gets accounted to
5124 * @hardirq_offset: the offset to subtract from hardirq_count()
5125 * @cputime: the cpu time spent in kernel space since the last update
5126 * @cputime_scaled: cputime scaled by cpu frequency
5128 void account_system_time(struct task_struct *p, int hardirq_offset,
5129 cputime_t cputime, cputime_t cputime_scaled)
5131 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5132 cputime64_t tmp;
5134 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
5135 account_guest_time(p, cputime, cputime_scaled);
5136 return;
5139 /* Add system time to process. */
5140 p->stime = cputime_add(p->stime, cputime);
5141 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
5142 account_group_system_time(p, cputime);
5144 /* Add system time to cpustat. */
5145 tmp = cputime_to_cputime64(cputime);
5146 if (hardirq_count() - hardirq_offset)
5147 cpustat->irq = cputime64_add(cpustat->irq, tmp);
5148 else if (softirq_count())
5149 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
5150 else
5151 cpustat->system = cputime64_add(cpustat->system, tmp);
5153 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
5155 /* Account for system time used */
5156 acct_update_integrals(p);
5160 * Account for involuntary wait time.
5161 * @steal: the cpu time spent in involuntary wait
5163 void account_steal_time(cputime_t cputime)
5165 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5166 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5168 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
5172 * Account for idle time.
5173 * @cputime: the cpu time spent in idle wait
5175 void account_idle_time(cputime_t cputime)
5177 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
5178 cputime64_t cputime64 = cputime_to_cputime64(cputime);
5179 struct rq *rq = this_rq();
5181 if (atomic_read(&rq->nr_iowait) > 0)
5182 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
5183 else
5184 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
5187 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
5190 * Account a single tick of cpu time.
5191 * @p: the process that the cpu time gets accounted to
5192 * @user_tick: indicates if the tick is a user or a system tick
5194 void account_process_tick(struct task_struct *p, int user_tick)
5196 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
5197 struct rq *rq = this_rq();
5199 if (user_tick)
5200 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
5201 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
5202 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
5203 one_jiffy_scaled);
5204 else
5205 account_idle_time(cputime_one_jiffy);
5209 * Account multiple ticks of steal time.
5210 * @p: the process from which the cpu time has been stolen
5211 * @ticks: number of stolen ticks
5213 void account_steal_ticks(unsigned long ticks)
5215 account_steal_time(jiffies_to_cputime(ticks));
5219 * Account multiple ticks of idle time.
5220 * @ticks: number of stolen ticks
5222 void account_idle_ticks(unsigned long ticks)
5224 account_idle_time(jiffies_to_cputime(ticks));
5227 #endif
5230 * Use precise platform statistics if available:
5232 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
5233 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5235 *ut = p->utime;
5236 *st = p->stime;
5239 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5241 struct task_cputime cputime;
5243 thread_group_cputime(p, &cputime);
5245 *ut = cputime.utime;
5246 *st = cputime.stime;
5248 #else
5250 #ifndef nsecs_to_cputime
5251 # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
5252 #endif
5254 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5256 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
5259 * Use CFS's precise accounting:
5261 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
5263 if (total) {
5264 u64 temp = rtime;
5266 temp *= utime;
5267 do_div(temp, total);
5268 utime = (cputime_t)temp;
5269 } else
5270 utime = rtime;
5273 * Compare with previous values, to keep monotonicity:
5275 p->prev_utime = max(p->prev_utime, utime);
5276 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
5278 *ut = p->prev_utime;
5279 *st = p->prev_stime;
5283 * Must be called with siglock held.
5285 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
5287 struct signal_struct *sig = p->signal;
5288 struct task_cputime cputime;
5289 cputime_t rtime, utime, total;
5291 thread_group_cputime(p, &cputime);
5293 total = cputime_add(cputime.utime, cputime.stime);
5294 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
5296 if (total) {
5297 u64 temp = rtime;
5299 temp *= cputime.utime;
5300 do_div(temp, total);
5301 utime = (cputime_t)temp;
5302 } else
5303 utime = rtime;
5305 sig->prev_utime = max(sig->prev_utime, utime);
5306 sig->prev_stime = max(sig->prev_stime,
5307 cputime_sub(rtime, sig->prev_utime));
5309 *ut = sig->prev_utime;
5310 *st = sig->prev_stime;
5312 #endif
5315 * This function gets called by the timer code, with HZ frequency.
5316 * We call it with interrupts disabled.
5318 * It also gets called by the fork code, when changing the parent's
5319 * timeslices.
5321 void scheduler_tick(void)
5323 int cpu = smp_processor_id();
5324 struct rq *rq = cpu_rq(cpu);
5325 struct task_struct *curr = rq->curr;
5327 sched_clock_tick();
5329 raw_spin_lock(&rq->lock);
5330 update_rq_clock(rq);
5331 update_cpu_load(rq);
5332 curr->sched_class->task_tick(rq, curr, 0);
5333 raw_spin_unlock(&rq->lock);
5335 perf_event_task_tick(curr, cpu);
5337 #ifdef CONFIG_SMP
5338 rq->idle_at_tick = idle_cpu(cpu);
5339 trigger_load_balance(rq, cpu);
5340 #endif
5343 notrace unsigned long get_parent_ip(unsigned long addr)
5345 if (in_lock_functions(addr)) {
5346 addr = CALLER_ADDR2;
5347 if (in_lock_functions(addr))
5348 addr = CALLER_ADDR3;
5350 return addr;
5353 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
5354 defined(CONFIG_PREEMPT_TRACER))
5356 void __kprobes add_preempt_count(int val)
5358 #ifdef CONFIG_DEBUG_PREEMPT
5360 * Underflow?
5362 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
5363 return;
5364 #endif
5365 preempt_count() += val;
5366 #ifdef CONFIG_DEBUG_PREEMPT
5368 * Spinlock count overflowing soon?
5370 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
5371 PREEMPT_MASK - 10);
5372 #endif
5373 if (preempt_count() == val)
5374 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5376 EXPORT_SYMBOL(add_preempt_count);
5378 void __kprobes sub_preempt_count(int val)
5380 #ifdef CONFIG_DEBUG_PREEMPT
5382 * Underflow?
5384 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
5385 return;
5387 * Is the spinlock portion underflowing?
5389 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
5390 !(preempt_count() & PREEMPT_MASK)))
5391 return;
5392 #endif
5394 if (preempt_count() == val)
5395 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
5396 preempt_count() -= val;
5398 EXPORT_SYMBOL(sub_preempt_count);
5400 #endif
5403 * Print scheduling while atomic bug:
5405 static noinline void __schedule_bug(struct task_struct *prev)
5407 struct pt_regs *regs = get_irq_regs();
5409 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
5410 prev->comm, prev->pid, preempt_count());
5412 debug_show_held_locks(prev);
5413 print_modules();
5414 if (irqs_disabled())
5415 print_irqtrace_events(prev);
5417 if (regs)
5418 show_regs(regs);
5419 else
5420 dump_stack();
5424 * Various schedule()-time debugging checks and statistics:
5426 static inline void schedule_debug(struct task_struct *prev)
5429 * Test if we are atomic. Since do_exit() needs to call into
5430 * schedule() atomically, we ignore that path for now.
5431 * Otherwise, whine if we are scheduling when we should not be.
5433 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
5434 __schedule_bug(prev);
5436 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
5438 schedstat_inc(this_rq(), sched_count);
5439 #ifdef CONFIG_SCHEDSTATS
5440 if (unlikely(prev->lock_depth >= 0)) {
5441 schedstat_inc(this_rq(), bkl_count);
5442 schedstat_inc(prev, sched_info.bkl_count);
5444 #endif
5447 static void put_prev_task(struct rq *rq, struct task_struct *prev)
5449 if (prev->state == TASK_RUNNING) {
5450 u64 runtime = prev->se.sum_exec_runtime;
5452 runtime -= prev->se.prev_sum_exec_runtime;
5453 runtime = min_t(u64, runtime, 2*sysctl_sched_migration_cost);
5456 * In order to avoid avg_overlap growing stale when we are
5457 * indeed overlapping and hence not getting put to sleep, grow
5458 * the avg_overlap on preemption.
5460 * We use the average preemption runtime because that
5461 * correlates to the amount of cache footprint a task can
5462 * build up.
5464 update_avg(&prev->se.avg_overlap, runtime);
5466 prev->sched_class->put_prev_task(rq, prev);
5470 * Pick up the highest-prio task:
5472 static inline struct task_struct *
5473 pick_next_task(struct rq *rq)
5475 const struct sched_class *class;
5476 struct task_struct *p;
5479 * Optimization: we know that if all tasks are in
5480 * the fair class we can call that function directly:
5482 if (likely(rq->nr_running == rq->cfs.nr_running)) {
5483 p = fair_sched_class.pick_next_task(rq);
5484 if (likely(p))
5485 return p;
5488 class = sched_class_highest;
5489 for ( ; ; ) {
5490 p = class->pick_next_task(rq);
5491 if (p)
5492 return p;
5494 * Will never be NULL as the idle class always
5495 * returns a non-NULL p:
5497 class = class->next;
5502 * schedule() is the main scheduler function.
5504 asmlinkage void __sched schedule(void)
5506 struct task_struct *prev, *next;
5507 unsigned long *switch_count;
5508 struct rq *rq;
5509 int cpu;
5511 need_resched:
5512 preempt_disable();
5513 cpu = smp_processor_id();
5514 rq = cpu_rq(cpu);
5515 rcu_sched_qs(cpu);
5516 prev = rq->curr;
5517 switch_count = &prev->nivcsw;
5519 release_kernel_lock(prev);
5520 need_resched_nonpreemptible:
5522 schedule_debug(prev);
5524 if (sched_feat(HRTICK))
5525 hrtick_clear(rq);
5527 raw_spin_lock_irq(&rq->lock);
5528 update_rq_clock(rq);
5529 clear_tsk_need_resched(prev);
5531 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
5532 if (unlikely(signal_pending_state(prev->state, prev)))
5533 prev->state = TASK_RUNNING;
5534 else
5535 deactivate_task(rq, prev, 1);
5536 switch_count = &prev->nvcsw;
5539 pre_schedule(rq, prev);
5541 if (unlikely(!rq->nr_running))
5542 idle_balance(cpu, rq);
5544 put_prev_task(rq, prev);
5545 next = pick_next_task(rq);
5547 if (likely(prev != next)) {
5548 sched_info_switch(prev, next);
5549 perf_event_task_sched_out(prev, next, cpu);
5551 rq->nr_switches++;
5552 rq->curr = next;
5553 ++*switch_count;
5555 context_switch(rq, prev, next); /* unlocks the rq */
5557 * the context switch might have flipped the stack from under
5558 * us, hence refresh the local variables.
5560 cpu = smp_processor_id();
5561 rq = cpu_rq(cpu);
5562 } else
5563 raw_spin_unlock_irq(&rq->lock);
5565 post_schedule(rq);
5567 if (unlikely(reacquire_kernel_lock(current) < 0)) {
5568 prev = rq->curr;
5569 switch_count = &prev->nivcsw;
5570 goto need_resched_nonpreemptible;
5573 preempt_enable_no_resched();
5574 if (need_resched())
5575 goto need_resched;
5577 EXPORT_SYMBOL(schedule);
5579 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
5581 * Look out! "owner" is an entirely speculative pointer
5582 * access and not reliable.
5584 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
5586 unsigned int cpu;
5587 struct rq *rq;
5589 if (!sched_feat(OWNER_SPIN))
5590 return 0;
5592 #ifdef CONFIG_DEBUG_PAGEALLOC
5594 * Need to access the cpu field knowing that
5595 * DEBUG_PAGEALLOC could have unmapped it if
5596 * the mutex owner just released it and exited.
5598 if (probe_kernel_address(&owner->cpu, cpu))
5599 goto out;
5600 #else
5601 cpu = owner->cpu;
5602 #endif
5605 * Even if the access succeeded (likely case),
5606 * the cpu field may no longer be valid.
5608 if (cpu >= nr_cpumask_bits)
5609 goto out;
5612 * We need to validate that we can do a
5613 * get_cpu() and that we have the percpu area.
5615 if (!cpu_online(cpu))
5616 goto out;
5618 rq = cpu_rq(cpu);
5620 for (;;) {
5622 * Owner changed, break to re-assess state.
5624 if (lock->owner != owner)
5625 break;
5628 * Is that owner really running on that cpu?
5630 if (task_thread_info(rq->curr) != owner || need_resched())
5631 return 0;
5633 cpu_relax();
5635 out:
5636 return 1;
5638 #endif
5640 #ifdef CONFIG_PREEMPT
5642 * this is the entry point to schedule() from in-kernel preemption
5643 * off of preempt_enable. Kernel preemptions off return from interrupt
5644 * occur there and call schedule directly.
5646 asmlinkage void __sched preempt_schedule(void)
5648 struct thread_info *ti = current_thread_info();
5651 * If there is a non-zero preempt_count or interrupts are disabled,
5652 * we do not want to preempt the current task. Just return..
5654 if (likely(ti->preempt_count || irqs_disabled()))
5655 return;
5657 do {
5658 add_preempt_count(PREEMPT_ACTIVE);
5659 schedule();
5660 sub_preempt_count(PREEMPT_ACTIVE);
5663 * Check again in case we missed a preemption opportunity
5664 * between schedule and now.
5666 barrier();
5667 } while (need_resched());
5669 EXPORT_SYMBOL(preempt_schedule);
5672 * this is the entry point to schedule() from kernel preemption
5673 * off of irq context.
5674 * Note, that this is called and return with irqs disabled. This will
5675 * protect us against recursive calling from irq.
5677 asmlinkage void __sched preempt_schedule_irq(void)
5679 struct thread_info *ti = current_thread_info();
5681 /* Catch callers which need to be fixed */
5682 BUG_ON(ti->preempt_count || !irqs_disabled());
5684 do {
5685 add_preempt_count(PREEMPT_ACTIVE);
5686 local_irq_enable();
5687 schedule();
5688 local_irq_disable();
5689 sub_preempt_count(PREEMPT_ACTIVE);
5692 * Check again in case we missed a preemption opportunity
5693 * between schedule and now.
5695 barrier();
5696 } while (need_resched());
5699 #endif /* CONFIG_PREEMPT */
5701 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
5702 void *key)
5704 return try_to_wake_up(curr->private, mode, wake_flags);
5706 EXPORT_SYMBOL(default_wake_function);
5709 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
5710 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
5711 * number) then we wake all the non-exclusive tasks and one exclusive task.
5713 * There are circumstances in which we can try to wake a task which has already
5714 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
5715 * zero in this (rare) case, and we handle it by continuing to scan the queue.
5717 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
5718 int nr_exclusive, int wake_flags, void *key)
5720 wait_queue_t *curr, *next;
5722 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
5723 unsigned flags = curr->flags;
5725 if (curr->func(curr, mode, wake_flags, key) &&
5726 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
5727 break;
5732 * __wake_up - wake up threads blocked on a waitqueue.
5733 * @q: the waitqueue
5734 * @mode: which threads
5735 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5736 * @key: is directly passed to the wakeup function
5738 * It may be assumed that this function implies a write memory barrier before
5739 * changing the task state if and only if any tasks are woken up.
5741 void __wake_up(wait_queue_head_t *q, unsigned int mode,
5742 int nr_exclusive, void *key)
5744 unsigned long flags;
5746 spin_lock_irqsave(&q->lock, flags);
5747 __wake_up_common(q, mode, nr_exclusive, 0, key);
5748 spin_unlock_irqrestore(&q->lock, flags);
5750 EXPORT_SYMBOL(__wake_up);
5753 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
5755 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
5757 __wake_up_common(q, mode, 1, 0, NULL);
5760 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
5762 __wake_up_common(q, mode, 1, 0, key);
5766 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
5767 * @q: the waitqueue
5768 * @mode: which threads
5769 * @nr_exclusive: how many wake-one or wake-many threads to wake up
5770 * @key: opaque value to be passed to wakeup targets
5772 * The sync wakeup differs that the waker knows that it will schedule
5773 * away soon, so while the target thread will be woken up, it will not
5774 * be migrated to another CPU - ie. the two threads are 'synchronized'
5775 * with each other. This can prevent needless bouncing between CPUs.
5777 * On UP it can prevent extra preemption.
5779 * It may be assumed that this function implies a write memory barrier before
5780 * changing the task state if and only if any tasks are woken up.
5782 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
5783 int nr_exclusive, void *key)
5785 unsigned long flags;
5786 int wake_flags = WF_SYNC;
5788 if (unlikely(!q))
5789 return;
5791 if (unlikely(!nr_exclusive))
5792 wake_flags = 0;
5794 spin_lock_irqsave(&q->lock, flags);
5795 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
5796 spin_unlock_irqrestore(&q->lock, flags);
5798 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
5801 * __wake_up_sync - see __wake_up_sync_key()
5803 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
5805 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
5807 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
5810 * complete: - signals a single thread waiting on this completion
5811 * @x: holds the state of this particular completion
5813 * This will wake up a single thread waiting on this completion. Threads will be
5814 * awakened in the same order in which they were queued.
5816 * See also complete_all(), wait_for_completion() and related routines.
5818 * It may be assumed that this function implies a write memory barrier before
5819 * changing the task state if and only if any tasks are woken up.
5821 void complete(struct completion *x)
5823 unsigned long flags;
5825 spin_lock_irqsave(&x->wait.lock, flags);
5826 x->done++;
5827 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
5828 spin_unlock_irqrestore(&x->wait.lock, flags);
5830 EXPORT_SYMBOL(complete);
5833 * complete_all: - signals all threads waiting on this completion
5834 * @x: holds the state of this particular completion
5836 * This will wake up all threads waiting on this particular completion event.
5838 * It may be assumed that this function implies a write memory barrier before
5839 * changing the task state if and only if any tasks are woken up.
5841 void complete_all(struct completion *x)
5843 unsigned long flags;
5845 spin_lock_irqsave(&x->wait.lock, flags);
5846 x->done += UINT_MAX/2;
5847 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
5848 spin_unlock_irqrestore(&x->wait.lock, flags);
5850 EXPORT_SYMBOL(complete_all);
5852 static inline long __sched
5853 do_wait_for_common(struct completion *x, long timeout, int state)
5855 if (!x->done) {
5856 DECLARE_WAITQUEUE(wait, current);
5858 wait.flags |= WQ_FLAG_EXCLUSIVE;
5859 __add_wait_queue_tail(&x->wait, &wait);
5860 do {
5861 if (signal_pending_state(state, current)) {
5862 timeout = -ERESTARTSYS;
5863 break;
5865 __set_current_state(state);
5866 spin_unlock_irq(&x->wait.lock);
5867 timeout = schedule_timeout(timeout);
5868 spin_lock_irq(&x->wait.lock);
5869 } while (!x->done && timeout);
5870 __remove_wait_queue(&x->wait, &wait);
5871 if (!x->done)
5872 return timeout;
5874 x->done--;
5875 return timeout ?: 1;
5878 static long __sched
5879 wait_for_common(struct completion *x, long timeout, int state)
5881 might_sleep();
5883 spin_lock_irq(&x->wait.lock);
5884 timeout = do_wait_for_common(x, timeout, state);
5885 spin_unlock_irq(&x->wait.lock);
5886 return timeout;
5890 * wait_for_completion: - waits for completion of a task
5891 * @x: holds the state of this particular completion
5893 * This waits to be signaled for completion of a specific task. It is NOT
5894 * interruptible and there is no timeout.
5896 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
5897 * and interrupt capability. Also see complete().
5899 void __sched wait_for_completion(struct completion *x)
5901 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
5903 EXPORT_SYMBOL(wait_for_completion);
5906 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
5907 * @x: holds the state of this particular completion
5908 * @timeout: timeout value in jiffies
5910 * This waits for either a completion of a specific task to be signaled or for a
5911 * specified timeout to expire. The timeout is in jiffies. It is not
5912 * interruptible.
5914 unsigned long __sched
5915 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
5917 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
5919 EXPORT_SYMBOL(wait_for_completion_timeout);
5922 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
5923 * @x: holds the state of this particular completion
5925 * This waits for completion of a specific task to be signaled. It is
5926 * interruptible.
5928 int __sched wait_for_completion_interruptible(struct completion *x)
5930 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
5931 if (t == -ERESTARTSYS)
5932 return t;
5933 return 0;
5935 EXPORT_SYMBOL(wait_for_completion_interruptible);
5938 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
5939 * @x: holds the state of this particular completion
5940 * @timeout: timeout value in jiffies
5942 * This waits for either a completion of a specific task to be signaled or for a
5943 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
5945 unsigned long __sched
5946 wait_for_completion_interruptible_timeout(struct completion *x,
5947 unsigned long timeout)
5949 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
5951 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
5954 * wait_for_completion_killable: - waits for completion of a task (killable)
5955 * @x: holds the state of this particular completion
5957 * This waits to be signaled for completion of a specific task. It can be
5958 * interrupted by a kill signal.
5960 int __sched wait_for_completion_killable(struct completion *x)
5962 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
5963 if (t == -ERESTARTSYS)
5964 return t;
5965 return 0;
5967 EXPORT_SYMBOL(wait_for_completion_killable);
5970 * try_wait_for_completion - try to decrement a completion without blocking
5971 * @x: completion structure
5973 * Returns: 0 if a decrement cannot be done without blocking
5974 * 1 if a decrement succeeded.
5976 * If a completion is being used as a counting completion,
5977 * attempt to decrement the counter without blocking. This
5978 * enables us to avoid waiting if the resource the completion
5979 * is protecting is not available.
5981 bool try_wait_for_completion(struct completion *x)
5983 unsigned long flags;
5984 int ret = 1;
5986 spin_lock_irqsave(&x->wait.lock, flags);
5987 if (!x->done)
5988 ret = 0;
5989 else
5990 x->done--;
5991 spin_unlock_irqrestore(&x->wait.lock, flags);
5992 return ret;
5994 EXPORT_SYMBOL(try_wait_for_completion);
5997 * completion_done - Test to see if a completion has any waiters
5998 * @x: completion structure
6000 * Returns: 0 if there are waiters (wait_for_completion() in progress)
6001 * 1 if there are no waiters.
6004 bool completion_done(struct completion *x)
6006 unsigned long flags;
6007 int ret = 1;
6009 spin_lock_irqsave(&x->wait.lock, flags);
6010 if (!x->done)
6011 ret = 0;
6012 spin_unlock_irqrestore(&x->wait.lock, flags);
6013 return ret;
6015 EXPORT_SYMBOL(completion_done);
6017 static long __sched
6018 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
6020 unsigned long flags;
6021 wait_queue_t wait;
6023 init_waitqueue_entry(&wait, current);
6025 __set_current_state(state);
6027 spin_lock_irqsave(&q->lock, flags);
6028 __add_wait_queue(q, &wait);
6029 spin_unlock(&q->lock);
6030 timeout = schedule_timeout(timeout);
6031 spin_lock_irq(&q->lock);
6032 __remove_wait_queue(q, &wait);
6033 spin_unlock_irqrestore(&q->lock, flags);
6035 return timeout;
6038 void __sched interruptible_sleep_on(wait_queue_head_t *q)
6040 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
6042 EXPORT_SYMBOL(interruptible_sleep_on);
6044 long __sched
6045 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
6047 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
6049 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
6051 void __sched sleep_on(wait_queue_head_t *q)
6053 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
6055 EXPORT_SYMBOL(sleep_on);
6057 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
6059 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
6061 EXPORT_SYMBOL(sleep_on_timeout);
6063 #ifdef CONFIG_RT_MUTEXES
6066 * rt_mutex_setprio - set the current priority of a task
6067 * @p: task
6068 * @prio: prio value (kernel-internal form)
6070 * This function changes the 'effective' priority of a task. It does
6071 * not touch ->normal_prio like __setscheduler().
6073 * Used by the rt_mutex code to implement priority inheritance logic.
6075 void rt_mutex_setprio(struct task_struct *p, int prio)
6077 unsigned long flags;
6078 int oldprio, on_rq, running;
6079 struct rq *rq;
6080 const struct sched_class *prev_class;
6082 BUG_ON(prio < 0 || prio > MAX_PRIO);
6084 rq = task_rq_lock(p, &flags);
6085 update_rq_clock(rq);
6087 oldprio = p->prio;
6088 prev_class = p->sched_class;
6089 on_rq = p->se.on_rq;
6090 running = task_current(rq, p);
6091 if (on_rq)
6092 dequeue_task(rq, p, 0);
6093 if (running)
6094 p->sched_class->put_prev_task(rq, p);
6096 if (rt_prio(prio))
6097 p->sched_class = &rt_sched_class;
6098 else
6099 p->sched_class = &fair_sched_class;
6101 p->prio = prio;
6103 if (running)
6104 p->sched_class->set_curr_task(rq);
6105 if (on_rq) {
6106 enqueue_task(rq, p, 0);
6108 check_class_changed(rq, p, prev_class, oldprio, running);
6110 task_rq_unlock(rq, &flags);
6113 #endif
6115 void set_user_nice(struct task_struct *p, long nice)
6117 int old_prio, delta, on_rq;
6118 unsigned long flags;
6119 struct rq *rq;
6121 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
6122 return;
6124 * We have to be careful, if called from sys_setpriority(),
6125 * the task might be in the middle of scheduling on another CPU.
6127 rq = task_rq_lock(p, &flags);
6128 update_rq_clock(rq);
6130 * The RT priorities are set via sched_setscheduler(), but we still
6131 * allow the 'normal' nice value to be set - but as expected
6132 * it wont have any effect on scheduling until the task is
6133 * SCHED_FIFO/SCHED_RR:
6135 if (task_has_rt_policy(p)) {
6136 p->static_prio = NICE_TO_PRIO(nice);
6137 goto out_unlock;
6139 on_rq = p->se.on_rq;
6140 if (on_rq)
6141 dequeue_task(rq, p, 0);
6143 p->static_prio = NICE_TO_PRIO(nice);
6144 set_load_weight(p);
6145 old_prio = p->prio;
6146 p->prio = effective_prio(p);
6147 delta = p->prio - old_prio;
6149 if (on_rq) {
6150 enqueue_task(rq, p, 0);
6152 * If the task increased its priority or is running and
6153 * lowered its priority, then reschedule its CPU:
6155 if (delta < 0 || (delta > 0 && task_running(rq, p)))
6156 resched_task(rq->curr);
6158 out_unlock:
6159 task_rq_unlock(rq, &flags);
6161 EXPORT_SYMBOL(set_user_nice);
6164 * can_nice - check if a task can reduce its nice value
6165 * @p: task
6166 * @nice: nice value
6168 int can_nice(const struct task_struct *p, const int nice)
6170 /* convert nice value [19,-20] to rlimit style value [1,40] */
6171 int nice_rlim = 20 - nice;
6173 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
6174 capable(CAP_SYS_NICE));
6177 #ifdef __ARCH_WANT_SYS_NICE
6180 * sys_nice - change the priority of the current process.
6181 * @increment: priority increment
6183 * sys_setpriority is a more generic, but much slower function that
6184 * does similar things.
6186 SYSCALL_DEFINE1(nice, int, increment)
6188 long nice, retval;
6191 * Setpriority might change our priority at the same moment.
6192 * We don't have to worry. Conceptually one call occurs first
6193 * and we have a single winner.
6195 if (increment < -40)
6196 increment = -40;
6197 if (increment > 40)
6198 increment = 40;
6200 nice = TASK_NICE(current) + increment;
6201 if (nice < -20)
6202 nice = -20;
6203 if (nice > 19)
6204 nice = 19;
6206 if (increment < 0 && !can_nice(current, nice))
6207 return -EPERM;
6209 retval = security_task_setnice(current, nice);
6210 if (retval)
6211 return retval;
6213 set_user_nice(current, nice);
6214 return 0;
6217 #endif
6220 * task_prio - return the priority value of a given task.
6221 * @p: the task in question.
6223 * This is the priority value as seen by users in /proc.
6224 * RT tasks are offset by -200. Normal tasks are centered
6225 * around 0, value goes from -16 to +15.
6227 int task_prio(const struct task_struct *p)
6229 return p->prio - MAX_RT_PRIO;
6233 * task_nice - return the nice value of a given task.
6234 * @p: the task in question.
6236 int task_nice(const struct task_struct *p)
6238 return TASK_NICE(p);
6240 EXPORT_SYMBOL(task_nice);
6243 * idle_cpu - is a given cpu idle currently?
6244 * @cpu: the processor in question.
6246 int idle_cpu(int cpu)
6248 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
6252 * idle_task - return the idle task for a given cpu.
6253 * @cpu: the processor in question.
6255 struct task_struct *idle_task(int cpu)
6257 return cpu_rq(cpu)->idle;
6261 * find_process_by_pid - find a process with a matching PID value.
6262 * @pid: the pid in question.
6264 static struct task_struct *find_process_by_pid(pid_t pid)
6266 return pid ? find_task_by_vpid(pid) : current;
6269 /* Actually do priority change: must hold rq lock. */
6270 static void
6271 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
6273 BUG_ON(p->se.on_rq);
6275 p->policy = policy;
6276 p->rt_priority = prio;
6277 p->normal_prio = normal_prio(p);
6278 /* we are holding p->pi_lock already */
6279 p->prio = rt_mutex_getprio(p);
6280 if (rt_prio(p->prio))
6281 p->sched_class = &rt_sched_class;
6282 else
6283 p->sched_class = &fair_sched_class;
6284 set_load_weight(p);
6288 * check the target process has a UID that matches the current process's
6290 static bool check_same_owner(struct task_struct *p)
6292 const struct cred *cred = current_cred(), *pcred;
6293 bool match;
6295 rcu_read_lock();
6296 pcred = __task_cred(p);
6297 match = (cred->euid == pcred->euid ||
6298 cred->euid == pcred->uid);
6299 rcu_read_unlock();
6300 return match;
6303 static int __sched_setscheduler(struct task_struct *p, int policy,
6304 struct sched_param *param, bool user)
6306 int retval, oldprio, oldpolicy = -1, on_rq, running;
6307 unsigned long flags;
6308 const struct sched_class *prev_class;
6309 struct rq *rq;
6310 int reset_on_fork;
6312 /* may grab non-irq protected spin_locks */
6313 BUG_ON(in_interrupt());
6314 recheck:
6315 /* double check policy once rq lock held */
6316 if (policy < 0) {
6317 reset_on_fork = p->sched_reset_on_fork;
6318 policy = oldpolicy = p->policy;
6319 } else {
6320 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
6321 policy &= ~SCHED_RESET_ON_FORK;
6323 if (policy != SCHED_FIFO && policy != SCHED_RR &&
6324 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
6325 policy != SCHED_IDLE)
6326 return -EINVAL;
6330 * Valid priorities for SCHED_FIFO and SCHED_RR are
6331 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
6332 * SCHED_BATCH and SCHED_IDLE is 0.
6334 if (param->sched_priority < 0 ||
6335 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
6336 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
6337 return -EINVAL;
6338 if (rt_policy(policy) != (param->sched_priority != 0))
6339 return -EINVAL;
6342 * Allow unprivileged RT tasks to decrease priority:
6344 if (user && !capable(CAP_SYS_NICE)) {
6345 if (rt_policy(policy)) {
6346 unsigned long rlim_rtprio;
6348 if (!lock_task_sighand(p, &flags))
6349 return -ESRCH;
6350 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
6351 unlock_task_sighand(p, &flags);
6353 /* can't set/change the rt policy */
6354 if (policy != p->policy && !rlim_rtprio)
6355 return -EPERM;
6357 /* can't increase priority */
6358 if (param->sched_priority > p->rt_priority &&
6359 param->sched_priority > rlim_rtprio)
6360 return -EPERM;
6363 * Like positive nice levels, dont allow tasks to
6364 * move out of SCHED_IDLE either:
6366 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
6367 return -EPERM;
6369 /* can't change other user's priorities */
6370 if (!check_same_owner(p))
6371 return -EPERM;
6373 /* Normal users shall not reset the sched_reset_on_fork flag */
6374 if (p->sched_reset_on_fork && !reset_on_fork)
6375 return -EPERM;
6378 if (user) {
6379 #ifdef CONFIG_RT_GROUP_SCHED
6381 * Do not allow realtime tasks into groups that have no runtime
6382 * assigned.
6384 if (rt_bandwidth_enabled() && rt_policy(policy) &&
6385 task_group(p)->rt_bandwidth.rt_runtime == 0)
6386 return -EPERM;
6387 #endif
6389 retval = security_task_setscheduler(p, policy, param);
6390 if (retval)
6391 return retval;
6395 * make sure no PI-waiters arrive (or leave) while we are
6396 * changing the priority of the task:
6398 raw_spin_lock_irqsave(&p->pi_lock, flags);
6400 * To be able to change p->policy safely, the apropriate
6401 * runqueue lock must be held.
6403 rq = __task_rq_lock(p);
6404 /* recheck policy now with rq lock held */
6405 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
6406 policy = oldpolicy = -1;
6407 __task_rq_unlock(rq);
6408 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
6409 goto recheck;
6411 update_rq_clock(rq);
6412 on_rq = p->se.on_rq;
6413 running = task_current(rq, p);
6414 if (on_rq)
6415 deactivate_task(rq, p, 0);
6416 if (running)
6417 p->sched_class->put_prev_task(rq, p);
6419 p->sched_reset_on_fork = reset_on_fork;
6421 oldprio = p->prio;
6422 prev_class = p->sched_class;
6423 __setscheduler(rq, p, policy, param->sched_priority);
6425 if (running)
6426 p->sched_class->set_curr_task(rq);
6427 if (on_rq) {
6428 activate_task(rq, p, 0);
6430 check_class_changed(rq, p, prev_class, oldprio, running);
6432 __task_rq_unlock(rq);
6433 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
6435 rt_mutex_adjust_pi(p);
6437 return 0;
6441 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
6442 * @p: the task in question.
6443 * @policy: new policy.
6444 * @param: structure containing the new RT priority.
6446 * NOTE that the task may be already dead.
6448 int sched_setscheduler(struct task_struct *p, int policy,
6449 struct sched_param *param)
6451 return __sched_setscheduler(p, policy, param, true);
6453 EXPORT_SYMBOL_GPL(sched_setscheduler);
6456 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
6457 * @p: the task in question.
6458 * @policy: new policy.
6459 * @param: structure containing the new RT priority.
6461 * Just like sched_setscheduler, only don't bother checking if the
6462 * current context has permission. For example, this is needed in
6463 * stop_machine(): we create temporary high priority worker threads,
6464 * but our caller might not have that capability.
6466 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
6467 struct sched_param *param)
6469 return __sched_setscheduler(p, policy, param, false);
6472 static int
6473 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
6475 struct sched_param lparam;
6476 struct task_struct *p;
6477 int retval;
6479 if (!param || pid < 0)
6480 return -EINVAL;
6481 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
6482 return -EFAULT;
6484 rcu_read_lock();
6485 retval = -ESRCH;
6486 p = find_process_by_pid(pid);
6487 if (p != NULL)
6488 retval = sched_setscheduler(p, policy, &lparam);
6489 rcu_read_unlock();
6491 return retval;
6495 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
6496 * @pid: the pid in question.
6497 * @policy: new policy.
6498 * @param: structure containing the new RT priority.
6500 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
6501 struct sched_param __user *, param)
6503 /* negative values for policy are not valid */
6504 if (policy < 0)
6505 return -EINVAL;
6507 return do_sched_setscheduler(pid, policy, param);
6511 * sys_sched_setparam - set/change the RT priority of a thread
6512 * @pid: the pid in question.
6513 * @param: structure containing the new RT priority.
6515 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
6517 return do_sched_setscheduler(pid, -1, param);
6521 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
6522 * @pid: the pid in question.
6524 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
6526 struct task_struct *p;
6527 int retval;
6529 if (pid < 0)
6530 return -EINVAL;
6532 retval = -ESRCH;
6533 rcu_read_lock();
6534 p = find_process_by_pid(pid);
6535 if (p) {
6536 retval = security_task_getscheduler(p);
6537 if (!retval)
6538 retval = p->policy
6539 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
6541 rcu_read_unlock();
6542 return retval;
6546 * sys_sched_getparam - get the RT priority of a thread
6547 * @pid: the pid in question.
6548 * @param: structure containing the RT priority.
6550 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
6552 struct sched_param lp;
6553 struct task_struct *p;
6554 int retval;
6556 if (!param || pid < 0)
6557 return -EINVAL;
6559 rcu_read_lock();
6560 p = find_process_by_pid(pid);
6561 retval = -ESRCH;
6562 if (!p)
6563 goto out_unlock;
6565 retval = security_task_getscheduler(p);
6566 if (retval)
6567 goto out_unlock;
6569 lp.sched_priority = p->rt_priority;
6570 rcu_read_unlock();
6573 * This one might sleep, we cannot do it with a spinlock held ...
6575 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
6577 return retval;
6579 out_unlock:
6580 rcu_read_unlock();
6581 return retval;
6584 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
6586 cpumask_var_t cpus_allowed, new_mask;
6587 struct task_struct *p;
6588 int retval;
6590 get_online_cpus();
6591 rcu_read_lock();
6593 p = find_process_by_pid(pid);
6594 if (!p) {
6595 rcu_read_unlock();
6596 put_online_cpus();
6597 return -ESRCH;
6600 /* Prevent p going away */
6601 get_task_struct(p);
6602 rcu_read_unlock();
6604 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
6605 retval = -ENOMEM;
6606 goto out_put_task;
6608 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
6609 retval = -ENOMEM;
6610 goto out_free_cpus_allowed;
6612 retval = -EPERM;
6613 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
6614 goto out_unlock;
6616 retval = security_task_setscheduler(p, 0, NULL);
6617 if (retval)
6618 goto out_unlock;
6620 cpuset_cpus_allowed(p, cpus_allowed);
6621 cpumask_and(new_mask, in_mask, cpus_allowed);
6622 again:
6623 retval = set_cpus_allowed_ptr(p, new_mask);
6625 if (!retval) {
6626 cpuset_cpus_allowed(p, cpus_allowed);
6627 if (!cpumask_subset(new_mask, cpus_allowed)) {
6629 * We must have raced with a concurrent cpuset
6630 * update. Just reset the cpus_allowed to the
6631 * cpuset's cpus_allowed
6633 cpumask_copy(new_mask, cpus_allowed);
6634 goto again;
6637 out_unlock:
6638 free_cpumask_var(new_mask);
6639 out_free_cpus_allowed:
6640 free_cpumask_var(cpus_allowed);
6641 out_put_task:
6642 put_task_struct(p);
6643 put_online_cpus();
6644 return retval;
6647 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
6648 struct cpumask *new_mask)
6650 if (len < cpumask_size())
6651 cpumask_clear(new_mask);
6652 else if (len > cpumask_size())
6653 len = cpumask_size();
6655 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6659 * sys_sched_setaffinity - set the cpu affinity of a process
6660 * @pid: pid of the process
6661 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6662 * @user_mask_ptr: user-space pointer to the new cpu mask
6664 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6665 unsigned long __user *, user_mask_ptr)
6667 cpumask_var_t new_mask;
6668 int retval;
6670 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6671 return -ENOMEM;
6673 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6674 if (retval == 0)
6675 retval = sched_setaffinity(pid, new_mask);
6676 free_cpumask_var(new_mask);
6677 return retval;
6680 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6682 struct task_struct *p;
6683 unsigned long flags;
6684 struct rq *rq;
6685 int retval;
6687 get_online_cpus();
6688 rcu_read_lock();
6690 retval = -ESRCH;
6691 p = find_process_by_pid(pid);
6692 if (!p)
6693 goto out_unlock;
6695 retval = security_task_getscheduler(p);
6696 if (retval)
6697 goto out_unlock;
6699 rq = task_rq_lock(p, &flags);
6700 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
6701 task_rq_unlock(rq, &flags);
6703 out_unlock:
6704 rcu_read_unlock();
6705 put_online_cpus();
6707 return retval;
6711 * sys_sched_getaffinity - get the cpu affinity of a process
6712 * @pid: pid of the process
6713 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6714 * @user_mask_ptr: user-space pointer to hold the current cpu mask
6716 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6717 unsigned long __user *, user_mask_ptr)
6719 int ret;
6720 cpumask_var_t mask;
6722 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
6723 return -EINVAL;
6724 if (len & (sizeof(unsigned long)-1))
6725 return -EINVAL;
6727 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
6728 return -ENOMEM;
6730 ret = sched_getaffinity(pid, mask);
6731 if (ret == 0) {
6732 size_t retlen = min_t(size_t, len, cpumask_size());
6734 if (copy_to_user(user_mask_ptr, mask, retlen))
6735 ret = -EFAULT;
6736 else
6737 ret = retlen;
6739 free_cpumask_var(mask);
6741 return ret;
6745 * sys_sched_yield - yield the current processor to other threads.
6747 * This function yields the current CPU to other tasks. If there are no
6748 * other threads running on this CPU then this function will return.
6750 SYSCALL_DEFINE0(sched_yield)
6752 struct rq *rq = this_rq_lock();
6754 schedstat_inc(rq, yld_count);
6755 current->sched_class->yield_task(rq);
6758 * Since we are going to call schedule() anyway, there's
6759 * no need to preempt or enable interrupts:
6761 __release(rq->lock);
6762 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
6763 do_raw_spin_unlock(&rq->lock);
6764 preempt_enable_no_resched();
6766 schedule();
6768 return 0;
6771 static inline int should_resched(void)
6773 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
6776 static void __cond_resched(void)
6778 add_preempt_count(PREEMPT_ACTIVE);
6779 schedule();
6780 sub_preempt_count(PREEMPT_ACTIVE);
6783 int __sched _cond_resched(void)
6785 if (should_resched()) {
6786 __cond_resched();
6787 return 1;
6789 return 0;
6791 EXPORT_SYMBOL(_cond_resched);
6794 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
6795 * call schedule, and on return reacquire the lock.
6797 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
6798 * operations here to prevent schedule() from being called twice (once via
6799 * spin_unlock(), once by hand).
6801 int __cond_resched_lock(spinlock_t *lock)
6803 int resched = should_resched();
6804 int ret = 0;
6806 lockdep_assert_held(lock);
6808 if (spin_needbreak(lock) || resched) {
6809 spin_unlock(lock);
6810 if (resched)
6811 __cond_resched();
6812 else
6813 cpu_relax();
6814 ret = 1;
6815 spin_lock(lock);
6817 return ret;
6819 EXPORT_SYMBOL(__cond_resched_lock);
6821 int __sched __cond_resched_softirq(void)
6823 BUG_ON(!in_softirq());
6825 if (should_resched()) {
6826 local_bh_enable();
6827 __cond_resched();
6828 local_bh_disable();
6829 return 1;
6831 return 0;
6833 EXPORT_SYMBOL(__cond_resched_softirq);
6836 * yield - yield the current processor to other threads.
6838 * This is a shortcut for kernel-space yielding - it marks the
6839 * thread runnable and calls sys_sched_yield().
6841 void __sched yield(void)
6843 set_current_state(TASK_RUNNING);
6844 sys_sched_yield();
6846 EXPORT_SYMBOL(yield);
6849 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6850 * that process accounting knows that this is a task in IO wait state.
6852 void __sched io_schedule(void)
6854 struct rq *rq = raw_rq();
6856 delayacct_blkio_start();
6857 atomic_inc(&rq->nr_iowait);
6858 current->in_iowait = 1;
6859 schedule();
6860 current->in_iowait = 0;
6861 atomic_dec(&rq->nr_iowait);
6862 delayacct_blkio_end();
6864 EXPORT_SYMBOL(io_schedule);
6866 long __sched io_schedule_timeout(long timeout)
6868 struct rq *rq = raw_rq();
6869 long ret;
6871 delayacct_blkio_start();
6872 atomic_inc(&rq->nr_iowait);
6873 current->in_iowait = 1;
6874 ret = schedule_timeout(timeout);
6875 current->in_iowait = 0;
6876 atomic_dec(&rq->nr_iowait);
6877 delayacct_blkio_end();
6878 return ret;
6882 * sys_sched_get_priority_max - return maximum RT priority.
6883 * @policy: scheduling class.
6885 * this syscall returns the maximum rt_priority that can be used
6886 * by a given scheduling class.
6888 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6890 int ret = -EINVAL;
6892 switch (policy) {
6893 case SCHED_FIFO:
6894 case SCHED_RR:
6895 ret = MAX_USER_RT_PRIO-1;
6896 break;
6897 case SCHED_NORMAL:
6898 case SCHED_BATCH:
6899 case SCHED_IDLE:
6900 ret = 0;
6901 break;
6903 return ret;
6907 * sys_sched_get_priority_min - return minimum RT priority.
6908 * @policy: scheduling class.
6910 * this syscall returns the minimum rt_priority that can be used
6911 * by a given scheduling class.
6913 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6915 int ret = -EINVAL;
6917 switch (policy) {
6918 case SCHED_FIFO:
6919 case SCHED_RR:
6920 ret = 1;
6921 break;
6922 case SCHED_NORMAL:
6923 case SCHED_BATCH:
6924 case SCHED_IDLE:
6925 ret = 0;
6927 return ret;
6931 * sys_sched_rr_get_interval - return the default timeslice of a process.
6932 * @pid: pid of the process.
6933 * @interval: userspace pointer to the timeslice value.
6935 * this syscall writes the default timeslice value of a given process
6936 * into the user-space timespec buffer. A value of '0' means infinity.
6938 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
6939 struct timespec __user *, interval)
6941 struct task_struct *p;
6942 unsigned int time_slice;
6943 unsigned long flags;
6944 struct rq *rq;
6945 int retval;
6946 struct timespec t;
6948 if (pid < 0)
6949 return -EINVAL;
6951 retval = -ESRCH;
6952 rcu_read_lock();
6953 p = find_process_by_pid(pid);
6954 if (!p)
6955 goto out_unlock;
6957 retval = security_task_getscheduler(p);
6958 if (retval)
6959 goto out_unlock;
6961 rq = task_rq_lock(p, &flags);
6962 time_slice = p->sched_class->get_rr_interval(rq, p);
6963 task_rq_unlock(rq, &flags);
6965 rcu_read_unlock();
6966 jiffies_to_timespec(time_slice, &t);
6967 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
6968 return retval;
6970 out_unlock:
6971 rcu_read_unlock();
6972 return retval;
6975 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
6977 void sched_show_task(struct task_struct *p)
6979 unsigned long free = 0;
6980 unsigned state;
6982 state = p->state ? __ffs(p->state) + 1 : 0;
6983 printk(KERN_INFO "%-13.13s %c", p->comm,
6984 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
6985 #if BITS_PER_LONG == 32
6986 if (state == TASK_RUNNING)
6987 printk(KERN_CONT " running ");
6988 else
6989 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
6990 #else
6991 if (state == TASK_RUNNING)
6992 printk(KERN_CONT " running task ");
6993 else
6994 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
6995 #endif
6996 #ifdef CONFIG_DEBUG_STACK_USAGE
6997 free = stack_not_used(p);
6998 #endif
6999 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
7000 task_pid_nr(p), task_pid_nr(p->real_parent),
7001 (unsigned long)task_thread_info(p)->flags);
7003 show_stack(p, NULL);
7006 void show_state_filter(unsigned long state_filter)
7008 struct task_struct *g, *p;
7010 #if BITS_PER_LONG == 32
7011 printk(KERN_INFO
7012 " task PC stack pid father\n");
7013 #else
7014 printk(KERN_INFO
7015 " task PC stack pid father\n");
7016 #endif
7017 read_lock(&tasklist_lock);
7018 do_each_thread(g, p) {
7020 * reset the NMI-timeout, listing all files on a slow
7021 * console might take alot of time:
7023 touch_nmi_watchdog();
7024 if (!state_filter || (p->state & state_filter))
7025 sched_show_task(p);
7026 } while_each_thread(g, p);
7028 touch_all_softlockup_watchdogs();
7030 #ifdef CONFIG_SCHED_DEBUG
7031 sysrq_sched_debug_show();
7032 #endif
7033 read_unlock(&tasklist_lock);
7035 * Only show locks if all tasks are dumped:
7037 if (!state_filter)
7038 debug_show_all_locks();
7041 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
7043 idle->sched_class = &idle_sched_class;
7047 * init_idle - set up an idle thread for a given CPU
7048 * @idle: task in question
7049 * @cpu: cpu the idle task belongs to
7051 * NOTE: this function does not set the idle thread's NEED_RESCHED
7052 * flag, to make booting more robust.
7054 void __cpuinit init_idle(struct task_struct *idle, int cpu)
7056 struct rq *rq = cpu_rq(cpu);
7057 unsigned long flags;
7059 raw_spin_lock_irqsave(&rq->lock, flags);
7061 __sched_fork(idle);
7062 idle->state = TASK_RUNNING;
7063 idle->se.exec_start = sched_clock();
7065 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
7066 __set_task_cpu(idle, cpu);
7068 rq->curr = rq->idle = idle;
7069 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
7070 idle->oncpu = 1;
7071 #endif
7072 raw_spin_unlock_irqrestore(&rq->lock, flags);
7074 /* Set the preempt count _outside_ the spinlocks! */
7075 #if defined(CONFIG_PREEMPT)
7076 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
7077 #else
7078 task_thread_info(idle)->preempt_count = 0;
7079 #endif
7081 * The idle tasks have their own, simple scheduling class:
7083 idle->sched_class = &idle_sched_class;
7084 ftrace_graph_init_idle_task(idle, cpu);
7088 * In a system that switches off the HZ timer nohz_cpu_mask
7089 * indicates which cpus entered this state. This is used
7090 * in the rcu update to wait only for active cpus. For system
7091 * which do not switch off the HZ timer nohz_cpu_mask should
7092 * always be CPU_BITS_NONE.
7094 cpumask_var_t nohz_cpu_mask;
7097 * Increase the granularity value when there are more CPUs,
7098 * because with more CPUs the 'effective latency' as visible
7099 * to users decreases. But the relationship is not linear,
7100 * so pick a second-best guess by going with the log2 of the
7101 * number of CPUs.
7103 * This idea comes from the SD scheduler of Con Kolivas:
7105 static int get_update_sysctl_factor(void)
7107 unsigned int cpus = min_t(int, num_online_cpus(), 8);
7108 unsigned int factor;
7110 switch (sysctl_sched_tunable_scaling) {
7111 case SCHED_TUNABLESCALING_NONE:
7112 factor = 1;
7113 break;
7114 case SCHED_TUNABLESCALING_LINEAR:
7115 factor = cpus;
7116 break;
7117 case SCHED_TUNABLESCALING_LOG:
7118 default:
7119 factor = 1 + ilog2(cpus);
7120 break;
7123 return factor;
7126 static void update_sysctl(void)
7128 unsigned int factor = get_update_sysctl_factor();
7130 #define SET_SYSCTL(name) \
7131 (sysctl_##name = (factor) * normalized_sysctl_##name)
7132 SET_SYSCTL(sched_min_granularity);
7133 SET_SYSCTL(sched_latency);
7134 SET_SYSCTL(sched_wakeup_granularity);
7135 SET_SYSCTL(sched_shares_ratelimit);
7136 #undef SET_SYSCTL
7139 static inline void sched_init_granularity(void)
7141 update_sysctl();
7144 #ifdef CONFIG_SMP
7146 * This is how migration works:
7148 * 1) we queue a struct migration_req structure in the source CPU's
7149 * runqueue and wake up that CPU's migration thread.
7150 * 2) we down() the locked semaphore => thread blocks.
7151 * 3) migration thread wakes up (implicitly it forces the migrated
7152 * thread off the CPU)
7153 * 4) it gets the migration request and checks whether the migrated
7154 * task is still in the wrong runqueue.
7155 * 5) if it's in the wrong runqueue then the migration thread removes
7156 * it and puts it into the right queue.
7157 * 6) migration thread up()s the semaphore.
7158 * 7) we wake up and the migration is done.
7162 * Change a given task's CPU affinity. Migrate the thread to a
7163 * proper CPU and schedule it away if the CPU it's executing on
7164 * is removed from the allowed bitmask.
7166 * NOTE: the caller must have a valid reference to the task, the
7167 * task must not exit() & deallocate itself prematurely. The
7168 * call is not atomic; no spinlocks may be held.
7170 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
7172 struct migration_req req;
7173 unsigned long flags;
7174 struct rq *rq;
7175 int ret = 0;
7178 * Since we rely on wake-ups to migrate sleeping tasks, don't change
7179 * the ->cpus_allowed mask from under waking tasks, which would be
7180 * possible when we change rq->lock in ttwu(), so synchronize against
7181 * TASK_WAKING to avoid that.
7183 * Make an exception for freshly cloned tasks, since cpuset namespaces
7184 * might move the task about, we have to validate the target in
7185 * wake_up_new_task() anyway since the cpu might have gone away.
7187 again:
7188 while (p->state == TASK_WAKING && !(p->flags & PF_STARTING))
7189 cpu_relax();
7191 rq = task_rq_lock(p, &flags);
7193 if (p->state == TASK_WAKING && !(p->flags & PF_STARTING)) {
7194 task_rq_unlock(rq, &flags);
7195 goto again;
7198 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
7199 ret = -EINVAL;
7200 goto out;
7203 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
7204 !cpumask_equal(&p->cpus_allowed, new_mask))) {
7205 ret = -EINVAL;
7206 goto out;
7209 if (p->sched_class->set_cpus_allowed)
7210 p->sched_class->set_cpus_allowed(p, new_mask);
7211 else {
7212 cpumask_copy(&p->cpus_allowed, new_mask);
7213 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
7216 /* Can the task run on the task's current CPU? If so, we're done */
7217 if (cpumask_test_cpu(task_cpu(p), new_mask))
7218 goto out;
7220 if (migrate_task(p, cpumask_any_and(cpu_active_mask, new_mask), &req)) {
7221 /* Need help from migration thread: drop lock and wait. */
7222 struct task_struct *mt = rq->migration_thread;
7224 get_task_struct(mt);
7225 task_rq_unlock(rq, &flags);
7226 wake_up_process(rq->migration_thread);
7227 put_task_struct(mt);
7228 wait_for_completion(&req.done);
7229 tlb_migrate_finish(p->mm);
7230 return 0;
7232 out:
7233 task_rq_unlock(rq, &flags);
7235 return ret;
7237 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
7240 * Move (not current) task off this cpu, onto dest cpu. We're doing
7241 * this because either it can't run here any more (set_cpus_allowed()
7242 * away from this CPU, or CPU going down), or because we're
7243 * attempting to rebalance this task on exec (sched_exec).
7245 * So we race with normal scheduler movements, but that's OK, as long
7246 * as the task is no longer on this CPU.
7248 * Returns non-zero if task was successfully migrated.
7250 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
7252 struct rq *rq_dest, *rq_src;
7253 int ret = 0;
7255 if (unlikely(!cpu_active(dest_cpu)))
7256 return ret;
7258 rq_src = cpu_rq(src_cpu);
7259 rq_dest = cpu_rq(dest_cpu);
7261 double_rq_lock(rq_src, rq_dest);
7262 /* Already moved. */
7263 if (task_cpu(p) != src_cpu)
7264 goto done;
7265 /* Affinity changed (again). */
7266 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
7267 goto fail;
7270 * If we're not on a rq, the next wake-up will ensure we're
7271 * placed properly.
7273 if (p->se.on_rq) {
7274 deactivate_task(rq_src, p, 0);
7275 set_task_cpu(p, dest_cpu);
7276 activate_task(rq_dest, p, 0);
7277 check_preempt_curr(rq_dest, p, 0);
7279 done:
7280 ret = 1;
7281 fail:
7282 double_rq_unlock(rq_src, rq_dest);
7283 return ret;
7286 #define RCU_MIGRATION_IDLE 0
7287 #define RCU_MIGRATION_NEED_QS 1
7288 #define RCU_MIGRATION_GOT_QS 2
7289 #define RCU_MIGRATION_MUST_SYNC 3
7292 * migration_thread - this is a highprio system thread that performs
7293 * thread migration by bumping thread off CPU then 'pushing' onto
7294 * another runqueue.
7296 static int migration_thread(void *data)
7298 int badcpu;
7299 int cpu = (long)data;
7300 struct rq *rq;
7302 rq = cpu_rq(cpu);
7303 BUG_ON(rq->migration_thread != current);
7305 set_current_state(TASK_INTERRUPTIBLE);
7306 while (!kthread_should_stop()) {
7307 struct migration_req *req;
7308 struct list_head *head;
7310 raw_spin_lock_irq(&rq->lock);
7312 if (cpu_is_offline(cpu)) {
7313 raw_spin_unlock_irq(&rq->lock);
7314 break;
7317 if (rq->active_balance) {
7318 active_load_balance(rq, cpu);
7319 rq->active_balance = 0;
7322 head = &rq->migration_queue;
7324 if (list_empty(head)) {
7325 raw_spin_unlock_irq(&rq->lock);
7326 schedule();
7327 set_current_state(TASK_INTERRUPTIBLE);
7328 continue;
7330 req = list_entry(head->next, struct migration_req, list);
7331 list_del_init(head->next);
7333 if (req->task != NULL) {
7334 raw_spin_unlock(&rq->lock);
7335 __migrate_task(req->task, cpu, req->dest_cpu);
7336 } else if (likely(cpu == (badcpu = smp_processor_id()))) {
7337 req->dest_cpu = RCU_MIGRATION_GOT_QS;
7338 raw_spin_unlock(&rq->lock);
7339 } else {
7340 req->dest_cpu = RCU_MIGRATION_MUST_SYNC;
7341 raw_spin_unlock(&rq->lock);
7342 WARN_ONCE(1, "migration_thread() on CPU %d, expected %d\n", badcpu, cpu);
7344 local_irq_enable();
7346 complete(&req->done);
7348 __set_current_state(TASK_RUNNING);
7350 return 0;
7353 #ifdef CONFIG_HOTPLUG_CPU
7355 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
7357 int ret;
7359 local_irq_disable();
7360 ret = __migrate_task(p, src_cpu, dest_cpu);
7361 local_irq_enable();
7362 return ret;
7366 * Figure out where task on dead CPU should go, use force if necessary.
7368 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
7370 int dest_cpu;
7372 again:
7373 dest_cpu = select_fallback_rq(dead_cpu, p);
7375 /* It can have affinity changed while we were choosing. */
7376 if (unlikely(!__migrate_task_irq(p, dead_cpu, dest_cpu)))
7377 goto again;
7381 * While a dead CPU has no uninterruptible tasks queued at this point,
7382 * it might still have a nonzero ->nr_uninterruptible counter, because
7383 * for performance reasons the counter is not stricly tracking tasks to
7384 * their home CPUs. So we just add the counter to another CPU's counter,
7385 * to keep the global sum constant after CPU-down:
7387 static void migrate_nr_uninterruptible(struct rq *rq_src)
7389 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
7390 unsigned long flags;
7392 local_irq_save(flags);
7393 double_rq_lock(rq_src, rq_dest);
7394 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
7395 rq_src->nr_uninterruptible = 0;
7396 double_rq_unlock(rq_src, rq_dest);
7397 local_irq_restore(flags);
7400 /* Run through task list and migrate tasks from the dead cpu. */
7401 static void migrate_live_tasks(int src_cpu)
7403 struct task_struct *p, *t;
7405 read_lock(&tasklist_lock);
7407 do_each_thread(t, p) {
7408 if (p == current)
7409 continue;
7411 if (task_cpu(p) == src_cpu)
7412 move_task_off_dead_cpu(src_cpu, p);
7413 } while_each_thread(t, p);
7415 read_unlock(&tasklist_lock);
7419 * Schedules idle task to be the next runnable task on current CPU.
7420 * It does so by boosting its priority to highest possible.
7421 * Used by CPU offline code.
7423 void sched_idle_next(void)
7425 int this_cpu = smp_processor_id();
7426 struct rq *rq = cpu_rq(this_cpu);
7427 struct task_struct *p = rq->idle;
7428 unsigned long flags;
7430 /* cpu has to be offline */
7431 BUG_ON(cpu_online(this_cpu));
7434 * Strictly not necessary since rest of the CPUs are stopped by now
7435 * and interrupts disabled on the current cpu.
7437 raw_spin_lock_irqsave(&rq->lock, flags);
7439 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7441 update_rq_clock(rq);
7442 activate_task(rq, p, 0);
7444 raw_spin_unlock_irqrestore(&rq->lock, flags);
7448 * Ensures that the idle task is using init_mm right before its cpu goes
7449 * offline.
7451 void idle_task_exit(void)
7453 struct mm_struct *mm = current->active_mm;
7455 BUG_ON(cpu_online(smp_processor_id()));
7457 if (mm != &init_mm)
7458 switch_mm(mm, &init_mm, current);
7459 mmdrop(mm);
7462 /* called under rq->lock with disabled interrupts */
7463 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
7465 struct rq *rq = cpu_rq(dead_cpu);
7467 /* Must be exiting, otherwise would be on tasklist. */
7468 BUG_ON(!p->exit_state);
7470 /* Cannot have done final schedule yet: would have vanished. */
7471 BUG_ON(p->state == TASK_DEAD);
7473 get_task_struct(p);
7476 * Drop lock around migration; if someone else moves it,
7477 * that's OK. No task can be added to this CPU, so iteration is
7478 * fine.
7480 raw_spin_unlock_irq(&rq->lock);
7481 move_task_off_dead_cpu(dead_cpu, p);
7482 raw_spin_lock_irq(&rq->lock);
7484 put_task_struct(p);
7487 /* release_task() removes task from tasklist, so we won't find dead tasks. */
7488 static void migrate_dead_tasks(unsigned int dead_cpu)
7490 struct rq *rq = cpu_rq(dead_cpu);
7491 struct task_struct *next;
7493 for ( ; ; ) {
7494 if (!rq->nr_running)
7495 break;
7496 update_rq_clock(rq);
7497 next = pick_next_task(rq);
7498 if (!next)
7499 break;
7500 next->sched_class->put_prev_task(rq, next);
7501 migrate_dead(dead_cpu, next);
7507 * remove the tasks which were accounted by rq from calc_load_tasks.
7509 static void calc_global_load_remove(struct rq *rq)
7511 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
7512 rq->calc_load_active = 0;
7514 #endif /* CONFIG_HOTPLUG_CPU */
7516 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
7518 static struct ctl_table sd_ctl_dir[] = {
7520 .procname = "sched_domain",
7521 .mode = 0555,
7526 static struct ctl_table sd_ctl_root[] = {
7528 .procname = "kernel",
7529 .mode = 0555,
7530 .child = sd_ctl_dir,
7535 static struct ctl_table *sd_alloc_ctl_entry(int n)
7537 struct ctl_table *entry =
7538 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
7540 return entry;
7543 static void sd_free_ctl_entry(struct ctl_table **tablep)
7545 struct ctl_table *entry;
7548 * In the intermediate directories, both the child directory and
7549 * procname are dynamically allocated and could fail but the mode
7550 * will always be set. In the lowest directory the names are
7551 * static strings and all have proc handlers.
7553 for (entry = *tablep; entry->mode; entry++) {
7554 if (entry->child)
7555 sd_free_ctl_entry(&entry->child);
7556 if (entry->proc_handler == NULL)
7557 kfree(entry->procname);
7560 kfree(*tablep);
7561 *tablep = NULL;
7564 static void
7565 set_table_entry(struct ctl_table *entry,
7566 const char *procname, void *data, int maxlen,
7567 mode_t mode, proc_handler *proc_handler)
7569 entry->procname = procname;
7570 entry->data = data;
7571 entry->maxlen = maxlen;
7572 entry->mode = mode;
7573 entry->proc_handler = proc_handler;
7576 static struct ctl_table *
7577 sd_alloc_ctl_domain_table(struct sched_domain *sd)
7579 struct ctl_table *table = sd_alloc_ctl_entry(13);
7581 if (table == NULL)
7582 return NULL;
7584 set_table_entry(&table[0], "min_interval", &sd->min_interval,
7585 sizeof(long), 0644, proc_doulongvec_minmax);
7586 set_table_entry(&table[1], "max_interval", &sd->max_interval,
7587 sizeof(long), 0644, proc_doulongvec_minmax);
7588 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
7589 sizeof(int), 0644, proc_dointvec_minmax);
7590 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
7591 sizeof(int), 0644, proc_dointvec_minmax);
7592 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
7593 sizeof(int), 0644, proc_dointvec_minmax);
7594 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
7595 sizeof(int), 0644, proc_dointvec_minmax);
7596 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
7597 sizeof(int), 0644, proc_dointvec_minmax);
7598 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
7599 sizeof(int), 0644, proc_dointvec_minmax);
7600 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
7601 sizeof(int), 0644, proc_dointvec_minmax);
7602 set_table_entry(&table[9], "cache_nice_tries",
7603 &sd->cache_nice_tries,
7604 sizeof(int), 0644, proc_dointvec_minmax);
7605 set_table_entry(&table[10], "flags", &sd->flags,
7606 sizeof(int), 0644, proc_dointvec_minmax);
7607 set_table_entry(&table[11], "name", sd->name,
7608 CORENAME_MAX_SIZE, 0444, proc_dostring);
7609 /* &table[12] is terminator */
7611 return table;
7614 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
7616 struct ctl_table *entry, *table;
7617 struct sched_domain *sd;
7618 int domain_num = 0, i;
7619 char buf[32];
7621 for_each_domain(cpu, sd)
7622 domain_num++;
7623 entry = table = sd_alloc_ctl_entry(domain_num + 1);
7624 if (table == NULL)
7625 return NULL;
7627 i = 0;
7628 for_each_domain(cpu, sd) {
7629 snprintf(buf, 32, "domain%d", i);
7630 entry->procname = kstrdup(buf, GFP_KERNEL);
7631 entry->mode = 0555;
7632 entry->child = sd_alloc_ctl_domain_table(sd);
7633 entry++;
7634 i++;
7636 return table;
7639 static struct ctl_table_header *sd_sysctl_header;
7640 static void register_sched_domain_sysctl(void)
7642 int i, cpu_num = num_possible_cpus();
7643 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
7644 char buf[32];
7646 WARN_ON(sd_ctl_dir[0].child);
7647 sd_ctl_dir[0].child = entry;
7649 if (entry == NULL)
7650 return;
7652 for_each_possible_cpu(i) {
7653 snprintf(buf, 32, "cpu%d", i);
7654 entry->procname = kstrdup(buf, GFP_KERNEL);
7655 entry->mode = 0555;
7656 entry->child = sd_alloc_ctl_cpu_table(i);
7657 entry++;
7660 WARN_ON(sd_sysctl_header);
7661 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
7664 /* may be called multiple times per register */
7665 static void unregister_sched_domain_sysctl(void)
7667 if (sd_sysctl_header)
7668 unregister_sysctl_table(sd_sysctl_header);
7669 sd_sysctl_header = NULL;
7670 if (sd_ctl_dir[0].child)
7671 sd_free_ctl_entry(&sd_ctl_dir[0].child);
7673 #else
7674 static void register_sched_domain_sysctl(void)
7677 static void unregister_sched_domain_sysctl(void)
7680 #endif
7682 static void set_rq_online(struct rq *rq)
7684 if (!rq->online) {
7685 const struct sched_class *class;
7687 cpumask_set_cpu(rq->cpu, rq->rd->online);
7688 rq->online = 1;
7690 for_each_class(class) {
7691 if (class->rq_online)
7692 class->rq_online(rq);
7697 static void set_rq_offline(struct rq *rq)
7699 if (rq->online) {
7700 const struct sched_class *class;
7702 for_each_class(class) {
7703 if (class->rq_offline)
7704 class->rq_offline(rq);
7707 cpumask_clear_cpu(rq->cpu, rq->rd->online);
7708 rq->online = 0;
7713 * migration_call - callback that gets triggered when a CPU is added.
7714 * Here we can start up the necessary migration thread for the new CPU.
7716 static int __cpuinit
7717 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
7719 struct task_struct *p;
7720 int cpu = (long)hcpu;
7721 unsigned long flags;
7722 struct rq *rq;
7724 switch (action) {
7726 case CPU_UP_PREPARE:
7727 case CPU_UP_PREPARE_FROZEN:
7728 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
7729 if (IS_ERR(p))
7730 return NOTIFY_BAD;
7731 kthread_bind(p, cpu);
7732 /* Must be high prio: stop_machine expects to yield to it. */
7733 rq = task_rq_lock(p, &flags);
7734 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
7735 task_rq_unlock(rq, &flags);
7736 get_task_struct(p);
7737 cpu_rq(cpu)->migration_thread = p;
7738 rq->calc_load_update = calc_load_update;
7739 break;
7741 case CPU_ONLINE:
7742 case CPU_ONLINE_FROZEN:
7743 /* Strictly unnecessary, as first user will wake it. */
7744 wake_up_process(cpu_rq(cpu)->migration_thread);
7746 /* Update our root-domain */
7747 rq = cpu_rq(cpu);
7748 raw_spin_lock_irqsave(&rq->lock, flags);
7749 if (rq->rd) {
7750 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7752 set_rq_online(rq);
7754 raw_spin_unlock_irqrestore(&rq->lock, flags);
7755 break;
7757 #ifdef CONFIG_HOTPLUG_CPU
7758 case CPU_UP_CANCELED:
7759 case CPU_UP_CANCELED_FROZEN:
7760 if (!cpu_rq(cpu)->migration_thread)
7761 break;
7762 /* Unbind it from offline cpu so it can run. Fall thru. */
7763 kthread_bind(cpu_rq(cpu)->migration_thread,
7764 cpumask_any(cpu_online_mask));
7765 kthread_stop(cpu_rq(cpu)->migration_thread);
7766 put_task_struct(cpu_rq(cpu)->migration_thread);
7767 cpu_rq(cpu)->migration_thread = NULL;
7768 break;
7770 case CPU_DEAD:
7771 case CPU_DEAD_FROZEN:
7772 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
7773 migrate_live_tasks(cpu);
7774 rq = cpu_rq(cpu);
7775 kthread_stop(rq->migration_thread);
7776 put_task_struct(rq->migration_thread);
7777 rq->migration_thread = NULL;
7778 /* Idle task back to normal (off runqueue, low prio) */
7779 raw_spin_lock_irq(&rq->lock);
7780 update_rq_clock(rq);
7781 deactivate_task(rq, rq->idle, 0);
7782 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
7783 rq->idle->sched_class = &idle_sched_class;
7784 migrate_dead_tasks(cpu);
7785 raw_spin_unlock_irq(&rq->lock);
7786 cpuset_unlock();
7787 migrate_nr_uninterruptible(rq);
7788 BUG_ON(rq->nr_running != 0);
7789 calc_global_load_remove(rq);
7791 * No need to migrate the tasks: it was best-effort if
7792 * they didn't take sched_hotcpu_mutex. Just wake up
7793 * the requestors.
7795 raw_spin_lock_irq(&rq->lock);
7796 while (!list_empty(&rq->migration_queue)) {
7797 struct migration_req *req;
7799 req = list_entry(rq->migration_queue.next,
7800 struct migration_req, list);
7801 list_del_init(&req->list);
7802 raw_spin_unlock_irq(&rq->lock);
7803 complete(&req->done);
7804 raw_spin_lock_irq(&rq->lock);
7806 raw_spin_unlock_irq(&rq->lock);
7807 break;
7809 case CPU_DYING:
7810 case CPU_DYING_FROZEN:
7811 /* Update our root-domain */
7812 rq = cpu_rq(cpu);
7813 raw_spin_lock_irqsave(&rq->lock, flags);
7814 if (rq->rd) {
7815 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7816 set_rq_offline(rq);
7818 raw_spin_unlock_irqrestore(&rq->lock, flags);
7819 break;
7820 #endif
7822 return NOTIFY_OK;
7826 * Register at high priority so that task migration (migrate_all_tasks)
7827 * happens before everything else. This has to be lower priority than
7828 * the notifier in the perf_event subsystem, though.
7830 static struct notifier_block __cpuinitdata migration_notifier = {
7831 .notifier_call = migration_call,
7832 .priority = 10
7835 static int __init migration_init(void)
7837 void *cpu = (void *)(long)smp_processor_id();
7838 int err;
7840 /* Start one for the boot CPU: */
7841 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
7842 BUG_ON(err == NOTIFY_BAD);
7843 migration_call(&migration_notifier, CPU_ONLINE, cpu);
7844 register_cpu_notifier(&migration_notifier);
7846 return 0;
7848 early_initcall(migration_init);
7849 #endif
7851 #ifdef CONFIG_SMP
7853 #ifdef CONFIG_SCHED_DEBUG
7855 static __read_mostly int sched_domain_debug_enabled;
7857 static int __init sched_domain_debug_setup(char *str)
7859 sched_domain_debug_enabled = 1;
7861 return 0;
7863 early_param("sched_debug", sched_domain_debug_setup);
7865 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
7866 struct cpumask *groupmask)
7868 struct sched_group *group = sd->groups;
7869 char str[256];
7871 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
7872 cpumask_clear(groupmask);
7874 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
7876 if (!(sd->flags & SD_LOAD_BALANCE)) {
7877 printk("does not load-balance\n");
7878 if (sd->parent)
7879 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
7880 " has parent");
7881 return -1;
7884 printk(KERN_CONT "span %s level %s\n", str, sd->name);
7886 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
7887 printk(KERN_ERR "ERROR: domain->span does not contain "
7888 "CPU%d\n", cpu);
7890 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
7891 printk(KERN_ERR "ERROR: domain->groups does not contain"
7892 " CPU%d\n", cpu);
7895 printk(KERN_DEBUG "%*s groups:", level + 1, "");
7896 do {
7897 if (!group) {
7898 printk("\n");
7899 printk(KERN_ERR "ERROR: group is NULL\n");
7900 break;
7903 if (!group->cpu_power) {
7904 printk(KERN_CONT "\n");
7905 printk(KERN_ERR "ERROR: domain->cpu_power not "
7906 "set\n");
7907 break;
7910 if (!cpumask_weight(sched_group_cpus(group))) {
7911 printk(KERN_CONT "\n");
7912 printk(KERN_ERR "ERROR: empty group\n");
7913 break;
7916 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
7917 printk(KERN_CONT "\n");
7918 printk(KERN_ERR "ERROR: repeated CPUs\n");
7919 break;
7922 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
7924 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
7926 printk(KERN_CONT " %s", str);
7927 if (group->cpu_power != SCHED_LOAD_SCALE) {
7928 printk(KERN_CONT " (cpu_power = %d)",
7929 group->cpu_power);
7932 group = group->next;
7933 } while (group != sd->groups);
7934 printk(KERN_CONT "\n");
7936 if (!cpumask_equal(sched_domain_span(sd), groupmask))
7937 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
7939 if (sd->parent &&
7940 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
7941 printk(KERN_ERR "ERROR: parent span is not a superset "
7942 "of domain->span\n");
7943 return 0;
7946 static void sched_domain_debug(struct sched_domain *sd, int cpu)
7948 cpumask_var_t groupmask;
7949 int level = 0;
7951 if (!sched_domain_debug_enabled)
7952 return;
7954 if (!sd) {
7955 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
7956 return;
7959 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
7961 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
7962 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
7963 return;
7966 for (;;) {
7967 if (sched_domain_debug_one(sd, cpu, level, groupmask))
7968 break;
7969 level++;
7970 sd = sd->parent;
7971 if (!sd)
7972 break;
7974 free_cpumask_var(groupmask);
7976 #else /* !CONFIG_SCHED_DEBUG */
7977 # define sched_domain_debug(sd, cpu) do { } while (0)
7978 #endif /* CONFIG_SCHED_DEBUG */
7980 static int sd_degenerate(struct sched_domain *sd)
7982 if (cpumask_weight(sched_domain_span(sd)) == 1)
7983 return 1;
7985 /* Following flags need at least 2 groups */
7986 if (sd->flags & (SD_LOAD_BALANCE |
7987 SD_BALANCE_NEWIDLE |
7988 SD_BALANCE_FORK |
7989 SD_BALANCE_EXEC |
7990 SD_SHARE_CPUPOWER |
7991 SD_SHARE_PKG_RESOURCES)) {
7992 if (sd->groups != sd->groups->next)
7993 return 0;
7996 /* Following flags don't use groups */
7997 if (sd->flags & (SD_WAKE_AFFINE))
7998 return 0;
8000 return 1;
8003 static int
8004 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
8006 unsigned long cflags = sd->flags, pflags = parent->flags;
8008 if (sd_degenerate(parent))
8009 return 1;
8011 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
8012 return 0;
8014 /* Flags needing groups don't count if only 1 group in parent */
8015 if (parent->groups == parent->groups->next) {
8016 pflags &= ~(SD_LOAD_BALANCE |
8017 SD_BALANCE_NEWIDLE |
8018 SD_BALANCE_FORK |
8019 SD_BALANCE_EXEC |
8020 SD_SHARE_CPUPOWER |
8021 SD_SHARE_PKG_RESOURCES);
8022 if (nr_node_ids == 1)
8023 pflags &= ~SD_SERIALIZE;
8025 if (~cflags & pflags)
8026 return 0;
8028 return 1;
8031 static void free_rootdomain(struct root_domain *rd)
8033 synchronize_sched();
8035 cpupri_cleanup(&rd->cpupri);
8037 free_cpumask_var(rd->rto_mask);
8038 free_cpumask_var(rd->online);
8039 free_cpumask_var(rd->span);
8040 kfree(rd);
8043 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
8045 struct root_domain *old_rd = NULL;
8046 unsigned long flags;
8048 raw_spin_lock_irqsave(&rq->lock, flags);
8050 if (rq->rd) {
8051 old_rd = rq->rd;
8053 if (cpumask_test_cpu(rq->cpu, old_rd->online))
8054 set_rq_offline(rq);
8056 cpumask_clear_cpu(rq->cpu, old_rd->span);
8059 * If we dont want to free the old_rt yet then
8060 * set old_rd to NULL to skip the freeing later
8061 * in this function:
8063 if (!atomic_dec_and_test(&old_rd->refcount))
8064 old_rd = NULL;
8067 atomic_inc(&rd->refcount);
8068 rq->rd = rd;
8070 cpumask_set_cpu(rq->cpu, rd->span);
8071 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
8072 set_rq_online(rq);
8074 raw_spin_unlock_irqrestore(&rq->lock, flags);
8076 if (old_rd)
8077 free_rootdomain(old_rd);
8080 static int init_rootdomain(struct root_domain *rd, bool bootmem)
8082 gfp_t gfp = GFP_KERNEL;
8084 memset(rd, 0, sizeof(*rd));
8086 if (bootmem)
8087 gfp = GFP_NOWAIT;
8089 if (!alloc_cpumask_var(&rd->span, gfp))
8090 goto out;
8091 if (!alloc_cpumask_var(&rd->online, gfp))
8092 goto free_span;
8093 if (!alloc_cpumask_var(&rd->rto_mask, gfp))
8094 goto free_online;
8096 if (cpupri_init(&rd->cpupri, bootmem) != 0)
8097 goto free_rto_mask;
8098 return 0;
8100 free_rto_mask:
8101 free_cpumask_var(rd->rto_mask);
8102 free_online:
8103 free_cpumask_var(rd->online);
8104 free_span:
8105 free_cpumask_var(rd->span);
8106 out:
8107 return -ENOMEM;
8110 static void init_defrootdomain(void)
8112 init_rootdomain(&def_root_domain, true);
8114 atomic_set(&def_root_domain.refcount, 1);
8117 static struct root_domain *alloc_rootdomain(void)
8119 struct root_domain *rd;
8121 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
8122 if (!rd)
8123 return NULL;
8125 if (init_rootdomain(rd, false) != 0) {
8126 kfree(rd);
8127 return NULL;
8130 return rd;
8134 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
8135 * hold the hotplug lock.
8137 static void
8138 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
8140 struct rq *rq = cpu_rq(cpu);
8141 struct sched_domain *tmp;
8143 /* Remove the sched domains which do not contribute to scheduling. */
8144 for (tmp = sd; tmp; ) {
8145 struct sched_domain *parent = tmp->parent;
8146 if (!parent)
8147 break;
8149 if (sd_parent_degenerate(tmp, parent)) {
8150 tmp->parent = parent->parent;
8151 if (parent->parent)
8152 parent->parent->child = tmp;
8153 } else
8154 tmp = tmp->parent;
8157 if (sd && sd_degenerate(sd)) {
8158 sd = sd->parent;
8159 if (sd)
8160 sd->child = NULL;
8163 sched_domain_debug(sd, cpu);
8165 rq_attach_root(rq, rd);
8166 rcu_assign_pointer(rq->sd, sd);
8169 /* cpus with isolated domains */
8170 static cpumask_var_t cpu_isolated_map;
8172 /* Setup the mask of cpus configured for isolated domains */
8173 static int __init isolated_cpu_setup(char *str)
8175 alloc_bootmem_cpumask_var(&cpu_isolated_map);
8176 cpulist_parse(str, cpu_isolated_map);
8177 return 1;
8180 __setup("isolcpus=", isolated_cpu_setup);
8183 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
8184 * to a function which identifies what group(along with sched group) a CPU
8185 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
8186 * (due to the fact that we keep track of groups covered with a struct cpumask).
8188 * init_sched_build_groups will build a circular linked list of the groups
8189 * covered by the given span, and will set each group's ->cpumask correctly,
8190 * and ->cpu_power to 0.
8192 static void
8193 init_sched_build_groups(const struct cpumask *span,
8194 const struct cpumask *cpu_map,
8195 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
8196 struct sched_group **sg,
8197 struct cpumask *tmpmask),
8198 struct cpumask *covered, struct cpumask *tmpmask)
8200 struct sched_group *first = NULL, *last = NULL;
8201 int i;
8203 cpumask_clear(covered);
8205 for_each_cpu(i, span) {
8206 struct sched_group *sg;
8207 int group = group_fn(i, cpu_map, &sg, tmpmask);
8208 int j;
8210 if (cpumask_test_cpu(i, covered))
8211 continue;
8213 cpumask_clear(sched_group_cpus(sg));
8214 sg->cpu_power = 0;
8216 for_each_cpu(j, span) {
8217 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
8218 continue;
8220 cpumask_set_cpu(j, covered);
8221 cpumask_set_cpu(j, sched_group_cpus(sg));
8223 if (!first)
8224 first = sg;
8225 if (last)
8226 last->next = sg;
8227 last = sg;
8229 last->next = first;
8232 #define SD_NODES_PER_DOMAIN 16
8234 #ifdef CONFIG_NUMA
8237 * find_next_best_node - find the next node to include in a sched_domain
8238 * @node: node whose sched_domain we're building
8239 * @used_nodes: nodes already in the sched_domain
8241 * Find the next node to include in a given scheduling domain. Simply
8242 * finds the closest node not already in the @used_nodes map.
8244 * Should use nodemask_t.
8246 static int find_next_best_node(int node, nodemask_t *used_nodes)
8248 int i, n, val, min_val, best_node = 0;
8250 min_val = INT_MAX;
8252 for (i = 0; i < nr_node_ids; i++) {
8253 /* Start at @node */
8254 n = (node + i) % nr_node_ids;
8256 if (!nr_cpus_node(n))
8257 continue;
8259 /* Skip already used nodes */
8260 if (node_isset(n, *used_nodes))
8261 continue;
8263 /* Simple min distance search */
8264 val = node_distance(node, n);
8266 if (val < min_val) {
8267 min_val = val;
8268 best_node = n;
8272 node_set(best_node, *used_nodes);
8273 return best_node;
8277 * sched_domain_node_span - get a cpumask for a node's sched_domain
8278 * @node: node whose cpumask we're constructing
8279 * @span: resulting cpumask
8281 * Given a node, construct a good cpumask for its sched_domain to span. It
8282 * should be one that prevents unnecessary balancing, but also spreads tasks
8283 * out optimally.
8285 static void sched_domain_node_span(int node, struct cpumask *span)
8287 nodemask_t used_nodes;
8288 int i;
8290 cpumask_clear(span);
8291 nodes_clear(used_nodes);
8293 cpumask_or(span, span, cpumask_of_node(node));
8294 node_set(node, used_nodes);
8296 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
8297 int next_node = find_next_best_node(node, &used_nodes);
8299 cpumask_or(span, span, cpumask_of_node(next_node));
8302 #endif /* CONFIG_NUMA */
8304 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
8307 * The cpus mask in sched_group and sched_domain hangs off the end.
8309 * ( See the the comments in include/linux/sched.h:struct sched_group
8310 * and struct sched_domain. )
8312 struct static_sched_group {
8313 struct sched_group sg;
8314 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
8317 struct static_sched_domain {
8318 struct sched_domain sd;
8319 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
8322 struct s_data {
8323 #ifdef CONFIG_NUMA
8324 int sd_allnodes;
8325 cpumask_var_t domainspan;
8326 cpumask_var_t covered;
8327 cpumask_var_t notcovered;
8328 #endif
8329 cpumask_var_t nodemask;
8330 cpumask_var_t this_sibling_map;
8331 cpumask_var_t this_core_map;
8332 cpumask_var_t send_covered;
8333 cpumask_var_t tmpmask;
8334 struct sched_group **sched_group_nodes;
8335 struct root_domain *rd;
8338 enum s_alloc {
8339 sa_sched_groups = 0,
8340 sa_rootdomain,
8341 sa_tmpmask,
8342 sa_send_covered,
8343 sa_this_core_map,
8344 sa_this_sibling_map,
8345 sa_nodemask,
8346 sa_sched_group_nodes,
8347 #ifdef CONFIG_NUMA
8348 sa_notcovered,
8349 sa_covered,
8350 sa_domainspan,
8351 #endif
8352 sa_none,
8356 * SMT sched-domains:
8358 #ifdef CONFIG_SCHED_SMT
8359 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
8360 static DEFINE_PER_CPU(struct static_sched_group, sched_groups);
8362 static int
8363 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
8364 struct sched_group **sg, struct cpumask *unused)
8366 if (sg)
8367 *sg = &per_cpu(sched_groups, cpu).sg;
8368 return cpu;
8370 #endif /* CONFIG_SCHED_SMT */
8373 * multi-core sched-domains:
8375 #ifdef CONFIG_SCHED_MC
8376 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
8377 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
8378 #endif /* CONFIG_SCHED_MC */
8380 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
8381 static int
8382 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8383 struct sched_group **sg, struct cpumask *mask)
8385 int group;
8387 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8388 group = cpumask_first(mask);
8389 if (sg)
8390 *sg = &per_cpu(sched_group_core, group).sg;
8391 return group;
8393 #elif defined(CONFIG_SCHED_MC)
8394 static int
8395 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
8396 struct sched_group **sg, struct cpumask *unused)
8398 if (sg)
8399 *sg = &per_cpu(sched_group_core, cpu).sg;
8400 return cpu;
8402 #endif
8404 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
8405 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
8407 static int
8408 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
8409 struct sched_group **sg, struct cpumask *mask)
8411 int group;
8412 #ifdef CONFIG_SCHED_MC
8413 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
8414 group = cpumask_first(mask);
8415 #elif defined(CONFIG_SCHED_SMT)
8416 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
8417 group = cpumask_first(mask);
8418 #else
8419 group = cpu;
8420 #endif
8421 if (sg)
8422 *sg = &per_cpu(sched_group_phys, group).sg;
8423 return group;
8426 #ifdef CONFIG_NUMA
8428 * The init_sched_build_groups can't handle what we want to do with node
8429 * groups, so roll our own. Now each node has its own list of groups which
8430 * gets dynamically allocated.
8432 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
8433 static struct sched_group ***sched_group_nodes_bycpu;
8435 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
8436 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
8438 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
8439 struct sched_group **sg,
8440 struct cpumask *nodemask)
8442 int group;
8444 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
8445 group = cpumask_first(nodemask);
8447 if (sg)
8448 *sg = &per_cpu(sched_group_allnodes, group).sg;
8449 return group;
8452 static void init_numa_sched_groups_power(struct sched_group *group_head)
8454 struct sched_group *sg = group_head;
8455 int j;
8457 if (!sg)
8458 return;
8459 do {
8460 for_each_cpu(j, sched_group_cpus(sg)) {
8461 struct sched_domain *sd;
8463 sd = &per_cpu(phys_domains, j).sd;
8464 if (j != group_first_cpu(sd->groups)) {
8466 * Only add "power" once for each
8467 * physical package.
8469 continue;
8472 sg->cpu_power += sd->groups->cpu_power;
8474 sg = sg->next;
8475 } while (sg != group_head);
8478 static int build_numa_sched_groups(struct s_data *d,
8479 const struct cpumask *cpu_map, int num)
8481 struct sched_domain *sd;
8482 struct sched_group *sg, *prev;
8483 int n, j;
8485 cpumask_clear(d->covered);
8486 cpumask_and(d->nodemask, cpumask_of_node(num), cpu_map);
8487 if (cpumask_empty(d->nodemask)) {
8488 d->sched_group_nodes[num] = NULL;
8489 goto out;
8492 sched_domain_node_span(num, d->domainspan);
8493 cpumask_and(d->domainspan, d->domainspan, cpu_map);
8495 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8496 GFP_KERNEL, num);
8497 if (!sg) {
8498 printk(KERN_WARNING "Can not alloc domain group for node %d\n",
8499 num);
8500 return -ENOMEM;
8502 d->sched_group_nodes[num] = sg;
8504 for_each_cpu(j, d->nodemask) {
8505 sd = &per_cpu(node_domains, j).sd;
8506 sd->groups = sg;
8509 sg->cpu_power = 0;
8510 cpumask_copy(sched_group_cpus(sg), d->nodemask);
8511 sg->next = sg;
8512 cpumask_or(d->covered, d->covered, d->nodemask);
8514 prev = sg;
8515 for (j = 0; j < nr_node_ids; j++) {
8516 n = (num + j) % nr_node_ids;
8517 cpumask_complement(d->notcovered, d->covered);
8518 cpumask_and(d->tmpmask, d->notcovered, cpu_map);
8519 cpumask_and(d->tmpmask, d->tmpmask, d->domainspan);
8520 if (cpumask_empty(d->tmpmask))
8521 break;
8522 cpumask_and(d->tmpmask, d->tmpmask, cpumask_of_node(n));
8523 if (cpumask_empty(d->tmpmask))
8524 continue;
8525 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
8526 GFP_KERNEL, num);
8527 if (!sg) {
8528 printk(KERN_WARNING
8529 "Can not alloc domain group for node %d\n", j);
8530 return -ENOMEM;
8532 sg->cpu_power = 0;
8533 cpumask_copy(sched_group_cpus(sg), d->tmpmask);
8534 sg->next = prev->next;
8535 cpumask_or(d->covered, d->covered, d->tmpmask);
8536 prev->next = sg;
8537 prev = sg;
8539 out:
8540 return 0;
8542 #endif /* CONFIG_NUMA */
8544 #ifdef CONFIG_NUMA
8545 /* Free memory allocated for various sched_group structures */
8546 static void free_sched_groups(const struct cpumask *cpu_map,
8547 struct cpumask *nodemask)
8549 int cpu, i;
8551 for_each_cpu(cpu, cpu_map) {
8552 struct sched_group **sched_group_nodes
8553 = sched_group_nodes_bycpu[cpu];
8555 if (!sched_group_nodes)
8556 continue;
8558 for (i = 0; i < nr_node_ids; i++) {
8559 struct sched_group *oldsg, *sg = sched_group_nodes[i];
8561 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
8562 if (cpumask_empty(nodemask))
8563 continue;
8565 if (sg == NULL)
8566 continue;
8567 sg = sg->next;
8568 next_sg:
8569 oldsg = sg;
8570 sg = sg->next;
8571 kfree(oldsg);
8572 if (oldsg != sched_group_nodes[i])
8573 goto next_sg;
8575 kfree(sched_group_nodes);
8576 sched_group_nodes_bycpu[cpu] = NULL;
8579 #else /* !CONFIG_NUMA */
8580 static void free_sched_groups(const struct cpumask *cpu_map,
8581 struct cpumask *nodemask)
8584 #endif /* CONFIG_NUMA */
8587 * Initialize sched groups cpu_power.
8589 * cpu_power indicates the capacity of sched group, which is used while
8590 * distributing the load between different sched groups in a sched domain.
8591 * Typically cpu_power for all the groups in a sched domain will be same unless
8592 * there are asymmetries in the topology. If there are asymmetries, group
8593 * having more cpu_power will pickup more load compared to the group having
8594 * less cpu_power.
8596 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
8598 struct sched_domain *child;
8599 struct sched_group *group;
8600 long power;
8601 int weight;
8603 WARN_ON(!sd || !sd->groups);
8605 if (cpu != group_first_cpu(sd->groups))
8606 return;
8608 child = sd->child;
8610 sd->groups->cpu_power = 0;
8612 if (!child) {
8613 power = SCHED_LOAD_SCALE;
8614 weight = cpumask_weight(sched_domain_span(sd));
8616 * SMT siblings share the power of a single core.
8617 * Usually multiple threads get a better yield out of
8618 * that one core than a single thread would have,
8619 * reflect that in sd->smt_gain.
8621 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
8622 power *= sd->smt_gain;
8623 power /= weight;
8624 power >>= SCHED_LOAD_SHIFT;
8626 sd->groups->cpu_power += power;
8627 return;
8631 * Add cpu_power of each child group to this groups cpu_power.
8633 group = child->groups;
8634 do {
8635 sd->groups->cpu_power += group->cpu_power;
8636 group = group->next;
8637 } while (group != child->groups);
8641 * Initializers for schedule domains
8642 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
8645 #ifdef CONFIG_SCHED_DEBUG
8646 # define SD_INIT_NAME(sd, type) sd->name = #type
8647 #else
8648 # define SD_INIT_NAME(sd, type) do { } while (0)
8649 #endif
8651 #define SD_INIT(sd, type) sd_init_##type(sd)
8653 #define SD_INIT_FUNC(type) \
8654 static noinline void sd_init_##type(struct sched_domain *sd) \
8656 memset(sd, 0, sizeof(*sd)); \
8657 *sd = SD_##type##_INIT; \
8658 sd->level = SD_LV_##type; \
8659 SD_INIT_NAME(sd, type); \
8662 SD_INIT_FUNC(CPU)
8663 #ifdef CONFIG_NUMA
8664 SD_INIT_FUNC(ALLNODES)
8665 SD_INIT_FUNC(NODE)
8666 #endif
8667 #ifdef CONFIG_SCHED_SMT
8668 SD_INIT_FUNC(SIBLING)
8669 #endif
8670 #ifdef CONFIG_SCHED_MC
8671 SD_INIT_FUNC(MC)
8672 #endif
8674 static int default_relax_domain_level = -1;
8676 static int __init setup_relax_domain_level(char *str)
8678 unsigned long val;
8680 val = simple_strtoul(str, NULL, 0);
8681 if (val < SD_LV_MAX)
8682 default_relax_domain_level = val;
8684 return 1;
8686 __setup("relax_domain_level=", setup_relax_domain_level);
8688 static void set_domain_attribute(struct sched_domain *sd,
8689 struct sched_domain_attr *attr)
8691 int request;
8693 if (!attr || attr->relax_domain_level < 0) {
8694 if (default_relax_domain_level < 0)
8695 return;
8696 else
8697 request = default_relax_domain_level;
8698 } else
8699 request = attr->relax_domain_level;
8700 if (request < sd->level) {
8701 /* turn off idle balance on this domain */
8702 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
8703 } else {
8704 /* turn on idle balance on this domain */
8705 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
8709 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
8710 const struct cpumask *cpu_map)
8712 switch (what) {
8713 case sa_sched_groups:
8714 free_sched_groups(cpu_map, d->tmpmask); /* fall through */
8715 d->sched_group_nodes = NULL;
8716 case sa_rootdomain:
8717 free_rootdomain(d->rd); /* fall through */
8718 case sa_tmpmask:
8719 free_cpumask_var(d->tmpmask); /* fall through */
8720 case sa_send_covered:
8721 free_cpumask_var(d->send_covered); /* fall through */
8722 case sa_this_core_map:
8723 free_cpumask_var(d->this_core_map); /* fall through */
8724 case sa_this_sibling_map:
8725 free_cpumask_var(d->this_sibling_map); /* fall through */
8726 case sa_nodemask:
8727 free_cpumask_var(d->nodemask); /* fall through */
8728 case sa_sched_group_nodes:
8729 #ifdef CONFIG_NUMA
8730 kfree(d->sched_group_nodes); /* fall through */
8731 case sa_notcovered:
8732 free_cpumask_var(d->notcovered); /* fall through */
8733 case sa_covered:
8734 free_cpumask_var(d->covered); /* fall through */
8735 case sa_domainspan:
8736 free_cpumask_var(d->domainspan); /* fall through */
8737 #endif
8738 case sa_none:
8739 break;
8743 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
8744 const struct cpumask *cpu_map)
8746 #ifdef CONFIG_NUMA
8747 if (!alloc_cpumask_var(&d->domainspan, GFP_KERNEL))
8748 return sa_none;
8749 if (!alloc_cpumask_var(&d->covered, GFP_KERNEL))
8750 return sa_domainspan;
8751 if (!alloc_cpumask_var(&d->notcovered, GFP_KERNEL))
8752 return sa_covered;
8753 /* Allocate the per-node list of sched groups */
8754 d->sched_group_nodes = kcalloc(nr_node_ids,
8755 sizeof(struct sched_group *), GFP_KERNEL);
8756 if (!d->sched_group_nodes) {
8757 printk(KERN_WARNING "Can not alloc sched group node list\n");
8758 return sa_notcovered;
8760 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = d->sched_group_nodes;
8761 #endif
8762 if (!alloc_cpumask_var(&d->nodemask, GFP_KERNEL))
8763 return sa_sched_group_nodes;
8764 if (!alloc_cpumask_var(&d->this_sibling_map, GFP_KERNEL))
8765 return sa_nodemask;
8766 if (!alloc_cpumask_var(&d->this_core_map, GFP_KERNEL))
8767 return sa_this_sibling_map;
8768 if (!alloc_cpumask_var(&d->send_covered, GFP_KERNEL))
8769 return sa_this_core_map;
8770 if (!alloc_cpumask_var(&d->tmpmask, GFP_KERNEL))
8771 return sa_send_covered;
8772 d->rd = alloc_rootdomain();
8773 if (!d->rd) {
8774 printk(KERN_WARNING "Cannot alloc root domain\n");
8775 return sa_tmpmask;
8777 return sa_rootdomain;
8780 static struct sched_domain *__build_numa_sched_domains(struct s_data *d,
8781 const struct cpumask *cpu_map, struct sched_domain_attr *attr, int i)
8783 struct sched_domain *sd = NULL;
8784 #ifdef CONFIG_NUMA
8785 struct sched_domain *parent;
8787 d->sd_allnodes = 0;
8788 if (cpumask_weight(cpu_map) >
8789 SD_NODES_PER_DOMAIN * cpumask_weight(d->nodemask)) {
8790 sd = &per_cpu(allnodes_domains, i).sd;
8791 SD_INIT(sd, ALLNODES);
8792 set_domain_attribute(sd, attr);
8793 cpumask_copy(sched_domain_span(sd), cpu_map);
8794 cpu_to_allnodes_group(i, cpu_map, &sd->groups, d->tmpmask);
8795 d->sd_allnodes = 1;
8797 parent = sd;
8799 sd = &per_cpu(node_domains, i).sd;
8800 SD_INIT(sd, NODE);
8801 set_domain_attribute(sd, attr);
8802 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
8803 sd->parent = parent;
8804 if (parent)
8805 parent->child = sd;
8806 cpumask_and(sched_domain_span(sd), sched_domain_span(sd), cpu_map);
8807 #endif
8808 return sd;
8811 static struct sched_domain *__build_cpu_sched_domain(struct s_data *d,
8812 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
8813 struct sched_domain *parent, int i)
8815 struct sched_domain *sd;
8816 sd = &per_cpu(phys_domains, i).sd;
8817 SD_INIT(sd, CPU);
8818 set_domain_attribute(sd, attr);
8819 cpumask_copy(sched_domain_span(sd), d->nodemask);
8820 sd->parent = parent;
8821 if (parent)
8822 parent->child = sd;
8823 cpu_to_phys_group(i, cpu_map, &sd->groups, d->tmpmask);
8824 return sd;
8827 static struct sched_domain *__build_mc_sched_domain(struct s_data *d,
8828 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
8829 struct sched_domain *parent, int i)
8831 struct sched_domain *sd = parent;
8832 #ifdef CONFIG_SCHED_MC
8833 sd = &per_cpu(core_domains, i).sd;
8834 SD_INIT(sd, MC);
8835 set_domain_attribute(sd, attr);
8836 cpumask_and(sched_domain_span(sd), cpu_map, cpu_coregroup_mask(i));
8837 sd->parent = parent;
8838 parent->child = sd;
8839 cpu_to_core_group(i, cpu_map, &sd->groups, d->tmpmask);
8840 #endif
8841 return sd;
8844 static struct sched_domain *__build_smt_sched_domain(struct s_data *d,
8845 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
8846 struct sched_domain *parent, int i)
8848 struct sched_domain *sd = parent;
8849 #ifdef CONFIG_SCHED_SMT
8850 sd = &per_cpu(cpu_domains, i).sd;
8851 SD_INIT(sd, SIBLING);
8852 set_domain_attribute(sd, attr);
8853 cpumask_and(sched_domain_span(sd), cpu_map, topology_thread_cpumask(i));
8854 sd->parent = parent;
8855 parent->child = sd;
8856 cpu_to_cpu_group(i, cpu_map, &sd->groups, d->tmpmask);
8857 #endif
8858 return sd;
8861 static void build_sched_groups(struct s_data *d, enum sched_domain_level l,
8862 const struct cpumask *cpu_map, int cpu)
8864 switch (l) {
8865 #ifdef CONFIG_SCHED_SMT
8866 case SD_LV_SIBLING: /* set up CPU (sibling) groups */
8867 cpumask_and(d->this_sibling_map, cpu_map,
8868 topology_thread_cpumask(cpu));
8869 if (cpu == cpumask_first(d->this_sibling_map))
8870 init_sched_build_groups(d->this_sibling_map, cpu_map,
8871 &cpu_to_cpu_group,
8872 d->send_covered, d->tmpmask);
8873 break;
8874 #endif
8875 #ifdef CONFIG_SCHED_MC
8876 case SD_LV_MC: /* set up multi-core groups */
8877 cpumask_and(d->this_core_map, cpu_map, cpu_coregroup_mask(cpu));
8878 if (cpu == cpumask_first(d->this_core_map))
8879 init_sched_build_groups(d->this_core_map, cpu_map,
8880 &cpu_to_core_group,
8881 d->send_covered, d->tmpmask);
8882 break;
8883 #endif
8884 case SD_LV_CPU: /* set up physical groups */
8885 cpumask_and(d->nodemask, cpumask_of_node(cpu), cpu_map);
8886 if (!cpumask_empty(d->nodemask))
8887 init_sched_build_groups(d->nodemask, cpu_map,
8888 &cpu_to_phys_group,
8889 d->send_covered, d->tmpmask);
8890 break;
8891 #ifdef CONFIG_NUMA
8892 case SD_LV_ALLNODES:
8893 init_sched_build_groups(cpu_map, cpu_map, &cpu_to_allnodes_group,
8894 d->send_covered, d->tmpmask);
8895 break;
8896 #endif
8897 default:
8898 break;
8903 * Build sched domains for a given set of cpus and attach the sched domains
8904 * to the individual cpus
8906 static int __build_sched_domains(const struct cpumask *cpu_map,
8907 struct sched_domain_attr *attr)
8909 enum s_alloc alloc_state = sa_none;
8910 struct s_data d;
8911 struct sched_domain *sd;
8912 int i;
8913 #ifdef CONFIG_NUMA
8914 d.sd_allnodes = 0;
8915 #endif
8917 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
8918 if (alloc_state != sa_rootdomain)
8919 goto error;
8920 alloc_state = sa_sched_groups;
8923 * Set up domains for cpus specified by the cpu_map.
8925 for_each_cpu(i, cpu_map) {
8926 cpumask_and(d.nodemask, cpumask_of_node(cpu_to_node(i)),
8927 cpu_map);
8929 sd = __build_numa_sched_domains(&d, cpu_map, attr, i);
8930 sd = __build_cpu_sched_domain(&d, cpu_map, attr, sd, i);
8931 sd = __build_mc_sched_domain(&d, cpu_map, attr, sd, i);
8932 sd = __build_smt_sched_domain(&d, cpu_map, attr, sd, i);
8935 for_each_cpu(i, cpu_map) {
8936 build_sched_groups(&d, SD_LV_SIBLING, cpu_map, i);
8937 build_sched_groups(&d, SD_LV_MC, cpu_map, i);
8940 /* Set up physical groups */
8941 for (i = 0; i < nr_node_ids; i++)
8942 build_sched_groups(&d, SD_LV_CPU, cpu_map, i);
8944 #ifdef CONFIG_NUMA
8945 /* Set up node groups */
8946 if (d.sd_allnodes)
8947 build_sched_groups(&d, SD_LV_ALLNODES, cpu_map, 0);
8949 for (i = 0; i < nr_node_ids; i++)
8950 if (build_numa_sched_groups(&d, cpu_map, i))
8951 goto error;
8952 #endif
8954 /* Calculate CPU power for physical packages and nodes */
8955 #ifdef CONFIG_SCHED_SMT
8956 for_each_cpu(i, cpu_map) {
8957 sd = &per_cpu(cpu_domains, i).sd;
8958 init_sched_groups_power(i, sd);
8960 #endif
8961 #ifdef CONFIG_SCHED_MC
8962 for_each_cpu(i, cpu_map) {
8963 sd = &per_cpu(core_domains, i).sd;
8964 init_sched_groups_power(i, sd);
8966 #endif
8968 for_each_cpu(i, cpu_map) {
8969 sd = &per_cpu(phys_domains, i).sd;
8970 init_sched_groups_power(i, sd);
8973 #ifdef CONFIG_NUMA
8974 for (i = 0; i < nr_node_ids; i++)
8975 init_numa_sched_groups_power(d.sched_group_nodes[i]);
8977 if (d.sd_allnodes) {
8978 struct sched_group *sg;
8980 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
8981 d.tmpmask);
8982 init_numa_sched_groups_power(sg);
8984 #endif
8986 /* Attach the domains */
8987 for_each_cpu(i, cpu_map) {
8988 #ifdef CONFIG_SCHED_SMT
8989 sd = &per_cpu(cpu_domains, i).sd;
8990 #elif defined(CONFIG_SCHED_MC)
8991 sd = &per_cpu(core_domains, i).sd;
8992 #else
8993 sd = &per_cpu(phys_domains, i).sd;
8994 #endif
8995 cpu_attach_domain(sd, d.rd, i);
8998 d.sched_group_nodes = NULL; /* don't free this we still need it */
8999 __free_domain_allocs(&d, sa_tmpmask, cpu_map);
9000 return 0;
9002 error:
9003 __free_domain_allocs(&d, alloc_state, cpu_map);
9004 return -ENOMEM;
9007 static int build_sched_domains(const struct cpumask *cpu_map)
9009 return __build_sched_domains(cpu_map, NULL);
9012 static cpumask_var_t *doms_cur; /* current sched domains */
9013 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
9014 static struct sched_domain_attr *dattr_cur;
9015 /* attribues of custom domains in 'doms_cur' */
9018 * Special case: If a kmalloc of a doms_cur partition (array of
9019 * cpumask) fails, then fallback to a single sched domain,
9020 * as determined by the single cpumask fallback_doms.
9022 static cpumask_var_t fallback_doms;
9025 * arch_update_cpu_topology lets virtualized architectures update the
9026 * cpu core maps. It is supposed to return 1 if the topology changed
9027 * or 0 if it stayed the same.
9029 int __attribute__((weak)) arch_update_cpu_topology(void)
9031 return 0;
9034 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
9036 int i;
9037 cpumask_var_t *doms;
9039 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
9040 if (!doms)
9041 return NULL;
9042 for (i = 0; i < ndoms; i++) {
9043 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
9044 free_sched_domains(doms, i);
9045 return NULL;
9048 return doms;
9051 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
9053 unsigned int i;
9054 for (i = 0; i < ndoms; i++)
9055 free_cpumask_var(doms[i]);
9056 kfree(doms);
9060 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
9061 * For now this just excludes isolated cpus, but could be used to
9062 * exclude other special cases in the future.
9064 static int arch_init_sched_domains(const struct cpumask *cpu_map)
9066 int err;
9068 arch_update_cpu_topology();
9069 ndoms_cur = 1;
9070 doms_cur = alloc_sched_domains(ndoms_cur);
9071 if (!doms_cur)
9072 doms_cur = &fallback_doms;
9073 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
9074 dattr_cur = NULL;
9075 err = build_sched_domains(doms_cur[0]);
9076 register_sched_domain_sysctl();
9078 return err;
9081 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
9082 struct cpumask *tmpmask)
9084 free_sched_groups(cpu_map, tmpmask);
9088 * Detach sched domains from a group of cpus specified in cpu_map
9089 * These cpus will now be attached to the NULL domain
9091 static void detach_destroy_domains(const struct cpumask *cpu_map)
9093 /* Save because hotplug lock held. */
9094 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
9095 int i;
9097 for_each_cpu(i, cpu_map)
9098 cpu_attach_domain(NULL, &def_root_domain, i);
9099 synchronize_sched();
9100 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
9103 /* handle null as "default" */
9104 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
9105 struct sched_domain_attr *new, int idx_new)
9107 struct sched_domain_attr tmp;
9109 /* fast path */
9110 if (!new && !cur)
9111 return 1;
9113 tmp = SD_ATTR_INIT;
9114 return !memcmp(cur ? (cur + idx_cur) : &tmp,
9115 new ? (new + idx_new) : &tmp,
9116 sizeof(struct sched_domain_attr));
9120 * Partition sched domains as specified by the 'ndoms_new'
9121 * cpumasks in the array doms_new[] of cpumasks. This compares
9122 * doms_new[] to the current sched domain partitioning, doms_cur[].
9123 * It destroys each deleted domain and builds each new domain.
9125 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
9126 * The masks don't intersect (don't overlap.) We should setup one
9127 * sched domain for each mask. CPUs not in any of the cpumasks will
9128 * not be load balanced. If the same cpumask appears both in the
9129 * current 'doms_cur' domains and in the new 'doms_new', we can leave
9130 * it as it is.
9132 * The passed in 'doms_new' should be allocated using
9133 * alloc_sched_domains. This routine takes ownership of it and will
9134 * free_sched_domains it when done with it. If the caller failed the
9135 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
9136 * and partition_sched_domains() will fallback to the single partition
9137 * 'fallback_doms', it also forces the domains to be rebuilt.
9139 * If doms_new == NULL it will be replaced with cpu_online_mask.
9140 * ndoms_new == 0 is a special case for destroying existing domains,
9141 * and it will not create the default domain.
9143 * Call with hotplug lock held
9145 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
9146 struct sched_domain_attr *dattr_new)
9148 int i, j, n;
9149 int new_topology;
9151 mutex_lock(&sched_domains_mutex);
9153 /* always unregister in case we don't destroy any domains */
9154 unregister_sched_domain_sysctl();
9156 /* Let architecture update cpu core mappings. */
9157 new_topology = arch_update_cpu_topology();
9159 n = doms_new ? ndoms_new : 0;
9161 /* Destroy deleted domains */
9162 for (i = 0; i < ndoms_cur; i++) {
9163 for (j = 0; j < n && !new_topology; j++) {
9164 if (cpumask_equal(doms_cur[i], doms_new[j])
9165 && dattrs_equal(dattr_cur, i, dattr_new, j))
9166 goto match1;
9168 /* no match - a current sched domain not in new doms_new[] */
9169 detach_destroy_domains(doms_cur[i]);
9170 match1:
9174 if (doms_new == NULL) {
9175 ndoms_cur = 0;
9176 doms_new = &fallback_doms;
9177 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
9178 WARN_ON_ONCE(dattr_new);
9181 /* Build new domains */
9182 for (i = 0; i < ndoms_new; i++) {
9183 for (j = 0; j < ndoms_cur && !new_topology; j++) {
9184 if (cpumask_equal(doms_new[i], doms_cur[j])
9185 && dattrs_equal(dattr_new, i, dattr_cur, j))
9186 goto match2;
9188 /* no match - add a new doms_new */
9189 __build_sched_domains(doms_new[i],
9190 dattr_new ? dattr_new + i : NULL);
9191 match2:
9195 /* Remember the new sched domains */
9196 if (doms_cur != &fallback_doms)
9197 free_sched_domains(doms_cur, ndoms_cur);
9198 kfree(dattr_cur); /* kfree(NULL) is safe */
9199 doms_cur = doms_new;
9200 dattr_cur = dattr_new;
9201 ndoms_cur = ndoms_new;
9203 register_sched_domain_sysctl();
9205 mutex_unlock(&sched_domains_mutex);
9208 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
9209 static void arch_reinit_sched_domains(void)
9211 get_online_cpus();
9213 /* Destroy domains first to force the rebuild */
9214 partition_sched_domains(0, NULL, NULL);
9216 rebuild_sched_domains();
9217 put_online_cpus();
9220 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
9222 unsigned int level = 0;
9224 if (sscanf(buf, "%u", &level) != 1)
9225 return -EINVAL;
9228 * level is always be positive so don't check for
9229 * level < POWERSAVINGS_BALANCE_NONE which is 0
9230 * What happens on 0 or 1 byte write,
9231 * need to check for count as well?
9234 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
9235 return -EINVAL;
9237 if (smt)
9238 sched_smt_power_savings = level;
9239 else
9240 sched_mc_power_savings = level;
9242 arch_reinit_sched_domains();
9244 return count;
9247 #ifdef CONFIG_SCHED_MC
9248 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
9249 char *page)
9251 return sprintf(page, "%u\n", sched_mc_power_savings);
9253 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
9254 const char *buf, size_t count)
9256 return sched_power_savings_store(buf, count, 0);
9258 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
9259 sched_mc_power_savings_show,
9260 sched_mc_power_savings_store);
9261 #endif
9263 #ifdef CONFIG_SCHED_SMT
9264 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
9265 char *page)
9267 return sprintf(page, "%u\n", sched_smt_power_savings);
9269 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
9270 const char *buf, size_t count)
9272 return sched_power_savings_store(buf, count, 1);
9274 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
9275 sched_smt_power_savings_show,
9276 sched_smt_power_savings_store);
9277 #endif
9279 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
9281 int err = 0;
9283 #ifdef CONFIG_SCHED_SMT
9284 if (smt_capable())
9285 err = sysfs_create_file(&cls->kset.kobj,
9286 &attr_sched_smt_power_savings.attr);
9287 #endif
9288 #ifdef CONFIG_SCHED_MC
9289 if (!err && mc_capable())
9290 err = sysfs_create_file(&cls->kset.kobj,
9291 &attr_sched_mc_power_savings.attr);
9292 #endif
9293 return err;
9295 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
9297 #ifndef CONFIG_CPUSETS
9299 * Add online and remove offline CPUs from the scheduler domains.
9300 * When cpusets are enabled they take over this function.
9302 static int update_sched_domains(struct notifier_block *nfb,
9303 unsigned long action, void *hcpu)
9305 switch (action) {
9306 case CPU_ONLINE:
9307 case CPU_ONLINE_FROZEN:
9308 case CPU_DOWN_PREPARE:
9309 case CPU_DOWN_PREPARE_FROZEN:
9310 case CPU_DOWN_FAILED:
9311 case CPU_DOWN_FAILED_FROZEN:
9312 partition_sched_domains(1, NULL, NULL);
9313 return NOTIFY_OK;
9315 default:
9316 return NOTIFY_DONE;
9319 #endif
9321 static int update_runtime(struct notifier_block *nfb,
9322 unsigned long action, void *hcpu)
9324 int cpu = (int)(long)hcpu;
9326 switch (action) {
9327 case CPU_DOWN_PREPARE:
9328 case CPU_DOWN_PREPARE_FROZEN:
9329 disable_runtime(cpu_rq(cpu));
9330 return NOTIFY_OK;
9332 case CPU_DOWN_FAILED:
9333 case CPU_DOWN_FAILED_FROZEN:
9334 case CPU_ONLINE:
9335 case CPU_ONLINE_FROZEN:
9336 enable_runtime(cpu_rq(cpu));
9337 return NOTIFY_OK;
9339 default:
9340 return NOTIFY_DONE;
9344 void __init sched_init_smp(void)
9346 cpumask_var_t non_isolated_cpus;
9348 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
9349 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
9351 #if defined(CONFIG_NUMA)
9352 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
9353 GFP_KERNEL);
9354 BUG_ON(sched_group_nodes_bycpu == NULL);
9355 #endif
9356 get_online_cpus();
9357 mutex_lock(&sched_domains_mutex);
9358 arch_init_sched_domains(cpu_active_mask);
9359 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
9360 if (cpumask_empty(non_isolated_cpus))
9361 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
9362 mutex_unlock(&sched_domains_mutex);
9363 put_online_cpus();
9365 #ifndef CONFIG_CPUSETS
9366 /* XXX: Theoretical race here - CPU may be hotplugged now */
9367 hotcpu_notifier(update_sched_domains, 0);
9368 #endif
9370 /* RT runtime code needs to handle some hotplug events */
9371 hotcpu_notifier(update_runtime, 0);
9373 init_hrtick();
9375 /* Move init over to a non-isolated CPU */
9376 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
9377 BUG();
9378 sched_init_granularity();
9379 free_cpumask_var(non_isolated_cpus);
9381 init_sched_rt_class();
9383 #else
9384 void __init sched_init_smp(void)
9386 sched_init_granularity();
9388 #endif /* CONFIG_SMP */
9390 const_debug unsigned int sysctl_timer_migration = 1;
9392 int in_sched_functions(unsigned long addr)
9394 return in_lock_functions(addr) ||
9395 (addr >= (unsigned long)__sched_text_start
9396 && addr < (unsigned long)__sched_text_end);
9399 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
9401 cfs_rq->tasks_timeline = RB_ROOT;
9402 INIT_LIST_HEAD(&cfs_rq->tasks);
9403 #ifdef CONFIG_FAIR_GROUP_SCHED
9404 cfs_rq->rq = rq;
9405 #endif
9406 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
9409 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
9411 struct rt_prio_array *array;
9412 int i;
9414 array = &rt_rq->active;
9415 for (i = 0; i < MAX_RT_PRIO; i++) {
9416 INIT_LIST_HEAD(array->queue + i);
9417 __clear_bit(i, array->bitmap);
9419 /* delimiter for bitsearch: */
9420 __set_bit(MAX_RT_PRIO, array->bitmap);
9422 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
9423 rt_rq->highest_prio.curr = MAX_RT_PRIO;
9424 #ifdef CONFIG_SMP
9425 rt_rq->highest_prio.next = MAX_RT_PRIO;
9426 #endif
9427 #endif
9428 #ifdef CONFIG_SMP
9429 rt_rq->rt_nr_migratory = 0;
9430 rt_rq->overloaded = 0;
9431 plist_head_init_raw(&rt_rq->pushable_tasks, &rq->lock);
9432 #endif
9434 rt_rq->rt_time = 0;
9435 rt_rq->rt_throttled = 0;
9436 rt_rq->rt_runtime = 0;
9437 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
9439 #ifdef CONFIG_RT_GROUP_SCHED
9440 rt_rq->rt_nr_boosted = 0;
9441 rt_rq->rq = rq;
9442 #endif
9445 #ifdef CONFIG_FAIR_GROUP_SCHED
9446 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
9447 struct sched_entity *se, int cpu, int add,
9448 struct sched_entity *parent)
9450 struct rq *rq = cpu_rq(cpu);
9451 tg->cfs_rq[cpu] = cfs_rq;
9452 init_cfs_rq(cfs_rq, rq);
9453 cfs_rq->tg = tg;
9454 if (add)
9455 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
9457 tg->se[cpu] = se;
9458 /* se could be NULL for init_task_group */
9459 if (!se)
9460 return;
9462 if (!parent)
9463 se->cfs_rq = &rq->cfs;
9464 else
9465 se->cfs_rq = parent->my_q;
9467 se->my_q = cfs_rq;
9468 se->load.weight = tg->shares;
9469 se->load.inv_weight = 0;
9470 se->parent = parent;
9472 #endif
9474 #ifdef CONFIG_RT_GROUP_SCHED
9475 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
9476 struct sched_rt_entity *rt_se, int cpu, int add,
9477 struct sched_rt_entity *parent)
9479 struct rq *rq = cpu_rq(cpu);
9481 tg->rt_rq[cpu] = rt_rq;
9482 init_rt_rq(rt_rq, rq);
9483 rt_rq->tg = tg;
9484 rt_rq->rt_se = rt_se;
9485 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
9486 if (add)
9487 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
9489 tg->rt_se[cpu] = rt_se;
9490 if (!rt_se)
9491 return;
9493 if (!parent)
9494 rt_se->rt_rq = &rq->rt;
9495 else
9496 rt_se->rt_rq = parent->my_q;
9498 rt_se->my_q = rt_rq;
9499 rt_se->parent = parent;
9500 INIT_LIST_HEAD(&rt_se->run_list);
9502 #endif
9504 void __init sched_init(void)
9506 int i, j;
9507 unsigned long alloc_size = 0, ptr;
9509 #ifdef CONFIG_FAIR_GROUP_SCHED
9510 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9511 #endif
9512 #ifdef CONFIG_RT_GROUP_SCHED
9513 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
9514 #endif
9515 #ifdef CONFIG_USER_SCHED
9516 alloc_size *= 2;
9517 #endif
9518 #ifdef CONFIG_CPUMASK_OFFSTACK
9519 alloc_size += num_possible_cpus() * cpumask_size();
9520 #endif
9521 if (alloc_size) {
9522 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
9524 #ifdef CONFIG_FAIR_GROUP_SCHED
9525 init_task_group.se = (struct sched_entity **)ptr;
9526 ptr += nr_cpu_ids * sizeof(void **);
9528 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
9529 ptr += nr_cpu_ids * sizeof(void **);
9531 #ifdef CONFIG_USER_SCHED
9532 root_task_group.se = (struct sched_entity **)ptr;
9533 ptr += nr_cpu_ids * sizeof(void **);
9535 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
9536 ptr += nr_cpu_ids * sizeof(void **);
9537 #endif /* CONFIG_USER_SCHED */
9538 #endif /* CONFIG_FAIR_GROUP_SCHED */
9539 #ifdef CONFIG_RT_GROUP_SCHED
9540 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
9541 ptr += nr_cpu_ids * sizeof(void **);
9543 init_task_group.rt_rq = (struct rt_rq **)ptr;
9544 ptr += nr_cpu_ids * sizeof(void **);
9546 #ifdef CONFIG_USER_SCHED
9547 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
9548 ptr += nr_cpu_ids * sizeof(void **);
9550 root_task_group.rt_rq = (struct rt_rq **)ptr;
9551 ptr += nr_cpu_ids * sizeof(void **);
9552 #endif /* CONFIG_USER_SCHED */
9553 #endif /* CONFIG_RT_GROUP_SCHED */
9554 #ifdef CONFIG_CPUMASK_OFFSTACK
9555 for_each_possible_cpu(i) {
9556 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
9557 ptr += cpumask_size();
9559 #endif /* CONFIG_CPUMASK_OFFSTACK */
9562 #ifdef CONFIG_SMP
9563 init_defrootdomain();
9564 #endif
9566 init_rt_bandwidth(&def_rt_bandwidth,
9567 global_rt_period(), global_rt_runtime());
9569 #ifdef CONFIG_RT_GROUP_SCHED
9570 init_rt_bandwidth(&init_task_group.rt_bandwidth,
9571 global_rt_period(), global_rt_runtime());
9572 #ifdef CONFIG_USER_SCHED
9573 init_rt_bandwidth(&root_task_group.rt_bandwidth,
9574 global_rt_period(), RUNTIME_INF);
9575 #endif /* CONFIG_USER_SCHED */
9576 #endif /* CONFIG_RT_GROUP_SCHED */
9578 #ifdef CONFIG_GROUP_SCHED
9579 list_add(&init_task_group.list, &task_groups);
9580 INIT_LIST_HEAD(&init_task_group.children);
9582 #ifdef CONFIG_USER_SCHED
9583 INIT_LIST_HEAD(&root_task_group.children);
9584 init_task_group.parent = &root_task_group;
9585 list_add(&init_task_group.siblings, &root_task_group.children);
9586 #endif /* CONFIG_USER_SCHED */
9587 #endif /* CONFIG_GROUP_SCHED */
9589 #if defined CONFIG_FAIR_GROUP_SCHED && defined CONFIG_SMP
9590 update_shares_data = __alloc_percpu(nr_cpu_ids * sizeof(unsigned long),
9591 __alignof__(unsigned long));
9592 #endif
9593 for_each_possible_cpu(i) {
9594 struct rq *rq;
9596 rq = cpu_rq(i);
9597 raw_spin_lock_init(&rq->lock);
9598 rq->nr_running = 0;
9599 rq->calc_load_active = 0;
9600 rq->calc_load_update = jiffies + LOAD_FREQ;
9601 init_cfs_rq(&rq->cfs, rq);
9602 init_rt_rq(&rq->rt, rq);
9603 #ifdef CONFIG_FAIR_GROUP_SCHED
9604 init_task_group.shares = init_task_group_load;
9605 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9606 #ifdef CONFIG_CGROUP_SCHED
9608 * How much cpu bandwidth does init_task_group get?
9610 * In case of task-groups formed thr' the cgroup filesystem, it
9611 * gets 100% of the cpu resources in the system. This overall
9612 * system cpu resource is divided among the tasks of
9613 * init_task_group and its child task-groups in a fair manner,
9614 * based on each entity's (task or task-group's) weight
9615 * (se->load.weight).
9617 * In other words, if init_task_group has 10 tasks of weight
9618 * 1024) and two child groups A0 and A1 (of weight 1024 each),
9619 * then A0's share of the cpu resource is:
9621 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
9623 * We achieve this by letting init_task_group's tasks sit
9624 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
9626 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
9627 #elif defined CONFIG_USER_SCHED
9628 root_task_group.shares = NICE_0_LOAD;
9629 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
9631 * In case of task-groups formed thr' the user id of tasks,
9632 * init_task_group represents tasks belonging to root user.
9633 * Hence it forms a sibling of all subsequent groups formed.
9634 * In this case, init_task_group gets only a fraction of overall
9635 * system cpu resource, based on the weight assigned to root
9636 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
9637 * by letting tasks of init_task_group sit in a separate cfs_rq
9638 * (init_tg_cfs_rq) and having one entity represent this group of
9639 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
9641 init_tg_cfs_entry(&init_task_group,
9642 &per_cpu(init_tg_cfs_rq, i),
9643 &per_cpu(init_sched_entity, i), i, 1,
9644 root_task_group.se[i]);
9646 #endif
9647 #endif /* CONFIG_FAIR_GROUP_SCHED */
9649 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
9650 #ifdef CONFIG_RT_GROUP_SCHED
9651 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
9652 #ifdef CONFIG_CGROUP_SCHED
9653 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
9654 #elif defined CONFIG_USER_SCHED
9655 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
9656 init_tg_rt_entry(&init_task_group,
9657 &per_cpu(init_rt_rq_var, i),
9658 &per_cpu(init_sched_rt_entity, i), i, 1,
9659 root_task_group.rt_se[i]);
9660 #endif
9661 #endif
9663 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
9664 rq->cpu_load[j] = 0;
9665 #ifdef CONFIG_SMP
9666 rq->sd = NULL;
9667 rq->rd = NULL;
9668 rq->post_schedule = 0;
9669 rq->active_balance = 0;
9670 rq->next_balance = jiffies;
9671 rq->push_cpu = 0;
9672 rq->cpu = i;
9673 rq->online = 0;
9674 rq->migration_thread = NULL;
9675 rq->idle_stamp = 0;
9676 rq->avg_idle = 2*sysctl_sched_migration_cost;
9677 INIT_LIST_HEAD(&rq->migration_queue);
9678 rq_attach_root(rq, &def_root_domain);
9679 #endif
9680 init_rq_hrtick(rq);
9681 atomic_set(&rq->nr_iowait, 0);
9684 set_load_weight(&init_task);
9686 #ifdef CONFIG_PREEMPT_NOTIFIERS
9687 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
9688 #endif
9690 #ifdef CONFIG_SMP
9691 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
9692 #endif
9694 #ifdef CONFIG_RT_MUTEXES
9695 plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock);
9696 #endif
9699 * The boot idle thread does lazy MMU switching as well:
9701 atomic_inc(&init_mm.mm_count);
9702 enter_lazy_tlb(&init_mm, current);
9705 * Make us the idle thread. Technically, schedule() should not be
9706 * called from this thread, however somewhere below it might be,
9707 * but because we are the idle thread, we just pick up running again
9708 * when this runqueue becomes "idle".
9710 init_idle(current, smp_processor_id());
9712 calc_load_update = jiffies + LOAD_FREQ;
9715 * During early bootup we pretend to be a normal task:
9717 current->sched_class = &fair_sched_class;
9719 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
9720 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
9721 #ifdef CONFIG_SMP
9722 #ifdef CONFIG_NO_HZ
9723 zalloc_cpumask_var(&nohz.cpu_mask, GFP_NOWAIT);
9724 alloc_cpumask_var(&nohz.ilb_grp_nohz_mask, GFP_NOWAIT);
9725 #endif
9726 /* May be allocated at isolcpus cmdline parse time */
9727 if (cpu_isolated_map == NULL)
9728 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
9729 #endif /* SMP */
9731 perf_event_init();
9733 scheduler_running = 1;
9736 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
9737 static inline int preempt_count_equals(int preempt_offset)
9739 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
9741 return (nested == PREEMPT_INATOMIC_BASE + preempt_offset);
9744 void __might_sleep(char *file, int line, int preempt_offset)
9746 #ifdef in_atomic
9747 static unsigned long prev_jiffy; /* ratelimiting */
9749 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
9750 system_state != SYSTEM_RUNNING || oops_in_progress)
9751 return;
9752 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
9753 return;
9754 prev_jiffy = jiffies;
9756 printk(KERN_ERR
9757 "BUG: sleeping function called from invalid context at %s:%d\n",
9758 file, line);
9759 printk(KERN_ERR
9760 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
9761 in_atomic(), irqs_disabled(),
9762 current->pid, current->comm);
9764 debug_show_held_locks(current);
9765 if (irqs_disabled())
9766 print_irqtrace_events(current);
9767 dump_stack();
9768 #endif
9770 EXPORT_SYMBOL(__might_sleep);
9771 #endif
9773 #ifdef CONFIG_MAGIC_SYSRQ
9774 static void normalize_task(struct rq *rq, struct task_struct *p)
9776 int on_rq;
9778 update_rq_clock(rq);
9779 on_rq = p->se.on_rq;
9780 if (on_rq)
9781 deactivate_task(rq, p, 0);
9782 __setscheduler(rq, p, SCHED_NORMAL, 0);
9783 if (on_rq) {
9784 activate_task(rq, p, 0);
9785 resched_task(rq->curr);
9789 void normalize_rt_tasks(void)
9791 struct task_struct *g, *p;
9792 unsigned long flags;
9793 struct rq *rq;
9795 read_lock_irqsave(&tasklist_lock, flags);
9796 do_each_thread(g, p) {
9798 * Only normalize user tasks:
9800 if (!p->mm)
9801 continue;
9803 p->se.exec_start = 0;
9804 #ifdef CONFIG_SCHEDSTATS
9805 p->se.wait_start = 0;
9806 p->se.sleep_start = 0;
9807 p->se.block_start = 0;
9808 #endif
9810 if (!rt_task(p)) {
9812 * Renice negative nice level userspace
9813 * tasks back to 0:
9815 if (TASK_NICE(p) < 0 && p->mm)
9816 set_user_nice(p, 0);
9817 continue;
9820 raw_spin_lock(&p->pi_lock);
9821 rq = __task_rq_lock(p);
9823 normalize_task(rq, p);
9825 __task_rq_unlock(rq);
9826 raw_spin_unlock(&p->pi_lock);
9827 } while_each_thread(g, p);
9829 read_unlock_irqrestore(&tasklist_lock, flags);
9832 #endif /* CONFIG_MAGIC_SYSRQ */
9834 #ifdef CONFIG_IA64
9836 * These functions are only useful for the IA64 MCA handling.
9838 * They can only be called when the whole system has been
9839 * stopped - every CPU needs to be quiescent, and no scheduling
9840 * activity can take place. Using them for anything else would
9841 * be a serious bug, and as a result, they aren't even visible
9842 * under any other configuration.
9846 * curr_task - return the current task for a given cpu.
9847 * @cpu: the processor in question.
9849 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9851 struct task_struct *curr_task(int cpu)
9853 return cpu_curr(cpu);
9857 * set_curr_task - set the current task for a given cpu.
9858 * @cpu: the processor in question.
9859 * @p: the task pointer to set.
9861 * Description: This function must only be used when non-maskable interrupts
9862 * are serviced on a separate stack. It allows the architecture to switch the
9863 * notion of the current task on a cpu in a non-blocking manner. This function
9864 * must be called with all CPU's synchronized, and interrupts disabled, the
9865 * and caller must save the original value of the current task (see
9866 * curr_task() above) and restore that value before reenabling interrupts and
9867 * re-starting the system.
9869 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
9871 void set_curr_task(int cpu, struct task_struct *p)
9873 cpu_curr(cpu) = p;
9876 #endif
9878 #ifdef CONFIG_FAIR_GROUP_SCHED
9879 static void free_fair_sched_group(struct task_group *tg)
9881 int i;
9883 for_each_possible_cpu(i) {
9884 if (tg->cfs_rq)
9885 kfree(tg->cfs_rq[i]);
9886 if (tg->se)
9887 kfree(tg->se[i]);
9890 kfree(tg->cfs_rq);
9891 kfree(tg->se);
9894 static
9895 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9897 struct cfs_rq *cfs_rq;
9898 struct sched_entity *se;
9899 struct rq *rq;
9900 int i;
9902 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
9903 if (!tg->cfs_rq)
9904 goto err;
9905 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
9906 if (!tg->se)
9907 goto err;
9909 tg->shares = NICE_0_LOAD;
9911 for_each_possible_cpu(i) {
9912 rq = cpu_rq(i);
9914 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
9915 GFP_KERNEL, cpu_to_node(i));
9916 if (!cfs_rq)
9917 goto err;
9919 se = kzalloc_node(sizeof(struct sched_entity),
9920 GFP_KERNEL, cpu_to_node(i));
9921 if (!se)
9922 goto err_free_rq;
9924 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent->se[i]);
9927 return 1;
9929 err_free_rq:
9930 kfree(cfs_rq);
9931 err:
9932 return 0;
9935 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9937 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
9938 &cpu_rq(cpu)->leaf_cfs_rq_list);
9941 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9943 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
9945 #else /* !CONFG_FAIR_GROUP_SCHED */
9946 static inline void free_fair_sched_group(struct task_group *tg)
9950 static inline
9951 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
9953 return 1;
9956 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
9960 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
9963 #endif /* CONFIG_FAIR_GROUP_SCHED */
9965 #ifdef CONFIG_RT_GROUP_SCHED
9966 static void free_rt_sched_group(struct task_group *tg)
9968 int i;
9970 destroy_rt_bandwidth(&tg->rt_bandwidth);
9972 for_each_possible_cpu(i) {
9973 if (tg->rt_rq)
9974 kfree(tg->rt_rq[i]);
9975 if (tg->rt_se)
9976 kfree(tg->rt_se[i]);
9979 kfree(tg->rt_rq);
9980 kfree(tg->rt_se);
9983 static
9984 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
9986 struct rt_rq *rt_rq;
9987 struct sched_rt_entity *rt_se;
9988 struct rq *rq;
9989 int i;
9991 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
9992 if (!tg->rt_rq)
9993 goto err;
9994 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
9995 if (!tg->rt_se)
9996 goto err;
9998 init_rt_bandwidth(&tg->rt_bandwidth,
9999 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
10001 for_each_possible_cpu(i) {
10002 rq = cpu_rq(i);
10004 rt_rq = kzalloc_node(sizeof(struct rt_rq),
10005 GFP_KERNEL, cpu_to_node(i));
10006 if (!rt_rq)
10007 goto err;
10009 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
10010 GFP_KERNEL, cpu_to_node(i));
10011 if (!rt_se)
10012 goto err_free_rq;
10014 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent->rt_se[i]);
10017 return 1;
10019 err_free_rq:
10020 kfree(rt_rq);
10021 err:
10022 return 0;
10025 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
10027 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
10028 &cpu_rq(cpu)->leaf_rt_rq_list);
10031 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
10033 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
10035 #else /* !CONFIG_RT_GROUP_SCHED */
10036 static inline void free_rt_sched_group(struct task_group *tg)
10040 static inline
10041 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
10043 return 1;
10046 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
10050 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
10053 #endif /* CONFIG_RT_GROUP_SCHED */
10055 #ifdef CONFIG_GROUP_SCHED
10056 static void free_sched_group(struct task_group *tg)
10058 free_fair_sched_group(tg);
10059 free_rt_sched_group(tg);
10060 kfree(tg);
10063 /* allocate runqueue etc for a new task group */
10064 struct task_group *sched_create_group(struct task_group *parent)
10066 struct task_group *tg;
10067 unsigned long flags;
10068 int i;
10070 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
10071 if (!tg)
10072 return ERR_PTR(-ENOMEM);
10074 if (!alloc_fair_sched_group(tg, parent))
10075 goto err;
10077 if (!alloc_rt_sched_group(tg, parent))
10078 goto err;
10080 spin_lock_irqsave(&task_group_lock, flags);
10081 for_each_possible_cpu(i) {
10082 register_fair_sched_group(tg, i);
10083 register_rt_sched_group(tg, i);
10085 list_add_rcu(&tg->list, &task_groups);
10087 WARN_ON(!parent); /* root should already exist */
10089 tg->parent = parent;
10090 INIT_LIST_HEAD(&tg->children);
10091 list_add_rcu(&tg->siblings, &parent->children);
10092 spin_unlock_irqrestore(&task_group_lock, flags);
10094 return tg;
10096 err:
10097 free_sched_group(tg);
10098 return ERR_PTR(-ENOMEM);
10101 /* rcu callback to free various structures associated with a task group */
10102 static void free_sched_group_rcu(struct rcu_head *rhp)
10104 /* now it should be safe to free those cfs_rqs */
10105 free_sched_group(container_of(rhp, struct task_group, rcu));
10108 /* Destroy runqueue etc associated with a task group */
10109 void sched_destroy_group(struct task_group *tg)
10111 unsigned long flags;
10112 int i;
10114 spin_lock_irqsave(&task_group_lock, flags);
10115 for_each_possible_cpu(i) {
10116 unregister_fair_sched_group(tg, i);
10117 unregister_rt_sched_group(tg, i);
10119 list_del_rcu(&tg->list);
10120 list_del_rcu(&tg->siblings);
10121 spin_unlock_irqrestore(&task_group_lock, flags);
10123 /* wait for possible concurrent references to cfs_rqs complete */
10124 call_rcu(&tg->rcu, free_sched_group_rcu);
10127 /* change task's runqueue when it moves between groups.
10128 * The caller of this function should have put the task in its new group
10129 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
10130 * reflect its new group.
10132 void sched_move_task(struct task_struct *tsk)
10134 int on_rq, running;
10135 unsigned long flags;
10136 struct rq *rq;
10138 rq = task_rq_lock(tsk, &flags);
10140 update_rq_clock(rq);
10142 running = task_current(rq, tsk);
10143 on_rq = tsk->se.on_rq;
10145 if (on_rq)
10146 dequeue_task(rq, tsk, 0);
10147 if (unlikely(running))
10148 tsk->sched_class->put_prev_task(rq, tsk);
10150 set_task_rq(tsk, task_cpu(tsk));
10152 #ifdef CONFIG_FAIR_GROUP_SCHED
10153 if (tsk->sched_class->moved_group)
10154 tsk->sched_class->moved_group(tsk, on_rq);
10155 #endif
10157 if (unlikely(running))
10158 tsk->sched_class->set_curr_task(rq);
10159 if (on_rq)
10160 enqueue_task(rq, tsk, 0);
10162 task_rq_unlock(rq, &flags);
10164 #endif /* CONFIG_GROUP_SCHED */
10166 #ifdef CONFIG_FAIR_GROUP_SCHED
10167 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
10169 struct cfs_rq *cfs_rq = se->cfs_rq;
10170 int on_rq;
10172 on_rq = se->on_rq;
10173 if (on_rq)
10174 dequeue_entity(cfs_rq, se, 0);
10176 se->load.weight = shares;
10177 se->load.inv_weight = 0;
10179 if (on_rq)
10180 enqueue_entity(cfs_rq, se, 0);
10183 static void set_se_shares(struct sched_entity *se, unsigned long shares)
10185 struct cfs_rq *cfs_rq = se->cfs_rq;
10186 struct rq *rq = cfs_rq->rq;
10187 unsigned long flags;
10189 raw_spin_lock_irqsave(&rq->lock, flags);
10190 __set_se_shares(se, shares);
10191 raw_spin_unlock_irqrestore(&rq->lock, flags);
10194 static DEFINE_MUTEX(shares_mutex);
10196 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
10198 int i;
10199 unsigned long flags;
10202 * We can't change the weight of the root cgroup.
10204 if (!tg->se[0])
10205 return -EINVAL;
10207 if (shares < MIN_SHARES)
10208 shares = MIN_SHARES;
10209 else if (shares > MAX_SHARES)
10210 shares = MAX_SHARES;
10212 mutex_lock(&shares_mutex);
10213 if (tg->shares == shares)
10214 goto done;
10216 spin_lock_irqsave(&task_group_lock, flags);
10217 for_each_possible_cpu(i)
10218 unregister_fair_sched_group(tg, i);
10219 list_del_rcu(&tg->siblings);
10220 spin_unlock_irqrestore(&task_group_lock, flags);
10222 /* wait for any ongoing reference to this group to finish */
10223 synchronize_sched();
10226 * Now we are free to modify the group's share on each cpu
10227 * w/o tripping rebalance_share or load_balance_fair.
10229 tg->shares = shares;
10230 for_each_possible_cpu(i) {
10232 * force a rebalance
10234 cfs_rq_set_shares(tg->cfs_rq[i], 0);
10235 set_se_shares(tg->se[i], shares);
10239 * Enable load balance activity on this group, by inserting it back on
10240 * each cpu's rq->leaf_cfs_rq_list.
10242 spin_lock_irqsave(&task_group_lock, flags);
10243 for_each_possible_cpu(i)
10244 register_fair_sched_group(tg, i);
10245 list_add_rcu(&tg->siblings, &tg->parent->children);
10246 spin_unlock_irqrestore(&task_group_lock, flags);
10247 done:
10248 mutex_unlock(&shares_mutex);
10249 return 0;
10252 unsigned long sched_group_shares(struct task_group *tg)
10254 return tg->shares;
10256 #endif
10258 #ifdef CONFIG_RT_GROUP_SCHED
10260 * Ensure that the real time constraints are schedulable.
10262 static DEFINE_MUTEX(rt_constraints_mutex);
10264 static unsigned long to_ratio(u64 period, u64 runtime)
10266 if (runtime == RUNTIME_INF)
10267 return 1ULL << 20;
10269 return div64_u64(runtime << 20, period);
10272 /* Must be called with tasklist_lock held */
10273 static inline int tg_has_rt_tasks(struct task_group *tg)
10275 struct task_struct *g, *p;
10277 do_each_thread(g, p) {
10278 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
10279 return 1;
10280 } while_each_thread(g, p);
10282 return 0;
10285 struct rt_schedulable_data {
10286 struct task_group *tg;
10287 u64 rt_period;
10288 u64 rt_runtime;
10291 static int tg_schedulable(struct task_group *tg, void *data)
10293 struct rt_schedulable_data *d = data;
10294 struct task_group *child;
10295 unsigned long total, sum = 0;
10296 u64 period, runtime;
10298 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10299 runtime = tg->rt_bandwidth.rt_runtime;
10301 if (tg == d->tg) {
10302 period = d->rt_period;
10303 runtime = d->rt_runtime;
10306 #ifdef CONFIG_USER_SCHED
10307 if (tg == &root_task_group) {
10308 period = global_rt_period();
10309 runtime = global_rt_runtime();
10311 #endif
10314 * Cannot have more runtime than the period.
10316 if (runtime > period && runtime != RUNTIME_INF)
10317 return -EINVAL;
10320 * Ensure we don't starve existing RT tasks.
10322 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
10323 return -EBUSY;
10325 total = to_ratio(period, runtime);
10328 * Nobody can have more than the global setting allows.
10330 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
10331 return -EINVAL;
10334 * The sum of our children's runtime should not exceed our own.
10336 list_for_each_entry_rcu(child, &tg->children, siblings) {
10337 period = ktime_to_ns(child->rt_bandwidth.rt_period);
10338 runtime = child->rt_bandwidth.rt_runtime;
10340 if (child == d->tg) {
10341 period = d->rt_period;
10342 runtime = d->rt_runtime;
10345 sum += to_ratio(period, runtime);
10348 if (sum > total)
10349 return -EINVAL;
10351 return 0;
10354 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
10356 struct rt_schedulable_data data = {
10357 .tg = tg,
10358 .rt_period = period,
10359 .rt_runtime = runtime,
10362 return walk_tg_tree(tg_schedulable, tg_nop, &data);
10365 static int tg_set_bandwidth(struct task_group *tg,
10366 u64 rt_period, u64 rt_runtime)
10368 int i, err = 0;
10370 mutex_lock(&rt_constraints_mutex);
10371 read_lock(&tasklist_lock);
10372 err = __rt_schedulable(tg, rt_period, rt_runtime);
10373 if (err)
10374 goto unlock;
10376 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10377 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
10378 tg->rt_bandwidth.rt_runtime = rt_runtime;
10380 for_each_possible_cpu(i) {
10381 struct rt_rq *rt_rq = tg->rt_rq[i];
10383 raw_spin_lock(&rt_rq->rt_runtime_lock);
10384 rt_rq->rt_runtime = rt_runtime;
10385 raw_spin_unlock(&rt_rq->rt_runtime_lock);
10387 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
10388 unlock:
10389 read_unlock(&tasklist_lock);
10390 mutex_unlock(&rt_constraints_mutex);
10392 return err;
10395 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
10397 u64 rt_runtime, rt_period;
10399 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
10400 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
10401 if (rt_runtime_us < 0)
10402 rt_runtime = RUNTIME_INF;
10404 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10407 long sched_group_rt_runtime(struct task_group *tg)
10409 u64 rt_runtime_us;
10411 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
10412 return -1;
10414 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
10415 do_div(rt_runtime_us, NSEC_PER_USEC);
10416 return rt_runtime_us;
10419 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
10421 u64 rt_runtime, rt_period;
10423 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
10424 rt_runtime = tg->rt_bandwidth.rt_runtime;
10426 if (rt_period == 0)
10427 return -EINVAL;
10429 return tg_set_bandwidth(tg, rt_period, rt_runtime);
10432 long sched_group_rt_period(struct task_group *tg)
10434 u64 rt_period_us;
10436 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
10437 do_div(rt_period_us, NSEC_PER_USEC);
10438 return rt_period_us;
10441 static int sched_rt_global_constraints(void)
10443 u64 runtime, period;
10444 int ret = 0;
10446 if (sysctl_sched_rt_period <= 0)
10447 return -EINVAL;
10449 runtime = global_rt_runtime();
10450 period = global_rt_period();
10453 * Sanity check on the sysctl variables.
10455 if (runtime > period && runtime != RUNTIME_INF)
10456 return -EINVAL;
10458 mutex_lock(&rt_constraints_mutex);
10459 read_lock(&tasklist_lock);
10460 ret = __rt_schedulable(NULL, 0, 0);
10461 read_unlock(&tasklist_lock);
10462 mutex_unlock(&rt_constraints_mutex);
10464 return ret;
10467 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
10469 /* Don't accept realtime tasks when there is no way for them to run */
10470 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
10471 return 0;
10473 return 1;
10476 #else /* !CONFIG_RT_GROUP_SCHED */
10477 static int sched_rt_global_constraints(void)
10479 unsigned long flags;
10480 int i;
10482 if (sysctl_sched_rt_period <= 0)
10483 return -EINVAL;
10486 * There's always some RT tasks in the root group
10487 * -- migration, kstopmachine etc..
10489 if (sysctl_sched_rt_runtime == 0)
10490 return -EBUSY;
10492 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
10493 for_each_possible_cpu(i) {
10494 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
10496 raw_spin_lock(&rt_rq->rt_runtime_lock);
10497 rt_rq->rt_runtime = global_rt_runtime();
10498 raw_spin_unlock(&rt_rq->rt_runtime_lock);
10500 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
10502 return 0;
10504 #endif /* CONFIG_RT_GROUP_SCHED */
10506 int sched_rt_handler(struct ctl_table *table, int write,
10507 void __user *buffer, size_t *lenp,
10508 loff_t *ppos)
10510 int ret;
10511 int old_period, old_runtime;
10512 static DEFINE_MUTEX(mutex);
10514 mutex_lock(&mutex);
10515 old_period = sysctl_sched_rt_period;
10516 old_runtime = sysctl_sched_rt_runtime;
10518 ret = proc_dointvec(table, write, buffer, lenp, ppos);
10520 if (!ret && write) {
10521 ret = sched_rt_global_constraints();
10522 if (ret) {
10523 sysctl_sched_rt_period = old_period;
10524 sysctl_sched_rt_runtime = old_runtime;
10525 } else {
10526 def_rt_bandwidth.rt_runtime = global_rt_runtime();
10527 def_rt_bandwidth.rt_period =
10528 ns_to_ktime(global_rt_period());
10531 mutex_unlock(&mutex);
10533 return ret;
10536 #ifdef CONFIG_CGROUP_SCHED
10538 /* return corresponding task_group object of a cgroup */
10539 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
10541 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
10542 struct task_group, css);
10545 static struct cgroup_subsys_state *
10546 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
10548 struct task_group *tg, *parent;
10550 if (!cgrp->parent) {
10551 /* This is early initialization for the top cgroup */
10552 return &init_task_group.css;
10555 parent = cgroup_tg(cgrp->parent);
10556 tg = sched_create_group(parent);
10557 if (IS_ERR(tg))
10558 return ERR_PTR(-ENOMEM);
10560 return &tg->css;
10563 static void
10564 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10566 struct task_group *tg = cgroup_tg(cgrp);
10568 sched_destroy_group(tg);
10571 static int
10572 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
10574 #ifdef CONFIG_RT_GROUP_SCHED
10575 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
10576 return -EINVAL;
10577 #else
10578 /* We don't support RT-tasks being in separate groups */
10579 if (tsk->sched_class != &fair_sched_class)
10580 return -EINVAL;
10581 #endif
10582 return 0;
10585 static int
10586 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10587 struct task_struct *tsk, bool threadgroup)
10589 int retval = cpu_cgroup_can_attach_task(cgrp, tsk);
10590 if (retval)
10591 return retval;
10592 if (threadgroup) {
10593 struct task_struct *c;
10594 rcu_read_lock();
10595 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
10596 retval = cpu_cgroup_can_attach_task(cgrp, c);
10597 if (retval) {
10598 rcu_read_unlock();
10599 return retval;
10602 rcu_read_unlock();
10604 return 0;
10607 static void
10608 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
10609 struct cgroup *old_cont, struct task_struct *tsk,
10610 bool threadgroup)
10612 sched_move_task(tsk);
10613 if (threadgroup) {
10614 struct task_struct *c;
10615 rcu_read_lock();
10616 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
10617 sched_move_task(c);
10619 rcu_read_unlock();
10623 #ifdef CONFIG_FAIR_GROUP_SCHED
10624 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
10625 u64 shareval)
10627 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
10630 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
10632 struct task_group *tg = cgroup_tg(cgrp);
10634 return (u64) tg->shares;
10636 #endif /* CONFIG_FAIR_GROUP_SCHED */
10638 #ifdef CONFIG_RT_GROUP_SCHED
10639 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
10640 s64 val)
10642 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
10645 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
10647 return sched_group_rt_runtime(cgroup_tg(cgrp));
10650 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
10651 u64 rt_period_us)
10653 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
10656 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
10658 return sched_group_rt_period(cgroup_tg(cgrp));
10660 #endif /* CONFIG_RT_GROUP_SCHED */
10662 static struct cftype cpu_files[] = {
10663 #ifdef CONFIG_FAIR_GROUP_SCHED
10665 .name = "shares",
10666 .read_u64 = cpu_shares_read_u64,
10667 .write_u64 = cpu_shares_write_u64,
10669 #endif
10670 #ifdef CONFIG_RT_GROUP_SCHED
10672 .name = "rt_runtime_us",
10673 .read_s64 = cpu_rt_runtime_read,
10674 .write_s64 = cpu_rt_runtime_write,
10677 .name = "rt_period_us",
10678 .read_u64 = cpu_rt_period_read_uint,
10679 .write_u64 = cpu_rt_period_write_uint,
10681 #endif
10684 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
10686 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
10689 struct cgroup_subsys cpu_cgroup_subsys = {
10690 .name = "cpu",
10691 .create = cpu_cgroup_create,
10692 .destroy = cpu_cgroup_destroy,
10693 .can_attach = cpu_cgroup_can_attach,
10694 .attach = cpu_cgroup_attach,
10695 .populate = cpu_cgroup_populate,
10696 .subsys_id = cpu_cgroup_subsys_id,
10697 .early_init = 1,
10700 #endif /* CONFIG_CGROUP_SCHED */
10702 #ifdef CONFIG_CGROUP_CPUACCT
10705 * CPU accounting code for task groups.
10707 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
10708 * (balbir@in.ibm.com).
10711 /* track cpu usage of a group of tasks and its child groups */
10712 struct cpuacct {
10713 struct cgroup_subsys_state css;
10714 /* cpuusage holds pointer to a u64-type object on every cpu */
10715 u64 *cpuusage;
10716 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
10717 struct cpuacct *parent;
10720 struct cgroup_subsys cpuacct_subsys;
10722 /* return cpu accounting group corresponding to this container */
10723 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
10725 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
10726 struct cpuacct, css);
10729 /* return cpu accounting group to which this task belongs */
10730 static inline struct cpuacct *task_ca(struct task_struct *tsk)
10732 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
10733 struct cpuacct, css);
10736 /* create a new cpu accounting group */
10737 static struct cgroup_subsys_state *cpuacct_create(
10738 struct cgroup_subsys *ss, struct cgroup *cgrp)
10740 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
10741 int i;
10743 if (!ca)
10744 goto out;
10746 ca->cpuusage = alloc_percpu(u64);
10747 if (!ca->cpuusage)
10748 goto out_free_ca;
10750 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
10751 if (percpu_counter_init(&ca->cpustat[i], 0))
10752 goto out_free_counters;
10754 if (cgrp->parent)
10755 ca->parent = cgroup_ca(cgrp->parent);
10757 return &ca->css;
10759 out_free_counters:
10760 while (--i >= 0)
10761 percpu_counter_destroy(&ca->cpustat[i]);
10762 free_percpu(ca->cpuusage);
10763 out_free_ca:
10764 kfree(ca);
10765 out:
10766 return ERR_PTR(-ENOMEM);
10769 /* destroy an existing cpu accounting group */
10770 static void
10771 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
10773 struct cpuacct *ca = cgroup_ca(cgrp);
10774 int i;
10776 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
10777 percpu_counter_destroy(&ca->cpustat[i]);
10778 free_percpu(ca->cpuusage);
10779 kfree(ca);
10782 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
10784 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10785 u64 data;
10787 #ifndef CONFIG_64BIT
10789 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
10791 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
10792 data = *cpuusage;
10793 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
10794 #else
10795 data = *cpuusage;
10796 #endif
10798 return data;
10801 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
10803 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10805 #ifndef CONFIG_64BIT
10807 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
10809 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
10810 *cpuusage = val;
10811 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
10812 #else
10813 *cpuusage = val;
10814 #endif
10817 /* return total cpu usage (in nanoseconds) of a group */
10818 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
10820 struct cpuacct *ca = cgroup_ca(cgrp);
10821 u64 totalcpuusage = 0;
10822 int i;
10824 for_each_present_cpu(i)
10825 totalcpuusage += cpuacct_cpuusage_read(ca, i);
10827 return totalcpuusage;
10830 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
10831 u64 reset)
10833 struct cpuacct *ca = cgroup_ca(cgrp);
10834 int err = 0;
10835 int i;
10837 if (reset) {
10838 err = -EINVAL;
10839 goto out;
10842 for_each_present_cpu(i)
10843 cpuacct_cpuusage_write(ca, i, 0);
10845 out:
10846 return err;
10849 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
10850 struct seq_file *m)
10852 struct cpuacct *ca = cgroup_ca(cgroup);
10853 u64 percpu;
10854 int i;
10856 for_each_present_cpu(i) {
10857 percpu = cpuacct_cpuusage_read(ca, i);
10858 seq_printf(m, "%llu ", (unsigned long long) percpu);
10860 seq_printf(m, "\n");
10861 return 0;
10864 static const char *cpuacct_stat_desc[] = {
10865 [CPUACCT_STAT_USER] = "user",
10866 [CPUACCT_STAT_SYSTEM] = "system",
10869 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
10870 struct cgroup_map_cb *cb)
10872 struct cpuacct *ca = cgroup_ca(cgrp);
10873 int i;
10875 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
10876 s64 val = percpu_counter_read(&ca->cpustat[i]);
10877 val = cputime64_to_clock_t(val);
10878 cb->fill(cb, cpuacct_stat_desc[i], val);
10880 return 0;
10883 static struct cftype files[] = {
10885 .name = "usage",
10886 .read_u64 = cpuusage_read,
10887 .write_u64 = cpuusage_write,
10890 .name = "usage_percpu",
10891 .read_seq_string = cpuacct_percpu_seq_read,
10894 .name = "stat",
10895 .read_map = cpuacct_stats_show,
10899 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
10901 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
10905 * charge this task's execution time to its accounting group.
10907 * called with rq->lock held.
10909 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
10911 struct cpuacct *ca;
10912 int cpu;
10914 if (unlikely(!cpuacct_subsys.active))
10915 return;
10917 cpu = task_cpu(tsk);
10919 rcu_read_lock();
10921 ca = task_ca(tsk);
10923 for (; ca; ca = ca->parent) {
10924 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
10925 *cpuusage += cputime;
10928 rcu_read_unlock();
10932 * Charge the system/user time to the task's accounting group.
10934 static void cpuacct_update_stats(struct task_struct *tsk,
10935 enum cpuacct_stat_index idx, cputime_t val)
10937 struct cpuacct *ca;
10939 if (unlikely(!cpuacct_subsys.active))
10940 return;
10942 rcu_read_lock();
10943 ca = task_ca(tsk);
10945 do {
10946 percpu_counter_add(&ca->cpustat[idx], val);
10947 ca = ca->parent;
10948 } while (ca);
10949 rcu_read_unlock();
10952 struct cgroup_subsys cpuacct_subsys = {
10953 .name = "cpuacct",
10954 .create = cpuacct_create,
10955 .destroy = cpuacct_destroy,
10956 .populate = cpuacct_populate,
10957 .subsys_id = cpuacct_subsys_id,
10959 #endif /* CONFIG_CGROUP_CPUACCT */
10961 #ifndef CONFIG_SMP
10963 int rcu_expedited_torture_stats(char *page)
10965 return 0;
10967 EXPORT_SYMBOL_GPL(rcu_expedited_torture_stats);
10969 void synchronize_sched_expedited(void)
10972 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
10974 #else /* #ifndef CONFIG_SMP */
10976 static DEFINE_PER_CPU(struct migration_req, rcu_migration_req);
10977 static DEFINE_MUTEX(rcu_sched_expedited_mutex);
10979 #define RCU_EXPEDITED_STATE_POST -2
10980 #define RCU_EXPEDITED_STATE_IDLE -1
10982 static int rcu_expedited_state = RCU_EXPEDITED_STATE_IDLE;
10984 int rcu_expedited_torture_stats(char *page)
10986 int cnt = 0;
10987 int cpu;
10989 cnt += sprintf(&page[cnt], "state: %d /", rcu_expedited_state);
10990 for_each_online_cpu(cpu) {
10991 cnt += sprintf(&page[cnt], " %d:%d",
10992 cpu, per_cpu(rcu_migration_req, cpu).dest_cpu);
10994 cnt += sprintf(&page[cnt], "\n");
10995 return cnt;
10997 EXPORT_SYMBOL_GPL(rcu_expedited_torture_stats);
10999 static long synchronize_sched_expedited_count;
11002 * Wait for an rcu-sched grace period to elapse, but use "big hammer"
11003 * approach to force grace period to end quickly. This consumes
11004 * significant time on all CPUs, and is thus not recommended for
11005 * any sort of common-case code.
11007 * Note that it is illegal to call this function while holding any
11008 * lock that is acquired by a CPU-hotplug notifier. Failing to
11009 * observe this restriction will result in deadlock.
11011 void synchronize_sched_expedited(void)
11013 int cpu;
11014 unsigned long flags;
11015 bool need_full_sync = 0;
11016 struct rq *rq;
11017 struct migration_req *req;
11018 long snap;
11019 int trycount = 0;
11021 smp_mb(); /* ensure prior mod happens before capturing snap. */
11022 snap = ACCESS_ONCE(synchronize_sched_expedited_count) + 1;
11023 get_online_cpus();
11024 while (!mutex_trylock(&rcu_sched_expedited_mutex)) {
11025 put_online_cpus();
11026 if (trycount++ < 10)
11027 udelay(trycount * num_online_cpus());
11028 else {
11029 synchronize_sched();
11030 return;
11032 if (ACCESS_ONCE(synchronize_sched_expedited_count) - snap > 0) {
11033 smp_mb(); /* ensure test happens before caller kfree */
11034 return;
11036 get_online_cpus();
11038 rcu_expedited_state = RCU_EXPEDITED_STATE_POST;
11039 for_each_online_cpu(cpu) {
11040 rq = cpu_rq(cpu);
11041 req = &per_cpu(rcu_migration_req, cpu);
11042 init_completion(&req->done);
11043 req->task = NULL;
11044 req->dest_cpu = RCU_MIGRATION_NEED_QS;
11045 raw_spin_lock_irqsave(&rq->lock, flags);
11046 list_add(&req->list, &rq->migration_queue);
11047 raw_spin_unlock_irqrestore(&rq->lock, flags);
11048 wake_up_process(rq->migration_thread);
11050 for_each_online_cpu(cpu) {
11051 rcu_expedited_state = cpu;
11052 req = &per_cpu(rcu_migration_req, cpu);
11053 rq = cpu_rq(cpu);
11054 wait_for_completion(&req->done);
11055 raw_spin_lock_irqsave(&rq->lock, flags);
11056 if (unlikely(req->dest_cpu == RCU_MIGRATION_MUST_SYNC))
11057 need_full_sync = 1;
11058 req->dest_cpu = RCU_MIGRATION_IDLE;
11059 raw_spin_unlock_irqrestore(&rq->lock, flags);
11061 rcu_expedited_state = RCU_EXPEDITED_STATE_IDLE;
11062 synchronize_sched_expedited_count++;
11063 mutex_unlock(&rcu_sched_expedited_mutex);
11064 put_online_cpus();
11065 if (need_full_sync)
11066 synchronize_sched();
11068 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
11070 #endif /* #else #ifndef CONFIG_SMP */