Merge branch 'next' of git://git.kernel.org/pub/scm/linux/kernel/git/davej/cpufreq
[linux-2.6/next.git] / kernel / sched.c
blob751a7cc6a5cd621d82f28d618f30562b7f97aeb6
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>
78 #ifdef CONFIG_PARAVIRT
79 #include <asm/paravirt.h>
80 #endif
82 #include "sched_cpupri.h"
83 #include "workqueue_sched.h"
84 #include "sched_autogroup.h"
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/sched.h>
90 * Convert user-nice values [ -20 ... 0 ... 19 ]
91 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
92 * and back.
94 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
95 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
96 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
99 * 'User priority' is the nice value converted to something we
100 * can work with better when scaling various scheduler parameters,
101 * it's a [ 0 ... 39 ] range.
103 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
104 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
105 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
108 * Helpers for converting nanosecond timing to jiffy resolution
110 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
112 #define NICE_0_LOAD SCHED_LOAD_SCALE
113 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
116 * These are the 'tuning knobs' of the scheduler:
118 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
119 * Timeslices get refilled after they expire.
121 #define DEF_TIMESLICE (100 * HZ / 1000)
124 * single value that denotes runtime == period, ie unlimited time.
126 #define RUNTIME_INF ((u64)~0ULL)
128 static inline int rt_policy(int policy)
130 if (policy == SCHED_FIFO || policy == SCHED_RR)
131 return 1;
132 return 0;
135 static inline int task_has_rt_policy(struct task_struct *p)
137 return rt_policy(p->policy);
141 * This is the priority-queue data structure of the RT scheduling class:
143 struct rt_prio_array {
144 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
145 struct list_head queue[MAX_RT_PRIO];
148 struct rt_bandwidth {
149 /* nests inside the rq lock: */
150 raw_spinlock_t rt_runtime_lock;
151 ktime_t rt_period;
152 u64 rt_runtime;
153 struct hrtimer rt_period_timer;
156 static struct rt_bandwidth def_rt_bandwidth;
158 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
160 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
162 struct rt_bandwidth *rt_b =
163 container_of(timer, struct rt_bandwidth, rt_period_timer);
164 ktime_t now;
165 int overrun;
166 int idle = 0;
168 for (;;) {
169 now = hrtimer_cb_get_time(timer);
170 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
172 if (!overrun)
173 break;
175 idle = do_sched_rt_period_timer(rt_b, overrun);
178 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
181 static
182 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
184 rt_b->rt_period = ns_to_ktime(period);
185 rt_b->rt_runtime = runtime;
187 raw_spin_lock_init(&rt_b->rt_runtime_lock);
189 hrtimer_init(&rt_b->rt_period_timer,
190 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
191 rt_b->rt_period_timer.function = sched_rt_period_timer;
194 static inline int rt_bandwidth_enabled(void)
196 return sysctl_sched_rt_runtime >= 0;
199 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
201 ktime_t now;
203 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
204 return;
206 if (hrtimer_active(&rt_b->rt_period_timer))
207 return;
209 raw_spin_lock(&rt_b->rt_runtime_lock);
210 for (;;) {
211 unsigned long delta;
212 ktime_t soft, hard;
214 if (hrtimer_active(&rt_b->rt_period_timer))
215 break;
217 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
218 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
220 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
221 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
222 delta = ktime_to_ns(ktime_sub(hard, soft));
223 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
224 HRTIMER_MODE_ABS_PINNED, 0);
226 raw_spin_unlock(&rt_b->rt_runtime_lock);
229 #ifdef CONFIG_RT_GROUP_SCHED
230 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
232 hrtimer_cancel(&rt_b->rt_period_timer);
234 #endif
237 * sched_domains_mutex serializes calls to init_sched_domains,
238 * detach_destroy_domains and partition_sched_domains.
240 static DEFINE_MUTEX(sched_domains_mutex);
242 #ifdef CONFIG_CGROUP_SCHED
244 #include <linux/cgroup.h>
246 struct cfs_rq;
248 static LIST_HEAD(task_groups);
250 /* task group related information */
251 struct task_group {
252 struct cgroup_subsys_state css;
254 #ifdef CONFIG_FAIR_GROUP_SCHED
255 /* schedulable entities of this group on each cpu */
256 struct sched_entity **se;
257 /* runqueue "owned" by this group on each cpu */
258 struct cfs_rq **cfs_rq;
259 unsigned long shares;
261 atomic_t load_weight;
262 #endif
264 #ifdef CONFIG_RT_GROUP_SCHED
265 struct sched_rt_entity **rt_se;
266 struct rt_rq **rt_rq;
268 struct rt_bandwidth rt_bandwidth;
269 #endif
271 struct rcu_head rcu;
272 struct list_head list;
274 struct task_group *parent;
275 struct list_head siblings;
276 struct list_head children;
278 #ifdef CONFIG_SCHED_AUTOGROUP
279 struct autogroup *autogroup;
280 #endif
283 /* task_group_lock serializes the addition/removal of task groups */
284 static DEFINE_SPINLOCK(task_group_lock);
286 #ifdef CONFIG_FAIR_GROUP_SCHED
288 # define ROOT_TASK_GROUP_LOAD NICE_0_LOAD
291 * A weight of 0 or 1 can cause arithmetics problems.
292 * A weight of a cfs_rq is the sum of weights of which entities
293 * are queued on this cfs_rq, so a weight of a entity should not be
294 * too large, so as the shares value of a task group.
295 * (The default weight is 1024 - so there's no practical
296 * limitation from this.)
298 #define MIN_SHARES (1UL << 1)
299 #define MAX_SHARES (1UL << 18)
301 static int root_task_group_load = ROOT_TASK_GROUP_LOAD;
302 #endif
304 /* Default task group.
305 * Every task in system belong to this group at bootup.
307 struct task_group root_task_group;
309 #endif /* CONFIG_CGROUP_SCHED */
311 /* CFS-related fields in a runqueue */
312 struct cfs_rq {
313 struct load_weight load;
314 unsigned long nr_running;
316 u64 exec_clock;
317 u64 min_vruntime;
318 #ifndef CONFIG_64BIT
319 u64 min_vruntime_copy;
320 #endif
322 struct rb_root tasks_timeline;
323 struct rb_node *rb_leftmost;
325 struct list_head tasks;
326 struct list_head *balance_iterator;
329 * 'curr' points to currently running entity on this cfs_rq.
330 * It is set to NULL otherwise (i.e when none are currently running).
332 struct sched_entity *curr, *next, *last, *skip;
334 #ifdef CONFIG_SCHED_DEBUG
335 unsigned int nr_spread_over;
336 #endif
338 #ifdef CONFIG_FAIR_GROUP_SCHED
339 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
342 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
343 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
344 * (like users, containers etc.)
346 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
347 * list is used during load balance.
349 int on_list;
350 struct list_head leaf_cfs_rq_list;
351 struct task_group *tg; /* group that "owns" this runqueue */
353 #ifdef CONFIG_SMP
355 * the part of load.weight contributed by tasks
357 unsigned long task_weight;
360 * h_load = weight * f(tg)
362 * Where f(tg) is the recursive weight fraction assigned to
363 * this group.
365 unsigned long h_load;
368 * Maintaining per-cpu shares distribution for group scheduling
370 * load_stamp is the last time we updated the load average
371 * load_last is the last time we updated the load average and saw load
372 * load_unacc_exec_time is currently unaccounted execution time
374 u64 load_avg;
375 u64 load_period;
376 u64 load_stamp, load_last, load_unacc_exec_time;
378 unsigned long load_contribution;
379 #endif
380 #endif
383 /* Real-Time classes' related field in a runqueue: */
384 struct rt_rq {
385 struct rt_prio_array active;
386 unsigned long rt_nr_running;
387 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
388 struct {
389 int curr; /* highest queued rt task prio */
390 #ifdef CONFIG_SMP
391 int next; /* next highest */
392 #endif
393 } highest_prio;
394 #endif
395 #ifdef CONFIG_SMP
396 unsigned long rt_nr_migratory;
397 unsigned long rt_nr_total;
398 int overloaded;
399 struct plist_head pushable_tasks;
400 #endif
401 int rt_throttled;
402 u64 rt_time;
403 u64 rt_runtime;
404 /* Nests inside the rq lock: */
405 raw_spinlock_t rt_runtime_lock;
407 #ifdef CONFIG_RT_GROUP_SCHED
408 unsigned long rt_nr_boosted;
410 struct rq *rq;
411 struct list_head leaf_rt_rq_list;
412 struct task_group *tg;
413 #endif
416 #ifdef CONFIG_SMP
419 * We add the notion of a root-domain which will be used to define per-domain
420 * variables. Each exclusive cpuset essentially defines an island domain by
421 * fully partitioning the member cpus from any other cpuset. Whenever a new
422 * exclusive cpuset is created, we also create and attach a new root-domain
423 * object.
426 struct root_domain {
427 atomic_t refcount;
428 atomic_t rto_count;
429 struct rcu_head rcu;
430 cpumask_var_t span;
431 cpumask_var_t online;
434 * The "RT overload" flag: it gets set if a CPU has more than
435 * one runnable RT task.
437 cpumask_var_t rto_mask;
438 struct cpupri cpupri;
442 * By default the system creates a single root-domain with all cpus as
443 * members (mimicking the global state we have today).
445 static struct root_domain def_root_domain;
447 #endif /* CONFIG_SMP */
450 * This is the main, per-CPU runqueue data structure.
452 * Locking rule: those places that want to lock multiple runqueues
453 * (such as the load balancing or the thread migration code), lock
454 * acquire operations must be ordered by ascending &runqueue.
456 struct rq {
457 /* runqueue lock: */
458 raw_spinlock_t lock;
461 * nr_running and cpu_load should be in the same cacheline because
462 * remote CPUs use both these fields when doing load calculation.
464 unsigned long nr_running;
465 #define CPU_LOAD_IDX_MAX 5
466 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
467 unsigned long last_load_update_tick;
468 #ifdef CONFIG_NO_HZ
469 u64 nohz_stamp;
470 unsigned char nohz_balance_kick;
471 #endif
472 int skip_clock_update;
474 /* capture load from *all* tasks on this cpu: */
475 struct load_weight load;
476 unsigned long nr_load_updates;
477 u64 nr_switches;
479 struct cfs_rq cfs;
480 struct rt_rq rt;
482 #ifdef CONFIG_FAIR_GROUP_SCHED
483 /* list of leaf cfs_rq on this cpu: */
484 struct list_head leaf_cfs_rq_list;
485 #endif
486 #ifdef CONFIG_RT_GROUP_SCHED
487 struct list_head leaf_rt_rq_list;
488 #endif
491 * This is part of a global counter where only the total sum
492 * over all CPUs matters. A task can increase this counter on
493 * one CPU and if it got migrated afterwards it may decrease
494 * it on another CPU. Always updated under the runqueue lock:
496 unsigned long nr_uninterruptible;
498 struct task_struct *curr, *idle, *stop;
499 unsigned long next_balance;
500 struct mm_struct *prev_mm;
502 u64 clock;
503 u64 clock_task;
505 atomic_t nr_iowait;
507 #ifdef CONFIG_SMP
508 struct root_domain *rd;
509 struct sched_domain *sd;
511 unsigned long cpu_power;
513 unsigned char idle_at_tick;
514 /* For active balancing */
515 int post_schedule;
516 int active_balance;
517 int push_cpu;
518 struct cpu_stop_work active_balance_work;
519 /* cpu of this runqueue: */
520 int cpu;
521 int online;
523 unsigned long avg_load_per_task;
525 u64 rt_avg;
526 u64 age_stamp;
527 u64 idle_stamp;
528 u64 avg_idle;
529 #endif
531 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
532 u64 prev_irq_time;
533 #endif
534 #ifdef CONFIG_PARAVIRT
535 u64 prev_steal_time;
536 #endif
537 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
538 u64 prev_steal_time_rq;
539 #endif
541 /* calc_load related fields */
542 unsigned long calc_load_update;
543 long calc_load_active;
545 #ifdef CONFIG_SCHED_HRTICK
546 #ifdef CONFIG_SMP
547 int hrtick_csd_pending;
548 struct call_single_data hrtick_csd;
549 #endif
550 struct hrtimer hrtick_timer;
551 #endif
553 #ifdef CONFIG_SCHEDSTATS
554 /* latency stats */
555 struct sched_info rq_sched_info;
556 unsigned long long rq_cpu_time;
557 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
559 /* sys_sched_yield() stats */
560 unsigned int yld_count;
562 /* schedule() stats */
563 unsigned int sched_switch;
564 unsigned int sched_count;
565 unsigned int sched_goidle;
567 /* try_to_wake_up() stats */
568 unsigned int ttwu_count;
569 unsigned int ttwu_local;
570 #endif
572 #ifdef CONFIG_SMP
573 struct task_struct *wake_list;
574 #endif
577 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
580 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags);
582 static inline int cpu_of(struct rq *rq)
584 #ifdef CONFIG_SMP
585 return rq->cpu;
586 #else
587 return 0;
588 #endif
591 #define rcu_dereference_check_sched_domain(p) \
592 rcu_dereference_check((p), \
593 rcu_read_lock_held() || \
594 lockdep_is_held(&sched_domains_mutex))
597 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
598 * See detach_destroy_domains: synchronize_sched for details.
600 * The domain tree of any CPU may only be accessed from within
601 * preempt-disabled sections.
603 #define for_each_domain(cpu, __sd) \
604 for (__sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
606 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
607 #define this_rq() (&__get_cpu_var(runqueues))
608 #define task_rq(p) cpu_rq(task_cpu(p))
609 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
610 #define raw_rq() (&__raw_get_cpu_var(runqueues))
612 #ifdef CONFIG_CGROUP_SCHED
615 * Return the group to which this tasks belongs.
617 * We use task_subsys_state_check() and extend the RCU verification with
618 * pi->lock and rq->lock because cpu_cgroup_attach() holds those locks for each
619 * task it moves into the cgroup. Therefore by holding either of those locks,
620 * we pin the task to the current cgroup.
622 static inline struct task_group *task_group(struct task_struct *p)
624 struct task_group *tg;
625 struct cgroup_subsys_state *css;
627 css = task_subsys_state_check(p, cpu_cgroup_subsys_id,
628 lockdep_is_held(&p->pi_lock) ||
629 lockdep_is_held(&task_rq(p)->lock));
630 tg = container_of(css, struct task_group, css);
632 return autogroup_task_group(p, tg);
635 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
636 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
638 #ifdef CONFIG_FAIR_GROUP_SCHED
639 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
640 p->se.parent = task_group(p)->se[cpu];
641 #endif
643 #ifdef CONFIG_RT_GROUP_SCHED
644 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
645 p->rt.parent = task_group(p)->rt_se[cpu];
646 #endif
649 #else /* CONFIG_CGROUP_SCHED */
651 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
652 static inline struct task_group *task_group(struct task_struct *p)
654 return NULL;
657 #endif /* CONFIG_CGROUP_SCHED */
659 static void update_rq_clock_task(struct rq *rq, s64 delta);
661 static void update_rq_clock(struct rq *rq)
663 s64 delta;
665 if (rq->skip_clock_update > 0)
666 return;
668 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
669 rq->clock += delta;
670 update_rq_clock_task(rq, delta);
674 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
676 #ifdef CONFIG_SCHED_DEBUG
677 # define const_debug __read_mostly
678 #else
679 # define const_debug static const
680 #endif
683 * runqueue_is_locked - Returns true if the current cpu runqueue is locked
684 * @cpu: the processor in question.
686 * This interface allows printk to be called with the runqueue lock
687 * held and know whether or not it is OK to wake up the klogd.
689 int runqueue_is_locked(int cpu)
691 return raw_spin_is_locked(&cpu_rq(cpu)->lock);
695 * Debugging: various feature bits
698 #define SCHED_FEAT(name, enabled) \
699 __SCHED_FEAT_##name ,
701 enum {
702 #include "sched_features.h"
705 #undef SCHED_FEAT
707 #define SCHED_FEAT(name, enabled) \
708 (1UL << __SCHED_FEAT_##name) * enabled |
710 const_debug unsigned int sysctl_sched_features =
711 #include "sched_features.h"
714 #undef SCHED_FEAT
716 #ifdef CONFIG_SCHED_DEBUG
717 #define SCHED_FEAT(name, enabled) \
718 #name ,
720 static __read_mostly char *sched_feat_names[] = {
721 #include "sched_features.h"
722 NULL
725 #undef SCHED_FEAT
727 static int sched_feat_show(struct seq_file *m, void *v)
729 int i;
731 for (i = 0; sched_feat_names[i]; i++) {
732 if (!(sysctl_sched_features & (1UL << i)))
733 seq_puts(m, "NO_");
734 seq_printf(m, "%s ", sched_feat_names[i]);
736 seq_puts(m, "\n");
738 return 0;
741 static ssize_t
742 sched_feat_write(struct file *filp, const char __user *ubuf,
743 size_t cnt, loff_t *ppos)
745 char buf[64];
746 char *cmp;
747 int neg = 0;
748 int i;
750 if (cnt > 63)
751 cnt = 63;
753 if (copy_from_user(&buf, ubuf, cnt))
754 return -EFAULT;
756 buf[cnt] = 0;
757 cmp = strstrip(buf);
759 if (strncmp(cmp, "NO_", 3) == 0) {
760 neg = 1;
761 cmp += 3;
764 for (i = 0; sched_feat_names[i]; i++) {
765 if (strcmp(cmp, sched_feat_names[i]) == 0) {
766 if (neg)
767 sysctl_sched_features &= ~(1UL << i);
768 else
769 sysctl_sched_features |= (1UL << i);
770 break;
774 if (!sched_feat_names[i])
775 return -EINVAL;
777 *ppos += cnt;
779 return cnt;
782 static int sched_feat_open(struct inode *inode, struct file *filp)
784 return single_open(filp, sched_feat_show, NULL);
787 static const struct file_operations sched_feat_fops = {
788 .open = sched_feat_open,
789 .write = sched_feat_write,
790 .read = seq_read,
791 .llseek = seq_lseek,
792 .release = single_release,
795 static __init int sched_init_debug(void)
797 debugfs_create_file("sched_features", 0644, NULL, NULL,
798 &sched_feat_fops);
800 return 0;
802 late_initcall(sched_init_debug);
804 #endif
806 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
809 * Number of tasks to iterate in a single balance run.
810 * Limited because this is done with IRQs disabled.
812 const_debug unsigned int sysctl_sched_nr_migrate = 32;
815 * period over which we average the RT time consumption, measured
816 * in ms.
818 * default: 1s
820 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
823 * period over which we measure -rt task cpu usage in us.
824 * default: 1s
826 unsigned int sysctl_sched_rt_period = 1000000;
828 static __read_mostly int scheduler_running;
831 * part of the period that we allow rt tasks to run in us.
832 * default: 0.95s
834 int sysctl_sched_rt_runtime = 950000;
836 static inline u64 global_rt_period(void)
838 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
841 static inline u64 global_rt_runtime(void)
843 if (sysctl_sched_rt_runtime < 0)
844 return RUNTIME_INF;
846 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
849 #ifndef prepare_arch_switch
850 # define prepare_arch_switch(next) do { } while (0)
851 #endif
852 #ifndef finish_arch_switch
853 # define finish_arch_switch(prev) do { } while (0)
854 #endif
856 static inline int task_current(struct rq *rq, struct task_struct *p)
858 return rq->curr == p;
861 static inline int task_running(struct rq *rq, struct task_struct *p)
863 #ifdef CONFIG_SMP
864 return p->on_cpu;
865 #else
866 return task_current(rq, p);
867 #endif
870 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
871 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
873 #ifdef CONFIG_SMP
875 * We can optimise this out completely for !SMP, because the
876 * SMP rebalancing from interrupt is the only thing that cares
877 * here.
879 next->on_cpu = 1;
880 #endif
883 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
885 #ifdef CONFIG_SMP
887 * After ->on_cpu is cleared, the task can be moved to a different CPU.
888 * We must ensure this doesn't happen until the switch is completely
889 * finished.
891 smp_wmb();
892 prev->on_cpu = 0;
893 #endif
894 #ifdef CONFIG_DEBUG_SPINLOCK
895 /* this is a valid case when another task releases the spinlock */
896 rq->lock.owner = current;
897 #endif
899 * If we are tracking spinlock dependencies then we have to
900 * fix up the runqueue lock - which gets 'carried over' from
901 * prev into current:
903 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
905 raw_spin_unlock_irq(&rq->lock);
908 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
909 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
911 #ifdef CONFIG_SMP
913 * We can optimise this out completely for !SMP, because the
914 * SMP rebalancing from interrupt is the only thing that cares
915 * here.
917 next->on_cpu = 1;
918 #endif
919 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
920 raw_spin_unlock_irq(&rq->lock);
921 #else
922 raw_spin_unlock(&rq->lock);
923 #endif
926 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
928 #ifdef CONFIG_SMP
930 * After ->on_cpu is cleared, the task can be moved to a different CPU.
931 * We must ensure this doesn't happen until the switch is completely
932 * finished.
934 smp_wmb();
935 prev->on_cpu = 0;
936 #endif
937 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
938 local_irq_enable();
939 #endif
941 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
944 * __task_rq_lock - lock the rq @p resides on.
946 static inline struct rq *__task_rq_lock(struct task_struct *p)
947 __acquires(rq->lock)
949 struct rq *rq;
951 lockdep_assert_held(&p->pi_lock);
953 for (;;) {
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(&rq->lock);
963 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
965 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
966 __acquires(p->pi_lock)
967 __acquires(rq->lock)
969 struct rq *rq;
971 for (;;) {
972 raw_spin_lock_irqsave(&p->pi_lock, *flags);
973 rq = task_rq(p);
974 raw_spin_lock(&rq->lock);
975 if (likely(rq == task_rq(p)))
976 return rq;
977 raw_spin_unlock(&rq->lock);
978 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
982 static void __task_rq_unlock(struct rq *rq)
983 __releases(rq->lock)
985 raw_spin_unlock(&rq->lock);
988 static inline void
989 task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
990 __releases(rq->lock)
991 __releases(p->pi_lock)
993 raw_spin_unlock(&rq->lock);
994 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
998 * this_rq_lock - lock this runqueue and disable interrupts.
1000 static struct rq *this_rq_lock(void)
1001 __acquires(rq->lock)
1003 struct rq *rq;
1005 local_irq_disable();
1006 rq = this_rq();
1007 raw_spin_lock(&rq->lock);
1009 return rq;
1012 #ifdef CONFIG_SCHED_HRTICK
1014 * Use HR-timers to deliver accurate preemption points.
1016 * Its all a bit involved since we cannot program an hrt while holding the
1017 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1018 * reschedule event.
1020 * When we get rescheduled we reprogram the hrtick_timer outside of the
1021 * rq->lock.
1025 * Use hrtick when:
1026 * - enabled by features
1027 * - hrtimer is actually high res
1029 static inline int hrtick_enabled(struct rq *rq)
1031 if (!sched_feat(HRTICK))
1032 return 0;
1033 if (!cpu_active(cpu_of(rq)))
1034 return 0;
1035 return hrtimer_is_hres_active(&rq->hrtick_timer);
1038 static void hrtick_clear(struct rq *rq)
1040 if (hrtimer_active(&rq->hrtick_timer))
1041 hrtimer_cancel(&rq->hrtick_timer);
1045 * High-resolution timer tick.
1046 * Runs from hardirq context with interrupts disabled.
1048 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1050 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1052 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1054 raw_spin_lock(&rq->lock);
1055 update_rq_clock(rq);
1056 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1057 raw_spin_unlock(&rq->lock);
1059 return HRTIMER_NORESTART;
1062 #ifdef CONFIG_SMP
1064 * called from hardirq (IPI) context
1066 static void __hrtick_start(void *arg)
1068 struct rq *rq = arg;
1070 raw_spin_lock(&rq->lock);
1071 hrtimer_restart(&rq->hrtick_timer);
1072 rq->hrtick_csd_pending = 0;
1073 raw_spin_unlock(&rq->lock);
1077 * Called to set the hrtick timer state.
1079 * called with rq->lock held and irqs disabled
1081 static void hrtick_start(struct rq *rq, u64 delay)
1083 struct hrtimer *timer = &rq->hrtick_timer;
1084 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1086 hrtimer_set_expires(timer, time);
1088 if (rq == this_rq()) {
1089 hrtimer_restart(timer);
1090 } else if (!rq->hrtick_csd_pending) {
1091 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1092 rq->hrtick_csd_pending = 1;
1096 static int
1097 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1099 int cpu = (int)(long)hcpu;
1101 switch (action) {
1102 case CPU_UP_CANCELED:
1103 case CPU_UP_CANCELED_FROZEN:
1104 case CPU_DOWN_PREPARE:
1105 case CPU_DOWN_PREPARE_FROZEN:
1106 case CPU_DEAD:
1107 case CPU_DEAD_FROZEN:
1108 hrtick_clear(cpu_rq(cpu));
1109 return NOTIFY_OK;
1112 return NOTIFY_DONE;
1115 static __init void init_hrtick(void)
1117 hotcpu_notifier(hotplug_hrtick, 0);
1119 #else
1121 * Called to set the hrtick timer state.
1123 * called with rq->lock held and irqs disabled
1125 static void hrtick_start(struct rq *rq, u64 delay)
1127 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1128 HRTIMER_MODE_REL_PINNED, 0);
1131 static inline void init_hrtick(void)
1134 #endif /* CONFIG_SMP */
1136 static void init_rq_hrtick(struct rq *rq)
1138 #ifdef CONFIG_SMP
1139 rq->hrtick_csd_pending = 0;
1141 rq->hrtick_csd.flags = 0;
1142 rq->hrtick_csd.func = __hrtick_start;
1143 rq->hrtick_csd.info = rq;
1144 #endif
1146 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1147 rq->hrtick_timer.function = hrtick;
1149 #else /* CONFIG_SCHED_HRTICK */
1150 static inline void hrtick_clear(struct rq *rq)
1154 static inline void init_rq_hrtick(struct rq *rq)
1158 static inline void init_hrtick(void)
1161 #endif /* CONFIG_SCHED_HRTICK */
1164 * resched_task - mark a task 'to be rescheduled now'.
1166 * On UP this means the setting of the need_resched flag, on SMP it
1167 * might also involve a cross-CPU call to trigger the scheduler on
1168 * the target CPU.
1170 #ifdef CONFIG_SMP
1172 #ifndef tsk_is_polling
1173 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1174 #endif
1176 static void resched_task(struct task_struct *p)
1178 int cpu;
1180 assert_raw_spin_locked(&task_rq(p)->lock);
1182 if (test_tsk_need_resched(p))
1183 return;
1185 set_tsk_need_resched(p);
1187 cpu = task_cpu(p);
1188 if (cpu == smp_processor_id())
1189 return;
1191 /* NEED_RESCHED must be visible before we test polling */
1192 smp_mb();
1193 if (!tsk_is_polling(p))
1194 smp_send_reschedule(cpu);
1197 static void resched_cpu(int cpu)
1199 struct rq *rq = cpu_rq(cpu);
1200 unsigned long flags;
1202 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1203 return;
1204 resched_task(cpu_curr(cpu));
1205 raw_spin_unlock_irqrestore(&rq->lock, flags);
1208 #ifdef CONFIG_NO_HZ
1210 * In the semi idle case, use the nearest busy cpu for migrating timers
1211 * from an idle cpu. This is good for power-savings.
1213 * We don't do similar optimization for completely idle system, as
1214 * selecting an idle cpu will add more delays to the timers than intended
1215 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
1217 int get_nohz_timer_target(void)
1219 int cpu = smp_processor_id();
1220 int i;
1221 struct sched_domain *sd;
1223 rcu_read_lock();
1224 for_each_domain(cpu, sd) {
1225 for_each_cpu(i, sched_domain_span(sd)) {
1226 if (!idle_cpu(i)) {
1227 cpu = i;
1228 goto unlock;
1232 unlock:
1233 rcu_read_unlock();
1234 return cpu;
1237 * When add_timer_on() enqueues a timer into the timer wheel of an
1238 * idle CPU then this timer might expire before the next timer event
1239 * which is scheduled to wake up that CPU. In case of a completely
1240 * idle system the next event might even be infinite time into the
1241 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1242 * leaves the inner idle loop so the newly added timer is taken into
1243 * account when the CPU goes back to idle and evaluates the timer
1244 * wheel for the next timer event.
1246 void wake_up_idle_cpu(int cpu)
1248 struct rq *rq = cpu_rq(cpu);
1250 if (cpu == smp_processor_id())
1251 return;
1254 * This is safe, as this function is called with the timer
1255 * wheel base lock of (cpu) held. When the CPU is on the way
1256 * to idle and has not yet set rq->curr to idle then it will
1257 * be serialized on the timer wheel base lock and take the new
1258 * timer into account automatically.
1260 if (rq->curr != rq->idle)
1261 return;
1264 * We can set TIF_RESCHED on the idle task of the other CPU
1265 * lockless. The worst case is that the other CPU runs the
1266 * idle task through an additional NOOP schedule()
1268 set_tsk_need_resched(rq->idle);
1270 /* NEED_RESCHED must be visible before we test polling */
1271 smp_mb();
1272 if (!tsk_is_polling(rq->idle))
1273 smp_send_reschedule(cpu);
1276 #endif /* CONFIG_NO_HZ */
1278 static u64 sched_avg_period(void)
1280 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1283 static void sched_avg_update(struct rq *rq)
1285 s64 period = sched_avg_period();
1287 while ((s64)(rq->clock - rq->age_stamp) > period) {
1289 * Inline assembly required to prevent the compiler
1290 * optimising this loop into a divmod call.
1291 * See __iter_div_u64_rem() for another example of this.
1293 asm("" : "+rm" (rq->age_stamp));
1294 rq->age_stamp += period;
1295 rq->rt_avg /= 2;
1299 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1301 rq->rt_avg += rt_delta;
1302 sched_avg_update(rq);
1305 #else /* !CONFIG_SMP */
1306 static void resched_task(struct task_struct *p)
1308 assert_raw_spin_locked(&task_rq(p)->lock);
1309 set_tsk_need_resched(p);
1312 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1316 static void sched_avg_update(struct rq *rq)
1319 #endif /* CONFIG_SMP */
1321 #if BITS_PER_LONG == 32
1322 # define WMULT_CONST (~0UL)
1323 #else
1324 # define WMULT_CONST (1UL << 32)
1325 #endif
1327 #define WMULT_SHIFT 32
1330 * Shift right and round:
1332 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1335 * delta *= weight / lw
1337 static unsigned long
1338 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1339 struct load_weight *lw)
1341 u64 tmp;
1344 * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
1345 * entities since MIN_SHARES = 2. Treat weight as 1 if less than
1346 * 2^SCHED_LOAD_RESOLUTION.
1348 if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
1349 tmp = (u64)delta_exec * scale_load_down(weight);
1350 else
1351 tmp = (u64)delta_exec;
1353 if (!lw->inv_weight) {
1354 unsigned long w = scale_load_down(lw->weight);
1356 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
1357 lw->inv_weight = 1;
1358 else if (unlikely(!w))
1359 lw->inv_weight = WMULT_CONST;
1360 else
1361 lw->inv_weight = WMULT_CONST / w;
1365 * Check whether we'd overflow the 64-bit multiplication:
1367 if (unlikely(tmp > WMULT_CONST))
1368 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1369 WMULT_SHIFT/2);
1370 else
1371 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1373 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1376 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1378 lw->weight += inc;
1379 lw->inv_weight = 0;
1382 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1384 lw->weight -= dec;
1385 lw->inv_weight = 0;
1388 static inline void update_load_set(struct load_weight *lw, unsigned long w)
1390 lw->weight = w;
1391 lw->inv_weight = 0;
1395 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1396 * of tasks with abnormal "nice" values across CPUs the contribution that
1397 * each task makes to its run queue's load is weighted according to its
1398 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1399 * scaled version of the new time slice allocation that they receive on time
1400 * slice expiry etc.
1403 #define WEIGHT_IDLEPRIO 3
1404 #define WMULT_IDLEPRIO 1431655765
1407 * Nice levels are multiplicative, with a gentle 10% change for every
1408 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1409 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1410 * that remained on nice 0.
1412 * The "10% effect" is relative and cumulative: from _any_ nice level,
1413 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1414 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1415 * If a task goes up by ~10% and another task goes down by ~10% then
1416 * the relative distance between them is ~25%.)
1418 static const int prio_to_weight[40] = {
1419 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1420 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1421 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1422 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1423 /* 0 */ 1024, 820, 655, 526, 423,
1424 /* 5 */ 335, 272, 215, 172, 137,
1425 /* 10 */ 110, 87, 70, 56, 45,
1426 /* 15 */ 36, 29, 23, 18, 15,
1430 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1432 * In cases where the weight does not change often, we can use the
1433 * precalculated inverse to speed up arithmetics by turning divisions
1434 * into multiplications:
1436 static const u32 prio_to_wmult[40] = {
1437 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1438 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1439 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1440 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1441 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1442 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1443 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1444 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1447 /* Time spent by the tasks of the cpu accounting group executing in ... */
1448 enum cpuacct_stat_index {
1449 CPUACCT_STAT_USER, /* ... user mode */
1450 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1452 CPUACCT_STAT_NSTATS,
1455 #ifdef CONFIG_CGROUP_CPUACCT
1456 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1457 static void cpuacct_update_stats(struct task_struct *tsk,
1458 enum cpuacct_stat_index idx, cputime_t val);
1459 #else
1460 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1461 static inline void cpuacct_update_stats(struct task_struct *tsk,
1462 enum cpuacct_stat_index idx, cputime_t val) {}
1463 #endif
1465 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1467 update_load_add(&rq->load, load);
1470 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1472 update_load_sub(&rq->load, load);
1475 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1476 typedef int (*tg_visitor)(struct task_group *, void *);
1479 * Iterate the full tree, calling @down when first entering a node and @up when
1480 * leaving it for the final time.
1482 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1484 struct task_group *parent, *child;
1485 int ret;
1487 rcu_read_lock();
1488 parent = &root_task_group;
1489 down:
1490 ret = (*down)(parent, data);
1491 if (ret)
1492 goto out_unlock;
1493 list_for_each_entry_rcu(child, &parent->children, siblings) {
1494 parent = child;
1495 goto down;
1498 continue;
1500 ret = (*up)(parent, data);
1501 if (ret)
1502 goto out_unlock;
1504 child = parent;
1505 parent = parent->parent;
1506 if (parent)
1507 goto up;
1508 out_unlock:
1509 rcu_read_unlock();
1511 return ret;
1514 static int tg_nop(struct task_group *tg, void *data)
1516 return 0;
1518 #endif
1520 #ifdef CONFIG_SMP
1521 /* Used instead of source_load when we know the type == 0 */
1522 static unsigned long weighted_cpuload(const int cpu)
1524 return cpu_rq(cpu)->load.weight;
1528 * Return a low guess at the load of a migration-source cpu weighted
1529 * according to the scheduling class and "nice" value.
1531 * We want to under-estimate the load of migration sources, to
1532 * balance conservatively.
1534 static unsigned long source_load(int cpu, int type)
1536 struct rq *rq = cpu_rq(cpu);
1537 unsigned long total = weighted_cpuload(cpu);
1539 if (type == 0 || !sched_feat(LB_BIAS))
1540 return total;
1542 return min(rq->cpu_load[type-1], total);
1546 * Return a high guess at the load of a migration-target cpu weighted
1547 * according to the scheduling class and "nice" value.
1549 static unsigned long target_load(int cpu, int type)
1551 struct rq *rq = cpu_rq(cpu);
1552 unsigned long total = weighted_cpuload(cpu);
1554 if (type == 0 || !sched_feat(LB_BIAS))
1555 return total;
1557 return max(rq->cpu_load[type-1], total);
1560 static unsigned long power_of(int cpu)
1562 return cpu_rq(cpu)->cpu_power;
1565 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1567 static unsigned long cpu_avg_load_per_task(int cpu)
1569 struct rq *rq = cpu_rq(cpu);
1570 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1572 if (nr_running)
1573 rq->avg_load_per_task = rq->load.weight / nr_running;
1574 else
1575 rq->avg_load_per_task = 0;
1577 return rq->avg_load_per_task;
1580 #ifdef CONFIG_PREEMPT
1582 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1585 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1586 * way at the expense of forcing extra atomic operations in all
1587 * invocations. This assures that the double_lock is acquired using the
1588 * same underlying policy as the spinlock_t on this architecture, which
1589 * reduces latency compared to the unfair variant below. However, it
1590 * also adds more overhead and therefore may reduce throughput.
1592 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1593 __releases(this_rq->lock)
1594 __acquires(busiest->lock)
1595 __acquires(this_rq->lock)
1597 raw_spin_unlock(&this_rq->lock);
1598 double_rq_lock(this_rq, busiest);
1600 return 1;
1603 #else
1605 * Unfair double_lock_balance: Optimizes throughput at the expense of
1606 * latency by eliminating extra atomic operations when the locks are
1607 * already in proper order on entry. This favors lower cpu-ids and will
1608 * grant the double lock to lower cpus over higher ids under contention,
1609 * regardless of entry order into the function.
1611 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1612 __releases(this_rq->lock)
1613 __acquires(busiest->lock)
1614 __acquires(this_rq->lock)
1616 int ret = 0;
1618 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1619 if (busiest < this_rq) {
1620 raw_spin_unlock(&this_rq->lock);
1621 raw_spin_lock(&busiest->lock);
1622 raw_spin_lock_nested(&this_rq->lock,
1623 SINGLE_DEPTH_NESTING);
1624 ret = 1;
1625 } else
1626 raw_spin_lock_nested(&busiest->lock,
1627 SINGLE_DEPTH_NESTING);
1629 return ret;
1632 #endif /* CONFIG_PREEMPT */
1635 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1637 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1639 if (unlikely(!irqs_disabled())) {
1640 /* printk() doesn't work good under rq->lock */
1641 raw_spin_unlock(&this_rq->lock);
1642 BUG_ON(1);
1645 return _double_lock_balance(this_rq, busiest);
1648 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1649 __releases(busiest->lock)
1651 raw_spin_unlock(&busiest->lock);
1652 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1656 * double_rq_lock - safely lock two runqueues
1658 * Note this does not disable interrupts like task_rq_lock,
1659 * you need to do so manually before calling.
1661 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1662 __acquires(rq1->lock)
1663 __acquires(rq2->lock)
1665 BUG_ON(!irqs_disabled());
1666 if (rq1 == rq2) {
1667 raw_spin_lock(&rq1->lock);
1668 __acquire(rq2->lock); /* Fake it out ;) */
1669 } else {
1670 if (rq1 < rq2) {
1671 raw_spin_lock(&rq1->lock);
1672 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
1673 } else {
1674 raw_spin_lock(&rq2->lock);
1675 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
1681 * double_rq_unlock - safely unlock two runqueues
1683 * Note this does not restore interrupts like task_rq_unlock,
1684 * you need to do so manually after calling.
1686 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1687 __releases(rq1->lock)
1688 __releases(rq2->lock)
1690 raw_spin_unlock(&rq1->lock);
1691 if (rq1 != rq2)
1692 raw_spin_unlock(&rq2->lock);
1693 else
1694 __release(rq2->lock);
1697 #else /* CONFIG_SMP */
1700 * double_rq_lock - safely lock two runqueues
1702 * Note this does not disable interrupts like task_rq_lock,
1703 * you need to do so manually before calling.
1705 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1706 __acquires(rq1->lock)
1707 __acquires(rq2->lock)
1709 BUG_ON(!irqs_disabled());
1710 BUG_ON(rq1 != rq2);
1711 raw_spin_lock(&rq1->lock);
1712 __acquire(rq2->lock); /* Fake it out ;) */
1716 * double_rq_unlock - safely unlock two runqueues
1718 * Note this does not restore interrupts like task_rq_unlock,
1719 * you need to do so manually after calling.
1721 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1722 __releases(rq1->lock)
1723 __releases(rq2->lock)
1725 BUG_ON(rq1 != rq2);
1726 raw_spin_unlock(&rq1->lock);
1727 __release(rq2->lock);
1730 #endif
1732 static void calc_load_account_idle(struct rq *this_rq);
1733 static void update_sysctl(void);
1734 static int get_update_sysctl_factor(void);
1735 static void update_cpu_load(struct rq *this_rq);
1737 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1739 set_task_rq(p, cpu);
1740 #ifdef CONFIG_SMP
1742 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1743 * successfuly executed on another CPU. We must ensure that updates of
1744 * per-task data have been completed by this moment.
1746 smp_wmb();
1747 task_thread_info(p)->cpu = cpu;
1748 #endif
1751 static const struct sched_class rt_sched_class;
1753 #define sched_class_highest (&stop_sched_class)
1754 #define for_each_class(class) \
1755 for (class = sched_class_highest; class; class = class->next)
1757 #include "sched_stats.h"
1759 static void inc_nr_running(struct rq *rq)
1761 rq->nr_running++;
1764 static void dec_nr_running(struct rq *rq)
1766 rq->nr_running--;
1769 static void set_load_weight(struct task_struct *p)
1771 int prio = p->static_prio - MAX_RT_PRIO;
1772 struct load_weight *load = &p->se.load;
1775 * SCHED_IDLE tasks get minimal weight:
1777 if (p->policy == SCHED_IDLE) {
1778 load->weight = scale_load(WEIGHT_IDLEPRIO);
1779 load->inv_weight = WMULT_IDLEPRIO;
1780 return;
1783 load->weight = scale_load(prio_to_weight[prio]);
1784 load->inv_weight = prio_to_wmult[prio];
1787 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
1789 update_rq_clock(rq);
1790 sched_info_queued(p);
1791 p->sched_class->enqueue_task(rq, p, flags);
1794 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
1796 update_rq_clock(rq);
1797 sched_info_dequeued(p);
1798 p->sched_class->dequeue_task(rq, p, flags);
1802 * activate_task - move a task to the runqueue.
1804 static void activate_task(struct rq *rq, struct task_struct *p, int flags)
1806 if (task_contributes_to_load(p))
1807 rq->nr_uninterruptible--;
1809 enqueue_task(rq, p, flags);
1810 inc_nr_running(rq);
1814 * deactivate_task - remove a task from the runqueue.
1816 static void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1818 if (task_contributes_to_load(p))
1819 rq->nr_uninterruptible++;
1821 dequeue_task(rq, p, flags);
1822 dec_nr_running(rq);
1825 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1828 * There are no locks covering percpu hardirq/softirq time.
1829 * They are only modified in account_system_vtime, on corresponding CPU
1830 * with interrupts disabled. So, writes are safe.
1831 * They are read and saved off onto struct rq in update_rq_clock().
1832 * This may result in other CPU reading this CPU's irq time and can
1833 * race with irq/account_system_vtime on this CPU. We would either get old
1834 * or new value with a side effect of accounting a slice of irq time to wrong
1835 * task when irq is in progress while we read rq->clock. That is a worthy
1836 * compromise in place of having locks on each irq in account_system_time.
1838 static DEFINE_PER_CPU(u64, cpu_hardirq_time);
1839 static DEFINE_PER_CPU(u64, cpu_softirq_time);
1841 static DEFINE_PER_CPU(u64, irq_start_time);
1842 static int sched_clock_irqtime;
1844 void enable_sched_clock_irqtime(void)
1846 sched_clock_irqtime = 1;
1849 void disable_sched_clock_irqtime(void)
1851 sched_clock_irqtime = 0;
1854 #ifndef CONFIG_64BIT
1855 static DEFINE_PER_CPU(seqcount_t, irq_time_seq);
1857 static inline void irq_time_write_begin(void)
1859 __this_cpu_inc(irq_time_seq.sequence);
1860 smp_wmb();
1863 static inline void irq_time_write_end(void)
1865 smp_wmb();
1866 __this_cpu_inc(irq_time_seq.sequence);
1869 static inline u64 irq_time_read(int cpu)
1871 u64 irq_time;
1872 unsigned seq;
1874 do {
1875 seq = read_seqcount_begin(&per_cpu(irq_time_seq, cpu));
1876 irq_time = per_cpu(cpu_softirq_time, cpu) +
1877 per_cpu(cpu_hardirq_time, cpu);
1878 } while (read_seqcount_retry(&per_cpu(irq_time_seq, cpu), seq));
1880 return irq_time;
1882 #else /* CONFIG_64BIT */
1883 static inline void irq_time_write_begin(void)
1887 static inline void irq_time_write_end(void)
1891 static inline u64 irq_time_read(int cpu)
1893 return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu);
1895 #endif /* CONFIG_64BIT */
1898 * Called before incrementing preempt_count on {soft,}irq_enter
1899 * and before decrementing preempt_count on {soft,}irq_exit.
1901 void account_system_vtime(struct task_struct *curr)
1903 unsigned long flags;
1904 s64 delta;
1905 int cpu;
1907 if (!sched_clock_irqtime)
1908 return;
1910 local_irq_save(flags);
1912 cpu = smp_processor_id();
1913 delta = sched_clock_cpu(cpu) - __this_cpu_read(irq_start_time);
1914 __this_cpu_add(irq_start_time, delta);
1916 irq_time_write_begin();
1918 * We do not account for softirq time from ksoftirqd here.
1919 * We want to continue accounting softirq time to ksoftirqd thread
1920 * in that case, so as not to confuse scheduler with a special task
1921 * that do not consume any time, but still wants to run.
1923 if (hardirq_count())
1924 __this_cpu_add(cpu_hardirq_time, delta);
1925 else if (in_serving_softirq() && curr != this_cpu_ksoftirqd())
1926 __this_cpu_add(cpu_softirq_time, delta);
1928 irq_time_write_end();
1929 local_irq_restore(flags);
1931 EXPORT_SYMBOL_GPL(account_system_vtime);
1933 #endif /* CONFIG_IRQ_TIME_ACCOUNTING */
1935 #ifdef CONFIG_PARAVIRT
1936 static inline u64 steal_ticks(u64 steal)
1938 if (unlikely(steal > NSEC_PER_SEC))
1939 return div_u64(steal, TICK_NSEC);
1941 return __iter_div_u64_rem(steal, TICK_NSEC, &steal);
1943 #endif
1945 static void update_rq_clock_task(struct rq *rq, s64 delta)
1948 * In theory, the compile should just see 0 here, and optimize out the call
1949 * to sched_rt_avg_update. But I don't trust it...
1951 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
1952 s64 steal = 0, irq_delta = 0;
1953 #endif
1954 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1955 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
1958 * Since irq_time is only updated on {soft,}irq_exit, we might run into
1959 * this case when a previous update_rq_clock() happened inside a
1960 * {soft,}irq region.
1962 * When this happens, we stop ->clock_task and only update the
1963 * prev_irq_time stamp to account for the part that fit, so that a next
1964 * update will consume the rest. This ensures ->clock_task is
1965 * monotonic.
1967 * It does however cause some slight miss-attribution of {soft,}irq
1968 * time, a more accurate solution would be to update the irq_time using
1969 * the current rq->clock timestamp, except that would require using
1970 * atomic ops.
1972 if (irq_delta > delta)
1973 irq_delta = delta;
1975 rq->prev_irq_time += irq_delta;
1976 delta -= irq_delta;
1977 #endif
1978 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
1979 if (static_branch((&paravirt_steal_rq_enabled))) {
1980 u64 st;
1982 steal = paravirt_steal_clock(cpu_of(rq));
1983 steal -= rq->prev_steal_time_rq;
1985 if (unlikely(steal > delta))
1986 steal = delta;
1988 st = steal_ticks(steal);
1989 steal = st * TICK_NSEC;
1991 rq->prev_steal_time_rq += steal;
1993 delta -= steal;
1995 #endif
1997 rq->clock_task += delta;
1999 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
2000 if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
2001 sched_rt_avg_update(rq, irq_delta + steal);
2002 #endif
2005 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
2006 static int irqtime_account_hi_update(void)
2008 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2009 unsigned long flags;
2010 u64 latest_ns;
2011 int ret = 0;
2013 local_irq_save(flags);
2014 latest_ns = this_cpu_read(cpu_hardirq_time);
2015 if (cputime64_gt(nsecs_to_cputime64(latest_ns), cpustat->irq))
2016 ret = 1;
2017 local_irq_restore(flags);
2018 return ret;
2021 static int irqtime_account_si_update(void)
2023 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2024 unsigned long flags;
2025 u64 latest_ns;
2026 int ret = 0;
2028 local_irq_save(flags);
2029 latest_ns = this_cpu_read(cpu_softirq_time);
2030 if (cputime64_gt(nsecs_to_cputime64(latest_ns), cpustat->softirq))
2031 ret = 1;
2032 local_irq_restore(flags);
2033 return ret;
2036 #else /* CONFIG_IRQ_TIME_ACCOUNTING */
2038 #define sched_clock_irqtime (0)
2040 #endif
2042 #include "sched_idletask.c"
2043 #include "sched_fair.c"
2044 #include "sched_rt.c"
2045 #include "sched_autogroup.c"
2046 #include "sched_stoptask.c"
2047 #ifdef CONFIG_SCHED_DEBUG
2048 # include "sched_debug.c"
2049 #endif
2051 void sched_set_stop_task(int cpu, struct task_struct *stop)
2053 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
2054 struct task_struct *old_stop = cpu_rq(cpu)->stop;
2056 if (stop) {
2058 * Make it appear like a SCHED_FIFO task, its something
2059 * userspace knows about and won't get confused about.
2061 * Also, it will make PI more or less work without too
2062 * much confusion -- but then, stop work should not
2063 * rely on PI working anyway.
2065 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
2067 stop->sched_class = &stop_sched_class;
2070 cpu_rq(cpu)->stop = stop;
2072 if (old_stop) {
2074 * Reset it back to a normal scheduling class so that
2075 * it can die in pieces.
2077 old_stop->sched_class = &rt_sched_class;
2082 * __normal_prio - return the priority that is based on the static prio
2084 static inline int __normal_prio(struct task_struct *p)
2086 return p->static_prio;
2090 * Calculate the expected normal priority: i.e. priority
2091 * without taking RT-inheritance into account. Might be
2092 * boosted by interactivity modifiers. Changes upon fork,
2093 * setprio syscalls, and whenever the interactivity
2094 * estimator recalculates.
2096 static inline int normal_prio(struct task_struct *p)
2098 int prio;
2100 if (task_has_rt_policy(p))
2101 prio = MAX_RT_PRIO-1 - p->rt_priority;
2102 else
2103 prio = __normal_prio(p);
2104 return prio;
2108 * Calculate the current priority, i.e. the priority
2109 * taken into account by the scheduler. This value might
2110 * be boosted by RT tasks, or might be boosted by
2111 * interactivity modifiers. Will be RT if the task got
2112 * RT-boosted. If not then it returns p->normal_prio.
2114 static int effective_prio(struct task_struct *p)
2116 p->normal_prio = normal_prio(p);
2118 * If we are RT tasks or we were boosted to RT priority,
2119 * keep the priority unchanged. Otherwise, update priority
2120 * to the normal priority:
2122 if (!rt_prio(p->prio))
2123 return p->normal_prio;
2124 return p->prio;
2128 * task_curr - is this task currently executing on a CPU?
2129 * @p: the task in question.
2131 inline int task_curr(const struct task_struct *p)
2133 return cpu_curr(task_cpu(p)) == p;
2136 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2137 const struct sched_class *prev_class,
2138 int oldprio)
2140 if (prev_class != p->sched_class) {
2141 if (prev_class->switched_from)
2142 prev_class->switched_from(rq, p);
2143 p->sched_class->switched_to(rq, p);
2144 } else if (oldprio != p->prio)
2145 p->sched_class->prio_changed(rq, p, oldprio);
2148 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
2150 const struct sched_class *class;
2152 if (p->sched_class == rq->curr->sched_class) {
2153 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
2154 } else {
2155 for_each_class(class) {
2156 if (class == rq->curr->sched_class)
2157 break;
2158 if (class == p->sched_class) {
2159 resched_task(rq->curr);
2160 break;
2166 * A queue event has occurred, and we're going to schedule. In
2167 * this case, we can save a useless back to back clock update.
2169 if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
2170 rq->skip_clock_update = 1;
2173 #ifdef CONFIG_SMP
2175 * Is this task likely cache-hot:
2177 static int
2178 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2180 s64 delta;
2182 if (p->sched_class != &fair_sched_class)
2183 return 0;
2185 if (unlikely(p->policy == SCHED_IDLE))
2186 return 0;
2189 * Buddy candidates are cache hot:
2191 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2192 (&p->se == cfs_rq_of(&p->se)->next ||
2193 &p->se == cfs_rq_of(&p->se)->last))
2194 return 1;
2196 if (sysctl_sched_migration_cost == -1)
2197 return 1;
2198 if (sysctl_sched_migration_cost == 0)
2199 return 0;
2201 delta = now - p->se.exec_start;
2203 return delta < (s64)sysctl_sched_migration_cost;
2206 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2208 #ifdef CONFIG_SCHED_DEBUG
2210 * We should never call set_task_cpu() on a blocked task,
2211 * ttwu() will sort out the placement.
2213 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2214 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2216 #ifdef CONFIG_LOCKDEP
2218 * The caller should hold either p->pi_lock or rq->lock, when changing
2219 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
2221 * sched_move_task() holds both and thus holding either pins the cgroup,
2222 * see set_task_rq().
2224 * Furthermore, all task_rq users should acquire both locks, see
2225 * task_rq_lock().
2227 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
2228 lockdep_is_held(&task_rq(p)->lock)));
2229 #endif
2230 #endif
2232 trace_sched_migrate_task(p, new_cpu);
2234 if (task_cpu(p) != new_cpu) {
2235 p->se.nr_migrations++;
2236 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
2239 __set_task_cpu(p, new_cpu);
2242 struct migration_arg {
2243 struct task_struct *task;
2244 int dest_cpu;
2247 static int migration_cpu_stop(void *data);
2250 * wait_task_inactive - wait for a thread to unschedule.
2252 * If @match_state is nonzero, it's the @p->state value just checked and
2253 * not expected to change. If it changes, i.e. @p might have woken up,
2254 * then return zero. When we succeed in waiting for @p to be off its CPU,
2255 * we return a positive number (its total switch count). If a second call
2256 * a short while later returns the same number, the caller can be sure that
2257 * @p has remained unscheduled the whole time.
2259 * The caller must ensure that the task *will* unschedule sometime soon,
2260 * else this function might spin for a *long* time. This function can't
2261 * be called with interrupts off, or it may introduce deadlock with
2262 * smp_call_function() if an IPI is sent by the same process we are
2263 * waiting to become inactive.
2265 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2267 unsigned long flags;
2268 int running, on_rq;
2269 unsigned long ncsw;
2270 struct rq *rq;
2272 for (;;) {
2274 * We do the initial early heuristics without holding
2275 * any task-queue locks at all. We'll only try to get
2276 * the runqueue lock when things look like they will
2277 * work out!
2279 rq = task_rq(p);
2282 * If the task is actively running on another CPU
2283 * still, just relax and busy-wait without holding
2284 * any locks.
2286 * NOTE! Since we don't hold any locks, it's not
2287 * even sure that "rq" stays as the right runqueue!
2288 * But we don't care, since "task_running()" will
2289 * return false if the runqueue has changed and p
2290 * is actually now running somewhere else!
2292 while (task_running(rq, p)) {
2293 if (match_state && unlikely(p->state != match_state))
2294 return 0;
2295 cpu_relax();
2299 * Ok, time to look more closely! We need the rq
2300 * lock now, to be *sure*. If we're wrong, we'll
2301 * just go back and repeat.
2303 rq = task_rq_lock(p, &flags);
2304 trace_sched_wait_task(p);
2305 running = task_running(rq, p);
2306 on_rq = p->on_rq;
2307 ncsw = 0;
2308 if (!match_state || p->state == match_state)
2309 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2310 task_rq_unlock(rq, p, &flags);
2313 * If it changed from the expected state, bail out now.
2315 if (unlikely(!ncsw))
2316 break;
2319 * Was it really running after all now that we
2320 * checked with the proper locks actually held?
2322 * Oops. Go back and try again..
2324 if (unlikely(running)) {
2325 cpu_relax();
2326 continue;
2330 * It's not enough that it's not actively running,
2331 * it must be off the runqueue _entirely_, and not
2332 * preempted!
2334 * So if it was still runnable (but just not actively
2335 * running right now), it's preempted, and we should
2336 * yield - it could be a while.
2338 if (unlikely(on_rq)) {
2339 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
2341 set_current_state(TASK_UNINTERRUPTIBLE);
2342 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
2343 continue;
2347 * Ahh, all good. It wasn't running, and it wasn't
2348 * runnable, which means that it will never become
2349 * running in the future either. We're all done!
2351 break;
2354 return ncsw;
2357 /***
2358 * kick_process - kick a running thread to enter/exit the kernel
2359 * @p: the to-be-kicked thread
2361 * Cause a process which is running on another CPU to enter
2362 * kernel-mode, without any delay. (to get signals handled.)
2364 * NOTE: this function doesn't have to take the runqueue lock,
2365 * because all it wants to ensure is that the remote task enters
2366 * the kernel. If the IPI races and the task has been migrated
2367 * to another CPU then no harm is done and the purpose has been
2368 * achieved as well.
2370 void kick_process(struct task_struct *p)
2372 int cpu;
2374 preempt_disable();
2375 cpu = task_cpu(p);
2376 if ((cpu != smp_processor_id()) && task_curr(p))
2377 smp_send_reschedule(cpu);
2378 preempt_enable();
2380 EXPORT_SYMBOL_GPL(kick_process);
2381 #endif /* CONFIG_SMP */
2383 #ifdef CONFIG_SMP
2385 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
2387 static int select_fallback_rq(int cpu, struct task_struct *p)
2389 int dest_cpu;
2390 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2392 /* Look for allowed, online CPU in same node. */
2393 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2394 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2395 return dest_cpu;
2397 /* Any allowed, online CPU? */
2398 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2399 if (dest_cpu < nr_cpu_ids)
2400 return dest_cpu;
2402 /* No more Mr. Nice Guy. */
2403 dest_cpu = cpuset_cpus_allowed_fallback(p);
2405 * Don't tell them about moving exiting tasks or
2406 * kernel threads (both mm NULL), since they never
2407 * leave kernel.
2409 if (p->mm && printk_ratelimit()) {
2410 printk(KERN_INFO "process %d (%s) no longer affine to cpu%d\n",
2411 task_pid_nr(p), p->comm, cpu);
2414 return dest_cpu;
2418 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
2420 static inline
2421 int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
2423 int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
2426 * In order not to call set_task_cpu() on a blocking task we need
2427 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2428 * cpu.
2430 * Since this is common to all placement strategies, this lives here.
2432 * [ this allows ->select_task() to simply return task_cpu(p) and
2433 * not worry about this generic constraint ]
2435 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2436 !cpu_online(cpu)))
2437 cpu = select_fallback_rq(task_cpu(p), p);
2439 return cpu;
2442 static void update_avg(u64 *avg, u64 sample)
2444 s64 diff = sample - *avg;
2445 *avg += diff >> 3;
2447 #endif
2449 static void
2450 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
2452 #ifdef CONFIG_SCHEDSTATS
2453 struct rq *rq = this_rq();
2455 #ifdef CONFIG_SMP
2456 int this_cpu = smp_processor_id();
2458 if (cpu == this_cpu) {
2459 schedstat_inc(rq, ttwu_local);
2460 schedstat_inc(p, se.statistics.nr_wakeups_local);
2461 } else {
2462 struct sched_domain *sd;
2464 schedstat_inc(p, se.statistics.nr_wakeups_remote);
2465 rcu_read_lock();
2466 for_each_domain(this_cpu, sd) {
2467 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2468 schedstat_inc(sd, ttwu_wake_remote);
2469 break;
2472 rcu_read_unlock();
2475 if (wake_flags & WF_MIGRATED)
2476 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
2478 #endif /* CONFIG_SMP */
2480 schedstat_inc(rq, ttwu_count);
2481 schedstat_inc(p, se.statistics.nr_wakeups);
2483 if (wake_flags & WF_SYNC)
2484 schedstat_inc(p, se.statistics.nr_wakeups_sync);
2486 #endif /* CONFIG_SCHEDSTATS */
2489 static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
2491 activate_task(rq, p, en_flags);
2492 p->on_rq = 1;
2494 /* if a worker is waking up, notify workqueue */
2495 if (p->flags & PF_WQ_WORKER)
2496 wq_worker_waking_up(p, cpu_of(rq));
2500 * Mark the task runnable and perform wakeup-preemption.
2502 static void
2503 ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
2505 trace_sched_wakeup(p, true);
2506 check_preempt_curr(rq, p, wake_flags);
2508 p->state = TASK_RUNNING;
2509 #ifdef CONFIG_SMP
2510 if (p->sched_class->task_woken)
2511 p->sched_class->task_woken(rq, p);
2513 if (rq->idle_stamp) {
2514 u64 delta = rq->clock - rq->idle_stamp;
2515 u64 max = 2*sysctl_sched_migration_cost;
2517 if (delta > max)
2518 rq->avg_idle = max;
2519 else
2520 update_avg(&rq->avg_idle, delta);
2521 rq->idle_stamp = 0;
2523 #endif
2526 static void
2527 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
2529 #ifdef CONFIG_SMP
2530 if (p->sched_contributes_to_load)
2531 rq->nr_uninterruptible--;
2532 #endif
2534 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
2535 ttwu_do_wakeup(rq, p, wake_flags);
2539 * Called in case the task @p isn't fully descheduled from its runqueue,
2540 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
2541 * since all we need to do is flip p->state to TASK_RUNNING, since
2542 * the task is still ->on_rq.
2544 static int ttwu_remote(struct task_struct *p, int wake_flags)
2546 struct rq *rq;
2547 int ret = 0;
2549 rq = __task_rq_lock(p);
2550 if (p->on_rq) {
2551 ttwu_do_wakeup(rq, p, wake_flags);
2552 ret = 1;
2554 __task_rq_unlock(rq);
2556 return ret;
2559 #ifdef CONFIG_SMP
2560 static void sched_ttwu_do_pending(struct task_struct *list)
2562 struct rq *rq = this_rq();
2564 raw_spin_lock(&rq->lock);
2566 while (list) {
2567 struct task_struct *p = list;
2568 list = list->wake_entry;
2569 ttwu_do_activate(rq, p, 0);
2572 raw_spin_unlock(&rq->lock);
2575 #ifdef CONFIG_HOTPLUG_CPU
2577 static void sched_ttwu_pending(void)
2579 struct rq *rq = this_rq();
2580 struct task_struct *list = xchg(&rq->wake_list, NULL);
2582 if (!list)
2583 return;
2585 sched_ttwu_do_pending(list);
2588 #endif /* CONFIG_HOTPLUG_CPU */
2590 void scheduler_ipi(void)
2592 struct rq *rq = this_rq();
2593 struct task_struct *list = xchg(&rq->wake_list, NULL);
2595 if (!list)
2596 return;
2599 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
2600 * traditionally all their work was done from the interrupt return
2601 * path. Now that we actually do some work, we need to make sure
2602 * we do call them.
2604 * Some archs already do call them, luckily irq_enter/exit nest
2605 * properly.
2607 * Arguably we should visit all archs and update all handlers,
2608 * however a fair share of IPIs are still resched only so this would
2609 * somewhat pessimize the simple resched case.
2611 irq_enter();
2612 sched_ttwu_do_pending(list);
2613 irq_exit();
2616 static void ttwu_queue_remote(struct task_struct *p, int cpu)
2618 struct rq *rq = cpu_rq(cpu);
2619 struct task_struct *next = rq->wake_list;
2621 for (;;) {
2622 struct task_struct *old = next;
2624 p->wake_entry = next;
2625 next = cmpxchg(&rq->wake_list, old, p);
2626 if (next == old)
2627 break;
2630 if (!next)
2631 smp_send_reschedule(cpu);
2634 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2635 static int ttwu_activate_remote(struct task_struct *p, int wake_flags)
2637 struct rq *rq;
2638 int ret = 0;
2640 rq = __task_rq_lock(p);
2641 if (p->on_cpu) {
2642 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2643 ttwu_do_wakeup(rq, p, wake_flags);
2644 ret = 1;
2646 __task_rq_unlock(rq);
2648 return ret;
2651 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2652 #endif /* CONFIG_SMP */
2654 static void ttwu_queue(struct task_struct *p, int cpu)
2656 struct rq *rq = cpu_rq(cpu);
2658 #if defined(CONFIG_SMP)
2659 if (sched_feat(TTWU_QUEUE) && cpu != smp_processor_id()) {
2660 sched_clock_cpu(cpu); /* sync clocks x-cpu */
2661 ttwu_queue_remote(p, cpu);
2662 return;
2664 #endif
2666 raw_spin_lock(&rq->lock);
2667 ttwu_do_activate(rq, p, 0);
2668 raw_spin_unlock(&rq->lock);
2672 * try_to_wake_up - wake up a thread
2673 * @p: the thread to be awakened
2674 * @state: the mask of task states that can be woken
2675 * @wake_flags: wake modifier flags (WF_*)
2677 * Put it on the run-queue if it's not already there. The "current"
2678 * thread is always on the run-queue (except when the actual
2679 * re-schedule is in progress), and as such you're allowed to do
2680 * the simpler "current->state = TASK_RUNNING" to mark yourself
2681 * runnable without the overhead of this.
2683 * Returns %true if @p was woken up, %false if it was already running
2684 * or @state didn't match @p's state.
2686 static int
2687 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
2689 unsigned long flags;
2690 int cpu, success = 0;
2692 smp_wmb();
2693 raw_spin_lock_irqsave(&p->pi_lock, flags);
2694 if (!(p->state & state))
2695 goto out;
2697 success = 1; /* we're going to change ->state */
2698 cpu = task_cpu(p);
2700 if (p->on_rq && ttwu_remote(p, wake_flags))
2701 goto stat;
2703 #ifdef CONFIG_SMP
2705 * If the owning (remote) cpu is still in the middle of schedule() with
2706 * this task as prev, wait until its done referencing the task.
2708 while (p->on_cpu) {
2709 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2711 * In case the architecture enables interrupts in
2712 * context_switch(), we cannot busy wait, since that
2713 * would lead to deadlocks when an interrupt hits and
2714 * tries to wake up @prev. So bail and do a complete
2715 * remote wakeup.
2717 if (ttwu_activate_remote(p, wake_flags))
2718 goto stat;
2719 #else
2720 cpu_relax();
2721 #endif
2724 * Pairs with the smp_wmb() in finish_lock_switch().
2726 smp_rmb();
2728 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2729 p->state = TASK_WAKING;
2731 if (p->sched_class->task_waking)
2732 p->sched_class->task_waking(p);
2734 cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
2735 if (task_cpu(p) != cpu) {
2736 wake_flags |= WF_MIGRATED;
2737 set_task_cpu(p, cpu);
2739 #endif /* CONFIG_SMP */
2741 ttwu_queue(p, cpu);
2742 stat:
2743 ttwu_stat(p, cpu, wake_flags);
2744 out:
2745 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2747 return success;
2751 * try_to_wake_up_local - try to wake up a local task with rq lock held
2752 * @p: the thread to be awakened
2754 * Put @p on the run-queue if it's not already there. The caller must
2755 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2756 * the current task.
2758 static void try_to_wake_up_local(struct task_struct *p)
2760 struct rq *rq = task_rq(p);
2762 BUG_ON(rq != this_rq());
2763 BUG_ON(p == current);
2764 lockdep_assert_held(&rq->lock);
2766 if (!raw_spin_trylock(&p->pi_lock)) {
2767 raw_spin_unlock(&rq->lock);
2768 raw_spin_lock(&p->pi_lock);
2769 raw_spin_lock(&rq->lock);
2772 if (!(p->state & TASK_NORMAL))
2773 goto out;
2775 if (!p->on_rq)
2776 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2778 ttwu_do_wakeup(rq, p, 0);
2779 ttwu_stat(p, smp_processor_id(), 0);
2780 out:
2781 raw_spin_unlock(&p->pi_lock);
2785 * wake_up_process - Wake up a specific process
2786 * @p: The process to be woken up.
2788 * Attempt to wake up the nominated process and move it to the set of runnable
2789 * processes. Returns 1 if the process was woken up, 0 if it was already
2790 * running.
2792 * It may be assumed that this function implies a write memory barrier before
2793 * changing the task state if and only if any tasks are woken up.
2795 int wake_up_process(struct task_struct *p)
2797 return try_to_wake_up(p, TASK_ALL, 0);
2799 EXPORT_SYMBOL(wake_up_process);
2801 int wake_up_state(struct task_struct *p, unsigned int state)
2803 return try_to_wake_up(p, state, 0);
2807 * Perform scheduler related setup for a newly forked process p.
2808 * p is forked by current.
2810 * __sched_fork() is basic setup used by init_idle() too:
2812 static void __sched_fork(struct task_struct *p)
2814 p->on_rq = 0;
2816 p->se.on_rq = 0;
2817 p->se.exec_start = 0;
2818 p->se.sum_exec_runtime = 0;
2819 p->se.prev_sum_exec_runtime = 0;
2820 p->se.nr_migrations = 0;
2821 p->se.vruntime = 0;
2822 INIT_LIST_HEAD(&p->se.group_node);
2824 #ifdef CONFIG_SCHEDSTATS
2825 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2826 #endif
2828 INIT_LIST_HEAD(&p->rt.run_list);
2830 #ifdef CONFIG_PREEMPT_NOTIFIERS
2831 INIT_HLIST_HEAD(&p->preempt_notifiers);
2832 #endif
2836 * fork()/clone()-time setup:
2838 void sched_fork(struct task_struct *p)
2840 unsigned long flags;
2841 int cpu = get_cpu();
2843 __sched_fork(p);
2845 * We mark the process as running here. This guarantees that
2846 * nobody will actually run it, and a signal or other external
2847 * event cannot wake it up and insert it on the runqueue either.
2849 p->state = TASK_RUNNING;
2852 * Revert to default priority/policy on fork if requested.
2854 if (unlikely(p->sched_reset_on_fork)) {
2855 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2856 p->policy = SCHED_NORMAL;
2857 p->normal_prio = p->static_prio;
2860 if (PRIO_TO_NICE(p->static_prio) < 0) {
2861 p->static_prio = NICE_TO_PRIO(0);
2862 p->normal_prio = p->static_prio;
2863 set_load_weight(p);
2867 * We don't need the reset flag anymore after the fork. It has
2868 * fulfilled its duty:
2870 p->sched_reset_on_fork = 0;
2874 * Make sure we do not leak PI boosting priority to the child.
2876 p->prio = current->normal_prio;
2878 if (!rt_prio(p->prio))
2879 p->sched_class = &fair_sched_class;
2881 if (p->sched_class->task_fork)
2882 p->sched_class->task_fork(p);
2885 * The child is not yet in the pid-hash so no cgroup attach races,
2886 * and the cgroup is pinned to this child due to cgroup_fork()
2887 * is ran before sched_fork().
2889 * Silence PROVE_RCU.
2891 raw_spin_lock_irqsave(&p->pi_lock, flags);
2892 set_task_cpu(p, cpu);
2893 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2895 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2896 if (likely(sched_info_on()))
2897 memset(&p->sched_info, 0, sizeof(p->sched_info));
2898 #endif
2899 #if defined(CONFIG_SMP)
2900 p->on_cpu = 0;
2901 #endif
2902 #ifdef CONFIG_PREEMPT_COUNT
2903 /* Want to start with kernel preemption disabled. */
2904 task_thread_info(p)->preempt_count = 1;
2905 #endif
2906 #ifdef CONFIG_SMP
2907 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2908 #endif
2910 put_cpu();
2914 * wake_up_new_task - wake up a newly created task for the first time.
2916 * This function will do some initial scheduler statistics housekeeping
2917 * that must be done for every newly created context, then puts the task
2918 * on the runqueue and wakes it.
2920 void wake_up_new_task(struct task_struct *p)
2922 unsigned long flags;
2923 struct rq *rq;
2925 raw_spin_lock_irqsave(&p->pi_lock, flags);
2926 #ifdef CONFIG_SMP
2928 * Fork balancing, do it here and not earlier because:
2929 * - cpus_allowed can change in the fork path
2930 * - any previously selected cpu might disappear through hotplug
2932 set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0));
2933 #endif
2935 rq = __task_rq_lock(p);
2936 activate_task(rq, p, 0);
2937 p->on_rq = 1;
2938 trace_sched_wakeup_new(p, true);
2939 check_preempt_curr(rq, p, WF_FORK);
2940 #ifdef CONFIG_SMP
2941 if (p->sched_class->task_woken)
2942 p->sched_class->task_woken(rq, p);
2943 #endif
2944 task_rq_unlock(rq, p, &flags);
2947 #ifdef CONFIG_PREEMPT_NOTIFIERS
2950 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2951 * @notifier: notifier struct to register
2953 void preempt_notifier_register(struct preempt_notifier *notifier)
2955 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2957 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2960 * preempt_notifier_unregister - no longer interested in preemption notifications
2961 * @notifier: notifier struct to unregister
2963 * This is safe to call from within a preemption notifier.
2965 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2967 hlist_del(&notifier->link);
2969 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2971 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2973 struct preempt_notifier *notifier;
2974 struct hlist_node *node;
2976 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2977 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2980 static void
2981 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2982 struct task_struct *next)
2984 struct preempt_notifier *notifier;
2985 struct hlist_node *node;
2987 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2988 notifier->ops->sched_out(notifier, next);
2991 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2993 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2997 static void
2998 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2999 struct task_struct *next)
3003 #endif /* CONFIG_PREEMPT_NOTIFIERS */
3006 * prepare_task_switch - prepare to switch tasks
3007 * @rq: the runqueue preparing to switch
3008 * @prev: the current task that is being switched out
3009 * @next: the task we are going to switch to.
3011 * This is called with the rq lock held and interrupts off. It must
3012 * be paired with a subsequent finish_task_switch after the context
3013 * switch.
3015 * prepare_task_switch sets up locking and calls architecture specific
3016 * hooks.
3018 static inline void
3019 prepare_task_switch(struct rq *rq, struct task_struct *prev,
3020 struct task_struct *next)
3022 sched_info_switch(prev, next);
3023 perf_event_task_sched_out(prev, next);
3024 fire_sched_out_preempt_notifiers(prev, next);
3025 prepare_lock_switch(rq, next);
3026 prepare_arch_switch(next);
3027 trace_sched_switch(prev, next);
3031 * finish_task_switch - clean up after a task-switch
3032 * @rq: runqueue associated with task-switch
3033 * @prev: the thread we just switched away from.
3035 * finish_task_switch must be called after the context switch, paired
3036 * with a prepare_task_switch call before the context switch.
3037 * finish_task_switch will reconcile locking set up by prepare_task_switch,
3038 * and do any other architecture-specific cleanup actions.
3040 * Note that we may have delayed dropping an mm in context_switch(). If
3041 * so, we finish that here outside of the runqueue lock. (Doing it
3042 * with the lock held can cause deadlocks; see schedule() for
3043 * details.)
3045 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
3046 __releases(rq->lock)
3048 struct mm_struct *mm = rq->prev_mm;
3049 long prev_state;
3051 rq->prev_mm = NULL;
3054 * A task struct has one reference for the use as "current".
3055 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
3056 * schedule one last time. The schedule call will never return, and
3057 * the scheduled task must drop that reference.
3058 * The test for TASK_DEAD must occur while the runqueue locks are
3059 * still held, otherwise prev could be scheduled on another cpu, die
3060 * there before we look at prev->state, and then the reference would
3061 * be dropped twice.
3062 * Manfred Spraul <manfred@colorfullife.com>
3064 prev_state = prev->state;
3065 finish_arch_switch(prev);
3066 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
3067 local_irq_disable();
3068 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
3069 perf_event_task_sched_in(current);
3070 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
3071 local_irq_enable();
3072 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
3073 finish_lock_switch(rq, prev);
3075 fire_sched_in_preempt_notifiers(current);
3076 if (mm)
3077 mmdrop(mm);
3078 if (unlikely(prev_state == TASK_DEAD)) {
3080 * Remove function-return probe instances associated with this
3081 * task and put them back on the free list.
3083 kprobe_flush_task(prev);
3084 put_task_struct(prev);
3088 #ifdef CONFIG_SMP
3090 /* assumes rq->lock is held */
3091 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
3093 if (prev->sched_class->pre_schedule)
3094 prev->sched_class->pre_schedule(rq, prev);
3097 /* rq->lock is NOT held, but preemption is disabled */
3098 static inline void post_schedule(struct rq *rq)
3100 if (rq->post_schedule) {
3101 unsigned long flags;
3103 raw_spin_lock_irqsave(&rq->lock, flags);
3104 if (rq->curr->sched_class->post_schedule)
3105 rq->curr->sched_class->post_schedule(rq);
3106 raw_spin_unlock_irqrestore(&rq->lock, flags);
3108 rq->post_schedule = 0;
3112 #else
3114 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
3118 static inline void post_schedule(struct rq *rq)
3122 #endif
3125 * schedule_tail - first thing a freshly forked thread must call.
3126 * @prev: the thread we just switched away from.
3128 asmlinkage void schedule_tail(struct task_struct *prev)
3129 __releases(rq->lock)
3131 struct rq *rq = this_rq();
3133 finish_task_switch(rq, prev);
3136 * FIXME: do we need to worry about rq being invalidated by the
3137 * task_switch?
3139 post_schedule(rq);
3141 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
3142 /* In this case, finish_task_switch does not reenable preemption */
3143 preempt_enable();
3144 #endif
3145 if (current->set_child_tid)
3146 put_user(task_pid_vnr(current), current->set_child_tid);
3150 * context_switch - switch to the new MM and the new
3151 * thread's register state.
3153 static inline void
3154 context_switch(struct rq *rq, struct task_struct *prev,
3155 struct task_struct *next)
3157 struct mm_struct *mm, *oldmm;
3159 prepare_task_switch(rq, prev, next);
3161 mm = next->mm;
3162 oldmm = prev->active_mm;
3164 * For paravirt, this is coupled with an exit in switch_to to
3165 * combine the page table reload and the switch backend into
3166 * one hypercall.
3168 arch_start_context_switch(prev);
3170 if (!mm) {
3171 next->active_mm = oldmm;
3172 atomic_inc(&oldmm->mm_count);
3173 enter_lazy_tlb(oldmm, next);
3174 } else
3175 switch_mm(oldmm, mm, next);
3177 if (!prev->mm) {
3178 prev->active_mm = NULL;
3179 rq->prev_mm = oldmm;
3182 * Since the runqueue lock will be released by the next
3183 * task (which is an invalid locking op but in the case
3184 * of the scheduler it's an obvious special-case), so we
3185 * do an early lockdep release here:
3187 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
3188 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3189 #endif
3191 /* Here we just switch the register state and the stack. */
3192 switch_to(prev, next, prev);
3194 barrier();
3196 * this_rq must be evaluated again because prev may have moved
3197 * CPUs since it called schedule(), thus the 'rq' on its stack
3198 * frame will be invalid.
3200 finish_task_switch(this_rq(), prev);
3204 * nr_running, nr_uninterruptible and nr_context_switches:
3206 * externally visible scheduler statistics: current number of runnable
3207 * threads, current number of uninterruptible-sleeping threads, total
3208 * number of context switches performed since bootup.
3210 unsigned long nr_running(void)
3212 unsigned long i, sum = 0;
3214 for_each_online_cpu(i)
3215 sum += cpu_rq(i)->nr_running;
3217 return sum;
3220 unsigned long nr_uninterruptible(void)
3222 unsigned long i, sum = 0;
3224 for_each_possible_cpu(i)
3225 sum += cpu_rq(i)->nr_uninterruptible;
3228 * Since we read the counters lockless, it might be slightly
3229 * inaccurate. Do not allow it to go below zero though:
3231 if (unlikely((long)sum < 0))
3232 sum = 0;
3234 return sum;
3237 unsigned long long nr_context_switches(void)
3239 int i;
3240 unsigned long long sum = 0;
3242 for_each_possible_cpu(i)
3243 sum += cpu_rq(i)->nr_switches;
3245 return sum;
3248 unsigned long nr_iowait(void)
3250 unsigned long i, sum = 0;
3252 for_each_possible_cpu(i)
3253 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3255 return sum;
3258 unsigned long nr_iowait_cpu(int cpu)
3260 struct rq *this = cpu_rq(cpu);
3261 return atomic_read(&this->nr_iowait);
3264 unsigned long this_cpu_load(void)
3266 struct rq *this = this_rq();
3267 return this->cpu_load[0];
3271 /* Variables and functions for calc_load */
3272 static atomic_long_t calc_load_tasks;
3273 static unsigned long calc_load_update;
3274 unsigned long avenrun[3];
3275 EXPORT_SYMBOL(avenrun);
3277 static long calc_load_fold_active(struct rq *this_rq)
3279 long nr_active, delta = 0;
3281 nr_active = this_rq->nr_running;
3282 nr_active += (long) this_rq->nr_uninterruptible;
3284 if (nr_active != this_rq->calc_load_active) {
3285 delta = nr_active - this_rq->calc_load_active;
3286 this_rq->calc_load_active = nr_active;
3289 return delta;
3292 static unsigned long
3293 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3295 load *= exp;
3296 load += active * (FIXED_1 - exp);
3297 load += 1UL << (FSHIFT - 1);
3298 return load >> FSHIFT;
3301 #ifdef CONFIG_NO_HZ
3303 * For NO_HZ we delay the active fold to the next LOAD_FREQ update.
3305 * When making the ILB scale, we should try to pull this in as well.
3307 static atomic_long_t calc_load_tasks_idle;
3309 static void calc_load_account_idle(struct rq *this_rq)
3311 long delta;
3313 delta = calc_load_fold_active(this_rq);
3314 if (delta)
3315 atomic_long_add(delta, &calc_load_tasks_idle);
3318 static long calc_load_fold_idle(void)
3320 long delta = 0;
3323 * Its got a race, we don't care...
3325 if (atomic_long_read(&calc_load_tasks_idle))
3326 delta = atomic_long_xchg(&calc_load_tasks_idle, 0);
3328 return delta;
3332 * fixed_power_int - compute: x^n, in O(log n) time
3334 * @x: base of the power
3335 * @frac_bits: fractional bits of @x
3336 * @n: power to raise @x to.
3338 * By exploiting the relation between the definition of the natural power
3339 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
3340 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
3341 * (where: n_i \elem {0, 1}, the binary vector representing n),
3342 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
3343 * of course trivially computable in O(log_2 n), the length of our binary
3344 * vector.
3346 static unsigned long
3347 fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
3349 unsigned long result = 1UL << frac_bits;
3351 if (n) for (;;) {
3352 if (n & 1) {
3353 result *= x;
3354 result += 1UL << (frac_bits - 1);
3355 result >>= frac_bits;
3357 n >>= 1;
3358 if (!n)
3359 break;
3360 x *= x;
3361 x += 1UL << (frac_bits - 1);
3362 x >>= frac_bits;
3365 return result;
3369 * a1 = a0 * e + a * (1 - e)
3371 * a2 = a1 * e + a * (1 - e)
3372 * = (a0 * e + a * (1 - e)) * e + a * (1 - e)
3373 * = a0 * e^2 + a * (1 - e) * (1 + e)
3375 * a3 = a2 * e + a * (1 - e)
3376 * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
3377 * = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
3379 * ...
3381 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
3382 * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
3383 * = a0 * e^n + a * (1 - e^n)
3385 * [1] application of the geometric series:
3387 * n 1 - x^(n+1)
3388 * S_n := \Sum x^i = -------------
3389 * i=0 1 - x
3391 static unsigned long
3392 calc_load_n(unsigned long load, unsigned long exp,
3393 unsigned long active, unsigned int n)
3396 return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
3400 * NO_HZ can leave us missing all per-cpu ticks calling
3401 * calc_load_account_active(), but since an idle CPU folds its delta into
3402 * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
3403 * in the pending idle delta if our idle period crossed a load cycle boundary.
3405 * Once we've updated the global active value, we need to apply the exponential
3406 * weights adjusted to the number of cycles missed.
3408 static void calc_global_nohz(unsigned long ticks)
3410 long delta, active, n;
3412 if (time_before(jiffies, calc_load_update))
3413 return;
3416 * If we crossed a calc_load_update boundary, make sure to fold
3417 * any pending idle changes, the respective CPUs might have
3418 * missed the tick driven calc_load_account_active() update
3419 * due to NO_HZ.
3421 delta = calc_load_fold_idle();
3422 if (delta)
3423 atomic_long_add(delta, &calc_load_tasks);
3426 * If we were idle for multiple load cycles, apply them.
3428 if (ticks >= LOAD_FREQ) {
3429 n = ticks / LOAD_FREQ;
3431 active = atomic_long_read(&calc_load_tasks);
3432 active = active > 0 ? active * FIXED_1 : 0;
3434 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
3435 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
3436 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
3438 calc_load_update += n * LOAD_FREQ;
3442 * Its possible the remainder of the above division also crosses
3443 * a LOAD_FREQ period, the regular check in calc_global_load()
3444 * which comes after this will take care of that.
3446 * Consider us being 11 ticks before a cycle completion, and us
3447 * sleeping for 4*LOAD_FREQ + 22 ticks, then the above code will
3448 * age us 4 cycles, and the test in calc_global_load() will
3449 * pick up the final one.
3452 #else
3453 static void calc_load_account_idle(struct rq *this_rq)
3457 static inline long calc_load_fold_idle(void)
3459 return 0;
3462 static void calc_global_nohz(unsigned long ticks)
3465 #endif
3468 * get_avenrun - get the load average array
3469 * @loads: pointer to dest load array
3470 * @offset: offset to add
3471 * @shift: shift count to shift the result left
3473 * These values are estimates at best, so no need for locking.
3475 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3477 loads[0] = (avenrun[0] + offset) << shift;
3478 loads[1] = (avenrun[1] + offset) << shift;
3479 loads[2] = (avenrun[2] + offset) << shift;
3483 * calc_load - update the avenrun load estimates 10 ticks after the
3484 * CPUs have updated calc_load_tasks.
3486 void calc_global_load(unsigned long ticks)
3488 long active;
3490 calc_global_nohz(ticks);
3492 if (time_before(jiffies, calc_load_update + 10))
3493 return;
3495 active = atomic_long_read(&calc_load_tasks);
3496 active = active > 0 ? active * FIXED_1 : 0;
3498 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3499 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3500 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3502 calc_load_update += LOAD_FREQ;
3506 * Called from update_cpu_load() to periodically update this CPU's
3507 * active count.
3509 static void calc_load_account_active(struct rq *this_rq)
3511 long delta;
3513 if (time_before(jiffies, this_rq->calc_load_update))
3514 return;
3516 delta = calc_load_fold_active(this_rq);
3517 delta += calc_load_fold_idle();
3518 if (delta)
3519 atomic_long_add(delta, &calc_load_tasks);
3521 this_rq->calc_load_update += LOAD_FREQ;
3525 * The exact cpuload at various idx values, calculated at every tick would be
3526 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
3528 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
3529 * on nth tick when cpu may be busy, then we have:
3530 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3531 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
3533 * decay_load_missed() below does efficient calculation of
3534 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3535 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
3537 * The calculation is approximated on a 128 point scale.
3538 * degrade_zero_ticks is the number of ticks after which load at any
3539 * particular idx is approximated to be zero.
3540 * degrade_factor is a precomputed table, a row for each load idx.
3541 * Each column corresponds to degradation factor for a power of two ticks,
3542 * based on 128 point scale.
3543 * Example:
3544 * row 2, col 3 (=12) says that the degradation at load idx 2 after
3545 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
3547 * With this power of 2 load factors, we can degrade the load n times
3548 * by looking at 1 bits in n and doing as many mult/shift instead of
3549 * n mult/shifts needed by the exact degradation.
3551 #define DEGRADE_SHIFT 7
3552 static const unsigned char
3553 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
3554 static const unsigned char
3555 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
3556 {0, 0, 0, 0, 0, 0, 0, 0},
3557 {64, 32, 8, 0, 0, 0, 0, 0},
3558 {96, 72, 40, 12, 1, 0, 0},
3559 {112, 98, 75, 43, 15, 1, 0},
3560 {120, 112, 98, 76, 45, 16, 2} };
3563 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
3564 * would be when CPU is idle and so we just decay the old load without
3565 * adding any new load.
3567 static unsigned long
3568 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
3570 int j = 0;
3572 if (!missed_updates)
3573 return load;
3575 if (missed_updates >= degrade_zero_ticks[idx])
3576 return 0;
3578 if (idx == 1)
3579 return load >> missed_updates;
3581 while (missed_updates) {
3582 if (missed_updates % 2)
3583 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
3585 missed_updates >>= 1;
3586 j++;
3588 return load;
3592 * Update rq->cpu_load[] statistics. This function is usually called every
3593 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
3594 * every tick. We fix it up based on jiffies.
3596 static void update_cpu_load(struct rq *this_rq)
3598 unsigned long this_load = this_rq->load.weight;
3599 unsigned long curr_jiffies = jiffies;
3600 unsigned long pending_updates;
3601 int i, scale;
3603 this_rq->nr_load_updates++;
3605 /* Avoid repeated calls on same jiffy, when moving in and out of idle */
3606 if (curr_jiffies == this_rq->last_load_update_tick)
3607 return;
3609 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
3610 this_rq->last_load_update_tick = curr_jiffies;
3612 /* Update our load: */
3613 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
3614 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3615 unsigned long old_load, new_load;
3617 /* scale is effectively 1 << i now, and >> i divides by scale */
3619 old_load = this_rq->cpu_load[i];
3620 old_load = decay_load_missed(old_load, pending_updates - 1, i);
3621 new_load = this_load;
3623 * Round up the averaging division if load is increasing. This
3624 * prevents us from getting stuck on 9 if the load is 10, for
3625 * example.
3627 if (new_load > old_load)
3628 new_load += scale - 1;
3630 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
3633 sched_avg_update(this_rq);
3636 static void update_cpu_load_active(struct rq *this_rq)
3638 update_cpu_load(this_rq);
3640 calc_load_account_active(this_rq);
3643 #ifdef CONFIG_SMP
3646 * sched_exec - execve() is a valuable balancing opportunity, because at
3647 * this point the task has the smallest effective memory and cache footprint.
3649 void sched_exec(void)
3651 struct task_struct *p = current;
3652 unsigned long flags;
3653 int dest_cpu;
3655 raw_spin_lock_irqsave(&p->pi_lock, flags);
3656 dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0);
3657 if (dest_cpu == smp_processor_id())
3658 goto unlock;
3660 if (likely(cpu_active(dest_cpu))) {
3661 struct migration_arg arg = { p, dest_cpu };
3663 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3664 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
3665 return;
3667 unlock:
3668 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3671 #endif
3673 DEFINE_PER_CPU(struct kernel_stat, kstat);
3675 EXPORT_PER_CPU_SYMBOL(kstat);
3678 * Return any ns on the sched_clock that have not yet been accounted in
3679 * @p in case that task is currently running.
3681 * Called with task_rq_lock() held on @rq.
3683 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
3685 u64 ns = 0;
3687 if (task_current(rq, p)) {
3688 update_rq_clock(rq);
3689 ns = rq->clock_task - p->se.exec_start;
3690 if ((s64)ns < 0)
3691 ns = 0;
3694 return ns;
3697 unsigned long long task_delta_exec(struct task_struct *p)
3699 unsigned long flags;
3700 struct rq *rq;
3701 u64 ns = 0;
3703 rq = task_rq_lock(p, &flags);
3704 ns = do_task_delta_exec(p, rq);
3705 task_rq_unlock(rq, p, &flags);
3707 return ns;
3711 * Return accounted runtime for the task.
3712 * In case the task is currently running, return the runtime plus current's
3713 * pending runtime that have not been accounted yet.
3715 unsigned long long task_sched_runtime(struct task_struct *p)
3717 unsigned long flags;
3718 struct rq *rq;
3719 u64 ns = 0;
3721 rq = task_rq_lock(p, &flags);
3722 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
3723 task_rq_unlock(rq, p, &flags);
3725 return ns;
3729 * Return sum_exec_runtime for the thread group.
3730 * In case the task is currently running, return the sum plus current's
3731 * pending runtime that have not been accounted yet.
3733 * Note that the thread group might have other running tasks as well,
3734 * so the return value not includes other pending runtime that other
3735 * running tasks might have.
3737 unsigned long long thread_group_sched_runtime(struct task_struct *p)
3739 struct task_cputime totals;
3740 unsigned long flags;
3741 struct rq *rq;
3742 u64 ns;
3744 rq = task_rq_lock(p, &flags);
3745 thread_group_cputime(p, &totals);
3746 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
3747 task_rq_unlock(rq, p, &flags);
3749 return ns;
3753 * Account user cpu time to a process.
3754 * @p: the process that the cpu time gets accounted to
3755 * @cputime: the cpu time spent in user space since the last update
3756 * @cputime_scaled: cputime scaled by cpu frequency
3758 void account_user_time(struct task_struct *p, cputime_t cputime,
3759 cputime_t cputime_scaled)
3761 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3762 cputime64_t tmp;
3764 /* Add user time to process. */
3765 p->utime = cputime_add(p->utime, cputime);
3766 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3767 account_group_user_time(p, cputime);
3769 /* Add user time to cpustat. */
3770 tmp = cputime_to_cputime64(cputime);
3771 if (TASK_NICE(p) > 0)
3772 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3773 else
3774 cpustat->user = cputime64_add(cpustat->user, tmp);
3776 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
3777 /* Account for user time used */
3778 acct_update_integrals(p);
3782 * Account guest cpu time to a process.
3783 * @p: the process that the cpu time gets accounted to
3784 * @cputime: the cpu time spent in virtual machine since the last update
3785 * @cputime_scaled: cputime scaled by cpu frequency
3787 static void account_guest_time(struct task_struct *p, cputime_t cputime,
3788 cputime_t cputime_scaled)
3790 cputime64_t tmp;
3791 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3793 tmp = cputime_to_cputime64(cputime);
3795 /* Add guest time to process. */
3796 p->utime = cputime_add(p->utime, cputime);
3797 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3798 account_group_user_time(p, cputime);
3799 p->gtime = cputime_add(p->gtime, cputime);
3801 /* Add guest time to cpustat. */
3802 if (TASK_NICE(p) > 0) {
3803 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3804 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
3805 } else {
3806 cpustat->user = cputime64_add(cpustat->user, tmp);
3807 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3812 * Account system cpu time to a process and desired cpustat field
3813 * @p: the process that the cpu time gets accounted to
3814 * @cputime: the cpu time spent in kernel space since the last update
3815 * @cputime_scaled: cputime scaled by cpu frequency
3816 * @target_cputime64: pointer to cpustat field that has to be updated
3818 static inline
3819 void __account_system_time(struct task_struct *p, cputime_t cputime,
3820 cputime_t cputime_scaled, cputime64_t *target_cputime64)
3822 cputime64_t tmp = cputime_to_cputime64(cputime);
3824 /* Add system time to process. */
3825 p->stime = cputime_add(p->stime, cputime);
3826 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
3827 account_group_system_time(p, cputime);
3829 /* Add system time to cpustat. */
3830 *target_cputime64 = cputime64_add(*target_cputime64, tmp);
3831 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
3833 /* Account for system time used */
3834 acct_update_integrals(p);
3838 * Account system cpu time to a process.
3839 * @p: the process that the cpu time gets accounted to
3840 * @hardirq_offset: the offset to subtract from hardirq_count()
3841 * @cputime: the cpu time spent in kernel space since the last update
3842 * @cputime_scaled: cputime scaled by cpu frequency
3844 void account_system_time(struct task_struct *p, int hardirq_offset,
3845 cputime_t cputime, cputime_t cputime_scaled)
3847 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3848 cputime64_t *target_cputime64;
3850 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
3851 account_guest_time(p, cputime, cputime_scaled);
3852 return;
3855 if (hardirq_count() - hardirq_offset)
3856 target_cputime64 = &cpustat->irq;
3857 else if (in_serving_softirq())
3858 target_cputime64 = &cpustat->softirq;
3859 else
3860 target_cputime64 = &cpustat->system;
3862 __account_system_time(p, cputime, cputime_scaled, target_cputime64);
3866 * Account for involuntary wait time.
3867 * @cputime: the cpu time spent in involuntary wait
3869 void account_steal_time(cputime_t cputime)
3871 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3872 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3874 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
3878 * Account for idle time.
3879 * @cputime: the cpu time spent in idle wait
3881 void account_idle_time(cputime_t cputime)
3883 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3884 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3885 struct rq *rq = this_rq();
3887 if (atomic_read(&rq->nr_iowait) > 0)
3888 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
3889 else
3890 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
3893 static __always_inline bool steal_account_process_tick(void)
3895 #ifdef CONFIG_PARAVIRT
3896 if (static_branch(&paravirt_steal_enabled)) {
3897 u64 steal, st = 0;
3899 steal = paravirt_steal_clock(smp_processor_id());
3900 steal -= this_rq()->prev_steal_time;
3902 st = steal_ticks(steal);
3903 this_rq()->prev_steal_time += st * TICK_NSEC;
3905 account_steal_time(st);
3906 return st;
3908 #endif
3909 return false;
3912 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
3914 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
3916 * Account a tick to a process and cpustat
3917 * @p: the process that the cpu time gets accounted to
3918 * @user_tick: is the tick from userspace
3919 * @rq: the pointer to rq
3921 * Tick demultiplexing follows the order
3922 * - pending hardirq update
3923 * - pending softirq update
3924 * - user_time
3925 * - idle_time
3926 * - system time
3927 * - check for guest_time
3928 * - else account as system_time
3930 * Check for hardirq is done both for system and user time as there is
3931 * no timer going off while we are on hardirq and hence we may never get an
3932 * opportunity to update it solely in system time.
3933 * p->stime and friends are only updated on system time and not on irq
3934 * softirq as those do not count in task exec_runtime any more.
3936 static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
3937 struct rq *rq)
3939 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3940 cputime64_t tmp = cputime_to_cputime64(cputime_one_jiffy);
3941 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3943 if (steal_account_process_tick())
3944 return;
3946 if (irqtime_account_hi_update()) {
3947 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3948 } else if (irqtime_account_si_update()) {
3949 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3950 } else if (this_cpu_ksoftirqd() == p) {
3952 * ksoftirqd time do not get accounted in cpu_softirq_time.
3953 * So, we have to handle it separately here.
3954 * Also, p->stime needs to be updated for ksoftirqd.
3956 __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled,
3957 &cpustat->softirq);
3958 } else if (user_tick) {
3959 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3960 } else if (p == rq->idle) {
3961 account_idle_time(cputime_one_jiffy);
3962 } else if (p->flags & PF_VCPU) { /* System time or guest time */
3963 account_guest_time(p, cputime_one_jiffy, one_jiffy_scaled);
3964 } else {
3965 __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled,
3966 &cpustat->system);
3970 static void irqtime_account_idle_ticks(int ticks)
3972 int i;
3973 struct rq *rq = this_rq();
3975 for (i = 0; i < ticks; i++)
3976 irqtime_account_process_tick(current, 0, rq);
3978 #else /* CONFIG_IRQ_TIME_ACCOUNTING */
3979 static void irqtime_account_idle_ticks(int ticks) {}
3980 static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
3981 struct rq *rq) {}
3982 #endif /* CONFIG_IRQ_TIME_ACCOUNTING */
3985 * Account a single tick of cpu time.
3986 * @p: the process that the cpu time gets accounted to
3987 * @user_tick: indicates if the tick is a user or a system tick
3989 void account_process_tick(struct task_struct *p, int user_tick)
3991 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3992 struct rq *rq = this_rq();
3994 if (sched_clock_irqtime) {
3995 irqtime_account_process_tick(p, user_tick, rq);
3996 return;
3999 if (steal_account_process_tick())
4000 return;
4002 if (user_tick)
4003 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
4004 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
4005 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
4006 one_jiffy_scaled);
4007 else
4008 account_idle_time(cputime_one_jiffy);
4012 * Account multiple ticks of steal time.
4013 * @p: the process from which the cpu time has been stolen
4014 * @ticks: number of stolen ticks
4016 void account_steal_ticks(unsigned long ticks)
4018 account_steal_time(jiffies_to_cputime(ticks));
4022 * Account multiple ticks of idle time.
4023 * @ticks: number of stolen ticks
4025 void account_idle_ticks(unsigned long ticks)
4028 if (sched_clock_irqtime) {
4029 irqtime_account_idle_ticks(ticks);
4030 return;
4033 account_idle_time(jiffies_to_cputime(ticks));
4036 #endif
4039 * Use precise platform statistics if available:
4041 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
4042 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4044 *ut = p->utime;
4045 *st = p->stime;
4048 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4050 struct task_cputime cputime;
4052 thread_group_cputime(p, &cputime);
4054 *ut = cputime.utime;
4055 *st = cputime.stime;
4057 #else
4059 #ifndef nsecs_to_cputime
4060 # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
4061 #endif
4063 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4065 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
4068 * Use CFS's precise accounting:
4070 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
4072 if (total) {
4073 u64 temp = rtime;
4075 temp *= utime;
4076 do_div(temp, total);
4077 utime = (cputime_t)temp;
4078 } else
4079 utime = rtime;
4082 * Compare with previous values, to keep monotonicity:
4084 p->prev_utime = max(p->prev_utime, utime);
4085 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
4087 *ut = p->prev_utime;
4088 *st = p->prev_stime;
4092 * Must be called with siglock held.
4094 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4096 struct signal_struct *sig = p->signal;
4097 struct task_cputime cputime;
4098 cputime_t rtime, utime, total;
4100 thread_group_cputime(p, &cputime);
4102 total = cputime_add(cputime.utime, cputime.stime);
4103 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
4105 if (total) {
4106 u64 temp = rtime;
4108 temp *= cputime.utime;
4109 do_div(temp, total);
4110 utime = (cputime_t)temp;
4111 } else
4112 utime = rtime;
4114 sig->prev_utime = max(sig->prev_utime, utime);
4115 sig->prev_stime = max(sig->prev_stime,
4116 cputime_sub(rtime, sig->prev_utime));
4118 *ut = sig->prev_utime;
4119 *st = sig->prev_stime;
4121 #endif
4124 * This function gets called by the timer code, with HZ frequency.
4125 * We call it with interrupts disabled.
4127 void scheduler_tick(void)
4129 int cpu = smp_processor_id();
4130 struct rq *rq = cpu_rq(cpu);
4131 struct task_struct *curr = rq->curr;
4133 sched_clock_tick();
4135 raw_spin_lock(&rq->lock);
4136 update_rq_clock(rq);
4137 update_cpu_load_active(rq);
4138 curr->sched_class->task_tick(rq, curr, 0);
4139 raw_spin_unlock(&rq->lock);
4141 perf_event_task_tick();
4143 #ifdef CONFIG_SMP
4144 rq->idle_at_tick = idle_cpu(cpu);
4145 trigger_load_balance(rq, cpu);
4146 #endif
4149 notrace unsigned long get_parent_ip(unsigned long addr)
4151 if (in_lock_functions(addr)) {
4152 addr = CALLER_ADDR2;
4153 if (in_lock_functions(addr))
4154 addr = CALLER_ADDR3;
4156 return addr;
4159 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4160 defined(CONFIG_PREEMPT_TRACER))
4162 void __kprobes add_preempt_count(int val)
4164 #ifdef CONFIG_DEBUG_PREEMPT
4166 * Underflow?
4168 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4169 return;
4170 #endif
4171 preempt_count() += val;
4172 #ifdef CONFIG_DEBUG_PREEMPT
4174 * Spinlock count overflowing soon?
4176 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4177 PREEMPT_MASK - 10);
4178 #endif
4179 if (preempt_count() == val)
4180 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4182 EXPORT_SYMBOL(add_preempt_count);
4184 void __kprobes sub_preempt_count(int val)
4186 #ifdef CONFIG_DEBUG_PREEMPT
4188 * Underflow?
4190 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4191 return;
4193 * Is the spinlock portion underflowing?
4195 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4196 !(preempt_count() & PREEMPT_MASK)))
4197 return;
4198 #endif
4200 if (preempt_count() == val)
4201 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4202 preempt_count() -= val;
4204 EXPORT_SYMBOL(sub_preempt_count);
4206 #endif
4209 * Print scheduling while atomic bug:
4211 static noinline void __schedule_bug(struct task_struct *prev)
4213 struct pt_regs *regs = get_irq_regs();
4215 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4216 prev->comm, prev->pid, preempt_count());
4218 debug_show_held_locks(prev);
4219 print_modules();
4220 if (irqs_disabled())
4221 print_irqtrace_events(prev);
4223 if (regs)
4224 show_regs(regs);
4225 else
4226 dump_stack();
4230 * Various schedule()-time debugging checks and statistics:
4232 static inline void schedule_debug(struct task_struct *prev)
4235 * Test if we are atomic. Since do_exit() needs to call into
4236 * schedule() atomically, we ignore that path for now.
4237 * Otherwise, whine if we are scheduling when we should not be.
4239 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
4240 __schedule_bug(prev);
4242 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4244 schedstat_inc(this_rq(), sched_count);
4247 static void put_prev_task(struct rq *rq, struct task_struct *prev)
4249 if (prev->on_rq || rq->skip_clock_update < 0)
4250 update_rq_clock(rq);
4251 prev->sched_class->put_prev_task(rq, prev);
4255 * Pick up the highest-prio task:
4257 static inline struct task_struct *
4258 pick_next_task(struct rq *rq)
4260 const struct sched_class *class;
4261 struct task_struct *p;
4264 * Optimization: we know that if all tasks are in
4265 * the fair class we can call that function directly:
4267 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4268 p = fair_sched_class.pick_next_task(rq);
4269 if (likely(p))
4270 return p;
4273 for_each_class(class) {
4274 p = class->pick_next_task(rq);
4275 if (p)
4276 return p;
4279 BUG(); /* the idle class will always have a runnable task */
4283 * schedule() is the main scheduler function.
4285 asmlinkage void __sched schedule(void)
4287 struct task_struct *prev, *next;
4288 unsigned long *switch_count;
4289 struct rq *rq;
4290 int cpu;
4292 need_resched:
4293 preempt_disable();
4294 cpu = smp_processor_id();
4295 rq = cpu_rq(cpu);
4296 rcu_note_context_switch(cpu);
4297 prev = rq->curr;
4299 schedule_debug(prev);
4301 if (sched_feat(HRTICK))
4302 hrtick_clear(rq);
4304 raw_spin_lock_irq(&rq->lock);
4306 switch_count = &prev->nivcsw;
4307 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4308 if (unlikely(signal_pending_state(prev->state, prev))) {
4309 prev->state = TASK_RUNNING;
4310 } else {
4311 deactivate_task(rq, prev, DEQUEUE_SLEEP);
4312 prev->on_rq = 0;
4315 * If a worker went to sleep, notify and ask workqueue
4316 * whether it wants to wake up a task to maintain
4317 * concurrency.
4319 if (prev->flags & PF_WQ_WORKER) {
4320 struct task_struct *to_wakeup;
4322 to_wakeup = wq_worker_sleeping(prev, cpu);
4323 if (to_wakeup)
4324 try_to_wake_up_local(to_wakeup);
4328 * If we are going to sleep and we have plugged IO
4329 * queued, make sure to submit it to avoid deadlocks.
4331 if (blk_needs_flush_plug(prev)) {
4332 raw_spin_unlock(&rq->lock);
4333 blk_schedule_flush_plug(prev);
4334 raw_spin_lock(&rq->lock);
4337 switch_count = &prev->nvcsw;
4340 pre_schedule(rq, prev);
4342 if (unlikely(!rq->nr_running))
4343 idle_balance(cpu, rq);
4345 put_prev_task(rq, prev);
4346 next = pick_next_task(rq);
4347 clear_tsk_need_resched(prev);
4348 rq->skip_clock_update = 0;
4350 if (likely(prev != next)) {
4351 rq->nr_switches++;
4352 rq->curr = next;
4353 ++*switch_count;
4355 context_switch(rq, prev, next); /* unlocks the rq */
4357 * The context switch have flipped the stack from under us
4358 * and restored the local variables which were saved when
4359 * this task called schedule() in the past. prev == current
4360 * is still correct, but it can be moved to another cpu/rq.
4362 cpu = smp_processor_id();
4363 rq = cpu_rq(cpu);
4364 } else
4365 raw_spin_unlock_irq(&rq->lock);
4367 post_schedule(rq);
4369 preempt_enable_no_resched();
4370 if (need_resched())
4371 goto need_resched;
4373 EXPORT_SYMBOL(schedule);
4375 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
4377 static inline bool owner_running(struct mutex *lock, struct task_struct *owner)
4379 if (lock->owner != owner)
4380 return false;
4383 * Ensure we emit the owner->on_cpu, dereference _after_ checking
4384 * lock->owner still matches owner, if that fails, owner might
4385 * point to free()d memory, if it still matches, the rcu_read_lock()
4386 * ensures the memory stays valid.
4388 barrier();
4390 return owner->on_cpu;
4394 * Look out! "owner" is an entirely speculative pointer
4395 * access and not reliable.
4397 int mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner)
4399 if (!sched_feat(OWNER_SPIN))
4400 return 0;
4402 rcu_read_lock();
4403 while (owner_running(lock, owner)) {
4404 if (need_resched())
4405 break;
4407 arch_mutex_cpu_relax();
4409 rcu_read_unlock();
4412 * We break out the loop above on need_resched() and when the
4413 * owner changed, which is a sign for heavy contention. Return
4414 * success only when lock->owner is NULL.
4416 return lock->owner == NULL;
4418 #endif
4420 #ifdef CONFIG_PREEMPT
4422 * this is the entry point to schedule() from in-kernel preemption
4423 * off of preempt_enable. Kernel preemptions off return from interrupt
4424 * occur there and call schedule directly.
4426 asmlinkage void __sched notrace preempt_schedule(void)
4428 struct thread_info *ti = current_thread_info();
4431 * If there is a non-zero preempt_count or interrupts are disabled,
4432 * we do not want to preempt the current task. Just return..
4434 if (likely(ti->preempt_count || irqs_disabled()))
4435 return;
4437 do {
4438 add_preempt_count_notrace(PREEMPT_ACTIVE);
4439 schedule();
4440 sub_preempt_count_notrace(PREEMPT_ACTIVE);
4443 * Check again in case we missed a preemption opportunity
4444 * between schedule and now.
4446 barrier();
4447 } while (need_resched());
4449 EXPORT_SYMBOL(preempt_schedule);
4452 * this is the entry point to schedule() from kernel preemption
4453 * off of irq context.
4454 * Note, that this is called and return with irqs disabled. This will
4455 * protect us against recursive calling from irq.
4457 asmlinkage void __sched preempt_schedule_irq(void)
4459 struct thread_info *ti = current_thread_info();
4461 /* Catch callers which need to be fixed */
4462 BUG_ON(ti->preempt_count || !irqs_disabled());
4464 do {
4465 add_preempt_count(PREEMPT_ACTIVE);
4466 local_irq_enable();
4467 schedule();
4468 local_irq_disable();
4469 sub_preempt_count(PREEMPT_ACTIVE);
4472 * Check again in case we missed a preemption opportunity
4473 * between schedule and now.
4475 barrier();
4476 } while (need_resched());
4479 #endif /* CONFIG_PREEMPT */
4481 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
4482 void *key)
4484 return try_to_wake_up(curr->private, mode, wake_flags);
4486 EXPORT_SYMBOL(default_wake_function);
4489 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4490 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4491 * number) then we wake all the non-exclusive tasks and one exclusive task.
4493 * There are circumstances in which we can try to wake a task which has already
4494 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4495 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4497 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4498 int nr_exclusive, int wake_flags, void *key)
4500 wait_queue_t *curr, *next;
4502 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4503 unsigned flags = curr->flags;
4505 if (curr->func(curr, mode, wake_flags, key) &&
4506 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4507 break;
4512 * __wake_up - wake up threads blocked on a waitqueue.
4513 * @q: the waitqueue
4514 * @mode: which threads
4515 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4516 * @key: is directly passed to the wakeup function
4518 * It may be assumed that this function implies a write memory barrier before
4519 * changing the task state if and only if any tasks are woken up.
4521 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4522 int nr_exclusive, void *key)
4524 unsigned long flags;
4526 spin_lock_irqsave(&q->lock, flags);
4527 __wake_up_common(q, mode, nr_exclusive, 0, key);
4528 spin_unlock_irqrestore(&q->lock, flags);
4530 EXPORT_SYMBOL(__wake_up);
4533 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4535 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4537 __wake_up_common(q, mode, 1, 0, NULL);
4539 EXPORT_SYMBOL_GPL(__wake_up_locked);
4541 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
4543 __wake_up_common(q, mode, 1, 0, key);
4545 EXPORT_SYMBOL_GPL(__wake_up_locked_key);
4548 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
4549 * @q: the waitqueue
4550 * @mode: which threads
4551 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4552 * @key: opaque value to be passed to wakeup targets
4554 * The sync wakeup differs that the waker knows that it will schedule
4555 * away soon, so while the target thread will be woken up, it will not
4556 * be migrated to another CPU - ie. the two threads are 'synchronized'
4557 * with each other. This can prevent needless bouncing between CPUs.
4559 * On UP it can prevent extra preemption.
4561 * It may be assumed that this function implies a write memory barrier before
4562 * changing the task state if and only if any tasks are woken up.
4564 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
4565 int nr_exclusive, void *key)
4567 unsigned long flags;
4568 int wake_flags = WF_SYNC;
4570 if (unlikely(!q))
4571 return;
4573 if (unlikely(!nr_exclusive))
4574 wake_flags = 0;
4576 spin_lock_irqsave(&q->lock, flags);
4577 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
4578 spin_unlock_irqrestore(&q->lock, flags);
4580 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
4583 * __wake_up_sync - see __wake_up_sync_key()
4585 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4587 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
4589 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4592 * complete: - signals a single thread waiting on this completion
4593 * @x: holds the state of this particular completion
4595 * This will wake up a single thread waiting on this completion. Threads will be
4596 * awakened in the same order in which they were queued.
4598 * See also complete_all(), wait_for_completion() and related routines.
4600 * It may be assumed that this function implies a write memory barrier before
4601 * changing the task state if and only if any tasks are woken up.
4603 void complete(struct completion *x)
4605 unsigned long flags;
4607 spin_lock_irqsave(&x->wait.lock, flags);
4608 x->done++;
4609 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4610 spin_unlock_irqrestore(&x->wait.lock, flags);
4612 EXPORT_SYMBOL(complete);
4615 * complete_all: - signals all threads waiting on this completion
4616 * @x: holds the state of this particular completion
4618 * This will wake up all threads waiting on this particular completion event.
4620 * It may be assumed that this function implies a write memory barrier before
4621 * changing the task state if and only if any tasks are woken up.
4623 void complete_all(struct completion *x)
4625 unsigned long flags;
4627 spin_lock_irqsave(&x->wait.lock, flags);
4628 x->done += UINT_MAX/2;
4629 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4630 spin_unlock_irqrestore(&x->wait.lock, flags);
4632 EXPORT_SYMBOL(complete_all);
4634 static inline long __sched
4635 do_wait_for_common(struct completion *x, long timeout, int state)
4637 if (!x->done) {
4638 DECLARE_WAITQUEUE(wait, current);
4640 __add_wait_queue_tail_exclusive(&x->wait, &wait);
4641 do {
4642 if (signal_pending_state(state, current)) {
4643 timeout = -ERESTARTSYS;
4644 break;
4646 __set_current_state(state);
4647 spin_unlock_irq(&x->wait.lock);
4648 timeout = schedule_timeout(timeout);
4649 spin_lock_irq(&x->wait.lock);
4650 } while (!x->done && timeout);
4651 __remove_wait_queue(&x->wait, &wait);
4652 if (!x->done)
4653 return timeout;
4655 x->done--;
4656 return timeout ?: 1;
4659 static long __sched
4660 wait_for_common(struct completion *x, long timeout, int state)
4662 might_sleep();
4664 spin_lock_irq(&x->wait.lock);
4665 timeout = do_wait_for_common(x, timeout, state);
4666 spin_unlock_irq(&x->wait.lock);
4667 return timeout;
4671 * wait_for_completion: - waits for completion of a task
4672 * @x: holds the state of this particular completion
4674 * This waits to be signaled for completion of a specific task. It is NOT
4675 * interruptible and there is no timeout.
4677 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4678 * and interrupt capability. Also see complete().
4680 void __sched wait_for_completion(struct completion *x)
4682 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4684 EXPORT_SYMBOL(wait_for_completion);
4687 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4688 * @x: holds the state of this particular completion
4689 * @timeout: timeout value in jiffies
4691 * This waits for either a completion of a specific task to be signaled or for a
4692 * specified timeout to expire. The timeout is in jiffies. It is not
4693 * interruptible.
4695 unsigned long __sched
4696 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4698 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4700 EXPORT_SYMBOL(wait_for_completion_timeout);
4703 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4704 * @x: holds the state of this particular completion
4706 * This waits for completion of a specific task to be signaled. It is
4707 * interruptible.
4709 int __sched wait_for_completion_interruptible(struct completion *x)
4711 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4712 if (t == -ERESTARTSYS)
4713 return t;
4714 return 0;
4716 EXPORT_SYMBOL(wait_for_completion_interruptible);
4719 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4720 * @x: holds the state of this particular completion
4721 * @timeout: timeout value in jiffies
4723 * This waits for either a completion of a specific task to be signaled or for a
4724 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4726 long __sched
4727 wait_for_completion_interruptible_timeout(struct completion *x,
4728 unsigned long timeout)
4730 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4732 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4735 * wait_for_completion_killable: - waits for completion of a task (killable)
4736 * @x: holds the state of this particular completion
4738 * This waits to be signaled for completion of a specific task. It can be
4739 * interrupted by a kill signal.
4741 int __sched wait_for_completion_killable(struct completion *x)
4743 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4744 if (t == -ERESTARTSYS)
4745 return t;
4746 return 0;
4748 EXPORT_SYMBOL(wait_for_completion_killable);
4751 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
4752 * @x: holds the state of this particular completion
4753 * @timeout: timeout value in jiffies
4755 * This waits for either a completion of a specific task to be
4756 * signaled or for a specified timeout to expire. It can be
4757 * interrupted by a kill signal. The timeout is in jiffies.
4759 long __sched
4760 wait_for_completion_killable_timeout(struct completion *x,
4761 unsigned long timeout)
4763 return wait_for_common(x, timeout, TASK_KILLABLE);
4765 EXPORT_SYMBOL(wait_for_completion_killable_timeout);
4768 * try_wait_for_completion - try to decrement a completion without blocking
4769 * @x: completion structure
4771 * Returns: 0 if a decrement cannot be done without blocking
4772 * 1 if a decrement succeeded.
4774 * If a completion is being used as a counting completion,
4775 * attempt to decrement the counter without blocking. This
4776 * enables us to avoid waiting if the resource the completion
4777 * is protecting is not available.
4779 bool try_wait_for_completion(struct completion *x)
4781 unsigned long flags;
4782 int ret = 1;
4784 spin_lock_irqsave(&x->wait.lock, flags);
4785 if (!x->done)
4786 ret = 0;
4787 else
4788 x->done--;
4789 spin_unlock_irqrestore(&x->wait.lock, flags);
4790 return ret;
4792 EXPORT_SYMBOL(try_wait_for_completion);
4795 * completion_done - Test to see if a completion has any waiters
4796 * @x: completion structure
4798 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4799 * 1 if there are no waiters.
4802 bool completion_done(struct completion *x)
4804 unsigned long flags;
4805 int ret = 1;
4807 spin_lock_irqsave(&x->wait.lock, flags);
4808 if (!x->done)
4809 ret = 0;
4810 spin_unlock_irqrestore(&x->wait.lock, flags);
4811 return ret;
4813 EXPORT_SYMBOL(completion_done);
4815 static long __sched
4816 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4818 unsigned long flags;
4819 wait_queue_t wait;
4821 init_waitqueue_entry(&wait, current);
4823 __set_current_state(state);
4825 spin_lock_irqsave(&q->lock, flags);
4826 __add_wait_queue(q, &wait);
4827 spin_unlock(&q->lock);
4828 timeout = schedule_timeout(timeout);
4829 spin_lock_irq(&q->lock);
4830 __remove_wait_queue(q, &wait);
4831 spin_unlock_irqrestore(&q->lock, flags);
4833 return timeout;
4836 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4838 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4840 EXPORT_SYMBOL(interruptible_sleep_on);
4842 long __sched
4843 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4845 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4847 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4849 void __sched sleep_on(wait_queue_head_t *q)
4851 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4853 EXPORT_SYMBOL(sleep_on);
4855 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4857 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4859 EXPORT_SYMBOL(sleep_on_timeout);
4861 #ifdef CONFIG_RT_MUTEXES
4864 * rt_mutex_setprio - set the current priority of a task
4865 * @p: task
4866 * @prio: prio value (kernel-internal form)
4868 * This function changes the 'effective' priority of a task. It does
4869 * not touch ->normal_prio like __setscheduler().
4871 * Used by the rt_mutex code to implement priority inheritance logic.
4873 void rt_mutex_setprio(struct task_struct *p, int prio)
4875 int oldprio, on_rq, running;
4876 struct rq *rq;
4877 const struct sched_class *prev_class;
4879 BUG_ON(prio < 0 || prio > MAX_PRIO);
4881 rq = __task_rq_lock(p);
4883 trace_sched_pi_setprio(p, prio);
4884 oldprio = p->prio;
4885 prev_class = p->sched_class;
4886 on_rq = p->on_rq;
4887 running = task_current(rq, p);
4888 if (on_rq)
4889 dequeue_task(rq, p, 0);
4890 if (running)
4891 p->sched_class->put_prev_task(rq, p);
4893 if (rt_prio(prio))
4894 p->sched_class = &rt_sched_class;
4895 else
4896 p->sched_class = &fair_sched_class;
4898 p->prio = prio;
4900 if (running)
4901 p->sched_class->set_curr_task(rq);
4902 if (on_rq)
4903 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
4905 check_class_changed(rq, p, prev_class, oldprio);
4906 __task_rq_unlock(rq);
4909 #endif
4911 void set_user_nice(struct task_struct *p, long nice)
4913 int old_prio, delta, on_rq;
4914 unsigned long flags;
4915 struct rq *rq;
4917 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4918 return;
4920 * We have to be careful, if called from sys_setpriority(),
4921 * the task might be in the middle of scheduling on another CPU.
4923 rq = task_rq_lock(p, &flags);
4925 * The RT priorities are set via sched_setscheduler(), but we still
4926 * allow the 'normal' nice value to be set - but as expected
4927 * it wont have any effect on scheduling until the task is
4928 * SCHED_FIFO/SCHED_RR:
4930 if (task_has_rt_policy(p)) {
4931 p->static_prio = NICE_TO_PRIO(nice);
4932 goto out_unlock;
4934 on_rq = p->on_rq;
4935 if (on_rq)
4936 dequeue_task(rq, p, 0);
4938 p->static_prio = NICE_TO_PRIO(nice);
4939 set_load_weight(p);
4940 old_prio = p->prio;
4941 p->prio = effective_prio(p);
4942 delta = p->prio - old_prio;
4944 if (on_rq) {
4945 enqueue_task(rq, p, 0);
4947 * If the task increased its priority or is running and
4948 * lowered its priority, then reschedule its CPU:
4950 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4951 resched_task(rq->curr);
4953 out_unlock:
4954 task_rq_unlock(rq, p, &flags);
4956 EXPORT_SYMBOL(set_user_nice);
4959 * can_nice - check if a task can reduce its nice value
4960 * @p: task
4961 * @nice: nice value
4963 int can_nice(const struct task_struct *p, const int nice)
4965 /* convert nice value [19,-20] to rlimit style value [1,40] */
4966 int nice_rlim = 20 - nice;
4968 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4969 capable(CAP_SYS_NICE));
4972 #ifdef __ARCH_WANT_SYS_NICE
4975 * sys_nice - change the priority of the current process.
4976 * @increment: priority increment
4978 * sys_setpriority is a more generic, but much slower function that
4979 * does similar things.
4981 SYSCALL_DEFINE1(nice, int, increment)
4983 long nice, retval;
4986 * Setpriority might change our priority at the same moment.
4987 * We don't have to worry. Conceptually one call occurs first
4988 * and we have a single winner.
4990 if (increment < -40)
4991 increment = -40;
4992 if (increment > 40)
4993 increment = 40;
4995 nice = TASK_NICE(current) + increment;
4996 if (nice < -20)
4997 nice = -20;
4998 if (nice > 19)
4999 nice = 19;
5001 if (increment < 0 && !can_nice(current, nice))
5002 return -EPERM;
5004 retval = security_task_setnice(current, nice);
5005 if (retval)
5006 return retval;
5008 set_user_nice(current, nice);
5009 return 0;
5012 #endif
5015 * task_prio - return the priority value of a given task.
5016 * @p: the task in question.
5018 * This is the priority value as seen by users in /proc.
5019 * RT tasks are offset by -200. Normal tasks are centered
5020 * around 0, value goes from -16 to +15.
5022 int task_prio(const struct task_struct *p)
5024 return p->prio - MAX_RT_PRIO;
5028 * task_nice - return the nice value of a given task.
5029 * @p: the task in question.
5031 int task_nice(const struct task_struct *p)
5033 return TASK_NICE(p);
5035 EXPORT_SYMBOL(task_nice);
5038 * idle_cpu - is a given cpu idle currently?
5039 * @cpu: the processor in question.
5041 int idle_cpu(int cpu)
5043 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5047 * idle_task - return the idle task for a given cpu.
5048 * @cpu: the processor in question.
5050 struct task_struct *idle_task(int cpu)
5052 return cpu_rq(cpu)->idle;
5056 * find_process_by_pid - find a process with a matching PID value.
5057 * @pid: the pid in question.
5059 static struct task_struct *find_process_by_pid(pid_t pid)
5061 return pid ? find_task_by_vpid(pid) : current;
5064 /* Actually do priority change: must hold rq lock. */
5065 static void
5066 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5068 p->policy = policy;
5069 p->rt_priority = prio;
5070 p->normal_prio = normal_prio(p);
5071 /* we are holding p->pi_lock already */
5072 p->prio = rt_mutex_getprio(p);
5073 if (rt_prio(p->prio))
5074 p->sched_class = &rt_sched_class;
5075 else
5076 p->sched_class = &fair_sched_class;
5077 set_load_weight(p);
5081 * check the target process has a UID that matches the current process's
5083 static bool check_same_owner(struct task_struct *p)
5085 const struct cred *cred = current_cred(), *pcred;
5086 bool match;
5088 rcu_read_lock();
5089 pcred = __task_cred(p);
5090 if (cred->user->user_ns == pcred->user->user_ns)
5091 match = (cred->euid == pcred->euid ||
5092 cred->euid == pcred->uid);
5093 else
5094 match = false;
5095 rcu_read_unlock();
5096 return match;
5099 static int __sched_setscheduler(struct task_struct *p, int policy,
5100 const struct sched_param *param, bool user)
5102 int retval, oldprio, oldpolicy = -1, on_rq, running;
5103 unsigned long flags;
5104 const struct sched_class *prev_class;
5105 struct rq *rq;
5106 int reset_on_fork;
5108 /* may grab non-irq protected spin_locks */
5109 BUG_ON(in_interrupt());
5110 recheck:
5111 /* double check policy once rq lock held */
5112 if (policy < 0) {
5113 reset_on_fork = p->sched_reset_on_fork;
5114 policy = oldpolicy = p->policy;
5115 } else {
5116 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
5117 policy &= ~SCHED_RESET_ON_FORK;
5119 if (policy != SCHED_FIFO && policy != SCHED_RR &&
5120 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5121 policy != SCHED_IDLE)
5122 return -EINVAL;
5126 * Valid priorities for SCHED_FIFO and SCHED_RR are
5127 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5128 * SCHED_BATCH and SCHED_IDLE is 0.
5130 if (param->sched_priority < 0 ||
5131 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5132 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5133 return -EINVAL;
5134 if (rt_policy(policy) != (param->sched_priority != 0))
5135 return -EINVAL;
5138 * Allow unprivileged RT tasks to decrease priority:
5140 if (user && !capable(CAP_SYS_NICE)) {
5141 if (rt_policy(policy)) {
5142 unsigned long rlim_rtprio =
5143 task_rlimit(p, RLIMIT_RTPRIO);
5145 /* can't set/change the rt policy */
5146 if (policy != p->policy && !rlim_rtprio)
5147 return -EPERM;
5149 /* can't increase priority */
5150 if (param->sched_priority > p->rt_priority &&
5151 param->sched_priority > rlim_rtprio)
5152 return -EPERM;
5156 * Treat SCHED_IDLE as nice 20. Only allow a switch to
5157 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
5159 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
5160 if (!can_nice(p, TASK_NICE(p)))
5161 return -EPERM;
5164 /* can't change other user's priorities */
5165 if (!check_same_owner(p))
5166 return -EPERM;
5168 /* Normal users shall not reset the sched_reset_on_fork flag */
5169 if (p->sched_reset_on_fork && !reset_on_fork)
5170 return -EPERM;
5173 if (user) {
5174 retval = security_task_setscheduler(p);
5175 if (retval)
5176 return retval;
5180 * make sure no PI-waiters arrive (or leave) while we are
5181 * changing the priority of the task:
5183 * To be able to change p->policy safely, the appropriate
5184 * runqueue lock must be held.
5186 rq = task_rq_lock(p, &flags);
5189 * Changing the policy of the stop threads its a very bad idea
5191 if (p == rq->stop) {
5192 task_rq_unlock(rq, p, &flags);
5193 return -EINVAL;
5197 * If not changing anything there's no need to proceed further:
5199 if (unlikely(policy == p->policy && (!rt_policy(policy) ||
5200 param->sched_priority == p->rt_priority))) {
5202 __task_rq_unlock(rq);
5203 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5204 return 0;
5207 #ifdef CONFIG_RT_GROUP_SCHED
5208 if (user) {
5210 * Do not allow realtime tasks into groups that have no runtime
5211 * assigned.
5213 if (rt_bandwidth_enabled() && rt_policy(policy) &&
5214 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
5215 !task_group_is_autogroup(task_group(p))) {
5216 task_rq_unlock(rq, p, &flags);
5217 return -EPERM;
5220 #endif
5222 /* recheck policy now with rq lock held */
5223 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5224 policy = oldpolicy = -1;
5225 task_rq_unlock(rq, p, &flags);
5226 goto recheck;
5228 on_rq = p->on_rq;
5229 running = task_current(rq, p);
5230 if (on_rq)
5231 deactivate_task(rq, p, 0);
5232 if (running)
5233 p->sched_class->put_prev_task(rq, p);
5235 p->sched_reset_on_fork = reset_on_fork;
5237 oldprio = p->prio;
5238 prev_class = p->sched_class;
5239 __setscheduler(rq, p, policy, param->sched_priority);
5241 if (running)
5242 p->sched_class->set_curr_task(rq);
5243 if (on_rq)
5244 activate_task(rq, p, 0);
5246 check_class_changed(rq, p, prev_class, oldprio);
5247 task_rq_unlock(rq, p, &flags);
5249 rt_mutex_adjust_pi(p);
5251 return 0;
5255 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5256 * @p: the task in question.
5257 * @policy: new policy.
5258 * @param: structure containing the new RT priority.
5260 * NOTE that the task may be already dead.
5262 int sched_setscheduler(struct task_struct *p, int policy,
5263 const struct sched_param *param)
5265 return __sched_setscheduler(p, policy, param, true);
5267 EXPORT_SYMBOL_GPL(sched_setscheduler);
5270 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5271 * @p: the task in question.
5272 * @policy: new policy.
5273 * @param: structure containing the new RT priority.
5275 * Just like sched_setscheduler, only don't bother checking if the
5276 * current context has permission. For example, this is needed in
5277 * stop_machine(): we create temporary high priority worker threads,
5278 * but our caller might not have that capability.
5280 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5281 const struct sched_param *param)
5283 return __sched_setscheduler(p, policy, param, false);
5286 static int
5287 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5289 struct sched_param lparam;
5290 struct task_struct *p;
5291 int retval;
5293 if (!param || pid < 0)
5294 return -EINVAL;
5295 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5296 return -EFAULT;
5298 rcu_read_lock();
5299 retval = -ESRCH;
5300 p = find_process_by_pid(pid);
5301 if (p != NULL)
5302 retval = sched_setscheduler(p, policy, &lparam);
5303 rcu_read_unlock();
5305 return retval;
5309 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5310 * @pid: the pid in question.
5311 * @policy: new policy.
5312 * @param: structure containing the new RT priority.
5314 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
5315 struct sched_param __user *, param)
5317 /* negative values for policy are not valid */
5318 if (policy < 0)
5319 return -EINVAL;
5321 return do_sched_setscheduler(pid, policy, param);
5325 * sys_sched_setparam - set/change the RT priority of a thread
5326 * @pid: the pid in question.
5327 * @param: structure containing the new RT priority.
5329 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
5331 return do_sched_setscheduler(pid, -1, param);
5335 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5336 * @pid: the pid in question.
5338 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
5340 struct task_struct *p;
5341 int retval;
5343 if (pid < 0)
5344 return -EINVAL;
5346 retval = -ESRCH;
5347 rcu_read_lock();
5348 p = find_process_by_pid(pid);
5349 if (p) {
5350 retval = security_task_getscheduler(p);
5351 if (!retval)
5352 retval = p->policy
5353 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
5355 rcu_read_unlock();
5356 return retval;
5360 * sys_sched_getparam - get the RT priority of a thread
5361 * @pid: the pid in question.
5362 * @param: structure containing the RT priority.
5364 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
5366 struct sched_param lp;
5367 struct task_struct *p;
5368 int retval;
5370 if (!param || pid < 0)
5371 return -EINVAL;
5373 rcu_read_lock();
5374 p = find_process_by_pid(pid);
5375 retval = -ESRCH;
5376 if (!p)
5377 goto out_unlock;
5379 retval = security_task_getscheduler(p);
5380 if (retval)
5381 goto out_unlock;
5383 lp.sched_priority = p->rt_priority;
5384 rcu_read_unlock();
5387 * This one might sleep, we cannot do it with a spinlock held ...
5389 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5391 return retval;
5393 out_unlock:
5394 rcu_read_unlock();
5395 return retval;
5398 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
5400 cpumask_var_t cpus_allowed, new_mask;
5401 struct task_struct *p;
5402 int retval;
5404 get_online_cpus();
5405 rcu_read_lock();
5407 p = find_process_by_pid(pid);
5408 if (!p) {
5409 rcu_read_unlock();
5410 put_online_cpus();
5411 return -ESRCH;
5414 /* Prevent p going away */
5415 get_task_struct(p);
5416 rcu_read_unlock();
5418 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
5419 retval = -ENOMEM;
5420 goto out_put_task;
5422 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
5423 retval = -ENOMEM;
5424 goto out_free_cpus_allowed;
5426 retval = -EPERM;
5427 if (!check_same_owner(p) && !task_ns_capable(p, CAP_SYS_NICE))
5428 goto out_unlock;
5430 retval = security_task_setscheduler(p);
5431 if (retval)
5432 goto out_unlock;
5434 cpuset_cpus_allowed(p, cpus_allowed);
5435 cpumask_and(new_mask, in_mask, cpus_allowed);
5436 again:
5437 retval = set_cpus_allowed_ptr(p, new_mask);
5439 if (!retval) {
5440 cpuset_cpus_allowed(p, cpus_allowed);
5441 if (!cpumask_subset(new_mask, cpus_allowed)) {
5443 * We must have raced with a concurrent cpuset
5444 * update. Just reset the cpus_allowed to the
5445 * cpuset's cpus_allowed
5447 cpumask_copy(new_mask, cpus_allowed);
5448 goto again;
5451 out_unlock:
5452 free_cpumask_var(new_mask);
5453 out_free_cpus_allowed:
5454 free_cpumask_var(cpus_allowed);
5455 out_put_task:
5456 put_task_struct(p);
5457 put_online_cpus();
5458 return retval;
5461 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5462 struct cpumask *new_mask)
5464 if (len < cpumask_size())
5465 cpumask_clear(new_mask);
5466 else if (len > cpumask_size())
5467 len = cpumask_size();
5469 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5473 * sys_sched_setaffinity - set the cpu affinity of a process
5474 * @pid: pid of the process
5475 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5476 * @user_mask_ptr: user-space pointer to the new cpu mask
5478 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
5479 unsigned long __user *, user_mask_ptr)
5481 cpumask_var_t new_mask;
5482 int retval;
5484 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
5485 return -ENOMEM;
5487 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
5488 if (retval == 0)
5489 retval = sched_setaffinity(pid, new_mask);
5490 free_cpumask_var(new_mask);
5491 return retval;
5494 long sched_getaffinity(pid_t pid, struct cpumask *mask)
5496 struct task_struct *p;
5497 unsigned long flags;
5498 int retval;
5500 get_online_cpus();
5501 rcu_read_lock();
5503 retval = -ESRCH;
5504 p = find_process_by_pid(pid);
5505 if (!p)
5506 goto out_unlock;
5508 retval = security_task_getscheduler(p);
5509 if (retval)
5510 goto out_unlock;
5512 raw_spin_lock_irqsave(&p->pi_lock, flags);
5513 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
5514 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5516 out_unlock:
5517 rcu_read_unlock();
5518 put_online_cpus();
5520 return retval;
5524 * sys_sched_getaffinity - get the cpu affinity of a process
5525 * @pid: pid of the process
5526 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5527 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5529 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5530 unsigned long __user *, user_mask_ptr)
5532 int ret;
5533 cpumask_var_t mask;
5535 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5536 return -EINVAL;
5537 if (len & (sizeof(unsigned long)-1))
5538 return -EINVAL;
5540 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5541 return -ENOMEM;
5543 ret = sched_getaffinity(pid, mask);
5544 if (ret == 0) {
5545 size_t retlen = min_t(size_t, len, cpumask_size());
5547 if (copy_to_user(user_mask_ptr, mask, retlen))
5548 ret = -EFAULT;
5549 else
5550 ret = retlen;
5552 free_cpumask_var(mask);
5554 return ret;
5558 * sys_sched_yield - yield the current processor to other threads.
5560 * This function yields the current CPU to other tasks. If there are no
5561 * other threads running on this CPU then this function will return.
5563 SYSCALL_DEFINE0(sched_yield)
5565 struct rq *rq = this_rq_lock();
5567 schedstat_inc(rq, yld_count);
5568 current->sched_class->yield_task(rq);
5571 * Since we are going to call schedule() anyway, there's
5572 * no need to preempt or enable interrupts:
5574 __release(rq->lock);
5575 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5576 do_raw_spin_unlock(&rq->lock);
5577 preempt_enable_no_resched();
5579 schedule();
5581 return 0;
5584 static inline int should_resched(void)
5586 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
5589 static void __cond_resched(void)
5591 add_preempt_count(PREEMPT_ACTIVE);
5592 schedule();
5593 sub_preempt_count(PREEMPT_ACTIVE);
5596 int __sched _cond_resched(void)
5598 if (should_resched()) {
5599 __cond_resched();
5600 return 1;
5602 return 0;
5604 EXPORT_SYMBOL(_cond_resched);
5607 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5608 * call schedule, and on return reacquire the lock.
5610 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5611 * operations here to prevent schedule() from being called twice (once via
5612 * spin_unlock(), once by hand).
5614 int __cond_resched_lock(spinlock_t *lock)
5616 int resched = should_resched();
5617 int ret = 0;
5619 lockdep_assert_held(lock);
5621 if (spin_needbreak(lock) || resched) {
5622 spin_unlock(lock);
5623 if (resched)
5624 __cond_resched();
5625 else
5626 cpu_relax();
5627 ret = 1;
5628 spin_lock(lock);
5630 return ret;
5632 EXPORT_SYMBOL(__cond_resched_lock);
5634 int __sched __cond_resched_softirq(void)
5636 BUG_ON(!in_softirq());
5638 if (should_resched()) {
5639 local_bh_enable();
5640 __cond_resched();
5641 local_bh_disable();
5642 return 1;
5644 return 0;
5646 EXPORT_SYMBOL(__cond_resched_softirq);
5649 * yield - yield the current processor to other threads.
5651 * This is a shortcut for kernel-space yielding - it marks the
5652 * thread runnable and calls sys_sched_yield().
5654 void __sched yield(void)
5656 set_current_state(TASK_RUNNING);
5657 sys_sched_yield();
5659 EXPORT_SYMBOL(yield);
5662 * yield_to - yield the current processor to another thread in
5663 * your thread group, or accelerate that thread toward the
5664 * processor it's on.
5665 * @p: target task
5666 * @preempt: whether task preemption is allowed or not
5668 * It's the caller's job to ensure that the target task struct
5669 * can't go away on us before we can do any checks.
5671 * Returns true if we indeed boosted the target task.
5673 bool __sched yield_to(struct task_struct *p, bool preempt)
5675 struct task_struct *curr = current;
5676 struct rq *rq, *p_rq;
5677 unsigned long flags;
5678 bool yielded = 0;
5680 local_irq_save(flags);
5681 rq = this_rq();
5683 again:
5684 p_rq = task_rq(p);
5685 double_rq_lock(rq, p_rq);
5686 while (task_rq(p) != p_rq) {
5687 double_rq_unlock(rq, p_rq);
5688 goto again;
5691 if (!curr->sched_class->yield_to_task)
5692 goto out;
5694 if (curr->sched_class != p->sched_class)
5695 goto out;
5697 if (task_running(p_rq, p) || p->state)
5698 goto out;
5700 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5701 if (yielded) {
5702 schedstat_inc(rq, yld_count);
5704 * Make p's CPU reschedule; pick_next_entity takes care of
5705 * fairness.
5707 if (preempt && rq != p_rq)
5708 resched_task(p_rq->curr);
5711 out:
5712 double_rq_unlock(rq, p_rq);
5713 local_irq_restore(flags);
5715 if (yielded)
5716 schedule();
5718 return yielded;
5720 EXPORT_SYMBOL_GPL(yield_to);
5723 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5724 * that process accounting knows that this is a task in IO wait state.
5726 void __sched io_schedule(void)
5728 struct rq *rq = raw_rq();
5730 delayacct_blkio_start();
5731 atomic_inc(&rq->nr_iowait);
5732 blk_flush_plug(current);
5733 current->in_iowait = 1;
5734 schedule();
5735 current->in_iowait = 0;
5736 atomic_dec(&rq->nr_iowait);
5737 delayacct_blkio_end();
5739 EXPORT_SYMBOL(io_schedule);
5741 long __sched io_schedule_timeout(long timeout)
5743 struct rq *rq = raw_rq();
5744 long ret;
5746 delayacct_blkio_start();
5747 atomic_inc(&rq->nr_iowait);
5748 blk_flush_plug(current);
5749 current->in_iowait = 1;
5750 ret = schedule_timeout(timeout);
5751 current->in_iowait = 0;
5752 atomic_dec(&rq->nr_iowait);
5753 delayacct_blkio_end();
5754 return ret;
5758 * sys_sched_get_priority_max - return maximum RT priority.
5759 * @policy: scheduling class.
5761 * this syscall returns the maximum rt_priority that can be used
5762 * by a given scheduling class.
5764 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5766 int ret = -EINVAL;
5768 switch (policy) {
5769 case SCHED_FIFO:
5770 case SCHED_RR:
5771 ret = MAX_USER_RT_PRIO-1;
5772 break;
5773 case SCHED_NORMAL:
5774 case SCHED_BATCH:
5775 case SCHED_IDLE:
5776 ret = 0;
5777 break;
5779 return ret;
5783 * sys_sched_get_priority_min - return minimum RT priority.
5784 * @policy: scheduling class.
5786 * this syscall returns the minimum rt_priority that can be used
5787 * by a given scheduling class.
5789 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5791 int ret = -EINVAL;
5793 switch (policy) {
5794 case SCHED_FIFO:
5795 case SCHED_RR:
5796 ret = 1;
5797 break;
5798 case SCHED_NORMAL:
5799 case SCHED_BATCH:
5800 case SCHED_IDLE:
5801 ret = 0;
5803 return ret;
5807 * sys_sched_rr_get_interval - return the default timeslice of a process.
5808 * @pid: pid of the process.
5809 * @interval: userspace pointer to the timeslice value.
5811 * this syscall writes the default timeslice value of a given process
5812 * into the user-space timespec buffer. A value of '0' means infinity.
5814 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5815 struct timespec __user *, interval)
5817 struct task_struct *p;
5818 unsigned int time_slice;
5819 unsigned long flags;
5820 struct rq *rq;
5821 int retval;
5822 struct timespec t;
5824 if (pid < 0)
5825 return -EINVAL;
5827 retval = -ESRCH;
5828 rcu_read_lock();
5829 p = find_process_by_pid(pid);
5830 if (!p)
5831 goto out_unlock;
5833 retval = security_task_getscheduler(p);
5834 if (retval)
5835 goto out_unlock;
5837 rq = task_rq_lock(p, &flags);
5838 time_slice = p->sched_class->get_rr_interval(rq, p);
5839 task_rq_unlock(rq, p, &flags);
5841 rcu_read_unlock();
5842 jiffies_to_timespec(time_slice, &t);
5843 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5844 return retval;
5846 out_unlock:
5847 rcu_read_unlock();
5848 return retval;
5851 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5853 void sched_show_task(struct task_struct *p)
5855 unsigned long free = 0;
5856 unsigned state;
5858 state = p->state ? __ffs(p->state) + 1 : 0;
5859 printk(KERN_INFO "%-15.15s %c", p->comm,
5860 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5861 #if BITS_PER_LONG == 32
5862 if (state == TASK_RUNNING)
5863 printk(KERN_CONT " running ");
5864 else
5865 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5866 #else
5867 if (state == TASK_RUNNING)
5868 printk(KERN_CONT " running task ");
5869 else
5870 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5871 #endif
5872 #ifdef CONFIG_DEBUG_STACK_USAGE
5873 free = stack_not_used(p);
5874 #endif
5875 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5876 task_pid_nr(p), task_pid_nr(p->real_parent),
5877 (unsigned long)task_thread_info(p)->flags);
5879 show_stack(p, NULL);
5882 void show_state_filter(unsigned long state_filter)
5884 struct task_struct *g, *p;
5886 #if BITS_PER_LONG == 32
5887 printk(KERN_INFO
5888 " task PC stack pid father\n");
5889 #else
5890 printk(KERN_INFO
5891 " task PC stack pid father\n");
5892 #endif
5893 read_lock(&tasklist_lock);
5894 do_each_thread(g, p) {
5896 * reset the NMI-timeout, listing all files on a slow
5897 * console might take a lot of time:
5899 touch_nmi_watchdog();
5900 if (!state_filter || (p->state & state_filter))
5901 sched_show_task(p);
5902 } while_each_thread(g, p);
5904 touch_all_softlockup_watchdogs();
5906 #ifdef CONFIG_SCHED_DEBUG
5907 sysrq_sched_debug_show();
5908 #endif
5909 read_unlock(&tasklist_lock);
5911 * Only show locks if all tasks are dumped:
5913 if (!state_filter)
5914 debug_show_all_locks();
5917 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5919 idle->sched_class = &idle_sched_class;
5923 * init_idle - set up an idle thread for a given CPU
5924 * @idle: task in question
5925 * @cpu: cpu the idle task belongs to
5927 * NOTE: this function does not set the idle thread's NEED_RESCHED
5928 * flag, to make booting more robust.
5930 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5932 struct rq *rq = cpu_rq(cpu);
5933 unsigned long flags;
5935 raw_spin_lock_irqsave(&rq->lock, flags);
5937 __sched_fork(idle);
5938 idle->state = TASK_RUNNING;
5939 idle->se.exec_start = sched_clock();
5941 do_set_cpus_allowed(idle, cpumask_of(cpu));
5943 * We're having a chicken and egg problem, even though we are
5944 * holding rq->lock, the cpu isn't yet set to this cpu so the
5945 * lockdep check in task_group() will fail.
5947 * Similar case to sched_fork(). / Alternatively we could
5948 * use task_rq_lock() here and obtain the other rq->lock.
5950 * Silence PROVE_RCU
5952 rcu_read_lock();
5953 __set_task_cpu(idle, cpu);
5954 rcu_read_unlock();
5956 rq->curr = rq->idle = idle;
5957 #if defined(CONFIG_SMP)
5958 idle->on_cpu = 1;
5959 #endif
5960 raw_spin_unlock_irqrestore(&rq->lock, flags);
5962 /* Set the preempt count _outside_ the spinlocks! */
5963 task_thread_info(idle)->preempt_count = 0;
5966 * The idle tasks have their own, simple scheduling class:
5968 idle->sched_class = &idle_sched_class;
5969 ftrace_graph_init_idle_task(idle, cpu);
5973 * In a system that switches off the HZ timer nohz_cpu_mask
5974 * indicates which cpus entered this state. This is used
5975 * in the rcu update to wait only for active cpus. For system
5976 * which do not switch off the HZ timer nohz_cpu_mask should
5977 * always be CPU_BITS_NONE.
5979 cpumask_var_t nohz_cpu_mask;
5982 * Increase the granularity value when there are more CPUs,
5983 * because with more CPUs the 'effective latency' as visible
5984 * to users decreases. But the relationship is not linear,
5985 * so pick a second-best guess by going with the log2 of the
5986 * number of CPUs.
5988 * This idea comes from the SD scheduler of Con Kolivas:
5990 static int get_update_sysctl_factor(void)
5992 unsigned int cpus = min_t(int, num_online_cpus(), 8);
5993 unsigned int factor;
5995 switch (sysctl_sched_tunable_scaling) {
5996 case SCHED_TUNABLESCALING_NONE:
5997 factor = 1;
5998 break;
5999 case SCHED_TUNABLESCALING_LINEAR:
6000 factor = cpus;
6001 break;
6002 case SCHED_TUNABLESCALING_LOG:
6003 default:
6004 factor = 1 + ilog2(cpus);
6005 break;
6008 return factor;
6011 static void update_sysctl(void)
6013 unsigned int factor = get_update_sysctl_factor();
6015 #define SET_SYSCTL(name) \
6016 (sysctl_##name = (factor) * normalized_sysctl_##name)
6017 SET_SYSCTL(sched_min_granularity);
6018 SET_SYSCTL(sched_latency);
6019 SET_SYSCTL(sched_wakeup_granularity);
6020 #undef SET_SYSCTL
6023 static inline void sched_init_granularity(void)
6025 update_sysctl();
6028 #ifdef CONFIG_SMP
6029 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
6031 if (p->sched_class && p->sched_class->set_cpus_allowed)
6032 p->sched_class->set_cpus_allowed(p, new_mask);
6033 else {
6034 cpumask_copy(&p->cpus_allowed, new_mask);
6035 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
6040 * This is how migration works:
6042 * 1) we invoke migration_cpu_stop() on the target CPU using
6043 * stop_one_cpu().
6044 * 2) stopper starts to run (implicitly forcing the migrated thread
6045 * off the CPU)
6046 * 3) it checks whether the migrated task is still in the wrong runqueue.
6047 * 4) if it's in the wrong runqueue then the migration thread removes
6048 * it and puts it into the right queue.
6049 * 5) stopper completes and stop_one_cpu() returns and the migration
6050 * is done.
6054 * Change a given task's CPU affinity. Migrate the thread to a
6055 * proper CPU and schedule it away if the CPU it's executing on
6056 * is removed from the allowed bitmask.
6058 * NOTE: the caller must have a valid reference to the task, the
6059 * task must not exit() & deallocate itself prematurely. The
6060 * call is not atomic; no spinlocks may be held.
6062 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
6064 unsigned long flags;
6065 struct rq *rq;
6066 unsigned int dest_cpu;
6067 int ret = 0;
6069 rq = task_rq_lock(p, &flags);
6071 if (cpumask_equal(&p->cpus_allowed, new_mask))
6072 goto out;
6074 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
6075 ret = -EINVAL;
6076 goto out;
6079 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current)) {
6080 ret = -EINVAL;
6081 goto out;
6084 do_set_cpus_allowed(p, new_mask);
6086 /* Can the task run on the task's current CPU? If so, we're done */
6087 if (cpumask_test_cpu(task_cpu(p), new_mask))
6088 goto out;
6090 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
6091 if (p->on_rq) {
6092 struct migration_arg arg = { p, dest_cpu };
6093 /* Need help from migration thread: drop lock and wait. */
6094 task_rq_unlock(rq, p, &flags);
6095 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
6096 tlb_migrate_finish(p->mm);
6097 return 0;
6099 out:
6100 task_rq_unlock(rq, p, &flags);
6102 return ret;
6104 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6107 * Move (not current) task off this cpu, onto dest cpu. We're doing
6108 * this because either it can't run here any more (set_cpus_allowed()
6109 * away from this CPU, or CPU going down), or because we're
6110 * attempting to rebalance this task on exec (sched_exec).
6112 * So we race with normal scheduler movements, but that's OK, as long
6113 * as the task is no longer on this CPU.
6115 * Returns non-zero if task was successfully migrated.
6117 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6119 struct rq *rq_dest, *rq_src;
6120 int ret = 0;
6122 if (unlikely(!cpu_active(dest_cpu)))
6123 return ret;
6125 rq_src = cpu_rq(src_cpu);
6126 rq_dest = cpu_rq(dest_cpu);
6128 raw_spin_lock(&p->pi_lock);
6129 double_rq_lock(rq_src, rq_dest);
6130 /* Already moved. */
6131 if (task_cpu(p) != src_cpu)
6132 goto done;
6133 /* Affinity changed (again). */
6134 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6135 goto fail;
6138 * If we're not on a rq, the next wake-up will ensure we're
6139 * placed properly.
6141 if (p->on_rq) {
6142 deactivate_task(rq_src, p, 0);
6143 set_task_cpu(p, dest_cpu);
6144 activate_task(rq_dest, p, 0);
6145 check_preempt_curr(rq_dest, p, 0);
6147 done:
6148 ret = 1;
6149 fail:
6150 double_rq_unlock(rq_src, rq_dest);
6151 raw_spin_unlock(&p->pi_lock);
6152 return ret;
6156 * migration_cpu_stop - this will be executed by a highprio stopper thread
6157 * and performs thread migration by bumping thread off CPU then
6158 * 'pushing' onto another runqueue.
6160 static int migration_cpu_stop(void *data)
6162 struct migration_arg *arg = data;
6165 * The original target cpu might have gone down and we might
6166 * be on another cpu but it doesn't matter.
6168 local_irq_disable();
6169 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
6170 local_irq_enable();
6171 return 0;
6174 #ifdef CONFIG_HOTPLUG_CPU
6177 * Ensures that the idle task is using init_mm right before its cpu goes
6178 * offline.
6180 void idle_task_exit(void)
6182 struct mm_struct *mm = current->active_mm;
6184 BUG_ON(cpu_online(smp_processor_id()));
6186 if (mm != &init_mm)
6187 switch_mm(mm, &init_mm, current);
6188 mmdrop(mm);
6192 * While a dead CPU has no uninterruptible tasks queued at this point,
6193 * it might still have a nonzero ->nr_uninterruptible counter, because
6194 * for performance reasons the counter is not stricly tracking tasks to
6195 * their home CPUs. So we just add the counter to another CPU's counter,
6196 * to keep the global sum constant after CPU-down:
6198 static void migrate_nr_uninterruptible(struct rq *rq_src)
6200 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
6202 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6203 rq_src->nr_uninterruptible = 0;
6207 * remove the tasks which were accounted by rq from calc_load_tasks.
6209 static void calc_global_load_remove(struct rq *rq)
6211 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
6212 rq->calc_load_active = 0;
6216 * Migrate all tasks from the rq, sleeping tasks will be migrated by
6217 * try_to_wake_up()->select_task_rq().
6219 * Called with rq->lock held even though we'er in stop_machine() and
6220 * there's no concurrency possible, we hold the required locks anyway
6221 * because of lock validation efforts.
6223 static void migrate_tasks(unsigned int dead_cpu)
6225 struct rq *rq = cpu_rq(dead_cpu);
6226 struct task_struct *next, *stop = rq->stop;
6227 int dest_cpu;
6230 * Fudge the rq selection such that the below task selection loop
6231 * doesn't get stuck on the currently eligible stop task.
6233 * We're currently inside stop_machine() and the rq is either stuck
6234 * in the stop_machine_cpu_stop() loop, or we're executing this code,
6235 * either way we should never end up calling schedule() until we're
6236 * done here.
6238 rq->stop = NULL;
6240 for ( ; ; ) {
6242 * There's this thread running, bail when that's the only
6243 * remaining thread.
6245 if (rq->nr_running == 1)
6246 break;
6248 next = pick_next_task(rq);
6249 BUG_ON(!next);
6250 next->sched_class->put_prev_task(rq, next);
6252 /* Find suitable destination for @next, with force if needed. */
6253 dest_cpu = select_fallback_rq(dead_cpu, next);
6254 raw_spin_unlock(&rq->lock);
6256 __migrate_task(next, dead_cpu, dest_cpu);
6258 raw_spin_lock(&rq->lock);
6261 rq->stop = stop;
6264 #endif /* CONFIG_HOTPLUG_CPU */
6266 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6268 static struct ctl_table sd_ctl_dir[] = {
6270 .procname = "sched_domain",
6271 .mode = 0555,
6276 static struct ctl_table sd_ctl_root[] = {
6278 .procname = "kernel",
6279 .mode = 0555,
6280 .child = sd_ctl_dir,
6285 static struct ctl_table *sd_alloc_ctl_entry(int n)
6287 struct ctl_table *entry =
6288 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6290 return entry;
6293 static void sd_free_ctl_entry(struct ctl_table **tablep)
6295 struct ctl_table *entry;
6298 * In the intermediate directories, both the child directory and
6299 * procname are dynamically allocated and could fail but the mode
6300 * will always be set. In the lowest directory the names are
6301 * static strings and all have proc handlers.
6303 for (entry = *tablep; entry->mode; entry++) {
6304 if (entry->child)
6305 sd_free_ctl_entry(&entry->child);
6306 if (entry->proc_handler == NULL)
6307 kfree(entry->procname);
6310 kfree(*tablep);
6311 *tablep = NULL;
6314 static void
6315 set_table_entry(struct ctl_table *entry,
6316 const char *procname, void *data, int maxlen,
6317 mode_t mode, proc_handler *proc_handler)
6319 entry->procname = procname;
6320 entry->data = data;
6321 entry->maxlen = maxlen;
6322 entry->mode = mode;
6323 entry->proc_handler = proc_handler;
6326 static struct ctl_table *
6327 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6329 struct ctl_table *table = sd_alloc_ctl_entry(13);
6331 if (table == NULL)
6332 return NULL;
6334 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6335 sizeof(long), 0644, proc_doulongvec_minmax);
6336 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6337 sizeof(long), 0644, proc_doulongvec_minmax);
6338 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6339 sizeof(int), 0644, proc_dointvec_minmax);
6340 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6341 sizeof(int), 0644, proc_dointvec_minmax);
6342 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6343 sizeof(int), 0644, proc_dointvec_minmax);
6344 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6345 sizeof(int), 0644, proc_dointvec_minmax);
6346 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6347 sizeof(int), 0644, proc_dointvec_minmax);
6348 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6349 sizeof(int), 0644, proc_dointvec_minmax);
6350 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6351 sizeof(int), 0644, proc_dointvec_minmax);
6352 set_table_entry(&table[9], "cache_nice_tries",
6353 &sd->cache_nice_tries,
6354 sizeof(int), 0644, proc_dointvec_minmax);
6355 set_table_entry(&table[10], "flags", &sd->flags,
6356 sizeof(int), 0644, proc_dointvec_minmax);
6357 set_table_entry(&table[11], "name", sd->name,
6358 CORENAME_MAX_SIZE, 0444, proc_dostring);
6359 /* &table[12] is terminator */
6361 return table;
6364 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6366 struct ctl_table *entry, *table;
6367 struct sched_domain *sd;
6368 int domain_num = 0, i;
6369 char buf[32];
6371 for_each_domain(cpu, sd)
6372 domain_num++;
6373 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6374 if (table == NULL)
6375 return NULL;
6377 i = 0;
6378 for_each_domain(cpu, sd) {
6379 snprintf(buf, 32, "domain%d", i);
6380 entry->procname = kstrdup(buf, GFP_KERNEL);
6381 entry->mode = 0555;
6382 entry->child = sd_alloc_ctl_domain_table(sd);
6383 entry++;
6384 i++;
6386 return table;
6389 static struct ctl_table_header *sd_sysctl_header;
6390 static void register_sched_domain_sysctl(void)
6392 int i, cpu_num = num_possible_cpus();
6393 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6394 char buf[32];
6396 WARN_ON(sd_ctl_dir[0].child);
6397 sd_ctl_dir[0].child = entry;
6399 if (entry == NULL)
6400 return;
6402 for_each_possible_cpu(i) {
6403 snprintf(buf, 32, "cpu%d", i);
6404 entry->procname = kstrdup(buf, GFP_KERNEL);
6405 entry->mode = 0555;
6406 entry->child = sd_alloc_ctl_cpu_table(i);
6407 entry++;
6410 WARN_ON(sd_sysctl_header);
6411 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6414 /* may be called multiple times per register */
6415 static void unregister_sched_domain_sysctl(void)
6417 if (sd_sysctl_header)
6418 unregister_sysctl_table(sd_sysctl_header);
6419 sd_sysctl_header = NULL;
6420 if (sd_ctl_dir[0].child)
6421 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6423 #else
6424 static void register_sched_domain_sysctl(void)
6427 static void unregister_sched_domain_sysctl(void)
6430 #endif
6432 static void set_rq_online(struct rq *rq)
6434 if (!rq->online) {
6435 const struct sched_class *class;
6437 cpumask_set_cpu(rq->cpu, rq->rd->online);
6438 rq->online = 1;
6440 for_each_class(class) {
6441 if (class->rq_online)
6442 class->rq_online(rq);
6447 static void set_rq_offline(struct rq *rq)
6449 if (rq->online) {
6450 const struct sched_class *class;
6452 for_each_class(class) {
6453 if (class->rq_offline)
6454 class->rq_offline(rq);
6457 cpumask_clear_cpu(rq->cpu, rq->rd->online);
6458 rq->online = 0;
6463 * migration_call - callback that gets triggered when a CPU is added.
6464 * Here we can start up the necessary migration thread for the new CPU.
6466 static int __cpuinit
6467 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6469 int cpu = (long)hcpu;
6470 unsigned long flags;
6471 struct rq *rq = cpu_rq(cpu);
6473 switch (action & ~CPU_TASKS_FROZEN) {
6475 case CPU_UP_PREPARE:
6476 rq->calc_load_update = calc_load_update;
6477 break;
6479 case CPU_ONLINE:
6480 /* Update our root-domain */
6481 raw_spin_lock_irqsave(&rq->lock, flags);
6482 if (rq->rd) {
6483 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6485 set_rq_online(rq);
6487 raw_spin_unlock_irqrestore(&rq->lock, flags);
6488 break;
6490 #ifdef CONFIG_HOTPLUG_CPU
6491 case CPU_DYING:
6492 sched_ttwu_pending();
6493 /* Update our root-domain */
6494 raw_spin_lock_irqsave(&rq->lock, flags);
6495 if (rq->rd) {
6496 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6497 set_rq_offline(rq);
6499 migrate_tasks(cpu);
6500 BUG_ON(rq->nr_running != 1); /* the migration thread */
6501 raw_spin_unlock_irqrestore(&rq->lock, flags);
6503 migrate_nr_uninterruptible(rq);
6504 calc_global_load_remove(rq);
6505 break;
6506 #endif
6509 update_max_interval();
6511 return NOTIFY_OK;
6515 * Register at high priority so that task migration (migrate_all_tasks)
6516 * happens before everything else. This has to be lower priority than
6517 * the notifier in the perf_event subsystem, though.
6519 static struct notifier_block __cpuinitdata migration_notifier = {
6520 .notifier_call = migration_call,
6521 .priority = CPU_PRI_MIGRATION,
6524 static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
6525 unsigned long action, void *hcpu)
6527 switch (action & ~CPU_TASKS_FROZEN) {
6528 case CPU_ONLINE:
6529 case CPU_DOWN_FAILED:
6530 set_cpu_active((long)hcpu, true);
6531 return NOTIFY_OK;
6532 default:
6533 return NOTIFY_DONE;
6537 static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
6538 unsigned long action, void *hcpu)
6540 switch (action & ~CPU_TASKS_FROZEN) {
6541 case CPU_DOWN_PREPARE:
6542 set_cpu_active((long)hcpu, false);
6543 return NOTIFY_OK;
6544 default:
6545 return NOTIFY_DONE;
6549 static int __init migration_init(void)
6551 void *cpu = (void *)(long)smp_processor_id();
6552 int err;
6554 /* Initialize migration for the boot CPU */
6555 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6556 BUG_ON(err == NOTIFY_BAD);
6557 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6558 register_cpu_notifier(&migration_notifier);
6560 /* Register cpu active notifiers */
6561 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
6562 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
6564 return 0;
6566 early_initcall(migration_init);
6567 #endif
6569 #ifdef CONFIG_SMP
6571 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
6573 #ifdef CONFIG_SCHED_DEBUG
6575 static __read_mostly int sched_domain_debug_enabled;
6577 static int __init sched_domain_debug_setup(char *str)
6579 sched_domain_debug_enabled = 1;
6581 return 0;
6583 early_param("sched_debug", sched_domain_debug_setup);
6585 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6586 struct cpumask *groupmask)
6588 struct sched_group *group = sd->groups;
6589 char str[256];
6591 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
6592 cpumask_clear(groupmask);
6594 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6596 if (!(sd->flags & SD_LOAD_BALANCE)) {
6597 printk("does not load-balance\n");
6598 if (sd->parent)
6599 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6600 " has parent");
6601 return -1;
6604 printk(KERN_CONT "span %s level %s\n", str, sd->name);
6606 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6607 printk(KERN_ERR "ERROR: domain->span does not contain "
6608 "CPU%d\n", cpu);
6610 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6611 printk(KERN_ERR "ERROR: domain->groups does not contain"
6612 " CPU%d\n", cpu);
6615 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6616 do {
6617 if (!group) {
6618 printk("\n");
6619 printk(KERN_ERR "ERROR: group is NULL\n");
6620 break;
6623 if (!group->sgp->power) {
6624 printk(KERN_CONT "\n");
6625 printk(KERN_ERR "ERROR: domain->cpu_power not "
6626 "set\n");
6627 break;
6630 if (!cpumask_weight(sched_group_cpus(group))) {
6631 printk(KERN_CONT "\n");
6632 printk(KERN_ERR "ERROR: empty group\n");
6633 break;
6636 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6637 printk(KERN_CONT "\n");
6638 printk(KERN_ERR "ERROR: repeated CPUs\n");
6639 break;
6642 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6644 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6646 printk(KERN_CONT " %s", str);
6647 if (group->sgp->power != SCHED_POWER_SCALE) {
6648 printk(KERN_CONT " (cpu_power = %d)",
6649 group->sgp->power);
6652 group = group->next;
6653 } while (group != sd->groups);
6654 printk(KERN_CONT "\n");
6656 if (!cpumask_equal(sched_domain_span(sd), groupmask))
6657 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6659 if (sd->parent &&
6660 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6661 printk(KERN_ERR "ERROR: parent span is not a superset "
6662 "of domain->span\n");
6663 return 0;
6666 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6668 int level = 0;
6670 if (!sched_domain_debug_enabled)
6671 return;
6673 if (!sd) {
6674 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6675 return;
6678 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6680 for (;;) {
6681 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
6682 break;
6683 level++;
6684 sd = sd->parent;
6685 if (!sd)
6686 break;
6689 #else /* !CONFIG_SCHED_DEBUG */
6690 # define sched_domain_debug(sd, cpu) do { } while (0)
6691 #endif /* CONFIG_SCHED_DEBUG */
6693 static int sd_degenerate(struct sched_domain *sd)
6695 if (cpumask_weight(sched_domain_span(sd)) == 1)
6696 return 1;
6698 /* Following flags need at least 2 groups */
6699 if (sd->flags & (SD_LOAD_BALANCE |
6700 SD_BALANCE_NEWIDLE |
6701 SD_BALANCE_FORK |
6702 SD_BALANCE_EXEC |
6703 SD_SHARE_CPUPOWER |
6704 SD_SHARE_PKG_RESOURCES)) {
6705 if (sd->groups != sd->groups->next)
6706 return 0;
6709 /* Following flags don't use groups */
6710 if (sd->flags & (SD_WAKE_AFFINE))
6711 return 0;
6713 return 1;
6716 static int
6717 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6719 unsigned long cflags = sd->flags, pflags = parent->flags;
6721 if (sd_degenerate(parent))
6722 return 1;
6724 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6725 return 0;
6727 /* Flags needing groups don't count if only 1 group in parent */
6728 if (parent->groups == parent->groups->next) {
6729 pflags &= ~(SD_LOAD_BALANCE |
6730 SD_BALANCE_NEWIDLE |
6731 SD_BALANCE_FORK |
6732 SD_BALANCE_EXEC |
6733 SD_SHARE_CPUPOWER |
6734 SD_SHARE_PKG_RESOURCES);
6735 if (nr_node_ids == 1)
6736 pflags &= ~SD_SERIALIZE;
6738 if (~cflags & pflags)
6739 return 0;
6741 return 1;
6744 static void free_rootdomain(struct rcu_head *rcu)
6746 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
6748 cpupri_cleanup(&rd->cpupri);
6749 free_cpumask_var(rd->rto_mask);
6750 free_cpumask_var(rd->online);
6751 free_cpumask_var(rd->span);
6752 kfree(rd);
6755 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6757 struct root_domain *old_rd = NULL;
6758 unsigned long flags;
6760 raw_spin_lock_irqsave(&rq->lock, flags);
6762 if (rq->rd) {
6763 old_rd = rq->rd;
6765 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6766 set_rq_offline(rq);
6768 cpumask_clear_cpu(rq->cpu, old_rd->span);
6771 * If we dont want to free the old_rt yet then
6772 * set old_rd to NULL to skip the freeing later
6773 * in this function:
6775 if (!atomic_dec_and_test(&old_rd->refcount))
6776 old_rd = NULL;
6779 atomic_inc(&rd->refcount);
6780 rq->rd = rd;
6782 cpumask_set_cpu(rq->cpu, rd->span);
6783 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6784 set_rq_online(rq);
6786 raw_spin_unlock_irqrestore(&rq->lock, flags);
6788 if (old_rd)
6789 call_rcu_sched(&old_rd->rcu, free_rootdomain);
6792 static int init_rootdomain(struct root_domain *rd)
6794 memset(rd, 0, sizeof(*rd));
6796 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
6797 goto out;
6798 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
6799 goto free_span;
6800 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6801 goto free_online;
6803 if (cpupri_init(&rd->cpupri) != 0)
6804 goto free_rto_mask;
6805 return 0;
6807 free_rto_mask:
6808 free_cpumask_var(rd->rto_mask);
6809 free_online:
6810 free_cpumask_var(rd->online);
6811 free_span:
6812 free_cpumask_var(rd->span);
6813 out:
6814 return -ENOMEM;
6817 static void init_defrootdomain(void)
6819 init_rootdomain(&def_root_domain);
6821 atomic_set(&def_root_domain.refcount, 1);
6824 static struct root_domain *alloc_rootdomain(void)
6826 struct root_domain *rd;
6828 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6829 if (!rd)
6830 return NULL;
6832 if (init_rootdomain(rd) != 0) {
6833 kfree(rd);
6834 return NULL;
6837 return rd;
6840 static void free_sched_groups(struct sched_group *sg, int free_sgp)
6842 struct sched_group *tmp, *first;
6844 if (!sg)
6845 return;
6847 first = sg;
6848 do {
6849 tmp = sg->next;
6851 if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
6852 kfree(sg->sgp);
6854 kfree(sg);
6855 sg = tmp;
6856 } while (sg != first);
6859 static void free_sched_domain(struct rcu_head *rcu)
6861 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
6864 * If its an overlapping domain it has private groups, iterate and
6865 * nuke them all.
6867 if (sd->flags & SD_OVERLAP) {
6868 free_sched_groups(sd->groups, 1);
6869 } else if (atomic_dec_and_test(&sd->groups->ref)) {
6870 kfree(sd->groups->sgp);
6871 kfree(sd->groups);
6873 kfree(sd);
6876 static void destroy_sched_domain(struct sched_domain *sd, int cpu)
6878 call_rcu(&sd->rcu, free_sched_domain);
6881 static void destroy_sched_domains(struct sched_domain *sd, int cpu)
6883 for (; sd; sd = sd->parent)
6884 destroy_sched_domain(sd, cpu);
6888 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6889 * hold the hotplug lock.
6891 static void
6892 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6894 struct rq *rq = cpu_rq(cpu);
6895 struct sched_domain *tmp;
6897 /* Remove the sched domains which do not contribute to scheduling. */
6898 for (tmp = sd; tmp; ) {
6899 struct sched_domain *parent = tmp->parent;
6900 if (!parent)
6901 break;
6903 if (sd_parent_degenerate(tmp, parent)) {
6904 tmp->parent = parent->parent;
6905 if (parent->parent)
6906 parent->parent->child = tmp;
6907 destroy_sched_domain(parent, cpu);
6908 } else
6909 tmp = tmp->parent;
6912 if (sd && sd_degenerate(sd)) {
6913 tmp = sd;
6914 sd = sd->parent;
6915 destroy_sched_domain(tmp, cpu);
6916 if (sd)
6917 sd->child = NULL;
6920 sched_domain_debug(sd, cpu);
6922 rq_attach_root(rq, rd);
6923 tmp = rq->sd;
6924 rcu_assign_pointer(rq->sd, sd);
6925 destroy_sched_domains(tmp, cpu);
6928 /* cpus with isolated domains */
6929 static cpumask_var_t cpu_isolated_map;
6931 /* Setup the mask of cpus configured for isolated domains */
6932 static int __init isolated_cpu_setup(char *str)
6934 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6935 cpulist_parse(str, cpu_isolated_map);
6936 return 1;
6939 __setup("isolcpus=", isolated_cpu_setup);
6941 #define SD_NODES_PER_DOMAIN 16
6943 #ifdef CONFIG_NUMA
6946 * find_next_best_node - find the next node to include in a sched_domain
6947 * @node: node whose sched_domain we're building
6948 * @used_nodes: nodes already in the sched_domain
6950 * Find the next node to include in a given scheduling domain. Simply
6951 * finds the closest node not already in the @used_nodes map.
6953 * Should use nodemask_t.
6955 static int find_next_best_node(int node, nodemask_t *used_nodes)
6957 int i, n, val, min_val, best_node = -1;
6959 min_val = INT_MAX;
6961 for (i = 0; i < nr_node_ids; i++) {
6962 /* Start at @node */
6963 n = (node + i) % nr_node_ids;
6965 if (!nr_cpus_node(n))
6966 continue;
6968 /* Skip already used nodes */
6969 if (node_isset(n, *used_nodes))
6970 continue;
6972 /* Simple min distance search */
6973 val = node_distance(node, n);
6975 if (val < min_val) {
6976 min_val = val;
6977 best_node = n;
6981 if (best_node != -1)
6982 node_set(best_node, *used_nodes);
6983 return best_node;
6987 * sched_domain_node_span - get a cpumask for a node's sched_domain
6988 * @node: node whose cpumask we're constructing
6989 * @span: resulting cpumask
6991 * Given a node, construct a good cpumask for its sched_domain to span. It
6992 * should be one that prevents unnecessary balancing, but also spreads tasks
6993 * out optimally.
6995 static void sched_domain_node_span(int node, struct cpumask *span)
6997 nodemask_t used_nodes;
6998 int i;
7000 cpumask_clear(span);
7001 nodes_clear(used_nodes);
7003 cpumask_or(span, span, cpumask_of_node(node));
7004 node_set(node, used_nodes);
7006 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
7007 int next_node = find_next_best_node(node, &used_nodes);
7008 if (next_node < 0)
7009 break;
7010 cpumask_or(span, span, cpumask_of_node(next_node));
7014 static const struct cpumask *cpu_node_mask(int cpu)
7016 lockdep_assert_held(&sched_domains_mutex);
7018 sched_domain_node_span(cpu_to_node(cpu), sched_domains_tmpmask);
7020 return sched_domains_tmpmask;
7023 static const struct cpumask *cpu_allnodes_mask(int cpu)
7025 return cpu_possible_mask;
7027 #endif /* CONFIG_NUMA */
7029 static const struct cpumask *cpu_cpu_mask(int cpu)
7031 return cpumask_of_node(cpu_to_node(cpu));
7034 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7036 struct sd_data {
7037 struct sched_domain **__percpu sd;
7038 struct sched_group **__percpu sg;
7039 struct sched_group_power **__percpu sgp;
7042 struct s_data {
7043 struct sched_domain ** __percpu sd;
7044 struct root_domain *rd;
7047 enum s_alloc {
7048 sa_rootdomain,
7049 sa_sd,
7050 sa_sd_storage,
7051 sa_none,
7054 struct sched_domain_topology_level;
7056 typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
7057 typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
7059 #define SDTL_OVERLAP 0x01
7061 struct sched_domain_topology_level {
7062 sched_domain_init_f init;
7063 sched_domain_mask_f mask;
7064 int flags;
7065 struct sd_data data;
7068 static int
7069 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
7071 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
7072 const struct cpumask *span = sched_domain_span(sd);
7073 struct cpumask *covered = sched_domains_tmpmask;
7074 struct sd_data *sdd = sd->private;
7075 struct sched_domain *child;
7076 int i;
7078 cpumask_clear(covered);
7080 for_each_cpu(i, span) {
7081 struct cpumask *sg_span;
7083 if (cpumask_test_cpu(i, covered))
7084 continue;
7086 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
7087 GFP_KERNEL, cpu_to_node(i));
7089 if (!sg)
7090 goto fail;
7092 sg_span = sched_group_cpus(sg);
7094 child = *per_cpu_ptr(sdd->sd, i);
7095 if (child->child) {
7096 child = child->child;
7097 cpumask_copy(sg_span, sched_domain_span(child));
7098 } else
7099 cpumask_set_cpu(i, sg_span);
7101 cpumask_or(covered, covered, sg_span);
7103 sg->sgp = *per_cpu_ptr(sdd->sgp, cpumask_first(sg_span));
7104 atomic_inc(&sg->sgp->ref);
7106 if (cpumask_test_cpu(cpu, sg_span))
7107 groups = sg;
7109 if (!first)
7110 first = sg;
7111 if (last)
7112 last->next = sg;
7113 last = sg;
7114 last->next = first;
7116 sd->groups = groups;
7118 return 0;
7120 fail:
7121 free_sched_groups(first, 0);
7123 return -ENOMEM;
7126 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
7128 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
7129 struct sched_domain *child = sd->child;
7131 if (child)
7132 cpu = cpumask_first(sched_domain_span(child));
7134 if (sg) {
7135 *sg = *per_cpu_ptr(sdd->sg, cpu);
7136 (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
7137 atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
7140 return cpu;
7144 * build_sched_groups will build a circular linked list of the groups
7145 * covered by the given span, and will set each group's ->cpumask correctly,
7146 * and ->cpu_power to 0.
7148 * Assumes the sched_domain tree is fully constructed
7150 static int
7151 build_sched_groups(struct sched_domain *sd, int cpu)
7153 struct sched_group *first = NULL, *last = NULL;
7154 struct sd_data *sdd = sd->private;
7155 const struct cpumask *span = sched_domain_span(sd);
7156 struct cpumask *covered;
7157 int i;
7159 get_group(cpu, sdd, &sd->groups);
7160 atomic_inc(&sd->groups->ref);
7162 if (cpu != cpumask_first(sched_domain_span(sd)))
7163 return 0;
7165 lockdep_assert_held(&sched_domains_mutex);
7166 covered = sched_domains_tmpmask;
7168 cpumask_clear(covered);
7170 for_each_cpu(i, span) {
7171 struct sched_group *sg;
7172 int group = get_group(i, sdd, &sg);
7173 int j;
7175 if (cpumask_test_cpu(i, covered))
7176 continue;
7178 cpumask_clear(sched_group_cpus(sg));
7179 sg->sgp->power = 0;
7181 for_each_cpu(j, span) {
7182 if (get_group(j, sdd, NULL) != group)
7183 continue;
7185 cpumask_set_cpu(j, covered);
7186 cpumask_set_cpu(j, sched_group_cpus(sg));
7189 if (!first)
7190 first = sg;
7191 if (last)
7192 last->next = sg;
7193 last = sg;
7195 last->next = first;
7197 return 0;
7201 * Initialize sched groups cpu_power.
7203 * cpu_power indicates the capacity of sched group, which is used while
7204 * distributing the load between different sched groups in a sched domain.
7205 * Typically cpu_power for all the groups in a sched domain will be same unless
7206 * there are asymmetries in the topology. If there are asymmetries, group
7207 * having more cpu_power will pickup more load compared to the group having
7208 * less cpu_power.
7210 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7212 struct sched_group *sg = sd->groups;
7214 WARN_ON(!sd || !sg);
7216 do {
7217 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
7218 sg = sg->next;
7219 } while (sg != sd->groups);
7221 if (cpu != group_first_cpu(sg))
7222 return;
7224 update_group_power(sd, cpu);
7228 * Initializers for schedule domains
7229 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7232 #ifdef CONFIG_SCHED_DEBUG
7233 # define SD_INIT_NAME(sd, type) sd->name = #type
7234 #else
7235 # define SD_INIT_NAME(sd, type) do { } while (0)
7236 #endif
7238 #define SD_INIT_FUNC(type) \
7239 static noinline struct sched_domain * \
7240 sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \
7242 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \
7243 *sd = SD_##type##_INIT; \
7244 SD_INIT_NAME(sd, type); \
7245 sd->private = &tl->data; \
7246 return sd; \
7249 SD_INIT_FUNC(CPU)
7250 #ifdef CONFIG_NUMA
7251 SD_INIT_FUNC(ALLNODES)
7252 SD_INIT_FUNC(NODE)
7253 #endif
7254 #ifdef CONFIG_SCHED_SMT
7255 SD_INIT_FUNC(SIBLING)
7256 #endif
7257 #ifdef CONFIG_SCHED_MC
7258 SD_INIT_FUNC(MC)
7259 #endif
7260 #ifdef CONFIG_SCHED_BOOK
7261 SD_INIT_FUNC(BOOK)
7262 #endif
7264 static int default_relax_domain_level = -1;
7265 int sched_domain_level_max;
7267 static int __init setup_relax_domain_level(char *str)
7269 unsigned long val;
7271 val = simple_strtoul(str, NULL, 0);
7272 if (val < sched_domain_level_max)
7273 default_relax_domain_level = val;
7275 return 1;
7277 __setup("relax_domain_level=", setup_relax_domain_level);
7279 static void set_domain_attribute(struct sched_domain *sd,
7280 struct sched_domain_attr *attr)
7282 int request;
7284 if (!attr || attr->relax_domain_level < 0) {
7285 if (default_relax_domain_level < 0)
7286 return;
7287 else
7288 request = default_relax_domain_level;
7289 } else
7290 request = attr->relax_domain_level;
7291 if (request < sd->level) {
7292 /* turn off idle balance on this domain */
7293 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
7294 } else {
7295 /* turn on idle balance on this domain */
7296 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
7300 static void __sdt_free(const struct cpumask *cpu_map);
7301 static int __sdt_alloc(const struct cpumask *cpu_map);
7303 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
7304 const struct cpumask *cpu_map)
7306 switch (what) {
7307 case sa_rootdomain:
7308 if (!atomic_read(&d->rd->refcount))
7309 free_rootdomain(&d->rd->rcu); /* fall through */
7310 case sa_sd:
7311 free_percpu(d->sd); /* fall through */
7312 case sa_sd_storage:
7313 __sdt_free(cpu_map); /* fall through */
7314 case sa_none:
7315 break;
7319 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
7320 const struct cpumask *cpu_map)
7322 memset(d, 0, sizeof(*d));
7324 if (__sdt_alloc(cpu_map))
7325 return sa_sd_storage;
7326 d->sd = alloc_percpu(struct sched_domain *);
7327 if (!d->sd)
7328 return sa_sd_storage;
7329 d->rd = alloc_rootdomain();
7330 if (!d->rd)
7331 return sa_sd;
7332 return sa_rootdomain;
7336 * NULL the sd_data elements we've used to build the sched_domain and
7337 * sched_group structure so that the subsequent __free_domain_allocs()
7338 * will not free the data we're using.
7340 static void claim_allocations(int cpu, struct sched_domain *sd)
7342 struct sd_data *sdd = sd->private;
7344 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
7345 *per_cpu_ptr(sdd->sd, cpu) = NULL;
7347 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
7348 *per_cpu_ptr(sdd->sg, cpu) = NULL;
7350 if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
7351 *per_cpu_ptr(sdd->sgp, cpu) = NULL;
7354 #ifdef CONFIG_SCHED_SMT
7355 static const struct cpumask *cpu_smt_mask(int cpu)
7357 return topology_thread_cpumask(cpu);
7359 #endif
7362 * Topology list, bottom-up.
7364 static struct sched_domain_topology_level default_topology[] = {
7365 #ifdef CONFIG_SCHED_SMT
7366 { sd_init_SIBLING, cpu_smt_mask, },
7367 #endif
7368 #ifdef CONFIG_SCHED_MC
7369 { sd_init_MC, cpu_coregroup_mask, },
7370 #endif
7371 #ifdef CONFIG_SCHED_BOOK
7372 { sd_init_BOOK, cpu_book_mask, },
7373 #endif
7374 { sd_init_CPU, cpu_cpu_mask, },
7375 #ifdef CONFIG_NUMA
7376 { sd_init_NODE, cpu_node_mask, SDTL_OVERLAP, },
7377 { sd_init_ALLNODES, cpu_allnodes_mask, },
7378 #endif
7379 { NULL, },
7382 static struct sched_domain_topology_level *sched_domain_topology = default_topology;
7384 static int __sdt_alloc(const struct cpumask *cpu_map)
7386 struct sched_domain_topology_level *tl;
7387 int j;
7389 for (tl = sched_domain_topology; tl->init; tl++) {
7390 struct sd_data *sdd = &tl->data;
7392 sdd->sd = alloc_percpu(struct sched_domain *);
7393 if (!sdd->sd)
7394 return -ENOMEM;
7396 sdd->sg = alloc_percpu(struct sched_group *);
7397 if (!sdd->sg)
7398 return -ENOMEM;
7400 sdd->sgp = alloc_percpu(struct sched_group_power *);
7401 if (!sdd->sgp)
7402 return -ENOMEM;
7404 for_each_cpu(j, cpu_map) {
7405 struct sched_domain *sd;
7406 struct sched_group *sg;
7407 struct sched_group_power *sgp;
7409 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
7410 GFP_KERNEL, cpu_to_node(j));
7411 if (!sd)
7412 return -ENOMEM;
7414 *per_cpu_ptr(sdd->sd, j) = sd;
7416 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
7417 GFP_KERNEL, cpu_to_node(j));
7418 if (!sg)
7419 return -ENOMEM;
7421 *per_cpu_ptr(sdd->sg, j) = sg;
7423 sgp = kzalloc_node(sizeof(struct sched_group_power),
7424 GFP_KERNEL, cpu_to_node(j));
7425 if (!sgp)
7426 return -ENOMEM;
7428 *per_cpu_ptr(sdd->sgp, j) = sgp;
7432 return 0;
7435 static void __sdt_free(const struct cpumask *cpu_map)
7437 struct sched_domain_topology_level *tl;
7438 int j;
7440 for (tl = sched_domain_topology; tl->init; tl++) {
7441 struct sd_data *sdd = &tl->data;
7443 for_each_cpu(j, cpu_map) {
7444 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, j);
7445 if (sd && (sd->flags & SD_OVERLAP))
7446 free_sched_groups(sd->groups, 0);
7447 kfree(*per_cpu_ptr(sdd->sg, j));
7448 kfree(*per_cpu_ptr(sdd->sgp, j));
7450 free_percpu(sdd->sd);
7451 free_percpu(sdd->sg);
7452 free_percpu(sdd->sgp);
7456 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
7457 struct s_data *d, const struct cpumask *cpu_map,
7458 struct sched_domain_attr *attr, struct sched_domain *child,
7459 int cpu)
7461 struct sched_domain *sd = tl->init(tl, cpu);
7462 if (!sd)
7463 return child;
7465 set_domain_attribute(sd, attr);
7466 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
7467 if (child) {
7468 sd->level = child->level + 1;
7469 sched_domain_level_max = max(sched_domain_level_max, sd->level);
7470 child->parent = sd;
7472 sd->child = child;
7474 return sd;
7478 * Build sched domains for a given set of cpus and attach the sched domains
7479 * to the individual cpus
7481 static int build_sched_domains(const struct cpumask *cpu_map,
7482 struct sched_domain_attr *attr)
7484 enum s_alloc alloc_state = sa_none;
7485 struct sched_domain *sd;
7486 struct s_data d;
7487 int i, ret = -ENOMEM;
7489 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7490 if (alloc_state != sa_rootdomain)
7491 goto error;
7493 /* Set up domains for cpus specified by the cpu_map. */
7494 for_each_cpu(i, cpu_map) {
7495 struct sched_domain_topology_level *tl;
7497 sd = NULL;
7498 for (tl = sched_domain_topology; tl->init; tl++) {
7499 sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i);
7500 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
7501 sd->flags |= SD_OVERLAP;
7502 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
7503 break;
7506 while (sd->child)
7507 sd = sd->child;
7509 *per_cpu_ptr(d.sd, i) = sd;
7512 /* Build the groups for the domains */
7513 for_each_cpu(i, cpu_map) {
7514 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7515 sd->span_weight = cpumask_weight(sched_domain_span(sd));
7516 if (sd->flags & SD_OVERLAP) {
7517 if (build_overlap_sched_groups(sd, i))
7518 goto error;
7519 } else {
7520 if (build_sched_groups(sd, i))
7521 goto error;
7526 /* Calculate CPU power for physical packages and nodes */
7527 for (i = nr_cpumask_bits-1; i >= 0; i--) {
7528 if (!cpumask_test_cpu(i, cpu_map))
7529 continue;
7531 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7532 claim_allocations(i, sd);
7533 init_sched_groups_power(i, sd);
7537 /* Attach the domains */
7538 rcu_read_lock();
7539 for_each_cpu(i, cpu_map) {
7540 sd = *per_cpu_ptr(d.sd, i);
7541 cpu_attach_domain(sd, d.rd, i);
7543 rcu_read_unlock();
7545 ret = 0;
7546 error:
7547 __free_domain_allocs(&d, alloc_state, cpu_map);
7548 return ret;
7551 static cpumask_var_t *doms_cur; /* current sched domains */
7552 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7553 static struct sched_domain_attr *dattr_cur;
7554 /* attribues of custom domains in 'doms_cur' */
7557 * Special case: If a kmalloc of a doms_cur partition (array of
7558 * cpumask) fails, then fallback to a single sched domain,
7559 * as determined by the single cpumask fallback_doms.
7561 static cpumask_var_t fallback_doms;
7564 * arch_update_cpu_topology lets virtualized architectures update the
7565 * cpu core maps. It is supposed to return 1 if the topology changed
7566 * or 0 if it stayed the same.
7568 int __attribute__((weak)) arch_update_cpu_topology(void)
7570 return 0;
7573 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7575 int i;
7576 cpumask_var_t *doms;
7578 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7579 if (!doms)
7580 return NULL;
7581 for (i = 0; i < ndoms; i++) {
7582 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7583 free_sched_domains(doms, i);
7584 return NULL;
7587 return doms;
7590 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7592 unsigned int i;
7593 for (i = 0; i < ndoms; i++)
7594 free_cpumask_var(doms[i]);
7595 kfree(doms);
7599 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7600 * For now this just excludes isolated cpus, but could be used to
7601 * exclude other special cases in the future.
7603 static int init_sched_domains(const struct cpumask *cpu_map)
7605 int err;
7607 arch_update_cpu_topology();
7608 ndoms_cur = 1;
7609 doms_cur = alloc_sched_domains(ndoms_cur);
7610 if (!doms_cur)
7611 doms_cur = &fallback_doms;
7612 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7613 dattr_cur = NULL;
7614 err = build_sched_domains(doms_cur[0], NULL);
7615 register_sched_domain_sysctl();
7617 return err;
7621 * Detach sched domains from a group of cpus specified in cpu_map
7622 * These cpus will now be attached to the NULL domain
7624 static void detach_destroy_domains(const struct cpumask *cpu_map)
7626 int i;
7628 rcu_read_lock();
7629 for_each_cpu(i, cpu_map)
7630 cpu_attach_domain(NULL, &def_root_domain, i);
7631 rcu_read_unlock();
7634 /* handle null as "default" */
7635 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7636 struct sched_domain_attr *new, int idx_new)
7638 struct sched_domain_attr tmp;
7640 /* fast path */
7641 if (!new && !cur)
7642 return 1;
7644 tmp = SD_ATTR_INIT;
7645 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7646 new ? (new + idx_new) : &tmp,
7647 sizeof(struct sched_domain_attr));
7651 * Partition sched domains as specified by the 'ndoms_new'
7652 * cpumasks in the array doms_new[] of cpumasks. This compares
7653 * doms_new[] to the current sched domain partitioning, doms_cur[].
7654 * It destroys each deleted domain and builds each new domain.
7656 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7657 * The masks don't intersect (don't overlap.) We should setup one
7658 * sched domain for each mask. CPUs not in any of the cpumasks will
7659 * not be load balanced. If the same cpumask appears both in the
7660 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7661 * it as it is.
7663 * The passed in 'doms_new' should be allocated using
7664 * alloc_sched_domains. This routine takes ownership of it and will
7665 * free_sched_domains it when done with it. If the caller failed the
7666 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7667 * and partition_sched_domains() will fallback to the single partition
7668 * 'fallback_doms', it also forces the domains to be rebuilt.
7670 * If doms_new == NULL it will be replaced with cpu_online_mask.
7671 * ndoms_new == 0 is a special case for destroying existing domains,
7672 * and it will not create the default domain.
7674 * Call with hotplug lock held
7676 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7677 struct sched_domain_attr *dattr_new)
7679 int i, j, n;
7680 int new_topology;
7682 mutex_lock(&sched_domains_mutex);
7684 /* always unregister in case we don't destroy any domains */
7685 unregister_sched_domain_sysctl();
7687 /* Let architecture update cpu core mappings. */
7688 new_topology = arch_update_cpu_topology();
7690 n = doms_new ? ndoms_new : 0;
7692 /* Destroy deleted domains */
7693 for (i = 0; i < ndoms_cur; i++) {
7694 for (j = 0; j < n && !new_topology; j++) {
7695 if (cpumask_equal(doms_cur[i], doms_new[j])
7696 && dattrs_equal(dattr_cur, i, dattr_new, j))
7697 goto match1;
7699 /* no match - a current sched domain not in new doms_new[] */
7700 detach_destroy_domains(doms_cur[i]);
7701 match1:
7705 if (doms_new == NULL) {
7706 ndoms_cur = 0;
7707 doms_new = &fallback_doms;
7708 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7709 WARN_ON_ONCE(dattr_new);
7712 /* Build new domains */
7713 for (i = 0; i < ndoms_new; i++) {
7714 for (j = 0; j < ndoms_cur && !new_topology; j++) {
7715 if (cpumask_equal(doms_new[i], doms_cur[j])
7716 && dattrs_equal(dattr_new, i, dattr_cur, j))
7717 goto match2;
7719 /* no match - add a new doms_new */
7720 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7721 match2:
7725 /* Remember the new sched domains */
7726 if (doms_cur != &fallback_doms)
7727 free_sched_domains(doms_cur, ndoms_cur);
7728 kfree(dattr_cur); /* kfree(NULL) is safe */
7729 doms_cur = doms_new;
7730 dattr_cur = dattr_new;
7731 ndoms_cur = ndoms_new;
7733 register_sched_domain_sysctl();
7735 mutex_unlock(&sched_domains_mutex);
7738 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7739 static void reinit_sched_domains(void)
7741 get_online_cpus();
7743 /* Destroy domains first to force the rebuild */
7744 partition_sched_domains(0, NULL, NULL);
7746 rebuild_sched_domains();
7747 put_online_cpus();
7750 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7752 unsigned int level = 0;
7754 if (sscanf(buf, "%u", &level) != 1)
7755 return -EINVAL;
7758 * level is always be positive so don't check for
7759 * level < POWERSAVINGS_BALANCE_NONE which is 0
7760 * What happens on 0 or 1 byte write,
7761 * need to check for count as well?
7764 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
7765 return -EINVAL;
7767 if (smt)
7768 sched_smt_power_savings = level;
7769 else
7770 sched_mc_power_savings = level;
7772 reinit_sched_domains();
7774 return count;
7777 #ifdef CONFIG_SCHED_MC
7778 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7779 struct sysdev_class_attribute *attr,
7780 char *page)
7782 return sprintf(page, "%u\n", sched_mc_power_savings);
7784 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7785 struct sysdev_class_attribute *attr,
7786 const char *buf, size_t count)
7788 return sched_power_savings_store(buf, count, 0);
7790 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7791 sched_mc_power_savings_show,
7792 sched_mc_power_savings_store);
7793 #endif
7795 #ifdef CONFIG_SCHED_SMT
7796 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7797 struct sysdev_class_attribute *attr,
7798 char *page)
7800 return sprintf(page, "%u\n", sched_smt_power_savings);
7802 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7803 struct sysdev_class_attribute *attr,
7804 const char *buf, size_t count)
7806 return sched_power_savings_store(buf, count, 1);
7808 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7809 sched_smt_power_savings_show,
7810 sched_smt_power_savings_store);
7811 #endif
7813 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7815 int err = 0;
7817 #ifdef CONFIG_SCHED_SMT
7818 if (smt_capable())
7819 err = sysfs_create_file(&cls->kset.kobj,
7820 &attr_sched_smt_power_savings.attr);
7821 #endif
7822 #ifdef CONFIG_SCHED_MC
7823 if (!err && mc_capable())
7824 err = sysfs_create_file(&cls->kset.kobj,
7825 &attr_sched_mc_power_savings.attr);
7826 #endif
7827 return err;
7829 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7832 * Update cpusets according to cpu_active mask. If cpusets are
7833 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7834 * around partition_sched_domains().
7836 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7837 void *hcpu)
7839 switch (action & ~CPU_TASKS_FROZEN) {
7840 case CPU_ONLINE:
7841 case CPU_DOWN_FAILED:
7842 cpuset_update_active_cpus();
7843 return NOTIFY_OK;
7844 default:
7845 return NOTIFY_DONE;
7849 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7850 void *hcpu)
7852 switch (action & ~CPU_TASKS_FROZEN) {
7853 case CPU_DOWN_PREPARE:
7854 cpuset_update_active_cpus();
7855 return NOTIFY_OK;
7856 default:
7857 return NOTIFY_DONE;
7861 static int update_runtime(struct notifier_block *nfb,
7862 unsigned long action, void *hcpu)
7864 int cpu = (int)(long)hcpu;
7866 switch (action) {
7867 case CPU_DOWN_PREPARE:
7868 case CPU_DOWN_PREPARE_FROZEN:
7869 disable_runtime(cpu_rq(cpu));
7870 return NOTIFY_OK;
7872 case CPU_DOWN_FAILED:
7873 case CPU_DOWN_FAILED_FROZEN:
7874 case CPU_ONLINE:
7875 case CPU_ONLINE_FROZEN:
7876 enable_runtime(cpu_rq(cpu));
7877 return NOTIFY_OK;
7879 default:
7880 return NOTIFY_DONE;
7884 void __init sched_init_smp(void)
7886 cpumask_var_t non_isolated_cpus;
7888 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7889 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7891 get_online_cpus();
7892 mutex_lock(&sched_domains_mutex);
7893 init_sched_domains(cpu_active_mask);
7894 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7895 if (cpumask_empty(non_isolated_cpus))
7896 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7897 mutex_unlock(&sched_domains_mutex);
7898 put_online_cpus();
7900 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7901 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7903 /* RT runtime code needs to handle some hotplug events */
7904 hotcpu_notifier(update_runtime, 0);
7906 init_hrtick();
7908 /* Move init over to a non-isolated CPU */
7909 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7910 BUG();
7911 sched_init_granularity();
7912 free_cpumask_var(non_isolated_cpus);
7914 init_sched_rt_class();
7916 #else
7917 void __init sched_init_smp(void)
7919 sched_init_granularity();
7921 #endif /* CONFIG_SMP */
7923 const_debug unsigned int sysctl_timer_migration = 1;
7925 int in_sched_functions(unsigned long addr)
7927 return in_lock_functions(addr) ||
7928 (addr >= (unsigned long)__sched_text_start
7929 && addr < (unsigned long)__sched_text_end);
7932 static void init_cfs_rq(struct cfs_rq *cfs_rq)
7934 cfs_rq->tasks_timeline = RB_ROOT;
7935 INIT_LIST_HEAD(&cfs_rq->tasks);
7936 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7937 #ifndef CONFIG_64BIT
7938 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
7939 #endif
7942 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7944 struct rt_prio_array *array;
7945 int i;
7947 array = &rt_rq->active;
7948 for (i = 0; i < MAX_RT_PRIO; i++) {
7949 INIT_LIST_HEAD(array->queue + i);
7950 __clear_bit(i, array->bitmap);
7952 /* delimiter for bitsearch: */
7953 __set_bit(MAX_RT_PRIO, array->bitmap);
7955 #if defined CONFIG_SMP
7956 rt_rq->highest_prio.curr = MAX_RT_PRIO;
7957 rt_rq->highest_prio.next = MAX_RT_PRIO;
7958 rt_rq->rt_nr_migratory = 0;
7959 rt_rq->overloaded = 0;
7960 plist_head_init(&rt_rq->pushable_tasks);
7961 #endif
7963 rt_rq->rt_time = 0;
7964 rt_rq->rt_throttled = 0;
7965 rt_rq->rt_runtime = 0;
7966 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
7969 #ifdef CONFIG_FAIR_GROUP_SCHED
7970 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7971 struct sched_entity *se, int cpu,
7972 struct sched_entity *parent)
7974 struct rq *rq = cpu_rq(cpu);
7976 cfs_rq->tg = tg;
7977 cfs_rq->rq = rq;
7978 #ifdef CONFIG_SMP
7979 /* allow initial update_cfs_load() to truncate */
7980 cfs_rq->load_stamp = 1;
7981 #endif
7983 tg->cfs_rq[cpu] = cfs_rq;
7984 tg->se[cpu] = se;
7986 /* se could be NULL for root_task_group */
7987 if (!se)
7988 return;
7990 if (!parent)
7991 se->cfs_rq = &rq->cfs;
7992 else
7993 se->cfs_rq = parent->my_q;
7995 se->my_q = cfs_rq;
7996 update_load_set(&se->load, 0);
7997 se->parent = parent;
7999 #endif
8001 #ifdef CONFIG_RT_GROUP_SCHED
8002 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
8003 struct sched_rt_entity *rt_se, int cpu,
8004 struct sched_rt_entity *parent)
8006 struct rq *rq = cpu_rq(cpu);
8008 rt_rq->highest_prio.curr = MAX_RT_PRIO;
8009 rt_rq->rt_nr_boosted = 0;
8010 rt_rq->rq = rq;
8011 rt_rq->tg = tg;
8013 tg->rt_rq[cpu] = rt_rq;
8014 tg->rt_se[cpu] = rt_se;
8016 if (!rt_se)
8017 return;
8019 if (!parent)
8020 rt_se->rt_rq = &rq->rt;
8021 else
8022 rt_se->rt_rq = parent->my_q;
8024 rt_se->my_q = rt_rq;
8025 rt_se->parent = parent;
8026 INIT_LIST_HEAD(&rt_se->run_list);
8028 #endif
8030 void __init sched_init(void)
8032 int i, j;
8033 unsigned long alloc_size = 0, ptr;
8035 #ifdef CONFIG_FAIR_GROUP_SCHED
8036 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8037 #endif
8038 #ifdef CONFIG_RT_GROUP_SCHED
8039 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8040 #endif
8041 #ifdef CONFIG_CPUMASK_OFFSTACK
8042 alloc_size += num_possible_cpus() * cpumask_size();
8043 #endif
8044 if (alloc_size) {
8045 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
8047 #ifdef CONFIG_FAIR_GROUP_SCHED
8048 root_task_group.se = (struct sched_entity **)ptr;
8049 ptr += nr_cpu_ids * sizeof(void **);
8051 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8052 ptr += nr_cpu_ids * sizeof(void **);
8054 #endif /* CONFIG_FAIR_GROUP_SCHED */
8055 #ifdef CONFIG_RT_GROUP_SCHED
8056 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8057 ptr += nr_cpu_ids * sizeof(void **);
8059 root_task_group.rt_rq = (struct rt_rq **)ptr;
8060 ptr += nr_cpu_ids * sizeof(void **);
8062 #endif /* CONFIG_RT_GROUP_SCHED */
8063 #ifdef CONFIG_CPUMASK_OFFSTACK
8064 for_each_possible_cpu(i) {
8065 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
8066 ptr += cpumask_size();
8068 #endif /* CONFIG_CPUMASK_OFFSTACK */
8071 #ifdef CONFIG_SMP
8072 init_defrootdomain();
8073 #endif
8075 init_rt_bandwidth(&def_rt_bandwidth,
8076 global_rt_period(), global_rt_runtime());
8078 #ifdef CONFIG_RT_GROUP_SCHED
8079 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8080 global_rt_period(), global_rt_runtime());
8081 #endif /* CONFIG_RT_GROUP_SCHED */
8083 #ifdef CONFIG_CGROUP_SCHED
8084 list_add(&root_task_group.list, &task_groups);
8085 INIT_LIST_HEAD(&root_task_group.children);
8086 autogroup_init(&init_task);
8087 #endif /* CONFIG_CGROUP_SCHED */
8089 for_each_possible_cpu(i) {
8090 struct rq *rq;
8092 rq = cpu_rq(i);
8093 raw_spin_lock_init(&rq->lock);
8094 rq->nr_running = 0;
8095 rq->calc_load_active = 0;
8096 rq->calc_load_update = jiffies + LOAD_FREQ;
8097 init_cfs_rq(&rq->cfs);
8098 init_rt_rq(&rq->rt, rq);
8099 #ifdef CONFIG_FAIR_GROUP_SCHED
8100 root_task_group.shares = root_task_group_load;
8101 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8103 * How much cpu bandwidth does root_task_group get?
8105 * In case of task-groups formed thr' the cgroup filesystem, it
8106 * gets 100% of the cpu resources in the system. This overall
8107 * system cpu resource is divided among the tasks of
8108 * root_task_group and its child task-groups in a fair manner,
8109 * based on each entity's (task or task-group's) weight
8110 * (se->load.weight).
8112 * In other words, if root_task_group has 10 tasks of weight
8113 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8114 * then A0's share of the cpu resource is:
8116 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8118 * We achieve this by letting root_task_group's tasks sit
8119 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
8121 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
8122 #endif /* CONFIG_FAIR_GROUP_SCHED */
8124 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8125 #ifdef CONFIG_RT_GROUP_SCHED
8126 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8127 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
8128 #endif
8130 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8131 rq->cpu_load[j] = 0;
8133 rq->last_load_update_tick = jiffies;
8135 #ifdef CONFIG_SMP
8136 rq->sd = NULL;
8137 rq->rd = NULL;
8138 rq->cpu_power = SCHED_POWER_SCALE;
8139 rq->post_schedule = 0;
8140 rq->active_balance = 0;
8141 rq->next_balance = jiffies;
8142 rq->push_cpu = 0;
8143 rq->cpu = i;
8144 rq->online = 0;
8145 rq->idle_stamp = 0;
8146 rq->avg_idle = 2*sysctl_sched_migration_cost;
8147 rq_attach_root(rq, &def_root_domain);
8148 #ifdef CONFIG_NO_HZ
8149 rq->nohz_balance_kick = 0;
8150 init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i));
8151 #endif
8152 #endif
8153 init_rq_hrtick(rq);
8154 atomic_set(&rq->nr_iowait, 0);
8157 set_load_weight(&init_task);
8159 #ifdef CONFIG_PREEMPT_NOTIFIERS
8160 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8161 #endif
8163 #ifdef CONFIG_SMP
8164 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
8165 #endif
8167 #ifdef CONFIG_RT_MUTEXES
8168 plist_head_init(&init_task.pi_waiters);
8169 #endif
8172 * The boot idle thread does lazy MMU switching as well:
8174 atomic_inc(&init_mm.mm_count);
8175 enter_lazy_tlb(&init_mm, current);
8178 * Make us the idle thread. Technically, schedule() should not be
8179 * called from this thread, however somewhere below it might be,
8180 * but because we are the idle thread, we just pick up running again
8181 * when this runqueue becomes "idle".
8183 init_idle(current, smp_processor_id());
8185 calc_load_update = jiffies + LOAD_FREQ;
8188 * During early bootup we pretend to be a normal task:
8190 current->sched_class = &fair_sched_class;
8192 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
8193 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
8194 #ifdef CONFIG_SMP
8195 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
8196 #ifdef CONFIG_NO_HZ
8197 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
8198 alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT);
8199 atomic_set(&nohz.load_balancer, nr_cpu_ids);
8200 atomic_set(&nohz.first_pick_cpu, nr_cpu_ids);
8201 atomic_set(&nohz.second_pick_cpu, nr_cpu_ids);
8202 #endif
8203 /* May be allocated at isolcpus cmdline parse time */
8204 if (cpu_isolated_map == NULL)
8205 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
8206 #endif /* SMP */
8208 scheduler_running = 1;
8211 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
8212 static inline int preempt_count_equals(int preempt_offset)
8214 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
8216 return (nested == preempt_offset);
8219 void __might_sleep(const char *file, int line, int preempt_offset)
8221 static unsigned long prev_jiffy; /* ratelimiting */
8223 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
8224 system_state != SYSTEM_RUNNING || oops_in_progress)
8225 return;
8226 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8227 return;
8228 prev_jiffy = jiffies;
8230 printk(KERN_ERR
8231 "BUG: sleeping function called from invalid context at %s:%d\n",
8232 file, line);
8233 printk(KERN_ERR
8234 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8235 in_atomic(), irqs_disabled(),
8236 current->pid, current->comm);
8238 debug_show_held_locks(current);
8239 if (irqs_disabled())
8240 print_irqtrace_events(current);
8241 dump_stack();
8243 EXPORT_SYMBOL(__might_sleep);
8244 #endif
8246 #ifdef CONFIG_MAGIC_SYSRQ
8247 static void normalize_task(struct rq *rq, struct task_struct *p)
8249 const struct sched_class *prev_class = p->sched_class;
8250 int old_prio = p->prio;
8251 int on_rq;
8253 on_rq = p->on_rq;
8254 if (on_rq)
8255 deactivate_task(rq, p, 0);
8256 __setscheduler(rq, p, SCHED_NORMAL, 0);
8257 if (on_rq) {
8258 activate_task(rq, p, 0);
8259 resched_task(rq->curr);
8262 check_class_changed(rq, p, prev_class, old_prio);
8265 void normalize_rt_tasks(void)
8267 struct task_struct *g, *p;
8268 unsigned long flags;
8269 struct rq *rq;
8271 read_lock_irqsave(&tasklist_lock, flags);
8272 do_each_thread(g, p) {
8274 * Only normalize user tasks:
8276 if (!p->mm)
8277 continue;
8279 p->se.exec_start = 0;
8280 #ifdef CONFIG_SCHEDSTATS
8281 p->se.statistics.wait_start = 0;
8282 p->se.statistics.sleep_start = 0;
8283 p->se.statistics.block_start = 0;
8284 #endif
8286 if (!rt_task(p)) {
8288 * Renice negative nice level userspace
8289 * tasks back to 0:
8291 if (TASK_NICE(p) < 0 && p->mm)
8292 set_user_nice(p, 0);
8293 continue;
8296 raw_spin_lock(&p->pi_lock);
8297 rq = __task_rq_lock(p);
8299 normalize_task(rq, p);
8301 __task_rq_unlock(rq);
8302 raw_spin_unlock(&p->pi_lock);
8303 } while_each_thread(g, p);
8305 read_unlock_irqrestore(&tasklist_lock, flags);
8308 #endif /* CONFIG_MAGIC_SYSRQ */
8310 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
8312 * These functions are only useful for the IA64 MCA handling, or kdb.
8314 * They can only be called when the whole system has been
8315 * stopped - every CPU needs to be quiescent, and no scheduling
8316 * activity can take place. Using them for anything else would
8317 * be a serious bug, and as a result, they aren't even visible
8318 * under any other configuration.
8322 * curr_task - return the current task for a given cpu.
8323 * @cpu: the processor in question.
8325 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8327 struct task_struct *curr_task(int cpu)
8329 return cpu_curr(cpu);
8332 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8334 #ifdef CONFIG_IA64
8336 * set_curr_task - set the current task for a given cpu.
8337 * @cpu: the processor in question.
8338 * @p: the task pointer to set.
8340 * Description: This function must only be used when non-maskable interrupts
8341 * are serviced on a separate stack. It allows the architecture to switch the
8342 * notion of the current task on a cpu in a non-blocking manner. This function
8343 * must be called with all CPU's synchronized, and interrupts disabled, the
8344 * and caller must save the original value of the current task (see
8345 * curr_task() above) and restore that value before reenabling interrupts and
8346 * re-starting the system.
8348 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8350 void set_curr_task(int cpu, struct task_struct *p)
8352 cpu_curr(cpu) = p;
8355 #endif
8357 #ifdef CONFIG_FAIR_GROUP_SCHED
8358 static void free_fair_sched_group(struct task_group *tg)
8360 int i;
8362 for_each_possible_cpu(i) {
8363 if (tg->cfs_rq)
8364 kfree(tg->cfs_rq[i]);
8365 if (tg->se)
8366 kfree(tg->se[i]);
8369 kfree(tg->cfs_rq);
8370 kfree(tg->se);
8373 static
8374 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8376 struct cfs_rq *cfs_rq;
8377 struct sched_entity *se;
8378 int i;
8380 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8381 if (!tg->cfs_rq)
8382 goto err;
8383 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8384 if (!tg->se)
8385 goto err;
8387 tg->shares = NICE_0_LOAD;
8389 for_each_possible_cpu(i) {
8390 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8391 GFP_KERNEL, cpu_to_node(i));
8392 if (!cfs_rq)
8393 goto err;
8395 se = kzalloc_node(sizeof(struct sched_entity),
8396 GFP_KERNEL, cpu_to_node(i));
8397 if (!se)
8398 goto err_free_rq;
8400 init_cfs_rq(cfs_rq);
8401 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
8404 return 1;
8406 err_free_rq:
8407 kfree(cfs_rq);
8408 err:
8409 return 0;
8412 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8414 struct rq *rq = cpu_rq(cpu);
8415 unsigned long flags;
8418 * Only empty task groups can be destroyed; so we can speculatively
8419 * check on_list without danger of it being re-added.
8421 if (!tg->cfs_rq[cpu]->on_list)
8422 return;
8424 raw_spin_lock_irqsave(&rq->lock, flags);
8425 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
8426 raw_spin_unlock_irqrestore(&rq->lock, flags);
8428 #else /* !CONFIG_FAIR_GROUP_SCHED */
8429 static inline void free_fair_sched_group(struct task_group *tg)
8433 static inline
8434 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8436 return 1;
8439 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8442 #endif /* CONFIG_FAIR_GROUP_SCHED */
8444 #ifdef CONFIG_RT_GROUP_SCHED
8445 static void free_rt_sched_group(struct task_group *tg)
8447 int i;
8449 if (tg->rt_se)
8450 destroy_rt_bandwidth(&tg->rt_bandwidth);
8452 for_each_possible_cpu(i) {
8453 if (tg->rt_rq)
8454 kfree(tg->rt_rq[i]);
8455 if (tg->rt_se)
8456 kfree(tg->rt_se[i]);
8459 kfree(tg->rt_rq);
8460 kfree(tg->rt_se);
8463 static
8464 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8466 struct rt_rq *rt_rq;
8467 struct sched_rt_entity *rt_se;
8468 int i;
8470 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8471 if (!tg->rt_rq)
8472 goto err;
8473 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8474 if (!tg->rt_se)
8475 goto err;
8477 init_rt_bandwidth(&tg->rt_bandwidth,
8478 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8480 for_each_possible_cpu(i) {
8481 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8482 GFP_KERNEL, cpu_to_node(i));
8483 if (!rt_rq)
8484 goto err;
8486 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8487 GFP_KERNEL, cpu_to_node(i));
8488 if (!rt_se)
8489 goto err_free_rq;
8491 init_rt_rq(rt_rq, cpu_rq(i));
8492 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8493 init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
8496 return 1;
8498 err_free_rq:
8499 kfree(rt_rq);
8500 err:
8501 return 0;
8503 #else /* !CONFIG_RT_GROUP_SCHED */
8504 static inline void free_rt_sched_group(struct task_group *tg)
8508 static inline
8509 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8511 return 1;
8513 #endif /* CONFIG_RT_GROUP_SCHED */
8515 #ifdef CONFIG_CGROUP_SCHED
8516 static void free_sched_group(struct task_group *tg)
8518 free_fair_sched_group(tg);
8519 free_rt_sched_group(tg);
8520 autogroup_free(tg);
8521 kfree(tg);
8524 /* allocate runqueue etc for a new task group */
8525 struct task_group *sched_create_group(struct task_group *parent)
8527 struct task_group *tg;
8528 unsigned long flags;
8530 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8531 if (!tg)
8532 return ERR_PTR(-ENOMEM);
8534 if (!alloc_fair_sched_group(tg, parent))
8535 goto err;
8537 if (!alloc_rt_sched_group(tg, parent))
8538 goto err;
8540 spin_lock_irqsave(&task_group_lock, flags);
8541 list_add_rcu(&tg->list, &task_groups);
8543 WARN_ON(!parent); /* root should already exist */
8545 tg->parent = parent;
8546 INIT_LIST_HEAD(&tg->children);
8547 list_add_rcu(&tg->siblings, &parent->children);
8548 spin_unlock_irqrestore(&task_group_lock, flags);
8550 return tg;
8552 err:
8553 free_sched_group(tg);
8554 return ERR_PTR(-ENOMEM);
8557 /* rcu callback to free various structures associated with a task group */
8558 static void free_sched_group_rcu(struct rcu_head *rhp)
8560 /* now it should be safe to free those cfs_rqs */
8561 free_sched_group(container_of(rhp, struct task_group, rcu));
8564 /* Destroy runqueue etc associated with a task group */
8565 void sched_destroy_group(struct task_group *tg)
8567 unsigned long flags;
8568 int i;
8570 /* end participation in shares distribution */
8571 for_each_possible_cpu(i)
8572 unregister_fair_sched_group(tg, i);
8574 spin_lock_irqsave(&task_group_lock, flags);
8575 list_del_rcu(&tg->list);
8576 list_del_rcu(&tg->siblings);
8577 spin_unlock_irqrestore(&task_group_lock, flags);
8579 /* wait for possible concurrent references to cfs_rqs complete */
8580 call_rcu(&tg->rcu, free_sched_group_rcu);
8583 /* change task's runqueue when it moves between groups.
8584 * The caller of this function should have put the task in its new group
8585 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8586 * reflect its new group.
8588 void sched_move_task(struct task_struct *tsk)
8590 int on_rq, running;
8591 unsigned long flags;
8592 struct rq *rq;
8594 rq = task_rq_lock(tsk, &flags);
8596 running = task_current(rq, tsk);
8597 on_rq = tsk->on_rq;
8599 if (on_rq)
8600 dequeue_task(rq, tsk, 0);
8601 if (unlikely(running))
8602 tsk->sched_class->put_prev_task(rq, tsk);
8604 #ifdef CONFIG_FAIR_GROUP_SCHED
8605 if (tsk->sched_class->task_move_group)
8606 tsk->sched_class->task_move_group(tsk, on_rq);
8607 else
8608 #endif
8609 set_task_rq(tsk, task_cpu(tsk));
8611 if (unlikely(running))
8612 tsk->sched_class->set_curr_task(rq);
8613 if (on_rq)
8614 enqueue_task(rq, tsk, 0);
8616 task_rq_unlock(rq, tsk, &flags);
8618 #endif /* CONFIG_CGROUP_SCHED */
8620 #ifdef CONFIG_FAIR_GROUP_SCHED
8621 static DEFINE_MUTEX(shares_mutex);
8623 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8625 int i;
8626 unsigned long flags;
8629 * We can't change the weight of the root cgroup.
8631 if (!tg->se[0])
8632 return -EINVAL;
8634 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
8636 mutex_lock(&shares_mutex);
8637 if (tg->shares == shares)
8638 goto done;
8640 tg->shares = shares;
8641 for_each_possible_cpu(i) {
8642 struct rq *rq = cpu_rq(i);
8643 struct sched_entity *se;
8645 se = tg->se[i];
8646 /* Propagate contribution to hierarchy */
8647 raw_spin_lock_irqsave(&rq->lock, flags);
8648 for_each_sched_entity(se)
8649 update_cfs_shares(group_cfs_rq(se));
8650 raw_spin_unlock_irqrestore(&rq->lock, flags);
8653 done:
8654 mutex_unlock(&shares_mutex);
8655 return 0;
8658 unsigned long sched_group_shares(struct task_group *tg)
8660 return tg->shares;
8662 #endif
8664 #ifdef CONFIG_RT_GROUP_SCHED
8666 * Ensure that the real time constraints are schedulable.
8668 static DEFINE_MUTEX(rt_constraints_mutex);
8670 static unsigned long to_ratio(u64 period, u64 runtime)
8672 if (runtime == RUNTIME_INF)
8673 return 1ULL << 20;
8675 return div64_u64(runtime << 20, period);
8678 /* Must be called with tasklist_lock held */
8679 static inline int tg_has_rt_tasks(struct task_group *tg)
8681 struct task_struct *g, *p;
8683 do_each_thread(g, p) {
8684 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8685 return 1;
8686 } while_each_thread(g, p);
8688 return 0;
8691 struct rt_schedulable_data {
8692 struct task_group *tg;
8693 u64 rt_period;
8694 u64 rt_runtime;
8697 static int tg_schedulable(struct task_group *tg, void *data)
8699 struct rt_schedulable_data *d = data;
8700 struct task_group *child;
8701 unsigned long total, sum = 0;
8702 u64 period, runtime;
8704 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8705 runtime = tg->rt_bandwidth.rt_runtime;
8707 if (tg == d->tg) {
8708 period = d->rt_period;
8709 runtime = d->rt_runtime;
8713 * Cannot have more runtime than the period.
8715 if (runtime > period && runtime != RUNTIME_INF)
8716 return -EINVAL;
8719 * Ensure we don't starve existing RT tasks.
8721 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8722 return -EBUSY;
8724 total = to_ratio(period, runtime);
8727 * Nobody can have more than the global setting allows.
8729 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8730 return -EINVAL;
8733 * The sum of our children's runtime should not exceed our own.
8735 list_for_each_entry_rcu(child, &tg->children, siblings) {
8736 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8737 runtime = child->rt_bandwidth.rt_runtime;
8739 if (child == d->tg) {
8740 period = d->rt_period;
8741 runtime = d->rt_runtime;
8744 sum += to_ratio(period, runtime);
8747 if (sum > total)
8748 return -EINVAL;
8750 return 0;
8753 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8755 struct rt_schedulable_data data = {
8756 .tg = tg,
8757 .rt_period = period,
8758 .rt_runtime = runtime,
8761 return walk_tg_tree(tg_schedulable, tg_nop, &data);
8764 static int tg_set_bandwidth(struct task_group *tg,
8765 u64 rt_period, u64 rt_runtime)
8767 int i, err = 0;
8769 mutex_lock(&rt_constraints_mutex);
8770 read_lock(&tasklist_lock);
8771 err = __rt_schedulable(tg, rt_period, rt_runtime);
8772 if (err)
8773 goto unlock;
8775 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8776 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8777 tg->rt_bandwidth.rt_runtime = rt_runtime;
8779 for_each_possible_cpu(i) {
8780 struct rt_rq *rt_rq = tg->rt_rq[i];
8782 raw_spin_lock(&rt_rq->rt_runtime_lock);
8783 rt_rq->rt_runtime = rt_runtime;
8784 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8786 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8787 unlock:
8788 read_unlock(&tasklist_lock);
8789 mutex_unlock(&rt_constraints_mutex);
8791 return err;
8794 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8796 u64 rt_runtime, rt_period;
8798 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8799 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8800 if (rt_runtime_us < 0)
8801 rt_runtime = RUNTIME_INF;
8803 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8806 long sched_group_rt_runtime(struct task_group *tg)
8808 u64 rt_runtime_us;
8810 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8811 return -1;
8813 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8814 do_div(rt_runtime_us, NSEC_PER_USEC);
8815 return rt_runtime_us;
8818 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8820 u64 rt_runtime, rt_period;
8822 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8823 rt_runtime = tg->rt_bandwidth.rt_runtime;
8825 if (rt_period == 0)
8826 return -EINVAL;
8828 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8831 long sched_group_rt_period(struct task_group *tg)
8833 u64 rt_period_us;
8835 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8836 do_div(rt_period_us, NSEC_PER_USEC);
8837 return rt_period_us;
8840 static int sched_rt_global_constraints(void)
8842 u64 runtime, period;
8843 int ret = 0;
8845 if (sysctl_sched_rt_period <= 0)
8846 return -EINVAL;
8848 runtime = global_rt_runtime();
8849 period = global_rt_period();
8852 * Sanity check on the sysctl variables.
8854 if (runtime > period && runtime != RUNTIME_INF)
8855 return -EINVAL;
8857 mutex_lock(&rt_constraints_mutex);
8858 read_lock(&tasklist_lock);
8859 ret = __rt_schedulable(NULL, 0, 0);
8860 read_unlock(&tasklist_lock);
8861 mutex_unlock(&rt_constraints_mutex);
8863 return ret;
8866 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8868 /* Don't accept realtime tasks when there is no way for them to run */
8869 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8870 return 0;
8872 return 1;
8875 #else /* !CONFIG_RT_GROUP_SCHED */
8876 static int sched_rt_global_constraints(void)
8878 unsigned long flags;
8879 int i;
8881 if (sysctl_sched_rt_period <= 0)
8882 return -EINVAL;
8885 * There's always some RT tasks in the root group
8886 * -- migration, kstopmachine etc..
8888 if (sysctl_sched_rt_runtime == 0)
8889 return -EBUSY;
8891 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8892 for_each_possible_cpu(i) {
8893 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8895 raw_spin_lock(&rt_rq->rt_runtime_lock);
8896 rt_rq->rt_runtime = global_rt_runtime();
8897 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8899 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8901 return 0;
8903 #endif /* CONFIG_RT_GROUP_SCHED */
8905 int sched_rt_handler(struct ctl_table *table, int write,
8906 void __user *buffer, size_t *lenp,
8907 loff_t *ppos)
8909 int ret;
8910 int old_period, old_runtime;
8911 static DEFINE_MUTEX(mutex);
8913 mutex_lock(&mutex);
8914 old_period = sysctl_sched_rt_period;
8915 old_runtime = sysctl_sched_rt_runtime;
8917 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8919 if (!ret && write) {
8920 ret = sched_rt_global_constraints();
8921 if (ret) {
8922 sysctl_sched_rt_period = old_period;
8923 sysctl_sched_rt_runtime = old_runtime;
8924 } else {
8925 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8926 def_rt_bandwidth.rt_period =
8927 ns_to_ktime(global_rt_period());
8930 mutex_unlock(&mutex);
8932 return ret;
8935 #ifdef CONFIG_CGROUP_SCHED
8937 /* return corresponding task_group object of a cgroup */
8938 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8940 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8941 struct task_group, css);
8944 static struct cgroup_subsys_state *
8945 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8947 struct task_group *tg, *parent;
8949 if (!cgrp->parent) {
8950 /* This is early initialization for the top cgroup */
8951 return &root_task_group.css;
8954 parent = cgroup_tg(cgrp->parent);
8955 tg = sched_create_group(parent);
8956 if (IS_ERR(tg))
8957 return ERR_PTR(-ENOMEM);
8959 return &tg->css;
8962 static void
8963 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8965 struct task_group *tg = cgroup_tg(cgrp);
8967 sched_destroy_group(tg);
8970 static int
8971 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8973 #ifdef CONFIG_RT_GROUP_SCHED
8974 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
8975 return -EINVAL;
8976 #else
8977 /* We don't support RT-tasks being in separate groups */
8978 if (tsk->sched_class != &fair_sched_class)
8979 return -EINVAL;
8980 #endif
8981 return 0;
8984 static void
8985 cpu_cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8987 sched_move_task(tsk);
8990 static void
8991 cpu_cgroup_exit(struct cgroup_subsys *ss, struct cgroup *cgrp,
8992 struct cgroup *old_cgrp, struct task_struct *task)
8995 * cgroup_exit() is called in the copy_process() failure path.
8996 * Ignore this case since the task hasn't ran yet, this avoids
8997 * trying to poke a half freed task state from generic code.
8999 if (!(task->flags & PF_EXITING))
9000 return;
9002 sched_move_task(task);
9005 #ifdef CONFIG_FAIR_GROUP_SCHED
9006 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9007 u64 shareval)
9009 return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval));
9012 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9014 struct task_group *tg = cgroup_tg(cgrp);
9016 return (u64) scale_load_down(tg->shares);
9018 #endif /* CONFIG_FAIR_GROUP_SCHED */
9020 #ifdef CONFIG_RT_GROUP_SCHED
9021 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9022 s64 val)
9024 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9027 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9029 return sched_group_rt_runtime(cgroup_tg(cgrp));
9032 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9033 u64 rt_period_us)
9035 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9038 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9040 return sched_group_rt_period(cgroup_tg(cgrp));
9042 #endif /* CONFIG_RT_GROUP_SCHED */
9044 static struct cftype cpu_files[] = {
9045 #ifdef CONFIG_FAIR_GROUP_SCHED
9047 .name = "shares",
9048 .read_u64 = cpu_shares_read_u64,
9049 .write_u64 = cpu_shares_write_u64,
9051 #endif
9052 #ifdef CONFIG_RT_GROUP_SCHED
9054 .name = "rt_runtime_us",
9055 .read_s64 = cpu_rt_runtime_read,
9056 .write_s64 = cpu_rt_runtime_write,
9059 .name = "rt_period_us",
9060 .read_u64 = cpu_rt_period_read_uint,
9061 .write_u64 = cpu_rt_period_write_uint,
9063 #endif
9066 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9068 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9071 struct cgroup_subsys cpu_cgroup_subsys = {
9072 .name = "cpu",
9073 .create = cpu_cgroup_create,
9074 .destroy = cpu_cgroup_destroy,
9075 .can_attach_task = cpu_cgroup_can_attach_task,
9076 .attach_task = cpu_cgroup_attach_task,
9077 .exit = cpu_cgroup_exit,
9078 .populate = cpu_cgroup_populate,
9079 .subsys_id = cpu_cgroup_subsys_id,
9080 .early_init = 1,
9083 #endif /* CONFIG_CGROUP_SCHED */
9085 #ifdef CONFIG_CGROUP_CPUACCT
9088 * CPU accounting code for task groups.
9090 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9091 * (balbir@in.ibm.com).
9094 /* track cpu usage of a group of tasks and its child groups */
9095 struct cpuacct {
9096 struct cgroup_subsys_state css;
9097 /* cpuusage holds pointer to a u64-type object on every cpu */
9098 u64 __percpu *cpuusage;
9099 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
9100 struct cpuacct *parent;
9103 struct cgroup_subsys cpuacct_subsys;
9105 /* return cpu accounting group corresponding to this container */
9106 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9108 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9109 struct cpuacct, css);
9112 /* return cpu accounting group to which this task belongs */
9113 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9115 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9116 struct cpuacct, css);
9119 /* create a new cpu accounting group */
9120 static struct cgroup_subsys_state *cpuacct_create(
9121 struct cgroup_subsys *ss, struct cgroup *cgrp)
9123 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9124 int i;
9126 if (!ca)
9127 goto out;
9129 ca->cpuusage = alloc_percpu(u64);
9130 if (!ca->cpuusage)
9131 goto out_free_ca;
9133 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
9134 if (percpu_counter_init(&ca->cpustat[i], 0))
9135 goto out_free_counters;
9137 if (cgrp->parent)
9138 ca->parent = cgroup_ca(cgrp->parent);
9140 return &ca->css;
9142 out_free_counters:
9143 while (--i >= 0)
9144 percpu_counter_destroy(&ca->cpustat[i]);
9145 free_percpu(ca->cpuusage);
9146 out_free_ca:
9147 kfree(ca);
9148 out:
9149 return ERR_PTR(-ENOMEM);
9152 /* destroy an existing cpu accounting group */
9153 static void
9154 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9156 struct cpuacct *ca = cgroup_ca(cgrp);
9157 int i;
9159 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
9160 percpu_counter_destroy(&ca->cpustat[i]);
9161 free_percpu(ca->cpuusage);
9162 kfree(ca);
9165 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
9167 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9168 u64 data;
9170 #ifndef CONFIG_64BIT
9172 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
9174 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
9175 data = *cpuusage;
9176 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
9177 #else
9178 data = *cpuusage;
9179 #endif
9181 return data;
9184 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
9186 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9188 #ifndef CONFIG_64BIT
9190 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
9192 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
9193 *cpuusage = val;
9194 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
9195 #else
9196 *cpuusage = val;
9197 #endif
9200 /* return total cpu usage (in nanoseconds) of a group */
9201 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9203 struct cpuacct *ca = cgroup_ca(cgrp);
9204 u64 totalcpuusage = 0;
9205 int i;
9207 for_each_present_cpu(i)
9208 totalcpuusage += cpuacct_cpuusage_read(ca, i);
9210 return totalcpuusage;
9213 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9214 u64 reset)
9216 struct cpuacct *ca = cgroup_ca(cgrp);
9217 int err = 0;
9218 int i;
9220 if (reset) {
9221 err = -EINVAL;
9222 goto out;
9225 for_each_present_cpu(i)
9226 cpuacct_cpuusage_write(ca, i, 0);
9228 out:
9229 return err;
9232 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
9233 struct seq_file *m)
9235 struct cpuacct *ca = cgroup_ca(cgroup);
9236 u64 percpu;
9237 int i;
9239 for_each_present_cpu(i) {
9240 percpu = cpuacct_cpuusage_read(ca, i);
9241 seq_printf(m, "%llu ", (unsigned long long) percpu);
9243 seq_printf(m, "\n");
9244 return 0;
9247 static const char *cpuacct_stat_desc[] = {
9248 [CPUACCT_STAT_USER] = "user",
9249 [CPUACCT_STAT_SYSTEM] = "system",
9252 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
9253 struct cgroup_map_cb *cb)
9255 struct cpuacct *ca = cgroup_ca(cgrp);
9256 int i;
9258 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
9259 s64 val = percpu_counter_read(&ca->cpustat[i]);
9260 val = cputime64_to_clock_t(val);
9261 cb->fill(cb, cpuacct_stat_desc[i], val);
9263 return 0;
9266 static struct cftype files[] = {
9268 .name = "usage",
9269 .read_u64 = cpuusage_read,
9270 .write_u64 = cpuusage_write,
9273 .name = "usage_percpu",
9274 .read_seq_string = cpuacct_percpu_seq_read,
9277 .name = "stat",
9278 .read_map = cpuacct_stats_show,
9282 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9284 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9288 * charge this task's execution time to its accounting group.
9290 * called with rq->lock held.
9292 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9294 struct cpuacct *ca;
9295 int cpu;
9297 if (unlikely(!cpuacct_subsys.active))
9298 return;
9300 cpu = task_cpu(tsk);
9302 rcu_read_lock();
9304 ca = task_ca(tsk);
9306 for (; ca; ca = ca->parent) {
9307 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9308 *cpuusage += cputime;
9311 rcu_read_unlock();
9315 * When CONFIG_VIRT_CPU_ACCOUNTING is enabled one jiffy can be very large
9316 * in cputime_t units. As a result, cpuacct_update_stats calls
9317 * percpu_counter_add with values large enough to always overflow the
9318 * per cpu batch limit causing bad SMP scalability.
9320 * To fix this we scale percpu_counter_batch by cputime_one_jiffy so we
9321 * batch the same amount of time with CONFIG_VIRT_CPU_ACCOUNTING disabled
9322 * and enabled. We cap it at INT_MAX which is the largest allowed batch value.
9324 #ifdef CONFIG_SMP
9325 #define CPUACCT_BATCH \
9326 min_t(long, percpu_counter_batch * cputime_one_jiffy, INT_MAX)
9327 #else
9328 #define CPUACCT_BATCH 0
9329 #endif
9332 * Charge the system/user time to the task's accounting group.
9334 static void cpuacct_update_stats(struct task_struct *tsk,
9335 enum cpuacct_stat_index idx, cputime_t val)
9337 struct cpuacct *ca;
9338 int batch = CPUACCT_BATCH;
9340 if (unlikely(!cpuacct_subsys.active))
9341 return;
9343 rcu_read_lock();
9344 ca = task_ca(tsk);
9346 do {
9347 __percpu_counter_add(&ca->cpustat[idx], val, batch);
9348 ca = ca->parent;
9349 } while (ca);
9350 rcu_read_unlock();
9353 struct cgroup_subsys cpuacct_subsys = {
9354 .name = "cpuacct",
9355 .create = cpuacct_create,
9356 .destroy = cpuacct_destroy,
9357 .populate = cpuacct_populate,
9358 .subsys_id = cpuacct_subsys_id,
9360 #endif /* CONFIG_CGROUP_CPUACCT */