hrtimer: convert kernel/* to the new hrtimer apis
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / sched.c
blobe46b5afa200d6cc63730ddb388c70c856610ea46
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/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/bootmem.h>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
73 #include <linux/ftrace.h>
75 #include <asm/tlb.h>
76 #include <asm/irq_regs.h>
78 #include "sched_cpupri.h"
81 * Convert user-nice values [ -20 ... 0 ... 19 ]
82 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
83 * and back.
85 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
86 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
87 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
90 * 'User priority' is the nice value converted to something we
91 * can work with better when scaling various scheduler parameters,
92 * it's a [ 0 ... 39 ] range.
94 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
95 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
96 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
99 * Helpers for converting nanosecond timing to jiffy resolution
101 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
103 #define NICE_0_LOAD SCHED_LOAD_SCALE
104 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
107 * These are the 'tuning knobs' of the scheduler:
109 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
110 * Timeslices get refilled after they expire.
112 #define DEF_TIMESLICE (100 * HZ / 1000)
115 * single value that denotes runtime == period, ie unlimited time.
117 #define RUNTIME_INF ((u64)~0ULL)
119 #ifdef CONFIG_SMP
121 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
122 * Since cpu_power is a 'constant', we can use a reciprocal divide.
124 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
126 return reciprocal_divide(load, sg->reciprocal_cpu_power);
130 * Each time a sched group cpu_power is changed,
131 * we must compute its reciprocal value
133 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
135 sg->__cpu_power += val;
136 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
138 #endif
140 static inline int rt_policy(int policy)
142 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
143 return 1;
144 return 0;
147 static inline int task_has_rt_policy(struct task_struct *p)
149 return rt_policy(p->policy);
153 * This is the priority-queue data structure of the RT scheduling class:
155 struct rt_prio_array {
156 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
157 struct list_head queue[MAX_RT_PRIO];
160 struct rt_bandwidth {
161 /* nests inside the rq lock: */
162 spinlock_t rt_runtime_lock;
163 ktime_t rt_period;
164 u64 rt_runtime;
165 struct hrtimer rt_period_timer;
168 static struct rt_bandwidth def_rt_bandwidth;
170 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
172 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
174 struct rt_bandwidth *rt_b =
175 container_of(timer, struct rt_bandwidth, rt_period_timer);
176 ktime_t now;
177 int overrun;
178 int idle = 0;
180 for (;;) {
181 now = hrtimer_cb_get_time(timer);
182 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
184 if (!overrun)
185 break;
187 idle = do_sched_rt_period_timer(rt_b, overrun);
190 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
193 static
194 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
196 rt_b->rt_period = ns_to_ktime(period);
197 rt_b->rt_runtime = runtime;
199 spin_lock_init(&rt_b->rt_runtime_lock);
201 hrtimer_init(&rt_b->rt_period_timer,
202 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
203 rt_b->rt_period_timer.function = sched_rt_period_timer;
204 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
207 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
209 ktime_t now;
211 if (rt_b->rt_runtime == RUNTIME_INF)
212 return;
214 if (hrtimer_active(&rt_b->rt_period_timer))
215 return;
217 spin_lock(&rt_b->rt_runtime_lock);
218 for (;;) {
219 if (hrtimer_active(&rt_b->rt_period_timer))
220 break;
222 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
223 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
224 hrtimer_start_expires(&rt_b->rt_period_timer,
225 HRTIMER_MODE_ABS);
227 spin_unlock(&rt_b->rt_runtime_lock);
230 #ifdef CONFIG_RT_GROUP_SCHED
231 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
233 hrtimer_cancel(&rt_b->rt_period_timer);
235 #endif
238 * sched_domains_mutex serializes calls to arch_init_sched_domains,
239 * detach_destroy_domains and partition_sched_domains.
241 static DEFINE_MUTEX(sched_domains_mutex);
243 #ifdef CONFIG_GROUP_SCHED
245 #include <linux/cgroup.h>
247 struct cfs_rq;
249 static LIST_HEAD(task_groups);
251 /* task group related information */
252 struct task_group {
253 #ifdef CONFIG_CGROUP_SCHED
254 struct cgroup_subsys_state css;
255 #endif
257 #ifdef CONFIG_FAIR_GROUP_SCHED
258 /* schedulable entities of this group on each cpu */
259 struct sched_entity **se;
260 /* runqueue "owned" by this group on each cpu */
261 struct cfs_rq **cfs_rq;
262 unsigned long shares;
263 #endif
265 #ifdef CONFIG_RT_GROUP_SCHED
266 struct sched_rt_entity **rt_se;
267 struct rt_rq **rt_rq;
269 struct rt_bandwidth rt_bandwidth;
270 #endif
272 struct rcu_head rcu;
273 struct list_head list;
275 struct task_group *parent;
276 struct list_head siblings;
277 struct list_head children;
280 #ifdef CONFIG_USER_SCHED
283 * Root task group.
284 * Every UID task group (including init_task_group aka UID-0) will
285 * be a child to this group.
287 struct task_group root_task_group;
289 #ifdef CONFIG_FAIR_GROUP_SCHED
290 /* Default task group's sched entity on each cpu */
291 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
292 /* Default task group's cfs_rq on each cpu */
293 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
294 #endif /* CONFIG_FAIR_GROUP_SCHED */
296 #ifdef CONFIG_RT_GROUP_SCHED
297 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
298 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
299 #endif /* CONFIG_RT_GROUP_SCHED */
300 #else /* !CONFIG_FAIR_GROUP_SCHED */
301 #define root_task_group init_task_group
302 #endif /* CONFIG_FAIR_GROUP_SCHED */
304 /* task_group_lock serializes add/remove of task groups and also changes to
305 * a task group's cpu shares.
307 static DEFINE_SPINLOCK(task_group_lock);
309 #ifdef CONFIG_FAIR_GROUP_SCHED
310 #ifdef CONFIG_USER_SCHED
311 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
312 #else /* !CONFIG_USER_SCHED */
313 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
314 #endif /* CONFIG_USER_SCHED */
317 * A weight of 0 or 1 can cause arithmetics problems.
318 * A weight of a cfs_rq is the sum of weights of which entities
319 * are queued on this cfs_rq, so a weight of a entity should not be
320 * too large, so as the shares value of a task group.
321 * (The default weight is 1024 - so there's no practical
322 * limitation from this.)
324 #define MIN_SHARES 2
325 #define MAX_SHARES (1UL << 18)
327 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
328 #endif
330 /* Default task group.
331 * Every task in system belong to this group at bootup.
333 struct task_group init_task_group;
335 /* return group to which a task belongs */
336 static inline struct task_group *task_group(struct task_struct *p)
338 struct task_group *tg;
340 #ifdef CONFIG_USER_SCHED
341 tg = p->user->tg;
342 #elif defined(CONFIG_CGROUP_SCHED)
343 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
344 struct task_group, css);
345 #else
346 tg = &init_task_group;
347 #endif
348 return tg;
351 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
352 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
354 #ifdef CONFIG_FAIR_GROUP_SCHED
355 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
356 p->se.parent = task_group(p)->se[cpu];
357 #endif
359 #ifdef CONFIG_RT_GROUP_SCHED
360 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
361 p->rt.parent = task_group(p)->rt_se[cpu];
362 #endif
365 #else
367 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
368 static inline struct task_group *task_group(struct task_struct *p)
370 return NULL;
373 #endif /* CONFIG_GROUP_SCHED */
375 /* CFS-related fields in a runqueue */
376 struct cfs_rq {
377 struct load_weight load;
378 unsigned long nr_running;
380 u64 exec_clock;
381 u64 min_vruntime;
382 u64 pair_start;
384 struct rb_root tasks_timeline;
385 struct rb_node *rb_leftmost;
387 struct list_head tasks;
388 struct list_head *balance_iterator;
391 * 'curr' points to currently running entity on this cfs_rq.
392 * It is set to NULL otherwise (i.e when none are currently running).
394 struct sched_entity *curr, *next;
396 unsigned long nr_spread_over;
398 #ifdef CONFIG_FAIR_GROUP_SCHED
399 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
402 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
403 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
404 * (like users, containers etc.)
406 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
407 * list is used during load balance.
409 struct list_head leaf_cfs_rq_list;
410 struct task_group *tg; /* group that "owns" this runqueue */
412 #ifdef CONFIG_SMP
414 * the part of load.weight contributed by tasks
416 unsigned long task_weight;
419 * h_load = weight * f(tg)
421 * Where f(tg) is the recursive weight fraction assigned to
422 * this group.
424 unsigned long h_load;
427 * this cpu's part of tg->shares
429 unsigned long shares;
432 * load.weight at the time we set shares
434 unsigned long rq_weight;
435 #endif
436 #endif
439 /* Real-Time classes' related field in a runqueue: */
440 struct rt_rq {
441 struct rt_prio_array active;
442 unsigned long rt_nr_running;
443 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
444 int highest_prio; /* highest queued rt task prio */
445 #endif
446 #ifdef CONFIG_SMP
447 unsigned long rt_nr_migratory;
448 int overloaded;
449 #endif
450 int rt_throttled;
451 u64 rt_time;
452 u64 rt_runtime;
453 /* Nests inside the rq lock: */
454 spinlock_t rt_runtime_lock;
456 #ifdef CONFIG_RT_GROUP_SCHED
457 unsigned long rt_nr_boosted;
459 struct rq *rq;
460 struct list_head leaf_rt_rq_list;
461 struct task_group *tg;
462 struct sched_rt_entity *rt_se;
463 #endif
466 #ifdef CONFIG_SMP
469 * We add the notion of a root-domain which will be used to define per-domain
470 * variables. Each exclusive cpuset essentially defines an island domain by
471 * fully partitioning the member cpus from any other cpuset. Whenever a new
472 * exclusive cpuset is created, we also create and attach a new root-domain
473 * object.
476 struct root_domain {
477 atomic_t refcount;
478 cpumask_t span;
479 cpumask_t online;
482 * The "RT overload" flag: it gets set if a CPU has more than
483 * one runnable RT task.
485 cpumask_t rto_mask;
486 atomic_t rto_count;
487 #ifdef CONFIG_SMP
488 struct cpupri cpupri;
489 #endif
493 * By default the system creates a single root-domain with all cpus as
494 * members (mimicking the global state we have today).
496 static struct root_domain def_root_domain;
498 #endif
501 * This is the main, per-CPU runqueue data structure.
503 * Locking rule: those places that want to lock multiple runqueues
504 * (such as the load balancing or the thread migration code), lock
505 * acquire operations must be ordered by ascending &runqueue.
507 struct rq {
508 /* runqueue lock: */
509 spinlock_t lock;
512 * nr_running and cpu_load should be in the same cacheline because
513 * remote CPUs use both these fields when doing load calculation.
515 unsigned long nr_running;
516 #define CPU_LOAD_IDX_MAX 5
517 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
518 unsigned char idle_at_tick;
519 #ifdef CONFIG_NO_HZ
520 unsigned long last_tick_seen;
521 unsigned char in_nohz_recently;
522 #endif
523 /* capture load from *all* tasks on this cpu: */
524 struct load_weight load;
525 unsigned long nr_load_updates;
526 u64 nr_switches;
528 struct cfs_rq cfs;
529 struct rt_rq rt;
531 #ifdef CONFIG_FAIR_GROUP_SCHED
532 /* list of leaf cfs_rq on this cpu: */
533 struct list_head leaf_cfs_rq_list;
534 #endif
535 #ifdef CONFIG_RT_GROUP_SCHED
536 struct list_head leaf_rt_rq_list;
537 #endif
540 * This is part of a global counter where only the total sum
541 * over all CPUs matters. A task can increase this counter on
542 * one CPU and if it got migrated afterwards it may decrease
543 * it on another CPU. Always updated under the runqueue lock:
545 unsigned long nr_uninterruptible;
547 struct task_struct *curr, *idle;
548 unsigned long next_balance;
549 struct mm_struct *prev_mm;
551 u64 clock;
553 atomic_t nr_iowait;
555 #ifdef CONFIG_SMP
556 struct root_domain *rd;
557 struct sched_domain *sd;
559 /* For active balancing */
560 int active_balance;
561 int push_cpu;
562 /* cpu of this runqueue: */
563 int cpu;
564 int online;
566 unsigned long avg_load_per_task;
568 struct task_struct *migration_thread;
569 struct list_head migration_queue;
570 #endif
572 #ifdef CONFIG_SCHED_HRTICK
573 #ifdef CONFIG_SMP
574 int hrtick_csd_pending;
575 struct call_single_data hrtick_csd;
576 #endif
577 struct hrtimer hrtick_timer;
578 #endif
580 #ifdef CONFIG_SCHEDSTATS
581 /* latency stats */
582 struct sched_info rq_sched_info;
584 /* sys_sched_yield() stats */
585 unsigned int yld_exp_empty;
586 unsigned int yld_act_empty;
587 unsigned int yld_both_empty;
588 unsigned int yld_count;
590 /* schedule() stats */
591 unsigned int sched_switch;
592 unsigned int sched_count;
593 unsigned int sched_goidle;
595 /* try_to_wake_up() stats */
596 unsigned int ttwu_count;
597 unsigned int ttwu_local;
599 /* BKL stats */
600 unsigned int bkl_count;
601 #endif
604 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
606 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
608 rq->curr->sched_class->check_preempt_curr(rq, p);
611 static inline int cpu_of(struct rq *rq)
613 #ifdef CONFIG_SMP
614 return rq->cpu;
615 #else
616 return 0;
617 #endif
621 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
622 * See detach_destroy_domains: synchronize_sched for details.
624 * The domain tree of any CPU may only be accessed from within
625 * preempt-disabled sections.
627 #define for_each_domain(cpu, __sd) \
628 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
630 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
631 #define this_rq() (&__get_cpu_var(runqueues))
632 #define task_rq(p) cpu_rq(task_cpu(p))
633 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
635 static inline void update_rq_clock(struct rq *rq)
637 rq->clock = sched_clock_cpu(cpu_of(rq));
641 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
643 #ifdef CONFIG_SCHED_DEBUG
644 # define const_debug __read_mostly
645 #else
646 # define const_debug static const
647 #endif
650 * runqueue_is_locked
652 * Returns true if the current cpu runqueue is locked.
653 * This interface allows printk to be called with the runqueue lock
654 * held and know whether or not it is OK to wake up the klogd.
656 int runqueue_is_locked(void)
658 int cpu = get_cpu();
659 struct rq *rq = cpu_rq(cpu);
660 int ret;
662 ret = spin_is_locked(&rq->lock);
663 put_cpu();
664 return ret;
668 * Debugging: various feature bits
671 #define SCHED_FEAT(name, enabled) \
672 __SCHED_FEAT_##name ,
674 enum {
675 #include "sched_features.h"
678 #undef SCHED_FEAT
680 #define SCHED_FEAT(name, enabled) \
681 (1UL << __SCHED_FEAT_##name) * enabled |
683 const_debug unsigned int sysctl_sched_features =
684 #include "sched_features.h"
687 #undef SCHED_FEAT
689 #ifdef CONFIG_SCHED_DEBUG
690 #define SCHED_FEAT(name, enabled) \
691 #name ,
693 static __read_mostly char *sched_feat_names[] = {
694 #include "sched_features.h"
695 NULL
698 #undef SCHED_FEAT
700 static int sched_feat_open(struct inode *inode, struct file *filp)
702 filp->private_data = inode->i_private;
703 return 0;
706 static ssize_t
707 sched_feat_read(struct file *filp, char __user *ubuf,
708 size_t cnt, loff_t *ppos)
710 char *buf;
711 int r = 0;
712 int len = 0;
713 int i;
715 for (i = 0; sched_feat_names[i]; i++) {
716 len += strlen(sched_feat_names[i]);
717 len += 4;
720 buf = kmalloc(len + 2, GFP_KERNEL);
721 if (!buf)
722 return -ENOMEM;
724 for (i = 0; sched_feat_names[i]; i++) {
725 if (sysctl_sched_features & (1UL << i))
726 r += sprintf(buf + r, "%s ", sched_feat_names[i]);
727 else
728 r += sprintf(buf + r, "NO_%s ", sched_feat_names[i]);
731 r += sprintf(buf + r, "\n");
732 WARN_ON(r >= len + 2);
734 r = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
736 kfree(buf);
738 return r;
741 static ssize_t
742 sched_feat_write(struct file *filp, const char __user *ubuf,
743 size_t cnt, loff_t *ppos)
745 char buf[64];
746 char *cmp = buf;
747 int neg = 0;
748 int i;
750 if (cnt > 63)
751 cnt = 63;
753 if (copy_from_user(&buf, ubuf, cnt))
754 return -EFAULT;
756 buf[cnt] = 0;
758 if (strncmp(buf, "NO_", 3) == 0) {
759 neg = 1;
760 cmp += 3;
763 for (i = 0; sched_feat_names[i]; i++) {
764 int len = strlen(sched_feat_names[i]);
766 if (strncmp(cmp, sched_feat_names[i], len) == 0) {
767 if (neg)
768 sysctl_sched_features &= ~(1UL << i);
769 else
770 sysctl_sched_features |= (1UL << i);
771 break;
775 if (!sched_feat_names[i])
776 return -EINVAL;
778 filp->f_pos += cnt;
780 return cnt;
783 static struct file_operations sched_feat_fops = {
784 .open = sched_feat_open,
785 .read = sched_feat_read,
786 .write = sched_feat_write,
789 static __init int sched_init_debug(void)
791 debugfs_create_file("sched_features", 0644, NULL, NULL,
792 &sched_feat_fops);
794 return 0;
796 late_initcall(sched_init_debug);
798 #endif
800 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
803 * Number of tasks to iterate in a single balance run.
804 * Limited because this is done with IRQs disabled.
806 const_debug unsigned int sysctl_sched_nr_migrate = 32;
809 * ratelimit for updating the group shares.
810 * default: 0.25ms
812 unsigned int sysctl_sched_shares_ratelimit = 250000;
815 * period over which we measure -rt task cpu usage in us.
816 * default: 1s
818 unsigned int sysctl_sched_rt_period = 1000000;
820 static __read_mostly int scheduler_running;
823 * part of the period that we allow rt tasks to run in us.
824 * default: 0.95s
826 int sysctl_sched_rt_runtime = 950000;
828 static inline u64 global_rt_period(void)
830 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
833 static inline u64 global_rt_runtime(void)
835 if (sysctl_sched_rt_runtime < 0)
836 return RUNTIME_INF;
838 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
841 #ifndef prepare_arch_switch
842 # define prepare_arch_switch(next) do { } while (0)
843 #endif
844 #ifndef finish_arch_switch
845 # define finish_arch_switch(prev) do { } while (0)
846 #endif
848 static inline int task_current(struct rq *rq, struct task_struct *p)
850 return rq->curr == p;
853 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
854 static inline int task_running(struct rq *rq, struct task_struct *p)
856 return task_current(rq, p);
859 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
863 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
865 #ifdef CONFIG_DEBUG_SPINLOCK
866 /* this is a valid case when another task releases the spinlock */
867 rq->lock.owner = current;
868 #endif
870 * If we are tracking spinlock dependencies then we have to
871 * fix up the runqueue lock - which gets 'carried over' from
872 * prev into current:
874 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
876 spin_unlock_irq(&rq->lock);
879 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
880 static inline int task_running(struct rq *rq, struct task_struct *p)
882 #ifdef CONFIG_SMP
883 return p->oncpu;
884 #else
885 return task_current(rq, p);
886 #endif
889 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
891 #ifdef CONFIG_SMP
893 * We can optimise this out completely for !SMP, because the
894 * SMP rebalancing from interrupt is the only thing that cares
895 * here.
897 next->oncpu = 1;
898 #endif
899 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
900 spin_unlock_irq(&rq->lock);
901 #else
902 spin_unlock(&rq->lock);
903 #endif
906 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
908 #ifdef CONFIG_SMP
910 * After ->oncpu is cleared, the task can be moved to a different CPU.
911 * We must ensure this doesn't happen until the switch is completely
912 * finished.
914 smp_wmb();
915 prev->oncpu = 0;
916 #endif
917 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
918 local_irq_enable();
919 #endif
921 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
924 * __task_rq_lock - lock the runqueue a given task resides on.
925 * Must be called interrupts disabled.
927 static inline struct rq *__task_rq_lock(struct task_struct *p)
928 __acquires(rq->lock)
930 for (;;) {
931 struct rq *rq = task_rq(p);
932 spin_lock(&rq->lock);
933 if (likely(rq == task_rq(p)))
934 return rq;
935 spin_unlock(&rq->lock);
940 * task_rq_lock - lock the runqueue a given task resides on and disable
941 * interrupts. Note the ordering: we can safely lookup the task_rq without
942 * explicitly disabling preemption.
944 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
945 __acquires(rq->lock)
947 struct rq *rq;
949 for (;;) {
950 local_irq_save(*flags);
951 rq = task_rq(p);
952 spin_lock(&rq->lock);
953 if (likely(rq == task_rq(p)))
954 return rq;
955 spin_unlock_irqrestore(&rq->lock, *flags);
959 static void __task_rq_unlock(struct rq *rq)
960 __releases(rq->lock)
962 spin_unlock(&rq->lock);
965 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
966 __releases(rq->lock)
968 spin_unlock_irqrestore(&rq->lock, *flags);
972 * this_rq_lock - lock this runqueue and disable interrupts.
974 static struct rq *this_rq_lock(void)
975 __acquires(rq->lock)
977 struct rq *rq;
979 local_irq_disable();
980 rq = this_rq();
981 spin_lock(&rq->lock);
983 return rq;
986 #ifdef CONFIG_SCHED_HRTICK
988 * Use HR-timers to deliver accurate preemption points.
990 * Its all a bit involved since we cannot program an hrt while holding the
991 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
992 * reschedule event.
994 * When we get rescheduled we reprogram the hrtick_timer outside of the
995 * rq->lock.
999 * Use hrtick when:
1000 * - enabled by features
1001 * - hrtimer is actually high res
1003 static inline int hrtick_enabled(struct rq *rq)
1005 if (!sched_feat(HRTICK))
1006 return 0;
1007 if (!cpu_active(cpu_of(rq)))
1008 return 0;
1009 return hrtimer_is_hres_active(&rq->hrtick_timer);
1012 static void hrtick_clear(struct rq *rq)
1014 if (hrtimer_active(&rq->hrtick_timer))
1015 hrtimer_cancel(&rq->hrtick_timer);
1019 * High-resolution timer tick.
1020 * Runs from hardirq context with interrupts disabled.
1022 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1024 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1026 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1028 spin_lock(&rq->lock);
1029 update_rq_clock(rq);
1030 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1031 spin_unlock(&rq->lock);
1033 return HRTIMER_NORESTART;
1036 #ifdef CONFIG_SMP
1038 * called from hardirq (IPI) context
1040 static void __hrtick_start(void *arg)
1042 struct rq *rq = arg;
1044 spin_lock(&rq->lock);
1045 hrtimer_restart(&rq->hrtick_timer);
1046 rq->hrtick_csd_pending = 0;
1047 spin_unlock(&rq->lock);
1051 * Called to set the hrtick timer state.
1053 * called with rq->lock held and irqs disabled
1055 static void hrtick_start(struct rq *rq, u64 delay)
1057 struct hrtimer *timer = &rq->hrtick_timer;
1058 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1060 hrtimer_set_expires(timer, time);
1062 if (rq == this_rq()) {
1063 hrtimer_restart(timer);
1064 } else if (!rq->hrtick_csd_pending) {
1065 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd);
1066 rq->hrtick_csd_pending = 1;
1070 static int
1071 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1073 int cpu = (int)(long)hcpu;
1075 switch (action) {
1076 case CPU_UP_CANCELED:
1077 case CPU_UP_CANCELED_FROZEN:
1078 case CPU_DOWN_PREPARE:
1079 case CPU_DOWN_PREPARE_FROZEN:
1080 case CPU_DEAD:
1081 case CPU_DEAD_FROZEN:
1082 hrtick_clear(cpu_rq(cpu));
1083 return NOTIFY_OK;
1086 return NOTIFY_DONE;
1089 static void init_hrtick(void)
1091 hotcpu_notifier(hotplug_hrtick, 0);
1093 #else
1095 * Called to set the hrtick timer state.
1097 * called with rq->lock held and irqs disabled
1099 static void hrtick_start(struct rq *rq, u64 delay)
1101 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay), HRTIMER_MODE_REL);
1104 static void init_hrtick(void)
1107 #endif /* CONFIG_SMP */
1109 static void init_rq_hrtick(struct rq *rq)
1111 #ifdef CONFIG_SMP
1112 rq->hrtick_csd_pending = 0;
1114 rq->hrtick_csd.flags = 0;
1115 rq->hrtick_csd.func = __hrtick_start;
1116 rq->hrtick_csd.info = rq;
1117 #endif
1119 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1120 rq->hrtick_timer.function = hrtick;
1121 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1123 #else
1124 static inline void hrtick_clear(struct rq *rq)
1128 static inline void init_rq_hrtick(struct rq *rq)
1132 static inline void init_hrtick(void)
1135 #endif
1138 * resched_task - mark a task 'to be rescheduled now'.
1140 * On UP this means the setting of the need_resched flag, on SMP it
1141 * might also involve a cross-CPU call to trigger the scheduler on
1142 * the target CPU.
1144 #ifdef CONFIG_SMP
1146 #ifndef tsk_is_polling
1147 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1148 #endif
1150 static void resched_task(struct task_struct *p)
1152 int cpu;
1154 assert_spin_locked(&task_rq(p)->lock);
1156 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
1157 return;
1159 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
1161 cpu = task_cpu(p);
1162 if (cpu == smp_processor_id())
1163 return;
1165 /* NEED_RESCHED must be visible before we test polling */
1166 smp_mb();
1167 if (!tsk_is_polling(p))
1168 smp_send_reschedule(cpu);
1171 static void resched_cpu(int cpu)
1173 struct rq *rq = cpu_rq(cpu);
1174 unsigned long flags;
1176 if (!spin_trylock_irqsave(&rq->lock, flags))
1177 return;
1178 resched_task(cpu_curr(cpu));
1179 spin_unlock_irqrestore(&rq->lock, flags);
1182 #ifdef CONFIG_NO_HZ
1184 * When add_timer_on() enqueues a timer into the timer wheel of an
1185 * idle CPU then this timer might expire before the next timer event
1186 * which is scheduled to wake up that CPU. In case of a completely
1187 * idle system the next event might even be infinite time into the
1188 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1189 * leaves the inner idle loop so the newly added timer is taken into
1190 * account when the CPU goes back to idle and evaluates the timer
1191 * wheel for the next timer event.
1193 void wake_up_idle_cpu(int cpu)
1195 struct rq *rq = cpu_rq(cpu);
1197 if (cpu == smp_processor_id())
1198 return;
1201 * This is safe, as this function is called with the timer
1202 * wheel base lock of (cpu) held. When the CPU is on the way
1203 * to idle and has not yet set rq->curr to idle then it will
1204 * be serialized on the timer wheel base lock and take the new
1205 * timer into account automatically.
1207 if (rq->curr != rq->idle)
1208 return;
1211 * We can set TIF_RESCHED on the idle task of the other CPU
1212 * lockless. The worst case is that the other CPU runs the
1213 * idle task through an additional NOOP schedule()
1215 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1217 /* NEED_RESCHED must be visible before we test polling */
1218 smp_mb();
1219 if (!tsk_is_polling(rq->idle))
1220 smp_send_reschedule(cpu);
1222 #endif /* CONFIG_NO_HZ */
1224 #else /* !CONFIG_SMP */
1225 static void resched_task(struct task_struct *p)
1227 assert_spin_locked(&task_rq(p)->lock);
1228 set_tsk_need_resched(p);
1230 #endif /* CONFIG_SMP */
1232 #if BITS_PER_LONG == 32
1233 # define WMULT_CONST (~0UL)
1234 #else
1235 # define WMULT_CONST (1UL << 32)
1236 #endif
1238 #define WMULT_SHIFT 32
1241 * Shift right and round:
1243 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1246 * delta *= weight / lw
1248 static unsigned long
1249 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1250 struct load_weight *lw)
1252 u64 tmp;
1254 if (!lw->inv_weight) {
1255 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1256 lw->inv_weight = 1;
1257 else
1258 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1259 / (lw->weight+1);
1262 tmp = (u64)delta_exec * weight;
1264 * Check whether we'd overflow the 64-bit multiplication:
1266 if (unlikely(tmp > WMULT_CONST))
1267 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1268 WMULT_SHIFT/2);
1269 else
1270 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1272 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1275 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1277 lw->weight += inc;
1278 lw->inv_weight = 0;
1281 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1283 lw->weight -= dec;
1284 lw->inv_weight = 0;
1288 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1289 * of tasks with abnormal "nice" values across CPUs the contribution that
1290 * each task makes to its run queue's load is weighted according to its
1291 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1292 * scaled version of the new time slice allocation that they receive on time
1293 * slice expiry etc.
1296 #define WEIGHT_IDLEPRIO 2
1297 #define WMULT_IDLEPRIO (1 << 31)
1300 * Nice levels are multiplicative, with a gentle 10% change for every
1301 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1302 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1303 * that remained on nice 0.
1305 * The "10% effect" is relative and cumulative: from _any_ nice level,
1306 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1307 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1308 * If a task goes up by ~10% and another task goes down by ~10% then
1309 * the relative distance between them is ~25%.)
1311 static const int prio_to_weight[40] = {
1312 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1313 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1314 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1315 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1316 /* 0 */ 1024, 820, 655, 526, 423,
1317 /* 5 */ 335, 272, 215, 172, 137,
1318 /* 10 */ 110, 87, 70, 56, 45,
1319 /* 15 */ 36, 29, 23, 18, 15,
1323 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1325 * In cases where the weight does not change often, we can use the
1326 * precalculated inverse to speed up arithmetics by turning divisions
1327 * into multiplications:
1329 static const u32 prio_to_wmult[40] = {
1330 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1331 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1332 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1333 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1334 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1335 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1336 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1337 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1340 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1343 * runqueue iterator, to support SMP load-balancing between different
1344 * scheduling classes, without having to expose their internal data
1345 * structures to the load-balancing proper:
1347 struct rq_iterator {
1348 void *arg;
1349 struct task_struct *(*start)(void *);
1350 struct task_struct *(*next)(void *);
1353 #ifdef CONFIG_SMP
1354 static unsigned long
1355 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1356 unsigned long max_load_move, struct sched_domain *sd,
1357 enum cpu_idle_type idle, int *all_pinned,
1358 int *this_best_prio, struct rq_iterator *iterator);
1360 static int
1361 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1362 struct sched_domain *sd, enum cpu_idle_type idle,
1363 struct rq_iterator *iterator);
1364 #endif
1366 #ifdef CONFIG_CGROUP_CPUACCT
1367 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1368 #else
1369 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1370 #endif
1372 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1374 update_load_add(&rq->load, load);
1377 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1379 update_load_sub(&rq->load, load);
1382 #ifdef CONFIG_SMP
1383 static unsigned long source_load(int cpu, int type);
1384 static unsigned long target_load(int cpu, int type);
1385 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1387 static unsigned long cpu_avg_load_per_task(int cpu)
1389 struct rq *rq = cpu_rq(cpu);
1391 if (rq->nr_running)
1392 rq->avg_load_per_task = rq->load.weight / rq->nr_running;
1394 return rq->avg_load_per_task;
1397 #ifdef CONFIG_FAIR_GROUP_SCHED
1399 typedef void (*tg_visitor)(struct task_group *, int, struct sched_domain *);
1402 * Iterate the full tree, calling @down when first entering a node and @up when
1403 * leaving it for the final time.
1405 static void
1406 walk_tg_tree(tg_visitor down, tg_visitor up, int cpu, struct sched_domain *sd)
1408 struct task_group *parent, *child;
1410 rcu_read_lock();
1411 parent = &root_task_group;
1412 down:
1413 (*down)(parent, cpu, sd);
1414 list_for_each_entry_rcu(child, &parent->children, siblings) {
1415 parent = child;
1416 goto down;
1419 continue;
1421 (*up)(parent, cpu, sd);
1423 child = parent;
1424 parent = parent->parent;
1425 if (parent)
1426 goto up;
1427 rcu_read_unlock();
1430 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1433 * Calculate and set the cpu's group shares.
1435 static void
1436 __update_group_shares_cpu(struct task_group *tg, int cpu,
1437 unsigned long sd_shares, unsigned long sd_rq_weight)
1439 int boost = 0;
1440 unsigned long shares;
1441 unsigned long rq_weight;
1443 if (!tg->se[cpu])
1444 return;
1446 rq_weight = tg->cfs_rq[cpu]->load.weight;
1449 * If there are currently no tasks on the cpu pretend there is one of
1450 * average load so that when a new task gets to run here it will not
1451 * get delayed by group starvation.
1453 if (!rq_weight) {
1454 boost = 1;
1455 rq_weight = NICE_0_LOAD;
1458 if (unlikely(rq_weight > sd_rq_weight))
1459 rq_weight = sd_rq_weight;
1462 * \Sum shares * rq_weight
1463 * shares = -----------------------
1464 * \Sum rq_weight
1467 shares = (sd_shares * rq_weight) / (sd_rq_weight + 1);
1470 * record the actual number of shares, not the boosted amount.
1472 tg->cfs_rq[cpu]->shares = boost ? 0 : shares;
1473 tg->cfs_rq[cpu]->rq_weight = rq_weight;
1475 if (shares < MIN_SHARES)
1476 shares = MIN_SHARES;
1477 else if (shares > MAX_SHARES)
1478 shares = MAX_SHARES;
1480 __set_se_shares(tg->se[cpu], shares);
1484 * Re-compute the task group their per cpu shares over the given domain.
1485 * This needs to be done in a bottom-up fashion because the rq weight of a
1486 * parent group depends on the shares of its child groups.
1488 static void
1489 tg_shares_up(struct task_group *tg, int cpu, struct sched_domain *sd)
1491 unsigned long rq_weight = 0;
1492 unsigned long shares = 0;
1493 int i;
1495 for_each_cpu_mask(i, sd->span) {
1496 rq_weight += tg->cfs_rq[i]->load.weight;
1497 shares += tg->cfs_rq[i]->shares;
1500 if ((!shares && rq_weight) || shares > tg->shares)
1501 shares = tg->shares;
1503 if (!sd->parent || !(sd->parent->flags & SD_LOAD_BALANCE))
1504 shares = tg->shares;
1506 if (!rq_weight)
1507 rq_weight = cpus_weight(sd->span) * NICE_0_LOAD;
1509 for_each_cpu_mask(i, sd->span) {
1510 struct rq *rq = cpu_rq(i);
1511 unsigned long flags;
1513 spin_lock_irqsave(&rq->lock, flags);
1514 __update_group_shares_cpu(tg, i, shares, rq_weight);
1515 spin_unlock_irqrestore(&rq->lock, flags);
1520 * Compute the cpu's hierarchical load factor for each task group.
1521 * This needs to be done in a top-down fashion because the load of a child
1522 * group is a fraction of its parents load.
1524 static void
1525 tg_load_down(struct task_group *tg, int cpu, struct sched_domain *sd)
1527 unsigned long load;
1529 if (!tg->parent) {
1530 load = cpu_rq(cpu)->load.weight;
1531 } else {
1532 load = tg->parent->cfs_rq[cpu]->h_load;
1533 load *= tg->cfs_rq[cpu]->shares;
1534 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1537 tg->cfs_rq[cpu]->h_load = load;
1540 static void
1541 tg_nop(struct task_group *tg, int cpu, struct sched_domain *sd)
1545 static void update_shares(struct sched_domain *sd)
1547 u64 now = cpu_clock(raw_smp_processor_id());
1548 s64 elapsed = now - sd->last_update;
1550 if (elapsed >= (s64)(u64)sysctl_sched_shares_ratelimit) {
1551 sd->last_update = now;
1552 walk_tg_tree(tg_nop, tg_shares_up, 0, sd);
1556 static void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1558 spin_unlock(&rq->lock);
1559 update_shares(sd);
1560 spin_lock(&rq->lock);
1563 static void update_h_load(int cpu)
1565 walk_tg_tree(tg_load_down, tg_nop, cpu, NULL);
1568 #else
1570 static inline void update_shares(struct sched_domain *sd)
1574 static inline void update_shares_locked(struct rq *rq, struct sched_domain *sd)
1578 #endif
1580 #endif
1582 #ifdef CONFIG_FAIR_GROUP_SCHED
1583 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1585 #ifdef CONFIG_SMP
1586 cfs_rq->shares = shares;
1587 #endif
1589 #endif
1591 #include "sched_stats.h"
1592 #include "sched_idletask.c"
1593 #include "sched_fair.c"
1594 #include "sched_rt.c"
1595 #ifdef CONFIG_SCHED_DEBUG
1596 # include "sched_debug.c"
1597 #endif
1599 #define sched_class_highest (&rt_sched_class)
1600 #define for_each_class(class) \
1601 for (class = sched_class_highest; class; class = class->next)
1603 static void inc_nr_running(struct rq *rq)
1605 rq->nr_running++;
1608 static void dec_nr_running(struct rq *rq)
1610 rq->nr_running--;
1613 static void set_load_weight(struct task_struct *p)
1615 if (task_has_rt_policy(p)) {
1616 p->se.load.weight = prio_to_weight[0] * 2;
1617 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1618 return;
1622 * SCHED_IDLE tasks get minimal weight:
1624 if (p->policy == SCHED_IDLE) {
1625 p->se.load.weight = WEIGHT_IDLEPRIO;
1626 p->se.load.inv_weight = WMULT_IDLEPRIO;
1627 return;
1630 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1631 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1634 static void update_avg(u64 *avg, u64 sample)
1636 s64 diff = sample - *avg;
1637 *avg += diff >> 3;
1640 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1642 sched_info_queued(p);
1643 p->sched_class->enqueue_task(rq, p, wakeup);
1644 p->se.on_rq = 1;
1647 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1649 if (sleep && p->se.last_wakeup) {
1650 update_avg(&p->se.avg_overlap,
1651 p->se.sum_exec_runtime - p->se.last_wakeup);
1652 p->se.last_wakeup = 0;
1655 sched_info_dequeued(p);
1656 p->sched_class->dequeue_task(rq, p, sleep);
1657 p->se.on_rq = 0;
1661 * __normal_prio - return the priority that is based on the static prio
1663 static inline int __normal_prio(struct task_struct *p)
1665 return p->static_prio;
1669 * Calculate the expected normal priority: i.e. priority
1670 * without taking RT-inheritance into account. Might be
1671 * boosted by interactivity modifiers. Changes upon fork,
1672 * setprio syscalls, and whenever the interactivity
1673 * estimator recalculates.
1675 static inline int normal_prio(struct task_struct *p)
1677 int prio;
1679 if (task_has_rt_policy(p))
1680 prio = MAX_RT_PRIO-1 - p->rt_priority;
1681 else
1682 prio = __normal_prio(p);
1683 return prio;
1687 * Calculate the current priority, i.e. the priority
1688 * taken into account by the scheduler. This value might
1689 * be boosted by RT tasks, or might be boosted by
1690 * interactivity modifiers. Will be RT if the task got
1691 * RT-boosted. If not then it returns p->normal_prio.
1693 static int effective_prio(struct task_struct *p)
1695 p->normal_prio = normal_prio(p);
1697 * If we are RT tasks or we were boosted to RT priority,
1698 * keep the priority unchanged. Otherwise, update priority
1699 * to the normal priority:
1701 if (!rt_prio(p->prio))
1702 return p->normal_prio;
1703 return p->prio;
1707 * activate_task - move a task to the runqueue.
1709 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1711 if (task_contributes_to_load(p))
1712 rq->nr_uninterruptible--;
1714 enqueue_task(rq, p, wakeup);
1715 inc_nr_running(rq);
1719 * deactivate_task - remove a task from the runqueue.
1721 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1723 if (task_contributes_to_load(p))
1724 rq->nr_uninterruptible++;
1726 dequeue_task(rq, p, sleep);
1727 dec_nr_running(rq);
1731 * task_curr - is this task currently executing on a CPU?
1732 * @p: the task in question.
1734 inline int task_curr(const struct task_struct *p)
1736 return cpu_curr(task_cpu(p)) == p;
1739 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1741 set_task_rq(p, cpu);
1742 #ifdef CONFIG_SMP
1744 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1745 * successfuly executed on another CPU. We must ensure that updates of
1746 * per-task data have been completed by this moment.
1748 smp_wmb();
1749 task_thread_info(p)->cpu = cpu;
1750 #endif
1753 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1754 const struct sched_class *prev_class,
1755 int oldprio, int running)
1757 if (prev_class != p->sched_class) {
1758 if (prev_class->switched_from)
1759 prev_class->switched_from(rq, p, running);
1760 p->sched_class->switched_to(rq, p, running);
1761 } else
1762 p->sched_class->prio_changed(rq, p, oldprio, running);
1765 #ifdef CONFIG_SMP
1767 /* Used instead of source_load when we know the type == 0 */
1768 static unsigned long weighted_cpuload(const int cpu)
1770 return cpu_rq(cpu)->load.weight;
1774 * Is this task likely cache-hot:
1776 static int
1777 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1779 s64 delta;
1782 * Buddy candidates are cache hot:
1784 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
1785 return 1;
1787 if (p->sched_class != &fair_sched_class)
1788 return 0;
1790 if (sysctl_sched_migration_cost == -1)
1791 return 1;
1792 if (sysctl_sched_migration_cost == 0)
1793 return 0;
1795 delta = now - p->se.exec_start;
1797 return delta < (s64)sysctl_sched_migration_cost;
1801 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1803 int old_cpu = task_cpu(p);
1804 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1805 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1806 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1807 u64 clock_offset;
1809 clock_offset = old_rq->clock - new_rq->clock;
1811 #ifdef CONFIG_SCHEDSTATS
1812 if (p->se.wait_start)
1813 p->se.wait_start -= clock_offset;
1814 if (p->se.sleep_start)
1815 p->se.sleep_start -= clock_offset;
1816 if (p->se.block_start)
1817 p->se.block_start -= clock_offset;
1818 if (old_cpu != new_cpu) {
1819 schedstat_inc(p, se.nr_migrations);
1820 if (task_hot(p, old_rq->clock, NULL))
1821 schedstat_inc(p, se.nr_forced2_migrations);
1823 #endif
1824 p->se.vruntime -= old_cfsrq->min_vruntime -
1825 new_cfsrq->min_vruntime;
1827 __set_task_cpu(p, new_cpu);
1830 struct migration_req {
1831 struct list_head list;
1833 struct task_struct *task;
1834 int dest_cpu;
1836 struct completion done;
1840 * The task's runqueue lock must be held.
1841 * Returns true if you have to wait for migration thread.
1843 static int
1844 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1846 struct rq *rq = task_rq(p);
1849 * If the task is not on a runqueue (and not running), then
1850 * it is sufficient to simply update the task's cpu field.
1852 if (!p->se.on_rq && !task_running(rq, p)) {
1853 set_task_cpu(p, dest_cpu);
1854 return 0;
1857 init_completion(&req->done);
1858 req->task = p;
1859 req->dest_cpu = dest_cpu;
1860 list_add(&req->list, &rq->migration_queue);
1862 return 1;
1866 * wait_task_inactive - wait for a thread to unschedule.
1868 * If @match_state is nonzero, it's the @p->state value just checked and
1869 * not expected to change. If it changes, i.e. @p might have woken up,
1870 * then return zero. When we succeed in waiting for @p to be off its CPU,
1871 * we return a positive number (its total switch count). If a second call
1872 * a short while later returns the same number, the caller can be sure that
1873 * @p has remained unscheduled the whole time.
1875 * The caller must ensure that the task *will* unschedule sometime soon,
1876 * else this function might spin for a *long* time. This function can't
1877 * be called with interrupts off, or it may introduce deadlock with
1878 * smp_call_function() if an IPI is sent by the same process we are
1879 * waiting to become inactive.
1881 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1883 unsigned long flags;
1884 int running, on_rq;
1885 unsigned long ncsw;
1886 struct rq *rq;
1888 for (;;) {
1890 * We do the initial early heuristics without holding
1891 * any task-queue locks at all. We'll only try to get
1892 * the runqueue lock when things look like they will
1893 * work out!
1895 rq = task_rq(p);
1898 * If the task is actively running on another CPU
1899 * still, just relax and busy-wait without holding
1900 * any locks.
1902 * NOTE! Since we don't hold any locks, it's not
1903 * even sure that "rq" stays as the right runqueue!
1904 * But we don't care, since "task_running()" will
1905 * return false if the runqueue has changed and p
1906 * is actually now running somewhere else!
1908 while (task_running(rq, p)) {
1909 if (match_state && unlikely(p->state != match_state))
1910 return 0;
1911 cpu_relax();
1915 * Ok, time to look more closely! We need the rq
1916 * lock now, to be *sure*. If we're wrong, we'll
1917 * just go back and repeat.
1919 rq = task_rq_lock(p, &flags);
1920 running = task_running(rq, p);
1921 on_rq = p->se.on_rq;
1922 ncsw = 0;
1923 if (!match_state || p->state == match_state) {
1924 ncsw = p->nivcsw + p->nvcsw;
1925 if (unlikely(!ncsw))
1926 ncsw = 1;
1928 task_rq_unlock(rq, &flags);
1931 * If it changed from the expected state, bail out now.
1933 if (unlikely(!ncsw))
1934 break;
1937 * Was it really running after all now that we
1938 * checked with the proper locks actually held?
1940 * Oops. Go back and try again..
1942 if (unlikely(running)) {
1943 cpu_relax();
1944 continue;
1948 * It's not enough that it's not actively running,
1949 * it must be off the runqueue _entirely_, and not
1950 * preempted!
1952 * So if it wa still runnable (but just not actively
1953 * running right now), it's preempted, and we should
1954 * yield - it could be a while.
1956 if (unlikely(on_rq)) {
1957 schedule_timeout_uninterruptible(1);
1958 continue;
1962 * Ahh, all good. It wasn't running, and it wasn't
1963 * runnable, which means that it will never become
1964 * running in the future either. We're all done!
1966 break;
1969 return ncsw;
1972 /***
1973 * kick_process - kick a running thread to enter/exit the kernel
1974 * @p: the to-be-kicked thread
1976 * Cause a process which is running on another CPU to enter
1977 * kernel-mode, without any delay. (to get signals handled.)
1979 * NOTE: this function doesnt have to take the runqueue lock,
1980 * because all it wants to ensure is that the remote task enters
1981 * the kernel. If the IPI races and the task has been migrated
1982 * to another CPU then no harm is done and the purpose has been
1983 * achieved as well.
1985 void kick_process(struct task_struct *p)
1987 int cpu;
1989 preempt_disable();
1990 cpu = task_cpu(p);
1991 if ((cpu != smp_processor_id()) && task_curr(p))
1992 smp_send_reschedule(cpu);
1993 preempt_enable();
1997 * Return a low guess at the load of a migration-source cpu weighted
1998 * according to the scheduling class and "nice" value.
2000 * We want to under-estimate the load of migration sources, to
2001 * balance conservatively.
2003 static unsigned long source_load(int cpu, int type)
2005 struct rq *rq = cpu_rq(cpu);
2006 unsigned long total = weighted_cpuload(cpu);
2008 if (type == 0 || !sched_feat(LB_BIAS))
2009 return total;
2011 return min(rq->cpu_load[type-1], total);
2015 * Return a high guess at the load of a migration-target cpu weighted
2016 * according to the scheduling class and "nice" value.
2018 static unsigned long target_load(int cpu, int type)
2020 struct rq *rq = cpu_rq(cpu);
2021 unsigned long total = weighted_cpuload(cpu);
2023 if (type == 0 || !sched_feat(LB_BIAS))
2024 return total;
2026 return max(rq->cpu_load[type-1], total);
2030 * find_idlest_group finds and returns the least busy CPU group within the
2031 * domain.
2033 static struct sched_group *
2034 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2036 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2037 unsigned long min_load = ULONG_MAX, this_load = 0;
2038 int load_idx = sd->forkexec_idx;
2039 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2041 do {
2042 unsigned long load, avg_load;
2043 int local_group;
2044 int i;
2046 /* Skip over this group if it has no CPUs allowed */
2047 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2048 continue;
2050 local_group = cpu_isset(this_cpu, group->cpumask);
2052 /* Tally up the load of all CPUs in the group */
2053 avg_load = 0;
2055 for_each_cpu_mask_nr(i, group->cpumask) {
2056 /* Bias balancing toward cpus of our domain */
2057 if (local_group)
2058 load = source_load(i, load_idx);
2059 else
2060 load = target_load(i, load_idx);
2062 avg_load += load;
2065 /* Adjust by relative CPU power of the group */
2066 avg_load = sg_div_cpu_power(group,
2067 avg_load * SCHED_LOAD_SCALE);
2069 if (local_group) {
2070 this_load = avg_load;
2071 this = group;
2072 } else if (avg_load < min_load) {
2073 min_load = avg_load;
2074 idlest = group;
2076 } while (group = group->next, group != sd->groups);
2078 if (!idlest || 100*this_load < imbalance*min_load)
2079 return NULL;
2080 return idlest;
2084 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2086 static int
2087 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2088 cpumask_t *tmp)
2090 unsigned long load, min_load = ULONG_MAX;
2091 int idlest = -1;
2092 int i;
2094 /* Traverse only the allowed CPUs */
2095 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2097 for_each_cpu_mask_nr(i, *tmp) {
2098 load = weighted_cpuload(i);
2100 if (load < min_load || (load == min_load && i == this_cpu)) {
2101 min_load = load;
2102 idlest = i;
2106 return idlest;
2110 * sched_balance_self: balance the current task (running on cpu) in domains
2111 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2112 * SD_BALANCE_EXEC.
2114 * Balance, ie. select the least loaded group.
2116 * Returns the target CPU number, or the same CPU if no balancing is needed.
2118 * preempt must be disabled.
2120 static int sched_balance_self(int cpu, int flag)
2122 struct task_struct *t = current;
2123 struct sched_domain *tmp, *sd = NULL;
2125 for_each_domain(cpu, tmp) {
2127 * If power savings logic is enabled for a domain, stop there.
2129 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2130 break;
2131 if (tmp->flags & flag)
2132 sd = tmp;
2135 if (sd)
2136 update_shares(sd);
2138 while (sd) {
2139 cpumask_t span, tmpmask;
2140 struct sched_group *group;
2141 int new_cpu, weight;
2143 if (!(sd->flags & flag)) {
2144 sd = sd->child;
2145 continue;
2148 span = sd->span;
2149 group = find_idlest_group(sd, t, cpu);
2150 if (!group) {
2151 sd = sd->child;
2152 continue;
2155 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2156 if (new_cpu == -1 || new_cpu == cpu) {
2157 /* Now try balancing at a lower domain level of cpu */
2158 sd = sd->child;
2159 continue;
2162 /* Now try balancing at a lower domain level of new_cpu */
2163 cpu = new_cpu;
2164 sd = NULL;
2165 weight = cpus_weight(span);
2166 for_each_domain(cpu, tmp) {
2167 if (weight <= cpus_weight(tmp->span))
2168 break;
2169 if (tmp->flags & flag)
2170 sd = tmp;
2172 /* while loop will break here if sd == NULL */
2175 return cpu;
2178 #endif /* CONFIG_SMP */
2180 /***
2181 * try_to_wake_up - wake up a thread
2182 * @p: the to-be-woken-up thread
2183 * @state: the mask of task states that can be woken
2184 * @sync: do a synchronous wakeup?
2186 * Put it on the run-queue if it's not already there. The "current"
2187 * thread is always on the run-queue (except when the actual
2188 * re-schedule is in progress), and as such you're allowed to do
2189 * the simpler "current->state = TASK_RUNNING" to mark yourself
2190 * runnable without the overhead of this.
2192 * returns failure only if the task is already active.
2194 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2196 int cpu, orig_cpu, this_cpu, success = 0;
2197 unsigned long flags;
2198 long old_state;
2199 struct rq *rq;
2201 if (!sched_feat(SYNC_WAKEUPS))
2202 sync = 0;
2204 #ifdef CONFIG_SMP
2205 if (sched_feat(LB_WAKEUP_UPDATE)) {
2206 struct sched_domain *sd;
2208 this_cpu = raw_smp_processor_id();
2209 cpu = task_cpu(p);
2211 for_each_domain(this_cpu, sd) {
2212 if (cpu_isset(cpu, sd->span)) {
2213 update_shares(sd);
2214 break;
2218 #endif
2220 smp_wmb();
2221 rq = task_rq_lock(p, &flags);
2222 old_state = p->state;
2223 if (!(old_state & state))
2224 goto out;
2226 if (p->se.on_rq)
2227 goto out_running;
2229 cpu = task_cpu(p);
2230 orig_cpu = cpu;
2231 this_cpu = smp_processor_id();
2233 #ifdef CONFIG_SMP
2234 if (unlikely(task_running(rq, p)))
2235 goto out_activate;
2237 cpu = p->sched_class->select_task_rq(p, sync);
2238 if (cpu != orig_cpu) {
2239 set_task_cpu(p, cpu);
2240 task_rq_unlock(rq, &flags);
2241 /* might preempt at this point */
2242 rq = task_rq_lock(p, &flags);
2243 old_state = p->state;
2244 if (!(old_state & state))
2245 goto out;
2246 if (p->se.on_rq)
2247 goto out_running;
2249 this_cpu = smp_processor_id();
2250 cpu = task_cpu(p);
2253 #ifdef CONFIG_SCHEDSTATS
2254 schedstat_inc(rq, ttwu_count);
2255 if (cpu == this_cpu)
2256 schedstat_inc(rq, ttwu_local);
2257 else {
2258 struct sched_domain *sd;
2259 for_each_domain(this_cpu, sd) {
2260 if (cpu_isset(cpu, sd->span)) {
2261 schedstat_inc(sd, ttwu_wake_remote);
2262 break;
2266 #endif /* CONFIG_SCHEDSTATS */
2268 out_activate:
2269 #endif /* CONFIG_SMP */
2270 schedstat_inc(p, se.nr_wakeups);
2271 if (sync)
2272 schedstat_inc(p, se.nr_wakeups_sync);
2273 if (orig_cpu != cpu)
2274 schedstat_inc(p, se.nr_wakeups_migrate);
2275 if (cpu == this_cpu)
2276 schedstat_inc(p, se.nr_wakeups_local);
2277 else
2278 schedstat_inc(p, se.nr_wakeups_remote);
2279 update_rq_clock(rq);
2280 activate_task(rq, p, 1);
2281 success = 1;
2283 out_running:
2284 trace_mark(kernel_sched_wakeup,
2285 "pid %d state %ld ## rq %p task %p rq->curr %p",
2286 p->pid, p->state, rq, p, rq->curr);
2287 check_preempt_curr(rq, p);
2289 p->state = TASK_RUNNING;
2290 #ifdef CONFIG_SMP
2291 if (p->sched_class->task_wake_up)
2292 p->sched_class->task_wake_up(rq, p);
2293 #endif
2294 out:
2295 current->se.last_wakeup = current->se.sum_exec_runtime;
2297 task_rq_unlock(rq, &flags);
2299 return success;
2302 int wake_up_process(struct task_struct *p)
2304 return try_to_wake_up(p, TASK_ALL, 0);
2306 EXPORT_SYMBOL(wake_up_process);
2308 int wake_up_state(struct task_struct *p, unsigned int state)
2310 return try_to_wake_up(p, state, 0);
2314 * Perform scheduler related setup for a newly forked process p.
2315 * p is forked by current.
2317 * __sched_fork() is basic setup used by init_idle() too:
2319 static void __sched_fork(struct task_struct *p)
2321 p->se.exec_start = 0;
2322 p->se.sum_exec_runtime = 0;
2323 p->se.prev_sum_exec_runtime = 0;
2324 p->se.last_wakeup = 0;
2325 p->se.avg_overlap = 0;
2327 #ifdef CONFIG_SCHEDSTATS
2328 p->se.wait_start = 0;
2329 p->se.sum_sleep_runtime = 0;
2330 p->se.sleep_start = 0;
2331 p->se.block_start = 0;
2332 p->se.sleep_max = 0;
2333 p->se.block_max = 0;
2334 p->se.exec_max = 0;
2335 p->se.slice_max = 0;
2336 p->se.wait_max = 0;
2337 #endif
2339 INIT_LIST_HEAD(&p->rt.run_list);
2340 p->se.on_rq = 0;
2341 INIT_LIST_HEAD(&p->se.group_node);
2343 #ifdef CONFIG_PREEMPT_NOTIFIERS
2344 INIT_HLIST_HEAD(&p->preempt_notifiers);
2345 #endif
2348 * We mark the process as running here, but have not actually
2349 * inserted it onto the runqueue yet. This guarantees that
2350 * nobody will actually run it, and a signal or other external
2351 * event cannot wake it up and insert it on the runqueue either.
2353 p->state = TASK_RUNNING;
2357 * fork()/clone()-time setup:
2359 void sched_fork(struct task_struct *p, int clone_flags)
2361 int cpu = get_cpu();
2363 __sched_fork(p);
2365 #ifdef CONFIG_SMP
2366 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2367 #endif
2368 set_task_cpu(p, cpu);
2371 * Make sure we do not leak PI boosting priority to the child:
2373 p->prio = current->normal_prio;
2374 if (!rt_prio(p->prio))
2375 p->sched_class = &fair_sched_class;
2377 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2378 if (likely(sched_info_on()))
2379 memset(&p->sched_info, 0, sizeof(p->sched_info));
2380 #endif
2381 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2382 p->oncpu = 0;
2383 #endif
2384 #ifdef CONFIG_PREEMPT
2385 /* Want to start with kernel preemption disabled. */
2386 task_thread_info(p)->preempt_count = 1;
2387 #endif
2388 put_cpu();
2392 * wake_up_new_task - wake up a newly created task for the first time.
2394 * This function will do some initial scheduler statistics housekeeping
2395 * that must be done for every newly created context, then puts the task
2396 * on the runqueue and wakes it.
2398 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2400 unsigned long flags;
2401 struct rq *rq;
2403 rq = task_rq_lock(p, &flags);
2404 BUG_ON(p->state != TASK_RUNNING);
2405 update_rq_clock(rq);
2407 p->prio = effective_prio(p);
2409 if (!p->sched_class->task_new || !current->se.on_rq) {
2410 activate_task(rq, p, 0);
2411 } else {
2413 * Let the scheduling class do new task startup
2414 * management (if any):
2416 p->sched_class->task_new(rq, p);
2417 inc_nr_running(rq);
2419 trace_mark(kernel_sched_wakeup_new,
2420 "pid %d state %ld ## rq %p task %p rq->curr %p",
2421 p->pid, p->state, rq, p, rq->curr);
2422 check_preempt_curr(rq, p);
2423 #ifdef CONFIG_SMP
2424 if (p->sched_class->task_wake_up)
2425 p->sched_class->task_wake_up(rq, p);
2426 #endif
2427 task_rq_unlock(rq, &flags);
2430 #ifdef CONFIG_PREEMPT_NOTIFIERS
2433 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2434 * @notifier: notifier struct to register
2436 void preempt_notifier_register(struct preempt_notifier *notifier)
2438 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2440 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2443 * preempt_notifier_unregister - no longer interested in preemption notifications
2444 * @notifier: notifier struct to unregister
2446 * This is safe to call from within a preemption notifier.
2448 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2450 hlist_del(&notifier->link);
2452 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2454 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2456 struct preempt_notifier *notifier;
2457 struct hlist_node *node;
2459 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2460 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2463 static void
2464 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2465 struct task_struct *next)
2467 struct preempt_notifier *notifier;
2468 struct hlist_node *node;
2470 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2471 notifier->ops->sched_out(notifier, next);
2474 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2476 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2480 static void
2481 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2482 struct task_struct *next)
2486 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2489 * prepare_task_switch - prepare to switch tasks
2490 * @rq: the runqueue preparing to switch
2491 * @prev: the current task that is being switched out
2492 * @next: the task we are going to switch to.
2494 * This is called with the rq lock held and interrupts off. It must
2495 * be paired with a subsequent finish_task_switch after the context
2496 * switch.
2498 * prepare_task_switch sets up locking and calls architecture specific
2499 * hooks.
2501 static inline void
2502 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2503 struct task_struct *next)
2505 fire_sched_out_preempt_notifiers(prev, next);
2506 prepare_lock_switch(rq, next);
2507 prepare_arch_switch(next);
2511 * finish_task_switch - clean up after a task-switch
2512 * @rq: runqueue associated with task-switch
2513 * @prev: the thread we just switched away from.
2515 * finish_task_switch must be called after the context switch, paired
2516 * with a prepare_task_switch call before the context switch.
2517 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2518 * and do any other architecture-specific cleanup actions.
2520 * Note that we may have delayed dropping an mm in context_switch(). If
2521 * so, we finish that here outside of the runqueue lock. (Doing it
2522 * with the lock held can cause deadlocks; see schedule() for
2523 * details.)
2525 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2526 __releases(rq->lock)
2528 struct mm_struct *mm = rq->prev_mm;
2529 long prev_state;
2531 rq->prev_mm = NULL;
2534 * A task struct has one reference for the use as "current".
2535 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2536 * schedule one last time. The schedule call will never return, and
2537 * the scheduled task must drop that reference.
2538 * The test for TASK_DEAD must occur while the runqueue locks are
2539 * still held, otherwise prev could be scheduled on another cpu, die
2540 * there before we look at prev->state, and then the reference would
2541 * be dropped twice.
2542 * Manfred Spraul <manfred@colorfullife.com>
2544 prev_state = prev->state;
2545 finish_arch_switch(prev);
2546 finish_lock_switch(rq, prev);
2547 #ifdef CONFIG_SMP
2548 if (current->sched_class->post_schedule)
2549 current->sched_class->post_schedule(rq);
2550 #endif
2552 fire_sched_in_preempt_notifiers(current);
2553 if (mm)
2554 mmdrop(mm);
2555 if (unlikely(prev_state == TASK_DEAD)) {
2557 * Remove function-return probe instances associated with this
2558 * task and put them back on the free list.
2560 kprobe_flush_task(prev);
2561 put_task_struct(prev);
2566 * schedule_tail - first thing a freshly forked thread must call.
2567 * @prev: the thread we just switched away from.
2569 asmlinkage void schedule_tail(struct task_struct *prev)
2570 __releases(rq->lock)
2572 struct rq *rq = this_rq();
2574 finish_task_switch(rq, prev);
2575 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2576 /* In this case, finish_task_switch does not reenable preemption */
2577 preempt_enable();
2578 #endif
2579 if (current->set_child_tid)
2580 put_user(task_pid_vnr(current), current->set_child_tid);
2584 * context_switch - switch to the new MM and the new
2585 * thread's register state.
2587 static inline void
2588 context_switch(struct rq *rq, struct task_struct *prev,
2589 struct task_struct *next)
2591 struct mm_struct *mm, *oldmm;
2593 prepare_task_switch(rq, prev, next);
2594 trace_mark(kernel_sched_schedule,
2595 "prev_pid %d next_pid %d prev_state %ld "
2596 "## rq %p prev %p next %p",
2597 prev->pid, next->pid, prev->state,
2598 rq, prev, next);
2599 mm = next->mm;
2600 oldmm = prev->active_mm;
2602 * For paravirt, this is coupled with an exit in switch_to to
2603 * combine the page table reload and the switch backend into
2604 * one hypercall.
2606 arch_enter_lazy_cpu_mode();
2608 if (unlikely(!mm)) {
2609 next->active_mm = oldmm;
2610 atomic_inc(&oldmm->mm_count);
2611 enter_lazy_tlb(oldmm, next);
2612 } else
2613 switch_mm(oldmm, mm, next);
2615 if (unlikely(!prev->mm)) {
2616 prev->active_mm = NULL;
2617 rq->prev_mm = oldmm;
2620 * Since the runqueue lock will be released by the next
2621 * task (which is an invalid locking op but in the case
2622 * of the scheduler it's an obvious special-case), so we
2623 * do an early lockdep release here:
2625 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2626 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2627 #endif
2629 /* Here we just switch the register state and the stack. */
2630 switch_to(prev, next, prev);
2632 barrier();
2634 * this_rq must be evaluated again because prev may have moved
2635 * CPUs since it called schedule(), thus the 'rq' on its stack
2636 * frame will be invalid.
2638 finish_task_switch(this_rq(), prev);
2642 * nr_running, nr_uninterruptible and nr_context_switches:
2644 * externally visible scheduler statistics: current number of runnable
2645 * threads, current number of uninterruptible-sleeping threads, total
2646 * number of context switches performed since bootup.
2648 unsigned long nr_running(void)
2650 unsigned long i, sum = 0;
2652 for_each_online_cpu(i)
2653 sum += cpu_rq(i)->nr_running;
2655 return sum;
2658 unsigned long nr_uninterruptible(void)
2660 unsigned long i, sum = 0;
2662 for_each_possible_cpu(i)
2663 sum += cpu_rq(i)->nr_uninterruptible;
2666 * Since we read the counters lockless, it might be slightly
2667 * inaccurate. Do not allow it to go below zero though:
2669 if (unlikely((long)sum < 0))
2670 sum = 0;
2672 return sum;
2675 unsigned long long nr_context_switches(void)
2677 int i;
2678 unsigned long long sum = 0;
2680 for_each_possible_cpu(i)
2681 sum += cpu_rq(i)->nr_switches;
2683 return sum;
2686 unsigned long nr_iowait(void)
2688 unsigned long i, sum = 0;
2690 for_each_possible_cpu(i)
2691 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2693 return sum;
2696 unsigned long nr_active(void)
2698 unsigned long i, running = 0, uninterruptible = 0;
2700 for_each_online_cpu(i) {
2701 running += cpu_rq(i)->nr_running;
2702 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2705 if (unlikely((long)uninterruptible < 0))
2706 uninterruptible = 0;
2708 return running + uninterruptible;
2712 * Update rq->cpu_load[] statistics. This function is usually called every
2713 * scheduler tick (TICK_NSEC).
2715 static void update_cpu_load(struct rq *this_rq)
2717 unsigned long this_load = this_rq->load.weight;
2718 int i, scale;
2720 this_rq->nr_load_updates++;
2722 /* Update our load: */
2723 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2724 unsigned long old_load, new_load;
2726 /* scale is effectively 1 << i now, and >> i divides by scale */
2728 old_load = this_rq->cpu_load[i];
2729 new_load = this_load;
2731 * Round up the averaging division if load is increasing. This
2732 * prevents us from getting stuck on 9 if the load is 10, for
2733 * example.
2735 if (new_load > old_load)
2736 new_load += scale-1;
2737 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2741 #ifdef CONFIG_SMP
2744 * double_rq_lock - safely lock two runqueues
2746 * Note this does not disable interrupts like task_rq_lock,
2747 * you need to do so manually before calling.
2749 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2750 __acquires(rq1->lock)
2751 __acquires(rq2->lock)
2753 BUG_ON(!irqs_disabled());
2754 if (rq1 == rq2) {
2755 spin_lock(&rq1->lock);
2756 __acquire(rq2->lock); /* Fake it out ;) */
2757 } else {
2758 if (rq1 < rq2) {
2759 spin_lock(&rq1->lock);
2760 spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
2761 } else {
2762 spin_lock(&rq2->lock);
2763 spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
2766 update_rq_clock(rq1);
2767 update_rq_clock(rq2);
2771 * double_rq_unlock - safely unlock two runqueues
2773 * Note this does not restore interrupts like task_rq_unlock,
2774 * you need to do so manually after calling.
2776 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2777 __releases(rq1->lock)
2778 __releases(rq2->lock)
2780 spin_unlock(&rq1->lock);
2781 if (rq1 != rq2)
2782 spin_unlock(&rq2->lock);
2783 else
2784 __release(rq2->lock);
2788 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2790 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2791 __releases(this_rq->lock)
2792 __acquires(busiest->lock)
2793 __acquires(this_rq->lock)
2795 int ret = 0;
2797 if (unlikely(!irqs_disabled())) {
2798 /* printk() doesn't work good under rq->lock */
2799 spin_unlock(&this_rq->lock);
2800 BUG_ON(1);
2802 if (unlikely(!spin_trylock(&busiest->lock))) {
2803 if (busiest < this_rq) {
2804 spin_unlock(&this_rq->lock);
2805 spin_lock(&busiest->lock);
2806 spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING);
2807 ret = 1;
2808 } else
2809 spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING);
2811 return ret;
2814 static void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
2815 __releases(busiest->lock)
2817 spin_unlock(&busiest->lock);
2818 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
2822 * If dest_cpu is allowed for this process, migrate the task to it.
2823 * This is accomplished by forcing the cpu_allowed mask to only
2824 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2825 * the cpu_allowed mask is restored.
2827 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2829 struct migration_req req;
2830 unsigned long flags;
2831 struct rq *rq;
2833 rq = task_rq_lock(p, &flags);
2834 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2835 || unlikely(!cpu_active(dest_cpu)))
2836 goto out;
2838 /* force the process onto the specified CPU */
2839 if (migrate_task(p, dest_cpu, &req)) {
2840 /* Need to wait for migration thread (might exit: take ref). */
2841 struct task_struct *mt = rq->migration_thread;
2843 get_task_struct(mt);
2844 task_rq_unlock(rq, &flags);
2845 wake_up_process(mt);
2846 put_task_struct(mt);
2847 wait_for_completion(&req.done);
2849 return;
2851 out:
2852 task_rq_unlock(rq, &flags);
2856 * sched_exec - execve() is a valuable balancing opportunity, because at
2857 * this point the task has the smallest effective memory and cache footprint.
2859 void sched_exec(void)
2861 int new_cpu, this_cpu = get_cpu();
2862 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2863 put_cpu();
2864 if (new_cpu != this_cpu)
2865 sched_migrate_task(current, new_cpu);
2869 * pull_task - move a task from a remote runqueue to the local runqueue.
2870 * Both runqueues must be locked.
2872 static void pull_task(struct rq *src_rq, struct task_struct *p,
2873 struct rq *this_rq, int this_cpu)
2875 deactivate_task(src_rq, p, 0);
2876 set_task_cpu(p, this_cpu);
2877 activate_task(this_rq, p, 0);
2879 * Note that idle threads have a prio of MAX_PRIO, for this test
2880 * to be always true for them.
2882 check_preempt_curr(this_rq, p);
2886 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2888 static
2889 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2890 struct sched_domain *sd, enum cpu_idle_type idle,
2891 int *all_pinned)
2894 * We do not migrate tasks that are:
2895 * 1) running (obviously), or
2896 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2897 * 3) are cache-hot on their current CPU.
2899 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2900 schedstat_inc(p, se.nr_failed_migrations_affine);
2901 return 0;
2903 *all_pinned = 0;
2905 if (task_running(rq, p)) {
2906 schedstat_inc(p, se.nr_failed_migrations_running);
2907 return 0;
2911 * Aggressive migration if:
2912 * 1) task is cache cold, or
2913 * 2) too many balance attempts have failed.
2916 if (!task_hot(p, rq->clock, sd) ||
2917 sd->nr_balance_failed > sd->cache_nice_tries) {
2918 #ifdef CONFIG_SCHEDSTATS
2919 if (task_hot(p, rq->clock, sd)) {
2920 schedstat_inc(sd, lb_hot_gained[idle]);
2921 schedstat_inc(p, se.nr_forced_migrations);
2923 #endif
2924 return 1;
2927 if (task_hot(p, rq->clock, sd)) {
2928 schedstat_inc(p, se.nr_failed_migrations_hot);
2929 return 0;
2931 return 1;
2934 static unsigned long
2935 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2936 unsigned long max_load_move, struct sched_domain *sd,
2937 enum cpu_idle_type idle, int *all_pinned,
2938 int *this_best_prio, struct rq_iterator *iterator)
2940 int loops = 0, pulled = 0, pinned = 0;
2941 struct task_struct *p;
2942 long rem_load_move = max_load_move;
2944 if (max_load_move == 0)
2945 goto out;
2947 pinned = 1;
2950 * Start the load-balancing iterator:
2952 p = iterator->start(iterator->arg);
2953 next:
2954 if (!p || loops++ > sysctl_sched_nr_migrate)
2955 goto out;
2957 if ((p->se.load.weight >> 1) > rem_load_move ||
2958 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2959 p = iterator->next(iterator->arg);
2960 goto next;
2963 pull_task(busiest, p, this_rq, this_cpu);
2964 pulled++;
2965 rem_load_move -= p->se.load.weight;
2968 * We only want to steal up to the prescribed amount of weighted load.
2970 if (rem_load_move > 0) {
2971 if (p->prio < *this_best_prio)
2972 *this_best_prio = p->prio;
2973 p = iterator->next(iterator->arg);
2974 goto next;
2976 out:
2978 * Right now, this is one of only two places pull_task() is called,
2979 * so we can safely collect pull_task() stats here rather than
2980 * inside pull_task().
2982 schedstat_add(sd, lb_gained[idle], pulled);
2984 if (all_pinned)
2985 *all_pinned = pinned;
2987 return max_load_move - rem_load_move;
2991 * move_tasks tries to move up to max_load_move weighted load from busiest to
2992 * this_rq, as part of a balancing operation within domain "sd".
2993 * Returns 1 if successful and 0 otherwise.
2995 * Called with both runqueues locked.
2997 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2998 unsigned long max_load_move,
2999 struct sched_domain *sd, enum cpu_idle_type idle,
3000 int *all_pinned)
3002 const struct sched_class *class = sched_class_highest;
3003 unsigned long total_load_moved = 0;
3004 int this_best_prio = this_rq->curr->prio;
3006 do {
3007 total_load_moved +=
3008 class->load_balance(this_rq, this_cpu, busiest,
3009 max_load_move - total_load_moved,
3010 sd, idle, all_pinned, &this_best_prio);
3011 class = class->next;
3013 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
3014 break;
3016 } while (class && max_load_move > total_load_moved);
3018 return total_load_moved > 0;
3021 static int
3022 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3023 struct sched_domain *sd, enum cpu_idle_type idle,
3024 struct rq_iterator *iterator)
3026 struct task_struct *p = iterator->start(iterator->arg);
3027 int pinned = 0;
3029 while (p) {
3030 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3031 pull_task(busiest, p, this_rq, this_cpu);
3033 * Right now, this is only the second place pull_task()
3034 * is called, so we can safely collect pull_task()
3035 * stats here rather than inside pull_task().
3037 schedstat_inc(sd, lb_gained[idle]);
3039 return 1;
3041 p = iterator->next(iterator->arg);
3044 return 0;
3048 * move_one_task tries to move exactly one task from busiest to this_rq, as
3049 * part of active balancing operations within "domain".
3050 * Returns 1 if successful and 0 otherwise.
3052 * Called with both runqueues locked.
3054 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3055 struct sched_domain *sd, enum cpu_idle_type idle)
3057 const struct sched_class *class;
3059 for (class = sched_class_highest; class; class = class->next)
3060 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3061 return 1;
3063 return 0;
3067 * find_busiest_group finds and returns the busiest CPU group within the
3068 * domain. It calculates and returns the amount of weighted load which
3069 * should be moved to restore balance via the imbalance parameter.
3071 static struct sched_group *
3072 find_busiest_group(struct sched_domain *sd, int this_cpu,
3073 unsigned long *imbalance, enum cpu_idle_type idle,
3074 int *sd_idle, const cpumask_t *cpus, int *balance)
3076 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3077 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3078 unsigned long max_pull;
3079 unsigned long busiest_load_per_task, busiest_nr_running;
3080 unsigned long this_load_per_task, this_nr_running;
3081 int load_idx, group_imb = 0;
3082 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3083 int power_savings_balance = 1;
3084 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3085 unsigned long min_nr_running = ULONG_MAX;
3086 struct sched_group *group_min = NULL, *group_leader = NULL;
3087 #endif
3089 max_load = this_load = total_load = total_pwr = 0;
3090 busiest_load_per_task = busiest_nr_running = 0;
3091 this_load_per_task = this_nr_running = 0;
3093 if (idle == CPU_NOT_IDLE)
3094 load_idx = sd->busy_idx;
3095 else if (idle == CPU_NEWLY_IDLE)
3096 load_idx = sd->newidle_idx;
3097 else
3098 load_idx = sd->idle_idx;
3100 do {
3101 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3102 int local_group;
3103 int i;
3104 int __group_imb = 0;
3105 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3106 unsigned long sum_nr_running, sum_weighted_load;
3107 unsigned long sum_avg_load_per_task;
3108 unsigned long avg_load_per_task;
3110 local_group = cpu_isset(this_cpu, group->cpumask);
3112 if (local_group)
3113 balance_cpu = first_cpu(group->cpumask);
3115 /* Tally up the load of all CPUs in the group */
3116 sum_weighted_load = sum_nr_running = avg_load = 0;
3117 sum_avg_load_per_task = avg_load_per_task = 0;
3119 max_cpu_load = 0;
3120 min_cpu_load = ~0UL;
3122 for_each_cpu_mask_nr(i, group->cpumask) {
3123 struct rq *rq;
3125 if (!cpu_isset(i, *cpus))
3126 continue;
3128 rq = cpu_rq(i);
3130 if (*sd_idle && rq->nr_running)
3131 *sd_idle = 0;
3133 /* Bias balancing toward cpus of our domain */
3134 if (local_group) {
3135 if (idle_cpu(i) && !first_idle_cpu) {
3136 first_idle_cpu = 1;
3137 balance_cpu = i;
3140 load = target_load(i, load_idx);
3141 } else {
3142 load = source_load(i, load_idx);
3143 if (load > max_cpu_load)
3144 max_cpu_load = load;
3145 if (min_cpu_load > load)
3146 min_cpu_load = load;
3149 avg_load += load;
3150 sum_nr_running += rq->nr_running;
3151 sum_weighted_load += weighted_cpuload(i);
3153 sum_avg_load_per_task += cpu_avg_load_per_task(i);
3157 * First idle cpu or the first cpu(busiest) in this sched group
3158 * is eligible for doing load balancing at this and above
3159 * domains. In the newly idle case, we will allow all the cpu's
3160 * to do the newly idle load balance.
3162 if (idle != CPU_NEWLY_IDLE && local_group &&
3163 balance_cpu != this_cpu && balance) {
3164 *balance = 0;
3165 goto ret;
3168 total_load += avg_load;
3169 total_pwr += group->__cpu_power;
3171 /* Adjust by relative CPU power of the group */
3172 avg_load = sg_div_cpu_power(group,
3173 avg_load * SCHED_LOAD_SCALE);
3177 * Consider the group unbalanced when the imbalance is larger
3178 * than the average weight of two tasks.
3180 * APZ: with cgroup the avg task weight can vary wildly and
3181 * might not be a suitable number - should we keep a
3182 * normalized nr_running number somewhere that negates
3183 * the hierarchy?
3185 avg_load_per_task = sg_div_cpu_power(group,
3186 sum_avg_load_per_task * SCHED_LOAD_SCALE);
3188 if ((max_cpu_load - min_cpu_load) > 2*avg_load_per_task)
3189 __group_imb = 1;
3191 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3193 if (local_group) {
3194 this_load = avg_load;
3195 this = group;
3196 this_nr_running = sum_nr_running;
3197 this_load_per_task = sum_weighted_load;
3198 } else if (avg_load > max_load &&
3199 (sum_nr_running > group_capacity || __group_imb)) {
3200 max_load = avg_load;
3201 busiest = group;
3202 busiest_nr_running = sum_nr_running;
3203 busiest_load_per_task = sum_weighted_load;
3204 group_imb = __group_imb;
3207 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3209 * Busy processors will not participate in power savings
3210 * balance.
3212 if (idle == CPU_NOT_IDLE ||
3213 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3214 goto group_next;
3217 * If the local group is idle or completely loaded
3218 * no need to do power savings balance at this domain
3220 if (local_group && (this_nr_running >= group_capacity ||
3221 !this_nr_running))
3222 power_savings_balance = 0;
3225 * If a group is already running at full capacity or idle,
3226 * don't include that group in power savings calculations
3228 if (!power_savings_balance || sum_nr_running >= group_capacity
3229 || !sum_nr_running)
3230 goto group_next;
3233 * Calculate the group which has the least non-idle load.
3234 * This is the group from where we need to pick up the load
3235 * for saving power
3237 if ((sum_nr_running < min_nr_running) ||
3238 (sum_nr_running == min_nr_running &&
3239 first_cpu(group->cpumask) <
3240 first_cpu(group_min->cpumask))) {
3241 group_min = group;
3242 min_nr_running = sum_nr_running;
3243 min_load_per_task = sum_weighted_load /
3244 sum_nr_running;
3248 * Calculate the group which is almost near its
3249 * capacity but still has some space to pick up some load
3250 * from other group and save more power
3252 if (sum_nr_running <= group_capacity - 1) {
3253 if (sum_nr_running > leader_nr_running ||
3254 (sum_nr_running == leader_nr_running &&
3255 first_cpu(group->cpumask) >
3256 first_cpu(group_leader->cpumask))) {
3257 group_leader = group;
3258 leader_nr_running = sum_nr_running;
3261 group_next:
3262 #endif
3263 group = group->next;
3264 } while (group != sd->groups);
3266 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3267 goto out_balanced;
3269 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3271 if (this_load >= avg_load ||
3272 100*max_load <= sd->imbalance_pct*this_load)
3273 goto out_balanced;
3275 busiest_load_per_task /= busiest_nr_running;
3276 if (group_imb)
3277 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3280 * We're trying to get all the cpus to the average_load, so we don't
3281 * want to push ourselves above the average load, nor do we wish to
3282 * reduce the max loaded cpu below the average load, as either of these
3283 * actions would just result in more rebalancing later, and ping-pong
3284 * tasks around. Thus we look for the minimum possible imbalance.
3285 * Negative imbalances (*we* are more loaded than anyone else) will
3286 * be counted as no imbalance for these purposes -- we can't fix that
3287 * by pulling tasks to us. Be careful of negative numbers as they'll
3288 * appear as very large values with unsigned longs.
3290 if (max_load <= busiest_load_per_task)
3291 goto out_balanced;
3294 * In the presence of smp nice balancing, certain scenarios can have
3295 * max load less than avg load(as we skip the groups at or below
3296 * its cpu_power, while calculating max_load..)
3298 if (max_load < avg_load) {
3299 *imbalance = 0;
3300 goto small_imbalance;
3303 /* Don't want to pull so many tasks that a group would go idle */
3304 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3306 /* How much load to actually move to equalise the imbalance */
3307 *imbalance = min(max_pull * busiest->__cpu_power,
3308 (avg_load - this_load) * this->__cpu_power)
3309 / SCHED_LOAD_SCALE;
3312 * if *imbalance is less than the average load per runnable task
3313 * there is no gaurantee that any tasks will be moved so we'll have
3314 * a think about bumping its value to force at least one task to be
3315 * moved
3317 if (*imbalance < busiest_load_per_task) {
3318 unsigned long tmp, pwr_now, pwr_move;
3319 unsigned int imbn;
3321 small_imbalance:
3322 pwr_move = pwr_now = 0;
3323 imbn = 2;
3324 if (this_nr_running) {
3325 this_load_per_task /= this_nr_running;
3326 if (busiest_load_per_task > this_load_per_task)
3327 imbn = 1;
3328 } else
3329 this_load_per_task = cpu_avg_load_per_task(this_cpu);
3331 if (max_load - this_load + 2*busiest_load_per_task >=
3332 busiest_load_per_task * imbn) {
3333 *imbalance = busiest_load_per_task;
3334 return busiest;
3338 * OK, we don't have enough imbalance to justify moving tasks,
3339 * however we may be able to increase total CPU power used by
3340 * moving them.
3343 pwr_now += busiest->__cpu_power *
3344 min(busiest_load_per_task, max_load);
3345 pwr_now += this->__cpu_power *
3346 min(this_load_per_task, this_load);
3347 pwr_now /= SCHED_LOAD_SCALE;
3349 /* Amount of load we'd subtract */
3350 tmp = sg_div_cpu_power(busiest,
3351 busiest_load_per_task * SCHED_LOAD_SCALE);
3352 if (max_load > tmp)
3353 pwr_move += busiest->__cpu_power *
3354 min(busiest_load_per_task, max_load - tmp);
3356 /* Amount of load we'd add */
3357 if (max_load * busiest->__cpu_power <
3358 busiest_load_per_task * SCHED_LOAD_SCALE)
3359 tmp = sg_div_cpu_power(this,
3360 max_load * busiest->__cpu_power);
3361 else
3362 tmp = sg_div_cpu_power(this,
3363 busiest_load_per_task * SCHED_LOAD_SCALE);
3364 pwr_move += this->__cpu_power *
3365 min(this_load_per_task, this_load + tmp);
3366 pwr_move /= SCHED_LOAD_SCALE;
3368 /* Move if we gain throughput */
3369 if (pwr_move > pwr_now)
3370 *imbalance = busiest_load_per_task;
3373 return busiest;
3375 out_balanced:
3376 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3377 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3378 goto ret;
3380 if (this == group_leader && group_leader != group_min) {
3381 *imbalance = min_load_per_task;
3382 return group_min;
3384 #endif
3385 ret:
3386 *imbalance = 0;
3387 return NULL;
3391 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3393 static struct rq *
3394 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3395 unsigned long imbalance, const cpumask_t *cpus)
3397 struct rq *busiest = NULL, *rq;
3398 unsigned long max_load = 0;
3399 int i;
3401 for_each_cpu_mask_nr(i, group->cpumask) {
3402 unsigned long wl;
3404 if (!cpu_isset(i, *cpus))
3405 continue;
3407 rq = cpu_rq(i);
3408 wl = weighted_cpuload(i);
3410 if (rq->nr_running == 1 && wl > imbalance)
3411 continue;
3413 if (wl > max_load) {
3414 max_load = wl;
3415 busiest = rq;
3419 return busiest;
3423 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3424 * so long as it is large enough.
3426 #define MAX_PINNED_INTERVAL 512
3429 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3430 * tasks if there is an imbalance.
3432 static int load_balance(int this_cpu, struct rq *this_rq,
3433 struct sched_domain *sd, enum cpu_idle_type idle,
3434 int *balance, cpumask_t *cpus)
3436 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3437 struct sched_group *group;
3438 unsigned long imbalance;
3439 struct rq *busiest;
3440 unsigned long flags;
3442 cpus_setall(*cpus);
3445 * When power savings policy is enabled for the parent domain, idle
3446 * sibling can pick up load irrespective of busy siblings. In this case,
3447 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3448 * portraying it as CPU_NOT_IDLE.
3450 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3451 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3452 sd_idle = 1;
3454 schedstat_inc(sd, lb_count[idle]);
3456 redo:
3457 update_shares(sd);
3458 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3459 cpus, balance);
3461 if (*balance == 0)
3462 goto out_balanced;
3464 if (!group) {
3465 schedstat_inc(sd, lb_nobusyg[idle]);
3466 goto out_balanced;
3469 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3470 if (!busiest) {
3471 schedstat_inc(sd, lb_nobusyq[idle]);
3472 goto out_balanced;
3475 BUG_ON(busiest == this_rq);
3477 schedstat_add(sd, lb_imbalance[idle], imbalance);
3479 ld_moved = 0;
3480 if (busiest->nr_running > 1) {
3482 * Attempt to move tasks. If find_busiest_group has found
3483 * an imbalance but busiest->nr_running <= 1, the group is
3484 * still unbalanced. ld_moved simply stays zero, so it is
3485 * correctly treated as an imbalance.
3487 local_irq_save(flags);
3488 double_rq_lock(this_rq, busiest);
3489 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3490 imbalance, sd, idle, &all_pinned);
3491 double_rq_unlock(this_rq, busiest);
3492 local_irq_restore(flags);
3495 * some other cpu did the load balance for us.
3497 if (ld_moved && this_cpu != smp_processor_id())
3498 resched_cpu(this_cpu);
3500 /* All tasks on this runqueue were pinned by CPU affinity */
3501 if (unlikely(all_pinned)) {
3502 cpu_clear(cpu_of(busiest), *cpus);
3503 if (!cpus_empty(*cpus))
3504 goto redo;
3505 goto out_balanced;
3509 if (!ld_moved) {
3510 schedstat_inc(sd, lb_failed[idle]);
3511 sd->nr_balance_failed++;
3513 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3515 spin_lock_irqsave(&busiest->lock, flags);
3517 /* don't kick the migration_thread, if the curr
3518 * task on busiest cpu can't be moved to this_cpu
3520 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3521 spin_unlock_irqrestore(&busiest->lock, flags);
3522 all_pinned = 1;
3523 goto out_one_pinned;
3526 if (!busiest->active_balance) {
3527 busiest->active_balance = 1;
3528 busiest->push_cpu = this_cpu;
3529 active_balance = 1;
3531 spin_unlock_irqrestore(&busiest->lock, flags);
3532 if (active_balance)
3533 wake_up_process(busiest->migration_thread);
3536 * We've kicked active balancing, reset the failure
3537 * counter.
3539 sd->nr_balance_failed = sd->cache_nice_tries+1;
3541 } else
3542 sd->nr_balance_failed = 0;
3544 if (likely(!active_balance)) {
3545 /* We were unbalanced, so reset the balancing interval */
3546 sd->balance_interval = sd->min_interval;
3547 } else {
3549 * If we've begun active balancing, start to back off. This
3550 * case may not be covered by the all_pinned logic if there
3551 * is only 1 task on the busy runqueue (because we don't call
3552 * move_tasks).
3554 if (sd->balance_interval < sd->max_interval)
3555 sd->balance_interval *= 2;
3558 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3559 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3560 ld_moved = -1;
3562 goto out;
3564 out_balanced:
3565 schedstat_inc(sd, lb_balanced[idle]);
3567 sd->nr_balance_failed = 0;
3569 out_one_pinned:
3570 /* tune up the balancing interval */
3571 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3572 (sd->balance_interval < sd->max_interval))
3573 sd->balance_interval *= 2;
3575 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3576 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3577 ld_moved = -1;
3578 else
3579 ld_moved = 0;
3580 out:
3581 if (ld_moved)
3582 update_shares(sd);
3583 return ld_moved;
3587 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3588 * tasks if there is an imbalance.
3590 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3591 * this_rq is locked.
3593 static int
3594 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3595 cpumask_t *cpus)
3597 struct sched_group *group;
3598 struct rq *busiest = NULL;
3599 unsigned long imbalance;
3600 int ld_moved = 0;
3601 int sd_idle = 0;
3602 int all_pinned = 0;
3604 cpus_setall(*cpus);
3607 * When power savings policy is enabled for the parent domain, idle
3608 * sibling can pick up load irrespective of busy siblings. In this case,
3609 * let the state of idle sibling percolate up as IDLE, instead of
3610 * portraying it as CPU_NOT_IDLE.
3612 if (sd->flags & SD_SHARE_CPUPOWER &&
3613 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3614 sd_idle = 1;
3616 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3617 redo:
3618 update_shares_locked(this_rq, sd);
3619 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3620 &sd_idle, cpus, NULL);
3621 if (!group) {
3622 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3623 goto out_balanced;
3626 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3627 if (!busiest) {
3628 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3629 goto out_balanced;
3632 BUG_ON(busiest == this_rq);
3634 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3636 ld_moved = 0;
3637 if (busiest->nr_running > 1) {
3638 /* Attempt to move tasks */
3639 double_lock_balance(this_rq, busiest);
3640 /* this_rq->clock is already updated */
3641 update_rq_clock(busiest);
3642 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3643 imbalance, sd, CPU_NEWLY_IDLE,
3644 &all_pinned);
3645 double_unlock_balance(this_rq, busiest);
3647 if (unlikely(all_pinned)) {
3648 cpu_clear(cpu_of(busiest), *cpus);
3649 if (!cpus_empty(*cpus))
3650 goto redo;
3654 if (!ld_moved) {
3655 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3656 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3657 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3658 return -1;
3659 } else
3660 sd->nr_balance_failed = 0;
3662 update_shares_locked(this_rq, sd);
3663 return ld_moved;
3665 out_balanced:
3666 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3667 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3668 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3669 return -1;
3670 sd->nr_balance_failed = 0;
3672 return 0;
3676 * idle_balance is called by schedule() if this_cpu is about to become
3677 * idle. Attempts to pull tasks from other CPUs.
3679 static void idle_balance(int this_cpu, struct rq *this_rq)
3681 struct sched_domain *sd;
3682 int pulled_task = -1;
3683 unsigned long next_balance = jiffies + HZ;
3684 cpumask_t tmpmask;
3686 for_each_domain(this_cpu, sd) {
3687 unsigned long interval;
3689 if (!(sd->flags & SD_LOAD_BALANCE))
3690 continue;
3692 if (sd->flags & SD_BALANCE_NEWIDLE)
3693 /* If we've pulled tasks over stop searching: */
3694 pulled_task = load_balance_newidle(this_cpu, this_rq,
3695 sd, &tmpmask);
3697 interval = msecs_to_jiffies(sd->balance_interval);
3698 if (time_after(next_balance, sd->last_balance + interval))
3699 next_balance = sd->last_balance + interval;
3700 if (pulled_task)
3701 break;
3703 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3705 * We are going idle. next_balance may be set based on
3706 * a busy processor. So reset next_balance.
3708 this_rq->next_balance = next_balance;
3713 * active_load_balance is run by migration threads. It pushes running tasks
3714 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3715 * running on each physical CPU where possible, and avoids physical /
3716 * logical imbalances.
3718 * Called with busiest_rq locked.
3720 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3722 int target_cpu = busiest_rq->push_cpu;
3723 struct sched_domain *sd;
3724 struct rq *target_rq;
3726 /* Is there any task to move? */
3727 if (busiest_rq->nr_running <= 1)
3728 return;
3730 target_rq = cpu_rq(target_cpu);
3733 * This condition is "impossible", if it occurs
3734 * we need to fix it. Originally reported by
3735 * Bjorn Helgaas on a 128-cpu setup.
3737 BUG_ON(busiest_rq == target_rq);
3739 /* move a task from busiest_rq to target_rq */
3740 double_lock_balance(busiest_rq, target_rq);
3741 update_rq_clock(busiest_rq);
3742 update_rq_clock(target_rq);
3744 /* Search for an sd spanning us and the target CPU. */
3745 for_each_domain(target_cpu, sd) {
3746 if ((sd->flags & SD_LOAD_BALANCE) &&
3747 cpu_isset(busiest_cpu, sd->span))
3748 break;
3751 if (likely(sd)) {
3752 schedstat_inc(sd, alb_count);
3754 if (move_one_task(target_rq, target_cpu, busiest_rq,
3755 sd, CPU_IDLE))
3756 schedstat_inc(sd, alb_pushed);
3757 else
3758 schedstat_inc(sd, alb_failed);
3760 double_unlock_balance(busiest_rq, target_rq);
3763 #ifdef CONFIG_NO_HZ
3764 static struct {
3765 atomic_t load_balancer;
3766 cpumask_t cpu_mask;
3767 } nohz ____cacheline_aligned = {
3768 .load_balancer = ATOMIC_INIT(-1),
3769 .cpu_mask = CPU_MASK_NONE,
3773 * This routine will try to nominate the ilb (idle load balancing)
3774 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3775 * load balancing on behalf of all those cpus. If all the cpus in the system
3776 * go into this tickless mode, then there will be no ilb owner (as there is
3777 * no need for one) and all the cpus will sleep till the next wakeup event
3778 * arrives...
3780 * For the ilb owner, tick is not stopped. And this tick will be used
3781 * for idle load balancing. ilb owner will still be part of
3782 * nohz.cpu_mask..
3784 * While stopping the tick, this cpu will become the ilb owner if there
3785 * is no other owner. And will be the owner till that cpu becomes busy
3786 * or if all cpus in the system stop their ticks at which point
3787 * there is no need for ilb owner.
3789 * When the ilb owner becomes busy, it nominates another owner, during the
3790 * next busy scheduler_tick()
3792 int select_nohz_load_balancer(int stop_tick)
3794 int cpu = smp_processor_id();
3796 if (stop_tick) {
3797 cpu_set(cpu, nohz.cpu_mask);
3798 cpu_rq(cpu)->in_nohz_recently = 1;
3801 * If we are going offline and still the leader, give up!
3803 if (!cpu_active(cpu) &&
3804 atomic_read(&nohz.load_balancer) == cpu) {
3805 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3806 BUG();
3807 return 0;
3810 /* time for ilb owner also to sleep */
3811 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3812 if (atomic_read(&nohz.load_balancer) == cpu)
3813 atomic_set(&nohz.load_balancer, -1);
3814 return 0;
3817 if (atomic_read(&nohz.load_balancer) == -1) {
3818 /* make me the ilb owner */
3819 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3820 return 1;
3821 } else if (atomic_read(&nohz.load_balancer) == cpu)
3822 return 1;
3823 } else {
3824 if (!cpu_isset(cpu, nohz.cpu_mask))
3825 return 0;
3827 cpu_clear(cpu, nohz.cpu_mask);
3829 if (atomic_read(&nohz.load_balancer) == cpu)
3830 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3831 BUG();
3833 return 0;
3835 #endif
3837 static DEFINE_SPINLOCK(balancing);
3840 * It checks each scheduling domain to see if it is due to be balanced,
3841 * and initiates a balancing operation if so.
3843 * Balancing parameters are set up in arch_init_sched_domains.
3845 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3847 int balance = 1;
3848 struct rq *rq = cpu_rq(cpu);
3849 unsigned long interval;
3850 struct sched_domain *sd;
3851 /* Earliest time when we have to do rebalance again */
3852 unsigned long next_balance = jiffies + 60*HZ;
3853 int update_next_balance = 0;
3854 int need_serialize;
3855 cpumask_t tmp;
3857 for_each_domain(cpu, sd) {
3858 if (!(sd->flags & SD_LOAD_BALANCE))
3859 continue;
3861 interval = sd->balance_interval;
3862 if (idle != CPU_IDLE)
3863 interval *= sd->busy_factor;
3865 /* scale ms to jiffies */
3866 interval = msecs_to_jiffies(interval);
3867 if (unlikely(!interval))
3868 interval = 1;
3869 if (interval > HZ*NR_CPUS/10)
3870 interval = HZ*NR_CPUS/10;
3872 need_serialize = sd->flags & SD_SERIALIZE;
3874 if (need_serialize) {
3875 if (!spin_trylock(&balancing))
3876 goto out;
3879 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3880 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
3882 * We've pulled tasks over so either we're no
3883 * longer idle, or one of our SMT siblings is
3884 * not idle.
3886 idle = CPU_NOT_IDLE;
3888 sd->last_balance = jiffies;
3890 if (need_serialize)
3891 spin_unlock(&balancing);
3892 out:
3893 if (time_after(next_balance, sd->last_balance + interval)) {
3894 next_balance = sd->last_balance + interval;
3895 update_next_balance = 1;
3899 * Stop the load balance at this level. There is another
3900 * CPU in our sched group which is doing load balancing more
3901 * actively.
3903 if (!balance)
3904 break;
3908 * next_balance will be updated only when there is a need.
3909 * When the cpu is attached to null domain for ex, it will not be
3910 * updated.
3912 if (likely(update_next_balance))
3913 rq->next_balance = next_balance;
3917 * run_rebalance_domains is triggered when needed from the scheduler tick.
3918 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3919 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3921 static void run_rebalance_domains(struct softirq_action *h)
3923 int this_cpu = smp_processor_id();
3924 struct rq *this_rq = cpu_rq(this_cpu);
3925 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3926 CPU_IDLE : CPU_NOT_IDLE;
3928 rebalance_domains(this_cpu, idle);
3930 #ifdef CONFIG_NO_HZ
3932 * If this cpu is the owner for idle load balancing, then do the
3933 * balancing on behalf of the other idle cpus whose ticks are
3934 * stopped.
3936 if (this_rq->idle_at_tick &&
3937 atomic_read(&nohz.load_balancer) == this_cpu) {
3938 cpumask_t cpus = nohz.cpu_mask;
3939 struct rq *rq;
3940 int balance_cpu;
3942 cpu_clear(this_cpu, cpus);
3943 for_each_cpu_mask_nr(balance_cpu, cpus) {
3945 * If this cpu gets work to do, stop the load balancing
3946 * work being done for other cpus. Next load
3947 * balancing owner will pick it up.
3949 if (need_resched())
3950 break;
3952 rebalance_domains(balance_cpu, CPU_IDLE);
3954 rq = cpu_rq(balance_cpu);
3955 if (time_after(this_rq->next_balance, rq->next_balance))
3956 this_rq->next_balance = rq->next_balance;
3959 #endif
3963 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3965 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3966 * idle load balancing owner or decide to stop the periodic load balancing,
3967 * if the whole system is idle.
3969 static inline void trigger_load_balance(struct rq *rq, int cpu)
3971 #ifdef CONFIG_NO_HZ
3973 * If we were in the nohz mode recently and busy at the current
3974 * scheduler tick, then check if we need to nominate new idle
3975 * load balancer.
3977 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3978 rq->in_nohz_recently = 0;
3980 if (atomic_read(&nohz.load_balancer) == cpu) {
3981 cpu_clear(cpu, nohz.cpu_mask);
3982 atomic_set(&nohz.load_balancer, -1);
3985 if (atomic_read(&nohz.load_balancer) == -1) {
3987 * simple selection for now: Nominate the
3988 * first cpu in the nohz list to be the next
3989 * ilb owner.
3991 * TBD: Traverse the sched domains and nominate
3992 * the nearest cpu in the nohz.cpu_mask.
3994 int ilb = first_cpu(nohz.cpu_mask);
3996 if (ilb < nr_cpu_ids)
3997 resched_cpu(ilb);
4002 * If this cpu is idle and doing idle load balancing for all the
4003 * cpus with ticks stopped, is it time for that to stop?
4005 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4006 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4007 resched_cpu(cpu);
4008 return;
4012 * If this cpu is idle and the idle load balancing is done by
4013 * someone else, then no need raise the SCHED_SOFTIRQ
4015 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4016 cpu_isset(cpu, nohz.cpu_mask))
4017 return;
4018 #endif
4019 if (time_after_eq(jiffies, rq->next_balance))
4020 raise_softirq(SCHED_SOFTIRQ);
4023 #else /* CONFIG_SMP */
4026 * on UP we do not need to balance between CPUs:
4028 static inline void idle_balance(int cpu, struct rq *rq)
4032 #endif
4034 DEFINE_PER_CPU(struct kernel_stat, kstat);
4036 EXPORT_PER_CPU_SYMBOL(kstat);
4039 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4040 * that have not yet been banked in case the task is currently running.
4042 unsigned long long task_sched_runtime(struct task_struct *p)
4044 unsigned long flags;
4045 u64 ns, delta_exec;
4046 struct rq *rq;
4048 rq = task_rq_lock(p, &flags);
4049 ns = p->se.sum_exec_runtime;
4050 if (task_current(rq, p)) {
4051 update_rq_clock(rq);
4052 delta_exec = rq->clock - p->se.exec_start;
4053 if ((s64)delta_exec > 0)
4054 ns += delta_exec;
4056 task_rq_unlock(rq, &flags);
4058 return ns;
4062 * Account user cpu time to a process.
4063 * @p: the process that the cpu time gets accounted to
4064 * @cputime: the cpu time spent in user space since the last update
4066 void account_user_time(struct task_struct *p, cputime_t cputime)
4068 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4069 cputime64_t tmp;
4071 p->utime = cputime_add(p->utime, cputime);
4073 /* Add user time to cpustat. */
4074 tmp = cputime_to_cputime64(cputime);
4075 if (TASK_NICE(p) > 0)
4076 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4077 else
4078 cpustat->user = cputime64_add(cpustat->user, tmp);
4079 /* Account for user time used */
4080 acct_update_integrals(p);
4084 * Account guest cpu time to a process.
4085 * @p: the process that the cpu time gets accounted to
4086 * @cputime: the cpu time spent in virtual machine since the last update
4088 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4090 cputime64_t tmp;
4091 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4093 tmp = cputime_to_cputime64(cputime);
4095 p->utime = cputime_add(p->utime, cputime);
4096 p->gtime = cputime_add(p->gtime, cputime);
4098 cpustat->user = cputime64_add(cpustat->user, tmp);
4099 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4103 * Account scaled user cpu time to a process.
4104 * @p: the process that the cpu time gets accounted to
4105 * @cputime: the cpu time spent in user space since the last update
4107 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4109 p->utimescaled = cputime_add(p->utimescaled, cputime);
4113 * Account system cpu time to a process.
4114 * @p: the process that the cpu time gets accounted to
4115 * @hardirq_offset: the offset to subtract from hardirq_count()
4116 * @cputime: the cpu time spent in kernel space since the last update
4118 void account_system_time(struct task_struct *p, int hardirq_offset,
4119 cputime_t cputime)
4121 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4122 struct rq *rq = this_rq();
4123 cputime64_t tmp;
4125 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
4126 account_guest_time(p, cputime);
4127 return;
4130 p->stime = cputime_add(p->stime, cputime);
4132 /* Add system time to cpustat. */
4133 tmp = cputime_to_cputime64(cputime);
4134 if (hardirq_count() - hardirq_offset)
4135 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4136 else if (softirq_count())
4137 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4138 else if (p != rq->idle)
4139 cpustat->system = cputime64_add(cpustat->system, tmp);
4140 else if (atomic_read(&rq->nr_iowait) > 0)
4141 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4142 else
4143 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4144 /* Account for system time used */
4145 acct_update_integrals(p);
4149 * Account scaled 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_scaled(struct task_struct *p, cputime_t cputime)
4156 p->stimescaled = cputime_add(p->stimescaled, cputime);
4160 * Account for involuntary wait time.
4161 * @p: the process from which the cpu time has been stolen
4162 * @steal: the cpu time spent in involuntary wait
4164 void account_steal_time(struct task_struct *p, cputime_t steal)
4166 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4167 cputime64_t tmp = cputime_to_cputime64(steal);
4168 struct rq *rq = this_rq();
4170 if (p == rq->idle) {
4171 p->stime = cputime_add(p->stime, steal);
4172 if (atomic_read(&rq->nr_iowait) > 0)
4173 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4174 else
4175 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4176 } else
4177 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4181 * Use precise platform statistics if available:
4183 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
4184 cputime_t task_utime(struct task_struct *p)
4186 return p->utime;
4189 cputime_t task_stime(struct task_struct *p)
4191 return p->stime;
4193 #else
4194 cputime_t task_utime(struct task_struct *p)
4196 clock_t utime = cputime_to_clock_t(p->utime),
4197 total = utime + cputime_to_clock_t(p->stime);
4198 u64 temp;
4201 * Use CFS's precise accounting:
4203 temp = (u64)nsec_to_clock_t(p->se.sum_exec_runtime);
4205 if (total) {
4206 temp *= utime;
4207 do_div(temp, total);
4209 utime = (clock_t)temp;
4211 p->prev_utime = max(p->prev_utime, clock_t_to_cputime(utime));
4212 return p->prev_utime;
4215 cputime_t task_stime(struct task_struct *p)
4217 clock_t stime;
4220 * Use CFS's precise accounting. (we subtract utime from
4221 * the total, to make sure the total observed by userspace
4222 * grows monotonically - apps rely on that):
4224 stime = nsec_to_clock_t(p->se.sum_exec_runtime) -
4225 cputime_to_clock_t(task_utime(p));
4227 if (stime >= 0)
4228 p->prev_stime = max(p->prev_stime, clock_t_to_cputime(stime));
4230 return p->prev_stime;
4232 #endif
4234 inline cputime_t task_gtime(struct task_struct *p)
4236 return p->gtime;
4240 * This function gets called by the timer code, with HZ frequency.
4241 * We call it with interrupts disabled.
4243 * It also gets called by the fork code, when changing the parent's
4244 * timeslices.
4246 void scheduler_tick(void)
4248 int cpu = smp_processor_id();
4249 struct rq *rq = cpu_rq(cpu);
4250 struct task_struct *curr = rq->curr;
4252 sched_clock_tick();
4254 spin_lock(&rq->lock);
4255 update_rq_clock(rq);
4256 update_cpu_load(rq);
4257 curr->sched_class->task_tick(rq, curr, 0);
4258 spin_unlock(&rq->lock);
4260 #ifdef CONFIG_SMP
4261 rq->idle_at_tick = idle_cpu(cpu);
4262 trigger_load_balance(rq, cpu);
4263 #endif
4266 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4267 defined(CONFIG_PREEMPT_TRACER))
4269 static inline unsigned long get_parent_ip(unsigned long addr)
4271 if (in_lock_functions(addr)) {
4272 addr = CALLER_ADDR2;
4273 if (in_lock_functions(addr))
4274 addr = CALLER_ADDR3;
4276 return addr;
4279 void __kprobes add_preempt_count(int val)
4281 #ifdef CONFIG_DEBUG_PREEMPT
4283 * Underflow?
4285 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4286 return;
4287 #endif
4288 preempt_count() += val;
4289 #ifdef CONFIG_DEBUG_PREEMPT
4291 * Spinlock count overflowing soon?
4293 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4294 PREEMPT_MASK - 10);
4295 #endif
4296 if (preempt_count() == val)
4297 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4299 EXPORT_SYMBOL(add_preempt_count);
4301 void __kprobes sub_preempt_count(int val)
4303 #ifdef CONFIG_DEBUG_PREEMPT
4305 * Underflow?
4307 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4308 return;
4310 * Is the spinlock portion underflowing?
4312 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4313 !(preempt_count() & PREEMPT_MASK)))
4314 return;
4315 #endif
4317 if (preempt_count() == val)
4318 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4319 preempt_count() -= val;
4321 EXPORT_SYMBOL(sub_preempt_count);
4323 #endif
4326 * Print scheduling while atomic bug:
4328 static noinline void __schedule_bug(struct task_struct *prev)
4330 struct pt_regs *regs = get_irq_regs();
4332 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4333 prev->comm, prev->pid, preempt_count());
4335 debug_show_held_locks(prev);
4336 print_modules();
4337 if (irqs_disabled())
4338 print_irqtrace_events(prev);
4340 if (regs)
4341 show_regs(regs);
4342 else
4343 dump_stack();
4347 * Various schedule()-time debugging checks and statistics:
4349 static inline void schedule_debug(struct task_struct *prev)
4352 * Test if we are atomic. Since do_exit() needs to call into
4353 * schedule() atomically, we ignore that path for now.
4354 * Otherwise, whine if we are scheduling when we should not be.
4356 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
4357 __schedule_bug(prev);
4359 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4361 schedstat_inc(this_rq(), sched_count);
4362 #ifdef CONFIG_SCHEDSTATS
4363 if (unlikely(prev->lock_depth >= 0)) {
4364 schedstat_inc(this_rq(), bkl_count);
4365 schedstat_inc(prev, sched_info.bkl_count);
4367 #endif
4371 * Pick up the highest-prio task:
4373 static inline struct task_struct *
4374 pick_next_task(struct rq *rq, struct task_struct *prev)
4376 const struct sched_class *class;
4377 struct task_struct *p;
4380 * Optimization: we know that if all tasks are in
4381 * the fair class we can call that function directly:
4383 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4384 p = fair_sched_class.pick_next_task(rq);
4385 if (likely(p))
4386 return p;
4389 class = sched_class_highest;
4390 for ( ; ; ) {
4391 p = class->pick_next_task(rq);
4392 if (p)
4393 return p;
4395 * Will never be NULL as the idle class always
4396 * returns a non-NULL p:
4398 class = class->next;
4403 * schedule() is the main scheduler function.
4405 asmlinkage void __sched schedule(void)
4407 struct task_struct *prev, *next;
4408 unsigned long *switch_count;
4409 struct rq *rq;
4410 int cpu;
4412 need_resched:
4413 preempt_disable();
4414 cpu = smp_processor_id();
4415 rq = cpu_rq(cpu);
4416 rcu_qsctr_inc(cpu);
4417 prev = rq->curr;
4418 switch_count = &prev->nivcsw;
4420 release_kernel_lock(prev);
4421 need_resched_nonpreemptible:
4423 schedule_debug(prev);
4425 if (sched_feat(HRTICK))
4426 hrtick_clear(rq);
4429 * Do the rq-clock update outside the rq lock:
4431 local_irq_disable();
4432 update_rq_clock(rq);
4433 spin_lock(&rq->lock);
4434 clear_tsk_need_resched(prev);
4436 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4437 if (unlikely(signal_pending_state(prev->state, prev)))
4438 prev->state = TASK_RUNNING;
4439 else
4440 deactivate_task(rq, prev, 1);
4441 switch_count = &prev->nvcsw;
4444 #ifdef CONFIG_SMP
4445 if (prev->sched_class->pre_schedule)
4446 prev->sched_class->pre_schedule(rq, prev);
4447 #endif
4449 if (unlikely(!rq->nr_running))
4450 idle_balance(cpu, rq);
4452 prev->sched_class->put_prev_task(rq, prev);
4453 next = pick_next_task(rq, prev);
4455 if (likely(prev != next)) {
4456 sched_info_switch(prev, next);
4458 rq->nr_switches++;
4459 rq->curr = next;
4460 ++*switch_count;
4462 context_switch(rq, prev, next); /* unlocks the rq */
4464 * the context switch might have flipped the stack from under
4465 * us, hence refresh the local variables.
4467 cpu = smp_processor_id();
4468 rq = cpu_rq(cpu);
4469 } else
4470 spin_unlock_irq(&rq->lock);
4472 if (unlikely(reacquire_kernel_lock(current) < 0))
4473 goto need_resched_nonpreemptible;
4475 preempt_enable_no_resched();
4476 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4477 goto need_resched;
4479 EXPORT_SYMBOL(schedule);
4481 #ifdef CONFIG_PREEMPT
4483 * this is the entry point to schedule() from in-kernel preemption
4484 * off of preempt_enable. Kernel preemptions off return from interrupt
4485 * occur there and call schedule directly.
4487 asmlinkage void __sched preempt_schedule(void)
4489 struct thread_info *ti = current_thread_info();
4492 * If there is a non-zero preempt_count or interrupts are disabled,
4493 * we do not want to preempt the current task. Just return..
4495 if (likely(ti->preempt_count || irqs_disabled()))
4496 return;
4498 do {
4499 add_preempt_count(PREEMPT_ACTIVE);
4500 schedule();
4501 sub_preempt_count(PREEMPT_ACTIVE);
4504 * Check again in case we missed a preemption opportunity
4505 * between schedule and now.
4507 barrier();
4508 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4510 EXPORT_SYMBOL(preempt_schedule);
4513 * this is the entry point to schedule() from kernel preemption
4514 * off of irq context.
4515 * Note, that this is called and return with irqs disabled. This will
4516 * protect us against recursive calling from irq.
4518 asmlinkage void __sched preempt_schedule_irq(void)
4520 struct thread_info *ti = current_thread_info();
4522 /* Catch callers which need to be fixed */
4523 BUG_ON(ti->preempt_count || !irqs_disabled());
4525 do {
4526 add_preempt_count(PREEMPT_ACTIVE);
4527 local_irq_enable();
4528 schedule();
4529 local_irq_disable();
4530 sub_preempt_count(PREEMPT_ACTIVE);
4533 * Check again in case we missed a preemption opportunity
4534 * between schedule and now.
4536 barrier();
4537 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4540 #endif /* CONFIG_PREEMPT */
4542 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4543 void *key)
4545 return try_to_wake_up(curr->private, mode, sync);
4547 EXPORT_SYMBOL(default_wake_function);
4550 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4551 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4552 * number) then we wake all the non-exclusive tasks and one exclusive task.
4554 * There are circumstances in which we can try to wake a task which has already
4555 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4556 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4558 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4559 int nr_exclusive, int sync, void *key)
4561 wait_queue_t *curr, *next;
4563 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4564 unsigned flags = curr->flags;
4566 if (curr->func(curr, mode, sync, key) &&
4567 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4568 break;
4573 * __wake_up - wake up threads blocked on a waitqueue.
4574 * @q: the waitqueue
4575 * @mode: which threads
4576 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4577 * @key: is directly passed to the wakeup function
4579 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4580 int nr_exclusive, void *key)
4582 unsigned long flags;
4584 spin_lock_irqsave(&q->lock, flags);
4585 __wake_up_common(q, mode, nr_exclusive, 0, key);
4586 spin_unlock_irqrestore(&q->lock, flags);
4588 EXPORT_SYMBOL(__wake_up);
4591 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4593 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4595 __wake_up_common(q, mode, 1, 0, NULL);
4599 * __wake_up_sync - wake up threads blocked on a waitqueue.
4600 * @q: the waitqueue
4601 * @mode: which threads
4602 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4604 * The sync wakeup differs that the waker knows that it will schedule
4605 * away soon, so while the target thread will be woken up, it will not
4606 * be migrated to another CPU - ie. the two threads are 'synchronized'
4607 * with each other. This can prevent needless bouncing between CPUs.
4609 * On UP it can prevent extra preemption.
4611 void
4612 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4614 unsigned long flags;
4615 int sync = 1;
4617 if (unlikely(!q))
4618 return;
4620 if (unlikely(!nr_exclusive))
4621 sync = 0;
4623 spin_lock_irqsave(&q->lock, flags);
4624 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4625 spin_unlock_irqrestore(&q->lock, flags);
4627 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4629 void complete(struct completion *x)
4631 unsigned long flags;
4633 spin_lock_irqsave(&x->wait.lock, flags);
4634 x->done++;
4635 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4636 spin_unlock_irqrestore(&x->wait.lock, flags);
4638 EXPORT_SYMBOL(complete);
4640 void complete_all(struct completion *x)
4642 unsigned long flags;
4644 spin_lock_irqsave(&x->wait.lock, flags);
4645 x->done += UINT_MAX/2;
4646 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4647 spin_unlock_irqrestore(&x->wait.lock, flags);
4649 EXPORT_SYMBOL(complete_all);
4651 static inline long __sched
4652 do_wait_for_common(struct completion *x, long timeout, int state)
4654 if (!x->done) {
4655 DECLARE_WAITQUEUE(wait, current);
4657 wait.flags |= WQ_FLAG_EXCLUSIVE;
4658 __add_wait_queue_tail(&x->wait, &wait);
4659 do {
4660 if ((state == TASK_INTERRUPTIBLE &&
4661 signal_pending(current)) ||
4662 (state == TASK_KILLABLE &&
4663 fatal_signal_pending(current))) {
4664 timeout = -ERESTARTSYS;
4665 break;
4667 __set_current_state(state);
4668 spin_unlock_irq(&x->wait.lock);
4669 timeout = schedule_timeout(timeout);
4670 spin_lock_irq(&x->wait.lock);
4671 } while (!x->done && timeout);
4672 __remove_wait_queue(&x->wait, &wait);
4673 if (!x->done)
4674 return timeout;
4676 x->done--;
4677 return timeout ?: 1;
4680 static long __sched
4681 wait_for_common(struct completion *x, long timeout, int state)
4683 might_sleep();
4685 spin_lock_irq(&x->wait.lock);
4686 timeout = do_wait_for_common(x, timeout, state);
4687 spin_unlock_irq(&x->wait.lock);
4688 return timeout;
4691 void __sched wait_for_completion(struct completion *x)
4693 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4695 EXPORT_SYMBOL(wait_for_completion);
4697 unsigned long __sched
4698 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4700 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4702 EXPORT_SYMBOL(wait_for_completion_timeout);
4704 int __sched wait_for_completion_interruptible(struct completion *x)
4706 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4707 if (t == -ERESTARTSYS)
4708 return t;
4709 return 0;
4711 EXPORT_SYMBOL(wait_for_completion_interruptible);
4713 unsigned long __sched
4714 wait_for_completion_interruptible_timeout(struct completion *x,
4715 unsigned long timeout)
4717 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4719 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4721 int __sched wait_for_completion_killable(struct completion *x)
4723 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4724 if (t == -ERESTARTSYS)
4725 return t;
4726 return 0;
4728 EXPORT_SYMBOL(wait_for_completion_killable);
4731 * try_wait_for_completion - try to decrement a completion without blocking
4732 * @x: completion structure
4734 * Returns: 0 if a decrement cannot be done without blocking
4735 * 1 if a decrement succeeded.
4737 * If a completion is being used as a counting completion,
4738 * attempt to decrement the counter without blocking. This
4739 * enables us to avoid waiting if the resource the completion
4740 * is protecting is not available.
4742 bool try_wait_for_completion(struct completion *x)
4744 int ret = 1;
4746 spin_lock_irq(&x->wait.lock);
4747 if (!x->done)
4748 ret = 0;
4749 else
4750 x->done--;
4751 spin_unlock_irq(&x->wait.lock);
4752 return ret;
4754 EXPORT_SYMBOL(try_wait_for_completion);
4757 * completion_done - Test to see if a completion has any waiters
4758 * @x: completion structure
4760 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4761 * 1 if there are no waiters.
4764 bool completion_done(struct completion *x)
4766 int ret = 1;
4768 spin_lock_irq(&x->wait.lock);
4769 if (!x->done)
4770 ret = 0;
4771 spin_unlock_irq(&x->wait.lock);
4772 return ret;
4774 EXPORT_SYMBOL(completion_done);
4776 static long __sched
4777 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4779 unsigned long flags;
4780 wait_queue_t wait;
4782 init_waitqueue_entry(&wait, current);
4784 __set_current_state(state);
4786 spin_lock_irqsave(&q->lock, flags);
4787 __add_wait_queue(q, &wait);
4788 spin_unlock(&q->lock);
4789 timeout = schedule_timeout(timeout);
4790 spin_lock_irq(&q->lock);
4791 __remove_wait_queue(q, &wait);
4792 spin_unlock_irqrestore(&q->lock, flags);
4794 return timeout;
4797 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4799 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4801 EXPORT_SYMBOL(interruptible_sleep_on);
4803 long __sched
4804 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4806 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4808 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4810 void __sched sleep_on(wait_queue_head_t *q)
4812 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4814 EXPORT_SYMBOL(sleep_on);
4816 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4818 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4820 EXPORT_SYMBOL(sleep_on_timeout);
4822 #ifdef CONFIG_RT_MUTEXES
4825 * rt_mutex_setprio - set the current priority of a task
4826 * @p: task
4827 * @prio: prio value (kernel-internal form)
4829 * This function changes the 'effective' priority of a task. It does
4830 * not touch ->normal_prio like __setscheduler().
4832 * Used by the rt_mutex code to implement priority inheritance logic.
4834 void rt_mutex_setprio(struct task_struct *p, int prio)
4836 unsigned long flags;
4837 int oldprio, on_rq, running;
4838 struct rq *rq;
4839 const struct sched_class *prev_class = p->sched_class;
4841 BUG_ON(prio < 0 || prio > MAX_PRIO);
4843 rq = task_rq_lock(p, &flags);
4844 update_rq_clock(rq);
4846 oldprio = p->prio;
4847 on_rq = p->se.on_rq;
4848 running = task_current(rq, p);
4849 if (on_rq)
4850 dequeue_task(rq, p, 0);
4851 if (running)
4852 p->sched_class->put_prev_task(rq, p);
4854 if (rt_prio(prio))
4855 p->sched_class = &rt_sched_class;
4856 else
4857 p->sched_class = &fair_sched_class;
4859 p->prio = prio;
4861 if (running)
4862 p->sched_class->set_curr_task(rq);
4863 if (on_rq) {
4864 enqueue_task(rq, p, 0);
4866 check_class_changed(rq, p, prev_class, oldprio, running);
4868 task_rq_unlock(rq, &flags);
4871 #endif
4873 void set_user_nice(struct task_struct *p, long nice)
4875 int old_prio, delta, on_rq;
4876 unsigned long flags;
4877 struct rq *rq;
4879 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4880 return;
4882 * We have to be careful, if called from sys_setpriority(),
4883 * the task might be in the middle of scheduling on another CPU.
4885 rq = task_rq_lock(p, &flags);
4886 update_rq_clock(rq);
4888 * The RT priorities are set via sched_setscheduler(), but we still
4889 * allow the 'normal' nice value to be set - but as expected
4890 * it wont have any effect on scheduling until the task is
4891 * SCHED_FIFO/SCHED_RR:
4893 if (task_has_rt_policy(p)) {
4894 p->static_prio = NICE_TO_PRIO(nice);
4895 goto out_unlock;
4897 on_rq = p->se.on_rq;
4898 if (on_rq)
4899 dequeue_task(rq, p, 0);
4901 p->static_prio = NICE_TO_PRIO(nice);
4902 set_load_weight(p);
4903 old_prio = p->prio;
4904 p->prio = effective_prio(p);
4905 delta = p->prio - old_prio;
4907 if (on_rq) {
4908 enqueue_task(rq, p, 0);
4910 * If the task increased its priority or is running and
4911 * lowered its priority, then reschedule its CPU:
4913 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4914 resched_task(rq->curr);
4916 out_unlock:
4917 task_rq_unlock(rq, &flags);
4919 EXPORT_SYMBOL(set_user_nice);
4922 * can_nice - check if a task can reduce its nice value
4923 * @p: task
4924 * @nice: nice value
4926 int can_nice(const struct task_struct *p, const int nice)
4928 /* convert nice value [19,-20] to rlimit style value [1,40] */
4929 int nice_rlim = 20 - nice;
4931 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4932 capable(CAP_SYS_NICE));
4935 #ifdef __ARCH_WANT_SYS_NICE
4938 * sys_nice - change the priority of the current process.
4939 * @increment: priority increment
4941 * sys_setpriority is a more generic, but much slower function that
4942 * does similar things.
4944 asmlinkage long sys_nice(int increment)
4946 long nice, retval;
4949 * Setpriority might change our priority at the same moment.
4950 * We don't have to worry. Conceptually one call occurs first
4951 * and we have a single winner.
4953 if (increment < -40)
4954 increment = -40;
4955 if (increment > 40)
4956 increment = 40;
4958 nice = PRIO_TO_NICE(current->static_prio) + increment;
4959 if (nice < -20)
4960 nice = -20;
4961 if (nice > 19)
4962 nice = 19;
4964 if (increment < 0 && !can_nice(current, nice))
4965 return -EPERM;
4967 retval = security_task_setnice(current, nice);
4968 if (retval)
4969 return retval;
4971 set_user_nice(current, nice);
4972 return 0;
4975 #endif
4978 * task_prio - return the priority value of a given task.
4979 * @p: the task in question.
4981 * This is the priority value as seen by users in /proc.
4982 * RT tasks are offset by -200. Normal tasks are centered
4983 * around 0, value goes from -16 to +15.
4985 int task_prio(const struct task_struct *p)
4987 return p->prio - MAX_RT_PRIO;
4991 * task_nice - return the nice value of a given task.
4992 * @p: the task in question.
4994 int task_nice(const struct task_struct *p)
4996 return TASK_NICE(p);
4998 EXPORT_SYMBOL(task_nice);
5001 * idle_cpu - is a given cpu idle currently?
5002 * @cpu: the processor in question.
5004 int idle_cpu(int cpu)
5006 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5010 * idle_task - return the idle task for a given cpu.
5011 * @cpu: the processor in question.
5013 struct task_struct *idle_task(int cpu)
5015 return cpu_rq(cpu)->idle;
5019 * find_process_by_pid - find a process with a matching PID value.
5020 * @pid: the pid in question.
5022 static struct task_struct *find_process_by_pid(pid_t pid)
5024 return pid ? find_task_by_vpid(pid) : current;
5027 /* Actually do priority change: must hold rq lock. */
5028 static void
5029 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5031 BUG_ON(p->se.on_rq);
5033 p->policy = policy;
5034 switch (p->policy) {
5035 case SCHED_NORMAL:
5036 case SCHED_BATCH:
5037 case SCHED_IDLE:
5038 p->sched_class = &fair_sched_class;
5039 break;
5040 case SCHED_FIFO:
5041 case SCHED_RR:
5042 p->sched_class = &rt_sched_class;
5043 break;
5046 p->rt_priority = prio;
5047 p->normal_prio = normal_prio(p);
5048 /* we are holding p->pi_lock already */
5049 p->prio = rt_mutex_getprio(p);
5050 set_load_weight(p);
5053 static int __sched_setscheduler(struct task_struct *p, int policy,
5054 struct sched_param *param, bool user)
5056 int retval, oldprio, oldpolicy = -1, on_rq, running;
5057 unsigned long flags;
5058 const struct sched_class *prev_class = p->sched_class;
5059 struct rq *rq;
5061 /* may grab non-irq protected spin_locks */
5062 BUG_ON(in_interrupt());
5063 recheck:
5064 /* double check policy once rq lock held */
5065 if (policy < 0)
5066 policy = oldpolicy = p->policy;
5067 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5068 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5069 policy != SCHED_IDLE)
5070 return -EINVAL;
5072 * Valid priorities for SCHED_FIFO and SCHED_RR are
5073 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5074 * SCHED_BATCH and SCHED_IDLE is 0.
5076 if (param->sched_priority < 0 ||
5077 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5078 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5079 return -EINVAL;
5080 if (rt_policy(policy) != (param->sched_priority != 0))
5081 return -EINVAL;
5084 * Allow unprivileged RT tasks to decrease priority:
5086 if (user && !capable(CAP_SYS_NICE)) {
5087 if (rt_policy(policy)) {
5088 unsigned long rlim_rtprio;
5090 if (!lock_task_sighand(p, &flags))
5091 return -ESRCH;
5092 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5093 unlock_task_sighand(p, &flags);
5095 /* can't set/change the rt policy */
5096 if (policy != p->policy && !rlim_rtprio)
5097 return -EPERM;
5099 /* can't increase priority */
5100 if (param->sched_priority > p->rt_priority &&
5101 param->sched_priority > rlim_rtprio)
5102 return -EPERM;
5105 * Like positive nice levels, dont allow tasks to
5106 * move out of SCHED_IDLE either:
5108 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5109 return -EPERM;
5111 /* can't change other user's priorities */
5112 if ((current->euid != p->euid) &&
5113 (current->euid != p->uid))
5114 return -EPERM;
5117 if (user) {
5118 #ifdef CONFIG_RT_GROUP_SCHED
5120 * Do not allow realtime tasks into groups that have no runtime
5121 * assigned.
5123 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5124 return -EPERM;
5125 #endif
5127 retval = security_task_setscheduler(p, policy, param);
5128 if (retval)
5129 return retval;
5133 * make sure no PI-waiters arrive (or leave) while we are
5134 * changing the priority of the task:
5136 spin_lock_irqsave(&p->pi_lock, flags);
5138 * To be able to change p->policy safely, the apropriate
5139 * runqueue lock must be held.
5141 rq = __task_rq_lock(p);
5142 /* recheck policy now with rq lock held */
5143 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5144 policy = oldpolicy = -1;
5145 __task_rq_unlock(rq);
5146 spin_unlock_irqrestore(&p->pi_lock, flags);
5147 goto recheck;
5149 update_rq_clock(rq);
5150 on_rq = p->se.on_rq;
5151 running = task_current(rq, p);
5152 if (on_rq)
5153 deactivate_task(rq, p, 0);
5154 if (running)
5155 p->sched_class->put_prev_task(rq, p);
5157 oldprio = p->prio;
5158 __setscheduler(rq, p, policy, param->sched_priority);
5160 if (running)
5161 p->sched_class->set_curr_task(rq);
5162 if (on_rq) {
5163 activate_task(rq, p, 0);
5165 check_class_changed(rq, p, prev_class, oldprio, running);
5167 __task_rq_unlock(rq);
5168 spin_unlock_irqrestore(&p->pi_lock, flags);
5170 rt_mutex_adjust_pi(p);
5172 return 0;
5176 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5177 * @p: the task in question.
5178 * @policy: new policy.
5179 * @param: structure containing the new RT priority.
5181 * NOTE that the task may be already dead.
5183 int sched_setscheduler(struct task_struct *p, int policy,
5184 struct sched_param *param)
5186 return __sched_setscheduler(p, policy, param, true);
5188 EXPORT_SYMBOL_GPL(sched_setscheduler);
5191 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5192 * @p: the task in question.
5193 * @policy: new policy.
5194 * @param: structure containing the new RT priority.
5196 * Just like sched_setscheduler, only don't bother checking if the
5197 * current context has permission. For example, this is needed in
5198 * stop_machine(): we create temporary high priority worker threads,
5199 * but our caller might not have that capability.
5201 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5202 struct sched_param *param)
5204 return __sched_setscheduler(p, policy, param, false);
5207 static int
5208 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5210 struct sched_param lparam;
5211 struct task_struct *p;
5212 int retval;
5214 if (!param || pid < 0)
5215 return -EINVAL;
5216 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5217 return -EFAULT;
5219 rcu_read_lock();
5220 retval = -ESRCH;
5221 p = find_process_by_pid(pid);
5222 if (p != NULL)
5223 retval = sched_setscheduler(p, policy, &lparam);
5224 rcu_read_unlock();
5226 return retval;
5230 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5231 * @pid: the pid in question.
5232 * @policy: new policy.
5233 * @param: structure containing the new RT priority.
5235 asmlinkage long
5236 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5238 /* negative values for policy are not valid */
5239 if (policy < 0)
5240 return -EINVAL;
5242 return do_sched_setscheduler(pid, policy, param);
5246 * sys_sched_setparam - set/change the RT priority of a thread
5247 * @pid: the pid in question.
5248 * @param: structure containing the new RT priority.
5250 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5252 return do_sched_setscheduler(pid, -1, param);
5256 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5257 * @pid: the pid in question.
5259 asmlinkage long sys_sched_getscheduler(pid_t pid)
5261 struct task_struct *p;
5262 int retval;
5264 if (pid < 0)
5265 return -EINVAL;
5267 retval = -ESRCH;
5268 read_lock(&tasklist_lock);
5269 p = find_process_by_pid(pid);
5270 if (p) {
5271 retval = security_task_getscheduler(p);
5272 if (!retval)
5273 retval = p->policy;
5275 read_unlock(&tasklist_lock);
5276 return retval;
5280 * sys_sched_getscheduler - get the RT priority of a thread
5281 * @pid: the pid in question.
5282 * @param: structure containing the RT priority.
5284 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5286 struct sched_param lp;
5287 struct task_struct *p;
5288 int retval;
5290 if (!param || pid < 0)
5291 return -EINVAL;
5293 read_lock(&tasklist_lock);
5294 p = find_process_by_pid(pid);
5295 retval = -ESRCH;
5296 if (!p)
5297 goto out_unlock;
5299 retval = security_task_getscheduler(p);
5300 if (retval)
5301 goto out_unlock;
5303 lp.sched_priority = p->rt_priority;
5304 read_unlock(&tasklist_lock);
5307 * This one might sleep, we cannot do it with a spinlock held ...
5309 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5311 return retval;
5313 out_unlock:
5314 read_unlock(&tasklist_lock);
5315 return retval;
5318 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5320 cpumask_t cpus_allowed;
5321 cpumask_t new_mask = *in_mask;
5322 struct task_struct *p;
5323 int retval;
5325 get_online_cpus();
5326 read_lock(&tasklist_lock);
5328 p = find_process_by_pid(pid);
5329 if (!p) {
5330 read_unlock(&tasklist_lock);
5331 put_online_cpus();
5332 return -ESRCH;
5336 * It is not safe to call set_cpus_allowed with the
5337 * tasklist_lock held. We will bump the task_struct's
5338 * usage count and then drop tasklist_lock.
5340 get_task_struct(p);
5341 read_unlock(&tasklist_lock);
5343 retval = -EPERM;
5344 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5345 !capable(CAP_SYS_NICE))
5346 goto out_unlock;
5348 retval = security_task_setscheduler(p, 0, NULL);
5349 if (retval)
5350 goto out_unlock;
5352 cpuset_cpus_allowed(p, &cpus_allowed);
5353 cpus_and(new_mask, new_mask, cpus_allowed);
5354 again:
5355 retval = set_cpus_allowed_ptr(p, &new_mask);
5357 if (!retval) {
5358 cpuset_cpus_allowed(p, &cpus_allowed);
5359 if (!cpus_subset(new_mask, cpus_allowed)) {
5361 * We must have raced with a concurrent cpuset
5362 * update. Just reset the cpus_allowed to the
5363 * cpuset's cpus_allowed
5365 new_mask = cpus_allowed;
5366 goto again;
5369 out_unlock:
5370 put_task_struct(p);
5371 put_online_cpus();
5372 return retval;
5375 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5376 cpumask_t *new_mask)
5378 if (len < sizeof(cpumask_t)) {
5379 memset(new_mask, 0, sizeof(cpumask_t));
5380 } else if (len > sizeof(cpumask_t)) {
5381 len = sizeof(cpumask_t);
5383 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5387 * sys_sched_setaffinity - set the cpu affinity of a process
5388 * @pid: pid of the process
5389 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5390 * @user_mask_ptr: user-space pointer to the new cpu mask
5392 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5393 unsigned long __user *user_mask_ptr)
5395 cpumask_t new_mask;
5396 int retval;
5398 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5399 if (retval)
5400 return retval;
5402 return sched_setaffinity(pid, &new_mask);
5405 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5407 struct task_struct *p;
5408 int retval;
5410 get_online_cpus();
5411 read_lock(&tasklist_lock);
5413 retval = -ESRCH;
5414 p = find_process_by_pid(pid);
5415 if (!p)
5416 goto out_unlock;
5418 retval = security_task_getscheduler(p);
5419 if (retval)
5420 goto out_unlock;
5422 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5424 out_unlock:
5425 read_unlock(&tasklist_lock);
5426 put_online_cpus();
5428 return retval;
5432 * sys_sched_getaffinity - get the cpu affinity of a process
5433 * @pid: pid of the process
5434 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5435 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5437 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5438 unsigned long __user *user_mask_ptr)
5440 int ret;
5441 cpumask_t mask;
5443 if (len < sizeof(cpumask_t))
5444 return -EINVAL;
5446 ret = sched_getaffinity(pid, &mask);
5447 if (ret < 0)
5448 return ret;
5450 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5451 return -EFAULT;
5453 return sizeof(cpumask_t);
5457 * sys_sched_yield - yield the current processor to other threads.
5459 * This function yields the current CPU to other tasks. If there are no
5460 * other threads running on this CPU then this function will return.
5462 asmlinkage long sys_sched_yield(void)
5464 struct rq *rq = this_rq_lock();
5466 schedstat_inc(rq, yld_count);
5467 current->sched_class->yield_task(rq);
5470 * Since we are going to call schedule() anyway, there's
5471 * no need to preempt or enable interrupts:
5473 __release(rq->lock);
5474 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5475 _raw_spin_unlock(&rq->lock);
5476 preempt_enable_no_resched();
5478 schedule();
5480 return 0;
5483 static void __cond_resched(void)
5485 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5486 __might_sleep(__FILE__, __LINE__);
5487 #endif
5489 * The BKS might be reacquired before we have dropped
5490 * PREEMPT_ACTIVE, which could trigger a second
5491 * cond_resched() call.
5493 do {
5494 add_preempt_count(PREEMPT_ACTIVE);
5495 schedule();
5496 sub_preempt_count(PREEMPT_ACTIVE);
5497 } while (need_resched());
5500 int __sched _cond_resched(void)
5502 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5503 system_state == SYSTEM_RUNNING) {
5504 __cond_resched();
5505 return 1;
5507 return 0;
5509 EXPORT_SYMBOL(_cond_resched);
5512 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5513 * call schedule, and on return reacquire the lock.
5515 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5516 * operations here to prevent schedule() from being called twice (once via
5517 * spin_unlock(), once by hand).
5519 int cond_resched_lock(spinlock_t *lock)
5521 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5522 int ret = 0;
5524 if (spin_needbreak(lock) || resched) {
5525 spin_unlock(lock);
5526 if (resched && need_resched())
5527 __cond_resched();
5528 else
5529 cpu_relax();
5530 ret = 1;
5531 spin_lock(lock);
5533 return ret;
5535 EXPORT_SYMBOL(cond_resched_lock);
5537 int __sched cond_resched_softirq(void)
5539 BUG_ON(!in_softirq());
5541 if (need_resched() && system_state == SYSTEM_RUNNING) {
5542 local_bh_enable();
5543 __cond_resched();
5544 local_bh_disable();
5545 return 1;
5547 return 0;
5549 EXPORT_SYMBOL(cond_resched_softirq);
5552 * yield - yield the current processor to other threads.
5554 * This is a shortcut for kernel-space yielding - it marks the
5555 * thread runnable and calls sys_sched_yield().
5557 void __sched yield(void)
5559 set_current_state(TASK_RUNNING);
5560 sys_sched_yield();
5562 EXPORT_SYMBOL(yield);
5565 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5566 * that process accounting knows that this is a task in IO wait state.
5568 * But don't do that if it is a deliberate, throttling IO wait (this task
5569 * has set its backing_dev_info: the queue against which it should throttle)
5571 void __sched io_schedule(void)
5573 struct rq *rq = &__raw_get_cpu_var(runqueues);
5575 delayacct_blkio_start();
5576 atomic_inc(&rq->nr_iowait);
5577 schedule();
5578 atomic_dec(&rq->nr_iowait);
5579 delayacct_blkio_end();
5581 EXPORT_SYMBOL(io_schedule);
5583 long __sched io_schedule_timeout(long timeout)
5585 struct rq *rq = &__raw_get_cpu_var(runqueues);
5586 long ret;
5588 delayacct_blkio_start();
5589 atomic_inc(&rq->nr_iowait);
5590 ret = schedule_timeout(timeout);
5591 atomic_dec(&rq->nr_iowait);
5592 delayacct_blkio_end();
5593 return ret;
5597 * sys_sched_get_priority_max - return maximum RT priority.
5598 * @policy: scheduling class.
5600 * this syscall returns the maximum rt_priority that can be used
5601 * by a given scheduling class.
5603 asmlinkage long sys_sched_get_priority_max(int policy)
5605 int ret = -EINVAL;
5607 switch (policy) {
5608 case SCHED_FIFO:
5609 case SCHED_RR:
5610 ret = MAX_USER_RT_PRIO-1;
5611 break;
5612 case SCHED_NORMAL:
5613 case SCHED_BATCH:
5614 case SCHED_IDLE:
5615 ret = 0;
5616 break;
5618 return ret;
5622 * sys_sched_get_priority_min - return minimum RT priority.
5623 * @policy: scheduling class.
5625 * this syscall returns the minimum rt_priority that can be used
5626 * by a given scheduling class.
5628 asmlinkage long sys_sched_get_priority_min(int policy)
5630 int ret = -EINVAL;
5632 switch (policy) {
5633 case SCHED_FIFO:
5634 case SCHED_RR:
5635 ret = 1;
5636 break;
5637 case SCHED_NORMAL:
5638 case SCHED_BATCH:
5639 case SCHED_IDLE:
5640 ret = 0;
5642 return ret;
5646 * sys_sched_rr_get_interval - return the default timeslice of a process.
5647 * @pid: pid of the process.
5648 * @interval: userspace pointer to the timeslice value.
5650 * this syscall writes the default timeslice value of a given process
5651 * into the user-space timespec buffer. A value of '0' means infinity.
5653 asmlinkage
5654 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5656 struct task_struct *p;
5657 unsigned int time_slice;
5658 int retval;
5659 struct timespec t;
5661 if (pid < 0)
5662 return -EINVAL;
5664 retval = -ESRCH;
5665 read_lock(&tasklist_lock);
5666 p = find_process_by_pid(pid);
5667 if (!p)
5668 goto out_unlock;
5670 retval = security_task_getscheduler(p);
5671 if (retval)
5672 goto out_unlock;
5675 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5676 * tasks that are on an otherwise idle runqueue:
5678 time_slice = 0;
5679 if (p->policy == SCHED_RR) {
5680 time_slice = DEF_TIMESLICE;
5681 } else if (p->policy != SCHED_FIFO) {
5682 struct sched_entity *se = &p->se;
5683 unsigned long flags;
5684 struct rq *rq;
5686 rq = task_rq_lock(p, &flags);
5687 if (rq->cfs.load.weight)
5688 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5689 task_rq_unlock(rq, &flags);
5691 read_unlock(&tasklist_lock);
5692 jiffies_to_timespec(time_slice, &t);
5693 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5694 return retval;
5696 out_unlock:
5697 read_unlock(&tasklist_lock);
5698 return retval;
5701 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5703 void sched_show_task(struct task_struct *p)
5705 unsigned long free = 0;
5706 unsigned state;
5708 state = p->state ? __ffs(p->state) + 1 : 0;
5709 printk(KERN_INFO "%-13.13s %c", p->comm,
5710 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5711 #if BITS_PER_LONG == 32
5712 if (state == TASK_RUNNING)
5713 printk(KERN_CONT " running ");
5714 else
5715 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5716 #else
5717 if (state == TASK_RUNNING)
5718 printk(KERN_CONT " running task ");
5719 else
5720 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5721 #endif
5722 #ifdef CONFIG_DEBUG_STACK_USAGE
5724 unsigned long *n = end_of_stack(p);
5725 while (!*n)
5726 n++;
5727 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5729 #endif
5730 printk(KERN_CONT "%5lu %5d %6d\n", free,
5731 task_pid_nr(p), task_pid_nr(p->real_parent));
5733 show_stack(p, NULL);
5736 void show_state_filter(unsigned long state_filter)
5738 struct task_struct *g, *p;
5740 #if BITS_PER_LONG == 32
5741 printk(KERN_INFO
5742 " task PC stack pid father\n");
5743 #else
5744 printk(KERN_INFO
5745 " task PC stack pid father\n");
5746 #endif
5747 read_lock(&tasklist_lock);
5748 do_each_thread(g, p) {
5750 * reset the NMI-timeout, listing all files on a slow
5751 * console might take alot of time:
5753 touch_nmi_watchdog();
5754 if (!state_filter || (p->state & state_filter))
5755 sched_show_task(p);
5756 } while_each_thread(g, p);
5758 touch_all_softlockup_watchdogs();
5760 #ifdef CONFIG_SCHED_DEBUG
5761 sysrq_sched_debug_show();
5762 #endif
5763 read_unlock(&tasklist_lock);
5765 * Only show locks if all tasks are dumped:
5767 if (state_filter == -1)
5768 debug_show_all_locks();
5771 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5773 idle->sched_class = &idle_sched_class;
5777 * init_idle - set up an idle thread for a given CPU
5778 * @idle: task in question
5779 * @cpu: cpu the idle task belongs to
5781 * NOTE: this function does not set the idle thread's NEED_RESCHED
5782 * flag, to make booting more robust.
5784 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5786 struct rq *rq = cpu_rq(cpu);
5787 unsigned long flags;
5789 __sched_fork(idle);
5790 idle->se.exec_start = sched_clock();
5792 idle->prio = idle->normal_prio = MAX_PRIO;
5793 idle->cpus_allowed = cpumask_of_cpu(cpu);
5794 __set_task_cpu(idle, cpu);
5796 spin_lock_irqsave(&rq->lock, flags);
5797 rq->curr = rq->idle = idle;
5798 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5799 idle->oncpu = 1;
5800 #endif
5801 spin_unlock_irqrestore(&rq->lock, flags);
5803 /* Set the preempt count _outside_ the spinlocks! */
5804 #if defined(CONFIG_PREEMPT)
5805 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5806 #else
5807 task_thread_info(idle)->preempt_count = 0;
5808 #endif
5810 * The idle tasks have their own, simple scheduling class:
5812 idle->sched_class = &idle_sched_class;
5816 * In a system that switches off the HZ timer nohz_cpu_mask
5817 * indicates which cpus entered this state. This is used
5818 * in the rcu update to wait only for active cpus. For system
5819 * which do not switch off the HZ timer nohz_cpu_mask should
5820 * always be CPU_MASK_NONE.
5822 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5825 * Increase the granularity value when there are more CPUs,
5826 * because with more CPUs the 'effective latency' as visible
5827 * to users decreases. But the relationship is not linear,
5828 * so pick a second-best guess by going with the log2 of the
5829 * number of CPUs.
5831 * This idea comes from the SD scheduler of Con Kolivas:
5833 static inline void sched_init_granularity(void)
5835 unsigned int factor = 1 + ilog2(num_online_cpus());
5836 const unsigned long limit = 200000000;
5838 sysctl_sched_min_granularity *= factor;
5839 if (sysctl_sched_min_granularity > limit)
5840 sysctl_sched_min_granularity = limit;
5842 sysctl_sched_latency *= factor;
5843 if (sysctl_sched_latency > limit)
5844 sysctl_sched_latency = limit;
5846 sysctl_sched_wakeup_granularity *= factor;
5848 sysctl_sched_shares_ratelimit *= factor;
5851 #ifdef CONFIG_SMP
5853 * This is how migration works:
5855 * 1) we queue a struct migration_req structure in the source CPU's
5856 * runqueue and wake up that CPU's migration thread.
5857 * 2) we down() the locked semaphore => thread blocks.
5858 * 3) migration thread wakes up (implicitly it forces the migrated
5859 * thread off the CPU)
5860 * 4) it gets the migration request and checks whether the migrated
5861 * task is still in the wrong runqueue.
5862 * 5) if it's in the wrong runqueue then the migration thread removes
5863 * it and puts it into the right queue.
5864 * 6) migration thread up()s the semaphore.
5865 * 7) we wake up and the migration is done.
5869 * Change a given task's CPU affinity. Migrate the thread to a
5870 * proper CPU and schedule it away if the CPU it's executing on
5871 * is removed from the allowed bitmask.
5873 * NOTE: the caller must have a valid reference to the task, the
5874 * task must not exit() & deallocate itself prematurely. The
5875 * call is not atomic; no spinlocks may be held.
5877 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
5879 struct migration_req req;
5880 unsigned long flags;
5881 struct rq *rq;
5882 int ret = 0;
5884 rq = task_rq_lock(p, &flags);
5885 if (!cpus_intersects(*new_mask, cpu_online_map)) {
5886 ret = -EINVAL;
5887 goto out;
5890 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
5891 !cpus_equal(p->cpus_allowed, *new_mask))) {
5892 ret = -EINVAL;
5893 goto out;
5896 if (p->sched_class->set_cpus_allowed)
5897 p->sched_class->set_cpus_allowed(p, new_mask);
5898 else {
5899 p->cpus_allowed = *new_mask;
5900 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
5903 /* Can the task run on the task's current CPU? If so, we're done */
5904 if (cpu_isset(task_cpu(p), *new_mask))
5905 goto out;
5907 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
5908 /* Need help from migration thread: drop lock and wait. */
5909 task_rq_unlock(rq, &flags);
5910 wake_up_process(rq->migration_thread);
5911 wait_for_completion(&req.done);
5912 tlb_migrate_finish(p->mm);
5913 return 0;
5915 out:
5916 task_rq_unlock(rq, &flags);
5918 return ret;
5920 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5923 * Move (not current) task off this cpu, onto dest cpu. We're doing
5924 * this because either it can't run here any more (set_cpus_allowed()
5925 * away from this CPU, or CPU going down), or because we're
5926 * attempting to rebalance this task on exec (sched_exec).
5928 * So we race with normal scheduler movements, but that's OK, as long
5929 * as the task is no longer on this CPU.
5931 * Returns non-zero if task was successfully migrated.
5933 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5935 struct rq *rq_dest, *rq_src;
5936 int ret = 0, on_rq;
5938 if (unlikely(!cpu_active(dest_cpu)))
5939 return ret;
5941 rq_src = cpu_rq(src_cpu);
5942 rq_dest = cpu_rq(dest_cpu);
5944 double_rq_lock(rq_src, rq_dest);
5945 /* Already moved. */
5946 if (task_cpu(p) != src_cpu)
5947 goto done;
5948 /* Affinity changed (again). */
5949 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5950 goto fail;
5952 on_rq = p->se.on_rq;
5953 if (on_rq)
5954 deactivate_task(rq_src, p, 0);
5956 set_task_cpu(p, dest_cpu);
5957 if (on_rq) {
5958 activate_task(rq_dest, p, 0);
5959 check_preempt_curr(rq_dest, p);
5961 done:
5962 ret = 1;
5963 fail:
5964 double_rq_unlock(rq_src, rq_dest);
5965 return ret;
5969 * migration_thread - this is a highprio system thread that performs
5970 * thread migration by bumping thread off CPU then 'pushing' onto
5971 * another runqueue.
5973 static int migration_thread(void *data)
5975 int cpu = (long)data;
5976 struct rq *rq;
5978 rq = cpu_rq(cpu);
5979 BUG_ON(rq->migration_thread != current);
5981 set_current_state(TASK_INTERRUPTIBLE);
5982 while (!kthread_should_stop()) {
5983 struct migration_req *req;
5984 struct list_head *head;
5986 spin_lock_irq(&rq->lock);
5988 if (cpu_is_offline(cpu)) {
5989 spin_unlock_irq(&rq->lock);
5990 goto wait_to_die;
5993 if (rq->active_balance) {
5994 active_load_balance(rq, cpu);
5995 rq->active_balance = 0;
5998 head = &rq->migration_queue;
6000 if (list_empty(head)) {
6001 spin_unlock_irq(&rq->lock);
6002 schedule();
6003 set_current_state(TASK_INTERRUPTIBLE);
6004 continue;
6006 req = list_entry(head->next, struct migration_req, list);
6007 list_del_init(head->next);
6009 spin_unlock(&rq->lock);
6010 __migrate_task(req->task, cpu, req->dest_cpu);
6011 local_irq_enable();
6013 complete(&req->done);
6015 __set_current_state(TASK_RUNNING);
6016 return 0;
6018 wait_to_die:
6019 /* Wait for kthread_stop */
6020 set_current_state(TASK_INTERRUPTIBLE);
6021 while (!kthread_should_stop()) {
6022 schedule();
6023 set_current_state(TASK_INTERRUPTIBLE);
6025 __set_current_state(TASK_RUNNING);
6026 return 0;
6029 #ifdef CONFIG_HOTPLUG_CPU
6031 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6033 int ret;
6035 local_irq_disable();
6036 ret = __migrate_task(p, src_cpu, dest_cpu);
6037 local_irq_enable();
6038 return ret;
6042 * Figure out where task on dead CPU should go, use force if necessary.
6043 * NOTE: interrupts should be disabled by the caller
6045 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6047 unsigned long flags;
6048 cpumask_t mask;
6049 struct rq *rq;
6050 int dest_cpu;
6052 do {
6053 /* On same node? */
6054 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6055 cpus_and(mask, mask, p->cpus_allowed);
6056 dest_cpu = any_online_cpu(mask);
6058 /* On any allowed CPU? */
6059 if (dest_cpu >= nr_cpu_ids)
6060 dest_cpu = any_online_cpu(p->cpus_allowed);
6062 /* No more Mr. Nice Guy. */
6063 if (dest_cpu >= nr_cpu_ids) {
6064 cpumask_t cpus_allowed;
6066 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6068 * Try to stay on the same cpuset, where the
6069 * current cpuset may be a subset of all cpus.
6070 * The cpuset_cpus_allowed_locked() variant of
6071 * cpuset_cpus_allowed() will not block. It must be
6072 * called within calls to cpuset_lock/cpuset_unlock.
6074 rq = task_rq_lock(p, &flags);
6075 p->cpus_allowed = cpus_allowed;
6076 dest_cpu = any_online_cpu(p->cpus_allowed);
6077 task_rq_unlock(rq, &flags);
6080 * Don't tell them about moving exiting tasks or
6081 * kernel threads (both mm NULL), since they never
6082 * leave kernel.
6084 if (p->mm && printk_ratelimit()) {
6085 printk(KERN_INFO "process %d (%s) no "
6086 "longer affine to cpu%d\n",
6087 task_pid_nr(p), p->comm, dead_cpu);
6090 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6094 * While a dead CPU has no uninterruptible tasks queued at this point,
6095 * it might still have a nonzero ->nr_uninterruptible counter, because
6096 * for performance reasons the counter is not stricly tracking tasks to
6097 * their home CPUs. So we just add the counter to another CPU's counter,
6098 * to keep the global sum constant after CPU-down:
6100 static void migrate_nr_uninterruptible(struct rq *rq_src)
6102 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6103 unsigned long flags;
6105 local_irq_save(flags);
6106 double_rq_lock(rq_src, rq_dest);
6107 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6108 rq_src->nr_uninterruptible = 0;
6109 double_rq_unlock(rq_src, rq_dest);
6110 local_irq_restore(flags);
6113 /* Run through task list and migrate tasks from the dead cpu. */
6114 static void migrate_live_tasks(int src_cpu)
6116 struct task_struct *p, *t;
6118 read_lock(&tasklist_lock);
6120 do_each_thread(t, p) {
6121 if (p == current)
6122 continue;
6124 if (task_cpu(p) == src_cpu)
6125 move_task_off_dead_cpu(src_cpu, p);
6126 } while_each_thread(t, p);
6128 read_unlock(&tasklist_lock);
6132 * Schedules idle task to be the next runnable task on current CPU.
6133 * It does so by boosting its priority to highest possible.
6134 * Used by CPU offline code.
6136 void sched_idle_next(void)
6138 int this_cpu = smp_processor_id();
6139 struct rq *rq = cpu_rq(this_cpu);
6140 struct task_struct *p = rq->idle;
6141 unsigned long flags;
6143 /* cpu has to be offline */
6144 BUG_ON(cpu_online(this_cpu));
6147 * Strictly not necessary since rest of the CPUs are stopped by now
6148 * and interrupts disabled on the current cpu.
6150 spin_lock_irqsave(&rq->lock, flags);
6152 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6154 update_rq_clock(rq);
6155 activate_task(rq, p, 0);
6157 spin_unlock_irqrestore(&rq->lock, flags);
6161 * Ensures that the idle task is using init_mm right before its cpu goes
6162 * offline.
6164 void idle_task_exit(void)
6166 struct mm_struct *mm = current->active_mm;
6168 BUG_ON(cpu_online(smp_processor_id()));
6170 if (mm != &init_mm)
6171 switch_mm(mm, &init_mm, current);
6172 mmdrop(mm);
6175 /* called under rq->lock with disabled interrupts */
6176 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6178 struct rq *rq = cpu_rq(dead_cpu);
6180 /* Must be exiting, otherwise would be on tasklist. */
6181 BUG_ON(!p->exit_state);
6183 /* Cannot have done final schedule yet: would have vanished. */
6184 BUG_ON(p->state == TASK_DEAD);
6186 get_task_struct(p);
6189 * Drop lock around migration; if someone else moves it,
6190 * that's OK. No task can be added to this CPU, so iteration is
6191 * fine.
6193 spin_unlock_irq(&rq->lock);
6194 move_task_off_dead_cpu(dead_cpu, p);
6195 spin_lock_irq(&rq->lock);
6197 put_task_struct(p);
6200 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6201 static void migrate_dead_tasks(unsigned int dead_cpu)
6203 struct rq *rq = cpu_rq(dead_cpu);
6204 struct task_struct *next;
6206 for ( ; ; ) {
6207 if (!rq->nr_running)
6208 break;
6209 update_rq_clock(rq);
6210 next = pick_next_task(rq, rq->curr);
6211 if (!next)
6212 break;
6213 next->sched_class->put_prev_task(rq, next);
6214 migrate_dead(dead_cpu, next);
6218 #endif /* CONFIG_HOTPLUG_CPU */
6220 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6222 static struct ctl_table sd_ctl_dir[] = {
6224 .procname = "sched_domain",
6225 .mode = 0555,
6227 {0, },
6230 static struct ctl_table sd_ctl_root[] = {
6232 .ctl_name = CTL_KERN,
6233 .procname = "kernel",
6234 .mode = 0555,
6235 .child = sd_ctl_dir,
6237 {0, },
6240 static struct ctl_table *sd_alloc_ctl_entry(int n)
6242 struct ctl_table *entry =
6243 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6245 return entry;
6248 static void sd_free_ctl_entry(struct ctl_table **tablep)
6250 struct ctl_table *entry;
6253 * In the intermediate directories, both the child directory and
6254 * procname are dynamically allocated and could fail but the mode
6255 * will always be set. In the lowest directory the names are
6256 * static strings and all have proc handlers.
6258 for (entry = *tablep; entry->mode; entry++) {
6259 if (entry->child)
6260 sd_free_ctl_entry(&entry->child);
6261 if (entry->proc_handler == NULL)
6262 kfree(entry->procname);
6265 kfree(*tablep);
6266 *tablep = NULL;
6269 static void
6270 set_table_entry(struct ctl_table *entry,
6271 const char *procname, void *data, int maxlen,
6272 mode_t mode, proc_handler *proc_handler)
6274 entry->procname = procname;
6275 entry->data = data;
6276 entry->maxlen = maxlen;
6277 entry->mode = mode;
6278 entry->proc_handler = proc_handler;
6281 static struct ctl_table *
6282 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6284 struct ctl_table *table = sd_alloc_ctl_entry(12);
6286 if (table == NULL)
6287 return NULL;
6289 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6290 sizeof(long), 0644, proc_doulongvec_minmax);
6291 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6292 sizeof(long), 0644, proc_doulongvec_minmax);
6293 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6294 sizeof(int), 0644, proc_dointvec_minmax);
6295 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6296 sizeof(int), 0644, proc_dointvec_minmax);
6297 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6298 sizeof(int), 0644, proc_dointvec_minmax);
6299 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6300 sizeof(int), 0644, proc_dointvec_minmax);
6301 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6302 sizeof(int), 0644, proc_dointvec_minmax);
6303 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6304 sizeof(int), 0644, proc_dointvec_minmax);
6305 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6306 sizeof(int), 0644, proc_dointvec_minmax);
6307 set_table_entry(&table[9], "cache_nice_tries",
6308 &sd->cache_nice_tries,
6309 sizeof(int), 0644, proc_dointvec_minmax);
6310 set_table_entry(&table[10], "flags", &sd->flags,
6311 sizeof(int), 0644, proc_dointvec_minmax);
6312 /* &table[11] is terminator */
6314 return table;
6317 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6319 struct ctl_table *entry, *table;
6320 struct sched_domain *sd;
6321 int domain_num = 0, i;
6322 char buf[32];
6324 for_each_domain(cpu, sd)
6325 domain_num++;
6326 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6327 if (table == NULL)
6328 return NULL;
6330 i = 0;
6331 for_each_domain(cpu, sd) {
6332 snprintf(buf, 32, "domain%d", i);
6333 entry->procname = kstrdup(buf, GFP_KERNEL);
6334 entry->mode = 0555;
6335 entry->child = sd_alloc_ctl_domain_table(sd);
6336 entry++;
6337 i++;
6339 return table;
6342 static struct ctl_table_header *sd_sysctl_header;
6343 static void register_sched_domain_sysctl(void)
6345 int i, cpu_num = num_online_cpus();
6346 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6347 char buf[32];
6349 WARN_ON(sd_ctl_dir[0].child);
6350 sd_ctl_dir[0].child = entry;
6352 if (entry == NULL)
6353 return;
6355 for_each_online_cpu(i) {
6356 snprintf(buf, 32, "cpu%d", i);
6357 entry->procname = kstrdup(buf, GFP_KERNEL);
6358 entry->mode = 0555;
6359 entry->child = sd_alloc_ctl_cpu_table(i);
6360 entry++;
6363 WARN_ON(sd_sysctl_header);
6364 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6367 /* may be called multiple times per register */
6368 static void unregister_sched_domain_sysctl(void)
6370 if (sd_sysctl_header)
6371 unregister_sysctl_table(sd_sysctl_header);
6372 sd_sysctl_header = NULL;
6373 if (sd_ctl_dir[0].child)
6374 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6376 #else
6377 static void register_sched_domain_sysctl(void)
6380 static void unregister_sched_domain_sysctl(void)
6383 #endif
6385 static void set_rq_online(struct rq *rq)
6387 if (!rq->online) {
6388 const struct sched_class *class;
6390 cpu_set(rq->cpu, rq->rd->online);
6391 rq->online = 1;
6393 for_each_class(class) {
6394 if (class->rq_online)
6395 class->rq_online(rq);
6400 static void set_rq_offline(struct rq *rq)
6402 if (rq->online) {
6403 const struct sched_class *class;
6405 for_each_class(class) {
6406 if (class->rq_offline)
6407 class->rq_offline(rq);
6410 cpu_clear(rq->cpu, rq->rd->online);
6411 rq->online = 0;
6416 * migration_call - callback that gets triggered when a CPU is added.
6417 * Here we can start up the necessary migration thread for the new CPU.
6419 static int __cpuinit
6420 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6422 struct task_struct *p;
6423 int cpu = (long)hcpu;
6424 unsigned long flags;
6425 struct rq *rq;
6427 switch (action) {
6429 case CPU_UP_PREPARE:
6430 case CPU_UP_PREPARE_FROZEN:
6431 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6432 if (IS_ERR(p))
6433 return NOTIFY_BAD;
6434 kthread_bind(p, cpu);
6435 /* Must be high prio: stop_machine expects to yield to it. */
6436 rq = task_rq_lock(p, &flags);
6437 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6438 task_rq_unlock(rq, &flags);
6439 cpu_rq(cpu)->migration_thread = p;
6440 break;
6442 case CPU_ONLINE:
6443 case CPU_ONLINE_FROZEN:
6444 /* Strictly unnecessary, as first user will wake it. */
6445 wake_up_process(cpu_rq(cpu)->migration_thread);
6447 /* Update our root-domain */
6448 rq = cpu_rq(cpu);
6449 spin_lock_irqsave(&rq->lock, flags);
6450 if (rq->rd) {
6451 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6453 set_rq_online(rq);
6455 spin_unlock_irqrestore(&rq->lock, flags);
6456 break;
6458 #ifdef CONFIG_HOTPLUG_CPU
6459 case CPU_UP_CANCELED:
6460 case CPU_UP_CANCELED_FROZEN:
6461 if (!cpu_rq(cpu)->migration_thread)
6462 break;
6463 /* Unbind it from offline cpu so it can run. Fall thru. */
6464 kthread_bind(cpu_rq(cpu)->migration_thread,
6465 any_online_cpu(cpu_online_map));
6466 kthread_stop(cpu_rq(cpu)->migration_thread);
6467 cpu_rq(cpu)->migration_thread = NULL;
6468 break;
6470 case CPU_DEAD:
6471 case CPU_DEAD_FROZEN:
6472 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6473 migrate_live_tasks(cpu);
6474 rq = cpu_rq(cpu);
6475 kthread_stop(rq->migration_thread);
6476 rq->migration_thread = NULL;
6477 /* Idle task back to normal (off runqueue, low prio) */
6478 spin_lock_irq(&rq->lock);
6479 update_rq_clock(rq);
6480 deactivate_task(rq, rq->idle, 0);
6481 rq->idle->static_prio = MAX_PRIO;
6482 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6483 rq->idle->sched_class = &idle_sched_class;
6484 migrate_dead_tasks(cpu);
6485 spin_unlock_irq(&rq->lock);
6486 cpuset_unlock();
6487 migrate_nr_uninterruptible(rq);
6488 BUG_ON(rq->nr_running != 0);
6491 * No need to migrate the tasks: it was best-effort if
6492 * they didn't take sched_hotcpu_mutex. Just wake up
6493 * the requestors.
6495 spin_lock_irq(&rq->lock);
6496 while (!list_empty(&rq->migration_queue)) {
6497 struct migration_req *req;
6499 req = list_entry(rq->migration_queue.next,
6500 struct migration_req, list);
6501 list_del_init(&req->list);
6502 complete(&req->done);
6504 spin_unlock_irq(&rq->lock);
6505 break;
6507 case CPU_DYING:
6508 case CPU_DYING_FROZEN:
6509 /* Update our root-domain */
6510 rq = cpu_rq(cpu);
6511 spin_lock_irqsave(&rq->lock, flags);
6512 if (rq->rd) {
6513 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6514 set_rq_offline(rq);
6516 spin_unlock_irqrestore(&rq->lock, flags);
6517 break;
6518 #endif
6520 return NOTIFY_OK;
6523 /* Register at highest priority so that task migration (migrate_all_tasks)
6524 * happens before everything else.
6526 static struct notifier_block __cpuinitdata migration_notifier = {
6527 .notifier_call = migration_call,
6528 .priority = 10
6531 static int __init migration_init(void)
6533 void *cpu = (void *)(long)smp_processor_id();
6534 int err;
6536 /* Start one for the boot CPU: */
6537 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6538 BUG_ON(err == NOTIFY_BAD);
6539 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6540 register_cpu_notifier(&migration_notifier);
6542 return err;
6544 early_initcall(migration_init);
6545 #endif
6547 #ifdef CONFIG_SMP
6549 #ifdef CONFIG_SCHED_DEBUG
6551 static inline const char *sd_level_to_string(enum sched_domain_level lvl)
6553 switch (lvl) {
6554 case SD_LV_NONE:
6555 return "NONE";
6556 case SD_LV_SIBLING:
6557 return "SIBLING";
6558 case SD_LV_MC:
6559 return "MC";
6560 case SD_LV_CPU:
6561 return "CPU";
6562 case SD_LV_NODE:
6563 return "NODE";
6564 case SD_LV_ALLNODES:
6565 return "ALLNODES";
6566 case SD_LV_MAX:
6567 return "MAX";
6570 return "MAX";
6573 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6574 cpumask_t *groupmask)
6576 struct sched_group *group = sd->groups;
6577 char str[256];
6579 cpulist_scnprintf(str, sizeof(str), sd->span);
6580 cpus_clear(*groupmask);
6582 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6584 if (!(sd->flags & SD_LOAD_BALANCE)) {
6585 printk("does not load-balance\n");
6586 if (sd->parent)
6587 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6588 " has parent");
6589 return -1;
6592 printk(KERN_CONT "span %s level %s\n",
6593 str, sd_level_to_string(sd->level));
6595 if (!cpu_isset(cpu, sd->span)) {
6596 printk(KERN_ERR "ERROR: domain->span does not contain "
6597 "CPU%d\n", cpu);
6599 if (!cpu_isset(cpu, group->cpumask)) {
6600 printk(KERN_ERR "ERROR: domain->groups does not contain"
6601 " CPU%d\n", cpu);
6604 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6605 do {
6606 if (!group) {
6607 printk("\n");
6608 printk(KERN_ERR "ERROR: group is NULL\n");
6609 break;
6612 if (!group->__cpu_power) {
6613 printk(KERN_CONT "\n");
6614 printk(KERN_ERR "ERROR: domain->cpu_power not "
6615 "set\n");
6616 break;
6619 if (!cpus_weight(group->cpumask)) {
6620 printk(KERN_CONT "\n");
6621 printk(KERN_ERR "ERROR: empty group\n");
6622 break;
6625 if (cpus_intersects(*groupmask, group->cpumask)) {
6626 printk(KERN_CONT "\n");
6627 printk(KERN_ERR "ERROR: repeated CPUs\n");
6628 break;
6631 cpus_or(*groupmask, *groupmask, group->cpumask);
6633 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6634 printk(KERN_CONT " %s", str);
6636 group = group->next;
6637 } while (group != sd->groups);
6638 printk(KERN_CONT "\n");
6640 if (!cpus_equal(sd->span, *groupmask))
6641 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6643 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6644 printk(KERN_ERR "ERROR: parent span is not a superset "
6645 "of domain->span\n");
6646 return 0;
6649 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6651 cpumask_t *groupmask;
6652 int level = 0;
6654 if (!sd) {
6655 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6656 return;
6659 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6661 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6662 if (!groupmask) {
6663 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6664 return;
6667 for (;;) {
6668 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6669 break;
6670 level++;
6671 sd = sd->parent;
6672 if (!sd)
6673 break;
6675 kfree(groupmask);
6677 #else /* !CONFIG_SCHED_DEBUG */
6678 # define sched_domain_debug(sd, cpu) do { } while (0)
6679 #endif /* CONFIG_SCHED_DEBUG */
6681 static int sd_degenerate(struct sched_domain *sd)
6683 if (cpus_weight(sd->span) == 1)
6684 return 1;
6686 /* Following flags need at least 2 groups */
6687 if (sd->flags & (SD_LOAD_BALANCE |
6688 SD_BALANCE_NEWIDLE |
6689 SD_BALANCE_FORK |
6690 SD_BALANCE_EXEC |
6691 SD_SHARE_CPUPOWER |
6692 SD_SHARE_PKG_RESOURCES)) {
6693 if (sd->groups != sd->groups->next)
6694 return 0;
6697 /* Following flags don't use groups */
6698 if (sd->flags & (SD_WAKE_IDLE |
6699 SD_WAKE_AFFINE |
6700 SD_WAKE_BALANCE))
6701 return 0;
6703 return 1;
6706 static int
6707 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6709 unsigned long cflags = sd->flags, pflags = parent->flags;
6711 if (sd_degenerate(parent))
6712 return 1;
6714 if (!cpus_equal(sd->span, parent->span))
6715 return 0;
6717 /* Does parent contain flags not in child? */
6718 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6719 if (cflags & SD_WAKE_AFFINE)
6720 pflags &= ~SD_WAKE_BALANCE;
6721 /* Flags needing groups don't count if only 1 group in parent */
6722 if (parent->groups == parent->groups->next) {
6723 pflags &= ~(SD_LOAD_BALANCE |
6724 SD_BALANCE_NEWIDLE |
6725 SD_BALANCE_FORK |
6726 SD_BALANCE_EXEC |
6727 SD_SHARE_CPUPOWER |
6728 SD_SHARE_PKG_RESOURCES);
6730 if (~cflags & pflags)
6731 return 0;
6733 return 1;
6736 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6738 unsigned long flags;
6740 spin_lock_irqsave(&rq->lock, flags);
6742 if (rq->rd) {
6743 struct root_domain *old_rd = rq->rd;
6745 if (cpu_isset(rq->cpu, old_rd->online))
6746 set_rq_offline(rq);
6748 cpu_clear(rq->cpu, old_rd->span);
6750 if (atomic_dec_and_test(&old_rd->refcount))
6751 kfree(old_rd);
6754 atomic_inc(&rd->refcount);
6755 rq->rd = rd;
6757 cpu_set(rq->cpu, rd->span);
6758 if (cpu_isset(rq->cpu, cpu_online_map))
6759 set_rq_online(rq);
6761 spin_unlock_irqrestore(&rq->lock, flags);
6764 static void init_rootdomain(struct root_domain *rd)
6766 memset(rd, 0, sizeof(*rd));
6768 cpus_clear(rd->span);
6769 cpus_clear(rd->online);
6771 cpupri_init(&rd->cpupri);
6774 static void init_defrootdomain(void)
6776 init_rootdomain(&def_root_domain);
6777 atomic_set(&def_root_domain.refcount, 1);
6780 static struct root_domain *alloc_rootdomain(void)
6782 struct root_domain *rd;
6784 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6785 if (!rd)
6786 return NULL;
6788 init_rootdomain(rd);
6790 return rd;
6794 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6795 * hold the hotplug lock.
6797 static void
6798 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6800 struct rq *rq = cpu_rq(cpu);
6801 struct sched_domain *tmp;
6803 /* Remove the sched domains which do not contribute to scheduling. */
6804 for (tmp = sd; tmp; tmp = tmp->parent) {
6805 struct sched_domain *parent = tmp->parent;
6806 if (!parent)
6807 break;
6808 if (sd_parent_degenerate(tmp, parent)) {
6809 tmp->parent = parent->parent;
6810 if (parent->parent)
6811 parent->parent->child = tmp;
6815 if (sd && sd_degenerate(sd)) {
6816 sd = sd->parent;
6817 if (sd)
6818 sd->child = NULL;
6821 sched_domain_debug(sd, cpu);
6823 rq_attach_root(rq, rd);
6824 rcu_assign_pointer(rq->sd, sd);
6827 /* cpus with isolated domains */
6828 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6830 /* Setup the mask of cpus configured for isolated domains */
6831 static int __init isolated_cpu_setup(char *str)
6833 static int __initdata ints[NR_CPUS];
6834 int i;
6836 str = get_options(str, ARRAY_SIZE(ints), ints);
6837 cpus_clear(cpu_isolated_map);
6838 for (i = 1; i <= ints[0]; i++)
6839 if (ints[i] < NR_CPUS)
6840 cpu_set(ints[i], cpu_isolated_map);
6841 return 1;
6844 __setup("isolcpus=", isolated_cpu_setup);
6847 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6848 * to a function which identifies what group(along with sched group) a CPU
6849 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6850 * (due to the fact that we keep track of groups covered with a cpumask_t).
6852 * init_sched_build_groups will build a circular linked list of the groups
6853 * covered by the given span, and will set each group's ->cpumask correctly,
6854 * and ->cpu_power to 0.
6856 static void
6857 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6858 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6859 struct sched_group **sg,
6860 cpumask_t *tmpmask),
6861 cpumask_t *covered, cpumask_t *tmpmask)
6863 struct sched_group *first = NULL, *last = NULL;
6864 int i;
6866 cpus_clear(*covered);
6868 for_each_cpu_mask_nr(i, *span) {
6869 struct sched_group *sg;
6870 int group = group_fn(i, cpu_map, &sg, tmpmask);
6871 int j;
6873 if (cpu_isset(i, *covered))
6874 continue;
6876 cpus_clear(sg->cpumask);
6877 sg->__cpu_power = 0;
6879 for_each_cpu_mask_nr(j, *span) {
6880 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6881 continue;
6883 cpu_set(j, *covered);
6884 cpu_set(j, sg->cpumask);
6886 if (!first)
6887 first = sg;
6888 if (last)
6889 last->next = sg;
6890 last = sg;
6892 last->next = first;
6895 #define SD_NODES_PER_DOMAIN 16
6897 #ifdef CONFIG_NUMA
6900 * find_next_best_node - find the next node to include in a sched_domain
6901 * @node: node whose sched_domain we're building
6902 * @used_nodes: nodes already in the sched_domain
6904 * Find the next node to include in a given scheduling domain. Simply
6905 * finds the closest node not already in the @used_nodes map.
6907 * Should use nodemask_t.
6909 static int find_next_best_node(int node, nodemask_t *used_nodes)
6911 int i, n, val, min_val, best_node = 0;
6913 min_val = INT_MAX;
6915 for (i = 0; i < nr_node_ids; i++) {
6916 /* Start at @node */
6917 n = (node + i) % nr_node_ids;
6919 if (!nr_cpus_node(n))
6920 continue;
6922 /* Skip already used nodes */
6923 if (node_isset(n, *used_nodes))
6924 continue;
6926 /* Simple min distance search */
6927 val = node_distance(node, n);
6929 if (val < min_val) {
6930 min_val = val;
6931 best_node = n;
6935 node_set(best_node, *used_nodes);
6936 return best_node;
6940 * sched_domain_node_span - get a cpumask for a node's sched_domain
6941 * @node: node whose cpumask we're constructing
6942 * @span: resulting cpumask
6944 * Given a node, construct a good cpumask for its sched_domain to span. It
6945 * should be one that prevents unnecessary balancing, but also spreads tasks
6946 * out optimally.
6948 static void sched_domain_node_span(int node, cpumask_t *span)
6950 nodemask_t used_nodes;
6951 node_to_cpumask_ptr(nodemask, node);
6952 int i;
6954 cpus_clear(*span);
6955 nodes_clear(used_nodes);
6957 cpus_or(*span, *span, *nodemask);
6958 node_set(node, used_nodes);
6960 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6961 int next_node = find_next_best_node(node, &used_nodes);
6963 node_to_cpumask_ptr_next(nodemask, next_node);
6964 cpus_or(*span, *span, *nodemask);
6967 #endif /* CONFIG_NUMA */
6969 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6972 * SMT sched-domains:
6974 #ifdef CONFIG_SCHED_SMT
6975 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6976 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6978 static int
6979 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6980 cpumask_t *unused)
6982 if (sg)
6983 *sg = &per_cpu(sched_group_cpus, cpu);
6984 return cpu;
6986 #endif /* CONFIG_SCHED_SMT */
6989 * multi-core sched-domains:
6991 #ifdef CONFIG_SCHED_MC
6992 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6993 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6994 #endif /* CONFIG_SCHED_MC */
6996 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6997 static int
6998 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6999 cpumask_t *mask)
7001 int group;
7003 *mask = per_cpu(cpu_sibling_map, cpu);
7004 cpus_and(*mask, *mask, *cpu_map);
7005 group = first_cpu(*mask);
7006 if (sg)
7007 *sg = &per_cpu(sched_group_core, group);
7008 return group;
7010 #elif defined(CONFIG_SCHED_MC)
7011 static int
7012 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7013 cpumask_t *unused)
7015 if (sg)
7016 *sg = &per_cpu(sched_group_core, cpu);
7017 return cpu;
7019 #endif
7021 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7022 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7024 static int
7025 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7026 cpumask_t *mask)
7028 int group;
7029 #ifdef CONFIG_SCHED_MC
7030 *mask = cpu_coregroup_map(cpu);
7031 cpus_and(*mask, *mask, *cpu_map);
7032 group = first_cpu(*mask);
7033 #elif defined(CONFIG_SCHED_SMT)
7034 *mask = per_cpu(cpu_sibling_map, cpu);
7035 cpus_and(*mask, *mask, *cpu_map);
7036 group = first_cpu(*mask);
7037 #else
7038 group = cpu;
7039 #endif
7040 if (sg)
7041 *sg = &per_cpu(sched_group_phys, group);
7042 return group;
7045 #ifdef CONFIG_NUMA
7047 * The init_sched_build_groups can't handle what we want to do with node
7048 * groups, so roll our own. Now each node has its own list of groups which
7049 * gets dynamically allocated.
7051 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7052 static struct sched_group ***sched_group_nodes_bycpu;
7054 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7055 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7057 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7058 struct sched_group **sg, cpumask_t *nodemask)
7060 int group;
7062 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7063 cpus_and(*nodemask, *nodemask, *cpu_map);
7064 group = first_cpu(*nodemask);
7066 if (sg)
7067 *sg = &per_cpu(sched_group_allnodes, group);
7068 return group;
7071 static void init_numa_sched_groups_power(struct sched_group *group_head)
7073 struct sched_group *sg = group_head;
7074 int j;
7076 if (!sg)
7077 return;
7078 do {
7079 for_each_cpu_mask_nr(j, sg->cpumask) {
7080 struct sched_domain *sd;
7082 sd = &per_cpu(phys_domains, j);
7083 if (j != first_cpu(sd->groups->cpumask)) {
7085 * Only add "power" once for each
7086 * physical package.
7088 continue;
7091 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7093 sg = sg->next;
7094 } while (sg != group_head);
7096 #endif /* CONFIG_NUMA */
7098 #ifdef CONFIG_NUMA
7099 /* Free memory allocated for various sched_group structures */
7100 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7102 int cpu, i;
7104 for_each_cpu_mask_nr(cpu, *cpu_map) {
7105 struct sched_group **sched_group_nodes
7106 = sched_group_nodes_bycpu[cpu];
7108 if (!sched_group_nodes)
7109 continue;
7111 for (i = 0; i < nr_node_ids; i++) {
7112 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7114 *nodemask = node_to_cpumask(i);
7115 cpus_and(*nodemask, *nodemask, *cpu_map);
7116 if (cpus_empty(*nodemask))
7117 continue;
7119 if (sg == NULL)
7120 continue;
7121 sg = sg->next;
7122 next_sg:
7123 oldsg = sg;
7124 sg = sg->next;
7125 kfree(oldsg);
7126 if (oldsg != sched_group_nodes[i])
7127 goto next_sg;
7129 kfree(sched_group_nodes);
7130 sched_group_nodes_bycpu[cpu] = NULL;
7133 #else /* !CONFIG_NUMA */
7134 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7137 #endif /* CONFIG_NUMA */
7140 * Initialize sched groups cpu_power.
7142 * cpu_power indicates the capacity of sched group, which is used while
7143 * distributing the load between different sched groups in a sched domain.
7144 * Typically cpu_power for all the groups in a sched domain will be same unless
7145 * there are asymmetries in the topology. If there are asymmetries, group
7146 * having more cpu_power will pickup more load compared to the group having
7147 * less cpu_power.
7149 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7150 * the maximum number of tasks a group can handle in the presence of other idle
7151 * or lightly loaded groups in the same sched domain.
7153 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7155 struct sched_domain *child;
7156 struct sched_group *group;
7158 WARN_ON(!sd || !sd->groups);
7160 if (cpu != first_cpu(sd->groups->cpumask))
7161 return;
7163 child = sd->child;
7165 sd->groups->__cpu_power = 0;
7168 * For perf policy, if the groups in child domain share resources
7169 * (for example cores sharing some portions of the cache hierarchy
7170 * or SMT), then set this domain groups cpu_power such that each group
7171 * can handle only one task, when there are other idle groups in the
7172 * same sched domain.
7174 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7175 (child->flags &
7176 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7177 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7178 return;
7182 * add cpu_power of each child group to this groups cpu_power
7184 group = child->groups;
7185 do {
7186 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7187 group = group->next;
7188 } while (group != child->groups);
7192 * Initializers for schedule domains
7193 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7196 #define SD_INIT(sd, type) sd_init_##type(sd)
7197 #define SD_INIT_FUNC(type) \
7198 static noinline void sd_init_##type(struct sched_domain *sd) \
7200 memset(sd, 0, sizeof(*sd)); \
7201 *sd = SD_##type##_INIT; \
7202 sd->level = SD_LV_##type; \
7205 SD_INIT_FUNC(CPU)
7206 #ifdef CONFIG_NUMA
7207 SD_INIT_FUNC(ALLNODES)
7208 SD_INIT_FUNC(NODE)
7209 #endif
7210 #ifdef CONFIG_SCHED_SMT
7211 SD_INIT_FUNC(SIBLING)
7212 #endif
7213 #ifdef CONFIG_SCHED_MC
7214 SD_INIT_FUNC(MC)
7215 #endif
7218 * To minimize stack usage kmalloc room for cpumasks and share the
7219 * space as the usage in build_sched_domains() dictates. Used only
7220 * if the amount of space is significant.
7222 struct allmasks {
7223 cpumask_t tmpmask; /* make this one first */
7224 union {
7225 cpumask_t nodemask;
7226 cpumask_t this_sibling_map;
7227 cpumask_t this_core_map;
7229 cpumask_t send_covered;
7231 #ifdef CONFIG_NUMA
7232 cpumask_t domainspan;
7233 cpumask_t covered;
7234 cpumask_t notcovered;
7235 #endif
7238 #if NR_CPUS > 128
7239 #define SCHED_CPUMASK_ALLOC 1
7240 #define SCHED_CPUMASK_FREE(v) kfree(v)
7241 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7242 #else
7243 #define SCHED_CPUMASK_ALLOC 0
7244 #define SCHED_CPUMASK_FREE(v)
7245 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7246 #endif
7248 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7249 ((unsigned long)(a) + offsetof(struct allmasks, v))
7251 static int default_relax_domain_level = -1;
7253 static int __init setup_relax_domain_level(char *str)
7255 unsigned long val;
7257 val = simple_strtoul(str, NULL, 0);
7258 if (val < SD_LV_MAX)
7259 default_relax_domain_level = val;
7261 return 1;
7263 __setup("relax_domain_level=", setup_relax_domain_level);
7265 static void set_domain_attribute(struct sched_domain *sd,
7266 struct sched_domain_attr *attr)
7268 int request;
7270 if (!attr || attr->relax_domain_level < 0) {
7271 if (default_relax_domain_level < 0)
7272 return;
7273 else
7274 request = default_relax_domain_level;
7275 } else
7276 request = attr->relax_domain_level;
7277 if (request < sd->level) {
7278 /* turn off idle balance on this domain */
7279 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7280 } else {
7281 /* turn on idle balance on this domain */
7282 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7287 * Build sched domains for a given set of cpus and attach the sched domains
7288 * to the individual cpus
7290 static int __build_sched_domains(const cpumask_t *cpu_map,
7291 struct sched_domain_attr *attr)
7293 int i;
7294 struct root_domain *rd;
7295 SCHED_CPUMASK_DECLARE(allmasks);
7296 cpumask_t *tmpmask;
7297 #ifdef CONFIG_NUMA
7298 struct sched_group **sched_group_nodes = NULL;
7299 int sd_allnodes = 0;
7302 * Allocate the per-node list of sched groups
7304 sched_group_nodes = kcalloc(nr_node_ids, sizeof(struct sched_group *),
7305 GFP_KERNEL);
7306 if (!sched_group_nodes) {
7307 printk(KERN_WARNING "Can not alloc sched group node list\n");
7308 return -ENOMEM;
7310 #endif
7312 rd = alloc_rootdomain();
7313 if (!rd) {
7314 printk(KERN_WARNING "Cannot alloc root domain\n");
7315 #ifdef CONFIG_NUMA
7316 kfree(sched_group_nodes);
7317 #endif
7318 return -ENOMEM;
7321 #if SCHED_CPUMASK_ALLOC
7322 /* get space for all scratch cpumask variables */
7323 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7324 if (!allmasks) {
7325 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7326 kfree(rd);
7327 #ifdef CONFIG_NUMA
7328 kfree(sched_group_nodes);
7329 #endif
7330 return -ENOMEM;
7332 #endif
7333 tmpmask = (cpumask_t *)allmasks;
7336 #ifdef CONFIG_NUMA
7337 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7338 #endif
7341 * Set up domains for cpus specified by the cpu_map.
7343 for_each_cpu_mask_nr(i, *cpu_map) {
7344 struct sched_domain *sd = NULL, *p;
7345 SCHED_CPUMASK_VAR(nodemask, allmasks);
7347 *nodemask = node_to_cpumask(cpu_to_node(i));
7348 cpus_and(*nodemask, *nodemask, *cpu_map);
7350 #ifdef CONFIG_NUMA
7351 if (cpus_weight(*cpu_map) >
7352 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7353 sd = &per_cpu(allnodes_domains, i);
7354 SD_INIT(sd, ALLNODES);
7355 set_domain_attribute(sd, attr);
7356 sd->span = *cpu_map;
7357 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7358 p = sd;
7359 sd_allnodes = 1;
7360 } else
7361 p = NULL;
7363 sd = &per_cpu(node_domains, i);
7364 SD_INIT(sd, NODE);
7365 set_domain_attribute(sd, attr);
7366 sched_domain_node_span(cpu_to_node(i), &sd->span);
7367 sd->parent = p;
7368 if (p)
7369 p->child = sd;
7370 cpus_and(sd->span, sd->span, *cpu_map);
7371 #endif
7373 p = sd;
7374 sd = &per_cpu(phys_domains, i);
7375 SD_INIT(sd, CPU);
7376 set_domain_attribute(sd, attr);
7377 sd->span = *nodemask;
7378 sd->parent = p;
7379 if (p)
7380 p->child = sd;
7381 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7383 #ifdef CONFIG_SCHED_MC
7384 p = sd;
7385 sd = &per_cpu(core_domains, i);
7386 SD_INIT(sd, MC);
7387 set_domain_attribute(sd, attr);
7388 sd->span = cpu_coregroup_map(i);
7389 cpus_and(sd->span, sd->span, *cpu_map);
7390 sd->parent = p;
7391 p->child = sd;
7392 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7393 #endif
7395 #ifdef CONFIG_SCHED_SMT
7396 p = sd;
7397 sd = &per_cpu(cpu_domains, i);
7398 SD_INIT(sd, SIBLING);
7399 set_domain_attribute(sd, attr);
7400 sd->span = per_cpu(cpu_sibling_map, i);
7401 cpus_and(sd->span, sd->span, *cpu_map);
7402 sd->parent = p;
7403 p->child = sd;
7404 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7405 #endif
7408 #ifdef CONFIG_SCHED_SMT
7409 /* Set up CPU (sibling) groups */
7410 for_each_cpu_mask_nr(i, *cpu_map) {
7411 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7412 SCHED_CPUMASK_VAR(send_covered, allmasks);
7414 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7415 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7416 if (i != first_cpu(*this_sibling_map))
7417 continue;
7419 init_sched_build_groups(this_sibling_map, cpu_map,
7420 &cpu_to_cpu_group,
7421 send_covered, tmpmask);
7423 #endif
7425 #ifdef CONFIG_SCHED_MC
7426 /* Set up multi-core groups */
7427 for_each_cpu_mask_nr(i, *cpu_map) {
7428 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7429 SCHED_CPUMASK_VAR(send_covered, allmasks);
7431 *this_core_map = cpu_coregroup_map(i);
7432 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7433 if (i != first_cpu(*this_core_map))
7434 continue;
7436 init_sched_build_groups(this_core_map, cpu_map,
7437 &cpu_to_core_group,
7438 send_covered, tmpmask);
7440 #endif
7442 /* Set up physical groups */
7443 for (i = 0; i < nr_node_ids; i++) {
7444 SCHED_CPUMASK_VAR(nodemask, allmasks);
7445 SCHED_CPUMASK_VAR(send_covered, allmasks);
7447 *nodemask = node_to_cpumask(i);
7448 cpus_and(*nodemask, *nodemask, *cpu_map);
7449 if (cpus_empty(*nodemask))
7450 continue;
7452 init_sched_build_groups(nodemask, cpu_map,
7453 &cpu_to_phys_group,
7454 send_covered, tmpmask);
7457 #ifdef CONFIG_NUMA
7458 /* Set up node groups */
7459 if (sd_allnodes) {
7460 SCHED_CPUMASK_VAR(send_covered, allmasks);
7462 init_sched_build_groups(cpu_map, cpu_map,
7463 &cpu_to_allnodes_group,
7464 send_covered, tmpmask);
7467 for (i = 0; i < nr_node_ids; i++) {
7468 /* Set up node groups */
7469 struct sched_group *sg, *prev;
7470 SCHED_CPUMASK_VAR(nodemask, allmasks);
7471 SCHED_CPUMASK_VAR(domainspan, allmasks);
7472 SCHED_CPUMASK_VAR(covered, allmasks);
7473 int j;
7475 *nodemask = node_to_cpumask(i);
7476 cpus_clear(*covered);
7478 cpus_and(*nodemask, *nodemask, *cpu_map);
7479 if (cpus_empty(*nodemask)) {
7480 sched_group_nodes[i] = NULL;
7481 continue;
7484 sched_domain_node_span(i, domainspan);
7485 cpus_and(*domainspan, *domainspan, *cpu_map);
7487 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7488 if (!sg) {
7489 printk(KERN_WARNING "Can not alloc domain group for "
7490 "node %d\n", i);
7491 goto error;
7493 sched_group_nodes[i] = sg;
7494 for_each_cpu_mask_nr(j, *nodemask) {
7495 struct sched_domain *sd;
7497 sd = &per_cpu(node_domains, j);
7498 sd->groups = sg;
7500 sg->__cpu_power = 0;
7501 sg->cpumask = *nodemask;
7502 sg->next = sg;
7503 cpus_or(*covered, *covered, *nodemask);
7504 prev = sg;
7506 for (j = 0; j < nr_node_ids; j++) {
7507 SCHED_CPUMASK_VAR(notcovered, allmasks);
7508 int n = (i + j) % nr_node_ids;
7509 node_to_cpumask_ptr(pnodemask, n);
7511 cpus_complement(*notcovered, *covered);
7512 cpus_and(*tmpmask, *notcovered, *cpu_map);
7513 cpus_and(*tmpmask, *tmpmask, *domainspan);
7514 if (cpus_empty(*tmpmask))
7515 break;
7517 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7518 if (cpus_empty(*tmpmask))
7519 continue;
7521 sg = kmalloc_node(sizeof(struct sched_group),
7522 GFP_KERNEL, i);
7523 if (!sg) {
7524 printk(KERN_WARNING
7525 "Can not alloc domain group for node %d\n", j);
7526 goto error;
7528 sg->__cpu_power = 0;
7529 sg->cpumask = *tmpmask;
7530 sg->next = prev->next;
7531 cpus_or(*covered, *covered, *tmpmask);
7532 prev->next = sg;
7533 prev = sg;
7536 #endif
7538 /* Calculate CPU power for physical packages and nodes */
7539 #ifdef CONFIG_SCHED_SMT
7540 for_each_cpu_mask_nr(i, *cpu_map) {
7541 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7543 init_sched_groups_power(i, sd);
7545 #endif
7546 #ifdef CONFIG_SCHED_MC
7547 for_each_cpu_mask_nr(i, *cpu_map) {
7548 struct sched_domain *sd = &per_cpu(core_domains, i);
7550 init_sched_groups_power(i, sd);
7552 #endif
7554 for_each_cpu_mask_nr(i, *cpu_map) {
7555 struct sched_domain *sd = &per_cpu(phys_domains, i);
7557 init_sched_groups_power(i, sd);
7560 #ifdef CONFIG_NUMA
7561 for (i = 0; i < nr_node_ids; i++)
7562 init_numa_sched_groups_power(sched_group_nodes[i]);
7564 if (sd_allnodes) {
7565 struct sched_group *sg;
7567 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7568 tmpmask);
7569 init_numa_sched_groups_power(sg);
7571 #endif
7573 /* Attach the domains */
7574 for_each_cpu_mask_nr(i, *cpu_map) {
7575 struct sched_domain *sd;
7576 #ifdef CONFIG_SCHED_SMT
7577 sd = &per_cpu(cpu_domains, i);
7578 #elif defined(CONFIG_SCHED_MC)
7579 sd = &per_cpu(core_domains, i);
7580 #else
7581 sd = &per_cpu(phys_domains, i);
7582 #endif
7583 cpu_attach_domain(sd, rd, i);
7586 SCHED_CPUMASK_FREE((void *)allmasks);
7587 return 0;
7589 #ifdef CONFIG_NUMA
7590 error:
7591 free_sched_groups(cpu_map, tmpmask);
7592 SCHED_CPUMASK_FREE((void *)allmasks);
7593 return -ENOMEM;
7594 #endif
7597 static int build_sched_domains(const cpumask_t *cpu_map)
7599 return __build_sched_domains(cpu_map, NULL);
7602 static cpumask_t *doms_cur; /* current sched domains */
7603 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7604 static struct sched_domain_attr *dattr_cur;
7605 /* attribues of custom domains in 'doms_cur' */
7608 * Special case: If a kmalloc of a doms_cur partition (array of
7609 * cpumask_t) fails, then fallback to a single sched domain,
7610 * as determined by the single cpumask_t fallback_doms.
7612 static cpumask_t fallback_doms;
7614 void __attribute__((weak)) arch_update_cpu_topology(void)
7619 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7620 * For now this just excludes isolated cpus, but could be used to
7621 * exclude other special cases in the future.
7623 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7625 int err;
7627 arch_update_cpu_topology();
7628 ndoms_cur = 1;
7629 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7630 if (!doms_cur)
7631 doms_cur = &fallback_doms;
7632 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7633 dattr_cur = NULL;
7634 err = build_sched_domains(doms_cur);
7635 register_sched_domain_sysctl();
7637 return err;
7640 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7641 cpumask_t *tmpmask)
7643 free_sched_groups(cpu_map, tmpmask);
7647 * Detach sched domains from a group of cpus specified in cpu_map
7648 * These cpus will now be attached to the NULL domain
7650 static void detach_destroy_domains(const cpumask_t *cpu_map)
7652 cpumask_t tmpmask;
7653 int i;
7655 unregister_sched_domain_sysctl();
7657 for_each_cpu_mask_nr(i, *cpu_map)
7658 cpu_attach_domain(NULL, &def_root_domain, i);
7659 synchronize_sched();
7660 arch_destroy_sched_domains(cpu_map, &tmpmask);
7663 /* handle null as "default" */
7664 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7665 struct sched_domain_attr *new, int idx_new)
7667 struct sched_domain_attr tmp;
7669 /* fast path */
7670 if (!new && !cur)
7671 return 1;
7673 tmp = SD_ATTR_INIT;
7674 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7675 new ? (new + idx_new) : &tmp,
7676 sizeof(struct sched_domain_attr));
7680 * Partition sched domains as specified by the 'ndoms_new'
7681 * cpumasks in the array doms_new[] of cpumasks. This compares
7682 * doms_new[] to the current sched domain partitioning, doms_cur[].
7683 * It destroys each deleted domain and builds each new domain.
7685 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7686 * The masks don't intersect (don't overlap.) We should setup one
7687 * sched domain for each mask. CPUs not in any of the cpumasks will
7688 * not be load balanced. If the same cpumask appears both in the
7689 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7690 * it as it is.
7692 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7693 * ownership of it and will kfree it when done with it. If the caller
7694 * failed the kmalloc call, then it can pass in doms_new == NULL,
7695 * and partition_sched_domains() will fallback to the single partition
7696 * 'fallback_doms', it also forces the domains to be rebuilt.
7698 * Call with hotplug lock held
7700 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7701 struct sched_domain_attr *dattr_new)
7703 int i, j;
7705 mutex_lock(&sched_domains_mutex);
7707 /* always unregister in case we don't destroy any domains */
7708 unregister_sched_domain_sysctl();
7710 if (doms_new == NULL)
7711 ndoms_new = 0;
7713 /* Destroy deleted domains */
7714 for (i = 0; i < ndoms_cur; i++) {
7715 for (j = 0; j < ndoms_new; j++) {
7716 if (cpus_equal(doms_cur[i], doms_new[j])
7717 && dattrs_equal(dattr_cur, i, dattr_new, j))
7718 goto match1;
7720 /* no match - a current sched domain not in new doms_new[] */
7721 detach_destroy_domains(doms_cur + i);
7722 match1:
7726 if (doms_new == NULL) {
7727 ndoms_cur = 0;
7728 ndoms_new = 1;
7729 doms_new = &fallback_doms;
7730 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7731 dattr_new = NULL;
7734 /* Build new domains */
7735 for (i = 0; i < ndoms_new; i++) {
7736 for (j = 0; j < ndoms_cur; j++) {
7737 if (cpus_equal(doms_new[i], doms_cur[j])
7738 && dattrs_equal(dattr_new, i, dattr_cur, j))
7739 goto match2;
7741 /* no match - add a new doms_new */
7742 __build_sched_domains(doms_new + i,
7743 dattr_new ? dattr_new + i : NULL);
7744 match2:
7748 /* Remember the new sched domains */
7749 if (doms_cur != &fallback_doms)
7750 kfree(doms_cur);
7751 kfree(dattr_cur); /* kfree(NULL) is safe */
7752 doms_cur = doms_new;
7753 dattr_cur = dattr_new;
7754 ndoms_cur = ndoms_new;
7756 register_sched_domain_sysctl();
7758 mutex_unlock(&sched_domains_mutex);
7761 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7762 int arch_reinit_sched_domains(void)
7764 get_online_cpus();
7765 rebuild_sched_domains();
7766 put_online_cpus();
7767 return 0;
7770 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7772 int ret;
7774 if (buf[0] != '0' && buf[0] != '1')
7775 return -EINVAL;
7777 if (smt)
7778 sched_smt_power_savings = (buf[0] == '1');
7779 else
7780 sched_mc_power_savings = (buf[0] == '1');
7782 ret = arch_reinit_sched_domains();
7784 return ret ? ret : count;
7787 #ifdef CONFIG_SCHED_MC
7788 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7789 char *page)
7791 return sprintf(page, "%u\n", sched_mc_power_savings);
7793 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7794 const char *buf, size_t count)
7796 return sched_power_savings_store(buf, count, 0);
7798 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7799 sched_mc_power_savings_show,
7800 sched_mc_power_savings_store);
7801 #endif
7803 #ifdef CONFIG_SCHED_SMT
7804 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7805 char *page)
7807 return sprintf(page, "%u\n", sched_smt_power_savings);
7809 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7810 const char *buf, size_t count)
7812 return sched_power_savings_store(buf, count, 1);
7814 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7815 sched_smt_power_savings_show,
7816 sched_smt_power_savings_store);
7817 #endif
7819 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7821 int err = 0;
7823 #ifdef CONFIG_SCHED_SMT
7824 if (smt_capable())
7825 err = sysfs_create_file(&cls->kset.kobj,
7826 &attr_sched_smt_power_savings.attr);
7827 #endif
7828 #ifdef CONFIG_SCHED_MC
7829 if (!err && mc_capable())
7830 err = sysfs_create_file(&cls->kset.kobj,
7831 &attr_sched_mc_power_savings.attr);
7832 #endif
7833 return err;
7835 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7837 #ifndef CONFIG_CPUSETS
7839 * Add online and remove offline CPUs from the scheduler domains.
7840 * When cpusets are enabled they take over this function.
7842 static int update_sched_domains(struct notifier_block *nfb,
7843 unsigned long action, void *hcpu)
7845 switch (action) {
7846 case CPU_ONLINE:
7847 case CPU_ONLINE_FROZEN:
7848 case CPU_DEAD:
7849 case CPU_DEAD_FROZEN:
7850 partition_sched_domains(0, NULL, NULL);
7851 return NOTIFY_OK;
7853 default:
7854 return NOTIFY_DONE;
7857 #endif
7859 static int update_runtime(struct notifier_block *nfb,
7860 unsigned long action, void *hcpu)
7862 int cpu = (int)(long)hcpu;
7864 switch (action) {
7865 case CPU_DOWN_PREPARE:
7866 case CPU_DOWN_PREPARE_FROZEN:
7867 disable_runtime(cpu_rq(cpu));
7868 return NOTIFY_OK;
7870 case CPU_DOWN_FAILED:
7871 case CPU_DOWN_FAILED_FROZEN:
7872 case CPU_ONLINE:
7873 case CPU_ONLINE_FROZEN:
7874 enable_runtime(cpu_rq(cpu));
7875 return NOTIFY_OK;
7877 default:
7878 return NOTIFY_DONE;
7882 void __init sched_init_smp(void)
7884 cpumask_t non_isolated_cpus;
7886 #if defined(CONFIG_NUMA)
7887 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7888 GFP_KERNEL);
7889 BUG_ON(sched_group_nodes_bycpu == NULL);
7890 #endif
7891 get_online_cpus();
7892 mutex_lock(&sched_domains_mutex);
7893 arch_init_sched_domains(&cpu_online_map);
7894 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7895 if (cpus_empty(non_isolated_cpus))
7896 cpu_set(smp_processor_id(), non_isolated_cpus);
7897 mutex_unlock(&sched_domains_mutex);
7898 put_online_cpus();
7900 #ifndef CONFIG_CPUSETS
7901 /* XXX: Theoretical race here - CPU may be hotplugged now */
7902 hotcpu_notifier(update_sched_domains, 0);
7903 #endif
7905 /* RT runtime code needs to handle some hotplug events */
7906 hotcpu_notifier(update_runtime, 0);
7908 init_hrtick();
7910 /* Move init over to a non-isolated CPU */
7911 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
7912 BUG();
7913 sched_init_granularity();
7915 #else
7916 void __init sched_init_smp(void)
7918 sched_init_granularity();
7920 #endif /* CONFIG_SMP */
7922 int in_sched_functions(unsigned long addr)
7924 return in_lock_functions(addr) ||
7925 (addr >= (unsigned long)__sched_text_start
7926 && addr < (unsigned long)__sched_text_end);
7929 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7931 cfs_rq->tasks_timeline = RB_ROOT;
7932 INIT_LIST_HEAD(&cfs_rq->tasks);
7933 #ifdef CONFIG_FAIR_GROUP_SCHED
7934 cfs_rq->rq = rq;
7935 #endif
7936 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7939 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7941 struct rt_prio_array *array;
7942 int i;
7944 array = &rt_rq->active;
7945 for (i = 0; i < MAX_RT_PRIO; i++) {
7946 INIT_LIST_HEAD(array->queue + i);
7947 __clear_bit(i, array->bitmap);
7949 /* delimiter for bitsearch: */
7950 __set_bit(MAX_RT_PRIO, array->bitmap);
7952 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7953 rt_rq->highest_prio = MAX_RT_PRIO;
7954 #endif
7955 #ifdef CONFIG_SMP
7956 rt_rq->rt_nr_migratory = 0;
7957 rt_rq->overloaded = 0;
7958 #endif
7960 rt_rq->rt_time = 0;
7961 rt_rq->rt_throttled = 0;
7962 rt_rq->rt_runtime = 0;
7963 spin_lock_init(&rt_rq->rt_runtime_lock);
7965 #ifdef CONFIG_RT_GROUP_SCHED
7966 rt_rq->rt_nr_boosted = 0;
7967 rt_rq->rq = rq;
7968 #endif
7971 #ifdef CONFIG_FAIR_GROUP_SCHED
7972 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7973 struct sched_entity *se, int cpu, int add,
7974 struct sched_entity *parent)
7976 struct rq *rq = cpu_rq(cpu);
7977 tg->cfs_rq[cpu] = cfs_rq;
7978 init_cfs_rq(cfs_rq, rq);
7979 cfs_rq->tg = tg;
7980 if (add)
7981 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7983 tg->se[cpu] = se;
7984 /* se could be NULL for init_task_group */
7985 if (!se)
7986 return;
7988 if (!parent)
7989 se->cfs_rq = &rq->cfs;
7990 else
7991 se->cfs_rq = parent->my_q;
7993 se->my_q = cfs_rq;
7994 se->load.weight = tg->shares;
7995 se->load.inv_weight = 0;
7996 se->parent = parent;
7998 #endif
8000 #ifdef CONFIG_RT_GROUP_SCHED
8001 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8002 struct sched_rt_entity *rt_se, int cpu, int add,
8003 struct sched_rt_entity *parent)
8005 struct rq *rq = cpu_rq(cpu);
8007 tg->rt_rq[cpu] = rt_rq;
8008 init_rt_rq(rt_rq, rq);
8009 rt_rq->tg = tg;
8010 rt_rq->rt_se = rt_se;
8011 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8012 if (add)
8013 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
8015 tg->rt_se[cpu] = rt_se;
8016 if (!rt_se)
8017 return;
8019 if (!parent)
8020 rt_se->rt_rq = &rq->rt;
8021 else
8022 rt_se->rt_rq = parent->my_q;
8024 rt_se->my_q = rt_rq;
8025 rt_se->parent = parent;
8026 INIT_LIST_HEAD(&rt_se->run_list);
8028 #endif
8030 void __init sched_init(void)
8032 int i, j;
8033 unsigned long alloc_size = 0, ptr;
8035 #ifdef CONFIG_FAIR_GROUP_SCHED
8036 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8037 #endif
8038 #ifdef CONFIG_RT_GROUP_SCHED
8039 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8040 #endif
8041 #ifdef CONFIG_USER_SCHED
8042 alloc_size *= 2;
8043 #endif
8045 * As sched_init() is called before page_alloc is setup,
8046 * we use alloc_bootmem().
8048 if (alloc_size) {
8049 ptr = (unsigned long)alloc_bootmem(alloc_size);
8051 #ifdef CONFIG_FAIR_GROUP_SCHED
8052 init_task_group.se = (struct sched_entity **)ptr;
8053 ptr += nr_cpu_ids * sizeof(void **);
8055 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8056 ptr += nr_cpu_ids * sizeof(void **);
8058 #ifdef CONFIG_USER_SCHED
8059 root_task_group.se = (struct sched_entity **)ptr;
8060 ptr += nr_cpu_ids * sizeof(void **);
8062 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8063 ptr += nr_cpu_ids * sizeof(void **);
8064 #endif /* CONFIG_USER_SCHED */
8065 #endif /* CONFIG_FAIR_GROUP_SCHED */
8066 #ifdef CONFIG_RT_GROUP_SCHED
8067 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8068 ptr += nr_cpu_ids * sizeof(void **);
8070 init_task_group.rt_rq = (struct rt_rq **)ptr;
8071 ptr += nr_cpu_ids * sizeof(void **);
8073 #ifdef CONFIG_USER_SCHED
8074 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8075 ptr += nr_cpu_ids * sizeof(void **);
8077 root_task_group.rt_rq = (struct rt_rq **)ptr;
8078 ptr += nr_cpu_ids * sizeof(void **);
8079 #endif /* CONFIG_USER_SCHED */
8080 #endif /* CONFIG_RT_GROUP_SCHED */
8083 #ifdef CONFIG_SMP
8084 init_defrootdomain();
8085 #endif
8087 init_rt_bandwidth(&def_rt_bandwidth,
8088 global_rt_period(), global_rt_runtime());
8090 #ifdef CONFIG_RT_GROUP_SCHED
8091 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8092 global_rt_period(), global_rt_runtime());
8093 #ifdef CONFIG_USER_SCHED
8094 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8095 global_rt_period(), RUNTIME_INF);
8096 #endif /* CONFIG_USER_SCHED */
8097 #endif /* CONFIG_RT_GROUP_SCHED */
8099 #ifdef CONFIG_GROUP_SCHED
8100 list_add(&init_task_group.list, &task_groups);
8101 INIT_LIST_HEAD(&init_task_group.children);
8103 #ifdef CONFIG_USER_SCHED
8104 INIT_LIST_HEAD(&root_task_group.children);
8105 init_task_group.parent = &root_task_group;
8106 list_add(&init_task_group.siblings, &root_task_group.children);
8107 #endif /* CONFIG_USER_SCHED */
8108 #endif /* CONFIG_GROUP_SCHED */
8110 for_each_possible_cpu(i) {
8111 struct rq *rq;
8113 rq = cpu_rq(i);
8114 spin_lock_init(&rq->lock);
8115 rq->nr_running = 0;
8116 init_cfs_rq(&rq->cfs, rq);
8117 init_rt_rq(&rq->rt, rq);
8118 #ifdef CONFIG_FAIR_GROUP_SCHED
8119 init_task_group.shares = init_task_group_load;
8120 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8121 #ifdef CONFIG_CGROUP_SCHED
8123 * How much cpu bandwidth does init_task_group get?
8125 * In case of task-groups formed thr' the cgroup filesystem, it
8126 * gets 100% of the cpu resources in the system. This overall
8127 * system cpu resource is divided among the tasks of
8128 * init_task_group and its child task-groups in a fair manner,
8129 * based on each entity's (task or task-group's) weight
8130 * (se->load.weight).
8132 * In other words, if init_task_group has 10 tasks of weight
8133 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8134 * then A0's share of the cpu resource is:
8136 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8138 * We achieve this by letting init_task_group's tasks sit
8139 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8141 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8142 #elif defined CONFIG_USER_SCHED
8143 root_task_group.shares = NICE_0_LOAD;
8144 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8146 * In case of task-groups formed thr' the user id of tasks,
8147 * init_task_group represents tasks belonging to root user.
8148 * Hence it forms a sibling of all subsequent groups formed.
8149 * In this case, init_task_group gets only a fraction of overall
8150 * system cpu resource, based on the weight assigned to root
8151 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8152 * by letting tasks of init_task_group sit in a separate cfs_rq
8153 * (init_cfs_rq) and having one entity represent this group of
8154 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8156 init_tg_cfs_entry(&init_task_group,
8157 &per_cpu(init_cfs_rq, i),
8158 &per_cpu(init_sched_entity, i), i, 1,
8159 root_task_group.se[i]);
8161 #endif
8162 #endif /* CONFIG_FAIR_GROUP_SCHED */
8164 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8165 #ifdef CONFIG_RT_GROUP_SCHED
8166 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8167 #ifdef CONFIG_CGROUP_SCHED
8168 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8169 #elif defined CONFIG_USER_SCHED
8170 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8171 init_tg_rt_entry(&init_task_group,
8172 &per_cpu(init_rt_rq, i),
8173 &per_cpu(init_sched_rt_entity, i), i, 1,
8174 root_task_group.rt_se[i]);
8175 #endif
8176 #endif
8178 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8179 rq->cpu_load[j] = 0;
8180 #ifdef CONFIG_SMP
8181 rq->sd = NULL;
8182 rq->rd = NULL;
8183 rq->active_balance = 0;
8184 rq->next_balance = jiffies;
8185 rq->push_cpu = 0;
8186 rq->cpu = i;
8187 rq->online = 0;
8188 rq->migration_thread = NULL;
8189 INIT_LIST_HEAD(&rq->migration_queue);
8190 rq_attach_root(rq, &def_root_domain);
8191 #endif
8192 init_rq_hrtick(rq);
8193 atomic_set(&rq->nr_iowait, 0);
8196 set_load_weight(&init_task);
8198 #ifdef CONFIG_PREEMPT_NOTIFIERS
8199 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8200 #endif
8202 #ifdef CONFIG_SMP
8203 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
8204 #endif
8206 #ifdef CONFIG_RT_MUTEXES
8207 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8208 #endif
8211 * The boot idle thread does lazy MMU switching as well:
8213 atomic_inc(&init_mm.mm_count);
8214 enter_lazy_tlb(&init_mm, current);
8217 * Make us the idle thread. Technically, schedule() should not be
8218 * called from this thread, however somewhere below it might be,
8219 * but because we are the idle thread, we just pick up running again
8220 * when this runqueue becomes "idle".
8222 init_idle(current, smp_processor_id());
8224 * During early bootup we pretend to be a normal task:
8226 current->sched_class = &fair_sched_class;
8228 scheduler_running = 1;
8231 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8232 void __might_sleep(char *file, int line)
8234 #ifdef in_atomic
8235 static unsigned long prev_jiffy; /* ratelimiting */
8237 if ((in_atomic() || irqs_disabled()) &&
8238 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8239 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8240 return;
8241 prev_jiffy = jiffies;
8242 printk(KERN_ERR "BUG: sleeping function called from invalid"
8243 " context at %s:%d\n", file, line);
8244 printk("in_atomic():%d, irqs_disabled():%d\n",
8245 in_atomic(), irqs_disabled());
8246 debug_show_held_locks(current);
8247 if (irqs_disabled())
8248 print_irqtrace_events(current);
8249 dump_stack();
8251 #endif
8253 EXPORT_SYMBOL(__might_sleep);
8254 #endif
8256 #ifdef CONFIG_MAGIC_SYSRQ
8257 static void normalize_task(struct rq *rq, struct task_struct *p)
8259 int on_rq;
8261 update_rq_clock(rq);
8262 on_rq = p->se.on_rq;
8263 if (on_rq)
8264 deactivate_task(rq, p, 0);
8265 __setscheduler(rq, p, SCHED_NORMAL, 0);
8266 if (on_rq) {
8267 activate_task(rq, p, 0);
8268 resched_task(rq->curr);
8272 void normalize_rt_tasks(void)
8274 struct task_struct *g, *p;
8275 unsigned long flags;
8276 struct rq *rq;
8278 read_lock_irqsave(&tasklist_lock, flags);
8279 do_each_thread(g, p) {
8281 * Only normalize user tasks:
8283 if (!p->mm)
8284 continue;
8286 p->se.exec_start = 0;
8287 #ifdef CONFIG_SCHEDSTATS
8288 p->se.wait_start = 0;
8289 p->se.sleep_start = 0;
8290 p->se.block_start = 0;
8291 #endif
8293 if (!rt_task(p)) {
8295 * Renice negative nice level userspace
8296 * tasks back to 0:
8298 if (TASK_NICE(p) < 0 && p->mm)
8299 set_user_nice(p, 0);
8300 continue;
8303 spin_lock(&p->pi_lock);
8304 rq = __task_rq_lock(p);
8306 normalize_task(rq, p);
8308 __task_rq_unlock(rq);
8309 spin_unlock(&p->pi_lock);
8310 } while_each_thread(g, p);
8312 read_unlock_irqrestore(&tasklist_lock, flags);
8315 #endif /* CONFIG_MAGIC_SYSRQ */
8317 #ifdef CONFIG_IA64
8319 * These functions are only useful for the IA64 MCA handling.
8321 * They can only be called when the whole system has been
8322 * stopped - every CPU needs to be quiescent, and no scheduling
8323 * activity can take place. Using them for anything else would
8324 * be a serious bug, and as a result, they aren't even visible
8325 * under any other configuration.
8329 * curr_task - return the current task for a given cpu.
8330 * @cpu: the processor in question.
8332 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8334 struct task_struct *curr_task(int cpu)
8336 return cpu_curr(cpu);
8340 * set_curr_task - set the current task for a given cpu.
8341 * @cpu: the processor in question.
8342 * @p: the task pointer to set.
8344 * Description: This function must only be used when non-maskable interrupts
8345 * are serviced on a separate stack. It allows the architecture to switch the
8346 * notion of the current task on a cpu in a non-blocking manner. This function
8347 * must be called with all CPU's synchronized, and interrupts disabled, the
8348 * and caller must save the original value of the current task (see
8349 * curr_task() above) and restore that value before reenabling interrupts and
8350 * re-starting the system.
8352 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8354 void set_curr_task(int cpu, struct task_struct *p)
8356 cpu_curr(cpu) = p;
8359 #endif
8361 #ifdef CONFIG_FAIR_GROUP_SCHED
8362 static void free_fair_sched_group(struct task_group *tg)
8364 int i;
8366 for_each_possible_cpu(i) {
8367 if (tg->cfs_rq)
8368 kfree(tg->cfs_rq[i]);
8369 if (tg->se)
8370 kfree(tg->se[i]);
8373 kfree(tg->cfs_rq);
8374 kfree(tg->se);
8377 static
8378 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8380 struct cfs_rq *cfs_rq;
8381 struct sched_entity *se, *parent_se;
8382 struct rq *rq;
8383 int i;
8385 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8386 if (!tg->cfs_rq)
8387 goto err;
8388 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8389 if (!tg->se)
8390 goto err;
8392 tg->shares = NICE_0_LOAD;
8394 for_each_possible_cpu(i) {
8395 rq = cpu_rq(i);
8397 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8398 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8399 if (!cfs_rq)
8400 goto err;
8402 se = kmalloc_node(sizeof(struct sched_entity),
8403 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8404 if (!se)
8405 goto err;
8407 parent_se = parent ? parent->se[i] : NULL;
8408 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8411 return 1;
8413 err:
8414 return 0;
8417 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8419 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8420 &cpu_rq(cpu)->leaf_cfs_rq_list);
8423 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8425 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8427 #else /* !CONFG_FAIR_GROUP_SCHED */
8428 static inline void free_fair_sched_group(struct task_group *tg)
8432 static inline
8433 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8435 return 1;
8438 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8442 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8445 #endif /* CONFIG_FAIR_GROUP_SCHED */
8447 #ifdef CONFIG_RT_GROUP_SCHED
8448 static void free_rt_sched_group(struct task_group *tg)
8450 int i;
8452 destroy_rt_bandwidth(&tg->rt_bandwidth);
8454 for_each_possible_cpu(i) {
8455 if (tg->rt_rq)
8456 kfree(tg->rt_rq[i]);
8457 if (tg->rt_se)
8458 kfree(tg->rt_se[i]);
8461 kfree(tg->rt_rq);
8462 kfree(tg->rt_se);
8465 static
8466 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8468 struct rt_rq *rt_rq;
8469 struct sched_rt_entity *rt_se, *parent_se;
8470 struct rq *rq;
8471 int i;
8473 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8474 if (!tg->rt_rq)
8475 goto err;
8476 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8477 if (!tg->rt_se)
8478 goto err;
8480 init_rt_bandwidth(&tg->rt_bandwidth,
8481 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8483 for_each_possible_cpu(i) {
8484 rq = cpu_rq(i);
8486 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8487 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8488 if (!rt_rq)
8489 goto err;
8491 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8492 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8493 if (!rt_se)
8494 goto err;
8496 parent_se = parent ? parent->rt_se[i] : NULL;
8497 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8500 return 1;
8502 err:
8503 return 0;
8506 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8508 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8509 &cpu_rq(cpu)->leaf_rt_rq_list);
8512 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8514 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8516 #else /* !CONFIG_RT_GROUP_SCHED */
8517 static inline void free_rt_sched_group(struct task_group *tg)
8521 static inline
8522 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8524 return 1;
8527 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8531 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8534 #endif /* CONFIG_RT_GROUP_SCHED */
8536 #ifdef CONFIG_GROUP_SCHED
8537 static void free_sched_group(struct task_group *tg)
8539 free_fair_sched_group(tg);
8540 free_rt_sched_group(tg);
8541 kfree(tg);
8544 /* allocate runqueue etc for a new task group */
8545 struct task_group *sched_create_group(struct task_group *parent)
8547 struct task_group *tg;
8548 unsigned long flags;
8549 int i;
8551 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8552 if (!tg)
8553 return ERR_PTR(-ENOMEM);
8555 if (!alloc_fair_sched_group(tg, parent))
8556 goto err;
8558 if (!alloc_rt_sched_group(tg, parent))
8559 goto err;
8561 spin_lock_irqsave(&task_group_lock, flags);
8562 for_each_possible_cpu(i) {
8563 register_fair_sched_group(tg, i);
8564 register_rt_sched_group(tg, i);
8566 list_add_rcu(&tg->list, &task_groups);
8568 WARN_ON(!parent); /* root should already exist */
8570 tg->parent = parent;
8571 INIT_LIST_HEAD(&tg->children);
8572 list_add_rcu(&tg->siblings, &parent->children);
8573 spin_unlock_irqrestore(&task_group_lock, flags);
8575 return tg;
8577 err:
8578 free_sched_group(tg);
8579 return ERR_PTR(-ENOMEM);
8582 /* rcu callback to free various structures associated with a task group */
8583 static void free_sched_group_rcu(struct rcu_head *rhp)
8585 /* now it should be safe to free those cfs_rqs */
8586 free_sched_group(container_of(rhp, struct task_group, rcu));
8589 /* Destroy runqueue etc associated with a task group */
8590 void sched_destroy_group(struct task_group *tg)
8592 unsigned long flags;
8593 int i;
8595 spin_lock_irqsave(&task_group_lock, flags);
8596 for_each_possible_cpu(i) {
8597 unregister_fair_sched_group(tg, i);
8598 unregister_rt_sched_group(tg, i);
8600 list_del_rcu(&tg->list);
8601 list_del_rcu(&tg->siblings);
8602 spin_unlock_irqrestore(&task_group_lock, flags);
8604 /* wait for possible concurrent references to cfs_rqs complete */
8605 call_rcu(&tg->rcu, free_sched_group_rcu);
8608 /* change task's runqueue when it moves between groups.
8609 * The caller of this function should have put the task in its new group
8610 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8611 * reflect its new group.
8613 void sched_move_task(struct task_struct *tsk)
8615 int on_rq, running;
8616 unsigned long flags;
8617 struct rq *rq;
8619 rq = task_rq_lock(tsk, &flags);
8621 update_rq_clock(rq);
8623 running = task_current(rq, tsk);
8624 on_rq = tsk->se.on_rq;
8626 if (on_rq)
8627 dequeue_task(rq, tsk, 0);
8628 if (unlikely(running))
8629 tsk->sched_class->put_prev_task(rq, tsk);
8631 set_task_rq(tsk, task_cpu(tsk));
8633 #ifdef CONFIG_FAIR_GROUP_SCHED
8634 if (tsk->sched_class->moved_group)
8635 tsk->sched_class->moved_group(tsk);
8636 #endif
8638 if (unlikely(running))
8639 tsk->sched_class->set_curr_task(rq);
8640 if (on_rq)
8641 enqueue_task(rq, tsk, 0);
8643 task_rq_unlock(rq, &flags);
8645 #endif /* CONFIG_GROUP_SCHED */
8647 #ifdef CONFIG_FAIR_GROUP_SCHED
8648 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8650 struct cfs_rq *cfs_rq = se->cfs_rq;
8651 int on_rq;
8653 on_rq = se->on_rq;
8654 if (on_rq)
8655 dequeue_entity(cfs_rq, se, 0);
8657 se->load.weight = shares;
8658 se->load.inv_weight = 0;
8660 if (on_rq)
8661 enqueue_entity(cfs_rq, se, 0);
8664 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8666 struct cfs_rq *cfs_rq = se->cfs_rq;
8667 struct rq *rq = cfs_rq->rq;
8668 unsigned long flags;
8670 spin_lock_irqsave(&rq->lock, flags);
8671 __set_se_shares(se, shares);
8672 spin_unlock_irqrestore(&rq->lock, flags);
8675 static DEFINE_MUTEX(shares_mutex);
8677 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8679 int i;
8680 unsigned long flags;
8683 * We can't change the weight of the root cgroup.
8685 if (!tg->se[0])
8686 return -EINVAL;
8688 if (shares < MIN_SHARES)
8689 shares = MIN_SHARES;
8690 else if (shares > MAX_SHARES)
8691 shares = MAX_SHARES;
8693 mutex_lock(&shares_mutex);
8694 if (tg->shares == shares)
8695 goto done;
8697 spin_lock_irqsave(&task_group_lock, flags);
8698 for_each_possible_cpu(i)
8699 unregister_fair_sched_group(tg, i);
8700 list_del_rcu(&tg->siblings);
8701 spin_unlock_irqrestore(&task_group_lock, flags);
8703 /* wait for any ongoing reference to this group to finish */
8704 synchronize_sched();
8707 * Now we are free to modify the group's share on each cpu
8708 * w/o tripping rebalance_share or load_balance_fair.
8710 tg->shares = shares;
8711 for_each_possible_cpu(i) {
8713 * force a rebalance
8715 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8716 set_se_shares(tg->se[i], shares);
8720 * Enable load balance activity on this group, by inserting it back on
8721 * each cpu's rq->leaf_cfs_rq_list.
8723 spin_lock_irqsave(&task_group_lock, flags);
8724 for_each_possible_cpu(i)
8725 register_fair_sched_group(tg, i);
8726 list_add_rcu(&tg->siblings, &tg->parent->children);
8727 spin_unlock_irqrestore(&task_group_lock, flags);
8728 done:
8729 mutex_unlock(&shares_mutex);
8730 return 0;
8733 unsigned long sched_group_shares(struct task_group *tg)
8735 return tg->shares;
8737 #endif
8739 #ifdef CONFIG_RT_GROUP_SCHED
8741 * Ensure that the real time constraints are schedulable.
8743 static DEFINE_MUTEX(rt_constraints_mutex);
8745 static unsigned long to_ratio(u64 period, u64 runtime)
8747 if (runtime == RUNTIME_INF)
8748 return 1ULL << 16;
8750 return div64_u64(runtime << 16, period);
8753 #ifdef CONFIG_CGROUP_SCHED
8754 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8756 struct task_group *tgi, *parent = tg->parent;
8757 unsigned long total = 0;
8759 if (!parent) {
8760 if (global_rt_period() < period)
8761 return 0;
8763 return to_ratio(period, runtime) <
8764 to_ratio(global_rt_period(), global_rt_runtime());
8767 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8768 return 0;
8770 rcu_read_lock();
8771 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8772 if (tgi == tg)
8773 continue;
8775 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8776 tgi->rt_bandwidth.rt_runtime);
8778 rcu_read_unlock();
8780 return total + to_ratio(period, runtime) <=
8781 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8782 parent->rt_bandwidth.rt_runtime);
8784 #elif defined CONFIG_USER_SCHED
8785 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8787 struct task_group *tgi;
8788 unsigned long total = 0;
8789 unsigned long global_ratio =
8790 to_ratio(global_rt_period(), global_rt_runtime());
8792 rcu_read_lock();
8793 list_for_each_entry_rcu(tgi, &task_groups, list) {
8794 if (tgi == tg)
8795 continue;
8797 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8798 tgi->rt_bandwidth.rt_runtime);
8800 rcu_read_unlock();
8802 return total + to_ratio(period, runtime) < global_ratio;
8804 #endif
8806 /* Must be called with tasklist_lock held */
8807 static inline int tg_has_rt_tasks(struct task_group *tg)
8809 struct task_struct *g, *p;
8810 do_each_thread(g, p) {
8811 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8812 return 1;
8813 } while_each_thread(g, p);
8814 return 0;
8817 static int tg_set_bandwidth(struct task_group *tg,
8818 u64 rt_period, u64 rt_runtime)
8820 int i, err = 0;
8822 mutex_lock(&rt_constraints_mutex);
8823 read_lock(&tasklist_lock);
8824 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8825 err = -EBUSY;
8826 goto unlock;
8828 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8829 err = -EINVAL;
8830 goto unlock;
8833 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8834 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8835 tg->rt_bandwidth.rt_runtime = rt_runtime;
8837 for_each_possible_cpu(i) {
8838 struct rt_rq *rt_rq = tg->rt_rq[i];
8840 spin_lock(&rt_rq->rt_runtime_lock);
8841 rt_rq->rt_runtime = rt_runtime;
8842 spin_unlock(&rt_rq->rt_runtime_lock);
8844 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8845 unlock:
8846 read_unlock(&tasklist_lock);
8847 mutex_unlock(&rt_constraints_mutex);
8849 return err;
8852 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8854 u64 rt_runtime, rt_period;
8856 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8857 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8858 if (rt_runtime_us < 0)
8859 rt_runtime = RUNTIME_INF;
8861 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8864 long sched_group_rt_runtime(struct task_group *tg)
8866 u64 rt_runtime_us;
8868 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8869 return -1;
8871 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8872 do_div(rt_runtime_us, NSEC_PER_USEC);
8873 return rt_runtime_us;
8876 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8878 u64 rt_runtime, rt_period;
8880 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8881 rt_runtime = tg->rt_bandwidth.rt_runtime;
8883 if (rt_period == 0)
8884 return -EINVAL;
8886 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8889 long sched_group_rt_period(struct task_group *tg)
8891 u64 rt_period_us;
8893 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8894 do_div(rt_period_us, NSEC_PER_USEC);
8895 return rt_period_us;
8898 static int sched_rt_global_constraints(void)
8900 struct task_group *tg = &root_task_group;
8901 u64 rt_runtime, rt_period;
8902 int ret = 0;
8904 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8905 rt_runtime = tg->rt_bandwidth.rt_runtime;
8907 mutex_lock(&rt_constraints_mutex);
8908 if (!__rt_schedulable(tg, rt_period, rt_runtime))
8909 ret = -EINVAL;
8910 mutex_unlock(&rt_constraints_mutex);
8912 return ret;
8914 #else /* !CONFIG_RT_GROUP_SCHED */
8915 static int sched_rt_global_constraints(void)
8917 unsigned long flags;
8918 int i;
8920 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8921 for_each_possible_cpu(i) {
8922 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8924 spin_lock(&rt_rq->rt_runtime_lock);
8925 rt_rq->rt_runtime = global_rt_runtime();
8926 spin_unlock(&rt_rq->rt_runtime_lock);
8928 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8930 return 0;
8932 #endif /* CONFIG_RT_GROUP_SCHED */
8934 int sched_rt_handler(struct ctl_table *table, int write,
8935 struct file *filp, void __user *buffer, size_t *lenp,
8936 loff_t *ppos)
8938 int ret;
8939 int old_period, old_runtime;
8940 static DEFINE_MUTEX(mutex);
8942 mutex_lock(&mutex);
8943 old_period = sysctl_sched_rt_period;
8944 old_runtime = sysctl_sched_rt_runtime;
8946 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
8948 if (!ret && write) {
8949 ret = sched_rt_global_constraints();
8950 if (ret) {
8951 sysctl_sched_rt_period = old_period;
8952 sysctl_sched_rt_runtime = old_runtime;
8953 } else {
8954 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8955 def_rt_bandwidth.rt_period =
8956 ns_to_ktime(global_rt_period());
8959 mutex_unlock(&mutex);
8961 return ret;
8964 #ifdef CONFIG_CGROUP_SCHED
8966 /* return corresponding task_group object of a cgroup */
8967 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8969 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8970 struct task_group, css);
8973 static struct cgroup_subsys_state *
8974 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8976 struct task_group *tg, *parent;
8978 if (!cgrp->parent) {
8979 /* This is early initialization for the top cgroup */
8980 init_task_group.css.cgroup = cgrp;
8981 return &init_task_group.css;
8984 parent = cgroup_tg(cgrp->parent);
8985 tg = sched_create_group(parent);
8986 if (IS_ERR(tg))
8987 return ERR_PTR(-ENOMEM);
8989 /* Bind the cgroup to task_group object we just created */
8990 tg->css.cgroup = cgrp;
8992 return &tg->css;
8995 static void
8996 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8998 struct task_group *tg = cgroup_tg(cgrp);
9000 sched_destroy_group(tg);
9003 static int
9004 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9005 struct task_struct *tsk)
9007 #ifdef CONFIG_RT_GROUP_SCHED
9008 /* Don't accept realtime tasks when there is no way for them to run */
9009 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
9010 return -EINVAL;
9011 #else
9012 /* We don't support RT-tasks being in separate groups */
9013 if (tsk->sched_class != &fair_sched_class)
9014 return -EINVAL;
9015 #endif
9017 return 0;
9020 static void
9021 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
9022 struct cgroup *old_cont, struct task_struct *tsk)
9024 sched_move_task(tsk);
9027 #ifdef CONFIG_FAIR_GROUP_SCHED
9028 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9029 u64 shareval)
9031 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9034 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9036 struct task_group *tg = cgroup_tg(cgrp);
9038 return (u64) tg->shares;
9040 #endif /* CONFIG_FAIR_GROUP_SCHED */
9042 #ifdef CONFIG_RT_GROUP_SCHED
9043 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9044 s64 val)
9046 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9049 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9051 return sched_group_rt_runtime(cgroup_tg(cgrp));
9054 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9055 u64 rt_period_us)
9057 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9060 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9062 return sched_group_rt_period(cgroup_tg(cgrp));
9064 #endif /* CONFIG_RT_GROUP_SCHED */
9066 static struct cftype cpu_files[] = {
9067 #ifdef CONFIG_FAIR_GROUP_SCHED
9069 .name = "shares",
9070 .read_u64 = cpu_shares_read_u64,
9071 .write_u64 = cpu_shares_write_u64,
9073 #endif
9074 #ifdef CONFIG_RT_GROUP_SCHED
9076 .name = "rt_runtime_us",
9077 .read_s64 = cpu_rt_runtime_read,
9078 .write_s64 = cpu_rt_runtime_write,
9081 .name = "rt_period_us",
9082 .read_u64 = cpu_rt_period_read_uint,
9083 .write_u64 = cpu_rt_period_write_uint,
9085 #endif
9088 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9090 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9093 struct cgroup_subsys cpu_cgroup_subsys = {
9094 .name = "cpu",
9095 .create = cpu_cgroup_create,
9096 .destroy = cpu_cgroup_destroy,
9097 .can_attach = cpu_cgroup_can_attach,
9098 .attach = cpu_cgroup_attach,
9099 .populate = cpu_cgroup_populate,
9100 .subsys_id = cpu_cgroup_subsys_id,
9101 .early_init = 1,
9104 #endif /* CONFIG_CGROUP_SCHED */
9106 #ifdef CONFIG_CGROUP_CPUACCT
9109 * CPU accounting code for task groups.
9111 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9112 * (balbir@in.ibm.com).
9115 /* track cpu usage of a group of tasks */
9116 struct cpuacct {
9117 struct cgroup_subsys_state css;
9118 /* cpuusage holds pointer to a u64-type object on every cpu */
9119 u64 *cpuusage;
9122 struct cgroup_subsys cpuacct_subsys;
9124 /* return cpu accounting group corresponding to this container */
9125 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9127 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9128 struct cpuacct, css);
9131 /* return cpu accounting group to which this task belongs */
9132 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9134 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9135 struct cpuacct, css);
9138 /* create a new cpu accounting group */
9139 static struct cgroup_subsys_state *cpuacct_create(
9140 struct cgroup_subsys *ss, struct cgroup *cgrp)
9142 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9144 if (!ca)
9145 return ERR_PTR(-ENOMEM);
9147 ca->cpuusage = alloc_percpu(u64);
9148 if (!ca->cpuusage) {
9149 kfree(ca);
9150 return ERR_PTR(-ENOMEM);
9153 return &ca->css;
9156 /* destroy an existing cpu accounting group */
9157 static void
9158 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9160 struct cpuacct *ca = cgroup_ca(cgrp);
9162 free_percpu(ca->cpuusage);
9163 kfree(ca);
9166 /* return total cpu usage (in nanoseconds) of a group */
9167 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9169 struct cpuacct *ca = cgroup_ca(cgrp);
9170 u64 totalcpuusage = 0;
9171 int i;
9173 for_each_possible_cpu(i) {
9174 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9177 * Take rq->lock to make 64-bit addition safe on 32-bit
9178 * platforms.
9180 spin_lock_irq(&cpu_rq(i)->lock);
9181 totalcpuusage += *cpuusage;
9182 spin_unlock_irq(&cpu_rq(i)->lock);
9185 return totalcpuusage;
9188 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9189 u64 reset)
9191 struct cpuacct *ca = cgroup_ca(cgrp);
9192 int err = 0;
9193 int i;
9195 if (reset) {
9196 err = -EINVAL;
9197 goto out;
9200 for_each_possible_cpu(i) {
9201 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9203 spin_lock_irq(&cpu_rq(i)->lock);
9204 *cpuusage = 0;
9205 spin_unlock_irq(&cpu_rq(i)->lock);
9207 out:
9208 return err;
9211 static struct cftype files[] = {
9213 .name = "usage",
9214 .read_u64 = cpuusage_read,
9215 .write_u64 = cpuusage_write,
9219 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9221 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9225 * charge this task's execution time to its accounting group.
9227 * called with rq->lock held.
9229 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9231 struct cpuacct *ca;
9233 if (!cpuacct_subsys.active)
9234 return;
9236 ca = task_ca(tsk);
9237 if (ca) {
9238 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9240 *cpuusage += cputime;
9244 struct cgroup_subsys cpuacct_subsys = {
9245 .name = "cpuacct",
9246 .create = cpuacct_create,
9247 .destroy = cpuacct_destroy,
9248 .populate = cpuacct_populate,
9249 .subsys_id = cpuacct_subsys_id,
9251 #endif /* CONFIG_CGROUP_CPUACCT */