tracepoints: add DECLARE_TRACE() and DEFINE_TRACE()
[linux-2.6/kvm.git] / kernel / sched.c
blob327f91c63c992c6141c0971c9b1b1f5fd7240134
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/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/kthread.h>
58 #include <linux/proc_fs.h>
59 #include <linux/seq_file.h>
60 #include <linux/sysctl.h>
61 #include <linux/syscalls.h>
62 #include <linux/times.h>
63 #include <linux/tsacct_kern.h>
64 #include <linux/kprobes.h>
65 #include <linux/delayacct.h>
66 #include <linux/reciprocal_div.h>
67 #include <linux/unistd.h>
68 #include <linux/pagemap.h>
69 #include <linux/hrtimer.h>
70 #include <linux/tick.h>
71 #include <linux/bootmem.h>
72 #include <linux/debugfs.h>
73 #include <linux/ctype.h>
74 #include <linux/ftrace.h>
75 #include <trace/sched.h>
77 #include <asm/tlb.h>
78 #include <asm/irq_regs.h>
80 #include "sched_cpupri.h"
83 * Convert user-nice values [ -20 ... 0 ... 19 ]
84 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
85 * and back.
87 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
88 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
89 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
92 * 'User priority' is the nice value converted to something we
93 * can work with better when scaling various scheduler parameters,
94 * it's a [ 0 ... 39 ] range.
96 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
97 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
98 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
101 * Helpers for converting nanosecond timing to jiffy resolution
103 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
105 #define NICE_0_LOAD SCHED_LOAD_SCALE
106 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
109 * These are the 'tuning knobs' of the scheduler:
111 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
112 * Timeslices get refilled after they expire.
114 #define DEF_TIMESLICE (100 * HZ / 1000)
117 * single value that denotes runtime == period, ie unlimited time.
119 #define RUNTIME_INF ((u64)~0ULL)
121 DEFINE_TRACE(sched_wait_task);
122 DEFINE_TRACE(sched_wakeup);
123 DEFINE_TRACE(sched_wakeup_new);
124 DEFINE_TRACE(sched_switch);
125 DEFINE_TRACE(sched_migrate_task);
127 #ifdef CONFIG_SMP
129 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
130 * Since cpu_power is a 'constant', we can use a reciprocal divide.
132 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
134 return reciprocal_divide(load, sg->reciprocal_cpu_power);
138 * Each time a sched group cpu_power is changed,
139 * we must compute its reciprocal value
141 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
143 sg->__cpu_power += val;
144 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
146 #endif
148 static inline int rt_policy(int policy)
150 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
151 return 1;
152 return 0;
155 static inline int task_has_rt_policy(struct task_struct *p)
157 return rt_policy(p->policy);
161 * This is the priority-queue data structure of the RT scheduling class:
163 struct rt_prio_array {
164 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
165 struct list_head queue[MAX_RT_PRIO];
168 struct rt_bandwidth {
169 /* nests inside the rq lock: */
170 spinlock_t rt_runtime_lock;
171 ktime_t rt_period;
172 u64 rt_runtime;
173 struct hrtimer rt_period_timer;
176 static struct rt_bandwidth def_rt_bandwidth;
178 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
180 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
182 struct rt_bandwidth *rt_b =
183 container_of(timer, struct rt_bandwidth, rt_period_timer);
184 ktime_t now;
185 int overrun;
186 int idle = 0;
188 for (;;) {
189 now = hrtimer_cb_get_time(timer);
190 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
192 if (!overrun)
193 break;
195 idle = do_sched_rt_period_timer(rt_b, overrun);
198 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
201 static
202 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
204 rt_b->rt_period = ns_to_ktime(period);
205 rt_b->rt_runtime = runtime;
207 spin_lock_init(&rt_b->rt_runtime_lock);
209 hrtimer_init(&rt_b->rt_period_timer,
210 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
211 rt_b->rt_period_timer.function = sched_rt_period_timer;
212 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_UNLOCKED;
215 static inline int rt_bandwidth_enabled(void)
217 return sysctl_sched_rt_runtime >= 0;
220 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
222 ktime_t now;
224 if (rt_bandwidth_enabled() && rt_b->rt_runtime == RUNTIME_INF)
225 return;
227 if (hrtimer_active(&rt_b->rt_period_timer))
228 return;
230 spin_lock(&rt_b->rt_runtime_lock);
231 for (;;) {
232 if (hrtimer_active(&rt_b->rt_period_timer))
233 break;
235 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
236 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
237 hrtimer_start_expires(&rt_b->rt_period_timer,
238 HRTIMER_MODE_ABS);
240 spin_unlock(&rt_b->rt_runtime_lock);
243 #ifdef CONFIG_RT_GROUP_SCHED
244 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
246 hrtimer_cancel(&rt_b->rt_period_timer);
248 #endif
251 * sched_domains_mutex serializes calls to arch_init_sched_domains,
252 * detach_destroy_domains and partition_sched_domains.
254 static DEFINE_MUTEX(sched_domains_mutex);
256 #ifdef CONFIG_GROUP_SCHED
258 #include <linux/cgroup.h>
260 struct cfs_rq;
262 static LIST_HEAD(task_groups);
264 /* task group related information */
265 struct task_group {
266 #ifdef CONFIG_CGROUP_SCHED
267 struct cgroup_subsys_state css;
268 #endif
270 #ifdef CONFIG_FAIR_GROUP_SCHED
271 /* schedulable entities of this group on each cpu */
272 struct sched_entity **se;
273 /* runqueue "owned" by this group on each cpu */
274 struct cfs_rq **cfs_rq;
275 unsigned long shares;
276 #endif
278 #ifdef CONFIG_RT_GROUP_SCHED
279 struct sched_rt_entity **rt_se;
280 struct rt_rq **rt_rq;
282 struct rt_bandwidth rt_bandwidth;
283 #endif
285 struct rcu_head rcu;
286 struct list_head list;
288 struct task_group *parent;
289 struct list_head siblings;
290 struct list_head children;
293 #ifdef CONFIG_USER_SCHED
296 * Root task group.
297 * Every UID task group (including init_task_group aka UID-0) will
298 * be a child to this group.
300 struct task_group root_task_group;
302 #ifdef CONFIG_FAIR_GROUP_SCHED
303 /* Default task group's sched entity on each cpu */
304 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
305 /* Default task group's cfs_rq on each cpu */
306 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
307 #endif /* CONFIG_FAIR_GROUP_SCHED */
309 #ifdef CONFIG_RT_GROUP_SCHED
310 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
311 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
312 #endif /* CONFIG_RT_GROUP_SCHED */
313 #else /* !CONFIG_USER_SCHED */
314 #define root_task_group init_task_group
315 #endif /* CONFIG_USER_SCHED */
317 /* task_group_lock serializes add/remove of task groups and also changes to
318 * a task group's cpu shares.
320 static DEFINE_SPINLOCK(task_group_lock);
322 #ifdef CONFIG_FAIR_GROUP_SCHED
323 #ifdef CONFIG_USER_SCHED
324 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
325 #else /* !CONFIG_USER_SCHED */
326 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
327 #endif /* CONFIG_USER_SCHED */
330 * A weight of 0 or 1 can cause arithmetics problems.
331 * A weight of a cfs_rq is the sum of weights of which entities
332 * are queued on this cfs_rq, so a weight of a entity should not be
333 * too large, so as the shares value of a task group.
334 * (The default weight is 1024 - so there's no practical
335 * limitation from this.)
337 #define MIN_SHARES 2
338 #define MAX_SHARES (1UL << 18)
340 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
341 #endif
343 /* Default task group.
344 * Every task in system belong to this group at bootup.
346 struct task_group init_task_group;
348 /* return group to which a task belongs */
349 static inline struct task_group *task_group(struct task_struct *p)
351 struct task_group *tg;
353 #ifdef CONFIG_USER_SCHED
354 tg = p->user->tg;
355 #elif defined(CONFIG_CGROUP_SCHED)
356 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
357 struct task_group, css);
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 int highest_prio; /* highest queued rt task prio */
457 #endif
458 #ifdef CONFIG_SMP
459 unsigned long rt_nr_migratory;
460 int overloaded;
461 #endif
462 int rt_throttled;
463 u64 rt_time;
464 u64 rt_runtime;
465 /* Nests inside the rq lock: */
466 spinlock_t rt_runtime_lock;
468 #ifdef CONFIG_RT_GROUP_SCHED
469 unsigned long rt_nr_boosted;
471 struct rq *rq;
472 struct list_head leaf_rt_rq_list;
473 struct task_group *tg;
474 struct sched_rt_entity *rt_se;
475 #endif
478 #ifdef CONFIG_SMP
481 * We add the notion of a root-domain which will be used to define per-domain
482 * variables. Each exclusive cpuset essentially defines an island domain by
483 * fully partitioning the member cpus from any other cpuset. Whenever a new
484 * exclusive cpuset is created, we also create and attach a new root-domain
485 * object.
488 struct root_domain {
489 atomic_t refcount;
490 cpumask_t span;
491 cpumask_t online;
494 * The "RT overload" flag: it gets set if a CPU has more than
495 * one runnable RT task.
497 cpumask_t rto_mask;
498 atomic_t rto_count;
499 #ifdef CONFIG_SMP
500 struct cpupri cpupri;
501 #endif
505 * By default the system creates a single root-domain with all cpus as
506 * members (mimicking the global state we have today).
508 static struct root_domain def_root_domain;
510 #endif
513 * This is the main, per-CPU runqueue data structure.
515 * Locking rule: those places that want to lock multiple runqueues
516 * (such as the load balancing or the thread migration code), lock
517 * acquire operations must be ordered by ascending &runqueue.
519 struct rq {
520 /* runqueue lock: */
521 spinlock_t lock;
524 * nr_running and cpu_load should be in the same cacheline because
525 * remote CPUs use both these fields when doing load calculation.
527 unsigned long nr_running;
528 #define CPU_LOAD_IDX_MAX 5
529 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
530 unsigned char idle_at_tick;
531 #ifdef CONFIG_NO_HZ
532 unsigned long last_tick_seen;
533 unsigned char in_nohz_recently;
534 #endif
535 /* capture load from *all* tasks on this cpu: */
536 struct load_weight load;
537 unsigned long nr_load_updates;
538 u64 nr_switches;
540 struct cfs_rq cfs;
541 struct rt_rq rt;
543 #ifdef CONFIG_FAIR_GROUP_SCHED
544 /* list of leaf cfs_rq on this cpu: */
545 struct list_head leaf_cfs_rq_list;
546 #endif
547 #ifdef CONFIG_RT_GROUP_SCHED
548 struct list_head leaf_rt_rq_list;
549 #endif
552 * This is part of a global counter where only the total sum
553 * over all CPUs matters. A task can increase this counter on
554 * one CPU and if it got migrated afterwards it may decrease
555 * it on another CPU. Always updated under the runqueue lock:
557 unsigned long nr_uninterruptible;
559 struct task_struct *curr, *idle;
560 unsigned long next_balance;
561 struct mm_struct *prev_mm;
563 u64 clock;
565 atomic_t nr_iowait;
567 #ifdef CONFIG_SMP
568 struct root_domain *rd;
569 struct sched_domain *sd;
571 /* For active balancing */
572 int active_balance;
573 int push_cpu;
574 /* cpu of this runqueue: */
575 int cpu;
576 int online;
578 unsigned long avg_load_per_task;
580 struct task_struct *migration_thread;
581 struct list_head migration_queue;
582 #endif
584 #ifdef CONFIG_SCHED_HRTICK
585 #ifdef CONFIG_SMP
586 int hrtick_csd_pending;
587 struct call_single_data hrtick_csd;
588 #endif
589 struct hrtimer hrtick_timer;
590 #endif
592 #ifdef CONFIG_SCHEDSTATS
593 /* latency stats */
594 struct sched_info rq_sched_info;
596 /* sys_sched_yield() stats */
597 unsigned int yld_exp_empty;
598 unsigned int yld_act_empty;
599 unsigned int yld_both_empty;
600 unsigned int yld_count;
602 /* schedule() stats */
603 unsigned int sched_switch;
604 unsigned int sched_count;
605 unsigned int sched_goidle;
607 /* try_to_wake_up() stats */
608 unsigned int ttwu_count;
609 unsigned int ttwu_local;
611 /* BKL stats */
612 unsigned int bkl_count;
613 #endif
616 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
618 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p, int sync)
620 rq->curr->sched_class->check_preempt_curr(rq, p, sync);
623 static inline int cpu_of(struct rq *rq)
625 #ifdef CONFIG_SMP
626 return rq->cpu;
627 #else
628 return 0;
629 #endif
633 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
634 * See detach_destroy_domains: synchronize_sched for details.
636 * The domain tree of any CPU may only be accessed from within
637 * preempt-disabled sections.
639 #define for_each_domain(cpu, __sd) \
640 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
642 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
643 #define this_rq() (&__get_cpu_var(runqueues))
644 #define task_rq(p) cpu_rq(task_cpu(p))
645 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
647 static inline void update_rq_clock(struct rq *rq)
649 rq->clock = sched_clock_cpu(cpu_of(rq));
653 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
655 #ifdef CONFIG_SCHED_DEBUG
656 # define const_debug __read_mostly
657 #else
658 # define const_debug static const
659 #endif
662 * runqueue_is_locked
664 * Returns true if the current cpu runqueue is locked.
665 * This interface allows printk to be called with the runqueue lock
666 * held and know whether or not it is OK to wake up the klogd.
668 int runqueue_is_locked(void)
670 int cpu = get_cpu();
671 struct rq *rq = cpu_rq(cpu);
672 int ret;
674 ret = spin_is_locked(&rq->lock);
675 put_cpu();
676 return ret;
680 * Debugging: various feature bits
683 #define SCHED_FEAT(name, enabled) \
684 __SCHED_FEAT_##name ,
686 enum {
687 #include "sched_features.h"
690 #undef SCHED_FEAT
692 #define SCHED_FEAT(name, enabled) \
693 (1UL << __SCHED_FEAT_##name) * enabled |
695 const_debug unsigned int sysctl_sched_features =
696 #include "sched_features.h"
699 #undef SCHED_FEAT
701 #ifdef CONFIG_SCHED_DEBUG
702 #define SCHED_FEAT(name, enabled) \
703 #name ,
705 static __read_mostly char *sched_feat_names[] = {
706 #include "sched_features.h"
707 NULL
710 #undef SCHED_FEAT
712 static int sched_feat_open(struct inode *inode, struct file *filp)
714 filp->private_data = inode->i_private;
715 return 0;
718 static ssize_t
719 sched_feat_read(struct file *filp, char __user *ubuf,
720 size_t cnt, loff_t *ppos)
722 char *buf;
723 int r = 0;
724 int len = 0;
725 int i;
727 for (i = 0; sched_feat_names[i]; i++) {
728 len += strlen(sched_feat_names[i]);
729 len += 4;
732 buf = kmalloc(len + 2, GFP_KERNEL);
733 if (!buf)
734 return -ENOMEM;
736 for (i = 0; sched_feat_names[i]; i++) {
737 if (sysctl_sched_features & (1UL << i))
738 r += sprintf(buf + r, "%s ", sched_feat_names[i]);
739 else
740 r += sprintf(buf + r, "NO_%s ", sched_feat_names[i]);
743 r += sprintf(buf + r, "\n");
744 WARN_ON(r >= len + 2);
746 r = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
748 kfree(buf);
750 return r;
753 static ssize_t
754 sched_feat_write(struct file *filp, const char __user *ubuf,
755 size_t cnt, loff_t *ppos)
757 char buf[64];
758 char *cmp = buf;
759 int neg = 0;
760 int i;
762 if (cnt > 63)
763 cnt = 63;
765 if (copy_from_user(&buf, ubuf, cnt))
766 return -EFAULT;
768 buf[cnt] = 0;
770 if (strncmp(buf, "NO_", 3) == 0) {
771 neg = 1;
772 cmp += 3;
775 for (i = 0; sched_feat_names[i]; i++) {
776 int len = strlen(sched_feat_names[i]);
778 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
779 if (neg)
780 sysctl_sched_features &= ~(1UL << i);
781 else
782 sysctl_sched_features |= (1UL << i);
783 break;
787 if (!sched_feat_names[i])
788 return -EINVAL;
790 filp->f_pos += cnt;
792 return cnt;
795 static struct file_operations sched_feat_fops = {
796 .open = sched_feat_open,
797 .read = sched_feat_read,
798 .write = sched_feat_write,
801 static __init int sched_init_debug(void)
803 debugfs_create_file("sched_features", 0644, NULL, NULL,
804 &sched_feat_fops);
806 return 0;
808 late_initcall(sched_init_debug);
810 #endif
812 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
815 * Number of tasks to iterate in a single balance run.
816 * Limited because this is done with IRQs disabled.
818 const_debug unsigned int sysctl_sched_nr_migrate = 32;
821 * ratelimit for updating the group shares.
822 * default: 0.25ms
824 unsigned int sysctl_sched_shares_ratelimit = 250000;
827 * Inject some fuzzyness into changing the per-cpu group shares
828 * this avoids remote rq-locks at the expense of fairness.
829 * default: 4
831 unsigned int sysctl_sched_shares_thresh = 4;
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 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 spin_unlock_irq(&rq->lock);
920 #else
921 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 spin_lock(&rq->lock);
952 if (likely(rq == task_rq(p)))
953 return rq;
954 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 spin_lock(&rq->lock);
972 if (likely(rq == task_rq(p)))
973 return rq;
974 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 spin_unlock_wait(&rq->lock);
986 static void __task_rq_unlock(struct rq *rq)
987 __releases(rq->lock)
989 spin_unlock(&rq->lock);
992 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
993 __releases(rq->lock)
995 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 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 spin_lock(&rq->lock);
1056 update_rq_clock(rq);
1057 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1058 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 spin_lock(&rq->lock);
1072 hrtimer_restart(&rq->hrtick_timer);
1073 rq->hrtick_csd_pending = 0;
1074 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);
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(&rq->hrtick_timer, ns_to_ktime(delay), HRTIMER_MODE_REL);
1131 static inline void init_hrtick(void)
1134 #endif /* CONFIG_SMP */
1136 static void init_rq_hrtick(struct rq *rq)
1138 #ifdef CONFIG_SMP
1139 rq->hrtick_csd_pending = 0;
1141 rq->hrtick_csd.flags = 0;
1142 rq->hrtick_csd.func = __hrtick_start;
1143 rq->hrtick_csd.info = rq;
1144 #endif
1146 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1147 rq->hrtick_timer.function = hrtick;
1148 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_PERCPU;
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_spin_locked(&task_rq(p)->lock);
1183 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
1184 return;
1186 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
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 (!spin_trylock_irqsave(&rq->lock, flags))
1204 return;
1205 resched_task(cpu_curr(cpu));
1206 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_thread_flag(rq->idle, TIF_NEED_RESCHED);
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 #else /* !CONFIG_SMP */
1252 static void resched_task(struct task_struct *p)
1254 assert_spin_locked(&task_rq(p)->lock);
1255 set_tsk_need_resched(p);
1257 #endif /* CONFIG_SMP */
1259 #if BITS_PER_LONG == 32
1260 # define WMULT_CONST (~0UL)
1261 #else
1262 # define WMULT_CONST (1UL << 32)
1263 #endif
1265 #define WMULT_SHIFT 32
1268 * Shift right and round:
1270 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1273 * delta *= weight / lw
1275 static unsigned long
1276 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1277 struct load_weight *lw)
1279 u64 tmp;
1281 if (!lw->inv_weight) {
1282 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1283 lw->inv_weight = 1;
1284 else
1285 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1286 / (lw->weight+1);
1289 tmp = (u64)delta_exec * weight;
1291 * Check whether we'd overflow the 64-bit multiplication:
1293 if (unlikely(tmp > WMULT_CONST))
1294 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1295 WMULT_SHIFT/2);
1296 else
1297 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1299 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1302 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1304 lw->weight += inc;
1305 lw->inv_weight = 0;
1308 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1310 lw->weight -= dec;
1311 lw->inv_weight = 0;
1315 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1316 * of tasks with abnormal "nice" values across CPUs the contribution that
1317 * each task makes to its run queue's load is weighted according to its
1318 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1319 * scaled version of the new time slice allocation that they receive on time
1320 * slice expiry etc.
1323 #define WEIGHT_IDLEPRIO 2
1324 #define WMULT_IDLEPRIO (1 << 31)
1327 * Nice levels are multiplicative, with a gentle 10% change for every
1328 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1329 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1330 * that remained on nice 0.
1332 * The "10% effect" is relative and cumulative: from _any_ nice level,
1333 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1334 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1335 * If a task goes up by ~10% and another task goes down by ~10% then
1336 * the relative distance between them is ~25%.)
1338 static const int prio_to_weight[40] = {
1339 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1340 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1341 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1342 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1343 /* 0 */ 1024, 820, 655, 526, 423,
1344 /* 5 */ 335, 272, 215, 172, 137,
1345 /* 10 */ 110, 87, 70, 56, 45,
1346 /* 15 */ 36, 29, 23, 18, 15,
1350 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1352 * In cases where the weight does not change often, we can use the
1353 * precalculated inverse to speed up arithmetics by turning divisions
1354 * into multiplications:
1356 static const u32 prio_to_wmult[40] = {
1357 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1358 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1359 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1360 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1361 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1362 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1363 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1364 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1367 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1370 * runqueue iterator, to support SMP load-balancing between different
1371 * scheduling classes, without having to expose their internal data
1372 * structures to the load-balancing proper:
1374 struct rq_iterator {
1375 void *arg;
1376 struct task_struct *(*start)(void *);
1377 struct task_struct *(*next)(void *);
1380 #ifdef CONFIG_SMP
1381 static unsigned long
1382 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1383 unsigned long max_load_move, struct sched_domain *sd,
1384 enum cpu_idle_type idle, int *all_pinned,
1385 int *this_best_prio, struct rq_iterator *iterator);
1387 static int
1388 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1389 struct sched_domain *sd, enum cpu_idle_type idle,
1390 struct rq_iterator *iterator);
1391 #endif
1393 #ifdef CONFIG_CGROUP_CPUACCT
1394 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1395 #else
1396 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1397 #endif
1399 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1401 update_load_add(&rq->load, load);
1404 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1406 update_load_sub(&rq->load, load);
1409 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1410 typedef int (*tg_visitor)(struct task_group *, void *);
1413 * Iterate the full tree, calling @down when first entering a node and @up when
1414 * leaving it for the final time.
1416 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1418 struct task_group *parent, *child;
1419 int ret;
1421 rcu_read_lock();
1422 parent = &root_task_group;
1423 down:
1424 ret = (*down)(parent, data);
1425 if (ret)
1426 goto out_unlock;
1427 list_for_each_entry_rcu(child, &parent->children, siblings) {
1428 parent = child;
1429 goto down;
1432 continue;
1434 ret = (*up)(parent, data);
1435 if (ret)
1436 goto out_unlock;
1438 child = parent;
1439 parent = parent->parent;
1440 if (parent)
1441 goto up;
1442 out_unlock:
1443 rcu_read_unlock();
1445 return ret;
1448 static int tg_nop(struct task_group *tg, void *data)
1450 return 0;
1452 #endif
1454 #ifdef CONFIG_SMP
1455 static unsigned long source_load(int cpu, int type);
1456 static unsigned long target_load(int cpu, int type);
1457 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1459 static unsigned long cpu_avg_load_per_task(int cpu)
1461 struct rq *rq = cpu_rq(cpu);
1463 if (rq->nr_running)
1464 rq->avg_load_per_task = rq->load.weight / rq->nr_running;
1466 return rq->avg_load_per_task;
1469 #ifdef CONFIG_FAIR_GROUP_SCHED
1471 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1474 * Calculate and set the cpu's group shares.
1476 static void
1477 update_group_shares_cpu(struct task_group *tg, int cpu,
1478 unsigned long sd_shares, unsigned long sd_rq_weight)
1480 int boost = 0;
1481 unsigned long shares;
1482 unsigned long rq_weight;
1484 if (!tg->se[cpu])
1485 return;
1487 rq_weight = tg->cfs_rq[cpu]->load.weight;
1490 * If there are currently no tasks on the cpu pretend there is one of
1491 * average load so that when a new task gets to run here it will not
1492 * get delayed by group starvation.
1494 if (!rq_weight) {
1495 boost = 1;
1496 rq_weight = NICE_0_LOAD;
1499 if (unlikely(rq_weight > sd_rq_weight))
1500 rq_weight = sd_rq_weight;
1503 * \Sum shares * rq_weight
1504 * shares = -----------------------
1505 * \Sum rq_weight
1508 shares = (sd_shares * rq_weight) / (sd_rq_weight + 1);
1509 shares = clamp_t(unsigned long, shares, MIN_SHARES, MAX_SHARES);
1511 if (abs(shares - tg->se[cpu]->load.weight) >
1512 sysctl_sched_shares_thresh) {
1513 struct rq *rq = cpu_rq(cpu);
1514 unsigned long flags;
1516 spin_lock_irqsave(&rq->lock, flags);
1518 * record the actual number of shares, not the boosted amount.
1520 tg->cfs_rq[cpu]->shares = boost ? 0 : shares;
1521 tg->cfs_rq[cpu]->rq_weight = rq_weight;
1523 __set_se_shares(tg->se[cpu], shares);
1524 spin_unlock_irqrestore(&rq->lock, flags);
1529 * Re-compute the task group their per cpu shares over the given domain.
1530 * This needs to be done in a bottom-up fashion because the rq weight of a
1531 * parent group depends on the shares of its child groups.
1533 static int tg_shares_up(struct task_group *tg, void *data)
1535 unsigned long rq_weight = 0;
1536 unsigned long shares = 0;
1537 struct sched_domain *sd = data;
1538 int i;
1540 for_each_cpu_mask(i, sd->span) {
1541 rq_weight += tg->cfs_rq[i]->load.weight;
1542 shares += tg->cfs_rq[i]->shares;
1545 if ((!shares && rq_weight) || shares > tg->shares)
1546 shares = tg->shares;
1548 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1549 shares = tg->shares;
1551 if (!rq_weight)
1552 rq_weight = cpus_weight(sd->span) * NICE_0_LOAD;
1554 for_each_cpu_mask(i, sd->span)
1555 update_group_shares_cpu(tg, i, shares, rq_weight);
1557 return 0;
1561 * Compute the cpu's hierarchical load factor for each task group.
1562 * This needs to be done in a top-down fashion because the load of a child
1563 * group is a fraction of its parents load.
1565 static int tg_load_down(struct task_group *tg, void *data)
1567 unsigned long load;
1568 long cpu = (long)data;
1570 if (!tg->parent) {
1571 load = cpu_rq(cpu)->load.weight;
1572 } else {
1573 load = tg->parent->cfs_rq[cpu]->h_load;
1574 load *= tg->cfs_rq[cpu]->shares;
1575 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1578 tg->cfs_rq[cpu]->h_load = load;
1580 return 0;
1583 static void update_shares(struct sched_domain *sd)
1585 u64 now = cpu_clock(raw_smp_processor_id());
1586 s64 elapsed = now - sd->last_update;
1588 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1589 sd->last_update = now;
1590 walk_tg_tree(tg_nop, tg_shares_up, sd);
1594 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1596 spin_unlock(&rq->lock);
1597 update_shares(sd);
1598 spin_lock(&rq->lock);
1601 static void update_h_load(long cpu)
1603 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1606 #else
1608 static inline void update_shares(struct sched_domain *sd)
1612 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1616 #endif
1618 #endif
1620 #ifdef CONFIG_FAIR_GROUP_SCHED
1621 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1623 #ifdef CONFIG_SMP
1624 cfs_rq->shares = shares;
1625 #endif
1627 #endif
1629 #include "sched_stats.h"
1630 #include "sched_idletask.c"
1631 #include "sched_fair.c"
1632 #include "sched_rt.c"
1633 #ifdef CONFIG_SCHED_DEBUG
1634 # include "sched_debug.c"
1635 #endif
1637 #define sched_class_highest (&rt_sched_class)
1638 #define for_each_class(class) \
1639 for (class = sched_class_highest; class; class = class->next)
1641 static void inc_nr_running(struct rq *rq)
1643 rq->nr_running++;
1646 static void dec_nr_running(struct rq *rq)
1648 rq->nr_running--;
1651 static void set_load_weight(struct task_struct *p)
1653 if (task_has_rt_policy(p)) {
1654 p->se.load.weight = prio_to_weight[0] * 2;
1655 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1656 return;
1660 * SCHED_IDLE tasks get minimal weight:
1662 if (p->policy == SCHED_IDLE) {
1663 p->se.load.weight = WEIGHT_IDLEPRIO;
1664 p->se.load.inv_weight = WMULT_IDLEPRIO;
1665 return;
1668 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1669 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1672 static void update_avg(u64 *avg, u64 sample)
1674 s64 diff = sample - *avg;
1675 *avg += diff >> 3;
1678 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1680 sched_info_queued(p);
1681 p->sched_class->enqueue_task(rq, p, wakeup);
1682 p->se.on_rq = 1;
1685 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1687 if (sleep && p->se.last_wakeup) {
1688 update_avg(&p->se.avg_overlap,
1689 p->se.sum_exec_runtime - p->se.last_wakeup);
1690 p->se.last_wakeup = 0;
1693 sched_info_dequeued(p);
1694 p->sched_class->dequeue_task(rq, p, sleep);
1695 p->se.on_rq = 0;
1699 * __normal_prio - return the priority that is based on the static prio
1701 static inline int __normal_prio(struct task_struct *p)
1703 return p->static_prio;
1707 * Calculate the expected normal priority: i.e. priority
1708 * without taking RT-inheritance into account. Might be
1709 * boosted by interactivity modifiers. Changes upon fork,
1710 * setprio syscalls, and whenever the interactivity
1711 * estimator recalculates.
1713 static inline int normal_prio(struct task_struct *p)
1715 int prio;
1717 if (task_has_rt_policy(p))
1718 prio = MAX_RT_PRIO-1 - p->rt_priority;
1719 else
1720 prio = __normal_prio(p);
1721 return prio;
1725 * Calculate the current priority, i.e. the priority
1726 * taken into account by the scheduler. This value might
1727 * be boosted by RT tasks, or might be boosted by
1728 * interactivity modifiers. Will be RT if the task got
1729 * RT-boosted. If not then it returns p->normal_prio.
1731 static int effective_prio(struct task_struct *p)
1733 p->normal_prio = normal_prio(p);
1735 * If we are RT tasks or we were boosted to RT priority,
1736 * keep the priority unchanged. Otherwise, update priority
1737 * to the normal priority:
1739 if (!rt_prio(p->prio))
1740 return p->normal_prio;
1741 return p->prio;
1745 * activate_task - move a task to the runqueue.
1747 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1749 if (task_contributes_to_load(p))
1750 rq->nr_uninterruptible--;
1752 enqueue_task(rq, p, wakeup);
1753 inc_nr_running(rq);
1757 * deactivate_task - remove a task from the runqueue.
1759 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1761 if (task_contributes_to_load(p))
1762 rq->nr_uninterruptible++;
1764 dequeue_task(rq, p, sleep);
1765 dec_nr_running(rq);
1769 * task_curr - is this task currently executing on a CPU?
1770 * @p: the task in question.
1772 inline int task_curr(const struct task_struct *p)
1774 return cpu_curr(task_cpu(p)) == p;
1777 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1779 set_task_rq(p, cpu);
1780 #ifdef CONFIG_SMP
1782 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1783 * successfuly executed on another CPU. We must ensure that updates of
1784 * per-task data have been completed by this moment.
1786 smp_wmb();
1787 task_thread_info(p)->cpu = cpu;
1788 #endif
1791 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1792 const struct sched_class *prev_class,
1793 int oldprio, int running)
1795 if (prev_class != p->sched_class) {
1796 if (prev_class->switched_from)
1797 prev_class->switched_from(rq, p, running);
1798 p->sched_class->switched_to(rq, p, running);
1799 } else
1800 p->sched_class->prio_changed(rq, p, oldprio, running);
1803 #ifdef CONFIG_SMP
1805 /* Used instead of source_load when we know the type == 0 */
1806 static unsigned long weighted_cpuload(const int cpu)
1808 return cpu_rq(cpu)->load.weight;
1812 * Is this task likely cache-hot:
1814 static int
1815 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1817 s64 delta;
1820 * Buddy candidates are cache hot:
1822 if (sched_feat(CACHE_HOT_BUDDY) &&
1823 (&p->se == cfs_rq_of(&p->se)->next ||
1824 &p->se == cfs_rq_of(&p->se)->last))
1825 return 1;
1827 if (p->sched_class != &fair_sched_class)
1828 return 0;
1830 if (sysctl_sched_migration_cost == -1)
1831 return 1;
1832 if (sysctl_sched_migration_cost == 0)
1833 return 0;
1835 delta = now - p->se.exec_start;
1837 return delta < (s64)sysctl_sched_migration_cost;
1841 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1843 int old_cpu = task_cpu(p);
1844 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1845 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1846 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1847 u64 clock_offset;
1849 clock_offset = old_rq->clock - new_rq->clock;
1851 #ifdef CONFIG_SCHEDSTATS
1852 if (p->se.wait_start)
1853 p->se.wait_start -= clock_offset;
1854 if (p->se.sleep_start)
1855 p->se.sleep_start -= clock_offset;
1856 if (p->se.block_start)
1857 p->se.block_start -= clock_offset;
1858 if (old_cpu != new_cpu) {
1859 schedstat_inc(p, se.nr_migrations);
1860 if (task_hot(p, old_rq->clock, NULL))
1861 schedstat_inc(p, se.nr_forced2_migrations);
1863 #endif
1864 p->se.vruntime -= old_cfsrq->min_vruntime -
1865 new_cfsrq->min_vruntime;
1867 __set_task_cpu(p, new_cpu);
1870 struct migration_req {
1871 struct list_head list;
1873 struct task_struct *task;
1874 int dest_cpu;
1876 struct completion done;
1880 * The task's runqueue lock must be held.
1881 * Returns true if you have to wait for migration thread.
1883 static int
1884 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1886 struct rq *rq = task_rq(p);
1889 * If the task is not on a runqueue (and not running), then
1890 * it is sufficient to simply update the task's cpu field.
1892 if (!p->se.on_rq && !task_running(rq, p)) {
1893 set_task_cpu(p, dest_cpu);
1894 return 0;
1897 init_completion(&req->done);
1898 req->task = p;
1899 req->dest_cpu = dest_cpu;
1900 list_add(&req->list, &rq->migration_queue);
1902 return 1;
1906 * wait_task_inactive - wait for a thread to unschedule.
1908 * If @match_state is nonzero, it's the @p->state value just checked and
1909 * not expected to change. If it changes, i.e. @p might have woken up,
1910 * then return zero. When we succeed in waiting for @p to be off its CPU,
1911 * we return a positive number (its total switch count). If a second call
1912 * a short while later returns the same number, the caller can be sure that
1913 * @p has remained unscheduled the whole time.
1915 * The caller must ensure that the task *will* unschedule sometime soon,
1916 * else this function might spin for a *long* time. This function can't
1917 * be called with interrupts off, or it may introduce deadlock with
1918 * smp_call_function() if an IPI is sent by the same process we are
1919 * waiting to become inactive.
1921 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1923 unsigned long flags;
1924 int running, on_rq;
1925 unsigned long ncsw;
1926 struct rq *rq;
1928 for (;;) {
1930 * We do the initial early heuristics without holding
1931 * any task-queue locks at all. We'll only try to get
1932 * the runqueue lock when things look like they will
1933 * work out!
1935 rq = task_rq(p);
1938 * If the task is actively running on another CPU
1939 * still, just relax and busy-wait without holding
1940 * any locks.
1942 * NOTE! Since we don't hold any locks, it's not
1943 * even sure that "rq" stays as the right runqueue!
1944 * But we don't care, since "task_running()" will
1945 * return false if the runqueue has changed and p
1946 * is actually now running somewhere else!
1948 while (task_running(rq, p)) {
1949 if (match_state && unlikely(p->state != match_state))
1950 return 0;
1951 cpu_relax();
1955 * Ok, time to look more closely! We need the rq
1956 * lock now, to be *sure*. If we're wrong, we'll
1957 * just go back and repeat.
1959 rq = task_rq_lock(p, &flags);
1960 trace_sched_wait_task(rq, p);
1961 running = task_running(rq, p);
1962 on_rq = p->se.on_rq;
1963 ncsw = 0;
1964 if (!match_state || p->state == match_state)
1965 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1966 task_rq_unlock(rq, &flags);
1969 * If it changed from the expected state, bail out now.
1971 if (unlikely(!ncsw))
1972 break;
1975 * Was it really running after all now that we
1976 * checked with the proper locks actually held?
1978 * Oops. Go back and try again..
1980 if (unlikely(running)) {
1981 cpu_relax();
1982 continue;
1986 * It's not enough that it's not actively running,
1987 * it must be off the runqueue _entirely_, and not
1988 * preempted!
1990 * So if it wa still runnable (but just not actively
1991 * running right now), it's preempted, and we should
1992 * yield - it could be a while.
1994 if (unlikely(on_rq)) {
1995 schedule_timeout_uninterruptible(1);
1996 continue;
2000 * Ahh, all good. It wasn't running, and it wasn't
2001 * runnable, which means that it will never become
2002 * running in the future either. We're all done!
2004 break;
2007 return ncsw;
2010 /***
2011 * kick_process - kick a running thread to enter/exit the kernel
2012 * @p: the to-be-kicked thread
2014 * Cause a process which is running on another CPU to enter
2015 * kernel-mode, without any delay. (to get signals handled.)
2017 * NOTE: this function doesnt have to take the runqueue lock,
2018 * because all it wants to ensure is that the remote task enters
2019 * the kernel. If the IPI races and the task has been migrated
2020 * to another CPU then no harm is done and the purpose has been
2021 * achieved as well.
2023 void kick_process(struct task_struct *p)
2025 int cpu;
2027 preempt_disable();
2028 cpu = task_cpu(p);
2029 if ((cpu != smp_processor_id()) && task_curr(p))
2030 smp_send_reschedule(cpu);
2031 preempt_enable();
2035 * Return a low guess at the load of a migration-source cpu weighted
2036 * according to the scheduling class and "nice" value.
2038 * We want to under-estimate the load of migration sources, to
2039 * balance conservatively.
2041 static unsigned long source_load(int cpu, int type)
2043 struct rq *rq = cpu_rq(cpu);
2044 unsigned long total = weighted_cpuload(cpu);
2046 if (type == 0 || !sched_feat(LB_BIAS))
2047 return total;
2049 return min(rq->cpu_load[type-1], total);
2053 * Return a high guess at the load of a migration-target cpu weighted
2054 * according to the scheduling class and "nice" value.
2056 static unsigned long target_load(int cpu, int type)
2058 struct rq *rq = cpu_rq(cpu);
2059 unsigned long total = weighted_cpuload(cpu);
2061 if (type == 0 || !sched_feat(LB_BIAS))
2062 return total;
2064 return max(rq->cpu_load[type-1], total);
2068 * find_idlest_group finds and returns the least busy CPU group within the
2069 * domain.
2071 static struct sched_group *
2072 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2074 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2075 unsigned long min_load = ULONG_MAX, this_load = 0;
2076 int load_idx = sd->forkexec_idx;
2077 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2079 do {
2080 unsigned long load, avg_load;
2081 int local_group;
2082 int i;
2084 /* Skip over this group if it has no CPUs allowed */
2085 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2086 continue;
2088 local_group = cpu_isset(this_cpu, group->cpumask);
2090 /* Tally up the load of all CPUs in the group */
2091 avg_load = 0;
2093 for_each_cpu_mask_nr(i, group->cpumask) {
2094 /* Bias balancing toward cpus of our domain */
2095 if (local_group)
2096 load = source_load(i, load_idx);
2097 else
2098 load = target_load(i, load_idx);
2100 avg_load += load;
2103 /* Adjust by relative CPU power of the group */
2104 avg_load = sg_div_cpu_power(group,
2105 avg_load * SCHED_LOAD_SCALE);
2107 if (local_group) {
2108 this_load = avg_load;
2109 this = group;
2110 } else if (avg_load < min_load) {
2111 min_load = avg_load;
2112 idlest = group;
2114 } while (group = group->next, group != sd->groups);
2116 if (!idlest || 100*this_load < imbalance*min_load)
2117 return NULL;
2118 return idlest;
2122 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2124 static int
2125 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2126 cpumask_t *tmp)
2128 unsigned long load, min_load = ULONG_MAX;
2129 int idlest = -1;
2130 int i;
2132 /* Traverse only the allowed CPUs */
2133 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2135 for_each_cpu_mask_nr(i, *tmp) {
2136 load = weighted_cpuload(i);
2138 if (load < min_load || (load == min_load && i == this_cpu)) {
2139 min_load = load;
2140 idlest = i;
2144 return idlest;
2148 * sched_balance_self: balance the current task (running on cpu) in domains
2149 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2150 * SD_BALANCE_EXEC.
2152 * Balance, ie. select the least loaded group.
2154 * Returns the target CPU number, or the same CPU if no balancing is needed.
2156 * preempt must be disabled.
2158 static int sched_balance_self(int cpu, int flag)
2160 struct task_struct *t = current;
2161 struct sched_domain *tmp, *sd = NULL;
2163 for_each_domain(cpu, tmp) {
2165 * If power savings logic is enabled for a domain, stop there.
2167 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2168 break;
2169 if (tmp->flags & flag)
2170 sd = tmp;
2173 if (sd)
2174 update_shares(sd);
2176 while (sd) {
2177 cpumask_t span, tmpmask;
2178 struct sched_group *group;
2179 int new_cpu, weight;
2181 if (!(sd->flags & flag)) {
2182 sd = sd->child;
2183 continue;
2186 span = sd->span;
2187 group = find_idlest_group(sd, t, cpu);
2188 if (!group) {
2189 sd = sd->child;
2190 continue;
2193 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2194 if (new_cpu == -1 || new_cpu == cpu) {
2195 /* Now try balancing at a lower domain level of cpu */
2196 sd = sd->child;
2197 continue;
2200 /* Now try balancing at a lower domain level of new_cpu */
2201 cpu = new_cpu;
2202 sd = NULL;
2203 weight = cpus_weight(span);
2204 for_each_domain(cpu, tmp) {
2205 if (weight <= cpus_weight(tmp->span))
2206 break;
2207 if (tmp->flags & flag)
2208 sd = tmp;
2210 /* while loop will break here if sd == NULL */
2213 return cpu;
2216 #endif /* CONFIG_SMP */
2218 /***
2219 * try_to_wake_up - wake up a thread
2220 * @p: the to-be-woken-up thread
2221 * @state: the mask of task states that can be woken
2222 * @sync: do a synchronous wakeup?
2224 * Put it on the run-queue if it's not already there. The "current"
2225 * thread is always on the run-queue (except when the actual
2226 * re-schedule is in progress), and as such you're allowed to do
2227 * the simpler "current->state = TASK_RUNNING" to mark yourself
2228 * runnable without the overhead of this.
2230 * returns failure only if the task is already active.
2232 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2234 int cpu, orig_cpu, this_cpu, success = 0;
2235 unsigned long flags;
2236 long old_state;
2237 struct rq *rq;
2239 if (!sched_feat(SYNC_WAKEUPS))
2240 sync = 0;
2242 #ifdef CONFIG_SMP
2243 if (sched_feat(LB_WAKEUP_UPDATE)) {
2244 struct sched_domain *sd;
2246 this_cpu = raw_smp_processor_id();
2247 cpu = task_cpu(p);
2249 for_each_domain(this_cpu, sd) {
2250 if (cpu_isset(cpu, sd->span)) {
2251 update_shares(sd);
2252 break;
2256 #endif
2258 smp_wmb();
2259 rq = task_rq_lock(p, &flags);
2260 old_state = p->state;
2261 if (!(old_state & state))
2262 goto out;
2264 if (p->se.on_rq)
2265 goto out_running;
2267 cpu = task_cpu(p);
2268 orig_cpu = cpu;
2269 this_cpu = smp_processor_id();
2271 #ifdef CONFIG_SMP
2272 if (unlikely(task_running(rq, p)))
2273 goto out_activate;
2275 cpu = p->sched_class->select_task_rq(p, sync);
2276 if (cpu != orig_cpu) {
2277 set_task_cpu(p, cpu);
2278 task_rq_unlock(rq, &flags);
2279 /* might preempt at this point */
2280 rq = task_rq_lock(p, &flags);
2281 old_state = p->state;
2282 if (!(old_state & state))
2283 goto out;
2284 if (p->se.on_rq)
2285 goto out_running;
2287 this_cpu = smp_processor_id();
2288 cpu = task_cpu(p);
2291 #ifdef CONFIG_SCHEDSTATS
2292 schedstat_inc(rq, ttwu_count);
2293 if (cpu == this_cpu)
2294 schedstat_inc(rq, ttwu_local);
2295 else {
2296 struct sched_domain *sd;
2297 for_each_domain(this_cpu, sd) {
2298 if (cpu_isset(cpu, sd->span)) {
2299 schedstat_inc(sd, ttwu_wake_remote);
2300 break;
2304 #endif /* CONFIG_SCHEDSTATS */
2306 out_activate:
2307 #endif /* CONFIG_SMP */
2308 schedstat_inc(p, se.nr_wakeups);
2309 if (sync)
2310 schedstat_inc(p, se.nr_wakeups_sync);
2311 if (orig_cpu != cpu)
2312 schedstat_inc(p, se.nr_wakeups_migrate);
2313 if (cpu == this_cpu)
2314 schedstat_inc(p, se.nr_wakeups_local);
2315 else
2316 schedstat_inc(p, se.nr_wakeups_remote);
2317 update_rq_clock(rq);
2318 activate_task(rq, p, 1);
2319 success = 1;
2321 out_running:
2322 trace_sched_wakeup(rq, p);
2323 check_preempt_curr(rq, p, sync);
2325 p->state = TASK_RUNNING;
2326 #ifdef CONFIG_SMP
2327 if (p->sched_class->task_wake_up)
2328 p->sched_class->task_wake_up(rq, p);
2329 #endif
2330 out:
2331 current->se.last_wakeup = current->se.sum_exec_runtime;
2333 task_rq_unlock(rq, &flags);
2335 return success;
2338 int wake_up_process(struct task_struct *p)
2340 return try_to_wake_up(p, TASK_ALL, 0);
2342 EXPORT_SYMBOL(wake_up_process);
2344 int wake_up_state(struct task_struct *p, unsigned int state)
2346 return try_to_wake_up(p, state, 0);
2350 * Perform scheduler related setup for a newly forked process p.
2351 * p is forked by current.
2353 * __sched_fork() is basic setup used by init_idle() too:
2355 static void __sched_fork(struct task_struct *p)
2357 p->se.exec_start = 0;
2358 p->se.sum_exec_runtime = 0;
2359 p->se.prev_sum_exec_runtime = 0;
2360 p->se.last_wakeup = 0;
2361 p->se.avg_overlap = 0;
2363 #ifdef CONFIG_SCHEDSTATS
2364 p->se.wait_start = 0;
2365 p->se.sum_sleep_runtime = 0;
2366 p->se.sleep_start = 0;
2367 p->se.block_start = 0;
2368 p->se.sleep_max = 0;
2369 p->se.block_max = 0;
2370 p->se.exec_max = 0;
2371 p->se.slice_max = 0;
2372 p->se.wait_max = 0;
2373 #endif
2375 INIT_LIST_HEAD(&p->rt.run_list);
2376 p->se.on_rq = 0;
2377 INIT_LIST_HEAD(&p->se.group_node);
2379 #ifdef CONFIG_PREEMPT_NOTIFIERS
2380 INIT_HLIST_HEAD(&p->preempt_notifiers);
2381 #endif
2384 * We mark the process as running here, but have not actually
2385 * inserted it onto the runqueue yet. This guarantees that
2386 * nobody will actually run it, and a signal or other external
2387 * event cannot wake it up and insert it on the runqueue either.
2389 p->state = TASK_RUNNING;
2393 * fork()/clone()-time setup:
2395 void sched_fork(struct task_struct *p, int clone_flags)
2397 int cpu = get_cpu();
2399 __sched_fork(p);
2401 #ifdef CONFIG_SMP
2402 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2403 #endif
2404 set_task_cpu(p, cpu);
2407 * Make sure we do not leak PI boosting priority to the child:
2409 p->prio = current->normal_prio;
2410 if (!rt_prio(p->prio))
2411 p->sched_class = &fair_sched_class;
2413 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2414 if (likely(sched_info_on()))
2415 memset(&p->sched_info, 0, sizeof(p->sched_info));
2416 #endif
2417 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2418 p->oncpu = 0;
2419 #endif
2420 #ifdef CONFIG_PREEMPT
2421 /* Want to start with kernel preemption disabled. */
2422 task_thread_info(p)->preempt_count = 1;
2423 #endif
2424 put_cpu();
2428 * wake_up_new_task - wake up a newly created task for the first time.
2430 * This function will do some initial scheduler statistics housekeeping
2431 * that must be done for every newly created context, then puts the task
2432 * on the runqueue and wakes it.
2434 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2436 unsigned long flags;
2437 struct rq *rq;
2439 rq = task_rq_lock(p, &flags);
2440 BUG_ON(p->state != TASK_RUNNING);
2441 update_rq_clock(rq);
2443 p->prio = effective_prio(p);
2445 if (!p->sched_class->task_new || !current->se.on_rq) {
2446 activate_task(rq, p, 0);
2447 } else {
2449 * Let the scheduling class do new task startup
2450 * management (if any):
2452 p->sched_class->task_new(rq, p);
2453 inc_nr_running(rq);
2455 trace_sched_wakeup_new(rq, p);
2456 check_preempt_curr(rq, p, 0);
2457 #ifdef CONFIG_SMP
2458 if (p->sched_class->task_wake_up)
2459 p->sched_class->task_wake_up(rq, p);
2460 #endif
2461 task_rq_unlock(rq, &flags);
2464 #ifdef CONFIG_PREEMPT_NOTIFIERS
2467 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2468 * @notifier: notifier struct to register
2470 void preempt_notifier_register(struct preempt_notifier *notifier)
2472 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2474 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2477 * preempt_notifier_unregister - no longer interested in preemption notifications
2478 * @notifier: notifier struct to unregister
2480 * This is safe to call from within a preemption notifier.
2482 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2484 hlist_del(&notifier->link);
2486 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2488 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2490 struct preempt_notifier *notifier;
2491 struct hlist_node *node;
2493 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2494 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2497 static void
2498 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2499 struct task_struct *next)
2501 struct preempt_notifier *notifier;
2502 struct hlist_node *node;
2504 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2505 notifier->ops->sched_out(notifier, next);
2508 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2510 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2514 static void
2515 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2516 struct task_struct *next)
2520 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2523 * prepare_task_switch - prepare to switch tasks
2524 * @rq: the runqueue preparing to switch
2525 * @prev: the current task that is being switched out
2526 * @next: the task we are going to switch to.
2528 * This is called with the rq lock held and interrupts off. It must
2529 * be paired with a subsequent finish_task_switch after the context
2530 * switch.
2532 * prepare_task_switch sets up locking and calls architecture specific
2533 * hooks.
2535 static inline void
2536 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2537 struct task_struct *next)
2539 fire_sched_out_preempt_notifiers(prev, next);
2540 prepare_lock_switch(rq, next);
2541 prepare_arch_switch(next);
2545 * finish_task_switch - clean up after a task-switch
2546 * @rq: runqueue associated with task-switch
2547 * @prev: the thread we just switched away from.
2549 * finish_task_switch must be called after the context switch, paired
2550 * with a prepare_task_switch call before the context switch.
2551 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2552 * and do any other architecture-specific cleanup actions.
2554 * Note that we may have delayed dropping an mm in context_switch(). If
2555 * so, we finish that here outside of the runqueue lock. (Doing it
2556 * with the lock held can cause deadlocks; see schedule() for
2557 * details.)
2559 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2560 __releases(rq->lock)
2562 struct mm_struct *mm = rq->prev_mm;
2563 long prev_state;
2565 rq->prev_mm = NULL;
2568 * A task struct has one reference for the use as "current".
2569 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2570 * schedule one last time. The schedule call will never return, and
2571 * the scheduled task must drop that reference.
2572 * The test for TASK_DEAD must occur while the runqueue locks are
2573 * still held, otherwise prev could be scheduled on another cpu, die
2574 * there before we look at prev->state, and then the reference would
2575 * be dropped twice.
2576 * Manfred Spraul <manfred@colorfullife.com>
2578 prev_state = prev->state;
2579 finish_arch_switch(prev);
2580 finish_lock_switch(rq, prev);
2581 #ifdef CONFIG_SMP
2582 if (current->sched_class->post_schedule)
2583 current->sched_class->post_schedule(rq);
2584 #endif
2586 fire_sched_in_preempt_notifiers(current);
2587 if (mm)
2588 mmdrop(mm);
2589 if (unlikely(prev_state == TASK_DEAD)) {
2591 * Remove function-return probe instances associated with this
2592 * task and put them back on the free list.
2594 kprobe_flush_task(prev);
2595 put_task_struct(prev);
2600 * schedule_tail - first thing a freshly forked thread must call.
2601 * @prev: the thread we just switched away from.
2603 asmlinkage void schedule_tail(struct task_struct *prev)
2604 __releases(rq->lock)
2606 struct rq *rq = this_rq();
2608 finish_task_switch(rq, prev);
2609 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2610 /* In this case, finish_task_switch does not reenable preemption */
2611 preempt_enable();
2612 #endif
2613 if (current->set_child_tid)
2614 put_user(task_pid_vnr(current), current->set_child_tid);
2618 * context_switch - switch to the new MM and the new
2619 * thread's register state.
2621 static inline void
2622 context_switch(struct rq *rq, struct task_struct *prev,
2623 struct task_struct *next)
2625 struct mm_struct *mm, *oldmm;
2627 prepare_task_switch(rq, prev, next);
2628 trace_sched_switch(rq, prev, next);
2629 mm = next->mm;
2630 oldmm = prev->active_mm;
2632 * For paravirt, this is coupled with an exit in switch_to to
2633 * combine the page table reload and the switch backend into
2634 * one hypercall.
2636 arch_enter_lazy_cpu_mode();
2638 if (unlikely(!mm)) {
2639 next->active_mm = oldmm;
2640 atomic_inc(&oldmm->mm_count);
2641 enter_lazy_tlb(oldmm, next);
2642 } else
2643 switch_mm(oldmm, mm, next);
2645 if (unlikely(!prev->mm)) {
2646 prev->active_mm = NULL;
2647 rq->prev_mm = oldmm;
2650 * Since the runqueue lock will be released by the next
2651 * task (which is an invalid locking op but in the case
2652 * of the scheduler it's an obvious special-case), so we
2653 * do an early lockdep release here:
2655 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2656 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2657 #endif
2659 /* Here we just switch the register state and the stack. */
2660 switch_to(prev, next, prev);
2662 barrier();
2664 * this_rq must be evaluated again because prev may have moved
2665 * CPUs since it called schedule(), thus the 'rq' on its stack
2666 * frame will be invalid.
2668 finish_task_switch(this_rq(), prev);
2672 * nr_running, nr_uninterruptible and nr_context_switches:
2674 * externally visible scheduler statistics: current number of runnable
2675 * threads, current number of uninterruptible-sleeping threads, total
2676 * number of context switches performed since bootup.
2678 unsigned long nr_running(void)
2680 unsigned long i, sum = 0;
2682 for_each_online_cpu(i)
2683 sum += cpu_rq(i)->nr_running;
2685 return sum;
2688 unsigned long nr_uninterruptible(void)
2690 unsigned long i, sum = 0;
2692 for_each_possible_cpu(i)
2693 sum += cpu_rq(i)->nr_uninterruptible;
2696 * Since we read the counters lockless, it might be slightly
2697 * inaccurate. Do not allow it to go below zero though:
2699 if (unlikely((long)sum < 0))
2700 sum = 0;
2702 return sum;
2705 unsigned long long nr_context_switches(void)
2707 int i;
2708 unsigned long long sum = 0;
2710 for_each_possible_cpu(i)
2711 sum += cpu_rq(i)->nr_switches;
2713 return sum;
2716 unsigned long nr_iowait(void)
2718 unsigned long i, sum = 0;
2720 for_each_possible_cpu(i)
2721 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2723 return sum;
2726 unsigned long nr_active(void)
2728 unsigned long i, running = 0, uninterruptible = 0;
2730 for_each_online_cpu(i) {
2731 running += cpu_rq(i)->nr_running;
2732 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2735 if (unlikely((long)uninterruptible < 0))
2736 uninterruptible = 0;
2738 return running + uninterruptible;
2742 * Update rq->cpu_load[] statistics. This function is usually called every
2743 * scheduler tick (TICK_NSEC).
2745 static void update_cpu_load(struct rq *this_rq)
2747 unsigned long this_load = this_rq->load.weight;
2748 int i, scale;
2750 this_rq->nr_load_updates++;
2752 /* Update our load: */
2753 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2754 unsigned long old_load, new_load;
2756 /* scale is effectively 1 << i now, and >> i divides by scale */
2758 old_load = this_rq->cpu_load[i];
2759 new_load = this_load;
2761 * Round up the averaging division if load is increasing. This
2762 * prevents us from getting stuck on 9 if the load is 10, for
2763 * example.
2765 if (new_load > old_load)
2766 new_load += scale-1;
2767 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2771 #ifdef CONFIG_SMP
2774 * double_rq_lock - safely lock two runqueues
2776 * Note this does not disable interrupts like task_rq_lock,
2777 * you need to do so manually before calling.
2779 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2780 __acquires(rq1->lock)
2781 __acquires(rq2->lock)
2783 BUG_ON(!irqs_disabled());
2784 if (rq1 == rq2) {
2785 spin_lock(&rq1->lock);
2786 __acquire(rq2->lock); /* Fake it out ;) */
2787 } else {
2788 if (rq1 < rq2) {
2789 spin_lock(&rq1->lock);
2790 spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
2791 } else {
2792 spin_lock(&rq2->lock);
2793 spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
2796 update_rq_clock(rq1);
2797 update_rq_clock(rq2);
2801 * double_rq_unlock - safely unlock two runqueues
2803 * Note this does not restore interrupts like task_rq_unlock,
2804 * you need to do so manually after calling.
2806 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2807 __releases(rq1->lock)
2808 __releases(rq2->lock)
2810 spin_unlock(&rq1->lock);
2811 if (rq1 != rq2)
2812 spin_unlock(&rq2->lock);
2813 else
2814 __release(rq2->lock);
2818 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2820 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2821 __releases(this_rq->lock)
2822 __acquires(busiest->lock)
2823 __acquires(this_rq->lock)
2825 int ret = 0;
2827 if (unlikely(!irqs_disabled())) {
2828 /* printk() doesn't work good under rq->lock */
2829 spin_unlock(&this_rq->lock);
2830 BUG_ON(1);
2832 if (unlikely(!spin_trylock(&busiest->lock))) {
2833 if (busiest < this_rq) {
2834 spin_unlock(&this_rq->lock);
2835 spin_lock(&busiest->lock);
2836 spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING);
2837 ret = 1;
2838 } else
2839 spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING);
2841 return ret;
2844 static void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
2845 __releases(busiest->lock)
2847 spin_unlock(&busiest->lock);
2848 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
2852 * If dest_cpu is allowed for this process, migrate the task to it.
2853 * This is accomplished by forcing the cpu_allowed mask to only
2854 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2855 * the cpu_allowed mask is restored.
2857 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2859 struct migration_req req;
2860 unsigned long flags;
2861 struct rq *rq;
2863 rq = task_rq_lock(p, &flags);
2864 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2865 || unlikely(!cpu_active(dest_cpu)))
2866 goto out;
2868 trace_sched_migrate_task(rq, p, dest_cpu);
2869 /* force the process onto the specified CPU */
2870 if (migrate_task(p, dest_cpu, &req)) {
2871 /* Need to wait for migration thread (might exit: take ref). */
2872 struct task_struct *mt = rq->migration_thread;
2874 get_task_struct(mt);
2875 task_rq_unlock(rq, &flags);
2876 wake_up_process(mt);
2877 put_task_struct(mt);
2878 wait_for_completion(&req.done);
2880 return;
2882 out:
2883 task_rq_unlock(rq, &flags);
2887 * sched_exec - execve() is a valuable balancing opportunity, because at
2888 * this point the task has the smallest effective memory and cache footprint.
2890 void sched_exec(void)
2892 int new_cpu, this_cpu = get_cpu();
2893 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2894 put_cpu();
2895 if (new_cpu != this_cpu)
2896 sched_migrate_task(current, new_cpu);
2900 * pull_task - move a task from a remote runqueue to the local runqueue.
2901 * Both runqueues must be locked.
2903 static void pull_task(struct rq *src_rq, struct task_struct *p,
2904 struct rq *this_rq, int this_cpu)
2906 deactivate_task(src_rq, p, 0);
2907 set_task_cpu(p, this_cpu);
2908 activate_task(this_rq, p, 0);
2910 * Note that idle threads have a prio of MAX_PRIO, for this test
2911 * to be always true for them.
2913 check_preempt_curr(this_rq, p, 0);
2917 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2919 static
2920 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2921 struct sched_domain *sd, enum cpu_idle_type idle,
2922 int *all_pinned)
2925 * We do not migrate tasks that are:
2926 * 1) running (obviously), or
2927 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2928 * 3) are cache-hot on their current CPU.
2930 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2931 schedstat_inc(p, se.nr_failed_migrations_affine);
2932 return 0;
2934 *all_pinned = 0;
2936 if (task_running(rq, p)) {
2937 schedstat_inc(p, se.nr_failed_migrations_running);
2938 return 0;
2942 * Aggressive migration if:
2943 * 1) task is cache cold, or
2944 * 2) too many balance attempts have failed.
2947 if (!task_hot(p, rq->clock, sd) ||
2948 sd->nr_balance_failed > sd->cache_nice_tries) {
2949 #ifdef CONFIG_SCHEDSTATS
2950 if (task_hot(p, rq->clock, sd)) {
2951 schedstat_inc(sd, lb_hot_gained[idle]);
2952 schedstat_inc(p, se.nr_forced_migrations);
2954 #endif
2955 return 1;
2958 if (task_hot(p, rq->clock, sd)) {
2959 schedstat_inc(p, se.nr_failed_migrations_hot);
2960 return 0;
2962 return 1;
2965 static unsigned long
2966 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2967 unsigned long max_load_move, struct sched_domain *sd,
2968 enum cpu_idle_type idle, int *all_pinned,
2969 int *this_best_prio, struct rq_iterator *iterator)
2971 int loops = 0, pulled = 0, pinned = 0;
2972 struct task_struct *p;
2973 long rem_load_move = max_load_move;
2975 if (max_load_move == 0)
2976 goto out;
2978 pinned = 1;
2981 * Start the load-balancing iterator:
2983 p = iterator->start(iterator->arg);
2984 next:
2985 if (!p || loops++ > sysctl_sched_nr_migrate)
2986 goto out;
2988 if ((p->se.load.weight >> 1) > rem_load_move ||
2989 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2990 p = iterator->next(iterator->arg);
2991 goto next;
2994 pull_task(busiest, p, this_rq, this_cpu);
2995 pulled++;
2996 rem_load_move -= p->se.load.weight;
2999 * We only want to steal up to the prescribed amount of weighted load.
3001 if (rem_load_move > 0) {
3002 if (p->prio < *this_best_prio)
3003 *this_best_prio = p->prio;
3004 p = iterator->next(iterator->arg);
3005 goto next;
3007 out:
3009 * Right now, this is one of only two places pull_task() is called,
3010 * so we can safely collect pull_task() stats here rather than
3011 * inside pull_task().
3013 schedstat_add(sd, lb_gained[idle], pulled);
3015 if (all_pinned)
3016 *all_pinned = pinned;
3018 return max_load_move - rem_load_move;
3022 * move_tasks tries to move up to max_load_move weighted load from busiest to
3023 * this_rq, as part of a balancing operation within domain "sd".
3024 * Returns 1 if successful and 0 otherwise.
3026 * Called with both runqueues locked.
3028 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3029 unsigned long max_load_move,
3030 struct sched_domain *sd, enum cpu_idle_type idle,
3031 int *all_pinned)
3033 const struct sched_class *class = sched_class_highest;
3034 unsigned long total_load_moved = 0;
3035 int this_best_prio = this_rq->curr->prio;
3037 do {
3038 total_load_moved +=
3039 class->load_balance(this_rq, this_cpu, busiest,
3040 max_load_move - total_load_moved,
3041 sd, idle, all_pinned, &this_best_prio);
3042 class = class->next;
3044 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3045 break;
3047 } while (class && max_load_move > total_load_moved);
3049 return total_load_moved > 0;
3052 static int
3053 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3054 struct sched_domain *sd, enum cpu_idle_type idle,
3055 struct rq_iterator *iterator)
3057 struct task_struct *p = iterator->start(iterator->arg);
3058 int pinned = 0;
3060 while (p) {
3061 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3062 pull_task(busiest, p, this_rq, this_cpu);
3064 * Right now, this is only the second place pull_task()
3065 * is called, so we can safely collect pull_task()
3066 * stats here rather than inside pull_task().
3068 schedstat_inc(sd, lb_gained[idle]);
3070 return 1;
3072 p = iterator->next(iterator->arg);
3075 return 0;
3079 * move_one_task tries to move exactly one task from busiest to this_rq, as
3080 * part of active balancing operations within "domain".
3081 * Returns 1 if successful and 0 otherwise.
3083 * Called with both runqueues locked.
3085 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3086 struct sched_domain *sd, enum cpu_idle_type idle)
3088 const struct sched_class *class;
3090 for (class = sched_class_highest; class; class = class->next)
3091 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3092 return 1;
3094 return 0;
3098 * find_busiest_group finds and returns the busiest CPU group within the
3099 * domain. It calculates and returns the amount of weighted load which
3100 * should be moved to restore balance via the imbalance parameter.
3102 static struct sched_group *
3103 find_busiest_group(struct sched_domain *sd, int this_cpu,
3104 unsigned long *imbalance, enum cpu_idle_type idle,
3105 int *sd_idle, const cpumask_t *cpus, int *balance)
3107 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3108 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3109 unsigned long max_pull;
3110 unsigned long busiest_load_per_task, busiest_nr_running;
3111 unsigned long this_load_per_task, this_nr_running;
3112 int load_idx, group_imb = 0;
3113 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3114 int power_savings_balance = 1;
3115 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3116 unsigned long min_nr_running = ULONG_MAX;
3117 struct sched_group *group_min = NULL, *group_leader = NULL;
3118 #endif
3120 max_load = this_load = total_load = total_pwr = 0;
3121 busiest_load_per_task = busiest_nr_running = 0;
3122 this_load_per_task = this_nr_running = 0;
3124 if (idle == CPU_NOT_IDLE)
3125 load_idx = sd->busy_idx;
3126 else if (idle == CPU_NEWLY_IDLE)
3127 load_idx = sd->newidle_idx;
3128 else
3129 load_idx = sd->idle_idx;
3131 do {
3132 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3133 int local_group;
3134 int i;
3135 int __group_imb = 0;
3136 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3137 unsigned long sum_nr_running, sum_weighted_load;
3138 unsigned long sum_avg_load_per_task;
3139 unsigned long avg_load_per_task;
3141 local_group = cpu_isset(this_cpu, group->cpumask);
3143 if (local_group)
3144 balance_cpu = first_cpu(group->cpumask);
3146 /* Tally up the load of all CPUs in the group */
3147 sum_weighted_load = sum_nr_running = avg_load = 0;
3148 sum_avg_load_per_task = avg_load_per_task = 0;
3150 max_cpu_load = 0;
3151 min_cpu_load = ~0UL;
3153 for_each_cpu_mask_nr(i, group->cpumask) {
3154 struct rq *rq;
3156 if (!cpu_isset(i, *cpus))
3157 continue;
3159 rq = cpu_rq(i);
3161 if (*sd_idle && rq->nr_running)
3162 *sd_idle = 0;
3164 /* Bias balancing toward cpus of our domain */
3165 if (local_group) {
3166 if (idle_cpu(i) && !first_idle_cpu) {
3167 first_idle_cpu = 1;
3168 balance_cpu = i;
3171 load = target_load(i, load_idx);
3172 } else {
3173 load = source_load(i, load_idx);
3174 if (load > max_cpu_load)
3175 max_cpu_load = load;
3176 if (min_cpu_load > load)
3177 min_cpu_load = load;
3180 avg_load += load;
3181 sum_nr_running += rq->nr_running;
3182 sum_weighted_load += weighted_cpuload(i);
3184 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3188 * First idle cpu or the first cpu(busiest) in this sched group
3189 * is eligible for doing load balancing at this and above
3190 * domains. In the newly idle case, we will allow all the cpu's
3191 * to do the newly idle load balance.
3193 if (idle != CPU_NEWLY_IDLE && local_group &&
3194 balance_cpu != this_cpu && balance) {
3195 *balance = 0;
3196 goto ret;
3199 total_load += avg_load;
3200 total_pwr += group->__cpu_power;
3202 /* Adjust by relative CPU power of the group */
3203 avg_load = sg_div_cpu_power(group,
3204 avg_load * SCHED_LOAD_SCALE);
3208 * Consider the group unbalanced when the imbalance is larger
3209 * than the average weight of two tasks.
3211 * APZ: with cgroup the avg task weight can vary wildly and
3212 * might not be a suitable number - should we keep a
3213 * normalized nr_running number somewhere that negates
3214 * the hierarchy?
3216 avg_load_per_task = sg_div_cpu_power(group,
3217 sum_avg_load_per_task * SCHED_LOAD_SCALE);
3219 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3220 __group_imb = 1;
3222 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3224 if (local_group) {
3225 this_load = avg_load;
3226 this = group;
3227 this_nr_running = sum_nr_running;
3228 this_load_per_task = sum_weighted_load;
3229 } else if (avg_load > max_load &&
3230 (sum_nr_running > group_capacity || __group_imb)) {
3231 max_load = avg_load;
3232 busiest = group;
3233 busiest_nr_running = sum_nr_running;
3234 busiest_load_per_task = sum_weighted_load;
3235 group_imb = __group_imb;
3238 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3240 * Busy processors will not participate in power savings
3241 * balance.
3243 if (idle == CPU_NOT_IDLE ||
3244 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3245 goto group_next;
3248 * If the local group is idle or completely loaded
3249 * no need to do power savings balance at this domain
3251 if (local_group && (this_nr_running >= group_capacity ||
3252 !this_nr_running))
3253 power_savings_balance = 0;
3256 * If a group is already running at full capacity or idle,
3257 * don't include that group in power savings calculations
3259 if (!power_savings_balance || sum_nr_running >= group_capacity
3260 || !sum_nr_running)
3261 goto group_next;
3264 * Calculate the group which has the least non-idle load.
3265 * This is the group from where we need to pick up the load
3266 * for saving power
3268 if ((sum_nr_running < min_nr_running) ||
3269 (sum_nr_running == min_nr_running &&
3270 first_cpu(group->cpumask) <
3271 first_cpu(group_min->cpumask))) {
3272 group_min = group;
3273 min_nr_running = sum_nr_running;
3274 min_load_per_task = sum_weighted_load /
3275 sum_nr_running;
3279 * Calculate the group which is almost near its
3280 * capacity but still has some space to pick up some load
3281 * from other group and save more power
3283 if (sum_nr_running <= group_capacity - 1) {
3284 if (sum_nr_running > leader_nr_running ||
3285 (sum_nr_running == leader_nr_running &&
3286 first_cpu(group->cpumask) >
3287 first_cpu(group_leader->cpumask))) {
3288 group_leader = group;
3289 leader_nr_running = sum_nr_running;
3292 group_next:
3293 #endif
3294 group = group->next;
3295 } while (group != sd->groups);
3297 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3298 goto out_balanced;
3300 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3302 if (this_load >= avg_load ||
3303 100*max_load <= sd->imbalance_pct*this_load)
3304 goto out_balanced;
3306 busiest_load_per_task /= busiest_nr_running;
3307 if (group_imb)
3308 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3311 * We're trying to get all the cpus to the average_load, so we don't
3312 * want to push ourselves above the average load, nor do we wish to
3313 * reduce the max loaded cpu below the average load, as either of these
3314 * actions would just result in more rebalancing later, and ping-pong
3315 * tasks around. Thus we look for the minimum possible imbalance.
3316 * Negative imbalances (*we* are more loaded than anyone else) will
3317 * be counted as no imbalance for these purposes -- we can't fix that
3318 * by pulling tasks to us. Be careful of negative numbers as they'll
3319 * appear as very large values with unsigned longs.
3321 if (max_load <= busiest_load_per_task)
3322 goto out_balanced;
3325 * In the presence of smp nice balancing, certain scenarios can have
3326 * max load less than avg load(as we skip the groups at or below
3327 * its cpu_power, while calculating max_load..)
3329 if (max_load < avg_load) {
3330 *imbalance = 0;
3331 goto small_imbalance;
3334 /* Don't want to pull so many tasks that a group would go idle */
3335 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3337 /* How much load to actually move to equalise the imbalance */
3338 *imbalance = min(max_pull * busiest->__cpu_power,
3339 (avg_load - this_load) * this->__cpu_power)
3340 / SCHED_LOAD_SCALE;
3343 * if *imbalance is less than the average load per runnable task
3344 * there is no gaurantee that any tasks will be moved so we'll have
3345 * a think about bumping its value to force at least one task to be
3346 * moved
3348 if (*imbalance < busiest_load_per_task) {
3349 unsigned long tmp, pwr_now, pwr_move;
3350 unsigned int imbn;
3352 small_imbalance:
3353 pwr_move = pwr_now = 0;
3354 imbn = 2;
3355 if (this_nr_running) {
3356 this_load_per_task /= this_nr_running;
3357 if (busiest_load_per_task > this_load_per_task)
3358 imbn = 1;
3359 } else
3360 this_load_per_task = cpu_avg_load_per_task(this_cpu);
3362 if (max_load - this_load + busiest_load_per_task >=
3363 busiest_load_per_task * imbn) {
3364 *imbalance = busiest_load_per_task;
3365 return busiest;
3369 * OK, we don't have enough imbalance to justify moving tasks,
3370 * however we may be able to increase total CPU power used by
3371 * moving them.
3374 pwr_now += busiest->__cpu_power *
3375 min(busiest_load_per_task, max_load);
3376 pwr_now += this->__cpu_power *
3377 min(this_load_per_task, this_load);
3378 pwr_now /= SCHED_LOAD_SCALE;
3380 /* Amount of load we'd subtract */
3381 tmp = sg_div_cpu_power(busiest,
3382 busiest_load_per_task * SCHED_LOAD_SCALE);
3383 if (max_load > tmp)
3384 pwr_move += busiest->__cpu_power *
3385 min(busiest_load_per_task, max_load - tmp);
3387 /* Amount of load we'd add */
3388 if (max_load * busiest->__cpu_power <
3389 busiest_load_per_task * SCHED_LOAD_SCALE)
3390 tmp = sg_div_cpu_power(this,
3391 max_load * busiest->__cpu_power);
3392 else
3393 tmp = sg_div_cpu_power(this,
3394 busiest_load_per_task * SCHED_LOAD_SCALE);
3395 pwr_move += this->__cpu_power *
3396 min(this_load_per_task, this_load + tmp);
3397 pwr_move /= SCHED_LOAD_SCALE;
3399 /* Move if we gain throughput */
3400 if (pwr_move > pwr_now)
3401 *imbalance = busiest_load_per_task;
3404 return busiest;
3406 out_balanced:
3407 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3408 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3409 goto ret;
3411 if (this == group_leader && group_leader != group_min) {
3412 *imbalance = min_load_per_task;
3413 return group_min;
3415 #endif
3416 ret:
3417 *imbalance = 0;
3418 return NULL;
3422 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3424 static struct rq *
3425 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3426 unsigned long imbalance, const cpumask_t *cpus)
3428 struct rq *busiest = NULL, *rq;
3429 unsigned long max_load = 0;
3430 int i;
3432 for_each_cpu_mask_nr(i, group->cpumask) {
3433 unsigned long wl;
3435 if (!cpu_isset(i, *cpus))
3436 continue;
3438 rq = cpu_rq(i);
3439 wl = weighted_cpuload(i);
3441 if (rq->nr_running == 1 && wl > imbalance)
3442 continue;
3444 if (wl > max_load) {
3445 max_load = wl;
3446 busiest = rq;
3450 return busiest;
3454 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3455 * so long as it is large enough.
3457 #define MAX_PINNED_INTERVAL 512
3460 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3461 * tasks if there is an imbalance.
3463 static int load_balance(int this_cpu, struct rq *this_rq,
3464 struct sched_domain *sd, enum cpu_idle_type idle,
3465 int *balance, cpumask_t *cpus)
3467 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3468 struct sched_group *group;
3469 unsigned long imbalance;
3470 struct rq *busiest;
3471 unsigned long flags;
3473 cpus_setall(*cpus);
3476 * When power savings policy is enabled for the parent domain, idle
3477 * sibling can pick up load irrespective of busy siblings. In this case,
3478 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3479 * portraying it as CPU_NOT_IDLE.
3481 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3482 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3483 sd_idle = 1;
3485 schedstat_inc(sd, lb_count[idle]);
3487 redo:
3488 update_shares(sd);
3489 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3490 cpus, balance);
3492 if (*balance == 0)
3493 goto out_balanced;
3495 if (!group) {
3496 schedstat_inc(sd, lb_nobusyg[idle]);
3497 goto out_balanced;
3500 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3501 if (!busiest) {
3502 schedstat_inc(sd, lb_nobusyq[idle]);
3503 goto out_balanced;
3506 BUG_ON(busiest == this_rq);
3508 schedstat_add(sd, lb_imbalance[idle], imbalance);
3510 ld_moved = 0;
3511 if (busiest->nr_running > 1) {
3513 * Attempt to move tasks. If find_busiest_group has found
3514 * an imbalance but busiest->nr_running <= 1, the group is
3515 * still unbalanced. ld_moved simply stays zero, so it is
3516 * correctly treated as an imbalance.
3518 local_irq_save(flags);
3519 double_rq_lock(this_rq, busiest);
3520 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3521 imbalance, sd, idle, &all_pinned);
3522 double_rq_unlock(this_rq, busiest);
3523 local_irq_restore(flags);
3526 * some other cpu did the load balance for us.
3528 if (ld_moved && this_cpu != smp_processor_id())
3529 resched_cpu(this_cpu);
3531 /* All tasks on this runqueue were pinned by CPU affinity */
3532 if (unlikely(all_pinned)) {
3533 cpu_clear(cpu_of(busiest), *cpus);
3534 if (!cpus_empty(*cpus))
3535 goto redo;
3536 goto out_balanced;
3540 if (!ld_moved) {
3541 schedstat_inc(sd, lb_failed[idle]);
3542 sd->nr_balance_failed++;
3544 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3546 spin_lock_irqsave(&busiest->lock, flags);
3548 /* don't kick the migration_thread, if the curr
3549 * task on busiest cpu can't be moved to this_cpu
3551 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3552 spin_unlock_irqrestore(&busiest->lock, flags);
3553 all_pinned = 1;
3554 goto out_one_pinned;
3557 if (!busiest->active_balance) {
3558 busiest->active_balance = 1;
3559 busiest->push_cpu = this_cpu;
3560 active_balance = 1;
3562 spin_unlock_irqrestore(&busiest->lock, flags);
3563 if (active_balance)
3564 wake_up_process(busiest->migration_thread);
3567 * We've kicked active balancing, reset the failure
3568 * counter.
3570 sd->nr_balance_failed = sd->cache_nice_tries+1;
3572 } else
3573 sd->nr_balance_failed = 0;
3575 if (likely(!active_balance)) {
3576 /* We were unbalanced, so reset the balancing interval */
3577 sd->balance_interval = sd->min_interval;
3578 } else {
3580 * If we've begun active balancing, start to back off. This
3581 * case may not be covered by the all_pinned logic if there
3582 * is only 1 task on the busy runqueue (because we don't call
3583 * move_tasks).
3585 if (sd->balance_interval < sd->max_interval)
3586 sd->balance_interval *= 2;
3589 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3590 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3591 ld_moved = -1;
3593 goto out;
3595 out_balanced:
3596 schedstat_inc(sd, lb_balanced[idle]);
3598 sd->nr_balance_failed = 0;
3600 out_one_pinned:
3601 /* tune up the balancing interval */
3602 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3603 (sd->balance_interval < sd->max_interval))
3604 sd->balance_interval *= 2;
3606 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3607 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3608 ld_moved = -1;
3609 else
3610 ld_moved = 0;
3611 out:
3612 if (ld_moved)
3613 update_shares(sd);
3614 return ld_moved;
3618 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3619 * tasks if there is an imbalance.
3621 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3622 * this_rq is locked.
3624 static int
3625 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3626 cpumask_t *cpus)
3628 struct sched_group *group;
3629 struct rq *busiest = NULL;
3630 unsigned long imbalance;
3631 int ld_moved = 0;
3632 int sd_idle = 0;
3633 int all_pinned = 0;
3635 cpus_setall(*cpus);
3638 * When power savings policy is enabled for the parent domain, idle
3639 * sibling can pick up load irrespective of busy siblings. In this case,
3640 * let the state of idle sibling percolate up as IDLE, instead of
3641 * portraying it as CPU_NOT_IDLE.
3643 if (sd->flags & SD_SHARE_CPUPOWER &&
3644 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3645 sd_idle = 1;
3647 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3648 redo:
3649 update_shares_locked(this_rq, sd);
3650 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3651 &sd_idle, cpus, NULL);
3652 if (!group) {
3653 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3654 goto out_balanced;
3657 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3658 if (!busiest) {
3659 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3660 goto out_balanced;
3663 BUG_ON(busiest == this_rq);
3665 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3667 ld_moved = 0;
3668 if (busiest->nr_running > 1) {
3669 /* Attempt to move tasks */
3670 double_lock_balance(this_rq, busiest);
3671 /* this_rq->clock is already updated */
3672 update_rq_clock(busiest);
3673 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3674 imbalance, sd, CPU_NEWLY_IDLE,
3675 &all_pinned);
3676 double_unlock_balance(this_rq, busiest);
3678 if (unlikely(all_pinned)) {
3679 cpu_clear(cpu_of(busiest), *cpus);
3680 if (!cpus_empty(*cpus))
3681 goto redo;
3685 if (!ld_moved) {
3686 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3687 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3688 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3689 return -1;
3690 } else
3691 sd->nr_balance_failed = 0;
3693 update_shares_locked(this_rq, sd);
3694 return ld_moved;
3696 out_balanced:
3697 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3698 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3699 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3700 return -1;
3701 sd->nr_balance_failed = 0;
3703 return 0;
3707 * idle_balance is called by schedule() if this_cpu is about to become
3708 * idle. Attempts to pull tasks from other CPUs.
3710 static void idle_balance(int this_cpu, struct rq *this_rq)
3712 struct sched_domain *sd;
3713 int pulled_task = -1;
3714 unsigned long next_balance = jiffies + HZ;
3715 cpumask_t tmpmask;
3717 for_each_domain(this_cpu, sd) {
3718 unsigned long interval;
3720 if (!(sd->flags & SD_LOAD_BALANCE))
3721 continue;
3723 if (sd->flags & SD_BALANCE_NEWIDLE)
3724 /* If we've pulled tasks over stop searching: */
3725 pulled_task = load_balance_newidle(this_cpu, this_rq,
3726 sd, &tmpmask);
3728 interval = msecs_to_jiffies(sd->balance_interval);
3729 if (time_after(next_balance, sd->last_balance + interval))
3730 next_balance = sd->last_balance + interval;
3731 if (pulled_task)
3732 break;
3734 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3736 * We are going idle. next_balance may be set based on
3737 * a busy processor. So reset next_balance.
3739 this_rq->next_balance = next_balance;
3744 * active_load_balance is run by migration threads. It pushes running tasks
3745 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3746 * running on each physical CPU where possible, and avoids physical /
3747 * logical imbalances.
3749 * Called with busiest_rq locked.
3751 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3753 int target_cpu = busiest_rq->push_cpu;
3754 struct sched_domain *sd;
3755 struct rq *target_rq;
3757 /* Is there any task to move? */
3758 if (busiest_rq->nr_running <= 1)
3759 return;
3761 target_rq = cpu_rq(target_cpu);
3764 * This condition is "impossible", if it occurs
3765 * we need to fix it. Originally reported by
3766 * Bjorn Helgaas on a 128-cpu setup.
3768 BUG_ON(busiest_rq == target_rq);
3770 /* move a task from busiest_rq to target_rq */
3771 double_lock_balance(busiest_rq, target_rq);
3772 update_rq_clock(busiest_rq);
3773 update_rq_clock(target_rq);
3775 /* Search for an sd spanning us and the target CPU. */
3776 for_each_domain(target_cpu, sd) {
3777 if ((sd->flags & SD_LOAD_BALANCE) &&
3778 cpu_isset(busiest_cpu, sd->span))
3779 break;
3782 if (likely(sd)) {
3783 schedstat_inc(sd, alb_count);
3785 if (move_one_task(target_rq, target_cpu, busiest_rq,
3786 sd, CPU_IDLE))
3787 schedstat_inc(sd, alb_pushed);
3788 else
3789 schedstat_inc(sd, alb_failed);
3791 double_unlock_balance(busiest_rq, target_rq);
3794 #ifdef CONFIG_NO_HZ
3795 static struct {
3796 atomic_t load_balancer;
3797 cpumask_t cpu_mask;
3798 } nohz ____cacheline_aligned = {
3799 .load_balancer = ATOMIC_INIT(-1),
3800 .cpu_mask = CPU_MASK_NONE,
3804 * This routine will try to nominate the ilb (idle load balancing)
3805 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3806 * load balancing on behalf of all those cpus. If all the cpus in the system
3807 * go into this tickless mode, then there will be no ilb owner (as there is
3808 * no need for one) and all the cpus will sleep till the next wakeup event
3809 * arrives...
3811 * For the ilb owner, tick is not stopped. And this tick will be used
3812 * for idle load balancing. ilb owner will still be part of
3813 * nohz.cpu_mask..
3815 * While stopping the tick, this cpu will become the ilb owner if there
3816 * is no other owner. And will be the owner till that cpu becomes busy
3817 * or if all cpus in the system stop their ticks at which point
3818 * there is no need for ilb owner.
3820 * When the ilb owner becomes busy, it nominates another owner, during the
3821 * next busy scheduler_tick()
3823 int select_nohz_load_balancer(int stop_tick)
3825 int cpu = smp_processor_id();
3827 if (stop_tick) {
3828 cpu_set(cpu, nohz.cpu_mask);
3829 cpu_rq(cpu)->in_nohz_recently = 1;
3832 * If we are going offline and still the leader, give up!
3834 if (!cpu_active(cpu) &&
3835 atomic_read(&nohz.load_balancer) == cpu) {
3836 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3837 BUG();
3838 return 0;
3841 /* time for ilb owner also to sleep */
3842 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3843 if (atomic_read(&nohz.load_balancer) == cpu)
3844 atomic_set(&nohz.load_balancer, -1);
3845 return 0;
3848 if (atomic_read(&nohz.load_balancer) == -1) {
3849 /* make me the ilb owner */
3850 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3851 return 1;
3852 } else if (atomic_read(&nohz.load_balancer) == cpu)
3853 return 1;
3854 } else {
3855 if (!cpu_isset(cpu, nohz.cpu_mask))
3856 return 0;
3858 cpu_clear(cpu, nohz.cpu_mask);
3860 if (atomic_read(&nohz.load_balancer) == cpu)
3861 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3862 BUG();
3864 return 0;
3866 #endif
3868 static DEFINE_SPINLOCK(balancing);
3871 * It checks each scheduling domain to see if it is due to be balanced,
3872 * and initiates a balancing operation if so.
3874 * Balancing parameters are set up in arch_init_sched_domains.
3876 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3878 int balance = 1;
3879 struct rq *rq = cpu_rq(cpu);
3880 unsigned long interval;
3881 struct sched_domain *sd;
3882 /* Earliest time when we have to do rebalance again */
3883 unsigned long next_balance = jiffies + 60*HZ;
3884 int update_next_balance = 0;
3885 int need_serialize;
3886 cpumask_t tmp;
3888 for_each_domain(cpu, sd) {
3889 if (!(sd->flags & SD_LOAD_BALANCE))
3890 continue;
3892 interval = sd->balance_interval;
3893 if (idle != CPU_IDLE)
3894 interval *= sd->busy_factor;
3896 /* scale ms to jiffies */
3897 interval = msecs_to_jiffies(interval);
3898 if (unlikely(!interval))
3899 interval = 1;
3900 if (interval > HZ*NR_CPUS/10)
3901 interval = HZ*NR_CPUS/10;
3903 need_serialize = sd->flags & SD_SERIALIZE;
3905 if (need_serialize) {
3906 if (!spin_trylock(&balancing))
3907 goto out;
3910 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3911 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
3913 * We've pulled tasks over so either we're no
3914 * longer idle, or one of our SMT siblings is
3915 * not idle.
3917 idle = CPU_NOT_IDLE;
3919 sd->last_balance = jiffies;
3921 if (need_serialize)
3922 spin_unlock(&balancing);
3923 out:
3924 if (time_after(next_balance, sd->last_balance + interval)) {
3925 next_balance = sd->last_balance + interval;
3926 update_next_balance = 1;
3930 * Stop the load balance at this level. There is another
3931 * CPU in our sched group which is doing load balancing more
3932 * actively.
3934 if (!balance)
3935 break;
3939 * next_balance will be updated only when there is a need.
3940 * When the cpu is attached to null domain for ex, it will not be
3941 * updated.
3943 if (likely(update_next_balance))
3944 rq->next_balance = next_balance;
3948 * run_rebalance_domains is triggered when needed from the scheduler tick.
3949 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3950 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3952 static void run_rebalance_domains(struct softirq_action *h)
3954 int this_cpu = smp_processor_id();
3955 struct rq *this_rq = cpu_rq(this_cpu);
3956 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3957 CPU_IDLE : CPU_NOT_IDLE;
3959 rebalance_domains(this_cpu, idle);
3961 #ifdef CONFIG_NO_HZ
3963 * If this cpu is the owner for idle load balancing, then do the
3964 * balancing on behalf of the other idle cpus whose ticks are
3965 * stopped.
3967 if (this_rq->idle_at_tick &&
3968 atomic_read(&nohz.load_balancer) == this_cpu) {
3969 cpumask_t cpus = nohz.cpu_mask;
3970 struct rq *rq;
3971 int balance_cpu;
3973 cpu_clear(this_cpu, cpus);
3974 for_each_cpu_mask_nr(balance_cpu, cpus) {
3976 * If this cpu gets work to do, stop the load balancing
3977 * work being done for other cpus. Next load
3978 * balancing owner will pick it up.
3980 if (need_resched())
3981 break;
3983 rebalance_domains(balance_cpu, CPU_IDLE);
3985 rq = cpu_rq(balance_cpu);
3986 if (time_after(this_rq->next_balance, rq->next_balance))
3987 this_rq->next_balance = rq->next_balance;
3990 #endif
3994 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3996 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3997 * idle load balancing owner or decide to stop the periodic load balancing,
3998 * if the whole system is idle.
4000 static inline void trigger_load_balance(struct rq *rq, int cpu)
4002 #ifdef CONFIG_NO_HZ
4004 * If we were in the nohz mode recently and busy at the current
4005 * scheduler tick, then check if we need to nominate new idle
4006 * load balancer.
4008 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4009 rq->in_nohz_recently = 0;
4011 if (atomic_read(&nohz.load_balancer) == cpu) {
4012 cpu_clear(cpu, nohz.cpu_mask);
4013 atomic_set(&nohz.load_balancer, -1);
4016 if (atomic_read(&nohz.load_balancer) == -1) {
4018 * simple selection for now: Nominate the
4019 * first cpu in the nohz list to be the next
4020 * ilb owner.
4022 * TBD: Traverse the sched domains and nominate
4023 * the nearest cpu in the nohz.cpu_mask.
4025 int ilb = first_cpu(nohz.cpu_mask);
4027 if (ilb < nr_cpu_ids)
4028 resched_cpu(ilb);
4033 * If this cpu is idle and doing idle load balancing for all the
4034 * cpus with ticks stopped, is it time for that to stop?
4036 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4037 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4038 resched_cpu(cpu);
4039 return;
4043 * If this cpu is idle and the idle load balancing is done by
4044 * someone else, then no need raise the SCHED_SOFTIRQ
4046 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4047 cpu_isset(cpu, nohz.cpu_mask))
4048 return;
4049 #endif
4050 if (time_after_eq(jiffies, rq->next_balance))
4051 raise_softirq(SCHED_SOFTIRQ);
4054 #else /* CONFIG_SMP */
4057 * on UP we do not need to balance between CPUs:
4059 static inline void idle_balance(int cpu, struct rq *rq)
4063 #endif
4065 DEFINE_PER_CPU(struct kernel_stat, kstat);
4067 EXPORT_PER_CPU_SYMBOL(kstat);
4070 * Return any ns on the sched_clock that have not yet been banked in
4071 * @p in case that task is currently running.
4073 unsigned long long task_delta_exec(struct task_struct *p)
4075 unsigned long flags;
4076 struct rq *rq;
4077 u64 ns = 0;
4079 rq = task_rq_lock(p, &flags);
4081 if (task_current(rq, p)) {
4082 u64 delta_exec;
4084 update_rq_clock(rq);
4085 delta_exec = rq->clock - p->se.exec_start;
4086 if ((s64)delta_exec > 0)
4087 ns = delta_exec;
4090 task_rq_unlock(rq, &flags);
4092 return ns;
4096 * Account user cpu time to a process.
4097 * @p: the process that the cpu time gets accounted to
4098 * @cputime: the cpu time spent in user space since the last update
4100 void account_user_time(struct task_struct *p, cputime_t cputime)
4102 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4103 cputime64_t tmp;
4105 p->utime = cputime_add(p->utime, cputime);
4106 account_group_user_time(p, cputime);
4108 /* Add user time to cpustat. */
4109 tmp = cputime_to_cputime64(cputime);
4110 if (TASK_NICE(p) > 0)
4111 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4112 else
4113 cpustat->user = cputime64_add(cpustat->user, tmp);
4114 /* Account for user time used */
4115 acct_update_integrals(p);
4119 * Account guest cpu time to a process.
4120 * @p: the process that the cpu time gets accounted to
4121 * @cputime: the cpu time spent in virtual machine since the last update
4123 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4125 cputime64_t tmp;
4126 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4128 tmp = cputime_to_cputime64(cputime);
4130 p->utime = cputime_add(p->utime, cputime);
4131 account_group_user_time(p, cputime);
4132 p->gtime = cputime_add(p->gtime, cputime);
4134 cpustat->user = cputime64_add(cpustat->user, tmp);
4135 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4139 * Account scaled user cpu time to a process.
4140 * @p: the process that the cpu time gets accounted to
4141 * @cputime: the cpu time spent in user space since the last update
4143 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4145 p->utimescaled = cputime_add(p->utimescaled, cputime);
4149 * Account system cpu time to a process.
4150 * @p: the process that the cpu time gets accounted to
4151 * @hardirq_offset: the offset to subtract from hardirq_count()
4152 * @cputime: the cpu time spent in kernel space since the last update
4154 void account_system_time(struct task_struct *p, int hardirq_offset,
4155 cputime_t cputime)
4157 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4158 struct rq *rq = this_rq();
4159 cputime64_t tmp;
4161 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4162 account_guest_time(p, cputime);
4163 return;
4166 p->stime = cputime_add(p->stime, cputime);
4167 account_group_system_time(p, cputime);
4169 /* Add system time to cpustat. */
4170 tmp = cputime_to_cputime64(cputime);
4171 if (hardirq_count() - hardirq_offset)
4172 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4173 else if (softirq_count())
4174 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4175 else if (p != rq->idle)
4176 cpustat->system = cputime64_add(cpustat->system, tmp);
4177 else if (atomic_read(&rq->nr_iowait) > 0)
4178 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4179 else
4180 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4181 /* Account for system time used */
4182 acct_update_integrals(p);
4186 * Account scaled system cpu time to a process.
4187 * @p: the process that the cpu time gets accounted to
4188 * @hardirq_offset: the offset to subtract from hardirq_count()
4189 * @cputime: the cpu time spent in kernel space since the last update
4191 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4193 p->stimescaled = cputime_add(p->stimescaled, cputime);
4197 * Account for involuntary wait time.
4198 * @p: the process from which the cpu time has been stolen
4199 * @steal: the cpu time spent in involuntary wait
4201 void account_steal_time(struct task_struct *p, cputime_t steal)
4203 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4204 cputime64_t tmp = cputime_to_cputime64(steal);
4205 struct rq *rq = this_rq();
4207 if (p == rq->idle) {
4208 p->stime = cputime_add(p->stime, steal);
4209 account_group_system_time(p, steal);
4210 if (atomic_read(&rq->nr_iowait) > 0)
4211 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4212 else
4213 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4214 } else
4215 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4219 * Use precise platform statistics if available:
4221 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
4222 cputime_t task_utime(struct task_struct *p)
4224 return p->utime;
4227 cputime_t task_stime(struct task_struct *p)
4229 return p->stime;
4231 #else
4232 cputime_t task_utime(struct task_struct *p)
4234 clock_t utime = cputime_to_clock_t(p->utime),
4235 total = utime + cputime_to_clock_t(p->stime);
4236 u64 temp;
4239 * Use CFS's precise accounting:
4241 temp = (u64)nsec_to_clock_t(p->se.sum_exec_runtime);
4243 if (total) {
4244 temp *= utime;
4245 do_div(temp, total);
4247 utime = (clock_t)temp;
4249 p->prev_utime = max(p->prev_utime, clock_t_to_cputime(utime));
4250 return p->prev_utime;
4253 cputime_t task_stime(struct task_struct *p)
4255 clock_t stime;
4258 * Use CFS's precise accounting. (we subtract utime from
4259 * the total, to make sure the total observed by userspace
4260 * grows monotonically - apps rely on that):
4262 stime = nsec_to_clock_t(p->se.sum_exec_runtime) -
4263 cputime_to_clock_t(task_utime(p));
4265 if (stime >= 0)
4266 p->prev_stime = max(p->prev_stime, clock_t_to_cputime(stime));
4268 return p->prev_stime;
4270 #endif
4272 inline cputime_t task_gtime(struct task_struct *p)
4274 return p->gtime;
4278 * This function gets called by the timer code, with HZ frequency.
4279 * We call it with interrupts disabled.
4281 * It also gets called by the fork code, when changing the parent's
4282 * timeslices.
4284 void scheduler_tick(void)
4286 int cpu = smp_processor_id();
4287 struct rq *rq = cpu_rq(cpu);
4288 struct task_struct *curr = rq->curr;
4290 sched_clock_tick();
4292 spin_lock(&rq->lock);
4293 update_rq_clock(rq);
4294 update_cpu_load(rq);
4295 curr->sched_class->task_tick(rq, curr, 0);
4296 spin_unlock(&rq->lock);
4298 #ifdef CONFIG_SMP
4299 rq->idle_at_tick = idle_cpu(cpu);
4300 trigger_load_balance(rq, cpu);
4301 #endif
4304 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4305 defined(CONFIG_PREEMPT_TRACER))
4307 static inline unsigned long get_parent_ip(unsigned long addr)
4309 if (in_lock_functions(addr)) {
4310 addr = CALLER_ADDR2;
4311 if (in_lock_functions(addr))
4312 addr = CALLER_ADDR3;
4314 return addr;
4317 void __kprobes add_preempt_count(int val)
4319 #ifdef CONFIG_DEBUG_PREEMPT
4321 * Underflow?
4323 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4324 return;
4325 #endif
4326 preempt_count() += val;
4327 #ifdef CONFIG_DEBUG_PREEMPT
4329 * Spinlock count overflowing soon?
4331 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4332 PREEMPT_MASK - 10);
4333 #endif
4334 if (preempt_count() == val)
4335 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4337 EXPORT_SYMBOL(add_preempt_count);
4339 void __kprobes sub_preempt_count(int val)
4341 #ifdef CONFIG_DEBUG_PREEMPT
4343 * Underflow?
4345 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4346 return;
4348 * Is the spinlock portion underflowing?
4350 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4351 !(preempt_count() & PREEMPT_MASK)))
4352 return;
4353 #endif
4355 if (preempt_count() == val)
4356 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4357 preempt_count() -= val;
4359 EXPORT_SYMBOL(sub_preempt_count);
4361 #endif
4364 * Print scheduling while atomic bug:
4366 static noinline void __schedule_bug(struct task_struct *prev)
4368 struct pt_regs *regs = get_irq_regs();
4370 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4371 prev->comm, prev->pid, preempt_count());
4373 debug_show_held_locks(prev);
4374 print_modules();
4375 if (irqs_disabled())
4376 print_irqtrace_events(prev);
4378 if (regs)
4379 show_regs(regs);
4380 else
4381 dump_stack();
4385 * Various schedule()-time debugging checks and statistics:
4387 static inline void schedule_debug(struct task_struct *prev)
4390 * Test if we are atomic. Since do_exit() needs to call into
4391 * schedule() atomically, we ignore that path for now.
4392 * Otherwise, whine if we are scheduling when we should not be.
4394 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
4395 __schedule_bug(prev);
4397 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4399 schedstat_inc(this_rq(), sched_count);
4400 #ifdef CONFIG_SCHEDSTATS
4401 if (unlikely(prev->lock_depth >= 0)) {
4402 schedstat_inc(this_rq(), bkl_count);
4403 schedstat_inc(prev, sched_info.bkl_count);
4405 #endif
4409 * Pick up the highest-prio task:
4411 static inline struct task_struct *
4412 pick_next_task(struct rq *rq, struct task_struct *prev)
4414 const struct sched_class *class;
4415 struct task_struct *p;
4418 * Optimization: we know that if all tasks are in
4419 * the fair class we can call that function directly:
4421 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4422 p = fair_sched_class.pick_next_task(rq);
4423 if (likely(p))
4424 return p;
4427 class = sched_class_highest;
4428 for ( ; ; ) {
4429 p = class->pick_next_task(rq);
4430 if (p)
4431 return p;
4433 * Will never be NULL as the idle class always
4434 * returns a non-NULL p:
4436 class = class->next;
4441 * schedule() is the main scheduler function.
4443 asmlinkage void __sched schedule(void)
4445 struct task_struct *prev, *next;
4446 unsigned long *switch_count;
4447 struct rq *rq;
4448 int cpu;
4450 need_resched:
4451 preempt_disable();
4452 cpu = smp_processor_id();
4453 rq = cpu_rq(cpu);
4454 rcu_qsctr_inc(cpu);
4455 prev = rq->curr;
4456 switch_count = &prev->nivcsw;
4458 release_kernel_lock(prev);
4459 need_resched_nonpreemptible:
4461 schedule_debug(prev);
4463 if (sched_feat(HRTICK))
4464 hrtick_clear(rq);
4466 spin_lock_irq(&rq->lock);
4467 update_rq_clock(rq);
4468 clear_tsk_need_resched(prev);
4470 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4471 if (unlikely(signal_pending_state(prev->state, prev)))
4472 prev->state = TASK_RUNNING;
4473 else
4474 deactivate_task(rq, prev, 1);
4475 switch_count = &prev->nvcsw;
4478 #ifdef CONFIG_SMP
4479 if (prev->sched_class->pre_schedule)
4480 prev->sched_class->pre_schedule(rq, prev);
4481 #endif
4483 if (unlikely(!rq->nr_running))
4484 idle_balance(cpu, rq);
4486 prev->sched_class->put_prev_task(rq, prev);
4487 next = pick_next_task(rq, prev);
4489 if (likely(prev != next)) {
4490 sched_info_switch(prev, next);
4492 rq->nr_switches++;
4493 rq->curr = next;
4494 ++*switch_count;
4496 context_switch(rq, prev, next); /* unlocks the rq */
4498 * the context switch might have flipped the stack from under
4499 * us, hence refresh the local variables.
4501 cpu = smp_processor_id();
4502 rq = cpu_rq(cpu);
4503 } else
4504 spin_unlock_irq(&rq->lock);
4506 if (unlikely(reacquire_kernel_lock(current) < 0))
4507 goto need_resched_nonpreemptible;
4509 preempt_enable_no_resched();
4510 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4511 goto need_resched;
4513 EXPORT_SYMBOL(schedule);
4515 #ifdef CONFIG_PREEMPT
4517 * this is the entry point to schedule() from in-kernel preemption
4518 * off of preempt_enable. Kernel preemptions off return from interrupt
4519 * occur there and call schedule directly.
4521 asmlinkage void __sched preempt_schedule(void)
4523 struct thread_info *ti = current_thread_info();
4526 * If there is a non-zero preempt_count or interrupts are disabled,
4527 * we do not want to preempt the current task. Just return..
4529 if (likely(ti->preempt_count || irqs_disabled()))
4530 return;
4532 do {
4533 add_preempt_count(PREEMPT_ACTIVE);
4534 schedule();
4535 sub_preempt_count(PREEMPT_ACTIVE);
4538 * Check again in case we missed a preemption opportunity
4539 * between schedule and now.
4541 barrier();
4542 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4544 EXPORT_SYMBOL(preempt_schedule);
4547 * this is the entry point to schedule() from kernel preemption
4548 * off of irq context.
4549 * Note, that this is called and return with irqs disabled. This will
4550 * protect us against recursive calling from irq.
4552 asmlinkage void __sched preempt_schedule_irq(void)
4554 struct thread_info *ti = current_thread_info();
4556 /* Catch callers which need to be fixed */
4557 BUG_ON(ti->preempt_count || !irqs_disabled());
4559 do {
4560 add_preempt_count(PREEMPT_ACTIVE);
4561 local_irq_enable();
4562 schedule();
4563 local_irq_disable();
4564 sub_preempt_count(PREEMPT_ACTIVE);
4567 * Check again in case we missed a preemption opportunity
4568 * between schedule and now.
4570 barrier();
4571 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4574 #endif /* CONFIG_PREEMPT */
4576 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4577 void *key)
4579 return try_to_wake_up(curr->private, mode, sync);
4581 EXPORT_SYMBOL(default_wake_function);
4584 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4585 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4586 * number) then we wake all the non-exclusive tasks and one exclusive task.
4588 * There are circumstances in which we can try to wake a task which has already
4589 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4590 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4592 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4593 int nr_exclusive, int sync, void *key)
4595 wait_queue_t *curr, *next;
4597 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4598 unsigned flags = curr->flags;
4600 if (curr->func(curr, mode, sync, key) &&
4601 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4602 break;
4607 * __wake_up - wake up threads blocked on a waitqueue.
4608 * @q: the waitqueue
4609 * @mode: which threads
4610 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4611 * @key: is directly passed to the wakeup function
4613 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4614 int nr_exclusive, void *key)
4616 unsigned long flags;
4618 spin_lock_irqsave(&q->lock, flags);
4619 __wake_up_common(q, mode, nr_exclusive, 0, key);
4620 spin_unlock_irqrestore(&q->lock, flags);
4622 EXPORT_SYMBOL(__wake_up);
4625 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4627 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4629 __wake_up_common(q, mode, 1, 0, NULL);
4633 * __wake_up_sync - wake up threads blocked on a waitqueue.
4634 * @q: the waitqueue
4635 * @mode: which threads
4636 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4638 * The sync wakeup differs that the waker knows that it will schedule
4639 * away soon, so while the target thread will be woken up, it will not
4640 * be migrated to another CPU - ie. the two threads are 'synchronized'
4641 * with each other. This can prevent needless bouncing between CPUs.
4643 * On UP it can prevent extra preemption.
4645 void
4646 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4648 unsigned long flags;
4649 int sync = 1;
4651 if (unlikely(!q))
4652 return;
4654 if (unlikely(!nr_exclusive))
4655 sync = 0;
4657 spin_lock_irqsave(&q->lock, flags);
4658 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4659 spin_unlock_irqrestore(&q->lock, flags);
4661 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4664 * complete: - signals a single thread waiting on this completion
4665 * @x: holds the state of this particular completion
4667 * This will wake up a single thread waiting on this completion. Threads will be
4668 * awakened in the same order in which they were queued.
4670 * See also complete_all(), wait_for_completion() and related routines.
4672 void complete(struct completion *x)
4674 unsigned long flags;
4676 spin_lock_irqsave(&x->wait.lock, flags);
4677 x->done++;
4678 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4679 spin_unlock_irqrestore(&x->wait.lock, flags);
4681 EXPORT_SYMBOL(complete);
4684 * complete_all: - signals all threads waiting on this completion
4685 * @x: holds the state of this particular completion
4687 * This will wake up all threads waiting on this particular completion event.
4689 void complete_all(struct completion *x)
4691 unsigned long flags;
4693 spin_lock_irqsave(&x->wait.lock, flags);
4694 x->done += UINT_MAX/2;
4695 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4696 spin_unlock_irqrestore(&x->wait.lock, flags);
4698 EXPORT_SYMBOL(complete_all);
4700 static inline long __sched
4701 do_wait_for_common(struct completion *x, long timeout, int state)
4703 if (!x->done) {
4704 DECLARE_WAITQUEUE(wait, current);
4706 wait.flags |= WQ_FLAG_EXCLUSIVE;
4707 __add_wait_queue_tail(&x->wait, &wait);
4708 do {
4709 if (signal_pending_state(state, current)) {
4710 timeout = -ERESTARTSYS;
4711 break;
4713 __set_current_state(state);
4714 spin_unlock_irq(&x->wait.lock);
4715 timeout = schedule_timeout(timeout);
4716 spin_lock_irq(&x->wait.lock);
4717 } while (!x->done && timeout);
4718 __remove_wait_queue(&x->wait, &wait);
4719 if (!x->done)
4720 return timeout;
4722 x->done--;
4723 return timeout ?: 1;
4726 static long __sched
4727 wait_for_common(struct completion *x, long timeout, int state)
4729 might_sleep();
4731 spin_lock_irq(&x->wait.lock);
4732 timeout = do_wait_for_common(x, timeout, state);
4733 spin_unlock_irq(&x->wait.lock);
4734 return timeout;
4738 * wait_for_completion: - waits for completion of a task
4739 * @x: holds the state of this particular completion
4741 * This waits to be signaled for completion of a specific task. It is NOT
4742 * interruptible and there is no timeout.
4744 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4745 * and interrupt capability. Also see complete().
4747 void __sched wait_for_completion(struct completion *x)
4749 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4751 EXPORT_SYMBOL(wait_for_completion);
4754 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4755 * @x: holds the state of this particular completion
4756 * @timeout: timeout value in jiffies
4758 * This waits for either a completion of a specific task to be signaled or for a
4759 * specified timeout to expire. The timeout is in jiffies. It is not
4760 * interruptible.
4762 unsigned long __sched
4763 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4765 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4767 EXPORT_SYMBOL(wait_for_completion_timeout);
4770 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4771 * @x: holds the state of this particular completion
4773 * This waits for completion of a specific task to be signaled. It is
4774 * interruptible.
4776 int __sched wait_for_completion_interruptible(struct completion *x)
4778 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4779 if (t == -ERESTARTSYS)
4780 return t;
4781 return 0;
4783 EXPORT_SYMBOL(wait_for_completion_interruptible);
4786 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4787 * @x: holds the state of this particular completion
4788 * @timeout: timeout value in jiffies
4790 * This waits for either a completion of a specific task to be signaled or for a
4791 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4793 unsigned long __sched
4794 wait_for_completion_interruptible_timeout(struct completion *x,
4795 unsigned long timeout)
4797 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4799 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4802 * wait_for_completion_killable: - waits for completion of a task (killable)
4803 * @x: holds the state of this particular completion
4805 * This waits to be signaled for completion of a specific task. It can be
4806 * interrupted by a kill signal.
4808 int __sched wait_for_completion_killable(struct completion *x)
4810 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4811 if (t == -ERESTARTSYS)
4812 return t;
4813 return 0;
4815 EXPORT_SYMBOL(wait_for_completion_killable);
4818 * try_wait_for_completion - try to decrement a completion without blocking
4819 * @x: completion structure
4821 * Returns: 0 if a decrement cannot be done without blocking
4822 * 1 if a decrement succeeded.
4824 * If a completion is being used as a counting completion,
4825 * attempt to decrement the counter without blocking. This
4826 * enables us to avoid waiting if the resource the completion
4827 * is protecting is not available.
4829 bool try_wait_for_completion(struct completion *x)
4831 int ret = 1;
4833 spin_lock_irq(&x->wait.lock);
4834 if (!x->done)
4835 ret = 0;
4836 else
4837 x->done--;
4838 spin_unlock_irq(&x->wait.lock);
4839 return ret;
4841 EXPORT_SYMBOL(try_wait_for_completion);
4844 * completion_done - Test to see if a completion has any waiters
4845 * @x: completion structure
4847 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4848 * 1 if there are no waiters.
4851 bool completion_done(struct completion *x)
4853 int ret = 1;
4855 spin_lock_irq(&x->wait.lock);
4856 if (!x->done)
4857 ret = 0;
4858 spin_unlock_irq(&x->wait.lock);
4859 return ret;
4861 EXPORT_SYMBOL(completion_done);
4863 static long __sched
4864 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4866 unsigned long flags;
4867 wait_queue_t wait;
4869 init_waitqueue_entry(&wait, current);
4871 __set_current_state(state);
4873 spin_lock_irqsave(&q->lock, flags);
4874 __add_wait_queue(q, &wait);
4875 spin_unlock(&q->lock);
4876 timeout = schedule_timeout(timeout);
4877 spin_lock_irq(&q->lock);
4878 __remove_wait_queue(q, &wait);
4879 spin_unlock_irqrestore(&q->lock, flags);
4881 return timeout;
4884 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4886 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4888 EXPORT_SYMBOL(interruptible_sleep_on);
4890 long __sched
4891 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4893 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4895 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4897 void __sched sleep_on(wait_queue_head_t *q)
4899 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4901 EXPORT_SYMBOL(sleep_on);
4903 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4905 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4907 EXPORT_SYMBOL(sleep_on_timeout);
4909 #ifdef CONFIG_RT_MUTEXES
4912 * rt_mutex_setprio - set the current priority of a task
4913 * @p: task
4914 * @prio: prio value (kernel-internal form)
4916 * This function changes the 'effective' priority of a task. It does
4917 * not touch ->normal_prio like __setscheduler().
4919 * Used by the rt_mutex code to implement priority inheritance logic.
4921 void rt_mutex_setprio(struct task_struct *p, int prio)
4923 unsigned long flags;
4924 int oldprio, on_rq, running;
4925 struct rq *rq;
4926 const struct sched_class *prev_class = p->sched_class;
4928 BUG_ON(prio < 0 || prio > MAX_PRIO);
4930 rq = task_rq_lock(p, &flags);
4931 update_rq_clock(rq);
4933 oldprio = p->prio;
4934 on_rq = p->se.on_rq;
4935 running = task_current(rq, p);
4936 if (on_rq)
4937 dequeue_task(rq, p, 0);
4938 if (running)
4939 p->sched_class->put_prev_task(rq, p);
4941 if (rt_prio(prio))
4942 p->sched_class = &rt_sched_class;
4943 else
4944 p->sched_class = &fair_sched_class;
4946 p->prio = prio;
4948 if (running)
4949 p->sched_class->set_curr_task(rq);
4950 if (on_rq) {
4951 enqueue_task(rq, p, 0);
4953 check_class_changed(rq, p, prev_class, oldprio, running);
4955 task_rq_unlock(rq, &flags);
4958 #endif
4960 void set_user_nice(struct task_struct *p, long nice)
4962 int old_prio, delta, on_rq;
4963 unsigned long flags;
4964 struct rq *rq;
4966 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4967 return;
4969 * We have to be careful, if called from sys_setpriority(),
4970 * the task might be in the middle of scheduling on another CPU.
4972 rq = task_rq_lock(p, &flags);
4973 update_rq_clock(rq);
4975 * The RT priorities are set via sched_setscheduler(), but we still
4976 * allow the 'normal' nice value to be set - but as expected
4977 * it wont have any effect on scheduling until the task is
4978 * SCHED_FIFO/SCHED_RR:
4980 if (task_has_rt_policy(p)) {
4981 p->static_prio = NICE_TO_PRIO(nice);
4982 goto out_unlock;
4984 on_rq = p->se.on_rq;
4985 if (on_rq)
4986 dequeue_task(rq, p, 0);
4988 p->static_prio = NICE_TO_PRIO(nice);
4989 set_load_weight(p);
4990 old_prio = p->prio;
4991 p->prio = effective_prio(p);
4992 delta = p->prio - old_prio;
4994 if (on_rq) {
4995 enqueue_task(rq, p, 0);
4997 * If the task increased its priority or is running and
4998 * lowered its priority, then reschedule its CPU:
5000 if (delta < 0 || (delta > 0 && task_running(rq, p)))
5001 resched_task(rq->curr);
5003 out_unlock:
5004 task_rq_unlock(rq, &flags);
5006 EXPORT_SYMBOL(set_user_nice);
5009 * can_nice - check if a task can reduce its nice value
5010 * @p: task
5011 * @nice: nice value
5013 int can_nice(const struct task_struct *p, const int nice)
5015 /* convert nice value [19,-20] to rlimit style value [1,40] */
5016 int nice_rlim = 20 - nice;
5018 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
5019 capable(CAP_SYS_NICE));
5022 #ifdef __ARCH_WANT_SYS_NICE
5025 * sys_nice - change the priority of the current process.
5026 * @increment: priority increment
5028 * sys_setpriority is a more generic, but much slower function that
5029 * does similar things.
5031 asmlinkage long sys_nice(int increment)
5033 long nice, retval;
5036 * Setpriority might change our priority at the same moment.
5037 * We don't have to worry. Conceptually one call occurs first
5038 * and we have a single winner.
5040 if (increment < -40)
5041 increment = -40;
5042 if (increment > 40)
5043 increment = 40;
5045 nice = PRIO_TO_NICE(current->static_prio) + increment;
5046 if (nice < -20)
5047 nice = -20;
5048 if (nice > 19)
5049 nice = 19;
5051 if (increment < 0 && !can_nice(current, nice))
5052 return -EPERM;
5054 retval = security_task_setnice(current, nice);
5055 if (retval)
5056 return retval;
5058 set_user_nice(current, nice);
5059 return 0;
5062 #endif
5065 * task_prio - return the priority value of a given task.
5066 * @p: the task in question.
5068 * This is the priority value as seen by users in /proc.
5069 * RT tasks are offset by -200. Normal tasks are centered
5070 * around 0, value goes from -16 to +15.
5072 int task_prio(const struct task_struct *p)
5074 return p->prio - MAX_RT_PRIO;
5078 * task_nice - return the nice value of a given task.
5079 * @p: the task in question.
5081 int task_nice(const struct task_struct *p)
5083 return TASK_NICE(p);
5085 EXPORT_SYMBOL(task_nice);
5088 * idle_cpu - is a given cpu idle currently?
5089 * @cpu: the processor in question.
5091 int idle_cpu(int cpu)
5093 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5097 * idle_task - return the idle task for a given cpu.
5098 * @cpu: the processor in question.
5100 struct task_struct *idle_task(int cpu)
5102 return cpu_rq(cpu)->idle;
5106 * find_process_by_pid - find a process with a matching PID value.
5107 * @pid: the pid in question.
5109 static struct task_struct *find_process_by_pid(pid_t pid)
5111 return pid ? find_task_by_vpid(pid) : current;
5114 /* Actually do priority change: must hold rq lock. */
5115 static void
5116 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5118 BUG_ON(p->se.on_rq);
5120 p->policy = policy;
5121 switch (p->policy) {
5122 case SCHED_NORMAL:
5123 case SCHED_BATCH:
5124 case SCHED_IDLE:
5125 p->sched_class = &fair_sched_class;
5126 break;
5127 case SCHED_FIFO:
5128 case SCHED_RR:
5129 p->sched_class = &rt_sched_class;
5130 break;
5133 p->rt_priority = prio;
5134 p->normal_prio = normal_prio(p);
5135 /* we are holding p->pi_lock already */
5136 p->prio = rt_mutex_getprio(p);
5137 set_load_weight(p);
5140 static int __sched_setscheduler(struct task_struct *p, int policy,
5141 struct sched_param *param, bool user)
5143 int retval, oldprio, oldpolicy = -1, on_rq, running;
5144 unsigned long flags;
5145 const struct sched_class *prev_class = p->sched_class;
5146 struct rq *rq;
5148 /* may grab non-irq protected spin_locks */
5149 BUG_ON(in_interrupt());
5150 recheck:
5151 /* double check policy once rq lock held */
5152 if (policy < 0)
5153 policy = oldpolicy = p->policy;
5154 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5155 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5156 policy != SCHED_IDLE)
5157 return -EINVAL;
5159 * Valid priorities for SCHED_FIFO and SCHED_RR are
5160 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5161 * SCHED_BATCH and SCHED_IDLE is 0.
5163 if (param->sched_priority < 0 ||
5164 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5165 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5166 return -EINVAL;
5167 if (rt_policy(policy) != (param->sched_priority != 0))
5168 return -EINVAL;
5171 * Allow unprivileged RT tasks to decrease priority:
5173 if (user && !capable(CAP_SYS_NICE)) {
5174 if (rt_policy(policy)) {
5175 unsigned long rlim_rtprio;
5177 if (!lock_task_sighand(p, &flags))
5178 return -ESRCH;
5179 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5180 unlock_task_sighand(p, &flags);
5182 /* can't set/change the rt policy */
5183 if (policy != p->policy && !rlim_rtprio)
5184 return -EPERM;
5186 /* can't increase priority */
5187 if (param->sched_priority > p->rt_priority &&
5188 param->sched_priority > rlim_rtprio)
5189 return -EPERM;
5192 * Like positive nice levels, dont allow tasks to
5193 * move out of SCHED_IDLE either:
5195 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5196 return -EPERM;
5198 /* can't change other user's priorities */
5199 if ((current->euid != p->euid) &&
5200 (current->euid != p->uid))
5201 return -EPERM;
5204 if (user) {
5205 #ifdef CONFIG_RT_GROUP_SCHED
5207 * Do not allow realtime tasks into groups that have no runtime
5208 * assigned.
5210 if (rt_bandwidth_enabled() && rt_policy(policy) &&
5211 task_group(p)->rt_bandwidth.rt_runtime == 0)
5212 return -EPERM;
5213 #endif
5215 retval = security_task_setscheduler(p, policy, param);
5216 if (retval)
5217 return retval;
5221 * make sure no PI-waiters arrive (or leave) while we are
5222 * changing the priority of the task:
5224 spin_lock_irqsave(&p->pi_lock, flags);
5226 * To be able to change p->policy safely, the apropriate
5227 * runqueue lock must be held.
5229 rq = __task_rq_lock(p);
5230 /* recheck policy now with rq lock held */
5231 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5232 policy = oldpolicy = -1;
5233 __task_rq_unlock(rq);
5234 spin_unlock_irqrestore(&p->pi_lock, flags);
5235 goto recheck;
5237 update_rq_clock(rq);
5238 on_rq = p->se.on_rq;
5239 running = task_current(rq, p);
5240 if (on_rq)
5241 deactivate_task(rq, p, 0);
5242 if (running)
5243 p->sched_class->put_prev_task(rq, p);
5245 oldprio = p->prio;
5246 __setscheduler(rq, p, policy, param->sched_priority);
5248 if (running)
5249 p->sched_class->set_curr_task(rq);
5250 if (on_rq) {
5251 activate_task(rq, p, 0);
5253 check_class_changed(rq, p, prev_class, oldprio, running);
5255 __task_rq_unlock(rq);
5256 spin_unlock_irqrestore(&p->pi_lock, flags);
5258 rt_mutex_adjust_pi(p);
5260 return 0;
5264 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5265 * @p: the task in question.
5266 * @policy: new policy.
5267 * @param: structure containing the new RT priority.
5269 * NOTE that the task may be already dead.
5271 int sched_setscheduler(struct task_struct *p, int policy,
5272 struct sched_param *param)
5274 return __sched_setscheduler(p, policy, param, true);
5276 EXPORT_SYMBOL_GPL(sched_setscheduler);
5279 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5280 * @p: the task in question.
5281 * @policy: new policy.
5282 * @param: structure containing the new RT priority.
5284 * Just like sched_setscheduler, only don't bother checking if the
5285 * current context has permission. For example, this is needed in
5286 * stop_machine(): we create temporary high priority worker threads,
5287 * but our caller might not have that capability.
5289 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5290 struct sched_param *param)
5292 return __sched_setscheduler(p, policy, param, false);
5295 static int
5296 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5298 struct sched_param lparam;
5299 struct task_struct *p;
5300 int retval;
5302 if (!param || pid < 0)
5303 return -EINVAL;
5304 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5305 return -EFAULT;
5307 rcu_read_lock();
5308 retval = -ESRCH;
5309 p = find_process_by_pid(pid);
5310 if (p != NULL)
5311 retval = sched_setscheduler(p, policy, &lparam);
5312 rcu_read_unlock();
5314 return retval;
5318 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5319 * @pid: the pid in question.
5320 * @policy: new policy.
5321 * @param: structure containing the new RT priority.
5323 asmlinkage long
5324 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5326 /* negative values for policy are not valid */
5327 if (policy < 0)
5328 return -EINVAL;
5330 return do_sched_setscheduler(pid, policy, param);
5334 * sys_sched_setparam - set/change the RT priority of a thread
5335 * @pid: the pid in question.
5336 * @param: structure containing the new RT priority.
5338 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5340 return do_sched_setscheduler(pid, -1, param);
5344 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5345 * @pid: the pid in question.
5347 asmlinkage long sys_sched_getscheduler(pid_t pid)
5349 struct task_struct *p;
5350 int retval;
5352 if (pid < 0)
5353 return -EINVAL;
5355 retval = -ESRCH;
5356 read_lock(&tasklist_lock);
5357 p = find_process_by_pid(pid);
5358 if (p) {
5359 retval = security_task_getscheduler(p);
5360 if (!retval)
5361 retval = p->policy;
5363 read_unlock(&tasklist_lock);
5364 return retval;
5368 * sys_sched_getscheduler - get the RT priority of a thread
5369 * @pid: the pid in question.
5370 * @param: structure containing the RT priority.
5372 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5374 struct sched_param lp;
5375 struct task_struct *p;
5376 int retval;
5378 if (!param || pid < 0)
5379 return -EINVAL;
5381 read_lock(&tasklist_lock);
5382 p = find_process_by_pid(pid);
5383 retval = -ESRCH;
5384 if (!p)
5385 goto out_unlock;
5387 retval = security_task_getscheduler(p);
5388 if (retval)
5389 goto out_unlock;
5391 lp.sched_priority = p->rt_priority;
5392 read_unlock(&tasklist_lock);
5395 * This one might sleep, we cannot do it with a spinlock held ...
5397 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5399 return retval;
5401 out_unlock:
5402 read_unlock(&tasklist_lock);
5403 return retval;
5406 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5408 cpumask_t cpus_allowed;
5409 cpumask_t new_mask = *in_mask;
5410 struct task_struct *p;
5411 int retval;
5413 get_online_cpus();
5414 read_lock(&tasklist_lock);
5416 p = find_process_by_pid(pid);
5417 if (!p) {
5418 read_unlock(&tasklist_lock);
5419 put_online_cpus();
5420 return -ESRCH;
5424 * It is not safe to call set_cpus_allowed with the
5425 * tasklist_lock held. We will bump the task_struct's
5426 * usage count and then drop tasklist_lock.
5428 get_task_struct(p);
5429 read_unlock(&tasklist_lock);
5431 retval = -EPERM;
5432 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5433 !capable(CAP_SYS_NICE))
5434 goto out_unlock;
5436 retval = security_task_setscheduler(p, 0, NULL);
5437 if (retval)
5438 goto out_unlock;
5440 cpuset_cpus_allowed(p, &cpus_allowed);
5441 cpus_and(new_mask, new_mask, cpus_allowed);
5442 again:
5443 retval = set_cpus_allowed_ptr(p, &new_mask);
5445 if (!retval) {
5446 cpuset_cpus_allowed(p, &cpus_allowed);
5447 if (!cpus_subset(new_mask, cpus_allowed)) {
5449 * We must have raced with a concurrent cpuset
5450 * update. Just reset the cpus_allowed to the
5451 * cpuset's cpus_allowed
5453 new_mask = cpus_allowed;
5454 goto again;
5457 out_unlock:
5458 put_task_struct(p);
5459 put_online_cpus();
5460 return retval;
5463 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5464 cpumask_t *new_mask)
5466 if (len < sizeof(cpumask_t)) {
5467 memset(new_mask, 0, sizeof(cpumask_t));
5468 } else if (len > sizeof(cpumask_t)) {
5469 len = sizeof(cpumask_t);
5471 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5475 * sys_sched_setaffinity - set the cpu affinity of a process
5476 * @pid: pid of the process
5477 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5478 * @user_mask_ptr: user-space pointer to the new cpu mask
5480 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5481 unsigned long __user *user_mask_ptr)
5483 cpumask_t new_mask;
5484 int retval;
5486 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5487 if (retval)
5488 return retval;
5490 return sched_setaffinity(pid, &new_mask);
5493 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5495 struct task_struct *p;
5496 int retval;
5498 get_online_cpus();
5499 read_lock(&tasklist_lock);
5501 retval = -ESRCH;
5502 p = find_process_by_pid(pid);
5503 if (!p)
5504 goto out_unlock;
5506 retval = security_task_getscheduler(p);
5507 if (retval)
5508 goto out_unlock;
5510 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5512 out_unlock:
5513 read_unlock(&tasklist_lock);
5514 put_online_cpus();
5516 return retval;
5520 * sys_sched_getaffinity - get the cpu affinity of a process
5521 * @pid: pid of the process
5522 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5523 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5525 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5526 unsigned long __user *user_mask_ptr)
5528 int ret;
5529 cpumask_t mask;
5531 if (len < sizeof(cpumask_t))
5532 return -EINVAL;
5534 ret = sched_getaffinity(pid, &mask);
5535 if (ret < 0)
5536 return ret;
5538 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5539 return -EFAULT;
5541 return sizeof(cpumask_t);
5545 * sys_sched_yield - yield the current processor to other threads.
5547 * This function yields the current CPU to other tasks. If there are no
5548 * other threads running on this CPU then this function will return.
5550 asmlinkage long sys_sched_yield(void)
5552 struct rq *rq = this_rq_lock();
5554 schedstat_inc(rq, yld_count);
5555 current->sched_class->yield_task(rq);
5558 * Since we are going to call schedule() anyway, there's
5559 * no need to preempt or enable interrupts:
5561 __release(rq->lock);
5562 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5563 _raw_spin_unlock(&rq->lock);
5564 preempt_enable_no_resched();
5566 schedule();
5568 return 0;
5571 static void __cond_resched(void)
5573 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5574 __might_sleep(__FILE__, __LINE__);
5575 #endif
5577 * The BKS might be reacquired before we have dropped
5578 * PREEMPT_ACTIVE, which could trigger a second
5579 * cond_resched() call.
5581 do {
5582 add_preempt_count(PREEMPT_ACTIVE);
5583 schedule();
5584 sub_preempt_count(PREEMPT_ACTIVE);
5585 } while (need_resched());
5588 int __sched _cond_resched(void)
5590 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5591 system_state == SYSTEM_RUNNING) {
5592 __cond_resched();
5593 return 1;
5595 return 0;
5597 EXPORT_SYMBOL(_cond_resched);
5600 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5601 * call schedule, and on return reacquire the lock.
5603 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5604 * operations here to prevent schedule() from being called twice (once via
5605 * spin_unlock(), once by hand).
5607 int cond_resched_lock(spinlock_t *lock)
5609 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5610 int ret = 0;
5612 if (spin_needbreak(lock) || resched) {
5613 spin_unlock(lock);
5614 if (resched && need_resched())
5615 __cond_resched();
5616 else
5617 cpu_relax();
5618 ret = 1;
5619 spin_lock(lock);
5621 return ret;
5623 EXPORT_SYMBOL(cond_resched_lock);
5625 int __sched cond_resched_softirq(void)
5627 BUG_ON(!in_softirq());
5629 if (need_resched() && system_state == SYSTEM_RUNNING) {
5630 local_bh_enable();
5631 __cond_resched();
5632 local_bh_disable();
5633 return 1;
5635 return 0;
5637 EXPORT_SYMBOL(cond_resched_softirq);
5640 * yield - yield the current processor to other threads.
5642 * This is a shortcut for kernel-space yielding - it marks the
5643 * thread runnable and calls sys_sched_yield().
5645 void __sched yield(void)
5647 set_current_state(TASK_RUNNING);
5648 sys_sched_yield();
5650 EXPORT_SYMBOL(yield);
5653 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5654 * that process accounting knows that this is a task in IO wait state.
5656 * But don't do that if it is a deliberate, throttling IO wait (this task
5657 * has set its backing_dev_info: the queue against which it should throttle)
5659 void __sched io_schedule(void)
5661 struct rq *rq = &__raw_get_cpu_var(runqueues);
5663 delayacct_blkio_start();
5664 atomic_inc(&rq->nr_iowait);
5665 schedule();
5666 atomic_dec(&rq->nr_iowait);
5667 delayacct_blkio_end();
5669 EXPORT_SYMBOL(io_schedule);
5671 long __sched io_schedule_timeout(long timeout)
5673 struct rq *rq = &__raw_get_cpu_var(runqueues);
5674 long ret;
5676 delayacct_blkio_start();
5677 atomic_inc(&rq->nr_iowait);
5678 ret = schedule_timeout(timeout);
5679 atomic_dec(&rq->nr_iowait);
5680 delayacct_blkio_end();
5681 return ret;
5685 * sys_sched_get_priority_max - return maximum RT priority.
5686 * @policy: scheduling class.
5688 * this syscall returns the maximum rt_priority that can be used
5689 * by a given scheduling class.
5691 asmlinkage long sys_sched_get_priority_max(int policy)
5693 int ret = -EINVAL;
5695 switch (policy) {
5696 case SCHED_FIFO:
5697 case SCHED_RR:
5698 ret = MAX_USER_RT_PRIO-1;
5699 break;
5700 case SCHED_NORMAL:
5701 case SCHED_BATCH:
5702 case SCHED_IDLE:
5703 ret = 0;
5704 break;
5706 return ret;
5710 * sys_sched_get_priority_min - return minimum RT priority.
5711 * @policy: scheduling class.
5713 * this syscall returns the minimum rt_priority that can be used
5714 * by a given scheduling class.
5716 asmlinkage long sys_sched_get_priority_min(int policy)
5718 int ret = -EINVAL;
5720 switch (policy) {
5721 case SCHED_FIFO:
5722 case SCHED_RR:
5723 ret = 1;
5724 break;
5725 case SCHED_NORMAL:
5726 case SCHED_BATCH:
5727 case SCHED_IDLE:
5728 ret = 0;
5730 return ret;
5734 * sys_sched_rr_get_interval - return the default timeslice of a process.
5735 * @pid: pid of the process.
5736 * @interval: userspace pointer to the timeslice value.
5738 * this syscall writes the default timeslice value of a given process
5739 * into the user-space timespec buffer. A value of '0' means infinity.
5741 asmlinkage
5742 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5744 struct task_struct *p;
5745 unsigned int time_slice;
5746 int retval;
5747 struct timespec t;
5749 if (pid < 0)
5750 return -EINVAL;
5752 retval = -ESRCH;
5753 read_lock(&tasklist_lock);
5754 p = find_process_by_pid(pid);
5755 if (!p)
5756 goto out_unlock;
5758 retval = security_task_getscheduler(p);
5759 if (retval)
5760 goto out_unlock;
5763 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5764 * tasks that are on an otherwise idle runqueue:
5766 time_slice = 0;
5767 if (p->policy == SCHED_RR) {
5768 time_slice = DEF_TIMESLICE;
5769 } else if (p->policy != SCHED_FIFO) {
5770 struct sched_entity *se = &p->se;
5771 unsigned long flags;
5772 struct rq *rq;
5774 rq = task_rq_lock(p, &flags);
5775 if (rq->cfs.load.weight)
5776 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5777 task_rq_unlock(rq, &flags);
5779 read_unlock(&tasklist_lock);
5780 jiffies_to_timespec(time_slice, &t);
5781 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5782 return retval;
5784 out_unlock:
5785 read_unlock(&tasklist_lock);
5786 return retval;
5789 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5791 void sched_show_task(struct task_struct *p)
5793 unsigned long free = 0;
5794 unsigned state;
5796 state = p->state ? __ffs(p->state) + 1 : 0;
5797 printk(KERN_INFO "%-13.13s %c", p->comm,
5798 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5799 #if BITS_PER_LONG == 32
5800 if (state == TASK_RUNNING)
5801 printk(KERN_CONT " running ");
5802 else
5803 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5804 #else
5805 if (state == TASK_RUNNING)
5806 printk(KERN_CONT " running task ");
5807 else
5808 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5809 #endif
5810 #ifdef CONFIG_DEBUG_STACK_USAGE
5812 unsigned long *n = end_of_stack(p);
5813 while (!*n)
5814 n++;
5815 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5817 #endif
5818 printk(KERN_CONT "%5lu %5d %6d\n", free,
5819 task_pid_nr(p), task_pid_nr(p->real_parent));
5821 show_stack(p, NULL);
5824 void show_state_filter(unsigned long state_filter)
5826 struct task_struct *g, *p;
5828 #if BITS_PER_LONG == 32
5829 printk(KERN_INFO
5830 " task PC stack pid father\n");
5831 #else
5832 printk(KERN_INFO
5833 " task PC stack pid father\n");
5834 #endif
5835 read_lock(&tasklist_lock);
5836 do_each_thread(g, p) {
5838 * reset the NMI-timeout, listing all files on a slow
5839 * console might take alot of time:
5841 touch_nmi_watchdog();
5842 if (!state_filter || (p->state & state_filter))
5843 sched_show_task(p);
5844 } while_each_thread(g, p);
5846 touch_all_softlockup_watchdogs();
5848 #ifdef CONFIG_SCHED_DEBUG
5849 sysrq_sched_debug_show();
5850 #endif
5851 read_unlock(&tasklist_lock);
5853 * Only show locks if all tasks are dumped:
5855 if (state_filter == -1)
5856 debug_show_all_locks();
5859 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5861 idle->sched_class = &idle_sched_class;
5865 * init_idle - set up an idle thread for a given CPU
5866 * @idle: task in question
5867 * @cpu: cpu the idle task belongs to
5869 * NOTE: this function does not set the idle thread's NEED_RESCHED
5870 * flag, to make booting more robust.
5872 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5874 struct rq *rq = cpu_rq(cpu);
5875 unsigned long flags;
5877 __sched_fork(idle);
5878 idle->se.exec_start = sched_clock();
5880 idle->prio = idle->normal_prio = MAX_PRIO;
5881 idle->cpus_allowed = cpumask_of_cpu(cpu);
5882 __set_task_cpu(idle, cpu);
5884 spin_lock_irqsave(&rq->lock, flags);
5885 rq->curr = rq->idle = idle;
5886 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5887 idle->oncpu = 1;
5888 #endif
5889 spin_unlock_irqrestore(&rq->lock, flags);
5891 /* Set the preempt count _outside_ the spinlocks! */
5892 #if defined(CONFIG_PREEMPT)
5893 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5894 #else
5895 task_thread_info(idle)->preempt_count = 0;
5896 #endif
5898 * The idle tasks have their own, simple scheduling class:
5900 idle->sched_class = &idle_sched_class;
5904 * In a system that switches off the HZ timer nohz_cpu_mask
5905 * indicates which cpus entered this state. This is used
5906 * in the rcu update to wait only for active cpus. For system
5907 * which do not switch off the HZ timer nohz_cpu_mask should
5908 * always be CPU_MASK_NONE.
5910 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5913 * Increase the granularity value when there are more CPUs,
5914 * because with more CPUs the 'effective latency' as visible
5915 * to users decreases. But the relationship is not linear,
5916 * so pick a second-best guess by going with the log2 of the
5917 * number of CPUs.
5919 * This idea comes from the SD scheduler of Con Kolivas:
5921 static inline void sched_init_granularity(void)
5923 unsigned int factor = 1 + ilog2(num_online_cpus());
5924 const unsigned long limit = 200000000;
5926 sysctl_sched_min_granularity *= factor;
5927 if (sysctl_sched_min_granularity > limit)
5928 sysctl_sched_min_granularity = limit;
5930 sysctl_sched_latency *= factor;
5931 if (sysctl_sched_latency > limit)
5932 sysctl_sched_latency = limit;
5934 sysctl_sched_wakeup_granularity *= factor;
5936 sysctl_sched_shares_ratelimit *= factor;
5939 #ifdef CONFIG_SMP
5941 * This is how migration works:
5943 * 1) we queue a struct migration_req structure in the source CPU's
5944 * runqueue and wake up that CPU's migration thread.
5945 * 2) we down() the locked semaphore => thread blocks.
5946 * 3) migration thread wakes up (implicitly it forces the migrated
5947 * thread off the CPU)
5948 * 4) it gets the migration request and checks whether the migrated
5949 * task is still in the wrong runqueue.
5950 * 5) if it's in the wrong runqueue then the migration thread removes
5951 * it and puts it into the right queue.
5952 * 6) migration thread up()s the semaphore.
5953 * 7) we wake up and the migration is done.
5957 * Change a given task's CPU affinity. Migrate the thread to a
5958 * proper CPU and schedule it away if the CPU it's executing on
5959 * is removed from the allowed bitmask.
5961 * NOTE: the caller must have a valid reference to the task, the
5962 * task must not exit() & deallocate itself prematurely. The
5963 * call is not atomic; no spinlocks may be held.
5965 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
5967 struct migration_req req;
5968 unsigned long flags;
5969 struct rq *rq;
5970 int ret = 0;
5972 rq = task_rq_lock(p, &flags);
5973 if (!cpus_intersects(*new_mask, cpu_online_map)) {
5974 ret = -EINVAL;
5975 goto out;
5978 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
5979 !cpus_equal(p->cpus_allowed, *new_mask))) {
5980 ret = -EINVAL;
5981 goto out;
5984 if (p->sched_class->set_cpus_allowed)
5985 p->sched_class->set_cpus_allowed(p, new_mask);
5986 else {
5987 p->cpus_allowed = *new_mask;
5988 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
5991 /* Can the task run on the task's current CPU? If so, we're done */
5992 if (cpu_isset(task_cpu(p), *new_mask))
5993 goto out;
5995 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
5996 /* Need help from migration thread: drop lock and wait. */
5997 task_rq_unlock(rq, &flags);
5998 wake_up_process(rq->migration_thread);
5999 wait_for_completion(&req.done);
6000 tlb_migrate_finish(p->mm);
6001 return 0;
6003 out:
6004 task_rq_unlock(rq, &flags);
6006 return ret;
6008 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6011 * Move (not current) task off this cpu, onto dest cpu. We're doing
6012 * this because either it can't run here any more (set_cpus_allowed()
6013 * away from this CPU, or CPU going down), or because we're
6014 * attempting to rebalance this task on exec (sched_exec).
6016 * So we race with normal scheduler movements, but that's OK, as long
6017 * as the task is no longer on this CPU.
6019 * Returns non-zero if task was successfully migrated.
6021 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6023 struct rq *rq_dest, *rq_src;
6024 int ret = 0, on_rq;
6026 if (unlikely(!cpu_active(dest_cpu)))
6027 return ret;
6029 rq_src = cpu_rq(src_cpu);
6030 rq_dest = cpu_rq(dest_cpu);
6032 double_rq_lock(rq_src, rq_dest);
6033 /* Already moved. */
6034 if (task_cpu(p) != src_cpu)
6035 goto done;
6036 /* Affinity changed (again). */
6037 if (!cpu_isset(dest_cpu, p->cpus_allowed))
6038 goto fail;
6040 on_rq = p->se.on_rq;
6041 if (on_rq)
6042 deactivate_task(rq_src, p, 0);
6044 set_task_cpu(p, dest_cpu);
6045 if (on_rq) {
6046 activate_task(rq_dest, p, 0);
6047 check_preempt_curr(rq_dest, p, 0);
6049 done:
6050 ret = 1;
6051 fail:
6052 double_rq_unlock(rq_src, rq_dest);
6053 return ret;
6057 * migration_thread - this is a highprio system thread that performs
6058 * thread migration by bumping thread off CPU then 'pushing' onto
6059 * another runqueue.
6061 static int migration_thread(void *data)
6063 int cpu = (long)data;
6064 struct rq *rq;
6066 rq = cpu_rq(cpu);
6067 BUG_ON(rq->migration_thread != current);
6069 set_current_state(TASK_INTERRUPTIBLE);
6070 while (!kthread_should_stop()) {
6071 struct migration_req *req;
6072 struct list_head *head;
6074 spin_lock_irq(&rq->lock);
6076 if (cpu_is_offline(cpu)) {
6077 spin_unlock_irq(&rq->lock);
6078 goto wait_to_die;
6081 if (rq->active_balance) {
6082 active_load_balance(rq, cpu);
6083 rq->active_balance = 0;
6086 head = &rq->migration_queue;
6088 if (list_empty(head)) {
6089 spin_unlock_irq(&rq->lock);
6090 schedule();
6091 set_current_state(TASK_INTERRUPTIBLE);
6092 continue;
6094 req = list_entry(head->next, struct migration_req, list);
6095 list_del_init(head->next);
6097 spin_unlock(&rq->lock);
6098 __migrate_task(req->task, cpu, req->dest_cpu);
6099 local_irq_enable();
6101 complete(&req->done);
6103 __set_current_state(TASK_RUNNING);
6104 return 0;
6106 wait_to_die:
6107 /* Wait for kthread_stop */
6108 set_current_state(TASK_INTERRUPTIBLE);
6109 while (!kthread_should_stop()) {
6110 schedule();
6111 set_current_state(TASK_INTERRUPTIBLE);
6113 __set_current_state(TASK_RUNNING);
6114 return 0;
6117 #ifdef CONFIG_HOTPLUG_CPU
6119 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6121 int ret;
6123 local_irq_disable();
6124 ret = __migrate_task(p, src_cpu, dest_cpu);
6125 local_irq_enable();
6126 return ret;
6130 * Figure out where task on dead CPU should go, use force if necessary.
6131 * NOTE: interrupts should be disabled by the caller
6133 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6135 unsigned long flags;
6136 cpumask_t mask;
6137 struct rq *rq;
6138 int dest_cpu;
6140 do {
6141 /* On same node? */
6142 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6143 cpus_and(mask, mask, p->cpus_allowed);
6144 dest_cpu = any_online_cpu(mask);
6146 /* On any allowed CPU? */
6147 if (dest_cpu >= nr_cpu_ids)
6148 dest_cpu = any_online_cpu(p->cpus_allowed);
6150 /* No more Mr. Nice Guy. */
6151 if (dest_cpu >= nr_cpu_ids) {
6152 cpumask_t cpus_allowed;
6154 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6156 * Try to stay on the same cpuset, where the
6157 * current cpuset may be a subset of all cpus.
6158 * The cpuset_cpus_allowed_locked() variant of
6159 * cpuset_cpus_allowed() will not block. It must be
6160 * called within calls to cpuset_lock/cpuset_unlock.
6162 rq = task_rq_lock(p, &flags);
6163 p->cpus_allowed = cpus_allowed;
6164 dest_cpu = any_online_cpu(p->cpus_allowed);
6165 task_rq_unlock(rq, &flags);
6168 * Don't tell them about moving exiting tasks or
6169 * kernel threads (both mm NULL), since they never
6170 * leave kernel.
6172 if (p->mm && printk_ratelimit()) {
6173 printk(KERN_INFO "process %d (%s) no "
6174 "longer affine to cpu%d\n",
6175 task_pid_nr(p), p->comm, dead_cpu);
6178 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6182 * While a dead CPU has no uninterruptible tasks queued at this point,
6183 * it might still have a nonzero ->nr_uninterruptible counter, because
6184 * for performance reasons the counter is not stricly tracking tasks to
6185 * their home CPUs. So we just add the counter to another CPU's counter,
6186 * to keep the global sum constant after CPU-down:
6188 static void migrate_nr_uninterruptible(struct rq *rq_src)
6190 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6191 unsigned long flags;
6193 local_irq_save(flags);
6194 double_rq_lock(rq_src, rq_dest);
6195 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6196 rq_src->nr_uninterruptible = 0;
6197 double_rq_unlock(rq_src, rq_dest);
6198 local_irq_restore(flags);
6201 /* Run through task list and migrate tasks from the dead cpu. */
6202 static void migrate_live_tasks(int src_cpu)
6204 struct task_struct *p, *t;
6206 read_lock(&tasklist_lock);
6208 do_each_thread(t, p) {
6209 if (p == current)
6210 continue;
6212 if (task_cpu(p) == src_cpu)
6213 move_task_off_dead_cpu(src_cpu, p);
6214 } while_each_thread(t, p);
6216 read_unlock(&tasklist_lock);
6220 * Schedules idle task to be the next runnable task on current CPU.
6221 * It does so by boosting its priority to highest possible.
6222 * Used by CPU offline code.
6224 void sched_idle_next(void)
6226 int this_cpu = smp_processor_id();
6227 struct rq *rq = cpu_rq(this_cpu);
6228 struct task_struct *p = rq->idle;
6229 unsigned long flags;
6231 /* cpu has to be offline */
6232 BUG_ON(cpu_online(this_cpu));
6235 * Strictly not necessary since rest of the CPUs are stopped by now
6236 * and interrupts disabled on the current cpu.
6238 spin_lock_irqsave(&rq->lock, flags);
6240 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6242 update_rq_clock(rq);
6243 activate_task(rq, p, 0);
6245 spin_unlock_irqrestore(&rq->lock, flags);
6249 * Ensures that the idle task is using init_mm right before its cpu goes
6250 * offline.
6252 void idle_task_exit(void)
6254 struct mm_struct *mm = current->active_mm;
6256 BUG_ON(cpu_online(smp_processor_id()));
6258 if (mm != &init_mm)
6259 switch_mm(mm, &init_mm, current);
6260 mmdrop(mm);
6263 /* called under rq->lock with disabled interrupts */
6264 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6266 struct rq *rq = cpu_rq(dead_cpu);
6268 /* Must be exiting, otherwise would be on tasklist. */
6269 BUG_ON(!p->exit_state);
6271 /* Cannot have done final schedule yet: would have vanished. */
6272 BUG_ON(p->state == TASK_DEAD);
6274 get_task_struct(p);
6277 * Drop lock around migration; if someone else moves it,
6278 * that's OK. No task can be added to this CPU, so iteration is
6279 * fine.
6281 spin_unlock_irq(&rq->lock);
6282 move_task_off_dead_cpu(dead_cpu, p);
6283 spin_lock_irq(&rq->lock);
6285 put_task_struct(p);
6288 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6289 static void migrate_dead_tasks(unsigned int dead_cpu)
6291 struct rq *rq = cpu_rq(dead_cpu);
6292 struct task_struct *next;
6294 for ( ; ; ) {
6295 if (!rq->nr_running)
6296 break;
6297 update_rq_clock(rq);
6298 next = pick_next_task(rq, rq->curr);
6299 if (!next)
6300 break;
6301 next->sched_class->put_prev_task(rq, next);
6302 migrate_dead(dead_cpu, next);
6306 #endif /* CONFIG_HOTPLUG_CPU */
6308 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6310 static struct ctl_table sd_ctl_dir[] = {
6312 .procname = "sched_domain",
6313 .mode = 0555,
6315 {0, },
6318 static struct ctl_table sd_ctl_root[] = {
6320 .ctl_name = CTL_KERN,
6321 .procname = "kernel",
6322 .mode = 0555,
6323 .child = sd_ctl_dir,
6325 {0, },
6328 static struct ctl_table *sd_alloc_ctl_entry(int n)
6330 struct ctl_table *entry =
6331 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6333 return entry;
6336 static void sd_free_ctl_entry(struct ctl_table **tablep)
6338 struct ctl_table *entry;
6341 * In the intermediate directories, both the child directory and
6342 * procname are dynamically allocated and could fail but the mode
6343 * will always be set. In the lowest directory the names are
6344 * static strings and all have proc handlers.
6346 for (entry = *tablep; entry->mode; entry++) {
6347 if (entry->child)
6348 sd_free_ctl_entry(&entry->child);
6349 if (entry->proc_handler == NULL)
6350 kfree(entry->procname);
6353 kfree(*tablep);
6354 *tablep = NULL;
6357 static void
6358 set_table_entry(struct ctl_table *entry,
6359 const char *procname, void *data, int maxlen,
6360 mode_t mode, proc_handler *proc_handler)
6362 entry->procname = procname;
6363 entry->data = data;
6364 entry->maxlen = maxlen;
6365 entry->mode = mode;
6366 entry->proc_handler = proc_handler;
6369 static struct ctl_table *
6370 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6372 struct ctl_table *table = sd_alloc_ctl_entry(13);
6374 if (table == NULL)
6375 return NULL;
6377 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6378 sizeof(long), 0644, proc_doulongvec_minmax);
6379 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6380 sizeof(long), 0644, proc_doulongvec_minmax);
6381 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6382 sizeof(int), 0644, proc_dointvec_minmax);
6383 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6384 sizeof(int), 0644, proc_dointvec_minmax);
6385 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6386 sizeof(int), 0644, proc_dointvec_minmax);
6387 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6388 sizeof(int), 0644, proc_dointvec_minmax);
6389 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6390 sizeof(int), 0644, proc_dointvec_minmax);
6391 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6392 sizeof(int), 0644, proc_dointvec_minmax);
6393 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6394 sizeof(int), 0644, proc_dointvec_minmax);
6395 set_table_entry(&table[9], "cache_nice_tries",
6396 &sd->cache_nice_tries,
6397 sizeof(int), 0644, proc_dointvec_minmax);
6398 set_table_entry(&table[10], "flags", &sd->flags,
6399 sizeof(int), 0644, proc_dointvec_minmax);
6400 set_table_entry(&table[11], "name", sd->name,
6401 CORENAME_MAX_SIZE, 0444, proc_dostring);
6402 /* &table[12] is terminator */
6404 return table;
6407 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6409 struct ctl_table *entry, *table;
6410 struct sched_domain *sd;
6411 int domain_num = 0, i;
6412 char buf[32];
6414 for_each_domain(cpu, sd)
6415 domain_num++;
6416 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6417 if (table == NULL)
6418 return NULL;
6420 i = 0;
6421 for_each_domain(cpu, sd) {
6422 snprintf(buf, 32, "domain%d", i);
6423 entry->procname = kstrdup(buf, GFP_KERNEL);
6424 entry->mode = 0555;
6425 entry->child = sd_alloc_ctl_domain_table(sd);
6426 entry++;
6427 i++;
6429 return table;
6432 static struct ctl_table_header *sd_sysctl_header;
6433 static void register_sched_domain_sysctl(void)
6435 int i, cpu_num = num_online_cpus();
6436 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6437 char buf[32];
6439 WARN_ON(sd_ctl_dir[0].child);
6440 sd_ctl_dir[0].child = entry;
6442 if (entry == NULL)
6443 return;
6445 for_each_online_cpu(i) {
6446 snprintf(buf, 32, "cpu%d", i);
6447 entry->procname = kstrdup(buf, GFP_KERNEL);
6448 entry->mode = 0555;
6449 entry->child = sd_alloc_ctl_cpu_table(i);
6450 entry++;
6453 WARN_ON(sd_sysctl_header);
6454 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6457 /* may be called multiple times per register */
6458 static void unregister_sched_domain_sysctl(void)
6460 if (sd_sysctl_header)
6461 unregister_sysctl_table(sd_sysctl_header);
6462 sd_sysctl_header = NULL;
6463 if (sd_ctl_dir[0].child)
6464 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6466 #else
6467 static void register_sched_domain_sysctl(void)
6470 static void unregister_sched_domain_sysctl(void)
6473 #endif
6475 static void set_rq_online(struct rq *rq)
6477 if (!rq->online) {
6478 const struct sched_class *class;
6480 cpu_set(rq->cpu, rq->rd->online);
6481 rq->online = 1;
6483 for_each_class(class) {
6484 if (class->rq_online)
6485 class->rq_online(rq);
6490 static void set_rq_offline(struct rq *rq)
6492 if (rq->online) {
6493 const struct sched_class *class;
6495 for_each_class(class) {
6496 if (class->rq_offline)
6497 class->rq_offline(rq);
6500 cpu_clear(rq->cpu, rq->rd->online);
6501 rq->online = 0;
6506 * migration_call - callback that gets triggered when a CPU is added.
6507 * Here we can start up the necessary migration thread for the new CPU.
6509 static int __cpuinit
6510 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6512 struct task_struct *p;
6513 int cpu = (long)hcpu;
6514 unsigned long flags;
6515 struct rq *rq;
6517 switch (action) {
6519 case CPU_UP_PREPARE:
6520 case CPU_UP_PREPARE_FROZEN:
6521 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6522 if (IS_ERR(p))
6523 return NOTIFY_BAD;
6524 kthread_bind(p, cpu);
6525 /* Must be high prio: stop_machine expects to yield to it. */
6526 rq = task_rq_lock(p, &flags);
6527 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6528 task_rq_unlock(rq, &flags);
6529 cpu_rq(cpu)->migration_thread = p;
6530 break;
6532 case CPU_ONLINE:
6533 case CPU_ONLINE_FROZEN:
6534 /* Strictly unnecessary, as first user will wake it. */
6535 wake_up_process(cpu_rq(cpu)->migration_thread);
6537 /* Update our root-domain */
6538 rq = cpu_rq(cpu);
6539 spin_lock_irqsave(&rq->lock, flags);
6540 if (rq->rd) {
6541 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6543 set_rq_online(rq);
6545 spin_unlock_irqrestore(&rq->lock, flags);
6546 break;
6548 #ifdef CONFIG_HOTPLUG_CPU
6549 case CPU_UP_CANCELED:
6550 case CPU_UP_CANCELED_FROZEN:
6551 if (!cpu_rq(cpu)->migration_thread)
6552 break;
6553 /* Unbind it from offline cpu so it can run. Fall thru. */
6554 kthread_bind(cpu_rq(cpu)->migration_thread,
6555 any_online_cpu(cpu_online_map));
6556 kthread_stop(cpu_rq(cpu)->migration_thread);
6557 cpu_rq(cpu)->migration_thread = NULL;
6558 break;
6560 case CPU_DEAD:
6561 case CPU_DEAD_FROZEN:
6562 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6563 migrate_live_tasks(cpu);
6564 rq = cpu_rq(cpu);
6565 kthread_stop(rq->migration_thread);
6566 rq->migration_thread = NULL;
6567 /* Idle task back to normal (off runqueue, low prio) */
6568 spin_lock_irq(&rq->lock);
6569 update_rq_clock(rq);
6570 deactivate_task(rq, rq->idle, 0);
6571 rq->idle->static_prio = MAX_PRIO;
6572 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6573 rq->idle->sched_class = &idle_sched_class;
6574 migrate_dead_tasks(cpu);
6575 spin_unlock_irq(&rq->lock);
6576 cpuset_unlock();
6577 migrate_nr_uninterruptible(rq);
6578 BUG_ON(rq->nr_running != 0);
6581 * No need to migrate the tasks: it was best-effort if
6582 * they didn't take sched_hotcpu_mutex. Just wake up
6583 * the requestors.
6585 spin_lock_irq(&rq->lock);
6586 while (!list_empty(&rq->migration_queue)) {
6587 struct migration_req *req;
6589 req = list_entry(rq->migration_queue.next,
6590 struct migration_req, list);
6591 list_del_init(&req->list);
6592 complete(&req->done);
6594 spin_unlock_irq(&rq->lock);
6595 break;
6597 case CPU_DYING:
6598 case CPU_DYING_FROZEN:
6599 /* Update our root-domain */
6600 rq = cpu_rq(cpu);
6601 spin_lock_irqsave(&rq->lock, flags);
6602 if (rq->rd) {
6603 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6604 set_rq_offline(rq);
6606 spin_unlock_irqrestore(&rq->lock, flags);
6607 break;
6608 #endif
6610 return NOTIFY_OK;
6613 /* Register at highest priority so that task migration (migrate_all_tasks)
6614 * happens before everything else.
6616 static struct notifier_block __cpuinitdata migration_notifier = {
6617 .notifier_call = migration_call,
6618 .priority = 10
6621 static int __init migration_init(void)
6623 void *cpu = (void *)(long)smp_processor_id();
6624 int err;
6626 /* Start one for the boot CPU: */
6627 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6628 BUG_ON(err == NOTIFY_BAD);
6629 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6630 register_cpu_notifier(&migration_notifier);
6632 return err;
6634 early_initcall(migration_init);
6635 #endif
6637 #ifdef CONFIG_SMP
6639 #ifdef CONFIG_SCHED_DEBUG
6641 static inline const char *sd_level_to_string(enum sched_domain_level lvl)
6643 switch (lvl) {
6644 case SD_LV_NONE:
6645 return "NONE";
6646 case SD_LV_SIBLING:
6647 return "SIBLING";
6648 case SD_LV_MC:
6649 return "MC";
6650 case SD_LV_CPU:
6651 return "CPU";
6652 case SD_LV_NODE:
6653 return "NODE";
6654 case SD_LV_ALLNODES:
6655 return "ALLNODES";
6656 case SD_LV_MAX:
6657 return "MAX";
6660 return "MAX";
6663 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6664 cpumask_t *groupmask)
6666 struct sched_group *group = sd->groups;
6667 char str[256];
6669 cpulist_scnprintf(str, sizeof(str), sd->span);
6670 cpus_clear(*groupmask);
6672 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6674 if (!(sd->flags & SD_LOAD_BALANCE)) {
6675 printk("does not load-balance\n");
6676 if (sd->parent)
6677 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6678 " has parent");
6679 return -1;
6682 printk(KERN_CONT "span %s level %s\n",
6683 str, sd_level_to_string(sd->level));
6685 if (!cpu_isset(cpu, sd->span)) {
6686 printk(KERN_ERR "ERROR: domain->span does not contain "
6687 "CPU%d\n", cpu);
6689 if (!cpu_isset(cpu, group->cpumask)) {
6690 printk(KERN_ERR "ERROR: domain->groups does not contain"
6691 " CPU%d\n", cpu);
6694 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6695 do {
6696 if (!group) {
6697 printk("\n");
6698 printk(KERN_ERR "ERROR: group is NULL\n");
6699 break;
6702 if (!group->__cpu_power) {
6703 printk(KERN_CONT "\n");
6704 printk(KERN_ERR "ERROR: domain->cpu_power not "
6705 "set\n");
6706 break;
6709 if (!cpus_weight(group->cpumask)) {
6710 printk(KERN_CONT "\n");
6711 printk(KERN_ERR "ERROR: empty group\n");
6712 break;
6715 if (cpus_intersects(*groupmask, group->cpumask)) {
6716 printk(KERN_CONT "\n");
6717 printk(KERN_ERR "ERROR: repeated CPUs\n");
6718 break;
6721 cpus_or(*groupmask, *groupmask, group->cpumask);
6723 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6724 printk(KERN_CONT " %s", str);
6726 group = group->next;
6727 } while (group != sd->groups);
6728 printk(KERN_CONT "\n");
6730 if (!cpus_equal(sd->span, *groupmask))
6731 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6733 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6734 printk(KERN_ERR "ERROR: parent span is not a superset "
6735 "of domain->span\n");
6736 return 0;
6739 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6741 cpumask_t *groupmask;
6742 int level = 0;
6744 if (!sd) {
6745 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6746 return;
6749 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6751 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6752 if (!groupmask) {
6753 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6754 return;
6757 for (;;) {
6758 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6759 break;
6760 level++;
6761 sd = sd->parent;
6762 if (!sd)
6763 break;
6765 kfree(groupmask);
6767 #else /* !CONFIG_SCHED_DEBUG */
6768 # define sched_domain_debug(sd, cpu) do { } while (0)
6769 #endif /* CONFIG_SCHED_DEBUG */
6771 static int sd_degenerate(struct sched_domain *sd)
6773 if (cpus_weight(sd->span) == 1)
6774 return 1;
6776 /* Following flags need at least 2 groups */
6777 if (sd->flags & (SD_LOAD_BALANCE |
6778 SD_BALANCE_NEWIDLE |
6779 SD_BALANCE_FORK |
6780 SD_BALANCE_EXEC |
6781 SD_SHARE_CPUPOWER |
6782 SD_SHARE_PKG_RESOURCES)) {
6783 if (sd->groups != sd->groups->next)
6784 return 0;
6787 /* Following flags don't use groups */
6788 if (sd->flags & (SD_WAKE_IDLE |
6789 SD_WAKE_AFFINE |
6790 SD_WAKE_BALANCE))
6791 return 0;
6793 return 1;
6796 static int
6797 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6799 unsigned long cflags = sd->flags, pflags = parent->flags;
6801 if (sd_degenerate(parent))
6802 return 1;
6804 if (!cpus_equal(sd->span, parent->span))
6805 return 0;
6807 /* Does parent contain flags not in child? */
6808 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6809 if (cflags & SD_WAKE_AFFINE)
6810 pflags &= ~SD_WAKE_BALANCE;
6811 /* Flags needing groups don't count if only 1 group in parent */
6812 if (parent->groups == parent->groups->next) {
6813 pflags &= ~(SD_LOAD_BALANCE |
6814 SD_BALANCE_NEWIDLE |
6815 SD_BALANCE_FORK |
6816 SD_BALANCE_EXEC |
6817 SD_SHARE_CPUPOWER |
6818 SD_SHARE_PKG_RESOURCES);
6820 if (~cflags & pflags)
6821 return 0;
6823 return 1;
6826 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6828 unsigned long flags;
6830 spin_lock_irqsave(&rq->lock, flags);
6832 if (rq->rd) {
6833 struct root_domain *old_rd = rq->rd;
6835 if (cpu_isset(rq->cpu, old_rd->online))
6836 set_rq_offline(rq);
6838 cpu_clear(rq->cpu, old_rd->span);
6840 if (atomic_dec_and_test(&old_rd->refcount))
6841 kfree(old_rd);
6844 atomic_inc(&rd->refcount);
6845 rq->rd = rd;
6847 cpu_set(rq->cpu, rd->span);
6848 if (cpu_isset(rq->cpu, cpu_online_map))
6849 set_rq_online(rq);
6851 spin_unlock_irqrestore(&rq->lock, flags);
6854 static void init_rootdomain(struct root_domain *rd)
6856 memset(rd, 0, sizeof(*rd));
6858 cpus_clear(rd->span);
6859 cpus_clear(rd->online);
6861 cpupri_init(&rd->cpupri);
6864 static void init_defrootdomain(void)
6866 init_rootdomain(&def_root_domain);
6867 atomic_set(&def_root_domain.refcount, 1);
6870 static struct root_domain *alloc_rootdomain(void)
6872 struct root_domain *rd;
6874 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6875 if (!rd)
6876 return NULL;
6878 init_rootdomain(rd);
6880 return rd;
6884 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6885 * hold the hotplug lock.
6887 static void
6888 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6890 struct rq *rq = cpu_rq(cpu);
6891 struct sched_domain *tmp;
6893 /* Remove the sched domains which do not contribute to scheduling. */
6894 for (tmp = sd; tmp; ) {
6895 struct sched_domain *parent = tmp->parent;
6896 if (!parent)
6897 break;
6899 if (sd_parent_degenerate(tmp, parent)) {
6900 tmp->parent = parent->parent;
6901 if (parent->parent)
6902 parent->parent->child = tmp;
6903 } else
6904 tmp = tmp->parent;
6907 if (sd && sd_degenerate(sd)) {
6908 sd = sd->parent;
6909 if (sd)
6910 sd->child = NULL;
6913 sched_domain_debug(sd, cpu);
6915 rq_attach_root(rq, rd);
6916 rcu_assign_pointer(rq->sd, sd);
6919 /* cpus with isolated domains */
6920 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6922 /* Setup the mask of cpus configured for isolated domains */
6923 static int __init isolated_cpu_setup(char *str)
6925 static int __initdata ints[NR_CPUS];
6926 int i;
6928 str = get_options(str, ARRAY_SIZE(ints), ints);
6929 cpus_clear(cpu_isolated_map);
6930 for (i = 1; i <= ints[0]; i++)
6931 if (ints[i] < NR_CPUS)
6932 cpu_set(ints[i], cpu_isolated_map);
6933 return 1;
6936 __setup("isolcpus=", isolated_cpu_setup);
6939 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6940 * to a function which identifies what group(along with sched group) a CPU
6941 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6942 * (due to the fact that we keep track of groups covered with a cpumask_t).
6944 * init_sched_build_groups will build a circular linked list of the groups
6945 * covered by the given span, and will set each group's ->cpumask correctly,
6946 * and ->cpu_power to 0.
6948 static void
6949 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6950 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6951 struct sched_group **sg,
6952 cpumask_t *tmpmask),
6953 cpumask_t *covered, cpumask_t *tmpmask)
6955 struct sched_group *first = NULL, *last = NULL;
6956 int i;
6958 cpus_clear(*covered);
6960 for_each_cpu_mask_nr(i, *span) {
6961 struct sched_group *sg;
6962 int group = group_fn(i, cpu_map, &sg, tmpmask);
6963 int j;
6965 if (cpu_isset(i, *covered))
6966 continue;
6968 cpus_clear(sg->cpumask);
6969 sg->__cpu_power = 0;
6971 for_each_cpu_mask_nr(j, *span) {
6972 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6973 continue;
6975 cpu_set(j, *covered);
6976 cpu_set(j, sg->cpumask);
6978 if (!first)
6979 first = sg;
6980 if (last)
6981 last->next = sg;
6982 last = sg;
6984 last->next = first;
6987 #define SD_NODES_PER_DOMAIN 16
6989 #ifdef CONFIG_NUMA
6992 * find_next_best_node - find the next node to include in a sched_domain
6993 * @node: node whose sched_domain we're building
6994 * @used_nodes: nodes already in the sched_domain
6996 * Find the next node to include in a given scheduling domain. Simply
6997 * finds the closest node not already in the @used_nodes map.
6999 * Should use nodemask_t.
7001 static int find_next_best_node(int node, nodemask_t *used_nodes)
7003 int i, n, val, min_val, best_node = 0;
7005 min_val = INT_MAX;
7007 for (i = 0; i < nr_node_ids; i++) {
7008 /* Start at @node */
7009 n = (node + i) % nr_node_ids;
7011 if (!nr_cpus_node(n))
7012 continue;
7014 /* Skip already used nodes */
7015 if (node_isset(n, *used_nodes))
7016 continue;
7018 /* Simple min distance search */
7019 val = node_distance(node, n);
7021 if (val < min_val) {
7022 min_val = val;
7023 best_node = n;
7027 node_set(best_node, *used_nodes);
7028 return best_node;
7032 * sched_domain_node_span - get a cpumask for a node's sched_domain
7033 * @node: node whose cpumask we're constructing
7034 * @span: resulting cpumask
7036 * Given a node, construct a good cpumask for its sched_domain to span. It
7037 * should be one that prevents unnecessary balancing, but also spreads tasks
7038 * out optimally.
7040 static void sched_domain_node_span(int node, cpumask_t *span)
7042 nodemask_t used_nodes;
7043 node_to_cpumask_ptr(nodemask, node);
7044 int i;
7046 cpus_clear(*span);
7047 nodes_clear(used_nodes);
7049 cpus_or(*span, *span, *nodemask);
7050 node_set(node, used_nodes);
7052 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7053 int next_node = find_next_best_node(node, &used_nodes);
7055 node_to_cpumask_ptr_next(nodemask, next_node);
7056 cpus_or(*span, *span, *nodemask);
7059 #endif /* CONFIG_NUMA */
7061 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7064 * SMT sched-domains:
7066 #ifdef CONFIG_SCHED_SMT
7067 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
7068 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
7070 static int
7071 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7072 cpumask_t *unused)
7074 if (sg)
7075 *sg = &per_cpu(sched_group_cpus, cpu);
7076 return cpu;
7078 #endif /* CONFIG_SCHED_SMT */
7081 * multi-core sched-domains:
7083 #ifdef CONFIG_SCHED_MC
7084 static DEFINE_PER_CPU(struct sched_domain, core_domains);
7085 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
7086 #endif /* CONFIG_SCHED_MC */
7088 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
7089 static int
7090 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7091 cpumask_t *mask)
7093 int group;
7095 *mask = per_cpu(cpu_sibling_map, cpu);
7096 cpus_and(*mask, *mask, *cpu_map);
7097 group = first_cpu(*mask);
7098 if (sg)
7099 *sg = &per_cpu(sched_group_core, group);
7100 return group;
7102 #elif defined(CONFIG_SCHED_MC)
7103 static int
7104 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7105 cpumask_t *unused)
7107 if (sg)
7108 *sg = &per_cpu(sched_group_core, cpu);
7109 return cpu;
7111 #endif
7113 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7114 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7116 static int
7117 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7118 cpumask_t *mask)
7120 int group;
7121 #ifdef CONFIG_SCHED_MC
7122 *mask = cpu_coregroup_map(cpu);
7123 cpus_and(*mask, *mask, *cpu_map);
7124 group = first_cpu(*mask);
7125 #elif defined(CONFIG_SCHED_SMT)
7126 *mask = per_cpu(cpu_sibling_map, cpu);
7127 cpus_and(*mask, *mask, *cpu_map);
7128 group = first_cpu(*mask);
7129 #else
7130 group = cpu;
7131 #endif
7132 if (sg)
7133 *sg = &per_cpu(sched_group_phys, group);
7134 return group;
7137 #ifdef CONFIG_NUMA
7139 * The init_sched_build_groups can't handle what we want to do with node
7140 * groups, so roll our own. Now each node has its own list of groups which
7141 * gets dynamically allocated.
7143 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7144 static struct sched_group ***sched_group_nodes_bycpu;
7146 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7147 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7149 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7150 struct sched_group **sg, cpumask_t *nodemask)
7152 int group;
7154 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7155 cpus_and(*nodemask, *nodemask, *cpu_map);
7156 group = first_cpu(*nodemask);
7158 if (sg)
7159 *sg = &per_cpu(sched_group_allnodes, group);
7160 return group;
7163 static void init_numa_sched_groups_power(struct sched_group *group_head)
7165 struct sched_group *sg = group_head;
7166 int j;
7168 if (!sg)
7169 return;
7170 do {
7171 for_each_cpu_mask_nr(j, sg->cpumask) {
7172 struct sched_domain *sd;
7174 sd = &per_cpu(phys_domains, j);
7175 if (j != first_cpu(sd->groups->cpumask)) {
7177 * Only add "power" once for each
7178 * physical package.
7180 continue;
7183 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7185 sg = sg->next;
7186 } while (sg != group_head);
7188 #endif /* CONFIG_NUMA */
7190 #ifdef CONFIG_NUMA
7191 /* Free memory allocated for various sched_group structures */
7192 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7194 int cpu, i;
7196 for_each_cpu_mask_nr(cpu, *cpu_map) {
7197 struct sched_group **sched_group_nodes
7198 = sched_group_nodes_bycpu[cpu];
7200 if (!sched_group_nodes)
7201 continue;
7203 for (i = 0; i < nr_node_ids; i++) {
7204 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7206 *nodemask = node_to_cpumask(i);
7207 cpus_and(*nodemask, *nodemask, *cpu_map);
7208 if (cpus_empty(*nodemask))
7209 continue;
7211 if (sg == NULL)
7212 continue;
7213 sg = sg->next;
7214 next_sg:
7215 oldsg = sg;
7216 sg = sg->next;
7217 kfree(oldsg);
7218 if (oldsg != sched_group_nodes[i])
7219 goto next_sg;
7221 kfree(sched_group_nodes);
7222 sched_group_nodes_bycpu[cpu] = NULL;
7225 #else /* !CONFIG_NUMA */
7226 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7229 #endif /* CONFIG_NUMA */
7232 * Initialize sched groups cpu_power.
7234 * cpu_power indicates the capacity of sched group, which is used while
7235 * distributing the load between different sched groups in a sched domain.
7236 * Typically cpu_power for all the groups in a sched domain will be same unless
7237 * there are asymmetries in the topology. If there are asymmetries, group
7238 * having more cpu_power will pickup more load compared to the group having
7239 * less cpu_power.
7241 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7242 * the maximum number of tasks a group can handle in the presence of other idle
7243 * or lightly loaded groups in the same sched domain.
7245 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7247 struct sched_domain *child;
7248 struct sched_group *group;
7250 WARN_ON(!sd || !sd->groups);
7252 if (cpu != first_cpu(sd->groups->cpumask))
7253 return;
7255 child = sd->child;
7257 sd->groups->__cpu_power = 0;
7260 * For perf policy, if the groups in child domain share resources
7261 * (for example cores sharing some portions of the cache hierarchy
7262 * or SMT), then set this domain groups cpu_power such that each group
7263 * can handle only one task, when there are other idle groups in the
7264 * same sched domain.
7266 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7267 (child->flags &
7268 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7269 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7270 return;
7274 * add cpu_power of each child group to this groups cpu_power
7276 group = child->groups;
7277 do {
7278 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7279 group = group->next;
7280 } while (group != child->groups);
7284 * Initializers for schedule domains
7285 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7288 #ifdef CONFIG_SCHED_DEBUG
7289 # define SD_INIT_NAME(sd, type) sd->name = #type
7290 #else
7291 # define SD_INIT_NAME(sd, type) do { } while (0)
7292 #endif
7294 #define SD_INIT(sd, type) sd_init_##type(sd)
7296 #define SD_INIT_FUNC(type) \
7297 static noinline void sd_init_##type(struct sched_domain *sd) \
7299 memset(sd, 0, sizeof(*sd)); \
7300 *sd = SD_##type##_INIT; \
7301 sd->level = SD_LV_##type; \
7302 SD_INIT_NAME(sd, type); \
7305 SD_INIT_FUNC(CPU)
7306 #ifdef CONFIG_NUMA
7307 SD_INIT_FUNC(ALLNODES)
7308 SD_INIT_FUNC(NODE)
7309 #endif
7310 #ifdef CONFIG_SCHED_SMT
7311 SD_INIT_FUNC(SIBLING)
7312 #endif
7313 #ifdef CONFIG_SCHED_MC
7314 SD_INIT_FUNC(MC)
7315 #endif
7318 * To minimize stack usage kmalloc room for cpumasks and share the
7319 * space as the usage in build_sched_domains() dictates. Used only
7320 * if the amount of space is significant.
7322 struct allmasks {
7323 cpumask_t tmpmask; /* make this one first */
7324 union {
7325 cpumask_t nodemask;
7326 cpumask_t this_sibling_map;
7327 cpumask_t this_core_map;
7329 cpumask_t send_covered;
7331 #ifdef CONFIG_NUMA
7332 cpumask_t domainspan;
7333 cpumask_t covered;
7334 cpumask_t notcovered;
7335 #endif
7338 #if NR_CPUS > 128
7339 #define SCHED_CPUMASK_ALLOC 1
7340 #define SCHED_CPUMASK_FREE(v) kfree(v)
7341 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7342 #else
7343 #define SCHED_CPUMASK_ALLOC 0
7344 #define SCHED_CPUMASK_FREE(v)
7345 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7346 #endif
7348 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7349 ((unsigned long)(a) + offsetof(struct allmasks, v))
7351 static int default_relax_domain_level = -1;
7353 static int __init setup_relax_domain_level(char *str)
7355 unsigned long val;
7357 val = simple_strtoul(str, NULL, 0);
7358 if (val < SD_LV_MAX)
7359 default_relax_domain_level = val;
7361 return 1;
7363 __setup("relax_domain_level=", setup_relax_domain_level);
7365 static void set_domain_attribute(struct sched_domain *sd,
7366 struct sched_domain_attr *attr)
7368 int request;
7370 if (!attr || attr->relax_domain_level < 0) {
7371 if (default_relax_domain_level < 0)
7372 return;
7373 else
7374 request = default_relax_domain_level;
7375 } else
7376 request = attr->relax_domain_level;
7377 if (request < sd->level) {
7378 /* turn off idle balance on this domain */
7379 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7380 } else {
7381 /* turn on idle balance on this domain */
7382 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7387 * Build sched domains for a given set of cpus and attach the sched domains
7388 * to the individual cpus
7390 static int __build_sched_domains(const cpumask_t *cpu_map,
7391 struct sched_domain_attr *attr)
7393 int i;
7394 struct root_domain *rd;
7395 SCHED_CPUMASK_DECLARE(allmasks);
7396 cpumask_t *tmpmask;
7397 #ifdef CONFIG_NUMA
7398 struct sched_group **sched_group_nodes = NULL;
7399 int sd_allnodes = 0;
7402 * Allocate the per-node list of sched groups
7404 sched_group_nodes = kcalloc(nr_node_ids, sizeof(struct sched_group *),
7405 GFP_KERNEL);
7406 if (!sched_group_nodes) {
7407 printk(KERN_WARNING "Can not alloc sched group node list\n");
7408 return -ENOMEM;
7410 #endif
7412 rd = alloc_rootdomain();
7413 if (!rd) {
7414 printk(KERN_WARNING "Cannot alloc root domain\n");
7415 #ifdef CONFIG_NUMA
7416 kfree(sched_group_nodes);
7417 #endif
7418 return -ENOMEM;
7421 #if SCHED_CPUMASK_ALLOC
7422 /* get space for all scratch cpumask variables */
7423 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7424 if (!allmasks) {
7425 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7426 kfree(rd);
7427 #ifdef CONFIG_NUMA
7428 kfree(sched_group_nodes);
7429 #endif
7430 return -ENOMEM;
7432 #endif
7433 tmpmask = (cpumask_t *)allmasks;
7436 #ifdef CONFIG_NUMA
7437 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7438 #endif
7441 * Set up domains for cpus specified by the cpu_map.
7443 for_each_cpu_mask_nr(i, *cpu_map) {
7444 struct sched_domain *sd = NULL, *p;
7445 SCHED_CPUMASK_VAR(nodemask, allmasks);
7447 *nodemask = node_to_cpumask(cpu_to_node(i));
7448 cpus_and(*nodemask, *nodemask, *cpu_map);
7450 #ifdef CONFIG_NUMA
7451 if (cpus_weight(*cpu_map) >
7452 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7453 sd = &per_cpu(allnodes_domains, i);
7454 SD_INIT(sd, ALLNODES);
7455 set_domain_attribute(sd, attr);
7456 sd->span = *cpu_map;
7457 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7458 p = sd;
7459 sd_allnodes = 1;
7460 } else
7461 p = NULL;
7463 sd = &per_cpu(node_domains, i);
7464 SD_INIT(sd, NODE);
7465 set_domain_attribute(sd, attr);
7466 sched_domain_node_span(cpu_to_node(i), &sd->span);
7467 sd->parent = p;
7468 if (p)
7469 p->child = sd;
7470 cpus_and(sd->span, sd->span, *cpu_map);
7471 #endif
7473 p = sd;
7474 sd = &per_cpu(phys_domains, i);
7475 SD_INIT(sd, CPU);
7476 set_domain_attribute(sd, attr);
7477 sd->span = *nodemask;
7478 sd->parent = p;
7479 if (p)
7480 p->child = sd;
7481 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7483 #ifdef CONFIG_SCHED_MC
7484 p = sd;
7485 sd = &per_cpu(core_domains, i);
7486 SD_INIT(sd, MC);
7487 set_domain_attribute(sd, attr);
7488 sd->span = cpu_coregroup_map(i);
7489 cpus_and(sd->span, sd->span, *cpu_map);
7490 sd->parent = p;
7491 p->child = sd;
7492 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7493 #endif
7495 #ifdef CONFIG_SCHED_SMT
7496 p = sd;
7497 sd = &per_cpu(cpu_domains, i);
7498 SD_INIT(sd, SIBLING);
7499 set_domain_attribute(sd, attr);
7500 sd->span = per_cpu(cpu_sibling_map, i);
7501 cpus_and(sd->span, sd->span, *cpu_map);
7502 sd->parent = p;
7503 p->child = sd;
7504 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7505 #endif
7508 #ifdef CONFIG_SCHED_SMT
7509 /* Set up CPU (sibling) groups */
7510 for_each_cpu_mask_nr(i, *cpu_map) {
7511 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7512 SCHED_CPUMASK_VAR(send_covered, allmasks);
7514 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7515 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7516 if (i != first_cpu(*this_sibling_map))
7517 continue;
7519 init_sched_build_groups(this_sibling_map, cpu_map,
7520 &cpu_to_cpu_group,
7521 send_covered, tmpmask);
7523 #endif
7525 #ifdef CONFIG_SCHED_MC
7526 /* Set up multi-core groups */
7527 for_each_cpu_mask_nr(i, *cpu_map) {
7528 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7529 SCHED_CPUMASK_VAR(send_covered, allmasks);
7531 *this_core_map = cpu_coregroup_map(i);
7532 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7533 if (i != first_cpu(*this_core_map))
7534 continue;
7536 init_sched_build_groups(this_core_map, cpu_map,
7537 &cpu_to_core_group,
7538 send_covered, tmpmask);
7540 #endif
7542 /* Set up physical groups */
7543 for (i = 0; i < nr_node_ids; i++) {
7544 SCHED_CPUMASK_VAR(nodemask, allmasks);
7545 SCHED_CPUMASK_VAR(send_covered, allmasks);
7547 *nodemask = node_to_cpumask(i);
7548 cpus_and(*nodemask, *nodemask, *cpu_map);
7549 if (cpus_empty(*nodemask))
7550 continue;
7552 init_sched_build_groups(nodemask, cpu_map,
7553 &cpu_to_phys_group,
7554 send_covered, tmpmask);
7557 #ifdef CONFIG_NUMA
7558 /* Set up node groups */
7559 if (sd_allnodes) {
7560 SCHED_CPUMASK_VAR(send_covered, allmasks);
7562 init_sched_build_groups(cpu_map, cpu_map,
7563 &cpu_to_allnodes_group,
7564 send_covered, tmpmask);
7567 for (i = 0; i < nr_node_ids; i++) {
7568 /* Set up node groups */
7569 struct sched_group *sg, *prev;
7570 SCHED_CPUMASK_VAR(nodemask, allmasks);
7571 SCHED_CPUMASK_VAR(domainspan, allmasks);
7572 SCHED_CPUMASK_VAR(covered, allmasks);
7573 int j;
7575 *nodemask = node_to_cpumask(i);
7576 cpus_clear(*covered);
7578 cpus_and(*nodemask, *nodemask, *cpu_map);
7579 if (cpus_empty(*nodemask)) {
7580 sched_group_nodes[i] = NULL;
7581 continue;
7584 sched_domain_node_span(i, domainspan);
7585 cpus_and(*domainspan, *domainspan, *cpu_map);
7587 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7588 if (!sg) {
7589 printk(KERN_WARNING "Can not alloc domain group for "
7590 "node %d\n", i);
7591 goto error;
7593 sched_group_nodes[i] = sg;
7594 for_each_cpu_mask_nr(j, *nodemask) {
7595 struct sched_domain *sd;
7597 sd = &per_cpu(node_domains, j);
7598 sd->groups = sg;
7600 sg->__cpu_power = 0;
7601 sg->cpumask = *nodemask;
7602 sg->next = sg;
7603 cpus_or(*covered, *covered, *nodemask);
7604 prev = sg;
7606 for (j = 0; j < nr_node_ids; j++) {
7607 SCHED_CPUMASK_VAR(notcovered, allmasks);
7608 int n = (i + j) % nr_node_ids;
7609 node_to_cpumask_ptr(pnodemask, n);
7611 cpus_complement(*notcovered, *covered);
7612 cpus_and(*tmpmask, *notcovered, *cpu_map);
7613 cpus_and(*tmpmask, *tmpmask, *domainspan);
7614 if (cpus_empty(*tmpmask))
7615 break;
7617 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7618 if (cpus_empty(*tmpmask))
7619 continue;
7621 sg = kmalloc_node(sizeof(struct sched_group),
7622 GFP_KERNEL, i);
7623 if (!sg) {
7624 printk(KERN_WARNING
7625 "Can not alloc domain group for node %d\n", j);
7626 goto error;
7628 sg->__cpu_power = 0;
7629 sg->cpumask = *tmpmask;
7630 sg->next = prev->next;
7631 cpus_or(*covered, *covered, *tmpmask);
7632 prev->next = sg;
7633 prev = sg;
7636 #endif
7638 /* Calculate CPU power for physical packages and nodes */
7639 #ifdef CONFIG_SCHED_SMT
7640 for_each_cpu_mask_nr(i, *cpu_map) {
7641 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7643 init_sched_groups_power(i, sd);
7645 #endif
7646 #ifdef CONFIG_SCHED_MC
7647 for_each_cpu_mask_nr(i, *cpu_map) {
7648 struct sched_domain *sd = &per_cpu(core_domains, i);
7650 init_sched_groups_power(i, sd);
7652 #endif
7654 for_each_cpu_mask_nr(i, *cpu_map) {
7655 struct sched_domain *sd = &per_cpu(phys_domains, i);
7657 init_sched_groups_power(i, sd);
7660 #ifdef CONFIG_NUMA
7661 for (i = 0; i < nr_node_ids; i++)
7662 init_numa_sched_groups_power(sched_group_nodes[i]);
7664 if (sd_allnodes) {
7665 struct sched_group *sg;
7667 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7668 tmpmask);
7669 init_numa_sched_groups_power(sg);
7671 #endif
7673 /* Attach the domains */
7674 for_each_cpu_mask_nr(i, *cpu_map) {
7675 struct sched_domain *sd;
7676 #ifdef CONFIG_SCHED_SMT
7677 sd = &per_cpu(cpu_domains, i);
7678 #elif defined(CONFIG_SCHED_MC)
7679 sd = &per_cpu(core_domains, i);
7680 #else
7681 sd = &per_cpu(phys_domains, i);
7682 #endif
7683 cpu_attach_domain(sd, rd, i);
7686 SCHED_CPUMASK_FREE((void *)allmasks);
7687 return 0;
7689 #ifdef CONFIG_NUMA
7690 error:
7691 free_sched_groups(cpu_map, tmpmask);
7692 SCHED_CPUMASK_FREE((void *)allmasks);
7693 kfree(rd);
7694 return -ENOMEM;
7695 #endif
7698 static int build_sched_domains(const cpumask_t *cpu_map)
7700 return __build_sched_domains(cpu_map, NULL);
7703 static cpumask_t *doms_cur; /* current sched domains */
7704 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7705 static struct sched_domain_attr *dattr_cur;
7706 /* attribues of custom domains in 'doms_cur' */
7709 * Special case: If a kmalloc of a doms_cur partition (array of
7710 * cpumask_t) fails, then fallback to a single sched domain,
7711 * as determined by the single cpumask_t fallback_doms.
7713 static cpumask_t fallback_doms;
7715 void __attribute__((weak)) arch_update_cpu_topology(void)
7720 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7721 * For now this just excludes isolated cpus, but could be used to
7722 * exclude other special cases in the future.
7724 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7726 int err;
7728 arch_update_cpu_topology();
7729 ndoms_cur = 1;
7730 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7731 if (!doms_cur)
7732 doms_cur = &fallback_doms;
7733 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7734 dattr_cur = NULL;
7735 err = build_sched_domains(doms_cur);
7736 register_sched_domain_sysctl();
7738 return err;
7741 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7742 cpumask_t *tmpmask)
7744 free_sched_groups(cpu_map, tmpmask);
7748 * Detach sched domains from a group of cpus specified in cpu_map
7749 * These cpus will now be attached to the NULL domain
7751 static void detach_destroy_domains(const cpumask_t *cpu_map)
7753 cpumask_t tmpmask;
7754 int i;
7756 unregister_sched_domain_sysctl();
7758 for_each_cpu_mask_nr(i, *cpu_map)
7759 cpu_attach_domain(NULL, &def_root_domain, i);
7760 synchronize_sched();
7761 arch_destroy_sched_domains(cpu_map, &tmpmask);
7764 /* handle null as "default" */
7765 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7766 struct sched_domain_attr *new, int idx_new)
7768 struct sched_domain_attr tmp;
7770 /* fast path */
7771 if (!new && !cur)
7772 return 1;
7774 tmp = SD_ATTR_INIT;
7775 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7776 new ? (new + idx_new) : &tmp,
7777 sizeof(struct sched_domain_attr));
7781 * Partition sched domains as specified by the 'ndoms_new'
7782 * cpumasks in the array doms_new[] of cpumasks. This compares
7783 * doms_new[] to the current sched domain partitioning, doms_cur[].
7784 * It destroys each deleted domain and builds each new domain.
7786 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7787 * The masks don't intersect (don't overlap.) We should setup one
7788 * sched domain for each mask. CPUs not in any of the cpumasks will
7789 * not be load balanced. If the same cpumask appears both in the
7790 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7791 * it as it is.
7793 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7794 * ownership of it and will kfree it when done with it. If the caller
7795 * failed the kmalloc call, then it can pass in doms_new == NULL,
7796 * and partition_sched_domains() will fallback to the single partition
7797 * 'fallback_doms', it also forces the domains to be rebuilt.
7799 * If doms_new==NULL it will be replaced with cpu_online_map.
7800 * ndoms_new==0 is a special case for destroying existing domains.
7801 * It will not create the default domain.
7803 * Call with hotplug lock held
7805 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7806 struct sched_domain_attr *dattr_new)
7808 int i, j, n;
7810 mutex_lock(&sched_domains_mutex);
7812 /* always unregister in case we don't destroy any domains */
7813 unregister_sched_domain_sysctl();
7815 n = doms_new ? ndoms_new : 0;
7817 /* Destroy deleted domains */
7818 for (i = 0; i < ndoms_cur; i++) {
7819 for (j = 0; j < n; j++) {
7820 if (cpus_equal(doms_cur[i], doms_new[j])
7821 && dattrs_equal(dattr_cur, i, dattr_new, j))
7822 goto match1;
7824 /* no match - a current sched domain not in new doms_new[] */
7825 detach_destroy_domains(doms_cur + i);
7826 match1:
7830 if (doms_new == NULL) {
7831 ndoms_cur = 0;
7832 doms_new = &fallback_doms;
7833 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7834 dattr_new = NULL;
7837 /* Build new domains */
7838 for (i = 0; i < ndoms_new; i++) {
7839 for (j = 0; j < ndoms_cur; j++) {
7840 if (cpus_equal(doms_new[i], doms_cur[j])
7841 && dattrs_equal(dattr_new, i, dattr_cur, j))
7842 goto match2;
7844 /* no match - add a new doms_new */
7845 __build_sched_domains(doms_new + i,
7846 dattr_new ? dattr_new + i : NULL);
7847 match2:
7851 /* Remember the new sched domains */
7852 if (doms_cur != &fallback_doms)
7853 kfree(doms_cur);
7854 kfree(dattr_cur); /* kfree(NULL) is safe */
7855 doms_cur = doms_new;
7856 dattr_cur = dattr_new;
7857 ndoms_cur = ndoms_new;
7859 register_sched_domain_sysctl();
7861 mutex_unlock(&sched_domains_mutex);
7864 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7865 int arch_reinit_sched_domains(void)
7867 get_online_cpus();
7869 /* Destroy domains first to force the rebuild */
7870 partition_sched_domains(0, NULL, NULL);
7872 rebuild_sched_domains();
7873 put_online_cpus();
7875 return 0;
7878 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7880 int ret;
7882 if (buf[0] != '0' && buf[0] != '1')
7883 return -EINVAL;
7885 if (smt)
7886 sched_smt_power_savings = (buf[0] == '1');
7887 else
7888 sched_mc_power_savings = (buf[0] == '1');
7890 ret = arch_reinit_sched_domains();
7892 return ret ? ret : count;
7895 #ifdef CONFIG_SCHED_MC
7896 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7897 char *page)
7899 return sprintf(page, "%u\n", sched_mc_power_savings);
7901 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7902 const char *buf, size_t count)
7904 return sched_power_savings_store(buf, count, 0);
7906 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7907 sched_mc_power_savings_show,
7908 sched_mc_power_savings_store);
7909 #endif
7911 #ifdef CONFIG_SCHED_SMT
7912 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7913 char *page)
7915 return sprintf(page, "%u\n", sched_smt_power_savings);
7917 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7918 const char *buf, size_t count)
7920 return sched_power_savings_store(buf, count, 1);
7922 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7923 sched_smt_power_savings_show,
7924 sched_smt_power_savings_store);
7925 #endif
7927 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7929 int err = 0;
7931 #ifdef CONFIG_SCHED_SMT
7932 if (smt_capable())
7933 err = sysfs_create_file(&cls->kset.kobj,
7934 &attr_sched_smt_power_savings.attr);
7935 #endif
7936 #ifdef CONFIG_SCHED_MC
7937 if (!err && mc_capable())
7938 err = sysfs_create_file(&cls->kset.kobj,
7939 &attr_sched_mc_power_savings.attr);
7940 #endif
7941 return err;
7943 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7945 #ifndef CONFIG_CPUSETS
7947 * Add online and remove offline CPUs from the scheduler domains.
7948 * When cpusets are enabled they take over this function.
7950 static int update_sched_domains(struct notifier_block *nfb,
7951 unsigned long action, void *hcpu)
7953 switch (action) {
7954 case CPU_ONLINE:
7955 case CPU_ONLINE_FROZEN:
7956 case CPU_DEAD:
7957 case CPU_DEAD_FROZEN:
7958 partition_sched_domains(1, NULL, NULL);
7959 return NOTIFY_OK;
7961 default:
7962 return NOTIFY_DONE;
7965 #endif
7967 static int update_runtime(struct notifier_block *nfb,
7968 unsigned long action, void *hcpu)
7970 int cpu = (int)(long)hcpu;
7972 switch (action) {
7973 case CPU_DOWN_PREPARE:
7974 case CPU_DOWN_PREPARE_FROZEN:
7975 disable_runtime(cpu_rq(cpu));
7976 return NOTIFY_OK;
7978 case CPU_DOWN_FAILED:
7979 case CPU_DOWN_FAILED_FROZEN:
7980 case CPU_ONLINE:
7981 case CPU_ONLINE_FROZEN:
7982 enable_runtime(cpu_rq(cpu));
7983 return NOTIFY_OK;
7985 default:
7986 return NOTIFY_DONE;
7990 void __init sched_init_smp(void)
7992 cpumask_t non_isolated_cpus;
7994 #if defined(CONFIG_NUMA)
7995 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7996 GFP_KERNEL);
7997 BUG_ON(sched_group_nodes_bycpu == NULL);
7998 #endif
7999 get_online_cpus();
8000 mutex_lock(&sched_domains_mutex);
8001 arch_init_sched_domains(&cpu_online_map);
8002 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
8003 if (cpus_empty(non_isolated_cpus))
8004 cpu_set(smp_processor_id(), non_isolated_cpus);
8005 mutex_unlock(&sched_domains_mutex);
8006 put_online_cpus();
8008 #ifndef CONFIG_CPUSETS
8009 /* XXX: Theoretical race here - CPU may be hotplugged now */
8010 hotcpu_notifier(update_sched_domains, 0);
8011 #endif
8013 /* RT runtime code needs to handle some hotplug events */
8014 hotcpu_notifier(update_runtime, 0);
8016 init_hrtick();
8018 /* Move init over to a non-isolated CPU */
8019 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
8020 BUG();
8021 sched_init_granularity();
8023 #else
8024 void __init sched_init_smp(void)
8026 sched_init_granularity();
8028 #endif /* CONFIG_SMP */
8030 int in_sched_functions(unsigned long addr)
8032 return in_lock_functions(addr) ||
8033 (addr >= (unsigned long)__sched_text_start
8034 && addr < (unsigned long)__sched_text_end);
8037 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
8039 cfs_rq->tasks_timeline = RB_ROOT;
8040 INIT_LIST_HEAD(&cfs_rq->tasks);
8041 #ifdef CONFIG_FAIR_GROUP_SCHED
8042 cfs_rq->rq = rq;
8043 #endif
8044 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
8047 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
8049 struct rt_prio_array *array;
8050 int i;
8052 array = &rt_rq->active;
8053 for (i = 0; i < MAX_RT_PRIO; i++) {
8054 INIT_LIST_HEAD(array->queue + i);
8055 __clear_bit(i, array->bitmap);
8057 /* delimiter for bitsearch: */
8058 __set_bit(MAX_RT_PRIO, array->bitmap);
8060 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
8061 rt_rq->highest_prio = MAX_RT_PRIO;
8062 #endif
8063 #ifdef CONFIG_SMP
8064 rt_rq->rt_nr_migratory = 0;
8065 rt_rq->overloaded = 0;
8066 #endif
8068 rt_rq->rt_time = 0;
8069 rt_rq->rt_throttled = 0;
8070 rt_rq->rt_runtime = 0;
8071 spin_lock_init(&rt_rq->rt_runtime_lock);
8073 #ifdef CONFIG_RT_GROUP_SCHED
8074 rt_rq->rt_nr_boosted = 0;
8075 rt_rq->rq = rq;
8076 #endif
8079 #ifdef CONFIG_FAIR_GROUP_SCHED
8080 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8081 struct sched_entity *se, int cpu, int add,
8082 struct sched_entity *parent)
8084 struct rq *rq = cpu_rq(cpu);
8085 tg->cfs_rq[cpu] = cfs_rq;
8086 init_cfs_rq(cfs_rq, rq);
8087 cfs_rq->tg = tg;
8088 if (add)
8089 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
8091 tg->se[cpu] = se;
8092 /* se could be NULL for init_task_group */
8093 if (!se)
8094 return;
8096 if (!parent)
8097 se->cfs_rq = &rq->cfs;
8098 else
8099 se->cfs_rq = parent->my_q;
8101 se->my_q = cfs_rq;
8102 se->load.weight = tg->shares;
8103 se->load.inv_weight = 0;
8104 se->parent = parent;
8106 #endif
8108 #ifdef CONFIG_RT_GROUP_SCHED
8109 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8110 struct sched_rt_entity *rt_se, int cpu, int add,
8111 struct sched_rt_entity *parent)
8113 struct rq *rq = cpu_rq(cpu);
8115 tg->rt_rq[cpu] = rt_rq;
8116 init_rt_rq(rt_rq, rq);
8117 rt_rq->tg = tg;
8118 rt_rq->rt_se = rt_se;
8119 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8120 if (add)
8121 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8123 tg->rt_se[cpu] = rt_se;
8124 if (!rt_se)
8125 return;
8127 if (!parent)
8128 rt_se->rt_rq = &rq->rt;
8129 else
8130 rt_se->rt_rq = parent->my_q;
8132 rt_se->my_q = rt_rq;
8133 rt_se->parent = parent;
8134 INIT_LIST_HEAD(&rt_se->run_list);
8136 #endif
8138 void __init sched_init(void)
8140 int i, j;
8141 unsigned long alloc_size = 0, ptr;
8143 #ifdef CONFIG_FAIR_GROUP_SCHED
8144 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8145 #endif
8146 #ifdef CONFIG_RT_GROUP_SCHED
8147 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8148 #endif
8149 #ifdef CONFIG_USER_SCHED
8150 alloc_size *= 2;
8151 #endif
8153 * As sched_init() is called before page_alloc is setup,
8154 * we use alloc_bootmem().
8156 if (alloc_size) {
8157 ptr = (unsigned long)alloc_bootmem(alloc_size);
8159 #ifdef CONFIG_FAIR_GROUP_SCHED
8160 init_task_group.se = (struct sched_entity **)ptr;
8161 ptr += nr_cpu_ids * sizeof(void **);
8163 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8164 ptr += nr_cpu_ids * sizeof(void **);
8166 #ifdef CONFIG_USER_SCHED
8167 root_task_group.se = (struct sched_entity **)ptr;
8168 ptr += nr_cpu_ids * sizeof(void **);
8170 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8171 ptr += nr_cpu_ids * sizeof(void **);
8172 #endif /* CONFIG_USER_SCHED */
8173 #endif /* CONFIG_FAIR_GROUP_SCHED */
8174 #ifdef CONFIG_RT_GROUP_SCHED
8175 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8176 ptr += nr_cpu_ids * sizeof(void **);
8178 init_task_group.rt_rq = (struct rt_rq **)ptr;
8179 ptr += nr_cpu_ids * sizeof(void **);
8181 #ifdef CONFIG_USER_SCHED
8182 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8183 ptr += nr_cpu_ids * sizeof(void **);
8185 root_task_group.rt_rq = (struct rt_rq **)ptr;
8186 ptr += nr_cpu_ids * sizeof(void **);
8187 #endif /* CONFIG_USER_SCHED */
8188 #endif /* CONFIG_RT_GROUP_SCHED */
8191 #ifdef CONFIG_SMP
8192 init_defrootdomain();
8193 #endif
8195 init_rt_bandwidth(&def_rt_bandwidth,
8196 global_rt_period(), global_rt_runtime());
8198 #ifdef CONFIG_RT_GROUP_SCHED
8199 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8200 global_rt_period(), global_rt_runtime());
8201 #ifdef CONFIG_USER_SCHED
8202 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8203 global_rt_period(), RUNTIME_INF);
8204 #endif /* CONFIG_USER_SCHED */
8205 #endif /* CONFIG_RT_GROUP_SCHED */
8207 #ifdef CONFIG_GROUP_SCHED
8208 list_add(&init_task_group.list, &task_groups);
8209 INIT_LIST_HEAD(&init_task_group.children);
8211 #ifdef CONFIG_USER_SCHED
8212 INIT_LIST_HEAD(&root_task_group.children);
8213 init_task_group.parent = &root_task_group;
8214 list_add(&init_task_group.siblings, &root_task_group.children);
8215 #endif /* CONFIG_USER_SCHED */
8216 #endif /* CONFIG_GROUP_SCHED */
8218 for_each_possible_cpu(i) {
8219 struct rq *rq;
8221 rq = cpu_rq(i);
8222 spin_lock_init(&rq->lock);
8223 rq->nr_running = 0;
8224 init_cfs_rq(&rq->cfs, rq);
8225 init_rt_rq(&rq->rt, rq);
8226 #ifdef CONFIG_FAIR_GROUP_SCHED
8227 init_task_group.shares = init_task_group_load;
8228 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8229 #ifdef CONFIG_CGROUP_SCHED
8231 * How much cpu bandwidth does init_task_group get?
8233 * In case of task-groups formed thr' the cgroup filesystem, it
8234 * gets 100% of the cpu resources in the system. This overall
8235 * system cpu resource is divided among the tasks of
8236 * init_task_group and its child task-groups in a fair manner,
8237 * based on each entity's (task or task-group's) weight
8238 * (se->load.weight).
8240 * In other words, if init_task_group has 10 tasks of weight
8241 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8242 * then A0's share of the cpu resource is:
8244 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8246 * We achieve this by letting init_task_group's tasks sit
8247 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8249 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8250 #elif defined CONFIG_USER_SCHED
8251 root_task_group.shares = NICE_0_LOAD;
8252 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8254 * In case of task-groups formed thr' the user id of tasks,
8255 * init_task_group represents tasks belonging to root user.
8256 * Hence it forms a sibling of all subsequent groups formed.
8257 * In this case, init_task_group gets only a fraction of overall
8258 * system cpu resource, based on the weight assigned to root
8259 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8260 * by letting tasks of init_task_group sit in a separate cfs_rq
8261 * (init_cfs_rq) and having one entity represent this group of
8262 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8264 init_tg_cfs_entry(&init_task_group,
8265 &per_cpu(init_cfs_rq, i),
8266 &per_cpu(init_sched_entity, i), i, 1,
8267 root_task_group.se[i]);
8269 #endif
8270 #endif /* CONFIG_FAIR_GROUP_SCHED */
8272 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8273 #ifdef CONFIG_RT_GROUP_SCHED
8274 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8275 #ifdef CONFIG_CGROUP_SCHED
8276 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8277 #elif defined CONFIG_USER_SCHED
8278 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8279 init_tg_rt_entry(&init_task_group,
8280 &per_cpu(init_rt_rq, i),
8281 &per_cpu(init_sched_rt_entity, i), i, 1,
8282 root_task_group.rt_se[i]);
8283 #endif
8284 #endif
8286 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8287 rq->cpu_load[j] = 0;
8288 #ifdef CONFIG_SMP
8289 rq->sd = NULL;
8290 rq->rd = NULL;
8291 rq->active_balance = 0;
8292 rq->next_balance = jiffies;
8293 rq->push_cpu = 0;
8294 rq->cpu = i;
8295 rq->online = 0;
8296 rq->migration_thread = NULL;
8297 INIT_LIST_HEAD(&rq->migration_queue);
8298 rq_attach_root(rq, &def_root_domain);
8299 #endif
8300 init_rq_hrtick(rq);
8301 atomic_set(&rq->nr_iowait, 0);
8304 set_load_weight(&init_task);
8306 #ifdef CONFIG_PREEMPT_NOTIFIERS
8307 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8308 #endif
8310 #ifdef CONFIG_SMP
8311 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
8312 #endif
8314 #ifdef CONFIG_RT_MUTEXES
8315 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8316 #endif
8319 * The boot idle thread does lazy MMU switching as well:
8321 atomic_inc(&init_mm.mm_count);
8322 enter_lazy_tlb(&init_mm, current);
8325 * Make us the idle thread. Technically, schedule() should not be
8326 * called from this thread, however somewhere below it might be,
8327 * but because we are the idle thread, we just pick up running again
8328 * when this runqueue becomes "idle".
8330 init_idle(current, smp_processor_id());
8332 * During early bootup we pretend to be a normal task:
8334 current->sched_class = &fair_sched_class;
8336 scheduler_running = 1;
8339 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8340 void __might_sleep(char *file, int line)
8342 #ifdef in_atomic
8343 static unsigned long prev_jiffy; /* ratelimiting */
8345 if ((!in_atomic() && !irqs_disabled()) ||
8346 system_state != SYSTEM_RUNNING || oops_in_progress)
8347 return;
8348 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8349 return;
8350 prev_jiffy = jiffies;
8352 printk(KERN_ERR
8353 "BUG: sleeping function called from invalid context at %s:%d\n",
8354 file, line);
8355 printk(KERN_ERR
8356 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8357 in_atomic(), irqs_disabled(),
8358 current->pid, current->comm);
8360 debug_show_held_locks(current);
8361 if (irqs_disabled())
8362 print_irqtrace_events(current);
8363 dump_stack();
8364 #endif
8366 EXPORT_SYMBOL(__might_sleep);
8367 #endif
8369 #ifdef CONFIG_MAGIC_SYSRQ
8370 static void normalize_task(struct rq *rq, struct task_struct *p)
8372 int on_rq;
8374 update_rq_clock(rq);
8375 on_rq = p->se.on_rq;
8376 if (on_rq)
8377 deactivate_task(rq, p, 0);
8378 __setscheduler(rq, p, SCHED_NORMAL, 0);
8379 if (on_rq) {
8380 activate_task(rq, p, 0);
8381 resched_task(rq->curr);
8385 void normalize_rt_tasks(void)
8387 struct task_struct *g, *p;
8388 unsigned long flags;
8389 struct rq *rq;
8391 read_lock_irqsave(&tasklist_lock, flags);
8392 do_each_thread(g, p) {
8394 * Only normalize user tasks:
8396 if (!p->mm)
8397 continue;
8399 p->se.exec_start = 0;
8400 #ifdef CONFIG_SCHEDSTATS
8401 p->se.wait_start = 0;
8402 p->se.sleep_start = 0;
8403 p->se.block_start = 0;
8404 #endif
8406 if (!rt_task(p)) {
8408 * Renice negative nice level userspace
8409 * tasks back to 0:
8411 if (TASK_NICE(p) < 0 && p->mm)
8412 set_user_nice(p, 0);
8413 continue;
8416 spin_lock(&p->pi_lock);
8417 rq = __task_rq_lock(p);
8419 normalize_task(rq, p);
8421 __task_rq_unlock(rq);
8422 spin_unlock(&p->pi_lock);
8423 } while_each_thread(g, p);
8425 read_unlock_irqrestore(&tasklist_lock, flags);
8428 #endif /* CONFIG_MAGIC_SYSRQ */
8430 #ifdef CONFIG_IA64
8432 * These functions are only useful for the IA64 MCA handling.
8434 * They can only be called when the whole system has been
8435 * stopped - every CPU needs to be quiescent, and no scheduling
8436 * activity can take place. Using them for anything else would
8437 * be a serious bug, and as a result, they aren't even visible
8438 * under any other configuration.
8442 * curr_task - return the current task for a given cpu.
8443 * @cpu: the processor in question.
8445 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8447 struct task_struct *curr_task(int cpu)
8449 return cpu_curr(cpu);
8453 * set_curr_task - set the current task for a given cpu.
8454 * @cpu: the processor in question.
8455 * @p: the task pointer to set.
8457 * Description: This function must only be used when non-maskable interrupts
8458 * are serviced on a separate stack. It allows the architecture to switch the
8459 * notion of the current task on a cpu in a non-blocking manner. This function
8460 * must be called with all CPU's synchronized, and interrupts disabled, the
8461 * and caller must save the original value of the current task (see
8462 * curr_task() above) and restore that value before reenabling interrupts and
8463 * re-starting the system.
8465 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8467 void set_curr_task(int cpu, struct task_struct *p)
8469 cpu_curr(cpu) = p;
8472 #endif
8474 #ifdef CONFIG_FAIR_GROUP_SCHED
8475 static void free_fair_sched_group(struct task_group *tg)
8477 int i;
8479 for_each_possible_cpu(i) {
8480 if (tg->cfs_rq)
8481 kfree(tg->cfs_rq[i]);
8482 if (tg->se)
8483 kfree(tg->se[i]);
8486 kfree(tg->cfs_rq);
8487 kfree(tg->se);
8490 static
8491 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8493 struct cfs_rq *cfs_rq;
8494 struct sched_entity *se, *parent_se;
8495 struct rq *rq;
8496 int i;
8498 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8499 if (!tg->cfs_rq)
8500 goto err;
8501 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8502 if (!tg->se)
8503 goto err;
8505 tg->shares = NICE_0_LOAD;
8507 for_each_possible_cpu(i) {
8508 rq = cpu_rq(i);
8510 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8511 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8512 if (!cfs_rq)
8513 goto err;
8515 se = kmalloc_node(sizeof(struct sched_entity),
8516 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8517 if (!se)
8518 goto err;
8520 parent_se = parent ? parent->se[i] : NULL;
8521 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8524 return 1;
8526 err:
8527 return 0;
8530 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8532 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8533 &cpu_rq(cpu)->leaf_cfs_rq_list);
8536 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8538 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8540 #else /* !CONFG_FAIR_GROUP_SCHED */
8541 static inline void free_fair_sched_group(struct task_group *tg)
8545 static inline
8546 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8548 return 1;
8551 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8555 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8558 #endif /* CONFIG_FAIR_GROUP_SCHED */
8560 #ifdef CONFIG_RT_GROUP_SCHED
8561 static void free_rt_sched_group(struct task_group *tg)
8563 int i;
8565 destroy_rt_bandwidth(&tg->rt_bandwidth);
8567 for_each_possible_cpu(i) {
8568 if (tg->rt_rq)
8569 kfree(tg->rt_rq[i]);
8570 if (tg->rt_se)
8571 kfree(tg->rt_se[i]);
8574 kfree(tg->rt_rq);
8575 kfree(tg->rt_se);
8578 static
8579 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8581 struct rt_rq *rt_rq;
8582 struct sched_rt_entity *rt_se, *parent_se;
8583 struct rq *rq;
8584 int i;
8586 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8587 if (!tg->rt_rq)
8588 goto err;
8589 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8590 if (!tg->rt_se)
8591 goto err;
8593 init_rt_bandwidth(&tg->rt_bandwidth,
8594 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8596 for_each_possible_cpu(i) {
8597 rq = cpu_rq(i);
8599 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8600 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8601 if (!rt_rq)
8602 goto err;
8604 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8605 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8606 if (!rt_se)
8607 goto err;
8609 parent_se = parent ? parent->rt_se[i] : NULL;
8610 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8613 return 1;
8615 err:
8616 return 0;
8619 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8621 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8622 &cpu_rq(cpu)->leaf_rt_rq_list);
8625 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8627 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8629 #else /* !CONFIG_RT_GROUP_SCHED */
8630 static inline void free_rt_sched_group(struct task_group *tg)
8634 static inline
8635 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8637 return 1;
8640 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8644 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8647 #endif /* CONFIG_RT_GROUP_SCHED */
8649 #ifdef CONFIG_GROUP_SCHED
8650 static void free_sched_group(struct task_group *tg)
8652 free_fair_sched_group(tg);
8653 free_rt_sched_group(tg);
8654 kfree(tg);
8657 /* allocate runqueue etc for a new task group */
8658 struct task_group *sched_create_group(struct task_group *parent)
8660 struct task_group *tg;
8661 unsigned long flags;
8662 int i;
8664 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8665 if (!tg)
8666 return ERR_PTR(-ENOMEM);
8668 if (!alloc_fair_sched_group(tg, parent))
8669 goto err;
8671 if (!alloc_rt_sched_group(tg, parent))
8672 goto err;
8674 spin_lock_irqsave(&task_group_lock, flags);
8675 for_each_possible_cpu(i) {
8676 register_fair_sched_group(tg, i);
8677 register_rt_sched_group(tg, i);
8679 list_add_rcu(&tg->list, &task_groups);
8681 WARN_ON(!parent); /* root should already exist */
8683 tg->parent = parent;
8684 INIT_LIST_HEAD(&tg->children);
8685 list_add_rcu(&tg->siblings, &parent->children);
8686 spin_unlock_irqrestore(&task_group_lock, flags);
8688 return tg;
8690 err:
8691 free_sched_group(tg);
8692 return ERR_PTR(-ENOMEM);
8695 /* rcu callback to free various structures associated with a task group */
8696 static void free_sched_group_rcu(struct rcu_head *rhp)
8698 /* now it should be safe to free those cfs_rqs */
8699 free_sched_group(container_of(rhp, struct task_group, rcu));
8702 /* Destroy runqueue etc associated with a task group */
8703 void sched_destroy_group(struct task_group *tg)
8705 unsigned long flags;
8706 int i;
8708 spin_lock_irqsave(&task_group_lock, flags);
8709 for_each_possible_cpu(i) {
8710 unregister_fair_sched_group(tg, i);
8711 unregister_rt_sched_group(tg, i);
8713 list_del_rcu(&tg->list);
8714 list_del_rcu(&tg->siblings);
8715 spin_unlock_irqrestore(&task_group_lock, flags);
8717 /* wait for possible concurrent references to cfs_rqs complete */
8718 call_rcu(&tg->rcu, free_sched_group_rcu);
8721 /* change task's runqueue when it moves between groups.
8722 * The caller of this function should have put the task in its new group
8723 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8724 * reflect its new group.
8726 void sched_move_task(struct task_struct *tsk)
8728 int on_rq, running;
8729 unsigned long flags;
8730 struct rq *rq;
8732 rq = task_rq_lock(tsk, &flags);
8734 update_rq_clock(rq);
8736 running = task_current(rq, tsk);
8737 on_rq = tsk->se.on_rq;
8739 if (on_rq)
8740 dequeue_task(rq, tsk, 0);
8741 if (unlikely(running))
8742 tsk->sched_class->put_prev_task(rq, tsk);
8744 set_task_rq(tsk, task_cpu(tsk));
8746 #ifdef CONFIG_FAIR_GROUP_SCHED
8747 if (tsk->sched_class->moved_group)
8748 tsk->sched_class->moved_group(tsk);
8749 #endif
8751 if (unlikely(running))
8752 tsk->sched_class->set_curr_task(rq);
8753 if (on_rq)
8754 enqueue_task(rq, tsk, 0);
8756 task_rq_unlock(rq, &flags);
8758 #endif /* CONFIG_GROUP_SCHED */
8760 #ifdef CONFIG_FAIR_GROUP_SCHED
8761 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8763 struct cfs_rq *cfs_rq = se->cfs_rq;
8764 int on_rq;
8766 on_rq = se->on_rq;
8767 if (on_rq)
8768 dequeue_entity(cfs_rq, se, 0);
8770 se->load.weight = shares;
8771 se->load.inv_weight = 0;
8773 if (on_rq)
8774 enqueue_entity(cfs_rq, se, 0);
8777 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8779 struct cfs_rq *cfs_rq = se->cfs_rq;
8780 struct rq *rq = cfs_rq->rq;
8781 unsigned long flags;
8783 spin_lock_irqsave(&rq->lock, flags);
8784 __set_se_shares(se, shares);
8785 spin_unlock_irqrestore(&rq->lock, flags);
8788 static DEFINE_MUTEX(shares_mutex);
8790 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8792 int i;
8793 unsigned long flags;
8796 * We can't change the weight of the root cgroup.
8798 if (!tg->se[0])
8799 return -EINVAL;
8801 if (shares < MIN_SHARES)
8802 shares = MIN_SHARES;
8803 else if (shares > MAX_SHARES)
8804 shares = MAX_SHARES;
8806 mutex_lock(&shares_mutex);
8807 if (tg->shares == shares)
8808 goto done;
8810 spin_lock_irqsave(&task_group_lock, flags);
8811 for_each_possible_cpu(i)
8812 unregister_fair_sched_group(tg, i);
8813 list_del_rcu(&tg->siblings);
8814 spin_unlock_irqrestore(&task_group_lock, flags);
8816 /* wait for any ongoing reference to this group to finish */
8817 synchronize_sched();
8820 * Now we are free to modify the group's share on each cpu
8821 * w/o tripping rebalance_share or load_balance_fair.
8823 tg->shares = shares;
8824 for_each_possible_cpu(i) {
8826 * force a rebalance
8828 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8829 set_se_shares(tg->se[i], shares);
8833 * Enable load balance activity on this group, by inserting it back on
8834 * each cpu's rq->leaf_cfs_rq_list.
8836 spin_lock_irqsave(&task_group_lock, flags);
8837 for_each_possible_cpu(i)
8838 register_fair_sched_group(tg, i);
8839 list_add_rcu(&tg->siblings, &tg->parent->children);
8840 spin_unlock_irqrestore(&task_group_lock, flags);
8841 done:
8842 mutex_unlock(&shares_mutex);
8843 return 0;
8846 unsigned long sched_group_shares(struct task_group *tg)
8848 return tg->shares;
8850 #endif
8852 #ifdef CONFIG_RT_GROUP_SCHED
8854 * Ensure that the real time constraints are schedulable.
8856 static DEFINE_MUTEX(rt_constraints_mutex);
8858 static unsigned long to_ratio(u64 period, u64 runtime)
8860 if (runtime == RUNTIME_INF)
8861 return 1ULL << 20;
8863 return div64_u64(runtime << 20, period);
8866 /* Must be called with tasklist_lock held */
8867 static inline int tg_has_rt_tasks(struct task_group *tg)
8869 struct task_struct *g, *p;
8871 do_each_thread(g, p) {
8872 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8873 return 1;
8874 } while_each_thread(g, p);
8876 return 0;
8879 struct rt_schedulable_data {
8880 struct task_group *tg;
8881 u64 rt_period;
8882 u64 rt_runtime;
8885 static int tg_schedulable(struct task_group *tg, void *data)
8887 struct rt_schedulable_data *d = data;
8888 struct task_group *child;
8889 unsigned long total, sum = 0;
8890 u64 period, runtime;
8892 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8893 runtime = tg->rt_bandwidth.rt_runtime;
8895 if (tg == d->tg) {
8896 period = d->rt_period;
8897 runtime = d->rt_runtime;
8901 * Cannot have more runtime than the period.
8903 if (runtime > period && runtime != RUNTIME_INF)
8904 return -EINVAL;
8907 * Ensure we don't starve existing RT tasks.
8909 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8910 return -EBUSY;
8912 total = to_ratio(period, runtime);
8915 * Nobody can have more than the global setting allows.
8917 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8918 return -EINVAL;
8921 * The sum of our children's runtime should not exceed our own.
8923 list_for_each_entry_rcu(child, &tg->children, siblings) {
8924 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8925 runtime = child->rt_bandwidth.rt_runtime;
8927 if (child == d->tg) {
8928 period = d->rt_period;
8929 runtime = d->rt_runtime;
8932 sum += to_ratio(period, runtime);
8935 if (sum > total)
8936 return -EINVAL;
8938 return 0;
8941 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8943 struct rt_schedulable_data data = {
8944 .tg = tg,
8945 .rt_period = period,
8946 .rt_runtime = runtime,
8949 return walk_tg_tree(tg_schedulable, tg_nop, &data);
8952 static int tg_set_bandwidth(struct task_group *tg,
8953 u64 rt_period, u64 rt_runtime)
8955 int i, err = 0;
8957 mutex_lock(&rt_constraints_mutex);
8958 read_lock(&tasklist_lock);
8959 err = __rt_schedulable(tg, rt_period, rt_runtime);
8960 if (err)
8961 goto unlock;
8963 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8964 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8965 tg->rt_bandwidth.rt_runtime = rt_runtime;
8967 for_each_possible_cpu(i) {
8968 struct rt_rq *rt_rq = tg->rt_rq[i];
8970 spin_lock(&rt_rq->rt_runtime_lock);
8971 rt_rq->rt_runtime = rt_runtime;
8972 spin_unlock(&rt_rq->rt_runtime_lock);
8974 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8975 unlock:
8976 read_unlock(&tasklist_lock);
8977 mutex_unlock(&rt_constraints_mutex);
8979 return err;
8982 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8984 u64 rt_runtime, rt_period;
8986 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8987 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8988 if (rt_runtime_us < 0)
8989 rt_runtime = RUNTIME_INF;
8991 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8994 long sched_group_rt_runtime(struct task_group *tg)
8996 u64 rt_runtime_us;
8998 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8999 return -1;
9001 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
9002 do_div(rt_runtime_us, NSEC_PER_USEC);
9003 return rt_runtime_us;
9006 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
9008 u64 rt_runtime, rt_period;
9010 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
9011 rt_runtime = tg->rt_bandwidth.rt_runtime;
9013 if (rt_period == 0)
9014 return -EINVAL;
9016 return tg_set_bandwidth(tg, rt_period, rt_runtime);
9019 long sched_group_rt_period(struct task_group *tg)
9021 u64 rt_period_us;
9023 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
9024 do_div(rt_period_us, NSEC_PER_USEC);
9025 return rt_period_us;
9028 static int sched_rt_global_constraints(void)
9030 u64 runtime, period;
9031 int ret = 0;
9033 if (sysctl_sched_rt_period <= 0)
9034 return -EINVAL;
9036 runtime = global_rt_runtime();
9037 period = global_rt_period();
9040 * Sanity check on the sysctl variables.
9042 if (runtime > period && runtime != RUNTIME_INF)
9043 return -EINVAL;
9045 mutex_lock(&rt_constraints_mutex);
9046 read_lock(&tasklist_lock);
9047 ret = __rt_schedulable(NULL, 0, 0);
9048 read_unlock(&tasklist_lock);
9049 mutex_unlock(&rt_constraints_mutex);
9051 return ret;
9053 #else /* !CONFIG_RT_GROUP_SCHED */
9054 static int sched_rt_global_constraints(void)
9056 unsigned long flags;
9057 int i;
9059 if (sysctl_sched_rt_period <= 0)
9060 return -EINVAL;
9062 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
9063 for_each_possible_cpu(i) {
9064 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
9066 spin_lock(&rt_rq->rt_runtime_lock);
9067 rt_rq->rt_runtime = global_rt_runtime();
9068 spin_unlock(&rt_rq->rt_runtime_lock);
9070 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
9072 return 0;
9074 #endif /* CONFIG_RT_GROUP_SCHED */
9076 int sched_rt_handler(struct ctl_table *table, int write,
9077 struct file *filp, void __user *buffer, size_t *lenp,
9078 loff_t *ppos)
9080 int ret;
9081 int old_period, old_runtime;
9082 static DEFINE_MUTEX(mutex);
9084 mutex_lock(&mutex);
9085 old_period = sysctl_sched_rt_period;
9086 old_runtime = sysctl_sched_rt_runtime;
9088 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
9090 if (!ret && write) {
9091 ret = sched_rt_global_constraints();
9092 if (ret) {
9093 sysctl_sched_rt_period = old_period;
9094 sysctl_sched_rt_runtime = old_runtime;
9095 } else {
9096 def_rt_bandwidth.rt_runtime = global_rt_runtime();
9097 def_rt_bandwidth.rt_period =
9098 ns_to_ktime(global_rt_period());
9101 mutex_unlock(&mutex);
9103 return ret;
9106 #ifdef CONFIG_CGROUP_SCHED
9108 /* return corresponding task_group object of a cgroup */
9109 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
9111 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
9112 struct task_group, css);
9115 static struct cgroup_subsys_state *
9116 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
9118 struct task_group *tg, *parent;
9120 if (!cgrp->parent) {
9121 /* This is early initialization for the top cgroup */
9122 return &init_task_group.css;
9125 parent = cgroup_tg(cgrp->parent);
9126 tg = sched_create_group(parent);
9127 if (IS_ERR(tg))
9128 return ERR_PTR(-ENOMEM);
9130 return &tg->css;
9133 static void
9134 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9136 struct task_group *tg = cgroup_tg(cgrp);
9138 sched_destroy_group(tg);
9141 static int
9142 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9143 struct task_struct *tsk)
9145 #ifdef CONFIG_RT_GROUP_SCHED
9146 /* Don't accept realtime tasks when there is no way for them to run */
9147 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9148 return -EINVAL;
9149 #else
9150 /* We don't support RT-tasks being in separate groups */
9151 if (tsk->sched_class != &fair_sched_class)
9152 return -EINVAL;
9153 #endif
9155 return 0;
9158 static void
9159 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9160 struct cgroup *old_cont, struct task_struct *tsk)
9162 sched_move_task(tsk);
9165 #ifdef CONFIG_FAIR_GROUP_SCHED
9166 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9167 u64 shareval)
9169 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9172 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9174 struct task_group *tg = cgroup_tg(cgrp);
9176 return (u64) tg->shares;
9178 #endif /* CONFIG_FAIR_GROUP_SCHED */
9180 #ifdef CONFIG_RT_GROUP_SCHED
9181 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9182 s64 val)
9184 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9187 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9189 return sched_group_rt_runtime(cgroup_tg(cgrp));
9192 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9193 u64 rt_period_us)
9195 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9198 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9200 return sched_group_rt_period(cgroup_tg(cgrp));
9202 #endif /* CONFIG_RT_GROUP_SCHED */
9204 static struct cftype cpu_files[] = {
9205 #ifdef CONFIG_FAIR_GROUP_SCHED
9207 .name = "shares",
9208 .read_u64 = cpu_shares_read_u64,
9209 .write_u64 = cpu_shares_write_u64,
9211 #endif
9212 #ifdef CONFIG_RT_GROUP_SCHED
9214 .name = "rt_runtime_us",
9215 .read_s64 = cpu_rt_runtime_read,
9216 .write_s64 = cpu_rt_runtime_write,
9219 .name = "rt_period_us",
9220 .read_u64 = cpu_rt_period_read_uint,
9221 .write_u64 = cpu_rt_period_write_uint,
9223 #endif
9226 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9228 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9231 struct cgroup_subsys cpu_cgroup_subsys = {
9232 .name = "cpu",
9233 .create = cpu_cgroup_create,
9234 .destroy = cpu_cgroup_destroy,
9235 .can_attach = cpu_cgroup_can_attach,
9236 .attach = cpu_cgroup_attach,
9237 .populate = cpu_cgroup_populate,
9238 .subsys_id = cpu_cgroup_subsys_id,
9239 .early_init = 1,
9242 #endif /* CONFIG_CGROUP_SCHED */
9244 #ifdef CONFIG_CGROUP_CPUACCT
9247 * CPU accounting code for task groups.
9249 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9250 * (balbir@in.ibm.com).
9253 /* track cpu usage of a group of tasks */
9254 struct cpuacct {
9255 struct cgroup_subsys_state css;
9256 /* cpuusage holds pointer to a u64-type object on every cpu */
9257 u64 *cpuusage;
9260 struct cgroup_subsys cpuacct_subsys;
9262 /* return cpu accounting group corresponding to this container */
9263 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9265 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9266 struct cpuacct, css);
9269 /* return cpu accounting group to which this task belongs */
9270 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9272 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9273 struct cpuacct, css);
9276 /* create a new cpu accounting group */
9277 static struct cgroup_subsys_state *cpuacct_create(
9278 struct cgroup_subsys *ss, struct cgroup *cgrp)
9280 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9282 if (!ca)
9283 return ERR_PTR(-ENOMEM);
9285 ca->cpuusage = alloc_percpu(u64);
9286 if (!ca->cpuusage) {
9287 kfree(ca);
9288 return ERR_PTR(-ENOMEM);
9291 return &ca->css;
9294 /* destroy an existing cpu accounting group */
9295 static void
9296 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9298 struct cpuacct *ca = cgroup_ca(cgrp);
9300 free_percpu(ca->cpuusage);
9301 kfree(ca);
9304 /* return total cpu usage (in nanoseconds) of a group */
9305 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9307 struct cpuacct *ca = cgroup_ca(cgrp);
9308 u64 totalcpuusage = 0;
9309 int i;
9311 for_each_possible_cpu(i) {
9312 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9315 * Take rq->lock to make 64-bit addition safe on 32-bit
9316 * platforms.
9318 spin_lock_irq(&cpu_rq(i)->lock);
9319 totalcpuusage += *cpuusage;
9320 spin_unlock_irq(&cpu_rq(i)->lock);
9323 return totalcpuusage;
9326 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9327 u64 reset)
9329 struct cpuacct *ca = cgroup_ca(cgrp);
9330 int err = 0;
9331 int i;
9333 if (reset) {
9334 err = -EINVAL;
9335 goto out;
9338 for_each_possible_cpu(i) {
9339 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9341 spin_lock_irq(&cpu_rq(i)->lock);
9342 *cpuusage = 0;
9343 spin_unlock_irq(&cpu_rq(i)->lock);
9345 out:
9346 return err;
9349 static struct cftype files[] = {
9351 .name = "usage",
9352 .read_u64 = cpuusage_read,
9353 .write_u64 = cpuusage_write,
9357 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9359 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9363 * charge this task's execution time to its accounting group.
9365 * called with rq->lock held.
9367 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9369 struct cpuacct *ca;
9371 if (!cpuacct_subsys.active)
9372 return;
9374 ca = task_ca(tsk);
9375 if (ca) {
9376 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9378 *cpuusage += cputime;
9382 struct cgroup_subsys cpuacct_subsys = {
9383 .name = "cpuacct",
9384 .create = cpuacct_create,
9385 .destroy = cpuacct_destroy,
9386 .populate = cpuacct_populate,
9387 .subsys_id = cpuacct_subsys_id,
9389 #endif /* CONFIG_CGROUP_CPUACCT */