BKL: That's all, folks
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / sched.c
blob827c170c601799d715749f6ee90d60f44d52f36b
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 <asm/mmu_context.h>
36 #include <linux/interrupt.h>
37 #include <linux/capability.h>
38 #include <linux/completion.h>
39 #include <linux/kernel_stat.h>
40 #include <linux/debug_locks.h>
41 #include <linux/perf_event.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/proc_fs.h>
58 #include <linux/seq_file.h>
59 #include <linux/stop_machine.h>
60 #include <linux/sysctl.h>
61 #include <linux/syscalls.h>
62 #include <linux/times.h>
63 #include <linux/tsacct_kern.h>
64 #include <linux/kprobes.h>
65 #include <linux/delayacct.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/debugfs.h>
71 #include <linux/ctype.h>
72 #include <linux/ftrace.h>
73 #include <linux/slab.h>
75 #include <asm/tlb.h>
76 #include <asm/irq_regs.h>
77 #include <asm/mutex.h>
79 #include "sched_cpupri.h"
80 #include "workqueue_sched.h"
81 #include "sched_autogroup.h"
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/sched.h>
87 * Convert user-nice values [ -20 ... 0 ... 19 ]
88 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
89 * and back.
91 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
92 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
93 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
96 * 'User priority' is the nice value converted to something we
97 * can work with better when scaling various scheduler parameters,
98 * it's a [ 0 ... 39 ] range.
100 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
101 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
102 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
105 * Helpers for converting nanosecond timing to jiffy resolution
107 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
109 #define NICE_0_LOAD SCHED_LOAD_SCALE
110 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
113 * These are the 'tuning knobs' of the scheduler:
115 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
116 * Timeslices get refilled after they expire.
118 #define DEF_TIMESLICE (100 * HZ / 1000)
121 * single value that denotes runtime == period, ie unlimited time.
123 #define RUNTIME_INF ((u64)~0ULL)
125 static inline int rt_policy(int policy)
127 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
128 return 1;
129 return 0;
132 static inline int task_has_rt_policy(struct task_struct *p)
134 return rt_policy(p->policy);
138 * This is the priority-queue data structure of the RT scheduling class:
140 struct rt_prio_array {
141 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
142 struct list_head queue[MAX_RT_PRIO];
145 struct rt_bandwidth {
146 /* nests inside the rq lock: */
147 raw_spinlock_t rt_runtime_lock;
148 ktime_t rt_period;
149 u64 rt_runtime;
150 struct hrtimer rt_period_timer;
153 static struct rt_bandwidth def_rt_bandwidth;
155 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
157 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
159 struct rt_bandwidth *rt_b =
160 container_of(timer, struct rt_bandwidth, rt_period_timer);
161 ktime_t now;
162 int overrun;
163 int idle = 0;
165 for (;;) {
166 now = hrtimer_cb_get_time(timer);
167 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
169 if (!overrun)
170 break;
172 idle = do_sched_rt_period_timer(rt_b, overrun);
175 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
178 static
179 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
181 rt_b->rt_period = ns_to_ktime(period);
182 rt_b->rt_runtime = runtime;
184 raw_spin_lock_init(&rt_b->rt_runtime_lock);
186 hrtimer_init(&rt_b->rt_period_timer,
187 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
188 rt_b->rt_period_timer.function = sched_rt_period_timer;
191 static inline int rt_bandwidth_enabled(void)
193 return sysctl_sched_rt_runtime >= 0;
196 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
198 ktime_t now;
200 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
201 return;
203 if (hrtimer_active(&rt_b->rt_period_timer))
204 return;
206 raw_spin_lock(&rt_b->rt_runtime_lock);
207 for (;;) {
208 unsigned long delta;
209 ktime_t soft, hard;
211 if (hrtimer_active(&rt_b->rt_period_timer))
212 break;
214 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
215 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
217 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
218 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
219 delta = ktime_to_ns(ktime_sub(hard, soft));
220 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
221 HRTIMER_MODE_ABS_PINNED, 0);
223 raw_spin_unlock(&rt_b->rt_runtime_lock);
226 #ifdef CONFIG_RT_GROUP_SCHED
227 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
229 hrtimer_cancel(&rt_b->rt_period_timer);
231 #endif
234 * sched_domains_mutex serializes calls to arch_init_sched_domains,
235 * detach_destroy_domains and partition_sched_domains.
237 static DEFINE_MUTEX(sched_domains_mutex);
239 #ifdef CONFIG_CGROUP_SCHED
241 #include <linux/cgroup.h>
243 struct cfs_rq;
245 static LIST_HEAD(task_groups);
247 /* task group related information */
248 struct task_group {
249 struct cgroup_subsys_state css;
251 #ifdef CONFIG_FAIR_GROUP_SCHED
252 /* schedulable entities of this group on each cpu */
253 struct sched_entity **se;
254 /* runqueue "owned" by this group on each cpu */
255 struct cfs_rq **cfs_rq;
256 unsigned long shares;
258 atomic_t load_weight;
259 #endif
261 #ifdef CONFIG_RT_GROUP_SCHED
262 struct sched_rt_entity **rt_se;
263 struct rt_rq **rt_rq;
265 struct rt_bandwidth rt_bandwidth;
266 #endif
268 struct rcu_head rcu;
269 struct list_head list;
271 struct task_group *parent;
272 struct list_head siblings;
273 struct list_head children;
275 #ifdef CONFIG_SCHED_AUTOGROUP
276 struct autogroup *autogroup;
277 #endif
280 /* task_group_lock serializes the addition/removal of task groups */
281 static DEFINE_SPINLOCK(task_group_lock);
283 #ifdef CONFIG_FAIR_GROUP_SCHED
285 # define ROOT_TASK_GROUP_LOAD NICE_0_LOAD
288 * A weight of 0 or 1 can cause arithmetics problems.
289 * A weight of a cfs_rq is the sum of weights of which entities
290 * are queued on this cfs_rq, so a weight of a entity should not be
291 * too large, so as the shares value of a task group.
292 * (The default weight is 1024 - so there's no practical
293 * limitation from this.)
295 #define MIN_SHARES 2
296 #define MAX_SHARES (1UL << 18)
298 static int root_task_group_load = ROOT_TASK_GROUP_LOAD;
299 #endif
301 /* Default task group.
302 * Every task in system belong to this group at bootup.
304 struct task_group root_task_group;
306 #endif /* CONFIG_CGROUP_SCHED */
308 /* CFS-related fields in a runqueue */
309 struct cfs_rq {
310 struct load_weight load;
311 unsigned long nr_running;
313 u64 exec_clock;
314 u64 min_vruntime;
316 struct rb_root tasks_timeline;
317 struct rb_node *rb_leftmost;
319 struct list_head tasks;
320 struct list_head *balance_iterator;
323 * 'curr' points to currently running entity on this cfs_rq.
324 * It is set to NULL otherwise (i.e when none are currently running).
326 struct sched_entity *curr, *next, *last;
328 unsigned int nr_spread_over;
330 #ifdef CONFIG_FAIR_GROUP_SCHED
331 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
334 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
335 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
336 * (like users, containers etc.)
338 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
339 * list is used during load balance.
341 int on_list;
342 struct list_head leaf_cfs_rq_list;
343 struct task_group *tg; /* group that "owns" this runqueue */
345 #ifdef CONFIG_SMP
347 * the part of load.weight contributed by tasks
349 unsigned long task_weight;
352 * h_load = weight * f(tg)
354 * Where f(tg) is the recursive weight fraction assigned to
355 * this group.
357 unsigned long h_load;
360 * Maintaining per-cpu shares distribution for group scheduling
362 * load_stamp is the last time we updated the load average
363 * load_last is the last time we updated the load average and saw load
364 * load_unacc_exec_time is currently unaccounted execution time
366 u64 load_avg;
367 u64 load_period;
368 u64 load_stamp, load_last, load_unacc_exec_time;
370 unsigned long load_contribution;
371 #endif
372 #endif
375 /* Real-Time classes' related field in a runqueue: */
376 struct rt_rq {
377 struct rt_prio_array active;
378 unsigned long rt_nr_running;
379 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
380 struct {
381 int curr; /* highest queued rt task prio */
382 #ifdef CONFIG_SMP
383 int next; /* next highest */
384 #endif
385 } highest_prio;
386 #endif
387 #ifdef CONFIG_SMP
388 unsigned long rt_nr_migratory;
389 unsigned long rt_nr_total;
390 int overloaded;
391 struct plist_head pushable_tasks;
392 #endif
393 int rt_throttled;
394 u64 rt_time;
395 u64 rt_runtime;
396 /* Nests inside the rq lock: */
397 raw_spinlock_t rt_runtime_lock;
399 #ifdef CONFIG_RT_GROUP_SCHED
400 unsigned long rt_nr_boosted;
402 struct rq *rq;
403 struct list_head leaf_rt_rq_list;
404 struct task_group *tg;
405 #endif
408 #ifdef CONFIG_SMP
411 * We add the notion of a root-domain which will be used to define per-domain
412 * variables. Each exclusive cpuset essentially defines an island domain by
413 * fully partitioning the member cpus from any other cpuset. Whenever a new
414 * exclusive cpuset is created, we also create and attach a new root-domain
415 * object.
418 struct root_domain {
419 atomic_t refcount;
420 cpumask_var_t span;
421 cpumask_var_t online;
424 * The "RT overload" flag: it gets set if a CPU has more than
425 * one runnable RT task.
427 cpumask_var_t rto_mask;
428 atomic_t rto_count;
429 struct cpupri cpupri;
433 * By default the system creates a single root-domain with all cpus as
434 * members (mimicking the global state we have today).
436 static struct root_domain def_root_domain;
438 #endif /* CONFIG_SMP */
441 * This is the main, per-CPU runqueue data structure.
443 * Locking rule: those places that want to lock multiple runqueues
444 * (such as the load balancing or the thread migration code), lock
445 * acquire operations must be ordered by ascending &runqueue.
447 struct rq {
448 /* runqueue lock: */
449 raw_spinlock_t lock;
452 * nr_running and cpu_load should be in the same cacheline because
453 * remote CPUs use both these fields when doing load calculation.
455 unsigned long nr_running;
456 #define CPU_LOAD_IDX_MAX 5
457 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
458 unsigned long last_load_update_tick;
459 #ifdef CONFIG_NO_HZ
460 u64 nohz_stamp;
461 unsigned char nohz_balance_kick;
462 #endif
463 unsigned int skip_clock_update;
465 /* capture load from *all* tasks on this cpu: */
466 struct load_weight load;
467 unsigned long nr_load_updates;
468 u64 nr_switches;
470 struct cfs_rq cfs;
471 struct rt_rq rt;
473 #ifdef CONFIG_FAIR_GROUP_SCHED
474 /* list of leaf cfs_rq on this cpu: */
475 struct list_head leaf_cfs_rq_list;
476 #endif
477 #ifdef CONFIG_RT_GROUP_SCHED
478 struct list_head leaf_rt_rq_list;
479 #endif
482 * This is part of a global counter where only the total sum
483 * over all CPUs matters. A task can increase this counter on
484 * one CPU and if it got migrated afterwards it may decrease
485 * it on another CPU. Always updated under the runqueue lock:
487 unsigned long nr_uninterruptible;
489 struct task_struct *curr, *idle, *stop;
490 unsigned long next_balance;
491 struct mm_struct *prev_mm;
493 u64 clock;
494 u64 clock_task;
496 atomic_t nr_iowait;
498 #ifdef CONFIG_SMP
499 struct root_domain *rd;
500 struct sched_domain *sd;
502 unsigned long cpu_power;
504 unsigned char idle_at_tick;
505 /* For active balancing */
506 int post_schedule;
507 int active_balance;
508 int push_cpu;
509 struct cpu_stop_work active_balance_work;
510 /* cpu of this runqueue: */
511 int cpu;
512 int online;
514 unsigned long avg_load_per_task;
516 u64 rt_avg;
517 u64 age_stamp;
518 u64 idle_stamp;
519 u64 avg_idle;
520 #endif
522 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
523 u64 prev_irq_time;
524 #endif
526 /* calc_load related fields */
527 unsigned long calc_load_update;
528 long calc_load_active;
530 #ifdef CONFIG_SCHED_HRTICK
531 #ifdef CONFIG_SMP
532 int hrtick_csd_pending;
533 struct call_single_data hrtick_csd;
534 #endif
535 struct hrtimer hrtick_timer;
536 #endif
538 #ifdef CONFIG_SCHEDSTATS
539 /* latency stats */
540 struct sched_info rq_sched_info;
541 unsigned long long rq_cpu_time;
542 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
544 /* sys_sched_yield() stats */
545 unsigned int yld_count;
547 /* schedule() stats */
548 unsigned int sched_switch;
549 unsigned int sched_count;
550 unsigned int sched_goidle;
552 /* try_to_wake_up() stats */
553 unsigned int ttwu_count;
554 unsigned int ttwu_local;
555 #endif
558 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
561 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags);
563 static inline int cpu_of(struct rq *rq)
565 #ifdef CONFIG_SMP
566 return rq->cpu;
567 #else
568 return 0;
569 #endif
572 #define rcu_dereference_check_sched_domain(p) \
573 rcu_dereference_check((p), \
574 rcu_read_lock_sched_held() || \
575 lockdep_is_held(&sched_domains_mutex))
578 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
579 * See detach_destroy_domains: synchronize_sched for details.
581 * The domain tree of any CPU may only be accessed from within
582 * preempt-disabled sections.
584 #define for_each_domain(cpu, __sd) \
585 for (__sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
587 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
588 #define this_rq() (&__get_cpu_var(runqueues))
589 #define task_rq(p) cpu_rq(task_cpu(p))
590 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
591 #define raw_rq() (&__raw_get_cpu_var(runqueues))
593 #ifdef CONFIG_CGROUP_SCHED
596 * Return the group to which this tasks belongs.
598 * We use task_subsys_state_check() and extend the RCU verification
599 * with lockdep_is_held(&task_rq(p)->lock) because cpu_cgroup_attach()
600 * holds that lock for each task it moves into the cgroup. Therefore
601 * by holding that lock, we pin the task to the current cgroup.
603 static inline struct task_group *task_group(struct task_struct *p)
605 struct task_group *tg;
606 struct cgroup_subsys_state *css;
608 if (p->flags & PF_EXITING)
609 return &root_task_group;
611 css = task_subsys_state_check(p, cpu_cgroup_subsys_id,
612 lockdep_is_held(&task_rq(p)->lock));
613 tg = container_of(css, struct task_group, css);
615 return autogroup_task_group(p, tg);
618 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
619 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
621 #ifdef CONFIG_FAIR_GROUP_SCHED
622 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
623 p->se.parent = task_group(p)->se[cpu];
624 #endif
626 #ifdef CONFIG_RT_GROUP_SCHED
627 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
628 p->rt.parent = task_group(p)->rt_se[cpu];
629 #endif
632 #else /* CONFIG_CGROUP_SCHED */
634 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
635 static inline struct task_group *task_group(struct task_struct *p)
637 return NULL;
640 #endif /* CONFIG_CGROUP_SCHED */
642 static void update_rq_clock_task(struct rq *rq, s64 delta);
644 static void update_rq_clock(struct rq *rq)
646 s64 delta;
648 if (rq->skip_clock_update)
649 return;
651 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
652 rq->clock += delta;
653 update_rq_clock_task(rq, delta);
657 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
659 #ifdef CONFIG_SCHED_DEBUG
660 # define const_debug __read_mostly
661 #else
662 # define const_debug static const
663 #endif
666 * runqueue_is_locked
667 * @cpu: the processor in question.
669 * Returns true if the current cpu runqueue is locked.
670 * This interface allows printk to be called with the runqueue lock
671 * held and know whether or not it is OK to wake up the klogd.
673 int runqueue_is_locked(int cpu)
675 return raw_spin_is_locked(&cpu_rq(cpu)->lock);
679 * Debugging: various feature bits
682 #define SCHED_FEAT(name, enabled) \
683 __SCHED_FEAT_##name ,
685 enum {
686 #include "sched_features.h"
689 #undef SCHED_FEAT
691 #define SCHED_FEAT(name, enabled) \
692 (1UL << __SCHED_FEAT_##name) * enabled |
694 const_debug unsigned int sysctl_sched_features =
695 #include "sched_features.h"
698 #undef SCHED_FEAT
700 #ifdef CONFIG_SCHED_DEBUG
701 #define SCHED_FEAT(name, enabled) \
702 #name ,
704 static __read_mostly char *sched_feat_names[] = {
705 #include "sched_features.h"
706 NULL
709 #undef SCHED_FEAT
711 static int sched_feat_show(struct seq_file *m, void *v)
713 int i;
715 for (i = 0; sched_feat_names[i]; i++) {
716 if (!(sysctl_sched_features & (1UL << i)))
717 seq_puts(m, "NO_");
718 seq_printf(m, "%s ", sched_feat_names[i]);
720 seq_puts(m, "\n");
722 return 0;
725 static ssize_t
726 sched_feat_write(struct file *filp, const char __user *ubuf,
727 size_t cnt, loff_t *ppos)
729 char buf[64];
730 char *cmp;
731 int neg = 0;
732 int i;
734 if (cnt > 63)
735 cnt = 63;
737 if (copy_from_user(&buf, ubuf, cnt))
738 return -EFAULT;
740 buf[cnt] = 0;
741 cmp = strstrip(buf);
743 if (strncmp(cmp, "NO_", 3) == 0) {
744 neg = 1;
745 cmp += 3;
748 for (i = 0; sched_feat_names[i]; i++) {
749 if (strcmp(cmp, sched_feat_names[i]) == 0) {
750 if (neg)
751 sysctl_sched_features &= ~(1UL << i);
752 else
753 sysctl_sched_features |= (1UL << i);
754 break;
758 if (!sched_feat_names[i])
759 return -EINVAL;
761 *ppos += cnt;
763 return cnt;
766 static int sched_feat_open(struct inode *inode, struct file *filp)
768 return single_open(filp, sched_feat_show, NULL);
771 static const struct file_operations sched_feat_fops = {
772 .open = sched_feat_open,
773 .write = sched_feat_write,
774 .read = seq_read,
775 .llseek = seq_lseek,
776 .release = single_release,
779 static __init int sched_init_debug(void)
781 debugfs_create_file("sched_features", 0644, NULL, NULL,
782 &sched_feat_fops);
784 return 0;
786 late_initcall(sched_init_debug);
788 #endif
790 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
793 * Number of tasks to iterate in a single balance run.
794 * Limited because this is done with IRQs disabled.
796 const_debug unsigned int sysctl_sched_nr_migrate = 32;
799 * period over which we average the RT time consumption, measured
800 * in ms.
802 * default: 1s
804 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
807 * period over which we measure -rt task cpu usage in us.
808 * default: 1s
810 unsigned int sysctl_sched_rt_period = 1000000;
812 static __read_mostly int scheduler_running;
815 * part of the period that we allow rt tasks to run in us.
816 * default: 0.95s
818 int sysctl_sched_rt_runtime = 950000;
820 static inline u64 global_rt_period(void)
822 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
825 static inline u64 global_rt_runtime(void)
827 if (sysctl_sched_rt_runtime < 0)
828 return RUNTIME_INF;
830 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
833 #ifndef prepare_arch_switch
834 # define prepare_arch_switch(next) do { } while (0)
835 #endif
836 #ifndef finish_arch_switch
837 # define finish_arch_switch(prev) do { } while (0)
838 #endif
840 static inline int task_current(struct rq *rq, struct task_struct *p)
842 return rq->curr == p;
845 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
846 static inline int task_running(struct rq *rq, struct task_struct *p)
848 return task_current(rq, p);
851 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
855 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
857 #ifdef CONFIG_DEBUG_SPINLOCK
858 /* this is a valid case when another task releases the spinlock */
859 rq->lock.owner = current;
860 #endif
862 * If we are tracking spinlock dependencies then we have to
863 * fix up the runqueue lock - which gets 'carried over' from
864 * prev into current:
866 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
868 raw_spin_unlock_irq(&rq->lock);
871 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
872 static inline int task_running(struct rq *rq, struct task_struct *p)
874 #ifdef CONFIG_SMP
875 return p->oncpu;
876 #else
877 return task_current(rq, p);
878 #endif
881 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
883 #ifdef CONFIG_SMP
885 * We can optimise this out completely for !SMP, because the
886 * SMP rebalancing from interrupt is the only thing that cares
887 * here.
889 next->oncpu = 1;
890 #endif
891 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
892 raw_spin_unlock_irq(&rq->lock);
893 #else
894 raw_spin_unlock(&rq->lock);
895 #endif
898 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
900 #ifdef CONFIG_SMP
902 * After ->oncpu is cleared, the task can be moved to a different CPU.
903 * We must ensure this doesn't happen until the switch is completely
904 * finished.
906 smp_wmb();
907 prev->oncpu = 0;
908 #endif
909 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
910 local_irq_enable();
911 #endif
913 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
916 * Check whether the task is waking, we use this to synchronize ->cpus_allowed
917 * against ttwu().
919 static inline int task_is_waking(struct task_struct *p)
921 return unlikely(p->state == TASK_WAKING);
925 * __task_rq_lock - lock the runqueue a given task resides on.
926 * Must be called interrupts disabled.
928 static inline struct rq *__task_rq_lock(struct task_struct *p)
929 __acquires(rq->lock)
931 struct rq *rq;
933 for (;;) {
934 rq = task_rq(p);
935 raw_spin_lock(&rq->lock);
936 if (likely(rq == task_rq(p)))
937 return rq;
938 raw_spin_unlock(&rq->lock);
943 * task_rq_lock - lock the runqueue a given task resides on and disable
944 * interrupts. Note the ordering: we can safely lookup the task_rq without
945 * explicitly disabling preemption.
947 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
948 __acquires(rq->lock)
950 struct rq *rq;
952 for (;;) {
953 local_irq_save(*flags);
954 rq = task_rq(p);
955 raw_spin_lock(&rq->lock);
956 if (likely(rq == task_rq(p)))
957 return rq;
958 raw_spin_unlock_irqrestore(&rq->lock, *flags);
962 static void __task_rq_unlock(struct rq *rq)
963 __releases(rq->lock)
965 raw_spin_unlock(&rq->lock);
968 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
969 __releases(rq->lock)
971 raw_spin_unlock_irqrestore(&rq->lock, *flags);
975 * this_rq_lock - lock this runqueue and disable interrupts.
977 static struct rq *this_rq_lock(void)
978 __acquires(rq->lock)
980 struct rq *rq;
982 local_irq_disable();
983 rq = this_rq();
984 raw_spin_lock(&rq->lock);
986 return rq;
989 #ifdef CONFIG_SCHED_HRTICK
991 * Use HR-timers to deliver accurate preemption points.
993 * Its all a bit involved since we cannot program an hrt while holding the
994 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
995 * reschedule event.
997 * When we get rescheduled we reprogram the hrtick_timer outside of the
998 * rq->lock.
1002 * Use hrtick when:
1003 * - enabled by features
1004 * - hrtimer is actually high res
1006 static inline int hrtick_enabled(struct rq *rq)
1008 if (!sched_feat(HRTICK))
1009 return 0;
1010 if (!cpu_active(cpu_of(rq)))
1011 return 0;
1012 return hrtimer_is_hres_active(&rq->hrtick_timer);
1015 static void hrtick_clear(struct rq *rq)
1017 if (hrtimer_active(&rq->hrtick_timer))
1018 hrtimer_cancel(&rq->hrtick_timer);
1022 * High-resolution timer tick.
1023 * Runs from hardirq context with interrupts disabled.
1025 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1027 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1029 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1031 raw_spin_lock(&rq->lock);
1032 update_rq_clock(rq);
1033 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1034 raw_spin_unlock(&rq->lock);
1036 return HRTIMER_NORESTART;
1039 #ifdef CONFIG_SMP
1041 * called from hardirq (IPI) context
1043 static void __hrtick_start(void *arg)
1045 struct rq *rq = arg;
1047 raw_spin_lock(&rq->lock);
1048 hrtimer_restart(&rq->hrtick_timer);
1049 rq->hrtick_csd_pending = 0;
1050 raw_spin_unlock(&rq->lock);
1054 * Called to set the hrtick timer state.
1056 * called with rq->lock held and irqs disabled
1058 static void hrtick_start(struct rq *rq, u64 delay)
1060 struct hrtimer *timer = &rq->hrtick_timer;
1061 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1063 hrtimer_set_expires(timer, time);
1065 if (rq == this_rq()) {
1066 hrtimer_restart(timer);
1067 } else if (!rq->hrtick_csd_pending) {
1068 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1069 rq->hrtick_csd_pending = 1;
1073 static int
1074 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1076 int cpu = (int)(long)hcpu;
1078 switch (action) {
1079 case CPU_UP_CANCELED:
1080 case CPU_UP_CANCELED_FROZEN:
1081 case CPU_DOWN_PREPARE:
1082 case CPU_DOWN_PREPARE_FROZEN:
1083 case CPU_DEAD:
1084 case CPU_DEAD_FROZEN:
1085 hrtick_clear(cpu_rq(cpu));
1086 return NOTIFY_OK;
1089 return NOTIFY_DONE;
1092 static __init void init_hrtick(void)
1094 hotcpu_notifier(hotplug_hrtick, 0);
1096 #else
1098 * Called to set the hrtick timer state.
1100 * called with rq->lock held and irqs disabled
1102 static void hrtick_start(struct rq *rq, u64 delay)
1104 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1105 HRTIMER_MODE_REL_PINNED, 0);
1108 static inline void init_hrtick(void)
1111 #endif /* CONFIG_SMP */
1113 static void init_rq_hrtick(struct rq *rq)
1115 #ifdef CONFIG_SMP
1116 rq->hrtick_csd_pending = 0;
1118 rq->hrtick_csd.flags = 0;
1119 rq->hrtick_csd.func = __hrtick_start;
1120 rq->hrtick_csd.info = rq;
1121 #endif
1123 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1124 rq->hrtick_timer.function = hrtick;
1126 #else /* CONFIG_SCHED_HRTICK */
1127 static inline void hrtick_clear(struct rq *rq)
1131 static inline void init_rq_hrtick(struct rq *rq)
1135 static inline void init_hrtick(void)
1138 #endif /* CONFIG_SCHED_HRTICK */
1141 * resched_task - mark a task 'to be rescheduled now'.
1143 * On UP this means the setting of the need_resched flag, on SMP it
1144 * might also involve a cross-CPU call to trigger the scheduler on
1145 * the target CPU.
1147 #ifdef CONFIG_SMP
1149 #ifndef tsk_is_polling
1150 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1151 #endif
1153 static void resched_task(struct task_struct *p)
1155 int cpu;
1157 assert_raw_spin_locked(&task_rq(p)->lock);
1159 if (test_tsk_need_resched(p))
1160 return;
1162 set_tsk_need_resched(p);
1164 cpu = task_cpu(p);
1165 if (cpu == smp_processor_id())
1166 return;
1168 /* NEED_RESCHED must be visible before we test polling */
1169 smp_mb();
1170 if (!tsk_is_polling(p))
1171 smp_send_reschedule(cpu);
1174 static void resched_cpu(int cpu)
1176 struct rq *rq = cpu_rq(cpu);
1177 unsigned long flags;
1179 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1180 return;
1181 resched_task(cpu_curr(cpu));
1182 raw_spin_unlock_irqrestore(&rq->lock, flags);
1185 #ifdef CONFIG_NO_HZ
1187 * In the semi idle case, use the nearest busy cpu for migrating timers
1188 * from an idle cpu. This is good for power-savings.
1190 * We don't do similar optimization for completely idle system, as
1191 * selecting an idle cpu will add more delays to the timers than intended
1192 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
1194 int get_nohz_timer_target(void)
1196 int cpu = smp_processor_id();
1197 int i;
1198 struct sched_domain *sd;
1200 for_each_domain(cpu, sd) {
1201 for_each_cpu(i, sched_domain_span(sd))
1202 if (!idle_cpu(i))
1203 return i;
1205 return cpu;
1208 * When add_timer_on() enqueues a timer into the timer wheel of an
1209 * idle CPU then this timer might expire before the next timer event
1210 * which is scheduled to wake up that CPU. In case of a completely
1211 * idle system the next event might even be infinite time into the
1212 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1213 * leaves the inner idle loop so the newly added timer is taken into
1214 * account when the CPU goes back to idle and evaluates the timer
1215 * wheel for the next timer event.
1217 void wake_up_idle_cpu(int cpu)
1219 struct rq *rq = cpu_rq(cpu);
1221 if (cpu == smp_processor_id())
1222 return;
1225 * This is safe, as this function is called with the timer
1226 * wheel base lock of (cpu) held. When the CPU is on the way
1227 * to idle and has not yet set rq->curr to idle then it will
1228 * be serialized on the timer wheel base lock and take the new
1229 * timer into account automatically.
1231 if (rq->curr != rq->idle)
1232 return;
1235 * We can set TIF_RESCHED on the idle task of the other CPU
1236 * lockless. The worst case is that the other CPU runs the
1237 * idle task through an additional NOOP schedule()
1239 set_tsk_need_resched(rq->idle);
1241 /* NEED_RESCHED must be visible before we test polling */
1242 smp_mb();
1243 if (!tsk_is_polling(rq->idle))
1244 smp_send_reschedule(cpu);
1247 #endif /* CONFIG_NO_HZ */
1249 static u64 sched_avg_period(void)
1251 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1254 static void sched_avg_update(struct rq *rq)
1256 s64 period = sched_avg_period();
1258 while ((s64)(rq->clock - rq->age_stamp) > period) {
1260 * Inline assembly required to prevent the compiler
1261 * optimising this loop into a divmod call.
1262 * See __iter_div_u64_rem() for another example of this.
1264 asm("" : "+rm" (rq->age_stamp));
1265 rq->age_stamp += period;
1266 rq->rt_avg /= 2;
1270 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1272 rq->rt_avg += rt_delta;
1273 sched_avg_update(rq);
1276 #else /* !CONFIG_SMP */
1277 static void resched_task(struct task_struct *p)
1279 assert_raw_spin_locked(&task_rq(p)->lock);
1280 set_tsk_need_resched(p);
1283 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1287 static void sched_avg_update(struct rq *rq)
1290 #endif /* CONFIG_SMP */
1292 #if BITS_PER_LONG == 32
1293 # define WMULT_CONST (~0UL)
1294 #else
1295 # define WMULT_CONST (1UL << 32)
1296 #endif
1298 #define WMULT_SHIFT 32
1301 * Shift right and round:
1303 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1306 * delta *= weight / lw
1308 static unsigned long
1309 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1310 struct load_weight *lw)
1312 u64 tmp;
1314 if (!lw->inv_weight) {
1315 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1316 lw->inv_weight = 1;
1317 else
1318 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1319 / (lw->weight+1);
1322 tmp = (u64)delta_exec * weight;
1324 * Check whether we'd overflow the 64-bit multiplication:
1326 if (unlikely(tmp > WMULT_CONST))
1327 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1328 WMULT_SHIFT/2);
1329 else
1330 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1332 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1335 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1337 lw->weight += inc;
1338 lw->inv_weight = 0;
1341 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1343 lw->weight -= dec;
1344 lw->inv_weight = 0;
1347 static inline void update_load_set(struct load_weight *lw, unsigned long w)
1349 lw->weight = w;
1350 lw->inv_weight = 0;
1354 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1355 * of tasks with abnormal "nice" values across CPUs the contribution that
1356 * each task makes to its run queue's load is weighted according to its
1357 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1358 * scaled version of the new time slice allocation that they receive on time
1359 * slice expiry etc.
1362 #define WEIGHT_IDLEPRIO 3
1363 #define WMULT_IDLEPRIO 1431655765
1366 * Nice levels are multiplicative, with a gentle 10% change for every
1367 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1368 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1369 * that remained on nice 0.
1371 * The "10% effect" is relative and cumulative: from _any_ nice level,
1372 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1373 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1374 * If a task goes up by ~10% and another task goes down by ~10% then
1375 * the relative distance between them is ~25%.)
1377 static const int prio_to_weight[40] = {
1378 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1379 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1380 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1381 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1382 /* 0 */ 1024, 820, 655, 526, 423,
1383 /* 5 */ 335, 272, 215, 172, 137,
1384 /* 10 */ 110, 87, 70, 56, 45,
1385 /* 15 */ 36, 29, 23, 18, 15,
1389 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1391 * In cases where the weight does not change often, we can use the
1392 * precalculated inverse to speed up arithmetics by turning divisions
1393 * into multiplications:
1395 static const u32 prio_to_wmult[40] = {
1396 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1397 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1398 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1399 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1400 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1401 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1402 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1403 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1406 /* Time spent by the tasks of the cpu accounting group executing in ... */
1407 enum cpuacct_stat_index {
1408 CPUACCT_STAT_USER, /* ... user mode */
1409 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1411 CPUACCT_STAT_NSTATS,
1414 #ifdef CONFIG_CGROUP_CPUACCT
1415 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1416 static void cpuacct_update_stats(struct task_struct *tsk,
1417 enum cpuacct_stat_index idx, cputime_t val);
1418 #else
1419 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1420 static inline void cpuacct_update_stats(struct task_struct *tsk,
1421 enum cpuacct_stat_index idx, cputime_t val) {}
1422 #endif
1424 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1426 update_load_add(&rq->load, load);
1429 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1431 update_load_sub(&rq->load, load);
1434 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1435 typedef int (*tg_visitor)(struct task_group *, void *);
1438 * Iterate the full tree, calling @down when first entering a node and @up when
1439 * leaving it for the final time.
1441 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1443 struct task_group *parent, *child;
1444 int ret;
1446 rcu_read_lock();
1447 parent = &root_task_group;
1448 down:
1449 ret = (*down)(parent, data);
1450 if (ret)
1451 goto out_unlock;
1452 list_for_each_entry_rcu(child, &parent->children, siblings) {
1453 parent = child;
1454 goto down;
1457 continue;
1459 ret = (*up)(parent, data);
1460 if (ret)
1461 goto out_unlock;
1463 child = parent;
1464 parent = parent->parent;
1465 if (parent)
1466 goto up;
1467 out_unlock:
1468 rcu_read_unlock();
1470 return ret;
1473 static int tg_nop(struct task_group *tg, void *data)
1475 return 0;
1477 #endif
1479 #ifdef CONFIG_SMP
1480 /* Used instead of source_load when we know the type == 0 */
1481 static unsigned long weighted_cpuload(const int cpu)
1483 return cpu_rq(cpu)->load.weight;
1487 * Return a low guess at the load of a migration-source cpu weighted
1488 * according to the scheduling class and "nice" value.
1490 * We want to under-estimate the load of migration sources, to
1491 * balance conservatively.
1493 static unsigned long source_load(int cpu, int type)
1495 struct rq *rq = cpu_rq(cpu);
1496 unsigned long total = weighted_cpuload(cpu);
1498 if (type == 0 || !sched_feat(LB_BIAS))
1499 return total;
1501 return min(rq->cpu_load[type-1], total);
1505 * Return a high guess at the load of a migration-target cpu weighted
1506 * according to the scheduling class and "nice" value.
1508 static unsigned long target_load(int cpu, int type)
1510 struct rq *rq = cpu_rq(cpu);
1511 unsigned long total = weighted_cpuload(cpu);
1513 if (type == 0 || !sched_feat(LB_BIAS))
1514 return total;
1516 return max(rq->cpu_load[type-1], total);
1519 static unsigned long power_of(int cpu)
1521 return cpu_rq(cpu)->cpu_power;
1524 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1526 static unsigned long cpu_avg_load_per_task(int cpu)
1528 struct rq *rq = cpu_rq(cpu);
1529 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1531 if (nr_running)
1532 rq->avg_load_per_task = rq->load.weight / nr_running;
1533 else
1534 rq->avg_load_per_task = 0;
1536 return rq->avg_load_per_task;
1539 #ifdef CONFIG_FAIR_GROUP_SCHED
1542 * Compute the cpu's hierarchical load factor for each task group.
1543 * This needs to be done in a top-down fashion because the load of a child
1544 * group is a fraction of its parents load.
1546 static int tg_load_down(struct task_group *tg, void *data)
1548 unsigned long load;
1549 long cpu = (long)data;
1551 if (!tg->parent) {
1552 load = cpu_rq(cpu)->load.weight;
1553 } else {
1554 load = tg->parent->cfs_rq[cpu]->h_load;
1555 load *= tg->se[cpu]->load.weight;
1556 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1559 tg->cfs_rq[cpu]->h_load = load;
1561 return 0;
1564 static void update_h_load(long cpu)
1566 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1569 #endif
1571 #ifdef CONFIG_PREEMPT
1573 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1576 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1577 * way at the expense of forcing extra atomic operations in all
1578 * invocations. This assures that the double_lock is acquired using the
1579 * same underlying policy as the spinlock_t on this architecture, which
1580 * reduces latency compared to the unfair variant below. However, it
1581 * also adds more overhead and therefore may reduce throughput.
1583 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1584 __releases(this_rq->lock)
1585 __acquires(busiest->lock)
1586 __acquires(this_rq->lock)
1588 raw_spin_unlock(&this_rq->lock);
1589 double_rq_lock(this_rq, busiest);
1591 return 1;
1594 #else
1596 * Unfair double_lock_balance: Optimizes throughput at the expense of
1597 * latency by eliminating extra atomic operations when the locks are
1598 * already in proper order on entry. This favors lower cpu-ids and will
1599 * grant the double lock to lower cpus over higher ids under contention,
1600 * regardless of entry order into the function.
1602 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1603 __releases(this_rq->lock)
1604 __acquires(busiest->lock)
1605 __acquires(this_rq->lock)
1607 int ret = 0;
1609 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1610 if (busiest < this_rq) {
1611 raw_spin_unlock(&this_rq->lock);
1612 raw_spin_lock(&busiest->lock);
1613 raw_spin_lock_nested(&this_rq->lock,
1614 SINGLE_DEPTH_NESTING);
1615 ret = 1;
1616 } else
1617 raw_spin_lock_nested(&busiest->lock,
1618 SINGLE_DEPTH_NESTING);
1620 return ret;
1623 #endif /* CONFIG_PREEMPT */
1626 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1628 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1630 if (unlikely(!irqs_disabled())) {
1631 /* printk() doesn't work good under rq->lock */
1632 raw_spin_unlock(&this_rq->lock);
1633 BUG_ON(1);
1636 return _double_lock_balance(this_rq, busiest);
1639 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1640 __releases(busiest->lock)
1642 raw_spin_unlock(&busiest->lock);
1643 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1647 * double_rq_lock - safely lock two runqueues
1649 * Note this does not disable interrupts like task_rq_lock,
1650 * you need to do so manually before calling.
1652 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1653 __acquires(rq1->lock)
1654 __acquires(rq2->lock)
1656 BUG_ON(!irqs_disabled());
1657 if (rq1 == rq2) {
1658 raw_spin_lock(&rq1->lock);
1659 __acquire(rq2->lock); /* Fake it out ;) */
1660 } else {
1661 if (rq1 < rq2) {
1662 raw_spin_lock(&rq1->lock);
1663 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
1664 } else {
1665 raw_spin_lock(&rq2->lock);
1666 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
1672 * double_rq_unlock - safely unlock two runqueues
1674 * Note this does not restore interrupts like task_rq_unlock,
1675 * you need to do so manually after calling.
1677 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1678 __releases(rq1->lock)
1679 __releases(rq2->lock)
1681 raw_spin_unlock(&rq1->lock);
1682 if (rq1 != rq2)
1683 raw_spin_unlock(&rq2->lock);
1684 else
1685 __release(rq2->lock);
1688 #endif
1690 static void calc_load_account_idle(struct rq *this_rq);
1691 static void update_sysctl(void);
1692 static int get_update_sysctl_factor(void);
1693 static void update_cpu_load(struct rq *this_rq);
1695 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1697 set_task_rq(p, cpu);
1698 #ifdef CONFIG_SMP
1700 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1701 * successfuly executed on another CPU. We must ensure that updates of
1702 * per-task data have been completed by this moment.
1704 smp_wmb();
1705 task_thread_info(p)->cpu = cpu;
1706 #endif
1709 static const struct sched_class rt_sched_class;
1711 #define sched_class_highest (&stop_sched_class)
1712 #define for_each_class(class) \
1713 for (class = sched_class_highest; class; class = class->next)
1715 #include "sched_stats.h"
1717 static void inc_nr_running(struct rq *rq)
1719 rq->nr_running++;
1722 static void dec_nr_running(struct rq *rq)
1724 rq->nr_running--;
1727 static void set_load_weight(struct task_struct *p)
1730 * SCHED_IDLE tasks get minimal weight:
1732 if (p->policy == SCHED_IDLE) {
1733 p->se.load.weight = WEIGHT_IDLEPRIO;
1734 p->se.load.inv_weight = WMULT_IDLEPRIO;
1735 return;
1738 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1739 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1742 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
1744 update_rq_clock(rq);
1745 sched_info_queued(p);
1746 p->sched_class->enqueue_task(rq, p, flags);
1747 p->se.on_rq = 1;
1750 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
1752 update_rq_clock(rq);
1753 sched_info_dequeued(p);
1754 p->sched_class->dequeue_task(rq, p, flags);
1755 p->se.on_rq = 0;
1759 * activate_task - move a task to the runqueue.
1761 static void activate_task(struct rq *rq, struct task_struct *p, int flags)
1763 if (task_contributes_to_load(p))
1764 rq->nr_uninterruptible--;
1766 enqueue_task(rq, p, flags);
1767 inc_nr_running(rq);
1771 * deactivate_task - remove a task from the runqueue.
1773 static void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1775 if (task_contributes_to_load(p))
1776 rq->nr_uninterruptible++;
1778 dequeue_task(rq, p, flags);
1779 dec_nr_running(rq);
1782 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1785 * There are no locks covering percpu hardirq/softirq time.
1786 * They are only modified in account_system_vtime, on corresponding CPU
1787 * with interrupts disabled. So, writes are safe.
1788 * They are read and saved off onto struct rq in update_rq_clock().
1789 * This may result in other CPU reading this CPU's irq time and can
1790 * race with irq/account_system_vtime on this CPU. We would either get old
1791 * or new value with a side effect of accounting a slice of irq time to wrong
1792 * task when irq is in progress while we read rq->clock. That is a worthy
1793 * compromise in place of having locks on each irq in account_system_time.
1795 static DEFINE_PER_CPU(u64, cpu_hardirq_time);
1796 static DEFINE_PER_CPU(u64, cpu_softirq_time);
1798 static DEFINE_PER_CPU(u64, irq_start_time);
1799 static int sched_clock_irqtime;
1801 void enable_sched_clock_irqtime(void)
1803 sched_clock_irqtime = 1;
1806 void disable_sched_clock_irqtime(void)
1808 sched_clock_irqtime = 0;
1811 #ifndef CONFIG_64BIT
1812 static DEFINE_PER_CPU(seqcount_t, irq_time_seq);
1814 static inline void irq_time_write_begin(void)
1816 __this_cpu_inc(irq_time_seq.sequence);
1817 smp_wmb();
1820 static inline void irq_time_write_end(void)
1822 smp_wmb();
1823 __this_cpu_inc(irq_time_seq.sequence);
1826 static inline u64 irq_time_read(int cpu)
1828 u64 irq_time;
1829 unsigned seq;
1831 do {
1832 seq = read_seqcount_begin(&per_cpu(irq_time_seq, cpu));
1833 irq_time = per_cpu(cpu_softirq_time, cpu) +
1834 per_cpu(cpu_hardirq_time, cpu);
1835 } while (read_seqcount_retry(&per_cpu(irq_time_seq, cpu), seq));
1837 return irq_time;
1839 #else /* CONFIG_64BIT */
1840 static inline void irq_time_write_begin(void)
1844 static inline void irq_time_write_end(void)
1848 static inline u64 irq_time_read(int cpu)
1850 return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu);
1852 #endif /* CONFIG_64BIT */
1855 * Called before incrementing preempt_count on {soft,}irq_enter
1856 * and before decrementing preempt_count on {soft,}irq_exit.
1858 void account_system_vtime(struct task_struct *curr)
1860 unsigned long flags;
1861 s64 delta;
1862 int cpu;
1864 if (!sched_clock_irqtime)
1865 return;
1867 local_irq_save(flags);
1869 cpu = smp_processor_id();
1870 delta = sched_clock_cpu(cpu) - __this_cpu_read(irq_start_time);
1871 __this_cpu_add(irq_start_time, delta);
1873 irq_time_write_begin();
1875 * We do not account for softirq time from ksoftirqd here.
1876 * We want to continue accounting softirq time to ksoftirqd thread
1877 * in that case, so as not to confuse scheduler with a special task
1878 * that do not consume any time, but still wants to run.
1880 if (hardirq_count())
1881 __this_cpu_add(cpu_hardirq_time, delta);
1882 else if (in_serving_softirq() && !(curr->flags & PF_KSOFTIRQD))
1883 __this_cpu_add(cpu_softirq_time, delta);
1885 irq_time_write_end();
1886 local_irq_restore(flags);
1888 EXPORT_SYMBOL_GPL(account_system_vtime);
1890 static void update_rq_clock_task(struct rq *rq, s64 delta)
1892 s64 irq_delta;
1894 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
1897 * Since irq_time is only updated on {soft,}irq_exit, we might run into
1898 * this case when a previous update_rq_clock() happened inside a
1899 * {soft,}irq region.
1901 * When this happens, we stop ->clock_task and only update the
1902 * prev_irq_time stamp to account for the part that fit, so that a next
1903 * update will consume the rest. This ensures ->clock_task is
1904 * monotonic.
1906 * It does however cause some slight miss-attribution of {soft,}irq
1907 * time, a more accurate solution would be to update the irq_time using
1908 * the current rq->clock timestamp, except that would require using
1909 * atomic ops.
1911 if (irq_delta > delta)
1912 irq_delta = delta;
1914 rq->prev_irq_time += irq_delta;
1915 delta -= irq_delta;
1916 rq->clock_task += delta;
1918 if (irq_delta && sched_feat(NONIRQ_POWER))
1919 sched_rt_avg_update(rq, irq_delta);
1922 #else /* CONFIG_IRQ_TIME_ACCOUNTING */
1924 static void update_rq_clock_task(struct rq *rq, s64 delta)
1926 rq->clock_task += delta;
1929 #endif /* CONFIG_IRQ_TIME_ACCOUNTING */
1931 #include "sched_idletask.c"
1932 #include "sched_fair.c"
1933 #include "sched_rt.c"
1934 #include "sched_autogroup.c"
1935 #include "sched_stoptask.c"
1936 #ifdef CONFIG_SCHED_DEBUG
1937 # include "sched_debug.c"
1938 #endif
1940 void sched_set_stop_task(int cpu, struct task_struct *stop)
1942 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1943 struct task_struct *old_stop = cpu_rq(cpu)->stop;
1945 if (stop) {
1947 * Make it appear like a SCHED_FIFO task, its something
1948 * userspace knows about and won't get confused about.
1950 * Also, it will make PI more or less work without too
1951 * much confusion -- but then, stop work should not
1952 * rely on PI working anyway.
1954 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
1956 stop->sched_class = &stop_sched_class;
1959 cpu_rq(cpu)->stop = stop;
1961 if (old_stop) {
1963 * Reset it back to a normal scheduling class so that
1964 * it can die in pieces.
1966 old_stop->sched_class = &rt_sched_class;
1971 * __normal_prio - return the priority that is based on the static prio
1973 static inline int __normal_prio(struct task_struct *p)
1975 return p->static_prio;
1979 * Calculate the expected normal priority: i.e. priority
1980 * without taking RT-inheritance into account. Might be
1981 * boosted by interactivity modifiers. Changes upon fork,
1982 * setprio syscalls, and whenever the interactivity
1983 * estimator recalculates.
1985 static inline int normal_prio(struct task_struct *p)
1987 int prio;
1989 if (task_has_rt_policy(p))
1990 prio = MAX_RT_PRIO-1 - p->rt_priority;
1991 else
1992 prio = __normal_prio(p);
1993 return prio;
1997 * Calculate the current priority, i.e. the priority
1998 * taken into account by the scheduler. This value might
1999 * be boosted by RT tasks, or might be boosted by
2000 * interactivity modifiers. Will be RT if the task got
2001 * RT-boosted. If not then it returns p->normal_prio.
2003 static int effective_prio(struct task_struct *p)
2005 p->normal_prio = normal_prio(p);
2007 * If we are RT tasks or we were boosted to RT priority,
2008 * keep the priority unchanged. Otherwise, update priority
2009 * to the normal priority:
2011 if (!rt_prio(p->prio))
2012 return p->normal_prio;
2013 return p->prio;
2017 * task_curr - is this task currently executing on a CPU?
2018 * @p: the task in question.
2020 inline int task_curr(const struct task_struct *p)
2022 return cpu_curr(task_cpu(p)) == p;
2025 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2026 const struct sched_class *prev_class,
2027 int oldprio, int running)
2029 if (prev_class != p->sched_class) {
2030 if (prev_class->switched_from)
2031 prev_class->switched_from(rq, p, running);
2032 p->sched_class->switched_to(rq, p, running);
2033 } else
2034 p->sched_class->prio_changed(rq, p, oldprio, running);
2037 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
2039 const struct sched_class *class;
2041 if (p->sched_class == rq->curr->sched_class) {
2042 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
2043 } else {
2044 for_each_class(class) {
2045 if (class == rq->curr->sched_class)
2046 break;
2047 if (class == p->sched_class) {
2048 resched_task(rq->curr);
2049 break;
2055 * A queue event has occurred, and we're going to schedule. In
2056 * this case, we can save a useless back to back clock update.
2058 if (rq->curr->se.on_rq && test_tsk_need_resched(rq->curr))
2059 rq->skip_clock_update = 1;
2062 #ifdef CONFIG_SMP
2064 * Is this task likely cache-hot:
2066 static int
2067 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2069 s64 delta;
2071 if (p->sched_class != &fair_sched_class)
2072 return 0;
2074 if (unlikely(p->policy == SCHED_IDLE))
2075 return 0;
2078 * Buddy candidates are cache hot:
2080 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2081 (&p->se == cfs_rq_of(&p->se)->next ||
2082 &p->se == cfs_rq_of(&p->se)->last))
2083 return 1;
2085 if (sysctl_sched_migration_cost == -1)
2086 return 1;
2087 if (sysctl_sched_migration_cost == 0)
2088 return 0;
2090 delta = now - p->se.exec_start;
2092 return delta < (s64)sysctl_sched_migration_cost;
2095 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2097 #ifdef CONFIG_SCHED_DEBUG
2099 * We should never call set_task_cpu() on a blocked task,
2100 * ttwu() will sort out the placement.
2102 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2103 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2104 #endif
2106 trace_sched_migrate_task(p, new_cpu);
2108 if (task_cpu(p) != new_cpu) {
2109 p->se.nr_migrations++;
2110 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0);
2113 __set_task_cpu(p, new_cpu);
2116 struct migration_arg {
2117 struct task_struct *task;
2118 int dest_cpu;
2121 static int migration_cpu_stop(void *data);
2124 * The task's runqueue lock must be held.
2125 * Returns true if you have to wait for migration thread.
2127 static bool migrate_task(struct task_struct *p, struct rq *rq)
2130 * If the task is not on a runqueue (and not running), then
2131 * the next wake-up will properly place the task.
2133 return p->se.on_rq || task_running(rq, p);
2137 * wait_task_inactive - wait for a thread to unschedule.
2139 * If @match_state is nonzero, it's the @p->state value just checked and
2140 * not expected to change. If it changes, i.e. @p might have woken up,
2141 * then return zero. When we succeed in waiting for @p to be off its CPU,
2142 * we return a positive number (its total switch count). If a second call
2143 * a short while later returns the same number, the caller can be sure that
2144 * @p has remained unscheduled the whole time.
2146 * The caller must ensure that the task *will* unschedule sometime soon,
2147 * else this function might spin for a *long* time. This function can't
2148 * be called with interrupts off, or it may introduce deadlock with
2149 * smp_call_function() if an IPI is sent by the same process we are
2150 * waiting to become inactive.
2152 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2154 unsigned long flags;
2155 int running, on_rq;
2156 unsigned long ncsw;
2157 struct rq *rq;
2159 for (;;) {
2161 * We do the initial early heuristics without holding
2162 * any task-queue locks at all. We'll only try to get
2163 * the runqueue lock when things look like they will
2164 * work out!
2166 rq = task_rq(p);
2169 * If the task is actively running on another CPU
2170 * still, just relax and busy-wait without holding
2171 * any locks.
2173 * NOTE! Since we don't hold any locks, it's not
2174 * even sure that "rq" stays as the right runqueue!
2175 * But we don't care, since "task_running()" will
2176 * return false if the runqueue has changed and p
2177 * is actually now running somewhere else!
2179 while (task_running(rq, p)) {
2180 if (match_state && unlikely(p->state != match_state))
2181 return 0;
2182 cpu_relax();
2186 * Ok, time to look more closely! We need the rq
2187 * lock now, to be *sure*. If we're wrong, we'll
2188 * just go back and repeat.
2190 rq = task_rq_lock(p, &flags);
2191 trace_sched_wait_task(p);
2192 running = task_running(rq, p);
2193 on_rq = p->se.on_rq;
2194 ncsw = 0;
2195 if (!match_state || p->state == match_state)
2196 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2197 task_rq_unlock(rq, &flags);
2200 * If it changed from the expected state, bail out now.
2202 if (unlikely(!ncsw))
2203 break;
2206 * Was it really running after all now that we
2207 * checked with the proper locks actually held?
2209 * Oops. Go back and try again..
2211 if (unlikely(running)) {
2212 cpu_relax();
2213 continue;
2217 * It's not enough that it's not actively running,
2218 * it must be off the runqueue _entirely_, and not
2219 * preempted!
2221 * So if it was still runnable (but just not actively
2222 * running right now), it's preempted, and we should
2223 * yield - it could be a while.
2225 if (unlikely(on_rq)) {
2226 schedule_timeout_uninterruptible(1);
2227 continue;
2231 * Ahh, all good. It wasn't running, and it wasn't
2232 * runnable, which means that it will never become
2233 * running in the future either. We're all done!
2235 break;
2238 return ncsw;
2241 /***
2242 * kick_process - kick a running thread to enter/exit the kernel
2243 * @p: the to-be-kicked thread
2245 * Cause a process which is running on another CPU to enter
2246 * kernel-mode, without any delay. (to get signals handled.)
2248 * NOTE: this function doesnt have to take the runqueue lock,
2249 * because all it wants to ensure is that the remote task enters
2250 * the kernel. If the IPI races and the task has been migrated
2251 * to another CPU then no harm is done and the purpose has been
2252 * achieved as well.
2254 void kick_process(struct task_struct *p)
2256 int cpu;
2258 preempt_disable();
2259 cpu = task_cpu(p);
2260 if ((cpu != smp_processor_id()) && task_curr(p))
2261 smp_send_reschedule(cpu);
2262 preempt_enable();
2264 EXPORT_SYMBOL_GPL(kick_process);
2265 #endif /* CONFIG_SMP */
2268 * task_oncpu_function_call - call a function on the cpu on which a task runs
2269 * @p: the task to evaluate
2270 * @func: the function to be called
2271 * @info: the function call argument
2273 * Calls the function @func when the task is currently running. This might
2274 * be on the current CPU, which just calls the function directly
2276 void task_oncpu_function_call(struct task_struct *p,
2277 void (*func) (void *info), void *info)
2279 int cpu;
2281 preempt_disable();
2282 cpu = task_cpu(p);
2283 if (task_curr(p))
2284 smp_call_function_single(cpu, func, info, 1);
2285 preempt_enable();
2288 #ifdef CONFIG_SMP
2290 * ->cpus_allowed is protected by either TASK_WAKING or rq->lock held.
2292 static int select_fallback_rq(int cpu, struct task_struct *p)
2294 int dest_cpu;
2295 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2297 /* Look for allowed, online CPU in same node. */
2298 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2299 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2300 return dest_cpu;
2302 /* Any allowed, online CPU? */
2303 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2304 if (dest_cpu < nr_cpu_ids)
2305 return dest_cpu;
2307 /* No more Mr. Nice Guy. */
2308 dest_cpu = cpuset_cpus_allowed_fallback(p);
2310 * Don't tell them about moving exiting tasks or
2311 * kernel threads (both mm NULL), since they never
2312 * leave kernel.
2314 if (p->mm && printk_ratelimit()) {
2315 printk(KERN_INFO "process %d (%s) no longer affine to cpu%d\n",
2316 task_pid_nr(p), p->comm, cpu);
2319 return dest_cpu;
2323 * The caller (fork, wakeup) owns TASK_WAKING, ->cpus_allowed is stable.
2325 static inline
2326 int select_task_rq(struct rq *rq, struct task_struct *p, int sd_flags, int wake_flags)
2328 int cpu = p->sched_class->select_task_rq(rq, p, sd_flags, wake_flags);
2331 * In order not to call set_task_cpu() on a blocking task we need
2332 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2333 * cpu.
2335 * Since this is common to all placement strategies, this lives here.
2337 * [ this allows ->select_task() to simply return task_cpu(p) and
2338 * not worry about this generic constraint ]
2340 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2341 !cpu_online(cpu)))
2342 cpu = select_fallback_rq(task_cpu(p), p);
2344 return cpu;
2347 static void update_avg(u64 *avg, u64 sample)
2349 s64 diff = sample - *avg;
2350 *avg += diff >> 3;
2352 #endif
2354 static inline void ttwu_activate(struct task_struct *p, struct rq *rq,
2355 bool is_sync, bool is_migrate, bool is_local,
2356 unsigned long en_flags)
2358 schedstat_inc(p, se.statistics.nr_wakeups);
2359 if (is_sync)
2360 schedstat_inc(p, se.statistics.nr_wakeups_sync);
2361 if (is_migrate)
2362 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
2363 if (is_local)
2364 schedstat_inc(p, se.statistics.nr_wakeups_local);
2365 else
2366 schedstat_inc(p, se.statistics.nr_wakeups_remote);
2368 activate_task(rq, p, en_flags);
2371 static inline void ttwu_post_activation(struct task_struct *p, struct rq *rq,
2372 int wake_flags, bool success)
2374 trace_sched_wakeup(p, success);
2375 check_preempt_curr(rq, p, wake_flags);
2377 p->state = TASK_RUNNING;
2378 #ifdef CONFIG_SMP
2379 if (p->sched_class->task_woken)
2380 p->sched_class->task_woken(rq, p);
2382 if (unlikely(rq->idle_stamp)) {
2383 u64 delta = rq->clock - rq->idle_stamp;
2384 u64 max = 2*sysctl_sched_migration_cost;
2386 if (delta > max)
2387 rq->avg_idle = max;
2388 else
2389 update_avg(&rq->avg_idle, delta);
2390 rq->idle_stamp = 0;
2392 #endif
2393 /* if a worker is waking up, notify workqueue */
2394 if ((p->flags & PF_WQ_WORKER) && success)
2395 wq_worker_waking_up(p, cpu_of(rq));
2399 * try_to_wake_up - wake up a thread
2400 * @p: the thread to be awakened
2401 * @state: the mask of task states that can be woken
2402 * @wake_flags: wake modifier flags (WF_*)
2404 * Put it on the run-queue if it's not already there. The "current"
2405 * thread is always on the run-queue (except when the actual
2406 * re-schedule is in progress), and as such you're allowed to do
2407 * the simpler "current->state = TASK_RUNNING" to mark yourself
2408 * runnable without the overhead of this.
2410 * Returns %true if @p was woken up, %false if it was already running
2411 * or @state didn't match @p's state.
2413 static int try_to_wake_up(struct task_struct *p, unsigned int state,
2414 int wake_flags)
2416 int cpu, orig_cpu, this_cpu, success = 0;
2417 unsigned long flags;
2418 unsigned long en_flags = ENQUEUE_WAKEUP;
2419 struct rq *rq;
2421 this_cpu = get_cpu();
2423 smp_wmb();
2424 rq = task_rq_lock(p, &flags);
2425 if (!(p->state & state))
2426 goto out;
2428 if (p->se.on_rq)
2429 goto out_running;
2431 cpu = task_cpu(p);
2432 orig_cpu = cpu;
2434 #ifdef CONFIG_SMP
2435 if (unlikely(task_running(rq, p)))
2436 goto out_activate;
2439 * In order to handle concurrent wakeups and release the rq->lock
2440 * we put the task in TASK_WAKING state.
2442 * First fix up the nr_uninterruptible count:
2444 if (task_contributes_to_load(p)) {
2445 if (likely(cpu_online(orig_cpu)))
2446 rq->nr_uninterruptible--;
2447 else
2448 this_rq()->nr_uninterruptible--;
2450 p->state = TASK_WAKING;
2452 if (p->sched_class->task_waking) {
2453 p->sched_class->task_waking(rq, p);
2454 en_flags |= ENQUEUE_WAKING;
2457 cpu = select_task_rq(rq, p, SD_BALANCE_WAKE, wake_flags);
2458 if (cpu != orig_cpu)
2459 set_task_cpu(p, cpu);
2460 __task_rq_unlock(rq);
2462 rq = cpu_rq(cpu);
2463 raw_spin_lock(&rq->lock);
2466 * We migrated the task without holding either rq->lock, however
2467 * since the task is not on the task list itself, nobody else
2468 * will try and migrate the task, hence the rq should match the
2469 * cpu we just moved it to.
2471 WARN_ON(task_cpu(p) != cpu);
2472 WARN_ON(p->state != TASK_WAKING);
2474 #ifdef CONFIG_SCHEDSTATS
2475 schedstat_inc(rq, ttwu_count);
2476 if (cpu == this_cpu)
2477 schedstat_inc(rq, ttwu_local);
2478 else {
2479 struct sched_domain *sd;
2480 for_each_domain(this_cpu, sd) {
2481 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2482 schedstat_inc(sd, ttwu_wake_remote);
2483 break;
2487 #endif /* CONFIG_SCHEDSTATS */
2489 out_activate:
2490 #endif /* CONFIG_SMP */
2491 ttwu_activate(p, rq, wake_flags & WF_SYNC, orig_cpu != cpu,
2492 cpu == this_cpu, en_flags);
2493 success = 1;
2494 out_running:
2495 ttwu_post_activation(p, rq, wake_flags, success);
2496 out:
2497 task_rq_unlock(rq, &flags);
2498 put_cpu();
2500 return success;
2504 * try_to_wake_up_local - try to wake up a local task with rq lock held
2505 * @p: the thread to be awakened
2507 * Put @p on the run-queue if it's not already there. The caller must
2508 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2509 * the current task. this_rq() stays locked over invocation.
2511 static void try_to_wake_up_local(struct task_struct *p)
2513 struct rq *rq = task_rq(p);
2514 bool success = false;
2516 BUG_ON(rq != this_rq());
2517 BUG_ON(p == current);
2518 lockdep_assert_held(&rq->lock);
2520 if (!(p->state & TASK_NORMAL))
2521 return;
2523 if (!p->se.on_rq) {
2524 if (likely(!task_running(rq, p))) {
2525 schedstat_inc(rq, ttwu_count);
2526 schedstat_inc(rq, ttwu_local);
2528 ttwu_activate(p, rq, false, false, true, ENQUEUE_WAKEUP);
2529 success = true;
2531 ttwu_post_activation(p, rq, 0, success);
2535 * wake_up_process - Wake up a specific process
2536 * @p: The process to be woken up.
2538 * Attempt to wake up the nominated process and move it to the set of runnable
2539 * processes. Returns 1 if the process was woken up, 0 if it was already
2540 * running.
2542 * It may be assumed that this function implies a write memory barrier before
2543 * changing the task state if and only if any tasks are woken up.
2545 int wake_up_process(struct task_struct *p)
2547 return try_to_wake_up(p, TASK_ALL, 0);
2549 EXPORT_SYMBOL(wake_up_process);
2551 int wake_up_state(struct task_struct *p, unsigned int state)
2553 return try_to_wake_up(p, state, 0);
2557 * Perform scheduler related setup for a newly forked process p.
2558 * p is forked by current.
2560 * __sched_fork() is basic setup used by init_idle() too:
2562 static void __sched_fork(struct task_struct *p)
2564 p->se.exec_start = 0;
2565 p->se.sum_exec_runtime = 0;
2566 p->se.prev_sum_exec_runtime = 0;
2567 p->se.nr_migrations = 0;
2569 #ifdef CONFIG_SCHEDSTATS
2570 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2571 #endif
2573 INIT_LIST_HEAD(&p->rt.run_list);
2574 p->se.on_rq = 0;
2575 INIT_LIST_HEAD(&p->se.group_node);
2577 #ifdef CONFIG_PREEMPT_NOTIFIERS
2578 INIT_HLIST_HEAD(&p->preempt_notifiers);
2579 #endif
2583 * fork()/clone()-time setup:
2585 void sched_fork(struct task_struct *p, int clone_flags)
2587 int cpu = get_cpu();
2589 __sched_fork(p);
2591 * We mark the process as running here. This guarantees that
2592 * nobody will actually run it, and a signal or other external
2593 * event cannot wake it up and insert it on the runqueue either.
2595 p->state = TASK_RUNNING;
2598 * Revert to default priority/policy on fork if requested.
2600 if (unlikely(p->sched_reset_on_fork)) {
2601 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2602 p->policy = SCHED_NORMAL;
2603 p->normal_prio = p->static_prio;
2606 if (PRIO_TO_NICE(p->static_prio) < 0) {
2607 p->static_prio = NICE_TO_PRIO(0);
2608 p->normal_prio = p->static_prio;
2609 set_load_weight(p);
2613 * We don't need the reset flag anymore after the fork. It has
2614 * fulfilled its duty:
2616 p->sched_reset_on_fork = 0;
2620 * Make sure we do not leak PI boosting priority to the child.
2622 p->prio = current->normal_prio;
2624 if (!rt_prio(p->prio))
2625 p->sched_class = &fair_sched_class;
2627 if (p->sched_class->task_fork)
2628 p->sched_class->task_fork(p);
2631 * The child is not yet in the pid-hash so no cgroup attach races,
2632 * and the cgroup is pinned to this child due to cgroup_fork()
2633 * is ran before sched_fork().
2635 * Silence PROVE_RCU.
2637 rcu_read_lock();
2638 set_task_cpu(p, cpu);
2639 rcu_read_unlock();
2641 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2642 if (likely(sched_info_on()))
2643 memset(&p->sched_info, 0, sizeof(p->sched_info));
2644 #endif
2645 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2646 p->oncpu = 0;
2647 #endif
2648 #ifdef CONFIG_PREEMPT
2649 /* Want to start with kernel preemption disabled. */
2650 task_thread_info(p)->preempt_count = 1;
2651 #endif
2652 #ifdef CONFIG_SMP
2653 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2654 #endif
2656 put_cpu();
2660 * wake_up_new_task - wake up a newly created task for the first time.
2662 * This function will do some initial scheduler statistics housekeeping
2663 * that must be done for every newly created context, then puts the task
2664 * on the runqueue and wakes it.
2666 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2668 unsigned long flags;
2669 struct rq *rq;
2670 int cpu __maybe_unused = get_cpu();
2672 #ifdef CONFIG_SMP
2673 rq = task_rq_lock(p, &flags);
2674 p->state = TASK_WAKING;
2677 * Fork balancing, do it here and not earlier because:
2678 * - cpus_allowed can change in the fork path
2679 * - any previously selected cpu might disappear through hotplug
2681 * We set TASK_WAKING so that select_task_rq() can drop rq->lock
2682 * without people poking at ->cpus_allowed.
2684 cpu = select_task_rq(rq, p, SD_BALANCE_FORK, 0);
2685 set_task_cpu(p, cpu);
2687 p->state = TASK_RUNNING;
2688 task_rq_unlock(rq, &flags);
2689 #endif
2691 rq = task_rq_lock(p, &flags);
2692 activate_task(rq, p, 0);
2693 trace_sched_wakeup_new(p, 1);
2694 check_preempt_curr(rq, p, WF_FORK);
2695 #ifdef CONFIG_SMP
2696 if (p->sched_class->task_woken)
2697 p->sched_class->task_woken(rq, p);
2698 #endif
2699 task_rq_unlock(rq, &flags);
2700 put_cpu();
2703 #ifdef CONFIG_PREEMPT_NOTIFIERS
2706 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2707 * @notifier: notifier struct to register
2709 void preempt_notifier_register(struct preempt_notifier *notifier)
2711 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2713 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2716 * preempt_notifier_unregister - no longer interested in preemption notifications
2717 * @notifier: notifier struct to unregister
2719 * This is safe to call from within a preemption notifier.
2721 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2723 hlist_del(&notifier->link);
2725 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2727 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2729 struct preempt_notifier *notifier;
2730 struct hlist_node *node;
2732 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2733 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2736 static void
2737 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2738 struct task_struct *next)
2740 struct preempt_notifier *notifier;
2741 struct hlist_node *node;
2743 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2744 notifier->ops->sched_out(notifier, next);
2747 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2749 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2753 static void
2754 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2755 struct task_struct *next)
2759 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2762 * prepare_task_switch - prepare to switch tasks
2763 * @rq: the runqueue preparing to switch
2764 * @prev: the current task that is being switched out
2765 * @next: the task we are going to switch to.
2767 * This is called with the rq lock held and interrupts off. It must
2768 * be paired with a subsequent finish_task_switch after the context
2769 * switch.
2771 * prepare_task_switch sets up locking and calls architecture specific
2772 * hooks.
2774 static inline void
2775 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2776 struct task_struct *next)
2778 fire_sched_out_preempt_notifiers(prev, next);
2779 prepare_lock_switch(rq, next);
2780 prepare_arch_switch(next);
2784 * finish_task_switch - clean up after a task-switch
2785 * @rq: runqueue associated with task-switch
2786 * @prev: the thread we just switched away from.
2788 * finish_task_switch must be called after the context switch, paired
2789 * with a prepare_task_switch call before the context switch.
2790 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2791 * and do any other architecture-specific cleanup actions.
2793 * Note that we may have delayed dropping an mm in context_switch(). If
2794 * so, we finish that here outside of the runqueue lock. (Doing it
2795 * with the lock held can cause deadlocks; see schedule() for
2796 * details.)
2798 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2799 __releases(rq->lock)
2801 struct mm_struct *mm = rq->prev_mm;
2802 long prev_state;
2804 rq->prev_mm = NULL;
2807 * A task struct has one reference for the use as "current".
2808 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2809 * schedule one last time. The schedule call will never return, and
2810 * the scheduled task must drop that reference.
2811 * The test for TASK_DEAD must occur while the runqueue locks are
2812 * still held, otherwise prev could be scheduled on another cpu, die
2813 * there before we look at prev->state, and then the reference would
2814 * be dropped twice.
2815 * Manfred Spraul <manfred@colorfullife.com>
2817 prev_state = prev->state;
2818 finish_arch_switch(prev);
2819 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2820 local_irq_disable();
2821 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2822 perf_event_task_sched_in(current);
2823 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2824 local_irq_enable();
2825 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2826 finish_lock_switch(rq, prev);
2828 fire_sched_in_preempt_notifiers(current);
2829 if (mm)
2830 mmdrop(mm);
2831 if (unlikely(prev_state == TASK_DEAD)) {
2833 * Remove function-return probe instances associated with this
2834 * task and put them back on the free list.
2836 kprobe_flush_task(prev);
2837 put_task_struct(prev);
2841 #ifdef CONFIG_SMP
2843 /* assumes rq->lock is held */
2844 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2846 if (prev->sched_class->pre_schedule)
2847 prev->sched_class->pre_schedule(rq, prev);
2850 /* rq->lock is NOT held, but preemption is disabled */
2851 static inline void post_schedule(struct rq *rq)
2853 if (rq->post_schedule) {
2854 unsigned long flags;
2856 raw_spin_lock_irqsave(&rq->lock, flags);
2857 if (rq->curr->sched_class->post_schedule)
2858 rq->curr->sched_class->post_schedule(rq);
2859 raw_spin_unlock_irqrestore(&rq->lock, flags);
2861 rq->post_schedule = 0;
2865 #else
2867 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2871 static inline void post_schedule(struct rq *rq)
2875 #endif
2878 * schedule_tail - first thing a freshly forked thread must call.
2879 * @prev: the thread we just switched away from.
2881 asmlinkage void schedule_tail(struct task_struct *prev)
2882 __releases(rq->lock)
2884 struct rq *rq = this_rq();
2886 finish_task_switch(rq, prev);
2889 * FIXME: do we need to worry about rq being invalidated by the
2890 * task_switch?
2892 post_schedule(rq);
2894 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2895 /* In this case, finish_task_switch does not reenable preemption */
2896 preempt_enable();
2897 #endif
2898 if (current->set_child_tid)
2899 put_user(task_pid_vnr(current), current->set_child_tid);
2903 * context_switch - switch to the new MM and the new
2904 * thread's register state.
2906 static inline void
2907 context_switch(struct rq *rq, struct task_struct *prev,
2908 struct task_struct *next)
2910 struct mm_struct *mm, *oldmm;
2912 prepare_task_switch(rq, prev, next);
2913 trace_sched_switch(prev, next);
2914 mm = next->mm;
2915 oldmm = prev->active_mm;
2917 * For paravirt, this is coupled with an exit in switch_to to
2918 * combine the page table reload and the switch backend into
2919 * one hypercall.
2921 arch_start_context_switch(prev);
2923 if (!mm) {
2924 next->active_mm = oldmm;
2925 atomic_inc(&oldmm->mm_count);
2926 enter_lazy_tlb(oldmm, next);
2927 } else
2928 switch_mm(oldmm, mm, next);
2930 if (!prev->mm) {
2931 prev->active_mm = NULL;
2932 rq->prev_mm = oldmm;
2935 * Since the runqueue lock will be released by the next
2936 * task (which is an invalid locking op but in the case
2937 * of the scheduler it's an obvious special-case), so we
2938 * do an early lockdep release here:
2940 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2941 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2942 #endif
2944 /* Here we just switch the register state and the stack. */
2945 switch_to(prev, next, prev);
2947 barrier();
2949 * this_rq must be evaluated again because prev may have moved
2950 * CPUs since it called schedule(), thus the 'rq' on its stack
2951 * frame will be invalid.
2953 finish_task_switch(this_rq(), prev);
2957 * nr_running, nr_uninterruptible and nr_context_switches:
2959 * externally visible scheduler statistics: current number of runnable
2960 * threads, current number of uninterruptible-sleeping threads, total
2961 * number of context switches performed since bootup.
2963 unsigned long nr_running(void)
2965 unsigned long i, sum = 0;
2967 for_each_online_cpu(i)
2968 sum += cpu_rq(i)->nr_running;
2970 return sum;
2973 unsigned long nr_uninterruptible(void)
2975 unsigned long i, sum = 0;
2977 for_each_possible_cpu(i)
2978 sum += cpu_rq(i)->nr_uninterruptible;
2981 * Since we read the counters lockless, it might be slightly
2982 * inaccurate. Do not allow it to go below zero though:
2984 if (unlikely((long)sum < 0))
2985 sum = 0;
2987 return sum;
2990 unsigned long long nr_context_switches(void)
2992 int i;
2993 unsigned long long sum = 0;
2995 for_each_possible_cpu(i)
2996 sum += cpu_rq(i)->nr_switches;
2998 return sum;
3001 unsigned long nr_iowait(void)
3003 unsigned long i, sum = 0;
3005 for_each_possible_cpu(i)
3006 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3008 return sum;
3011 unsigned long nr_iowait_cpu(int cpu)
3013 struct rq *this = cpu_rq(cpu);
3014 return atomic_read(&this->nr_iowait);
3017 unsigned long this_cpu_load(void)
3019 struct rq *this = this_rq();
3020 return this->cpu_load[0];
3024 /* Variables and functions for calc_load */
3025 static atomic_long_t calc_load_tasks;
3026 static unsigned long calc_load_update;
3027 unsigned long avenrun[3];
3028 EXPORT_SYMBOL(avenrun);
3030 static long calc_load_fold_active(struct rq *this_rq)
3032 long nr_active, delta = 0;
3034 nr_active = this_rq->nr_running;
3035 nr_active += (long) this_rq->nr_uninterruptible;
3037 if (nr_active != this_rq->calc_load_active) {
3038 delta = nr_active - this_rq->calc_load_active;
3039 this_rq->calc_load_active = nr_active;
3042 return delta;
3045 static unsigned long
3046 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3048 load *= exp;
3049 load += active * (FIXED_1 - exp);
3050 load += 1UL << (FSHIFT - 1);
3051 return load >> FSHIFT;
3054 #ifdef CONFIG_NO_HZ
3056 * For NO_HZ we delay the active fold to the next LOAD_FREQ update.
3058 * When making the ILB scale, we should try to pull this in as well.
3060 static atomic_long_t calc_load_tasks_idle;
3062 static void calc_load_account_idle(struct rq *this_rq)
3064 long delta;
3066 delta = calc_load_fold_active(this_rq);
3067 if (delta)
3068 atomic_long_add(delta, &calc_load_tasks_idle);
3071 static long calc_load_fold_idle(void)
3073 long delta = 0;
3076 * Its got a race, we don't care...
3078 if (atomic_long_read(&calc_load_tasks_idle))
3079 delta = atomic_long_xchg(&calc_load_tasks_idle, 0);
3081 return delta;
3085 * fixed_power_int - compute: x^n, in O(log n) time
3087 * @x: base of the power
3088 * @frac_bits: fractional bits of @x
3089 * @n: power to raise @x to.
3091 * By exploiting the relation between the definition of the natural power
3092 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
3093 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
3094 * (where: n_i \elem {0, 1}, the binary vector representing n),
3095 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
3096 * of course trivially computable in O(log_2 n), the length of our binary
3097 * vector.
3099 static unsigned long
3100 fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
3102 unsigned long result = 1UL << frac_bits;
3104 if (n) for (;;) {
3105 if (n & 1) {
3106 result *= x;
3107 result += 1UL << (frac_bits - 1);
3108 result >>= frac_bits;
3110 n >>= 1;
3111 if (!n)
3112 break;
3113 x *= x;
3114 x += 1UL << (frac_bits - 1);
3115 x >>= frac_bits;
3118 return result;
3122 * a1 = a0 * e + a * (1 - e)
3124 * a2 = a1 * e + a * (1 - e)
3125 * = (a0 * e + a * (1 - e)) * e + a * (1 - e)
3126 * = a0 * e^2 + a * (1 - e) * (1 + e)
3128 * a3 = a2 * e + a * (1 - e)
3129 * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
3130 * = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
3132 * ...
3134 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
3135 * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
3136 * = a0 * e^n + a * (1 - e^n)
3138 * [1] application of the geometric series:
3140 * n 1 - x^(n+1)
3141 * S_n := \Sum x^i = -------------
3142 * i=0 1 - x
3144 static unsigned long
3145 calc_load_n(unsigned long load, unsigned long exp,
3146 unsigned long active, unsigned int n)
3149 return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
3153 * NO_HZ can leave us missing all per-cpu ticks calling
3154 * calc_load_account_active(), but since an idle CPU folds its delta into
3155 * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
3156 * in the pending idle delta if our idle period crossed a load cycle boundary.
3158 * Once we've updated the global active value, we need to apply the exponential
3159 * weights adjusted to the number of cycles missed.
3161 static void calc_global_nohz(unsigned long ticks)
3163 long delta, active, n;
3165 if (time_before(jiffies, calc_load_update))
3166 return;
3169 * If we crossed a calc_load_update boundary, make sure to fold
3170 * any pending idle changes, the respective CPUs might have
3171 * missed the tick driven calc_load_account_active() update
3172 * due to NO_HZ.
3174 delta = calc_load_fold_idle();
3175 if (delta)
3176 atomic_long_add(delta, &calc_load_tasks);
3179 * If we were idle for multiple load cycles, apply them.
3181 if (ticks >= LOAD_FREQ) {
3182 n = ticks / LOAD_FREQ;
3184 active = atomic_long_read(&calc_load_tasks);
3185 active = active > 0 ? active * FIXED_1 : 0;
3187 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
3188 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
3189 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
3191 calc_load_update += n * LOAD_FREQ;
3195 * Its possible the remainder of the above division also crosses
3196 * a LOAD_FREQ period, the regular check in calc_global_load()
3197 * which comes after this will take care of that.
3199 * Consider us being 11 ticks before a cycle completion, and us
3200 * sleeping for 4*LOAD_FREQ + 22 ticks, then the above code will
3201 * age us 4 cycles, and the test in calc_global_load() will
3202 * pick up the final one.
3205 #else
3206 static void calc_load_account_idle(struct rq *this_rq)
3210 static inline long calc_load_fold_idle(void)
3212 return 0;
3215 static void calc_global_nohz(unsigned long ticks)
3218 #endif
3221 * get_avenrun - get the load average array
3222 * @loads: pointer to dest load array
3223 * @offset: offset to add
3224 * @shift: shift count to shift the result left
3226 * These values are estimates at best, so no need for locking.
3228 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3230 loads[0] = (avenrun[0] + offset) << shift;
3231 loads[1] = (avenrun[1] + offset) << shift;
3232 loads[2] = (avenrun[2] + offset) << shift;
3236 * calc_load - update the avenrun load estimates 10 ticks after the
3237 * CPUs have updated calc_load_tasks.
3239 void calc_global_load(unsigned long ticks)
3241 long active;
3243 calc_global_nohz(ticks);
3245 if (time_before(jiffies, calc_load_update + 10))
3246 return;
3248 active = atomic_long_read(&calc_load_tasks);
3249 active = active > 0 ? active * FIXED_1 : 0;
3251 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3252 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3253 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3255 calc_load_update += LOAD_FREQ;
3259 * Called from update_cpu_load() to periodically update this CPU's
3260 * active count.
3262 static void calc_load_account_active(struct rq *this_rq)
3264 long delta;
3266 if (time_before(jiffies, this_rq->calc_load_update))
3267 return;
3269 delta = calc_load_fold_active(this_rq);
3270 delta += calc_load_fold_idle();
3271 if (delta)
3272 atomic_long_add(delta, &calc_load_tasks);
3274 this_rq->calc_load_update += LOAD_FREQ;
3278 * The exact cpuload at various idx values, calculated at every tick would be
3279 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
3281 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
3282 * on nth tick when cpu may be busy, then we have:
3283 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3284 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
3286 * decay_load_missed() below does efficient calculation of
3287 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3288 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
3290 * The calculation is approximated on a 128 point scale.
3291 * degrade_zero_ticks is the number of ticks after which load at any
3292 * particular idx is approximated to be zero.
3293 * degrade_factor is a precomputed table, a row for each load idx.
3294 * Each column corresponds to degradation factor for a power of two ticks,
3295 * based on 128 point scale.
3296 * Example:
3297 * row 2, col 3 (=12) says that the degradation at load idx 2 after
3298 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
3300 * With this power of 2 load factors, we can degrade the load n times
3301 * by looking at 1 bits in n and doing as many mult/shift instead of
3302 * n mult/shifts needed by the exact degradation.
3304 #define DEGRADE_SHIFT 7
3305 static const unsigned char
3306 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
3307 static const unsigned char
3308 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
3309 {0, 0, 0, 0, 0, 0, 0, 0},
3310 {64, 32, 8, 0, 0, 0, 0, 0},
3311 {96, 72, 40, 12, 1, 0, 0},
3312 {112, 98, 75, 43, 15, 1, 0},
3313 {120, 112, 98, 76, 45, 16, 2} };
3316 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
3317 * would be when CPU is idle and so we just decay the old load without
3318 * adding any new load.
3320 static unsigned long
3321 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
3323 int j = 0;
3325 if (!missed_updates)
3326 return load;
3328 if (missed_updates >= degrade_zero_ticks[idx])
3329 return 0;
3331 if (idx == 1)
3332 return load >> missed_updates;
3334 while (missed_updates) {
3335 if (missed_updates % 2)
3336 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
3338 missed_updates >>= 1;
3339 j++;
3341 return load;
3345 * Update rq->cpu_load[] statistics. This function is usually called every
3346 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
3347 * every tick. We fix it up based on jiffies.
3349 static void update_cpu_load(struct rq *this_rq)
3351 unsigned long this_load = this_rq->load.weight;
3352 unsigned long curr_jiffies = jiffies;
3353 unsigned long pending_updates;
3354 int i, scale;
3356 this_rq->nr_load_updates++;
3358 /* Avoid repeated calls on same jiffy, when moving in and out of idle */
3359 if (curr_jiffies == this_rq->last_load_update_tick)
3360 return;
3362 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
3363 this_rq->last_load_update_tick = curr_jiffies;
3365 /* Update our load: */
3366 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
3367 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3368 unsigned long old_load, new_load;
3370 /* scale is effectively 1 << i now, and >> i divides by scale */
3372 old_load = this_rq->cpu_load[i];
3373 old_load = decay_load_missed(old_load, pending_updates - 1, i);
3374 new_load = this_load;
3376 * Round up the averaging division if load is increasing. This
3377 * prevents us from getting stuck on 9 if the load is 10, for
3378 * example.
3380 if (new_load > old_load)
3381 new_load += scale - 1;
3383 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
3386 sched_avg_update(this_rq);
3389 static void update_cpu_load_active(struct rq *this_rq)
3391 update_cpu_load(this_rq);
3393 calc_load_account_active(this_rq);
3396 #ifdef CONFIG_SMP
3399 * sched_exec - execve() is a valuable balancing opportunity, because at
3400 * this point the task has the smallest effective memory and cache footprint.
3402 void sched_exec(void)
3404 struct task_struct *p = current;
3405 unsigned long flags;
3406 struct rq *rq;
3407 int dest_cpu;
3409 rq = task_rq_lock(p, &flags);
3410 dest_cpu = p->sched_class->select_task_rq(rq, p, SD_BALANCE_EXEC, 0);
3411 if (dest_cpu == smp_processor_id())
3412 goto unlock;
3415 * select_task_rq() can race against ->cpus_allowed
3417 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed) &&
3418 likely(cpu_active(dest_cpu)) && migrate_task(p, rq)) {
3419 struct migration_arg arg = { p, dest_cpu };
3421 task_rq_unlock(rq, &flags);
3422 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
3423 return;
3425 unlock:
3426 task_rq_unlock(rq, &flags);
3429 #endif
3431 DEFINE_PER_CPU(struct kernel_stat, kstat);
3433 EXPORT_PER_CPU_SYMBOL(kstat);
3436 * Return any ns on the sched_clock that have not yet been accounted in
3437 * @p in case that task is currently running.
3439 * Called with task_rq_lock() held on @rq.
3441 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
3443 u64 ns = 0;
3445 if (task_current(rq, p)) {
3446 update_rq_clock(rq);
3447 ns = rq->clock_task - p->se.exec_start;
3448 if ((s64)ns < 0)
3449 ns = 0;
3452 return ns;
3455 unsigned long long task_delta_exec(struct task_struct *p)
3457 unsigned long flags;
3458 struct rq *rq;
3459 u64 ns = 0;
3461 rq = task_rq_lock(p, &flags);
3462 ns = do_task_delta_exec(p, rq);
3463 task_rq_unlock(rq, &flags);
3465 return ns;
3469 * Return accounted runtime for the task.
3470 * In case the task is currently running, return the runtime plus current's
3471 * pending runtime that have not been accounted yet.
3473 unsigned long long task_sched_runtime(struct task_struct *p)
3475 unsigned long flags;
3476 struct rq *rq;
3477 u64 ns = 0;
3479 rq = task_rq_lock(p, &flags);
3480 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
3481 task_rq_unlock(rq, &flags);
3483 return ns;
3487 * Return sum_exec_runtime for the thread group.
3488 * In case the task is currently running, return the sum plus current's
3489 * pending runtime that have not been accounted yet.
3491 * Note that the thread group might have other running tasks as well,
3492 * so the return value not includes other pending runtime that other
3493 * running tasks might have.
3495 unsigned long long thread_group_sched_runtime(struct task_struct *p)
3497 struct task_cputime totals;
3498 unsigned long flags;
3499 struct rq *rq;
3500 u64 ns;
3502 rq = task_rq_lock(p, &flags);
3503 thread_group_cputime(p, &totals);
3504 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
3505 task_rq_unlock(rq, &flags);
3507 return ns;
3511 * Account user cpu time to a process.
3512 * @p: the process that the cpu time gets accounted to
3513 * @cputime: the cpu time spent in user space since the last update
3514 * @cputime_scaled: cputime scaled by cpu frequency
3516 void account_user_time(struct task_struct *p, cputime_t cputime,
3517 cputime_t cputime_scaled)
3519 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3520 cputime64_t tmp;
3522 /* Add user time to process. */
3523 p->utime = cputime_add(p->utime, cputime);
3524 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3525 account_group_user_time(p, cputime);
3527 /* Add user time to cpustat. */
3528 tmp = cputime_to_cputime64(cputime);
3529 if (TASK_NICE(p) > 0)
3530 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3531 else
3532 cpustat->user = cputime64_add(cpustat->user, tmp);
3534 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
3535 /* Account for user time used */
3536 acct_update_integrals(p);
3540 * Account guest cpu time to a process.
3541 * @p: the process that the cpu time gets accounted to
3542 * @cputime: the cpu time spent in virtual machine since the last update
3543 * @cputime_scaled: cputime scaled by cpu frequency
3545 static void account_guest_time(struct task_struct *p, cputime_t cputime,
3546 cputime_t cputime_scaled)
3548 cputime64_t tmp;
3549 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3551 tmp = cputime_to_cputime64(cputime);
3553 /* Add guest time to process. */
3554 p->utime = cputime_add(p->utime, cputime);
3555 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3556 account_group_user_time(p, cputime);
3557 p->gtime = cputime_add(p->gtime, cputime);
3559 /* Add guest time to cpustat. */
3560 if (TASK_NICE(p) > 0) {
3561 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3562 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
3563 } else {
3564 cpustat->user = cputime64_add(cpustat->user, tmp);
3565 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3570 * Account system cpu time to a process.
3571 * @p: the process that the cpu time gets accounted to
3572 * @hardirq_offset: the offset to subtract from hardirq_count()
3573 * @cputime: the cpu time spent in kernel space since the last update
3574 * @cputime_scaled: cputime scaled by cpu frequency
3576 void account_system_time(struct task_struct *p, int hardirq_offset,
3577 cputime_t cputime, cputime_t cputime_scaled)
3579 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3580 cputime64_t tmp;
3582 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
3583 account_guest_time(p, cputime, cputime_scaled);
3584 return;
3587 /* Add system time to process. */
3588 p->stime = cputime_add(p->stime, cputime);
3589 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
3590 account_group_system_time(p, cputime);
3592 /* Add system time to cpustat. */
3593 tmp = cputime_to_cputime64(cputime);
3594 if (hardirq_count() - hardirq_offset)
3595 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3596 else if (in_serving_softirq())
3597 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3598 else
3599 cpustat->system = cputime64_add(cpustat->system, tmp);
3601 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
3603 /* Account for system time used */
3604 acct_update_integrals(p);
3608 * Account for involuntary wait time.
3609 * @steal: the cpu time spent in involuntary wait
3611 void account_steal_time(cputime_t cputime)
3613 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3614 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3616 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
3620 * Account for idle time.
3621 * @cputime: the cpu time spent in idle wait
3623 void account_idle_time(cputime_t cputime)
3625 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3626 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3627 struct rq *rq = this_rq();
3629 if (atomic_read(&rq->nr_iowait) > 0)
3630 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
3631 else
3632 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
3635 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
3638 * Account a single tick of cpu time.
3639 * @p: the process that the cpu time gets accounted to
3640 * @user_tick: indicates if the tick is a user or a system tick
3642 void account_process_tick(struct task_struct *p, int user_tick)
3644 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3645 struct rq *rq = this_rq();
3647 if (user_tick)
3648 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3649 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
3650 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
3651 one_jiffy_scaled);
3652 else
3653 account_idle_time(cputime_one_jiffy);
3657 * Account multiple ticks of steal time.
3658 * @p: the process from which the cpu time has been stolen
3659 * @ticks: number of stolen ticks
3661 void account_steal_ticks(unsigned long ticks)
3663 account_steal_time(jiffies_to_cputime(ticks));
3667 * Account multiple ticks of idle time.
3668 * @ticks: number of stolen ticks
3670 void account_idle_ticks(unsigned long ticks)
3672 account_idle_time(jiffies_to_cputime(ticks));
3675 #endif
3678 * Use precise platform statistics if available:
3680 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
3681 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3683 *ut = p->utime;
3684 *st = p->stime;
3687 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3689 struct task_cputime cputime;
3691 thread_group_cputime(p, &cputime);
3693 *ut = cputime.utime;
3694 *st = cputime.stime;
3696 #else
3698 #ifndef nsecs_to_cputime
3699 # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
3700 #endif
3702 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3704 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
3707 * Use CFS's precise accounting:
3709 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
3711 if (total) {
3712 u64 temp = rtime;
3714 temp *= utime;
3715 do_div(temp, total);
3716 utime = (cputime_t)temp;
3717 } else
3718 utime = rtime;
3721 * Compare with previous values, to keep monotonicity:
3723 p->prev_utime = max(p->prev_utime, utime);
3724 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
3726 *ut = p->prev_utime;
3727 *st = p->prev_stime;
3731 * Must be called with siglock held.
3733 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3735 struct signal_struct *sig = p->signal;
3736 struct task_cputime cputime;
3737 cputime_t rtime, utime, total;
3739 thread_group_cputime(p, &cputime);
3741 total = cputime_add(cputime.utime, cputime.stime);
3742 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
3744 if (total) {
3745 u64 temp = rtime;
3747 temp *= cputime.utime;
3748 do_div(temp, total);
3749 utime = (cputime_t)temp;
3750 } else
3751 utime = rtime;
3753 sig->prev_utime = max(sig->prev_utime, utime);
3754 sig->prev_stime = max(sig->prev_stime,
3755 cputime_sub(rtime, sig->prev_utime));
3757 *ut = sig->prev_utime;
3758 *st = sig->prev_stime;
3760 #endif
3763 * This function gets called by the timer code, with HZ frequency.
3764 * We call it with interrupts disabled.
3766 * It also gets called by the fork code, when changing the parent's
3767 * timeslices.
3769 void scheduler_tick(void)
3771 int cpu = smp_processor_id();
3772 struct rq *rq = cpu_rq(cpu);
3773 struct task_struct *curr = rq->curr;
3775 sched_clock_tick();
3777 raw_spin_lock(&rq->lock);
3778 update_rq_clock(rq);
3779 update_cpu_load_active(rq);
3780 curr->sched_class->task_tick(rq, curr, 0);
3781 raw_spin_unlock(&rq->lock);
3783 perf_event_task_tick();
3785 #ifdef CONFIG_SMP
3786 rq->idle_at_tick = idle_cpu(cpu);
3787 trigger_load_balance(rq, cpu);
3788 #endif
3791 notrace unsigned long get_parent_ip(unsigned long addr)
3793 if (in_lock_functions(addr)) {
3794 addr = CALLER_ADDR2;
3795 if (in_lock_functions(addr))
3796 addr = CALLER_ADDR3;
3798 return addr;
3801 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3802 defined(CONFIG_PREEMPT_TRACER))
3804 void __kprobes add_preempt_count(int val)
3806 #ifdef CONFIG_DEBUG_PREEMPT
3808 * Underflow?
3810 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3811 return;
3812 #endif
3813 preempt_count() += val;
3814 #ifdef CONFIG_DEBUG_PREEMPT
3816 * Spinlock count overflowing soon?
3818 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3819 PREEMPT_MASK - 10);
3820 #endif
3821 if (preempt_count() == val)
3822 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3824 EXPORT_SYMBOL(add_preempt_count);
3826 void __kprobes sub_preempt_count(int val)
3828 #ifdef CONFIG_DEBUG_PREEMPT
3830 * Underflow?
3832 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3833 return;
3835 * Is the spinlock portion underflowing?
3837 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3838 !(preempt_count() & PREEMPT_MASK)))
3839 return;
3840 #endif
3842 if (preempt_count() == val)
3843 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3844 preempt_count() -= val;
3846 EXPORT_SYMBOL(sub_preempt_count);
3848 #endif
3851 * Print scheduling while atomic bug:
3853 static noinline void __schedule_bug(struct task_struct *prev)
3855 struct pt_regs *regs = get_irq_regs();
3857 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3858 prev->comm, prev->pid, preempt_count());
3860 debug_show_held_locks(prev);
3861 print_modules();
3862 if (irqs_disabled())
3863 print_irqtrace_events(prev);
3865 if (regs)
3866 show_regs(regs);
3867 else
3868 dump_stack();
3872 * Various schedule()-time debugging checks and statistics:
3874 static inline void schedule_debug(struct task_struct *prev)
3877 * Test if we are atomic. Since do_exit() needs to call into
3878 * schedule() atomically, we ignore that path for now.
3879 * Otherwise, whine if we are scheduling when we should not be.
3881 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
3882 __schedule_bug(prev);
3884 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3886 schedstat_inc(this_rq(), sched_count);
3887 #ifdef CONFIG_SCHEDSTATS
3888 if (unlikely(prev->lock_depth >= 0)) {
3889 schedstat_inc(this_rq(), rq_sched_info.bkl_count);
3890 schedstat_inc(prev, sched_info.bkl_count);
3892 #endif
3895 static void put_prev_task(struct rq *rq, struct task_struct *prev)
3897 if (prev->se.on_rq)
3898 update_rq_clock(rq);
3899 prev->sched_class->put_prev_task(rq, prev);
3903 * Pick up the highest-prio task:
3905 static inline struct task_struct *
3906 pick_next_task(struct rq *rq)
3908 const struct sched_class *class;
3909 struct task_struct *p;
3912 * Optimization: we know that if all tasks are in
3913 * the fair class we can call that function directly:
3915 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3916 p = fair_sched_class.pick_next_task(rq);
3917 if (likely(p))
3918 return p;
3921 for_each_class(class) {
3922 p = class->pick_next_task(rq);
3923 if (p)
3924 return p;
3927 BUG(); /* the idle class will always have a runnable task */
3931 * schedule() is the main scheduler function.
3933 asmlinkage void __sched schedule(void)
3935 struct task_struct *prev, *next;
3936 unsigned long *switch_count;
3937 struct rq *rq;
3938 int cpu;
3940 need_resched:
3941 preempt_disable();
3942 cpu = smp_processor_id();
3943 rq = cpu_rq(cpu);
3944 rcu_note_context_switch(cpu);
3945 prev = rq->curr;
3947 schedule_debug(prev);
3949 if (sched_feat(HRTICK))
3950 hrtick_clear(rq);
3952 raw_spin_lock_irq(&rq->lock);
3954 switch_count = &prev->nivcsw;
3955 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3956 if (unlikely(signal_pending_state(prev->state, prev))) {
3957 prev->state = TASK_RUNNING;
3958 } else {
3960 * If a worker is going to sleep, notify and
3961 * ask workqueue whether it wants to wake up a
3962 * task to maintain concurrency. If so, wake
3963 * up the task.
3965 if (prev->flags & PF_WQ_WORKER) {
3966 struct task_struct *to_wakeup;
3968 to_wakeup = wq_worker_sleeping(prev, cpu);
3969 if (to_wakeup)
3970 try_to_wake_up_local(to_wakeup);
3972 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3974 switch_count = &prev->nvcsw;
3977 pre_schedule(rq, prev);
3979 if (unlikely(!rq->nr_running))
3980 idle_balance(cpu, rq);
3982 put_prev_task(rq, prev);
3983 next = pick_next_task(rq);
3984 clear_tsk_need_resched(prev);
3985 rq->skip_clock_update = 0;
3987 if (likely(prev != next)) {
3988 sched_info_switch(prev, next);
3989 perf_event_task_sched_out(prev, next);
3991 rq->nr_switches++;
3992 rq->curr = next;
3993 ++*switch_count;
3995 context_switch(rq, prev, next); /* unlocks the rq */
3997 * The context switch have flipped the stack from under us
3998 * and restored the local variables which were saved when
3999 * this task called schedule() in the past. prev == current
4000 * is still correct, but it can be moved to another cpu/rq.
4002 cpu = smp_processor_id();
4003 rq = cpu_rq(cpu);
4004 } else
4005 raw_spin_unlock_irq(&rq->lock);
4007 post_schedule(rq);
4009 preempt_enable_no_resched();
4010 if (need_resched())
4011 goto need_resched;
4013 EXPORT_SYMBOL(schedule);
4015 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
4017 * Look out! "owner" is an entirely speculative pointer
4018 * access and not reliable.
4020 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
4022 unsigned int cpu;
4023 struct rq *rq;
4025 if (!sched_feat(OWNER_SPIN))
4026 return 0;
4028 #ifdef CONFIG_DEBUG_PAGEALLOC
4030 * Need to access the cpu field knowing that
4031 * DEBUG_PAGEALLOC could have unmapped it if
4032 * the mutex owner just released it and exited.
4034 if (probe_kernel_address(&owner->cpu, cpu))
4035 return 0;
4036 #else
4037 cpu = owner->cpu;
4038 #endif
4041 * Even if the access succeeded (likely case),
4042 * the cpu field may no longer be valid.
4044 if (cpu >= nr_cpumask_bits)
4045 return 0;
4048 * We need to validate that we can do a
4049 * get_cpu() and that we have the percpu area.
4051 if (!cpu_online(cpu))
4052 return 0;
4054 rq = cpu_rq(cpu);
4056 for (;;) {
4058 * Owner changed, break to re-assess state.
4060 if (lock->owner != owner) {
4062 * If the lock has switched to a different owner,
4063 * we likely have heavy contention. Return 0 to quit
4064 * optimistic spinning and not contend further:
4066 if (lock->owner)
4067 return 0;
4068 break;
4072 * Is that owner really running on that cpu?
4074 if (task_thread_info(rq->curr) != owner || need_resched())
4075 return 0;
4077 arch_mutex_cpu_relax();
4080 return 1;
4082 #endif
4084 #ifdef CONFIG_PREEMPT
4086 * this is the entry point to schedule() from in-kernel preemption
4087 * off of preempt_enable. Kernel preemptions off return from interrupt
4088 * occur there and call schedule directly.
4090 asmlinkage void __sched notrace preempt_schedule(void)
4092 struct thread_info *ti = current_thread_info();
4095 * If there is a non-zero preempt_count or interrupts are disabled,
4096 * we do not want to preempt the current task. Just return..
4098 if (likely(ti->preempt_count || irqs_disabled()))
4099 return;
4101 do {
4102 add_preempt_count_notrace(PREEMPT_ACTIVE);
4103 schedule();
4104 sub_preempt_count_notrace(PREEMPT_ACTIVE);
4107 * Check again in case we missed a preemption opportunity
4108 * between schedule and now.
4110 barrier();
4111 } while (need_resched());
4113 EXPORT_SYMBOL(preempt_schedule);
4116 * this is the entry point to schedule() from kernel preemption
4117 * off of irq context.
4118 * Note, that this is called and return with irqs disabled. This will
4119 * protect us against recursive calling from irq.
4121 asmlinkage void __sched preempt_schedule_irq(void)
4123 struct thread_info *ti = current_thread_info();
4125 /* Catch callers which need to be fixed */
4126 BUG_ON(ti->preempt_count || !irqs_disabled());
4128 do {
4129 add_preempt_count(PREEMPT_ACTIVE);
4130 local_irq_enable();
4131 schedule();
4132 local_irq_disable();
4133 sub_preempt_count(PREEMPT_ACTIVE);
4136 * Check again in case we missed a preemption opportunity
4137 * between schedule and now.
4139 barrier();
4140 } while (need_resched());
4143 #endif /* CONFIG_PREEMPT */
4145 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
4146 void *key)
4148 return try_to_wake_up(curr->private, mode, wake_flags);
4150 EXPORT_SYMBOL(default_wake_function);
4153 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4154 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4155 * number) then we wake all the non-exclusive tasks and one exclusive task.
4157 * There are circumstances in which we can try to wake a task which has already
4158 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4159 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4161 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4162 int nr_exclusive, int wake_flags, void *key)
4164 wait_queue_t *curr, *next;
4166 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4167 unsigned flags = curr->flags;
4169 if (curr->func(curr, mode, wake_flags, key) &&
4170 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4171 break;
4176 * __wake_up - wake up threads blocked on a waitqueue.
4177 * @q: the waitqueue
4178 * @mode: which threads
4179 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4180 * @key: is directly passed to the wakeup function
4182 * It may be assumed that this function implies a write memory barrier before
4183 * changing the task state if and only if any tasks are woken up.
4185 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4186 int nr_exclusive, void *key)
4188 unsigned long flags;
4190 spin_lock_irqsave(&q->lock, flags);
4191 __wake_up_common(q, mode, nr_exclusive, 0, key);
4192 spin_unlock_irqrestore(&q->lock, flags);
4194 EXPORT_SYMBOL(__wake_up);
4197 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4199 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4201 __wake_up_common(q, mode, 1, 0, NULL);
4203 EXPORT_SYMBOL_GPL(__wake_up_locked);
4205 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
4207 __wake_up_common(q, mode, 1, 0, key);
4211 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
4212 * @q: the waitqueue
4213 * @mode: which threads
4214 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4215 * @key: opaque value to be passed to wakeup targets
4217 * The sync wakeup differs that the waker knows that it will schedule
4218 * away soon, so while the target thread will be woken up, it will not
4219 * be migrated to another CPU - ie. the two threads are 'synchronized'
4220 * with each other. This can prevent needless bouncing between CPUs.
4222 * On UP it can prevent extra preemption.
4224 * It may be assumed that this function implies a write memory barrier before
4225 * changing the task state if and only if any tasks are woken up.
4227 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
4228 int nr_exclusive, void *key)
4230 unsigned long flags;
4231 int wake_flags = WF_SYNC;
4233 if (unlikely(!q))
4234 return;
4236 if (unlikely(!nr_exclusive))
4237 wake_flags = 0;
4239 spin_lock_irqsave(&q->lock, flags);
4240 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
4241 spin_unlock_irqrestore(&q->lock, flags);
4243 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
4246 * __wake_up_sync - see __wake_up_sync_key()
4248 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4250 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
4252 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4255 * complete: - signals a single thread waiting on this completion
4256 * @x: holds the state of this particular completion
4258 * This will wake up a single thread waiting on this completion. Threads will be
4259 * awakened in the same order in which they were queued.
4261 * See also complete_all(), wait_for_completion() and related routines.
4263 * It may be assumed that this function implies a write memory barrier before
4264 * changing the task state if and only if any tasks are woken up.
4266 void complete(struct completion *x)
4268 unsigned long flags;
4270 spin_lock_irqsave(&x->wait.lock, flags);
4271 x->done++;
4272 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4273 spin_unlock_irqrestore(&x->wait.lock, flags);
4275 EXPORT_SYMBOL(complete);
4278 * complete_all: - signals all threads waiting on this completion
4279 * @x: holds the state of this particular completion
4281 * This will wake up all threads waiting on this particular completion event.
4283 * It may be assumed that this function implies a write memory barrier before
4284 * changing the task state if and only if any tasks are woken up.
4286 void complete_all(struct completion *x)
4288 unsigned long flags;
4290 spin_lock_irqsave(&x->wait.lock, flags);
4291 x->done += UINT_MAX/2;
4292 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4293 spin_unlock_irqrestore(&x->wait.lock, flags);
4295 EXPORT_SYMBOL(complete_all);
4297 static inline long __sched
4298 do_wait_for_common(struct completion *x, long timeout, int state)
4300 if (!x->done) {
4301 DECLARE_WAITQUEUE(wait, current);
4303 __add_wait_queue_tail_exclusive(&x->wait, &wait);
4304 do {
4305 if (signal_pending_state(state, current)) {
4306 timeout = -ERESTARTSYS;
4307 break;
4309 __set_current_state(state);
4310 spin_unlock_irq(&x->wait.lock);
4311 timeout = schedule_timeout(timeout);
4312 spin_lock_irq(&x->wait.lock);
4313 } while (!x->done && timeout);
4314 __remove_wait_queue(&x->wait, &wait);
4315 if (!x->done)
4316 return timeout;
4318 x->done--;
4319 return timeout ?: 1;
4322 static long __sched
4323 wait_for_common(struct completion *x, long timeout, int state)
4325 might_sleep();
4327 spin_lock_irq(&x->wait.lock);
4328 timeout = do_wait_for_common(x, timeout, state);
4329 spin_unlock_irq(&x->wait.lock);
4330 return timeout;
4334 * wait_for_completion: - waits for completion of a task
4335 * @x: holds the state of this particular completion
4337 * This waits to be signaled for completion of a specific task. It is NOT
4338 * interruptible and there is no timeout.
4340 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4341 * and interrupt capability. Also see complete().
4343 void __sched wait_for_completion(struct completion *x)
4345 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4347 EXPORT_SYMBOL(wait_for_completion);
4350 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4351 * @x: holds the state of this particular completion
4352 * @timeout: timeout value in jiffies
4354 * This waits for either a completion of a specific task to be signaled or for a
4355 * specified timeout to expire. The timeout is in jiffies. It is not
4356 * interruptible.
4358 unsigned long __sched
4359 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4361 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4363 EXPORT_SYMBOL(wait_for_completion_timeout);
4366 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4367 * @x: holds the state of this particular completion
4369 * This waits for completion of a specific task to be signaled. It is
4370 * interruptible.
4372 int __sched wait_for_completion_interruptible(struct completion *x)
4374 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4375 if (t == -ERESTARTSYS)
4376 return t;
4377 return 0;
4379 EXPORT_SYMBOL(wait_for_completion_interruptible);
4382 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4383 * @x: holds the state of this particular completion
4384 * @timeout: timeout value in jiffies
4386 * This waits for either a completion of a specific task to be signaled or for a
4387 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4389 long __sched
4390 wait_for_completion_interruptible_timeout(struct completion *x,
4391 unsigned long timeout)
4393 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4395 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4398 * wait_for_completion_killable: - waits for completion of a task (killable)
4399 * @x: holds the state of this particular completion
4401 * This waits to be signaled for completion of a specific task. It can be
4402 * interrupted by a kill signal.
4404 int __sched wait_for_completion_killable(struct completion *x)
4406 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4407 if (t == -ERESTARTSYS)
4408 return t;
4409 return 0;
4411 EXPORT_SYMBOL(wait_for_completion_killable);
4414 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
4415 * @x: holds the state of this particular completion
4416 * @timeout: timeout value in jiffies
4418 * This waits for either a completion of a specific task to be
4419 * signaled or for a specified timeout to expire. It can be
4420 * interrupted by a kill signal. The timeout is in jiffies.
4422 long __sched
4423 wait_for_completion_killable_timeout(struct completion *x,
4424 unsigned long timeout)
4426 return wait_for_common(x, timeout, TASK_KILLABLE);
4428 EXPORT_SYMBOL(wait_for_completion_killable_timeout);
4431 * try_wait_for_completion - try to decrement a completion without blocking
4432 * @x: completion structure
4434 * Returns: 0 if a decrement cannot be done without blocking
4435 * 1 if a decrement succeeded.
4437 * If a completion is being used as a counting completion,
4438 * attempt to decrement the counter without blocking. This
4439 * enables us to avoid waiting if the resource the completion
4440 * is protecting is not available.
4442 bool try_wait_for_completion(struct completion *x)
4444 unsigned long flags;
4445 int ret = 1;
4447 spin_lock_irqsave(&x->wait.lock, flags);
4448 if (!x->done)
4449 ret = 0;
4450 else
4451 x->done--;
4452 spin_unlock_irqrestore(&x->wait.lock, flags);
4453 return ret;
4455 EXPORT_SYMBOL(try_wait_for_completion);
4458 * completion_done - Test to see if a completion has any waiters
4459 * @x: completion structure
4461 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4462 * 1 if there are no waiters.
4465 bool completion_done(struct completion *x)
4467 unsigned long flags;
4468 int ret = 1;
4470 spin_lock_irqsave(&x->wait.lock, flags);
4471 if (!x->done)
4472 ret = 0;
4473 spin_unlock_irqrestore(&x->wait.lock, flags);
4474 return ret;
4476 EXPORT_SYMBOL(completion_done);
4478 static long __sched
4479 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4481 unsigned long flags;
4482 wait_queue_t wait;
4484 init_waitqueue_entry(&wait, current);
4486 __set_current_state(state);
4488 spin_lock_irqsave(&q->lock, flags);
4489 __add_wait_queue(q, &wait);
4490 spin_unlock(&q->lock);
4491 timeout = schedule_timeout(timeout);
4492 spin_lock_irq(&q->lock);
4493 __remove_wait_queue(q, &wait);
4494 spin_unlock_irqrestore(&q->lock, flags);
4496 return timeout;
4499 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4501 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4503 EXPORT_SYMBOL(interruptible_sleep_on);
4505 long __sched
4506 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4508 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4510 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4512 void __sched sleep_on(wait_queue_head_t *q)
4514 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4516 EXPORT_SYMBOL(sleep_on);
4518 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4520 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4522 EXPORT_SYMBOL(sleep_on_timeout);
4524 #ifdef CONFIG_RT_MUTEXES
4527 * rt_mutex_setprio - set the current priority of a task
4528 * @p: task
4529 * @prio: prio value (kernel-internal form)
4531 * This function changes the 'effective' priority of a task. It does
4532 * not touch ->normal_prio like __setscheduler().
4534 * Used by the rt_mutex code to implement priority inheritance logic.
4536 void rt_mutex_setprio(struct task_struct *p, int prio)
4538 unsigned long flags;
4539 int oldprio, on_rq, running;
4540 struct rq *rq;
4541 const struct sched_class *prev_class;
4543 BUG_ON(prio < 0 || prio > MAX_PRIO);
4545 rq = task_rq_lock(p, &flags);
4547 trace_sched_pi_setprio(p, prio);
4548 oldprio = p->prio;
4549 prev_class = p->sched_class;
4550 on_rq = p->se.on_rq;
4551 running = task_current(rq, p);
4552 if (on_rq)
4553 dequeue_task(rq, p, 0);
4554 if (running)
4555 p->sched_class->put_prev_task(rq, p);
4557 if (rt_prio(prio))
4558 p->sched_class = &rt_sched_class;
4559 else
4560 p->sched_class = &fair_sched_class;
4562 p->prio = prio;
4564 if (running)
4565 p->sched_class->set_curr_task(rq);
4566 if (on_rq) {
4567 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
4569 check_class_changed(rq, p, prev_class, oldprio, running);
4571 task_rq_unlock(rq, &flags);
4574 #endif
4576 void set_user_nice(struct task_struct *p, long nice)
4578 int old_prio, delta, on_rq;
4579 unsigned long flags;
4580 struct rq *rq;
4582 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4583 return;
4585 * We have to be careful, if called from sys_setpriority(),
4586 * the task might be in the middle of scheduling on another CPU.
4588 rq = task_rq_lock(p, &flags);
4590 * The RT priorities are set via sched_setscheduler(), but we still
4591 * allow the 'normal' nice value to be set - but as expected
4592 * it wont have any effect on scheduling until the task is
4593 * SCHED_FIFO/SCHED_RR:
4595 if (task_has_rt_policy(p)) {
4596 p->static_prio = NICE_TO_PRIO(nice);
4597 goto out_unlock;
4599 on_rq = p->se.on_rq;
4600 if (on_rq)
4601 dequeue_task(rq, p, 0);
4603 p->static_prio = NICE_TO_PRIO(nice);
4604 set_load_weight(p);
4605 old_prio = p->prio;
4606 p->prio = effective_prio(p);
4607 delta = p->prio - old_prio;
4609 if (on_rq) {
4610 enqueue_task(rq, p, 0);
4612 * If the task increased its priority or is running and
4613 * lowered its priority, then reschedule its CPU:
4615 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4616 resched_task(rq->curr);
4618 out_unlock:
4619 task_rq_unlock(rq, &flags);
4621 EXPORT_SYMBOL(set_user_nice);
4624 * can_nice - check if a task can reduce its nice value
4625 * @p: task
4626 * @nice: nice value
4628 int can_nice(const struct task_struct *p, const int nice)
4630 /* convert nice value [19,-20] to rlimit style value [1,40] */
4631 int nice_rlim = 20 - nice;
4633 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4634 capable(CAP_SYS_NICE));
4637 #ifdef __ARCH_WANT_SYS_NICE
4640 * sys_nice - change the priority of the current process.
4641 * @increment: priority increment
4643 * sys_setpriority is a more generic, but much slower function that
4644 * does similar things.
4646 SYSCALL_DEFINE1(nice, int, increment)
4648 long nice, retval;
4651 * Setpriority might change our priority at the same moment.
4652 * We don't have to worry. Conceptually one call occurs first
4653 * and we have a single winner.
4655 if (increment < -40)
4656 increment = -40;
4657 if (increment > 40)
4658 increment = 40;
4660 nice = TASK_NICE(current) + increment;
4661 if (nice < -20)
4662 nice = -20;
4663 if (nice > 19)
4664 nice = 19;
4666 if (increment < 0 && !can_nice(current, nice))
4667 return -EPERM;
4669 retval = security_task_setnice(current, nice);
4670 if (retval)
4671 return retval;
4673 set_user_nice(current, nice);
4674 return 0;
4677 #endif
4680 * task_prio - return the priority value of a given task.
4681 * @p: the task in question.
4683 * This is the priority value as seen by users in /proc.
4684 * RT tasks are offset by -200. Normal tasks are centered
4685 * around 0, value goes from -16 to +15.
4687 int task_prio(const struct task_struct *p)
4689 return p->prio - MAX_RT_PRIO;
4693 * task_nice - return the nice value of a given task.
4694 * @p: the task in question.
4696 int task_nice(const struct task_struct *p)
4698 return TASK_NICE(p);
4700 EXPORT_SYMBOL(task_nice);
4703 * idle_cpu - is a given cpu idle currently?
4704 * @cpu: the processor in question.
4706 int idle_cpu(int cpu)
4708 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4712 * idle_task - return the idle task for a given cpu.
4713 * @cpu: the processor in question.
4715 struct task_struct *idle_task(int cpu)
4717 return cpu_rq(cpu)->idle;
4721 * find_process_by_pid - find a process with a matching PID value.
4722 * @pid: the pid in question.
4724 static struct task_struct *find_process_by_pid(pid_t pid)
4726 return pid ? find_task_by_vpid(pid) : current;
4729 /* Actually do priority change: must hold rq lock. */
4730 static void
4731 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4733 BUG_ON(p->se.on_rq);
4735 p->policy = policy;
4736 p->rt_priority = prio;
4737 p->normal_prio = normal_prio(p);
4738 /* we are holding p->pi_lock already */
4739 p->prio = rt_mutex_getprio(p);
4740 if (rt_prio(p->prio))
4741 p->sched_class = &rt_sched_class;
4742 else
4743 p->sched_class = &fair_sched_class;
4744 set_load_weight(p);
4748 * check the target process has a UID that matches the current process's
4750 static bool check_same_owner(struct task_struct *p)
4752 const struct cred *cred = current_cred(), *pcred;
4753 bool match;
4755 rcu_read_lock();
4756 pcred = __task_cred(p);
4757 match = (cred->euid == pcred->euid ||
4758 cred->euid == pcred->uid);
4759 rcu_read_unlock();
4760 return match;
4763 static int __sched_setscheduler(struct task_struct *p, int policy,
4764 const struct sched_param *param, bool user)
4766 int retval, oldprio, oldpolicy = -1, on_rq, running;
4767 unsigned long flags;
4768 const struct sched_class *prev_class;
4769 struct rq *rq;
4770 int reset_on_fork;
4772 /* may grab non-irq protected spin_locks */
4773 BUG_ON(in_interrupt());
4774 recheck:
4775 /* double check policy once rq lock held */
4776 if (policy < 0) {
4777 reset_on_fork = p->sched_reset_on_fork;
4778 policy = oldpolicy = p->policy;
4779 } else {
4780 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
4781 policy &= ~SCHED_RESET_ON_FORK;
4783 if (policy != SCHED_FIFO && policy != SCHED_RR &&
4784 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4785 policy != SCHED_IDLE)
4786 return -EINVAL;
4790 * Valid priorities for SCHED_FIFO and SCHED_RR are
4791 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4792 * SCHED_BATCH and SCHED_IDLE is 0.
4794 if (param->sched_priority < 0 ||
4795 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4796 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4797 return -EINVAL;
4798 if (rt_policy(policy) != (param->sched_priority != 0))
4799 return -EINVAL;
4802 * Allow unprivileged RT tasks to decrease priority:
4804 if (user && !capable(CAP_SYS_NICE)) {
4805 if (rt_policy(policy)) {
4806 unsigned long rlim_rtprio =
4807 task_rlimit(p, RLIMIT_RTPRIO);
4809 /* can't set/change the rt policy */
4810 if (policy != p->policy && !rlim_rtprio)
4811 return -EPERM;
4813 /* can't increase priority */
4814 if (param->sched_priority > p->rt_priority &&
4815 param->sched_priority > rlim_rtprio)
4816 return -EPERM;
4819 * Like positive nice levels, dont allow tasks to
4820 * move out of SCHED_IDLE either:
4822 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4823 return -EPERM;
4825 /* can't change other user's priorities */
4826 if (!check_same_owner(p))
4827 return -EPERM;
4829 /* Normal users shall not reset the sched_reset_on_fork flag */
4830 if (p->sched_reset_on_fork && !reset_on_fork)
4831 return -EPERM;
4834 if (user) {
4835 retval = security_task_setscheduler(p);
4836 if (retval)
4837 return retval;
4841 * make sure no PI-waiters arrive (or leave) while we are
4842 * changing the priority of the task:
4844 raw_spin_lock_irqsave(&p->pi_lock, flags);
4846 * To be able to change p->policy safely, the apropriate
4847 * runqueue lock must be held.
4849 rq = __task_rq_lock(p);
4852 * Changing the policy of the stop threads its a very bad idea
4854 if (p == rq->stop) {
4855 __task_rq_unlock(rq);
4856 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4857 return -EINVAL;
4860 #ifdef CONFIG_RT_GROUP_SCHED
4861 if (user) {
4863 * Do not allow realtime tasks into groups that have no runtime
4864 * assigned.
4866 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4867 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4868 !task_group_is_autogroup(task_group(p))) {
4869 __task_rq_unlock(rq);
4870 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4871 return -EPERM;
4874 #endif
4876 /* recheck policy now with rq lock held */
4877 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4878 policy = oldpolicy = -1;
4879 __task_rq_unlock(rq);
4880 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4881 goto recheck;
4883 on_rq = p->se.on_rq;
4884 running = task_current(rq, p);
4885 if (on_rq)
4886 deactivate_task(rq, p, 0);
4887 if (running)
4888 p->sched_class->put_prev_task(rq, p);
4890 p->sched_reset_on_fork = reset_on_fork;
4892 oldprio = p->prio;
4893 prev_class = p->sched_class;
4894 __setscheduler(rq, p, policy, param->sched_priority);
4896 if (running)
4897 p->sched_class->set_curr_task(rq);
4898 if (on_rq) {
4899 activate_task(rq, p, 0);
4901 check_class_changed(rq, p, prev_class, oldprio, running);
4903 __task_rq_unlock(rq);
4904 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4906 rt_mutex_adjust_pi(p);
4908 return 0;
4912 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4913 * @p: the task in question.
4914 * @policy: new policy.
4915 * @param: structure containing the new RT priority.
4917 * NOTE that the task may be already dead.
4919 int sched_setscheduler(struct task_struct *p, int policy,
4920 const struct sched_param *param)
4922 return __sched_setscheduler(p, policy, param, true);
4924 EXPORT_SYMBOL_GPL(sched_setscheduler);
4927 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4928 * @p: the task in question.
4929 * @policy: new policy.
4930 * @param: structure containing the new RT priority.
4932 * Just like sched_setscheduler, only don't bother checking if the
4933 * current context has permission. For example, this is needed in
4934 * stop_machine(): we create temporary high priority worker threads,
4935 * but our caller might not have that capability.
4937 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4938 const struct sched_param *param)
4940 return __sched_setscheduler(p, policy, param, false);
4943 static int
4944 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4946 struct sched_param lparam;
4947 struct task_struct *p;
4948 int retval;
4950 if (!param || pid < 0)
4951 return -EINVAL;
4952 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4953 return -EFAULT;
4955 rcu_read_lock();
4956 retval = -ESRCH;
4957 p = find_process_by_pid(pid);
4958 if (p != NULL)
4959 retval = sched_setscheduler(p, policy, &lparam);
4960 rcu_read_unlock();
4962 return retval;
4966 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4967 * @pid: the pid in question.
4968 * @policy: new policy.
4969 * @param: structure containing the new RT priority.
4971 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4972 struct sched_param __user *, param)
4974 /* negative values for policy are not valid */
4975 if (policy < 0)
4976 return -EINVAL;
4978 return do_sched_setscheduler(pid, policy, param);
4982 * sys_sched_setparam - set/change the RT priority of a thread
4983 * @pid: the pid in question.
4984 * @param: structure containing the new RT priority.
4986 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4988 return do_sched_setscheduler(pid, -1, param);
4992 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4993 * @pid: the pid in question.
4995 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4997 struct task_struct *p;
4998 int retval;
5000 if (pid < 0)
5001 return -EINVAL;
5003 retval = -ESRCH;
5004 rcu_read_lock();
5005 p = find_process_by_pid(pid);
5006 if (p) {
5007 retval = security_task_getscheduler(p);
5008 if (!retval)
5009 retval = p->policy
5010 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
5012 rcu_read_unlock();
5013 return retval;
5017 * sys_sched_getparam - get the RT priority of a thread
5018 * @pid: the pid in question.
5019 * @param: structure containing the RT priority.
5021 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
5023 struct sched_param lp;
5024 struct task_struct *p;
5025 int retval;
5027 if (!param || pid < 0)
5028 return -EINVAL;
5030 rcu_read_lock();
5031 p = find_process_by_pid(pid);
5032 retval = -ESRCH;
5033 if (!p)
5034 goto out_unlock;
5036 retval = security_task_getscheduler(p);
5037 if (retval)
5038 goto out_unlock;
5040 lp.sched_priority = p->rt_priority;
5041 rcu_read_unlock();
5044 * This one might sleep, we cannot do it with a spinlock held ...
5046 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5048 return retval;
5050 out_unlock:
5051 rcu_read_unlock();
5052 return retval;
5055 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
5057 cpumask_var_t cpus_allowed, new_mask;
5058 struct task_struct *p;
5059 int retval;
5061 get_online_cpus();
5062 rcu_read_lock();
5064 p = find_process_by_pid(pid);
5065 if (!p) {
5066 rcu_read_unlock();
5067 put_online_cpus();
5068 return -ESRCH;
5071 /* Prevent p going away */
5072 get_task_struct(p);
5073 rcu_read_unlock();
5075 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
5076 retval = -ENOMEM;
5077 goto out_put_task;
5079 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
5080 retval = -ENOMEM;
5081 goto out_free_cpus_allowed;
5083 retval = -EPERM;
5084 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
5085 goto out_unlock;
5087 retval = security_task_setscheduler(p);
5088 if (retval)
5089 goto out_unlock;
5091 cpuset_cpus_allowed(p, cpus_allowed);
5092 cpumask_and(new_mask, in_mask, cpus_allowed);
5093 again:
5094 retval = set_cpus_allowed_ptr(p, new_mask);
5096 if (!retval) {
5097 cpuset_cpus_allowed(p, cpus_allowed);
5098 if (!cpumask_subset(new_mask, cpus_allowed)) {
5100 * We must have raced with a concurrent cpuset
5101 * update. Just reset the cpus_allowed to the
5102 * cpuset's cpus_allowed
5104 cpumask_copy(new_mask, cpus_allowed);
5105 goto again;
5108 out_unlock:
5109 free_cpumask_var(new_mask);
5110 out_free_cpus_allowed:
5111 free_cpumask_var(cpus_allowed);
5112 out_put_task:
5113 put_task_struct(p);
5114 put_online_cpus();
5115 return retval;
5118 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5119 struct cpumask *new_mask)
5121 if (len < cpumask_size())
5122 cpumask_clear(new_mask);
5123 else if (len > cpumask_size())
5124 len = cpumask_size();
5126 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5130 * sys_sched_setaffinity - set the cpu affinity of a process
5131 * @pid: pid of the process
5132 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5133 * @user_mask_ptr: user-space pointer to the new cpu mask
5135 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
5136 unsigned long __user *, user_mask_ptr)
5138 cpumask_var_t new_mask;
5139 int retval;
5141 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
5142 return -ENOMEM;
5144 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
5145 if (retval == 0)
5146 retval = sched_setaffinity(pid, new_mask);
5147 free_cpumask_var(new_mask);
5148 return retval;
5151 long sched_getaffinity(pid_t pid, struct cpumask *mask)
5153 struct task_struct *p;
5154 unsigned long flags;
5155 struct rq *rq;
5156 int retval;
5158 get_online_cpus();
5159 rcu_read_lock();
5161 retval = -ESRCH;
5162 p = find_process_by_pid(pid);
5163 if (!p)
5164 goto out_unlock;
5166 retval = security_task_getscheduler(p);
5167 if (retval)
5168 goto out_unlock;
5170 rq = task_rq_lock(p, &flags);
5171 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
5172 task_rq_unlock(rq, &flags);
5174 out_unlock:
5175 rcu_read_unlock();
5176 put_online_cpus();
5178 return retval;
5182 * sys_sched_getaffinity - get the cpu affinity of a process
5183 * @pid: pid of the process
5184 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5185 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5187 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5188 unsigned long __user *, user_mask_ptr)
5190 int ret;
5191 cpumask_var_t mask;
5193 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5194 return -EINVAL;
5195 if (len & (sizeof(unsigned long)-1))
5196 return -EINVAL;
5198 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5199 return -ENOMEM;
5201 ret = sched_getaffinity(pid, mask);
5202 if (ret == 0) {
5203 size_t retlen = min_t(size_t, len, cpumask_size());
5205 if (copy_to_user(user_mask_ptr, mask, retlen))
5206 ret = -EFAULT;
5207 else
5208 ret = retlen;
5210 free_cpumask_var(mask);
5212 return ret;
5216 * sys_sched_yield - yield the current processor to other threads.
5218 * This function yields the current CPU to other tasks. If there are no
5219 * other threads running on this CPU then this function will return.
5221 SYSCALL_DEFINE0(sched_yield)
5223 struct rq *rq = this_rq_lock();
5225 schedstat_inc(rq, yld_count);
5226 current->sched_class->yield_task(rq);
5229 * Since we are going to call schedule() anyway, there's
5230 * no need to preempt or enable interrupts:
5232 __release(rq->lock);
5233 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5234 do_raw_spin_unlock(&rq->lock);
5235 preempt_enable_no_resched();
5237 schedule();
5239 return 0;
5242 static inline int should_resched(void)
5244 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
5247 static void __cond_resched(void)
5249 add_preempt_count(PREEMPT_ACTIVE);
5250 schedule();
5251 sub_preempt_count(PREEMPT_ACTIVE);
5254 int __sched _cond_resched(void)
5256 if (should_resched()) {
5257 __cond_resched();
5258 return 1;
5260 return 0;
5262 EXPORT_SYMBOL(_cond_resched);
5265 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5266 * call schedule, and on return reacquire the lock.
5268 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5269 * operations here to prevent schedule() from being called twice (once via
5270 * spin_unlock(), once by hand).
5272 int __cond_resched_lock(spinlock_t *lock)
5274 int resched = should_resched();
5275 int ret = 0;
5277 lockdep_assert_held(lock);
5279 if (spin_needbreak(lock) || resched) {
5280 spin_unlock(lock);
5281 if (resched)
5282 __cond_resched();
5283 else
5284 cpu_relax();
5285 ret = 1;
5286 spin_lock(lock);
5288 return ret;
5290 EXPORT_SYMBOL(__cond_resched_lock);
5292 int __sched __cond_resched_softirq(void)
5294 BUG_ON(!in_softirq());
5296 if (should_resched()) {
5297 local_bh_enable();
5298 __cond_resched();
5299 local_bh_disable();
5300 return 1;
5302 return 0;
5304 EXPORT_SYMBOL(__cond_resched_softirq);
5307 * yield - yield the current processor to other threads.
5309 * This is a shortcut for kernel-space yielding - it marks the
5310 * thread runnable and calls sys_sched_yield().
5312 void __sched yield(void)
5314 set_current_state(TASK_RUNNING);
5315 sys_sched_yield();
5317 EXPORT_SYMBOL(yield);
5320 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5321 * that process accounting knows that this is a task in IO wait state.
5323 void __sched io_schedule(void)
5325 struct rq *rq = raw_rq();
5327 delayacct_blkio_start();
5328 atomic_inc(&rq->nr_iowait);
5329 current->in_iowait = 1;
5330 schedule();
5331 current->in_iowait = 0;
5332 atomic_dec(&rq->nr_iowait);
5333 delayacct_blkio_end();
5335 EXPORT_SYMBOL(io_schedule);
5337 long __sched io_schedule_timeout(long timeout)
5339 struct rq *rq = raw_rq();
5340 long ret;
5342 delayacct_blkio_start();
5343 atomic_inc(&rq->nr_iowait);
5344 current->in_iowait = 1;
5345 ret = schedule_timeout(timeout);
5346 current->in_iowait = 0;
5347 atomic_dec(&rq->nr_iowait);
5348 delayacct_blkio_end();
5349 return ret;
5353 * sys_sched_get_priority_max - return maximum RT priority.
5354 * @policy: scheduling class.
5356 * this syscall returns the maximum rt_priority that can be used
5357 * by a given scheduling class.
5359 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5361 int ret = -EINVAL;
5363 switch (policy) {
5364 case SCHED_FIFO:
5365 case SCHED_RR:
5366 ret = MAX_USER_RT_PRIO-1;
5367 break;
5368 case SCHED_NORMAL:
5369 case SCHED_BATCH:
5370 case SCHED_IDLE:
5371 ret = 0;
5372 break;
5374 return ret;
5378 * sys_sched_get_priority_min - return minimum RT priority.
5379 * @policy: scheduling class.
5381 * this syscall returns the minimum rt_priority that can be used
5382 * by a given scheduling class.
5384 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5386 int ret = -EINVAL;
5388 switch (policy) {
5389 case SCHED_FIFO:
5390 case SCHED_RR:
5391 ret = 1;
5392 break;
5393 case SCHED_NORMAL:
5394 case SCHED_BATCH:
5395 case SCHED_IDLE:
5396 ret = 0;
5398 return ret;
5402 * sys_sched_rr_get_interval - return the default timeslice of a process.
5403 * @pid: pid of the process.
5404 * @interval: userspace pointer to the timeslice value.
5406 * this syscall writes the default timeslice value of a given process
5407 * into the user-space timespec buffer. A value of '0' means infinity.
5409 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5410 struct timespec __user *, interval)
5412 struct task_struct *p;
5413 unsigned int time_slice;
5414 unsigned long flags;
5415 struct rq *rq;
5416 int retval;
5417 struct timespec t;
5419 if (pid < 0)
5420 return -EINVAL;
5422 retval = -ESRCH;
5423 rcu_read_lock();
5424 p = find_process_by_pid(pid);
5425 if (!p)
5426 goto out_unlock;
5428 retval = security_task_getscheduler(p);
5429 if (retval)
5430 goto out_unlock;
5432 rq = task_rq_lock(p, &flags);
5433 time_slice = p->sched_class->get_rr_interval(rq, p);
5434 task_rq_unlock(rq, &flags);
5436 rcu_read_unlock();
5437 jiffies_to_timespec(time_slice, &t);
5438 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5439 return retval;
5441 out_unlock:
5442 rcu_read_unlock();
5443 return retval;
5446 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5448 void sched_show_task(struct task_struct *p)
5450 unsigned long free = 0;
5451 unsigned state;
5453 state = p->state ? __ffs(p->state) + 1 : 0;
5454 printk(KERN_INFO "%-15.15s %c", p->comm,
5455 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5456 #if BITS_PER_LONG == 32
5457 if (state == TASK_RUNNING)
5458 printk(KERN_CONT " running ");
5459 else
5460 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5461 #else
5462 if (state == TASK_RUNNING)
5463 printk(KERN_CONT " running task ");
5464 else
5465 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5466 #endif
5467 #ifdef CONFIG_DEBUG_STACK_USAGE
5468 free = stack_not_used(p);
5469 #endif
5470 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5471 task_pid_nr(p), task_pid_nr(p->real_parent),
5472 (unsigned long)task_thread_info(p)->flags);
5474 show_stack(p, NULL);
5477 void show_state_filter(unsigned long state_filter)
5479 struct task_struct *g, *p;
5481 #if BITS_PER_LONG == 32
5482 printk(KERN_INFO
5483 " task PC stack pid father\n");
5484 #else
5485 printk(KERN_INFO
5486 " task PC stack pid father\n");
5487 #endif
5488 read_lock(&tasklist_lock);
5489 do_each_thread(g, p) {
5491 * reset the NMI-timeout, listing all files on a slow
5492 * console might take alot of time:
5494 touch_nmi_watchdog();
5495 if (!state_filter || (p->state & state_filter))
5496 sched_show_task(p);
5497 } while_each_thread(g, p);
5499 touch_all_softlockup_watchdogs();
5501 #ifdef CONFIG_SCHED_DEBUG
5502 sysrq_sched_debug_show();
5503 #endif
5504 read_unlock(&tasklist_lock);
5506 * Only show locks if all tasks are dumped:
5508 if (!state_filter)
5509 debug_show_all_locks();
5512 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5514 idle->sched_class = &idle_sched_class;
5518 * init_idle - set up an idle thread for a given CPU
5519 * @idle: task in question
5520 * @cpu: cpu the idle task belongs to
5522 * NOTE: this function does not set the idle thread's NEED_RESCHED
5523 * flag, to make booting more robust.
5525 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5527 struct rq *rq = cpu_rq(cpu);
5528 unsigned long flags;
5530 raw_spin_lock_irqsave(&rq->lock, flags);
5532 __sched_fork(idle);
5533 idle->state = TASK_RUNNING;
5534 idle->se.exec_start = sched_clock();
5536 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
5538 * We're having a chicken and egg problem, even though we are
5539 * holding rq->lock, the cpu isn't yet set to this cpu so the
5540 * lockdep check in task_group() will fail.
5542 * Similar case to sched_fork(). / Alternatively we could
5543 * use task_rq_lock() here and obtain the other rq->lock.
5545 * Silence PROVE_RCU
5547 rcu_read_lock();
5548 __set_task_cpu(idle, cpu);
5549 rcu_read_unlock();
5551 rq->curr = rq->idle = idle;
5552 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5553 idle->oncpu = 1;
5554 #endif
5555 raw_spin_unlock_irqrestore(&rq->lock, flags);
5557 /* Set the preempt count _outside_ the spinlocks! */
5558 #if defined(CONFIG_PREEMPT)
5559 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5560 #else
5561 task_thread_info(idle)->preempt_count = 0;
5562 #endif
5564 * The idle tasks have their own, simple scheduling class:
5566 idle->sched_class = &idle_sched_class;
5567 ftrace_graph_init_task(idle);
5571 * In a system that switches off the HZ timer nohz_cpu_mask
5572 * indicates which cpus entered this state. This is used
5573 * in the rcu update to wait only for active cpus. For system
5574 * which do not switch off the HZ timer nohz_cpu_mask should
5575 * always be CPU_BITS_NONE.
5577 cpumask_var_t nohz_cpu_mask;
5580 * Increase the granularity value when there are more CPUs,
5581 * because with more CPUs the 'effective latency' as visible
5582 * to users decreases. But the relationship is not linear,
5583 * so pick a second-best guess by going with the log2 of the
5584 * number of CPUs.
5586 * This idea comes from the SD scheduler of Con Kolivas:
5588 static int get_update_sysctl_factor(void)
5590 unsigned int cpus = min_t(int, num_online_cpus(), 8);
5591 unsigned int factor;
5593 switch (sysctl_sched_tunable_scaling) {
5594 case SCHED_TUNABLESCALING_NONE:
5595 factor = 1;
5596 break;
5597 case SCHED_TUNABLESCALING_LINEAR:
5598 factor = cpus;
5599 break;
5600 case SCHED_TUNABLESCALING_LOG:
5601 default:
5602 factor = 1 + ilog2(cpus);
5603 break;
5606 return factor;
5609 static void update_sysctl(void)
5611 unsigned int factor = get_update_sysctl_factor();
5613 #define SET_SYSCTL(name) \
5614 (sysctl_##name = (factor) * normalized_sysctl_##name)
5615 SET_SYSCTL(sched_min_granularity);
5616 SET_SYSCTL(sched_latency);
5617 SET_SYSCTL(sched_wakeup_granularity);
5618 #undef SET_SYSCTL
5621 static inline void sched_init_granularity(void)
5623 update_sysctl();
5626 #ifdef CONFIG_SMP
5628 * This is how migration works:
5630 * 1) we invoke migration_cpu_stop() on the target CPU using
5631 * stop_one_cpu().
5632 * 2) stopper starts to run (implicitly forcing the migrated thread
5633 * off the CPU)
5634 * 3) it checks whether the migrated task is still in the wrong runqueue.
5635 * 4) if it's in the wrong runqueue then the migration thread removes
5636 * it and puts it into the right queue.
5637 * 5) stopper completes and stop_one_cpu() returns and the migration
5638 * is done.
5642 * Change a given task's CPU affinity. Migrate the thread to a
5643 * proper CPU and schedule it away if the CPU it's executing on
5644 * is removed from the allowed bitmask.
5646 * NOTE: the caller must have a valid reference to the task, the
5647 * task must not exit() & deallocate itself prematurely. The
5648 * call is not atomic; no spinlocks may be held.
5650 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
5652 unsigned long flags;
5653 struct rq *rq;
5654 unsigned int dest_cpu;
5655 int ret = 0;
5658 * Serialize against TASK_WAKING so that ttwu() and wunt() can
5659 * drop the rq->lock and still rely on ->cpus_allowed.
5661 again:
5662 while (task_is_waking(p))
5663 cpu_relax();
5664 rq = task_rq_lock(p, &flags);
5665 if (task_is_waking(p)) {
5666 task_rq_unlock(rq, &flags);
5667 goto again;
5670 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
5671 ret = -EINVAL;
5672 goto out;
5675 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
5676 !cpumask_equal(&p->cpus_allowed, new_mask))) {
5677 ret = -EINVAL;
5678 goto out;
5681 if (p->sched_class->set_cpus_allowed)
5682 p->sched_class->set_cpus_allowed(p, new_mask);
5683 else {
5684 cpumask_copy(&p->cpus_allowed, new_mask);
5685 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
5688 /* Can the task run on the task's current CPU? If so, we're done */
5689 if (cpumask_test_cpu(task_cpu(p), new_mask))
5690 goto out;
5692 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
5693 if (migrate_task(p, rq)) {
5694 struct migration_arg arg = { p, dest_cpu };
5695 /* Need help from migration thread: drop lock and wait. */
5696 task_rq_unlock(rq, &flags);
5697 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
5698 tlb_migrate_finish(p->mm);
5699 return 0;
5701 out:
5702 task_rq_unlock(rq, &flags);
5704 return ret;
5706 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5709 * Move (not current) task off this cpu, onto dest cpu. We're doing
5710 * this because either it can't run here any more (set_cpus_allowed()
5711 * away from this CPU, or CPU going down), or because we're
5712 * attempting to rebalance this task on exec (sched_exec).
5714 * So we race with normal scheduler movements, but that's OK, as long
5715 * as the task is no longer on this CPU.
5717 * Returns non-zero if task was successfully migrated.
5719 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5721 struct rq *rq_dest, *rq_src;
5722 int ret = 0;
5724 if (unlikely(!cpu_active(dest_cpu)))
5725 return ret;
5727 rq_src = cpu_rq(src_cpu);
5728 rq_dest = cpu_rq(dest_cpu);
5730 double_rq_lock(rq_src, rq_dest);
5731 /* Already moved. */
5732 if (task_cpu(p) != src_cpu)
5733 goto done;
5734 /* Affinity changed (again). */
5735 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
5736 goto fail;
5739 * If we're not on a rq, the next wake-up will ensure we're
5740 * placed properly.
5742 if (p->se.on_rq) {
5743 deactivate_task(rq_src, p, 0);
5744 set_task_cpu(p, dest_cpu);
5745 activate_task(rq_dest, p, 0);
5746 check_preempt_curr(rq_dest, p, 0);
5748 done:
5749 ret = 1;
5750 fail:
5751 double_rq_unlock(rq_src, rq_dest);
5752 return ret;
5756 * migration_cpu_stop - this will be executed by a highprio stopper thread
5757 * and performs thread migration by bumping thread off CPU then
5758 * 'pushing' onto another runqueue.
5760 static int migration_cpu_stop(void *data)
5762 struct migration_arg *arg = data;
5765 * The original target cpu might have gone down and we might
5766 * be on another cpu but it doesn't matter.
5768 local_irq_disable();
5769 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
5770 local_irq_enable();
5771 return 0;
5774 #ifdef CONFIG_HOTPLUG_CPU
5777 * Ensures that the idle task is using init_mm right before its cpu goes
5778 * offline.
5780 void idle_task_exit(void)
5782 struct mm_struct *mm = current->active_mm;
5784 BUG_ON(cpu_online(smp_processor_id()));
5786 if (mm != &init_mm)
5787 switch_mm(mm, &init_mm, current);
5788 mmdrop(mm);
5792 * While a dead CPU has no uninterruptible tasks queued at this point,
5793 * it might still have a nonzero ->nr_uninterruptible counter, because
5794 * for performance reasons the counter is not stricly tracking tasks to
5795 * their home CPUs. So we just add the counter to another CPU's counter,
5796 * to keep the global sum constant after CPU-down:
5798 static void migrate_nr_uninterruptible(struct rq *rq_src)
5800 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
5802 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5803 rq_src->nr_uninterruptible = 0;
5807 * remove the tasks which were accounted by rq from calc_load_tasks.
5809 static void calc_global_load_remove(struct rq *rq)
5811 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
5812 rq->calc_load_active = 0;
5816 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5817 * try_to_wake_up()->select_task_rq().
5819 * Called with rq->lock held even though we'er in stop_machine() and
5820 * there's no concurrency possible, we hold the required locks anyway
5821 * because of lock validation efforts.
5823 static void migrate_tasks(unsigned int dead_cpu)
5825 struct rq *rq = cpu_rq(dead_cpu);
5826 struct task_struct *next, *stop = rq->stop;
5827 int dest_cpu;
5830 * Fudge the rq selection such that the below task selection loop
5831 * doesn't get stuck on the currently eligible stop task.
5833 * We're currently inside stop_machine() and the rq is either stuck
5834 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5835 * either way we should never end up calling schedule() until we're
5836 * done here.
5838 rq->stop = NULL;
5840 for ( ; ; ) {
5842 * There's this thread running, bail when that's the only
5843 * remaining thread.
5845 if (rq->nr_running == 1)
5846 break;
5848 next = pick_next_task(rq);
5849 BUG_ON(!next);
5850 next->sched_class->put_prev_task(rq, next);
5852 /* Find suitable destination for @next, with force if needed. */
5853 dest_cpu = select_fallback_rq(dead_cpu, next);
5854 raw_spin_unlock(&rq->lock);
5856 __migrate_task(next, dead_cpu, dest_cpu);
5858 raw_spin_lock(&rq->lock);
5861 rq->stop = stop;
5864 #endif /* CONFIG_HOTPLUG_CPU */
5866 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5868 static struct ctl_table sd_ctl_dir[] = {
5870 .procname = "sched_domain",
5871 .mode = 0555,
5876 static struct ctl_table sd_ctl_root[] = {
5878 .procname = "kernel",
5879 .mode = 0555,
5880 .child = sd_ctl_dir,
5885 static struct ctl_table *sd_alloc_ctl_entry(int n)
5887 struct ctl_table *entry =
5888 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5890 return entry;
5893 static void sd_free_ctl_entry(struct ctl_table **tablep)
5895 struct ctl_table *entry;
5898 * In the intermediate directories, both the child directory and
5899 * procname are dynamically allocated and could fail but the mode
5900 * will always be set. In the lowest directory the names are
5901 * static strings and all have proc handlers.
5903 for (entry = *tablep; entry->mode; entry++) {
5904 if (entry->child)
5905 sd_free_ctl_entry(&entry->child);
5906 if (entry->proc_handler == NULL)
5907 kfree(entry->procname);
5910 kfree(*tablep);
5911 *tablep = NULL;
5914 static void
5915 set_table_entry(struct ctl_table *entry,
5916 const char *procname, void *data, int maxlen,
5917 mode_t mode, proc_handler *proc_handler)
5919 entry->procname = procname;
5920 entry->data = data;
5921 entry->maxlen = maxlen;
5922 entry->mode = mode;
5923 entry->proc_handler = proc_handler;
5926 static struct ctl_table *
5927 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5929 struct ctl_table *table = sd_alloc_ctl_entry(13);
5931 if (table == NULL)
5932 return NULL;
5934 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5935 sizeof(long), 0644, proc_doulongvec_minmax);
5936 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5937 sizeof(long), 0644, proc_doulongvec_minmax);
5938 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5939 sizeof(int), 0644, proc_dointvec_minmax);
5940 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5941 sizeof(int), 0644, proc_dointvec_minmax);
5942 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5943 sizeof(int), 0644, proc_dointvec_minmax);
5944 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5945 sizeof(int), 0644, proc_dointvec_minmax);
5946 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5947 sizeof(int), 0644, proc_dointvec_minmax);
5948 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5949 sizeof(int), 0644, proc_dointvec_minmax);
5950 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5951 sizeof(int), 0644, proc_dointvec_minmax);
5952 set_table_entry(&table[9], "cache_nice_tries",
5953 &sd->cache_nice_tries,
5954 sizeof(int), 0644, proc_dointvec_minmax);
5955 set_table_entry(&table[10], "flags", &sd->flags,
5956 sizeof(int), 0644, proc_dointvec_minmax);
5957 set_table_entry(&table[11], "name", sd->name,
5958 CORENAME_MAX_SIZE, 0444, proc_dostring);
5959 /* &table[12] is terminator */
5961 return table;
5964 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5966 struct ctl_table *entry, *table;
5967 struct sched_domain *sd;
5968 int domain_num = 0, i;
5969 char buf[32];
5971 for_each_domain(cpu, sd)
5972 domain_num++;
5973 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5974 if (table == NULL)
5975 return NULL;
5977 i = 0;
5978 for_each_domain(cpu, sd) {
5979 snprintf(buf, 32, "domain%d", i);
5980 entry->procname = kstrdup(buf, GFP_KERNEL);
5981 entry->mode = 0555;
5982 entry->child = sd_alloc_ctl_domain_table(sd);
5983 entry++;
5984 i++;
5986 return table;
5989 static struct ctl_table_header *sd_sysctl_header;
5990 static void register_sched_domain_sysctl(void)
5992 int i, cpu_num = num_possible_cpus();
5993 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5994 char buf[32];
5996 WARN_ON(sd_ctl_dir[0].child);
5997 sd_ctl_dir[0].child = entry;
5999 if (entry == NULL)
6000 return;
6002 for_each_possible_cpu(i) {
6003 snprintf(buf, 32, "cpu%d", i);
6004 entry->procname = kstrdup(buf, GFP_KERNEL);
6005 entry->mode = 0555;
6006 entry->child = sd_alloc_ctl_cpu_table(i);
6007 entry++;
6010 WARN_ON(sd_sysctl_header);
6011 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6014 /* may be called multiple times per register */
6015 static void unregister_sched_domain_sysctl(void)
6017 if (sd_sysctl_header)
6018 unregister_sysctl_table(sd_sysctl_header);
6019 sd_sysctl_header = NULL;
6020 if (sd_ctl_dir[0].child)
6021 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6023 #else
6024 static void register_sched_domain_sysctl(void)
6027 static void unregister_sched_domain_sysctl(void)
6030 #endif
6032 static void set_rq_online(struct rq *rq)
6034 if (!rq->online) {
6035 const struct sched_class *class;
6037 cpumask_set_cpu(rq->cpu, rq->rd->online);
6038 rq->online = 1;
6040 for_each_class(class) {
6041 if (class->rq_online)
6042 class->rq_online(rq);
6047 static void set_rq_offline(struct rq *rq)
6049 if (rq->online) {
6050 const struct sched_class *class;
6052 for_each_class(class) {
6053 if (class->rq_offline)
6054 class->rq_offline(rq);
6057 cpumask_clear_cpu(rq->cpu, rq->rd->online);
6058 rq->online = 0;
6063 * migration_call - callback that gets triggered when a CPU is added.
6064 * Here we can start up the necessary migration thread for the new CPU.
6066 static int __cpuinit
6067 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6069 int cpu = (long)hcpu;
6070 unsigned long flags;
6071 struct rq *rq = cpu_rq(cpu);
6073 switch (action & ~CPU_TASKS_FROZEN) {
6075 case CPU_UP_PREPARE:
6076 rq->calc_load_update = calc_load_update;
6077 break;
6079 case CPU_ONLINE:
6080 /* Update our root-domain */
6081 raw_spin_lock_irqsave(&rq->lock, flags);
6082 if (rq->rd) {
6083 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6085 set_rq_online(rq);
6087 raw_spin_unlock_irqrestore(&rq->lock, flags);
6088 break;
6090 #ifdef CONFIG_HOTPLUG_CPU
6091 case CPU_DYING:
6092 /* Update our root-domain */
6093 raw_spin_lock_irqsave(&rq->lock, flags);
6094 if (rq->rd) {
6095 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6096 set_rq_offline(rq);
6098 migrate_tasks(cpu);
6099 BUG_ON(rq->nr_running != 1); /* the migration thread */
6100 raw_spin_unlock_irqrestore(&rq->lock, flags);
6102 migrate_nr_uninterruptible(rq);
6103 calc_global_load_remove(rq);
6104 break;
6105 #endif
6107 return NOTIFY_OK;
6111 * Register at high priority so that task migration (migrate_all_tasks)
6112 * happens before everything else. This has to be lower priority than
6113 * the notifier in the perf_event subsystem, though.
6115 static struct notifier_block __cpuinitdata migration_notifier = {
6116 .notifier_call = migration_call,
6117 .priority = CPU_PRI_MIGRATION,
6120 static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
6121 unsigned long action, void *hcpu)
6123 switch (action & ~CPU_TASKS_FROZEN) {
6124 case CPU_ONLINE:
6125 case CPU_DOWN_FAILED:
6126 set_cpu_active((long)hcpu, true);
6127 return NOTIFY_OK;
6128 default:
6129 return NOTIFY_DONE;
6133 static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
6134 unsigned long action, void *hcpu)
6136 switch (action & ~CPU_TASKS_FROZEN) {
6137 case CPU_DOWN_PREPARE:
6138 set_cpu_active((long)hcpu, false);
6139 return NOTIFY_OK;
6140 default:
6141 return NOTIFY_DONE;
6145 static int __init migration_init(void)
6147 void *cpu = (void *)(long)smp_processor_id();
6148 int err;
6150 /* Initialize migration for the boot CPU */
6151 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6152 BUG_ON(err == NOTIFY_BAD);
6153 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6154 register_cpu_notifier(&migration_notifier);
6156 /* Register cpu active notifiers */
6157 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
6158 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
6160 return 0;
6162 early_initcall(migration_init);
6163 #endif
6165 #ifdef CONFIG_SMP
6167 #ifdef CONFIG_SCHED_DEBUG
6169 static __read_mostly int sched_domain_debug_enabled;
6171 static int __init sched_domain_debug_setup(char *str)
6173 sched_domain_debug_enabled = 1;
6175 return 0;
6177 early_param("sched_debug", sched_domain_debug_setup);
6179 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6180 struct cpumask *groupmask)
6182 struct sched_group *group = sd->groups;
6183 char str[256];
6185 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
6186 cpumask_clear(groupmask);
6188 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6190 if (!(sd->flags & SD_LOAD_BALANCE)) {
6191 printk("does not load-balance\n");
6192 if (sd->parent)
6193 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6194 " has parent");
6195 return -1;
6198 printk(KERN_CONT "span %s level %s\n", str, sd->name);
6200 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6201 printk(KERN_ERR "ERROR: domain->span does not contain "
6202 "CPU%d\n", cpu);
6204 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6205 printk(KERN_ERR "ERROR: domain->groups does not contain"
6206 " CPU%d\n", cpu);
6209 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6210 do {
6211 if (!group) {
6212 printk("\n");
6213 printk(KERN_ERR "ERROR: group is NULL\n");
6214 break;
6217 if (!group->cpu_power) {
6218 printk(KERN_CONT "\n");
6219 printk(KERN_ERR "ERROR: domain->cpu_power not "
6220 "set\n");
6221 break;
6224 if (!cpumask_weight(sched_group_cpus(group))) {
6225 printk(KERN_CONT "\n");
6226 printk(KERN_ERR "ERROR: empty group\n");
6227 break;
6230 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6231 printk(KERN_CONT "\n");
6232 printk(KERN_ERR "ERROR: repeated CPUs\n");
6233 break;
6236 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6238 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6240 printk(KERN_CONT " %s", str);
6241 if (group->cpu_power != SCHED_LOAD_SCALE) {
6242 printk(KERN_CONT " (cpu_power = %d)",
6243 group->cpu_power);
6246 group = group->next;
6247 } while (group != sd->groups);
6248 printk(KERN_CONT "\n");
6250 if (!cpumask_equal(sched_domain_span(sd), groupmask))
6251 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6253 if (sd->parent &&
6254 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6255 printk(KERN_ERR "ERROR: parent span is not a superset "
6256 "of domain->span\n");
6257 return 0;
6260 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6262 cpumask_var_t groupmask;
6263 int level = 0;
6265 if (!sched_domain_debug_enabled)
6266 return;
6268 if (!sd) {
6269 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6270 return;
6273 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6275 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
6276 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6277 return;
6280 for (;;) {
6281 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6282 break;
6283 level++;
6284 sd = sd->parent;
6285 if (!sd)
6286 break;
6288 free_cpumask_var(groupmask);
6290 #else /* !CONFIG_SCHED_DEBUG */
6291 # define sched_domain_debug(sd, cpu) do { } while (0)
6292 #endif /* CONFIG_SCHED_DEBUG */
6294 static int sd_degenerate(struct sched_domain *sd)
6296 if (cpumask_weight(sched_domain_span(sd)) == 1)
6297 return 1;
6299 /* Following flags need at least 2 groups */
6300 if (sd->flags & (SD_LOAD_BALANCE |
6301 SD_BALANCE_NEWIDLE |
6302 SD_BALANCE_FORK |
6303 SD_BALANCE_EXEC |
6304 SD_SHARE_CPUPOWER |
6305 SD_SHARE_PKG_RESOURCES)) {
6306 if (sd->groups != sd->groups->next)
6307 return 0;
6310 /* Following flags don't use groups */
6311 if (sd->flags & (SD_WAKE_AFFINE))
6312 return 0;
6314 return 1;
6317 static int
6318 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6320 unsigned long cflags = sd->flags, pflags = parent->flags;
6322 if (sd_degenerate(parent))
6323 return 1;
6325 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6326 return 0;
6328 /* Flags needing groups don't count if only 1 group in parent */
6329 if (parent->groups == parent->groups->next) {
6330 pflags &= ~(SD_LOAD_BALANCE |
6331 SD_BALANCE_NEWIDLE |
6332 SD_BALANCE_FORK |
6333 SD_BALANCE_EXEC |
6334 SD_SHARE_CPUPOWER |
6335 SD_SHARE_PKG_RESOURCES);
6336 if (nr_node_ids == 1)
6337 pflags &= ~SD_SERIALIZE;
6339 if (~cflags & pflags)
6340 return 0;
6342 return 1;
6345 static void free_rootdomain(struct root_domain *rd)
6347 synchronize_sched();
6349 cpupri_cleanup(&rd->cpupri);
6351 free_cpumask_var(rd->rto_mask);
6352 free_cpumask_var(rd->online);
6353 free_cpumask_var(rd->span);
6354 kfree(rd);
6357 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6359 struct root_domain *old_rd = NULL;
6360 unsigned long flags;
6362 raw_spin_lock_irqsave(&rq->lock, flags);
6364 if (rq->rd) {
6365 old_rd = rq->rd;
6367 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6368 set_rq_offline(rq);
6370 cpumask_clear_cpu(rq->cpu, old_rd->span);
6373 * If we dont want to free the old_rt yet then
6374 * set old_rd to NULL to skip the freeing later
6375 * in this function:
6377 if (!atomic_dec_and_test(&old_rd->refcount))
6378 old_rd = NULL;
6381 atomic_inc(&rd->refcount);
6382 rq->rd = rd;
6384 cpumask_set_cpu(rq->cpu, rd->span);
6385 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6386 set_rq_online(rq);
6388 raw_spin_unlock_irqrestore(&rq->lock, flags);
6390 if (old_rd)
6391 free_rootdomain(old_rd);
6394 static int init_rootdomain(struct root_domain *rd)
6396 memset(rd, 0, sizeof(*rd));
6398 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
6399 goto out;
6400 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
6401 goto free_span;
6402 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6403 goto free_online;
6405 if (cpupri_init(&rd->cpupri) != 0)
6406 goto free_rto_mask;
6407 return 0;
6409 free_rto_mask:
6410 free_cpumask_var(rd->rto_mask);
6411 free_online:
6412 free_cpumask_var(rd->online);
6413 free_span:
6414 free_cpumask_var(rd->span);
6415 out:
6416 return -ENOMEM;
6419 static void init_defrootdomain(void)
6421 init_rootdomain(&def_root_domain);
6423 atomic_set(&def_root_domain.refcount, 1);
6426 static struct root_domain *alloc_rootdomain(void)
6428 struct root_domain *rd;
6430 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6431 if (!rd)
6432 return NULL;
6434 if (init_rootdomain(rd) != 0) {
6435 kfree(rd);
6436 return NULL;
6439 return rd;
6443 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6444 * hold the hotplug lock.
6446 static void
6447 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6449 struct rq *rq = cpu_rq(cpu);
6450 struct sched_domain *tmp;
6452 for (tmp = sd; tmp; tmp = tmp->parent)
6453 tmp->span_weight = cpumask_weight(sched_domain_span(tmp));
6455 /* Remove the sched domains which do not contribute to scheduling. */
6456 for (tmp = sd; tmp; ) {
6457 struct sched_domain *parent = tmp->parent;
6458 if (!parent)
6459 break;
6461 if (sd_parent_degenerate(tmp, parent)) {
6462 tmp->parent = parent->parent;
6463 if (parent->parent)
6464 parent->parent->child = tmp;
6465 } else
6466 tmp = tmp->parent;
6469 if (sd && sd_degenerate(sd)) {
6470 sd = sd->parent;
6471 if (sd)
6472 sd->child = NULL;
6475 sched_domain_debug(sd, cpu);
6477 rq_attach_root(rq, rd);
6478 rcu_assign_pointer(rq->sd, sd);
6481 /* cpus with isolated domains */
6482 static cpumask_var_t cpu_isolated_map;
6484 /* Setup the mask of cpus configured for isolated domains */
6485 static int __init isolated_cpu_setup(char *str)
6487 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6488 cpulist_parse(str, cpu_isolated_map);
6489 return 1;
6492 __setup("isolcpus=", isolated_cpu_setup);
6495 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6496 * to a function which identifies what group(along with sched group) a CPU
6497 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
6498 * (due to the fact that we keep track of groups covered with a struct cpumask).
6500 * init_sched_build_groups will build a circular linked list of the groups
6501 * covered by the given span, and will set each group's ->cpumask correctly,
6502 * and ->cpu_power to 0.
6504 static void
6505 init_sched_build_groups(const struct cpumask *span,
6506 const struct cpumask *cpu_map,
6507 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
6508 struct sched_group **sg,
6509 struct cpumask *tmpmask),
6510 struct cpumask *covered, struct cpumask *tmpmask)
6512 struct sched_group *first = NULL, *last = NULL;
6513 int i;
6515 cpumask_clear(covered);
6517 for_each_cpu(i, span) {
6518 struct sched_group *sg;
6519 int group = group_fn(i, cpu_map, &sg, tmpmask);
6520 int j;
6522 if (cpumask_test_cpu(i, covered))
6523 continue;
6525 cpumask_clear(sched_group_cpus(sg));
6526 sg->cpu_power = 0;
6528 for_each_cpu(j, span) {
6529 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6530 continue;
6532 cpumask_set_cpu(j, covered);
6533 cpumask_set_cpu(j, sched_group_cpus(sg));
6535 if (!first)
6536 first = sg;
6537 if (last)
6538 last->next = sg;
6539 last = sg;
6541 last->next = first;
6544 #define SD_NODES_PER_DOMAIN 16
6546 #ifdef CONFIG_NUMA
6549 * find_next_best_node - find the next node to include in a sched_domain
6550 * @node: node whose sched_domain we're building
6551 * @used_nodes: nodes already in the sched_domain
6553 * Find the next node to include in a given scheduling domain. Simply
6554 * finds the closest node not already in the @used_nodes map.
6556 * Should use nodemask_t.
6558 static int find_next_best_node(int node, nodemask_t *used_nodes)
6560 int i, n, val, min_val, best_node = 0;
6562 min_val = INT_MAX;
6564 for (i = 0; i < nr_node_ids; i++) {
6565 /* Start at @node */
6566 n = (node + i) % nr_node_ids;
6568 if (!nr_cpus_node(n))
6569 continue;
6571 /* Skip already used nodes */
6572 if (node_isset(n, *used_nodes))
6573 continue;
6575 /* Simple min distance search */
6576 val = node_distance(node, n);
6578 if (val < min_val) {
6579 min_val = val;
6580 best_node = n;
6584 node_set(best_node, *used_nodes);
6585 return best_node;
6589 * sched_domain_node_span - get a cpumask for a node's sched_domain
6590 * @node: node whose cpumask we're constructing
6591 * @span: resulting cpumask
6593 * Given a node, construct a good cpumask for its sched_domain to span. It
6594 * should be one that prevents unnecessary balancing, but also spreads tasks
6595 * out optimally.
6597 static void sched_domain_node_span(int node, struct cpumask *span)
6599 nodemask_t used_nodes;
6600 int i;
6602 cpumask_clear(span);
6603 nodes_clear(used_nodes);
6605 cpumask_or(span, span, cpumask_of_node(node));
6606 node_set(node, used_nodes);
6608 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6609 int next_node = find_next_best_node(node, &used_nodes);
6611 cpumask_or(span, span, cpumask_of_node(next_node));
6614 #endif /* CONFIG_NUMA */
6616 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6619 * The cpus mask in sched_group and sched_domain hangs off the end.
6621 * ( See the the comments in include/linux/sched.h:struct sched_group
6622 * and struct sched_domain. )
6624 struct static_sched_group {
6625 struct sched_group sg;
6626 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
6629 struct static_sched_domain {
6630 struct sched_domain sd;
6631 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
6634 struct s_data {
6635 #ifdef CONFIG_NUMA
6636 int sd_allnodes;
6637 cpumask_var_t domainspan;
6638 cpumask_var_t covered;
6639 cpumask_var_t notcovered;
6640 #endif
6641 cpumask_var_t nodemask;
6642 cpumask_var_t this_sibling_map;
6643 cpumask_var_t this_core_map;
6644 cpumask_var_t this_book_map;
6645 cpumask_var_t send_covered;
6646 cpumask_var_t tmpmask;
6647 struct sched_group **sched_group_nodes;
6648 struct root_domain *rd;
6651 enum s_alloc {
6652 sa_sched_groups = 0,
6653 sa_rootdomain,
6654 sa_tmpmask,
6655 sa_send_covered,
6656 sa_this_book_map,
6657 sa_this_core_map,
6658 sa_this_sibling_map,
6659 sa_nodemask,
6660 sa_sched_group_nodes,
6661 #ifdef CONFIG_NUMA
6662 sa_notcovered,
6663 sa_covered,
6664 sa_domainspan,
6665 #endif
6666 sa_none,
6670 * SMT sched-domains:
6672 #ifdef CONFIG_SCHED_SMT
6673 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
6674 static DEFINE_PER_CPU(struct static_sched_group, sched_groups);
6676 static int
6677 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
6678 struct sched_group **sg, struct cpumask *unused)
6680 if (sg)
6681 *sg = &per_cpu(sched_groups, cpu).sg;
6682 return cpu;
6684 #endif /* CONFIG_SCHED_SMT */
6687 * multi-core sched-domains:
6689 #ifdef CONFIG_SCHED_MC
6690 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
6691 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
6693 static int
6694 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
6695 struct sched_group **sg, struct cpumask *mask)
6697 int group;
6698 #ifdef CONFIG_SCHED_SMT
6699 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6700 group = cpumask_first(mask);
6701 #else
6702 group = cpu;
6703 #endif
6704 if (sg)
6705 *sg = &per_cpu(sched_group_core, group).sg;
6706 return group;
6708 #endif /* CONFIG_SCHED_MC */
6711 * book sched-domains:
6713 #ifdef CONFIG_SCHED_BOOK
6714 static DEFINE_PER_CPU(struct static_sched_domain, book_domains);
6715 static DEFINE_PER_CPU(struct static_sched_group, sched_group_book);
6717 static int
6718 cpu_to_book_group(int cpu, const struct cpumask *cpu_map,
6719 struct sched_group **sg, struct cpumask *mask)
6721 int group = cpu;
6722 #ifdef CONFIG_SCHED_MC
6723 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6724 group = cpumask_first(mask);
6725 #elif defined(CONFIG_SCHED_SMT)
6726 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6727 group = cpumask_first(mask);
6728 #endif
6729 if (sg)
6730 *sg = &per_cpu(sched_group_book, group).sg;
6731 return group;
6733 #endif /* CONFIG_SCHED_BOOK */
6735 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
6736 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
6738 static int
6739 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
6740 struct sched_group **sg, struct cpumask *mask)
6742 int group;
6743 #ifdef CONFIG_SCHED_BOOK
6744 cpumask_and(mask, cpu_book_mask(cpu), cpu_map);
6745 group = cpumask_first(mask);
6746 #elif defined(CONFIG_SCHED_MC)
6747 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6748 group = cpumask_first(mask);
6749 #elif defined(CONFIG_SCHED_SMT)
6750 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6751 group = cpumask_first(mask);
6752 #else
6753 group = cpu;
6754 #endif
6755 if (sg)
6756 *sg = &per_cpu(sched_group_phys, group).sg;
6757 return group;
6760 #ifdef CONFIG_NUMA
6762 * The init_sched_build_groups can't handle what we want to do with node
6763 * groups, so roll our own. Now each node has its own list of groups which
6764 * gets dynamically allocated.
6766 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
6767 static struct sched_group ***sched_group_nodes_bycpu;
6769 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
6770 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
6772 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
6773 struct sched_group **sg,
6774 struct cpumask *nodemask)
6776 int group;
6778 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
6779 group = cpumask_first(nodemask);
6781 if (sg)
6782 *sg = &per_cpu(sched_group_allnodes, group).sg;
6783 return group;
6786 static void init_numa_sched_groups_power(struct sched_group *group_head)
6788 struct sched_group *sg = group_head;
6789 int j;
6791 if (!sg)
6792 return;
6793 do {
6794 for_each_cpu(j, sched_group_cpus(sg)) {
6795 struct sched_domain *sd;
6797 sd = &per_cpu(phys_domains, j).sd;
6798 if (j != group_first_cpu(sd->groups)) {
6800 * Only add "power" once for each
6801 * physical package.
6803 continue;
6806 sg->cpu_power += sd->groups->cpu_power;
6808 sg = sg->next;
6809 } while (sg != group_head);
6812 static int build_numa_sched_groups(struct s_data *d,
6813 const struct cpumask *cpu_map, int num)
6815 struct sched_domain *sd;
6816 struct sched_group *sg, *prev;
6817 int n, j;
6819 cpumask_clear(d->covered);
6820 cpumask_and(d->nodemask, cpumask_of_node(num), cpu_map);
6821 if (cpumask_empty(d->nodemask)) {
6822 d->sched_group_nodes[num] = NULL;
6823 goto out;
6826 sched_domain_node_span(num, d->domainspan);
6827 cpumask_and(d->domainspan, d->domainspan, cpu_map);
6829 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6830 GFP_KERNEL, num);
6831 if (!sg) {
6832 printk(KERN_WARNING "Can not alloc domain group for node %d\n",
6833 num);
6834 return -ENOMEM;
6836 d->sched_group_nodes[num] = sg;
6838 for_each_cpu(j, d->nodemask) {
6839 sd = &per_cpu(node_domains, j).sd;
6840 sd->groups = sg;
6843 sg->cpu_power = 0;
6844 cpumask_copy(sched_group_cpus(sg), d->nodemask);
6845 sg->next = sg;
6846 cpumask_or(d->covered, d->covered, d->nodemask);
6848 prev = sg;
6849 for (j = 0; j < nr_node_ids; j++) {
6850 n = (num + j) % nr_node_ids;
6851 cpumask_complement(d->notcovered, d->covered);
6852 cpumask_and(d->tmpmask, d->notcovered, cpu_map);
6853 cpumask_and(d->tmpmask, d->tmpmask, d->domainspan);
6854 if (cpumask_empty(d->tmpmask))
6855 break;
6856 cpumask_and(d->tmpmask, d->tmpmask, cpumask_of_node(n));
6857 if (cpumask_empty(d->tmpmask))
6858 continue;
6859 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6860 GFP_KERNEL, num);
6861 if (!sg) {
6862 printk(KERN_WARNING
6863 "Can not alloc domain group for node %d\n", j);
6864 return -ENOMEM;
6866 sg->cpu_power = 0;
6867 cpumask_copy(sched_group_cpus(sg), d->tmpmask);
6868 sg->next = prev->next;
6869 cpumask_or(d->covered, d->covered, d->tmpmask);
6870 prev->next = sg;
6871 prev = sg;
6873 out:
6874 return 0;
6876 #endif /* CONFIG_NUMA */
6878 #ifdef CONFIG_NUMA
6879 /* Free memory allocated for various sched_group structures */
6880 static void free_sched_groups(const struct cpumask *cpu_map,
6881 struct cpumask *nodemask)
6883 int cpu, i;
6885 for_each_cpu(cpu, cpu_map) {
6886 struct sched_group **sched_group_nodes
6887 = sched_group_nodes_bycpu[cpu];
6889 if (!sched_group_nodes)
6890 continue;
6892 for (i = 0; i < nr_node_ids; i++) {
6893 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6895 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
6896 if (cpumask_empty(nodemask))
6897 continue;
6899 if (sg == NULL)
6900 continue;
6901 sg = sg->next;
6902 next_sg:
6903 oldsg = sg;
6904 sg = sg->next;
6905 kfree(oldsg);
6906 if (oldsg != sched_group_nodes[i])
6907 goto next_sg;
6909 kfree(sched_group_nodes);
6910 sched_group_nodes_bycpu[cpu] = NULL;
6913 #else /* !CONFIG_NUMA */
6914 static void free_sched_groups(const struct cpumask *cpu_map,
6915 struct cpumask *nodemask)
6918 #endif /* CONFIG_NUMA */
6921 * Initialize sched groups cpu_power.
6923 * cpu_power indicates the capacity of sched group, which is used while
6924 * distributing the load between different sched groups in a sched domain.
6925 * Typically cpu_power for all the groups in a sched domain will be same unless
6926 * there are asymmetries in the topology. If there are asymmetries, group
6927 * having more cpu_power will pickup more load compared to the group having
6928 * less cpu_power.
6930 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6932 struct sched_domain *child;
6933 struct sched_group *group;
6934 long power;
6935 int weight;
6937 WARN_ON(!sd || !sd->groups);
6939 if (cpu != group_first_cpu(sd->groups))
6940 return;
6942 sd->groups->group_weight = cpumask_weight(sched_group_cpus(sd->groups));
6944 child = sd->child;
6946 sd->groups->cpu_power = 0;
6948 if (!child) {
6949 power = SCHED_LOAD_SCALE;
6950 weight = cpumask_weight(sched_domain_span(sd));
6952 * SMT siblings share the power of a single core.
6953 * Usually multiple threads get a better yield out of
6954 * that one core than a single thread would have,
6955 * reflect that in sd->smt_gain.
6957 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
6958 power *= sd->smt_gain;
6959 power /= weight;
6960 power >>= SCHED_LOAD_SHIFT;
6962 sd->groups->cpu_power += power;
6963 return;
6967 * Add cpu_power of each child group to this groups cpu_power.
6969 group = child->groups;
6970 do {
6971 sd->groups->cpu_power += group->cpu_power;
6972 group = group->next;
6973 } while (group != child->groups);
6977 * Initializers for schedule domains
6978 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6981 #ifdef CONFIG_SCHED_DEBUG
6982 # define SD_INIT_NAME(sd, type) sd->name = #type
6983 #else
6984 # define SD_INIT_NAME(sd, type) do { } while (0)
6985 #endif
6987 #define SD_INIT(sd, type) sd_init_##type(sd)
6989 #define SD_INIT_FUNC(type) \
6990 static noinline void sd_init_##type(struct sched_domain *sd) \
6992 memset(sd, 0, sizeof(*sd)); \
6993 *sd = SD_##type##_INIT; \
6994 sd->level = SD_LV_##type; \
6995 SD_INIT_NAME(sd, type); \
6998 SD_INIT_FUNC(CPU)
6999 #ifdef CONFIG_NUMA
7000 SD_INIT_FUNC(ALLNODES)
7001 SD_INIT_FUNC(NODE)
7002 #endif
7003 #ifdef CONFIG_SCHED_SMT
7004 SD_INIT_FUNC(SIBLING)
7005 #endif
7006 #ifdef CONFIG_SCHED_MC
7007 SD_INIT_FUNC(MC)
7008 #endif
7009 #ifdef CONFIG_SCHED_BOOK
7010 SD_INIT_FUNC(BOOK)
7011 #endif
7013 static int default_relax_domain_level = -1;
7015 static int __init setup_relax_domain_level(char *str)
7017 unsigned long val;
7019 val = simple_strtoul(str, NULL, 0);
7020 if (val < SD_LV_MAX)
7021 default_relax_domain_level = val;
7023 return 1;
7025 __setup("relax_domain_level=", setup_relax_domain_level);
7027 static void set_domain_attribute(struct sched_domain *sd,
7028 struct sched_domain_attr *attr)
7030 int request;
7032 if (!attr || attr->relax_domain_level < 0) {
7033 if (default_relax_domain_level < 0)
7034 return;
7035 else
7036 request = default_relax_domain_level;
7037 } else
7038 request = attr->relax_domain_level;
7039 if (request < sd->level) {
7040 /* turn off idle balance on this domain */
7041 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
7042 } else {
7043 /* turn on idle balance on this domain */
7044 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
7048 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
7049 const struct cpumask *cpu_map)
7051 switch (what) {
7052 case sa_sched_groups:
7053 free_sched_groups(cpu_map, d->tmpmask); /* fall through */
7054 d->sched_group_nodes = NULL;
7055 case sa_rootdomain:
7056 free_rootdomain(d->rd); /* fall through */
7057 case sa_tmpmask:
7058 free_cpumask_var(d->tmpmask); /* fall through */
7059 case sa_send_covered:
7060 free_cpumask_var(d->send_covered); /* fall through */
7061 case sa_this_book_map:
7062 free_cpumask_var(d->this_book_map); /* fall through */
7063 case sa_this_core_map:
7064 free_cpumask_var(d->this_core_map); /* fall through */
7065 case sa_this_sibling_map:
7066 free_cpumask_var(d->this_sibling_map); /* fall through */
7067 case sa_nodemask:
7068 free_cpumask_var(d->nodemask); /* fall through */
7069 case sa_sched_group_nodes:
7070 #ifdef CONFIG_NUMA
7071 kfree(d->sched_group_nodes); /* fall through */
7072 case sa_notcovered:
7073 free_cpumask_var(d->notcovered); /* fall through */
7074 case sa_covered:
7075 free_cpumask_var(d->covered); /* fall through */
7076 case sa_domainspan:
7077 free_cpumask_var(d->domainspan); /* fall through */
7078 #endif
7079 case sa_none:
7080 break;
7084 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
7085 const struct cpumask *cpu_map)
7087 #ifdef CONFIG_NUMA
7088 if (!alloc_cpumask_var(&d->domainspan, GFP_KERNEL))
7089 return sa_none;
7090 if (!alloc_cpumask_var(&d->covered, GFP_KERNEL))
7091 return sa_domainspan;
7092 if (!alloc_cpumask_var(&d->notcovered, GFP_KERNEL))
7093 return sa_covered;
7094 /* Allocate the per-node list of sched groups */
7095 d->sched_group_nodes = kcalloc(nr_node_ids,
7096 sizeof(struct sched_group *), GFP_KERNEL);
7097 if (!d->sched_group_nodes) {
7098 printk(KERN_WARNING "Can not alloc sched group node list\n");
7099 return sa_notcovered;
7101 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = d->sched_group_nodes;
7102 #endif
7103 if (!alloc_cpumask_var(&d->nodemask, GFP_KERNEL))
7104 return sa_sched_group_nodes;
7105 if (!alloc_cpumask_var(&d->this_sibling_map, GFP_KERNEL))
7106 return sa_nodemask;
7107 if (!alloc_cpumask_var(&d->this_core_map, GFP_KERNEL))
7108 return sa_this_sibling_map;
7109 if (!alloc_cpumask_var(&d->this_book_map, GFP_KERNEL))
7110 return sa_this_core_map;
7111 if (!alloc_cpumask_var(&d->send_covered, GFP_KERNEL))
7112 return sa_this_book_map;
7113 if (!alloc_cpumask_var(&d->tmpmask, GFP_KERNEL))
7114 return sa_send_covered;
7115 d->rd = alloc_rootdomain();
7116 if (!d->rd) {
7117 printk(KERN_WARNING "Cannot alloc root domain\n");
7118 return sa_tmpmask;
7120 return sa_rootdomain;
7123 static struct sched_domain *__build_numa_sched_domains(struct s_data *d,
7124 const struct cpumask *cpu_map, struct sched_domain_attr *attr, int i)
7126 struct sched_domain *sd = NULL;
7127 #ifdef CONFIG_NUMA
7128 struct sched_domain *parent;
7130 d->sd_allnodes = 0;
7131 if (cpumask_weight(cpu_map) >
7132 SD_NODES_PER_DOMAIN * cpumask_weight(d->nodemask)) {
7133 sd = &per_cpu(allnodes_domains, i).sd;
7134 SD_INIT(sd, ALLNODES);
7135 set_domain_attribute(sd, attr);
7136 cpumask_copy(sched_domain_span(sd), cpu_map);
7137 cpu_to_allnodes_group(i, cpu_map, &sd->groups, d->tmpmask);
7138 d->sd_allnodes = 1;
7140 parent = sd;
7142 sd = &per_cpu(node_domains, i).sd;
7143 SD_INIT(sd, NODE);
7144 set_domain_attribute(sd, attr);
7145 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
7146 sd->parent = parent;
7147 if (parent)
7148 parent->child = sd;
7149 cpumask_and(sched_domain_span(sd), sched_domain_span(sd), cpu_map);
7150 #endif
7151 return sd;
7154 static struct sched_domain *__build_cpu_sched_domain(struct s_data *d,
7155 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7156 struct sched_domain *parent, int i)
7158 struct sched_domain *sd;
7159 sd = &per_cpu(phys_domains, i).sd;
7160 SD_INIT(sd, CPU);
7161 set_domain_attribute(sd, attr);
7162 cpumask_copy(sched_domain_span(sd), d->nodemask);
7163 sd->parent = parent;
7164 if (parent)
7165 parent->child = sd;
7166 cpu_to_phys_group(i, cpu_map, &sd->groups, d->tmpmask);
7167 return sd;
7170 static struct sched_domain *__build_book_sched_domain(struct s_data *d,
7171 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7172 struct sched_domain *parent, int i)
7174 struct sched_domain *sd = parent;
7175 #ifdef CONFIG_SCHED_BOOK
7176 sd = &per_cpu(book_domains, i).sd;
7177 SD_INIT(sd, BOOK);
7178 set_domain_attribute(sd, attr);
7179 cpumask_and(sched_domain_span(sd), cpu_map, cpu_book_mask(i));
7180 sd->parent = parent;
7181 parent->child = sd;
7182 cpu_to_book_group(i, cpu_map, &sd->groups, d->tmpmask);
7183 #endif
7184 return sd;
7187 static struct sched_domain *__build_mc_sched_domain(struct s_data *d,
7188 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7189 struct sched_domain *parent, int i)
7191 struct sched_domain *sd = parent;
7192 #ifdef CONFIG_SCHED_MC
7193 sd = &per_cpu(core_domains, i).sd;
7194 SD_INIT(sd, MC);
7195 set_domain_attribute(sd, attr);
7196 cpumask_and(sched_domain_span(sd), cpu_map, cpu_coregroup_mask(i));
7197 sd->parent = parent;
7198 parent->child = sd;
7199 cpu_to_core_group(i, cpu_map, &sd->groups, d->tmpmask);
7200 #endif
7201 return sd;
7204 static struct sched_domain *__build_smt_sched_domain(struct s_data *d,
7205 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7206 struct sched_domain *parent, int i)
7208 struct sched_domain *sd = parent;
7209 #ifdef CONFIG_SCHED_SMT
7210 sd = &per_cpu(cpu_domains, i).sd;
7211 SD_INIT(sd, SIBLING);
7212 set_domain_attribute(sd, attr);
7213 cpumask_and(sched_domain_span(sd), cpu_map, topology_thread_cpumask(i));
7214 sd->parent = parent;
7215 parent->child = sd;
7216 cpu_to_cpu_group(i, cpu_map, &sd->groups, d->tmpmask);
7217 #endif
7218 return sd;
7221 static void build_sched_groups(struct s_data *d, enum sched_domain_level l,
7222 const struct cpumask *cpu_map, int cpu)
7224 switch (l) {
7225 #ifdef CONFIG_SCHED_SMT
7226 case SD_LV_SIBLING: /* set up CPU (sibling) groups */
7227 cpumask_and(d->this_sibling_map, cpu_map,
7228 topology_thread_cpumask(cpu));
7229 if (cpu == cpumask_first(d->this_sibling_map))
7230 init_sched_build_groups(d->this_sibling_map, cpu_map,
7231 &cpu_to_cpu_group,
7232 d->send_covered, d->tmpmask);
7233 break;
7234 #endif
7235 #ifdef CONFIG_SCHED_MC
7236 case SD_LV_MC: /* set up multi-core groups */
7237 cpumask_and(d->this_core_map, cpu_map, cpu_coregroup_mask(cpu));
7238 if (cpu == cpumask_first(d->this_core_map))
7239 init_sched_build_groups(d->this_core_map, cpu_map,
7240 &cpu_to_core_group,
7241 d->send_covered, d->tmpmask);
7242 break;
7243 #endif
7244 #ifdef CONFIG_SCHED_BOOK
7245 case SD_LV_BOOK: /* set up book groups */
7246 cpumask_and(d->this_book_map, cpu_map, cpu_book_mask(cpu));
7247 if (cpu == cpumask_first(d->this_book_map))
7248 init_sched_build_groups(d->this_book_map, cpu_map,
7249 &cpu_to_book_group,
7250 d->send_covered, d->tmpmask);
7251 break;
7252 #endif
7253 case SD_LV_CPU: /* set up physical groups */
7254 cpumask_and(d->nodemask, cpumask_of_node(cpu), cpu_map);
7255 if (!cpumask_empty(d->nodemask))
7256 init_sched_build_groups(d->nodemask, cpu_map,
7257 &cpu_to_phys_group,
7258 d->send_covered, d->tmpmask);
7259 break;
7260 #ifdef CONFIG_NUMA
7261 case SD_LV_ALLNODES:
7262 init_sched_build_groups(cpu_map, cpu_map, &cpu_to_allnodes_group,
7263 d->send_covered, d->tmpmask);
7264 break;
7265 #endif
7266 default:
7267 break;
7272 * Build sched domains for a given set of cpus and attach the sched domains
7273 * to the individual cpus
7275 static int __build_sched_domains(const struct cpumask *cpu_map,
7276 struct sched_domain_attr *attr)
7278 enum s_alloc alloc_state = sa_none;
7279 struct s_data d;
7280 struct sched_domain *sd;
7281 int i;
7282 #ifdef CONFIG_NUMA
7283 d.sd_allnodes = 0;
7284 #endif
7286 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7287 if (alloc_state != sa_rootdomain)
7288 goto error;
7289 alloc_state = sa_sched_groups;
7292 * Set up domains for cpus specified by the cpu_map.
7294 for_each_cpu(i, cpu_map) {
7295 cpumask_and(d.nodemask, cpumask_of_node(cpu_to_node(i)),
7296 cpu_map);
7298 sd = __build_numa_sched_domains(&d, cpu_map, attr, i);
7299 sd = __build_cpu_sched_domain(&d, cpu_map, attr, sd, i);
7300 sd = __build_book_sched_domain(&d, cpu_map, attr, sd, i);
7301 sd = __build_mc_sched_domain(&d, cpu_map, attr, sd, i);
7302 sd = __build_smt_sched_domain(&d, cpu_map, attr, sd, i);
7305 for_each_cpu(i, cpu_map) {
7306 build_sched_groups(&d, SD_LV_SIBLING, cpu_map, i);
7307 build_sched_groups(&d, SD_LV_BOOK, cpu_map, i);
7308 build_sched_groups(&d, SD_LV_MC, cpu_map, i);
7311 /* Set up physical groups */
7312 for (i = 0; i < nr_node_ids; i++)
7313 build_sched_groups(&d, SD_LV_CPU, cpu_map, i);
7315 #ifdef CONFIG_NUMA
7316 /* Set up node groups */
7317 if (d.sd_allnodes)
7318 build_sched_groups(&d, SD_LV_ALLNODES, cpu_map, 0);
7320 for (i = 0; i < nr_node_ids; i++)
7321 if (build_numa_sched_groups(&d, cpu_map, i))
7322 goto error;
7323 #endif
7325 /* Calculate CPU power for physical packages and nodes */
7326 #ifdef CONFIG_SCHED_SMT
7327 for_each_cpu(i, cpu_map) {
7328 sd = &per_cpu(cpu_domains, i).sd;
7329 init_sched_groups_power(i, sd);
7331 #endif
7332 #ifdef CONFIG_SCHED_MC
7333 for_each_cpu(i, cpu_map) {
7334 sd = &per_cpu(core_domains, i).sd;
7335 init_sched_groups_power(i, sd);
7337 #endif
7338 #ifdef CONFIG_SCHED_BOOK
7339 for_each_cpu(i, cpu_map) {
7340 sd = &per_cpu(book_domains, i).sd;
7341 init_sched_groups_power(i, sd);
7343 #endif
7345 for_each_cpu(i, cpu_map) {
7346 sd = &per_cpu(phys_domains, i).sd;
7347 init_sched_groups_power(i, sd);
7350 #ifdef CONFIG_NUMA
7351 for (i = 0; i < nr_node_ids; i++)
7352 init_numa_sched_groups_power(d.sched_group_nodes[i]);
7354 if (d.sd_allnodes) {
7355 struct sched_group *sg;
7357 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
7358 d.tmpmask);
7359 init_numa_sched_groups_power(sg);
7361 #endif
7363 /* Attach the domains */
7364 for_each_cpu(i, cpu_map) {
7365 #ifdef CONFIG_SCHED_SMT
7366 sd = &per_cpu(cpu_domains, i).sd;
7367 #elif defined(CONFIG_SCHED_MC)
7368 sd = &per_cpu(core_domains, i).sd;
7369 #elif defined(CONFIG_SCHED_BOOK)
7370 sd = &per_cpu(book_domains, i).sd;
7371 #else
7372 sd = &per_cpu(phys_domains, i).sd;
7373 #endif
7374 cpu_attach_domain(sd, d.rd, i);
7377 d.sched_group_nodes = NULL; /* don't free this we still need it */
7378 __free_domain_allocs(&d, sa_tmpmask, cpu_map);
7379 return 0;
7381 error:
7382 __free_domain_allocs(&d, alloc_state, cpu_map);
7383 return -ENOMEM;
7386 static int build_sched_domains(const struct cpumask *cpu_map)
7388 return __build_sched_domains(cpu_map, NULL);
7391 static cpumask_var_t *doms_cur; /* current sched domains */
7392 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7393 static struct sched_domain_attr *dattr_cur;
7394 /* attribues of custom domains in 'doms_cur' */
7397 * Special case: If a kmalloc of a doms_cur partition (array of
7398 * cpumask) fails, then fallback to a single sched domain,
7399 * as determined by the single cpumask fallback_doms.
7401 static cpumask_var_t fallback_doms;
7404 * arch_update_cpu_topology lets virtualized architectures update the
7405 * cpu core maps. It is supposed to return 1 if the topology changed
7406 * or 0 if it stayed the same.
7408 int __attribute__((weak)) arch_update_cpu_topology(void)
7410 return 0;
7413 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7415 int i;
7416 cpumask_var_t *doms;
7418 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7419 if (!doms)
7420 return NULL;
7421 for (i = 0; i < ndoms; i++) {
7422 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7423 free_sched_domains(doms, i);
7424 return NULL;
7427 return doms;
7430 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7432 unsigned int i;
7433 for (i = 0; i < ndoms; i++)
7434 free_cpumask_var(doms[i]);
7435 kfree(doms);
7439 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7440 * For now this just excludes isolated cpus, but could be used to
7441 * exclude other special cases in the future.
7443 static int arch_init_sched_domains(const struct cpumask *cpu_map)
7445 int err;
7447 arch_update_cpu_topology();
7448 ndoms_cur = 1;
7449 doms_cur = alloc_sched_domains(ndoms_cur);
7450 if (!doms_cur)
7451 doms_cur = &fallback_doms;
7452 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7453 dattr_cur = NULL;
7454 err = build_sched_domains(doms_cur[0]);
7455 register_sched_domain_sysctl();
7457 return err;
7460 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
7461 struct cpumask *tmpmask)
7463 free_sched_groups(cpu_map, tmpmask);
7467 * Detach sched domains from a group of cpus specified in cpu_map
7468 * These cpus will now be attached to the NULL domain
7470 static void detach_destroy_domains(const struct cpumask *cpu_map)
7472 /* Save because hotplug lock held. */
7473 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
7474 int i;
7476 for_each_cpu(i, cpu_map)
7477 cpu_attach_domain(NULL, &def_root_domain, i);
7478 synchronize_sched();
7479 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
7482 /* handle null as "default" */
7483 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7484 struct sched_domain_attr *new, int idx_new)
7486 struct sched_domain_attr tmp;
7488 /* fast path */
7489 if (!new && !cur)
7490 return 1;
7492 tmp = SD_ATTR_INIT;
7493 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7494 new ? (new + idx_new) : &tmp,
7495 sizeof(struct sched_domain_attr));
7499 * Partition sched domains as specified by the 'ndoms_new'
7500 * cpumasks in the array doms_new[] of cpumasks. This compares
7501 * doms_new[] to the current sched domain partitioning, doms_cur[].
7502 * It destroys each deleted domain and builds each new domain.
7504 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7505 * The masks don't intersect (don't overlap.) We should setup one
7506 * sched domain for each mask. CPUs not in any of the cpumasks will
7507 * not be load balanced. If the same cpumask appears both in the
7508 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7509 * it as it is.
7511 * The passed in 'doms_new' should be allocated using
7512 * alloc_sched_domains. This routine takes ownership of it and will
7513 * free_sched_domains it when done with it. If the caller failed the
7514 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7515 * and partition_sched_domains() will fallback to the single partition
7516 * 'fallback_doms', it also forces the domains to be rebuilt.
7518 * If doms_new == NULL it will be replaced with cpu_online_mask.
7519 * ndoms_new == 0 is a special case for destroying existing domains,
7520 * and it will not create the default domain.
7522 * Call with hotplug lock held
7524 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7525 struct sched_domain_attr *dattr_new)
7527 int i, j, n;
7528 int new_topology;
7530 mutex_lock(&sched_domains_mutex);
7532 /* always unregister in case we don't destroy any domains */
7533 unregister_sched_domain_sysctl();
7535 /* Let architecture update cpu core mappings. */
7536 new_topology = arch_update_cpu_topology();
7538 n = doms_new ? ndoms_new : 0;
7540 /* Destroy deleted domains */
7541 for (i = 0; i < ndoms_cur; i++) {
7542 for (j = 0; j < n && !new_topology; j++) {
7543 if (cpumask_equal(doms_cur[i], doms_new[j])
7544 && dattrs_equal(dattr_cur, i, dattr_new, j))
7545 goto match1;
7547 /* no match - a current sched domain not in new doms_new[] */
7548 detach_destroy_domains(doms_cur[i]);
7549 match1:
7553 if (doms_new == NULL) {
7554 ndoms_cur = 0;
7555 doms_new = &fallback_doms;
7556 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7557 WARN_ON_ONCE(dattr_new);
7560 /* Build new domains */
7561 for (i = 0; i < ndoms_new; i++) {
7562 for (j = 0; j < ndoms_cur && !new_topology; j++) {
7563 if (cpumask_equal(doms_new[i], doms_cur[j])
7564 && dattrs_equal(dattr_new, i, dattr_cur, j))
7565 goto match2;
7567 /* no match - add a new doms_new */
7568 __build_sched_domains(doms_new[i],
7569 dattr_new ? dattr_new + i : NULL);
7570 match2:
7574 /* Remember the new sched domains */
7575 if (doms_cur != &fallback_doms)
7576 free_sched_domains(doms_cur, ndoms_cur);
7577 kfree(dattr_cur); /* kfree(NULL) is safe */
7578 doms_cur = doms_new;
7579 dattr_cur = dattr_new;
7580 ndoms_cur = ndoms_new;
7582 register_sched_domain_sysctl();
7584 mutex_unlock(&sched_domains_mutex);
7587 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7588 static void arch_reinit_sched_domains(void)
7590 get_online_cpus();
7592 /* Destroy domains first to force the rebuild */
7593 partition_sched_domains(0, NULL, NULL);
7595 rebuild_sched_domains();
7596 put_online_cpus();
7599 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7601 unsigned int level = 0;
7603 if (sscanf(buf, "%u", &level) != 1)
7604 return -EINVAL;
7607 * level is always be positive so don't check for
7608 * level < POWERSAVINGS_BALANCE_NONE which is 0
7609 * What happens on 0 or 1 byte write,
7610 * need to check for count as well?
7613 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
7614 return -EINVAL;
7616 if (smt)
7617 sched_smt_power_savings = level;
7618 else
7619 sched_mc_power_savings = level;
7621 arch_reinit_sched_domains();
7623 return count;
7626 #ifdef CONFIG_SCHED_MC
7627 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7628 struct sysdev_class_attribute *attr,
7629 char *page)
7631 return sprintf(page, "%u\n", sched_mc_power_savings);
7633 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7634 struct sysdev_class_attribute *attr,
7635 const char *buf, size_t count)
7637 return sched_power_savings_store(buf, count, 0);
7639 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7640 sched_mc_power_savings_show,
7641 sched_mc_power_savings_store);
7642 #endif
7644 #ifdef CONFIG_SCHED_SMT
7645 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7646 struct sysdev_class_attribute *attr,
7647 char *page)
7649 return sprintf(page, "%u\n", sched_smt_power_savings);
7651 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7652 struct sysdev_class_attribute *attr,
7653 const char *buf, size_t count)
7655 return sched_power_savings_store(buf, count, 1);
7657 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7658 sched_smt_power_savings_show,
7659 sched_smt_power_savings_store);
7660 #endif
7662 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7664 int err = 0;
7666 #ifdef CONFIG_SCHED_SMT
7667 if (smt_capable())
7668 err = sysfs_create_file(&cls->kset.kobj,
7669 &attr_sched_smt_power_savings.attr);
7670 #endif
7671 #ifdef CONFIG_SCHED_MC
7672 if (!err && mc_capable())
7673 err = sysfs_create_file(&cls->kset.kobj,
7674 &attr_sched_mc_power_savings.attr);
7675 #endif
7676 return err;
7678 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7681 * Update cpusets according to cpu_active mask. If cpusets are
7682 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7683 * around partition_sched_domains().
7685 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7686 void *hcpu)
7688 switch (action & ~CPU_TASKS_FROZEN) {
7689 case CPU_ONLINE:
7690 case CPU_DOWN_FAILED:
7691 cpuset_update_active_cpus();
7692 return NOTIFY_OK;
7693 default:
7694 return NOTIFY_DONE;
7698 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7699 void *hcpu)
7701 switch (action & ~CPU_TASKS_FROZEN) {
7702 case CPU_DOWN_PREPARE:
7703 cpuset_update_active_cpus();
7704 return NOTIFY_OK;
7705 default:
7706 return NOTIFY_DONE;
7710 static int update_runtime(struct notifier_block *nfb,
7711 unsigned long action, void *hcpu)
7713 int cpu = (int)(long)hcpu;
7715 switch (action) {
7716 case CPU_DOWN_PREPARE:
7717 case CPU_DOWN_PREPARE_FROZEN:
7718 disable_runtime(cpu_rq(cpu));
7719 return NOTIFY_OK;
7721 case CPU_DOWN_FAILED:
7722 case CPU_DOWN_FAILED_FROZEN:
7723 case CPU_ONLINE:
7724 case CPU_ONLINE_FROZEN:
7725 enable_runtime(cpu_rq(cpu));
7726 return NOTIFY_OK;
7728 default:
7729 return NOTIFY_DONE;
7733 void __init sched_init_smp(void)
7735 cpumask_var_t non_isolated_cpus;
7737 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7738 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7740 #if defined(CONFIG_NUMA)
7741 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7742 GFP_KERNEL);
7743 BUG_ON(sched_group_nodes_bycpu == NULL);
7744 #endif
7745 get_online_cpus();
7746 mutex_lock(&sched_domains_mutex);
7747 arch_init_sched_domains(cpu_active_mask);
7748 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7749 if (cpumask_empty(non_isolated_cpus))
7750 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7751 mutex_unlock(&sched_domains_mutex);
7752 put_online_cpus();
7754 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7755 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7757 /* RT runtime code needs to handle some hotplug events */
7758 hotcpu_notifier(update_runtime, 0);
7760 init_hrtick();
7762 /* Move init over to a non-isolated CPU */
7763 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7764 BUG();
7765 sched_init_granularity();
7766 free_cpumask_var(non_isolated_cpus);
7768 init_sched_rt_class();
7770 #else
7771 void __init sched_init_smp(void)
7773 sched_init_granularity();
7775 #endif /* CONFIG_SMP */
7777 const_debug unsigned int sysctl_timer_migration = 1;
7779 int in_sched_functions(unsigned long addr)
7781 return in_lock_functions(addr) ||
7782 (addr >= (unsigned long)__sched_text_start
7783 && addr < (unsigned long)__sched_text_end);
7786 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7788 cfs_rq->tasks_timeline = RB_ROOT;
7789 INIT_LIST_HEAD(&cfs_rq->tasks);
7790 #ifdef CONFIG_FAIR_GROUP_SCHED
7791 cfs_rq->rq = rq;
7792 #endif
7793 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7796 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7798 struct rt_prio_array *array;
7799 int i;
7801 array = &rt_rq->active;
7802 for (i = 0; i < MAX_RT_PRIO; i++) {
7803 INIT_LIST_HEAD(array->queue + i);
7804 __clear_bit(i, array->bitmap);
7806 /* delimiter for bitsearch: */
7807 __set_bit(MAX_RT_PRIO, array->bitmap);
7809 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7810 rt_rq->highest_prio.curr = MAX_RT_PRIO;
7811 #ifdef CONFIG_SMP
7812 rt_rq->highest_prio.next = MAX_RT_PRIO;
7813 #endif
7814 #endif
7815 #ifdef CONFIG_SMP
7816 rt_rq->rt_nr_migratory = 0;
7817 rt_rq->overloaded = 0;
7818 plist_head_init_raw(&rt_rq->pushable_tasks, &rq->lock);
7819 #endif
7821 rt_rq->rt_time = 0;
7822 rt_rq->rt_throttled = 0;
7823 rt_rq->rt_runtime = 0;
7824 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
7826 #ifdef CONFIG_RT_GROUP_SCHED
7827 rt_rq->rt_nr_boosted = 0;
7828 rt_rq->rq = rq;
7829 #endif
7832 #ifdef CONFIG_FAIR_GROUP_SCHED
7833 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7834 struct sched_entity *se, int cpu,
7835 struct sched_entity *parent)
7837 struct rq *rq = cpu_rq(cpu);
7838 tg->cfs_rq[cpu] = cfs_rq;
7839 init_cfs_rq(cfs_rq, rq);
7840 cfs_rq->tg = tg;
7842 tg->se[cpu] = se;
7843 /* se could be NULL for root_task_group */
7844 if (!se)
7845 return;
7847 if (!parent)
7848 se->cfs_rq = &rq->cfs;
7849 else
7850 se->cfs_rq = parent->my_q;
7852 se->my_q = cfs_rq;
7853 update_load_set(&se->load, 0);
7854 se->parent = parent;
7856 #endif
7858 #ifdef CONFIG_RT_GROUP_SCHED
7859 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7860 struct sched_rt_entity *rt_se, int cpu,
7861 struct sched_rt_entity *parent)
7863 struct rq *rq = cpu_rq(cpu);
7865 tg->rt_rq[cpu] = rt_rq;
7866 init_rt_rq(rt_rq, rq);
7867 rt_rq->tg = tg;
7868 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7870 tg->rt_se[cpu] = rt_se;
7871 if (!rt_se)
7872 return;
7874 if (!parent)
7875 rt_se->rt_rq = &rq->rt;
7876 else
7877 rt_se->rt_rq = parent->my_q;
7879 rt_se->my_q = rt_rq;
7880 rt_se->parent = parent;
7881 INIT_LIST_HEAD(&rt_se->run_list);
7883 #endif
7885 void __init sched_init(void)
7887 int i, j;
7888 unsigned long alloc_size = 0, ptr;
7890 #ifdef CONFIG_FAIR_GROUP_SCHED
7891 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7892 #endif
7893 #ifdef CONFIG_RT_GROUP_SCHED
7894 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7895 #endif
7896 #ifdef CONFIG_CPUMASK_OFFSTACK
7897 alloc_size += num_possible_cpus() * cpumask_size();
7898 #endif
7899 if (alloc_size) {
7900 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7902 #ifdef CONFIG_FAIR_GROUP_SCHED
7903 root_task_group.se = (struct sched_entity **)ptr;
7904 ptr += nr_cpu_ids * sizeof(void **);
7906 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7907 ptr += nr_cpu_ids * sizeof(void **);
7909 #endif /* CONFIG_FAIR_GROUP_SCHED */
7910 #ifdef CONFIG_RT_GROUP_SCHED
7911 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7912 ptr += nr_cpu_ids * sizeof(void **);
7914 root_task_group.rt_rq = (struct rt_rq **)ptr;
7915 ptr += nr_cpu_ids * sizeof(void **);
7917 #endif /* CONFIG_RT_GROUP_SCHED */
7918 #ifdef CONFIG_CPUMASK_OFFSTACK
7919 for_each_possible_cpu(i) {
7920 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
7921 ptr += cpumask_size();
7923 #endif /* CONFIG_CPUMASK_OFFSTACK */
7926 #ifdef CONFIG_SMP
7927 init_defrootdomain();
7928 #endif
7930 init_rt_bandwidth(&def_rt_bandwidth,
7931 global_rt_period(), global_rt_runtime());
7933 #ifdef CONFIG_RT_GROUP_SCHED
7934 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7935 global_rt_period(), global_rt_runtime());
7936 #endif /* CONFIG_RT_GROUP_SCHED */
7938 #ifdef CONFIG_CGROUP_SCHED
7939 list_add(&root_task_group.list, &task_groups);
7940 INIT_LIST_HEAD(&root_task_group.children);
7941 autogroup_init(&init_task);
7942 #endif /* CONFIG_CGROUP_SCHED */
7944 for_each_possible_cpu(i) {
7945 struct rq *rq;
7947 rq = cpu_rq(i);
7948 raw_spin_lock_init(&rq->lock);
7949 rq->nr_running = 0;
7950 rq->calc_load_active = 0;
7951 rq->calc_load_update = jiffies + LOAD_FREQ;
7952 init_cfs_rq(&rq->cfs, rq);
7953 init_rt_rq(&rq->rt, rq);
7954 #ifdef CONFIG_FAIR_GROUP_SCHED
7955 root_task_group.shares = root_task_group_load;
7956 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7958 * How much cpu bandwidth does root_task_group get?
7960 * In case of task-groups formed thr' the cgroup filesystem, it
7961 * gets 100% of the cpu resources in the system. This overall
7962 * system cpu resource is divided among the tasks of
7963 * root_task_group and its child task-groups in a fair manner,
7964 * based on each entity's (task or task-group's) weight
7965 * (se->load.weight).
7967 * In other words, if root_task_group has 10 tasks of weight
7968 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7969 * then A0's share of the cpu resource is:
7971 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7973 * We achieve this by letting root_task_group's tasks sit
7974 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7976 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7977 #endif /* CONFIG_FAIR_GROUP_SCHED */
7979 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7980 #ifdef CONFIG_RT_GROUP_SCHED
7981 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7982 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7983 #endif
7985 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7986 rq->cpu_load[j] = 0;
7988 rq->last_load_update_tick = jiffies;
7990 #ifdef CONFIG_SMP
7991 rq->sd = NULL;
7992 rq->rd = NULL;
7993 rq->cpu_power = SCHED_LOAD_SCALE;
7994 rq->post_schedule = 0;
7995 rq->active_balance = 0;
7996 rq->next_balance = jiffies;
7997 rq->push_cpu = 0;
7998 rq->cpu = i;
7999 rq->online = 0;
8000 rq->idle_stamp = 0;
8001 rq->avg_idle = 2*sysctl_sched_migration_cost;
8002 rq_attach_root(rq, &def_root_domain);
8003 #ifdef CONFIG_NO_HZ
8004 rq->nohz_balance_kick = 0;
8005 init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i));
8006 #endif
8007 #endif
8008 init_rq_hrtick(rq);
8009 atomic_set(&rq->nr_iowait, 0);
8012 set_load_weight(&init_task);
8014 #ifdef CONFIG_PREEMPT_NOTIFIERS
8015 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8016 #endif
8018 #ifdef CONFIG_SMP
8019 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
8020 #endif
8022 #ifdef CONFIG_RT_MUTEXES
8023 plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock);
8024 #endif
8027 * The boot idle thread does lazy MMU switching as well:
8029 atomic_inc(&init_mm.mm_count);
8030 enter_lazy_tlb(&init_mm, current);
8033 * Make us the idle thread. Technically, schedule() should not be
8034 * called from this thread, however somewhere below it might be,
8035 * but because we are the idle thread, we just pick up running again
8036 * when this runqueue becomes "idle".
8038 init_idle(current, smp_processor_id());
8040 calc_load_update = jiffies + LOAD_FREQ;
8043 * During early bootup we pretend to be a normal task:
8045 current->sched_class = &fair_sched_class;
8047 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
8048 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
8049 #ifdef CONFIG_SMP
8050 #ifdef CONFIG_NO_HZ
8051 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
8052 alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT);
8053 atomic_set(&nohz.load_balancer, nr_cpu_ids);
8054 atomic_set(&nohz.first_pick_cpu, nr_cpu_ids);
8055 atomic_set(&nohz.second_pick_cpu, nr_cpu_ids);
8056 #endif
8057 /* May be allocated at isolcpus cmdline parse time */
8058 if (cpu_isolated_map == NULL)
8059 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
8060 #endif /* SMP */
8062 scheduler_running = 1;
8065 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8066 static inline int preempt_count_equals(int preempt_offset)
8068 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
8070 return (nested == preempt_offset);
8073 void __might_sleep(const char *file, int line, int preempt_offset)
8075 #ifdef in_atomic
8076 static unsigned long prev_jiffy; /* ratelimiting */
8078 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
8079 system_state != SYSTEM_RUNNING || oops_in_progress)
8080 return;
8081 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8082 return;
8083 prev_jiffy = jiffies;
8085 printk(KERN_ERR
8086 "BUG: sleeping function called from invalid context at %s:%d\n",
8087 file, line);
8088 printk(KERN_ERR
8089 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8090 in_atomic(), irqs_disabled(),
8091 current->pid, current->comm);
8093 debug_show_held_locks(current);
8094 if (irqs_disabled())
8095 print_irqtrace_events(current);
8096 dump_stack();
8097 #endif
8099 EXPORT_SYMBOL(__might_sleep);
8100 #endif
8102 #ifdef CONFIG_MAGIC_SYSRQ
8103 static void normalize_task(struct rq *rq, struct task_struct *p)
8105 int on_rq;
8107 on_rq = p->se.on_rq;
8108 if (on_rq)
8109 deactivate_task(rq, p, 0);
8110 __setscheduler(rq, p, SCHED_NORMAL, 0);
8111 if (on_rq) {
8112 activate_task(rq, p, 0);
8113 resched_task(rq->curr);
8117 void normalize_rt_tasks(void)
8119 struct task_struct *g, *p;
8120 unsigned long flags;
8121 struct rq *rq;
8123 read_lock_irqsave(&tasklist_lock, flags);
8124 do_each_thread(g, p) {
8126 * Only normalize user tasks:
8128 if (!p->mm)
8129 continue;
8131 p->se.exec_start = 0;
8132 #ifdef CONFIG_SCHEDSTATS
8133 p->se.statistics.wait_start = 0;
8134 p->se.statistics.sleep_start = 0;
8135 p->se.statistics.block_start = 0;
8136 #endif
8138 if (!rt_task(p)) {
8140 * Renice negative nice level userspace
8141 * tasks back to 0:
8143 if (TASK_NICE(p) < 0 && p->mm)
8144 set_user_nice(p, 0);
8145 continue;
8148 raw_spin_lock(&p->pi_lock);
8149 rq = __task_rq_lock(p);
8151 normalize_task(rq, p);
8153 __task_rq_unlock(rq);
8154 raw_spin_unlock(&p->pi_lock);
8155 } while_each_thread(g, p);
8157 read_unlock_irqrestore(&tasklist_lock, flags);
8160 #endif /* CONFIG_MAGIC_SYSRQ */
8162 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
8164 * These functions are only useful for the IA64 MCA handling, or kdb.
8166 * They can only be called when the whole system has been
8167 * stopped - every CPU needs to be quiescent, and no scheduling
8168 * activity can take place. Using them for anything else would
8169 * be a serious bug, and as a result, they aren't even visible
8170 * under any other configuration.
8174 * curr_task - return the current task for a given cpu.
8175 * @cpu: the processor in question.
8177 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8179 struct task_struct *curr_task(int cpu)
8181 return cpu_curr(cpu);
8184 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8186 #ifdef CONFIG_IA64
8188 * set_curr_task - set the current task for a given cpu.
8189 * @cpu: the processor in question.
8190 * @p: the task pointer to set.
8192 * Description: This function must only be used when non-maskable interrupts
8193 * are serviced on a separate stack. It allows the architecture to switch the
8194 * notion of the current task on a cpu in a non-blocking manner. This function
8195 * must be called with all CPU's synchronized, and interrupts disabled, the
8196 * and caller must save the original value of the current task (see
8197 * curr_task() above) and restore that value before reenabling interrupts and
8198 * re-starting the system.
8200 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8202 void set_curr_task(int cpu, struct task_struct *p)
8204 cpu_curr(cpu) = p;
8207 #endif
8209 #ifdef CONFIG_FAIR_GROUP_SCHED
8210 static void free_fair_sched_group(struct task_group *tg)
8212 int i;
8214 for_each_possible_cpu(i) {
8215 if (tg->cfs_rq)
8216 kfree(tg->cfs_rq[i]);
8217 if (tg->se)
8218 kfree(tg->se[i]);
8221 kfree(tg->cfs_rq);
8222 kfree(tg->se);
8225 static
8226 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8228 struct cfs_rq *cfs_rq;
8229 struct sched_entity *se;
8230 struct rq *rq;
8231 int i;
8233 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8234 if (!tg->cfs_rq)
8235 goto err;
8236 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8237 if (!tg->se)
8238 goto err;
8240 tg->shares = NICE_0_LOAD;
8242 for_each_possible_cpu(i) {
8243 rq = cpu_rq(i);
8245 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8246 GFP_KERNEL, cpu_to_node(i));
8247 if (!cfs_rq)
8248 goto err;
8250 se = kzalloc_node(sizeof(struct sched_entity),
8251 GFP_KERNEL, cpu_to_node(i));
8252 if (!se)
8253 goto err_free_rq;
8255 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
8258 return 1;
8260 err_free_rq:
8261 kfree(cfs_rq);
8262 err:
8263 return 0;
8266 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8268 struct rq *rq = cpu_rq(cpu);
8269 unsigned long flags;
8272 * Only empty task groups can be destroyed; so we can speculatively
8273 * check on_list without danger of it being re-added.
8275 if (!tg->cfs_rq[cpu]->on_list)
8276 return;
8278 raw_spin_lock_irqsave(&rq->lock, flags);
8279 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
8280 raw_spin_unlock_irqrestore(&rq->lock, flags);
8282 #else /* !CONFG_FAIR_GROUP_SCHED */
8283 static inline void free_fair_sched_group(struct task_group *tg)
8287 static inline
8288 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8290 return 1;
8293 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8296 #endif /* CONFIG_FAIR_GROUP_SCHED */
8298 #ifdef CONFIG_RT_GROUP_SCHED
8299 static void free_rt_sched_group(struct task_group *tg)
8301 int i;
8303 destroy_rt_bandwidth(&tg->rt_bandwidth);
8305 for_each_possible_cpu(i) {
8306 if (tg->rt_rq)
8307 kfree(tg->rt_rq[i]);
8308 if (tg->rt_se)
8309 kfree(tg->rt_se[i]);
8312 kfree(tg->rt_rq);
8313 kfree(tg->rt_se);
8316 static
8317 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8319 struct rt_rq *rt_rq;
8320 struct sched_rt_entity *rt_se;
8321 struct rq *rq;
8322 int i;
8324 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8325 if (!tg->rt_rq)
8326 goto err;
8327 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8328 if (!tg->rt_se)
8329 goto err;
8331 init_rt_bandwidth(&tg->rt_bandwidth,
8332 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8334 for_each_possible_cpu(i) {
8335 rq = cpu_rq(i);
8337 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8338 GFP_KERNEL, cpu_to_node(i));
8339 if (!rt_rq)
8340 goto err;
8342 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8343 GFP_KERNEL, cpu_to_node(i));
8344 if (!rt_se)
8345 goto err_free_rq;
8347 init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
8350 return 1;
8352 err_free_rq:
8353 kfree(rt_rq);
8354 err:
8355 return 0;
8357 #else /* !CONFIG_RT_GROUP_SCHED */
8358 static inline void free_rt_sched_group(struct task_group *tg)
8362 static inline
8363 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8365 return 1;
8367 #endif /* CONFIG_RT_GROUP_SCHED */
8369 #ifdef CONFIG_CGROUP_SCHED
8370 static void free_sched_group(struct task_group *tg)
8372 free_fair_sched_group(tg);
8373 free_rt_sched_group(tg);
8374 autogroup_free(tg);
8375 kfree(tg);
8378 /* allocate runqueue etc for a new task group */
8379 struct task_group *sched_create_group(struct task_group *parent)
8381 struct task_group *tg;
8382 unsigned long flags;
8384 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8385 if (!tg)
8386 return ERR_PTR(-ENOMEM);
8388 if (!alloc_fair_sched_group(tg, parent))
8389 goto err;
8391 if (!alloc_rt_sched_group(tg, parent))
8392 goto err;
8394 spin_lock_irqsave(&task_group_lock, flags);
8395 list_add_rcu(&tg->list, &task_groups);
8397 WARN_ON(!parent); /* root should already exist */
8399 tg->parent = parent;
8400 INIT_LIST_HEAD(&tg->children);
8401 list_add_rcu(&tg->siblings, &parent->children);
8402 spin_unlock_irqrestore(&task_group_lock, flags);
8404 return tg;
8406 err:
8407 free_sched_group(tg);
8408 return ERR_PTR(-ENOMEM);
8411 /* rcu callback to free various structures associated with a task group */
8412 static void free_sched_group_rcu(struct rcu_head *rhp)
8414 /* now it should be safe to free those cfs_rqs */
8415 free_sched_group(container_of(rhp, struct task_group, rcu));
8418 /* Destroy runqueue etc associated with a task group */
8419 void sched_destroy_group(struct task_group *tg)
8421 unsigned long flags;
8422 int i;
8424 /* end participation in shares distribution */
8425 for_each_possible_cpu(i)
8426 unregister_fair_sched_group(tg, i);
8428 spin_lock_irqsave(&task_group_lock, flags);
8429 list_del_rcu(&tg->list);
8430 list_del_rcu(&tg->siblings);
8431 spin_unlock_irqrestore(&task_group_lock, flags);
8433 /* wait for possible concurrent references to cfs_rqs complete */
8434 call_rcu(&tg->rcu, free_sched_group_rcu);
8437 /* change task's runqueue when it moves between groups.
8438 * The caller of this function should have put the task in its new group
8439 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8440 * reflect its new group.
8442 void sched_move_task(struct task_struct *tsk)
8444 int on_rq, running;
8445 unsigned long flags;
8446 struct rq *rq;
8448 rq = task_rq_lock(tsk, &flags);
8450 running = task_current(rq, tsk);
8451 on_rq = tsk->se.on_rq;
8453 if (on_rq)
8454 dequeue_task(rq, tsk, 0);
8455 if (unlikely(running))
8456 tsk->sched_class->put_prev_task(rq, tsk);
8458 #ifdef CONFIG_FAIR_GROUP_SCHED
8459 if (tsk->sched_class->task_move_group)
8460 tsk->sched_class->task_move_group(tsk, on_rq);
8461 else
8462 #endif
8463 set_task_rq(tsk, task_cpu(tsk));
8465 if (unlikely(running))
8466 tsk->sched_class->set_curr_task(rq);
8467 if (on_rq)
8468 enqueue_task(rq, tsk, 0);
8470 task_rq_unlock(rq, &flags);
8472 #endif /* CONFIG_CGROUP_SCHED */
8474 #ifdef CONFIG_FAIR_GROUP_SCHED
8475 static DEFINE_MUTEX(shares_mutex);
8477 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8479 int i;
8480 unsigned long flags;
8483 * We can't change the weight of the root cgroup.
8485 if (!tg->se[0])
8486 return -EINVAL;
8488 if (shares < MIN_SHARES)
8489 shares = MIN_SHARES;
8490 else if (shares > MAX_SHARES)
8491 shares = MAX_SHARES;
8493 mutex_lock(&shares_mutex);
8494 if (tg->shares == shares)
8495 goto done;
8497 tg->shares = shares;
8498 for_each_possible_cpu(i) {
8499 struct rq *rq = cpu_rq(i);
8500 struct sched_entity *se;
8502 se = tg->se[i];
8503 /* Propagate contribution to hierarchy */
8504 raw_spin_lock_irqsave(&rq->lock, flags);
8505 for_each_sched_entity(se)
8506 update_cfs_shares(group_cfs_rq(se), 0);
8507 raw_spin_unlock_irqrestore(&rq->lock, flags);
8510 done:
8511 mutex_unlock(&shares_mutex);
8512 return 0;
8515 unsigned long sched_group_shares(struct task_group *tg)
8517 return tg->shares;
8519 #endif
8521 #ifdef CONFIG_RT_GROUP_SCHED
8523 * Ensure that the real time constraints are schedulable.
8525 static DEFINE_MUTEX(rt_constraints_mutex);
8527 static unsigned long to_ratio(u64 period, u64 runtime)
8529 if (runtime == RUNTIME_INF)
8530 return 1ULL << 20;
8532 return div64_u64(runtime << 20, period);
8535 /* Must be called with tasklist_lock held */
8536 static inline int tg_has_rt_tasks(struct task_group *tg)
8538 struct task_struct *g, *p;
8540 do_each_thread(g, p) {
8541 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8542 return 1;
8543 } while_each_thread(g, p);
8545 return 0;
8548 struct rt_schedulable_data {
8549 struct task_group *tg;
8550 u64 rt_period;
8551 u64 rt_runtime;
8554 static int tg_schedulable(struct task_group *tg, void *data)
8556 struct rt_schedulable_data *d = data;
8557 struct task_group *child;
8558 unsigned long total, sum = 0;
8559 u64 period, runtime;
8561 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8562 runtime = tg->rt_bandwidth.rt_runtime;
8564 if (tg == d->tg) {
8565 period = d->rt_period;
8566 runtime = d->rt_runtime;
8570 * Cannot have more runtime than the period.
8572 if (runtime > period && runtime != RUNTIME_INF)
8573 return -EINVAL;
8576 * Ensure we don't starve existing RT tasks.
8578 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8579 return -EBUSY;
8581 total = to_ratio(period, runtime);
8584 * Nobody can have more than the global setting allows.
8586 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8587 return -EINVAL;
8590 * The sum of our children's runtime should not exceed our own.
8592 list_for_each_entry_rcu(child, &tg->children, siblings) {
8593 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8594 runtime = child->rt_bandwidth.rt_runtime;
8596 if (child == d->tg) {
8597 period = d->rt_period;
8598 runtime = d->rt_runtime;
8601 sum += to_ratio(period, runtime);
8604 if (sum > total)
8605 return -EINVAL;
8607 return 0;
8610 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8612 struct rt_schedulable_data data = {
8613 .tg = tg,
8614 .rt_period = period,
8615 .rt_runtime = runtime,
8618 return walk_tg_tree(tg_schedulable, tg_nop, &data);
8621 static int tg_set_bandwidth(struct task_group *tg,
8622 u64 rt_period, u64 rt_runtime)
8624 int i, err = 0;
8626 mutex_lock(&rt_constraints_mutex);
8627 read_lock(&tasklist_lock);
8628 err = __rt_schedulable(tg, rt_period, rt_runtime);
8629 if (err)
8630 goto unlock;
8632 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8633 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8634 tg->rt_bandwidth.rt_runtime = rt_runtime;
8636 for_each_possible_cpu(i) {
8637 struct rt_rq *rt_rq = tg->rt_rq[i];
8639 raw_spin_lock(&rt_rq->rt_runtime_lock);
8640 rt_rq->rt_runtime = rt_runtime;
8641 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8643 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8644 unlock:
8645 read_unlock(&tasklist_lock);
8646 mutex_unlock(&rt_constraints_mutex);
8648 return err;
8651 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8653 u64 rt_runtime, rt_period;
8655 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8656 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8657 if (rt_runtime_us < 0)
8658 rt_runtime = RUNTIME_INF;
8660 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8663 long sched_group_rt_runtime(struct task_group *tg)
8665 u64 rt_runtime_us;
8667 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8668 return -1;
8670 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8671 do_div(rt_runtime_us, NSEC_PER_USEC);
8672 return rt_runtime_us;
8675 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8677 u64 rt_runtime, rt_period;
8679 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8680 rt_runtime = tg->rt_bandwidth.rt_runtime;
8682 if (rt_period == 0)
8683 return -EINVAL;
8685 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8688 long sched_group_rt_period(struct task_group *tg)
8690 u64 rt_period_us;
8692 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8693 do_div(rt_period_us, NSEC_PER_USEC);
8694 return rt_period_us;
8697 static int sched_rt_global_constraints(void)
8699 u64 runtime, period;
8700 int ret = 0;
8702 if (sysctl_sched_rt_period <= 0)
8703 return -EINVAL;
8705 runtime = global_rt_runtime();
8706 period = global_rt_period();
8709 * Sanity check on the sysctl variables.
8711 if (runtime > period && runtime != RUNTIME_INF)
8712 return -EINVAL;
8714 mutex_lock(&rt_constraints_mutex);
8715 read_lock(&tasklist_lock);
8716 ret = __rt_schedulable(NULL, 0, 0);
8717 read_unlock(&tasklist_lock);
8718 mutex_unlock(&rt_constraints_mutex);
8720 return ret;
8723 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8725 /* Don't accept realtime tasks when there is no way for them to run */
8726 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8727 return 0;
8729 return 1;
8732 #else /* !CONFIG_RT_GROUP_SCHED */
8733 static int sched_rt_global_constraints(void)
8735 unsigned long flags;
8736 int i;
8738 if (sysctl_sched_rt_period <= 0)
8739 return -EINVAL;
8742 * There's always some RT tasks in the root group
8743 * -- migration, kstopmachine etc..
8745 if (sysctl_sched_rt_runtime == 0)
8746 return -EBUSY;
8748 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8749 for_each_possible_cpu(i) {
8750 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8752 raw_spin_lock(&rt_rq->rt_runtime_lock);
8753 rt_rq->rt_runtime = global_rt_runtime();
8754 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8756 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8758 return 0;
8760 #endif /* CONFIG_RT_GROUP_SCHED */
8762 int sched_rt_handler(struct ctl_table *table, int write,
8763 void __user *buffer, size_t *lenp,
8764 loff_t *ppos)
8766 int ret;
8767 int old_period, old_runtime;
8768 static DEFINE_MUTEX(mutex);
8770 mutex_lock(&mutex);
8771 old_period = sysctl_sched_rt_period;
8772 old_runtime = sysctl_sched_rt_runtime;
8774 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8776 if (!ret && write) {
8777 ret = sched_rt_global_constraints();
8778 if (ret) {
8779 sysctl_sched_rt_period = old_period;
8780 sysctl_sched_rt_runtime = old_runtime;
8781 } else {
8782 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8783 def_rt_bandwidth.rt_period =
8784 ns_to_ktime(global_rt_period());
8787 mutex_unlock(&mutex);
8789 return ret;
8792 #ifdef CONFIG_CGROUP_SCHED
8794 /* return corresponding task_group object of a cgroup */
8795 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8797 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8798 struct task_group, css);
8801 static struct cgroup_subsys_state *
8802 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8804 struct task_group *tg, *parent;
8806 if (!cgrp->parent) {
8807 /* This is early initialization for the top cgroup */
8808 return &root_task_group.css;
8811 parent = cgroup_tg(cgrp->parent);
8812 tg = sched_create_group(parent);
8813 if (IS_ERR(tg))
8814 return ERR_PTR(-ENOMEM);
8816 return &tg->css;
8819 static void
8820 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8822 struct task_group *tg = cgroup_tg(cgrp);
8824 sched_destroy_group(tg);
8827 static int
8828 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8830 #ifdef CONFIG_RT_GROUP_SCHED
8831 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
8832 return -EINVAL;
8833 #else
8834 /* We don't support RT-tasks being in separate groups */
8835 if (tsk->sched_class != &fair_sched_class)
8836 return -EINVAL;
8837 #endif
8838 return 0;
8841 static int
8842 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8843 struct task_struct *tsk, bool threadgroup)
8845 int retval = cpu_cgroup_can_attach_task(cgrp, tsk);
8846 if (retval)
8847 return retval;
8848 if (threadgroup) {
8849 struct task_struct *c;
8850 rcu_read_lock();
8851 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8852 retval = cpu_cgroup_can_attach_task(cgrp, c);
8853 if (retval) {
8854 rcu_read_unlock();
8855 return retval;
8858 rcu_read_unlock();
8860 return 0;
8863 static void
8864 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8865 struct cgroup *old_cont, struct task_struct *tsk,
8866 bool threadgroup)
8868 sched_move_task(tsk);
8869 if (threadgroup) {
8870 struct task_struct *c;
8871 rcu_read_lock();
8872 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8873 sched_move_task(c);
8875 rcu_read_unlock();
8879 static void
8880 cpu_cgroup_exit(struct cgroup_subsys *ss, struct task_struct *task)
8883 * cgroup_exit() is called in the copy_process() failure path.
8884 * Ignore this case since the task hasn't ran yet, this avoids
8885 * trying to poke a half freed task state from generic code.
8887 if (!(task->flags & PF_EXITING))
8888 return;
8890 sched_move_task(task);
8893 #ifdef CONFIG_FAIR_GROUP_SCHED
8894 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
8895 u64 shareval)
8897 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8900 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
8902 struct task_group *tg = cgroup_tg(cgrp);
8904 return (u64) tg->shares;
8906 #endif /* CONFIG_FAIR_GROUP_SCHED */
8908 #ifdef CONFIG_RT_GROUP_SCHED
8909 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8910 s64 val)
8912 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8915 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8917 return sched_group_rt_runtime(cgroup_tg(cgrp));
8920 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8921 u64 rt_period_us)
8923 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8926 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8928 return sched_group_rt_period(cgroup_tg(cgrp));
8930 #endif /* CONFIG_RT_GROUP_SCHED */
8932 static struct cftype cpu_files[] = {
8933 #ifdef CONFIG_FAIR_GROUP_SCHED
8935 .name = "shares",
8936 .read_u64 = cpu_shares_read_u64,
8937 .write_u64 = cpu_shares_write_u64,
8939 #endif
8940 #ifdef CONFIG_RT_GROUP_SCHED
8942 .name = "rt_runtime_us",
8943 .read_s64 = cpu_rt_runtime_read,
8944 .write_s64 = cpu_rt_runtime_write,
8947 .name = "rt_period_us",
8948 .read_u64 = cpu_rt_period_read_uint,
8949 .write_u64 = cpu_rt_period_write_uint,
8951 #endif
8954 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8956 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8959 struct cgroup_subsys cpu_cgroup_subsys = {
8960 .name = "cpu",
8961 .create = cpu_cgroup_create,
8962 .destroy = cpu_cgroup_destroy,
8963 .can_attach = cpu_cgroup_can_attach,
8964 .attach = cpu_cgroup_attach,
8965 .exit = cpu_cgroup_exit,
8966 .populate = cpu_cgroup_populate,
8967 .subsys_id = cpu_cgroup_subsys_id,
8968 .early_init = 1,
8971 #endif /* CONFIG_CGROUP_SCHED */
8973 #ifdef CONFIG_CGROUP_CPUACCT
8976 * CPU accounting code for task groups.
8978 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8979 * (balbir@in.ibm.com).
8982 /* track cpu usage of a group of tasks and its child groups */
8983 struct cpuacct {
8984 struct cgroup_subsys_state css;
8985 /* cpuusage holds pointer to a u64-type object on every cpu */
8986 u64 __percpu *cpuusage;
8987 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
8988 struct cpuacct *parent;
8991 struct cgroup_subsys cpuacct_subsys;
8993 /* return cpu accounting group corresponding to this container */
8994 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
8996 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
8997 struct cpuacct, css);
9000 /* return cpu accounting group to which this task belongs */
9001 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9003 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9004 struct cpuacct, css);
9007 /* create a new cpu accounting group */
9008 static struct cgroup_subsys_state *cpuacct_create(
9009 struct cgroup_subsys *ss, struct cgroup *cgrp)
9011 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9012 int i;
9014 if (!ca)
9015 goto out;
9017 ca->cpuusage = alloc_percpu(u64);
9018 if (!ca->cpuusage)
9019 goto out_free_ca;
9021 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
9022 if (percpu_counter_init(&ca->cpustat[i], 0))
9023 goto out_free_counters;
9025 if (cgrp->parent)
9026 ca->parent = cgroup_ca(cgrp->parent);
9028 return &ca->css;
9030 out_free_counters:
9031 while (--i >= 0)
9032 percpu_counter_destroy(&ca->cpustat[i]);
9033 free_percpu(ca->cpuusage);
9034 out_free_ca:
9035 kfree(ca);
9036 out:
9037 return ERR_PTR(-ENOMEM);
9040 /* destroy an existing cpu accounting group */
9041 static void
9042 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9044 struct cpuacct *ca = cgroup_ca(cgrp);
9045 int i;
9047 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
9048 percpu_counter_destroy(&ca->cpustat[i]);
9049 free_percpu(ca->cpuusage);
9050 kfree(ca);
9053 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
9055 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9056 u64 data;
9058 #ifndef CONFIG_64BIT
9060 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
9062 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
9063 data = *cpuusage;
9064 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
9065 #else
9066 data = *cpuusage;
9067 #endif
9069 return data;
9072 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
9074 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9076 #ifndef CONFIG_64BIT
9078 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
9080 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
9081 *cpuusage = val;
9082 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
9083 #else
9084 *cpuusage = val;
9085 #endif
9088 /* return total cpu usage (in nanoseconds) of a group */
9089 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9091 struct cpuacct *ca = cgroup_ca(cgrp);
9092 u64 totalcpuusage = 0;
9093 int i;
9095 for_each_present_cpu(i)
9096 totalcpuusage += cpuacct_cpuusage_read(ca, i);
9098 return totalcpuusage;
9101 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9102 u64 reset)
9104 struct cpuacct *ca = cgroup_ca(cgrp);
9105 int err = 0;
9106 int i;
9108 if (reset) {
9109 err = -EINVAL;
9110 goto out;
9113 for_each_present_cpu(i)
9114 cpuacct_cpuusage_write(ca, i, 0);
9116 out:
9117 return err;
9120 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
9121 struct seq_file *m)
9123 struct cpuacct *ca = cgroup_ca(cgroup);
9124 u64 percpu;
9125 int i;
9127 for_each_present_cpu(i) {
9128 percpu = cpuacct_cpuusage_read(ca, i);
9129 seq_printf(m, "%llu ", (unsigned long long) percpu);
9131 seq_printf(m, "\n");
9132 return 0;
9135 static const char *cpuacct_stat_desc[] = {
9136 [CPUACCT_STAT_USER] = "user",
9137 [CPUACCT_STAT_SYSTEM] = "system",
9140 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
9141 struct cgroup_map_cb *cb)
9143 struct cpuacct *ca = cgroup_ca(cgrp);
9144 int i;
9146 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
9147 s64 val = percpu_counter_read(&ca->cpustat[i]);
9148 val = cputime64_to_clock_t(val);
9149 cb->fill(cb, cpuacct_stat_desc[i], val);
9151 return 0;
9154 static struct cftype files[] = {
9156 .name = "usage",
9157 .read_u64 = cpuusage_read,
9158 .write_u64 = cpuusage_write,
9161 .name = "usage_percpu",
9162 .read_seq_string = cpuacct_percpu_seq_read,
9165 .name = "stat",
9166 .read_map = cpuacct_stats_show,
9170 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9172 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9176 * charge this task's execution time to its accounting group.
9178 * called with rq->lock held.
9180 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9182 struct cpuacct *ca;
9183 int cpu;
9185 if (unlikely(!cpuacct_subsys.active))
9186 return;
9188 cpu = task_cpu(tsk);
9190 rcu_read_lock();
9192 ca = task_ca(tsk);
9194 for (; ca; ca = ca->parent) {
9195 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9196 *cpuusage += cputime;
9199 rcu_read_unlock();
9203 * When CONFIG_VIRT_CPU_ACCOUNTING is enabled one jiffy can be very large
9204 * in cputime_t units. As a result, cpuacct_update_stats calls
9205 * percpu_counter_add with values large enough to always overflow the
9206 * per cpu batch limit causing bad SMP scalability.
9208 * To fix this we scale percpu_counter_batch by cputime_one_jiffy so we
9209 * batch the same amount of time with CONFIG_VIRT_CPU_ACCOUNTING disabled
9210 * and enabled. We cap it at INT_MAX which is the largest allowed batch value.
9212 #ifdef CONFIG_SMP
9213 #define CPUACCT_BATCH \
9214 min_t(long, percpu_counter_batch * cputime_one_jiffy, INT_MAX)
9215 #else
9216 #define CPUACCT_BATCH 0
9217 #endif
9220 * Charge the system/user time to the task's accounting group.
9222 static void cpuacct_update_stats(struct task_struct *tsk,
9223 enum cpuacct_stat_index idx, cputime_t val)
9225 struct cpuacct *ca;
9226 int batch = CPUACCT_BATCH;
9228 if (unlikely(!cpuacct_subsys.active))
9229 return;
9231 rcu_read_lock();
9232 ca = task_ca(tsk);
9234 do {
9235 __percpu_counter_add(&ca->cpustat[idx], val, batch);
9236 ca = ca->parent;
9237 } while (ca);
9238 rcu_read_unlock();
9241 struct cgroup_subsys cpuacct_subsys = {
9242 .name = "cpuacct",
9243 .create = cpuacct_create,
9244 .destroy = cpuacct_destroy,
9245 .populate = cpuacct_populate,
9246 .subsys_id = cpuacct_subsys_id,
9248 #endif /* CONFIG_CGROUP_CPUACCT */